de-francophones commited on
Commit
8d1d644
·
verified ·
1 Parent(s): b9d9059

Add languages tag

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