/
sparsity.py
1733 lines (1486 loc) · 71.2 KB
/
sparsity.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 2024 The Trax 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 used for experiments with sparsity."""
import functools
import math
import random as pyrandom
import numpy as np
from trax import fastmath
from trax import layers as tl
from trax.fastmath import numpy as jnp
from trax.fastmath import random
from trax.layers import base
from trax.layers import core
from trax.layers import initializers as init
from trax.layers import reversible
from trax.layers.assert_shape import assert_shape
# We use mixed CamelCase and snake_case names in this file.
# pylint: disable=invalid-name
@assert_shape('...->...')
class ReversibleReshapePermute(reversible.ReversibleLayer):
"""Simple and fast, reversible, random-looking permutation layer.
This layer permutates the last dimension (usually the embedding dimension)
with simple reshapes. It uses the same permutation for every embedding, and
permutation never changes.
The layer works only when the last dimension is a power of 2. The
permutation is not truly random, as it just uses reshapes to get a fast
random-looking permutation. It has, however, a permutation cycle length
of just log2(dimension_size).
"""
def forward(self, x):
shape = x.shape
x = x.reshape(shape[:-1]+(-1, self._get_multiplier(x)))
t_x = jnp.einsum('...ab->...ba', x) # transpose
return t_x.reshape(shape)
def reverse(self, x, weights=(), state=(), new_state=(), rng=None):
del state, new_state, rng
shape = x.shape
x = x.reshape(shape[:-1]+(self._get_multiplier(x), -1))
t_x = jnp.einsum('...ab->...ba', x) # transpose
return t_x.reshape(shape)
def _get_multiplier(self, x):
"""Return a size of the new dimension for reshaping.
We want to split the last dimension into two using approximately equal
dimensions, we could split a dimension of size 512 into 16 * 32.
However, not all numbers will work equally well, because we have a different
cycle length for permutations for different numbers. For example, for
dimension size 1024 and multiplier 32 we would get the same permutation
already after applying permutation twice (cycle length is 2), but with
multiplier 8 we would get the same permutation after appling permutation 10
times (cycle length is 10).
For powers of two the cycle length is limited by log2(dimension_size).
This function returns the biggest multiplier smaller than
sqrt(dimension_size) that keeps the longest possible cycle lenght of the
permutation.
Args:
x: The input tensor.
Returns:
An appropriate multiplier for the permutation reshape.
"""
last_dim = x.shape[-1]
def big_relatively_prime(n):
# The longest possible cycle is achieved iff log2(multiplier) and
# log2(dimension_size) are relatively prime. We choose the biggest such
# number smaller than sqrt(dimension_size).
for i in range(n//2, 0, -1):
if n%i != 0:
return i
return 1
max_cycle_len = int(math.log(last_dim, 2))
assert 2 ** max_cycle_len == last_dim
return 2 ** big_relatively_prime(max_cycle_len)
@assert_shape('...->...')
class ReversibleRandomPermute(reversible.ReversibleLayer):
"""Reversible, random permutation layer.
This layer permutates the last dimension (usually the embedding dimension)
by indexing and slicing. It uses the same random permutation for every
embedding, and this permutation never changes.
"""
def forward(self, x):
permutation, _ = self._get_permutation_and_reverse_permutation(x)
return x[..., permutation]
def reverse(self, x, weights=(), state=(), new_state=(), rng=None):
_, rev_permutation = self._get_permutation_and_reverse_permutation(x)
return x[..., rev_permutation]
def _get_permutation_and_reverse_permutation(self, x):
# TODO(jaszczur): random seed should be stored in state.
# Currently there is no way of doing it reliably.
last_dim = x.shape[-1]
permutation = list(range(last_dim))
rand = pyrandom.Random(42)
rand.shuffle(permutation)
rev_permutation = [permutation.index(i) for i in range(last_dim)]
return permutation, rev_permutation
@assert_shape('...a->...bc')
def SplitLastAxis(num_splits):
return tl.Fn(f'SplitLastAxis_{num_splits}',
lambda x: jnp.reshape(x, tuple(x.shape)[:-1] + (num_splits, -1)))
@assert_shape('...ab->...c')
def MergeLastTwoAxes():
return tl.Fn('MergeLastTwoAxes',
lambda x: jnp.reshape(x, tuple(x.shape)[:-2] + (-1,)))
@assert_shape('...a->...b')
def LocallyConnectedDense(n_modules, n_units, kernel_size=1,
kernel_initializer=init.GlorotUniformInitializer(),
bias_initializer=init.RandomNormalInitializer(1e-6),
use_bias=True):
"""Layer using LocallyConnected1d for approximation of Dense layer.
The layer splits the last axis of a tensor into `n_modules`, then runs
LocallyConnected1d (grouped convolution) on all those modules, and
concatenates their results. It is essentially a locally-sensitive
approximation of Dense layer, with number of parameters smaller by the factor
of `n_modules / kernel_size`.
Args:
n_modules: Indicates how many modules (pixels) should be input and output
split into for processing.
n_units: how many outputs (filters) should each module generate.
kernel_size: The size of the kernel to be used.
kernel_initializer: Function that creates a matrix of (random) initial
connection weights `W` for the layer.
bias_initializer: Function that creates a vector of (random) initial
bias weights `b` for the layer.
use_bias: If `True`, compute an affine map `y = Wx + b`; else compute
a linear map `y = Wx`.
Returns:
LocallyConnectedDense base.Layer.
"""
if n_modules == 1:
return tl.Dense(n_units, kernel_initializer=kernel_initializer,
bias_initializer=bias_initializer, use_bias=use_bias)
return tl.Serial(
tl.SplitLastAxis(n_modules),
tl.LocallyConnected1d(
n_units, kernel_size, kernel_initializer=kernel_initializer,
bias_initializer=bias_initializer, use_bias=use_bias, padding='WRAP'),
tl.MergeLastTwoAxes())
@assert_shape('bld->bld')
def ModularCausalAttention(d_feature, n_heads=1, sparsity=None, dropout=0.0,
max_inference_length=2048,
kernel_size=1, mode='train'):
"""Returns a layer that maps activations to activations, with causal masking.
Like `CausalAttention`, this layer type represents one pass of multi-head
self-attention with causal masking rather than padding-based masking. However,
it uses LocallyConnectedDense instead of Dense layer for computing Q/K/V.
Args:
d_feature: Depth/dimensionality of feature embedding.
n_heads: Number of attention heads.
sparsity: Number of modules used in LocallyConnectedDense.
dropout: Probababilistic rate for internal dropout applied to attention
activations (based on query-key pairs) before dotting them with values.
max_inference_length: maximum length for inference.
kernel_size: Kernel size used in LocallyConnectedDense.
mode: One of `'train'`, `'eval'`, or `'predict'`.
"""
n_modules = n_heads if sparsity is None else sparsity
@assert_shape('...a->...b')
def ProcessingLayer():
assert d_feature % n_modules == 0
return LocallyConnectedDense(n_modules, d_feature // n_modules,
kernel_size=kernel_size)
return tl.ConfigurableAttention(
ProcessingLayer(), ProcessingLayer(), ProcessingLayer(),
ProcessingLayer(), n_heads=n_heads,
qkv_attention_layer=tl.DotProductCausalAttention(
dropout=dropout, max_inference_length=max_inference_length,
mode=mode))
class _RememberPad(base.Layer):
"""Layer which remembers last N elements in predict mode."""
def __init__(self, n_items_to_remember, mode):
"""Returns a layer which remembers last N elements in predict mode.
For predict mode, the layer remembers last N elements and pads with them.
For other modes, it pads with zeros. The layer pads/remembers elements from
the second axis.
Args:
n_items_to_remember: Number of items to remember/pad with.
mode: One of `'train'`, `'eval'`, or `'predict'`.
"""
super().__init__(name='_RememberPad')
self._n_items_to_remember = n_items_to_remember
self._mode = mode
self._portal_mask = self.monkey_patched_mask() # pylint: disable=assignment-from-none
def monkey_patched_mask(self):
# This is necessary for Terraformer model. See comments there.
# The mask will only be used in Terraformer in predict mode.
return None
def forward(self, x):
if self._n_items_to_remember == 0:
return x
if self._mode == 'predict':
x = jnp.concatenate([self.state[0], x], axis=1)
if self._portal_mask is not None and 'init' in self.state[1]:
# TODO(jaszczur): In predict mode with monkey-patched mask, we
# currently assume that batch size is 1.
assert x.shape[0] == 1
mask = self._portal_mask.get_value()
count_padding = jnp.sum(mask == 0, dtype=jnp.int32)
self.state = (fastmath.dynamic_slice_in_dim(
x, x.shape[1] - (self._n_items_to_remember + count_padding),
self._n_items_to_remember, axis=1), {'forward': ()})
else:
self.state = (x[:, -self._n_items_to_remember:, ...], {'forward': ()})
else:
pad_widths = [[0, 0] for _ in range(len(x.shape))]
pad_widths[1][0] = self._n_items_to_remember
x = jnp.pad(x, pad_width=pad_widths, mode='constant')
return x
def init_weights_and_state(self, input_signature):
"""Initializes this layer's weights."""
if isinstance(input_signature, (list, tuple)):
input_signature = input_signature[0]
self.weights = ()
if self._mode == 'predict':
shape = list(input_signature.shape)
shape[1] = self._n_items_to_remember
self.state = (jnp.zeros(shape, dtype=jnp.float32), {'init': ()})
else:
self.state = ()
@assert_shape('...a->...b')
def LocallyConvDense(n_modules, n_units, mode, kernel_size=1,
length_kernel_size=1):
"""Layer using local convolutions for approximation of Dense layer.
The layer splits the last axis of a tensor into `n_modules`, then runs
a convolution on all those modules, and concatenates their results.
It is similar to LocallyConnectedDense above, but shares weights.
Args:
n_modules: Indicates how many modules (pixels) should be input and output
split into for processing.
n_units: how many outputs (filters) should each module generate.
mode: One of `'train'`, `'eval'`, or `'predict'`.
kernel_size: The size of the kernel to be used.
length_kernel_size: If > 1, also do causal convolution on the previous axis,
which is often the sentence length in sequence models.
Returns:
LocallyConvDense base.Layer.
"""
if n_modules == 1:
return tl.Dense(n_units)
if kernel_size % 2 != 1:
raise ValueError('Currently we only handle odd kernel sizes.')
half = (kernel_size - 1) // 2
pad_widths = [[0, 0], [0, 0], [half, half], [0, 0]]
return tl.Serial(
tl.SplitLastAxis(n_modules),
tl.Fn('Pad', lambda x: jnp.pad(x, pad_width=pad_widths, mode='constant')),
_RememberPad(length_kernel_size-1, mode=mode),
tl.Conv(n_units, kernel_size=(length_kernel_size, kernel_size)),
tl.MergeLastTwoAxes()
)
@assert_shape('bld->bld')
def ConvCausalAttention(d_feature, n_heads=1, sparsity=None, dropout=0.0,
max_inference_length=2048,
kernel_size=1, mode='train'):
"""Returns a layer that maps activations to activations, with causal masking.
Like `CausalAttention`, this layer type represents one pass of multi-head
self-attention with causal masking rather than padding-based masking. However,
it uses LocallyConvDense instead of Dense layer for computing Q/K/V.
Args:
d_feature: Depth/dimensionality of feature embedding.
n_heads: Number of attention heads.
sparsity: Number of modules used in LocallyConvDense.
dropout: Probababilistic rate for internal dropout applied to attention
activations (based on query-key pairs) before dotting them with values.
max_inference_length: maximum length for inference.
kernel_size: Kernel size used in LocallyConnectedDense.
mode: One of `'train'`, `'eval'`, or `'predict'`.
"""
n_modules = n_heads if sparsity is None else sparsity
@assert_shape('...a->...b')
def ProcessingLayer():
assert d_feature % n_modules == 0
return LocallyConvDense(n_modules, d_feature // n_modules, mode=mode,
kernel_size=kernel_size)
return tl.ConfigurableAttention(
ProcessingLayer(), ProcessingLayer(), ProcessingLayer(),
ProcessingLayer(), n_heads=n_heads,
qkv_attention_layer=tl.DotProductCausalAttention(
dropout=dropout, max_inference_length=max_inference_length,
mode=mode))
@assert_shape('...a->...b')
def LowRankDense(n_units, d_lowrank):
return tl.Serial(
tl.Dense(d_lowrank),
tl.Dense(n_units)
)
@assert_shape('...a->...b')
def EinsumDense(d_input, d_output, use_bias):
"""Returns a reimplementation of Dense layer, using einsum.
While this is an equivalent of a Dense layer, it seems to be faster when used
in decoding if used with bias (see decoding_timing_test.py ).
This layer can be removed when we understand better the reason for the
difference in decoding speed.
Args:
d_input: Dimensionality of the input tensor.
d_output: Dimensionality of the output tensor.
use_bias: Whether to use bias.
"""
layers = [
tl.Weights(init.GlorotUniformInitializer(), [d_output, d_input]),
tl.Fn('EinsumDense',
(lambda kernel, embeds: # pylint: disable=g-long-lambda
jnp.einsum('xd,...d->...x', kernel, embeds)))
]
if use_bias:
layers.extend([
tl.Weights(init.RandomNormalInitializer(1e-6), [d_output]),
tl.Add()
])
return tl.Serial(layers)
def RandomLayer(layer_a, layer_b, prob_a):
"""Runs `layer_a` with probability `prob_a`, otherwise runs `layer_b`."""
condition = tl.Serial(
tl.RandomUniform(),
tl.Fn('SmallerThan', lambda x: x < prob_a)
)
return tl.Cond(condition, layer_a, layer_b)
@assert_shape('...a->...b')
def SparseDenseWithOptions(n_units, d_input=None, sparsity_type=None,
sparsity=0, d_lowrank=None, prob_sparse=None,
mode=None, use_bias=True, use_bfloat16=False):
"""Configurable sparse version of Dense layer."""
if prob_sparse is not None:
if mode is not None and mode != 'train':
# For non-training modes, we want to use a sparse variant.
# This is different than simply prob_sparse being None, as the weights of
# the model are different.
prob_sparse = 1.0
return RandomLayer(
SparseDenseWithOptions(n_units, d_input, sparsity_type, sparsity,
d_lowrank, use_bias=use_bias,
use_bfloat16=use_bfloat16),
tl.Dense(n_units, use_bias=use_bias, use_bfloat16=use_bfloat16),
prob_sparse)
if sparsity_type is None or sparsity_type == 'None' or sparsity == 0:
return tl.Dense(n_units, use_bias=use_bias, use_bfloat16=use_bfloat16)
if sparsity_type == 'mult':
return FactoredDense(sparsity, d_input, n_units, use_bias=use_bias,
use_bfloat16=use_bfloat16)
assert not use_bfloat16 # use_bfloat16 is unsupported for other variants
if sparsity_type == 'lowrank':
assert use_bias # use_bias=False is unsupported
return LowRankDense(n_units, d_lowrank)
if sparsity_type == 'einsum':
return EinsumDense(d_input, n_units, use_bias=use_bias)
if sparsity_type == 'local':
assert use_bias # use_bias = False is unsupported
assert n_units % sparsity == 0
return LocallyConnectedDense(sparsity, n_units/sparsity)
if sparsity_type == 'local3':
assert use_bias # use_bias = False is unsupported
assert n_units % sparsity == 0
return LocallyConnectedDense(sparsity, n_units/sparsity, kernel_size=3)
raise ValueError('Unknown sparsity type: {}'.format(sparsity_type))
@assert_shape('bld->bld')
def LowRankCausalAttention(d_feature, n_heads=1, dropout=0.0,
max_inference_length=2048, lowrank=64,
mode='train'):
"""Returns a layer that maps activations to activations, with causal masking.
Like `CausalAttention`, this layer type represents one pass of multi-head
self-attention with causal masking rather than padding-based masking. However,
it uses low-rank approximation of kernel in Dense layer for computing Q/K/V.
Args:
d_feature: Depth/dimensionality of feature embedding.
n_heads: Number of attention heads.
dropout: Probababilistic rate for internal dropout applied to attention
activations (based on query-key pairs) before dotting them with values.
max_inference_length: maximum length for inference.
lowrank: The rank of low-rank approximation.
mode: One of `'train'`, `'eval'`, or `'predict'`.
"""
return tl.ConfigurableAttention(
LowRankDense(d_feature, lowrank), LowRankDense(d_feature, lowrank),
LowRankDense(d_feature, lowrank), LowRankDense(d_feature, lowrank),
n_heads=n_heads, qkv_attention_layer=tl.DotProductCausalAttention(
dropout=dropout, max_inference_length=max_inference_length,
mode=mode))
@assert_shape('...a->...b')
def FactoredDense(n_modules, d_in, d_out, use_bias=True, use_bfloat16=False):
r"""Returns a Dense-like layer, internally factored to use fewer parameters.
This layer treats an activation vector as if divided into :math:`M`
subvectors (``n_modules`` 'modules'). It uses this factored view to compute
a :py:class:`Dense`-like mapping with high mixing/connectivity, but using
approximately :math:`1/M` the number of weights of a similarly dimensioned
:py:class:`Dense` layer.
More specifically, each activation vector of dimensionality ``n_in`` is
multiplied element-wise (a generalized form of gating) with ``n_modules``
vectors also of dimensionality ``n_in``. The resulting vectors are projected
to the subvector/module dimensionality ``d_out / n_modules`` via a matrix
multiply, and finally reshaped back to a single vector of dimensionality
``d_out``. Optionally, a bias vector of dimensionality ``d_out`` is added at
the end. All the above-mentioned non-input objects -- gating vectors,
projection matrix, and optional bias -- are trainable weights.
Args:
n_modules: Number by which an activation vector is divided into subvectors
(modules) for the factored computation.
d_in: Last/innermost dimension of input array.
d_out: Last/innermost dimension of output array.
use_bias: If True, add bias vectors at the end of the layer; else end the
layer with the matrix multiply.
use_bfloat16: If True, use bfloat16 weights; else use float32 weights.
"""
if d_out % n_modules != 0:
raise ValueError(f'Value d_out ({d_out}) must be a multiple of arg '
f'n_modules ({n_modules}).')
d_module = d_out // n_modules
def GatingVectors():
return tl.Weights(init.RandomNormalInitializer(stddev=0.5),
shape=[n_modules, d_in],
use_bfloat16=use_bfloat16)
def ProjectionMatrix():
return tl.Weights(init.GlorotUniformInitializer(),
shape=[d_in, d_module],
use_bfloat16=use_bfloat16),
def Bias():
return tl.Weights(init.RandomNormalInitializer(1e-6),
shape=[d_out],
use_bfloat16=use_bfloat16),
layers = [
GatingVectors(),
ProjectionMatrix(),
_GateAndProject(),
MergeLastTwoAxes(),
]
if use_bias:
layers += [Bias(), tl.Add()]
return tl.Serial(layers)
def _GateAndProject():
"""Returns a combined gating+projection layer that saves on memory."""
def f(projection, gating, x):
# Args arrive in reverse order because of how they were put on the stack.
# Einsum indices: d (d_in), n (n_modules), m (d_module = d_out/n_modules)
return jnp.einsum('...d,nd,dm->...nm', x, gating, projection)
return tl.Fn('_GateAndProject', f)
@assert_shape('...a->...a')
def MultiplicativeModularSparseDense(sparsity, d_feature):
"""Returns a replacement of Dense layer which uses less parameters.
The layer uses number of modules equal to `sparsity`. It is a combination of
multiplicative dense and locally connected dense layers.
Args:
sparsity: The sparsity of the layer; the output vector is divided into this
number of modules.
d_feature: Dimensionality of input and output tensor.
"""
assert d_feature % sparsity == 0
d_module = d_feature // sparsity
return tl.Serial(
# Weight below is used for per-head preprocessing of an embedding.
tl.Weights(init.RandomNormalInitializer(stddev=0.5),
shape=[sparsity, d_feature]),
# Weight below is a kernel of multiplicative dense, shared across heads.
tl.Weights(init.GlorotUniformInitializer(), [d_feature, d_module]),
# Weight below is a kernel of modular dense.
tl.Weights(functools.partial(init.GlorotUniformInitializer(),
nonreceptive_dims=[0]),
[sparsity, d_module, d_module]),
# To save memory the per-head preprocessing and multiplying by
# kernels is done in a single einsum.
tl.Fn('SparseDenseEinsum',
(lambda kmod, kmult, multiplier, embeds: # pylint: disable=g-long-lambda
jnp.einsum('hxo,dx,hd,...d->...ho', kmod, kmult, multiplier, embeds
))),
MergeLastTwoAxes(),
# Weight below is bias after dense, per-head.
tl.Weights(init.RandomNormalInitializer(1e-6), [d_feature]),
tl.Add(),
)
@assert_shape('bld->bld')
def MultiplicativeCausalAttention(d_feature, n_heads=1, sparsity=None,
dropout=0.0, max_inference_length=2048,
mode='train'):
"""Returns a layer that maps activations to activations, with causal masking.
Like `CausalAttention`, this layer type represents one pass of multi-head
self-attention with causal masking rather than padding-based masking. However,
for computing Q/K/V instead of a Dense layer it multiplies each embedding
dimension by a scalar specific to each dimension and each head; then it
produces Q/K/V by applying the same dense layer to each head. In comparison
to standard dense layer for computing Q/K/V, this layer uses less parameters
while still being able to express many functions, like a permutation.
Args:
d_feature: Depth/dimensionality of feature embedding.
n_heads: Number of attention heads.
sparsity: The sparsity of the layer; usually it should be equal to n_heads.
dropout: Probababilistic rate for internal dropout applied to attention
activations (based on query-key pairs) before dotting them with values.
max_inference_length: maximum length for inference.
mode: One of `'train'`, `'eval'`, or `'predict'`.
"""
sparsity = n_heads if sparsity is None else sparsity
return tl.ConfigurableAttention(
FactoredDense(sparsity, d_feature, d_feature),
FactoredDense(sparsity, d_feature, d_feature),
FactoredDense(sparsity, d_feature, d_feature),
FactoredDense(sparsity, d_feature, d_feature),
n_heads=n_heads, qkv_attention_layer=tl.DotProductCausalAttention(
dropout=dropout, max_inference_length=max_inference_length,
mode=mode))
@assert_shape('bld->bld')
def MultiplicativeModularCausalAttention(
d_feature, n_heads=1, sparsity=None, dropout=0.0, max_inference_length=2048,
mode='train'):
"""Returns a layer that maps activations to activations, with causal masking.
Like `CausalAttention`, this layer type represents one pass of multi-head
self-attention with causal masking rather than padding-based masking. However,
for computing Q/K/V instead of a Dense layer it combines
FactoredDense layer with LocallyConnectedLayer.
Args:
d_feature: Depth/dimensionality of feature embedding.
n_heads: Number of attention heads.
sparsity: The sparsity of the layer; usually it should be equal to n_heads.
dropout: Probababilistic rate for internal dropout applied to attention
activations (based on query-key pairs) before dotting them with values.
max_inference_length: maximum length for inference.
mode: One of `'train'`, `'eval'`, or `'predict'`.
"""
sparsity = n_heads if sparsity is None else sparsity
return tl.ConfigurableAttention(
MultiplicativeModularSparseDense(sparsity, d_feature),
MultiplicativeModularSparseDense(sparsity, d_feature),
MultiplicativeModularSparseDense(sparsity, d_feature),
MultiplicativeModularSparseDense(sparsity, d_feature), n_heads=n_heads,
qkv_attention_layer=tl.DotProductCausalAttention(
dropout=dropout, max_inference_length=max_inference_length,
mode=mode))
@assert_shape('bld->bld')
def MultiplicativeConvCausalAttention(
d_feature, n_heads=1, sparsity=None, length_kernel_size=3, dropout=0.0,
force_no_dropout=False, max_inference_length=2048, share_qk=False,
output_layer_type='none', v_concat_type='none', mode='train'):
"""Returns a layer that maps activations to activations, with causal masking.
Like `CausalAttention`, this layer type represents one pass of multi-head
self-attention with causal masking rather than padding-based masking. However,
for computing Q/K/V instead of a Dense layer it combines
FactoredDense layer with LocallyConvLayer.
Args:
d_feature: Depth/dimensionality of feature embedding.
n_heads: Number of attention heads.
sparsity: The sparsity of the layer; usually it should be equal to n_heads.
length_kernel_size: Size of convolution kernel on the length dimension.
dropout: Probababilistic rate for internal dropout applied to attention
activations (based on query-key pairs) before dotting them with values.
force_no_dropout: If True, force dropout to be 0.0 independent of the above
value; used to override some configurations.
max_inference_length: maximum length for inference.
share_qk: if True, average Q and K embeddings and share for both Q and K.
output_layer_type: Which sparse layers to use for processing output from the
attention mechanism. One of `'none'`, `'mult'`, `'conv'`,
or `'multconv'`.
v_concat_type: What kind of concatenation to use when computing V tensor.
One of `'original'`, `'fixed'`, or `'none'`. `'none'` means using just
output from mutliplicative layer shared by Q, K, V. `'fixed'` means
using output from multiplicative layer concatenated, for each module,
with the layer input. `'original'` means using concatenation without
properly taking modules into account; this method was used in
experiments previously, so it is included for backwards-compatibility.
mode: One of `'train'`, `'eval'`, or `'predict'`.
"""
assert output_layer_type in ['none', 'mult', 'conv', 'multconv']
assert v_concat_type in ['original', 'fixed', 'none']
dropout = 0.0 if force_no_dropout else dropout
sparsity = n_heads if sparsity is None else sparsity
d_module = d_feature // sparsity
output_layers = []
if 'mult' in output_layer_type:
output_layers.append(FactoredDense(
sparsity, d_feature, d_feature))
if 'conv' in output_layer_type:
output_layers.append(LocallyConvDense(
sparsity, d_module, mode=mode, kernel_size=3,
length_kernel_size=length_kernel_size))
if v_concat_type == 'original':
# 'original'` uses concatenation without properly taking modules into
# account; this method was used in experiments previously, so it is included
# for backwards-compatibility.
concat_layers = [tl.Concatenate()] # use permuted and original for v
elif v_concat_type == 'fixed':
# `'fixed'` uses the output from multiplicative layer concatenated, for each
# module, with the layer input. This means that every module in Conv layer
# has access both to parts of embeddings which were used to compute Q/K of
# this particular module, and it ha access to parts of the embedding which
# will be modified by this module.
concat_layers = [
tl.Parallel(
tl.Fn('Reshape1', lambda x: jnp.reshape( # pylint: disable=g-long-lambda
x, (x.shape[0], x.shape[1], sparsity, d_module))),
tl.Fn('Reshape2', lambda x: jnp.reshape( # pylint: disable=g-long-lambda
x, (x.shape[0], x.shape[1], sparsity, d_module)))),
tl.Concatenate(),
tl.Fn('Reshape3',
lambda x: jnp.reshape(x, (x.shape[0], x.shape[1], 2*d_feature))),
]
elif v_concat_type == 'none':
# `'none'` doesn't use concatenation: we throw away the original layer
# input and pass to Conv only output of shared Multiplicative layer.
concat_layers = [tl.Select([0], n_in=2)]
if share_qk:
return tl.Serial(
tl.Select([0, 0]), # pre-qkv, pre-v-for-concat
FactoredDense(sparsity, d_feature, d_feature), # shared q k
tl.Select([0, 0]), # pre-qk, pre-v, pre-v-for-concat
LocallyConvDense(sparsity, d_module, mode=mode, kernel_size=3,
length_kernel_size=length_kernel_size),
tl.SplitIntoHeads(n_heads),
tl.Select([0, 0]), # use for q and k
tl.Parallel(
[],
[],
[concat_layers,
LocallyConvDense(sparsity, d_module, mode=mode, kernel_size=1,
length_kernel_size=length_kernel_size),
tl.SplitIntoHeads(n_heads)],
),
tl.DotProductCausalAttention(
dropout=dropout, max_inference_length=max_inference_length,
mode=mode),
tl.MergeHeads(n_heads),
output_layers,
)
return tl.Serial(
tl.Select([0, 0]), # duplicate activations
FactoredDense(sparsity, d_feature, d_feature), # shared q, k
tl.Select([0, 0, 0]), # use for q, k, v
tl.Parallel(
[LocallyConvDense(sparsity, d_module, mode=mode, kernel_size=3,
length_kernel_size=length_kernel_size),
tl.SplitIntoHeads(n_heads)],
[LocallyConvDense(sparsity, d_module, mode=mode, kernel_size=3,
length_kernel_size=length_kernel_size),
tl.SplitIntoHeads(n_heads)],
[concat_layers,
LocallyConvDense(sparsity, d_module, mode=mode, kernel_size=1,
length_kernel_size=length_kernel_size),
tl.SplitIntoHeads(n_heads)],
),
tl.DotProductCausalAttention(
dropout=dropout, max_inference_length=max_inference_length,
mode=mode),
tl.MergeHeads(n_heads),
output_layers,
)
class FavorAttention(base.Layer):
"""Implements FAVOR+ attention.
Original paper: https://arxiv.org/abs/2006.03555
The layer expects 4 inputs: (Q, K, V, MASK), and returns two outputs:
(RENORMALIZED_ATTENTION, MASK).
Attributes:
d_feature: Dimensionality of feature embedding.
n_heads: Number of attention heads.
n_random_features: Free dimension size for the orthogonal random matrix.
numerical_stabilizer: float, small number used for numerical stability.
use_approximate_softmax: Bool, if True uses approximate softmax, otherwise
Relu.
scale_by_norm: Boolean; whether to scale orthogonal random matrix.
normalize_data: predicate indicating whether data should be normalized.
epsilon: numerical stabilizer.
mode: One of `'train'`, `'eval'`, or `'predict'`.
"""
def __init__(self, d_feature=4, n_heads=1, n_random_features=256,
numerical_stabilizer=0.001,
use_approximate_softmax=False, scale_by_norm=True,
normalize_data=False,
epsilon=0.0001, mode='train'):
super().__init__(n_in=4, n_out=2)
self._d_feature = d_feature
self._n_heads = n_heads
self._n_random_features = n_random_features
self._numerical_stabilizer = numerical_stabilizer
self._mode = mode
self._use_approximate_softmax = use_approximate_softmax
self._normalize_data = normalize_data
self._epsilon = epsilon
if self._use_approximate_softmax:
rng = random.get_prng(0)
self._projection_matrix = self.get_2d_array(
rng=rng, n_rows=self._n_random_features,
n_columns=(self._d_feature // self._n_heads),
scale_by_norm=scale_by_norm,
normalize_data=normalize_data, epsilon=epsilon)
else:
self._projection_matrix = None
def nonnegative_softmax_kernel_feature_creator(self, x, is_query):
"""Constructs nonnegative kernel features for fast softmax attention.
Args:
x: input for which features are computed.
is_query: predicate indicating whether input data corresponds to
queries or keys.
Returns:
Random features for fast softmax attention.
"""
if self._normalize_data:
# We have e^{qk^T/sqrt{d}} = e^{q_norm k_norm^T}, where
# w_norm = w * data_normalizer for w in {q,k}.
data_normalizer = 1.0 / (jnp.sqrt(jnp.sqrt(x.shape[-1])))
else:
data_normalizer = 1.0
ratio = 1.0 / jnp.sqrt(self._projection_matrix.shape[0])
# TODO(wgaj): Double-check... Should there be only one batch dimension...?
data_mod_shape = x.shape[0:1] + self._projection_matrix.shape
data_thick_random_matrix = (jnp.zeros(data_mod_shape) +
self._projection_matrix)
data_dash = jnp.einsum('Bij, Bkj -> Bik',
data_normalizer * x,
data_thick_random_matrix)
diag_data = jnp.square(x)
diag_data = jnp.sum(diag_data, axis=x.ndim - 1)
diag_data = (diag_data / 2.0) * data_normalizer * data_normalizer
diag_data = jnp.expand_dims(diag_data, axis=x.ndim - 1)
last_dims_t = (len(data_dash.shape) - 1,)
attention_dims_t = (1,)
if is_query:
data_dash = ratio * (
jnp.exp(data_dash - diag_data -
jnp.max(data_dash, axis=last_dims_t, keepdims=True)) +
self._epsilon)
else:
data_dash = ratio * (
jnp.exp(data_dash - diag_data - jnp.max(
data_dash, axis=last_dims_t + attention_dims_t, keepdims=True)) +
self._epsilon)
return data_dash
@staticmethod
def get_2d_array(rng, n_rows=256, n_columns=0, scale_by_norm=True,
normalize_data=False, epsilon=0.0001):
"""Generator for approximate softmax orthogonal kernel feature matrix.
Args:
rng: Random number generator.
n_rows: Number of rows.
n_columns: Number of columns.
scale_by_norm: Boolean; whether to scale orthogonal random matrix.
normalize_data: predicate indicating whether data should be normalized.
epsilon: numerical stabilizer.
Returns:
Orthogonal kernel feature matrix.
"""
n_full_blocks = int(n_rows / n_columns)
block_list = []
rng_key = rng
for _ in range(n_full_blocks):
rng, rng_input = random.split(rng)
unstructured_block = random.normal(rng_input, (n_columns, n_columns))
q, _ = jnp.linalg.qr(unstructured_block)
q = jnp.transpose(q)
block_list.append(q)
remaining_rows = n_rows - n_full_blocks * n_columns
if remaining_rows > 0:
rng, rng_input = random.split(rng)
unstructured_block = random.normal(rng_input, (n_columns, n_columns))
q, _ = jnp.linalg.qr(unstructured_block)
q = jnp.transpose(q)
block_list.append(q[0:remaining_rows])
final_matrix = jnp.vstack(block_list)
if scale_by_norm:
multiplier = jnp.linalg.norm(
random.normal(rng_key, (n_rows, n_columns)), axis=1)
else:
multiplier = jnp.sqrt(float(n_columns)) * jnp.ones((n_rows))
return jnp.matmul(jnp.diag(multiplier), final_matrix)
@staticmethod
def bidirectional_numerator(query_prime, key_prime, value):
kvs = jnp.einsum('lbm,lbd->bmd', key_prime, value)
return jnp.einsum('lbm,bmd->lbd', query_prime, kvs)
@staticmethod
def bidirectional_denominator(query_prime, key_prime):
all_ones = jnp.ones([query_prime.shape[0]])
ks_sum = jnp.einsum('lbm,l->bm', key_prime, all_ones)
return jnp.einsum('lbm,bm->lb', query_prime, ks_sum)
@staticmethod
def relu(x):
return jnp.where(x <= 0, jnp.zeros_like(x), x)
def forward(self, inputs):
query, key, value, mask = inputs
if self._use_approximate_softmax:
query_prime = self.nonnegative_softmax_kernel_feature_creator(query, True)
key_prime = self.nonnegative_softmax_kernel_feature_creator(key, False)
else:
query_prime = self.relu(query) + self._numerical_stabilizer
key_prime = self.relu(key) + self._numerical_stabilizer
mask_batch_1_length = jnp.reshape(
mask, [key.shape[0] // self._n_heads, 1, key.shape[1]]).astype(
jnp.float32)
mask_heads = mask_batch_1_length + jnp.zeros((1, self._n_heads, 1))
key_prime *= jnp.reshape(mask_heads, [key.shape[0], key.shape[1], 1])
w = self.bidirectional_numerator(jnp.moveaxis(query_prime, 1, 0),
jnp.moveaxis(key_prime, 1, 0),
jnp.moveaxis(value, 1, 0))
r = self.bidirectional_denominator(jnp.moveaxis(query_prime, 1, 0),
jnp.moveaxis(key_prime, 1, 0))
w = jnp.moveaxis(w, 0, 1)
r = jnp.moveaxis(r, 0, 1)
r = jnp.reciprocal(r)
r = jnp.expand_dims(r, len(r.shape))
renormalized_attention = w * r
return renormalized_attention, mask
def Favor(d_feature, n_heads=1, n_random_features=256, dropout=0.0,
numerical_stabilizer=0.001, use_approximate_softmax=False,
scale_by_norm=0, normalize_data=False, epsilon=0.0001, mode='train'):
"""Returns a layer that maps (activations, mask) to (new_activations, mask).
See the FAVOR paper for details: https://arxiv.org/abs/2006.03555
Args:
d_feature: Depth/dimensionality of feature embedding.
n_heads: Number of attention heads.
n_random_features: Free dimension size for the orthogonal random matrix.
dropout: Probababilistic rate for internal dropout applied to attention
activations (based on query-key pairs) before dotting them with values.
numerical_stabilizer: float, small number used for numerical stability.
use_approximate_softmax: Bool, if True uses approximate softmax, otherwise
Relu.
scale_by_norm: Boolean; whether to scale orthogonal random matrix.
normalize_data: predicate indicating whether data should be normalized.
epsilon: numerical stabilizer.
mode: One of `'train'`, `'eval'`, or `'predict'`.
"""
del dropout # not implemented yet but needed in the API
return tl.ConfigurableAttention(
tl.Dense(d_feature), tl.Dense(d_feature), tl.Dense(d_feature),
tl.Dense(d_feature),
tl.FavorAttention(d_feature, n_heads, n_random_features,
numerical_stabilizer, use_approximate_softmax,
scale_by_norm, normalize_data, epsilon, mode),
n_heads=n_heads)
class CausalFavorAttention(base.Layer):
"""Returns a layer that maps activations to activations, with causal masking.
Like `CausalAttention`, this layer type represents one pass of multi-head
causal attention, but using FAVOR fast attention as in the following paper:
https://arxiv.org/abs/2006.03555
Layer expects three inputs (Q, K, V), and returns one output
RENORMALIZED_ATTENTION.
Attributes:
numerical_stabilizer: float, small number used for numerical stability.
mode: One of `'train'`, `'eval'`, or `'predict'`.
"""
def __init__(self, numerical_stabilizer=0.001, mode='train'):
super().__init__(n_in=3, n_out=1)
self._numerical_stabilizer = numerical_stabilizer
self._mode = mode
def forward(self, inputs):
def favor_numerator_fwd(init_prefix_sum_value,
query_prime, key_prime, value):
def body(p, qkv):
(q, k, v) = qkv
p += jnp.einsum('...m,...d->...md', k, v)
x_slice = jnp.einsum('...m,...md->...d', q, p)
return p, x_slice
p, w = fastmath.scan(body, init_prefix_sum_value,
(query_prime, key_prime, value))
return w, (p, query_prime, key_prime, value)