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,2149 @@
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
+ """Utilities."""
15
+
16
+ import enum
17
+ import fractions
18
+ import functools
19
+ import math
20
+ import operator
21
+ import pprint
22
+ import re
23
+ import typing
24
+ from typing import Any, Callable, Protocol, Self, Sequence as TypingSequence, TypeVar
25
+
26
+ import flax.linen as nn
27
+ import jax
28
+ import jax.numpy as jnp
29
+ import numpy as np
30
+ from sequence_layers.jax import meta
31
+ from sequence_layers.jax import types
32
+ from sequence_layers.jax import typing as jt
33
+
34
+
35
+ @jt.typed
36
+ def combine_mask(
37
+ *masks: TypingSequence[jt.Bool[jt.ArrayT, '#B #T']]
38
+ ) -> jt.Bool[jt.ArrayT, '#B #T']:
39
+ """Combines masks with logical AND or a shortcut when reference equal."""
40
+ if all(x is masks[0] for x in masks[1:]):
41
+ return masks[0]
42
+ return functools.reduce(jnp.logical_and, masks)
43
+
44
+
45
+ def convolution_effective_kernel_size(
46
+ kernel_size: int, dilation_rate: int
47
+ ) -> int:
48
+ """Returns kernel_size with dilation_rate holes inserted."""
49
+ return (kernel_size - 1) * dilation_rate + 1
50
+
51
+
52
+ def convolution_padding_output_size(
53
+ input_size: int,
54
+ padding: types.PaddingModeString | tuple[int, int],
55
+ kernel_size: int,
56
+ stride: int,
57
+ dilation_rate: int,
58
+ ) -> int:
59
+ """Returns the output size for a convolution over input_size."""
60
+ # Formula from: https://www.tensorflow.org/api_docs/python/tf/nn/convolution
61
+ # SAME: ceil(input_shape / stride)
62
+ # VALID: ceil((input_shape - (kernel_size - 1) * dilation_rate) / stride)
63
+ pad_amount = sum(
64
+ convolution_explicit_padding(padding, kernel_size, stride, dilation_rate)
65
+ )
66
+ effective_kernel_size = convolution_effective_kernel_size(
67
+ kernel_size, dilation_rate
68
+ )
69
+ output_size = max(0, input_size + pad_amount - (effective_kernel_size - 1))
70
+ # Ceiling division.
71
+ return (output_size + stride - 1) // stride
72
+
73
+
74
+ def convolution_explicit_padding(
75
+ padding: types.PaddingModeString | tuple[int, int],
76
+ kernel_size: int,
77
+ stride: int,
78
+ dilation_rate: int,
79
+ ) -> tuple[int, int]:
80
+ """Returns explicit padding amounts to achieve the desired pad mode."""
81
+ if not isinstance(padding, str):
82
+ return padding
83
+
84
+ effective_kernel_size = convolution_effective_kernel_size(
85
+ kernel_size, dilation_rate
86
+ )
87
+
88
+ match padding:
89
+ case types.PaddingMode.CAUSAL_VALID.value | types.PaddingMode.CAUSAL.value:
90
+ return (effective_kernel_size - 1, 0)
91
+ case types.PaddingMode.SEMICAUSAL.value:
92
+ pad_amount = effective_kernel_size - 1
93
+ pad_left = max(effective_kernel_size - stride, 0)
94
+ pad_right = pad_amount - pad_left
95
+ return pad_left, pad_right
96
+ case (
97
+ types.PaddingMode.REVERSE_CAUSAL_VALID.value
98
+ | types.PaddingMode.REVERSE_CAUSAL.value
99
+ ):
100
+ return (0, effective_kernel_size - 1)
101
+ case types.PaddingMode.SAME.value:
102
+ pad_amount = effective_kernel_size - 1
103
+ pad_left = pad_amount // 2
104
+ pad_right = pad_amount - pad_left
105
+ return pad_left, pad_right
106
+ case types.PaddingMode.VALID.value:
107
+ return 0, 0
108
+ case types.PaddingMode.SEMICAUSAL_FULL.value:
109
+ pad_left = max(effective_kernel_size - stride, 0)
110
+ pad_right = effective_kernel_size - 1
111
+ return pad_left, pad_right
112
+ case _:
113
+ raise ValueError(f'Unsupported padding: {padding}')
114
+
115
+
116
+ def assert_is_compatible_with(a: types.ShapeLike, b: types.ShapeLike):
117
+ """TODO(rryan): Replace with JAX asserts module."""
118
+ a, b = tuple(a), tuple(b)
119
+ if len(a) != len(b):
120
+ raise ValueError(f'Shapes differ in rank: {a=} vs. {b=}')
121
+ for i, (d1, d2) in enumerate(zip(a, b)):
122
+ if d2 is None or d2 == 1:
123
+ continue
124
+ if d1 != d2:
125
+ raise ValueError(f'Incompatible dimension {i} {a=} {b=}.')
126
+
127
+
128
+ def assert_has_rank(shape: types.ShapeLike, rank: int) -> None:
129
+ """TODO(rryan): Replace with JAX asserts module."""
130
+ if len(shape) != rank:
131
+ raise ValueError(f'Rank of {shape=} is not {rank}.')
132
+
133
+
134
+ def _pad_to_multiple(
135
+ x: types.Sequence, block_size: int
136
+ ) -> tuple[types.Sequence, int, int]:
137
+ """Pads x to multiple of block_size."""
138
+ time = x.shape[1]
139
+ num_blocks = (time + block_size - 1) // block_size
140
+ padded_time = num_blocks * block_size
141
+ pad_amount = padded_time - time
142
+ x = x.pad_time(0, pad_amount, valid=False)
143
+ return x, padded_time, num_blocks
144
+
145
+
146
+ def _extract_blocks(x: types.Sequence, block_size: int) -> types.Sequence:
147
+ """Pads x and extract blocks of size block_size."""
148
+ x, _, num_blocks = _pad_to_multiple(x, block_size)
149
+ b, _, *rest = x.shape
150
+
151
+ return type(x)(
152
+ jnp.reshape(x.values, [b, num_blocks, block_size] + rest),
153
+ jnp.reshape(x.mask, [b, num_blocks, block_size]),
154
+ )
155
+
156
+
157
+ def _flatten_blocks(x: jax.Array) -> jax.Array:
158
+ """Combines the num_blocks and block_size dimension into one."""
159
+ b, num_blocks, block_size, *rest = x.shape
160
+ return jnp.reshape(x, [b, num_blocks * block_size] + rest)
161
+
162
+
163
+ def insert_with_unique_key(
164
+ emits: dict[str, types.Emits], key: str, value
165
+ ) -> str:
166
+ """Inserts value into emits with a unique name prefixed by key."""
167
+ if key not in emits:
168
+ emits[key] = value
169
+ return key
170
+ i = 1
171
+ while True:
172
+ unique_key = f'{key}_{i}'
173
+ if unique_key not in emits:
174
+ emits[unique_key] = value
175
+ return unique_key
176
+ i += 1
177
+
178
+
179
+ def setup_shared_scope(
180
+ parent: nn.Module,
181
+ layers: TypingSequence[nn.Module],
182
+ share_scope: bool | TypingSequence[bool],
183
+ ) -> None:
184
+ """Shares scopes between parent and layers based on share_scope."""
185
+ if isinstance(share_scope, bool):
186
+ share_scope = [share_scope] * len(layers)
187
+
188
+ if len(share_scope) != len(layers):
189
+ raise ValueError(
190
+ 'share_scope must be a bool or a sequence of the same length as'
191
+ f' layers: {len(share_scope)} != {len(layers)}'
192
+ )
193
+ for layer, share_scope in zip(layers, share_scope, strict=True):
194
+ if share_scope:
195
+ nn.share_scope(parent, layer)
196
+
197
+
198
+ def step_by_step_static(
199
+ l: types.Steppable,
200
+ x: types.Sequence,
201
+ training: bool,
202
+ initial_state: types.State = None,
203
+ blocks_per_step: int = 1,
204
+ constants: types.Constants | None = None,
205
+ with_emits: bool = True,
206
+ stream_constants: bool = False,
207
+ ) -> tuple[types.Sequence, types.State, types.Emits]:
208
+ """Executes a SequenceLayer timestep-by-timestep statically.
209
+
210
+ If the sequence length is not a multiple of l.block_size * blocks_per_step,
211
+ the sequence is padded to that length with invalid timesteps.
212
+
213
+ Args:
214
+ l: The SequenceLayer to invoke step-by-step.
215
+ x: The input Sequence to process step-by-step.
216
+ training: Whether we are in training mode.
217
+ initial_state: The initial state to use. If None, the initial state returned
218
+ by l.get_initial_state is used.
219
+ blocks_per_step: Runs the layer with this multiple of l.block_size timesteps
220
+ per step.
221
+ constants: The constants dictionary to provide to the step function.
222
+ with_emits: If True, collects emits from the layer for each step and returns
223
+ them. If False, returns an empty tuple for emits. If emits are not used it
224
+ is more efficient to disable this.
225
+ stream_constants: If True, stream Sequences present in constants at the same
226
+ block size as x.
227
+
228
+ Returns:
229
+ The resulting sequence, final state, and emits stacked over time (if
230
+ with_emits is True).
231
+ """
232
+ if not l.supports_step:
233
+ raise ValueError(f'{l} cannot be stepped.')
234
+ if initial_state is None:
235
+ initial_state = l.get_initial_state(
236
+ batch_size=x.shape[0],
237
+ input_spec=x.channel_spec,
238
+ training=training,
239
+ constants=constants,
240
+ )
241
+ input_block_size = l.block_size * blocks_per_step
242
+ x, _, num_blocks = _pad_to_multiple(x, input_block_size)
243
+
244
+ if constants is None:
245
+ constants = {}
246
+
247
+ if stream_constants:
248
+
249
+ def pad_constant(x):
250
+ if isinstance(x, types.Sequence):
251
+ return _pad_to_multiple(x, input_block_size)[0]
252
+ else:
253
+ return x
254
+
255
+ constants = jax.tree_util.tree_map(
256
+ pad_constant, constants, is_leaf=lambda x: isinstance(x, types.Sequence)
257
+ )
258
+
259
+ # If static unrolling, run a for loop over num_blocks, strided slice
260
+ # the block from x, and run transition_fn to get the output block
261
+ # and next state.
262
+ output_blocks = []
263
+ output_emits = []
264
+
265
+ def read_block(x: types.Sequence, b: int) -> types.Sequence:
266
+ start = b * input_block_size
267
+ end = start + input_block_size
268
+ x_b = x[:, start:end]
269
+ pad_amount = input_block_size - x_b.shape[1]
270
+ if pad_amount:
271
+ x_b = x_b.pad_time(0, pad_amount, valid=False)
272
+ return x_b
273
+
274
+ state = initial_state
275
+ for b in range(num_blocks):
276
+ x_block = read_block(x, b)
277
+
278
+ if stream_constants:
279
+ step_constants = jax.tree_util.tree_map(
280
+ lambda x: read_block(x, b) if isinstance(x, types.Sequence) else x, # pylint: disable=cell-var-from-loop
281
+ constants,
282
+ is_leaf=lambda x: isinstance(x, types.Sequence),
283
+ )
284
+ else:
285
+ step_constants = constants
286
+
287
+ if with_emits:
288
+ y_block, state, y_emit = l.step_with_emits(
289
+ x_block, state, training=training, constants=step_constants
290
+ )
291
+ else:
292
+ y_block, state = l.step(
293
+ x_block, state, training=training, constants=step_constants
294
+ )
295
+ y_emit = ()
296
+
297
+ output_blocks.append(y_block)
298
+ output_emits.append(y_emit)
299
+
300
+ # Concatenate all timesteps.
301
+ output = types.Sequence.concatenate_sequences(output_blocks)
302
+
303
+ def concatenate(*ts):
304
+ if isinstance(ts[0], types.Sequence):
305
+ return types.Sequence.concatenate_sequences(ts)
306
+ else:
307
+ return jnp.concatenate(ts, axis=1)
308
+
309
+ output_emits = jax.tree_util.tree_map(concatenate, *output_emits)
310
+ return output, state, output_emits
311
+
312
+
313
+ def step_by_step_dynamic(
314
+ l: types.Steppable,
315
+ x: types.Sequence,
316
+ training: bool,
317
+ initial_state: types.State = None,
318
+ blocks_per_step: int = 1,
319
+ constants: types.Constants | None = None,
320
+ with_emits: bool = True,
321
+ unroll: int = 1,
322
+ stream_constants: bool = False,
323
+ ) -> tuple[types.Sequence, types.State, types.Emits]:
324
+ """Executes a SequenceLayer timestep-by-timestep dynamically.
325
+
326
+ If the sequence length is not a multiple of l.block_size * blocks_per_step,
327
+ the sequence is padded to that length with invalid timesteps.
328
+
329
+ Args:
330
+ l: The SequenceLayer to invoke step-by-step.
331
+ x: The input Sequence to process step-by-step.
332
+ training: Whether we are in training mode.
333
+ initial_state: The initial state to use. If None, the initial state returned
334
+ by l.get_initial_state is used.
335
+ blocks_per_step: Runs the layer with this multiple of l.block_size timesteps
336
+ per step.
337
+ constants: The constants dictionary to provide to the step function.
338
+ with_emits: If True, collects emits from the layer for each step and returns
339
+ them. If False, returns an empty tuple for emits. If emits are not used it
340
+ is more efficient to disable this.
341
+ unroll: How many scan iterations to unroll in one iteration of the dynamic
342
+ loop. Unrolling enables more XLA fusion, but increases memory usage and
343
+ compile times.
344
+ stream_constants: If True, stream Sequences present in constants at the same
345
+ block size as x.
346
+
347
+ Returns:
348
+ The resulting sequence, final state, and emits stacked over time (if
349
+ with_emits is True).
350
+ """
351
+ if initial_state is None:
352
+ initial_state = l.get_initial_state(
353
+ batch_size=x.shape[0],
354
+ input_spec=x.channel_spec,
355
+ training=training,
356
+ constants=constants,
357
+ )
358
+
359
+ input_block_size = l.block_size * blocks_per_step
360
+ x_blocked = _extract_blocks(x, input_block_size)
361
+
362
+ if constants is None:
363
+ constants = {}
364
+
365
+ if stream_constants:
366
+ blocked_constants = {}
367
+ static_constants = {}
368
+ for k, v in constants.items():
369
+ if isinstance(v, types.Sequence):
370
+ blocked_constants[k] = _extract_blocks(v, input_block_size)
371
+ else:
372
+ static_constants[k] = v
373
+ else:
374
+ blocked_constants = {}
375
+ static_constants = constants
376
+
377
+ def step_fn(
378
+ layer: types.Steppable,
379
+ state: types.State,
380
+ inputs: types.Sequence,
381
+ step_constants: types.Constants,
382
+ ) -> tuple[types.State, tuple[types.Sequence, types.Emits]]:
383
+ # Check supports_step within the nn.scan body so that layers are bound.
384
+ if with_emits:
385
+ output, state, emits = layer.step_with_emits(
386
+ inputs,
387
+ state,
388
+ training=training,
389
+ constants=static_constants | step_constants,
390
+ )
391
+ else:
392
+ output, state = layer.step(
393
+ inputs,
394
+ state,
395
+ training=training,
396
+ constants=static_constants | step_constants,
397
+ )
398
+ emits = ()
399
+
400
+ return state, (output, emits)
401
+
402
+ scan_fn = nn.scan(
403
+ step_fn,
404
+ variable_broadcast=True,
405
+ # Split all RNGs in our scope except for params (which when split during
406
+ # initialization leads to different parameters on each iteration of the
407
+ # loop and causes compilation errors).
408
+ split_rngs={'params': False, nn.DenyList(('params',)): True},
409
+ in_axes=1,
410
+ out_axes=1,
411
+ length=x_blocked.shape[1],
412
+ unroll=unroll,
413
+ )
414
+
415
+ state, (output, emits) = scan_fn(
416
+ l, initial_state, x_blocked, blocked_constants
417
+ )
418
+ output, emits = jax.tree_util.tree_map(_flatten_blocks, (output, emits))
419
+ return output, state, emits
420
+
421
+
422
+ def _reshape_for_broadcast(
423
+ *seqs: types.Sequence,
424
+ ) -> tuple[types.Sequence, ...]:
425
+ """Reshapes channel dims of many sequences to be broadcastable to each other."""
426
+
427
+ max_dims = max(x.ndim for x in seqs)
428
+
429
+ def _maybe_reshape(values: jax.Array) -> jax.Array:
430
+ extra_dims = max_dims - values.ndim
431
+ if extra_dims == 0:
432
+ return values
433
+
434
+ batch_size, time = values.shape[:2]
435
+ shape = (batch_size, time) + (1,) * extra_dims + values.shape[2:]
436
+ return jnp.reshape(values, shape)
437
+
438
+ reshaped = tuple(x.apply_values(_maybe_reshape) for x in seqs)
439
+ for y in reshaped[1:]:
440
+ assert len(reshaped[0].channel_shape) == len(y.channel_shape)
441
+ return reshaped
442
+
443
+
444
+ def sequence_broadcast_add(*seqs: types.Sequence) -> types.Sequence:
445
+ """Broadcast-add sequences.
446
+
447
+ This follows NumPy "right-to-left" broadcasting semantics in the case of
448
+ mismatched channels (i.e., assume sequences with fewer dimensions are dim=1
449
+ in the extra dimensions). Separately, batch and time dimensions broadcast as
450
+ usual (equal or 1 over all sequences).
451
+
452
+ b t channels
453
+ X: 2 x 3 x 4 x 1 x 5
454
+ Y: 1 x 3 x 2 x 1
455
+ Result: 2 x 3 x 4 x 2 x 5
456
+
457
+ Args:
458
+ *seqs: The sequences to broadcast.
459
+
460
+ Returns:
461
+ A new Sequence with the sum of the broadcasted values and the logical-and of
462
+ the broadcasted combine masks.
463
+ """
464
+ seqs = _reshape_for_broadcast(*seqs)
465
+ return types.Sequence(
466
+ sum(x.values for x in seqs), combine_mask(*(x.mask for x in seqs))
467
+ )
468
+
469
+
470
+ def sequence_broadcast_mean(*seqs: types.Sequence) -> types.Sequence:
471
+ """Broadcast-average sequences.
472
+
473
+ This follows NumPy "right-to-left" broadcasting semantics in the case of
474
+ mismatched channels (i.e., assume sequences with fewer dimensions are dim=1
475
+ in the extra dimensions). Separately, batch and time dimensions broadcast as
476
+ usual (equal or 1 over all sequences).
477
+
478
+ b t channels
479
+ X: 2 x 3 x 4 x 1 x 5
480
+ Y: 1 x 3 x 2 x 1
481
+ Result: 2 x 3 x 4 x 2 x 5
482
+
483
+ Args:
484
+ *seqs: The sequences to broadcast.
485
+
486
+ Returns:
487
+ A new Sequence with the average of the broadcasted values and the
488
+ logical-and of the broadcasted combine masks.
489
+ """
490
+ return sequence_broadcast_add(*seqs).apply_values_masked(
491
+ lambda x: x / len(seqs)
492
+ )
493
+
494
+
495
+ def sequence_broadcast_product(*seqs: types.Sequence) -> types.Sequence:
496
+ """Broadcast-multiply sequences.
497
+
498
+ This follows NumPy "right-to-left" broadcasting semantics in the case of
499
+ mismatched channels (i.e., assume sequences with fewer dimensions are dim=1
500
+ in the extra dimensions). Separately, batch and time dimensions broadcast as
501
+ usual (equal or 1 over all sequences).
502
+
503
+ b t channels
504
+ X: 2 x 3 x 4 x 1 x 5
505
+ Y: 1 x 3 x 2 x 1
506
+ Result: 2 x 3 x 4 x 2 x 5
507
+
508
+ Args:
509
+ *seqs: The sequences to broadcast.
510
+
511
+ Returns:
512
+ A new Sequence with the product of the broadcasted values and the
513
+ logical-and of the broadcasted combine masks.
514
+ """
515
+ seqs = _reshape_for_broadcast(*seqs)
516
+ return types.Sequence(
517
+ functools.reduce(operator.mul, (x.values for x in seqs)),
518
+ combine_mask(*(x.mask for x in seqs)),
519
+ )
520
+
521
+
522
+ def sequence_broadcast_stack(*seqs: types.Sequence) -> types.Sequence:
523
+ """Broadcast-stack sequences into a new first channel.
524
+
525
+ This follows NumPy "right-to-left" broadcasting semantics in the case of
526
+ mismatched channels (i.e., assume sequences with fewer dimensions are dim=1
527
+ in the extra dimensions). Separately, batch and time dimensions broadcast as
528
+ usual (equal or 1 over all sequences).
529
+
530
+ b t channels
531
+ X: 2 x 3 x 4 x 1 x 5
532
+ Y: 1 x 3 x 2 x 1
533
+ Z: 2 x 1 x 1 x 1
534
+ Result: 2 x 3 x 3 x 4 x 2 x 5
535
+
536
+ Args:
537
+ *seqs: The sequences to broadcast.
538
+
539
+ Returns:
540
+ A new Sequence stacked on the new first channel of the broadcasted values.
541
+ """
542
+ seqs = _reshape_for_broadcast(*seqs)
543
+ broadcasted_channel_shape = jnp.broadcast_shapes(
544
+ *(x.channel_shape for x in seqs)
545
+ )
546
+
547
+ # Also broadcast batch and time. Callers can impose further constraints.
548
+ batch_size = max(x.shape[0] for x in seqs)
549
+ time = max(x.shape[1] for x in seqs)
550
+
551
+ def _broadcast_channel_shape(values):
552
+ shape = (batch_size, time) + broadcasted_channel_shape
553
+ return jnp.broadcast_to(values, shape)
554
+
555
+ return types.Sequence(
556
+ jnp.stack([_broadcast_channel_shape(x.values) for x in seqs], axis=2),
557
+ combine_mask(*(x.mask for x in seqs)),
558
+ )
559
+
560
+
561
+ def sequence_broadcast_concat(*seqs: types.Sequence) -> types.Sequence:
562
+ """Broadcast-concatenate sequences on their final axis.
563
+
564
+ This follows NumPy "right-to-left" broadcasting semantics in the case of
565
+ mismatched channels (i.e., assume sequences with fewer dimensions are dim=1
566
+ in the extra dimensions). Separately, batch and time dimensions broadcast as
567
+ usual (equal or 1 over all sequences).
568
+
569
+ b t channels
570
+ X: 2 x 3 x 4 x 1 x 5
571
+ Y: 1 x 3 x 2 x 1
572
+ Z: 2 x 1 x 1 x 1
573
+ Result: 2 x 3 x 4 x 2 x 7
574
+
575
+ Args:
576
+ *seqs: The sequences to broadcast.
577
+
578
+ Returns:
579
+ A new Sequence broadcasting on all but the last channel, then concatenating
580
+ on the last channel.
581
+ """
582
+ seqs = _reshape_for_broadcast(*seqs)
583
+ channel_outer_dims_broadcast_shape = jnp.broadcast_shapes(
584
+ *(x.channel_shape[:-1] for x in seqs)
585
+ )
586
+
587
+ # Also broadcast batch and time. Callers can impose further constraints.
588
+ batch_size = max(x.shape[0] for x in seqs)
589
+ time = max(x.shape[1] for x in seqs)
590
+
591
+ def _broadcast_channel_outer_dims(values):
592
+ # Expand dim 2D tensors for concatenation.
593
+ if values.ndim == 2 and not channel_outer_dims_broadcast_shape:
594
+ values = values[..., jnp.newaxis]
595
+ shape = (
596
+ (batch_size, time)
597
+ + channel_outer_dims_broadcast_shape
598
+ + values.shape[-1:]
599
+ )
600
+ return jnp.broadcast_to(values, shape)
601
+
602
+ values = [_broadcast_channel_outer_dims(x.values) for x in seqs]
603
+ return types.Sequence(
604
+ jnp.concatenate(values, -1), combine_mask(*(x.mask for x in seqs))
605
+ )
606
+
607
+
608
+ def sequence_broadcast_affine(
609
+ x: types.Sequence, scale: types.Sequence, shift: types.Sequence
610
+ ) -> types.Sequence:
611
+ """Affine transform of x."""
612
+ x, scale = _reshape_for_broadcast(x, scale)
613
+ x, shift = _reshape_for_broadcast(x, shift)
614
+ values = x.values * scale.values + shift.values
615
+ # Scale and shift are often derived from the same sequence so combine their
616
+ # mask first as an optimization.
617
+ mask = combine_mask(x.mask, combine_mask(scale.mask, shift.mask))
618
+ return types.Sequence(values, mask)
619
+
620
+
621
+ @enum.unique
622
+ class CombinationMode(enum.Enum):
623
+ """The type of combination to perform."""
624
+
625
+ # Broadcasts inputs together and stacks them on the first channel axis:
626
+ #
627
+ # Examples:
628
+ # x=() y=() -> (2)
629
+ # x=() y=(2) -> (2, 2)
630
+ # x=(3) y=(3) -> (2, 3)
631
+ # x=(5) y=(3, 5) -> (2, 3, 5)
632
+ STACK = 1
633
+
634
+ # Broadcasts inputs together and concatenates them on the final channel axis:
635
+ #
636
+ # Examples:
637
+ # x=() y=() -> (2)
638
+ # x=() y=(2) -> (3)
639
+ # x=(3) y=(3) -> (6)
640
+ # x=(5) y=(3, 5) -> (3, 10)
641
+ CONCAT = 2
642
+ # Broadcasts inputs together and adds them.
643
+ #
644
+ # Examples:
645
+ # x=() y=() -> ()
646
+ # x=() y=(2) -> (2)
647
+ # x=(3) y=(3) -> (3)
648
+ # x=(5) y=(3, 5) -> (3, 5)
649
+ ADD = 3
650
+ # Broadcasts inputs together and averages them.
651
+ #
652
+ # Examples:
653
+ # x=() y=() -> ()
654
+ # x=() y=(2) -> (2)
655
+ # x=(3) y=(3) -> (3)
656
+ # x=(5) y=(3, 5) -> (3, 5)
657
+ MEAN = 4
658
+ # Examples:
659
+ # x=() y=() -> ()
660
+ # x=() y=(2) -> (2)
661
+ # x=(3) y=(3) -> (3)
662
+ # x=(5) y=(3, 5) -> (3, 5)
663
+ PRODUCT = 5
664
+
665
+
666
+ def sequence_broadcast_combine(
667
+ mode: CombinationMode, *seqs: types.Sequence
668
+ ) -> types.Sequence:
669
+ """Combines sequences according to the specified CombinationMode."""
670
+ match (mode):
671
+ case CombinationMode.STACK:
672
+ return sequence_broadcast_stack(*seqs)
673
+ case CombinationMode.CONCAT:
674
+ return sequence_broadcast_concat(*seqs)
675
+ case CombinationMode.ADD:
676
+ return sequence_broadcast_add(*seqs)
677
+ case CombinationMode.MEAN:
678
+ return sequence_broadcast_mean(*seqs)
679
+ case CombinationMode.PRODUCT:
680
+ return sequence_broadcast_product(*seqs)
681
+ case _:
682
+ raise NotImplementedError(f'Unknown combination: {mode}')
683
+
684
+
685
+ def sequence_broadcast_combine_output_channel_shape(
686
+ mode: CombinationMode, *channel_shapes: types.Shape
687
+ ) -> types.Shape:
688
+ """Computes the output channel shape for given mode / input channel shapes."""
689
+ max_dims = max(len(x) for x in channel_shapes)
690
+ channel_shapes = tuple((1,) * (max_dims - len(x)) + x for x in channel_shapes)
691
+
692
+ match (mode):
693
+ case CombinationMode.STACK:
694
+ channel_broadcasted_shape = jnp.broadcast_shapes(*channel_shapes)
695
+ return (len(channel_shapes),) + channel_broadcasted_shape
696
+ case CombinationMode.CONCAT:
697
+ channel_broadcasted_shape = jnp.broadcast_shapes(
698
+ *(x[:-1] for x in channel_shapes)
699
+ )
700
+ if not channel_broadcasted_shape:
701
+ channel_shapes = tuple(x if x else (1,) for x in channel_shapes)
702
+ final_dim = sum(x[-1] for x in channel_shapes)
703
+ return channel_broadcasted_shape + (final_dim,)
704
+ case CombinationMode.ADD:
705
+ return jnp.broadcast_shapes(*channel_shapes)
706
+ case CombinationMode.MEAN:
707
+ return jnp.broadcast_shapes(*channel_shapes)
708
+ case CombinationMode.PRODUCT:
709
+ return jnp.broadcast_shapes(*channel_shapes)
710
+ case _:
711
+ raise NotImplementedError(f'Unknown combination: {mode}')
712
+
713
+
714
+ class EinsumCommon(Protocol):
715
+ """Common base for Einsum layer users."""
716
+
717
+ def param(
718
+ self,
719
+ name: str,
720
+ init_fn: Callable[..., nn.initializers.Initializer],
721
+ *init_args,
722
+ ):
723
+ """Existence of the param() function (as in an nn.Module) is assumed."""
724
+
725
+ @nn.nowrap
726
+ def einsum(
727
+ self,
728
+ inputs: jax.Array,
729
+ equation: str,
730
+ kernel_shape: types.ShapeLike,
731
+ bias_shape: types.ShapeLike | None,
732
+ activation: Callable[[jax.Array], jax.Array] | None = None,
733
+ compute_dtype: types.DType | None = None,
734
+ param_dtype: types.DType = jnp.float32,
735
+ precision: nn.linear.PrecisionLike = None,
736
+ kernel_init: nn.initializers.Initializer = nn.linear.default_kernel_init,
737
+ kernel_sharding: types.Sharding | None = None,
738
+ bias_init: nn.initializers.Initializer = nn.initializers.zeros_init(),
739
+ bias_sharding: types.Sharding | None = None,
740
+ einsum_factory: types.EinsumFactoryT | None = None,
741
+ **kernel_init_kwargs,
742
+ ) -> jax.Array:
743
+ """Compute einsum with the given shapes. Call from an @nn.compact method."""
744
+ kernel_init = shard_initializer(
745
+ kernel_init, kernel_sharding, **kernel_init_kwargs
746
+ )
747
+ kernel = self.param('kernel', kernel_init, kernel_shape, param_dtype)
748
+ if bias_shape is not None:
749
+ bias_init = shard_initializer(bias_init, bias_sharding)
750
+ bias = self.param('bias', bias_init, bias_shape, param_dtype)
751
+ else:
752
+ bias = None
753
+
754
+ inputs, kernel, bias = nn.dtypes.promote_dtype(
755
+ inputs, kernel, bias, dtype=compute_dtype
756
+ )
757
+
758
+ if einsum_factory is None:
759
+ ret = jnp.einsum(equation, inputs, kernel, precision=precision)
760
+ else:
761
+ einsum_func = einsum_factory()
762
+ ret = einsum_func(equation, inputs, kernel)
763
+
764
+ if bias is not None:
765
+ ret = bias_add(ret, bias)
766
+ if activation is not None:
767
+ ret = activation(ret)
768
+ return ret
769
+
770
+
771
+ class FlaxEinsumDense(nn.Module, EinsumCommon):
772
+ """A dense layer that uses `jnp.einsum` as the backing computation.
773
+
774
+ Copied from Keras's EinsumDense layer.
775
+ """
776
+
777
+ # An equation describing the einsum to perform. This equation must be a valid
778
+ # einsum string of the form `ab,bc->ac`, `...ab,bc->...ac`, or
779
+ # `ab...,bc->ac...` where 'ab', 'bc', and 'ac' can be any valid einsum axis
780
+ # expression sequence.
781
+ equation: str
782
+ # The expected shape of the output tensor (excluding the batch dimension and
783
+ # any dimensions represented by ellipses). You can specify None for any
784
+ # dimension that is unknown or can be inferred from the input shape.
785
+ output_shape: tuple[int, ...]
786
+ # A string containing the output dimension(s) to apply a bias to. Each
787
+ # character in the `bias_axes` string should correspond to a character in the
788
+ # output portion of the equation string.
789
+ bias_axes: str | None = None
790
+ activation: Callable[[jax.Array], jax.Array] | None = None
791
+ compute_dtype: types.DType | None = None
792
+ param_dtype: types.DType = jnp.float32
793
+ precision: nn.linear.PrecisionLike = None
794
+ kernel_init: nn.initializers.Initializer = nn.linear.default_kernel_init
795
+ kernel_sharding: types.Sharding | None = None
796
+ bias_init: nn.initializers.Initializer = nn.initializers.zeros_init()
797
+ bias_sharding: types.Sharding | None = None
798
+ # Optional einsum factory to replace the default jnp.einsum callable.
799
+ einsum_factory: types.EinsumFactoryT | None = None
800
+
801
+ def get_output_dtype(self, input_dtype: types.DType) -> types.DType:
802
+ """Returns the layer's output dtype for the specified input dtype."""
803
+ if self.is_initializing():
804
+ param_dtype = jnp.float32
805
+ else:
806
+ param_dtype = jax.tree_util.tree_leaves(self.scope.variables())[0].dtype
807
+ return get_promoted_dtype(
808
+ input_dtype, param_dtype, dtype=self.compute_dtype
809
+ )
810
+
811
+ def project_sequence(self, inputs: types.Sequence) -> types.Sequence:
812
+ """Applies dense to Sequence. If no bias, mask status is preserved."""
813
+ # TODO(rryan): If activation(0) == 0, we can use apply_values_masked.
814
+ if not self.bias_axes and self.activation is None:
815
+ return inputs.apply_values_masked(self)
816
+ else:
817
+ return inputs.apply_values(self)
818
+
819
+ @nn.compact
820
+ def __call__(self, inputs: jax.Array) -> jax.Array:
821
+ input_shape = list(inputs.shape)
822
+ kernel_shape, bias_shape, _ = _analyze_einsum_string(
823
+ self.equation,
824
+ self.bias_axes,
825
+ input_shape,
826
+ list(self.output_shape),
827
+ )
828
+ return self.einsum(
829
+ inputs,
830
+ self.equation,
831
+ kernel_shape,
832
+ bias_shape,
833
+ activation=self.activation,
834
+ compute_dtype=self.compute_dtype,
835
+ param_dtype=self.param_dtype,
836
+ precision=self.precision,
837
+ kernel_init=self.kernel_init,
838
+ kernel_sharding=self.kernel_sharding,
839
+ bias_init=self.bias_init,
840
+ bias_sharding=self.bias_sharding,
841
+ einsum_factory=self.einsum_factory,
842
+ )
843
+
844
+
845
+ def _analyze_einsum_string(equation, bias_axes, input_shape, output_shape):
846
+ """Analyzes an einsum string to determine the required weight shape."""
847
+
848
+ dot_replaced_string = re.sub(r'\.\.\.', '0', equation)
849
+
850
+ # This is the case where no ellipses are present in the string.
851
+ split_string = re.match(
852
+ '([a-zA-Z]+),([a-zA-Z]+)->([a-zA-Z]+)', dot_replaced_string
853
+ )
854
+ if split_string:
855
+ return einsum_analyze_split_string(
856
+ split_string.groups(), bias_axes, input_shape, output_shape
857
+ )
858
+
859
+ # This is the case where ellipses are present on the left.
860
+ split_string = re.match(
861
+ '0([a-zA-Z]+),([a-zA-Z]+)->0([a-zA-Z]+)', dot_replaced_string
862
+ )
863
+ if split_string:
864
+ return einsum_analyze_split_string(
865
+ split_string.groups(),
866
+ bias_axes,
867
+ input_shape,
868
+ output_shape,
869
+ left_elided=True,
870
+ )
871
+
872
+ # This is the case where ellipses are present on the right.
873
+ split_string = re.match(
874
+ '([a-zA-Z]{2,})0,([a-zA-Z]+)->([a-zA-Z]+)0', dot_replaced_string
875
+ )
876
+ if split_string:
877
+ return einsum_analyze_split_string(
878
+ split_string.groups(), bias_axes, input_shape, output_shape
879
+ )
880
+
881
+ raise ValueError(
882
+ f"Invalid einsum equation '{equation}'. Equations must be in the form "
883
+ '[X],[Y]->[Z], ...[X],[Y]->...[Z], or [X]...,[Y]->[Z]....'
884
+ )
885
+
886
+
887
+ def einsum_analyze_split_string(
888
+ split_string: tuple[str, str, str],
889
+ bias_axes: str,
890
+ input_shape: types.ShapeLike,
891
+ output_shape: types.ShapeLike,
892
+ left_elided: bool = False,
893
+ ) -> tuple[types.ShapeLike, types.ShapeLike | None, types.ShapeLike]:
894
+ """Analyze a pre-split einsum string to find the weight shape."""
895
+ input_spec = split_string[0]
896
+ weight_spec = split_string[1]
897
+ output_spec = split_string[2]
898
+ elided = len(input_shape) - len(input_spec)
899
+
900
+ output_shape = list(output_shape)
901
+
902
+ output_shape.insert(0, input_shape[0])
903
+
904
+ if elided > 0 and left_elided:
905
+ for i in range(1, elided):
906
+ # We already inserted the 0th input dimension at dim 0, so we need
907
+ # to start at location 1 here.
908
+ output_shape.insert(1, input_shape[i])
909
+ elif elided > 0 and not left_elided:
910
+ for i in range(len(input_shape) - elided, len(input_shape)):
911
+ output_shape.append(input_shape[i])
912
+
913
+ if left_elided:
914
+ # If we have beginning dimensions elided, we need to use negative
915
+ # indexing to determine where in the input dimension our values are.
916
+ input_dim_map = {
917
+ dim: (i + elided) - len(input_shape) for i, dim in enumerate(input_spec)
918
+ }
919
+ # Because we've constructed the full output shape already, we don't need
920
+ # to do negative indexing.
921
+ output_dim_map = {dim: i + elided for i, dim in enumerate(output_spec)}
922
+ else:
923
+ input_dim_map = {dim: i for i, dim in enumerate(input_spec)}
924
+ output_dim_map = {dim: i for i, dim in enumerate(output_spec)}
925
+
926
+ for dim in input_spec:
927
+ input_shape_at_dim = input_shape[input_dim_map[dim]]
928
+ if dim in output_dim_map:
929
+ output_shape_at_dim = output_shape[output_dim_map[dim]]
930
+ if (
931
+ output_shape_at_dim is not None
932
+ and output_shape_at_dim != input_shape_at_dim
933
+ ):
934
+ raise ValueError(
935
+ 'Input shape and output shape do not match at shared '
936
+ f"dimension '{dim}'. Input shape is {input_shape_at_dim}, "
937
+ 'and output shape '
938
+ f'is {output_shape[output_dim_map[dim]]}.'
939
+ )
940
+
941
+ for dim in output_spec:
942
+ if dim not in input_spec and dim not in weight_spec:
943
+ raise ValueError(
944
+ f"Dimension '{dim}' was specified in the output "
945
+ f"'{output_spec}' but has no corresponding dim in the input "
946
+ f"spec '{input_spec}' or weight spec '{output_spec}'"
947
+ )
948
+
949
+ weight_shape = []
950
+ for dim in weight_spec:
951
+ if dim in input_dim_map:
952
+ weight_shape.append(input_shape[input_dim_map[dim]])
953
+ elif dim in output_dim_map:
954
+ weight_shape.append(output_shape[output_dim_map[dim]])
955
+ else:
956
+ raise ValueError(
957
+ f"Weight dimension '{dim}' did not have a match in either "
958
+ f"the input spec '{input_spec}' or the output "
959
+ f"spec '{output_spec}'. For this layer, the weight must "
960
+ 'be fully specified.'
961
+ )
962
+
963
+ if bias_axes:
964
+ num_left_elided = elided if left_elided else 0
965
+ idx_map = {
966
+ char: output_shape[i + num_left_elided]
967
+ for i, char in enumerate(output_spec)
968
+ }
969
+
970
+ for char in bias_axes:
971
+ if char not in output_spec:
972
+ raise ValueError(
973
+ f"Bias dimension '{char}' was requested, but is not part "
974
+ f"of the output spec '{output_spec}'"
975
+ )
976
+
977
+ first_bias_location = min([output_spec.find(char) for char in bias_axes])
978
+ bias_output_spec = output_spec[first_bias_location:]
979
+
980
+ bias_shape = [
981
+ idx_map[char] if char in bias_axes else 1 for char in bias_output_spec
982
+ ]
983
+
984
+ if not left_elided:
985
+ for _ in range(elided):
986
+ bias_shape.append(1)
987
+ else:
988
+ bias_shape = None
989
+
990
+ return weight_shape, bias_shape, output_shape
991
+
992
+
993
+ def shard_initializer(
994
+ initializer: nn.initializers.Initializer,
995
+ sharding: types.Sharding | None,
996
+ **kwargs,
997
+ ) -> nn.initializers.Initializer:
998
+ """Applies sharding to initializer (if provided)."""
999
+ if sharding is None and not kwargs:
1000
+ return initializer
1001
+ return meta.with_meta(initializer, sharding, **kwargs)
1002
+
1003
+
1004
+ def bias_add(y: jax.Array, bias: jax.Array) -> jax.Array:
1005
+ """Adds bias to y with appropriate broadcasting."""
1006
+ # Assert broadcastable.
1007
+ jnp.broadcast_shapes(y.shape, bias.shape)
1008
+ return y + jnp.reshape(bias, (1,) * (y.ndim - bias.ndim) + bias.shape)
1009
+
1010
+
1011
+ def sequence_split(
1012
+ seq: types.SequenceSelf,
1013
+ indices_or_sections: int | TypingSequence[int],
1014
+ axis: int = 0,
1015
+ ) -> list[types.SequenceSelf]:
1016
+ """Splits an sl.Sequence on the specified axes, preserving sequence type."""
1017
+
1018
+ if axis < 0 and axis >= -seq.ndim:
1019
+ axis += seq.ndim
1020
+ if axis < 0 or axis >= seq.ndim:
1021
+ raise ValueError(f'Invalid axis for sequence_split: {axis=} {seq.ndim=}')
1022
+
1023
+ x_values = jnp.split(seq.values, indices_or_sections, axis=axis)
1024
+ x_masks = (
1025
+ jnp.split(seq.mask, indices_or_sections, axis=axis)
1026
+ if axis < 2
1027
+ else [seq.mask] * len(x_values)
1028
+ )
1029
+
1030
+ return [type(seq)(v, m) for v, m in zip(x_values, x_masks)]
1031
+
1032
+
1033
+ def sequence_stack(
1034
+ seqs: TypingSequence[types.SequenceSelf], axis: int
1035
+ ) -> types.SequenceSelf:
1036
+ """Stacks sl.Sequences on the specified axis, preserving sequence type.
1037
+
1038
+ Args:
1039
+ seqs: The sl.Sequences to stack.
1040
+ axis: The axis to stack along. Can be negative.
1041
+
1042
+ Returns:
1043
+ A sequence with the same type as the input sequences, where the input
1044
+ sequences are stacked along the specified axis.
1045
+
1046
+ Raises:
1047
+ ValueError: If no sequences are given, the sequences have different shapes,
1048
+ or the axis is invalid, i.e., out of range or the first two (non-channel)
1049
+ axes.
1050
+ """
1051
+ if len({seq.shape for seq in seqs}) > 1:
1052
+ raise ValueError(
1053
+ 'All sequences must have the same dimensions; if not, use'
1054
+ ' sequence_broadcast_stack instead.'
1055
+ )
1056
+ if not seqs:
1057
+ raise ValueError('No sequences provided.')
1058
+ seq_type, ndim = type(seqs[0]), seqs[0].ndim
1059
+ if axis < 0 and axis >= -ndim:
1060
+ axis += ndim + 1
1061
+ if axis <= 1 or axis > ndim:
1062
+ raise ValueError(f'Invalid axis for sequence_stack: {axis=} {ndim=}')
1063
+ return seq_type(
1064
+ jnp.stack([seq.values for seq in seqs], axis=axis),
1065
+ combine_mask(*(x.mask for x in seqs)),
1066
+ )
1067
+
1068
+
1069
+ def unstack(x: jax.Array, axis: int = 0) -> list[jax.Array]:
1070
+ """Unstacks x on the specified axis. Inverse of np.stack(xs, axis=axis)."""
1071
+ return [
1072
+ jax.lax.index_in_dim(x, i, axis, keepdims=False)
1073
+ for i in range(x.shape[axis])
1074
+ ]
1075
+
1076
+
1077
+ def sequence_unstack(
1078
+ seq: types.SequenceSelf, axis: int
1079
+ ) -> list[types.SequenceSelf]:
1080
+ """Unstacks an sl.Sequence on the specified axis, preserving sequence type.
1081
+
1082
+ Args:
1083
+ seq: The sl.Sequence to unstack.
1084
+ axis: The axis to unstack along. Can be negative.
1085
+
1086
+ Returns:
1087
+ A list of sequences with the same type as the input sequence, where the
1088
+ input sequences are unstacked along the specified axis.
1089
+
1090
+ Raises:
1091
+ ValueError: If the axis is invalid, i.e., out of range or the first two
1092
+ (non-channel) axes.
1093
+ """
1094
+ if axis < 0 and axis >= -seq.ndim:
1095
+ axis += seq.ndim
1096
+ if axis <= 1 or axis >= seq.ndim:
1097
+ raise ValueError(f'Invalid axis for sequence_unstack: {axis=} {seq.ndim=}')
1098
+ return [type(seq)(v, seq.mask) for v in unstack(seq.values, axis)]
1099
+
1100
+
1101
+ def unstack_tree(tree: jt.AnyPyTree, axis: int = 0) -> list[jt.AnyPyTree]:
1102
+ """Unstacks provided tree on axis into multiple trees with same structure."""
1103
+ leaves, treedef = jax.tree_util.tree_flatten(tree)
1104
+ leaves = [unstack(leaf, axis=axis) for leaf in leaves]
1105
+ flat_trees = list(zip(*leaves))
1106
+ return [
1107
+ jax.tree_util.tree_unflatten(treedef, tree_i) for tree_i in flat_trees
1108
+ ]
1109
+
1110
+
1111
+ def normalize_ntuple(x: int | TypingSequence[int], n: int) -> tuple[int, ...]:
1112
+ if isinstance(x, int):
1113
+ return (x,) * n
1114
+ result = tuple(x)
1115
+ if len(result) != n:
1116
+ raise ValueError(f'Expected a {n}-element iterable, got: {x}')
1117
+ return result
1118
+
1119
+
1120
+ def normalize_2tuple(x: int | TypingSequence[int]) -> tuple[int, int]:
1121
+ return typing.cast(tuple[int, int], normalize_ntuple(x, 2))
1122
+
1123
+
1124
+ def normalize_3tuple(x: int | TypingSequence[int]) -> tuple[int, int, int]:
1125
+ return typing.cast(tuple[int, int, int], normalize_ntuple(x, 3))
1126
+
1127
+
1128
+ def get_promoted_dtype(
1129
+ *args: types.DType | None,
1130
+ dtype: types.DType | None = None,
1131
+ inexact: bool = True,
1132
+ ) -> types.DType:
1133
+ """Returns the dtype result of nn.dtypes.promote_dtype."""
1134
+ if dtype is None:
1135
+ dtype = jnp.result_type(*(x for x in args if x is not None))
1136
+ if inexact and not jnp.issubdtype(dtype, jnp.inexact):
1137
+ dtype = jnp.promote_types(jnp.float32, dtype)
1138
+ if inexact and not jnp.issubdtype(dtype, jnp.inexact):
1139
+ raise ValueError(f'Dtype must be inexact: {dtype}')
1140
+ return dtype
1141
+
1142
+
1143
+ def match_shape_along_axes(
1144
+ channel_shape: types.Shape,
1145
+ axes: int | TypingSequence[int] | None,
1146
+ ) -> types.Shape:
1147
+ """Return a shape matching channel_shape on axes and is equal to 1 elsewhere.
1148
+
1149
+ Use this to make a equal-length shape that will unambiguously broadcast with
1150
+ channel_shape.
1151
+
1152
+ Args:
1153
+ channel_shape: The shape to match.
1154
+ axes: The axes to match along to (int or sequence of ints). If None, all
1155
+ axes are matched. Negative indices are supported.
1156
+
1157
+ Returns:
1158
+ A shape with the same number of dimensions as channel_shape, where the
1159
+ specified axes are equal to channel_shape[axis] and all other axes are 1.
1160
+
1161
+ Raises:
1162
+ ValueError: If any of the given axes does not exist in channel_shape.
1163
+ """
1164
+ if axes is None:
1165
+ return tuple(channel_shape)
1166
+
1167
+ target_shape = [1] * len(channel_shape)
1168
+ if isinstance(axes, int):
1169
+ axes = [axes]
1170
+ for axis in axes:
1171
+ if not -len(channel_shape) <= axis < len(channel_shape):
1172
+ raise ValueError(f'Invalid {axis=} found in {axes=}.')
1173
+ target_shape[axis] = channel_shape[axis]
1174
+ return tuple(target_shape)
1175
+
1176
+
1177
+ @typing.runtime_checkable
1178
+ class Castable(Protocol):
1179
+ """Protocol for types that have a DType and can be cast to another DType."""
1180
+
1181
+ @property
1182
+ def dtype(self) -> types.DType:
1183
+ ...
1184
+
1185
+ def astype(self, dtype) -> Self:
1186
+ ...
1187
+
1188
+
1189
+ # TODO: b/339021149 - Use TypeVarTuple, ParamSpecArgs type hints once in pytype.
1190
+ _CastableOrNoneT = TypeVar('_CastableOrNoneT', bound=Castable | None)
1191
+ PreservesDTypeFn = Callable[..., Any]
1192
+ _PreservesDTypeFnT = TypeVar('_PreservesDTypeFnT', bound=PreservesDTypeFn)
1193
+ PreservesDTypeFnDecorator = Callable[..., _PreservesDTypeFnT]
1194
+
1195
+
1196
+ def _run_with_min_dtype(
1197
+ min_dtype: types.DType | None = None,
1198
+ restore_dtypes: bool = True,
1199
+ ) -> PreservesDTypeFnDecorator[PreservesDTypeFn]:
1200
+ """Factory for decorators to promote inputs to a DType within a function."""
1201
+
1202
+ # See run_in_at_least_fp32's docstring for the interface of this decorator
1203
+ # (where min_dtype=jnp.float32).
1204
+ def _decorator(fn: _PreservesDTypeFnT) -> _PreservesDTypeFnT:
1205
+
1206
+ def _maybe_cast(
1207
+ value: _CastableOrNoneT,
1208
+ dtype: types.DType | None,
1209
+ promote: bool = False,
1210
+ ) -> _CastableOrNoneT:
1211
+ if value is not None and dtype is not None:
1212
+ if promote:
1213
+ try:
1214
+ dtype = jnp.promote_types(value.dtype, dtype)
1215
+ except Exception as e:
1216
+ raise TypeError(
1217
+ f'Cannot promote {value=} of type {type(value)} with {dtype=}.'
1218
+ ) from e
1219
+ try:
1220
+ if value.dtype != dtype:
1221
+ value = value.astype(dtype)
1222
+ except Exception as e:
1223
+ raise TypeError(
1224
+ f'Cannot cast {value=} of type {type(value)} into {dtype=}.'
1225
+ ) from e
1226
+ return value
1227
+
1228
+ @functools.wraps(fn)
1229
+ def wrapped(*args: _CastableOrNoneT) -> Any:
1230
+ # Promote arguments if possible, then call the wrapped function.
1231
+ promoted_args = tuple(
1232
+ _maybe_cast(value, min_dtype, promote=True) for value in args
1233
+ )
1234
+ results = fn(*promoted_args)
1235
+
1236
+ if not restore_dtypes:
1237
+ return results
1238
+
1239
+ # Validate results and cast back to their respective inputs' DTypes.
1240
+ if (len(results) if isinstance(results, tuple) else 1) != len(args):
1241
+ raise TypeError(
1242
+ f'The promoted function `{wrapped.__name__}` must return a number'
1243
+ ' of outputs equal to the number of positional arguments.'
1244
+ )
1245
+ if isinstance(results, tuple):
1246
+ return tuple(
1247
+ _maybe_cast(value, arg.dtype if arg is not None else None)
1248
+ for value, arg in zip(results, args)
1249
+ )
1250
+ else:
1251
+ value, arg = results, args[0]
1252
+ return _maybe_cast(value, arg.dtype if arg is not None else None)
1253
+
1254
+ return wrapped
1255
+
1256
+ return _decorator
1257
+
1258
+
1259
+ @typing.overload
1260
+ def run_in_at_least_fp32(
1261
+ fn: _PreservesDTypeFnT, *, restore_dtypes: bool = True
1262
+ ) -> _PreservesDTypeFnT:
1263
+ ...
1264
+
1265
+
1266
+ @typing.overload
1267
+ def run_in_at_least_fp32(
1268
+ fn: None = None, *, restore_dtypes: bool = True
1269
+ ) -> PreservesDTypeFnDecorator[PreservesDTypeFn]:
1270
+ ...
1271
+
1272
+
1273
+ def run_in_at_least_fp32(
1274
+ fn: _PreservesDTypeFnT | None = None, *, restore_dtypes: bool = True
1275
+ ) -> _PreservesDTypeFnT | PreservesDTypeFnDecorator[PreservesDTypeFn]:
1276
+ """Decorator for promoting inputs to >=float32 for the function's duration.
1277
+
1278
+ Args:
1279
+ fn: Function to wrap. `fn` must return the same number of positional
1280
+ arguments as it receives. All its arguments must be Castable or None, and
1281
+ each of its outputs must be castable to its respective input's DType
1282
+ (unless that input was None).
1283
+ restore_dtypes: Whether to cast the outputs back to their respective inputs'
1284
+ DTypes.
1285
+
1286
+ Returns:
1287
+ If `fn` is provided, we return a version of `fn` that promotes its
1288
+ positional arguments with float32 and casts each of its outputs to its
1289
+ respective input's DType (unless that input was None). `fn` cannot be called
1290
+ with keyword arguments. If `fn` is None, we return a decorator that can be
1291
+ applied to a function to do the same.
1292
+
1293
+ Raises:
1294
+ TypeError: A keyword argument was provided, an argument could not be
1295
+ promoted with float32, a result could not be cast back to an input DType,
1296
+ or `fn` did not return the same number of arguments as it received.
1297
+ """
1298
+ decorator = _run_with_min_dtype(jnp.float32, restore_dtypes=restore_dtypes)
1299
+ return decorator(fn) if fn else decorator
1300
+
1301
+
1302
+ def maybe_in_at_least_fp32(
1303
+ promote: bool, *, restore_dtypes: bool = True
1304
+ ) -> PreservesDTypeFnDecorator[PreservesDTypeFn]:
1305
+ """Variant of `run_in_at_least_fp32` that is conditional on promote=True."""
1306
+ return (
1307
+ _run_with_min_dtype(jnp.float32, restore_dtypes=restore_dtypes)
1308
+ if promote
1309
+ else lambda fn: fn
1310
+ )
1311
+
1312
+
1313
+ def left_shift(
1314
+ x: types.Sequence,
1315
+ shifts: jt.Int[jt.ArrayT, 'B'] | TypingSequence[int] | int,
1316
+ ) -> types.Sequence:
1317
+ """Left shift the sequence by the provided amounts on the time axis.
1318
+
1319
+ Bitmask trick taken from google3/third_party/py/t5x/decoding.py.
1320
+
1321
+ TODO(rryan): Benchmark against a vmap + roll + mask.
1322
+
1323
+ Args:
1324
+ x: The sequence to be left shifted on the time axis.
1325
+ shifts: A scalar integer or [batch_size] array of offsets to shift by per
1326
+ batch item.
1327
+
1328
+ Returns:
1329
+ The sequence left shifted by the specified amount per batch item, with
1330
+ invalid zero padding inserted on the right. Sequences that are shifted
1331
+ outside of the physical extent of the array are truncated. The physical
1332
+ shape of the returned sequence is unchanged.
1333
+ """
1334
+ max_len = x.shape[1]
1335
+ if not max_len:
1336
+ return x
1337
+
1338
+ if isinstance(shifts, int):
1339
+ if shifts <= 0:
1340
+ return x
1341
+ return x[:, shifts:].pad_time(0, shifts, valid=False)
1342
+
1343
+ shifts = jnp.maximum(0, jnp.asarray(shifts))
1344
+ nbits = np.ceil(np.log2(max_len)).astype(np.int32)
1345
+
1346
+ def apply_fn(
1347
+ values: jax.Array, mask: jax.Array, bitmask: int
1348
+ ) -> tuple[jax.Array, jax.Array]:
1349
+ assert bitmask > 0
1350
+ c = shifts & bitmask
1351
+
1352
+ paddings = [(0, 0)] * values.ndim
1353
+ paddings[1] = (0, bitmask)
1354
+
1355
+ values = jnp.where(
1356
+ c.reshape(shifts.shape + (1,) * (values.ndim - 1)),
1357
+ jnp.pad(values, paddings)[:, bitmask:, ...],
1358
+ values,
1359
+ )
1360
+ paddings = [(0, 0)] * mask.ndim
1361
+ paddings[1] = (0, bitmask)
1362
+ mask = jnp.where(
1363
+ c.reshape(shifts.shape + (1,)),
1364
+ jnp.pad(mask, paddings)[:, bitmask:],
1365
+ mask,
1366
+ )
1367
+ return values, mask
1368
+
1369
+ for i in range(0, nbits + 1):
1370
+ bitmask = 2**i
1371
+ x = x.apply_masked(apply_fn, bitmask=bitmask)
1372
+
1373
+ return x
1374
+
1375
+
1376
+ def right_shift(
1377
+ x: types.Sequence,
1378
+ shifts: jt.Int[jt.ArrayT, 'B'] | TypingSequence[int] | int,
1379
+ ) -> types.Sequence:
1380
+ """Right shift the sequence by the provided amounts on the time axis.
1381
+
1382
+ Bitmask trick taken from google3/third_party/py/t5x/decoding.py.
1383
+
1384
+ TODO(rryan): Benchmark against a vmap + roll + mask.
1385
+
1386
+ Args:
1387
+ x: The sequence to be right shifted on the time axis.
1388
+ shifts: A scalar integer or [batch_size] array of offsets to shift by per
1389
+ batch item.
1390
+
1391
+ Returns:
1392
+ The sequence right shifted by the specified amount per batch item, with
1393
+ invalid zero padding inserted on the left. Sequences that are shifted
1394
+ outside of the physical extent of the array are truncated. The physical
1395
+ shape of the returned sequence is unchanged.
1396
+ """
1397
+ max_len = x.shape[1]
1398
+ if not max_len:
1399
+ return x
1400
+
1401
+ if isinstance(shifts, int):
1402
+ if shifts <= 0:
1403
+ return x
1404
+ return x[:, :-shifts].pad_time(shifts, 0, valid=False)
1405
+
1406
+ shifts = jnp.maximum(0, jnp.asarray(shifts))
1407
+ nbits = np.ceil(np.log2(max_len)).astype(np.int32)
1408
+
1409
+ def apply_fn(
1410
+ values: jax.Array, mask: jax.Array, bitmask: int
1411
+ ) -> tuple[jax.Array, jax.Array]:
1412
+ assert bitmask > 0
1413
+
1414
+ paddings = [(0, 0)] * values.ndim
1415
+ paddings[1] = (bitmask, 0)
1416
+
1417
+ values = jnp.where(
1418
+ (shifts & bitmask).reshape(shifts.shape + (1,) * (values.ndim - 1)),
1419
+ jnp.pad(values, paddings)[:, :-bitmask, ...],
1420
+ values,
1421
+ )
1422
+
1423
+ paddings = [(0, 0)] * mask.ndim
1424
+ paddings[1] = (bitmask, 0)
1425
+ mask = jnp.where(
1426
+ (shifts & bitmask).reshape(shifts.shape + (1,)),
1427
+ jnp.pad(mask, paddings)[:, :-bitmask],
1428
+ mask,
1429
+ )
1430
+ return values, mask
1431
+
1432
+ for i in range(0, nbits + 1):
1433
+ bitmask = 2**i
1434
+ x = x.apply_masked(apply_fn, bitmask=bitmask)
1435
+
1436
+ return x
1437
+
1438
+
1439
+ def ragged_sequence_concat(
1440
+ x: types.Sequence, y: types.Sequence
1441
+ ) -> types.Sequence:
1442
+ """Concatenates left-aligned contiguous sequences logically.
1443
+
1444
+ x and y are assumed to be left-aligned sequences with contiguous masks and
1445
+ different lengths per batch item. x and y must have equal batch size and
1446
+ channel spec.
1447
+
1448
+ As opposed to sl.Sequence.concatenate_sequences which concatenates physical
1449
+ sequence arrays, this function concatenates sequences logically by right
1450
+ shifting y by the lengths of each sequence in x, then stitching them together.
1451
+
1452
+ Both x and y are padded to the sum of their physical lengths before
1453
+ concatenation, so no truncation of y can occur.
1454
+
1455
+ Args:
1456
+ x: Sequence to prepend to y.
1457
+ y: Sequence to append to x.
1458
+
1459
+ Returns:
1460
+ A new sequence where each batch item is the concatenation of the logical
1461
+ sequence x[i] and y[i].
1462
+ """
1463
+ if x.shape[0] != y.shape[0] or x.channel_spec != y.channel_spec:
1464
+ raise ValueError(
1465
+ 'x and y must have the same batch size and channel spec:'
1466
+ f' {x.shape[0]=} {x.channel_spec=} != {y.shape[0]} {y.channel_spec=}'
1467
+ )
1468
+ max_length = x.shape[1] + y.shape[1]
1469
+ x_lengths = x.lengths()
1470
+
1471
+ # Pad both x and y to the maximum of their combined physical lengths.
1472
+ x = x.pad_time(0, max_length - x.shape[1], valid=False)
1473
+ y = y.pad_time(0, max_length - y.shape[1], valid=False)
1474
+
1475
+ y_shifted = right_shift(y, x_lengths)
1476
+
1477
+ values = jnp.where(x.expanded_mask(), x.values, y_shifted.values)
1478
+ mask = jnp.logical_or(x.mask, y_shifted.mask)
1479
+ return types.Sequence(values, mask)
1480
+
1481
+
1482
+ def get_timing_signal_1d_pos(
1483
+ position: jax.Array,
1484
+ channels: int,
1485
+ min_timescale: float = 1.0,
1486
+ max_timescale: float = 1.0e4,
1487
+ dtype: types.DType = jnp.float32,
1488
+ ) -> jax.Array:
1489
+ """Sinusoidal position embeddings with explicit positions.
1490
+
1491
+ Copied from tensor2tensor.
1492
+
1493
+ Each channel of the input Tensor is incremented by a sinusoid of a different
1494
+ frequency and phase.
1495
+
1496
+ This allows attention to learn to use absolute and relative positions.
1497
+ Timing signals should be added to some precursors of both the query and the
1498
+ memory inputs to attention.
1499
+
1500
+ The use of relative position is possible because sin(x+y) and cos(x+y) can be
1501
+ expressed in terms of y, sin(x) and cos(x).
1502
+
1503
+ In particular, we use a geometric sequence of timescales starting with
1504
+ min_timescale and ending with max_timescale. The number of different
1505
+ timescales is equal to channels / 2. For each timescale, we
1506
+ generate the two sinusoidal signals sin(timestep/timescale) and
1507
+ cos(timestep/timescale). All of these sinusoids are concatenated in
1508
+ the channels dimension.
1509
+
1510
+ Args:
1511
+ position: A [batch, length] tensor of positions to compute timing signal
1512
+ for.
1513
+ channels: scalar, size of timing embeddings to create. The number of
1514
+ different timescales is equal to channels / 2.
1515
+ min_timescale: a float
1516
+ max_timescale: a float
1517
+ dtype: Type of the returned timing signal.
1518
+
1519
+ Returns:
1520
+ a Tensor of timing signals [batch, length, channels]
1521
+ """
1522
+ position = jnp.array(position, jnp.float32)
1523
+ assert_has_rank(position.shape, 2)
1524
+ num_timescales = channels // 2
1525
+ log_timescale_increment = math.log(
1526
+ float(max_timescale) / float(min_timescale)
1527
+ ) / max(num_timescales - 1, 1)
1528
+ inv_timescales = min_timescale * np.exp(
1529
+ np.arange(num_timescales, dtype=np.float32) * -log_timescale_increment
1530
+ )
1531
+ scaled_time = (
1532
+ position[:, :, jnp.newaxis] * inv_timescales[jnp.newaxis, jnp.newaxis, :]
1533
+ )
1534
+ # Please note that this slightly differs from the published paper.
1535
+ # See a discussion here: https://github.com/tensorflow/tensor2tensor/pull/177
1536
+ timing_signal = jnp.concatenate(
1537
+ [jnp.sin(scaled_time), jnp.cos(scaled_time)], axis=2
1538
+ )
1539
+ timing_signal = jnp.pad(
1540
+ timing_signal, [[0, 0], [0, 0], [0, np.mod(channels, 2)]]
1541
+ )
1542
+ return timing_signal.astype(dtype)
1543
+
1544
+
1545
+ def ones_matrix_band_part(
1546
+ rows: int,
1547
+ cols: int,
1548
+ num_lower: int,
1549
+ num_upper: int,
1550
+ out_dtype: types.DType = jnp.float32,
1551
+ out_shape: types.ShapeLike | None = None,
1552
+ ):
1553
+ """Matrix band part of ones.
1554
+
1555
+ Copied from tensor2tensor.
1556
+
1557
+ Args:
1558
+ rows: int determining number of rows in output
1559
+ cols: int
1560
+ num_lower: int, maximum distance backward. Negative values indicate
1561
+ unlimited.
1562
+ num_upper: int, maximum distance forward. Negative values indicate
1563
+ unlimited.
1564
+ out_dtype: Output dtype.
1565
+ out_shape: shape to reshape output by.
1566
+
1567
+ Returns:
1568
+ Tensor of size rows * cols reshaped into shape out_shape.
1569
+ """
1570
+ if all([isinstance(el, int) for el in [rows, cols, num_lower, num_upper]]):
1571
+ # Needed info is constant, so we construct in numpy
1572
+ if num_lower < 0:
1573
+ num_lower = rows - 1
1574
+ if num_upper < 0:
1575
+ num_upper = cols - 1
1576
+ lower_mask = np.tri(cols, rows, num_lower).T
1577
+ upper_mask = np.tri(rows, cols, num_upper)
1578
+ band = np.ones((rows, cols)) * lower_mask * upper_mask
1579
+ if out_shape:
1580
+ band = band.reshape(out_shape)
1581
+ band = jnp.asarray(band, out_dtype)
1582
+ else:
1583
+ m = jnp.arange(rows).reshape((rows, 1))
1584
+ n = jnp.arange(cols).reshape((1, cols))
1585
+ band = ((num_lower < 0) | ((m - n) <= num_lower)) & (
1586
+ (num_upper < 0) | ((n - m) <= num_upper)
1587
+ )
1588
+ if out_shape:
1589
+ band = jnp.reshape(band, out_shape)
1590
+ band = band.astype(out_dtype)
1591
+
1592
+ return band
1593
+
1594
+
1595
+ def get_input_latency(
1596
+ config: types.SequenceLayerConfig, accumulated_input_latency: int = 0
1597
+ ) -> int:
1598
+ """Returns the input latency of the provided SequenceLayerConfig."""
1599
+
1600
+ def fn():
1601
+ layer = config.make()
1602
+
1603
+ def init_fn(layer: types.SequenceLayer):
1604
+ return layer.get_accumulated_input_latency(accumulated_input_latency)
1605
+
1606
+ result, _ = layer.init_with_output(jax.random.PRNGKey(0), method=init_fn)
1607
+ return jnp.zeros((result,))
1608
+
1609
+ (result,) = jax.eval_shape(fn).shape
1610
+ return result
1611
+
1612
+
1613
+ def get_output_latency(
1614
+ config: types.SequenceLayerConfig, accumulated_output_latency: int = 0
1615
+ ) -> int:
1616
+ """Returns the output latency of the provided SequenceLayerConfig."""
1617
+
1618
+ def fn():
1619
+ layer = config.make()
1620
+
1621
+ def init_fn(layer: types.SequenceLayer):
1622
+ return layer.get_accumulated_output_latency(accumulated_output_latency)
1623
+
1624
+ result, _ = layer.init_with_output(jax.random.PRNGKey(0), method=init_fn)
1625
+ return jnp.zeros((result,))
1626
+
1627
+ (result,) = jax.eval_shape(fn).shape
1628
+ return result
1629
+
1630
+
1631
+ def get_required_stepwise_delay(
1632
+ output_ratio: fractions.Fraction, input_latency: int
1633
+ ) -> int:
1634
+ """Returns the delay required so input_latency is divisible by 1/output_ratio.
1635
+
1636
+ b/372530075 - When combining upsampling and downsampling layers with latency,
1637
+ layer/step equivalence requires inserting delays. This function returns the
1638
+ correct amount of step-wise delay to insert.
1639
+
1640
+ Args:
1641
+ output_ratio: The output ratio of the layer.
1642
+ input_latency: The accumulated input latency of layers preceding the layer.
1643
+
1644
+ Returns:
1645
+ The amount of delay required to ensure input latency is divisible by
1646
+ output_ratio.
1647
+ """
1648
+ if 1 not in output_ratio.as_integer_ratio():
1649
+ raise NotImplementedError(
1650
+ 'get_required_stepwise_delay expects integer upsampling or'
1651
+ f' downsampling, got {output_ratio=}'
1652
+ )
1653
+ return int(-input_latency % (1 / output_ratio))
1654
+
1655
+
1656
+ def get_output_ratio(config: types.SequenceLayerConfig) -> fractions.Fraction:
1657
+ """Returns the output ratio of the provided SequenceLayerConfig."""
1658
+
1659
+ def fn():
1660
+ layer = config.make()
1661
+
1662
+ def init_fn(layer: types.SequenceLayer):
1663
+ return layer.output_ratio
1664
+
1665
+ output, _ = layer.init_with_output(jax.random.PRNGKey(0), method=init_fn)
1666
+ return jnp.zeros((output.numerator, output.denominator))
1667
+
1668
+ numerator, denominator = jax.eval_shape(fn).shape
1669
+ return fractions.Fraction(numerator, denominator)
1670
+
1671
+
1672
+ @jt.typed
1673
+ def batch_where(
1674
+ cond: jt.Bool[jt.ArrayT, 'B'], a: jt.AnyPyTree, b: jt.AnyPyTree
1675
+ ) -> jt.AnyPyTree:
1676
+ """A jnp.where-like operation switching on the outermost batch dimension."""
1677
+
1678
+ def where_a(a: jax.Array, b: jax.Array) -> jax.Array:
1679
+ assert a.shape == b.shape, (a.shape, b.shape)
1680
+ assert a.shape[:1] == cond.shape
1681
+
1682
+ c = cond.reshape(cond.shape + (1,) * (a.ndim - 1))
1683
+ return jnp.where(c, a, b)
1684
+
1685
+ return jax.tree.map(where_a, a, b)
1686
+
1687
+
1688
+ def split_dimension(
1689
+ x: jax.Array, axis: int, shape: types.ShapeLike
1690
+ ) -> jax.Array:
1691
+ """Splits axis in x into the provided shape."""
1692
+ axis_size = x.shape[axis]
1693
+ if axis_size != np.prod(shape):
1694
+ raise ValueError(
1695
+ f'Splitting {axis=} of {x.shape=}, incorrect number of elements for'
1696
+ f' {shape=}.'
1697
+ )
1698
+
1699
+ axis = axis % x.ndim
1700
+ outer_dimensions = x.shape[:axis]
1701
+ inner_dimensions = x.shape[axis + 1 :]
1702
+ new_shape = outer_dimensions + tuple(shape) + inner_dimensions
1703
+ return x.reshape(new_shape)
1704
+
1705
+
1706
+ def is_integral(dtype: np.dtype) -> bool:
1707
+ """Returns true if the dtype is integral."""
1708
+ # Follow .dtype if passed a jnp.bfloat16/float32/etc. constructor.
1709
+ if hasattr(dtype, 'dtype'):
1710
+ dtype = dtype.dtype
1711
+
1712
+ return issubclass(dtype.type, jnp.integer)
1713
+
1714
+
1715
+ def is_floating(dtype: np.dtype) -> bool:
1716
+ """Returns true if the dtype is floating point."""
1717
+ # Follow .dtype if passed a jnp.bfloat16/float32/etc. constructor.
1718
+ if hasattr(dtype, 'dtype'):
1719
+ dtype = dtype.dtype
1720
+
1721
+ return dtype == jnp.bfloat16 or issubclass(dtype.type, jnp.floating)
1722
+
1723
+
1724
+ def pprint_tree_shapes_types(tree: Any) -> None:
1725
+ """Pretty-prints the shapes and types of a pytree."""
1726
+ pprint.pprint(
1727
+ jax.tree.map(lambda a: jax.ShapeDtypeStruct(a.shape, a.dtype), tree)
1728
+ )
1729
+
1730
+
1731
+ def pformat_tree_shapes_types(tree: Any) -> str:
1732
+ """Pretty-formats the shapes and types of a pytree."""
1733
+ return pprint.pformat(
1734
+ jax.tree.map(lambda a: jax.ShapeDtypeStruct(a.shape, a.dtype), tree)
1735
+ )
1736
+
1737
+
1738
+ @jt.typed
1739
+ def batched_time_slice(
1740
+ x: types.SequenceT[jt.Shaped, 'B T ...'],
1741
+ begin: jt.Int[jt.ArrayT, 'B'],
1742
+ size: int,
1743
+ ) -> types.SequenceT[jt.Shaped, 'B {size} ...']:
1744
+ """Gathers a slice of time dimension of the sequence."""
1745
+ time = x.shape[1]
1746
+ available = jnp.maximum(time - begin, 0)
1747
+ valid_size = jnp.minimum(size, available)
1748
+
1749
+ if not time:
1750
+ # Return an empty slice if x is zero-length.
1751
+ return x.pad_time(0, size, valid=False)
1752
+
1753
+ # Use jnp.arange(size) and clip indices that are out of range instead of
1754
+ # jnp.arange(valid_size) so that shapes are fixed (therefore TPU compatible).
1755
+ time_indices = jnp.minimum(
1756
+ begin[:, jnp.newaxis] + jnp.arange(size)[jnp.newaxis, :],
1757
+ jnp.maximum(0, time - 1),
1758
+ )
1759
+
1760
+ # Make a mask that is zero if the index went beyond the end.
1761
+ valid_mask = types.sequence_mask(valid_size, size)
1762
+
1763
+ mask = jnp.logical_and(
1764
+ valid_mask, jnp.take_along_axis(x.mask, time_indices, axis=1)
1765
+ )
1766
+ time_indices = time_indices.reshape(time_indices.shape + (1,) * (x.ndim - 2))
1767
+ values = jnp.take_along_axis(x.values, time_indices, axis=1)
1768
+
1769
+ # Preserve MaskedSequence type if x is MaskedSequence.
1770
+ return type(x)(values, mask)
1771
+
1772
+
1773
+ def _get_constant(
1774
+ layer: types.SequenceLayer,
1775
+ constants: types.Constants | None,
1776
+ name: str,
1777
+ expected_shape: types.ShapeLike | None,
1778
+ expected_dtype: types.DType | None,
1779
+ allow_broadcastable: bool,
1780
+ optional: bool,
1781
+ ) -> jax.Array | types.Sequence | None:
1782
+ """Returns the constant with the given name from the constants dictionary."""
1783
+ value = (constants or {}).get(name)
1784
+ if value is None:
1785
+ if optional:
1786
+ return None
1787
+ else:
1788
+ raise ValueError(
1789
+ f'{layer} requires the constant {name} to be provided via '
1790
+ f'constants, got: {constants}'
1791
+ )
1792
+
1793
+ wrong_shape = False
1794
+ if expected_shape is not None:
1795
+ if allow_broadcastable:
1796
+ try:
1797
+ jnp.broadcast_shapes(value.shape, expected_shape)
1798
+ except ValueError:
1799
+ wrong_shape = True
1800
+ else:
1801
+ wrong_shape = value.shape != expected_shape
1802
+ wrong_dtype = expected_dtype is not None and value.dtype != expected_dtype
1803
+ if wrong_shape or wrong_dtype:
1804
+ raise ValueError(
1805
+ f'{layer} requires the constant {name} to have shape'
1806
+ f' {expected_shape} dtype {expected_dtype}, got:'
1807
+ f' {value.shape=} {value.dtype=}'
1808
+ )
1809
+
1810
+ return value
1811
+
1812
+
1813
+ def get_constant_array(
1814
+ layer: types.SequenceLayer,
1815
+ constants: types.Constants | None,
1816
+ name: str,
1817
+ expected_shape: types.ShapeLike | None = None,
1818
+ expected_dtype: types.DType | None = None,
1819
+ unpack_sequence: bool = False,
1820
+ allow_broadcastable: bool = False,
1821
+ ) -> jax.Array:
1822
+ """Returns the constant with the given name from the constants dictionary."""
1823
+ value = _get_constant(
1824
+ layer,
1825
+ constants,
1826
+ name,
1827
+ expected_shape,
1828
+ expected_dtype,
1829
+ allow_broadcastable,
1830
+ optional=False,
1831
+ )
1832
+ if isinstance(value, types.Sequence) and unpack_sequence:
1833
+ value = value.values
1834
+ if not isinstance(value, jax.Array):
1835
+ raise ValueError(
1836
+ f'{layer} requires the constant {name} to be an array, got: {value}'
1837
+ )
1838
+ return value
1839
+
1840
+
1841
+ def get_constant_sequence(
1842
+ layer: types.SequenceLayer,
1843
+ constants: types.Constants | None,
1844
+ name: str,
1845
+ expected_shape: types.ShapeLike | None = None,
1846
+ expected_dtype: types.DType | None = None,
1847
+ allow_broadcastable: bool = False,
1848
+ ) -> types.Sequence:
1849
+ """Returns the constant with the given name from the constants dictionary."""
1850
+ value = _get_constant(
1851
+ layer,
1852
+ constants,
1853
+ name,
1854
+ expected_shape,
1855
+ expected_dtype,
1856
+ allow_broadcastable,
1857
+ optional=False,
1858
+ )
1859
+ if not isinstance(value, types.Sequence):
1860
+ raise ValueError(
1861
+ f'{layer} requires the constant {name} to be a sequence, got: {value}'
1862
+ )
1863
+ return value
1864
+
1865
+
1866
+ def get_optional_constant_sequence(
1867
+ layer: types.SequenceLayer,
1868
+ constants: types.Constants | None,
1869
+ name: str,
1870
+ expected_shape: types.ShapeLike | None = None,
1871
+ expected_dtype: types.DType | None = None,
1872
+ allow_broadcastable: bool = False,
1873
+ ) -> types.Sequence | None:
1874
+ """Returns the constant with the given name from the constants dictionary."""
1875
+ value = _get_constant(
1876
+ layer,
1877
+ constants,
1878
+ name,
1879
+ expected_shape,
1880
+ expected_dtype,
1881
+ allow_broadcastable,
1882
+ optional=True,
1883
+ )
1884
+ if value is None:
1885
+ return None
1886
+ if not isinstance(value, types.Sequence):
1887
+ raise ValueError(
1888
+ f'{layer} requires the constant {name} to be a sequence, got: {value}'
1889
+ )
1890
+ return value
1891
+
1892
+
1893
+ def get_step_with_emits_output_spec(
1894
+ layer: types.SequenceLayer,
1895
+ x: types.Sequence,
1896
+ state: types.State,
1897
+ *,
1898
+ training: bool,
1899
+ constants: types.Constants | None = None,
1900
+ ) -> tuple[types.Sequence, types.Emits]:
1901
+ """Returns the output spec of the layer."""
1902
+
1903
+ def step_fn(
1904
+ layer: types.SequenceLayer,
1905
+ x: types.Sequence,
1906
+ state: types.State,
1907
+ constants: types.Constants,
1908
+ ):
1909
+ y, _, emits = layer.step_with_emits(
1910
+ x, state, training=training, constants=constants
1911
+ )
1912
+ return y, emits
1913
+
1914
+ step_fn = functools.partial(nn.jit(step_fn), layer)
1915
+ return jax.eval_shape(step_fn, x, state, constants)
1916
+
1917
+
1918
+ def serial_block_size(layers: TypingSequence[types.SequenceLayer]) -> int:
1919
+ """Returns the block size of a serial combination of layers."""
1920
+ block_size = fractions.Fraction(1)
1921
+ output_ratio = fractions.Fraction(1)
1922
+
1923
+ for child_layer in layers:
1924
+ layer_output_ratio = child_layer.output_ratio
1925
+ layer_block_size = child_layer.block_size
1926
+ block_size = (
1927
+ np.lcm(block_size * output_ratio, layer_block_size) / output_ratio
1928
+ )
1929
+ assert block_size.denominator == 1
1930
+ output_ratio *= layer_output_ratio
1931
+
1932
+ return block_size.numerator
1933
+
1934
+
1935
+ def serial_output_ratio(
1936
+ layers: TypingSequence[types.SequenceLayer],
1937
+ ) -> fractions.Fraction:
1938
+ """Returns the output ratio of a serial combination of layers."""
1939
+ output_ratio = fractions.Fraction(1)
1940
+ for child_layer in layers:
1941
+ output_ratio *= child_layer.output_ratio
1942
+ return output_ratio
1943
+
1944
+
1945
+ def serial_input_latency(
1946
+ layers: TypingSequence[types.SequenceLayer],
1947
+ input_latency: int = 0,
1948
+ ) -> int:
1949
+ """Returns the input latency of a serial combination of layers."""
1950
+ for child_layer in reversed(layers):
1951
+ input_latency = child_layer.get_accumulated_input_latency(input_latency)
1952
+ return input_latency
1953
+
1954
+
1955
+ def serial_output_latency(
1956
+ layers: TypingSequence[types.SequenceLayer], output_latency: int = 0
1957
+ ) -> int:
1958
+ """Returns the output latency of a serial combination of layers."""
1959
+ for child_layer in layers:
1960
+ output_latency = child_layer.get_accumulated_output_latency(output_latency)
1961
+ return output_latency
1962
+
1963
+
1964
+ def receptive_field_union(
1965
+ rf_a: types.ReceptiveField, rf_b: types.ReceptiveField
1966
+ ) -> types.ReceptiveField:
1967
+ """Returns the union of the receptive fields of the layers."""
1968
+ if rf_a is None:
1969
+ return rf_b
1970
+ if rf_b is None:
1971
+ return rf_a
1972
+ past = min(rf_a[0], rf_b[0])
1973
+ future = max(rf_a[1], rf_b[1])
1974
+ return past, future
1975
+
1976
+
1977
+ def receptive_field_at(
1978
+ layer_receptive_field_per_step: dict[int, types.ReceptiveField],
1979
+ layer_output_ratio: fractions.Fraction,
1980
+ output_step: int,
1981
+ ) -> types.ReceptiveField:
1982
+ """Returns the receptive field of the layer at the given output step."""
1983
+ rf_per_step = layer_receptive_field_per_step
1984
+ types.validate_receptive_field_per_step(rf_per_step)
1985
+ # `output_step` can take any value, and we shift it to the range of values in
1986
+ # rf_per_step to compute the relative receptive field, and apply the reverse
1987
+ # shift in the input steps to get the actual input range for `output_step`.
1988
+ normalized_step = output_step % len(rf_per_step)
1989
+ shift = (output_step - normalized_step) // layer_output_ratio
1990
+ rf = rf_per_step[normalized_step]
1991
+ if rf is None:
1992
+ return None
1993
+ past, future = rf
1994
+ return past + shift, future + shift
1995
+
1996
+
1997
+ def layer_receptive_field_at(
1998
+ layer: types.SequenceLayer,
1999
+ output_step: int,
2000
+ ) -> types.ReceptiveField:
2001
+ """Returns the receptive field of the layer at the given output step."""
2002
+ return receptive_field_at(
2003
+ layer.receptive_field_per_step, layer.output_ratio, output_step
2004
+ )
2005
+
2006
+
2007
+ def reduce_receptive_field_per_step(
2008
+ rf_per_step: dict[int, types.ReceptiveField],
2009
+ output_ratio: fractions.Fraction,
2010
+ ) -> types.ReceptiveField:
2011
+ """Returns the union of the receptive fields in rf_per_step.
2012
+
2013
+ Args:
2014
+ rf_per_step: The receptive field per step.
2015
+ output_ratio: The output ratio of the layer.
2016
+
2017
+ Returns:
2018
+ The overall union of the receptive fields.
2019
+ """
2020
+ types.validate_receptive_field_per_step(rf_per_step)
2021
+
2022
+ # Pick the steps that have receptive field.
2023
+ rf_per_step = {k: v for k, v in rf_per_step.items() if v is not None}
2024
+ if not rf_per_step:
2025
+ # No receptive field if all steps have no receptive field.
2026
+ return None
2027
+
2028
+ # Compute the overall union of the receptive fields.
2029
+ min_past = np.inf
2030
+ max_future = -np.inf
2031
+ for step, rf in rf_per_step.items():
2032
+ past, future = rf
2033
+ past -= step // output_ratio
2034
+ future -= step // output_ratio
2035
+ min_past = min(min_past, past)
2036
+ max_future = max(max_future, future)
2037
+ return min_past, max_future
2038
+
2039
+
2040
+ def aggregate_layers_receptive_field_per_steps(
2041
+ layers: TypingSequence[types.SequenceLayer],
2042
+ ) -> dict[int, types.ReceptiveField]:
2043
+ return aggregate_receptive_field_per_steps(
2044
+ [layer.receptive_field_per_step for layer in layers]
2045
+ )
2046
+
2047
+
2048
+ def aggregate_receptive_field_per_steps(
2049
+ receptive_field_per_step_list: TypingSequence[
2050
+ dict[int, types.ReceptiveField]
2051
+ ],
2052
+ ) -> dict[int, types.ReceptiveField]:
2053
+ """Aggregates a list receptive field per step."""
2054
+ agg_rf_per_step = {}
2055
+ for rf_per_step in receptive_field_per_step_list:
2056
+ types.validate_receptive_field_per_step(rf_per_step)
2057
+ for step, rf in rf_per_step.items():
2058
+ agg_rf_per_step[step] = receptive_field_union(
2059
+ rf, agg_rf_per_step.get(step)
2060
+ )
2061
+ types.validate_receptive_field_per_step(agg_rf_per_step)
2062
+ return agg_rf_per_step
2063
+
2064
+
2065
+ def propagate_receptive_field_to_prev_layer(
2066
+ layer_rf_per_step_next: dict[int, types.ReceptiveField],
2067
+ layer_rf_per_step_prev: dict[int, types.ReceptiveField],
2068
+ layer_output_ratio_prev: fractions.Fraction,
2069
+ ) -> dict[int, types.ReceptiveField]:
2070
+ """Propagates the receptive field of the next layer to the previous layer.
2071
+
2072
+ Given the receptive field per step of next layer, this function traces back
2073
+ and expands the receptive field to the previous layer, returns the overall
2074
+ receptive per step obtained by stacking the two layers.
2075
+
2076
+ Args:
2077
+ layer_rf_per_step_next: The receptive field of the next layer.
2078
+ layer_rf_per_step_prev: The receptive field of the previous layer.
2079
+ layer_output_ratio_prev: The output ratio of the previous layer.
2080
+
2081
+ Returns:
2082
+ The receptive field per step of the Serial([previous, next]) layers.
2083
+ """
2084
+ expanded_rf_per_step = {}
2085
+ for step_next, rf_next in layer_rf_per_step_next.items():
2086
+ if rf_next is None:
2087
+ expanded_rf_per_step[step_next] = None
2088
+ continue
2089
+ types.validate_receptive_field(rf_next)
2090
+ past, future = rf_next
2091
+
2092
+ rf_prev_list = []
2093
+
2094
+ if past == -np.inf and future == np.inf:
2095
+ rf_prev_list.append((-np.inf, np.inf))
2096
+ else:
2097
+ if past == -np.inf:
2098
+ rf_prev_list.append((-np.inf, -np.inf))
2099
+ if future == np.inf:
2100
+ rf_prev_list.append((np.inf, np.inf))
2101
+
2102
+ # Is +1 enough when one side is +/-inf?
2103
+ start = past if past != -np.inf else future
2104
+ end = future + 1 if future != np.inf else past + 1
2105
+ # There is a possibility of optimizing by only considering
2106
+ # the first (past) and last (future) steps in computation below, but need
2107
+ # to verify that it works for the case of layers with varying rf per step.
2108
+ rf_prev_list.extend([
2109
+ receptive_field_at(layer_rf_per_step_prev, layer_output_ratio_prev, i)
2110
+ for i in range(start, end)
2111
+ ])
2112
+ rf_prev_list = [rf for rf in rf_prev_list if rf is not None]
2113
+ if not rf_prev_list:
2114
+ expanded_rf_per_step[step_next] = None
2115
+ continue
2116
+
2117
+ min_past = np.inf
2118
+ max_future = -np.inf
2119
+ for rf_prev in rf_prev_list:
2120
+ types.validate_receptive_field(rf_prev)
2121
+ past_prev, future_prev = rf_prev
2122
+ min_past = min(min_past, past_prev)
2123
+ max_future = max(max_future, future_prev)
2124
+ expanded_rf_per_step[step_next] = (min_past, max_future)
2125
+ return expanded_rf_per_step
2126
+
2127
+
2128
+ def receptive_field_per_step_of_serial_layers(
2129
+ layers: TypingSequence[types.SequenceLayer],
2130
+ ) -> dict[int, types.ReceptiveField]:
2131
+ """Returns the receptive field per step of the Serial(layers)."""
2132
+ if not layers:
2133
+ return {0: (0, 0)}
2134
+ receptive_field_per_step_list = [
2135
+ layer.receptive_field_per_step for layer in layers
2136
+ ]
2137
+ output_ratio_list = [layer.output_ratio for layer in layers]
2138
+ # Note extra steps does not affect the result, and LCM is the
2139
+ # upperbound of what we need, and we can reduce it to speed up computation.
2140
+ num_steps = math.lcm(*[len(r) for r in receptive_field_per_step_list])
2141
+ rf_per_step = {k: (k, k) for k in range(num_steps)}
2142
+ # Start from the last layer and work our way to the first.
2143
+ for output_ratio_i, rf_per_step_i in zip(
2144
+ reversed(output_ratio_list), reversed(receptive_field_per_step_list)
2145
+ ):
2146
+ rf_per_step = propagate_receptive_field_to_prev_layer(
2147
+ rf_per_step, rf_per_step_i, output_ratio_i
2148
+ )
2149
+ return rf_per_step