-
Notifications
You must be signed in to change notification settings - Fork 0
/
prompt_bart.py
2889 lines (2524 loc) · 104 KB
/
prompt_bart.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.
"""
BART: Denoising Sequence-to-Sequence Pre-training for
Natural Language Generation, Translation, and Comprehension
See https://arxiv.org/abs/1910.13461.
The BART agent can be instantiated as simply `-m bart`,
however it is recommended to specify `--init-model zoo:bart/bart_large/model`
or `-mf zoo:bart/bart_large/model` to ensure correct dictionaries are saved.
"""
from __future__ import annotations
# from abc import ABC, abstractmethod
from dataclasses import dataclass
from typing import Any, Dict, List, Optional, Tuple, Type, Union
import numpy as np
import torch
import torch.cuda
import torch.nn.functional as F
from torch import nn
# import parlai.utils.fsdp as fsdp_utils
from parlai.agents.bart.convert_fairseq_to_parlai import ConversionScript
from parlai.agents.transformer.modules import (
TransformerDecoder,
TransformerEncoder,
create_embeddings,
)
from parlai.agents.transformer.modules.modular import swappable
from parlai.agents.transformer.transformer import (
# _check_positional_embeddings,
add_common_cmdline_args,
)
# from parlai.core.agents import compare_init_model_opts
# from parlai.core.message import Message
from parlai.core.torch_generator_agent import SearchBlocklist
from parlai.core.metrics import AverageMetric, FairseqBleuMetric, SumMetric
from parlai.core.opt import Opt
from parlai.core.params import ParlaiParser
from parlai.core.torch_agent import (
Batch,
DictionaryAgent,
History,
Output,
TorchAgent,
)
from parlai.core.torch_generator_agent import (
BeamSearch,
DelayedBeamSearch,
GreedySearch,
NucleusSampling,
PPLMetric,
SearchBlocklist,
TopKSampling,
TorchGeneratorModel,
TorchGeneratorAgent,
)
# from parlai.agents.transformer.transformer import TransformerGeneratorAgent
from parlai.core.metrics import ExactMatchMetric, F1Metric
# from parlai.utils.distributed import is_distributed, sync_parameters
from parlai.utils.fp16 import FP16SafeCrossEntropy
# from parlai.utils.io import PathManager
from parlai.utils.logging import logging
from parlai.utils.misc import AttrDict, recursive_getattr, warn_once
from parlai.utils.torch import (
# PipelineHelper,
argsort,
neginf,
# total_parameters,
# trainable_parameters,
)
# from parlai.utils.typing import TShared
from parlai.zoo.bart.build import BART_ARGS, CONVERSION_ARGS, download
from parlai.agents.bart.bart import BartAgent
DecoderIncrState = Dict[int, Dict[str, Dict[str, torch.tensor]]]
from parlai.core.core_utils import (
NashBargainingLoss,
MultiTaskBatch,
OutputGenerator,
OutputClassifier,
GlobalModelOutput,
set_requires_grad
)
from parlai.agents.transformer.modules import (
create_position_codes,
get_n_positions_from_options,
LAYER_NORM_EPS,
MultiHeadAttention,
TransformerFFN,
)
from parlai.core.params import default
from parlai.utils.torch import PipelineHelper
from parlai.utils.fsdp import fsdp_wrap
from parlai.nn.checkpoint import checkpoint_wrapper
from parlai.agents.transformer.modules import (
create_position_codes,
get_n_positions_from_options,
LAYER_NORM_EPS,
MultiHeadAttention,
TransformerFFN,
)
from abc import ABC
################
# Decoder #
################
DecoderIncrState = Dict[int, Dict[str, Dict[str, torch.Tensor]]]
# Prefix Changes
class BaseTransformerDecoder(nn.Module, ABC):
"""
Implements functionality common to all transformer decoder variants. Not intended to
be instantiated directly.
For a (Vaswani 2017) style encoder-decoder transformer, use ``TransformerDecoder``. For a GPT-style decoder-only transformer, use ``TransformerDecoderOnly``.
Subclasses are required to implement ``forward``. In your ``forward`` implementation, you can call ``forward_embedding`` to get embeddings for the input tokens and ``forward_layers`` to pass those embeddings sequentially through each layer.
Subclasses can optionally override ``__init__``, ``build_layer``, and
``build_layers`` to customize subcomponents. In particular, ``build_layer`` can be used to instantiate heterogeneous layers (e.g. every other layer being a different type).
"""
def __init__(
self,
opt: Opt,
embedding: nn.Embedding,
dictionary: DictionaryAgent,
n_positions: Optional[int] = None,
**kwargs,
):
super().__init__()
self.opt = opt
self.pad_idx = dictionary[dictionary.null_token]
self.start_idx = dictionary[dictionary.start_token]
self.end_idx = dictionary[dictionary.end_token]
self.embedding_size = opt['embedding_size']
self.ffn_size = opt['ffn_size']
self.n_layers = (
opt['n_decoder_layers']
if opt.get('n_decoder_layers', -1) > 0
else opt['n_layers']
)
self.n_heads = opt['n_heads']
self.dim = self.embedding_size
self.activation = opt.get('activation', 'relu')
self.variant = opt.get('variant', 'aiayn')
self.embeddings_scale = opt.get('embeddings_scale', True)
self.dropout = nn.Dropout(p=opt.get('dropout', 0.0)) # --dropout
self.n_positions = default(n_positions, get_n_positions_from_options(opt))
self.out_dim = self.embedding_size
assert (
self.embedding_size % self.n_heads == 0
), 'Transformer embedding size must be a multiple of n_heads'
self.embeddings = embedding
if (
self.variant == 'xlm'
or self.variant == 'prelayernorm'
or self.variant == 'bart'
):
self.norm_embeddings = torch.nn.LayerNorm(self.dim, eps=LAYER_NORM_EPS)
if self.variant == 'xlm':
warn_once(
'DEPRECATED: XLM should only be used for backwards compatibility, '
'as it involves a less-stable layernorm operation.'
)
elif self.variant == 'aiayn':
pass
else:
raise ValueError("Can't handle --variant {}".format(self.variant))
# create the positional embeddings
self.position_embeddings = nn.Embedding(self.n_positions, self.embedding_size)
if not opt.get('learn_positional_embeddings', False):
create_position_codes(
self.n_positions,
self.embedding_size,
out=self.position_embeddings.weight,
)
else:
nn.init.normal_(
self.position_embeddings.weight, 0, self.embedding_size**-0.5
)
# build the model
self.layers = self.build_layers()
def build_layers(self) -> nn.ModuleList:
"""
Instantiates all layers. Called only once during __init__.
Additional setup common to all layers, such as checkpoint wrapping, can be done
here.
"""
layers = nn.ModuleList()
for i in range(self.n_layers):
layer = self.build_layer(index=i)
if self.opt.get('checkpoint_activations'):
layer = checkpoint_wrapper(layer)
layers.append(fsdp_wrap(layer)) # type: ignore
return layers
def build_layer(self, index: int) -> BaseTransformerDecoderLayer:
"""
Instantiate a single layer. Called n_layers times during __init__.
:param int index:
Index of current layer.
"""
return BaseTransformerDecoderLayer( # type: ignore
self.opt,
attention_dropout=self.opt.get('attention_dropout', 0.0),
relu_dropout=self.opt.get('relu_dropout', 0.0),
dropout=self.opt.get('dropout', 0.0),
activation=self.activation,
variant=self.variant,
)
def forward(
self,
input: torch.Tensor,
encoder_state: Tuple[torch.Tensor, torch.Tensor],
incr_state: Optional[DecoderIncrState] = None,
**kwargs,
) -> Tuple[torch.Tensor, DecoderIncrState]:
"""
Forward pass.
:param LongTensor[batch,seqlen] input:
The decoder inputs (partial or full decoded token IDs).
:param encoder_state:
Output from the encoder module forward pass.
:param incr_state:
The incremental state: a dictionary whose keys index the layers and whose
values contain the incremental state for each layer.
"""
raise NotImplementedError
def forward_embedding(
self,
input: torch.LongTensor,
positions: Optional[torch.LongTensor] = None,
segments: Optional[torch.LongTensor] = None,
**kwargs,
):
"""
Embed tokens prior to feeding into transformer.
:param LongTensor[batch, seqlen] input:
The target input IDs
:param LongTensor[batch, seqlen] positions:
Positions for input IDs. If None, computes defaults.
:param LongTensor[batch, seqlen] segments:
Segment IDs for extra embedding features. If None, not used.
:return (tensor, mask):
embedded input and mask
"""
tensor = self.embeddings(input)
if self.opt["prefix_seq_len"]:
positions = positions + self.opt["prefix_seq_len"]
tensor = self.embeddings(input)
if self.embeddings_scale:
tensor = tensor * np.sqrt(self.dim)
if self.variant == 'xlm':
tensor = self.norm_embeddings(tensor)
if positions.max().item() > self.n_positions:
warn_once(
'You are inputting a sequence of {x} length, but only have '
'--n-positions {y}. Set --truncate or increase --n-positions'.format(
x=positions.max().item(), y=self.n_positions
)
)
tensor = tensor + self.position_embeddings(positions).expand_as(tensor)
if self.variant == 'bart':
tensor = self.norm_embeddings(tensor)
return tensor
def forward_layers(
self, tensor: torch.Tensor, *extra_args, incr_state: DecoderIncrState, **kwargs
) -> Tuple[torch.Tensor, DecoderIncrState]:
"""
Forward pass of decoder layers.
:param tensor:
embedded input tensor for the decoder
:param extra_args:
any number of positional arguments to be passed to each layer
:param incr_state:
Dict mapping layer_idx to incremental state
:param kwargs:
any number of keyword (named) arguments to be passed to each layer
:return (tensor, new_incr_state):
return encoding after applying decoder layers, as well
as new incremental decoding state.
"""
new_incr_state = {}
if getattr(self.layers, 'is_model_parallel', False):
tensor, new_incr_state = self._apply_model_parallel(
tensor, *extra_args, incr_state=incr_state
)
else:
for idx, layer in enumerate(self.layers):
# print("inside decoder ", idx)
# print("tensor ", tensor.shape)
if "past_key_values" in kwargs and kwargs["past_key_values"] is not None:
if "past_key_values" in kwargs and idx in kwargs["past_key_values"]:
# print("using this ")
past_key_values = kwargs["past_key_values"][idx]
batch_size, seq_len = tensor.size(0), tensor.size(1)
new_mask = torch.zeros(batch_size, seq_len, self.opt["prefix_seq_len"]).cuda()
past_key_values.mask = new_mask
else:
past_key_values = None
if "inference_mode" in kwargs:
# print(kwargs['inference_mode'], kwargs['decoding_idx'])
if kwargs['decoding_idx'] == 1:
batch_size, seq_len = tensor.size(0), tensor.size(1)
new_mask = torch.zeros(batch_size, 1, 8).cuda()
past_key_values = {"prev_mask": new_mask}
else:
past_key_values = None
tensor, new_incr_state[idx] = layer(
tensor, *extra_args, incr_state=incr_state.get(idx), past_key_values=past_key_values
)
return tensor, new_incr_state
def _apply_model_parallel(
self, tensor: torch.Tensor, *extra_args, incr_state: DecoderIncrState
) -> Tuple[torch.Tensor, DecoderIncrState]:
"""
Pipeline application of model parallelism.
"""
chunks = PipelineHelper.split((tensor, *extra_args, incr_state))
work_items = PipelineHelper.schedule_work_items(self.layers, chunks)
new_incr_state = {i: [] for i, _ in enumerate(self.layers)}
for chunk_idx, layer_nos, next_device in work_items:
s_tensor, *s_extra_args, s_incr_state = chunks[chunk_idx]
for layer_no in layer_nos:
s_tensor, nis = self.layers[layer_no](
s_tensor, *s_extra_args, incr_state=s_incr_state.get(layer_no)
)
new_incr_state[layer_no].append(nis)
# don't move incr state, it's always on the correct device
s_layer_args = PipelineHelper.chunk_to(
(s_tensor, *s_extra_args), next_device
)
chunks[chunk_idx] = (*s_layer_args, s_incr_state)
tensor_out = PipelineHelper.join([c[0] for c in chunks])
new_incr_state = {
layer_no: PipelineHelper.join(pieces)
for layer_no, pieces in new_incr_state.items()
}
return tensor_out, new_incr_state
class BaseTransformerDecoderLayer(nn.Module, ABC):
"""
Implements functionality common to all transformer decoder layer variants. Subclass
this if you'd like to modify the behavior of any layer in a transformer decoder.
While this code is functional, it is not intended to be instantiated directly. If
this functionality is desired as-is, use TransformerDecoderOnlyLayer instead to gain
the ability to swap self-attention and feedforward classes at instantiation.
"""
def __init__(
self,
opt: Opt,
n_heads: int = None,
embedding_size: int = None,
ffn_size: int = None,
attention_dropout: float = 0.0,
relu_dropout: float = 0.0,
dropout: float = 0.0,
activation: str = 'relu',
variant: str = 'aiayn',
**kwargs,
):
super().__init__()
n_heads = default(n_heads, opt['n_heads'])
embedding_size = default(embedding_size, opt['embedding_size'])
ffn_size = default(ffn_size, opt['ffn_size'])
self.opt = opt
self.dim = embedding_size
self.ffn_dim = ffn_size
self.variant = variant
self.activation = activation
self.dropout = nn.Dropout(p=dropout)
self.self_attention = self.build_self_attention(
n_heads=n_heads, dim=embedding_size, dropout=attention_dropout
)
self.norm1 = torch.nn.LayerNorm(embedding_size, eps=LAYER_NORM_EPS)
self.ffn = self.build_feedforward(
dim=embedding_size,
dim_hidden=ffn_size,
relu_dropout=relu_dropout,
activation=activation,
)
self.norm3 = torch.nn.LayerNorm(embedding_size, eps=LAYER_NORM_EPS)
def build_self_attention(
self, n_heads: int = None, dim: int = None, dropout: float = 0
) -> MultiHeadAttention:
return MultiHeadAttention(
opt=self.opt, n_heads=n_heads, dim=dim, dropout=dropout
)
def build_feedforward(
self,
dim: int = None,
dim_hidden: int = None,
relu_dropout: float = 0,
activation: str = 'relu',
) -> TransformerFFN:
return TransformerFFN(
opt=self.opt,
dim=dim,
dim_hidden=dim_hidden,
relu_dropout=relu_dropout,
activation=activation,
)
def forward(
self,
x: torch.Tensor,
*extra_args,
incr_state: Optional[DecoderLayerIncrState] = None,
**kwargs,
) -> Tuple[torch.Tensor, DecoderLayerIncrState]:
"""
Forward pass.
The incremental state is a dict with values for self-attention states.
"""
if incr_state is None:
incr_state = {}
decoder_mask = self._create_selfattn_mask(x)
# first self attn
residual = x
if self.variant == 'prelayernorm':
x = self.norm1(x)
# don't peak into the future!
x, final_self_attn_incr_state = self.self_attention(
query=x,
mask=decoder_mask,
incr_state=incr_state.get('self_attn'),
static_kv=False,
**kwargs,
)[:2]
x = self.dropout(x) # --dropout
x = x + residual
if self.variant == 'aiayn' or self.variant == 'xlm' or self.variant == 'bart':
x = self.norm1(x)
# finally the ffn
residual = x
if self.variant == 'prelayernorm':
x = self.norm3(x)
x = self.ffn(x, **kwargs)
x = self.dropout(x) # --dropout
x = residual + x
if self.variant == 'aiayn' or self.variant == 'xlm' or self.variant == 'bart':
x = self.norm3(x)
return x, {'self_attn': final_self_attn_incr_state}
def reorder_incremental_state(
self, incremental_state: DecoderLayerIncrState, inds: torch.Tensor
) -> Dict[str, dict]:
"""
Reorder all incremental-state tensors for this layer.
"""
attn_types = {'self_attn': self.self_attention}
return {
attn_type: attn.reorder_incremental_state(
incremental_state[attn_type], inds
)
for attn_type, attn in attn_types.items()
}
def _create_selfattn_mask(self, x):
# figure out how many timestamps we need
bsz = x.size(0)
time = x.size(1)
# make sure that we don't look into the future
mask = torch.tril(x.new(time, time).fill_(1))
# broadcast across batch
mask = mask.unsqueeze(0).expand(bsz, -1, -1)
return mask
@swappable(
self_attention=MultiHeadAttention,
encoder_attention=MultiHeadAttention,
feedforward=TransformerFFN,
)
class TransformerDecoderLayer(BaseTransformerDecoderLayer):
"""
Implements a single Transformer decoder layer with cross (encoder) attention as in
[Vaswani, 2017](https://arxiv.org/abs/1706.03762).
Decoder layers are similar to encoder layers but:
1. Self-attention is limited in a causal (auto-regressive) manner.
2. Attend over all of the encoder states.
"""
def __init__(
self,
opt: Opt,
n_heads: int = None,
embedding_size: int = None,
ffn_size: int = None,
attention_dropout: float = 0.0,
relu_dropout: float = 0.0,
dropout: float = 0.0,
activation: str = 'relu',
variant: str = 'aiayn',
**kwargs,
):
super().__init__(
opt=opt,
n_heads=n_heads,
embedding_size=embedding_size,
ffn_size=ffn_size,
attention_dropout=attention_dropout,
relu_dropout=relu_dropout,
dropout=dropout,
activation=activation,
variant=variant,
**kwargs,
)
n_heads = default(n_heads, opt['n_heads'])
embedding_size = default(embedding_size, opt['embedding_size'])
self.encoder_attention = self.swappables.encoder_attention( # type: ignore
opt=self.opt, n_heads=n_heads, dim=embedding_size, dropout=attention_dropout
)
self.norm2 = torch.nn.LayerNorm(embedding_size, eps=LAYER_NORM_EPS)
def build_self_attention(
self, n_heads: int = None, dim: int = None, dropout: float = 0
) -> MultiHeadAttention:
"""
Overridden to allow swapping out of the attention class at instantiation.
"""
return self.swappables.self_attention( # type: ignore
opt=self.opt, n_heads=n_heads, dim=dim, dropout=dropout
)
def build_feedforward(
self,
dim: int = None,
dim_hidden: int = None,
relu_dropout: float = 0,
activation: str = 'relu',
) -> TransformerFFN:
"""
Overridden to allow swapping out of the feedforward class at instantiation.
"""
return self.swappables.feedforward( # type: ignore
opt=self.opt,
dim=dim,
dim_hidden=dim_hidden,
relu_dropout=relu_dropout,
activation=activation,
)
def forward(
self,
x: torch.Tensor,
encoder_output: torch.Tensor,
encoder_mask: torch.Tensor,
incr_state: Optional[DecoderLayerIncrState] = None,
**kwargs,
) -> Tuple[torch.Tensor, DecoderLayerIncrState]:
"""
Forward pass.
The incremental state is a dict with values for self- and encoder-attention
states.
"""
if incr_state is None:
incr_state = {}
decoder_mask = self._create_selfattn_mask(x)
# first self attn
residual = x
if self.variant == 'prelayernorm':
x = self.norm1(x)
# don't peak into the future!
x, final_self_attn_incr_state = self.self_attention(
query=x,
mask=decoder_mask,
incr_state=incr_state.get('self_attn'),
static_kv=False,
**kwargs,
)[:2]
x = self.dropout(x) # --dropout
x = x + residual
if self.variant == 'aiayn' or self.variant == 'xlm' or self.variant == 'bart':
x = self.norm1(x)
residual = x
# encoder_attn_layer_norm norm 2
if self.variant == 'prelayernorm':
x = self.norm2(x)
x, final_encoder_attn_incr_state = self.encoder_attention(
query=x,
key=encoder_output,
value=encoder_output,
mask=encoder_mask,
incr_state=incr_state.get('encoder_attn'),
static_kv=True,
**kwargs,
)[:2]
x = self.dropout(x) # --dropout
x = residual + x
if self.variant == 'aiayn' or self.variant == 'xlm' or self.variant == 'bart':
x = self.norm2(x)
# finally the ffn
residual = x
if self.variant == 'prelayernorm':
x = self.norm3(x)
x = self.ffn(x, **kwargs)
x = self.dropout(x) # --dropout
x = residual + x
if self.variant == 'aiayn' or self.variant == 'xlm' or self.variant == 'bart':
x = self.norm3(x)
new_incr_state = {
'self_attn': final_self_attn_incr_state,
'encoder_attn': final_encoder_attn_incr_state,
}
return x, new_incr_state
def reorder_incremental_state(
self, incremental_state: DecoderLayerIncrState, inds: torch.Tensor
) -> DecoderLayerIncrState:
"""
Reorder all incremental-state tensors for this layer.
"""
attn_types = {
'self_attn': self.self_attention,
'encoder_attn': self.encoder_attention,
}
return {
attn_type: attn.reorder_incremental_state(
incremental_state[attn_type], inds
)
for attn_type, attn in attn_types.items()
}
@swappable(layer=TransformerDecoderLayer)
class TransformerDecoder(BaseTransformerDecoder):
"""
Transformer Decoder module.
For documentation on parameters that are take directly from opt,
see parlai/agents/transformer/transformer.py
:param opt: ParlAI-parsed options.
:param embedding: an embedding matrix for the bottom layer of the transformer.
If none, one is created for this encoder.
:param int n_positions: Size of the position embeddings matrix.
"""
def build_layer(self, index: int) -> BaseTransformerDecoderLayer:
"""
Instantiate a single layer. Called n_layers times during __init__.
Overridden to allow swapping out of the layer class at instantiation.
:param int index:
Index of current layer.
"""
return self.swappables.layer( # type: ignore
self.opt,
attention_dropout=self.opt.get('attention_dropout', 0.0),
relu_dropout=self.opt.get('relu_dropout', 0.0),
dropout=self.opt.get('dropout', 0.0),
activation=self.activation,
variant=self.variant,
)
def forward(
self,
input: torch.Tensor,
encoder_state: Tuple[torch.Tensor, torch.Tensor],
incr_state: Optional[DecoderIncrState] = None,
**kwargs,
) -> Tuple[torch.Tensor, DecoderIncrState]:
"""
Forward pass.
:param LongTensor[batch,seqlen] input:
The decoder inputs (partial or full decoded token IDs).
:param encoder_state:
Output from the encoder module forward pass.
:param incr_state:
The incremental state: a dictionary whose keys index the layers and whose
values contain the incremental state for each layer.
"""
encoder_output, encoder_mask = encoder_state
seq_len = input.size(1)
positions = torch.arange(
seq_len, dtype=torch.long, device=input.device
).unsqueeze(0)
if incr_state is not None:
# We're doing incremental decoding, so select only the most recent position
input = input[:, -1:]
if positions is not None:
positions = positions[:, -1:]
else:
incr_state = {}
tensor = self.forward_embedding(input, positions, **kwargs)
tensor = self.dropout(tensor) # --dropout
tensor, new_incr_state = self.forward_layers(
tensor, encoder_output, encoder_mask, incr_state=incr_state, **kwargs
)
if self.variant == 'prelayernorm':
tensor = self.norm_embeddings(tensor)
return tensor, new_incr_state
###########################
# ENCODER MODULES #
###########################
@swappable(self_attention=MultiHeadAttention, feedforward=TransformerFFN)
class TransformerEncoderLayer(nn.Module):
"""
Implements a single Transformer encoder layer.
"""
def __init__(
self,
opt: Opt,
n_heads: int = None,
embedding_size: int = None,
ffn_size: int = None,
attention_dropout: float = 0.0,
relu_dropout: float = 0.0,
dropout: float = 0.0,
activation: str = 'relu',
variant: Optional[str] = None,
**kwargs,
):
super().__init__()
n_heads = default(n_heads, opt['n_heads'])
embedding_size = default(embedding_size, opt['embedding_size'])
ffn_size = default(ffn_size, opt['ffn_size'])
self.opt = opt
self.dim = embedding_size
self.ffn_dim = ffn_size
self.activation = activation
self.variant = variant
self.attention = self.swappables.self_attention( # type: ignore
opt=self.opt,
n_heads=n_heads,
dim=embedding_size,
dropout=attention_dropout, # --attention-dropout
)
self.norm1 = torch.nn.LayerNorm(embedding_size, eps=LAYER_NORM_EPS)
self.ffn = self.swappables.feedforward( # type: ignore
opt=self.opt,
dim=embedding_size,
dim_hidden=ffn_size,
relu_dropout=relu_dropout,
activation=self.activation,
)
self.norm2 = torch.nn.LayerNorm(embedding_size, eps=LAYER_NORM_EPS)
self.dropout = nn.Dropout(p=dropout)
def forward(
self, tensor: torch.Tensor, mask: torch.Tensor, **kwargs
) -> torch.Tensor:
"""
Forward pass.
"""
residual = tensor
if self.variant == 'prelayernorm':
tensor = self.norm1(tensor)
attended_tensor = self.attention(tensor, mask=mask, **kwargs)[0]
tensor = residual + self.dropout(attended_tensor)
if self.variant == 'aiayn' or self.variant == 'xlm' or self.variant == 'bart':
tensor = self.norm1(tensor)
residual = tensor
if self.variant == 'prelayernorm':
tensor = self.norm2(tensor)
tensor = residual + self.dropout(self.ffn(tensor))
if self.variant == 'aiayn' or self.variant == 'xlm' or self.variant == 'bart':
tensor = self.norm2(tensor)
tensor *= mask.unsqueeze(-1).type_as(tensor)
return tensor
class PrefixEmbedding(torch.nn.Module):
'''
The torch.nn model to encode the prefix
Input shape: (batch-size, prefix-length)
Output shape: (batch-size, prefix-length, 2*layers*hidden)
'''
def __init__(self, config):
super().__init__()
self.prefix_embedding = nn.Embedding(config["prefix_seq_len"], config["embedding_size"])
self.prefix_weights = torch.nn.Sequential(
torch.nn.Linear(
config['embedding_size'], config["prefix_mid_dim"]
),
torch.nn.Tanh(),
nn.Linear(config['prefix_mid_dim'], config['prefix_mid_dim']),
nn.Tanh(),
torch.nn.Linear(
config['prefix_mid_dim'],
config["num_decoder_layers"]*config["embedding_size"]
),
)
self.apply(self._init_weights)
def _init_weights(self, module):
if isinstance(module, nn.Linear):
nn.init.kaiming_uniform_(module.weight)
# module.weight.data.normal_(mean=0.0, std=1.0)
if module.bias is not None:
module.bias.data.zero_()
def forward(self, prefix_tokens: torch.Tensor):
prefix_embeds = self.prefix_embedding(prefix_tokens)
past_key_values = self.prefix_weights(prefix_embeds)
# print(past_key_values.shape)
# prefix_embeds = prefix_embeds.view(
# prefix_embeds.size(0), -1, 1024
# )
return past_key_values
# forward embeddings is here
# Positions embeddings are switched
@swappable(layer=TransformerEncoderLayer)
class TransformerEncoder(nn.Module):
"""
Transformer encoder module.
For documentation on parameters that are take directly from opt,
see parlai/agents/transformer/transformer.py
:param opt: ParlAI-parsed options.
:param vocabulary_size: Count of tokens/words in the dictionary.
:param embedding: an embedding matrix for the bottom layer of the transformer.
If none, one is created for this encoder.
:param int padding_idx: Reserved padding index in the embeddings matrix.
:param str reduction_type: Type of reduction at the end of the encoder.
:param int n_positions: Size of the position embeddings matrix.
:param int n_segments: Number of segments/lang/sentence embeddings.
:param bool embeddings_scale: Scale embeddings relative to their dimensionality.
Found useful in fairseq.
"""
def __init__(
self,
opt: Opt,
vocabulary_size: int,
embedding: Optional[nn.Embedding] = None,
padding_idx: int = 0,
reduction_type: str = 'mean',
n_positions: Optional[int] = None,
n_segments: Optional[int] = None,
embeddings_scale: Optional[bool] = None,
dropout: Optional[float] = None,
activation: Optional[str] = None,
variant: Optional[str] = None,
output_scaling: Optional[float] = None,
**kwargs,
):
super().__init__()
self.opt = opt
self.embedding_size = opt['embedding_size']
self.ffn_size = opt['ffn_size']
self.n_layers = (
opt['n_encoder_layers']
if opt.get('n_encoder_layers', -1) > 0
else opt['n_layers']
)
self.n_heads = opt['n_heads']
self.dim = self.embedding_size
self.embeddings_scale = default(
embeddings_scale, opt.get('embeddings_scale', False)
)
self.reduction_type = reduction_type
self.padding_idx = padding_idx
# this is --dropout, not --relu-dropout or --attention-dropout
self.dropout_frac = default(dropout, opt.get('dropout', 0.0))
self.dropout = nn.Dropout(p=self.dropout_frac)
self.activation = default(activation, opt.get('activation', 'relu'))
self.variant = default(variant, opt.get('variant', 'aiayn'))
self.n_segments = default(n_segments, opt.get('n_segments', 0))
self.n_positions = default(n_positions, get_n_positions_from_options(opt))
self.out_dim = self.embedding_size
assert (
self.embedding_size % self.n_heads == 0
), 'Transformer embedding size must be a multiple of n_heads'
# check input formats:
if embedding is not None:
assert (
self.embedding_size is None
or self.embedding_size == embedding.weight.shape[1]
), "Embedding dim must match the embedding size."
if embedding is not None:
self.embeddings = embedding
else:
raise AssertionError(
"This code should not execute. Left here in case we want to enable it."
)
assert self.padding_idx is not None
self.embeddings = nn.Embedding(
vocabulary_size, self.embedding_size, padding_idx=padding_idx
)
nn.init.normal_(self.embeddings.weight, 0, self.embedding_size**-0.5)
# create the positional embeddings
self.position_embeddings = nn.Embedding(self.n_positions, self.embedding_size)
if not opt.get('learn_positional_embeddings', False):
create_position_codes(
self.n_positions,
self.embedding_size,
out=self.position_embeddings.weight,
)
else:
nn.init.normal_(
self.position_embeddings.weight, 0, self.embedding_size**-0.5
)
# embedding normalization
if (
self.variant == 'xlm'
or self.variant == 'prelayernorm'
or self.variant == 'bart'
):
self.norm_embeddings = torch.nn.LayerNorm(self.dim, eps=LAYER_NORM_EPS)
elif self.variant == 'aiayn':
pass
else:
raise ValueError("Can't handle --variant {}".format(self.variant))