-
Notifications
You must be signed in to change notification settings - Fork 0
/
deploying_t5.py
1767 lines (1501 loc) · 88.2 KB
/
deploying_t5.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
"""
T5: https://github.com/huggingface/transformers/blob/main/src/transformers/models/t5/modeling_t5.py#L19
"""
from typing import Optional, Tuple, Union, List, Callable
import time
import copy
import datetime
import warnings
import numpy as np
import torch
import math
from einops import rearrange
import torch.distributed as dist
from torch import nn
from torch.nn import CrossEntropyLoss
from torch.utils.checkpoint import checkpoint
from transformers import T5Tokenizer
from transformers.modeling_outputs import (
BaseModelOutput,
BaseModelOutputWithPastAndCrossAttentions,
Seq2SeqLMOutput
)
from transformers.models.t5.modeling_t5 import (
T5LayerNorm,
T5Attention,
T5LayerSelfAttention,
T5LayerCrossAttention,
T5LayerFF,
T5Block,
T5Stack,
T5ForConditionalGeneration,
)
from transformers.models.t5.configuration_t5 import T5Config
from transformers.generation.utils import GreedySearchDecoderOnlyOutput, GreedySearchEncoderDecoderOutput
from transformers.generation.logits_process import LogitsProcessorList
from transformers.generation.stopping_criteria import StoppingCriteriaList, validate_stopping_criteria
from transformers.utils import logging
from util import (
get_skip_mask,
BetaMixture1D,
)
from util.skip_conf import get_skip_mask_cd
logger = logging.get_logger(__name__)
__HEAD_MASK_WARNING_MSG = """
The input argument `head_mask` was split into two arguments `head_mask` and `decoder_head_mask`. Currently,
`decoder_head_mask` is set to copy `head_mask`, but this feature is deprecated and will be removed in future versions.
If you do not want to use any `decoder_head_mask` now, please set `decoder_head_mask = torch.ones(num_layers,
num_heads)`.
"""
GreedySearchOutput = Union[GreedySearchEncoderDecoderOutput, GreedySearchDecoderOnlyOutput]
class DeployT5Attention(T5Attention):
def __init__(self, config: T5Config, has_relative_attention_bias=False):
"""
Initialize the Deploy T5 Attention layer.
What's New:
- Initialization of configuration and model parameters.
- Initialization of Mesh TensorFlow to avoid scaling before softmax.
- Initialization of additional neural network layers if relative attention biases are enabled.
Args:
config (T5Config): Configuration object with model parameters.
has_relative_attention_bias (bool): Flag to indicate if relative attention biases are used.
The constructor extends the base T5Attention with specific configurations, and initializes
additional neural network layers if relative attention biases are enabled.
"""
super().__init__(config, has_relative_attention_bias)
self.config = config
####### Initialization of configuration and model parameters #######
self.is_decoder = config.is_decoder # Boolean indicating if this is a decoder module
self.has_relative_attention_bias = has_relative_attention_bias # Boolean for relative attention bias usage
self.relative_attention_num_buckets = config.relative_attention_num_buckets # Number of buckets for relative attention
self.relative_attention_max_distance = config.relative_attention_max_distance # Maximum distance for relative attention
self.d_model = config.d_model # Dimension of the model
self.key_value_proj_dim = config.d_kv # Dimension for key/value projections
self.n_heads = config.num_heads # Number of attention heads
self.dropout = config.dropout_rate # Dropout rate
self.inner_dim = self.n_heads * self.key_value_proj_dim # Compute the inner dimension for the model
####### Mesh TensorFlow initialization to avoid scaling before softmax #######
self.q = nn.Linear(self.d_model, self.inner_dim, bias=False) # Linear transformation for query
self.k = nn.Linear(self.d_model, self.inner_dim, bias=False) # Linear transformation for key
self.v = nn.Linear(self.d_model, self.inner_dim, bias=False) # Linear transformation for value
self.o = nn.Linear(self.inner_dim, self.d_model, bias=False) # Linear transformation to output from attention heads
####### Initialization of additional neural network layers if relative attention biases are enabled #######
if self.has_relative_attention_bias:
self.relative_attention_bias = nn.Embedding(self.relative_attention_num_buckets, self.n_heads)
self.pruned_heads = set()
self.gradient_checkpointing = False
def forward(
self,
hidden_states,
mask=None,
key_value_states=None,
position_bias=None,
past_key_value=None,
layer_head_mask=None,
query_length=None,
use_cache=False,
output_attentions=False,
skip_mask=False,
gen_cross_attn_key_value=False,
stack_hidden_states=None,
):
"""
Self-attention (if key_value_states is None) or attention over source sentence (provided by key_value_states).
"""
# Input is (batch_size, seq_length, dim)
# Mask is (batch_size, key_length) (non-causal) or (batch_size, key_length, key_length)
# past_key_value[0] is (batch_size, n_heads, q_len - 1, dim_per_head)
# Input and output preparation for attention operation
if self.config.use_synchronize: torch.cuda.synchronize()
start = datetime.datetime.now()
_, seq_length = hidden_states.shape[:2]
real_seq_length = seq_length
####### Handling of past key-value states for incremental decoding #######
if past_key_value is not None:
assert (
len(past_key_value) == 2
), f"past_key_value should have 2 past states: keys and values. Got { len(past_key_value)} past states"
if query_length is None:
if past_key_value[0] is not None: real_seq_length += past_key_value[0].shape[2]
if stack_hidden_states is not None: real_seq_length += stack_hidden_states.shape[1]
else:
real_seq_length += query_length
key_length = real_seq_length if key_value_states is None else key_value_states.shape[1]
def project(hidden_states, proj_layer, key_value_states, past_key_value):
"""Projects input states into query, key, or value states for attention."""
if key_value_states is None:
# Self-attention projection
# (batch_size, n_heads, seq_length, dim_per_head)
hidden_states = rearrange(proj_layer(hidden_states), 'b l (h d) -> b h l d', h=self.n_heads)
elif past_key_value is None:
# Cross-attention projection when there is no past key value
# (batch_size, n_heads, seq_length, dim_per_head)
hidden_states = rearrange(proj_layer(key_value_states), 'b l (h d) -> b h l d', h=self.n_heads)
if past_key_value is not None:
if key_value_states is None:
# Append past key or value states for self-attention
# (batch_size, n_heads, key_length, dim_per_head)
hidden_states = torch.cat([past_key_value, hidden_states], dim=2)
elif past_key_value.shape[2] != key_value_states.shape[1]:
# Handle mismatch in sequence lengths between past states and current key-value states
# Cross-attention
# (batch_size, n_heads, seq_length, dim_per_head)
hidden_states = rearrange(proj_layer(key_value_states), 'b l (h d) -> b h l d', h=self.n_heads)
else:
# Use past key or value states directly in cross-attention
hidden_states = past_key_value
return hidden_states
####### Compute key and value states from hidden states #######
if self.is_decoder and key_value_states is None and stack_hidden_states is not None:
_hidden_states = torch.cat((stack_hidden_states,) + (hidden_states,), dim=1)
else:
_hidden_states = hidden_states
key_states = project(
_hidden_states, self.k, key_value_states, past_key_value[0] if past_key_value is not None else None
)
value_states = project(
_hidden_states, self.v, key_value_states, past_key_value[1] if past_key_value is not None else None
)
if self.config.use_synchronize: torch.cuda.synchronize()
if self.is_decoder: self.key_value_gen_time = (datetime.datetime.now() - start)
####### Generate cross-attention key-value pairs for past skipped tokens (if specified) #######
if gen_cross_attn_key_value:
return [key_states, value_states]
if self.config.use_synchronize: torch.cuda.synchronize()
start = datetime.datetime.now()
####### Initialize or use provided position bias for attention computation #######
if position_bias is None:
if not self.has_relative_attention_bias:
# Default position bias for models without relative attention bias
position_bias = torch.zeros(
(1, self.n_heads, real_seq_length, key_length), device=hidden_states.device, dtype=hidden_states.dtype
)
if self.gradient_checkpointing and self.training:
position_bias.requires_grad = True
else:
# Compute position bias using a learned embedding table
position_bias = self.compute_bias(real_seq_length, key_length, device=hidden_states.device)
# if key and values are already calculated
# we want only the last query position bias
# Adjust position bias based on past states if necessary
if past_key_value is not None:
position_bias = position_bias[:, :, -hidden_states.size(1):, :]
if mask is not None:
# Apply mask to position bias for padded tokens or future tokens in causal attention
position_bias = position_bias + mask # (batch_size, n_heads, seq_length, key_length)
####### Skip mask computation if not required ########
if skip_mask:
attn_output = None
else:
# get query states
query_states = rearrange(self.q(hidden_states), 'b l (h d) -> b h l d', h=self.n_heads)
# compute scores
scores = torch.einsum("bhid,bhjd->bhij", query_states, key_states)
if self.pruned_heads:
mask = torch.ones(position_bias.shape[1])
mask[list(self.pruned_heads)] = 0
position_bias_masked = position_bias[:, mask.bool()]
else:
position_bias_masked = position_bias
scores += position_bias_masked
attn_weights = nn.functional.softmax(scores.float(), dim=-1)
attn_weights = nn.functional.dropout(
attn_weights, p=self.dropout, training=self.training
) # (batch_size, n_heads, seq_length, key_length)
# Mask heads if we want to
if layer_head_mask is not None:
attn_weights = attn_weights * layer_head_mask
attn_output = torch.einsum("bhij,bhjd->bhid", attn_weights, value_states)
attn_output = rearrange(attn_output, 'b h s d -> b s (h d)', h=self.n_heads, d=self.key_value_proj_dim)
attn_output = self.o(attn_output)
if self.config.use_synchronize: torch.cuda.synchronize()
if self.is_decoder: self.attn_ffn_time = (datetime.datetime.now() - start)
####### Prepare outputs including the present key-value states if caching is enabled #######
present_key_value_state = [key_states, value_states] if (self.is_decoder and use_cache) else None
outputs = (attn_output,) + (present_key_value_state,) + (position_bias,)
####### Include attention weights in output if requested #######
if output_attentions:
outputs = outputs + (attn_weights,)
return outputs
class DeployT5LayerSelfAttention(T5LayerSelfAttention):
def __init__(self, config, has_relative_attention_bias=False):
super().__init__(config, has_relative_attention_bias)
self.config = config
self.SelfAttention = DeployT5Attention(config, has_relative_attention_bias=has_relative_attention_bias)
self.layer_norm = T5LayerNorm(config.d_model, eps=config.layer_norm_epsilon)
self.dropout = nn.Dropout(config.dropout_rate)
def forward(
self,
hidden_states,
attention_mask=None,
position_bias=None,
layer_head_mask=None,
past_key_value=None,
use_cache=False,
output_attentions=False,
skip_mask=False,
stack_hidden_states=None,
):
if self.config.use_synchronize: torch.cuda.synchronize()
start = datetime.datetime.now()
normed_hidden_states = self.layer_norm(hidden_states)
normed_stack_hidden_states = self.layer_norm(stack_hidden_states) if stack_hidden_states is not None else None
if self.config.use_synchronize: torch.cuda.synchronize()
norm_time = (datetime.datetime.now() - start)
attention_output = self.SelfAttention(
normed_hidden_states,
mask=attention_mask,
position_bias=position_bias,
layer_head_mask=layer_head_mask,
past_key_value=past_key_value,
use_cache=use_cache,
output_attentions=output_attentions,
skip_mask=skip_mask,
stack_hidden_states=normed_stack_hidden_states,
)
if self.config.use_synchronize: torch.cuda.synchronize()
start = datetime.datetime.now()
if not skip_mask:
hidden_states = hidden_states + self.dropout(attention_output[0])
outputs = (hidden_states,) + attention_output[1:] # add attentions if we output them
else:
outputs = (hidden_states,) + attention_output[1:] # add attentions if we output them
if self.config.use_synchronize: torch.cuda.synchronize()
if self.config.is_decoder:
self.attn_ffn_time = self.SelfAttention.attn_ffn_time + norm_time + (datetime.datetime.now() - start)
self.key_value_gen_time = self.SelfAttention.key_value_gen_time
return outputs
class DeployT5LayerCrossAttention(T5LayerCrossAttention):
def __init__(self, config):
super().__init__(config)
self.config = config
self.EncDecAttention = DeployT5Attention(config, has_relative_attention_bias=False)
self.layer_norm = T5LayerNorm(config.d_model, eps=config.layer_norm_epsilon)
self.dropout = nn.Dropout(config.dropout_rate)
def forward(
self,
hidden_states,
key_value_states,
attention_mask=None,
position_bias=None,
layer_head_mask=None,
past_key_value=None,
use_cache=False,
query_length=None,
output_attentions=False,
skip_mask=False,
parallel_mask=False,
gen_cross_attn_key_value=False,
):
if self.config.use_synchronize: torch.cuda.synchronize()
start = datetime.datetime.now()
if (not skip_mask and not gen_cross_attn_key_value) or parallel_mask:
normed_hidden_states = self.layer_norm(hidden_states)
else: normed_hidden_states = hidden_states
if self.config.use_synchronize: torch.cuda.synchronize()
norm_time = (datetime.datetime.now() - start)
attention_output = self.EncDecAttention(
normed_hidden_states,
mask=attention_mask,
key_value_states=key_value_states,
position_bias=position_bias,
layer_head_mask=layer_head_mask,
past_key_value=past_key_value,
use_cache=use_cache,
query_length=query_length,
output_attentions=output_attentions,
skip_mask=skip_mask,
gen_cross_attn_key_value=gen_cross_attn_key_value,
)
if gen_cross_attn_key_value:
self.key_value_gen_time = self.EncDecAttention.key_value_gen_time
return attention_output # non-autoregressively generated key_value_states
if self.config.use_synchronize: torch.cuda.synchronize()
start = datetime.datetime.now()
if not skip_mask:
hidden_states = hidden_states + self.dropout(attention_output[0])
outputs = (hidden_states,) + attention_output[1:] # add attentions if we output them
else:
outputs = (hidden_states,) + attention_output[1:] # add attentions if we output them
if self.config.use_synchronize: torch.cuda.synchronize()
if self.config.is_decoder:
self.attn_ffn_time = self.EncDecAttention.attn_ffn_time + norm_time + (datetime.datetime.now() - start)
self.key_value_gen_time = self.EncDecAttention.key_value_gen_time
return outputs
class DeployT5Block(T5Block):
def __init__(self, config, has_relative_attention_bias=False):
super().__init__(config, has_relative_attention_bias)
self.config = config
self.is_decoder = config.is_decoder # Flag to check if this block is part of the decoder
# Initialize layers in the block
self.layer = nn.ModuleList()
self.layer.append(DeployT5LayerSelfAttention(config, has_relative_attention_bias=has_relative_attention_bias))
######## decoder ########
if self.is_decoder:
# Add cross-attention layer only if it's a decoder
self.layer.append(DeployT5LayerCrossAttention(config))
######## common ########
# Always add the feed-forward layer
self.layer.append(T5LayerFF(config))
######## decoder ########
def get_shallow_logits(self, hidden_states):
# Generate logits from shallow hidden states (typically used in fast decoding)
shallow_hidden_states = self.layer[0].layer_norm(hidden_states)
shallow_hidden_states = self.dropout(shallow_hidden_states)
shallow_logits = self.lm_head(shallow_hidden_states)
return shallow_logits
######## decoder ########
def gen_cross_attn_key_value(
self,
hidden_states,
attention_mask=None,
position_bias=None,
encoder_hidden_states=None,
encoder_attention_mask=None,
encoder_decoder_position_bias=None,
layer_head_mask=None,
cross_attn_layer_head_mask=None,
past_key_value=None,
use_cache=False,
output_attentions=False,
):
r"""
In Shallow-Deep framework, if all previous tokens, including <start> token, have skipped Deep decoder,
generate cross-attn key_values only ONCE because they are shared for all sequence.
return (None, None) + cross_attn_past_key_value: Tuple[torch.Tensor] (length of 2)
"""
# if all previous tokens, including <start> token, have skipped Deep decoder
assert self.is_decoder and encoder_hidden_states is not None
cross_attn_past_key_value = self.layer[1](
hidden_states,
key_value_states=encoder_hidden_states,
attention_mask=encoder_attention_mask,
position_bias=encoder_decoder_position_bias,
layer_head_mask=cross_attn_layer_head_mask,
past_key_value=past_key_value,
use_cache=use_cache,
output_attentions=output_attentions,
gen_cross_attn_key_value=True,
)
self.key_value_gen_time = self.layer[1].key_value_gen_time
past_key_value = [None, None,] + cross_attn_past_key_value
return past_key_value
def forward(
self,
hidden_states,
attention_mask=None,
position_bias=None,
encoder_hidden_states=None,
encoder_attention_mask=None,
encoder_decoder_position_bias=None,
layer_head_mask=None,
cross_attn_layer_head_mask=None,
past_key_value=None,
use_cache=False,
output_attentions=False,
return_dict=True,
skip_mask=False,
parallel_mask=False,
stack_hidden_states=None,
):
# Process input through the block, handling both self-attention and cross-attention if applicable
######## common ########
# Handling past key values for caching and faster processing
if past_key_value is not None:
if not self.is_decoder:
logger.warning("`past_key_values` is passed to the encoder. Please make sure this is intended.")
expected_num_past_key_values = 2 if encoder_hidden_states is None else 4
if len(past_key_value) != expected_num_past_key_values:
raise ValueError(
f"There should be {expected_num_past_key_values} past states. "
f"{'2 (past / key) for cross attention. ' if expected_num_past_key_values == 4 else ''}"
f"Got {len(past_key_value)} past key / value states"
)
self_attn_past_key_value = past_key_value[:2]
cross_attn_past_key_value = past_key_value[2:]
else:
self_attn_past_key_value, cross_attn_past_key_value = None, None
######## common ########
# Process self-attention
self_attention_outputs = self.layer[0](
hidden_states,
attention_mask=attention_mask,
position_bias=position_bias,
layer_head_mask=layer_head_mask,
past_key_value=self_attn_past_key_value,
use_cache=use_cache,
output_attentions=output_attentions,
skip_mask=skip_mask,
stack_hidden_states=stack_hidden_states,
)
hidden_states, present_key_value_state = self_attention_outputs[:2]
attention_outputs = self_attention_outputs[2:] # Keep self-attention outputs and relative position weights
do_cross_attention = self.is_decoder and encoder_hidden_states is not None
if do_cross_attention:
# the actual query length is unknown for cross attention
# if using past key value states. Need to inject it here
if present_key_value_state is not None:
query_length = present_key_value_state[0].shape[2]
else:
query_length = None
cross_attention_outputs = self.layer[1](
hidden_states,
key_value_states=encoder_hidden_states,
attention_mask=encoder_attention_mask,
position_bias=encoder_decoder_position_bias,
layer_head_mask=cross_attn_layer_head_mask,
past_key_value=cross_attn_past_key_value,
query_length=query_length,
use_cache=use_cache,
output_attentions=output_attentions,
skip_mask=skip_mask,
parallel_mask=parallel_mask,
)
hidden_states = cross_attention_outputs[0]
# Combine self attn and cross attn key value states
if present_key_value_state is not None:
present_key_value_state = present_key_value_state + cross_attention_outputs[1]
# Keep cross-attention outputs and relative position weights
attention_outputs = attention_outputs + cross_attention_outputs[2:]
if self.config.use_synchronize: torch.cuda.synchronize()
start = datetime.datetime.now()
# Apply Feed Forward layer
if not skip_mask:
hidden_states = self.layer[-1](hidden_states)
if self.config.use_synchronize: torch.cuda.synchronize()
if self.is_decoder:
self.ffn_time = datetime.datetime.now() - start
self.key_value_gen_time = (self.layer[0].key_value_gen_time, self.layer[1].key_value_gen_time)
self.attn_time = (self.layer[0].attn_ffn_time, self.layer[1].attn_ffn_time)
outputs = (hidden_states,)
if use_cache:
outputs = outputs + (present_key_value_state,) + attention_outputs
else:
outputs = outputs + attention_outputs
return outputs # hidden-states, present_key_value_states, (self-attention position bias), (self-attention weights), (cross-attention position bias), (cross-attention weights)
class DeployT5Stack(T5Stack):
def __init__(self, config, embed_tokens=None):
super().__init__(config, embed_tokens)
self.graph_top_k_list = []
self.graph_top_k_confidence = []
self.top_k_indices = None
self.embed_tokens = embed_tokens
self.is_decoder = config.is_decoder
self.flop_counter = 0.0
self.block = nn.ModuleList(
[DeployT5Block(config, has_relative_attention_bias=bool(i == 0)) for i in range(config.num_layers)]
)
self.final_layer_norm = T5LayerNorm(config.d_model, eps=config.layer_norm_epsilon)
self.dropout = nn.Dropout(config.dropout_rate)
# Initialize weights and apply final processing
self.post_init()
self.device_map = None
self.gradient_checkpointing = False
# Early-Exit framework
self.use_early_exit = config.use_early_exit
self.exit_min_layer = config.exit_min_layer
# Shallow-Deep Module
self.use_shallow_deep = config.use_shallow_deep
self.shallow_exit_layer = config.shallow_exit_layer
if self.is_decoder and config.use_shallow_deep:
assert config.shallow_exit_layer > 0 and config.shallow_exit_layer < len(self.block)
# Synchronized Parallel Decoding
self.block_op = [0] * config.num_layers # to calculate the average number of forward block layers
self.parallel_tokens_shallow = 0 # how much tokens are used in parallel decoding as stack_hidden_states
self.parallel_tokens_deep = 0 # how much tokens are used in parallel decoding with skip_mask = False
self.stack_hidden_states = () # store hidden_states that do not forward Deep decoder
# Adaptive Threshold Estimator
self.bmm_model = BetaMixture1D()
self.bmm_threshold = None
self.stack_conf, self.stack_pred = (), ()
self.stack_conf_all, self.stack_ident_all = (), ()
if self.is_decoder:
self._reset_time_measure()
else: self.deploy_time = None
self.render = config.render_jsds
if self.render:
self.tokenizer = T5Tokenizer.from_pretrained("google-t5/t5-large")
def _reset_time_measure(self):
self.deploy_time = {'time_key_value_gen': [datetime.timedelta(), datetime.timedelta()],
'time_attn': [datetime.timedelta(), datetime.timedelta()],
'time_ffn': datetime.timedelta(),
'time_confidence': datetime.timedelta(),
'time_exit_key_value_gen': [datetime.timedelta(), datetime.timedelta()],
'time_exit_attn': [datetime.timedelta(), datetime.timedelta()],
'time_exit_ffn': datetime.timedelta(),
'time_parallel_key_value_gen': [datetime.timedelta(), datetime.timedelta()],
'time_parallel_attn': [datetime.timedelta(), datetime.timedelta()],
'time_parallel_ffn': datetime.timedelta(),
'time_others': datetime.timedelta(),}
def parallel_gen_token(
self,
hidden_states,
attention_mask=None,
position_bias=None,
encoder_hidden_states=None,
encoder_extended_attention_mask=None,
encoder_decoder_position_bias=None,
head_mask=None,
cross_attn_head_mask=None,
past_key_values=None,
present_key_value_states=None,
use_cache=None,
output_attentions=None,
layer_idx=None,
):
r"""
if pask_key_values is not defined, it implies that all previous tokens have skipped Deep decoder.
Because all sequences share key_value of cross-attn layer,
we need to generate key_value of cross-attn layer only once for <start> token.
else:
key_values of cross-attn are already stored in 'past_key_values'.
Then, generate the next token in a non-autoregressive manner.
if copy_skipped_hidden_states is True,
copy previous skipped hidden_states for Deep decoder blocks.
else:
attention calculate for stack_hidden_states as well.
thus, we can utilize them in RollBack policy.
"""
if not self.config.copy_skipped_hidden_states:
hidden_states = torch.cat(self.stack_hidden_states + (hidden_states,), dim=1)
# reset and re-calculate based on the length of hidden_states
extended_attention_mask, position_bias = None, None
else:
self.stack_hidden_states = torch.cat(self.stack_hidden_states, dim=1)
extended_attention_mask = attention_mask
previous_hidden_states = []
for j in range(layer_idx, len(self.block)):
past_key_value = past_key_values[j]
if past_key_value is None:
# if pask_key_values is not defined, it implies that all previous tokens have skipped Deep decoder
# need to generate key_value of cross-attn layer only once for <start> token
past_key_value = self.block[j].gen_cross_attn_key_value(
hidden_states, # dummy
attention_mask=extended_attention_mask,
position_bias=position_bias,
encoder_hidden_states=encoder_hidden_states,
encoder_attention_mask=encoder_extended_attention_mask,
encoder_decoder_position_bias=encoder_decoder_position_bias,
layer_head_mask=head_mask[j],
cross_attn_layer_head_mask=cross_attn_head_mask[j],
past_key_value=None,
use_cache=use_cache,
output_attentions=output_attentions,
)
self.deploy_time['time_parallel_key_value_gen'][1] += self.block[j].key_value_gen_time
if self.config.use_synchronize: torch.cuda.synchronize()
start = datetime.datetime.now()
if extended_attention_mask is None or position_bias is None:
real_seq_length = hidden_states.shape[1]
if past_key_value[0] is not None: real_seq_length += past_key_value[0].shape[2]
key_length = real_seq_length
if self.config.parallel_causal_mask and extended_attention_mask is None:
attention_mask = torch.ones(hidden_states.shape[0], real_seq_length, device=hidden_states.device)
extended_attention_mask = self.get_extended_attention_mask(attention_mask, torch.Size([hidden_states.shape[0], hidden_states.shape[1]]))
if position_bias is None:
position_bias = self.block[0].layer[0].SelfAttention.compute_bias(real_seq_length, key_length, device=hidden_states.device)
# if key and values are already calculated
# we want only the last query position bias
if past_key_value is not None:
position_bias = position_bias[:, :, -hidden_states.size(1):, :]
if extended_attention_mask is not None:
position_bias = position_bias + extended_attention_mask # (batch_size, n_heads, seq_length, key_length)
if self.config.use_synchronize: torch.cuda.synchronize()
self.deploy_time['time_others'] += (datetime.datetime.now() - start)
layer_outputs = self.block[j]( #### Block forward pass, should be outputting the logits indeed no?
hidden_states,
attention_mask=extended_attention_mask,
position_bias=position_bias,
encoder_hidden_states=encoder_hidden_states,
encoder_attention_mask=encoder_extended_attention_mask,
encoder_decoder_position_bias=encoder_decoder_position_bias,
layer_head_mask=head_mask[j],
cross_attn_layer_head_mask=cross_attn_head_mask[j],
past_key_value=past_key_value,
use_cache=use_cache,
output_attentions=output_attentions,
skip_mask=False,
parallel_mask=True,
stack_hidden_states=self.stack_hidden_states if self.config.copy_skipped_hidden_states else None,
)
for idx, t in enumerate(self.block[j].key_value_gen_time): self.deploy_time['time_parallel_key_value_gen'][idx] += t
for idx, t in enumerate(self.block[j].attn_time): self.deploy_time['time_parallel_attn'][idx] += t
self.deploy_time['time_parallel_ffn'] += self.block[j].ffn_time
if self.config.use_synchronize: torch.cuda.synchronize()
start = datetime.datetime.now()
# layer_outputs is a tuple with:
# hidden-states, key-value-states, (self-attention position bias), (self-attention weights), (cross-attention position bias), (cross-attention weights)
if use_cache is False:
layer_outputs = layer_outputs[:1] + (None,) + layer_outputs[1:]
hidden_states, present_key_value_state = layer_outputs[:2]
position_bias = layer_outputs[2]
if self.is_decoder and encoder_hidden_states is not None:
encoder_decoder_position_bias = layer_outputs[4 if output_attentions else 3]
# append next layer key value states
if use_cache:
present_key_value_states = present_key_value_states + [present_key_value_state,]
if self.config.use_synchronize: torch.cuda.synchronize()
self.deploy_time['time_others'] += (datetime.datetime.now() - start)
if self.config.use_synchronize: torch.cuda.synchronize()
start = datetime.datetime.now()
self.stack_hidden_states = ()
if self.config.use_synchronize: torch.cuda.synchronize()
self.deploy_time['time_others'] += (datetime.datetime.now() - start)
return hidden_states, present_key_value_states
def func_inverse(self, i, k1, k2, num_layers): # this is the function for doing smoothed pruning
return max(k2, int(k1 / (1 + (k1 - k2) / k2 * i / num_layers)))
def forward(
self,
input_ids=None,
attention_mask=None,
encoder_hidden_states=None,
encoder_attention_mask=None,
inputs_embeds=None,
head_mask=None,
cross_attn_head_mask=None,
past_key_values=None,
use_cache=None,
output_attentions=None,
output_hidden_states=None,
return_dict=None,
lm_head=None,
cm_head=None,
):
r"""
We have implemented the following inference strategy:
1) Normal framework: Forward all transformer layers.
2) Static framework: Only forward the pre-defined number of early layers.
3) Early-Exit framework: Each token can exit the forward path if confidence is higher than threshold.
4) Shallow-Deep framework:
While a few early layers are defined as 'Shallow' decoder, the entire network including Shallow is defined as 'Deep' decoder.
Each token can skip the Deep decoder path if confidence at Shallow decoder is higher than threshold.
"""
if self.config.use_synchronize: torch.cuda.synchronize()
start = datetime.datetime.now()
use_cache = use_cache if use_cache is not None else self.config.use_cache
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
output_hidden_states = (
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
)
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
if input_ids is not None and inputs_embeds is not None:
err_msg_prefix = "decoder_" if self.is_decoder else ""
raise ValueError(
f"You cannot specify both {err_msg_prefix}input_ids and {err_msg_prefix}inputs_embeds at the same time"
)
elif input_ids is not None:
input_shape = input_ids.size()
input_ids = input_ids.view(-1, input_shape[-1])
elif inputs_embeds is not None:
input_shape = inputs_embeds.size()[:-1]
else:
err_msg_prefix = "decoder_" if self.is_decoder else ""
raise ValueError(f"You have to specify either {err_msg_prefix}input_ids or {err_msg_prefix}inputs_embeds")
if inputs_embeds is None:
assert self.embed_tokens is not None, "You have to initialize the model with valid token embeddings"
inputs_embeds = self.embed_tokens(input_ids)
batch_size, seq_length = input_shape
# required mask seq length can be calculated via length of past
mask_seq_length = past_key_values[0][0].shape[2] + seq_length if past_key_values is not None else seq_length
if use_cache is True:
assert self.is_decoder, f"`use_cache` can only be set to `True` if {self} is used as a decoder"
if attention_mask is None:
attention_mask = torch.ones(batch_size, mask_seq_length, device=inputs_embeds.device)
if self.is_decoder and encoder_attention_mask is None and encoder_hidden_states is not None:
encoder_seq_length = encoder_hidden_states.shape[1]
encoder_attention_mask = torch.ones(
batch_size, encoder_seq_length, device=inputs_embeds.device, dtype=torch.long
)
# initialize past_key_values with `None` if past does not exist
if past_key_values is None:
past_key_values = [None] * len(self.block)
self.stack_hidden_states = ()
self.stack_conf, self.stack_pred = (), ()
# We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
# ourselves in which case we just need to make it broadcastable to all heads.
extended_attention_mask = self.get_extended_attention_mask(attention_mask, input_shape)
# If a 2D or 3D attention mask is provided for the cross-attention
# we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
if self.is_decoder and encoder_hidden_states is not None:
encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size()
encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
if encoder_attention_mask is None:
encoder_attention_mask = torch.ones(encoder_hidden_shape, device=inputs_embeds.device)
encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask)
else:
encoder_extended_attention_mask = None
if self.gradient_checkpointing and self.training:
if use_cache:
logger.warning_once(
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
)
use_cache = False
# Prepare head mask if needed
head_mask = self.get_head_mask(head_mask, self.config.num_layers)
cross_attn_head_mask = self.get_head_mask(cross_attn_head_mask, self.config.num_layers)
present_key_value_states = [] if use_cache else None
all_hidden_states = None
all_attentions = None
all_cross_attentions = None
position_bias = None
encoder_decoder_position_bias = None
hidden_states = self.dropout(inputs_embeds)
if self.config.use_synchronize: torch.cuda.synchronize()
if self.is_decoder: self.deploy_time['time_others'] += (datetime.datetime.now() - start)
skip_mask = False # False: forward, and True: skip
self.shallow2deep = False # False: skip, and True: forward
self.lm_logits = None # to prevent calculating logits twice
prev_probits = {}
prev_confidences = {}
if self.is_decoder and self.config.plotting_logits:
previous_logits = []
for i, layer_module in enumerate(self.block):
if self.is_decoder and self.config.plotting_logits:
_hidden_states = self.dropout(self.final_layer_norm(hidden_states))
_hidden_states = (_hidden_states * (self.config.d_model ** -0.5)) if self.config.tie_word_embeddings else _hidden_states
lm_logits = lm_head(_hidden_states)
previous_logits.append(lm_logits)
# Static framework
if self.is_decoder and self.config.static_exit_layer is not None:
if i == self.config.static_exit_layer: break
layer_head_mask = head_mask[i]
cross_attn_layer_head_mask = cross_attn_head_mask[i]
# check that tokens are generated once in a time
auto_reg = True if hidden_states.shape[1] == 1 else False
if self.is_decoder and auto_reg and i == 0: self.block_op[i] += 1
if self.is_decoder and auto_reg and i > 0:
# Shallow-Deep framework
if self.use_shallow_deep and i == self.shallow_exit_layer:
if self.config.use_synchronize: torch.cuda.synchronize()
start = datetime.datetime.now()
_hidden_states = self.dropout(self.final_layer_norm(hidden_states))
lm_logits = lm_head(_hidden_states) if not self.config.tie_word_embeddings \
else lm_head(_hidden_states * (self.config.d_model ** -0.5))
skip_mask, conf = get_skip_mask(
lm_logits,
_hidden_states,
cm_head,
config=self.config,
adapt_threshold=self.bmm_threshold,
return_conf=True,
)
self.stack_conf = self.stack_conf + (conf,)
self.stack_pred = self.stack_pred + (lm_logits,)
if not skip_mask: self.block_op[i] += 1
if self.config.use_synchronize: torch.cuda.synchronize()
self.deploy_time['time_confidence'] += (datetime.datetime.now() - start)
# if skip Deep decoder, store hidden_states at self.shallow_exit_layer
if skip_mask:
if self.config.use_synchronize: torch.cuda.synchronize()
start = datetime.datetime.now()
self.lm_logits = lm_logits
if self.config.parallel_gen_token:
if use_cache:
for j in range(i, len(self.block)):
present_key_value_states = present_key_value_states + [past_key_values[j],]
self.stack_hidden_states = self.stack_hidden_states + (hidden_states,)
if self.config.use_synchronize: torch.cuda.synchronize()
if self.is_decoder: self.deploy_time['time_others'] += (datetime.datetime.now() - start)
break
if not skip_mask:
self.shallow2deep = True
# if self.config.parallel_gen_token:
if self.config.parallel_gen_token and len(self.stack_hidden_states):
self.parallel_tokens_shallow += len(self.stack_hidden_states)
self.parallel_tokens_deep += 1
# in Shallow-Deep decoder, generate the next token in a non-autoregressive manner
hidden_states, present_key_value_states = self.parallel_gen_token(
hidden_states,
attention_mask=extended_attention_mask,
position_bias=position_bias,
encoder_hidden_states=encoder_hidden_states,
encoder_extended_attention_mask=encoder_extended_attention_mask,
encoder_decoder_position_bias=encoder_decoder_position_bias,
head_mask=head_mask,
cross_attn_head_mask=cross_attn_head_mask,
past_key_values=past_key_values,
present_key_value_states=present_key_value_states,
use_cache=use_cache,
output_attentions=output_attentions,
layer_idx=self.shallow_exit_layer,
)
# Adaptive Threshold Estimator
if self.config.use_adapt_threshold:
# Calibration Set Update
self.lm_logits = self.lm_head(self.dropout(self.final_layer_norm(hidden_states)))
deep_pred = self.lm_logits.argmax(-1)
shallow_pred = torch.cat(self.stack_pred).argmax(-1).view(-1)
self.stack_conf_all += self.stack_conf
self.stack_ident_all += ((deep_pred.view(-1) == shallow_pred.view(-1)).long().cpu().numpy(),)
self.stack_conf, self.stack_pred = (), ()
break
# Early-Exit framework
elif self.use_early_exit and not skip_mask:
if (self.exit_min_layer is not None and i < self.exit_min_layer):
if self.config.use_synchronize: torch.cuda.synchronize()
# start = datetime.datetime.now()
_hidden_states = self.dropout(self.final_layer_norm(hidden_states))
lm_logits = lm_head(_hidden_states) if not self.config.tie_word_embeddings \
else lm_head(_hidden_states * (self.config.d_model ** -0.5))
probits = lm_logits.softmax(dim=-1).squeeze() #torch.softmax(lm_logits, dim=-1) + squeezing
prev_probits[i] = probits
self.block_op[i] += 1
else:
if self.config.use_synchronize: torch.cuda.synchronize()
start = datetime.datetime.now()
_hidden_states = self.dropout(self.final_layer_norm(hidden_states))
# SHRINKING VOCAB PART:
if not self.config.type_vocab_reduct: # If we are not using any vocab reduction
a = _hidden_states * (self.config.d_model ** -0.5)
lm_logits = lm_head(_hidden_states) if not self.config.tie_word_embeddings \
else lm_head(a)
if self.config.count_flops:
self.flop_counter += (self.config.d_model**2)* self.config.vocab_size * 1 # Seq length is always one