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