README.md
17.3 KB · 502 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-7B
11 new_version: Qwen/Qwen2.5-VL-7B-Instruct
12 ---
13
14 # Qwen2-VL-7B-Instruct
15 <a href="https://chat.qwenlm.ai/" target="_blank" style="margin: 2px;">
16 <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;"/>
17 </a>
18
19 ## Introduction
20
21 We're excited to unveil **Qwen2-VL**, the latest iteration of our Qwen-VL model, representing nearly a year of innovation.
22
23 ### What’s New in Qwen2-VL?
24
25 #### Key Enhancements:
26
27
28 * **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.
29
30 * **Understanding videos of 20min+**: Qwen2-VL can understand videos over 20 minutes for high-quality video-based question answering, dialog, content creation, etc.
31
32 * **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.
33
34 * **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.
35
36
37 #### Model Architecture Updates:
38
39 * **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.
40
41 <p align="center">
42 <img src="https://qianwen-res.oss-accelerate-overseas.aliyuncs.com/Qwen2-VL/qwen2_vl.jpg" width="80%"/>
43 <p>
44
45 * **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.
46
47 <p align="center">
48 <img src="http://qianwen-res.oss-accelerate-overseas.aliyuncs.com/Qwen2-VL/mrope.png" width="80%"/>
49 <p>
50
51 We have three models with 2, 7 and 72 billion parameters. This repo contains the instruction-tuned 7B Qwen2-VL model. For more information, visit our [Blog](https://qwenlm.github.io/blog/qwen2-vl/) and [GitHub](https://github.com/QwenLM/Qwen2-VL).
52
53
54
55 ## Evaluation
56
57 ### Image Benchmarks
58
59 | Benchmark | InternVL2-8B | MiniCPM-V 2.6 | GPT-4o-mini | **Qwen2-VL-7B** |
60 | :--- | :---: | :---: | :---: | :---: |
61 | MMMU<sub>val</sub> | 51.8 | 49.8 | **60**| 54.1 |
62 | DocVQA<sub>test</sub> | 91.6 | 90.8 | - | **94.5** |
63 | InfoVQA<sub>test</sub> | 74.8 | - | - |**76.5** |
64 | ChartQA<sub>test</sub> | **83.3** | - |- | 83.0 |
65 | TextVQA<sub>val</sub> | 77.4 | 80.1 | -| **84.3** |
66 | OCRBench | 794 | **852** | 785 | 845 |
67 | MTVQA | - | - | -| **26.3** |
68 | VCR<sub>en easy</sub> | - | 73.88 | 83.60 | **89.70** |
69 | VCR<sub>zh easy</sub> | - | 10.18| 1.10 | **59.94** |
70 | RealWorldQA | 64.4 | - | - | **70.1** |
71 | MME<sub>sum</sub> | 2210.3 | **2348.4** | 2003.4| 2326.8 |
72 | MMBench-EN<sub>test</sub> | 81.7 | - | - | **83.0** |
73 | MMBench-CN<sub>test</sub> | **81.2** | - | - | 80.5 |
74 | MMBench-V1.1<sub>test</sub> | 79.4 | 78.0 | 76.0| **80.7** |
75 | MMT-Bench<sub>test</sub> | - | - | - |**63.7** |
76 | MMStar | **61.5** | 57.5 | 54.8 | 60.7 |
77 | MMVet<sub>GPT-4-Turbo</sub> | 54.2 | 60.0 | **66.9** | 62.0 |
78 | HallBench<sub>avg</sub> | 45.2 | 48.1 | 46.1| **50.6** |
79 | MathVista<sub>testmini</sub> | 58.3 | **60.6** | 52.4 | 58.2 |
80 | MathVision | - | - | - | **16.3** |
81
82 ### Video Benchmarks
83
84 | Benchmark | Internvl2-8B | LLaVA-OneVision-7B | MiniCPM-V 2.6 | **Qwen2-VL-7B** |
85 | :--- | :---: | :---: | :---: | :---: |
86 | MVBench | 66.4 | 56.7 | - | **67.0** |
87 | PerceptionTest<sub>test</sub> | - | 57.1 | - | **62.3** |
88 | EgoSchema<sub>test</sub> | - | 60.1 | - | **66.7** |
89 | Video-MME<sub>wo/w subs</sub> | 54.0/56.9 | 58.2/- | 60.9/63.6 | **63.3**/**69.0** |
90
91
92
93
94 ## Requirements
95 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:
96 ```
97 KeyError: 'qwen2_vl'
98 ```
99
100 ## Quickstart
101 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:
102
103 ```bash
104 pip install qwen-vl-utils
105 ```
106
107 Here we show a code snippet to show you how to use the chat model with `transformers` and `qwen_vl_utils`:
108
109 ```python
110 from transformers import Qwen2VLForConditionalGeneration, AutoTokenizer, AutoProcessor
111 from qwen_vl_utils import process_vision_info
112
113 # default: Load the model on the available device(s)
114 model = Qwen2VLForConditionalGeneration.from_pretrained(
115 "Qwen/Qwen2-VL-7B-Instruct", torch_dtype="auto", device_map="auto"
116 )
117
118 # We recommend enabling flash_attention_2 for better acceleration and memory saving, especially in multi-image and video scenarios.
119 # model = Qwen2VLForConditionalGeneration.from_pretrained(
120 # "Qwen/Qwen2-VL-7B-Instruct",
121 # torch_dtype=torch.bfloat16,
122 # attn_implementation="flash_attention_2",
123 # device_map="auto",
124 # )
125
126 # default processer
127 processor = AutoProcessor.from_pretrained("Qwen/Qwen2-VL-7B-Instruct")
128
129 # 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.
130 # min_pixels = 256*28*28
131 # max_pixels = 1280*28*28
132 # processor = AutoProcessor.from_pretrained("Qwen/Qwen2-VL-7B-Instruct", min_pixels=min_pixels, max_pixels=max_pixels)
133
134 messages = [
135 {
136 "role": "user",
137 "content": [
138 {
139 "type": "image",
140 "image": "https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen-VL/assets/demo.jpeg",
141 },
142 {"type": "text", "text": "Describe this image."},
143 ],
144 }
145 ]
146
147 # Preparation for inference
148 text = processor.apply_chat_template(
149 messages, tokenize=False, add_generation_prompt=True
150 )
151 image_inputs, video_inputs = process_vision_info(messages)
152 inputs = processor(
153 text=[text],
154 images=image_inputs,
155 videos=video_inputs,
156 padding=True,
157 return_tensors="pt",
158 )
159 inputs = inputs.to("cuda")
160
161 # Inference: Generation of the output
162 generated_ids = model.generate(**inputs, max_new_tokens=128)
163 generated_ids_trimmed = [
164 out_ids[len(in_ids) :] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
165 ]
166 output_text = processor.batch_decode(
167 generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
168 )
169 print(output_text)
170 ```
171 <details>
172 <summary>Without qwen_vl_utils</summary>
173
174 ```python
175 from PIL import Image
176 import requests
177 import torch
178 from torchvision import io
179 from typing import Dict
180 from transformers import Qwen2VLForConditionalGeneration, AutoTokenizer, AutoProcessor
181
182 # Load the model in half-precision on the available device(s)
183 model = Qwen2VLForConditionalGeneration.from_pretrained(
184 "Qwen/Qwen2-VL-7B-Instruct", torch_dtype="auto", device_map="auto"
185 )
186 processor = AutoProcessor.from_pretrained("Qwen/Qwen2-VL-7B-Instruct")
187
188 # Image
189 url = "https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen-VL/assets/demo.jpeg"
190 image = Image.open(requests.get(url, stream=True).raw)
191
192 conversation = [
193 {
194 "role": "user",
195 "content": [
196 {
197 "type": "image",
198 },
199 {"type": "text", "text": "Describe this image."},
200 ],
201 }
202 ]
203
204
205 # Preprocess the inputs
206 text_prompt = processor.apply_chat_template(conversation, add_generation_prompt=True)
207 # 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'
208
209 inputs = processor(
210 text=[text_prompt], images=[image], padding=True, return_tensors="pt"
211 )
212 inputs = inputs.to("cuda")
213
214 # Inference: Generation of the output
215 output_ids = model.generate(**inputs, max_new_tokens=128)
216 generated_ids = [
217 output_ids[len(input_ids) :]
218 for input_ids, output_ids in zip(inputs.input_ids, output_ids)
219 ]
220 output_text = processor.batch_decode(
221 generated_ids, skip_special_tokens=True, clean_up_tokenization_spaces=True
222 )
223 print(output_text)
224 ```
225 </details>
226 <details>
227 <summary>Multi image inference</summary>
228
229 ```python
230 # Messages containing multiple images and a text query
231 messages = [
232 {
233 "role": "user",
234 "content": [
235 {"type": "image", "image": "file:///path/to/image1.jpg"},
236 {"type": "image", "image": "file:///path/to/image2.jpg"},
237 {"type": "text", "text": "Identify the similarities between these images."},
238 ],
239 }
240 ]
241
242 # Preparation for inference
243 text = processor.apply_chat_template(
244 messages, tokenize=False, add_generation_prompt=True
245 )
246 image_inputs, video_inputs = process_vision_info(messages)
247 inputs = processor(
248 text=[text],
249 images=image_inputs,
250 videos=video_inputs,
251 padding=True,
252 return_tensors="pt",
253 )
254 inputs = inputs.to("cuda")
255
256 # Inference
257 generated_ids = model.generate(**inputs, max_new_tokens=128)
258 generated_ids_trimmed = [
259 out_ids[len(in_ids) :] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
260 ]
261 output_text = processor.batch_decode(
262 generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
263 )
264 print(output_text)
265 ```
266 </details>
267
268 <details>
269 <summary>Video inference</summary>
270
271 ```python
272 # Messages containing a images list as a video and a text query
273 messages = [
274 {
275 "role": "user",
276 "content": [
277 {
278 "type": "video",
279 "video": [
280 "file:///path/to/frame1.jpg",
281 "file:///path/to/frame2.jpg",
282 "file:///path/to/frame3.jpg",
283 "file:///path/to/frame4.jpg",
284 ],
285 "fps": 1.0,
286 },
287 {"type": "text", "text": "Describe this video."},
288 ],
289 }
290 ]
291 # Messages containing a video and a text query
292 messages = [
293 {
294 "role": "user",
295 "content": [
296 {
297 "type": "video",
298 "video": "file:///path/to/video1.mp4",
299 "max_pixels": 360 * 420,
300 "fps": 1.0,
301 },
302 {"type": "text", "text": "Describe this video."},
303 ],
304 }
305 ]
306
307 # Preparation for inference
308 text = processor.apply_chat_template(
309 messages, tokenize=False, add_generation_prompt=True
310 )
311 image_inputs, video_inputs = process_vision_info(messages)
312 inputs = processor(
313 text=[text],
314 images=image_inputs,
315 videos=video_inputs,
316 padding=True,
317 return_tensors="pt",
318 )
319 inputs = inputs.to("cuda")
320
321 # Inference
322 generated_ids = model.generate(**inputs, max_new_tokens=128)
323 generated_ids_trimmed = [
324 out_ids[len(in_ids) :] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
325 ]
326 output_text = processor.batch_decode(
327 generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
328 )
329 print(output_text)
330 ```
331 </details>
332
333 <details>
334 <summary>Batch inference</summary>
335
336 ```python
337 # Sample messages for batch inference
338 messages1 = [
339 {
340 "role": "user",
341 "content": [
342 {"type": "image", "image": "file:///path/to/image1.jpg"},
343 {"type": "image", "image": "file:///path/to/image2.jpg"},
344 {"type": "text", "text": "What are the common elements in these pictures?"},
345 ],
346 }
347 ]
348 messages2 = [
349 {"role": "system", "content": "You are a helpful assistant."},
350 {"role": "user", "content": "Who are you?"},
351 ]
352 # Combine messages for batch processing
353 messages = [messages1, messages1]
354
355 # Preparation for batch inference
356 texts = [
357 processor.apply_chat_template(msg, tokenize=False, add_generation_prompt=True)
358 for msg in messages
359 ]
360 image_inputs, video_inputs = process_vision_info(messages)
361 inputs = processor(
362 text=texts,
363 images=image_inputs,
364 videos=video_inputs,
365 padding=True,
366 return_tensors="pt",
367 )
368 inputs = inputs.to("cuda")
369
370 # Batch Inference
371 generated_ids = model.generate(**inputs, max_new_tokens=128)
372 generated_ids_trimmed = [
373 out_ids[len(in_ids) :] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
374 ]
375 output_texts = processor.batch_decode(
376 generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
377 )
378 print(output_texts)
379 ```
380 </details>
381
382 ### More Usage Tips
383
384 For input images, we support local files, base64, and URLs. For videos, we currently only support local files.
385
386 ```python
387 # You can directly insert a local file path, a URL, or a base64-encoded image into the position where you want in the text.
388 ## Local file path
389 messages = [
390 {
391 "role": "user",
392 "content": [
393 {"type": "image", "image": "file:///path/to/your/image.jpg"},
394 {"type": "text", "text": "Describe this image."},
395 ],
396 }
397 ]
398 ## Image URL
399 messages = [
400 {
401 "role": "user",
402 "content": [
403 {"type": "image", "image": "http://path/to/your/image.jpg"},
404 {"type": "text", "text": "Describe this image."},
405 ],
406 }
407 ]
408 ## Base64 encoded image
409 messages = [
410 {
411 "role": "user",
412 "content": [
413 {"type": "image", "image": "data:image;base64,/9j/..."},
414 {"type": "text", "text": "Describe this image."},
415 ],
416 }
417 ]
418 ```
419 #### Image Resolution for performance boost
420
421 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.
422
423 ```python
424 min_pixels = 256 * 28 * 28
425 max_pixels = 1280 * 28 * 28
426 processor = AutoProcessor.from_pretrained(
427 "Qwen/Qwen2-VL-7B-Instruct", min_pixels=min_pixels, max_pixels=max_pixels
428 )
429 ```
430
431 Besides, We provide two methods for fine-grained control over the image size input to the model:
432
433 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.
434
435 2. Specify exact dimensions: Directly set `resized_height` and `resized_width`. These values will be rounded to the nearest multiple of 28.
436
437 ```python
438 # min_pixels and max_pixels
439 messages = [
440 {
441 "role": "user",
442 "content": [
443 {
444 "type": "image",
445 "image": "file:///path/to/your/image.jpg",
446 "resized_height": 280,
447 "resized_width": 420,
448 },
449 {"type": "text", "text": "Describe this image."},
450 ],
451 }
452 ]
453 # resized_height and resized_width
454 messages = [
455 {
456 "role": "user",
457 "content": [
458 {
459 "type": "image",
460 "image": "file:///path/to/your/image.jpg",
461 "min_pixels": 50176,
462 "max_pixels": 50176,
463 },
464 {"type": "text", "text": "Describe this image."},
465 ],
466 }
467 ]
468 ```
469
470 ## Limitations
471
472 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:
473
474 1. Lack of Audio Support: The current model does **not comprehend audio information** within videos.
475 2. Data timeliness: Our image dataset is **updated until June 2023**, and information subsequent to this date may not be covered.
476 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.
477 4. Limited Capacity for Complex Instruction: When faced with intricate multi-step instructions, the model's understanding and execution capabilities require enhancement.
478 5. Insufficient Counting Accuracy: Particularly in complex scenes, the accuracy of object counting is not high, necessitating further improvements.
479 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.
480
481 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.
482
483
484 ## Citation
485
486 If you find our work helpful, feel free to give us a cite.
487
488 ```
489 @article{Qwen2VL,
490 title={Qwen2-VL: Enhancing Vision-Language Model's Perception of the World at Any Resolution},
491 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},
492 journal={arXiv preprint arXiv:2409.12191},
493 year={2024}
494 }
495
496 @article{Qwen-VL,
497 title={Qwen-VL: A Versatile Vision-Language Model for Understanding, Localization, Text Reading, and Beyond},
498 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},
499 journal={arXiv preprint arXiv:2308.12966},
500 year={2023}
501 }
502 ```