-
Notifications
You must be signed in to change notification settings - Fork 5
/
generate.py
339 lines (295 loc) · 13.2 KB
/
generate.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
import os
import sys
import argparse
import re
import torch
from torch.utils.data.distributed import DistributedSampler
import transformers
from transformers import (
HfArgumentParser,
AutoTokenizer,
AutoModelForCausalLM,
AutoModelForSeq2SeqLM,
GenerationConfig,
DataCollatorForSeq2Seq,
PreTrainedTokenizerBase,
load_tool,
LogitsProcessor,
set_seed,
)
from torch.utils.data import Dataset, DataLoader
from dataclasses import dataclass, asdict, field
from typing import Optional, Dict, Sequence, List, Any, Union
import torch.distributed as dist
from torch.nn.parallel import DistributedDataParallel as DDP
import json
from tqdm import tqdm
import copy
from torch.cuda.amp import autocast
from datasets import load_dataset, concatenate_datasets
from datasets.utils.logging import disable_progress_bar
disable_progress_bar()
from ruamel.yaml import YAML
import hydra
from omegaconf import DictConfig, OmegaConf
from dotenv import load_dotenv
load_dotenv()
DATA_DIR = os.environ.get("DATA_DIR")
from data_modules import GSM8K, GSM8KForLLAMA
def sequence_gather(s, world_size, pad_tok_id):
local_size = torch.tensor(s.size(), device=s.device)
all_sizes = [torch.zeros_like(local_size) for _ in range(world_size)]
dist.all_gather(all_sizes, local_size)
max_length = max(size[1] for size in all_sizes)
length_diff = max_length.item() - local_size[1].item()
if length_diff:
pad_size = (s.shape[0], length_diff)
padding = torch.ones(pad_size, device=s.device, dtype=s.dtype)*pad_tok_id
s = torch.concat((s, padding), dim = -1)
gathered_s = [torch.ones_like(s)*pad_tok_id for _ in range(world_size)]
dist.all_gather(gathered_s, s)
return gathered_s
def tool_fn(expr):
raw_result = eval(expr)
f_res = float(raw_result)
if abs(int(f_res)-f_res) < 0.0001:
return str(int(f_res))
else:
return str(round(f_res, 2))
class CustomLogitsProcessor(LogitsProcessor):
def __init__(self, tokenizer, tool):
self.tokenizer = tokenizer
self.tool = tool
self.eq_token_id = tokenizer.convert_tokens_to_ids('▁=')
self.right_token_id = tokenizer.convert_tokens_to_ids(']')
self.left_token_id = tokenizer.convert_tokens_to_ids('▁[')
def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
bz = scores.size(0)
for b in range(bz):
if input_ids[b][-1].item() == self.tokenizer.pad_token_id:
continue
if input_ids[b][-1].item() == self.tokenizer.eos_token_id:
continue
cur_tokens = self.tokenizer.convert_ids_to_tokens(input_ids[b])
meet_right = False
meet_eq = None
for i in range(len(cur_tokens)-1, -1, -1):
if cur_tokens[i] == ']':
break
elif cur_tokens[i] == '▁=':
meet_eq = i
elif cur_tokens[i] == '▁[' and meet_eq is not None:
string = ''.join(cur_tokens[i+1:meet_eq])
string = re.sub('▁', ' ', string)
try:
res = self.tool(string)
except:
break
target_token_ids = self.tokenizer.encode(res, add_special_tokens=False, return_tensors='pt')[0]
if all(torch.eq(target_token_ids, input_ids[b][-len(target_token_ids):].cpu())):
scores[b, self.right_token_id] = 10e7
elif input_ids[b][-1] == self.eq_token_id:
scores[b, target_token_ids[0]] = 10e7
else:
gen_token_ids = input_ids[b][meet_eq+1:]
l = len(gen_token_ids)
scores[b, target_token_ids[l]] = 10e7
break
return scores
class CustomLogitsProcessorLLAMA(LogitsProcessor):
def __init__(self, tokenizer, tool):
self.tokenizer = tokenizer
self.tool = tool
self.right_token_id = tokenizer.convert_tokens_to_ids('>>')
self.space_token_id = tokenizer.convert_tokens_to_ids('▁')
def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor:
bz = scores.size(0)
for b in range(bz):
if input_ids[b][-1].item() == self.tokenizer.pad_token_id:
continue
if input_ids[b][-1].item() == self.tokenizer.eos_token_id:
continue
# 查找有无闭合的 <<...>>
# current_string = self.tokenizer.decode(input_ids[b])
current_string = self.tokenizer.decode(input_ids[b][100:])
pattern = r'<<[^>]+=[^>]*$'
match = re.search(pattern, current_string)
if match:
focus_string = match.group(0).strip('<<')
try:
eq_left, eq_right = focus_string.split('=')
num_result = self.tool(eq_left)
if float(num_result) < 0:
continue
except:
continue
if num_result == eq_right:
scores[b, self.right_token_id] = 1e6
else:
res_token_ids = self.tokenizer.encode(num_result, add_special_tokens=False)
if res_token_ids[0] == self.space_token_id:
res_token_ids = res_token_ids[1:]
res_token_ids = torch.LongTensor(res_token_ids)
if len(eq_right) == 0:
scores[b, res_token_ids[0]] = 1e6
else:
try:
scores[b, res_token_ids[len(eq_right)]] = 1e6
except:
continue
return scores
@hydra.main(version_base=None, config_path="exp_config/t5")
def main(cfg : DictConfig):
exp_name = cfg.exp_name
run_name = cfg.trainer.run_name
split = cfg.data.split
bz = cfg.eval.per_device_eval_batch_size
rank = int(os.environ["LOCAL_RANK"])
dist.init_process_group("nccl")
torch.manual_seed(cfg.trainer.seed)
world_size = torch.cuda.device_count()
base_model = os.path.join(DATA_DIR, cfg.trainer.output_dir)
if 'llama' in base_model:
tokenizer = AutoTokenizer.from_pretrained(base_model, truncation_side='left', padding_side='left')
model = AutoModelForCausalLM.from_pretrained(base_model, torch_dtype=torch.bfloat16)
gsm8k_module = GSM8KForLLAMA(cfg.data, tokenizer)
else:
tokenizer = AutoTokenizer.from_pretrained(base_model)
model = AutoModelForSeq2SeqLM.from_pretrained(base_model)
gsm8k_module = GSM8K(cfg.data, tokenizer)
assert tokenizer.pad_token is not None
torch.cuda.set_device(rank)
model.to(torch.cuda.current_device())
model = DDP(model, device_ids=[torch.cuda.current_device()])
model.eval()
eval_dataset = gsm8k_module.dataset[split]
effective_bz = world_size * bz
if len(eval_dataset) % effective_bz != 0:
diff = effective_bz - len(eval_dataset) % effective_bz
for_pad = eval_dataset.select(list(range(diff+20)))
eval_dataset = concatenate_datasets([eval_dataset, for_pad])
sampler = DistributedSampler(
eval_dataset,
num_replicas=world_size,
rank=rank,
shuffle=False,
)
dataloader = DataLoader(
eval_dataset,
shuffle=False,
collate_fn=gsm8k_module.data_collator,
batch_size=bz,
sampler=sampler,
drop_last=True,
num_workers=12,
)
if cfg.eval.mode == 'greedy':
out_path = os.path.join(
'model_outputs/', exp_name, run_name, split,
'greedy_decode.json',
)
generation_config = GenerationConfig(
do_sample=False,
max_new_tokens=cfg.eval.max_new_tokens,
eos_token_id=tokenizer.eos_token_id,
pad_token_id=tokenizer.pad_token_id,
)
if cfg.eval.use_calc:
m = CustomLogitsProcessorLLAMA(tokenizer=tokenizer, tool=tool_fn) if 'llama' in base_model \
else CustomLogitsProcessor(tokenizer=tokenizer, tool=tool_fn)
logits_proc = [m]
else:
logits_proc = []
if rank == 0:
iterator = tqdm(enumerate(dataloader), total=len(eval_dataset)//(bz*world_size))
else:
iterator = enumerate(dataloader)
all_outputs = []
for _, batch in iterator:
input_ids = batch['input_ids'].to(model.device)
attention_mask = batch['attention_mask'].to(model.device)
with torch.no_grad():
with torch.autocast(device_type='cuda', dtype=torch.bfloat16):
output_ids = model.module.generate(
input_ids=input_ids,
attention_mask=attention_mask,
generation_config=generation_config,
logits_processor=logits_proc,
return_dict_in_generate=False,
)
gather_outputs = sequence_gather(output_ids, world_size, tokenizer.pad_token_id)
gathered_inputs = sequence_gather(input_ids, world_size, tokenizer.pad_token_id)
gather_outputs = torch.stack(gather_outputs)
gathered_inputs = torch.stack(gathered_inputs)
gather_outputs = gather_outputs.transpose(0,1).reshape(bz*world_size, -1)
gathered_inputs = gathered_inputs.transpose(0,1).reshape(bz*world_size,-1)
outputs_string = tokenizer.batch_decode(gather_outputs, skip_special_tokens=True)
inputs_string = tokenizer.batch_decode(gathered_inputs, skip_special_tokens=True)
for idx in range(len(inputs_string)):
temp = [[inputs_string[idx], outputs_string[idx].replace(inputs_string[idx], '')]]
all_outputs.append(temp)
if rank == 0:
folder = '/'.join(out_path.split('/')[:-1])
if not os.path.exists(folder):
os.makedirs(folder)
with open(out_path, 'w') as f:
for item in all_outputs:
f.write(json.dumps(item) + '\n')
dist.barrier()
else:
assert cfg.eval.mode == 'sampling'
out_path = os.path.join(
'model_outputs/', exp_name, run_name, f'{split}/',
)
generation_config = GenerationConfig(
do_sample=True,
max_new_tokens=300,
temperature=cfg.eval.sampling.temperature,
)
m = CustomLogitsProcessor(
tokenizer=tokenizer,
tool=tool_fn,
)
if rank == 0:
pbar = tqdm(total=(cfg.eval.sampling.max_seed - cfg.eval.sampling.min_seed) * len(eval_dataset)//effective_bz)
for seed in range(cfg.eval.sampling.min_seed, cfg.eval.sampling.max_seed):
set_seed(seed)
all_outputs = []
for _, batch in enumerate(dataloader):
input_ids = batch['input_ids'].to(model.device)
attention_mask = batch['attention_mask'].to(model.device)
with torch.no_grad():
with torch.autocast(device_type='cuda', dtype=torch.bfloat16):
output_ids = model.module.generate(
input_ids=input_ids,
attention_mask=attention_mask,
generation_config=generation_config,
logits_processor=[m],
return_dict_in_generate=False,
)
gather_outputs = sequence_gather(output_ids, world_size, tokenizer.pad_token_id)
gathered_inputs = sequence_gather(input_ids, world_size, tokenizer.pad_token_id)
gather_outputs = torch.stack(gather_outputs)
gathered_inputs = torch.stack(gathered_inputs)
gather_outputs = gather_outputs.transpose(0,1).reshape(effective_bz, -1)
gathered_inputs = gathered_inputs.transpose(0,1).reshape(effective_bz,-1)
outputs_string = tokenizer.batch_decode(gather_outputs, skip_special_tokens=True)
inputs_string = tokenizer.batch_decode(gathered_inputs, skip_special_tokens=True)
for idx in range(len(inputs_string)):
temp = [[inputs_string[idx], outputs_string[idx].replace(inputs_string[idx], '')]]
all_outputs.append(temp)
if rank == 0:
pbar.update(1)
if rank == 0:
folder = '/'.join(out_path.split('/')[:-1])
if not os.path.exists(folder):
os.makedirs(folder)
with open(out_path+f'seed_{seed}-t_{cfg.eval.sampling.temperature}.json', 'w') as f:
for item in all_outputs:
f.write(json.dumps(item) + '\n')
dist.barrier()
if rank == 0:
pbar.close()
return
if __name__ == "__main__":
main()