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.
Files changed (55) hide show
  1. sequence_layers/__init__.py +16 -0
  2. sequence_layers/internal/types.py +521 -0
  3. sequence_layers/jax/__init__.py +29 -0
  4. sequence_layers/jax/attention.py +6124 -0
  5. sequence_layers/jax/combinators.py +1907 -0
  6. sequence_layers/jax/conditioning.py +511 -0
  7. sequence_layers/jax/convolution.py +2103 -0
  8. sequence_layers/jax/dense.py +447 -0
  9. sequence_layers/jax/dsp.py +1686 -0
  10. sequence_layers/jax/examples/gemma3n_audio_encoder.py +358 -0
  11. sequence_layers/jax/export.py +313 -0
  12. sequence_layers/jax/meta.py +54 -0
  13. sequence_layers/jax/normalization.py +889 -0
  14. sequence_layers/jax/pooling.py +925 -0
  15. sequence_layers/jax/position.py +370 -0
  16. sequence_layers/jax/recurrent.py +674 -0
  17. sequence_layers/jax/sharding.py +48 -0
  18. sequence_layers/jax/signal.py +511 -0
  19. sequence_layers/jax/simple.py +2679 -0
  20. sequence_layers/jax/test_utils.py +1343 -0
  21. sequence_layers/jax/time_varying.py +673 -0
  22. sequence_layers/jax/types.py +1537 -0
  23. sequence_layers/jax/typing.py +59 -0
  24. sequence_layers/jax/utils.py +2149 -0
  25. sequence_layers/tensorflow/__init__.py +56 -0
  26. sequence_layers/tensorflow/attention.py +3426 -0
  27. sequence_layers/tensorflow/combinators.py +938 -0
  28. sequence_layers/tensorflow/conditioning.py +644 -0
  29. sequence_layers/tensorflow/convolution.py +1855 -0
  30. sequence_layers/tensorflow/dense.py +285 -0
  31. sequence_layers/tensorflow/dsp.py +740 -0
  32. sequence_layers/tensorflow/examples/bert.py +144 -0
  33. sequence_layers/tensorflow/examples/conformer.py +138 -0
  34. sequence_layers/tensorflow/examples/deep_voice.py +72 -0
  35. sequence_layers/tensorflow/examples/listen_attend_spell.py +102 -0
  36. sequence_layers/tensorflow/examples/mobilenet.py +92 -0
  37. sequence_layers/tensorflow/examples/t5.py +225 -0
  38. sequence_layers/tensorflow/examples/tacotron.py +124 -0
  39. sequence_layers/tensorflow/examples/transformer.py +159 -0
  40. sequence_layers/tensorflow/examples/very_attentive_tacotron.py +1771 -0
  41. sequence_layers/tensorflow/examples/wavernn.py +225 -0
  42. sequence_layers/tensorflow/normalization.py +1127 -0
  43. sequence_layers/tensorflow/pooling.py +462 -0
  44. sequence_layers/tensorflow/position.py +509 -0
  45. sequence_layers/tensorflow/recurrent.py +645 -0
  46. sequence_layers/tensorflow/simple.py +1207 -0
  47. sequence_layers/tensorflow/squeeze.py +178 -0
  48. sequence_layers/tensorflow/test_util.py +834 -0
  49. sequence_layers/tensorflow/time_varying.py +439 -0
  50. sequence_layers/tensorflow/types.py +961 -0
  51. sequence_layers/tensorflow/utils.py +858 -0
  52. sequence_layers-0.1.dist-info/METADATA +69 -0
  53. sequence_layers-0.1.dist-info/RECORD +55 -0
  54. sequence_layers-0.1.dist-info/WHEEL +4 -0
  55. sequence_layers-0.1.dist-info/licenses/LICENSE +202 -0
@@ -0,0 +1,961 @@
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
+ """Type definitions for streaming sequence layers."""
15
+
16
+ import abc
17
+ import sys
18
+ from typing import Any, Callable, Generator, Iterable, NamedTuple, Optional, Type, Union
19
+
20
+ import attr
21
+ import numpy as np
22
+ from sequence_layers.internal import types as internal
23
+ import tensorflow.compat.v1 as tf1
24
+ import tensorflow.compat.v2 as tf
25
+ import tf_keras
26
+
27
+ from tensorflow.python.framework import type_spec
28
+
29
+
30
+ TensorLike = Union[tf.Tensor, np.ndarray]
31
+ # Type hint that is basically Any but represents the semantic meaning.
32
+ State = Union[tf.Tensor, 'Sequence', Any]
33
+ Constants = Optional[dict[str, Union[tf.Tensor, 'Sequence']]]
34
+ # Any nest of Tensors or Sequences.
35
+ Emits = Union[tf.Tensor, 'Sequence', Any]
36
+ # Any nest of TensorSpecs.
37
+ EmitSpecs = Union[tf.TensorSpec, Any]
38
+
39
+ MASK_DTYPE = tf.float32
40
+
41
+
42
+ def _check_shape_constraints(values, mask):
43
+ """Raises ValueError if values/lengths do not satisfy shape constraints."""
44
+ # Special-case types that are used as part of tf.nest
45
+ # and tf.data.Dataset machinery.
46
+ for tp in [
47
+ tf.TensorArray,
48
+ tf.TensorArraySpec,
49
+ tf.TensorSpec,
50
+ tf.TensorShape,
51
+ tf.DType,
52
+ tf.TypeSpec,
53
+ type,
54
+ bool,
55
+ ]:
56
+ if isinstance(values, tp) and isinstance(mask, tp):
57
+ return
58
+ # Allow variant tensors (TensorArrayV2).
59
+ if (
60
+ isinstance(values, tf.Tensor)
61
+ and values.dtype == tf.variant
62
+ and isinstance(mask, tf.Tensor)
63
+ and mask.dtype == tf.variant
64
+ ):
65
+ return
66
+ if (
67
+ type(values).__name__ == 'PerReplica'
68
+ and type(mask).__name__ == 'PerReplica'
69
+ ):
70
+ return
71
+ # _DotString is used to pretty print some tf.nest error messages.
72
+ if (
73
+ type(values).__name__ == '_DotString'
74
+ and type(mask).__name__ == '_DotString'
75
+ ):
76
+ return
77
+ # Allow empty tuple, which also shows up in nest/tpu.rewrite machinery.
78
+ if values is None and mask is None:
79
+ return
80
+ # Checking the rank in this way allows these checks to work for Tensors,
81
+ # ndarrays, and anything else with a shape attribute.
82
+ try:
83
+ values_rank = len(values.shape)
84
+ mask_rank = len(mask.shape)
85
+ except ValueError as e:
86
+ raise ValueError(
87
+ ' '.join([
88
+ str(e),
89
+ f'str(values)={values} str(mask)={mask}',
90
+ 'Sequence has unknown rank. This can happen when e.g. a Tensor is the ' # pylint: disable=implicit-str-concat
91
+ 'output of a tf.cond() whose two branches output different'
92
+ ' shapes.',
93
+ ])
94
+ ).with_traceback(sys.exc_info()[2]) from e
95
+
96
+ # tf.data.Dataset batching creates a pad_value Sequence with rank 0
97
+ # values and mask, so we have to special-case this.
98
+ if values_rank < 2 and mask_rank != 0:
99
+ raise ValueError(
100
+ '`values` must have rank of at least 2. Found: %s' % str(values)
101
+ )
102
+ if mask_rank != 2:
103
+ raise ValueError('`mask` must have rank of 2. Found: %s' % str(mask))
104
+ elif values_rank and mask_rank == 2:
105
+ # values and mask are Tensor-like (have a shape property) but we can't
106
+ # convert_to_tensor so we can assume shape is a TensorShape.
107
+ def get_dim(tensor, index):
108
+ """Returns tensor's dimension size at position index. None if unknown."""
109
+ dim = tensor.shape[index]
110
+ return dim.value if isinstance(dim, tf1.Dimension) else dim
111
+
112
+ values_batch = get_dim(values, 0)
113
+ mask_batch = get_dim(mask, 0)
114
+ # If values_batch or lengths_batch are None, then we can't check whether
115
+ # there is a mismatch. Additionally, to support using SequenceTuples with
116
+ # tf.data, we allow mismatches if either dimension is zero (tf.data's
117
+ # padded_batch machinery builds SequenceTuples with mismatched batch
118
+ # dimension as an intermediate step).
119
+ if values_batch and mask_batch and values_batch != mask_batch:
120
+ raise ValueError(
121
+ 'Sequence `values` and `mask` must have equal batch dimension: '
122
+ 'values=%s mask=%s' % (values, mask)
123
+ )
124
+
125
+ values_time = get_dim(values, 1)
126
+ mask_time = get_dim(mask, 1)
127
+ # If values_batch or lengths_batch are None, then we can't check whether
128
+ # there is a mismatch. Additionally, to support using SequenceTuples with
129
+ # tf.data, we allow mismatches if either dimension is zero (tf.data's
130
+ # padded_batch machinery builds SequenceTuples with mismatched batch
131
+ # dimension as an intermediate step).
132
+ if values_time and mask_time and values_time != mask_time:
133
+ raise ValueError(
134
+ 'Sequence `values` and `mask` must have equal time dimension: '
135
+ 'values=%s mask=%s' % (values, mask)
136
+ )
137
+
138
+
139
+ PaddingMode = internal.PaddingMode
140
+ validate_padding = internal.validate_padding
141
+
142
+
143
+ class SequenceSpec(tf.TypeSpec):
144
+ """A tf.TypeSpec for Sequence objects."""
145
+
146
+ __slots__ = ('_spec',)
147
+
148
+ def __init__(self, values_spec: tf.TensorSpec, mask_spec: tf.TensorSpec):
149
+ self._spec = (values_spec, mask_spec)
150
+
151
+ @property
152
+ def value_type(self) -> Type['Sequence']:
153
+ return Sequence
154
+
155
+ def _to_components(self, obj: 'Sequence') -> tuple[tf.Tensor, tf.Tensor]:
156
+ return (obj.values, obj.mask)
157
+
158
+ def _from_components(
159
+ self, components: tuple[tf.Tensor, tf.Tensor]
160
+ ) -> 'Sequence':
161
+ return Sequence(*components)
162
+
163
+ @property
164
+ def _component_specs(self) -> tuple[tf.TensorSpec, tf.TensorSpec]:
165
+ return self._spec
166
+
167
+ def _serialize(self) -> tuple[tf.TensorSpec, tf.TensorSpec]:
168
+ return self._spec
169
+
170
+ @classmethod
171
+ def _deserialize(
172
+ cls, encoded: tuple[tf.TensorSpec, tf.TensorSpec]
173
+ ) -> 'SequenceSpec':
174
+ return cls(*encoded)
175
+
176
+ @classmethod
177
+ def from_sequence(cls, sequence: 'Sequence') -> 'SequenceSpec':
178
+ return SequenceSpec(
179
+ tf.TensorSpec.from_tensor(sequence.values),
180
+ tf.TensorSpec.from_tensor(sequence.mask),
181
+ )
182
+
183
+
184
+ # TODO(rryan): Switch to dataclass once we turn off Python 2.
185
+ @attr.s(frozen=True)
186
+ class Sequence(internal.Sequence):
187
+ """A structure representing a sequence and its valid timesteps (a mask).
188
+
189
+ Sequences are immutable.
190
+ """
191
+
192
+ # TODO(rryan): Switch the types to TensorLike after updating to V2
193
+ # TensorShape (so that values.shape works equivalently to numpy).
194
+ # The sequence values. A [batch_size, time, ...] tensor of any dtype.
195
+ values: tf.Tensor = attr.ib()
196
+ # The sequence mask. A [batch_size, time] tensor of type tf.float32.
197
+ # batch_size and time must match values.
198
+ mask: tf.Tensor = attr.ib()
199
+
200
+ def __attrs_post_init__(self):
201
+ _check_shape_constraints(self.values, self.mask)
202
+
203
+ @classmethod
204
+ def concatenate_sequences(cls, sequences: Iterable['Sequence']) -> 'Sequence':
205
+ with tf.name_scope('Sequence.concatenate_sequences'):
206
+ values = []
207
+ masks = []
208
+ for sequence in sequences:
209
+ values.append(sequence.values)
210
+ masks.append(sequence.mask)
211
+ return Sequence(tf.concat(values, axis=1), tf.concat(masks, axis=1))
212
+
213
+ def apply(
214
+ self, map_fn: Callable[..., tuple[tf.Tensor, tf.Tensor]], *args, **kwargs
215
+ ) -> 'Sequence':
216
+ # Don't create a name scope here to avoid dirtying variable names.
217
+ return Sequence(*map_fn(self.values, self.mask, *args, **kwargs))
218
+
219
+ def apply_values(
220
+ self, map_fn: Callable[..., tf.Tensor], *args, **kwargs
221
+ ) -> 'Sequence':
222
+ # Don't create a name scope here to avoid dirtying variable names.
223
+ return Sequence(map_fn(self.values, *args, **kwargs), self.mask)
224
+
225
+ def lengths(self) -> tf.Tensor:
226
+ with tf.name_scope('Sequence.lengths'):
227
+ return tf.reduce_sum(tf.cast(self.mask, tf.int32), axis=1)
228
+
229
+ def mask_invalid(self) -> 'Sequence':
230
+ """Returns a new Sequence with invalid timesteps replaced with zeros."""
231
+ with tf.name_scope('Sequence.mask_invalid'):
232
+ mask = self.expanded_mask() > 0.0
233
+ return Sequence(
234
+ tf.where(mask, self.values, tf.zeros([], dtype=self.values.dtype)),
235
+ self.mask,
236
+ )
237
+
238
+ def expanded_mask(self) -> tf.Tensor:
239
+ """Returns mask reshaped to the same rank as values."""
240
+ with tf.name_scope('Sequence.expanded_mask'):
241
+ return expand_to_rank(self.mask, len(self.values.shape))
242
+
243
+ def concatenate(self, other: 'Sequence') -> 'Sequence':
244
+ with tf.name_scope('Sequence.concatenate'):
245
+ values = tf.concat([self.values, other.values], axis=1)
246
+ mask = tf.concat([self.mask, other.mask], axis=1)
247
+ return Sequence(values, mask)
248
+
249
+ def __getitem__(
250
+ self, the_slice: Union[slice, tuple[slice], tuple[slice, slice]]
251
+ ) -> 'Sequence':
252
+ """Slices the Sequence values and mask with the provided slice."""
253
+ if isinstance(the_slice, slice):
254
+ the_slice = (the_slice,)
255
+ if len(the_slice) > 2:
256
+ raise ValueError(
257
+ 'sl.Sequence[...] can only be used for slicing the sequence batch '
258
+ 'and time dimension. Use apply_values to slice channels dimensions. '
259
+ 'Got: %s'
260
+ % repr(the_slice)
261
+ )
262
+ if not all(isinstance(dim, slice) for dim in the_slice):
263
+ raise ValueError(
264
+ 'sl.Sequence[...] must only be used to slice, not index. Got: %s'
265
+ % repr(the_slice)
266
+ )
267
+ return Sequence(
268
+ self.values.__getitem__(the_slice), self.mask.__getitem__(the_slice)
269
+ )
270
+
271
+ def pad_time(
272
+ self,
273
+ pad_left: Union[int, tf.Tensor],
274
+ pad_right: Union[int, tf.Tensor],
275
+ valid: bool,
276
+ pad_value=0,
277
+ ) -> 'Sequence':
278
+ """Pads this sequence with timesteps on the left and right."""
279
+ with tf.name_scope('Sequence.pad_time'):
280
+ values_rank = len(self.values.shape)
281
+ values = tf.pad(
282
+ self.values,
283
+ [[0, 0], [pad_left, pad_right]] + [[0, 0]] * (values_rank - 2),
284
+ constant_values=tf.cast(pad_value, self.values.dtype),
285
+ )
286
+ mask = tf.pad(
287
+ self.mask,
288
+ [[0, 0], [pad_left, pad_right]],
289
+ constant_values=tf.cast(1.0 if valid else 0.0, self.mask.dtype),
290
+ )
291
+ return Sequence(values, mask)
292
+
293
+ def reverse_time(self) -> 'Sequence':
294
+ with tf.name_scope('Sequence.reverse_time'):
295
+ return Sequence(
296
+ tf.reverse(self.values, axis=[1], name='values'),
297
+ tf.reverse(self.mask, axis=[1], name='mask'),
298
+ )
299
+
300
+ def print(self, message=None, summarize=None):
301
+ """Prints this Sequence with an optional message."""
302
+ with tf.name_scope('Sequence.print'):
303
+ values = [self.values, self.mask]
304
+ if message:
305
+ values.append(message)
306
+ # If in Eager mode or within a tf.function this print happens
307
+ # automatically. In TF1 Graph mode, we need a control dependency to make
308
+ # sure it runs.
309
+ print_op = tf.print(*values, summarize=summarize)
310
+ # Ensure that touching either values or mask causes the print.
311
+ with tf.control_dependencies([print_op]):
312
+ return Sequence(tf.identity(self.values), tf.identity(self.mask))
313
+
314
+ def to_spec(self):
315
+ """Returns a Sequence with values/mask replaced with TensorSpecs."""
316
+ return Sequence(
317
+ tf.TensorSpec.from_tensor(self.values),
318
+ tf.TensorSpec.from_tensor(self.mask),
319
+ )
320
+
321
+ @property
322
+ def channel_shape(self) -> tf.TensorShape:
323
+ """Returns the sequence's channel shape (i.e. excluding batch and time)."""
324
+ return tf.TensorShape(self.values.shape[2:])
325
+
326
+ @property
327
+ def dtype(self) -> tf.DType:
328
+ """Returns the values dtype."""
329
+ return self.values.dtype
330
+
331
+ @property
332
+ def channel_spec(self) -> tf.TensorSpec:
333
+ """Returns the sequence's channel spec (i.e. excluding batch and time)."""
334
+ return tf.TensorSpec(self.channel_shape, self.values.dtype)
335
+
336
+ def __len__(self):
337
+ """Workaround to enable nest.assert_shallow_structure compatibility."""
338
+ # nest.assert_shallow_structure assumes __len__ is implemented, even though
339
+ # it supports attr.s which does not define a __len__.
340
+ return 2
341
+
342
+
343
+ type_spec.register_type_spec_from_value_converter(
344
+ Sequence, SequenceSpec.from_sequence
345
+ )
346
+
347
+
348
+ # TODO(dthkao): This should inherit from internal.SequenceArray, but
349
+ # NamedTuples and ABCs do not play nicely.
350
+ class SequenceArray(NamedTuple):
351
+ """A SequenceArray is a TensorArray for sl.Sequences.
352
+
353
+ Typically used to dynamically concatenate Sequences of fixed length into a
354
+ single Sequence in a loop. For example:
355
+
356
+ sa = sl.SequenceArray.new(tf.float32, size=num_steps)
357
+ for i in range(num_steps):
358
+ input_block = inputs[:, i * layer.block_size:(i + 1) * layer.block_size]
359
+ output, state = layer.step(input_block, state, training=False)
360
+ sa = sa.write(i, output)
361
+ result = sa.concat()
362
+
363
+ The size of a SequenceArray is the number of Sequence blocks that can be
364
+ written to the SequenceArray, not the total length of the resulting Sequence
365
+ returned from concat.
366
+ """
367
+
368
+ values: tf.TensorArray
369
+ mask: tf.TensorArray
370
+
371
+ @classmethod
372
+ def new(
373
+ cls,
374
+ dtype: tf.DType,
375
+ size: tf.Tensor | None = None,
376
+ dynamic_size: bool | None = None,
377
+ ) -> 'SequenceArray':
378
+ """Constructs a new SequenceArray.
379
+
380
+ Args:
381
+ dtype: The dtype of the Sequence's values.
382
+ size: The number of Sequence blocks that will be written to this
383
+ SequenceArray.
384
+ dynamic_size: Whether the array should dynamically grow if write indices
385
+ exceed size.
386
+
387
+ Returns:
388
+ A SequenceArray containing TensorArrays for the Sequence values and mask.
389
+ """
390
+ return SequenceArray(
391
+ tf.TensorArray(dtype, size=size, dynamic_size=dynamic_size),
392
+ tf.TensorArray(MASK_DTYPE, size=size, dynamic_size=dynamic_size),
393
+ )
394
+
395
+ def write(self, index: tf.Tensor, sequence: Sequence) -> 'SequenceArray':
396
+ """Writes the provided Sequence to the specified index.
397
+
398
+ Args:
399
+ index: An integer Tensor indicating the index to write to.
400
+ sequence: A Sequence to write.
401
+
402
+ Returns:
403
+ A new SequenceArray object that ensures the write occurs. Use this object
404
+ for all subsequent operations.
405
+ """
406
+ return SequenceArray(
407
+ self.values.write(index, sequence.values),
408
+ self.mask.write(index, sequence.mask),
409
+ )
410
+
411
+ def concat(self) -> Sequence:
412
+ """Concatenates the Sequences written to this SequenceArray together."""
413
+ values = self.values.stack() # [steps, batch, time, ...]
414
+ mask = self.mask.stack() # [steps, batch, time]
415
+
416
+ def to_batch_major_and_reshape(t):
417
+ shape = t.shape.as_list()
418
+ if not t.shape.is_fully_defined():
419
+ dynamic_shape = tf.shape(t)
420
+ shape = [
421
+ dim if dim else dynamic_shape[i] for i, dim in enumerate(shape)
422
+ ]
423
+ batch_major = tf.transpose(t, [1, 0] + list(range(2, t.shape.rank)))
424
+ return tf.reshape(batch_major, [shape[1], -1] + shape[3:])
425
+
426
+ # Transpose to [batch, steps, time, ...] and collapse steps/time.
427
+ return Sequence(
428
+ to_batch_major_and_reshape(values), to_batch_major_and_reshape(mask)
429
+ )
430
+
431
+
432
+ class SequenceLayer(tf.Module, internal.SequenceLayer, metaclass=abc.ABCMeta):
433
+ """A sequence processing layer that can be executed layerwise or stepwise.
434
+
435
+ Step-wise execution:
436
+
437
+ A SequenceLayer supports step-wise execution if its `supports_step` property
438
+ is true. Most built-in SequenceLayers support step-wise processing by default,
439
+ but may support processing features that are not causal and therefore cannot
440
+ be executed step-by-step (e.g. non-causal convolutions, bidirectional RNNs,
441
+ etc.).
442
+
443
+ When executing step-wise, use the `step` or `step_with_emits` method to
444
+ process a block of inputs (a `Sequence` shaped `[b, block_size * n, ...]`) and
445
+ a `state` input whose structure matches `get_initial_state`.
446
+
447
+ This produces:
448
+ - An output `Sequence` shaped `[b, block_size * n * output_ratio, ...]`
449
+ whose `...` shape matches `get_output_shape`.
450
+ - A `state` output whose structure matches `get_initial_state`.
451
+ - (Optionally) an `emits` output whose structure/specs match `get_emit_specs`.
452
+
453
+ The output `Sequence` is the primary output of the step, while the `emits`
454
+ represent "auxiliary" outputs that are produced by the layer (for example,
455
+ debug output).
456
+
457
+ Layer-wise execution:
458
+
459
+ When executing layer-wise, use the `layer` or `layer_with_emits` method to
460
+ process inputs (a `Sequence` shaped `[b, t, ...]`).
461
+
462
+ This produces:
463
+ - An output `Sequence` shaped `[b, t * output_ratio, ...]`
464
+ whose `...` shape matches `get_output_shape`.
465
+ - (Optionally) an `emits` output whose structure/specs match `get_emit_specs`.
466
+
467
+ The output `Sequence` is the primary output of the layer, while the `emits`
468
+ represent "auxiliary" outputs that are produced by the layer (for example,
469
+ debug output).
470
+ """
471
+
472
+ def __init__(self, name=None):
473
+ # Imitate how Keras layers work by creating a unique name from the class
474
+ # name when no layer name is provided.
475
+ if not name:
476
+ name = tf_keras.src.backend.unique_object_name(
477
+ self._default_name(),
478
+ zero_based=True,
479
+ namespace='audio_hearing_tensorflow_python_sequence_layers',
480
+ )
481
+ super().__init__(name=name)
482
+
483
+ def supports_step(self) -> bool:
484
+ """Returns whether this layer supports the SequenceLayer.step method."""
485
+ return True
486
+
487
+ @abc.abstractmethod
488
+ def step(
489
+ self,
490
+ x: Sequence,
491
+ state: State,
492
+ training: bool,
493
+ constants: Constants | None = None,
494
+ ) -> tuple[Sequence, State]:
495
+ """Process this layer step-wise.
496
+
497
+ If `supports_step` is False, it is an error to call this function and
498
+ incorrect behavior will result.
499
+
500
+ Args:
501
+ x: Input sequence with values shaped [b, t_i, ...], where t_i is a
502
+ multiple of block_size.
503
+ state: A structure of state tensors matching get_initial_state. The
504
+ previous state for this layer.
505
+ training: Python bool. Whether we are in training mode.
506
+ constants: A dictionary of constant name to tf.Tensor or sl.Sequence.
507
+ Values or sequences that are "constant" with respect to the
508
+ SequenceLayer, but may affect its processing. For example, for an
509
+ Attention layer this may contain the key/value sequence to attend to.
510
+
511
+ Returns:
512
+ y: The outputs corresponding to this step with values shaped [b, t_o, ...]
513
+ where `t_o == t_i * output_ratio`.
514
+ state: A structure of state tensors matching get_initial_state. The
515
+ new state for this layer.
516
+ """
517
+ pass
518
+
519
+ # Despite calling the parent directly, the type annotations in this method
520
+ # definition are more specific
521
+ def step_with_emits( # pylint: disable=useless-parent-delegation
522
+ self,
523
+ x: Sequence,
524
+ state: State,
525
+ training: bool,
526
+ constants: Constants | None = None,
527
+ ) -> tuple[Sequence, State, Emits]:
528
+ """Process this layer step-wise, producing emitted tensors.
529
+
530
+ This is like `step`, except it has an additional return value which is the
531
+ "emitted" tensors for the step. The emitted tensors are a structure of
532
+ tensors whose spec matches the return value of `get_emit_specs` and whose
533
+ values are `tf.Tensors` or `Sequence`s.
534
+
535
+ Args:
536
+ x: Input sequence with values shaped [b, t_i, ...], where t_i is a
537
+ multiple of block_size.
538
+ state: A structure of state tensors matching get_initial_state. The
539
+ previous state for this layer.
540
+ training: Python bool. Whether we are in training mode.
541
+ constants: A dictionary of constant name to tf.Tensor or sl.Sequence.
542
+ Values or sequences that are "constant" with respect to the
543
+ SequenceLayer, but may affect its processing. For example, for an
544
+ Attention layer this may contain the key/value sequence to attend to.
545
+
546
+ Returns:
547
+ y: The outputs corresponding to this step with values shaped [b, t_o, ...]
548
+ where `t_o == t_i * output_ratio`.
549
+ state: A structure of state tensors matching get_initial_state. The
550
+ new state for this layer.
551
+ emits: A nest of emitted tensors or Sequences. The nest structure and
552
+ tensor specs match `get_emit_specs`.
553
+ """
554
+ return super().step_with_emits(x, state, training, constants)
555
+
556
+ @abc.abstractmethod
557
+ def layer(
558
+ self,
559
+ x: Sequence,
560
+ training: bool,
561
+ initial_state: State | None = None,
562
+ constants: Constants | None = None,
563
+ ) -> Sequence:
564
+ """Process this layer layer-wise.
565
+
566
+ Args:
567
+ x: Input sequence with values shaped [b, t_i, ...].
568
+ training: Python bool. Whether we are in training mode.
569
+ initial_state: A structure of state tensors matching get_initial_state.
570
+ The initial state to use for this layer.
571
+ constants: A dictionary of constant name to tf.Tensor or sl.Sequence.
572
+ Values or sequences that are "constant" with respect to the
573
+ SequenceLayer, but may affect its processing. For example, for an
574
+ Attention layer this may contain the key/value sequence to attend to.
575
+
576
+ Returns:
577
+ y: The outputs corresponding to this layer with values shaped
578
+ [b, t_o, ...] where `t_o == t_i * output_ratio`. t_o may have been
579
+ truncated to only represent valid frames.
580
+ """
581
+ pass
582
+
583
+ # Despite calling the parent directly, the type annotations in this method
584
+ # definition are more specific
585
+ def layer_with_emits( # pylint: disable=useless-parent-delegation
586
+ self,
587
+ x: Sequence,
588
+ training: bool,
589
+ initial_state: State | None = None,
590
+ constants: Constants | None = None,
591
+ ) -> tuple[Sequence, Emits]:
592
+ """Process this layer layer-wise, producing emitted tensors.
593
+
594
+ This is like `layer`, except it has an additional return value which is the
595
+ "emitted" tensors for the laeyr. The emitted tensors are a structure of
596
+ tensors whose spec matches the return value of `get_emit_specs` and whose
597
+ values are `tf.Tensors` or `Sequence`s.
598
+
599
+ Args:
600
+ x: Input sequence with values shaped [b, t_i, ...].
601
+ training: Python bool. Whether we are in training mode.
602
+ initial_state: A structure of state tensors matching get_initial_state.
603
+ The initial state to use for this layer.
604
+ constants: A dictionary of constant name to tf.Tensor or sl.Sequence.
605
+ Values or sequences that are "constant" with respect to the
606
+ SequenceLayer, but may affect its processing. For example, for an
607
+ Attention layer this may contain the key/value sequence to attend to.
608
+
609
+ Returns:
610
+ y: The outputs corresponding to this layer with values shaped
611
+ [b, t_o, ...] where `t_o == t_i * output_ratio`. t_o may have been
612
+ truncated to only represent valid frames.
613
+ emits: A nest of emitted tensors or Sequences. The nest structure and
614
+ tensor specs match `get_emit_specs`.
615
+ """
616
+ return super().layer_with_emits(x, training, initial_state, constants)
617
+
618
+ @abc.abstractmethod
619
+ def get_initial_state(
620
+ self, x: Sequence, constants: Constants | None = None
621
+ ) -> State:
622
+ """Returns the initial state for this SequenceLayer.
623
+
624
+ Args:
625
+ x: Sequence. A representative input sequence. Do not rely on its values,
626
+ just shape.
627
+ constants: A dictionary of constant name to tf.Tensor or sl.Sequence.
628
+ Values or sequences that are "constant" with respect to the
629
+ SequenceLayer, but may affect its processing. For example, for an
630
+ Attention layer this may contain the key/value sequence to attend to.
631
+
632
+ Returns:
633
+ An integer, TensorShape or structure of integer/TensorShapes.
634
+ """
635
+ pass
636
+
637
+ # Despite calling the parent directly, the type annotations in this method
638
+ # definition are more specific
639
+ def get_output_shape_for_sequence( # pylint: disable=useless-parent-delegation
640
+ self, x: Sequence, constants: Constants | None = None
641
+ ) -> tf.TensorShape:
642
+ """Returns the output shape this layer produces for the provided Sequence.
643
+
644
+ A convenience wrapper around get_output_shape.
645
+
646
+ Args:
647
+ x: Sequence. An input sequence.
648
+ constants: A dictionary of constant name to tf.Tensor or sl.Sequence.
649
+ Values or sequences that are "constant" with respect to the
650
+ SequenceLayer, but may affect its processing. For example, for an
651
+ Attention layer this may contain the key/value sequence to attend to.
652
+
653
+ Returns:
654
+ A TensorShape representing the channels dimensions (i.e. not including the
655
+ batch or time dimension).
656
+ """
657
+ return super().get_output_shape_for_sequence(x, constants)
658
+
659
+ def get_output_spec_for_sequence(
660
+ self, x: Sequence, constants: Constants | None = None
661
+ ) -> tf.TensorSpec:
662
+ """Returns the output spec this layer produces for the provided Sequence.
663
+
664
+ A convenience wrapper around get_output_spec.
665
+
666
+ Args:
667
+ x: Sequence. An input sequence.
668
+ constants: A dictionary of constant name to tf.Tensor or sl.Sequence.
669
+ Values or sequences that are "constant" with respect to the
670
+ SequenceLayer, but may affect its processing. For example, for an
671
+ Attention layer this may contain the key/value sequence to attend to.
672
+
673
+ Returns:
674
+ A TensorSpec whose shape represents the channels dimensions (i.e. not
675
+ including the batch or time dimension).
676
+ """
677
+ return self.get_output_spec(
678
+ tf.TensorSpec(x.channel_shape, x.dtype), constants=constants
679
+ )
680
+
681
+ @abc.abstractmethod
682
+ def get_output_shape(
683
+ self, input_shape: tf.TensorShape, constants: Constants | None = None
684
+ ) -> tf.TensorShape:
685
+ """Returns the output shape this layer produces for an input shape.
686
+
687
+ Args:
688
+ input_shape: A TensorShape representing the channels dimension of the
689
+ input sequence (i.e. not including the batch or time dimension).
690
+ constants: A dictionary of constant name to tf.Tensor or sl.Sequence.
691
+ Values or sequences that are "constant" with respect to the
692
+ SequenceLayer, but may affect its processing. For example, for an
693
+ Attention layer this may contain the key/value sequence to attend to.
694
+
695
+ Returns:
696
+ A TensorShape representing the channels dimensions (i.e. not including the
697
+ batch or time dimension).
698
+ """
699
+ pass
700
+
701
+ def get_output_spec(
702
+ self, input_spec: tf.TensorSpec, constants: Constants | None = None
703
+ ) -> tf.TensorSpec:
704
+ """Returns the output spec this layer produces for an input spec.
705
+
706
+ Args:
707
+ input_spec: A TensorSpec whose shape represents the channels dimension of
708
+ the input sequence (i.e. not including the batch or time dimension).
709
+ constants: A dictionary of constant name to tf.Tensor or sl.Sequence.
710
+ Values or sequences that are "constant" with respect to the
711
+ SequenceLayer, but may affect its processing. For example, for an
712
+ Attention layer this may contain the key/value sequence to attend to.
713
+
714
+ Returns:
715
+ A TensorSpec representing the channels dimensions (i.e. not including the
716
+ batch or time dimension).
717
+ """
718
+ return tf.TensorSpec(
719
+ self.get_output_shape(input_spec.shape, constants),
720
+ self.get_output_dtype(input_spec.dtype),
721
+ )
722
+
723
+ def get_emit_specs(
724
+ self, input_spec: tf.TensorSpec, constants: Constants | None = None
725
+ ) -> EmitSpecs:
726
+ """Returns the emit specs this layer produces for an input spec.
727
+
728
+ Args:
729
+ input_spec: A TensorSpec whose shape represents the channels dimension of
730
+ the input sequence (i.e. not including the batch or time dimension).
731
+ constants: A dictionary of constant name to tf.Tensor or sl.Sequence.
732
+ Values or sequences that are "constant" with respect to the
733
+ SequenceLayer, but may affect its processing. For example, for an
734
+ Attention layer this may contain the key/value sequence to attend to.
735
+
736
+ Returns:
737
+ A nest of TensorSpec whose structure matches the emit structure
738
+ returned from `layer_with_emits` or `step_with_emits`. Shapes represent
739
+ the channels dimensions (i.e. not including the batch or time dimension).
740
+ """
741
+ del input_spec
742
+ del constants
743
+ return ()
744
+
745
+ def get_emit_specs_for_sequence(
746
+ self, x: Sequence, constants: Constants | None = None
747
+ ) -> EmitSpecs:
748
+ """Returns the emit specs this layer produces for the provided Sequence.
749
+
750
+ A convenience wrapper around get_emit_specs.
751
+
752
+ Args:
753
+ x: Sequence. An input sequence.
754
+ constants: A dictionary of constant name to tf.Tensor or sl.Sequence.
755
+ Values or sequences that are "constant" with respect to the
756
+ SequenceLayer, but may affect its processing. For example, for an
757
+ Attention layer this may contain the key/value sequence to attend to.
758
+
759
+ Returns:
760
+ A nest of TensorSpec whose structure matches that of the emit structure
761
+ returned from layer_with_emits or step_with_emits. Shapes represent the
762
+ channels dimensions (i.e. not including the batch or time dimension).
763
+ """
764
+ return self.get_emit_specs(
765
+ tf.TensorSpec(x.channel_shape, x.values.dtype), constants=constants
766
+ )
767
+
768
+ # Despite calling the parent directly, the type annotations in this method
769
+ # definition are more specific
770
+ def get_output_dtype(self, input_dtype: tf.DType) -> tf.DType: # pylint: disable=useless-parent-delegation
771
+ """Returns the layer's output dtype."""
772
+ return super().get_output_dtype(input_dtype)
773
+
774
+ # Despite calling the parent directly, the type annotations in this method
775
+ # definition are more specific
776
+ def _yield_emits( # pylint: disable=useless-parent-delegation
777
+ self, emits: Emits
778
+ ) -> Generator[tuple['SequenceLayer', Emits], None, None]:
779
+ """Yields (layer, emits) tuples to allow associating emits with layers."""
780
+ yield from super()._yield_emits(emits)
781
+
782
+
783
+ class PreservesShape:
784
+ """A mix-in for layers that do not change the input shape."""
785
+
786
+ def get_output_shape(
787
+ self, input_shape: tf.TensorShape, constants: Constants | None = None
788
+ ) -> tf.TensorShape:
789
+ del constants
790
+ if not input_shape.is_fully_defined():
791
+ raise ValueError(
792
+ '%s depends on input shape, but input has unknown '
793
+ 'channels dimension: %s' % (self, input_shape)
794
+ )
795
+ return input_shape
796
+
797
+
798
+ class Emitting(SequenceLayer, internal.Emitting, metaclass=abc.ABCMeta):
799
+ """A SequenceLayer that emits auxiliary tensors.
800
+
801
+ This is a convenience subclass that implements step and layer in terms of
802
+ step_with_emits and layer_with_emits, so that implementors need only implement
803
+ two of the four methods. For emits that are substantially expensive to compute
804
+ subclasses can choose to implement all four and save computation in those that
805
+ do not produce emits.
806
+ """
807
+
808
+ @tf.Module.with_name_scope
809
+ def step(
810
+ self, x, state, training, constants: Constants | None = None
811
+ ) -> tuple[Sequence, State]:
812
+ output, state, _ = self.step_with_emits(x, state, training, constants)
813
+ return output, state
814
+
815
+ @abc.abstractmethod
816
+ def step_with_emits(
817
+ self,
818
+ x: Sequence,
819
+ state: State,
820
+ training: bool,
821
+ constants: Constants | None = None,
822
+ ) -> tuple[Sequence, State, Emits]:
823
+ pass
824
+
825
+ @tf.Module.with_name_scope
826
+ def layer(
827
+ self,
828
+ x: Sequence,
829
+ training: bool,
830
+ initial_state: State | None = None,
831
+ constants: Constants | None = None,
832
+ ) -> Sequence:
833
+ outputs, _ = self.layer_with_emits(x, training, initial_state, constants)
834
+ return outputs
835
+
836
+ @abc.abstractmethod
837
+ def layer_with_emits(
838
+ self,
839
+ x: Sequence,
840
+ training: bool,
841
+ initial_state: State | None = None,
842
+ constants: Constants | None = None,
843
+ ) -> tuple[Sequence, Emits]:
844
+ pass
845
+
846
+ @abc.abstractmethod
847
+ def get_emit_specs(
848
+ self, input_spec: tf.TensorShape, constants: Constants | None = None
849
+ ) -> EmitSpecs:
850
+ pass
851
+
852
+
853
+ class Stateless(SequenceLayer):
854
+ """A SequenceLayer with no state.
855
+
856
+ Sub-classes must only implement:
857
+ - layer
858
+ - get_output_shape
859
+ """
860
+
861
+ @tf.Module.with_name_scope
862
+ def step(
863
+ self,
864
+ x: Sequence,
865
+ state: State,
866
+ training: bool,
867
+ constants: Constants | None = None,
868
+ ) -> tuple[Sequence, State]:
869
+ return (
870
+ self.layer(x, training, initial_state=state, constants=constants),
871
+ state,
872
+ )
873
+
874
+ def get_initial_state(
875
+ self, x: Sequence, constants: Constants | None = None
876
+ ) -> State:
877
+ return ()
878
+
879
+
880
+ class StatelessEmitting(Emitting):
881
+ """A SequenceLayer with no state that emits auxiliary tensors.
882
+
883
+ Sub-classes must only implement:
884
+ - layer_with_emits
885
+ - get_output_shape
886
+ - get_emit_specs
887
+ """
888
+
889
+ @tf.Module.with_name_scope
890
+ def step_with_emits(
891
+ self,
892
+ x: Sequence,
893
+ state: State,
894
+ training: bool,
895
+ constants: Constants | None = None,
896
+ ) -> tuple[Sequence, State, Emits]:
897
+ outputs, emits = self.layer_with_emits(
898
+ x, training, initial_state=state, constants=constants
899
+ )
900
+ return outputs, state, emits
901
+
902
+ def get_initial_state(
903
+ self, x: Sequence, constants: Constants | None = None
904
+ ) -> State:
905
+ return ()
906
+
907
+
908
+ class StatelessPointwise(PreservesShape, Stateless):
909
+ """A SequenceLayer that operates pointwise (per-scalar) on its input."""
910
+
911
+
912
+ class StatelessPointwiseFunctor(StatelessPointwise, metaclass=abc.ABCMeta):
913
+ """A stateless SequenceLayer for simple pointwise processing fns."""
914
+
915
+ def __init__(self, name=None):
916
+ super().__init__(name=name)
917
+
918
+ @abc.abstractmethod
919
+ def fn(
920
+ self, values: tf.Tensor, mask: tf.Tensor
921
+ ) -> tuple[tf.Tensor, tf.Tensor]:
922
+ pass
923
+
924
+ @tf.Module.with_name_scope
925
+ def layer(
926
+ self,
927
+ x: Sequence,
928
+ training: bool,
929
+ initial_state: State | None = None,
930
+ constants: Constants | None = None,
931
+ ) -> Sequence:
932
+ del training
933
+ del initial_state
934
+ return x.apply(self.fn).mask_invalid()
935
+
936
+
937
+ def expand_to_rank(t: tf.Tensor, rank: int) -> tf.Tensor:
938
+ # TODO(rryan): This iterative approach is tf.lite compatible and
939
+ # preserves shape information.. Using Tensor.__getitem__((Ellipsis, ...))
940
+ # would do it in one strided slice, but is not supported by tf.lite.
941
+ while len(t.shape) < rank:
942
+ t = tf.expand_dims(t, -1)
943
+ return t
944
+
945
+
946
+ def experimental_iterate_emits(
947
+ layer: SequenceLayer, emits: Emits
948
+ ) -> Generator[tuple[SequenceLayer, Emits], None, None]:
949
+ """Yields (layer, emits) tuples to allow associating emits with layers.
950
+
951
+ This enables associating emits in the structure of emits with specific layers
952
+ that produced the emits.
953
+
954
+ Args:
955
+ layer: SequenceLayer to iterate the emits for.
956
+ emits: The emits or emit specs associated with layer.
957
+
958
+ Yields:
959
+ (layer, emits) tuples for layer and all of its sublayers.
960
+ """
961
+ yield from layer._yield_emits(emits) # pylint: disable=protected-access