ctranslate2-4you commited on
Commit
b9427fb
·
verified ·
1 Parent(s): 5f74ce7

Create README.md

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