shimmyshimmer commited on
Commit
e041f2b
1 Parent(s): ac0e1de

Update README.md

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