README.md
17.8 KB · 526 lines · markdown Raw
1
2 ---
3 license_name: qwen-research
4 license_link: https://huggingface.co/Qwen/Qwen2.5-VL-3B-Instruct/blob/main/LICENSE
5 language:
6 - en
7 pipeline_tag: image-text-to-text
8 tags:
9 - multimodal
10 library_name: transformers
11 ---
12
13 # Qwen2.5-VL-3B-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 In the past five months since Qwen2-VL’s release, numerous developers have built new models on the Qwen2-VL vision-language models, providing us with valuable feedback. During this period, we focused on building more useful vision-language models. Today, we are excited to introduce the latest addition to the Qwen family: Qwen2.5-VL.
21
22 #### Key Enhancements:
23 * **Understand things visually**: Qwen2.5-VL is not only proficient in recognizing common objects such as flowers, birds, fish, and insects, but it is highly capable of analyzing texts, charts, icons, graphics, and layouts within images.
24
25 * **Being agentic**: Qwen2.5-VL directly plays as a visual agent that can reason and dynamically direct tools, which is capable of computer use and phone use.
26
27 * **Understanding long videos and capturing events**: Qwen2.5-VL can comprehend videos of over 1 hour, and this time it has a new ability of cpaturing event by pinpointing the relevant video segments.
28
29 * **Capable of visual localization in different formats**: Qwen2.5-VL can accurately localize objects in an image by generating bounding boxes or points, and it can provide stable JSON outputs for coordinates and attributes.
30
31 * **Generating structured outputs**: for data like scans of invoices, forms, tables, etc. Qwen2.5-VL supports structured outputs of their contents, benefiting usages in finance, commerce, etc.
32
33
34 #### Model Architecture Updates:
35
36 * **Dynamic Resolution and Frame Rate Training for Video Understanding**:
37
38 We extend dynamic resolution to the temporal dimension by adopting dynamic FPS sampling, enabling the model to comprehend videos at various sampling rates. Accordingly, we update mRoPE in the time dimension with IDs and absolute time alignment, enabling the model to learn temporal sequence and speed, and ultimately acquire the ability to pinpoint specific moments.
39
40 <p align="center">
41 <img src="https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen2.5-VL/qwen2.5vl_arc.jpeg" width="80%"/>
42 <p>
43
44
45 * **Streamlined and Efficient Vision Encoder**
46
47 We enhance both training and inference speeds by strategically implementing window attention into the ViT. The ViT architecture is further optimized with SwiGLU and RMSNorm, aligning it with the structure of the Qwen2.5 LLM.
48
49
50 We have three models with 3, 7 and 72 billion parameters. This repo contains the instruction-tuned 3B Qwen2.5-VL model. For more information, visit our [Blog](https://qwenlm.github.io/blog/qwen2.5-vl/) and [GitHub](https://github.com/QwenLM/Qwen2.5-VL).
51
52
53
54 ## Evaluation
55
56 ### Image benchmark
57
58 | Benchmark | InternVL2.5-4B |Qwen2-VL-7B |Qwen2.5-VL-3B |
59 | :--- | :---: | :---: | :---: |
60 | MMMU<sub>val</sub> | 52.3 | 54.1 | 53.1|
61 | MMMU-Pro<sub>val</sub> | **32.7** | 30.5 | 31.6|
62 | AI2D<sub>test</sub> | 81.4 | **83.0** | 81.5 |
63 | DocVQA<sub>test</sub> | 91.6 | 94.5 | **93.9** |
64 | InfoVQA<sub>test</sub> | 72.1 | 76.5 | **77.1** |
65 | TextVQA<sub>val</sub> | 76.8 | **84.3** | 79.3|
66 | MMBench-V1.1<sub>test</sub> | 79.3 | **80.7** | 77.6 |
67 | MMStar | 58.3 | **60.7** | 55.9 |
68 | MathVista<sub>testmini</sub> | 60.5 | 58.2 | **62.3** |
69 | MathVision<sub>full</sub> | 20.9 | 16.3 | **21.2** |
70
71
72 ### Video benchmark
73 | Benchmark | InternVL2.5-4B | Qwen2-VL-7B | Qwen2.5-VL-3B |
74 | :--- | :---: | :---: | :---: |
75 | MVBench | 71.6 | 67.0 | 67.0 |
76 | VideoMME | 63.6/62.3 | 69.0/63.3 | 67.6/61.5 |
77 | MLVU | 48.3 | - | 68.2 |
78 | LVBench | - | - | 43.3 |
79 | MMBench-Video | 1.73 | 1.44 | 1.63 |
80 | EgoSchema | - | - | 64.8 |
81 | PerceptionTest | - | - | 66.9 |
82 | TempCompass | - | - | 64.4 |
83 | LongVideoBench | 55.2 | 55.6 | 54.2 |
84 | CharadesSTA/mIoU | - | - | 38.8 |
85
86
87 ### Agent benchmark
88 | Benchmarks | Qwen2.5-VL-3B |
89 |-------------------------|---------------|
90 | ScreenSpot | 55.5 |
91 | ScreenSpot Pro | 23.9 |
92 | AITZ_EM | 76.9 |
93 | Android Control High_EM | 63.7 |
94 | Android Control Low_EM | 22.2 |
95 | AndroidWorld_SR | 90.8 |
96 | MobileMiniWob++_SR | 67.9 |
97
98 ## Requirements
99 The code of Qwen2.5-VL has been in the latest Hugging face transformers and we advise you to build from source with command:
100 ```
101 pip install git+https://github.com/huggingface/transformers accelerate
102 ```
103 or you might encounter the following error:
104 ```
105 KeyError: 'qwen2_5_vl'
106 ```
107
108
109 ## Quickstart
110
111 Below, we provide simple examples to show how to use Qwen2.5-VL with 🤖 ModelScope and 🤗 Transformers.
112
113 The code of Qwen2.5-VL has been in the latest Hugging face transformers and we advise you to build from source with command:
114 ```
115 pip install git+https://github.com/huggingface/transformers accelerate
116 ```
117 or you might encounter the following error:
118 ```
119 KeyError: 'qwen2_5_vl'
120 ```
121
122
123 We offer a toolkit to help you handle various types of visual input more conveniently, as if you were using an API. This includes base64, URLs, and interleaved images and videos. You can install it using the following command:
124
125 ```bash
126 # It's highly recommanded to use `[decord]` feature for faster video loading.
127 pip install qwen-vl-utils[decord]==0.0.8
128 ```
129
130 If you are not using Linux, you might not be able to install `decord` from PyPI. In that case, you can use `pip install qwen-vl-utils` which will fall back to using torchvision for video processing. However, you can still [install decord from source](https://github.com/dmlc/decord?tab=readme-ov-file#install-from-source) to get decord used when loading video.
131
132 ### Using 🤗 Transformers to Chat
133
134 Here we show a code snippet to show you how to use the chat model with `transformers` and `qwen_vl_utils`:
135
136 ```python
137 from transformers import Qwen2_5_VLForConditionalGeneration, AutoTokenizer, AutoProcessor
138 from qwen_vl_utils import process_vision_info
139
140 # default: Load the model on the available device(s)
141 model = Qwen2_5_VLForConditionalGeneration.from_pretrained(
142 "Qwen/Qwen2.5-VL-3B-Instruct", torch_dtype="auto", device_map="auto"
143 )
144
145 # We recommend enabling flash_attention_2 for better acceleration and memory saving, especially in multi-image and video scenarios.
146 # model = Qwen2_5_VLForConditionalGeneration.from_pretrained(
147 # "Qwen/Qwen2.5-VL-3B-Instruct",
148 # torch_dtype=torch.bfloat16,
149 # attn_implementation="flash_attention_2",
150 # device_map="auto",
151 # )
152
153 # default processer
154 processor = AutoProcessor.from_pretrained("Qwen/Qwen2.5-VL-3B-Instruct")
155
156 # The default range for the number of visual tokens per image in the model is 4-16384.
157 # You can set min_pixels and max_pixels according to your needs, such as a token range of 256-1280, to balance performance and cost.
158 # min_pixels = 256*28*28
159 # max_pixels = 1280*28*28
160 # processor = AutoProcessor.from_pretrained("Qwen/Qwen2.5-VL-3B-Instruct", min_pixels=min_pixels, max_pixels=max_pixels)
161
162 messages = [
163 {
164 "role": "user",
165 "content": [
166 {
167 "type": "image",
168 "image": "https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen-VL/assets/demo.jpeg",
169 },
170 {"type": "text", "text": "Describe this image."},
171 ],
172 }
173 ]
174
175 # Preparation for inference
176 text = processor.apply_chat_template(
177 messages, tokenize=False, add_generation_prompt=True
178 )
179 image_inputs, video_inputs = process_vision_info(messages)
180 inputs = processor(
181 text=[text],
182 images=image_inputs,
183 videos=video_inputs,
184 padding=True,
185 return_tensors="pt",
186 )
187 inputs = inputs.to("cuda")
188
189 # Inference: Generation of the output
190 generated_ids = model.generate(**inputs, max_new_tokens=128)
191 generated_ids_trimmed = [
192 out_ids[len(in_ids) :] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
193 ]
194 output_text = processor.batch_decode(
195 generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
196 )
197 print(output_text)
198 ```
199 <details>
200 <summary>Multi image inference</summary>
201
202 ```python
203 # Messages containing multiple images and a text query
204 messages = [
205 {
206 "role": "user",
207 "content": [
208 {"type": "image", "image": "file:///path/to/image1.jpg"},
209 {"type": "image", "image": "file:///path/to/image2.jpg"},
210 {"type": "text", "text": "Identify the similarities between these images."},
211 ],
212 }
213 ]
214
215 # Preparation for inference
216 text = processor.apply_chat_template(
217 messages, tokenize=False, add_generation_prompt=True
218 )
219 image_inputs, video_inputs = process_vision_info(messages)
220 inputs = processor(
221 text=[text],
222 images=image_inputs,
223 videos=video_inputs,
224 padding=True,
225 return_tensors="pt",
226 )
227 inputs = inputs.to("cuda")
228
229 # Inference
230 generated_ids = model.generate(**inputs, max_new_tokens=128)
231 generated_ids_trimmed = [
232 out_ids[len(in_ids) :] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
233 ]
234 output_text = processor.batch_decode(
235 generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
236 )
237 print(output_text)
238 ```
239 </details>
240
241 <details>
242 <summary>Video inference</summary>
243
244 ```python
245 # Messages containing a images list as a video and a text query
246 messages = [
247 {
248 "role": "user",
249 "content": [
250 {
251 "type": "video",
252 "video": [
253 "file:///path/to/frame1.jpg",
254 "file:///path/to/frame2.jpg",
255 "file:///path/to/frame3.jpg",
256 "file:///path/to/frame4.jpg",
257 ],
258 },
259 {"type": "text", "text": "Describe this video."},
260 ],
261 }
262 ]
263
264 # Messages containing a local video path and a text query
265 messages = [
266 {
267 "role": "user",
268 "content": [
269 {
270 "type": "video",
271 "video": "file:///path/to/video1.mp4",
272 "max_pixels": 360 * 420,
273 "fps": 1.0,
274 },
275 {"type": "text", "text": "Describe this video."},
276 ],
277 }
278 ]
279
280 # Messages containing a video url and a text query
281 messages = [
282 {
283 "role": "user",
284 "content": [
285 {
286 "type": "video",
287 "video": "https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen2-VL/space_woaudio.mp4",
288 },
289 {"type": "text", "text": "Describe this video."},
290 ],
291 }
292 ]
293
294 #In Qwen 2.5 VL, frame rate information is also input into the model to align with absolute time.
295 # Preparation for inference
296 text = processor.apply_chat_template(
297 messages, tokenize=False, add_generation_prompt=True
298 )
299 image_inputs, video_inputs, video_kwargs = process_vision_info(messages, return_video_kwargs=True)
300 inputs = processor(
301 text=[text],
302 images=image_inputs,
303 videos=video_inputs,
304 fps=fps,
305 padding=True,
306 return_tensors="pt",
307 **video_kwargs,
308 )
309 inputs = inputs.to("cuda")
310
311 # Inference
312 generated_ids = model.generate(**inputs, max_new_tokens=128)
313 generated_ids_trimmed = [
314 out_ids[len(in_ids) :] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
315 ]
316 output_text = processor.batch_decode(
317 generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
318 )
319 print(output_text)
320 ```
321
322 Video URL compatibility largely depends on the third-party library version. The details are in the table below. change the backend by `FORCE_QWENVL_VIDEO_READER=torchvision` or `FORCE_QWENVL_VIDEO_READER=decord` if you prefer not to use the default one.
323
324 | Backend | HTTP | HTTPS |
325 |-------------|------|-------|
326 | torchvision >= 0.19.0 | ✅ | ✅ |
327 | torchvision < 0.19.0 | ❌ | ❌ |
328 | decord | ✅ | ❌ |
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, messages2]
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 ### 🤖 ModelScope
381 We strongly advise users especially those in mainland China to use ModelScope. `snapshot_download` can help you solve issues concerning downloading checkpoints.
382
383
384 ### More Usage Tips
385
386 For input images, we support local files, base64, and URLs. For videos, we currently only support local files.
387
388 ```python
389 # You can directly insert a local file path, a URL, or a base64-encoded image into the position where you want in the text.
390 ## Local file path
391 messages = [
392 {
393 "role": "user",
394 "content": [
395 {"type": "image", "image": "file:///path/to/your/image.jpg"},
396 {"type": "text", "text": "Describe this image."},
397 ],
398 }
399 ]
400 ## Image URL
401 messages = [
402 {
403 "role": "user",
404 "content": [
405 {"type": "image", "image": "http://path/to/your/image.jpg"},
406 {"type": "text", "text": "Describe this image."},
407 ],
408 }
409 ]
410 ## Base64 encoded image
411 messages = [
412 {
413 "role": "user",
414 "content": [
415 {"type": "image", "image": "data:image;base64,/9j/..."},
416 {"type": "text", "text": "Describe this image."},
417 ],
418 }
419 ]
420 ```
421 #### Image Resolution for performance boost
422
423 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.
424
425 ```python
426 min_pixels = 256 * 28 * 28
427 max_pixels = 1280 * 28 * 28
428 processor = AutoProcessor.from_pretrained(
429 "Qwen/Qwen2.5-VL-3B-Instruct", min_pixels=min_pixels, max_pixels=max_pixels
430 )
431 ```
432
433 Besides, We provide two methods for fine-grained control over the image size input to the model:
434
435 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.
436
437 2. Specify exact dimensions: Directly set `resized_height` and `resized_width`. These values will be rounded to the nearest multiple of 28.
438
439 ```python
440 # min_pixels and max_pixels
441 messages = [
442 {
443 "role": "user",
444 "content": [
445 {
446 "type": "image",
447 "image": "file:///path/to/your/image.jpg",
448 "resized_height": 280,
449 "resized_width": 420,
450 },
451 {"type": "text", "text": "Describe this image."},
452 ],
453 }
454 ]
455 # resized_height and resized_width
456 messages = [
457 {
458 "role": "user",
459 "content": [
460 {
461 "type": "image",
462 "image": "file:///path/to/your/image.jpg",
463 "min_pixels": 50176,
464 "max_pixels": 50176,
465 },
466 {"type": "text", "text": "Describe this image."},
467 ],
468 }
469 ]
470 ```
471
472 ### Processing Long Texts
473
474 The current `config.json` is set for context length up to 32,768 tokens.
475 To handle extensive inputs exceeding 32,768 tokens, we utilize [YaRN](https://arxiv.org/abs/2309.00071), a technique for enhancing model length extrapolation, ensuring optimal performance on lengthy texts.
476
477 For supported frameworks, you could add the following to `config.json` to enable YaRN:
478
479 ```
480 {
481 ...,
482 "type": "yarn",
483 "mrope_section": [
484 16,
485 24,
486 24
487 ],
488 "factor": 4,
489 "original_max_position_embeddings": 32768
490 }
491 ```
492
493 However, it should be noted that this method has a significant impact on the performance of temporal and spatial localization tasks, and is therefore not recommended for use.
494
495 At the same time, for long video inputs, since MRoPE itself is more economical with ids, the max_position_embeddings can be directly modified to a larger value, such as 64k.
496
497
498
499 ## Citation
500
501 If you find our work helpful, feel free to give us a cite.
502
503 ```
504 @misc{qwen2.5-VL,
505 title = {Qwen2.5-VL},
506 url = {https://qwenlm.github.io/blog/qwen2.5-vl/},
507 author = {Qwen Team},
508 month = {January},
509 year = {2025}
510 }
511
512 @article{Qwen2VL,
513 title={Qwen2-VL: Enhancing Vision-Language Model's Perception of the World at Any Resolution},
514 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},
515 journal={arXiv preprint arXiv:2409.12191},
516 year={2024}
517 }
518
519 @article{Qwen-VL,
520 title={Qwen-VL: A Versatile Vision-Language Model for Understanding, Localization, Text Reading, and Beyond},
521 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},
522 journal={arXiv preprint arXiv:2308.12966},
523 year={2023}
524 }
525 ```
526