Files changed (1) hide show
  1. README.md +463 -344
README.md CHANGED
@@ -1,345 +1,464 @@
1
- ---
2
- tags:
3
- - unsloth
4
- base_model:
5
- - Qwen/Qwen3-30B-A3B
6
- ---
7
- # Qwen3-30B-A3B
8
-
9
- ## Qwen3 Highlights
10
-
11
- 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:
12
-
13
- - **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.
14
- - **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.
15
- - **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.
16
- - **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.
17
- - **Support of 100+ languages and dialects** with strong capabilities for **multilingual instruction following** and **translation**.
18
-
19
- ## Model Overview
20
-
21
- **Qwen3-30B-A3B** has the following features:
22
- - Type: Causal Language Models
23
- - Training Stage: Pretraining & Post-training
24
- - Number of Parameters: 30.5B in total and 3.3B activated
25
- - Number of Paramaters (Non-Embedding): 29.9B
26
- - Number of Layers: 48
27
- - Number of Attention Heads (GQA): 32 for Q and 4 for KV
28
- - Number of Experts: 128
29
- - Number of Activated Experts: 8
30
- - Context Length: 32,768 natively and [131,072 tokens with YaRN](#processing-long-texts).
31
-
32
- 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/).
33
-
34
- ## Quickstart
35
-
36
- The code of Qwen3-MoE has been in the latest Hugging Face `transformers` and we advise you to use the latest version of `transformers`.
37
-
38
- With `transformers<4.51.0`, you will encounter the following error:
39
- ```
40
- KeyError: 'qwen3_moe'
41
- ```
42
-
43
- The following contains a code snippet illustrating how to use the model generate content based on given inputs.
44
- ```python
45
- from transformers import AutoModelForCausalLM, AutoTokenizer
46
-
47
- model_name = "Qwen/Qwen3-30B-A3B"
48
-
49
- # load the tokenizer and the model
50
- tokenizer = AutoTokenizer.from_pretrained(model_name)
51
- model = AutoModelForCausalLM.from_pretrained(
52
- model_name,
53
- torch_dtype="auto",
54
- device_map="auto"
55
- )
56
-
57
- # prepare the model input
58
- prompt = "Give me a short introduction to large language model."
59
- messages = [
60
- {"role": "user", "content": prompt}
61
- ]
62
- text = tokenizer.apply_chat_template(
63
- messages,
64
- tokenize=False,
65
- add_generation_prompt=True,
66
- enable_thinking=True # Switches between thinking and non-thinking modes. Default is True.
67
- )
68
- model_inputs = tokenizer([text], return_tensors="pt").to(model.device)
69
-
70
- # conduct text completion
71
- generated_ids = model.generate(
72
- **model_inputs,
73
- max_new_tokens=32768
74
- )
75
- output_ids = generated_ids[0][len(model_inputs.input_ids[0]):].tolist()
76
-
77
- # parsing thinking content
78
- try:
79
- # rindex finding 151668 (</think>)
80
- index = len(output_ids) - output_ids[::-1].index(151668)
81
- except ValueError:
82
- index = 0
83
-
84
- thinking_content = tokenizer.decode(output_ids[:index], skip_special_tokens=True).strip("\n")
85
- content = tokenizer.decode(output_ids[index:], skip_special_tokens=True).strip("\n")
86
-
87
- print("thinking content:", thinking_content)
88
- print("content:", content)
89
- ```
90
-
91
- For deployment, you can use `vllm>=0.8.5` or `sglang>=0.4.5.post2` to create an OpenAI-compatible API endpoint:
92
- - vLLM:
93
- ```shell
94
- vllm serve Qwen/Qwen3-30B-A3B --enable-reasoning --reasoning-parser deepseek_r1
95
- ```
96
- - SGLang:
97
- ```shell
98
- python -m sglang.launch_server --model-path Qwen/Qwen3-30B-A3B --reasoning-parser deepseek-r1
99
- ```
100
-
101
- ## Switching Between Thinking and Non-Thinking Mode
102
-
103
- > [!TIP]
104
- > The `enable_thinking` switch is also available in APIs created by vLLM and SGLang.
105
- > Please refer to [our documentation](https://qwen.readthedocs.io/) for more details.
106
-
107
- ### `enable_thinking=True`
108
-
109
- 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.
110
-
111
- ```python
112
- text = tokenizer.apply_chat_template(
113
- messages,
114
- tokenize=False,
115
- add_generation_prompt=True,
116
- enable_thinking=True # True is the default value for enable_thinking
117
- )
118
- ```
119
-
120
- In this mode, the model will generate think content wrapped in a `<think>...</think>` block, followed by the final response.
121
-
122
- > [!NOTE]
123
- > 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.
124
-
125
-
126
- ### `enable_thinking=False`
127
-
128
- 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.
129
-
130
- ```python
131
- text = tokenizer.apply_chat_template(
132
- messages,
133
- tokenize=False,
134
- add_generation_prompt=True,
135
- enable_thinking=False # Setting enable_thinking=False disables thinking mode
136
- )
137
- ```
138
-
139
- In this mode, the model will not generate any think content and will not include a `<think>...</think>` block.
140
-
141
- > [!NOTE]
142
- > 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.
143
-
144
- ### Advanced Usage: Switching Between Thinking and Non-Thinking Modes via User Input
145
-
146
- 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.
147
-
148
- Here is an example of a multi-turn conversation:
149
-
150
- ```python
151
- from transformers import AutoModelForCausalLM, AutoTokenizer
152
-
153
- class QwenChatbot:
154
- def __init__(self, model_name="Qwen/Qwen3-30B-A3B"):
155
- self.tokenizer = AutoTokenizer.from_pretrained(model_name)
156
- self.model = AutoModelForCausalLM.from_pretrained(model_name)
157
- self.history = []
158
-
159
- def generate_response(self, user_input):
160
- messages = self.history + [{"role": "user", "content": user_input}]
161
-
162
- text = self.tokenizer.apply_chat_template(
163
- messages,
164
- tokenize=False,
165
- add_generation_prompt=True
166
- )
167
-
168
- inputs = self.tokenizer(text, return_tensors="pt")
169
- response_ids = self.model.generate(**inputs, max_new_tokens=32768)[0][len(inputs.input_ids[0]):].tolist()
170
- response = self.tokenizer.decode(response_ids, skip_special_tokens=True)
171
-
172
- # Update history
173
- self.history.append({"role": "user", "content": user_input})
174
- self.history.append({"role": "assistant", "content": response})
175
-
176
- return response
177
-
178
- # Example Usage
179
- if __name__ == "__main__":
180
- chatbot = QwenChatbot()
181
-
182
- # First input (without /think or /no_think tags, thinking mode is enabled by default)
183
- user_input_1 = "How many r's in strawberries?"
184
- print(f"User: {user_input_1}")
185
- response_1 = chatbot.generate_response(user_input_1)
186
- print(f"Bot: {response_1}")
187
- print("----------------------")
188
-
189
- # Second input with /no_think
190
- user_input_2 = "Then, how many r's in blueberries? /no_think"
191
- print(f"User: {user_input_2}")
192
- response_2 = chatbot.generate_response(user_input_2)
193
- print(f"Bot: {response_2}")
194
- print("----------------------")
195
-
196
- # Third input with /think
197
- user_input_3 = "Really? /think"
198
- print(f"User: {user_input_3}")
199
- response_3 = chatbot.generate_response(user_input_3)
200
- print(f"Bot: {response_3}")
201
- ```
202
-
203
- > **Note**
204
- > 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.
205
- > 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.
206
-
207
- ## Agentic Use
208
-
209
- 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.
210
-
211
- 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.
212
- ```python
213
- from qwen_agent.agents import Assistant
214
-
215
- # Define LLM
216
- llm_cfg = {
217
- 'model': 'Qwen3-30B-A3B',
218
-
219
- # Use the endpoint provided by Alibaba Model Studio:
220
- # 'model_type': 'qwen_dashscope',
221
- # 'api_key': os.getenv('DASHSCOPE_API_KEY'),
222
-
223
- # Use a custom endpoint compatible with OpenAI API:
224
- 'model_server': 'http://localhost:8000/v1', # api_base
225
- 'api_key': 'EMPTY',
226
-
227
- # Other parameters:
228
- # 'generate_cfg': {
229
- # # Add: When the response content is `<think>this is the thought</think>this is the answer;
230
- # # Do not add: When the response has been separated by reasoning_content and content.
231
- # 'thought_in_content': True,
232
- # },
233
- }
234
-
235
- # Define Tools
236
- tools = [
237
- {'mcpServers': { # You can specify the MCP configuration file
238
- 'time': {
239
- 'command': 'uvx',
240
- 'args': ['mcp-server-time', '--local-timezone=Asia/Shanghai']
241
- },
242
- "fetch": {
243
- "command": "uvx",
244
- "args": ["mcp-server-fetch"]
245
- }
246
- }
247
- },
248
- 'code_interpreter', # Built-in tools
249
- ]
250
-
251
- # Define Agent
252
- bot = Assistant(llm=llm_cfg, function_list=tools)
253
-
254
- # Streaming generation
255
- messages = [{'role': 'user', 'content': 'https://qwenlm.github.io/blog/ Introduce the latest developments of Qwen'}]
256
- for responses in bot.run(messages=messages):
257
- pass
258
- print(responses)
259
- ```
260
-
261
- ## Processing Long Texts
262
-
263
- 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.
264
-
265
- 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:
266
-
267
- - Modifying the model files:
268
- In the `config.json` file, add the `rope_scaling` fields:
269
- ```json
270
- {
271
- ...,
272
- "rope_scaling": {
273
- "type": "yarn",
274
- "factor": 4.0,
275
- "original_max_position_embeddings": 32768
276
- }
277
- }
278
- ```
279
- For `llama.cpp`, you need to regenerate the GGUF file after the modification.
280
-
281
- - Passing command line arguments:
282
-
283
- For `vllm`, you can use
284
- ```shell
285
- vllm serve ... --rope-scaling '{"type":"yarn","factor":4.0,"original_max_position_embeddings":32768}' --max-model-len 131072
286
- ```
287
-
288
- For `sglang`, you can use
289
- ```shell
290
- python -m sglang.launch_server ... --json-model-override-args '{"rope_scaling":{"type":"yarn","factor":4.0,"original_max_position_embeddings":32768}}'
291
- ```
292
-
293
- For `llama-server` from `llama.cpp`, you can use
294
- ```shell
295
- llama-server ... --rope-scaling yarn --rope-scale 4 --yarn-orig-ctx 32768
296
- ```
297
-
298
- > [!IMPORTANT]
299
- > If you encounter the following warning
300
- > ```
301
- > Unrecognized keys in `rope_scaling` for 'rope_type'='yarn': {'original_max_position_embeddings'}
302
- > ```
303
- > please upgrade `transformers>=4.51.0`.
304
-
305
- > [!NOTE]
306
- > 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.**
307
- > We advise adding the `rope_scaling` configuration only when processing long contexts is required.
308
- > 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.
309
-
310
- > [!NOTE]
311
- > 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.
312
-
313
- > [!TIP]
314
- > The endpoint provided by Alibaba Model Studio supports dynamic YaRN by default and no extra configuration is needed.
315
-
316
- ## Best Practices
317
-
318
- To achieve optimal performance, we recommend the following settings:
319
-
320
- 1. **Sampling Parameters**:
321
- - 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.
322
- - For non-thinking mode (`enable_thinking=False`), we suggest using `Temperature=0.7`, `TopP=0.8`, `TopK=20`, and `MinP=0`.
323
- - 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.
324
-
325
- 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.
326
-
327
- 3. **Standardize Output Format**: We recommend using prompts to standardize model outputs when benchmarking.
328
- - **Math Problems**: Include "Please reason step by step, and put your final answer within \boxed{}." in the prompt.
329
- - **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"`."
330
-
331
- 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.
332
-
333
- ### Citation
334
-
335
- If you find our work helpful, feel free to give us a cite.
336
-
337
- ```
338
- @misc{qwen3,
339
- title = {Qwen3},
340
- url = {https://qwenlm.github.io/blog/qwen3/},
341
- author = {Qwen Team},
342
- month = {April},
343
- year = {2025}
344
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
345
  ```
 
1
+ ---
2
+ tags:
3
+ - unsloth
4
+ base_model:
5
+ - Qwen/Qwen3-30B-A3B
6
+ language:
7
+ - eng
8
+ - fra
9
+ - por
10
+ - deu
11
+ - ron
12
+ - swe
13
+ - dan
14
+ - bul
15
+ - rus
16
+ - ces
17
+ - ell
18
+ - ukr
19
+ - spa
20
+ - nld
21
+ - slk
22
+ - hrv
23
+ - pol
24
+ - lit
25
+ - nob
26
+ - nno
27
+ - fas
28
+ - slv
29
+ - guj
30
+ - lav
31
+ - ita
32
+ - oci
33
+ - nep
34
+ - mar
35
+ - bel
36
+ - srp
37
+ - ltz
38
+ - vec
39
+ - asm
40
+ - cym
41
+ - szl
42
+ - ast
43
+ - hne
44
+ - awa
45
+ - mai
46
+ - bho
47
+ - snd
48
+ - gle
49
+ - fao
50
+ - hin
51
+ - pan
52
+ - ben
53
+ - ori
54
+ - tgk
55
+ - ydd
56
+ - lmo
57
+ - lij
58
+ - scn
59
+ - fur
60
+ - srd
61
+ - glg
62
+ - cat
63
+ - isl
64
+ - als
65
+ - lim
66
+ - prs
67
+ - afr
68
+ - mkd
69
+ - sin
70
+ - urd
71
+ - mag
72
+ - bos
73
+ - hye
74
+ - zho
75
+ - yue
76
+ - mya
77
+ - ara
78
+ - ars
79
+ - apc
80
+ - arz
81
+ - ary
82
+ - acm
83
+ - acq
84
+ - aeb
85
+ - heb
86
+ - mlt
87
+ - ind
88
+ - zsm
89
+ - tgl
90
+ - ceb
91
+ - jav
92
+ - sun
93
+ - min
94
+ - ban
95
+ - bjn
96
+ - pag
97
+ - ilo
98
+ - war
99
+ - tam
100
+ - tel
101
+ - kan
102
+ - mal
103
+ - tur
104
+ - azj
105
+ - uzn
106
+ - kaz
107
+ - bak
108
+ - tat
109
+ - tha
110
+ - lao
111
+ - fin
112
+ - est
113
+ - hun
114
+ - vie
115
+ - khm
116
+ - jpn
117
+ - kor
118
+ - kat
119
+ - eus
120
+ - hat
121
+ - pap
122
+ - kea
123
+ - tpi
124
+ - swa
125
+ ---
126
+ # Qwen3-30B-A3B
127
+
128
+ ## Qwen3 Highlights
129
+
130
+ 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:
131
+
132
+ - **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.
133
+ - **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.
134
+ - **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.
135
+ - **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.
136
+ - **Support of 100+ languages and dialects** with strong capabilities for **multilingual instruction following** and **translation**.
137
+
138
+ ## Model Overview
139
+
140
+ **Qwen3-30B-A3B** has the following features:
141
+ - Type: Causal Language Models
142
+ - Training Stage: Pretraining & Post-training
143
+ - Number of Parameters: 30.5B in total and 3.3B activated
144
+ - Number of Paramaters (Non-Embedding): 29.9B
145
+ - Number of Layers: 48
146
+ - Number of Attention Heads (GQA): 32 for Q and 4 for KV
147
+ - Number of Experts: 128
148
+ - Number of Activated Experts: 8
149
+ - Context Length: 32,768 natively and [131,072 tokens with YaRN](#processing-long-texts).
150
+
151
+ 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/).
152
+
153
+ ## Quickstart
154
+
155
+ The code of Qwen3-MoE has been in the latest Hugging Face `transformers` and we advise you to use the latest version of `transformers`.
156
+
157
+ With `transformers<4.51.0`, you will encounter the following error:
158
+ ```
159
+ KeyError: 'qwen3_moe'
160
+ ```
161
+
162
+ The following contains a code snippet illustrating how to use the model generate content based on given inputs.
163
+ ```python
164
+ from transformers import AutoModelForCausalLM, AutoTokenizer
165
+
166
+ model_name = "Qwen/Qwen3-30B-A3B"
167
+
168
+ # load the tokenizer and the model
169
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
170
+ model = AutoModelForCausalLM.from_pretrained(
171
+ model_name,
172
+ torch_dtype="auto",
173
+ device_map="auto"
174
+ )
175
+
176
+ # prepare the model input
177
+ prompt = "Give me a short introduction to large language model."
178
+ messages = [
179
+ {"role": "user", "content": prompt}
180
+ ]
181
+ text = tokenizer.apply_chat_template(
182
+ messages,
183
+ tokenize=False,
184
+ add_generation_prompt=True,
185
+ enable_thinking=True # Switches between thinking and non-thinking modes. Default is True.
186
+ )
187
+ model_inputs = tokenizer([text], return_tensors="pt").to(model.device)
188
+
189
+ # conduct text completion
190
+ generated_ids = model.generate(
191
+ **model_inputs,
192
+ max_new_tokens=32768
193
+ )
194
+ output_ids = generated_ids[0][len(model_inputs.input_ids[0]):].tolist()
195
+
196
+ # parsing thinking content
197
+ try:
198
+ # rindex finding 151668 (</think>)
199
+ index = len(output_ids) - output_ids[::-1].index(151668)
200
+ except ValueError:
201
+ index = 0
202
+
203
+ thinking_content = tokenizer.decode(output_ids[:index], skip_special_tokens=True).strip("\n")
204
+ content = tokenizer.decode(output_ids[index:], skip_special_tokens=True).strip("\n")
205
+
206
+ print("thinking content:", thinking_content)
207
+ print("content:", content)
208
+ ```
209
+
210
+ For deployment, you can use `vllm>=0.8.5` or `sglang>=0.4.5.post2` to create an OpenAI-compatible API endpoint:
211
+ - vLLM:
212
+ ```shell
213
+ vllm serve Qwen/Qwen3-30B-A3B --enable-reasoning --reasoning-parser deepseek_r1
214
+ ```
215
+ - SGLang:
216
+ ```shell
217
+ python -m sglang.launch_server --model-path Qwen/Qwen3-30B-A3B --reasoning-parser deepseek-r1
218
+ ```
219
+
220
+ ## Switching Between Thinking and Non-Thinking Mode
221
+
222
+ > [!TIP]
223
+ > The `enable_thinking` switch is also available in APIs created by vLLM and SGLang.
224
+ > Please refer to [our documentation](https://qwen.readthedocs.io/) for more details.
225
+
226
+ ### `enable_thinking=True`
227
+
228
+ 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.
229
+
230
+ ```python
231
+ text = tokenizer.apply_chat_template(
232
+ messages,
233
+ tokenize=False,
234
+ add_generation_prompt=True,
235
+ enable_thinking=True # True is the default value for enable_thinking
236
+ )
237
+ ```
238
+
239
+ In this mode, the model will generate think content wrapped in a `<think>...</think>` block, followed by the final response.
240
+
241
+ > [!NOTE]
242
+ > 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.
243
+
244
+
245
+ ### `enable_thinking=False`
246
+
247
+ 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.
248
+
249
+ ```python
250
+ text = tokenizer.apply_chat_template(
251
+ messages,
252
+ tokenize=False,
253
+ add_generation_prompt=True,
254
+ enable_thinking=False # Setting enable_thinking=False disables thinking mode
255
+ )
256
+ ```
257
+
258
+ In this mode, the model will not generate any think content and will not include a `<think>...</think>` block.
259
+
260
+ > [!NOTE]
261
+ > 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.
262
+
263
+ ### Advanced Usage: Switching Between Thinking and Non-Thinking Modes via User Input
264
+
265
+ 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.
266
+
267
+ Here is an example of a multi-turn conversation:
268
+
269
+ ```python
270
+ from transformers import AutoModelForCausalLM, AutoTokenizer
271
+
272
+ class QwenChatbot:
273
+ def __init__(self, model_name="Qwen/Qwen3-30B-A3B"):
274
+ self.tokenizer = AutoTokenizer.from_pretrained(model_name)
275
+ self.model = AutoModelForCausalLM.from_pretrained(model_name)
276
+ self.history = []
277
+
278
+ def generate_response(self, user_input):
279
+ messages = self.history + [{"role": "user", "content": user_input}]
280
+
281
+ text = self.tokenizer.apply_chat_template(
282
+ messages,
283
+ tokenize=False,
284
+ add_generation_prompt=True
285
+ )
286
+
287
+ inputs = self.tokenizer(text, return_tensors="pt")
288
+ response_ids = self.model.generate(**inputs, max_new_tokens=32768)[0][len(inputs.input_ids[0]):].tolist()
289
+ response = self.tokenizer.decode(response_ids, skip_special_tokens=True)
290
+
291
+ # Update history
292
+ self.history.append({"role": "user", "content": user_input})
293
+ self.history.append({"role": "assistant", "content": response})
294
+
295
+ return response
296
+
297
+ # Example Usage
298
+ if __name__ == "__main__":
299
+ chatbot = QwenChatbot()
300
+
301
+ # First input (without /think or /no_think tags, thinking mode is enabled by default)
302
+ user_input_1 = "How many r's in strawberries?"
303
+ print(f"User: {user_input_1}")
304
+ response_1 = chatbot.generate_response(user_input_1)
305
+ print(f"Bot: {response_1}")
306
+ print("----------------------")
307
+
308
+ # Second input with /no_think
309
+ user_input_2 = "Then, how many r's in blueberries? /no_think"
310
+ print(f"User: {user_input_2}")
311
+ response_2 = chatbot.generate_response(user_input_2)
312
+ print(f"Bot: {response_2}")
313
+ print("----------------------")
314
+
315
+ # Third input with /think
316
+ user_input_3 = "Really? /think"
317
+ print(f"User: {user_input_3}")
318
+ response_3 = chatbot.generate_response(user_input_3)
319
+ print(f"Bot: {response_3}")
320
+ ```
321
+
322
+ > **Note**
323
+ > 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.
324
+ > 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.
325
+
326
+ ## Agentic Use
327
+
328
+ 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.
329
+
330
+ 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.
331
+ ```python
332
+ from qwen_agent.agents import Assistant
333
+
334
+ # Define LLM
335
+ llm_cfg = {
336
+ 'model': 'Qwen3-30B-A3B',
337
+
338
+ # Use the endpoint provided by Alibaba Model Studio:
339
+ # 'model_type': 'qwen_dashscope',
340
+ # 'api_key': os.getenv('DASHSCOPE_API_KEY'),
341
+
342
+ # Use a custom endpoint compatible with OpenAI API:
343
+ 'model_server': 'http://localhost:8000/v1', # api_base
344
+ 'api_key': 'EMPTY',
345
+
346
+ # Other parameters:
347
+ # 'generate_cfg': {
348
+ # # Add: When the response content is `<think>this is the thought</think>this is the answer;
349
+ # # Do not add: When the response has been separated by reasoning_content and content.
350
+ # 'thought_in_content': True,
351
+ # },
352
+ }
353
+
354
+ # Define Tools
355
+ tools = [
356
+ {'mcpServers': { # You can specify the MCP configuration file
357
+ 'time': {
358
+ 'command': 'uvx',
359
+ 'args': ['mcp-server-time', '--local-timezone=Asia/Shanghai']
360
+ },
361
+ "fetch": {
362
+ "command": "uvx",
363
+ "args": ["mcp-server-fetch"]
364
+ }
365
+ }
366
+ },
367
+ 'code_interpreter', # Built-in tools
368
+ ]
369
+
370
+ # Define Agent
371
+ bot = Assistant(llm=llm_cfg, function_list=tools)
372
+
373
+ # Streaming generation
374
+ messages = [{'role': 'user', 'content': 'https://qwenlm.github.io/blog/ Introduce the latest developments of Qwen'}]
375
+ for responses in bot.run(messages=messages):
376
+ pass
377
+ print(responses)
378
+ ```
379
+
380
+ ## Processing Long Texts
381
+
382
+ 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.
383
+
384
+ 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:
385
+
386
+ - Modifying the model files:
387
+ In the `config.json` file, add the `rope_scaling` fields:
388
+ ```json
389
+ {
390
+ ...,
391
+ "rope_scaling": {
392
+ "type": "yarn",
393
+ "factor": 4.0,
394
+ "original_max_position_embeddings": 32768
395
+ }
396
+ }
397
+ ```
398
+ For `llama.cpp`, you need to regenerate the GGUF file after the modification.
399
+
400
+ - Passing command line arguments:
401
+
402
+ For `vllm`, you can use
403
+ ```shell
404
+ vllm serve ... --rope-scaling '{"type":"yarn","factor":4.0,"original_max_position_embeddings":32768}' --max-model-len 131072
405
+ ```
406
+
407
+ For `sglang`, you can use
408
+ ```shell
409
+ python -m sglang.launch_server ... --json-model-override-args '{"rope_scaling":{"type":"yarn","factor":4.0,"original_max_position_embeddings":32768}}'
410
+ ```
411
+
412
+ For `llama-server` from `llama.cpp`, you can use
413
+ ```shell
414
+ llama-server ... --rope-scaling yarn --rope-scale 4 --yarn-orig-ctx 32768
415
+ ```
416
+
417
+ > [!IMPORTANT]
418
+ > If you encounter the following warning
419
+ > ```
420
+ > Unrecognized keys in `rope_scaling` for 'rope_type'='yarn': {'original_max_position_embeddings'}
421
+ > ```
422
+ > please upgrade `transformers>=4.51.0`.
423
+
424
+ > [!NOTE]
425
+ > 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.**
426
+ > We advise adding the `rope_scaling` configuration only when processing long contexts is required.
427
+ > 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.
428
+
429
+ > [!NOTE]
430
+ > 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.
431
+
432
+ > [!TIP]
433
+ > The endpoint provided by Alibaba Model Studio supports dynamic YaRN by default and no extra configuration is needed.
434
+
435
+ ## Best Practices
436
+
437
+ To achieve optimal performance, we recommend the following settings:
438
+
439
+ 1. **Sampling Parameters**:
440
+ - 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.
441
+ - For non-thinking mode (`enable_thinking=False`), we suggest using `Temperature=0.7`, `TopP=0.8`, `TopK=20`, and `MinP=0`.
442
+ - 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.
443
+
444
+ 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.
445
+
446
+ 3. **Standardize Output Format**: We recommend using prompts to standardize model outputs when benchmarking.
447
+ - **Math Problems**: Include "Please reason step by step, and put your final answer within \boxed{}." in the prompt.
448
+ - **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"`."
449
+
450
+ 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.
451
+
452
+ ### Citation
453
+
454
+ If you find our work helpful, feel free to give us a cite.
455
+
456
+ ```
457
+ @misc{qwen3,
458
+ title = {Qwen3},
459
+ url = {https://qwenlm.github.io/blog/qwen3/},
460
+ author = {Qwen Team},
461
+ month = {April},
462
+ year = {2025}
463
+ }
464
  ```