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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
---
|
2 |
+
license: mit
|
3 |
+
pipeline_tag: image-text-to-text
|
4 |
+
library_name: transformers
|
5 |
+
base_model:
|
6 |
+
- internlm/internlm2-chat-1_8b
|
7 |
+
base_model_relation: merge
|
8 |
+
language:
|
9 |
+
- multilingual
|
10 |
+
tags:
|
11 |
+
- internvl
|
12 |
+
- vision
|
13 |
+
- ocr
|
14 |
+
- video
|
15 |
+
- custom_code
|
16 |
+
---
|
17 |
+
|
18 |
+
# Mono-InternVL-2B
|
19 |
+
|
20 |
+
[\[📂 GitHub\]](https://github.com/OpenGVLab/InternVL) [\[📜 Mono-InternVL Paper\]](https://arxiv.org/abs/2410.TODO)
|
21 |
+
|
22 |
+
[切换至中文版](#简介)
|
23 |
+
|
24 |
+
<a id="radar"></a>
|
25 |
+
|
26 |
+
![image/png](images/fig1.jpg)
|
27 |
+
|
28 |
+
![image/png](images/fig2.jpg)
|
29 |
+
|
30 |
+
|
31 |
+
|
32 |
+
## Introduction
|
33 |
+
|
34 |
+
We release Mono-InternVL, a **monolithic** multimodal large language model (MLLM) that integrates visual encoding and textual decoding into a single LLM. In Mono-InternVL, a set of visual experts is embedded into the pre-trained LLM via a mixture-of-experts mechanism. By freezing the LLM, Mono-InternVL ensures that visual capabilities are optimized without compromising the pre-trained language knowledge. Based on this structure, an innovative Endogenous Visual Pretraining (EViP) is introduced to realize coarse-to-fine visual learning.
|
35 |
+
|
36 |
+
|
37 |
+
|
38 |
+
Mono-InternVL achieves superior performance compared to state-of-the-art MLLM Mini-InternVL-2B-1.5 and significantly outperforms other monolithic MLLMs, as shown in the [radar chart](#radar) above. Meanwhile, it achieves better deployment efficiency, with first token latency reduced by up to 67%.
|
39 |
+
|
40 |
+
|
41 |
+
|
42 |
+
This repository contains the instruction-tuned Mono-InternVL-2B model. It is built upon [internlm2-chat-1_8b](https://huggingface.co/internlm/internlm2-chat-1_8b). For more details, please refer to our [paper](https://arxiv.org/abs/2410.TODO).
|
43 |
+
|
44 |
+
|
45 |
+
|
46 |
+
|
47 |
+
|
48 |
+
## Performance
|
49 |
+
|
50 |
+
| Benchmark | Chameleon-7B | EVE-7B (HD) | Emu3 | Mini-InternVL-2B-1-5 | Mono-InternVL-2B |
|
51 |
+
| :--------------------------: | :----------: | :---------: | :--------: | :------------------: | :--------------: |
|
52 |
+
| Type | Monolithic | Monolithic | Monolithic | Modular | Monolithic |
|
53 |
+
| #Activated Params | 7B | 7B | 8B | 2.2B | 1.8B |
|
54 |
+
| | | | | | |
|
55 |
+
| MMVet | 8.3 | 25.7 | 37.2 | 39.3 | 40.1 |
|
56 |
+
| MMMU<sub>val</sub> | 25.4 | 32.6 | 31.6 | 34.6 | 33.7 |
|
57 |
+
| MME<sub>sum</sub> | 170 | 1628 | — | 1902 | 1875 |
|
58 |
+
| MMBench-EN<sub>test</sub> | 31.1 | 52.3 | 58.5 | 70.9 | 65.5 |
|
59 |
+
| MathVista<sub>testmini</sub> | 22.3 | 34.2 | — | 41.1 | 45.7 |
|
60 |
+
| SEED-Image | 30.6 | 64.6 | 68.2 | 69.8 | 67.4 |
|
61 |
+
| OCRBench | 7 | 398 | 687 | 654 | 767 |
|
62 |
+
| Hallusion-Bench | 17.1 | 26.4 | — | 37.5 | 34.8 |
|
63 |
+
| CCBench<sub>dev</sub> | 3.5 | 16.3 | — | 63.5 | 66.3 |
|
64 |
+
| Avg<sub>multimodal</sub> | 16.1 | 38.9 | — | 54.4 | 55.2 |
|
65 |
+
| | | | | | |
|
66 |
+
| TextVQA<sub>val</sub> | 4.8 | 56.8 | 64.7 | 70.5 | 72.6 |
|
67 |
+
| SQA-I<sub>test</sub> | 47.2 | 64.9 | 89.2 | 84.9 | 93.6 |
|
68 |
+
| GQA<sub>test</sub> | — | 62.6 | 60.3 | 61.6 | 59.5 |
|
69 |
+
| DocVQA<sub>test</sub> | 1.5 | 53.0 | 76.3 | 85.0 | 80.0 |
|
70 |
+
| AI2D<sub>test</sub> | 46.0 | 61.0 | 70.0 | 69.8 | 68.6 |
|
71 |
+
| ChartQA<sub>test</sub> | 2.9 | 59.1 | 68.6 | 74.8 | 73.7 |
|
72 |
+
| InfoVQA<sub>test</sub> | 5.0 | 25.0 | 43.8 | 55.4 | 43.0 |
|
73 |
+
| Avg<sub>VQA</sub> | 17.9 | 54.6 | 67.6 | 71.7 | 70.1 |
|
74 |
+
|
75 |
+
- Sources of the results include the original papers, our evaluation with [VLMEvalKit](https://github.com/open-compass/VLMEvalKit), and [OpenCompass](https://rank.opencompass.org.cn/leaderboard-multimodal/?m=REALTIME).
|
76 |
+
- Average scores are computed by normalizing each metric to a range between 0 and 100.
|
77 |
+
- Please note that evaluating the same model using different testing toolkits can result in slight differences, which is normal. Updates to code versions and variations in environment and hardware can also cause minor discrepancies in results.
|
78 |
+
|
79 |
+
|
80 |
+
|
81 |
+
Limitations: Although we have made efforts to ensure the safety of the model during the training process and to encourage the model to generate text that complies with ethical and legal requirements, the model may still produce unexpected outputs due to its size and probabilistic generation paradigm. For example, the generated responses may contain biases, discrimination, or other harmful content. Please do not propagate such content. We are not responsible for any consequences resulting from the dissemination of harmful information.
|
82 |
+
|
83 |
+
|
84 |
+
|
85 |
+
## Quick Start
|
86 |
+
|
87 |
+
We provide an example code to run Mono-InternVL-2B using `transformers`.
|
88 |
+
|
89 |
+
> Please use transformers==4.37.2TODO to ensure the model works normally.
|
90 |
+
|
91 |
+
### Model Loading
|
92 |
+
|
93 |
+
#### 16-bit (bf16 / fp16)
|
94 |
+
|
95 |
+
```python
|
96 |
+
import torch
|
97 |
+
from transformers import AutoTokenizer, AutoModel
|
98 |
+
path = "OpenGVLab/Mono-InternVL-2B"
|
99 |
+
model = AutoModel.from_pretrained(
|
100 |
+
path,
|
101 |
+
torch_dtype=torch.bfloat16,
|
102 |
+
low_cpu_mem_usage=True,
|
103 |
+
use_flash_attn=True,
|
104 |
+
trust_remote_code=True).eval().cuda()
|
105 |
+
```
|
106 |
+
|
107 |
+
#### BNB 8-bit Quantization
|
108 |
+
|
109 |
+
```python
|
110 |
+
import torch
|
111 |
+
from transformers import AutoTokenizer, AutoModel
|
112 |
+
path = "OpenGVLab/Mono-InternVL-2B"
|
113 |
+
model = AutoModel.from_pretrained(
|
114 |
+
path,
|
115 |
+
torch_dtype=torch.bfloat16,
|
116 |
+
load_in_8bit=True,
|
117 |
+
low_cpu_mem_usage=True,
|
118 |
+
use_flash_attn=True,
|
119 |
+
trust_remote_code=True).eval()
|
120 |
+
```
|
121 |
+
|
122 |
+
#### BNB 4-bit Quantization
|
123 |
+
|
124 |
+
```python
|
125 |
+
import torch
|
126 |
+
from transformers import AutoTokenizer, AutoModel
|
127 |
+
path = "OpenGVLab/Mono-InternVL-2B"
|
128 |
+
model = AutoModel.from_pretrained(
|
129 |
+
path,
|
130 |
+
torch_dtype=torch.bfloat16,
|
131 |
+
load_in_4bit=True,
|
132 |
+
low_cpu_mem_usage=True,
|
133 |
+
use_flash_attn=True,
|
134 |
+
trust_remote_code=True).eval()
|
135 |
+
```
|
136 |
+
|
137 |
+
#### Multiple GPUs
|
138 |
+
|
139 |
+
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.
|
140 |
+
|
141 |
+
```python
|
142 |
+
import math
|
143 |
+
import torch
|
144 |
+
from transformers import AutoTokenizer, AutoModel
|
145 |
+
|
146 |
+
def split_model(model_name):
|
147 |
+
device_map = {}
|
148 |
+
world_size = torch.cuda.device_count()
|
149 |
+
num_layers = {'Mono-InternVL-2B': 24}[model_name]
|
150 |
+
# Since the first GPU will be used for ViT, treat it as half a GPU.
|
151 |
+
num_layers_per_gpu = math.ceil(num_layers / (world_size - 0.5))
|
152 |
+
num_layers_per_gpu = [num_layers_per_gpu] * world_size
|
153 |
+
num_layers_per_gpu[0] = math.ceil(num_layers_per_gpu[0] * 0.5)
|
154 |
+
layer_cnt = 0
|
155 |
+
for i, num_layer in enumerate(num_layers_per_gpu):
|
156 |
+
for j in range(num_layer):
|
157 |
+
device_map[f'language_model.model.layers.{layer_cnt}'] = i
|
158 |
+
layer_cnt += 1
|
159 |
+
device_map['vision_model'] = 0
|
160 |
+
device_map['mlp1'] = 0
|
161 |
+
device_map['language_model.model.tok_embeddings'] = 0
|
162 |
+
device_map['language_model.model.embed_tokens'] = 0
|
163 |
+
device_map['language_model.output'] = 0
|
164 |
+
device_map['language_model.model.norm'] = 0
|
165 |
+
device_map['language_model.lm_head'] = 0
|
166 |
+
device_map[f'language_model.model.layers.{num_layers - 1}'] = 0
|
167 |
+
|
168 |
+
return device_map
|
169 |
+
|
170 |
+
path = "OpenGVLab/Mono-InternVL-2B"
|
171 |
+
device_map = split_model('Mono-InternVL-2B')
|
172 |
+
model = AutoModel.from_pretrained(
|
173 |
+
path,
|
174 |
+
torch_dtype=torch.bfloat16,
|
175 |
+
low_cpu_mem_usage=True,
|
176 |
+
use_flash_attn=True,
|
177 |
+
trust_remote_code=True,
|
178 |
+
device_map=device_map).eval()
|
179 |
+
```
|
180 |
+
|
181 |
+
### Inference with Transformers
|
182 |
+
|
183 |
+
```python
|
184 |
+
import numpy as np
|
185 |
+
import torch
|
186 |
+
import torchvision.transforms as T
|
187 |
+
from decord import VideoReader, cpu
|
188 |
+
from PIL import Image
|
189 |
+
from torchvision.transforms.functional import InterpolationMode
|
190 |
+
from transformers import AutoModel, AutoTokenizer
|
191 |
+
|
192 |
+
IMAGENET_MEAN = (0.485, 0.456, 0.406)
|
193 |
+
IMAGENET_STD = (0.229, 0.224, 0.225)
|
194 |
+
|
195 |
+
def build_transform(input_size):
|
196 |
+
MEAN, STD = IMAGENET_MEAN, IMAGENET_STD
|
197 |
+
transform = T.Compose([
|
198 |
+
T.Lambda(lambda img: img.convert('RGB') if img.mode != 'RGB' else img),
|
199 |
+
T.Resize((input_size, input_size), interpolation=InterpolationMode.BICUBIC),
|
200 |
+
T.ToTensor(),
|
201 |
+
T.Normalize(mean=MEAN, std=STD)
|
202 |
+
])
|
203 |
+
return transform
|
204 |
+
|
205 |
+
def find_closest_aspect_ratio(aspect_ratio, target_ratios, width, height, image_size):
|
206 |
+
best_ratio_diff = float('inf')
|
207 |
+
best_ratio = (1, 1)
|
208 |
+
area = width * height
|
209 |
+
for ratio in target_ratios:
|
210 |
+
target_aspect_ratio = ratio[0] / ratio[1]
|
211 |
+
ratio_diff = abs(aspect_ratio - target_aspect_ratio)
|
212 |
+
if ratio_diff < best_ratio_diff:
|
213 |
+
best_ratio_diff = ratio_diff
|
214 |
+
best_ratio = ratio
|
215 |
+
elif ratio_diff == best_ratio_diff:
|
216 |
+
if area > 0.5 * image_size * image_size * ratio[0] * ratio[1]:
|
217 |
+
best_ratio = ratio
|
218 |
+
return best_ratio
|
219 |
+
|
220 |
+
def dynamic_preprocess(image, min_num=1, max_num=12, image_size=448, use_thumbnail=False):
|
221 |
+
orig_width, orig_height = image.size
|
222 |
+
aspect_ratio = orig_width / orig_height
|
223 |
+
|
224 |
+
# calculate the existing image aspect ratio
|
225 |
+
target_ratios = set(
|
226 |
+
(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
|
227 |
+
i * j <= max_num and i * j >= min_num)
|
228 |
+
target_ratios = sorted(target_ratios, key=lambda x: x[0] * x[1])
|
229 |
+
|
230 |
+
# find the closest aspect ratio to the target
|
231 |
+
target_aspect_ratio = find_closest_aspect_ratio(
|
232 |
+
aspect_ratio, target_ratios, orig_width, orig_height, image_size)
|
233 |
+
|
234 |
+
# calculate the target width and height
|
235 |
+
target_width = image_size * target_aspect_ratio[0]
|
236 |
+
target_height = image_size * target_aspect_ratio[1]
|
237 |
+
blocks = target_aspect_ratio[0] * target_aspect_ratio[1]
|
238 |
+
|
239 |
+
# resize the image
|
240 |
+
resized_img = image.resize((target_width, target_height))
|
241 |
+
processed_images = []
|
242 |
+
for i in range(blocks):
|
243 |
+
box = (
|
244 |
+
(i % (target_width // image_size)) * image_size,
|
245 |
+
(i // (target_width // image_size)) * image_size,
|
246 |
+
((i % (target_width // image_size)) + 1) * image_size,
|
247 |
+
((i // (target_width // image_size)) + 1) * image_size
|
248 |
+
)
|
249 |
+
# split the image
|
250 |
+
split_img = resized_img.crop(box)
|
251 |
+
processed_images.append(split_img)
|
252 |
+
assert len(processed_images) == blocks
|
253 |
+
if use_thumbnail and len(processed_images) != 1:
|
254 |
+
thumbnail_img = image.resize((image_size, image_size))
|
255 |
+
processed_images.append(thumbnail_img)
|
256 |
+
return processed_images
|
257 |
+
|
258 |
+
def load_image(image_file, input_size=448, max_num=12):
|
259 |
+
image = Image.open(image_file).convert('RGB')
|
260 |
+
transform = build_transform(input_size=input_size)
|
261 |
+
images = dynamic_preprocess(image, image_size=input_size, use_thumbnail=True, max_num=max_num)
|
262 |
+
pixel_values = [transform(image) for image in images]
|
263 |
+
pixel_values = torch.stack(pixel_values)
|
264 |
+
return pixel_values
|
265 |
+
|
266 |
+
# If you want to load a model using multiple GPUs, please refer to the `Multiple GPUs` section.
|
267 |
+
path = 'OpenGVLab/Mono-InternVL-2B'
|
268 |
+
model = AutoModel.from_pretrained(
|
269 |
+
path,
|
270 |
+
torch_dtype=torch.bfloat16,
|
271 |
+
low_cpu_mem_usage=True,
|
272 |
+
use_flash_attn=True,
|
273 |
+
trust_remote_code=True).eval().cuda()
|
274 |
+
tokenizer = AutoTokenizer.from_pretrained(path, trust_remote_code=True, use_fast=False)
|
275 |
+
|
276 |
+
# set the max number of tiles in `max_num`
|
277 |
+
pixel_values = load_image('./examples/image1.jpg', max_num=12).to(torch.bfloat16).cuda()
|
278 |
+
generation_config = dict(max_new_tokens=1024, do_sample=True)
|
279 |
+
|
280 |
+
# pure-text conversation (纯文本对话)
|
281 |
+
question = 'Hello, who are you?'
|
282 |
+
response, history = model.chat(tokenizer, None, question, generation_config, history=None, return_history=True)
|
283 |
+
print(f'User: {question}\nAssistant: {response}')
|
284 |
+
|
285 |
+
question = 'Can you tell me a story?'
|
286 |
+
response, history = model.chat(tokenizer, None, question, generation_config, history=history, return_history=True)
|
287 |
+
print(f'User: {question}\nAssistant: {response}')
|
288 |
+
|
289 |
+
# single-image single-round conversation (单图单轮对话)
|
290 |
+
question = '<image>\nPlease describe the image shortly.'
|
291 |
+
response = model.chat(tokenizer, pixel_values, question, generation_config)
|
292 |
+
print(f'User: {question}\nAssistant: {response}')
|
293 |
+
|
294 |
+
# single-image multi-round conversation (单图多轮对话)
|
295 |
+
question = '<image>\nPlease describe the image in detail.'
|
296 |
+
response, history = model.chat(tokenizer, pixel_values, question, generation_config, history=None, return_history=True)
|
297 |
+
print(f'User: {question}\nAssistant: {response}')
|
298 |
+
|
299 |
+
question = 'Please write a poem according to the image.'
|
300 |
+
response, history = model.chat(tokenizer, pixel_values, question, generation_config, history=history, return_history=True)
|
301 |
+
print(f'User: {question}\nAssistant: {response}')
|
302 |
+
|
303 |
+
# multi-image multi-round conversation, combined images (多图多轮对话,拼接图像)
|
304 |
+
pixel_values1 = load_image('./examples/image1.jpg', max_num=12).to(torch.bfloat16).cuda()
|
305 |
+
pixel_values2 = load_image('./examples/image2.jpg', max_num=12).to(torch.bfloat16).cuda()
|
306 |
+
pixel_values = torch.cat((pixel_values1, pixel_values2), dim=0)
|
307 |
+
|
308 |
+
question = '<image>\nDescribe the two images in detail.'
|
309 |
+
response, history = model.chat(tokenizer, pixel_values, question, generation_config,
|
310 |
+
history=None, return_history=True)
|
311 |
+
print(f'User: {question}\nAssistant: {response}')
|
312 |
+
|
313 |
+
question = 'What are the similarities and differences between these two images.'
|
314 |
+
response, history = model.chat(tokenizer, pixel_values, question, generation_config,
|
315 |
+
history=history, return_history=True)
|
316 |
+
print(f'User: {question}\nAssistant: {response}')
|
317 |
+
|
318 |
+
# multi-image multi-round conversation, separate images (多图多轮对话,独立图像)
|
319 |
+
pixel_values1 = load_image('./examples/image1.jpg', max_num=12).to(torch.bfloat16).cuda()
|
320 |
+
pixel_values2 = load_image('./examples/image2.jpg', max_num=12).to(torch.bfloat16).cuda()
|
321 |
+
pixel_values = torch.cat((pixel_values1, pixel_values2), dim=0)
|
322 |
+
num_patches_list = [pixel_values1.size(0), pixel_values2.size(0)]
|
323 |
+
|
324 |
+
question = 'Image-1: <image>\nImage-2: <image>\nDescribe the two images in detail.'
|
325 |
+
response, history = model.chat(tokenizer, pixel_values, question, generation_config,
|
326 |
+
num_patches_list=num_patches_list,
|
327 |
+
history=None, return_history=True)
|
328 |
+
print(f'User: {question}\nAssistant: {response}')
|
329 |
+
|
330 |
+
question = 'What are the similarities and differences between these two images.'
|
331 |
+
response, history = model.chat(tokenizer, pixel_values, question, generation_config,
|
332 |
+
num_patches_list=num_patches_list,
|
333 |
+
history=history, return_history=True)
|
334 |
+
print(f'User: {question}\nAssistant: {response}')
|
335 |
+
|
336 |
+
# batch inference, single image per sample (单图批处理)
|
337 |
+
pixel_values1 = load_image('./examples/image1.jpg', max_num=12).to(torch.bfloat16).cuda()
|
338 |
+
pixel_values2 = load_image('./examples/image2.jpg', max_num=12).to(torch.bfloat16).cuda()
|
339 |
+
num_patches_list = [pixel_values1.size(0), pixel_values2.size(0)]
|
340 |
+
pixel_values = torch.cat((pixel_values1, pixel_values2), dim=0)
|
341 |
+
|
342 |
+
questions = ['<image>\nDescribe the image in detail.'] * len(num_patches_list)
|
343 |
+
responses = model.batch_chat(tokenizer, pixel_values,
|
344 |
+
num_patches_list=num_patches_list,
|
345 |
+
questions=questions,
|
346 |
+
generation_config=generation_config)
|
347 |
+
for question, response in zip(questions, responses):
|
348 |
+
print(f'User: {question}\nAssistant: {response}')
|
349 |
+
|
350 |
+
# video multi-round conversation (视频多轮对话)
|
351 |
+
def get_index(bound, fps, max_frame, first_idx=0, num_segments=32):
|
352 |
+
if bound:
|
353 |
+
start, end = bound[0], bound[1]
|
354 |
+
else:
|
355 |
+
start, end = -100000, 100000
|
356 |
+
start_idx = max(first_idx, round(start * fps))
|
357 |
+
end_idx = min(round(end * fps), max_frame)
|
358 |
+
seg_size = float(end_idx - start_idx) / num_segments
|
359 |
+
frame_indices = np.array([
|
360 |
+
int(start_idx + (seg_size / 2) + np.round(seg_size * idx))
|
361 |
+
for idx in range(num_segments)
|
362 |
+
])
|
363 |
+
return frame_indices
|
364 |
+
|
365 |
+
def load_video(video_path, bound=None, input_size=448, max_num=1, num_segments=32):
|
366 |
+
vr = VideoReader(video_path, ctx=cpu(0), num_threads=1)
|
367 |
+
max_frame = len(vr) - 1
|
368 |
+
fps = float(vr.get_avg_fps())
|
369 |
+
|
370 |
+
pixel_values_list, num_patches_list = [], []
|
371 |
+
transform = build_transform(input_size=input_size)
|
372 |
+
frame_indices = get_index(bound, fps, max_frame, first_idx=0, num_segments=num_segments)
|
373 |
+
for frame_index in frame_indices:
|
374 |
+
img = Image.fromarray(vr[frame_index].asnumpy()).convert('RGB')
|
375 |
+
img = dynamic_preprocess(img, image_size=input_size, use_thumbnail=True, max_num=max_num)
|
376 |
+
pixel_values = [transform(tile) for tile in img]
|
377 |
+
pixel_values = torch.stack(pixel_values)
|
378 |
+
num_patches_list.append(pixel_values.shape[0])
|
379 |
+
pixel_values_list.append(pixel_values)
|
380 |
+
pixel_values = torch.cat(pixel_values_list)
|
381 |
+
return pixel_values, num_patches_list
|
382 |
+
|
383 |
+
video_path = './examples/red-panda.mp4'
|
384 |
+
pixel_values, num_patches_list = load_video(video_path, num_segments=8, max_num=1)
|
385 |
+
pixel_values = pixel_values.to(torch.bfloat16).cuda()
|
386 |
+
video_prefix = ''.join([f'Frame{i+1}: <image>\n' for i in range(len(num_patches_list))])
|
387 |
+
question = video_prefix + 'What is the red panda doing?'
|
388 |
+
# Frame1: <image>\nFrame2: <image>\n...\nFrame8: <image>\n{question}
|
389 |
+
response, history = model.chat(tokenizer, pixel_values, question, generation_config,
|
390 |
+
num_patches_list=num_patches_list, history=None, return_history=True)
|
391 |
+
print(f'User: {question}\nAssistant: {response}')
|
392 |
+
|
393 |
+
question = 'Describe this video in detail. Don\'t repeat.'
|
394 |
+
response, history = model.chat(tokenizer, pixel_values, question, generation_config,
|
395 |
+
num_patches_list=num_patches_list, history=history, return_history=True)
|
396 |
+
print(f'User: {question}\nAssistant: {response}')
|
397 |
+
```
|
398 |
+
|
399 |
+
#### Streaming output
|
400 |
+
|
401 |
+
Besides this method, you can also use the following code to get streamed output.
|
402 |
+
|
403 |
+
```python
|
404 |
+
from transformers import TextIteratorStreamer
|
405 |
+
from threading import Thread
|
406 |
+
|
407 |
+
# Initialize the streamer
|
408 |
+
streamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True, timeout=10)
|
409 |
+
# Define the generation configuration
|
410 |
+
generation_config = dict(max_new_tokens=1024, do_sample=False, streamer=streamer)
|
411 |
+
# Start the model chat in a separate thread
|
412 |
+
thread = Thread(target=model.chat, kwargs=dict(
|
413 |
+
tokenizer=tokenizer, pixel_values=pixel_values, question=question,
|
414 |
+
history=None, return_history=False, generation_config=generation_config,
|
415 |
+
))
|
416 |
+
thread.start()
|
417 |
+
|
418 |
+
# Initialize an empty string to store the generated text
|
419 |
+
generated_text = ''
|
420 |
+
# Loop through the streamer to get the new text as it is generated
|
421 |
+
for new_text in streamer:
|
422 |
+
if new_text == model.conv_template.sep:
|
423 |
+
break
|
424 |
+
generated_text += new_text
|
425 |
+
print(new_text, end='', flush=True) # Print each new chunk of generated text on the same line
|
426 |
+
```
|
427 |
+
|
428 |
+
## Finetune
|
429 |
+
|
430 |
+
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.
|
431 |
+
|
432 |
+
## Deployment
|
433 |
+
|
434 |
+
### LMDeploy
|
435 |
+
|
436 |
+
LMDeploy is a toolkit for compressing, deploying, and serving LLM, developed by the MMRazor and MMDeploy teams.
|
437 |
+
|
438 |
+
```sh
|
439 |
+
pip install lmdeploy==0.5.3
|
440 |
+
```
|
441 |
+
|
442 |
+
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.
|
443 |
+
|
444 |
+
#### A 'Hello, world' example
|
445 |
+
|
446 |
+
```python
|
447 |
+
from lmdeploy import pipeline, TurbomindEngineConfig
|
448 |
+
from lmdeploy.vl import load_image
|
449 |
+
|
450 |
+
model = 'OpenGVLab/Mono-InternVL-2B'
|
451 |
+
image = load_image('https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/tests/data/tiger.jpeg')
|
452 |
+
pipe = pipeline(model, backend_config=TurbomindEngineConfig(session_len=8192))
|
453 |
+
response = pipe(('describe this image', image))
|
454 |
+
print(response.text)
|
455 |
+
```
|
456 |
+
|
457 |
+
If `ImportError` occurs while executing this case, please install the required dependency packages as prompted.
|
458 |
+
|
459 |
+
#### Multi-images inference
|
460 |
+
|
461 |
+
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.
|
462 |
+
|
463 |
+
> 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.
|
464 |
+
|
465 |
+
```python
|
466 |
+
from lmdeploy import pipeline, TurbomindEngineConfig
|
467 |
+
from lmdeploy.vl import load_image
|
468 |
+
from lmdeploy.vl.constants import IMAGE_TOKEN
|
469 |
+
|
470 |
+
model = 'OpenGVLab/Mono-InternVL-2B'
|
471 |
+
pipe = pipeline(model, backend_config=TurbomindEngineConfig(session_len=8192))
|
472 |
+
|
473 |
+
image_urls=[
|
474 |
+
'https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/human-pose.jpg',
|
475 |
+
'https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/det.jpg'
|
476 |
+
]
|
477 |
+
|
478 |
+
images = [load_image(img_url) for img_url in image_urls]
|
479 |
+
# Numbering images improves multi-image conversations
|
480 |
+
response = pipe((f'Image-1: {IMAGE_TOKEN}\nImage-2: {IMAGE_TOKEN}\ndescribe these two images', images))
|
481 |
+
print(response.text)
|
482 |
+
```
|
483 |
+
|
484 |
+
#### Batch prompts inference
|
485 |
+
|
486 |
+
Conducting inference with batch prompts is quite straightforward; just place them within a list structure:
|
487 |
+
|
488 |
+
```python
|
489 |
+
from lmdeploy import pipeline, TurbomindEngineConfig
|
490 |
+
from lmdeploy.vl import load_image
|
491 |
+
|
492 |
+
model = 'OpenGVLab/Mono-InternVL-2B'
|
493 |
+
pipe = pipeline(model, backend_config=TurbomindEngineConfig(session_len=8192))
|
494 |
+
|
495 |
+
image_urls=[
|
496 |
+
"https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/human-pose.jpg",
|
497 |
+
"https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/det.jpg"
|
498 |
+
]
|
499 |
+
prompts = [('describe this image', load_image(img_url)) for img_url in image_urls]
|
500 |
+
response = pipe(prompts)
|
501 |
+
print(response)
|
502 |
+
```
|
503 |
+
|
504 |
+
#### Multi-turn conversation
|
505 |
+
|
506 |
+
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.
|
507 |
+
|
508 |
+
```python
|
509 |
+
from lmdeploy import pipeline, TurbomindEngineConfig, GenerationConfig
|
510 |
+
from lmdeploy.vl import load_image
|
511 |
+
|
512 |
+
model = 'OpenGVLab/Mono-InternVL-2B'
|
513 |
+
pipe = pipeline(model, backend_config=TurbomindEngineConfig(session_len=8192))
|
514 |
+
|
515 |
+
image = load_image('https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/human-pose.jpg')
|
516 |
+
gen_config = GenerationConfig(top_k=40, top_p=0.8, temperature=0.8)
|
517 |
+
sess = pipe.chat(('describe this image', image), gen_config=gen_config)
|
518 |
+
print(sess.response.text)
|
519 |
+
sess = pipe.chat('What is the woman doing?', session=sess, gen_config=gen_config)
|
520 |
+
print(sess.response.text)
|
521 |
+
```
|
522 |
+
|
523 |
+
#### Service
|
524 |
+
|
525 |
+
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:
|
526 |
+
|
527 |
+
```shell
|
528 |
+
lmdeploy serve api_server OpenGVLab/Mono-InternVL-2B --backend turbomind --server-port 23333
|
529 |
+
```
|
530 |
+
|
531 |
+
To use the OpenAI-style interface, you need to install OpenAI:
|
532 |
+
|
533 |
+
```shell
|
534 |
+
pip install openai
|
535 |
+
```
|
536 |
+
|
537 |
+
Then, use the code below to make the API call:
|
538 |
+
|
539 |
+
```python
|
540 |
+
from openai import OpenAI
|
541 |
+
|
542 |
+
client = OpenAI(api_key='YOUR_API_KEY', base_url='http://0.0.0.0:23333/v1')
|
543 |
+
model_name = client.models.list().data[0].id
|
544 |
+
response = client.chat.completions.create(
|
545 |
+
model=model_name,
|
546 |
+
messages=[{
|
547 |
+
'role':
|
548 |
+
'user',
|
549 |
+
'content': [{
|
550 |
+
'type': 'text',
|
551 |
+
'text': 'describe this image',
|
552 |
+
}, {
|
553 |
+
'type': 'image_url',
|
554 |
+
'image_url': {
|
555 |
+
'url':
|
556 |
+
'https://modelscope.oss-cn-beijing.aliyuncs.com/resource/tiger.jpeg',
|
557 |
+
},
|
558 |
+
}],
|
559 |
+
}],
|
560 |
+
temperature=0.8,
|
561 |
+
top_p=0.8)
|
562 |
+
print(response)
|
563 |
+
```
|
564 |
+
|
565 |
+
## License
|
566 |
+
|
567 |
+
This project is released under the MIT license, while InternLM2 is licensed under the Apache-2.0 license.
|
568 |
+
|
569 |
+
## Citation
|
570 |
+
|
571 |
+
If you find this project useful in your research, please consider citing:
|
572 |
+
|
573 |
+
```BibTeX
|
574 |
+
@article{luo2024mono,
|
575 |
+
title={Mono-InternVL: Pushing the Boundaries of Monolithic Multimodal Large Language Models with Endogenous Visual Pre-training},
|
576 |
+
author={Luo, Gen and Yang, Xue and Dou, Wenhan and Wang, Zhaokai and Dai, Jifeng and Qiao, Yu and Zhu, Xizhou},
|
577 |
+
journal={arXiv preprint arXiv:2410.TODO},
|
578 |
+
year={2024}
|
579 |
+
}
|
580 |
+
```
|
581 |
+
|
582 |
+
|
583 |
+
|
584 |
+
|
585 |
+
|
586 |
+
## 简介
|
587 |
+
|
588 |
+
我们发布了Mono-InternVL,这是一种**单体化**的多模态大语言模型(MLLM),将视觉编码和文本解码集成到一个单一的大语言模型中。在Mono-InternVL中,一组视觉专家通过专家混合机制嵌入到预训练的LLM中。通过冻结LLM的语言部分参数,Mono-InternVL确保了视觉能力的优化,同时不会影响预训练的语言知识。基于这一结构,我们引入了内源视觉预训练(Endogenous Visual Pretraining, EViP),实现了由粗粒度到精粒度的视觉学习。
|
589 |
+
|
590 |
+
Mono-InternVL在性能上优于当前最先进的MLLM Mini-InternVL-2B-1.5,并且显著超越了其他单体化MLLMs,如上方的[雷达图](#radar)所示。同时,它的部署效率也得到了提升,首个token的延迟降低了最多达67%。
|
591 |
+
|
592 |
+
本仓库包含了经过指令微调的Mono-InternVL-2B模型,它是基于[internlm2-chat-1_8b](https://huggingface.co/internlm/internlm2-chat-1_8b)搭建的。更多详细信息,请参阅我们的[论文](TODO)。
|
593 |
+
|
594 |
+
|
595 |
+
|
596 |
+
## 性能测试
|
597 |
+
|
598 |
+
| 评测数据集 | Chameleon-7B | EVE-7B (HD) | Emu3 | Mini-InternVL-2B-1-5 | Mono-InternVL-2B |
|
599 |
+
| :--------------------------: | :----------: | :---------: | :----: | :------------------: | :--------------: |
|
600 |
+
| 模型种类 | 单体化 | 单体化 | 单体化 | 模块化 | 单体化 |
|
601 |
+
| 激活参数 | 7B | 7B | 8B | 2.2B | 1.8B |
|
602 |
+
| | | | | | |
|
603 |
+
| MMVet | 8.3 | 25.7 | 37.2 | 39.3 | 40.1 |
|
604 |
+
| MMMU<sub>val</sub> | 25.4 | 32.6 | 31.6 | 34.6 | 33.7 |
|
605 |
+
| MME<sub>sum</sub> | 170 | 1628 | — | 1902 | 1875 |
|
606 |
+
| MMBench-EN<sub>test</sub> | 31.1 | 52.3 | 58.5 | 70.9 | 65.5 |
|
607 |
+
| MathVista<sub>testmini</sub> | 22.3 | 34.2 | — | 41.1 | 45.7 |
|
608 |
+
| SEED-Image | 30.6 | 64.6 | 68.2 | 69.8 | 67.4 |
|
609 |
+
| OCRBench | 7 | 398 | 687 | 654 | 767 |
|
610 |
+
| Hallusion-Bench | 17.1 | 26.4 | — | 37.5 | 34.8 |
|
611 |
+
| CCBench<sub>dev</sub> | 3.5 | 16.3 | — | 63.5 | 66.3 |
|
612 |
+
| Avg<sub>multimodal</sub> | 16.1 | 38.9 | — | 54.4 | 55.2 |
|
613 |
+
| | | | | | |
|
614 |
+
| TextVQA<sub>val</sub> | 4.8 | 56.8 | 64.7 | 70.5 | 72.6 |
|
615 |
+
| SQA-I<sub>test</sub> | 47.2 | 64.9 | 89.2 | 84.9 | 93.6 |
|
616 |
+
| GQA<sub>test</sub> | — | 62.6 | 60.3 | 61.6 | 59.5 |
|
617 |
+
| DocVQA<sub>test</sub> | 1.5 | 53.0 | 76.3 | 85.0 | 80.0 |
|
618 |
+
| AI2D<sub>test</sub> | 46.0 | 61.0 | 70.0 | 69.8 | 68.6 |
|
619 |
+
| ChartQA<sub>test</sub> | 2.9 | 59.1 | 68.6 | 74.8 | 73.7 |
|
620 |
+
| InfoVQA<sub>test</sub> | 5.0 | 25.0 | 43.8 | 55.4 | 43.0 |
|
621 |
+
| Avg<sub>VQA</sub> | 17.9 | 54.6 | 67.6 | 71.7 | 70.1 |
|
622 |
+
|
623 |
+
- 以上结果的来源包括相应的原始论文、我们基于[VLMEvalKit](https://github.com/open-compass/VLMEvalKit)的评测,以及[OpenCompass](https://rank.opencompass.org.cn/leaderboard-multimodal/?m=REALTIME)。
|
624 |
+
- 平均分数Avg通过将每个指标归一化到0至100之间来计算。
|
625 |
+
- 请注意,使用不同的测试工具包评估同一模型可能会导致细微差异,这是正常的。代码版本的更新、环境和硬件的变化也可能导致结果的微小差异。
|
626 |
+
|
627 |
+
|
628 |
+
|
629 |
+
## 快速启动
|
630 |
+
|
631 |
+
我们提供了一个示例代码,用于使用 `transformers` 运行 Mono-InternVL-2B。
|
632 |
+
|
633 |
+
> 请使用 transformers==4.37.2 以确保模型正常运行。
|
634 |
+
|
635 |
+
示例代码请[点击这里](#quick-start)。
|
636 |
+
|
637 |
+
## 微调
|
638 |
+
|
639 |
+
许多仓库现在都支持 InternVL 系列模型的微调,包括 [InternVL](https://github.com/OpenGVLab/InternVL)、[SWIFT](https://github.com/modelscope/ms-swift)、[XTurner](https://github.com/InternLM/xtuner) 等。请参阅它们的文档以获取更多微调细节。
|
640 |
+
|
641 |
+
## 部署
|
642 |
+
|
643 |
+
### LMDeploy
|
644 |
+
|
645 |
+
LMDeploy 是由 MMRazor 和 MMDeploy 团队开发的用于压缩、部署和服务大语言模型(LLM)的工具包。
|
646 |
+
|
647 |
+
```sh
|
648 |
+
pip install lmdeploy==0.5.3
|
649 |
+
```
|
650 |
+
|
651 |
+
LMDeploy 将多模态视觉-语言模型(VLM)的复杂推理过程抽象为一个易于使用的管道,类似于大语言模型(LLM)的推理管道。
|
652 |
+
|
653 |
+
#### 一个“你好,世界”示例
|
654 |
+
|
655 |
+
```python
|
656 |
+
from lmdeploy import pipeline, TurbomindEngineConfig
|
657 |
+
from lmdeploy.vl import load_image
|
658 |
+
|
659 |
+
model = 'OpenGVLab/Mono-InternVL-2B'
|
660 |
+
image = load_image('https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/tests/data/tiger.jpeg')
|
661 |
+
pipe = pipeline(model, backend_config=TurbomindEngineConfig(session_len=8192))
|
662 |
+
response = pipe(('describe this image', image))
|
663 |
+
print(response.text)
|
664 |
+
```
|
665 |
+
|
666 |
+
如果在执行此示例时出现 `ImportError`,请按照提示安装所需的依赖包。
|
667 |
+
|
668 |
+
#### 多图像推理
|
669 |
+
|
670 |
+
在处理多张图像时,可以将它们全部放入一个列表中。请注意,多张图像会导致输入 token 数量增加,因此通常需要增加上下文窗口的大小。
|
671 |
+
|
672 |
+
```python
|
673 |
+
from lmdeploy import pipeline, TurbomindEngineConfig
|
674 |
+
from lmdeploy.vl import load_image
|
675 |
+
from lmdeploy.vl.constants import IMAGE_TOKEN
|
676 |
+
|
677 |
+
model = 'OpenGVLab/Mono-InternVL-2B'
|
678 |
+
pipe = pipeline(model, backend_config=TurbomindEngineConfig(session_len=8192))
|
679 |
+
|
680 |
+
image_urls=[
|
681 |
+
'https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/human-pose.jpg',
|
682 |
+
'https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/det.jpg'
|
683 |
+
]
|
684 |
+
|
685 |
+
images = [load_image(img_url) for img_url in image_urls]
|
686 |
+
# Numbering images improves multi-image conversations
|
687 |
+
response = pipe((f'Image-1: {IMAGE_TOKEN}\nImage-2: {IMAGE_TOKEN}\ndescribe these two images', images))
|
688 |
+
print(response.text)
|
689 |
+
```
|
690 |
+
|
691 |
+
#### 批量Prompt推理
|
692 |
+
|
693 |
+
使用批量Prompt进行推理非常简单;只需将它们放在一个列表结构中:
|
694 |
+
|
695 |
+
```python
|
696 |
+
from lmdeploy import pipeline, TurbomindEngineConfig
|
697 |
+
from lmdeploy.vl import load_image
|
698 |
+
|
699 |
+
model = 'OpenGVLab/Mono-InternVL-2B'
|
700 |
+
pipe = pipeline(model, backend_config=TurbomindEngineConfig(session_len=8192))
|
701 |
+
|
702 |
+
image_urls=[
|
703 |
+
"https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/human-pose.jpg",
|
704 |
+
"https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/det.jpg"
|
705 |
+
]
|
706 |
+
prompts = [('describe this image', load_image(img_url)) for img_url in image_urls]
|
707 |
+
response = pipe(prompts)
|
708 |
+
print(response)
|
709 |
+
```
|
710 |
+
|
711 |
+
#### 多轮对话
|
712 |
+
|
713 |
+
使用管道进行多轮对话有两种方法。一种是根据 OpenAI 的格式构建消息并使用上述方法,另一种是使用 `pipeline.chat` 接口。
|
714 |
+
|
715 |
+
```python
|
716 |
+
from lmdeploy import pipeline, TurbomindEngineConfig, GenerationConfig
|
717 |
+
from lmdeploy.vl import load_image
|
718 |
+
|
719 |
+
model = 'OpenGVLab/Mono-InternVL-2B'
|
720 |
+
pipe = pipeline(model, backend_config=TurbomindEngineConfig(session_len=8192))
|
721 |
+
|
722 |
+
image = load_image('https://raw.githubusercontent.com/open-mmlab/mmdeploy/main/demo/resources/human-pose.jpg')
|
723 |
+
gen_config = GenerationConfig(top_k=40, top_p=0.8, temperature=0.8)
|
724 |
+
sess = pipe.chat(('describe this image', image), gen_config=gen_config)
|
725 |
+
print(sess.response.text)
|
726 |
+
sess = pipe.chat('What is the woman doing?', session=sess, gen_config=gen_config)
|
727 |
+
print(sess.response.text)
|
728 |
+
```
|
729 |
+
|
730 |
+
#### API部署
|
731 |
+
|
732 |
+
LMDeploy 的 `api_server` 使模型能够通过一个命令轻松打包成服务。提供的 RESTful API 与 OpenAI 的接口兼容。以下是服务启动的示例:
|
733 |
+
|
734 |
+
```shell
|
735 |
+
lmdeploy serve api_server OpenGVLab/Mono-InternVL-2B --backend turbomind --server-port 23333
|
736 |
+
```
|
737 |
+
|
738 |
+
为了使用OpenAI风格的API接口,您需要安装OpenAI:
|
739 |
+
|
740 |
+
```shell
|
741 |
+
pip install openai
|
742 |
+
```
|
743 |
+
|
744 |
+
然后,使用下面的代码进行API调用:
|
745 |
+
|
746 |
+
```python
|
747 |
+
from openai import OpenAI
|
748 |
+
|
749 |
+
client = OpenAI(api_key='YOUR_API_KEY', base_url='http://0.0.0.0:23333/v1')
|
750 |
+
model_name = client.models.list().data[0].id
|
751 |
+
response = client.chat.completions.create(
|
752 |
+
model=model_name,
|
753 |
+
messages=[{
|
754 |
+
'role':
|
755 |
+
'user',
|
756 |
+
'content': [{
|
757 |
+
'type': 'text',
|
758 |
+
'text': 'describe this image',
|
759 |
+
}, {
|
760 |
+
'type': 'image_url',
|
761 |
+
'image_url': {
|
762 |
+
'url':
|
763 |
+
'https://modelscope.oss-cn-beijing.aliyuncs.com/resource/tiger.jpeg',
|
764 |
+
},
|
765 |
+
}],
|
766 |
+
}],
|
767 |
+
temperature=0.8,
|
768 |
+
top_p=0.8)
|
769 |
+
print(response)
|
770 |
+
```
|
771 |
+
|
772 |
+
## 开源许可证
|
773 |
+
|
774 |
+
该项目采用 MIT 许可证发布,而 InternLM2 则采用 Apache-2.0 许可证。
|
775 |
+
|
776 |
+
## 引用
|
777 |
+
|
778 |
+
如果您发现此项目对您的研究有用,可以考虑引用我们的论文:
|
779 |
+
|
780 |
+
```BibTeX
|
781 |
+
@article{luo2024mono,
|
782 |
+
title={Mono-InternVL: Pushing the Boundaries of Monolithic Multimodal Large Language Models with Endogenous Visual Pre-training},
|
783 |
+
author={Luo, Gen and Yang, Xue and Dou, Wenhan and Wang, Zhaokai and Dai, Jifeng and Qiao, Yu and Zhu, Xizhou},
|
784 |
+
journal={arXiv preprint arXiv:2410.TODO},
|
785 |
+
year={2024}
|
786 |
+
}
|
787 |
+
```
|