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,225 @@
|
|
|
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
|
+
"""T5 using SequenceLayers.
|
|
16
|
+
|
|
17
|
+
Based on:
|
|
18
|
+
"Exploring the Limits of Transfer Learning with a Unified Text-to-Text
|
|
19
|
+
Transformer"
|
|
20
|
+
|
|
21
|
+
https://arxiv.org/abs/1910.10683
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
from typing import Optional
|
|
25
|
+
from sequence_layers import tensorflow as sl
|
|
26
|
+
import tensorflow.compat.v2 as tf
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def FeedforwardBlock(
|
|
30
|
+
dimension: int, hidden_dimension: int, activation: ..., dropout_rate: float
|
|
31
|
+
) -> sl.SequenceLayer:
|
|
32
|
+
with tf.name_scope('ffn'):
|
|
33
|
+
return sl.Residual([
|
|
34
|
+
sl.RMSNormalization(epsilon=1e-6),
|
|
35
|
+
sl.Dense(hidden_dimension, use_bias=False, activation=activation),
|
|
36
|
+
sl.Dropout(dropout_rate, noise_shape=[None, 1, None]),
|
|
37
|
+
sl.Dense(dimension, use_bias=False),
|
|
38
|
+
sl.Dropout(dropout_rate, noise_shape=[None, 1, None]),
|
|
39
|
+
])
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def SelfAttentionBlock(
|
|
43
|
+
dimension: int,
|
|
44
|
+
num_heads: int,
|
|
45
|
+
units_per_head: int,
|
|
46
|
+
dropout_rate: float,
|
|
47
|
+
relative_position_embedding: sl.RelativePositionEmbedding,
|
|
48
|
+
max_past_horizon: int = -1,
|
|
49
|
+
max_future_horizon: int = -1,
|
|
50
|
+
) -> sl.SequenceLayer:
|
|
51
|
+
with tf.name_scope('self_attention'):
|
|
52
|
+
return sl.Residual([
|
|
53
|
+
sl.RMSNormalization(epsilon=1e-6),
|
|
54
|
+
sl.DotProductSelfAttention(
|
|
55
|
+
num_heads=num_heads,
|
|
56
|
+
units_per_head=units_per_head,
|
|
57
|
+
max_horizon=max_past_horizon,
|
|
58
|
+
use_relative_position_embedding=True,
|
|
59
|
+
relative_position_embedding=relative_position_embedding,
|
|
60
|
+
max_future_horizon=max_future_horizon,
|
|
61
|
+
attention_probabilities_dropout_rate=dropout_rate,
|
|
62
|
+
broadcast_dropout_across_queries=True,
|
|
63
|
+
use_bias=False,
|
|
64
|
+
),
|
|
65
|
+
sl.Flatten(),
|
|
66
|
+
sl.Dense(dimension, use_bias=False),
|
|
67
|
+
sl.Dropout(dropout_rate, noise_shape=[None, 1, None]),
|
|
68
|
+
])
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def CrossAttentionBlock(
|
|
72
|
+
source_name: str,
|
|
73
|
+
dimension: int,
|
|
74
|
+
num_heads: int,
|
|
75
|
+
units_per_head: int,
|
|
76
|
+
dropout_rate: float,
|
|
77
|
+
) -> sl.SequenceLayer:
|
|
78
|
+
with tf.name_scope('cross_attention'):
|
|
79
|
+
return sl.Residual([
|
|
80
|
+
sl.RMSNormalization(epsilon=1e-6),
|
|
81
|
+
sl.DotProductAttention(
|
|
82
|
+
source_name=source_name,
|
|
83
|
+
num_heads=num_heads,
|
|
84
|
+
units_per_head=units_per_head,
|
|
85
|
+
attention_probabilities_dropout_rate=dropout_rate,
|
|
86
|
+
broadcast_dropout_across_queries=True,
|
|
87
|
+
use_bias=False,
|
|
88
|
+
),
|
|
89
|
+
sl.Flatten(),
|
|
90
|
+
sl.Dense(dimension, use_bias=False),
|
|
91
|
+
sl.Dropout(dropout_rate, noise_shape=[None, 1, None]),
|
|
92
|
+
])
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def T5Encoder(
|
|
96
|
+
num_layers: int,
|
|
97
|
+
dimension: int,
|
|
98
|
+
num_heads: int,
|
|
99
|
+
ffn_dimension: int,
|
|
100
|
+
ffn_activation: ... = tf.nn.relu,
|
|
101
|
+
dropout_rate: float = 0.0,
|
|
102
|
+
name: Optional[str] = None,
|
|
103
|
+
) -> sl.SequenceLayer:
|
|
104
|
+
"""Builds a T5 encoder."""
|
|
105
|
+
assert dimension % num_heads == 0
|
|
106
|
+
units_per_head = dimension // num_heads
|
|
107
|
+
|
|
108
|
+
shared_relative_position_embedding = sl.T5RelativePositionEmbedding(
|
|
109
|
+
num_buckets=32, num_heads=num_heads, bidirectional=True, max_distance=128
|
|
110
|
+
)
|
|
111
|
+
|
|
112
|
+
def EncoderBlock(name):
|
|
113
|
+
with tf.name_scope(name):
|
|
114
|
+
return sl.Serial([
|
|
115
|
+
SelfAttentionBlock(
|
|
116
|
+
dimension=dimension,
|
|
117
|
+
num_heads=num_heads,
|
|
118
|
+
units_per_head=units_per_head,
|
|
119
|
+
dropout_rate=dropout_rate,
|
|
120
|
+
relative_position_embedding=shared_relative_position_embedding,
|
|
121
|
+
max_past_horizon=-1,
|
|
122
|
+
max_future_horizon=-1,
|
|
123
|
+
),
|
|
124
|
+
FeedforwardBlock(
|
|
125
|
+
dimension=dimension,
|
|
126
|
+
hidden_dimension=ffn_dimension,
|
|
127
|
+
activation=ffn_activation,
|
|
128
|
+
dropout_rate=dropout_rate,
|
|
129
|
+
),
|
|
130
|
+
])
|
|
131
|
+
|
|
132
|
+
with tf.name_scope(name or 't5_encoder'):
|
|
133
|
+
return sl.Serial([
|
|
134
|
+
sl.Dropout(dropout_rate, noise_shape=[None, 1, None]),
|
|
135
|
+
sl.Serial([
|
|
136
|
+
EncoderBlock(name=f'layer{layer_i:02d}')
|
|
137
|
+
for layer_i in range(num_layers)
|
|
138
|
+
]),
|
|
139
|
+
sl.RMSNormalization(epsilon=1e-6),
|
|
140
|
+
sl.Dropout(dropout_rate),
|
|
141
|
+
])
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def T5DecoderBlock(
|
|
145
|
+
name: str,
|
|
146
|
+
dimension: int,
|
|
147
|
+
num_heads: int,
|
|
148
|
+
units_per_head: int,
|
|
149
|
+
dropout_rate: float,
|
|
150
|
+
source_name: str,
|
|
151
|
+
max_past_horizon: int,
|
|
152
|
+
ffn_dimension: int,
|
|
153
|
+
ffn_activation: ...,
|
|
154
|
+
relative_position_embedding: sl.RelativePositionEmbedding,
|
|
155
|
+
) -> sl.SequenceLayer:
|
|
156
|
+
"""Construct a T5 decoder block (self attention, cross attention, FFN)."""
|
|
157
|
+
with tf.name_scope(name):
|
|
158
|
+
return sl.Serial([
|
|
159
|
+
SelfAttentionBlock(
|
|
160
|
+
dimension=dimension,
|
|
161
|
+
num_heads=num_heads,
|
|
162
|
+
units_per_head=units_per_head,
|
|
163
|
+
dropout_rate=dropout_rate,
|
|
164
|
+
relative_position_embedding=relative_position_embedding,
|
|
165
|
+
max_past_horizon=max_past_horizon,
|
|
166
|
+
max_future_horizon=0,
|
|
167
|
+
),
|
|
168
|
+
CrossAttentionBlock(
|
|
169
|
+
source_name=source_name,
|
|
170
|
+
dimension=dimension,
|
|
171
|
+
num_heads=num_heads,
|
|
172
|
+
units_per_head=units_per_head,
|
|
173
|
+
dropout_rate=dropout_rate,
|
|
174
|
+
),
|
|
175
|
+
FeedforwardBlock(
|
|
176
|
+
dimension=dimension,
|
|
177
|
+
hidden_dimension=ffn_dimension,
|
|
178
|
+
activation=ffn_activation,
|
|
179
|
+
dropout_rate=dropout_rate,
|
|
180
|
+
),
|
|
181
|
+
])
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def T5Decoder(
|
|
185
|
+
source_name: str,
|
|
186
|
+
vocab_size: int,
|
|
187
|
+
num_layers: int,
|
|
188
|
+
dimension: int,
|
|
189
|
+
num_heads: int,
|
|
190
|
+
ffn_dimension: int,
|
|
191
|
+
ffn_activation: ... = tf.nn.relu,
|
|
192
|
+
dropout_rate: float = 0.0,
|
|
193
|
+
max_past_horizon: int = 128,
|
|
194
|
+
name: Optional[str] = None,
|
|
195
|
+
) -> sl.SequenceLayer:
|
|
196
|
+
"""Builds a T5 decoder."""
|
|
197
|
+
assert dimension % num_heads == 0
|
|
198
|
+
units_per_head = dimension // num_heads
|
|
199
|
+
|
|
200
|
+
shared_relative_position_embedding = sl.T5RelativePositionEmbedding(
|
|
201
|
+
num_buckets=32, num_heads=num_heads, bidirectional=False, max_distance=128
|
|
202
|
+
)
|
|
203
|
+
|
|
204
|
+
with tf.name_scope(name or 'transformer_decoder'):
|
|
205
|
+
return sl.Serial([
|
|
206
|
+
sl.Dropout(dropout_rate, noise_shape=[None, 1, None]),
|
|
207
|
+
sl.Serial([
|
|
208
|
+
T5DecoderBlock(
|
|
209
|
+
name=f'layer{layer_i:02d}',
|
|
210
|
+
dimension=dimension,
|
|
211
|
+
num_heads=num_heads,
|
|
212
|
+
units_per_head=units_per_head,
|
|
213
|
+
dropout_rate=dropout_rate,
|
|
214
|
+
source_name=source_name,
|
|
215
|
+
max_past_horizon=max_past_horizon,
|
|
216
|
+
ffn_dimension=ffn_dimension,
|
|
217
|
+
ffn_activation=ffn_activation,
|
|
218
|
+
relative_position_embedding=shared_relative_position_embedding,
|
|
219
|
+
)
|
|
220
|
+
for layer_i in range(num_layers)
|
|
221
|
+
]),
|
|
222
|
+
sl.RMSNormalization(epsilon=1e-6),
|
|
223
|
+
sl.Dropout(dropout_rate, noise_shape=[None, 1, None]),
|
|
224
|
+
sl.Dense(vocab_size, name='to_logits'),
|
|
225
|
+
])
|
|
@@ -0,0 +1,124 @@
|
|
|
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
|
+
"""Tacotron using SequenceLayers.
|
|
16
|
+
|
|
17
|
+
Based on:
|
|
18
|
+
Tacotron: Towards End-to-End Speech Synthesis
|
|
19
|
+
https://arxiv.org/abs/1703.10135
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
from sequence_layers import proto as slp
|
|
23
|
+
from sequence_layers import tensorflow as sl
|
|
24
|
+
import tensorflow.compat.v2 as tf
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def TacotronDecoder(
|
|
28
|
+
source_name: str, reduction_factor: int = 2, target_dimension: int = 128
|
|
29
|
+
):
|
|
30
|
+
return sl.Serial([
|
|
31
|
+
# Squeeze to [b, t // rf, rf, target_dimension].
|
|
32
|
+
sl.Squeeze(reduction_factor),
|
|
33
|
+
# Flatten to [b, t // rf, rf * target_dimension]
|
|
34
|
+
sl.Flatten(),
|
|
35
|
+
# Pre-net: Apply an information bottleneck to the previous feature frames.
|
|
36
|
+
sl.Dense(256, activation=tf.nn.relu),
|
|
37
|
+
sl.Dropout(0.5),
|
|
38
|
+
sl.Dense(128, activation=tf.nn.relu),
|
|
39
|
+
sl.Dropout(0.5),
|
|
40
|
+
# Autoregress on the attention output (cell_output, context_vector).
|
|
41
|
+
sl.Autoregressive([
|
|
42
|
+
sl.RNN(tf.keras.layers.LSTMCell(256)),
|
|
43
|
+
# Concatenate cell output with context vector.
|
|
44
|
+
sl.Skip([
|
|
45
|
+
# Attend to the source sequence with
|
|
46
|
+
# query = RNN([previous_context_vector, previous_output]).
|
|
47
|
+
sl.GmmAttention(
|
|
48
|
+
source_name,
|
|
49
|
+
num_heads=1,
|
|
50
|
+
units_per_head=128,
|
|
51
|
+
num_components=5,
|
|
52
|
+
monotonic=True,
|
|
53
|
+
init_offset_bias=1.0,
|
|
54
|
+
init_scale_bias=1.0,
|
|
55
|
+
),
|
|
56
|
+
# Flatten the [b, t//2, num_heads, units_per_head] to
|
|
57
|
+
# [b, t//2, num_heads * units_per_head].
|
|
58
|
+
sl.Flatten(),
|
|
59
|
+
]),
|
|
60
|
+
]),
|
|
61
|
+
# Transform the [attention RNN output, context vector] with 2 residual RNN
|
|
62
|
+
# layers.
|
|
63
|
+
sl.Residual(sl.RNN(tf.keras.layers.LSTMCell(256))),
|
|
64
|
+
sl.Residual(sl.RNN(tf.keras.layers.LSTMCell(256))),
|
|
65
|
+
# Predict reduction_factor output frames from the resulting hidden state.
|
|
66
|
+
sl.Dense(target_dimension * reduction_factor),
|
|
67
|
+
])
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def TacotronDecoderAsProto(
|
|
71
|
+
source_name: str, reduction_factor: int = 2, target_dimension: int = 128
|
|
72
|
+
) -> slp.SequenceLayer:
|
|
73
|
+
"""Returns a SequenceLayer protobuf representing a Tacotron decoder."""
|
|
74
|
+
|
|
75
|
+
def LSTM(num_units):
|
|
76
|
+
return slp.RNN(cell=[slp.RNN.Cell(lstm=slp.RNN.LSTMCell(units=num_units))])
|
|
77
|
+
|
|
78
|
+
return slp.Serial(
|
|
79
|
+
layer=[
|
|
80
|
+
# Squeeze to [b, t // rf, rf, target_dimension].
|
|
81
|
+
slp.Squeeze(factor=reduction_factor),
|
|
82
|
+
# Flatten to [b, t // rf, rf * target_dimension]
|
|
83
|
+
slp.Flatten(),
|
|
84
|
+
# Pre-net: Apply an information bottleneck to the previous feature
|
|
85
|
+
# frames.
|
|
86
|
+
slp.Dense(units=256, activation=slp.Relu()),
|
|
87
|
+
slp.Dropout(rate=0.5),
|
|
88
|
+
slp.Dense(units=128, activation=slp.Relu()),
|
|
89
|
+
slp.Dropout(rate=0.5),
|
|
90
|
+
# Autoregress on the attention output (cell_output, context_vector).
|
|
91
|
+
slp.Autoregressive(
|
|
92
|
+
layer=[
|
|
93
|
+
LSTM(256),
|
|
94
|
+
# Concatenate cell output with context vector.
|
|
95
|
+
slp.Skip(
|
|
96
|
+
layer=[
|
|
97
|
+
# Attend to the source sequence with
|
|
98
|
+
# query = RNN([previous_context_vector,
|
|
99
|
+
# previous_output]).
|
|
100
|
+
slp.GmmAttention(
|
|
101
|
+
source_name=source_name,
|
|
102
|
+
num_heads=1,
|
|
103
|
+
units_per_head=128,
|
|
104
|
+
num_components=5,
|
|
105
|
+
monotonic=True,
|
|
106
|
+
init_offset_bias=1.0,
|
|
107
|
+
init_scale_bias=1.0,
|
|
108
|
+
),
|
|
109
|
+
# Flatten the [b, t//2, num_heads, units_per_head] to
|
|
110
|
+
# [b, t//2, num_heads * units_per_head].
|
|
111
|
+
slp.Flatten(),
|
|
112
|
+
]
|
|
113
|
+
),
|
|
114
|
+
]
|
|
115
|
+
),
|
|
116
|
+
# Transform the [attention RNN output, context vector] with 2 residual
|
|
117
|
+
# RNN layers.
|
|
118
|
+
slp.Residual(layer=[LSTM(256)]),
|
|
119
|
+
slp.Residual(layer=[LSTM(256)]),
|
|
120
|
+
# Predict reduction_factor output frames from the resulting hidden
|
|
121
|
+
# state.
|
|
122
|
+
slp.Dense(units=target_dimension * reduction_factor),
|
|
123
|
+
]
|
|
124
|
+
)
|
|
@@ -0,0 +1,159 @@
|
|
|
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
|
+
"""Transformer using SequenceLayers.
|
|
16
|
+
|
|
17
|
+
Based on:
|
|
18
|
+
"Attention Is All You Need"
|
|
19
|
+
https://arxiv.org/abs/1706.03762
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
from typing import Optional
|
|
23
|
+
from sequence_layers import tensorflow as sl
|
|
24
|
+
import tensorflow.compat.v2 as tf
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def TransformerEncoder(
|
|
28
|
+
num_layers: int,
|
|
29
|
+
dimension: int,
|
|
30
|
+
num_heads: int,
|
|
31
|
+
max_horizon: int,
|
|
32
|
+
max_future_horizon: int,
|
|
33
|
+
ffn_activation=tf.nn.relu,
|
|
34
|
+
attention_probabilities_dropout_rate: float = 0.0,
|
|
35
|
+
ffn_dropout_rate: float = 0.0,
|
|
36
|
+
kernel_initializer=None,
|
|
37
|
+
name: Optional[str] = None,
|
|
38
|
+
):
|
|
39
|
+
"""Builds a Transformer encoder."""
|
|
40
|
+
assert dimension % num_heads == 0
|
|
41
|
+
units_per_head = dimension // num_heads
|
|
42
|
+
|
|
43
|
+
def TransformerLayer(name):
|
|
44
|
+
with tf.name_scope(name):
|
|
45
|
+
return sl.Serial([
|
|
46
|
+
sl.Residual([
|
|
47
|
+
sl.DotProductSelfAttention(
|
|
48
|
+
num_heads=num_heads,
|
|
49
|
+
units_per_head=units_per_head,
|
|
50
|
+
max_horizon=max_horizon,
|
|
51
|
+
max_future_horizon=max_future_horizon,
|
|
52
|
+
kernel_initializer=CloneInitializer(kernel_initializer),
|
|
53
|
+
attention_probabilities_dropout_rate=attention_probabilities_dropout_rate,
|
|
54
|
+
),
|
|
55
|
+
sl.Flatten(),
|
|
56
|
+
]),
|
|
57
|
+
sl.LayerNormalization(),
|
|
58
|
+
sl.Residual([
|
|
59
|
+
sl.Dense(
|
|
60
|
+
dimension * 4,
|
|
61
|
+
kernel_initializer=CloneInitializer(kernel_initializer),
|
|
62
|
+
activation=ffn_activation,
|
|
63
|
+
),
|
|
64
|
+
sl.Dense(
|
|
65
|
+
dimension,
|
|
66
|
+
kernel_initializer=CloneInitializer(kernel_initializer),
|
|
67
|
+
),
|
|
68
|
+
sl.Dropout(ffn_dropout_rate),
|
|
69
|
+
]),
|
|
70
|
+
sl.LayerNormalization(),
|
|
71
|
+
])
|
|
72
|
+
|
|
73
|
+
with tf.name_scope(name or 'transformer_encoder'):
|
|
74
|
+
return sl.Serial(
|
|
75
|
+
[sl.AddTimingSignal()]
|
|
76
|
+
+ [
|
|
77
|
+
TransformerLayer(name=f'layer{layer_i:02d}')
|
|
78
|
+
for layer_i in range(num_layers)
|
|
79
|
+
]
|
|
80
|
+
)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def TransformerDecoder(
|
|
84
|
+
source_name: str,
|
|
85
|
+
num_layers: int,
|
|
86
|
+
dimension: int,
|
|
87
|
+
num_heads: int,
|
|
88
|
+
max_horizon: int,
|
|
89
|
+
ffn_activation=tf.nn.relu,
|
|
90
|
+
attention_probabilities_dropout_rate: float = 0.0,
|
|
91
|
+
ffn_dropout_rate: float = 0.0,
|
|
92
|
+
kernel_initializer=None,
|
|
93
|
+
name: Optional[str] = None,
|
|
94
|
+
):
|
|
95
|
+
"""Builds a Transformer decoder."""
|
|
96
|
+
assert dimension % num_heads == 0
|
|
97
|
+
units_per_head = dimension // num_heads
|
|
98
|
+
|
|
99
|
+
def TransformerLayer(name):
|
|
100
|
+
with tf.name_scope(name):
|
|
101
|
+
return sl.Serial([
|
|
102
|
+
sl.Residual([
|
|
103
|
+
sl.DotProductSelfAttention(
|
|
104
|
+
num_heads=num_heads,
|
|
105
|
+
units_per_head=units_per_head,
|
|
106
|
+
max_horizon=max_horizon,
|
|
107
|
+
attention_probabilities_dropout_rate=attention_probabilities_dropout_rate,
|
|
108
|
+
kernel_initializer=CloneInitializer(kernel_initializer),
|
|
109
|
+
),
|
|
110
|
+
sl.Flatten(),
|
|
111
|
+
]),
|
|
112
|
+
sl.LayerNormalization(),
|
|
113
|
+
# TODO(rryan): Timing signal for queries and keys.
|
|
114
|
+
sl.Residual([
|
|
115
|
+
sl.DotProductAttention(
|
|
116
|
+
source_name,
|
|
117
|
+
num_heads=num_heads,
|
|
118
|
+
units_per_head=units_per_head,
|
|
119
|
+
attention_probabilities_dropout_rate=attention_probabilities_dropout_rate,
|
|
120
|
+
kernel_initializer=CloneInitializer(kernel_initializer),
|
|
121
|
+
),
|
|
122
|
+
sl.Flatten(),
|
|
123
|
+
]),
|
|
124
|
+
sl.LayerNormalization(),
|
|
125
|
+
sl.Residual([
|
|
126
|
+
sl.Dense(
|
|
127
|
+
dimension * 4,
|
|
128
|
+
kernel_initializer=CloneInitializer(kernel_initializer),
|
|
129
|
+
activation=ffn_activation,
|
|
130
|
+
),
|
|
131
|
+
sl.Dense(
|
|
132
|
+
dimension,
|
|
133
|
+
kernel_initializer=CloneInitializer(kernel_initializer),
|
|
134
|
+
),
|
|
135
|
+
sl.Dropout(ffn_dropout_rate),
|
|
136
|
+
]),
|
|
137
|
+
sl.LayerNormalization(),
|
|
138
|
+
])
|
|
139
|
+
|
|
140
|
+
with tf.name_scope(name or 'transformer_decoder'):
|
|
141
|
+
return sl.Serial(
|
|
142
|
+
[sl.AddTimingSignal()]
|
|
143
|
+
+ [
|
|
144
|
+
TransformerLayer(name=f'layer{layer_i:02d}')
|
|
145
|
+
for layer_i in range(num_layers)
|
|
146
|
+
]
|
|
147
|
+
+ [sl.Dense(dimension, activation=tf.nn.softmax)]
|
|
148
|
+
)
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def CloneInitializer(initializer):
|
|
152
|
+
# Keras initializer is going to be stateless, which mean reusing the same
|
|
153
|
+
# initializer will produce same init value when the shapes are the same.
|
|
154
|
+
if isinstance(initializer, tf.keras.initializers.Initializer):
|
|
155
|
+
return initializer.__class__.from_config(initializer.get_config())
|
|
156
|
+
# When the input is string/dict or other serialized configs, caller will
|
|
157
|
+
# create a new keras Initializer instance based on that, and we don't need to
|
|
158
|
+
# do anything
|
|
159
|
+
return initializer
|