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
/
Copy pathtorch_agent.py
2414 lines (2087 loc) · 89.8 KB
/
torch_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.
"""
General utility code for building PyTorch-based agents in ParlAI.
Contains the following main utilities:
* TorchAgent class which serves as a useful parent class for other model agents
* Batch namedtuple which is the input type of the main abstract methods of
the TorchAgent class
* Output namedtuple which is the expected output type of the main abstract
methods of the TorchAgent class
* History class which handles tracking the dialogue state over the course of an episode.
See below for documentation on each specific tool.
"""
from parlai.core.params import ParlaiParser
from typing import Dict, Any, Union, List, Tuple, Optional
from abc import ABC, abstractmethod
import random
import warnings
import torch
import parlai.utils.logging as logging
from torch import optim
from parlai.core.opt import Opt
from parlai.core.agents import Agent
from parlai.core.dict import DictionaryAgent, TokenizationMode
from parlai.nn.lr_scheduler import ParlAILRScheduler
from parlai.core.message import Message
from parlai.utils.distributed import is_distributed
from parlai.utils.misc import AttrDict, warn_once
from parlai.utils.io import PathManager
from parlai.utils.fsdp import (
should_sync_gradnorm,
is_fsdp,
DEFAULT_DDP_BACKEND,
FSDP_AVAILABLE,
get_state_dict,
)
from parlai.utils.fp16 import (
SafeFP16Optimizer,
MemoryEfficientFP16Optimizer,
MemoryEfficientFP16Adam,
Adafactor,
)
from parlai.core.metrics import (
AverageMetric,
Metrics,
Metric,
GlobalAverageMetric,
GlobalFixedMetric,
GlobalTimerMetric,
)
from parlai.utils.distributed import is_primary_worker
from parlai.utils.torch import argsort, compute_grad_norm, padded_tensor, atomic_save
class Batch(AttrDict):
"""
Batch is a namedtuple containing data being sent to an agent.
This is the input type of the train_step and eval_step functions. Agents
can override the batchify function to return a Batch with additional fields
if they would like, though we recommend calling the parent function to set
up these fields as a base.
Batch objects contain some magic semantics when dealing with CUDA. Namely,
Batch objects have a to() method that can be used to send all tensors to
a particular device (GPU). This is undesireable in some instances, as some
fields may be used only for accumulating metrics, or are only used on CPU.
Prefixing a field with an underscore will prevent it from being transferred
to GPU.
Note that in upcoming versions of ParlAI, we will enable features for getting
speedups in training which work best when the number of non-Tensor objects
in a batch is minimal.
:param text_vec:
bsz x seqlen tensor containing the parsed text data.
:param label_vec:
bsz x seqlen tensor containing the parsed label (one per batch row).
:param labels:
list of length bsz containing the selected label for each batch row (some
datasets have multiple labels per input example).
:param valid_indices:
tensor of length bsz containing the original indices of each example in the
batch. we use these to map predictions back to their proper row, since e.g.
we may sort examples by their length or some examples may be invalid.
:param candidates:
list of lists of text. outer list has size bsz, inner lists vary in size
based on the number of candidates for each row in the batch.
:param candidate_vecs:
list of lists of tensors. outer list has size bsz, inner lists vary in size
based on the number of candidates for each row in the batch.
:param image:
list of image features in the format specified by the --image-mode arg.
:param reward:
Tensor containing the "reward" field of observations, if present
"""
batchsize: int
is_training: bool
text_vec: Optional[torch.LongTensor]
label_vec: Optional[torch.LongTensor]
labels: Optional[List[str]]
valid_indices: Optional[torch.LongTensor]
candidates: Optional[List[List[str]]]
candidate_vecs: Optional[List[List[torch.LongTensor]]]
image: Optional[List[Any]]
_context_original_length: Optional[torch.LongTensor]
_context_truncate_rate: Optional[torch.LongTensor]
_context_truncated_length: Optional[torch.LongTensor]
_label_original_length: Optional[torch.LongTensor]
_label_truncate_rate: Optional[torch.LongTensor]
_label_truncated_length: Optional[torch.LongTensor]
def __init__(
self,
text_vec=None,
text_lengths=None,
label_vec=None,
label_lengths=None,
labels=None,
valid_indices=None,
candidates=None,
candidate_vecs=None,
reward=None,
image=None,
is_training: Optional[bool] = None,
_context_original_length: Optional[torch.LongTensor] = None,
_context_truncate_rate: Optional[torch.LongTensor] = None,
_context_truncated_length: Optional[torch.LongTensor] = None,
_label_original_length: Optional[torch.LongTensor] = None,
_label_truncate_rate: Optional[torch.LongTensor] = None,
_label_truncated_length: Optional[torch.LongTensor] = None,
**kwargs,
):
super().__init__(
text_vec=text_vec,
text_lengths=text_lengths,
label_vec=label_vec,
label_lengths=label_lengths,
labels=labels,
valid_indices=valid_indices,
candidates=candidates,
candidate_vecs=candidate_vecs,
image=image,
is_training=is_training,
_context_original_length=_context_original_length,
_context_truncate_rate=_context_truncate_rate,
_context_truncated_length=_context_truncated_length,
_label_original_length=_label_original_length,
_label_truncate_rate=_label_truncate_rate,
_label_truncated_length=_label_truncated_length,
**kwargs,
)
def to(self, dev):
"""
Move all tensors in the batch to a device.
NOT in place.
Note that valid_indices and fields starting with an underscore are
always kept on CPU.
:return:
self
"""
output = {}
for key in self.keys():
value = getattr(self, key)
# never move valid_indices or keys starting with a _
if key == 'valid_indices' or key.startswith('_'):
output[key] = value
continue
if torch.is_tensor(value):
output[key] = value.to(dev)
else:
output[key] = value
return type(self)(**output)
def __repr__(self):
output = ['Batch({']
for key in sorted(self.keys()):
value = self[key]
if key == 'observations' and value is None:
output.append(f' {key}: {value} (use --debug to include),')
elif value is None:
output.append(f' {key}: {value},')
elif isinstance(value, torch.Tensor):
typ = value.type().replace("torch.", "")
shape = ", ".join(str(s) for s in value.shape)
output.append(f' {key}: {typ}[{shape}],')
else:
s = repr(value)
output.append(f' {key}: {s},')
output.append('})')
return "\n".join(output)
class Output(AttrDict):
"""
Output is an object containing agent predictions.
This is the expected return type of the train_step and eval_step functions,
though agents can choose to return None if they do not want to answer.
:param List[str] text:
list of strings of length bsz containing the predictions of the model
:param List[List[str]] text_candidates:
list of lists of length bsz containing ranked predictions of the model.
each sub-list is an ordered ranking of strings, of variable length.
"""
def __init__(self, text=None, text_candidates=None, **kwargs):
super().__init__(text=text, text_candidates=text_candidates, **kwargs)
class History(object):
"""
History handles tracking the dialogue state over the course of an episode.
History may also be used to track the history of any field.
:param field:
field in the observation to track over the course of the episode
(defaults to 'text')
:param maxlen:
sets the maximum number of tunrs
:param p1_token:
token indicating 'person 1'; opt must have 'person_tokens' set to True
for this to be added
:param p1_token:
token indicating 'person 2'; opt must have 'person_tokens' set to True
for this to be added
:param dict_agent:
DictionaryAgent object for tokenizing the history
"""
def __init__(
self,
opt,
field='text',
maxlen=None,
size=-1,
p1_token='__p1__',
p2_token='__p2__',
dict_agent=None,
):
self.field = field
self.dict = dict_agent
self.delimiter = opt.get('delimiter', '\n')
self.delimiter_tok = self.parse(self.delimiter)
self.size = size
self.split_on_newln = opt.get('split_lines', False)
self.reversed = opt.get('history_reversed', False)
self._global_end_token = opt.get('history_add_global_end_token', None)
if self._global_end_token is not None:
self._global_end_token = self.dict[self.dict.end_token]
# set up history objects
self.max_len = maxlen
self.history_strings = []
self.history_raw_strings = []
self.history_vecs = []
self.temp_history = None
# person token args
self.add_person_tokens = opt.get('person_tokens', False)
self.add_p1_after_newln = opt.get('add_p1_after_newln', False)
self.p1_token = p1_token
self.p2_token = p2_token
def parse(self, text):
"""
Tokenize text with the given dictionary.
"""
return self.dict.txt2vec(text)
def reset(self):
"""
Clear the history.
"""
self.history_raw_strings = []
self.history_strings = []
self.history_vecs = []
def _update_strings(self, text):
if self.size > 0:
while len(self.history_strings) >= self.size:
self.history_strings.pop(0)
self.history_strings.append(text)
def _update_raw_strings(self, text):
if self.size > 0:
while len(self.history_raw_strings) >= self.size:
self.history_raw_strings.pop(0)
self.history_raw_strings.append(text)
def _update_vecs(self, text):
if self.size > 0:
while len(self.history_vecs) >= self.size:
self.history_vecs.pop(0)
self.history_vecs.append(self.parse(text))
def add_reply(self, text):
"""
Add your own response to the history.
"""
self._update_raw_strings(text)
if self.add_person_tokens:
text = self._add_person_tokens(text, self.p2_token)
# update history string
self._update_strings(text)
# update history vecs
self._update_vecs(text)
def update_history(self, obs: Message, temp_history: Optional[str] = None):
"""
Update the history with the given observation.
:param obs:
Observation used to update the history.
:param temp_history:
Optional temporary string. If it is not None, this string will be
appended to the end of the history. It will not be in the history
on the next dialogue turn. Set to None to stop adding to the
history.
"""
if self.field in obs and obs[self.field] is not None:
if self.split_on_newln:
next_texts = obs[self.field].split('\n')
else:
next_texts = [obs[self.field]]
for text in next_texts:
self._update_raw_strings(text)
if self.add_person_tokens:
text = self._add_person_tokens(
obs[self.field], self.p1_token, self.add_p1_after_newln
)
# update history string
self._update_strings(text)
# update history vecs
self._update_vecs(text)
self.temp_history = temp_history
def get_history_str(self) -> Optional[str]:
"""
Return the string version of the history.
"""
if len(self.history_strings) > 0:
history = self.history_strings[:]
history = self.delimiter.join(history)
if self.temp_history is not None:
history += self.temp_history
return history
return None
def get_history_vec(self):
"""
Return a vectorized version of the history.
"""
if len(self.history_vecs) == 0:
return None
# vec type is a list
history = []
for vec in self.history_vecs[:-1]:
history += [vec]
history += [self.delimiter_tok]
history += [self.history_vecs[-1]]
if self.temp_history is not None:
history.extend([self.parse(self.temp_history)])
if self._global_end_token is not None:
history += [[self._global_end_token]]
history = sum(history, [])
if self.reversed:
history = list(reversed(history))
return history
def get_history_vec_list(self):
"""
Return a list of history vecs.
"""
return self.history_vecs
def _add_person_tokens(self, text, token, add_after_newln=False):
if add_after_newln:
split = text.split('\n')
split[-1] = token + ' ' + split[-1]
return '\n'.join(split)
else:
return token + ' ' + text
def __str__(self) -> str:
return self.get_history_str() or ''
class TorchAgent(ABC, Agent):
"""
A provided abstract base agent for any model that wants to use Torch.
Exists to make it easier to implement a new agent.
Not necessary, but reduces duplicated code.
Many methods are intended to be either used as is when the default is
acceptable, or to be overriden and called with super(), with the extra
functionality added to the initial result. See the method comment for
recommended behavior.
This agent serves as a common framework for all ParlAI models which want
to use PyTorch.
"""
P1_TOKEN = '__p1__'
P2_TOKEN = '__p2__'
@classmethod
def optim_opts(cls):
"""
Fetch optimizer selection.
By default, collects everything in torch.optim, as well as importing:
- qhm / qhmadam if installed from github.com/facebookresearch/qhoptim
Override this (and probably call super()) to add your own optimizers.
"""
# first pull torch.optim in
optims = {
k.lower(): v
for k, v in optim.__dict__.items()
if not k.startswith('__') and k[0].isupper()
}
try:
from fairscale.optim import Adam as FusedAdam
optims['fusedadam'] = FusedAdam
except ImportError:
pass
# now pull in memory efficient implementations
optims['mem_eff_adam'] = MemoryEfficientFP16Adam
optims['adafactor'] = Adafactor
return optims
@staticmethod
def dictionary_class():
"""
Return the dictionary class that this agent expects to use.
Can be overridden if a more complex dictionary is required.
"""
return DictionaryAgent
@classmethod
def history_class(cls):
"""
Return the history class that this agent expects to use.
Can be overridden if a more complex history is required.
"""
return History
@classmethod
def add_cmdline_args(
cls, parser: ParlaiParser, partial_opt: Optional[Opt] = None
) -> ParlaiParser:
"""
Add the default commandline args we expect most agents to want.
"""
agent = parser.add_argument_group('TorchAgent Arguments')
agent.add_argument(
'-i',
'--interactive-mode',
type='bool',
default=False,
help='Whether in full interactive mode or not, which means generating text or'
' retrieving from a full set of candidates, which is necessary to actually'
' do full dialogue. However, during training or quick validation (e.g. PPL for'
' generation or ranking a few candidates for ranking models) you might want these'
' set to off.'
' Typically, scripts can set their preferred default behavior at the start,'
' e.g. eval scripts.',
)
# pretrained embedding arguments
agent.add_argument(
'-emb',
'--embedding-type',
default='random',
choices=[
'random',
'glove',
'glove-fixed',
'fasttext',
'fasttext-fixed',
'fasttext_cc',
'fasttext_cc-fixed',
],
help='Choose between different strategies for initializing word '
'embeddings. Default is random, but can also preinitialize '
'from Glove or Fasttext. Preinitialized embeddings can also '
'be fixed so they are not updated during training.',
)
agent.add_argument(
'-embp',
'--embedding-projection',
default='random',
help='If pretrained embeddings have a different dimensionality '
'than your embedding size, strategy for projecting to the '
'correct size. If the dimensions are the same, this is '
'ignored unless you append "-force" to your choice.',
)
agent.add_argument(
'--fp16', type='bool', default=False, help='Use fp16 computations.'
)
agent.add_argument(
'--fp16-impl',
type=str,
default='safe',
choices=['safe', 'mem_efficient'],
help='Implementation of FP16 to use',
)
agent.add_argument(
'--force-fp16-tokens',
type='bool',
default=False,
hidden=True,
help='Add the special fp16 tokens even if not using fp16.',
)
# optimizer arguments
optim_group = agent.add_argument_group('Optimizer Arguments')
optim_group.add_argument(
'-opt',
'--optimizer',
default='sgd',
metavar='OPTIMIZER',
choices=cls.optim_opts(),
help=(
f'Optimizer choice. Possible values: '
f'{", ".join(cls.optim_opts().keys())}.'
),
)
optim_group.add_argument(
'-lr', '--learningrate', type=float, default=1, help='Learning rate'
)
optim_group.add_argument(
'-clip',
'--gradient-clip',
type=float,
default=0.1,
help='gradient clipping using l2 norm',
)
optim_group.add_argument(
'--adam-eps',
type=float,
default=1e-8,
hidden=True,
help='Epsilon value for Adam optimizers. Set to 1e-6 if your '
'large model has stability issues, but prefer the default.',
)
optim_group.add_argument(
'--adafactor-eps',
default='1e-30,1e-3',
type='floats',
help='Epsilon values for adafactor optimizer: regularization '
'constants for square gradient and parameter scale respectively',
recommended='1e-30,1e-3',
)
optim_group.add_argument(
'-mom',
'--momentum',
default=0,
type=float,
help='if applicable, momentum value for optimizer.',
)
optim_group.add_argument(
'--nesterov',
default=True,
type='bool',
help='if applicable, whether to use nesterov momentum.',
)
optim_group.add_argument(
'-nu',
'--nus',
default='0.7',
type='floats',
help='if applicable, nu value(s) for optimizer. can use a single '
'value like 0.7 or a comma-separated tuple like 0.7,1.0',
)
optim_group.add_argument(
'-beta',
'--betas',
default='0.9,0.999',
type='floats',
help='if applicable, beta value(s) for optimizer. can use a single '
'value like 0.9 or a comma-separated tuple like 0.9,0.999',
)
optim_group.add_argument(
'-wdecay',
'--weight-decay',
type=float,
default=None,
help='Weight decay on the weights.',
)
# preprocessing arguments
agent.add_argument(
'-rc',
'--rank-candidates',
type='bool',
default=False,
help='Whether the model should parse candidates for ranking.',
)
agent.add_argument(
'-tr',
'--truncate',
default=-1,
type=int,
help='Truncate input lengths to increase speed / use less memory.',
)
agent.add_argument(
'--text-truncate',
type=int,
help='Text input truncation length: if not specified, this will '
'default to `truncate`',
)
agent.add_argument(
'--label-truncate',
type=int,
help='Label truncation length: if not specified, this will default '
'to `truncate`',
)
agent.add_argument(
'--history-reversed', default=False, type='bool', help='Reverse the history'
)
agent.add_argument(
'-histsz',
'--history-size',
default=-1,
type=int,
help='Number of past dialog utterances to remember.',
)
agent.add_argument(
'-pt',
'--person-tokens',
type='bool',
default=False,
help='add person tokens to history. adds __p1__ in front of input '
'text and __p2__ in front of past labels when available or '
'past utterances generated by the model. these are added to '
'the dictionary during initialization.',
)
agent.add_argument(
'--split-lines',
type='bool',
default=False,
help='split the dialogue history on newlines and save in separate '
'vectors',
)
agent.add_argument(
'--use-reply',
default='label',
hidden=True,
choices=['label', 'model', 'none'],
help='Which previous replies to use as history. If label, use '
'gold dataset replies. If model, use model\'s own replies. '
'If none, do not track replies in history.',
)
agent.add_argument(
'--add-p1-after-newln',
type='bool',
default=False,
hidden=True,
help='Add the other speaker token before the last newline in the '
'input instead of at the beginning of the input. this is '
'useful for tasks that include some kind of context before '
'the actual utterance (e.g. squad, babi, personachat).',
)
agent.add_argument(
'--delimiter',
type=str,
default='\n',
help='Join history lines with this token, defaults to newline',
)
agent.add_argument(
'--history-add-global-end-token',
type='nonestr',
default=None,
hidden=True,
help='Add special token to the end of history encoding.',
)
agent.add_argument(
'--special-tok-lst',
type=str,
default=None,
help=(
'Comma separated list of special tokens. '
'In case of ambiguous parses from special tokens, the ordering '
'provided in this arg sets precedence.'
),
)
# GPU arguments
# these gpu options are all mutually exclusive, and should error if the
# user tries to present multiple of them
gpugroup = agent.add_mutually_exclusive_group()
gpugroup.add_argument(
'-gpu', '--gpu', type=int, default=-1, help='which GPU to use'
)
gpugroup.add_argument(
'--no-cuda',
default=False,
action='store_true',
dest='no_cuda',
help='disable GPUs even if available. otherwise, will use GPUs if '
'available on the device.',
)
cls.dictionary_class().add_cmdline_args(parser, partial_opt=partial_opt)
ParlAILRScheduler.add_cmdline_args(parser, partial_opt=partial_opt)
return parser
def __init__(self, opt: Opt, shared=None):
"""
Initialize agent.
"""
super().__init__(opt, shared)
self.is_debug = opt.get('is_debug', False)
opt = self.opt
# Safety checkers to ensure TorchAgent assumptions aren't being violated.
self.__expecting_clear_history = False
self.__expecting_to_reply = False
# used for sharing metrics back to the teacher
self._local_metrics: Dict[str, List[Metric]] = {}
# we may want to temporarily disable local metrics, roughly similar to
# `with torch.no_grad`. See TorchGeneratorAgent._init_cuda_buffer for
# example
self.__local_metrics_enabled = True
# check for cuda
self.use_cuda = not opt['no_cuda'] and torch.cuda.is_available()
if self.use_cuda:
if not shared:
logging.info('Using CUDA')
if not shared and opt['gpu'] != -1:
torch.cuda.set_device(opt['gpu'])
# whether we're using multi-gpu, a few different ways. these are not
# supported by all models, but we can still keep track of the options
self.model_parallel = opt.get('model_parallel', False) and self.use_cuda
self.data_parallel = opt.get('data_parallel', False) and self.use_cuda
if self.data_parallel and is_distributed():
raise RuntimeError('Cannot combine --data-parallel and distributed mode.')
if self.model_parallel and self.data_parallel:
raise RuntimeError('Cannot combine --data-parallel and --model-parallel.')
# indicate whether using fp16
self.fp16 = self.use_cuda and self.opt.get('fp16', False)
if self.fp16:
# check that the implementation requested is available
self.fp16_impl = self.opt.get('fp16_impl', 'safe')
if shared is None:
# intialize any important structures from scratch
self.dict = self.build_dictionary()
if opt.get('fp16') or opt.get('force_fp16_tokens'):
# Volta cores revert to FP32 hardware if tensors are not multiples
# of 8 in all dimensions. This INCLUDES the embeddings layer! As
# such, we need some extra magic to ensure the dictionary is padded
# with extra tokens to make it a multiple of 8.
from parlai.utils.torch import FP16_PAD_SIZE
if len(self.dict) % FP16_PAD_SIZE != 0:
for i in range(FP16_PAD_SIZE - len(self.dict) % FP16_PAD_SIZE):
self.dict['__FP16_PAD_{}__'.format(i)] = 1
# global_metrics keeps track of batch-level or global-level metrics
self.global_metrics = Metrics(shared=None)
# self.metrics is there for legacy reasons
self.metrics: Dict[str, Any] = {}
else:
# copy initialized data from shared table
self.opt = shared['opt']
self.dict = shared['dict']
self.model = shared['model']
self.criterion = shared['criterion']
self.metrics = shared['metrics']
self.global_metrics = Metrics(shared=shared['global_metrics'])
# Default to the class name, sans "Agent". child can override
self.id = type(self).__name__.replace("Agent", "")
# now set up any fields that all instances may need
self.EMPTY = torch.zeros(0, dtype=torch.long)
self.NULL_IDX = self.dict[self.dict.null_token]
self.START_IDX = self.dict[self.dict.start_token]
self.END_IDX = self.dict[self.dict.end_token]
# for gradient acumulation
self._number_grad_accum = 0
# for the LR scheduler
self._number_training_updates = 0
# fixed random seed
self.random = random.Random(42)
# can remember as few as zero utterances if desired
self.histsz = opt['history_size']
# truncate == 0 might give funny behavior
self.truncate = opt['truncate'] if opt['truncate'] >= 0 else None
text_truncate = opt.get('text_truncate') or opt['truncate']
self.text_truncate = text_truncate if text_truncate >= 0 else None
label_truncate = opt.get('label_truncate') or opt['truncate']
self.label_truncate = label_truncate if label_truncate >= 0 else None
# stores up to hist_utt past observations within current dialog
self.history = self.build_history()
self.history_reversed = opt.get('history_reversed', False)
self.is_training = False # track whether model is training
self.rank_candidates = opt['rank_candidates']
self.add_person_tokens = opt.get('person_tokens', False)
# set interactive mode or not according to options.
self.set_interactive_mode(opt.get('interactive_mode', False), shared)
def build_history(self):
"""
Return the constructed history object.
"""
return self.history_class()(
self.opt,
maxlen=self.text_truncate,
size=self.histsz,
p1_token=self.P1_TOKEN,
p2_token=self.P2_TOKEN,
dict_agent=self.dict,
)
def build_dictionary(self):
"""
Return the constructed dictionary, which will be set to self.dict.
If you need to add additional tokens to the dictionary, this is likely the right
place to do it.
"""
d = self.dictionary_class()(self.opt)
self.special_toks = self._get_special_tokens()
if self.special_toks:
d.add_additional_special_tokens(self.special_toks)
if self.opt.get('person_tokens'):
d[self.P1_TOKEN] = 999_999_999
d[self.P2_TOKEN] = 999_999_998
return d
def _resize_token_embeddings(self, state_dict, msg=None):
"""
Must define this for your agent if you wish to add additional special tokens.
Must make a call to resize the token embeddings and load the model state dict
with the resized token embeddings.
"""
raise NotImplementedError(
'If you are intending to add special tokens to an already pretrained model, '
'you must write the function `_resize_token_embeddings` for your specific '
'agent.'
)
def _get_init_model(self, opt: Opt, shared):
"""
Get model file to initialize with.
If `init_model` exits, we will return the path to that file and maybe
load dict file from that path. Otherwise, use `model_file.`
:return: path to load model from, whether we loaded from `init_model`
or not
"""
init_model = None
is_finetune = False
if not shared: # only do this on first setup
# first check load path in case we need to override paths
if opt.get('init_model') and PathManager.exists(opt['init_model']):
# check first for 'init_model' for loading model from file
init_model = opt['init_model']
is_finetune = True
if opt.get('model_file') and PathManager.exists(opt['model_file']):
# next check for 'model_file', this would override init_model
init_model = opt['model_file']
is_finetune = False
if (
opt.get('load_from_checkpoint')
and opt.get('init_model')
and opt['init_model'].endswith('.checkpoint')
):
# but if we're loading from a checkpoint, we should explicitly load
# from that point
init_model = opt['init_model']
is_finetune = False
if init_model is not None:
# if we are loading a model, should load its dict too
if PathManager.exists(init_model + '.dict') or opt['dict_file'] is None:
opt['dict_file'] = init_model + '.dict'
return init_model, is_finetune
def _get_special_tokens(self) -> List[str]:
"""
Return list of special tokens.
Made easily overridable for special cases.
Note that in the case of ambiguity of special-token parsing, the
precedence is set by the ordering returned in this method. For
example, if special tokens are ["OHB", "BOY"], parsing "OHBOY" will
become (special)OHB and (normal)OY. But with special tokens
["BOY", "OHB"], then we will get (normal)OH and (special)BOY.
"""
if self.opt.get('special_tok_lst'):
return self.opt['special_tok_lst'].split(',')
return []
@abstractmethod
def build_model(self):
"""
Construct the model and return it.
"""
raise NotImplementedError('not implemented for this class')
def _should_initialize_optimizer(self) -> bool:
"""
Used to indicate whether we should initialize an optimizer.
When this is off, we can save memory and use larger batches.
"""
if self.opt.get('interactive_mode'):
return False
datatype = self.opt.get('datatype', '')
is_train = 'train' in datatype and 'evalmode' not in datatype
return is_train
def init_optim(
self,
params,
optim_states=None,
saved_optim_type=None,
is_finetune: bool = False,
) -> bool:
"""
Initialize optimizer with model parameters.
:param params:
parameters from the model
:param optim_states:
optional argument providing states of optimizer to load
:param saved_optim_type:
type of optimizer being loaded, if changed will skip loading
optimizer states
:param is_finetune:
bool indicating whether this training run is a fine-tune or not
:returns:
boolean indicating whether the optimizer failed to initialize with
optim_states.
"""
if hasattr(self, 'resized_embeddings') and self.resized_embeddings:
optim_states = None
logging.warning('Not loading optimizer due to resize in token embeddings')
opt = self.opt
# set up optimizer args
lr = opt['learningrate']
kwargs = {'lr': lr}