-
Notifications
You must be signed in to change notification settings - Fork 6
/
dataloader.py
372 lines (332 loc) · 15.6 KB
/
dataloader.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
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
import datasets
from fastNLP import DataSet, Instance
from fastNLP.io import Loader, DataBundle
from functools import partial
from transformers import RobertaTokenizer
# 从huggingface datasets脚本中读取数据
def load_hf_dataset(task_name: str = 'SST-2', seed: int = 42, split: str = 'train') -> datasets.Dataset:
"""
Please choose from:
:param task_name: 'AGNews', 'MRPC', 'SNLI', 'SST-2', 'TREC', 'Yelp'
:param seed: 8, 13, 42, 50, 60
:param split: 'train', 'dev'
"""
dataset = datasets.load_dataset(
path=f'./datasets/{task_name}/{task_name}.py',
split=f'{split}_{seed}'
)
return dataset
def convert_to_features(example_batch, tokenizer):
input_encodings = tokenizer.batch_encode_plus(example_batch['input_text'])
target_encodings = tokenizer.batch_encode_plus(example_batch['target_text'], add_special_tokens=False)
mask_pos = []
for input_ids in input_encodings['input_ids']:
mask_pos.append(input_ids.index(tokenizer.mask_token_id))
encodings = {
'input_ids': input_encodings['input_ids'],
'attention_mask': input_encodings['attention_mask'],
'mask_pos': mask_pos,
'labels': target_encodings['input_ids'],
}
return encodings
class SST2Loader(Loader):
def __init__(self, tokenizer=None, n_prompt_tokens=50):
super().__init__()
if tokenizer is None:
self.tokenizer = RobertaTokenizer.from_pretrained('roberta-large')
else:
self.tokenizer = tokenizer
self.n_prompt_tokens = n_prompt_tokens
self.label2text = {
0: "bad",
1: "great",
}
def convert_examples(self, example):
if self.n_prompt_tokens > 0: # use randomly selected words as initial prompt
offset = 1000
prompt = self.tokenizer.decode(list(range(offset, offset + self.n_prompt_tokens)))
example['input_text'] = '%s . %s . It was %s .' % (prompt, example['text'], self.tokenizer.mask_token)
example['target_text'] = self.label2text[example['labels']]
else:
example['input_text'] = '%s . It was %s .' % (example['text'], self.tokenizer.mask_token)
example['target_text'] = self.label2text[example['labels']]
return example
def _load(self, split, seed) -> DataSet:
# load dataset with Huggingface's Datasets
dataset = load_hf_dataset(task_name='SST-2', split=split, seed=seed)
dataset = dataset.map(self.convert_examples, load_from_cache_file=False)
print('Example in {} set:'.format(split))
print(dataset[0])
dataset = dataset.map(partial(convert_to_features, tokenizer=self.tokenizer), batched=True, load_from_cache_file=False)
# Convert to fastNLP.DataSet
ds = DataSet()
for ins in dataset:
if len(ins["input_ids"]) <= 512:
example = {
"input_ids": ins["input_ids"],
"attention_mask": ins["attention_mask"],
"mask_pos": ins["mask_pos"],
"labels": ins["labels"][0],
}
ds.append(Instance(**example))
ds.set_input("input_ids", "attention_mask", "mask_pos")
ds.set_target("labels")
return ds
def my_load(self, splits, seed) -> DataBundle:
datasets = {name: self._load(name, seed) for name in splits}
data_bundle = DataBundle(datasets=datasets)
return data_bundle
class YelpPLoader(Loader):
def __init__(self, tokenizer=None, n_prompt_tokens=50):
super().__init__()
if tokenizer is None:
self.tokenizer = RobertaTokenizer.from_pretrained('roberta-large')
else:
self.tokenizer = tokenizer
self.n_prompt_tokens = n_prompt_tokens
self.label2text = {
0: "bad",
1: "great",
}
def convert_examples(self, example):
if self.n_prompt_tokens > 0: # use randomly selected words as initial prompt
offset = 1000
prompt = self.tokenizer.decode(list(range(offset, offset + self.n_prompt_tokens)))
example['input_text'] = '%s . %s .' % (prompt, example['text'].replace("\\n", " "))
example['target_text'] = self.label2text[example['labels']]
else:
example['input_text'] = '%s .' % (example['text'].replace("\\n", " "))
example['target_text'] = self.label2text[example['labels']]
return example
def _load(self, split, seed) -> DataSet:
# load dataset with Huggingface's Datasets
dataset = load_hf_dataset(task_name='Yelp', split=split, seed=seed)
dataset = dataset.map(self.convert_examples, load_from_cache_file=False)
print(dataset[0])
def convert_to_features_yelp(example_batch, tokenizer):
input_encodings = tokenizer.batch_encode_plus(example_batch['input_text'], max_length=509, truncation=True)
target_encodings = tokenizer.batch_encode_plus(example_batch['target_text'], add_special_tokens=False)
template = tokenizer.encode(f'It was {tokenizer.mask_token}', add_special_tokens=False)
input_encodings['input_ids'] = [ids[:-1] + template + [tokenizer.sep_token_id] for ids in input_encodings['input_ids']]
input_encodings['attention_mask'] = [am + [1] * 3 for am in input_encodings['attention_mask']]
mask_pos = []
for input_ids in input_encodings['input_ids']:
mask_pos.append(input_ids.index(tokenizer.mask_token_id))
encodings = {
'input_ids': input_encodings['input_ids'],
'attention_mask': input_encodings['attention_mask'],
'mask_pos': mask_pos,
'labels': target_encodings['input_ids'],
}
return encodings
dataset = dataset.map(partial(convert_to_features_yelp, tokenizer=self.tokenizer), batched=True, load_from_cache_file=False)
# Convert to fastNLP.DataSet
ds = DataSet()
for ins in dataset:
if len(ins["input_ids"]) <= 512:
example = {
"input_ids": ins["input_ids"],
"attention_mask": ins["attention_mask"],
"mask_pos": ins["mask_pos"],
"labels": ins["labels"][0],
}
ds.append(Instance(**example))
ds.set_input("input_ids", "attention_mask", "mask_pos")
ds.set_target("labels")
return ds
def my_load(self, splits, seed) -> DataBundle:
datasets = {name: self._load(name, seed) for name in splits}
data_bundle = DataBundle(datasets=datasets)
return data_bundle
class AGNewsLoader(Loader):
def __init__(self, tokenizer=None, n_prompt_tokens=50):
super().__init__()
if tokenizer is None:
self.tokenizer = RobertaTokenizer.from_pretrained('roberta-large')
else:
self.tokenizer = tokenizer
self.n_prompt_tokens = n_prompt_tokens
self.label2text = {
0: "World",
1: "Sports",
2: "Business",
3: "Tech"
}
def convert_examples(self, example):
if self.n_prompt_tokens > 0: # use randomly selected words as initial prompt
offset = 1000
prompt = self.tokenizer.decode(list(range(offset, offset + self.n_prompt_tokens)))
example['input_text'] = '%s . %s News: %s' % (prompt, self.tokenizer.mask_token, example['text'])
example['target_text'] = self.label2text[example['labels']]
else:
example['input_text'] = '%s News: %s' % (self.tokenizer.mask_token, example['text'])
example['target_text'] = self.label2text[example['labels']]
return example
def _load(self, split, seed) -> DataSet:
# load dataset with Huggingface's Datasets
dataset = load_hf_dataset(task_name='AGNews', split=split, seed=seed)
dataset = dataset.map(self.convert_examples, load_from_cache_file=False)
print(dataset[0])
dataset = dataset.map(partial(convert_to_features, tokenizer=self.tokenizer), batched=True, load_from_cache_file=False)
# Convert to fastNLP.DataSet
ds = DataSet()
for ins in dataset:
if len(ins["input_ids"]) <= 512:
example = {
"input_ids": ins["input_ids"],
"attention_mask": ins["attention_mask"],
"mask_pos": ins["mask_pos"],
"labels": ins["labels"][0],
}
ds.append(Instance(**example))
ds.set_input("input_ids", "attention_mask", "mask_pos")
ds.set_target("labels")
return ds
def my_load(self, splits, seed) -> DataBundle:
datasets = {name: self._load(name, seed) for name in splits}
data_bundle = DataBundle(datasets=datasets)
return data_bundle
class MRPCLoader(Loader):
def __init__(self, tokenizer=None, n_prompt_tokens=50):
super().__init__()
if tokenizer is None:
self.tokenizer = RobertaTokenizer.from_pretrained('roberta-large')
else:
self.tokenizer = tokenizer
self.n_prompt_tokens = n_prompt_tokens
self.label2text = {
0: "No",
1: "Yes",
}
def convert_examples(self, example):
if self.n_prompt_tokens > 0: # use randomly selected words as initial prompt
offset = 1000
prompt = self.tokenizer.decode(list(range(offset, offset + self.n_prompt_tokens)))
example['input_text'] = '%s . %s ? %s , %s' % (prompt, example['text1'], self.tokenizer.mask_token, example['text2'])
example['target_text'] = self.label2text[example['labels']]
else:
example['input_text'] = '%s ? %s , %s' % (example['text1'], self.tokenizer.mask_token, example['text2'])
example['target_text'] = self.label2text[example['labels']]
return example
def _load(self, split, seed) -> DataSet:
# load dataset with Huggingface's Datasets
dataset = load_hf_dataset(task_name='MRPC', split=split, seed=seed)
dataset = dataset.map(self.convert_examples, load_from_cache_file=False)
print(dataset[0])
dataset = dataset.map(partial(convert_to_features, tokenizer=self.tokenizer), batched=True, load_from_cache_file=False)
# Convert to fastNLP.DataSet
ds = DataSet()
for ins in dataset:
if len(ins["input_ids"]) <= 512:
example = {
"input_ids": ins["input_ids"],
"attention_mask": ins["attention_mask"],
"mask_pos": ins["mask_pos"],
"labels": ins["labels"][0],
}
ds.append(Instance(**example))
ds.set_input("input_ids", "attention_mask", "mask_pos")
ds.set_target("labels")
return ds
def my_load(self, splits, seed) -> DataBundle:
datasets = {name: self._load(name, seed) for name in splits}
data_bundle = DataBundle(datasets=datasets)
return data_bundle
class SNLILoader(Loader):
def __init__(self, tokenizer=None, n_prompt_tokens=50):
super().__init__()
if tokenizer is None:
self.tokenizer = RobertaTokenizer.from_pretrained('roberta-large')
else:
self.tokenizer = tokenizer
self.n_prompt_tokens = n_prompt_tokens
self.label2text = {
0: "Yes",
1: "Maybe",
2: "No",
}
def convert_examples(self, example):
if self.n_prompt_tokens > 0: # use randomly selected words as initial prompt
offset = 1000
prompt = self.tokenizer.decode(list(range(offset, offset + self.n_prompt_tokens)))
example['input_text'] = '%s . %s ? %s , %s' % (prompt, example['text1'], self.tokenizer.mask_token, example['text2'])
example['target_text'] = self.label2text[example['labels']]
else:
example['input_text'] = '%s ? %s , %s' % (example['text1'], self.tokenizer.mask_token, example['text2'])
example['target_text'] = self.label2text[example['labels']]
return example
def _load(self, split, seed) -> DataSet:
# load dataset with Huggingface's Datasets
dataset = load_hf_dataset(task_name='SNLI', split=split, seed=seed)
dataset = dataset.filter(lambda example: example['labels'] in [0, 1, 2])
dataset = dataset.map(self.convert_examples, load_from_cache_file=False)
print(dataset[0])
dataset = dataset.map(partial(convert_to_features, tokenizer=self.tokenizer), batched=True, load_from_cache_file=False)
# Convert to fastNLP.DataSet
ds = DataSet()
for ins in dataset:
if len(ins["input_ids"]) <= 512:
example = {
"input_ids": ins["input_ids"],
"attention_mask": ins["attention_mask"],
"mask_pos": ins["mask_pos"],
"labels": ins["labels"][0],
}
ds.append(Instance(**example))
ds.set_input("input_ids", "attention_mask", "mask_pos")
ds.set_target("labels")
return ds
def my_load(self, splits, seed) -> DataBundle:
datasets = {name: self._load(name, seed) for name in splits}
data_bundle = DataBundle(datasets=datasets)
return data_bundle
class TRECLoader(Loader):
def __init__(self, tokenizer=None, n_prompt_tokens=50):
super().__init__()
if tokenizer is None:
self.tokenizer = RobertaTokenizer.from_pretrained('roberta-large')
else:
self.tokenizer = tokenizer
self.n_prompt_tokens = n_prompt_tokens
self.label2text = {
0: "description",
1: "entity",
2: "abbreviation",
3: "human",
4: "numeric",
5: "location"
}
def convert_examples(self, example):
if self.n_prompt_tokens > 0: # use randomly selected words as initial prompt
offset = 1000
prompt = self.tokenizer.decode(list(range(offset, offset + self.n_prompt_tokens)))
example['input_text'] = '%s . %s question: %s ' % (prompt, self.tokenizer.mask_token, example['text'])
example['target_text'] = self.label2text[example['labels']]
else:
example['input_text'] = '%s . question: %s' % (self.tokenizer.mask_token, example['text'])
example['target_text'] = self.label2text[example['labels']]
return example
def _load(self, split, seed) -> DataSet:
# load dataset with Huggingface's Datasets
dataset = load_hf_dataset(task_name='TREC', split=split, seed=seed)
dataset = dataset.map(self.convert_examples, load_from_cache_file=False)
print(dataset[0])
dataset = dataset.map(partial(convert_to_features, tokenizer=self.tokenizer), batched=True, load_from_cache_file=False)
# Convert to fastNLP.DataSet
ds = DataSet()
for ins in dataset:
if len(ins["input_ids"]) <= 512:
example = {
"input_ids": ins["input_ids"],
"attention_mask": ins["attention_mask"],
"mask_pos": ins["mask_pos"],
"labels": ins["labels"][0],
}
ds.append(Instance(**example))
ds.set_input("input_ids", "attention_mask", "mask_pos")
ds.set_target("labels")
return ds
def my_load(self, splits, seed) -> DataBundle:
datasets = {name: self._load(name, seed) for name in splits}
data_bundle = DataBundle(datasets=datasets)
return data_bundle