Files changed (1) hide show
  1. README.md +721 -709
README.md CHANGED
@@ -1,709 +1,721 @@
1
- ---
2
- license: mit
3
- pipeline_tag: image-text-to-text
4
- library_name: transformers
5
- base_model:
6
- - OpenGVLab/InternViT-6B-448px-V2_5
7
- - Qwen/Qwen2.5-32B-Instruct
8
- base_model_relation: merge
9
- language:
10
- - multilingual
11
- tags:
12
- - internvl
13
- - custom_code
14
- datasets:
15
- - HuggingFaceFV/finevideo
16
- ---
17
-
18
- # InternVL2_5-38B
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) [\[📜 Mini-InternVL\]](https://arxiv.org/abs/2410.16261) [\[📜 InternVL 2.5\]](https://huggingface.co/papers/2412.05271)
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
- We are excited to introduce **InternVL 2.5**, an advanced multimodal large language model (MLLM) series that builds upon InternVL 2.0, maintaining its core model architecture while introducing significant enhancements in training and testing strategies as well as data quality.
31
-
32
- ![image/png](https://cdn-uploads.huggingface.co/production/uploads/64119264f0f81eb569e0d569/5HDAGOQOZvS1EtI107Ac-.png)
33
-
34
- ## InternVL 2.5 Family
35
-
36
- In the following table, we provide an overview of the InternVL 2.5 series.
37
-
38
- | Model Name | Vision Part | Language Part | HF Link |
39
- | :-------------: | :-------------------------------------------------------------------------------------: | :----------------------------------------------------------------------------: | :---------------------------------------------------------: |
40
- | InternVL2_5-1B | [InternViT-300M-448px-V2_5](https://huggingface.co/OpenGVLab/InternViT-300M-448px-V2_5) | [Qwen2.5-0.5B-Instruct](https://huggingface.co/Qwen/Qwen2.5-0.5B-Instruct) | [🤗 link](https://huggingface.co/OpenGVLab/InternVL2_5-1B) |
41
- | InternVL2_5-2B | [InternViT-300M-448px-V2_5](https://huggingface.co/OpenGVLab/InternViT-300M-448px-V2_5) | [internlm2_5-1_8b-chat](https://huggingface.co/internlm/internlm2_5-1_8b-chat) | [🤗 link](https://huggingface.co/OpenGVLab/InternVL2_5-2B) |
42
- | InternVL2_5-4B | [InternViT-300M-448px-V2_5](https://huggingface.co/OpenGVLab/InternViT-300M-448px-V2_5) | [Qwen2.5-3B-Instruct](https://huggingface.co/Qwen/Qwen2.5-3B-Instruct) | [🤗 link](https://huggingface.co/OpenGVLab/InternVL2_5-4B) |
43
- | InternVL2_5-8B | [InternViT-300M-448px-V2_5](https://huggingface.co/OpenGVLab/InternViT-300M-448px-V2_5) | [internlm2_5-7b-chat](https://huggingface.co/internlm/internlm2_5-7b-chat) | [🤗 link](https://huggingface.co/OpenGVLab/InternVL2_5-8B) |
44
- | InternVL2_5-26B | [InternViT-6B-448px-V2_5](https://huggingface.co/OpenGVLab/InternViT-6B-448px-V2_5) | [internlm2_5-20b-chat](https://huggingface.co/internlm/internlm2_5-20b-chat) | [🤗 link](https://huggingface.co/OpenGVLab/InternVL2_5-26B) |
45
- | InternVL2_5-38B | [InternViT-6B-448px-V2_5](https://huggingface.co/OpenGVLab/InternViT-6B-448px-V2_5) | [Qwen2.5-32B-Instruct](https://huggingface.co/Qwen/Qwen2.5-32B-Instruct) | [🤗 link](https://huggingface.co/OpenGVLab/InternVL2_5-38B) |
46
- | InternVL2_5-78B | [InternViT-6B-448px-V2_5](https://huggingface.co/OpenGVLab/InternViT-6B-448px-V2_5) | [Qwen2.5-72B-Instruct](https://huggingface.co/Qwen/Qwen2.5-72B-Instruct) | [🤗 link](https://huggingface.co/OpenGVLab/InternVL2_5-78B) |
47
-
48
- ## Model Architecture
49
-
50
- As shown in the following figure, InternVL 2.5 retains the same model architecture as 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 2.5 and Qwen 2.5, using a randomly initialized MLP projector.
51
-
52
- ![image/png](https://cdn-uploads.huggingface.co/production/uploads/64119264f0f81eb569e0d569/BiiyXN6NOk0p-3rl3ueyL.png)
53
-
54
- 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.
55
-
56
- ## Training Strategy
57
-
58
- ### Dynamic High-Resolution for Multimodal Data
59
-
60
- In InternVL 2.0 and 2.5, we extend the dynamic high-resolution training approach, enhancing its capabilities to handle multi-image and video datasets.
61
-
62
- ![image/png](https://cdn-uploads.huggingface.co/production/uploads/64119264f0f81eb569e0d569/xoMY6rwRrNxbAGYPNyU8g.png)
63
-
64
- - For single-image datasets, the total number of tiles `n_max` are allocated to a single image for maximum resolution. Visual tokens are enclosed in `<img>` and `</img>` tags.
65
-
66
- - For multi-image datasets, the total number of tiles `n_max` are distributed across all images in a sample. Each image is labeled with auxiliary tags like `Image-1` and enclosed in `<img>` and `</img>` tags.
67
-
68
- - For videos, each frame is resized to 448×448. Frames are labeled with tags like `Frame-1` and enclosed in `<img>` and `</img>` tags, similar to images.
69
-
70
- ### Single Model Training Pipeline
71
-
72
- The training pipeline for a single model in InternVL 2.5 is structured across three stages, designed to enhance the model's visual perception and multimodal capabilities.
73
-
74
- ![image/png](https://cdn-uploads.huggingface.co/production/uploads/64119264f0f81eb569e0d569/5NduZeCPLgPJTFr0RGTq3.png)
75
-
76
- - **Stage 1: MLP Warmup.** In this stage, only the MLP projector is trained while the vision encoder and language model are frozen. A dynamic high-resolution training strategy is applied for better performance, despite increased cost. This phase ensures robust cross-modal alignment and prepares the model for stable multimodal training.
77
-
78
- - **Stage 1.5: ViT Incremental Learning (Optional).** This stage allows incremental training of the vision encoder and MLP projector using the same data as Stage 1. It enhances the encoder’s ability to handle rare domains like multilingual OCR and mathematical charts. Once trained, the encoder can be reused across LLMs without retraining, making this stage optional unless new domains are introduced.
79
-
80
- - **Stage 2: Full Model Instruction Tuning.** The entire model is trained on high-quality multimodal instruction datasets. Strict data quality controls are enforced to prevent degradation of the LLM, as noisy data can cause issues like repetitive or incorrect outputs. After this stage, the training process is complete.
81
-
82
- ### Progressive Scaling Strategy
83
-
84
- We introduce a progressive scaling strategy to align the vision encoder with LLMs efficiently. This approach trains with smaller LLMs first (e.g., 20B) to optimize foundational visual capabilities and cross-modal alignment before transferring the vision encoder to larger LLMs (e.g., 72B) without retraining. This reuse skips intermediate stages for larger models.
85
-
86
- ![image/png](https://cdn-uploads.huggingface.co/production/uploads/64006c09330a45b03605bba3/UoNUyS7ctN5pBxNv9KnzH.png)
87
-
88
- Compared to Qwen2-VL's 1.4 trillion tokens, InternVL2.5-78B uses only 120 billion tokens—less than one-tenth. This strategy minimizes redundancy, maximizes pre-trained component reuse, and enables efficient training for complex vision-language tasks.
89
-
90
- ### Training Enhancements
91
-
92
- To improve real-world adaptability and performance, we introduce two key techniques:
93
-
94
- - **Random JPEG Compression**: Random JPEG compression with quality levels between 75 and 100 is applied as a data augmentation technique. This simulates image degradation from internet sources, enhancing the model's robustness to noisy images.
95
-
96
- - **Loss Reweighting**: To balance the NTP loss across responses of different lengths, we use a reweighting strategy called **square averaging**. This method balances contributions from responses of varying lengths, mitigating biases toward longer or shorter responses.
97
-
98
- ### Data Organization
99
-
100
- #### Dataset Configuration
101
-
102
- In InternVL 2.0 and 2.5, the organization of the training data is controlled by several key parameters to optimize the balance and distribution of datasets during training.
103
-
104
- ![image/png](https://cdn-uploads.huggingface.co/production/uploads/64119264f0f81eb569e0d569/2LJe24b1ua3gjI9gDitVl.png)
105
-
106
- - **Data Augmentation:** JPEG compression is applied conditionally: enabled for image datasets to enhance robustness and disabled for video datasets to maintain consistent frame quality.
107
-
108
- - **Maximum Tile Number:** The parameter `n_max` controls the maximum tiles per dataset. For example, higher values (24–36) are used for multi-image or high-resolution data, lower values (6–12) for standard images, and 1 for videos.
109
-
110
- - **Repeat Factor:** The repeat factor `r` adjusts dataset sampling frequency. Values below 1 reduce a dataset's weight, while values above 1 increase it. This ensures balanced training across tasks and prevents overfitting or underfitting.
111
-
112
- #### Data Filtering Pipeline
113
-
114
- During development, we found that LLMs are highly sensitive to data noise, with even small anomalies—like outliers or repetitive data—causing abnormal behavior during inference. Repetitive generation, especially in long-form or CoT reasoning tasks, proved particularly harmful.
115
-
116
- ![image/png](https://cdn-uploads.huggingface.co/production/uploads/64119264f0f81eb569e0d569/aka8ZRiKF3ajdyZBnNFZI.png)
117
-
118
- To address this challenge and support future research, we designed an efficient data filtering pipeline to remove low-quality samples.
119
-
120
- ![image/png](https://cdn-uploads.huggingface.co/production/uploads/64119264f0f81eb569e0d569/70l1UxnX-Arn0NoOGwpth.png)
121
-
122
- The pipeline includes two modules, for **pure-text data**, three key strategies are used:
123
-
124
- 1. **LLM-Based Quality Scoring**: Each sample is scored (0–10) using a pre-trained LLM with domain-specific prompts. Samples scoring below a threshold (e.g., 7) are removed to ensure high-quality data.
125
- 2. **Repetition Detection**: Repetitive samples are flagged using LLM-based prompts and manually reviewed. Samples scoring below a stricter threshold (e.g., 3) are excluded to avoid repetitive patterns.
126
- 3. **Heuristic Rule-Based Filtering**: Anomalies like abnormal sentence lengths or duplicate lines are detected using rules. Flagged samples undergo manual verification to ensure accuracy before removal.
127
-
128
- For **multimodal data**, two strategies are used:
129
-
130
- 1. **Repetition Detection**: Repetitive samples in non-academic datasets are flagged and manually reviewed to prevent pattern loops. High-quality datasets are exempt from this process.
131
- 2. **Heuristic Rule-Based Filtering**: Similar rules are applied to detect visual anomalies, with flagged data verified manually to maintain integrity.
132
-
133
- #### Training Data
134
-
135
- As shown in the following figure, from InternVL 1.5 to 2.0 and then to 2.5, the fine-tuning data mixture has undergone iterative improvements in scale, quality, and diversity. For more information about the training data, please refer to our technical report.
136
-
137
- ![image/png](https://cdn-uploads.huggingface.co/production/uploads/64119264f0f81eb569e0d569/GaTY9Lde02YzclASMthDa.png)
138
-
139
- ## Evaluation on Multimodal Capability
140
-
141
- ### Multimodal Reasoning and Mathematics
142
-
143
- ![image/png](https://cdn-uploads.huggingface.co/production/uploads/64119264f0f81eb569e0d569/ihFWMRHbF0lpFTkLqnnj1.png)
144
-
145
- ![image/png](https://cdn-uploads.huggingface.co/production/uploads/64119264f0f81eb569e0d569/Nrzq0kjlitjp_jrJCqtwX.png)
146
-
147
- ### OCR, Chart, and Document Understanding
148
-
149
- ![image/png](https://cdn-uploads.huggingface.co/production/uploads/64119264f0f81eb569e0d569/3yCMoLjlbsqY7ZJViGzih.png)
150
-
151
- ### Multi-Image & Real-World Comprehension
152
-
153
- ![image/png](https://cdn-uploads.huggingface.co/production/uploads/64119264f0f81eb569e0d569/DSnalmEyhDVQ9GE0GPCla.png)
154
-
155
- ### Comprehensive Multimodal & Hallucination Evaluation
156
-
157
- ![image/png](https://cdn-uploads.huggingface.co/production/uploads/64119264f0f81eb569e0d569/Z7Raj3TGDiV1H81pDHtoG.png)
158
-
159
- ### Visual Grounding
160
-
161
- ![image/png](https://cdn-uploads.huggingface.co/production/uploads/64119264f0f81eb569e0d569/lPcIrng8MPSg_PM1hpDPt.png)
162
-
163
- ### Multimodal Multilingual Understanding
164
-
165
- ![image/png](https://cdn-uploads.huggingface.co/production/uploads/64119264f0f81eb569e0d569/BPpbAOX36RV8RTnm3j-gs.png)
166
-
167
- ### Video Understanding
168
-
169
- ![image/png](https://cdn-uploads.huggingface.co/production/uploads/64006c09330a45b03605bba3/tcwH-i1qc8H16En-7AZ5M.png)
170
-
171
- ## Evaluation on Language Capability
172
-
173
- Training InternVL 2.0 models led to a decline in pure language capabilities. InternVL 2.5 addresses this by collecting more high-quality open-source data and filtering out low-quality data, achieving better preservation of pure language performance.
174
-
175
- ![image/png](https://cdn-uploads.huggingface.co/production/uploads/64119264f0f81eb569e0d569/mxuSKvSY-kfI8zePpXj6y.png)
176
-
177
- ## Quick Start
178
-
179
- We provide an example code to run `InternVL2_5-38B` using `transformers`.
180
-
181
- > Please use transformers>=4.37.2 to ensure the model works normally.
182
-
183
- ### Model Loading
184
-
185
- #### 16-bit (bf16 / fp16)
186
-
187
- ```python
188
- import torch
189
- from transformers import AutoTokenizer, AutoModel
190
- path = "OpenGVLab/InternVL2_5-38B"
191
- model = AutoModel.from_pretrained(
192
- path,
193
- torch_dtype=torch.bfloat16,
194
- low_cpu_mem_usage=True,
195
- use_flash_attn=True,
196
- trust_remote_code=True).eval().cuda()
197
- ```
198
-
199
- #### BNB 8-bit Quantization
200
-
201
- ```python
202
- import torch
203
- from transformers import AutoTokenizer, AutoModel
204
- path = "OpenGVLab/InternVL2_5-38B"
205
- model = AutoModel.from_pretrained(
206
- path,
207
- torch_dtype=torch.bfloat16,
208
- load_in_8bit=True,
209
- low_cpu_mem_usage=True,
210
- use_flash_attn=True,
211
- trust_remote_code=True).eval()
212
- ```
213
-
214
- #### Multiple GPUs
215
-
216
- 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.
217
-
218
- ```python
219
- import math
220
- import torch
221
- from transformers import AutoTokenizer, AutoModel
222
-
223
- def split_model(model_name):
224
- device_map = {}
225
- world_size = torch.cuda.device_count()
226
- num_layers = {
227
- 'InternVL2_5-1B': 24, 'InternVL2_5-2B': 24, 'InternVL2_5-4B': 36, 'InternVL2_5-8B': 32,
228
- 'InternVL2_5-26B': 48, 'InternVL2_5-38B': 64, 'InternVL2_5-78B': 80}[model_name]
229
- # Since the first GPU will be used for ViT, treat it as half a GPU.
230
- num_layers_per_gpu = math.ceil(num_layers / (world_size - 0.5))
231
- num_layers_per_gpu = [num_layers_per_gpu] * world_size
232
- num_layers_per_gpu[0] = math.ceil(num_layers_per_gpu[0] * 0.5)
233
- layer_cnt = 0
234
- for i, num_layer in enumerate(num_layers_per_gpu):
235
- for j in range(num_layer):
236
- device_map[f'language_model.model.layers.{layer_cnt}'] = i
237
- layer_cnt += 1
238
- device_map['vision_model'] = 0
239
- device_map['mlp1'] = 0
240
- device_map['language_model.model.tok_embeddings'] = 0
241
- device_map['language_model.model.embed_tokens'] = 0
242
- device_map['language_model.output'] = 0
243
- device_map['language_model.model.norm'] = 0
244
- device_map['language_model.model.rotary_emb'] = 0
245
- device_map['language_model.lm_head'] = 0
246
- device_map[f'language_model.model.layers.{num_layers - 1}'] = 0
247
-
248
- return device_map
249
-
250
- path = "OpenGVLab/InternVL2_5-38B"
251
- device_map = split_model('InternVL2_5-38B')
252
- model = AutoModel.from_pretrained(
253
- path,
254
- torch_dtype=torch.bfloat16,
255
- low_cpu_mem_usage=True,
256
- use_flash_attn=True,
257
- trust_remote_code=True,
258
- device_map=device_map).eval()
259
- ```
260
-
261
- ### Inference with Transformers
262
-
263
- ```python
264
- import math
265
- import numpy as np
266
- import torch
267
- import torchvision.transforms as T
268
- from decord import VideoReader, cpu
269
- from PIL import Image
270
- from torchvision.transforms.functional import InterpolationMode
271
- from transformers import AutoModel, AutoTokenizer
272
-
273
- IMAGENET_MEAN = (0.485, 0.456, 0.406)
274
- IMAGENET_STD = (0.229, 0.224, 0.225)
275
-
276
- def build_transform(input_size):
277
- MEAN, STD = IMAGENET_MEAN, IMAGENET_STD
278
- transform = T.Compose([
279
- T.Lambda(lambda img: img.convert('RGB') if img.mode != 'RGB' else img),
280
- T.Resize((input_size, input_size), interpolation=InterpolationMode.BICUBIC),
281
- T.ToTensor(),
282
- T.Normalize(mean=MEAN, std=STD)
283
- ])
284
- return transform
285
-
286
- def find_closest_aspect_ratio(aspect_ratio, target_ratios, width, height, image_size):
287
- best_ratio_diff = float('inf')
288
- best_ratio = (1, 1)
289
- area = width * height
290
- for ratio in target_ratios:
291
- target_aspect_ratio = ratio[0] / ratio[1]
292
- ratio_diff = abs(aspect_ratio - target_aspect_ratio)
293
- if ratio_diff < best_ratio_diff:
294
- best_ratio_diff = ratio_diff
295
- best_ratio = ratio
296
- elif ratio_diff == best_ratio_diff:
297
- if area > 0.5 * image_size * image_size * ratio[0] * ratio[1]:
298
- best_ratio = ratio
299
- return best_ratio
300
-
301
- def dynamic_preprocess(image, min_num=1, max_num=12, image_size=448, use_thumbnail=False):
302
- orig_width, orig_height = image.size
303
- aspect_ratio = orig_width / orig_height
304
-
305
- # calculate the existing image aspect ratio
306
- target_ratios = set(
307
- (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
308
- i * j <= max_num and i * j >= min_num)
309
- target_ratios = sorted(target_ratios, key=lambda x: x[0] * x[1])
310
-
311
- # find the closest aspect ratio to the target
312
- target_aspect_ratio = find_closest_aspect_ratio(
313
- aspect_ratio, target_ratios, orig_width, orig_height, image_size)
314
-
315
- # calculate the target width and height
316
- target_width = image_size * target_aspect_ratio[0]
317
- target_height = image_size * target_aspect_ratio[1]
318
- blocks = target_aspect_ratio[0] * target_aspect_ratio[1]
319
-
320
- # resize the image
321
- resized_img = image.resize((target_width, target_height))
322
- processed_images = []
323
- for i in range(blocks):
324
- box = (
325
- (i % (target_width // image_size)) * image_size,
326
- (i // (target_width // image_size)) * image_size,
327
- ((i % (target_width // image_size)) + 1) * image_size,
328
- ((i // (target_width // image_size)) + 1) * image_size
329
- )
330
- # split the image
331
- split_img = resized_img.crop(box)
332
- processed_images.append(split_img)
333
- assert len(processed_images) == blocks
334
- if use_thumbnail and len(processed_images) != 1:
335
- thumbnail_img = image.resize((image_size, image_size))
336
- processed_images.append(thumbnail_img)
337
- return processed_images
338
-
339
- def load_image(image_file, input_size=448, max_num=12):
340
- image = Image.open(image_file).convert('RGB')
341
- transform = build_transform(input_size=input_size)
342
- images = dynamic_preprocess(image, image_size=input_size, use_thumbnail=True, max_num=max_num)
343
- pixel_values = [transform(image) for image in images]
344
- pixel_values = torch.stack(pixel_values)
345
- return pixel_values
346
-
347
- def split_model(model_name):
348
- device_map = {}
349
- world_size = torch.cuda.device_count()
350
- num_layers = {
351
- 'InternVL2_5-1B': 24, 'InternVL2_5-2B': 24, 'InternVL2_5-4B': 36, 'InternVL2_5-8B': 32,
352
- 'InternVL2_5-26B': 48, 'InternVL2_5-38B': 64, 'InternVL2_5-78B': 80}[model_name]
353
- # Since the first GPU will be used for ViT, treat it as half a GPU.
354
- num_layers_per_gpu = math.ceil(num_layers / (world_size - 0.5))
355
- num_layers_per_gpu = [num_layers_per_gpu] * world_size
356
- num_layers_per_gpu[0] = math.ceil(num_layers_per_gpu[0] * 0.5)
357
- layer_cnt = 0
358
- for i, num_layer in enumerate(num_layers_per_gpu):
359
- for j in range(num_layer):
360
- device_map[f'language_model.model.layers.{layer_cnt}'] = i
361
- layer_cnt += 1
362
- device_map['vision_model'] = 0
363
- device_map['mlp1'] = 0
364
- device_map['language_model.model.tok_embeddings'] = 0
365
- device_map['language_model.model.embed_tokens'] = 0
366
- device_map['language_model.output'] = 0
367
- device_map['language_model.model.norm'] = 0
368
- device_map['language_model.model.rotary_emb'] = 0
369
- device_map['language_model.lm_head'] = 0
370
- device_map[f'language_model.model.layers.{num_layers - 1}'] = 0
371
-
372
- return device_map
373
-
374
- # If you set `load_in_8bit=True`, you will need one 80GB GPUs.
375
- # If you set `load_in_8bit=False`, you will need at least two 80GB GPUs.
376
- path = 'OpenGVLab/InternVL2_5-38B'
377
- device_map = split_model('InternVL2_5-38B')
378
- model = AutoModel.from_pretrained(
379
- path,
380
- torch_dtype=torch.bfloat16,
381
- load_in_8bit=True,
382
- low_cpu_mem_usage=True,
383
- use_flash_attn=True,
384
- trust_remote_code=True,
385
- device_map=device_map).eval()
386
- tokenizer = AutoTokenizer.from_pretrained(path, trust_remote_code=True, use_fast=False)
387
-
388
- # set the max number of tiles in `max_num`
389
- pixel_values = load_image('./examples/image1.jpg', max_num=12).to(torch.bfloat16).cuda()
390
- generation_config = dict(max_new_tokens=1024, do_sample=True)
391
-
392
- # pure-text conversation (纯文本对话)
393
- question = 'Hello, who are you?'
394
- response, history = model.chat(tokenizer, None, question, generation_config, history=None, return_history=True)
395
- print(f'User: {question}\nAssistant: {response}')
396
-
397
- question = 'Can you tell me a story?'
398
- response, history = model.chat(tokenizer, None, question, generation_config, history=history, return_history=True)
399
- print(f'User: {question}\nAssistant: {response}')
400
-
401
- # single-image single-round conversation (单图单轮对话)
402
- question = '<image>\nPlease describe the image shortly.'
403
- response = model.chat(tokenizer, pixel_values, question, generation_config)
404
- print(f'User: {question}\nAssistant: {response}')
405
-
406
- # single-image multi-round conversation (单图多轮对话)
407
- question = '<image>\nPlease describe the image in detail.'
408
- response, history = model.chat(tokenizer, pixel_values, question, generation_config, history=None, return_history=True)
409
- print(f'User: {question}\nAssistant: {response}')
410
-
411
- question = 'Please write a poem according to the image.'
412
- response, history = model.chat(tokenizer, pixel_values, question, generation_config, history=history, return_history=True)
413
- print(f'User: {question}\nAssistant: {response}')
414
-
415
- # multi-image multi-round conversation, combined images (多图多轮对话,拼接图像)
416
- pixel_values1 = load_image('./examples/image1.jpg', max_num=12).to(torch.bfloat16).cuda()
417
- pixel_values2 = load_image('./examples/image2.jpg', max_num=12).to(torch.bfloat16).cuda()
418
- pixel_values = torch.cat((pixel_values1, pixel_values2), dim=0)
419
-
420
- question = '<image>\nDescribe the two images in detail.'
421
- response, history = model.chat(tokenizer, pixel_values, question, generation_config,
422
- history=None, return_history=True)
423
- print(f'User: {question}\nAssistant: {response}')
424
-
425
- question = 'What are the similarities and differences between these two images.'
426
- response, history = model.chat(tokenizer, pixel_values, question, generation_config,
427
- history=history, return_history=True)
428
- print(f'User: {question}\nAssistant: {response}')
429
-
430
- # multi-image multi-round conversation, separate images (多图多轮对话,独立图像)
431
- pixel_values1 = load_image('./examples/image1.jpg', max_num=12).to(torch.bfloat16).cuda()
432
- pixel_values2 = load_image('./examples/image2.jpg', max_num=12).to(torch.bfloat16).cuda()
433
- pixel_values = torch.cat((pixel_values1, pixel_values2), dim=0)
434
- num_patches_list = [pixel_values1.size(0), pixel_values2.size(0)]
435
-
436
- question = 'Image-1: <image>\nImage-2: <image>\nDescribe the two images in detail.'
437
- response, history = model.chat(tokenizer, pixel_values, question, generation_config,
438
- num_patches_list=num_patches_list,
439
- history=None, return_history=True)
440
- print(f'User: {question}\nAssistant: {response}')
441
-
442
- question = 'What are the similarities and differences between these two images.'
443
- response, history = model.chat(tokenizer, pixel_values, question, generation_config,
444
- num_patches_list=num_patches_list,
445
- history=history, return_history=True)
446
- print(f'User: {question}\nAssistant: {response}')
447
-
448
- # batch inference, single image per sample (单图批处理)
449
- pixel_values1 = load_image('./examples/image1.jpg', max_num=12).to(torch.bfloat16).cuda()
450
- pixel_values2 = load_image('./examples/image2.jpg', max_num=12).to(torch.bfloat16).cuda()
451
- num_patches_list = [pixel_values1.size(0), pixel_values2.size(0)]
452
- pixel_values = torch.cat((pixel_values1, pixel_values2), dim=0)
453
-
454
- questions = ['<image>\nDescribe the image in detail.'] * len(num_patches_list)
455
- responses = model.batch_chat(tokenizer, pixel_values,
456
- num_patches_list=num_patches_list,
457
- questions=questions,
458
- generation_config=generation_config)
459
- for question, response in zip(questions, responses):
460
- print(f'User: {question}\nAssistant: {response}')
461
-
462
- # video multi-round conversation (视频多轮对话)
463
- def get_index(bound, fps, max_frame, first_idx=0, num_segments=32):
464
- if bound:
465
- start, end = bound[0], bound[1]
466
- else:
467
- start, end = -100000, 100000
468
- start_idx = max(first_idx, round(start * fps))
469
- end_idx = min(round(end * fps), max_frame)
470
- seg_size = float(end_idx - start_idx) / num_segments
471
- frame_indices = np.array([
472
- int(start_idx + (seg_size / 2) + np.round(seg_size * idx))
473
- for idx in range(num_segments)
474
- ])
475
- return frame_indices
476
-
477
- def load_video(video_path, bound=None, input_size=448, max_num=1, num_segments=32):
478
- vr = VideoReader(video_path, ctx=cpu(0), num_threads=1)
479
- max_frame = len(vr) - 1
480
- fps = float(vr.get_avg_fps())
481
-
482
- pixel_values_list, num_patches_list = [], []
483
- transform = build_transform(input_size=input_size)
484
- frame_indices = get_index(bound, fps, max_frame, first_idx=0, num_segments=num_segments)
485
- for frame_index in frame_indices:
486
- img = Image.fromarray(vr[frame_index].asnumpy()).convert('RGB')
487
- img = dynamic_preprocess(img, image_size=input_size, use_thumbnail=True, max_num=max_num)
488
- pixel_values = [transform(tile) for tile in img]
489
- pixel_values = torch.stack(pixel_values)
490
- num_patches_list.append(pixel_values.shape[0])
491
- pixel_values_list.append(pixel_values)
492
- pixel_values = torch.cat(pixel_values_list)
493
- return pixel_values, num_patches_list
494
-
495
- video_path = './examples/red-panda.mp4'
496
- pixel_values, num_patches_list = load_video(video_path, num_segments=8, max_num=1)
497
- pixel_values = pixel_values.to(torch.bfloat16).cuda()
498
- video_prefix = ''.join([f'Frame{i+1}: <image>\n' for i in range(len(num_patches_list))])
499
- question = video_prefix + 'What is the red panda doing?'
500
- # Frame1: <image>\nFrame2: <image>\n...\nFrame8: <image>\n{question}
501
- response, history = model.chat(tokenizer, pixel_values, question, generation_config,
502
- num_patches_list=num_patches_list, history=None, return_history=True)
503
- print(f'User: {question}\nAssistant: {response}')
504
-
505
- question = 'Describe this video in detail.'
506
- response, history = model.chat(tokenizer, pixel_values, question, generation_config,
507
- num_patches_list=num_patches_list, history=history, return_history=True)
508
- print(f'User: {question}\nAssistant: {response}')
509
- ```
510
-
511
- #### Streaming Output
512
-
513
- Besides this method, you can also use the following code to get streamed output.
514
-
515
- ```python
516
- from transformers import TextIteratorStreamer
517
- from threading import Thread
518
-
519
- # Initialize the streamer
520
- streamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True, timeout=10)
521
- # Define the generation configuration
522
- generation_config = dict(max_new_tokens=1024, do_sample=False, streamer=streamer)
523
- # Start the model chat in a separate thread
524
- thread = Thread(target=model.chat, kwargs=dict(
525
- tokenizer=tokenizer, pixel_values=pixel_values, question=question,
526
- history=None, return_history=False, generation_config=generation_config,
527
- ))
528
- thread.start()
529
-
530
- # Initialize an empty string to store the generated text
531
- generated_text = ''
532
- # Loop through the streamer to get the new text as it is generated
533
- for new_text in streamer:
534
- if new_text == model.conv_template.sep:
535
- break
536
- generated_text += new_text
537
- print(new_text, end='', flush=True) # Print each new chunk of generated text on the same line
538
- ```
539
-
540
- ## Finetune
541
-
542
- 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.
543
-
544
- ## Deployment
545
-
546
- ### LMDeploy
547
-
548
- LMDeploy is a toolkit for compressing, deploying, and serving LLMs & VLMs.
549
-
550
- ```sh
551
- pip install lmdeploy>=0.6.4
552
- ```
553
-
554
- 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.
555
-
556
- #### A 'Hello, world' Example
557
-
558
- ```python
559
- from lmdeploy import pipeline, TurbomindEngineConfig
560
- from lmdeploy.vl import load_image
561
-
562
- model = 'OpenGVLab/InternVL2_5-38B'
563
- image = load_image('https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/tests/data/tiger.jpeg')
564
- pipe = pipeline(model, backend_config=TurbomindEngineConfig(session_len=8192, tp=2))
565
- response = pipe(('describe this image', image))
566
- print(response.text)
567
- ```
568
-
569
- If `ImportError` occurs while executing this case, please install the required dependency packages as prompted.
570
-
571
- #### Multi-images Inference
572
-
573
- 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.
574
-
575
- ```python
576
- from lmdeploy import pipeline, TurbomindEngineConfig
577
- from lmdeploy.vl import load_image
578
- from lmdeploy.vl.constants import IMAGE_TOKEN
579
-
580
- model = 'OpenGVLab/InternVL2_5-38B'
581
- pipe = pipeline(model, backend_config=TurbomindEngineConfig(session_len=8192, tp=2))
582
-
583
- image_urls=[
584
- 'https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/human-pose.jpg',
585
- 'https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/det.jpg'
586
- ]
587
-
588
- images = [load_image(img_url) for img_url in image_urls]
589
- # Numbering images improves multi-image conversations
590
- response = pipe((f'Image-1: {IMAGE_TOKEN}\nImage-2: {IMAGE_TOKEN}\ndescribe these two images', images))
591
- print(response.text)
592
- ```
593
-
594
- #### Batch Prompts Inference
595
-
596
- Conducting inference with batch prompts is quite straightforward; just place them within a list structure:
597
-
598
- ```python
599
- from lmdeploy import pipeline, TurbomindEngineConfig
600
- from lmdeploy.vl import load_image
601
-
602
- model = 'OpenGVLab/InternVL2_5-38B'
603
- pipe = pipeline(model, backend_config=TurbomindEngineConfig(session_len=8192, tp=2))
604
-
605
- image_urls=[
606
- "https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/human-pose.jpg",
607
- "https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/det.jpg"
608
- ]
609
- prompts = [('describe this image', load_image(img_url)) for img_url in image_urls]
610
- response = pipe(prompts)
611
- print(response)
612
- ```
613
-
614
- #### Multi-turn Conversation
615
-
616
- 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.
617
-
618
- ```python
619
- from lmdeploy import pipeline, TurbomindEngineConfig, GenerationConfig
620
- from lmdeploy.vl import load_image
621
-
622
- model = 'OpenGVLab/InternVL2_5-38B'
623
- pipe = pipeline(model, backend_config=TurbomindEngineConfig(session_len=8192, tp=2))
624
-
625
- image = load_image('https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/human-pose.jpg')
626
- gen_config = GenerationConfig(top_k=40, top_p=0.8, temperature=0.8)
627
- sess = pipe.chat(('describe this image', image), gen_config=gen_config)
628
- print(sess.response.text)
629
- sess = pipe.chat('What is the woman doing?', session=sess, gen_config=gen_config)
630
- print(sess.response.text)
631
- ```
632
-
633
- #### Service
634
-
635
- 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:
636
-
637
- ```shell
638
- lmdeploy serve api_server OpenGVLab/InternVL2_5-38B --server-port 23333 --tp 2
639
- ```
640
-
641
- To use the OpenAI-style interface, you need to install OpenAI:
642
-
643
- ```shell
644
- pip install openai
645
- ```
646
-
647
- Then, use the code below to make the API call:
648
-
649
- ```python
650
- from openai import OpenAI
651
-
652
- client = OpenAI(api_key='YOUR_API_KEY', base_url='http://0.0.0.0:23333/v1')
653
- model_name = client.models.list().data[0].id
654
- response = client.chat.completions.create(
655
- model=model_name,
656
- messages=[{
657
- 'role':
658
- 'user',
659
- 'content': [{
660
- 'type': 'text',
661
- 'text': 'describe this image',
662
- }, {
663
- 'type': 'image_url',
664
- 'image_url': {
665
- 'url':
666
- 'https://modelscope.oss-cn-beijing.aliyuncs.com/resource/tiger.jpeg',
667
- },
668
- }],
669
- }],
670
- temperature=0.8,
671
- top_p=0.8)
672
- print(response)
673
- ```
674
-
675
- ## License
676
-
677
- This project is released under the MIT License. This project uses the pre-trained Qwen2.5-32B-Instruct as a component, which is licensed under the Apache License 2.0.
678
-
679
- ## Citation
680
-
681
- If you find this project useful in your research, please consider citing:
682
-
683
- ```BibTeX
684
- @article{chen2024expanding,
685
- title={Expanding Performance Boundaries of Open-Source Multimodal Models with Model, Data, and Test-Time Scaling},
686
- 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},
687
- journal={arXiv preprint arXiv:2412.05271},
688
- year={2024}
689
- }
690
- @article{gao2024mini,
691
- title={Mini-internvl: A flexible-transfer pocket multimodal model with 5\% parameters and 90\% performance},
692
- author={Gao, Zhangwei and Chen, Zhe and Cui, Erfei and Ren, Yiming and Wang, Weiyun and Zhu, Jinguo and Tian, Hao and Ye, Shenglong and He, Junjun and Zhu, Xizhou and others},
693
- journal={arXiv preprint arXiv:2410.16261},
694
- year={2024}
695
- }
696
- @article{chen2024far,
697
- title={How Far Are We to GPT-4V? Closing the Gap to Commercial Multimodal Models with Open-Source Suites},
698
- 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},
699
- journal={arXiv preprint arXiv:2404.16821},
700
- year={2024}
701
- }
702
- @inproceedings{chen2024internvl,
703
- title={Internvl: Scaling up vision foundation models and aligning for generic visual-linguistic tasks},
704
- 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},
705
- booktitle={Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition},
706
- pages={24185--24198},
707
- year={2024}
708
- }
709
- ```
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: mit
3
+ pipeline_tag: image-text-to-text
4
+ library_name: transformers
5
+ base_model:
6
+ - OpenGVLab/InternViT-6B-448px-V2_5
7
+ - Qwen/Qwen2.5-32B-Instruct
8
+ base_model_relation: merge
9
+ language:
10
+ - zho
11
+ - eng
12
+ - fra
13
+ - spa
14
+ - por
15
+ - deu
16
+ - ita
17
+ - rus
18
+ - jpn
19
+ - kor
20
+ - vie
21
+ - tha
22
+ - ara
23
+ tags:
24
+ - internvl
25
+ - custom_code
26
+ datasets:
27
+ - HuggingFaceFV/finevideo
28
+ ---
29
+
30
+ # InternVL2_5-38B
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) [\[📜 Mini-InternVL\]](https://arxiv.org/abs/2410.16261) [\[📜 InternVL 2.5\]](https://huggingface.co/papers/2412.05271)
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
+ We are excited to introduce **InternVL 2.5**, an advanced multimodal large language model (MLLM) series that builds upon InternVL 2.0, maintaining its core model architecture while introducing significant enhancements in training and testing strategies as well as data quality.
43
+
44
+ ![image/png](https://cdn-uploads.huggingface.co/production/uploads/64119264f0f81eb569e0d569/5HDAGOQOZvS1EtI107Ac-.png)
45
+
46
+ ## InternVL 2.5 Family
47
+
48
+ In the following table, we provide an overview of the InternVL 2.5 series.
49
+
50
+ | Model Name | Vision Part | Language Part | HF Link |
51
+ | :-------------: | :-------------------------------------------------------------------------------------: | :----------------------------------------------------------------------------: | :---------------------------------------------------------: |
52
+ | InternVL2_5-1B | [InternViT-300M-448px-V2_5](https://huggingface.co/OpenGVLab/InternViT-300M-448px-V2_5) | [Qwen2.5-0.5B-Instruct](https://huggingface.co/Qwen/Qwen2.5-0.5B-Instruct) | [🤗 link](https://huggingface.co/OpenGVLab/InternVL2_5-1B) |
53
+ | InternVL2_5-2B | [InternViT-300M-448px-V2_5](https://huggingface.co/OpenGVLab/InternViT-300M-448px-V2_5) | [internlm2_5-1_8b-chat](https://huggingface.co/internlm/internlm2_5-1_8b-chat) | [🤗 link](https://huggingface.co/OpenGVLab/InternVL2_5-2B) |
54
+ | InternVL2_5-4B | [InternViT-300M-448px-V2_5](https://huggingface.co/OpenGVLab/InternViT-300M-448px-V2_5) | [Qwen2.5-3B-Instruct](https://huggingface.co/Qwen/Qwen2.5-3B-Instruct) | [🤗 link](https://huggingface.co/OpenGVLab/InternVL2_5-4B) |
55
+ | InternVL2_5-8B | [InternViT-300M-448px-V2_5](https://huggingface.co/OpenGVLab/InternViT-300M-448px-V2_5) | [internlm2_5-7b-chat](https://huggingface.co/internlm/internlm2_5-7b-chat) | [🤗 link](https://huggingface.co/OpenGVLab/InternVL2_5-8B) |
56
+ | InternVL2_5-26B | [InternViT-6B-448px-V2_5](https://huggingface.co/OpenGVLab/InternViT-6B-448px-V2_5) | [internlm2_5-20b-chat](https://huggingface.co/internlm/internlm2_5-20b-chat) | [🤗 link](https://huggingface.co/OpenGVLab/InternVL2_5-26B) |
57
+ | InternVL2_5-38B | [InternViT-6B-448px-V2_5](https://huggingface.co/OpenGVLab/InternViT-6B-448px-V2_5) | [Qwen2.5-32B-Instruct](https://huggingface.co/Qwen/Qwen2.5-32B-Instruct) | [🤗 link](https://huggingface.co/OpenGVLab/InternVL2_5-38B) |
58
+ | InternVL2_5-78B | [InternViT-6B-448px-V2_5](https://huggingface.co/OpenGVLab/InternViT-6B-448px-V2_5) | [Qwen2.5-72B-Instruct](https://huggingface.co/Qwen/Qwen2.5-72B-Instruct) | [🤗 link](https://huggingface.co/OpenGVLab/InternVL2_5-78B) |
59
+
60
+ ## Model Architecture
61
+
62
+ As shown in the following figure, InternVL 2.5 retains the same model architecture as 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 2.5 and Qwen 2.5, using a randomly initialized MLP projector.
63
+
64
+ ![image/png](https://cdn-uploads.huggingface.co/production/uploads/64119264f0f81eb569e0d569/BiiyXN6NOk0p-3rl3ueyL.png)
65
+
66
+ 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.
67
+
68
+ ## Training Strategy
69
+
70
+ ### Dynamic High-Resolution for Multimodal Data
71
+
72
+ In InternVL 2.0 and 2.5, we extend the dynamic high-resolution training approach, enhancing its capabilities to handle multi-image and video datasets.
73
+
74
+ ![image/png](https://cdn-uploads.huggingface.co/production/uploads/64119264f0f81eb569e0d569/xoMY6rwRrNxbAGYPNyU8g.png)
75
+
76
+ - For single-image datasets, the total number of tiles `n_max` are allocated to a single image for maximum resolution. Visual tokens are enclosed in `<img>` and `</img>` tags.
77
+
78
+ - For multi-image datasets, the total number of tiles `n_max` are distributed across all images in a sample. Each image is labeled with auxiliary tags like `Image-1` and enclosed in `<img>` and `</img>` tags.
79
+
80
+ - For videos, each frame is resized to 448×448. Frames are labeled with tags like `Frame-1` and enclosed in `<img>` and `</img>` tags, similar to images.
81
+
82
+ ### Single Model Training Pipeline
83
+
84
+ The training pipeline for a single model in InternVL 2.5 is structured across three stages, designed to enhance the model's visual perception and multimodal capabilities.
85
+
86
+ ![image/png](https://cdn-uploads.huggingface.co/production/uploads/64119264f0f81eb569e0d569/5NduZeCPLgPJTFr0RGTq3.png)
87
+
88
+ - **Stage 1: MLP Warmup.** In this stage, only the MLP projector is trained while the vision encoder and language model are frozen. A dynamic high-resolution training strategy is applied for better performance, despite increased cost. This phase ensures robust cross-modal alignment and prepares the model for stable multimodal training.
89
+
90
+ - **Stage 1.5: ViT Incremental Learning (Optional).** This stage allows incremental training of the vision encoder and MLP projector using the same data as Stage 1. It enhances the encoder’s ability to handle rare domains like multilingual OCR and mathematical charts. Once trained, the encoder can be reused across LLMs without retraining, making this stage optional unless new domains are introduced.
91
+
92
+ - **Stage 2: Full Model Instruction Tuning.** The entire model is trained on high-quality multimodal instruction datasets. Strict data quality controls are enforced to prevent degradation of the LLM, as noisy data can cause issues like repetitive or incorrect outputs. After this stage, the training process is complete.
93
+
94
+ ### Progressive Scaling Strategy
95
+
96
+ We introduce a progressive scaling strategy to align the vision encoder with LLMs efficiently. This approach trains with smaller LLMs first (e.g., 20B) to optimize foundational visual capabilities and cross-modal alignment before transferring the vision encoder to larger LLMs (e.g., 72B) without retraining. This reuse skips intermediate stages for larger models.
97
+
98
+ ![image/png](https://cdn-uploads.huggingface.co/production/uploads/64006c09330a45b03605bba3/UoNUyS7ctN5pBxNv9KnzH.png)
99
+
100
+ Compared to Qwen2-VL's 1.4 trillion tokens, InternVL2.5-78B uses only 120 billion tokens—less than one-tenth. This strategy minimizes redundancy, maximizes pre-trained component reuse, and enables efficient training for complex vision-language tasks.
101
+
102
+ ### Training Enhancements
103
+
104
+ To improve real-world adaptability and performance, we introduce two key techniques:
105
+
106
+ - **Random JPEG Compression**: Random JPEG compression with quality levels between 75 and 100 is applied as a data augmentation technique. This simulates image degradation from internet sources, enhancing the model's robustness to noisy images.
107
+
108
+ - **Loss Reweighting**: To balance the NTP loss across responses of different lengths, we use a reweighting strategy called **square averaging**. This method balances contributions from responses of varying lengths, mitigating biases toward longer or shorter responses.
109
+
110
+ ### Data Organization
111
+
112
+ #### Dataset Configuration
113
+
114
+ In InternVL 2.0 and 2.5, the organization of the training data is controlled by several key parameters to optimize the balance and distribution of datasets during training.
115
+
116
+ ![image/png](https://cdn-uploads.huggingface.co/production/uploads/64119264f0f81eb569e0d569/2LJe24b1ua3gjI9gDitVl.png)
117
+
118
+ - **Data Augmentation:** JPEG compression is applied conditionally: enabled for image datasets to enhance robustness and disabled for video datasets to maintain consistent frame quality.
119
+
120
+ - **Maximum Tile Number:** The parameter `n_max` controls the maximum tiles per dataset. For example, higher values (24–36) are used for multi-image or high-resolution data, lower values (6–12) for standard images, and 1 for videos.
121
+
122
+ - **Repeat Factor:** The repeat factor `r` adjusts dataset sampling frequency. Values below 1 reduce a dataset's weight, while values above 1 increase it. This ensures balanced training across tasks and prevents overfitting or underfitting.
123
+
124
+ #### Data Filtering Pipeline
125
+
126
+ During development, we found that LLMs are highly sensitive to data noise, with even small anomalies—like outliers or repetitive data—causing abnormal behavior during inference. Repetitive generation, especially in long-form or CoT reasoning tasks, proved particularly harmful.
127
+
128
+ ![image/png](https://cdn-uploads.huggingface.co/production/uploads/64119264f0f81eb569e0d569/aka8ZRiKF3ajdyZBnNFZI.png)
129
+
130
+ To address this challenge and support future research, we designed an efficient data filtering pipeline to remove low-quality samples.
131
+
132
+ ![image/png](https://cdn-uploads.huggingface.co/production/uploads/64119264f0f81eb569e0d569/70l1UxnX-Arn0NoOGwpth.png)
133
+
134
+ The pipeline includes two modules, for **pure-text data**, three key strategies are used:
135
+
136
+ 1. **LLM-Based Quality Scoring**: Each sample is scored (0–10) using a pre-trained LLM with domain-specific prompts. Samples scoring below a threshold (e.g., 7) are removed to ensure high-quality data.
137
+ 2. **Repetition Detection**: Repetitive samples are flagged using LLM-based prompts and manually reviewed. Samples scoring below a stricter threshold (e.g., 3) are excluded to avoid repetitive patterns.
138
+ 3. **Heuristic Rule-Based Filtering**: Anomalies like abnormal sentence lengths or duplicate lines are detected using rules. Flagged samples undergo manual verification to ensure accuracy before removal.
139
+
140
+ For **multimodal data**, two strategies are used:
141
+
142
+ 1. **Repetition Detection**: Repetitive samples in non-academic datasets are flagged and manually reviewed to prevent pattern loops. High-quality datasets are exempt from this process.
143
+ 2. **Heuristic Rule-Based Filtering**: Similar rules are applied to detect visual anomalies, with flagged data verified manually to maintain integrity.
144
+
145
+ #### Training Data
146
+
147
+ As shown in the following figure, from InternVL 1.5 to 2.0 and then to 2.5, the fine-tuning data mixture has undergone iterative improvements in scale, quality, and diversity. For more information about the training data, please refer to our technical report.
148
+
149
+ ![image/png](https://cdn-uploads.huggingface.co/production/uploads/64119264f0f81eb569e0d569/GaTY9Lde02YzclASMthDa.png)
150
+
151
+ ## Evaluation on Multimodal Capability
152
+
153
+ ### Multimodal Reasoning and Mathematics
154
+
155
+ ![image/png](https://cdn-uploads.huggingface.co/production/uploads/64119264f0f81eb569e0d569/ihFWMRHbF0lpFTkLqnnj1.png)
156
+
157
+ ![image/png](https://cdn-uploads.huggingface.co/production/uploads/64119264f0f81eb569e0d569/Nrzq0kjlitjp_jrJCqtwX.png)
158
+
159
+ ### OCR, Chart, and Document Understanding
160
+
161
+ ![image/png](https://cdn-uploads.huggingface.co/production/uploads/64119264f0f81eb569e0d569/3yCMoLjlbsqY7ZJViGzih.png)
162
+
163
+ ### Multi-Image & Real-World Comprehension
164
+
165
+ ![image/png](https://cdn-uploads.huggingface.co/production/uploads/64119264f0f81eb569e0d569/DSnalmEyhDVQ9GE0GPCla.png)
166
+
167
+ ### Comprehensive Multimodal & Hallucination Evaluation
168
+
169
+ ![image/png](https://cdn-uploads.huggingface.co/production/uploads/64119264f0f81eb569e0d569/Z7Raj3TGDiV1H81pDHtoG.png)
170
+
171
+ ### Visual Grounding
172
+
173
+ ![image/png](https://cdn-uploads.huggingface.co/production/uploads/64119264f0f81eb569e0d569/lPcIrng8MPSg_PM1hpDPt.png)
174
+
175
+ ### Multimodal Multilingual Understanding
176
+
177
+ ![image/png](https://cdn-uploads.huggingface.co/production/uploads/64119264f0f81eb569e0d569/BPpbAOX36RV8RTnm3j-gs.png)
178
+
179
+ ### Video Understanding
180
+
181
+ ![image/png](https://cdn-uploads.huggingface.co/production/uploads/64006c09330a45b03605bba3/tcwH-i1qc8H16En-7AZ5M.png)
182
+
183
+ ## Evaluation on Language Capability
184
+
185
+ Training InternVL 2.0 models led to a decline in pure language capabilities. InternVL 2.5 addresses this by collecting more high-quality open-source data and filtering out low-quality data, achieving better preservation of pure language performance.
186
+
187
+ ![image/png](https://cdn-uploads.huggingface.co/production/uploads/64119264f0f81eb569e0d569/mxuSKvSY-kfI8zePpXj6y.png)
188
+
189
+ ## Quick Start
190
+
191
+ We provide an example code to run `InternVL2_5-38B` using `transformers`.
192
+
193
+ > Please use transformers>=4.37.2 to ensure the model works normally.
194
+
195
+ ### Model Loading
196
+
197
+ #### 16-bit (bf16 / fp16)
198
+
199
+ ```python
200
+ import torch
201
+ from transformers import AutoTokenizer, AutoModel
202
+ path = "OpenGVLab/InternVL2_5-38B"
203
+ model = AutoModel.from_pretrained(
204
+ path,
205
+ torch_dtype=torch.bfloat16,
206
+ low_cpu_mem_usage=True,
207
+ use_flash_attn=True,
208
+ trust_remote_code=True).eval().cuda()
209
+ ```
210
+
211
+ #### BNB 8-bit Quantization
212
+
213
+ ```python
214
+ import torch
215
+ from transformers import AutoTokenizer, AutoModel
216
+ path = "OpenGVLab/InternVL2_5-38B"
217
+ model = AutoModel.from_pretrained(
218
+ path,
219
+ torch_dtype=torch.bfloat16,
220
+ load_in_8bit=True,
221
+ low_cpu_mem_usage=True,
222
+ use_flash_attn=True,
223
+ trust_remote_code=True).eval()
224
+ ```
225
+
226
+ #### Multiple GPUs
227
+
228
+ 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.
229
+
230
+ ```python
231
+ import math
232
+ import torch
233
+ from transformers import AutoTokenizer, AutoModel
234
+
235
+ def split_model(model_name):
236
+ device_map = {}
237
+ world_size = torch.cuda.device_count()
238
+ num_layers = {
239
+ 'InternVL2_5-1B': 24, 'InternVL2_5-2B': 24, 'InternVL2_5-4B': 36, 'InternVL2_5-8B': 32,
240
+ 'InternVL2_5-26B': 48, 'InternVL2_5-38B': 64, 'InternVL2_5-78B': 80}[model_name]
241
+ # Since the first GPU will be used for ViT, treat it as half a GPU.
242
+ num_layers_per_gpu = math.ceil(num_layers / (world_size - 0.5))
243
+ num_layers_per_gpu = [num_layers_per_gpu] * world_size
244
+ num_layers_per_gpu[0] = math.ceil(num_layers_per_gpu[0] * 0.5)
245
+ layer_cnt = 0
246
+ for i, num_layer in enumerate(num_layers_per_gpu):
247
+ for j in range(num_layer):
248
+ device_map[f'language_model.model.layers.{layer_cnt}'] = i
249
+ layer_cnt += 1
250
+ device_map['vision_model'] = 0
251
+ device_map['mlp1'] = 0
252
+ device_map['language_model.model.tok_embeddings'] = 0
253
+ device_map['language_model.model.embed_tokens'] = 0
254
+ device_map['language_model.output'] = 0
255
+ device_map['language_model.model.norm'] = 0
256
+ device_map['language_model.model.rotary_emb'] = 0
257
+ device_map['language_model.lm_head'] = 0
258
+ device_map[f'language_model.model.layers.{num_layers - 1}'] = 0
259
+
260
+ return device_map
261
+
262
+ path = "OpenGVLab/InternVL2_5-38B"
263
+ device_map = split_model('InternVL2_5-38B')
264
+ model = AutoModel.from_pretrained(
265
+ path,
266
+ torch_dtype=torch.bfloat16,
267
+ low_cpu_mem_usage=True,
268
+ use_flash_attn=True,
269
+ trust_remote_code=True,
270
+ device_map=device_map).eval()
271
+ ```
272
+
273
+ ### Inference with Transformers
274
+
275
+ ```python
276
+ import math
277
+ import numpy as np
278
+ import torch
279
+ import torchvision.transforms as T
280
+ from decord import VideoReader, cpu
281
+ from PIL import Image
282
+ from torchvision.transforms.functional import InterpolationMode
283
+ from transformers import AutoModel, AutoTokenizer
284
+
285
+ IMAGENET_MEAN = (0.485, 0.456, 0.406)
286
+ IMAGENET_STD = (0.229, 0.224, 0.225)
287
+
288
+ def build_transform(input_size):
289
+ MEAN, STD = IMAGENET_MEAN, IMAGENET_STD
290
+ transform = T.Compose([
291
+ T.Lambda(lambda img: img.convert('RGB') if img.mode != 'RGB' else img),
292
+ T.Resize((input_size, input_size), interpolation=InterpolationMode.BICUBIC),
293
+ T.ToTensor(),
294
+ T.Normalize(mean=MEAN, std=STD)
295
+ ])
296
+ return transform
297
+
298
+ def find_closest_aspect_ratio(aspect_ratio, target_ratios, width, height, image_size):
299
+ best_ratio_diff = float('inf')
300
+ best_ratio = (1, 1)
301
+ area = width * height
302
+ for ratio in target_ratios:
303
+ target_aspect_ratio = ratio[0] / ratio[1]
304
+ ratio_diff = abs(aspect_ratio - target_aspect_ratio)
305
+ if ratio_diff < best_ratio_diff:
306
+ best_ratio_diff = ratio_diff
307
+ best_ratio = ratio
308
+ elif ratio_diff == best_ratio_diff:
309
+ if area > 0.5 * image_size * image_size * ratio[0] * ratio[1]:
310
+ best_ratio = ratio
311
+ return best_ratio
312
+
313
+ def dynamic_preprocess(image, min_num=1, max_num=12, image_size=448, use_thumbnail=False):
314
+ orig_width, orig_height = image.size
315
+ aspect_ratio = orig_width / orig_height
316
+
317
+ # calculate the existing image aspect ratio
318
+ target_ratios = set(
319
+ (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
320
+ i * j <= max_num and i * j >= min_num)
321
+ target_ratios = sorted(target_ratios, key=lambda x: x[0] * x[1])
322
+
323
+ # find the closest aspect ratio to the target
324
+ target_aspect_ratio = find_closest_aspect_ratio(
325
+ aspect_ratio, target_ratios, orig_width, orig_height, image_size)
326
+
327
+ # calculate the target width and height
328
+ target_width = image_size * target_aspect_ratio[0]
329
+ target_height = image_size * target_aspect_ratio[1]
330
+ blocks = target_aspect_ratio[0] * target_aspect_ratio[1]
331
+
332
+ # resize the image
333
+ resized_img = image.resize((target_width, target_height))
334
+ processed_images = []
335
+ for i in range(blocks):
336
+ box = (
337
+ (i % (target_width // image_size)) * image_size,
338
+ (i // (target_width // image_size)) * image_size,
339
+ ((i % (target_width // image_size)) + 1) * image_size,
340
+ ((i // (target_width // image_size)) + 1) * image_size
341
+ )
342
+ # split the image
343
+ split_img = resized_img.crop(box)
344
+ processed_images.append(split_img)
345
+ assert len(processed_images) == blocks
346
+ if use_thumbnail and len(processed_images) != 1:
347
+ thumbnail_img = image.resize((image_size, image_size))
348
+ processed_images.append(thumbnail_img)
349
+ return processed_images
350
+
351
+ def load_image(image_file, input_size=448, max_num=12):
352
+ image = Image.open(image_file).convert('RGB')
353
+ transform = build_transform(input_size=input_size)
354
+ images = dynamic_preprocess(image, image_size=input_size, use_thumbnail=True, max_num=max_num)
355
+ pixel_values = [transform(image) for image in images]
356
+ pixel_values = torch.stack(pixel_values)
357
+ return pixel_values
358
+
359
+ def split_model(model_name):
360
+ device_map = {}
361
+ world_size = torch.cuda.device_count()
362
+ num_layers = {
363
+ 'InternVL2_5-1B': 24, 'InternVL2_5-2B': 24, 'InternVL2_5-4B': 36, 'InternVL2_5-8B': 32,
364
+ 'InternVL2_5-26B': 48, 'InternVL2_5-38B': 64, 'InternVL2_5-78B': 80}[model_name]
365
+ # Since the first GPU will be used for ViT, treat it as half a GPU.
366
+ num_layers_per_gpu = math.ceil(num_layers / (world_size - 0.5))
367
+ num_layers_per_gpu = [num_layers_per_gpu] * world_size
368
+ num_layers_per_gpu[0] = math.ceil(num_layers_per_gpu[0] * 0.5)
369
+ layer_cnt = 0
370
+ for i, num_layer in enumerate(num_layers_per_gpu):
371
+ for j in range(num_layer):
372
+ device_map[f'language_model.model.layers.{layer_cnt}'] = i
373
+ layer_cnt += 1
374
+ device_map['vision_model'] = 0
375
+ device_map['mlp1'] = 0
376
+ device_map['language_model.model.tok_embeddings'] = 0
377
+ device_map['language_model.model.embed_tokens'] = 0
378
+ device_map['language_model.output'] = 0
379
+ device_map['language_model.model.norm'] = 0
380
+ device_map['language_model.model.rotary_emb'] = 0
381
+ device_map['language_model.lm_head'] = 0
382
+ device_map[f'language_model.model.layers.{num_layers - 1}'] = 0
383
+
384
+ return device_map
385
+
386
+ # If you set `load_in_8bit=True`, you will need one 80GB GPUs.
387
+ # If you set `load_in_8bit=False`, you will need at least two 80GB GPUs.
388
+ path = 'OpenGVLab/InternVL2_5-38B'
389
+ device_map = split_model('InternVL2_5-38B')
390
+ model = AutoModel.from_pretrained(
391
+ path,
392
+ torch_dtype=torch.bfloat16,
393
+ load_in_8bit=True,
394
+ low_cpu_mem_usage=True,
395
+ use_flash_attn=True,
396
+ trust_remote_code=True,
397
+ device_map=device_map).eval()
398
+ tokenizer = AutoTokenizer.from_pretrained(path, trust_remote_code=True, use_fast=False)
399
+
400
+ # set the max number of tiles in `max_num`
401
+ pixel_values = load_image('./examples/image1.jpg', max_num=12).to(torch.bfloat16).cuda()
402
+ generation_config = dict(max_new_tokens=1024, do_sample=True)
403
+
404
+ # pure-text conversation (纯文本对话)
405
+ question = 'Hello, who are you?'
406
+ response, history = model.chat(tokenizer, None, question, generation_config, history=None, return_history=True)
407
+ print(f'User: {question}\nAssistant: {response}')
408
+
409
+ question = 'Can you tell me a story?'
410
+ response, history = model.chat(tokenizer, None, question, generation_config, history=history, return_history=True)
411
+ print(f'User: {question}\nAssistant: {response}')
412
+
413
+ # single-image single-round conversation (单图单轮对话)
414
+ question = '<image>\nPlease describe the image shortly.'
415
+ response = model.chat(tokenizer, pixel_values, question, generation_config)
416
+ print(f'User: {question}\nAssistant: {response}')
417
+
418
+ # single-image multi-round conversation (单图多轮对话)
419
+ question = '<image>\nPlease describe the image in detail.'
420
+ response, history = model.chat(tokenizer, pixel_values, question, generation_config, history=None, return_history=True)
421
+ print(f'User: {question}\nAssistant: {response}')
422
+
423
+ question = 'Please write a poem according to the image.'
424
+ response, history = model.chat(tokenizer, pixel_values, question, generation_config, history=history, return_history=True)
425
+ print(f'User: {question}\nAssistant: {response}')
426
+
427
+ # multi-image multi-round conversation, combined images (多图多轮对话,拼接图像)
428
+ pixel_values1 = load_image('./examples/image1.jpg', max_num=12).to(torch.bfloat16).cuda()
429
+ pixel_values2 = load_image('./examples/image2.jpg', max_num=12).to(torch.bfloat16).cuda()
430
+ pixel_values = torch.cat((pixel_values1, pixel_values2), dim=0)
431
+
432
+ question = '<image>\nDescribe the two images in detail.'
433
+ response, history = model.chat(tokenizer, pixel_values, question, generation_config,
434
+ history=None, return_history=True)
435
+ print(f'User: {question}\nAssistant: {response}')
436
+
437
+ question = 'What are the similarities and differences between these two images.'
438
+ response, history = model.chat(tokenizer, pixel_values, question, generation_config,
439
+ history=history, return_history=True)
440
+ print(f'User: {question}\nAssistant: {response}')
441
+
442
+ # multi-image multi-round conversation, separate images (多图多轮对话,独立图像)
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
+ pixel_values = torch.cat((pixel_values1, pixel_values2), dim=0)
446
+ num_patches_list = [pixel_values1.size(0), pixel_values2.size(0)]
447
+
448
+ question = 'Image-1: <image>\nImage-2: <image>\nDescribe the two images in detail.'
449
+ response, history = model.chat(tokenizer, pixel_values, question, generation_config,
450
+ num_patches_list=num_patches_list,
451
+ history=None, return_history=True)
452
+ print(f'User: {question}\nAssistant: {response}')
453
+
454
+ question = 'What are the similarities and differences between these two images.'
455
+ response, history = model.chat(tokenizer, pixel_values, question, generation_config,
456
+ num_patches_list=num_patches_list,
457
+ history=history, return_history=True)
458
+ print(f'User: {question}\nAssistant: {response}')
459
+
460
+ # batch inference, single image per sample (单图批处理)
461
+ pixel_values1 = load_image('./examples/image1.jpg', max_num=12).to(torch.bfloat16).cuda()
462
+ pixel_values2 = load_image('./examples/image2.jpg', max_num=12).to(torch.bfloat16).cuda()
463
+ num_patches_list = [pixel_values1.size(0), pixel_values2.size(0)]
464
+ pixel_values = torch.cat((pixel_values1, pixel_values2), dim=0)
465
+
466
+ questions = ['<image>\nDescribe the image in detail.'] * len(num_patches_list)
467
+ responses = model.batch_chat(tokenizer, pixel_values,
468
+ num_patches_list=num_patches_list,
469
+ questions=questions,
470
+ generation_config=generation_config)
471
+ for question, response in zip(questions, responses):
472
+ print(f'User: {question}\nAssistant: {response}')
473
+
474
+ # video multi-round conversation (视频多轮对话)
475
+ def get_index(bound, fps, max_frame, first_idx=0, num_segments=32):
476
+ if bound:
477
+ start, end = bound[0], bound[1]
478
+ else:
479
+ start, end = -100000, 100000
480
+ start_idx = max(first_idx, round(start * fps))
481
+ end_idx = min(round(end * fps), max_frame)
482
+ seg_size = float(end_idx - start_idx) / num_segments
483
+ frame_indices = np.array([
484
+ int(start_idx + (seg_size / 2) + np.round(seg_size * idx))
485
+ for idx in range(num_segments)
486
+ ])
487
+ return frame_indices
488
+
489
+ def load_video(video_path, bound=None, input_size=448, max_num=1, num_segments=32):
490
+ vr = VideoReader(video_path, ctx=cpu(0), num_threads=1)
491
+ max_frame = len(vr) - 1
492
+ fps = float(vr.get_avg_fps())
493
+
494
+ pixel_values_list, num_patches_list = [], []
495
+ transform = build_transform(input_size=input_size)
496
+ frame_indices = get_index(bound, fps, max_frame, first_idx=0, num_segments=num_segments)
497
+ for frame_index in frame_indices:
498
+ img = Image.fromarray(vr[frame_index].asnumpy()).convert('RGB')
499
+ img = dynamic_preprocess(img, image_size=input_size, use_thumbnail=True, max_num=max_num)
500
+ pixel_values = [transform(tile) for tile in img]
501
+ pixel_values = torch.stack(pixel_values)
502
+ num_patches_list.append(pixel_values.shape[0])
503
+ pixel_values_list.append(pixel_values)
504
+ pixel_values = torch.cat(pixel_values_list)
505
+ return pixel_values, num_patches_list
506
+
507
+ video_path = './examples/red-panda.mp4'
508
+ pixel_values, num_patches_list = load_video(video_path, num_segments=8, max_num=1)
509
+ pixel_values = pixel_values.to(torch.bfloat16).cuda()
510
+ video_prefix = ''.join([f'Frame{i+1}: <image>\n' for i in range(len(num_patches_list))])
511
+ question = video_prefix + 'What is the red panda doing?'
512
+ # Frame1: <image>\nFrame2: <image>\n...\nFrame8: <image>\n{question}
513
+ response, history = model.chat(tokenizer, pixel_values, question, generation_config,
514
+ num_patches_list=num_patches_list, history=None, return_history=True)
515
+ print(f'User: {question}\nAssistant: {response}')
516
+
517
+ question = 'Describe this video in detail.'
518
+ response, history = model.chat(tokenizer, pixel_values, question, generation_config,
519
+ num_patches_list=num_patches_list, history=history, return_history=True)
520
+ print(f'User: {question}\nAssistant: {response}')
521
+ ```
522
+
523
+ #### Streaming Output
524
+
525
+ Besides this method, you can also use the following code to get streamed output.
526
+
527
+ ```python
528
+ from transformers import TextIteratorStreamer
529
+ from threading import Thread
530
+
531
+ # Initialize the streamer
532
+ streamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True, timeout=10)
533
+ # Define the generation configuration
534
+ generation_config = dict(max_new_tokens=1024, do_sample=False, streamer=streamer)
535
+ # Start the model chat in a separate thread
536
+ thread = Thread(target=model.chat, kwargs=dict(
537
+ tokenizer=tokenizer, pixel_values=pixel_values, question=question,
538
+ history=None, return_history=False, generation_config=generation_config,
539
+ ))
540
+ thread.start()
541
+
542
+ # Initialize an empty string to store the generated text
543
+ generated_text = ''
544
+ # Loop through the streamer to get the new text as it is generated
545
+ for new_text in streamer:
546
+ if new_text == model.conv_template.sep:
547
+ break
548
+ generated_text += new_text
549
+ print(new_text, end='', flush=True) # Print each new chunk of generated text on the same line
550
+ ```
551
+
552
+ ## Finetune
553
+
554
+ 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.
555
+
556
+ ## Deployment
557
+
558
+ ### LMDeploy
559
+
560
+ LMDeploy is a toolkit for compressing, deploying, and serving LLMs & VLMs.
561
+
562
+ ```sh
563
+ pip install lmdeploy>=0.6.4
564
+ ```
565
+
566
+ 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.
567
+
568
+ #### A 'Hello, world' Example
569
+
570
+ ```python
571
+ from lmdeploy import pipeline, TurbomindEngineConfig
572
+ from lmdeploy.vl import load_image
573
+
574
+ model = 'OpenGVLab/InternVL2_5-38B'
575
+ image = load_image('https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/tests/data/tiger.jpeg')
576
+ pipe = pipeline(model, backend_config=TurbomindEngineConfig(session_len=8192, tp=2))
577
+ response = pipe(('describe this image', image))
578
+ print(response.text)
579
+ ```
580
+
581
+ If `ImportError` occurs while executing this case, please install the required dependency packages as prompted.
582
+
583
+ #### Multi-images Inference
584
+
585
+ 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.
586
+
587
+ ```python
588
+ from lmdeploy import pipeline, TurbomindEngineConfig
589
+ from lmdeploy.vl import load_image
590
+ from lmdeploy.vl.constants import IMAGE_TOKEN
591
+
592
+ model = 'OpenGVLab/InternVL2_5-38B'
593
+ pipe = pipeline(model, backend_config=TurbomindEngineConfig(session_len=8192, tp=2))
594
+
595
+ image_urls=[
596
+ 'https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/human-pose.jpg',
597
+ 'https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/det.jpg'
598
+ ]
599
+
600
+ images = [load_image(img_url) for img_url in image_urls]
601
+ # Numbering images improves multi-image conversations
602
+ response = pipe((f'Image-1: {IMAGE_TOKEN}\nImage-2: {IMAGE_TOKEN}\ndescribe these two images', images))
603
+ print(response.text)
604
+ ```
605
+
606
+ #### Batch Prompts Inference
607
+
608
+ Conducting inference with batch prompts is quite straightforward; just place them within a list structure:
609
+
610
+ ```python
611
+ from lmdeploy import pipeline, TurbomindEngineConfig
612
+ from lmdeploy.vl import load_image
613
+
614
+ model = 'OpenGVLab/InternVL2_5-38B'
615
+ pipe = pipeline(model, backend_config=TurbomindEngineConfig(session_len=8192, tp=2))
616
+
617
+ image_urls=[
618
+ "https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/human-pose.jpg",
619
+ "https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/det.jpg"
620
+ ]
621
+ prompts = [('describe this image', load_image(img_url)) for img_url in image_urls]
622
+ response = pipe(prompts)
623
+ print(response)
624
+ ```
625
+
626
+ #### Multi-turn Conversation
627
+
628
+ 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.
629
+
630
+ ```python
631
+ from lmdeploy import pipeline, TurbomindEngineConfig, GenerationConfig
632
+ from lmdeploy.vl import load_image
633
+
634
+ model = 'OpenGVLab/InternVL2_5-38B'
635
+ pipe = pipeline(model, backend_config=TurbomindEngineConfig(session_len=8192, tp=2))
636
+
637
+ image = load_image('https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/human-pose.jpg')
638
+ gen_config = GenerationConfig(top_k=40, top_p=0.8, temperature=0.8)
639
+ sess = pipe.chat(('describe this image', image), gen_config=gen_config)
640
+ print(sess.response.text)
641
+ sess = pipe.chat('What is the woman doing?', session=sess, gen_config=gen_config)
642
+ print(sess.response.text)
643
+ ```
644
+
645
+ #### Service
646
+
647
+ 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:
648
+
649
+ ```shell
650
+ lmdeploy serve api_server OpenGVLab/InternVL2_5-38B --server-port 23333 --tp 2
651
+ ```
652
+
653
+ To use the OpenAI-style interface, you need to install OpenAI:
654
+
655
+ ```shell
656
+ pip install openai
657
+ ```
658
+
659
+ Then, use the code below to make the API call:
660
+
661
+ ```python
662
+ from openai import OpenAI
663
+
664
+ client = OpenAI(api_key='YOUR_API_KEY', base_url='http://0.0.0.0:23333/v1')
665
+ model_name = client.models.list().data[0].id
666
+ response = client.chat.completions.create(
667
+ model=model_name,
668
+ messages=[{
669
+ 'role':
670
+ 'user',
671
+ 'content': [{
672
+ 'type': 'text',
673
+ 'text': 'describe this image',
674
+ }, {
675
+ 'type': 'image_url',
676
+ 'image_url': {
677
+ 'url':
678
+ 'https://modelscope.oss-cn-beijing.aliyuncs.com/resource/tiger.jpeg',
679
+ },
680
+ }],
681
+ }],
682
+ temperature=0.8,
683
+ top_p=0.8)
684
+ print(response)
685
+ ```
686
+
687
+ ## License
688
+
689
+ This project is released under the MIT License. This project uses the pre-trained Qwen2.5-32B-Instruct as a component, which is licensed under the Apache License 2.0.
690
+
691
+ ## Citation
692
+
693
+ If you find this project useful in your research, please consider citing:
694
+
695
+ ```BibTeX
696
+ @article{chen2024expanding,
697
+ title={Expanding Performance Boundaries of Open-Source Multimodal Models with Model, Data, and Test-Time Scaling},
698
+ 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},
699
+ journal={arXiv preprint arXiv:2412.05271},
700
+ year={2024}
701
+ }
702
+ @article{gao2024mini,
703
+ title={Mini-internvl: A flexible-transfer pocket multimodal model with 5\% parameters and 90\% performance},
704
+ author={Gao, Zhangwei and Chen, Zhe and Cui, Erfei and Ren, Yiming and Wang, Weiyun and Zhu, Jinguo and Tian, Hao and Ye, Shenglong and He, Junjun and Zhu, Xizhou and others},
705
+ journal={arXiv preprint arXiv:2410.16261},
706
+ year={2024}
707
+ }
708
+ @article{chen2024far,
709
+ title={How Far Are We to GPT-4V? Closing the Gap to Commercial Multimodal Models with Open-Source Suites},
710
+ 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},
711
+ journal={arXiv preprint arXiv:2404.16821},
712
+ year={2024}
713
+ }
714
+ @inproceedings{chen2024internvl,
715
+ title={Internvl: Scaling up vision foundation models and aligning for generic visual-linguistic tasks},
716
+ 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},
717
+ booktitle={Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition},
718
+ pages={24185--24198},
719
+ year={2024}
720
+ }
721
+ ```