/
modeling_mbart.py
executable file
·3938 lines (3443 loc) · 230 KB
/
modeling_mbart.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
# coding=utf-8
# Copyright 2021, The Facebook AI Research Team and The HuggingFace Inc. team. All rights reserved.
# Copyright 2021, National Institute of Information and Communication Technology (Raj Dabre)
# Modified portions by Raj Dabre are indicated as so.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
""" PyTorch MBART model. """
import copy
import math
import random
from typing import Optional, Tuple
import torch
from torch import nn, einsum
from einops import rearrange, repeat
import numpy as np
import torch.nn.functional as F
import torch.utils.checkpoint
from torch import nn
from torch.nn import CrossEntropyLoss
## Modified by Raj Dabre. Start.
from torch.autograd import Function
from mixture_of_experts import MoE
from math import log, pi
## Modified by Raj Dabre. End.
from ...activations import ACT2FN
from ...file_utils import (
add_code_sample_docstrings,
add_end_docstrings,
add_start_docstrings,
add_start_docstrings_to_model_forward,
replace_return_docstrings,
)
from ...modeling_outputs import (
BaseModelOutput,
BaseModelOutputWithPastAndCrossAttentions,
CausalLMOutputWithCrossAttentions,
Seq2SeqLMOutput,
Seq2SeqModelOutput,
Seq2SeqQuestionAnsweringModelOutput,
Seq2SeqSequenceClassifierOutput,
)
from ...modeling_utils import PreTrainedModel
from ...utils import logging
from .configuration_mbart import MBartConfig
logger = logging.get_logger(__name__)
_CONFIG_FOR_DOC = "MBartConfig"
_TOKENIZER_FOR_DOC = "MBartTokenizer"
MBART_PRETRAINED_MODEL_ARCHIVE_LIST = [
"facebook/mbart-large-cc25",
# See all MBART models at https://huggingface.co/models?filter=mbart
]
def shift_tokens_right(input_ids: torch.Tensor, pad_token_id: int):
"""
Shift input ids one token to the right, and wrap the last non pad token (the <LID> token) Note that MBart does not
have a single `decoder_start_token_id` in contrast to other Bart-like models.
"""
prev_output_tokens = input_ids.clone()
assert pad_token_id is not None, "self.model.config.pad_token_id has to be defined."
# replace possible -100 values in labels by `pad_token_id`
prev_output_tokens.masked_fill_(prev_output_tokens == -100, pad_token_id)
index_of_eos = (prev_output_tokens.ne(pad_token_id).sum(dim=1) - 1).unsqueeze(-1)
decoder_start_tokens = prev_output_tokens.gather(1, index_of_eos).squeeze()
prev_output_tokens[:, 1:] = prev_output_tokens[:, :-1].clone()
prev_output_tokens[:, 0] = decoder_start_tokens
return prev_output_tokens
# Copied from transformers.models.bart.modeling_bart._make_causal_mask
def _make_causal_mask(input_ids_shape: torch.Size, dtype: torch.dtype, past_key_values_length: int = 0):
"""
Make causal mask used for bi-directional self-attention.
"""
bsz, tgt_len = input_ids_shape
mask = torch.full((tgt_len, tgt_len), torch.finfo(dtype).min) ## Changed here to -1e10 float("-inf") ## Modified by Raj Dabre.
mask_cond = torch.arange(mask.size(-1))
mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0)
mask = mask.to(dtype)
if past_key_values_length > 0:
mask = torch.cat([torch.zeros(tgt_len, past_key_values_length, dtype=dtype), mask], dim=-1)
return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len + past_key_values_length)
## Modified by Raj Dabre. Start.
# Copied from transformers.models.bart.modeling_bart._expand_mask
def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None, wait_k: Optional[int] = -1, curr_decode_length: Optional[int] = -1):
"""
Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
"""
bsz, src_len = mask.size()
tgt_len = tgt_len if tgt_len is not None else src_len
expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)
if wait_k != -1:
if curr_decode_length == -1:
expanded_mask = torch.tril(expanded_mask, wait_k-1) ## This causes the attention mask to be lower triangular to mask future tokens. If wait-k is k then the diagonal shift should be k-1.
else:
expanded_mask = torch.tril(expanded_mask, (curr_decode_length-1) + (wait_k-1)) ## This causes the attention mask to be lower triangular to mask future tokens. If wait-k is k then the diagonal shift should be k-1. This is used during decoding time as tgt_len will always be 1 so we need to shift the triangle by an appropriate amount.
inverted_mask = 1.0 - expanded_mask
return inverted_mask.masked_fill(inverted_mask.bool(), torch.finfo(dtype).min) # torch.finfo(dtype).min -1e10
def get_slopes(num_heads, device):
closest_power_of_2 = 2 ** math.floor(math.log2(num_heads))
base = torch.tensor(
2 ** (-(2 ** -(math.log2(closest_power_of_2) - 3))), device=device, dtype=torch.float32
)
powers = torch.arange(1, 1 + closest_power_of_2, device=device, dtype=torch.int32)
slopes = torch.pow(base, powers)
if closest_power_of_2 != num_heads:
extra_base = torch.tensor(
2 ** (-(2 ** -(math.log2(2 * closest_power_of_2) - 3))), device=device, dtype=torch.float32
)
num_remaining_heads = min(closest_power_of_2, num_heads - closest_power_of_2)
extra_powers = torch.arange(1, 1 + 2 * num_remaining_heads, 2, device=device, dtype=torch.int32)
slopes = torch.cat([slopes, torch.pow(extra_base, extra_powers)], dim=0)
return slopes
def build_alibi_tensor_decoder(attention_mask: torch.Tensor, num_heads: int, dtype: torch.dtype) -> torch.Tensor:
"""
Coped from BLOOM implementation of huggingface.
Link to paper: https://arxiv.org/abs/2108.12409 Alibi tensor is not causal as the original paper mentions, it
relies on a translation invariance of softmax for quick implementation: with l being a tensor, and a fixed value
`softmax(l+a) = softmax(l)`. Based on
https://github.com/ofirpress/attention_with_linear_biases/blob/a35aaca144e0eb6b789dfcb46784c4b8e31b7983/fairseq/models/transformer.py#L742
Args:
Returns tensor shaped (batch_size * num_heads, 1, max_seq_len)
attention_mask (`torch.Tensor`):
Token-wise attention mask, this should be of shape (batch_size, max_seq_len).
num_heads (`int`, *required*):
number of heads
dtype (`torch.dtype`, *optional*, default=`torch.float32`):
dtype of the output tensor
"""
batch_size, seq_length = attention_mask.shape
slopes = get_slopes(num_heads, attention_mask.device)
# Note: alibi will added to the attention bias that will be applied to the query, key product of attention
# => therefore alibi will have to be of shape (batch_size, num_heads, query_length, key_length)
# => here we set (batch_size=1, num_heads=num_heads, query_length=1, key_length=max_length)
# => the query_length dimension will then be broadcasted correctly
# This is more or less identical to T5's relative position bias:
# https://github.com/huggingface/transformers/blob/f681437203baa7671de3174b0fa583c349d9d5e1/src/transformers/models/t5/modeling_t5.py#L527
arange_tensor = ((attention_mask.cumsum(dim=-1) - 1) * attention_mask)[:, None, :] ## The future tokens beyond padding are wiped out.
alibi = slopes[..., None] * arange_tensor
return alibi.reshape(batch_size * num_heads, 1, seq_length).to(dtype)
def fill_with_neg_inf(t):
"""FP16-compatible function that fills a tensor with -inf.""" ## Taken from fairseq
return t.float().fill_(float("-inf")).type_as(t)
def build_alibi_tensor_encoder(attention_mask: torch.Tensor, num_heads: int, dtype: torch.dtype, asymmetric: bool = False) -> torch.Tensor:
"""
Partly taken from huggingface.
Link to paper: https://arxiv.org/abs/2108.12409 Alibi tensor is not causal as the original paper mentions, it
relies on a translation invariance of softmax for quick implementation: with l being a tensor, and a fixed value
`softmax(l+a) = softmax(l)`. Based on
https://github.com/ofirpress/attention_with_linear_biases/blob/a35aaca144e0eb6b789dfcb46784c4b8e31b7983/fairseq/models/transformer.py#L742
Args:
Returns tensor shaped (batch_size * num_heads, 1, max_seq_len)
attention_mask (`torch.Tensor`):
Token-wise attention mask, this should be of shape (batch_size, max_seq_len).
num_heads (`int`, *required*):
number of heads
dtype (`torch.dtype`, *optional*, default=`torch.float32`):
dtype of the output tensor
asymmetric (`bool`, *optional*, default=True)
To decide between symmetric and asymmetric alibi tensor for encoder
"""
batch_size, seq_length = attention_mask.shape
# Note: alibi will added to the attention bias that will be applied to the query, key product of attention
# => therefore alibi will have to be of shape (batch_size, num_heads, query_length, key_length)
# => here we set (batch_size=1, num_heads=num_heads, query_length=1, key_length=max_length)
# => the query_length dimension will then be broadcasted correctly
# This is more or less identical to T5's relative position bias:
# https://github.com/huggingface/transformers/blob/f681437203baa7671de3174b0fa583c349d9d5e1/src/transformers/models/t5/modeling_t5.py#L527
# if asymmetric:
# future_mask_right = torch.triu(fill_with_neg_inf(torch.zeros([seq_length, seq_length])), 1).unsqueeze(0).repeat(num_heads//2, 1, 1)
# future_mask_left = torch.tril(fill_with_neg_inf(torch.zeros([seq_length, seq_length])), -1).unsqueeze(0).repeat(num_heads//2, 1, 1)
# nonsym_mask = torch.cat((future_mask_right, future_mask_left), dim = 0).unsqueeze(0).cuda()
# self.slopes = get_slopes(num_heads//2).cuda()*-1
# context_position = torch.arange(seq_length)[:, None].cuda()
# memory_position = torch.arange(seq_length)[None, :].cuda()
# relative_position = memory_position - context_position
# relative_position = torch.abs(relative_position).unsqueeze(0).expand(attn_heads//2, -1,-1)
# self.alibi = self.slopes.unsqueeze(1).unsqueeze(1) * relative_position
# self.alibi = self.alibi.view(1, attn_heads//2, seq_length, seq_length)
# self.alibi = self.alibi.repeat(1, 2, 1, 1).cuda()
# else:
if asymmetric: ## Not implemented yet.
pass
else:
slopes = get_slopes(num_heads, attention_mask.device)
context_position = torch.arange(seq_length)[:, None]
memory_position = torch.arange(seq_length)[None, :]
relative_position = (memory_position - context_position).to(slopes.device)
relative_position = torch.abs(relative_position).unsqueeze(0).expand(num_heads, -1,-1)
slopes = slopes * (-1)
alibi = slopes.unsqueeze(1).unsqueeze(1) * relative_position
alibi = alibi.view(1, num_heads, seq_length, seq_length).to(dtype)
alibi = alibi.expand(batch_size, -1, -1, -1) # This gives [batch size, num_heads, seq_len, seq_len].
attention_mask = attention_mask.unsqueeze(1).unsqueeze(1) ## This gives [batch size, 1, 1, seq_len]. Essentially we now use this to mask out the undesirable values corresponding to padding to the right of every batch.
alibi = alibi * attention_mask ## This ensures that we have symmetric alibi encodings along with the padding positions being zero so that no value is added. We dont want anything to over or underflow when doing attention masking. This is critical because we add masking biases, rather than mask_fill and this could lead to overflows.
return alibi.reshape(batch_size * num_heads, seq_length, seq_length).to(dtype)
## Modified RoPE implementation of lucidrains. Start.
# helper functions
def exists(val):
return val is not None
def broadcat(tensors, dim = -1):
num_tensors = len(tensors)
shape_lens = set(list(map(lambda t: len(t.shape), tensors)))
assert len(shape_lens) == 1, 'tensors must all have the same number of dimensions'
shape_len = list(shape_lens)[0]
dim = (dim + shape_len) if dim < 0 else dim
dims = list(zip(*map(lambda t: list(t.shape), tensors)))
expandable_dims = [(i, val) for i, val in enumerate(dims) if i != dim]
assert all([*map(lambda t: len(set(t[1])) <= 2, expandable_dims)]), 'invalid dimensions for broadcastable concatentation'
max_dims = list(map(lambda t: (t[0], max(t[1])), expandable_dims))
expanded_dims = list(map(lambda t: (t[0], (t[1],) * num_tensors), max_dims))
expanded_dims.insert(dim, (dim, dims[dim]))
expandable_shapes = list(zip(*map(lambda t: t[1], expanded_dims)))
tensors = list(map(lambda t: t[0].expand(*t[1]), zip(tensors, expandable_shapes)))
return torch.cat(tensors, dim = dim)
# rotary embedding helper functions
def rotate_half(x):
x = rearrange(x, '... (d r) -> ... d r', r = 2)
x1, x2 = x.unbind(dim = -1)
x = torch.stack((-x2, x1), dim = -1)
return rearrange(x, '... d r -> ... (d r)')
def apply_rotary_emb(freqs, t, start_index = 0, scale = 1.):
freqs = freqs.to(t)
rot_dim = freqs.shape[-1]
end_index = start_index + rot_dim
assert rot_dim <= t.shape[-1], f'feature dimension {t.shape[-1]} is not of sufficient size to rotate in all the positions {rot_dim}'
t_left, t, t_right = t[..., :start_index], t[..., start_index:end_index], t[..., end_index:]
t = (t * freqs.cos() * scale) + (rotate_half(t) * freqs.sin() * scale)
return torch.cat((t_left, t, t_right), dim = -1)
# learned rotation helpers
def apply_learned_rotations(rotations, t, start_index = 0, freq_ranges = None):
if exists(freq_ranges):
rotations = einsum('..., f -> ... f', rotations, freq_ranges)
rotations = rearrange(rotations, '... r f -> ... (r f)')
rotations = repeat(rotations, '... n -> ... (n r)', r = 2)
return apply_rotary_emb(rotations, t, start_index = start_index)
# classes
class RotaryEmbedding(nn.Module):
def __init__(
self,
dim,
custom_freqs = None,
freqs_for = 'lang',
theta = 10000,
max_freq = 10,
num_freqs = 1,
learned_freq = False,
use_xpos = False,
xpos_scale_base = 512,
):
super().__init__()
if exists(custom_freqs):
freqs = custom_freqs
elif freqs_for == 'lang':
freqs = 1. / (theta ** (torch.arange(0, dim, 2)[:(dim // 2)].float() / dim))
elif freqs_for == 'pixel':
freqs = torch.linspace(1., max_freq / 2, dim // 2) * pi
elif freqs_for == 'constant':
freqs = torch.ones(num_freqs).float()
else:
raise ValueError(f'unknown modality {freqs_for}')
self.cache = dict()
self.cache_scale = dict()
self.freqs = nn.Parameter(freqs, requires_grad = learned_freq)
self.use_xpos = use_xpos
if not use_xpos:
self.register_buffer('scale', None)
return
scale = (torch.arange(0, dim, 2) + 0.4 * dim) / (1.4 * dim)
self.scale_base = xpos_scale_base
self.register_buffer('scale', scale)
def rotate_queries_or_keys(self, t, past_key_values_length=0, seq_dim = -2):
assert not self.use_xpos, 'you must use `.rotate_queries_and_keys` method instead and pass in both queries and keys, for length extrapolatable rotary embeddings'
device, seq_len = t.device, t.shape[seq_dim]
freqs = self.forward(lambda: torch.arange(past_key_values_length+seq_len, device = device), cache_key = past_key_values_length+seq_len)
return apply_rotary_emb(freqs[-seq_len:,:], t)
def rotate_queries_and_keys(self, q, k, past_key_values_length=0, seq_dim = -2):
assert self.use_xpos
device, seq_len = q.device, q.shape[seq_dim]
seq = torch.arange(past_key_values_length+seq_len, device = device)
freqs = self.forward(lambda: seq, cache_key = f'freqs:{past_key_values_length+seq_len}')
scale = self.get_scale(lambda: seq, cache_key = f'scale:{past_key_values_length+seq_len}')
rotated_q = apply_rotary_emb(freqs[-seq_len:,:], q, scale = scale[-seq_len:,:])
rotated_k = apply_rotary_emb(freqs[-seq_len:,:], k, scale = scale[-seq_len:,:] ** -1)
return rotated_q, rotated_k
def get_scale(self, t, cache_key = None):
assert self.use_xpos
if exists(cache_key) and cache_key in self.cache:
return self.cache[cache_key]
if callable(t):
t = t()
scale = 1.
if self.use_xpos:
power = (t - len(t) // 2) / self.scale_base
scale = self.scale ** rearrange(power, 'n -> n 1')
scale = torch.cat((scale, scale), dim = -1)
if exists(cache_key):
self.cache[cache_key] = scale
return scale
def forward(self, t, cache_key = None):
if exists(cache_key) and cache_key in self.cache:
return self.cache[cache_key]
if callable(t):
t = t()
freqs = self.freqs
freqs = torch.einsum('..., f -> ... f', t.type(freqs.dtype), freqs)
freqs = repeat(freqs, '... n -> ... (n r)', r = 2)
if exists(cache_key):
self.cache[cache_key] = freqs
return freqs
## End of modified RoPE implementation of lucidrains.
def cast_tuple(el):
return el if isinstance(el, tuple) else (el,)
class GELU_(nn.Module):
def forward(self, x):
return 0.5 * x * (1 + torch.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 * torch.pow(x, 3))))
class Experts(nn.Module):
def __init__(self,
dim,
num_experts = 8,
hidden_dim = 128,
activation = "gelu",
activation_dropout = 0.0,
std = 0.2,
initialization_strategy = 'static',
depth = 1,
ia3_adaptors = False,):
super().__init__()
num_experts = cast_tuple(num_experts)
w1 = torch.zeros(*num_experts, dim, hidden_dim)
w2 = torch.zeros(*num_experts, hidden_dim, dim)
activation_string = activation
activation = ACT2FN[activation]
if ia3_adaptors:
initialization_strategy = 'static'
if initialization_strategy == 'static':
w1.normal_(mean=0.0, std=std)
w2.normal_(mean=0.0, std=std)
elif initialization_strategy == 'xavier':
a = math.sqrt(6.0 / (dim + hidden_dim))
gain = 1.0 #nn.init.calculate_gain(activation_string if activation_string != "gelu" else "relu")
w1.uniform_(-a*gain, a*gain)
w2.uniform_(-a*gain, a*gain)
elif initialization_strategy == 'kaiming':
gain = 1.0 # nn.init.calculate_gain(activation_string if activation_string != "gelu" else "relu")
a = 1 / math.sqrt(dim)
w1.normal_(mean=0.0, std=a*gain)
a = 1 / math.sqrt(hidden_dim)
w2.normal_(mean=0.0, std=a*gain)
elif initialization_strategy == 'depth_scaled_xavier':
a = math.sqrt(6.0 / (dim + hidden_dim))
gain = 1.0 * (1/math.sqrt(depth)) # nn.init.calculate_gain(activation_string if activation_string != "gelu" else "relu")
w1.uniform_(-a*gain, a*gain)
w2.uniform_(-a*gain, a*gain)
self.w1 = nn.Parameter(w1)
self.w2 = nn.Parameter(w2)
self.act = activation
self.act_drop = activation_dropout
if ia3_adaptors:
self.ia3_adaptors = True
ia3_ones = torch.ones(*num_experts, 1, 1, hidden_dim, dtype=torch.float32)
self.ia3_adaptor_linear = nn.Parameter(ia3_ones)
self.ia3_adaptors = ia3_adaptors
def forward(self, x):
hidden = torch.einsum('...nd,...dh->...nh', x, self.w1)
hidden = F.dropout(self.act(hidden), p=self.act_drop, training=self.training)
hidden = hidden * self.ia3_adaptor_linear if self.ia3_adaptors else hidden
out = torch.einsum('...nh,...hd->...nd', hidden, self.w2)
return out
class HardConcreteGate(nn.Module):
def __init__(self,
chunks=1,
stretch_limits=(-0.1, 1.1),
init_std=0.01,
temperature=3.0,
eps=1e-6):
super().__init__()
self.stretch_limits, self.chunks, self.temperature, self.eps = stretch_limits, chunks, 1/temperature, eps
self.loc = nn.Parameter(torch.zeros((1, chunks)).normal_(0, init_std))
def forward(self, values, dim=None):
gates = self.get_gates(reps=values.size()[-1]//self.chunks, dim=-1)
l0_reg = self.get_penalty(values=values, dim=dim) if self.training else 0
return (values*gates, l0_reg)
def get_gates(self, reps=None, dim=None):
""" samples gate activations in [0, 1] interval """
low, high = self.stretch_limits
if self.training:
noise = torch.rand(self.loc.size(), device="cuda")
concrete = torch.sigmoid((torch.log(noise) - torch.log(1 - noise) + self.loc) / self.temperature)
else:
concrete = torch.sigmoid(self.loc)
stretched_concrete = (concrete * (high - low)) + low
clipped_concrete = torch.clamp(stretched_concrete, 0, 1)
hard_concrete = torch.gt(clipped_concrete, 0.5).float()
clipped_concrete += nn.Parameter((hard_concrete - clipped_concrete), requires_grad=False)
return clipped_concrete if reps is None else torch.repeat_interleave(clipped_concrete, repeats=reps, dim=dim)
def get_penalty(self, values=None, dim=None):
low, high = self.stretch_limits
assert low < 0.0, "p_gate_closed can be computed only if lower stretch limit is negative"
p_open = torch.sigmoid(self.loc - self.temperature * log(-low/high))
p_open = torch.clamp(p_open, self.eps, 1.0-self.eps)
l0_reg = torch.mean(torch.sum(p_open, dim=dim))
return l0_reg
def get_sparsity_rate(self):
""" Computes the fraction of gates which are now zero """
return torch.mean(torch.eq(self.get_gates(dim=-1), 0.0).float())
class MBartSinusoidalPositionalEmbedding(nn.Embedding):
"""This module produces sinusoidal positional embeddings of any length."""
def __init__(self, num_positions: int, embedding_dim: int, padding_idx: Optional[int] = None):
super().__init__(num_positions, embedding_dim)
self.weight = self._init_weight(self.weight)
@staticmethod
def _init_weight(out: nn.Parameter):
"""
Identical to the XLM create_sinusoidal_embeddings except features are not interleaved. The cos features are in
the 2nd half of the vector. [dim // 2:]
"""
n_pos, dim = out.shape
position_enc = np.array(
[[pos / np.power(10000, 2 * (j // 2) / dim) for j in range(dim)] for pos in range(n_pos)]
)
out.requires_grad = False # set early to avoid an error in pytorch-1.8+
sentinel = dim // 2 if dim % 2 == 0 else (dim // 2) + 1
out[:, 0:sentinel] = torch.FloatTensor(np.sin(position_enc[:, 0::2]))
out[:, sentinel:] = torch.FloatTensor(np.cos(position_enc[:, 1::2]))
out.detach_()
return out
@torch.no_grad()
def forward(self, input_ids_shape: torch.Size, past_key_values_length: int = 0):
"""`input_ids_shape` is expected to be [bsz x seqlen]."""
bsz, seq_len = input_ids_shape[:2]
positions = torch.arange(
past_key_values_length, past_key_values_length + seq_len, dtype=torch.long, device=self.weight.device
)
return super().forward(positions)
## Modified by Raj Dabre. End.
# Copied from transformers.models.bart.modeling_bart.BartLearnedPositionalEmbedding with Bart->MBart
class MBartLearnedPositionalEmbedding(nn.Embedding):
"""
This module learns positional embeddings up to a fixed maximum size.
"""
def __init__(self, num_embeddings: int, embedding_dim: int, padding_idx: int):
assert padding_idx is not None, "`padding_idx` should not be None, but of type int"
# MBart is set up so that if padding_idx is specified then offset the embedding ids by 2
# and adjust num_embeddings appropriately. Other models dont have this hack
self.offset = 2
super().__init__(num_embeddings + self.offset, embedding_dim, padding_idx=padding_idx)
def forward(self, input_ids_shape: torch.Size, past_key_values_length: int = 0):
"""`input_ids_shape` is expected to be [bsz x seqlen]."""
bsz, seq_len = input_ids_shape[:2]
positions = torch.arange(
past_key_values_length, past_key_values_length + seq_len, dtype=torch.long, device=self.weight.device
)
return super().forward(positions + self.offset)
def get_lora_matrices(embed_dim, lora_dim, std):
w1 = torch.zeros(embed_dim, lora_dim)
w1.normal_(mean=0.0, std=std)
w2 = torch.zeros(lora_dim, embed_dim)
return w1, w2
# Copied from transformers.models.bart.modeling_bart.BartAttention with Bart->MBart
class MBartAttention(nn.Module):
"""Multi-headed attention from 'Attention Is All You Need' paper"""
def __init__(
self,
embed_dim: int,
num_heads: int,
dropout: float = 0.0,
is_decoder: bool = False,
bias: bool = True,
multi_source_method = None,
no_scale_attention_embedding = False,
ia3_adaptors = False,
lora_adaptors = False,
lora_adaptor_rank = 2,
init_std = 0.02,
sparsify_attention = False,
sparsification_temperature = 3.0,
):
super().__init__()
self.embed_dim = embed_dim
self.num_heads = num_heads
self.dropout = dropout
self.head_dim = embed_dim // num_heads
assert (
self.head_dim * num_heads == self.embed_dim
), f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`: {num_heads})."
self.scaling = self.head_dim ** -0.5 if not no_scale_attention_embedding else 1.0
self.is_decoder = is_decoder
self.k_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
self.v_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
if sparsify_attention:
self.sparsification_gate = HardConcreteGate(chunks=num_heads, temperature=sparsification_temperature)
self.sparsify_attention = True
else:
self.sparsify_attention = False
## Modified by Raj Dabre. Start.
if multi_source_method == "merge_after_attention" or multi_source_method == "self_relevance_and_merge_after_attention" or multi_source_method == "self_relevance_and_merge_after_attention_with_context_relevance_only" or multi_source_method == "merge_after_attention_with_context_relevance_only" or multi_source_method == "mid_fusion_merge_after_attention" or multi_source_method == "bottleneck_mid_fusion_merge_after_attention": ## We pass the attentions through a gating method. X and Y are combined as w*x+(1-w)*Y where w=sigmoid(W[X:Y]) where [X:Y] is the concatenation of X and Y along hidden axis.
if multi_source_method == "merge_after_attention" or multi_source_method == "self_relevance_and_merge_after_attention" or multi_source_method == "mid_fusion_merge_after_attention" or multi_source_method == "bottleneck_mid_fusion_merge_after_attention":
self.gating_layer = nn.Linear(2*self.head_dim, self.head_dim, bias=False)
else:
self.gating_layer = nn.Linear(self.head_dim, self.head_dim, bias=False)
self.multi_source = True
self.multi_source_method = multi_source_method
else:
self.multi_source = False
self.multi_source_method = ""
if ia3_adaptors:
ia3_ones = torch.ones(embed_dim, dtype=torch.float32)
self.ia3_adaptor_key = nn.Parameter(ia3_ones)
ia3_ones = torch.ones(embed_dim, dtype=torch.float32)
self.ia3_adaptor_value = nn.Parameter(ia3_ones)
self.ia3_adaptors = ia3_adaptors
if lora_adaptors:
w1, w2 = get_lora_matrices(self.embed_dim, lora_adaptor_rank, init_std)
self.lora_adapter_down_q_proj = nn.Parameter(w1)
self.lora_adapter_up_q_proj = nn.Parameter(w2)
w1, w2 = get_lora_matrices(self.embed_dim, lora_adaptor_rank, init_std)
self.lora_adapter_down_k_proj = nn.Parameter(w1)
self.lora_adapter_up_k_proj = nn.Parameter(w2)
w1, w2 = get_lora_matrices(self.embed_dim, lora_adaptor_rank, init_std)
self.lora_adapter_down_v_proj = nn.Parameter(w1)
self.lora_adapter_up_v_proj = nn.Parameter(w2)
w1, w2 = get_lora_matrices(self.embed_dim, lora_adaptor_rank, init_std)
self.lora_adapter_down_out_proj = nn.Parameter(w1)
self.lora_adapter_up_out_proj = nn.Parameter(w2)
self.lora_adaptors = lora_adaptors
## Modified by Raj Dabre. End.
def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
def forward(
self,
hidden_states: torch.Tensor,
key_value_states: Optional[torch.Tensor] = None,
additional_key_value_states: Optional[torch.Tensor] = None,
past_key_value: Optional[Tuple[torch.Tensor]] = None,
additional_past_key_value: Optional[Tuple[torch.Tensor]] = None,
attention_mask: Optional[torch.Tensor] = None,
additional_attention_mask: Optional[torch.Tensor] = None,
layer_head_mask: Optional[torch.Tensor] = None,
output_attentions: bool = False,
prompt_params = None,
adaptor_or_prompt_layer_idx = 0,
alibi_bias = None,
rope_encoder=None,
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
"""Input shape: Batch x Time x Channel"""
# if key_value_states are provided this layer is used as a cross-attention layer
# for the decoder
is_cross_attention = key_value_states is not None
bsz, tgt_len, embed_dim = hidden_states.size()
# get query proj
query_states = self.q_proj(hidden_states) * self.scaling
if self.lora_adaptors:
query_states += torch.matmul(torch.matmul(hidden_states, self.lora_adapter_down_q_proj), self.lora_adapter_up_q_proj) * self.scaling
query_states = self._shape(query_states, tgt_len, bsz)
if past_key_value is not None:
past_key_values_length = past_key_value[0].shape[2]
else:
past_key_values_length = 0
# get key, value proj
## Modified by Raj Dabre. Start.
if is_cross_attention and past_key_value is not None:
# reuse k,v, cross_attentions
key_states = past_key_value[0]
value_states = past_key_value[1]
if self.multi_source: # additional_past_key_value is not None
additional_key_states = additional_past_key_value[0]
additional_value_states = additional_past_key_value[1]
## Modified by Raj Dabre. End.
elif is_cross_attention:
# cross_attentions
key_states = self.k_proj(key_value_states)
if self.lora_adaptors:
key_states += torch.matmul(torch.matmul(key_value_states, self.lora_adapter_down_k_proj), self.lora_adapter_up_k_proj)
key_states = key_states * self.ia3_adaptor_key if self.ia3_adaptors else key_states
key_states = self._shape(key_states, -1, bsz)
if prompt_params is not None:
prompt_params_expanded = self._shape(prompt_params[0][adaptor_or_prompt_layer_idx], -1, bsz)
key_states = torch.cat([prompt_params_expanded, key_states], dim=2)
value_states = self.v_proj(key_value_states)
if self.lora_adaptors:
value_states += torch.matmul(torch.matmul(key_value_states, self.lora_adapter_down_v_proj), self.lora_adapter_up_v_proj)
value_states = value_states * self.ia3_adaptor_value if self.ia3_adaptors else value_states
value_states = self._shape(value_states, -1, bsz)
if prompt_params is not None:
prompt_params_expanded = self._shape(prompt_params[1][adaptor_or_prompt_layer_idx], -1, bsz)
value_states = torch.cat([prompt_params_expanded, value_states], dim=2)
## Modified by Raj Dabre. Start.
if self.multi_source: # additional_past_key_value is not None
additional_key_states = self.k_proj(additional_key_value_states)
if self.lora_adaptors:
additional_key_states += torch.matmul(torch.matmul(additional_key_value_states, self.lora_adapter_down_k_proj), self.lora_adapter_up_k_proj)
additional_key_states = additional_key_states * self.ia3_adaptor_key if self.ia3_adaptors else additional_key_states
additional_key_states = self._shape(additional_key_states, -1, bsz)
if prompt_params is not None:
prompt_params_expanded = self._shape(prompt_params[0][adaptor_or_prompt_layer_idx], -1, bsz)
additional_key_states = torch.cat([prompt_params_expanded, additional_key_states], dim=2)
additional_value_states = self.v_proj(additional_key_value_states)
if self.lora_adaptors:
additional_value_states += torch.matmul(torch.matmul(additional_key_value_states, self.lora_adapter_down_v_proj), self.lora_adapter_up_v_proj)
additional_value_states = additional_value_states * self.ia3_adaptor_value if self.ia3_adaptors else additional_value_states
additional_value_states = self._shape(additional_value_states, -1, bsz)
if prompt_params is not None:
prompt_params_expanded = self._shape(prompt_params[1][adaptor_or_prompt_layer_idx], -1, bsz)
additional_value_states = torch.cat([prompt_params_expanded, additional_value_states], dim=2)
## Modified by Raj Dabre. End.
elif past_key_value is not None:
# reuse k, v, self_attention
key_states = self.k_proj(hidden_states)
if self.lora_adaptors:
key_states += torch.matmul(torch.matmul(hidden_states, self.lora_adapter_down_k_proj), self.lora_adapter_up_k_proj)
key_states = key_states * self.ia3_adaptor_key if self.ia3_adaptors else key_states
key_states = self._shape(key_states, -1, bsz)
if rope_encoder is not None: ## In case of decoding self attention, both query and key will be sequence length 1. In this case we need to provide the past key value length to the rope encoder which will select the appropriate frequency and scale components.
query_states, key_states = rope_encoder.rotate_queries_and_keys(query_states, key_states, past_key_values_length=past_key_values_length)
value_states = self.v_proj(hidden_states)
if self.lora_adaptors:
value_states += torch.matmul(torch.matmul(hidden_states, self.lora_adapter_down_v_proj), self.lora_adapter_up_v_proj)
value_states = value_states * self.ia3_adaptor_value if self.ia3_adaptors else value_states
value_states = self._shape(value_states, -1, bsz)
key_states = torch.cat([past_key_value[0], key_states], dim=2)
value_states = torch.cat([past_key_value[1], value_states], dim=2)
else:
# self_attention
key_states = self.k_proj(hidden_states)
if self.lora_adaptors:
key_states += torch.matmul(torch.matmul(hidden_states, self.lora_adapter_down_k_proj), self.lora_adapter_up_k_proj)
key_states = key_states * self.ia3_adaptor_key if self.ia3_adaptors else key_states
key_states = self._shape(key_states, -1, bsz)
if rope_encoder is not None: ## In case of decoding self attention, both query and key will be sequence length 1. In this case we need to provide the past key value length to the rope encoder which will select the appropriate frequency and scale components.
query_states, key_states = rope_encoder.rotate_queries_and_keys(query_states, key_states, past_key_values_length=past_key_values_length)
if prompt_params is not None:
prompt_params_expanded = self._shape(prompt_params[0][adaptor_or_prompt_layer_idx], -1, bsz)
key_states = torch.cat([prompt_params_expanded, key_states], dim=2)
value_states = self.v_proj(hidden_states)
if self.lora_adaptors:
value_states += torch.matmul(torch.matmul(hidden_states, self.lora_adapter_down_v_proj), self.lora_adapter_up_v_proj)
value_states = value_states * self.ia3_adaptor_value if self.ia3_adaptors else value_states
value_states = self._shape(value_states, -1, bsz)
if prompt_params is not None:
prompt_params_expanded = self._shape(prompt_params[1][adaptor_or_prompt_layer_idx], -1, bsz)
value_states = torch.cat([prompt_params_expanded, value_states], dim=2)
if self.is_decoder:
# if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states.
# Further calls to cross_attention layer can then reuse all cross-attention
# key/value_states (first "if" case)
# if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of
# all previous decoder key/value_states. Further calls to uni-directional self-attention
# can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
# if encoder bi-directional self-attention `past_key_value` is always `None`
past_key_value = (key_states, value_states)
## Modified by Raj Dabre. Start.
if self.multi_source and is_cross_attention: ## Both conditions are not needed as one multi-source logic can only run when there is cross attention. multi_source is sufficient but keeping this condition for checking.
additional_past_key_value = (additional_key_states, additional_value_states)
## Modified by Raj Dabre. End.
proj_shape = (bsz * self.num_heads, -1, self.head_dim)
query_states = query_states.view(*proj_shape)
key_states = key_states.view(*proj_shape)
value_states = value_states.view(*proj_shape)
src_len = key_states.size(1)
attn_weights = torch.bmm(query_states, key_states.transpose(1, 2))
assert attn_weights.size() == (
bsz * self.num_heads,
tgt_len,
src_len,
), f"Attention weights should be of size {(bsz * self.num_heads, tgt_len, src_len)}, but is {attn_weights.size()}"
if attention_mask is not None:
assert attention_mask.size() == (
bsz,
1,
tgt_len,
src_len,
), f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is {attention_mask.size()}"
# print("Attn weights device: ", attn_weights.device)
# print("Attn mask device: ", attention_mask.device)
attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + attention_mask
attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
if alibi_bias is not None:
assert ((alibi_bias.size() == (bsz*self.num_heads, tgt_len, src_len)) or (alibi_bias.size() == (bsz*self.num_heads, 1, src_len))), f"Attention mask should be of size {(bsz*self.num_heads, tgt_len, src_len)} or {(bsz*self.num_heads, 1, src_len)}, but is {alibi_bias.size()}"
attn_weights += alibi_bias
attn_weights = F.softmax(attn_weights, dim=-1)
## Modified by Raj Dabre. Start.
if self.multi_source:
additional_key_states = additional_key_states.view(*proj_shape)
additional_value_states = additional_value_states.view(*proj_shape)
additional_src_len = additional_key_states.size(1)
additional_attn_weights = torch.bmm(query_states, additional_key_states.transpose(1, 2))
assert additional_attn_weights.size() == (
bsz * self.num_heads,
tgt_len,
additional_src_len,
), f"Additional attention weights should be of size {(bsz * self.num_heads, tgt_len, additional_src_len)}, but is {additional_attn_weights.size()}"
if additional_attention_mask is not None:
assert additional_attention_mask.size() == (
bsz,
1,
tgt_len,
additional_src_len,
), f"Attention mask should be of size {(bsz, 1, tgt_len, additional_src_len)}, but is {additional_attention_mask.size()}"
additional_attn_weights = additional_attn_weights.view(bsz, self.num_heads, tgt_len, additional_src_len) + additional_attention_mask
additional_attn_weights = additional_attn_weights.view(bsz * self.num_heads, tgt_len, additional_src_len)
additional_attn_weights = F.softmax(additional_attn_weights, dim=-1)
## Modified by Raj Dabre. End.
if layer_head_mask is not None:
assert layer_head_mask.size() == (
self.num_heads,
), f"Head mask for a single layer should be of size {(self.num_heads,)}, but is {layer_head_mask.size()}"
attn_weights = layer_head_mask.view(1, -1, 1, 1) * attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
## Modified by Raj Dabre. Start.
if self.multi_source:
additional_attn_weights = layer_head_mask.view(1, -1, 1, 1) * additional_attn_weights.view(bsz, self.num_heads, tgt_len, additional_src_len)
additional_attn_weights = additional_attn_weights.view(bsz * self.num_heads, tgt_len, additional_src_len)
## Modified by Raj Dabre. End.
if output_attentions:
# this operation is a bit akward, but it's required to
# make sure that attn_weights keeps its gradient.
# In order to do so, attn_weights have to reshaped
# twice and have to be reused in the following
attn_weights_reshaped = attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
attn_weights = attn_weights_reshaped.view(bsz * self.num_heads, tgt_len, src_len)
## Modified by Raj Dabre. Start.
if self.multi_source:
additional_attn_weights_reshaped = additional_attn_weights.view(bsz, self.num_heads, tgt_len, additional_src_len)
additional_attn_weights = additional_attn_weights_reshaped.view(bsz * self.num_heads, tgt_len, additional_src_len)
## Modified by Raj Dabre. End.
else:
attn_weights_reshaped = None
## Modified by Raj Dabre. Start.
if self.multi_source:
additional_attn_weights_reshaped = None
## Modified by Raj Dabre. End.
attn_probs = F.dropout(attn_weights, p=self.dropout, training=self.training)
attn_output = torch.bmm(attn_probs, value_states)
assert attn_output.size() == (
bsz * self.num_heads,
tgt_len,
self.head_dim,
), f"`attn_output` should be of size {(bsz, self.num_heads, tgt_len, self.head_dim)}, but is {attn_output.size()}"
## Modified by Raj Dabre. Start.
if self.multi_source:
additional_attn_probs = F.dropout(additional_attn_weights, p=self.dropout, training=self.training)
additional_attn_output = torch.bmm(additional_attn_probs, additional_value_states)
assert additional_attn_output.size() == (
bsz * self.num_heads,
tgt_len,
self.head_dim,
), f"`attn_output` should be of size {(bsz, self.num_heads, tgt_len, self.head_dim)}, but is {additional_attn_output.size()}"
if self.multi_source_method == "merge_after_attention" or self.multi_source_method == "self_relevance_and_merge_after_attention" or self.multi_source_method == "mid_fusion_merge_after_attention" or self.multi_source_method == "bottleneck_mid_fusion_merge_after_attention":
attentions_merged = torch.cat([attn_output, additional_attn_output], -1) ## Concatenate along hidden axis.
gating_weight = torch.sigmoid(self.gating_layer(attentions_merged)) ## Compute gating weight.
attn_output = gating_weight*attn_output + (1.0-gating_weight)*additional_attn_output ## Combine attentions.
else:
context_self_relevance_weight = torch.sigmoid(self.gating_layer(additional_attn_output)) ## Compute gating weight.
attn_output = attn_output + context_self_relevance_weight*additional_attn_output ## Combine attentions.
## Modified by Raj Dabre. End.
attn_output = (
attn_output.view(bsz, self.num_heads, tgt_len, self.head_dim)
.transpose(1, 2)
.reshape(bsz, tgt_len, embed_dim)
)
if self.sparsify_attention:
attn_output, sparsification_l0_loss = self.sparsification_gate(attn_output, dim=-1)
attn_input = attn_output
attn_output = self.out_proj(attn_input)
if self.lora_adaptors:
attn_output += torch.matmul(torch.matmul(attn_input, self.lora_adapter_down_out_proj), self.lora_adapter_up_out_proj)
## Modified by Raj Dabre. Start.
if self.sparsify_attention:
if self.multi_source:
return [attn_output, sparsification_l0_loss], attn_weights_reshaped, additional_attn_weights_reshaped, past_key_value, additional_past_key_value
else:
return [attn_output, sparsification_l0_loss], attn_weights_reshaped, past_key_value
else:
if self.multi_source:
return attn_output, attn_weights_reshaped, additional_attn_weights_reshaped, past_key_value, additional_past_key_value
else:
return attn_output, attn_weights_reshaped, past_key_value
## Modified by Raj Dabre. End.
class MBartEncoderLayer(nn.Module):
def __init__(self, config: MBartConfig, layer_id: int = 1):
super().__init__()
self.embed_dim = config.d_model
self.config = config
moe_loss = () if self.config.use_moe else None
self.self_attn = MBartAttention(
embed_dim=self.embed_dim,
num_heads=config.encoder_attention_heads,
dropout=config.attention_dropout,
no_scale_attention_embedding=config.no_scale_attention_embedding,
ia3_adaptors=config.ia3_adaptors,
lora_adaptors=config.lora_adaptors,
lora_adaptor_rank=config.lora_adaptor_rank,
init_std=config.init_std,
sparsify_attention=config.sparsify_attention,
sparsification_temperature=config.sparsification_temperature,
) ## An if else condition to either return the sann or a FFT. The FFT will be implemented via a method which pre-generates a bunch of matrices and returns a closure which uses the right matrix during runtime.
self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim)
self.dropout = config.dropout
self.activation_fn = ACT2FN[config.activation_function]
self.activation_dropout = config.activation_dropout
if config.use_moe:
print("Using Mixtures of Experts")
experts = Experts(dim = self.embed_dim,
num_experts = config.num_experts,
hidden_dim = config.expert_ffn_size,
activation = config.activation_function,
activation_dropout = self.activation_dropout,
std = config.init_std,
initialization_strategy=config.initialization_strategy,
depth = layer_id,
ia3_adaptors = config.ia3_adaptors,)
self.moe = MoE(
dim = self.embed_dim,
num_experts = config.num_experts,
hidden_dim = config.expert_ffn_size,
second_policy_train = 'random',
second_policy_eval = 'random',
second_threshold_train = 0.2,
second_threshold_eval = 0.2,
capacity_factor_train = 1.25,
capacity_factor_eval = 2.,
loss_coef = 1e-2,
experts = experts
)
else:
self.fc1 = nn.Linear(self.embed_dim, config.encoder_ffn_dim)
self.fc2 = nn.Linear(config.encoder_ffn_dim, self.embed_dim)
if config.ia3_adaptors:
ia3_ones = torch.ones(config.encoder_ffn_dim, dtype=torch.float32)
self.ia3_adaptor_linear = nn.Parameter(ia3_ones)
self.final_layer_norm = nn.LayerNorm(self.embed_dim)
if config.sparsify_ffn:
self.sparsification_gate = HardConcreteGate(chunks=config.num_sparsify_blocks, temperature=config.sparsification_temperature)
def forward(
self,
hidden_states: torch.Tensor,
attention_mask: torch.Tensor,
layer_head_mask: torch.Tensor,
output_attentions: bool = False,
prompt_params = None,
adaptor_layers = None,
deep_adaptor_tuning = False,
deep_adaptor_tuning_ffn_only = False,
parallel_adaptors=False,
moe_adaptors=False,
adaptor_or_prompt_layer_idx = 0,
alibi_bias=None,
rope_encoder=None,