Views
No views yet

1import torch
2import re
3from transformers import AutoModelForCausalLM, AutoTokenizer
4
5def get_user_prompt(prompt: str) -> str:
6 match = re.search(r"<\|im_start\|>user\s*(.*?)\s*<\|im_end\|>", prompt, re.DOTALL)
7 return match.group(1).strip() if match else "\n".join(
8 line.strip()[4:].strip() if line.strip().lower().startswith("user") else line
9 for line in prompt.splitlines() if not line.strip().lower().startswith("system")
10 ).strip()
11
12def get_assistant_response(text: str) -> str:
13 match = re.search(r"<\|im_start\|>assistant\s*(.*?)\s*<\|im_end\|>", text, re.DOTALL)
14 return match.group(1).strip() if match else "\n".join(
15 line for line in text.splitlines() if not line.strip().lower().startswith("assistant")
16 ).strip()
17
18model_name = "Jaward/smollm2_360m_grpo_gsm8k_reasoner"
19device = "cuda" if torch.cuda.is_available() else "cpu"
20
21tokenizer = AutoTokenizer.from_pretrained(model_name)
22model = AutoModelForCausalLM.from_pretrained(model_name).to(device)
23
24messages = [
25 {"role": "system", "content": "Please respond in this specific format ONLY:\n<thinking>\n input your reasoning behind your answer in between these reasoning tags.\n</thinking>\n<answer>\nyour answer in between these answer tags.\n</answer>\n"},
26 {"role": "user", "content": "If there are 12 cookies in a dozen and you have 5 dozen, how many cookies do you have?"}
27]
28
29input_text = tokenizer.apply_chat_template(messages, tokenize=False)
30inputs = tokenizer.encode(input_text, return_tensors="pt").to(device)
31outputs = model.generate(inputs, max_new_tokens=100, temperature=0.2, top_p=0.9, do_sample=True, use_cache=False)
32
33decoded = tokenizer.decode(outputs[0], skip_special_tokens=False)
34
35print("Question:\n", get_user_prompt(input_text))
36print("\nResponse:\n", get_assistant_response(decoded))
37
38# OUTPUT:
39"""
40Question:
41If there are 12 cookies in a dozen and you have 5 dozen, how many cookies do you have?
42
43Response:
44<thinking>
4512 cookies in a dozen is 12/12 = 1.
465 dozen is 5 * 12 = 60.
47So 60 cookies in total.
48</thinking>
49<answer>
50You have 60 cookies.
51"""