Views
No views yet
1import torch
2from transformers import AutoTokenizer, AutoModelForCausalLM
3
4model_name = "Yingqian/dream_prm_math_7b" # <-- replace with this repo name
5
6tokenizer = AutoTokenizer.from_pretrained(model_name)
7model = AutoModelForCausalLM.from_pretrained(
8 model_name,
9 torch_dtype=torch.bfloat16,
10 device_map="auto",
11)
12
13# padding settings used in our code
14tokenizer.padding_side = "right"
15tokenizer.pad_token = tokenizer.eos_token
16model.config.pad_token_id = model.config.eos_token_id
17
18model.eval()1import torch
2
3def get_reward(conversation):
4 """
5 conversation: list of dicts, e.g.
6 [
7 {"role": "user", "content": "<question and partial reasoning>"},
8 {"role": "assistant", "content": "+"},
9 ]
10 Returns: float in (0, 1), probability of "+".
11 """
12
13 device = next(model.parameters()).device
14
15 # Apply the model's chat template
16 input_ids = tokenizer.apply_chat_template(
17 conversation,
18 return_tensors="pt"
19 ).to(device)
20
21 # IDs of "+" and "-" (last token of each encoding)
22 plus_id = tokenizer.encode("+")[-1]
23 minus_id = tokenizer.encode("-")[-1]
24 candidate_ids = [plus_id, minus_id]
25
26 with torch.no_grad():
27 logits = model(input_ids).logits
28 # In our experiments we read the logits from the 4th token from the end
29 token_logits = logits[:, -4, candidate_ids]
30 probs = token_logits.softmax(dim=-1)
31
32 # Probability that the label is "+"
33 return probs[0, 0].item()1question = "Q: If 2x + 3 = 11, what is x?"
2partial_step = "Step 1: Subtract 3 from both sides to get 2x = 8."
3reward_context = question + "\n" + partial_step
4
5conversation = [
6 {"role": "user", "content": reward_context},
7 {"role": "assistant", "content": "+"}, # target label
8]
9
10score = get_reward(conversation)
11print("Reward score (probability of '+'):", score)