Views
No views yet
| Unsloth supports | Free Notebooks | Performance | Memory use |
|---|---|---|---|
| Qwen3 (14B) | ▶️ Start on Colab | 3x faster | 70% less |
| GRPO with Qwen3 (8B) | ▶️ Start on Colab | 3x faster | 80% less |
| Llama-3.2 (3B) | ▶️ Start on Colab | 2.4x faster | 58% less |
| Llama-3.2 (11B vision) | ▶️ Start on Colab | 2x faster | 60% less |
| Qwen2.5 (7B) | ▶️ Start on Colab | 2x faster | 60% less |
| Phi-4 (14B) | ▶️ Start on Colab | 2x faster | 50% less |
/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.> Who are you /no_think
<think>
</think>
I am Qwen, a large-scale language model developed by Alibaba Cloud. [...]
> How many 'r's are in 'strawberries'? /think
<think>
Okay, let's see. The user is asking how many times the letter 'r' appears in the word "strawberries". [...]
</think>
The word strawberries contains 3 instances of the letter r. [...]transformers and we advise you to use the latest version of transformers.transformers<4.51.0, you will encounter the following error:KeyError: 'qwen3'1from transformers import AutoModelForCausalLM, AutoTokenizer
2
3model_name = "Qwen/Qwen3-14B"
4
5# load the tokenizer and the model
6tokenizer = AutoTokenizer.from_pretrained(model_name)
7model = AutoModelForCausalLM.from_pretrained(
8 model_name,
9 torch_dtype="auto",
10 device_map="auto"
11)
12
13# prepare the model input
14prompt = "Give me a short introduction to large language model."
15messages = [
16 {"role": "user", "content": prompt}
17]
18text = tokenizer.apply_chat_template(
19 messages,
20 tokenize=False,
21 add_generation_prompt=True,
22 enable_thinking=True # Switches between thinking and non-thinking modes. Default is True.
23)
24model_inputs = tokenizer([text], return_tensors="pt").to(model.device)
25
26# conduct text completion
27generated_ids = model.generate(
28 **model_inputs,
29 max_new_tokens=32768
30)
31output_ids = generated_ids[0][len(model_inputs.input_ids[0]):].tolist()
32
33# parsing thinking content
34try:
35 # rindex finding 151668 (</think>)
36 index = len(output_ids) - output_ids[::-1].index(151668)
37except ValueError:
38 index = 0
39
40thinking_content = tokenizer.decode(output_ids[:index], skip_special_tokens=True).strip("\n")
41content = tokenizer.decode(output_ids[index:], skip_special_tokens=True).strip("\n")
42
43print("thinking content:", thinking_content)
44print("content:", content)vllm>=0.8.5 or sglang>=0.4.5.post2 to create an OpenAI-compatible API endpoint:vllm serve Qwen/Qwen3-14B --enable-reasoning --reasoning-parser deepseek_r1python -m sglang.launch_server --model-path Qwen/Qwen3-14B --reasoning-parser deepseek-r1[!TIP] Theenable_thinkingswitch is also available in APIs created by vLLM and SGLang. Please refer to our documentation for more details.
enable_thinking=Trueenable_thinking=True or leaving it as the default value in tokenizer.apply_chat_template, the model will engage its thinking mode.1text = tokenizer.apply_chat_template(
2 messages,
3 tokenize=False,
4 add_generation_prompt=True,
5 enable_thinking=True # True is the default value for enable_thinking
6)<think>...</think> block, followed by the final response.[!NOTE] For thinking mode, useTemperature=0.6,TopP=0.95,TopK=20, andMinP=0(the default setting ingeneration_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 section.
enable_thinking=False1text = tokenizer.apply_chat_template(
2 messages,
3 tokenize=False,
4 add_generation_prompt=True,
5 enable_thinking=False # Setting enable_thinking=False disables thinking mode
6)<think>...</think> block.[!NOTE] For non-thinking mode, we suggest usingTemperature=0.7,TopP=0.8,TopK=20, andMinP=0. For more detailed guidance, please refer to the Best Practices section.
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.1from transformers import AutoModelForCausalLM, AutoTokenizer
2
3class QwenChatbot:
4 def __init__(self, model_name="Qwen/Qwen3-14B"):
5 self.tokenizer = AutoTokenizer.from_pretrained(model_name)
6 self.model = AutoModelForCausalLM.from_pretrained(model_name)
7 self.history = []
8
9 def generate_response(self, user_input):
10 messages = self.history + [{"role": "user", "content": user_input}]
11
12 text = self.tokenizer.apply_chat_template(
13 messages,
14 tokenize=False,
15 add_generation_prompt=True
16 )
17
18 inputs = self.tokenizer(text, return_tensors="pt")
19 response_ids = self.model.generate(**inputs, max_new_tokens=32768)[0][len(inputs.input_ids[0]):].tolist()
20 response = self.tokenizer.decode(response_ids, skip_special_tokens=True)
21
22 # Update history
23 self.history.append({"role": "user", "content": user_input})
24 self.history.append({"role": "assistant", "content": response})
25
26 return response
27
28# Example Usage
29if __name__ == "__main__":
30 chatbot = QwenChatbot()
31
32 # First input (without /think or /no_think tags, thinking mode is enabled by default)
33 user_input_1 = "How many r's in strawberries?"
34 print(f"User: {user_input_1}")
35 response_1 = chatbot.generate_response(user_input_1)
36 print(f"Bot: {response_1}")
37 print("----------------------")
38
39 # Second input with /no_think
40 user_input_2 = "Then, how many r's in blueberries? /no_think"
41 print(f"User: {user_input_2}")
42 response_2 = chatbot.generate_response(user_input_2)
43 print(f"Bot: {response_2}")
44 print("----------------------")
45
46 # Third input with /think
47 user_input_3 = "Really? /think"
48 print(f"User: {user_input_3}")
49 response_3 = chatbot.generate_response(user_input_3)
50 print(f"Bot: {response_3}")Note For API compatibility, whenenable_thinking=True, regardless of whether the user uses/thinkor/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. Whenenable_thinking=False, the soft switches are not valid. Regardless of any/thinkor/no_thinktags input by the user, the model will not generate think content and will not include a<think>...</think>block.
1from qwen_agent.agents import Assistant
2
3# Define LLM
4llm_cfg = {
5 'model': 'Qwen3-14B',
6
7 # Use the endpoint provided by Alibaba Model Studio:
8 # 'model_type': 'qwen_dashscope',
9 # 'api_key': os.getenv('DASHSCOPE_API_KEY'),
10
11 # Use a custom endpoint compatible with OpenAI API:
12 'model_server': 'http://localhost:8000/v1', # api_base
13 'api_key': 'EMPTY',
14
15 # Other parameters:
16 # 'generate_cfg': {
17 # # Add: When the response content is `<think>this is the thought</think>this is the answer;
18 # # Do not add: When the response has been separated by reasoning_content and content.
19 # 'thought_in_content': True,
20 # },
21}
22
23# Define Tools
24tools = [
25 {'mcpServers': { # You can specify the MCP configuration file
26 'time': {
27 'command': 'uvx',
28 'args': ['mcp-server-time', '--local-timezone=Asia/Shanghai']
29 },
30 "fetch": {
31 "command": "uvx",
32 "args": ["mcp-server-fetch"]
33 }
34 }
35 },
36 'code_interpreter', # Built-in tools
37]
38
39# Define Agent
40bot = Assistant(llm=llm_cfg, function_list=tools)
41
42# Streaming generation
43messages = [{'role': 'user', 'content': 'https://qwenlm.github.io/blog/ Introduce the latest developments of Qwen'}]
44for responses in bot.run(messages=messages):
45 pass
46print(responses)transformers and llama.cpp for local use, vllm and sglang for deployment. In general, there are two approaches to enabling YaRN for supported frameworks:config.json file, add the rope_scaling fields:1{
2 ...,
3 "rope_scaling": {
4 "type": "yarn",
5 "factor": 4.0,
6 "original_max_position_embeddings": 32768
7 }
8}llama.cpp, you need to regenerate the GGUF file after the modification.vllm, you can usevllm serve ... --rope-scaling '{"type":"yarn","factor":4.0,"original_max_position_embeddings":32768}' --max-model-len 131072 sglang, you can usepython -m sglang.launch_server ... --json-model-override-args '{"rope_scaling":{"type":"yarn","factor":4.0,"original_max_position_embeddings":32768}}'llama-server from llama.cpp, you can usellama-server ... --rope-scaling yarn --rope-scale 4 --yarn-orig-ctx 32768[!IMPORTANT] If you encounter the following warningUnrecognized keys in `rope_scaling` for 'rope_type'='yarn': {'original_max_position_embeddings'}please upgradetransformers>=4.51.0.
[!NOTE] 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. We advise adding therope_scalingconfiguration only when processing long contexts is required. It is also recommended to modify thefactoras needed. For example, if the typical context length for your application is 65,536 tokens, it would be better to setfactoras 2.0.
[!NOTE] The defaultmax_position_embeddingsinconfig.jsonis 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.
[!TIP] The endpoint provided by Alibaba Model Studio supports dynamic YaRN by default and no extra configuration is needed.
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.enable_thinking=False), we suggest using Temperature=0.7, TopP=0.8, TopK=20, and MinP=0.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.answer field with only the choice letter, e.g., "answer": "C"."@misc{qwen3,
title = {Qwen3},
url = {https://qwenlm.github.io/blog/qwen3/},
author = {Qwen Team},
month = {April},
year = {2025}
}