sequence-layers 0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. sequence_layers/__init__.py +16 -0
  2. sequence_layers/internal/types.py +521 -0
  3. sequence_layers/jax/__init__.py +29 -0
  4. sequence_layers/jax/attention.py +6124 -0
  5. sequence_layers/jax/combinators.py +1907 -0
  6. sequence_layers/jax/conditioning.py +511 -0
  7. sequence_layers/jax/convolution.py +2103 -0
  8. sequence_layers/jax/dense.py +447 -0
  9. sequence_layers/jax/dsp.py +1686 -0
  10. sequence_layers/jax/examples/gemma3n_audio_encoder.py +358 -0
  11. sequence_layers/jax/export.py +313 -0
  12. sequence_layers/jax/meta.py +54 -0
  13. sequence_layers/jax/normalization.py +889 -0
  14. sequence_layers/jax/pooling.py +925 -0
  15. sequence_layers/jax/position.py +370 -0
  16. sequence_layers/jax/recurrent.py +674 -0
  17. sequence_layers/jax/sharding.py +48 -0
  18. sequence_layers/jax/signal.py +511 -0
  19. sequence_layers/jax/simple.py +2679 -0
  20. sequence_layers/jax/test_utils.py +1343 -0
  21. sequence_layers/jax/time_varying.py +673 -0
  22. sequence_layers/jax/types.py +1537 -0
  23. sequence_layers/jax/typing.py +59 -0
  24. sequence_layers/jax/utils.py +2149 -0
  25. sequence_layers/tensorflow/__init__.py +56 -0
  26. sequence_layers/tensorflow/attention.py +3426 -0
  27. sequence_layers/tensorflow/combinators.py +938 -0
  28. sequence_layers/tensorflow/conditioning.py +644 -0
  29. sequence_layers/tensorflow/convolution.py +1855 -0
  30. sequence_layers/tensorflow/dense.py +285 -0
  31. sequence_layers/tensorflow/dsp.py +740 -0
  32. sequence_layers/tensorflow/examples/bert.py +144 -0
  33. sequence_layers/tensorflow/examples/conformer.py +138 -0
  34. sequence_layers/tensorflow/examples/deep_voice.py +72 -0
  35. sequence_layers/tensorflow/examples/listen_attend_spell.py +102 -0
  36. sequence_layers/tensorflow/examples/mobilenet.py +92 -0
  37. sequence_layers/tensorflow/examples/t5.py +225 -0
  38. sequence_layers/tensorflow/examples/tacotron.py +124 -0
  39. sequence_layers/tensorflow/examples/transformer.py +159 -0
  40. sequence_layers/tensorflow/examples/very_attentive_tacotron.py +1771 -0
  41. sequence_layers/tensorflow/examples/wavernn.py +225 -0
  42. sequence_layers/tensorflow/normalization.py +1127 -0
  43. sequence_layers/tensorflow/pooling.py +462 -0
  44. sequence_layers/tensorflow/position.py +509 -0
  45. sequence_layers/tensorflow/recurrent.py +645 -0
  46. sequence_layers/tensorflow/simple.py +1207 -0
  47. sequence_layers/tensorflow/squeeze.py +178 -0
  48. sequence_layers/tensorflow/test_util.py +834 -0
  49. sequence_layers/tensorflow/time_varying.py +439 -0
  50. sequence_layers/tensorflow/types.py +961 -0
  51. sequence_layers/tensorflow/utils.py +858 -0
  52. sequence_layers-0.1.dist-info/METADATA +69 -0
  53. sequence_layers-0.1.dist-info/RECORD +55 -0
  54. sequence_layers-0.1.dist-info/WHEEL +4 -0
  55. sequence_layers-0.1.dist-info/licenses/LICENSE +202 -0
@@ -0,0 +1,3426 @@
1
+ # Copyright 2023 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # https://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Attention layers."""
15
+
16
+ import abc
17
+ import fractions
18
+ import functools
19
+ import math
20
+ from typing import Callable, NamedTuple, Optional, Tuple
21
+
22
+ import numpy as np
23
+ import scipy
24
+ from sequence_layers.tensorflow import dense
25
+ from sequence_layers.tensorflow import types
26
+ from sequence_layers.tensorflow import utils
27
+ import tensorflow.compat.v1 as tf1
28
+ import tensorflow.compat.v2 as tf
29
+
30
+
31
+ # A negative enough value such that it underflows to a hard zero in softmax.
32
+ _INVALID_LOGIT_VALUE = -1e9
33
+
34
+
35
+ def _ones_matrix_band_part(rows, cols, num_lower, num_upper, out_shape=None):
36
+ """Matrix band part of ones.
37
+
38
+ Copied from tensor2tensor.
39
+
40
+ Args:
41
+ rows: int determining number of rows in output
42
+ cols: int
43
+ num_lower: int, maximum distance backward. Negative values indicate
44
+ unlimited.
45
+ num_upper: int, maximum distance forward. Negative values indicate
46
+ unlimited.
47
+ out_shape: shape to reshape output by.
48
+
49
+ Returns:
50
+ Tensor of size rows * cols reshaped into shape out_shape.
51
+ """
52
+ if all([isinstance(el, int) for el in [rows, cols, num_lower, num_upper]]):
53
+ # Needed info is constant, so we construct in numpy
54
+ if num_lower < 0:
55
+ num_lower = rows - 1
56
+ if num_upper < 0:
57
+ num_upper = cols - 1
58
+ lower_mask = np.tri(cols, rows, num_lower).T
59
+ upper_mask = np.tri(rows, cols, num_upper)
60
+ band = np.ones((rows, cols)) * lower_mask * upper_mask
61
+ if out_shape:
62
+ band = band.reshape(out_shape)
63
+ band = tf.constant(band, tf.float32)
64
+ else:
65
+ band = tf.linalg.band_part(
66
+ tf.ones([rows, cols]),
67
+ tf.cast(num_lower, tf.int64),
68
+ tf.cast(num_upper, tf.int64),
69
+ )
70
+ if out_shape:
71
+ band = tf.reshape(band, out_shape)
72
+
73
+ return band
74
+
75
+
76
+ def _soft_cap_attention_logits(logits: tf.Tensor, cap: float) -> tf.Tensor:
77
+ with tf.name_scope('soft_cap_attention_logits'):
78
+ cap = tf.cast(cap, logits.dtype)
79
+ return cap * tf.math.tanh(logits / cap)
80
+
81
+
82
+ def _mask_attention_logits(
83
+ logits: tf.Tensor, invalid_mask: tf.Tensor
84
+ ) -> tf.Tensor:
85
+ with tf.name_scope('mask_attention_logits'):
86
+ logits.shape.assert_has_rank(4)
87
+ invalid_mask.shape.assert_has_rank(4)
88
+ # Mask invalid timesteps, potentially broadcasting.
89
+ # Adding can change the softmax output so replace values with tf.where.
90
+ return tf.where(
91
+ invalid_mask > 0.0, tf.cast(_INVALID_LOGIT_VALUE, logits.dtype), logits
92
+ )
93
+
94
+
95
+ def _softmax_in_at_least_float32(logits: tf.Tensor) -> tf.Tensor:
96
+ compute_dtype = logits.dtype
97
+ assert compute_dtype.is_floating
98
+ softmax_dtype = tf.float32 if compute_dtype.size < 4 else compute_dtype
99
+ return tf.cast(tf.nn.softmax(tf.cast(logits, softmax_dtype)), compute_dtype)
100
+
101
+
102
+ def _validate_heads(num_heads: int, units_per_head: int, name: str):
103
+ if num_heads <= 0:
104
+ raise ValueError(f'Expected num_heads > 0 for {name}. Got {num_heads}')
105
+ if units_per_head <= 0:
106
+ raise ValueError(
107
+ f'Expected units_per_head > 0 for {name}. Got {units_per_head}'
108
+ )
109
+
110
+
111
+ def _validate_attention(
112
+ source_name: str, num_heads: int, units_per_head: int, name: str
113
+ ):
114
+ if not source_name:
115
+ raise ValueError(f'Expected non-empty source_name for {name}.')
116
+ _validate_heads(num_heads, units_per_head, name)
117
+
118
+
119
+ def _get_source(
120
+ layer: types.SequenceLayer, source_name: str, constants: types.Constants
121
+ ) -> types.Sequence:
122
+ """Gets the attention source from constants and does basic validation."""
123
+ if constants is None:
124
+ raise ValueError(
125
+ f'{layer} requires the source to be provided via '
126
+ f'constants, got: {constants}'
127
+ )
128
+ source = constants.get(source_name)
129
+ if not source:
130
+ raise ValueError(
131
+ f'{layer} expected {source_name} to be present in '
132
+ f'constants, got: {constants}'
133
+ )
134
+ if not isinstance(source, types.Sequence):
135
+ raise ValueError(
136
+ f'{layer} expected a Sequence for {source_name}, got: {source}'
137
+ )
138
+ if source.values.shape.rank != 3:
139
+ raise ValueError(f'{layer} requires a rank 3 source, got: {source}')
140
+ if source.values.shape.dims[2].value is None:
141
+ raise ValueError(
142
+ f'{layer} depends on source shape, but source has '
143
+ f'unknown channels dimension: {source}'
144
+ )
145
+ return source
146
+
147
+
148
+ class AttentionEmits(NamedTuple):
149
+ """A structure for emits produced by attention layers."""
150
+
151
+ # The attention probabilities, generally shaped
152
+ # [batch_size, query_time, num_heads, source_time].
153
+ probabilities: types.Sequence
154
+
155
+
156
+ class AdditiveAttention(types.StatelessEmitting):
157
+ """A multi-headed content-based attention layer."""
158
+
159
+ def __init__(
160
+ self,
161
+ source_name: str,
162
+ num_heads: int,
163
+ units_per_head: int,
164
+ name: Optional[str] = None,
165
+ ):
166
+ super().__init__(name)
167
+ _validate_attention(source_name, num_heads, units_per_head, name)
168
+ self._source_name = source_name
169
+ self._num_heads = num_heads
170
+ self._units_per_head = units_per_head
171
+ num_units = num_heads * units_per_head
172
+ with self.name_scope as name_scope:
173
+ self._attn_v = tf.Variable(
174
+ lambda: tf.initializers.GlorotUniform()(
175
+ [num_heads, units_per_head], dtype=utils.variable_dtype()
176
+ ),
177
+ name='v',
178
+ )
179
+ self._source_projection = tf.keras.layers.Dense(
180
+ num_units, use_bias=True, name=name_scope + 'source_projection/'
181
+ )
182
+ self._query_projection = tf.keras.layers.Dense(
183
+ num_units, use_bias=False, name=name_scope + 'query_projection/'
184
+ )
185
+
186
+ def get_output_shape(
187
+ self,
188
+ input_shape: tf.TensorShape,
189
+ constants: Optional[types.Constants] = None,
190
+ ) -> tf.TensorShape:
191
+ if input_shape.rank != 1:
192
+ raise ValueError(
193
+ 'AdditiveAttention requires rank 3 input got: %s'
194
+ % tf.TensorShape([None, None]).concatenate(input_shape)
195
+ )
196
+ source = _get_source(self, self._source_name, constants)
197
+ return tf.TensorShape([self._num_heads, source.values.shape.dims[2].value])
198
+
199
+ def get_emit_specs(
200
+ self,
201
+ input_spec: tf.TensorSpec,
202
+ constants: Optional[types.Constants] = None,
203
+ ) -> AttentionEmits:
204
+ source = _get_source(self, self._source_name, constants)
205
+ return AttentionEmits(
206
+ types.Sequence(
207
+ tf.TensorSpec(
208
+ tf.TensorShape(
209
+ [self._num_heads, source.values.shape.dims[1].value]
210
+ ),
211
+ input_spec.dtype,
212
+ ),
213
+ tf.TensorSpec(tf.TensorShape([]), tf.float32),
214
+ )
215
+ )
216
+
217
+ @tf.Module.with_name_scope
218
+ def layer_with_emits(
219
+ self,
220
+ x: types.Sequence,
221
+ training: bool,
222
+ initial_state: Optional[types.State] = None,
223
+ constants: Optional[types.Constants] = None,
224
+ ) -> Tuple[types.Sequence, AttentionEmits]:
225
+ source = _get_source(self, self._source_name, constants)
226
+ num_heads = self._num_heads
227
+ units_per_head = self._units_per_head
228
+ query = x.apply_values(self._query_projection)
229
+ batch_size, query_time = utils.smart_dimension_size(query.values, [0, 1])
230
+ query = query.apply_values(
231
+ tf.reshape, [batch_size, query_time, 1, num_heads, units_per_head]
232
+ )
233
+
234
+ keys = source.apply_values(self._source_projection).mask_invalid()
235
+ keys_time = utils.smart_dimension_size(keys.values, 1)
236
+ keys_values_for_broadcast = tf.reshape(
237
+ keys.values, [batch_size, 1, keys_time, num_heads, units_per_head]
238
+ )
239
+
240
+ # Broadcast keys and queries to
241
+ # [b, query_time, keys_time, num_heads, units_per_head]
242
+ hidden = tf.tanh(keys_values_for_broadcast + query.values)
243
+
244
+ logits = tf.einsum(
245
+ 'BijNH,NH->BiNj', hidden, tf.cast(self._attn_v, hidden.dtype)
246
+ )
247
+ # [b, query_time, num_heads, keys_time]
248
+ mask = keys.mask[:, tf.newaxis, tf.newaxis, :]
249
+
250
+ logits = tf.where(mask > 0.0, logits, _INVALID_LOGIT_VALUE)
251
+ probabilities = _softmax_in_at_least_float32(logits)
252
+ context_vector = tf.einsum('BiNj,BjS->BiNS', probabilities, source.values)
253
+ emits = AttentionEmits(types.Sequence(probabilities, query.mask))
254
+ return types.Sequence(context_vector, query.mask).mask_invalid(), emits
255
+
256
+
257
+ class _GmmCell(tf1.nn.rnn_cell.RNNCell):
258
+ """Executes GMM attention step-by-step as an RNN."""
259
+
260
+ def __init__(
261
+ self, layer, output_shape, comb_weight_shape, state_size, training, source
262
+ ):
263
+ self._layer = layer
264
+ self._output_shape = output_shape
265
+ self._comb_weight_shape = comb_weight_shape
266
+ self._state_size = state_size
267
+ self._training = training
268
+ self._source = source
269
+
270
+ @property
271
+ def output_size(self):
272
+ return self._output_shape, self._comb_weight_shape
273
+
274
+ @property
275
+ def state_size(self):
276
+ return self._state_size
277
+
278
+ def __call__(self, inputs, state):
279
+ # Keras RNN state is quirky.
280
+ return self.call(inputs, (state,), self._training)
281
+
282
+ def call(self, query_2d, state, training):
283
+ del training
284
+ query = query_2d[:, tf.newaxis, :]
285
+ (prev_position,) = state
286
+ context_vector, comb_weights, new_position = self._layer.attention(
287
+ self._source, query, prev_position
288
+ )
289
+ batch_size = utils.smart_dimension_size(context_vector, 0)
290
+ context_vector = tf.reshape(
291
+ context_vector,
292
+ tf.concat([[batch_size], self._output_shape.as_list()], 0),
293
+ )
294
+ comb_weights = tf.reshape(
295
+ comb_weights, tf.concat([[batch_size], self._comb_weight_shape], 0)
296
+ )
297
+ return (context_vector, comb_weights), new_position
298
+
299
+
300
+ class GmmAttention(types.Emitting):
301
+ """A multi-headed Gaussian-mixture attention layer."""
302
+
303
+ def __init__(
304
+ self,
305
+ source_name: str,
306
+ num_heads: int,
307
+ units_per_head: int,
308
+ num_components: int,
309
+ monotonic: bool,
310
+ init_offset_bias: float = 0.0,
311
+ init_scale_bias: float = 0.0,
312
+ max_offset: float = -1.0,
313
+ name: Optional[str] = None,
314
+ ):
315
+ super().__init__(name=name)
316
+ _validate_attention(source_name, num_heads, units_per_head, name)
317
+ if num_components <= 0:
318
+ raise ValueError(
319
+ f'Expected num_components > 0 for {name}. Got: {num_components}.'
320
+ )
321
+
322
+ self._source_name = source_name
323
+ self._num_heads = num_heads
324
+ self._units_per_head = units_per_head
325
+ num_units = num_heads * units_per_head
326
+ self._num_components = num_components
327
+ self._monotonic = monotonic
328
+ self._init_offset_bias = init_offset_bias
329
+ self._init_scale_bias = init_scale_bias
330
+ self._max_offset = max_offset
331
+ self._built = False
332
+
333
+ with self.name_scope as name_scope:
334
+ self._mlp_hidden = tf.keras.layers.Dense(
335
+ num_units, activation=tf.nn.relu, name=name_scope + 'gmm_mlp_hidden/'
336
+ )
337
+ # TODO(rryan): Pull this pattern into a "DenseShaped" layer?
338
+ with tf.name_scope('gmm_mlp_output'):
339
+ self._mlp_output_w = tf.Variable(
340
+ lambda: tf.initializers.GlorotUniform()(
341
+ [num_heads, units_per_head, num_components * 3],
342
+ dtype=utils.variable_dtype(),
343
+ ),
344
+ name='kernel',
345
+ )
346
+ self._mlp_output_b = tf.Variable(
347
+ lambda: tf.initializers.Zeros()(
348
+ [1, 1, num_heads, num_components * 3],
349
+ dtype=utils.variable_dtype(),
350
+ ),
351
+ name='bias',
352
+ )
353
+
354
+ def get_initial_state(
355
+ self, x: types.Sequence, constants: Optional[types.Constants] = None
356
+ ) -> types.State:
357
+ if self._monotonic:
358
+ batch_size = utils.smart_dimension_size(x.values, 0)
359
+ # Start from zero positions.
360
+ return tf.zeros(
361
+ [batch_size, 1, self._num_heads, self._num_components],
362
+ utils.compute_dtype(),
363
+ )
364
+ else:
365
+ return ()
366
+
367
+ def get_output_shape(
368
+ self,
369
+ input_shape: tf.TensorShape,
370
+ constants: Optional[types.Constants] = None,
371
+ ) -> tf.TensorShape:
372
+ if input_shape.rank != 1:
373
+ raise ValueError(
374
+ 'GmmAttention requires rank 3 input got: %s'
375
+ % tf.TensorShape([None, None]).concatenate(input_shape)
376
+ )
377
+ source = _get_source(self, self._source_name, constants)
378
+ return tf.TensorShape([self._num_heads, source.values.shape.dims[2].value])
379
+
380
+ def get_emit_specs(
381
+ self,
382
+ input_spec: tf.TensorSpec,
383
+ constants: Optional[types.Constants] = None,
384
+ ) -> AttentionEmits:
385
+ source = _get_source(self, self._source_name, constants)
386
+ return AttentionEmits(
387
+ types.Sequence(
388
+ tf.TensorSpec(
389
+ tf.TensorShape(
390
+ [self._num_heads, source.values.shape.dims[1].value]
391
+ ),
392
+ input_spec.dtype,
393
+ ),
394
+ tf.TensorSpec(tf.TensorShape([]), tf.float32),
395
+ )
396
+ )
397
+
398
+ @tf.Module.with_name_scope
399
+ def step_with_emits(
400
+ self,
401
+ x: types.Sequence,
402
+ state: types.State,
403
+ training: bool,
404
+ constants: Optional[types.Constants] = None,
405
+ unroll: bool = True,
406
+ ) -> Tuple[types.Sequence, types.State, types.Emits]:
407
+ # Compute in parallel if stateless.
408
+ if not self._monotonic:
409
+ outputs, emits = self.layer_with_emits(x, training, state, constants)
410
+ return outputs, state, emits
411
+
412
+ source = _get_source(self, self._source_name, constants)
413
+
414
+ state_size = tf.nest.map_structure(lambda t: t.shape[1:], state)
415
+ output_shape: tf.TensorShape = self.get_output_shape_for_sequence(
416
+ x, constants
417
+ )
418
+ source_time = utils.smart_dimension_size(source.values, 1)
419
+ comb_weight_shape = tf.stack([self._num_heads, source_time])
420
+ use_keras = False
421
+ # TODO(rryan): Reimplement using utils.step_by_step_{dynamic,static}
422
+ # to harmonize with other parts of go/sequence-layers.
423
+ cell = _GmmCell(
424
+ self, output_shape, comb_weight_shape, state_size, training, source
425
+ )
426
+ if use_keras:
427
+ rnn = tf.keras.layers.RNN(
428
+ cell, return_sequences=True, return_state=True, unroll=unroll
429
+ )
430
+ result = rnn(
431
+ x.values, mask=x.mask, initial_state=state, training=training
432
+ )
433
+ (values, comb_weights), state = result[0], result[1]
434
+ else:
435
+ if unroll:
436
+ inputs = tf.unstack(x.values, axis=1)
437
+ # To avoid creating complicated control flow for what is probably a
438
+ # short sequence of frames, do not provide lengths to static_rnn. We are
439
+ # masking the output values below, so this is safe.
440
+ outputs, state = tf1.nn.static_rnn(cell, inputs, initial_state=state)
441
+ values, comb_weights = zip(*outputs)
442
+ values = tf.stack(values, axis=1)
443
+ comb_weights = tf.stack(comb_weights, axis=1)
444
+ else:
445
+ (values, comb_weights), state = tf1.nn.dynamic_rnn(
446
+ cell,
447
+ x.values,
448
+ initial_state=state,
449
+ dtype=x.values.dtype,
450
+ sequence_length=x.lengths(),
451
+ )
452
+ emits = AttentionEmits(types.Sequence(comb_weights, x.mask))
453
+ return types.Sequence(values, x.mask).mask_invalid(), state, emits
454
+
455
+ @tf.Module.with_name_scope
456
+ def layer_with_emits(
457
+ self,
458
+ x: types.Sequence,
459
+ training: bool,
460
+ initial_state: Optional[types.State] = None,
461
+ constants: Optional[types.Constants] = None,
462
+ ) -> Tuple[types.Sequence, types.Emits]:
463
+ prev_position = initial_state
464
+ if prev_position is None:
465
+ prev_position = self.get_initial_state(x, constants)
466
+
467
+ if self._monotonic:
468
+ x, _, emits = self.step_with_emits(
469
+ x, prev_position, training, constants, unroll=False
470
+ )
471
+ # step masks.
472
+ return x, emits
473
+
474
+ query = x
475
+ source = _get_source(self, self._source_name, constants)
476
+ context_vector, comb_weights, _ = self.attention(
477
+ source, query.values, prev_position
478
+ )
479
+ emits = AttentionEmits(types.Sequence(comb_weights, query.mask))
480
+ return types.Sequence(context_vector, query.mask).mask_invalid(), emits
481
+
482
+ def attention(self, source, query_values, prev_position):
483
+ """Computes GMM attention from query and previous position.
484
+
485
+ Args:
486
+ source: The source sequence to attend to.
487
+ query_values: [batch_size, query_time, query_channels]
488
+ prev_position: [batch_size, 1, num_heads, num_components]. Previous
489
+ position of each mixture component per-head.
490
+
491
+ Returns:
492
+ context_vector: [batch_size, query_time, num_heads, source_dimension].
493
+ The per-head context vector.
494
+ comb_weights: [batch_size, query_time, num_heads, source_time]
495
+ The per-head combination weights.
496
+ position: [batch_size, 1, num_heads, num_components]. Current position
497
+ of each mixture component per head.
498
+ """
499
+ num_heads = self._num_heads
500
+ units_per_head = self._units_per_head
501
+
502
+ batch_size, query_time = utils.smart_dimension_size(query_values, [0, 1])
503
+ if self._monotonic and not isinstance(query_time, tf.Tensor):
504
+ assert query_time == 1
505
+ query_values = self._mlp_hidden(query_values)
506
+ query_values = tf.reshape(
507
+ query_values, [batch_size, query_time, num_heads, units_per_head]
508
+ )
509
+
510
+ # Per-head projection from units_per_head to num_components * 3.
511
+ # Equivalent to tf.stack(
512
+ # [tf.tensordot(query_values[:, :, i, :], mlp_output_w[i, :, :], 1)
513
+ # for i in range(num_heads)], axis=2)
514
+
515
+ query_values = tf.einsum(
516
+ 'BiNH,NHM->BiNM',
517
+ query_values,
518
+ tf.cast(self._mlp_output_w, query_values.dtype),
519
+ )
520
+ # bias_add doesn't work for biases with rank > 1.
521
+ query_values += tf.cast(self._mlp_output_b, query_values.dtype)
522
+
523
+ # Each is [batch_size, query_time, num_heads, num_components].
524
+ prior_logits, offset_logits, scale_logits = tf.split(
525
+ query_values, 3, axis=3
526
+ )
527
+
528
+ offset_logits += self._init_offset_bias
529
+ scale_logits += self._init_scale_bias
530
+ assert prior_logits.shape.dims[-1].value == self._num_components
531
+
532
+ # comb_weights: [b, query_time, num_heads, source_time]
533
+ # new_position: [b, q, num_heads, num_components]
534
+ comb_weights, new_position = self._v2_comb_weights(
535
+ source, prior_logits, offset_logits, scale_logits, prev_position
536
+ )
537
+
538
+ # Expand source mask for broadcasting to
539
+ # [b, query_time, num_heads, source_time].
540
+ comb_weights *= tf.cast(
541
+ source.mask[:, tf.newaxis, tf.newaxis, :], comb_weights.dtype
542
+ )
543
+
544
+ # [b, query_time, num_heads, source_time]
545
+ # [b, source_time, source_dim]
546
+ # -> [b, query_time, num_heads, source_dim]
547
+ context_vector = tf.einsum('BiNj,BjS->BiNS', comb_weights, source.values)
548
+ return context_vector, comb_weights, new_position
549
+
550
+ def _v2_comb_weights(
551
+ self, source, prior_logits, offset_logits, scale_logits, prev_position
552
+ ):
553
+ """Return comb weights computed using V2 method."""
554
+ # V2 properties:
555
+ # * Uses softmax for the mixture weights.
556
+ # * Uses softplus for means and scales.
557
+ # * Scale represents the standard deviation.
558
+ priors = _softmax_in_at_least_float32(prior_logits)
559
+ variances = tf.square(tf.nn.softplus(scale_logits))
560
+ if self._max_offset > 0:
561
+ # softplus(x) - softplus(x - M) gives a sigmoid that saturates outside
562
+ # [0, M] and is approximately linear in between.
563
+ position_offset = tf.nn.softplus(offset_logits) - tf.nn.softplus(
564
+ offset_logits - self._max_offset
565
+ )
566
+ else:
567
+ position_offset = tf.nn.softplus(offset_logits)
568
+
569
+ comb_weights, new_position = self._eval_gmm_pdfs(
570
+ source, priors, position_offset, variances, prev_position
571
+ )
572
+ return comb_weights, new_position
573
+
574
+ def _eval_gmm_pdfs(
575
+ self,
576
+ source,
577
+ priors,
578
+ position_offset,
579
+ variances,
580
+ prev_position,
581
+ normalize=True,
582
+ ):
583
+ """Evaluate the location GMMs on all encoder positions."""
584
+ # priors, position_offset, variances are shaped
585
+ # [b, query_time, num_heads, num_components].
586
+ priors.shape.assert_is_compatible_with(
587
+ [None, None, self._num_heads, self._num_components]
588
+ )
589
+ position_offset.shape.assert_is_compatible_with(
590
+ [None, None, self._num_heads, self._num_components]
591
+ )
592
+ variances.shape.assert_is_compatible_with(
593
+ [None, None, self._num_heads, self._num_components]
594
+ )
595
+ # prev_position is [b, 1, num_heads, num_components].
596
+ if self._monotonic:
597
+ prev_position.shape.assert_is_compatible_with(
598
+ [None, 1, self._num_heads, self._num_components]
599
+ )
600
+ # If we're monotonic, then query time is always 1.
601
+ position_offset.shape.assert_is_compatible_with(
602
+ [None, 1, self._num_heads, self._num_components]
603
+ )
604
+ new_position = prev_position + position_offset
605
+ new_position.shape.assert_is_compatible_with(
606
+ [None, 1, self._num_heads, self._num_components]
607
+ )
608
+ else:
609
+ new_position = position_offset
610
+
611
+ # Expand all to [b, query_time, num_heads, source_time (1), num_components]
612
+ priors = priors[:, :, :, tf.newaxis, :]
613
+ means = new_position[:, :, :, tf.newaxis, :]
614
+ variances = variances[:, :, :, tf.newaxis, :]
615
+
616
+ # [1, 1, 1, source_timesteps, 1].
617
+ source_length = utils.smart_dimension_size(source.values, 1)
618
+ encoder_positions = tf.cast(tf.range(source_length), means.dtype)
619
+ encoder_positions = encoder_positions[
620
+ tf.newaxis, tf.newaxis, tf.newaxis, :, tf.newaxis
621
+ ]
622
+
623
+ if normalize:
624
+ priors *= tf.math.rsqrt(2 * np.pi * variances + 1e-8)
625
+ # Broadcast source time and query time.
626
+ # encoder_positions is [1, 1, 1, source_time, 1]
627
+ # means/priors/variances are
628
+ # [batch, query_time, num_heads, 1, num_components]
629
+ pdfs = priors * tf.exp(
630
+ -((encoder_positions - means) ** 2) / (2 * variances + 1e-8)
631
+ )
632
+ # pdfs sized [batch, query_time, num_heads, source_time].
633
+ pdfs = tf.reduce_sum(pdfs, 4)
634
+ return pdfs, new_position
635
+
636
+
637
+ class RelativePositionEmbedding(tf.Module, metaclass=abc.ABCMeta):
638
+ """Abstract base class for computing relative position biases."""
639
+
640
+ @abc.abstractmethod
641
+ def get_position_bias_streaming(
642
+ self, queries: tf.Tensor, keys: tf.Tensor, queries_position: tf.Tensor
643
+ ) -> tf.Tensor:
644
+ """Computes relative self-attention position biases for streaming queries.
645
+
646
+ This method computes relative position biases for a block of queries_time
647
+ timesteps of the overall queries tensor, and the keys/values available are
648
+ always the queries within the current queries_time block, and a fixed
649
+ "max_previous" trailing window of timesteps.
650
+
651
+ Args:
652
+ queries: [batch, queries_time, num_heads, units_per_head] queries.
653
+ queries_time is the number of streaming steps we are taking at once.
654
+ keys: [batch, queries_time + max_previous, num_heads, units_per_head]
655
+ keys.
656
+ queries_position: scalar integer indicating the current decode position of
657
+ queries[:, 0, :]. For example, this value is n * queries_time for the
658
+ n'th queries_time block we process.
659
+
660
+ Returns:
661
+ A tensor of relative position biases broadcastable to
662
+ [batch, num_heads, queries_time, keys_time].
663
+ """
664
+
665
+ @abc.abstractmethod
666
+ def get_position_bias_raw(
667
+ self,
668
+ queries_position: tf.Tensor,
669
+ queries_length: tf.Tensor | int,
670
+ keys_position: tf.Tensor,
671
+ keys_length: tf.Tensor | int,
672
+ ) -> tf.Tensor:
673
+ """Computes relative self-attention position biases for absolute positions.
674
+
675
+ This method computes relative position biases for absolute query / key
676
+ positions and lengths.
677
+
678
+ Args:
679
+ queries_position: Scalar integer query absolute position.
680
+ queries_length: Number of query timesteps to produce relative position
681
+ embeddings for.
682
+ keys_position: Scalar integer key absolute position.
683
+ keys_length: Number of key timesteps to produce relative position
684
+ embeddings for.
685
+
686
+ Returns:
687
+ A tensor of relative position biases broadcastable to
688
+ [batch, queries_length, num_heads, keys_length].
689
+ """
690
+
691
+ @abc.abstractmethod
692
+ def get_position_bias(self, queries: tf.Tensor) -> tf.Tensor:
693
+ """Computes relative self-attention position biases for queries.
694
+
695
+ Args:
696
+ queries: [batch, queries_time, num_heads, units_per_head] queries.
697
+
698
+ Returns:
699
+ A tensor of relative position biases broadcastable to
700
+ [batch, num_heads, queries_time, keys_time].
701
+ """
702
+
703
+
704
+ class ShawRelativePositionEmbedding(RelativePositionEmbedding):
705
+ """Computes query-dependent relative position embeddings.
706
+
707
+ Based on:
708
+ Self-Attention with Relative Position Representations
709
+ https://arxiv.org/abs/1803.02155
710
+
711
+ Warning: Implements the attention logits bias, but not the value biases
712
+ described in the paper. Does not clip based on maximum distance (distances
713
+ beyond max_backward/max_forward receive no relative position bias).
714
+
715
+ Computes a [batch, num_heads, queries_time, keys_time] tensor of relative
716
+ position biases, biasing the selection of keys for every query timestep.
717
+ """
718
+
719
+ def __init__(
720
+ self,
721
+ max_backward: int,
722
+ max_forward: int,
723
+ num_heads: int,
724
+ units_per_head: int,
725
+ name: Optional[str] = None,
726
+ ):
727
+ super().__init__(name=name)
728
+ self._max_forward = max_forward
729
+ self._max_backward = max_backward
730
+ self._num_heads = num_heads
731
+ self._units_per_head = units_per_head
732
+
733
+ if max_forward > 0:
734
+ raise ValueError(f'{self} does not support forward relative biases yet.')
735
+
736
+ if max_forward < 0 or max_backward < 0:
737
+ raise ValueError(f'{max_forward=} and {max_backward=} must be >= 0')
738
+ with self.name_scope:
739
+ # Create an embedding vector for the max_backward previous timesteps and
740
+ # the current timestep.
741
+ # TODO(rryan): Support the ability to share embeddings across heads.
742
+ self._relative_position_embedding = tf.Variable(
743
+ lambda: tf.keras.initializers.VarianceScaling()(
744
+ [max_backward + 1, num_heads, units_per_head],
745
+ dtype=utils.variable_dtype(),
746
+ ),
747
+ name='embedding',
748
+ )
749
+
750
+ @tf.Module.with_name_scope
751
+ def get_position_bias_streaming(
752
+ self, queries: tf.Tensor, keys: tf.Tensor, queries_position: tf.Tensor
753
+ ) -> tf.Tensor:
754
+ """Computes relative self-attention position biases for streaming queries.
755
+
756
+ This method computes relative position biases for a block of queries_time
757
+ timesteps of the overall queries tensor, and the keys/values available are
758
+ always the queries within the current queries_time block, and a fixed
759
+ "max_previous" trailing window of timesteps.
760
+
761
+ Args:
762
+ queries: [batch, queries_time, num_heads, units_per_head] queries.
763
+ queries_time is the number of streaming steps we are taking at once.
764
+ keys: [batch, queries_time + max_previous, num_heads, units_per_head]
765
+ keys.
766
+ queries_position: scalar integer indicating the current decode position of
767
+ queries[:, 0, :]. For example, this value is n * queries_time for the
768
+ n'th queries_time block we process.
769
+
770
+ Returns:
771
+ A tensor of relative position biases broadcastable to
772
+ [batch, num_heads, queries_time, keys_time].
773
+ """
774
+ del queries_position
775
+ assert self._max_forward == 0
776
+ batch_size, queries_time = utils.smart_dimension_size(queries, [0, 1])
777
+ queries_time_static = queries.shape.dims[1].value
778
+ queries.shape.assert_is_compatible_with(
779
+ [None, None, self._num_heads, self._units_per_head]
780
+ )
781
+
782
+ keys_time = utils.smart_dimension_size(keys, 1)
783
+ expected_keys_time_static = (
784
+ queries_time_static + self._max_backward
785
+ if queries_time_static is not None
786
+ else None
787
+ )
788
+ keys.shape.assert_is_compatible_with(
789
+ [None, expected_keys_time_static, self._num_heads, self._units_per_head]
790
+ )
791
+
792
+ # First, we compute a
793
+ # [batch_size, num_heads, queries_time, max_backward + 1]
794
+ # tensor of relative position biases for each (query, relative) pair.
795
+ relative_logits = tf.einsum(
796
+ 'jNH,BiNH->BNij',
797
+ tf.cast(self._relative_position_embedding, queries.dtype),
798
+ queries,
799
+ )
800
+
801
+ if queries_time_static == 1:
802
+ # If queries_time_static is 1, there is no need to compute any coordinate
803
+ # remappings, because keys_time is max_backward + 1 timesteps, and its
804
+ # layout already matches the ordering of relative_logits.
805
+ pass
806
+ else:
807
+ # Following the above example of the mask, if letters correspond to each
808
+ # relative bias, and 'a' is the relative position bias for the current
809
+ # queries_time timestep, then our goal for a given batch/head is the
810
+ # following matrix:
811
+ # f e d c b a 0 0
812
+ # 0 f e d c b a 0
813
+ # 0 0 f e d c b a
814
+ #
815
+ # In the above example, relative_logits is now this matrix:
816
+ # f e d c b a
817
+ # f e d c b a
818
+ # f e d c b a
819
+ #
820
+ # To achieve the goal we use some reshaping trickery. We insert 3 zeros
821
+ # at the end of each row:
822
+ # f e d c b a 0 0 0
823
+ # f e d c b a 0 0 0
824
+ # f e d c b a 0 0 0
825
+ pad = (queries_time - 1) + 1
826
+ relative_logits = tf.pad(
827
+ relative_logits, [[0, 0], [0, 0], [0, 0], [0, pad]]
828
+ )
829
+
830
+ # Then flatten, trim, and reshape into an 8x3 matrix, arriving at our
831
+ # goal:
832
+ # f e d c b a 0 0
833
+ # 0 f e d c b a 0
834
+ # 0 0 f e d c b a
835
+ relative_logits = tf.reshape(
836
+ relative_logits, [batch_size, self._num_heads, -1]
837
+ )
838
+ total = queries_time * keys_time
839
+ relative_logits = relative_logits[:, :, :total]
840
+ relative_logits = tf.reshape(
841
+ relative_logits,
842
+ [batch_size, self._num_heads, queries_time, keys_time],
843
+ )
844
+
845
+ # Shaw, et al. scale the relative logits by rsqrt(units_per_head).
846
+ relative_logits *= tf.math.rsqrt(
847
+ tf.cast(self._units_per_head, queries.dtype)
848
+ )
849
+
850
+ return relative_logits
851
+
852
+ @tf.Module.with_name_scope
853
+ def get_position_bias_raw(
854
+ self,
855
+ queries_position: tf.Tensor,
856
+ queries_length: tf.Tensor | int,
857
+ keys_position: tf.Tensor,
858
+ keys_length: tf.Tensor | int,
859
+ ) -> tf.Tensor:
860
+ """Computes relative self-attention position biases for absolute positions.
861
+
862
+ This method computes relative position biases for absolute query / key
863
+ positions and lengths.
864
+
865
+ Args:
866
+ queries_position: Scalar integer query absolute position.
867
+ queries_length: Number of query timesteps to produce relative position
868
+ embeddings for.
869
+ keys_position: Scalar integer key absolute position.
870
+ keys_length: Number of key timesteps to produce relative position
871
+ embeddings for.
872
+
873
+ Returns:
874
+ A tensor of relative position biases broadcastable to
875
+ [batch, queries_length, num_heads, keys_length].
876
+ """
877
+ # This API cannot be implemented since we need key/query values.
878
+ raise NotImplementedError(
879
+ f'{type(self).__name__} does not support get_position_bias_raw.'
880
+ )
881
+
882
+ @tf.Module.with_name_scope
883
+ def get_position_bias(self, queries: tf.Tensor) -> tf.Tensor:
884
+ """Computes relative self-attention position biases for queries.
885
+
886
+ Args:
887
+ queries: [batch, queries_time, num_heads, units_per_head] queries.
888
+
889
+ Returns:
890
+ A tensor of relative position biases broadcastable to
891
+ [batch, num_heads, queries_time, keys_time].
892
+ """
893
+ assert self._max_forward == 0
894
+ batch_size, queries_time = utils.smart_dimension_size(queries, [0, 1])
895
+
896
+ # This implementation closely follows tensor2tensor:
897
+ # https://github.com/tensorflow/tensor2tensor/blob/bafdc1b67730430d38d6ab802cbd51f9d053ba2e/tensor2tensor/layers/common_attention.py#L1934
898
+ # If relative position embedding is enabled, then we need to compute a
899
+ # [batch, num_heads, queries_time, keys_time] tensor of relative
900
+ # position biases, biasing the selection of keys for every query
901
+ # timestep.
902
+ #
903
+ # Following the above example of the mask, if letters correspond to each
904
+ # relative bias, and 'a' is the relative position bias for the current
905
+ # queries_time timestep, then our goal for a given batch/head is the
906
+ # following matrix:
907
+ # a 0 0 0 0
908
+ # b a 0 0 0
909
+ # c b a 0 0
910
+ # 0 c b a 0
911
+ # 0 0 c b a
912
+
913
+ # First we pad from the left to queries_time so that the relative
914
+ # embeddings are right aligned.
915
+ # 0 0 c b a
916
+ # In the corner case that queries_time is smaller than
917
+ # max_previous + 1, make sure we use the right-most relative
918
+ # embeddings.
919
+ # TODO(rryan): Handle queries_time == 0! Bad slice.
920
+ relative_position_embedding = tf.cast(
921
+ self._relative_position_embedding[-queries_time:, :, :], queries.dtype
922
+ )
923
+ pad_amount = queries_time - tf.minimum(self._max_backward + 1, queries_time)
924
+ relative_position_embedding = tf.pad(
925
+ relative_position_embedding, [[pad_amount, 0], [0, 0], [0, 0]]
926
+ )
927
+
928
+ # Then we compute the relative position biases. Considering just one
929
+ # batch/head slice, the matrix looks like this with queries_time = 5
930
+ # and max_past_horizon = 2.
931
+ # 0 0 c b a
932
+ # 0 0 c b a
933
+ # 0 0 c b a
934
+ # 0 0 c b a
935
+ # 0 0 c b a
936
+ relative_logits = tf.einsum(
937
+ 'jNH,BiNH->BNij', relative_position_embedding, queries
938
+ )
939
+
940
+ # To achieve the goal we use some reshaping trickery. We insert 1 zero
941
+ # at the beginning of each row:
942
+ # 0 0 0 c b a
943
+ # 0 0 0 c b a
944
+ # 0 0 0 c b a
945
+ # 0 0 0 c b a
946
+ # 0 0 0 c b a
947
+ relative_logits = tf.pad(relative_logits, [[0, 0], [0, 0], [0, 0], [1, 0]])
948
+
949
+ # Then reshape into a 6x5 matrix, and trim off the first row to achieve
950
+ # the goal:
951
+ # 0 0 0 c b <- Trim this row.
952
+ # a 0 0 0 c
953
+ # b a 0 0 0
954
+ # c b a 0 0
955
+ # 0 c b a 0
956
+ # 0 0 c b a
957
+ #
958
+ # The biases that wrap around and inhabit the upper triangular portion of
959
+ # the matrix have no effect because the invalid_mask computed above is a
960
+ # banded matrix that only covers the diagonal and max_past_horizon lower
961
+ # bandwidth.
962
+ relative_logits = tf.reshape(
963
+ relative_logits,
964
+ [batch_size, self._num_heads, queries_time + 1, queries_time],
965
+ )
966
+ relative_logits = relative_logits[:, :, 1:, :]
967
+
968
+ # Shaw, et al. scale the relative logits by rsqrt(units_per_head).
969
+ relative_logits *= tf.math.rsqrt(
970
+ tf.cast(self._units_per_head, queries.dtype)
971
+ )
972
+
973
+ return relative_logits
974
+
975
+
976
+ class T5RelativePositionEmbedding(RelativePositionEmbedding):
977
+ """Relative position embeddings in the T5 style.
978
+
979
+ Exploring the Limits of Transfer Learning with a Unified Text-to-Text
980
+ Transformer
981
+ https://arxiv.org/abs/1910.10683
982
+
983
+ Implementation copied from
984
+ https://github.com/tensorflow/models/blob/master/official/nlp/modeling/models/t5.py
985
+ """
986
+
987
+ def __init__(
988
+ self,
989
+ num_buckets: int,
990
+ num_heads: int,
991
+ bidirectional: bool,
992
+ max_distance: int = 128,
993
+ embeddings_initializer: Optional[
994
+ tf.keras.initializers.Initializer
995
+ ] = None,
996
+ name: Optional[str] = None,
997
+ ):
998
+ super().__init__(name=name)
999
+ self._num_heads = num_heads
1000
+ self._num_buckets = num_buckets
1001
+ self._bidirectional = bidirectional
1002
+ self._max_distance = max_distance
1003
+ with self.name_scope:
1004
+ self.relative_attention_bias = tf.keras.layers.Embedding(
1005
+ input_dim=self._num_buckets,
1006
+ output_dim=self._num_heads,
1007
+ embeddings_initializer=embeddings_initializer,
1008
+ name='rel_embedding',
1009
+ )
1010
+
1011
+ @tf.Module.with_name_scope
1012
+ def get_position_bias_streaming(
1013
+ self, queries: tf.Tensor, keys: tf.Tensor, queries_position: tf.Tensor
1014
+ ) -> tf.Tensor:
1015
+ """Computes relative self-attention position biases for streaming queries.
1016
+
1017
+ This method computes relative position biases for a block of queries_time
1018
+ timesteps of the overall queries tensor, and the keys/values available are
1019
+ always the queries within the current queries_time block, and a fixed
1020
+ "max_previous" trailing window of timesteps.
1021
+
1022
+ Args:
1023
+ queries: [batch, queries_time, num_heads, units_per_head] queries.
1024
+ queries_time is the number of streaming steps we are taking at once.
1025
+ keys: [batch, queries_time + max_previous, num_heads, units_per_head]
1026
+ keys.
1027
+ queries_position: scalar integer indicating the current decode position of
1028
+ queries[:, 0, :]. For example, this value is n * queries_time for the
1029
+ n'th queries_time block we process.
1030
+
1031
+ Returns:
1032
+ A tensor of relative position biases broadcastable to
1033
+ [batch, num_heads, queries_time, keys_time].
1034
+ """
1035
+ queries_time_static = queries.shape.dims[1].value
1036
+ keys_time_static = keys.shape.dims[1].value
1037
+ queries_time = utils.smart_dimension_size(queries, 1)
1038
+ keys_time = utils.smart_dimension_size(keys, 1)
1039
+
1040
+ context_position = queries_position + tf.range(queries_time)[:, tf.newaxis]
1041
+ # keys[:, 0, :]'s absolute position is queries_position - max_previous.
1042
+ max_previous = keys_time - queries_time
1043
+ memory_start_position = queries_position - max_previous
1044
+ memory_position = memory_start_position + tf.range(keys_time)[tf.newaxis, :]
1045
+ # Semantically, this tensor is [queries, keys].
1046
+ relative_position = memory_position - context_position
1047
+ rp_bucket = self._relative_position_bucket(relative_position)
1048
+ values = self.relative_attention_bias(rp_bucket)
1049
+ values = tf.expand_dims(tf.transpose(values, [2, 0, 1]), axis=0)
1050
+ values.shape.assert_is_compatible_with(
1051
+ [1, self._num_heads, queries_time_static, keys_time_static]
1052
+ )
1053
+ return values
1054
+
1055
+ @tf.Module.with_name_scope
1056
+ def get_position_bias_raw(
1057
+ self,
1058
+ queries_position: tf.Tensor,
1059
+ queries_length: tf.Tensor | int,
1060
+ keys_position: tf.Tensor,
1061
+ keys_length: tf.Tensor | int,
1062
+ ) -> tf.Tensor:
1063
+ """Computes relative self-attention position biases for absolute positions.
1064
+
1065
+ This method computes relative position biases for absolute query / key
1066
+ positions and lengths.
1067
+
1068
+ Args:
1069
+ queries_position: Scalar integer query absolute position.
1070
+ queries_length: Number of query timesteps to produce relative position
1071
+ embeddings for.
1072
+ keys_position: Scalar integer key absolute position.
1073
+ keys_length: Number of key timesteps to produce relative position
1074
+ embeddings for.
1075
+
1076
+ Returns:
1077
+ A tensor of relative position biases broadcastable to
1078
+ [batch, queries_length, num_heads, keys_length].
1079
+ """
1080
+ queries_time_static = (
1081
+ queries_length if isinstance(queries_length, int) else None
1082
+ )
1083
+ keys_time_static = keys_length if isinstance(keys_length, int) else None
1084
+
1085
+ queries_positions = (
1086
+ queries_position + tf.range(queries_length)[:, tf.newaxis]
1087
+ )
1088
+ keys_positions = keys_position + tf.range(keys_length)[tf.newaxis, :]
1089
+
1090
+ relative_position = keys_positions - queries_positions
1091
+ rp_bucket = self._relative_position_bucket(relative_position)
1092
+ values = self.relative_attention_bias(rp_bucket)
1093
+ values = tf.expand_dims(tf.transpose(values, [0, 2, 1]), axis=0)
1094
+ values.shape.assert_is_compatible_with(
1095
+ [1, queries_time_static, self._num_heads, keys_time_static]
1096
+ )
1097
+ return values
1098
+
1099
+ @tf.Module.with_name_scope
1100
+ def get_position_bias(self, queries: tf.Tensor) -> tf.Tensor:
1101
+ """Computes relative self-attention position biases for queries.
1102
+
1103
+ Args:
1104
+ queries: [batch, queries_time, num_heads, units_per_head] queries.
1105
+
1106
+ Returns:
1107
+ A tensor of relative position biases broadcastable to
1108
+ [batch, num_heads, queries_time, keys_time].
1109
+ """
1110
+ queries_time_static = queries.shape.dims[1].value
1111
+ queries_time = utils.smart_dimension_size(queries, 1)
1112
+ context_position = tf.range(queries_time)[:, tf.newaxis]
1113
+ memory_position = tf.range(queries_time)[tf.newaxis, :]
1114
+ # Semantically, this tensor is [queries, keys].
1115
+ relative_position = memory_position - context_position
1116
+ rp_bucket = self._relative_position_bucket(relative_position)
1117
+ values = self.relative_attention_bias(rp_bucket)
1118
+ values = tf.expand_dims(tf.transpose(values, [2, 0, 1]), axis=0)
1119
+ values.shape.assert_is_compatible_with(
1120
+ [1, self._num_heads, queries_time_static, queries_time_static]
1121
+ )
1122
+ return values
1123
+
1124
+ def _relative_position_bucket(
1125
+ self, relative_position: tf.Tensor
1126
+ ) -> tf.Tensor:
1127
+ """Translate relative position to a bucket number for relative attention.
1128
+
1129
+ The relative position is defined as memory_position - query_position, i.e.
1130
+ the distance in tokens from the attending position to the attended-to
1131
+ position.
1132
+
1133
+ If bidirectional=False, then positive relative positions are invalid.
1134
+
1135
+ We use smaller buckets for small absolute relative_position and larger
1136
+ buckets for larger absolute relative_positions.
1137
+
1138
+ All relative positions >=max_distance map to the same bucket.
1139
+
1140
+ All relative positions <=-max_distance map to the same bucket.
1141
+
1142
+ This should allow for more graceful generalization to longer sequences
1143
+ than the model has been trained on.
1144
+
1145
+ Args:
1146
+ relative_position: A [query_time, keys_time] int32 Tensor of relative
1147
+ positions. r = relative_position[q, k] indicates key timestep k is r
1148
+ timesteps ahead (positive) or behind (negative) of query timestep q.
1149
+
1150
+ Returns:
1151
+ a Tensor with the same shape as relative_position, containing int32
1152
+ values in the range [0, num_buckets)
1153
+ """
1154
+ with tf.name_scope('relative_position_bucket'):
1155
+ ret = 0
1156
+ n = -relative_position
1157
+ num_buckets = self._num_buckets
1158
+ max_distance = self._max_distance
1159
+ if self._bidirectional:
1160
+ num_buckets //= 2
1161
+ ret += tf.cast(tf.math.less(n, 0), tf.int32) * num_buckets
1162
+ n = tf.math.abs(n)
1163
+ else:
1164
+ n = tf.math.maximum(n, 0)
1165
+ # now n is in the range [0, inf)
1166
+ max_exact = num_buckets // 2
1167
+ is_small = tf.math.less(n, max_exact)
1168
+ compute_dtype = utils.compute_dtype()
1169
+ eps = np.finfo(tf.float32.as_numpy_dtype).eps
1170
+ # Note that `(num_buckets - 1 - max_exact)` below differs from the
1171
+ # reference implementation of T5 relative position biases which uses
1172
+ # `(num_buckets - max_exact)`, and therefore doesn't produce the
1173
+ # max_distance behavior described in the docstring above.
1174
+ val_if_large = max_exact + tf.dtypes.cast(
1175
+ tf.math.log(tf.cast(n, compute_dtype) / max_exact + eps)
1176
+ / math.log(max_distance / max_exact)
1177
+ * (num_buckets - 1 - max_exact),
1178
+ tf.int32,
1179
+ )
1180
+ val_if_large = tf.math.minimum(val_if_large, num_buckets - 1)
1181
+ ret += tf.where(is_small, n, val_if_large)
1182
+ return ret
1183
+
1184
+
1185
+ def _dot_product_attention(
1186
+ queries: tf.Tensor,
1187
+ keys: tf.Tensor,
1188
+ values: tf.Tensor,
1189
+ invalid_mask: tf.Tensor,
1190
+ logit_bias: Optional[tf.Tensor],
1191
+ training: bool,
1192
+ num_heads: int,
1193
+ units_per_head: int,
1194
+ attention_logits_soft_cap: float | None,
1195
+ attention_probabilities_dropout: tf.keras.layers.Dropout,
1196
+ ) -> tuple[tf.Tensor, tf.Tensor, tf.Tensor]:
1197
+ """Computes standard dot product attention with queries, keys and values.
1198
+
1199
+ Args:
1200
+ queries: A [batch, query_time, num_heads, units_per_head] tensor of queries.
1201
+ keys: A [batch, key_time, num_heads, units_per_head] tensor of keys.
1202
+ values: A [batch, key_time, num_heads, units_per_head] tensor of values.
1203
+ invalid_mask: A tensor broadcastable to [batch, num_heads, query_time,
1204
+ key_time] which is 1.0 for positions that are invalid (i.e. should not be
1205
+ attended to).
1206
+ logit_bias: A tensor broadcastable to [batch, num_heads, query_time,
1207
+ key_time] of attention logit biases to apply after computing the logits.
1208
+ training: Whether we are in training mode.
1209
+ num_heads: The number of attention heads.
1210
+ units_per_head: The number of units per head.
1211
+ attention_logits_soft_cap: If non-zero, a soft cap applied to attention
1212
+ logits to prevent outliers from dominating the softmax. Empirically, 50.0
1213
+ works well across a variety of tasks. Implemented as tanh(logits / cap) *
1214
+ cap.
1215
+ attention_probabilities_dropout: A dropout layer to apply to the attention
1216
+ probabilities.
1217
+
1218
+ Returns:
1219
+ context_vectors: A [batch_size, query_time, num_heads, units_per_head]
1220
+ tensor of context vectors for the queries.
1221
+ probabilities: A [batch_size, query_time, num_heads, keys_time] tensor of
1222
+ attention probabilities (for debugging).
1223
+ logits: A [batch_size, query_time, num_heads, keys_time] tensor of attention
1224
+ logits (for debugging).
1225
+ """
1226
+ queries.shape.assert_is_compatible_with(
1227
+ [None, None, num_heads, units_per_head]
1228
+ )
1229
+ keys.shape.assert_is_compatible_with([None, None, num_heads, units_per_head])
1230
+ values.shape.assert_is_compatible_with(
1231
+ [None, None, num_heads, units_per_head]
1232
+ )
1233
+
1234
+ # Attention weights are computed as
1235
+ # softmax((queries * keys^T) / sqrt(units_per_head)), but for efficiency we
1236
+ # scale the queries before the matmul with keys to get logits.
1237
+ queries *= tf.math.rsqrt(tf.cast(units_per_head, queries.dtype))
1238
+
1239
+ # Babelfish uses this order because it's more efficient on TPU.
1240
+ logits = tf.einsum('BjNH,BiNH->BNij', keys, queries)
1241
+
1242
+ if logit_bias is not None:
1243
+ # Layout matches logits.
1244
+ logit_bias.shape.assert_is_compatible_with([None, num_heads, None, None])
1245
+ # Check that relative logits is broadcastable to logits.
1246
+ tf.broadcast_static_shape(logit_bias.shape, logits.shape)
1247
+ logits += logit_bias
1248
+
1249
+ # Cap attention logits before masking.
1250
+ if attention_logits_soft_cap is not None:
1251
+ logits = _soft_cap_attention_logits(logits, attention_logits_soft_cap)
1252
+
1253
+ logits = _mask_attention_logits(logits, invalid_mask)
1254
+ probabilities = _softmax_in_at_least_float32(logits)
1255
+ probabilities = attention_probabilities_dropout(
1256
+ probabilities, training=training
1257
+ )
1258
+
1259
+ # Contract the keys_time dimension into per-head context vectors:
1260
+ # [batch, query_time, num_heads, units_per_head].
1261
+ context_vectors = tf.einsum('BNij,BjNH->BiNH', probabilities, values)
1262
+
1263
+ # Transpose [batch, num_heads, query_time, source_time] to
1264
+ # [batch, query_time, num_heads, source_time].
1265
+ probabilities = tf.transpose(probabilities, [0, 2, 1, 3])
1266
+ logits = tf.transpose(logits, [0, 2, 1, 3])
1267
+ return context_vectors, probabilities, logits
1268
+
1269
+
1270
+ class _StreamingSoftmaxState(NamedTuple):
1271
+ """State tuple for a streaming softmax.
1272
+
1273
+ Tracks the numerator and the denominator as well as the maximum logit seen so
1274
+ far separately for each query position.
1275
+ """
1276
+
1277
+ # [b, t, num_heads, units_per_head]
1278
+ numerator: tf.Tensor
1279
+ # [b, t, num_heads]
1280
+ denominator: tf.Tensor
1281
+ # [b, t, num_heads]
1282
+ max_so_far: tf.Tensor
1283
+
1284
+
1285
+ def _streaming_logits_and_softmax_step(
1286
+ state: _StreamingSoftmaxState,
1287
+ queries: tf.Tensor,
1288
+ keys: tf.Tensor,
1289
+ values: tf.Tensor,
1290
+ invalid_mask: tf.Tensor,
1291
+ logit_bias: tf.Tensor | None,
1292
+ num_heads: int,
1293
+ query_chunk_size: int,
1294
+ attention_logits_soft_cap: float | None,
1295
+ compute_dtype: tf.DType,
1296
+ ) -> _StreamingSoftmaxState:
1297
+ """Computes an update to the state given queries/keys/values."""
1298
+ state.max_so_far.shape.assert_is_compatible_with(
1299
+ [None, query_chunk_size, num_heads]
1300
+ )
1301
+
1302
+ # Perform the query/key multiplication in compute_dtype to match the
1303
+ # _dot_product_attention implementation. If we need higher precision here in
1304
+ # _chunked_attention, we should also do it in _attention.
1305
+ logits = tf.einsum('BiNH,BjNH->BiNj', queries, keys)
1306
+
1307
+ if logit_bias is not None:
1308
+ # Check that relative logits is broadcastable to logits.
1309
+ tf.broadcast_static_shape(logit_bias.shape, logits.shape)
1310
+ logits += logit_bias
1311
+
1312
+ # Cap attention logits before masking.
1313
+ if attention_logits_soft_cap is not None:
1314
+ logits = _soft_cap_attention_logits(logits, attention_logits_soft_cap)
1315
+
1316
+ logits = _mask_attention_logits(logits, invalid_mask)
1317
+
1318
+ if compute_dtype.size < 4:
1319
+ logits = tf.cast(logits, tf.float32)
1320
+ values = tf.cast(values, tf.float32)
1321
+
1322
+ # Maximum key logit for each (batch/query/head) slice.
1323
+ chunk_max = tf.reduce_max(logits, axis=-1)
1324
+
1325
+ chunk_max.shape.assert_is_compatible_with([None, None, num_heads])
1326
+ max_so_far = tf.math.maximum(state.max_so_far, chunk_max)
1327
+ max_so_far = tf.stop_gradient(max_so_far)
1328
+ max_so_far.shape.assert_is_compatible_with([None, None, num_heads])
1329
+ correction = tf.math.exp(state.max_so_far - max_so_far)
1330
+
1331
+ corrected_weights = tf.math.exp(logits - max_so_far[:, :, :, tf.newaxis])
1332
+
1333
+ numerator = state.numerator * correction[:, :, :, tf.newaxis]
1334
+ # Compute weighted values and add them to the numerator.
1335
+ numerator += tf.einsum('BiNj,BjNH->BiNH', corrected_weights, values)
1336
+
1337
+ denominator = state.denominator * correction
1338
+ # Add sum of all weights for keys to the denominator.
1339
+ # Invalid locations are zero because e^(-inf - max) = 0.
1340
+ denominator += tf.reduce_sum(corrected_weights, axis=-1)
1341
+
1342
+ return _StreamingSoftmaxState(numerator, denominator, max_so_far)
1343
+
1344
+
1345
+ def _pad_dim_to(
1346
+ t: tf.Tensor,
1347
+ axis: int,
1348
+ cur_length: tf.Tensor,
1349
+ target_length: tf.Tensor,
1350
+ pad_value: float,
1351
+ ) -> tf.Tensor:
1352
+ paddings = [[0, 0]] * t.shape.rank
1353
+ paddings[axis] = [0, tf.maximum(target_length - cur_length, 0)]
1354
+ return tf.pad(t, paddings, constant_values=tf.constant(pad_value, t.dtype))
1355
+
1356
+
1357
+ def _chunked_dot_product_attention(
1358
+ queries: tf.Tensor,
1359
+ keys: tf.Tensor,
1360
+ keys_mask: tf.Tensor,
1361
+ values: tf.Tensor,
1362
+ invalid_mask_fn: Callable[
1363
+ [tf.Tensor, tf.Tensor, tf.Tensor, tf.Tensor, tf.Tensor], tf.Tensor
1364
+ ],
1365
+ logit_bias_fn: Callable[
1366
+ [tf.Tensor, tf.Tensor, tf.Tensor, tf.Tensor],
1367
+ tf.Tensor,
1368
+ ]
1369
+ | None,
1370
+ num_heads: int,
1371
+ units_per_head: int,
1372
+ attention_logits_soft_cap: float | None,
1373
+ query_chunk_size: int,
1374
+ key_chunk_size: int | None,
1375
+ ) -> tf.Tensor:
1376
+ """Computes chunked dot product attention with queries, keys and values.
1377
+
1378
+ Chunked dot product attention avoids materializing the full [query_time,
1379
+ key_time] tensor of attention logits by computing the context vectors for the
1380
+ queries incrementally in chunks of [query_chunk_size, key_chunk_size].
1381
+ - This avoids using O(n^2) memory, allowing increased scale of dense
1382
+ attention.
1383
+ - Using the decomposed softmax trick, the the memory access patterns of
1384
+ computing the softmax are improved which can combine well with XLA kernel
1385
+ fusion. to reduce the total number of reads and writes from HBM and improve
1386
+ memory bandwidth consumption.
1387
+
1388
+ References:
1389
+ - https://arxiv.org/abs/2112.05682
1390
+ - https://arxiv.org/abs/2205.14135
1391
+
1392
+ Args:
1393
+ queries: A [batch, query_time, num_heads, units_per_head] tensor of queries.
1394
+ keys: A [batch, key_time, num_heads, units_per_head] tensor of keys.
1395
+ keys_mask: A [batch, key_time] tensor indicating valid positiosn in the keys
1396
+ sequence. Implementation detail required for gradient checkpointing.
1397
+ values: A [batch, key_time, num_heads, units_per_head] tensor of values.
1398
+ invalid_mask_fn: A callable that returns a tensor broadcastable to [batch,
1399
+ query_time, num_heads, key_time] which is 1.0 for positions that are
1400
+ invalid (i.e. should not be attended to).
1401
+ logit_bias_fn: A callable that returns a tensor broadcastable to [batch,
1402
+ query_time, num_heads, key_time] of attention logit biases to apply after
1403
+ computing the logits.
1404
+ num_heads: The number of attention heads.
1405
+ units_per_head: The number of units per head.
1406
+ attention_logits_soft_cap: If non-zero, a soft cap applied to attention
1407
+ logits to prevent outliers from dominating the softmax. Empirically, 50.0
1408
+ works well across a variety of tasks. Implemented as tanh(logits / cap) *
1409
+ cap.
1410
+ query_chunk_size: The query chunk size to use. Computes attention in
1411
+ parallel for blocks of queries of this size.
1412
+ key_chunk_size: The key chunk size to use. If None, computes chunked
1413
+ attention over the entire key sequence for each block of queries. If
1414
+ non-None, computes attention for blocks of [query_chunk_size,
1415
+ key_chunk_size] at a time, bounding the overall memory usage to
1416
+ O(query_chunk_size * key_chunk_size).
1417
+
1418
+ Returns:
1419
+ context_vectors: A [batch_size, query_time, num_heads, units_per_head]
1420
+ tensor of context vectors for the queries.
1421
+ """
1422
+ if query_chunk_size <= 0:
1423
+ raise ValueError(f'{query_chunk_size=} must be positive.')
1424
+ compute_dtype = queries.dtype
1425
+
1426
+ # This implementation supports the "extra logit" feature but
1427
+ # _dot_product_attention doesn't.
1428
+ # TODO(rryan): Enable this functionality.
1429
+ use_extra_logit = False
1430
+
1431
+ # [b, q, h, d]
1432
+ queries.shape.assert_is_compatible_with(
1433
+ [None, None, num_heads, units_per_head]
1434
+ )
1435
+ # [b, k, h, d]
1436
+ keys.shape.assert_is_compatible_with([None, None, num_heads, units_per_head])
1437
+ # [b, v, h, d]
1438
+ values.shape.assert_is_compatible_with(
1439
+ [None, None, num_heads, units_per_head]
1440
+ )
1441
+
1442
+ # Attention weights are computed as
1443
+ # softmax((queries * keys^T) / sqrt(units_per_head)), but for efficiency we
1444
+ # scale the queries before the matmul with keys to get logits.
1445
+ queries *= tf.math.rsqrt(tf.cast(units_per_head, queries.dtype))
1446
+
1447
+ query_batch_size, query_time = utils.smart_dimension_size(queries, [0, 1])
1448
+ key_batch_size, key_time = utils.smart_dimension_size(keys, [0, 1])
1449
+ tf.debugging.assert_equal(query_batch_size, key_batch_size)
1450
+
1451
+ num_query_chunks = (query_time + query_chunk_size - 1) // query_chunk_size
1452
+
1453
+ # TODO(b/298748783): Work around slice failure by padding input to multiple of
1454
+ # slice length.
1455
+ query_time_padded = num_query_chunks * query_chunk_size
1456
+ queries = _pad_dim_to(
1457
+ queries,
1458
+ axis=1,
1459
+ cur_length=query_time,
1460
+ target_length=query_time_padded,
1461
+ pad_value=0.0,
1462
+ )
1463
+
1464
+ num_key_chunks = 1
1465
+ if key_chunk_size is not None:
1466
+ num_key_chunks = (key_time + key_chunk_size - 1) // key_chunk_size
1467
+ key_time_padded = num_key_chunks * key_chunk_size
1468
+ keys = _pad_dim_to(
1469
+ keys,
1470
+ axis=1,
1471
+ cur_length=key_time,
1472
+ target_length=key_time_padded,
1473
+ pad_value=0.0,
1474
+ )
1475
+ keys_mask = _pad_dim_to(
1476
+ keys_mask,
1477
+ axis=1,
1478
+ cur_length=key_time,
1479
+ target_length=key_time_padded,
1480
+ pad_value=0.0,
1481
+ )
1482
+ keys_mask = tf.stop_gradient(keys_mask)
1483
+ values = _pad_dim_to(
1484
+ values,
1485
+ axis=1,
1486
+ cur_length=key_time,
1487
+ target_length=key_time_padded,
1488
+ pad_value=0.0,
1489
+ )
1490
+ del key_time
1491
+
1492
+ state_dtype = tf.float32 if queries.dtype.size < 4 else queries.dtype
1493
+ zero_chunk = _StreamingSoftmaxState(
1494
+ tf.zeros(
1495
+ [
1496
+ query_batch_size,
1497
+ query_chunk_size,
1498
+ num_heads,
1499
+ units_per_head,
1500
+ ],
1501
+ dtype=state_dtype,
1502
+ ),
1503
+ tf.zeros(
1504
+ [
1505
+ query_batch_size,
1506
+ query_chunk_size,
1507
+ num_heads,
1508
+ ],
1509
+ dtype=state_dtype,
1510
+ ),
1511
+ tf.fill(
1512
+ [
1513
+ query_batch_size,
1514
+ query_chunk_size,
1515
+ num_heads,
1516
+ ],
1517
+ tf.constant(-np.inf, dtype=state_dtype),
1518
+ ),
1519
+ )
1520
+
1521
+ def query_loop_cond(query_i, output_ta):
1522
+ del output_ta
1523
+ return query_i < num_query_chunks
1524
+
1525
+ def query_loop_body(
1526
+ query_i,
1527
+ output_ta: tf.TensorArray,
1528
+ ):
1529
+ query_start = query_i * query_chunk_size
1530
+ query_chunk = None
1531
+
1532
+ @tf.recompute_grad
1533
+ def no_key_chunking(
1534
+ queries: tf.Tensor,
1535
+ keys: tf.Tensor,
1536
+ keys_mask: tf.Tensor,
1537
+ values: tf.Tensor,
1538
+ *args,
1539
+ ) -> _StreamingSoftmaxState:
1540
+ # We can't pass None values through tf.recompute_grad so optionally unpack
1541
+ # it from *args.
1542
+ logit_bias_chunk = args[0] if args else None
1543
+ query_chunk = utils.slice_and_pad_tensor(
1544
+ queries,
1545
+ [(1, query_start, query_chunk_size)],
1546
+ pad_value=0.0,
1547
+ # TODO(b/298748783): Queries tensor is pre-padded.
1548
+ tensor_is_pre_padded=True,
1549
+ name='no_key_chunking_query_chunk',
1550
+ )
1551
+ key_chunk = keys
1552
+ value_chunk = values
1553
+ invalid_mask_chunk = invalid_mask_fn(
1554
+ query_start,
1555
+ query_chunk_size,
1556
+ 0,
1557
+ utils.smart_dimension_size(keys, 1),
1558
+ # Don't know why keys_mask needs to be plumbed through to here despite
1559
+ # the top level stop gradient. It only seems to affect
1560
+ # DotProductAttention (error about dependence on source.mask).
1561
+ tf.stop_gradient(keys_mask),
1562
+ )
1563
+
1564
+ # TODO(rryan): See what XLA does when we use tf.nn.softmax in this case?
1565
+ return _streaming_logits_and_softmax_step(
1566
+ state=zero_chunk,
1567
+ queries=query_chunk,
1568
+ keys=key_chunk,
1569
+ values=value_chunk,
1570
+ invalid_mask=invalid_mask_chunk,
1571
+ logit_bias=logit_bias_chunk,
1572
+ num_heads=num_heads,
1573
+ query_chunk_size=query_chunk_size,
1574
+ attention_logits_soft_cap=attention_logits_soft_cap,
1575
+ compute_dtype=compute_dtype,
1576
+ )
1577
+
1578
+ def kv_loop_cond(kv_i: tf.Tensor, chunk_state: _StreamingSoftmaxState):
1579
+ del chunk_state
1580
+ return kv_i < num_key_chunks
1581
+
1582
+ def kv_loop_body(kv_i: tf.Tensor, chunk_state: _StreamingSoftmaxState):
1583
+ kv_start = kv_i * key_chunk_size
1584
+
1585
+ @tf.recompute_grad
1586
+ def kv_loop_body_inner(
1587
+ query_chunk: tf.Tensor,
1588
+ keys: tf.Tensor,
1589
+ values: tf.Tensor,
1590
+ chunk_state: _StreamingSoftmaxState,
1591
+ *args,
1592
+ ) -> _StreamingSoftmaxState:
1593
+ # We can't pass None values through tf.recompute_grad so optionally
1594
+ # unpack it from *args.
1595
+ logit_bias_chunk = args[0] if args else None
1596
+ key_chunk = utils.slice_and_pad_tensor(
1597
+ keys,
1598
+ [(1, kv_start, key_chunk_size)],
1599
+ pad_value=0.0,
1600
+ # TODO(b/298748783): Queries tensor is pre-padded.
1601
+ tensor_is_pre_padded=True,
1602
+ name='kv_loop_key_chunk',
1603
+ )
1604
+ value_chunk = utils.slice_and_pad_tensor(
1605
+ values,
1606
+ [(1, kv_start, key_chunk_size)],
1607
+ pad_value=0.0,
1608
+ # TODO(b/298748783): Queries tensor is pre-padded.
1609
+ tensor_is_pre_padded=True,
1610
+ name='kv_loop_value_chunk',
1611
+ )
1612
+ invalid_mask_chunk = invalid_mask_fn(
1613
+ query_start,
1614
+ query_chunk_size,
1615
+ kv_start,
1616
+ key_chunk_size,
1617
+ tf.stop_gradient(keys_mask),
1618
+ )
1619
+
1620
+ chunk_state = _streaming_logits_and_softmax_step(
1621
+ state=chunk_state,
1622
+ queries=query_chunk,
1623
+ keys=key_chunk,
1624
+ values=value_chunk,
1625
+ invalid_mask=invalid_mask_chunk,
1626
+ logit_bias=logit_bias_chunk,
1627
+ num_heads=num_heads,
1628
+ query_chunk_size=query_chunk_size,
1629
+ attention_logits_soft_cap=attention_logits_soft_cap,
1630
+ compute_dtype=compute_dtype,
1631
+ )
1632
+ return chunk_state
1633
+
1634
+ args = [query_chunk, keys, values, chunk_state]
1635
+ if logit_bias_fn is not None:
1636
+ logit_bias_chunk = logit_bias_fn(
1637
+ query_start,
1638
+ query_chunk_size,
1639
+ kv_start,
1640
+ key_chunk_size,
1641
+ )
1642
+ args.append(logit_bias_chunk)
1643
+ chunk_state = kv_loop_body_inner(*args)
1644
+ return kv_i + 1, chunk_state
1645
+
1646
+ if key_chunk_size is None:
1647
+ # Query chunk happens inside no_key_chunking so it is re-sliced in the
1648
+ # backward pass.
1649
+ args = [queries, keys, keys_mask, values]
1650
+ if logit_bias_fn is not None:
1651
+ logit_bias_chunk = logit_bias_fn(
1652
+ query_start,
1653
+ query_chunk_size,
1654
+ 0,
1655
+ utils.smart_dimension_size(keys, 1),
1656
+ )
1657
+ args.append(logit_bias_chunk)
1658
+ state = no_key_chunking(*args)
1659
+ else:
1660
+ # Read query_chunk outside of loop.
1661
+ query_chunk = utils.slice_and_pad_tensor(
1662
+ queries,
1663
+ [(1, query_start, query_chunk_size)],
1664
+ pad_value=0.0,
1665
+ # TODO(b/298748783): Queries tensor is pre-padded.
1666
+ tensor_is_pre_padded=True,
1667
+ name='query_chunk_for_key_chunk_loop',
1668
+ )
1669
+ _, state = tf.while_loop(
1670
+ kv_loop_cond,
1671
+ kv_loop_body,
1672
+ (tf.constant(0), zero_chunk),
1673
+ maximum_iterations=num_key_chunks,
1674
+ name='key_chunk_loop',
1675
+ )
1676
+
1677
+ numerator, denominator, max_so_far = state
1678
+ if use_extra_logit:
1679
+ denominator += tf.math.exp(-max_so_far)
1680
+ output_i = numerator / denominator[:, :, :, tf.newaxis]
1681
+ output_i = tf.cast(output_i, compute_dtype)
1682
+ output_i.shape.assert_is_compatible_with(
1683
+ [None, None, num_heads, units_per_head]
1684
+ )
1685
+
1686
+ output_ta = output_ta.write(query_i, output_i)
1687
+ return query_i + 1, output_ta
1688
+
1689
+ output_ta = tf.TensorArray(
1690
+ dtype=compute_dtype, size=num_query_chunks, dynamic_size=False
1691
+ )
1692
+
1693
+ _, output_ta = tf.while_loop(
1694
+ query_loop_cond,
1695
+ query_loop_body,
1696
+ (tf.constant(0), output_ta),
1697
+ maximum_iterations=num_query_chunks,
1698
+ name='query_chunk_loop',
1699
+ )
1700
+ output = output_ta.stack()
1701
+ output.shape.assert_is_compatible_with([
1702
+ num_query_chunks if isinstance(num_query_chunks, int) else None,
1703
+ None, # batch_size
1704
+ query_chunk_size,
1705
+ num_heads,
1706
+ units_per_head,
1707
+ ])
1708
+
1709
+ # Transpose to [b, num_query_chunks, query_chunk_size, num_heads,
1710
+ # units_per_head] and combine num_query_chunks and query_chunk_size.
1711
+ output = tf.transpose(output, [1, 0, 2, 3, 4])
1712
+ context_vectors = tf.reshape(
1713
+ output,
1714
+ [
1715
+ query_batch_size,
1716
+ num_query_chunks * query_chunk_size,
1717
+ num_heads,
1718
+ units_per_head,
1719
+ ],
1720
+ )
1721
+ # Slice off padded query timesteps from the last block.
1722
+ context_vectors = context_vectors[:, :query_time, :, :]
1723
+
1724
+ return context_vectors
1725
+
1726
+
1727
+ def _dot_product_attention_logit_bias_fn(
1728
+ query_time: tf.Tensor,
1729
+ query_length: tf.Tensor | int,
1730
+ key_time: tf.Tensor,
1731
+ key_length: tf.Tensor | int,
1732
+ *,
1733
+ relative_position_embedding: RelativePositionEmbedding,
1734
+ ) -> tf.Tensor:
1735
+ """Returns logit biases [b, q, h, k] for the provided positions."""
1736
+ return relative_position_embedding.get_position_bias_raw(
1737
+ query_time, query_length, key_time, key_length
1738
+ )
1739
+
1740
+
1741
+ def _dot_product_attention_invalid_mask_fn(
1742
+ query_time: tf.Tensor,
1743
+ query_length: tf.Tensor,
1744
+ key_time: tf.Tensor,
1745
+ key_length: tf.Tensor,
1746
+ key_mask: tf.Tensor,
1747
+ *,
1748
+ max_past_horizon: int,
1749
+ max_future_horizon: int,
1750
+ ) -> tf.Tensor:
1751
+ """Returns an invalid mask [b, q, 1, k] for the provided parameters."""
1752
+ compute_dtype = utils.compute_dtype()
1753
+ if max_past_horizon == -1 and max_future_horizon == -1:
1754
+ visibility_mask = None
1755
+ else:
1756
+ query_ix = query_time + tf.range(query_length)
1757
+ key_ix = key_time + tf.range(key_length)
1758
+
1759
+ # Positive offset means key position lies ahead of query position.
1760
+ offsets = key_ix[tf.newaxis, :] - query_ix[:, tf.newaxis]
1761
+
1762
+ visibility_mask = None
1763
+ if max_past_horizon != -1:
1764
+ visibility_mask = offsets >= -max_past_horizon
1765
+ if max_future_horizon != -1:
1766
+ condition = offsets <= max_future_horizon
1767
+ visibility_mask = (
1768
+ condition
1769
+ if visibility_mask is None
1770
+ else tf.logical_and(visibility_mask, condition)
1771
+ )
1772
+
1773
+ visibility_mask = tf.cast(visibility_mask, compute_dtype)[
1774
+ tf.newaxis, :, tf.newaxis, :
1775
+ ]
1776
+ # Check the mask is [1 (broadcast to batch), query_length, 1 (broadcast to
1777
+ # heads), key_length].
1778
+ visibility_mask.shape.assert_is_compatible_with([1, None, 1, None])
1779
+
1780
+ valid_mask = tf.cast(key_mask, compute_dtype)
1781
+ valid_mask = tf.slice(valid_mask, [0, key_time], [-1, key_length])
1782
+
1783
+ valid_mask = valid_mask[:, tf.newaxis, tf.newaxis, :]
1784
+ # Check the mask is [batch, 1 (broadcast to query), 1 (broadcast to heads),
1785
+ # key_length].
1786
+ valid_mask.shape.assert_is_compatible_with([None, 1, 1, None])
1787
+
1788
+ invalid_mask = 1.0 - (
1789
+ visibility_mask * valid_mask
1790
+ if visibility_mask is not None
1791
+ else valid_mask
1792
+ )
1793
+ if visibility_mask is not None:
1794
+ invalid_mask.shape.assert_is_compatible_with([None, None, 1, None])
1795
+ else:
1796
+ invalid_mask.shape.assert_is_compatible_with([None, 1, 1, None])
1797
+ return invalid_mask
1798
+
1799
+
1800
+ class DotProductSelfAttention(types.Emitting):
1801
+ """A multi-headed dot-product self attention layer.
1802
+
1803
+ TODO(rryan): Support for stepping layers with max_horizon == -1.
1804
+ """
1805
+
1806
+ def __init__(
1807
+ self,
1808
+ num_heads: int,
1809
+ units_per_head: int,
1810
+ max_horizon: int,
1811
+ use_relative_position_embedding: bool = False,
1812
+ relative_position_embedding: Optional[RelativePositionEmbedding] = None,
1813
+ max_future_horizon: int = 0,
1814
+ attention_probabilities_dropout_rate: float = 0.0,
1815
+ broadcast_dropout_across_queries: bool = False,
1816
+ use_bias: bool = False,
1817
+ kernel_initializer: tf.keras.initializers.Initializer = 'glorot_uniform',
1818
+ bias_initializer: tf.keras.initializers.Initializer = 'zeros',
1819
+ attention_logits_soft_cap: float | None = None,
1820
+ query_chunk_size: int | None = None,
1821
+ key_chunk_size: int | None = None,
1822
+ query_network: types.SequenceLayer | None = None,
1823
+ key_network: types.SequenceLayer | None = None,
1824
+ value_network: types.SequenceLayer | None = None,
1825
+ name: Optional[str] = None,
1826
+ ):
1827
+ """A dot-product self attention layer as in Transformers.
1828
+
1829
+ Args:
1830
+ num_heads: The number of attention heads.
1831
+ units_per_head: The number of units per head.
1832
+ max_horizon: The number of past timesteps each timestep can see. -1:
1833
+ Disable masking of the past (all past timesteps are visible)
1834
+ 0: No past timesteps are visible. The layer is only steppable when
1835
+ max_horizon >= 0.
1836
+ use_relative_position_embedding: Whether to use a relative position
1837
+ embedding.
1838
+ relative_position_embedding: An optional RelativePositionEmbedding to use
1839
+ to compute relative position biases. If not provided and
1840
+ use_relative_position_embedding is true, a ShawRelativePositionEmbedding
1841
+ is created.
1842
+ max_future_horizon: The number of future timesteps each timestep can see.
1843
+ -1: Disable masking of the future (all future timesteps are visible)
1844
+ 0: No future timesteps are visible. The layer is only steppable when
1845
+ max_future_horizon == 0.
1846
+ attention_probabilities_dropout_rate: The dropout rate for the attention
1847
+ probabilities.
1848
+ broadcast_dropout_across_queries: Whether to broadcast the dropout across
1849
+ the query time dimension as is done in T5.
1850
+ use_bias: Whether to learn a bias in the query/key/value projection.
1851
+ kernel_initializer: Kernel initializer for the query/key/value projection.
1852
+ bias_initializer: Bias initialier for the query/key/value projection.
1853
+ attention_logits_soft_cap: If non-zero, a soft cap applied to attention
1854
+ logits to prevent outliers from dominating the softmax. Empirically,
1855
+ 50.0 works well across a variety of tasks. Implemented as tanh(logits /
1856
+ cap) * cap.
1857
+ query_chunk_size: The query chunk size to use. Computes attention in
1858
+ parallel for blocks of queries of this size. If enabled, no emits are
1859
+ produced (e.g. attention probabilities for debugging).
1860
+ key_chunk_size: The key chunk size to use. If None, computes chunked
1861
+ attention over the entire key sequence for each block of queries. If
1862
+ non-None, computes attention for blocks of [query_chunk_size,
1863
+ key_chunk_size] at a time, bounding the overall memory usage to
1864
+ O(query_chunk_size * key_chunk_size). If enabled, no emits are produced
1865
+ (e.g. attention probabilities for debugging).
1866
+ query_network: An optional layer for processing queries before logit
1867
+ calculations are performed. Must have an output ratio and block size
1868
+ of 1.
1869
+ key_network: An optional layer for processing keys before logit
1870
+ calculations are performed. Must have an output ratio and block size
1871
+ of 1.
1872
+ value_network: An optional layer for processing values before attention
1873
+ weighted summation is performed. Must have an output ratio and block
1874
+ size of 1.
1875
+ name: An optional name for the layer.
1876
+ """
1877
+ super().__init__(name=name)
1878
+ _validate_heads(num_heads, units_per_head, name)
1879
+ if max_horizon < -1:
1880
+ raise ValueError(
1881
+ f'Expected max_horizon >= -1 for {name}, got {max_horizon}.'
1882
+ )
1883
+ if max_future_horizon < -1:
1884
+ raise ValueError(
1885
+ 'Expected max_future_horizon >= -1 for '
1886
+ f'{name}, got {max_future_horizon}.'
1887
+ )
1888
+ if max_future_horizon == 0 and max_horizon == 0:
1889
+ raise ValueError(
1890
+ 'Both max_horizon and max_future_horizon are 0, which '
1891
+ f'does not make sense for {self}.'
1892
+ )
1893
+ if (
1894
+ not use_relative_position_embedding
1895
+ and relative_position_embedding is not None
1896
+ ):
1897
+ raise ValueError(
1898
+ f'Inconsistent value for {use_relative_position_embedding=} and '
1899
+ f'{relative_position_embedding=}.'
1900
+ )
1901
+
1902
+ chunking_enabled = query_chunk_size or key_chunk_size
1903
+ if attention_probabilities_dropout_rate > 0.0 and chunking_enabled:
1904
+ raise NotImplementedError(
1905
+ 'Attention probability dropout is incompatible with chunking.'
1906
+ )
1907
+
1908
+ self._num_heads = num_heads
1909
+ self._units_per_head = units_per_head
1910
+ self._max_past_horizon = max_horizon
1911
+ self._max_future_horizon = max_future_horizon
1912
+ self._use_relative_position_embedding = use_relative_position_embedding
1913
+ self._attention_logits_soft_cap = attention_logits_soft_cap
1914
+ self._query_chunk_size = query_chunk_size
1915
+ self._key_chunk_size = key_chunk_size
1916
+ if (
1917
+ attention_logits_soft_cap is not None
1918
+ and attention_logits_soft_cap <= 0.0
1919
+ ):
1920
+ raise ValueError(
1921
+ f'{attention_logits_soft_cap=} should be a positive number.'
1922
+ )
1923
+ with self.name_scope:
1924
+ # TODO(rryan): Benchmark whether we should split these up.
1925
+ self._qkv = dense.DenseShaped(
1926
+ [3, self._num_heads, self._units_per_head],
1927
+ use_bias=use_bias,
1928
+ kernel_initializer=kernel_initializer,
1929
+ bias_initializer=bias_initializer,
1930
+ name='query_key_value_projection',
1931
+ )
1932
+ if broadcast_dropout_across_queries:
1933
+ # [batch, num_heads, query_time, source_time]
1934
+ noise_shape = [None, None, 1, None]
1935
+ else:
1936
+ noise_shape = None
1937
+ self._attention_probabilities_dropout = tf.keras.layers.Dropout(
1938
+ attention_probabilities_dropout_rate,
1939
+ noise_shape=noise_shape,
1940
+ name='attention_probabilities_dropout',
1941
+ )
1942
+ if use_relative_position_embedding:
1943
+ if relative_position_embedding:
1944
+ self._relative_position_embedding = relative_position_embedding
1945
+ else:
1946
+ if use_relative_position_embedding and max_future_horizon != 0:
1947
+ raise ValueError(
1948
+ 'Future-dependent relative position embeddings are not '
1949
+ 'supported yet.'
1950
+ )
1951
+ self._relative_position_embedding = ShawRelativePositionEmbedding(
1952
+ max_backward=self._max_past_horizon,
1953
+ max_forward=self._max_future_horizon,
1954
+ num_heads=num_heads,
1955
+ units_per_head=units_per_head,
1956
+ )
1957
+ else:
1958
+ self._relative_position_embedding = None
1959
+
1960
+ if callable(query_network):
1961
+ query_network = query_network()
1962
+ if callable(key_network):
1963
+ key_network = key_network()
1964
+ if callable(value_network):
1965
+ value_network = value_network()
1966
+
1967
+ if query_network and (
1968
+ query_network.output_ratio != 1 or query_network.block_size != 1
1969
+ ):
1970
+ raise ValueError(
1971
+ 'Query network must have an output_ratio'
1972
+ f' ({query_network.output_ratio}) and block_size'
1973
+ f' ({query_network.block_size}) of 1.'
1974
+ )
1975
+
1976
+ if key_network and (
1977
+ key_network.output_ratio != 1 or key_network.block_size != 1
1978
+ ):
1979
+ raise ValueError(
1980
+ 'Key network must have an output_ratio'
1981
+ f' ({key_network.output_ratio}) and block_size'
1982
+ f' ({key_network.block_size}) of 1.'
1983
+ )
1984
+
1985
+ if value_network and (
1986
+ value_network.output_ratio != 1 or value_network.block_size != 1
1987
+ ):
1988
+ raise ValueError(
1989
+ 'Value network must have an output_ratio'
1990
+ f' ({value_network.output_ratio}) and block_size'
1991
+ f' ({value_network.block_size}) of 1.'
1992
+ )
1993
+
1994
+ self._query_network = query_network
1995
+ self._key_network = key_network
1996
+ self._value_network = value_network
1997
+
1998
+ @property
1999
+ def supports_step(self) -> bool:
2000
+ supports_step = (
2001
+ self._max_future_horizon == 0 and self._max_past_horizon >= 0
2002
+ )
2003
+ if self._query_network:
2004
+ supports_step = supports_step and self._query_network.supports_step
2005
+
2006
+ if self._key_network:
2007
+ supports_step = supports_step and self._key_network.supports_step
2008
+
2009
+ if self._value_network:
2010
+ supports_step = supports_step and self._value_network.supports_step
2011
+
2012
+ return supports_step
2013
+
2014
+ def get_initial_state(
2015
+ self, x: types.Sequence, constants: Optional[types.Constants] = None
2016
+ ) -> types.State:
2017
+ # State to contain the max_horizon previous projected keys and values.
2018
+ batch_size = utils.smart_dimension_size(x.values, 0)
2019
+ # Note, the state is invalid since it is padding, so we don't want to attend
2020
+ # to it.
2021
+ max_past_horizon = max(0, self._max_past_horizon)
2022
+ zero_values = tf.zeros(
2023
+ (batch_size, max_past_horizon, self._num_heads, self._units_per_head),
2024
+ dtype=x.values.dtype,
2025
+ )
2026
+ zero_mask = tf.zeros([batch_size, max_past_horizon], dtype=types.MASK_DTYPE)
2027
+ state_keys = zero_values
2028
+ state_values = zero_values
2029
+ state_mask = zero_mask
2030
+ position = tf.constant(0, tf.int32)
2031
+
2032
+ qkv_input = types.Sequence(
2033
+ tf.zeros(
2034
+ (batch_size, 0, self._num_heads, self._units_per_head),
2035
+ x.values.dtype,
2036
+ ),
2037
+ tf.zeros((batch_size, 0), types.MASK_DTYPE),
2038
+ )
2039
+
2040
+ if self._query_network:
2041
+ query_state = self._query_network.get_initial_state(
2042
+ qkv_input,
2043
+ constants=constants,
2044
+ )
2045
+ else:
2046
+ query_state = ()
2047
+ if self._key_network:
2048
+ key_state = self._key_network.get_initial_state(
2049
+ qkv_input,
2050
+ constants=constants,
2051
+ )
2052
+ else:
2053
+ key_state = ()
2054
+ if self._value_network:
2055
+ value_state = self._value_network.get_initial_state(
2056
+ qkv_input,
2057
+ constants=constants,
2058
+ )
2059
+ else:
2060
+ value_state = ()
2061
+
2062
+ return (
2063
+ state_keys,
2064
+ state_values,
2065
+ state_mask,
2066
+ position,
2067
+ query_state,
2068
+ key_state,
2069
+ value_state,
2070
+ )
2071
+
2072
+ def get_output_shape(
2073
+ self,
2074
+ input_shape: tf.TensorShape,
2075
+ constants: Optional[types.Constants] = None,
2076
+ ) -> tf.TensorShape:
2077
+ if input_shape.rank != 1:
2078
+ raise ValueError(
2079
+ 'DotProductSelfAttention requires rank 3 input got: %s'
2080
+ % tf.TensorShape([None, None]).concatenate(input_shape)
2081
+ )
2082
+ return tf.TensorShape([self._num_heads, self._units_per_head])
2083
+
2084
+ def get_emit_specs(
2085
+ self,
2086
+ input_spec: tf.TensorShape,
2087
+ constants: Optional[types.Constants] = None,
2088
+ ) -> types.Emits:
2089
+ # If query / key chunking is not enabled, emit attention probabilities.
2090
+ if self._query_chunk_size is None and self._key_chunk_size is None:
2091
+ # The input time dimension is unknown so we can't provide a known
2092
+ # shape for comb_weights.
2093
+ return AttentionEmits(
2094
+ types.Sequence(
2095
+ tf.TensorSpec(
2096
+ tf.TensorShape([self._num_heads, None]), input_spec.dtype
2097
+ ),
2098
+ tf.TensorSpec(tf.TensorShape([]), tf.float32),
2099
+ )
2100
+ )
2101
+ return ()
2102
+
2103
+ @tf.Module.with_name_scope
2104
+ def step_with_emits(
2105
+ self,
2106
+ x: types.Sequence,
2107
+ state: types.State,
2108
+ training: bool,
2109
+ constants: Optional[types.Constants] = None,
2110
+ ) -> Tuple[types.Sequence, types.State, types.Emits]:
2111
+ if self._max_future_horizon != 0:
2112
+ raise ValueError(
2113
+ f'{self} is not steppable since max_future_horizon != 0.'
2114
+ )
2115
+ if self._max_past_horizon == -1:
2116
+ raise ValueError(f'{self} is not steppable since max_horizon is not set.')
2117
+ batch_size_static = x.values.shape.dims[0].value
2118
+ x_values_time = utils.smart_dimension_size(x.values, 1)
2119
+ x_values_time_static = x.values.shape.dims[1].value
2120
+
2121
+ (
2122
+ state_keys,
2123
+ state_values,
2124
+ state_mask,
2125
+ position,
2126
+ query_state,
2127
+ key_state,
2128
+ value_state,
2129
+ ) = state
2130
+
2131
+ # Micro-optimization: If use_bias is false, we can elide masking inside
2132
+ # _qkv. Maybe in general?
2133
+ x_qkv = self._qkv.layer(x, training=training)
2134
+ x_queries, x_keys, x_values = tf.unstack(x_qkv.values, axis=2)
2135
+
2136
+ if self._query_network:
2137
+ x_queries, query_state = self._query_network.step(
2138
+ types.Sequence(x_queries, x_qkv.mask),
2139
+ query_state,
2140
+ training=training,
2141
+ constants=constants,
2142
+ )
2143
+ x_queries = x_queries.values
2144
+ if self._key_network:
2145
+ x_keys, key_state = self._key_network.step(
2146
+ types.Sequence(x_keys, x_qkv.mask),
2147
+ key_state,
2148
+ training=training,
2149
+ constants=constants,
2150
+ )
2151
+ x_keys = x_keys.values
2152
+ if self._value_network:
2153
+ x_values, value_state = self._value_network.step(
2154
+ types.Sequence(x_values, x_qkv.mask),
2155
+ value_state,
2156
+ training=training,
2157
+ constants=constants,
2158
+ )
2159
+ x_values = x_values.values
2160
+
2161
+ # To process a step, concatenate our max_horizon state with the input
2162
+ # x_values_time_static timesteps. We need to make a banded mask tensor with
2163
+ # max_horizon + block_size timesteps per row.
2164
+ state_keys = tf.concat([state_keys, x_keys], axis=1)
2165
+ state_values = tf.concat([state_values, x_values], axis=1)
2166
+ state_mask = tf.concat([state_mask, x_qkv.mask], axis=1)
2167
+
2168
+ state_values_time = x_values_time + self._max_past_horizon
2169
+ state_values_time_static = (
2170
+ x_values_time_static + self._max_past_horizon
2171
+ if x_values_time_static is not None
2172
+ else None
2173
+ )
2174
+
2175
+ relative_logits = None
2176
+ if self._relative_position_embedding:
2177
+ relative_logits = (
2178
+ self._relative_position_embedding.get_position_bias_streaming(
2179
+ x_queries, state_keys, position
2180
+ )
2181
+ )
2182
+
2183
+ if x_values_time_static is not None and x_values_time_static == 1:
2184
+ # If queries_time is 1, there is no need for causal masking because our
2185
+ # state covers the previous max_horizon timesteps (which we can look at)
2186
+ # and the 1 timestep in x that we concatenated. We can simply
2187
+ # use state's "invalid" mask, reshaped to [batch_size, 1, 1, keys_time] so
2188
+ # it broadcasts across heads and queries_time.
2189
+ combined_invalid_mask = 1.0 - state_mask[:, tf.newaxis, tf.newaxis, :]
2190
+ else:
2191
+ valid_mask = state_mask[:, tf.newaxis, tf.newaxis, :]
2192
+ # To obey causality, the output for each of the block_size input timesteps
2193
+ # may only depend on itself and max_horizon previous timesteps. Earlier
2194
+ # timesteps in block_size cannot depend on later timesteps.
2195
+ #
2196
+ # After the above concatenation, the state tensor is of length
2197
+ # max_horizon + block_size. For example, with max_horizon = 5 and
2198
+ # block_size = 3:
2199
+ #
2200
+ # 1 2 3 4 5 a b c
2201
+ #
2202
+ # Where numbers indicate previous state and letters indicate timesteps of
2203
+ # the current block.
2204
+ #
2205
+ # Timestep a can look at a and 1-5, but not b or c. Its mask looks like:
2206
+ # 1 1 1 1 1 1 0 0
2207
+ # Timestep b can look at b, a, and 2-5:
2208
+ # 0 1 1 1 1 1 1 0
2209
+ # Timestep c can look at c, b, a, and 3-5:
2210
+ # 0 0 1 1 1 1 1 1
2211
+ #
2212
+ # This matrix corresponds to a 3x8 banded matrix with zero lower-bandwidth
2213
+ # and max_horizon upper-bandwidth.
2214
+ causal_mask = _ones_matrix_band_part(
2215
+ x_values_time,
2216
+ state_values_time,
2217
+ num_lower=0,
2218
+ num_upper=self._max_past_horizon,
2219
+ out_shape=[1, 1, x_values_time, state_values_time],
2220
+ )
2221
+
2222
+ # Broadcasting across batch_size, heads and query time.
2223
+ combined_invalid_mask = 1.0 - valid_mask * causal_mask
2224
+
2225
+ combined_invalid_mask.shape.assert_is_compatible_with(
2226
+ [batch_size_static, 1, x_values_time_static, state_values_time_static]
2227
+ )
2228
+
2229
+ # TODO(b/297462463): Step-wise support for chunked attention.
2230
+ context_vectors, probabilities, _ = _dot_product_attention(
2231
+ queries=x_queries,
2232
+ keys=state_keys,
2233
+ values=state_values,
2234
+ invalid_mask=combined_invalid_mask,
2235
+ logit_bias=relative_logits,
2236
+ training=training,
2237
+ num_heads=self._num_heads,
2238
+ units_per_head=self._units_per_head,
2239
+ attention_logits_soft_cap=self._attention_logits_soft_cap,
2240
+ attention_probabilities_dropout=self._attention_probabilities_dropout,
2241
+ )
2242
+
2243
+ # Preserve last max_horizon as state for next step.
2244
+ state_keys = state_keys[:, -self._max_past_horizon :]
2245
+ state_values = state_values[:, -self._max_past_horizon :]
2246
+ state_mask = state_mask[:, -self._max_past_horizon :]
2247
+
2248
+ state = (
2249
+ state_keys,
2250
+ state_values,
2251
+ state_mask,
2252
+ position + x_values_time,
2253
+ query_state,
2254
+ key_state,
2255
+ value_state,
2256
+ )
2257
+
2258
+ if self._key_chunk_size is None and self._query_chunk_size is None:
2259
+ emits = AttentionEmits(types.Sequence(probabilities, x.mask))
2260
+ else:
2261
+ emits = ()
2262
+
2263
+ # If this step is a mix of valid and invalid values, the mask_invalid here
2264
+ # will clear the invalid timesteps.
2265
+ context_vectors = types.Sequence(context_vectors, x.mask).mask_invalid()
2266
+
2267
+ return context_vectors, state, emits
2268
+
2269
+ @tf.Module.with_name_scope
2270
+ def layer_with_emits(
2271
+ self,
2272
+ x: types.Sequence,
2273
+ training: bool,
2274
+ initial_state: Optional[types.State] = None,
2275
+ constants: Optional[types.Constants] = None,
2276
+ ) -> Tuple[types.Sequence, types.Emits]:
2277
+ values_time = utils.smart_dimension_size(x.values, 1)
2278
+ batch_size_static = x.values.shape.dims[0].value
2279
+ values_time_static = x.values.shape.dims[1].value
2280
+ compute_dtype = utils.compute_dtype()
2281
+
2282
+ def default_invalid_mask() -> tf.Tensor:
2283
+ # Compute a connectivity mask indicating which of the [query, key]
2284
+ # timesteps can see each other. Since query_time == key_time, this is a
2285
+ # banded square matrix with max_past_horizon lower-bandwidth and
2286
+ # max_future_horizon upper-bandwidth.
2287
+ #
2288
+ # For example, for values_time = 5, max_past_horizon = 2,
2289
+ # max_future_horizon = 1:
2290
+ #
2291
+ # a b c d e
2292
+ #
2293
+ # a can only look at itself and b:
2294
+ # 1 1 0 0 0
2295
+ # b can look at a, itself and c:
2296
+ # 1 1 1 0 0
2297
+ # c can look at a, b, itself and d:
2298
+ # 1 1 1 1 0
2299
+ # d can look at b, c, itself and e.
2300
+ # 0 1 1 1 1
2301
+ # e can look at c, d and itself:
2302
+ # 0 0 1 1 1
2303
+ #
2304
+ # This corresponds to a 5x5 banded matrix with max_past_horizon
2305
+ # lower-bandwidth and max_future_horizon upper-bandwidth.
2306
+ if self._max_past_horizon != -1 or self._max_future_horizon != -1:
2307
+ num_lower = values_time - 1
2308
+ if self._max_past_horizon != -1:
2309
+ # tf.minimum handles the corner case where values_time - 1 is less
2310
+ # than max_past_horizon.
2311
+ num_lower = tf.minimum(num_lower, self._max_past_horizon)
2312
+
2313
+ num_upper = values_time - 1
2314
+ if self._max_future_horizon != -1:
2315
+ # tf.minimum handles the corner case where values_time - 1 is less
2316
+ # than max_future_horizon.
2317
+ num_upper = tf.minimum(num_upper, self._max_future_horizon)
2318
+ visibility_mask = _ones_matrix_band_part(
2319
+ values_time,
2320
+ values_time,
2321
+ num_lower=num_lower,
2322
+ num_upper=num_upper,
2323
+ # [1, 1, queries_time, keys_time] so it broadcasts across batch size
2324
+ # and heads.
2325
+ out_shape=[1, 1, values_time, values_time],
2326
+ )
2327
+ visibility_mask = tf.cast(visibility_mask, compute_dtype)
2328
+ visibility_mask.shape.assert_is_compatible_with(
2329
+ [1, 1, values_time_static, values_time_static]
2330
+ )
2331
+ else:
2332
+ # If both max_past_horizon and max_future_horizon are -1 then we operate
2333
+ # unmasked.
2334
+ visibility_mask = None
2335
+
2336
+ # Mask out invalid timesteps in the input sequence so that we do not
2337
+ # attend to invalid timesteps. By shaping it [b, 1, 1, key_time], we
2338
+ # ensure that each query timestep cannot see invalid timesteps. If the
2339
+ # query timestep itself is invalid, it will be masked below
2340
+ valid_mask = tf.cast(x.mask[:, tf.newaxis, tf.newaxis, :], compute_dtype)
2341
+ valid_mask.shape.assert_is_compatible_with(
2342
+ [batch_size_static, 1, 1, values_time_static]
2343
+ )
2344
+
2345
+ # Since we need to specify which timesteps are invalid, we invert the
2346
+ # banded matrix.
2347
+ invalid_mask = 1.0 - (
2348
+ visibility_mask * valid_mask
2349
+ if visibility_mask is not None
2350
+ else valid_mask
2351
+ )
2352
+ if visibility_mask is not None:
2353
+ invalid_mask.shape.assert_is_compatible_with(
2354
+ [batch_size_static, 1, values_time_static, values_time_static]
2355
+ )
2356
+ else:
2357
+ invalid_mask.shape.assert_is_compatible_with(
2358
+ [batch_size_static, 1, 1, values_time_static]
2359
+ )
2360
+ return invalid_mask
2361
+
2362
+ queries, keys, values = tf.unstack(
2363
+ self._qkv.layer(x, training=training).values, axis=2
2364
+ )
2365
+
2366
+ if self._query_network:
2367
+ queries = self._query_network.layer(
2368
+ types.Sequence(queries, x.mask),
2369
+ training=training,
2370
+ constants=constants,
2371
+ ).values
2372
+ if self._key_network:
2373
+ keys = self._key_network.layer(
2374
+ types.Sequence(keys, x.mask),
2375
+ training=training,
2376
+ constants=constants,
2377
+ ).values
2378
+ if self._value_network:
2379
+ values = self._value_network.layer(
2380
+ types.Sequence(values, x.mask),
2381
+ training=training,
2382
+ constants=constants,
2383
+ ).values
2384
+
2385
+ if self._query_chunk_size is not None or self._key_chunk_size is not None:
2386
+ invalid_mask_fn = functools.partial(
2387
+ _dot_product_attention_invalid_mask_fn,
2388
+ max_past_horizon=self._max_past_horizon,
2389
+ max_future_horizon=self._max_future_horizon,
2390
+ )
2391
+ if self._relative_position_embedding is None:
2392
+ logit_bias_fn = None
2393
+ else:
2394
+ logit_bias_fn = functools.partial(
2395
+ _dot_product_attention_logit_bias_fn,
2396
+ relative_position_embedding=self._relative_position_embedding,
2397
+ )
2398
+ context_vectors = _chunked_dot_product_attention(
2399
+ queries=queries,
2400
+ keys=keys,
2401
+ keys_mask=x.mask,
2402
+ values=values,
2403
+ invalid_mask_fn=invalid_mask_fn,
2404
+ logit_bias_fn=logit_bias_fn,
2405
+ num_heads=self._num_heads,
2406
+ units_per_head=self._units_per_head,
2407
+ attention_logits_soft_cap=self._attention_logits_soft_cap,
2408
+ query_chunk_size=self._query_chunk_size,
2409
+ key_chunk_size=self._key_chunk_size,
2410
+ )
2411
+ emits = ()
2412
+ else:
2413
+ relative_logits = None
2414
+ if self._relative_position_embedding:
2415
+ relative_logits = self._relative_position_embedding.get_position_bias(
2416
+ queries
2417
+ )
2418
+ # [1, h, q, k]
2419
+ relative_logits.shape.assert_is_compatible_with([
2420
+ None,
2421
+ self._num_heads,
2422
+ values_time_static,
2423
+ values_time_static,
2424
+ ])
2425
+ assert relative_logits.dtype == compute_dtype
2426
+ invalid_mask = default_invalid_mask()
2427
+ context_vectors, probabilities, _ = _dot_product_attention(
2428
+ queries=queries,
2429
+ keys=keys,
2430
+ values=values,
2431
+ invalid_mask=invalid_mask,
2432
+ logit_bias=relative_logits,
2433
+ training=training,
2434
+ num_heads=self._num_heads,
2435
+ units_per_head=self._units_per_head,
2436
+ attention_logits_soft_cap=self._attention_logits_soft_cap,
2437
+ attention_probabilities_dropout=self._attention_probabilities_dropout,
2438
+ )
2439
+ emits = AttentionEmits(types.Sequence(probabilities, x.mask))
2440
+
2441
+ # Mask out invalid input timesteps. The invalid_mask we computed above
2442
+ # ensures that no timestep in context_vectors could have been computed from
2443
+ # invalid timesteps.
2444
+ context_vectors = types.Sequence(context_vectors, x.mask).mask_invalid()
2445
+
2446
+ return context_vectors, emits
2447
+
2448
+
2449
+ class DotProductAttention(types.Emitting):
2450
+ """Dot product attention."""
2451
+
2452
+ def __init__(
2453
+ self,
2454
+ source_name: str,
2455
+ num_heads: int,
2456
+ units_per_head: int,
2457
+ attention_probabilities_dropout_rate: float = 0.0,
2458
+ broadcast_dropout_across_queries: bool = False,
2459
+ use_bias: bool = False,
2460
+ kernel_initializer='glorot_uniform',
2461
+ bias_initializer='zeros',
2462
+ attention_logits_soft_cap: float | None = None,
2463
+ query_chunk_size: int | None = None,
2464
+ key_chunk_size: int | None = None,
2465
+ query_network: types.SequenceLayer | None = None,
2466
+ key_network: types.SequenceLayer | None = None,
2467
+ value_network: types.SequenceLayer | None = None,
2468
+ name: Optional[str] = None,
2469
+ ):
2470
+ """A dot-product attention layer as in Transformers.
2471
+
2472
+ Args:
2473
+ source_name: The key to lookup source sequence from constants dictionary.
2474
+ num_heads: The number of attention heads.
2475
+ units_per_head: The number of units per head.
2476
+ attention_probabilities_dropout_rate: The dropout rate for the attention
2477
+ probabilities.
2478
+ broadcast_dropout_across_queries: Whether to broadcast the dropout across
2479
+ the query time dimension as is done in T5.
2480
+ use_bias: Whether to learn a bias in the query/key/value projection.
2481
+ kernel_initializer: Kernel initializer for the query/key/value projection.
2482
+ bias_initializer: Bias initialier for the query/key/value projection.
2483
+ attention_logits_soft_cap: If non-zero, a soft cap applied to attention
2484
+ logits to prevent outliers from dominating the softmax. Empirically,
2485
+ 50.0 works well across a variety of tasks. Implemented as tanh(logits /
2486
+ cap) * cap.
2487
+ query_chunk_size: The query chunk size to use. Computes attention in
2488
+ parallel for blocks of queries of this size. If enabled, no emits are
2489
+ produced (e.g. attention probabilities for debugging).
2490
+ key_chunk_size: The key chunk size to use. If None, computes chunked
2491
+ attention over the entire key sequence for each block of queries. If
2492
+ non-None, computes attention for blocks of [query_chunk_size,
2493
+ key_chunk_size] at a time, bounding the overall memory usage to
2494
+ O(query_chunk_size * key_chunk_size). If enabled, no emits are produced
2495
+ (e.g. attention probabilities for debugging).
2496
+ query_network: An optional layer for processing queries before logit
2497
+ calculations are performed.
2498
+ key_network: An optional layer for processing keys before logit
2499
+ calculations are performed. Must have same output ratio as
2500
+ values_network.
2501
+ value_network: An optional layer for processing values before attention
2502
+ weighted summation is performed. Must have same output ratio as
2503
+ keys_network.
2504
+ name: An optional name for the layer.
2505
+ """
2506
+ super().__init__(name=name)
2507
+ _validate_attention(source_name, num_heads, units_per_head, name)
2508
+ self._num_heads = num_heads
2509
+ self._units_per_head = units_per_head
2510
+ num_units = num_heads * units_per_head
2511
+ self._source_name = source_name
2512
+ self._attention_logits_soft_cap = attention_logits_soft_cap
2513
+ if (
2514
+ attention_logits_soft_cap is not None
2515
+ and attention_logits_soft_cap <= 0.0
2516
+ ):
2517
+ raise ValueError(
2518
+ f'{attention_logits_soft_cap=} should be a positive number.'
2519
+ )
2520
+
2521
+ self._query_chunk_size = query_chunk_size
2522
+ self._key_chunk_size = key_chunk_size
2523
+ chunking_enabled = query_chunk_size or key_chunk_size
2524
+ if attention_probabilities_dropout_rate > 0.0 and chunking_enabled:
2525
+ raise NotImplementedError(
2526
+ 'Attention probability dropout is incompatible with chunking.'
2527
+ )
2528
+
2529
+ with self.name_scope as name_scope:
2530
+ if broadcast_dropout_across_queries:
2531
+ # [batch, num_heads, query_time, source_time]
2532
+ noise_shape = [None, None, 1, None]
2533
+ else:
2534
+ noise_shape = None
2535
+ self._attention_probabilities_dropout = tf.keras.layers.Dropout(
2536
+ attention_probabilities_dropout_rate,
2537
+ noise_shape=noise_shape,
2538
+ name='attention_probabilities_dropout',
2539
+ )
2540
+ self._q = tf.keras.layers.Dense(
2541
+ num_units,
2542
+ use_bias=use_bias,
2543
+ kernel_initializer=kernel_initializer,
2544
+ bias_initializer=bias_initializer,
2545
+ name=name_scope + 'query_projection/',
2546
+ )
2547
+ self._kv = tf.keras.layers.Dense(
2548
+ num_units * 2,
2549
+ use_bias=use_bias,
2550
+ kernel_initializer=kernel_initializer,
2551
+ bias_initializer=bias_initializer,
2552
+ name=name_scope + 'key_value_projection/',
2553
+ )
2554
+
2555
+ if callable(query_network):
2556
+ query_network = query_network()
2557
+ if callable(key_network):
2558
+ key_network = key_network()
2559
+ if callable(value_network):
2560
+ value_network = value_network()
2561
+
2562
+ self._query_network = query_network
2563
+ self._key_network = key_network
2564
+ self._value_network = value_network
2565
+
2566
+ key_output_ratio = (
2567
+ key_network.output_ratio if key_network else fractions.Fraction(1)
2568
+ )
2569
+ value_output_ratio = (
2570
+ value_network.output_ratio if value_network else fractions.Fraction(1)
2571
+ )
2572
+ if key_output_ratio != value_output_ratio:
2573
+ raise ValueError(
2574
+ f'{key_output_ratio=} and {value_output_ratio=} must be equal.'
2575
+ )
2576
+
2577
+ @property
2578
+ def supports_step(self) -> bool:
2579
+ return self._query_network.supports_step if self._query_network else True
2580
+
2581
+ @property
2582
+ def block_size(self) -> int:
2583
+ return self._query_network.block_size if self._query_network else 1
2584
+
2585
+ @property
2586
+ def output_ratio(self) -> fractions.Fraction:
2587
+ return (
2588
+ self._query_network.output_ratio
2589
+ if self._query_network
2590
+ else fractions.Fraction(1)
2591
+ )
2592
+
2593
+ def get_initial_state(
2594
+ self, x: types.Sequence, constants: types.Constants | None = None
2595
+ ) -> types.State:
2596
+ if self._query_network:
2597
+ batch_size = utils.smart_dimension_size(x.values, 0)
2598
+ q_input = types.Sequence(
2599
+ tf.zeros(
2600
+ (batch_size, 0, self._num_heads, self._units_per_head),
2601
+ x.values.dtype,
2602
+ ),
2603
+ tf.zeros((batch_size, 0), types.MASK_DTYPE),
2604
+ )
2605
+ return self._query_network.get_initial_state(q_input, constants)
2606
+ return ()
2607
+
2608
+ def get_output_shape(
2609
+ self,
2610
+ input_shape: tf.TensorShape,
2611
+ constants: Optional[types.Constants] = None,
2612
+ ) -> tf.TensorShape:
2613
+ if input_shape.rank != 1:
2614
+ raise ValueError(
2615
+ 'DotProductAttention requires rank 3 input got: %s'
2616
+ % tf.TensorShape([None, None]).concatenate(input_shape)
2617
+ )
2618
+ return tf.TensorShape([self._num_heads, self._units_per_head])
2619
+
2620
+ def get_emit_specs(
2621
+ self,
2622
+ input_spec: tf.TensorSpec,
2623
+ constants: Optional[types.Constants] = None,
2624
+ ) -> types.Emits:
2625
+ if self._query_chunk_size is None and self._key_chunk_size is None:
2626
+ source = _get_source(self, self._source_name, constants)
2627
+ spec = types.Sequence(
2628
+ tf.TensorSpec(
2629
+ tf.TensorShape(
2630
+ [self._num_heads, source.values.shape.dims[1].value]
2631
+ ),
2632
+ input_spec.dtype,
2633
+ ),
2634
+ tf.TensorSpec(tf.TensorShape([]), tf.float32),
2635
+ )
2636
+ return AttentionEmits(spec)
2637
+ return ()
2638
+
2639
+ def _get_queries(self, x: types.Sequence) -> types.Sequence:
2640
+ batch_size, queries_time = utils.smart_dimension_size(x.values, [0, 1])
2641
+ return types.Sequence(
2642
+ tf.reshape(
2643
+ self._q(x.values),
2644
+ [batch_size, queries_time, self._num_heads, self._units_per_head],
2645
+ ),
2646
+ x.mask,
2647
+ )
2648
+
2649
+ def _get_key_values(self, source: tf.Tensor) -> tuple[tf.Tensor, tf.Tensor]:
2650
+ batch_size, keys_time = utils.smart_dimension_size(source.values, [0, 1])
2651
+ keys, values = tf.unstack(
2652
+ tf.reshape(
2653
+ self._kv(source.values),
2654
+ [batch_size, keys_time, 2, self._num_heads, self._units_per_head],
2655
+ ),
2656
+ axis=2,
2657
+ )
2658
+ keys = types.Sequence(keys, source.mask)
2659
+ values = types.Sequence(values, source.mask)
2660
+ return keys, values
2661
+
2662
+ @tf.Module.with_name_scope
2663
+ def step_with_emits(
2664
+ self,
2665
+ x: types.Sequence,
2666
+ state: types.State,
2667
+ training: bool,
2668
+ constants: Optional[types.Constants] = None,
2669
+ ) -> Tuple[types.Sequence, types.State, types.Emits]:
2670
+ source = _get_source(self, self._source_name, constants)
2671
+
2672
+ queries = self._get_queries(x)
2673
+ keys, values = self._get_key_values(source)
2674
+
2675
+ if self._query_network:
2676
+ queries, state = self._query_network.step(
2677
+ queries.mask_invalid(),
2678
+ state,
2679
+ training=training,
2680
+ constants=constants,
2681
+ )
2682
+
2683
+ if self._key_network:
2684
+ keys = self._key_network.layer(
2685
+ keys.mask_invalid(),
2686
+ training=training,
2687
+ constants=constants,
2688
+ )
2689
+
2690
+ if self._value_network:
2691
+ values = self._value_network.layer(
2692
+ values.mask_invalid(),
2693
+ training=training,
2694
+ constants=constants,
2695
+ )
2696
+
2697
+ y, emits = self._attention(
2698
+ queries,
2699
+ keys,
2700
+ values,
2701
+ logit_bias_fn=None,
2702
+ is_step=True,
2703
+ training=training,
2704
+ )
2705
+ return y, state, emits
2706
+
2707
+ @tf.Module.with_name_scope
2708
+ def layer_with_emits(
2709
+ self,
2710
+ x: types.Sequence,
2711
+ training: bool,
2712
+ initial_state: Optional[types.State] = None,
2713
+ constants: Optional[types.Constants] = None,
2714
+ ) -> Tuple[types.Sequence, types.Emits]:
2715
+ source = _get_source(self, self._source_name, constants)
2716
+ queries = self._get_queries(x)
2717
+ keys, values = self._get_key_values(source)
2718
+
2719
+ if self._query_network:
2720
+ queries = self._query_network.layer(
2721
+ queries.mask_invalid(),
2722
+ training=training,
2723
+ constants=constants,
2724
+ )
2725
+
2726
+ if self._key_network:
2727
+ keys = self._key_network.layer(
2728
+ keys.mask_invalid(),
2729
+ training=training,
2730
+ constants=constants,
2731
+ )
2732
+
2733
+ if self._value_network:
2734
+ values = self._value_network.layer(
2735
+ values.mask_invalid(),
2736
+ training=training,
2737
+ constants=constants,
2738
+ )
2739
+
2740
+ return self._attention(
2741
+ queries,
2742
+ keys,
2743
+ values,
2744
+ logit_bias_fn=None,
2745
+ is_step=False,
2746
+ training=training,
2747
+ )
2748
+
2749
+ def _attention(
2750
+ self,
2751
+ queries: types.Sequence,
2752
+ keys: types.Sequence,
2753
+ values: types.Sequence,
2754
+ logit_bias_fn: (
2755
+ Callable[
2756
+ [tf.Tensor, tf.Tensor | int, tf.Tensor, tf.Tensor | int],
2757
+ tf.Tensor,
2758
+ ]
2759
+ | None
2760
+ ),
2761
+ is_step: bool,
2762
+ training: bool,
2763
+ ) -> tuple[types.Sequence, types.Emits]:
2764
+ # TODO(b/297462463): Step-wise support for chunked attention.
2765
+ if not is_step and (
2766
+ self._query_chunk_size is not None or self._key_chunk_size is not None
2767
+ ):
2768
+ invalid_mask_fn = functools.partial(
2769
+ _dot_product_attention_invalid_mask_fn,
2770
+ max_past_horizon=-1,
2771
+ max_future_horizon=-1,
2772
+ )
2773
+ context_vectors = _chunked_dot_product_attention(
2774
+ queries=queries.values,
2775
+ keys=keys.values,
2776
+ keys_mask=keys.mask,
2777
+ values=values.values,
2778
+ invalid_mask_fn=invalid_mask_fn,
2779
+ logit_bias_fn=logit_bias_fn,
2780
+ num_heads=self._num_heads,
2781
+ units_per_head=self._units_per_head,
2782
+ attention_logits_soft_cap=self._attention_logits_soft_cap,
2783
+ query_chunk_size=self._query_chunk_size,
2784
+ key_chunk_size=self._key_chunk_size,
2785
+ )
2786
+ emits = ()
2787
+ else:
2788
+ queries_time = utils.smart_dimension_size(queries.values, 1)
2789
+ keys_time = utils.smart_dimension_size(keys.values, 1)
2790
+ invalid_mask = 1.0 - keys.mask[:, tf.newaxis, tf.newaxis, :]
2791
+ logit_bias = None
2792
+ if logit_bias_fn is not None:
2793
+ logit_bias = logit_bias_fn(0, queries_time, 0, keys_time)
2794
+ # [b, q, h, k] -> [b, h, q, k]
2795
+ logit_bias = tf.transpose(logit_bias, [0, 2, 1, 3])
2796
+ context_vectors, probabilities, _ = _dot_product_attention(
2797
+ queries=queries.values,
2798
+ keys=keys.values,
2799
+ values=values.values,
2800
+ invalid_mask=invalid_mask,
2801
+ logit_bias=logit_bias,
2802
+ training=training,
2803
+ num_heads=self._num_heads,
2804
+ units_per_head=self._units_per_head,
2805
+ attention_logits_soft_cap=self._attention_logits_soft_cap,
2806
+ attention_probabilities_dropout=self._attention_probabilities_dropout,
2807
+ )
2808
+ # If we are stepping with chunking enabled, don't emit AttentionEmits.
2809
+ # TODO(rryan): Figure out a way to produce different emits in layer/step.
2810
+ if self._key_chunk_size is None and self._query_chunk_size is None:
2811
+ emits = AttentionEmits(types.Sequence(probabilities, queries.mask))
2812
+ else:
2813
+ emits = ()
2814
+ return types.Sequence(context_vectors, queries.mask).mask_invalid(), emits
2815
+
2816
+
2817
+ class LocationSensitiveAttention(types.Emitting):
2818
+ """Location Sensitive attention mechanism.
2819
+
2820
+ Similar to AdditiveAttention, but adds two additional features:
2821
+ 1. prev attention alignment (local history)
2822
+ 2. cum_sum of previous attention alignment (full history)
2823
+ """
2824
+
2825
+ def __init__(
2826
+ self,
2827
+ source_name: str,
2828
+ num_heads: int,
2829
+ units_per_head: int,
2830
+ location_num_filters: int,
2831
+ location_filter_size: int,
2832
+ location_filter_padding: str = 'same',
2833
+ name: Optional[str] = None,
2834
+ ):
2835
+ """Creates a location sensitive attention module."""
2836
+ super().__init__(name=name)
2837
+ _validate_attention(source_name, num_heads, units_per_head, name)
2838
+ if location_num_filters <= 0:
2839
+ raise ValueError(
2840
+ f'Expected location_num_filters > 0 for {name}. '
2841
+ f'Got {location_num_filters}'
2842
+ )
2843
+ if location_filter_size <= 0:
2844
+ raise ValueError(
2845
+ f'Expected location_filter_size > 0 for {name}. '
2846
+ f'Got {location_filter_size}'
2847
+ )
2848
+ if location_filter_padding not in ('same', 'valid'):
2849
+ raise ValueError(
2850
+ f'location_filter_padding must be "same" or "valid" for {name}. '
2851
+ f'Got "{location_filter_padding}".'
2852
+ )
2853
+ self._source_name = source_name
2854
+ self._num_heads = num_heads
2855
+ self._units_per_head = units_per_head
2856
+ num_units = num_heads * units_per_head
2857
+ with self.name_scope as name_scope:
2858
+ # GlorotNormal() scaled independently for each head.
2859
+ self._attn_v = tf.Variable(
2860
+ lambda: tf.initializers.VarianceScaling(
2861
+ mode='fan_out', distribution='truncated_normal'
2862
+ )([num_heads, units_per_head], dtype=utils.variable_dtype()),
2863
+ name='v',
2864
+ )
2865
+ self._source_projection = tf.keras.layers.Dense(
2866
+ num_units, use_bias=True, name=name_scope + 'source_projection/'
2867
+ )
2868
+ self._query_projection = tf.keras.layers.Dense(
2869
+ num_units, use_bias=False, name=name_scope + 'query_projection/'
2870
+ )
2871
+ # Implement independent location filters for each attention head using a
2872
+ # depthwise 2D convolution along a [batch, source_time, 2, num_heads]
2873
+ # shaped tensor. Since we really only need a 1D convlution along the
2874
+ # source_time axis, we use 'valid' padding and, if specified, manually
2875
+ # implement 'same' pre-padding along that axis.
2876
+ # If 'valid' padding is used, we post-pad the convolution output to have
2877
+ # the same length as the input.
2878
+ pad_amount = location_filter_size - 1
2879
+ if location_filter_padding == 'same':
2880
+ left = pad_amount // 2
2881
+ right = pad_amount - left
2882
+ pre_pad = [tf.keras.layers.ZeroPadding2D(((left, right), (0, 0)))]
2883
+ post_pad = []
2884
+ else:
2885
+ pre_pad = []
2886
+ post_pad = [tf.keras.layers.ZeroPadding2D(((0, pad_amount), (0, 0)))]
2887
+ self._location_filters = tf.keras.Sequential(
2888
+ pre_pad
2889
+ + [
2890
+ tf.keras.layers.DepthwiseConv2D(
2891
+ (location_filter_size, 2),
2892
+ depth_multiplier=location_num_filters,
2893
+ padding='valid',
2894
+ use_bias=False,
2895
+ kernel_initializer=tf.random_uniform_initializer(),
2896
+ name=name_scope + 'location_filters/',
2897
+ )
2898
+ ]
2899
+ + post_pad
2900
+ + [tf.keras.layers.Reshape((-1, num_heads, location_num_filters))]
2901
+ )
2902
+ self._location_projection_kernel = tf.Variable(
2903
+ lambda: tf.initializers.VarianceScaling(
2904
+ mode='fan_out', distribution='truncated_normal'
2905
+ )(
2906
+ [num_heads, location_num_filters, units_per_head],
2907
+ dtype=utils.variable_dtype(),
2908
+ ),
2909
+ name='location_projection',
2910
+ )
2911
+
2912
+ def get_initial_state(
2913
+ self, x: types.Sequence, constants: Optional[types.Constants] = None
2914
+ ) -> types.State:
2915
+ source = _get_source(self, self._source_name, constants)
2916
+ batch_size, source_length = utils.smart_dimension_size(
2917
+ source.values, [0, 1]
2918
+ )
2919
+
2920
+ # The location state tensor is shaped [batch_size, source_length, 2,
2921
+ # num_heads] where the 1st inner dimension is the current attention energy
2922
+ # for the source timestep and the 2nd inner dimension is the cumulative
2923
+ # attention energy for the source timestep. We initialize the location state
2924
+ # with ones in the first timestep and zeros everywhere else.
2925
+ cumulative_prob_length = tf.maximum(0, source_length - 1)
2926
+ compute_dtype = utils.compute_dtype()
2927
+ location_initial_state = tf.concat(
2928
+ [
2929
+ tf.ones([batch_size, 1, 2, self._num_heads], dtype=compute_dtype),
2930
+ tf.zeros(
2931
+ [batch_size, cumulative_prob_length, 2, self._num_heads],
2932
+ dtype=compute_dtype,
2933
+ ),
2934
+ ],
2935
+ 1,
2936
+ )
2937
+ return types.Sequence(location_initial_state, source.mask)
2938
+
2939
+ def get_output_shape(
2940
+ self,
2941
+ input_shape: tf.TensorShape,
2942
+ constants: Optional[types.Constants] = None,
2943
+ ) -> tf.TensorShape:
2944
+ if input_shape.rank != 1:
2945
+ raise ValueError(
2946
+ 'LocationSensitiveAttention requires rank 3 input got: %s'
2947
+ % tf.TensorShape([None, None]).concatenate(input_shape)
2948
+ )
2949
+ source = _get_source(self, self._source_name, constants)
2950
+ return tf.TensorShape([self._num_heads, source.values.shape.dims[2].value])
2951
+
2952
+ def get_emit_specs(
2953
+ self,
2954
+ input_spec: tf.TensorSpec,
2955
+ constants: Optional[types.Constants] = None,
2956
+ ) -> AttentionEmits:
2957
+ source = _get_source(self, self._source_name, constants)
2958
+ return AttentionEmits(
2959
+ types.Sequence(
2960
+ tf.TensorSpec(
2961
+ tf.TensorShape(
2962
+ [self._num_heads, source.values.shape.dims[1].value]
2963
+ ),
2964
+ input_spec.dtype,
2965
+ ),
2966
+ tf.TensorSpec(tf.TensorShape([]), tf.float32),
2967
+ )
2968
+ )
2969
+
2970
+ def _single_step_with_emits(
2971
+ self,
2972
+ x: types.Sequence,
2973
+ state: types.State,
2974
+ training: bool,
2975
+ constants: Optional[types.Constants] = None,
2976
+ ) -> Tuple[types.Sequence, types.State, AttentionEmits]:
2977
+ """Implements a single step of location sensitive attention."""
2978
+ batch_size = utils.smart_dimension_size(x.values, 0)
2979
+ x.values.shape.assert_is_compatible_with([None, 1, None])
2980
+ source = _get_source(self, self._source_name, constants)
2981
+ num_heads = self._num_heads
2982
+ units_per_head = self._units_per_head
2983
+ query = x.apply_values(self._query_projection)
2984
+ query = query.apply_values(
2985
+ tf.reshape, [batch_size, 1, num_heads, units_per_head]
2986
+ )
2987
+
2988
+ keys = source.apply_values(self._source_projection).mask_invalid()
2989
+ keys_time = utils.smart_dimension_size(keys.values, 1)
2990
+ keys = keys.apply_values(
2991
+ tf.reshape, [batch_size, keys_time, num_heads, units_per_head]
2992
+ )
2993
+
2994
+ # Convolution over the [batch, keys_time, 2, num_heads] tensor containing
2995
+ # the last step's attention probabilities and the cumulative probabilities
2996
+ # across all previous frames produces the
2997
+ # [batch, keys_time, num_heads, units_per_head] "location features" used to
2998
+ # condition the attention on this frame.
2999
+ def compute_location_features(x):
3000
+ features = self._location_filters(x)
3001
+ return tf.einsum(
3002
+ 'BiNL,NLH->BiNH',
3003
+ features,
3004
+ tf.cast(self._location_projection_kernel, features.dtype),
3005
+ )
3006
+
3007
+ location = state.apply_values(compute_location_features).mask_invalid()
3008
+
3009
+ # Broadcast to [b, keys_time, num_heads, units_per_head]
3010
+ hidden = tf.tanh(query.values + keys.values + location.values)
3011
+
3012
+ logits = tf.einsum(
3013
+ 'BjNH,NH->BNj', hidden, tf.cast(self._attn_v, hidden.dtype)
3014
+ )
3015
+ # [b, num_heads, keys_time]
3016
+ mask = keys.mask[:, tf.newaxis, :]
3017
+ logits = tf.where(mask > 0.0, logits, _INVALID_LOGIT_VALUE)
3018
+ probabilities = _softmax_in_at_least_float32(logits)
3019
+
3020
+ # Expand to [b, 1, num_heads, keys_time].
3021
+ probabilities = probabilities[:, tf.newaxis, :, :]
3022
+
3023
+ context_vector = types.Sequence(
3024
+ tf.einsum('BiNj,BjS->BiNS', probabilities, source.values), query.mask
3025
+ ).mask_invalid()
3026
+ # Compute the updated location state (the current step's probability
3027
+ # concatenated with the cumulative attention probabilities).
3028
+ prob_transposed = tf.transpose(probabilities[:, 0], [0, 2, 1])
3029
+ # [b, keys_time, num_heads]
3030
+ cumulative_prob = state.values[:, :, 1, :] + prob_transposed
3031
+ state = types.Sequence(
3032
+ tf.stack([prob_transposed, cumulative_prob], axis=2), state.mask
3033
+ )
3034
+ probabilities = types.Sequence(probabilities, query.mask).mask_invalid()
3035
+ emits = AttentionEmits(probabilities)
3036
+ return context_vector, state, emits
3037
+
3038
+ @tf.Module.with_name_scope
3039
+ def step_with_emits(
3040
+ self,
3041
+ x: types.Sequence,
3042
+ state: types.State,
3043
+ training: bool,
3044
+ constants: Optional[types.Constants] = None,
3045
+ unroll: bool = True,
3046
+ ) -> Tuple[types.Sequence, types.State, AttentionEmits]:
3047
+ step_fn = functools.partial(
3048
+ self._single_step_with_emits, training=training, constants=constants
3049
+ )
3050
+ x_length = utils.smart_dimension_size(x.values, 1)
3051
+ num_blocks = x_length // self.block_size
3052
+ if unroll:
3053
+ return utils.step_by_step_fn_static(
3054
+ step_fn, num_blocks, self.block_size, x, state
3055
+ )
3056
+ else:
3057
+ return utils.step_by_step_fn_dynamic(
3058
+ step_fn,
3059
+ x_length,
3060
+ x.channel_shape,
3061
+ self.get_output_spec_for_sequence(x, constants),
3062
+ self.get_emit_specs_for_sequence(x, constants),
3063
+ num_blocks,
3064
+ self.block_size,
3065
+ int(self.block_size * self.output_ratio),
3066
+ x,
3067
+ state,
3068
+ )
3069
+
3070
+ @tf.Module.with_name_scope
3071
+ def layer_with_emits(
3072
+ self,
3073
+ x: types.Sequence,
3074
+ training: bool,
3075
+ initial_state: Optional[types.State] = None,
3076
+ constants: Optional[types.Constants] = None,
3077
+ ) -> Tuple[types.Sequence, types.Emits]:
3078
+ if initial_state is None:
3079
+ initial_state = self.get_initial_state(x, constants)
3080
+ outputs, _, emits = self.step_with_emits(
3081
+ x,
3082
+ training=training,
3083
+ state=initial_state,
3084
+ constants=constants,
3085
+ unroll=False,
3086
+ )
3087
+ return outputs, emits
3088
+
3089
+
3090
+ class DynamicConvolutionAttention(types.Emitting):
3091
+ """A multi-headed dynamic convolution attention (DCA) layer.
3092
+
3093
+ paper: https://arxiv.org/abs/1910.10288.
3094
+ """
3095
+
3096
+ # To prevent attention from looking at regions of the encoder state that are
3097
+ # invalid, a bias mask is added before applying the attention. This scaling
3098
+ # factor indicates the absolute value of the bias mask for invalid regions.
3099
+ # Larger values make it less possible for the attention module to attend to
3100
+ # invalid regions.
3101
+ _LOGIT_BIAS_SCALE = 1e6
3102
+
3103
+ def __init__(
3104
+ self,
3105
+ source_name: str,
3106
+ max_forward_step: int,
3107
+ prior_alpha: float,
3108
+ prior_beta: float,
3109
+ num_static_filters: int,
3110
+ num_dynamic_filters: int,
3111
+ dynamic_filter_hidden_dim: int,
3112
+ name: Optional[str] = None,
3113
+ ):
3114
+ """Initializes DynamicConvolutionAttention layer.
3115
+
3116
+ Args:
3117
+ source_name: The key to lookup source sequence from constants dictionary.
3118
+ max_forward_step: Maximum forward step allowed by prior. This also
3119
+ determines size of all filters (filter_size = 2 * max_forward_step + 1).
3120
+ prior_alpha: The alpha parameters for the Beta-Binomial alignment step
3121
+ size prior. The prior filter taps for forward movement are computed as:
3122
+ BetaBinomialPMF(k, N, alpha, beta) for k in [0, 1, ..., N], where N is
3123
+ max_forward_step. Setting alpha = beta = 1.0 gives a uniform prior. For
3124
+ guidance on tweaking these parameters, see: -
3125
+ https://en.wikipedia.org/wiki/Beta-binomial_distribution -
3126
+ prior_beta: The beta parameter for the Beta-Binomial alignment step size
3127
+ prior.
3128
+ num_static_filters: Number of static filters.
3129
+ num_dynamic_filters: Number of dynamic filters computed from the query.
3130
+ dynamic_filter_hidden_dim: Size of the hidden layer that computes the
3131
+ dynamic filters from the query.
3132
+ name: An optional module name.
3133
+ """
3134
+ super().__init__(name)
3135
+ if not source_name:
3136
+ raise ValueError(f'Expected non-empty source_name for {source_name}.')
3137
+ if num_static_filters <= 0:
3138
+ raise ValueError(
3139
+ f'Expected num_static_filters > 0 for {name}. '
3140
+ f'Got {num_static_filters}'
3141
+ )
3142
+ if num_dynamic_filters <= 0:
3143
+ raise ValueError(
3144
+ f'Expected num_dynamic_filters > 0 for {name}. '
3145
+ f'Got {num_dynamic_filters}'
3146
+ )
3147
+ # TODO(soroosho): Support multiple heads. Currently, only single-head is
3148
+ # supported, but the output is accomodating extra dimension for heads, to
3149
+ # be consistent with other SL attention layers.
3150
+ self._num_heads = 1
3151
+ self._source_name = source_name
3152
+ self._max_forward_step = max_forward_step
3153
+ self._prior_alpha = prior_alpha
3154
+ self._prior_beta = prior_beta
3155
+ self._filter_size = filter_size = 2 * max_forward_step + 1
3156
+
3157
+ with self.name_scope as name_scope:
3158
+ self._attn_v = tf.keras.layers.Dense(1, name=f'{name_scope}v/')
3159
+
3160
+ # Input: [b, source_time, 1].
3161
+ self._static_location_conv = tf.keras.layers.Conv1D(
3162
+ num_static_filters,
3163
+ filter_size,
3164
+ padding='same',
3165
+ use_bias=True,
3166
+ kernel_initializer=tf.random_uniform_initializer(),
3167
+ name=f'{name_scope}static_location_filters/',
3168
+ )
3169
+ # Output: [b, source_time, num_static_filters].
3170
+
3171
+ self._dynamic_location_filter_and_bias_mlp = tf.keras.Sequential(
3172
+ [
3173
+ # Input: [b, 1, query_dim].
3174
+ tf.keras.layers.experimental.EinsumDense(
3175
+ 'Biq,qH->BiH',
3176
+ bias_axes='H',
3177
+ output_shape=(1, dynamic_filter_hidden_dim),
3178
+ activation=tf.nn.tanh,
3179
+ name=f'{name_scope}dynamic_location_filters_einsum_dense0/',
3180
+ ),
3181
+ # [b, 1, dynamic_filter_hidden_dim].
3182
+ tf.keras.layers.experimental.EinsumDense(
3183
+ 'BiH,iHFjD->BFjD',
3184
+ bias_axes='FjD',
3185
+ output_shape=(filter_size + 1, 1, num_dynamic_filters),
3186
+ name=f'{name_scope}dynamic_location_filters_einsum_dense1/',
3187
+ ),
3188
+ # Output: [b, filter_size + 1, 1, num_dynamic_filters].
3189
+ ]
3190
+ )
3191
+
3192
+ # [b, source_time, 1]
3193
+ self._prior_filter = self._build_prior_filter()
3194
+
3195
+ def _build_prior_filter(self) -> np.ndarray:
3196
+ """Build prior location filter."""
3197
+
3198
+ # Construct prior filter.
3199
+ # [filter_size, chan_in=1, chan_out=1]
3200
+ prior_filter = np.zeros([self._filter_size, 1, 1], dtype='float32')
3201
+ # The filter tap at the center index provides no relative movement. Indices
3202
+ # after center_ind provide increasing amounts of forward movement; those
3203
+ # before center_ind provide increasing amounts of backward movement.
3204
+ center_ind = self._filter_size // 2
3205
+ # The prior filter acts as a monotonicity constraint and it limits the
3206
+ # maximum forward movement to `max_forward_step` steps.
3207
+ # The filter taps for forward movement are determined using a Beta-Binomial
3208
+ # distribution.
3209
+ prior_filter[center_ind:, 0, 0] = self._beta_binomial_pmf(
3210
+ np.arange(self._max_forward_step + 1),
3211
+ self._max_forward_step,
3212
+ self._prior_alpha,
3213
+ self._prior_beta,
3214
+ )
3215
+
3216
+ # Because tf.nn.conv1d is actually correlation and not convolution, we have
3217
+ # to flip the filter.
3218
+ prior_filter = prior_filter[::-1]
3219
+ return prior_filter
3220
+
3221
+ def _beta_binomial_pmf(self, k, n, a, b) -> np.ndarray:
3222
+ """Compute Beta-Binomial probability mass function (PMF).
3223
+
3224
+ See: https://en.wikipedia.org/wiki/Beta-binomial_distribution
3225
+
3226
+ Args:
3227
+ k: Tensor of locations at which to evaluate the PMF (integers in 0 <= k <=
3228
+ n).
3229
+ n: Number of Bernoulli trials.
3230
+ a: Alpha parameter of the distribution (float).
3231
+ b: Beta parameter of the distribution (float).
3232
+
3233
+ Returns:
3234
+ A tensor containing the probability mass at each location in k.
3235
+ """
3236
+ return (
3237
+ scipy.special.binom(n, k)
3238
+ * scipy.special.beta(k + a, n - k + b)
3239
+ / scipy.special.beta(a, b)
3240
+ )
3241
+
3242
+ def get_initial_state(
3243
+ self, x: types.Sequence, constants: Optional[types.Constants] = None
3244
+ ) -> types.State:
3245
+ source = _get_source(self, self._source_name, constants)
3246
+ batch_size, source_length = utils.smart_dimension_size(
3247
+ source.values, [0, 1]
3248
+ )
3249
+
3250
+ # The state tensor is shaped [batch_size, source_length, 1] where the 1st
3251
+ # inner dimension is the current attention energy for the source timestep.
3252
+ # We initialize the location state with ones in the first timestep and zeros
3253
+ # everywhere else.
3254
+ location_initial_state = tf.sequence_mask(
3255
+ tf.fill([batch_size], 1),
3256
+ source_length,
3257
+ dtype=utils.compute_dtype(),
3258
+ )[:, :, tf.newaxis]
3259
+
3260
+ # TODO(b/196245589): Fix SL gradient tests with zero-length sources.
3261
+ return types.Sequence(location_initial_state, source.mask)
3262
+
3263
+ def get_output_shape(
3264
+ self,
3265
+ input_shape: tf.TensorShape,
3266
+ constants: Optional[types.Constants] = None,
3267
+ ) -> tf.TensorShape:
3268
+ if input_shape.rank != 1:
3269
+ raise ValueError(
3270
+ 'DynamicConvoluationAttention requires rank 3 input got: %s'
3271
+ % tf.TensorShape([None, None]).concatenate(input_shape)
3272
+ )
3273
+ source = _get_source(self, self._source_name, constants)
3274
+ return tf.TensorShape([self._num_heads, source.values.shape.dims[2].value])
3275
+
3276
+ def get_emit_specs(
3277
+ self,
3278
+ input_spec: tf.TensorSpec,
3279
+ constants: Optional[types.Constants] = None,
3280
+ ) -> AttentionEmits:
3281
+ source = _get_source(self, self._source_name, constants)
3282
+ return AttentionEmits(
3283
+ types.Sequence(
3284
+ tf.TensorSpec(
3285
+ tf.TensorShape(
3286
+ [self._num_heads, source.values.shape.dims[1].value]
3287
+ ),
3288
+ input_spec.dtype,
3289
+ ),
3290
+ tf.TensorSpec(tf.TensorShape([]), types.MASK_DTYPE),
3291
+ )
3292
+ )
3293
+
3294
+ def _single_step_with_emits(
3295
+ self,
3296
+ x: types.Sequence,
3297
+ state: types.State,
3298
+ training: bool,
3299
+ constants: Optional[types.Constants] = None,
3300
+ ) -> Tuple[types.Sequence, types.State, AttentionEmits]:
3301
+ """Implements a single step of dynamic convoluation attention."""
3302
+ # [b, 1, query_dim].
3303
+ query = x
3304
+ query.values.shape.assert_is_compatible_with([None, 1, None])
3305
+ # [b, source_time, key_dim].
3306
+ source = _get_source(self, self._source_name, constants)
3307
+
3308
+ # Output: [b, source_time, num_static_filters].
3309
+ static_filter_output = state.apply_values(self._static_location_conv).values
3310
+
3311
+ # [b, filter_size + 1, 1, num_dynamic_filters]
3312
+ dynamic_filters_and_biases = self._dynamic_location_filter_and_bias_mlp(
3313
+ query.values
3314
+ )
3315
+
3316
+ # dynamic_filters: [b, filter_size, 1, num_dynamic_filters]
3317
+ # dynamic_biases: [b, 1, num_dynamic_filters]
3318
+ dynamic_biases, dynamic_filters = tf.split(
3319
+ dynamic_filters_and_biases, [1, self._filter_size], axis=1
3320
+ )
3321
+
3322
+ # [b, 1, num_dynamic_filters]
3323
+ dynamic_biases = tf.squeeze(dynamic_biases, 1)
3324
+
3325
+ # [b, source_time, num_dynamic_filters]
3326
+ dynamic_filter_output = utils.dynamic_filter_conv1d(
3327
+ state.values, dynamic_filters
3328
+ )
3329
+ # [b, source_time, num_dynamic_filters]
3330
+ dynamic_filter_output += dynamic_biases
3331
+
3332
+ # Compute prior outputs and logits from location state using prior filter.
3333
+ # [b, source_time, 1]
3334
+ prior_outputs = tf.nn.conv1d(
3335
+ state.values,
3336
+ tf.constant(self._prior_filter, dtype=state.values.dtype),
3337
+ stride=1,
3338
+ padding='SAME',
3339
+ )
3340
+ # compute logits from values using log, and set values that would underflow
3341
+ # to -self._LOGIT_BIAS_SCALE to get hard zeros out of the softmax.
3342
+ # [b, source_time, 1]
3343
+ prior_logits = utils.log_without_underflow(
3344
+ prior_outputs, -self._LOGIT_BIAS_SCALE
3345
+ )
3346
+
3347
+ # [b, source_time, loc_num_dynamic_filters + loc_num_static_filters]
3348
+ hidden = tf.concat([dynamic_filter_output, static_filter_output], axis=-1)
3349
+ hidden = tf.nn.tanh(hidden)
3350
+
3351
+ # [b, source_time, 1]
3352
+ logits = self._attn_v(hidden, training=training) + prior_logits
3353
+ logits = tf.where(
3354
+ source.mask[:, :, tf.newaxis] > 0.0,
3355
+ logits,
3356
+ tf.constant(-self._LOGIT_BIAS_SCALE, dtype=logits.dtype),
3357
+ )
3358
+ # [b, source_time]
3359
+ logits = tf.squeeze(logits, axis=-1)
3360
+
3361
+ # [b, source_time]
3362
+ probabilities = _softmax_in_at_least_float32(logits)
3363
+ # [b, 1, 1, source_time].
3364
+ probabilities = probabilities[:, tf.newaxis, tf.newaxis, :]
3365
+
3366
+ context_vector = types.Sequence(
3367
+ tf.einsum('BiNj,BjS->BiNS', probabilities, source.values), query.mask
3368
+ ).mask_invalid()
3369
+ # Compute the updated location state (the current step's probability
3370
+ # concatenated with the cumulative attention probabilities).
3371
+ prob_transposed = tf.transpose(probabilities[:, 0, :, :], [0, 2, 1])
3372
+ state = types.Sequence(prob_transposed, state.mask)
3373
+ probabilities = types.Sequence(probabilities, query.mask).mask_invalid()
3374
+ emits = AttentionEmits(probabilities)
3375
+ return context_vector, state, emits
3376
+
3377
+ @tf.Module.with_name_scope
3378
+ def step_with_emits(
3379
+ self,
3380
+ x: types.Sequence,
3381
+ state: types.State,
3382
+ training: bool,
3383
+ constants: Optional[types.Constants] = None,
3384
+ unroll: bool = True,
3385
+ ) -> Tuple[types.Sequence, types.State, AttentionEmits]:
3386
+ step_fn = functools.partial(
3387
+ self._single_step_with_emits, training=training, constants=constants
3388
+ )
3389
+ x_length = utils.smart_dimension_size(x.values, 1)
3390
+ num_blocks = x_length // self.block_size
3391
+ if unroll:
3392
+ return utils.step_by_step_fn_static(
3393
+ step_fn, num_blocks, self.block_size, x, state
3394
+ )
3395
+ else:
3396
+ return utils.step_by_step_fn_dynamic(
3397
+ step_fn,
3398
+ x_length,
3399
+ x.channel_shape,
3400
+ self.get_output_spec_for_sequence(x, constants),
3401
+ self.get_emit_specs_for_sequence(x, constants),
3402
+ num_blocks,
3403
+ self.block_size,
3404
+ int(self.block_size * self.output_ratio),
3405
+ x,
3406
+ state,
3407
+ )
3408
+
3409
+ @tf.Module.with_name_scope
3410
+ def layer_with_emits(
3411
+ self,
3412
+ x: types.Sequence,
3413
+ training: bool,
3414
+ initial_state: Optional[types.State] = None,
3415
+ constants: Optional[types.Constants] = None,
3416
+ ) -> Tuple[types.Sequence, types.Emits]:
3417
+ if initial_state is None:
3418
+ initial_state = self.get_initial_state(x, constants)
3419
+ outputs, _, emits = self.step_with_emits(
3420
+ x,
3421
+ training=training,
3422
+ state=initial_state,
3423
+ constants=constants,
3424
+ unroll=False,
3425
+ )
3426
+ return outputs, emits