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.
- sequence_layers/__init__.py +16 -0
- sequence_layers/internal/types.py +521 -0
- sequence_layers/jax/__init__.py +29 -0
- sequence_layers/jax/attention.py +6124 -0
- sequence_layers/jax/combinators.py +1907 -0
- sequence_layers/jax/conditioning.py +511 -0
- sequence_layers/jax/convolution.py +2103 -0
- sequence_layers/jax/dense.py +447 -0
- sequence_layers/jax/dsp.py +1686 -0
- sequence_layers/jax/examples/gemma3n_audio_encoder.py +358 -0
- sequence_layers/jax/export.py +313 -0
- sequence_layers/jax/meta.py +54 -0
- sequence_layers/jax/normalization.py +889 -0
- sequence_layers/jax/pooling.py +925 -0
- sequence_layers/jax/position.py +370 -0
- sequence_layers/jax/recurrent.py +674 -0
- sequence_layers/jax/sharding.py +48 -0
- sequence_layers/jax/signal.py +511 -0
- sequence_layers/jax/simple.py +2679 -0
- sequence_layers/jax/test_utils.py +1343 -0
- sequence_layers/jax/time_varying.py +673 -0
- sequence_layers/jax/types.py +1537 -0
- sequence_layers/jax/typing.py +59 -0
- sequence_layers/jax/utils.py +2149 -0
- sequence_layers/tensorflow/__init__.py +56 -0
- sequence_layers/tensorflow/attention.py +3426 -0
- sequence_layers/tensorflow/combinators.py +938 -0
- sequence_layers/tensorflow/conditioning.py +644 -0
- sequence_layers/tensorflow/convolution.py +1855 -0
- sequence_layers/tensorflow/dense.py +285 -0
- sequence_layers/tensorflow/dsp.py +740 -0
- sequence_layers/tensorflow/examples/bert.py +144 -0
- sequence_layers/tensorflow/examples/conformer.py +138 -0
- sequence_layers/tensorflow/examples/deep_voice.py +72 -0
- sequence_layers/tensorflow/examples/listen_attend_spell.py +102 -0
- sequence_layers/tensorflow/examples/mobilenet.py +92 -0
- sequence_layers/tensorflow/examples/t5.py +225 -0
- sequence_layers/tensorflow/examples/tacotron.py +124 -0
- sequence_layers/tensorflow/examples/transformer.py +159 -0
- sequence_layers/tensorflow/examples/very_attentive_tacotron.py +1771 -0
- sequence_layers/tensorflow/examples/wavernn.py +225 -0
- sequence_layers/tensorflow/normalization.py +1127 -0
- sequence_layers/tensorflow/pooling.py +462 -0
- sequence_layers/tensorflow/position.py +509 -0
- sequence_layers/tensorflow/recurrent.py +645 -0
- sequence_layers/tensorflow/simple.py +1207 -0
- sequence_layers/tensorflow/squeeze.py +178 -0
- sequence_layers/tensorflow/test_util.py +834 -0
- sequence_layers/tensorflow/time_varying.py +439 -0
- sequence_layers/tensorflow/types.py +961 -0
- sequence_layers/tensorflow/utils.py +858 -0
- sequence_layers-0.1.dist-info/METADATA +69 -0
- sequence_layers-0.1.dist-info/RECORD +55 -0
- sequence_layers-0.1.dist-info/WHEEL +4 -0
- sequence_layers-0.1.dist-info/licenses/LICENSE +202 -0
|
@@ -0,0 +1,1771 @@
|
|
|
1
|
+
# Copyright 2024 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
|
+
|
|
15
|
+
|
|
16
|
+
"""Reference implementations for Very Attentive Tacotron.
|
|
17
|
+
|
|
18
|
+
From the paper:
|
|
19
|
+
"Very Attentive Tacotron: Robust and Unbounded Length Generalization in
|
|
20
|
+
Transformer-based Text-to-Speech."
|
|
21
|
+
https://arxiv.org/abs/2410.22179
|
|
22
|
+
|
|
23
|
+
Includes text encoder and autoregressive decoder configurations for the
|
|
24
|
+
large and small (3/8 width) variants of the T5 baseline model and the
|
|
25
|
+
proposed Very Attentive Tacotron (VAT) model.
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
import abc
|
|
30
|
+
import dataclasses
|
|
31
|
+
import functools
|
|
32
|
+
import math
|
|
33
|
+
|
|
34
|
+
import numpy as np
|
|
35
|
+
from sequence_layers import tensorflow as sl
|
|
36
|
+
from sequence_layers.tensorflow import utils
|
|
37
|
+
from sequence_layers.tensorflow.examples import t5
|
|
38
|
+
import tensorflow.compat.v2 as tf
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
# Value used to bias the attention logits for excluded positions.
|
|
42
|
+
ATTENTION_MASK_BIAS = -1e9
|
|
43
|
+
# Epsilon value to prevent log underflow.
|
|
44
|
+
LOG_EPS = 1e-16
|
|
45
|
+
# Constants key for alignment position.
|
|
46
|
+
ALIGNMENT_POSITION = 'alignment_position'
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
# ------------------------------------------------------------------------------
|
|
50
|
+
# Text encoder configurations.
|
|
51
|
+
# ------------------------------------------------------------------------------
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def SmallT5BaselineTextEncoder() -> sl.SequenceLayer:
|
|
55
|
+
return TextEncoder(
|
|
56
|
+
dimension=192,
|
|
57
|
+
use_irpbs=False,
|
|
58
|
+
name='small_t5_tts_text_encoder',
|
|
59
|
+
)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def SmallVATTextEncoder() -> sl.SequenceLayer:
|
|
63
|
+
return TextEncoder(
|
|
64
|
+
dimension=192,
|
|
65
|
+
use_irpbs=True,
|
|
66
|
+
name='small_vat_text_encoder',
|
|
67
|
+
)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def LargeT5BaselineTextEncoder() -> sl.SequenceLayer:
|
|
71
|
+
return TextEncoder(
|
|
72
|
+
dimension=512,
|
|
73
|
+
use_irpbs=False,
|
|
74
|
+
name='large_t5_tts_text_encoder',
|
|
75
|
+
)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def LargeVATTextEncoder() -> sl.SequenceLayer:
|
|
79
|
+
return TextEncoder(
|
|
80
|
+
dimension=512,
|
|
81
|
+
use_irpbs=True,
|
|
82
|
+
name='large_vat_text_encoder',
|
|
83
|
+
)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
# ------------------------------------------------------------------------------
|
|
87
|
+
# Decoder configurations.
|
|
88
|
+
# ------------------------------------------------------------------------------
|
|
89
|
+
def SmallT5BaselineDecoder() -> sl.SequenceLayer:
|
|
90
|
+
decoder_block_num_heads = 8
|
|
91
|
+
decoder_block_units_per_head = 48
|
|
92
|
+
decoder_block_hidden_dim = (
|
|
93
|
+
decoder_block_num_heads * decoder_block_units_per_head
|
|
94
|
+
)
|
|
95
|
+
return T5BaselineDecoder(
|
|
96
|
+
config=T5BaselineDecoderConfig(
|
|
97
|
+
name='t5_tts_decoder',
|
|
98
|
+
source_name='text_encoder_top',
|
|
99
|
+
num_codebooks=8,
|
|
100
|
+
codebook_size=256,
|
|
101
|
+
num_decoder_blocks=6,
|
|
102
|
+
num_heads=decoder_block_num_heads,
|
|
103
|
+
units_per_head=decoder_block_units_per_head,
|
|
104
|
+
ffn_dimension=decoder_block_hidden_dim * 4,
|
|
105
|
+
dropout_rate=0.1,
|
|
106
|
+
max_past_horizon=128,
|
|
107
|
+
),
|
|
108
|
+
)
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def SmallVATDecoder() -> sl.SequenceLayer:
|
|
112
|
+
decoder_block_num_heads = 8
|
|
113
|
+
decoder_block_units_per_head = 48
|
|
114
|
+
decoder_block_hidden_dim = (
|
|
115
|
+
decoder_block_num_heads * decoder_block_units_per_head
|
|
116
|
+
)
|
|
117
|
+
return VATDecoder(
|
|
118
|
+
config=VATDecoderConfig(
|
|
119
|
+
name='very_attentive_decoder',
|
|
120
|
+
source_name='text_encoder_top',
|
|
121
|
+
alignment_layer=AlignmentLayerConfig(alignment_rnn_units=96),
|
|
122
|
+
num_codebooks=8,
|
|
123
|
+
codebook_size=256,
|
|
124
|
+
num_decoder_blocks=6,
|
|
125
|
+
dropout_rate=0.1,
|
|
126
|
+
decoder_block=DecoderBlockConfig(
|
|
127
|
+
alignment_rnn_units=96,
|
|
128
|
+
num_heads=decoder_block_num_heads,
|
|
129
|
+
units_per_head=decoder_block_units_per_head,
|
|
130
|
+
hidden_dim=decoder_block_hidden_dim,
|
|
131
|
+
feedforward_hidden_dim=decoder_block_hidden_dim * 4,
|
|
132
|
+
),
|
|
133
|
+
),
|
|
134
|
+
)
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def LargeT5BaselineDecoder() -> sl.SequenceLayer:
|
|
138
|
+
decoder_block_num_heads = 16
|
|
139
|
+
decoder_block_units_per_head = 64
|
|
140
|
+
decoder_block_hidden_dim = (
|
|
141
|
+
decoder_block_num_heads * decoder_block_units_per_head
|
|
142
|
+
)
|
|
143
|
+
return T5BaselineDecoder(
|
|
144
|
+
config=T5BaselineDecoderConfig(
|
|
145
|
+
name='t5_tts_decoder',
|
|
146
|
+
source_name='text_encoder_top',
|
|
147
|
+
num_codebooks=8,
|
|
148
|
+
codebook_size=256,
|
|
149
|
+
num_decoder_blocks=6,
|
|
150
|
+
num_heads=decoder_block_num_heads,
|
|
151
|
+
units_per_head=decoder_block_units_per_head,
|
|
152
|
+
ffn_dimension=decoder_block_hidden_dim * 4,
|
|
153
|
+
dropout_rate=0.1,
|
|
154
|
+
max_past_horizon=128,
|
|
155
|
+
),
|
|
156
|
+
)
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def LargeVATDecoder() -> sl.SequenceLayer:
|
|
160
|
+
decoder_block_num_heads = 16
|
|
161
|
+
decoder_block_units_per_head = 64
|
|
162
|
+
decoder_block_hidden_dim = (
|
|
163
|
+
decoder_block_num_heads * decoder_block_units_per_head
|
|
164
|
+
)
|
|
165
|
+
return VATDecoder(
|
|
166
|
+
config=VATDecoderConfig(
|
|
167
|
+
name='very_attentive_decoder',
|
|
168
|
+
source_name='text_encoder_top',
|
|
169
|
+
alignment_layer=AlignmentLayerConfig(alignment_rnn_units=256),
|
|
170
|
+
num_codebooks=8,
|
|
171
|
+
codebook_size=256,
|
|
172
|
+
num_decoder_blocks=6,
|
|
173
|
+
dropout_rate=0.1,
|
|
174
|
+
decoder_block=DecoderBlockConfig(
|
|
175
|
+
alignment_rnn_units=96,
|
|
176
|
+
num_heads=decoder_block_num_heads,
|
|
177
|
+
units_per_head=decoder_block_units_per_head,
|
|
178
|
+
hidden_dim=decoder_block_hidden_dim,
|
|
179
|
+
feedforward_hidden_dim=decoder_block_hidden_dim * 4,
|
|
180
|
+
),
|
|
181
|
+
),
|
|
182
|
+
)
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
class PreprocessConstants(abc.ABC):
|
|
186
|
+
"""sl.SequenceLayer mix-in for preprocess_constants support."""
|
|
187
|
+
|
|
188
|
+
@abc.abstractmethod
|
|
189
|
+
def preprocess_constants(self, constants: sl.Constants) -> None: # pylint: disable=invalid-name
|
|
190
|
+
"""Preprocess constants and stash resulting Tensors internally.
|
|
191
|
+
|
|
192
|
+
This method allows a SequenceLayer to precompute and stash constant-derived
|
|
193
|
+
values so they don't need to be recomputed on each call to step.
|
|
194
|
+
|
|
195
|
+
Args:
|
|
196
|
+
constants: Constants to preprocess.
|
|
197
|
+
"""
|
|
198
|
+
|
|
199
|
+
@abc.abstractmethod
|
|
200
|
+
def clear_preprocessed_constants(self) -> None: # pylint: disable=invalid-name
|
|
201
|
+
"""Clear preprocessed constants.
|
|
202
|
+
|
|
203
|
+
This method should remove any internally stashed preprocessed constants when
|
|
204
|
+
they are no longer needed in the current graph (or tf.function). This is to
|
|
205
|
+
prevent Tensors from crossing from one graph to another (which results in
|
|
206
|
+
an error.)
|
|
207
|
+
"""
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def FeedforwardBlock(
|
|
211
|
+
hidden_dim: int,
|
|
212
|
+
output_dim: int,
|
|
213
|
+
activation: ...,
|
|
214
|
+
dropout_rate: float,
|
|
215
|
+
) -> sl.SequenceLayer:
|
|
216
|
+
"""T5-style feed-forward block."""
|
|
217
|
+
return sl.Residual([
|
|
218
|
+
sl.RMSNormalization(epsilon=1e-6, name='rms_normalization'),
|
|
219
|
+
sl.Dense(hidden_dim, use_bias=False, activation=activation),
|
|
220
|
+
sl.Dropout(dropout_rate, noise_shape=[None, 1, None]),
|
|
221
|
+
sl.Dense(output_dim, use_bias=False, name='dense'),
|
|
222
|
+
sl.Dropout(dropout_rate, noise_shape=[None, 1, None]),
|
|
223
|
+
])
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
# ------------------------------------------------------------------------------
|
|
227
|
+
# Relative position embedding helper classes.
|
|
228
|
+
# ------------------------------------------------------------------------------
|
|
229
|
+
@dataclasses.dataclass
|
|
230
|
+
class InterpolatedRelativePositionBiasesConfig:
|
|
231
|
+
"""Configuration for InterpolatedRelativePositionBiases."""
|
|
232
|
+
|
|
233
|
+
# Number of buckets to use for the relative position bias matrix.
|
|
234
|
+
num_buckets: int
|
|
235
|
+
# Maximum relative distance to support. All distances above this value are
|
|
236
|
+
# mapped to the same bucket.
|
|
237
|
+
max_distance: int
|
|
238
|
+
# Scale of value to subtract from the output position biases for relative
|
|
239
|
+
# positions that exceed max_distance. The subtracted value is equal to:
|
|
240
|
+
# `max_distance_penalty * (abs(relative_position) - max_distance)`.
|
|
241
|
+
max_distance_penalty: float
|
|
242
|
+
# pyformat: disable
|
|
243
|
+
# Bias matrix initialization scheme. One of:
|
|
244
|
+
# * 'constant': Initialize all biases to `init_scheme_value`.
|
|
245
|
+
# * 'gaussian_window_stddev': Initialize biases with values drawn from a
|
|
246
|
+
# Gaussian distribution centered at relative position 0, with standard
|
|
247
|
+
# deviation `init_scheme_value`.
|
|
248
|
+
# * 'truncated_normal_stddev': Initialize biases with values drawn from a
|
|
249
|
+
# truncated normal distribution centered at relative position 0, with
|
|
250
|
+
# standard deviation `init_scheme_value`.
|
|
251
|
+
# pyformat: enable
|
|
252
|
+
init_scheme: str
|
|
253
|
+
# Value to use for the bias matrix initialization scheme.
|
|
254
|
+
init_scheme_value: float
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
@dataclasses.dataclass
|
|
258
|
+
class T5RelativePositionEmbeddingConfig:
|
|
259
|
+
"""Configuration for sl.T5RelativePositionEmbedding."""
|
|
260
|
+
|
|
261
|
+
# Number of buckets to use for the relative position bias matrix.
|
|
262
|
+
num_buckets: int
|
|
263
|
+
# Maximum relative distance to support. All distances above this value are
|
|
264
|
+
# mapped to the same bucket.
|
|
265
|
+
max_distance: int
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
class GaussianWindowBiasInitializer(tf.keras.initializers.Initializer):
|
|
269
|
+
"""Gaussian window initializer for InterpolatedRelativePositionBiases.
|
|
270
|
+
|
|
271
|
+
This returns the normalized logits of a Gaussian window.
|
|
272
|
+
"""
|
|
273
|
+
|
|
274
|
+
def __init__(self, stddev: float, bidirectional: bool):
|
|
275
|
+
"""Construct GaussianWindowBiasInitializer.
|
|
276
|
+
|
|
277
|
+
Args:
|
|
278
|
+
stddev: The standard deviation of the Gaussian window.
|
|
279
|
+
bidirectional: Whether the position biases are bidirectional. This
|
|
280
|
+
determines where the window is centered.
|
|
281
|
+
"""
|
|
282
|
+
self.bidirectional = bidirectional
|
|
283
|
+
self.stddev = stddev
|
|
284
|
+
|
|
285
|
+
def __call__(self, shape, dtype=tf.float32, **kwargs):
|
|
286
|
+
num_buckets, num_heads = shape
|
|
287
|
+
|
|
288
|
+
# Work around missing bfloat16 support in tf.range.
|
|
289
|
+
if dtype == tf.bfloat16:
|
|
290
|
+
bucket_inds = tf.cast(
|
|
291
|
+
tf.range(num_buckets, dtype=tf.float32), tf.bfloat16
|
|
292
|
+
)
|
|
293
|
+
else:
|
|
294
|
+
bucket_inds = tf.range(num_buckets, dtype=dtype)
|
|
295
|
+
if self.bidirectional:
|
|
296
|
+
offset = num_buckets // 2
|
|
297
|
+
else:
|
|
298
|
+
offset = 0
|
|
299
|
+
|
|
300
|
+
logits = -0.5 * tf.square((bucket_inds - offset) / self.stddev)
|
|
301
|
+
logits -= tf.math.reduce_logsumexp(logits) # Normalize logits.
|
|
302
|
+
|
|
303
|
+
biases = tf.tile(logits[:, tf.newaxis], [1, num_heads])
|
|
304
|
+
return biases
|
|
305
|
+
|
|
306
|
+
|
|
307
|
+
class InterpolatedRelativePositionBiases(sl.RelativePositionEmbedding):
|
|
308
|
+
"""InterpolatedRelativePositionBiases.
|
|
309
|
+
|
|
310
|
+
This is an extension of T5's relative position biases that supports
|
|
311
|
+
non-integer relative positions. This is done by interpolating between
|
|
312
|
+
bias values for adjacent integer bins. Additionally, interpolation is used
|
|
313
|
+
to compute the bias values for the "non-exact" logarithmically spaced bins
|
|
314
|
+
(as an alternative to flooring to the nearest bin).
|
|
315
|
+
|
|
316
|
+
The motivation behind this scheme is to support location-relative
|
|
317
|
+
cross-attention where the "query" position is differentiable; and therefore,
|
|
318
|
+
must be continuous.
|
|
319
|
+
|
|
320
|
+
This also supports the SequenceLayer RelativePositionEmbedding interface.
|
|
321
|
+
"""
|
|
322
|
+
|
|
323
|
+
def __init__(
|
|
324
|
+
self,
|
|
325
|
+
num_heads: int,
|
|
326
|
+
num_buckets: int,
|
|
327
|
+
max_distance: int,
|
|
328
|
+
max_distance_penalty: float,
|
|
329
|
+
bidirectional: bool,
|
|
330
|
+
initializer: str,
|
|
331
|
+
name: str | None = None,
|
|
332
|
+
):
|
|
333
|
+
"""Construct InterpolatedRelativePositionBiases.
|
|
334
|
+
|
|
335
|
+
Args:
|
|
336
|
+
num_heads: Number of biases to produce for each relative position.
|
|
337
|
+
num_buckets: Number of relative position buckets to use.
|
|
338
|
+
max_distance: Maximum relative distance to support. All distances above
|
|
339
|
+
this value are mapped to the same bucket.
|
|
340
|
+
max_distance_penalty: Scale of value to subtract from the output position
|
|
341
|
+
biases for relative positions that exceed max_distance. The subtracted
|
|
342
|
+
value is equal to: `max_distance_penalty * (abs(relative_position) -
|
|
343
|
+
max_distance)`.
|
|
344
|
+
bidirectional: Whether biases should be produced for both positive and
|
|
345
|
+
negative relative positions. If False, positive relative positions
|
|
346
|
+
(where key_position > query_position) are not supported.
|
|
347
|
+
initializer: Initializer for the biases (embedding) matrix.
|
|
348
|
+
name: Module name.
|
|
349
|
+
|
|
350
|
+
If bidirectional is True, the buckets are evenly split between positive and
|
|
351
|
+
negative relative positions; if False, all of the buckets are used for
|
|
352
|
+
negative relative positions (and zero). In either case, half of the buckets
|
|
353
|
+
are used for "exact" relative positions and the other half are used for
|
|
354
|
+
logarithmically-spaced buckets of increasing size.
|
|
355
|
+
|
|
356
|
+
Positive relative positions greater than or equal to max_distance are
|
|
357
|
+
mapped to the same bias bucket. Negative relative positions less than or
|
|
358
|
+
equal to -max_distance are mapped to the same bias bucket.
|
|
359
|
+
"""
|
|
360
|
+
super().__init__(name=name)
|
|
361
|
+
self.num_heads = num_heads
|
|
362
|
+
self.num_buckets = num_buckets
|
|
363
|
+
self.bidirectional = bidirectional
|
|
364
|
+
self.max_distance = max_distance
|
|
365
|
+
self.max_distance_penalty = max_distance_penalty
|
|
366
|
+
with self.name_scope:
|
|
367
|
+
self.bias_matrix = tf.keras.layers.Embedding(
|
|
368
|
+
input_dim=self.num_buckets,
|
|
369
|
+
output_dim=self.num_heads,
|
|
370
|
+
embeddings_initializer=initializer,
|
|
371
|
+
use_one_hot_matmul=True, # Avoid gathers on TPU.
|
|
372
|
+
name='bias_matrix',
|
|
373
|
+
)
|
|
374
|
+
|
|
375
|
+
@classmethod
|
|
376
|
+
def from_config(
|
|
377
|
+
cls,
|
|
378
|
+
num_heads: int,
|
|
379
|
+
bidirectional: bool,
|
|
380
|
+
config: InterpolatedRelativePositionBiasesConfig,
|
|
381
|
+
) -> 'InterpolatedRelativePositionBiases':
|
|
382
|
+
|
|
383
|
+
if config.init_scheme is None or config.init_scheme == 'constant':
|
|
384
|
+
initializer = tf.keras.initializers.Constant(config.init_scheme_value)
|
|
385
|
+
elif config.init_scheme == 'gaussian_window_stddev':
|
|
386
|
+
initializer = GaussianWindowBiasInitializer(
|
|
387
|
+
config.init_scheme_value, bidirectional=bidirectional
|
|
388
|
+
)
|
|
389
|
+
elif config.init_scheme == 'truncated_normal_stddev':
|
|
390
|
+
initializer = tf.keras.initializers.TruncatedNormal(
|
|
391
|
+
stddev=config.init_scheme_value
|
|
392
|
+
)
|
|
393
|
+
else:
|
|
394
|
+
raise NotImplementedError(f'Unknown {config.init_scheme=}')
|
|
395
|
+
|
|
396
|
+
return cls(
|
|
397
|
+
num_heads=num_heads,
|
|
398
|
+
num_buckets=config.num_buckets,
|
|
399
|
+
max_distance=config.max_distance,
|
|
400
|
+
max_distance_penalty=config.max_distance_penalty,
|
|
401
|
+
bidirectional=bidirectional,
|
|
402
|
+
initializer=initializer,
|
|
403
|
+
)
|
|
404
|
+
|
|
405
|
+
def _relative_position_bucket(self, relative_position):
|
|
406
|
+
"""Translate relative position to a continuous bucket value.
|
|
407
|
+
|
|
408
|
+
The relative position is defined as memory_position - query_position, i.e.
|
|
409
|
+
the distance in tokens from the attending position to the attended-to
|
|
410
|
+
position.
|
|
411
|
+
|
|
412
|
+
If bidirectional=False, then positive relative positions are invalid.
|
|
413
|
+
|
|
414
|
+
We use smaller buckets for small absolute relative_position and larger
|
|
415
|
+
buckets for larger absolute relative_positions.
|
|
416
|
+
|
|
417
|
+
All relative positions >=max_distance map to the same bucket.
|
|
418
|
+
|
|
419
|
+
All relative positions <=-max_distance map to the same bucket.
|
|
420
|
+
|
|
421
|
+
Args:
|
|
422
|
+
relative_position: a float32 Tensor
|
|
423
|
+
|
|
424
|
+
Returns:
|
|
425
|
+
a Tensor with the same shape as relative_position, containing float32
|
|
426
|
+
values in the range [0, num_buckets)
|
|
427
|
+
"""
|
|
428
|
+
is_positive = None
|
|
429
|
+
n = -relative_position
|
|
430
|
+
if self.bidirectional:
|
|
431
|
+
buckets_per_side = self.num_buckets // 2
|
|
432
|
+
is_positive = tf.math.less(n, 0) # n = -relative_position
|
|
433
|
+
n = tf.math.abs(n)
|
|
434
|
+
else:
|
|
435
|
+
buckets_per_side = self.num_buckets
|
|
436
|
+
n = tf.math.maximum(n, 0)
|
|
437
|
+
# now n is in the range [0, inf)
|
|
438
|
+
max_exact = buckets_per_side // 2
|
|
439
|
+
is_small = tf.math.less(n, max_exact)
|
|
440
|
+
# Note that `(buckets_per_side - 1 - max_exact)` below differs from the
|
|
441
|
+
# reference implementation of T5 relative position biases which uses
|
|
442
|
+
# `(buckets_per_side - max_exact)`, and therefore doesn't produce the
|
|
443
|
+
# max_distance behavior described in the docstring above.
|
|
444
|
+
val_if_large = max_exact + (
|
|
445
|
+
tf.math.log(n / max_exact + LOG_EPS)
|
|
446
|
+
/ math.log(self.max_distance / max_exact)
|
|
447
|
+
* (buckets_per_side - 1 - max_exact)
|
|
448
|
+
)
|
|
449
|
+
val_if_large = tf.math.minimum(val_if_large, buckets_per_side - 1)
|
|
450
|
+
val = tf.where(is_small, n, val_if_large)
|
|
451
|
+
if self.bidirectional:
|
|
452
|
+
# Relative position `0` is centered in the bias matrix.
|
|
453
|
+
val = tf.where(
|
|
454
|
+
is_positive, buckets_per_side + val, buckets_per_side - val
|
|
455
|
+
)
|
|
456
|
+
return val
|
|
457
|
+
|
|
458
|
+
@tf.Module.with_name_scope
|
|
459
|
+
def __call__(
|
|
460
|
+
self, query_positions: tf.Tensor, key_positions: tf.Tensor
|
|
461
|
+
) -> tf.Tensor:
|
|
462
|
+
"""Get biases from position indices.
|
|
463
|
+
|
|
464
|
+
Args:
|
|
465
|
+
query_positions: [batch, query_length] int/float Tensor containing query
|
|
466
|
+
position indices.
|
|
467
|
+
key_positions: [batch, key_length] int/float Tensor containing position
|
|
468
|
+
indices.
|
|
469
|
+
|
|
470
|
+
Returns:
|
|
471
|
+
position_biases: [batch, num_heads, query_length, key_length] Tensor
|
|
472
|
+
containing head-wise biases for each query-key pair.
|
|
473
|
+
"""
|
|
474
|
+
compute_dtype = utils.compute_dtype()
|
|
475
|
+
# [batch, query_length, 1]
|
|
476
|
+
query_positions = tf.cast(query_positions[:, :, tf.newaxis], compute_dtype)
|
|
477
|
+
# [batch, 1, key_length]
|
|
478
|
+
key_positions = tf.cast(key_positions[:, tf.newaxis, :], compute_dtype)
|
|
479
|
+
# [batch, query_length, key_length]
|
|
480
|
+
relative_positions = key_positions - query_positions
|
|
481
|
+
bucket_val = self._relative_position_bucket(relative_positions)
|
|
482
|
+
|
|
483
|
+
# Interpolate between adjacent buckets.
|
|
484
|
+
bucket_ind_low = tf.math.floor(bucket_val)
|
|
485
|
+
bucket_ind_high = tf.math.ceil(bucket_val)
|
|
486
|
+
# [batch, query_length, key_length, 1]
|
|
487
|
+
high_weight = tf.expand_dims(bucket_val - bucket_ind_low, axis=-1)
|
|
488
|
+
# [batch, query_length, key_length, num_heads]
|
|
489
|
+
biases_low = self.bias_matrix(tf.cast(bucket_ind_low, tf.int32))
|
|
490
|
+
biases_high = self.bias_matrix(tf.cast(bucket_ind_high, tf.int32))
|
|
491
|
+
biases = (1.0 - high_weight) * biases_low + high_weight * biases_high
|
|
492
|
+
|
|
493
|
+
# Apply optional max_distance_penalty.
|
|
494
|
+
if self.max_distance_penalty != 0.0:
|
|
495
|
+
# [batch, query_length, key_length]
|
|
496
|
+
excess_distance = tf.maximum(
|
|
497
|
+
0.0, tf.abs(relative_positions) - self.max_distance
|
|
498
|
+
)
|
|
499
|
+
penalty_amount = excess_distance * self.max_distance_penalty
|
|
500
|
+
# [batch, query_length, key_length, num_heads]
|
|
501
|
+
biases -= penalty_amount[:, :, :, tf.newaxis]
|
|
502
|
+
|
|
503
|
+
# -> [batch, num_heads, query_length, key_length]
|
|
504
|
+
position_biases = tf.transpose(biases, [0, 3, 1, 2])
|
|
505
|
+
|
|
506
|
+
return position_biases
|
|
507
|
+
|
|
508
|
+
@tf.Module.with_name_scope
|
|
509
|
+
def get_position_bias_raw(
|
|
510
|
+
self,
|
|
511
|
+
queries_position: tf.Tensor,
|
|
512
|
+
queries_length: tf.Tensor | int,
|
|
513
|
+
keys_position: tf.Tensor,
|
|
514
|
+
keys_length: tf.Tensor | int,
|
|
515
|
+
) -> tf.Tensor:
|
|
516
|
+
"""Computes relative self-attention position biases for absolute positions.
|
|
517
|
+
|
|
518
|
+
This method computes relative position biases for absolute query / key
|
|
519
|
+
positions and lengths.
|
|
520
|
+
|
|
521
|
+
Args:
|
|
522
|
+
queries_position: Scalar integer query absolute position.
|
|
523
|
+
queries_length: Number of query timesteps to produce relative position
|
|
524
|
+
embeddings for.
|
|
525
|
+
keys_position: Scalar integer key absolute position.
|
|
526
|
+
keys_length: Number of key timesteps to produce relative position
|
|
527
|
+
embeddings for.
|
|
528
|
+
|
|
529
|
+
Returns:
|
|
530
|
+
A tensor of relative position biases broadcastable to
|
|
531
|
+
[batch, queries_length, num_heads, keys_length].
|
|
532
|
+
"""
|
|
533
|
+
queries_positions = (
|
|
534
|
+
queries_position + tf.range(queries_length)[tf.newaxis, :]
|
|
535
|
+
)
|
|
536
|
+
keys_positions = keys_position + tf.range(keys_length)[tf.newaxis, :]
|
|
537
|
+
|
|
538
|
+
position_biases = self(queries_positions, keys_positions)
|
|
539
|
+
position_biases = tf.transpose(position_biases, [0, 2, 1, 3])
|
|
540
|
+
return position_biases
|
|
541
|
+
|
|
542
|
+
@tf.Module.with_name_scope
|
|
543
|
+
def get_position_bias_streaming(
|
|
544
|
+
self, queries: tf.Tensor, keys: tf.Tensor, queries_position: tf.Tensor
|
|
545
|
+
) -> tf.Tensor:
|
|
546
|
+
"""Computes relative self-attention position biases for streaming queries.
|
|
547
|
+
|
|
548
|
+
This method computes relative position biases for a block of queries_time
|
|
549
|
+
timesteps of the overall queries tensor, and the keys/values available are
|
|
550
|
+
always the queries within the current queries_time block, and a fixed
|
|
551
|
+
"max_previous" trailing window of timesteps.
|
|
552
|
+
|
|
553
|
+
Args:
|
|
554
|
+
queries: [batch, queries_time, num_heads, units_per_head] queries.
|
|
555
|
+
queries_time is the number of streaming steps we are taking at once.
|
|
556
|
+
keys: [batch, queries_time + max_previous, num_heads, units_per_head]
|
|
557
|
+
keys.
|
|
558
|
+
queries_position: scalar integer indicating the current decode position of
|
|
559
|
+
queries[:, 0, :]. For example, this value is n * queries_time for the
|
|
560
|
+
n'th queries_time block we process.
|
|
561
|
+
|
|
562
|
+
Returns:
|
|
563
|
+
A tensor of relative position biases broadcastable to
|
|
564
|
+
[batch, num_heads, queries_time, keys_time].
|
|
565
|
+
"""
|
|
566
|
+
queries_time_static = queries.shape.dims[1].value
|
|
567
|
+
keys_time_static = keys.shape.dims[1].value
|
|
568
|
+
queries_time = sl.utils.smart_dimension_size(queries, 1)
|
|
569
|
+
keys_time = sl.utils.smart_dimension_size(keys, 1)
|
|
570
|
+
|
|
571
|
+
# Add singleton batch dimension to context/memory_position.
|
|
572
|
+
context_position = queries_position + tf.range(queries_time)[tf.newaxis, :]
|
|
573
|
+
# keys[:, 0, :]'s absolute position is queries_position - max_previous.
|
|
574
|
+
max_previous = keys_time - queries_time
|
|
575
|
+
memory_start_position = queries_position - max_previous
|
|
576
|
+
memory_position = memory_start_position + tf.range(keys_time)[tf.newaxis, :]
|
|
577
|
+
|
|
578
|
+
values = self.__call__(context_position, memory_position)
|
|
579
|
+
values.shape.assert_is_compatible_with(
|
|
580
|
+
[1, self.num_heads, queries_time_static, keys_time_static]
|
|
581
|
+
)
|
|
582
|
+
return values
|
|
583
|
+
|
|
584
|
+
@tf.Module.with_name_scope
|
|
585
|
+
def get_position_bias(self, queries: tf.Tensor) -> tf.Tensor:
|
|
586
|
+
"""Computes relative self-attention position biases for queries.
|
|
587
|
+
|
|
588
|
+
Args:
|
|
589
|
+
queries: [batch, queries_time, num_heads, units_per_head] queries.
|
|
590
|
+
|
|
591
|
+
Returns:
|
|
592
|
+
A tensor of relative position biases broadcastable to
|
|
593
|
+
[batch, num_heads, queries_time, keys_time].
|
|
594
|
+
"""
|
|
595
|
+
queries_time_static = queries.shape.dims[1].value
|
|
596
|
+
queries_time = sl.utils.smart_dimension_size(queries, 1)
|
|
597
|
+
# Add singleton batch dimension.
|
|
598
|
+
context_position = tf.range(queries_time)[tf.newaxis, :]
|
|
599
|
+
values = self.__call__(context_position, context_position)
|
|
600
|
+
values.shape.assert_is_compatible_with(
|
|
601
|
+
[1, self.num_heads, queries_time_static, queries_time_static]
|
|
602
|
+
)
|
|
603
|
+
return values
|
|
604
|
+
|
|
605
|
+
|
|
606
|
+
# ------------------------------------------------------------------------------
|
|
607
|
+
# Text encoder helper classes.
|
|
608
|
+
# ------------------------------------------------------------------------------
|
|
609
|
+
def ConvStage(
|
|
610
|
+
num_blocks: int,
|
|
611
|
+
strides: int,
|
|
612
|
+
num_filters: int = 256,
|
|
613
|
+
kernel_size: int = 3,
|
|
614
|
+
output_dim: int = 256,
|
|
615
|
+
dropout_rate: float = 0.1,
|
|
616
|
+
name: str = 'conv_stage',
|
|
617
|
+
) -> sl.SequenceLayer:
|
|
618
|
+
"""A sequence of N Conv1D residual blocks plus a final rms_norm + dropout."""
|
|
619
|
+
|
|
620
|
+
def ConvBlock(block_ind):
|
|
621
|
+
return sl.Residual(
|
|
622
|
+
[
|
|
623
|
+
sl.RMSNormalization(epsilon=1e-6, name='rms_norm'),
|
|
624
|
+
sl.Conv1D(
|
|
625
|
+
filters=num_filters,
|
|
626
|
+
kernel_size=kernel_size,
|
|
627
|
+
dilation_rate=1,
|
|
628
|
+
padding='same',
|
|
629
|
+
activation=tf.nn.gelu,
|
|
630
|
+
name='conv_layer',
|
|
631
|
+
),
|
|
632
|
+
sl.Dropout(dropout_rate, noise_shape=[-1, 1, -1]),
|
|
633
|
+
sl.Dense(units=output_dim, use_bias=False, name='output_layer'),
|
|
634
|
+
sl.Dropout(dropout_rate, noise_shape=[-1, 1, -1]),
|
|
635
|
+
],
|
|
636
|
+
name=f'residual_block_{block_ind:02d}',
|
|
637
|
+
)
|
|
638
|
+
|
|
639
|
+
return sl.Serial(
|
|
640
|
+
[
|
|
641
|
+
sl.Conv1D(
|
|
642
|
+
filters=num_filters,
|
|
643
|
+
kernel_size=3,
|
|
644
|
+
strides=strides,
|
|
645
|
+
padding='same',
|
|
646
|
+
name='resample_conv1d',
|
|
647
|
+
)
|
|
648
|
+
]
|
|
649
|
+
+ [ConvBlock(block_ind) for block_ind in range(num_blocks)]
|
|
650
|
+
+ [
|
|
651
|
+
sl.RMSNormalization(epsilon=1e-6, name='rms_norm'),
|
|
652
|
+
sl.Dropout(dropout_rate, noise_shape=[-1, 1, -1]),
|
|
653
|
+
],
|
|
654
|
+
name=name,
|
|
655
|
+
)
|
|
656
|
+
|
|
657
|
+
|
|
658
|
+
def SelfAttentionBlock(
|
|
659
|
+
output_dim: int,
|
|
660
|
+
num_heads: int,
|
|
661
|
+
units_per_head: int,
|
|
662
|
+
max_horizon: int,
|
|
663
|
+
max_future_horizon: int,
|
|
664
|
+
relative_position_embedding: (
|
|
665
|
+
InterpolatedRelativePositionBiases | sl.T5RelativePositionEmbedding
|
|
666
|
+
),
|
|
667
|
+
dropout_rate: float,
|
|
668
|
+
) -> sl.SequenceLayer:
|
|
669
|
+
"""Self-attention with relative position biases (interpolated or not)."""
|
|
670
|
+
return sl.Residual([
|
|
671
|
+
sl.RMSNormalization(epsilon=1e-6, name='rms_normalization'),
|
|
672
|
+
sl.DotProductSelfAttention(
|
|
673
|
+
num_heads=num_heads,
|
|
674
|
+
units_per_head=units_per_head,
|
|
675
|
+
max_horizon=max_horizon,
|
|
676
|
+
max_future_horizon=max_future_horizon,
|
|
677
|
+
use_relative_position_embedding=True,
|
|
678
|
+
relative_position_embedding=relative_position_embedding,
|
|
679
|
+
attention_probabilities_dropout_rate=dropout_rate,
|
|
680
|
+
broadcast_dropout_across_queries=True,
|
|
681
|
+
use_bias=False,
|
|
682
|
+
name='dot_product_self_attention',
|
|
683
|
+
),
|
|
684
|
+
sl.Flatten(),
|
|
685
|
+
sl.Dense(output_dim, use_bias=False, name='dense'),
|
|
686
|
+
sl.Dropout(dropout_rate, noise_shape=[None, 1, None]),
|
|
687
|
+
])
|
|
688
|
+
|
|
689
|
+
|
|
690
|
+
def TransformerEncoderBlock(
|
|
691
|
+
dimension: int,
|
|
692
|
+
num_heads: int,
|
|
693
|
+
units_per_head: int,
|
|
694
|
+
position_embeddings_config: (
|
|
695
|
+
InterpolatedRelativePositionBiasesConfig
|
|
696
|
+
| T5RelativePositionEmbeddingConfig
|
|
697
|
+
),
|
|
698
|
+
ffn_activation: ... = tf.nn.gelu,
|
|
699
|
+
dropout_rate: float = 0.1,
|
|
700
|
+
) -> sl.SequenceLayer:
|
|
701
|
+
"""Self-attention + feed-forward encoder block."""
|
|
702
|
+
|
|
703
|
+
if isinstance(
|
|
704
|
+
position_embeddings_config, InterpolatedRelativePositionBiasesConfig
|
|
705
|
+
):
|
|
706
|
+
position_embeddings = InterpolatedRelativePositionBiases.from_config(
|
|
707
|
+
bidirectional=True,
|
|
708
|
+
num_heads=num_heads,
|
|
709
|
+
config=position_embeddings_config,
|
|
710
|
+
)
|
|
711
|
+
else:
|
|
712
|
+
position_embeddings = sl.T5RelativePositionEmbedding(
|
|
713
|
+
num_buckets=position_embeddings_config.num_buckets,
|
|
714
|
+
num_heads=num_heads,
|
|
715
|
+
bidirectional=True,
|
|
716
|
+
max_distance=position_embeddings_config.max_distance,
|
|
717
|
+
)
|
|
718
|
+
return sl.Serial([
|
|
719
|
+
SelfAttentionBlock(
|
|
720
|
+
output_dim=dimension,
|
|
721
|
+
num_heads=num_heads,
|
|
722
|
+
units_per_head=units_per_head,
|
|
723
|
+
relative_position_embedding=position_embeddings,
|
|
724
|
+
max_horizon=-1,
|
|
725
|
+
max_future_horizon=-1,
|
|
726
|
+
dropout_rate=dropout_rate,
|
|
727
|
+
),
|
|
728
|
+
FeedforwardBlock(
|
|
729
|
+
output_dim=dimension,
|
|
730
|
+
hidden_dim=dimension * 4,
|
|
731
|
+
activation=ffn_activation,
|
|
732
|
+
dropout_rate=dropout_rate,
|
|
733
|
+
),
|
|
734
|
+
])
|
|
735
|
+
|
|
736
|
+
|
|
737
|
+
# ------------------------------------------------------------------------------
|
|
738
|
+
# Text encoder base class.
|
|
739
|
+
# ------------------------------------------------------------------------------
|
|
740
|
+
def TextEncoder(
|
|
741
|
+
dimension: int,
|
|
742
|
+
use_irpbs: bool,
|
|
743
|
+
num_layers: int = 3,
|
|
744
|
+
max_distance: int = 64,
|
|
745
|
+
num_heads: int = 8,
|
|
746
|
+
num_buckets: int = 32,
|
|
747
|
+
ffn_activation: ... = tf.nn.gelu,
|
|
748
|
+
dropout_rate: float = 0.1,
|
|
749
|
+
name: str | None = None,
|
|
750
|
+
) -> sl.SequenceLayer:
|
|
751
|
+
"""Builds a hybrid text encoder, with or without relative position biases."""
|
|
752
|
+
assert dimension % num_heads == 0
|
|
753
|
+
units_per_head = dimension // num_heads
|
|
754
|
+
|
|
755
|
+
if use_irpbs:
|
|
756
|
+
position_embeddings_config = InterpolatedRelativePositionBiasesConfig(
|
|
757
|
+
num_buckets=num_buckets,
|
|
758
|
+
max_distance=max_distance,
|
|
759
|
+
max_distance_penalty=1.0,
|
|
760
|
+
init_scheme='truncated_normal_stddev',
|
|
761
|
+
init_scheme_value=1.0,
|
|
762
|
+
)
|
|
763
|
+
else:
|
|
764
|
+
position_embeddings_config = T5RelativePositionEmbeddingConfig(
|
|
765
|
+
num_buckets=num_buckets,
|
|
766
|
+
max_distance=max_distance,
|
|
767
|
+
)
|
|
768
|
+
|
|
769
|
+
with tf.name_scope(name or 't5_encoder'):
|
|
770
|
+
return sl.Serial([
|
|
771
|
+
ConvStage(
|
|
772
|
+
num_blocks=3,
|
|
773
|
+
num_filters=int(dimension / 2),
|
|
774
|
+
strides=1,
|
|
775
|
+
output_dim=int(dimension / 2),
|
|
776
|
+
),
|
|
777
|
+
ConvStage(
|
|
778
|
+
num_blocks=3,
|
|
779
|
+
num_filters=dimension,
|
|
780
|
+
strides=2,
|
|
781
|
+
output_dim=dimension,
|
|
782
|
+
),
|
|
783
|
+
sl.Serial([
|
|
784
|
+
TransformerEncoderBlock(
|
|
785
|
+
dimension=dimension,
|
|
786
|
+
num_heads=num_heads,
|
|
787
|
+
units_per_head=units_per_head,
|
|
788
|
+
position_embeddings_config=position_embeddings_config,
|
|
789
|
+
ffn_activation=ffn_activation,
|
|
790
|
+
dropout_rate=dropout_rate,
|
|
791
|
+
)
|
|
792
|
+
for _ in range(num_layers)
|
|
793
|
+
]),
|
|
794
|
+
sl.RMSNormalization(epsilon=1e-6),
|
|
795
|
+
sl.Dropout(dropout_rate),
|
|
796
|
+
])
|
|
797
|
+
|
|
798
|
+
|
|
799
|
+
# ------------------------------------------------------------------------------
|
|
800
|
+
# VAT decoder helper classes.
|
|
801
|
+
# ------------------------------------------------------------------------------
|
|
802
|
+
@dataclasses.dataclass
|
|
803
|
+
class AlignmentLayerConfig:
|
|
804
|
+
"""Configuration for AlignmentLayer."""
|
|
805
|
+
|
|
806
|
+
# Number of RNN units for the alignment LSTM sublayer.
|
|
807
|
+
alignment_rnn_units: int
|
|
808
|
+
# Number of heads used in location-based cross-attention.
|
|
809
|
+
num_heads: int = 4
|
|
810
|
+
# Number of units per head used in location-based cross-attention.
|
|
811
|
+
units_per_head: int = 32
|
|
812
|
+
# Initial delta for the alignment position.
|
|
813
|
+
initial_delta: float = 0.25
|
|
814
|
+
# Configuration for the cross-attention bias.
|
|
815
|
+
cross_attention_bias: InterpolatedRelativePositionBiasesConfig = (
|
|
816
|
+
dataclasses.field(
|
|
817
|
+
default_factory=lambda: InterpolatedRelativePositionBiasesConfig(
|
|
818
|
+
num_buckets=32,
|
|
819
|
+
max_distance=64,
|
|
820
|
+
max_distance_penalty=1.0,
|
|
821
|
+
init_scheme='gaussian_window_stddev',
|
|
822
|
+
init_scheme_value=15.0,
|
|
823
|
+
)
|
|
824
|
+
)
|
|
825
|
+
)
|
|
826
|
+
|
|
827
|
+
|
|
828
|
+
class AlignmentLayer(sl.Emitting, PreprocessConstants):
|
|
829
|
+
"""AlignmentLayer.
|
|
830
|
+
|
|
831
|
+
Emits a differentiable monotonic alignment position. This can be used to
|
|
832
|
+
provide the "query" position in a cross-attention mechanism that uses relative
|
|
833
|
+
position biases.
|
|
834
|
+
|
|
835
|
+
The order of operations is as follows:
|
|
836
|
+
1. The alignment position is initialized to zero.
|
|
837
|
+
2. For the current time step:
|
|
838
|
+
a. A multi-head context vector is computed for the current alignment
|
|
839
|
+
position using a purely location-relative mechanism (using no query-key
|
|
840
|
+
comparisons) based on T5 relative position biases.
|
|
841
|
+
b. The input to this layer and the context vector are concatenated and fed
|
|
842
|
+
into an RNN.
|
|
843
|
+
c. To produce the updated alignment position:
|
|
844
|
+
- The output of the MLP is converted to a positive scalar using a
|
|
845
|
+
softplus layer.
|
|
846
|
+
- The positive float is added to the current alignment position to produce
|
|
847
|
+
the updated alignment position.
|
|
848
|
+
3. Repeat #2 for all time steps in the input sequence.
|
|
849
|
+
4. RNN outputs are returned as layer outputs and the alignment position
|
|
850
|
+
Sequence is returned as layer emits.
|
|
851
|
+
"""
|
|
852
|
+
|
|
853
|
+
def __init__(
|
|
854
|
+
self,
|
|
855
|
+
source_name: str,
|
|
856
|
+
config: AlignmentLayerConfig,
|
|
857
|
+
dropout_rate: float,
|
|
858
|
+
name: str | None = None,
|
|
859
|
+
):
|
|
860
|
+
|
|
861
|
+
super().__init__(name=name)
|
|
862
|
+
self.config = config
|
|
863
|
+
self.source_name = source_name
|
|
864
|
+
self.num_heads = config.num_heads
|
|
865
|
+
self.units_per_head = config.units_per_head
|
|
866
|
+
|
|
867
|
+
# This is set by preprocess_constants().
|
|
868
|
+
self._source_head_values = None
|
|
869
|
+
|
|
870
|
+
def _inverse_softplus(x: tf.Tensor) -> tf.Tensor: # pylint: disable=invalid-name
|
|
871
|
+
return np.log(np.exp(x) - 1.0)
|
|
872
|
+
|
|
873
|
+
with self.name_scope:
|
|
874
|
+
# Source value-projection for cross-attention.
|
|
875
|
+
self.source_value_projection = tf.keras.layers.Dense(
|
|
876
|
+
units=config.num_heads * config.units_per_head,
|
|
877
|
+
use_bias=False,
|
|
878
|
+
name='source_value_projection',
|
|
879
|
+
)
|
|
880
|
+
# Position biases for cross-attention.
|
|
881
|
+
self.position_embeddings = InterpolatedRelativePositionBiases.from_config(
|
|
882
|
+
num_heads=config.num_heads,
|
|
883
|
+
bidirectional=True,
|
|
884
|
+
config=config.cross_attention_bias,
|
|
885
|
+
)
|
|
886
|
+
self.sublayer = sl.RNN(
|
|
887
|
+
tf.keras.layers.LSTMCell(config.alignment_rnn_units)
|
|
888
|
+
)
|
|
889
|
+
# Compute initial bias from initial_delta using inverse softplus.
|
|
890
|
+
if config.initial_delta <= 0.0:
|
|
891
|
+
raise ValueError('initial_delta must be positive')
|
|
892
|
+
initial_output_bias = _inverse_softplus(config.initial_delta)
|
|
893
|
+
self.delta_output_layer = tf.keras.layers.Dense(
|
|
894
|
+
units=1,
|
|
895
|
+
activation='softplus', # Keeps the output positive.
|
|
896
|
+
kernel_initializer='zeros',
|
|
897
|
+
bias_initializer=tf.constant_initializer(initial_output_bias),
|
|
898
|
+
name='delta_output_layer',
|
|
899
|
+
)
|
|
900
|
+
self.dropout = tf.keras.layers.Dropout(
|
|
901
|
+
rate=dropout_rate, name='attention_dropout'
|
|
902
|
+
)
|
|
903
|
+
|
|
904
|
+
@tf.Module.with_name_scope
|
|
905
|
+
def preprocess_constants(self, constants: sl.Constants) -> None:
|
|
906
|
+
source = self._get_source(constants)
|
|
907
|
+
batch_size, source_len, _ = sl.utils.smart_dimension_size(source.values)
|
|
908
|
+
# Precompute self._source_head_values.
|
|
909
|
+
source_head_values = tf.reshape(
|
|
910
|
+
self.source_value_projection(source.values),
|
|
911
|
+
[batch_size, source_len, self.num_heads, self.units_per_head],
|
|
912
|
+
)
|
|
913
|
+
self._source_head_values = sl.Sequence(
|
|
914
|
+
source_head_values, source.mask
|
|
915
|
+
).mask_invalid()
|
|
916
|
+
|
|
917
|
+
@tf.Module.with_name_scope
|
|
918
|
+
def clear_preprocessed_constants(self) -> None:
|
|
919
|
+
self._source_head_values = None
|
|
920
|
+
|
|
921
|
+
def _get_source_head_values(self) -> sl.Sequence:
|
|
922
|
+
"""Get [bs, source_len, num_heads, units_per_head] Sequence."""
|
|
923
|
+
if self._source_head_values is None:
|
|
924
|
+
raise ValueError(
|
|
925
|
+
'source_head_values must be precomputed using preprocess_constants().'
|
|
926
|
+
)
|
|
927
|
+
return self._source_head_values
|
|
928
|
+
|
|
929
|
+
def _get_source(self, constants: sl.Constants) -> sl.Sequence:
|
|
930
|
+
if constants is None:
|
|
931
|
+
constants = {}
|
|
932
|
+
source = constants.get(self.source_name)
|
|
933
|
+
if not isinstance(source, sl.Sequence):
|
|
934
|
+
raise ValueError('constants[source_name] must contain an sl.Sequence')
|
|
935
|
+
return source
|
|
936
|
+
|
|
937
|
+
def _compute_context(
|
|
938
|
+
self, x: sl.Sequence, alignment_position: tf.Tensor, training: bool
|
|
939
|
+
) -> sl.Sequence:
|
|
940
|
+
"""Compute bias-only attention context (no query-key comparisons)."""
|
|
941
|
+
source_head_values = self._get_source_head_values()
|
|
942
|
+
|
|
943
|
+
# Compute position biases.
|
|
944
|
+
batch_size, source_len, _, _ = sl.utils.smart_dimension_size(
|
|
945
|
+
source_head_values.values
|
|
946
|
+
)
|
|
947
|
+
source_position = tf.tile(
|
|
948
|
+
tf.range(source_len)[tf.newaxis, :], [batch_size, 1]
|
|
949
|
+
)
|
|
950
|
+
# [bs, num_heads, query_len=1, source_len]
|
|
951
|
+
position_biases = self.position_embeddings(
|
|
952
|
+
alignment_position, source_position
|
|
953
|
+
)
|
|
954
|
+
# [bs, num_heads, source_len]
|
|
955
|
+
position_biases = tf.squeeze(position_biases, axis=2)
|
|
956
|
+
|
|
957
|
+
# Compute attention bias mask.
|
|
958
|
+
# [bs, num_heads=1, source_len] (broadcast across heads).
|
|
959
|
+
attention_mask = source_head_values.mask[:, tf.newaxis, :]
|
|
960
|
+
attention_bias_mask = (1.0 - attention_mask) * ATTENTION_MASK_BIAS
|
|
961
|
+
assert attention_bias_mask.dtype == tf.float32
|
|
962
|
+
|
|
963
|
+
compute_dtype = utils.compute_dtype()
|
|
964
|
+
|
|
965
|
+
# Compute attention weights in float32, then downcast to compute_dtype.
|
|
966
|
+
# [bs, num_heads, source_len]
|
|
967
|
+
scores = tf.cast(position_biases, tf.float32) + attention_bias_mask
|
|
968
|
+
weights = tf.nn.softmax(scores, axis=-1)
|
|
969
|
+
weights = tf.cast(weights, compute_dtype)
|
|
970
|
+
weights = self.dropout(weights, training=training)
|
|
971
|
+
|
|
972
|
+
# Compute context vectors.
|
|
973
|
+
# b=batch_size, s=source_len, n=num_heads, d=units_per_head.
|
|
974
|
+
context = tf.einsum('bns,bsnd->bnd', weights, source_head_values.values)
|
|
975
|
+
# Add time dim, flatten heads.
|
|
976
|
+
context = tf.reshape(
|
|
977
|
+
context, [batch_size, 1, self.num_heads * self.units_per_head]
|
|
978
|
+
)
|
|
979
|
+
context = sl.Sequence(context, x.mask).mask_invalid()
|
|
980
|
+
|
|
981
|
+
return context
|
|
982
|
+
|
|
983
|
+
def _compute_alignment_deltas(
|
|
984
|
+
self, sublayer_output: sl.Sequence, training: bool
|
|
985
|
+
) -> tf.Tensor:
|
|
986
|
+
# Here, T = 1, because we only compute deltas for single steps.
|
|
987
|
+
net = tf.ensure_shape(sublayer_output.values, [None, 1, None])
|
|
988
|
+
# [B, T=1, D]
|
|
989
|
+
net = self.delta_net(net, training=training)
|
|
990
|
+
# [B, T=1, 1]
|
|
991
|
+
net = self.delta_output_layer(net, training=training)
|
|
992
|
+
# [B, T=1]
|
|
993
|
+
net = tf.squeeze(net, axis=2)
|
|
994
|
+
# Set invalid deltas to zero.
|
|
995
|
+
deltas = sl.Sequence(net, sublayer_output.mask).mask_invalid()
|
|
996
|
+
# [B, T=1]
|
|
997
|
+
return deltas.values
|
|
998
|
+
|
|
999
|
+
def _single_step_with_emits(
|
|
1000
|
+
self,
|
|
1001
|
+
x: sl.Sequence,
|
|
1002
|
+
state: sl.State,
|
|
1003
|
+
training: bool,
|
|
1004
|
+
constants: sl.Constants = None,
|
|
1005
|
+
) -> tuple[sl.Sequence, sl.State, sl.Emits]:
|
|
1006
|
+
|
|
1007
|
+
alignment_position, sublayer_state = state
|
|
1008
|
+
|
|
1009
|
+
context = self._compute_context(x, alignment_position, training)
|
|
1010
|
+
sublayer_input = sl.Sequence(
|
|
1011
|
+
tf.concat([x.values, context.values], axis=-1), x.mask
|
|
1012
|
+
)
|
|
1013
|
+
|
|
1014
|
+
outputs, sublayer_state = self.sublayer.step(
|
|
1015
|
+
sublayer_input, sublayer_state, training, constants
|
|
1016
|
+
)
|
|
1017
|
+
alignment_position += self._compute_alignment_deltas(outputs, training)
|
|
1018
|
+
|
|
1019
|
+
state = (alignment_position, sublayer_state)
|
|
1020
|
+
emits = sl.Sequence(alignment_position, x.mask).mask_invalid()
|
|
1021
|
+
|
|
1022
|
+
return outputs, state, emits
|
|
1023
|
+
|
|
1024
|
+
@tf.Module.with_name_scope
|
|
1025
|
+
def layer_with_emits(
|
|
1026
|
+
self,
|
|
1027
|
+
x: sl.Sequence,
|
|
1028
|
+
training: bool,
|
|
1029
|
+
initial_state: sl.State = None,
|
|
1030
|
+
constants: sl.Constants = None,
|
|
1031
|
+
) -> tuple[sl.Sequence, sl.Emits]:
|
|
1032
|
+
if initial_state is None:
|
|
1033
|
+
initial_state = self.get_initial_state(x, constants)
|
|
1034
|
+
output, _, alignment_position = self.step_with_emits(
|
|
1035
|
+
x, initial_state, training, constants, unroll=False
|
|
1036
|
+
)
|
|
1037
|
+
return output, alignment_position
|
|
1038
|
+
|
|
1039
|
+
@tf.Module.with_name_scope
|
|
1040
|
+
def step_with_emits(
|
|
1041
|
+
self,
|
|
1042
|
+
x: sl.Sequence,
|
|
1043
|
+
state: sl.State,
|
|
1044
|
+
training: bool,
|
|
1045
|
+
constants: sl.Constants = None,
|
|
1046
|
+
unroll: bool = True,
|
|
1047
|
+
) -> tuple[sl.Sequence, sl.State, sl.Emits]:
|
|
1048
|
+
|
|
1049
|
+
# block_size = 1
|
|
1050
|
+
num_blocks = sl.utils.smart_dimension_size(x.values, 1)
|
|
1051
|
+
|
|
1052
|
+
step_fn = functools.partial(
|
|
1053
|
+
self._single_step_with_emits, training=training, constants=constants
|
|
1054
|
+
)
|
|
1055
|
+
|
|
1056
|
+
if unroll:
|
|
1057
|
+
return sl.utils.step_by_step_fn_static(step_fn, num_blocks, 1, x, state)
|
|
1058
|
+
else:
|
|
1059
|
+
output_spec = self.sublayer.get_output_spec_for_sequence(x, constants)
|
|
1060
|
+
emit_specs = self.get_emit_specs_for_sequence(x, constants)
|
|
1061
|
+
return sl.utils.step_by_step_fn_dynamic(
|
|
1062
|
+
step_fn,
|
|
1063
|
+
num_blocks,
|
|
1064
|
+
x.channel_shape,
|
|
1065
|
+
output_spec,
|
|
1066
|
+
emit_specs,
|
|
1067
|
+
num_blocks,
|
|
1068
|
+
1,
|
|
1069
|
+
1,
|
|
1070
|
+
x,
|
|
1071
|
+
state,
|
|
1072
|
+
)
|
|
1073
|
+
|
|
1074
|
+
@tf.Module.with_name_scope
|
|
1075
|
+
def get_emit_specs(
|
|
1076
|
+
self, input_spec: tf.TensorSpec, constants: sl.Constants = None
|
|
1077
|
+
) -> sl.Sequence:
|
|
1078
|
+
del constants
|
|
1079
|
+
# Scalar alignment position Sequence is emitted.
|
|
1080
|
+
return sl.Sequence(
|
|
1081
|
+
tf.TensorSpec(tf.TensorShape([]), input_spec.dtype),
|
|
1082
|
+
tf.TensorSpec(tf.TensorShape([]), sl.MASK_DTYPE),
|
|
1083
|
+
)
|
|
1084
|
+
|
|
1085
|
+
@tf.Module.with_name_scope
|
|
1086
|
+
def get_initial_state(
|
|
1087
|
+
self, x: sl.Sequence, constants: sl.Constants = None
|
|
1088
|
+
) -> sl.State:
|
|
1089
|
+
batch_size = sl.utils.smart_dimension_size(x.values, 0)
|
|
1090
|
+
compute_dtype = utils.compute_dtype()
|
|
1091
|
+
|
|
1092
|
+
# Initial alignment position is zero.
|
|
1093
|
+
alignment_position = tf.zeros([batch_size, 1], compute_dtype)
|
|
1094
|
+
|
|
1095
|
+
# Note: technically the shape is wrong for passing this on to sublayer
|
|
1096
|
+
# since we concat with context. In practice, the layer is an RNN
|
|
1097
|
+
# which does not care about input size for computing state size.
|
|
1098
|
+
x = x.apply_values(tf.cast, compute_dtype)
|
|
1099
|
+
|
|
1100
|
+
sublayer_state = self.sublayer.get_initial_state(x, constants)
|
|
1101
|
+
return (alignment_position, sublayer_state)
|
|
1102
|
+
|
|
1103
|
+
@tf.Module.with_name_scope
|
|
1104
|
+
def get_output_shape(
|
|
1105
|
+
self, input_shape: tf.TensorShape, constants: sl.Constants = None
|
|
1106
|
+
) -> tf.TensorShape:
|
|
1107
|
+
return self.sublayer.get_output_shape(input_shape, constants)
|
|
1108
|
+
|
|
1109
|
+
|
|
1110
|
+
class RelativeCrossAttention(sl.DotProductAttention):
|
|
1111
|
+
"""RelativeCrossAttention.
|
|
1112
|
+
|
|
1113
|
+
This computes: y = cross_attention(x, source, alignment_position).
|
|
1114
|
+
Here, cross_attention computes multi-head attention between a query sequence
|
|
1115
|
+
and a source sequence. It uses interpolated relative position biases that are
|
|
1116
|
+
computed from externally provided alignment positions for the query positions
|
|
1117
|
+
and basic time indices for the source positions.
|
|
1118
|
+
|
|
1119
|
+
The constants dict must contain the following:
|
|
1120
|
+
constants[source_name] - A [batch, source_len, source_dim] source Sequence
|
|
1121
|
+
to attend to.
|
|
1122
|
+
constants[ALIGNMENT_POSITION] - A [batch, input_len] query alignment
|
|
1123
|
+
position Tensor.
|
|
1124
|
+
|
|
1125
|
+
Note that because constants[ALIGNMENT_POSITION] contains a Tensor that is to
|
|
1126
|
+
be used synchronously with the input Sequence, this layer doesn't fully obey
|
|
1127
|
+
the SequenceLayer contract and shouldn't be used as a general-purpose
|
|
1128
|
+
SequenceLayer.
|
|
1129
|
+
"""
|
|
1130
|
+
|
|
1131
|
+
def __init__(
|
|
1132
|
+
self,
|
|
1133
|
+
source_name: str,
|
|
1134
|
+
num_heads: int,
|
|
1135
|
+
units_per_head: int,
|
|
1136
|
+
relative_position_biases: InterpolatedRelativePositionBiases,
|
|
1137
|
+
attention_probabilities_dropout_rate: float,
|
|
1138
|
+
broadcast_dropout_across_queries: bool = False,
|
|
1139
|
+
use_bias: bool = False,
|
|
1140
|
+
kernel_initializer='glorot_uniform',
|
|
1141
|
+
bias_initializer='zeros',
|
|
1142
|
+
name: str | None = None,
|
|
1143
|
+
):
|
|
1144
|
+
"""Construct RelativeCrossAttention."""
|
|
1145
|
+
super().__init__(
|
|
1146
|
+
source_name=source_name,
|
|
1147
|
+
num_heads=num_heads,
|
|
1148
|
+
units_per_head=units_per_head,
|
|
1149
|
+
attention_probabilities_dropout_rate=attention_probabilities_dropout_rate,
|
|
1150
|
+
broadcast_dropout_across_queries=broadcast_dropout_across_queries,
|
|
1151
|
+
use_bias=use_bias,
|
|
1152
|
+
kernel_initializer=kernel_initializer,
|
|
1153
|
+
bias_initializer=bias_initializer,
|
|
1154
|
+
name=name,
|
|
1155
|
+
)
|
|
1156
|
+
self._relative_position_biases = relative_position_biases
|
|
1157
|
+
|
|
1158
|
+
def _get_constants(
|
|
1159
|
+
self, constants: sl.Constants
|
|
1160
|
+
) -> tuple[sl.Sequence, tf.Tensor]:
|
|
1161
|
+
if constants is None:
|
|
1162
|
+
constants = {}
|
|
1163
|
+
source = constants.get(self._source_name)
|
|
1164
|
+
if not isinstance(source, sl.Sequence):
|
|
1165
|
+
raise ValueError('constants[source_name] must contain an sl.Sequence')
|
|
1166
|
+
alignment_position = constants.get(ALIGNMENT_POSITION)
|
|
1167
|
+
if not isinstance(alignment_position, tf.Tensor):
|
|
1168
|
+
raise ValueError('constants[ALIGNMENT_POSITION] must contain a tf.Tensor')
|
|
1169
|
+
return source, alignment_position
|
|
1170
|
+
|
|
1171
|
+
@tf.Module.with_name_scope
|
|
1172
|
+
def step_with_emits(
|
|
1173
|
+
self,
|
|
1174
|
+
x: sl.Sequence,
|
|
1175
|
+
state: sl.State,
|
|
1176
|
+
training: bool,
|
|
1177
|
+
constants: sl.Constants | None = None,
|
|
1178
|
+
) -> tuple[sl.Sequence, sl.State, sl.Emits]:
|
|
1179
|
+
source, alignment_position = self._get_constants(constants)
|
|
1180
|
+
|
|
1181
|
+
# alignment_position is used synchronously with the input.
|
|
1182
|
+
alignment_position.shape.assert_is_compatible_with(x.values.shape[:2])
|
|
1183
|
+
|
|
1184
|
+
queries = self._get_queries(x)
|
|
1185
|
+
keys, values = self._get_key_values(source)
|
|
1186
|
+
|
|
1187
|
+
if self._query_network:
|
|
1188
|
+
queries, state = self._query_network.step(
|
|
1189
|
+
queries.mask_invalid(),
|
|
1190
|
+
state,
|
|
1191
|
+
training=training,
|
|
1192
|
+
constants=constants,
|
|
1193
|
+
)
|
|
1194
|
+
|
|
1195
|
+
if self._key_network:
|
|
1196
|
+
keys = self._key_network.layer(
|
|
1197
|
+
keys.mask_invalid(),
|
|
1198
|
+
training=training,
|
|
1199
|
+
constants=constants,
|
|
1200
|
+
)
|
|
1201
|
+
|
|
1202
|
+
if self._value_network:
|
|
1203
|
+
values = self._value_network.layer(
|
|
1204
|
+
values.mask_invalid(),
|
|
1205
|
+
training=training,
|
|
1206
|
+
constants=constants,
|
|
1207
|
+
)
|
|
1208
|
+
|
|
1209
|
+
y, emits = self._attention(
|
|
1210
|
+
queries,
|
|
1211
|
+
keys,
|
|
1212
|
+
values,
|
|
1213
|
+
logit_bias_fn=functools.partial(
|
|
1214
|
+
self._logit_bias_fn, alignment_position=alignment_position
|
|
1215
|
+
),
|
|
1216
|
+
is_step=True,
|
|
1217
|
+
training=training,
|
|
1218
|
+
)
|
|
1219
|
+
|
|
1220
|
+
return y, state, emits
|
|
1221
|
+
|
|
1222
|
+
@tf.Module.with_name_scope
|
|
1223
|
+
def layer_with_emits(
|
|
1224
|
+
self,
|
|
1225
|
+
x: sl.Sequence,
|
|
1226
|
+
training: bool,
|
|
1227
|
+
initial_state: sl.State = None,
|
|
1228
|
+
constants: sl.Constants = None,
|
|
1229
|
+
is_step: bool = False,
|
|
1230
|
+
) -> tuple[sl.Sequence, sl.Emits]:
|
|
1231
|
+
del initial_state # Stateless.
|
|
1232
|
+
source, alignment_position = self._get_constants(constants)
|
|
1233
|
+
|
|
1234
|
+
# alignment_position is used synchronously with the input.
|
|
1235
|
+
alignment_position.shape.assert_is_compatible_with(x.values.shape[:2])
|
|
1236
|
+
|
|
1237
|
+
queries = self._get_queries(x)
|
|
1238
|
+
keys, values = self._get_key_values(source)
|
|
1239
|
+
|
|
1240
|
+
if self._query_network:
|
|
1241
|
+
queries = self._query_network.layer(
|
|
1242
|
+
queries.mask_invalid(),
|
|
1243
|
+
training=training,
|
|
1244
|
+
constants=constants,
|
|
1245
|
+
)
|
|
1246
|
+
|
|
1247
|
+
if self._key_network:
|
|
1248
|
+
keys = self._key_network.layer(
|
|
1249
|
+
keys.mask_invalid(),
|
|
1250
|
+
training=training,
|
|
1251
|
+
constants=constants,
|
|
1252
|
+
)
|
|
1253
|
+
|
|
1254
|
+
if self._value_network:
|
|
1255
|
+
values = self._value_network.layer(
|
|
1256
|
+
values.mask_invalid(),
|
|
1257
|
+
training=training,
|
|
1258
|
+
constants=constants,
|
|
1259
|
+
)
|
|
1260
|
+
|
|
1261
|
+
return self._attention(
|
|
1262
|
+
queries,
|
|
1263
|
+
keys,
|
|
1264
|
+
values,
|
|
1265
|
+
logit_bias_fn=functools.partial(
|
|
1266
|
+
self._logit_bias_fn, alignment_position=alignment_position
|
|
1267
|
+
),
|
|
1268
|
+
is_step=False,
|
|
1269
|
+
training=training,
|
|
1270
|
+
)
|
|
1271
|
+
|
|
1272
|
+
def _logit_bias_fn(
|
|
1273
|
+
self,
|
|
1274
|
+
query_time: tf.Tensor,
|
|
1275
|
+
query_length: tf.Tensor | int,
|
|
1276
|
+
key_time: tf.Tensor,
|
|
1277
|
+
key_length: tf.Tensor | int,
|
|
1278
|
+
alignment_position: tf.Tensor,
|
|
1279
|
+
) -> tf.Tensor:
|
|
1280
|
+
"""Returns logit biases [b, q, h, k] for the provided positions."""
|
|
1281
|
+
batch_size = sl.utils.smart_dimension_size(alignment_position, 0)
|
|
1282
|
+
query_position = tf.slice(
|
|
1283
|
+
alignment_position, [0, query_time], [-1, query_length]
|
|
1284
|
+
)
|
|
1285
|
+
|
|
1286
|
+
source_position = key_time + tf.range(key_length)[tf.newaxis, :]
|
|
1287
|
+
source_position = tf.tile(source_position, [batch_size, 1])
|
|
1288
|
+
|
|
1289
|
+
position_biases = self._relative_position_biases(
|
|
1290
|
+
query_position, source_position
|
|
1291
|
+
)
|
|
1292
|
+
position_biases = tf.transpose(position_biases, [0, 2, 1, 3])
|
|
1293
|
+
return position_biases
|
|
1294
|
+
|
|
1295
|
+
|
|
1296
|
+
class AlignmentBlock(sl.Residual, PreprocessConstants):
|
|
1297
|
+
"""AlignmentBlock that wraps AlignmentLayer with a residual connection."""
|
|
1298
|
+
|
|
1299
|
+
def __init__(
|
|
1300
|
+
self,
|
|
1301
|
+
source_name: str,
|
|
1302
|
+
config: AlignmentLayerConfig,
|
|
1303
|
+
output_dim: int,
|
|
1304
|
+
dropout_rate: float,
|
|
1305
|
+
name: str | None = None,
|
|
1306
|
+
):
|
|
1307
|
+
self.alignment_layer = AlignmentLayer(
|
|
1308
|
+
source_name, config, dropout_rate, name='alignment_layer'
|
|
1309
|
+
)
|
|
1310
|
+
super().__init__(
|
|
1311
|
+
[
|
|
1312
|
+
sl.RMSNormalization(epsilon=1e-6, name='rms_normalization'),
|
|
1313
|
+
self.alignment_layer,
|
|
1314
|
+
sl.Dense(units=output_dim, use_bias=False, name='dense'),
|
|
1315
|
+
sl.Dropout(rate=dropout_rate, noise_shape=[None, 1, None]),
|
|
1316
|
+
],
|
|
1317
|
+
name='residual',
|
|
1318
|
+
)
|
|
1319
|
+
|
|
1320
|
+
def get_alignment_position(self, emits: sl.Emits) -> sl.Sequence:
|
|
1321
|
+
return emits['residual']['serial']['alignment_layer']
|
|
1322
|
+
|
|
1323
|
+
@tf.Module.with_name_scope
|
|
1324
|
+
def preprocess_constants(self, constants: sl.Constants) -> None:
|
|
1325
|
+
self.alignment_layer.preprocess_constants(constants)
|
|
1326
|
+
|
|
1327
|
+
@tf.Module.with_name_scope
|
|
1328
|
+
def clear_preprocessed_constants(self) -> None:
|
|
1329
|
+
self.alignment_layer.clear_preprocessed_constants()
|
|
1330
|
+
|
|
1331
|
+
|
|
1332
|
+
def RelativeCrossAttentionBlock(
|
|
1333
|
+
source_name: str,
|
|
1334
|
+
output_dim: int,
|
|
1335
|
+
num_heads: int,
|
|
1336
|
+
units_per_head: int,
|
|
1337
|
+
position_bias_config: InterpolatedRelativePositionBiasesConfig,
|
|
1338
|
+
dropout_rate: float,
|
|
1339
|
+
) -> sl.SequenceLayer:
|
|
1340
|
+
"""See RelativeCrossAttention for required constants."""
|
|
1341
|
+
|
|
1342
|
+
relative_position_embedding = InterpolatedRelativePositionBiases.from_config(
|
|
1343
|
+
num_heads=num_heads,
|
|
1344
|
+
bidirectional=True, # Non-causal cross-attention.
|
|
1345
|
+
config=position_bias_config,
|
|
1346
|
+
)
|
|
1347
|
+
|
|
1348
|
+
return sl.Residual([
|
|
1349
|
+
sl.RMSNormalization(epsilon=1e-6, name='rms_normalization'),
|
|
1350
|
+
RelativeCrossAttention(
|
|
1351
|
+
source_name=source_name,
|
|
1352
|
+
num_heads=num_heads,
|
|
1353
|
+
units_per_head=units_per_head,
|
|
1354
|
+
relative_position_biases=relative_position_embedding,
|
|
1355
|
+
attention_probabilities_dropout_rate=dropout_rate,
|
|
1356
|
+
broadcast_dropout_across_queries=True,
|
|
1357
|
+
use_bias=False,
|
|
1358
|
+
name='relative_cross_attention',
|
|
1359
|
+
),
|
|
1360
|
+
sl.Flatten(),
|
|
1361
|
+
sl.Dense(units=output_dim, use_bias=False, name='dense'),
|
|
1362
|
+
sl.Dropout(rate=dropout_rate, noise_shape=[None, 1, None]),
|
|
1363
|
+
])
|
|
1364
|
+
|
|
1365
|
+
|
|
1366
|
+
@dataclasses.dataclass
|
|
1367
|
+
class DecoderBlockConfig:
|
|
1368
|
+
"""Configuration for DecoderBlock."""
|
|
1369
|
+
|
|
1370
|
+
alignment_rnn_units: int
|
|
1371
|
+
num_heads: int
|
|
1372
|
+
units_per_head: int
|
|
1373
|
+
hidden_dim: int
|
|
1374
|
+
feedforward_hidden_dim: int
|
|
1375
|
+
max_future_horizon: int = 0
|
|
1376
|
+
feedforward_activation: str = 'gelu'
|
|
1377
|
+
max_past_horizon: int = 128
|
|
1378
|
+
|
|
1379
|
+
self_attention_bias: InterpolatedRelativePositionBiasesConfig = (
|
|
1380
|
+
dataclasses.field(
|
|
1381
|
+
default_factory=lambda: InterpolatedRelativePositionBiasesConfig(
|
|
1382
|
+
num_buckets=32,
|
|
1383
|
+
max_distance=128,
|
|
1384
|
+
max_distance_penalty=1.0,
|
|
1385
|
+
init_scheme='truncated_normal_stddev',
|
|
1386
|
+
init_scheme_value=1.0,
|
|
1387
|
+
)
|
|
1388
|
+
)
|
|
1389
|
+
)
|
|
1390
|
+
|
|
1391
|
+
cross_attention_bias: InterpolatedRelativePositionBiasesConfig = (
|
|
1392
|
+
dataclasses.field(
|
|
1393
|
+
default_factory=lambda: InterpolatedRelativePositionBiasesConfig(
|
|
1394
|
+
num_buckets=32,
|
|
1395
|
+
max_distance=64,
|
|
1396
|
+
max_distance_penalty=1.0,
|
|
1397
|
+
init_scheme='gaussian_window_stddev',
|
|
1398
|
+
init_scheme_value=15.0,
|
|
1399
|
+
)
|
|
1400
|
+
)
|
|
1401
|
+
)
|
|
1402
|
+
|
|
1403
|
+
|
|
1404
|
+
def DecoderBlock(
|
|
1405
|
+
source_name: str,
|
|
1406
|
+
config: DecoderBlockConfig,
|
|
1407
|
+
dropout_rate: float,
|
|
1408
|
+
) -> sl.SequenceLayer:
|
|
1409
|
+
"""Self-attention, cross-attention, feed-forward block."""
|
|
1410
|
+
return sl.Serial([
|
|
1411
|
+
SelfAttentionBlock(
|
|
1412
|
+
output_dim=config.hidden_dim,
|
|
1413
|
+
num_heads=config.num_heads,
|
|
1414
|
+
units_per_head=config.units_per_head,
|
|
1415
|
+
max_horizon=config.max_past_horizon,
|
|
1416
|
+
max_future_horizon=0,
|
|
1417
|
+
relative_position_embedding=InterpolatedRelativePositionBiases.from_config(
|
|
1418
|
+
config=config.self_attention_bias,
|
|
1419
|
+
bidirectional=False, # Causal self-attention.
|
|
1420
|
+
num_heads=config.num_heads,
|
|
1421
|
+
),
|
|
1422
|
+
dropout_rate=dropout_rate,
|
|
1423
|
+
),
|
|
1424
|
+
RelativeCrossAttentionBlock(
|
|
1425
|
+
source_name=source_name,
|
|
1426
|
+
output_dim=config.hidden_dim,
|
|
1427
|
+
num_heads=config.num_heads,
|
|
1428
|
+
units_per_head=config.units_per_head,
|
|
1429
|
+
position_bias_config=config.cross_attention_bias,
|
|
1430
|
+
dropout_rate=dropout_rate,
|
|
1431
|
+
),
|
|
1432
|
+
FeedforwardBlock(
|
|
1433
|
+
output_dim=config.hidden_dim,
|
|
1434
|
+
hidden_dim=config.feedforward_hidden_dim,
|
|
1435
|
+
activation=config.feedforward_activation,
|
|
1436
|
+
dropout_rate=dropout_rate,
|
|
1437
|
+
),
|
|
1438
|
+
])
|
|
1439
|
+
|
|
1440
|
+
|
|
1441
|
+
def VATDecoderBlockStack(
|
|
1442
|
+
source_name: str,
|
|
1443
|
+
decoder_block_config: DecoderBlockConfig,
|
|
1444
|
+
num_decoder_blocks: int,
|
|
1445
|
+
dropout_rate: float,
|
|
1446
|
+
) -> sl.SequenceLayer:
|
|
1447
|
+
"""Stack of DecoderBlocks with RMSNorm and Dropout."""
|
|
1448
|
+
|
|
1449
|
+
return sl.Serial(
|
|
1450
|
+
[
|
|
1451
|
+
DecoderBlock(
|
|
1452
|
+
source_name,
|
|
1453
|
+
decoder_block_config,
|
|
1454
|
+
dropout_rate,
|
|
1455
|
+
)
|
|
1456
|
+
for _ in range(num_decoder_blocks)
|
|
1457
|
+
]
|
|
1458
|
+
+ [
|
|
1459
|
+
sl.RMSNormalization(epsilon=1e-6, name='rms_normalization'),
|
|
1460
|
+
sl.Dropout(rate=dropout_rate, noise_shape=[None, 1, None]),
|
|
1461
|
+
]
|
|
1462
|
+
)
|
|
1463
|
+
|
|
1464
|
+
|
|
1465
|
+
@dataclasses.dataclass
|
|
1466
|
+
class VATDecoderConfig:
|
|
1467
|
+
"""Configuration for VATDecoder."""
|
|
1468
|
+
|
|
1469
|
+
name: str | None
|
|
1470
|
+
# The name of the source sequence to use for cross-attention, e.g.
|
|
1471
|
+
# 'text_encoder_top'.
|
|
1472
|
+
source_name: str
|
|
1473
|
+
# Configuration for the alignment layer.
|
|
1474
|
+
alignment_layer: AlignmentLayerConfig
|
|
1475
|
+
# Configuration for the decoder block stack.
|
|
1476
|
+
decoder_block: DecoderBlockConfig
|
|
1477
|
+
# The number of VQ codebooks.
|
|
1478
|
+
num_codebooks: int
|
|
1479
|
+
# The per-codebook vocabulary size.
|
|
1480
|
+
codebook_size: int
|
|
1481
|
+
# Number of decoder blocks in the decoder block stack.
|
|
1482
|
+
num_decoder_blocks: int
|
|
1483
|
+
# Dropout rate for the decoder.
|
|
1484
|
+
dropout_rate: float
|
|
1485
|
+
|
|
1486
|
+
|
|
1487
|
+
# ------------------------------------------------------------------------------
|
|
1488
|
+
# VeryAttentiveTacotron decoder.
|
|
1489
|
+
# ------------------------------------------------------------------------------
|
|
1490
|
+
class VATDecoder(sl.Emitting, PreprocessConstants):
|
|
1491
|
+
"""VeryAttentiveTacotron decoder.
|
|
1492
|
+
|
|
1493
|
+
This SequenceLayer composes the following operations:
|
|
1494
|
+
* Optional SequenceLayer prenet.
|
|
1495
|
+
* AlignmentBlock (which contains an AlignmentLayer that runs step-wise during
|
|
1496
|
+
training).
|
|
1497
|
+
* VATDecoderBlockStack (consisting of N DecoderBlocks).
|
|
1498
|
+
"""
|
|
1499
|
+
|
|
1500
|
+
def __init__(self, config: VATDecoderConfig):
|
|
1501
|
+
"""Construct VATDecoder."""
|
|
1502
|
+
super().__init__(name=config.name or None)
|
|
1503
|
+
if not config.source_name:
|
|
1504
|
+
raise ValueError('source_name not defined.')
|
|
1505
|
+
self.config = config
|
|
1506
|
+
self._source_name = config.source_name
|
|
1507
|
+
|
|
1508
|
+
with self.name_scope:
|
|
1509
|
+
self._build(config)
|
|
1510
|
+
|
|
1511
|
+
def _build(self, config):
|
|
1512
|
+
with tf.name_scope('prenet'):
|
|
1513
|
+
# Embed each codebook with a unique embedding.
|
|
1514
|
+
self.prenet = sl.Serial([
|
|
1515
|
+
sl.OneHot(depth=config.codebook_size),
|
|
1516
|
+
sl.EinsumDense(
|
|
1517
|
+
equation='...GC,GCE->...GE',
|
|
1518
|
+
output_shape=[
|
|
1519
|
+
config.num_codebooks,
|
|
1520
|
+
int(config.decoder_block.hidden_dim / config.num_codebooks),
|
|
1521
|
+
],
|
|
1522
|
+
kernel_initializer=tf.keras.initializers.RandomUniform(),
|
|
1523
|
+
name='target_codebooks',
|
|
1524
|
+
),
|
|
1525
|
+
sl.Flatten(),
|
|
1526
|
+
sl.Conv1D(filters=config.decoder_block.hidden_dim, kernel_size=3),
|
|
1527
|
+
])
|
|
1528
|
+
self.alignment_block = AlignmentBlock(
|
|
1529
|
+
source_name=config.source_name,
|
|
1530
|
+
config=config.alignment_layer,
|
|
1531
|
+
output_dim=config.decoder_block.hidden_dim,
|
|
1532
|
+
dropout_rate=config.dropout_rate,
|
|
1533
|
+
name='alignment_block',
|
|
1534
|
+
)
|
|
1535
|
+
self.decoder_block_stack = VATDecoderBlockStack(
|
|
1536
|
+
source_name=config.source_name,
|
|
1537
|
+
decoder_block_config=config.decoder_block,
|
|
1538
|
+
num_decoder_blocks=config.num_decoder_blocks,
|
|
1539
|
+
dropout_rate=config.dropout_rate,
|
|
1540
|
+
)
|
|
1541
|
+
|
|
1542
|
+
# Wrap layers in an sl.Serial to use its initial state and output shape
|
|
1543
|
+
# helpers.
|
|
1544
|
+
self.serial_layer = sl.Serial([
|
|
1545
|
+
self.prenet,
|
|
1546
|
+
self.alignment_block,
|
|
1547
|
+
self.decoder_block_stack,
|
|
1548
|
+
])
|
|
1549
|
+
|
|
1550
|
+
@tf.Module.with_name_scope
|
|
1551
|
+
def preprocess_constants(self, constants: sl.Constants) -> None:
|
|
1552
|
+
self.alignment_block.preprocess_constants(constants)
|
|
1553
|
+
|
|
1554
|
+
@tf.Module.with_name_scope
|
|
1555
|
+
def clear_preprocessed_constants(self) -> None:
|
|
1556
|
+
self.alignment_block.clear_preprocessed_constants()
|
|
1557
|
+
|
|
1558
|
+
@tf.Module.with_name_scope
|
|
1559
|
+
def layer_with_emits(
|
|
1560
|
+
self,
|
|
1561
|
+
x: sl.Sequence,
|
|
1562
|
+
training: bool,
|
|
1563
|
+
initial_state: sl.State = None,
|
|
1564
|
+
constants: sl.Constants = None,
|
|
1565
|
+
) -> tuple[sl.Sequence, sl.Emits]:
|
|
1566
|
+
if initial_state is None:
|
|
1567
|
+
initial_state = self.get_initial_state(x, constants)
|
|
1568
|
+
|
|
1569
|
+
(
|
|
1570
|
+
prenet_state,
|
|
1571
|
+
alignment_block_state,
|
|
1572
|
+
decoder_block_stack_state,
|
|
1573
|
+
) = initial_state
|
|
1574
|
+
|
|
1575
|
+
x = self.prenet.layer(x, training, prenet_state, constants)
|
|
1576
|
+
x, emits = self.alignment_block.layer_with_emits(
|
|
1577
|
+
x, training, alignment_block_state, constants
|
|
1578
|
+
)
|
|
1579
|
+
alignment_position = self.alignment_block.get_alignment_position(emits)
|
|
1580
|
+
# Feed alignment_position to decoder_block_stack.
|
|
1581
|
+
post_alignment_constants = constants | {
|
|
1582
|
+
ALIGNMENT_POSITION: alignment_position.values
|
|
1583
|
+
}
|
|
1584
|
+
outputs = self.decoder_block_stack.layer(
|
|
1585
|
+
x, training, decoder_block_stack_state, post_alignment_constants
|
|
1586
|
+
)
|
|
1587
|
+
emits = self._compute_emits(alignment_position, constants)
|
|
1588
|
+
|
|
1589
|
+
return outputs, emits
|
|
1590
|
+
|
|
1591
|
+
@tf.Module.with_name_scope
|
|
1592
|
+
def step_with_emits(
|
|
1593
|
+
self,
|
|
1594
|
+
x: sl.Sequence,
|
|
1595
|
+
state: sl.State,
|
|
1596
|
+
training: bool,
|
|
1597
|
+
constants: sl.Constants = None,
|
|
1598
|
+
) -> tuple[sl.Sequence, sl.State, sl.Emits]:
|
|
1599
|
+
|
|
1600
|
+
(
|
|
1601
|
+
prenet_state,
|
|
1602
|
+
alignment_block_state,
|
|
1603
|
+
decoder_block_stack_state,
|
|
1604
|
+
) = state
|
|
1605
|
+
|
|
1606
|
+
x, prenet_state = self.prenet.step(x, prenet_state, training, constants)
|
|
1607
|
+
x, alignment_block_state, emits = self.alignment_block.step_with_emits(
|
|
1608
|
+
x, alignment_block_state, training, constants
|
|
1609
|
+
)
|
|
1610
|
+
alignment_position = self.alignment_block.get_alignment_position(emits)
|
|
1611
|
+
# Feed alignment_position to decoder_block_stack.
|
|
1612
|
+
post_alignment_constants = constants | {
|
|
1613
|
+
ALIGNMENT_POSITION: alignment_position.values
|
|
1614
|
+
}
|
|
1615
|
+
outputs, decoder_block_stack_state = self.decoder_block_stack.step(
|
|
1616
|
+
x, decoder_block_stack_state, training, post_alignment_constants
|
|
1617
|
+
)
|
|
1618
|
+
emits = self._compute_emits(alignment_position, constants)
|
|
1619
|
+
|
|
1620
|
+
state = (
|
|
1621
|
+
prenet_state,
|
|
1622
|
+
alignment_block_state,
|
|
1623
|
+
decoder_block_stack_state,
|
|
1624
|
+
)
|
|
1625
|
+
|
|
1626
|
+
return outputs, state, emits
|
|
1627
|
+
|
|
1628
|
+
def _compute_emits(
|
|
1629
|
+
self, alignment_position: sl.Sequence, constants
|
|
1630
|
+
) -> sl.Emits:
|
|
1631
|
+
"""Compute soft alignment probabilities from alignment positions."""
|
|
1632
|
+
source = constants[self.config.source_name]
|
|
1633
|
+
source_time = sl.utils.smart_dimension_size(source.values, 1)
|
|
1634
|
+
|
|
1635
|
+
# [batch, query_time]
|
|
1636
|
+
position_ind_low = tf.math.floor(alignment_position.values)
|
|
1637
|
+
position_ind_high = tf.math.ceil(alignment_position.values)
|
|
1638
|
+
high_weight = alignment_position.values - position_ind_low
|
|
1639
|
+
|
|
1640
|
+
# [batch, query_time, source_time]
|
|
1641
|
+
compute_dtype = utils.compute_dtype()
|
|
1642
|
+
position_low = tf.one_hot(
|
|
1643
|
+
tf.cast(position_ind_low, tf.int32), source_time, dtype=compute_dtype
|
|
1644
|
+
)
|
|
1645
|
+
position_high = tf.one_hot(
|
|
1646
|
+
tf.cast(position_ind_high, tf.int32), source_time, dtype=compute_dtype
|
|
1647
|
+
)
|
|
1648
|
+
high_weight = high_weight[:, :, tf.newaxis]
|
|
1649
|
+
attention_probabilities = (
|
|
1650
|
+
1.0 - high_weight
|
|
1651
|
+
) * position_low + high_weight * position_high
|
|
1652
|
+
|
|
1653
|
+
# [batch, query_time, num_heads=1, source_time]
|
|
1654
|
+
attention_probabilities = attention_probabilities[:, :, tf.newaxis, :]
|
|
1655
|
+
attention_probabilities = sl.Sequence(
|
|
1656
|
+
attention_probabilities, alignment_position.mask
|
|
1657
|
+
).mask_invalid()
|
|
1658
|
+
|
|
1659
|
+
return sl.AttentionEmits(attention_probabilities)
|
|
1660
|
+
|
|
1661
|
+
@tf.Module.with_name_scope
|
|
1662
|
+
def get_initial_state(
|
|
1663
|
+
self, x: sl.Sequence, constants: sl.Constants = None
|
|
1664
|
+
) -> sl.State:
|
|
1665
|
+
return tuple(self.serial_layer.get_initial_state(x, constants))
|
|
1666
|
+
|
|
1667
|
+
@tf.Module.with_name_scope
|
|
1668
|
+
def get_output_shape(
|
|
1669
|
+
self, input_shape: tf.TensorShape, constants: sl.Constants = None
|
|
1670
|
+
) -> tf.TensorShape:
|
|
1671
|
+
return self.serial_layer.get_output_shape(input_shape, constants)
|
|
1672
|
+
|
|
1673
|
+
@tf.Module.with_name_scope
|
|
1674
|
+
def get_emit_specs(
|
|
1675
|
+
self, input_spec: tf.TensorSpec, constants: sl.Constants = None
|
|
1676
|
+
) -> sl.EmitSpecs:
|
|
1677
|
+
# We emit AttentionEmits with soft alignment position.
|
|
1678
|
+
source = constants[self.config.source_name]
|
|
1679
|
+
prenet_output_spec = self.prenet.get_output_spec(input_spec, constants)
|
|
1680
|
+
return sl.AttentionEmits(
|
|
1681
|
+
sl.Sequence(
|
|
1682
|
+
tf.TensorSpec(
|
|
1683
|
+
tf.TensorShape([1, source.values.shape[1]]),
|
|
1684
|
+
prenet_output_spec.dtype,
|
|
1685
|
+
),
|
|
1686
|
+
tf.TensorSpec(tf.TensorShape([]), sl.MASK_DTYPE),
|
|
1687
|
+
)
|
|
1688
|
+
)
|
|
1689
|
+
|
|
1690
|
+
|
|
1691
|
+
# ------------------------------------------------------------------------------
|
|
1692
|
+
# T5 Baseline decoder.
|
|
1693
|
+
# ------------------------------------------------------------------------------
|
|
1694
|
+
|
|
1695
|
+
|
|
1696
|
+
@dataclasses.dataclass
|
|
1697
|
+
class T5BaselineDecoderConfig:
|
|
1698
|
+
"""Configuration for T5BaselineDecoder."""
|
|
1699
|
+
|
|
1700
|
+
name: str | None
|
|
1701
|
+
# The name of the source sequence to use for cross-attention, e.g.
|
|
1702
|
+
# 'text_encoder_top'.
|
|
1703
|
+
source_name: str
|
|
1704
|
+
# The number of VQ codebooks.
|
|
1705
|
+
num_codebooks: int
|
|
1706
|
+
# The per-codebook vocabulary size.
|
|
1707
|
+
codebook_size: int
|
|
1708
|
+
# Number of decoder blocks in the decoder block stack.
|
|
1709
|
+
num_decoder_blocks: int
|
|
1710
|
+
# Number of attention heads per self attention layer.
|
|
1711
|
+
num_heads: int
|
|
1712
|
+
# Number of units per attention head.
|
|
1713
|
+
units_per_head: int
|
|
1714
|
+
# The hidden dimension of the FFN layer.
|
|
1715
|
+
ffn_dimension: int
|
|
1716
|
+
# Maximum past horizon for self attention.
|
|
1717
|
+
max_past_horizon: int
|
|
1718
|
+
# Dropout rate for the decoder.
|
|
1719
|
+
dropout_rate: float
|
|
1720
|
+
|
|
1721
|
+
|
|
1722
|
+
class T5BaselineDecoder(sl.Serial):
|
|
1723
|
+
"""A T5-based TTS decoder."""
|
|
1724
|
+
|
|
1725
|
+
def __init__(self, config: T5BaselineDecoderConfig):
|
|
1726
|
+
"""Construct T5BaselineDecoder."""
|
|
1727
|
+
hidden_dim = config.units_per_head * config.num_heads
|
|
1728
|
+
|
|
1729
|
+
layers = [
|
|
1730
|
+
# Embed each codebook with a unique embedding.
|
|
1731
|
+
sl.Serial([
|
|
1732
|
+
sl.OneHot(depth=config.codebook_size),
|
|
1733
|
+
sl.EinsumDense(
|
|
1734
|
+
equation='...GC,GCE->...GE',
|
|
1735
|
+
output_shape=[
|
|
1736
|
+
config.num_codebooks,
|
|
1737
|
+
int(hidden_dim / config.num_codebooks),
|
|
1738
|
+
],
|
|
1739
|
+
kernel_initializer=tf.keras.initializers.RandomUniform(),
|
|
1740
|
+
name='target_codebooks',
|
|
1741
|
+
),
|
|
1742
|
+
sl.Flatten(),
|
|
1743
|
+
]),
|
|
1744
|
+
*[
|
|
1745
|
+
t5.T5DecoderBlock(
|
|
1746
|
+
name=f'layer{i:02d}',
|
|
1747
|
+
dimension=hidden_dim,
|
|
1748
|
+
num_heads=config.num_heads,
|
|
1749
|
+
units_per_head=config.units_per_head,
|
|
1750
|
+
dropout_rate=config.dropout_rate,
|
|
1751
|
+
source_name=config.source_name,
|
|
1752
|
+
max_past_horizon=config.max_past_horizon,
|
|
1753
|
+
ffn_dimension=config.ffn_dimension,
|
|
1754
|
+
ffn_activation=tf.nn.gelu,
|
|
1755
|
+
relative_position_embedding=sl.T5RelativePositionEmbedding(
|
|
1756
|
+
num_buckets=32,
|
|
1757
|
+
num_heads=config.num_heads,
|
|
1758
|
+
bidirectional=False,
|
|
1759
|
+
max_distance=config.max_past_horizon,
|
|
1760
|
+
),
|
|
1761
|
+
)
|
|
1762
|
+
for i in range(config.num_decoder_blocks)
|
|
1763
|
+
],
|
|
1764
|
+
sl.RMSNormalization(epsilon=1e-6, name='rms_normalization'),
|
|
1765
|
+
sl.Dropout(rate=config.dropout_rate, noise_shape=[None, 1, None]),
|
|
1766
|
+
]
|
|
1767
|
+
|
|
1768
|
+
super().__init__(
|
|
1769
|
+
layers,
|
|
1770
|
+
name=config.name or None,
|
|
1771
|
+
)
|