Views
No views yet
1
2import torch
3from transformers import AutoModel, AutoTokenizer
4import torch.nn.functional as F
5
6# load model and tokenizer
7
8model_name = "agadetskii/Qwen2.5-14B-Instruct-uPRM-T80-adapters"
9
10tokenizer = AutoTokenizer.from_pretrained(
11 model_name,
12 trust_remote_code=True,
13 force_download=True
14)
15
16model = AutoModel.from_pretrained(
17 model_name,
18 trust_remote_code=True,
19 torch_dtype="bfloat16",
20 device_map="auto", # or "cuda" for single GPU
21 attn_implementation="flash_attention_2",
22)
23
24device = torch.device("cuda")
25model = model.to(device)
26
27
28# example data
29
30DEFAULT_SYSTEM_PROMPT = """You are a strict mathematical reasoning judge.
31
32Your task is to evaluate one individual reasoning step of a math problem at a time.
33
34- If the step is mathematically correct, respond with `+`.
35- If the step is mathematically incorrect or logically flawed, respond with `-`.
36- Do not provide any explanation, comment, or feedback — only respond with `+` or `-`, and nothing else.
37- Each input is either a single reasoning step or a new problem followed by its first reasoning step. In both cases, evaluate only the validity of the reasoning step.
38- For each new problem, once you determine that a step is incorrect, you must consider all subsequent steps for that problem to also be incorrect, and respond with `-` for them as well.
39
40Your response must only be one of these two symbols: `+` or `-`.
41"""
42
43data = {
44 "system": DEFAULT_SYSTEM_PROMPT,
45 "query": "Sue lives in a fun neighborhood. One weekend, the neighbors decided to play a prank on Sue. On Friday morning, the neighbors placed 18 pink plastic flamingos out on Sue's front yard. On Saturday morning, the neighbors took back one third of the flamingos, painted them white, and put these newly painted white flamingos back out on Sue's front yard. Then, on Sunday morning, they added another 18 pink plastic flamingos to the collection. At noon on Sunday, how many more pink plastic flamingos were out than white plastic flamingos?",
46 "response": [
47 "To find out how many more pink plastic flamingos were out than white plastic flamingos at noon on Sunday, we can break down the problem into steps. First, on Friday, the neighbors start with 18 pink plastic flamingos.",
48 "On Saturday, they take back one third of the flamingos. Since there were 18 flamingos, (1/3 \\times 18 = 6) flamingos are taken back. So, they have (18 - 6 = 12) flamingos left in their possession. Then, they paint these 6 flamingos white and put them back out on Sue's front yard. Now, Sue has the original 12 pink flamingos plus the 6 new white ones. Thus, by the end of Saturday, Sue has (12 + 6 = 18) pink flamingos and 6 white flamingos.",
49 "On Sunday, the neighbors add another 18 pink plastic flamingos to Sue's front yard. By the end of Sunday morning, Sue has (18 + 18 = 36) pink flamingos and still 6 white flamingos.",
50 "To find the difference, subtract the number of white flamingos from the number of pink flamingos: (36 - 6 = 30). Therefore, at noon on Sunday, there were 30 more pink plastic flamingos out than white plastic flamingos. The answer is (\\boxed{30})."
51 ]
52}
53
54messages = [
55 {"role": "system", "content": data['system']},
56]
57for i in range(len(data["response"])):
58 if i == 0:
59 usr_msg = data["query"] + " " + data["response"][i]
60 else:
61 usr_msg = data["response"][i]
62 messages.append({"role": "user", "content": usr_msg})
63 messages.append({"role": "assistant", "content": "<|*|>"})
64
65
66conversation_str = tokenizer.apply_chat_template(
67 messages,
68 tokenize=False,
69 add_generation_prompt=False
70)
71
72input_ids = tokenizer.encode(
73 conversation_str,
74 return_tensors="pt",
75).to(model.device)
76
77with torch.no_grad():
78 outputs = model(input_ids=input_ids)
79
80
81
82def make_step_rewards(logits, token_masks):
83 probabilities = F.softmax(logits, dim=-1)
84 probabilities = probabilities * token_masks.unsqueeze(-1) # bs, seq_len, num_labels
85
86 all_scores_res = []
87 for i in range(probabilities.size(0)):
88 sample = probabilities[i] # seq_len, num_labels
89 positive_probs = sample[sample != 0].view(-1, 2)[:, 0] # valid_tokens, num_labels
90 non_zero_elements_list = positive_probs.cpu().tolist()
91 all_scores_res.append(non_zero_elements_list)
92 return all_scores_res
93
94
95step_sep_id = tokenizer.encode("<|*|>")[0]
96token_masks = (input_ids == step_sep_id)
97step_reward = make_step_rewards(outputs[0], token_masks)
98print(step_reward)
99# returns [[0.9668280482292175, 0.2960759401321411, 0.9475431442260742, 0.9833130240440369]]
100