Views
No views yet
Accuracy shot by_letter category
44.802378 0shot True STEM
43.143675 0shot True Language
44.232437 0shot True Social science
43.439673 0shot True Others
49.260523 0shot True Humanities
[5 rows x 5 columns]
{'Social science': np.int64(6918), 'Language': np.int64(6288), 'Humanities': np.int64(4395), 'Others': np.int64(4169), 'STEM': np.int64(2443)}
Model : Malaysian-Qwen3-4B-unsloth-bnb-4bit-v1.0
Metric : first
Shot : 0shot
average accuracy 44.80237888737455
accuracy for STEM 43.143675808432256
accuracy for Language 43.86132315521628
accuracy for Social science 44.232437120555076
accuracy for Others 43.439673782681695
accuracy for Humanities 49.26052332195677| 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 |
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
2model_name = "Qwen/Qwen3-4B"
3# load the tokenizer and the model
4tokenizer = AutoTokenizer.from_pretrained(model_name)
5model = AutoModelForCausalLM.from_pretrained(
6 model_name,
7 torch_dtype="auto",
8 device_map="auto"
9)
10# prepare the model input
11prompt = "Give me a short introduction to large language model."
12messages = [
13 {"role": "user", "content": prompt}
14]
15text = tokenizer.apply_chat_template(
16 messages,
17 tokenize=False,
18 add_generation_prompt=True,
19 enable_thinking=True # Switches between thinking and non-thinking modes. Default is True.
20)
21model_inputs = tokenizer([text], return_tensors="pt").to(model.device)
22# conduct text completion
23generated_ids = model.generate(
24 **model_inputs,
25 max_new_tokens=32768
26)
27output_ids = generated_ids[0][len(model_inputs.input_ids[0]):].tolist()
28# parsing thinking content
29try:
30 # rindex finding 151668 (</think>)
31 index = len(output_ids) - output_ids[::-1].index(151668)
32except ValueError:
33 index = 0
34thinking_content = tokenizer.decode(output_ids[:index], skip_special_tokens=True).strip("\n")
35content = tokenizer.decode(output_ids[index:], skip_special_tokens=True).strip("\n")
36print("thinking content:", thinking_content)
37print("content:", content)vllm>=0.8.5 or sglang>=0.4.5.post2 to create an OpenAI-compatible API endpoint:vllm serve Qwen/Qwen3-4B --enable-reasoning --reasoning-parser deepseek_r1python -m sglang.launch_server --model-path Qwen/Qwen3-4B --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
2class QwenChatbot:
3 def __init__(self, model_name="Qwen/Qwen3-4B"):
4 self.tokenizer = AutoTokenizer.from_pretrained(model_name)
5 self.model = AutoModelForCausalLM.from_pretrained(model_name)
6 self.history = []
7 def generate_response(self, user_input):
8 messages = self.history + [{"role": "user", "content": user_input}]
9 text = self.tokenizer.apply_chat_template(
10 messages,
11 tokenize=False,
12 add_generation_prompt=True
13 )
14 inputs = self.tokenizer(text, return_tensors="pt")
15 response_ids = self.model.generate(**inputs, max_new_tokens=32768)[0][len(inputs.input_ids[0]):].tolist()
16 response = self.tokenizer.decode(response_ids, skip_special_tokens=True)
17 # Update history
18 self.history.append({"role": "user", "content": user_input})
19 self.history.append({"role": "assistant", "content": response})
20 return response
21# Example Usage
22if __name__ == "__main__":
23 chatbot = QwenChatbot()
24 # First input (without /think or /no_think tags, thinking mode is enabled by default)
25 user_input_1 = "How many r's in strawberries?"
26 print(f"User: {user_input_1}")
27 response_1 = chatbot.generate_response(user_input_1)
28 print(f"Bot: {response_1}")
29 print("----------------------")
30 # Second input with /no_think
31 user_input_2 = "Then, how many r's in blueberries? /no_think"
32 print(f"User: {user_input_2}")
33 response_2 = chatbot.generate_response(user_input_2)
34 print(f"Bot: {response_2}")
35 print("----------------------")
36 # Third input with /think
37 user_input_3 = "Really? /think"
38 print(f"User: {user_input_3}")
39 response_3 = chatbot.generate_response(user_input_3)
40 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.
1import os
2from qwen_agent.agents import Assistant
3# Define LLM
4llm_cfg = {
5 'model': 'Qwen3-4B',
6 # Use the endpoint provided by Alibaba Model Studio:
7 # 'model_type': 'qwen_dashscope',
8 # 'api_key': os.getenv('DASHSCOPE_API_KEY'),
9 # Use a custom endpoint compatible with OpenAI API:
10 'model_server': 'http://localhost:8000/v1', # api_base
11 'api_key': 'EMPTY',
12 # Other parameters:
13 # 'generate_cfg': {
14 # # Add: When the response content is `<think>this is the thought</think>this is the answer;
15 # # Do not add: When the response has been separated by reasoning_content and content.
16 # 'thought_in_content': True,
17 # },
18}
19# Define Tools
20tools = [
21 {'mcpServers': { # You can specify the MCP configuration file
22 'time': {
23 'command': 'uvx',
24 'args': ['mcp-server-time', '--local-timezone=Asia/Shanghai']
25 },
26 }
27 },
28 'code_interpreter', # Built-in tools
29]
30# Define Agent
31bot = Assistant(llm=llm_cfg, function_list=tools)
32# Streaming generation
33messages = [{'role': 'user', 'content': 'What time is it?'}]
34for responses in bot.run(messages=messages):
35 pass
36print(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}
}