forked from louaaron/Score-Entropy-Discrete-Diffusion
-
Notifications
You must be signed in to change notification settings - Fork 0
/
data.py
296 lines (248 loc) · 10.1 KB
/
data.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
import re
from transformers import GPT2TokenizerFast
from datasets import load_dataset
from itertools import chain
import numpy as np
import tempfile
from Bio import SeqIO
import requests
import json
from datasets import Dataset
from torch.utils.data import DataLoader, DistributedSampler
def cycle_loader(dataloader, sampler=None):
while 1:
if sampler is not None:
sampler.set_epoch(np.random.randint(0, 100000))
for data in dataloader:
yield data
def wt_detokenizer(string):
# contractions
string = string.replace("s '", "s'")
string = re.sub(r"/' [0-9]/", r"/'[0-9]/", string)
# number separators
string = string.replace(" @-@ ", "-")
string = string.replace(" @,@ ", ",")
string = string.replace(" @.@ ", ".")
# punctuation
string = string.replace(" : ", ": ")
string = string.replace(" ; ", "; ")
string = string.replace(" . ", ". ")
string = string.replace(" ! ", "! ")
string = string.replace(" ? ", "? ")
string = string.replace(" , ", ", ")
# double brackets
string = re.sub(r"\(\s*([^\)]*?)\s*\)", r"(\1)", string)
string = re.sub(r"\[\s*([^\]]*?)\s*\]", r"[\1]", string)
string = re.sub(r"{\s*([^}]*?)\s*}", r"{\1}", string)
string = re.sub(r"\"\s*([^\"]*?)\s*\"", r'"\1"', string)
string = re.sub(r"'\s*([^']*?)\s*'", r"'\1'", string)
# miscellaneous
string = string.replace("= = = =", "====")
string = string.replace("= = =", "===")
string = string.replace("= =", "==")
string = string.replace(" " + chr(176) + " ", chr(176))
string = string.replace(" \n", "\n")
string = string.replace("\n ", "\n")
string = string.replace(" N ", " 1 ")
string = string.replace(" 's", "'s")
return string
def ptb_detokenizer(x):
x = x.replace(" 's", "'s")
x = x.replace("s ' ", "s' ")
x = x.replace(" n't", "n't")
x = x.replace(" \n ", "\n")
x = x.replace("\\/", "/")
for _ in range(10):
x = x.replace(" N ", " 1 ")
x = x.replace("$ 1", "$1")
x = x.replace("# 1", "#1")
x = x.replace("<unk>", "?")
return x
def lm1b_detokenizer(x):
x = x.replace('http : / / ', 'http://')
x = x.replace('https : / / ', 'https://')
x = re.sub(r' \'(\w+)', r"'\1", x)
x = re.sub(r' (\w+) \. ', r' \1. ', x)
x = re.sub(r' (\w+) \.$', r' \1.', x)
x = x.replace(' ? ', '? ')
x = re.sub(r' \?$', '?', x)
x = x.replace(' ! ', '! ')
x = re.sub(r' \!$', '!', x)
x = x.replace(' , ', ', ')
x = x.replace(' : ', ': ')
x = x.replace(' ; ', '; ')
x = x.replace(' / ', '/')
x = re.sub(r'\" ([^\"]+) \"', r'"\1"', x)
x = re.sub(r'\' ([^\']+) \'', r"'\1'", x)
x = re.sub(r'\( ([^\(\)]+) \)', r"(\1)", x)
x = re.sub(r'\[ ([^\[\]]+) \]', r"[\1]", x)
x = x.replace('$ ', '$')
x = x.replace('£ ', '£')
return x
def lambada_detokenizer(text):
text = text.replace("“", '"')
text = text.replace("”", '"')
return '\n'+text.strip()
def acyp_detokenizer(text):
return text
def get_lambada_test_dataset():
url = "https://openaipublic.blob.core.windows.net/gpt-2/data/lambada_test.jsonl"
def read_jsonl_to_list(url):
response = requests.get(url, stream=True)
data_list = []
# Process each line in the response content
for line in response.iter_lines(decode_unicode=True):
if line:
data = json.loads(line)
data_list.append(data)
return data_list
lambada_data = read_jsonl_to_list(url)
dataset = Dataset.from_list(lambada_data)
return dataset
def get_acyp_dataset():
url = "https://github.com/dacarlin/protein-transformers/raw/refs/heads/main/hypf.fa"
def download_fasta_to_tempfile(url):
# Create a temporary file
with tempfile.NamedTemporaryFile(delete=False, mode='w+') as temp_fasta:
response = requests.get(url)
temp_fasta.write(response.text)
temp_fasta.flush() # Ensure the file is written to disk
return temp_fasta.name
def read_fasta_from_file(filepath):
# Read the FASTA file using BioPython
sequence_list = []
with open(filepath, "r") as fasta_handle:
for record in SeqIO.parse(fasta_handle, "fasta"):
sequence_list.append({
"text": str(record.seq), # Convert sequence object to string
})
return sequence_list
# Download FASTA to temporary file
fasta_filepath = download_fasta_to_tempfile(url)
# Read and parse FASTA sequences from the temporary file
acyp_data = read_fasta_from_file(fasta_filepath)
dataset = Dataset.from_list(acyp_data)
return dataset
def get_dataset(name, mode, cache_dir=None, block_size=1024, num_proc=8):
if name == "wikitext103":
dataset = load_dataset("wikitext", name="wikitext-103-raw-v1", cache_dir=cache_dir)
elif name == "wikitext2":
dataset = load_dataset("wikitext", name="wikitext-2-raw-v1", cache_dir=cache_dir)
elif name == "ptb":
dataset = load_dataset("ptb_text_only", cache_dir=cache_dir)
elif name == "lambada":
dataset = get_lambada_test_dataset()
elif name == "acyp":
dataset = get_acyp_dataset()
elif name == "uniref50":
dataset = load_dataset("agemagician/uniref50", cache_dir=cache_dir)
else:
dataset = load_dataset(name, cache_dir=cache_dir)
if name == "lambada":
data = dataset
elif name == "acyp":
data = dataset
else:
data = dataset[mode]
if name.startswith("wikitext"):
detokenizer = wt_detokenizer
elif name == "ptb":
detokenizer = ptb_detokenizer
elif name == "lm1b":
detokenizer = lm1b_detokenizer
elif name == "lambada":
detokenizer = lambada_detokenizer
elif name in ["acyp", "uniref50"]:
detokenizer = acyp_detokenizer
else:
detokenizer = None
def _apply_detokenizer(detokenizer):
def detok(text):
for i, t in enumerate(text, 0):
text[i] = detokenizer(t)
return text
return detok
tokenizer = GPT2TokenizerFast.from_pretrained('gpt2')
EOS = tokenizer.encode(tokenizer.eos_token)[0]
if name in ["acyp", "uniref50"]:
# Initialize the tokenizer
tokenizer = GPT2TokenizerFast(
vocab_file='vocab.json',
merges_file='merges.txt',
bos_token='<s>',
eos_token='</s>',
unk_token='<unk>',
pad_token='<pad>',
mask_token='<mask>'
)
EOS = tokenizer.encode(tokenizer.eos_token)[0]
def preprocess_and_tokenize(example):
if name == "ptb":
text = example['sentence']
if name == "acyp":
#print(example["text"])
text = example["text"]
else:
text = example["text"]
# print(list(example.keys()))
# exit()
if detokenizer is not None:
text = _apply_detokenizer(detokenizer)(text)
tokens = tokenizer(text, return_attention_mask=False)
# add in EOS token following
# https://github.com/jcpeterson/openwebtext/blob/master/tokenize_text.py#L67
for token in tokens['input_ids']:
token.append(EOS)
return tokens
tokenized_dataset = data.map(preprocess_and_tokenize, batched=True, num_proc=num_proc, load_from_cache_file=True)
if name == "ptb":
tokenized_dataset = tokenized_dataset.remove_columns('sentence')
else:
tokenized_dataset = tokenized_dataset.remove_columns('text')
def group_texts(examples):
# Concatenate all texts.
concatenated_examples = {k: list(chain(*examples[k])) for k in examples.keys()}
total_length = len(concatenated_examples[list(examples.keys())[0]])
# We drop the small remainder, and if the total_length < block_size we exclude this batch and return an empty dict.
# We could add padding if the model supported it instead of this drop, you can customize this part to your needs.
total_length = (total_length // block_size) * block_size
# Split by chunks of max_len.
result = {
k: [t[i : i + block_size] for i in range(0, total_length, block_size)]
for k, t in concatenated_examples.items()
}
return result
chunked_dataset = tokenized_dataset.map(group_texts, batched=True, num_proc=num_proc, load_from_cache_file=True)
chunked_dataset = chunked_dataset.with_format('torch')
return chunked_dataset
def get_dataloaders(config, distributed=True):
if config.training.batch_size % (config.ngpus * config.training.accum) != 0:
raise ValueError(f"Train Batch Size {config.training.batch_size} is not divisible by {config.ngpus} gpus with accumulation {config.training.accum}.")
if config.eval.batch_size % (config.ngpus * config.training.accum) != 0:
raise ValueError(f"Eval Batch Size for {config.eval.batch_size} is not divisible by {config.ngpus} gpus with accumulation {config.training.accum}.")
train_set = get_dataset(config.data.train, "train", cache_dir=config.data.cache_dir, block_size=config.model.length)
valid_set = get_dataset(config.data.valid, "validation" if config.data.valid != "text8" else "test", cache_dir=config.data.cache_dir, block_size=config.model.length)
if distributed:
train_sampler = DistributedSampler(train_set)
test_sampler = DistributedSampler(valid_set)
else:
train_sampler = None
test_sampler = None
train_loader = cycle_loader(DataLoader(
train_set,
batch_size=config.training.batch_size // (config.ngpus * config.training.accum),
sampler=train_sampler,
num_workers=4,
pin_memory=True,
shuffle=(train_sampler is None),
persistent_workers=True,
))
valid_loader = cycle_loader(DataLoader(
valid_set,
batch_size=config.eval.batch_size // (config.ngpus * config.training.accum),
sampler=test_sampler,
num_workers=4,
pin_memory=True,
shuffle=(test_sampler is None),
))
return train_loader, valid_loader