-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathseq2seq_loader.py
434 lines (386 loc) · 18.5 KB
/
seq2seq_loader.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
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
from random import randint, shuffle, choice
from random import random as rand
import math
import torch
from biunilm.loader_utils import get_random_word, batch_list_to_batch_tensors, Pipeline
# Input file format :
# 1. One sentence per line. These should ideally be actual sentences,
# not entire paragraphs or arbitrary spans of text. (Because we use
# the sentence boundaries for the "next sentence prediction" task).
# 2. Blank lines between documents. Document boundaries are needed
# so that the "next sentence prediction" task doesn't span between documents.
def truncate_tokens_pair(tokens_a, tokens_b, tokens_a_label, tokens_b_label, max_len, max_len_a=0, \
max_len_b=0, trunc_seg=None, always_truncate_tail=False):
num_truncated_a = [0, 0]
num_truncated_b = [0, 0]
while True:
if len(tokens_a) + len(tokens_b) <= max_len:
break
if (max_len_a > 0) and len(tokens_a) > max_len_a:
trunc_tokens = tokens_a
trunc_tokens_label = tokens_a_label
num_truncated = num_truncated_a
elif (max_len_b > 0) and len(tokens_b) > max_len_b:
trunc_tokens = tokens_b
trunc_tokens_label = tokens_b_label
num_truncated = num_truncated_b
elif trunc_seg:
# truncate the specified segment
if trunc_seg == 'a':
trunc_tokens = tokens_a
trunc_tokens_label = tokens_a_label
num_truncated = num_truncated_a
else:
trunc_tokens = tokens_b
trunc_tokens_label = tokens_b_label
num_truncated = num_truncated_b
else:
# truncate the longer segment
if len(tokens_a) > len(tokens_b):
trunc_tokens = tokens_a
trunc_tokens_label = tokens_a_label
num_truncated = num_truncated_a
else:
trunc_tokens = tokens_b
trunc_tokens_label = tokens_b_label
num_truncated = num_truncated_b
# whether always truncate source sequences
if (not always_truncate_tail) and (rand() < 0.5):
del trunc_tokens[0]
del trunc_tokens_label[0]
num_truncated[0] += 1
else:
trunc_tokens.pop()
trunc_tokens_label.pop()
num_truncated[1] += 1
return num_truncated_a, num_truncated_b
class Seq2SeqDataset(torch.utils.data.Dataset):
""" Load sentence pair (sequential or random order) from corpus """
def __init__(self, file_src, file_tgt, file_label, batch_size, tokenizer, max_len, label_indexer,\
file_oracle=None, short_sampling_prob=0.1, sent_reverse_order=False,\
bi_uni_pipeline=[]):
super().__init__()
self.tokenizer = tokenizer # tokenize function
self.max_len = max_len # maximum length of tokens
self.short_sampling_prob = short_sampling_prob
self.bi_uni_pipeline = bi_uni_pipeline
self.batch_size = batch_size
self.sent_reverse_order = sent_reverse_order
self.label_indexer = label_indexer
# read the file into memory
self.ex_list = []
if file_oracle is None:
with open(file_src, "r", encoding='utf-8') as f_src, \
open(file_tgt, "r", encoding='utf-8') as f_tgt, \
open(file_label, "r", encoding='utf-8') as f_label:
for src, tgt, label in zip(f_src, f_tgt, f_label):
src_tk = tokenizer.tokenize(src.strip())
tgt_tk = tokenizer.tokenize(tgt.strip())
label_list = label.strip().split(" ")
assert len(src_tk) > 0
assert len(tgt_tk) > 0
assert len(src_tk) == len(label_list)
self.ex_list.append((src_tk, tgt_tk, label_list))
print('Load {0} documents'.format(len(self.ex_list)))
def __len__(self):
return len(self.ex_list)
def __getitem__(self, idx):
instance = self.ex_list[idx]
proc = choice(self.bi_uni_pipeline)
instance = proc(instance, self.label_indexer)
return instance
def __iter__(self): # iterator to load data
for __ in range(math.ceil(len(self.ex_list) / float(self.batch_size))):
batch = []
for __ in range(self.batch_size):
idx = randint(0, len(self.ex_list)-1)
batch.append(self.__getitem__(idx))
# To Tensor
yield batch_list_to_batch_tensors(batch)
class Preprocess4Seq2seq(Pipeline):
""" Pre-processing steps for pretraining transformer """
def __init__(self, max_pred, mask_prob, vocab_words, indexer, max_len=512, \
new_segment_ids=False, truncate_config={}, mask_source_words=False, \
skipgram_prb=0, skipgram_size=0, mask_whole_word=False, \
mode="s2s", has_oracle=False, num_qkv=0, s2s_special_token=False, \
s2s_add_segment=False, s2s_share_segment=False, pos_shift=False):
super().__init__()
self.max_len = max_len # max tokens of a+b, max_len_a + max_len_b <= max_len
self.max_pred = max_pred # max tokens of prediction
self.mask_prob = mask_prob # masking probability
self.vocab_words = vocab_words # vocabulary (sub)words
self.indexer = indexer # function from token to token index
self._tril_matrix = torch.tril(torch.ones((max_len, max_len), dtype=torch.long))
self.skipgram_prb = skipgram_prb
self.skipgram_size = skipgram_size
self.mask_whole_word = mask_whole_word
self.new_segment_ids = new_segment_ids
self.always_truncate_tail = truncate_config.get('always_truncate_tail', False)
self.max_len_a = truncate_config.get('max_len_a', None)
self.max_len_b = truncate_config.get('max_len_b', None)
self.trunc_seg = truncate_config.get('trunc_seg', None)
self.task_idx = 3 # relax projection layer for different tasks
self.mask_source_words = mask_source_words
assert mode in ("s2s", "l2r")
self.mode = mode
self.has_oracle = has_oracle
self.num_qkv = num_qkv
self.s2s_special_token = s2s_special_token
self.s2s_add_segment = s2s_add_segment
self.s2s_share_segment = s2s_share_segment
self.pos_shift = pos_shift
def __call__(self, instance, label_indexer):
tokens_a, tokens_b, tokens_a_label = instance[:3]
tokens_b_label = ['O'] * len(tokens_b)
assert len(tokens_a) == len(tokens_a_label)
if self.pos_shift:
tokens_b = ['[S2S_SOS]'] + tokens_b
tokens_b_label = ['S2S_SOS'] + tokens_b_label
raw_tokens_a = tokens_a
raw_tokens_b = tokens_b
raw_tokens_a_label = tokens_a_label
raw_tokens_b_label = tokens_b_label
num_truncated_a, _ = truncate_tokens_pair(tokens_a, tokens_b, tokens_a_label, tokens_b_label, \
self.max_len - 3, max_len_a=self.max_len_a, max_len_b=self.max_len_b, \
trunc_seg=self.trunc_seg, always_truncate_tail=self.always_truncate_tail)
if self.s2s_special_token:
tokens = ['[S2S_CLS]'] + tokens_a + ['[S2S_SEP]'] + tokens_b + ['[SEP]']
label = ['[S2S_CLS]'] + tokens_a_label + ['[S2S_SEP]'] + tokens_b_label + ['[SEP]']
label_mask = [0] + [1] * len(tokens_a) + [0] + [0] * len(tokens_b_label) + [0]
else:
tokens = ['[CLS]'] + tokens_a + ['[SEP]'] + tokens_b + ['[SEP]']
label = ['[CLS]'] + tokens_a_label + ['[SEP]'] + tokens_b_label + ['[SEP]']
label_mask = [0] + [1] * len(tokens_a) + [0] + [0] * len(tokens_b_label) + [0]
assert len(tokens) == len(label)
assert len(label) == len(label_mask)
if self.new_segment_ids:
if self.mode == "s2s":
if self.s2s_add_segment:
if self.s2s_share_segment:
segment_ids = [0] + [1] * (len(tokens_a)+1) + [5]*(len(tokens_b)+1)
else:
segment_ids = [4] + [6] * \
(len(tokens_a)+1) + [5]*(len(tokens_b)+1)
else:
segment_ids = [4] * (len(tokens_a)+2) + \
[5]*(len(tokens_b)+1)
else:
segment_ids = [2] * (len(tokens))
else:
segment_ids = [0]*(len(tokens_a)+2) + [1]*(len(tokens_b)+1)
if self.pos_shift:
n_pred = min(self.max_pred, len(tokens_b))
masked_pos = [len(tokens_a)+2+i for i in range(len(tokens_b))]
masked_weights = [1]*n_pred
masked_ids = self.indexer(tokens_b[1:]+['[SEP]'])
else:
# For masked Language Models
# the number of prediction is sometimes less than max_pred when sequence is short
effective_length = len(tokens_b)
if self.mask_source_words:
effective_length += len(tokens_a)
n_pred = min(self.max_pred, max(
1, int(round(effective_length*self.mask_prob))))
# candidate positions of masked tokens
cand_pos = []
special_pos = set()
for i, tk in enumerate(tokens):
# only mask tokens_b (target sequence)
# we will mask [SEP] as an ending symbol
if (i >= len(tokens_a)+2) and (tk != '[CLS]'):
cand_pos.append(i)
elif self.mask_source_words and (i < len(tokens_a)+2) and (tk != '[CLS]') and (not tk.startswith('[SEP')):
cand_pos.append(i)
else:
special_pos.add(i)
shuffle(cand_pos)
masked_pos = set()
max_cand_pos = max(cand_pos)
for pos in cand_pos:
if len(masked_pos) >= n_pred:
break
if pos in masked_pos:
continue
def _expand_whole_word(st, end):
new_st, new_end = st, end
while (new_st >= 0) and tokens[new_st].startswith('##'):
new_st -= 1
while (new_end < len(tokens)) and tokens[new_end].startswith('##'):
new_end += 1
return new_st, new_end
if (self.skipgram_prb > 0) and (self.skipgram_size >= 2) and (rand() < self.skipgram_prb):
# ngram
cur_skipgram_size = randint(2, self.skipgram_size)
if self.mask_whole_word:
st_pos, end_pos = _expand_whole_word(
pos, pos + cur_skipgram_size)
else:
st_pos, end_pos = pos, pos + cur_skipgram_size
else:
# directly mask
if self.mask_whole_word:
st_pos, end_pos = _expand_whole_word(pos, pos + 1)
else:
st_pos, end_pos = pos, pos + 1
for mp in range(st_pos, end_pos):
if (0 < mp <= max_cand_pos) and (mp not in special_pos):
masked_pos.add(mp)
else:
break
masked_pos = list(masked_pos)
if len(masked_pos) > n_pred:
shuffle(masked_pos)
masked_pos = masked_pos[:n_pred]
masked_tokens = [tokens[pos] for pos in masked_pos]
for pos in masked_pos:
if rand() < 0.8: # 80%
tokens[pos] = '[MASK]'
elif rand() < 0.5: # 10%
tokens[pos] = get_random_word(self.vocab_words)
# when n_pred < max_pred, we only calculate loss within n_pred
masked_weights = [1]*len(masked_tokens)
# Token Indexing
masked_ids = self.indexer(masked_tokens)
assert len(tokens) == len(label)
input_ids = self.indexer(tokens)
label_ids = []
for l in label:
label_ids.append(label_indexer[l])
assert len(input_ids) == len(label_ids)
# Zero Padding
n_pad = self.max_len - len(input_ids)
input_ids.extend([0]*n_pad)
label_ids.extend([0]*n_pad)
segment_ids.extend([0]*n_pad)
label_mask.extend([0]*n_pad)
if self.num_qkv > 1:
mask_qkv = [0]*(len(tokens_a)+2) + [1] * (len(tokens_b)+1)
mask_qkv.extend([0]*n_pad)
else:
mask_qkv = None
input_mask = torch.zeros(self.max_len, self.max_len, dtype=torch.long)
if self.mode == "s2s":
input_mask[:, :len(tokens_a)+2].fill_(1)
second_st, second_end = len(
tokens_a)+2, len(tokens_a)+len(tokens_b)+3
input_mask[second_st:second_end, second_st:second_end].copy_(
self._tril_matrix[:second_end-second_st, :second_end-second_st])
else:
st, end = 0, len(tokens_a) + len(tokens_b) + 3
input_mask[st:end, st:end].copy_(self._tril_matrix[:end, :end])
# Zero Padding for masked target
if self.max_pred > n_pred:
n_pad = self.max_pred - n_pred
if masked_ids is not None:
masked_ids.extend([0]*n_pad)
if masked_pos is not None:
masked_pos.extend([0]*n_pad)
if masked_weights is not None:
masked_weights.extend([0]*n_pad)
oracle_pos = None
oracle_weights = None
oracle_labels = None
if self.has_oracle:
s_st, labls = instance[2:]
oracle_pos = []
oracle_labels = []
for st, lb in zip(s_st, labls):
st = st - num_truncated_a[0]
if st > 0 and st < len(tokens_a):
oracle_pos.append(st)
oracle_labels.append(lb)
oracle_pos = oracle_pos[:20]
oracle_labels = oracle_labels[:20]
oracle_weights = [1] * len(oracle_pos)
if len(oracle_pos) < 20:
x_pad = 20 - len(oracle_pos)
oracle_pos.extend([0] * x_pad)
oracle_labels.extend([0] * x_pad)
oracle_weights.extend([0] * x_pad)
return (input_ids, segment_ids, input_mask, mask_qkv, masked_ids,
masked_pos, masked_weights, -1, self.task_idx,
oracle_pos, oracle_weights, oracle_labels)
return (input_ids, segment_ids, input_mask, label_ids, label_mask, mask_qkv, \
masked_ids, masked_pos, masked_weights, -1, self.task_idx)
class Preprocess4Seq2seqDecoder(Pipeline):
""" Pre-processing steps for pretraining transformer """
def __init__(self, vocab_words, indexer, max_len=512, max_tgt_length=128, new_segment_ids=False, mode="s2s",
num_qkv=0, s2s_special_token=False, s2s_add_segment=False, s2s_share_segment=False, pos_shift=False):
super().__init__()
self.max_len = max_len
self.vocab_words = vocab_words # vocabulary (sub)words
self.indexer = indexer # function from token to token index
self.max_len = max_len
self._tril_matrix = torch.tril(torch.ones(
(max_len, max_len), dtype=torch.long))
self.new_segment_ids = new_segment_ids
self.task_idx = 3 # relax projection layer for different tasks
assert mode in ("s2s", "l2r")
self.mode = mode
self.max_tgt_length = max_tgt_length
self.num_qkv = num_qkv
self.s2s_special_token = s2s_special_token
self.s2s_add_segment = s2s_add_segment
self.s2s_share_segment = s2s_share_segment
self.pos_shift = pos_shift
def __call__(self, instance):
tokens_a, max_a_len = instance
# Add Special Tokens
if self.s2s_special_token:
padded_tokens_a = ['[S2S_CLS]'] + tokens_a + ['[S2S_SEP]']
else:
padded_tokens_a = ['[CLS]'] + tokens_a + ['[SEP]']
assert len(padded_tokens_a) <= max_a_len + 2
if max_a_len + 2 > len(padded_tokens_a):
padded_tokens_a += ['[PAD]'] * \
(max_a_len + 2 - len(padded_tokens_a))
assert len(padded_tokens_a) == max_a_len + 2
max_len_in_batch = min(self.max_tgt_length +
max_a_len + 2, self.max_len)
tokens = padded_tokens_a
if self.new_segment_ids:
if self.mode == "s2s":
_enc_seg1 = 0 if self.s2s_share_segment else 4
if self.s2s_add_segment:
if self.s2s_share_segment:
segment_ids = [
0] + [1]*(len(padded_tokens_a)-1) + [5]*(max_len_in_batch - len(padded_tokens_a))
else:
segment_ids = [
4] + [6]*(len(padded_tokens_a)-1) + [5]*(max_len_in_batch - len(padded_tokens_a))
else:
segment_ids = [4]*(len(padded_tokens_a)) + \
[5]*(max_len_in_batch - len(padded_tokens_a))
else:
segment_ids = [2]*max_len_in_batch
else:
segment_ids = [0]*(len(padded_tokens_a)) \
+ [1]*(max_len_in_batch - len(padded_tokens_a))
if self.num_qkv > 1:
mask_qkv = [0]*(len(padded_tokens_a)) + [1] * \
(max_len_in_batch - len(padded_tokens_a))
else:
mask_qkv = None
position_ids = []
for i in range(len(tokens_a) + 2):
position_ids.append(i)
for i in range(len(tokens_a) + 2, max_a_len + 2):
position_ids.append(0)
for i in range(max_a_len + 2, max_len_in_batch):
position_ids.append(i - (max_a_len + 2) + len(tokens_a) + 2)
# Token Indexing
input_ids = self.indexer(tokens)
# Zero Padding
input_mask = torch.zeros(
max_len_in_batch, max_len_in_batch, dtype=torch.long)
if self.mode == "s2s":
input_mask[:, :len(tokens_a)+2].fill_(1)
else:
st, end = 0, len(tokens_a) + 2
input_mask[st:end, st:end].copy_(
self._tril_matrix[:end, :end])
input_mask[end:, :len(tokens_a)+2].fill_(1)
second_st, second_end = len(padded_tokens_a), max_len_in_batch
input_mask[second_st:second_end, second_st:second_end].copy_(
self._tril_matrix[:second_end-second_st, :second_end-second_st])
return (input_ids, segment_ids, position_ids, input_mask, mask_qkv, self.task_idx)