Mungert commited on
Commit
65d053d
·
verified ·
1 Parent(s): c7a4b9f

Create README.md

Browse files
Files changed (1) hide show
  1. README.md +747 -0
README.md ADDED
@@ -0,0 +1,747 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ ---
3
+ license: apache-2.0
4
+ language:
5
+ - en
6
+ pipeline_tag: image-text-to-text
7
+ tags:
8
+ - multimodal
9
+ library_name: transformers
10
+ ---
11
+
12
+ # <span style="color: #7FFF7F;">Qwen2.5-VL-7B-Instruct GGUF Models</span>
13
+
14
+ ## How to Use Qwen 2.5 VL Instruct with llama.cpp
15
+
16
+ To utilize the experimental support for Qwen 2.5 VL in `llama.cpp`, follow these steps:
17
+ Note this uses a fork of llama.cpp. At this time the main branch does not support vision for this model
18
+ 1. **Clone the lastest llama.cpp Fork**:
19
+ ```bash
20
+ git clone https://github.com/HimariO/llama.cpp.qwen2vl.git
21
+ git checkout qwen25-vl
22
+ cd llama.cpp
23
+ ```
24
+
25
+
26
+ 2. **Build the Llama.cpp**:
27
+
28
+ Build llama.cpp as usual : https://github.com/ggml-org/llama.cpp#building-the-project
29
+
30
+ Once llama.cpp is built Copy the ./llama.cpp/build/bin/llama-qwen2-vl-cli to a chosen folder.
31
+
32
+ 3. **Download the Qwen 2.5 VL gguf file**:
33
+
34
+ https://huggingface.co/Mungert/Qwen2.5-VL-7B-Instruct-GGUF/tree/main
35
+
36
+ Choose a gguf file without the mmproj in the name
37
+
38
+ Example gguf file : https://huggingface.co/Mungert/Mungert/Qwen2.5-VL-7B-Instruct-GGUF/resolve/main/Qwen2.5-VL-7B-Instruct-q8_0.gguf
39
+
40
+ Copy this file to your chosen folder.
41
+
42
+ 4. **Download the Gemma 3 mmproj file**
43
+
44
+ https://huggingface.co/Mungert/Qwen2.5-VL-7B-Instruct-GGUF/tree/main
45
+
46
+ Choose a file with mmproj in the name
47
+
48
+ Example mmproj file : https://huggingface.co/Mungert/Qwen2.5-VL-7B-Instruct-GGUF/resolve/main/Qwen2.5-VL-7B-Instruct-mmproj-f16.gguf
49
+
50
+ Copy this file to your chosen folder.
51
+
52
+ 5. Copy images to the same folder as the gguf files or alter paths appropriately.
53
+
54
+ In the example below the gguf files, images and llama-qwen2vl-cli are in the same folder.
55
+
56
+ Example image: image https://huggingface.co/Mungert/Qwen2.5-VL-7B-Instruct-GGUF/resolve/main/car-1.jpg
57
+
58
+ Copy this file to your chosen folder.
59
+
60
+ 6. **Run the CLI Tool**:
61
+
62
+ From your chosen folder :
63
+
64
+ ```bash
65
+ llama-qwen2vl-cli -m Qwen2.5-VL-7B-Instruct-q8_0.gguf --mmproj Qwen2.5-VL-7B-Instruct-mmproj-f16.gguf -p "Describe this image." --image ./car-1.jpg
66
+
67
+ ```
68
+
69
+ ```
70
+
71
+
72
+ ## **Choosing the Right Model Format**
73
+
74
+ Selecting the correct model format depends on your **hardware capabilities** and **memory constraints**.
75
+
76
+ ### **BF16 (Brain Float 16) – Use if BF16 acceleration is available**
77
+ - A 16-bit floating-point format designed for **faster computation** while retaining good precision.
78
+ - Provides **similar dynamic range** as FP32 but with **lower memory usage**.
79
+ - Recommended if your hardware supports **BF16 acceleration** (check your device’s specs).
80
+ - Ideal for **high-performance inference** with **reduced memory footprint** compared to FP32.
81
+
82
+ 📌 **Use BF16 if:**
83
+ ✔ Your hardware has native **BF16 support** (e.g., newer GPUs, TPUs).
84
+ ✔ You want **higher precision** while saving memory.
85
+ ✔ You plan to **requantize** the model into another format.
86
+
87
+ 📌 **Avoid BF16 if:**
88
+ ❌ Your hardware does **not** support BF16 (it may fall back to FP32 and run slower).
89
+ ❌ You need compatibility with older devices that lack BF16 optimization.
90
+
91
+ ---
92
+
93
+ ### **F16 (Float 16) – More widely supported than BF16**
94
+ - A 16-bit floating-point **high precision** but with less of range of values than BF16.
95
+ - Works on most devices with **FP16 acceleration support** (including many GPUs and some CPUs).
96
+ - Slightly lower numerical precision than BF16 but generally sufficient for inference.
97
+
98
+ 📌 **Use F16 if:**
99
+ ✔ Your hardware supports **FP16** but **not BF16**.
100
+ ✔ You need a **balance between speed, memory usage, and accuracy**.
101
+ ✔ You are running on a **GPU** or another device optimized for FP16 computations.
102
+
103
+ 📌 **Avoid F16 if:**
104
+ ❌ Your device lacks **native FP16 support** (it may run slower than expected).
105
+ ❌ You have memory limitations.
106
+
107
+ ---
108
+
109
+ ### **Quantized Models (Q4_K, Q6_K, Q8, etc.) – For CPU & Low-VRAM Inference**
110
+ Quantization reduces model size and memory usage while maintaining as much accuracy as possible.
111
+ - **Lower-bit models (Q4_K)** → **Best for minimal memory usage**, may have lower precision.
112
+ - **Higher-bit models (Q6_K, Q8_0)** → **Better accuracy**, requires more memory.
113
+
114
+ 📌 **Use Quantized Models if:**
115
+ ✔ You are running inference on a **CPU** and need an optimized model.
116
+ ✔ Your device has **low VRAM** and cannot load full-precision models.
117
+ ✔ You want to reduce **memory footprint** while keeping reasonable accuracy.
118
+
119
+ 📌 **Avoid Quantized Models if:**
120
+ ❌ You need **maximum accuracy** (full-precision models are better for this).
121
+ ❌ Your hardware has enough VRAM for higher-precision formats (BF16/F16).
122
+
123
+ ---
124
+
125
+ ### **Very Low-Bit Quantization (IQ3_XS, IQ3_S, IQ3_M, Q4_K, Q4_0)**
126
+ These models are optimized for **extreme memory efficiency**, making them ideal for **low-power devices** or **large-scale deployments** where memory is a critical constraint.
127
+
128
+ - **IQ3_XS**: Ultra-low-bit quantization (3-bit) with **extreme memory efficiency**.
129
+ - **Use case**: Best for **ultra-low-memory devices** where even Q4_K is too large.
130
+ - **Trade-off**: Lower accuracy compared to higher-bit quantizations.
131
+
132
+ - **IQ3_S**: Small block size for **maximum memory efficiency**.
133
+ - **Use case**: Best for **low-memory devices** where **IQ3_XS** is too aggressive.
134
+
135
+ - **IQ3_M**: Medium block size for better accuracy than **IQ3_S**.
136
+ - **Use case**: Suitable for **low-memory devices** where **IQ3_S** is too limiting.
137
+
138
+ - **Q4_K**: 4-bit quantization with **block-wise optimization** for better accuracy.
139
+ - **Use case**: Best for **low-memory devices** where **Q6_K** is too large.
140
+
141
+ - **Q4_0**: Pure 4-bit quantization, optimized for **ARM devices**.
142
+ - **Use case**: Best for **ARM-based devices** or **low-memory environments**.
143
+
144
+ ---
145
+
146
+ ### **Summary Table: Model Format Selection**
147
+
148
+ | Model Format | Precision | Memory Usage | Device Requirements | Best Use Case |
149
+ |--------------|------------|---------------|----------------------|---------------|
150
+ | **BF16** | Highest | High | BF16-supported GPU/CPUs | High-speed inference with reduced memory |
151
+ | **F16** | High | High | FP16-supported devices | GPU inference when BF16 isn’t available |
152
+ | **Q4_K** | Medium Low | Low | CPU or Low-VRAM devices | Best for memory-constrained environments |
153
+ | **Q6_K** | Medium | Moderate | CPU with more memory | Better accuracy while still being quantized |
154
+ | **Q8_0** | High | Moderate | CPU or GPU with enough VRAM | Best accuracy among quantized models |
155
+ | **IQ3_XS** | Very Low | Very Low | Ultra-low-memory devices | Extreme memory efficiency and low accuracy |
156
+ | **Q4_0** | Low | Low | ARM or low-memory devices | llama.cpp can optimize for ARM devices |
157
+
158
+ ---
159
+
160
+ ## **Included Files & Details**
161
+
162
+ ### `Qwen2.5-VL-7B-Instruct-bf16.gguf`
163
+ - Model weights preserved in **BF16**.
164
+ - Use this if you want to **requantize** the model into a different format.
165
+ - Best if your device supports **BF16 acceleration**.
166
+
167
+ ### `Qwen2.5-VL-7B-Instruct-f16.gguf`
168
+ - Model weights stored in **F16**.
169
+ - Use if your device supports **FP16**, especially if BF16 is not available.
170
+
171
+ ### `Qwen2.5-VL-7B-Instruct-bf16-q8_0.gguf`
172
+ - **Output & embeddings** remain in **BF16**.
173
+ - All other layers quantized to **Q8_0**.
174
+ - Use if your device supports **BF16** and you want a quantized version.
175
+
176
+ ### `Qwen2.5-VL-7B-Instruct-f16-q8_0.gguf`
177
+ - **Output & embeddings** remain in **F16**.
178
+ - All other layers quantized to **Q8_0**.
179
+
180
+ ### `Qwen2.5-VL-7B-Instruct-q4_k.gguf`
181
+ - **Output & embeddings** quantized to **Q8_0**.
182
+ - All other layers quantized to **Q4_K**.
183
+ - Good for **CPU inference** with limited memory.
184
+
185
+ ### `Qwen2.5-VL-7B-Instruct-q4_k_s.gguf`
186
+ - Smallest **Q4_K** variant, using less memory at the cost of accuracy.
187
+ - Best for **very low-memory setups**.
188
+
189
+ ### `Qwen2.5-VL-7B-Instruct-q6_k.gguf`
190
+ - **Output & embeddings** quantized to **Q8_0**.
191
+ - All other layers quantized to **Q6_K** .
192
+
193
+ ### `Qwen2.5-VL-7B-Instruct-q8_0.gguf`
194
+ - Fully **Q8** quantized model for better accuracy.
195
+ - Requires **more memory** but offers higher precision.
196
+
197
+ ### `Qwen2.5-VL-7B-Instruct-iq3_xs.gguf`
198
+ - **IQ3_XS** quantization, optimized for **extreme memory efficiency**.
199
+ - Best for **ultra-low-memory devices**.
200
+
201
+ ### `Qwen2.5-VL-7B-Instruct-iq3_m.gguf`
202
+ - **IQ3_M** quantization, offering a **medium block size** for better accuracy.
203
+ - Suitable for **low-memory devices**.
204
+
205
+ ### `Qwen2.5-VL-7B-Instruct-q4_0.gguf`
206
+ - Pure **Q4_0** quantization, optimized for **ARM devices**.
207
+ - Best for **low-memory environments**.
208
+ - Prefer IQ4_NL for better accuracy.
209
+
210
+ # <span id="testllm" style="color: #7F7FFF;">🚀 If you find these models useful</span>
211
+
212
+ Please click like ❤ . Also I’d really appreciate it if you could test my Network Monitor Assistant at 👉 [Network Monitor Assitant](https://freenetworkmonitor.click/dashboard).
213
+
214
+ 💬 Click the **chat icon** (bottom right of the main and dashboard pages) . Choose a LLM; toggle between the LLM Types TurboLLM -> FreeLLM -> TestLLM.
215
+
216
+ ### What I'm Testing
217
+
218
+ I'm experimenting with **function calling** against my network monitoring service. Using small open source models. I am into the question "How small can it go and still function".
219
+
220
+ 🟡 **TestLLM** – Runs the current testing model using llama.cpp on 6 threads of a Cpu VM (Should take about 15s to load. Inference speed is quite slow and it only processes one user prompt at a time—still working on scaling!). If you're curious, I'd be happy to share how it works! .
221
+
222
+ ### The other Available AI Assistants
223
+
224
+ 🟢 **TurboLLM** – Uses **gpt-4o-mini** Fast! . Note: tokens are limited since OpenAI models are pricey, but you can [Login](https://freenetworkmonitor.click) or [Download](https://freenetworkmonitor.click/download) the Free Network Monitor agent to get more tokens, Alternatively use the TestLLM .
225
+
226
+ 🔵 **HugLLM** – Runs **open-source Hugging Face models** Fast, Runs small models (≈8B) hence lower quality, Get 2x more tokens (subject to Hugging Face API availability)
227
+
228
+
229
+
230
+
231
+ # Qwen2.5-VL-7B-Instruct
232
+ <a href="https://chat.qwenlm.ai/" target="_blank" style="margin: 2px;">
233
+ <img alt="Chat" src="https://img.shields.io/badge/%F0%9F%92%9C%EF%B8%8F%20Qwen%20Chat%20-536af5" style="display: inline-block; vertical-align: middle;"/>
234
+ </a>
235
+
236
+ ## Introduction
237
+
238
+ In the past five months since Qwen2-VL’s release, numerous developers have built new models on the Qwen2-VL vision-language models, providing us with valuable feedback. During this period, we focused on building more useful vision-language models. Today, we are excited to introduce the latest addition to the Qwen family: Qwen2.5-VL.
239
+
240
+ #### Key Enhancements:
241
+ * **Understand things visually**: Qwen2.5-VL is not only proficient in recognizing common objects such as flowers, birds, fish, and insects, but it is highly capable of analyzing texts, charts, icons, graphics, and layouts within images.
242
+
243
+ * **Being agentic**: Qwen2.5-VL directly plays as a visual agent that can reason and dynamically direct tools, which is capable of computer use and phone use.
244
+
245
+ * **Understanding long videos and capturing events**: Qwen2.5-VL can comprehend videos of over 1 hour, and this time it has a new ability of cpaturing event by pinpointing the relevant video segments.
246
+
247
+ * **Capable of visual localization in different formats**: Qwen2.5-VL can accurately localize objects in an image by generating bounding boxes or points, and it can provide stable JSON outputs for coordinates and attributes.
248
+
249
+ * **Generating structured outputs**: for data like scans of invoices, forms, tables, etc. Qwen2.5-VL supports structured outputs of their contents, benefiting usages in finance, commerce, etc.
250
+
251
+
252
+ #### Model Architecture Updates:
253
+
254
+ * **Dynamic Resolution and Frame Rate Training for Video Understanding**:
255
+
256
+ We extend dynamic resolution to the temporal dimension by adopting dynamic FPS sampling, enabling the model to comprehend videos at various sampling rates. Accordingly, we update mRoPE in the time dimension with IDs and absolute time alignment, enabling the model to learn temporal sequence and speed, and ultimately acquire the ability to pinpoint specific moments.
257
+
258
+ <p align="center">
259
+ <img src="https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen2.5-VL/qwen2.5vl_arc.jpeg" width="80%"/>
260
+ <p>
261
+
262
+
263
+ * **Streamlined and Efficient Vision Encoder**
264
+
265
+ We enhance both training and inference speeds by strategically implementing window attention into the ViT. The ViT architecture is further optimized with SwiGLU and RMSNorm, aligning it with the structure of the Qwen2.5 LLM.
266
+
267
+
268
+ We have three models with 3, 7 and 72 billion parameters. This repo contains the instruction-tuned 7B Qwen2.5-VL model. For more information, visit our [Blog](https://qwenlm.github.io/blog/qwen2.5-vl/) and [GitHub](https://github.com/QwenLM/Qwen2.5-VL).
269
+
270
+
271
+
272
+ ## Evaluation
273
+
274
+ ### Image benchmark
275
+
276
+
277
+ | Benchmark | InternVL2.5-8B | MiniCPM-o 2.6 | GPT-4o-mini | Qwen2-VL-7B |**Qwen2.5-VL-7B** |
278
+ | :--- | :---: | :---: | :---: | :---: | :---: |
279
+ | MMMU<sub>val</sub> | 56 | 50.4 | **60**| 54.1 | 58.6|
280
+ | MMMU-Pro<sub>val</sub> | 34.3 | - | 37.6| 30.5 | 41.0|
281
+ | DocVQA<sub>test</sub> | 93 | 93 | - | 94.5 | **95.7** |
282
+ | InfoVQA<sub>test</sub> | 77.6 | - | - |76.5 | **82.6** |
283
+ | ChartQA<sub>test</sub> | 84.8 | - |- | 83.0 |**87.3** |
284
+ | TextVQA<sub>val</sub> | 79.1 | 80.1 | -| 84.3 | **84.9**|
285
+ | OCRBench | 822 | 852 | 785 | 845 | **864** |
286
+ | CC_OCR | 57.7 | | | 61.6 | **77.8**|
287
+ | MMStar | 62.8| | |60.7| **63.9**|
288
+ | MMBench-V1.1-En<sub>test</sub> | 79.4 | 78.0 | 76.0| 80.7 | **82.6** |
289
+ | MMT-Bench<sub>test</sub> | - | - | - |**63.7** |63.6 |
290
+ | MMStar | **61.5** | 57.5 | 54.8 | 60.7 |63.9 |
291
+ | MMVet<sub>GPT-4-Turbo</sub> | 54.2 | 60.0 | 66.9 | 62.0 | **67.1**|
292
+ | HallBench<sub>avg</sub> | 45.2 | 48.1 | 46.1| 50.6 | **52.9**|
293
+ | MathVista<sub>testmini</sub> | 58.3 | 60.6 | 52.4 | 58.2 | **68.2**|
294
+ | MathVision | - | - | - | 16.3 | **25.07** |
295
+
296
+ ### Video Benchmarks
297
+
298
+ | Benchmark | Qwen2-VL-7B | **Qwen2.5-VL-7B** |
299
+ | :--- | :---: | :---: |
300
+ | MVBench | 67.0 | **69.6** |
301
+ | PerceptionTest<sub>test</sub> | 66.9 | **70.5** |
302
+ | Video-MME<sub>wo/w subs</sub> | 63.3/69.0 | **65.1**/**71.6** |
303
+ | LVBench | | 45.3 |
304
+ | LongVideoBench | | 54.7 |
305
+ | MMBench-Video | 1.44 | 1.79 |
306
+ | TempCompass | | 71.7 |
307
+ | MLVU | | 70.2 |
308
+ | CharadesSTA/mIoU | 43.6|
309
+
310
+ ### Agent benchmark
311
+ | Benchmarks | Qwen2.5-VL-7B |
312
+ |-------------------------|---------------|
313
+ | ScreenSpot | 84.7 |
314
+ | ScreenSpot Pro | 29.0 |
315
+ | AITZ_EM | 81.9 |
316
+ | Android Control High_EM | 60.1 |
317
+ | Android Control Low_EM | 93.7 |
318
+ | AndroidWorld_SR | 25.5 |
319
+ | MobileMiniWob++_SR | 91.4 |
320
+
321
+ ## Requirements
322
+ The code of Qwen2.5-VL has been in the latest Hugging face transformers and we advise you to build from source with command:
323
+ ```
324
+ pip install git+https://github.com/huggingface/transformers accelerate
325
+ ```
326
+ or you might encounter the following error:
327
+ ```
328
+ KeyError: 'qwen2_5_vl'
329
+ ```
330
+
331
+
332
+ ## Quickstart
333
+
334
+ Below, we provide simple examples to show how to use Qwen2.5-VL with 🤖 ModelScope and 🤗 Transformers.
335
+
336
+ The code of Qwen2.5-VL has been in the latest Hugging face transformers and we advise you to build from source with command:
337
+ ```
338
+ pip install git+https://github.com/huggingface/transformers accelerate
339
+ ```
340
+ or you might encounter the following error:
341
+ ```
342
+ KeyError: 'qwen2_5_vl'
343
+ ```
344
+
345
+
346
+ We offer a toolkit to help you handle various types of visual input more conveniently, as if you were using an API. This includes base64, URLs, and interleaved images and videos. You can install it using the following command:
347
+
348
+ ```bash
349
+ # It's highly recommanded to use `[decord]` feature for faster video loading.
350
+ pip install qwen-vl-utils[decord]==0.0.8
351
+ ```
352
+
353
+ If you are not using Linux, you might not be able to install `decord` from PyPI. In that case, you can use `pip install qwen-vl-utils` which will fall back to using torchvision for video processing. However, you can still [install decord from source](https://github.com/dmlc/decord?tab=readme-ov-file#install-from-source) to get decord used when loading video.
354
+
355
+ ### Using 🤗 Transformers to Chat
356
+
357
+ Here we show a code snippet to show you how to use the chat model with `transformers` and `qwen_vl_utils`:
358
+
359
+ ```python
360
+ from transformers import Qwen2_5_VLForConditionalGeneration, AutoTokenizer, AutoProcessor
361
+ from qwen_vl_utils import process_vision_info
362
+
363
+ # default: Load the model on the available device(s)
364
+ model = Qwen2_5_VLForConditionalGeneration.from_pretrained(
365
+ "Qwen/Qwen2.5-VL-7B-Instruct", torch_dtype="auto", device_map="auto"
366
+ )
367
+
368
+ # We recommend enabling flash_attention_2 for better acceleration and memory saving, especially in multi-image and video scenarios.
369
+ # model = Qwen2_5_VLForConditionalGeneration.from_pretrained(
370
+ # "Qwen/Qwen2.5-VL-7B-Instruct",
371
+ # torch_dtype=torch.bfloat16,
372
+ # attn_implementation="flash_attention_2",
373
+ # device_map="auto",
374
+ # )
375
+
376
+ # default processer
377
+ processor = AutoProcessor.from_pretrained("Qwen/Qwen2.5-VL-7B-Instruct")
378
+
379
+ # The default range for the number of visual tokens per image in the model is 4-16384.
380
+ # You can set min_pixels and max_pixels according to your needs, such as a token range of 256-1280, to balance performance and cost.
381
+ # min_pixels = 256*28*28
382
+ # max_pixels = 1280*28*28
383
+ # processor = AutoProcessor.from_pretrained("Qwen/Qwen2.5-VL-7B-Instruct", min_pixels=min_pixels, max_pixels=max_pixels)
384
+
385
+ messages = [
386
+ {
387
+ "role": "user",
388
+ "content": [
389
+ {
390
+ "type": "image",
391
+ "image": "https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen-VL/assets/demo.jpeg",
392
+ },
393
+ {"type": "text", "text": "Describe this image."},
394
+ ],
395
+ }
396
+ ]
397
+
398
+ # Preparation for inference
399
+ text = processor.apply_chat_template(
400
+ messages, tokenize=False, add_generation_prompt=True
401
+ )
402
+ image_inputs, video_inputs = process_vision_info(messages)
403
+ inputs = processor(
404
+ text=[text],
405
+ images=image_inputs,
406
+ videos=video_inputs,
407
+ padding=True,
408
+ return_tensors="pt",
409
+ )
410
+ inputs = inputs.to("cuda")
411
+
412
+ # Inference: Generation of the output
413
+ generated_ids = model.generate(**inputs, max_new_tokens=128)
414
+ generated_ids_trimmed = [
415
+ out_ids[len(in_ids) :] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
416
+ ]
417
+ output_text = processor.batch_decode(
418
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
419
+ )
420
+ print(output_text)
421
+ ```
422
+ <details>
423
+ <summary>Multi image inference</summary>
424
+
425
+ ```python
426
+ # Messages containing multiple images and a text query
427
+ messages = [
428
+ {
429
+ "role": "user",
430
+ "content": [
431
+ {"type": "image", "image": "file:///path/to/image1.jpg"},
432
+ {"type": "image", "image": "file:///path/to/image2.jpg"},
433
+ {"type": "text", "text": "Identify the similarities between these images."},
434
+ ],
435
+ }
436
+ ]
437
+
438
+ # Preparation for inference
439
+ text = processor.apply_chat_template(
440
+ messages, tokenize=False, add_generation_prompt=True
441
+ )
442
+ image_inputs, video_inputs = process_vision_info(messages)
443
+ inputs = processor(
444
+ text=[text],
445
+ images=image_inputs,
446
+ videos=video_inputs,
447
+ padding=True,
448
+ return_tensors="pt",
449
+ )
450
+ inputs = inputs.to("cuda")
451
+
452
+ # Inference
453
+ generated_ids = model.generate(**inputs, max_new_tokens=128)
454
+ generated_ids_trimmed = [
455
+ out_ids[len(in_ids) :] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
456
+ ]
457
+ output_text = processor.batch_decode(
458
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
459
+ )
460
+ print(output_text)
461
+ ```
462
+ </details>
463
+
464
+ <details>
465
+ <summary>Video inference</summary>
466
+
467
+ ```python
468
+ # Messages containing a images list as a video and a text query
469
+ messages = [
470
+ {
471
+ "role": "user",
472
+ "content": [
473
+ {
474
+ "type": "video",
475
+ "video": [
476
+ "file:///path/to/frame1.jpg",
477
+ "file:///path/to/frame2.jpg",
478
+ "file:///path/to/frame3.jpg",
479
+ "file:///path/to/frame4.jpg",
480
+ ],
481
+ },
482
+ {"type": "text", "text": "Describe this video."},
483
+ ],
484
+ }
485
+ ]
486
+
487
+ # Messages containing a local video path and a text query
488
+ messages = [
489
+ {
490
+ "role": "user",
491
+ "content": [
492
+ {
493
+ "type": "video",
494
+ "video": "file:///path/to/video1.mp4",
495
+ "max_pixels": 360 * 420,
496
+ "fps": 1.0,
497
+ },
498
+ {"type": "text", "text": "Describe this video."},
499
+ ],
500
+ }
501
+ ]
502
+
503
+ # Messages containing a video url and a text query
504
+ messages = [
505
+ {
506
+ "role": "user",
507
+ "content": [
508
+ {
509
+ "type": "video",
510
+ "video": "https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen2-VL/space_woaudio.mp4",
511
+ },
512
+ {"type": "text", "text": "Describe this video."},
513
+ ],
514
+ }
515
+ ]
516
+
517
+ #In Qwen 2.5 VL, frame rate information is also input into the model to align with absolute time.
518
+ # Preparation for inference
519
+ text = processor.apply_chat_template(
520
+ messages, tokenize=False, add_generation_prompt=True
521
+ )
522
+ image_inputs, video_inputs, video_kwargs = process_vision_info(messages, return_video_kwargs=True)
523
+ inputs = processor(
524
+ text=[text],
525
+ images=image_inputs,
526
+ videos=video_inputs,
527
+ fps=fps,
528
+ padding=True,
529
+ return_tensors="pt",
530
+ **video_kwargs,
531
+ )
532
+ inputs = inputs.to("cuda")
533
+
534
+ # Inference
535
+ generated_ids = model.generate(**inputs, max_new_tokens=128)
536
+ generated_ids_trimmed = [
537
+ out_ids[len(in_ids) :] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
538
+ ]
539
+ output_text = processor.batch_decode(
540
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
541
+ )
542
+ print(output_text)
543
+ ```
544
+
545
+ Video URL compatibility largely depends on the third-party library version. The details are in the table below. change the backend by `FORCE_QWENVL_VIDEO_READER=torchvision` or `FORCE_QWENVL_VIDEO_READER=decord` if you prefer not to use the default one.
546
+
547
+ | Backend | HTTP | HTTPS |
548
+ |-------------|------|-------|
549
+ | torchvision >= 0.19.0 | ✅ | ✅ |
550
+ | torchvision < 0.19.0 | ❌ | ❌ |
551
+ | decord | ✅ | ❌ |
552
+ </details>
553
+
554
+ <details>
555
+ <summary>Batch inference</summary>
556
+
557
+ ```python
558
+ # Sample messages for batch inference
559
+ messages1 = [
560
+ {
561
+ "role": "user",
562
+ "content": [
563
+ {"type": "image", "image": "file:///path/to/image1.jpg"},
564
+ {"type": "image", "image": "file:///path/to/image2.jpg"},
565
+ {"type": "text", "text": "What are the common elements in these pictures?"},
566
+ ],
567
+ }
568
+ ]
569
+ messages2 = [
570
+ {"role": "system", "content": "You are a helpful assistant."},
571
+ {"role": "user", "content": "Who are you?"},
572
+ ]
573
+ # Combine messages for batch processing
574
+ messages = [messages1, messages2]
575
+
576
+ # Preparation for batch inference
577
+ texts = [
578
+ processor.apply_chat_template(msg, tokenize=False, add_generation_prompt=True)
579
+ for msg in messages
580
+ ]
581
+ image_inputs, video_inputs = process_vision_info(messages)
582
+ inputs = processor(
583
+ text=texts,
584
+ images=image_inputs,
585
+ videos=video_inputs,
586
+ padding=True,
587
+ return_tensors="pt",
588
+ )
589
+ inputs = inputs.to("cuda")
590
+
591
+ # Batch Inference
592
+ generated_ids = model.generate(**inputs, max_new_tokens=128)
593
+ generated_ids_trimmed = [
594
+ out_ids[len(in_ids) :] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
595
+ ]
596
+ output_texts = processor.batch_decode(
597
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
598
+ )
599
+ print(output_texts)
600
+ ```
601
+ </details>
602
+
603
+ ### 🤖 ModelScope
604
+ We strongly advise users especially those in mainland China to use ModelScope. `snapshot_download` can help you solve issues concerning downloading checkpoints.
605
+
606
+
607
+ ### More Usage Tips
608
+
609
+ For input images, we support local files, base64, and URLs. For videos, we currently only support local files.
610
+
611
+ ```python
612
+ # You can directly insert a local file path, a URL, or a base64-encoded image into the position where you want in the text.
613
+ ## Local file path
614
+ messages = [
615
+ {
616
+ "role": "user",
617
+ "content": [
618
+ {"type": "image", "image": "file:///path/to/your/image.jpg"},
619
+ {"type": "text", "text": "Describe this image."},
620
+ ],
621
+ }
622
+ ]
623
+ ## Image URL
624
+ messages = [
625
+ {
626
+ "role": "user",
627
+ "content": [
628
+ {"type": "image", "image": "http://path/to/your/image.jpg"},
629
+ {"type": "text", "text": "Describe this image."},
630
+ ],
631
+ }
632
+ ]
633
+ ## Base64 encoded image
634
+ messages = [
635
+ {
636
+ "role": "user",
637
+ "content": [
638
+ {"type": "image", "image": "data:image;base64,/9j/..."},
639
+ {"type": "text", "text": "Describe this image."},
640
+ ],
641
+ }
642
+ ]
643
+ ```
644
+ #### Image Resolution for performance boost
645
+
646
+ 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.
647
+
648
+ ```python
649
+ min_pixels = 256 * 28 * 28
650
+ max_pixels = 1280 * 28 * 28
651
+ processor = AutoProcessor.from_pretrained(
652
+ "Qwen/Qwen2.5-VL-7B-Instruct", min_pixels=min_pixels, max_pixels=max_pixels
653
+ )
654
+ ```
655
+
656
+ Besides, We provide two methods for fine-grained control over the image size input to the model:
657
+
658
+ 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.
659
+
660
+ 2. Specify exact dimensions: Directly set `resized_height` and `resized_width`. These values will be rounded to the nearest multiple of 28.
661
+
662
+ ```python
663
+ # min_pixels and max_pixels
664
+ messages = [
665
+ {
666
+ "role": "user",
667
+ "content": [
668
+ {
669
+ "type": "image",
670
+ "image": "file:///path/to/your/image.jpg",
671
+ "resized_height": 280,
672
+ "resized_width": 420,
673
+ },
674
+ {"type": "text", "text": "Describe this image."},
675
+ ],
676
+ }
677
+ ]
678
+ # resized_height and resized_width
679
+ messages = [
680
+ {
681
+ "role": "user",
682
+ "content": [
683
+ {
684
+ "type": "image",
685
+ "image": "file:///path/to/your/image.jpg",
686
+ "min_pixels": 50176,
687
+ "max_pixels": 50176,
688
+ },
689
+ {"type": "text", "text": "Describe this image."},
690
+ ],
691
+ }
692
+ ]
693
+ ```
694
+
695
+ ### Processing Long Texts
696
+
697
+ The current `config.json` is set for context length up to 32,768 tokens.
698
+ To handle extensive inputs exceeding 32,768 tokens, we utilize [YaRN](https://arxiv.org/abs/2309.00071), a technique for enhancing model length extrapolation, ensuring optimal performance on lengthy texts.
699
+
700
+ For supported frameworks, you could add the following to `config.json` to enable YaRN:
701
+
702
+ {
703
+ ...,
704
+ "type": "yarn",
705
+ "mrope_section": [
706
+ 16,
707
+ 24,
708
+ 24
709
+ ],
710
+ "factor": 4,
711
+ "original_max_position_embeddings": 32768
712
+ }
713
+
714
+ However, it should be noted that this method has a significant impact on the performance of temporal and spatial localization tasks, and is therefore not recommended for use.
715
+
716
+ At the same time, for long video inputs, since MRoPE itself is more economical with ids, the max_position_embeddings can be directly modified to a larger value, such as 64k.
717
+
718
+
719
+
720
+
721
+ ## Citation
722
+
723
+ If you find our work helpful, feel free to give us a cite.
724
+
725
+ ```
726
+ @misc{qwen2.5-VL,
727
+ title = {Qwen2.5-VL},
728
+ url = {https://qwenlm.github.io/blog/qwen2.5-vl/},
729
+ author = {Qwen Team},
730
+ month = {January},
731
+ year = {2025}
732
+ }
733
+
734
+ @article{Qwen2VL,
735
+ title={Qwen2-VL: Enhancing Vision-Language Model's Perception of the World at Any Resolution},
736
+ 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},
737
+ journal={arXiv preprint arXiv:2409.12191},
738
+ year={2024}
739
+ }
740
+
741
+ @article{Qwen-VL,
742
+ title={Qwen-VL: A Versatile Vision-Language Model for Understanding, Localization, Text Reading, and Beyond},
743
+ 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},
744
+ journal={arXiv preprint arXiv:2308.12966},
745
+ year={2023}
746
+ }
747
+ ```