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,673 @@
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
+ """Time-varying layers."""
15
+
16
+ import dataclasses
17
+ from typing import Callable, Sequence as TypingSequence
18
+
19
+ import flax.linen as nn
20
+ import jax
21
+ from jax.experimental import checkify
22
+ import jax.numpy as jnp
23
+ import numpy as np
24
+ from sequence_layers.jax import meta
25
+ from sequence_layers.jax import types
26
+ from sequence_layers.jax import utils
27
+
28
+ __all__ = (
29
+ # go/keep-sorted start
30
+ 'MaskedDense',
31
+ 'SequenceDense',
32
+ 'SequenceEmbedding',
33
+ # go/keep-sorted end
34
+ )
35
+
36
+
37
+ def _round_up_to_multiple_of(x: int, multiple_of: int) -> int:
38
+ return (x + multiple_of - 1) // multiple_of * multiple_of
39
+
40
+
41
+ class SequenceEmbedding(types.SequenceLayer):
42
+ """Computes sequence embeddings of integer input codes.
43
+
44
+ Provides step-dependent Embedding layers up to num_steps, where the sequence
45
+ step determines which Embedding layer is used. This layer can be used with
46
+ fixed length sequences, where num_steps is set to the fixed length. For
47
+ variable length sequences, set num_steps to the maximum sequence length.
48
+ """
49
+
50
+ @dataclasses.dataclass(frozen=True)
51
+ class Config(types.SequenceLayerConfig):
52
+ """Config for SequenceEmbedding."""
53
+
54
+ # Dimensionality of the embedded values.
55
+ dimension: int
56
+ # The number of embeddings in the embedding table per step. The inputs at
57
+ # step i are expected to be in the range [0, num_embeddings_per_step[i]). If
58
+ # num_embeddings_per_step is an int, the inputs at all steps are expected to
59
+ # be in [0, num_embeddings_per_step).
60
+ num_embeddings_per_step: TypingSequence[int] | int
61
+ # The number of valid timesteps for the SequenceEmbedding layer.
62
+ num_steps: int
63
+ # The dtype of the embeddings output by the layer.
64
+ compute_dtype: types.DType | None = None
65
+ # The dtype to use for layer parameters.
66
+ param_dtype: types.DType = jnp.float32
67
+ # By default, initialize embeddings to have a norm of 1.
68
+ embedding_init: nn.initializers.Initializer = nn.linear.default_embed_init
69
+ # Optional sharding for the embedding table.
70
+ embedding_sharding: types.Sharding | None = None
71
+ # Round up the number of embeddings to a multiple of this value. If 128 or
72
+ # 256, this leads to more TPU friendly shapes. If None, does not round.
73
+ round_num_embeddings_to_multiple_of: int | None = None
74
+ # Optional name for the layer.
75
+ name: str | None = None
76
+
77
+ def __post_init__(self):
78
+ # Ensure hashable sequence type.
79
+ if not isinstance(self.num_embeddings_per_step, int):
80
+ if len(self.num_embeddings_per_step) != self.num_steps:
81
+ raise ValueError(
82
+ 'num_embeddings_per_step must have length num_steps. Got: '
83
+ f'{self.num_embeddings_per_step=} vs {self.num_steps=}.'
84
+ )
85
+ object.__setattr__(
86
+ self,
87
+ 'num_embeddings_per_step',
88
+ tuple(self.num_embeddings_per_step),
89
+ )
90
+
91
+ def make(self) -> 'SequenceEmbedding':
92
+ return SequenceEmbedding(self, name=self.name)
93
+
94
+ config: Config
95
+
96
+ def setup(self):
97
+
98
+ if isinstance(self.config.num_embeddings_per_step, int):
99
+ num_embeddings = (
100
+ self.config.num_embeddings_per_step * self.config.num_steps
101
+ )
102
+ else:
103
+ num_embeddings = sum(self.config.num_embeddings_per_step)
104
+
105
+ if num_embeddings <= 0:
106
+ raise ValueError(
107
+ f'{self.config.num_embeddings_per_step=} must be positive.'
108
+ )
109
+
110
+ if self.config.round_num_embeddings_to_multiple_of:
111
+ num_embeddings = _round_up_to_multiple_of(
112
+ num_embeddings, self.config.round_num_embeddings_to_multiple_of
113
+ )
114
+
115
+ self.embedding = self.param(
116
+ 'embedding',
117
+ utils.shard_initializer(
118
+ self.config.embedding_init, self.config.embedding_sharding
119
+ ),
120
+ (
121
+ num_embeddings,
122
+ self.config.dimension,
123
+ ),
124
+ self.config.param_dtype,
125
+ )
126
+
127
+ @property
128
+ def receptive_field_per_step(self) -> dict[int, types.ReceptiveField]:
129
+ return {0: (0, 0)}
130
+
131
+ @nn.nowrap
132
+ def _validate_input_dtype(self, dtype: types.DType):
133
+ if not jnp.issubdtype(dtype, jnp.integer):
134
+ raise ValueError(
135
+ 'Input to Embedding must be an integer or unsigned integer, got:'
136
+ f' {dtype}'
137
+ )
138
+
139
+ @nn.nowrap
140
+ def get_output_shape(
141
+ self,
142
+ input_shape: types.ShapeLike,
143
+ *,
144
+ constants: types.Constants | None = None,
145
+ ) -> types.Shape:
146
+ return tuple(input_shape) + (self.config.dimension,)
147
+
148
+ @nn.nowrap
149
+ def get_output_dtype(self, input_dtype: types.DType) -> types.DType:
150
+ self._validate_input_dtype(input_dtype)
151
+ if self.config.compute_dtype is None:
152
+ return self.config.param_dtype
153
+ return self.config.compute_dtype
154
+
155
+ @types.check_layer
156
+ def layer(
157
+ self,
158
+ x: types.Sequence,
159
+ *,
160
+ training: bool,
161
+ constants: types.Constants | None = None,
162
+ ) -> types.Sequence:
163
+ y, _ = self.step(x, 0, training=training, constants=constants)
164
+ return y
165
+
166
+ def get_initial_state(
167
+ self,
168
+ batch_size: int,
169
+ input_spec: types.ChannelSpec,
170
+ *,
171
+ training: bool,
172
+ constants: types.Constants | None = None,
173
+ ) -> types.State:
174
+ del batch_size
175
+ del input_spec
176
+ del constants
177
+ # TODO(b/338656992): Support continuous batching by removing the unbatched
178
+ # state.
179
+ return jnp.array(0, dtype=jnp.int32)
180
+
181
+ @types.check_step
182
+ def step(
183
+ self,
184
+ x: types.Sequence,
185
+ state: types.State,
186
+ *,
187
+ training: bool,
188
+ constants: types.Constants | None = None,
189
+ ) -> tuple[types.Sequence, types.State]:
190
+ del training
191
+ del constants
192
+ self._validate_input_dtype(x.dtype)
193
+ num_steps = self.config.num_steps
194
+ start_time = state
195
+ time_delta = x.shape[1]
196
+ end_time = start_time + time_delta
197
+ _check_step_bounds(start_time, end_time, num_steps)
198
+
199
+ embedding = self.embedding
200
+ (embedding,) = nn.dtypes.promote_dtype(
201
+ embedding, dtype=self.config.compute_dtype, inexact=False
202
+ )
203
+
204
+ def broadcast_to_x(a: jax.Array) -> jax.Array:
205
+ """Reshapes (time_delta) to (1, time_delta, ...)."""
206
+ assert a.ndim == 1 and a.shape[0] == time_delta
207
+ return a.reshape((1,) + a.shape + (1,) * (x.ndim - 2))
208
+
209
+ # Input is codebook indices shaped [b, time_delta, ...].
210
+
211
+ # Ensure steps are in range.
212
+ steps = start_time + jnp.arange(time_delta)
213
+ steps_valid = broadcast_to_x(
214
+ jnp.logical_and(steps >= 0, steps < self.config.num_steps)
215
+ )
216
+
217
+ if isinstance(self.config.num_embeddings_per_step, int):
218
+ offsets = broadcast_to_x(self.config.num_embeddings_per_step * steps)
219
+ # No broadcast reshaping needed for scalar.
220
+ limits = self.config.num_embeddings_per_step
221
+ else:
222
+ offsets = np.cumsum(
223
+ (0,) + tuple(self.config.num_embeddings_per_step[:-1])
224
+ )
225
+ offsets = broadcast_to_x(jnp.take(offsets, steps))
226
+ limits = np.array(self.config.num_embeddings_per_step, np.int32)
227
+ limits = broadcast_to_x(jnp.take(limits, steps))
228
+
229
+ # Ensure per-step indices are in range. [batch, num_steps, ...].
230
+ indices_valid = jnp.logical_and(x.values >= 0, x.values < limits)
231
+ indices = x.values + offsets
232
+
233
+ # Replace invalid indices with the an out-of-range value to ensure they are
234
+ # replaced with NaN in the gather.
235
+ indices = jnp.where(
236
+ steps_valid & indices_valid, indices, embedding.shape[0]
237
+ )
238
+
239
+ embedded = x.apply_values(lambda v: jnp.take(embedding, indices, axis=0))
240
+
241
+ return embedded, end_time
242
+
243
+
244
+ class SequenceDense(types.SequenceLayer):
245
+ """Step-dependent Dense layer.
246
+
247
+ Provides step-dependent Dense layers up to num_steps, where the sequence
248
+ step determines which Dense layer is used. This layer can be used with fixed
249
+ length sequences, where num_steps is set to the fixed length. For variable
250
+ length sequences, set num_steps to the maximum sequence length.
251
+
252
+ Each step-dependent Dense layer only operates on the inputs at the associated
253
+ timestep, i.e., y[t] = Dense_t(x[t]), where Dense_t is the Dense layer
254
+ used for timestep t.
255
+ """
256
+
257
+ @dataclasses.dataclass(frozen=True)
258
+ class Config(types.SequenceLayerConfig):
259
+ """Config for SequenceDense."""
260
+
261
+ # The number of output features for the dense layer.
262
+ features: int
263
+ # The number of valid timesteps for the SequenceDense layer.
264
+ num_steps: int
265
+ # Whether to use a bias.
266
+ use_bias: bool = True
267
+ # An optional activation to apply after the dense layer.
268
+ activation: Callable[[jax.Array], jax.Array] | None = None
269
+ # The dtype to use for layer compute.
270
+ compute_dtype: types.DType | None = None
271
+ # The dtype to use for layer parameters.
272
+ param_dtype: types.DType = jnp.float32
273
+ # An optional precision to use for the einsum.
274
+ precision: nn.linear.PrecisionLike = None
275
+ # Initializer for the kernel.
276
+ kernel_init: nn.initializers.Initializer = nn.linear.default_kernel_init
277
+ # Optional sharding for the kernel. Any axes that are present in the input
278
+ # spec are marked as FANIN.
279
+ kernel_sharding: types.Sharding | None = None
280
+ # Initializer for the bias, if used and not gated by another config option.
281
+ bias_init: nn.initializers.Initializer = nn.initializers.zeros_init()
282
+ # Optional sharding for the bias.
283
+ bias_sharding: types.Sharding | None = None
284
+ # Optional name for the layer.
285
+ name: str | None = None
286
+
287
+ def make(self) -> 'SequenceDense':
288
+ return SequenceDense(self, name=self.name)
289
+
290
+ config: Config
291
+
292
+ @property
293
+ def receptive_field_per_step(self) -> dict[int, types.ReceptiveField]:
294
+ return {0: (0, 0)}
295
+
296
+ @nn.nowrap
297
+ def get_output_dtype(self, input_dtype: types.DType) -> types.DType:
298
+ return utils.get_promoted_dtype(
299
+ input_dtype, self.config.param_dtype, dtype=self.config.compute_dtype
300
+ )
301
+
302
+ @nn.nowrap
303
+ def get_output_shape(
304
+ self,
305
+ input_shape: types.ShapeLike,
306
+ constants: types.Constants | None = None,
307
+ ) -> types.Shape:
308
+ del constants
309
+ # TODO(rryan): Support rank > 3 inputs.
310
+ if len(input_shape) != 1:
311
+ raise ValueError(
312
+ f'SequenceDense requires rank 3 input. Got: {input_shape=}'
313
+ )
314
+ return tuple(input_shape[:-1]) + (self.config.features,)
315
+
316
+ @types.check_layer
317
+ def layer(
318
+ self,
319
+ x: types.Sequence,
320
+ *,
321
+ training: bool,
322
+ constants: types.Constants | None = None,
323
+ ) -> types.Sequence:
324
+ y, _ = self.step(x, 0, training=training, constants=constants)
325
+ return y
326
+
327
+ def get_initial_state(
328
+ self,
329
+ batch_size: int,
330
+ input_spec: types.ChannelSpec,
331
+ *,
332
+ training: bool,
333
+ constants: types.Constants | None = None,
334
+ ) -> types.State:
335
+ del batch_size
336
+ del input_spec
337
+ del constants
338
+ # TODO(b/338656992): Support continuous batching by removing the unbatched
339
+ # state.
340
+ return jnp.array(0, dtype=jnp.int32)
341
+
342
+ @types.check_step
343
+ @nn.compact
344
+ def step(
345
+ self,
346
+ x: types.Sequence,
347
+ step: types.State,
348
+ *,
349
+ training: bool,
350
+ constants: types.Constants | None = None,
351
+ ) -> tuple[types.Sequence, types.State]:
352
+ del training
353
+ del constants
354
+
355
+ num_steps = self.config.num_steps
356
+ start_time = step
357
+ time_delta = x.shape[1]
358
+ end_time = start_time + time_delta
359
+ _check_step_bounds(start_time, end_time, num_steps)
360
+
361
+ # TODO(rryan): Support rank > 3 inputs.
362
+ if x.ndim != 3:
363
+ raise ValueError(f'SequenceDense requires rank 3 input. Got: {x.shape=}')
364
+
365
+ kernel_shape = (num_steps, x.shape[-1], self.config.features)
366
+
367
+ kernel_init = utils.shard_initializer(
368
+ self.config.kernel_init,
369
+ self.config.kernel_sharding,
370
+ projectable=True,
371
+ axes_types=(meta.AxisType.FANIN, meta.AxisType.FANIN, None),
372
+ )
373
+ kernel = self.param(
374
+ 'kernel', kernel_init, kernel_shape, self.config.param_dtype
375
+ )
376
+ if self.config.use_bias:
377
+ bias_shape = (num_steps, self.config.features)
378
+ bias_init = utils.shard_initializer(
379
+ self.config.bias_init, self.config.bias_sharding
380
+ )
381
+ bias = self.param('bias', bias_init, bias_shape, self.config.param_dtype)
382
+ else:
383
+ bias = None
384
+
385
+ inputs, kernel, bias = nn.dtypes.promote_dtype(
386
+ x.values, kernel, bias, dtype=self.config.compute_dtype
387
+ )
388
+
389
+ # Slice [T, I, O] kernel to be used with current timesteps.
390
+ slice_size = min(self.config.num_steps, time_delta)
391
+ step_kernel = jax.lax.dynamic_slice_in_dim(
392
+ kernel, start_index=start_time, slice_size=slice_size, axis=0
393
+ )
394
+
395
+ if pad_amount := max(0, time_delta - step_kernel.shape[0]):
396
+ step_kernel = jnp.pad(
397
+ step_kernel,
398
+ ((0, pad_amount), (0, 0), (0, 0)),
399
+ )
400
+
401
+ ret = jnp.einsum(
402
+ '...ti,tio->...to', inputs, step_kernel, precision=self.config.precision
403
+ )
404
+ if bias is not None:
405
+ step_bias = jax.lax.dynamic_slice_in_dim(
406
+ bias, start_index=start_time, slice_size=slice_size, axis=0
407
+ )
408
+ if pad_amount:
409
+ step_bias = jnp.pad(step_bias, ((0, pad_amount), (0, 0)))
410
+ ret = utils.bias_add(ret, step_bias)
411
+ if self.config.activation is not None:
412
+ ret = self.config.activation(ret)
413
+
414
+ steps_valid = (start_time + jnp.arange(time_delta)) < self.config.num_steps
415
+ steps_valid = steps_valid.reshape(
416
+ (1,) + steps_valid.shape + (1,) * (ret.ndim - 2)
417
+ )
418
+ ret = jnp.where(steps_valid, ret, jnp.full_like(ret, jnp.nan))
419
+
420
+ # Preserve masked state if no bias or activation are in use.
421
+ apply_fn = (
422
+ x.apply_values
423
+ if self.config.use_bias or self.config.activation is not None
424
+ else x.apply_values_masked
425
+ )
426
+ return apply_fn(lambda v: ret), start_time + time_delta
427
+
428
+
429
+ class MaskedDense(types.SequenceLayer):
430
+ """Step-dependent causal masked Dense layers.
431
+
432
+ Provides step-dependent masked Dense layers up to num_steps, where the
433
+ sequence step determines which masked Dense layer is used. This layer can be
434
+ used with fixed length sequences, where num_steps is set to the fixed length.
435
+ For variable length sequences, set num_steps to the maximum sequence length.
436
+
437
+ Masked Dense layers are causally masked so that y[t] (the output at time=t)
438
+ is a Dense transformation of x[0:t+1] (the input from time=0 up to time=t,
439
+ inclusive.); i.e., y[t] = Dense_t(x[0,...,t]), where Dense_t is the Dense
440
+ layer used for timestep t.
441
+
442
+ Note:
443
+ This layer uses a masked kernel variable in order to maintain the
444
+ autoregressive property, and therefore, half of the weights are unused and
445
+ have zero gradient. This could affect the behavior of certain optimizers or
446
+ normalization schemes (e.g., AdaFactor).
447
+ """
448
+
449
+ @dataclasses.dataclass(frozen=True)
450
+ class Config(types.SequenceLayerConfig):
451
+ """Config for MaskedDense."""
452
+
453
+ features: int
454
+ num_steps: int
455
+ # Whether to use a bias.
456
+ use_bias: bool = True
457
+ # An optional activation to apply after the dense layer.
458
+ activation: Callable[[jax.Array], jax.Array] | None = None
459
+ # The dtype to use for layer compute.
460
+ compute_dtype: types.DType | None = None
461
+ # The dtype to use for layer parameters.
462
+ param_dtype: types.DType = jnp.float32
463
+ # An optional precision to use for the einsum.
464
+ precision: nn.linear.PrecisionLike = None
465
+ # Initializer for the kernel.
466
+ kernel_init: nn.initializers.Initializer = nn.linear.default_kernel_init
467
+ # Optional sharding for the kernel. Any axes that are present in the input
468
+ # spec are marked as FANIN.
469
+ kernel_sharding: types.Sharding | None = None
470
+ # Initializer for the bias, if used and not gated by another config option.
471
+ bias_init: nn.initializers.Initializer = nn.initializers.zeros_init()
472
+ # Optional sharding for the bias.
473
+ bias_sharding: types.Sharding | None = None
474
+ # Optional name for the layer.
475
+ name: str | None = None
476
+
477
+ def make(self) -> 'MaskedDense':
478
+ return MaskedDense(self, name=self.name)
479
+
480
+ config: Config
481
+
482
+ @nn.nowrap
483
+ def get_output_dtype(self, input_dtype: types.DType) -> types.DType:
484
+ return utils.get_promoted_dtype(
485
+ input_dtype, self.config.param_dtype, dtype=self.config.compute_dtype
486
+ )
487
+
488
+ @property
489
+ def receptive_field_per_step(self) -> dict[int, types.ReceptiveField]:
490
+ return {0: (-self.config.num_steps + 1, 0)}
491
+
492
+ @nn.nowrap
493
+ def get_output_shape(
494
+ self,
495
+ input_shape: types.ShapeLike,
496
+ constants: types.Constants | None = None,
497
+ ) -> types.Shape:
498
+ del constants
499
+ # TODO(rryan): Support rank > 3 inputs.
500
+ if len(input_shape) != 1:
501
+ raise ValueError(
502
+ f'MaskedDense requires rank 3 input. Got: {input_shape=}'
503
+ )
504
+ return tuple(input_shape[:-1]) + (self.config.features,)
505
+
506
+ def get_initial_state(
507
+ self,
508
+ batch_size: int,
509
+ input_spec: types.ChannelSpec,
510
+ *,
511
+ training: bool,
512
+ constants: types.Constants | None = None,
513
+ ) -> types.State:
514
+ del constants
515
+ # TODO(rryan): Support rank > 3 inputs.
516
+ if len(input_spec.shape) != 1:
517
+ raise ValueError(f'MaskedDense requires rank 3 input. Got: {input_spec=}')
518
+
519
+ input_dim = input_spec.shape[0]
520
+
521
+ # When executing step-by-step, we need a buffer for tracking past inputs.
522
+ # TODO(b/338656992): Support continuous batching by removing the unbatched
523
+ # state.
524
+ t0 = jnp.array(0, dtype=jnp.int32)
525
+ input_buffer = types.MaskedSequence(
526
+ jnp.zeros(
527
+ (batch_size, self.config.num_steps, input_dim),
528
+ dtype=input_spec.dtype,
529
+ ),
530
+ jnp.zeros((batch_size, self.config.num_steps), dtype=types.MASK_DTYPE),
531
+ )
532
+ return t0, input_buffer
533
+
534
+ @types.check_step
535
+ @nn.compact
536
+ def step(
537
+ self,
538
+ x: types.Sequence,
539
+ state: types.State,
540
+ *,
541
+ training: bool,
542
+ constants: types.Constants | None = None,
543
+ ) -> tuple[types.Sequence, types.State]:
544
+ """Steps forward, input shape: [..., block_size, num_groups]."""
545
+ del training, constants
546
+
547
+ # TODO(rryan): Support rank > 3 inputs.
548
+ if x.ndim != 3:
549
+ raise ValueError(f'MaskedDense requires rank 3 input. Got: {x.shape=}')
550
+
551
+ num_steps = self.config.num_steps
552
+ start_time, input_buffer = state
553
+ time_delta = x.shape[1]
554
+ end_time = start_time + time_delta
555
+ _check_step_bounds(start_time, end_time, num_steps)
556
+
557
+ # Append new input to end of buffer and truncate at the front:
558
+ # e.g., [0, 0, x0, x1] -> [0, x0, x1, x2], where new input is [x2].
559
+ input_buffer = input_buffer.concatenate(x.mask_invalid())
560
+ input_buffer = input_buffer[:, -num_steps:]
561
+ # Roll buffer so padding is at the end:
562
+ # e.g., [0, x0, x1, x2] -> [x0, x1, x2, 0]
563
+ step_input = jnp.roll(input_buffer.values, shift=end_time, axis=1)
564
+
565
+ # TODO(ebattenberg): Consider ways to eliminate unused (masked off)
566
+ # weights (e.g., construct a masked kernel Tensor from smaller
567
+ # sub-variables.)
568
+
569
+ # Construct a [T, T', I, O] kernel tensor to project [B, T, I] input to
570
+ # [B, T', O] output, where T represents the input time dimension and T'
571
+ # represents the output time dimension, and T = T' = num_steps.
572
+ kernel_shape = (
573
+ num_steps,
574
+ num_steps,
575
+ x.shape[-1],
576
+ self.config.features,
577
+ )
578
+ kernel_init = utils.shard_initializer(
579
+ self.config.kernel_init,
580
+ self.config.kernel_sharding,
581
+ projectable=True,
582
+ axes_types=(
583
+ meta.AxisType.FANIN,
584
+ meta.AxisType.FANIN,
585
+ meta.AxisType.FANIN,
586
+ None,
587
+ ),
588
+ )
589
+
590
+ kernel = self.param(
591
+ 'kernel', kernel_init, kernel_shape, self.config.param_dtype
592
+ )
593
+
594
+ if self.config.use_bias:
595
+ bias_shape = (num_steps, self.config.features)
596
+ bias_init = utils.shard_initializer(
597
+ self.config.bias_init, self.config.bias_sharding
598
+ )
599
+ bias = self.param('bias', bias_init, bias_shape, self.config.param_dtype)
600
+ else:
601
+ bias = None
602
+
603
+ step_input, kernel, bias = nn.dtypes.promote_dtype(
604
+ step_input, kernel, bias, dtype=self.config.compute_dtype
605
+ )
606
+
607
+ # Construct a [T, T', 1, 1] upper triangular autoregressive mask matrix,
608
+ # where T represents the input time dimension and T' represents the output
609
+ # time dimension, and T = T' = num_steps.
610
+ mask = utils.ones_matrix_band_part(
611
+ num_steps,
612
+ num_steps,
613
+ num_lower=0,
614
+ num_upper=-1,
615
+ out_dtype=kernel.dtype,
616
+ out_shape=(num_steps, num_steps, 1, 1),
617
+ )
618
+ masked_kernel = kernel * mask
619
+
620
+ # Slice kernel and mask to produce current output timesteps.
621
+ # Kernel is [T, T', I, O], mask is [T, T', 1, 1], where T represents the
622
+ # input time dimension and T' represents the output time dimension,
623
+ # and T = T' = num_steps.
624
+ # step_kernel = self._kernel[:, start_time:end_time]
625
+ masked_step_kernel = jax.lax.dynamic_slice_in_dim(
626
+ masked_kernel, start_time, time_delta, axis=1
627
+ )
628
+
629
+ ret = jnp.einsum(
630
+ 'BTI,TtIO->BtO',
631
+ step_input,
632
+ masked_step_kernel,
633
+ precision=self.config.precision,
634
+ )
635
+ if self.config.use_bias:
636
+ # Bias is [T', O]. Slice for current output timesteps.
637
+ step_bias = jax.lax.dynamic_slice_in_dim(
638
+ bias, start_time, time_delta, axis=0
639
+ )
640
+ ret = utils.bias_add(ret, step_bias)
641
+
642
+ if self.config.activation is not None:
643
+ ret = self.config.activation(ret)
644
+
645
+ # Never preserve x's masked state, since even if the current timestep is
646
+ # masked, the above einsum can produce non-zero values from buffered valid
647
+ # outputs.
648
+ y = types.Sequence(ret, x.mask)
649
+ state = (end_time, input_buffer)
650
+ return y, state
651
+
652
+ @types.check_layer
653
+ def layer(
654
+ self,
655
+ x: types.Sequence,
656
+ *,
657
+ training: bool,
658
+ constants: types.Constants | None = None,
659
+ ) -> types.Sequence:
660
+ state = self.get_initial_state(
661
+ x.shape[0], x.channel_spec, training=training
662
+ )
663
+ y, _ = self.step(x, state, training=training, constants=constants)
664
+ return y
665
+
666
+
667
+ @checkify.checkify
668
+ def _check_step_bounds(start_time, end_time, num_steps):
669
+ """Check that step indices are within range."""
670
+ checkify.check(start_time >= 0, 'Out of range step index (< 0).')
671
+ checkify.check(
672
+ end_time <= num_steps, 'Out of range step index (> num_steps).'
673
+ )