saishshinde15 commited on
Commit
7b01038
·
verified ·
1 Parent(s): 9128646

Update README.md

Browse files
Files changed (1) hide show
  1. README.md +410 -1
README.md CHANGED
@@ -18,4 +18,413 @@ language:
18
 
19
  This qwen2_vl model was trained 2x faster with [Unsloth](https://github.com/unslothai/unsloth) and Huggingface's TRL library.
20
 
21
- [<img src="https://raw.githubusercontent.com/unslothai/unsloth/main/images/unsloth%20made%20with%20love.png" width="200"/>](https://github.com/unslothai/unsloth)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18
 
19
  This qwen2_vl model was trained 2x faster with [Unsloth](https://github.com/unslothai/unsloth) and Huggingface's TRL library.
20
 
21
+ ## Requirements
22
+ 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:
23
+ ```
24
+ KeyError: 'qwen2_vl'
25
+ ```
26
+
27
+ ## Quickstart
28
+ 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:
29
+
30
+ ```bash
31
+ pip install qwen-vl-utils
32
+ ```
33
+
34
+ Here we show a code snippet to show you how to use the chat model with `transformers` and `qwen_vl_utils`:
35
+
36
+ ```python
37
+ from transformers import Qwen2VLForConditionalGeneration, AutoTokenizer, AutoProcessor
38
+ from qwen_vl_utils import process_vision_info
39
+
40
+ # default: Load the model on the available device(s)
41
+ model = Qwen2VLForConditionalGeneration.from_pretrained(
42
+ "Qwen/Qwen2-VL-2B-Instruct", torch_dtype="auto", device_map="auto"
43
+ )
44
+
45
+ # We recommend enabling flash_attention_2 for better acceleration and memory saving, especially in multi-image and video scenarios.
46
+ # model = Qwen2VLForConditionalGeneration.from_pretrained(
47
+ # "Qwen/Qwen2-VL-2B-Instruct",
48
+ # torch_dtype=torch.bfloat16,
49
+ # attn_implementation="flash_attention_2",
50
+ # device_map="auto",
51
+ # )
52
+
53
+ # default processer
54
+ processor = AutoProcessor.from_pretrained("Qwen/Qwen2-VL-2B-Instruct")
55
+
56
+ # 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.
57
+ # min_pixels = 256*28*28
58
+ # max_pixels = 1280*28*28
59
+ # processor = AutoProcessor.from_pretrained("Qwen/Qwen2-VL-2B-Instruct", min_pixels=min_pixels, max_pixels=max_pixels)
60
+
61
+ messages = [
62
+ {
63
+ "role": "user",
64
+ "content": [
65
+ {
66
+ "type": "image",
67
+ "image": "https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen-VL/assets/demo.jpeg",
68
+ },
69
+ {"type": "text", "text": "Describe this image."},
70
+ ],
71
+ }
72
+ ]
73
+
74
+ # Preparation for inference
75
+ text = processor.apply_chat_template(
76
+ messages, tokenize=False, add_generation_prompt=True
77
+ )
78
+ image_inputs, video_inputs = process_vision_info(messages)
79
+ inputs = processor(
80
+ text=[text],
81
+ images=image_inputs,
82
+ videos=video_inputs,
83
+ padding=True,
84
+ return_tensors="pt",
85
+ )
86
+ inputs = inputs.to("cuda")
87
+
88
+ # Inference: Generation of the output
89
+ generated_ids = model.generate(**inputs, max_new_tokens=128)
90
+ generated_ids_trimmed = [
91
+ out_ids[len(in_ids) :] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
92
+ ]
93
+ output_text = processor.batch_decode(
94
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
95
+ )
96
+ print(output_text)
97
+ ```
98
+ <details>
99
+ <summary>Without qwen_vl_utils</summary>
100
+
101
+ ```python
102
+ from PIL import Image
103
+ import requests
104
+ import torch
105
+ from torchvision import io
106
+ from typing import Dict
107
+ from transformers import Qwen2VLForConditionalGeneration, AutoTokenizer, AutoProcessor
108
+
109
+ # Load the model in half-precision on the available device(s)
110
+ model = Qwen2VLForConditionalGeneration.from_pretrained(
111
+ "Qwen/Qwen2-VL-2B-Instruct", torch_dtype="auto", device_map="auto"
112
+ )
113
+ processor = AutoProcessor.from_pretrained("Qwen/Qwen2-VL-2B-Instruct")
114
+
115
+ # Image
116
+ url = "https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen-VL/assets/demo.jpeg"
117
+ image = Image.open(requests.get(url, stream=True).raw)
118
+
119
+ conversation = [
120
+ {
121
+ "role": "user",
122
+ "content": [
123
+ {
124
+ "type": "image",
125
+ },
126
+ {"type": "text", "text": "Describe this image."},
127
+ ],
128
+ }
129
+ ]
130
+
131
+
132
+ # Preprocess the inputs
133
+ text_prompt = processor.apply_chat_template(conversation, add_generation_prompt=True)
134
+ # 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'
135
+
136
+ inputs = processor(
137
+ text=[text_prompt], images=[image], padding=True, return_tensors="pt"
138
+ )
139
+ inputs = inputs.to("cuda")
140
+
141
+ # Inference: Generation of the output
142
+ output_ids = model.generate(**inputs, max_new_tokens=128)
143
+ generated_ids = [
144
+ output_ids[len(input_ids) :]
145
+ for input_ids, output_ids in zip(inputs.input_ids, output_ids)
146
+ ]
147
+ output_text = processor.batch_decode(
148
+ generated_ids, skip_special_tokens=True, clean_up_tokenization_spaces=True
149
+ )
150
+ print(output_text)
151
+ ```
152
+ </details>
153
+
154
+ <details>
155
+ <summary>Multi image inference</summary>
156
+
157
+ ```python
158
+ # Messages containing multiple images and a text query
159
+ messages = [
160
+ {
161
+ "role": "user",
162
+ "content": [
163
+ {"type": "image", "image": "file:///path/to/image1.jpg"},
164
+ {"type": "image", "image": "file:///path/to/image2.jpg"},
165
+ {"type": "text", "text": "Identify the similarities between these images."},
166
+ ],
167
+ }
168
+ ]
169
+
170
+ # Preparation for inference
171
+ text = processor.apply_chat_template(
172
+ messages, tokenize=False, add_generation_prompt=True
173
+ )
174
+ image_inputs, video_inputs = process_vision_info(messages)
175
+ inputs = processor(
176
+ text=[text],
177
+ images=image_inputs,
178
+ videos=video_inputs,
179
+ padding=True,
180
+ return_tensors="pt",
181
+ )
182
+ inputs = inputs.to("cuda")
183
+
184
+ # Inference
185
+ generated_ids = model.generate(**inputs, max_new_tokens=128)
186
+ generated_ids_trimmed = [
187
+ out_ids[len(in_ids) :] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
188
+ ]
189
+ output_text = processor.batch_decode(
190
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
191
+ )
192
+ print(output_text)
193
+ ```
194
+ </details>
195
+
196
+ <details>
197
+ <summary>Video inference</summary>
198
+
199
+ ```python
200
+ # Messages containing a images list as a video and a text query
201
+ messages = [
202
+ {
203
+ "role": "user",
204
+ "content": [
205
+ {
206
+ "type": "video",
207
+ "video": [
208
+ "file:///path/to/frame1.jpg",
209
+ "file:///path/to/frame2.jpg",
210
+ "file:///path/to/frame3.jpg",
211
+ "file:///path/to/frame4.jpg",
212
+ ],
213
+ "fps": 1.0,
214
+ },
215
+ {"type": "text", "text": "Describe this video."},
216
+ ],
217
+ }
218
+ ]
219
+ # Messages containing a video and a text query
220
+ messages = [
221
+ {
222
+ "role": "user",
223
+ "content": [
224
+ {
225
+ "type": "video",
226
+ "video": "file:///path/to/video1.mp4",
227
+ "max_pixels": 360 * 420,
228
+ "fps": 1.0,
229
+ },
230
+ {"type": "text", "text": "Describe this video."},
231
+ ],
232
+ }
233
+ ]
234
+
235
+ # Preparation for inference
236
+ text = processor.apply_chat_template(
237
+ messages, tokenize=False, add_generation_prompt=True
238
+ )
239
+ image_inputs, video_inputs = process_vision_info(messages)
240
+ inputs = processor(
241
+ text=[text],
242
+ images=image_inputs,
243
+ videos=video_inputs,
244
+ padding=True,
245
+ return_tensors="pt",
246
+ )
247
+ inputs = inputs.to("cuda")
248
+
249
+ # Inference
250
+ generated_ids = model.generate(**inputs, max_new_tokens=128)
251
+ generated_ids_trimmed = [
252
+ out_ids[len(in_ids) :] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
253
+ ]
254
+ output_text = processor.batch_decode(
255
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
256
+ )
257
+ print(output_text)
258
+ ```
259
+ </details>
260
+
261
+ <details>
262
+ <summary>Batch inference</summary>
263
+
264
+ ```python
265
+ # Sample messages for batch inference
266
+ messages1 = [
267
+ {
268
+ "role": "user",
269
+ "content": [
270
+ {"type": "image", "image": "file:///path/to/image1.jpg"},
271
+ {"type": "image", "image": "file:///path/to/image2.jpg"},
272
+ {"type": "text", "text": "What are the common elements in these pictures?"},
273
+ ],
274
+ }
275
+ ]
276
+ messages2 = [
277
+ {"role": "system", "content": "You are a helpful assistant."},
278
+ {"role": "user", "content": "Who are you?"},
279
+ ]
280
+ # Combine messages for batch processing
281
+ messages = [messages1, messages1]
282
+
283
+ # Preparation for batch inference
284
+ texts = [
285
+ processor.apply_chat_template(msg, tokenize=False, add_generation_prompt=True)
286
+ for msg in messages
287
+ ]
288
+ image_inputs, video_inputs = process_vision_info(messages)
289
+ inputs = processor(
290
+ text=texts,
291
+ images=image_inputs,
292
+ videos=video_inputs,
293
+ padding=True,
294
+ return_tensors="pt",
295
+ )
296
+ inputs = inputs.to("cuda")
297
+
298
+ # Batch Inference
299
+ generated_ids = model.generate(**inputs, max_new_tokens=128)
300
+ generated_ids_trimmed = [
301
+ out_ids[len(in_ids) :] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
302
+ ]
303
+ output_texts = processor.batch_decode(
304
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
305
+ )
306
+ print(output_texts)
307
+ ```
308
+ </details>
309
+
310
+ ### More Usage Tips
311
+
312
+ For input images, we support local files, base64, and URLs. For videos, we currently only support local files.
313
+
314
+ ```python
315
+ # You can directly insert a local file path, a URL, or a base64-encoded image into the position where you want in the text.
316
+ ## Local file path
317
+ messages = [
318
+ {
319
+ "role": "user",
320
+ "content": [
321
+ {"type": "image", "image": "file:///path/to/your/image.jpg"},
322
+ {"type": "text", "text": "Describe this image."},
323
+ ],
324
+ }
325
+ ]
326
+ ## Image URL
327
+ messages = [
328
+ {
329
+ "role": "user",
330
+ "content": [
331
+ {"type": "image", "image": "http://path/to/your/image.jpg"},
332
+ {"type": "text", "text": "Describe this image."},
333
+ ],
334
+ }
335
+ ]
336
+ ## Base64 encoded image
337
+ messages = [
338
+ {
339
+ "role": "user",
340
+ "content": [
341
+ {"type": "image", "image": "data:image;base64,/9j/..."},
342
+ {"type": "text", "text": "Describe this image."},
343
+ ],
344
+ }
345
+ ]
346
+ ```
347
+ #### Image Resolution for performance boost
348
+
349
+ 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.
350
+
351
+ ```python
352
+ min_pixels = 256 * 28 * 28
353
+ max_pixels = 1280 * 28 * 28
354
+ processor = AutoProcessor.from_pretrained(
355
+ "Qwen/Qwen2-VL-2B-Instruct", min_pixels=min_pixels, max_pixels=max_pixels
356
+ )
357
+ ```
358
+
359
+ Besides, We provide two methods for fine-grained control over the image size input to the model:
360
+
361
+ 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.
362
+
363
+ 2. Specify exact dimensions: Directly set `resized_height` and `resized_width`. These values will be rounded to the nearest multiple of 28.
364
+
365
+ ```python
366
+ # min_pixels and max_pixels
367
+ messages = [
368
+ {
369
+ "role": "user",
370
+ "content": [
371
+ {
372
+ "type": "image",
373
+ "image": "file:///path/to/your/image.jpg",
374
+ "resized_height": 280,
375
+ "resized_width": 420,
376
+ },
377
+ {"type": "text", "text": "Describe this image."},
378
+ ],
379
+ }
380
+ ]
381
+ # resized_height and resized_width
382
+ messages = [
383
+ {
384
+ "role": "user",
385
+ "content": [
386
+ {
387
+ "type": "image",
388
+ "image": "file:///path/to/your/image.jpg",
389
+ "min_pixels": 50176,
390
+ "max_pixels": 50176,
391
+ },
392
+ {"type": "text", "text": "Describe this image."},
393
+ ],
394
+ }
395
+ ]
396
+ ```
397
+
398
+ ## Limitations
399
+
400
+ 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:
401
+
402
+ 1. Lack of Audio Support: The current model does **not comprehend audio information** within videos.
403
+ 2. Data timeliness: Our image dataset is **updated until June 2023**, and information subsequent to this date may not be covered.
404
+ 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.
405
+ 4. Limited Capacity for Complex Instruction: When faced with intricate multi-step instructions, the model's understanding and execution capabilities require enhancement.
406
+ 5. Insufficient Counting Accuracy: Particularly in complex scenes, the accuracy of object counting is not high, necessitating further improvements.
407
+ 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.
408
+
409
+ 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.
410
+
411
+
412
+ ## Citation
413
+
414
+ If you find our work helpful, feel free to give us a cite.
415
+
416
+ ```
417
+ @article{Qwen2VL,
418
+ title={Qwen2-VL: Enhancing Vision-Language Model's Perception of the World at Any Resolution},
419
+ 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},
420
+ journal={arXiv preprint arXiv:2409.12191},
421
+ year={2024}
422
+ }
423
+
424
+ @article{Qwen-VL,
425
+ title={Qwen-VL: A Versatile Vision-Language Model for Understanding, Localization, Text Reading, and Beyond},
426
+ 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},
427
+ journal={arXiv preprint arXiv:2308.12966},
428
+ year={2023}
429
+ }
430
+ ```