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,674 @@
1
+ # Copyright 2025 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
+ """Recurrent layers."""
15
+
16
+ import dataclasses
17
+ from typing import Callable, Literal
18
+
19
+ import einops
20
+ import flax.linen as nn
21
+ import jax
22
+ import jax.numpy as jnp
23
+ import numpy as np
24
+ import recurrentgemma
25
+ from sequence_layers.jax import types
26
+ from sequence_layers.jax import typing as jt
27
+ from sequence_layers.jax import utils
28
+
29
+
30
+ __all__ = (
31
+ # go/keep-sorted start
32
+ 'LSTM',
33
+ 'RGLRU',
34
+ # go/keep-sorted end
35
+ )
36
+
37
+
38
+ def unit_forget_bias(key, shape, dtype) -> jax.Array:
39
+ """An initializer for LSTM bias that sets the forget gate bias to one.
40
+
41
+ This is recommended in Jozefowicz et al.
42
+ https://github.com/mlresearch/v37/blob/gh-pages/jozefowicz15.pdf
43
+
44
+ Args:
45
+ key: Unused key array.
46
+ shape: The shape of the bias.
47
+ dtype: The dtype of the bias.
48
+
49
+ Returns:
50
+ A bias array with the forget gate component set to one.
51
+ """
52
+ del key
53
+ if len(shape) != 1 or shape[0] % 4 != 0:
54
+ raise ValueError(
55
+ f'Expected a single dimensional shape divisible by 4, got: {shape}.'
56
+ )
57
+ units = shape[0] // 4
58
+ return jnp.concatenate(
59
+ [
60
+ jnp.zeros([units], dtype),
61
+ jnp.ones([units], dtype),
62
+ jnp.zeros([2 * units], dtype),
63
+ ],
64
+ axis=0,
65
+ )
66
+
67
+
68
+ def orthogonal_init(scale: float = 1.0, column_axis: int = -1):
69
+ def init(key: jax.Array, shape: types.Shape, dtype: types.DType) -> jax.Array:
70
+ # Flax's orthogonal initializer uses jax.lax.qr internally, which only
71
+ # supports float32. Compute the initializer in float32 then cast to the
72
+ # desired dtype.
73
+ value = nn.initializers.orthogonal(scale=scale, column_axis=column_axis)(
74
+ key, shape, jnp.float32
75
+ )
76
+ return value.astype(dtype)
77
+
78
+ return init
79
+
80
+
81
+ class LSTM(types.SequenceLayer):
82
+ """A Long Short-term Memory (LSTM) layer."""
83
+
84
+ @dataclasses.dataclass(frozen=True)
85
+ class Config(types.SequenceLayerConfig):
86
+ """Config for LSTM."""
87
+
88
+ units: int
89
+ compute_dtype: types.DType | None = None
90
+ param_dtype: types.DType | None = jnp.float32
91
+ precision: nn.linear.PrecisionLike = None
92
+ activation: Callable[[jax.Array], jax.Array] = jax.nn.tanh
93
+ recurrent_activation: Callable[[jax.Array], jax.Array] = jax.nn.sigmoid
94
+ use_bias: bool = True
95
+ kernel_init: nn.initializers.Initializer = nn.linear.default_kernel_init
96
+ kernel_sharding: types.Sharding | None = None
97
+ recurrent_kernel_init: nn.initializers.Initializer = orthogonal_init()
98
+ recurrent_kernel_sharding: types.Sharding | None = None
99
+ bias_init: nn.initializers.Initializer = unit_forget_bias
100
+ bias_sharding: types.Sharding | None = None
101
+ name: str | None = None
102
+
103
+ def make(self) -> 'LSTM':
104
+ return LSTM(self, name=self.name)
105
+
106
+ config: Config
107
+
108
+ @nn.nowrap
109
+ def get_output_shape(
110
+ self,
111
+ input_shape: types.ShapeLike,
112
+ *,
113
+ constants: types.Constants | None = None,
114
+ ) -> types.Shape:
115
+ return (self.config.units,)
116
+
117
+ @nn.nowrap
118
+ def get_output_dtype(
119
+ self,
120
+ input_dtype: types.DType,
121
+ ) -> types.DType:
122
+ return utils.get_promoted_dtype(
123
+ input_dtype, self.config.param_dtype, dtype=self.config.compute_dtype
124
+ )
125
+
126
+ @property
127
+ def receptive_field_per_step(self) -> dict[int, types.ReceptiveField]:
128
+ return {0: (-np.inf, 0)}
129
+
130
+ @nn.compact
131
+ def _cell(
132
+ self, x: jax.Array, state: tuple[jax.Array, jax.Array]
133
+ ) -> tuple[jax.Array, tuple[jax.Array, jax.Array]]:
134
+ if x.ndim != 3 or x.shape[1] != 1:
135
+ raise ValueError(f'Expected [b, 1, d] inputs, got: {x.shape}.')
136
+ c_tm1, h_tm1 = state
137
+
138
+ compute_dtype = self.get_output_dtype(x.dtype)
139
+
140
+ # Project [b, 1, d] to [b, 1, 4 * units].
141
+ z = utils.FlaxEinsumDense(
142
+ '...d,dh->...h',
143
+ output_shape=(4 * self.config.units,),
144
+ compute_dtype=self.config.compute_dtype,
145
+ param_dtype=self.config.param_dtype,
146
+ precision=self.config.precision,
147
+ kernel_init=self.config.kernel_init,
148
+ kernel_sharding=self.config.kernel_sharding,
149
+ name='kernel',
150
+ )(x)
151
+ # Project [b, 1, h] to [b, 1, 4 * units]
152
+ z += utils.FlaxEinsumDense(
153
+ '...u,uh->...h',
154
+ output_shape=(4 * self.config.units,),
155
+ compute_dtype=self.config.compute_dtype,
156
+ param_dtype=self.config.param_dtype,
157
+ precision=self.config.precision,
158
+ kernel_init=self.config.recurrent_kernel_init,
159
+ kernel_sharding=self.config.recurrent_kernel_sharding,
160
+ name='recurrent_kernel',
161
+ )(h_tm1)
162
+
163
+ if self.config.use_bias:
164
+ bias_init = utils.shard_initializer(
165
+ self.config.bias_init, self.config.bias_sharding
166
+ )
167
+ bias = self.param(
168
+ 'bias',
169
+ bias_init,
170
+ (4 * self.config.units,),
171
+ self.config.param_dtype,
172
+ )
173
+ z, bias = nn.dtypes.promote_dtype(z, bias, dtype=compute_dtype)
174
+ z = utils.bias_add(z, bias)
175
+
176
+ z0, z1, z2, z3 = jnp.split(
177
+ z,
178
+ [
179
+ self.config.units,
180
+ 2 * self.config.units,
181
+ 3 * self.config.units,
182
+ ],
183
+ axis=-1,
184
+ )
185
+
186
+ i = self.config.recurrent_activation(z0)
187
+ f = self.config.recurrent_activation(z1)
188
+ c = f * c_tm1 + i * self.config.activation(z2)
189
+ o = self.config.recurrent_activation(z3)
190
+ h = o * self.config.activation(c)
191
+ return h, (c, h)
192
+
193
+ @types.check_step
194
+ def step(
195
+ self,
196
+ x: types.Sequence,
197
+ state: types.State,
198
+ *,
199
+ training: bool,
200
+ constants: types.Constants | None = None,
201
+ ) -> tuple[types.Sequence, types.State]:
202
+ if x.shape[1] == 1:
203
+
204
+ y, new_state = self._cell(x.values, state)
205
+
206
+ def copy_state_through(new_a: jax.Array, a: jax.Array) -> jax.Array:
207
+ assert new_a.ndim >= 2, (new_a.shape, new_a.dtype)
208
+ mask = x.mask.reshape(x.mask.shape + (1,) * (new_a.ndim - 2))
209
+ return jnp.where(mask, new_a, a)
210
+
211
+ # Don't update state on invalid timesteps.
212
+ state = jax.tree.map(copy_state_through, new_state, state)
213
+
214
+ return types.Sequence(y, x.mask), state
215
+
216
+ # If we received multiple timesteps, unroll them statically (assuming step
217
+ # inputs are usually small).
218
+ output, state, _ = utils.step_by_step_static(
219
+ self,
220
+ x,
221
+ training=training,
222
+ initial_state=state,
223
+ constants=constants,
224
+ with_emits=False,
225
+ )
226
+ return output, state
227
+
228
+ @types.check_layer
229
+ def layer(
230
+ self,
231
+ x: types.Sequence,
232
+ *,
233
+ training: bool,
234
+ constants: types.Constants | None = None,
235
+ ) -> types.Sequence:
236
+ # Use dynamic unroll for layer-wise application.
237
+ output, _, _ = utils.step_by_step_dynamic(
238
+ self, x, training=training, constants=constants, with_emits=False
239
+ )
240
+ return output
241
+
242
+ def get_initial_state(
243
+ self,
244
+ batch_size: int,
245
+ input_spec: types.ShapeDType,
246
+ *,
247
+ training: bool,
248
+ constants: types.Constants | None = None,
249
+ ) -> types.State:
250
+ # A time axis of 1 is included in the state arrays for ease of broadcasting
251
+ # with the input.
252
+ compute_dtype = self.get_output_dtype(input_spec.dtype)
253
+ c = jnp.zeros((batch_size, 1, self.config.units), dtype=compute_dtype)
254
+ h = jnp.zeros((batch_size, 1, self.config.units), dtype=compute_dtype)
255
+ return (c, h)
256
+
257
+
258
+ def _rnn_real_param_init(
259
+ min_rad: float,
260
+ max_rad: float,
261
+ transform: str = 'softplus',
262
+ eps: float = 1e-8,
263
+ ) -> nn.initializers.Initializer:
264
+ """Initializes the `A` real parameter of the RG-LRU uniformly on a ring."""
265
+
266
+ def init(
267
+ key: jax.Array,
268
+ shape: types.Shape,
269
+ dtype: types.DType = jnp.float32,
270
+ ) -> jt.Float[jt.ArrayT, 'e']:
271
+ unif = jax.random.uniform(key, shape=shape)
272
+ # Proportional to area in a ring.
273
+ a_real = 0.5 * jnp.log(unif * (max_rad**2 - min_rad**2) + min_rad**2 + eps)
274
+
275
+ if transform == 'softplus':
276
+ # Inverse transform.
277
+ return jnp.log(jnp.exp(-a_real) - 1.0).astype(dtype)
278
+ else:
279
+ raise NotImplementedError()
280
+
281
+ return init
282
+
283
+
284
+ def _rnn_imag_param_init(
285
+ max_rad: float,
286
+ ) -> nn.initializers.Initializer:
287
+ """Initializes the `A` imag parameter of the RG-LRU uniformly on a ring."""
288
+
289
+ def init(
290
+ key: jax.Array,
291
+ shape: types.ShapeLike,
292
+ dtype: types.DType = jnp.float32,
293
+ ) -> jt.Float[jt.ArrayT, 'e']:
294
+ unif = jax.random.uniform(key, shape=shape)
295
+ return (jnp.pi * max_rad * unif).astype(dtype)
296
+
297
+ return init
298
+
299
+
300
+ class RGLRU(types.SequenceLayer):
301
+ """A Real-Gated Linear Recurrent Unit (RG-LRU) layer.
302
+
303
+ From the Griffin architecture: https://arxiv.org/abs/2402.19427
304
+
305
+ Implementation follows https://github.com/google-deepmind/recurrentgemma.
306
+
307
+ WARNING: The current implementation is not able to work with anything but
308
+ left-aligned ragged masks. Non-contiguous masks will incorrectly compute
309
+ results on the mask=False timesteps.
310
+ """
311
+
312
+ ScanType = Literal[ # pylint: disable=invalid-name
313
+ 'auto', 'linear_native', 'associative_native', 'linear_pallas'
314
+ ]
315
+
316
+ @dataclasses.dataclass(frozen=True)
317
+ class Config(types.SequenceLayerConfig):
318
+ """Config for RG-LRU."""
319
+
320
+ units: int
321
+ num_heads: int
322
+ scan_type: 'RGLRU.ScanType' = 'auto'
323
+ scan_sharding: types.Sharding | None = None
324
+ only_real: bool = True
325
+ min_rad: float = 0.9
326
+ # Sharding for the `A` real and imaginary parameters.
327
+ # Shape is [units] if only_real or [units // 2] if complex.
328
+ a_sharding: types.Sharding | None = None
329
+ gate_kernel_variance_scale: float = 1.0
330
+ # Sharding for the kernel matrices in the gate operations. Shape is
331
+ # [num_heads, units // units_per_head, units // units_per_head] if only_real
332
+ # or [num_heads, units // units_per_head, units // (2 * units_per_head)] if
333
+ # complex.
334
+ gate_kernel_sharding: types.Sharding | None = None
335
+ # Sharding for the bias matrices in the gate operations. Shape is
336
+ # [num_heads, units // units_per_head] if only_real or [num_heads, units //
337
+ # (2 * units_per_head)] if complex.
338
+ gate_bias_sharding: types.Sharding | None = None
339
+ compute_dtype: types.DType | None = None
340
+ param_dtype: types.DType | None = jnp.float32
341
+ # An optional name for the layer.
342
+ name: str | None = None
343
+
344
+ def __post_init__(self):
345
+ if not self.only_real:
346
+ if self.units % 2 != 0:
347
+ raise ValueError(
348
+ 'If `only_real=False`, `units` must be even, but got'
349
+ f' {self.units=}.'
350
+ )
351
+ if self.min_rad >= 0.999:
352
+ raise ValueError(
353
+ 'If `only_real=False`, `min_rad` must be less than 0.999, but got'
354
+ f' {self.min_rad=}.'
355
+ )
356
+
357
+ complex_units = self.units if self.only_real else self.units // 2
358
+ if complex_units % self.num_heads != 0:
359
+ raise ValueError(
360
+ 'The number of heads must divide the number of complex units, but'
361
+ f' got {self.num_heads=} and {complex_units=}.'
362
+ )
363
+
364
+ def make(self) -> 'RGLRU':
365
+ return RGLRU(self, name=self.name)
366
+
367
+ config: Config
368
+
369
+ @property
370
+ def _scan_type(self) -> recurrentgemma.common.ScanType:
371
+ match self.config.scan_type:
372
+ case 'auto':
373
+ return recurrentgemma.common.ScanType.AUTO
374
+ case 'linear_native':
375
+ return recurrentgemma.common.ScanType.LINEAR_NATIVE
376
+ case 'associative_native':
377
+ return recurrentgemma.common.ScanType.ASSOCIATIVE_NATIVE
378
+ case 'linear_pallas':
379
+ return recurrentgemma.common.ScanType.LINEAR_PALLAS
380
+ case _:
381
+ raise ValueError(f'Unknown scan type: {self.config.scan_type}')
382
+
383
+ @nn.nowrap
384
+ def get_output_shape(
385
+ self,
386
+ input_shape: types.ShapeLike,
387
+ *,
388
+ constants: types.Constants | None = None,
389
+ ) -> types.Shape:
390
+ return (self.config.units,)
391
+
392
+ @nn.nowrap
393
+ def get_output_dtype(
394
+ self,
395
+ input_dtype: types.DType,
396
+ ) -> types.DType:
397
+ return utils.get_promoted_dtype(
398
+ input_dtype, self.config.param_dtype, dtype=self.config.compute_dtype
399
+ )
400
+
401
+ @property
402
+ def receptive_field_per_step(self) -> dict[int, types.ReceptiveField]:
403
+ return {0: (-np.inf, 0)}
404
+
405
+ @jt.typed
406
+ def merged_to_complex(
407
+ self,
408
+ x: jt.Float[jt.ArrayT, '*b'],
409
+ ) -> recurrentgemma.complex_lib.RealOrComplex:
410
+ """Returns a (complex) array from a merged array.
411
+
412
+ A merged array is one where the first half over the last axis represents the
413
+ real part of a complex array, while the second part represents the
414
+ imaginary.
415
+
416
+ Args:
417
+ x: The merged array.
418
+
419
+ Returns:
420
+ A (complex) array represented by `x`.
421
+ """
422
+ if self.config.only_real:
423
+ return x
424
+
425
+ assert x.shape[-1] % 2 == 0
426
+ return self.real_imag_complex(*jnp.split(x, 2, axis=-1))
427
+
428
+ @jt.typed
429
+ def real_imag_complex(
430
+ self,
431
+ real: jt.Float[jt.ArrayT, '*b'],
432
+ imag: jt.Float[jt.ArrayT, '*b'] | None,
433
+ ) -> recurrentgemma.complex_lib.RealOrComplex:
434
+ """Based on the settings, creates a (complex) number in the correct format.
435
+
436
+ Args:
437
+ real: The real part of the complex number.
438
+ imag: The imaginary part of the complex number.
439
+
440
+ Returns:
441
+ The correct representation for a complex number. If `only_real=True`
442
+ the function expects that `imag` is None and will directly return `real`.
443
+ When using `bfloat16` or Pallas a `complex_lib.Complex` is returned,
444
+ otherwise a native jax array with a complex type.
445
+ """
446
+ if self.config.only_real:
447
+ assert imag is None
448
+ return real
449
+
450
+ if self.use_custom_complex(real.dtype):
451
+ return recurrentgemma.complex_lib.Complex(real, imag)
452
+ else:
453
+ return real + 1j * imag
454
+
455
+ def use_custom_complex(self, real_dtype: jnp.dtype) -> bool:
456
+ return (
457
+ real_dtype in (jnp.bfloat16, jnp.float16)
458
+ or self._scan_type == recurrentgemma.common.ScanType.LINEAR_PALLAS
459
+ )
460
+
461
+ @jt.typed
462
+ def complex_to_merged(
463
+ self,
464
+ x: recurrentgemma.complex_lib.RealOrComplex,
465
+ ) -> jt.Float[jt.ArrayT, '*b']:
466
+ """Returns a merged array from a (complex) array.
467
+
468
+ A merged array is one where the first half over the last axis represents the
469
+ real part of a complex array, while the second part represents the
470
+ imaginary.
471
+
472
+ Args:
473
+ x: The (complex) array.
474
+
475
+ Returns:
476
+ A merged array represented by `x`.
477
+ """
478
+ if self.config.only_real:
479
+ assert not isinstance(
480
+ x, recurrentgemma.complex_lib.Complex
481
+ ) and not jnp.iscomplexobj(x)
482
+ return x
483
+ else:
484
+ return jnp.concatenate([x.real, x.imag], axis=-1)
485
+
486
+ @nn.compact
487
+ def _cell(
488
+ self,
489
+ x: types.Sequence,
490
+ h: jax.Array,
491
+ segment_pos: jax.Array,
492
+ ) -> tuple[types.Sequence, jax.Array]:
493
+ mask = x.mask
494
+ x = x.values
495
+
496
+ width_output = (
497
+ self.config.units if self.config.only_real else self.config.units // 2
498
+ )
499
+ a_real_param = self.param(
500
+ 'a_param',
501
+ utils.shard_initializer(
502
+ _rnn_real_param_init(min_rad=self.config.min_rad, max_rad=0.999),
503
+ self.config.a_sharding,
504
+ ),
505
+ [width_output],
506
+ self.config.param_dtype,
507
+ )
508
+
509
+ a_imag_param = None
510
+ if not self.config.only_real:
511
+ a_imag_param = self.param(
512
+ 'a_imag_param',
513
+ utils.shard_initializer(
514
+ _rnn_imag_param_init(max_rad=0.1), self.config.a_sharding
515
+ ),
516
+ [width_output],
517
+ self.config.param_dtype,
518
+ )
519
+
520
+ if width_output % self.config.num_heads != 0:
521
+ raise ValueError(
522
+ 'The number of heads must divide the width of the output, but got'
523
+ f' {self.config.num_heads=} and {width_output=}.'
524
+ )
525
+ units_per_head = width_output // self.config.num_heads
526
+
527
+ input_gate = utils.FlaxEinsumDense(
528
+ '...hi,hij->...hj',
529
+ output_shape=(self.config.num_heads, units_per_head),
530
+ bias_axes='hj',
531
+ kernel_init=nn.initializers.variance_scaling(
532
+ scale=self.config.gate_kernel_variance_scale,
533
+ mode='fan_in',
534
+ distribution='normal',
535
+ ),
536
+ kernel_sharding=self.config.gate_kernel_sharding,
537
+ bias_sharding=self.config.gate_bias_sharding,
538
+ compute_dtype=self.config.compute_dtype,
539
+ param_dtype=self.config.param_dtype,
540
+ name='input_gate',
541
+ )
542
+ a_gate = utils.FlaxEinsumDense(
543
+ '...hi,hij->...hj',
544
+ output_shape=(self.config.num_heads, units_per_head),
545
+ bias_axes='hj',
546
+ kernel_init=nn.initializers.variance_scaling(
547
+ scale=self.config.gate_kernel_variance_scale,
548
+ mode='fan_in',
549
+ distribution='normal',
550
+ ),
551
+ kernel_sharding=self.config.gate_kernel_sharding,
552
+ bias_sharding=self.config.gate_bias_sharding,
553
+ compute_dtype=self.config.compute_dtype,
554
+ param_dtype=self.config.param_dtype,
555
+ name='a_gate',
556
+ )
557
+
558
+ x, a_real_param, a_imag_param = nn.dtypes.promote_dtype(
559
+ x,
560
+ a_real_param,
561
+ a_imag_param,
562
+ dtype=self.config.compute_dtype,
563
+ )
564
+
565
+ # Group x into heads.
566
+ x_heads = einops.rearrange(
567
+ x, '... (h i) -> ... h i', h=self.config.num_heads
568
+ )
569
+
570
+ # Compute input and `A` gates.
571
+ gate_x = recurrentgemma.complex_lib.sigmoid(input_gate(x_heads))
572
+ gate_x = einops.rearrange(
573
+ gate_x, '... h j -> ... (h j)', h=self.config.num_heads
574
+ )
575
+
576
+ gate_a = recurrentgemma.complex_lib.sigmoid(a_gate(x_heads))
577
+ gate_a = einops.rearrange(
578
+ gate_a, '... h j -> ... (h j)', h=self.config.num_heads
579
+ )
580
+
581
+ # Compute the parameter `A` of the recurrence.
582
+ log_a_real = (
583
+ -8.0 * gate_a * recurrentgemma.complex_lib.softplus(a_real_param)
584
+ )
585
+
586
+ if self.config.only_real:
587
+ a = recurrentgemma.complex_lib.exp(log_a_real)
588
+ else:
589
+ log_a_imag = a_imag_param * gate_a
590
+ log_a_complex = self.real_imag_complex(log_a_real, log_a_imag)
591
+ a = recurrentgemma.complex_lib.exp(log_a_complex)
592
+
593
+ # Since A = |A| e^(i*θ), log A = log |A| + i*θ.
594
+ # Real(log A) = log |A| therefore |A|^2 = e^(2*Real(log A))
595
+ mag_a_squared = recurrentgemma.complex_lib.exp(2 * log_a_real)
596
+
597
+ x = self.merged_to_complex(x)
598
+
599
+ assert h.dtype == jnp.float32, h.dtype
600
+ h = self.merged_to_complex(h)
601
+
602
+ # Gate the input.
603
+ gated_x = x * gate_x
604
+
605
+ # Apply gamma normalization to the input. We need to clip the derivatives of
606
+ # `sqrt` in order to prevent NaNs during training in bfloat16.
607
+ reset = (segment_pos == 0).astype(a)
608
+ multiplier = recurrentgemma.layers.sqrt_bound_derivative(
609
+ 1 - mag_a_squared, max_gradient=1000
610
+ )
611
+ multiplier = (
612
+ reset[..., jnp.newaxis] + (1 - reset)[..., jnp.newaxis] * multiplier
613
+ )
614
+ normalized_x = gated_x * multiplier.astype(gated_x.dtype)
615
+
616
+ # TODO(b/398200724): Add masking support to the scan and skip state updates
617
+ # on invalid timesteps.
618
+ y, h = recurrentgemma.scan.linear_scan(
619
+ x=normalized_x,
620
+ a=a * (1 - reset[..., jnp.newaxis]),
621
+ h0=h,
622
+ scan_type=self._scan_type,
623
+ sharding_spec=self.config.scan_sharding,
624
+ unroll=128,
625
+ )
626
+
627
+ y = self.complex_to_merged(y)
628
+ h = self.complex_to_merged(h)
629
+ assert h.dtype == jnp.float32, h.dtype
630
+ return types.Sequence(y, mask), h
631
+
632
+ @types.check_step
633
+ def step(
634
+ self,
635
+ x: types.Sequence,
636
+ state: types.State,
637
+ *,
638
+ training: bool,
639
+ constants: types.Constants | None = None,
640
+ ) -> tuple[types.Sequence, types.State]:
641
+ h, start_index = state
642
+ segment_pos = (
643
+ start_index[:, jnp.newaxis] + jnp.arange(x.shape[1])[jnp.newaxis, :]
644
+ )
645
+ y, h = self._cell(x, h, segment_pos)
646
+ return y, (h, start_index + x.shape[1])
647
+
648
+ @types.check_layer
649
+ def layer(
650
+ self,
651
+ x: types.Sequence,
652
+ *,
653
+ training: bool,
654
+ constants: types.Constants | None = None,
655
+ ) -> types.Sequence:
656
+ segment_pos = jnp.arange(x.shape[1])[jnp.newaxis, :]
657
+ h, _ = self.get_initial_state(
658
+ x.shape[0], x.channel_spec, training=training, constants=constants
659
+ )
660
+ y, _ = self._cell(x, h, segment_pos)
661
+ return y
662
+
663
+ def get_initial_state(
664
+ self,
665
+ batch_size: int,
666
+ input_spec: types.ShapeDType,
667
+ *,
668
+ training: bool,
669
+ constants: types.Constants | None = None,
670
+ ) -> types.State:
671
+ # Always use float32 for the state, regardless of the input dtype.
672
+ h = jnp.zeros((batch_size, self.config.units), dtype=jnp.float32)
673
+ start_index = jnp.zeros([batch_size], jnp.int32)
674
+ return h, start_index
@@ -0,0 +1,48 @@
1
+ # Copyright 2025 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
+ """Sharding utilities."""
15
+
16
+ from typing import Sequence
17
+
18
+ import jax
19
+
20
+ UNCONSTRAINED = jax.sharding.PartitionSpec.UNCONSTRAINED
21
+ DimSharding = str | Sequence[str] | None | type(UNCONSTRAINED)
22
+ Sharding = Sequence[DimSharding] | None
23
+
24
+ use_mesh = jax.sharding.use_mesh
25
+
26
+
27
+ def shard(x: jax.Array, s: Sharding) -> jax.Array:
28
+ """Annotates x with the provided sharding.
29
+
30
+ Args:
31
+ x: The array to annotate.
32
+ s: The sharding to apply.
33
+
34
+ Returns:
35
+ The array with sharding constraints applied.
36
+ """
37
+ abstract_mesh = jax.sharding.get_abstract_mesh()
38
+
39
+ if s is None or abstract_mesh is None:
40
+ return x
41
+
42
+ x = jax.lax.with_sharding_constraint(
43
+ x,
44
+ jax.sharding.NamedSharding(
45
+ abstract_mesh, jax.sharding.PartitionSpec(*s)
46
+ ),
47
+ )
48
+ return x