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,645 @@
|
|
|
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
|
+
"""Recurrent layers."""
|
|
15
|
+
|
|
16
|
+
import collections
|
|
17
|
+
import copy
|
|
18
|
+
import fractions
|
|
19
|
+
from typing import Any, Generator, Optional, Tuple
|
|
20
|
+
|
|
21
|
+
from sequence_layers.tensorflow import combinators
|
|
22
|
+
from sequence_layers.tensorflow import types
|
|
23
|
+
from sequence_layers.tensorflow import utils
|
|
24
|
+
import tensorflow.compat.v1 as tf1
|
|
25
|
+
import tensorflow.compat.v2 as tf
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class RNN(types.SequenceLayer):
|
|
29
|
+
"""A (Keras) recurrent layer."""
|
|
30
|
+
|
|
31
|
+
def __init__(self, cell, name: Optional[str] = None):
|
|
32
|
+
super().__init__(name=name)
|
|
33
|
+
self._output_size = cell.output_size
|
|
34
|
+
self._built = False
|
|
35
|
+
self._cell = cell
|
|
36
|
+
with self.name_scope as name_scope:
|
|
37
|
+
self._dynamic_rnn = tf.keras.layers.RNN(
|
|
38
|
+
cell, return_sequences=True, return_state=True, name=name_scope
|
|
39
|
+
)
|
|
40
|
+
self._static_rnn = tf.keras.layers.RNN(
|
|
41
|
+
cell,
|
|
42
|
+
return_sequences=True,
|
|
43
|
+
return_state=True,
|
|
44
|
+
unroll=True,
|
|
45
|
+
name=name_scope,
|
|
46
|
+
)
|
|
47
|
+
|
|
48
|
+
def _build(self, x: types.Sequence):
|
|
49
|
+
"""Builds the RNN cell."""
|
|
50
|
+
if self._built:
|
|
51
|
+
return
|
|
52
|
+
# The cell scope differs based on whether _dynamic_rnn or _static_rnn is the
|
|
53
|
+
# layer to build the RNN cell, so we explicitly build the cell first to give
|
|
54
|
+
# it a stable name regardless of which method is called first.
|
|
55
|
+
# TODO(b/152153746): The cell loses its name when built manually.
|
|
56
|
+
with tf.name_scope(self._cell.name):
|
|
57
|
+
self._cell.build(x.values.shape)
|
|
58
|
+
self._built = True
|
|
59
|
+
|
|
60
|
+
def get_initial_state(
|
|
61
|
+
self, x: types.Sequence, constants: Optional[types.Constants] = None
|
|
62
|
+
) -> types.State:
|
|
63
|
+
return self._dynamic_rnn.get_initial_state(x.values)
|
|
64
|
+
|
|
65
|
+
def get_output_shape(
|
|
66
|
+
self,
|
|
67
|
+
input_shape: tf.TensorShape,
|
|
68
|
+
constants: Optional[types.Constants] = None,
|
|
69
|
+
) -> tf.TensorShape:
|
|
70
|
+
del input_shape
|
|
71
|
+
|
|
72
|
+
def to_tensor_shape(x):
|
|
73
|
+
if isinstance(x, int):
|
|
74
|
+
return tf.TensorShape([x])
|
|
75
|
+
return x
|
|
76
|
+
|
|
77
|
+
# An RNN cell's output_size can be a structures of int/TensorShape. Convert
|
|
78
|
+
# to TensorShape.
|
|
79
|
+
return tf.nest.map_structure(to_tensor_shape, self._output_size)
|
|
80
|
+
|
|
81
|
+
@tf.Module.with_name_scope
|
|
82
|
+
def step(
|
|
83
|
+
self,
|
|
84
|
+
x: types.Sequence,
|
|
85
|
+
state: types.State,
|
|
86
|
+
training: bool,
|
|
87
|
+
constants: Optional[types.Constants] = None,
|
|
88
|
+
) -> Tuple[types.Sequence, types.State]:
|
|
89
|
+
self._build(x)
|
|
90
|
+
result = self._static_rnn(
|
|
91
|
+
x.values, initial_state=state, mask=x.mask, training=training
|
|
92
|
+
)
|
|
93
|
+
values, state = result[0], result[1:]
|
|
94
|
+
# Keras's RNN copies outputs for masked states instead of zeroing them.
|
|
95
|
+
return types.Sequence(values, x.mask).mask_invalid(), state
|
|
96
|
+
|
|
97
|
+
@tf.Module.with_name_scope
|
|
98
|
+
def layer(
|
|
99
|
+
self,
|
|
100
|
+
x: types.Sequence,
|
|
101
|
+
training: bool,
|
|
102
|
+
initial_state: Optional[types.State] = None,
|
|
103
|
+
constants: Optional[types.Constants] = None,
|
|
104
|
+
) -> types.Sequence:
|
|
105
|
+
self._build(x)
|
|
106
|
+
result = self._dynamic_rnn(
|
|
107
|
+
x.values, mask=x.mask, initial_state=initial_state, training=training
|
|
108
|
+
)
|
|
109
|
+
values = result[0]
|
|
110
|
+
|
|
111
|
+
# Keras's RNN copies outputs for masked states instead of zeroing them.
|
|
112
|
+
return types.Sequence(values, x.mask).mask_invalid()
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
class LegacyRNN(types.SequenceLayer):
|
|
116
|
+
"""An RNN layer that uses tf.nn.dynamic_rnn and tf.nn.static_rnn."""
|
|
117
|
+
|
|
118
|
+
def __init__(self, cell, name: Optional[str] = None):
|
|
119
|
+
super().__init__(name=name)
|
|
120
|
+
self._output_size = cell.output_size
|
|
121
|
+
self._cell = cell
|
|
122
|
+
|
|
123
|
+
def get_initial_state(
|
|
124
|
+
self, x: types.Sequence, constants: Optional[types.Constants] = None
|
|
125
|
+
) -> types.State:
|
|
126
|
+
batch_size = x.values.shape.dims[0].value
|
|
127
|
+
dtype = x.values.dtype
|
|
128
|
+
# TODO(rryan): This doesn't belong here, but creates the variables for the
|
|
129
|
+
# cell outside of layer/step.
|
|
130
|
+
if not self._cell.built:
|
|
131
|
+
self._cell.build(x.values.shape)
|
|
132
|
+
if hasattr(self._cell, 'get_initial_state'):
|
|
133
|
+
return self._cell.get_initial_state(x.values, batch_size, dtype)
|
|
134
|
+
return self._cell.zero_state(batch_size, dtype)
|
|
135
|
+
|
|
136
|
+
def get_output_shape(
|
|
137
|
+
self,
|
|
138
|
+
input_shape: tf.TensorShape,
|
|
139
|
+
constants: Optional[types.Constants] = None,
|
|
140
|
+
) -> tf.TensorShape:
|
|
141
|
+
del input_shape
|
|
142
|
+
|
|
143
|
+
def to_tensor_shape(x):
|
|
144
|
+
if isinstance(x, int):
|
|
145
|
+
return tf.TensorShape([x])
|
|
146
|
+
return x
|
|
147
|
+
|
|
148
|
+
# An RNN cell's output_size can be a structures of int/TensorShape. Convert
|
|
149
|
+
# to TensorShape.
|
|
150
|
+
return tf.nest.map_structure(to_tensor_shape, self._output_size)
|
|
151
|
+
|
|
152
|
+
@tf.Module.with_name_scope
|
|
153
|
+
def step(
|
|
154
|
+
self,
|
|
155
|
+
x: types.Sequence,
|
|
156
|
+
state: types.State,
|
|
157
|
+
training: bool,
|
|
158
|
+
constants: Optional[types.Constants] = None,
|
|
159
|
+
) -> Tuple[types.Sequence, types.State]:
|
|
160
|
+
values = tf.unstack(x.values, axis=1)
|
|
161
|
+
# To avoid creating complicated control flow for what is probably a
|
|
162
|
+
# short sequence of frames, do not provide lengths to static_rnn. We are
|
|
163
|
+
# masking the output values below, so this is safe.
|
|
164
|
+
values, state = tf1.nn.static_rnn(self._cell, values, initial_state=state)
|
|
165
|
+
values = tf.stack(values, axis=1)
|
|
166
|
+
return types.Sequence(values, x.mask).mask_invalid(), state
|
|
167
|
+
|
|
168
|
+
@tf.Module.with_name_scope
|
|
169
|
+
def layer(
|
|
170
|
+
self,
|
|
171
|
+
x: types.Sequence,
|
|
172
|
+
training: bool,
|
|
173
|
+
initial_state: Optional[types.State] = None,
|
|
174
|
+
constants: Optional[types.Constants] = None,
|
|
175
|
+
) -> types.Sequence:
|
|
176
|
+
if initial_state is None:
|
|
177
|
+
initial_state = self.get_initial_state(x)
|
|
178
|
+
lengths = x.lengths()
|
|
179
|
+
values, _ = tf1.nn.dynamic_rnn(
|
|
180
|
+
self._cell,
|
|
181
|
+
x.values,
|
|
182
|
+
initial_state=initial_state,
|
|
183
|
+
dtype=x.values.dtype,
|
|
184
|
+
sequence_length=lengths,
|
|
185
|
+
)
|
|
186
|
+
return types.Sequence(values, x.mask)
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
class Autoregressive(types.Emitting):
|
|
190
|
+
"""Wraps any SequenceLayer, concatenating input with its previous output.
|
|
191
|
+
|
|
192
|
+
If the wrapped layer downsamples the output will be "upsampled" to the input
|
|
193
|
+
rate via tiling. Upsampling is currently unsupported.
|
|
194
|
+
|
|
195
|
+
TODO(rryan): User-specified downsampling or upsampling.
|
|
196
|
+
TODO(rryan): User-specified feedback combination function (concat, add, etc.)
|
|
197
|
+
"""
|
|
198
|
+
|
|
199
|
+
def __init__(
|
|
200
|
+
self,
|
|
201
|
+
layer: combinators.SequenceLayerListOrCallable,
|
|
202
|
+
feedback_layer: Optional[combinators.SequenceLayerListOrCallable] = None,
|
|
203
|
+
name: Optional[str] = None,
|
|
204
|
+
):
|
|
205
|
+
super().__init__(name=name)
|
|
206
|
+
# TODO(rryan): Support upsample rate?
|
|
207
|
+
self._layer = combinators._maybe_wrap_layers(self, layer)
|
|
208
|
+
if feedback_layer is not None:
|
|
209
|
+
feedback_layer = combinators._maybe_wrap_layers(self, feedback_layer)
|
|
210
|
+
self._feedback_layer = feedback_layer
|
|
211
|
+
|
|
212
|
+
if self._layer.output_ratio > 1:
|
|
213
|
+
raise ValueError(
|
|
214
|
+
'Autoregressive requires output_ratio of <= 1: %s %s'
|
|
215
|
+
% (self._layer, self._layer.output_ratio)
|
|
216
|
+
)
|
|
217
|
+
if not self._layer.supports_step:
|
|
218
|
+
raise ValueError(
|
|
219
|
+
f'Autoregressive layer ({self._layer}) does not support stepping.'
|
|
220
|
+
)
|
|
221
|
+
|
|
222
|
+
@property
|
|
223
|
+
def block_size(self) -> int:
|
|
224
|
+
return self._layer.block_size
|
|
225
|
+
|
|
226
|
+
@property
|
|
227
|
+
def output_ratio(self) -> fractions.Fraction:
|
|
228
|
+
return self._layer.output_ratio
|
|
229
|
+
|
|
230
|
+
def get_initial_state(
|
|
231
|
+
self, x: types.Sequence, constants: Optional[types.Constants] = None
|
|
232
|
+
) -> types.State:
|
|
233
|
+
input_shape = x.channel_shape
|
|
234
|
+
output_shape = self._layer.get_output_shape(input_shape, constants)
|
|
235
|
+
output_dtype = self._layer.get_output_dtype(x.dtype)
|
|
236
|
+
feedback_shape = output_shape
|
|
237
|
+
feedback_dtype = output_dtype
|
|
238
|
+
feedback_state = ()
|
|
239
|
+
if self._feedback_layer:
|
|
240
|
+
tensor_output_shape = tf.concat(
|
|
241
|
+
[tf.shape(x.values)[:2], output_shape.as_list()], 0
|
|
242
|
+
)
|
|
243
|
+
# Create a fake output sequence to get initial state for the feedback
|
|
244
|
+
# layer.
|
|
245
|
+
x_out = x.apply_values(
|
|
246
|
+
lambda v: tf.zeros(tensor_output_shape, dtype=output_dtype)
|
|
247
|
+
)
|
|
248
|
+
feedback_state = self._feedback_layer.get_initial_state(x_out, constants)
|
|
249
|
+
feedback_shape = self._feedback_layer.get_output_shape(
|
|
250
|
+
output_shape, constants
|
|
251
|
+
)
|
|
252
|
+
feedback_dtype = self._feedback_layer.get_output_dtype(output_dtype)
|
|
253
|
+
# We concatenate the result of the feedback layer, so the actual input
|
|
254
|
+
# is augmented with the output.
|
|
255
|
+
if input_shape[1:] != feedback_shape[1:]:
|
|
256
|
+
raise ValueError(
|
|
257
|
+
'Input and feedback shape must match on every dimension '
|
|
258
|
+
'but the first: input_shape=%s feedback_shape=%s'
|
|
259
|
+
% (input_shape, feedback_shape)
|
|
260
|
+
)
|
|
261
|
+
if x.dtype != feedback_dtype:
|
|
262
|
+
raise ValueError(
|
|
263
|
+
f'Autoregressive feedback dtype ({feedback_dtype}) '
|
|
264
|
+
f'does not match the input dtype ({x.dtype}).'
|
|
265
|
+
)
|
|
266
|
+
|
|
267
|
+
extra_dims = input_shape.ndims - 1
|
|
268
|
+
feedback_size = feedback_shape.dims[0].value
|
|
269
|
+
|
|
270
|
+
autoregressive_input_shape = tf.TensorShape(
|
|
271
|
+
[input_shape.dims[0].value + feedback_size]
|
|
272
|
+
).concatenate(input_shape[1:])
|
|
273
|
+
x = x.apply_values(
|
|
274
|
+
tf.pad, [[0, 0], [0, 0], [0, feedback_size]] + [[0, 0]] * extra_dims
|
|
275
|
+
)
|
|
276
|
+
autoregressive_output_shape = self._layer.get_output_shape(
|
|
277
|
+
autoregressive_input_shape, constants
|
|
278
|
+
)
|
|
279
|
+
if autoregressive_output_shape != output_shape:
|
|
280
|
+
raise ValueError(
|
|
281
|
+
'Autoregressive cannot be used with a layer whose '
|
|
282
|
+
'output shape depends on its input shape: %s != %s'
|
|
283
|
+
% (autoregressive_output_shape, output_shape)
|
|
284
|
+
)
|
|
285
|
+
batch_size = utils.smart_dimension_size(x.values, 0)
|
|
286
|
+
output_block_size = self._layer.block_size * self._layer.output_ratio
|
|
287
|
+
assert output_block_size.denominator == 1
|
|
288
|
+
# TODO(rryan): Should we track the mask through the feedback connection?
|
|
289
|
+
# If we're processing contiguous sequences causally, then we can skip
|
|
290
|
+
# tracking the mask in the feedback connection, because fed-back frames
|
|
291
|
+
# can only be valid where the current block is invalid.
|
|
292
|
+
zero_feedback = tf.zeros(
|
|
293
|
+
[batch_size, int(output_block_size)] + feedback_shape.as_list(),
|
|
294
|
+
dtype=feedback_dtype,
|
|
295
|
+
)
|
|
296
|
+
# x is a correct input here because zero padding is equivalent to
|
|
297
|
+
# concatenating zero_feedback.
|
|
298
|
+
layer_state = self._layer.get_initial_state(x, constants)
|
|
299
|
+
return zero_feedback, feedback_state, layer_state
|
|
300
|
+
|
|
301
|
+
def _get_autoregressive_input_shape(
|
|
302
|
+
self,
|
|
303
|
+
input_shape: tf.TensorShape,
|
|
304
|
+
output_shape: tf.TensorShape,
|
|
305
|
+
constants: Optional[types.Constants] = None,
|
|
306
|
+
) -> tf.TensorShape:
|
|
307
|
+
feedback_shape = output_shape
|
|
308
|
+
if self._feedback_layer:
|
|
309
|
+
feedback_shape = self._feedback_layer.get_output_shape(
|
|
310
|
+
output_shape, constants
|
|
311
|
+
)
|
|
312
|
+
feedback_size = feedback_shape.dims[0].value
|
|
313
|
+
return tf.TensorShape(
|
|
314
|
+
[input_shape.dims[0].value + feedback_size]
|
|
315
|
+
).concatenate(input_shape[1:])
|
|
316
|
+
|
|
317
|
+
def _get_autoregressive_input_spec(
|
|
318
|
+
self,
|
|
319
|
+
input_spec: tf.TensorSpec,
|
|
320
|
+
output_shape: tf.TensorShape,
|
|
321
|
+
constants: Optional[types.Constants] = None,
|
|
322
|
+
) -> tf.TensorSpec:
|
|
323
|
+
return tf.TensorSpec(
|
|
324
|
+
self._get_autoregressive_input_shape(
|
|
325
|
+
input_spec.shape, output_shape, constants
|
|
326
|
+
),
|
|
327
|
+
input_spec.dtype,
|
|
328
|
+
)
|
|
329
|
+
|
|
330
|
+
def get_output_shape(
|
|
331
|
+
self,
|
|
332
|
+
input_shape: tf.TensorShape,
|
|
333
|
+
constants: Optional[types.Constants] = None,
|
|
334
|
+
) -> tf.TensorShape:
|
|
335
|
+
output_shape = self._layer.get_output_shape(input_shape, constants)
|
|
336
|
+
autoregressive_input_shape = self._get_autoregressive_input_shape(
|
|
337
|
+
input_shape, output_shape, constants
|
|
338
|
+
)
|
|
339
|
+
autoregressive_output_shape = self._layer.get_output_shape(
|
|
340
|
+
autoregressive_input_shape, constants
|
|
341
|
+
)
|
|
342
|
+
if autoregressive_output_shape != output_shape:
|
|
343
|
+
raise ValueError(
|
|
344
|
+
'Autoregressive cannot be used with a layer whose '
|
|
345
|
+
'output shape depends on its input shape: %s != %s'
|
|
346
|
+
% (autoregressive_output_shape, output_shape)
|
|
347
|
+
)
|
|
348
|
+
return output_shape
|
|
349
|
+
|
|
350
|
+
def get_emit_specs(
|
|
351
|
+
self,
|
|
352
|
+
input_spec: tf.TensorSpec,
|
|
353
|
+
constants: Optional[types.Constants] = None,
|
|
354
|
+
) -> types.EmitSpecs:
|
|
355
|
+
# TODO(rryan): Feedback layer emits?
|
|
356
|
+
output_shape = self._layer.get_output_shape(input_spec.shape, constants)
|
|
357
|
+
autoregressive_input_spec = self._get_autoregressive_input_spec(
|
|
358
|
+
input_spec, output_shape, constants
|
|
359
|
+
)
|
|
360
|
+
return collections.OrderedDict([[
|
|
361
|
+
self._layer.name,
|
|
362
|
+
self._layer.get_emit_specs(autoregressive_input_spec, constants),
|
|
363
|
+
]])
|
|
364
|
+
|
|
365
|
+
def _autoregressive_step(
|
|
366
|
+
self,
|
|
367
|
+
x: types.Sequence,
|
|
368
|
+
state: types.State,
|
|
369
|
+
training: bool,
|
|
370
|
+
constants: types.Constants,
|
|
371
|
+
unroll: bool,
|
|
372
|
+
) -> Tuple[types.Sequence, types.State, types.Emits]:
|
|
373
|
+
input_block_size = self._layer.block_size
|
|
374
|
+
output_block_size = int(input_block_size * self._layer.output_ratio)
|
|
375
|
+
# Guaranteed by the constructor.
|
|
376
|
+
assert output_block_size <= input_block_size
|
|
377
|
+
assert input_block_size % output_block_size == 0
|
|
378
|
+
block_ratio = input_block_size // output_block_size
|
|
379
|
+
|
|
380
|
+
input_spec = x.channel_spec
|
|
381
|
+
output_spec = self._layer.get_output_spec(input_spec, constants)
|
|
382
|
+
feedback_shape = output_spec.shape
|
|
383
|
+
if self._feedback_layer:
|
|
384
|
+
feedback_shape = self._feedback_layer.get_output_shape(
|
|
385
|
+
output_spec.shape, constants
|
|
386
|
+
)
|
|
387
|
+
autoregressive_input_spec = self._get_autoregressive_input_spec(
|
|
388
|
+
x.channel_spec, output_spec.shape, constants
|
|
389
|
+
)
|
|
390
|
+
emit_specs = self._layer.get_emit_specs(
|
|
391
|
+
autoregressive_input_spec, constants
|
|
392
|
+
)
|
|
393
|
+
|
|
394
|
+
input_time = utils.smart_dimension_size(x.values, 1)
|
|
395
|
+
if unroll and not isinstance(input_time, int):
|
|
396
|
+
raise ValueError(
|
|
397
|
+
'To statically unroll, the Sequence time dimension must be known: %s'
|
|
398
|
+
% x
|
|
399
|
+
)
|
|
400
|
+
|
|
401
|
+
# The number of blocks we will process (i.e. iterations of while loop).
|
|
402
|
+
num_blocks = (input_time + input_block_size - 1) // input_block_size
|
|
403
|
+
# The timesteps for the number of whole blocks we can process.
|
|
404
|
+
padded_time = num_blocks * input_block_size
|
|
405
|
+
|
|
406
|
+
pad_amount = padded_time - input_time
|
|
407
|
+
x = x.pad_time(0, pad_amount, valid=False)
|
|
408
|
+
input_time = padded_time
|
|
409
|
+
|
|
410
|
+
def transition_fn(
|
|
411
|
+
x_block: types.Sequence, state: types.State
|
|
412
|
+
) -> Tuple[types.Sequence, types.State, types.Emits]:
|
|
413
|
+
"""Concatenates previous output to input and runs the wrapped layer."""
|
|
414
|
+
previous_output, feedback_state, layer_state = state
|
|
415
|
+
previous_output.shape.assert_is_compatible_with(
|
|
416
|
+
tf.TensorShape([None, output_block_size]).concatenate(feedback_shape)
|
|
417
|
+
)
|
|
418
|
+
|
|
419
|
+
if block_ratio > 1:
|
|
420
|
+
previous_output = tf.tile(
|
|
421
|
+
previous_output,
|
|
422
|
+
[1, block_ratio] + [1] * (previous_output.shape.rank - 2),
|
|
423
|
+
)
|
|
424
|
+
x_block = x_block.apply_values(
|
|
425
|
+
lambda v: tf.concat([v, previous_output], axis=2)
|
|
426
|
+
) # pylint: disable=cell-var-from-loop
|
|
427
|
+
|
|
428
|
+
y_block, layer_state, y_emits = self._layer.step_with_emits(
|
|
429
|
+
x_block, layer_state, training=training, constants=constants
|
|
430
|
+
)
|
|
431
|
+
|
|
432
|
+
if self._feedback_layer is not None:
|
|
433
|
+
feedback_block, feedback_state = self._feedback_layer.step(
|
|
434
|
+
y_block, feedback_state, training=training, constants=constants
|
|
435
|
+
)
|
|
436
|
+
feedback_block = feedback_block.values
|
|
437
|
+
else:
|
|
438
|
+
feedback_block = y_block.values
|
|
439
|
+
|
|
440
|
+
return y_block, (feedback_block, feedback_state, layer_state), y_emits
|
|
441
|
+
|
|
442
|
+
if unroll:
|
|
443
|
+
return utils.step_by_step_fn_static(
|
|
444
|
+
transition_fn, num_blocks, input_block_size, x, state
|
|
445
|
+
)
|
|
446
|
+
else:
|
|
447
|
+
return utils.step_by_step_fn_dynamic(
|
|
448
|
+
transition_fn,
|
|
449
|
+
input_time,
|
|
450
|
+
input_spec.shape,
|
|
451
|
+
output_spec,
|
|
452
|
+
emit_specs,
|
|
453
|
+
num_blocks,
|
|
454
|
+
input_block_size,
|
|
455
|
+
output_block_size,
|
|
456
|
+
x,
|
|
457
|
+
state,
|
|
458
|
+
)
|
|
459
|
+
|
|
460
|
+
@tf.Module.with_name_scope
|
|
461
|
+
def step_with_emits(
|
|
462
|
+
self,
|
|
463
|
+
x: types.Sequence,
|
|
464
|
+
state: types.State,
|
|
465
|
+
training: bool,
|
|
466
|
+
constants: Optional[types.Constants] = None,
|
|
467
|
+
) -> Tuple[types.Sequence, types.State, types.Emits]:
|
|
468
|
+
outputs, state, emits = self._autoregressive_step(
|
|
469
|
+
x, state, training, constants, unroll=True
|
|
470
|
+
)
|
|
471
|
+
emits = collections.OrderedDict([[self._layer.name, emits]])
|
|
472
|
+
return outputs, state, emits
|
|
473
|
+
|
|
474
|
+
@tf.Module.with_name_scope
|
|
475
|
+
def layer_with_emits(
|
|
476
|
+
self,
|
|
477
|
+
x: types.Sequence,
|
|
478
|
+
training: bool,
|
|
479
|
+
initial_state: Optional[types.State] = None,
|
|
480
|
+
constants: Optional[types.Constants] = None,
|
|
481
|
+
) -> Tuple[types.Sequence, types.Emits]:
|
|
482
|
+
if initial_state is None:
|
|
483
|
+
initial_state = self.get_initial_state(x, constants)
|
|
484
|
+
x, _, emits = self._autoregressive_step(
|
|
485
|
+
x, initial_state, training=training, constants=constants, unroll=False
|
|
486
|
+
)
|
|
487
|
+
emits = collections.OrderedDict([[self._layer.name, emits]])
|
|
488
|
+
return x, emits
|
|
489
|
+
|
|
490
|
+
def _yield_emits(
|
|
491
|
+
self, emits: types.Emits
|
|
492
|
+
) -> Generator[tuple[types.SequenceLayer, types.Emits], None, None]:
|
|
493
|
+
yield from super()._yield_emits(emits)
|
|
494
|
+
yield from self._layer._yield_emits(emits[self._layer.name]) # pylint: disable=protected-access
|
|
495
|
+
|
|
496
|
+
|
|
497
|
+
def _compute_zoneout(output, state, new_state, zoneout_probability, is_train):
|
|
498
|
+
"""Implements zoneout. See KerasZoneoutWrapper for details."""
|
|
499
|
+
zoneout_probability = tf.convert_to_tensor(zoneout_probability, output.dtype)
|
|
500
|
+
keep_probability = 1.0 - zoneout_probability
|
|
501
|
+
|
|
502
|
+
# Special-case zoneout being off to save computation.
|
|
503
|
+
if tf.get_static_value(zoneout_probability) == 0.0:
|
|
504
|
+
return output, new_state
|
|
505
|
+
|
|
506
|
+
def _zoneout_train(new_state, state):
|
|
507
|
+
# A copy of tf.nn.dropout without scaling by 1/keep_probability.
|
|
508
|
+
random_tensor = keep_probability
|
|
509
|
+
random_tensor += tf.random.uniform(
|
|
510
|
+
tf.shape(new_state), dtype=new_state.dtype
|
|
511
|
+
)
|
|
512
|
+
|
|
513
|
+
# keep_selector is 0.0 if random_tensor lies in [keep_probability, 1.0)
|
|
514
|
+
# and 1.0 if random_tensor lies in [1.0, 1.0 + keep_probability).
|
|
515
|
+
keep_selector = tf.floor(random_tensor)
|
|
516
|
+
return (new_state - state) * keep_selector + state
|
|
517
|
+
|
|
518
|
+
def _zoneout_eval(new_state, state):
|
|
519
|
+
return keep_probability * new_state + zoneout_probability * state
|
|
520
|
+
|
|
521
|
+
with tf.name_scope('zoneout'):
|
|
522
|
+
zoneout_fn = _zoneout_train if is_train else _zoneout_eval
|
|
523
|
+
# Applies zoneout_fn to each pair of members of the
|
|
524
|
+
# potentially-hierarchical structures of new_state and state.
|
|
525
|
+
# Work around Keras's quirky RNN behavior by flattening first then
|
|
526
|
+
# re-packing.
|
|
527
|
+
flat_new_state = tf.nest.map_structure(
|
|
528
|
+
zoneout_fn, tf.nest.flatten(new_state), tf.nest.flatten(state)
|
|
529
|
+
)
|
|
530
|
+
new_state = tf.nest.pack_sequence_as(new_state, flat_new_state)
|
|
531
|
+
return output, new_state
|
|
532
|
+
|
|
533
|
+
|
|
534
|
+
class KerasZoneoutWrapper(tf.keras.layers.AbstractRNNCell):
|
|
535
|
+
"""Implements ZoneOut regularization for RNN states.
|
|
536
|
+
|
|
537
|
+
From "Zoneout: Regularizing RNNs by Randomly Preserving Hidden Activations".
|
|
538
|
+
https://arxiv.org/abs/1606.01305
|
|
539
|
+
|
|
540
|
+
Uses the same approach as the canonical implementation from the authors:
|
|
541
|
+
https://github.com/teganmaharaj/zoneout
|
|
542
|
+
|
|
543
|
+
Computed as
|
|
544
|
+
|
|
545
|
+
`(1 - zoneout_probability) * tf.nn.dropout(new_state - old_state, 1 -
|
|
546
|
+
zoneout_probability) + old_state`
|
|
547
|
+
|
|
548
|
+
in training, and
|
|
549
|
+
|
|
550
|
+
`zoneout_probability * old_state + (1 - zoneout_probability) * new_state`
|
|
551
|
+
|
|
552
|
+
in inference.
|
|
553
|
+
"""
|
|
554
|
+
|
|
555
|
+
def __init__(self, cell, zoneout_probability, name=None):
|
|
556
|
+
"""Constructs a ZoneoutWrapper to apply ZoneOut to the provided RNNCell.
|
|
557
|
+
|
|
558
|
+
Args:
|
|
559
|
+
cell: An RNNCell to apply to ZoneOut regularization to.
|
|
560
|
+
zoneout_probability: The probability or rate at which state updates for
|
|
561
|
+
`cell`'s units are forgotten. Must be a Python float.
|
|
562
|
+
name: An optional name for the wrapper.
|
|
563
|
+
|
|
564
|
+
Raises:
|
|
565
|
+
ValueError: If zoneout_probability is not a Python float in [0.0, 1.0].
|
|
566
|
+
"""
|
|
567
|
+
super().__init__(name=name)
|
|
568
|
+
if not isinstance(zoneout_probability, float):
|
|
569
|
+
raise ValueError('zoneout_probability must be a float.')
|
|
570
|
+
if zoneout_probability < 0.0 or zoneout_probability > 1.0:
|
|
571
|
+
raise ValueError('Invalid zoneout_probability: %s' % zoneout_probability)
|
|
572
|
+
|
|
573
|
+
self._cell = cell
|
|
574
|
+
self._zoneout_probability = zoneout_probability
|
|
575
|
+
|
|
576
|
+
def build(self, input_shape):
|
|
577
|
+
super().build(input_shape)
|
|
578
|
+
# TODO(b/152153746): The cell loses its name when built manually.
|
|
579
|
+
with tf.name_scope(self._cell.name):
|
|
580
|
+
self._cell.build(input_shape)
|
|
581
|
+
self.built = True
|
|
582
|
+
|
|
583
|
+
@property
|
|
584
|
+
def state_size(self):
|
|
585
|
+
"""Returns the `state_size` of the wrapped RNNCell."""
|
|
586
|
+
return self._cell.state_size
|
|
587
|
+
|
|
588
|
+
@property
|
|
589
|
+
def output_size(self):
|
|
590
|
+
"""Returns the `output_size` of the wrapped RNNCell."""
|
|
591
|
+
return self._cell.output_size
|
|
592
|
+
|
|
593
|
+
def get_initial_state(self, inputs=None, batch_size=None, dtype=None):
|
|
594
|
+
"""Returns initial state for the wrapped RNNCell.
|
|
595
|
+
|
|
596
|
+
Args:
|
|
597
|
+
inputs: The input tensor to the RNN layer, which should contain the batch
|
|
598
|
+
size as its shape[0], and also dtype.
|
|
599
|
+
batch_size: a scalar tensor that represents the batch size of the inputs.
|
|
600
|
+
dtype: a tf.DType that represents the type of the inputs.
|
|
601
|
+
|
|
602
|
+
Returns:
|
|
603
|
+
A Tensor or hierarchical structure of initial state Tensors of type
|
|
604
|
+
`dtype` and `batch_size` outer dimension.
|
|
605
|
+
"""
|
|
606
|
+
return self._cell.get_initial_state(inputs, batch_size, dtype)
|
|
607
|
+
|
|
608
|
+
def call(self, inputs, state, training=None):
|
|
609
|
+
"""Runs the RNN cell with `inputs` and `state` and applies ZoneOut.
|
|
610
|
+
|
|
611
|
+
Args:
|
|
612
|
+
inputs: A rank 2 Tensor with shape `[batch_size, input_size]`.
|
|
613
|
+
state: A Tensor or hierarchical structure of Tensors representing the
|
|
614
|
+
current RNN cell state.
|
|
615
|
+
training: Whether training is enabled.
|
|
616
|
+
|
|
617
|
+
Returns:
|
|
618
|
+
output: A rank 2 Tensor with shape `[batch_size, output_size]`.
|
|
619
|
+
new_state: A Tensor or hierarchical structure of Tensors representing the
|
|
620
|
+
new RNN cell state, with ZoneOut applied.
|
|
621
|
+
"""
|
|
622
|
+
if training is None:
|
|
623
|
+
raise ValueError('You must provide training kwarg to ZoneoutWrapper.')
|
|
624
|
+
output, new_state = self._cell(inputs, state, training=training)
|
|
625
|
+
return _compute_zoneout(
|
|
626
|
+
output, state, new_state, self._zoneout_probability, training
|
|
627
|
+
)
|
|
628
|
+
|
|
629
|
+
def get_config(self) -> dict[str, Any]:
|
|
630
|
+
return {
|
|
631
|
+
'cell': tf.keras.utils.legacy.serialize_keras_object(self._cell),
|
|
632
|
+
'zoneout_probability': self._zoneout_probability,
|
|
633
|
+
}
|
|
634
|
+
|
|
635
|
+
@classmethod
|
|
636
|
+
def from_config(
|
|
637
|
+
cls, config: dict[str, Any], custom_objects: ... = None
|
|
638
|
+
) -> 'KerasZoneoutWrapper':
|
|
639
|
+
config = copy.deepcopy(config)
|
|
640
|
+
cell = tf.keras.layers.deserialize(
|
|
641
|
+
config.pop('cell'),
|
|
642
|
+
custom_objects=custom_objects,
|
|
643
|
+
use_legacy_format=True,
|
|
644
|
+
)
|
|
645
|
+
return cls(cell, **config)
|