This repository has been archived by the owner on Nov 3, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
torch_generator_agent.py
1699 lines (1455 loc) · 60 KB
/
torch_generator_agent.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
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""
Generic PyTorch-based Generator agent.
Implements quite a bit of boilerplate, including forced-decoding loss and a tree search.
Contains the following utilities:
* `ref:TorchGeneratorAgent` class, which serves as a useful parent for generative torch
agents.
* Beam class which provides some generic beam functionality for classes to use
"""
from parlai.core.params import ParlaiParser
from abc import ABC, abstractmethod
from typing import TypeVar, List, Dict, Optional, Tuple, Set, Iterable
import math
from operator import attrgetter
import torch
import torch.nn as nn
import torch.nn.functional as F
from parlai.core.opt import Opt
from parlai.utils.distributed import is_distributed, sync_parameters
from parlai.core.torch_agent import TorchAgent, Batch, Output, DictionaryAgent
from parlai.utils.misc import warn_once
from parlai.utils.io import PathManager
import parlai.utils.logging as logging
from parlai.core.metrics import (
Metric,
SumMetric,
AverageMetric,
BleuMetric,
FairseqBleuMetric,
)
from parlai.utils.fp16 import FP16SafeCrossEntropy
from parlai.utils.torch import (
neginf,
total_parameters,
trainable_parameters,
PipelineHelper,
)
try:
from nltk.translate import bleu_score as nltkbleu
except ImportError:
nltkbleu = None
try:
from fairseq.scoring import bleu as fairseq_bleu
except ImportError:
fairseq_bleu = None
class SearchBlocklist(object):
"""
Search block list facilitates blocking ngrams from being generated.
"""
def __init__(self, dict_agent: DictionaryAgent) -> None:
self.dict = dict_agent
self._phrases: Set[str] = set()
self._phrase_ngrams: Dict[int, List[List[int]]] = {}
def __bool__(self):
return bool(self._phrases)
def clear(self) -> None:
self._phrases = set()
self._phrase_ngrams = {}
def _add_literal(self, phrase_literal: str):
if phrase_literal in self._phrases:
return
ngram = self.dict.txt2vec(phrase_literal)
self._phrases.add(phrase_literal)
logging.debug(f"Adding '{phrase_literal}' to the beam block_list {ngram}")
l = len(ngram)
if l not in self._phrase_ngrams:
self._phrase_ngrams[l] = []
self._phrase_ngrams[l].append(ngram)
def add(self, phrase: str):
phrase = phrase.strip()
if not phrase:
return
self._add_literal(phrase)
self._add_literal(phrase + "s")
self._add_literal(phrase.lower())
self._add_literal(phrase.lower() + "s")
self._add_literal(phrase.upper())
self._add_literal(phrase.upper() + "S")
self._add_literal(phrase.title())
self._add_literal(phrase.title() + "S")
self._add_literal(phrase[0].upper() + phrase[1:])
self._add_literal(phrase[0].upper() + phrase[1:] + "s")
self._add_literal(phrase[0].upper() + phrase[1:].lower())
self._add_literal(phrase[0].upper() + phrase[1:].lower() + "s")
def items(self) -> Iterable[Tuple[int, List[List[int]]]]:
return self._phrase_ngrams.items()
TSType = TypeVar('TSType', bound='TreeSearch')
class TorchGeneratorModel(nn.Module, ABC):
"""
Abstract TorchGeneratorModel.
This interface expects you to implement model with the following reqs:
:attribute model.encoder:
takes input returns tuple (enc_out, enc_hidden, attn_mask)
:attribute model.decoder:
takes decoder params and returns decoder outputs after attn
:attribute model.output:
takes decoder outputs and returns distr over dictionary
"""
def __init__(
self,
padding_idx=0,
start_idx=1,
end_idx=2,
unknown_idx=3,
input_dropout=0,
longest_label=1,
):
super().__init__()
self.NULL_IDX = padding_idx
self.END_IDX = end_idx
self.START_IDX = start_idx
self.register_buffer('START', torch.LongTensor([start_idx]))
self.longest_label = longest_label
def _get_initial_forced_decoder_input(self, bsz: int, inputs: torch.LongTensor):
"""
Return initial input to the decoder.
:param bsz:
batchsize
:param inputs:
inputs to decode
:return initial_input:
initial input for the decoder.
"""
return torch.cat([self.START.detach().expand(bsz, 1), inputs], 1)
def decode_forced(self, encoder_states, ys):
"""
Decode with a fixed, true sequence, computing loss.
Useful for training, or ranking fixed candidates.
:param ys:
the prediction targets. Contains both the start and end tokens.
:type ys:
LongTensor[bsz, time]
:param encoder_states:
Output of the encoder. Model specific types.
:type encoder_states:
model specific
:return:
pair (logits, choices) containing the logits and MLE predictions
:rtype:
(FloatTensor[bsz, ys, vocab], LongTensor[bsz, ys])
"""
bsz = ys.size(0)
seqlen = ys.size(1)
inputs = ys.narrow(1, 0, seqlen - 1)
if (ys[:, 0] == self.START_IDX).any():
raise AssertionError(
"The Beginning of Sentence token is automatically added to the "
"label in decode_forced, but you included it in the label. This means "
"your model will have a double BOS token, which is probably not what "
"you intended."
)
inputs = self._get_initial_forced_decoder_input(bsz, inputs)
latent, _ = self.decoder(inputs, encoder_states)
logits = self.output(latent)
_, preds = logits.max(dim=2)
return logits, preds
@abstractmethod
def reorder_encoder_states(self, encoder_states, indices):
"""
Reorder encoder states according to a new set of indices.
This is an abstract method, and *must* be implemented by the user.
Its purpose is to provide beam search with a model-agnostic interface for
beam search. For example, this method is used to sort hypotheses,
expand beams, etc.
For example, assume that encoder_states is an bsz x 1 tensor of values
.. code-block:: python
indices = [0, 2, 2]
encoder_states = [[0.1]
[0.2]
[0.3]]
then the output will be
.. code-block:: python
output = [[0.1]
[0.3]
[0.3]]
:param encoder_states:
output from encoder. type is model specific.
:type encoder_states:
model specific
:param indices:
the indices to select over. The user must support non-tensor
inputs.
:type indices: list[int]
:return:
The re-ordered encoder states. It should be of the same type as
encoder states, and it must be a valid input to the decoder.
:rtype:
model specific
"""
pass
@abstractmethod
def reorder_decoder_incremental_state(self, incremental_state, inds):
"""
Reorder incremental state for the decoder.
Used to expand selected beams in beam search. Unlike reorder_encoder_states,
implementing this method is optional. However, without incremental decoding,
decoding a single beam becomes O(n^2) instead of O(n), which can make
beam search impractically slow.
In order to fall back to non-incremental decoding, just return None from this
method.
:param incremental_state:
second output of model.decoder
:type incremental_state:
model specific
:param inds:
indices to select and reorder over.
:type inds:
LongTensor[n]
:return:
The re-ordered decoder incremental states. It should be the same
type as incremental_state, and usable as an input to the decoder.
This method should return None if the model does not support
incremental decoding.
:rtype:
model specific
"""
pass
def forward(self, *xs, ys=None, prev_enc=None, maxlen=None, bsz=None):
"""
Get output predictions from the model.
:param xs:
input to the encoder
:type xs:
LongTensor[bsz, seqlen]
:param ys:
Expected output from the decoder. Used
for teacher forcing to calculate loss.
:type ys:
LongTensor[bsz, outlen]
:param prev_enc:
if you know you'll pass in the same xs multiple times, you can pass
in the encoder output from the last forward pass to skip
recalcuating the same encoder output.
:param maxlen:
max number of tokens to decode. if not set, will use the length of
the longest label this model has seen. ignored when ys is not None.
:param bsz:
if ys is not provided, then you must specify the bsz for greedy
decoding.
:return:
(scores, candidate_scores, encoder_states) tuple
- scores contains the model's predicted token scores.
(FloatTensor[bsz, seqlen, num_features])
- candidate_scores are the score the model assigned to each candidate.
(FloatTensor[bsz, num_cands])
- encoder_states are the output of model.encoder. Model specific types.
Feed this back in to skip encoding on the next call.
"""
assert ys is not None, "Greedy decoding in TGModel.forward no longer supported."
# TODO: get rid of longest_label
# keep track of longest label we've ever seen
# we'll never produce longer ones than that during prediction
self.longest_label = max(self.longest_label, ys.size(1))
# use cached encoding if available
encoder_states = prev_enc if prev_enc is not None else self.encoder(*xs)
# use teacher forcing
scores, preds = self.decode_forced(encoder_states, ys)
return scores, preds, encoder_states
class PPLMetric(AverageMetric):
def value(self):
return math.exp(super().value())
class TorchGeneratorAgent(TorchAgent, ABC):
"""
Abstract Generator agent; only meant to be extended.
TorchGeneratorAgent aims to handle much of the bookkeeping and infrastructure work
for any generative models, like seq2seq or transformer. It implements the train_step
and eval_step. The only requirement is that your model *must* implemented the
interface TorchGeneratorModel interface.
"""
@classmethod
def upgrade_opt(cls, opt_from_disk: Opt):
# call the parent upgrades
opt_from_disk = super(TorchGeneratorAgent, cls).upgrade_opt(opt_from_disk)
# 2019-08-18: Adding support for generation other than beam search
# Previously, selecting --beam-size > 1 enabled beam search and == 1 was
# greedy. New behavior is --inference greedy or --inference beam.
if 'inference' not in opt_from_disk:
assert 'beam_size' in opt_from_disk
if opt_from_disk['beam_size'] == 1:
method = 'greedy'
else:
method = 'beam'
opt_from_disk['inference'] = method
warn_once(f'Old model inference method inferred as {method}')
# 2020-06-03: Changing "blacklist" --> "blocklist"
if 'beam_blacklist_filename' in opt_from_disk:
if opt_from_disk['beam_blacklist_filename'] is not None:
opt_from_disk['beam_block_list_filename'] = opt_from_disk[
'beam_blacklist_filename'
]
del opt_from_disk['beam_blacklist_filename']
# 2020-08-04: Introduce full context beam blocking
# Previous, specifying --beam-context-block-ngram > 1 would block
# from generating ngrams from model's context, which is limited
# by truncation parameters. Now, we block on full dialogue history.
if 'beam_block_full_context' not in opt_from_disk:
warn_once('Loading model with `--beam-block-full-context false`')
opt_from_disk['beam_block_full_context'] = False
return opt_from_disk
@classmethod
def add_cmdline_args(
cls, parser: ParlaiParser, partial_opt: Optional[Opt] = None
) -> ParlaiParser:
"""
Add command line arguments.
"""
agent = parser.add_argument_group('Torch Generator Agent')
agent.add_argument(
'--beam-size',
type=int,
default=1,
help='Beam size, if 1 then greedy search',
)
agent.add_argument(
'--beam-min-length',
type=int,
default=1,
help='Minimum length of prediction to be generated by the beam search',
)
agent.add_argument(
'--beam-context-block-ngram',
type=int,
default=-1,
help=(
'Size n-grams to block in beam search from the context. val <= 0 '
'implies no blocking'
),
)
agent.add_argument(
'--beam-block-ngram',
type=int,
default=-1,
help='Size n-grams to block in beam search. val <= 0 implies no blocking',
)
agent.add_argument(
'--beam-block-full-context',
type='bool',
default=True,
help='Block n-grams from the *full* history context. Specify False to block '
'up to m tokens in the past, where m is truncation parameter for agent',
)
agent.add_argument(
'--beam-length-penalty',
type=float,
default=0.65,
help='Applies a length penalty. Set to 0 for no penalty.',
)
agent.add_argument(
'--skip-generation',
type='bool',
default=False,
hidden=True,
help='Skip beam search. Useful for speeding up training, '
'if perplexity is the validation metric.',
)
agent.add_argument(
'--inference',
choices={'beam', 'greedy', 'topk', 'nucleus', 'delayedbeam'},
default='greedy',
help='Generation algorithm',
)
agent.add_argument(
'--topk', type=int, default=10, help='K used in Top K sampling'
)
agent.add_argument(
'--topp', type=float, default=0.9, help='p used in nucleus sampling'
)
agent.add_argument(
'--beam-delay', type=int, default=30, help='used in delayedbeam search'
)
agent.add_argument(
'--beam-block-list-filename',
type=str,
default=None,
help='Load a text file of hard blocks for beam search to never say.',
)
agent.add_argument(
'--temperature',
type=float,
default=1.0,
help='temperature to add during decoding',
)
agent.add_argument(
'--compute-tokenized-bleu',
type='bool',
default=False,
help='if true, compute tokenized bleu scores',
)
super().add_cmdline_args(parser, partial_opt=partial_opt)
return agent
def __init__(self, opt: Opt, shared=None):
init_model, is_finetune = self._get_init_model(opt, shared)
super().__init__(opt, shared)
self.beam_size = opt.get('beam_size', 1)
self.beam_min_length = opt.get('beam_min_length', 1)
self.beam_block_ngram = opt.get('beam_block_ngram', -1)
self.beam_context_block_ngram = opt.get('beam_context_block_ngram', -1)
self.beam_block_full_context = opt.get('beam_block_full_context', False)
self.temperature = opt.get('temperature', 1.0)
assert self.temperature > 0, '--temperature must be greater than 0'
self.output_token_losses = opt.get(
'verbose', False
) or 'token_losses' in opt.get('display_add_fields', '')
self.compute_tokenized_bleu = opt.get('compute_tokenized_bleu', False)
self.beam_block_list: Optional[SearchBlocklist] = None
if shared:
# set up shared properties
states = shared.get('states', {})
self.beam_block_list = shared.get('beam_block_list')
else:
# this is not a shared instance of this class, so do full init
self.criterion = self.build_criterion()
# ensure all distributed copies will always be in sync
self.model = self.build_model()
# load the block_list for beam search
self.beam_block_list = self._load_beam_block_list()
if self.model is None or self.criterion is None:
raise AttributeError(
'build_model() and build_criterion() need to return the model or criterion'
)
if self.use_cuda:
if self.model_parallel:
ph = PipelineHelper()
ph.check_compatibility(self.opt)
self.model = ph.make_parallel(self.model)
else:
self.model.cuda()
self.criterion.cuda()
sync_parameters(self.model)
train_params = trainable_parameters(self.model)
total_params = total_parameters(self.model)
logging.info(
f"Total parameters: {total_params:,d} ({train_params:,d} trainable)"
)
if self.fp16:
self.model = self.model.half()
if init_model is not None:
# load model parameters if available
logging.info(f'Loading existing model params from {init_model}')
states = self.load(init_model)
else:
states = {}
if shared is not None:
if 'optimizer' in shared:
self.optimizer = shared['optimizer']
elif self._should_initialize_optimizer():
# do this regardless of share state, but don't
self.init_optim(
[p for p in self.model.parameters() if p.requires_grad],
optim_states=states.get('optimizer'),
saved_optim_type=states.get('optimizer_type'),
)
self.build_lr_scheduler(states, hard_reset=is_finetune)
if shared is None and is_distributed():
device_ids = None if self.model_parallel else [self.opt['gpu']]
self.model = torch.nn.parallel.DistributedDataParallel(
self.model, device_ids=device_ids, broadcast_buffers=False
)
self.reset()
def build_criterion(self):
"""
Construct and return the loss function.
By default torch.nn.CrossEntropyLoss.
If overridden, this model should produce a sum that can be used for a per-token loss.
"""
if not self.fp16:
return torch.nn.CrossEntropyLoss(
ignore_index=self.NULL_IDX, reduction='none'
)
else:
# FP16 safe cross entropy (softmax done in FP32)
return FP16SafeCrossEntropy(ignore_index=self.NULL_IDX, reduction='none')
def _v2t(self, vec):
"""
Convert token indices to string of tokens.
"""
new_vec = []
if hasattr(vec, 'cpu'):
vec = vec.cpu()
for i in vec:
if i == self.END_IDX:
break
elif i != self.START_IDX:
new_vec.append(i)
return self.dict.vec2txt(new_vec)
def set_interactive_mode(self, mode, shared=False):
"""
Turn on interactive mode.
"""
super().set_interactive_mode(mode, shared)
if mode:
self.skip_generation = False
else:
self.skip_generation = self.opt.get('skip_generation', False)
def _dummy_batch(self, batchsize, maxlen):
"""
Create a dummy batch.
This is used to preinitialize the cuda buffer, or otherwise force a
null backward pass after an OOM.
If your model uses additional inputs beyond text_vec and label_vec,
you will need to override it to add additional fields.
"""
text_vec = (
torch.arange(1, maxlen + 1) # need it as long as specified
.clamp(max=3) # cap at 3 for testing with tiny dictionaries
.unsqueeze(0)
.expand(batchsize, maxlen)
.cuda()
)
# label vec has two tokens to make it interesting, but we we can't use the
# start token, it's reserved.
label_vec = (
torch.LongTensor([self.END_IDX, self.NULL_IDX])
.unsqueeze(0)
.expand(batchsize, 2)
.cuda()
)
return Batch(
text_vec=text_vec, label_vec=label_vec, text_lengths=[maxlen] * batchsize
)
def _init_cuda_buffer(self, batchsize, maxlen, force=False):
"""
Pre-initialize CUDA buffer by doing fake forward pass.
This is also used in distributed mode to force a worker to sync with others.
"""
if self.use_cuda and (force or not hasattr(self, 'buffer_initialized')):
try:
self._control_local_metrics(disabled=True)
loss = 0 * self.compute_loss(self._dummy_batch(batchsize, maxlen))
self._control_local_metrics(enabled=True)
self._temporarily_disable_local_metrics = False
self.backward(loss)
self.buffer_initialized = True
except RuntimeError as e:
if 'out of memory' in str(e):
m = (
'CUDA OOM: Lower batch size (-bs) from {} or lower '
' max sequence length (-tr) from {}'
''.format(batchsize, maxlen)
)
raise RuntimeError(m)
else:
raise e
def reset_metrics(self):
"""
Reset metrics for reporting loss and perplexity.
"""
super().reset_metrics()
def share(self):
"""
Share internal states between parent and child instances.
"""
shared = super().share()
shared['beam_block_list'] = self.beam_block_list
if hasattr(self, 'optimizer'):
shared['optimizer'] = self.optimizer
return shared
def vectorize(self, *args, **kwargs):
"""
Override vectorize for generative models.
"""
kwargs['add_start'] = False # model does this in module code
kwargs['add_end'] = True # we do want this
return super().vectorize(*args, **kwargs)
def _model_input(self, batch):
"""
Create the input (x) value for the model.
Must return a tuple. This will be passed directly into the model via
`*args`, i.e.,
>>> model(*_model_input(batch))
This is intentionally overridable so that richer models can pass the
additional inputs.
"""
return (batch.text_vec,)
def _encoder_input(self, batch):
"""
Create the input (x) value for the encoder.
Must return a tuple. This will be passed directly into the encoder via
`*args`, i.e.,
>>> model.encoder(*_encoder_input(batch))
This is intentionally overridable so that richer models can pass the
additional inputs directly to the encoder.
"""
return self._model_input(batch)
def compute_loss(self, batch, return_output=False):
"""
Compute and return the loss for the given batch.
Easily overridable for customized loss functions.
If return_output is True, the full output from the call to self.model()
is also returned, via a (loss, model_output) pair.
"""
if batch.label_vec is None:
raise ValueError('Cannot compute loss without a label.')
model_output = self.model(*self._model_input(batch), ys=batch.label_vec)
scores, preds, *_ = model_output
score_view = scores.view(-1, scores.size(-1))
loss = self.criterion(score_view, batch.label_vec.view(-1))
loss = loss.view(scores.shape[:-1]).sum(dim=1)
# save loss to metrics
notnull = batch.label_vec.ne(self.NULL_IDX)
target_tokens = notnull.long().sum(dim=-1)
correct = ((batch.label_vec == preds) * notnull).sum(dim=-1)
self.record_local_metric('loss', AverageMetric.many(loss, target_tokens))
self.record_local_metric('ppl', PPLMetric.many(loss, target_tokens))
self.record_local_metric(
'token_acc', AverageMetric.many(correct, target_tokens)
)
# actually do backwards loss
loss = loss.sum()
loss /= target_tokens.sum() # average loss per token
if return_output:
return (loss, model_output)
else:
return loss
def train_step(self, batch):
"""
Train on a single batch of examples.
"""
# helps with memory usage
# note we want to use the opt's batchsize instead of the observed batch size
# in case dynamic batching is in use
self._init_cuda_buffer(self.opt['batchsize'], self.label_truncate or 256)
self.model.train()
self.zero_grad()
try:
loss = self.compute_loss(batch)
self.backward(loss)
self.update_params()
oom_sync = False
except RuntimeError as e:
# catch out of memory exceptions during fwd/bck (skip batch)
if 'out of memory' in str(e):
oom_sync = True
logging.error(
'Ran out of memory, skipping batch. '
'if this happens frequently, decrease batchsize or '
'truncate the inputs to the model.'
)
self.global_metrics.add('skipped_batches', SumMetric(1))
else:
raise e
if oom_sync:
# moved outside of the try-except because the raised exception in scope
# actually prevents from the data being freed, which can sometimes cause
# us to OOM during our OOM handling.
# https://github.com/pytorch/pytorch/issues/18853#issuecomment-583779161
# gradients are synced on backward, now this model is going to be
# out of sync! catch up with the other workers
self._init_cuda_buffer(8, 8, True)
def _construct_token_losses(self, labels, model_output):
# Get non-aggregated losses
scores, _, _ = model_output
score_view = scores.view(-1, scores.size(-1))
losses = self.criterion(score_view, labels.view(-1)).view(len(labels), -1)
# Zip decoded tokens with losses
token_losses = []
for i, label in enumerate(labels):
token_losses.append(
list(
zip(
[self.dict[token] for token in label.tolist()],
losses[i].tolist(),
)
)
)
return token_losses
def _compute_fairseq_bleu(self, batch: Batch, preds):
"""
Compute BLEU score between text and label, using the FAIRSeq BLEU Scorer.
:param batch:
Batch of observations
:param texts:
list of string predictions
"""
all_results = []
label_vec = batch.label_vec
assert label_vec is not None, "label_vec must exist for fairseq bleu"
for i, t in enumerate(preds):
result = FairseqBleuMetric.compute_many(
t[1:],
label_vec[i].unsqueeze(0),
pad_idx=self.NULL_IDX,
end_idx=self.END_IDX,
unk_idx=self.dict[self.dict.unk_token],
)
if result is None:
return
all_results.append(result)
bleu_scores = list(zip(*all_results))
for k in range(4):
self.record_local_metric(f'fairseq_bleu{k + 1}', bleu_scores[k])
def _compute_nltk_bleu(self, batch: Batch, texts: List[str]):
"""
Compute BLEU score between text and label(s), using the NLTK BLEU Scorer.
Note this differs from BLEU in ParlAI metrics in that the answers
are unnormalized (no removal of stop words, etc.)
:param batch:
Batch of observations
:param texts:
list of string predictions
"""
results: Dict[int, List[Metric]] = {}
observations = batch.observations
assert observations is not None, 'observations must not be none in nltk bleu'
for i, p in enumerate(texts):
obs = observations[i]
references = []
for lbl in obs['eval_labels']:
references.append(
self._v2t(
self._vectorize_text(
lbl, True, True, self.label_truncate, False
)
)
)
for k in range(1, 5):
b = BleuMetric.compute(p, references, k)
if b is None:
b = BleuMetric(0)
if k not in results:
results[k] = []
results[k].append(b)
for k in range(1, 5):
self.record_local_metric(f'nltk_bleu{k}', results[k])
def _add_generation_metrics(self, batch, preds):
"""
Can be overridden to allow for some metrics on the generations calculated at
eval.
"""
pass
def eval_step(self, batch):
"""
Evaluate a single batch of examples.
"""
if batch.text_vec is None and batch.image is None:
return
if batch.text_vec is not None:
bsz = batch.text_vec.size(0)
else:
bsz = len(batch.image)
self.model.eval()
cand_scores = None
token_losses = None
if batch.label_vec is not None:
# calculate loss on targets with teacher forcing
loss, model_output = self.compute_loss(batch, return_output=True)
if self.output_token_losses:
token_losses = self._construct_token_losses(
batch.label_vec, model_output
)
preds = None
if self.skip_generation:
warn_once("--skip-generation true produces limited metrics")
else:
maxlen = self.label_truncate or 256
beam_preds_scores, beams = self._generate(batch, self.beam_size, maxlen)
preds, scores = zip(*beam_preds_scores)
self._add_generation_metrics(batch, preds)
# bsz x beamsize
beam_texts: List[List[Tuple[str, float]]] = []
for beam in beams:
beam_texts.append([])
for tokens, score in beam.get_rescored_finished():
try:
beam_texts[-1].append((self._v2t(tokens), score.item()))
except KeyError:
logging.error("Decoding error: %s", tokens)
continue
cand_choices = None
# TODO: abstract out the scoring here
if self.rank_candidates:
# compute roughly ppl to rank candidates
cand_choices = []
encoder_states = self.model.encoder(*self._encoder_input(batch))
for i in range(bsz):
num_cands = len(batch.candidate_vecs[i])
enc = self.model.reorder_encoder_states(encoder_states, [i] * num_cands)
cands, _ = self._pad_tensor(batch.candidate_vecs[i])
scores, _ = self.model.decode_forced(enc, cands)
cand_losses = F.cross_entropy(
scores.view(num_cands * cands.size(1), -1),
cands.view(-1),
reduction='none',
).view(num_cands, cands.size(1))
# now cand_losses is cands x seqlen size, but we still need to
# check padding and such
mask = (cands != self.NULL_IDX).float()
cand_scores = (cand_losses * mask).sum(dim=1) / (mask.sum(dim=1) + 1e-9)
_, ordering = cand_scores.sort()
cand_choices.append([batch.candidates[i][o] for o in ordering])
text = [self._v2t(p) for p in preds] if preds is not None else None
if text and self.compute_tokenized_bleu:
# compute additional bleu scores
self._compute_fairseq_bleu(batch, preds)
self._compute_nltk_bleu(batch, text)
retval = Output(text, cand_choices, token_losses=token_losses)
if not self.skip_generation:
retval.beam_texts = beam_texts
return retval
def _treesearch_factory(self, device):
method = self.opt.get('inference', 'greedy')
beam_size = self.opt.get('beam_size', 1)
if method == 'greedy':
return GreedySearch(
beam_size,
min_length=0,
block_ngram=self.beam_block_ngram,
context_block_ngram=self.beam_context_block_ngram,
length_penalty=self.opt.get('beam_length_penalty', 0.65),
padding_token=self.NULL_IDX,
bos_token=self.START_IDX,
eos_token=self.END_IDX,
device=device,
)
elif method == 'beam':
return BeamSearch(
beam_size,
min_length=self.beam_min_length,
block_ngram=self.beam_block_ngram,
context_block_ngram=self.beam_context_block_ngram,
length_penalty=self.opt.get('beam_length_penalty', 0.65),
padding_token=self.NULL_IDX,
bos_token=self.START_IDX,
eos_token=self.END_IDX,
device=device,
)
elif method == 'delayedbeam':
return DelayedBeamSearch(
self.opt['topk'],
self.opt['beam_delay'],
beam_size,
min_length=self.beam_min_length,
block_ngram=self.beam_block_ngram,
context_block_ngram=self.beam_context_block_ngram,
length_penalty=self.opt.get('beam_length_penalty', 0.65),
padding_token=self.NULL_IDX,
bos_token=self.START_IDX,
eos_token=self.END_IDX,
device=device,
)
elif method == 'topk':
return TopKSampling(
self.opt['topk'],
beam_size,
min_length=self.beam_min_length,
block_ngram=self.beam_block_ngram,
context_block_ngram=self.beam_context_block_ngram,
length_penalty=self.opt.get('beam_length_penalty', 0.65),
padding_token=self.NULL_IDX,
bos_token=self.START_IDX,
eos_token=self.END_IDX,
device=device,
)
elif method == 'nucleus':
return NucleusSampling(
self.opt['topp'],
beam_size,
min_length=self.beam_min_length,