Safetensors
qwen3
unsloth
de-francophones commited on
Commit
ff8ff0a
·
verified ·
1 Parent(s): 57d0924

Add languages tag

Browse files
Files changed (1) hide show
  1. README.md +462 -343
README.md CHANGED
@@ -1,344 +1,463 @@
1
- ---
2
- tags:
3
- - unsloth
4
- base_model:
5
- - Qwen/Qwen3-14B
6
- license: apache-2.0
7
- ---
8
- # Qwen3-14B
9
-
10
- ## Qwen3 Highlights
11
-
12
- Qwen3 is the latest generation of large language models in Qwen series, offering a comprehensive suite of dense and mixture-of-experts (MoE) models. Built upon extensive training, Qwen3 delivers groundbreaking advancements in reasoning, instruction-following, agent capabilities, and multilingual support, with the following key features:
13
-
14
- - **Uniquely support of seamless switching between thinking mode** (for complex logical reasoning, math, and coding) and **non-thinking mode** (for efficient, general-purpose dialogue) **within single model**, ensuring optimal performance across various scenarios.
15
- - **Significantly enhancement in its reasoning capabilities**, surpassing previous QwQ (in thinking mode) and Qwen2.5 instruct models (in non-thinking mode) on mathematics, code generation, and commonsense logical reasoning.
16
- - **Superior human preference alignment**, excelling in creative writing, role-playing, multi-turn dialogues, and instruction following, to deliver a more natural, engaging, and immersive conversational experience.
17
- - **Expertise in agent capabilities**, enabling precise integration with external tools in both thinking and unthinking modes and achieving leading performance among open-source models in complex agent-based tasks.
18
- - **Support of 100+ languages and dialects** with strong capabilities for **multilingual instruction following** and **translation**.
19
-
20
- ## Model Overview
21
-
22
- **Qwen3-14B** has the following features:
23
- - Type: Causal Language Models
24
- - Training Stage: Pretraining & Post-training
25
- - Number of Parameters: 14.8B
26
- - Number of Paramaters (Non-Embedding): 13.2B
27
- - Number of Layers: 40
28
- - Number of Attention Heads (GQA): 40 for Q and 8 for KV
29
- - Context Length: 32,768 natively and [131,072 tokens with YaRN](#processing-long-texts).
30
-
31
- For more details, including benchmark evaluation, hardware requirements, and inference performance, please refer to our [blog](https://qwenlm.github.io/blog/qwen3/), [GitHub](https://github.com/QwenLM/Qwen3), and [Documentation](https://qwen.readthedocs.io/en/latest/).
32
-
33
- ## Quickstart
34
-
35
- The code of Qwen3 has been in the latest Hugging Face `transformers` and we advise you to use the latest version of `transformers`.
36
-
37
- With `transformers<4.51.0`, you will encounter the following error:
38
- ```
39
- KeyError: 'qwen3'
40
- ```
41
-
42
- The following contains a code snippet illustrating how to use the model generate content based on given inputs.
43
- ```python
44
- from transformers import AutoModelForCausalLM, AutoTokenizer
45
-
46
- model_name = "Qwen/Qwen3-14B"
47
-
48
- # load the tokenizer and the model
49
- tokenizer = AutoTokenizer.from_pretrained(model_name)
50
- model = AutoModelForCausalLM.from_pretrained(
51
- model_name,
52
- torch_dtype="auto",
53
- device_map="auto"
54
- )
55
-
56
- # prepare the model input
57
- prompt = "Give me a short introduction to large language model."
58
- messages = [
59
- {"role": "user", "content": prompt}
60
- ]
61
- text = tokenizer.apply_chat_template(
62
- messages,
63
- tokenize=False,
64
- add_generation_prompt=True,
65
- enable_thinking=True # Switches between thinking and non-thinking modes. Default is True.
66
- )
67
- model_inputs = tokenizer([text], return_tensors="pt").to(model.device)
68
-
69
- # conduct text completion
70
- generated_ids = model.generate(
71
- **model_inputs,
72
- max_new_tokens=32768
73
- )
74
- output_ids = generated_ids[0][len(model_inputs.input_ids[0]):].tolist()
75
-
76
- # parsing thinking content
77
- try:
78
- # rindex finding 151668 (</think>)
79
- index = len(output_ids) - output_ids[::-1].index(151668)
80
- except ValueError:
81
- index = 0
82
-
83
- thinking_content = tokenizer.decode(output_ids[:index], skip_special_tokens=True).strip("\n")
84
- content = tokenizer.decode(output_ids[index:], skip_special_tokens=True).strip("\n")
85
-
86
- print("thinking content:", thinking_content)
87
- print("content:", content)
88
- ```
89
-
90
- For deployment, you can use `vllm>=0.8.5` or `sglang>=0.4.5.post2` to create an OpenAI-compatible API endpoint:
91
- - vLLM:
92
- ```shell
93
- vllm serve Qwen/Qwen3-14B --enable-reasoning --reasoning-parser deepseek_r1
94
- ```
95
- - SGLang:
96
- ```shell
97
- python -m sglang.launch_server --model-path Qwen/Qwen3-14B --reasoning-parser deepseek-r1
98
- ```
99
-
100
- ## Switching Between Thinking and Non-Thinking Mode
101
-
102
- > [!TIP]
103
- > The `enable_thinking` switch is also available in APIs created by vLLM and SGLang.
104
- > Please refer to [our documentation](https://qwen.readthedocs.io/) for more details.
105
-
106
- ### `enable_thinking=True`
107
-
108
- By default, Qwen3 has thinking capabilities enabled, similar to QwQ-32B. This means the model will use its reasoning abilities to enhance the quality of generated responses. For example, when explicitly setting `enable_thinking=True` or leaving it as the default value in `tokenizer.apply_chat_template`, the model will engage its thinking mode.
109
-
110
- ```python
111
- text = tokenizer.apply_chat_template(
112
- messages,
113
- tokenize=False,
114
- add_generation_prompt=True,
115
- enable_thinking=True # True is the default value for enable_thinking
116
- )
117
- ```
118
-
119
- In this mode, the model will generate think content wrapped in a `<think>...</think>` block, followed by the final response.
120
-
121
- > [!NOTE]
122
- > For thinking mode, use `Temperature=0.6`, `TopP=0.95`, `TopK=20`, and `MinP=0` (the default setting in `generation_config.json`). **DO NOT use greedy decoding**, as it can lead to performance degradation and endless repetitions. For more detailed guidance, please refer to the [Best Practices](#best-practices) section.
123
-
124
-
125
- ### `enable_thinking=False`
126
-
127
- We provide a hard switch to strictly disable the model's thinking behavior, aligning its functionality with the previous Qwen2.5-Instruct models. This mode is particularly useful in scenarios where disabling thinking is essential for enhancing efficiency.
128
-
129
- ```python
130
- text = tokenizer.apply_chat_template(
131
- messages,
132
- tokenize=False,
133
- add_generation_prompt=True,
134
- enable_thinking=False # Setting enable_thinking=False disables thinking mode
135
- )
136
- ```
137
-
138
- In this mode, the model will not generate any think content and will not include a `<think>...</think>` block.
139
-
140
- > [!NOTE]
141
- > For non-thinking mode, we suggest using `Temperature=0.7`, `TopP=0.8`, `TopK=20`, and `MinP=0`. For more detailed guidance, please refer to the [Best Practices](#best-practices) section.
142
-
143
- ### Advanced Usage: Switching Between Thinking and Non-Thinking Modes via User Input
144
-
145
- We provide a soft switch mechanism that allows users to dynamically control the model's behavior when `enable_thinking=True`. Specifically, you can add `/think` and `/no_think` to user prompts or system messages to switch the model's thinking mode from turn to turn. The model will follow the most recent instruction in multi-turn conversations.
146
-
147
- Here is an example of a multi-turn conversation:
148
-
149
- ```python
150
- from transformers import AutoModelForCausalLM, AutoTokenizer
151
-
152
- class QwenChatbot:
153
- def __init__(self, model_name="Qwen/Qwen3-14B"):
154
- self.tokenizer = AutoTokenizer.from_pretrained(model_name)
155
- self.model = AutoModelForCausalLM.from_pretrained(model_name)
156
- self.history = []
157
-
158
- def generate_response(self, user_input):
159
- messages = self.history + [{"role": "user", "content": user_input}]
160
-
161
- text = self.tokenizer.apply_chat_template(
162
- messages,
163
- tokenize=False,
164
- add_generation_prompt=True
165
- )
166
-
167
- inputs = self.tokenizer(text, return_tensors="pt")
168
- response_ids = self.model.generate(**inputs, max_new_tokens=32768)[0][len(inputs.input_ids[0]):].tolist()
169
- response = self.tokenizer.decode(response_ids, skip_special_tokens=True)
170
-
171
- # Update history
172
- self.history.append({"role": "user", "content": user_input})
173
- self.history.append({"role": "assistant", "content": response})
174
-
175
- return response
176
-
177
- # Example Usage
178
- if __name__ == "__main__":
179
- chatbot = QwenChatbot()
180
-
181
- # First input (without /think or /no_think tags, thinking mode is enabled by default)
182
- user_input_1 = "How many r's in strawberries?"
183
- print(f"User: {user_input_1}")
184
- response_1 = chatbot.generate_response(user_input_1)
185
- print(f"Bot: {response_1}")
186
- print("----------------------")
187
-
188
- # Second input with /no_think
189
- user_input_2 = "Then, how many r's in blueberries? /no_think"
190
- print(f"User: {user_input_2}")
191
- response_2 = chatbot.generate_response(user_input_2)
192
- print(f"Bot: {response_2}")
193
- print("----------------------")
194
-
195
- # Third input with /think
196
- user_input_3 = "Really? /think"
197
- print(f"User: {user_input_3}")
198
- response_3 = chatbot.generate_response(user_input_3)
199
- print(f"Bot: {response_3}")
200
- ```
201
-
202
- > **Note**
203
- > For API compatibility, when `enable_thinking=True`, regardless of whether the user uses `/think` or `/no_think`, the model will always output a block wrapped in `<think>...</think>`. However, the content inside this block may be empty if thinking is disabled.
204
- > When `enable_thinking=False`, the soft switches are not valid. Regardless of any `/think` or `/no_think` tags input by the user, the model will not generate think content and will not include a `<think>...</think>` block.
205
-
206
- ## Agentic Use
207
-
208
- Qwen3 excels in tool calling capabilities. We recommend using [Qwen-Agent](https://github.com/QwenLM/Qwen-Agent) to make the best use of agentic ability of Qwen3. Qwen-Agent encapsulates tool-calling templates and tool-calling parsers internally, greatly reducing coding complexity.
209
-
210
- To define the available tools, you can use the MCP configuration file, use the integrated tool of Qwen-Agent, or integrate other tools by yourself.
211
- ```python
212
- from qwen_agent.agents import Assistant
213
-
214
- # Define LLM
215
- llm_cfg = {
216
- 'model': 'Qwen3-14B',
217
-
218
- # Use the endpoint provided by Alibaba Model Studio:
219
- # 'model_type': 'qwen_dashscope',
220
- # 'api_key': os.getenv('DASHSCOPE_API_KEY'),
221
-
222
- # Use a custom endpoint compatible with OpenAI API:
223
- 'model_server': 'http://localhost:8000/v1', # api_base
224
- 'api_key': 'EMPTY',
225
-
226
- # Other parameters:
227
- # 'generate_cfg': {
228
- # # Add: When the response content is `<think>this is the thought</think>this is the answer;
229
- # # Do not add: When the response has been separated by reasoning_content and content.
230
- # 'thought_in_content': True,
231
- # },
232
- }
233
-
234
- # Define Tools
235
- tools = [
236
- {'mcpServers': { # You can specify the MCP configuration file
237
- 'time': {
238
- 'command': 'uvx',
239
- 'args': ['mcp-server-time', '--local-timezone=Asia/Shanghai']
240
- },
241
- "fetch": {
242
- "command": "uvx",
243
- "args": ["mcp-server-fetch"]
244
- }
245
- }
246
- },
247
- 'code_interpreter', # Built-in tools
248
- ]
249
-
250
- # Define Agent
251
- bot = Assistant(llm=llm_cfg, function_list=tools)
252
-
253
- # Streaming generation
254
- messages = [{'role': 'user', 'content': 'https://qwenlm.github.io/blog/ Introduce the latest developments of Qwen'}]
255
- for responses in bot.run(messages=messages):
256
- pass
257
- print(responses)
258
- ```
259
-
260
- ## Processing Long Texts
261
-
262
- Qwen3 natively supports context lengths of up to 32,768 tokens. For conversations where the total length (including both input and output) significantly exceeds this limit, we recommend using RoPE scaling techniques to handle long texts effectively. We have validated the model's performance on context lengths of up to 131,072 tokens using the [YaRN](https://arxiv.org/abs/2309.00071) method.
263
-
264
- YaRN is currently supported by several inference frameworks, e.g., `transformers` and `llama.cpp` for local use, `vllm` and `sglang` for deployment. In general, there are two approaches to enabling YaRN for supported frameworks:
265
-
266
- - Modifying the model files:
267
- In the `config.json` file, add the `rope_scaling` fields:
268
- ```json
269
- {
270
- ...,
271
- "rope_scaling": {
272
- "type": "yarn",
273
- "factor": 4.0,
274
- "original_max_position_embeddings": 32768
275
- }
276
- }
277
- ```
278
- For `llama.cpp`, you need to regenerate the GGUF file after the modification.
279
-
280
- - Passing command line arguments:
281
-
282
- For `vllm`, you can use
283
- ```shell
284
- vllm serve ... --rope-scaling '{"type":"yarn","factor":4.0,"original_max_position_embeddings":32768}' --max-model-len 131072
285
- ```
286
-
287
- For `sglang`, you can use
288
- ```shell
289
- python -m sglang.launch_server ... --json-model-override-args '{"rope_scaling":{"type":"yarn","factor":4.0,"original_max_position_embeddings":32768}}'
290
- ```
291
-
292
- For `llama-server` from `llama.cpp`, you can use
293
- ```shell
294
- llama-server ... --rope-scaling yarn --rope-scale 4 --yarn-orig-ctx 32768
295
- ```
296
-
297
- > [!IMPORTANT]
298
- > If you encounter the following warning
299
- > ```
300
- > Unrecognized keys in `rope_scaling` for 'rope_type'='yarn': {'original_max_position_embeddings'}
301
- > ```
302
- > please upgrade `transformers>=4.51.0`.
303
-
304
- > [!NOTE]
305
- > All the notable open-source frameworks implement static YaRN, which means the scaling factor remains constant regardless of input length, **potentially impacting performance on shorter texts.**
306
- > We advise adding the `rope_scaling` configuration only when processing long contexts is required.
307
- > It is also recommended to modify the `factor` as needed. For example, if the typical context length for your application is 65,536 tokens, it would be better to set `factor` as 2.0.
308
-
309
- > [!NOTE]
310
- > The default `max_position_embeddings` in `config.json` is set to 40,960. This allocation includes reserving 32,768 tokens for outputs and 8,192 tokens for typical prompts, which is sufficient for most scenarios involving short text processing. If the average context length does not exceed 32,768 tokens, we do not recommend enabling YaRN in this scenario, as it may potentially degrade model performance.
311
-
312
- > [!TIP]
313
- > The endpoint provided by Alibaba Model Studio supports dynamic YaRN by default and no extra configuration is needed.
314
-
315
- ## Best Practices
316
-
317
- To achieve optimal performance, we recommend the following settings:
318
-
319
- 1. **Sampling Parameters**:
320
- - For thinking mode (`enable_thinking=True`), use `Temperature=0.6`, `TopP=0.95`, `TopK=20`, and `MinP=0`. **DO NOT use greedy decoding**, as it can lead to performance degradation and endless repetitions.
321
- - For non-thinking mode (`enable_thinking=False`), we suggest using `Temperature=0.7`, `TopP=0.8`, `TopK=20`, and `MinP=0`.
322
- - For supported frameworks, you can adjust the `presence_penalty` parameter between 0 and 2 to reduce endless repetitions. However, using a higher value may occasionally result in language mixing and a slight decrease in model performance.
323
-
324
- 2. **Adequate Output Length**: We recommend using an output length of 32,768 tokens for most queries. For benchmarking on highly complex problems, such as those found in math and programming competitions, we suggest setting the max output length to 38,912 tokens. This provides the model with sufficient space to generate detailed and comprehensive responses, thereby enhancing its overall performance.
325
-
326
- 3. **Standardize Output Format**: We recommend using prompts to standardize model outputs when benchmarking.
327
- - **Math Problems**: Include "Please reason step by step, and put your final answer within \boxed{}." in the prompt.
328
- - **Multiple-Choice Questions**: Add the following JSON structure to the prompt to standardize responses: "Please show your choice in the `answer` field with only the choice letter, e.g., `"answer": "C"`."
329
-
330
- 4. **No Thinking Content in History**: In multi-turn conversations, the historical model output should only include the final output part and does not need to include the thinking content. It is implemented in the provided chat template in Jinja2. However, for frameworks that do not directly use the Jinja2 chat template, it is up to the developers to ensure that the best practice is followed.
331
-
332
- ### Citation
333
-
334
- If you find our work helpful, feel free to give us a cite.
335
-
336
- ```
337
- @misc{qwen3,
338
- title = {Qwen3},
339
- url = {https://qwenlm.github.io/blog/qwen3/},
340
- author = {Qwen Team},
341
- month = {April},
342
- year = {2025}
343
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
344
  ```
 
1
+ ---
2
+ tags:
3
+ - unsloth
4
+ base_model:
5
+ - Qwen/Qwen3-14B
6
+ license: apache-2.0
7
+ language:
8
+ - eng
9
+ - fra
10
+ - por
11
+ - deu
12
+ - ron
13
+ - swe
14
+ - dan
15
+ - bul
16
+ - rus
17
+ - ces
18
+ - ell
19
+ - ukr
20
+ - spa
21
+ - nld
22
+ - slk
23
+ - hrv
24
+ - pol
25
+ - lit
26
+ - nob
27
+ - nno
28
+ - fas
29
+ - slv
30
+ - guj
31
+ - lav
32
+ - ita
33
+ - oci
34
+ - nep
35
+ - mar
36
+ - bel
37
+ - srp
38
+ - ltz
39
+ - vec
40
+ - asm
41
+ - cym
42
+ - szl
43
+ - ast
44
+ - hne
45
+ - awa
46
+ - mai
47
+ - bho
48
+ - snd
49
+ - gle
50
+ - fao
51
+ - hin
52
+ - pan
53
+ - ben
54
+ - ori
55
+ - tgk
56
+ - ydd
57
+ - lmo
58
+ - lij
59
+ - scn
60
+ - fur
61
+ - srd
62
+ - glg
63
+ - cat
64
+ - isl
65
+ - als
66
+ - lim
67
+ - prs
68
+ - afr
69
+ - mkd
70
+ - sin
71
+ - urd
72
+ - mag
73
+ - bos
74
+ - hye
75
+ - zho
76
+ - yue
77
+ - mya
78
+ - ara
79
+ - ars
80
+ - apc
81
+ - arz
82
+ - ary
83
+ - acm
84
+ - acq
85
+ - aeb
86
+ - heb
87
+ - mlt
88
+ - ind
89
+ - zsm
90
+ - tgl
91
+ - ceb
92
+ - jav
93
+ - sun
94
+ - min
95
+ - ban
96
+ - bjn
97
+ - pag
98
+ - ilo
99
+ - war
100
+ - tam
101
+ - tel
102
+ - kan
103
+ - mal
104
+ - tur
105
+ - azj
106
+ - uzn
107
+ - kaz
108
+ - bak
109
+ - tat
110
+ - tha
111
+ - lao
112
+ - fin
113
+ - est
114
+ - hun
115
+ - vie
116
+ - khm
117
+ - jpn
118
+ - kor
119
+ - kat
120
+ - eus
121
+ - hat
122
+ - pap
123
+ - kea
124
+ - tpi
125
+ - swa
126
+ ---
127
+ # Qwen3-14B
128
+
129
+ ## Qwen3 Highlights
130
+
131
+ Qwen3 is the latest generation of large language models in Qwen series, offering a comprehensive suite of dense and mixture-of-experts (MoE) models. Built upon extensive training, Qwen3 delivers groundbreaking advancements in reasoning, instruction-following, agent capabilities, and multilingual support, with the following key features:
132
+
133
+ - **Uniquely support of seamless switching between thinking mode** (for complex logical reasoning, math, and coding) and **non-thinking mode** (for efficient, general-purpose dialogue) **within single model**, ensuring optimal performance across various scenarios.
134
+ - **Significantly enhancement in its reasoning capabilities**, surpassing previous QwQ (in thinking mode) and Qwen2.5 instruct models (in non-thinking mode) on mathematics, code generation, and commonsense logical reasoning.
135
+ - **Superior human preference alignment**, excelling in creative writing, role-playing, multi-turn dialogues, and instruction following, to deliver a more natural, engaging, and immersive conversational experience.
136
+ - **Expertise in agent capabilities**, enabling precise integration with external tools in both thinking and unthinking modes and achieving leading performance among open-source models in complex agent-based tasks.
137
+ - **Support of 100+ languages and dialects** with strong capabilities for **multilingual instruction following** and **translation**.
138
+
139
+ ## Model Overview
140
+
141
+ **Qwen3-14B** has the following features:
142
+ - Type: Causal Language Models
143
+ - Training Stage: Pretraining & Post-training
144
+ - Number of Parameters: 14.8B
145
+ - Number of Paramaters (Non-Embedding): 13.2B
146
+ - Number of Layers: 40
147
+ - Number of Attention Heads (GQA): 40 for Q and 8 for KV
148
+ - Context Length: 32,768 natively and [131,072 tokens with YaRN](#processing-long-texts).
149
+
150
+ For more details, including benchmark evaluation, hardware requirements, and inference performance, please refer to our [blog](https://qwenlm.github.io/blog/qwen3/), [GitHub](https://github.com/QwenLM/Qwen3), and [Documentation](https://qwen.readthedocs.io/en/latest/).
151
+
152
+ ## Quickstart
153
+
154
+ The code of Qwen3 has been in the latest Hugging Face `transformers` and we advise you to use the latest version of `transformers`.
155
+
156
+ With `transformers<4.51.0`, you will encounter the following error:
157
+ ```
158
+ KeyError: 'qwen3'
159
+ ```
160
+
161
+ The following contains a code snippet illustrating how to use the model generate content based on given inputs.
162
+ ```python
163
+ from transformers import AutoModelForCausalLM, AutoTokenizer
164
+
165
+ model_name = "Qwen/Qwen3-14B"
166
+
167
+ # load the tokenizer and the model
168
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
169
+ model = AutoModelForCausalLM.from_pretrained(
170
+ model_name,
171
+ torch_dtype="auto",
172
+ device_map="auto"
173
+ )
174
+
175
+ # prepare the model input
176
+ prompt = "Give me a short introduction to large language model."
177
+ messages = [
178
+ {"role": "user", "content": prompt}
179
+ ]
180
+ text = tokenizer.apply_chat_template(
181
+ messages,
182
+ tokenize=False,
183
+ add_generation_prompt=True,
184
+ enable_thinking=True # Switches between thinking and non-thinking modes. Default is True.
185
+ )
186
+ model_inputs = tokenizer([text], return_tensors="pt").to(model.device)
187
+
188
+ # conduct text completion
189
+ generated_ids = model.generate(
190
+ **model_inputs,
191
+ max_new_tokens=32768
192
+ )
193
+ output_ids = generated_ids[0][len(model_inputs.input_ids[0]):].tolist()
194
+
195
+ # parsing thinking content
196
+ try:
197
+ # rindex finding 151668 (</think>)
198
+ index = len(output_ids) - output_ids[::-1].index(151668)
199
+ except ValueError:
200
+ index = 0
201
+
202
+ thinking_content = tokenizer.decode(output_ids[:index], skip_special_tokens=True).strip("\n")
203
+ content = tokenizer.decode(output_ids[index:], skip_special_tokens=True).strip("\n")
204
+
205
+ print("thinking content:", thinking_content)
206
+ print("content:", content)
207
+ ```
208
+
209
+ For deployment, you can use `vllm>=0.8.5` or `sglang>=0.4.5.post2` to create an OpenAI-compatible API endpoint:
210
+ - vLLM:
211
+ ```shell
212
+ vllm serve Qwen/Qwen3-14B --enable-reasoning --reasoning-parser deepseek_r1
213
+ ```
214
+ - SGLang:
215
+ ```shell
216
+ python -m sglang.launch_server --model-path Qwen/Qwen3-14B --reasoning-parser deepseek-r1
217
+ ```
218
+
219
+ ## Switching Between Thinking and Non-Thinking Mode
220
+
221
+ > [!TIP]
222
+ > The `enable_thinking` switch is also available in APIs created by vLLM and SGLang.
223
+ > Please refer to [our documentation](https://qwen.readthedocs.io/) for more details.
224
+
225
+ ### `enable_thinking=True`
226
+
227
+ By default, Qwen3 has thinking capabilities enabled, similar to QwQ-32B. This means the model will use its reasoning abilities to enhance the quality of generated responses. For example, when explicitly setting `enable_thinking=True` or leaving it as the default value in `tokenizer.apply_chat_template`, the model will engage its thinking mode.
228
+
229
+ ```python
230
+ text = tokenizer.apply_chat_template(
231
+ messages,
232
+ tokenize=False,
233
+ add_generation_prompt=True,
234
+ enable_thinking=True # True is the default value for enable_thinking
235
+ )
236
+ ```
237
+
238
+ In this mode, the model will generate think content wrapped in a `<think>...</think>` block, followed by the final response.
239
+
240
+ > [!NOTE]
241
+ > For thinking mode, use `Temperature=0.6`, `TopP=0.95`, `TopK=20`, and `MinP=0` (the default setting in `generation_config.json`). **DO NOT use greedy decoding**, as it can lead to performance degradation and endless repetitions. For more detailed guidance, please refer to the [Best Practices](#best-practices) section.
242
+
243
+
244
+ ### `enable_thinking=False`
245
+
246
+ We provide a hard switch to strictly disable the model's thinking behavior, aligning its functionality with the previous Qwen2.5-Instruct models. This mode is particularly useful in scenarios where disabling thinking is essential for enhancing efficiency.
247
+
248
+ ```python
249
+ text = tokenizer.apply_chat_template(
250
+ messages,
251
+ tokenize=False,
252
+ add_generation_prompt=True,
253
+ enable_thinking=False # Setting enable_thinking=False disables thinking mode
254
+ )
255
+ ```
256
+
257
+ In this mode, the model will not generate any think content and will not include a `<think>...</think>` block.
258
+
259
+ > [!NOTE]
260
+ > For non-thinking mode, we suggest using `Temperature=0.7`, `TopP=0.8`, `TopK=20`, and `MinP=0`. For more detailed guidance, please refer to the [Best Practices](#best-practices) section.
261
+
262
+ ### Advanced Usage: Switching Between Thinking and Non-Thinking Modes via User Input
263
+
264
+ We provide a soft switch mechanism that allows users to dynamically control the model's behavior when `enable_thinking=True`. Specifically, you can add `/think` and `/no_think` to user prompts or system messages to switch the model's thinking mode from turn to turn. The model will follow the most recent instruction in multi-turn conversations.
265
+
266
+ Here is an example of a multi-turn conversation:
267
+
268
+ ```python
269
+ from transformers import AutoModelForCausalLM, AutoTokenizer
270
+
271
+ class QwenChatbot:
272
+ def __init__(self, model_name="Qwen/Qwen3-14B"):
273
+ self.tokenizer = AutoTokenizer.from_pretrained(model_name)
274
+ self.model = AutoModelForCausalLM.from_pretrained(model_name)
275
+ self.history = []
276
+
277
+ def generate_response(self, user_input):
278
+ messages = self.history + [{"role": "user", "content": user_input}]
279
+
280
+ text = self.tokenizer.apply_chat_template(
281
+ messages,
282
+ tokenize=False,
283
+ add_generation_prompt=True
284
+ )
285
+
286
+ inputs = self.tokenizer(text, return_tensors="pt")
287
+ response_ids = self.model.generate(**inputs, max_new_tokens=32768)[0][len(inputs.input_ids[0]):].tolist()
288
+ response = self.tokenizer.decode(response_ids, skip_special_tokens=True)
289
+
290
+ # Update history
291
+ self.history.append({"role": "user", "content": user_input})
292
+ self.history.append({"role": "assistant", "content": response})
293
+
294
+ return response
295
+
296
+ # Example Usage
297
+ if __name__ == "__main__":
298
+ chatbot = QwenChatbot()
299
+
300
+ # First input (without /think or /no_think tags, thinking mode is enabled by default)
301
+ user_input_1 = "How many r's in strawberries?"
302
+ print(f"User: {user_input_1}")
303
+ response_1 = chatbot.generate_response(user_input_1)
304
+ print(f"Bot: {response_1}")
305
+ print("----------------------")
306
+
307
+ # Second input with /no_think
308
+ user_input_2 = "Then, how many r's in blueberries? /no_think"
309
+ print(f"User: {user_input_2}")
310
+ response_2 = chatbot.generate_response(user_input_2)
311
+ print(f"Bot: {response_2}")
312
+ print("----------------------")
313
+
314
+ # Third input with /think
315
+ user_input_3 = "Really? /think"
316
+ print(f"User: {user_input_3}")
317
+ response_3 = chatbot.generate_response(user_input_3)
318
+ print(f"Bot: {response_3}")
319
+ ```
320
+
321
+ > **Note**
322
+ > For API compatibility, when `enable_thinking=True`, regardless of whether the user uses `/think` or `/no_think`, the model will always output a block wrapped in `<think>...</think>`. However, the content inside this block may be empty if thinking is disabled.
323
+ > When `enable_thinking=False`, the soft switches are not valid. Regardless of any `/think` or `/no_think` tags input by the user, the model will not generate think content and will not include a `<think>...</think>` block.
324
+
325
+ ## Agentic Use
326
+
327
+ Qwen3 excels in tool calling capabilities. We recommend using [Qwen-Agent](https://github.com/QwenLM/Qwen-Agent) to make the best use of agentic ability of Qwen3. Qwen-Agent encapsulates tool-calling templates and tool-calling parsers internally, greatly reducing coding complexity.
328
+
329
+ To define the available tools, you can use the MCP configuration file, use the integrated tool of Qwen-Agent, or integrate other tools by yourself.
330
+ ```python
331
+ from qwen_agent.agents import Assistant
332
+
333
+ # Define LLM
334
+ llm_cfg = {
335
+ 'model': 'Qwen3-14B',
336
+
337
+ # Use the endpoint provided by Alibaba Model Studio:
338
+ # 'model_type': 'qwen_dashscope',
339
+ # 'api_key': os.getenv('DASHSCOPE_API_KEY'),
340
+
341
+ # Use a custom endpoint compatible with OpenAI API:
342
+ 'model_server': 'http://localhost:8000/v1', # api_base
343
+ 'api_key': 'EMPTY',
344
+
345
+ # Other parameters:
346
+ # 'generate_cfg': {
347
+ # # Add: When the response content is `<think>this is the thought</think>this is the answer;
348
+ # # Do not add: When the response has been separated by reasoning_content and content.
349
+ # 'thought_in_content': True,
350
+ # },
351
+ }
352
+
353
+ # Define Tools
354
+ tools = [
355
+ {'mcpServers': { # You can specify the MCP configuration file
356
+ 'time': {
357
+ 'command': 'uvx',
358
+ 'args': ['mcp-server-time', '--local-timezone=Asia/Shanghai']
359
+ },
360
+ "fetch": {
361
+ "command": "uvx",
362
+ "args": ["mcp-server-fetch"]
363
+ }
364
+ }
365
+ },
366
+ 'code_interpreter', # Built-in tools
367
+ ]
368
+
369
+ # Define Agent
370
+ bot = Assistant(llm=llm_cfg, function_list=tools)
371
+
372
+ # Streaming generation
373
+ messages = [{'role': 'user', 'content': 'https://qwenlm.github.io/blog/ Introduce the latest developments of Qwen'}]
374
+ for responses in bot.run(messages=messages):
375
+ pass
376
+ print(responses)
377
+ ```
378
+
379
+ ## Processing Long Texts
380
+
381
+ Qwen3 natively supports context lengths of up to 32,768 tokens. For conversations where the total length (including both input and output) significantly exceeds this limit, we recommend using RoPE scaling techniques to handle long texts effectively. We have validated the model's performance on context lengths of up to 131,072 tokens using the [YaRN](https://arxiv.org/abs/2309.00071) method.
382
+
383
+ YaRN is currently supported by several inference frameworks, e.g., `transformers` and `llama.cpp` for local use, `vllm` and `sglang` for deployment. In general, there are two approaches to enabling YaRN for supported frameworks:
384
+
385
+ - Modifying the model files:
386
+ In the `config.json` file, add the `rope_scaling` fields:
387
+ ```json
388
+ {
389
+ ...,
390
+ "rope_scaling": {
391
+ "type": "yarn",
392
+ "factor": 4.0,
393
+ "original_max_position_embeddings": 32768
394
+ }
395
+ }
396
+ ```
397
+ For `llama.cpp`, you need to regenerate the GGUF file after the modification.
398
+
399
+ - Passing command line arguments:
400
+
401
+ For `vllm`, you can use
402
+ ```shell
403
+ vllm serve ... --rope-scaling '{"type":"yarn","factor":4.0,"original_max_position_embeddings":32768}' --max-model-len 131072
404
+ ```
405
+
406
+ For `sglang`, you can use
407
+ ```shell
408
+ python -m sglang.launch_server ... --json-model-override-args '{"rope_scaling":{"type":"yarn","factor":4.0,"original_max_position_embeddings":32768}}'
409
+ ```
410
+
411
+ For `llama-server` from `llama.cpp`, you can use
412
+ ```shell
413
+ llama-server ... --rope-scaling yarn --rope-scale 4 --yarn-orig-ctx 32768
414
+ ```
415
+
416
+ > [!IMPORTANT]
417
+ > If you encounter the following warning
418
+ > ```
419
+ > Unrecognized keys in `rope_scaling` for 'rope_type'='yarn': {'original_max_position_embeddings'}
420
+ > ```
421
+ > please upgrade `transformers>=4.51.0`.
422
+
423
+ > [!NOTE]
424
+ > All the notable open-source frameworks implement static YaRN, which means the scaling factor remains constant regardless of input length, **potentially impacting performance on shorter texts.**
425
+ > We advise adding the `rope_scaling` configuration only when processing long contexts is required.
426
+ > It is also recommended to modify the `factor` as needed. For example, if the typical context length for your application is 65,536 tokens, it would be better to set `factor` as 2.0.
427
+
428
+ > [!NOTE]
429
+ > The default `max_position_embeddings` in `config.json` is set to 40,960. This allocation includes reserving 32,768 tokens for outputs and 8,192 tokens for typical prompts, which is sufficient for most scenarios involving short text processing. If the average context length does not exceed 32,768 tokens, we do not recommend enabling YaRN in this scenario, as it may potentially degrade model performance.
430
+
431
+ > [!TIP]
432
+ > The endpoint provided by Alibaba Model Studio supports dynamic YaRN by default and no extra configuration is needed.
433
+
434
+ ## Best Practices
435
+
436
+ To achieve optimal performance, we recommend the following settings:
437
+
438
+ 1. **Sampling Parameters**:
439
+ - For thinking mode (`enable_thinking=True`), use `Temperature=0.6`, `TopP=0.95`, `TopK=20`, and `MinP=0`. **DO NOT use greedy decoding**, as it can lead to performance degradation and endless repetitions.
440
+ - For non-thinking mode (`enable_thinking=False`), we suggest using `Temperature=0.7`, `TopP=0.8`, `TopK=20`, and `MinP=0`.
441
+ - For supported frameworks, you can adjust the `presence_penalty` parameter between 0 and 2 to reduce endless repetitions. However, using a higher value may occasionally result in language mixing and a slight decrease in model performance.
442
+
443
+ 2. **Adequate Output Length**: We recommend using an output length of 32,768 tokens for most queries. For benchmarking on highly complex problems, such as those found in math and programming competitions, we suggest setting the max output length to 38,912 tokens. This provides the model with sufficient space to generate detailed and comprehensive responses, thereby enhancing its overall performance.
444
+
445
+ 3. **Standardize Output Format**: We recommend using prompts to standardize model outputs when benchmarking.
446
+ - **Math Problems**: Include "Please reason step by step, and put your final answer within \boxed{}." in the prompt.
447
+ - **Multiple-Choice Questions**: Add the following JSON structure to the prompt to standardize responses: "Please show your choice in the `answer` field with only the choice letter, e.g., `"answer": "C"`."
448
+
449
+ 4. **No Thinking Content in History**: In multi-turn conversations, the historical model output should only include the final output part and does not need to include the thinking content. It is implemented in the provided chat template in Jinja2. However, for frameworks that do not directly use the Jinja2 chat template, it is up to the developers to ensure that the best practice is followed.
450
+
451
+ ### Citation
452
+
453
+ If you find our work helpful, feel free to give us a cite.
454
+
455
+ ```
456
+ @misc{qwen3,
457
+ title = {Qwen3},
458
+ url = {https://qwenlm.github.io/blog/qwen3/},
459
+ author = {Qwen Team},
460
+ month = {April},
461
+ year = {2025}
462
+ }
463
  ```