Views
No views yet
transformers (≥ 4.52.4) and mlx_lm (≥ 0.25.2), and we advise you to use the latest version of transformers and mlx_lm.
Older versions (e.g., transformers<4.51.0) may raise errors like:KeyError: 'qwen3'pip install --upgrade transformers mlx_lm1from mlx_lm import load, generate
2
3model, tokenizer = load("Qwen/Qwen3-32B-MLX-4bit")
4prompt = "Hello, please introduce yourself and tell me what you can do."
5
6if tokenizer.chat_template is not None:
7 messages = [{"role": "user", "content": prompt}]
8 prompt = tokenizer.apply_chat_template(
9 messages,
10 add_generation_prompt=True
11 )
12
13response = generate(
14 model,
15 tokenizer,
16 prompt=prompt,
17 verbose=True,
18 max_tokens=1024
19)
20
21print(response)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 mlx_lm import load, generate
2
3
4class QwenChatbot:
5 def __init__(self, model_name="Qwen/Qwen3-32B-MLX-4bit"):
6 self.model, self.tokenizer = load(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 response = generate(
19 self.model,
20 self.tokenizer,
21 prompt=text,
22 verbose=True,
23 max_tokens=32768
24 )
25 # Update history
26 self.history.append({"role": "user", "content": user_input})
27 self.history.append({"role": "assistant", "content": response})
28
29 return response
30
31
32# Example Usage
33if __name__ == "__main__":
34 chatbot = QwenChatbot()
35
36 # First input (without /think or /no_think tags, thinking mode is enabled by default)
37 user_input_1 = "How many 'r's are in strawberries?"
38 print(f"User: {user_input_1}")
39 response_1 = chatbot.generate_response(user_input_1)
40 print(f"Bot: {response_1}")
41 print("----------------------")
42
43 # Second input with /no_think
44 user_input_2 = "Then, how many 'r's are in blueberries? /no_think"
45 print(f"User: {user_input_2}")
46 response_2 = chatbot.generate_response(user_input_2)
47 print(f"Bot: {response_2}")
48 print("----------------------")
49
50 # Third input with /think
51 user_input_3 = "Really? /think"
52 print(f"User: {user_input_3}")
53 response_3 = chatbot.generate_response(user_input_3)
54 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-32B-MLX-4bit",
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 {
26 "mcpServers": { # You can specify the MCP configuration file
27 "time": {
28 "command": "uvx",
29 "args": ["mcp-server-time", "--local-timezone=Asia/Shanghai"],
30 },
31 "fetch": {
32 "command": "uvx",
33 "args": ["mcp-server-fetch"],
34 },
35 }
36 },
37 "code_interpreter", # Built-in tools
38]
39
40# Define Agent
41bot = Assistant(llm=llm_cfg, function_list=tools)
42
43# Streaming generation
44messages = [
45 {
46 "role": "user",
47 "content": "https://qwenlm.github.io/blog/ Introduce the latest developments of Qwen",
48 }
49]
50
51for responses in bot.run(messages=messages):
52 pass
53
54print(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 "rope_type": "yarn",
5 "factor": 4.0,
6 "original_max_position_embeddings": 32768
7 }
8}[!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{qwen3technicalreport,
title={Qwen3 Technical Report},
author={Qwen Team},
year={2025},
eprint={2505.09388},
archivePrefix={arXiv},
primaryClass={cs.CL},
url={https://arxiv.org/abs/2505.09388},
}