-
Notifications
You must be signed in to change notification settings - Fork 6
/
utils.py
429 lines (340 loc) · 16.3 KB
/
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
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
import torch
import numpy as np
import revtok
import os
from torch.autograd import Variable
from torchtext import data, datasets
from nltk.translate.gleu_score import sentence_gleu, corpus_gleu
from bleu_score import corpus_bleu
from contextlib import ExitStack
from collections import OrderedDict, Counter
INF = 1e10
TINY = 1e-9
def computeGLEU(outputs, targets, corpus=False, tokenizer=None):
if tokenizer is None:
tokenizer = revtok.tokenize
outputs = [tokenizer(o) for o in outputs]
targets = [tokenizer(t) for t in targets]
if not corpus:
return torch.Tensor([sentence_gleu(
[t], o) for o, t in zip(outputs, targets)])
return corpus_gleu([[t] for t in targets], [o for o in outputs])
def computeBLEU(outputs, targets, corpus=False, tokenizer=None):
if tokenizer is None:
tokenizer = revtok.tokenize
outputs = [tokenizer(o) for o in outputs]
targets = [tokenizer(t) for t in targets]
if not corpus:
return torch.Tensor([sentence_gleu(
[t], o) for o, t in zip(outputs, targets)])
return corpus_bleu([[t] for t in targets], [o for o in outputs], emulate_multibleu=True)
def computeGroupBLEU(outputs, targets, tokenizer=None, bra=10, maxmaxlen=80):
if tokenizer is None:
tokenizer = revtok.tokenize
outputs = [tokenizer(o) for o in outputs]
targets = [tokenizer(t) for t in targets]
maxlens = max([len(t) for t in targets])
print(maxlens)
maxlens = min([maxlens, maxmaxlen])
nums = int(np.ceil(maxlens / bra))
outputs_buckets = [[] for _ in range(nums)]
targets_buckets = [[] for _ in range(nums)]
for o, t in zip(outputs, targets):
idx = len(o) // bra
if idx >= len(outputs_buckets):
idx = -1
outputs_buckets[idx] += [o]
targets_buckets[idx] += [t]
for k in range(nums):
print(corpus_bleu([[t] for t in targets_buckets[k]], [o for o in outputs_buckets[k]], emulate_multibleu=True))
# load the dataset + reversible tokenization
class NormalField(data.Field):
def reverse(self, batch):
if not self.batch_first:
batch.t_()
with torch.cuda.device_of(batch):
batch = batch.tolist()
def detagging(s):
if (len(s) > 3) and (s[-3] == '_') and (s[-2:].isupper()):
return s[:-3]
return s
batch = [[detagging(self.vocab.itos[ind]) for ind in ex] for ex in batch] # denumericalize
def trim(s, t):
sentence = []
for w in s:
if w == t:
break
sentence.append(w)
return sentence
batch = [trim(ex, self.eos_token) for ex in batch] # trim past frst eos
def filter_special(tok):
return tok not in (self.init_token, self.pad_token)
batch = [" ".join(filter(filter_special, ex)) for ex in batch]
return batch
def build_vocab_from_vocab(self, vocab):
counter = Counter()
self.vocab = self.vocab_cls(counter, specials=['<unk>', '<pad>', '<init>', '<eos>'])
for i, (v, c) in enumerate(vocab):
self.vocab.itos.append(v)
self.vocab.stoi[v] = len(self.vocab.itos) - 1
print('build vocab done. {} tokens'.format(len(self.vocab.itos)))
class NormalTranslationDataset(datasets.TranslationDataset):
"""Defines a dataset for machine translation."""
def __init__(self, path, exts, fields, load_dataset=False, prefix='', **kwargs):
"""Create a TranslationDataset given paths and fields.
Arguments:
path: Common prefix of paths to the data files for both languages.
exts: A tuple containing the extension to path for each language.
fields: A tuple containing the fields that will be used for data
in each language.
Remaining keyword arguments: Passed to the constructor of
data.Dataset.
"""
if not isinstance(fields[0], (tuple, list)):
fields = [('src', fields[0]), ('trg', fields[1])]
src_path, trg_path = tuple(os.path.expanduser(path + x) for x in exts)
if load_dataset and (os.path.exists(path + '.processed.{}.pt'.format(prefix))):
examples = torch.load(path + '.processed.{}.pt'.format(prefix))
else:
examples = []
with open(src_path) as src_file, open(trg_path) as trg_file:
for src_line, trg_line in zip(src_file, trg_file):
src_line, trg_line = src_line.strip(), trg_line.strip()
if src_line != '' and trg_line != '':
examples.append(data.Example.fromlist(
[src_line, trg_line], fields))
if load_dataset:
torch.save(examples, path + '.processed.{}.pt'.format(prefix))
super(datasets.TranslationDataset, self).__init__(examples, fields, **kwargs)
class TripleTranslationDataset(datasets.TranslationDataset):
"""Define a triple-translation dataset: src, trg, dec(output of a pre-trained teacher)"""
def __init__(self, path, exts, fields, load_dataset=False, prefix='', **kwargs):
if not isinstance(fields[0], (tuple, list)):
fields = [('src', fields[0]), ('trg', fields[1]), ('dec', fields[2])]
src_path, trg_path, dec_path = tuple(os.path.expanduser(path + x) for x in exts)
if load_dataset and (os.path.exists(path + '.processed.{}.pt'.format(prefix))):
examples = torch.load(path + '.processed.{}.pt'.format(prefix))
else:
examples = []
with open(src_path) as src_file, open(trg_path) as trg_file, open(dec_path) as dec_file:
for src_line, trg_line, dec_line in zip(src_file, trg_file, dec_file):
src_line, trg_line, dec_line = src_line.strip(), trg_line.strip(), dec_line.strip()
if src_line != '' and trg_line != '' and dec_line != '':
examples.append(data.Example.fromlist(
[src_line, trg_line, dec_line], fields))
if load_dataset:
torch.save(examples, path + '.processed.{}.pt'.format(prefix))
super(datasets.TranslationDataset, self).__init__(examples, fields, **kwargs)
# -------- Data-Loader --------- #
class ParallelDataset(datasets.TranslationDataset):
""" Define a N-parallel dataset: supports abitriry numbers of input streams"""
def __init__(self, path=None, exts=None, fields=None,
load_dataset=False, prefix='', examples=None, **kwargs):
if examples is None:
assert len(exts) == len(fields), 'N parallel dataset must match'
self.N = len(fields)
paths = tuple(os.path.expanduser(path + x) for x in exts)
if load_dataset and (os.path.exists(path + '.processed.{}.pt'.format(prefix))):
examples = torch.load(path + '.processed.{}.pt'.format(prefix))
else:
examples = []
with ExitStack() as stack:
files = [stack.enter_context(open(fname, "r", encoding="utf-8")) for fname in paths]
for lines in zip(*files):
lines = [line.strip() for line in lines]
if not any(line == '' for line in lines):
examples.append(data.Example.fromlist(lines, fields))
if load_dataset:
torch.save(examples, path + '.processed.{}.pt'.format(prefix))
super(datasets.TranslationDataset, self).__init__(examples, fields, **kwargs)
def lazy_reader(paths, fields, max_len=None): # infinite dataloader
while True:
with ExitStack() as stack:
files = [stack.enter_context(open(fname, "r", encoding="utf-8")) for fname in paths]
examples = []
for steps, lines in enumerate(zip(*files)):
lines = [line.strip() for line in lines]
if not any(line == '' for line in lines):
if max_len is not None:
flag = 0
for line in lines:
if len(line.split()) > max_len:
flag = 1
break
if flag == 1:
continue
examples.append(lines)
if steps % 2048 == 2047: # pre-read 4096 lines of the dataset
# sort the lines based on source length + target length
examples = sorted(examples, key=lambda x: sum([len(xi.split()) for xi in x]) )
for example in examples:
yield data.Example.fromlist(example, fields)
examples = []
for example in examples:
yield data.Example.fromlist(example, fields)
# raise StopIteration
examples = []
def full_reader(paths, fields, max_len=None):
with ExitStack() as stack:
files = [stack.enter_context(open(fname, "r", encoding="utf-8")) for fname in paths]
examples = []
for steps, lines in enumerate(zip(*files)):
lines = [line.strip() for line in lines]
if not any(line == '' for line in lines):
examples.append(data.Example.fromlist(lines, fields))
return examples
class LazyParallelDataset(datasets.TranslationDataset):
""" Define a N-parallel dataset: supports abitriry numbers of input streams"""
def __init__(self, path=None, exts=None, fields=None,
load_dataset=False, prefix='', examples=None, lazy=True,
max_len=None, **kwargs):
assert len(exts) == len(fields), 'N parallel dataset must match'
self.N = len(fields)
paths = tuple(os.path.expanduser(path + x) for x in exts)
if lazy:
super(datasets.TranslationDataset, self).__init__(lazy_reader(paths, fields, max_len), fields, **kwargs)
else:
super(datasets.TranslationDataset, self).__init__(full_reader(paths, fields, max_len), fields, **kwargs)
@classmethod
def splits(cls, path, train=None, validation=None, test=None, **kwargs):
train_data = None if train is None else cls(path + train, lazy=True, **kwargs)
val_data = None if validation is None else cls(path + validation, lazy=False, **kwargs)
test_data = None if test is None else cls(path + test, lazy=False, **kwargs)
return tuple(d for d in (train_data, val_data, test_data) if d is not None)
class Metrics:
def __init__(self, name, *metrics):
self.count = 0
self.metrics = OrderedDict((metric, 0) for metric in metrics)
self.name = name
def accumulate(self, count, *values, print_iter=None):
self.count += count
if print_iter is not None:
print(print_iter, end=' ')
for value, metric in zip(values, self.metrics):
if isinstance(value, torch.autograd.Variable):
value = value.data
if torch.is_tensor(value):
with torch.cuda.device_of(value):
value = value.cpu()
value = value.float().mean()
if print_iter is not None:
print('%.3f' % value, end=' ')
self.metrics[metric] += value * count
if print_iter is not None:
print()
return values[0] # loss
def __getattr__(self, key):
if key in self.metrics:
return self.metrics[key] / (self.count + 1e-9)
raise AttributeError
def __repr__(self):
return (f"{self.name}: " +
', '.join(f'{metric}: {getattr(self, metric):.3f}'
for metric, value in self.metrics.items()
if value is not 0))
def tensorboard(self, expt, i):
for metric in self.metrics:
value = getattr(self, metric)
if value != 0:
expt.add_scalar_value(f'{self.name}_{metric}', value, step=i)
def reset(self):
self.count = 0
self.metrics.update({metric: 0 for metric in self.metrics})
class Best:
def __init__(self, cmp_fn, *metrics, model=None, opt=None, path='', gpu=0):
self.cmp_fn = cmp_fn
self.model = model
self.opt = opt
self.path = path + '.pt'
self.metrics = OrderedDict((metric, None) for metric in metrics)
self.gpu = gpu
def accumulate(self, cmp_value, *other_values):
with torch.cuda.device(self.gpu):
cmp_metric, best_cmp_value = list(self.metrics.items())[0]
if best_cmp_value is None or self.cmp_fn(
best_cmp_value, cmp_value) == cmp_value:
self.metrics[cmp_metric] = cmp_value
self.metrics.update({metric: value for metric, value in zip(
list(self.metrics.keys())[1:], other_values)})
open(self.path + '.temp', 'w')
if self.model is not None:
torch.save(self.model.state_dict(), self.path)
if self.opt is not None:
torch.save([self.i, self.opt.state_dict()], self.path + '.states')
os.remove(self.path + '.temp')
def __getattr__(self, key):
if key in self.metrics:
return self.metrics[key]
raise AttributeError
def __repr__(self):
return ("BEST: " +
', '.join(f'{metric}: {getattr(self, metric):.3f}'
for metric, value in self.metrics.items()
if value is not None))
class CacheExample(data.Example):
@classmethod
def fromsample(cls, data_lists, names):
ex = cls()
for data, name in zip(data_lists, names):
setattr(ex, name, data)
return ex
class Cache:
def __init__(self, size=10000, fileds=["src", "trg"]):
self.cache = []
self.maxsize = size
def demask(self, data, mask):
with torch.cuda.device_of(data):
data = [d[:l] for d, l in zip(data.data.tolist(), mask.sum(1).long().tolist())]
return data
def add(self, data_lists, masks, names):
data_lists = [self.demask(d, m) for d, m in zip(data_lists, masks)]
for data in zip(*data_lists):
self.cache.append(CacheExample.fromsample(data, names))
if len(self.cache) >= self.maxsize:
self.cache = self.cache[-self.maxsize:]
class Batch:
def __init__(self, src=None, trg=None, dec=None):
self.src, self.trg, self.dec = src, trg, dec
def masked_sort(x, mask, dim=-1):
x.data += ((1 - mask) * INF).long()
y, i = torch.sort(x, dim)
y.data *= mask.long()
return y, i
def unsorted(y, i, dim=-1):
z = Variable(y.data.new(*y.size()))
z.scatter_(dim, i, y)
return z
def merge_cache(decoding_path, names0, last_epoch=0, max_cache=20):
file_lock = open(decoding_path + '/_temp_decode', 'w')
for name in names0:
filenames = []
for i in range(max_cache):
filenames.append('{}/{}.ep{}'.format(decoding_path, name, last_epoch - i))
if (last_epoch - i) <= 0:
break
code = 'cat {} > {}.train.{}'.format(" ".join(filenames), '{}/{}'.format(decoding_path, name), last_epoch)
os.system(code)
os.remove(decoding_path + '/_temp_decode')
class NormalBucketIterator(data.Iterator):
"""Defines an iterator that batches examples of similar lengths together.
Minimizes amount of padding needed while producing freshly shuffled
batches for each new epoch. See pool for the bucketing procedure used.
"""
def create_batches(self):
self.batches = batch(self.data(), self.batch_size, self.batch_size_fn)
def batch(data, batch_size, batch_size_fn=lambda new, count, sofar: count):
"""Yield elements from data in chunks of batch_size."""
minibatch, size_so_far = [], 0
for ex in data:
minibatch.append(ex)
size_so_far = batch_size_fn(ex, len(minibatch), size_so_far)
if size_so_far == batch_size:
print('size_so_far', size_so_far)
yield minibatch
minibatch, size_so_far = [], 0
elif size_so_far > batch_size:
print('size_so_far', size_so_far)
yield minibatch[:-1]
minibatch, size_so_far = minibatch[-1:], batch_size_fn(ex, 1, 0)
if minibatch:
yield minibatch