-
Notifications
You must be signed in to change notification settings - Fork 1
/
data_utils.py
304 lines (255 loc) · 8.86 KB
/
data_utils.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
import datetime
import io
import json
import os
import random
from itertools import chain
from itertools import cycle
import jsonlines
import torch
import zstandard
from torch.utils.data.dataset import IterableDataset
from transformers import GPT2Tokenizer
# from openwebtext2 https://github.com/EleutherAI/openwebtext2/blob/master/utils/archiver.py
from transformers import PreTrainedTokenizer
def json_serial(obj):
"""JSON serializer for objects not serializable by default json code"""
if isinstance(obj, (datetime.datetime,)):
return obj.isoformat()
raise TypeError("Type %s not serializable" % type(obj))
class Archive:
def __init__(self, file_path, compression_level=3):
self.file_path = file_path
dir_name = os.path.dirname(file_path)
if dir_name:
os.makedirs(dir_name, exist_ok=True)
self.fh = open(self.file_path, "wb")
self.cctx = zstandard.ZstdCompressor(level=compression_level)
self.compressor = self.cctx.stream_writer(self.fh)
def add_data(self, data, meta={}):
self.compressor.write(
json.dumps({"text": data, "meta": meta}, default=json_serial).encode(
"UTF-8"
)
+ b"\n"
)
def commit(self):
self.compressor.flush(zstandard.FLUSH_FRAME)
self.fh.flush()
self.fh.close()
class Reader:
def __init__(self):
pass
def read_jsonl(
self, file, get_meta=False, autojoin_paragraphs=True, para_joiner="\n\n"
):
with open(file, "rb") as fh:
self.fh = fh
cctx = zstandard.ZstdDecompressor()
reader = io.BufferedReader(cctx.stream_reader(fh))
rdr = jsonlines.Reader(reader)
for ob in rdr:
# naive jsonl where each object is just the string itself, with no meta. For legacy compatibility.
if isinstance(ob, str):
assert not get_meta
yield ob
continue
text = ob["text"]
if autojoin_paragraphs and isinstance(text, list):
text = para_joiner.join(text)
if get_meta:
yield file, text, (ob["meta"] if "meta" in ob else {})
else:
yield file, text
def collate_fn(batch):
data_list, label_list, seq_len_list = [], [], []
for _data, _seq in batch:
data_list.append(_data)
seq_len_list.append(_seq)
return (
torch.LongTensor(data_list),
seq_len_list,
)
class WebTextDocumentIterator:
def __init__(self, dataset_path):
self.dataset_path = dataset_path
def __iter__(self):
reader = Reader()
doc_chunk_size = 20000
documents = []
for i, x in enumerate(reader.read_jsonl(self.dataset_path)):
documents.append(x)
if len(documents) == doc_chunk_size:
yield documents
documents = []
yield documents
class FileIterator:
def __init__(self, dataset_path: str):
self.dataset_path = dataset_path
def __iter__(self):
with open(self.dataset_path, "r", encoding="utf-8") as f:
text = f.read()
yield text
class TokenizerIterator:
def __init__(
self, seq_len: int, tokenizer: PreTrainedTokenizer, seed: int, dataset_path: str
):
self.seq_len = seq_len
self.tokenizer = tokenizer
self.document_iter = WebTextDocumentIterator(dataset_path)
self.seed = seed
def __iter__(self):
block = []
for documents in self.document_iter:
random.Random(self.seed).shuffle(documents)
for doc_i, x in enumerate(documents):
tokenized = self.tokenizer(text=x[1],).input_ids
tokenized.append(self.tokenizer.eos_token_id)
tokenized.insert(0, self.tokenizer.eos_token_id)
for token in tokenized:
if len(block) == self.seq_len:
yield block, (x[0], doc_i)
block = []
block.append(token)
class BatchIterator:
def __init__(
self,
seq_len: int,
batch_size: int,
drop_last: bool,
tokenizer: PreTrainedTokenizer,
dataset_paths: str,
):
self.dataset_paths = dataset_paths
self.batch_size = batch_size
self.drop_last = drop_last
self.seq_len = seq_len
self.tokenizer = tokenizer
def process_data(self, seed_dataset):
seed, dataset = seed_dataset
self.tokenizer_iter = TokenizerIterator(
self.seq_len, self.tokenizer, seed, dataset
)
for x in self.tokenizer_iter:
yield x
def shuffled_data_list(self, i):
shuffled = self.dataset_paths
# does not impact global seed
random.Random(i).shuffle(shuffled)
return [(i, x) for x in shuffled]
def get_stream(self, data_list):
return chain.from_iterable(map(self.process_data, cycle(data_list)))
def get_streams(self):
return zip(
*[
self.get_stream(self.shuffled_data_list(i))
for i in range(len(self.dataset_paths))
]
)
def __iter__(self):
return self.get_streams()
class WebTextIter(IterableDataset):
def __init__(
self, batch_size, dataset_paths, seq_len, tokenizer=None, drop_last=True
):
if tokenizer is None:
tokenizer = GPT2Tokenizer.from_pretrained("gpt2")
self.seq_len = seq_len
self.dataset_paths = dataset_paths
self.batch_size = batch_size
self.batch_iter = BatchIterator(
seq_len=seq_len,
batch_size=batch_size,
drop_last=drop_last,
tokenizer=tokenizer,
dataset_paths=dataset_paths,
)
def __iter__(self):
try:
batch = []
for streams in self.batch_iter:
for sample in streams:
if len(batch) == self.batch_size:
yield collate_fn(batch)
batch = []
batch.append(sample)
except StopIteration:
return
class ChineseWebtextDataset(IterableDataset):
def __init__(
self,
file: str,
seq_len: int,
batch_size: int,
token_limit: int,
tokenizer=None,
):
self.file = file
self.seq_len = seq_len
self.batch_size = batch_size
self.token_limit = token_limit
self.token_count = 0
if tokenizer is None:
self.tokenizer = GPT2Tokenizer.from_pretrained("gpt2")
else:
self.tokenizer = tokenizer
def get_block(self):
block = []
with jsonlines.open(self.file) as reader:
for obj in reader:
content = obj["content"]
tokenized = self.tokenizer(text=content,).input_ids
tokenized.append(self.tokenizer.eos_token_id)
tokenized.insert(0, self.tokenizer.eos_token_id)
for token in tokenized:
if len(block) == self.seq_len:
yield block, len(block)
self.token_count += len(block)
block = []
block.append(token)
def __iter__(self):
batch = []
for x in self.get_block():
batch.append(x)
if len(batch) == self.batch_size:
yield collate_fn(batch)
batch = []
class OscarDataset(IterableDataset):
def __init__(
self,
file: str,
seq_len: int,
batch_size: int,
token_limit: int,
tokenizer=None,
):
self.file = file
self.seq_len = seq_len
self.batch_size = batch_size
self.token_limit = token_limit
self.token_count = 0
if tokenizer is None:
self.tokenizer = GPT2Tokenizer.from_pretrained("gpt2")
else:
self.tokenizer = tokenizer
def get_block(self):
block = []
with open(self.file, "rb") as reader:
for line in reader:
line = str(line)
tokenized = self.tokenizer(text=line,).input_ids
tokenized.append(self.tokenizer.eos_token_id)
tokenized.insert(0, self.tokenizer.eos_token_id)
for token in tokenized:
if len(block) == self.seq_len:
yield block, len(block)
self.token_count += len(block)
block = []
block.append(token)
def __iter__(self):
batch = []
for x in self.get_block():
batch.append(x)
if len(batch) == self.batch_size:
yield collate_fn(batch)
batch = []