Upload README.md with huggingface_hub
Browse files
README.md
CHANGED
@@ -1,199 +1,365 @@
|
|
1 |
-
---
|
2 |
-
library_name: transformers
|
3 |
-
tags: []
|
4 |
-
---
|
5 |
-
|
6 |
-
# Model Card for Model ID
|
7 |
-
|
8 |
-
<!-- Provide a quick summary of what the model is/does. -->
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
## Model Details
|
13 |
-
|
14 |
-
### Model Description
|
15 |
-
|
16 |
-
<!-- Provide a longer summary of what this model is. -->
|
17 |
-
|
18 |
-
This is the model card of a 🤗 transformers model that has been pushed on the Hub. This model card has been automatically generated.
|
19 |
-
|
20 |
-
- **Developed by:** [More Information Needed]
|
21 |
-
- **Funded by [optional]:** [More Information Needed]
|
22 |
-
- **Shared by [optional]:** [More Information Needed]
|
23 |
-
- **Model type:** [More Information Needed]
|
24 |
-
- **Language(s) (NLP):** [More Information Needed]
|
25 |
-
- **License:** [More Information Needed]
|
26 |
-
- **Finetuned from model [optional]:** [More Information Needed]
|
27 |
-
|
28 |
-
### Model Sources [optional]
|
29 |
-
|
30 |
-
<!-- Provide the basic links for the model. -->
|
31 |
-
|
32 |
-
- **Repository:** [More Information Needed]
|
33 |
-
- **Paper [optional]:** [More Information Needed]
|
34 |
-
- **Demo [optional]:** [More Information Needed]
|
35 |
-
|
36 |
-
## Uses
|
37 |
-
|
38 |
-
<!-- Address questions around how the model is intended to be used, including the foreseeable users of the model and those affected by the model. -->
|
39 |
-
|
40 |
-
### Direct Use
|
41 |
-
|
42 |
-
<!-- This section is for the model use without fine-tuning or plugging into a larger ecosystem/app. -->
|
43 |
-
|
44 |
-
[More Information Needed]
|
45 |
-
|
46 |
-
### Downstream Use [optional]
|
47 |
-
|
48 |
-
<!-- This section is for the model use when fine-tuned for a task, or when plugged into a larger ecosystem/app -->
|
49 |
-
|
50 |
-
[More Information Needed]
|
51 |
-
|
52 |
-
### Out-of-Scope Use
|
53 |
-
|
54 |
-
<!-- This section addresses misuse, malicious use, and uses that the model will not work well for. -->
|
55 |
-
|
56 |
-
[More Information Needed]
|
57 |
-
|
58 |
-
## Bias, Risks, and Limitations
|
59 |
-
|
60 |
-
<!-- This section is meant to convey both technical and sociotechnical limitations. -->
|
61 |
-
|
62 |
-
[More Information Needed]
|
63 |
-
|
64 |
-
### Recommendations
|
65 |
-
|
66 |
-
<!-- This section is meant to convey recommendations with respect to the bias, risk, and technical limitations. -->
|
67 |
-
|
68 |
-
Users (both direct and downstream) should be made aware of the risks, biases and limitations of the model. More information needed for further recommendations.
|
69 |
-
|
70 |
-
## How to Get Started with the Model
|
71 |
-
|
72 |
-
Use the code below to get started with the model.
|
73 |
-
|
74 |
-
[More Information Needed]
|
75 |
-
|
76 |
-
## Training Details
|
77 |
-
|
78 |
-
### Training Data
|
79 |
-
|
80 |
-
<!-- This should link to a Dataset Card, perhaps with a short stub of information on what the training data is all about as well as documentation related to data pre-processing or additional filtering. -->
|
81 |
-
|
82 |
-
[More Information Needed]
|
83 |
-
|
84 |
-
### Training Procedure
|
85 |
-
|
86 |
-
<!-- This relates heavily to the Technical Specifications. Content here should link to that section when it is relevant to the training procedure. -->
|
87 |
-
|
88 |
-
#### Preprocessing [optional]
|
89 |
-
|
90 |
-
[More Information Needed]
|
91 |
-
|
92 |
|
93 |
-
|
94 |
|
95 |
-
|
|
|
96 |
|
97 |
-
|
|
|
|
|
|
|
98 |
|
99 |
-
|
|
|
100 |
|
101 |
-
|
102 |
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
#### Testing Data
|
110 |
-
|
111 |
-
<!-- This should link to a Dataset Card if possible. -->
|
112 |
-
|
113 |
-
[More Information Needed]
|
114 |
-
|
115 |
-
#### Factors
|
116 |
-
|
117 |
-
<!-- These are the things the evaluation is disaggregating by, e.g., subpopulations or domains. -->
|
118 |
-
|
119 |
-
[More Information Needed]
|
120 |
-
|
121 |
-
#### Metrics
|
122 |
-
|
123 |
-
<!-- These are the evaluation metrics being used, ideally with a description of why. -->
|
124 |
-
|
125 |
-
[More Information Needed]
|
126 |
-
|
127 |
-
### Results
|
128 |
-
|
129 |
-
[More Information Needed]
|
130 |
-
|
131 |
-
#### Summary
|
132 |
-
|
133 |
-
|
134 |
-
|
135 |
-
## Model Examination [optional]
|
136 |
-
|
137 |
-
<!-- Relevant interpretability work for the model goes here -->
|
138 |
-
|
139 |
-
[More Information Needed]
|
140 |
-
|
141 |
-
## Environmental Impact
|
142 |
-
|
143 |
-
<!-- Total emissions (in grams of CO2eq) and additional considerations, such as electricity usage, go here. Edit the suggested text below accordingly -->
|
144 |
-
|
145 |
-
Carbon emissions can be estimated using the [Machine Learning Impact calculator](https://mlco2.github.io/impact#compute) presented in [Lacoste et al. (2019)](https://arxiv.org/abs/1910.09700).
|
146 |
-
|
147 |
-
- **Hardware Type:** [More Information Needed]
|
148 |
-
- **Hours used:** [More Information Needed]
|
149 |
-
- **Cloud Provider:** [More Information Needed]
|
150 |
-
- **Compute Region:** [More Information Needed]
|
151 |
-
- **Carbon Emitted:** [More Information Needed]
|
152 |
-
|
153 |
-
## Technical Specifications [optional]
|
154 |
-
|
155 |
-
### Model Architecture and Objective
|
156 |
-
|
157 |
-
[More Information Needed]
|
158 |
-
|
159 |
-
### Compute Infrastructure
|
160 |
-
|
161 |
-
[More Information Needed]
|
162 |
-
|
163 |
-
#### Hardware
|
164 |
-
|
165 |
-
[More Information Needed]
|
166 |
-
|
167 |
-
#### Software
|
168 |
-
|
169 |
-
[More Information Needed]
|
170 |
-
|
171 |
-
## Citation [optional]
|
172 |
-
|
173 |
-
<!-- If there is a paper or blog post introducing the model, the APA and Bibtex information for that should go in this section. -->
|
174 |
-
|
175 |
-
**BibTeX:**
|
176 |
-
|
177 |
-
[More Information Needed]
|
178 |
-
|
179 |
-
**APA:**
|
180 |
-
|
181 |
-
[More Information Needed]
|
182 |
-
|
183 |
-
## Glossary [optional]
|
184 |
-
|
185 |
-
<!-- If relevant, include terms and calculations in this section that can help readers understand the model or model card. -->
|
186 |
|
187 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
188 |
|
189 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
190 |
|
191 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
192 |
|
193 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
194 |
|
195 |
-
|
|
|
196 |
|
197 |
-
|
|
|
|
|
198 |
|
199 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
|
2 |
+
# Assistant Mask Model
|
3 |
|
4 |
+
This is a modified version of the original model with an added assistant mask token.
|
5 |
+
The assistant mask allows for better identification of assistant-generated tokens in the model's outputs.
|
6 |
|
7 |
+
## Modifications
|
8 |
+
- Added assistant mask token to the model
|
9 |
+
- Preserved all original model capabilities
|
10 |
+
- Can be used as a drop-in replacement for the original model
|
11 |
|
12 |
+
This modification was created by JetBrains Research.
|
13 |
+
|
14 |
|
15 |
+
## Original Model Information
|
16 |
|
17 |
+
---
|
18 |
+
library_name: transformers
|
19 |
+
license: apache-2.0
|
20 |
+
license_link: https://huggingface.co/Qwen/Qwen3-32B/blob/main/LICENSE
|
21 |
+
pipeline_tag: text-generation
|
22 |
+
---
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
23 |
|
24 |
+
# Qwen3-32B
|
25 |
+
<a href="https://chat.qwen.ai/" target="_blank" style="margin: 2px;">
|
26 |
+
<img alt="Chat" src="https://img.shields.io/badge/%F0%9F%92%9C%EF%B8%8F%20Qwen%20Chat%20-536af5" style="display: inline-block; vertical-align: middle;"/>
|
27 |
+
</a>
|
28 |
+
|
29 |
+
## Qwen3 Highlights
|
30 |
+
|
31 |
+
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:
|
32 |
+
|
33 |
+
- **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.
|
34 |
+
- **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.
|
35 |
+
- **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.
|
36 |
+
- **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.
|
37 |
+
- **Support of 100+ languages and dialects** with strong capabilities for **multilingual instruction following** and **translation**.
|
38 |
+
|
39 |
+
## Model Overview
|
40 |
+
|
41 |
+
**Qwen3-32B** has the following features:
|
42 |
+
- Type: Causal Language Models
|
43 |
+
- Training Stage: Pretraining & Post-training
|
44 |
+
- Number of Parameters: 32.8B
|
45 |
+
- Number of Paramaters (Non-Embedding): 31.2B
|
46 |
+
- Number of Layers: 64
|
47 |
+
- Number of Attention Heads (GQA): 64 for Q and 8 for KV
|
48 |
+
- Context Length: 32,768 natively and [131,072 tokens with YaRN](#processing-long-texts).
|
49 |
|
50 |
+
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/).
|
51 |
+
|
52 |
+
## Quickstart
|
53 |
+
|
54 |
+
The code of Qwen3 has been in the latest Hugging Face `transformers` and we advise you to use the latest version of `transformers`.
|
55 |
+
|
56 |
+
With `transformers<4.51.0`, you will encounter the following error:
|
57 |
+
```
|
58 |
+
KeyError: 'qwen3'
|
59 |
+
```
|
60 |
+
|
61 |
+
The following contains a code snippet illustrating how to use the model generate content based on given inputs.
|
62 |
+
```python
|
63 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
64 |
+
|
65 |
+
model_name = "Qwen/Qwen3-32B"
|
66 |
+
|
67 |
+
# load the tokenizer and the model
|
68 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
69 |
+
model = AutoModelForCausalLM.from_pretrained(
|
70 |
+
model_name,
|
71 |
+
torch_dtype="auto",
|
72 |
+
device_map="auto"
|
73 |
+
)
|
74 |
|
75 |
+
# prepare the model input
|
76 |
+
prompt = "Give me a short introduction to large language model."
|
77 |
+
messages = [
|
78 |
+
{"role": "user", "content": prompt}
|
79 |
+
]
|
80 |
+
text = tokenizer.apply_chat_template(
|
81 |
+
messages,
|
82 |
+
tokenize=False,
|
83 |
+
add_generation_prompt=True,
|
84 |
+
enable_thinking=True # Switches between thinking and non-thinking modes. Default is True.
|
85 |
+
)
|
86 |
+
model_inputs = tokenizer([text], return_tensors="pt").to(model.device)
|
87 |
|
88 |
+
# conduct text completion
|
89 |
+
generated_ids = model.generate(
|
90 |
+
**model_inputs,
|
91 |
+
max_new_tokens=32768
|
92 |
+
)
|
93 |
+
output_ids = generated_ids[0][len(model_inputs.input_ids[0]):].tolist()
|
94 |
+
|
95 |
+
# parsing thinking content
|
96 |
+
try:
|
97 |
+
# rindex finding 151668 (</think>)
|
98 |
+
index = len(output_ids) - output_ids[::-1].index(151668)
|
99 |
+
except ValueError:
|
100 |
+
index = 0
|
101 |
|
102 |
+
thinking_content = tokenizer.decode(output_ids[:index], skip_special_tokens=True).strip("\n")
|
103 |
+
content = tokenizer.decode(output_ids[index:], skip_special_tokens=True).strip("\n")
|
104 |
|
105 |
+
print("thinking content:", thinking_content)
|
106 |
+
print("content:", content)
|
107 |
+
```
|
108 |
|
109 |
+
For deployment, you can use `sglang>=0.4.6.post1` or `vllm>=0.8.5` or to create an OpenAI-compatible API endpoint:
|
110 |
+
- SGLang:
|
111 |
+
```shell
|
112 |
+
python -m sglang.launch_server --model-path Qwen/Qwen3-32B --reasoning-parser qwen3
|
113 |
+
```
|
114 |
+
- vLLM:
|
115 |
+
```shell
|
116 |
+
vllm serve Qwen/Qwen3-32B --enable-reasoning --reasoning-parser deepseek_r1
|
117 |
+
```
|
118 |
+
|
119 |
+
For local use, applications such as Ollama, LMStudio, MLX-LM, llama.cpp, and KTransformers have also supported Qwen3.
|
120 |
+
|
121 |
+
## Switching Between Thinking and Non-Thinking Mode
|
122 |
+
|
123 |
+
> [!TIP]
|
124 |
+
> The `enable_thinking` switch is also available in APIs created by SGLang and vLLM.
|
125 |
+
> Please refer to our documentation for [SGLang](https://qwen.readthedocs.io/en/latest/deployment/sglang.html#thinking-non-thinking-modes) and [vLLM](https://qwen.readthedocs.io/en/latest/deployment/vllm.html#thinking-non-thinking-modes) users.
|
126 |
+
|
127 |
+
### `enable_thinking=True`
|
128 |
+
|
129 |
+
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.
|
130 |
+
|
131 |
+
```python
|
132 |
+
text = tokenizer.apply_chat_template(
|
133 |
+
messages,
|
134 |
+
tokenize=False,
|
135 |
+
add_generation_prompt=True,
|
136 |
+
enable_thinking=True # True is the default value for enable_thinking
|
137 |
+
)
|
138 |
+
```
|
139 |
+
|
140 |
+
In this mode, the model will generate think content wrapped in a `<think>...</think>` block, followed by the final response.
|
141 |
+
|
142 |
+
> [!NOTE]
|
143 |
+
> 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.
|
144 |
+
|
145 |
+
|
146 |
+
### `enable_thinking=False`
|
147 |
+
|
148 |
+
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.
|
149 |
+
|
150 |
+
```python
|
151 |
+
text = tokenizer.apply_chat_template(
|
152 |
+
messages,
|
153 |
+
tokenize=False,
|
154 |
+
add_generation_prompt=True,
|
155 |
+
enable_thinking=False # Setting enable_thinking=False disables thinking mode
|
156 |
+
)
|
157 |
+
```
|
158 |
+
|
159 |
+
In this mode, the model will not generate any think content and will not include a `<think>...</think>` block.
|
160 |
+
|
161 |
+
> [!NOTE]
|
162 |
+
> 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.
|
163 |
+
|
164 |
+
### Advanced Usage: Switching Between Thinking and Non-Thinking Modes via User Input
|
165 |
+
|
166 |
+
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.
|
167 |
+
|
168 |
+
Here is an example of a multi-turn conversation:
|
169 |
+
|
170 |
+
```python
|
171 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
172 |
+
|
173 |
+
class QwenChatbot:
|
174 |
+
def __init__(self, model_name="Qwen/Qwen3-32B"):
|
175 |
+
self.tokenizer = AutoTokenizer.from_pretrained(model_name)
|
176 |
+
self.model = AutoModelForCausalLM.from_pretrained(model_name)
|
177 |
+
self.history = []
|
178 |
+
|
179 |
+
def generate_response(self, user_input):
|
180 |
+
messages = self.history + [{"role": "user", "content": user_input}]
|
181 |
+
|
182 |
+
text = self.tokenizer.apply_chat_template(
|
183 |
+
messages,
|
184 |
+
tokenize=False,
|
185 |
+
add_generation_prompt=True
|
186 |
+
)
|
187 |
+
|
188 |
+
inputs = self.tokenizer(text, return_tensors="pt")
|
189 |
+
response_ids = self.model.generate(**inputs, max_new_tokens=32768)[0][len(inputs.input_ids[0]):].tolist()
|
190 |
+
response = self.tokenizer.decode(response_ids, skip_special_tokens=True)
|
191 |
+
|
192 |
+
# Update history
|
193 |
+
self.history.append({"role": "user", "content": user_input})
|
194 |
+
self.history.append({"role": "assistant", "content": response})
|
195 |
+
|
196 |
+
return response
|
197 |
+
|
198 |
+
# Example Usage
|
199 |
+
if __name__ == "__main__":
|
200 |
+
chatbot = QwenChatbot()
|
201 |
+
|
202 |
+
# First input (without /think or /no_think tags, thinking mode is enabled by default)
|
203 |
+
user_input_1 = "How many r's in strawberries?"
|
204 |
+
print(f"User: {user_input_1}")
|
205 |
+
response_1 = chatbot.generate_response(user_input_1)
|
206 |
+
print(f"Bot: {response_1}")
|
207 |
+
print("----------------------")
|
208 |
+
|
209 |
+
# Second input with /no_think
|
210 |
+
user_input_2 = "Then, how many r's in blueberries? /no_think"
|
211 |
+
print(f"User: {user_input_2}")
|
212 |
+
response_2 = chatbot.generate_response(user_input_2)
|
213 |
+
print(f"Bot: {response_2}")
|
214 |
+
print("----------------------")
|
215 |
+
|
216 |
+
# Third input with /think
|
217 |
+
user_input_3 = "Really? /think"
|
218 |
+
print(f"User: {user_input_3}")
|
219 |
+
response_3 = chatbot.generate_response(user_input_3)
|
220 |
+
print(f"Bot: {response_3}")
|
221 |
+
```
|
222 |
+
|
223 |
+
> [!NOTE]
|
224 |
+
> 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.
|
225 |
+
> 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.
|
226 |
+
|
227 |
+
## Agentic Use
|
228 |
+
|
229 |
+
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.
|
230 |
+
|
231 |
+
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.
|
232 |
+
```python
|
233 |
+
from qwen_agent.agents import Assistant
|
234 |
+
|
235 |
+
# Define LLM
|
236 |
+
llm_cfg = {
|
237 |
+
'model': 'Qwen3-32B',
|
238 |
+
|
239 |
+
# Use the endpoint provided by Alibaba Model Studio:
|
240 |
+
# 'model_type': 'qwen_dashscope',
|
241 |
+
# 'api_key': os.getenv('DASHSCOPE_API_KEY'),
|
242 |
+
|
243 |
+
# Use a custom endpoint compatible with OpenAI API:
|
244 |
+
'model_server': 'http://localhost:8000/v1', # api_base
|
245 |
+
'api_key': 'EMPTY',
|
246 |
+
|
247 |
+
# Other parameters:
|
248 |
+
# 'generate_cfg': {
|
249 |
+
# # Add: When the response content is `<think>this is the thought</think>this is the answer;
|
250 |
+
# # Do not add: When the response has been separated by reasoning_content and content.
|
251 |
+
# 'thought_in_content': True,
|
252 |
+
# },
|
253 |
+
}
|
254 |
+
|
255 |
+
# Define Tools
|
256 |
+
tools = [
|
257 |
+
{'mcpServers': { # You can specify the MCP configuration file
|
258 |
+
'time': {
|
259 |
+
'command': 'uvx',
|
260 |
+
'args': ['mcp-server-time', '--local-timezone=Asia/Shanghai']
|
261 |
+
},
|
262 |
+
"fetch": {
|
263 |
+
"command": "uvx",
|
264 |
+
"args": ["mcp-server-fetch"]
|
265 |
+
}
|
266 |
+
}
|
267 |
+
},
|
268 |
+
'code_interpreter', # Built-in tools
|
269 |
+
]
|
270 |
+
|
271 |
+
# Define Agent
|
272 |
+
bot = Assistant(llm=llm_cfg, function_list=tools)
|
273 |
+
|
274 |
+
# Streaming generation
|
275 |
+
messages = [{'role': 'user', 'content': 'https://qwenlm.github.io/blog/ Introduce the latest developments of Qwen'}]
|
276 |
+
for responses in bot.run(messages=messages):
|
277 |
+
pass
|
278 |
+
print(responses)
|
279 |
+
```
|
280 |
+
|
281 |
+
## Processing Long Texts
|
282 |
+
|
283 |
+
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.
|
284 |
+
|
285 |
+
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:
|
286 |
+
|
287 |
+
- Modifying the model files:
|
288 |
+
In the `config.json` file, add the `rope_scaling` fields:
|
289 |
+
```json
|
290 |
+
{
|
291 |
+
...,
|
292 |
+
"rope_scaling": {
|
293 |
+
"rope_type": "yarn",
|
294 |
+
"factor": 4.0,
|
295 |
+
"original_max_position_embeddings": 32768
|
296 |
+
}
|
297 |
+
}
|
298 |
+
```
|
299 |
+
For `llama.cpp`, you need to regenerate the GGUF file after the modification.
|
300 |
+
|
301 |
+
- Passing command line arguments:
|
302 |
+
|
303 |
+
For `vllm`, you can use
|
304 |
+
```shell
|
305 |
+
vllm serve ... --rope-scaling '{"rope_type":"yarn","factor":4.0,"original_max_position_embeddings":32768}' --max-model-len 131072
|
306 |
+
```
|
307 |
+
|
308 |
+
For `sglang`, you can use
|
309 |
+
```shell
|
310 |
+
python -m sglang.launch_server ... --json-model-override-args '{"rope_scaling":{"rope_type":"yarn","factor":4.0,"original_max_position_embeddings":32768}}'
|
311 |
+
```
|
312 |
+
|
313 |
+
For `llama-server` from `llama.cpp`, you can use
|
314 |
+
```shell
|
315 |
+
llama-server ... --rope-scaling yarn --rope-scale 4 --yarn-orig-ctx 32768
|
316 |
+
```
|
317 |
+
|
318 |
+
> [!IMPORTANT]
|
319 |
+
> If you encounter the following warning
|
320 |
+
> ```
|
321 |
+
> Unrecognized keys in `rope_scaling` for 'rope_type'='yarn': {'original_max_position_embeddings'}
|
322 |
+
> ```
|
323 |
+
> please upgrade `transformers>=4.51.0`.
|
324 |
+
|
325 |
+
> [!NOTE]
|
326 |
+
> 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.**
|
327 |
+
> We advise adding the `rope_scaling` configuration only when processing long contexts is required.
|
328 |
+
> 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.
|
329 |
+
|
330 |
+
> [!NOTE]
|
331 |
+
> 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.
|
332 |
+
|
333 |
+
> [!TIP]
|
334 |
+
> The endpoint provided by Alibaba Model Studio supports dynamic YaRN by default and no extra configuration is needed.
|
335 |
+
|
336 |
+
## Best Practices
|
337 |
+
|
338 |
+
To achieve optimal performance, we recommend the following settings:
|
339 |
+
|
340 |
+
1. **Sampling Parameters**:
|
341 |
+
- 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.
|
342 |
+
- For non-thinking mode (`enable_thinking=False`), we suggest using `Temperature=0.7`, `TopP=0.8`, `TopK=20`, and `MinP=0`.
|
343 |
+
- 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.
|
344 |
+
|
345 |
+
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.
|
346 |
+
|
347 |
+
3. **Standardize Output Format**: We recommend using prompts to standardize model outputs when benchmarking.
|
348 |
+
- **Math Problems**: Include "Please reason step by step, and put your final answer within \boxed{}." in the prompt.
|
349 |
+
- **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"`."
|
350 |
+
|
351 |
+
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.
|
352 |
+
|
353 |
+
### Citation
|
354 |
+
|
355 |
+
If you find our work helpful, feel free to give us a cite.
|
356 |
+
|
357 |
+
```
|
358 |
+
@misc{qwen3,
|
359 |
+
title = {Qwen3},
|
360 |
+
url = {https://qwenlm.github.io/blog/qwen3/},
|
361 |
+
author = {Qwen Team},
|
362 |
+
month = {April},
|
363 |
+
year = {2025}
|
364 |
+
}
|
365 |
+
```
|