shimmyshimmer commited on
Commit
aab01d3
1 Parent(s): 795dcd9

Update README.md

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