This repository was archived by the owner on Jul 7, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3.6k
/
Copy pathcommon_attention.py
6237 lines (5365 loc) · 241 KB
/
common_attention.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# coding=utf-8
# Copyright 2021 The Tensor2Tensor 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.
"""Utilities for attention."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import functools
import itertools
import math
import operator
import numpy as np
from six.moves import range # pylint: disable=redefined-builtin
from six.moves import zip # pylint: disable=redefined-builtin
from tensor2tensor.layers import area_attention
from tensor2tensor.layers import common_layers
from tensor2tensor.utils import contrib
from tensor2tensor.utils import expert_utils
import tensorflow.compat.v1 as tf
import tensorflow_probability as tfp
# pylint: disable=g-direct-tensorflow-import
from tensorflow.python.framework import function
from tensorflow.python.ops import inplace_ops
# pylint: enable=g-direct-tensorflow-import
# TODO(lukaszkaiser): remove this function when not needed any more.
def layers():
return common_layers.layers()
def large_compatible_negative(tensor_type):
"""Large negative number as Tensor.
This function is necessary because the standard value for epsilon
in this module (-1e9) cannot be represented using tf.float16
Args:
tensor_type: a dtype to determine the type.
Returns:
a large negative number.
"""
if tensor_type == tf.float16:
return tf.float16.min
return -1e9
def mixed_precision_is_enabled(
activation_dtype=None, weight_dtype=None, hparams=None):
assert not (hparams and (activation_dtype or weight_dtype)), (
"Provide only hparams or activation_dtype and weight_dtype")
if (hparams and hasattr(hparams, "activation_dtype") and
hasattr(hparams, "weight_dtype")):
activation_dtype = hparams.activation_dtype
weight_dtype = hparams.weight_dtype
return activation_dtype == tf.float16 and weight_dtype == tf.float32
def maybe_upcast(logits,
activation_dtype=None, weight_dtype=None, hparams=None):
if mixed_precision_is_enabled(activation_dtype, weight_dtype, hparams):
return tf.cast(logits, tf.float32)
return logits
# Struct containing the sequences ids and order on a batch (are send to the
# expert to allow them to compute the bias mask)
BatchInfo = collections.namedtuple("BatchInfo", "coordinates, order")
_expert_count = 0
def get_standardized_layers(hparams, dp=None):
"""Get the common attention and feed-forward layers.
The returned layer functions will have the following signature:
y, extra_loss = fct(x)
extra_loss is set to 0.0 if the layer doesn't have extra loss.
If dp is provided, the layers will be distributed within the devices.
If moe wants to be used, both dp and model need to be set.
Args:
hparams (tf.HParams): the model hparameters
dp (expert_utils.Parallelism): A data parallelism object. If not given,
the dp calls are simply ignored.
Returns:
dict[str:fct]: A dictionary containing the standardized functions
"""
def partial(fct, *args, **kwargs):
"""Same as functools.partial but with functools.wraps."""
return functools.wraps(fct)(functools.partial(fct, *args, **kwargs))
def register_layer(
fct_in,
default_args=None,
default_kwargs=None,
use_dp=True,
recompute_grad=False,
):
"""Turn a function into its standardized version.
Args:
fct_in (fct): The function to register
default_args (list): The default parameters to add to the function.
default_kwargs (dict): The default parameters to add to the function.
Those arguments can be overwritten when calling the function.
use_dp (bool): Wrap the function call within a dataparallelism object if
dp is available. Some layers (like MOE) must be called without dp.
recompute_grad (bool): If True, recompute the function during the
backward pass to save memory
Returns:
fct: the standardized layer function.
"""
# The kwargs given when calling the function overwrite the default ones
fct_in = partial(fct_in, *(default_args or []), **(default_kwargs or {}))
@functools.wraps(fct_in)
def decorator(x, *args, **kwargs):
"""Call the layer function."""
fct = fct_in # For closure. Could use nonlocal with Python 3
# Eventually create the memory optimized version of the function
if recompute_grad:
fct = partial(fct, **kwargs) # recompute_grad only accept args
fct = common_layers.recompute_grad(fct)
kwargs = {}
# Eventually use dp (if given and not MoE)
if use_dp and dp is not None:
y = dp(fct, x, *args, **kwargs)
else:
y = fct(x, *args, **kwargs)
# Eventually capture the extra loss
extra_loss = 0.0
if isinstance(y, tuple):
y, extra_loss = y
return y, extra_loss
return decorator
total_key_depth = hparams.attention_key_channels or hparams.hidden_size
total_value_depth = hparams.attention_value_channels or hparams.hidden_size
# Attention layers:
# === Multi-head full attention layer ===
multihead_attention_fn = register_layer(
multihead_attention,
default_kwargs=dict(
memory_antecedent=None, # Self-attention by default
bias=None,
total_key_depth=total_key_depth,
total_value_depth=total_value_depth,
output_depth=hparams.hidden_size,
num_heads=hparams.num_heads,
dropout_rate=hparams.attention_dropout,
))
# === Memory efficient full-attention layer ===
# Save memory by not storing the activations and
# recomputing them during the backward pass
memeff_attention_base_fn = register_layer(
multihead_attention,
default_kwargs=dict(
total_key_depth=total_key_depth,
total_value_depth=total_value_depth,
output_depth=hparams.hidden_size,
num_heads=hparams.num_heads,
dropout_rate=hparams.attention_dropout,
),
recompute_grad=True,
)
def memeff_attention_fn(*args, **kwargs):
"""Modify args/kwargs for compatibility with recompute_grad."""
kwargs = kwargs.copy()
assert len(args) == 1
x = args[0]
memory_antecedent = kwargs.pop("memory_antecedent", x) # Same as x if None
if kwargs.get("bias", None) is not None: # Case where bias has been set
args = (x, memory_antecedent, kwargs.pop("bias"))
else:
# Otherwise, only 2 args. This is necessary as recompute_grad does not
# support None values.
args = (x, memory_antecedent)
return memeff_attention_base_fn(*args, **kwargs)
# === Local attention (unmasked) layer ===
# Reuse same parameters as multihead_attention
# Don't mask the future
local_attention_fn = partial(
multihead_attention_fn,
block_length=hparams.attention_loc_block_length,
block_width=hparams.attention_loc_block_width,
attention_type="local_unmasked",
)
# === Local attention (masked) layer ===
# Reuse same parameters as multihead_attention
# Only works for self attention. Always mask the future.
local_attention_masked_fn = partial(
multihead_attention_fn,
block_length=hparams.attention_loc_block_length,
attention_type="local_mask_right",
)
# === Masked memory-compressed multihead self attention layer ===
# Only works for self attention. Always mask the future.
compressed_attention_masked_fn = register_layer(
multihead_self_attention_reduced,
default_kwargs=dict(
factor=hparams.attention_red_factor,
nonlinearity=hparams.attention_red_nonlinearity,
reduction_type=hparams.attention_red_type,
multihead_params=dict(
total_key_depth=total_key_depth,
total_value_depth=total_value_depth,
num_heads=hparams.num_heads,
dropout_rate=hparams.attention_dropout,
),
),
)
# === Unmasked memory-compressed multihead self attention layer ===
# Only works for self attention. Never mask the future. Bias never added
compressed_attention_fn = partial(
compressed_attention_masked_fn,
add_mask=False,
)
# Feed-forwards layers:
# === FC layer ===
conv_hidden_relu = register_layer(
common_layers.conv_hidden_relu,
default_kwargs=dict(
hidden_size=hparams.filter_size,
output_size=hparams.hidden_size,
dropout=hparams.relu_dropout,
),
)
# === Separable convolution layer ===
# No mask applied
sep_conv_relu = partial(
conv_hidden_relu,
padding="SAME",
# Parameters copied from the transformer model, could add hparams
kernel_size=(3, 1),
second_kernel_size=(31, 1),
)
# === Separable convolution layer (masked version) ===
# Mask the future
sep_conv_relu_masked = partial(
sep_conv_relu,
padding="LEFT", # Mask future for decoder
)
# Define all available layers
cur_layers = dict(
# Attention layers:
a=multihead_attention_fn, # Multihead full attention
loc=local_attention_fn, # Local attention
locm=local_attention_masked_fn, # Local attention (masked)
red=compressed_attention_fn, # Memory-compressed attention
redm=compressed_attention_masked_fn, # Memory-compressed att (masked)
mem=memeff_attention_fn, # Memory efficient
# Feed-forward layers:
fc=conv_hidden_relu, # Fully connected
sep=sep_conv_relu, # Separable convolution (unmasked)
sepm=sep_conv_relu_masked, # Separable convolution (masked)
)
return cur_layers
def add_standard_attention_hparams(hparams):
"""Adds the hparams used by get_standardized_layers."""
# All hyperparameters ending in "dropout" are automatically set to 0.0
# when not in training mode.
# hparams used and which should have been defined outside (in
# common_hparams):
# Global flags
# hparams.mode
# hparams.hidden_size
# Pre-post processing flags
# hparams.layer_preprocess_sequence
# hparams.layer_postprocess_sequence
# hparams.layer_prepostprocess_dropout
# hparams.norm_type
# hparams.norm_epsilon
# Mixture-of-Expert flags
# hparams.moe_hidden_sizes
# hparams.moe_num_experts
# hparams.moe_k
# hparams.moe_loss_coef
# Attention layers flags
hparams.add_hparam("num_heads", 8)
hparams.add_hparam("attention_key_channels", 0)
hparams.add_hparam("attention_value_channels", 0)
hparams.add_hparam("attention_dropout", 0.0)
# Attention: Local
hparams.add_hparam("attention_loc_block_length", 256)
# Attention: Local (unmasked only): How much to look left.
hparams.add_hparam("attention_loc_block_width", 128)
# Attention: Memory-compressed
hparams.add_hparam("attention_red_factor", 3)
hparams.add_hparam("attention_red_type", "conv")
hparams.add_hparam("attention_red_nonlinearity", "none")
# Fully connected layers flags
# To be more consistent, should use filter_size to also control the MOE
# size if moe_hidden_sizes not set.
hparams.add_hparam("filter_size", 2048)
hparams.add_hparam("relu_dropout", 0.0)
return hparams
def encoder_decoder_attention_loss(expected_attention_logits,
actual_attentions,
loss_type="kl_divergence",
loss_multiplier=1.0):
"""Computes encdec attention loss between expected and actual attentions.
Args:
expected_attention_logits: Tensor storing the expected encoder-decoder
attention logits with shape [batch_size, target_length, input_length].
actual_attentions: Dictionary with actual attention logits for different
attention types and hidden layers.
loss_type: type of the loss function.
loss_multiplier: multiplier for the attention loss.
Returns:
KL_divergence loss between the actual and expected attention logits.
"""
def combine_attentions(attention_list):
"""Combine different layer attentions and then average over layers/heads."""
# Stack all hidden layer attention tensors to get a tensor with shape
# [num_hidden_layers, batch_size, num_heads, target_length, input_length].
attentions = tf.stack(attention_list)
# Reduce mean across all layers (axis=0) and all heads (axis=2) to get a
# tensor with shape [batch_size, target_length, input_length].
return tf.reduce_mean(attentions, [0, 2])
def kl_divergence_loss(expected_logits, actual_logits):
p = tfp.distributions.Categorical(logits=expected_logits)
q = tfp.distributions.Categorical(logits=actual_logits)
return tfp.distributions.kl_divergence(p, q)
def mse_loss(expected_logits, actual_weights):
expected_weights = tf.nn.softmax(expected_logits)
return tf.losses.mean_squared_error(expected_weights, actual_weights)
# For each hidden layer, we have attention-logit and attention-weight tensors
# with shape [batch_size, num_heads, target_length, input_length].
loss = 0.0
if loss_type == "mse":
actual_encdec_attention_weights = [
t for layer_key, t in actual_attentions.items()
if "encdec_attention" in layer_key and not layer_key.endswith("/logits")
]
actual_attention_weights = combine_attentions(
actual_encdec_attention_weights)
loss = mse_loss(expected_attention_logits, actual_attention_weights)
else:
actual_encdec_attention_logits = [
t for layer_key, t in actual_attentions.items()
if "encdec_attention" in layer_key and layer_key.endswith("/logits")
]
actual_attention_logits = combine_attentions(actual_encdec_attention_logits)
loss = kl_divergence_loss(expected_attention_logits,
actual_attention_logits)
return loss * loss_multiplier
@expert_utils.add_name_scope()
def get_timing_signal_1d(length,
channels,
min_timescale=1.0,
max_timescale=1.0e4,
start_index=0):
"""Gets a bunch of sinusoids of different frequencies.
Each channel of the input Tensor is incremented by a sinusoid of a different
frequency and phase.
This allows attention to learn to use absolute and relative positions.
Timing signals should be added to some precursors of both the query and the
memory inputs to attention.
The use of relative position is possible because sin(x+y) and cos(x+y) can be
expressed in terms of y, sin(x) and cos(x).
In particular, we use a geometric sequence of timescales starting with
min_timescale and ending with max_timescale. The number of different
timescales is equal to channels / 2. For each timescale, we
generate the two sinusoidal signals sin(timestep/timescale) and
cos(timestep/timescale). All of these sinusoids are concatenated in
the channels dimension.
Args:
length: scalar, length of timing signal sequence.
channels: scalar, size of timing embeddings to create. The number of
different timescales is equal to channels / 2.
min_timescale: a float
max_timescale: a float
start_index: index of first position
Returns:
a Tensor of timing signals [1, length, channels]
"""
position = tf.to_float(tf.range(length) + start_index)
num_timescales = channels // 2
log_timescale_increment = (
math.log(float(max_timescale) / float(min_timescale)) /
tf.maximum(tf.to_float(num_timescales) - 1, 1))
inv_timescales = min_timescale * tf.exp(
tf.to_float(tf.range(num_timescales)) * -log_timescale_increment)
scaled_time = tf.expand_dims(position, 1) * tf.expand_dims(inv_timescales, 0)
# Please note that this slightly differs from the published paper.
# See a discussion here: https://github.com/tensorflow/tensor2tensor/pull/177
signal = tf.concat([tf.sin(scaled_time), tf.cos(scaled_time)], axis=1)
signal = tf.pad(signal, [[0, 0], [0, tf.mod(channels, 2)]])
signal = tf.reshape(signal, [1, length, channels])
return signal
@expert_utils.add_name_scope()
def add_timing_signal_1d(x,
min_timescale=1.0,
max_timescale=1.0e4,
start_index=0):
"""Adds a bunch of sinusoids of different frequencies to a Tensor.
Each channel of the input Tensor is incremented by a sinusoid of a different
frequency and phase.
This allows attention to learn to use absolute and relative positions.
Timing signals should be added to some precursors of both the query and the
memory inputs to attention.
The use of relative position is possible because sin(x+y) and cos(x+y) can be
expressed in terms of y, sin(x) and cos(x).
In particular, we use a geometric sequence of timescales starting with
min_timescale and ending with max_timescale. The number of different
timescales is equal to channels / 2. For each timescale, we
generate the two sinusoidal signals sin(timestep/timescale) and
cos(timestep/timescale). All of these sinusoids are concatenated in
the channels dimension.
Args:
x: a Tensor with shape [batch, length, channels]
min_timescale: a float
max_timescale: a float
start_index: index of first position
Returns:
a Tensor the same shape as x.
"""
length = common_layers.shape_list(x)[1]
channels = common_layers.shape_list(x)[2]
signal = get_timing_signal_1d(length, channels, min_timescale, max_timescale,
start_index)
return x + common_layers.cast_like(signal, x)
@expert_utils.add_name_scope()
def get_layer_timing_signal_learned_1d(channels, layer, num_layers):
"""get n-dimensional embedding as the layer (vertical) timing signal.
Adds embeddings to represent the position of the layer in the tower.
Args:
channels: dimension of the timing signal
layer: layer num
num_layers: total number of layers
Returns:
a Tensor of timing signals [1, 1, channels].
"""
shape = [num_layers, 1, 1, channels]
layer_embedding = (
tf.get_variable(
"layer_embedding",
shape,
initializer=tf.random_normal_initializer(0, channels**-0.5)) *
(channels**0.5))
return layer_embedding[layer, :, :, :]
@expert_utils.add_name_scope()
def add_layer_timing_signal_learned_1d(x, layer, num_layers):
"""Add n-dimensional embedding as the layer (vertical) timing signal.
Adds embeddings to represent the position of the layer in the tower.
Args:
x: a tensor with shape [batch, length, depth]
layer: layer num
num_layers: total number of layers
Returns:
a Tensor the same shape as x.
"""
channels = common_layers.shape_list(x)[-1]
signal = get_layer_timing_signal_learned_1d(channels, layer, num_layers)
x += signal
return x
@expert_utils.add_name_scope()
def get_layer_timing_signal_sinusoid_1d(channels, layer, num_layers):
"""Add sinusoids of different frequencies as layer (vertical) timing signal.
Args:
channels: dimension of the timing signal
layer: layer num
num_layers: total number of layers
Returns:
a Tensor of timing signals [1, 1, channels].
"""
signal = get_timing_signal_1d(num_layers, channels)
layer_signal = tf.expand_dims(signal[:, layer, :], axis=1)
return layer_signal
@expert_utils.add_name_scope()
def add_layer_timing_signal_sinusoid_1d(x, layer, num_layers):
"""Add sinusoids of different frequencies as layer (vertical) timing signal.
Args:
x: a Tensor with shape [batch, length, channels]
layer: layer num
num_layers: total number of layers
Returns:
a Tensor the same shape as x.
"""
channels = common_layers.shape_list(x)[-1]
signal = get_layer_timing_signal_sinusoid_1d(channels, layer, num_layers)
return x + signal
@expert_utils.add_name_scope()
def add_timing_signals_given_positions(x,
positions,
min_timescale=1.0,
max_timescale=1.0e4):
"""Adds sinusoids of diff frequencies to a Tensor, with timing positions given.
Args:
x: a Tensor with shape [batch, length, channels]
positions: a list of positions, each of which can either be a Tensor of
shape [batch, length] or None for a default of (0..length]
min_timescale: a float
max_timescale: a float
Returns:
a Tensor the same shape as x.
"""
shape = common_layers.shape_list(x)
batch = shape[0]
length = shape[1]
channels = shape[2]
num_dims = len(positions)
num_timescales = channels // (num_dims * 2)
log_timescale_increment = (
math.log(float(max_timescale) / float(min_timescale)) /
(tf.to_float(num_timescales) - 1))
inv_timescales = min_timescale * tf.exp(
tf.to_float(tf.range(num_timescales)) * -log_timescale_increment)
for dim, position in enumerate(positions):
if position is None:
# Create a [batch, length] Tensor of incrementing positions 0..length-1.
position = tf.tile(
tf.transpose(tf.expand_dims(tf.range(0, length), axis=1)), [batch, 1])
scaled_time = (
tf.expand_dims(tf.to_float(position), 2) *
tf.expand_dims(tf.expand_dims(inv_timescales, 0), 0))
signal = tf.concat([tf.sin(scaled_time), tf.cos(scaled_time)], axis=2)
prepad = dim * 2 * num_timescales
postpad = channels - (dim + 1) * 2 * num_timescales
signal = tf.pad(signal, [[0, 0], [0, 0], [prepad, postpad]])
signal = common_layers.cast_like(signal, x)
x += signal
return x
@expert_utils.add_name_scope()
def add_timing_signals_from_features(x,
features,
position_features,
min_timescale=1.0,
max_timescale=1.0e4):
"""Adds timing signals from features named in `position_features`.
Args:
x: a Tensor with shape [batch, length, channels]
features: a features dictionary
position_features: a comma-delimited string where each item is either a
feature key or the empty string (which denotes a default position tensor
of [0..length])
min_timescale: a float
max_timescale: a float
Returns:
a Tensor the same shape as x.
"""
return add_timing_signals_given_positions(x, [
features.get(position_feature)
for position_feature in position_features.split(",")
], min_timescale, max_timescale)
@expert_utils.add_name_scope()
def add_timing_signal_1d_given_position(x,
position,
min_timescale=1.0,
max_timescale=1.0e4):
"""Adds sinusoids of diff frequencies to a Tensor, with timing position given.
Args:
x: a Tensor with shape [batch, length, channels]
position: a Tensor with shape [batch, length]
min_timescale: a float
max_timescale: a float
Returns:
a Tensor the same shape as x.
"""
channels = common_layers.shape_list(x)[2]
num_timescales = channels // 2
log_timescale_increment = (
math.log(float(max_timescale) / float(min_timescale)) /
(tf.to_float(num_timescales) - 1))
inv_timescales = min_timescale * tf.exp(
tf.to_float(tf.range(num_timescales)) * -log_timescale_increment)
scaled_time = (
tf.expand_dims(tf.to_float(position), 2) * tf.expand_dims(
tf.expand_dims(inv_timescales, 0), 0))
signal = tf.concat([tf.sin(scaled_time), tf.cos(scaled_time)], axis=2)
signal = tf.pad(signal, [[0, 0], [0, 0], [0, tf.mod(channels, 2)]])
signal = common_layers.cast_like(signal, x)
return x + signal
@expert_utils.add_name_scope()
def add_timing_signal_nd(x, min_timescale=1.0, max_timescale=1.0e4):
"""Adds a bunch of sinusoids of different frequencies to a Tensor.
Each channel of the input Tensor is incremented by a sinusoid of a different
frequency and phase in one of the positional dimensions.
This allows attention to learn to use absolute and relative positions.
Timing signals should be added to some precursors of both the query and the
memory inputs to attention.
The use of relative position is possible because sin(a+b) and cos(a+b) can be
expressed in terms of b, sin(a) and cos(a).
x is a Tensor with n "positional" dimensions, e.g. one dimension for a
sequence or two dimensions for an image
We use a geometric sequence of timescales starting with
min_timescale and ending with max_timescale. The number of different
timescales is equal to channels // (n * 2). For each timescale, we
generate the two sinusoidal signals sin(timestep/timescale) and
cos(timestep/timescale). All of these sinusoids are concatenated in
the channels dimension.
Args:
x: a Tensor with shape [batch, d1 ... dn, channels]
min_timescale: a float
max_timescale: a float
Returns:
a Tensor the same shape as x.
"""
num_dims = len(x.get_shape().as_list()) - 2
channels = common_layers.shape_list(x)[-1]
num_timescales = channels // (num_dims * 2)
log_timescale_increment = (
math.log(float(max_timescale) / float(min_timescale)) /
(tf.to_float(num_timescales) - 1))
inv_timescales = min_timescale * tf.exp(
tf.to_float(tf.range(num_timescales)) * -log_timescale_increment)
for dim in range(num_dims):
length = common_layers.shape_list(x)[dim + 1]
position = tf.to_float(tf.range(length))
scaled_time = tf.expand_dims(position, 1) * tf.expand_dims(
inv_timescales, 0)
signal = tf.concat([tf.sin(scaled_time), tf.cos(scaled_time)], axis=1)
prepad = dim * 2 * num_timescales
postpad = channels - (dim + 1) * 2 * num_timescales
signal = tf.pad(signal, [[0, 0], [prepad, postpad]])
for _ in range(1 + dim):
signal = tf.expand_dims(signal, 0)
for _ in range(num_dims - 1 - dim):
signal = tf.expand_dims(signal, -2)
x += signal
return x
def add_positional_embedding(x, max_length, name=None, positions=None):
"""Adds positional embedding.
Args:
x: Tensor with shape [batch, length, depth].
max_length: int representing static maximum size of any dimension.
name: str representing name of the embedding tf.Variable.
positions: Tensor with shape [batch, length].
Returns:
Tensor of same shape as x.
"""
with tf.name_scope("add_positional_embedding"):
_, length, depth = common_layers.shape_list(x)
var = tf.cast(tf.get_variable(name, [max_length, depth]), x.dtype)
if positions is None:
pad_length = tf.maximum(0, length - max_length)
sliced = tf.cond(
tf.less(length, max_length),
lambda: tf.slice(var, [0, 0], [length, -1]),
lambda: tf.pad(var, [[0, pad_length], [0, 0]]))
return x + tf.expand_dims(sliced, 0)
else:
return x + tf.gather(var, tf.to_int32(positions))
def add_positional_embedding_nd(x, max_length, name=None):
"""Adds n-dimensional positional embedding.
The embeddings add to all positional dimensions of the tensor.
Args:
x: Tensor with shape [batch, p1 ... pn, depth]. It has n positional
dimensions, i.e., 1 for text, 2 for images, 3 for video, etc.
max_length: int representing static maximum size of any dimension.
name: str representing name of the embedding tf.Variable.
Returns:
Tensor of same shape as x.
"""
with tf.name_scope("add_positional_embedding_nd"):
x_shape = common_layers.shape_list(x)
num_dims = len(x_shape) - 2
depth = x_shape[-1]
base_shape = [1] * (num_dims + 1) + [depth]
base_start = [0] * (num_dims + 2)
base_size = [-1] + [1] * num_dims + [depth]
for i in range(num_dims):
shape = base_shape[:]
start = base_start[:]
size = base_size[:]
shape[i + 1] = max_length
size[i + 1] = x_shape[i + 1]
var = tf.get_variable(
name + "_%d" % i,
shape,
initializer=tf.random_normal_initializer(0, depth**-0.5))
var = var * depth**0.5
x += tf.slice(var, start, size)
return x
def make_edge_vectors(adjacency_matrix, num_edge_types, depth, name=None):
"""Gets edge vectors for the edge types in the adjacency matrix.
Args:
adjacency_matrix: A [batch, num_nodes, num_nodes] tensor of ints.
num_edge_types: Number of different edge types
depth: Number of channels
name: a string
Returns:
A [batch, num_nodes, num_nodes, depth] vector of tensors
"""
with tf.variable_scope(name, default_name="edge_vectors"):
att_adj_vectors_shape = [num_edge_types, depth]
adjacency_matrix_shape = common_layers.shape_list(adjacency_matrix)
adj_vectors = (
tf.get_variable(
"adj_vectors",
att_adj_vectors_shape,
initializer=tf.random_normal_initializer(0, depth**-0.5)) *
(depth**0.5))
# Avoiding gathers so that it works on TPUs
# adjacency_matrix_one_hot has shape
# [batch, num_nodes, num_nodes, num_edge_types]
adjacency_matrix_one_hot = tf.one_hot(adjacency_matrix, num_edge_types)
att_adj_vectors = tf.matmul(
tf.reshape(tf.to_float(adjacency_matrix_one_hot), [-1, num_edge_types]),
adj_vectors)
return tf.reshape(att_adj_vectors,
[adjacency_matrix_shape[0], adjacency_matrix_shape[1],
adjacency_matrix_shape[2], depth])
class LshGating(object):
"""Class to split key/queries into separate buckets."""
def __init__(self, depth, nb_hyperplanes, nb_replicat=1, trainable=False):
"""Construct the gating function parameters.
Compute the gates for a single head.
Args:
depth (int): Dimension of the key/queries to dispatch
nb_hyperplanes (int): Nb of vectors use to split the space. Will determine
the number of buckets (2^nb_hyperplanes - 1).
nb_replicat (int): Redundancy to avoid the edge cases (to be in one bucket
the input should be in a majority)
trainable (bool): If True, a balance loss is added to force the hyperplane
to divide the key/query space evenly
"""
self.depth = depth
self.nb_hyperplanes = nb_hyperplanes
self.nb_buckets = 2**nb_hyperplanes
self.nb_replicat = nb_replicat # Unused for now
self.trainable = trainable # Unused for now
self.dispatchers = {}
assert self.nb_replicat == 1 # For now
with tf.variable_scope("lsh_gating"):
# Vectors defining the hyperplanes
self.t_vectors = tf.get_variable(
"vector",
shape=(self.depth, self.nb_hyperplanes * self.nb_replicat),
dtype=tf.float32,
trainable=self.trainable,
)
# Projection vector from the bit space to similarity score space
self.t_group = tf.constant(
[self._idx_to_bits(i) for i in range(self.nb_buckets)],
dtype=tf.float32,
name="group")
def _idx_to_bits(self, i):
"""Convert an group index to its bit representation."""
bits = bin(i)[2:].zfill(self.nb_hyperplanes) # Pad the bits str with 0
return [-1.0 if b == "0" else 1.0 for b in bits]
@expert_utils.add_name_scope("lsh_gating")
def get_gates(self, x):
"""Return the bucket id of the given tensor.
Args:
x (tf.Tensor): float32 of shape [length, depth]
Returns:
tf.Tensor: One-hot vector int64 of shape [heads, length, nb_buckets]
containing the id of the bucket
"""
# The balance loss don't propagate to the rest of the network
x = tf.stop_gradient(x)
# [length, depth] * [depth, nb_vectors * replicat]
x = tf.matmul(x, self.t_vectors)
# [length, nb_vector * replicat]
x = tf.sign(x) # Get on which side of the hyperplane the keys are.
# x = tf.reshape(x, [-1, nb_replicat, nb_vector])
# [length, replicat, nb_vector] * [nb_vector, 2^nb_vector - 1]
x = tf.matmul(x, self.t_group, transpose_b=True) / self.nb_hyperplanes
# We get a similarity score for each of the group between [-1, 1]
# [length, (replicat,) 2^nb_vector - 1]
# Do an argmax to get the most likely group for each replicat
x = tf.argmax(x, axis=-1)
# [length(, replicat)]
# One-hot for compatibility with the sparse dispatcher
x = tf.one_hot(x, self.nb_buckets)
# TODO(epot): Use a loss to force an even distribution
return x
@expert_utils.add_name_scope()
def embedding_to_padding(emb):
"""Calculates the padding mask based on which embeddings are all zero.
We have hacked symbol_modality to return all-zero embeddings for padding.
Args:
emb: a Tensor with shape [..., depth].
Returns:
a float Tensor with shape [...]. Each element is 1 if its corresponding
embedding vector is all zero, and is 0 otherwise.
"""
emb_sum = tf.reduce_sum(tf.abs(emb), axis=-1)
return tf.to_float(tf.equal(emb_sum, 0.0))
@expert_utils.add_name_scope()
def padding_to_length(padding):
"""Calculate the length of mask based on padding.
Args:
padding: a Tensor with shape [..., length].
Returns:
a Tensor with shape [...].
"""
non_padding = 1.0 - padding
return tf.to_int32(tf.reduce_sum(non_padding, axis=-1))
@expert_utils.add_name_scope()
def attention_bias_local(length, max_backward, max_forward):
"""Create an bias tensor to be added to attention logits.
A position may attend to positions at most max_distance from it,
forward and backwards.
This does not actually save any computation.
Args:
length: int
max_backward: int, maximum distance backward to attend. Negative values
indicate unlimited.
max_forward: int, maximum distance forward to attend. Negative values
indicate unlimited.
Returns:
a `Tensor` with shape [1, 1, length, length].
"""
band = common_layers.ones_matrix_band_part(
length,
length,
max_backward,
max_forward,
out_shape=[1, 1, length, length])
return -1e9 * (1.0 - band)
@expert_utils.add_name_scope()
def attention_bias_lower_triangle(length):
"""Create an bias tensor to be added to attention logits.
Allows a query to attend to all positions up to and including its own.
Args:
length: a Scalar.
Returns:
a `Tensor` with shape [1, 1, length, length].
"""
return attention_bias_local(length, -1, 0)
@expert_utils.add_name_scope()
def attention_bias_same_segment(query_segment_id, memory_segment_id):
"""Create an bias tensor to be added to attention logits.
Positions with the same segment_ids can see each other.
Args:
query_segment_id: a float `Tensor` with shape [batch, query_length].
memory_segment_id: a float `Tensor` with shape [batch, memory_length].
Returns: