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,1907 @@
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
+ """Combinators."""
15
+
16
+ import dataclasses
17
+ import fractions
18
+ import functools
19
+ import math
20
+ from typing import Callable, Sequence as TypingSequence, TypeVar
21
+
22
+ import flax
23
+ import flax.linen as nn
24
+ import jax
25
+ import jax.numpy as jnp
26
+ import numpy as np
27
+ from sequence_layers.jax import meta
28
+ from sequence_layers.jax import simple
29
+ from sequence_layers.jax import types
30
+ from sequence_layers.jax import utils
31
+
32
+
33
+ CombinationMode = utils.CombinationMode
34
+
35
+ __all__ = (
36
+ # go/keep-sorted start
37
+ 'Bidirectional',
38
+ 'Blockwise',
39
+ 'CheckpointGradient',
40
+ 'CombinationMode',
41
+ 'Parallel',
42
+ 'ParallelChannels',
43
+ 'Repeat',
44
+ 'Residual',
45
+ 'Serial',
46
+ 'SerialCombinatorMixin',
47
+ 'SerialModules',
48
+ 'WrapperMixin',
49
+ # go/keep-sorted end
50
+ )
51
+
52
+
53
+ T = TypeVar('T')
54
+ SequenceLayerConfigOrList = (
55
+ types.SequenceLayerConfig | TypingSequence[types.SequenceLayerConfig]
56
+ )
57
+
58
+
59
+ def _wrap_layers(layers: SequenceLayerConfigOrList) -> types.SequenceLayer:
60
+ if isinstance(layers, types.SequenceLayerConfig):
61
+ return layers.make()
62
+ else:
63
+ return Serial.Config(layers=tuple(layers)).make()
64
+
65
+
66
+ class WrapperMixin:
67
+ """A wrapper mixin where the wrapped layer properties are unchanged.
68
+
69
+ Used for layers that modify the wrapped layer's behavior in a way that does
70
+ not change any of the layer properties or utility functions.
71
+ """
72
+
73
+ child_layer: types.SequenceLayer
74
+
75
+ @property
76
+ def supports_step(self) -> bool:
77
+ return self.child_layer.supports_step
78
+
79
+ @property
80
+ def input_latency(self) -> int:
81
+ return self.child_layer.input_latency
82
+
83
+ @property
84
+ def output_latency(self) -> int:
85
+ return self.child_layer.output_latency
86
+
87
+ @functools.cached_property
88
+ def receptive_field_per_step(self) -> dict[int, types.ReceptiveField]:
89
+ return self.child_layer.receptive_field_per_step
90
+
91
+ def get_accumulated_input_latency(self, input_latency: int) -> int:
92
+ return self.child_layer.get_accumulated_input_latency(input_latency)
93
+
94
+ def get_accumulated_output_latency(self, output_latency: int) -> int:
95
+ return self.child_layer.get_accumulated_output_latency(output_latency)
96
+
97
+ @property
98
+ def block_size(self) -> int:
99
+ return self.child_layer.block_size
100
+
101
+ @property
102
+ def output_ratio(self) -> fractions.Fraction:
103
+ return self.child_layer.output_ratio
104
+
105
+ @nn.nowrap
106
+ def get_output_dtype(self, input_dtype: types.DType) -> types.DType:
107
+ return self.child_layer.get_output_dtype(input_dtype)
108
+
109
+ @nn.nowrap
110
+ def get_output_shape(
111
+ self,
112
+ input_shape: types.ShapeLike,
113
+ *,
114
+ constants: types.Constants | None = None,
115
+ ) -> types.Shape:
116
+ return self.child_layer.get_output_shape(input_shape, constants=constants)
117
+
118
+ def layer(
119
+ self,
120
+ x: types.Sequence,
121
+ *,
122
+ training: bool,
123
+ constants: types.Constants | None = None,
124
+ ) -> types.Sequence:
125
+ return self.child_layer.layer(x, training=training, constants=constants)
126
+
127
+ def layer_with_emits(
128
+ self,
129
+ x: types.Sequence,
130
+ *,
131
+ training: bool,
132
+ constants: types.Constants | None = None,
133
+ ) -> tuple[types.Sequence, types.Emits]:
134
+ return self.child_layer.layer_with_emits(
135
+ x, training=training, constants=constants
136
+ )
137
+
138
+ def get_initial_state(
139
+ self,
140
+ batch_size: int,
141
+ input_spec: types.ChannelSpec,
142
+ *,
143
+ training: bool,
144
+ constants: types.Constants | None = None,
145
+ ) -> types.State:
146
+ return self.child_layer.get_initial_state(
147
+ batch_size, input_spec, training=training, constants=constants
148
+ )
149
+
150
+ def step(
151
+ self,
152
+ x: types.Sequence,
153
+ state: types.State,
154
+ *,
155
+ training: bool,
156
+ constants: types.Constants | None = None,
157
+ ) -> tuple[types.Sequence, types.State]:
158
+ return self.child_layer.step(
159
+ x, state, training=training, constants=constants
160
+ )
161
+
162
+ def step_with_emits(
163
+ self,
164
+ x: types.Sequence,
165
+ state: types.State,
166
+ *,
167
+ training: bool,
168
+ constants: types.Constants | None = None,
169
+ ) -> tuple[types.Sequence, types.State, types.Emits]:
170
+ return self.child_layer.step_with_emits(
171
+ x, state, training=training, constants=constants
172
+ )
173
+
174
+
175
+ class SerialCombinatorMixin:
176
+ """Mixin for Serial logic."""
177
+
178
+ layers: tuple[types.SequenceLayer, ...]
179
+ # Provided by nn.Module.path.
180
+ path: tuple[str, ...]
181
+ # Provided by nn.Module.name.
182
+ name: str
183
+
184
+ @property
185
+ def supports_step(self) -> bool:
186
+ return all(child_layer.supports_step for child_layer in self.layers)
187
+
188
+ @property
189
+ def input_latency(self) -> int:
190
+ return self.get_accumulated_input_latency(0)
191
+
192
+ @property
193
+ def output_latency(self) -> int:
194
+ return self.get_accumulated_output_latency(0)
195
+
196
+ @functools.cached_property
197
+ def receptive_field(self) -> types.ReceptiveField:
198
+ """Returns the receptive field of the serial combinator."""
199
+ return utils.reduce_receptive_field_per_step(
200
+ self.receptive_field_per_step, self.output_ratio
201
+ )
202
+
203
+ @functools.cached_property
204
+ def receptive_field_per_step(self) -> dict[int, types.ReceptiveField]:
205
+ """Returns the range of the receptive field of this layer per step."""
206
+ return utils.receptive_field_per_step_of_serial_layers(self.layers)
207
+
208
+ def get_accumulated_input_latency(self, input_latency: int) -> int:
209
+ return utils.serial_input_latency(self.layers, input_latency)
210
+
211
+ def get_accumulated_output_latency(self, output_latency: int) -> int:
212
+ return utils.serial_output_latency(self.layers, output_latency)
213
+
214
+ @property
215
+ def block_size(self) -> int:
216
+ """The block size of the layer."""
217
+ return utils.serial_block_size(self.layers)
218
+
219
+ @property
220
+ def output_ratio(self) -> fractions.Fraction:
221
+ return utils.serial_output_ratio(self.layers)
222
+
223
+ def get_initial_state(
224
+ self,
225
+ batch_size: int,
226
+ input_spec: types.ShapeDType,
227
+ *,
228
+ training: bool,
229
+ constants: types.Constants | None = None,
230
+ ) -> types.State:
231
+ """Returns initial state for the layer."""
232
+ spec = input_spec
233
+ states = []
234
+ for child_layer in self.layers:
235
+ states.append(
236
+ child_layer.get_initial_state(
237
+ batch_size, spec, training=training, constants=constants
238
+ )
239
+ )
240
+ spec = child_layer.get_output_spec(spec, constants=constants)
241
+ return tuple(states)
242
+
243
+ @nn.nowrap
244
+ def get_output_dtype(self, input_dtype: types.DType) -> types.DType:
245
+ dtype = input_dtype
246
+ for child_layer in self.layers:
247
+ dtype = child_layer.get_output_dtype(dtype)
248
+ return dtype
249
+
250
+ @nn.nowrap
251
+ def get_output_shape(
252
+ self,
253
+ input_shape: types.ShapeLike,
254
+ *,
255
+ constants: types.Constants | None = None,
256
+ ) -> types.Shape:
257
+ shape = tuple(input_shape)
258
+ for child_layer in self.layers:
259
+ shape = child_layer.get_output_shape(shape, constants=constants)
260
+ return shape
261
+
262
+ def step_with_emits(
263
+ self,
264
+ x: types.Sequence,
265
+ state: types.State,
266
+ *,
267
+ training: bool,
268
+ constants: types.Constants | None = None,
269
+ ) -> tuple[types.Sequence, types.State, types.Emits]:
270
+ """Applies the layer to a block of inputs."""
271
+ new_state = []
272
+ emits = {}
273
+ if len(self.layers) != len(state):
274
+ raise ValueError(
275
+ f'{type(self)=} {self.path=} received unexpected state structure:'
276
+ f' {len(self.layers)=} != {len(state)=}:'
277
+ f' {state=} {[type(l) for l in self.layers]=}'
278
+ )
279
+
280
+ for child_layer, state_i in zip(self.layers, state):
281
+ x, state_i, emits_i = child_layer.step_with_emits(
282
+ x, state_i, training=training, constants=constants
283
+ )
284
+ new_state.append(state_i)
285
+ utils.insert_with_unique_key(emits, child_layer.name, emits_i)
286
+ return x, tuple(new_state), emits
287
+
288
+ def layer_with_emits(
289
+ self,
290
+ x: types.Sequence,
291
+ *,
292
+ training: bool,
293
+ constants: types.Constants | None = None,
294
+ ) -> tuple[types.Sequence, types.Emits]:
295
+ """Applies the layer to the input sequence."""
296
+ emits = {}
297
+ for child_layer in self.layers:
298
+ x, emits_i = child_layer.layer_with_emits(
299
+ x, training=training, constants=constants
300
+ )
301
+ utils.insert_with_unique_key(emits, child_layer.name, emits_i)
302
+ return x, emits
303
+
304
+
305
+ class Serial(SerialCombinatorMixin, types.Emitting):
306
+ """A combinator that processes SequenceLayers serially."""
307
+
308
+ @dataclasses.dataclass(frozen=True)
309
+ class Config(types.SequenceLayerConfig):
310
+ """Configuration for Serial."""
311
+
312
+ layers: TypingSequence[types.SequenceLayerConfig]
313
+ # If true, a list of boolean values for each layer in `layers` indicating
314
+ # whether to share this Serial's Flax parameter scope with that layer. This
315
+ # is useful to avoid representing the Serial layer in the parameter tree. If
316
+ # child layers have conflicting parameter names, a flax.errors.NameInUsError
317
+ # is thrown. No parameter sharing will occur.
318
+ share_scope: bool | TypingSequence[bool] = False
319
+ name: str | None = None
320
+
321
+ def __post_init__(self):
322
+ # Use hashable types for sequences.
323
+ object.__setattr__(self, 'layers', tuple(self.layers))
324
+
325
+ def make(self) -> 'Serial':
326
+ return Serial(self, name=self.name)
327
+
328
+ config: Config
329
+
330
+ def setup(self) -> None:
331
+ self.layers = [l.make() for l in self.config.layers]
332
+
333
+ if self.config.share_scope:
334
+ utils.setup_shared_scope(self, self.layers, self.config.share_scope)
335
+
336
+
337
+ class SerialModules(SerialCombinatorMixin, types.Emitting):
338
+ """A Serial combinator that processes pre-existing SequenceLayers serially.
339
+
340
+ Passing pre-constructed modules into another nn.Module can have unintended
341
+ effects with respect to variable trees. The intended use of SerialModules is
342
+ to create a Serial from pre-constructed SequenceLayers when those modules are
343
+ parented to another nn.Module. For example:
344
+
345
+ class MyModule(nn.Module):
346
+ class Config:
347
+ def make(self) -> 'MyModule':
348
+ return MyModule(self)
349
+
350
+ config: Config
351
+
352
+ def setup(self) -> None:
353
+ self.encoder = self.config.encoder.make()
354
+ self.decoder = self.config.decoder.make()
355
+
356
+ # Sampler is a SequenceLayer that runs encoder and decoder.get_sampler()
357
+ # but does not own encoder or decoder.
358
+ self.sampler = sl.SerialModules(
359
+ [self.encoder, self.decoder.get_sampler()])
360
+
361
+ def get_sampler(self) -> sl.SequenceLayer:
362
+ return self.sampler
363
+ """
364
+
365
+ layers: tuple[types.SequenceLayer, ...]
366
+
367
+
368
+ class Parallel(types.Emitting):
369
+ """Applies a sequence of layers in parallel.
370
+
371
+ Outputs are broadcasted and combined together.
372
+ """
373
+
374
+ @dataclasses.dataclass(frozen=True)
375
+ class Config(types.SequenceLayerConfig):
376
+ """Config for Parallel."""
377
+
378
+ layers: TypingSequence[types.SequenceLayerConfig]
379
+ combination: utils.CombinationMode = utils.CombinationMode.STACK
380
+ # If true, a list of boolean values for each layer in `layers` indicating
381
+ # whether to share this Serial's Flax parameter scope with that layer. This
382
+ # is useful to avoid representing the Serial layer in the parameter tree. If
383
+ # child layers have conflicting parameter names, a flax.errors.NameInUsError
384
+ # is thrown. No parameter sharing will occur.
385
+ share_scope: bool | TypingSequence[bool] = False
386
+ name: str | None = None
387
+
388
+ def __post_init__(self):
389
+ # Use hashable types for sequences.
390
+ object.__setattr__(self, 'layers', tuple(self.layers))
391
+
392
+ def make(self) -> 'Parallel':
393
+ return Parallel(self, name=self.name)
394
+
395
+ config: Config
396
+
397
+ def setup(self) -> None:
398
+ self.layers = tuple(l.make() for l in self.config.layers)
399
+
400
+ if self.config.share_scope:
401
+ utils.setup_shared_scope(self, self.layers, self.config.share_scope)
402
+
403
+ if not self.layers:
404
+ self._output_ratio = fractions.Fraction(1)
405
+ return
406
+
407
+ first, *rest = self.layers
408
+ self._output_ratio = first.output_ratio
409
+ for child_layer in rest:
410
+ if child_layer.output_ratio != self._output_ratio:
411
+ raise ValueError(
412
+ 'Output ratios must be equal for all layers:'
413
+ f' {self._output_ratio} != {child_layer.output_ratio} for'
414
+ f' {child_layer}'
415
+ )
416
+
417
+ input_latency = first.input_latency
418
+ for child_layer in rest:
419
+ if (child_input_latency := child_layer.input_latency) != input_latency:
420
+ raise ValueError(
421
+ f'{self.name}: Parallel layers must have the same'
422
+ f' input latency. Child layer {child_layer.name} has'
423
+ f' input_latency={child_input_latency} which is not equal to the'
424
+ " first layer's input latency"
425
+ f' ({input_latency=}). ({self.layers=}'
426
+ )
427
+
428
+ @property
429
+ def supports_step(self) -> bool:
430
+ return all(child_layer.supports_step for child_layer in self.layers)
431
+
432
+ @property
433
+ def input_latency(self) -> int:
434
+ return self.get_accumulated_input_latency(0)
435
+
436
+ @property
437
+ def output_latency(self) -> int:
438
+ return self.get_accumulated_output_latency(0)
439
+
440
+ @functools.cached_property
441
+ def receptive_field_per_step(self) -> dict[int, types.ReceptiveField]:
442
+ if not self.layers:
443
+ return {0: (0, 0)}
444
+ return utils.aggregate_layers_receptive_field_per_steps(self.layers)
445
+
446
+ def get_accumulated_input_latency(self, input_latency: int) -> int:
447
+ """Latency of a parallel is the same for all layers."""
448
+ if not self.layers:
449
+ return input_latency
450
+
451
+ child_latencies = [
452
+ layer.get_accumulated_input_latency(input_latency)
453
+ for layer in self.layers
454
+ ]
455
+
456
+ if len(set(child_latencies)) > 1:
457
+ raise ValueError(
458
+ f'{self.name}: Parallel layers must have the same accumulated input'
459
+ f' latency. Got: {child_latencies} for {input_latency=}.'
460
+ )
461
+
462
+ return child_latencies[0]
463
+
464
+ def get_accumulated_output_latency(self, output_latency: int) -> int:
465
+ """Latency of a parallel is the same for all layers."""
466
+ if not self.layers:
467
+ return output_latency
468
+
469
+ child_latencies = [
470
+ layer.get_accumulated_output_latency(output_latency)
471
+ for layer in self.layers
472
+ ]
473
+
474
+ if len(set(child_latencies)) > 1:
475
+ raise ValueError(
476
+ f'{self.name}: Parallel layers must have the same accumulated output'
477
+ f' latency. Got: {child_latencies} for {output_latency=}.'
478
+ )
479
+ return child_latencies[0]
480
+
481
+ @property
482
+ def block_size(self) -> int:
483
+ block_size = 1
484
+ for child_layer in self.layers:
485
+ block_size = np.lcm(block_size, child_layer.block_size)
486
+ return int(block_size)
487
+
488
+ @property
489
+ def output_ratio(self) -> fractions.Fraction:
490
+ return self._output_ratio
491
+
492
+ def get_initial_state(
493
+ self,
494
+ batch_size: int,
495
+ input_spec: types.ShapeDType,
496
+ *,
497
+ training: bool,
498
+ constants: types.Constants | None = None,
499
+ ) -> types.State:
500
+ """Returns initial state for the layer."""
501
+ states = []
502
+ for child_layer in self.layers:
503
+ states.append(
504
+ child_layer.get_initial_state(
505
+ batch_size, input_spec, training=training, constants=constants
506
+ )
507
+ )
508
+ return tuple(states)
509
+
510
+ @nn.nowrap
511
+ def get_output_shape(
512
+ self,
513
+ input_shape: types.ShapeLike,
514
+ *,
515
+ constants: types.Constants | None = None,
516
+ ) -> types.Shape:
517
+ if not self.layers:
518
+ return tuple(input_shape)
519
+
520
+ output_shapes = [
521
+ child_layer.get_output_shape(input_shape, constants=constants)
522
+ for child_layer in self.layers
523
+ ]
524
+ return utils.sequence_broadcast_combine_output_channel_shape(
525
+ self.config.combination, *output_shapes
526
+ )
527
+
528
+ @nn.nowrap
529
+ def get_output_dtype(self, input_dtype: types.DType) -> types.DType:
530
+ if not self.layers:
531
+ return input_dtype
532
+
533
+ dtype = self.layers[0].get_output_dtype(input_dtype)
534
+ for child_layer in self.layers[1:]:
535
+ # TODO(rryan): We should probably disallow automatic type promotion
536
+ # between integer and float types, since this is usually a sign of a bug.
537
+ dtype = jnp.result_type(dtype, child_layer.get_output_dtype(input_dtype))
538
+ return dtype
539
+
540
+ def step_with_emits(
541
+ self,
542
+ x: types.Sequence,
543
+ state: types.State,
544
+ *,
545
+ training: bool,
546
+ constants: types.Constants | None = None,
547
+ ) -> tuple[types.Sequence, types.State, types.Emits]:
548
+ new_state = []
549
+ emits = {}
550
+ if len(self.layers) != len(state):
551
+ raise ValueError(
552
+ f'{type(self)=} {self.path=} received unexpected state structure:'
553
+ f' {len(self.layers)=} != {len(state)=}:'
554
+ f' {state=} {[type(l) for l in self.layers]=}'
555
+ )
556
+ if not self.layers:
557
+ return x, state, emits
558
+
559
+ ys = []
560
+ for child_layer, layer_state in zip(self.layers, state):
561
+ y, layer_state, layer_emits = child_layer.step_with_emits(
562
+ x, layer_state, training=training, constants=constants
563
+ )
564
+ ys.append(y)
565
+ new_state.append(layer_state)
566
+ utils.insert_with_unique_key(emits, child_layer.name, layer_emits)
567
+ y = utils.sequence_broadcast_combine(self.config.combination, *ys)
568
+ return y, tuple(new_state), emits
569
+
570
+ def layer_with_emits(
571
+ self,
572
+ x: types.Sequence,
573
+ *,
574
+ training: bool,
575
+ constants: types.Constants | None = None,
576
+ ) -> tuple[types.Sequence, types.Emits]:
577
+ emits = {}
578
+
579
+ if not self.layers:
580
+ return x, emits
581
+
582
+ ys = []
583
+ for child_layer in self.layers:
584
+ y, layer_emits = child_layer.layer_with_emits(
585
+ x, training=training, constants=constants
586
+ )
587
+ ys.append(y)
588
+ utils.insert_with_unique_key(emits, child_layer.name, layer_emits)
589
+ y = utils.sequence_broadcast_combine(self.config.combination, *ys)
590
+ return y, emits
591
+
592
+
593
+ class ParallelChannels(WrapperMixin, types.SequenceLayer):
594
+ """Applies a layer with shared parameters to groups of input channels.
595
+
596
+ The input sequence is split on its final channels dimension into num_groups
597
+ separate sequences and processed with the child layer. Unlike sl.Parallel,
598
+ parameters for the child layer are shared across all parallel invocations.
599
+
600
+ This is like a grouped convolution, but works with an arbitrary SequenceLayer.
601
+ """
602
+
603
+ @dataclasses.dataclass(frozen=True)
604
+ class Config(types.SequenceLayerConfig):
605
+ child_layer: types.SequenceLayerConfig
606
+ num_groups: int
607
+ combination: utils.CombinationMode = utils.CombinationMode.STACK
608
+ name: str | None = None
609
+
610
+ def make(self) -> types.SequenceLayer:
611
+ return ParallelChannels(self, name=self.name)
612
+
613
+ config: Config
614
+
615
+ def setup(self) -> None:
616
+ self.child_layer = self.config.child_layer.make()
617
+ nn.share_scope(self, self.child_layer)
618
+
619
+ @nn.nowrap
620
+ def get_output_shape(
621
+ self,
622
+ input_shape: types.ShapeLike,
623
+ *,
624
+ constants: types.Constants | None = None,
625
+ ) -> types.Shape:
626
+ input_shape = list(input_shape)
627
+ if not input_shape:
628
+ raise ValueError(f'Input must be at least 3D, got: {input_shape=}.')
629
+ if input_shape[-1] % self.config.num_groups != 0:
630
+ raise ValueError(
631
+ f'Input channels ({input_shape[-1]}) must be divisible by'
632
+ f' num_groups ({self.config.num_groups}).'
633
+ )
634
+ input_shape[-1] //= self.config.num_groups
635
+ result_shape = self.child_layer.get_output_shape(
636
+ input_shape, constants=constants
637
+ )
638
+ output_shapes = (result_shape,) * self.config.num_groups
639
+ return utils.sequence_broadcast_combine_output_channel_shape(
640
+ self.config.combination, *output_shapes
641
+ )
642
+
643
+ def _validate_inputs(self, x: types.Sequence) -> None:
644
+ if x.ndim == 2:
645
+ raise ValueError(f'Input must be at least 3D, got: {x.shape=}.')
646
+ if x.shape[-1] % self.config.num_groups != 0:
647
+ raise ValueError(
648
+ f'Input channels ({x.shape[-1]}) must be divisible by'
649
+ f' num_groups ({self.config.num_groups}).'
650
+ )
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
+ self._validate_inputs(x)
661
+
662
+ ys = [
663
+ self.child_layer.layer(x_i, training=training, constants=constants)
664
+ for x_i in utils.sequence_split(x, self.config.num_groups, axis=-1)
665
+ ]
666
+ return utils.sequence_broadcast_combine(self.config.combination, *ys)
667
+
668
+ @types.check_layer_with_emits
669
+ def layer_with_emits(
670
+ self,
671
+ x: types.Sequence,
672
+ *,
673
+ training: bool,
674
+ constants: types.Constants | None = None,
675
+ ) -> tuple[types.Sequence, types.Emits]:
676
+ self._validate_inputs(x)
677
+ ys, emits = [], []
678
+ for x_i in utils.sequence_split(x, self.config.num_groups, axis=-1):
679
+ y_i, emits_i = self.child_layer.layer_with_emits(
680
+ x_i, training=training, constants=constants
681
+ )
682
+ ys.append(y_i)
683
+ emits.append(emits_i)
684
+ y = utils.sequence_broadcast_combine(self.config.combination, *ys)
685
+ return y, tuple(emits)
686
+
687
+ def get_initial_state(
688
+ self,
689
+ batch_size: int,
690
+ input_spec: types.ChannelSpec,
691
+ *,
692
+ training: bool,
693
+ constants: types.Constants | None = None,
694
+ ) -> types.State:
695
+ if not input_spec.shape:
696
+ raise ValueError(f'Input must be at least 3D, got: {input_spec.shape=}.')
697
+ if input_spec.shape[-1] % self.config.num_groups != 0:
698
+ raise ValueError(
699
+ f'Input channels ({input_spec.shape[-1]}) must be divisible by'
700
+ f' num_groups ({self.config.num_groups}).'
701
+ )
702
+ input_shape = list(input_spec.shape)
703
+ input_shape[-1] //= self.config.num_groups
704
+ input_spec = types.ChannelSpec(
705
+ shape=tuple(input_shape),
706
+ dtype=input_spec.dtype,
707
+ )
708
+ state = self.child_layer.get_initial_state(
709
+ batch_size, input_spec, training=training, constants=constants
710
+ )
711
+ return (state,) * self.config.num_groups
712
+
713
+ @types.check_step
714
+ def step(
715
+ self,
716
+ x: types.Sequence,
717
+ state: types.State,
718
+ *,
719
+ training: bool,
720
+ constants: types.Constants | None = None,
721
+ ) -> tuple[types.Sequence, types.State]:
722
+ self._validate_inputs(x)
723
+
724
+ xs = utils.sequence_split(x, self.config.num_groups, axis=-1)
725
+ ys = []
726
+ states = []
727
+ for x_i, state_i in zip(xs, state, strict=True):
728
+ y_i, state_i = self.child_layer.step(
729
+ x_i, state_i, training=training, constants=constants
730
+ )
731
+ ys.append(y_i)
732
+ states.append(state_i)
733
+ y = utils.sequence_broadcast_combine(self.config.combination, *ys)
734
+ return y, tuple(states)
735
+
736
+ @types.check_step_with_emits
737
+ def step_with_emits(
738
+ self,
739
+ x: types.Sequence,
740
+ state: types.State,
741
+ *,
742
+ training: bool,
743
+ constants: types.Constants | None = None,
744
+ ) -> tuple[types.Sequence, types.State, types.Emits]:
745
+ self._validate_inputs(x)
746
+
747
+ xs = utils.sequence_split(x, self.config.num_groups, axis=-1)
748
+ ys = []
749
+ states = []
750
+ emits = []
751
+ for x_i, state_i in zip(xs, state, strict=True):
752
+ y_i, state_i, emits_i = self.child_layer.step_with_emits(
753
+ x_i, state_i, training=training, constants=constants
754
+ )
755
+ ys.append(y_i)
756
+ states.append(state_i)
757
+ emits.append(emits_i)
758
+ y = utils.sequence_broadcast_combine(self.config.combination, *ys)
759
+ return y, tuple(states), tuple(emits)
760
+
761
+
762
+ class Residual(SerialCombinatorMixin, types.Emitting):
763
+ """A residual wrapper around l that computes `y = l(x) + shortcut(x)`.
764
+
765
+ If shortcut is not provided, it defaults to an identity or a linear projection
766
+ to match the output shape of l(x).
767
+
768
+ Subclasses may override the combination logic via `residual_function`.
769
+ """
770
+
771
+ @dataclasses.dataclass(frozen=True)
772
+ class Config(types.SequenceLayerConfig):
773
+ """Config for Residual."""
774
+
775
+ layers: TypingSequence[types.SequenceLayerConfig]
776
+ shortcut_layers: TypingSequence[types.SequenceLayerConfig] | None = None
777
+ # If true, a list of boolean values for each layer in `layers` indicating
778
+ # whether to share this Residual's Flax parameter scope with that layer.
779
+ # This is useful to avoid representing the Residual layer in the parameter
780
+ # tree. If child layers have conflicting parameter names, a
781
+ # flax.errors.NameInUsError is thrown. No parameter sharing will occur.
782
+ share_scope: bool | TypingSequence[bool] = False
783
+ name: str | None = None
784
+
785
+ def __post_init__(self):
786
+ # Use hashable types for sequences.
787
+ object.__setattr__(self, 'layers', tuple(self.layers))
788
+ if self.shortcut_layers is not None:
789
+ object.__setattr__(self, 'shortcut_layers', tuple(self.shortcut_layers))
790
+
791
+ def make(self) -> 'Residual':
792
+ return Residual(self, name=self.name)
793
+
794
+ config: Config
795
+
796
+ def setup(self) -> None:
797
+ self.layers = tuple(l.make() for l in self.config.layers)
798
+ if self.config.share_scope:
799
+ utils.setup_shared_scope(self, self.layers, self.config.share_scope)
800
+
801
+ if self.config.shortcut_layers is None:
802
+ self.shortcut_layer = simple.Identity()
803
+ else:
804
+ self.shortcut_layer = _wrap_layers(self.config.shortcut_layers)
805
+
806
+ if self.shortcut_layer.output_ratio != super().output_ratio:
807
+ raise ValueError(
808
+ 'Residual layers and shortcut_layers must have the same output '
809
+ f'ratio {super().output_ratio} != '
810
+ f'{self.shortcut_layer.output_ratio}.'
811
+ )
812
+ if self.shortcut_layer.input_latency != super().input_latency:
813
+ raise ValueError(
814
+ f'{self.name}: Residual layers and shortcut_layers must have the same'
815
+ f' input latency {super().input_latency} !='
816
+ f' {self.shortcut_layer.input_latency}. ({self.layers=},'
817
+ f' {self.shortcut_layer=})'
818
+ )
819
+
820
+ @property
821
+ def supports_step(self) -> bool:
822
+ return super().supports_step and self.shortcut_layer.supports_step
823
+
824
+ @property
825
+ def input_latency(self) -> int:
826
+ return self.get_accumulated_input_latency(0)
827
+
828
+ @property
829
+ def output_latency(self) -> int:
830
+ return self.get_accumulated_output_latency(0)
831
+
832
+ @functools.cached_property
833
+ def receptive_field(self) -> types.ReceptiveField:
834
+ return utils.reduce_receptive_field_per_step(
835
+ self.receptive_field_per_step, self.output_ratio
836
+ )
837
+
838
+ @functools.cached_property
839
+ def receptive_field_per_step(self) -> dict[int, types.ReceptiveField]:
840
+ layers_rf_per_step = super().receptive_field_per_step
841
+ shortcut_rf_per_step = self.shortcut_layer.receptive_field_per_step
842
+ layers_output_ratio = super().output_ratio
843
+ shortcut_output_ratio = self.shortcut_layer.output_ratio
844
+ types.validate_receptive_field_per_step(layers_rf_per_step)
845
+ types.validate_receptive_field_per_step(shortcut_rf_per_step)
846
+ steps = range(math.lcm(len(layers_rf_per_step), len(shortcut_rf_per_step)))
847
+ rf_per_step = {}
848
+ for step in steps:
849
+ rf_per_step[step] = utils.receptive_field_union(
850
+ utils.receptive_field_at(
851
+ layers_rf_per_step, layers_output_ratio, step
852
+ ),
853
+ utils.receptive_field_at(
854
+ shortcut_rf_per_step, shortcut_output_ratio, step
855
+ ),
856
+ )
857
+ types.validate_receptive_field_per_step(rf_per_step)
858
+ return rf_per_step
859
+
860
+ def get_accumulated_input_latency(self, input_latency: int) -> int:
861
+ latency = super().get_accumulated_input_latency(input_latency)
862
+ shortcut_latency = self.shortcut_layer.get_accumulated_input_latency(
863
+ input_latency
864
+ )
865
+ if latency != shortcut_latency:
866
+ raise ValueError(
867
+ 'Residual layers and shortcut_layers must have the same input'
868
+ f' latency {latency} != {shortcut_latency}. ({self.layers=},'
869
+ f' {self.shortcut_layer=})'
870
+ )
871
+ return latency
872
+
873
+ def get_accumulated_output_latency(self, output_latency: int) -> int:
874
+ latency = super().get_accumulated_output_latency(output_latency)
875
+ shortcut_latency = self.shortcut_layer.get_accumulated_output_latency(
876
+ output_latency
877
+ )
878
+ if latency != shortcut_latency:
879
+ raise ValueError(
880
+ 'Residual layers and shortcut_layers must have the same output'
881
+ f' latency {latency} != {shortcut_latency}. ({self.layers=},'
882
+ f' {self.shortcut_layer=})'
883
+ )
884
+ return latency
885
+
886
+ @property
887
+ def block_size(self) -> int:
888
+ if self.shortcut_layer:
889
+ return int(np.lcm(super().block_size, self.shortcut_layer.block_size))
890
+ return super().block_size
891
+
892
+ @nn.nowrap
893
+ def _validate(
894
+ self,
895
+ x_spec: types.ShapeDType,
896
+ constants: types.Constants,
897
+ ):
898
+ layer_shape = super().get_output_shape(x_spec.shape, constants=constants)
899
+ shortcut_shape = self.shortcut_layer.get_output_shape(
900
+ x_spec.shape, constants=constants
901
+ )
902
+ # TODO(rryan): Support broadcastable shapes.
903
+ if layer_shape != shortcut_shape:
904
+ raise ValueError(
905
+ f'{self.name}: Residual connection must have same output shape: '
906
+ f'layer: {layer_shape} shortcut: {shortcut_shape}'
907
+ )
908
+
909
+ layer_dtype = super().get_output_dtype(x_spec.dtype)
910
+ shortcut_dtype = self.shortcut_layer.get_output_dtype(x_spec.dtype)
911
+ # Make sure we can compute a result dtype.
912
+ jnp.result_type(layer_dtype, shortcut_dtype)
913
+
914
+ def residual_function(
915
+ self, y_body: types.Sequence, y_shortcut: types.Sequence
916
+ ) -> types.Sequence:
917
+ """Combines the body and shortcut layer outputs."""
918
+ y_values = y_body.values + y_shortcut.values
919
+ y_mask = utils.combine_mask(y_body.mask, y_shortcut.mask)
920
+
921
+ # Assume unmasked since masking is only preserved when both sequences are
922
+ # masked and the body and shortcut masks are equal.
923
+ return types.Sequence(y_values, y_mask)
924
+
925
+ def step_with_emits(
926
+ self,
927
+ x: types.Sequence,
928
+ state: types.State,
929
+ *,
930
+ training: bool,
931
+ constants: types.Constants | None = None,
932
+ ) -> tuple[types.Sequence, types.State, types.Emits]:
933
+ self._validate(x.channel_spec, constants)
934
+ body_state, shortcut_state = state
935
+ y_body, body_state, body_emits = super().step_with_emits(
936
+ x, body_state, training=training, constants=constants
937
+ )
938
+ y_shortcut, shortcut_state, shortcut_emits = (
939
+ self.shortcut_layer.step_with_emits(
940
+ x, shortcut_state, training=training, constants=constants
941
+ )
942
+ )
943
+ y = self.residual_function(y_body, y_shortcut)
944
+
945
+ state = (body_state, shortcut_state)
946
+ emits = (body_emits, shortcut_emits)
947
+ return y, state, emits
948
+
949
+ def layer_with_emits(
950
+ self,
951
+ x: types.Sequence,
952
+ *,
953
+ training: bool,
954
+ constants: types.Constants | None = None,
955
+ ) -> tuple[types.Sequence, types.Emits]:
956
+ self._validate(x.channel_spec, constants)
957
+ y_body, body_emits = super().layer_with_emits(
958
+ x, training=training, constants=constants
959
+ )
960
+ y_shortcut, shortcut_emits = self.shortcut_layer.layer_with_emits(
961
+ x,
962
+ training=training,
963
+ constants=constants,
964
+ )
965
+ y = self.residual_function(y_body, y_shortcut)
966
+ emits = (body_emits, shortcut_emits)
967
+ return y, emits
968
+
969
+ def get_initial_state(
970
+ self,
971
+ batch_size: int,
972
+ input_spec: types.ShapeDType,
973
+ *,
974
+ training: bool,
975
+ constants: types.Constants | None = None,
976
+ ) -> types.State:
977
+ body_state = super().get_initial_state(
978
+ batch_size, input_spec, training=training, constants=constants
979
+ )
980
+ shortcut_state = self.shortcut_layer.get_initial_state(
981
+ batch_size, input_spec, training=training, constants=constants
982
+ )
983
+ return body_state, shortcut_state
984
+
985
+ @nn.nowrap
986
+ def get_output_dtype(self, input_dtype: types.DType) -> types.DType:
987
+ layer_dtype = super().get_output_dtype(input_dtype)
988
+ shortcut_dtype = self.shortcut_layer.get_output_dtype(input_dtype)
989
+ # TODO(rryan): We should probably disallow automatic type promotion between
990
+ # integer and float types, since this is usually a sign of a bug.
991
+ return jnp.result_type(layer_dtype, shortcut_dtype)
992
+
993
+
994
+ class Repeat(types.Emitting):
995
+ """A combinator that repeats the specified SequenceLayer N times.
996
+
997
+ Execution is performed in a loop, enabling reduced compilation times since the
998
+ layer logic only has to be compiled once.
999
+
1000
+ Variables and layer state are represented in a stacked fashion, with a
1001
+ `num_repeats` leading dimension.
1002
+
1003
+ Requires that the layer being repeated has an `output_ratio` of 1, and that
1004
+ the output dtype and shape are equal to the input dtype and shape, since the
1005
+ input and output to jax.nn.scan must be equal.
1006
+
1007
+ TODO(rryan): It's possible to support `output_ratios` with padding of the
1008
+ inputs or outputs.
1009
+ """
1010
+
1011
+ @dataclasses.dataclass(frozen=True)
1012
+ class Config(types.SequenceLayerConfig):
1013
+ layer: types.SequenceLayerConfig
1014
+ num_repeats: int
1015
+ remat: bool = False
1016
+ # Whether to unroll the repeat layer when running layer-wise.
1017
+ unroll_layer: bool = False
1018
+ # Whether to unroll the repeat layer when running step-wise.
1019
+ unroll_step: bool = False
1020
+ name: str | None = None
1021
+
1022
+ def make(self) -> 'Repeat':
1023
+ return Repeat(self, name=self.name)
1024
+
1025
+ config: Config
1026
+
1027
+ def setup(self):
1028
+ if not self.config.num_repeats:
1029
+ raise ValueError(f'Expected {self.config.num_repeats=} > 0.')
1030
+ self.child_layer = self.config.layer.make()
1031
+
1032
+ def _get_child_property(
1033
+ self, property_fn: Callable[[types.SequenceLayer], T]
1034
+ ) -> T:
1035
+ results = []
1036
+
1037
+ def scan_fn(
1038
+ child_layer: types.SequenceLayer,
1039
+ scan_carry,
1040
+ scan_input,
1041
+ ):
1042
+ del scan_carry, scan_input
1043
+ results.append(property_fn(child_layer))
1044
+ return (), ()
1045
+
1046
+ repeat = nn.scan(
1047
+ scan_fn,
1048
+ variable_axes={True: 0}, # Slice all variables on axis 0.
1049
+ variable_broadcast=False,
1050
+ in_axes=0, # No input.
1051
+ out_axes=0, # No output.
1052
+ split_rngs={
1053
+ 'params': self.is_initializing(),
1054
+ nn.DenyList(('params',)): True,
1055
+ },
1056
+ length=self.config.num_repeats,
1057
+ metadata_params={
1058
+ # For params we replicate along this scan-over-layers axis.
1059
+ meta.MESH_AXIS: None,
1060
+ # For optimizers mark this axis in params as 'independent'.
1061
+ meta.AXIS_TYPE: meta.AxisType.STACKED,
1062
+ },
1063
+ )
1064
+
1065
+ # No inputs or outputs.
1066
+ repeat(self.child_layer, (), ())
1067
+ if len(set(results)) != 1:
1068
+ raise ValueError(
1069
+ 'Repeat._get_child_property expected all results to be equal:'
1070
+ f' {results=}'
1071
+ )
1072
+ return results[0]
1073
+
1074
+ def _build_child_layer_scanner(self, scan_fn):
1075
+ return nn.scan(
1076
+ scan_fn,
1077
+ variable_axes={True: 0}, # Slice all variables on axis 0.
1078
+ variable_broadcast=False,
1079
+ in_axes=0, # No input.
1080
+ out_axes=0, # No output.
1081
+ split_rngs={
1082
+ 'params': self.is_initializing(),
1083
+ nn.DenyList(('params',)): True,
1084
+ },
1085
+ length=self.config.num_repeats,
1086
+ metadata_params={
1087
+ # For params we replicate along this scan-over-layers axis.
1088
+ meta.MESH_AXIS: None,
1089
+ # For optimizers mark this axis in params as 'independent'.
1090
+ meta.AXIS_TYPE: meta.AxisType.STACKED,
1091
+ },
1092
+ )
1093
+
1094
+ @property
1095
+ def supports_step(self) -> bool:
1096
+ return self._get_child_property(lambda l: l.supports_step)
1097
+
1098
+ @property
1099
+ def input_latency(self) -> int:
1100
+ return self.get_accumulated_input_latency(0)
1101
+
1102
+ @property
1103
+ def output_latency(self) -> int:
1104
+ return self.get_accumulated_output_latency(0)
1105
+
1106
+ @functools.cached_property
1107
+ def receptive_field_per_step(self) -> dict[int, types.ReceptiveField]:
1108
+ layer_rf_per_step = [{}]
1109
+ layer_output_ratio = [fractions.Fraction(1)]
1110
+
1111
+ def scan_fn(
1112
+ child_layer: types.SequenceLayer,
1113
+ scan_carry,
1114
+ scan_input,
1115
+ ):
1116
+ layer_rf_per_step[0] = child_layer.receptive_field_per_step
1117
+ layer_output_ratio[0] = child_layer.output_ratio
1118
+ return scan_carry, scan_input
1119
+
1120
+ # This is slightly inefficient since scan keeps overwritting the receptive
1121
+ # field and output ratios which do not change in scan iterations.
1122
+ self._build_child_layer_scanner(scan_fn)(self.child_layer, (), ())
1123
+
1124
+ overall_rf_per_step = layer_rf_per_step[0]
1125
+ for _ in range(self.config.num_repeats - 1):
1126
+ overall_rf_per_step = utils.propagate_receptive_field_to_prev_layer(
1127
+ overall_rf_per_step, layer_rf_per_step[0], layer_output_ratio[0]
1128
+ )
1129
+ return overall_rf_per_step
1130
+
1131
+ def get_accumulated_input_latency(self, input_latency: int) -> int:
1132
+ result = [input_latency]
1133
+
1134
+ def scan_fn(
1135
+ child_layer: types.SequenceLayer,
1136
+ scan_carry,
1137
+ scan_input,
1138
+ ):
1139
+ result[0] = child_layer.get_accumulated_input_latency(result[0])
1140
+ return scan_carry, scan_input
1141
+
1142
+ self._build_child_layer_scanner(scan_fn)(self.child_layer, (), ())
1143
+ input_latency = result[0]
1144
+ return input_latency
1145
+
1146
+ def get_accumulated_output_latency(self, output_latency: int) -> int:
1147
+ result = [output_latency]
1148
+
1149
+ def scan_fn(
1150
+ child_layer: types.SequenceLayer,
1151
+ scan_carry,
1152
+ scan_input,
1153
+ ):
1154
+ result[0] = child_layer.get_accumulated_output_latency(result[0])
1155
+ return scan_carry, scan_input
1156
+
1157
+ self._build_child_layer_scanner(scan_fn)(self.child_layer, (), ())
1158
+ output_latency = result[0]
1159
+ return output_latency
1160
+
1161
+ @property
1162
+ def block_size(self) -> int:
1163
+ """The block size of the layer."""
1164
+ block_size = fractions.Fraction(1)
1165
+ output_ratio = fractions.Fraction(1)
1166
+
1167
+ layer_output_ratio = self._get_child_property(lambda l: l.output_ratio)
1168
+ layer_block_size = self._get_child_property(lambda l: l.block_size)
1169
+
1170
+ # TODO(rryan): Clean up logic.
1171
+ for _ in range(self.config.num_repeats):
1172
+ block_size = (
1173
+ np.lcm(block_size * output_ratio, layer_block_size) / output_ratio
1174
+ )
1175
+ output_ratio *= layer_output_ratio
1176
+
1177
+ assert block_size.denominator == 1
1178
+ return block_size.numerator
1179
+
1180
+ @property
1181
+ def output_ratio(self) -> fractions.Fraction:
1182
+ layer_output_ratio = self._get_child_property(lambda l: l.output_ratio)
1183
+ return layer_output_ratio**self.config.num_repeats
1184
+
1185
+ @nn.nowrap
1186
+ def get_output_dtype(self, input_dtype: types.DType) -> types.DType:
1187
+ # _validate asserts that input_dtype equals output_dtype.
1188
+ return input_dtype
1189
+
1190
+ @nn.nowrap
1191
+ def get_output_shape(
1192
+ self,
1193
+ input_shape: types.ShapeLike,
1194
+ *,
1195
+ constants: types.Constants | None = None,
1196
+ ) -> types.Shape:
1197
+ # _validate asserts that input shape equals output shape.
1198
+ return tuple(input_shape)
1199
+
1200
+ @nn.nowrap
1201
+ def _validate(
1202
+ self, input_spec: types.ChannelSpec, constants: types.Constants | None
1203
+ ):
1204
+ del input_spec
1205
+ del constants
1206
+
1207
+ child_output_ratio = self._get_child_property(lambda l: l.output_ratio)
1208
+ if child_output_ratio != 1:
1209
+ raise ValueError(
1210
+ f'Repeat layer must have output ratio of 1: {child_output_ratio=}.'
1211
+ )
1212
+
1213
+ # TODO(rryan): Check that child layer's output dtype matches the input
1214
+ # dtype. We cannot accurately compute child_layer's output type using
1215
+ # SequenceLayer.get_output_dtype, since our weights might have
1216
+ # been replaced with donwcasted versions.
1217
+
1218
+ @types.check_layer
1219
+ def layer(
1220
+ self,
1221
+ x: types.Sequence,
1222
+ *,
1223
+ training: bool,
1224
+ constants: types.Constants | None = None,
1225
+ ) -> types.Sequence:
1226
+ y, _ = self._layer_internal(x, training, constants, with_emits=False)
1227
+ return y
1228
+
1229
+ @types.check_layer_with_emits
1230
+ def layer_with_emits(
1231
+ self,
1232
+ x: types.Sequence,
1233
+ *,
1234
+ training: bool,
1235
+ constants: types.Constants | None = None,
1236
+ ) -> tuple[types.Sequence, types.Emits]:
1237
+ return self._layer_internal(x, training, constants, with_emits=True)
1238
+
1239
+ def _layer_internal(
1240
+ self,
1241
+ x: types.Sequence,
1242
+ training: bool,
1243
+ constants: types.Constants | None,
1244
+ with_emits: bool,
1245
+ ) -> tuple[types.Sequence, types.Emits]:
1246
+ self._validate(x.channel_spec, constants)
1247
+
1248
+ def scan_fn(child_layer, scan_carry: types.Sequence, scan_input):
1249
+ del scan_input
1250
+ x = scan_carry
1251
+ if with_emits:
1252
+ y, emits = child_layer.layer_with_emits(
1253
+ x, training=training, constants=constants
1254
+ )
1255
+ else:
1256
+ y = child_layer.layer(x, training=training, constants=constants)
1257
+ emits = ()
1258
+
1259
+ scan_output = emits
1260
+ # Unmask the sequence so that scan's type checks pass.
1261
+ scan_carry_output = y.unmask()
1262
+ return scan_carry_output, scan_output
1263
+
1264
+ if self.config.remat:
1265
+ # TODO(rryan): Support customization (prevent_cse, policy, etc.).
1266
+ scan_fn = nn.remat(scan_fn, prevent_cse=False)
1267
+
1268
+ metadata_params = {
1269
+ # For params we replicate along this scan-over-layers axis.
1270
+ meta.MESH_AXIS: None,
1271
+ # For optimizers mark this axis in params as 'independent'.
1272
+ meta.AXIS_TYPE: meta.AxisType.STACKED,
1273
+ }
1274
+
1275
+ if not self.is_initializing() and self.config.unroll_layer:
1276
+ emits = []
1277
+
1278
+ def trans_in_fn(tree, i):
1279
+ tree = flax.core.meta.remove_axis(tree, 0, metadata_params)
1280
+ return jax.tree.map(lambda a: a[i], tree)
1281
+
1282
+ def trans_out_fn(tree):
1283
+ return flax.core.meta.add_axis(tree, 0, metadata_params)
1284
+
1285
+ for i in range(self.config.num_repeats):
1286
+ x, emit_i = nn.map_variables(
1287
+ scan_fn,
1288
+ trans_in_fn=functools.partial(trans_in_fn, i=i),
1289
+ trans_out_fn=trans_out_fn,
1290
+ )(self.child_layer, x, ())
1291
+ emits.append(emit_i)
1292
+
1293
+ return x, tuple(emits)
1294
+
1295
+ repeat = nn.scan(
1296
+ scan_fn,
1297
+ variable_axes={True: 0}, # Slice all variables on axis 0.
1298
+ variable_broadcast=False,
1299
+ in_axes=0, # No inputs.
1300
+ out_axes=0, # Emits packed on axis 0.
1301
+ # Split all RNGs in our scope except for params when not initializing.
1302
+ split_rngs={
1303
+ 'params': self.is_initializing(),
1304
+ nn.DenyList(('params',)): True,
1305
+ },
1306
+ length=self.config.num_repeats,
1307
+ metadata_params=metadata_params,
1308
+ )
1309
+
1310
+ # repeat(module, carry, *xs)
1311
+ # Unmask the sequence so that scan's type checks pass.
1312
+ scan_carry = x.unmask()
1313
+ scan_input = ()
1314
+ scan_carry_output, scan_output = repeat(
1315
+ self.child_layer, scan_carry, scan_input
1316
+ )
1317
+
1318
+ y = scan_carry_output
1319
+ emits = scan_output
1320
+
1321
+ # Emits are stacked on axis 0. Unpack them.
1322
+ emits = utils.unstack_tree(emits)
1323
+
1324
+ return y, emits
1325
+
1326
+ def get_initial_state(
1327
+ self,
1328
+ batch_size: int,
1329
+ input_spec: types.ChannelSpec,
1330
+ *,
1331
+ training: bool,
1332
+ constants: types.Constants | None = None,
1333
+ ) -> types.State:
1334
+ self._validate(input_spec, constants)
1335
+
1336
+ def scan_fn(
1337
+ child_layer: types.SequenceLayer,
1338
+ scan_carry,
1339
+ scan_input,
1340
+ ):
1341
+ del scan_carry, scan_input
1342
+ state = child_layer.get_initial_state(
1343
+ batch_size, input_spec, training=training, constants=constants
1344
+ )
1345
+ scan_output = state
1346
+ scan_carry_output = ()
1347
+ return scan_carry_output, scan_output
1348
+
1349
+ metadata_params = {
1350
+ # For params we replicate along this scan-over-layers axis.
1351
+ meta.MESH_AXIS: None,
1352
+ # For optimizers mark this axis in params as 'independent'.
1353
+ meta.AXIS_TYPE: meta.AxisType.STACKED,
1354
+ }
1355
+
1356
+ if not self.is_initializing() and self.config.unroll_step:
1357
+ states = []
1358
+
1359
+ def trans_in_fn(tree, i):
1360
+ tree = flax.core.meta.remove_axis(tree, 0, metadata_params)
1361
+ return jax.tree.map(lambda a: a[i], tree)
1362
+
1363
+ def trans_out_fn(tree):
1364
+ return flax.core.meta.add_axis(tree, 0, metadata_params)
1365
+
1366
+ for i in range(self.config.num_repeats):
1367
+ _, state = nn.map_variables(
1368
+ scan_fn,
1369
+ trans_in_fn=functools.partial(trans_in_fn, i=i),
1370
+ trans_out_fn=trans_out_fn,
1371
+ )(self.child_layer, (), ())
1372
+ states.append(state)
1373
+ return tuple(states)
1374
+
1375
+ repeat = nn.scan(
1376
+ scan_fn,
1377
+ variable_axes={True: 0}, # Slice all variables on axis 0.
1378
+ variable_broadcast=False,
1379
+ in_axes=0, # No input.
1380
+ out_axes=1, # State stacked on axis 1.
1381
+ split_rngs={
1382
+ 'params': self.is_initializing(),
1383
+ nn.DenyList(('params',)): True,
1384
+ },
1385
+ length=self.config.num_repeats,
1386
+ metadata_params=metadata_params,
1387
+ )
1388
+
1389
+ # No carry or input.
1390
+ scan_carry = ()
1391
+ scan_input = ()
1392
+ # repeat(module, carry, *xs)
1393
+ scan_carry_output, scan_output = repeat(
1394
+ self.child_layer, scan_carry, scan_input
1395
+ )
1396
+ # No carry output.
1397
+ del scan_carry_output
1398
+ state = scan_output
1399
+
1400
+ return state
1401
+
1402
+ @types.check_step
1403
+ def step(
1404
+ self,
1405
+ x: types.Sequence,
1406
+ state: types.State,
1407
+ *,
1408
+ training: bool,
1409
+ constants: types.Constants | None = None,
1410
+ ) -> tuple[types.Sequence, types.State]:
1411
+ y, state, _ = self._step_internal(
1412
+ x, state, training=training, constants=constants, with_emits=False
1413
+ )
1414
+ return y, state
1415
+
1416
+ @types.check_step_with_emits
1417
+ def step_with_emits(
1418
+ self,
1419
+ x: types.Sequence,
1420
+ state: types.State,
1421
+ *,
1422
+ training: bool,
1423
+ constants: types.Constants | None = None,
1424
+ ) -> tuple[types.Sequence, types.State, types.Emits]:
1425
+ return self._step_internal(
1426
+ x, state, training=training, constants=constants, with_emits=True
1427
+ )
1428
+
1429
+ def _step_internal(
1430
+ self,
1431
+ x: types.Sequence,
1432
+ state: types.State,
1433
+ *,
1434
+ training: bool,
1435
+ constants: types.Constants | None,
1436
+ with_emits: bool,
1437
+ ) -> tuple[types.Sequence, types.State, types.Emits]:
1438
+ self._validate(x.channel_spec, constants)
1439
+
1440
+ def scan_fn(
1441
+ child_layer: types.SequenceLayer,
1442
+ scan_carry: types.Sequence,
1443
+ scan_input: types.State,
1444
+ ):
1445
+ x = scan_carry
1446
+ state = scan_input
1447
+ if with_emits:
1448
+ y, state, emits = child_layer.step_with_emits(
1449
+ x, state, training=training, constants=constants
1450
+ )
1451
+ else:
1452
+ y, state = child_layer.step(
1453
+ x, state, training=training, constants=constants
1454
+ )
1455
+ emits = ()
1456
+
1457
+ scan_output = (state, emits)
1458
+ # Unmask the sequence so that scan's type checks pass.
1459
+ scan_carry_output = y.unmask()
1460
+ return scan_carry_output, scan_output
1461
+
1462
+ if self.config.remat:
1463
+ scan_fn = nn.remat(scan_fn)
1464
+
1465
+ metadata_params = {
1466
+ # For params we replicate along this scan-over-layers axis.
1467
+ meta.MESH_AXIS: None,
1468
+ # For optimizers mark this axis in params as 'independent'.
1469
+ meta.AXIS_TYPE: meta.AxisType.STACKED,
1470
+ }
1471
+
1472
+ if not self.is_initializing() and self.config.unroll_step:
1473
+ states = []
1474
+ emits = []
1475
+
1476
+ def trans_in_fn(tree, i):
1477
+ tree = flax.core.meta.remove_axis(tree, 0, metadata_params)
1478
+ return jax.tree.map(lambda a: a[i], tree)
1479
+
1480
+ def trans_out_fn(tree):
1481
+ return flax.core.meta.add_axis(tree, 0, metadata_params)
1482
+
1483
+ for i, state_i in enumerate(state):
1484
+ x, (state_i, emit_i) = nn.map_variables(
1485
+ scan_fn,
1486
+ trans_in_fn=functools.partial(trans_in_fn, i=i),
1487
+ trans_out_fn=trans_out_fn,
1488
+ )(self.child_layer, x, state_i)
1489
+ states.append(state_i)
1490
+ emits.append(emit_i)
1491
+
1492
+ return x, tuple(states), tuple(emits)
1493
+
1494
+ repeat = nn.scan(
1495
+ scan_fn,
1496
+ variable_axes={True: 0}, # Slice all variables on axis 0.
1497
+ variable_broadcast=False,
1498
+ in_axes=1, # State packed on axis 1.
1499
+ out_axes=1, # State and emits stacked on axis 1.
1500
+ split_rngs={
1501
+ 'params': self.is_initializing(),
1502
+ nn.DenyList(('params',)): True,
1503
+ },
1504
+ length=self.config.num_repeats,
1505
+ metadata_params=metadata_params,
1506
+ )
1507
+
1508
+ # Unmask the sequence so that scan's type checks pass.
1509
+ scan_carry = x.unmask()
1510
+ scan_input = state
1511
+ scan_carry_output, scan_output = repeat(
1512
+ self.child_layer, scan_carry, scan_input
1513
+ )
1514
+
1515
+ y = scan_carry_output
1516
+ state, emits = scan_output
1517
+
1518
+ # Emits are stacked on axis 1. Unpack them.
1519
+ emits = utils.unstack_tree(emits, axis=1)
1520
+
1521
+ return y, state, emits
1522
+
1523
+
1524
+ class CheckpointGradient(WrapperMixin, types.Emitting):
1525
+ """A layer that wraps the specified SequenceLayer with a gradient checkpoint.
1526
+
1527
+ This enables a memory/compute trade-off during gradient calculations by
1528
+ discarding intermediate activations within the wrapped SequenceLayer in the
1529
+ forward pass, and recalculating the forward activations in the backward pass.
1530
+
1531
+ This layer is a no-op when not computing gradients, however it will introduce
1532
+ an additional layer in the variable tree due to how Flax variable tracking
1533
+ works, so wrapping a layer with CheckpointGradient is not checkpoint
1534
+ compatible with a non-wrapped layer.
1535
+ """
1536
+
1537
+ @dataclasses.dataclass(frozen=True)
1538
+ class Config(types.SequenceLayerConfig):
1539
+ """Config for CheckpointGradient."""
1540
+
1541
+ layer: types.SequenceLayerConfig
1542
+ # Whether to prevent common subexpression elimination (CSE). Preventing CSE
1543
+ # comes with a potentially high cost performance-wise, but is true by
1544
+ # default since it can prevent the intended behavior of gradient
1545
+ # checkpointing. If used inside of an nn.scan, this is unnecessary and can
1546
+ # be set to false.
1547
+ prevent_cse: bool = True
1548
+ # JAX checkpoint policy. By default, recalculates everything.
1549
+ # https://jax.readthedocs.io/en/latest/notebooks/autodiff_remat.html
1550
+ # TODO(rryan): Do we need a layer vs. step policy?
1551
+ policy: Callable[..., bool] | None = None
1552
+ name: str | None = None
1553
+
1554
+ def make(self) -> 'CheckpointGradient':
1555
+ return CheckpointGradient(self, name=self.name)
1556
+
1557
+ config: Config
1558
+
1559
+ def setup(self) -> None:
1560
+ self.child_layer = self.config.layer.make()
1561
+
1562
+ def layer(
1563
+ self,
1564
+ x: types.Sequence,
1565
+ *,
1566
+ training: bool,
1567
+ constants: types.Constants | None = None,
1568
+ ) -> types.Sequence:
1569
+ @functools.partial(
1570
+ nn.checkpoint,
1571
+ prevent_cse=self.config.prevent_cse,
1572
+ policy=self.config.policy,
1573
+ )
1574
+ def checkpoint_fn(
1575
+ child_layer: types.SequenceLayer,
1576
+ x: types.Sequence,
1577
+ constants: types.Constants | None,
1578
+ ) -> types.Sequence:
1579
+ return child_layer.layer(x, training=training, constants=constants)
1580
+
1581
+ return checkpoint_fn(self.child_layer, x, constants)
1582
+
1583
+ def layer_with_emits(
1584
+ self,
1585
+ x: types.Sequence,
1586
+ *,
1587
+ training: bool,
1588
+ constants: types.Constants | None = None,
1589
+ ) -> tuple[types.Sequence, types.Emits]:
1590
+ @functools.partial(
1591
+ nn.checkpoint,
1592
+ prevent_cse=self.config.prevent_cse,
1593
+ policy=self.config.policy,
1594
+ )
1595
+ def checkpoint_fn(
1596
+ child_layer: types.SequenceLayer,
1597
+ x: types.Sequence,
1598
+ constants: types.Constants | None,
1599
+ ) -> tuple[types.Sequence, types.Emits]:
1600
+ return child_layer.layer_with_emits(
1601
+ x, training=training, constants=constants
1602
+ )
1603
+
1604
+ return checkpoint_fn(self.child_layer, x, constants)
1605
+
1606
+ def step(
1607
+ self,
1608
+ x: types.Sequence,
1609
+ state: types.State,
1610
+ *,
1611
+ training: bool,
1612
+ constants: types.Constants | None = None,
1613
+ ) -> tuple[types.Sequence, types.State]:
1614
+ @functools.partial(
1615
+ nn.checkpoint,
1616
+ prevent_cse=self.config.prevent_cse,
1617
+ policy=self.config.policy,
1618
+ )
1619
+ def checkpoint_fn(
1620
+ child_layer: types.SequenceLayer,
1621
+ x: types.Sequence,
1622
+ state: types.State,
1623
+ constants: types.Constants | None,
1624
+ ) -> tuple[types.Sequence, types.State]:
1625
+ return child_layer.step(x, state, training=training, constants=constants)
1626
+
1627
+ return checkpoint_fn(self.child_layer, x, state, constants)
1628
+
1629
+ def step_with_emits(
1630
+ self,
1631
+ x: types.Sequence,
1632
+ state: types.State,
1633
+ *,
1634
+ training: bool,
1635
+ constants: types.Constants | None = None,
1636
+ ) -> tuple[types.Sequence, types.State, types.Emits]:
1637
+ @functools.partial(
1638
+ nn.checkpoint,
1639
+ prevent_cse=self.config.prevent_cse,
1640
+ policy=self.config.policy,
1641
+ )
1642
+ def checkpoint_fn(
1643
+ child_layer: types.SequenceLayer,
1644
+ x: types.Sequence,
1645
+ state: types.State,
1646
+ constants: types.Constants | None,
1647
+ ) -> tuple[types.Sequence, types.State, types.Emits]:
1648
+ return child_layer.step_with_emits(
1649
+ x, state, training=training, constants=constants
1650
+ )
1651
+
1652
+ return checkpoint_fn(self.child_layer, x, state, constants)
1653
+
1654
+
1655
+ class Bidirectional(types.Emitting):
1656
+ """Performs bidirectional processing of a sequence.
1657
+
1658
+ Input sequences are processed by a "forward" and "backward" layer. The forward
1659
+ layer processes the sequence unmodified, while the input sequence is reversed
1660
+ and processed with the backward layer. Finally, it is reversed again and then
1661
+ combined with the forward layer's output according to a combination mode.
1662
+
1663
+ Sequence reversal is performed by reversing the physical time dimension of the
1664
+ sequence without making any assumptions about the layout or valid timesteps in
1665
+ the sequence.
1666
+
1667
+ For example a sequence with 3 padding timesteps:
1668
+
1669
+ A B C D E X X X
1670
+
1671
+ Is processed by the forward layer to produce:
1672
+
1673
+ FA FB FC FD FE FX FX FX
1674
+
1675
+ The backward layer processes the sequence:
1676
+
1677
+ X X X E D C B A
1678
+
1679
+ To produce:
1680
+
1681
+ BX BX BX BE BD BC BB BA
1682
+
1683
+ Which is then reversed and combined with the forward layer outputs according
1684
+ to the combination mode. For example, with combination = STACK, the result is
1685
+ a [2, output_shape...] sequence:
1686
+
1687
+ [FA BA] [FB BB] [FC BC] [FD BD] [FE BE] [XX] [XX] [XX]
1688
+
1689
+ The resulting mask from processesing the forward and backward is combined via
1690
+ boolean AND.
1691
+
1692
+ WARNING: Causal convolution layers do not work well in backward mode due to
1693
+ how causal padding is applied and masked. The physical reversal of the
1694
+ sequence combined with causal padding leads to improper masking like:
1695
+
1696
+ For kernel_size = 3:
1697
+
1698
+ P P X X X E D C B A
1699
+
1700
+ Where P is the causal padding applied to the sequence. The correct behavior
1701
+ would be to pad like:
1702
+
1703
+ X X X P P E D C B A
1704
+
1705
+ The impact of this is that timestep E and D (for this kernel_size 3 example)
1706
+ become invalid, incorrectly shrinking the sequence length.
1707
+ """
1708
+
1709
+ @dataclasses.dataclass(frozen=True)
1710
+ class Config(types.SequenceLayerConfig):
1711
+ """Configuration for Bidirectional."""
1712
+
1713
+ # The forward layer definition.
1714
+ forward: types.SequenceLayerConfig
1715
+ # The backward layer definition.
1716
+ backward: types.SequenceLayerConfig
1717
+ # The combination mode to use for combining the forward and backward layer
1718
+ # outputs.
1719
+ combination: utils.CombinationMode = utils.CombinationMode.STACK
1720
+ # An optional name for the layer.
1721
+ name: str | None = None
1722
+
1723
+ def make(self) -> 'Bidirectional':
1724
+ return Bidirectional(self, name=self.name)
1725
+
1726
+ config: Config
1727
+
1728
+ def setup(self) -> None:
1729
+ self.forward = self.config.forward.make()
1730
+ self.backward = self.config.backward.make()
1731
+
1732
+ if self.forward.output_ratio != self.backward.output_ratio:
1733
+ raise ValueError(
1734
+ f'{self}: output ratios for the forward '
1735
+ 'and backward direction must be equal. '
1736
+ f'forward={self.forward.output_ratio} '
1737
+ f'backward={self.backward.output_ratio}.'
1738
+ )
1739
+
1740
+ @property
1741
+ def supports_step(self) -> bool:
1742
+ return False
1743
+
1744
+ @property
1745
+ def block_size(self) -> int:
1746
+ # Bidirectional is not steppable, so block size does not matter.
1747
+ return 1
1748
+
1749
+ @property
1750
+ def output_ratio(self) -> fractions.Fraction:
1751
+ # setup() checks forward and backward output ratio is equal.
1752
+ return self.forward.output_ratio
1753
+
1754
+ @functools.cached_property
1755
+ def receptive_field_per_step(self) -> dict[int, types.ReceptiveField]:
1756
+ rf_per_step_fwd = self.forward.receptive_field_per_step
1757
+ rf_per_step_bwd = self.backward.receptive_field_per_step
1758
+ types.validate_receptive_field_per_step(rf_per_step_fwd)
1759
+ types.validate_receptive_field_per_step(rf_per_step_bwd)
1760
+ num_steps_fwd = len(rf_per_step_fwd)
1761
+ num_steps_bwd = len(rf_per_step_bwd)
1762
+ num_steps = math.lcm(num_steps_fwd, num_steps_bwd)
1763
+ rf_per_step = {}
1764
+ for step in range(num_steps):
1765
+ fwd_step = step % num_steps_fwd
1766
+ bwd_step = (num_steps - step) % num_steps_bwd
1767
+ rf_f = rf_per_step_fwd.get(fwd_step)
1768
+ rf_b = rf_per_step_bwd.get(bwd_step)
1769
+ rf_b = tuple(-r for r in reversed(rf_b)) if rf_b is not None else None
1770
+ if rf_f is None and rf_b is None:
1771
+ rf_per_step[step] = None
1772
+ elif rf_f is None:
1773
+ rf_per_step[step] = rf_b
1774
+ elif rf_b is None:
1775
+ rf_per_step[step] = rf_f
1776
+ else:
1777
+ rf_per_step[step] = (min(rf_f[0], rf_b[0]), max(rf_f[1], rf_b[1]))
1778
+ return rf_per_step
1779
+
1780
+ @nn.nowrap
1781
+ def get_output_shape(
1782
+ self,
1783
+ input_shape: types.ShapeLike,
1784
+ *,
1785
+ constants: types.Constants | None = None,
1786
+ ) -> types.Shape:
1787
+ forward_output_shape = self.forward.get_output_shape(
1788
+ input_shape, constants=constants
1789
+ )
1790
+ backward_output_shape = self.backward.get_output_shape(
1791
+ input_shape,
1792
+ constants=constants,
1793
+ )
1794
+ return utils.sequence_broadcast_combine_output_channel_shape(
1795
+ self.config.combination, forward_output_shape, backward_output_shape
1796
+ )
1797
+
1798
+ @nn.nowrap
1799
+ def get_output_dtype(self, input_dtype: types.DType) -> types.DType:
1800
+ forward_dtype = self.forward.get_output_dtype(input_dtype)
1801
+ backward_dtype = self.backward.get_output_dtype(input_dtype)
1802
+ # TODO(rryan): We should probably disallow automatic type promotion between
1803
+ # integer and float types, since this is usually a sign of a bug.
1804
+ return jnp.result_type(forward_dtype, backward_dtype)
1805
+
1806
+ def get_initial_state(
1807
+ self,
1808
+ batch_size: int,
1809
+ input_spec: types.ChannelSpec,
1810
+ *,
1811
+ training: bool,
1812
+ constants: types.Constants | None = None,
1813
+ ) -> types.State:
1814
+ forward_state = self.forward.get_initial_state(
1815
+ batch_size, input_spec, training=training, constants=constants
1816
+ )
1817
+ backward_state = self.backward.get_initial_state(
1818
+ batch_size, input_spec, training=training, constants=constants
1819
+ )
1820
+ return (forward_state, backward_state)
1821
+
1822
+ def step_with_emits(
1823
+ self,
1824
+ x: types.Sequence,
1825
+ state: types.State,
1826
+ *,
1827
+ training: bool,
1828
+ constants: types.Constants | None = None,
1829
+ ) -> tuple[types.Sequence, types.State, types.Emits]:
1830
+ raise ValueError('Bidirectional does not support step-wise processing.')
1831
+
1832
+ def layer(
1833
+ self,
1834
+ x: types.Sequence,
1835
+ *,
1836
+ training: bool,
1837
+ constants: types.Constants | None = None,
1838
+ ) -> types.Sequence:
1839
+ y_forward = self.forward.layer(x, training=training, constants=constants)
1840
+
1841
+ x_reverse = x.reverse_time()
1842
+ y_backward = self.backward.layer(
1843
+ x_reverse,
1844
+ training=training,
1845
+ constants=constants,
1846
+ )
1847
+ y_backward = y_backward.reverse_time()
1848
+
1849
+ return utils.sequence_broadcast_combine(
1850
+ self.config.combination, y_forward, y_backward
1851
+ )
1852
+
1853
+ def layer_with_emits(
1854
+ self,
1855
+ x: types.Sequence,
1856
+ *,
1857
+ training: bool,
1858
+ constants: types.Constants | None = None,
1859
+ ) -> tuple[types.Sequence, types.Emits]:
1860
+ y_forward, forward_emits = self.forward.layer_with_emits(
1861
+ x, training=training, constants=constants
1862
+ )
1863
+
1864
+ x_reverse = x.reverse_time()
1865
+ y_backward, backward_emits = self.backward.layer_with_emits(
1866
+ x_reverse,
1867
+ training=training,
1868
+ constants=constants,
1869
+ )
1870
+ y_backward = y_backward.reverse_time()
1871
+ y = utils.sequence_broadcast_combine(
1872
+ self.config.combination, y_forward, y_backward
1873
+ )
1874
+ emits = (forward_emits, backward_emits)
1875
+ return y, emits
1876
+
1877
+
1878
+ class Blockwise(WrapperMixin, types.SequenceLayer):
1879
+ """Processes the provided layer in blocks of a given size."""
1880
+
1881
+ @dataclasses.dataclass(frozen=True)
1882
+ class Config(types.SequenceLayerConfig):
1883
+ """Config for Blockwise."""
1884
+
1885
+ child_layer: types.SequenceLayerConfig
1886
+ block_size: int
1887
+ name: str | None = None
1888
+
1889
+ def make(self) -> 'Blockwise':
1890
+ return Blockwise(self, name=self.name)
1891
+
1892
+ config: Config
1893
+
1894
+ def setup(self) -> None:
1895
+ self.child_layer = self.config.child_layer.make()
1896
+ nn.share_scope(self, self.child_layer)
1897
+
1898
+ if self.config.block_size % self.child_layer.block_size != 0:
1899
+ raise ValueError(
1900
+ 'Block size must be a multiple of the child layer block size.'
1901
+ f' {self.config.block_size=} % {self.child_layer.block_size=} =='
1902
+ f' {self.config.block_size % self.child_layer.block_size}'
1903
+ )
1904
+
1905
+ @property
1906
+ def block_size(self) -> int:
1907
+ return self.config.block_size