Files changed (1) hide show
  1. README.md +355 -343
README.md CHANGED
@@ -1,344 +1,356 @@
1
- ---
2
- license: apache-2.0
3
- pipeline_tag: text-generation
4
- language:
5
- - en
6
- license_link: LICENSE
7
- base_model: Qwen/Qwen2.5-7B
8
- quantized_by: bartowski
9
- tags:
10
- - llamafile
11
- - chat
12
- ---
13
-
14
- # Qwen 2.5 Instruct 7B - llamafile
15
-
16
- - Model creator: [Qwen](https://huggingface.co/Qwen/)
17
- - Original model: [Qwen/Qwen2.5-7B-Instruct-1M](https://huggingface.co/Qwen/Qwen2.5-7B-Instruct-1M/)
18
-
19
- Mozilla packaged the Qwen 2.5 models into executable weights that we
20
- call [llamafiles](https://github.com/Mozilla-Ocho/llamafile). This gives
21
- you the easiest fastest way to use the model on Linux, MacOS, Windows,
22
- FreeBSD, OpenBSD and NetBSD systems you control on both AMD64 and ARM64.
23
-
24
- *Software Last Updated: 2025-03-31*
25
-
26
- *Llamafile Version: 0.9.2*
27
-
28
- ## Quickstart
29
-
30
- To get started, you need both the Qwen 2.5 weights, and the llamafile
31
- software. Both of them are included in a single file, which can be
32
- downloaded and run as follows:
33
-
34
- ```
35
- wget https://huggingface.co/Mozilla/Qwen2.5-7B-Instruct-1M-llamafile/resolve/main/Qwen2.5-7B-Instruct-1M-Q6_K.llamafile
36
- chmod +x Qwen2.5-7B-Instruct-1M-Q6_K.llamafile
37
- ./Qwen2.5-7B-Instruct-1M-Q6_K.llamafile
38
- ```
39
-
40
- The default mode of operation for these llamafiles is our new command
41
- line chatbot interface.
42
-
43
- ## Usage
44
-
45
- You can use triple quotes to ask questions on multiple lines. You can
46
- pass commands like `/stats` and `/context` to see runtime status
47
- information. You can change the system prompt by passing the `-p "new
48
- system prompt"` flag. You can press CTRL-C to interrupt the model.
49
- Finally CTRL-D may be used to exit.
50
-
51
- If you prefer to use a web GUI, then a `--server` mode is provided, that
52
- will open a tab with a chatbot and completion interface in your browser.
53
- For additional help on how it may be used, pass the `--help` flag. The
54
- server also has an OpenAI API compatible completions endpoint that can
55
- be accessed via Python using the `openai` pip package.
56
-
57
- ```
58
- ./Qwen2.5-7B-Instruct-1M-Q6_K.llamafile --server
59
- ```
60
-
61
- An advanced CLI mode is provided that's useful for shell scripting. You
62
- can use it by passing the `--cli` flag. For additional help on how it
63
- may be used, pass the `--help` flag.
64
-
65
- ```
66
- ./Qwen2.5-7B-Instruct-1M-Q6_K.llamafile --cli -p 'four score and seven' --log-disable
67
- ```
68
-
69
- ## Troubleshooting
70
-
71
- Having **trouble?** See the ["Gotchas"
72
- section](https://github.com/mozilla-ocho/llamafile/?tab=readme-ov-file#gotchas-and-troubleshooting)
73
- of the README.
74
-
75
- On Linux, the way to avoid run-detector errors is to install the APE
76
- interpreter.
77
-
78
- ```sh
79
- sudo wget -O /usr/bin/ape https://cosmo.zip/pub/cosmos/bin/ape-$(uname -m).elf
80
- sudo chmod +x /usr/bin/ape
81
- sudo sh -c "echo ':APE:M::MZqFpD::/usr/bin/ape:' >/proc/sys/fs/binfmt_misc/register"
82
- sudo sh -c "echo ':APE-jart:M::jartsr::/usr/bin/ape:' >/proc/sys/fs/binfmt_misc/register"
83
- ```
84
-
85
- On Windows there's a 4GB limit on executable sizes.
86
-
87
- ## Context Window
88
-
89
- This model has a max context window size of 128k tokens. By default, a
90
- context window size of 8192 tokens is used. You can ask llamafile
91
- to use the maximum context size by passing the `-c 0` flag. That's big
92
- enough for a small book. If you want to be able to have a conversation
93
- with your book, you can use the `-f book.txt` flag.
94
-
95
- ## GPU Acceleration
96
-
97
- On GPUs with sufficient RAM, the `-ngl 999` flag may be passed to use
98
- the system's NVIDIA or AMD GPU(s). On Windows, only the graphics card
99
- driver needs to be installed if you own an NVIDIA GPU. On Windows, if
100
- you have an AMD GPU, you should install the ROCm SDK v6.1 and then pass
101
- the flags `--recompile --gpu amd` the first time you run your llamafile.
102
-
103
- On NVIDIA GPUs, by default, the prebuilt tinyBLAS library is used to
104
- perform matrix multiplications. This is open source software, but it
105
- doesn't go as fast as closed source cuBLAS. If you have the CUDA SDK
106
- installed on your system, then you can pass the `--recompile` flag to
107
- build a GGML CUDA library just for your system that uses cuBLAS. This
108
- ensures you get maximum performance.
109
-
110
- For further information, please see the [llamafile
111
- README](https://github.com/mozilla-ocho/llamafile/).
112
-
113
- ## About llamafile
114
-
115
- llamafile is a new format introduced by Mozilla on Nov 20th 2023. It
116
- uses Cosmopolitan Libc to turn LLM weights into runnable llama.cpp
117
- binaries that run on the stock installs of six OSes for both ARM64 and
118
- AMD64.
119
-
120
- ---
121
-
122
- # Qwen2.5-7B-Instruct-1M
123
- <a href="https://chat.qwenlm.ai/" target="_blank" style="margin: 2px;">
124
- <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;"/>
125
- </a>
126
-
127
- ## Introduction
128
-
129
- Qwen2.5-1M is the long-context version of the Qwen2.5 series models, supporting a context length of up to 1M tokens. Compared to the Qwen2.5 128K version, Qwen2.5-1M demonstrates significantly improved performance in handling long-context tasks while maintaining its capability in short tasks.
130
-
131
- The model has the following features:
132
- - Type: Causal Language Models
133
- - Training Stage: Pretraining & Post-training
134
- - Architecture: transformers with RoPE, SwiGLU, RMSNorm, and Attention QKV bias
135
- - Number of Parameters: 7.61B
136
- - Number of Paramaters (Non-Embedding): 6.53B
137
- - Number of Layers: 28
138
- - Number of Attention Heads (GQA): 28 for Q and 4 for KV
139
- - Context Length: Full 1,010,000 tokens and generation 8192 tokens
140
- - We recommend deploying with our custom vLLM, which introduces sparse attention and length extrapolation methods to ensure efficiency and accuracy for long-context tasks. For specific guidance, refer to [this section](#processing-ultra-long-texts).
141
- - You can also use the previous framework that supports Qwen2.5 for inference, but accuracy degradation may occur for sequences exceeding 262,144 tokens.
142
-
143
- For more details, please refer to our [blog](https://qwenlm.github.io/blog/qwen2.5-1m/), [GitHub](https://github.com/QwenLM/Qwen2.5), [Technical Report](https://huggingface.co/papers/2501.15383), and [Documentation](https://qwen.readthedocs.io/en/latest/).
144
- ## Requirements
145
-
146
- The code of Qwen2.5 has been in the latest Hugging face `transformers` and we advise you to use the latest version of `transformers`.
147
-
148
- With `transformers<4.37.0`, you will encounter the following error:
149
- ```
150
- KeyError: 'qwen2'
151
- ```
152
-
153
- ## Quickstart
154
-
155
- Here provides a code snippet with `apply_chat_template` to show you how to load the tokenizer and model and how to generate contents.
156
-
157
- ```python
158
- from transformers import AutoModelForCausalLM, AutoTokenizer
159
-
160
- model_name = "Qwen/Qwen2.5-7B-Instruct-1M"
161
-
162
- model = AutoModelForCausalLM.from_pretrained(
163
- model_name,
164
- torch_dtype="auto",
165
- device_map="auto"
166
- )
167
- tokenizer = AutoTokenizer.from_pretrained(model_name)
168
-
169
- prompt = "Give me a short introduction to large language model."
170
- messages = [
171
- {"role": "system", "content": "You are Qwen, created by Alibaba Cloud. You are a helpful assistant."},
172
- {"role": "user", "content": prompt}
173
- ]
174
- text = tokenizer.apply_chat_template(
175
- messages,
176
- tokenize=False,
177
- add_generation_prompt=True
178
- )
179
- model_inputs = tokenizer([text], return_tensors="pt").to(model.device)
180
-
181
- generated_ids = model.generate(
182
- **model_inputs,
183
- max_new_tokens=512
184
- )
185
- generated_ids = [
186
- output_ids[len(input_ids):] for input_ids, output_ids in zip(model_inputs.input_ids, generated_ids)
187
- ]
188
-
189
- response = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]
190
- ```
191
-
192
- ### Processing Ultra Long Texts
193
-
194
- To enhance processing accuracy and efficiency for long sequences, we have developed an advanced inference framework based on vLLM, incorporating sparse attention and length extrapolation. This approach significantly improves model generation performance for sequences exceeding 256K tokens and achieves a 3 to 7 times speedup for sequences up to 1M tokens.
195
-
196
- Here we provide step-by-step instructions for deploying the Qwen2.5-1M models with our framework.
197
-
198
- #### 1. System Preparation
199
-
200
- To achieve the best performance, we recommend using GPUs with Ampere or Hopper architecture, which support optimized kernels.
201
-
202
- Ensure your system meets the following requirements:
203
-
204
- - **CUDA Version**: 12.1 or 12.3
205
- - **Python Version**: >=3.9 and <=3.12
206
-
207
- **VRAM Requirements:**
208
-
209
- - For processing 1 million-token sequences:
210
- - **Qwen2.5-7B-Instruct-1M**: At least 120GB VRAM (total across GPUs).
211
- - **Qwen2.5-14B-Instruct-1M**: At least 320GB VRAM (total across GPUs).
212
-
213
- If your GPUs do not have sufficient VRAM, you can still use Qwen2.5-1M for shorter tasks.
214
-
215
- #### 2. Install Dependencies
216
-
217
- For now, you need to clone the vLLM repository from our custom branch and install it manually. We are working on getting our branch merged into the main vLLM project.
218
-
219
- ```bash
220
- git clone -b dev/dual-chunk-attn [email protected]:QwenLM/vllm.git
221
- cd vllm
222
- pip install -e . -v
223
- ```
224
-
225
-
226
- #### 3. Launch vLLM
227
-
228
- vLLM supports offline inference or launch an openai-like server.
229
-
230
- **Example of Offline Inference**
231
-
232
- ```python
233
- from transformers import AutoTokenizer
234
- from vllm import LLM, SamplingParams
235
-
236
- # Initialize the tokenizer
237
- tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen2.5-7B-Instruct-1M")
238
-
239
- # Pass the default decoding hyperparameters of Qwen2.5-7B-Instruct
240
- # max_tokens is for the maximum length for generation.
241
- sampling_params = SamplingParams(temperature=0.7, top_p=0.8, repetition_penalty=1.05, max_tokens=512)
242
-
243
- # Input the model name or path. See below for parameter explanation (after the example of openai-like server).
244
- llm = LLM(model="Qwen/Qwen2.5-7B-Instruct-1M",
245
- tensor_parallel_size=4,
246
- max_model_len=1010000,
247
- enable_chunked_prefill=True,
248
- max_num_batched_tokens=131072,
249
- enforce_eager=True,
250
- # quantization="fp8", # Enabling FP8 quantization for model weights can reduce memory usage.
251
- )
252
-
253
- # Prepare your prompts
254
- prompt = "Tell me something about large language models."
255
- messages = [
256
- {"role": "system", "content": "You are Qwen, created by Alibaba Cloud. You are a helpful assistant."},
257
- {"role": "user", "content": prompt}
258
- ]
259
- text = tokenizer.apply_chat_template(
260
- messages,
261
- tokenize=False,
262
- add_generation_prompt=True
263
- )
264
-
265
- # generate outputs
266
- outputs = llm.generate([text], sampling_params)
267
-
268
- # Print the outputs.
269
- for output in outputs:
270
- prompt = output.prompt
271
- generated_text = output.outputs[0].text
272
- print(f"Prompt: {prompt!r}, Generated text: {generated_text!r}")
273
- ```
274
-
275
- **Example of Openai-like Server**
276
-
277
- ```bash
278
- vllm serve Qwen/Qwen2.5-7B-Instruct-1M \
279
- --tensor-parallel-size 4 \
280
- --max-model-len 1010000 \
281
- --enable-chunked-prefill --max-num-batched-tokens 131072 \
282
- --enforce-eager \
283
- --max-num-seqs 1
284
-
285
- # --quantization fp8 # Enabling FP8 quantization for model weights can reduce memory usage.
286
- ```
287
-
288
- Then you can use curl or python to interact with the deployed model.
289
-
290
- **Parameter Explanations:**
291
-
292
- - **`--tensor-parallel-size`**
293
- - Set to the number of GPUs you are using. Max 4 GPUs for the 7B model, and 8 GPUs for the 14B model.
294
-
295
- - **`--max-model-len`**
296
- - Defines the maximum input sequence length. Reduce this value if you encounter Out of Memory issues.
297
-
298
- - **`--max-num-batched-tokens`**
299
- - Sets the chunk size in Chunked Prefill. A smaller value reduces activation memory usage but may slow down inference.
300
- - Recommend 131072 for optimal performance.
301
-
302
- - **`--max-num-seqs`**
303
- - Limits concurrent sequences processed.
304
-
305
- You can also refer to our [Documentation](https://qwen.readthedocs.io/en/latest/deployment/vllm.html) for usage of vLLM.
306
-
307
- #### Troubleshooting:
308
-
309
- 1. Encountering the error: "The model's max sequence length (xxxxx) is larger than the maximum number of tokens that can be stored in the KV cache."
310
-
311
- The VRAM reserved for the KV cache is insufficient. Consider reducing the ``max_model_len`` or increasing the ``tensor_parallel_size``. Alternatively, you can reduce ``max_num_batched_tokens``, although this may significantly slow down inference.
312
-
313
- 2. Encountering the error: "torch.OutOfMemoryError: CUDA out of memory."
314
-
315
- The VRAM reserved for activation weights is insufficient. You can try setting ``gpu_memory_utilization`` to 0.85 or lower, but be aware that this might reduce the VRAM available for the KV cache.
316
-
317
- 3. Encountering the error: "Input prompt (xxxxx tokens) + lookahead slots (0) is too long and exceeds the capacity of the block manager."
318
-
319
- The input is too lengthy. Consider using a shorter sequence or increasing the ``max_model_len``.
320
-
321
- ## Evaluation & Performance
322
-
323
- Detailed evaluation results are reported in this [📑 blog](https://qwenlm.github.io/blog/qwen2.5-1m/) and our [technical report](https://arxiv.org/abs/2501.15383).
324
-
325
- ## Citation
326
-
327
- If you find our work helpful, feel free to give us a cite.
328
-
329
- ```
330
- @misc{qwen2.5-1m,
331
- title = {Qwen2.5-1M: Deploy Your Own Qwen with Context Length up to 1M Tokens},
332
- url = {https://qwenlm.github.io/blog/qwen2.5-1m/},
333
- author = {Qwen Team},
334
- month = {January},
335
- year = {2025}
336
- }
337
-
338
- @article{qwen2.5,
339
- title={Qwen2.5-1M Technical Report},
340
- author={An Yang and Bowen Yu and Chengyuan Li and Dayiheng Liu and Fei Huang and Haoyan Huang and Jiandong Jiang and Jianhong Tu and Jianwei Zhang and Jingren Zhou and Junyang Lin and Kai Dang and Kexin Yang and Le Yu and Mei Li and Minmin Sun and Qin Zhu and Rui Men and Tao He and Weijia Xu and Wenbiao Yin and Wenyuan Yu and Xiafei Qiu and Xingzhang Ren and Xinlong Yang and Yong Li and Zhiying Xu and Zipeng Zhang},
341
- journal={arXiv preprint arXiv:2501.15383},
342
- year={2025}
343
- }
 
 
 
 
 
 
 
 
 
 
 
 
344
  ```
 
1
+ ---
2
+ license: apache-2.0
3
+ pipeline_tag: text-generation
4
+ language:
5
+ - zho
6
+ - eng
7
+ - fra
8
+ - spa
9
+ - por
10
+ - deu
11
+ - ita
12
+ - rus
13
+ - jpn
14
+ - kor
15
+ - vie
16
+ - tha
17
+ - ara
18
+ license_link: LICENSE
19
+ base_model: Qwen/Qwen2.5-7B
20
+ quantized_by: bartowski
21
+ tags:
22
+ - llamafile
23
+ - chat
24
+ ---
25
+
26
+ # Qwen 2.5 Instruct 7B - llamafile
27
+
28
+ - Model creator: [Qwen](https://huggingface.co/Qwen/)
29
+ - Original model: [Qwen/Qwen2.5-7B-Instruct-1M](https://huggingface.co/Qwen/Qwen2.5-7B-Instruct-1M/)
30
+
31
+ Mozilla packaged the Qwen 2.5 models into executable weights that we
32
+ call [llamafiles](https://github.com/Mozilla-Ocho/llamafile). This gives
33
+ you the easiest fastest way to use the model on Linux, MacOS, Windows,
34
+ FreeBSD, OpenBSD and NetBSD systems you control on both AMD64 and ARM64.
35
+
36
+ *Software Last Updated: 2025-03-31*
37
+
38
+ *Llamafile Version: 0.9.2*
39
+
40
+ ## Quickstart
41
+
42
+ To get started, you need both the Qwen 2.5 weights, and the llamafile
43
+ software. Both of them are included in a single file, which can be
44
+ downloaded and run as follows:
45
+
46
+ ```
47
+ wget https://huggingface.co/Mozilla/Qwen2.5-7B-Instruct-1M-llamafile/resolve/main/Qwen2.5-7B-Instruct-1M-Q6_K.llamafile
48
+ chmod +x Qwen2.5-7B-Instruct-1M-Q6_K.llamafile
49
+ ./Qwen2.5-7B-Instruct-1M-Q6_K.llamafile
50
+ ```
51
+
52
+ The default mode of operation for these llamafiles is our new command
53
+ line chatbot interface.
54
+
55
+ ## Usage
56
+
57
+ You can use triple quotes to ask questions on multiple lines. You can
58
+ pass commands like `/stats` and `/context` to see runtime status
59
+ information. You can change the system prompt by passing the `-p "new
60
+ system prompt"` flag. You can press CTRL-C to interrupt the model.
61
+ Finally CTRL-D may be used to exit.
62
+
63
+ If you prefer to use a web GUI, then a `--server` mode is provided, that
64
+ will open a tab with a chatbot and completion interface in your browser.
65
+ For additional help on how it may be used, pass the `--help` flag. The
66
+ server also has an OpenAI API compatible completions endpoint that can
67
+ be accessed via Python using the `openai` pip package.
68
+
69
+ ```
70
+ ./Qwen2.5-7B-Instruct-1M-Q6_K.llamafile --server
71
+ ```
72
+
73
+ An advanced CLI mode is provided that's useful for shell scripting. You
74
+ can use it by passing the `--cli` flag. For additional help on how it
75
+ may be used, pass the `--help` flag.
76
+
77
+ ```
78
+ ./Qwen2.5-7B-Instruct-1M-Q6_K.llamafile --cli -p 'four score and seven' --log-disable
79
+ ```
80
+
81
+ ## Troubleshooting
82
+
83
+ Having **trouble?** See the ["Gotchas"
84
+ section](https://github.com/mozilla-ocho/llamafile/?tab=readme-ov-file#gotchas-and-troubleshooting)
85
+ of the README.
86
+
87
+ On Linux, the way to avoid run-detector errors is to install the APE
88
+ interpreter.
89
+
90
+ ```sh
91
+ sudo wget -O /usr/bin/ape https://cosmo.zip/pub/cosmos/bin/ape-$(uname -m).elf
92
+ sudo chmod +x /usr/bin/ape
93
+ sudo sh -c "echo ':APE:M::MZqFpD::/usr/bin/ape:' >/proc/sys/fs/binfmt_misc/register"
94
+ sudo sh -c "echo ':APE-jart:M::jartsr::/usr/bin/ape:' >/proc/sys/fs/binfmt_misc/register"
95
+ ```
96
+
97
+ On Windows there's a 4GB limit on executable sizes.
98
+
99
+ ## Context Window
100
+
101
+ This model has a max context window size of 128k tokens. By default, a
102
+ context window size of 8192 tokens is used. You can ask llamafile
103
+ to use the maximum context size by passing the `-c 0` flag. That's big
104
+ enough for a small book. If you want to be able to have a conversation
105
+ with your book, you can use the `-f book.txt` flag.
106
+
107
+ ## GPU Acceleration
108
+
109
+ On GPUs with sufficient RAM, the `-ngl 999` flag may be passed to use
110
+ the system's NVIDIA or AMD GPU(s). On Windows, only the graphics card
111
+ driver needs to be installed if you own an NVIDIA GPU. On Windows, if
112
+ you have an AMD GPU, you should install the ROCm SDK v6.1 and then pass
113
+ the flags `--recompile --gpu amd` the first time you run your llamafile.
114
+
115
+ On NVIDIA GPUs, by default, the prebuilt tinyBLAS library is used to
116
+ perform matrix multiplications. This is open source software, but it
117
+ doesn't go as fast as closed source cuBLAS. If you have the CUDA SDK
118
+ installed on your system, then you can pass the `--recompile` flag to
119
+ build a GGML CUDA library just for your system that uses cuBLAS. This
120
+ ensures you get maximum performance.
121
+
122
+ For further information, please see the [llamafile
123
+ README](https://github.com/mozilla-ocho/llamafile/).
124
+
125
+ ## About llamafile
126
+
127
+ llamafile is a new format introduced by Mozilla on Nov 20th 2023. It
128
+ uses Cosmopolitan Libc to turn LLM weights into runnable llama.cpp
129
+ binaries that run on the stock installs of six OSes for both ARM64 and
130
+ AMD64.
131
+
132
+ ---
133
+
134
+ # Qwen2.5-7B-Instruct-1M
135
+ <a href="https://chat.qwenlm.ai/" target="_blank" style="margin: 2px;">
136
+ <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;"/>
137
+ </a>
138
+
139
+ ## Introduction
140
+
141
+ Qwen2.5-1M is the long-context version of the Qwen2.5 series models, supporting a context length of up to 1M tokens. Compared to the Qwen2.5 128K version, Qwen2.5-1M demonstrates significantly improved performance in handling long-context tasks while maintaining its capability in short tasks.
142
+
143
+ The model has the following features:
144
+ - Type: Causal Language Models
145
+ - Training Stage: Pretraining & Post-training
146
+ - Architecture: transformers with RoPE, SwiGLU, RMSNorm, and Attention QKV bias
147
+ - Number of Parameters: 7.61B
148
+ - Number of Paramaters (Non-Embedding): 6.53B
149
+ - Number of Layers: 28
150
+ - Number of Attention Heads (GQA): 28 for Q and 4 for KV
151
+ - Context Length: Full 1,010,000 tokens and generation 8192 tokens
152
+ - We recommend deploying with our custom vLLM, which introduces sparse attention and length extrapolation methods to ensure efficiency and accuracy for long-context tasks. For specific guidance, refer to [this section](#processing-ultra-long-texts).
153
+ - You can also use the previous framework that supports Qwen2.5 for inference, but accuracy degradation may occur for sequences exceeding 262,144 tokens.
154
+
155
+ For more details, please refer to our [blog](https://qwenlm.github.io/blog/qwen2.5-1m/), [GitHub](https://github.com/QwenLM/Qwen2.5), [Technical Report](https://huggingface.co/papers/2501.15383), and [Documentation](https://qwen.readthedocs.io/en/latest/).
156
+ ## Requirements
157
+
158
+ The code of Qwen2.5 has been in the latest Hugging face `transformers` and we advise you to use the latest version of `transformers`.
159
+
160
+ With `transformers<4.37.0`, you will encounter the following error:
161
+ ```
162
+ KeyError: 'qwen2'
163
+ ```
164
+
165
+ ## Quickstart
166
+
167
+ Here provides a code snippet with `apply_chat_template` to show you how to load the tokenizer and model and how to generate contents.
168
+
169
+ ```python
170
+ from transformers import AutoModelForCausalLM, AutoTokenizer
171
+
172
+ model_name = "Qwen/Qwen2.5-7B-Instruct-1M"
173
+
174
+ model = AutoModelForCausalLM.from_pretrained(
175
+ model_name,
176
+ torch_dtype="auto",
177
+ device_map="auto"
178
+ )
179
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
180
+
181
+ prompt = "Give me a short introduction to large language model."
182
+ messages = [
183
+ {"role": "system", "content": "You are Qwen, created by Alibaba Cloud. You are a helpful assistant."},
184
+ {"role": "user", "content": prompt}
185
+ ]
186
+ text = tokenizer.apply_chat_template(
187
+ messages,
188
+ tokenize=False,
189
+ add_generation_prompt=True
190
+ )
191
+ model_inputs = tokenizer([text], return_tensors="pt").to(model.device)
192
+
193
+ generated_ids = model.generate(
194
+ **model_inputs,
195
+ max_new_tokens=512
196
+ )
197
+ generated_ids = [
198
+ output_ids[len(input_ids):] for input_ids, output_ids in zip(model_inputs.input_ids, generated_ids)
199
+ ]
200
+
201
+ response = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]
202
+ ```
203
+
204
+ ### Processing Ultra Long Texts
205
+
206
+ To enhance processing accuracy and efficiency for long sequences, we have developed an advanced inference framework based on vLLM, incorporating sparse attention and length extrapolation. This approach significantly improves model generation performance for sequences exceeding 256K tokens and achieves a 3 to 7 times speedup for sequences up to 1M tokens.
207
+
208
+ Here we provide step-by-step instructions for deploying the Qwen2.5-1M models with our framework.
209
+
210
+ #### 1. System Preparation
211
+
212
+ To achieve the best performance, we recommend using GPUs with Ampere or Hopper architecture, which support optimized kernels.
213
+
214
+ Ensure your system meets the following requirements:
215
+
216
+ - **CUDA Version**: 12.1 or 12.3
217
+ - **Python Version**: >=3.9 and <=3.12
218
+
219
+ **VRAM Requirements:**
220
+
221
+ - For processing 1 million-token sequences:
222
+ - **Qwen2.5-7B-Instruct-1M**: At least 120GB VRAM (total across GPUs).
223
+ - **Qwen2.5-14B-Instruct-1M**: At least 320GB VRAM (total across GPUs).
224
+
225
+ If your GPUs do not have sufficient VRAM, you can still use Qwen2.5-1M for shorter tasks.
226
+
227
+ #### 2. Install Dependencies
228
+
229
+ For now, you need to clone the vLLM repository from our custom branch and install it manually. We are working on getting our branch merged into the main vLLM project.
230
+
231
+ ```bash
232
+ git clone -b dev/dual-chunk-attn [email protected]:QwenLM/vllm.git
233
+ cd vllm
234
+ pip install -e . -v
235
+ ```
236
+
237
+
238
+ #### 3. Launch vLLM
239
+
240
+ vLLM supports offline inference or launch an openai-like server.
241
+
242
+ **Example of Offline Inference**
243
+
244
+ ```python
245
+ from transformers import AutoTokenizer
246
+ from vllm import LLM, SamplingParams
247
+
248
+ # Initialize the tokenizer
249
+ tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen2.5-7B-Instruct-1M")
250
+
251
+ # Pass the default decoding hyperparameters of Qwen2.5-7B-Instruct
252
+ # max_tokens is for the maximum length for generation.
253
+ sampling_params = SamplingParams(temperature=0.7, top_p=0.8, repetition_penalty=1.05, max_tokens=512)
254
+
255
+ # Input the model name or path. See below for parameter explanation (after the example of openai-like server).
256
+ llm = LLM(model="Qwen/Qwen2.5-7B-Instruct-1M",
257
+ tensor_parallel_size=4,
258
+ max_model_len=1010000,
259
+ enable_chunked_prefill=True,
260
+ max_num_batched_tokens=131072,
261
+ enforce_eager=True,
262
+ # quantization="fp8", # Enabling FP8 quantization for model weights can reduce memory usage.
263
+ )
264
+
265
+ # Prepare your prompts
266
+ prompt = "Tell me something about large language models."
267
+ messages = [
268
+ {"role": "system", "content": "You are Qwen, created by Alibaba Cloud. You are a helpful assistant."},
269
+ {"role": "user", "content": prompt}
270
+ ]
271
+ text = tokenizer.apply_chat_template(
272
+ messages,
273
+ tokenize=False,
274
+ add_generation_prompt=True
275
+ )
276
+
277
+ # generate outputs
278
+ outputs = llm.generate([text], sampling_params)
279
+
280
+ # Print the outputs.
281
+ for output in outputs:
282
+ prompt = output.prompt
283
+ generated_text = output.outputs[0].text
284
+ print(f"Prompt: {prompt!r}, Generated text: {generated_text!r}")
285
+ ```
286
+
287
+ **Example of Openai-like Server**
288
+
289
+ ```bash
290
+ vllm serve Qwen/Qwen2.5-7B-Instruct-1M \
291
+ --tensor-parallel-size 4 \
292
+ --max-model-len 1010000 \
293
+ --enable-chunked-prefill --max-num-batched-tokens 131072 \
294
+ --enforce-eager \
295
+ --max-num-seqs 1
296
+
297
+ # --quantization fp8 # Enabling FP8 quantization for model weights can reduce memory usage.
298
+ ```
299
+
300
+ Then you can use curl or python to interact with the deployed model.
301
+
302
+ **Parameter Explanations:**
303
+
304
+ - **`--tensor-parallel-size`**
305
+ - Set to the number of GPUs you are using. Max 4 GPUs for the 7B model, and 8 GPUs for the 14B model.
306
+
307
+ - **`--max-model-len`**
308
+ - Defines the maximum input sequence length. Reduce this value if you encounter Out of Memory issues.
309
+
310
+ - **`--max-num-batched-tokens`**
311
+ - Sets the chunk size in Chunked Prefill. A smaller value reduces activation memory usage but may slow down inference.
312
+ - Recommend 131072 for optimal performance.
313
+
314
+ - **`--max-num-seqs`**
315
+ - Limits concurrent sequences processed.
316
+
317
+ You can also refer to our [Documentation](https://qwen.readthedocs.io/en/latest/deployment/vllm.html) for usage of vLLM.
318
+
319
+ #### Troubleshooting:
320
+
321
+ 1. Encountering the error: "The model's max sequence length (xxxxx) is larger than the maximum number of tokens that can be stored in the KV cache."
322
+
323
+ The VRAM reserved for the KV cache is insufficient. Consider reducing the ``max_model_len`` or increasing the ``tensor_parallel_size``. Alternatively, you can reduce ``max_num_batched_tokens``, although this may significantly slow down inference.
324
+
325
+ 2. Encountering the error: "torch.OutOfMemoryError: CUDA out of memory."
326
+
327
+ The VRAM reserved for activation weights is insufficient. You can try setting ``gpu_memory_utilization`` to 0.85 or lower, but be aware that this might reduce the VRAM available for the KV cache.
328
+
329
+ 3. Encountering the error: "Input prompt (xxxxx tokens) + lookahead slots (0) is too long and exceeds the capacity of the block manager."
330
+
331
+ The input is too lengthy. Consider using a shorter sequence or increasing the ``max_model_len``.
332
+
333
+ ## Evaluation & Performance
334
+
335
+ Detailed evaluation results are reported in this [📑 blog](https://qwenlm.github.io/blog/qwen2.5-1m/) and our [technical report](https://arxiv.org/abs/2501.15383).
336
+
337
+ ## Citation
338
+
339
+ If you find our work helpful, feel free to give us a cite.
340
+
341
+ ```
342
+ @misc{qwen2.5-1m,
343
+ title = {Qwen2.5-1M: Deploy Your Own Qwen with Context Length up to 1M Tokens},
344
+ url = {https://qwenlm.github.io/blog/qwen2.5-1m/},
345
+ author = {Qwen Team},
346
+ month = {January},
347
+ year = {2025}
348
+ }
349
+
350
+ @article{qwen2.5,
351
+ title={Qwen2.5-1M Technical Report},
352
+ author={An Yang and Bowen Yu and Chengyuan Li and Dayiheng Liu and Fei Huang and Haoyan Huang and Jiandong Jiang and Jianhong Tu and Jianwei Zhang and Jingren Zhou and Junyang Lin and Kai Dang and Kexin Yang and Le Yu and Mei Li and Minmin Sun and Qin Zhu and Rui Men and Tao He and Weijia Xu and Wenbiao Yin and Wenyuan Yu and Xiafei Qiu and Xingzhang Ren and Xinlong Yang and Yong Li and Zhiying Xu and Zipeng Zhang},
353
+ journal={arXiv preprint arXiv:2501.15383},
354
+ year={2025}
355
+ }
356
  ```