Views
No views yet
1import torch
2from transformers import AutoTokenizer, AutoModelForCausalLM
3
4model_name = "ScalableMath/llemma-7b-orm-prm800k-level-1to3-hf"
5model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype=torch.bfloat16, device_map="auto")
6
7tokenizer = AutoTokenizer.from_pretrained("EleutherAI/llemma_7b")
8
9qa_example = """# Question
10
11Convert the point $(0,3)$ in rectangular coordinates to polar coordinates. Enter your answer in the form $(r,\theta),$ where $r > 0$ and $0 \le \theta < 2 \pi.$
12
13# Solution
14
15To convert from rectangular to polar coordinates, I need to use the formulas $r = \sqrt{x^2 + y^2}$ and $\theta = \tan^{-1}(y/x).$
16
17In this case, $x = 0$ and $y = 3,$ so I can plug them into the formulas.
18
19For $r,$ I get $r = \sqrt{0^2 + 3^2} = \sqrt{9} = 3.$
20
21For $\theta,$ I get $\theta = \tan^{-1}(3/0).$
22
23This is undefined, since the tangent function is not defined at $0.$
24
25However, I can use the fact that the point $(0,3)$ lies on the positive $y$-axis, which has an angle of $\pi/2$ radians or $90^\circ.$
26
27Therefore, I can choose any angle in the range $(0,\pi/2)$ as the value of $\theta.$
28
29I will choose $\theta = \pi/2,$ since it is the simplest and most natural choice.
30
31Therefore, the polar coordinates of the point $(0,3)$ are $(3,\pi/2).$
32
33# Answer
34
35(3,\pi/2)"""
36
37begin_solution_tokens = tokenizer.encode("\n\n# Solution", add_special_tokens=False)[1:]
38scoring_tokens = tokenizer.encode("\n\n", add_special_tokens=False)[1:]
39eos_token = tokenizer.eos_token_id
40
41input_ids = tokenizer.encode(qa_example)
42
43begin_solution_flag = False
44
45candidate_positions = []
46
47for start_idx in range(len(input_ids)):
48 if tuple(input_ids[start_idx:start_idx+len(begin_solution_tokens)]) == tuple(begin_solution_tokens):
49 begin_solution_flag = True
50
51 if begin_solution_flag and tuple(input_ids[start_idx:start_idx+len(scoring_tokens)]) == tuple(scoring_tokens):
52 candidate_positions.append(start_idx)
53
54 if input_ids[start_idx] == eos_token:
55 candidate_positions.append(start_idx)
56 break
57
58# maybe delete the first and the second to last candidate_positions
59# because they are "\n\n" after "# Solution" and after "# Answer"
60del candidate_positions[0]
61del candidate_positions[-2]
62
63input_tensor = torch.tensor([input_ids])
64candidate_positions = torch.tensor(candidate_positions)
65
66with torch.no_grad():
67 logits = model(input_tensor).logits
68 scores =logits.mean(dim=-1)
69 step_scores = scores[0][candidate_positions]
70 step_probs = torch.sigmoid(step_scores)
71
72print(step_probs)
73
74# only the last logprob is orm's output
75# tensor([0.4531, 0.3882, 0.3748, 0.4785, 0.4087, 0.3166, 0.3040, 0.2295, 0.2628, 0.2568])