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,144 @@
|
|
|
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
|
+
"""BERT using SequenceLayers.
|
|
16
|
+
|
|
17
|
+
Based on:
|
|
18
|
+
BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding
|
|
19
|
+
https://arxiv.org/abs/1810.04805
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
from typing import Optional, Tuple
|
|
23
|
+
from sequence_layers import tensorflow as sl
|
|
24
|
+
from sequence_layers.tensorflow.examples import transformer
|
|
25
|
+
import tensorflow.compat.v2 as tf
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class BERTEncoder(tf.Module):
|
|
29
|
+
"""A BERT encoder network."""
|
|
30
|
+
|
|
31
|
+
def __init__(
|
|
32
|
+
self,
|
|
33
|
+
vocab_size: int,
|
|
34
|
+
num_layers: int = 12,
|
|
35
|
+
dimension: int = 768,
|
|
36
|
+
num_heads: int = 12,
|
|
37
|
+
dropout_rate: float = 0.1,
|
|
38
|
+
kernel_initializer: Optional[tf.keras.initializers.Initializer] = None,
|
|
39
|
+
max_token_length: int = 512,
|
|
40
|
+
name: Optional[str] = None,
|
|
41
|
+
):
|
|
42
|
+
"""Create a BERT encoder.
|
|
43
|
+
|
|
44
|
+
Args:
|
|
45
|
+
vocab_size: The vocab size for the token embedding.
|
|
46
|
+
num_layers: Number of Transformer layers in the encoder.
|
|
47
|
+
dimension: The model dimenison.
|
|
48
|
+
num_heads: The number of heads to use in self-attention layers.
|
|
49
|
+
dropout_rate: The dropout rate to use throughout the model (attention
|
|
50
|
+
probabilities, feed-forward network outputs, etc.).
|
|
51
|
+
kernel_initializer: Initializer to use for kernels throughout the model.
|
|
52
|
+
Biases are initialized as zeros.
|
|
53
|
+
max_token_length: The maximum length in tokens the model supports.
|
|
54
|
+
name: An optional name for the module.
|
|
55
|
+
"""
|
|
56
|
+
super().__init__(name=name)
|
|
57
|
+
if kernel_initializer is None:
|
|
58
|
+
kernel_initializer = tf.keras.initializers.TruncatedNormal(stddev=0.02)
|
|
59
|
+
with self.name_scope:
|
|
60
|
+
self._token_embedding = tf.keras.layers.Embedding(
|
|
61
|
+
vocab_size,
|
|
62
|
+
dimension,
|
|
63
|
+
embeddings_initializer=transformer.CloneInitializer(
|
|
64
|
+
kernel_initializer
|
|
65
|
+
),
|
|
66
|
+
name='token_embeddings',
|
|
67
|
+
)
|
|
68
|
+
self._source_embedding = tf.keras.layers.Embedding(
|
|
69
|
+
2,
|
|
70
|
+
dimension,
|
|
71
|
+
embeddings_initializer=transformer.CloneInitializer(
|
|
72
|
+
kernel_initializer
|
|
73
|
+
),
|
|
74
|
+
name='source_embeddings',
|
|
75
|
+
)
|
|
76
|
+
self._position_embedding = tf.Variable(
|
|
77
|
+
transformer.CloneInitializer(kernel_initializer)(
|
|
78
|
+
(max_token_length, dimension)
|
|
79
|
+
),
|
|
80
|
+
dtype=tf.float32,
|
|
81
|
+
name='position_embeddings',
|
|
82
|
+
)
|
|
83
|
+
self._encoder = sl.Serial([
|
|
84
|
+
sl.LayerNormalization(epsilon=1e-12),
|
|
85
|
+
sl.Dropout(dropout_rate),
|
|
86
|
+
transformer.TransformerEncoder(
|
|
87
|
+
num_layers=num_layers,
|
|
88
|
+
dimension=dimension,
|
|
89
|
+
num_heads=num_heads,
|
|
90
|
+
max_horizon=-1,
|
|
91
|
+
max_future_horizon=-1,
|
|
92
|
+
ffn_activation=tf.nn.gelu,
|
|
93
|
+
ffn_dropout_rate=dropout_rate,
|
|
94
|
+
attention_probabilities_dropout_rate=dropout_rate,
|
|
95
|
+
kernel_initializer=transformer.CloneInitializer(
|
|
96
|
+
kernel_initializer
|
|
97
|
+
),
|
|
98
|
+
name='transformer',
|
|
99
|
+
),
|
|
100
|
+
])
|
|
101
|
+
self._pooler = sl.Dense(
|
|
102
|
+
dimension,
|
|
103
|
+
kernel_initializer=transformer.CloneInitializer(kernel_initializer),
|
|
104
|
+
activation=tf.nn.tanh,
|
|
105
|
+
name='pooler_transform',
|
|
106
|
+
)
|
|
107
|
+
|
|
108
|
+
@tf.Module.with_name_scope
|
|
109
|
+
def encode(
|
|
110
|
+
self, token_ids: sl.Sequence, source_ids: sl.Sequence, training: bool
|
|
111
|
+
) -> Tuple[sl.Sequence, tf.Tensor]:
|
|
112
|
+
"""Encodes the provided sequence.
|
|
113
|
+
|
|
114
|
+
Args:
|
|
115
|
+
token_ids: A [batch_size, time] integer sequence of token IDs. The input
|
|
116
|
+
ids are expected to be formatted according to the BERT paper, i.e.:
|
|
117
|
+
[CLS] Token1 Token2 [SEP] Token3 Token4 [SEP] [MASK] [MASK] [MASK] ...
|
|
118
|
+
source_ids: A [batch_size, time] integer sequence of source IDs (source 0
|
|
119
|
+
is sentence A, source 1 is sentence B). source_ids mask is assumed equal
|
|
120
|
+
to token_ids's mask.
|
|
121
|
+
training: Whether we are in training mode.
|
|
122
|
+
|
|
123
|
+
Returns:
|
|
124
|
+
- A [batch_size, time, dimension] encoded sequence.
|
|
125
|
+
- A [batch_size, dimension] tensor containing the pooled (CLS token)
|
|
126
|
+
outputs for each batch item.
|
|
127
|
+
"""
|
|
128
|
+
token_embeddings = token_ids.apply_values(
|
|
129
|
+
self._token_embedding, training=training
|
|
130
|
+
)
|
|
131
|
+
source_embeddings = source_ids.apply_values(
|
|
132
|
+
self._source_embedding, training=training
|
|
133
|
+
)
|
|
134
|
+
|
|
135
|
+
length = token_ids.values.shape[1] or tf.shape(token_ids.values)[1]
|
|
136
|
+
position_embeddings = self._position_embedding[tf.newaxis, :length]
|
|
137
|
+
|
|
138
|
+
embeddings = token_embeddings.apply_values(
|
|
139
|
+
lambda v: v + source_embeddings.values + position_embeddings
|
|
140
|
+
).mask_invalid()
|
|
141
|
+
outputs = self._encoder.layer(embeddings, training=training)
|
|
142
|
+
cls_output = self._pooler.layer(outputs[:, :1], training=training)
|
|
143
|
+
# TODO(rryan): Corner case of zero output.
|
|
144
|
+
return outputs, cls_output.values[:, 0, :]
|
|
@@ -0,0 +1,138 @@
|
|
|
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
|
+
"""Conformer using Sequence Layers.
|
|
16
|
+
|
|
17
|
+
TODO(rryan): SpecAugment is unimplemented for now.
|
|
18
|
+
|
|
19
|
+
Based on:
|
|
20
|
+
"Conformer: Convolution-augmented Transformer for Speech Recognition"
|
|
21
|
+
https://arxiv.org/abs/2005.08100
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
from typing import Optional
|
|
25
|
+
|
|
26
|
+
from sequence_layers import tensorflow as sl
|
|
27
|
+
import tensorflow.compat.v2 as tf
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def MultiHeadedSelfAttention(
|
|
31
|
+
hidden_size: int, num_heads: int, max_horizon: int, dropout_rate: float
|
|
32
|
+
) -> sl.SequenceLayer:
|
|
33
|
+
with tf.name_scope('multi_headed_self_attention_module'):
|
|
34
|
+
return sl.Residual([
|
|
35
|
+
sl.LayerNormalization(),
|
|
36
|
+
# TODO(rryan): Lingvo's Conformer implementation drops out attention
|
|
37
|
+
# probs as well. Add support for this.
|
|
38
|
+
sl.DotProductSelfAttention(
|
|
39
|
+
num_heads=num_heads,
|
|
40
|
+
units_per_head=hidden_size // num_heads,
|
|
41
|
+
max_horizon=max_horizon,
|
|
42
|
+
use_relative_position_embedding=True,
|
|
43
|
+
),
|
|
44
|
+
# Combine heads with linear projection: [b, t, heads * units_per_head].
|
|
45
|
+
sl.DenseShaped(hidden_size),
|
|
46
|
+
sl.Dropout(dropout_rate),
|
|
47
|
+
])
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def FeedForwardModule(
|
|
51
|
+
hidden_size: int, dropout_rate: float
|
|
52
|
+
) -> sl.SequenceLayer:
|
|
53
|
+
with tf.name_scope('feed_forward_module'):
|
|
54
|
+
return sl.Residual([
|
|
55
|
+
sl.LayerNormalization(),
|
|
56
|
+
sl.Dense(4 * hidden_size, activation=tf.nn.swish),
|
|
57
|
+
sl.Dropout(dropout_rate),
|
|
58
|
+
sl.Dense(hidden_size),
|
|
59
|
+
sl.Dropout(dropout_rate),
|
|
60
|
+
sl.Scale(0.5),
|
|
61
|
+
])
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def ConvolutionModule(
|
|
65
|
+
hidden_size: int, dropout_rate: float
|
|
66
|
+
) -> sl.SequenceLayer:
|
|
67
|
+
with tf.name_scope('convolution_module'):
|
|
68
|
+
return sl.Residual([
|
|
69
|
+
sl.LayerNormalization(),
|
|
70
|
+
sl.Dense(2 * hidden_size),
|
|
71
|
+
sl.GatedLinearUnit(),
|
|
72
|
+
sl.DepthwiseConv1D(kernel_size=32),
|
|
73
|
+
sl.BatchNormalization(),
|
|
74
|
+
sl.Swish(),
|
|
75
|
+
sl.Dense(hidden_size),
|
|
76
|
+
sl.Dropout(dropout_rate),
|
|
77
|
+
])
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def ConformerBlock(
|
|
81
|
+
hidden_size: int,
|
|
82
|
+
dropout_rate: float,
|
|
83
|
+
max_horizon: int,
|
|
84
|
+
name: Optional[str] = None,
|
|
85
|
+
) -> sl.SequenceLayer:
|
|
86
|
+
with tf.name_scope(name or 'conformer_block'):
|
|
87
|
+
# Conformer L uses 8 heads. S and M use 4.
|
|
88
|
+
num_heads = 8
|
|
89
|
+
return sl.Serial([
|
|
90
|
+
FeedForwardModule(hidden_size, dropout_rate),
|
|
91
|
+
MultiHeadedSelfAttention(
|
|
92
|
+
hidden_size, num_heads, max_horizon, dropout_rate
|
|
93
|
+
),
|
|
94
|
+
ConvolutionModule(hidden_size, dropout_rate),
|
|
95
|
+
FeedForwardModule(hidden_size, dropout_rate),
|
|
96
|
+
sl.LayerNormalization(),
|
|
97
|
+
])
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def ConvolutionSubsampling(hidden_size: int) -> sl.SequenceLayer:
|
|
101
|
+
with tf.name_scope('convolutional_subsampling'):
|
|
102
|
+
return sl.Serial([
|
|
103
|
+
# "Convolutional subsampling". Reduce rate by 4x.
|
|
104
|
+
sl.Conv1D(
|
|
105
|
+
filters=hidden_size,
|
|
106
|
+
kernel_size=3,
|
|
107
|
+
strides=2,
|
|
108
|
+
activation=tf.nn.relu,
|
|
109
|
+
),
|
|
110
|
+
sl.Conv1D(
|
|
111
|
+
filters=hidden_size,
|
|
112
|
+
kernel_size=3,
|
|
113
|
+
strides=2,
|
|
114
|
+
activation=tf.nn.relu,
|
|
115
|
+
),
|
|
116
|
+
])
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def ConformerEncoder(
|
|
120
|
+
hidden_size: int,
|
|
121
|
+
num_blocks: int,
|
|
122
|
+
max_horizon: int,
|
|
123
|
+
dropout_rate: float = 0.1,
|
|
124
|
+
) -> sl.SequenceLayer:
|
|
125
|
+
with tf.name_scope('conformer_encoder'):
|
|
126
|
+
return sl.Serial(
|
|
127
|
+
[
|
|
128
|
+
# TODO(rryan): Implement SpecAugment.
|
|
129
|
+
ConvolutionSubsampling(hidden_size),
|
|
130
|
+
sl.Dense(hidden_size),
|
|
131
|
+
sl.AddTimingSignal(),
|
|
132
|
+
sl.Dropout(dropout_rate),
|
|
133
|
+
]
|
|
134
|
+
+ [
|
|
135
|
+
ConformerBlock(hidden_size, dropout_rate, max_horizon, f'block{i}')
|
|
136
|
+
for i in range(num_blocks)
|
|
137
|
+
]
|
|
138
|
+
)
|
|
@@ -0,0 +1,72 @@
|
|
|
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
|
+
"""Deep Voice 3 using SequenceLayers.
|
|
16
|
+
|
|
17
|
+
Based on:
|
|
18
|
+
"Deep Voice 3: Scaling Text-to-Speech with Convolutional Sequence Learning"
|
|
19
|
+
https://arxiv.org/abs/1710.07654
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
import math
|
|
23
|
+
|
|
24
|
+
from sequence_layers import tensorflow as sl
|
|
25
|
+
import tensorflow.compat.v2 as tf
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def DeepVoice3Decoder(
|
|
29
|
+
source_name: str, reduction_factor: int, target_dimension: int
|
|
30
|
+
):
|
|
31
|
+
"""Builds the Deep Voice 3 decoder."""
|
|
32
|
+
|
|
33
|
+
def ConvBlock():
|
|
34
|
+
return sl.Serial([
|
|
35
|
+
sl.Residual([
|
|
36
|
+
sl.Dropout(0.05),
|
|
37
|
+
sl.Conv1D(filters=512, kernel_size=5, strides=1),
|
|
38
|
+
sl.GatedLinearUnit(),
|
|
39
|
+
]),
|
|
40
|
+
sl.Scale(math.sqrt(0.5)),
|
|
41
|
+
])
|
|
42
|
+
|
|
43
|
+
def DecoderLayer():
|
|
44
|
+
return sl.Serial([
|
|
45
|
+
ConvBlock(),
|
|
46
|
+
sl.Residual([
|
|
47
|
+
sl.DotProductAttention(
|
|
48
|
+
source_name, num_heads=1, units_per_head=128
|
|
49
|
+
),
|
|
50
|
+
sl.Flatten(),
|
|
51
|
+
]),
|
|
52
|
+
sl.Scale(math.sqrt(0.5)),
|
|
53
|
+
])
|
|
54
|
+
|
|
55
|
+
return sl.Serial([
|
|
56
|
+
# Squeeze to [b, t // rf, rf, target_dimension].
|
|
57
|
+
sl.Squeeze(reduction_factor),
|
|
58
|
+
# Flatten to [b, t // rf, rf * target_dimension]
|
|
59
|
+
sl.Flatten(),
|
|
60
|
+
# N_prenet=2 pre-net layers.
|
|
61
|
+
sl.Dropout(0.05),
|
|
62
|
+
sl.Dense(128, activation=tf.nn.relu),
|
|
63
|
+
sl.Dropout(0.05),
|
|
64
|
+
sl.Dense(256, activation=tf.nn.relu),
|
|
65
|
+
# N_decoder=4 decoder layers.
|
|
66
|
+
DecoderLayer(),
|
|
67
|
+
DecoderLayer(),
|
|
68
|
+
DecoderLayer(),
|
|
69
|
+
DecoderLayer(),
|
|
70
|
+
# Predict reduction_factor output frames from the resulting hidden state.
|
|
71
|
+
sl.Dense(target_dimension * reduction_factor),
|
|
72
|
+
])
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
# Copyright 2023 Google LLC
|
|
2
|
+
#
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at
|
|
6
|
+
#
|
|
7
|
+
# https://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
#
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License.
|
|
14
|
+
"""Listen Attend and Spell-style seq2seq speech recognizer using SequenceLayers.
|
|
15
|
+
|
|
16
|
+
Roughly follows the "medium" archictecture in:
|
|
17
|
+
K. Irie, R. Prabhavalkar, A. Kannan, A. Bruguier, D. Rybach, and P. Nguyen,
|
|
18
|
+
“On the choice of modeling unit for sequence-to-sequence speech recognition”
|
|
19
|
+
Interspeech, 2019.
|
|
20
|
+
https://arxiv.org/abs/1902.01955
|
|
21
|
+
|
|
22
|
+
which was itself based on
|
|
23
|
+
Y. Zhang, W. Chan, and N. Jaitly
|
|
24
|
+
“Very deep convolutional networks for end-to-end speech recognition”
|
|
25
|
+
ICASSP, 2017.
|
|
26
|
+
https://arxiv.org/abs/1610.03022
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
from sequence_layers import tensorflow as sl
|
|
30
|
+
import tensorflow.compat.v1 as tf
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def StreamingEncoder() -> sl.SequenceLayer:
|
|
34
|
+
"""Defines of a streaming (unidirectional) speech encoder."""
|
|
35
|
+
|
|
36
|
+
def StridedConv2D():
|
|
37
|
+
return sl.Serial([
|
|
38
|
+
sl.Conv2D(
|
|
39
|
+
filters=32,
|
|
40
|
+
kernel_size=3,
|
|
41
|
+
strides=2,
|
|
42
|
+
spatial_padding='valid',
|
|
43
|
+
use_bias=False,
|
|
44
|
+
),
|
|
45
|
+
sl.BatchNormalization(),
|
|
46
|
+
sl.Relu(),
|
|
47
|
+
])
|
|
48
|
+
|
|
49
|
+
def LSTM():
|
|
50
|
+
return sl.Serial([
|
|
51
|
+
sl.RNN(tf.keras.layers.LSTMCell(512)),
|
|
52
|
+
# Skip projection layer since the RNN is unidirectional.
|
|
53
|
+
sl.BatchNormalization(),
|
|
54
|
+
sl.Relu(),
|
|
55
|
+
])
|
|
56
|
+
|
|
57
|
+
return sl.Serial([
|
|
58
|
+
# Strided convolutions downsample the input sequence.
|
|
59
|
+
StridedConv2D(),
|
|
60
|
+
StridedConv2D(),
|
|
61
|
+
# Flatten the frequency and channels dimensions.
|
|
62
|
+
sl.Flatten(),
|
|
63
|
+
LSTM(),
|
|
64
|
+
LSTM(),
|
|
65
|
+
LSTM(),
|
|
66
|
+
LSTM(),
|
|
67
|
+
])
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def DecoderBody(
|
|
71
|
+
source_name: str, num_output_tokens: int = 128
|
|
72
|
+
) -> sl.SequenceLayer:
|
|
73
|
+
"""Single decoder step, takes a one-hot of the previous token as input."""
|
|
74
|
+
embedding_dim = 64
|
|
75
|
+
lstm_dim = 512
|
|
76
|
+
return sl.Serial([
|
|
77
|
+
# Hacky embedding lookup, assumes the inputs are one hot.
|
|
78
|
+
sl.Dense(units=embedding_dim, use_bias=False),
|
|
79
|
+
# Use Autoregressive to pass the context vector from the previous step
|
|
80
|
+
# as input to the first decoder RNN layer.
|
|
81
|
+
sl.Autoregressive(
|
|
82
|
+
[
|
|
83
|
+
sl.RNN(tf.keras.layers.LSTMCell(lstm_dim)),
|
|
84
|
+
# Concatenate cell output with the new context vector to feed into
|
|
85
|
+
# the next RNN layer following attention.
|
|
86
|
+
sl.Skip([
|
|
87
|
+
# Attend to the source sequence with
|
|
88
|
+
# query = RNN([previous_context_vector, previous_output]).
|
|
89
|
+
sl.AdditiveAttention(
|
|
90
|
+
source_name, num_heads=1, units_per_head=128
|
|
91
|
+
),
|
|
92
|
+
# Flatten the num_heads dimension.
|
|
93
|
+
sl.Flatten(),
|
|
94
|
+
]),
|
|
95
|
+
],
|
|
96
|
+
# Only feed the context vector back to the next step.
|
|
97
|
+
feedback_layer=sl.Slice()[lstm_dim:],
|
|
98
|
+
),
|
|
99
|
+
sl.RNN(tf.keras.layers.LSTMCell(lstm_dim)),
|
|
100
|
+
sl.Dense(num_output_tokens),
|
|
101
|
+
sl.Softmax(),
|
|
102
|
+
])
|
|
@@ -0,0 +1,92 @@
|
|
|
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
|
+
"""MobileNet using SequenceLayers.
|
|
16
|
+
|
|
17
|
+
Based on:
|
|
18
|
+
MobileNets: Efficient Convolutional Neural Networks for Mobile Vision
|
|
19
|
+
Applications
|
|
20
|
+
https://arxiv.org/abs/1704.04861
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
from sequence_layers import tensorflow as sl
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def MobileNet2D(num_classes: int = 1000) -> sl.SequenceLayer:
|
|
27
|
+
"""Builds a 2D MobileNet V1 where the time axis is streamed.
|
|
28
|
+
|
|
29
|
+
This is useful for streaming audio processing, where the input is a
|
|
30
|
+
time-frequency representation of sound. It is not useful for video processing;
|
|
31
|
+
we will need a MobileNet3D for that so that each timestep of the stream is a
|
|
32
|
+
new image to process.
|
|
33
|
+
|
|
34
|
+
Args:
|
|
35
|
+
num_classes: The number of classes to model.
|
|
36
|
+
|
|
37
|
+
Returns:
|
|
38
|
+
A SequenceLayer that consumes a [b, t, s, c] tensor and produces a
|
|
39
|
+
[b, t, num_classes] tensor.
|
|
40
|
+
"""
|
|
41
|
+
|
|
42
|
+
def SeparableConv2D(filters, stride):
|
|
43
|
+
return sl.Serial([
|
|
44
|
+
sl.DepthwiseConv2D(
|
|
45
|
+
kernel_size=3,
|
|
46
|
+
strides=stride,
|
|
47
|
+
spatial_padding='same',
|
|
48
|
+
depth_multiplier=1,
|
|
49
|
+
use_bias=False,
|
|
50
|
+
),
|
|
51
|
+
# Normalize the channels dimension of the [b, t, s, c] tensor.
|
|
52
|
+
sl.BatchNormalization(),
|
|
53
|
+
sl.Relu(),
|
|
54
|
+
sl.Conv2D(
|
|
55
|
+
filters=filters,
|
|
56
|
+
kernel_size=1,
|
|
57
|
+
strides=1,
|
|
58
|
+
spatial_padding='valid',
|
|
59
|
+
use_bias=False,
|
|
60
|
+
),
|
|
61
|
+
# Normalize the channels dimension of the [b, t, s, c] tensor.
|
|
62
|
+
sl.BatchNormalization(),
|
|
63
|
+
sl.Relu(),
|
|
64
|
+
])
|
|
65
|
+
|
|
66
|
+
return sl.Serial([
|
|
67
|
+
sl.Conv2D(
|
|
68
|
+
filters=32, kernel_size=3, strides=2, spatial_padding='same'
|
|
69
|
+
), # -> [b, t//2, s//2, 32]
|
|
70
|
+
SeparableConv2D(filters=64, stride=1), # -> [b, t//2, s//2, 64]
|
|
71
|
+
SeparableConv2D(filters=128, stride=2), # -> [b, t//4, s//4, 128]
|
|
72
|
+
SeparableConv2D(filters=128, stride=1), # -> [b, t//4, s//4, 128]
|
|
73
|
+
SeparableConv2D(filters=256, stride=2), # -> [b, t//8, s//8, 256]
|
|
74
|
+
SeparableConv2D(filters=256, stride=1), # -> [b, t//8, s//8, 256]
|
|
75
|
+
SeparableConv2D(filters=512, stride=2), # -> [b, t//16, s//16, 512]
|
|
76
|
+
SeparableConv2D(filters=512, stride=1), # -> [b, t//16, s//16, 512]
|
|
77
|
+
SeparableConv2D(filters=512, stride=1), # -> [b, t//16, s//16, 512]
|
|
78
|
+
SeparableConv2D(filters=512, stride=1), # -> [b, t//16, s//16, 512]
|
|
79
|
+
SeparableConv2D(filters=512, stride=1), # -> [b, t//16, s//16, 512]
|
|
80
|
+
SeparableConv2D(filters=512, stride=1), # -> [b, t//16, s//16, 512]
|
|
81
|
+
SeparableConv2D(filters=1024, stride=2), # -> [b, t//32, s//32, 1024]
|
|
82
|
+
SeparableConv2D(filters=1024, stride=1), # -> [b, t//32, s//32, 1024]
|
|
83
|
+
# We don't have a GlobalAveragePooling2D, so assuming the input spatial
|
|
84
|
+
# dimension is 224, we can use stride 7 in the spatial dimension to reduce
|
|
85
|
+
# the spatial dimension to size 1.
|
|
86
|
+
sl.AveragePooling2D(
|
|
87
|
+
pool_size=7, strides=(1, 7)
|
|
88
|
+
), # -> [b, t//32, s//224, 1024]
|
|
89
|
+
sl.Flatten(), # -> [b, t//32, s//224 * 1024]
|
|
90
|
+
sl.Dense(num_classes), # -> [b, t//32, num_classes]
|
|
91
|
+
sl.Softmax(), # -> [b, t//32, num_classes]
|
|
92
|
+
])
|