lbourdois commited on
Commit
38645ce
·
verified ·
1 Parent(s): 899e067

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