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