zwgao commited on
Commit
3094781
1 Parent(s): bb37903

Update README.md

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