zwgao commited on
Commit
8308a36
1 Parent(s): a90afc2

Update README.md

Browse files
Files changed (1) hide show
  1. README.md +722 -3
README.md CHANGED
@@ -1,3 +1,722 @@
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-0.5B-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-1B
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/png](https://cdn-uploads.huggingface.co/production/uploads/64119264f0f81eb569e0d569/_mLpMwsav5eMeNcZdrIQl.png)
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-1B** 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-1B consists of [InternViT-300M-448px-V2_5](https://huggingface.co/OpenGVLab/InternViT-300M-448px-V2_5), an MLP projector, and [Qwen2.5-0.5B-Instruct](https://huggingface.co/Qwen/Qwen2.5-0.5B-Instruct).
50
+
51
+ ## Performance
52
+
53
+ ### Image Benchmarks
54
+
55
+ | Benchmark | LLaVA-OneVision-0.5B | InternVL2-1B | InternVL2.5-1B | Qwen2-VL-2B | Aquila-VL-2B | InternVL2-2B | InternVL2.5-2B |
56
+ |---------------------|----------------------|--------------|----------------|-------------|--------------|--------------|----------------|
57
+ | MMMU (val) | 31.4 | 36.7 | 40.9 | 41.1 | 47.4 | 36.3 | 43.6 |
58
+ | MMMU (test) | - | 32.8 | 35.8 | - | - | 34.7 | 38.2 |
59
+ | MMMU-PRO (overall) | - | 14.8 | 19.4 | 21.2 | 26.2 | - | 23.7 |
60
+ | MathVista (mini) | 34.8 | 37.7 | 43.2 | 43.0 | 59.0 | 46.3 | 51.3 |
61
+ | MathVision (mini) | - | 12.2 | 16.8 | 19.7 | 21.1 | 15.8 | 13.5 |
62
+ | MathVision (full) | - | 11.1 | 14.4 | 12.4 | 18.4 | 12.1 | 14.7 |
63
+ | MathVerse (mini) | 17.9 | 18.4 | 28.0 | 21.0 | 26.2 | 25.3 | 30.6 |
64
+ | Olympiad Bench | - | 0.3 | 1.7 | - | - | 0.4 | 2.0 |
65
+ | AI2D (w / wo M) | 57.1 / - | 64.1 / 70.5 | 69.3 / 77.8 | 74.7 / 84.6 | 75.0 / - | 74.1 / 82.3 | 74.9 / 83.5 |
66
+ | ChartQA (test avg.) | 61.4 | 72.9 | 75.9 | 73.5 | 76.5 | 76.2 | 79.2 |
67
+ | TextVQA (val) | - | 70.5 | 72.0 | 79.7 | 76.4 | 73.4 | 74.3 |
68
+ | DocVQA (test) | 70.0 | 81.7 | 84.8 | 90.1 | 85.0 | 86.9 | 88.7 |
69
+ | InfoVQA (test) | 41.8 | 50.9 | 56.0 | 65.5 | 58.3 | 58.9 | 60.9 |
70
+ | OCR-Bench | 565 | 754 | 785 | 809 | 772 | 784 | 804 |
71
+ | SEED-2 Plus | - | 54.3 | 59.0 | 62.4 | 63.0 | 60.0 | 60.9 |
72
+ | CharXiv (RQ / DQ) | - | 18.1 / 30.7 | 19.0 / 38.4 | - | - | 21.0 / 40.6 | 21.3 / 49.7 |
73
+ | VCR-EN-Easy (EM / Jaccard) | - | 21.5 / 48.4 | 91.5 / 97.0 | 81.5 / - | 70.0 / - | 32.9 / 59.2 | 93.2 / 97.6 |
74
+ | BLINK (val) | 52.1 | 38.6 | 42.0 | 44.4 | | 43.8 | 44.0 |
75
+ | Mantis Eval | 39.6 | 46.1 | 51.2 | - | - |48.4 | 54.8 |
76
+ | MMIU | - | 37.3 | 38.5 | - | - |39.8 | 43.5 |
77
+ | Muir Bench | 25.5 | 29.3 | 29.9 | - | - |32.5 | 40.6 |
78
+ | MMT (val) | - | 49.5 | 50.3 | 55.1 | - | 50.4 | 54.5 |
79
+ | MIRB (avg.) | - | 31.5 | 35.6 | - | - | 32.1 | 36.4 |
80
+ | RealWorld QA | 55.6 | 50.3 | 57.5 | 62.6 | - |57.3 | 60.1 |
81
+ | MME-RW (EN) | - | 40.2 | 44.2 | - | - |47.3 | 48.8 |
82
+ | WildVision (win rate)| - | 17.8 | 43.4 | - | - |31.8 | 44.2 |
83
+ | R-Bench | - | 55.6 | 59.0 | - |- | 56.8 | 62.2 |
84
+ | MME (sum) | 1438.0 | 1794.4 | 1950.5 | 1872.0 | - | 1876.8 | 2138.2 |
85
+ | MMB (EN / CN) | 61.6 / 55.5 | 65.4 / 60.7 | 70.7 / 66.3 | 74.9 / 73.5 | - |73.2 / 70.9 | 74.7 / 71.9 |
86
+ | MMBv1.1 (EN) | 59.6 | 61.6 | 68.4 | 72.2 | - |70.2 | 72.2 |
87
+ | MMVet (turbo) | 32.2 | 32.7 | 48.8 | 49.5 | - |39.5 | 60.8 |
88
+ | MMVetv2 (0613) | - | 36.1 | 43.2 | - | - |39.6 | 52.3 |
89
+ | MMStar | 37.7 | 45.7 | 50.1 | 48.0 | - |50.1 | 53.7 |
90
+ | HallBench (avg.) | 27.9 | 34.0 | 39.0 | 41.7 | - |37.9 | 42.6 |
91
+ | MMHal (score) | - | 2.25 | 2.49 | - | - |2.52 | 2.94 |
92
+ | CRPE (relation) | - | 57.5 | 60.9 | - | - |66.3 | 70.2 |
93
+ | POPE (avg.) | - | 87.3 | 89.9 | - | - |88.3 | 90.6 |
94
+
95
+
96
+ ### Video Benchmarks
97
+
98
+ ### Multimodal Multilingual Understanding
99
+
100
+ <table>
101
+ <tr>
102
+ <td rowspan="2">Model Name</td>
103
+ <td colspan="6">MMMB</td>
104
+ <td colspan="6">MultiMMB</td>
105
+ <td>MTVQA</td>
106
+ </tr>
107
+ <tr>
108
+ <td>en</td>
109
+ <td>zh</td>
110
+ <td>pt</td>
111
+ <td>ar</td>
112
+ <td>tr</td>
113
+ <td>ru</td>
114
+ <td>en</td>
115
+ <td>zh</td>
116
+ <td>pt</td>
117
+ <td>ar</td>
118
+ <td>tr</td>
119
+ <td>ru</td>
120
+ <td>(avg)</td>
121
+ </tr>
122
+ <tr>
123
+ <td>InternVL2-1B</td>
124
+ <td>73.2</td>
125
+ <td>67.4</td>
126
+ <td>55.5</td>
127
+ <td>53.5</td>
128
+ <td>43.8</td>
129
+ <td>55.2</td>
130
+ <td>67.9</td>
131
+ <td>61.2</td>
132
+ <td>50.8</td>
133
+ <td>43.3</td>
134
+ <td>31.8</td>
135
+ <td>52.7</td>
136
+ <td>12.6</td>
137
+ </tr>
138
+ <tr>
139
+ <td>InternVL2.5-1B</td>
140
+ <td>78.8</td>
141
+ <td>70.2</td>
142
+ <td>61.5</td>
143
+ <td>55.0</td>
144
+ <td>45.3</td>
145
+ <td>61.1</td>
146
+ <td>72.5</td>
147
+ <td>64.7</td>
148
+ <td>57.0</td>
149
+ <td>43.0</td>
150
+ <td>37.8</td>
151
+ <td>53.2</td>
152
+ <td>21.4</td>
153
+ </tr>
154
+ <tr>
155
+ <td>Qwen2-VL-2B</td>
156
+ <td>78.3</td>
157
+ <td>74.2</td>
158
+ <td>72.6</td>
159
+ <td>68.3</td>
160
+ <td>61.8</td>
161
+ <td>72.8</td>
162
+ <td>72.1</td>
163
+ <td>71.1</td>
164
+ <td>69.9</td>
165
+ <td>61.1</td>
166
+ <td>54.4</td>
167
+ <td>69.3</td>
168
+ <td>20.0</td>
169
+ </tr>
170
+ <tr>
171
+ <td>InternVL2-2B</td>
172
+ <td>79.4</td>
173
+ <td>71.6</td>
174
+ <td>54.0</td>
175
+ <td>43.5</td>
176
+ <td>46.4</td>
177
+ <td>48.1</td>
178
+ <td>73.8</td>
179
+ <td>69.6</td>
180
+ <td>51.4</td>
181
+ <td>29.8</td>
182
+ <td>31.3</td>
183
+ <td>42.3</td>
184
+ <td>10.9</td>
185
+ </tr>
186
+ <tr>
187
+ <td>InternVL2.5-2B</td>
188
+ <td>81.4</td>
189
+ <td>74.4</td>
190
+ <td>58.2</td>
191
+ <td>48.3</td>
192
+ <td>46.4</td>
193
+ <td>53.2</td>
194
+ <td>76.5</td>
195
+ <td>71.6</td>
196
+ <td>55.9</td>
197
+ <td>37.3</td>
198
+ <td>33.9</td>
199
+ <td>44.8</td>
200
+ <td>21.8</td>
201
+ </tr>
202
+ </table>
203
+
204
+
205
+ ### Invitation to Evaluate InternVL
206
+
207
+ We welcome MLLM benchmark developers to assess our InternVL series models. If you need to add your evaluation results here, please contact me at [[email protected]](mailto:[email protected]).
208
+
209
+ ## Quick Start
210
+
211
+ We provide an example code to run InternVL2_5-1B using `transformers`.
212
+
213
+ We also welcome you to experience the InternVL2_5 series models in our [online demo](https://internvl.opengvlab.com/).
214
+
215
+ > Please use transformers ≳ 4.37.2 to ensure the model works normally.
216
+
217
+ ### Model Loading
218
+
219
+ #### 16-bit (bf16 / fp16)
220
+
221
+ ```python
222
+ import torch
223
+ from transformers import AutoTokenizer, AutoModel
224
+ path = "OpenGVLab/InternVL2_5-1B"
225
+ model = AutoModel.from_pretrained(
226
+ path,
227
+ torch_dtype=torch.bfloat16,
228
+ low_cpu_mem_usage=True,
229
+ use_flash_attn=True,
230
+ trust_remote_code=True).eval().cuda()
231
+ ```
232
+
233
+ #### BNB 8-bit Quantization
234
+
235
+ ```python
236
+ import torch
237
+ from transformers import AutoTokenizer, AutoModel
238
+ path = "OpenGVLab/InternVL2_5-1B"
239
+ model = AutoModel.from_pretrained(
240
+ path,
241
+ torch_dtype=torch.bfloat16,
242
+ load_in_8bit=True,
243
+ low_cpu_mem_usage=True,
244
+ use_flash_attn=True,
245
+ trust_remote_code=True).eval()
246
+ ```
247
+
248
+ #### BNB 4-bit Quantization
249
+
250
+ ```python
251
+ import torch
252
+ from transformers import AutoTokenizer, AutoModel
253
+ path = "OpenGVLab/InternVL2_5-1B"
254
+ model = AutoModel.from_pretrained(
255
+ path,
256
+ torch_dtype=torch.bfloat16,
257
+ load_in_4bit=True,
258
+ low_cpu_mem_usage=True,
259
+ use_flash_attn=True,
260
+ trust_remote_code=True).eval()
261
+ ```
262
+
263
+ #### Multiple GPUs
264
+
265
+ 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.
266
+
267
+ ```python
268
+ import math
269
+ import torch
270
+ from transformers import AutoTokenizer, AutoModel
271
+
272
+ def split_model(model_name):
273
+ device_map = {}
274
+ world_size = torch.cuda.device_count()
275
+ num_layers = {
276
+ 'InternVL2_5-1B': 24, 'InternVL_5-2B': 24, 'InternVL2_5-4B': 36, 'InternVL2_5-8B': 32,
277
+ 'InternVL2_5-26B': 48, 'InternVL2_5-38B': 64, 'InternVL2_5-78B': 80}[model_name]
278
+ # Since the first GPU will be used for ViT, treat it as half a GPU.
279
+ num_layers_per_gpu = math.ceil(num_layers / (world_size - 0.5))
280
+ num_layers_per_gpu = [num_layers_per_gpu] * world_size
281
+ num_layers_per_gpu[0] = math.ceil(num_layers_per_gpu[0] * 0.5)
282
+ layer_cnt = 0
283
+ for i, num_layer in enumerate(num_layers_per_gpu):
284
+ for j in range(num_layer):
285
+ device_map[f'language_model.model.layers.{layer_cnt}'] = i
286
+ layer_cnt += 1
287
+ device_map['vision_model'] = 0
288
+ device_map['mlp1'] = 0
289
+ device_map['language_model.model.tok_embeddings'] = 0
290
+ device_map['language_model.model.embed_tokens'] = 0
291
+ device_map['language_model.output'] = 0
292
+ device_map['language_model.model.norm'] = 0
293
+ device_map['language_model.lm_head'] = 0
294
+ device_map[f'language_model.model.layers.{num_layers - 1}'] = 0
295
+
296
+ return device_map
297
+
298
+ path = "OpenGVLab/InternVL2_5-1B"
299
+ device_map = split_model('InternVL2_5-1B')
300
+ model = AutoModel.from_pretrained(
301
+ path,
302
+ torch_dtype=torch.bfloat16,
303
+ low_cpu_mem_usage=True,
304
+ use_flash_attn=True,
305
+ trust_remote_code=True,
306
+ device_map=device_map).eval()
307
+ ```
308
+
309
+ ### Inference with Transformers
310
+
311
+ ```python
312
+ import numpy as np
313
+ import torch
314
+ import torchvision.transforms as T
315
+ from decord import VideoReader, cpu
316
+ from PIL import Image
317
+ from torchvision.transforms.functional import InterpolationMode
318
+ from transformers import AutoModel, AutoTokenizer
319
+
320
+ IMAGENET_MEAN = (0.485, 0.456, 0.406)
321
+ IMAGENET_STD = (0.229, 0.224, 0.225)
322
+
323
+ def build_transform(input_size):
324
+ MEAN, STD = IMAGENET_MEAN, IMAGENET_STD
325
+ transform = T.Compose([
326
+ T.Lambda(lambda img: img.convert('RGB') if img.mode != 'RGB' else img),
327
+ T.Resize((input_size, input_size), interpolation=InterpolationMode.BICUBIC),
328
+ T.ToTensor(),
329
+ T.Normalize(mean=MEAN, std=STD)
330
+ ])
331
+ return transform
332
+
333
+ def find_closest_aspect_ratio(aspect_ratio, target_ratios, width, height, image_size):
334
+ best_ratio_diff = float('inf')
335
+ best_ratio = (1, 1)
336
+ area = width * height
337
+ for ratio in target_ratios:
338
+ target_aspect_ratio = ratio[0] / ratio[1]
339
+ ratio_diff = abs(aspect_ratio - target_aspect_ratio)
340
+ if ratio_diff < best_ratio_diff:
341
+ best_ratio_diff = ratio_diff
342
+ best_ratio = ratio
343
+ elif ratio_diff == best_ratio_diff:
344
+ if area > 0.5 * image_size * image_size * ratio[0] * ratio[1]:
345
+ best_ratio = ratio
346
+ return best_ratio
347
+
348
+ def dynamic_preprocess(image, min_num=1, max_num=12, image_size=448, use_thumbnail=False):
349
+ orig_width, orig_height = image.size
350
+ aspect_ratio = orig_width / orig_height
351
+
352
+ # calculate the existing image aspect ratio
353
+ target_ratios = set(
354
+ (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
355
+ i * j <= max_num and i * j >= min_num)
356
+ target_ratios = sorted(target_ratios, key=lambda x: x[0] * x[1])
357
+
358
+ # find the closest aspect ratio to the target
359
+ target_aspect_ratio = find_closest_aspect_ratio(
360
+ aspect_ratio, target_ratios, orig_width, orig_height, image_size)
361
+
362
+ # calculate the target width and height
363
+ target_width = image_size * target_aspect_ratio[0]
364
+ target_height = image_size * target_aspect_ratio[1]
365
+ blocks = target_aspect_ratio[0] * target_aspect_ratio[1]
366
+
367
+ # resize the image
368
+ resized_img = image.resize((target_width, target_height))
369
+ processed_images = []
370
+ for i in range(blocks):
371
+ box = (
372
+ (i % (target_width // image_size)) * image_size,
373
+ (i // (target_width // image_size)) * image_size,
374
+ ((i % (target_width // image_size)) + 1) * image_size,
375
+ ((i // (target_width // image_size)) + 1) * image_size
376
+ )
377
+ # split the image
378
+ split_img = resized_img.crop(box)
379
+ processed_images.append(split_img)
380
+ assert len(processed_images) == blocks
381
+ if use_thumbnail and len(processed_images) != 1:
382
+ thumbnail_img = image.resize((image_size, image_size))
383
+ processed_images.append(thumbnail_img)
384
+ return processed_images
385
+
386
+ def load_image(image_file, input_size=448, max_num=12):
387
+ image = Image.open(image_file).convert('RGB')
388
+ transform = build_transform(input_size=input_size)
389
+ images = dynamic_preprocess(image, image_size=input_size, use_thumbnail=True, max_num=max_num)
390
+ pixel_values = [transform(image) for image in images]
391
+ pixel_values = torch.stack(pixel_values)
392
+ return pixel_values
393
+
394
+ # If you want to load a model using multiple GPUs, please refer to the `Multiple GPUs` section.
395
+ path = 'OpenGVLab/InternVL2_5-1B'
396
+ model = AutoModel.from_pretrained(
397
+ path,
398
+ torch_dtype=torch.bfloat16,
399
+ low_cpu_mem_usage=True,
400
+ use_flash_attn=True,
401
+ trust_remote_code=True).eval().cuda()
402
+ tokenizer = AutoTokenizer.from_pretrained(path, trust_remote_code=True, use_fast=False)
403
+
404
+ # set the max number of tiles in `max_num`
405
+ pixel_values = load_image('./examples/image1.jpg', max_num=12).to(torch.bfloat16).cuda()
406
+ generation_config = dict(max_new_tokens=1024, do_sample=True)
407
+
408
+ # pure-text conversation (纯文本对话)
409
+ question = 'Hello, who are you?'
410
+ response, history = model.chat(tokenizer, None, question, generation_config, history=None, return_history=True)
411
+ print(f'User: {question}\nAssistant: {response}')
412
+
413
+ question = 'Can you tell me a story?'
414
+ response, history = model.chat(tokenizer, None, question, generation_config, history=history, return_history=True)
415
+ print(f'User: {question}\nAssistant: {response}')
416
+
417
+ # single-image single-round conversation (单图单轮对话)
418
+ question = '<image>\nPlease describe the image shortly.'
419
+ response = model.chat(tokenizer, pixel_values, question, generation_config)
420
+ print(f'User: {question}\nAssistant: {response}')
421
+
422
+ # single-image multi-round conversation (单图多轮对话)
423
+ question = '<image>\nPlease describe the image in detail.'
424
+ response, history = model.chat(tokenizer, pixel_values, question, generation_config, history=None, return_history=True)
425
+ print(f'User: {question}\nAssistant: {response}')
426
+
427
+ question = 'Please write a poem according to the image.'
428
+ response, history = model.chat(tokenizer, pixel_values, question, generation_config, history=history, return_history=True)
429
+ print(f'User: {question}\nAssistant: {response}')
430
+
431
+ # multi-image multi-round conversation, combined images (多图多轮对话,拼接图像)
432
+ pixel_values1 = load_image('./examples/image1.jpg', max_num=12).to(torch.bfloat16).cuda()
433
+ pixel_values2 = load_image('./examples/image2.jpg', max_num=12).to(torch.bfloat16).cuda()
434
+ pixel_values = torch.cat((pixel_values1, pixel_values2), dim=0)
435
+
436
+ question = '<image>\nDescribe the two images in detail.'
437
+ response, history = model.chat(tokenizer, pixel_values, question, generation_config,
438
+ history=None, return_history=True)
439
+ print(f'User: {question}\nAssistant: {response}')
440
+
441
+ question = 'What are the similarities and differences between these two images.'
442
+ response, history = model.chat(tokenizer, pixel_values, question, generation_config,
443
+ history=history, return_history=True)
444
+ print(f'User: {question}\nAssistant: {response}')
445
+
446
+ # multi-image multi-round conversation, separate images (多图多轮对话,独立图像)
447
+ pixel_values1 = load_image('./examples/image1.jpg', max_num=12).to(torch.bfloat16).cuda()
448
+ pixel_values2 = load_image('./examples/image2.jpg', max_num=12).to(torch.bfloat16).cuda()
449
+ pixel_values = torch.cat((pixel_values1, pixel_values2), dim=0)
450
+ num_patches_list = [pixel_values1.size(0), pixel_values2.size(0)]
451
+
452
+ question = 'Image-1: <image>\nImage-2: <image>\nDescribe the two images in detail.'
453
+ response, history = model.chat(tokenizer, pixel_values, question, generation_config,
454
+ num_patches_list=num_patches_list,
455
+ history=None, return_history=True)
456
+ print(f'User: {question}\nAssistant: {response}')
457
+
458
+ question = 'What are the similarities and differences between these two images.'
459
+ response, history = model.chat(tokenizer, pixel_values, question, generation_config,
460
+ num_patches_list=num_patches_list,
461
+ history=history, return_history=True)
462
+ print(f'User: {question}\nAssistant: {response}')
463
+
464
+ # batch inference, single image per sample (单图批处理)
465
+ pixel_values1 = load_image('./examples/image1.jpg', max_num=12).to(torch.bfloat16).cuda()
466
+ pixel_values2 = load_image('./examples/image2.jpg', max_num=12).to(torch.bfloat16).cuda()
467
+ num_patches_list = [pixel_values1.size(0), pixel_values2.size(0)]
468
+ pixel_values = torch.cat((pixel_values1, pixel_values2), dim=0)
469
+
470
+ questions = ['<image>\nDescribe the image in detail.'] * len(num_patches_list)
471
+ responses = model.batch_chat(tokenizer, pixel_values,
472
+ num_patches_list=num_patches_list,
473
+ questions=questions,
474
+ generation_config=generation_config)
475
+ for question, response in zip(questions, responses):
476
+ print(f'User: {question}\nAssistant: {response}')
477
+
478
+ # video multi-round conversation (视频多轮对话)
479
+ def get_index(bound, fps, max_frame, first_idx=0, num_segments=32):
480
+ if bound:
481
+ start, end = bound[0], bound[1]
482
+ else:
483
+ start, end = -100000, 100000
484
+ start_idx = max(first_idx, round(start * fps))
485
+ end_idx = min(round(end * fps), max_frame)
486
+ seg_size = float(end_idx - start_idx) / num_segments
487
+ frame_indices = np.array([
488
+ int(start_idx + (seg_size / 2) + np.round(seg_size * idx))
489
+ for idx in range(num_segments)
490
+ ])
491
+ return frame_indices
492
+
493
+ def load_video(video_path, bound=None, input_size=448, max_num=1, num_segments=32):
494
+ vr = VideoReader(video_path, ctx=cpu(0), num_threads=1)
495
+ max_frame = len(vr) - 1
496
+ fps = float(vr.get_avg_fps())
497
+
498
+ pixel_values_list, num_patches_list = [], []
499
+ transform = build_transform(input_size=input_size)
500
+ frame_indices = get_index(bound, fps, max_frame, first_idx=0, num_segments=num_segments)
501
+ for frame_index in frame_indices:
502
+ img = Image.fromarray(vr[frame_index].asnumpy()).convert('RGB')
503
+ img = dynamic_preprocess(img, image_size=input_size, use_thumbnail=True, max_num=max_num)
504
+ pixel_values = [transform(tile) for tile in img]
505
+ pixel_values = torch.stack(pixel_values)
506
+ num_patches_list.append(pixel_values.shape[0])
507
+ pixel_values_list.append(pixel_values)
508
+ pixel_values = torch.cat(pixel_values_list)
509
+ return pixel_values, num_patches_list
510
+
511
+ video_path = './examples/red-panda.mp4'
512
+ pixel_values, num_patches_list = load_video(video_path, num_segments=8, max_num=1)
513
+ pixel_values = pixel_values.to(torch.bfloat16).cuda()
514
+ video_prefix = ''.join([f'Frame{i+1}: <image>\n' for i in range(len(num_patches_list))])
515
+ question = video_prefix + 'What is the red panda doing?'
516
+ # Frame1: <image>\nFrame2: <image>\n...\nFrame8: <image>\n{question}
517
+ response, history = model.chat(tokenizer, pixel_values, question, generation_config,
518
+ num_patches_list=num_patches_list, history=None, return_history=True)
519
+ print(f'User: {question}\nAssistant: {response}')
520
+
521
+ question = 'Describe this video in detail. Don\'t repeat.'
522
+ response, history = model.chat(tokenizer, pixel_values, question, generation_config,
523
+ num_patches_list=num_patches_list, history=history, return_history=True)
524
+ print(f'User: {question}\nAssistant: {response}')
525
+ ```
526
+
527
+ #### Streaming output
528
+
529
+ Besides this method, you can also use the following code to get streamed output.
530
+
531
+ ```python
532
+ from transformers import TextIteratorStreamer
533
+ from threading import Thread
534
+
535
+ # Initialize the streamer
536
+ streamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True, timeout=10)
537
+ # Define the generation configuration
538
+ generation_config = dict(max_new_tokens=1024, do_sample=False, streamer=streamer)
539
+ # Start the model chat in a separate thread
540
+ thread = Thread(target=model.chat, kwargs=dict(
541
+ tokenizer=tokenizer, pixel_values=pixel_values, question=question,
542
+ history=None, return_history=False, generation_config=generation_config,
543
+ ))
544
+ thread.start()
545
+
546
+ # Initialize an empty string to store the generated text
547
+ generated_text = ''
548
+ # Loop through the streamer to get the new text as it is generated
549
+ for new_text in streamer:
550
+ if new_text == model.conv_template.sep:
551
+ break
552
+ generated_text += new_text
553
+ print(new_text, end='', flush=True) # Print each new chunk of generated text on the same line
554
+ ```
555
+
556
+ ## Finetune
557
+
558
+ 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.
559
+
560
+ ## Deployment
561
+
562
+ ### LMDeploy
563
+
564
+ LMDeploy is a toolkit for compressing, deploying, and serving LLM, developed by the MMRazor and MMDeploy teams.
565
+
566
+ ```sh
567
+ pip install lmdeploy>=0.5.3
568
+ ```
569
+
570
+ 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.
571
+
572
+ #### A 'Hello, world' example
573
+
574
+ ```python
575
+ from lmdeploy import pipeline, TurbomindEngineConfig
576
+ from lmdeploy.vl import load_image
577
+
578
+ model = 'OpenGVLab/InternVL2_5-1B'
579
+ image = load_image('https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/tests/data/tiger.jpeg')
580
+ pipe = pipeline(model, backend_config=TurbomindEngineConfig(session_len=8192))
581
+ response = pipe(('describe this image', image))
582
+ print(response.text)
583
+ ```
584
+
585
+ If `ImportError` occurs while executing this case, please install the required dependency packages as prompted.
586
+
587
+ #### Multi-images inference
588
+
589
+ 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.
590
+
591
+ > 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.
592
+
593
+ ```python
594
+ from lmdeploy import pipeline, TurbomindEngineConfig
595
+ from lmdeploy.vl import load_image
596
+ from lmdeploy.vl.constants import IMAGE_TOKEN
597
+
598
+ model = 'OpenGVLab/InternVL2_5-1B'
599
+ pipe = pipeline(model, backend_config=TurbomindEngineConfig(session_len=8192))
600
+
601
+ image_urls=[
602
+ 'https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/human-pose.jpg',
603
+ 'https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/det.jpg'
604
+ ]
605
+
606
+ images = [load_image(img_url) for img_url in image_urls]
607
+ # Numbering images improves multi-image conversations
608
+ response = pipe((f'Image-1: {IMAGE_TOKEN}\nImage-2: {IMAGE_TOKEN}\ndescribe these two images', images))
609
+ print(response.text)
610
+ ```
611
+
612
+ #### Batch prompts inference
613
+
614
+ Conducting inference with batch prompts is quite straightforward; just place them within a list structure:
615
+
616
+ ```python
617
+ from lmdeploy import pipeline, TurbomindEngineConfig
618
+ from lmdeploy.vl import load_image
619
+
620
+ model = 'OpenGVLab/InternVL2_5-1B'
621
+ pipe = pipeline(model, backend_config=TurbomindEngineConfig(session_len=8192))
622
+
623
+ image_urls=[
624
+ "https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/human-pose.jpg",
625
+ "https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/det.jpg"
626
+ ]
627
+ prompts = [('describe this image', load_image(img_url)) for img_url in image_urls]
628
+ response = pipe(prompts)
629
+ print(response)
630
+ ```
631
+
632
+ #### Multi-turn conversation
633
+
634
+ 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.
635
+
636
+ ```python
637
+ from lmdeploy import pipeline, TurbomindEngineConfig, GenerationConfig
638
+ from lmdeploy.vl import load_image
639
+
640
+ model = 'OpenGVLab/InternVL2_5-1B'
641
+ pipe = pipeline(model, backend_config=TurbomindEngineConfig(session_len=8192))
642
+
643
+ image = load_image('https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/human-pose.jpg')
644
+ gen_config = GenerationConfig(top_k=40, top_p=0.8, temperature=0.8)
645
+ sess = pipe.chat(('describe this image', image), gen_config=gen_config)
646
+ print(sess.response.text)
647
+ sess = pipe.chat('What is the woman doing?', session=sess, gen_config=gen_config)
648
+ print(sess.response.text)
649
+ ```
650
+
651
+ #### Service
652
+
653
+ 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:
654
+
655
+ ```shell
656
+ lmdeploy serve api_server OpenGVLab/InternVL2_5-1B --backend turbomind --server-port 23333
657
+ ```
658
+
659
+ To use the OpenAI-style interface, you need to install OpenAI:
660
+
661
+ ```shell
662
+ pip install openai
663
+ ```
664
+
665
+ Then, use the code below to make the API call:
666
+
667
+ ```python
668
+ from openai import OpenAI
669
+
670
+ client = OpenAI(api_key='YOUR_API_KEY', base_url='http://0.0.0.0:23333/v1')
671
+ model_name = client.models.list().data[0].id
672
+ response = client.chat.completions.create(
673
+ model=model_name,
674
+ messages=[{
675
+ 'role':
676
+ 'user',
677
+ 'content': [{
678
+ 'type': 'text',
679
+ 'text': 'describe this image',
680
+ }, {
681
+ 'type': 'image_url',
682
+ 'image_url': {
683
+ 'url':
684
+ 'https://modelscope.oss-cn-beijing.aliyuncs.com/resource/tiger.jpeg',
685
+ },
686
+ }],
687
+ }],
688
+ temperature=0.8,
689
+ top_p=0.8)
690
+ print(response)
691
+ ```
692
+
693
+ ## License
694
+
695
+ This project is released under the MIT license, while Qwen2 is licensed under the Tongyi Qianwen LICENSE.
696
+
697
+ ## Citation
698
+
699
+ If you find this project useful in your research, please consider citing:
700
+
701
+ ```BibTeX
702
+ @article{chen2023internvl,
703
+ title={InternVL: Scaling up Vision Foundation Models and Aligning for Generic Visual-Linguistic Tasks},
704
+ author={Chen, Zhe and Wu, Jiannan and Wang, Wenhai and Su, Weijie and Chen, Guo and Xing, Sen and Zhong, Muyan and Zhang, Qinglong and Zhu, Xizhou and Lu, Lewei and Li, Bin and Luo, Ping and Lu, Tong and Qiao, Yu and Dai, Jifeng},
705
+ journal={arXiv preprint arXiv:2312.14238},
706
+ year={2023}
707
+ }
708
+ @article{chen2024far,
709
+ title={How Far Are We to GPT-4V? Closing the Gap to Commercial Multimodal Models with Open-Source Suites},
710
+ author={Chen, Zhe and Wang, Weiyun and Tian, Hao and Ye, Shenglong and Gao, Zhangwei and Cui, Erfei and Tong, Wenwen and Hu, Kongzhi and Luo, Jiapeng and Ma, Zheng and others},
711
+ journal={arXiv preprint arXiv:2404.16821},
712
+ year={2024}
713
+ }
714
+ @article{gao2024mini,
715
+ title={Mini-internvl: A flexible-transfer pocket multimodal model with 5\% parameters and 90\% performance},
716
+ 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},
717
+ journal={arXiv preprint arXiv:2410.16261},
718
+ year={2024}
719
+ }
720
+
721
+ ```
722
+