-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathdata_module.py
320 lines (278 loc) · 12.9 KB
/
data_module.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
import re
import os
import numpy as np
from dataclasses import dataclass
from omegaconf import DictConfig, OmegaConf
from typing import Any, Dict, List, Optional, Tuple, Union
import torch
from transformers import DataCollatorForSeq2Seq, AutoTokenizer
from datasets import load_dataset
from dotenv import load_dotenv
load_dotenv()
DATA_DIR = os.environ.get("DATA_DIR")
class GSM8K:
def __init__(self, cfg: DictConfig, tokenizer: AutoTokenizer):
super().__init__()
self.model_max_length = cfg.model_max_length
self.max_src_len = cfg.max_src_len
self.max_tgt_len = cfg.max_tgt_len
self.tokenizer = tokenizer
data_files = {'train': cfg.data_path}
dataset_dict = load_dataset('json', data_files=data_files)
column_names = dataset_dict['train'].column_names
processed_dataset = dataset_dict.map(
self.preprocess,
batched=True,
num_proc=16,
remove_columns=column_names,
load_from_cache_file=False,
desc="Running tokenizer on train dataset",
)
self.train_dataset = processed_dataset['train']
data_files = {
'train': cfg.train_data_path,
'dev': cfg.dev_data_path,
'test': cfg.test_data_path,
}
dataset_dict = load_dataset('json', data_files=data_files)
processed_eval_dataset = dataset_dict.map(
self.preprocess,
batched=True,
num_proc=16,
remove_columns=column_names,
load_from_cache_file=False,
desc="Running tokenizer on train dataset",
)
self.dataset = processed_eval_dataset
self.data_collator = DataCollatorForSeq2Seq(
tokenizer=self.tokenizer, padding=True,
)
@classmethod
def process_question(cls, question):
return question
@classmethod
def process_answer(cls, solution):
solution = re.sub(r'<<\d+=\d+>>', '', solution)
solution = re.sub(r'(\D):(\d)', r'\1: \2', solution)
solution = re.sub(r'<<', '[ ', solution)
solution = re.sub(r'>>', '] ', solution)
solution = re.sub(r'\$([^\s])', r'$ \1', solution)
solution = re.sub(r'([^\s])\+([^\s])', r'\1 + \2', solution)
solution = re.sub(r'([^\s])-([^\s])', r'\1 - \2', solution)
solution = re.sub(r'([^\s])\*([^\s])', r'\1 * \2', solution)
solution = re.sub(r'([^\s])/([^\s])', r'\1 / \2', solution)
solution = re.sub(r'([^\s])=([^\s])', r'\1 = \2', solution)
solution_split_by_line = solution.split('\n')
sol = []
for l in solution_split_by_line:
if l.startswith('##'):
sol.append(l)
elif not l.endswith('.'):
sol.append(l+'.')
else:
sol.append(l)
solution = ' '.join(sol)
return solution
def preprocess(self, examples):
inputs, targets = [], []
for i in range(len(examples['question'])):
processed_question = self.process_question(examples['question'][i])
inputs.append(processed_question)
processed_answer = self.process_answer(examples['answer'][i])
targets.append(processed_answer)
model_inputs = self.tokenizer(
inputs, max_length=self.max_src_len, padding=False, truncation=True,
)
labels = self.tokenizer(
text_target=targets, max_length=self.max_tgt_len, padding=False, truncation=True,
)
model_inputs["labels"] = labels["input_ids"]
return model_inputs
def pad(tensors: List[torch.Tensor], padding_value: int = 0, padding_side: str = "right") -> torch.Tensor:
"""
Pads a list of tensors to the same shape along the first dimension.
Args:
tensors (`List[torch.Tensor]`):
List of input tensors to pad.
padding_value (`int`):
Value to use for padding. Default is 0.
padding_side (`str`):
Side on which to add padding. Must be 'left' or 'right'. Default is 'right'.
Returns:
`torch.Tensor`:
A single tensor containing the padded tensors.
Examples:
>>> import torch
>>> pad([torch.tensor([1, 2, 3]), torch.tensor([4, 5])])
tensor([[1, 2, 3],
[4, 5, 0]])
>>> pad([torch.tensor([[1, 2], [3, 4]]), torch.tensor([[5, 6]])])
tensor([[[1, 2],
[3, 4]],
[[5, 6],
[0, 0]]])
"""
# Determine the maximum shape for each dimension
output_shape = np.max([t.shape for t in tensors], 0).tolist()
# Create an output tensor filled with the padding value
output = torch.full((len(tensors), *output_shape), padding_value, dtype=tensors[0].dtype, device=tensors[0].device)
for i, t in enumerate(tensors):
# Determine the slice for the sequence dimension
if padding_side == "left":
seq_slice = slice(output_shape[0] - t.shape[0], output_shape[0])
elif padding_side == "right":
seq_slice = slice(0, t.shape[0])
else:
raise ValueError("padding_side must be 'left' or 'right'")
slices = (seq_slice,) + tuple(slice(0, s) for s in t.shape[1:])
output[i][slices] = t
return output
@dataclass
class DataCollatorForLLAMA:
tokenizer: AutoTokenizer
label_pad_token_id: int = -100
def __call__(self, features: List[Dict[str, Any]]) -> Dict[str, Any]:
# first, pad everything to the same length
padded_batch = {}
for k in features[0].keys():
# Set padding value based on the key
if k.endswith("input_ids"):
padding_value = self.tokenizer.pad_token_id
elif k.endswith("labels"):
padding_value = self.label_pad_token_id
elif k.endswith("attention_mask"):
padding_value = 0
else:
raise ValueError(f"Unexpected key in batch '{k}'")
padding_side = self.tokenizer.padding_side
to_pad = [torch.tensor(ex[k], dtype=torch.int64) for ex in features]
padded_batch[k] = pad(to_pad, padding_value=padding_value, padding_side=padding_side)
return padded_batch
class GSM8KForLLAMA:
def __init__(self, cfg: DictConfig, tokenizer: AutoTokenizer):
super().__init__()
self.model_max_length = cfg.model_max_length
self.max_src_len = cfg.max_src_len
self.max_tgt_len = cfg.max_tgt_len
self.tokenizer = tokenizer
data_files = {'train': cfg.data_path}
dataset_dict = load_dataset('json', data_files=data_files)
column_names = dataset_dict['train'].column_names
processed_dataset = dataset_dict.map(
self.preprocess,
batched=False,
num_proc=16,
remove_columns=column_names,
load_from_cache_file=False,
desc="Running tokenizer on train dataset",
)
self.train_dataset = processed_dataset['train']
eval_data_files = {'train': cfg.train_data_path, 'dev': cfg.dev_data_path, 'test': cfg.test_data_path}
dataset_dict = load_dataset('json', data_files=eval_data_files)
column_names = dataset_dict['dev'].column_names
processed_eval_dataset = dataset_dict.map(
self.preprocess_eval,
batched=False,
num_proc=16,
remove_columns=column_names,
load_from_cache_file=False,
desc="Running tokenizer on train dataset",
)
self.dataset = processed_eval_dataset
self.data_collator = DataCollatorForLLAMA(tokenizer=tokenizer)
@classmethod
def process_question(cls, question):
question_w_template = (
"Below is an instruction that describes a task. "
"Write a response that appropriately completes the request.\n\n"
f"### Instruction:\n{question}\n\n### Response:\n"
)
return question_w_template
@classmethod
def process_answer(cls, answer):
return answer
def build_tokenized_answer(self, prompt, answer):
full_tokenized = self.tokenizer(prompt+answer, add_special_tokens=False)
prompt_input_ids = self.tokenizer(prompt, add_special_tokens=False)["input_ids"]
answer_input_ids = full_tokenized["input_ids"][len(prompt_input_ids) :]
answer_attention_mask = full_tokenized["attention_mask"][len(prompt_input_ids) :]
full_concat_input_ids = np.concatenate([prompt_input_ids, answer_input_ids])
# Prepare input tokens for token by token comparison
full_input_ids = np.array(full_tokenized["input_ids"])
assert len(full_input_ids) == len(full_concat_input_ids)
response_token_ids_start_idx = len(prompt_input_ids)
# If tokenized prompt is different than both prompt+answer, then it means the
# last token has changed due to merging.
if prompt_input_ids != full_tokenized["input_ids"][:response_token_ids_start_idx]:
response_token_ids_start_idx -= 1
prompt_input_ids = full_tokenized["input_ids"][:response_token_ids_start_idx]
prompt_attention_mask = full_tokenized["attention_mask"][:response_token_ids_start_idx]
assert len(prompt_input_ids) == len(prompt_attention_mask)
answer_input_ids = full_tokenized["input_ids"][response_token_ids_start_idx:]
answer_attention_mask = full_tokenized["attention_mask"][response_token_ids_start_idx:]
return_dict = dict(
prompt_input_ids=prompt_input_ids,
prompt_attention_mask=prompt_attention_mask,
input_ids=answer_input_ids,
attention_mask=answer_attention_mask,
)
return return_dict
def preprocess(self, examples):
batch = {}
prompt = self.process_question(examples["question"])
chosen = self.process_answer(examples["answer"])
prompt_tokens = self.tokenizer(prompt, add_special_tokens=False)
prompt_tokens = {f"prompt_{k}": v for k, v in prompt_tokens.items()}
chosen_tokens = self.build_tokenized_answer(prompt, chosen)
prompt_len_input_ids = len(prompt_tokens["prompt_input_ids"])
chosen_prompt_len_input_ids = len(chosen_tokens["prompt_input_ids"])
prompt_len_input_ids = chosen_prompt_len_input_ids
for k, v in prompt_tokens.items():
prompt_tokens[k] = v[:prompt_len_input_ids]
bos_token_id = self.tokenizer.bos_token_id
if prompt_len_input_ids == 0 or bos_token_id != prompt_tokens["prompt_input_ids"][0]:
prompt_tokens["prompt_input_ids"] = [bos_token_id] + prompt_tokens["prompt_input_ids"]
prompt_tokens["prompt_attention_mask"] = [1] + prompt_tokens["prompt_attention_mask"]
if chosen_prompt_len_input_ids == 0 or bos_token_id != chosen_tokens["prompt_input_ids"][0]:
chosen_tokens["prompt_input_ids"] = [bos_token_id] + chosen_tokens["prompt_input_ids"]
chosen_tokens["prompt_attention_mask"] = [1] + chosen_tokens["prompt_attention_mask"]
eos_token_id = self.tokenizer.eos_token_id
if len(chosen_tokens["input_ids"]) == 0 or eos_token_id != chosen_tokens["input_ids"][-1]:
chosen_tokens["input_ids"].append(eos_token_id)
chosen_tokens["attention_mask"].append(1)
# Truncate long sequences
response_length = len(chosen_tokens["input_ids"])
for answer_tokens in [chosen_tokens, prompt_tokens]:
if len(answer_tokens["prompt_input_ids"]) + response_length > self.model_max_length:
for k in ["prompt_input_ids", "prompt_attention_mask"]:
answer_tokens[k] = answer_tokens[k][-self.max_src_len :]
# Create labels
chosen_sequence_tokens = {
k: chosen_tokens[f"prompt_{k}"] + chosen_tokens[k] for k in ["input_ids", "attention_mask"]
}
chosen_sequence_tokens["labels"] = chosen_sequence_tokens["input_ids"][:]
chosen_sequence_tokens["labels"][: len(chosen_tokens["prompt_input_ids"])] = [
-100
] * len(chosen_tokens["prompt_input_ids"])
for k, toks in {
"chosen_": chosen_sequence_tokens,
"": prompt_tokens,
}.items():
for type_key, tokens in toks.items():
if type_key == "token_type_ids":
continue
batch[f"{k}{type_key}"] = tokens
new_batch = dict(
input_ids=batch['chosen_input_ids'],
attention_mask=batch['chosen_attention_mask'],
labels=batch['chosen_labels'],
)
return new_batch
def preprocess_eval(self, example):
prompt = self.process_question(example["question"])
prompt_tokens = self.tokenizer(prompt, add_special_tokens=False)
batch = dict(
input_ids=prompt_tokens['input_ids'],
attention_mask=prompt_tokens['attention_mask'],
)
return batch