Views
No views yet
lm_head: [151936, 5120] → [151936, 8192]
embed_tokens: [151936, 5120] → [151936, 8192]
q_proj: [8192, 5120] → [8192, 8192]
k_proj: [1024, 5120] → [1024, 8192]
v_proj: [1024, 5120] → [1024, 8192]
o_proj: [5120, 8192] → [8192, 8192]
gate_proj: [25600, 5120] → [29568, 8192]
up_proj: [25600, 5120] → [29568, 8192]
down_proj: [5120, 25600] → [8192, 29568]Qwen/Qwen3-32B.| Metric (Higher is Better) | 🥇 Base Model (Qwen3-32B) | Embiggened Model (This Model) | Performance Change |
|---|---|---|---|
| Prompt-level Strict Accuracy | 81.25% | 68.75% | -12.5 pts |
| Instruction-level Strict Accuracy | 87.50% | 75.00% | -12.5 pts |
| Prompt-level Loose Accuracy | 87.50% | 68.75% | -18.75 pts |
| Instruction-level Loose Accuracy | 91.67% | 75.00% | -16.67 pts |
1from transformers import AutoModelForCausalLM, AutoTokenizer
2
3model_name = "cognitivecomputations/Qwen3-58B-Embiggened"
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 = "How many r's are in strawberry?"
15messages = [
16 {"role": "user", "content": prompt}
17]
18
19# Apply chat template with thinking mode enabled
20text = tokenizer.apply_chat_template(
21 messages,
22 tokenize=False,
23 add_generation_prompt=True,
24 enable_thinking=True # Enable thinking mode (default)
25)
26model_inputs = tokenizer([text], return_tensors="pt").to(model.device)
27
28# Generate response
29generated_ids = model.generate(
30 **model_inputs,
31 max_new_tokens=32768,
32 temperature=0.6, # Recommended for thinking mode
33 top_p=0.95,
34 top_k=20,
35 min_p=0
36)
37
38# Parse thinking content and final response
39output_ids = generated_ids[0][len(model_inputs.input_ids[0]):].tolist()
40
41try:
42 # Find </think> token (151668)
43 index = len(output_ids) - output_ids[::-1].index(151668)
44except ValueError:
45 index = 0
46
47thinking_content = tokenizer.decode(output_ids[:index], skip_special_tokens=True).strip("\n")
48content = tokenizer.decode(output_ids[index:], skip_special_tokens=True).strip("\n")
49
50print("Thinking content:", thinking_content)
51print("Final answer:", content)1# Same setup as above...
2
3# Apply chat template with thinking mode disabled
4text = tokenizer.apply_chat_template(
5 messages,
6 tokenize=False,
7 add_generation_prompt=True,
8 enable_thinking=False # Disable thinking for efficiency
9)
10model_inputs = tokenizer([text], return_tensors="pt").to(model.device)
11
12# Generate with non-thinking parameters
13outputs = model.generate(
14 **model_inputs,
15 max_new_tokens=2048,
16 temperature=0.7, # Recommended for non-thinking mode
17 top_p=0.8,
18 top_k=20,
19 min_p=0
20)1# Use /think and /no_think tags to control behavior
2messages = [
3 {"role": "user", "content": "Explain quantum computing /no_think"}, # Quick response
4 {"role": "assistant", "content": "Quantum computing uses quantum bits..."},
5 {"role": "user", "content": "How does superposition work mathematically? /think"} # Detailed reasoning
6]1# Start server with reasoning parser
2# vllm serve cognitivecomputations/Qwen3-58B-Embiggened --enable-reasoning --reasoning-parser deepseek_r1
3
4from openai import OpenAI
5client = OpenAI(base_url="http://localhost:8000/v1", api_key="dummy")
6
7# Use with thinking mode
8response = client.chat.completions.create(
9 model="cognitivecomputations/Qwen3-58B-Embiggened",
10 messages=[{"role": "user", "content": "Solve: What is 15% of 250?"}],
11 extra_body={"enable_thinking": True}
12)1from transformers import BitsAndBytesConfig
2
3# 4-bit quantization for reduced memory usage
4bnb_config = BitsAndBytesConfig(
5 load_in_4bit=True,
6 bnb_4bit_compute_dtype=torch.bfloat16,
7 bnb_4bit_use_double_quant=True,
8)
9
10model = AutoModelForCausalLM.from_pretrained(
11 "cognitivecomputations/Qwen3-58B-Embiggened",
12 quantization_config=bnb_config,
13 device_map="auto"
14)Prompt: "How many r's are in strawberry?"
Thinking: Let me count the r's in "strawberry". S-t-r-a-w-b-e-r-r-y.
Going through each letter: s(no), t(no), r(yes, 1), a(no), w(no),
b(no), e(no), r(yes, 2), r(yes, 3), y(no).
Final answer: There are 3 r's in the word "strawberry".
Prompt: "What is the capital of France, and what is it famous for?"
Final answer (no thinking): Paris is the capital of France. It's famous for
the Eiffel Tower, the Louvre Museum, Notre-Dame Cathedral, and its rich
cultural heritage, fashion, and cuisine.1@misc{qwen3-embiggening-2025,
2 title={Qwen3 32B to 72B Architecture Expansion via Structure-Aware Interpolation},
3 author={[Your Name]},
4 year={2025},
5 howpublished={\url{https://github.com/yourusername/qwen3-embiggening}}
6}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-32B"
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)sglang>=0.4.6.post1 or vllm>=0.8.5 or to create an OpenAI-compatible API endpoint:python -m sglang.launch_server --model-path Qwen/Qwen3-32B --reasoning-parser qwen3vllm serve Qwen/Qwen3-32B --enable-reasoning --reasoning-parser deepseek_r1enable_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-32B"):
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-32B',
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 "rope_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 '{"rope_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":{"rope_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{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},
}