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,447 @@
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
+ """Dense layers."""
15
+
16
+ import dataclasses
17
+ import typing
18
+ from typing import Callable
19
+
20
+ import flax.linen as nn
21
+ import jax
22
+ import jax.numpy as jnp
23
+ from sequence_layers.jax import meta
24
+ from sequence_layers.jax import types
25
+ from sequence_layers.jax import utils
26
+
27
+
28
+ __all__ = (
29
+ # go/keep-sorted start
30
+ 'Dense',
31
+ 'DenseShaped',
32
+ 'EinsumDense',
33
+ # go/keep-sorted end
34
+ )
35
+
36
+
37
+ class Dense(types.Stateless, utils.EinsumCommon):
38
+ """A basic dense layer."""
39
+
40
+ @dataclasses.dataclass(frozen=True)
41
+ class Config(types.SequenceLayerConfig):
42
+ """Dense config."""
43
+ # The number of output features for the dense layer.
44
+ features: int
45
+ # Whether to use a bias.
46
+ use_bias: bool = True
47
+ # An optional activation to apply after the dense layer.
48
+ activation: Callable[[jax.Array], jax.Array] | None = None
49
+ # The dtype to use for layer compute.
50
+ compute_dtype: types.DType | None = None
51
+ # The dtype to use for layer parameters.
52
+ param_dtype: types.DType = jnp.float32
53
+ # An optional precision to use for the einsum.
54
+ precision: nn.linear.PrecisionLike = None
55
+ # Initializer for the kernel.
56
+ kernel_init: nn.initializers.Initializer = nn.linear.default_kernel_init
57
+ # Optional sharding for the kernel. Any axes that are present in the input
58
+ # spec are marked as FANIN.
59
+ kernel_sharding: types.Sharding | None = None
60
+ # Initializer for the bias, if used and not gated by another config option.
61
+ bias_init: nn.initializers.Initializer = nn.initializers.zeros_init()
62
+ # Optional sharding for the bias.
63
+ bias_sharding: types.Sharding | None = None
64
+ # Optional callable that returns a jnp.einsum-compatible function to use
65
+ # instead of jnp.einsum. For example, to enable quantization aware training.
66
+ einsum_factory: types.EinsumFactoryT | None = None
67
+ # Optional name for the layer.
68
+ name: str | None = None
69
+
70
+ def make(self) -> 'Dense':
71
+ return Dense(self, name=self.name)
72
+
73
+ config: Config
74
+
75
+ @nn.nowrap
76
+ def get_output_dtype(self, input_dtype: types.DType) -> types.DType:
77
+ return utils.get_promoted_dtype(
78
+ input_dtype, self.config.param_dtype, dtype=self.config.compute_dtype
79
+ )
80
+
81
+ @nn.nowrap
82
+ def get_output_shape(
83
+ self,
84
+ input_shape: types.ShapeLike,
85
+ constants: types.Constants | None = None,
86
+ ) -> types.Shape:
87
+ del constants
88
+ if not input_shape:
89
+ raise ValueError(
90
+ f'Dense requires at least rank 3 input. Got: {input_shape=}'
91
+ )
92
+ return tuple(input_shape[:-1]) + (self.config.features,)
93
+
94
+ @nn.compact
95
+ @types.check_layer
96
+ def layer(
97
+ self,
98
+ x: types.Sequence,
99
+ training: bool,
100
+ constants: types.Constants | None = None,
101
+ ) -> types.Sequence:
102
+ del constants
103
+
104
+ if x.ndim < 3:
105
+ raise ValueError(f'Dense requires at least rank 3 input. Got: {x.shape=}')
106
+
107
+ # Preserve masked state if no bias or activation are in use.
108
+ apply_fn = (
109
+ x.apply_values
110
+ if self.config.use_bias or self.config.activation is not None
111
+ else x.apply_values_masked
112
+ )
113
+
114
+ return apply_fn(
115
+ self.einsum,
116
+ '...a,ab->...b',
117
+ (x.shape[-1], self.config.features),
118
+ bias_shape=(self.config.features,) if self.config.use_bias else None,
119
+ activation=self.config.activation,
120
+ compute_dtype=self.config.compute_dtype,
121
+ param_dtype=self.config.param_dtype,
122
+ precision=self.config.precision,
123
+ kernel_init=self.config.kernel_init,
124
+ kernel_sharding=self.config.kernel_sharding,
125
+ bias_init=self.config.bias_init,
126
+ bias_sharding=self.config.bias_sharding,
127
+ projectable=True,
128
+ axes_types=(meta.AxisType.FANIN, None),
129
+ einsum_factory=self.config.einsum_factory,
130
+ )
131
+
132
+
133
+ class DenseShaped(types.Stateless, utils.EinsumCommon):
134
+ """A dense layer that transforms the channel shape."""
135
+
136
+ @dataclasses.dataclass(frozen=True)
137
+ class Config(types.SequenceLayerConfig):
138
+ """DenseShaped config."""
139
+
140
+ # The expected shape of the output tensor (excluding the batch and time
141
+ # dimension).
142
+ output_shape: types.ShapeLike
143
+ # Whether to use a bias, with shape imputed from `output_shape`.
144
+ use_bias: bool = True
145
+ # An optional activation to apply after the dense layer.
146
+ activation: Callable[[jax.Array], jax.Array] | None = None
147
+ # The dtype to use for layer compute.
148
+ compute_dtype: types.DType | None = None
149
+ # The dtype to use for layer parameters.
150
+ param_dtype: types.DType = jnp.float32
151
+ # An optional precision to use for the einsum.
152
+ precision: nn.linear.PrecisionLike = None
153
+ # Initializer for the kernel.
154
+ kernel_init: nn.initializers.Initializer = nn.linear.default_kernel_init
155
+ # Optional sharding for the kernel. Any axes that are present in the input
156
+ # spec are marked as FANIN.
157
+ kernel_sharding: types.Sharding | None = None
158
+ # Initializer for the bias, if used and not gated by another config option.
159
+ bias_init: nn.initializers.Initializer = nn.initializers.zeros_init()
160
+ # Optional sharding for the bias.
161
+ bias_sharding: types.Sharding | None = None
162
+ # Optional name for the layer.
163
+ name: str | None = None
164
+
165
+ def __post_init__(self):
166
+ # Use hashable types for sequences.
167
+ object.__setattr__(self, 'output_shape', tuple(self.output_shape))
168
+
169
+ def make(self) -> 'DenseShaped':
170
+ return DenseShaped(self, name=self.name)
171
+
172
+ config: Config
173
+
174
+ @nn.nowrap
175
+ def get_output_dtype(self, input_dtype: types.DType) -> types.DType:
176
+ return utils.get_promoted_dtype(
177
+ input_dtype, self.config.param_dtype, dtype=self.config.compute_dtype
178
+ )
179
+
180
+ @nn.nowrap
181
+ def get_output_shape(
182
+ self,
183
+ input_shape: types.ShapeLike,
184
+ constants: types.Constants | None = None,
185
+ ) -> types.Shape:
186
+ del constants
187
+ return tuple(self.config.output_shape)
188
+
189
+ @nn.compact
190
+ @types.check_layer
191
+ def layer(
192
+ self,
193
+ x: types.Sequence,
194
+ training: bool,
195
+ constants: types.Constants | None = None,
196
+ ) -> types.Sequence:
197
+ del constants
198
+
199
+ input_channel_shape = x.channel_shape
200
+ output_channel_shape = tuple(self.config.output_shape)
201
+
202
+ input_einsum_dims = ''.join(
203
+ [chr(ord('a') + i) for i in range(len(input_channel_shape))]
204
+ )
205
+ output_einsum_dims = ''.join([
206
+ chr(ord('a') + i + len(input_channel_shape))
207
+ for i in range(len(output_channel_shape))
208
+ ])
209
+ input_kernel_shape = input_channel_shape
210
+ input_weight_dims = input_einsum_dims
211
+ if not input_weight_dims:
212
+ input_kernel_shape = (1,)
213
+ input_weight_dims = 'I'
214
+ output_kernel_shape = output_channel_shape
215
+ output_weight_dims = output_einsum_dims
216
+ if not output_weight_dims:
217
+ output_kernel_shape = (1,)
218
+ output_weight_dims = 'O'
219
+
220
+ equation = f'BT{input_einsum_dims},{input_weight_dims}{output_weight_dims}->BT{output_einsum_dims}'
221
+ kernel_shape = input_kernel_shape + output_kernel_shape
222
+ axes_types = (meta.AxisType.FANIN,) * len(input_kernel_shape) + (
223
+ None,
224
+ ) * len(output_kernel_shape)
225
+
226
+ # Preserve masked state if no bias or activation are in use.
227
+ apply_fn = (
228
+ x.apply_values
229
+ if self.config.use_bias or self.config.activation is not None
230
+ else x.apply_values_masked
231
+ )
232
+
233
+ return apply_fn(
234
+ self.einsum,
235
+ equation,
236
+ kernel_shape,
237
+ bias_shape=output_kernel_shape if self.config.use_bias else None,
238
+ activation=self.config.activation,
239
+ compute_dtype=self.config.compute_dtype,
240
+ param_dtype=self.config.param_dtype,
241
+ precision=self.config.precision,
242
+ kernel_init=self.config.kernel_init,
243
+ kernel_sharding=self.config.kernel_sharding,
244
+ bias_init=self.config.bias_init,
245
+ bias_sharding=self.config.bias_sharding,
246
+ projectable=True,
247
+ axes_types=axes_types,
248
+ )
249
+
250
+
251
+ class EinsumDense(types.Stateless, utils.EinsumCommon):
252
+ """A dense layer that transforms the channel shape with an einsum equation.
253
+
254
+ Equation input and output specs must have leading ellipses to broadcast over
255
+ the batch and time dimension.
256
+
257
+ Example:
258
+
259
+ Input sequence: [b, t, c1, c2, c3]
260
+ - equation = '...abc,bd->...bd'
261
+ - output_shape = [None, c4]
262
+ - bias_axes = 'd'
263
+ Output sequence: [b, t, c2, c4]
264
+
265
+ Kernel shape: [c2, c4]
266
+ Bias shape: [c4]
267
+
268
+ Interpretation: Every [c1, c2, c3] tensor per timestep is transformed with the
269
+ einsum formula abc,bd->bd.
270
+ """
271
+
272
+ @dataclasses.dataclass(frozen=True)
273
+ class Config(types.SequenceLayerConfig):
274
+ """EinsumDense config."""
275
+
276
+ # An equation describing the einsum to perform. This equation must be a
277
+ # valid einsum string of the form `...ab,bc->...ac`, or where 'ab', 'bc',
278
+ # and 'ac' can be any valid einsum axis expression sequence.
279
+ equation: str
280
+ # The expected shape of the output tensor (excluding the batch and time
281
+ # dimension). You can specify None for any dimension that should be inferred
282
+ # from the input shape.
283
+ output_shape: list[int | None] | tuple[int | None, ...]
284
+ # A string containing the output dimension(s) to apply a bias to. Each
285
+ # character in the `bias_axes` string should correspond to a character in
286
+ # the output portion of the `equation` string.
287
+ bias_axes: str = ''
288
+
289
+ # An optional activation to apply after the dense layer.
290
+ activation: Callable[[jax.Array], jax.Array] | None = None
291
+ # The dtype to use for layer compute.
292
+ compute_dtype: types.DType | None = None
293
+ # The dtype to use for layer parameters.
294
+ param_dtype: types.DType = jnp.float32
295
+ # An optional precision to use for the einsum.
296
+ precision: nn.linear.PrecisionLike = None
297
+ # Initializer for the kernel.
298
+ kernel_init: nn.initializers.Initializer = nn.linear.default_kernel_init
299
+ # Optional sharding for the kernel. Any axes that are present in the input
300
+ # spec are marked as FANIN.
301
+ kernel_sharding: types.Sharding | None = None
302
+ # Initializer for the bias, if used and not gated by another config option.
303
+ bias_init: nn.initializers.Initializer = nn.initializers.zeros_init()
304
+ # Optional sharding for the bias.
305
+ bias_sharding: types.Sharding | None = None
306
+ # Optional name for the layer.
307
+ name: str | None = None
308
+
309
+ def __post_init__(self):
310
+ # Use hashable types for sequences.
311
+ object.__setattr__(self, 'output_shape', tuple(self.output_shape))
312
+
313
+ def make(self) -> 'EinsumDense':
314
+ return EinsumDense(self, name=self.name)
315
+
316
+ config: Config
317
+
318
+ @nn.nowrap
319
+ def _parse_and_validate_equation(self, equation) -> tuple[str, str, str]:
320
+ if '->' not in equation:
321
+ raise ValueError(f'equation is not valid for EinsumDense: {equation}')
322
+ left, output_spec = equation.split('->')
323
+ input_spec, kernel_spec = left.split(',')
324
+ if not input_spec.startswith('...') or not output_spec.startswith('...'):
325
+ raise ValueError('Equation must be of the form "...X,Y->...Z".')
326
+ if 3 + len(set(input_spec[3:])) != len(input_spec):
327
+ raise ValueError(
328
+ f'Equation {input_spec=} must not contain duplicate variables.'
329
+ )
330
+
331
+ if 3 + len(set(output_spec[3:])) != len(output_spec):
332
+ raise ValueError(
333
+ f'Equation {output_spec=} must not contain duplicate variables.'
334
+ )
335
+ return input_spec, kernel_spec, output_spec
336
+
337
+ @nn.nowrap
338
+ def _get_and_validate_output_shape(
339
+ self,
340
+ input_shape: types.ShapeLike,
341
+ ) -> types.Shape:
342
+ input_spec, _, output_spec = self._parse_and_validate_equation(
343
+ self.config.equation
344
+ )
345
+ assert input_spec.startswith('...')
346
+ assert output_spec.startswith('...')
347
+ # Trim '...' off.
348
+ input_spec, output_spec = input_spec[3:], output_spec[3:]
349
+
350
+ if len(input_spec) != len(input_shape):
351
+ raise ValueError(
352
+ f'Equation {input_spec=} does not match {input_shape=} rank.'
353
+ )
354
+
355
+ input_dims = {d: input_shape[i] for i, d in enumerate(input_spec)}
356
+ assert len(input_dims) == len(input_spec)
357
+
358
+ output_shape = list(self.config.output_shape)
359
+ if len(output_spec) != len(output_shape):
360
+ raise ValueError(
361
+ f'Equation {output_spec=} does not match {output_shape=}.'
362
+ )
363
+
364
+ for i, d in enumerate(output_spec):
365
+ if output_shape[i] is None:
366
+ output_shape[i] = input_dims[d]
367
+ elif d in input_dims and output_shape[i] != input_dims[d]:
368
+ raise ValueError(
369
+ 'Input shape and output shape inconsistent for dimension '
370
+ f'{d=}. {output_shape=} {input_shape=}'
371
+ )
372
+ return typing.cast(types.Shape, tuple(output_shape))
373
+
374
+ @nn.nowrap
375
+ def get_output_dtype(self, input_dtype: types.DType) -> types.DType:
376
+ return utils.get_promoted_dtype(
377
+ input_dtype, self.config.param_dtype, dtype=self.config.compute_dtype
378
+ )
379
+
380
+ @nn.nowrap
381
+ def get_output_shape(
382
+ self,
383
+ input_shape: types.ShapeLike,
384
+ constants: types.Constants | None = None,
385
+ ) -> types.Shape:
386
+ del constants
387
+ return self._get_and_validate_output_shape(input_shape)
388
+
389
+ @nn.compact
390
+ @types.check_layer
391
+ def layer(
392
+ self,
393
+ x: types.Sequence,
394
+ training: bool,
395
+ constants: types.Constants | None = None,
396
+ ) -> types.Sequence:
397
+ del constants
398
+ input_spec, kernel_spec, output_spec = self._parse_and_validate_equation(
399
+ self.config.equation
400
+ )
401
+ assert input_spec.startswith('...')
402
+ assert output_spec.startswith('...')
403
+ # Trim '...' off.
404
+ input_spec, output_spec = input_spec[3:], output_spec[3:]
405
+
406
+ input_shape = x.shape
407
+ output_shape = self._get_and_validate_output_shape(x.channel_shape)
408
+
409
+ kernel_shape, bias_shape, _ = utils.einsum_analyze_split_string(
410
+ (input_spec, kernel_spec, output_spec),
411
+ self.config.bias_axes,
412
+ input_shape,
413
+ output_shape,
414
+ left_elided=True,
415
+ )
416
+
417
+ axes_types = []
418
+ input_only_dims = {dim for dim in input_spec if dim not in set(output_spec)}
419
+ for dim in kernel_spec:
420
+ if dim in input_only_dims:
421
+ axes_types.append(meta.AxisType.FANIN)
422
+ else:
423
+ axes_types.append(None)
424
+
425
+ # Preserve masked state if no bias or activation are in use.
426
+ apply_fn = (
427
+ x.apply_values
428
+ if self.config.bias_axes or self.config.activation is not None
429
+ else x.apply_values_masked
430
+ )
431
+
432
+ return apply_fn(
433
+ self.einsum,
434
+ self.config.equation,
435
+ kernel_shape,
436
+ bias_shape,
437
+ activation=self.config.activation,
438
+ compute_dtype=self.config.compute_dtype,
439
+ param_dtype=self.config.param_dtype,
440
+ precision=self.config.precision,
441
+ kernel_init=self.config.kernel_init,
442
+ kernel_sharding=self.config.kernel_sharding,
443
+ bias_init=self.config.bias_init,
444
+ bias_sharding=self.config.bias_sharding,
445
+ projectable=True,
446
+ axes_types=axes_types,
447
+ )