Views
No views yet
1from typing import Optional, List, Dict
2import torch
3import torch.nn as nn
4from transformers import AutoConfig, AutoModel, AutoModelForCausalLM
5import torch.nn.functional as F
6from transformers import AutoTokenizer
7import os
8from safetensors.torch import load_file
9from huggingface_hub import snapshot_download
10
11def get_tokenizer(pretrain, model, padding_side="left", use_fast=True):
12 tokenizer = AutoTokenizer.from_pretrained(pretrain, trust_remote_code=True, use_fast=use_fast)
13 tokenizer.padding_side = padding_side
14 if tokenizer.pad_token is None:
15 tokenizer.pad_token = tokenizer.eos_token
16 tokenizer.pad_token_id = tokenizer.eos_token_id
17 model.config.pad_token_id = tokenizer.pad_token_id
18 return tokenizer
19
20def get_reward_model(base_causal_model, base_llm_model, value_head_dim: int, add_prompt_head: bool, is_general_preference: bool=False):
21 class CustomRewardModel(base_causal_model):
22
23 def __init__(self, config: AutoConfig):
24 super().__init__(config)
25 setattr(self, self.base_model_prefix, base_llm_model(config))
26 self.is_general_preference = is_general_preference
27
28 self.value_head = nn.Linear(config.hidden_size, value_head_dim, bias=False)
29 if add_prompt_head:
30 self.prompt_head = nn.Linear(config.hidden_size, value_head_dim // 2, bias=False)
31
32 def custom_forward(
33 self,
34 input_ids: torch.LongTensor = None,
35 attention_mask: Optional[torch.Tensor] = None,
36 return_output=False,
37 ) -> torch.Tensor:
38 position_ids = attention_mask.long().cumsum(-1) - 1
39 position_ids.masked_fill_(attention_mask == 0, 1)
40 outputs = getattr(self, self.base_model_prefix)(
41 input_ids, attention_mask=attention_mask, position_ids=position_ids
42 )
43 last_hidden_states = outputs["last_hidden_state"]
44
45 if not self.is_general_preference:
46 values = self.value_head(last_hidden_states).squeeze(-1)
47 # left padding in training mode
48 if self.training:
49 reward = values[:, -1]
50 else:
51 eos_indices = attention_mask.size(1) - 1 - attention_mask.long().fliplr().argmax(dim=1, keepdim=True)
52 reward = values.gather(dim=1, index=eos_indices).squeeze(1)
53 if return_output:
54 return reward, outputs
55 else:
56 return reward, None
57 else:
58 values = self.value_head(last_hidden_states)
59 # left padding in training mode
60 if self.training:
61 reward = values[:, -1, :]
62 reward = F.normalize(reward, p=2, dim=-1) # Shape will be [batch_size, value_head_dim]
63 else:
64 eos_indices = attention_mask.size(1) - 1 - attention_mask.long().fliplr().argmax(dim=1)
65 eos_indices = eos_indices.unsqueeze(1) # Change shape to [batch_size, 1]
66 reward_list = []
67 for dim in range(self.value_head.out_features):
68 reward_list.append(values[:,:,dim].gather(dim=1, index=eos_indices))
69 reward = torch.cat(reward_list, dim=1)
70 reward = F.normalize(reward, p=2, dim=-1) # Shape will be [batch_size, value_head_dim]
71 if return_output:
72 return reward, outputs
73 else:
74 return reward, None
75
76 def create_skew_symmetric_block_matrix(self, dim, device, dtype, prompt_hidden_states):
77 """
78 Create a batch of skew-symmetric block matrices where each matrix is data-dependent on
79 the corresponding prompt_hidden_states. Only the relevant block diagonal parts are generated.
80
81 Args:
82 - dim: Dimension of the square matrix (must be even).
83 - prompt_hidden_states: Tensor of shape [batch_size, hidden_dim].
84
85 Returns:
86 - batch_R_matrices: Tensor of shape [batch_size, dim, dim], with skew-symmetric block entries.
87 """
88 if hasattr(self, 'prompt_head'):
89 batch_size = prompt_hidden_states.shape[0]
90
91 # Ensure that dim is even, as we're creating blocks of size 2x2
92 assert dim % 2 == 0, "dim must be even for skew-symmetric block generation"
93
94 # Pass through the linear layer to get the block diagonal entries (half of the matrix's off-diagonal blocks)
95 block_values = self.prompt_head(prompt_hidden_states).view(batch_size, dim // 2)
96 block_values = torch.softmax(block_values, dim=-1)
97
98 # Create a batch of zero matrices [batch_size, dim, dim]
99 batch_R_matrices = torch.zeros((batch_size, dim, dim), device=device, dtype=dtype)
100
101 # Fill only the block diagonal entries with the learned values
102 for i in range(0, dim, 2):
103 batch_R_matrices[:, i, i + 1] = -block_values[:, i // 2]
104 batch_R_matrices[:, i + 1, i] = block_values[:, i // 2] # Skew-symmetric condition
105 else:
106 raise AttributeError("prompt_head is not defined. Ensure 'add_prompt_head' is set to True during initialization.")
107
108 return batch_R_matrices
109
110 return CustomRewardModel
111
112def generate_high_dim_result_with_prompt(model, value_head_dim, chosen_reward, rejected_reward, prompt_hidden_states):
113 R_matrix = model.create_skew_symmetric_block_matrix(value_head_dim, chosen_reward.device, chosen_reward.dtype, prompt_hidden_states)
114 if chosen_reward.device == rejected_reward.device == R_matrix.device:
115 transformed_chosen = torch.bmm(chosen_reward.view(chosen_reward.shape[0], 1, value_head_dim), R_matrix.transpose(1, 2))
116 result = torch.bmm(transformed_chosen, rejected_reward.view(rejected_reward.shape[0], value_head_dim, 1))
117 result = result.view(chosen_reward.shape[0])
118 return result
119
120class GPMPipeline:
121 def __init__(self, model_name_or_path, device=torch.device("cuda:0"), is_general_preference: bool=True, bf16: bool=True, truncation: bool=True, max_length: int=4096, padding: bool=True, tau: float=0.1):
122 self.device = device
123 self.is_general_preference = is_general_preference
124
125 self.truncation = truncation
126 self.max_length = max_length
127 self.padding = padding
128 self.tau = tau
129
130 config = AutoConfig.from_pretrained(model_name_or_path, trust_remote_code=True)
131 config._attn_implementation = "flash_attention_2"
132 base_class = AutoModel._model_mapping[type(config)]
133 base_causal_class = AutoModelForCausalLM._model_mapping.get(type(config), None)
134
135 try:
136 dir_path = snapshot_download(repo_id=model_name_or_path)
137 except Exception as e:
138 dir_path = model_name_or_path
139 combined_weights = {}
140 for filename in os.listdir(dir_path):
141 if filename.endswith(".safetensors"):
142 file_path = os.path.join(dir_path, filename)
143 weights = load_file(file_path)
144 combined_weights.update(weights)
145
146 if "value_head.weight" in combined_weights:
147 self.value_head_dim = combined_weights["value_head.weight"].shape[0]
148
149 self.add_prompt_head = True if "prompt_head.weight" in combined_weights else False
150
151 cls_class = get_reward_model(base_causal_class, base_class, add_prompt_head=self.add_prompt_head, value_head_dim=self.value_head_dim, is_general_preference=is_general_preference)
152
153 # configure model
154 self.model = cls_class.from_pretrained(
155 model_name_or_path,
156 config=config,
157 trust_remote_code=True,
158 torch_dtype=torch.bfloat16 if bf16 else "auto",
159 )
160
161 # configure tokenizer
162 self.tokenizer = get_tokenizer(model_name_or_path, self.model, "left", use_fast=True)
163 self.tokenizer.truncation_side = "right"
164
165 # prepare model
166 self.model.to(device)
167 self.model.eval()
168
169 def __call__(self, samples: List[List[Dict[str, str]]], return_prompt=False):
170 input_texts = [self.tokenizer.apply_chat_template(sample, tokenize=False) for sample in samples]
171
172 inputs = self.tokenizer(
173 input_texts,
174 truncation=True,
175 max_length=self.max_length,
176 padding=True,
177 return_tensors="pt",
178 ).to(self.device)
179
180 inputs["input_ids"][:, -1] = self.tokenizer.eos_token_id
181 inputs["attention_mask"][:, -1] = 1
182
183 with torch.no_grad():
184 rewards, outputs = self.model.custom_forward(**inputs, return_output=return_prompt)
185
186 chosen_response_len_list = []
187 if return_prompt:
188 prompt_texts = [self.tokenizer.apply_chat_template([sample[0]], tokenize=False) for sample in samples]
189 for i in range(len(input_texts)):
190 prompt_token = self.tokenizer(
191 prompt_texts[i],
192 max_length=self.max_length,
193 padding=False,
194 truncation=True,
195 return_tensors="pt",
196 )
197 chosen_token = self.tokenizer(
198 input_texts[i],
199 max_length=self.max_length,
200 padding=False,
201 truncation=True,
202 return_tensors="pt",
203 )
204 chosen_response_len = chosen_token["attention_mask"].sum() - prompt_token["attention_mask"].sum()
205 chosen_response_len_list.append(chosen_response_len)
206 chosen_response_len = torch.tensor(chosen_response_len_list).view(-1, 1).to(self.device)
207 if return_prompt:
208 chosen_last_hidden_states = outputs["last_hidden_state"]
209 prompt_end_index = chosen_last_hidden_states.size(1) - chosen_response_len - 1
210 prompt_end_index_expanded = prompt_end_index.unsqueeze(-1).expand(-1, -1, chosen_last_hidden_states.size(-1))
211 prompt_hidden_state = torch.gather(chosen_last_hidden_states, dim=1, index=prompt_end_index_expanded).squeeze(1)
212 return rewards, prompt_hidden_state
213 else:
214 return rewards
215
216
217prompt_text = "Describe the importance of reading books in today's digital age."
218response1 = "Books remain crucial in the digital era, offering in-depth knowledge and fostering critical thinking. They provide a unique, immersive experience that digital media can't replicate, contributing significantly to personal and intellectual growth."
219response2 = "Books are still useful for learning new things. They help you relax and can be a good break from screens."
220
221context1 = [
222 {"role": "user", "content": prompt_text},
223 {"role": "assistant", "content": response1}
224]
225
226context2 = [
227 {"role": "user", "content": prompt_text},
228 {"role": "assistant", "content": response2}
229]
230
231rm = GPMPipeline("general-preference/GPM-Gemma-2B")
232
233reward1, prompt_hidden_state = rm([context1], return_prompt=True)
234reward2 = rm([context2])
235
236result = generate_high_dim_result_with_prompt(rm.model, rm.value_head_dim, reward1, reward2, prompt_hidden_state)
237# score = result / rm.tau
238
239result_batch = result.float().cpu().detach().numpy().tolist()
240
241results = []
242[
243 results.append(1) if result > 0 else results.append(0)
244 for result in result_batch
245]
246
247print(result_batch)@article{zhang2024general,
title={General Preference Modeling with Preference Representations for Aligning Language Models},
author={Zhang, Yifan and Zhang, Ge and Wu, Yue and Xu, Kangping and Gu, Quanquan},
journal={arXiv preprint arXiv:2410.02197},
year={2024}
}