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,1537 @@
1
+ # Copyright 2024 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # https://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Basic sequence types."""
15
+
16
+ import abc
17
+ import dataclasses
18
+ import enum
19
+ import fractions
20
+ import functools
21
+ import math
22
+ import typing
23
+ from typing import Any, Callable, Generic, Iterable, Literal, MutableMapping, ParamSpec, Self, Sequence as TypingSequence, TypeVar
24
+
25
+ from absl import logging
26
+ from flax import linen as nn
27
+ from flax import struct
28
+ import jax
29
+ from jax import numpy as jnp
30
+ import jaxtyping
31
+ import numpy as np
32
+ from sequence_layers.jax import sharding as sharding_lib
33
+ from sequence_layers.jax import typing as jt
34
+ import typeguard
35
+
36
+
37
+ __all__ = (
38
+ # go/keep-sorted start
39
+ 'ArrayLike',
40
+ 'ChannelSpec',
41
+ 'Constants',
42
+ 'DType',
43
+ 'EinsumFactoryT',
44
+ 'Emits',
45
+ 'Emitting',
46
+ 'ExpandedMaskT',
47
+ 'MASK_DTYPE',
48
+ 'MaskT',
49
+ 'MaskedSequence',
50
+ 'PaddingMode',
51
+ 'PaddingModeString',
52
+ 'PreservesShape',
53
+ 'PreservesType',
54
+ 'Sequence',
55
+ 'SequenceLayer',
56
+ 'SequenceLayerConfig',
57
+ 'SequenceT',
58
+ 'Shape',
59
+ 'ShapeDType',
60
+ 'ShapeLike',
61
+ 'Sharding',
62
+ 'State',
63
+ 'Stateless',
64
+ 'StatelessEmitting',
65
+ 'StatelessPointwise',
66
+ 'StatelessPointwiseFunctor',
67
+ 'Steppable',
68
+ 'ValuesT',
69
+ 'check_layer',
70
+ 'check_layer_with_emits',
71
+ 'check_step',
72
+ 'check_step_with_emits',
73
+ 'validate_padding',
74
+ # go/keep-sorted end
75
+ )
76
+
77
+ UNCONSTRAINED = sharding_lib.UNCONSTRAINED
78
+ DimSharding = sharding_lib.DimSharding
79
+
80
+ # Sharding is the *args to jax.sharding.PartitionSpec.
81
+ Sharding = sharding_lib.Sharding
82
+
83
+ # Sequence type aliases:
84
+ MASK_DTYPE = np.bool_
85
+
86
+ # A rank 2+ tensor of any type.
87
+ ValuesT = TypeVar('ValuesT', bound=jt.Shaped[jt.ArrayT, 'B T *C'])
88
+
89
+ # A boolean batched mask tensor. True indicates a given timepoint is valid, and
90
+ # False indicates it is invalid.
91
+ MaskT = TypeVar('MaskT', bound=jt.Bool[jt.ArrayT, 'B T'])
92
+
93
+ # An integer batched lengths tensor.
94
+ LengthsT = TypeVar('LengthsT', bound=jt.Int[jt.ArrayT, 'B'])
95
+
96
+ # A rank 2 boolean tensor with unit dimensions inserted to match their
97
+ # corresponding values (e.g. for broadcasting).
98
+ ExpandedMaskT = TypeVar('ExpandedMaskT', bound=jt.Bool[jt.ArrayT, 'B T *C'])
99
+
100
+ # A "self" type alias to allow Sequence and subclasses to return their own
101
+ # Sequence subtype.
102
+ # TODO(rryan): Remove when PEP-0673 lands.
103
+ SequenceSelf = TypeVar('SequenceSelf', bound='Sequence')
104
+
105
+ # Args and keyword args for Sequence.apply_values.
106
+ ApplyValuesParams = ParamSpec('ApplyValuesParams')
107
+ ApplyValuesMaskedParams = ParamSpec('ApplyValuesMaskedParams')
108
+
109
+ # Args and keyword args for Sequence.apply.
110
+ ApplyParams = ParamSpec('ApplyParams')
111
+ ApplyMaskedParams = ParamSpec('ApplyMaskedParams')
112
+
113
+ # Einsum factory types.
114
+ JnpEinsumT = Callable[[str, Any, Any], Any]
115
+ EinsumFactoryT = Callable[..., JnpEinsumT]
116
+
117
+ # SequenceLayer type aliases:
118
+ State = jt.AnyPyTree
119
+ ShapeLike = list[int] | tuple[int, ...]
120
+ Shape = tuple[int, ...]
121
+ DType = np.dtype
122
+ ShapeDType = jax.ShapeDtypeStruct
123
+ Constants = MutableMapping[str, jt.AnyPyTree]
124
+ Emits = jt.AnyPyTree
125
+ ChannelSpec = ShapeDType
126
+ ArrayLike = jax.Array | jax.core.Tracer | jax.core.ShapedArray | np.ndarray
127
+ # Receptive field:
128
+ # - (past, future) integer input time steps.
129
+ # - Allow floats to accommodate -/+ inf indicating unlimited past/future.
130
+ # - None for cases with no receptive field.
131
+ ReceptiveField = tuple[float | int, float | int] | None
132
+
133
+ ARRAY_LIKE_TYPES = (
134
+ jax.Array,
135
+ jax.core.Tracer,
136
+ np.ndarray,
137
+ jax.core.ShapedArray,
138
+ )
139
+
140
+
141
+ class PaddingMode(enum.Enum):
142
+ """Supported padding modes."""
143
+
144
+ # In VALID padding mode, no padding is applied.
145
+ #
146
+ # Key properties:
147
+ # * The physical length of an input array to a VALID padded function shrinks,
148
+ # dropping any timesteps whose inputs are computed from implicit edge
149
+ # padding.
150
+ # * An output timestep is valid when all of its input timesteps are also
151
+ # valid.
152
+ VALID = 'valid'
153
+
154
+ # In SAME padding mode, the input sequence is padded such that the output
155
+ # length is equal to the input length before applying striding.
156
+ #
157
+ # Key properties:
158
+ # * The input length is equal to the output length, before applying striding.
159
+ # * Padding of `effective_kernel_size - 1` is applied. Half is applied to the
160
+ # front and half to the back. If `effective_kernel_size` is even, the extra
161
+ # padding is added to the end.
162
+ # * An output timestep is valid when its corresponding input timestep is
163
+ # valid.
164
+ SAME = 'same'
165
+
166
+ # In CAUSAL_VALID padding mode, the input sequence is padded such that the
167
+ # output length is equal to the input length before applying striding. Padding
168
+ # is applied such that the output timestep `to` can only depend on input
169
+ # timesteps at or before `ti` where `ti * output_ratio = to`.
170
+ #
171
+ # Key properties:
172
+ # * As in SAME padding, the input length is equal to the output length, before
173
+ # applying striding.
174
+ # * Padding of `effective_kernel_size - 1` is applied to the front of the
175
+ # sequence.
176
+ # * As in VALID padding, an output timestep is valid iff all of its input
177
+ # timesteps are also valid.
178
+ CAUSAL_VALID = 'causal_valid'
179
+
180
+ # In REVERSE_CAUSAL_VALID padding mode, the input sequence is padded such that
181
+ # the output length is equal to the input length before applying striding.
182
+ # Padding is applied such that the output timestep `to` can only depend on
183
+ # input timesteps at or after `ti` where `ti * output_ratio = to`.
184
+ #
185
+ # Key properties:
186
+ # * As in SAME padding, the input length is equal to the output length, before
187
+ # applying striding.
188
+ # * Padding of `effective_kernel_size - 1` is applied to the back of the
189
+ # sequence.
190
+ REVERSE_CAUSAL_VALID = 'reverse_causal_valid'
191
+
192
+ # In CAUSAL padding mode, the input sequence is padded such that the output
193
+ # length is equal to the input length before applying striding. Padding is
194
+ # applied such that the output timestep `to` can only depend on input
195
+ # timesteps at or before `ti` where `ti * output_ratio = to`.
196
+ #
197
+ # Key properties:
198
+ # * As in SAME padding, the input length is equal to the output length, before
199
+ # applying striding.
200
+ # * Padding of `effective_kernel_size - 1` is applied to the front of the
201
+ # sequence.
202
+ # * As in SAME padding, an output timestep is valid when its corresponding
203
+ # input timestep is valid.
204
+ CAUSAL = 'causal'
205
+
206
+ # In REVERSE_CAUSAL padding mode, the input sequence is padded such that the
207
+ # output length is equal to the input length before applying striding. Padding
208
+ # is applied such that the output timestep `to` can only depend on input
209
+ # timesteps at or after `ti` where `ti * output_ratio = to`.
210
+ #
211
+ # Key properties:
212
+ # * As in SAME padding, the input length is equal to the output length, before
213
+ # applying striding.
214
+ # * Padding of `effective_kernel_size - 1` is applied to the back of the
215
+ # sequence.
216
+ # * As in SAME padding, an output timestep is valid when its corresponding
217
+ # input timestep is valid.
218
+ REVERSE_CAUSAL = 'reverse_causal'
219
+
220
+ # In SEMICAUSAL padding mode, the input sequence is padded such that the
221
+ # output length is equal to the input length before applying striding. Padding
222
+ # is applied such that the output timestep `to` can only depend on input
223
+ # timesteps at or before `ti` where `ti * output_ratio = to`.
224
+ #
225
+ # Key properties:
226
+ # * As in SAME padding, the input length is equal to the output length, before
227
+ # applying striding.
228
+ # * Padding of `effective_kernel_size - stride` is applied to the front of the
229
+ # sequence, and padding of `stride - 1` timesteps is applied to the back of
230
+ # the sequence for a total of `effective_kernel_size - 1` timesteps of
231
+ # padding. If `effective_kernel_size` < `stride`, then padding of
232
+ # `effective_kernel_size - 1` is applied to the back of the sequence.
233
+ # * As in SAME padding, an output timestep is valid when its corresponding
234
+ # input timestep is valid.
235
+ SEMICAUSAL = 'semicausal'
236
+
237
+ # In SEMICAUSAL_FULL padding mode, the input sequence is padded such that the
238
+ # output of the corresponding overlap-add or transpose convolution is of the
239
+ # same size as the input sequence and perfect reconstruction can be achieved.
240
+ # The reconstructed signal is of the same length or of length rounded up to
241
+ # cover the full input sequence.
242
+ SEMICAUSAL_FULL = 'semicausal_full'
243
+
244
+
245
+ PaddingModeString = Literal[
246
+ 'valid',
247
+ 'same',
248
+ 'causal_valid',
249
+ 'reverse_causal_valid',
250
+ 'causal',
251
+ 'reverse_causal',
252
+ 'semicausal',
253
+ 'semicausal_full',
254
+ ]
255
+
256
+
257
+ def validate_padding(padding: str) -> PaddingModeString:
258
+ """Checks that the provided padding string matches the PaddingMode enum."""
259
+ if padding not in [mode.value for mode in PaddingMode]:
260
+ raise ValueError(
261
+ 'Expected padding of "valid", "same", "causal_valid",'
262
+ ' "reverse_causal_valid", "causal", "reverse_causal", or "semicausal".'
263
+ f' Got {padding}'
264
+ )
265
+ return typing.cast(PaddingModeString, padding)
266
+
267
+
268
+ def validate_explicit_padding(padding: TypingSequence[int]) -> tuple[int, int]:
269
+ """Checks that padding is a 2-element sequence of non-negative numbers."""
270
+ padding = tuple(padding)
271
+
272
+ if len(padding) != 2:
273
+ raise ValueError(
274
+ f'Expected explicit padding to be a 2 element sequence. Got: {padding}.'
275
+ )
276
+
277
+ if padding[0] < 0 or padding[1] < 0:
278
+ raise ValueError(
279
+ f'Expected explicit padding to be non-negative. Got: {padding}.'
280
+ )
281
+
282
+ return padding
283
+
284
+
285
+ def validate_receptive_field(receptive_field: ReceptiveField) -> None:
286
+ """Checks that the provided receptive field is valid."""
287
+ if receptive_field is None:
288
+ return
289
+ past, future = receptive_field
290
+ if past > future:
291
+ raise ValueError(f'Invalid receptive field: {past=} > {future=}.')
292
+ if isinstance(past, float) and not np.isinf(past):
293
+ raise ValueError(f'Invalid receptive field: non-inf float {past=}.')
294
+ if isinstance(future, float) and not np.isinf(future):
295
+ raise ValueError(f'Invalid receptive field: non-inf float {future=}.')
296
+
297
+
298
+ def validate_receptive_field_per_step(
299
+ receptive_field_per_step: dict[int, ReceptiveField],
300
+ ) -> None:
301
+ """Checks that the provided receptive field per step is valid."""
302
+ steps = sorted(receptive_field_per_step.keys())
303
+ if steps != list(range(len(steps))):
304
+ raise ValueError(
305
+ 'receptive field steps must be a contiguous range starting from 0:'
306
+ f' {steps=}'
307
+ )
308
+ for rf in receptive_field_per_step.values():
309
+ validate_receptive_field(rf)
310
+
311
+
312
+ def sequence_mask(lengths: LengthsT, maxlen: int) -> MaskT:
313
+ return (
314
+ jnp.arange(maxlen)[jnp.newaxis, :] < jnp.asarray(lengths)[:, jnp.newaxis]
315
+ )
316
+
317
+
318
+ class Sequence(Generic[ValuesT, MaskT], struct.PyTreeNode):
319
+ """A generic sequence container that preserves masking information."""
320
+
321
+ values: ValuesT
322
+ mask: MaskT
323
+
324
+ def __post_init__(self):
325
+ """Applies type and shape checks for values and mask."""
326
+ values_arraylike = isinstance(self.values, ARRAY_LIKE_TYPES)
327
+ mask_arraylike = isinstance(self.mask, ARRAY_LIKE_TYPES)
328
+
329
+ # NOTE: We can't have `tuple` in the bad types, as e.g. PartitionSpec
330
+ # inherits from it.
331
+ bad_types = (int, list, set, Sequence, MaskedSequence)
332
+ if isinstance(self.values, bad_types) or isinstance(self.mask, bad_types):
333
+ raise jaxtyping.TypeCheckError(
334
+ 'Sequence values and mask must be array-like. Got values:'
335
+ f' {type(self.values)} and mask: {type(self.mask)}'
336
+ )
337
+
338
+ if isinstance(self.values, ShapeDType) != isinstance(self.mask, ShapeDType):
339
+ raise jaxtyping.TypeCheckError(
340
+ 'Either Sequence values and mask must be either both ShapeDType or'
341
+ f' neither of them. Got values: {type(self.values)} and mask:'
342
+ f' {type(self.mask)}'
343
+ )
344
+
345
+ if not values_arraylike or not mask_arraylike:
346
+ # Avoid checking types if the values and mask are not array-like. This
347
+ # happens e.g. during various passes that JAX does during
348
+ # compilation/optimization.
349
+ return
350
+
351
+ # Check mask dtype is correct.
352
+ #
353
+ # Allow JAX float0 types, which are used in jvp/linearization of booleans.
354
+ # go/jax-integer-autodiff
355
+ if self.mask.dtype not in (MASK_DTYPE, jax.dtypes.float0):
356
+ raise jaxtyping.TypeCheckError(
357
+ f'Sequence mask dtype ({self.mask.dtype}) is not {MASK_DTYPE}.'
358
+ )
359
+
360
+ if self.mask.ndim < 2 or self.values.ndim < 2:
361
+ raise jaxtyping.TypeCheckError(
362
+ f'Expected values rank ({self.values.ndim}) and mask rank'
363
+ f' ({self.mask.ndim}) to be at least 2.'
364
+ )
365
+
366
+ # Since Sequence is a struct.PyTree, and we pass Sequence through
367
+ # transformations like scan, values and mask might get stacked to have a
368
+ # higher rank batch dimension. For this reason, all we do here is check that
369
+ # the values and mask shapes are coherent (mask shape is a prefix of values
370
+ # shape).
371
+ # TODO(rryan): We may want to allow broadcastable shapes at some point.
372
+ if self.values.shape[: self.mask.ndim] != self.mask.shape:
373
+ raise jaxtyping.TypeCheckError(
374
+ f'Sequence values shape ({self.values.shape}) does not match mask'
375
+ f' shape ({self.mask.shape}).'
376
+ )
377
+
378
+ @property
379
+ def shape(self) -> Shape:
380
+ """Returns the shape of the sequence values."""
381
+ return self.values.shape
382
+
383
+ @property
384
+ def ndim(self) -> int:
385
+ """Returns the rank of the sequence values."""
386
+ return self.values.ndim
387
+
388
+ @property
389
+ def channel_shape(self) -> Shape:
390
+ """Returns the channel shape (the shape without batch and time)."""
391
+ return self.values.shape[2:]
392
+
393
+ @property
394
+ def channel_spec(self) -> ChannelSpec:
395
+ """Returns a "spec" for this sequence (the channel shape and dtype)."""
396
+ return ChannelSpec(self.channel_shape, self.dtype)
397
+
398
+ @property
399
+ def dtype(self) -> DType:
400
+ """Returns the dtype of the sequence values."""
401
+ return self.values.dtype
402
+
403
+ @classmethod
404
+ def from_lengths(
405
+ cls, values: ValuesT, lengths: LengthsT, is_masked: bool = False
406
+ ) -> 'Sequence':
407
+ values = jnp.asarray(values)
408
+ mask = sequence_mask(lengths, maxlen=values.shape[1])
409
+ return MaskedSequence(values, mask) if is_masked else Sequence(values, mask)
410
+
411
+ @classmethod
412
+ def from_values(cls, values: ValuesT) -> 'MaskedSequence':
413
+ """Returns a MaskedSequence for values, assuming every timestep is valid."""
414
+ if values.ndim < 2:
415
+ raise ValueError(f'Expected {values.ndim=} to be at least 2.')
416
+ return MaskedSequence(values, jnp.ones(values.shape[:2], jnp.bool_))
417
+
418
+ @classmethod
419
+ def concatenate_sequences(cls, sequences: Iterable['Sequence']) -> 'Sequence':
420
+ """Concatenates sequences and their masks on the time axis."""
421
+ values = []
422
+ masks = []
423
+ all_masked = True
424
+ for sequence in sequences:
425
+ if not isinstance(sequence, MaskedSequence):
426
+ all_masked = False
427
+ values.append(sequence.values)
428
+ masks.append(sequence.mask)
429
+ if all_masked:
430
+ sequence_type = MaskedSequence
431
+ else:
432
+ sequence_type = Sequence
433
+ return sequence_type(
434
+ jnp.concatenate(values, axis=1), jnp.concatenate(masks, axis=1)
435
+ )
436
+
437
+ def expanded_mask(self) -> ExpandedMaskT:
438
+ """Returns the Sequence mask with dimensions expanded to match values."""
439
+ return self.mask.reshape(self.mask.shape + (1,) * (self.values.ndim - 2))
440
+
441
+ def concatenate(self, other: 'Sequence') -> 'Sequence':
442
+ """Concatenates this sequence with other on the time dimension."""
443
+ values = jnp.concatenate([self.values, other.values], axis=1)
444
+ mask = jnp.concatenate([self.mask, other.mask], axis=1)
445
+
446
+ # Preserve mask state if both sequences are masked.
447
+ return_type = type(self) if type(self) is type(other) else Sequence
448
+ return return_type(values, mask)
449
+
450
+ def apply_values(
451
+ self,
452
+ values_fn: Callable[..., ValuesT],
453
+ *args: ApplyValuesParams.args,
454
+ **kwargs: ApplyValuesParams.kwargs,
455
+ ) -> 'Sequence':
456
+ """Transforms values with values_fn, assuming result is unmasked."""
457
+ return Sequence(values_fn(self.values, *args, **kwargs), self.mask)
458
+
459
+ def apply_values_masked(
460
+ self: SequenceSelf,
461
+ values_fn: Callable[..., ValuesT],
462
+ *args: ApplyValuesMaskedParams.args,
463
+ **kwargs: ApplyValuesMaskedParams.kwargs,
464
+ ) -> SequenceSelf:
465
+ """Transforms values with values_fn, preserving masked state."""
466
+ return type(self)(values_fn(self.values, *args, **kwargs), self.mask)
467
+
468
+ def apply(
469
+ self,
470
+ apply_fn: Callable[..., tuple[ValuesT, MaskT]],
471
+ *args: ApplyParams.args,
472
+ **kwargs: ApplyParams.kwargs,
473
+ ) -> 'Sequence':
474
+ """Transforms values/mask with apply_fn, assuming result is unmasked."""
475
+ values, mask = apply_fn(self.values, self.mask, *args, **kwargs)
476
+ return Sequence(values, mask)
477
+
478
+ def apply_masked(
479
+ self: SequenceSelf,
480
+ apply_fn: Callable[..., tuple[ValuesT, MaskT]],
481
+ *args: ApplyMaskedParams.args,
482
+ **kwargs: ApplyMaskedParams.kwargs,
483
+ ) -> SequenceSelf:
484
+ """Transforms values/mask with apply_fn, preserving masked state."""
485
+ # TODO(rryan): Dig into bug preventing the use of
486
+ # Callable[Concatenate[ValuesT, MaskT, ApplyMaskedParams], tuple[ValuesT,
487
+ # MaskT]] for apply_fn.
488
+ values, mask = apply_fn(self.values, self.mask, *args, **kwargs)
489
+ return type(self)(values, mask)
490
+
491
+ def astype(
492
+ self: SequenceSelf,
493
+ dtype: DType | None,
494
+ ) -> SequenceSelf:
495
+ """Returns a copy of this sequence with its values cast to dtype."""
496
+ return type(self)(self.values.astype(dtype), self.mask)
497
+
498
+ def lengths(self) -> jt.Int[jt.ArrayT, 'B']:
499
+ """Returns the number of valid timesteps per batch item."""
500
+ return jnp.sum(self.mask.astype(jnp.int32), axis=1)
501
+
502
+ def __getitem__(
503
+ self: SequenceSelf,
504
+ the_slice: slice | tuple[int | slice | None | type(Ellipsis), ...],
505
+ ) -> SequenceSelf:
506
+ """Slices the Sequence values and mask with the provided slice."""
507
+ if isinstance(the_slice, slice):
508
+ the_slice = (the_slice,)
509
+ if not all(isinstance(dim, slice) for dim in the_slice[:2]):
510
+ raise ValueError(
511
+ 'Sequence[...] must only be used to slice, not index, batch and time '
512
+ 'dimensions. Got: %s'
513
+ % repr(the_slice)
514
+ )
515
+ return type(self)(
516
+ self.values.__getitem__(the_slice), self.mask.__getitem__(the_slice[:2])
517
+ )
518
+
519
+ def pad_time(
520
+ self: SequenceSelf,
521
+ pad_left: jt.ScalarInt,
522
+ pad_right: jt.ScalarInt,
523
+ valid: bool,
524
+ pad_value: jt.Scalar | None = None,
525
+ ) -> SequenceSelf:
526
+ """Pads this sequence with timesteps on the left and right.
527
+
528
+ Args:
529
+ pad_left: Amount to pad on the left.
530
+ pad_right: Amount to pad on the right.
531
+ valid: Whether padded values are considered valid (i.e. unmasked).
532
+ pad_value: An optional pad value to use for padding.
533
+
534
+ Returns:
535
+ A sequence of the same time with the padded values appended.
536
+ """
537
+ values_rank = self.values.ndim
538
+ pad_value = 0.0 if pad_value is None else pad_value
539
+ if not pad_left and not pad_right:
540
+ return self
541
+ values = jnp.pad(
542
+ self.values,
543
+ [[0, 0], [pad_left, pad_right]] + [[0, 0]] * (values_rank - 2),
544
+ constant_values=jnp.asarray(pad_value).astype(self.values.dtype),
545
+ )
546
+ mask = jnp.pad(
547
+ self.mask,
548
+ [[0, 0], [pad_left, pad_right]],
549
+ constant_values=valid,
550
+ )
551
+ return type(self)(values, mask)
552
+
553
+ def reverse_time(self: SequenceSelf) -> SequenceSelf:
554
+ """Reverses the sequence along the time dimension.
555
+
556
+ Note that this only reverses the physical array with no assumptions about
557
+ whether the sequence is contiguous / ragged.
558
+
559
+ Returns:
560
+ The sequence with values and mask reversed along the time dimension of the
561
+ physical array.
562
+ """
563
+ return type(self)(
564
+ jnp.flip(self.values, axis=1), jnp.flip(self.mask, axis=1)
565
+ )
566
+
567
+ def pad_to_multiple(self, block_size: jt.ScalarInt) -> SequenceSelf:
568
+ pad_length = (
569
+ self.shape[1] + block_size - 1
570
+ ) // block_size * block_size - self.shape[1]
571
+ return self.pad_time(pad_left=0, pad_right=pad_length, valid=False)
572
+
573
+ def mask_invalid(self, mask_value: complex | None = None) -> 'Sequence':
574
+ """Returns a sequence with invalid timesteps replaced with mask_value."""
575
+ raise NotImplementedError('Replaced below.')
576
+
577
+ def unmask(self) -> 'Sequence':
578
+ """Returns an unmasked version of this sequence with unchanged values."""
579
+ # We are already an unmasked sequence.
580
+ return self
581
+
582
+
583
+ class MaskedSequence(Sequence[ValuesT, MaskT]):
584
+ """Sequence whose invalid timesteps are masked to zero."""
585
+
586
+ def mask_invalid(self, mask_value: complex | None = None) -> 'Sequence':
587
+ """Returns a sequence with invalid timesteps replaced with mask_value."""
588
+ if mask_value is None:
589
+ return self
590
+ else:
591
+ return mask_invalid(self, mask_value)
592
+
593
+ def unmask(self) -> Sequence:
594
+ """Returns an unmasked version of this sequence with unchanged values."""
595
+ return Sequence(self.values, self.mask)
596
+
597
+
598
+ def mask_invalid(
599
+ sequence: Sequence,
600
+ mask_value: complex | None = None,
601
+ ) -> 'Sequence':
602
+ """Returns a sequence whose invalid timesteps are replaced with mask_value."""
603
+ expanded_mask = sequence.expanded_mask()
604
+ if mask_value is None:
605
+ masked_values = jnp.zeros_like(sequence.values)
606
+ result_type = MaskedSequence
607
+ else:
608
+ masked_values = jnp.full(
609
+ sequence.values.shape, mask_value, sequence.values.dtype
610
+ )
611
+ result_type = Sequence
612
+ masked_values = jnp.where(expanded_mask, sequence.values, masked_values)
613
+ return result_type(masked_values, sequence.mask)
614
+
615
+
616
+ # Defined outside of Sequence so that mask_invalid can return a MaskedSequence.
617
+ Sequence.mask_invalid = mask_invalid
618
+
619
+
620
+ class MetaSequenceT(type):
621
+ """A metaclass for SequenceT to support jaxtyping-style type parameters."""
622
+
623
+ def __getitem__(cls, item):
624
+ dtype, shape = item
625
+ axes = shape.split(' ')
626
+ if len(axes) < 2:
627
+ raise ValueError(
628
+ 'Shape spec must contain at least two components for the batch and'
629
+ f' time dimensions, got: {shape}.'
630
+ )
631
+
632
+ values_dtype = dtype[jt.ArrayT, shape]
633
+ batch_time = ' '.join(axes[:2])
634
+ mask_dtype = jt.Bool[jt.ArrayT, batch_time]
635
+ return (
636
+ Sequence[values_dtype, mask_dtype]
637
+ | MaskedSequence[values_dtype, mask_dtype]
638
+ )
639
+
640
+
641
+ class SequenceT(metaclass=MetaSequenceT):
642
+ pass
643
+
644
+
645
+ def _sequence_checker_fn(value, origin_type, args, memo):
646
+ """Checks that Sequence's values/mask adheres to the type spec."""
647
+ del origin_type
648
+
649
+ if not isinstance(value, Sequence):
650
+ raise TypeError(f'{value} is not a Sequence.')
651
+
652
+ values_dtype, mask_dtype = args
653
+
654
+ try:
655
+ typeguard.check_type_internal(
656
+ value.values,
657
+ values_dtype,
658
+ memo=memo,
659
+ )
660
+ except typeguard.TypeCheckError as exc:
661
+ exc.append_path_element('values')
662
+ raise
663
+
664
+ try:
665
+ typeguard.check_type_internal(
666
+ value.mask,
667
+ mask_dtype,
668
+ memo=memo,
669
+ )
670
+ except typeguard.TypeCheckError as exc:
671
+ exc.append_path_element('mask')
672
+ raise
673
+
674
+
675
+ def _sequence_checker_lookup_fn(
676
+ origin_type: Any, args: tuple[Any, ...], extras: tuple[Any, ...]
677
+ ):
678
+ """Lookup function to register Sequence type checker in typeguard."""
679
+ del args
680
+ del extras
681
+ return (
682
+ _sequence_checker_fn
683
+ if origin_type in (Sequence, MaskedSequence)
684
+ else None
685
+ )
686
+
687
+
688
+ def _add_custom_checker_lookup_fn(lookup_fn):
689
+ """Add custom Sequence checker lookup function to typeguard."""
690
+ if hasattr(typeguard, 'checker_lookup_functions'):
691
+ # Recent `typeguard` has different API.
692
+ checker_lookup_fns = typeguard.checker_lookup_functions
693
+ elif hasattr(typeguard, 'config'):
694
+ # TODO(rryan): Remove once typeguard is updated
695
+ checker_lookup_fns = typeguard.config.checker_lookup_functions
696
+ else:
697
+ # This typeguard version (e.g. 2.13.3) doesn't support custom checkers.
698
+ return
699
+ for i, f in enumerate(checker_lookup_fns):
700
+ # Check qualname instead of equality, to avoid many copies when reloading
701
+ # modules from colab.
702
+ if f.__qualname__ == lookup_fn.__qualname__:
703
+ # replace
704
+ checker_lookup_fns[i : i + 1] = [lookup_fn]
705
+ break
706
+ else: # prepend
707
+ checker_lookup_fns[:0] = [lookup_fn]
708
+
709
+
710
+ _add_custom_checker_lookup_fn(_sequence_checker_lookup_fn)
711
+
712
+
713
+ class Steppable(metaclass=abc.ABCMeta):
714
+ """A sequence processing layer that can be executed layerwise or stepwise.
715
+
716
+ # Step-wise execution:
717
+
718
+ A SequenceLayer supports step-wise execution if its `supports_step` property
719
+ is true. Most built-in SequenceLayers support step-wise processing by default,
720
+ but may support processing features that are not causal and therefore cannot
721
+ be executed step-by-step (e.g. non-causal convolutions, bidirectional RNNs,
722
+ etc.).
723
+
724
+ When executing step-wise, use the `step` or `step_with_emits` method to
725
+ process a block of inputs (a `Sequence` shaped `[b, block_size * n, ...]`) and
726
+ a `state` input whose structure matches `get_initial_state`.
727
+
728
+ This produces:
729
+ - An output `Sequence` shaped `[b, block_size * n * output_ratio, ...]`
730
+ whose `...` shape matches `get_output_shape`.
731
+ - A `state` output whose structure matches `get_initial_state`.
732
+ - (Optionally) an `emits` output.
733
+
734
+ The output `Sequence` is the primary output of the step, while the `emits`
735
+ represent "auxiliary" outputs that are produced by the layer (for example,
736
+ debug output).
737
+
738
+ # Layer-wise execution:
739
+
740
+ When executing layer-wise, use the `layer` or `layer_with_emits` method to
741
+ process inputs (a `Sequence` shaped `[b, t, ...]`).
742
+
743
+ This produces:
744
+ - An output `Sequence` shaped `[b, t * output_ratio, ...]`
745
+ whose `...` shape matches `get_output_shape`.
746
+ - (Optionally) an `emits` output.
747
+
748
+ The output `Sequence` is the primary output of the layer, while the `emits`
749
+ represent "auxiliary" outputs that are produced by the layer (for example,
750
+ debug output).
751
+
752
+ # Latency
753
+
754
+ SequenceLayers have an input and output "latency" to describe their latency
755
+ characteristics. Latency is the number of input or output timesteps from
756
+ step-wise excecution that are input or output before the step-wise output of
757
+ the layer matches the layer-wise output of the layer.
758
+
759
+ An invariant that all layers must maintain is that for the layer-wise output
760
+ and step-wise output:
761
+
762
+ ```
763
+ y_layer = l.layer(x, training=training)
764
+
765
+ # Pad x with input_latency timesteps to process the entire sequence:
766
+ x = x.pad_time(0, l.input_latency, valid=False)
767
+
768
+ y_step, _, _ = utils.step_by_step_dynamic(l, x, training=training)
769
+ ```
770
+
771
+ The step-wise output is equivalent to the layer-wise output after dropping the
772
+ initial latency timesteps of the step-wise output:
773
+
774
+ ```
775
+ y_layer == y_step[:, l.output_latency:]
776
+ ```
777
+ """
778
+
779
+ path: str # Provided by nn.Module.
780
+
781
+ @property
782
+ def block_size(self) -> int:
783
+ """The block size multiple required by the layer.
784
+
785
+ Sequences (`[b, t, ...]`) passed to `step` will come in multiples of
786
+ `block_size` timesteps. In other words, `t % block_size == 0`.
787
+
788
+ Returns:
789
+ The layer's block size.
790
+ """
791
+ return 1
792
+
793
+ @property
794
+ def output_ratio(self) -> fractions.Fraction:
795
+ """The number of output frames for one input frame."""
796
+ return fractions.Fraction(1)
797
+
798
+ @property
799
+ def supports_step(self) -> bool:
800
+ """Returns whether this layer supports the SequenceLayer.step method."""
801
+ return True
802
+
803
+ @property
804
+ def input_latency(self) -> int:
805
+ """Returns the input latency of this layer.
806
+
807
+ Input latency is defined as the number of input timesteps before the
808
+ step-wise output of the layer matches its layer-wise output.
809
+ """
810
+ return 0
811
+
812
+ @property
813
+ def output_latency(self) -> int:
814
+ """Returns the output latency of this layer.
815
+
816
+ Output latency is defined as the number of output timesteps before the
817
+ step-wise output of the layer matches its layer-wise output.
818
+ """
819
+ # Layers can only produce discrete delays, so truncate the output latency
820
+ # to integer here.
821
+ return int(self.input_latency * self.output_ratio)
822
+
823
+ def get_accumulated_input_latency(self, input_latency: int) -> int:
824
+ """Returns the accumulated input latency of this layer."""
825
+ return math.ceil(input_latency / self.output_ratio) + self.input_latency
826
+
827
+ def get_accumulated_output_latency(self, output_latency: int) -> int:
828
+ """Returns the accumulated output latency of this layer."""
829
+ output_ratio = self.output_ratio
830
+ if required_delay := -output_latency % (1 / output_ratio):
831
+ path = '/'.join(self.path)
832
+ raise ValueError(
833
+ f'Input to {self.__class__.__name__}(path={path!r}) has a step-wise'
834
+ f' incoming {output_latency=} which is not divisible'
835
+ f" by the layer's {output_ratio=}. Insert a delay of"
836
+ f' -output_latency % (1/output_ratio)={required_delay} before the'
837
+ ' layer to compensate.'
838
+ )
839
+
840
+ # After the above check, we know the accumulated output latency is divisible
841
+ # by the output ratio.
842
+ return int(output_latency * output_ratio) + self.output_latency
843
+
844
+ @property
845
+ def receptive_field(self) -> ReceptiveField:
846
+ """Returns the range of the receptive field of this layer.
847
+
848
+ A (past, future) tuple indicating the input time step range
849
+ `[ti + past, ti + future]` that affects the output step `to`, where `ti` is
850
+ the first step of the input block corresponding to `to`, i.e.,
851
+ `ti = to // output_ratio`.
852
+
853
+ For cases where the receptive field varies across steps, we return the
854
+ union of the receptive fields. For example, with 2x downsampling and 2x
855
+ upsampling, the receptive field is [0, 1] at even steps and [-1, 0] at odd
856
+ steps. This property would return [-1, 1]. The `receptive_field_per_step`
857
+ property is a helper to compute the overall receptive field of a layer and
858
+ the receptive field of a composition of layers.
859
+
860
+ Infinite receptive field is represtend with +/-np.inf. E.g., RNNs have
861
+ (-np.inf, 0) receptive field.
862
+
863
+ No receptive field is represented as None. E.g., Conv1DTranspose with
864
+ kernel_size=1, stirde=2, produces None receptive on every other steps.
865
+ """
866
+ # To avoid circular dependency, the logic here is copied from utils.py, can
867
+ # we dedup?
868
+ rf_per_step = self.receptive_field_per_step
869
+ validate_receptive_field_per_step(rf_per_step)
870
+
871
+ # Only pick the steps that have receptive field.
872
+ rf_list = {s: rf for s, rf in rf_per_step.items() if rf is not None}
873
+ if not rf_list:
874
+ # No receptive field if all steps have no receptive field.
875
+ return None
876
+
877
+ # Compute the overall union of the receptive fields.
878
+ min_past = np.inf
879
+ max_future = -np.inf
880
+ output_ratio = self.output_ratio
881
+ for output_step, (past, future) in rf_list.items():
882
+ input_step = output_step // output_ratio
883
+ past -= input_step
884
+ future -= input_step
885
+ min_past = min(min_past, past)
886
+ max_future = max(max_future, future)
887
+ return min_past, max_future
888
+
889
+ # Should we cache this property? To compute the overall receptive field of a
890
+ # a composition of layers, we traverse all the possible paths to the input
891
+ # sequence in a brute force BFS manner. To avoid recomputing this property
892
+ # over and over, we can cache it.
893
+ @property
894
+ def receptive_field_per_step(self) -> dict[int, ReceptiveField]:
895
+ """Returns the range of the receptive field of this layer per step.
896
+
897
+ For the cases that receptive field varies across steps, and repeats every
898
+ `n` steps, this property provides the per step receptive field, where steps
899
+ should be a contiguous range starting from 0. E.g., with 2x down-sampling
900
+ and 2x up-sampling, the receptive field at even steps is [0, 1] and at odd
901
+ steps is [-1, 0], so we get {0: [-1, 1], 1: [0, 1]}.
902
+
903
+ This serves as a helper to compute the overall receptive field of the layer
904
+ and the receptive field of composition of layers.
905
+
906
+ In most layers, the receptive field does not vary across steps, and this
907
+ property returns a single receptive field for step 0, i.e., {0: (p, f)}.
908
+ """
909
+ layer_name = type(self).__name__
910
+ raise NotImplementedError(
911
+ f'receptive_field_per_step is not implemented by {layer_name}'
912
+ )
913
+
914
+ @abc.abstractmethod
915
+ def layer(
916
+ self, x: Sequence, *, training: bool, constants: Constants | None = None
917
+ ) -> Sequence:
918
+ """Process this layer layer-wise.
919
+
920
+ Args:
921
+ x: Input sequence with values shaped [b, t_i, ...].
922
+ training: Python bool. Whether we are in training mode.
923
+ constants: A dictionary of constant name to ArrayLike or sl.Sequence.
924
+ Values or sequences that are "constant" with respect to the
925
+ SequenceLayer, but may affect its processing. For example, for an
926
+ attention layer this may contain the source sequence to attend to.
927
+
928
+ Returns:
929
+ y: The outputs corresponding to this layer with values shaped
930
+ [b, t_o, ...] where `t_o == t_i * output_ratio`. t_o may have been
931
+ truncated to only represent valid frames.
932
+ """
933
+
934
+ def layer_with_emits(
935
+ self,
936
+ x: Sequence,
937
+ *,
938
+ training: bool,
939
+ constants: Constants | None = None,
940
+ ) -> tuple[Sequence, Emits]:
941
+ """Process this layer layer-wise, producing emitted tensors.
942
+
943
+ This is like `layer`, except it has an additional return value which is the
944
+ "emitted" tensors for the layer. The emitted tensors are a structure of
945
+ tensors whose whose values are `ArrayLike`s or `Sequence`s.
946
+
947
+ Args:
948
+ x: Input sequence with values shaped [b, t_i, ...].
949
+ training: Python bool. Whether we are in training mode.
950
+ constants: A dictionary of constant name to ArrayLike or sl.Sequence.
951
+ Values or sequences that are "constant" with respect to the
952
+ SequenceLayer, but may affect its processing. For example, for an
953
+ attention layer this may contain the key/value sequence to attend to.
954
+
955
+ Returns:
956
+ y: The outputs corresponding to this layer with values shaped
957
+ [b, t_o, ...] where `t_o == t_i * output_ratio`. t_o may have been
958
+ truncated to only represent valid frames.
959
+ emits: A nest of emitted tensors or Sequences.
960
+ """
961
+ outputs = self.layer(x, training=training, constants=constants)
962
+ return outputs, ()
963
+
964
+ def __call__(
965
+ self, x: Sequence, training: bool, constants: Constants | None = None
966
+ ) -> Sequence:
967
+ """For Flax-compatibility, define __call__ as an alias for layer."""
968
+ return self.layer(x, training=training, constants=constants)
969
+
970
+ @abc.abstractmethod
971
+ def step(
972
+ self,
973
+ x: Sequence,
974
+ state: State,
975
+ *,
976
+ training: bool,
977
+ constants: Constants | None = None,
978
+ ) -> tuple[Sequence, State]:
979
+ """Process this layer step-wise, producing emitted tensors.
980
+
981
+ Args:
982
+ x: Input sequence with values shaped [b, t_i, ...], where t_i is a
983
+ multiple of block_size.
984
+ state: A structure of state tensors matching get_initial_state. The
985
+ previous state for this layer.
986
+ training: Python bool. Whether we are in training mode.
987
+ constants: A dictionary of constant name to ArrayLike or sl.Sequence.
988
+ Values or sequences that are "constant" with respect to the
989
+ SequenceLayer, but may affect its processing. For example, for an
990
+ attention layer this may contain the key/value sequence to attend to.
991
+
992
+ Returns:
993
+ y: The outputs corresponding to this step with values shaped [b, t_o, ...]
994
+ where `t_o == t_i * output_ratio`.
995
+ state: A structure of state tensors matching get_initial_state. The
996
+ new state for this layer.
997
+ """
998
+
999
+ def step_with_emits(
1000
+ self,
1001
+ x: Sequence,
1002
+ state: State,
1003
+ *,
1004
+ training: bool,
1005
+ constants: Constants | None = None,
1006
+ ) -> tuple[Sequence, State, Emits]:
1007
+ """Process this layer step-wise, producing emitted tensors.
1008
+
1009
+ This is like `step`, except it has an additional return value which is the
1010
+ "emitted" tensors for the step. The emitted tensors are a structure of
1011
+ tensors whose values are `ArrayLike`s or `Sequence`s.
1012
+
1013
+ Args:
1014
+ x: Input sequence with values shaped [b, t_i, ...], where t_i is a
1015
+ multiple of block_size.
1016
+ state: A structure of state tensors matching get_initial_state. The
1017
+ previous state for this layer.
1018
+ training: Python bool. Whether we are in training mode.
1019
+ constants: A dictionary of constant name to ArrayLike or sl.Sequence.
1020
+ Values or sequences that are "constant" with respect to the
1021
+ SequenceLayer, but may affect its processing. For example, for an
1022
+ attention layer this may contain the key/value sequence to attend to.
1023
+
1024
+ Returns:
1025
+ y: The outputs corresponding to this step with values shaped [b, t_o, ...]
1026
+ where `t_o == t_i * output_ratio`.
1027
+ state: A structure of state tensors matching get_initial_state. The
1028
+ new state for this layer.
1029
+ emits: A nest of emitted tensors or Sequences.
1030
+ """
1031
+ outputs, state = self.step(x, state, training=training, constants=constants)
1032
+ return outputs, state, ()
1033
+
1034
+ @abc.abstractmethod
1035
+ def get_initial_state(
1036
+ self,
1037
+ batch_size: int,
1038
+ input_spec: ChannelSpec,
1039
+ *,
1040
+ training: bool,
1041
+ constants: Constants | None = None,
1042
+ ) -> State:
1043
+ """Returns the initial state for this SequenceLayer.
1044
+
1045
+ Args:
1046
+ batch_size: The batch size to create state for.
1047
+ input_spec: An input ChannelSpec representing the channel shape and dtype
1048
+ of the input that will be stepped.
1049
+ training: Whether we are in training mode.
1050
+ constants: A dictionary of constant name to ArrayLike or sl.Sequence.
1051
+ Values or sequences that are "constant" with respect to the
1052
+ SequenceLayer, but may affect its processing. For example, for an
1053
+ attention layer this may contain the source sequence to attend to.
1054
+
1055
+ Returns:
1056
+ An integer, TensorShape or structure of integer/TensorShapes.
1057
+ """
1058
+
1059
+ @abc.abstractmethod
1060
+ def get_output_shape(
1061
+ self, input_shape: ShapeLike, *, constants: Constants | None = None
1062
+ ) -> Shape:
1063
+ """Returns the output shape this layer produces for an input shape.
1064
+
1065
+ Args:
1066
+ input_shape: A shape representing the channels dimension of the input
1067
+ sequence (i.e. not including the batch or time dimension).
1068
+ constants: A dictionary of constant name to ArrayLike or sl.Sequence.
1069
+ Values or sequences that are "constant" with respect to the
1070
+ SequenceLayer, but may affect its processing. For example, for an
1071
+ attention layer this may contain the source sequence to attend to.
1072
+
1073
+ Returns:
1074
+ A shape representing the output channels dimensions (i.e. not including
1075
+ the batch or time dimension).
1076
+ """
1077
+
1078
+ @nn.nowrap
1079
+ def get_output_shape_for_sequence(
1080
+ self,
1081
+ x: Sequence,
1082
+ *,
1083
+ constants: Constants | None = None,
1084
+ ) -> Shape:
1085
+ """Returns the output shape this layer produces for the provided Sequence.
1086
+
1087
+ A convenience wrapper around get_output_shape.
1088
+
1089
+ Args:
1090
+ x: Sequence. An input sequence.
1091
+ constants: A dictionary of constant name to ArrayLike or sl.Sequence.
1092
+ Values or sequences that are "constant" with respect to the
1093
+ SequenceLayer, but may affect its processing. For example, for an
1094
+ attention layer this may contain the source sequence to attend to.
1095
+
1096
+ Returns:
1097
+ A shape representing the output channels dimensions (i.e. not including
1098
+ the batch or time dimension).
1099
+ """
1100
+ return self.get_output_shape(x.channel_shape, constants=constants)
1101
+
1102
+ @nn.nowrap
1103
+ def get_output_spec_for_sequence(
1104
+ self, x: Sequence, *, constants: Constants | None = None
1105
+ ) -> ChannelSpec:
1106
+ """Returns the output spec this layer produces for the provided Sequence.
1107
+
1108
+ A convenience wrapper around get_output_spec.
1109
+
1110
+ Args:
1111
+ x: Sequence. An input sequence.
1112
+ constants: A dictionary of constant name to ArrayLike or sl.Sequence.
1113
+ Values or sequences that are "constant" with respect to the
1114
+ SequenceLayer, but may affect its processing. For example, for an
1115
+ attention layer this may contain the source sequence to attend to.
1116
+
1117
+ Returns:
1118
+ A ChannelSpec which represents the output channels dimensions (i.e. not
1119
+ including the batch or time dimension) and dtype.
1120
+ """
1121
+ return self.get_output_spec(x.channel_spec, constants=constants)
1122
+
1123
+ @abc.abstractmethod
1124
+ def get_output_dtype(self, input_dtype: DType) -> DType:
1125
+ """Returns the layer's output dtype for the specified input dtype."""
1126
+
1127
+ @nn.nowrap
1128
+ def get_output_spec(
1129
+ self,
1130
+ input_spec: ChannelSpec,
1131
+ *,
1132
+ constants: Constants | None = None,
1133
+ ) -> ChannelSpec:
1134
+ """Returns the output spec this layer produces for the provided input spec.
1135
+
1136
+ Args:
1137
+ input_spec: A ChannelSpec which represents the channels shape and dtype of
1138
+ the input sequence (i.e. not including the batch or time dimension).
1139
+ constants: A dictionary of constant name to ArrayLike or sl.Sequence.
1140
+ Values or sequences that are "constant" with respect to the
1141
+ SequenceLayer, but may affect its processing. For example, for an
1142
+ attention layer this may contain the source sequence to attend to.
1143
+
1144
+ Returns:
1145
+ A ChannelSpec which represents the output channels dimensions (i.e. not
1146
+ including the batch or time dimension) and dtype.
1147
+ """
1148
+ shape = self.get_output_shape(input_spec.shape, constants=constants)
1149
+ dtype = self.get_output_dtype(input_spec.dtype)
1150
+ return ChannelSpec(shape, dtype)
1151
+
1152
+
1153
+ def _check_step_common(layer: Steppable, x: Sequence) -> None:
1154
+ """Checks layer is steppable and step input is a multiple of block size."""
1155
+ if not layer.supports_step:
1156
+ raise ValueError(f'{layer.__class__.__name__} does not support step().')
1157
+
1158
+ block_size = layer.block_size
1159
+
1160
+ if x.shape[1] % block_size != 0:
1161
+ raise ValueError(
1162
+ f'{layer.__class__.__name__} received input with shape'
1163
+ f' {x.shape=} which is not a multiple of {block_size=}.'
1164
+ )
1165
+
1166
+
1167
+ def _check_output_spec(
1168
+ layer: Steppable, x: Sequence, y: Sequence, constants: Constants | None
1169
+ ):
1170
+ """Checks the layer output matches get_output_spec."""
1171
+ expected_output_spec = layer.get_output_spec(
1172
+ x.channel_spec, constants=constants
1173
+ )
1174
+ if y.dtype != expected_output_spec.dtype:
1175
+ logging.warning(
1176
+ '%s produced output (%s) for input (%s) whose dtype does not match'
1177
+ ' get_output_spec (%s)',
1178
+ layer.__class__.__name__,
1179
+ y.channel_spec,
1180
+ x.channel_spec,
1181
+ expected_output_spec,
1182
+ )
1183
+
1184
+ if y.channel_shape != expected_output_spec.shape:
1185
+ raise ValueError(
1186
+ f'{layer.__class__.__name__} produced output ({y.channel_spec}) for'
1187
+ f' input ({x.channel_spec}), whose shape does not match get_output_spec'
1188
+ f' ({expected_output_spec}).'
1189
+ )
1190
+
1191
+
1192
+ def _check_output_ratio(layer: Steppable, x: Sequence, y: Sequence):
1193
+ output_ratio = layer.output_ratio
1194
+ expected_output_length = x.shape[1] * output_ratio
1195
+ if y.shape[1] != expected_output_length:
1196
+ raise ValueError(
1197
+ f'{layer.__class__.__name__} produced output ({y.shape}) for input'
1198
+ f' ({x.shape}), whose length does not equal'
1199
+ f' {expected_output_length} ({output_ratio=}).'
1200
+ )
1201
+
1202
+
1203
+ def check_layer(layer_fn):
1204
+ """A decorator that validates layer inputs and outputs."""
1205
+
1206
+ @functools.wraps(layer_fn)
1207
+ def check_layer_fn(
1208
+ self,
1209
+ x: Sequence,
1210
+ *,
1211
+ training: bool,
1212
+ constants: Constants | None = None,
1213
+ ) -> Sequence:
1214
+ y = layer_fn(self, x, training=training, constants=constants)
1215
+ _check_output_spec(self, x, y, constants)
1216
+
1217
+ return y
1218
+
1219
+ return check_layer_fn
1220
+
1221
+
1222
+ def check_layer_with_emits(layer_with_emits_fn):
1223
+ """A decorator that validates layer_with_emits inputs and outputs."""
1224
+
1225
+ @functools.wraps(layer_with_emits_fn)
1226
+ def check_layer_with_emits_fn(
1227
+ self,
1228
+ x: Sequence,
1229
+ *,
1230
+ training: bool,
1231
+ constants: Constants | None = None,
1232
+ ) -> tuple[Sequence, Emits]:
1233
+ y, emits = layer_with_emits_fn(
1234
+ self, x, training=training, constants=constants
1235
+ )
1236
+ _check_output_spec(self, x, y, constants)
1237
+
1238
+ return y, emits
1239
+
1240
+ return check_layer_with_emits_fn
1241
+
1242
+
1243
+ def check_step(step_fn):
1244
+ """A decorator that validates step inputs and outputs."""
1245
+
1246
+ @functools.wraps(step_fn)
1247
+ def check_step_fn(
1248
+ self,
1249
+ x: Sequence,
1250
+ state: State,
1251
+ *,
1252
+ training: bool,
1253
+ constants: Constants | None = None,
1254
+ ) -> tuple[Sequence, State]:
1255
+
1256
+ _check_step_common(self, x)
1257
+
1258
+ # TODO(rryan): Validate state pytree does not change.
1259
+ y, state = step_fn(self, x, state, training=training, constants=constants)
1260
+ _check_output_spec(self, x, y, constants)
1261
+ _check_output_ratio(self, x, y)
1262
+
1263
+ return y, state
1264
+
1265
+ return check_step_fn
1266
+
1267
+
1268
+ def check_step_with_emits(step_with_emits_fn):
1269
+ """A decorator that validates step_with_emits inputs and outputs."""
1270
+
1271
+ @functools.wraps(step_with_emits_fn)
1272
+ def check_step_with_emits_fn(
1273
+ self: Steppable,
1274
+ x: Sequence,
1275
+ state: State,
1276
+ *,
1277
+ training: bool,
1278
+ constants: Constants | None = None,
1279
+ ) -> tuple[Sequence, State, Emits]:
1280
+ _check_step_common(self, x)
1281
+
1282
+ # TODO(rryan): Validate state pytree does not change.
1283
+ y, state, emits = step_with_emits_fn(
1284
+ self, x, state, training=training, constants=constants
1285
+ )
1286
+ _check_output_spec(self, x, y, constants)
1287
+ _check_output_ratio(self, x, y)
1288
+
1289
+ return y, state, emits
1290
+
1291
+ return check_step_with_emits_fn
1292
+
1293
+
1294
+ class SequenceLayer(nn.Module, Steppable):
1295
+ """Base Module for Sequence Layers."""
1296
+
1297
+
1298
+ class PreservesType:
1299
+ """A mix-in for layers that do not change the input dtype."""
1300
+
1301
+ @nn.nowrap
1302
+ def get_output_dtype(self, input_dtype: DType) -> DType:
1303
+ return input_dtype
1304
+
1305
+
1306
+ class PreservesShape:
1307
+ """A mix-in for layers that do not change the input shape."""
1308
+
1309
+ @nn.nowrap
1310
+ def get_output_shape(
1311
+ self, input_shape: ShapeLike, *, constants: Constants | None = None
1312
+ ) -> Shape:
1313
+ del constants
1314
+ return tuple(input_shape)
1315
+
1316
+
1317
+ class Emitting(SequenceLayer, metaclass=abc.ABCMeta):
1318
+ """A SequenceLayer that emits auxiliary tensors.
1319
+
1320
+ This is a convenience subclass that implements step and layer in terms of
1321
+ step_with_emits and layer_with_emits, so that implementors need only implement
1322
+ two of the four methods. For emits that are substantially expensive to compute
1323
+ subclasses can choose to implement all four and save computation in those that
1324
+ do not produce emits.
1325
+ """
1326
+
1327
+ def step(
1328
+ self,
1329
+ x: Sequence,
1330
+ state: State,
1331
+ *,
1332
+ training: bool,
1333
+ constants: Constants | None = None,
1334
+ ) -> tuple[Sequence, State]:
1335
+ output, state, _ = self.step_with_emits(
1336
+ x, state, training=training, constants=constants
1337
+ )
1338
+ return output, state
1339
+
1340
+ @abc.abstractmethod
1341
+ def step_with_emits(
1342
+ self,
1343
+ x: Sequence,
1344
+ state: State,
1345
+ *,
1346
+ training: bool,
1347
+ constants: Constants | None = None,
1348
+ ) -> tuple[Sequence, State, Emits]:
1349
+ pass
1350
+
1351
+ def layer(
1352
+ self,
1353
+ x: Sequence,
1354
+ *,
1355
+ training: bool,
1356
+ constants: Constants | None = None,
1357
+ ) -> Sequence:
1358
+ outputs, _ = self.layer_with_emits(
1359
+ x, training=training, constants=constants
1360
+ )
1361
+ return outputs
1362
+
1363
+ @abc.abstractmethod
1364
+ def layer_with_emits(
1365
+ self,
1366
+ x: Sequence,
1367
+ *,
1368
+ training: bool,
1369
+ constants: Constants | None = None,
1370
+ ) -> tuple[Sequence, Emits]:
1371
+ pass
1372
+
1373
+
1374
+ class Stateless(SequenceLayer):
1375
+ """A SequenceLayer with no state over time required for step-wise processing.
1376
+
1377
+ Sub-classes must only implement:
1378
+ - layer
1379
+ - get_output_shape
1380
+ - get_output_dtype
1381
+ """
1382
+
1383
+ @property
1384
+ def receptive_field_per_step(self) -> dict[int, ReceptiveField]:
1385
+ return {0: (0, 0)}
1386
+
1387
+ def get_initial_state(
1388
+ self,
1389
+ batch_size: int,
1390
+ input_spec: ChannelSpec,
1391
+ *,
1392
+ training: bool,
1393
+ constants: Constants | None = None,
1394
+ ) -> State:
1395
+ del batch_size
1396
+ del input_spec
1397
+ del constants
1398
+ return ()
1399
+
1400
+ def step(
1401
+ self,
1402
+ x: Sequence,
1403
+ state: State,
1404
+ *,
1405
+ training: bool,
1406
+ constants: Constants | None = None,
1407
+ ) -> tuple[Sequence, State]:
1408
+ return self.layer(x, training=training, constants=constants), state
1409
+
1410
+
1411
+ class StatelessEmitting(Emitting):
1412
+ """A SequenceLayer with no state over time that emits auxiliary tensors.
1413
+
1414
+ Sub-classes must only implement:
1415
+ - layer_with_emits
1416
+ - get_output_shape
1417
+ - get_output_dtype
1418
+ """
1419
+
1420
+ @property
1421
+ def receptive_field_per_step(self) -> dict[int, ReceptiveField]:
1422
+ return {0: (0, 0)}
1423
+
1424
+ def step_with_emits(
1425
+ self,
1426
+ x: Sequence,
1427
+ state: State,
1428
+ *,
1429
+ training: bool,
1430
+ constants: Constants | None = None,
1431
+ ) -> tuple[Sequence, State, Emits]:
1432
+ outputs, emits = self.layer_with_emits(
1433
+ x, training=training, constants=constants
1434
+ )
1435
+ return outputs, state, emits
1436
+
1437
+ def get_initial_state(
1438
+ self,
1439
+ batch_size: int,
1440
+ input_spec: ChannelSpec,
1441
+ *,
1442
+ training: bool,
1443
+ constants: Constants | None = None,
1444
+ ) -> State:
1445
+ return ()
1446
+
1447
+
1448
+ class StatelessPointwise(PreservesShape, Stateless):
1449
+ """A SequenceLayer that has no state and operates pointwise on its input."""
1450
+
1451
+
1452
+ class StatelessPointwiseFunctor(StatelessPointwise, metaclass=abc.ABCMeta):
1453
+ """A stateless SequenceLayer for simple pointwise processing fns."""
1454
+
1455
+ @abc.abstractmethod
1456
+ def fn(self, values: ValuesT, mask: MaskT) -> tuple[ValuesT, MaskT]:
1457
+ """Transforms each scalar in values independently."""
1458
+
1459
+ @property
1460
+ def mask_required(self):
1461
+ """Returns true if fn can change the sequence's masked state.
1462
+
1463
+ If fn(0) -> 0, then mask_required() is False.
1464
+ """
1465
+ return True
1466
+
1467
+ @check_layer
1468
+ def layer(
1469
+ self,
1470
+ x: Sequence,
1471
+ *,
1472
+ training: bool,
1473
+ constants: Constants | None = None,
1474
+ ) -> Sequence:
1475
+ del training
1476
+ # If mask is not required, use Sequence.apply_masked, which preserves x's
1477
+ # type (i.e. a MaskedSequence stays a MaskedSequence).
1478
+ if self.mask_required:
1479
+ y = x.apply(self.fn)
1480
+ else:
1481
+ y = x.apply_masked(self.fn)
1482
+ return y
1483
+
1484
+
1485
+ class SequenceLayerConfig(metaclass=abc.ABCMeta):
1486
+ """Base class for SequenceLayer configuration objects.
1487
+
1488
+ Requires a no-argument make() method which returns a SequenceLayer.
1489
+
1490
+ This generic type allows users of SequenceLayers to abstract away the details
1491
+ of the specific SequenceLayer in use. This allows easy swapping of
1492
+ implementations based on behaviors (steppability, output ratio, latency,
1493
+ etc.).
1494
+ """
1495
+
1496
+ @abc.abstractmethod
1497
+ def make(self) -> SequenceLayer:
1498
+ """Builds a SequenceLayer from this config."""
1499
+
1500
+ def copy(self, **kwargs) -> Self:
1501
+ """Create a copy of this config.
1502
+
1503
+ Args:
1504
+ **kwargs: Keywords which correspond to attributes in the config copy, that
1505
+ should be overridden with their respective provided values.
1506
+
1507
+ Returns:
1508
+ A new instance of this config, possibly with overridden attributes.
1509
+
1510
+ Raises:
1511
+ AttributeError: The provided kwargs are not valid fields of this config.
1512
+ TypeError: The implementation does not support this config type. In this
1513
+ base implementation, only dataclasses with hashable fields are supported
1514
+ (a proxy for immutability, to avoid accidental mutation via e.g. shared
1515
+ child configs).
1516
+ """
1517
+ if not dataclasses.is_dataclass(self):
1518
+ raise TypeError(f'SequenceLayerConfig {self=} is not a dataclass.')
1519
+
1520
+ unhashable = dict()
1521
+ for field in dataclasses.fields(self):
1522
+ value = getattr(self, field.name)
1523
+ if not value.__hash__:
1524
+ unhashable[field.name] = value
1525
+ if unhashable:
1526
+ raise TypeError(
1527
+ f'SequenceLayerConfig {self=} has unhashable fields: {unhashable}.'
1528
+ )
1529
+
1530
+ try:
1531
+ return typing.cast(Self, dataclasses.replace(self, **kwargs))
1532
+ except TypeError as type_error:
1533
+ raise AttributeError(
1534
+ 'Failed to copy SequenceLayerConfig. Make sure that the kwargs keys '
1535
+ f"({list(kwargs.keys())}) you're passing to copy() are all fields "
1536
+ f'in the SequenceLayerConfig being copied: {self}, {kwargs=}'
1537
+ ) from type_error