1!pip install --upgrade torchao
2
3import torch
4from transformers import AutoModelForCausalLM, AutoTokenizer
5from peft import PeftModel
6
7base_model_id = "Qwen/Qwen3-1.7B"
8adapter_id = "ehzawad/qwen3_1_7b-gsm8k-grpo"
9
10# 1. Load tokenizer
11tokenizer = AutoTokenizer.from_pretrained(adapter_id)
12if tokenizer.pad_token is None:
13 tokenizer.pad_token = tokenizer.eos_token
14tokenizer.padding_side = "left"
15
16# 2. Load base model
17model = AutoModelForCausalLM.from_pretrained(
18 base_model_id,
19 torch_dtype=torch.bfloat16,
20 device_map="auto"
21)
22
23# 3. Load and apply adapter
24model = PeftModel.from_pretrained(model, adapter_id)
25model.eval()
26
27# 4. Prepare prompt
28system_prompt = "You are a careful math reasoning assistant. Solve the problem step by step, but keep the solution concise. Use only the needed calculations, avoid repetition, and end with exactly one final answer in the form \\boxed{answer}."
29question = "Janet has 3 bags with 4 apples each. She gives away 5 apples and then took back 4. Then ate 3 apples and then friends took away 2 apples and then he boughts 5 apples again. How many remain?"
30
31messages = [
32 {"role": "system", "content": system_prompt},
33 {"role": "user", "content": question}
34]
35
36# 5. Format and Generate
37try:
38 inputs = tokenizer.apply_chat_template(messages, tokenize=True, add_generation_prompt=True, enable_thinking=True, return_dict=True, return_tensors="pt").to(model.device)
39except TypeError:
40 inputs = tokenizer.apply_chat_template(messages, tokenize=True, add_generation_prompt=True, return_dict=True, return_tensors="pt").to(model.device)
41
42with torch.inference_mode():
43 outputs = model.generate(
44 **inputs,
45 max_new_tokens=512,
46 do_sample=True,
47 temperature=0.6,
48 pad_token_id=tokenizer.pad_token_id,
49 eos_token_id=tokenizer.eos_token_id
50 )
51
52print(tokenizer.decode(outputs[0][inputs['input_ids'].shape[-1]:], skip_special_tokens=True))
53
54
55