zwgao commited on
Commit
aad15bf
1 Parent(s): f01b74c

Update README.md

Browse files
Files changed (1) hide show
  1. README.md +756 -3
README.md CHANGED
@@ -1,3 +1,756 @@
1
- ---
2
- license: mit
3
- ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ - vision
14
+ - ocr
15
+ - multi-image
16
+ - video
17
+ - custom_code
18
+ ---
19
+
20
+ # InternVL2_5-4B
21
+
22
+ [\[📂 GitHub\]](https://github.com/OpenGVLab/InternVL) [\[🆕 Blog\]](https://internvl.github.io/blog/)
23
+ [\[📜 InternVL 2.5 Report\]]()
24
+ [\[📜 InternVL 1.0 Paper\]](https://arxiv.org/abs/2312.14238) [\[📜 InternVL 1.5 Report\]](https://arxiv.org/abs/2404.16821)
25
+ [\[🗨️ 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/)
26
+
27
+ ![image/jpeg](https://cdn-uploads.huggingface.co/production/uploads/64564b0e4a7ffb7d5a47f412/3i-8-6VSoTAo0-OKUUpec.jpeg)
28
+
29
+ ## Introduction
30
+
31
+ 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.
32
+
33
+ Through extensive evaluations on a wide range of benchmarks, including multi-discipline reasoning, document understanding, multi-image / video understanding, real-world comprehension, multimodal hallucination detection, visual grounding, multilingual capabilities, and pure language processing, InternVL 2.5 exhibits competitive performance, rivaling leading commercial models such as GPT-4o and Claude-3.5-Sonnet. Notably, our model is the first open-source MLLMs to achieve over **70%** on the **MMMU benchmark**. We hope this model contributes to the open-source community by setting new standards for developing and applying multimodal AI systems. This repository contains the instruction-tuned **InternVL2_5-4B** model.
34
+
35
+ We delve into the relationship between model scaling and performance, systematically exploring the performance trends in vision encoders, language models, dataset sizes, and test-time configurations. For more details, please refer to our [blog](), [tech report]() and [GitHub](https://github.com/OpenGVLab/InternVL).
36
+
37
+ | Model Name | Vision Part | Language Part | HF Link |
38
+ | :------------------: | :---------------------------------------------------------------------------------: | :------------------------------------------------------------------------------------------: | :--------------------------------------------------------------: |
39
+ | 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) |
40
+ | 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) |
41
+ | 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) |
42
+ | 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) |
43
+ | 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) |
44
+ | 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) |
45
+ | 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) |
46
+
47
+ ## Model Details
48
+
49
+ InternVL 2.5 is a multimodal large language model series, featuring models of various sizes. For each size, we release instruction-tuned models optimized for multimodal tasks. InternVL2_5-4B consists of [InternViT-300M-448px-V2_5](https://huggingface.co/OpenGVLab/InternViT-300M-448px-V2_5), an MLP projector, and [Qwen2.5-3B-Instruct](https://huggingface.co/Qwen/Qwen2.5-3B-Instruct).
50
+
51
+ ## Performance
52
+
53
+ ### Image Benchmarks
54
+
55
+ | Benchmark | Phi-3.5-Vision-4B | InternVL2-4B | InternVL2.5-4B |
56
+ |---------------------|-------------------|--------------|----------------|
57
+ | MMMU (val) | 43.0 | 47.9 | 52.3 |
58
+ | MMMU (test) | - | 41.4 | 46.3 |
59
+ | MMMU-PRO (overall) | 19.7 | 24.7 | 32.7 |
60
+ | MathVista (mini) | 43.9 | 58.6 | 60.5 |
61
+ | MathVision (mini) | 17.4 | 17.8 | 21.7 |
62
+ | MathVision (full) | 15.5 | 16.5 | 20.9 |
63
+ | MathVerse (mini) | 24.1 | 32.0 | 37.1 |
64
+ | Olympiad Bench | - | 1.1 | 3.0 |
65
+ | AI2D (w / wo M) | 77.8 / 87.6 | 78.9 / 87.8 | 81.4 / 90.5 |
66
+ | ChartQA (test avg.) | 81.8 | 81.5 | 84.0 |
67
+ | TextVQA (val) |72.0 | 74.4 | 76.8 |
68
+ | DocVQA (test) |69.3 | 89.2 | 91.6 |
69
+ | InfoVQA (test) | 36.6 | 67.0 | 72.1 |
70
+ | OCR-Bench | 599 | 788 | 828 |
71
+ | SEED-2 Plus | 62.2 | 63.9 | 66.9 |
72
+ | CharXiv (RQ / DQ) | - | 24.5 / 48.0 | 24.9 / 61.7 |
73
+ | VCR-EN-Easy (EM / Jaccard) |39.3 / 60.4 | 33.7 / 61.1 | 93.7 / 97.8 |
74
+ | BLINK (val) |58.3 | 46.1 | 50.8 |
75
+ | Mantis Eval | - | 61.3 | 62.7 |
76
+ | MMIU | - | 43.3 | 43.8 |
77
+ | Muir Bench | - | 40.5 | 45.2 |
78
+ | MMT (val) | 53.6 | 55.7 | 62.4 |
79
+ | MIRB (avg.) | - | 39.9 | 51.7 |
80
+ | RealWorld QA | 53.6 | 60.7 | 64.3 |
81
+ | MME-RW (EN) | - | 52.1 | 55.3 |
82
+ | WildVision (win rate)|-- | 44.2 | 49.4 |
83
+ | R-Bench | 55.5 | 64.5 | 66.1 |
84
+ | MME (sum) | - | 2059.8 | 2337.5 |
85
+ | MMB (EN / CN) | 76.0 / 66.1 | 78.6 / 73.9 | 81.1 / 79.3 |
86
+ | MMBv1.1 (EN) | 72.1 | 75.8 | 79.3 |
87
+ | MMVet (turbo) | 43.2 | 51.0 | 60.6 |
88
+ | MMVetv2 (0613) | - | 46.6 | 55.4 |
89
+ | MMStar | 47.5 | 54.3 | 58.3 |
90
+ | HallBench (avg.) | 40.5 | 41.9 | 46.3 |
91
+ | MMHal (score) | - | 2.75 | 3.31 |
92
+ | CRPE (relation) | - | 71.1 | 75.5 |
93
+ | POPE (avg.) | - | 87.2 | 90.9 |
94
+
95
+ ### Video Benchmarks
96
+
97
+ ### Multimodal Multilingual Understanding
98
+ <table border="1">
99
+ <thead>
100
+ <tr>
101
+ <th rowspan="2">Model Name</th>
102
+ <th colspan="6">MMMB</th>
103
+ <th colspan="6">MultiMMB</th>
104
+ <th>MTVQA</th>
105
+ </tr>
106
+ <tr>
107
+ <th>en</th>
108
+ <th>zh</th>
109
+ <th>pt</th>
110
+ <th>ar</th>
111
+ <th>tr</th>
112
+ <th>ru</th>
113
+ <th>en</th>
114
+ <th>zh</th>
115
+ <th>pt</th>
116
+ <th>ar</th>
117
+ <th>tr</th>
118
+ <th>ru</th>
119
+ <th>(avg)</th>
120
+ </tr>
121
+ </thead>
122
+ <tbody>
123
+ <tr>
124
+ <td>Qwen2-VL-2B</td>
125
+ <td>78.3</td>
126
+ <td>74.2</td>
127
+ <td>72.6</td>
128
+ <td>68.3</td>
129
+ <td>61.8</td>
130
+ <td>72.8</td>
131
+ <td>72.1</td>
132
+ <td>71.1</td>
133
+ <td>69.9</td>
134
+ <td>61.1</td>
135
+ <td>54.4</td>
136
+ <td>69.3</td>
137
+ <td>20.0</td>
138
+ </tr>
139
+ <tr>
140
+ <td>InternVL2-2B</td>
141
+ <td>79.4</td>
142
+ <td>71.6</td>
143
+ <td>54.0</td>
144
+ <td>43.5</td>
145
+ <td>46.4</td>
146
+ <td>48.1</td>
147
+ <td>73.8</td>
148
+ <td>69.6</td>
149
+ <td>51.4</td>
150
+ <td>29.8</td>
151
+ <td>31.3</td>
152
+ <td>42.3</td>
153
+ <td>10.9</td>
154
+ </tr>
155
+ <tr style="background-color: #D3D3D3;">
156
+ <td>InternVL2.5-2B</td>
157
+ <td>81.4</td>
158
+ <td>74.4</td>
159
+ <td>58.2</td>
160
+ <td>48.3</td>
161
+ <td>46.4</td>
162
+ <td>53.2</td>
163
+ <td>76.5</td>
164
+ <td>71.6</td>
165
+ <td>55.9</td>
166
+ <td>37.3</td>
167
+ <td>33.9</td>
168
+ <td>44.8</td>
169
+ <td>21.8</td>
170
+ </tr>
171
+ <tr>
172
+ <td>InternVL2-4B</td>
173
+ <td>82.0</td>
174
+ <td>76.1</td>
175
+ <td>75.6</td>
176
+ <td>54.3</td>
177
+ <td>51.2</td>
178
+ <td>67.4</td>
179
+ <td>77.3</td>
180
+ <td>72.4</td>
181
+ <td>72.6</td>
182
+ <td>43.6</td>
183
+ <td>46.5</td>
184
+ <td>61.2</td>
185
+ <td>15.3</td>
186
+ </tr>
187
+ <tr style="background-color: #D3D3D3;">
188
+ <td>InternVL2.5-4B</td>
189
+ <td>83.7</td>
190
+ <td>81.0</td>
191
+ <td>79.7</td>
192
+ <td>76.0</td>
193
+ <td>70.5</td>
194
+ <td>79.9</td>
195
+ <td>82.3</td>
196
+ <td>81.1</td>
197
+ <td>78.9</td>
198
+ <td>73.4</td>
199
+ <td>68.1</td>
200
+ <td>76.2</td>
201
+ <td>28.4</td>
202
+ </tr>
203
+ <tr>
204
+ <td>mPLUG-Owl2</td>
205
+ <td>67.3</td>
206
+ <td>61.0</td>
207
+ <td>59.7</td>
208
+ <td>45.8</td>
209
+ <td>45.4</td>
210
+ <td>62.6</td>
211
+ <td>66.2</td>
212
+ <td>59.4</td>
213
+ <td>58.2</td>
214
+ <td>37.9</td>
215
+ <td>47.7</td>
216
+ <td>60.4</td>
217
+ <td>--</td>
218
+ </tr>
219
+ <tr>
220
+ <td>Qwen2-VL-7B</td>
221
+ <td>83.9</td>
222
+ <td>82.4</td>
223
+ <td>81.2</td>
224
+ <td>79.0</td>
225
+ <td>74.7</td>
226
+ <td>82.4</td>
227
+ <td>81.8</td>
228
+ <td>81.6</td>
229
+ <td>79.1</td>
230
+ <td>75.6</td>
231
+ <td>74.5</td>
232
+ <td>79.3</td>
233
+ <td>25.6</td>
234
+ </tr>
235
+ </tbody>
236
+ </table>
237
+
238
+
239
+
240
+ ### Invitation to Evaluate InternVL
241
+
242
+ We welcome MLLM benchmark developers to assess our InternVL series models. If you need to add your evaluation results here, please contact me at [wztxy89@163.com](mailto:wztxy89@163.com).
243
+
244
+ ## Quick Start
245
+
246
+ We provide an example code to run InternVL2_5-4B using `transformers`.
247
+
248
+ We also welcome you to experience the InternVL series models in our [online demo](https://internvl.opengvlab.com/).
249
+
250
+ > Please use transformers ≳ 4.37.2 to ensure the model works normally.
251
+
252
+ ### Model Loading
253
+
254
+ #### 16-bit (bf16 / fp16)
255
+
256
+ ```python
257
+ import torch
258
+ from transformers import AutoTokenizer, AutoModel
259
+ path = "OpenGVLab/InternVL2_5-4B"
260
+ model = AutoModel.from_pretrained(
261
+ path,
262
+ torch_dtype=torch.bfloat16,
263
+ low_cpu_mem_usage=True,
264
+ use_flash_attn=True,
265
+ trust_remote_code=True).eval().cuda()
266
+ ```
267
+
268
+ #### BNB 8-bit Quantization
269
+
270
+ ```python
271
+ import torch
272
+ from transformers import AutoTokenizer, AutoModel
273
+ path = "OpenGVLab/InternVL2_5-4B"
274
+ model = AutoModel.from_pretrained(
275
+ path,
276
+ torch_dtype=torch.bfloat16,
277
+ load_in_8bit=True,
278
+ low_cpu_mem_usage=True,
279
+ use_flash_attn=True,
280
+ trust_remote_code=True).eval()
281
+ ```
282
+
283
+ #### BNB 4-bit Quantization
284
+
285
+ ```python
286
+ import torch
287
+ from transformers import AutoTokenizer, AutoModel
288
+ path = "OpenGVLab/InternVL2_5-4B"
289
+ model = AutoModel.from_pretrained(
290
+ path,
291
+ torch_dtype=torch.bfloat16,
292
+ load_in_4bit=True,
293
+ low_cpu_mem_usage=True,
294
+ use_flash_attn=True,
295
+ trust_remote_code=True).eval()
296
+ ```
297
+
298
+ #### Multiple GPUs
299
+
300
+ 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.
301
+
302
+ ```python
303
+ import math
304
+ import torch
305
+ from transformers import AutoTokenizer, AutoModel
306
+
307
+ def split_model(model_name):
308
+ device_map = {}
309
+ world_size = torch.cuda.device_count()
310
+ num_layers = {
311
+ 'InternVL2_5-1B': 24, 'InternVL_5-2B': 24, 'InternVL2_5-4B': 36, 'InternVL2_5-8B': 32,
312
+ 'InternVL2_5-26B': 48, 'InternVL2_5-38B': 64, 'InternVL2_5-78B': 80}[model_name]
313
+ # Since the first GPU will be used for ViT, treat it as half a GPU.
314
+ num_layers_per_gpu = math.ceil(num_layers / (world_size - 0.5))
315
+ num_layers_per_gpu = [num_layers_per_gpu] * world_size
316
+ num_layers_per_gpu[0] = math.ceil(num_layers_per_gpu[0] * 0.5)
317
+ layer_cnt = 0
318
+ for i, num_layer in enumerate(num_layers_per_gpu):
319
+ for j in range(num_layer):
320
+ device_map[f'language_model.model.layers.{layer_cnt}'] = i
321
+ layer_cnt += 1
322
+ device_map['vision_model'] = 0
323
+ device_map['mlp1'] = 0
324
+ device_map['language_model.model.tok_embeddings'] = 0
325
+ device_map['language_model.model.embed_tokens'] = 0
326
+ device_map['language_model.output'] = 0
327
+ device_map['language_model.model.norm'] = 0
328
+ device_map['language_model.lm_head'] = 0
329
+ device_map[f'language_model.model.layers.{num_layers - 1}'] = 0
330
+
331
+ return device_map
332
+
333
+ path = "OpenGVLab/InternVL2_5-4B"
334
+ device_map = split_model('InternVL2_5-4B')
335
+ model = AutoModel.from_pretrained(
336
+ path,
337
+ torch_dtype=torch.bfloat16,
338
+ low_cpu_mem_usage=True,
339
+ use_flash_attn=True,
340
+ trust_remote_code=True,
341
+ device_map=device_map).eval()
342
+ ```
343
+
344
+ ### Inference with Transformers
345
+
346
+ ```python
347
+ import numpy as np
348
+ import torch
349
+ import torchvision.transforms as T
350
+ from decord import VideoReader, cpu
351
+ from PIL import Image
352
+ from torchvision.transforms.functional import InterpolationMode
353
+ from transformers import AutoModel, AutoTokenizer
354
+
355
+ IMAGENET_MEAN = (0.485, 0.456, 0.406)
356
+ IMAGENET_STD = (0.229, 0.224, 0.225)
357
+
358
+ def build_transform(input_size):
359
+ MEAN, STD = IMAGENET_MEAN, IMAGENET_STD
360
+ transform = T.Compose([
361
+ T.Lambda(lambda img: img.convert('RGB') if img.mode != 'RGB' else img),
362
+ T.Resize((input_size, input_size), interpolation=InterpolationMode.BICUBIC),
363
+ T.ToTensor(),
364
+ T.Normalize(mean=MEAN, std=STD)
365
+ ])
366
+ return transform
367
+
368
+ def find_closest_aspect_ratio(aspect_ratio, target_ratios, width, height, image_size):
369
+ best_ratio_diff = float('inf')
370
+ best_ratio = (1, 1)
371
+ area = width * height
372
+ for ratio in target_ratios:
373
+ target_aspect_ratio = ratio[0] / ratio[1]
374
+ ratio_diff = abs(aspect_ratio - target_aspect_ratio)
375
+ if ratio_diff < best_ratio_diff:
376
+ best_ratio_diff = ratio_diff
377
+ best_ratio = ratio
378
+ elif ratio_diff == best_ratio_diff:
379
+ if area > 0.5 * image_size * image_size * ratio[0] * ratio[1]:
380
+ best_ratio = ratio
381
+ return best_ratio
382
+
383
+ def dynamic_preprocess(image, min_num=1, max_num=12, image_size=448, use_thumbnail=False):
384
+ orig_width, orig_height = image.size
385
+ aspect_ratio = orig_width / orig_height
386
+
387
+ # calculate the existing image aspect ratio
388
+ target_ratios = set(
389
+ (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
390
+ i * j <= max_num and i * j >= min_num)
391
+ target_ratios = sorted(target_ratios, key=lambda x: x[0] * x[1])
392
+
393
+ # find the closest aspect ratio to the target
394
+ target_aspect_ratio = find_closest_aspect_ratio(
395
+ aspect_ratio, target_ratios, orig_width, orig_height, image_size)
396
+
397
+ # calculate the target width and height
398
+ target_width = image_size * target_aspect_ratio[0]
399
+ target_height = image_size * target_aspect_ratio[1]
400
+ blocks = target_aspect_ratio[0] * target_aspect_ratio[1]
401
+
402
+ # resize the image
403
+ resized_img = image.resize((target_width, target_height))
404
+ processed_images = []
405
+ for i in range(blocks):
406
+ box = (
407
+ (i % (target_width // image_size)) * image_size,
408
+ (i // (target_width // image_size)) * image_size,
409
+ ((i % (target_width // image_size)) + 1) * image_size,
410
+ ((i // (target_width // image_size)) + 1) * image_size
411
+ )
412
+ # split the image
413
+ split_img = resized_img.crop(box)
414
+ processed_images.append(split_img)
415
+ assert len(processed_images) == blocks
416
+ if use_thumbnail and len(processed_images) != 1:
417
+ thumbnail_img = image.resize((image_size, image_size))
418
+ processed_images.append(thumbnail_img)
419
+ return processed_images
420
+
421
+ def load_image(image_file, input_size=448, max_num=12):
422
+ image = Image.open(image_file).convert('RGB')
423
+ transform = build_transform(input_size=input_size)
424
+ images = dynamic_preprocess(image, image_size=input_size, use_thumbnail=True, max_num=max_num)
425
+ pixel_values = [transform(image) for image in images]
426
+ pixel_values = torch.stack(pixel_values)
427
+ return pixel_values
428
+
429
+ # If you want to load a model using multiple GPUs, please refer to the `Multiple GPUs` section.
430
+ path = 'OpenGVLab/InternVL2_5-4B'
431
+ model = AutoModel.from_pretrained(
432
+ path,
433
+ torch_dtype=torch.bfloat16,
434
+ low_cpu_mem_usage=True,
435
+ use_flash_attn=True,
436
+ trust_remote_code=True).eval().cuda()
437
+ tokenizer = AutoTokenizer.from_pretrained(path, trust_remote_code=True, use_fast=False)
438
+
439
+ # set the max number of tiles in `max_num`
440
+ pixel_values = load_image('./examples/image1.jpg', max_num=12).to(torch.bfloat16).cuda()
441
+ generation_config = dict(max_new_tokens=1024, do_sample=True)
442
+
443
+ # pure-text conversation (纯文本对话)
444
+ question = 'Hello, who are you?'
445
+ response, history = model.chat(tokenizer, None, question, generation_config, history=None, return_history=True)
446
+ print(f'User: {question}\nAssistant: {response}')
447
+
448
+ question = 'Can you tell me a story?'
449
+ response, history = model.chat(tokenizer, None, question, generation_config, history=history, return_history=True)
450
+ print(f'User: {question}\nAssistant: {response}')
451
+
452
+ # single-image single-round conversation (单图单轮对话)
453
+ question = '<image>\nPlease describe the image shortly.'
454
+ response = model.chat(tokenizer, pixel_values, question, generation_config)
455
+ print(f'User: {question}\nAssistant: {response}')
456
+
457
+ # single-image multi-round conversation (单图多轮对话)
458
+ question = '<image>\nPlease describe the image in detail.'
459
+ response, history = model.chat(tokenizer, pixel_values, question, generation_config, history=None, return_history=True)
460
+ print(f'User: {question}\nAssistant: {response}')
461
+
462
+ question = 'Please write a poem according to the image.'
463
+ response, history = model.chat(tokenizer, pixel_values, question, generation_config, history=history, return_history=True)
464
+ print(f'User: {question}\nAssistant: {response}')
465
+
466
+ # multi-image multi-round conversation, combined images (多图多轮对话,拼接图像)
467
+ pixel_values1 = load_image('./examples/image1.jpg', max_num=12).to(torch.bfloat16).cuda()
468
+ pixel_values2 = load_image('./examples/image2.jpg', max_num=12).to(torch.bfloat16).cuda()
469
+ pixel_values = torch.cat((pixel_values1, pixel_values2), dim=0)
470
+
471
+ question = '<image>\nDescribe the two images in detail.'
472
+ response, history = model.chat(tokenizer, pixel_values, question, generation_config,
473
+ history=None, return_history=True)
474
+ print(f'User: {question}\nAssistant: {response}')
475
+
476
+ question = 'What are the similarities and differences between these two images.'
477
+ response, history = model.chat(tokenizer, pixel_values, question, generation_config,
478
+ history=history, return_history=True)
479
+ print(f'User: {question}\nAssistant: {response}')
480
+
481
+ # multi-image multi-round conversation, separate images (多图多轮对话,独立图像)
482
+ pixel_values1 = load_image('./examples/image1.jpg', max_num=12).to(torch.bfloat16).cuda()
483
+ pixel_values2 = load_image('./examples/image2.jpg', max_num=12).to(torch.bfloat16).cuda()
484
+ pixel_values = torch.cat((pixel_values1, pixel_values2), dim=0)
485
+ num_patches_list = [pixel_values1.size(0), pixel_values2.size(0)]
486
+
487
+ question = 'Image-1: <image>\nImage-2: <image>\nDescribe the two images in detail.'
488
+ response, history = model.chat(tokenizer, pixel_values, question, generation_config,
489
+ num_patches_list=num_patches_list,
490
+ history=None, return_history=True)
491
+ print(f'User: {question}\nAssistant: {response}')
492
+
493
+ question = 'What are the similarities and differences between these two images.'
494
+ response, history = model.chat(tokenizer, pixel_values, question, generation_config,
495
+ num_patches_list=num_patches_list,
496
+ history=history, return_history=True)
497
+ print(f'User: {question}\nAssistant: {response}')
498
+
499
+ # batch inference, single image per sample (单图批处理)
500
+ pixel_values1 = load_image('./examples/image1.jpg', max_num=12).to(torch.bfloat16).cuda()
501
+ pixel_values2 = load_image('./examples/image2.jpg', max_num=12).to(torch.bfloat16).cuda()
502
+ num_patches_list = [pixel_values1.size(0), pixel_values2.size(0)]
503
+ pixel_values = torch.cat((pixel_values1, pixel_values2), dim=0)
504
+
505
+ questions = ['<image>\nDescribe the image in detail.'] * len(num_patches_list)
506
+ responses = model.batch_chat(tokenizer, pixel_values,
507
+ num_patches_list=num_patches_list,
508
+ questions=questions,
509
+ generation_config=generation_config)
510
+ for question, response in zip(questions, responses):
511
+ print(f'User: {question}\nAssistant: {response}')
512
+
513
+ # video multi-round conversation (视频多轮对话)
514
+ def get_index(bound, fps, max_frame, first_idx=0, num_segments=32):
515
+ if bound:
516
+ start, end = bound[0], bound[1]
517
+ else:
518
+ start, end = -100000, 100000
519
+ start_idx = max(first_idx, round(start * fps))
520
+ end_idx = min(round(end * fps), max_frame)
521
+ seg_size = float(end_idx - start_idx) / num_segments
522
+ frame_indices = np.array([
523
+ int(start_idx + (seg_size / 2) + np.round(seg_size * idx))
524
+ for idx in range(num_segments)
525
+ ])
526
+ return frame_indices
527
+
528
+ def load_video(video_path, bound=None, input_size=448, max_num=1, num_segments=32):
529
+ vr = VideoReader(video_path, ctx=cpu(0), num_threads=1)
530
+ max_frame = len(vr) - 1
531
+ fps = float(vr.get_avg_fps())
532
+
533
+ pixel_values_list, num_patches_list = [], []
534
+ transform = build_transform(input_size=input_size)
535
+ frame_indices = get_index(bound, fps, max_frame, first_idx=0, num_segments=num_segments)
536
+ for frame_index in frame_indices:
537
+ img = Image.fromarray(vr[frame_index].asnumpy()).convert('RGB')
538
+ img = dynamic_preprocess(img, image_size=input_size, use_thumbnail=True, max_num=max_num)
539
+ pixel_values = [transform(tile) for tile in img]
540
+ pixel_values = torch.stack(pixel_values)
541
+ num_patches_list.append(pixel_values.shape[0])
542
+ pixel_values_list.append(pixel_values)
543
+ pixel_values = torch.cat(pixel_values_list)
544
+ return pixel_values, num_patches_list
545
+
546
+ video_path = './examples/red-panda.mp4'
547
+ pixel_values, num_patches_list = load_video(video_path, num_segments=8, max_num=1)
548
+ pixel_values = pixel_values.to(torch.bfloat16).cuda()
549
+ video_prefix = ''.join([f'Frame{i+1}: <image>\n' for i in range(len(num_patches_list))])
550
+ question = video_prefix + 'What is the red panda doing?'
551
+ # Frame1: <image>\nFrame2: <image>\n...\nFrame8: <image>\n{question}
552
+ response, history = model.chat(tokenizer, pixel_values, question, generation_config,
553
+ num_patches_list=num_patches_list, history=None, return_history=True)
554
+ print(f'User: {question}\nAssistant: {response}')
555
+
556
+ question = 'Describe this video in detail. Don\'t repeat.'
557
+ response, history = model.chat(tokenizer, pixel_values, question, generation_config,
558
+ num_patches_list=num_patches_list, history=history, return_history=True)
559
+ print(f'User: {question}\nAssistant: {response}')
560
+ ```
561
+
562
+ #### Streaming output
563
+
564
+ Besides this method, you can also use the following code to get streamed output.
565
+
566
+ ```python
567
+ from transformers import TextIteratorStreamer
568
+ from threading import Thread
569
+
570
+ # Initialize the streamer
571
+ streamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True, timeout=10)
572
+ # Define the generation configuration
573
+ generation_config = dict(max_new_tokens=1024, do_sample=False, streamer=streamer)
574
+ # Start the model chat in a separate thread
575
+ thread = Thread(target=model.chat, kwargs=dict(
576
+ tokenizer=tokenizer, pixel_values=pixel_values, question=question,
577
+ history=None, return_history=False, generation_config=generation_config,
578
+ ))
579
+ thread.start()
580
+
581
+ # Initialize an empty string to store the generated text
582
+ generated_text = ''
583
+ # Loop through the streamer to get the new text as it is generated
584
+ for new_text in streamer:
585
+ if new_text == model.conv_template.sep:
586
+ break
587
+ generated_text += new_text
588
+ print(new_text, end='', flush=True) # Print each new chunk of generated text on the same line
589
+ ```
590
+
591
+ ## Finetune
592
+
593
+ 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.
594
+
595
+ ## Deployment
596
+
597
+ ### LMDeploy
598
+
599
+ LMDeploy is a toolkit for compressing, deploying, and serving LLM, developed by the MMRazor and MMDeploy teams.
600
+
601
+ ```sh
602
+ pip install lmdeploy>=0.5.3
603
+ ```
604
+
605
+ 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.
606
+
607
+ #### A 'Hello, world' example
608
+
609
+ ```python
610
+ from lmdeploy import pipeline, TurbomindEngineConfig
611
+ from lmdeploy.vl import load_image
612
+
613
+ model = 'OpenGVLab/InternVL2_5-4B'
614
+ image = load_image('https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/tests/data/tiger.jpeg')
615
+ pipe = pipeline(model, backend_config=TurbomindEngineConfig(session_len=8192))
616
+ response = pipe(('describe this image', image))
617
+ print(response.text)
618
+ ```
619
+
620
+ If `ImportError` occurs while executing this case, please install the required dependency packages as prompted.
621
+
622
+ #### Multi-images inference
623
+
624
+ 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.
625
+
626
+ > Warning: Due to the scarcity of multi-image conversation data, the performance on multi-image tasks may be unstable, and it may require multiple attempts to achieve satisfactory results.
627
+
628
+ ```python
629
+ from lmdeploy import pipeline, TurbomindEngineConfig
630
+ from lmdeploy.vl import load_image
631
+ from lmdeploy.vl.constants import IMAGE_TOKEN
632
+
633
+ model = 'OpenGVLab/InternVL2_5-4B'
634
+ pipe = pipeline(model, backend_config=TurbomindEngineConfig(session_len=8192))
635
+
636
+ image_urls=[
637
+ 'https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/human-pose.jpg',
638
+ 'https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/det.jpg'
639
+ ]
640
+
641
+ images = [load_image(img_url) for img_url in image_urls]
642
+ # Numbering images improves multi-image conversations
643
+ response = pipe((f'Image-1: {IMAGE_TOKEN}\nImage-2: {IMAGE_TOKEN}\ndescribe these two images', images))
644
+ print(response.text)
645
+ ```
646
+
647
+ #### Batch prompts inference
648
+
649
+ Conducting inference with batch prompts is quite straightforward; just place them within a list structure:
650
+
651
+ ```python
652
+ from lmdeploy import pipeline, TurbomindEngineConfig
653
+ from lmdeploy.vl import load_image
654
+
655
+ model = 'OpenGVLab/InternVL2_5-4B'
656
+ pipe = pipeline(model, backend_config=TurbomindEngineConfig(session_len=8192))
657
+
658
+ image_urls=[
659
+ "https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/human-pose.jpg",
660
+ "https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/det.jpg"
661
+ ]
662
+ prompts = [('describe this image', load_image(img_url)) for img_url in image_urls]
663
+ response = pipe(prompts)
664
+ print(response)
665
+ ```
666
+
667
+ #### Multi-turn conversation
668
+
669
+ 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.
670
+
671
+ ```python
672
+ from lmdeploy import pipeline, TurbomindEngineConfig, GenerationConfig
673
+ from lmdeploy.vl import load_image
674
+
675
+ model = 'OpenGVLab/InternVL2_5-4B'
676
+ pipe = pipeline(model, backend_config=TurbomindEngineConfig(session_len=8192))
677
+
678
+ image = load_image('https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/human-pose.jpg')
679
+ gen_config = GenerationConfig(top_k=40, top_p=0.8, temperature=0.8)
680
+ sess = pipe.chat(('describe this image', image), gen_config=gen_config)
681
+ print(sess.response.text)
682
+ sess = pipe.chat('What is the woman doing?', session=sess, gen_config=gen_config)
683
+ print(sess.response.text)
684
+ ```
685
+
686
+ #### Service
687
+
688
+ 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:
689
+
690
+ ```shell
691
+ lmdeploy serve api_server OpenGVLab/InternVL2_5-4B --backend turbomind --server-port 23333
692
+ ```
693
+
694
+ To use the OpenAI-style interface, you need to install OpenAI:
695
+
696
+ ```shell
697
+ pip install openai
698
+ ```
699
+
700
+ Then, use the code below to make the API call:
701
+
702
+ ```python
703
+ from openai import OpenAI
704
+
705
+ client = OpenAI(api_key='YOUR_API_KEY', base_url='http://0.0.0.0:23333/v1')
706
+ model_name = client.models.list().data[0].id
707
+ response = client.chat.completions.create(
708
+ model=model_name,
709
+ messages=[{
710
+ 'role':
711
+ 'user',
712
+ 'content': [{
713
+ 'type': 'text',
714
+ 'text': 'describe this image',
715
+ }, {
716
+ 'type': 'image_url',
717
+ 'image_url': {
718
+ 'url':
719
+ 'https://modelscope.oss-cn-beijing.aliyuncs.com/resource/tiger.jpeg',
720
+ },
721
+ }],
722
+ }],
723
+ temperature=0.8,
724
+ top_p=0.8)
725
+ print(response)
726
+ ```
727
+
728
+ ## License
729
+
730
+ This project is released under the MIT license, while Qwen2 is licensed under the Tongyi Qianwen LICENSE.
731
+
732
+ ## Citation
733
+
734
+ If you find this project useful in your research, please consider citing:
735
+
736
+ ```BibTeX
737
+ @article{chen2023internvl,
738
+ title={InternVL: Scaling up Vision Foundation Models and Aligning for Generic Visual-Linguistic Tasks},
739
+ 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 Li, Bin and Luo, Ping and Lu, Tong and Qiao, Yu and Dai, Jifeng},
740
+ journal={arXiv preprint arXiv:2312.14238},
741
+ year={2023}
742
+ }
743
+ @article{chen2024far,
744
+ title={How Far Are We to GPT-4V? Closing the Gap to Commercial Multimodal Models with Open-Source Suites},
745
+ 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},
746
+ journal={arXiv preprint arXiv:2404.16821},
747
+ year={2024}
748
+ }
749
+ @article{gao2024mini,
750
+ title={Mini-internvl: A flexible-transfer pocket multimodal model with 5\% parameters and 90\% performance},
751
+ 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},
752
+ journal={arXiv preprint arXiv:2410.16261},
753
+ year={2024}
754
+ }
755
+ ```
756
+