README.md
17.0 KB · 500 lines · markdown Raw
1 ---
2 license: apache-2.0
3 language:
4 - en
5 pipeline_tag: image-text-to-text
6 tags:
7 - multimodal
8 library_name: transformers
9 base_model:
10 - Qwen/Qwen2-VL-2B
11 ---
12
13 # Qwen2-VL-2B-Instruct
14 <a href="https://chat.qwenlm.ai/" target="_blank" style="margin: 2px;">
15 <img alt="Chat" src="https://img.shields.io/badge/%F0%9F%92%9C%EF%B8%8F%20Qwen%20Chat%20-536af5" style="display: inline-block; vertical-align: middle;"/>
16 </a>
17
18 ## Introduction
19
20 We're excited to unveil **Qwen2-VL**, the latest iteration of our Qwen-VL model, representing nearly a year of innovation.
21
22 ### What’s New in Qwen2-VL?
23
24 #### Key Enhancements:
25
26
27 * **SoTA understanding of images of various resolution & ratio**: Qwen2-VL achieves state-of-the-art performance on visual understanding benchmarks, including MathVista, DocVQA, RealWorldQA, MTVQA, etc.
28
29 * **Understanding videos of 20min+**: Qwen2-VL can understand videos over 20 minutes for high-quality video-based question answering, dialog, content creation, etc.
30
31 * **Agent that can operate your mobiles, robots, etc.**: with the abilities of complex reasoning and decision making, Qwen2-VL can be integrated with devices like mobile phones, robots, etc., for automatic operation based on visual environment and text instructions.
32
33 * **Multilingual Support**: to serve global users, besides English and Chinese, Qwen2-VL now supports the understanding of texts in different languages inside images, including most European languages, Japanese, Korean, Arabic, Vietnamese, etc.
34
35
36 #### Model Architecture Updates:
37
38 * **Naive Dynamic Resolution**: Unlike before, Qwen2-VL can handle arbitrary image resolutions, mapping them into a dynamic number of visual tokens, offering a more human-like visual processing experience.
39
40 <p align="center">
41 <img src="https://qianwen-res.oss-accelerate-overseas.aliyuncs.com/Qwen2-VL/qwen2_vl.jpg" width="80%"/>
42 <p>
43
44 * **Multimodal Rotary Position Embedding (M-ROPE)**: Decomposes positional embedding into parts to capture 1D textual, 2D visual, and 3D video positional information, enhancing its multimodal processing capabilities.
45
46 <p align="center">
47 <img src="http://qianwen-res.oss-accelerate-overseas.aliyuncs.com/Qwen2-VL/mrope.png" width="80%"/>
48 <p>
49
50 We have three models with 2, 7 and 72 billion parameters. This repo contains the instruction-tuned 2B Qwen2-VL model. For more information, visit our [Blog](https://qwenlm.github.io/blog/qwen2-vl/) and [GitHub](https://github.com/QwenLM/Qwen2-VL).
51
52
53
54 ## Evaluation
55
56 ### Image Benchmarks
57
58 | Benchmark | InternVL2-2B | MiniCPM-V 2.0 | **Qwen2-VL-2B** |
59 | :--- | :---: | :---: | :---: |
60 | MMMU<sub>val</sub> | 36.3 | 38.2 | **41.1** |
61 | DocVQA<sub>test</sub> | 86.9 | - | **90.1** |
62 | InfoVQA<sub>test</sub> | 58.9 | - | **65.5** |
63 | ChartQA<sub>test</sub> | **76.2** | - | 73.5 |
64 | TextVQA<sub>val</sub> | 73.4 | - | **79.7** |
65 | OCRBench | 781 | 605 | **794** |
66 | MTVQA | - | - | **20.0** |
67 | VCR<sub>en easy</sub> | - | - | **81.45**
68 | VCR<sub>zh easy</sub> | - | - | **46.16**
69 | RealWorldQA | 57.3 | 55.8 | **62.9** |
70 | MME<sub>sum</sub> | **1876.8** | 1808.6 | 1872.0 |
71 | MMBench-EN<sub>test</sub> | 73.2 | 69.1 | **74.9** |
72 | MMBench-CN<sub>test</sub> | 70.9 | 66.5 | **73.5** |
73 | MMBench-V1.1<sub>test</sub> | 69.6 | 65.8 | **72.2** |
74 | MMT-Bench<sub>test</sub> | - | - | **54.5** |
75 | MMStar | **49.8** | 39.1 | 48.0 |
76 | MMVet<sub>GPT-4-Turbo</sub> | 39.7 | 41.0 | **49.5** |
77 | HallBench<sub>avg</sub> | 38.0 | 36.1 | **41.7** |
78 | MathVista<sub>testmini</sub> | **46.0** | 39.8 | 43.0 |
79 | MathVision | - | - | **12.4** |
80
81 ### Video Benchmarks
82
83 | Benchmark | **Qwen2-VL-2B** |
84 | :--- | :---: |
85 | MVBench | **63.2** |
86 | PerceptionTest<sub>test</sub> | **53.9** |
87 | EgoSchema<sub>test</sub> | **54.9** |
88 | Video-MME<sub>wo/w subs</sub> | **55.6**/**60.4** |
89
90
91 ## Requirements
92 The code of Qwen2-VL has been in the latest Hugging face transformers and we advise you to build from source with command `pip install git+https://github.com/huggingface/transformers`, or you might encounter the following error:
93 ```
94 KeyError: 'qwen2_vl'
95 ```
96
97 ## Quickstart
98 We offer a toolkit to help you handle various types of visual input more conveniently. This includes base64, URLs, and interleaved images and videos. You can install it using the following command:
99
100 ```bash
101 pip install qwen-vl-utils
102 ```
103
104 Here we show a code snippet to show you how to use the chat model with `transformers` and `qwen_vl_utils`:
105
106 ```python
107 from transformers import Qwen2VLForConditionalGeneration, AutoTokenizer, AutoProcessor
108 from qwen_vl_utils import process_vision_info
109
110 # default: Load the model on the available device(s)
111 model = Qwen2VLForConditionalGeneration.from_pretrained(
112 "Qwen/Qwen2-VL-2B-Instruct", torch_dtype="auto", device_map="auto"
113 )
114
115 # We recommend enabling flash_attention_2 for better acceleration and memory saving, especially in multi-image and video scenarios.
116 # model = Qwen2VLForConditionalGeneration.from_pretrained(
117 # "Qwen/Qwen2-VL-2B-Instruct",
118 # torch_dtype=torch.bfloat16,
119 # attn_implementation="flash_attention_2",
120 # device_map="auto",
121 # )
122
123 # default processer
124 processor = AutoProcessor.from_pretrained("Qwen/Qwen2-VL-2B-Instruct")
125
126 # The default range for the number of visual tokens per image in the model is 4-16384. You can set min_pixels and max_pixels according to your needs, such as a token count range of 256-1280, to balance speed and memory usage.
127 # min_pixels = 256*28*28
128 # max_pixels = 1280*28*28
129 # processor = AutoProcessor.from_pretrained("Qwen/Qwen2-VL-2B-Instruct", min_pixels=min_pixels, max_pixels=max_pixels)
130
131 messages = [
132 {
133 "role": "user",
134 "content": [
135 {
136 "type": "image",
137 "image": "https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen-VL/assets/demo.jpeg",
138 },
139 {"type": "text", "text": "Describe this image."},
140 ],
141 }
142 ]
143
144 # Preparation for inference
145 text = processor.apply_chat_template(
146 messages, tokenize=False, add_generation_prompt=True
147 )
148 image_inputs, video_inputs = process_vision_info(messages)
149 inputs = processor(
150 text=[text],
151 images=image_inputs,
152 videos=video_inputs,
153 padding=True,
154 return_tensors="pt",
155 )
156 inputs = inputs.to("cuda")
157
158 # Inference: Generation of the output
159 generated_ids = model.generate(**inputs, max_new_tokens=128)
160 generated_ids_trimmed = [
161 out_ids[len(in_ids) :] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
162 ]
163 output_text = processor.batch_decode(
164 generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
165 )
166 print(output_text)
167 ```
168 <details>
169 <summary>Without qwen_vl_utils</summary>
170
171 ```python
172 from PIL import Image
173 import requests
174 import torch
175 from torchvision import io
176 from typing import Dict
177 from transformers import Qwen2VLForConditionalGeneration, AutoTokenizer, AutoProcessor
178
179 # Load the model in half-precision on the available device(s)
180 model = Qwen2VLForConditionalGeneration.from_pretrained(
181 "Qwen/Qwen2-VL-2B-Instruct", torch_dtype="auto", device_map="auto"
182 )
183 processor = AutoProcessor.from_pretrained("Qwen/Qwen2-VL-2B-Instruct")
184
185 # Image
186 url = "https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen-VL/assets/demo.jpeg"
187 image = Image.open(requests.get(url, stream=True).raw)
188
189 conversation = [
190 {
191 "role": "user",
192 "content": [
193 {
194 "type": "image",
195 },
196 {"type": "text", "text": "Describe this image."},
197 ],
198 }
199 ]
200
201
202 # Preprocess the inputs
203 text_prompt = processor.apply_chat_template(conversation, add_generation_prompt=True)
204 # Excepted output: '<|im_start|>system\nYou are a helpful assistant.<|im_end|>\n<|im_start|>user\n<|vision_start|><|image_pad|><|vision_end|>Describe this image.<|im_end|>\n<|im_start|>assistant\n'
205
206 inputs = processor(
207 text=[text_prompt], images=[image], padding=True, return_tensors="pt"
208 )
209 inputs = inputs.to("cuda")
210
211 # Inference: Generation of the output
212 output_ids = model.generate(**inputs, max_new_tokens=128)
213 generated_ids = [
214 output_ids[len(input_ids) :]
215 for input_ids, output_ids in zip(inputs.input_ids, output_ids)
216 ]
217 output_text = processor.batch_decode(
218 generated_ids, skip_special_tokens=True, clean_up_tokenization_spaces=True
219 )
220 print(output_text)
221 ```
222 </details>
223
224 <details>
225 <summary>Multi image inference</summary>
226
227 ```python
228 # Messages containing multiple images and a text query
229 messages = [
230 {
231 "role": "user",
232 "content": [
233 {"type": "image", "image": "file:///path/to/image1.jpg"},
234 {"type": "image", "image": "file:///path/to/image2.jpg"},
235 {"type": "text", "text": "Identify the similarities between these images."},
236 ],
237 }
238 ]
239
240 # Preparation for inference
241 text = processor.apply_chat_template(
242 messages, tokenize=False, add_generation_prompt=True
243 )
244 image_inputs, video_inputs = process_vision_info(messages)
245 inputs = processor(
246 text=[text],
247 images=image_inputs,
248 videos=video_inputs,
249 padding=True,
250 return_tensors="pt",
251 )
252 inputs = inputs.to("cuda")
253
254 # Inference
255 generated_ids = model.generate(**inputs, max_new_tokens=128)
256 generated_ids_trimmed = [
257 out_ids[len(in_ids) :] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
258 ]
259 output_text = processor.batch_decode(
260 generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
261 )
262 print(output_text)
263 ```
264 </details>
265
266 <details>
267 <summary>Video inference</summary>
268
269 ```python
270 # Messages containing a images list as a video and a text query
271 messages = [
272 {
273 "role": "user",
274 "content": [
275 {
276 "type": "video",
277 "video": [
278 "file:///path/to/frame1.jpg",
279 "file:///path/to/frame2.jpg",
280 "file:///path/to/frame3.jpg",
281 "file:///path/to/frame4.jpg",
282 ],
283 "fps": 1.0,
284 },
285 {"type": "text", "text": "Describe this video."},
286 ],
287 }
288 ]
289 # Messages containing a video and a text query
290 messages = [
291 {
292 "role": "user",
293 "content": [
294 {
295 "type": "video",
296 "video": "file:///path/to/video1.mp4",
297 "max_pixels": 360 * 420,
298 "fps": 1.0,
299 },
300 {"type": "text", "text": "Describe this video."},
301 ],
302 }
303 ]
304
305 # Preparation for inference
306 text = processor.apply_chat_template(
307 messages, tokenize=False, add_generation_prompt=True
308 )
309 image_inputs, video_inputs = process_vision_info(messages)
310 inputs = processor(
311 text=[text],
312 images=image_inputs,
313 videos=video_inputs,
314 padding=True,
315 return_tensors="pt",
316 )
317 inputs = inputs.to("cuda")
318
319 # Inference
320 generated_ids = model.generate(**inputs, max_new_tokens=128)
321 generated_ids_trimmed = [
322 out_ids[len(in_ids) :] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
323 ]
324 output_text = processor.batch_decode(
325 generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
326 )
327 print(output_text)
328 ```
329 </details>
330
331 <details>
332 <summary>Batch inference</summary>
333
334 ```python
335 # Sample messages for batch inference
336 messages1 = [
337 {
338 "role": "user",
339 "content": [
340 {"type": "image", "image": "file:///path/to/image1.jpg"},
341 {"type": "image", "image": "file:///path/to/image2.jpg"},
342 {"type": "text", "text": "What are the common elements in these pictures?"},
343 ],
344 }
345 ]
346 messages2 = [
347 {"role": "system", "content": "You are a helpful assistant."},
348 {"role": "user", "content": "Who are you?"},
349 ]
350 # Combine messages for batch processing
351 messages = [messages1, messages1]
352
353 # Preparation for batch inference
354 texts = [
355 processor.apply_chat_template(msg, tokenize=False, add_generation_prompt=True)
356 for msg in messages
357 ]
358 image_inputs, video_inputs = process_vision_info(messages)
359 inputs = processor(
360 text=texts,
361 images=image_inputs,
362 videos=video_inputs,
363 padding=True,
364 return_tensors="pt",
365 )
366 inputs = inputs.to("cuda")
367
368 # Batch Inference
369 generated_ids = model.generate(**inputs, max_new_tokens=128)
370 generated_ids_trimmed = [
371 out_ids[len(in_ids) :] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
372 ]
373 output_texts = processor.batch_decode(
374 generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
375 )
376 print(output_texts)
377 ```
378 </details>
379
380 ### More Usage Tips
381
382 For input images, we support local files, base64, and URLs. For videos, we currently only support local files.
383
384 ```python
385 # You can directly insert a local file path, a URL, or a base64-encoded image into the position where you want in the text.
386 ## Local file path
387 messages = [
388 {
389 "role": "user",
390 "content": [
391 {"type": "image", "image": "file:///path/to/your/image.jpg"},
392 {"type": "text", "text": "Describe this image."},
393 ],
394 }
395 ]
396 ## Image URL
397 messages = [
398 {
399 "role": "user",
400 "content": [
401 {"type": "image", "image": "http://path/to/your/image.jpg"},
402 {"type": "text", "text": "Describe this image."},
403 ],
404 }
405 ]
406 ## Base64 encoded image
407 messages = [
408 {
409 "role": "user",
410 "content": [
411 {"type": "image", "image": "data:image;base64,/9j/..."},
412 {"type": "text", "text": "Describe this image."},
413 ],
414 }
415 ]
416 ```
417 #### Image Resolution for performance boost
418
419 The model supports a wide range of resolution inputs. By default, it uses the native resolution for input, but higher resolutions can enhance performance at the cost of more computation. Users can set the minimum and maximum number of pixels to achieve an optimal configuration for their needs, such as a token count range of 256-1280, to balance speed and memory usage.
420
421 ```python
422 min_pixels = 256 * 28 * 28
423 max_pixels = 1280 * 28 * 28
424 processor = AutoProcessor.from_pretrained(
425 "Qwen/Qwen2-VL-2B-Instruct", min_pixels=min_pixels, max_pixels=max_pixels
426 )
427 ```
428
429 Besides, We provide two methods for fine-grained control over the image size input to the model:
430
431 1. Define min_pixels and max_pixels: Images will be resized to maintain their aspect ratio within the range of min_pixels and max_pixels.
432
433 2. Specify exact dimensions: Directly set `resized_height` and `resized_width`. These values will be rounded to the nearest multiple of 28.
434
435 ```python
436 # min_pixels and max_pixels
437 messages = [
438 {
439 "role": "user",
440 "content": [
441 {
442 "type": "image",
443 "image": "file:///path/to/your/image.jpg",
444 "resized_height": 280,
445 "resized_width": 420,
446 },
447 {"type": "text", "text": "Describe this image."},
448 ],
449 }
450 ]
451 # resized_height and resized_width
452 messages = [
453 {
454 "role": "user",
455 "content": [
456 {
457 "type": "image",
458 "image": "file:///path/to/your/image.jpg",
459 "min_pixels": 50176,
460 "max_pixels": 50176,
461 },
462 {"type": "text", "text": "Describe this image."},
463 ],
464 }
465 ]
466 ```
467
468 ## Limitations
469
470 While Qwen2-VL are applicable to a wide range of visual tasks, it is equally important to understand its limitations. Here are some known restrictions:
471
472 1. Lack of Audio Support: The current model does **not comprehend audio information** within videos.
473 2. Data timeliness: Our image dataset is **updated until June 2023**, and information subsequent to this date may not be covered.
474 3. Constraints in Individuals and Intellectual Property (IP): The model's capacity to recognize specific individuals or IPs is limited, potentially failing to comprehensively cover all well-known personalities or brands.
475 4. Limited Capacity for Complex Instruction: When faced with intricate multi-step instructions, the model's understanding and execution capabilities require enhancement.
476 5. Insufficient Counting Accuracy: Particularly in complex scenes, the accuracy of object counting is not high, necessitating further improvements.
477 6. Weak Spatial Reasoning Skills: Especially in 3D spaces, the model's inference of object positional relationships is inadequate, making it difficult to precisely judge the relative positions of objects.
478
479 These limitations serve as ongoing directions for model optimization and improvement, and we are committed to continually enhancing the model's performance and scope of application.
480
481
482 ## Citation
483
484 If you find our work helpful, feel free to give us a cite.
485
486 ```
487 @article{Qwen2VL,
488 title={Qwen2-VL: Enhancing Vision-Language Model's Perception of the World at Any Resolution},
489 author={Wang, Peng and Bai, Shuai and Tan, Sinan and Wang, Shijie and Fan, Zhihao and Bai, Jinze and Chen, Keqin and Liu, Xuejing and Wang, Jialin and Ge, Wenbin and Fan, Yang and Dang, Kai and Du, Mengfei and Ren, Xuancheng and Men, Rui and Liu, Dayiheng and Zhou, Chang and Zhou, Jingren and Lin, Junyang},
490 journal={arXiv preprint arXiv:2409.12191},
491 year={2024}
492 }
493
494 @article{Qwen-VL,
495 title={Qwen-VL: A Versatile Vision-Language Model for Understanding, Localization, Text Reading, and Beyond},
496 author={Bai, Jinze and Bai, Shuai and Yang, Shusheng and Wang, Shijie and Tan, Sinan and Wang, Peng and Lin, Junyang and Zhou, Chang and Zhou, Jingren},
497 journal={arXiv preprint arXiv:2308.12966},
498 year={2023}
499 }
500 ```