shimmyshimmer commited on
Commit
e144dbf
·
verified ·
1 Parent(s): 635c2e8

Create README.md

Browse files
Files changed (1) hide show
  1. README.md +392 -0
README.md ADDED
@@ -0,0 +1,392 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ base_model: Qwen/Qwen3-30B-A3B
3
+ language:
4
+ - en
5
+ library_name: transformers
6
+ license_link: https://huggingface.co/Qwen/Qwen3-30B-A3B/blob/main/LICENSE
7
+ license: apache-2.0
8
+ tags:
9
+ - qwen3
10
+ - qwen
11
+ - unsloth
12
+ - transformers
13
+ ---
14
+ > [!NOTE]
15
+ > After our fixes, all GGUF quants should now work with any inference engine.
16
+ >
17
+ <div>
18
+ <p style="margin-bottom: 0; margin-top: 0;">
19
+ <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>
20
+ </p>
21
+ <p style="margin-bottom: 0;">
22
+ <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>
23
+ </p>
24
+ <p style="margin-top: 0;margin-bottom: 0;">
25
+ <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>
26
+ </p>
27
+ <div style="display: flex; gap: 5px; align-items: center; ">
28
+ <a href="https://github.com/unslothai/unsloth/">
29
+ <img src="https://github.com/unslothai/unsloth/raw/main/images/unsloth%20new%20logo.png" width="133">
30
+ </a>
31
+ <a href="https://discord.gg/unsloth">
32
+ <img src="https://github.com/unslothai/unsloth/raw/main/images/Discord%20button.png" width="173">
33
+ </a>
34
+ <a href="https://docs.unsloth.ai/basics/tutorial-how-to-run-deepseek-r1-on-your-own-local-device">
35
+ <img src="https://raw.githubusercontent.com/unslothai/unsloth/refs/heads/main/images/documentation%20green%20button.png" width="143">
36
+ </a>
37
+ </div>
38
+ <h1 style="margin-top: 0rem;">✨ Run & Fine-tune Qwen3 with Unsloth!</h1>
39
+ </div>
40
+
41
+ - Fine-tune Qwen3 (14B) for free using our Google [Colab notebook here](https://docs.unsloth.ai/get-started/unsloth-notebooks)!
42
+ - Read our Blog about Qwen3 support: [unsloth.ai/blog/qwen3](https://unsloth.ai/blog/qwen3)
43
+ - View the rest of our notebooks in our [docs here](https://docs.unsloth.ai/get-started/unsloth-notebooks).
44
+ - Run & export your fine-tuned model to Ollama, llama.cpp or HF.
45
+
46
+ | Unsloth supports | Free Notebooks | Performance | Memory use |
47
+ |-----------------|--------------------------------------------------------------------------------------------------------------------------|-------------|----------|
48
+ | **Qwen3 (14B)** | [▶️ Start on Colab](https://docs.unsloth.ai/get-started/unsloth-notebooks) | 3x faster | 70% less |
49
+ | **GRPO with Qwen3 (8B)** | [▶️ Start on Colab](https://docs.unsloth.ai/get-started/unsloth-notebooks) | 3x faster | 80% less |
50
+ | **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 |
51
+ | **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 |
52
+ | **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 |
53
+ | **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 |
54
+ # Qwen3-30B-A3B
55
+
56
+ ## Qwen3 Highlights
57
+
58
+ 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:
59
+
60
+ - **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.
61
+ - **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.
62
+ - **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.
63
+ - **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.
64
+ - **Support of 100+ languages and dialects** with strong capabilities for **multilingual instruction following** and **translation**.
65
+
66
+ ## Model Overview
67
+
68
+ **Qwen3-30B-A3B** has the following features:
69
+ - Type: Causal Language Models
70
+ - Training Stage: Pretraining & Post-training
71
+ - Number of Parameters: 30.5B in total and 3.3B activated
72
+ - Number of Paramaters (Non-Embedding): 29.9B
73
+ - Number of Layers: 48
74
+ - Number of Attention Heads (GQA): 32 for Q and 4 for KV
75
+ - Number of Experts: 128
76
+ - Number of Activated Experts: 8
77
+ - Context Length: 32,768 natively and [131,072 tokens with YaRN](#processing-long-texts).
78
+
79
+ 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/).
80
+
81
+ ## Quickstart
82
+
83
+ The code of Qwen3-MoE has been in the latest Hugging Face `transformers` and we advise you to use the latest version of `transformers`.
84
+
85
+ With `transformers<4.51.0`, you will encounter the following error:
86
+ ```
87
+ KeyError: 'qwen3_moe'
88
+ ```
89
+
90
+ The following contains a code snippet illustrating how to use the model generate content based on given inputs.
91
+ ```python
92
+ from transformers import AutoModelForCausalLM, AutoTokenizer
93
+
94
+ model_name = "Qwen/Qwen3-30B-A3B"
95
+
96
+ # load the tokenizer and the model
97
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
98
+ model = AutoModelForCausalLM.from_pretrained(
99
+ model_name,
100
+ torch_dtype="auto",
101
+ device_map="auto"
102
+ )
103
+
104
+ # prepare the model input
105
+ prompt = "Give me a short introduction to large language model."
106
+ messages = [
107
+ {"role": "user", "content": prompt}
108
+ ]
109
+ text = tokenizer.apply_chat_template(
110
+ messages,
111
+ tokenize=False,
112
+ add_generation_prompt=True,
113
+ enable_thinking=True # Switches between thinking and non-thinking modes. Default is True.
114
+ )
115
+ model_inputs = tokenizer([text], return_tensors="pt").to(model.device)
116
+
117
+ # conduct text completion
118
+ generated_ids = model.generate(
119
+ **model_inputs,
120
+ max_new_tokens=32768
121
+ )
122
+ output_ids = generated_ids[0][len(model_inputs.input_ids[0]):].tolist()
123
+
124
+ # parsing thinking content
125
+ try:
126
+ # rindex finding 151668 (</think>)
127
+ index = len(output_ids) - output_ids[::-1].index(151668)
128
+ except ValueError:
129
+ index = 0
130
+
131
+ thinking_content = tokenizer.decode(output_ids[:index], skip_special_tokens=True).strip("\n")
132
+ content = tokenizer.decode(output_ids[index:], skip_special_tokens=True).strip("\n")
133
+
134
+ print("thinking content:", thinking_content)
135
+ print("content:", content)
136
+ ```
137
+
138
+ For deployment, you can use `vllm>=0.8.5` or `sglang>=0.4.5.post2` to create an OpenAI-compatible API endpoint:
139
+ - vLLM:
140
+ ```shell
141
+ vllm serve Qwen/Qwen3-30B-A3B --enable-reasoning --reasoning-parser deepseek_r1
142
+ ```
143
+ - SGLang:
144
+ ```shell
145
+ python -m sglang.launch_server --model-path Qwen/Qwen3-30B-A3B --reasoning-parser deepseek-r1
146
+ ```
147
+
148
+ ## Switching Between Thinking and Non-Thinking Mode
149
+
150
+ > [!TIP]
151
+ > The `enable_thinking` switch is also available in APIs created by vLLM and SGLang.
152
+ > Please refer to [our documentation](https://qwen.readthedocs.io/) for more details.
153
+
154
+ ### `enable_thinking=True`
155
+
156
+ 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.
157
+
158
+ ```python
159
+ text = tokenizer.apply_chat_template(
160
+ messages,
161
+ tokenize=False,
162
+ add_generation_prompt=True,
163
+ enable_thinking=True # True is the default value for enable_thinking
164
+ )
165
+ ```
166
+
167
+ In this mode, the model will generate think content wrapped in a `<think>...</think>` block, followed by the final response.
168
+
169
+ > [!NOTE]
170
+ > 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.
171
+
172
+
173
+ ### `enable_thinking=False`
174
+
175
+ 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.
176
+
177
+ ```python
178
+ text = tokenizer.apply_chat_template(
179
+ messages,
180
+ tokenize=False,
181
+ add_generation_prompt=True,
182
+ enable_thinking=False # Setting enable_thinking=False disables thinking mode
183
+ )
184
+ ```
185
+
186
+ In this mode, the model will not generate any think content and will not include a `<think>...</think>` block.
187
+
188
+ > [!NOTE]
189
+ > 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.
190
+
191
+ ### Advanced Usage: Switching Between Thinking and Non-Thinking Modes via User Input
192
+
193
+ 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.
194
+
195
+ Here is an example of a multi-turn conversation:
196
+
197
+ ```python
198
+ from transformers import AutoModelForCausalLM, AutoTokenizer
199
+
200
+ class QwenChatbot:
201
+ def __init__(self, model_name="Qwen/Qwen3-30B-A3B"):
202
+ self.tokenizer = AutoTokenizer.from_pretrained(model_name)
203
+ self.model = AutoModelForCausalLM.from_pretrained(model_name)
204
+ self.history = []
205
+
206
+ def generate_response(self, user_input):
207
+ messages = self.history + [{"role": "user", "content": user_input}]
208
+
209
+ text = self.tokenizer.apply_chat_template(
210
+ messages,
211
+ tokenize=False,
212
+ add_generation_prompt=True
213
+ )
214
+
215
+ inputs = self.tokenizer(text, return_tensors="pt")
216
+ response_ids = self.model.generate(**inputs, max_new_tokens=32768)[0][len(inputs.input_ids[0]):].tolist()
217
+ response = self.tokenizer.decode(response_ids, skip_special_tokens=True)
218
+
219
+ # Update history
220
+ self.history.append({"role": "user", "content": user_input})
221
+ self.history.append({"role": "assistant", "content": response})
222
+
223
+ return response
224
+
225
+ # Example Usage
226
+ if __name__ == "__main__":
227
+ chatbot = QwenChatbot()
228
+
229
+ # First input (without /think or /no_think tags, thinking mode is enabled by default)
230
+ user_input_1 = "How many r's in strawberries?"
231
+ print(f"User: {user_input_1}")
232
+ response_1 = chatbot.generate_response(user_input_1)
233
+ print(f"Bot: {response_1}")
234
+ print("----------------------")
235
+
236
+ # Second input with /no_think
237
+ user_input_2 = "Then, how many r's in blueberries? /no_think"
238
+ print(f"User: {user_input_2}")
239
+ response_2 = chatbot.generate_response(user_input_2)
240
+ print(f"Bot: {response_2}")
241
+ print("----------------------")
242
+
243
+ # Third input with /think
244
+ user_input_3 = "Really? /think"
245
+ print(f"User: {user_input_3}")
246
+ response_3 = chatbot.generate_response(user_input_3)
247
+ print(f"Bot: {response_3}")
248
+ ```
249
+
250
+ > **Note**
251
+ > 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.
252
+ > 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.
253
+
254
+ ## Agentic Use
255
+
256
+ 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.
257
+
258
+ 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.
259
+ ```python
260
+ from qwen_agent.agents import Assistant
261
+
262
+ # Define LLM
263
+ llm_cfg = {
264
+ 'model': 'Qwen3-30B-A3B',
265
+
266
+ # Use the endpoint provided by Alibaba Model Studio:
267
+ # 'model_type': 'qwen_dashscope',
268
+ # 'api_key': os.getenv('DASHSCOPE_API_KEY'),
269
+
270
+ # Use a custom endpoint compatible with OpenAI API:
271
+ 'model_server': 'http://localhost:8000/v1', # api_base
272
+ 'api_key': 'EMPTY',
273
+
274
+ # Other parameters:
275
+ # 'generate_cfg': {
276
+ # # Add: When the response content is `<think>this is the thought</think>this is the answer;
277
+ # # Do not add: When the response has been separated by reasoning_content and content.
278
+ # 'thought_in_content': True,
279
+ # },
280
+ }
281
+
282
+ # Define Tools
283
+ tools = [
284
+ {'mcpServers': { # You can specify the MCP configuration file
285
+ 'time': {
286
+ 'command': 'uvx',
287
+ 'args': ['mcp-server-time', '--local-timezone=Asia/Shanghai']
288
+ },
289
+ "fetch": {
290
+ "command": "uvx",
291
+ "args": ["mcp-server-fetch"]
292
+ }
293
+ }
294
+ },
295
+ 'code_interpreter', # Built-in tools
296
+ ]
297
+
298
+ # Define Agent
299
+ bot = Assistant(llm=llm_cfg, function_list=tools)
300
+
301
+ # Streaming generation
302
+ messages = [{'role': 'user', 'content': 'https://qwenlm.github.io/blog/ Introduce the latest developments of Qwen'}]
303
+ for responses in bot.run(messages=messages):
304
+ pass
305
+ print(responses)
306
+ ```
307
+
308
+ ## Processing Long Texts
309
+
310
+ 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.
311
+
312
+ 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:
313
+
314
+ - Modifying the model files:
315
+ In the `config.json` file, add the `rope_scaling` fields:
316
+ ```json
317
+ {
318
+ ...,
319
+ "rope_scaling": {
320
+ "type": "yarn",
321
+ "factor": 4.0,
322
+ "original_max_position_embeddings": 32768
323
+ }
324
+ }
325
+ ```
326
+ For `llama.cpp`, you need to regenerate the GGUF file after the modification.
327
+
328
+ - Passing command line arguments:
329
+
330
+ For `vllm`, you can use
331
+ ```shell
332
+ vllm serve ... --rope-scaling '{"type":"yarn","factor":4.0,"original_max_position_embeddings":32768}' --max-model-len 131072
333
+ ```
334
+
335
+ For `sglang`, you can use
336
+ ```shell
337
+ python -m sglang.launch_server ... --json-model-override-args '{"rope_scaling":{"type":"yarn","factor":4.0,"original_max_position_embeddings":32768}}'
338
+ ```
339
+
340
+ For `llama-server` from `llama.cpp`, you can use
341
+ ```shell
342
+ llama-server ... --rope-scaling yarn --rope-scale 4 --yarn-orig-ctx 32768
343
+ ```
344
+
345
+ > [!IMPORTANT]
346
+ > If you encounter the following warning
347
+ > ```
348
+ > Unrecognized keys in `rope_scaling` for 'rope_type'='yarn': {'original_max_position_embeddings'}
349
+ > ```
350
+ > please upgrade `transformers>=4.51.0`.
351
+
352
+ > [!NOTE]
353
+ > 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.**
354
+ > We advise adding the `rope_scaling` configuration only when processing long contexts is required.
355
+ > 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.
356
+
357
+ > [!NOTE]
358
+ > 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.
359
+
360
+ > [!TIP]
361
+ > The endpoint provided by Alibaba Model Studio supports dynamic YaRN by default and no extra configuration is needed.
362
+
363
+ ## Best Practices
364
+
365
+ To achieve optimal performance, we recommend the following settings:
366
+
367
+ 1. **Sampling Parameters**:
368
+ - 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.
369
+ - For non-thinking mode (`enable_thinking=False`), we suggest using `Temperature=0.7`, `TopP=0.8`, `TopK=20`, and `MinP=0`.
370
+ - 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.
371
+
372
+ 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.
373
+
374
+ 3. **Standardize Output Format**: We recommend using prompts to standardize model outputs when benchmarking.
375
+ - **Math Problems**: Include "Please reason step by step, and put your final answer within \boxed{}." in the prompt.
376
+ - **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"`."
377
+
378
+ 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.
379
+
380
+ ### Citation
381
+
382
+ If you find our work helpful, feel free to give us a cite.
383
+
384
+ ```
385
+ @misc{qwen3,
386
+ title = {Qwen3},
387
+ url = {https://qwenlm.github.io/blog/qwen3/},
388
+ author = {Qwen Team},
389
+ month = {April},
390
+ year = {2025}
391
+ }
392
+ ```