Views
No views yet
1from transformers import PreTrainedModel, LlamaConfig, LlamaModel, LlamaTokenizer
2import torch.nn as nn
3import torch
4from typing import Optional, List
5
6class LlamaRewardModel(PreTrainedModel):
7 config_class = LlamaConfig
8 def __init__(self, config):
9 super().__init__(config)
10 self.model = LlamaModel(config)
11 self.regression_head = nn.Linear(self.config.hidden_size, 1, bias=False)
12
13 def forward( # args are the same as LlamaForCausalLM
14 self,
15 input_ids: torch.LongTensor = None,
16 attention_mask: Optional[torch.Tensor] = None,
17 position_ids: Optional[torch.LongTensor] = None,
18 past_key_values: Optional[List[torch.FloatTensor]] = None,
19 inputs_embeds: Optional[torch.FloatTensor] = None,
20 labels: Optional[torch.LongTensor] = None,
21 use_cache: Optional[bool] = None,
22 output_attentions: Optional[bool] = None,
23 output_hidden_states: Optional[bool] = None,
24 return_dict: Optional[bool] = None,
25 ):
26
27 transformer_outputs = self.model(
28 input_ids,
29 attention_mask=attention_mask,
30 position_ids=position_ids,
31 past_key_values=past_key_values,
32 inputs_embeds=inputs_embeds,
33 )
34
35 hidden_states = transformer_outputs[0]
36 rewards = self.regression_head(hidden_states).squeeze(-1)
37
38 ends = attention_mask.cumsum(dim=1).argmax(dim=1).view(-1,1)
39 rewards = torch.gather(rewards, 1, ends)
40
41 return rewards
42
43ultrarm_template = """Human: {instruction}
44
45Assistant: {completion}"""
46
47dataset = [ # cases in webgpt
48 {"chosen":"Human: \"Who orders martinis \"\"shaken, not stirred\"\"?\"\nAssistant: Sean Connery's character, fictional British Secret Service agent James Bond, in the movie Goldfinger, stated that he preferred his martini to be \"shaken, not stirred\". [1] Some believe that Bond ordered his martini shaken because of the vodka it contained, as vodka was, for the most part, refined from potatoes (cheaper brands) which made the vodka oily. To disperse the oil, Bond ordered his martinis shaken. [2]","rejected":"Human: \"Who orders martinis \"\"shaken, not stirred\"\"?\"\nAssistant: Fleming's fictional British Secret Service agent James Bond orders his martini cocktail shaken, not stirred [1]. Bond's preferences for his martini are carried over to the films, where his orders are seen in both the 1961 film Dr. No and the 2006 film Casino Royale [1, 2]. In both films, Bond's subordinates copy his order, telling the bartender to keep the fruit with their drinks [2]. However, in the 2006 film, Bond appears irritated when the bartender asks if he would like his drink shaken or stirred [2]."},
49 {"chosen":"Human: Sural relates to which part of the body?\nAssistant: The sural region is the muscular swelling of the back of the leg below the knee, formed chiefly by the bellies of the gastrocnemius and soleus muscles [1,2].","rejected":"Human: Sural relates to which part of the body?\nAssistant: The Sural nerve runs down the side of the leg near the small saphenous vein, then passes forward below the lateral malleolus and continues on the outside of the foot as the lateral dorsal cutaneous nerve, which then communicates with the intermediate dorsal cutaneous nerve, which branches off to the side of the foot. [1]"}
50]
51
52
53tokenizer = LlamaTokenizer.from_pretrained("/data/UltraRM-13b")
54model = LlamaRewardModel.from_pretrained("/data/UltraRM-13b")
55
56for example in dataset:
57 inputs = tokenizer(example["chosen"], return_tensors="pt")
58 chosen_reward = model(**inputs).item()
59 inputs = tokenizer(example["rejected"], return_tensors="pt")
60 rejected_reward = model(**inputs).item()
61 print(chosen_reward - rejected_reward)
62
63# Output 1: 2.4158712085336447
64# Output 2: 0.1896953582763672@misc{cui2023ultrafeedback,
title={UltraFeedback: Boosting Language Models with High-quality Feedback},
author={Ganqu Cui and Lifan Yuan and Ning Ding and Guanming Yao and Wei Zhu and Yuan Ni and Guotong Xie and Zhiyuan Liu and Maosong Sun},
year={2023},
eprint={2310.01377},
archivePrefix={arXiv},
primaryClass={cs.CL}
}