Views
No views yet
Qwen/Qwen3-14B) and merge these adapters to use the model.pip install torch transformers peft bitsandbytes accelerate1import torch
2from transformers import AutoTokenizer, AutoModelForSequenceClassification
3from peft import PeftModel
4
5# Load base model and LoRA adapters
6base_model = AutoModelForSequenceClassification.from_pretrained(
7 "Qwen/Qwen3-14B",
8 num_labels=65,
9 torch_dtype=torch.bfloat16,
10 device_map="auto",
11 trust_remote_code=True
12)
13
14model = PeftModel.from_pretrained(
15 base_model,
16 "jatinmehra/Qwen-3-14B-MATH-Misconception-Annotation-Project"
17)
18
19# Merge adapters for faster inference (optional but recommended)
20model = model.merge_and_unload()
21
22# Load tokenizer
23tokenizer = AutoTokenizer.from_pretrained(
24 "Qwen/Qwen3-14B",
25 trust_remote_code=True
26)
27
28# Move to GPU and set to eval mode
29model = model.cuda()
30model.eval()1import torch
2from transformers import AutoTokenizer, AutoModelForSequenceClassification, BitsAndBytesConfig
3from peft import PeftModel
4
5# Configure 4-bit quantization
6bnb_config = BitsAndBytesConfig(
7 load_in_4bit=True,
8 bnb_4bit_use_double_quant=True,
9 bnb_4bit_quant_type="nf4",
10 bnb_4bit_compute_dtype=torch.bfloat16
11)
12
13# Load quantized base model and LoRA adapters
14base_model = AutoModelForSequenceClassification.from_pretrained(
15 "Qwen/Qwen3-14B",
16 num_labels=2675,
17 quantization_config=bnb_config,
18 device_map="auto",
19 trust_remote_code=True
20)
21
22model = PeftModel.from_pretrained(
23 base_model,
24 "jatinmehra/Qwen-3-14B-MATH-Misconception-Annotation-Project"
25)
26
27tokenizer = AutoTokenizer.from_pretrained(
28 "Qwen/Qwen3-14B",
29 trust_remote_code=True
30)
31
32model.eval()1import numpy as np
2
3# Example input (format used during training)
4question = "Which of the following is equivalent to 3(2x + 5)?"
5answer = "6x + 5"
6is_correct = "No"
7explanation = "I distributed the 3 to 2x but forgot to distribute it to 5"
8
9# Format input
10input_text = f"""Question: {question}
11Answer: {answer}
12Is Correct Answer: {is_correct}
13Student Explanation: {explanation}"""
14
15# Tokenize
16inputs = tokenizer(
17 input_text,
18 truncation=True,
19 max_length=256,
20 return_tensors="pt"
21).to(model.device)
22
23# Get predictions
24with torch.no_grad():
25 outputs = model(**inputs)
26 logits = outputs.logits
27 probs = torch.nn.functional.softmax(logits, dim=-1)
28
29# Get top 3 predictions
30top_k = 3
31top_probs, top_indices = torch.topk(probs, top_k, dim=-1)
32
33print(f"Top {top_k} Predictions:")
34for i in range(top_k):
35 class_id = top_indices[0][i].item()
36 confidence = top_probs[0][i].item()
37 print(f"{i+1}. Class {class_id}: {confidence:.4f}")1import pandas as pd
2
3def predict_batch(texts, batch_size=8):
4 """Process multiple examples efficiently"""
5 all_probs = []
6
7 for i in range(0, len(texts), batch_size):
8 batch_texts = texts[i:i+batch_size]
9
10 # Tokenize batch
11 inputs = tokenizer(
12 batch_texts,
13 truncation=True,
14 max_length=256,
15 padding=True,
16 return_tensors="pt"
17 ).to(model.device)
18
19 # Inference
20 with torch.no_grad():
21 outputs = model(**inputs)
22 probs = torch.nn.functional.softmax(outputs.logits, dim=-1)
23 all_probs.append(probs.cpu().numpy())
24
25 return np.vstack(all_probs)
26
27# Example usage
28test_data = pd.read_csv("test.csv")
29formatted_texts = [
30 f"Question: {row['QuestionText']}\n"
31 f"Answer: {row['MC_Answer']}\n"
32 f"Is Correct Answer: {row['IsCorrect']}\n"
33 f"Student Explanation: {row['StudentExplanation']}"
34 for _, row in test_data.iterrows()
35]
36
37predictions = predict_batch(formatted_texts, batch_size=8)
38top3_classes = np.argsort(-predictions, axis=1)[:, :3]1lora_config = LoraConfig(
2 r=16, # Low-rank dimension
3 lora_alpha=32, # Scaling factor
4 target_modules=[ # Attention & MLP layers
5 "q_proj",
6 "v_proj",
7 "o_proj",
8 "gate_proj",
9 "up_proj",
10 "down_proj"
11 ],
12 lora_dropout=0.1, # Regularization
13 bias="none",
14 task_type="SEQ_CLS", # Sequence classification
15 modules_to_save=["score"] # Save classification head
16)| Hyperparameter | Value |
|---|---|
| Base Model | Qwen/Qwen3-14B |
| Epochs | 3 |
| Learning Rate | 2e-4 |
| LR Scheduler | Cosine with warmup |
| Warmup Ratio | 0.1 |
| Batch Size | 8 per device |
| Gradient Accumulation | 4 steps |
| Effective Batch Size | 128 (8 × 4 devices × 4 accumulation) |
| Max Sequence Length | 256 tokens |
| Precision | bfloat16 |
| Gradient Checkpointing | Enabled |
| Quantization | 4-bit NF4 |
| GPUs | 4×NVIDIA L4 (24GB) |
| Training Time | 11 hours 34 minutes |
Question: {question_text}
Answer: {student_answer}
Is Correct Answer: {Yes/No}
Student Explanation: {student_reasoning}1@misc{qwen3-14b-math-misconception-lora,
2 author = {Jatin Mehra},
3 title = {Qwen3-14B LoRA for Math Misconception Detection},
4 year = {2025},
5 publisher = {HuggingFace},
6 howpublished = {\url{https://huggingface.co/jatinmehra/Qwen-3-14B-MATH-Misconception-Annotation-Project}},
7 note = {Silver Medal Solution (45th place) in Kaggle MAP Competition}
8}
9
10@inproceedings{map-competition-2025,
11 title = {MAP: Charting Student Math Misunderstandings},
12 author = {Vanderbilt University and The Learning Agency},
13 year = {2025},
14 organization = {Kaggle}
15}