-
Notifications
You must be signed in to change notification settings - Fork 2.6k
/
Copy pathtransformer.py
1795 lines (1635 loc) · 85.2 KB
/
transformer.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 (c) 2020, NVIDIA CORPORATION. All rights reserved.
#
# 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.
"""Transformer."""
from contextlib import nullcontext
from importlib.metadata import version
from typing import Any, Callable, Optional
import packaging
import torch
import torch.nn as nn
from einops import rearrange
from omegaconf.listconfig import ListConfig
from nemo.collections.common.parts.adapter_modules import LinearAdapterConfig
from nemo.collections.nlp.modules.common.megatron.adapters.parallel_adapters import (
AdapterName,
ParallelLinearAdapterConfig,
ParallelLinearAdapterWeightTyingConfig,
)
from nemo.collections.nlp.modules.common.megatron.attention import ParallelAttention, ParallelChunkedCrossAttention
from nemo.collections.nlp.modules.common.megatron.fused_bias_dropout_add import (
bias_dropout_add,
bias_dropout_add_fused_inference,
bias_dropout_add_fused_train,
dropout_add,
)
from nemo.collections.nlp.modules.common.megatron.fused_layer_norm import get_layer_norm
from nemo.collections.nlp.modules.common.megatron.layer_norm_1p import LayerNorm1P, LPLayerNorm
from nemo.collections.nlp.modules.common.megatron.layer_type import LayerType
from nemo.collections.nlp.modules.common.megatron.mlp import ParallelMLP, SwitchMLP
from nemo.collections.nlp.modules.common.megatron.module import MegatronModule
from nemo.collections.nlp.modules.common.megatron.utils import ApexGuardDefaults
from nemo.collections.nlp.parts import utils_funcs
from nemo.core import adapter_mixins
from nemo.utils import logging
from nemo.utils.import_utils import safe_import_from
try:
from apex.normalization import MixedFusedRMSNorm
from apex.transformer.enums import AttnMaskType, AttnType, ModelType
HAVE_APEX = True
except (ImportError, ModuleNotFoundError):
HAVE_APEX = False
# fake missing classes with None attributes
ModelType = AttnMaskType = AttnType = LayerType = ApexGuardDefaults()
try:
from megatron.core import ModelParallelConfig, parallel_state, tensor_parallel
HAVE_MEGATRON_CORE = True
except (ImportError, ModuleNotFoundError):
ModelParallelConfig = ApexGuardDefaults
HAVE_MEGATRON_CORE = False
recipe, HAVE_RECIPE = safe_import_from("transformer_engine.common", "recipe")
TransformerLayer, HAVE_LAYER = safe_import_from("transformer_engine.pytorch", "TransformerLayer")
fp8_autocast, HAVE_AUTOCAST = safe_import_from("transformer_engine.pytorch", "fp8_autocast")
te_checkpoint, HAVE_CKPT = safe_import_from("transformer_engine.pytorch.distributed", "checkpoint")
HAVE_TE = HAVE_RECIPE and HAVE_LAYER and HAVE_AUTOCAST and HAVE_CKPT
if not HAVE_TE:
# fake missing class
class TransformerLayer(ApexGuardDefaults):
def __init__(self):
super().__init__()
logging.warning(
"Transformer Engine was not found. transformer_engine.pytorch.transformer.TransformerLayer will not work. Please see the NeMo README for installation instructions: https://github.com/NVIDIA/NeMo#megatron-gpt."
)
""" We use the following notation throughout this file:
h: hidden size
n: number of attention heads
p: number of model parallel partitions
np: n/p
hp: h/p
hn: h/n
b: batch size
s: sequence length
l: number of layers
Transformer takes input of size [s, b, h] and returns a
tensor of the same size. We use the following arguments:
hyperparameters: transformer hyperparameters
"""
def get_bias_dropout_add(training):
def _bias_dropout_add(x, bias, residual, prob):
return bias_dropout_add(x, bias, residual, prob, training)
return _bias_dropout_add
def get_dropout_add(training):
def _dropout_add(x, bias, residual, prob):
assert bias is None
return dropout_add(x, bias, residual, prob, training)
return _dropout_add
def remove_bias_from_layernorm(layer):
for module in layer.modules():
if hasattr(module, 'bias') and isinstance(module.bias, nn.Parameter):
module.register_parameter('bias', None)
class ParallelTransformerLayer_(MegatronModule, adapter_mixins.AdapterModuleMixin):
"""A single transformer layer.
Transformer layer takes input with size [s, b, h] and returns an
output of the same size.
"""
def __init__(
self,
config: ModelParallelConfig,
init_method,
output_layer_init_method,
layer_number,
hidden_size,
ffn_hidden_size,
num_attention_heads,
layer_type=LayerType.encoder,
self_attn_mask_type=AttnMaskType.padding,
fp32_residual_connection=False,
precision=16,
apply_query_key_layer_scaling=False,
kv_channels=None,
layernorm_epsilon=1e-5,
hidden_dropout=0.1,
persist_layer_norm=False,
bias_activation_fusion=True,
bias_dropout_add_fusion=True,
masked_softmax_fusion=True,
openai_gelu=False,
onnx_safe=False,
attention_dropout=0.1,
ffn_dropout=0.0,
activation='gelu',
megatron_legacy=False,
bias=True,
chunk_size=64,
normalization='layernorm',
transformer_block_type='pre_ln',
position_embedding_type='learned_absolute',
multi_query_attention=False,
headscale=False,
activations_checkpoint_granularity=None,
normalize_attention_scores=True,
num_moe_experts=1,
moe_frequency=1,
moe_dropout=0.0,
use_flash_attention=False,
):
super(ParallelTransformerLayer_, self).__init__(config=config)
if kv_channels is None:
assert (
hidden_size % num_attention_heads == 0
), 'hidden_size must be divisible by num_attention_heads if kv_channels is None'
kv_channels = hidden_size // num_attention_heads
self.layer_number = layer_number
self.layer_type = layer_type
self.bias = bias
self.transformer_block_type = transformer_block_type
self.position_embedding_type = position_embedding_type
self.set_accepted_adapter_types(
[
LinearAdapterConfig._target_,
ParallelLinearAdapterConfig._target_,
ParallelLinearAdapterWeightTyingConfig._target_,
]
)
if not bias and bias_dropout_add_fusion:
raise ValueError(
'bias_dropout_add_fusion=True requires bias=True, found bias=False. Either set both to True or both to False.'
)
# the low_precision_layernorm does not require a bias term, whereas layernorm1p from apex
# does require a bias, so it cannot be used for bias-less low precision LN such as in MPT-7B
if normalization not in ['layernorm', 'layernorm1p', 'rmsnorm', 'low_precision_layernorm']:
raise ValueError(f'normalization must be "layernorm", "layernorm1p" or "rmsnorm", found {normalization}')
if transformer_block_type not in ['pre_ln', 'post_ln', 'normformer']:
raise ValueError(
f'transformer_block_type must be either "pre_ln" or "post_ln" or "normformer", found {transformer_block_type}'
)
self.fp32_residual_connection = fp32_residual_connection # if true move residual connections to fp32
self.hidden_dropout = hidden_dropout
self.attention_dropout = attention_dropout
self.bias_dropout_add_fusion = bias_dropout_add_fusion # if true, enable bias dropout fusion
# Self attention.
# retrieval_decoder_after_self_attn skips the self attention
if self.layer_type != LayerType.retrieval_decoder_after_self_attn:
# Layernorm on the input data.
if normalization == 'layernorm':
self.input_layernorm = get_layer_norm(
hidden_size, layernorm_epsilon, persist_layer_norm, config.sequence_parallel
)
elif normalization == 'layernorm1p':
self.input_layernorm = LayerNorm1P(
hidden_size, layernorm_epsilon, sequence_parallel_enabled=config.sequence_parallel
)
elif normalization == 'low_precision_layernorm':
self.input_layernorm = LPLayerNorm(hidden_size, layernorm_epsilon)
else:
self.input_layernorm = MixedFusedRMSNorm(hidden_size, layernorm_epsilon)
# for architectures such as MPT, there is no bias term even on the layernorms
# this code allows us to remove the bias terms from the layernorm module
# so that we can support MPT. However, certain apex-based LNs don't support
# removing bias, so we also have to check for that
if not bias and normalization not in ['layernorm', 'layernorm1p']:
remove_bias_from_layernorm(self.input_layernorm)
self.self_attention = ParallelAttention(
config=config,
init_method=init_method,
output_layer_init_method=output_layer_init_method,
layer_number=layer_number,
num_attention_heads=num_attention_heads,
hidden_size=hidden_size,
attention_type=AttnType.self_attn,
attn_mask_type=self_attn_mask_type,
precision=precision,
apply_query_key_layer_scaling=apply_query_key_layer_scaling,
kv_channels=kv_channels,
masked_softmax_fusion=masked_softmax_fusion,
attention_dropout=attention_dropout,
multi_query_attention=multi_query_attention,
layer_type=layer_type,
megatron_legacy=megatron_legacy,
bias=bias,
headscale=headscale,
position_embedding_type=position_embedding_type,
normalize_attention_scores=normalize_attention_scores,
use_flash_attention=use_flash_attention,
)
if transformer_block_type == 'normformer':
if normalization == 'layernorm':
self.post_attention_normformer_norm = get_layer_norm(
hidden_size, layernorm_epsilon, persist_layer_norm
)
else:
self.post_attention_normformer_norm = MixedFusedRMSNorm(hidden_size, layernorm_epsilon)
if self.layer_type != LayerType.decoder_pre_mlp or self.transformer_block_type != 'post_ln':
# the post_attention_layernorm is used for layermorm after mlp
# don't need it for decoder_pre_mlp and post_ln
if normalization == 'layernorm':
self.post_attention_layernorm = get_layer_norm(
hidden_size, layernorm_epsilon, persist_layer_norm, config.sequence_parallel
)
elif normalization == 'layernorm1p':
self.post_attention_layernorm = LayerNorm1P(
hidden_size, layernorm_epsilon, sequence_parallel_enabled=config.sequence_parallel
)
elif normalization == 'low_precision_layernorm':
self.post_attention_layernorm = LPLayerNorm(hidden_size, layernorm_epsilon)
else:
self.post_attention_layernorm = MixedFusedRMSNorm(hidden_size, layernorm_epsilon)
if not bias and normalization not in ['layernorm', 'layernorm1p']:
remove_bias_from_layernorm(self.post_attention_layernorm)
if self.layer_type == LayerType.decoder_pre_mlp:
# skip MLP and cross attention
return
# the post_attention_layernorm is used for layermorm after mlp
# need it for post_ln
if self.layer_type == LayerType.retrieval_decoder_after_self_attn and self.transformer_block_type == 'post_ln':
# Layernorm on the attention output
if normalization == 'layernorm':
self.post_attention_layernorm = get_layer_norm(
hidden_size, layernorm_epsilon, persist_layer_norm, config.sequence_parallel
)
elif normalization == 'layernorm1p':
self.post_attention_layernorm = LayerNorm1P(
hidden_size, layernorm_epsilon, sequence_parallel_enabled=config.sequence_parallel
)
elif normalization == 'low_precision_layernorm':
self.post_attention_layernorm = LPLayerNorm(hidden_size, layernorm_epsilon)
else:
self.post_attention_layernorm = MixedFusedRMSNorm(hidden_size, layernorm_epsilon)
if not bias and normalization not in ['layernorm', 'layernorm1p']:
remove_bias_from_layernorm(self.post_attention_layernorm)
if self.layer_type == LayerType.decoder or self.layer_type == LayerType.retrieval_encoder:
self.inter_attention = ParallelAttention(
config=config,
init_method=init_method,
output_layer_init_method=output_layer_init_method,
layer_number=layer_number,
num_attention_heads=num_attention_heads,
hidden_size=hidden_size,
attention_type=AttnType.cross_attn,
attn_mask_type=AttnMaskType.padding,
precision=precision,
apply_query_key_layer_scaling=apply_query_key_layer_scaling,
kv_channels=kv_channels,
multi_query_attention=multi_query_attention,
masked_softmax_fusion=masked_softmax_fusion,
attention_dropout=attention_dropout,
megatron_legacy=megatron_legacy,
bias=bias,
headscale=headscale,
normalize_attention_scores=normalize_attention_scores,
)
# Normformer normalization
if transformer_block_type == 'normformer':
if normalization == 'layernorm':
self.post_inter_attention_normformer_norm = get_layer_norm(
hidden_size, layernorm_epsilon, persist_layer_norm, config.sequence_parallel
)
elif normalization == 'layernorm1p':
self.post_inter_attention_normformer_norm = LayerNorm1P(
hidden_size, layernorm_epsilon, sequence_parallel_enabled=config.sequence_parallel
)
else:
self.post_inter_attention_normformer_norm = MixedFusedRMSNorm(hidden_size, layernorm_epsilon)
# Layernorm on the attention output.
if normalization == 'layernorm':
self.post_inter_attention_layernorm = get_layer_norm(
hidden_size, layernorm_epsilon, persist_layer_norm, config.sequence_parallel
)
elif normalization == 'layernorm1p':
self.post_inter_attention_layernorm = LayerNorm1P(
hidden_size, layernorm_epsilon, sequence_parallel_enabled=config.sequence_parallel
)
else:
self.post_inter_attention_layernorm = MixedFusedRMSNorm(hidden_size, layernorm_epsilon)
elif (
self.layer_type == LayerType.retrieval_decoder
or self.layer_type == LayerType.retrieval_decoder_after_self_attn
):
self.inter_attention = ParallelChunkedCrossAttention(
config=config,
init_method=init_method,
output_layer_init_method=output_layer_init_method,
layer_number=layer_number,
num_attention_heads=num_attention_heads,
hidden_size=hidden_size,
precision=precision,
apply_query_key_layer_scaling=apply_query_key_layer_scaling,
kv_channels=kv_channels,
masked_softmax_fusion=masked_softmax_fusion,
attention_dropout=attention_dropout,
megatron_legacy=megatron_legacy,
chunk_size=chunk_size,
bias=bias,
headscale=headscale,
)
# Normformer normalization
if transformer_block_type == 'normformer':
if normalization == 'layernorm':
self.post_inter_attention_normformer_norm = get_layer_norm(
hidden_size, layernorm_epsilon, persist_layer_norm, config.sequence_parallel
)
elif normalization == 'layernorm1p':
self.post_inter_attention_normformer_norm = LayerNorm1P(
hidden_size, layernorm_epsilon, sequence_parallel_enabled=config.sequence_parallel
)
else:
self.post_inter_attention_normformer_norm = MixedFusedRMSNorm(hidden_size, layernorm_epsilon)
# Layernorm on the attention output.
if normalization == 'layernorm':
self.post_inter_attention_layernorm = get_layer_norm(
hidden_size, layernorm_epsilon, persist_layer_norm, config.sequence_parallel
)
elif normalization == 'layernorm1p':
self.post_inter_attention_layernorm = LayerNorm1P(
hidden_size, layernorm_epsilon, sequence_parallel_enabled=config.sequence_parallel
)
else:
self.post_inter_attention_layernorm = MixedFusedRMSNorm(hidden_size, layernorm_epsilon)
# MLP
if num_moe_experts > 1 and self.layer_number % moe_frequency == 0:
self.mlp = SwitchMLP(
config=config,
num_experts=num_moe_experts,
init_method=init_method,
output_layer_init_method=output_layer_init_method,
hidden_size=hidden_size,
ffn_hidden_size=ffn_hidden_size,
bias_activation_fusion=bias_activation_fusion,
openai_gelu=openai_gelu,
onnx_safe=onnx_safe,
activation=activation,
bias=bias,
transformer_block_type=transformer_block_type,
normalization=normalization,
layernorm_epsilon=layernorm_epsilon,
persist_layer_norm=persist_layer_norm,
dropout=moe_dropout,
)
else:
self.mlp = ParallelMLP(
config=config,
init_method=init_method,
output_layer_init_method=output_layer_init_method,
hidden_size=hidden_size,
ffn_hidden_size=ffn_hidden_size,
bias_activation_fusion=bias_activation_fusion,
openai_gelu=openai_gelu,
onnx_safe=onnx_safe,
activation=activation,
bias=bias,
transformer_block_type=transformer_block_type,
normalization=normalization,
layernorm_epsilon=layernorm_epsilon,
persist_layer_norm=persist_layer_norm,
dropout=ffn_dropout,
)
def _get_bias_droput_add_func(self, transformer_block_type='pre_ln', position_after='attention'):
"""
Returns a function that potentially fuses the dropout and bias addition.
This function is particularly helpful for the normformer architecture that does not the fused kernel after attention layers, but can after the MLP.
"""
# Normformer activations at this point have no bias vector since they've gone through another normalization layer.
if transformer_block_type == 'normformer' and position_after == 'attention':
bias_dropout_add_func = get_dropout_add(self.training)
# Bias dropout add fused kernel
elif self.bias and self.bias_dropout_add_fusion:
if self.training:
bias_dropout_add_func = bias_dropout_add_fused_train
else:
bias_dropout_add_func = bias_dropout_add_fused_inference
# Bias dropout add non-fused kernel
elif self.bias and not self.bias_dropout_add_fusion:
bias_dropout_add_func = get_bias_dropout_add(self.training)
# Dropout add non-fused kernel for a model without bias terms.
else:
bias_dropout_add_func = get_dropout_add(self.training)
return bias_dropout_add_func
def forward(
self,
hidden_states,
attention_mask,
encoder_output=None,
enc_dec_attn_mask=None,
layer_past=None,
get_key_value=False,
set_inference_key_value_memory=False,
inference_max_sequence_len=None,
rotary_pos_emb=None, # list of positional embedding tensors, first one self attention, second one and third one are for cross attention (q, k)
self_attention_relative_position_bias=None,
cross_attention_relative_position_bias=None,
checkpoint_core_attention=False,
return_crossattention_scores=False,
return_selfattention_scores=False,
decoder_max_sequence_len=None,
encoder_max_sequence_len=None,
):
# Self attention.
if rotary_pos_emb is not None:
# self attention pos_emb is (q, q)
self_attention_pos_emb = (rotary_pos_emb[0], rotary_pos_emb[0])
cross_attention_pos_emb = (rotary_pos_emb[1], rotary_pos_emb[2])
else:
self_attention_pos_emb = None
cross_attention_pos_emb = None
if return_crossattention_scores and return_selfattention_scores:
raise NotImplementedError(
"We can only return 1 of cross attention scores or self attention scores. Not both yet."
)
attention_probs = None
if self.layer_type != LayerType.retrieval_decoder_after_self_attn:
# hidden_states: [b, s, h]
# Pre-LN: x -> LN -> MHA -> Residual -> LN -> MLP -> Residual
# Post-LN: x -> MHA -> Residual -> LN -> MLP -> Residual -> LN
# Normformer: x -> LN -> MHA -> LN -> Residual -> MLP (w/LN) -> Residual
residual = hidden_states
# Layer norm at the beginning of the transformer layer.
if self.transformer_block_type in ['pre_ln', 'normformer']:
hidden_states = self.input_layernorm(hidden_states)
attention_output, attention_bias = self.self_attention(
hidden_states,
attention_mask,
layer_past=layer_past,
get_key_value=get_key_value,
set_inference_key_value_memory=set_inference_key_value_memory,
inference_max_sequence_len=inference_max_sequence_len or decoder_max_sequence_len,
rotary_pos_emb=self_attention_pos_emb,
relative_position_bias=self_attention_relative_position_bias,
checkpoint_core_attention=checkpoint_core_attention,
return_scores=return_selfattention_scores,
)
if return_selfattention_scores:
attention_output, attention_probs = attention_output
if get_key_value:
attention_output, presents = attention_output
# If normformer, apply norm on the output of the self attention.
if self.transformer_block_type == 'normformer':
# Normformer normalization
attention_output = (
attention_output + attention_bias if attention_bias is not None else attention_output
)
attention_output = self.post_attention_normformer_norm(attention_output)
attention_bias = None
# jit scripting for a nn.module (with dropout) is not
# triggering the fusion kernel. For now, we use two
# different nn.functional routines to account for varying
# dropout semantics during training and inference phases.
bias_dropout_add_func = self._get_bias_droput_add_func(
transformer_block_type=self.transformer_block_type, position_after='attention'
)
if attention_bias is not None:
attention_bias = attention_bias.expand_as(residual)
if self.is_adapter_available():
adapter_1 = self.get_adapter_module(AdapterName.PRE_ATTN_ADAPTER)
if adapter_1 and self.adapter_cfg[AdapterName.PRE_ATTN_ADAPTER]['enabled']:
attention_output = (
adapter_1(attention_output) + attention_output
) # simple adapter call with residual connection
layernorm_input = bias_dropout_add_func(attention_output, attention_bias, residual, self.hidden_dropout)
# print(f"Layer: {self.layer_number} Attention checksum {layernorm_input.sum()}")
# Post-LN normalization after residual
if self.transformer_block_type == 'post_ln':
normalization_output = self.input_layernorm(layernorm_input)
layernorm_input = normalization_output
elif self.transformer_block_type in ['pre_ln', 'normformer']:
# Layer norm post the self attention.
normalization_output = self.post_attention_layernorm(layernorm_input)
else:
normalization_output = None
logging.warning(f"This is a rare case since `normalization_output=None`")
else:
layernorm_input, normalization_output = hidden_states
if self.layer_type == LayerType.decoder_pre_mlp:
return layernorm_input, normalization_output
if (
self.layer_type == LayerType.decoder
or self.layer_type == LayerType.retrieval_decoder
or self.layer_type == LayerType.retrieval_encoder
or self.layer_type == LayerType.retrieval_decoder_after_self_attn
):
if (
self.layer_type == LayerType.retrieval_decoder
or self.layer_type == LayerType.retrieval_decoder_after_self_attn
):
attention_output, attention_bias = self.inter_attention(
normalization_output,
enc_dec_attn_mask,
encoder_output=encoder_output,
rotary_pos_emb=cross_attention_pos_emb,
set_inference_key_value_memory=set_inference_key_value_memory,
inference_max_sequence_len=inference_max_sequence_len,
checkpoint_core_attention=checkpoint_core_attention,
)
else:
# Return Scores is being passed only for inter_attention and not self attention
attention_output, attention_bias = self.inter_attention(
normalization_output,
enc_dec_attn_mask,
encoder_output=encoder_output,
rotary_pos_emb=cross_attention_pos_emb,
relative_position_bias=cross_attention_relative_position_bias,
checkpoint_core_attention=checkpoint_core_attention,
return_scores=return_crossattention_scores,
set_inference_key_value_memory=set_inference_key_value_memory,
inference_max_sequence_len=encoder_max_sequence_len,
)
if return_crossattention_scores:
attention_output, attention_probs = attention_output
# If normformer, apply norm on the output of the self attention.
if self.transformer_block_type == 'normformer':
# Normformer normalization
attention_output = (
attention_output + attention_bias if attention_bias is not None else attention_output
)
attention_output = self.post_inter_attention_normformer_norm(attention_output)
attention_bias = None
residual = layernorm_input
bias_dropout_add_func = self._get_bias_droput_add_func(
transformer_block_type=self.transformer_block_type, position_after='attention'
)
layernorm_input = bias_dropout_add_func(attention_output, attention_bias, residual, self.hidden_dropout)
# print(f"Layer: {self.layer_number} Cross-Attention checksum {layernorm_input.sum()}")
normalization_output = self.post_inter_attention_layernorm(layernorm_input)
# Post-LN normalization after residual
if self.transformer_block_type == 'post_ln':
layernorm_input = normalization_output
# MLP.
mlp_output, mlp_bias = self.mlp(normalization_output)
if self.is_adapter_available():
# TODO: (@adithyre) was able to move adapter_2 back to the end of the transformer after ptl 1.7 update.
adapter_2 = self.get_adapter_module(AdapterName.POST_ATTN_ADAPTER)
if adapter_2 and self.adapter_cfg[AdapterName.POST_ATTN_ADAPTER]['enabled']:
mlp_output = adapter_2(mlp_output) + mlp_output # simple adapter call with residual connection
residual = layernorm_input
bias_dropout_add_func = self._get_bias_droput_add_func(
transformer_block_type=self.transformer_block_type, position_after='mlp'
)
output = bias_dropout_add_func(mlp_output, mlp_bias, residual, self.hidden_dropout)
if self.transformer_block_type == 'post_ln':
output = self.post_attention_layernorm(output)
if get_key_value:
output = [output, presents]
if attention_probs is not None:
output = [output, attention_probs]
return output
class ParallelTransformerLayer(ParallelTransformerLayer_):
def __init__(
self,
config: ModelParallelConfig,
init_method,
output_layer_init_method,
layer_number,
hidden_size,
ffn_hidden_size,
num_attention_heads,
layer_type=LayerType.encoder,
self_attn_mask_type=AttnMaskType.padding,
fp32_residual_connection=False,
precision=16,
apply_query_key_layer_scaling=False,
kv_channels=None,
layernorm_epsilon=1e-5,
hidden_dropout=0.1,
bias_dropout_add_fusion=True,
persist_layer_norm=False,
bias_activation_fusion=True,
openai_gelu=False,
onnx_safe=False,
masked_softmax_fusion=True,
attention_dropout=0.1,
ffn_dropout=0.0,
activation='gelu',
megatron_legacy=False,
bias=True,
chunk_size=64,
normalization='layernorm',
transformer_block_type='pre_ln',
position_embedding_type='learned_absolute',
multi_query_attention=False,
headscale=False,
activations_checkpoint_granularity=None,
normalize_attention_scores=True,
num_moe_experts=1,
moe_frequency=1,
moe_dropout=0.0,
use_flash_attention=False,
):
super(ParallelTransformerLayer, self).__init__(
config=config,
init_method=init_method,
output_layer_init_method=output_layer_init_method,
layer_number=layer_number,
hidden_size=hidden_size,
ffn_hidden_size=ffn_hidden_size,
num_attention_heads=num_attention_heads,
layer_type=layer_type,
self_attn_mask_type=self_attn_mask_type,
fp32_residual_connection=fp32_residual_connection,
precision=precision,
apply_query_key_layer_scaling=apply_query_key_layer_scaling,
kv_channels=kv_channels,
layernorm_epsilon=layernorm_epsilon,
hidden_dropout=hidden_dropout,
bias_dropout_add_fusion=bias_dropout_add_fusion,
persist_layer_norm=persist_layer_norm,
bias_activation_fusion=bias_activation_fusion,
openai_gelu=openai_gelu,
onnx_safe=onnx_safe,
masked_softmax_fusion=masked_softmax_fusion,
attention_dropout=attention_dropout,
ffn_dropout=ffn_dropout,
activation=activation,
megatron_legacy=megatron_legacy,
bias=bias,
chunk_size=chunk_size,
normalization=normalization,
transformer_block_type=transformer_block_type,
position_embedding_type=position_embedding_type,
headscale=headscale,
multi_query_attention=multi_query_attention,
activations_checkpoint_granularity=activations_checkpoint_granularity,
normalize_attention_scores=normalize_attention_scores,
num_moe_experts=num_moe_experts,
moe_frequency=moe_frequency,
moe_dropout=moe_dropout,
use_flash_attention=use_flash_attention,
)
# Dtype for forward pass - ignore amp O2
self.dtype = utils_funcs.torch_dtype_from_precision(precision, megatron_amp_O2=None)
def forward(
self,
hidden_states,
attention_mask,
encoder_output=None,
enc_dec_attn_mask=None,
rotary_pos_emb=None,
layer_past=None,
get_key_value=False,
set_inference_key_value_memory=False,
inference_max_sequence_len=None,
self_attention_relative_position_bias=None,
cross_attention_relative_position_bias=None,
checkpoint_core_attention=False,
return_crossattention_scores=False,
return_selfattention_scores=False,
decoder_max_sequence_len=None,
encoder_max_sequence_len=None,
):
if self.dtype == torch.float32:
return super().forward(
hidden_states,
attention_mask,
encoder_output,
enc_dec_attn_mask,
layer_past,
get_key_value,
set_inference_key_value_memory,
inference_max_sequence_len,
rotary_pos_emb,
self_attention_relative_position_bias,
cross_attention_relative_position_bias,
checkpoint_core_attention,
return_crossattention_scores=return_crossattention_scores,
return_selfattention_scores=return_selfattention_scores,
decoder_max_sequence_len=decoder_max_sequence_len,
encoder_max_sequence_len=encoder_max_sequence_len,
)
with torch.autocast(device_type="cuda", dtype=self.dtype):
return super().forward(
hidden_states,
attention_mask,
encoder_output,
enc_dec_attn_mask,
layer_past,
get_key_value,
set_inference_key_value_memory,
inference_max_sequence_len,
rotary_pos_emb,
self_attention_relative_position_bias,
cross_attention_relative_position_bias,
checkpoint_core_attention,
return_crossattention_scores=return_crossattention_scores,
return_selfattention_scores=return_selfattention_scores,
decoder_max_sequence_len=decoder_max_sequence_len,
encoder_max_sequence_len=encoder_max_sequence_len,
)
class AutocastTransformerLayer(TransformerLayer):
def __init__(
self,
hidden_size: int,
ffn_hidden_size: int,
layernorm_epsilon: float,
num_attention_heads: int,
init_method: Callable,
output_layer_init_method: Callable,
hidden_dropout: float,
attention_dropout: float,
layer_number: Optional[int] = None,
kv_channels: Optional[int] = None,
self_attn_mask_type: str = "causal",
tp_group: Optional[Any] = None,
tp_size: int = 1,
params_dtype: torch.dtype = torch.float32,
get_rng_state_tracker: Optional[Callable] = None,
fuse_wgrad_accumulation: bool = False,
seq_length: Optional[int] = None,
micro_batch_size: Optional[int] = None,
sequence_parallel: bool = False,
apply_residual_connection_post_layernorm: bool = False,
output_layernorm: bool = False,
layer_type: str = "encoder",
drop_path_rate: float = 0,
use_emha: bool = False,
ub_tp_comm_overlap: bool = False,
ub_bulk_wgrad: bool = True,
ub_bulk_dgrad: bool = True,
autocast_dtype: Any = 16,
zero_centered_gamma: bool = False,
device: str = 'cuda',
**kwargs,
) -> None:
transformer_layer_args = {
"hidden_size": hidden_size,
"ffn_hidden_size": ffn_hidden_size,
"layernorm_epsilon": layernorm_epsilon,
"num_attention_heads": num_attention_heads,
"init_method": init_method,
"output_layer_init_method": output_layer_init_method,
"hidden_dropout": hidden_dropout,
"attention_dropout": attention_dropout,
"layer_number": layer_number,
"kv_channels": kv_channels,
"self_attn_mask_type": self_attn_mask_type,
"tp_group": tp_group,
"tp_size": tp_size,
"params_dtype": params_dtype,
"get_rng_state_tracker": get_rng_state_tracker,
"fuse_wgrad_accumulation": fuse_wgrad_accumulation,
"seq_length": seq_length,
"micro_batch_size": micro_batch_size,
"sequence_parallel": sequence_parallel,
"apply_residual_connection_post_layernorm": apply_residual_connection_post_layernorm,
"output_layernorm": output_layernorm,
"layer_type": layer_type,
"drop_path_rate": drop_path_rate,
"set_parallel_mode": tp_size > 1,
"fuse_qkv_params": True,
"zero_centered_gamma": zero_centered_gamma,
"ub_tp_comm_overlap": ub_tp_comm_overlap,
"ub_bulk_wgrad": ub_bulk_wgrad,
"ub_bulk_dgrad": ub_bulk_dgrad,
"device": device,
}
te_version = packaging.version.Version(version("transformer-engine"))
if te_version > packaging.version.Version("1.5.0"):
for comm in ["ag", "rs"]:
ub_overlap_flag = "ub_overlap_" + comm
split_gemm_flag = "ub_split_" + comm
atomic_gemm_flag = "ub_atomic_gemm_" + comm
# Use old overlap flags if they were supplied instead
if ub_overlap_flag in kwargs:
transformer_layer_args[ub_overlap_flag] = kwargs[ub_overlap_flag]
else:
transformer_layer_args[ub_overlap_flag] = kwargs.get(split_gemm_flag, True) or kwargs.get(
atomic_gemm_flag, False
)
if te_version > packaging.version.Version("1.6.0.dev0"):
transformer_layer_args["ub_overlap_rs_dgrad"] = kwargs.get("ub_overlap_rs_dgrad", False)
else:
transformer_layer_args["ub_split_ag"] = kwargs.get("ub_split_ag", True)
transformer_layer_args["ub_split_rs"] = kwargs.get("ub_split_rs", True)
transformer_layer_args["ub_atomic_gemm_ag"] = kwargs.get("ub_atomic_gemm_ag", False)
transformer_layer_args["ub_atomic_gemm_rs"] = kwargs.get("ub_atomic_gemm_rs", False)
super().__init__(**transformer_layer_args)
# Dtype for forward pass - ignore amp O2
self.dtype = utils_funcs.torch_dtype_from_precision(autocast_dtype, megatron_amp_O2=None)
def forward(
self,
hidden_states: torch.Tensor,
attention_mask: torch.Tensor,
encoder_output: Optional[torch.Tensor] = None,
enc_dec_attn_mask: Optional[torch.Tensor] = None,
inference_params: Optional[Any] = None,
is_first_microbatch: Optional[bool] = None,
checkpoint_core_attention: Optional[bool] = False,
) -> torch.Tensor:
if self.dtype == torch.float32:
return super().forward(
hidden_states,
attention_mask,
encoder_output=encoder_output,
enc_dec_attn_mask=enc_dec_attn_mask,
inference_params=inference_params,
is_first_microbatch=is_first_microbatch,
checkpoint_core_attention=checkpoint_core_attention,
)
with torch.autocast(device_type="cuda", dtype=self.dtype):
return super().forward(
hidden_states,
attention_mask,
encoder_output=encoder_output,
enc_dec_attn_mask=enc_dec_attn_mask,
inference_params=inference_params,
is_first_microbatch=is_first_microbatch,
checkpoint_core_attention=checkpoint_core_attention,
)
class ParallelTransformer(MegatronModule):
"""Transformer class."""
def __init__(
self,
config: ModelParallelConfig,
init_method,
output_layer_init_method,
num_layers,
hidden_size,
ffn_hidden_size,
num_attention_heads,
apply_query_key_layer_scaling=False,
kv_channels=None,
layer_type=LayerType.encoder, # it can be a list of types or single type
self_attn_mask_type=AttnMaskType.padding,
pre_process=True,
post_process=True,
precision=16,
fp32_residual_connection=False,
activations_checkpoint_method=None,
activations_checkpoint_num_layers=None,
layernorm_epsilon=1e-5,
hidden_dropout=0.1,
attention_dropout=0.1,
ffn_dropout=0.0,
bias_activation_fusion=True,
bias_dropout_add_fusion=True,
masked_softmax_fusion=True,
persist_layer_norm=False,
openai_gelu=False,
onnx_safe=False,
activation='gelu',
model_type=ModelType.encoder_or_decoder,
megatron_legacy=False,
bias=True,
chunk_size=64,
normalization='layernorm',
transformer_block_type='pre_ln',
position_embedding_type='learned_absolute',
headscale=False,
layer_number_offset=0, # this is use only for attention norm_factor scaling
activations_checkpoint_granularity=None,
activations_checkpoint_layers_per_pipeline=None,
transformer_engine=False,
fp8=False,
fp8_e4m3=False,
fp8_hybrid=False,
fp8_margin=0,
fp8_interval=1,
fp8_amax_history_len=1024,
fp8_amax_compute_algo='max',
reduce_amax=True,
use_emha=False,
ub_tp_comm_overlap=False,
normalize_attention_scores=True,
multi_query_attention=False,
num_moe_experts=1,
moe_frequency=1,
moe_dropout=0.0,
use_flash_attention=False,
):
super(ParallelTransformer, self).__init__(config=config)
if kv_channels is None:
assert (
hidden_size % num_attention_heads == 0
), 'hidden_size must be divisible by num_attention_heads if kv_channels is None'