zwgao commited on
Commit
f4c1979
1 Parent(s): a8b6240

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-6B-448px-V2_5
7
+ - Qwen/Qwen2.5-32B-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-38B
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-38B** 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-38B consists of [InternViT-6B-448px-V2_5](https://huggingface.co/OpenGVLab/InternViT-6B-448px-V2_5), an MLP projector, and [Qwen2.5-32B-Instruct](https://huggingface.co/Qwen/Qwen2.5-32B-Instruct).
50
+
51
+ ## Performance
52
+
53
+ ### Image Benchmarks
54
+
55
+
56
+ | Benchmark | InternVL-Chat-V1.5 | InternVL2-26B | InternVL2.5-26B | Cambrian-34B | VILA-1.5-40B | InternVL2-40B | InternVL2.5-38B |
57
+ |---------------------|------------------- |-------------- |---------------- |---------------|-------------- |----------------|----------------|
58
+ | MMMU (val) | 46.8 | 51.2 | 60.0 | 49.7 | 55.1 | 55.2 | 63.9 |
59
+ | MMMU (test) | 41.0 | 43.8 | 51.8 | - | 46.9 | 49.3 | 57.6 |
60
+ | MMMU-PRO (overall) | 24.7 | 30.0 | 37.1 | - | 25.0 | 34.2 | 46.0 |
61
+ | MathVista (mini) | 53.5 | 59.4 | 67.7 | 53.2 | 49.5 | 63.7 | 71.9 |
62
+ | MathVision (mini) | 15.8 | 23.4 | 28.0 | - | - | 21.4 | 32.2 |
63
+ | MathVision (full) | 15.0 | 17.0 | 23.1 | - | - | 16.9 | 31.8 |
64
+ | MathVerse (mini) | 28.4 | 31.1 | 40.1 | - | - | 36.3 | 49.4 |
65
+ | Olympiad Bench | 0.6 | 3.5 | 8.8 | - | - | 3.9 | 12.1 |
66
+ | AI2D (w / wo M) | 80.7 / 89.8 | 84.5 / 92.5 | 86.4 / 94.4 | 79.5 / - | 69.9 / - | 86.6 / 94.5 | 87.6 / 95.1 |
67
+ | ChartQA (test avg.) |83.8 | 84.9 | 87.2 | 75.6 | 67.2 | 86.2 | 88.2 |
68
+ | TextVQA (val) | 80.6 | 82.3 | 82.4 | 76.7 | 73.6 | 83.0 | 82.7 |
69
+ | DocVQA (test) |90.9 | 92.9 | 94.0 | 75.5 | - | 93.9 | 95.3 |
70
+ | InfoVQA (test) | 72.5 | 75.9 | 79.8 | 46.0 | - | 78.7 | 83.6 |
71
+ | OCR-Bench |724 | 825 | 852 | 600 | 460 | 837 | 842 |
72
+ | SEED-2 Plus | 66.3 | 67.6 | 70.8 | - | - | 69.2 | 71.2 |
73
+ | CharXiv (RQ / DQ) | 29.2 / 58.5 | 33.4 / 62.4 | 35.9 / 73.5 | 27.3 / 59.7 | 24.0 / 38.7 | 32.3 / 66.0 | 42.4 / 79.6 |
74
+ | VCR-EN-Easy (EM / Jaccard) |14.7 / 51.4 | 74.5 / 86.7 | 94.4 / 98.0 | 79.7 / 89.3 | - | 84.7 / 92.6 | 94.7 / 98.2 |
75
+ | BLINK (val) |46.6 | 56.2 | 61.8 | - | - | 57.2 | 63.2 |
76
+ | Mantis Eval | 66.8 | 69.6 | 75.6 | - | - |71.4 | 78.3 |
77
+ | MMIU | 37.4 | 42.6 | 49.4 | - | - | 47.9 | 55.3 |
78
+ | Muir Bench | 38.5 | 50.6 | 61.1 | - | - | 54.4 | 62.7 |
79
+ | MMT (val) | 58.0 | 60.6 | 66.9 | - | - |66.2 | 70.0 |
80
+ | MIRB (avg.) | 50.3 | 53.7 | 55.7 | - | - |55.2 | 61.2 |
81
+ | RealWorld QA | 66.0 | 68.3 | 74.5 | 67.8 | - | 71.8 | 73.5 |
82
+ | MME-RW (EN) | 49.4 | 58.7 | 61.8 | 44.1 | - |61.8 | 64.0 |
83
+ | WildVision (win rate)|56.6 | 62.2 | 65.2 | - | - | 63.2 | 66.4 |
84
+ | R-Bench | 67.9 | 70.1 | 72.9 | - | - | 73.3 | 72.1 |
85
+ | MME (sum) | 2194.2 | 2260.7 | 2373.3 | - | - | 2307.5 | 2455.8 |
86
+ | MMB (EN / CN) |82.2 / 82.0 | 83.4 / 82.0 | 85.4 / 85.5 | 80.4 / 79.2 | - | 86.8 / 86.5 | 86.5 / 86.3 |
87
+ | MMBv1.1 (EN) | 80.3 | 81.5 | 84.2 | 78.3 | - | 85.1 | 85.5 |
88
+ | MMVet (turbo) | 61.5 | 62.1 | 65.0 | 53.2 | - | 65.5 | 68.8 |
89
+ | MMVetv2 (0613) |51.5 | 57.2 | 60.8 | - | - | 63.8 | 62.1 |
90
+ | MMStar | 57.3 | 61.2 | 66.5 | 54.2 |- | 65.4 | 67.9 |
91
+ | HallBench (avg.) | 50.3 | 50.7 | 55.0 | 41.6 | - | 56.9 | 56.8 |
92
+ | MMHal (score) | 3.11 | 3.55 | 3.70 | - |- | 3.75 | 3.71 |
93
+ | CRPE (relation) | 75.4 | 75.6 | 79.1 | - | - | 77.6 | 78.3 |
94
+ | POPE (avg.) |88.4 | 88.0 | 90.6 | - |- | 88.4 | 90.7 |
95
+
96
+
97
+
98
+
99
+ ### Video Benchmarks
100
+
101
+ ### Multimodal Multilingual Understanding
102
+ <table style="width: 100%; font-size: 8px; border-collapse: collapse; text-align: center;">
103
+ <thead>
104
+ <tr>
105
+ <th rowspan="2">Model Name</th>
106
+ <th colspan="6">MMMB</th>
107
+ <th colspan="6">Multilingual MMBench</th>
108
+ <th>MTVQA</th>
109
+ </tr>
110
+ <tr>
111
+ <th>en</th>
112
+ <th>zh</th>
113
+ <th>pt</th>
114
+ <th>ar</th>
115
+ <th>tr</th>
116
+ <th>ru</th>
117
+ <th>en</th>
118
+ <th>zh</th>
119
+ <th>pt</th>
120
+ <th>ar</th>
121
+ <th>tr</th>
122
+ <th>ru</th>
123
+ <th>(avg)</th>
124
+ </tr>
125
+ </thead>
126
+ <tbody>
127
+ <tr>
128
+ <td>InternVL-Chat-V1.5</td>
129
+ <td>82.6</td>
130
+ <td>80.8</td>
131
+ <td>76.3</td>
132
+ <td>65.2</td>
133
+ <td>68.6</td>
134
+ <td>74.0</td>
135
+ <td>81.1</td>
136
+ <td>80.2</td>
137
+ <td>76.9</td>
138
+ <td>56.2</td>
139
+ <td>66.7</td>
140
+ <td>71.0</td>
141
+ <td>20.5</td>
142
+ </tr>
143
+ <tr>
144
+ <td>InternVL2-26B</td>
145
+ <td>83.8</td>
146
+ <td>81.7</td>
147
+ <td>78.0</td>
148
+ <td>68.8</td>
149
+ <td>69.3</td>
150
+ <td>76.3</td>
151
+ <td>82.7</td>
152
+ <td>81.8</td>
153
+ <td>77.8</td>
154
+ <td>61.9</td>
155
+ <td>69.6</td>
156
+ <td>74.4</td>
157
+ <td>17.7</td>
158
+ </tr>
159
+ <tr>
160
+ <td>InternVL2.5-26B</td>
161
+ <td>86.2</td>
162
+ <td>83.8</td>
163
+ <td>81.6</td>
164
+ <td>73.3</td>
165
+ <td>73.7</td>
166
+ <td>82.8</td>
167
+ <td>86.1</td>
168
+ <td>85.5</td>
169
+ <td>80.7</td>
170
+ <td>67.5</td>
171
+ <td>75.0</td>
172
+ <td>79.6</td>
173
+ <td>28.5</td>
174
+ </tr>
175
+ <tr>
176
+ <td>InternVL2-40B</td>
177
+ <td>85.3</td>
178
+ <td>84.1</td>
179
+ <td>81.1</td>
180
+ <td>70.3</td>
181
+ <td>74.2</td>
182
+ <td>81.4</td>
183
+ <td>86.2</td>
184
+ <td>85.8</td>
185
+ <td>82.8</td>
186
+ <td>64.0</td>
187
+ <td>74.2</td>
188
+ <td>81.8</td>
189
+ <td>20.6</td>
190
+ </tr>
191
+ <tr>
192
+ <td>InternVL2.5-38B</td>
193
+ <td>86.4</td>
194
+ <td>85.1</td>
195
+ <td>84.1</td>
196
+ <td>84.3</td>
197
+ <td>82.8</td>
198
+ <td>84.9</td>
199
+ <td>87.5</td>
200
+ <td>88.6</td>
201
+ <td>85.3</td>
202
+ <td>84.5</td>
203
+ <td>84.0</td>
204
+ <td>85.9</td>
205
+ <td>31.7</td>
206
+ </tr>
207
+ </tbody>
208
+ </table>
209
+
210
+
211
+
212
+ ### Invitation to Evaluate InternVL
213
+
214
+ 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).
215
+
216
+ ## Quick Start
217
+
218
+ We provide an example code to run InternVL2_5-38B using `transformers`.
219
+
220
+ We also welcome you to experience the InternVL series models in our [online demo](https://internvl.opengvlab.com/).
221
+
222
+ > Please use transformers ≳ 4.37.2 to ensure the model works normally.
223
+
224
+ ### Model Loading
225
+
226
+ #### 16-bit (bf16 / fp16)
227
+
228
+ ```python
229
+ import torch
230
+ from transformers import AutoTokenizer, AutoModel
231
+ path = "OpenGVLab/InternVL2_5-38B"
232
+ model = AutoModel.from_pretrained(
233
+ path,
234
+ torch_dtype=torch.bfloat16,
235
+ low_cpu_mem_usage=True,
236
+ use_flash_attn=True,
237
+ trust_remote_code=True).eval().cuda()
238
+ ```
239
+
240
+ #### BNB 8-bit Quantization
241
+
242
+ ```python
243
+ import torch
244
+ from transformers import AutoTokenizer, AutoModel
245
+ path = "OpenGVLab/InternVL2_5-38B"
246
+ model = AutoModel.from_pretrained(
247
+ path,
248
+ torch_dtype=torch.bfloat16,
249
+ load_in_8bit=True,
250
+ low_cpu_mem_usage=True,
251
+ use_flash_attn=True,
252
+ trust_remote_code=True).eval()
253
+ ```
254
+
255
+ #### BNB 4-bit Quantization
256
+
257
+ ```python
258
+ import torch
259
+ from transformers import AutoTokenizer, AutoModel
260
+ path = "OpenGVLab/InternVL2_5-38B"
261
+ model = AutoModel.from_pretrained(
262
+ path,
263
+ torch_dtype=torch.bfloat16,
264
+ load_in_4bit=True,
265
+ low_cpu_mem_usage=True,
266
+ use_flash_attn=True,
267
+ trust_remote_code=True).eval()
268
+ ```
269
+
270
+ #### Multiple GPUs
271
+
272
+ 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.
273
+
274
+ ```python
275
+ import math
276
+ import torch
277
+ from transformers import AutoTokenizer, AutoModel
278
+
279
+ def split_model(model_name):
280
+ device_map = {}
281
+ world_size = torch.cuda.device_count()
282
+ num_layers = {
283
+ 'InternVL2_5-1B': 24, 'InternVL_5-2B': 24, 'InternVL2_5-4B': 36, 'InternVL2_5-8B': 32,
284
+ 'InternVL2_5-26B': 48, 'InternVL2_5-38B': 64, 'InternVL2_5-78B': 80}[model_name]
285
+ # Since the first GPU will be used for ViT, treat it as half a GPU.
286
+ num_layers_per_gpu = math.ceil(num_layers / (world_size - 0.5))
287
+ num_layers_per_gpu = [num_layers_per_gpu] * world_size
288
+ num_layers_per_gpu[0] = math.ceil(num_layers_per_gpu[0] * 0.5)
289
+ layer_cnt = 0
290
+ for i, num_layer in enumerate(num_layers_per_gpu):
291
+ for j in range(num_layer):
292
+ device_map[f'language_model.model.layers.{layer_cnt}'] = i
293
+ layer_cnt += 1
294
+ device_map['vision_model'] = 0
295
+ device_map['mlp1'] = 0
296
+ device_map['language_model.model.tok_embeddings'] = 0
297
+ device_map['language_model.model.embed_tokens'] = 0
298
+ device_map['language_model.output'] = 0
299
+ device_map['language_model.model.norm'] = 0
300
+ device_map['language_model.lm_head'] = 0
301
+ device_map[f'language_model.model.layers.{num_layers - 1}'] = 0
302
+
303
+ return device_map
304
+
305
+ path = "OpenGVLab/InternVL2_5-38B"
306
+ device_map = split_model('InternVL2_5-38B')
307
+ model = AutoModel.from_pretrained(
308
+ path,
309
+ torch_dtype=torch.bfloat16,
310
+ low_cpu_mem_usage=True,
311
+ use_flash_attn=True,
312
+ trust_remote_code=True,
313
+ device_map=device_map).eval()
314
+ ```
315
+
316
+ ### Inference with Transformers
317
+
318
+ ```python
319
+ import numpy as np
320
+ import torch
321
+ import torchvision.transforms as T
322
+ from decord import VideoReader, cpu
323
+ from PIL import Image
324
+ from torchvision.transforms.functional import InterpolationMode
325
+ from transformers import AutoModel, AutoTokenizer
326
+
327
+ IMAGENET_MEAN = (0.485, 0.456, 0.406)
328
+ IMAGENET_STD = (0.229, 0.224, 0.225)
329
+
330
+ def build_transform(input_size):
331
+ MEAN, STD = IMAGENET_MEAN, IMAGENET_STD
332
+ transform = T.Compose([
333
+ T.Lambda(lambda img: img.convert('RGB') if img.mode != 'RGB' else img),
334
+ T.Resize((input_size, input_size), interpolation=InterpolationMode.BICUBIC),
335
+ T.ToTensor(),
336
+ T.Normalize(mean=MEAN, std=STD)
337
+ ])
338
+ return transform
339
+
340
+ def find_closest_aspect_ratio(aspect_ratio, target_ratios, width, height, image_size):
341
+ best_ratio_diff = float('inf')
342
+ best_ratio = (1, 1)
343
+ area = width * height
344
+ for ratio in target_ratios:
345
+ target_aspect_ratio = ratio[0] / ratio[1]
346
+ ratio_diff = abs(aspect_ratio - target_aspect_ratio)
347
+ if ratio_diff < best_ratio_diff:
348
+ best_ratio_diff = ratio_diff
349
+ best_ratio = ratio
350
+ elif ratio_diff == best_ratio_diff:
351
+ if area > 0.5 * image_size * image_size * ratio[0] * ratio[1]:
352
+ best_ratio = ratio
353
+ return best_ratio
354
+
355
+ def dynamic_preprocess(image, min_num=1, max_num=12, image_size=448, use_thumbnail=False):
356
+ orig_width, orig_height = image.size
357
+ aspect_ratio = orig_width / orig_height
358
+
359
+ # calculate the existing image aspect ratio
360
+ target_ratios = set(
361
+ (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
362
+ i * j <= max_num and i * j >= min_num)
363
+ target_ratios = sorted(target_ratios, key=lambda x: x[0] * x[1])
364
+
365
+ # find the closest aspect ratio to the target
366
+ target_aspect_ratio = find_closest_aspect_ratio(
367
+ aspect_ratio, target_ratios, orig_width, orig_height, image_size)
368
+
369
+ # calculate the target width and height
370
+ target_width = image_size * target_aspect_ratio[0]
371
+ target_height = image_size * target_aspect_ratio[1]
372
+ blocks = target_aspect_ratio[0] * target_aspect_ratio[1]
373
+
374
+ # resize the image
375
+ resized_img = image.resize((target_width, target_height))
376
+ processed_images = []
377
+ for i in range(blocks):
378
+ box = (
379
+ (i % (target_width // image_size)) * image_size,
380
+ (i // (target_width // image_size)) * image_size,
381
+ ((i % (target_width // image_size)) + 1) * image_size,
382
+ ((i // (target_width // image_size)) + 1) * image_size
383
+ )
384
+ # split the image
385
+ split_img = resized_img.crop(box)
386
+ processed_images.append(split_img)
387
+ assert len(processed_images) == blocks
388
+ if use_thumbnail and len(processed_images) != 1:
389
+ thumbnail_img = image.resize((image_size, image_size))
390
+ processed_images.append(thumbnail_img)
391
+ return processed_images
392
+
393
+ def load_image(image_file, input_size=448, max_num=12):
394
+ image = Image.open(image_file).convert('RGB')
395
+ transform = build_transform(input_size=input_size)
396
+ images = dynamic_preprocess(image, image_size=input_size, use_thumbnail=True, max_num=max_num)
397
+ pixel_values = [transform(image) for image in images]
398
+ pixel_values = torch.stack(pixel_values)
399
+ return pixel_values
400
+
401
+ # If you want to load a model using multiple GPUs, please refer to the `Multiple GPUs` section.
402
+ path = 'OpenGVLab/InternVL2_5-38B'
403
+ model = AutoModel.from_pretrained(
404
+ path,
405
+ torch_dtype=torch.bfloat16,
406
+ low_cpu_mem_usage=True,
407
+ use_flash_attn=True,
408
+ trust_remote_code=True).eval().cuda()
409
+ tokenizer = AutoTokenizer.from_pretrained(path, trust_remote_code=True, use_fast=False)
410
+
411
+ # set the max number of tiles in `max_num`
412
+ pixel_values = load_image('./examples/image1.jpg', max_num=12).to(torch.bfloat16).cuda()
413
+ generation_config = dict(max_new_tokens=1024, do_sample=True)
414
+
415
+ # pure-text conversation (纯文本对话)
416
+ question = 'Hello, who are you?'
417
+ response, history = model.chat(tokenizer, None, question, generation_config, history=None, return_history=True)
418
+ print(f'User: {question}\nAssistant: {response}')
419
+
420
+ question = 'Can you tell me a story?'
421
+ response, history = model.chat(tokenizer, None, question, generation_config, history=history, return_history=True)
422
+ print(f'User: {question}\nAssistant: {response}')
423
+
424
+ # single-image single-round conversation (单图单轮对话)
425
+ question = '<image>\nPlease describe the image shortly.'
426
+ response = model.chat(tokenizer, pixel_values, question, generation_config)
427
+ print(f'User: {question}\nAssistant: {response}')
428
+
429
+ # single-image multi-round conversation (单图多轮对话)
430
+ question = '<image>\nPlease describe the image in detail.'
431
+ response, history = model.chat(tokenizer, pixel_values, question, generation_config, history=None, return_history=True)
432
+ print(f'User: {question}\nAssistant: {response}')
433
+
434
+ question = 'Please write a poem according to the image.'
435
+ response, history = model.chat(tokenizer, pixel_values, question, generation_config, history=history, return_history=True)
436
+ print(f'User: {question}\nAssistant: {response}')
437
+
438
+ # multi-image multi-round conversation, combined images (多图多轮对话,拼接图像)
439
+ pixel_values1 = load_image('./examples/image1.jpg', max_num=12).to(torch.bfloat16).cuda()
440
+ pixel_values2 = load_image('./examples/image2.jpg', max_num=12).to(torch.bfloat16).cuda()
441
+ pixel_values = torch.cat((pixel_values1, pixel_values2), dim=0)
442
+
443
+ question = '<image>\nDescribe the two images in detail.'
444
+ response, history = model.chat(tokenizer, pixel_values, question, generation_config,
445
+ history=None, return_history=True)
446
+ print(f'User: {question}\nAssistant: {response}')
447
+
448
+ question = 'What are the similarities and differences between these two images.'
449
+ response, history = model.chat(tokenizer, pixel_values, question, generation_config,
450
+ history=history, return_history=True)
451
+ print(f'User: {question}\nAssistant: {response}')
452
+
453
+ # multi-image multi-round conversation, separate images (多图多轮对话,独立图像)
454
+ pixel_values1 = load_image('./examples/image1.jpg', max_num=12).to(torch.bfloat16).cuda()
455
+ pixel_values2 = load_image('./examples/image2.jpg', max_num=12).to(torch.bfloat16).cuda()
456
+ pixel_values = torch.cat((pixel_values1, pixel_values2), dim=0)
457
+ num_patches_list = [pixel_values1.size(0), pixel_values2.size(0)]
458
+
459
+ question = 'Image-1: <image>\nImage-2: <image>\nDescribe the two images in detail.'
460
+ response, history = model.chat(tokenizer, pixel_values, question, generation_config,
461
+ num_patches_list=num_patches_list,
462
+ history=None, return_history=True)
463
+ print(f'User: {question}\nAssistant: {response}')
464
+
465
+ question = 'What are the similarities and differences between these two images.'
466
+ response, history = model.chat(tokenizer, pixel_values, question, generation_config,
467
+ num_patches_list=num_patches_list,
468
+ history=history, return_history=True)
469
+ print(f'User: {question}\nAssistant: {response}')
470
+
471
+ # batch inference, single image per sample (单图批处理)
472
+ pixel_values1 = load_image('./examples/image1.jpg', max_num=12).to(torch.bfloat16).cuda()
473
+ pixel_values2 = load_image('./examples/image2.jpg', max_num=12).to(torch.bfloat16).cuda()
474
+ num_patches_list = [pixel_values1.size(0), pixel_values2.size(0)]
475
+ pixel_values = torch.cat((pixel_values1, pixel_values2), dim=0)
476
+
477
+ questions = ['<image>\nDescribe the image in detail.'] * len(num_patches_list)
478
+ responses = model.batch_chat(tokenizer, pixel_values,
479
+ num_patches_list=num_patches_list,
480
+ questions=questions,
481
+ generation_config=generation_config)
482
+ for question, response in zip(questions, responses):
483
+ print(f'User: {question}\nAssistant: {response}')
484
+
485
+ # video multi-round conversation (视频多轮对话)
486
+ def get_index(bound, fps, max_frame, first_idx=0, num_segments=32):
487
+ if bound:
488
+ start, end = bound[0], bound[1]
489
+ else:
490
+ start, end = -100000, 100000
491
+ start_idx = max(first_idx, round(start * fps))
492
+ end_idx = min(round(end * fps), max_frame)
493
+ seg_size = float(end_idx - start_idx) / num_segments
494
+ frame_indices = np.array([
495
+ int(start_idx + (seg_size / 2) + np.round(seg_size * idx))
496
+ for idx in range(num_segments)
497
+ ])
498
+ return frame_indices
499
+
500
+ def load_video(video_path, bound=None, input_size=448, max_num=1, num_segments=32):
501
+ vr = VideoReader(video_path, ctx=cpu(0), num_threads=1)
502
+ max_frame = len(vr) - 1
503
+ fps = float(vr.get_avg_fps())
504
+
505
+ pixel_values_list, num_patches_list = [], []
506
+ transform = build_transform(input_size=input_size)
507
+ frame_indices = get_index(bound, fps, max_frame, first_idx=0, num_segments=num_segments)
508
+ for frame_index in frame_indices:
509
+ img = Image.fromarray(vr[frame_index].asnumpy()).convert('RGB')
510
+ img = dynamic_preprocess(img, image_size=input_size, use_thumbnail=True, max_num=max_num)
511
+ pixel_values = [transform(tile) for tile in img]
512
+ pixel_values = torch.stack(pixel_values)
513
+ num_patches_list.append(pixel_values.shape[0])
514
+ pixel_values_list.append(pixel_values)
515
+ pixel_values = torch.cat(pixel_values_list)
516
+ return pixel_values, num_patches_list
517
+
518
+ video_path = './examples/red-panda.mp4'
519
+ pixel_values, num_patches_list = load_video(video_path, num_segments=8, max_num=1)
520
+ pixel_values = pixel_values.to(torch.bfloat16).cuda()
521
+ video_prefix = ''.join([f'Frame{i+1}: <image>\n' for i in range(len(num_patches_list))])
522
+ question = video_prefix + 'What is the red panda doing?'
523
+ # Frame1: <image>\nFrame2: <image>\n...\nFrame8: <image>\n{question}
524
+ response, history = model.chat(tokenizer, pixel_values, question, generation_config,
525
+ num_patches_list=num_patches_list, history=None, return_history=True)
526
+ print(f'User: {question}\nAssistant: {response}')
527
+
528
+ question = 'Describe this video in detail. Don\'t repeat.'
529
+ response, history = model.chat(tokenizer, pixel_values, question, generation_config,
530
+ num_patches_list=num_patches_list, history=history, return_history=True)
531
+ print(f'User: {question}\nAssistant: {response}')
532
+ ```
533
+
534
+ #### Streaming output
535
+
536
+ Besides this method, you can also use the following code to get streamed output.
537
+
538
+ ```python
539
+ from transformers import TextIteratorStreamer
540
+ from threading import Thread
541
+
542
+ # Initialize the streamer
543
+ streamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True, timeout=10)
544
+ # Define the generation configuration
545
+ generation_config = dict(max_new_tokens=1024, do_sample=False, streamer=streamer)
546
+ # Start the model chat in a separate thread
547
+ thread = Thread(target=model.chat, kwargs=dict(
548
+ tokenizer=tokenizer, pixel_values=pixel_values, question=question,
549
+ history=None, return_history=False, generation_config=generation_config,
550
+ ))
551
+ thread.start()
552
+
553
+ # Initialize an empty string to store the generated text
554
+ generated_text = ''
555
+ # Loop through the streamer to get the new text as it is generated
556
+ for new_text in streamer:
557
+ if new_text == model.conv_template.sep:
558
+ break
559
+ generated_text += new_text
560
+ print(new_text, end='', flush=True) # Print each new chunk of generated text on the same line
561
+ ```
562
+
563
+ ## Finetune
564
+
565
+ 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.
566
+
567
+ ## Deployment
568
+
569
+ ### LMDeploy
570
+
571
+ LMDeploy is a toolkit for compressing, deploying, and serving LLM, developed by the MMRazor and MMDeploy teams.
572
+
573
+ ```sh
574
+ pip install lmdeploy>=0.5.3
575
+ ```
576
+
577
+ 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.
578
+
579
+ #### A 'Hello, world' example
580
+
581
+ ```python
582
+ from lmdeploy import pipeline, TurbomindEngineConfig
583
+ from lmdeploy.vl import load_image
584
+
585
+ model = 'OpenGVLab/InternVL2_5-38B'
586
+ image = load_image('https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/tests/data/tiger.jpeg')
587
+ pipe = pipeline(model, backend_config=TurbomindEngineConfig(session_len=8192))
588
+ response = pipe(('describe this image', image))
589
+ print(response.text)
590
+ ```
591
+
592
+ If `ImportError` occurs while executing this case, please install the required dependency packages as prompted.
593
+
594
+ #### Multi-images inference
595
+
596
+ 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.
597
+
598
+ > 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.
599
+
600
+ ```python
601
+ from lmdeploy import pipeline, TurbomindEngineConfig
602
+ from lmdeploy.vl import load_image
603
+ from lmdeploy.vl.constants import IMAGE_TOKEN
604
+
605
+ model = 'OpenGVLab/InternVL2_5-38B'
606
+ pipe = pipeline(model, backend_config=TurbomindEngineConfig(session_len=8192))
607
+
608
+ image_urls=[
609
+ 'https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/human-pose.jpg',
610
+ 'https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/det.jpg'
611
+ ]
612
+
613
+ images = [load_image(img_url) for img_url in image_urls]
614
+ # Numbering images improves multi-image conversations
615
+ response = pipe((f'Image-1: {IMAGE_TOKEN}\nImage-2: {IMAGE_TOKEN}\ndescribe these two images', images))
616
+ print(response.text)
617
+ ```
618
+
619
+ #### Batch prompts inference
620
+
621
+ Conducting inference with batch prompts is quite straightforward; just place them within a list structure:
622
+
623
+ ```python
624
+ from lmdeploy import pipeline, TurbomindEngineConfig
625
+ from lmdeploy.vl import load_image
626
+
627
+ model = 'OpenGVLab/InternVL2_5-38B'
628
+ pipe = pipeline(model, backend_config=TurbomindEngineConfig(session_len=8192))
629
+
630
+ image_urls=[
631
+ "https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/human-pose.jpg",
632
+ "https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/det.jpg"
633
+ ]
634
+ prompts = [('describe this image', load_image(img_url)) for img_url in image_urls]
635
+ response = pipe(prompts)
636
+ print(response)
637
+ ```
638
+
639
+ #### Multi-turn conversation
640
+
641
+ 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.
642
+
643
+ ```python
644
+ from lmdeploy import pipeline, TurbomindEngineConfig, GenerationConfig
645
+ from lmdeploy.vl import load_image
646
+
647
+ model = 'OpenGVLab/InternVL2_5-38B'
648
+ pipe = pipeline(model, backend_config=TurbomindEngineConfig(session_len=8192))
649
+
650
+ image = load_image('https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/human-pose.jpg')
651
+ gen_config = GenerationConfig(top_k=40, top_p=0.8, temperature=0.8)
652
+ sess = pipe.chat(('describe this image', image), gen_config=gen_config)
653
+ print(sess.response.text)
654
+ sess = pipe.chat('What is the woman doing?', session=sess, gen_config=gen_config)
655
+ print(sess.response.text)
656
+ ```
657
+
658
+ #### Service
659
+
660
+ 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:
661
+
662
+ ```shell
663
+ lmdeploy serve api_server OpenGVLab/InternVL2_5-38B --backend turbomind --server-port 23333
664
+ ```
665
+
666
+ To use the OpenAI-style interface, you need to install OpenAI:
667
+
668
+ ```shell
669
+ pip install openai
670
+ ```
671
+
672
+ Then, use the code below to make the API call:
673
+
674
+ ```python
675
+ from openai import OpenAI
676
+
677
+ client = OpenAI(api_key='YOUR_API_KEY', base_url='http://0.0.0.0:23333/v1')
678
+ model_name = client.models.list().data[0].id
679
+ response = client.chat.completions.create(
680
+ model=model_name,
681
+ messages=[{
682
+ 'role':
683
+ 'user',
684
+ 'content': [{
685
+ 'type': 'text',
686
+ 'text': 'describe this image',
687
+ }, {
688
+ 'type': 'image_url',
689
+ 'image_url': {
690
+ 'url':
691
+ 'https://modelscope.oss-cn-beijing.aliyuncs.com/resource/tiger.jpeg',
692
+ },
693
+ }],
694
+ }],
695
+ temperature=0.8,
696
+ top_p=0.8)
697
+ print(response)
698
+ ```
699
+
700
+ ## License
701
+
702
+ This project is released under the MIT license, while Qwen2 is licensed under the Tongyi Qianwen LICENSE.
703
+
704
+ ## Citation
705
+
706
+ If you find this project useful in your research, please consider citing:
707
+
708
+ ```BibTeX
709
+ @article{chen2023internvl,
710
+ title={InternVL: Scaling up Vision Foundation Models and Aligning for Generic Visual-Linguistic Tasks},
711
+ 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},
712
+ journal={arXiv preprint arXiv:2312.14238},
713
+ year={2023}
714
+ }
715
+ @article{chen2024far,
716
+ title={How Far Are We to GPT-4V? Closing the Gap to Commercial Multimodal Models with Open-Source Suites},
717
+ 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},
718
+ journal={arXiv preprint arXiv:2404.16821},
719
+ year={2024}
720
+ }
721
+ ```
722
+