JZHWS commited on
Commit
97d51c2
·
verified ·
1 Parent(s): 1053918

Delete README.md

Browse files
Files changed (1) hide show
  1. README.md +0 -703
README.md DELETED
@@ -1,703 +0,0 @@
1
- ---
2
- license: apache-2.0
3
- license_name: qwen
4
- license_link: https://huggingface.co/Qwen/Qwen2.5-72B-Instruct/blob/main/LICENSE
5
- pipeline_tag: image-text-to-text
6
- library_name: transformers
7
- base_model:
8
- - OpenGVLab/InternVL3-8B-Pretrained
9
- base_model_relation: finetune
10
- language:
11
- - multilingual
12
- tags:
13
- - internvl
14
- - custom_code
15
- ---
16
-
17
- # InternVL3-8B-Instruct
18
-
19
- [\[📂 GitHub\]](https://github.com/OpenGVLab/InternVL) [\[📜 InternVL 1.0\]](https://huggingface.co/papers/2312.14238) [\[📜 InternVL 1.5\]](https://huggingface.co/papers/2404.16821) [\[📜 InternVL 2.5\]](https://huggingface.co/papers/2412.05271) [\[📜 InternVL2.5-MPO\]](https://huggingface.co/papers/2411.10442) [\[📜 InternVL3\]](https://huggingface.co/papers/2504.10479)
20
-
21
- [\[🆕 Blog\]](https://internvl.github.io/blog/) [\[🗨️ Chat Demo\]](https://internvl.opengvlab.com/) [\[🤗 HF Demo\]](https://huggingface.co/spaces/OpenGVLab/InternVL) [\[🚀 Quick Start\]](#quick-start) [\[📖 Documents\]](https://internvl.readthedocs.io/en/latest/)
22
-
23
- <div align="center">
24
- <img width="500" alt="image" src="https://cdn-uploads.huggingface.co/production/uploads/64006c09330a45b03605bba3/zJsd2hqd3EevgXo6fNgC-.png">
25
- </div>
26
-
27
- ## Introduction
28
-
29
- ***This is the SFT version of InternVL3-8B, which has undergone native multimodal pre-trainin and SFT but has not undergone MPO. If you're unsure which version to use, please use the [InternVL3-8B](https://huggingface.co/OpenGVLab/InternVL3-8B) version.***
30
-
31
- We introduce InternVL3, an advanced multimodal large language model (MLLM) series that demonstrates superior overall performance.
32
- Compared to InternVL 2.5, InternVL3 exhibits superior multimodal perception and reasoning capabilities, while further extending its multimodal capabilities to encompass tool usage, GUI agents, industrial image analysis, 3D vision perception, and more.
33
- Additionally, we compare InternVL3 with Qwen2.5 Chat models, whose corresponding pre-trained base models are employed as the initialization of the langauge component in InternVL3. Benefitting from Native Multimodal Pre-Training, the InternVL3 series achieves even better overall text performance than the Qwen2.5 series.
34
-
35
- ![image/png](https://huggingface.co/datasets/Weiyun1025/InternVL-Performance/resolve/main/internvl3/overall.png)
36
-
37
- ## InternVL3 Family
38
-
39
- In the following table, we provide an overview of the InternVL3 series.
40
-
41
- | Model Name | Vision Part | Language Part | HF Link |
42
- | :-----------: | :-------------------------------------------------------------------------------------: | :----------------------------------------------------------------------------: | :------------------------------------------------------: |
43
- | InternVL3-1B | [InternViT-300M-448px-V2_5](https://huggingface.co/OpenGVLab/InternViT-300M-448px-V2_5) | [Qwen2.5-0.5B](https://huggingface.co/Qwen/Qwen2.5-0.5B) | [🤗 link](https://huggingface.co/OpenGVLab/InternVL3-1B) |
44
- | InternVL3-2B | [InternViT-300M-448px-V2_5](https://huggingface.co/OpenGVLab/InternViT-300M-448px-V2_5) | [Qwen2.5-1.5B](https://huggingface.co/Qwen/Qwen2.5-1.5B) | [🤗 link](https://huggingface.co/OpenGVLab/InternVL3-2B) |
45
- | InternVL3-8B | [InternViT-300M-448px-V2_5](https://huggingface.co/OpenGVLab/InternViT-300M-448px-V2_5) | [Qwen2.5-7B](https://huggingface.co/Qwen/Qwen2.5-7B) | [🤗 link](https://huggingface.co/OpenGVLab/InternVL3-8B) |
46
- | InternVL3-9B | [InternViT-300M-448px-V2_5](https://huggingface.co/OpenGVLab/InternViT-300M-448px-V2_5) | [internlm3-8b-instruct](https://huggingface.co/internlm/internlm3-8b-instruct) | [🤗 link](https://huggingface.co/OpenGVLab/InternVL3-9B) |
47
- | InternVL3-14B | [InternViT-300M-448px-V2_5](https://huggingface.co/OpenGVLab/InternViT-300M-448px-V2_5) | [Qwen2.5-14B](https://huggingface.co/Qwen/Qwen2.5-14B) | [🤗 link](https://huggingface.co/OpenGVLab/InternVL3-14B) |
48
- | InternVL3-38B | [InternViT-6B-448px-V2_5](https://huggingface.co/OpenGVLab/InternViT-6B-448px-V2_5) | [Qwen2.5-32B](https://huggingface.co/Qwen/Qwen2.5-32B) | [🤗 link](https://huggingface.co/OpenGVLab/InternVL3-38B) |
49
- | InternVL3-78B | [InternViT-6B-448px-V2_5](https://huggingface.co/OpenGVLab/InternViT-6B-448px-V2_5) | [Qwen2.5-72B](https://huggingface.co/Qwen/Qwen2.5-72B) | [🤗 link](https://huggingface.co/OpenGVLab/InternVL3-78B) |
50
-
51
- ![image/png](https://huggingface.co/datasets/Weiyun1025/InternVL-Performance/resolve/main/internvl3/overall-table.png)
52
-
53
- ## Model Architecture
54
-
55
- As shown in the following figure, [InternVL3](https://internvl.github.io/blog/2025-04-11-InternVL-3/) retains the same model architecture as [InternVL 2.5](https://internvl.github.io/blog/2024-12-05-InternVL-2.5/) and its predecessors, InternVL 1.5 and 2.0, following the "ViT-MLP-LLM" paradigm. In this new version, we integrate a newly incrementally pre-trained InternViT with various pre-trained LLMs, including InternLM 3 and Qwen 2.5, using a randomly initialized MLP projector.
56
-
57
-
58
- ![image/png](https://cdn-uploads.huggingface.co/production/uploads/64119264f0f81eb569e0d569/BiiyXN6NOk0p-3rl3ueyL.png)
59
-
60
- As in the previous version, we applied a pixel unshuffle operation, reducing the number of visual tokens to one-quarter of the original. Besides, we adopted a similar dynamic resolution strategy as InternVL 1.5, dividing images into tiles of 448×448 pixels. The key difference, starting from InternVL 2.0, is that we additionally introduced support for multi-image and video data.
61
-
62
- Notably, in InternVL3, we integrate the [Variable Visual Position Encoding (V2PE)](https://arxiv.org/abs/2412.09616), which utilizes smaller, more flexible position increments for visual tokens. Benefiting from V2PE, InternVL3 exhibits better long context understanding capabilities compared to its predecessors.
63
-
64
- ## Training Strategy
65
-
66
- ### Native Multimodal Pre-Training
67
-
68
- We propose a [Native Multimodal Pre-Training](https://huggingface.co/papers/2504.10479) approach that consolidates language and vision learning into a single pre-training stage.
69
- In contrast to standard paradigms that first train a language-only model and subsequently adapt it to handle additional modalities, our method interleaves multimodal data (e.g., image-text, video-text, or image-text interleaved sequences) with large-scale textual corpora. This unified training scheme allows the model to learn both linguistic and multimodal representations simultaneously, ultimately enhancing its capability to handle vision-language tasks without the need for separate alignment or bridging modules.
70
- Please see [our paper](https://huggingface.co/papers/2504.10479) for more details.
71
-
72
- ### Supervised Fine-Tuning
73
-
74
- In this phase, the techniques of random JPEG compression, square loss re-weighting, and multimodal data packing proposed in [InternVL2.5](https://arxiv.org/abs/2412.05271) are also employed in the InternVL3 series.
75
- The main advancement of the SFT phase in InternVL3 compared to InternVL2.5 lies in the use of higher-quality and more diverse training data.
76
- Specifically, we further extend training samples for tool use, 3D scene understanding, GUI operations, long context tasks, video understanding, scientific diagrams, creative writing, and multimodal reasoning.
77
-
78
- ### Mixed Preference Optimization
79
-
80
- During Pre-training and SFT, the model is trained to predict the next token conditioned on previous ground-truth tokens.
81
- However, during inference, the model predicts each token based on its own prior outputs.
82
- This discrepancy between ground-truth tokens and model-predicted tokens introduces a distribution shift, which can impair the model’s Chain-of-Thought (CoT) reasoning capabilities.
83
- To mitigate this issue, we employ [MPO](https://arxiv.org/abs/2411.10442), which introduces additional supervision from both positive and negative samples to align the model response distribution with the ground-truth distribution, thereby improving reasoning performance.
84
- Specifically, the training objective of MPO is a combination of
85
- preference loss \\(\mathcal{L}_{\text{p}}\\),
86
- quality loss \\(\mathcal{L}_{\text{q}}\\),
87
- and generation loss \\(\mathcal{L}_{\text{g}}\\),
88
- which can be formulated as follows:
89
-
90
-
91
- $$
92
- \mathcal{L}=w_{p}\cdot\mathcal{L}_{\text{p}} + w_{q}\cdot\mathcal{L}_{\text{q}} + w_{g}\cdot\mathcal{L}_{\text{g}},
93
- $$
94
-
95
-
96
- where \\(w_{*}\\) represents the weight assigned to each loss component. Please see [our paper](https://arxiv.org/abs/2411.10442) for more details about MPO.
97
-
98
-
99
- ### Test-Time Scaling
100
-
101
- Test-Time Scaling has been shown to be an effective method to enhance the reasoning abilities of LLMs and MLLMs.
102
- In this work, we use the Best-of-N evaluation strategy and employ [VisualPRM-8B](https://huggingface.co/OpenGVLab/VisualPRM-8B) as the critic model to select the best response for reasoning and mathematics evaluation.
103
-
104
- ## Evaluation on Multimodal Capability
105
-
106
- ### Multimodal Reasoning and Mathematics
107
-
108
- ![image/png](https://huggingface.co/datasets/OpenGVLab/VisualPRM400K-v1.1/resolve/main/visualprm-performance.png)
109
-
110
- ### OCR, Chart, and Document Understanding
111
-
112
- ![image/png](https://huggingface.co/datasets/Weiyun1025/InternVL-Performance/resolve/main/internvl3/ocr.png)
113
-
114
- ### Multi-Image & Real-World Comprehension
115
-
116
- ![image/png](https://huggingface.co/datasets/Weiyun1025/InternVL-Performance/resolve/main/internvl3/multi-images.png)
117
-
118
- ### Comprehensive Multimodal & Hallucination Evaluation
119
-
120
- ![image/png](https://huggingface.co/datasets/Weiyun1025/InternVL-Performance/resolve/main/internvl3/comprehensive.png)
121
-
122
- ### Visual Grounding
123
-
124
- ![image/png](https://huggingface.co/datasets/Weiyun1025/InternVL-Performance/resolve/main/internvl3/grounding.png)
125
-
126
- ### Multimodal Multilingual Understanding
127
-
128
- ![image/png](https://huggingface.co/datasets/Weiyun1025/InternVL-Performance/resolve/main/internvl3/multilingual.png)
129
-
130
- ### Video Understanding
131
-
132
- ![image/png](https://huggingface.co/datasets/Weiyun1025/InternVL-Performance/resolve/main/internvl3/video.png)
133
-
134
- ### GUI Grounding
135
-
136
- ![image/png](https://huggingface.co/datasets/Weiyun1025/InternVL-Performance/resolve/main/internvl3/gui.png)
137
-
138
- ### Spatial Reasoning
139
-
140
- ![image/png](https://huggingface.co/datasets/Weiyun1025/InternVL-Performance/resolve/main/internvl3/vsi.png)
141
-
142
- ## Evaluation on Language Capability
143
-
144
- We compare InternVL3 with Qwen2.5 Chat models, whose corresponding pre-trained base models are employed as the initialization of the langauge component in InternVL3.
145
- Benefitting from Native Multimodal Pre-Training, the InternVL3 series achieves even better overall text performance than the Qwen2.5 series.
146
- Please note that the evaluation scores of Qwen2.5 series may differ from those officially reported, as we have adopted the prompt versions provided in the table across all datasets for OpenCompass evaluation.
147
-
148
- ![image/png](https://huggingface.co/datasets/Weiyun1025/InternVL-Performance/resolve/main/internvl3/text.png)
149
-
150
- ## Ablation Study
151
-
152
- ### Native Multimodal Pre-Training
153
-
154
- We conduct experiments on the InternVL2-8B model while keeping its architecture, initialization parameters, and training data entirely unchanged. Traditionally, InternVL2-8B employs a training pipeline that begins with an MLP warmup phase for feature alignment followed by an Instruction Tuning stage. In our experiments, we substitute the conventional MLP warmup phase with a native multimodal pre-training process. This modification isolates the contribution of native multimodal pre-training to the overall multimodal capability of the model.
155
-
156
- The evaluation results in the Figure below shows that the model with native multimodal pre-training exhibits performance on most benchmarks that is comparable to the fully multi-stage-trained InternVL2-8B baseline. Furthermore, when followed by instruction tuning on higher-quality data, the model demonstrates further performance gains across evaluated multimodal tasks. These findings underscore the efficiency of native multimodal pre-training in imparting powerful multimodal capabilities to MLLMs.
157
-
158
- ![image/png](https://huggingface.co/datasets/Weiyun1025/InternVL-Performance/resolve/main/internvl3/ablation-native.png)
159
-
160
- ### Mixed Preference Optimization
161
-
162
- As shown in the table below, models fine-tuned with MPO demonstrate superior reasoning performance across seven multimodal reasoning benchmarks compared to their counterparts without MPO. Specifically, InternVL3-78B and InternVL3-38B outperform their counterparts by 4.1 and 4.5 points, respectively. Notably, the training data used for MPO is a subset of that used for SFT, indicating that the performance improvements primarily stem from the training algorithm rather than the training data.
163
-
164
- ![image/png](https://huggingface.co/datasets/OpenGVLab/MMPR-v1.2/resolve/main/ablation-mpo.png)
165
-
166
- ### Variable Visual Position Encoding
167
-
168
- As reported in the table below, the introduction of V2PE leads to significant performance gains across most evaluation metrics. In addition, our ablation studies—by varying the positional increment \\( \delta \\)—reveal that even for tasks primarily involving conventional contexts, relatively small \\( \delta \\) values can achieve optimal performance. These findings provide important insights for future efforts aimed at refining position encoding strategies for visual tokens in MLLMs.
169
-
170
- ![image/png](https://huggingface.co/datasets/Weiyun1025/InternVL-Performance/resolve/main/internvl3/ablation-v2pe.png)
171
-
172
- ## Quick Start
173
-
174
- We provide an example code to run `InternVL3-8B` using `transformers`.
175
-
176
- > Please use transformers>=4.37.2 to ensure the model works normally.
177
-
178
- ### Model Loading
179
-
180
- #### 16-bit (bf16 / fp16)
181
-
182
- ```python
183
- import torch
184
- from transformers import AutoTokenizer, AutoModel
185
- path = "OpenGVLab/InternVL3-8B"
186
- model = AutoModel.from_pretrained(
187
- path,
188
- torch_dtype=torch.bfloat16,
189
- low_cpu_mem_usage=True,
190
- use_flash_attn=True,
191
- trust_remote_code=True).eval().cuda()
192
- ```
193
-
194
- #### BNB 8-bit Quantization
195
-
196
- ```python
197
- import torch
198
- from transformers import AutoTokenizer, AutoModel
199
- path = "OpenGVLab/InternVL3-8B"
200
- model = AutoModel.from_pretrained(
201
- path,
202
- torch_dtype=torch.bfloat16,
203
- load_in_8bit=True,
204
- low_cpu_mem_usage=True,
205
- use_flash_attn=True,
206
- trust_remote_code=True).eval()
207
- ```
208
-
209
- #### Multiple GPUs
210
-
211
- The reason for writing the code this way is to avoid errors that occur during multi-GPU inference due to tensors not being on the same device. By ensuring that the first and last layers of the large language model (LLM) are on the same device, we prevent such errors.
212
-
213
- ```python
214
- import math
215
- import torch
216
- from transformers import AutoTokenizer, AutoModel
217
-
218
- def split_model(model_name):
219
- device_map = {}
220
- world_size = torch.cuda.device_count()
221
- config = AutoConfig.from_pretrained(model_path, trust_remote_code=True)
222
- num_layers = config.llm_config.num_hidden_layers
223
- # Since the first GPU will be used for ViT, treat it as half a GPU.
224
- num_layers_per_gpu = math.ceil(num_layers / (world_size - 0.5))
225
- num_layers_per_gpu = [num_layers_per_gpu] * world_size
226
- num_layers_per_gpu[0] = math.ceil(num_layers_per_gpu[0] * 0.5)
227
- layer_cnt = 0
228
- for i, num_layer in enumerate(num_layers_per_gpu):
229
- for j in range(num_layer):
230
- device_map[f'language_model.model.layers.{layer_cnt}'] = i
231
- layer_cnt += 1
232
- device_map['vision_model'] = 0
233
- device_map['mlp1'] = 0
234
- device_map['language_model.model.tok_embeddings'] = 0
235
- device_map['language_model.model.embed_tokens'] = 0
236
- device_map['language_model.output'] = 0
237
- device_map['language_model.model.norm'] = 0
238
- device_map['language_model.model.rotary_emb'] = 0
239
- device_map['language_model.lm_head'] = 0
240
- device_map[f'language_model.model.layers.{num_layers - 1}'] = 0
241
-
242
- return device_map
243
-
244
- path = "OpenGVLab/InternVL3-8B"
245
- device_map = split_model('InternVL3-8B')
246
- model = AutoModel.from_pretrained(
247
- path,
248
- torch_dtype=torch.bfloat16,
249
- low_cpu_mem_usage=True,
250
- use_flash_attn=True,
251
- trust_remote_code=True,
252
- device_map=device_map).eval()
253
- ```
254
-
255
- ### Inference with Transformers
256
-
257
- ```python
258
- import math
259
- import numpy as np
260
- import torch
261
- import torchvision.transforms as T
262
- from decord import VideoReader, cpu
263
- from PIL import Image
264
- from torchvision.transforms.functional import InterpolationMode
265
- from transformers import AutoModel, AutoTokenizer
266
-
267
- IMAGENET_MEAN = (0.485, 0.456, 0.406)
268
- IMAGENET_STD = (0.229, 0.224, 0.225)
269
-
270
- def build_transform(input_size):
271
- MEAN, STD = IMAGENET_MEAN, IMAGENET_STD
272
- transform = T.Compose([
273
- T.Lambda(lambda img: img.convert('RGB') if img.mode != 'RGB' else img),
274
- T.Resize((input_size, input_size), interpolation=InterpolationMode.BICUBIC),
275
- T.ToTensor(),
276
- T.Normalize(mean=MEAN, std=STD)
277
- ])
278
- return transform
279
-
280
- def find_closest_aspect_ratio(aspect_ratio, target_ratios, width, height, image_size):
281
- best_ratio_diff = float('inf')
282
- best_ratio = (1, 1)
283
- area = width * height
284
- for ratio in target_ratios:
285
- target_aspect_ratio = ratio[0] / ratio[1]
286
- ratio_diff = abs(aspect_ratio - target_aspect_ratio)
287
- if ratio_diff < best_ratio_diff:
288
- best_ratio_diff = ratio_diff
289
- best_ratio = ratio
290
- elif ratio_diff == best_ratio_diff:
291
- if area > 0.5 * image_size * image_size * ratio[0] * ratio[1]:
292
- best_ratio = ratio
293
- return best_ratio
294
-
295
- def dynamic_preprocess(image, min_num=1, max_num=12, image_size=448, use_thumbnail=False):
296
- orig_width, orig_height = image.size
297
- aspect_ratio = orig_width / orig_height
298
-
299
- # calculate the existing image aspect ratio
300
- target_ratios = set(
301
- (i, j) for n in range(min_num, max_num + 1) for i in range(1, n + 1) for j in range(1, n + 1) if
302
- i * j <= max_num and i * j >= min_num)
303
- target_ratios = sorted(target_ratios, key=lambda x: x[0] * x[1])
304
-
305
- # find the closest aspect ratio to the target
306
- target_aspect_ratio = find_closest_aspect_ratio(
307
- aspect_ratio, target_ratios, orig_width, orig_height, image_size)
308
-
309
- # calculate the target width and height
310
- target_width = image_size * target_aspect_ratio[0]
311
- target_height = image_size * target_aspect_ratio[1]
312
- blocks = target_aspect_ratio[0] * target_aspect_ratio[1]
313
-
314
- # resize the image
315
- resized_img = image.resize((target_width, target_height))
316
- processed_images = []
317
- for i in range(blocks):
318
- box = (
319
- (i % (target_width // image_size)) * image_size,
320
- (i // (target_width // image_size)) * image_size,
321
- ((i % (target_width // image_size)) + 1) * image_size,
322
- ((i // (target_width // image_size)) + 1) * image_size
323
- )
324
- # split the image
325
- split_img = resized_img.crop(box)
326
- processed_images.append(split_img)
327
- assert len(processed_images) == blocks
328
- if use_thumbnail and len(processed_images) != 1:
329
- thumbnail_img = image.resize((image_size, image_size))
330
- processed_images.append(thumbnail_img)
331
- return processed_images
332
-
333
- def load_image(image_file, input_size=448, max_num=12):
334
- image = Image.open(image_file).convert('RGB')
335
- transform = build_transform(input_size=input_size)
336
- images = dynamic_preprocess(image, image_size=input_size, use_thumbnail=True, max_num=max_num)
337
- pixel_values = [transform(image) for image in images]
338
- pixel_values = torch.stack(pixel_values)
339
- return pixel_values
340
-
341
- def split_model(model_name):
342
- device_map = {}
343
- world_size = torch.cuda.device_count()
344
- config = AutoConfig.from_pretrained(model_path, trust_remote_code=True)
345
- num_layers = config.llm_config.num_hidden_layers
346
- # Since the first GPU will be used for ViT, treat it as half a GPU.
347
- num_layers_per_gpu = math.ceil(num_layers / (world_size - 0.5))
348
- num_layers_per_gpu = [num_layers_per_gpu] * world_size
349
- num_layers_per_gpu[0] = math.ceil(num_layers_per_gpu[0] * 0.5)
350
- layer_cnt = 0
351
- for i, num_layer in enumerate(num_layers_per_gpu):
352
- for j in range(num_layer):
353
- device_map[f'language_model.model.layers.{layer_cnt}'] = i
354
- layer_cnt += 1
355
- device_map['vision_model'] = 0
356
- device_map['mlp1'] = 0
357
- device_map['language_model.model.tok_embeddings'] = 0
358
- device_map['language_model.model.embed_tokens'] = 0
359
- device_map['language_model.output'] = 0
360
- device_map['language_model.model.norm'] = 0
361
- device_map['language_model.model.rotary_emb'] = 0
362
- device_map['language_model.lm_head'] = 0
363
- device_map[f'language_model.model.layers.{num_layers - 1}'] = 0
364
-
365
- return device_map
366
-
367
- # If you set `load_in_8bit=True`, you will need two 80GB GPUs.
368
- # If you set `load_in_8bit=False`, you will need at least three 80GB GPUs.
369
- path = 'OpenGVLab/InternVL3-8B'
370
- device_map = split_model('InternVL3-8B')
371
- model = AutoModel.from_pretrained(
372
- path,
373
- torch_dtype=torch.bfloat16,
374
- load_in_8bit=False,
375
- low_cpu_mem_usage=True,
376
- use_flash_attn=True,
377
- trust_remote_code=True,
378
- device_map=device_map).eval()
379
- tokenizer = AutoTokenizer.from_pretrained(path, trust_remote_code=True, use_fast=False)
380
-
381
- # set the max number of tiles in `max_num`
382
- pixel_values = load_image('./examples/image1.jpg', max_num=12).to(torch.bfloat16).cuda()
383
- generation_config = dict(max_new_tokens=1024, do_sample=True)
384
-
385
- # pure-text conversation (纯文本对话)
386
- question = 'Hello, who are you?'
387
- response, history = model.chat(tokenizer, None, question, generation_config, history=None, return_history=True)
388
- print(f'User: {question}\nAssistant: {response}')
389
-
390
- question = 'Can you tell me a story?'
391
- response, history = model.chat(tokenizer, None, question, generation_config, history=history, return_history=True)
392
- print(f'User: {question}\nAssistant: {response}')
393
-
394
- # single-image single-round conversation (单图单轮对话)
395
- question = '<image>\nPlease describe the image shortly.'
396
- response = model.chat(tokenizer, pixel_values, question, generation_config)
397
- print(f'User: {question}\nAssistant: {response}')
398
-
399
- # single-image multi-round conversation (单图多轮对话)
400
- question = '<image>\nPlease describe the image in detail.'
401
- response, history = model.chat(tokenizer, pixel_values, question, generation_config, history=None, return_history=True)
402
- print(f'User: {question}\nAssistant: {response}')
403
-
404
- question = 'Please write a poem according to the image.'
405
- response, history = model.chat(tokenizer, pixel_values, question, generation_config, history=history, return_history=True)
406
- print(f'User: {question}\nAssistant: {response}')
407
-
408
- # multi-image multi-round conversation, combined images (多图多轮对话,拼接图像)
409
- pixel_values1 = load_image('./examples/image1.jpg', max_num=12).to(torch.bfloat16).cuda()
410
- pixel_values2 = load_image('./examples/image2.jpg', max_num=12).to(torch.bfloat16).cuda()
411
- pixel_values = torch.cat((pixel_values1, pixel_values2), dim=0)
412
-
413
- question = '<image>\nDescribe the two images in detail.'
414
- response, history = model.chat(tokenizer, pixel_values, question, generation_config,
415
- history=None, return_history=True)
416
- print(f'User: {question}\nAssistant: {response}')
417
-
418
- question = 'What are the similarities and differences between these two images.'
419
- response, history = model.chat(tokenizer, pixel_values, question, generation_config,
420
- history=history, return_history=True)
421
- print(f'User: {question}\nAssistant: {response}')
422
-
423
- # multi-image multi-round conversation, separate images (多图多轮对话,独立图像)
424
- pixel_values1 = load_image('./examples/image1.jpg', max_num=12).to(torch.bfloat16).cuda()
425
- pixel_values2 = load_image('./examples/image2.jpg', max_num=12).to(torch.bfloat16).cuda()
426
- pixel_values = torch.cat((pixel_values1, pixel_values2), dim=0)
427
- num_patches_list = [pixel_values1.size(0), pixel_values2.size(0)]
428
-
429
- question = 'Image-1: <image>\nImage-2: <image>\nDescribe the two images in detail.'
430
- response, history = model.chat(tokenizer, pixel_values, question, generation_config,
431
- num_patches_list=num_patches_list,
432
- history=None, return_history=True)
433
- print(f'User: {question}\nAssistant: {response}')
434
-
435
- question = 'What are the similarities and differences between these two images.'
436
- response, history = model.chat(tokenizer, pixel_values, question, generation_config,
437
- num_patches_list=num_patches_list,
438
- history=history, return_history=True)
439
- print(f'User: {question}\nAssistant: {response}')
440
-
441
- # batch inference, single image per sample (单图批处理)
442
- pixel_values1 = load_image('./examples/image1.jpg', max_num=12).to(torch.bfloat16).cuda()
443
- pixel_values2 = load_image('./examples/image2.jpg', max_num=12).to(torch.bfloat16).cuda()
444
- num_patches_list = [pixel_values1.size(0), pixel_values2.size(0)]
445
- pixel_values = torch.cat((pixel_values1, pixel_values2), dim=0)
446
-
447
- questions = ['<image>\nDescribe the image in detail.'] * len(num_patches_list)
448
- responses = model.batch_chat(tokenizer, pixel_values,
449
- num_patches_list=num_patches_list,
450
- questions=questions,
451
- generation_config=generation_config)
452
- for question, response in zip(questions, responses):
453
- print(f'User: {question}\nAssistant: {response}')
454
-
455
- # video multi-round conversation (视频多轮对话)
456
- def get_index(bound, fps, max_frame, first_idx=0, num_segments=32):
457
- if bound:
458
- start, end = bound[0], bound[1]
459
- else:
460
- start, end = -100000, 100000
461
- start_idx = max(first_idx, round(start * fps))
462
- end_idx = min(round(end * fps), max_frame)
463
- seg_size = float(end_idx - start_idx) / num_segments
464
- frame_indices = np.array([
465
- int(start_idx + (seg_size / 2) + np.round(seg_size * idx))
466
- for idx in range(num_segments)
467
- ])
468
- return frame_indices
469
-
470
- def load_video(video_path, bound=None, input_size=448, max_num=1, num_segments=32):
471
- vr = VideoReader(video_path, ctx=cpu(0), num_threads=1)
472
- max_frame = len(vr) - 1
473
- fps = float(vr.get_avg_fps())
474
-
475
- pixel_values_list, num_patches_list = [], []
476
- transform = build_transform(input_size=input_size)
477
- frame_indices = get_index(bound, fps, max_frame, first_idx=0, num_segments=num_segments)
478
- for frame_index in frame_indices:
479
- img = Image.fromarray(vr[frame_index].asnumpy()).convert('RGB')
480
- img = dynamic_preprocess(img, image_size=input_size, use_thumbnail=True, max_num=max_num)
481
- pixel_values = [transform(tile) for tile in img]
482
- pixel_values = torch.stack(pixel_values)
483
- num_patches_list.append(pixel_values.shape[0])
484
- pixel_values_list.append(pixel_values)
485
- pixel_values = torch.cat(pixel_values_list)
486
- return pixel_values, num_patches_list
487
-
488
- video_path = './examples/red-panda.mp4'
489
- pixel_values, num_patches_list = load_video(video_path, num_segments=8, max_num=1)
490
- pixel_values = pixel_values.to(torch.bfloat16).cuda()
491
- video_prefix = ''.join([f'Frame{i+1}: <image>\n' for i in range(len(num_patches_list))])
492
- question = video_prefix + 'What is the red panda doing?'
493
- # Frame1: <image>\nFrame2: <image>\n...\nFrame8: <image>\n{question}
494
- response, history = model.chat(tokenizer, pixel_values, question, generation_config,
495
- num_patches_list=num_patches_list, history=None, return_history=True)
496
- print(f'User: {question}\nAssistant: {response}')
497
-
498
- question = 'Describe this video in detail.'
499
- response, history = model.chat(tokenizer, pixel_values, question, generation_config,
500
- num_patches_list=num_patches_list, history=history, return_history=True)
501
- print(f'User: {question}\nAssistant: {response}')
502
- ```
503
-
504
- #### Streaming Output
505
-
506
- Besides this method, you can also use the following code to get streamed output.
507
-
508
- ```python
509
- from transformers import TextIteratorStreamer
510
- from threading import Thread
511
-
512
- # Initialize the streamer
513
- streamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True, timeout=10)
514
- # Define the generation configuration
515
- generation_config = dict(max_new_tokens=1024, do_sample=False, streamer=streamer)
516
- # Start the model chat in a separate thread
517
- thread = Thread(target=model.chat, kwargs=dict(
518
- tokenizer=tokenizer, pixel_values=pixel_values, question=question,
519
- history=None, return_history=False, generation_config=generation_config,
520
- ))
521
- thread.start()
522
-
523
- # Initialize an empty string to store the generated text
524
- generated_text = ''
525
- # Loop through the streamer to get the new text as it is generated
526
- for new_text in streamer:
527
- if new_text == model.conv_template.sep:
528
- break
529
- generated_text += new_text
530
- print(new_text, end='', flush=True) # Print each new chunk of generated text on the same line
531
- ```
532
-
533
- ## Finetune
534
-
535
- Many repositories now support fine-tuning of the InternVL series models, including [InternVL](https://github.com/OpenGVLab/InternVL), [SWIFT](https://github.com/modelscope/ms-swift), [XTurner](https://github.com/InternLM/xtuner), and others. Please refer to their documentation for more details on fine-tuning.
536
-
537
- ## Deployment
538
-
539
- ### LMDeploy
540
-
541
- LMDeploy is a toolkit for compressing, deploying, and serving LLMs & VLMs.
542
-
543
- ```sh
544
- # if lmdeploy<0.7.3, you need to explicitly set chat_template_config=ChatTemplateConfig(model_name='internvl2_5')
545
- pip install lmdeploy>=0.7.3
546
- ```
547
-
548
- LMDeploy abstracts the complex inference process of multi-modal Vision-Language Models (VLM) into an easy-to-use pipeline, similar to the Large Language Model (LLM) inference pipeline.
549
-
550
- #### A 'Hello, world' Example
551
-
552
- ```python
553
- from lmdeploy import pipeline, TurbomindEngineConfig, ChatTemplateConfig
554
- from lmdeploy.vl import load_image
555
-
556
- model = 'OpenGVLab/InternVL3-8B'
557
- image = load_image('https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/tests/data/tiger.jpeg')
558
- pipe = pipeline(model, backend_config=TurbomindEngineConfig(session_len=16384, tp=1), chat_template_config=ChatTemplateConfig(model_name='internvl2_5'))
559
- response = pipe(('describe this image', image))
560
- print(response.text)
561
- ```
562
-
563
- If `ImportError` occurs while executing this case, please install the required dependency packages as prompted.
564
-
565
- #### Multi-images Inference
566
-
567
- When dealing with multiple images, you can put them all in one list. Keep in mind that multiple images will lead to a higher number of input tokens, and as a result, the size of the context window typically needs to be increased.
568
-
569
- ```python
570
- from lmdeploy import pipeline, TurbomindEngineConfig, ChatTemplateConfig
571
- from lmdeploy.vl import load_image
572
- from lmdeploy.vl.constants import IMAGE_TOKEN
573
-
574
- model = 'OpenGVLab/InternVL3-8B'
575
- pipe = pipeline(model, backend_config=TurbomindEngineConfig(session_len=16384, tp=1), chat_template_config=ChatTemplateConfig(model_name='internvl2_5'))
576
-
577
- image_urls=[
578
- 'https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/human-pose.jpg',
579
- 'https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/det.jpg'
580
- ]
581
-
582
- images = [load_image(img_url) for img_url in image_urls]
583
- # Numbering images improves multi-image conversations
584
- response = pipe((f'Image-1: {IMAGE_TOKEN}\nImage-2: {IMAGE_TOKEN}\ndescribe these two images', images))
585
- print(response.text)
586
- ```
587
-
588
- #### Batch Prompts Inference
589
-
590
- Conducting inference with batch prompts is quite straightforward; just place them within a list structure:
591
-
592
- ```python
593
- from lmdeploy import pipeline, TurbomindEngineConfig, ChatTemplateConfig
594
- from lmdeploy.vl import load_image
595
-
596
- model = 'OpenGVLab/InternVL3-8B'
597
- pipe = pipeline(model, backend_config=TurbomindEngineConfig(session_len=16384, tp=1), chat_template_config=ChatTemplateConfig(model_name='internvl2_5'))
598
-
599
- image_urls=[
600
- "https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/human-pose.jpg",
601
- "https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/det.jpg"
602
- ]
603
- prompts = [('describe this image', load_image(img_url)) for img_url in image_urls]
604
- response = pipe(prompts)
605
- print(response)
606
- ```
607
-
608
- #### Multi-turn Conversation
609
-
610
- There are two ways to do the multi-turn conversations with the pipeline. One is to construct messages according to the format of OpenAI and use above introduced method, the other is to use the `pipeline.chat` interface.
611
-
612
- ```python
613
- from lmdeploy import pipeline, TurbomindEngineConfig, GenerationConfig, ChatTemplateConfig
614
- from lmdeploy.vl import load_image
615
-
616
- model = 'OpenGVLab/InternVL3-8B'
617
- pipe = pipeline(model, backend_config=TurbomindEngineConfig(session_len=16384, tp=1), chat_template_config=ChatTemplateConfig(model_name='internvl2_5'))
618
-
619
- image = load_image('https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/human-pose.jpg')
620
- gen_config = GenerationConfig(top_k=40, top_p=0.8, temperature=0.8)
621
- sess = pipe.chat(('describe this image', image), gen_config=gen_config)
622
- print(sess.response.text)
623
- sess = pipe.chat('What is the woman doing?', session=sess, gen_config=gen_config)
624
- print(sess.response.text)
625
- ```
626
-
627
- #### Service
628
-
629
- LMDeploy's `api_server` enables models to be easily packed into services with a single command. The provided RESTful APIs are compatible with OpenAI's interfaces. Below are an example of service startup:
630
-
631
- ```shell
632
- lmdeploy serve api_server OpenGVLab/InternVL3-8B --chat-template internvl2_5 --server-port 23333 --tp 1
633
- ```
634
-
635
- To use the OpenAI-style interface, you need to install OpenAI:
636
-
637
- ```shell
638
- pip install openai
639
- ```
640
-
641
- Then, use the code below to make the API call:
642
-
643
- ```python
644
- from openai import OpenAI
645
-
646
- client = OpenAI(api_key='YOUR_API_KEY', base_url='http://0.0.0.0:23333/v1')
647
- model_name = client.models.list().data[0].id
648
- response = client.chat.completions.create(
649
- model=model_name,
650
- messages=[{
651
- 'role':
652
- 'user',
653
- 'content': [{
654
- 'type': 'text',
655
- 'text': 'describe this image',
656
- }, {
657
- 'type': 'image_url',
658
- 'image_url': {
659
- 'url':
660
- 'https://modelscope.oss-cn-beijing.aliyuncs.com/resource/tiger.jpeg',
661
- },
662
- }],
663
- }],
664
- temperature=0.8,
665
- top_p=0.8)
666
- print(response)
667
- ```
668
-
669
- ## License
670
-
671
- This project is released under the MIT License. This project uses the pre-trained Qwen2.5 as a component, which is licensed under the Apache-2.0 License.
672
-
673
- ## Citation
674
-
675
- If you find this project useful in your research, please consider citing:
676
-
677
- ```BibTeX
678
- @article{chen2024expanding,
679
- title={Expanding Performance Boundaries of Open-Source Multimodal Models with Model, Data, and Test-Time Scaling},
680
- author={Chen, Zhe and Wang, Weiyun and Cao, Yue and Liu, Yangzhou and Gao, Zhangwei and Cui, Erfei and Zhu, Jinguo and Ye, Shenglong and Tian, Hao and Liu, Zhaoyang and others},
681
- journal={arXiv preprint arXiv:2412.05271},
682
- year={2024}
683
- }
684
- @article{wang2024mpo,
685
- title={Enhancing the Reasoning Ability of Multimodal Large Language Models via Mixed Preference Optimization},
686
- author={Wang, Weiyun and Chen, Zhe and Wang, Wenhai and Cao, Yue and Liu, Yangzhou and Gao, Zhangwei and Zhu, Jinguo and Zhu, Xizhou and Lu, Lewei and Qiao, Yu and Dai, Jifeng},
687
- journal={arXiv preprint arXiv:2411.10442},
688
- year={2024}
689
- }
690
- @article{chen2024far,
691
- title={How Far Are We to GPT-4V? Closing the Gap to Commercial Multimodal Models with Open-Source Suites},
692
- author={Chen, Zhe and Wang, Weiyun and Tian, Hao and Ye, Shenglong and Gao, Zhangwei and Cui, Erfei and Tong, Wenwen and Hu, Kongzhi and Luo, Jiapeng and Ma, Zheng and others},
693
- journal={arXiv preprint arXiv:2404.16821},
694
- year={2024}
695
- }
696
- @inproceedings{chen2024internvl,
697
- title={Internvl: Scaling up vision foundation models and aligning for generic visual-linguistic tasks},
698
- author={Chen, Zhe and Wu, Jiannan and Wang, Wenhai and Su, Weijie and Chen, Guo and Xing, Sen and Zhong, Muyan and Zhang, Qinglong and Zhu, Xizhou and Lu, Lewei and others},
699
- booktitle={Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition},
700
- pages={24185--24198},
701
- year={2024}
702
- }
703
- ```