zwgao commited on
Commit
d974b7c
1 Parent(s): 67d22a2

Update README.md

Browse files
Files changed (1) hide show
  1. README.md +747 -3
README.md CHANGED
@@ -1,3 +1,747 @@
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
+ - internlm/internlm2_5-20b-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-26B
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-26B** 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-26B consists of [InternViT-6B-448px-V2_5](https://huggingface.co/OpenGVLab/InternViT-6B-448px-V2_5), an MLP projector, and [internlm2_5-20b-chat](https://huggingface.co/internlm/internlm2_5-20b-chat).
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%; 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
+ ### Language Benchmarks
212
+
213
+ | Dataset | Settings | InternLM2-20B-Chat | InternVL2-26B | InternLM2.5-20B-Chat | InternVL2.5-26B |
214
+ |------------------|----------|--------------------|---------------|----------------------|-----------------|
215
+ | MMLU | 5-shot | 66.5 | 68.2 | 73.3 | 76.6 |
216
+ | CMMLU | 5-shot | 64.7 | 68.1 | 79.4 | 81.9 |
217
+ | C-Eval | 5-shot | 61.8 | 67.7 | 80.2 | 83.8 |
218
+ | GAOKAO | 0-shot | 63.5 | 62.3 | 81.0 | 86.9 |
219
+ | TriviaQA | 0-shot | 61.8 | 61.8 | 67.3 | 69.0 |
220
+ | NaturalQuestions | 0-shot | 23.6 | 28.8 | 21.3 | 36.1 |
221
+ | C3 | 0-shot | 92.2 | 93.2 | 94.0 | 95.8 |
222
+ | RACE-High | 0-shot | 86.2 | 86.5 | 91.3 | 92.2 |
223
+ | WinoGrande | 0-shot | 76.4 | 79.9 | 86.4 | 87.9 |
224
+ | HellaSwag | 0-shot | 85.3 | 87.5 | 95.9 | 95.8 |
225
+ | BBH | 0-shot | 70.1 | 69.8 | 78.4 | 78.9 |
226
+ | GSM8K | 4-shot | 80.7 | 80.0 | 88.5 | 82.9 |
227
+ | MATH | 4-shot | 34.9 | 35.5 | 54.7 | 53.7 |
228
+ | TheoremQA | 0-shot | 22.1 | 15.3 | 23.9 | 15.4 |
229
+ | HumanEval | 4-shot | 71.3 | 67.1 | 69.5 | 68.9 |
230
+ | MBPP | 3-shot | 70.8 | 66.2 | 70.0 | 72.0 |
231
+ | MBPP-CN | 0-shot | 55.8 | 54.2 | 61.0 | 61.6 |
232
+ | Average | -- | 64.0 | 64.2 | 71.5 | 72.9 |
233
+ | Gain | -- | -- | **+0.2** | -- | **+1.4** |
234
+
235
+
236
+
237
+ ### Invitation to Evaluate InternVL
238
+
239
+ 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).
240
+
241
+ ## Quick Start
242
+
243
+ We provide an example code to run InternVL2_5-26B using `transformers`.
244
+
245
+ We also welcome you to experience the InternVL series models in our [online demo](https://internvl.opengvlab.com/).
246
+
247
+ > Please use transformers ≳ 4.37.2 to ensure the model works normally.
248
+
249
+ ### Model Loading
250
+
251
+ #### 16-bit (bf16 / fp16)
252
+
253
+ ```python
254
+ import torch
255
+ from transformers import AutoTokenizer, AutoModel
256
+ path = "OpenGVLab/InternVL2_5-26B"
257
+ model = AutoModel.from_pretrained(
258
+ path,
259
+ torch_dtype=torch.bfloat16,
260
+ low_cpu_mem_usage=True,
261
+ use_flash_attn=True,
262
+ trust_remote_code=True).eval().cuda()
263
+ ```
264
+
265
+ #### BNB 8-bit Quantization
266
+
267
+ ```python
268
+ import torch
269
+ from transformers import AutoTokenizer, AutoModel
270
+ path = "OpenGVLab/InternVL2_5-26B"
271
+ model = AutoModel.from_pretrained(
272
+ path,
273
+ torch_dtype=torch.bfloat16,
274
+ load_in_8bit=True,
275
+ low_cpu_mem_usage=True,
276
+ use_flash_attn=True,
277
+ trust_remote_code=True).eval()
278
+ ```
279
+
280
+ #### BNB 4-bit Quantization
281
+
282
+ ```python
283
+ import torch
284
+ from transformers import AutoTokenizer, AutoModel
285
+ path = "OpenGVLab/InternVL2_5-26B"
286
+ model = AutoModel.from_pretrained(
287
+ path,
288
+ torch_dtype=torch.bfloat16,
289
+ load_in_4bit=True,
290
+ low_cpu_mem_usage=True,
291
+ use_flash_attn=True,
292
+ trust_remote_code=True).eval()
293
+ ```
294
+
295
+ #### Multiple GPUs
296
+
297
+ 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.
298
+
299
+ ```python
300
+ import math
301
+ import torch
302
+ from transformers import AutoTokenizer, AutoModel
303
+
304
+ def split_model(model_name):
305
+ device_map = {}
306
+ world_size = torch.cuda.device_count()
307
+ num_layers = {
308
+ 'InternVL2_5-1B': 24, 'InternVL_5-2B': 24, 'InternVL2_5-4B': 36, 'InternVL2_5-8B': 32,
309
+ 'InternVL2_5-26B': 48, 'InternVL2_5-38B': 64, 'InternVL2_5-78B': 80}[model_name]
310
+ # Since the first GPU will be used for ViT, treat it as half a GPU.
311
+ num_layers_per_gpu = math.ceil(num_layers / (world_size - 0.5))
312
+ num_layers_per_gpu = [num_layers_per_gpu] * world_size
313
+ num_layers_per_gpu[0] = math.ceil(num_layers_per_gpu[0] * 0.5)
314
+ layer_cnt = 0
315
+ for i, num_layer in enumerate(num_layers_per_gpu):
316
+ for j in range(num_layer):
317
+ device_map[f'language_model.model.layers.{layer_cnt}'] = i
318
+ layer_cnt += 1
319
+ device_map['vision_model'] = 0
320
+ device_map['mlp1'] = 0
321
+ device_map['language_model.model.tok_embeddings'] = 0
322
+ device_map['language_model.model.embed_tokens'] = 0
323
+ device_map['language_model.output'] = 0
324
+ device_map['language_model.model.norm'] = 0
325
+ device_map['language_model.lm_head'] = 0
326
+ device_map[f'language_model.model.layers.{num_layers - 1}'] = 0
327
+
328
+ return device_map
329
+
330
+ path = "OpenGVLab/InternVL2_5-26B"
331
+ device_map = split_model('InternVL2_5-26B')
332
+ model = AutoModel.from_pretrained(
333
+ path,
334
+ torch_dtype=torch.bfloat16,
335
+ low_cpu_mem_usage=True,
336
+ use_flash_attn=True,
337
+ trust_remote_code=True,
338
+ device_map=device_map).eval()
339
+ ```
340
+
341
+ ### Inference with Transformers
342
+
343
+ ```python
344
+ import numpy as np
345
+ import torch
346
+ import torchvision.transforms as T
347
+ from decord import VideoReader, cpu
348
+ from PIL import Image
349
+ from torchvision.transforms.functional import InterpolationMode
350
+ from transformers import AutoModel, AutoTokenizer
351
+
352
+ IMAGENET_MEAN = (0.485, 0.456, 0.406)
353
+ IMAGENET_STD = (0.229, 0.224, 0.225)
354
+
355
+ def build_transform(input_size):
356
+ MEAN, STD = IMAGENET_MEAN, IMAGENET_STD
357
+ transform = T.Compose([
358
+ T.Lambda(lambda img: img.convert('RGB') if img.mode != 'RGB' else img),
359
+ T.Resize((input_size, input_size), interpolation=InterpolationMode.BICUBIC),
360
+ T.ToTensor(),
361
+ T.Normalize(mean=MEAN, std=STD)
362
+ ])
363
+ return transform
364
+
365
+ def find_closest_aspect_ratio(aspect_ratio, target_ratios, width, height, image_size):
366
+ best_ratio_diff = float('inf')
367
+ best_ratio = (1, 1)
368
+ area = width * height
369
+ for ratio in target_ratios:
370
+ target_aspect_ratio = ratio[0] / ratio[1]
371
+ ratio_diff = abs(aspect_ratio - target_aspect_ratio)
372
+ if ratio_diff < best_ratio_diff:
373
+ best_ratio_diff = ratio_diff
374
+ best_ratio = ratio
375
+ elif ratio_diff == best_ratio_diff:
376
+ if area > 0.5 * image_size * image_size * ratio[0] * ratio[1]:
377
+ best_ratio = ratio
378
+ return best_ratio
379
+
380
+ def dynamic_preprocess(image, min_num=1, max_num=12, image_size=448, use_thumbnail=False):
381
+ orig_width, orig_height = image.size
382
+ aspect_ratio = orig_width / orig_height
383
+
384
+ # calculate the existing image aspect ratio
385
+ target_ratios = set(
386
+ (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
387
+ i * j <= max_num and i * j >= min_num)
388
+ target_ratios = sorted(target_ratios, key=lambda x: x[0] * x[1])
389
+
390
+ # find the closest aspect ratio to the target
391
+ target_aspect_ratio = find_closest_aspect_ratio(
392
+ aspect_ratio, target_ratios, orig_width, orig_height, image_size)
393
+
394
+ # calculate the target width and height
395
+ target_width = image_size * target_aspect_ratio[0]
396
+ target_height = image_size * target_aspect_ratio[1]
397
+ blocks = target_aspect_ratio[0] * target_aspect_ratio[1]
398
+
399
+ # resize the image
400
+ resized_img = image.resize((target_width, target_height))
401
+ processed_images = []
402
+ for i in range(blocks):
403
+ box = (
404
+ (i % (target_width // image_size)) * image_size,
405
+ (i // (target_width // image_size)) * image_size,
406
+ ((i % (target_width // image_size)) + 1) * image_size,
407
+ ((i // (target_width // image_size)) + 1) * image_size
408
+ )
409
+ # split the image
410
+ split_img = resized_img.crop(box)
411
+ processed_images.append(split_img)
412
+ assert len(processed_images) == blocks
413
+ if use_thumbnail and len(processed_images) != 1:
414
+ thumbnail_img = image.resize((image_size, image_size))
415
+ processed_images.append(thumbnail_img)
416
+ return processed_images
417
+
418
+ def load_image(image_file, input_size=448, max_num=12):
419
+ image = Image.open(image_file).convert('RGB')
420
+ transform = build_transform(input_size=input_size)
421
+ images = dynamic_preprocess(image, image_size=input_size, use_thumbnail=True, max_num=max_num)
422
+ pixel_values = [transform(image) for image in images]
423
+ pixel_values = torch.stack(pixel_values)
424
+ return pixel_values
425
+
426
+ # If you want to load a model using multiple GPUs, please refer to the `Multiple GPUs` section.
427
+ path = 'OpenGVLab/InternVL2_5-26B'
428
+ model = AutoModel.from_pretrained(
429
+ path,
430
+ torch_dtype=torch.bfloat16,
431
+ low_cpu_mem_usage=True,
432
+ use_flash_attn=True,
433
+ trust_remote_code=True).eval().cuda()
434
+ tokenizer = AutoTokenizer.from_pretrained(path, trust_remote_code=True, use_fast=False)
435
+
436
+ # set the max number of tiles in `max_num`
437
+ pixel_values = load_image('./examples/image1.jpg', max_num=12).to(torch.bfloat16).cuda()
438
+ generation_config = dict(max_new_tokens=1024, do_sample=True)
439
+
440
+ # pure-text conversation (纯文本对话)
441
+ question = 'Hello, who are you?'
442
+ response, history = model.chat(tokenizer, None, question, generation_config, history=None, return_history=True)
443
+ print(f'User: {question}\nAssistant: {response}')
444
+
445
+ question = 'Can you tell me a story?'
446
+ response, history = model.chat(tokenizer, None, question, generation_config, history=history, return_history=True)
447
+ print(f'User: {question}\nAssistant: {response}')
448
+
449
+ # single-image single-round conversation (单图单轮对话)
450
+ question = '<image>\nPlease describe the image shortly.'
451
+ response = model.chat(tokenizer, pixel_values, question, generation_config)
452
+ print(f'User: {question}\nAssistant: {response}')
453
+
454
+ # single-image multi-round conversation (单图多轮对话)
455
+ question = '<image>\nPlease describe the image in detail.'
456
+ response, history = model.chat(tokenizer, pixel_values, question, generation_config, history=None, return_history=True)
457
+ print(f'User: {question}\nAssistant: {response}')
458
+
459
+ question = 'Please write a poem according to the image.'
460
+ response, history = model.chat(tokenizer, pixel_values, question, generation_config, history=history, return_history=True)
461
+ print(f'User: {question}\nAssistant: {response}')
462
+
463
+ # multi-image multi-round conversation, combined images (多图多轮对话,拼接图像)
464
+ pixel_values1 = load_image('./examples/image1.jpg', max_num=12).to(torch.bfloat16).cuda()
465
+ pixel_values2 = load_image('./examples/image2.jpg', max_num=12).to(torch.bfloat16).cuda()
466
+ pixel_values = torch.cat((pixel_values1, pixel_values2), dim=0)
467
+
468
+ question = '<image>\nDescribe the two images in detail.'
469
+ response, history = model.chat(tokenizer, pixel_values, question, generation_config,
470
+ history=None, return_history=True)
471
+ print(f'User: {question}\nAssistant: {response}')
472
+
473
+ question = 'What are the similarities and differences between these two images.'
474
+ response, history = model.chat(tokenizer, pixel_values, question, generation_config,
475
+ history=history, return_history=True)
476
+ print(f'User: {question}\nAssistant: {response}')
477
+
478
+ # multi-image multi-round conversation, separate images (多图多轮对话,独立图像)
479
+ pixel_values1 = load_image('./examples/image1.jpg', max_num=12).to(torch.bfloat16).cuda()
480
+ pixel_values2 = load_image('./examples/image2.jpg', max_num=12).to(torch.bfloat16).cuda()
481
+ pixel_values = torch.cat((pixel_values1, pixel_values2), dim=0)
482
+ num_patches_list = [pixel_values1.size(0), pixel_values2.size(0)]
483
+
484
+ question = 'Image-1: <image>\nImage-2: <image>\nDescribe the two images in detail.'
485
+ response, history = model.chat(tokenizer, pixel_values, question, generation_config,
486
+ num_patches_list=num_patches_list,
487
+ history=None, return_history=True)
488
+ print(f'User: {question}\nAssistant: {response}')
489
+
490
+ question = 'What are the similarities and differences between these two images.'
491
+ response, history = model.chat(tokenizer, pixel_values, question, generation_config,
492
+ num_patches_list=num_patches_list,
493
+ history=history, return_history=True)
494
+ print(f'User: {question}\nAssistant: {response}')
495
+
496
+ # batch inference, single image per sample (单图批处理)
497
+ pixel_values1 = load_image('./examples/image1.jpg', max_num=12).to(torch.bfloat16).cuda()
498
+ pixel_values2 = load_image('./examples/image2.jpg', max_num=12).to(torch.bfloat16).cuda()
499
+ num_patches_list = [pixel_values1.size(0), pixel_values2.size(0)]
500
+ pixel_values = torch.cat((pixel_values1, pixel_values2), dim=0)
501
+
502
+ questions = ['<image>\nDescribe the image in detail.'] * len(num_patches_list)
503
+ responses = model.batch_chat(tokenizer, pixel_values,
504
+ num_patches_list=num_patches_list,
505
+ questions=questions,
506
+ generation_config=generation_config)
507
+ for question, response in zip(questions, responses):
508
+ print(f'User: {question}\nAssistant: {response}')
509
+
510
+ # video multi-round conversation (视频多轮对话)
511
+ def get_index(bound, fps, max_frame, first_idx=0, num_segments=32):
512
+ if bound:
513
+ start, end = bound[0], bound[1]
514
+ else:
515
+ start, end = -100000, 100000
516
+ start_idx = max(first_idx, round(start * fps))
517
+ end_idx = min(round(end * fps), max_frame)
518
+ seg_size = float(end_idx - start_idx) / num_segments
519
+ frame_indices = np.array([
520
+ int(start_idx + (seg_size / 2) + np.round(seg_size * idx))
521
+ for idx in range(num_segments)
522
+ ])
523
+ return frame_indices
524
+
525
+ def load_video(video_path, bound=None, input_size=448, max_num=1, num_segments=32):
526
+ vr = VideoReader(video_path, ctx=cpu(0), num_threads=1)
527
+ max_frame = len(vr) - 1
528
+ fps = float(vr.get_avg_fps())
529
+
530
+ pixel_values_list, num_patches_list = [], []
531
+ transform = build_transform(input_size=input_size)
532
+ frame_indices = get_index(bound, fps, max_frame, first_idx=0, num_segments=num_segments)
533
+ for frame_index in frame_indices:
534
+ img = Image.fromarray(vr[frame_index].asnumpy()).convert('RGB')
535
+ img = dynamic_preprocess(img, image_size=input_size, use_thumbnail=True, max_num=max_num)
536
+ pixel_values = [transform(tile) for tile in img]
537
+ pixel_values = torch.stack(pixel_values)
538
+ num_patches_list.append(pixel_values.shape[0])
539
+ pixel_values_list.append(pixel_values)
540
+ pixel_values = torch.cat(pixel_values_list)
541
+ return pixel_values, num_patches_list
542
+
543
+ video_path = './examples/red-panda.mp4'
544
+ pixel_values, num_patches_list = load_video(video_path, num_segments=8, max_num=1)
545
+ pixel_values = pixel_values.to(torch.bfloat16).cuda()
546
+ video_prefix = ''.join([f'Frame{i+1}: <image>\n' for i in range(len(num_patches_list))])
547
+ question = video_prefix + 'What is the red panda doing?'
548
+ # Frame1: <image>\nFrame2: <image>\n...\nFrame8: <image>\n{question}
549
+ response, history = model.chat(tokenizer, pixel_values, question, generation_config,
550
+ num_patches_list=num_patches_list, history=None, return_history=True)
551
+ print(f'User: {question}\nAssistant: {response}')
552
+
553
+ question = 'Describe this video in detail. Don\'t repeat.'
554
+ response, history = model.chat(tokenizer, pixel_values, question, generation_config,
555
+ num_patches_list=num_patches_list, history=history, return_history=True)
556
+ print(f'User: {question}\nAssistant: {response}')
557
+ ```
558
+
559
+ #### Streaming output
560
+
561
+ Besides this method, you can also use the following code to get streamed output.
562
+
563
+ ```python
564
+ from transformers import TextIteratorStreamer
565
+ from threading import Thread
566
+
567
+ # Initialize the streamer
568
+ streamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True, timeout=10)
569
+ # Define the generation configuration
570
+ generation_config = dict(max_new_tokens=1024, do_sample=False, streamer=streamer)
571
+ # Start the model chat in a separate thread
572
+ thread = Thread(target=model.chat, kwargs=dict(
573
+ tokenizer=tokenizer, pixel_values=pixel_values, question=question,
574
+ history=None, return_history=False, generation_config=generation_config,
575
+ ))
576
+ thread.start()
577
+
578
+ # Initialize an empty string to store the generated text
579
+ generated_text = ''
580
+ # Loop through the streamer to get the new text as it is generated
581
+ for new_text in streamer:
582
+ if new_text == model.conv_template.sep:
583
+ break
584
+ generated_text += new_text
585
+ print(new_text, end='', flush=True) # Print each new chunk of generated text on the same line
586
+ ```
587
+
588
+ ## Finetune
589
+
590
+ 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.
591
+
592
+ ## Deployment
593
+
594
+ ### LMDeploy
595
+
596
+ LMDeploy is a toolkit for compressing, deploying, and serving LLM, developed by the MMRazor and MMDeploy teams.
597
+
598
+ ```sh
599
+ pip install lmdeploy>=0.5.3
600
+ ```
601
+
602
+ 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.
603
+
604
+ #### A 'Hello, world' example
605
+
606
+ ```python
607
+ from lmdeploy import pipeline, TurbomindEngineConfig
608
+ from lmdeploy.vl import load_image
609
+
610
+ model = 'OpenGVLab/InternVL2_5-26B'
611
+ image = load_image('https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/tests/data/tiger.jpeg')
612
+ pipe = pipeline(model, backend_config=TurbomindEngineConfig(session_len=8192))
613
+ response = pipe(('describe this image', image))
614
+ print(response.text)
615
+ ```
616
+
617
+ If `ImportError` occurs while executing this case, please install the required dependency packages as prompted.
618
+
619
+ #### Multi-images inference
620
+
621
+ 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.
622
+
623
+ > 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.
624
+
625
+ ```python
626
+ from lmdeploy import pipeline, TurbomindEngineConfig
627
+ from lmdeploy.vl import load_image
628
+ from lmdeploy.vl.constants import IMAGE_TOKEN
629
+
630
+ model = 'OpenGVLab/InternVL2_5-26B'
631
+ pipe = pipeline(model, backend_config=TurbomindEngineConfig(session_len=8192))
632
+
633
+ image_urls=[
634
+ 'https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/human-pose.jpg',
635
+ 'https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/det.jpg'
636
+ ]
637
+
638
+ images = [load_image(img_url) for img_url in image_urls]
639
+ # Numbering images improves multi-image conversations
640
+ response = pipe((f'Image-1: {IMAGE_TOKEN}\nImage-2: {IMAGE_TOKEN}\ndescribe these two images', images))
641
+ print(response.text)
642
+ ```
643
+
644
+ #### Batch prompts inference
645
+
646
+ Conducting inference with batch prompts is quite straightforward; just place them within a list structure:
647
+
648
+ ```python
649
+ from lmdeploy import pipeline, TurbomindEngineConfig
650
+ from lmdeploy.vl import load_image
651
+
652
+ model = 'OpenGVLab/InternVL2_5-26B'
653
+ pipe = pipeline(model, backend_config=TurbomindEngineConfig(session_len=8192))
654
+
655
+ image_urls=[
656
+ "https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/human-pose.jpg",
657
+ "https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/det.jpg"
658
+ ]
659
+ prompts = [('describe this image', load_image(img_url)) for img_url in image_urls]
660
+ response = pipe(prompts)
661
+ print(response)
662
+ ```
663
+
664
+ #### Multi-turn conversation
665
+
666
+ 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.
667
+
668
+ ```python
669
+ from lmdeploy import pipeline, TurbomindEngineConfig, GenerationConfig
670
+ from lmdeploy.vl import load_image
671
+
672
+ model = 'OpenGVLab/InternVL2_5-26B'
673
+ pipe = pipeline(model, backend_config=TurbomindEngineConfig(session_len=8192))
674
+
675
+ image = load_image('https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/human-pose.jpg')
676
+ gen_config = GenerationConfig(top_k=40, top_p=0.8, temperature=0.8)
677
+ sess = pipe.chat(('describe this image', image), gen_config=gen_config)
678
+ print(sess.response.text)
679
+ sess = pipe.chat('What is the woman doing?', session=sess, gen_config=gen_config)
680
+ print(sess.response.text)
681
+ ```
682
+
683
+ #### Service
684
+
685
+ 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:
686
+
687
+ ```shell
688
+ lmdeploy serve api_server OpenGVLab/InternVL2_5-26B --backend turbomind --server-port 23333
689
+ ```
690
+
691
+ To use the OpenAI-style interface, you need to install OpenAI:
692
+
693
+ ```shell
694
+ pip install openai
695
+ ```
696
+
697
+ Then, use the code below to make the API call:
698
+
699
+ ```python
700
+ from openai import OpenAI
701
+
702
+ client = OpenAI(api_key='YOUR_API_KEY', base_url='http://0.0.0.0:23333/v1')
703
+ model_name = client.models.list().data[0].id
704
+ response = client.chat.completions.create(
705
+ model=model_name,
706
+ messages=[{
707
+ 'role':
708
+ 'user',
709
+ 'content': [{
710
+ 'type': 'text',
711
+ 'text': 'describe this image',
712
+ }, {
713
+ 'type': 'image_url',
714
+ 'image_url': {
715
+ 'url':
716
+ 'https://modelscope.oss-cn-beijing.aliyuncs.com/resource/tiger.jpeg',
717
+ },
718
+ }],
719
+ }],
720
+ temperature=0.8,
721
+ top_p=0.8)
722
+ print(response)
723
+ ```
724
+
725
+ ## License
726
+
727
+ This project is released under the MIT license, while Qwen2 is licensed under the Tongyi Qianwen LICENSE.
728
+
729
+ ## Citation
730
+
731
+ If you find this project useful in your research, please consider citing:
732
+
733
+ ```BibTeX
734
+ @article{chen2023internvl,
735
+ title={InternVL: Scaling up Vision Foundation Models and Aligning for Generic Visual-Linguistic Tasks},
736
+ 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},
737
+ journal={arXiv preprint arXiv:2312.14238},
738
+ year={2023}
739
+ }
740
+ @article{chen2024far,
741
+ title={How Far Are We to GPT-4V? Closing the Gap to Commercial Multimodal Models with Open-Source Suites},
742
+ 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},
743
+ journal={arXiv preprint arXiv:2404.16821},
744
+ year={2024}
745
+ }
746
+ ```
747
+