1from peft import PeftModel
2from transformers import AutoModelForCausalLM, AutoTokenizer
3import torch
45# Load base model and tokenizer6model_name ="Qwen/Qwen3-0.6B"7model = AutoModelForCausalLM.from_pretrained(8 model_name,9 torch_dtype=torch.float16,10 device_map="auto"11)12tokenizer = AutoTokenizer.from_pretrained(model_name)1314# Load LoRA adapter15model = PeftModel.from_pretrained(model,"YOUR_USERNAME/qwen3-mmlu-classifier")16model.eval()1718# Prepare prompt19question ="What are the key principles of quantum mechanics?"20prompt =f"""You are an expert academic classifier. Classify the following question into exactly ONE category. Respond with ONLY the category name.
2122Categories: biology, business, chemistry, computer science, economics, engineering, health, history, law, math, other, philosophy, physics, psychology
2324Examples:
25Q: What is the optimal capital structure for a corporation?
26A: business
2728Q: How do neurons transmit signals?
29A: biology
3031Q: What are the principles of contract law?
32A: law
3334Now classify this question:
35Q: {question}36A:"""3738# Generate classification39inputs = tokenizer(prompt, return_tensors="pt").to(model.device)40with torch.no_grad():41 outputs = model.generate(42**inputs,43 max_new_tokens=10,44 temperature=0.1,45 do_sample=False,46 pad_token_id=tokenizer.pad_token_id
47)4849# Parse result50generated_text = tokenizer.decode(outputs[0], skip_special_tokens=True)51category = generated_text.split("A:")[-1].strip().split()[0]52print(f"Category: {category}")# Output: physics
Batch Classification
python
1questions =[2"What is the best strategy for corporate mergers?",3"How does cognitive bias affect decision making?",4"Explain the legal requirements for contract formation"5]67for q in questions:8 prompt =f"Q: {q}\nA:"# Simplified for batch9 inputs = tokenizer(prompt, return_tensors="pt").to(model.device)10 outputs = model.generate(**inputs, max_new_tokens=5)11 category = tokenizer.decode(outputs[0], skip_special_tokens=True).split("A:")[-1].strip()12print(f"{q[:50]}... -> {category}")
📊 Performance
Metric
Value
Validation Accuracy
65-70%
Training Loss (final)
0.12
Validation Loss (best)
0.82 (epoch 4)
Training Samples
1,192
Validation Samples
398
Why Generative Approach?
Unlike traditional classification heads, this model generates the category name as text:
Approach
Qwen3 Performance
Reason
Classification Head
❌ 16%
Decoder models don't have good sentence representations
Generative (This)
✅ 65-70%
Natural for decoder models, aligned with pre-training
The model was trained with this instruction template:
You are an expert academic classifier. Classify the following question into exactly ONE category. Respond with ONLY the category name.
Categories: biology, business, chemistry, computer science, economics, engineering, health, history, law, math, other, philosophy, physics, psychology
Examples:
Q: What is the optimal capital structure for a corporation?
A: business
Q: How do neurons transmit signals?
A: biology
Q: What are the principles of contract law?
A: law
Now classify this question:
Q: {question}
A:
Important: The few-shot examples help the small 0.6B model learn the task better.
⚠️ Limitations
Model Size: Qwen3-0.6B is relatively small (596M params)
Larger models (1.8B, 3B) would achieve 75-85% accuracy
Overfitting: Best performance at epoch 4 (eval_loss: 0.82)
Later epochs showed overfitting (eval_loss increased to 1.12)
Multi-word Categories: Requires careful parsing
"computer science" needs special handling vs "computer"
Generative Overhead: Slower than classification head
Needs to generate tokens vs single forward pass
MMLU-Pro Specific: Trained on academic questions
May not generalize well to other domains
🔄 Comparison with Other Approaches
Model
Approach
Accuracy
Speed
BERT-base
Classification head
85-90%
Fast
ModernBERT
Classification head
87-92%
Fast
Qwen3-0.6B (this)
Generative
65-70%
Medium
Qwen3-1.8B
Generative
75-80%
Slower
Why use this over BERT?
✅ Generative models (better for complex reasoning)
✅ Instruction-following format (flexible)
✅ Can add explanations ("This is physics because...")
❌ Lower accuracy than BERT for pure classification