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,1855 @@
|
|
|
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
|
+
"""Convolution layers."""
|
|
15
|
+
|
|
16
|
+
import fractions
|
|
17
|
+
from typing import List, Optional, Tuple, Union
|
|
18
|
+
|
|
19
|
+
import numpy as np
|
|
20
|
+
from sequence_layers.tensorflow import types
|
|
21
|
+
from sequence_layers.tensorflow import utils
|
|
22
|
+
import tensorflow as tf
|
|
23
|
+
import tensorflow.compat.v2 as tf
|
|
24
|
+
import tf_keras
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def compute_conv_mask(
|
|
28
|
+
mask: tf.Tensor,
|
|
29
|
+
kernel_size: int,
|
|
30
|
+
stride: int,
|
|
31
|
+
dilation_rate: int,
|
|
32
|
+
padding: str,
|
|
33
|
+
) -> tf.Tensor:
|
|
34
|
+
"""Given an input mask, computes the output mask for a convolution.
|
|
35
|
+
|
|
36
|
+
The formula for the output time dimension for a [b, t] mask is:
|
|
37
|
+
|
|
38
|
+
effective_kernel_size = (kernel_size - 1) * dilation_rate + 1
|
|
39
|
+
output_frames = ceil((t - effective_kernel_size + 1) / stride)
|
|
40
|
+
|
|
41
|
+
If padding is 'causal', we assume that the mask has causal padding of
|
|
42
|
+
`effective_kernel_size - 1` applied which ensures that the above
|
|
43
|
+
formula is at least zero, because `t >= effective_kernel_size - 1`.
|
|
44
|
+
|
|
45
|
+
Args:
|
|
46
|
+
mask: The input [b, t] mask.
|
|
47
|
+
kernel_size: The kernel size in the time dimension.
|
|
48
|
+
stride: The stride in the time dimension.
|
|
49
|
+
dilation_rate: The dilation rate in the time dimension.
|
|
50
|
+
padding: The padding mode.
|
|
51
|
+
|
|
52
|
+
Returns:
|
|
53
|
+
The output mask. [b, ceil((t - effective_kernel_size + 1) / stride)]
|
|
54
|
+
"""
|
|
55
|
+
assert kernel_size >= 1
|
|
56
|
+
assert stride >= 1
|
|
57
|
+
assert dilation_rate >= 1
|
|
58
|
+
|
|
59
|
+
# Special-case kernel_size 1. Dilation has no effect at kernel_size 1.
|
|
60
|
+
if kernel_size == 1:
|
|
61
|
+
if stride == 1:
|
|
62
|
+
return mask
|
|
63
|
+
else:
|
|
64
|
+
return mask[:, ::stride]
|
|
65
|
+
|
|
66
|
+
padding = types.validate_padding(padding)
|
|
67
|
+
if padding == types.PaddingMode.SAME.value:
|
|
68
|
+
# If stride is 1, input mask equals the output mask.
|
|
69
|
+
if stride == 1:
|
|
70
|
+
return mask
|
|
71
|
+
else:
|
|
72
|
+
# We assume that we have corrected for TensorFlow's SAME padding quirks
|
|
73
|
+
# which align the last input timestep with the last output timestep
|
|
74
|
+
# instead of the first input timestep with the first output timestep.
|
|
75
|
+
# Strided slice behaves like a kernel size 1, same convolution with this
|
|
76
|
+
# adjustment applied -- the output length is (input + stride - 1) //
|
|
77
|
+
# stride.
|
|
78
|
+
return mask[:, ::stride]
|
|
79
|
+
|
|
80
|
+
if padding == types.PaddingMode.REVERSE_CAUSAL.value:
|
|
81
|
+
effective_kernel_size = utils.convolution_effective_kernel_size(
|
|
82
|
+
kernel_size, dilation_rate
|
|
83
|
+
)
|
|
84
|
+
padding = [(0, 0), (0, effective_kernel_size - 1), (0, 0), (0, 0)]
|
|
85
|
+
# Use conv2d since conv1d doesn't support explicit padding.
|
|
86
|
+
mask = tf.nn.conv2d(
|
|
87
|
+
mask[:, :, tf.newaxis, tf.newaxis],
|
|
88
|
+
tf.ones([kernel_size, 1, 1, 1]),
|
|
89
|
+
strides=[stride, 1],
|
|
90
|
+
dilations=[dilation_rate, 1],
|
|
91
|
+
padding=padding,
|
|
92
|
+
)
|
|
93
|
+
mask = tf.squeeze(mask, [2, 3])
|
|
94
|
+
# Each timestep contains the sum of the mask values for inputs in its
|
|
95
|
+
# receptive field, so only timesteps equal to kernel_size are fully valid.
|
|
96
|
+
return mask // kernel_size
|
|
97
|
+
|
|
98
|
+
assert padding in (
|
|
99
|
+
types.PaddingMode.VALID.value,
|
|
100
|
+
types.PaddingMode.CAUSAL.value,
|
|
101
|
+
), padding
|
|
102
|
+
if dilation_rate > 1:
|
|
103
|
+
# This is the correct but expensive (conv1d) calculation of the mask.
|
|
104
|
+
# TODO(rryan): Benchmark whether this is actually any slower than the
|
|
105
|
+
# below "shortcut" methods.
|
|
106
|
+
mask = tf.nn.conv1d(
|
|
107
|
+
mask[:, :, tf.newaxis],
|
|
108
|
+
tf.ones([kernel_size, 1, 1]),
|
|
109
|
+
stride=stride,
|
|
110
|
+
dilations=dilation_rate,
|
|
111
|
+
padding='VALID',
|
|
112
|
+
)
|
|
113
|
+
mask = tf.squeeze(mask, 2)
|
|
114
|
+
# Each timestep contains the sum of the mask values for inputs in its
|
|
115
|
+
# receptive field, so only timesteps equal to kernel_size are fully valid.
|
|
116
|
+
return mask // kernel_size
|
|
117
|
+
else:
|
|
118
|
+
assert dilation_rate == 1
|
|
119
|
+
assert stride >= 1
|
|
120
|
+
# To avoid running a second convolution for the mask, consider 3 cases
|
|
121
|
+
# where stride >= 1:
|
|
122
|
+
# - kernel_size > stride
|
|
123
|
+
# - kernel_size == stride
|
|
124
|
+
# - kernel_size < stride
|
|
125
|
+
#
|
|
126
|
+
# Example length 5 sequence:
|
|
127
|
+
# x is causal padding, ABCDE is valid and 0 is padding.
|
|
128
|
+
# values: x x A B C D E 0 0 0 0 0
|
|
129
|
+
# mask: 1 1 1 1 1 1 1 0 0 0 0 0
|
|
130
|
+
#
|
|
131
|
+
# The formula for the output size of a VALID convolution is:
|
|
132
|
+
# out_t = ceil((in_t - dilation_rate * (kernel_size - 1)) / stride)
|
|
133
|
+
#
|
|
134
|
+
# Causal padding means that we always output at least 0 samples, and will
|
|
135
|
+
# never get an error that the convolution would produce a negative size
|
|
136
|
+
# input.
|
|
137
|
+
#
|
|
138
|
+
# kernel_size 3 stride 2:
|
|
139
|
+
# x x A B C D E 0 0 0 0 0
|
|
140
|
+
# x x A
|
|
141
|
+
# A B C
|
|
142
|
+
# C D E
|
|
143
|
+
# E 0 0
|
|
144
|
+
# 0 0 0
|
|
145
|
+
# 0 0 <- not produced with VALID convolution.
|
|
146
|
+
# expected output_size = ceil(10 / 2) = 5
|
|
147
|
+
# expected mask: 1 1 1 0 0
|
|
148
|
+
|
|
149
|
+
if kernel_size > stride:
|
|
150
|
+
# Case 1: The convolution kernel overlaps from step to step. Use
|
|
151
|
+
# tf.signal.frame to compute [batch, num_frames, kernel_size]
|
|
152
|
+
# overlapping frames of the mask tensor, then reduce across channels so
|
|
153
|
+
# that any frame containing partially valid samples is considered
|
|
154
|
+
# invalid.
|
|
155
|
+
mask = tf.signal.frame(
|
|
156
|
+
mask, frame_length=kernel_size, frame_step=stride, pad_end=False
|
|
157
|
+
)
|
|
158
|
+
return tf.reduce_min(mask, axis=2)
|
|
159
|
+
|
|
160
|
+
# kernel_size 3 stride 3:
|
|
161
|
+
# x x A B C D E 0 0 0 0 0
|
|
162
|
+
# x x A
|
|
163
|
+
# B C D
|
|
164
|
+
# E 0 0
|
|
165
|
+
# 0 0 0
|
|
166
|
+
# expected output_size = ceil(10 / 3) = 4
|
|
167
|
+
# expected mask: 1 1 0 0
|
|
168
|
+
|
|
169
|
+
elif kernel_size == stride:
|
|
170
|
+
# Case 2: The kernel size is equal to the stride. This means we can
|
|
171
|
+
# just reshape the mask into [batch_size, num_frames, kernel_size],
|
|
172
|
+
# then reduce across channels so that any frame containing partially
|
|
173
|
+
# valid samples is considered invalid. We have to use the VALID formula
|
|
174
|
+
# above to truncate the mask so the reshape produces the same number of
|
|
175
|
+
# frames that the convolution will.
|
|
176
|
+
batch_size, time = utils.smart_dimension_size(mask)
|
|
177
|
+
num_frames = time // stride
|
|
178
|
+
time_truncated = num_frames * stride
|
|
179
|
+
mask = tf.reshape(
|
|
180
|
+
mask[:, :time_truncated], [batch_size, num_frames, stride]
|
|
181
|
+
)
|
|
182
|
+
return tf.reduce_min(mask, axis=2)
|
|
183
|
+
|
|
184
|
+
# kernel_size 3 stride 4:
|
|
185
|
+
# x x A B C D E 0 0 0 0 0
|
|
186
|
+
# x x A
|
|
187
|
+
# C D E
|
|
188
|
+
# 0 0 0
|
|
189
|
+
# . . . <- past the end of the signal
|
|
190
|
+
# expected output_size = ceil(10 / 4) = 3
|
|
191
|
+
# expected mask: 1 1 0
|
|
192
|
+
|
|
193
|
+
else:
|
|
194
|
+
# In this case, the stride is greater than the kernel size. Like case 2
|
|
195
|
+
# there is no overlap, and we just need to know the number of valid
|
|
196
|
+
# frames the convolution will produce. We thus just reshape the mask to
|
|
197
|
+
# [batch, ..., stride], and then trim that to [batch, ..., kernel_size].
|
|
198
|
+
#
|
|
199
|
+
# The general formula for the length of an overlap-added signal with
|
|
200
|
+
# stride/kernel_size is:
|
|
201
|
+
# (num_frames - 1) * stride + kernel_size == length
|
|
202
|
+
#
|
|
203
|
+
# Solving for num_frames, we can see the target to pad/truncate to:
|
|
204
|
+
# num_frames = 1 + (length - kernel_size) // stride
|
|
205
|
+
assert kernel_size < stride
|
|
206
|
+
batch_size, time = utils.smart_dimension_size(mask)
|
|
207
|
+
num_frames = 1 + (time - kernel_size) // stride
|
|
208
|
+
# The length we need to pad or truncate mask to.
|
|
209
|
+
padded_time = num_frames * stride
|
|
210
|
+
pad_amount = tf.maximum(0, padded_time - time)
|
|
211
|
+
# Pad and truncate so that mask is num_frames * stride long.
|
|
212
|
+
mask = tf.pad(mask, [[0, 0], [0, pad_amount]])[:, :padded_time]
|
|
213
|
+
# Reshape into windows of length stride.
|
|
214
|
+
mask = tf.reshape(mask, [batch_size, num_frames, stride])
|
|
215
|
+
# Trim the windows to cover only the kernel_size region.
|
|
216
|
+
mask = mask[:, :, :kernel_size]
|
|
217
|
+
# Mark any frame covering any invalid samples as invalid.
|
|
218
|
+
return tf.reduce_min(mask, axis=2)
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def _compute_conv_transpose_output_length(
|
|
222
|
+
time: tf.Tensor,
|
|
223
|
+
kernel_size: int,
|
|
224
|
+
stride: int,
|
|
225
|
+
dilation_rate: int,
|
|
226
|
+
padding: str,
|
|
227
|
+
):
|
|
228
|
+
"""Returns the output time for a transpose convolution, matching Keras."""
|
|
229
|
+
# Based on tf-keras (tf_keras/utils/conv_utils.py).
|
|
230
|
+
padding = types.validate_padding(padding)
|
|
231
|
+
# Get the effective kernel size with dilation.
|
|
232
|
+
kernel_size = utils.convolution_effective_kernel_size(
|
|
233
|
+
kernel_size, dilation_rate
|
|
234
|
+
)
|
|
235
|
+
|
|
236
|
+
if padding == 'same':
|
|
237
|
+
output_time = time * stride
|
|
238
|
+
else:
|
|
239
|
+
output_time = time * stride + max(kernel_size - stride, 0)
|
|
240
|
+
|
|
241
|
+
return output_time
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def _compute_conv_transpose_mask(
|
|
245
|
+
mask: tf.Tensor, kernel_size: int, stride: int, padding: str
|
|
246
|
+
) -> tf.Tensor:
|
|
247
|
+
"""Given an input mask, computes the output mask for a transpose convolution.
|
|
248
|
+
|
|
249
|
+
Args:
|
|
250
|
+
mask: The input [b, t] mask.
|
|
251
|
+
kernel_size: The kernel size in the time dimension.
|
|
252
|
+
stride: The stride in the time dimension.
|
|
253
|
+
padding: The padding mode. One of 'valid', 'same', or 'causal'.
|
|
254
|
+
|
|
255
|
+
Returns:
|
|
256
|
+
The output mask. [b, t * stride + max(kernel_size - stride, 0)].
|
|
257
|
+
"""
|
|
258
|
+
padding = types.validate_padding(padding)
|
|
259
|
+
with tf.name_scope('conv_transpose_mask'):
|
|
260
|
+
batch_size, time = utils.smart_dimension_size(mask)
|
|
261
|
+
|
|
262
|
+
if kernel_size <= stride or padding == 'same':
|
|
263
|
+
return tf.repeat(mask, stride, axis=1)
|
|
264
|
+
|
|
265
|
+
# If kernel_size > stride, use an actual transpose convolution to compute
|
|
266
|
+
# the mask.
|
|
267
|
+
invalid_mask = 1.0 - mask
|
|
268
|
+
output_time = _compute_conv_transpose_output_length(
|
|
269
|
+
time, kernel_size, stride, dilation_rate=1, padding=padding
|
|
270
|
+
)
|
|
271
|
+
mask = tf.nn.conv2d_transpose(
|
|
272
|
+
invalid_mask[:, :, tf.newaxis, tf.newaxis],
|
|
273
|
+
filters=tf.ones((kernel_size, 1, 1, 1), dtype=mask.dtype),
|
|
274
|
+
output_shape=[batch_size, output_time, 1, 1],
|
|
275
|
+
strides=stride,
|
|
276
|
+
padding='SAME' if padding == 'same' else 'VALID',
|
|
277
|
+
data_format='NHWC',
|
|
278
|
+
dilations=None,
|
|
279
|
+
)
|
|
280
|
+
mask = tf.squeeze(mask, [2, 3])
|
|
281
|
+
# Any non-zero values in mask have been corrupted by invalid timesteps.
|
|
282
|
+
mask = tf.cast(tf.equal(mask, 0.0), mask.dtype)
|
|
283
|
+
return mask
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
class BaseConv1D(types.SequenceLayer):
|
|
287
|
+
"""Shared base logic for Conv1D layers."""
|
|
288
|
+
|
|
289
|
+
def __init__(
|
|
290
|
+
self,
|
|
291
|
+
kernel_size: int,
|
|
292
|
+
strides: int,
|
|
293
|
+
dilation_rate: int,
|
|
294
|
+
padding: str,
|
|
295
|
+
name=None,
|
|
296
|
+
):
|
|
297
|
+
super().__init__(name=name)
|
|
298
|
+
self._kernel_size = kernel_size
|
|
299
|
+
self._strides = strides
|
|
300
|
+
self._dilation_rate = dilation_rate
|
|
301
|
+
self._padding = types.validate_padding(padding)
|
|
302
|
+
|
|
303
|
+
if self._padding == 'causal':
|
|
304
|
+
# (effective_kernel_size - 1) padding makes convolution fully causal.
|
|
305
|
+
self._buffer_width = (
|
|
306
|
+
utils.convolution_effective_kernel_size(kernel_size, dilation_rate)
|
|
307
|
+
- 1
|
|
308
|
+
)
|
|
309
|
+
else:
|
|
310
|
+
self._buffer_width = 0
|
|
311
|
+
|
|
312
|
+
@property
|
|
313
|
+
def supports_step(self) -> bool:
|
|
314
|
+
return self._padding == 'causal'
|
|
315
|
+
|
|
316
|
+
@property
|
|
317
|
+
def block_size(self) -> int:
|
|
318
|
+
return self._strides
|
|
319
|
+
|
|
320
|
+
@property
|
|
321
|
+
def output_ratio(self) -> fractions.Fraction:
|
|
322
|
+
return fractions.Fraction(1, self._strides)
|
|
323
|
+
|
|
324
|
+
def get_initial_state(
|
|
325
|
+
self, x: types.Sequence, constants: Optional[types.Constants] = None
|
|
326
|
+
) -> types.State:
|
|
327
|
+
# Special case kernel_size 1 since it is stateless.
|
|
328
|
+
if not self._buffer_width:
|
|
329
|
+
return ()
|
|
330
|
+
# When executing a conv1d step-by-step, we need a buffer for tracking
|
|
331
|
+
# the current causal convolution window.
|
|
332
|
+
batch_size = utils.smart_dimension_size(x.values, 0)
|
|
333
|
+
# This matches the causal padding added by `layer`.
|
|
334
|
+
return types.Sequence(
|
|
335
|
+
tf.zeros(
|
|
336
|
+
(batch_size, self._buffer_width, x.values.shape.dims[2].value),
|
|
337
|
+
dtype=x.values.dtype,
|
|
338
|
+
),
|
|
339
|
+
tf.ones((batch_size, self._buffer_width), dtype=x.mask.dtype),
|
|
340
|
+
)
|
|
341
|
+
|
|
342
|
+
def _apply_conv(
|
|
343
|
+
self,
|
|
344
|
+
x: tf.Tensor,
|
|
345
|
+
explicit_padding: tuple[int, int],
|
|
346
|
+
) -> tf.Tensor:
|
|
347
|
+
if explicit_padding[0] != 0 or explicit_padding[1] != 0:
|
|
348
|
+
x = tf.pad(x, ((0, 0), explicit_padding, (0, 0)))
|
|
349
|
+
return self._layer(x)
|
|
350
|
+
|
|
351
|
+
@tf.Module.with_name_scope
|
|
352
|
+
def step(
|
|
353
|
+
self,
|
|
354
|
+
x: types.Sequence,
|
|
355
|
+
state: types.State,
|
|
356
|
+
training: bool,
|
|
357
|
+
constants: Optional[types.Constants] = None,
|
|
358
|
+
) -> Tuple[types.Sequence, types.State]:
|
|
359
|
+
if not self.supports_step:
|
|
360
|
+
raise ValueError(f'{self} does not support stepping.')
|
|
361
|
+
|
|
362
|
+
# Special case kernel_size 1 since it is stateless.
|
|
363
|
+
if not self._buffer_width:
|
|
364
|
+
values = self._apply_conv(x.values, (0, 0))
|
|
365
|
+
mask = compute_conv_mask(
|
|
366
|
+
x.mask,
|
|
367
|
+
self._kernel_size,
|
|
368
|
+
self._strides,
|
|
369
|
+
self._dilation_rate,
|
|
370
|
+
self._padding,
|
|
371
|
+
)
|
|
372
|
+
return types.Sequence(values, mask).mask_invalid(), state
|
|
373
|
+
|
|
374
|
+
# Concatenate the new frames with the previous buffer_width frames.
|
|
375
|
+
state = state.concatenate(x)
|
|
376
|
+
|
|
377
|
+
# Compute the output for the current timestep.
|
|
378
|
+
values = self._apply_conv(state.values, (0, 0))
|
|
379
|
+
mask = compute_conv_mask(
|
|
380
|
+
state.mask,
|
|
381
|
+
self._kernel_size,
|
|
382
|
+
self._strides,
|
|
383
|
+
self._dilation_rate,
|
|
384
|
+
self._padding,
|
|
385
|
+
)
|
|
386
|
+
|
|
387
|
+
# Keep the trailing buffer_width samples for the next step.
|
|
388
|
+
state = state[:, -self._buffer_width :]
|
|
389
|
+
|
|
390
|
+
return types.Sequence(values, mask).mask_invalid(), state
|
|
391
|
+
|
|
392
|
+
@tf.Module.with_name_scope
|
|
393
|
+
def layer(
|
|
394
|
+
self,
|
|
395
|
+
x: types.Sequence,
|
|
396
|
+
training: bool,
|
|
397
|
+
initial_state: Optional[types.State] = None,
|
|
398
|
+
constants: Optional[types.Constants] = None,
|
|
399
|
+
):
|
|
400
|
+
explicit_padding = utils.convolution_explicit_padding(
|
|
401
|
+
self._padding,
|
|
402
|
+
self._kernel_size,
|
|
403
|
+
self._dilation_rate,
|
|
404
|
+
)
|
|
405
|
+
values = self._apply_conv(x.values, explicit_padding)
|
|
406
|
+
|
|
407
|
+
# In causal mode, x.mask is padded and compute_conv_mask uses a VALID
|
|
408
|
+
# convolution. In SAME mode, x.mask is not padded, and compute_conv_mask
|
|
409
|
+
# uses a strided slice mask[:, ::time_stride].
|
|
410
|
+
if self._padding == types.PaddingMode.CAUSAL.value:
|
|
411
|
+
# We can't use convolutional padding here since its value is 0.0, not 1.0.
|
|
412
|
+
mask = tf.pad(
|
|
413
|
+
x.mask,
|
|
414
|
+
[[0, 0], [self._buffer_width, 0]],
|
|
415
|
+
mode='constant',
|
|
416
|
+
constant_values=1.0,
|
|
417
|
+
)
|
|
418
|
+
else:
|
|
419
|
+
mask = x.mask
|
|
420
|
+
|
|
421
|
+
mask = compute_conv_mask(
|
|
422
|
+
mask,
|
|
423
|
+
self._kernel_size,
|
|
424
|
+
self._strides,
|
|
425
|
+
self._dilation_rate,
|
|
426
|
+
self._padding,
|
|
427
|
+
)
|
|
428
|
+
return types.Sequence(values, mask).mask_invalid()
|
|
429
|
+
|
|
430
|
+
|
|
431
|
+
class Conv1D(BaseConv1D):
|
|
432
|
+
"""A 1D convolution layer. Supports both strided and dilated convolution."""
|
|
433
|
+
|
|
434
|
+
@classmethod
|
|
435
|
+
def _default_name(cls):
|
|
436
|
+
"""The default module name for this class."""
|
|
437
|
+
return 'conv1d'
|
|
438
|
+
|
|
439
|
+
def __init__(
|
|
440
|
+
self,
|
|
441
|
+
filters: int,
|
|
442
|
+
kernel_size: int,
|
|
443
|
+
strides: int = 1,
|
|
444
|
+
dilation_rate: int = 1,
|
|
445
|
+
groups: int = 1,
|
|
446
|
+
activation=None,
|
|
447
|
+
use_bias: bool = True,
|
|
448
|
+
kernel_initializer='glorot_uniform',
|
|
449
|
+
bias_initializer='zeros',
|
|
450
|
+
kernel_regularizer=None,
|
|
451
|
+
bias_regularizer=None,
|
|
452
|
+
activity_regularizer=None,
|
|
453
|
+
kernel_constraint=None,
|
|
454
|
+
bias_constraint=None,
|
|
455
|
+
trainable: bool = True,
|
|
456
|
+
padding: str = 'causal',
|
|
457
|
+
weight_norm: bool = False,
|
|
458
|
+
name: Optional[str] = None,
|
|
459
|
+
):
|
|
460
|
+
super().__init__(kernel_size, strides, dilation_rate, padding, name=name)
|
|
461
|
+
self._filters = filters
|
|
462
|
+
with self.name_scope as name_scope:
|
|
463
|
+
self._layer = tf.keras.layers.Conv1D(
|
|
464
|
+
filters,
|
|
465
|
+
kernel_size,
|
|
466
|
+
strides,
|
|
467
|
+
# We apply padding outside of Keras.
|
|
468
|
+
padding='valid',
|
|
469
|
+
data_format='channels_last',
|
|
470
|
+
dilation_rate=dilation_rate,
|
|
471
|
+
groups=groups,
|
|
472
|
+
activation=activation,
|
|
473
|
+
use_bias=use_bias,
|
|
474
|
+
kernel_initializer=kernel_initializer,
|
|
475
|
+
bias_initializer=bias_initializer,
|
|
476
|
+
kernel_regularizer=kernel_regularizer,
|
|
477
|
+
bias_regularizer=bias_regularizer,
|
|
478
|
+
activity_regularizer=activity_regularizer,
|
|
479
|
+
kernel_constraint=kernel_constraint,
|
|
480
|
+
bias_constraint=bias_constraint,
|
|
481
|
+
trainable=trainable,
|
|
482
|
+
name=name_scope,
|
|
483
|
+
)
|
|
484
|
+
if weight_norm:
|
|
485
|
+
self._layer = utils.WeightNorm(self._layer, name='weight_norm')
|
|
486
|
+
|
|
487
|
+
def get_output_shape(
|
|
488
|
+
self,
|
|
489
|
+
input_shape: tf.TensorShape,
|
|
490
|
+
constants: Optional[types.Constants] = None,
|
|
491
|
+
) -> tf.TensorShape:
|
|
492
|
+
if input_shape.rank != 1:
|
|
493
|
+
raise ValueError(
|
|
494
|
+
'Conv1D requires rank 3 input got: %s'
|
|
495
|
+
% tf.TensorShape([None, None]).concatenate(input_shape)
|
|
496
|
+
)
|
|
497
|
+
return tf.TensorShape([self._filters])
|
|
498
|
+
|
|
499
|
+
|
|
500
|
+
def _kaiser_sinc_filter1d(
|
|
501
|
+
cutoff: float, kaiser_beta: float, window_length: int
|
|
502
|
+
) -> np.ndarray:
|
|
503
|
+
"""Creates a kaiser-windowed sinc filter."""
|
|
504
|
+
if cutoff <= 0.0 or cutoff > 0.5:
|
|
505
|
+
raise ValueError(f'{cutoff=} should be in (0, 0.5].')
|
|
506
|
+
|
|
507
|
+
# The general form of the length M + 1 filter is:
|
|
508
|
+
# h[i] = K * window * sin(2 * pi * cutoff * i) / (i * pi)
|
|
509
|
+
#
|
|
510
|
+
# With a shift of i = t - M/2 to center the length M + 1 filter.
|
|
511
|
+
# Where K is a normalizing constant ensuring the filter sums to 1.
|
|
512
|
+
#
|
|
513
|
+
# https://www.analog.com/media/en/technical-documentation/dsp-book/dsp_book_Ch16.pdf
|
|
514
|
+
#
|
|
515
|
+
# Since np.sinc is sin(pi * x) / (pi * x):
|
|
516
|
+
# h[i] = K * 2 * cutoff * window * np.sinc(2 * cutoff * i)
|
|
517
|
+
window = np.kaiser(window_length, kaiser_beta)
|
|
518
|
+
time = np.arange(window_length) - window_length / 2 + 0.5
|
|
519
|
+
f = 2 * cutoff * window * np.sinc(2 * cutoff * time)
|
|
520
|
+
|
|
521
|
+
# Normalize the filter to sum to 1. (K)
|
|
522
|
+
f /= np.sum(f)
|
|
523
|
+
|
|
524
|
+
return f.astype(np.float32)
|
|
525
|
+
|
|
526
|
+
|
|
527
|
+
class SincFilter1D(BaseConv1D):
|
|
528
|
+
"""Applies a windowed-sinc filter as a DepthwiseConv1D."""
|
|
529
|
+
|
|
530
|
+
@classmethod
|
|
531
|
+
def _default_name(cls):
|
|
532
|
+
"""The default module name for this class."""
|
|
533
|
+
return 'sinc_filter1d'
|
|
534
|
+
|
|
535
|
+
def __init__(
|
|
536
|
+
self,
|
|
537
|
+
kernel_size: int,
|
|
538
|
+
strides: int = 1,
|
|
539
|
+
cutoff: float = 0.5,
|
|
540
|
+
kaiser_beta: float = 6.0,
|
|
541
|
+
padding: str = 'causal',
|
|
542
|
+
name: Optional[str] = None,
|
|
543
|
+
):
|
|
544
|
+
super().__init__(
|
|
545
|
+
kernel_size, strides, dilation_rate=1, padding=padding, name=name
|
|
546
|
+
)
|
|
547
|
+
self._filter = _kaiser_sinc_filter1d(cutoff, kaiser_beta, kernel_size)
|
|
548
|
+
|
|
549
|
+
def _layer(self, x: tf.Tensor) -> tf.Tensor:
|
|
550
|
+
if x.shape.rank != 3:
|
|
551
|
+
raise ValueError(f'Expected rank 3 inputs. Got: {x.shape}')
|
|
552
|
+
channels = x.shape.dims[2].value
|
|
553
|
+
|
|
554
|
+
# Filter shape is [height, width=1, in_channels, channel_multiplier=1].
|
|
555
|
+
sinc_filter = tf.tile(
|
|
556
|
+
self._filter[:, tf.newaxis, tf.newaxis, tf.newaxis], [1, 1, channels, 1]
|
|
557
|
+
)
|
|
558
|
+
|
|
559
|
+
# Insert a placeholder width dimension.
|
|
560
|
+
x = x[:, :, tf.newaxis, :]
|
|
561
|
+
|
|
562
|
+
y = tf.nn.depthwise_conv2d(
|
|
563
|
+
x,
|
|
564
|
+
sinc_filter,
|
|
565
|
+
# tf.nn.depthwise_conv2d requires equal strides in both dimensions.
|
|
566
|
+
strides=[1, self._strides, self._strides, 1],
|
|
567
|
+
# We apply padding outside of Keras.
|
|
568
|
+
padding='VALID',
|
|
569
|
+
)
|
|
570
|
+
y.shape.assert_is_compatible_with([None, None, 1, channels])
|
|
571
|
+
# Remove the placeholder width dimension.
|
|
572
|
+
return tf.squeeze(y, 2)
|
|
573
|
+
|
|
574
|
+
def get_output_shape(
|
|
575
|
+
self,
|
|
576
|
+
input_shape: tf.TensorShape,
|
|
577
|
+
constants: Optional[types.Constants] = None,
|
|
578
|
+
) -> tf.TensorShape:
|
|
579
|
+
if input_shape.rank != 1:
|
|
580
|
+
raise ValueError(
|
|
581
|
+
'SincFilter1D requires rank 3 input got: %s'
|
|
582
|
+
% tf.TensorShape([None, None]).concatenate(input_shape)
|
|
583
|
+
)
|
|
584
|
+
return input_shape
|
|
585
|
+
|
|
586
|
+
|
|
587
|
+
class DepthwiseConv1D(BaseConv1D):
|
|
588
|
+
"""A 1D depthwise convolution. Supports strided and dilated convolution."""
|
|
589
|
+
|
|
590
|
+
@classmethod
|
|
591
|
+
def _default_name(cls):
|
|
592
|
+
"""The default module name for this class."""
|
|
593
|
+
return 'depthwise_conv1d'
|
|
594
|
+
|
|
595
|
+
def __init__(
|
|
596
|
+
self,
|
|
597
|
+
kernel_size: int,
|
|
598
|
+
strides: int = 1,
|
|
599
|
+
depth_multiplier: int = 1,
|
|
600
|
+
dilation_rate: int = 1,
|
|
601
|
+
activation=None,
|
|
602
|
+
use_bias: bool = True,
|
|
603
|
+
depthwise_initializer='glorot_uniform',
|
|
604
|
+
bias_initializer='zeros',
|
|
605
|
+
depthwise_regularizer=None,
|
|
606
|
+
bias_regularizer=None,
|
|
607
|
+
activity_regularizer=None,
|
|
608
|
+
depthwise_constraint=None,
|
|
609
|
+
bias_constraint=None,
|
|
610
|
+
trainable: bool = True,
|
|
611
|
+
padding: str = 'causal',
|
|
612
|
+
name: Optional[str] = None,
|
|
613
|
+
):
|
|
614
|
+
super().__init__(kernel_size, strides, dilation_rate, padding, name=name)
|
|
615
|
+
self._depth_multiplier = depth_multiplier
|
|
616
|
+
with self.name_scope as name_scope:
|
|
617
|
+
self._depthwise_2d_layer = tf.keras.layers.DepthwiseConv2D(
|
|
618
|
+
(1, kernel_size),
|
|
619
|
+
# tf.nn.depthwise_conv2d requires equal strides in both dimensions.
|
|
620
|
+
strides=(strides, strides),
|
|
621
|
+
# We apply padding outside of Keras.
|
|
622
|
+
padding='valid',
|
|
623
|
+
depth_multiplier=depth_multiplier,
|
|
624
|
+
data_format='channels_last',
|
|
625
|
+
dilation_rate=(1, dilation_rate),
|
|
626
|
+
activation=activation,
|
|
627
|
+
use_bias=use_bias,
|
|
628
|
+
depthwise_initializer=depthwise_initializer,
|
|
629
|
+
bias_initializer=bias_initializer,
|
|
630
|
+
depthwise_regularizer=depthwise_regularizer,
|
|
631
|
+
bias_regularizer=bias_regularizer,
|
|
632
|
+
activity_regularizer=activity_regularizer,
|
|
633
|
+
depthwise_constraint=depthwise_constraint,
|
|
634
|
+
bias_constraint=bias_constraint,
|
|
635
|
+
trainable=trainable,
|
|
636
|
+
name=name_scope,
|
|
637
|
+
)
|
|
638
|
+
|
|
639
|
+
def _layer(self, values):
|
|
640
|
+
values = tf.expand_dims(values, 1)
|
|
641
|
+
values = self._depthwise_2d_layer(values)
|
|
642
|
+
return tf.squeeze(values, 1)
|
|
643
|
+
|
|
644
|
+
def get_output_shape(
|
|
645
|
+
self,
|
|
646
|
+
input_shape: tf.TensorShape,
|
|
647
|
+
constants: Optional[types.Constants] = None,
|
|
648
|
+
) -> tf.TensorShape:
|
|
649
|
+
if input_shape.rank != 1:
|
|
650
|
+
raise ValueError(
|
|
651
|
+
'DepthwiseConv1D requires rank 3 input got: %s'
|
|
652
|
+
% tf.TensorShape([None, None]).concatenate(input_shape)
|
|
653
|
+
)
|
|
654
|
+
return tf.TensorShape([input_shape.dims[0].value * self._depth_multiplier])
|
|
655
|
+
|
|
656
|
+
|
|
657
|
+
class _NormalizedDepthwiseConv1D(tf.keras.layers.Conv2D):
|
|
658
|
+
"""Normalized depthwise 1D convolution implemented as a Conv2D.
|
|
659
|
+
|
|
660
|
+
The height dimension is assumed to be one and the width is the dimension to
|
|
661
|
+
normalize.
|
|
662
|
+
"""
|
|
663
|
+
|
|
664
|
+
def __init__(
|
|
665
|
+
self,
|
|
666
|
+
kernel_size,
|
|
667
|
+
strides=(1, 1),
|
|
668
|
+
padding='valid',
|
|
669
|
+
depth_multiplier=1,
|
|
670
|
+
data_format=None,
|
|
671
|
+
dilation_rate=(1, 1),
|
|
672
|
+
activation=None,
|
|
673
|
+
use_bias=True,
|
|
674
|
+
depthwise_initializer='glorot_uniform',
|
|
675
|
+
bias_initializer='zeros',
|
|
676
|
+
depthwise_regularizer=None,
|
|
677
|
+
bias_regularizer=None,
|
|
678
|
+
activity_regularizer=None,
|
|
679
|
+
depthwise_constraint=None,
|
|
680
|
+
bias_constraint=None,
|
|
681
|
+
num_heads: Optional[int] = None,
|
|
682
|
+
depthwise_dropconnect_rate: float = 0.0,
|
|
683
|
+
**kwargs,
|
|
684
|
+
):
|
|
685
|
+
super().__init__(
|
|
686
|
+
filters=None,
|
|
687
|
+
kernel_size=kernel_size,
|
|
688
|
+
strides=strides,
|
|
689
|
+
padding=padding,
|
|
690
|
+
data_format=data_format,
|
|
691
|
+
dilation_rate=dilation_rate,
|
|
692
|
+
activation=activation,
|
|
693
|
+
use_bias=use_bias,
|
|
694
|
+
bias_regularizer=bias_regularizer,
|
|
695
|
+
activity_regularizer=activity_regularizer,
|
|
696
|
+
bias_constraint=bias_constraint,
|
|
697
|
+
**kwargs,
|
|
698
|
+
)
|
|
699
|
+
if self.kernel_size[0] != 1:
|
|
700
|
+
raise ValueError(
|
|
701
|
+
f'Expected kernel height to be one. Got: {self.kernel_size[0]}'
|
|
702
|
+
)
|
|
703
|
+
self.depth_multiplier = depth_multiplier
|
|
704
|
+
self.depthwise_initializer = tf.keras.initializers.get(
|
|
705
|
+
depthwise_initializer
|
|
706
|
+
)
|
|
707
|
+
self.depthwise_regularizer = tf.keras.regularizers.get(
|
|
708
|
+
depthwise_regularizer
|
|
709
|
+
)
|
|
710
|
+
self.depthwise_constraint = tf.keras.constraints.get(depthwise_constraint)
|
|
711
|
+
self.depthwise_dropconnect = tf.keras.layers.Dropout(
|
|
712
|
+
depthwise_dropconnect_rate
|
|
713
|
+
)
|
|
714
|
+
self.bias_initializer = tf.keras.initializers.get(bias_initializer)
|
|
715
|
+
self.num_heads = num_heads
|
|
716
|
+
|
|
717
|
+
def build(self, input_shape):
|
|
718
|
+
if len(input_shape) < 4:
|
|
719
|
+
raise ValueError(
|
|
720
|
+
(
|
|
721
|
+
'Inputs to `NormalizedDepthwiseConv2D` should have rank 4. '
|
|
722
|
+
'Received input shape:'
|
|
723
|
+
),
|
|
724
|
+
str(input_shape),
|
|
725
|
+
)
|
|
726
|
+
input_shape = tf.TensorShape(input_shape)
|
|
727
|
+
channel_axis = self._get_channel_axis()
|
|
728
|
+
if input_shape.dims[channel_axis].value is None:
|
|
729
|
+
raise ValueError(
|
|
730
|
+
'The channel dimension of the inputs to '
|
|
731
|
+
'`DepthwiseConv2D` '
|
|
732
|
+
'should be defined. Found `None`.'
|
|
733
|
+
)
|
|
734
|
+
input_dim = int(input_shape[channel_axis])
|
|
735
|
+
|
|
736
|
+
if self.num_heads is not None and input_dim % self.num_heads != 0:
|
|
737
|
+
raise ValueError(
|
|
738
|
+
'Input channels (%d) must be divisible by num_heads (%d).'
|
|
739
|
+
% (input_dim, self.num_heads)
|
|
740
|
+
)
|
|
741
|
+
depthwise_kernel_shape = (
|
|
742
|
+
self.kernel_size[0],
|
|
743
|
+
self.kernel_size[1],
|
|
744
|
+
self.num_heads if self.num_heads else input_dim,
|
|
745
|
+
self.depth_multiplier,
|
|
746
|
+
)
|
|
747
|
+
|
|
748
|
+
self.depthwise_kernel = self.add_weight(
|
|
749
|
+
shape=depthwise_kernel_shape,
|
|
750
|
+
initializer=self.depthwise_initializer,
|
|
751
|
+
name='depthwise_kernel',
|
|
752
|
+
regularizer=self.depthwise_regularizer,
|
|
753
|
+
constraint=self.depthwise_constraint,
|
|
754
|
+
)
|
|
755
|
+
|
|
756
|
+
if self.use_bias:
|
|
757
|
+
self.bias = self.add_weight(
|
|
758
|
+
shape=(input_dim * self.depth_multiplier,),
|
|
759
|
+
initializer=self.bias_initializer,
|
|
760
|
+
name='bias',
|
|
761
|
+
regularizer=self.bias_regularizer,
|
|
762
|
+
constraint=self.bias_constraint,
|
|
763
|
+
)
|
|
764
|
+
else:
|
|
765
|
+
self.bias = None
|
|
766
|
+
# Set input spec.
|
|
767
|
+
self.input_spec = tf.keras.layers.InputSpec(
|
|
768
|
+
ndim=4, axes={channel_axis: input_dim}
|
|
769
|
+
)
|
|
770
|
+
self.built = True
|
|
771
|
+
|
|
772
|
+
def call(self, inputs, training=None):
|
|
773
|
+
depthwise_kernel = tf.nn.softmax(self.depthwise_kernel, axis=1)
|
|
774
|
+
|
|
775
|
+
depthwise_kernel = self.depthwise_dropconnect(
|
|
776
|
+
depthwise_kernel, training=training
|
|
777
|
+
)
|
|
778
|
+
|
|
779
|
+
# TODO(rryan): Benchmark reshaping inputs to
|
|
780
|
+
# [b * channels / num_heads, t, num_heads, channels]
|
|
781
|
+
if self.num_heads:
|
|
782
|
+
input_dim = int(inputs.shape[self._get_channel_axis()])
|
|
783
|
+
depthwise_kernel = tf.tile(
|
|
784
|
+
depthwise_kernel, [1, 1, input_dim // self.num_heads, 1]
|
|
785
|
+
)
|
|
786
|
+
|
|
787
|
+
# We could apply DropConnect after tiling, but this is not what the fairseq
|
|
788
|
+
# implementation does.
|
|
789
|
+
outputs = tf.keras.backend.depthwise_conv2d(
|
|
790
|
+
inputs,
|
|
791
|
+
depthwise_kernel,
|
|
792
|
+
strides=self.strides,
|
|
793
|
+
padding=self.padding,
|
|
794
|
+
dilation_rate=self.dilation_rate,
|
|
795
|
+
data_format=self.data_format,
|
|
796
|
+
)
|
|
797
|
+
|
|
798
|
+
if self.use_bias:
|
|
799
|
+
outputs = tf.keras.backend.bias_add(
|
|
800
|
+
outputs, self.bias, data_format=self.data_format
|
|
801
|
+
)
|
|
802
|
+
|
|
803
|
+
if self.activation is not None:
|
|
804
|
+
return self.activation(outputs)
|
|
805
|
+
|
|
806
|
+
return outputs
|
|
807
|
+
|
|
808
|
+
@tf_keras.src.utils.tf_utils.shape_type_conversion
|
|
809
|
+
def compute_output_shape(self, input_shape):
|
|
810
|
+
if self.data_format == 'channels_first':
|
|
811
|
+
rows = input_shape[2]
|
|
812
|
+
cols = input_shape[3]
|
|
813
|
+
out_filters = input_shape[1] * self.depth_multiplier
|
|
814
|
+
elif self.data_format == 'channels_last':
|
|
815
|
+
rows = input_shape[1]
|
|
816
|
+
cols = input_shape[2]
|
|
817
|
+
out_filters = input_shape[3] * self.depth_multiplier
|
|
818
|
+
|
|
819
|
+
rows = tf_keras.src.utils.conv_utils.conv_output_length(
|
|
820
|
+
rows,
|
|
821
|
+
self.kernel_size[0],
|
|
822
|
+
self.padding,
|
|
823
|
+
self.strides[0],
|
|
824
|
+
self.dilation_rate[0],
|
|
825
|
+
)
|
|
826
|
+
cols = tf_keras.src.utils.conv_utils.conv_output_length(
|
|
827
|
+
cols,
|
|
828
|
+
self.kernel_size[1],
|
|
829
|
+
self.padding,
|
|
830
|
+
self.strides[1],
|
|
831
|
+
self.dilation_rate[1],
|
|
832
|
+
)
|
|
833
|
+
if self.data_format == 'channels_first':
|
|
834
|
+
return (input_shape[0], out_filters, rows, cols)
|
|
835
|
+
elif self.data_format == 'channels_last':
|
|
836
|
+
return (input_shape[0], rows, cols, out_filters)
|
|
837
|
+
|
|
838
|
+
def get_config(self):
|
|
839
|
+
config = super().get_config()
|
|
840
|
+
config.pop('filters')
|
|
841
|
+
config.pop('kernel_initializer')
|
|
842
|
+
config.pop('kernel_regularizer')
|
|
843
|
+
config.pop('kernel_constraint')
|
|
844
|
+
config['depth_multiplier'] = self.depth_multiplier
|
|
845
|
+
config['depthwise_initializer'] = tf.keras.initializers.serialize(
|
|
846
|
+
self.depthwise_initializer
|
|
847
|
+
)
|
|
848
|
+
config['depthwise_regularizer'] = tf.keras.regularizers.serialize(
|
|
849
|
+
self.depthwise_regularizer
|
|
850
|
+
)
|
|
851
|
+
config['depthwise_constraint'] = tf.keras.constraints.serialize(
|
|
852
|
+
self.depthwise_constraint
|
|
853
|
+
)
|
|
854
|
+
config['num_heads'] = self.num_heads
|
|
855
|
+
return config
|
|
856
|
+
|
|
857
|
+
|
|
858
|
+
class NormalizedDepthwiseConv1D(BaseConv1D):
|
|
859
|
+
"""A 1D normalized depthwise convolution.
|
|
860
|
+
|
|
861
|
+
Based on "Pay Less Attention with Lightweight and Dynamic Convolutions"
|
|
862
|
+
https://arxiv.org/abs/1901.10430
|
|
863
|
+
|
|
864
|
+
Like a 1D depthwise convolution but:
|
|
865
|
+
- The [kernel_size, input_channels, depthwise_multiplier] kernel weights are
|
|
866
|
+
softmax normalized along the kernel_size dimension. This is akin to an
|
|
867
|
+
attention weighted combination of the timesteps in the filter's receptive
|
|
868
|
+
field.
|
|
869
|
+
- Weight tying is supported via the num_heads parameter. If non-None, each
|
|
870
|
+
group of (input_channels // num_heads) input channels share the same
|
|
871
|
+
depthwise convolution weights. The total number of weights in the depthwise
|
|
872
|
+
kernel is therefore `kernel_size * num_heads * depth_multiplier`.
|
|
873
|
+
- Dropconnect regularization, dropping out the depthwise kernel after
|
|
874
|
+
softmax normalization, is supported. This is akin to forgetting certain
|
|
875
|
+
timesteps of the input for each depthwise filter.
|
|
876
|
+
|
|
877
|
+
Supports strided and dilated convolution.
|
|
878
|
+
"""
|
|
879
|
+
|
|
880
|
+
@classmethod
|
|
881
|
+
def _default_name(cls):
|
|
882
|
+
"""The default module name for this class."""
|
|
883
|
+
return 'normalized_depthwise_conv1d'
|
|
884
|
+
|
|
885
|
+
def __init__(
|
|
886
|
+
self,
|
|
887
|
+
kernel_size: int,
|
|
888
|
+
strides: int = 1,
|
|
889
|
+
depth_multiplier: int = 1,
|
|
890
|
+
dilation_rate: int = 1,
|
|
891
|
+
activation=None,
|
|
892
|
+
use_bias: bool = True,
|
|
893
|
+
depthwise_initializer='glorot_uniform',
|
|
894
|
+
bias_initializer='zeros',
|
|
895
|
+
depthwise_regularizer=None,
|
|
896
|
+
bias_regularizer=None,
|
|
897
|
+
activity_regularizer=None,
|
|
898
|
+
depthwise_constraint=None,
|
|
899
|
+
bias_constraint=None,
|
|
900
|
+
trainable: bool = True,
|
|
901
|
+
padding: str = 'causal',
|
|
902
|
+
num_heads: Optional[int] = None,
|
|
903
|
+
depthwise_dropconnect_rate: float = 0.0,
|
|
904
|
+
name: Optional[str] = None,
|
|
905
|
+
):
|
|
906
|
+
super().__init__(kernel_size, strides, dilation_rate, padding, name=name)
|
|
907
|
+
self._depth_multiplier = depth_multiplier
|
|
908
|
+
with self.name_scope as name_scope:
|
|
909
|
+
self._depthwise_2d_layer = _NormalizedDepthwiseConv1D(
|
|
910
|
+
(1, kernel_size),
|
|
911
|
+
# tf.nn.depthwise_conv2d requires equal strides in both dimensions.
|
|
912
|
+
strides=(strides, strides),
|
|
913
|
+
# We apply padding outside of Keras.
|
|
914
|
+
padding='valid',
|
|
915
|
+
depth_multiplier=depth_multiplier,
|
|
916
|
+
data_format='channels_last',
|
|
917
|
+
dilation_rate=(1, dilation_rate),
|
|
918
|
+
activation=activation,
|
|
919
|
+
use_bias=use_bias,
|
|
920
|
+
depthwise_initializer=depthwise_initializer,
|
|
921
|
+
bias_initializer=bias_initializer,
|
|
922
|
+
depthwise_regularizer=depthwise_regularizer,
|
|
923
|
+
bias_regularizer=bias_regularizer,
|
|
924
|
+
activity_regularizer=activity_regularizer,
|
|
925
|
+
depthwise_constraint=depthwise_constraint,
|
|
926
|
+
bias_constraint=bias_constraint,
|
|
927
|
+
trainable=trainable,
|
|
928
|
+
num_heads=num_heads,
|
|
929
|
+
depthwise_dropconnect_rate=depthwise_dropconnect_rate,
|
|
930
|
+
name=name_scope,
|
|
931
|
+
)
|
|
932
|
+
|
|
933
|
+
def _layer(self, values):
|
|
934
|
+
values = tf.expand_dims(values, 1)
|
|
935
|
+
values = self._depthwise_2d_layer(values)
|
|
936
|
+
return tf.squeeze(values, 1)
|
|
937
|
+
|
|
938
|
+
def get_output_shape(
|
|
939
|
+
self,
|
|
940
|
+
input_shape: tf.TensorShape,
|
|
941
|
+
constants: Optional[types.Constants] = None,
|
|
942
|
+
) -> tf.TensorShape:
|
|
943
|
+
if input_shape.rank != 1:
|
|
944
|
+
raise ValueError(
|
|
945
|
+
'NormalizedDepthwiseConv1D requires rank 3 input got: %s'
|
|
946
|
+
% tf.TensorShape([None, None]).concatenate(input_shape)
|
|
947
|
+
)
|
|
948
|
+
return tf.TensorShape([input_shape.dims[0].value * self._depth_multiplier])
|
|
949
|
+
|
|
950
|
+
|
|
951
|
+
class SeparableConv1D(BaseConv1D):
|
|
952
|
+
"""A 1D separable convolution. Supports strided and dilated convolution."""
|
|
953
|
+
|
|
954
|
+
@classmethod
|
|
955
|
+
def _default_name(cls):
|
|
956
|
+
"""The default module name for this class."""
|
|
957
|
+
return 'separable_conv1d'
|
|
958
|
+
|
|
959
|
+
def __init__(
|
|
960
|
+
self,
|
|
961
|
+
filters: int,
|
|
962
|
+
kernel_size: int,
|
|
963
|
+
strides: int = 1,
|
|
964
|
+
dilation_rate: int = 1,
|
|
965
|
+
depth_multiplier: int = 1,
|
|
966
|
+
activation=None,
|
|
967
|
+
use_bias: bool = True,
|
|
968
|
+
depthwise_initializer='glorot_uniform',
|
|
969
|
+
pointwise_initializer='glorot_uniform',
|
|
970
|
+
bias_initializer='zeros',
|
|
971
|
+
depthwise_regularizer=None,
|
|
972
|
+
pointwise_regularizer=None,
|
|
973
|
+
bias_regularizer=None,
|
|
974
|
+
activity_regularizer=None,
|
|
975
|
+
depthwise_constraint=None,
|
|
976
|
+
pointwise_constraint=None,
|
|
977
|
+
bias_constraint=None,
|
|
978
|
+
trainable: bool = True,
|
|
979
|
+
padding: str = 'causal',
|
|
980
|
+
name: Optional[str] = None,
|
|
981
|
+
):
|
|
982
|
+
super().__init__(kernel_size, strides, dilation_rate, padding, name=name)
|
|
983
|
+
self._filters = filters
|
|
984
|
+
with self.name_scope as name_scope:
|
|
985
|
+
self._layer = tf.keras.layers.SeparableConv1D(
|
|
986
|
+
filters,
|
|
987
|
+
kernel_size,
|
|
988
|
+
strides=strides,
|
|
989
|
+
# We apply padding outside of Keras.
|
|
990
|
+
padding='valid',
|
|
991
|
+
data_format='channels_last',
|
|
992
|
+
dilation_rate=dilation_rate,
|
|
993
|
+
depth_multiplier=depth_multiplier,
|
|
994
|
+
activation=activation,
|
|
995
|
+
use_bias=use_bias,
|
|
996
|
+
depthwise_initializer=depthwise_initializer,
|
|
997
|
+
pointwise_initializer=pointwise_initializer,
|
|
998
|
+
bias_initializer=bias_initializer,
|
|
999
|
+
depthwise_regularizer=depthwise_regularizer,
|
|
1000
|
+
pointwise_regularizer=pointwise_regularizer,
|
|
1001
|
+
bias_regularizer=bias_regularizer,
|
|
1002
|
+
activity_regularizer=activity_regularizer,
|
|
1003
|
+
depthwise_constraint=depthwise_constraint,
|
|
1004
|
+
pointwise_constraint=pointwise_constraint,
|
|
1005
|
+
bias_constraint=bias_constraint,
|
|
1006
|
+
trainable=trainable,
|
|
1007
|
+
name=name_scope,
|
|
1008
|
+
)
|
|
1009
|
+
|
|
1010
|
+
def get_output_shape(
|
|
1011
|
+
self,
|
|
1012
|
+
input_shape: tf.TensorShape,
|
|
1013
|
+
constants: Optional[types.Constants] = None,
|
|
1014
|
+
) -> tf.TensorShape:
|
|
1015
|
+
if input_shape.rank != 1:
|
|
1016
|
+
raise ValueError(
|
|
1017
|
+
'SeparableConv1D requires rank 3 input got: %s'
|
|
1018
|
+
% tf.TensorShape([None, None]).concatenate(input_shape)
|
|
1019
|
+
)
|
|
1020
|
+
return tf.TensorShape([self._filters])
|
|
1021
|
+
|
|
1022
|
+
|
|
1023
|
+
class Conv1DTranspose(types.SequenceLayer):
|
|
1024
|
+
"""A 1D transpose convolution layer."""
|
|
1025
|
+
|
|
1026
|
+
@classmethod
|
|
1027
|
+
def _default_name(cls):
|
|
1028
|
+
"""The default module name for this class."""
|
|
1029
|
+
return 'conv1d_transpose'
|
|
1030
|
+
|
|
1031
|
+
def __init__(
|
|
1032
|
+
self,
|
|
1033
|
+
filters: int,
|
|
1034
|
+
kernel_size: int,
|
|
1035
|
+
strides: int = 1,
|
|
1036
|
+
activation=None,
|
|
1037
|
+
use_bias: bool = True,
|
|
1038
|
+
kernel_initializer='glorot_uniform',
|
|
1039
|
+
bias_initializer='zeros',
|
|
1040
|
+
kernel_regularizer=None,
|
|
1041
|
+
bias_regularizer=None,
|
|
1042
|
+
activity_regularizer=None,
|
|
1043
|
+
kernel_constraint=None,
|
|
1044
|
+
bias_constraint=None,
|
|
1045
|
+
trainable: bool = True,
|
|
1046
|
+
padding: str = 'causal',
|
|
1047
|
+
weight_norm: bool = False,
|
|
1048
|
+
name: Optional[str] = None,
|
|
1049
|
+
):
|
|
1050
|
+
super().__init__(name=name)
|
|
1051
|
+
self._filters = filters
|
|
1052
|
+
self._kernel_size = kernel_size
|
|
1053
|
+
self._strides = strides
|
|
1054
|
+
self._padding = types.validate_padding(padding)
|
|
1055
|
+
if self._padding == 'causal':
|
|
1056
|
+
self._buffer_width = max(0, self._kernel_size - self._strides)
|
|
1057
|
+
else:
|
|
1058
|
+
self._buffer_width = 0
|
|
1059
|
+
# TODO(rryan): Add support for dilated transpose convolution (Keras
|
|
1060
|
+
# supports it).
|
|
1061
|
+
# We apply the activation ourselves outside of the layer.
|
|
1062
|
+
self._activation = activation
|
|
1063
|
+
with self.name_scope as name_scope:
|
|
1064
|
+
# To support streaming of transpose convolutions, we apply bias and
|
|
1065
|
+
# activation outside of the model, but use the bias in the
|
|
1066
|
+
# Conv2DTranspose layer. Since we might apply weight normalization, we
|
|
1067
|
+
# keep a reference to the original layer so we can disable bias when we
|
|
1068
|
+
# call it.
|
|
1069
|
+
self._inner_layer = self._layer = tf.keras.layers.Conv2DTranspose(
|
|
1070
|
+
filters=filters,
|
|
1071
|
+
kernel_size=(kernel_size, 1),
|
|
1072
|
+
strides=(strides, 1),
|
|
1073
|
+
padding='same' if self._padding == 'same' else 'valid',
|
|
1074
|
+
data_format='channels_last',
|
|
1075
|
+
activation=None,
|
|
1076
|
+
use_bias=use_bias,
|
|
1077
|
+
kernel_initializer=kernel_initializer,
|
|
1078
|
+
bias_initializer=bias_initializer,
|
|
1079
|
+
kernel_regularizer=kernel_regularizer,
|
|
1080
|
+
bias_regularizer=bias_regularizer,
|
|
1081
|
+
activity_regularizer=activity_regularizer,
|
|
1082
|
+
kernel_constraint=kernel_constraint,
|
|
1083
|
+
bias_constraint=bias_constraint,
|
|
1084
|
+
trainable=trainable,
|
|
1085
|
+
name=name_scope,
|
|
1086
|
+
)
|
|
1087
|
+
if weight_norm:
|
|
1088
|
+
self._layer = utils.WeightNorm(self._layer, name='weight_norm')
|
|
1089
|
+
|
|
1090
|
+
@property
|
|
1091
|
+
def supports_step(self) -> bool:
|
|
1092
|
+
return self._padding == 'causal'
|
|
1093
|
+
|
|
1094
|
+
def build(self, input_shape):
|
|
1095
|
+
if not self._layer.built:
|
|
1096
|
+
self._layer.build(
|
|
1097
|
+
input_shape[:2].concatenate(1).concatenate(input_shape[2:])
|
|
1098
|
+
)
|
|
1099
|
+
|
|
1100
|
+
def get_initial_state(
|
|
1101
|
+
self, x: types.Sequence, constants: Optional[types.Constants] = None
|
|
1102
|
+
) -> types.State:
|
|
1103
|
+
if self._buffer_width > 0:
|
|
1104
|
+
batch_size = utils.smart_dimension_size(x.values, 0)
|
|
1105
|
+
return types.Sequence(
|
|
1106
|
+
tf.zeros(
|
|
1107
|
+
(batch_size, self._buffer_width, self._filters),
|
|
1108
|
+
dtype=x.values.dtype,
|
|
1109
|
+
),
|
|
1110
|
+
tf.ones((batch_size, self._buffer_width), dtype=x.mask.dtype),
|
|
1111
|
+
)
|
|
1112
|
+
else:
|
|
1113
|
+
return ()
|
|
1114
|
+
|
|
1115
|
+
@property
|
|
1116
|
+
def block_size(self) -> int:
|
|
1117
|
+
return 1
|
|
1118
|
+
|
|
1119
|
+
@property
|
|
1120
|
+
def output_ratio(self) -> fractions.Fraction:
|
|
1121
|
+
return fractions.Fraction(self._strides)
|
|
1122
|
+
|
|
1123
|
+
def get_output_shape(
|
|
1124
|
+
self,
|
|
1125
|
+
input_shape: tf.TensorShape,
|
|
1126
|
+
constants: Optional[types.Constants] = None,
|
|
1127
|
+
) -> tf.TensorShape:
|
|
1128
|
+
if input_shape.rank != 1:
|
|
1129
|
+
raise ValueError(
|
|
1130
|
+
'Conv1DTranspose requires rank 3 input got: %s'
|
|
1131
|
+
% tf.TensorShape([None, None]).concatenate(input_shape)
|
|
1132
|
+
)
|
|
1133
|
+
return tf.TensorShape([self._filters])
|
|
1134
|
+
|
|
1135
|
+
@tf.Module.with_name_scope
|
|
1136
|
+
def step(
|
|
1137
|
+
self,
|
|
1138
|
+
x: types.Sequence,
|
|
1139
|
+
state: types.State,
|
|
1140
|
+
training: bool,
|
|
1141
|
+
constants: Optional[types.Constants] = None,
|
|
1142
|
+
) -> Tuple[types.Sequence, types.State]:
|
|
1143
|
+
if not self.supports_step:
|
|
1144
|
+
raise ValueError(f'{self} does not support stepping.')
|
|
1145
|
+
|
|
1146
|
+
self.build(x.values.shape)
|
|
1147
|
+
# Our strategy for running Conv2DTranspose step-wise involves buffering the
|
|
1148
|
+
# output of the layer and overlap-adding that output with future timesteps.
|
|
1149
|
+
# Because of this, we have to delay bias and activation until we have
|
|
1150
|
+
# performed the overlap add.
|
|
1151
|
+
use_bias = self._inner_layer.use_bias
|
|
1152
|
+
self._inner_layer.use_bias = False
|
|
1153
|
+
values = tf.squeeze(self._layer(x.values[:, :, tf.newaxis, :]), 2)
|
|
1154
|
+
self._inner_layer.use_bias = use_bias
|
|
1155
|
+
mask = _compute_conv_transpose_mask(
|
|
1156
|
+
x.mask, self._kernel_size, self._strides, self._padding
|
|
1157
|
+
)
|
|
1158
|
+
|
|
1159
|
+
# If kernel_size > stride, mix the state into the output and compute
|
|
1160
|
+
# state for the next timestep.
|
|
1161
|
+
if self._buffer_width > 0:
|
|
1162
|
+
time = utils.smart_dimension_size(x.values, 1)
|
|
1163
|
+
output_time = _compute_conv_transpose_output_length(
|
|
1164
|
+
time,
|
|
1165
|
+
self._kernel_size,
|
|
1166
|
+
self._strides,
|
|
1167
|
+
dilation_rate=1,
|
|
1168
|
+
padding=self._padding,
|
|
1169
|
+
)
|
|
1170
|
+
|
|
1171
|
+
# Pad the state to extend it to the length of the layer output.
|
|
1172
|
+
# output_time is at least kernel_size and buffer_width is at most
|
|
1173
|
+
# kernel_size - 1, so output_time - buffer_width is positive.
|
|
1174
|
+
state = state.pad_time(0, output_time - self._buffer_width, valid=True)
|
|
1175
|
+
values += state.values
|
|
1176
|
+
mask *= state.mask
|
|
1177
|
+
|
|
1178
|
+
# Stride samples are "ready" for output after one timestep, so the number
|
|
1179
|
+
# of output samples for the block is stride * time.
|
|
1180
|
+
output_samples = self._strides * time
|
|
1181
|
+
|
|
1182
|
+
# We need to store output_time - output_samples samples for the next step,
|
|
1183
|
+
# since their value depends on future inputs.
|
|
1184
|
+
state_samples = output_time - output_samples
|
|
1185
|
+
values, state_values = tf.split(
|
|
1186
|
+
values, [output_samples, state_samples], axis=1
|
|
1187
|
+
)
|
|
1188
|
+
mask, state_mask = tf.split(mask, [output_samples, state_samples], axis=1)
|
|
1189
|
+
state = types.Sequence(state_values, state_mask)
|
|
1190
|
+
|
|
1191
|
+
if use_bias:
|
|
1192
|
+
values = tf.nn.bias_add(values, self._inner_layer.bias, data_format='NWC')
|
|
1193
|
+
if self._activation:
|
|
1194
|
+
values = self._activation(values)
|
|
1195
|
+
return types.Sequence(values, mask).mask_invalid(), state
|
|
1196
|
+
|
|
1197
|
+
@tf.Module.with_name_scope
|
|
1198
|
+
def layer(
|
|
1199
|
+
self,
|
|
1200
|
+
x: types.Sequence,
|
|
1201
|
+
training: bool,
|
|
1202
|
+
initial_state: Optional[types.State] = None,
|
|
1203
|
+
constants: Optional[types.Constants] = None,
|
|
1204
|
+
) -> types.Sequence:
|
|
1205
|
+
self.build(x.values.shape)
|
|
1206
|
+
values = tf.squeeze(self._layer(x.values[:, :, tf.newaxis, :]), 2)
|
|
1207
|
+
mask = _compute_conv_transpose_mask(
|
|
1208
|
+
x.mask, self._kernel_size, self._strides, self._padding
|
|
1209
|
+
)
|
|
1210
|
+
|
|
1211
|
+
if self._activation:
|
|
1212
|
+
values = self._activation(values)
|
|
1213
|
+
|
|
1214
|
+
# Trim the last frame_length - stride samples since we don't produce these
|
|
1215
|
+
# in step mode (we can only produce stride samples at a time in step mode,
|
|
1216
|
+
# so we can't produce the final kernel_size - stride samples).
|
|
1217
|
+
x = types.Sequence(values, mask)
|
|
1218
|
+
if self._padding == 'causal':
|
|
1219
|
+
trim = max(self._kernel_size - self._strides, 0)
|
|
1220
|
+
if trim:
|
|
1221
|
+
x = x[:, :-trim]
|
|
1222
|
+
return x.mask_invalid()
|
|
1223
|
+
|
|
1224
|
+
|
|
1225
|
+
class SincFilter1DTranspose(types.SequenceLayer):
|
|
1226
|
+
"""Applies a windowed-sinc filter as a DepthwiseConv1DTranpsose."""
|
|
1227
|
+
|
|
1228
|
+
@classmethod
|
|
1229
|
+
def _default_name(cls):
|
|
1230
|
+
"""The default module name for this class."""
|
|
1231
|
+
return 'sinc_filter1d_transpose'
|
|
1232
|
+
|
|
1233
|
+
def __init__(
|
|
1234
|
+
self,
|
|
1235
|
+
kernel_size: int,
|
|
1236
|
+
strides: int = 1,
|
|
1237
|
+
cutoff: float = 0.5,
|
|
1238
|
+
kaiser_beta: float = 6.0,
|
|
1239
|
+
padding: str = 'causal',
|
|
1240
|
+
name: Optional[str] = None,
|
|
1241
|
+
):
|
|
1242
|
+
super().__init__(name=name)
|
|
1243
|
+
self._kernel_size = kernel_size
|
|
1244
|
+
self._strides = strides
|
|
1245
|
+
self._padding = types.validate_padding(padding)
|
|
1246
|
+
if self._padding == 'causal':
|
|
1247
|
+
self._buffer_width = max(0, self._kernel_size - self._strides)
|
|
1248
|
+
else:
|
|
1249
|
+
self._buffer_width = 0
|
|
1250
|
+
self._filter = _kaiser_sinc_filter1d(cutoff, kaiser_beta, kernel_size)
|
|
1251
|
+
|
|
1252
|
+
@property
|
|
1253
|
+
def supports_step(self) -> bool:
|
|
1254
|
+
return self._padding == 'causal'
|
|
1255
|
+
|
|
1256
|
+
def get_initial_state(
|
|
1257
|
+
self, x: types.Sequence, constants: Optional[types.Constants] = None
|
|
1258
|
+
) -> types.State:
|
|
1259
|
+
if self._buffer_width > 0:
|
|
1260
|
+
batch_size, channels = utils.smart_dimension_size(x.values, [0, 2])
|
|
1261
|
+
return types.Sequence(
|
|
1262
|
+
tf.zeros(
|
|
1263
|
+
(batch_size, self._buffer_width, channels),
|
|
1264
|
+
dtype=x.values.dtype,
|
|
1265
|
+
),
|
|
1266
|
+
tf.ones((batch_size, self._buffer_width), dtype=x.mask.dtype),
|
|
1267
|
+
)
|
|
1268
|
+
else:
|
|
1269
|
+
return ()
|
|
1270
|
+
|
|
1271
|
+
@property
|
|
1272
|
+
def block_size(self) -> int:
|
|
1273
|
+
return 1
|
|
1274
|
+
|
|
1275
|
+
@property
|
|
1276
|
+
def output_ratio(self) -> fractions.Fraction:
|
|
1277
|
+
return fractions.Fraction(self._strides)
|
|
1278
|
+
|
|
1279
|
+
def get_output_shape(
|
|
1280
|
+
self,
|
|
1281
|
+
input_shape: tf.TensorShape,
|
|
1282
|
+
constants: Optional[types.Constants] = None,
|
|
1283
|
+
) -> tf.TensorShape:
|
|
1284
|
+
if input_shape.rank != 1:
|
|
1285
|
+
raise ValueError(
|
|
1286
|
+
'SincFilter1DTranspose requires rank 3 input got: %s'
|
|
1287
|
+
% tf.TensorShape([None, None]).concatenate(input_shape)
|
|
1288
|
+
)
|
|
1289
|
+
return input_shape
|
|
1290
|
+
|
|
1291
|
+
def _layer(self, x: tf.Tensor) -> tf.Tensor:
|
|
1292
|
+
if x.shape.rank != 3:
|
|
1293
|
+
raise ValueError(f'Expected rank 3 inputs. Got: {x.shape}')
|
|
1294
|
+
batch, time, channels = utils.smart_dimension_size(x)
|
|
1295
|
+
assert isinstance(channels, int)
|
|
1296
|
+
|
|
1297
|
+
# Filter shape is [height, width=1, in_channels, channel_multiplier=1].
|
|
1298
|
+
sinc_filter = tf.tile(
|
|
1299
|
+
self._filter[:, tf.newaxis, tf.newaxis, tf.newaxis], [1, 1, channels, 1]
|
|
1300
|
+
)
|
|
1301
|
+
|
|
1302
|
+
# Insert a placeholder width dimension.
|
|
1303
|
+
x = x[:, :, tf.newaxis, :]
|
|
1304
|
+
|
|
1305
|
+
output_time = _compute_conv_transpose_output_length(
|
|
1306
|
+
time,
|
|
1307
|
+
kernel_size=self._kernel_size,
|
|
1308
|
+
stride=self._strides,
|
|
1309
|
+
dilation_rate=1,
|
|
1310
|
+
padding=self._padding,
|
|
1311
|
+
)
|
|
1312
|
+
input_sizes = [batch, output_time, 1, channels]
|
|
1313
|
+
|
|
1314
|
+
# Why on earth doesn't TensorFlow have a depthwise_conv1d_transpose?
|
|
1315
|
+
y = tf.nn.depthwise_conv2d_backprop_input(
|
|
1316
|
+
input_sizes=input_sizes,
|
|
1317
|
+
filter=sinc_filter,
|
|
1318
|
+
out_backprop=x,
|
|
1319
|
+
strides=[1, self._strides, self._strides, 1],
|
|
1320
|
+
padding='SAME' if self._padding == 'same' else 'VALID',
|
|
1321
|
+
)
|
|
1322
|
+
|
|
1323
|
+
y.shape.assert_is_compatible_with([None, None, 1, channels])
|
|
1324
|
+
return tf.squeeze(y, 2)
|
|
1325
|
+
|
|
1326
|
+
@tf.Module.with_name_scope
|
|
1327
|
+
def step(
|
|
1328
|
+
self,
|
|
1329
|
+
x: types.Sequence,
|
|
1330
|
+
state: types.State,
|
|
1331
|
+
training: bool,
|
|
1332
|
+
constants: Optional[types.Constants] = None,
|
|
1333
|
+
) -> Tuple[types.Sequence, types.State]:
|
|
1334
|
+
if not self.supports_step:
|
|
1335
|
+
raise ValueError(f'{self} does not support stepping.')
|
|
1336
|
+
values = self._layer(x.values)
|
|
1337
|
+
mask = _compute_conv_transpose_mask(
|
|
1338
|
+
x.mask, self._kernel_size, self._strides, self._padding
|
|
1339
|
+
)
|
|
1340
|
+
|
|
1341
|
+
# If kernel_size > stride, mix the state into the output and compute
|
|
1342
|
+
# state for the next timestep.
|
|
1343
|
+
if self._buffer_width > 0:
|
|
1344
|
+
time = utils.smart_dimension_size(x.values, 1)
|
|
1345
|
+
output_time = _compute_conv_transpose_output_length(
|
|
1346
|
+
time,
|
|
1347
|
+
self._kernel_size,
|
|
1348
|
+
self._strides,
|
|
1349
|
+
dilation_rate=1,
|
|
1350
|
+
padding=self._padding,
|
|
1351
|
+
)
|
|
1352
|
+
|
|
1353
|
+
# Pad the state to extend it to the length of the layer output.
|
|
1354
|
+
# output_time is at least kernel_size and buffer_width is at most
|
|
1355
|
+
# kernel_size - 1, so output_time - buffer_width is positive.
|
|
1356
|
+
state = state.pad_time(0, output_time - self._buffer_width, valid=True)
|
|
1357
|
+
values += state.values
|
|
1358
|
+
mask *= state.mask
|
|
1359
|
+
|
|
1360
|
+
# Stride samples are "ready" for output after one timestep, so the number
|
|
1361
|
+
# of output samples for the block is stride * time.
|
|
1362
|
+
output_samples = self._strides * time
|
|
1363
|
+
|
|
1364
|
+
# We need to store output_time - output_samples samples for the next step,
|
|
1365
|
+
# since their value depends on future inputs.
|
|
1366
|
+
state_samples = output_time - output_samples
|
|
1367
|
+
values, state_values = tf.split(
|
|
1368
|
+
values, [output_samples, state_samples], axis=1
|
|
1369
|
+
)
|
|
1370
|
+
mask, state_mask = tf.split(mask, [output_samples, state_samples], axis=1)
|
|
1371
|
+
state = types.Sequence(state_values, state_mask)
|
|
1372
|
+
|
|
1373
|
+
return types.Sequence(values, mask).mask_invalid(), state
|
|
1374
|
+
|
|
1375
|
+
@tf.Module.with_name_scope
|
|
1376
|
+
def layer(
|
|
1377
|
+
self,
|
|
1378
|
+
x: types.Sequence,
|
|
1379
|
+
training: bool,
|
|
1380
|
+
initial_state: Optional[types.State] = None,
|
|
1381
|
+
constants: Optional[types.Constants] = None,
|
|
1382
|
+
) -> types.Sequence:
|
|
1383
|
+
values = self._layer(x.values)
|
|
1384
|
+
mask = _compute_conv_transpose_mask(
|
|
1385
|
+
x.mask, self._kernel_size, self._strides, self._padding
|
|
1386
|
+
)
|
|
1387
|
+
|
|
1388
|
+
# Trim the last frame_length - stride samples since we don't produce these
|
|
1389
|
+
# in step mode (we can only produce stride samples at a time in step mode,
|
|
1390
|
+
# so we can't produce the final kernel_size - stride samples).
|
|
1391
|
+
x = types.Sequence(values, mask)
|
|
1392
|
+
if self._padding == 'causal':
|
|
1393
|
+
trim = max(self._kernel_size - self._strides, 0)
|
|
1394
|
+
if trim:
|
|
1395
|
+
x = x[:, :-trim]
|
|
1396
|
+
return x.mask_invalid()
|
|
1397
|
+
|
|
1398
|
+
|
|
1399
|
+
class BaseConv2D(types.SequenceLayer):
|
|
1400
|
+
"""Shared base logic for Conv2D layers."""
|
|
1401
|
+
|
|
1402
|
+
def __init__(
|
|
1403
|
+
self,
|
|
1404
|
+
kernel_size: Union[int, List[int], Tuple[int, int]],
|
|
1405
|
+
strides: Union[int, List[int], Tuple[int, int]],
|
|
1406
|
+
time_padding: str,
|
|
1407
|
+
spatial_padding: str,
|
|
1408
|
+
dilation_rate: Union[int, List[int], Tuple[int, int]],
|
|
1409
|
+
name=None,
|
|
1410
|
+
):
|
|
1411
|
+
super().__init__(name=name)
|
|
1412
|
+
|
|
1413
|
+
def normalize_2tuple(
|
|
1414
|
+
x: Union[int, List[int], Tuple[int, int]]
|
|
1415
|
+
) -> Tuple[int, int]:
|
|
1416
|
+
if isinstance(x, int):
|
|
1417
|
+
return (x, x)
|
|
1418
|
+
result = tuple(x)
|
|
1419
|
+
if len(result) != 2:
|
|
1420
|
+
raise ValueError('Expected a 2-element iterable, got: %r' % x)
|
|
1421
|
+
return result
|
|
1422
|
+
|
|
1423
|
+
self._kernel_size = normalize_2tuple(kernel_size)
|
|
1424
|
+
self._strides = normalize_2tuple(strides)
|
|
1425
|
+
self._time_padding = types.validate_padding(time_padding)
|
|
1426
|
+
self._spatial_padding = types.validate_padding(spatial_padding)
|
|
1427
|
+
self._dilation_rate = normalize_2tuple(dilation_rate)
|
|
1428
|
+
|
|
1429
|
+
# (effective_kernel_size - 1) padding makes convolution fully causal.
|
|
1430
|
+
if self._time_padding == 'causal':
|
|
1431
|
+
effective_kernel_size = utils.convolution_effective_kernel_size(
|
|
1432
|
+
self._kernel_size[0], self._dilation_rate[0]
|
|
1433
|
+
)
|
|
1434
|
+
self._buffer_width = effective_kernel_size - 1
|
|
1435
|
+
else:
|
|
1436
|
+
self._buffer_width = 0
|
|
1437
|
+
|
|
1438
|
+
@property
|
|
1439
|
+
def supports_step(self) -> bool:
|
|
1440
|
+
return self._time_padding == 'causal'
|
|
1441
|
+
|
|
1442
|
+
@property
|
|
1443
|
+
def block_size(self) -> int:
|
|
1444
|
+
return self._strides[0]
|
|
1445
|
+
|
|
1446
|
+
@property
|
|
1447
|
+
def output_ratio(self) -> fractions.Fraction:
|
|
1448
|
+
return fractions.Fraction(1, self._strides[0])
|
|
1449
|
+
|
|
1450
|
+
def get_initial_state(
|
|
1451
|
+
self, x: types.Sequence, constants: Optional[types.Constants] = None
|
|
1452
|
+
) -> types.State:
|
|
1453
|
+
# Special case kernel_size 1 in time since it is stateless.
|
|
1454
|
+
if not self._buffer_width:
|
|
1455
|
+
return ()
|
|
1456
|
+
if x.values.shape.rank != 4:
|
|
1457
|
+
raise ValueError('Conv2D requires rank 4 input, got: %s' % str(x))
|
|
1458
|
+
# When executing a conv1d step-by-step, we need a buffer for tracking
|
|
1459
|
+
# the current causal convolution window.
|
|
1460
|
+
batch_size = utils.smart_dimension_size(x.values, 0)
|
|
1461
|
+
# This matches the causal padding added by `layer`.
|
|
1462
|
+
return types.Sequence(
|
|
1463
|
+
tf.zeros(
|
|
1464
|
+
(
|
|
1465
|
+
batch_size,
|
|
1466
|
+
self._buffer_width,
|
|
1467
|
+
x.values.shape.dims[2].value,
|
|
1468
|
+
x.values.shape.dims[3].value,
|
|
1469
|
+
),
|
|
1470
|
+
dtype=x.values.dtype,
|
|
1471
|
+
),
|
|
1472
|
+
tf.ones((batch_size, self._buffer_width), dtype=x.mask.dtype),
|
|
1473
|
+
)
|
|
1474
|
+
|
|
1475
|
+
def _apply_conv(
|
|
1476
|
+
self,
|
|
1477
|
+
x: tf.Tensor,
|
|
1478
|
+
explicit_padding: tuple[tuple[int, int], tuple[int, int]],
|
|
1479
|
+
) -> tf.Tensor:
|
|
1480
|
+
if (
|
|
1481
|
+
explicit_padding[0][0] != 0
|
|
1482
|
+
or explicit_padding[0][1] != 0
|
|
1483
|
+
or explicit_padding[1][0] != 0
|
|
1484
|
+
or explicit_padding[1][1] != 0
|
|
1485
|
+
):
|
|
1486
|
+
x = tf.pad(x, [(0, 0), explicit_padding[0], explicit_padding[1], (0, 0)])
|
|
1487
|
+
return self._layer(x)
|
|
1488
|
+
|
|
1489
|
+
@tf.Module.with_name_scope
|
|
1490
|
+
def step(
|
|
1491
|
+
self,
|
|
1492
|
+
x: types.Sequence,
|
|
1493
|
+
state: types.State,
|
|
1494
|
+
training: bool,
|
|
1495
|
+
constants: Optional[types.Constants] = None,
|
|
1496
|
+
) -> Tuple[types.Sequence, types.State]:
|
|
1497
|
+
if not self.supports_step:
|
|
1498
|
+
raise ValueError(f'{self} does not support stepping.')
|
|
1499
|
+
|
|
1500
|
+
# In step mode, causal padding is handled by the state that is concatenated
|
|
1501
|
+
# below.
|
|
1502
|
+
time_padding = (0, 0)
|
|
1503
|
+
spatial_padding = utils.convolution_explicit_padding(
|
|
1504
|
+
self._spatial_padding,
|
|
1505
|
+
self._kernel_size[1],
|
|
1506
|
+
self._dilation_rate[1],
|
|
1507
|
+
)
|
|
1508
|
+
|
|
1509
|
+
# Special case kernel_size 1 in time since it is stateless.
|
|
1510
|
+
if not self._buffer_width:
|
|
1511
|
+
values = self._apply_conv(x.values, (time_padding, spatial_padding))
|
|
1512
|
+
mask = compute_conv_mask(
|
|
1513
|
+
x.mask,
|
|
1514
|
+
self._kernel_size[0],
|
|
1515
|
+
self._strides[0],
|
|
1516
|
+
self._dilation_rate[0],
|
|
1517
|
+
self._time_padding,
|
|
1518
|
+
)
|
|
1519
|
+
return types.Sequence(values, mask).mask_invalid(), state
|
|
1520
|
+
|
|
1521
|
+
# Concatenate the new frames with the previous buffer_width frames.
|
|
1522
|
+
state = state.concatenate(x)
|
|
1523
|
+
|
|
1524
|
+
# Compute the output for the current timestep.
|
|
1525
|
+
values = self._apply_conv(state.values, (time_padding, spatial_padding))
|
|
1526
|
+
mask = compute_conv_mask(
|
|
1527
|
+
state.mask,
|
|
1528
|
+
self._kernel_size[0],
|
|
1529
|
+
self._strides[0],
|
|
1530
|
+
self._dilation_rate[0],
|
|
1531
|
+
self._time_padding,
|
|
1532
|
+
)
|
|
1533
|
+
|
|
1534
|
+
# Keep the trailing buffer_width samples for the next step.
|
|
1535
|
+
state = state[:, -self._buffer_width :]
|
|
1536
|
+
|
|
1537
|
+
return types.Sequence(values, mask).mask_invalid(), state
|
|
1538
|
+
|
|
1539
|
+
@tf.Module.with_name_scope
|
|
1540
|
+
def layer(
|
|
1541
|
+
self,
|
|
1542
|
+
x: types.Sequence,
|
|
1543
|
+
training: bool,
|
|
1544
|
+
initial_state: Optional[types.State] = None,
|
|
1545
|
+
constants: Optional[types.Constants] = None,
|
|
1546
|
+
) -> types.Sequence:
|
|
1547
|
+
time_padding = utils.convolution_explicit_padding(
|
|
1548
|
+
self._time_padding,
|
|
1549
|
+
self._kernel_size[0],
|
|
1550
|
+
self._dilation_rate[0],
|
|
1551
|
+
)
|
|
1552
|
+
spatial_padding = utils.convolution_explicit_padding(
|
|
1553
|
+
self._spatial_padding,
|
|
1554
|
+
self._kernel_size[1],
|
|
1555
|
+
self._dilation_rate[1],
|
|
1556
|
+
)
|
|
1557
|
+
values = self._apply_conv(x.values, (time_padding, spatial_padding))
|
|
1558
|
+
|
|
1559
|
+
# In causal mode, x.mask is padded and compute_conv_mask uses a VALID
|
|
1560
|
+
# convolution. In SAME mode, x.mask is not padded, and compute_conv_mask
|
|
1561
|
+
# uses a strided slice mask[:, ::time_stride].
|
|
1562
|
+
if self._time_padding == types.PaddingMode.CAUSAL.value:
|
|
1563
|
+
# We can't use convolutional padding here since its value is 0.0, not 1.0.
|
|
1564
|
+
mask = tf.pad(
|
|
1565
|
+
x.mask,
|
|
1566
|
+
[[0, 0], [self._buffer_width, 0]],
|
|
1567
|
+
mode='constant',
|
|
1568
|
+
constant_values=1.0,
|
|
1569
|
+
)
|
|
1570
|
+
else:
|
|
1571
|
+
mask = x.mask
|
|
1572
|
+
|
|
1573
|
+
mask = compute_conv_mask(
|
|
1574
|
+
mask,
|
|
1575
|
+
self._kernel_size[0],
|
|
1576
|
+
self._strides[0],
|
|
1577
|
+
self._dilation_rate[0],
|
|
1578
|
+
self._time_padding,
|
|
1579
|
+
)
|
|
1580
|
+
return types.Sequence(values, mask).mask_invalid()
|
|
1581
|
+
|
|
1582
|
+
|
|
1583
|
+
class Conv2D(BaseConv2D):
|
|
1584
|
+
"""A 2D convolution layer.
|
|
1585
|
+
|
|
1586
|
+
Supports both strided and dilated convolution.
|
|
1587
|
+
|
|
1588
|
+
The first spatial dimension (time) is processed causally, but the second
|
|
1589
|
+
spatial dimension is non-causal (i.e. 'valid' or 'same' convolution).
|
|
1590
|
+
"""
|
|
1591
|
+
|
|
1592
|
+
@classmethod
|
|
1593
|
+
def _default_name(cls):
|
|
1594
|
+
"""The default module name for this class."""
|
|
1595
|
+
return 'conv2d'
|
|
1596
|
+
|
|
1597
|
+
def __init__(
|
|
1598
|
+
self,
|
|
1599
|
+
filters: int,
|
|
1600
|
+
kernel_size: Union[int, List[int], Tuple[int, int]],
|
|
1601
|
+
strides: Union[int, List[int], Tuple[int, int]],
|
|
1602
|
+
spatial_padding: str,
|
|
1603
|
+
dilation_rate: Union[int, List[int], Tuple[int, int]] = 1,
|
|
1604
|
+
activation=None,
|
|
1605
|
+
use_bias: bool = True,
|
|
1606
|
+
kernel_initializer='glorot_uniform',
|
|
1607
|
+
bias_initializer='zeros',
|
|
1608
|
+
kernel_regularizer=None,
|
|
1609
|
+
bias_regularizer=None,
|
|
1610
|
+
activity_regularizer=None,
|
|
1611
|
+
kernel_constraint=None,
|
|
1612
|
+
bias_constraint=None,
|
|
1613
|
+
trainable=True,
|
|
1614
|
+
time_padding: str = 'causal',
|
|
1615
|
+
weight_norm: bool = False,
|
|
1616
|
+
name: Optional[str] = None,
|
|
1617
|
+
):
|
|
1618
|
+
super().__init__(
|
|
1619
|
+
kernel_size,
|
|
1620
|
+
strides,
|
|
1621
|
+
time_padding,
|
|
1622
|
+
spatial_padding,
|
|
1623
|
+
dilation_rate,
|
|
1624
|
+
name=name,
|
|
1625
|
+
)
|
|
1626
|
+
self._filters = filters
|
|
1627
|
+
# For the inner Conv2D layer we always use valid and handle padding within
|
|
1628
|
+
# this layer.
|
|
1629
|
+
with self.name_scope as name_scope:
|
|
1630
|
+
self._layer = tf.keras.layers.Conv2D(
|
|
1631
|
+
filters,
|
|
1632
|
+
self._kernel_size,
|
|
1633
|
+
self._strides,
|
|
1634
|
+
# We apply time and spatial padding outside of Keras.
|
|
1635
|
+
padding='valid',
|
|
1636
|
+
data_format='channels_last',
|
|
1637
|
+
dilation_rate=self._dilation_rate,
|
|
1638
|
+
activation=activation,
|
|
1639
|
+
use_bias=use_bias,
|
|
1640
|
+
kernel_initializer=kernel_initializer,
|
|
1641
|
+
bias_initializer=bias_initializer,
|
|
1642
|
+
kernel_regularizer=kernel_regularizer,
|
|
1643
|
+
bias_regularizer=bias_regularizer,
|
|
1644
|
+
activity_regularizer=activity_regularizer,
|
|
1645
|
+
kernel_constraint=kernel_constraint,
|
|
1646
|
+
bias_constraint=bias_constraint,
|
|
1647
|
+
trainable=trainable,
|
|
1648
|
+
name=name_scope,
|
|
1649
|
+
)
|
|
1650
|
+
if weight_norm:
|
|
1651
|
+
self._layer = utils.WeightNorm(self._layer, name='weight_norm')
|
|
1652
|
+
|
|
1653
|
+
def get_output_shape(
|
|
1654
|
+
self,
|
|
1655
|
+
input_shape: tf.TensorShape,
|
|
1656
|
+
constants: Optional[types.Constants] = None,
|
|
1657
|
+
) -> tf.TensorShape:
|
|
1658
|
+
if input_shape.rank != 2:
|
|
1659
|
+
raise ValueError(
|
|
1660
|
+
'Conv2D requires rank 4 input got: %s'
|
|
1661
|
+
% tf.TensorShape([None, None]).concatenate(input_shape)
|
|
1662
|
+
)
|
|
1663
|
+
spatial_output_size = utils.convolution_padding_output_size(
|
|
1664
|
+
input_shape.dims[0].value,
|
|
1665
|
+
self._spatial_padding,
|
|
1666
|
+
kernel_size=self._kernel_size[1],
|
|
1667
|
+
stride=self._strides[1],
|
|
1668
|
+
dilation_rate=self._dilation_rate[1],
|
|
1669
|
+
)
|
|
1670
|
+
return tf.TensorShape([spatial_output_size, self._filters])
|
|
1671
|
+
|
|
1672
|
+
|
|
1673
|
+
class DepthwiseConv2D(BaseConv2D):
|
|
1674
|
+
"""A 2D depthwise convolution layer.
|
|
1675
|
+
|
|
1676
|
+
Supports strided and dilated convolution.
|
|
1677
|
+
|
|
1678
|
+
The first spatial dimension (time) is processed causally, but the second
|
|
1679
|
+
spatial dimension is non-causal (i.e. 'valid' or 'same' convolution).
|
|
1680
|
+
"""
|
|
1681
|
+
|
|
1682
|
+
@classmethod
|
|
1683
|
+
def _default_name(cls):
|
|
1684
|
+
"""The default module name for this class."""
|
|
1685
|
+
return 'depthwise_conv2d'
|
|
1686
|
+
|
|
1687
|
+
def __init__(
|
|
1688
|
+
self,
|
|
1689
|
+
kernel_size: Union[int, List[int], Tuple[int, int]],
|
|
1690
|
+
strides: Union[int, List[int], Tuple[int, int]],
|
|
1691
|
+
spatial_padding: str,
|
|
1692
|
+
depth_multiplier: int,
|
|
1693
|
+
dilation_rate: Union[int, List[int], Tuple[int, int]] = 1,
|
|
1694
|
+
activation=None,
|
|
1695
|
+
use_bias: bool = True,
|
|
1696
|
+
depthwise_initializer='glorot_uniform',
|
|
1697
|
+
bias_initializer='zeros',
|
|
1698
|
+
depthwise_regularizer=None,
|
|
1699
|
+
bias_regularizer=None,
|
|
1700
|
+
activity_regularizer=None,
|
|
1701
|
+
depthwise_constraint=None,
|
|
1702
|
+
bias_constraint=None,
|
|
1703
|
+
trainable=True,
|
|
1704
|
+
time_padding: str = 'causal',
|
|
1705
|
+
name: Optional[str] = None,
|
|
1706
|
+
):
|
|
1707
|
+
super().__init__(
|
|
1708
|
+
kernel_size,
|
|
1709
|
+
strides,
|
|
1710
|
+
time_padding,
|
|
1711
|
+
spatial_padding,
|
|
1712
|
+
dilation_rate,
|
|
1713
|
+
name=name,
|
|
1714
|
+
)
|
|
1715
|
+
self._depth_multiplier = depth_multiplier
|
|
1716
|
+
|
|
1717
|
+
# For the inner DepthwiseConv2D layer we always use valid and handle padding
|
|
1718
|
+
# within this layer.
|
|
1719
|
+
with self.name_scope as name_scope:
|
|
1720
|
+
self._layer = tf.keras.layers.DepthwiseConv2D(
|
|
1721
|
+
kernel_size=self._kernel_size,
|
|
1722
|
+
strides=self._strides,
|
|
1723
|
+
# We apply time and spatial padding outside of Keras.
|
|
1724
|
+
padding='valid',
|
|
1725
|
+
depth_multiplier=depth_multiplier,
|
|
1726
|
+
data_format='channels_last',
|
|
1727
|
+
dilation_rate=self._dilation_rate,
|
|
1728
|
+
activation=activation,
|
|
1729
|
+
use_bias=use_bias,
|
|
1730
|
+
depthwise_initializer=depthwise_initializer,
|
|
1731
|
+
bias_initializer=bias_initializer,
|
|
1732
|
+
depthwise_regularizer=depthwise_regularizer,
|
|
1733
|
+
bias_regularizer=bias_regularizer,
|
|
1734
|
+
activity_regularizer=activity_regularizer,
|
|
1735
|
+
depthwise_constraint=depthwise_constraint,
|
|
1736
|
+
bias_constraint=bias_constraint,
|
|
1737
|
+
trainable=trainable,
|
|
1738
|
+
name=name_scope,
|
|
1739
|
+
)
|
|
1740
|
+
|
|
1741
|
+
def get_output_shape(
|
|
1742
|
+
self,
|
|
1743
|
+
input_shape: tf.TensorShape,
|
|
1744
|
+
constants: Optional[types.Constants] = None,
|
|
1745
|
+
) -> tf.TensorShape:
|
|
1746
|
+
if input_shape.rank != 2:
|
|
1747
|
+
raise ValueError(
|
|
1748
|
+
'DepthwiseConv2D requires rank 4 input got: %s'
|
|
1749
|
+
% tf.TensorShape([None, None]).concatenate(input_shape)
|
|
1750
|
+
)
|
|
1751
|
+
spatial_output_size = utils.convolution_padding_output_size(
|
|
1752
|
+
input_shape.dims[0].value,
|
|
1753
|
+
self._spatial_padding,
|
|
1754
|
+
kernel_size=self._kernel_size[1],
|
|
1755
|
+
stride=self._strides[1],
|
|
1756
|
+
dilation_rate=self._dilation_rate[1],
|
|
1757
|
+
)
|
|
1758
|
+
output_filters = input_shape.dims[1].value * self._depth_multiplier
|
|
1759
|
+
return tf.TensorShape([spatial_output_size, output_filters])
|
|
1760
|
+
|
|
1761
|
+
|
|
1762
|
+
class SeparableConv2D(BaseConv2D):
|
|
1763
|
+
"""A 2D separable convolution layer.
|
|
1764
|
+
|
|
1765
|
+
Supports strided and dilated convolution.
|
|
1766
|
+
|
|
1767
|
+
The first spatial dimension (time) is processed causally, but the second
|
|
1768
|
+
spatial dimension is non-causal (i.e. 'valid' or 'same' convolution).
|
|
1769
|
+
"""
|
|
1770
|
+
|
|
1771
|
+
@classmethod
|
|
1772
|
+
def _default_name(cls):
|
|
1773
|
+
"""The default module name for this class."""
|
|
1774
|
+
return 'separable_conv2d'
|
|
1775
|
+
|
|
1776
|
+
def __init__(
|
|
1777
|
+
self,
|
|
1778
|
+
filters: int,
|
|
1779
|
+
kernel_size: Union[int, List[int], Tuple[int, int]],
|
|
1780
|
+
strides: Union[int, List[int], Tuple[int, int]],
|
|
1781
|
+
spatial_padding: str,
|
|
1782
|
+
depth_multiplier: int,
|
|
1783
|
+
dilation_rate: Union[int, List[int], Tuple[int, int]] = 1,
|
|
1784
|
+
activation=None,
|
|
1785
|
+
use_bias: bool = True,
|
|
1786
|
+
depthwise_initializer='glorot_uniform',
|
|
1787
|
+
pointwise_initializer='glorot_uniform',
|
|
1788
|
+
bias_initializer='zeros',
|
|
1789
|
+
depthwise_regularizer=None,
|
|
1790
|
+
pointwise_regularizer=None,
|
|
1791
|
+
bias_regularizer=None,
|
|
1792
|
+
activity_regularizer=None,
|
|
1793
|
+
depthwise_constraint=None,
|
|
1794
|
+
pointwise_constraint=None,
|
|
1795
|
+
bias_constraint=None,
|
|
1796
|
+
trainable=True,
|
|
1797
|
+
time_padding: str = 'causal',
|
|
1798
|
+
name: Optional[str] = None,
|
|
1799
|
+
):
|
|
1800
|
+
super().__init__(
|
|
1801
|
+
kernel_size,
|
|
1802
|
+
strides,
|
|
1803
|
+
time_padding,
|
|
1804
|
+
spatial_padding,
|
|
1805
|
+
dilation_rate,
|
|
1806
|
+
name=name,
|
|
1807
|
+
)
|
|
1808
|
+
self._filters = filters
|
|
1809
|
+
|
|
1810
|
+
# For the inner SeparableConv2D layer we always use valid and handle padding
|
|
1811
|
+
# within this layer.
|
|
1812
|
+
with self.name_scope as name_scope:
|
|
1813
|
+
self._layer = tf.keras.layers.SeparableConv2D(
|
|
1814
|
+
filters=filters,
|
|
1815
|
+
kernel_size=self._kernel_size,
|
|
1816
|
+
strides=self._strides,
|
|
1817
|
+
# We apply time and spatial padding outside of Keras.
|
|
1818
|
+
padding='valid',
|
|
1819
|
+
depth_multiplier=depth_multiplier,
|
|
1820
|
+
data_format='channels_last',
|
|
1821
|
+
dilation_rate=self._dilation_rate,
|
|
1822
|
+
activation=activation,
|
|
1823
|
+
use_bias=use_bias,
|
|
1824
|
+
depthwise_initializer=depthwise_initializer,
|
|
1825
|
+
pointwise_initializer=pointwise_initializer,
|
|
1826
|
+
bias_initializer=bias_initializer,
|
|
1827
|
+
depthwise_regularizer=depthwise_regularizer,
|
|
1828
|
+
pointwise_regularizer=pointwise_regularizer,
|
|
1829
|
+
bias_regularizer=bias_regularizer,
|
|
1830
|
+
activity_regularizer=activity_regularizer,
|
|
1831
|
+
depthwise_constraint=depthwise_constraint,
|
|
1832
|
+
pointwise_constraint=pointwise_constraint,
|
|
1833
|
+
bias_constraint=bias_constraint,
|
|
1834
|
+
trainable=trainable,
|
|
1835
|
+
name=name_scope,
|
|
1836
|
+
)
|
|
1837
|
+
|
|
1838
|
+
def get_output_shape(
|
|
1839
|
+
self,
|
|
1840
|
+
input_shape: tf.TensorShape,
|
|
1841
|
+
constants: Optional[types.Constants] = None,
|
|
1842
|
+
) -> tf.TensorShape:
|
|
1843
|
+
if input_shape.rank != 2:
|
|
1844
|
+
raise ValueError(
|
|
1845
|
+
'SeparableConv2D requires rank 4 input got: %s'
|
|
1846
|
+
% tf.TensorShape([None, None]).concatenate(input_shape)
|
|
1847
|
+
)
|
|
1848
|
+
spatial_output_size = utils.convolution_padding_output_size(
|
|
1849
|
+
input_shape.dims[0].value,
|
|
1850
|
+
self._spatial_padding,
|
|
1851
|
+
kernel_size=self._kernel_size[1],
|
|
1852
|
+
stride=self._strides[1],
|
|
1853
|
+
dilation_rate=self._dilation_rate[1],
|
|
1854
|
+
)
|
|
1855
|
+
return tf.TensorShape([spatial_output_size, self._filters])
|