English
GretaYY commited on
Commit
606f02a
·
verified ·
1 Parent(s): 7897a8b

Upload mara_generator.py

Browse files
Files changed (1) hide show
  1. mara_generator.py +271 -0
mara_generator.py ADDED
@@ -0,0 +1,271 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ from loguru import logger as log
4
+ from torch.distributions import Categorical
5
+ from transformers import AutoTokenizer, AutoModelForCausalLM, LogitsProcessorList, TopKLogitsWarper, TopPLogitsWarper, \
6
+ TemperatureLogitsWarper
7
+
8
+
9
+ class DiscreteActor(nn.Module):
10
+ def __init__(self, state_dim, action_dim, hidden_dim=1024):
11
+ super(DiscreteActor, self).__init__()
12
+ self.state_dim = state_dim
13
+ self.action_dim = action_dim
14
+
15
+ self.ln = nn.LayerNorm(state_dim)
16
+ self.linear1 = nn.Linear(self.state_dim, hidden_dim)
17
+ self.linear2 = nn.Linear(hidden_dim, int(hidden_dim / 4))
18
+ self.output_linear = nn.Linear(int(hidden_dim / 4), self.action_dim)
19
+
20
+ def forward(self, state):
21
+ state = self.ln(state)
22
+ x = torch.relu(self.linear1(state))
23
+ x = torch.relu(self.linear2(x))
24
+ output = torch.softmax(self.output_linear(x), dim=1)
25
+ return output
26
+
27
+ def sample(self, state):
28
+ state = state.unsqueeze(0)
29
+ prob = self.forward(state)
30
+ distribution = Categorical(torch.Tensor(prob))
31
+ sample_action = distribution.sample().unsqueeze(-1).detach()
32
+ z = (prob == 0.0).float() * 1e-8
33
+ logprob = torch.log(prob + z)
34
+ greedy_action = torch.argmax(prob, dim=-1).unsqueeze(-1) # 1d tensor
35
+ return sample_action, prob, logprob, greedy_action
36
+
37
+ def select_action(self, state):
38
+ state = state.unsqueeze(0)
39
+ prob = self.forward(state)
40
+ action = torch.argmax(prob, dim=-1).unsqueeze(-1) # 1d tensor
41
+ action = action.squeeze().tolist()
42
+ return action
43
+
44
+
45
+ class MARAGenerator():
46
+ def __init__(
47
+ self,
48
+ agent_path, base_model_path, state_dim=4096, hidden_dim=1024, model_device="cuda:0",
49
+ max_new_token=2048, topk=40, topp=0.95, temperature=0.8
50
+ ):
51
+ # 文本生成模型初始化
52
+ self.base_model_path = base_model_path
53
+ self.model_device = torch.device(model_device)
54
+ self.base_model = AutoModelForCausalLM.from_pretrained(self.base_model_path).to(
55
+ self.model_device).eval().requires_grad_(False)
56
+ self.tokenizer = AutoTokenizer.from_pretrained(self.base_model_path)
57
+ self.tokenizer.pad_token_id = self.tokenizer.eos_token_id
58
+
59
+ self.topk = topk
60
+ self.topp = topp
61
+ self.max_new_token = max_new_token
62
+ self.temperature = temperature
63
+
64
+ # instantiate logits processors and wraper
65
+ self.logits_wraper = LogitsProcessorList(
66
+ [TopKLogitsWarper(self.topk), TopPLogitsWarper(top_p=self.topp),
67
+ TemperatureLogitsWarper(self.temperature)])
68
+
69
+ '''init agent'''
70
+ self.mara_agent = self.get_mara_agent(agent_path, state_dim, hidden_dim).to(self.model_device)
71
+ # log.info("mara_agent:{}".format(self.mara_agent))
72
+
73
+ self.instruction = "" # 输入指令
74
+ self.generate_ids = [] # 已生成的token
75
+ self.new_token_cnt = 0 # 已生成token数
76
+ self.curr_input_ids = None # 生成new_token的输入input_id,
77
+ self.curr_new_token_ids_list = None # 采样的new_token
78
+ self.sum_logprobs = None
79
+ self.curr_new_outputs_list = None # 以self.curr_input_ids+curr_new_token_id为输入的模型输出
80
+ self.next_new_outputs_list = None # 对应self.curr_new_outputs_list下一个token
81
+ self.is_new_token = True
82
+ self.chosen_indices = None
83
+ self.cand_chosen_idx = 0
84
+ self.last_outputs = None
85
+ self.attention_mask = None
86
+ self.position_id = None
87
+
88
+ # proxy_detail
89
+ self.gen_info = {"gen_token_cnt": 0, # 每个样例生成的结果长度,len(gen_token_cnt_list)=sample_cnt
90
+ "proxy_token_cnt": 0, # 需要经过agent进行决策的token长度,len(proxy_token_cnt_listt)=sample_cnt
91
+ "cand_token_dict": {}, # 每个决策位的候选token数,1<=cand_token_cnt<=topK,0表示不需要决策
92
+ "accept_index_dict": {} # 每个决策位的选择第几个token, accept_idx
93
+ }
94
+
95
+ def get_mara_agent(self, agent_path, state_dim, hidden_dim):
96
+ mara_agent = DiscreteActor(state_dim, 2, hidden_dim)
97
+ log.info('Begin to load mara agent model from {}'.format(agent_path))
98
+ try:
99
+ model_state_dict = torch.load(agent_path, map_location=self.model_device)
100
+ mara_agent.load_state_dict(model_state_dict)
101
+ except Exception as e:
102
+ log.error("load mara_agent occur error: {}".format(str(e)))
103
+ raise
104
+ return mara_agent
105
+
106
+ def get_input_text(self, instruction):
107
+ messages = [{"role": "user", "content": instruction}]
108
+ input_text = self.tokenizer.apply_chat_template(
109
+ messages,
110
+ tokenize=False,
111
+ add_generation_prompt=True
112
+ )
113
+ return input_text
114
+
115
+ def get_raw_output(self, instruction, do_sample=True):
116
+ if do_sample:
117
+ generation_config = {"do_sample": True, "max_new_tokens": self.max_new_token, "top_k": self.topk,
118
+ "top_p": self.topp, "temperature": self.temperature}
119
+ else:
120
+ generation_config = {"do_sample": False, "max_new_tokens": self.max_new_token}
121
+ input_text = self.get_input_text(instruction)
122
+ inputs = self.tokenizer(input_text, return_tensors="pt").to(self.model_device)
123
+
124
+ output_ids = self.base_model.generate(**inputs, **generation_config)[0]
125
+ response = self.tokenizer.decode(output_ids[len(inputs.input_ids[0]):], skip_special_tokens=True)
126
+ return {"answer": response}
127
+
128
+ def get_proxy_output(self, instruction):
129
+ input_text = self.get_input_text(instruction)
130
+ model_inputs = self.tokenizer(input_text, return_tensors="pt").to(self.model_device)
131
+ self.new_token_cnt = 0
132
+ self.generate_ids = []
133
+ self.gen_info = {"gen_token_cnt": 0, # 每个样例生成的结果长度,len(gen_token_cnt_list)=sample_cnt
134
+ "mara_token_cnt": 0, # 需要经过agent进行决策的token长度,len(proxy_token_cnt_list)=sample_cnt
135
+ "cand_token_dict": {}, # 每个决策位的候选token数,1<=cand_token_cnt<=topK,0表示不需要决策
136
+ "accept_index_dict": {} # 每个决策位的选择第几个token, accept_idx
137
+ }
138
+
139
+ input_ids = model_inputs.input_ids
140
+ self.attention_mask = model_inputs.attention_mask
141
+ self.curr_input_ids = input_ids
142
+ self.last_outputs = self.base_model(input_ids=input_ids,
143
+ attention_mask=self.attention_mask,
144
+ output_hidden_states=True)
145
+
146
+ # 一个token一个token地进行状态转移
147
+ self.is_new_token = True
148
+ self.cand_chosen_idx = 0
149
+ self.position_id = None
150
+ end_of_generate = False
151
+ while not end_of_generate:
152
+ end_of_generate, self.chosen_indices = self.rank_topk_ouputs_serial(self.curr_input_ids, self.last_outputs)
153
+ self.is_new_token = False
154
+ if end_of_generate:
155
+ break
156
+ accept_idx = 0
157
+ curr_new_outputs_list = []
158
+ for i in range(len(self.chosen_indices)):
159
+ _, curr_new_outputs = self.rank_topk_ouputs_serial(self.curr_input_ids, self.last_outputs)
160
+ curr_new_outputs_list.append(curr_new_outputs)
161
+ curr_state = curr_new_outputs['hidden_states'][-1][0, -1].to(self.model_device)
162
+
163
+ action = self.mara_agent.select_action(curr_state)
164
+ if action == 1:
165
+ accept_idx = i
166
+ break
167
+ self.is_new_token = True
168
+ # log.info(
169
+ # "new_token_cnt:{}/{}, accept_idx: {}".format(self.new_token_cnt, self.max_new_token, accept_idx))
170
+ accept_token_id = self.chosen_indices[accept_idx]
171
+ self.generate_ids.append(accept_token_id)
172
+ self.new_token_cnt += 1
173
+ self.gen_info["gen_token_cnt"] += 1
174
+ self.gen_info["mara_token_cnt"] += 1
175
+ if len(self.chosen_indices) not in self.gen_info["cand_token_dict"]:
176
+ self.gen_info["cand_token_dict"][len(self.chosen_indices)] = 1
177
+ else:
178
+ self.gen_info["cand_token_dict"][len(self.chosen_indices)] += 1
179
+ if accept_idx not in self.gen_info["accept_index_dict"]:
180
+ self.gen_info["accept_index_dict"][accept_idx] = 1
181
+ else:
182
+ self.gen_info["accept_index_dict"][accept_idx] += 1
183
+
184
+ self.curr_input_ids = torch.cat(
185
+ (self.curr_input_ids, torch.LongTensor([[accept_token_id]]).to(self.model_device)), dim=-1)
186
+ self.last_outputs = curr_new_outputs_list[accept_idx]
187
+
188
+ if accept_token_id == self.tokenizer.eos_token_id or self.new_token_cnt >= self.max_new_token:
189
+ end_of_generate = True
190
+ completion = self.tokenizer.decode(self.generate_ids, skip_special_tokens=True)
191
+ return {"answer": completion, "detail": self.gen_info}
192
+
193
+ def one_step_transfer(self, pre_input_ids, past_key_values, new_token_id):
194
+ attention_mask = torch.ones_like(pre_input_ids)
195
+ attention_mask = torch.cat([attention_mask, attention_mask.new_ones((attention_mask.shape[0], 1))], dim=-1)
196
+ position_ids = attention_mask.long().cumsum(-1) - 1
197
+ position_ids.masked_fill_(attention_mask == 0, 1)
198
+ position_id = position_ids[:, -1:].to(self.model_device)
199
+ new_token_id = new_token_id.to(self.model_device)
200
+
201
+ new_outputs = self.base_model(input_ids=new_token_id,
202
+ attention_mask=attention_mask.to(self.model_device),
203
+ position_ids=position_id,
204
+ past_key_values=past_key_values,
205
+ output_hidden_states=True)
206
+ new_input_ids = torch.cat((pre_input_ids, new_token_id), dim=-1)
207
+ return new_input_ids, new_outputs
208
+
209
+ def rank_topk_ouputs_serial(self, pre_input_ids, last_outputs):
210
+ if self.is_new_token:
211
+ end_of_generate = False
212
+ next_token_logits = last_outputs.logits[:, -1, :].clone() # (batch_size, vocab_size)
213
+ next_token_scores = nn.functional.log_softmax(next_token_logits, dim=-1) # (batch_size, vocab_size)
214
+ next_token_scores = self.logits_wraper(pre_input_ids, next_token_scores)
215
+ sorted_scores, sorted_indices = torch.sort(next_token_scores, descending=True)
216
+ chosen_indices = torch.masked_select(sorted_indices, sorted_scores != -float("Inf")).tolist()
217
+ # 当候选token数只有1个且不为终止eos_token_id时直接一步转移
218
+ while len(chosen_indices) == 1:
219
+ self.new_token_cnt += 1
220
+ self.gen_info["gen_token_cnt"] += 1
221
+ self.generate_ids.append(chosen_indices[0])
222
+ if chosen_indices[0] == self.tokenizer.eos_token_id or self.new_token_cnt >= self.max_new_token:
223
+ end_of_generate = True
224
+ return end_of_generate, None
225
+ else:
226
+ pre_input_ids, last_outputs = self.one_step_transfer(pre_input_ids,
227
+ past_key_values=last_outputs.past_key_values,
228
+ new_token_id=torch.LongTensor(
229
+ [[chosen_indices[0]]]))
230
+ self.curr_input_ids = pre_input_ids
231
+
232
+ next_token_logits = last_outputs.logits[:, -1, :].clone() # (batch_size, vocab_size)
233
+ next_token_scores = nn.functional.log_softmax(next_token_logits, dim=-1) # (batch_size, vocab_size)
234
+ next_token_scores = self.logits_wraper(pre_input_ids, next_token_scores)
235
+ sorted_scores, sorted_indices = torch.sort(next_token_scores, descending=True)
236
+ chosen_indices = torch.masked_select(sorted_indices, sorted_scores != -float("Inf")).tolist()
237
+
238
+ attention_mask = torch.ones_like(pre_input_ids)
239
+ attention_mask = torch.cat([attention_mask, attention_mask.new_ones((attention_mask.shape[0], 1))], dim=-1)
240
+ position_ids = attention_mask.long().cumsum(-1) - 1
241
+ position_ids.masked_fill_(attention_mask == 0, 1)
242
+ position_id = position_ids[:, -1:].to(self.model_device)
243
+ # log.info("len(chosen_indices):{}".format(len(chosen_indices)))
244
+ self.chosen_indices = chosen_indices
245
+ self.cand_chosen_idx = 0
246
+ self.attention_mask = attention_mask
247
+ self.position_id = position_id
248
+ self.last_outputs = last_outputs
249
+ return end_of_generate, chosen_indices
250
+ else:
251
+ new_token_id = torch.LongTensor([[self.chosen_indices[self.cand_chosen_idx]]])
252
+ curr_next_output = self.base_model(input_ids=new_token_id.to(self.model_device),
253
+ attention_mask=self.attention_mask.to(self.model_device),
254
+ position_ids=self.position_id.to(self.model_device),
255
+ past_key_values=self.last_outputs.past_key_values,
256
+ output_hidden_states=True)
257
+ self.cand_chosen_idx += 1
258
+ return False, curr_next_output
259
+
260
+
261
+ if __name__ == "__main__":
262
+ agent_path = "../proxy_rlhf/train_result/multi_reward/mistral_v3_2_1/run2/trained_model/actor_11000.pth"
263
+ base_model_path = "/mnt/public/model/huggingface/Mistral-7B-Instruct-v0.3"
264
+ proxy_generator = MARAGenerator(agent_path, base_model_path)
265
+ instruction = "Please introduce yourself."
266
+ raw_result = proxy_generator.get_raw_output(instruction, do_sample=False)
267
+ print("base model answer: ")
268
+ print(raw_result["answer"])
269
+ proxy_result = proxy_generator.get_proxy_output(instruction)
270
+ print("mara agent align answer: ")
271
+ print(proxy_result["answer"])