-
Notifications
You must be signed in to change notification settings - Fork 40
/
Copy pathdataset.py
325 lines (268 loc) · 9.81 KB
/
dataset.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
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
import json
import itertools
import random
from dataclasses import dataclass
from typing import Optional
import torch
import torch.distributed as dist
from datasets import Dataset
from transformers import PreTrainedTokenizerBase
from transformers.data.data_collator import pad_without_fast_tokenizer_warning
def get_dataset(path, tokenizer, max_size=1000000000):
def tokenize_sample(sample):
question_tokenized = tokenizer.encode(
sample["question"] + "\n", add_special_tokens=True
)
steps_tokenized = [
tokenizer.encode(s + "\n", add_special_tokens=False)
for s in sample["steps"]
]
answer_tokenized = tokenizer.encode(
"### " + sample["answer"], add_special_tokens=False
) + [tokenizer.eos_token_id]
sample = {
"question_tokenized": question_tokenized,
"steps_tokenized": steps_tokenized,
"answer_tokenized": answer_tokenized,
"idx": sample["idx"],
}
return sample
data = json.load(open(path))[:max_size]
data = [{**d, "idx": idx} for idx, d in enumerate(data)]
keys = data[0].keys()
dataset = Dataset.from_dict({k: [d[k] for d in data] for k in keys})
if torch.cuda.device_count() > 1:
if dist.get_rank() == 0:
processed_dataset = [
dataset.map(
tokenize_sample, remove_columns=list(dataset.features), num_proc=32
)
]
else:
processed_dataset = [None]
dist.broadcast_object_list(processed_dataset, src=0)
dataset = processed_dataset[0]
else:
dataset = dataset.map(
tokenize_sample, remove_columns=list(dataset.features), num_proc=32
)
# verify
d = data[0]
complete = d["question"] + "\n" + "\n".join(d["steps"]) + "\n### " + d["answer"]
complete_tokenized = tokenizer.encode(complete, add_special_tokens=True) + [
tokenizer.eos_token_id
]
assert (
complete_tokenized
== dataset[0]["question_tokenized"]
+ list(itertools.chain.from_iterable(dataset[0]["steps_tokenized"]))
+ dataset[0]["answer_tokenized"]
)
return dataset
@dataclass
class MyCollator:
tokenizer: PreTrainedTokenizerBase
latent_id: Optional[int] = None
label_pad_token_id: Optional[int] = -100
def __call__(self, features, return_tensors=None):
assert self.tokenizer.padding_side == "right"
"""
Pad the batch like this to maximize the reuse of kv cache.
E.g.,
xxxxxxxxxx<latent><latent>xxxxx--
-----xxxxx<latent>xxxxxxxx-------
---xxxxxxx<latent><latent>xxxxxxx
("x" is word token, "-" is pad token)
"""
earliest_latent = [
feature["input_ids"].index(self.latent_id)
for feature in features
if self.latent_id in feature["input_ids"]
]
if len(earliest_latent) > 0: # if there are continuous thoughts in the sequence
latest_earliest_latent = max(earliest_latent)
for feature in features:
if self.latent_id in feature["input_ids"]:
n_tok_pad = latest_earliest_latent - feature["input_ids"].index(
self.latent_id
)
else:
n_tok_pad = 0
feature["position_ids"] = [0] * n_tok_pad + list(
range(len(feature["input_ids"]))
)
feature["input_ids"] = [
self.tokenizer.pad_token_id
] * n_tok_pad + feature["input_ids"]
if "labels" in feature:
feature["labels"] = [self.label_pad_token_id] * n_tok_pad + feature[
"labels"
]
feature["attention_mask"] = [0] * n_tok_pad + feature["attention_mask"]
return_tensors = "pt"
label_name = "label" if "label" in features[0].keys() else "labels"
non_label_position_features = [
{
k: v
for k, v in feature.items()
if k != label_name and k != "position_ids"
}
for feature in features
]
# run through tokenizer without labels to ensure no side effects
batch = pad_without_fast_tokenizer_warning(
self.tokenizer,
non_label_position_features,
padding=True,
pad_to_multiple_of=None,
return_tensors=return_tensors,
)
labels = (
[feature[label_name] for feature in features]
if label_name in features[0].keys()
else None
)
if labels is not None and all(label is None for label in labels):
labels = None
position_ids = (
[feature["position_ids"] for feature in features]
if "position_ids" in features[0].keys()
else None
)
# we have to pad the labels and position_ids manually as we cannot rely on `tokenizer.pad`
if labels is not None:
max_label_length = max(len(l) for l in labels)
batch["labels"] = [
label + [self.label_pad_token_id] * (max_label_length - len(label))
for label in labels
]
batch["labels"] = torch.tensor(batch["labels"], dtype=torch.int64)
if position_ids is not None:
max_pos_length = max(len(l) for l in position_ids)
batch["position_ids"] = [
position_id + [0] * (max_pos_length - len(position_id))
for position_id in position_ids
]
batch["position_ids"] = torch.tensor(
batch["position_ids"], dtype=torch.int64
)
return batch
def get_question_latent_dataset(
scheduled_stage,
base_dataset_valid,
configs,
start_id,
latent_id,
end_id,
no_special_marker=False,
):
def process_dataset(sample):
if configs.pad_latent_to_max:
max_latent_stage = configs.max_latent_stage
else:
max_latent_stage = min(
configs.max_latent_stage, len(sample["steps_tokenized"])
)
k = min(max_latent_stage, scheduled_stage)
k *= configs.c_thought
tokens = (
sample["question_tokenized"]
+ ([] if no_special_marker else [start_id])
+ [latent_id] * k
+ ([] if no_special_marker else [end_id])
)
return {
"input_ids": tokens,
"idx": sample["idx"],
"attention_mask": [1] * len(tokens),
"position_ids": list(range(len(tokens))),
}
return base_dataset_valid.map(
process_dataset, remove_columns=list(base_dataset_valid.features), num_proc=32
)
def get_cot_latent_dataset(
scheduled_stage,
base_dataset,
configs,
start_id,
latent_id,
end_id,
no_special_marker=False,
shuffle=False,
):
n_additional_tokens = 0 if no_special_marker else 2
def process_dataset(sample):
if (
random.random() < configs.uniform_prob
): # with some prob, randomly sample stage
scheduled_stage_to_train = random.choice(
list(range(len(sample["steps_tokenized"]) + 1))
)
else:
scheduled_stage_to_train = scheduled_stage
if scheduled_stage_to_train > configs.max_latent_stage:
n_skip_steps = 10000 # skip all
if configs.pad_latent_to_max:
n_latent_tokens = configs.max_latent_stage
else:
n_latent_tokens = min(
len(sample["steps_tokenized"]), configs.max_latent_stage
)
else:
n_skip_steps, n_latent_tokens = (
scheduled_stage_to_train,
scheduled_stage_to_train,
)
if configs.no_cot:
n_skip_steps = 100 # skip all step
n_latent_tokens = 0
n_latent_tokens *= configs.c_thought
tokens = (
sample["question_tokenized"]
+ ([] if no_special_marker else [start_id])
+ [latent_id] * n_latent_tokens
+ ([] if no_special_marker else [end_id])
+ list(
itertools.chain.from_iterable(sample["steps_tokenized"][n_skip_steps:])
)
+ sample["answer_tokenized"]
)
return {
"input_ids": tokens,
"labels": [-100]
* (
len(sample["question_tokenized"])
+ n_latent_tokens
+ n_additional_tokens
)
+ tokens[
n_latent_tokens
+ n_additional_tokens
+ len(sample["question_tokenized"]) :
],
"attention_mask": [1] * len(tokens),
"idx": sample["idx"],
"position_ids": list(range(len(tokens))),
}
if torch.cuda.device_count() > 1:
if dist.get_rank() == 0:
processed_dataset = base_dataset.map(
process_dataset, remove_columns=list(base_dataset.features), num_proc=32
)
if shuffle:
processed_dataset = processed_dataset.shuffle()
processed_dataset = [processed_dataset]
else:
processed_dataset = [None]
dist.broadcast_object_list(processed_dataset, src=0)
dataset = processed_dataset[0]
else:
processed_dataset = base_dataset.map(
process_dataset, remove_columns=list(base_dataset.features), num_proc=32
)
if shuffle:
processed_dataset = processed_dataset.shuffle()
dataset = processed_dataset
return dataset