shimmyshimmer commited on
Commit
9fceaaa
1 Parent(s): 352bf43

Update README.md

Browse files
Files changed (1) hide show
  1. README.md +499 -165
README.md CHANGED
@@ -1,199 +1,533 @@
1
  ---
 
 
 
2
  library_name: transformers
3
- tags: []
 
 
 
 
 
 
 
 
4
  ---
5
 
6
- # Model Card for Model ID
7
 
8
- <!-- Provide a quick summary of what the model is/does. -->
9
 
 
10
 
 
 
11
 
12
- ## Model Details
13
 
14
- ### Model Description
 
15
 
16
- <!-- Provide a longer summary of what this model is. -->
17
 
18
- This is the model card of a 🤗 transformers model that has been pushed on the Hub. This model card has been automatically generated.
19
 
20
- - **Developed by:** [More Information Needed]
21
- - **Funded by [optional]:** [More Information Needed]
22
- - **Shared by [optional]:** [More Information Needed]
23
- - **Model type:** [More Information Needed]
24
- - **Language(s) (NLP):** [More Information Needed]
25
- - **License:** [More Information Needed]
26
- - **Finetuned from model [optional]:** [More Information Needed]
 
 
 
 
27
 
28
- ### Model Sources [optional]
29
 
30
- <!-- Provide the basic links for the model. -->
 
 
31
 
32
- - **Repository:** [More Information Needed]
33
- - **Paper [optional]:** [More Information Needed]
34
- - **Demo [optional]:** [More Information Needed]
35
 
36
- ## Uses
37
 
38
- <!-- Address questions around how the model is intended to be used, including the foreseeable users of the model and those affected by the model. -->
39
 
40
- ### Direct Use
41
 
42
- <!-- This section is for the model use without fine-tuning or plugging into a larger ecosystem/app. -->
43
 
44
- [More Information Needed]
45
 
46
- ### Downstream Use [optional]
47
 
48
- <!-- This section is for the model use when fine-tuned for a task, or when plugged into a larger ecosystem/app -->
49
 
50
- [More Information Needed]
51
 
52
- ### Out-of-Scope Use
53
 
54
- <!-- This section addresses misuse, malicious use, and uses that the model will not work well for. -->
55
 
56
- [More Information Needed]
 
 
57
 
58
- ## Bias, Risks, and Limitations
59
 
60
- <!-- This section is meant to convey both technical and sociotechnical limitations. -->
 
 
61
 
62
- [More Information Needed]
63
 
64
- ### Recommendations
65
 
66
- <!-- This section is meant to convey recommendations with respect to the bias, risk, and technical limitations. -->
67
-
68
- Users (both direct and downstream) should be made aware of the risks, biases and limitations of the model. More information needed for further recommendations.
69
-
70
- ## How to Get Started with the Model
71
-
72
- Use the code below to get started with the model.
73
-
74
- [More Information Needed]
75
-
76
- ## Training Details
77
-
78
- ### Training Data
79
-
80
- <!-- This should link to a Dataset Card, perhaps with a short stub of information on what the training data is all about as well as documentation related to data pre-processing or additional filtering. -->
81
-
82
- [More Information Needed]
83
-
84
- ### Training Procedure
85
-
86
- <!-- This relates heavily to the Technical Specifications. Content here should link to that section when it is relevant to the training procedure. -->
87
-
88
- #### Preprocessing [optional]
89
-
90
- [More Information Needed]
91
-
92
-
93
- #### Training Hyperparameters
94
-
95
- - **Training regime:** [More Information Needed] <!--fp32, fp16 mixed precision, bf16 mixed precision, bf16 non-mixed precision, fp16 non-mixed precision, fp8 mixed precision -->
96
-
97
- #### Speeds, Sizes, Times [optional]
98
-
99
- <!-- This section provides information about throughput, start/end time, checkpoint size if relevant, etc. -->
100
-
101
- [More Information Needed]
102
 
103
  ## Evaluation
104
 
105
- <!-- This section describes the evaluation protocols and provides the results. -->
106
-
107
- ### Testing Data, Factors & Metrics
108
-
109
- #### Testing Data
110
-
111
- <!-- This should link to a Dataset Card if possible. -->
112
-
113
- [More Information Needed]
114
-
115
- #### Factors
116
-
117
- <!-- These are the things the evaluation is disaggregating by, e.g., subpopulations or domains. -->
118
-
119
- [More Information Needed]
120
-
121
- #### Metrics
122
-
123
- <!-- These are the evaluation metrics being used, ideally with a description of why. -->
124
-
125
- [More Information Needed]
126
-
127
- ### Results
128
-
129
- [More Information Needed]
130
-
131
- #### Summary
132
-
133
-
134
-
135
- ## Model Examination [optional]
136
-
137
- <!-- Relevant interpretability work for the model goes here -->
138
-
139
- [More Information Needed]
140
-
141
- ## Environmental Impact
142
-
143
- <!-- Total emissions (in grams of CO2eq) and additional considerations, such as electricity usage, go here. Edit the suggested text below accordingly -->
144
-
145
- Carbon emissions can be estimated using the [Machine Learning Impact calculator](https://mlco2.github.io/impact#compute) presented in [Lacoste et al. (2019)](https://arxiv.org/abs/1910.09700).
146
-
147
- - **Hardware Type:** [More Information Needed]
148
- - **Hours used:** [More Information Needed]
149
- - **Cloud Provider:** [More Information Needed]
150
- - **Compute Region:** [More Information Needed]
151
- - **Carbon Emitted:** [More Information Needed]
152
-
153
- ## Technical Specifications [optional]
154
-
155
- ### Model Architecture and Objective
156
-
157
- [More Information Needed]
158
-
159
- ### Compute Infrastructure
160
-
161
- [More Information Needed]
162
-
163
- #### Hardware
164
-
165
- [More Information Needed]
166
-
167
- #### Software
168
-
169
- [More Information Needed]
170
-
171
- ## Citation [optional]
172
-
173
- <!-- If there is a paper or blog post introducing the model, the APA and Bibtex information for that should go in this section. -->
174
-
175
- **BibTeX:**
176
-
177
- [More Information Needed]
178
-
179
- **APA:**
180
-
181
- [More Information Needed]
182
-
183
- ## Glossary [optional]
184
-
185
- <!-- If relevant, include terms and calculations in this section that can help readers understand the model or model card. -->
186
-
187
- [More Information Needed]
188
-
189
- ## More Information [optional]
190
-
191
- [More Information Needed]
192
-
193
- ## Model Card Authors [optional]
194
-
195
- [More Information Needed]
196
-
197
- ## Model Card Contact
198
-
199
- [More Information Needed]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ base_model: Qwen/Qwen2-VL-2B-Instruct
3
+ language:
4
+ - en
5
  library_name: transformers
6
+ pipeline_tag: image-text-to-text
7
+ license: apache-2.0
8
+ tags:
9
+ - multimodal
10
+ - qwen
11
+ - qwen2
12
+ - unsloth
13
+ - transformers
14
+ - vision
15
  ---
16
 
17
+ # Finetune Llama 3.2, Qwen 2.5, Gemma 2, Mistral 2-5x faster with 70% less memory via Unsloth!
18
 
19
+ We have a free Google Colab Tesla T4 notebook for Qwen2-VL (7B) here: https://colab.research.google.com/drive/1whHb54GNZMrNxIsi2wm2EY_-Pvo2QyKh?usp=sharing
20
 
21
+ And a free notebook for [Llama 3.2 Vision (11B) here](https://colab.research.google.com/drive/1j0N4XTY1zXXy7mPAhOC1_gMYZ2F2EBlk?usp=sharing)
22
 
23
+ [<img src="https://raw.githubusercontent.com/unslothai/unsloth/main/images/Discord%20button.png" width="200"/>](https://discord.gg/unsloth)
24
+ [<img src="https://raw.githubusercontent.com/unslothai/unsloth/main/images/unsloth%20made%20with%20love.png" width="200"/>](https://github.com/unslothai/unsloth)
25
 
 
26
 
27
+ # unsloth/Qwen2-VL-2B-Instruct-bnb-4bit
28
+ For more details on the model, please go to Qwen's original [model card](https://huggingface.co/Qwen/Qwen2-VL-2B-Instruct)
29
 
30
+ ## Finetune for Free
31
 
32
+ All notebooks are **beginner friendly**! Add your dataset, click "Run All", and you'll get a 2x faster finetuned model which can be exported to GGUF, vLLM or uploaded to Hugging Face.
33
 
34
+ | Unsloth supports | Free Notebooks | Performance | Memory use |
35
+ |-----------------|--------------------------------------------------------------------------------------------------------------------------|-------------|----------|
36
+ | **Llama-3.2 (3B)** | [▶️ Start on Colab](https://colab.research.google.com/drive/1Ys44kVvmeZtnICzWz0xgpRnrIOjZAuxp?usp=sharing) | 2.4x faster | 58% less |
37
+ | **Llama-3.2 (11B vision)** | [▶️ Start on Colab](https://colab.research.google.com/drive/1j0N4XTY1zXXy7mPAhOC1_gMYZ2F2EBlk?usp=sharing) | 2x faster | 40% less |
38
+ | **Qwen2 VL (7B)** | [▶️ Start on Colab](https://colab.research.google.com/drive/1whHb54GNZMrNxIsi2wm2EY_-Pvo2QyKh?usp=sharing) | 1.8x faster | 40% less |
39
+ | **Qwen2.5 (7B)** | [▶️ Start on Colab](https://colab.research.google.com/drive/1Kose-ucXO1IBaZq5BvbwWieuubP7hxvQ?usp=sharing) | 2x faster | 60% less |
40
+ | **Llama-3.1 (8B)** | [▶️ Start on Colab](https://colab.research.google.com/drive/1Ys44kVvmeZtnICzWz0xgpRnrIOjZAuxp?usp=sharing) | 2.4x faster | 58% less |
41
+ | **Phi-3.5 (mini)** | [▶️ Start on Colab](https://colab.research.google.com/drive/1lN6hPQveB_mHSnTOYifygFcrO8C1bxq4?usp=sharing) | 2x faster | 50% less |
42
+ | **Gemma 2 (9B)** | [▶️ Start on Colab](https://colab.research.google.com/drive/1vIrqH5uYDQwsJ4-OO3DErvuv4pBgVwk4?usp=sharing) | 2.4x faster | 58% less |
43
+ | **Mistral (7B)** | [▶️ Start on Colab](https://colab.research.google.com/drive/1Dyauq4kTZoLewQ1cApceUQVNcnnNTzg_?usp=sharing) | 2.2x faster | 62% less |
44
+ | **DPO - Zephyr** | [▶️ Start on Colab](https://colab.research.google.com/drive/15vttTpzzVXv_tJwEk-hIcQ0S9FcEWvwP?usp=sharing) | 1.9x faster | 19% less |
45
 
46
+ [<img src="https://raw.githubusercontent.com/unslothai/unsloth/refs/heads/main/images/documentation%20green%20button.png" width="200"/>](https://docs.unsloth.ai)
47
 
48
+ - This [conversational notebook](https://colab.research.google.com/drive/1Aau3lgPzeZKQ-98h69CCu1UJcvIBLmy2?usp=sharing) is useful for ShareGPT ChatML / Vicuna templates.
49
+ - This [text completion notebook](https://colab.research.google.com/drive/1ef-tab5bhkvWmBOObepl1WgJvfvSzn5Q?usp=sharing) is for raw text. This [DPO notebook](https://colab.research.google.com/drive/15vttTpzzVXv_tJwEk-hIcQ0S9FcEWvwP?usp=sharing) replicates Zephyr.
50
+ - \* Kaggle has 2x T4s, but we use 1. Due to overhead, 1x T4 is 5x faster.
51
 
52
+ ## Special Thanks
53
+ A huge thank you to the Qwen team for creating and releasing these models.
 
54
 
55
+ ### What’s New in Qwen2-VL?
56
 
57
+ #### Key Enhancements:
58
 
 
59
 
60
+ * **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.
61
 
62
+ * **Understanding videos of 20min+**: Qwen2-VL can understand videos over 20 minutes for high-quality video-based question answering, dialog, content creation, etc.
63
 
64
+ * **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.
65
 
66
+ * **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.
67
 
 
68
 
69
+ #### Model Architecture Updates:
70
 
71
+ * **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.
72
 
73
+ <p align="center">
74
+ <img src="https://qianwen-res.oss-accelerate-overseas.aliyuncs.com/Qwen2-VL/qwen2_vl.jpg" width="80%"/>
75
+ <p>
76
 
77
+ * **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.
78
 
79
+ <p align="center">
80
+ <img src="http://qianwen-res.oss-accelerate-overseas.aliyuncs.com/Qwen2-VL/mrope.png" width="80%"/>
81
+ <p>
82
 
83
+ 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).
84
 
 
85
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86
 
87
  ## Evaluation
88
 
89
+ ### Image Benchmarks
90
+
91
+ | Benchmark | InternVL2-2B | MiniCPM-V 2.0 | **Qwen2-VL-2B** |
92
+ | :--- | :---: | :---: | :---: |
93
+ | MMMU<sub>val</sub> | 36.3 | 38.2 | **41.1** |
94
+ | DocVQA<sub>test</sub> | 86.9 | - | **90.1** |
95
+ | InfoVQA<sub>test</sub> | 58.9 | - | **65.5** |
96
+ | ChartQA<sub>test</sub> | **76.2** | - | 73.5 |
97
+ | TextVQA<sub>val</sub> | 73.4 | - | **79.7** |
98
+ | OCRBench | 781 | 605 | **794** |
99
+ | MTVQA | - | - | **20.0** |
100
+ | VCR<sub>en easy</sub> | - | - | **81.45**
101
+ | VCR<sub>zh easy</sub> | - | - | **46.16**
102
+ | RealWorldQA | 57.3 | 55.8 | **62.9** |
103
+ | MME<sub>sum</sub> | **1876.8** | 1808.6 | 1872.0 |
104
+ | MMBench-EN<sub>test</sub> | 73.2 | 69.1 | **74.9** |
105
+ | MMBench-CN<sub>test</sub> | 70.9 | 66.5 | **73.5** |
106
+ | MMBench-V1.1<sub>test</sub> | 69.6 | 65.8 | **72.2** |
107
+ | MMT-Bench<sub>test</sub> | - | - | **54.5** |
108
+ | MMStar | **49.8** | 39.1 | 48.0 |
109
+ | MMVet<sub>GPT-4-Turbo</sub> | 39.7 | 41.0 | **49.5** |
110
+ | HallBench<sub>avg</sub> | 38.0 | 36.1 | **41.7** |
111
+ | MathVista<sub>testmini</sub> | **46.0** | 39.8 | 43.0 |
112
+ | MathVision | - | - | **12.4** |
113
+
114
+ ### Video Benchmarks
115
+
116
+ | Benchmark | **Qwen2-VL-2B** |
117
+ | :--- | :---: |
118
+ | MVBench | **63.2** |
119
+ | PerceptionTest<sub>test</sub> | **53.9** |
120
+ | EgoSchema<sub>test</sub> | **54.9** |
121
+ | Video-MME<sub>wo/w subs</sub> | **55.6**/**60.4** |
122
+
123
+
124
+ ## Requirements
125
+ 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:
126
+ ```
127
+ KeyError: 'qwen2_vl'
128
+ ```
129
+
130
+ ## Quickstart
131
+ 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:
132
+
133
+ ```bash
134
+ pip install qwen-vl-utils
135
+ ```
136
+
137
+ Here we show a code snippet to show you how to use the chat model with `transformers` and `qwen_vl_utils`:
138
+
139
+ ```python
140
+ from transformers import Qwen2VLForConditionalGeneration, AutoTokenizer, AutoProcessor
141
+ from qwen_vl_utils import process_vision_info
142
+
143
+ # default: Load the model on the available device(s)
144
+ model = Qwen2VLForConditionalGeneration.from_pretrained(
145
+ "Qwen/Qwen2-VL-2B-Instruct", torch_dtype="auto", device_map="auto"
146
+ )
147
+
148
+ # We recommend enabling flash_attention_2 for better acceleration and memory saving, especially in multi-image and video scenarios.
149
+ # model = Qwen2VLForConditionalGeneration.from_pretrained(
150
+ # "Qwen/Qwen2-VL-2B-Instruct",
151
+ # torch_dtype=torch.bfloat16,
152
+ # attn_implementation="flash_attention_2",
153
+ # device_map="auto",
154
+ # )
155
+
156
+ # default processer
157
+ processor = AutoProcessor.from_pretrained("Qwen/Qwen2-VL-2B-Instruct")
158
+
159
+ # 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.
160
+ # min_pixels = 256*28*28
161
+ # max_pixels = 1280*28*28
162
+ # processor = AutoProcessor.from_pretrained("Qwen/Qwen2-VL-2B-Instruct", min_pixels=min_pixels, max_pixels=max_pixels)
163
+
164
+ messages = [
165
+ {
166
+ "role": "user",
167
+ "content": [
168
+ {
169
+ "type": "image",
170
+ "image": "https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen-VL/assets/demo.jpeg",
171
+ },
172
+ {"type": "text", "text": "Describe this image."},
173
+ ],
174
+ }
175
+ ]
176
+
177
+ # Preparation for inference
178
+ text = processor.apply_chat_template(
179
+ messages, tokenize=False, add_generation_prompt=True
180
+ )
181
+ image_inputs, video_inputs = process_vision_info(messages)
182
+ inputs = processor(
183
+ text=[text],
184
+ images=image_inputs,
185
+ videos=video_inputs,
186
+ padding=True,
187
+ return_tensors="pt",
188
+ )
189
+ inputs = inputs.to("cuda")
190
+
191
+ # Inference: Generation of the output
192
+ generated_ids = model.generate(**inputs, max_new_tokens=128)
193
+ generated_ids_trimmed = [
194
+ out_ids[len(in_ids) :] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
195
+ ]
196
+ output_text = processor.batch_decode(
197
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
198
+ )
199
+ print(output_text)
200
+ ```
201
+ <details>
202
+ <summary>Without qwen_vl_utils</summary>
203
+
204
+ ```python
205
+ from PIL import Image
206
+ import requests
207
+ import torch
208
+ from torchvision import io
209
+ from typing import Dict
210
+ from transformers import Qwen2VLForConditionalGeneration, AutoTokenizer, AutoProcessor
211
+
212
+ # Load the model in half-precision on the available device(s)
213
+ model = Qwen2VLForConditionalGeneration.from_pretrained(
214
+ "Qwen/Qwen2-VL-2B-Instruct", torch_dtype="auto", device_map="auto"
215
+ )
216
+ processor = AutoProcessor.from_pretrained("Qwen/Qwen2-VL-2B-Instruct")
217
+
218
+ # Image
219
+ url = "https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen-VL/assets/demo.jpeg"
220
+ image = Image.open(requests.get(url, stream=True).raw)
221
+
222
+ conversation = [
223
+ {
224
+ "role": "user",
225
+ "content": [
226
+ {
227
+ "type": "image",
228
+ },
229
+ {"type": "text", "text": "Describe this image."},
230
+ ],
231
+ }
232
+ ]
233
+
234
+
235
+ # Preprocess the inputs
236
+ text_prompt = processor.apply_chat_template(conversation, add_generation_prompt=True)
237
+ # 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'
238
+
239
+ inputs = processor(
240
+ text=[text_prompt], images=[image], padding=True, return_tensors="pt"
241
+ )
242
+ inputs = inputs.to("cuda")
243
+
244
+ # Inference: Generation of the output
245
+ output_ids = model.generate(**inputs, max_new_tokens=128)
246
+ generated_ids = [
247
+ output_ids[len(input_ids) :]
248
+ for input_ids, output_ids in zip(inputs.input_ids, output_ids)
249
+ ]
250
+ output_text = processor.batch_decode(
251
+ generated_ids, skip_special_tokens=True, clean_up_tokenization_spaces=True
252
+ )
253
+ print(output_text)
254
+ ```
255
+ </details>
256
+
257
+ <details>
258
+ <summary>Multi image inference</summary>
259
+
260
+ ```python
261
+ # Messages containing multiple images and a text query
262
+ messages = [
263
+ {
264
+ "role": "user",
265
+ "content": [
266
+ {"type": "image", "image": "file:///path/to/image1.jpg"},
267
+ {"type": "image", "image": "file:///path/to/image2.jpg"},
268
+ {"type": "text", "text": "Identify the similarities between these images."},
269
+ ],
270
+ }
271
+ ]
272
+
273
+ # Preparation for inference
274
+ text = processor.apply_chat_template(
275
+ messages, tokenize=False, add_generation_prompt=True
276
+ )
277
+ image_inputs, video_inputs = process_vision_info(messages)
278
+ inputs = processor(
279
+ text=[text],
280
+ images=image_inputs,
281
+ videos=video_inputs,
282
+ padding=True,
283
+ return_tensors="pt",
284
+ )
285
+ inputs = inputs.to("cuda")
286
+
287
+ # Inference
288
+ generated_ids = model.generate(**inputs, max_new_tokens=128)
289
+ generated_ids_trimmed = [
290
+ out_ids[len(in_ids) :] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
291
+ ]
292
+ output_text = processor.batch_decode(
293
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
294
+ )
295
+ print(output_text)
296
+ ```
297
+ </details>
298
+
299
+ <details>
300
+ <summary>Video inference</summary>
301
+
302
+ ```python
303
+ # Messages containing a images list as a video and a text query
304
+ messages = [
305
+ {
306
+ "role": "user",
307
+ "content": [
308
+ {
309
+ "type": "video",
310
+ "video": [
311
+ "file:///path/to/frame1.jpg",
312
+ "file:///path/to/frame2.jpg",
313
+ "file:///path/to/frame3.jpg",
314
+ "file:///path/to/frame4.jpg",
315
+ ],
316
+ "fps": 1.0,
317
+ },
318
+ {"type": "text", "text": "Describe this video."},
319
+ ],
320
+ }
321
+ ]
322
+ # Messages containing a video and a text query
323
+ messages = [
324
+ {
325
+ "role": "user",
326
+ "content": [
327
+ {
328
+ "type": "video",
329
+ "video": "file:///path/to/video1.mp4",
330
+ "max_pixels": 360 * 420,
331
+ "fps": 1.0,
332
+ },
333
+ {"type": "text", "text": "Describe this video."},
334
+ ],
335
+ }
336
+ ]
337
+
338
+ # Preparation for inference
339
+ text = processor.apply_chat_template(
340
+ messages, tokenize=False, add_generation_prompt=True
341
+ )
342
+ image_inputs, video_inputs = process_vision_info(messages)
343
+ inputs = processor(
344
+ text=[text],
345
+ images=image_inputs,
346
+ videos=video_inputs,
347
+ padding=True,
348
+ return_tensors="pt",
349
+ )
350
+ inputs = inputs.to("cuda")
351
+
352
+ # Inference
353
+ generated_ids = model.generate(**inputs, max_new_tokens=128)
354
+ generated_ids_trimmed = [
355
+ out_ids[len(in_ids) :] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
356
+ ]
357
+ output_text = processor.batch_decode(
358
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
359
+ )
360
+ print(output_text)
361
+ ```
362
+ </details>
363
+
364
+ <details>
365
+ <summary>Batch inference</summary>
366
+
367
+ ```python
368
+ # Sample messages for batch inference
369
+ messages1 = [
370
+ {
371
+ "role": "user",
372
+ "content": [
373
+ {"type": "image", "image": "file:///path/to/image1.jpg"},
374
+ {"type": "image", "image": "file:///path/to/image2.jpg"},
375
+ {"type": "text", "text": "What are the common elements in these pictures?"},
376
+ ],
377
+ }
378
+ ]
379
+ messages2 = [
380
+ {"role": "system", "content": "You are a helpful assistant."},
381
+ {"role": "user", "content": "Who are you?"},
382
+ ]
383
+ # Combine messages for batch processing
384
+ messages = [messages1, messages1]
385
+
386
+ # Preparation for batch inference
387
+ texts = [
388
+ processor.apply_chat_template(msg, tokenize=False, add_generation_prompt=True)
389
+ for msg in messages
390
+ ]
391
+ image_inputs, video_inputs = process_vision_info(messages)
392
+ inputs = processor(
393
+ text=texts,
394
+ images=image_inputs,
395
+ videos=video_inputs,
396
+ padding=True,
397
+ return_tensors="pt",
398
+ )
399
+ inputs = inputs.to("cuda")
400
+
401
+ # Batch Inference
402
+ generated_ids = model.generate(**inputs, max_new_tokens=128)
403
+ generated_ids_trimmed = [
404
+ out_ids[len(in_ids) :] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
405
+ ]
406
+ output_texts = processor.batch_decode(
407
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
408
+ )
409
+ print(output_texts)
410
+ ```
411
+ </details>
412
+
413
+ ### More Usage Tips
414
+
415
+ For input images, we support local files, base64, and URLs. For videos, we currently only support local files.
416
+
417
+ ```python
418
+ # You can directly insert a local file path, a URL, or a base64-encoded image into the position where you want in the text.
419
+ ## Local file path
420
+ messages = [
421
+ {
422
+ "role": "user",
423
+ "content": [
424
+ {"type": "image", "image": "file:///path/to/your/image.jpg"},
425
+ {"type": "text", "text": "Describe this image."},
426
+ ],
427
+ }
428
+ ]
429
+ ## Image URL
430
+ messages = [
431
+ {
432
+ "role": "user",
433
+ "content": [
434
+ {"type": "image", "image": "http://path/to/your/image.jpg"},
435
+ {"type": "text", "text": "Describe this image."},
436
+ ],
437
+ }
438
+ ]
439
+ ## Base64 encoded image
440
+ messages = [
441
+ {
442
+ "role": "user",
443
+ "content": [
444
+ {"type": "image", "image": "data:image;base64,/9j/..."},
445
+ {"type": "text", "text": "Describe this image."},
446
+ ],
447
+ }
448
+ ]
449
+ ```
450
+ #### Image Resolution for performance boost
451
+
452
+ 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.
453
+
454
+ ```python
455
+ min_pixels = 256 * 28 * 28
456
+ max_pixels = 1280 * 28 * 28
457
+ processor = AutoProcessor.from_pretrained(
458
+ "Qwen/Qwen2-VL-2B-Instruct", min_pixels=min_pixels, max_pixels=max_pixels
459
+ )
460
+ ```
461
+
462
+ Besides, We provide two methods for fine-grained control over the image size input to the model:
463
+
464
+ 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.
465
+
466
+ 2. Specify exact dimensions: Directly set `resized_height` and `resized_width`. These values will be rounded to the nearest multiple of 28.
467
+
468
+ ```python
469
+ # min_pixels and max_pixels
470
+ messages = [
471
+ {
472
+ "role": "user",
473
+ "content": [
474
+ {
475
+ "type": "image",
476
+ "image": "file:///path/to/your/image.jpg",
477
+ "resized_height": 280,
478
+ "resized_width": 420,
479
+ },
480
+ {"type": "text", "text": "Describe this image."},
481
+ ],
482
+ }
483
+ ]
484
+ # resized_height and resized_width
485
+ messages = [
486
+ {
487
+ "role": "user",
488
+ "content": [
489
+ {
490
+ "type": "image",
491
+ "image": "file:///path/to/your/image.jpg",
492
+ "min_pixels": 50176,
493
+ "max_pixels": 50176,
494
+ },
495
+ {"type": "text", "text": "Describe this image."},
496
+ ],
497
+ }
498
+ ]
499
+ ```
500
+
501
+ ## Limitations
502
+
503
+ 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:
504
+
505
+ 1. Lack of Audio Support: The current model does **not comprehend audio information** within videos.
506
+ 2. Data timeliness: Our image dataset is **updated until June 2023**, and information subsequent to this date may not be covered.
507
+ 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.
508
+ 4. Limited Capacity for Complex Instruction: When faced with intricate multi-step instructions, the model's understanding and execution capabilities require enhancement.
509
+ 5. Insufficient Counting Accuracy: Particularly in complex scenes, the accuracy of object counting is not high, necessitating further improvements.
510
+ 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.
511
+
512
+ 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.
513
+
514
+
515
+ ## Citation
516
+
517
+ If you find our work helpful, feel free to give us a cite.
518
+
519
+ ```
520
+ @article{Qwen2VL,
521
+ title={Qwen2-VL: Enhancing Vision-Language Model's Perception of the World at Any Resolution},
522
+ 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},
523
+ journal={arXiv preprint arXiv:2409.12191},
524
+ year={2024}
525
+ }
526
+
527
+ @article{Qwen-VL,
528
+ title={Qwen-VL: A Versatile Vision-Language Model for Understanding, Localization, Text Reading, and Beyond},
529
+ 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},
530
+ journal={arXiv preprint arXiv:2308.12966},
531
+ year={2023}
532
+ }
533
+ ```