lbourdois commited on
Commit
e4a39ce
·
verified ·
1 Parent(s): 8e4360b

Improve language tag

Browse files

Hi! As the model is multilingual, this is a PR to add other languages than English to the language tag to improve the referencing. Note that 29 languages are announced in the README, but only 13 are explicitly listed. I was therefore only able to add these 13 languages.

Files changed (1) hide show
  1. README.md +715 -703
README.md CHANGED
@@ -1,704 +1,716 @@
1
- ---
2
- license: other
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/InternViT-6B-448px-V2_5
9
- - Qwen/Qwen2.5-72B
10
- base_model_relation: merge
11
- language:
12
- - multilingual
13
- tags:
14
- - internvl
15
- - custom_code
16
- ---
17
-
18
- # InternVL3-78B-Pretrained
19
-
20
- [\[📂 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)
21
-
22
- [\[🆕 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/)
23
-
24
- <div align="center">
25
- <img width="500" alt="image" src="https://cdn-uploads.huggingface.co/production/uploads/64006c09330a45b03605bba3/zJsd2hqd3EevgXo6fNgC-.png">
26
- </div>
27
-
28
- ## Introduction
29
-
30
- ***This is the pretrained version of InternVL3-78B, which has undergone native multimodal pre-trainin but has not undergone post-training (i.e., SFT and MPO). If you're unsure which version to use, please use the [InternVL3-78B](https://huggingface.co/OpenGVLab/InternVL3-78B) version.***
31
-
32
- We introduce InternVL3, an advanced multimodal large language model (MLLM) series that demonstrates superior overall performance.
33
- 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.
34
- 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.
35
-
36
- ![image/png](https://huggingface.co/datasets/Weiyun1025/InternVL-Performance/resolve/main/internvl3/overall.png)
37
-
38
- ## InternVL3 Family
39
-
40
- In the following table, we provide an overview of the InternVL3 series.
41
-
42
- | Model Name | Vision Part | Language Part | HF Link |
43
- | :-----------: | :-------------------------------------------------------------------------------------: | :----------------------------------------------------------------------------: | :------------------------------------------------------: |
44
- | 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) |
45
- | 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) |
46
- | 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) |
47
- | 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) |
48
- | 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) |
49
- | 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) |
50
- | 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) |
51
-
52
- ![image/png](https://huggingface.co/datasets/Weiyun1025/InternVL-Performance/resolve/main/internvl3/overall-table.png)
53
-
54
- ## Model Architecture
55
-
56
- 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.
57
-
58
-
59
- ![image/png](https://cdn-uploads.huggingface.co/production/uploads/64119264f0f81eb569e0d569/BiiyXN6NOk0p-3rl3ueyL.png)
60
-
61
- 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.
62
-
63
- 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.
64
-
65
- ## Training Strategy
66
-
67
- ### Native Multimodal Pre-Training
68
-
69
- 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.
70
- 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.
71
- Please see [our paper](https://huggingface.co/papers/2504.10479) for more details.
72
-
73
- ### Supervised Fine-Tuning
74
-
75
- 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.
76
- 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.
77
- 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.
78
-
79
- ### Mixed Preference Optimization
80
-
81
- During Pre-training and SFT, the model is trained to predict the next token conditioned on previous ground-truth tokens.
82
- However, during inference, the model predicts each token based on its own prior outputs.
83
- 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.
84
- 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.
85
- Specifically, the training objective of MPO is a combination of
86
- preference loss \\(\mathcal{L}_{\text{p}}\\),
87
- quality loss \\(\mathcal{L}_{\text{q}}\\),
88
- and generation loss \\(\mathcal{L}_{\text{g}}\\),
89
- which can be formulated as follows:
90
-
91
-
92
- $$
93
- \mathcal{L}=w_{p}\cdot\mathcal{L}_{\text{p}} + w_{q}\cdot\mathcal{L}_{\text{q}} + w_{g}\cdot\mathcal{L}_{\text{g}},
94
- $$
95
-
96
-
97
- 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.
98
-
99
-
100
- ### Test-Time Scaling
101
-
102
- Test-Time Scaling has been shown to be an effective method to enhance the reasoning abilities of LLMs and MLLMs.
103
- 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.
104
-
105
- ## Evaluation on Multimodal Capability
106
-
107
- ### Multimodal Reasoning and Mathematics
108
-
109
- ![image/png](https://huggingface.co/datasets/Weiyun1025/InternVL-Performance/resolve/main/internvl3/reasoning.png)
110
-
111
- ### OCR, Chart, and Document Understanding
112
-
113
- ![image/png](https://huggingface.co/datasets/Weiyun1025/InternVL-Performance/resolve/main/internvl3/ocr.png)
114
-
115
- ### Multi-Image & Real-World Comprehension
116
-
117
- ![image/png](https://huggingface.co/datasets/Weiyun1025/InternVL-Performance/resolve/main/internvl3/multi-images.png)
118
-
119
- ### Comprehensive Multimodal & Hallucination Evaluation
120
-
121
- ![image/png](https://huggingface.co/datasets/Weiyun1025/InternVL-Performance/resolve/main/internvl3/comprehensive.png)
122
-
123
- ### Visual Grounding
124
-
125
- ![image/png](https://huggingface.co/datasets/Weiyun1025/InternVL-Performance/resolve/main/internvl3/grounding.png)
126
-
127
- ### Multimodal Multilingual Understanding
128
-
129
- ![image/png](https://huggingface.co/datasets/Weiyun1025/InternVL-Performance/resolve/main/internvl3/multilingual.png)
130
-
131
- ### Video Understanding
132
-
133
- ![image/png](https://huggingface.co/datasets/Weiyun1025/InternVL-Performance/resolve/main/internvl3/video.png)
134
-
135
- ### GUI Grounding
136
-
137
- ![image/png](https://huggingface.co/datasets/Weiyun1025/InternVL-Performance/resolve/main/internvl3/gui.png)
138
-
139
- ### Spatial Reasoning
140
-
141
- ![image/png](https://huggingface.co/datasets/Weiyun1025/InternVL-Performance/resolve/main/internvl3/vsi.png)
142
-
143
- ## Evaluation on Language Capability
144
-
145
- 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.
146
- Benefitting from Native Multimodal Pre-Training, the InternVL3 series achieves even better overall text performance than the Qwen2.5 series.
147
- 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.
148
-
149
- ![image/png](https://huggingface.co/datasets/Weiyun1025/InternVL-Performance/resolve/main/internvl3/text.png)
150
-
151
- ## Ablation Study
152
-
153
- ### Native Multimodal Pre-Training
154
-
155
- 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.
156
-
157
- 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.
158
-
159
- ![image/png](https://huggingface.co/datasets/Weiyun1025/InternVL-Performance/resolve/main/internvl3/ablation-native.png)
160
-
161
- ### Mixed Preference Optimization
162
-
163
- 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.
164
-
165
- ![image/png](https://huggingface.co/datasets/Weiyun1025/InternVL-Performance/resolve/main/internvl3/ablation-mpo.png)
166
-
167
- ### Variable Visual Position Encoding
168
-
169
- 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.
170
-
171
- ![image/png](https://huggingface.co/datasets/Weiyun1025/InternVL-Performance/resolve/main/internvl3/ablation-v2pe.png)
172
-
173
- ## Quick Start
174
-
175
- We provide an example code to run `InternVL3-78B` using `transformers`.
176
-
177
- > Please use transformers>=4.37.2 to ensure the model works normally.
178
-
179
- ### Model Loading
180
-
181
- #### 16-bit (bf16 / fp16)
182
-
183
- ```python
184
- import torch
185
- from transformers import AutoTokenizer, AutoModel
186
- path = "OpenGVLab/InternVL3-78B"
187
- model = AutoModel.from_pretrained(
188
- path,
189
- torch_dtype=torch.bfloat16,
190
- low_cpu_mem_usage=True,
191
- use_flash_attn=True,
192
- trust_remote_code=True).eval().cuda()
193
- ```
194
-
195
- #### BNB 8-bit Quantization
196
-
197
- ```python
198
- import torch
199
- from transformers import AutoTokenizer, AutoModel
200
- path = "OpenGVLab/InternVL3-78B"
201
- model = AutoModel.from_pretrained(
202
- path,
203
- torch_dtype=torch.bfloat16,
204
- load_in_8bit=True,
205
- low_cpu_mem_usage=True,
206
- use_flash_attn=True,
207
- trust_remote_code=True).eval()
208
- ```
209
-
210
- #### Multiple GPUs
211
-
212
- 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.
213
-
214
- ```python
215
- import math
216
- import torch
217
- from transformers import AutoTokenizer, AutoModel
218
-
219
- def split_model(model_name):
220
- device_map = {}
221
- world_size = torch.cuda.device_count()
222
- config = AutoConfig.from_pretrained(model_path, trust_remote_code=True)
223
- num_layers = config.llm_config.num_hidden_layers
224
- # Since the first GPU will be used for ViT, treat it as half a GPU.
225
- num_layers_per_gpu = math.ceil(num_layers / (world_size - 0.5))
226
- num_layers_per_gpu = [num_layers_per_gpu] * world_size
227
- num_layers_per_gpu[0] = math.ceil(num_layers_per_gpu[0] * 0.5)
228
- layer_cnt = 0
229
- for i, num_layer in enumerate(num_layers_per_gpu):
230
- for j in range(num_layer):
231
- device_map[f'language_model.model.layers.{layer_cnt}'] = i
232
- layer_cnt += 1
233
- device_map['vision_model'] = 0
234
- device_map['mlp1'] = 0
235
- device_map['language_model.model.tok_embeddings'] = 0
236
- device_map['language_model.model.embed_tokens'] = 0
237
- device_map['language_model.output'] = 0
238
- device_map['language_model.model.norm'] = 0
239
- device_map['language_model.model.rotary_emb'] = 0
240
- device_map['language_model.lm_head'] = 0
241
- device_map[f'language_model.model.layers.{num_layers - 1}'] = 0
242
-
243
- return device_map
244
-
245
- path = "OpenGVLab/InternVL3-78B"
246
- device_map = split_model('InternVL3-78B')
247
- model = AutoModel.from_pretrained(
248
- path,
249
- torch_dtype=torch.bfloat16,
250
- low_cpu_mem_usage=True,
251
- use_flash_attn=True,
252
- trust_remote_code=True,
253
- device_map=device_map).eval()
254
- ```
255
-
256
- ### Inference with Transformers
257
-
258
- ```python
259
- import math
260
- import numpy as np
261
- import torch
262
- import torchvision.transforms as T
263
- from decord import VideoReader, cpu
264
- from PIL import Image
265
- from torchvision.transforms.functional import InterpolationMode
266
- from transformers import AutoModel, AutoTokenizer
267
-
268
- IMAGENET_MEAN = (0.485, 0.456, 0.406)
269
- IMAGENET_STD = (0.229, 0.224, 0.225)
270
-
271
- def build_transform(input_size):
272
- MEAN, STD = IMAGENET_MEAN, IMAGENET_STD
273
- transform = T.Compose([
274
- T.Lambda(lambda img: img.convert('RGB') if img.mode != 'RGB' else img),
275
- T.Resize((input_size, input_size), interpolation=InterpolationMode.BICUBIC),
276
- T.ToTensor(),
277
- T.Normalize(mean=MEAN, std=STD)
278
- ])
279
- return transform
280
-
281
- def find_closest_aspect_ratio(aspect_ratio, target_ratios, width, height, image_size):
282
- best_ratio_diff = float('inf')
283
- best_ratio = (1, 1)
284
- area = width * height
285
- for ratio in target_ratios:
286
- target_aspect_ratio = ratio[0] / ratio[1]
287
- ratio_diff = abs(aspect_ratio - target_aspect_ratio)
288
- if ratio_diff < best_ratio_diff:
289
- best_ratio_diff = ratio_diff
290
- best_ratio = ratio
291
- elif ratio_diff == best_ratio_diff:
292
- if area > 0.5 * image_size * image_size * ratio[0] * ratio[1]:
293
- best_ratio = ratio
294
- return best_ratio
295
-
296
- def dynamic_preprocess(image, min_num=1, max_num=12, image_size=448, use_thumbnail=False):
297
- orig_width, orig_height = image.size
298
- aspect_ratio = orig_width / orig_height
299
-
300
- # calculate the existing image aspect ratio
301
- target_ratios = set(
302
- (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
303
- i * j <= max_num and i * j >= min_num)
304
- target_ratios = sorted(target_ratios, key=lambda x: x[0] * x[1])
305
-
306
- # find the closest aspect ratio to the target
307
- target_aspect_ratio = find_closest_aspect_ratio(
308
- aspect_ratio, target_ratios, orig_width, orig_height, image_size)
309
-
310
- # calculate the target width and height
311
- target_width = image_size * target_aspect_ratio[0]
312
- target_height = image_size * target_aspect_ratio[1]
313
- blocks = target_aspect_ratio[0] * target_aspect_ratio[1]
314
-
315
- # resize the image
316
- resized_img = image.resize((target_width, target_height))
317
- processed_images = []
318
- for i in range(blocks):
319
- box = (
320
- (i % (target_width // image_size)) * image_size,
321
- (i // (target_width // image_size)) * image_size,
322
- ((i % (target_width // image_size)) + 1) * image_size,
323
- ((i // (target_width // image_size)) + 1) * image_size
324
- )
325
- # split the image
326
- split_img = resized_img.crop(box)
327
- processed_images.append(split_img)
328
- assert len(processed_images) == blocks
329
- if use_thumbnail and len(processed_images) != 1:
330
- thumbnail_img = image.resize((image_size, image_size))
331
- processed_images.append(thumbnail_img)
332
- return processed_images
333
-
334
- def load_image(image_file, input_size=448, max_num=12):
335
- image = Image.open(image_file).convert('RGB')
336
- transform = build_transform(input_size=input_size)
337
- images = dynamic_preprocess(image, image_size=input_size, use_thumbnail=True, max_num=max_num)
338
- pixel_values = [transform(image) for image in images]
339
- pixel_values = torch.stack(pixel_values)
340
- return pixel_values
341
-
342
- def split_model(model_name):
343
- device_map = {}
344
- world_size = torch.cuda.device_count()
345
- config = AutoConfig.from_pretrained(model_path, trust_remote_code=True)
346
- num_layers = config.llm_config.num_hidden_layers
347
- # Since the first GPU will be used for ViT, treat it as half a GPU.
348
- num_layers_per_gpu = math.ceil(num_layers / (world_size - 0.5))
349
- num_layers_per_gpu = [num_layers_per_gpu] * world_size
350
- num_layers_per_gpu[0] = math.ceil(num_layers_per_gpu[0] * 0.5)
351
- layer_cnt = 0
352
- for i, num_layer in enumerate(num_layers_per_gpu):
353
- for j in range(num_layer):
354
- device_map[f'language_model.model.layers.{layer_cnt}'] = i
355
- layer_cnt += 1
356
- device_map['vision_model'] = 0
357
- device_map['mlp1'] = 0
358
- device_map['language_model.model.tok_embeddings'] = 0
359
- device_map['language_model.model.embed_tokens'] = 0
360
- device_map['language_model.output'] = 0
361
- device_map['language_model.model.norm'] = 0
362
- device_map['language_model.model.rotary_emb'] = 0
363
- device_map['language_model.lm_head'] = 0
364
- device_map[f'language_model.model.layers.{num_layers - 1}'] = 0
365
-
366
- return device_map
367
-
368
- # If you set `load_in_8bit=True`, you will need two 80GB GPUs.
369
- # If you set `load_in_8bit=False`, you will need at least three 80GB GPUs.
370
- path = 'OpenGVLab/InternVL3-78B'
371
- device_map = split_model('InternVL3-78B')
372
- model = AutoModel.from_pretrained(
373
- path,
374
- torch_dtype=torch.bfloat16,
375
- load_in_8bit=False,
376
- low_cpu_mem_usage=True,
377
- use_flash_attn=True,
378
- trust_remote_code=True,
379
- device_map=device_map).eval()
380
- tokenizer = AutoTokenizer.from_pretrained(path, trust_remote_code=True, use_fast=False)
381
-
382
- # set the max number of tiles in `max_num`
383
- pixel_values = load_image('./examples/image1.jpg', max_num=12).to(torch.bfloat16).cuda()
384
- generation_config = dict(max_new_tokens=1024, do_sample=True)
385
-
386
- # pure-text conversation (纯文本对话)
387
- question = 'Hello, who are you?'
388
- response, history = model.chat(tokenizer, None, question, generation_config, history=None, return_history=True)
389
- print(f'User: {question}\nAssistant: {response}')
390
-
391
- question = 'Can you tell me a story?'
392
- response, history = model.chat(tokenizer, None, question, generation_config, history=history, return_history=True)
393
- print(f'User: {question}\nAssistant: {response}')
394
-
395
- # single-image single-round conversation (单图单轮对话)
396
- question = '<image>\nPlease describe the image shortly.'
397
- response = model.chat(tokenizer, pixel_values, question, generation_config)
398
- print(f'User: {question}\nAssistant: {response}')
399
-
400
- # single-image multi-round conversation (单图多轮对话)
401
- question = '<image>\nPlease describe the image in detail.'
402
- response, history = model.chat(tokenizer, pixel_values, question, generation_config, history=None, return_history=True)
403
- print(f'User: {question}\nAssistant: {response}')
404
-
405
- question = 'Please write a poem according to the image.'
406
- response, history = model.chat(tokenizer, pixel_values, question, generation_config, history=history, return_history=True)
407
- print(f'User: {question}\nAssistant: {response}')
408
-
409
- # multi-image multi-round conversation, combined images (多图多轮对话,拼接图像)
410
- pixel_values1 = load_image('./examples/image1.jpg', max_num=12).to(torch.bfloat16).cuda()
411
- pixel_values2 = load_image('./examples/image2.jpg', max_num=12).to(torch.bfloat16).cuda()
412
- pixel_values = torch.cat((pixel_values1, pixel_values2), dim=0)
413
-
414
- question = '<image>\nDescribe the two images in detail.'
415
- response, history = model.chat(tokenizer, pixel_values, question, generation_config,
416
- history=None, return_history=True)
417
- print(f'User: {question}\nAssistant: {response}')
418
-
419
- question = 'What are the similarities and differences between these two images.'
420
- response, history = model.chat(tokenizer, pixel_values, question, generation_config,
421
- history=history, return_history=True)
422
- print(f'User: {question}\nAssistant: {response}')
423
-
424
- # multi-image multi-round conversation, separate images (多图多轮对话,独立图像)
425
- pixel_values1 = load_image('./examples/image1.jpg', max_num=12).to(torch.bfloat16).cuda()
426
- pixel_values2 = load_image('./examples/image2.jpg', max_num=12).to(torch.bfloat16).cuda()
427
- pixel_values = torch.cat((pixel_values1, pixel_values2), dim=0)
428
- num_patches_list = [pixel_values1.size(0), pixel_values2.size(0)]
429
-
430
- question = 'Image-1: <image>\nImage-2: <image>\nDescribe the two images in detail.'
431
- response, history = model.chat(tokenizer, pixel_values, question, generation_config,
432
- num_patches_list=num_patches_list,
433
- history=None, return_history=True)
434
- print(f'User: {question}\nAssistant: {response}')
435
-
436
- question = 'What are the similarities and differences between these two images.'
437
- response, history = model.chat(tokenizer, pixel_values, question, generation_config,
438
- num_patches_list=num_patches_list,
439
- history=history, return_history=True)
440
- print(f'User: {question}\nAssistant: {response}')
441
-
442
- # batch inference, single image per sample (单图批处理)
443
- pixel_values1 = load_image('./examples/image1.jpg', max_num=12).to(torch.bfloat16).cuda()
444
- pixel_values2 = load_image('./examples/image2.jpg', max_num=12).to(torch.bfloat16).cuda()
445
- num_patches_list = [pixel_values1.size(0), pixel_values2.size(0)]
446
- pixel_values = torch.cat((pixel_values1, pixel_values2), dim=0)
447
-
448
- questions = ['<image>\nDescribe the image in detail.'] * len(num_patches_list)
449
- responses = model.batch_chat(tokenizer, pixel_values,
450
- num_patches_list=num_patches_list,
451
- questions=questions,
452
- generation_config=generation_config)
453
- for question, response in zip(questions, responses):
454
- print(f'User: {question}\nAssistant: {response}')
455
-
456
- # video multi-round conversation (视频多轮对话)
457
- def get_index(bound, fps, max_frame, first_idx=0, num_segments=32):
458
- if bound:
459
- start, end = bound[0], bound[1]
460
- else:
461
- start, end = -100000, 100000
462
- start_idx = max(first_idx, round(start * fps))
463
- end_idx = min(round(end * fps), max_frame)
464
- seg_size = float(end_idx - start_idx) / num_segments
465
- frame_indices = np.array([
466
- int(start_idx + (seg_size / 2) + np.round(seg_size * idx))
467
- for idx in range(num_segments)
468
- ])
469
- return frame_indices
470
-
471
- def load_video(video_path, bound=None, input_size=448, max_num=1, num_segments=32):
472
- vr = VideoReader(video_path, ctx=cpu(0), num_threads=1)
473
- max_frame = len(vr) - 1
474
- fps = float(vr.get_avg_fps())
475
-
476
- pixel_values_list, num_patches_list = [], []
477
- transform = build_transform(input_size=input_size)
478
- frame_indices = get_index(bound, fps, max_frame, first_idx=0, num_segments=num_segments)
479
- for frame_index in frame_indices:
480
- img = Image.fromarray(vr[frame_index].asnumpy()).convert('RGB')
481
- img = dynamic_preprocess(img, image_size=input_size, use_thumbnail=True, max_num=max_num)
482
- pixel_values = [transform(tile) for tile in img]
483
- pixel_values = torch.stack(pixel_values)
484
- num_patches_list.append(pixel_values.shape[0])
485
- pixel_values_list.append(pixel_values)
486
- pixel_values = torch.cat(pixel_values_list)
487
- return pixel_values, num_patches_list
488
-
489
- video_path = './examples/red-panda.mp4'
490
- pixel_values, num_patches_list = load_video(video_path, num_segments=8, max_num=1)
491
- pixel_values = pixel_values.to(torch.bfloat16).cuda()
492
- video_prefix = ''.join([f'Frame{i+1}: <image>\n' for i in range(len(num_patches_list))])
493
- question = video_prefix + 'What is the red panda doing?'
494
- # Frame1: <image>\nFrame2: <image>\n...\nFrame8: <image>\n{question}
495
- response, history = model.chat(tokenizer, pixel_values, question, generation_config,
496
- num_patches_list=num_patches_list, history=None, return_history=True)
497
- print(f'User: {question}\nAssistant: {response}')
498
-
499
- question = 'Describe this video in detail.'
500
- response, history = model.chat(tokenizer, pixel_values, question, generation_config,
501
- num_patches_list=num_patches_list, history=history, return_history=True)
502
- print(f'User: {question}\nAssistant: {response}')
503
- ```
504
-
505
- #### Streaming Output
506
-
507
- Besides this method, you can also use the following code to get streamed output.
508
-
509
- ```python
510
- from transformers import TextIteratorStreamer
511
- from threading import Thread
512
-
513
- # Initialize the streamer
514
- streamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True, timeout=10)
515
- # Define the generation configuration
516
- generation_config = dict(max_new_tokens=1024, do_sample=False, streamer=streamer)
517
- # Start the model chat in a separate thread
518
- thread = Thread(target=model.chat, kwargs=dict(
519
- tokenizer=tokenizer, pixel_values=pixel_values, question=question,
520
- history=None, return_history=False, generation_config=generation_config,
521
- ))
522
- thread.start()
523
-
524
- # Initialize an empty string to store the generated text
525
- generated_text = ''
526
- # Loop through the streamer to get the new text as it is generated
527
- for new_text in streamer:
528
- if new_text == model.conv_template.sep:
529
- break
530
- generated_text += new_text
531
- print(new_text, end='', flush=True) # Print each new chunk of generated text on the same line
532
- ```
533
-
534
- ## Finetune
535
-
536
- 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.
537
-
538
- ## Deployment
539
-
540
- ### LMDeploy
541
-
542
- LMDeploy is a toolkit for compressing, deploying, and serving LLMs & VLMs.
543
-
544
- ```sh
545
- # if lmdeploy<0.7.3, you need to explicitly set chat_template_config=ChatTemplateConfig(model_name='internvl2_5')
546
- pip install lmdeploy>=0.7.3
547
- ```
548
-
549
- 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.
550
-
551
- #### A 'Hello, world' Example
552
-
553
- ```python
554
- from lmdeploy import pipeline, TurbomindEngineConfig, ChatTemplateConfig
555
- from lmdeploy.vl import load_image
556
-
557
- model = 'OpenGVLab/InternVL3-78B'
558
- image = load_image('https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/tests/data/tiger.jpeg')
559
- pipe = pipeline(model, backend_config=TurbomindEngineConfig(session_len=16384, tp=4), chat_template_config=ChatTemplateConfig(model_name='internvl2_5'))
560
- response = pipe(('describe this image', image))
561
- print(response.text)
562
- ```
563
-
564
- If `ImportError` occurs while executing this case, please install the required dependency packages as prompted.
565
-
566
- #### Multi-images Inference
567
-
568
- 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.
569
-
570
- ```python
571
- from lmdeploy import pipeline, TurbomindEngineConfig, ChatTemplateConfig
572
- from lmdeploy.vl import load_image
573
- from lmdeploy.vl.constants import IMAGE_TOKEN
574
-
575
- model = 'OpenGVLab/InternVL3-78B'
576
- pipe = pipeline(model, backend_config=TurbomindEngineConfig(session_len=16384, tp=4), chat_template_config=ChatTemplateConfig(model_name='internvl2_5'))
577
-
578
- image_urls=[
579
- 'https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/human-pose.jpg',
580
- 'https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/det.jpg'
581
- ]
582
-
583
- images = [load_image(img_url) for img_url in image_urls]
584
- # Numbering images improves multi-image conversations
585
- response = pipe((f'Image-1: {IMAGE_TOKEN}\nImage-2: {IMAGE_TOKEN}\ndescribe these two images', images))
586
- print(response.text)
587
- ```
588
-
589
- #### Batch Prompts Inference
590
-
591
- Conducting inference with batch prompts is quite straightforward; just place them within a list structure:
592
-
593
- ```python
594
- from lmdeploy import pipeline, TurbomindEngineConfig, ChatTemplateConfig
595
- from lmdeploy.vl import load_image
596
-
597
- model = 'OpenGVLab/InternVL3-78B'
598
- pipe = pipeline(model, backend_config=TurbomindEngineConfig(session_len=16384, tp=4), chat_template_config=ChatTemplateConfig(model_name='internvl2_5'))
599
-
600
- image_urls=[
601
- "https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/human-pose.jpg",
602
- "https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/det.jpg"
603
- ]
604
- prompts = [('describe this image', load_image(img_url)) for img_url in image_urls]
605
- response = pipe(prompts)
606
- print(response)
607
- ```
608
-
609
- #### Multi-turn Conversation
610
-
611
- 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.
612
-
613
- ```python
614
- from lmdeploy import pipeline, TurbomindEngineConfig, GenerationConfig, ChatTemplateConfig
615
- from lmdeploy.vl import load_image
616
-
617
- model = 'OpenGVLab/InternVL3-78B'
618
- pipe = pipeline(model, backend_config=TurbomindEngineConfig(session_len=16384, tp=4), chat_template_config=ChatTemplateConfig(model_name='internvl2_5'))
619
-
620
- image = load_image('https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/human-pose.jpg')
621
- gen_config = GenerationConfig(top_k=40, top_p=0.8, temperature=0.8)
622
- sess = pipe.chat(('describe this image', image), gen_config=gen_config)
623
- print(sess.response.text)
624
- sess = pipe.chat('What is the woman doing?', session=sess, gen_config=gen_config)
625
- print(sess.response.text)
626
- ```
627
-
628
- #### Service
629
-
630
- 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:
631
-
632
- ```shell
633
- lmdeploy serve api_server OpenGVLab/InternVL3-78B --chat-template internvl2_5 --server-port 23333 --tp 4
634
- ```
635
-
636
- To use the OpenAI-style interface, you need to install OpenAI:
637
-
638
- ```shell
639
- pip install openai
640
- ```
641
-
642
- Then, use the code below to make the API call:
643
-
644
- ```python
645
- from openai import OpenAI
646
-
647
- client = OpenAI(api_key='YOUR_API_KEY', base_url='http://0.0.0.0:23333/v1')
648
- model_name = client.models.list().data[0].id
649
- response = client.chat.completions.create(
650
- model=model_name,
651
- messages=[{
652
- 'role':
653
- 'user',
654
- 'content': [{
655
- 'type': 'text',
656
- 'text': 'describe this image',
657
- }, {
658
- 'type': 'image_url',
659
- 'image_url': {
660
- 'url':
661
- 'https://modelscope.oss-cn-beijing.aliyuncs.com/resource/tiger.jpeg',
662
- },
663
- }],
664
- }],
665
- temperature=0.8,
666
- top_p=0.8)
667
- print(response)
668
- ```
669
-
670
- ## License
671
-
672
- This project is released under the MIT License. This project uses the pre-trained Qwen2.5 as a component, which is licensed under the Qwen License.
673
-
674
- ## Citation
675
-
676
- If you find this project useful in your research, please consider citing:
677
-
678
- ```BibTeX
679
- @article{chen2024expanding,
680
- title={Expanding Performance Boundaries of Open-Source Multimodal Models with Model, Data, and Test-Time Scaling},
681
- 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},
682
- journal={arXiv preprint arXiv:2412.05271},
683
- year={2024}
684
- }
685
- @article{wang2024mpo,
686
- title={Enhancing the Reasoning Ability of Multimodal Large Language Models via Mixed Preference Optimization},
687
- 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},
688
- journal={arXiv preprint arXiv:2411.10442},
689
- year={2024}
690
- }
691
- @article{chen2024far,
692
- title={How Far Are We to GPT-4V? Closing the Gap to Commercial Multimodal Models with Open-Source Suites},
693
- 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},
694
- journal={arXiv preprint arXiv:2404.16821},
695
- year={2024}
696
- }
697
- @inproceedings{chen2024internvl,
698
- title={Internvl: Scaling up vision foundation models and aligning for generic visual-linguistic tasks},
699
- 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},
700
- booktitle={Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition},
701
- pages={24185--24198},
702
- year={2024}
703
- }
 
 
 
 
 
 
 
 
 
 
 
 
704
  ```
 
1
+ ---
2
+ license: other
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/InternViT-6B-448px-V2_5
9
+ - Qwen/Qwen2.5-72B
10
+ base_model_relation: merge
11
+ language:
12
+ - zho
13
+ - eng
14
+ - fra
15
+ - spa
16
+ - por
17
+ - deu
18
+ - ita
19
+ - rus
20
+ - jpn
21
+ - kor
22
+ - vie
23
+ - tha
24
+ - ara
25
+ tags:
26
+ - internvl
27
+ - custom_code
28
+ ---
29
+
30
+ # InternVL3-78B-Pretrained
31
+
32
+ [\[📂 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)
33
+
34
+ [\[🆕 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/)
35
+
36
+ <div align="center">
37
+ <img width="500" alt="image" src="https://cdn-uploads.huggingface.co/production/uploads/64006c09330a45b03605bba3/zJsd2hqd3EevgXo6fNgC-.png">
38
+ </div>
39
+
40
+ ## Introduction
41
+
42
+ ***This is the pretrained version of InternVL3-78B, which has undergone native multimodal pre-trainin but has not undergone post-training (i.e., SFT and MPO). If you're unsure which version to use, please use the [InternVL3-78B](https://huggingface.co/OpenGVLab/InternVL3-78B) version.***
43
+
44
+ We introduce InternVL3, an advanced multimodal large language model (MLLM) series that demonstrates superior overall performance.
45
+ 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.
46
+ 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.
47
+
48
+ ![image/png](https://huggingface.co/datasets/Weiyun1025/InternVL-Performance/resolve/main/internvl3/overall.png)
49
+
50
+ ## InternVL3 Family
51
+
52
+ In the following table, we provide an overview of the InternVL3 series.
53
+
54
+ | Model Name | Vision Part | Language Part | HF Link |
55
+ | :-----------: | :-------------------------------------------------------------------------------------: | :----------------------------------------------------------------------------: | :------------------------------------------------------: |
56
+ | 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) |
57
+ | 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) |
58
+ | 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) |
59
+ | 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) |
60
+ | 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) |
61
+ | 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) |
62
+ | 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) |
63
+
64
+ ![image/png](https://huggingface.co/datasets/Weiyun1025/InternVL-Performance/resolve/main/internvl3/overall-table.png)
65
+
66
+ ## Model Architecture
67
+
68
+ 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.
69
+
70
+
71
+ ![image/png](https://cdn-uploads.huggingface.co/production/uploads/64119264f0f81eb569e0d569/BiiyXN6NOk0p-3rl3ueyL.png)
72
+
73
+ 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.
74
+
75
+ 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.
76
+
77
+ ## Training Strategy
78
+
79
+ ### Native Multimodal Pre-Training
80
+
81
+ 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.
82
+ 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.
83
+ Please see [our paper](https://huggingface.co/papers/2504.10479) for more details.
84
+
85
+ ### Supervised Fine-Tuning
86
+
87
+ 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.
88
+ 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.
89
+ 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.
90
+
91
+ ### Mixed Preference Optimization
92
+
93
+ During Pre-training and SFT, the model is trained to predict the next token conditioned on previous ground-truth tokens.
94
+ However, during inference, the model predicts each token based on its own prior outputs.
95
+ 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.
96
+ 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.
97
+ Specifically, the training objective of MPO is a combination of
98
+ preference loss \\(\mathcal{L}_{\text{p}}\\),
99
+ quality loss \\(\mathcal{L}_{\text{q}}\\),
100
+ and generation loss \\(\mathcal{L}_{\text{g}}\\),
101
+ which can be formulated as follows:
102
+
103
+
104
+ $$
105
+ \mathcal{L}=w_{p}\cdot\mathcal{L}_{\text{p}} + w_{q}\cdot\mathcal{L}_{\text{q}} + w_{g}\cdot\mathcal{L}_{\text{g}},
106
+ $$
107
+
108
+
109
+ 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.
110
+
111
+
112
+ ### Test-Time Scaling
113
+
114
+ Test-Time Scaling has been shown to be an effective method to enhance the reasoning abilities of LLMs and MLLMs.
115
+ 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.
116
+
117
+ ## Evaluation on Multimodal Capability
118
+
119
+ ### Multimodal Reasoning and Mathematics
120
+
121
+ ![image/png](https://huggingface.co/datasets/Weiyun1025/InternVL-Performance/resolve/main/internvl3/reasoning.png)
122
+
123
+ ### OCR, Chart, and Document Understanding
124
+
125
+ ![image/png](https://huggingface.co/datasets/Weiyun1025/InternVL-Performance/resolve/main/internvl3/ocr.png)
126
+
127
+ ### Multi-Image & Real-World Comprehension
128
+
129
+ ![image/png](https://huggingface.co/datasets/Weiyun1025/InternVL-Performance/resolve/main/internvl3/multi-images.png)
130
+
131
+ ### Comprehensive Multimodal & Hallucination Evaluation
132
+
133
+ ![image/png](https://huggingface.co/datasets/Weiyun1025/InternVL-Performance/resolve/main/internvl3/comprehensive.png)
134
+
135
+ ### Visual Grounding
136
+
137
+ ![image/png](https://huggingface.co/datasets/Weiyun1025/InternVL-Performance/resolve/main/internvl3/grounding.png)
138
+
139
+ ### Multimodal Multilingual Understanding
140
+
141
+ ![image/png](https://huggingface.co/datasets/Weiyun1025/InternVL-Performance/resolve/main/internvl3/multilingual.png)
142
+
143
+ ### Video Understanding
144
+
145
+ ![image/png](https://huggingface.co/datasets/Weiyun1025/InternVL-Performance/resolve/main/internvl3/video.png)
146
+
147
+ ### GUI Grounding
148
+
149
+ ![image/png](https://huggingface.co/datasets/Weiyun1025/InternVL-Performance/resolve/main/internvl3/gui.png)
150
+
151
+ ### Spatial Reasoning
152
+
153
+ ![image/png](https://huggingface.co/datasets/Weiyun1025/InternVL-Performance/resolve/main/internvl3/vsi.png)
154
+
155
+ ## Evaluation on Language Capability
156
+
157
+ 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.
158
+ Benefitting from Native Multimodal Pre-Training, the InternVL3 series achieves even better overall text performance than the Qwen2.5 series.
159
+ 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.
160
+
161
+ ![image/png](https://huggingface.co/datasets/Weiyun1025/InternVL-Performance/resolve/main/internvl3/text.png)
162
+
163
+ ## Ablation Study
164
+
165
+ ### Native Multimodal Pre-Training
166
+
167
+ 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.
168
+
169
+ 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.
170
+
171
+ ![image/png](https://huggingface.co/datasets/Weiyun1025/InternVL-Performance/resolve/main/internvl3/ablation-native.png)
172
+
173
+ ### Mixed Preference Optimization
174
+
175
+ 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.
176
+
177
+ ![image/png](https://huggingface.co/datasets/Weiyun1025/InternVL-Performance/resolve/main/internvl3/ablation-mpo.png)
178
+
179
+ ### Variable Visual Position Encoding
180
+
181
+ 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.
182
+
183
+ ![image/png](https://huggingface.co/datasets/Weiyun1025/InternVL-Performance/resolve/main/internvl3/ablation-v2pe.png)
184
+
185
+ ## Quick Start
186
+
187
+ We provide an example code to run `InternVL3-78B` using `transformers`.
188
+
189
+ > Please use transformers>=4.37.2 to ensure the model works normally.
190
+
191
+ ### Model Loading
192
+
193
+ #### 16-bit (bf16 / fp16)
194
+
195
+ ```python
196
+ import torch
197
+ from transformers import AutoTokenizer, AutoModel
198
+ path = "OpenGVLab/InternVL3-78B"
199
+ model = AutoModel.from_pretrained(
200
+ path,
201
+ torch_dtype=torch.bfloat16,
202
+ low_cpu_mem_usage=True,
203
+ use_flash_attn=True,
204
+ trust_remote_code=True).eval().cuda()
205
+ ```
206
+
207
+ #### BNB 8-bit Quantization
208
+
209
+ ```python
210
+ import torch
211
+ from transformers import AutoTokenizer, AutoModel
212
+ path = "OpenGVLab/InternVL3-78B"
213
+ model = AutoModel.from_pretrained(
214
+ path,
215
+ torch_dtype=torch.bfloat16,
216
+ load_in_8bit=True,
217
+ low_cpu_mem_usage=True,
218
+ use_flash_attn=True,
219
+ trust_remote_code=True).eval()
220
+ ```
221
+
222
+ #### Multiple GPUs
223
+
224
+ 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.
225
+
226
+ ```python
227
+ import math
228
+ import torch
229
+ from transformers import AutoTokenizer, AutoModel
230
+
231
+ def split_model(model_name):
232
+ device_map = {}
233
+ world_size = torch.cuda.device_count()
234
+ config = AutoConfig.from_pretrained(model_path, trust_remote_code=True)
235
+ num_layers = config.llm_config.num_hidden_layers
236
+ # Since the first GPU will be used for ViT, treat it as half a GPU.
237
+ num_layers_per_gpu = math.ceil(num_layers / (world_size - 0.5))
238
+ num_layers_per_gpu = [num_layers_per_gpu] * world_size
239
+ num_layers_per_gpu[0] = math.ceil(num_layers_per_gpu[0] * 0.5)
240
+ layer_cnt = 0
241
+ for i, num_layer in enumerate(num_layers_per_gpu):
242
+ for j in range(num_layer):
243
+ device_map[f'language_model.model.layers.{layer_cnt}'] = i
244
+ layer_cnt += 1
245
+ device_map['vision_model'] = 0
246
+ device_map['mlp1'] = 0
247
+ device_map['language_model.model.tok_embeddings'] = 0
248
+ device_map['language_model.model.embed_tokens'] = 0
249
+ device_map['language_model.output'] = 0
250
+ device_map['language_model.model.norm'] = 0
251
+ device_map['language_model.model.rotary_emb'] = 0
252
+ device_map['language_model.lm_head'] = 0
253
+ device_map[f'language_model.model.layers.{num_layers - 1}'] = 0
254
+
255
+ return device_map
256
+
257
+ path = "OpenGVLab/InternVL3-78B"
258
+ device_map = split_model('InternVL3-78B')
259
+ model = AutoModel.from_pretrained(
260
+ path,
261
+ torch_dtype=torch.bfloat16,
262
+ low_cpu_mem_usage=True,
263
+ use_flash_attn=True,
264
+ trust_remote_code=True,
265
+ device_map=device_map).eval()
266
+ ```
267
+
268
+ ### Inference with Transformers
269
+
270
+ ```python
271
+ import math
272
+ import numpy as np
273
+ import torch
274
+ import torchvision.transforms as T
275
+ from decord import VideoReader, cpu
276
+ from PIL import Image
277
+ from torchvision.transforms.functional import InterpolationMode
278
+ from transformers import AutoModel, AutoTokenizer
279
+
280
+ IMAGENET_MEAN = (0.485, 0.456, 0.406)
281
+ IMAGENET_STD = (0.229, 0.224, 0.225)
282
+
283
+ def build_transform(input_size):
284
+ MEAN, STD = IMAGENET_MEAN, IMAGENET_STD
285
+ transform = T.Compose([
286
+ T.Lambda(lambda img: img.convert('RGB') if img.mode != 'RGB' else img),
287
+ T.Resize((input_size, input_size), interpolation=InterpolationMode.BICUBIC),
288
+ T.ToTensor(),
289
+ T.Normalize(mean=MEAN, std=STD)
290
+ ])
291
+ return transform
292
+
293
+ def find_closest_aspect_ratio(aspect_ratio, target_ratios, width, height, image_size):
294
+ best_ratio_diff = float('inf')
295
+ best_ratio = (1, 1)
296
+ area = width * height
297
+ for ratio in target_ratios:
298
+ target_aspect_ratio = ratio[0] / ratio[1]
299
+ ratio_diff = abs(aspect_ratio - target_aspect_ratio)
300
+ if ratio_diff < best_ratio_diff:
301
+ best_ratio_diff = ratio_diff
302
+ best_ratio = ratio
303
+ elif ratio_diff == best_ratio_diff:
304
+ if area > 0.5 * image_size * image_size * ratio[0] * ratio[1]:
305
+ best_ratio = ratio
306
+ return best_ratio
307
+
308
+ def dynamic_preprocess(image, min_num=1, max_num=12, image_size=448, use_thumbnail=False):
309
+ orig_width, orig_height = image.size
310
+ aspect_ratio = orig_width / orig_height
311
+
312
+ # calculate the existing image aspect ratio
313
+ target_ratios = set(
314
+ (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
315
+ i * j <= max_num and i * j >= min_num)
316
+ target_ratios = sorted(target_ratios, key=lambda x: x[0] * x[1])
317
+
318
+ # find the closest aspect ratio to the target
319
+ target_aspect_ratio = find_closest_aspect_ratio(
320
+ aspect_ratio, target_ratios, orig_width, orig_height, image_size)
321
+
322
+ # calculate the target width and height
323
+ target_width = image_size * target_aspect_ratio[0]
324
+ target_height = image_size * target_aspect_ratio[1]
325
+ blocks = target_aspect_ratio[0] * target_aspect_ratio[1]
326
+
327
+ # resize the image
328
+ resized_img = image.resize((target_width, target_height))
329
+ processed_images = []
330
+ for i in range(blocks):
331
+ box = (
332
+ (i % (target_width // image_size)) * image_size,
333
+ (i // (target_width // image_size)) * image_size,
334
+ ((i % (target_width // image_size)) + 1) * image_size,
335
+ ((i // (target_width // image_size)) + 1) * image_size
336
+ )
337
+ # split the image
338
+ split_img = resized_img.crop(box)
339
+ processed_images.append(split_img)
340
+ assert len(processed_images) == blocks
341
+ if use_thumbnail and len(processed_images) != 1:
342
+ thumbnail_img = image.resize((image_size, image_size))
343
+ processed_images.append(thumbnail_img)
344
+ return processed_images
345
+
346
+ def load_image(image_file, input_size=448, max_num=12):
347
+ image = Image.open(image_file).convert('RGB')
348
+ transform = build_transform(input_size=input_size)
349
+ images = dynamic_preprocess(image, image_size=input_size, use_thumbnail=True, max_num=max_num)
350
+ pixel_values = [transform(image) for image in images]
351
+ pixel_values = torch.stack(pixel_values)
352
+ return pixel_values
353
+
354
+ def split_model(model_name):
355
+ device_map = {}
356
+ world_size = torch.cuda.device_count()
357
+ config = AutoConfig.from_pretrained(model_path, trust_remote_code=True)
358
+ num_layers = config.llm_config.num_hidden_layers
359
+ # Since the first GPU will be used for ViT, treat it as half a GPU.
360
+ num_layers_per_gpu = math.ceil(num_layers / (world_size - 0.5))
361
+ num_layers_per_gpu = [num_layers_per_gpu] * world_size
362
+ num_layers_per_gpu[0] = math.ceil(num_layers_per_gpu[0] * 0.5)
363
+ layer_cnt = 0
364
+ for i, num_layer in enumerate(num_layers_per_gpu):
365
+ for j in range(num_layer):
366
+ device_map[f'language_model.model.layers.{layer_cnt}'] = i
367
+ layer_cnt += 1
368
+ device_map['vision_model'] = 0
369
+ device_map['mlp1'] = 0
370
+ device_map['language_model.model.tok_embeddings'] = 0
371
+ device_map['language_model.model.embed_tokens'] = 0
372
+ device_map['language_model.output'] = 0
373
+ device_map['language_model.model.norm'] = 0
374
+ device_map['language_model.model.rotary_emb'] = 0
375
+ device_map['language_model.lm_head'] = 0
376
+ device_map[f'language_model.model.layers.{num_layers - 1}'] = 0
377
+
378
+ return device_map
379
+
380
+ # If you set `load_in_8bit=True`, you will need two 80GB GPUs.
381
+ # If you set `load_in_8bit=False`, you will need at least three 80GB GPUs.
382
+ path = 'OpenGVLab/InternVL3-78B'
383
+ device_map = split_model('InternVL3-78B')
384
+ model = AutoModel.from_pretrained(
385
+ path,
386
+ torch_dtype=torch.bfloat16,
387
+ load_in_8bit=False,
388
+ low_cpu_mem_usage=True,
389
+ use_flash_attn=True,
390
+ trust_remote_code=True,
391
+ device_map=device_map).eval()
392
+ tokenizer = AutoTokenizer.from_pretrained(path, trust_remote_code=True, use_fast=False)
393
+
394
+ # set the max number of tiles in `max_num`
395
+ pixel_values = load_image('./examples/image1.jpg', max_num=12).to(torch.bfloat16).cuda()
396
+ generation_config = dict(max_new_tokens=1024, do_sample=True)
397
+
398
+ # pure-text conversation (纯文本对话)
399
+ question = 'Hello, who are you?'
400
+ response, history = model.chat(tokenizer, None, question, generation_config, history=None, return_history=True)
401
+ print(f'User: {question}\nAssistant: {response}')
402
+
403
+ question = 'Can you tell me a story?'
404
+ response, history = model.chat(tokenizer, None, question, generation_config, history=history, return_history=True)
405
+ print(f'User: {question}\nAssistant: {response}')
406
+
407
+ # single-image single-round conversation (单图单轮对话)
408
+ question = '<image>\nPlease describe the image shortly.'
409
+ response = model.chat(tokenizer, pixel_values, question, generation_config)
410
+ print(f'User: {question}\nAssistant: {response}')
411
+
412
+ # single-image multi-round conversation (单图多轮对话)
413
+ question = '<image>\nPlease describe the image in detail.'
414
+ response, history = model.chat(tokenizer, pixel_values, question, generation_config, history=None, return_history=True)
415
+ print(f'User: {question}\nAssistant: {response}')
416
+
417
+ question = 'Please write a poem according to the image.'
418
+ response, history = model.chat(tokenizer, pixel_values, question, generation_config, history=history, return_history=True)
419
+ print(f'User: {question}\nAssistant: {response}')
420
+
421
+ # multi-image multi-round conversation, combined images (多图多轮对话,拼接图像)
422
+ pixel_values1 = load_image('./examples/image1.jpg', max_num=12).to(torch.bfloat16).cuda()
423
+ pixel_values2 = load_image('./examples/image2.jpg', max_num=12).to(torch.bfloat16).cuda()
424
+ pixel_values = torch.cat((pixel_values1, pixel_values2), dim=0)
425
+
426
+ question = '<image>\nDescribe the two images in detail.'
427
+ response, history = model.chat(tokenizer, pixel_values, question, generation_config,
428
+ history=None, return_history=True)
429
+ print(f'User: {question}\nAssistant: {response}')
430
+
431
+ question = 'What are the similarities and differences between these two images.'
432
+ response, history = model.chat(tokenizer, pixel_values, question, generation_config,
433
+ history=history, return_history=True)
434
+ print(f'User: {question}\nAssistant: {response}')
435
+
436
+ # multi-image multi-round conversation, separate images (多图多轮对话,独立图像)
437
+ pixel_values1 = load_image('./examples/image1.jpg', max_num=12).to(torch.bfloat16).cuda()
438
+ pixel_values2 = load_image('./examples/image2.jpg', max_num=12).to(torch.bfloat16).cuda()
439
+ pixel_values = torch.cat((pixel_values1, pixel_values2), dim=0)
440
+ num_patches_list = [pixel_values1.size(0), pixel_values2.size(0)]
441
+
442
+ question = 'Image-1: <image>\nImage-2: <image>\nDescribe the two images in detail.'
443
+ response, history = model.chat(tokenizer, pixel_values, question, generation_config,
444
+ num_patches_list=num_patches_list,
445
+ history=None, return_history=True)
446
+ print(f'User: {question}\nAssistant: {response}')
447
+
448
+ question = 'What are the similarities and differences between these two images.'
449
+ response, history = model.chat(tokenizer, pixel_values, question, generation_config,
450
+ num_patches_list=num_patches_list,
451
+ history=history, return_history=True)
452
+ print(f'User: {question}\nAssistant: {response}')
453
+
454
+ # batch inference, single image per sample (单图批处理)
455
+ pixel_values1 = load_image('./examples/image1.jpg', max_num=12).to(torch.bfloat16).cuda()
456
+ pixel_values2 = load_image('./examples/image2.jpg', max_num=12).to(torch.bfloat16).cuda()
457
+ num_patches_list = [pixel_values1.size(0), pixel_values2.size(0)]
458
+ pixel_values = torch.cat((pixel_values1, pixel_values2), dim=0)
459
+
460
+ questions = ['<image>\nDescribe the image in detail.'] * len(num_patches_list)
461
+ responses = model.batch_chat(tokenizer, pixel_values,
462
+ num_patches_list=num_patches_list,
463
+ questions=questions,
464
+ generation_config=generation_config)
465
+ for question, response in zip(questions, responses):
466
+ print(f'User: {question}\nAssistant: {response}')
467
+
468
+ # video multi-round conversation (视频多轮对话)
469
+ def get_index(bound, fps, max_frame, first_idx=0, num_segments=32):
470
+ if bound:
471
+ start, end = bound[0], bound[1]
472
+ else:
473
+ start, end = -100000, 100000
474
+ start_idx = max(first_idx, round(start * fps))
475
+ end_idx = min(round(end * fps), max_frame)
476
+ seg_size = float(end_idx - start_idx) / num_segments
477
+ frame_indices = np.array([
478
+ int(start_idx + (seg_size / 2) + np.round(seg_size * idx))
479
+ for idx in range(num_segments)
480
+ ])
481
+ return frame_indices
482
+
483
+ def load_video(video_path, bound=None, input_size=448, max_num=1, num_segments=32):
484
+ vr = VideoReader(video_path, ctx=cpu(0), num_threads=1)
485
+ max_frame = len(vr) - 1
486
+ fps = float(vr.get_avg_fps())
487
+
488
+ pixel_values_list, num_patches_list = [], []
489
+ transform = build_transform(input_size=input_size)
490
+ frame_indices = get_index(bound, fps, max_frame, first_idx=0, num_segments=num_segments)
491
+ for frame_index in frame_indices:
492
+ img = Image.fromarray(vr[frame_index].asnumpy()).convert('RGB')
493
+ img = dynamic_preprocess(img, image_size=input_size, use_thumbnail=True, max_num=max_num)
494
+ pixel_values = [transform(tile) for tile in img]
495
+ pixel_values = torch.stack(pixel_values)
496
+ num_patches_list.append(pixel_values.shape[0])
497
+ pixel_values_list.append(pixel_values)
498
+ pixel_values = torch.cat(pixel_values_list)
499
+ return pixel_values, num_patches_list
500
+
501
+ video_path = './examples/red-panda.mp4'
502
+ pixel_values, num_patches_list = load_video(video_path, num_segments=8, max_num=1)
503
+ pixel_values = pixel_values.to(torch.bfloat16).cuda()
504
+ video_prefix = ''.join([f'Frame{i+1}: <image>\n' for i in range(len(num_patches_list))])
505
+ question = video_prefix + 'What is the red panda doing?'
506
+ # Frame1: <image>\nFrame2: <image>\n...\nFrame8: <image>\n{question}
507
+ response, history = model.chat(tokenizer, pixel_values, question, generation_config,
508
+ num_patches_list=num_patches_list, history=None, return_history=True)
509
+ print(f'User: {question}\nAssistant: {response}')
510
+
511
+ question = 'Describe this video in detail.'
512
+ response, history = model.chat(tokenizer, pixel_values, question, generation_config,
513
+ num_patches_list=num_patches_list, history=history, return_history=True)
514
+ print(f'User: {question}\nAssistant: {response}')
515
+ ```
516
+
517
+ #### Streaming Output
518
+
519
+ Besides this method, you can also use the following code to get streamed output.
520
+
521
+ ```python
522
+ from transformers import TextIteratorStreamer
523
+ from threading import Thread
524
+
525
+ # Initialize the streamer
526
+ streamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True, timeout=10)
527
+ # Define the generation configuration
528
+ generation_config = dict(max_new_tokens=1024, do_sample=False, streamer=streamer)
529
+ # Start the model chat in a separate thread
530
+ thread = Thread(target=model.chat, kwargs=dict(
531
+ tokenizer=tokenizer, pixel_values=pixel_values, question=question,
532
+ history=None, return_history=False, generation_config=generation_config,
533
+ ))
534
+ thread.start()
535
+
536
+ # Initialize an empty string to store the generated text
537
+ generated_text = ''
538
+ # Loop through the streamer to get the new text as it is generated
539
+ for new_text in streamer:
540
+ if new_text == model.conv_template.sep:
541
+ break
542
+ generated_text += new_text
543
+ print(new_text, end='', flush=True) # Print each new chunk of generated text on the same line
544
+ ```
545
+
546
+ ## Finetune
547
+
548
+ 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.
549
+
550
+ ## Deployment
551
+
552
+ ### LMDeploy
553
+
554
+ LMDeploy is a toolkit for compressing, deploying, and serving LLMs & VLMs.
555
+
556
+ ```sh
557
+ # if lmdeploy<0.7.3, you need to explicitly set chat_template_config=ChatTemplateConfig(model_name='internvl2_5')
558
+ pip install lmdeploy>=0.7.3
559
+ ```
560
+
561
+ 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.
562
+
563
+ #### A 'Hello, world' Example
564
+
565
+ ```python
566
+ from lmdeploy import pipeline, TurbomindEngineConfig, ChatTemplateConfig
567
+ from lmdeploy.vl import load_image
568
+
569
+ model = 'OpenGVLab/InternVL3-78B'
570
+ image = load_image('https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/tests/data/tiger.jpeg')
571
+ pipe = pipeline(model, backend_config=TurbomindEngineConfig(session_len=16384, tp=4), chat_template_config=ChatTemplateConfig(model_name='internvl2_5'))
572
+ response = pipe(('describe this image', image))
573
+ print(response.text)
574
+ ```
575
+
576
+ If `ImportError` occurs while executing this case, please install the required dependency packages as prompted.
577
+
578
+ #### Multi-images Inference
579
+
580
+ 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.
581
+
582
+ ```python
583
+ from lmdeploy import pipeline, TurbomindEngineConfig, ChatTemplateConfig
584
+ from lmdeploy.vl import load_image
585
+ from lmdeploy.vl.constants import IMAGE_TOKEN
586
+
587
+ model = 'OpenGVLab/InternVL3-78B'
588
+ pipe = pipeline(model, backend_config=TurbomindEngineConfig(session_len=16384, tp=4), chat_template_config=ChatTemplateConfig(model_name='internvl2_5'))
589
+
590
+ image_urls=[
591
+ 'https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/human-pose.jpg',
592
+ 'https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/det.jpg'
593
+ ]
594
+
595
+ images = [load_image(img_url) for img_url in image_urls]
596
+ # Numbering images improves multi-image conversations
597
+ response = pipe((f'Image-1: {IMAGE_TOKEN}\nImage-2: {IMAGE_TOKEN}\ndescribe these two images', images))
598
+ print(response.text)
599
+ ```
600
+
601
+ #### Batch Prompts Inference
602
+
603
+ Conducting inference with batch prompts is quite straightforward; just place them within a list structure:
604
+
605
+ ```python
606
+ from lmdeploy import pipeline, TurbomindEngineConfig, ChatTemplateConfig
607
+ from lmdeploy.vl import load_image
608
+
609
+ model = 'OpenGVLab/InternVL3-78B'
610
+ pipe = pipeline(model, backend_config=TurbomindEngineConfig(session_len=16384, tp=4), chat_template_config=ChatTemplateConfig(model_name='internvl2_5'))
611
+
612
+ image_urls=[
613
+ "https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/human-pose.jpg",
614
+ "https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/det.jpg"
615
+ ]
616
+ prompts = [('describe this image', load_image(img_url)) for img_url in image_urls]
617
+ response = pipe(prompts)
618
+ print(response)
619
+ ```
620
+
621
+ #### Multi-turn Conversation
622
+
623
+ 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.
624
+
625
+ ```python
626
+ from lmdeploy import pipeline, TurbomindEngineConfig, GenerationConfig, ChatTemplateConfig
627
+ from lmdeploy.vl import load_image
628
+
629
+ model = 'OpenGVLab/InternVL3-78B'
630
+ pipe = pipeline(model, backend_config=TurbomindEngineConfig(session_len=16384, tp=4), chat_template_config=ChatTemplateConfig(model_name='internvl2_5'))
631
+
632
+ image = load_image('https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/human-pose.jpg')
633
+ gen_config = GenerationConfig(top_k=40, top_p=0.8, temperature=0.8)
634
+ sess = pipe.chat(('describe this image', image), gen_config=gen_config)
635
+ print(sess.response.text)
636
+ sess = pipe.chat('What is the woman doing?', session=sess, gen_config=gen_config)
637
+ print(sess.response.text)
638
+ ```
639
+
640
+ #### Service
641
+
642
+ 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:
643
+
644
+ ```shell
645
+ lmdeploy serve api_server OpenGVLab/InternVL3-78B --chat-template internvl2_5 --server-port 23333 --tp 4
646
+ ```
647
+
648
+ To use the OpenAI-style interface, you need to install OpenAI:
649
+
650
+ ```shell
651
+ pip install openai
652
+ ```
653
+
654
+ Then, use the code below to make the API call:
655
+
656
+ ```python
657
+ from openai import OpenAI
658
+
659
+ client = OpenAI(api_key='YOUR_API_KEY', base_url='http://0.0.0.0:23333/v1')
660
+ model_name = client.models.list().data[0].id
661
+ response = client.chat.completions.create(
662
+ model=model_name,
663
+ messages=[{
664
+ 'role':
665
+ 'user',
666
+ 'content': [{
667
+ 'type': 'text',
668
+ 'text': 'describe this image',
669
+ }, {
670
+ 'type': 'image_url',
671
+ 'image_url': {
672
+ 'url':
673
+ 'https://modelscope.oss-cn-beijing.aliyuncs.com/resource/tiger.jpeg',
674
+ },
675
+ }],
676
+ }],
677
+ temperature=0.8,
678
+ top_p=0.8)
679
+ print(response)
680
+ ```
681
+
682
+ ## License
683
+
684
+ This project is released under the MIT License. This project uses the pre-trained Qwen2.5 as a component, which is licensed under the Qwen License.
685
+
686
+ ## Citation
687
+
688
+ If you find this project useful in your research, please consider citing:
689
+
690
+ ```BibTeX
691
+ @article{chen2024expanding,
692
+ title={Expanding Performance Boundaries of Open-Source Multimodal Models with Model, Data, and Test-Time Scaling},
693
+ 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},
694
+ journal={arXiv preprint arXiv:2412.05271},
695
+ year={2024}
696
+ }
697
+ @article{wang2024mpo,
698
+ title={Enhancing the Reasoning Ability of Multimodal Large Language Models via Mixed Preference Optimization},
699
+ 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},
700
+ journal={arXiv preprint arXiv:2411.10442},
701
+ year={2024}
702
+ }
703
+ @article{chen2024far,
704
+ title={How Far Are We to GPT-4V? Closing the Gap to Commercial Multimodal Models with Open-Source Suites},
705
+ 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},
706
+ journal={arXiv preprint arXiv:2404.16821},
707
+ year={2024}
708
+ }
709
+ @inproceedings{chen2024internvl,
710
+ title={Internvl: Scaling up vision foundation models and aligning for generic visual-linguistic tasks},
711
+ 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},
712
+ booktitle={Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition},
713
+ pages={24185--24198},
714
+ year={2024}
715
+ }
716
  ```