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,511 @@
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
+ """Conditioning layers."""
15
+
16
+ import abc
17
+ import dataclasses
18
+ import enum
19
+
20
+ import flax.linen as nn
21
+ import jax
22
+ import jax.numpy as jnp
23
+ from sequence_layers.jax import dense
24
+ from sequence_layers.jax import types
25
+ from sequence_layers.jax import utils
26
+
27
+
28
+ __all__ = (
29
+ # go/keep-sorted start
30
+ 'Conditioning',
31
+ # go/keep-sorted end
32
+ )
33
+
34
+
35
+ def _get_conditioning(
36
+ layer: types.SequenceLayer,
37
+ conditioning_name: str,
38
+ constants: types.Constants | None,
39
+ ) -> jax.Array | types.Sequence:
40
+ """Gets the conditioning from constants and does basic validation."""
41
+ if constants is None:
42
+ raise ValueError(
43
+ f'{layer} requires the conditioning to be provided via '
44
+ f'constants, got: {constants}'
45
+ )
46
+ conditioning = constants.get(conditioning_name)
47
+ if conditioning is None:
48
+ raise ValueError(
49
+ f'{layer} expected {conditioning_name} to be present in '
50
+ f'constants, got: {constants}'
51
+ )
52
+ elif not isinstance(conditioning, types.ARRAY_LIKE_TYPES) and not isinstance(
53
+ conditioning, types.Sequence
54
+ ):
55
+ raise ValueError(
56
+ f'Unexpected conditioning "{conditioning_name}" having '
57
+ f'type: {type(conditioning)}: {conditioning=}'
58
+ )
59
+
60
+ return conditioning
61
+
62
+
63
+ class BaseConditioning(
64
+ types.PreservesType, types.SequenceLayer, metaclass=abc.ABCMeta
65
+ ):
66
+ """Base class for conditioning types."""
67
+
68
+ @enum.unique
69
+ class Projection(enum.Enum):
70
+ """The type of projection to perform."""
71
+
72
+ # No projection.
73
+ IDENTITY = 1
74
+ # Dense projection from every element of c at a given time step, to a tensor
75
+ # of the same shape as x at given time step (c.channel_shape.num_elements()
76
+ # to x.channel_shape.num_elements()).
77
+ LINEAR = 2
78
+ # Dense projection from every element of c at a given time step, to a tensor
79
+ # of shape [2, x.shape...] at given time step (
80
+ # c.channel_shape.num_elements() to 2 * x.channel_shape.num_elements()).
81
+ LINEAR_AFFINE = 3
82
+
83
+ @enum.unique
84
+ class Combination(enum.Enum):
85
+ """The type of combination to perform."""
86
+
87
+ # Broadcast-add conditioning.
88
+ ADD = 1
89
+ # Broadcast-concat conditioning.
90
+ CONCAT = 2
91
+ # Affine conditioning. Requires LINEAR_AFFINE projection.
92
+ AFFINE = 3
93
+ # Affine shift conditioning. Requires LINEAR projection.
94
+ AFFINE_SHIFT = 4
95
+ # Affine scale conditioning. Requires LINEAR projection.
96
+ AFFINE_SCALE = 5
97
+ # Broadcast-multiply conditioning. Requires LINEAR or IDENTITY projection.
98
+ MUL = 6
99
+ # Broadcast-concat conditioning via prepending.
100
+ CONCAT_BEFORE = 7
101
+
102
+ def _projected_condition_shape(
103
+ self, input_shape: types.Shape, condition_shape: types.Shape
104
+ ) -> types.Shape:
105
+ projection_channel_shape = self._projection_channel_shape
106
+ if projection_channel_shape is None:
107
+ projection_channel_shape = input_shape
108
+
109
+ match self._projection:
110
+ case self.Projection.IDENTITY:
111
+ return condition_shape
112
+ case self.Projection.LINEAR:
113
+ return projection_channel_shape
114
+ case self.Projection.LINEAR_AFFINE:
115
+ return (2,) + projection_channel_shape
116
+ case _:
117
+ raise ValueError(f'Unsupported projection: {self._projection}')
118
+
119
+ def _get_conditioning_channel_shape(
120
+ self,
121
+ constants: types.Constants | None,
122
+ ) -> types.Shape:
123
+ conditioning = _get_conditioning(self, self._conditioning_name, constants)
124
+ if isinstance(conditioning, types.Sequence):
125
+ return conditioning.channel_shape
126
+ else:
127
+ return conditioning.shape[1:]
128
+
129
+ @property
130
+ @abc.abstractmethod
131
+ def _conditioning_name(self) -> str:
132
+ pass
133
+
134
+ @property
135
+ @abc.abstractmethod
136
+ def _projection(self) -> Projection:
137
+ pass
138
+
139
+ @property
140
+ @abc.abstractmethod
141
+ def _projection_channel_shape(self) -> types.Shape | None:
142
+ pass
143
+
144
+ @property
145
+ @abc.abstractmethod
146
+ def _combination(self) -> Combination:
147
+ pass
148
+
149
+ @property
150
+ @abc.abstractmethod
151
+ def _compute_dtype(self) -> types.DType | None:
152
+ pass
153
+
154
+ @property
155
+ @abc.abstractmethod
156
+ def _param_dtype(self) -> types.DType:
157
+ pass
158
+
159
+ @property
160
+ @abc.abstractmethod
161
+ def affine_scale_offset(self) -> complex:
162
+ pass
163
+
164
+ @property
165
+ @abc.abstractmethod
166
+ def _kernel_init(self) -> nn.initializers.Initializer:
167
+ pass
168
+
169
+ @property
170
+ @abc.abstractmethod
171
+ def _kernel_sharding(self) -> types.Sharding | None:
172
+ pass
173
+
174
+ @property
175
+ @abc.abstractmethod
176
+ def _bias_init(self) -> nn.initializers.Initializer:
177
+ pass
178
+
179
+ @property
180
+ @abc.abstractmethod
181
+ def _bias_sharding(self) -> types.Sharding | None:
182
+ pass
183
+
184
+ def _validate(self):
185
+ if (
186
+ self._combination == self.Combination.AFFINE
187
+ and self._projection != self.Projection.LINEAR_AFFINE
188
+ ):
189
+ raise ValueError('AFFINE combination requires LINEAR_AFFINE projection.')
190
+ if (
191
+ self._combination == self.Combination.AFFINE_SHIFT
192
+ and self._projection != self.Projection.LINEAR
193
+ ):
194
+ raise ValueError('AFFINE_SHIFT combination requires LINEAR projection.')
195
+ if (
196
+ self._combination == self.Combination.AFFINE_SCALE
197
+ and self._projection != self.Projection.LINEAR
198
+ ):
199
+ raise ValueError('AFFINE_SCALE combination requires LINEAR projection.')
200
+ if (
201
+ self._combination != self.Combination.AFFINE
202
+ and self._projection == self.Projection.LINEAR_AFFINE
203
+ ):
204
+ raise ValueError('LINEAR_AFFINE projection requires AFFINE combination.')
205
+
206
+ def get_output_shape(
207
+ self,
208
+ input_shape: types.ShapeLike,
209
+ *,
210
+ constants: types.Constants | None = None,
211
+ ) -> types.Shape:
212
+ self._validate()
213
+ conditioning_channel_shape = self._get_conditioning_channel_shape(constants)
214
+ projected_conditioning_shape = self._projected_condition_shape(
215
+ input_shape, conditioning_channel_shape
216
+ )
217
+ match self._combination:
218
+ case (
219
+ self.Combination.ADD
220
+ | self.Combination.MUL
221
+ | self.Combination.AFFINE_SHIFT
222
+ | self.Combination.AFFINE_SCALE
223
+ ):
224
+ return jnp.broadcast_shapes(input_shape, projected_conditioning_shape)
225
+ case self.Combination.CONCAT | self.Combination.CONCAT_BEFORE:
226
+ input_inner_dim = input_shape[-1] if input_shape else 1
227
+ projected_conditioning_inner_dim = (
228
+ projected_conditioning_shape[-1]
229
+ if projected_conditioning_shape
230
+ else 1
231
+ )
232
+ output_inner_dim = input_inner_dim + projected_conditioning_inner_dim
233
+ output_outer_shape = jnp.broadcast_shapes(
234
+ input_shape[:-1], projected_conditioning_shape[:-1]
235
+ )
236
+ return output_outer_shape + (output_inner_dim,)
237
+ case self.Combination.AFFINE:
238
+ projected_conditioning_shape = projected_conditioning_shape[1:]
239
+ return jnp.broadcast_shapes(input_shape, projected_conditioning_shape)
240
+ case _:
241
+ raise ValueError(f'Unsupported combination: {self._combination}')
242
+
243
+ def _project_and_combine(
244
+ self, x: types.Sequence, conditioning: types.Sequence, training: bool
245
+ ):
246
+ return self._combine(x, self._project(x, conditioning, training))
247
+
248
+ @nn.compact
249
+ def _project(
250
+ self, x: types.Sequence, conditioning: types.Sequence, training: bool
251
+ ) -> types.Sequence:
252
+ self._validate()
253
+ projection_channel_shape = self._projection_channel_shape
254
+ if projection_channel_shape is None:
255
+ projection_channel_shape = x.channel_shape
256
+ match self._projection:
257
+ case self.Projection.IDENTITY:
258
+ return conditioning
259
+ case self.Projection.LINEAR:
260
+ return (
261
+ dense.DenseShaped.Config(
262
+ projection_channel_shape,
263
+ param_dtype=self._param_dtype,
264
+ compute_dtype=self._compute_dtype,
265
+ kernel_init=self._kernel_init,
266
+ kernel_sharding=self._kernel_sharding,
267
+ bias_init=self._bias_init,
268
+ bias_sharding=self._bias_sharding,
269
+ name='dense',
270
+ )
271
+ .make()
272
+ .layer(conditioning, training=training)
273
+ )
274
+ case self.Projection.LINEAR_AFFINE:
275
+ return (
276
+ dense.DenseShaped.Config(
277
+ (2,) + projection_channel_shape,
278
+ param_dtype=self._param_dtype,
279
+ compute_dtype=self._compute_dtype,
280
+ kernel_init=self._kernel_init,
281
+ kernel_sharding=self._kernel_sharding,
282
+ bias_init=self._bias_init,
283
+ bias_sharding=self._bias_sharding,
284
+ name='dense',
285
+ )
286
+ .make()
287
+ .layer(conditioning, training=training)
288
+ )
289
+ case _:
290
+ raise ValueError(f'Unsupported projection: {self._projection}')
291
+
292
+ @nn.nowrap
293
+ def _combine(
294
+ self, x: types.Sequence, conditioning: types.Sequence
295
+ ) -> types.Sequence:
296
+ self._validate()
297
+
298
+ def _affine_fn(x, conditioning):
299
+ scale, shift = utils.sequence_unstack(conditioning, axis=2)
300
+ scale = scale.apply_values(lambda v: v + self.affine_scale_offset)
301
+ return utils.sequence_broadcast_affine(x, scale, shift)
302
+
303
+ def _affine_scale_fn(x, conditioning):
304
+ scale = conditioning.apply_values(lambda v: v + self.affine_scale_offset)
305
+ return utils.sequence_broadcast_product(x, scale)
306
+
307
+ match self._combination:
308
+ case self.Combination.ADD:
309
+ combine_fn = utils.sequence_broadcast_add
310
+ case self.Combination.CONCAT:
311
+ combine_fn = utils.sequence_broadcast_concat
312
+ case self.Combination.CONCAT_BEFORE:
313
+ combine_fn = lambda x, c: utils.sequence_broadcast_concat(c, x)
314
+ case self.Combination.AFFINE:
315
+ combine_fn = _affine_fn
316
+ case self.Combination.AFFINE_SHIFT:
317
+ combine_fn = utils.sequence_broadcast_add
318
+ case self.Combination.AFFINE_SCALE:
319
+ combine_fn = _affine_scale_fn
320
+ case self.Combination.MUL:
321
+ combine_fn = utils.sequence_broadcast_product
322
+ case _:
323
+ raise ValueError(f'Unsupported combination: {self._combination}')
324
+ return combine_fn(x, conditioning)
325
+
326
+
327
+ def _tensor_to_fake_sequence(t: jax.Array) -> types.MaskedSequence:
328
+ batch_size = t.shape[0]
329
+ return types.MaskedSequence(
330
+ t[:, jnp.newaxis],
331
+ jnp.full([batch_size, 1], True),
332
+ )
333
+
334
+
335
+ class Conditioning(BaseConditioning):
336
+ """Conditions the sequence x on a conditioning sequence c.
337
+
338
+ Conditioning is done in a time-synchronized way, where each time step of x is
339
+ conditioned on the corresponding time step of c.
340
+
341
+ Conditioning is defined as Combine(x, Project(c)), where supported projection
342
+ and combination functions are available in Projection and Combination enums
343
+ above.
344
+
345
+ All valid broadcasts between x and c channel_shapes are supported, e.g.:
346
+ - Projection=IDENTITY, Combination=ADD:
347
+ - (x: [b, t_x, 3], c: [b, t_c, 3]) -> c_x: [b, t_x, 3]
348
+ - (x: [b, t_x, 3, 1, 5], c: [b, t_c, 2, 5]) -> c_x: [b, t_x, 3, 2, 5]
349
+ - Projection=IDENTITY, Combination=CONCAT:
350
+ - (x: [b, t_x, 3], c: [b, t_c, 7]) -> c_x: [b, t_x, 10]
351
+ - (x: [b, t_x, 3, 1, 5], c: [b, t_c, 2, 7]) -> c_x: [b, t_x, 3, 2, 12]
352
+ - Projection=LINEAR, Combination=ADD:
353
+ - (x: [b, t_x, 3], c: [b, t_c, 7]) -> c_x: [b, t_x, 3]
354
+ - (x: [b, t_x, 3, 1, 5], c: [b, t_c, 2, 7]) -> c_x: [b, t_x, 3, 1, 5]
355
+ - Projection=LINEAR, Combination=CONCAT:
356
+ - (x: [b, t_x, 3], c: [b, t_c, 7]) -> c_x: [b, t_x, 6]
357
+ - (x: [b, t_x, 3, 1, 5], c: [b, t_c, 2, 7]) -> c_x: [b, t_x, 3, 1, 10]
358
+
359
+ Where t_x = t_c. For t_x != t_c, see UpsampleConditioning.
360
+ TODO(rryan): Implement UpsampleConditioning.
361
+ """
362
+
363
+ @dataclasses.dataclass(frozen=True)
364
+ class Config(types.SequenceLayerConfig):
365
+ """Config for Conditioning."""
366
+
367
+ # The name of the conditioning sequence or array in the constants
368
+ # dictionary.
369
+ conditioning_name: str
370
+ # The type of projection to perform to project the conditioning before
371
+ # combination.
372
+ projection: BaseConditioning.Projection
373
+ # The type of combination to perform between the projected conditioning and
374
+ # the input sequence.
375
+ combination: BaseConditioning.Combination
376
+ # If projection is LINEAR or LINEAR_AFFINE, the channel shape to project the
377
+ # conditioning to. If unspecified, projects to the input sequence's channel
378
+ # shape.
379
+ projection_channel_shape: types.Shape | None = None
380
+ # If true, the conditioning sequence is expected to be streamed at the same
381
+ # block_size as the input sequence.
382
+ streaming: bool = False
383
+ # The dtype to use for layer compute.
384
+ compute_dtype: types.DType | None = None
385
+ # The dtype to use for layer parameters.
386
+ param_dtype: types.DType = jnp.float32
387
+ # Initializer for the kernel.
388
+ kernel_init: nn.initializers.Initializer = nn.linear.default_kernel_init
389
+ # Optional sharding for the kernel. Any axes that are present in the input
390
+ # spec are marked as FANIN.
391
+ kernel_sharding: types.Sharding | None = None
392
+ # Initializer for the bias, if used and not gated by another config option.
393
+ bias_init: nn.initializers.Initializer = nn.initializers.zeros_init()
394
+ # Optional sharding for the bias.
395
+ bias_sharding: types.Sharding | None = None
396
+ # An offset to add to the affine scale when `combination` is AFFINE or
397
+ # AFFINE_SCALE. Typically 1.0 is used with parameter initializations near 0,
398
+ # as this is close to an identity function and allows the network to learn
399
+ # residual scaling adjustments more easily.
400
+ affine_scale_offset: complex = 1.0
401
+ # An optional name for the layer.
402
+ name: str | None = None
403
+
404
+ def make(self) -> 'Conditioning':
405
+ return Conditioning(self, name=self.name)
406
+
407
+ config: Config
408
+
409
+ @property
410
+ def receptive_field_per_step(self) -> dict[int, types.ReceptiveField]:
411
+ return {0: (0, 0)}
412
+
413
+ @property
414
+ def _conditioning_name(self) -> str:
415
+ return self.config.conditioning_name
416
+
417
+ @property
418
+ def _projection(self) -> BaseConditioning.Projection:
419
+ return self.config.projection
420
+
421
+ @property
422
+ def _projection_channel_shape(self) -> types.Shape | None:
423
+ return self.config.projection_channel_shape
424
+
425
+ @property
426
+ def _combination(self) -> BaseConditioning.Combination:
427
+ return self.config.combination
428
+
429
+ @property
430
+ def _compute_dtype(self) -> types.DType | None:
431
+ return self.config.compute_dtype
432
+
433
+ @property
434
+ def _param_dtype(self) -> types.DType:
435
+ return self.config.param_dtype
436
+
437
+ @property
438
+ def affine_scale_offset(self) -> complex:
439
+ return self.config.affine_scale_offset
440
+
441
+ @property
442
+ def _kernel_init(self) -> nn.initializers.Initializer:
443
+ return self.config.kernel_init
444
+
445
+ @property
446
+ def _kernel_sharding(self) -> types.Sharding | None:
447
+ return self.config.kernel_sharding
448
+
449
+ @property
450
+ def _bias_init(self) -> nn.initializers.Initializer:
451
+ return self.config.bias_init
452
+
453
+ @property
454
+ def _bias_sharding(self) -> types.Sharding | None:
455
+ return self.config.bias_sharding
456
+
457
+ def get_initial_state(
458
+ self,
459
+ batch_size: int,
460
+ input_spec: types.ChannelSpec,
461
+ *,
462
+ training: bool,
463
+ constants: types.Constants | None = None,
464
+ ) -> types.State:
465
+ conditioning = _get_conditioning(self, self._conditioning_name, constants)
466
+ if isinstance(conditioning, types.Sequence) and not self.config.streaming:
467
+ return jnp.zeros([batch_size], jnp.int32)
468
+ else:
469
+ return ()
470
+
471
+ @types.check_layer
472
+ def layer(
473
+ self,
474
+ x: types.Sequence,
475
+ *,
476
+ training: bool,
477
+ constants: types.Constants | None = None,
478
+ ) -> types.Sequence:
479
+ conditioning = _get_conditioning(self, self._conditioning_name, constants)
480
+ if not isinstance(conditioning, types.Sequence):
481
+ conditioning = _tensor_to_fake_sequence(conditioning)
482
+ broadcasted_shape = jnp.broadcast_shapes(
483
+ x.shape[:2], conditioning.shape[:2]
484
+ )
485
+ utils.assert_is_compatible_with(x.shape[:2], broadcasted_shape)
486
+ return self._project_and_combine(x, conditioning, training)
487
+
488
+ @types.check_step
489
+ def step(
490
+ self,
491
+ x: types.Sequence,
492
+ state: types.State,
493
+ *,
494
+ training: bool,
495
+ constants: types.Constants | None = None,
496
+ ) -> tuple[types.Sequence, types.State]:
497
+ conditioning = _get_conditioning(self, self._conditioning_name, constants)
498
+ conditioning_batch_shape = conditioning.shape[:1]
499
+ if not isinstance(conditioning, types.Sequence):
500
+ conditioning = _tensor_to_fake_sequence(conditioning)
501
+ elif not self.config.streaming:
502
+ # If not streaming, time slice the conditioning.
503
+ time_index = state
504
+ step_size = x.shape[1]
505
+ conditioning = utils.batched_time_slice(
506
+ conditioning, time_index, step_size
507
+ )
508
+ state = time_index + step_size
509
+ utils.assert_is_compatible_with(x.shape[:1], conditioning_batch_shape)
510
+ conditioned_x = self._project_and_combine(x, conditioning, training)
511
+ return conditioned_x, state