This repository was archived by the owner on Jan 21, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 256
/
Copy pathtransformer_layers.py
2266 lines (2003 loc) · 89 KB
/
transformer_layers.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 2023 The Mesh TensorFlow Authors.
#
# 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.
"""Layers for the Transformer."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import copy
import functools
import math
import gin
import mesh_tensorflow as mtf
from mesh_tensorflow import layers
from mesh_tensorflow.transformer import attention
from mesh_tensorflow.transformer import transformer
import tensorflow.compat.v1 as tf
@gin.configurable
class DenseReluDense(transformer.TransformerLayer):
"""Two dense layers with ReLU or other activation on hidden layer."""
def __init__(self, hidden_size=4096, dropout_rate=0.0, activation="relu",
use_bias=False):
"""Create a DenseReluDense.
Args:
hidden_size: an integer - size of the hidden layer
dropout_rate: a floating-point number
activation: an activation function or a list of activation functions.
see documentation for mtf.layers.dense_product()
use_bias: a boolean, whether to use bias in the dense layers.
"""
self.hidden_size = hidden_size
self.dropout_rate = dropout_rate
self.activation = activation
self.use_bias = use_bias
def call(self, context, x, losses=None):
"""Call the layer."""
io_channels = x.shape.dims[-1]
hidden_channels = mtf.Dimension("d_ff", self.hidden_size)
h = mtf.layers.dense_product(x,
reduced_dims=x.shape.dims[-1:],
new_dims=hidden_channels,
activation_functions=self.activation,
use_bias=self.use_bias,
variable_dtype=context.variable_dtype,
name="wi",
expert_dims=context.model.ensemble_dims)
if context.train and self.dropout_rate != 0.0:
h = mtf.dropout(h, context.train, keep_prob=1.0 - self.dropout_rate,
noise_shape=h.shape - context.length_dim)
return mtf.layers.dense(h, io_channels,
use_bias=self.use_bias,
activation=None,
variable_dtype=context.variable_dtype,
reduced_dims=h.shape.dims[-1:],
name="wo",
expert_dims=context.model.ensemble_dims)
def attention_params(context,
kv_dim,
num_heads,
num_memory_heads=0,
shared_kv=False,
no_query=False,
combine_dims=True,
keep_query_heads_dims=False,
fold_scaling_into_initializer=True):
"""Attention Parameters for Transformer Layers.
The num_heads argument indicates the number of read-heads.
For the familiar behavior described in "Attention Is All You Need", set
num_memory_heads=0.
If num_memory_heads==1, then there is only a single write-head, and multiple
read-heads. This leads to faster incremental decoding, since the
recurrent state is smaller
If num_memory_heads > 1, then num_memory_heads indicates the number of
write-heads. A fraction of the read-heads read each write-head.
num_memory_heads must divide num_heads. This behavior has not yet been tested.
no query flag is set to true when we do not want to create parameters
for query params (for synthesizer model).
Args:
context: a transformer.Context
kv_dim: a dimension (for key and value channels)
num_heads: an integer
num_memory_heads: an optional integer
shared_kv: a boolean
no_query: a boolean
combine_dims: a boolean
keep_query_heads_dims: a boolean
fold_scaling_into_initializer: a boolean
Returns:
an attention.AttentionParams object
"""
if num_heads == 1:
query_heads_dims = None
memory_heads_dims = None
elif num_memory_heads == 0:
query_heads_dims = [mtf.Dimension("heads", num_heads)]
memory_heads_dims = query_heads_dims
elif num_memory_heads == 1:
query_heads_dims = [mtf.Dimension("heads", num_heads)]
memory_heads_dims = None
else:
if num_heads % num_memory_heads != 0:
raise ValueError("num_memory_heads must divide num_heads")
memory_heads_dims = [mtf.Dimension("heads", num_memory_heads)]
query_heads_dims = memory_heads_dims + [
mtf.Dimension("query_heads", num_heads // num_memory_heads)]
return attention.AttentionParams(
context.mesh,
query_input_dim=context.model.model_dim,
memory_input_dim=context.model.model_dim,
output_dim=context.model.model_dim,
key_dim=kv_dim,
value_dim=kv_dim,
query_heads_dims=query_heads_dims,
memory_heads_dims=memory_heads_dims,
variable_dtype=context.variable_dtype,
shared_kv=shared_kv,
no_query=no_query,
ensemble_dim=context.model.ensemble_dim,
combine_dims=combine_dims,
keep_query_heads_dims=keep_query_heads_dims,
fold_scaling_into_initializer=fold_scaling_into_initializer)
@gin.configurable
class SelfAttention(transformer.TransformerLayer):
"""Multi-head self-attention layer."""
def __init__(self,
num_heads=8,
num_memory_heads=0,
key_value_size=128,
shared_kv=False,
dropout_rate=0.0,
attention_kwargs=None,
relative_attention_type=None,
relative_attention_num_buckets=32,
attention_func=None,
combine_dims=True,
keep_query_heads_dims=False,
fold_scaling_into_initializer=True,
z_loss_coeff=None,
use_hyperprompt=False,
hyperprompt_mtlshare=False,
hyperprompt_length_encoder=None,
hyperprompt_length_decoder=None,
hyperprompt_hidden_dim=None,
hyperprompt_task_num=8):
"""Create a SelfAttention Layer.
Args:
num_heads: an integer
num_memory_heads: an optional integer
key_value_size: an integer
shared_kv: a boolean
dropout_rate: a float
attention_kwargs: a dictionary of kwargs for attention.attention
relative_attention_type: an optional string - one of
(None, "bias", "bias_shared", "contextual")
relative_attention_num_buckets: an integer
attention_func: attention function: None/'hybrid'.
combine_dims: a boolean
keep_query_heads_dims: a boolean
fold_scaling_into_initializer: a boolean
z_loss_coeff: a float, if z_loss_coeff is not None then add an auxiliary
loss to push the attention logits closer to zero. This helps to
stabilize model training.
use_hyperprompt: a boolean, whether to use hypernetwork to enable the info
sharing among task-prompts. Otherwise, MTL-Prompt is enabled if either
hyperprompt_length_encoder or hyperprompt_length_decoder is not None.
hyperprompt_mtlshare: a boolean, whether to share MTL-Prompt project
networks among tasks if MTL-Prompt is activate. Otherwise, each task has
its own project network (MTL-Prompt-Sep).
hyperprompt_length_encoder: an integer, the length of task embeddings
prepended to the keys and values in encoder. If it is None, prompts are
not prepended in the encoder.
hyperprompt_length_decoder: aan integer, the length of task embeddings
prepended to the keys and values in decoder. If it is None, prompts are
not prepended in the decoder.
hyperprompt_hidden_dim: the bottleneck dimension in MLPs to generate
hyper-prompts.
hyperprompt_task_num: an integer, # of tasks in hyperprompt mode.
"""
self.num_heads = num_heads
self.num_memory_heads = num_memory_heads
self.key_value_size = key_value_size
self.shared_kv = shared_kv
self.dropout_rate = dropout_rate
self.attention_kwargs = attention_kwargs or {}
self.relative_attention_type = relative_attention_type
self.relative_attention_num_buckets = relative_attention_num_buckets
self.attention_func = attention_func
self.combine_dims = combine_dims
self.keep_query_heads_dims = keep_query_heads_dims
self.fold_scaling_into_initializer = fold_scaling_into_initializer
self.z_loss_coeff = z_loss_coeff
self.use_hyperprompt = use_hyperprompt
self.hyperprompt_mtlshare = hyperprompt_mtlshare
self.hyperprompt_length_encoder = hyperprompt_length_encoder
self.hyperprompt_length_decoder = hyperprompt_length_decoder
self.hyperprompt_hidden_dim = hyperprompt_hidden_dim
self.hyperprompt_task_num = hyperprompt_task_num
def layer_output_from_attention_output(self, context, attention_output,
losses):
return attention_output
def expected_attention_output_shape(self, x, params):
if self.keep_query_heads_dims:
return mtf.Shape(x.shape[:-1] + params.query_heads_dims + x.shape[-1:])
return x.shape
def attention_kwargs_from_context(self, context):
kwargs = copy.copy(self.attention_kwargs)
kwargs["dropout_rate"] = self.dropout_rate if context.train else 0.0
if "dropout_broadcast_dims" not in kwargs:
kwargs["dropout_broadcast_dims"] = [context.length_dim]
return kwargs
def make_params(self, context):
return attention_params(
context=context,
kv_dim=self.kv_dim,
num_heads=self.num_heads,
num_memory_heads=self.num_memory_heads,
shared_kv=self.shared_kv,
combine_dims=self.combine_dims,
keep_query_heads_dims=self.keep_query_heads_dims,
fold_scaling_into_initializer=self.fold_scaling_into_initializer)
def call(self, context, x, losses=None):
"""Call the layer."""
params = self.make_params(context)
q = params.compute_q(x)
memory_length = self.memory_length(context)
if context.mode == "incremental":
m = x
else:
m = mtf.replace_dimensions(x, context.length_dim, memory_length)
if self.shared_kv:
kv = params.compute_kv(m)
else:
k = params.compute_k(m)
v = params.compute_v(m)
if context.mode == "incremental":
one_hot = mtf.one_hot(
context.position, memory_length, dtype=context.activation_dtype)
inv_one_hot = 1.0 - one_hot
if self.shared_kv:
old_kv, = context.get_states(1)
kv = old_kv * inv_one_hot + kv * one_hot
else:
old_k, old_v = context.get_states(2)
k = old_k * inv_one_hot + k * one_hot
v = old_v * inv_one_hot + v * one_hot
memory_position = mtf.range(context.mesh, memory_length, tf.int32)
else:
memory_position = self.rename_length_to_memory_length(
context.position, context)
if context.mode == "incremental" or context.mode == "first_part":
context.record_new_states([kv] if self.shared_kv else [k, v])
if self.shared_kv:
k = kv
v = kv
# Inject hyper-prompts into k and v, skipped when prompt length is None.
scope_encoder_or_decoder = tf.get_variable_scope().name.split("/")[0]
use_prompt_kv = None
if self.hyperprompt_length_encoder and scope_encoder_or_decoder == "encoder":
k, v, memory_position, memory_length = attention.concat_hyper_prompts_kv(
k,
v,
scope_encoder_or_decoder,
self.use_hyperprompt,
memory_length,
self.hyperprompt_task_num,
self.num_heads,
self.hyperprompt_hidden_dim,
self.kv_dim,
context,
self.hyperprompt_mtlshare,
self.dropout_rate,
prompt_length=self.hyperprompt_length_encoder)
use_prompt_kv = "encoder_prompts"
if self.hyperprompt_length_decoder and scope_encoder_or_decoder == "decoder":
k, v, memory_position, memory_length = attention.concat_hyper_prompts_kv(
k,
v,
scope_encoder_or_decoder,
self.use_hyperprompt,
memory_length,
self.hyperprompt_task_num,
self.num_heads,
self.hyperprompt_hidden_dim,
self.kv_dim,
context,
self.hyperprompt_mtlshare,
self.dropout_rate,
prompt_length=self.hyperprompt_length_decoder)
use_prompt_kv = "decoder_prompts"
o = self.attention_fn(
q,
k,
v,
context=context,
memory_length_dim=memory_length,
key_dim=self.kv_dim,
value_dim=self.kv_dim,
bias=self.compute_bias(
context,
memory_position,
x,
params.query_heads_dims,
q,
use_prompt_kv=use_prompt_kv),
z_loss_coeff=self.z_loss_coeff,
**self.attention_kwargs_from_context(context))
attention_output_shape = self.expected_attention_output_shape(x, params)
attention_output = params.compute_output(
o, output_shape=attention_output_shape)
return self.layer_output_from_attention_output(context, attention_output,
losses)
def compute_bias(self,
context,
memory_position,
x,
heads_dims,
q,
use_prompt_kv=None):
"""Compute attention bias.
Args:
context: a transformer.Context
memory_position: an int32 tensor containing memory_length dimension.
x: a Tensor - the query antecedent - required for relative attention
heads_dims: a list of dimensions
q: a Tensor - the queries - required for contextual relative attention
use_prompt_kv: a string, "encoder_prompts" is to add prompts in encoder
"decoder_prompts" is to add prompt in decoder, which affects biases.
Returns:
a Tensor or None
"""
min_relative_position = self.min_relative_position(context) # pylint: disable=assignment-from-none
max_relative_position = self.max_relative_position(context) # pylint: disable=assignment-from-none
biases = []
relative_position = memory_position - context.position
if use_prompt_kv == "encoder_prompts":
relative_position -= self.hyperprompt_length_encoder
elif use_prompt_kv == "decoder_prompts":
relative_position -= self.hyperprompt_length_decoder
if min_relative_position is not None:
visible = mtf.greater_equal(relative_position, min_relative_position)
biases.append(attention.visibility_mask_to_attention_bias(
visible, context.activation_dtype))
if max_relative_position is not None:
visible = mtf.less_equal(relative_position, max_relative_position)
biases.append(attention.visibility_mask_to_attention_bias(
visible, context.activation_dtype))
if context.read_priority is not None:
if use_prompt_kv == "decoder_prompts":
prompt_length_dim = mtf.Dimension(context.length_dim.name,
self.hyperprompt_length_decoder)
write_priority_memory = mtf.ones(
x.mesh, shape=[prompt_length_dim], dtype=tf.int32) * -1
write_priority = mtf.concat(
[write_priority_memory, context.write_priority],
concat_dim_name=context.length_dim.name)
visible = mtf.greater_equal(
context.read_priority,
mtf.layers.rename_length_to_memory_length(write_priority))
else:
visible = mtf.greater_equal(
context.read_priority,
mtf.layers.rename_length_to_memory_length(context.write_priority))
biases.append(attention.visibility_mask_to_attention_bias(
visible, context.activation_dtype))
sequence_id = None
# Subsequence id should only be set if we are in the decoder and have
# multiple targets per input. This will allow each sub-target to only attend
# to itself.
if isinstance(context.subsequence_id, mtf.Tensor):
sequence_id = context.subsequence_id
elif isinstance(context.sequence_id, mtf.Tensor):
sequence_id = context.sequence_id
if (sequence_id is not None and context.length_dim in sequence_id.shape):
if use_prompt_kv:
if use_prompt_kv == "decoder_prompts":
memory_length = mtf.Dimension(
"memory_length",
context.length_dim.size + self.hyperprompt_length_decoder)
elif use_prompt_kv == "encoder_prompts":
memory_length = mtf.Dimension(
"memory_length",
context.length_dim.size + self.hyperprompt_length_encoder)
memory_sequence_id = mtf.ones(
x.mesh, shape=[x.shape.dims[0], memory_length], dtype=tf.int32)
visible = mtf.equal(sequence_id, memory_sequence_id)
else:
visible = mtf.equal(
sequence_id,
self.rename_length_to_memory_length(sequence_id, context))
biases.append(attention.visibility_mask_to_attention_bias(
visible, context.activation_dtype))
if self.relative_attention_type is not None:
buckets_dim = mtf.Dimension(
"buckets", self.relative_attention_num_buckets)
bidirectional = not context.model.fully_autoregressive
rp_bucket = _relative_position_bucket(
relative_position,
bidirectional=bidirectional,
num_buckets=buckets_dim.size)
if (self.relative_attention_type == "bias" or
self.relative_attention_type == "bias_shared"):
bias_shape = context.model.ensemble_dims + heads_dims + [buckets_dim]
values = None
cache = self.relative_attention_type == "bias_shared"
if cache:
cache_key = ("self_attention_bias",
min_relative_position,
max_relative_position,
tuple(heads_dims))
if cache_key in context.cache:
values = context.cache[cache_key]
if values is None:
values = mtf.get_variable(
context.mesh, "relative_attention_bias",
bias_shape, dtype=context.variable_dtype)
if cache:
context.cache[cache_key] = values
elif self.relative_attention_type == "contextual":
values = layers.dense(
q, reduced_dims=[self.kv_dim],
new_dims=[buckets_dim],
variable_dtype=context.variable_dtype,
name="relative_attention_ak",
use_bias=False,
expert_dims=context.model.ensemble_dims + heads_dims)
else:
raise ValueError("unrecognized relative_attention_type \"%s\"" %
self.relative_attention_type)
biases.append(mtf.gather(values, rp_bucket, buckets_dim))
return mtf.add_n(biases) if biases else None
@property
def kv_dim(self):
return mtf.Dimension("d_kv", self.key_value_size)
def memory_length(self, context):
return mtf.Dimension("memory_length", context.length_dim.size)
def rename_length_to_memory_length(self, x, context):
return mtf.replace_dimensions(
x, context.length_dim, self.memory_length(context))
def min_relative_position(self, context):
return None
def max_relative_position(self, context):
return None
@property
def attention_fn(self):
if self.attention_func == "hybrid":
return attention.hybrid_attention
else:
return attention.attention
@gin.configurable
class ExpertsSelfAttention(SelfAttention):
"""Expert-layers for SelfAttention computations."""
def __init__(self,
num_experts=16,
loss_coef=1e-2,
group_size=1024,
capacity_factor_train=1.25,
capacity_factor_eval=2.0,
moe_gating="switch",
min_expert_capacity=4,
switch_policy_train="input_jitter",
switch_policy_eval="input_jitter",
switch_dropout=0.0,
switch_temperature=1.0,
switch_jitter=1e-2,
ntlb_top_k=4,
hidden_size=3072,
activation="relu",
z_loss=None,
expert_computation="qkv",
**kwargs):
super(ExpertsSelfAttention, self).__init__(**kwargs)
self.expert_computation = expert_computation
self._hparams = mtf.transformer.moe.HParams(
moe_gating=moe_gating,
num_experts=num_experts,
loss_coef=loss_coef,
group_size=group_size,
min_expert_capacity=min_expert_capacity,
capacity_factor_train=capacity_factor_train,
capacity_factor_eval=capacity_factor_eval,
switch_policy_train=switch_policy_train,
switch_policy_eval=switch_policy_eval,
switch_dropout=switch_dropout,
switch_temperature=switch_temperature,
switch_jitter=switch_jitter,
ntlb_top_k=ntlb_top_k,
hidden_size=hidden_size,
activation=activation,
z_loss=z_loss)
def make_params(self, context):
num_heads = self.num_heads
num_memory_heads = self.num_memory_heads
if num_heads == 1:
query_heads_dims = None
memory_heads_dims = None
elif num_memory_heads == 0:
query_heads_dims = [mtf.Dimension("heads", num_heads)]
memory_heads_dims = query_heads_dims
elif num_memory_heads == 1:
query_heads_dims = [mtf.Dimension("heads", num_heads)]
memory_heads_dims = None
else:
if num_heads % num_memory_heads != 0:
raise ValueError("num_memory_heads must divide num_heads")
memory_heads_dims = [mtf.Dimension("heads", num_memory_heads)]
query_heads_dims = memory_heads_dims + [
mtf.Dimension("query_heads", num_heads // num_memory_heads)]
return attention.ExpertsAttentionParams(
context.mesh,
query_input_dim=context.model.model_dim,
memory_input_dim=context.model.model_dim,
output_dim=context.model.model_dim,
key_dim=self.kv_dim,
value_dim=self.kv_dim,
query_heads_dims=query_heads_dims,
memory_heads_dims=memory_heads_dims,
variable_dtype=context.variable_dtype,
shared_kv=self.shared_kv,
no_query=False,
ensemble_dim=context.model.ensemble_dim,
combine_dims=self.combine_dims,
keep_query_heads_dims=self.keep_query_heads_dims,
fold_scaling_into_initializer=self.fold_scaling_into_initializer,
context=context,
experts_hparams=self._hparams,
expert_computation=self.expert_computation)
@gin.configurable
class ExpertsEncDecAttention(ExpertsSelfAttention):
"""Expert-layers for EncDecAttention computations."""
def __init__(self, relative_attention_type=None, **kwargs):
super(ExpertsEncDecAttention, self).__init__(
relative_attention_type=relative_attention_type, **kwargs)
def _get_memory_antecedent(self, context):
return context.encoder_output
def call(self, context, x, losses=None):
"""Call the layer."""
return enc_dec_attention(self, self._get_memory_antecedent(context),
context, x, losses)
@gin.configurable
class Synthesizer(SelfAttention):
"""Multi-head Synthesizer layer https://arxiv.org/abs/2005.00743."""
def __init__(self,
num_heads=8,
num_memory_heads=0,
key_value_size=128,
shared_kv=False,
dropout_rate=0.0,
attention_kwargs=None,
relative_attention_type=None,
relative_attention_num_buckets=32,
attention_func=None,
combine_dims=True,
keep_query_heads_dims=False,
synthesize_mode="random_plus_alpha",
fold_scaling_into_initializer=True,
**kwargs):
"""Create a Synthesizer Layer.
Args:
num_heads: an integer
num_memory_heads: an optional integer
key_value_size: an integer
shared_kv: a boolean
dropout_rate: a float
attention_kwargs: a dictionary of kwargs for attention.attention
relative_attention_type: an optional string - one of
(None, "bias", "bias_shared", "contextual")
relative_attention_num_buckets: an integer
attention_func: attention function: None/'hybrid'.
combine_dims: a boolean
keep_query_heads_dims: a boolean
synthesize_mode: a string to select synthesizer variant
fold_scaling_into_initializer: a boolean
**kwargs: additional constructor params
"""
super(Synthesizer, self).__init__(**kwargs)
self.num_heads = num_heads
self.num_memory_heads = num_memory_heads
self.key_value_size = key_value_size
self.shared_kv = shared_kv
self.dropout_rate = dropout_rate
self.attention_kwargs = attention_kwargs or {}
self.relative_attention_type = relative_attention_type
self.relative_attention_num_buckets = relative_attention_num_buckets
self.attention_func = attention_func
self.combine_dims = combine_dims
self.keep_query_heads_dims = keep_query_heads_dims
self.synthesize_mode = synthesize_mode
self.fold_scaling_into_initializer = fold_scaling_into_initializer
self.no_query = False
if "plus" in self.synthesize_mode:
self.shared_kv = False
self.no_query = False
elif "minus" in self.synthesize_mode:
# We still keep the query as first projection
self.shared_kv = True
self.no_query = False
else:
self.shared_kv = True
self.no_query = True
def make_params(self, context):
return attention_params(
context=context,
kv_dim=self.kv_dim,
num_heads=self.num_heads,
num_memory_heads=self.num_memory_heads,
shared_kv=self.shared_kv,
no_query=self.no_query,
fold_scaling_into_initializer=self.fold_scaling_into_initializer)
def call(self, context, x, losses=None):
"""Call the layer."""
params = self.make_params(context)
memory_length = self.memory_length(context)
if context.mode == "incremental":
m = x
else:
m = mtf.replace_dimensions(x, context.length_dim, memory_length)
if self.shared_kv:
kv = params.compute_kv(m)
else:
k = params.compute_k(m)
v = params.compute_v(m)
if self.no_query:
# we don't use q for some synthesizer modes that don't use QKV at all.
q = x
else:
q = params.compute_q(x)
if self.shared_kv:
k = kv
v = kv
if context.mode == "incremental":
one_hot = mtf.one_hot(
context.position, memory_length, dtype=context.activation_dtype)
inv_one_hot = 1.0 - one_hot
old_k, old_v = context.get_states(2)
k = old_k * inv_one_hot + k * one_hot
v = old_v * inv_one_hot + v * one_hot
memory_position = mtf.range(context.mesh, memory_length, tf.int32)
else:
memory_position = self.rename_length_to_memory_length(
context.position, context)
if context.mode == "incremental" or context.mode == "first_part":
context.record_new_states([k, v])
o = attention.synthetic_attention(q, k, v, memory_length,
self.kv_dim, self.kv_dim,
self.compute_bias(context,
memory_position,
x,
params.query_heads_dims,
q),
synthesize=True,
synthesize_mode=self.synthesize_mode,
context=context,
**self.attention_kwargs_from_context(
context))
attention_output_shape = self.expected_attention_output_shape(x, params)
attention_output = params.compute_output(
o, output_shape=attention_output_shape)
return self.layer_output_from_attention_output(context, attention_output,
losses)
@gin.configurable
def relative_position_spans(context, num_sentinels=gin.REQUIRED):
"""Compute relative positions between inputs and targets.
Used by enc_dec_attention_bias.
Assumes that inputs and targets were generated by a span-filling objective:
The inputs consist of the original text with some spans removed and replaced
by single sentinels.
The targets consist of the dropped spans, each preceded by a single sentinel.
Sentinels are the last tokens in the vocabulary.
e.g.
inputs: A B C <S> F G H <S>
shifted-targets: <BOS> <S> D E <S> I J K
Relative positions are computed by identifying a target token with the
corresponding sentinel in the input and returning the distance between these
two tokens in the input.
Target tokens which precede all sentinels get identified with the beginning of
the input. So if we apply this to a problem with no sentinels, all target
tokens will be indentified with the beginning of the input. We assume this is
the case during incremental decoding, so this code will not work properly to
incrementally decode a problem with sentinels. This may not be an issue,
since the span-filling objective is primarily used for unsupervised
pre-training.
Args:
context: a Context
num_sentinels: an integer. Should have the same value as
SentencePieceVocabulary.extra_ids
Returns:
a Tensor
"""
decoder_id = context.inputs
encoder_id = context.encoder_inputs
decoder_length = context.length_dim
encoder_length = context.encoder_length_dim
mesh = encoder_id.mesh
encoder_pos = mtf.range(mesh, encoder_length, tf.int32)
if decoder_length not in decoder_id.shape.dims:
# we are doing incremental decoding.
# Map the target token to the beginning of the input.
dec_to_enc_pos = 0
else:
vocab_size = context.model.input_vocab_size_unpadded
def sentinel_mask(t):
return mtf.cast(mtf.greater_equal(
t, vocab_size - num_sentinels), tf.int32)
decoder_is_sentinel = sentinel_mask(decoder_id)
encoder_is_sentinel = sentinel_mask(encoder_id)
encoder_segment_id = mtf.cumsum(encoder_is_sentinel, encoder_length)
decoder_segment_id = mtf.cumsum(decoder_is_sentinel, decoder_length)
encoder_sequence_id = context.encoder_sequence_id
decoder_sequence_id = context.sequence_id
if encoder_sequence_id is not None:
# distinguish segments from different sequences
multiplier = max(encoder_length.size, decoder_length.size)
encoder_segment_id += encoder_sequence_id * multiplier
decoder_segment_id += decoder_sequence_id * multiplier
dec_to_enc_pos = mtf.reduce_sum(
mtf.cast(mtf.less(encoder_segment_id, decoder_segment_id), tf.int32),
reduced_dim=encoder_length)
return dec_to_enc_pos - encoder_pos
@gin.configurable
def enc_dec_attention_bias(layer,
context,
heads_dims,
relative_position_fn=relative_position_spans):
"""Compute bias term for encoder-decoder attention.
Args:
layer: a TransformerLayer
context: a Context
heads_dims: a list of Dimension
relative_position_fn: an optional function
Returns:
a Tensor
"""
biases = []
if context.encoder_sequence_id and context.sequence_id:
visible = mtf.equal(context.sequence_id, context.encoder_sequence_id)
biases.append(attention.visibility_mask_to_attention_bias(
visible, context.activation_dtype))
if (layer.relative_attention_type == "bias" or
layer.relative_attention_type == "bias_shared"):
buckets_dim = mtf.Dimension(
"buckets", layer.relative_attention_num_buckets)
bias_shape = context.model.ensemble_dims + heads_dims + [buckets_dim]
values = None
cache = layer.relative_attention_type == "bias_shared"
if cache:
cache_key = ("enc_dec_relative_attention_bias", tuple(heads_dims))
if cache_key in context.cache:
values = context.cache[cache_key]
if values is None:
values = mtf.get_variable(
context.mesh, "enc_dec_relative_attention_bias",
bias_shape, dtype=context.variable_dtype)
if cache:
context.cache[cache_key] = values
rel_pos = relative_position_fn(context)
rp_bucket = _relative_position_bucket(
rel_pos,
bidirectional=True,
num_buckets=buckets_dim.size)
biases.append(mtf.gather(values, rp_bucket, buckets_dim))
elif layer.relative_attention_type is not None:
raise ValueError("unrecognized relative_attention_type \"%s\"" %
layer.relative_attention_type)
return mtf.add_n(biases) if biases else None
@gin.configurable
def enc_dec_attention(self_attention_layer, memory_antecedent, context, x,
losses, attention_fn=attention.attention,
z_loss_coeff=None):
"""Multi-head attention over the encoder outputs."""
memory_input_dim = memory_antecedent.shape[-1]
if memory_input_dim != context.model.model_dim:
raise NotImplementedError(
"TODO(noam): support different model_dim in encoder and decoder.")
params = self_attention_layer.make_params(context)
q = params.compute_q(x)
if context.mode == "incremental":
k, v, memory_length = context.get_constant_state()
else:
m = memory_antecedent
if self_attention_layer.shared_kv:
kv = params.compute_kv(m)
k = kv
v = kv
else:
k = params.compute_k(m)
v = params.compute_v(m)
memory_length, = [d for d in m.shape.dims if d.name == "memory_length"]
if context.mode == "first_part":
context.record_constant_state((k, v, memory_length))
bias = enc_dec_attention_bias(self_attention_layer,
context,
params.query_heads_dims)
a = attention_fn(
q, k, v, memory_length, self_attention_layer.kv_dim,
self_attention_layer.kv_dim, bias,
context=context,
z_loss_coeff=z_loss_coeff,
**self_attention_layer.attention_kwargs_from_context(context))
attention_output_shape = self_attention_layer.expected_attention_output_shape(
x, params)
attention_output = params.compute_output(
a, output_shape=attention_output_shape)
return self_attention_layer.layer_output_from_attention_output(
context, attention_output, losses)
@gin.configurable
class EncDecAttention(SelfAttention):
"""Multi-head attention over encoder output."""
def __init__(self, relative_attention_type=None, **kwargs):
super(EncDecAttention, self).__init__(
relative_attention_type=relative_attention_type, **kwargs)
def _get_memory_antecedent(self, context):
return context.encoder_output
def call(self, context, x, losses=None):
"""Call the layer."""
return enc_dec_attention(self, self._get_memory_antecedent(context),
context, x, losses,
attention_fn=self.attention_fn,
z_loss_coeff=self.z_loss_coeff)
@property
def attention_fn(self):
return attention.attention
@gin.configurable
class TransparentEncDecAttention(EncDecAttention):
"""Transparent multi-head attention over encoder output."""
def __init__(self,
layers_per_encoder_module=gin.REQUIRED,
layers_per_decoder_module=gin.REQUIRED,
encoder_num_modules=gin.REQUIRED,
decoder_num_modules=gin.REQUIRED,
dropout_rate=0.0,
**kwargs):
"""Create a transparent attention EncDec Layer.
Args:
layers_per_encoder_module: positive integer telling how many layer are in
each repeated module in the encoder
layers_per_decoder_module: positive integer telling how many layer are in
each repeated module in the decoder
encoder_num_modules: positive integer of how many repeated modules there
are in the encoder
decoder_num_modules: positive integer of how many repeated modules there
are in the decoder
dropout_rate: positive float, the dropout rate for the matrix relating
encoder outputs to decoder inputs
**kwargs: additional constructor params
"""
super(TransparentEncDecAttention, self).__init__(**kwargs)
self.layers_per_encoder_module = layers_per_encoder_module
self.layers_per_decoder_module = layers_per_decoder_module
self.encoder_num_modules = encoder_num_modules
self.decoder_num_modules = decoder_num_modules
self.dropout_rate = dropout_rate
def _get_memory_antecedent(self, context):
decoder_module_index = context.layer_index // self.layers_per_decoder_module
decoder_inputs = self._get_decoder_inputs(context)
return decoder_inputs[decoder_module_index]
def _get_decoder_inputs(self, context):
"""Computes the inputs to the decoder when using transparent attention.
We must cache on the context in order to ensure that we are not replicating
variables when the layer's call function is called in different tf variable
scopes.
Args:
context: a Context
Returns:
a list containing `self.num_decoder_modules` of tensors with shape
[<batch_dims>, length_dim, output_vocab_dim]
"""
if hasattr(context, "decoder_layers_per_module"):
return context.decoder_layers_per_module
encoder_layer_outputs = [
mtf.layers.rename_length_to_memory_length(output)
for output in context.encoder_layer_outputs
]
layers_per_module = self.layers_per_encoder_module
encoder_module_outputs_dim = mtf.Dimension(
"encoder_module_outputs", size=self.encoder_num_modules + 1)
decoder_module_inputs_dim = mtf.Dimension(
"decoder_module_inputs", size=self.decoder_num_modules)
encoder_module_outputs = mtf.stack(
[encoder_layer_outputs[0]] +
encoder_layer_outputs[layers_per_module::layers_per_module],
dim_name="encoder_module_outputs")
stddev = 1.0
if not mtf.layers.unit_scaling_convention():
stddev *= encoder_module_outputs_dim.size ** -0.5
w = mtf.get_variable(
context.mesh,
"w",
mtf.Shape([encoder_module_outputs_dim, decoder_module_inputs_dim]),
initializer=tf.random_normal_initializer(stddev=stddev),
dtype=context.variable_dtype)
w = mtf.dropout(w, context.train, 1.0 - self.dropout_rate)
s = mtf.softmax(w, reduced_dim=encoder_module_outputs_dim)
z = mtf.layers.us_einsum([s, encoder_module_outputs],
reduced_dims=[encoder_module_outputs_dim])
input_per_decoder = mtf.split(
z,
split_dim=decoder_module_inputs_dim,
num_or_size_splits=decoder_module_inputs_dim.size)
context.decoder_layers_per_module = [
mtf.reshape(inpt, z.shape.dims[1:]) for inpt in input_per_decoder
]
return context.decoder_layers_per_module