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,462 @@
1
+ # Copyright 2023 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
+ """Pooling layers."""
15
+
16
+ import fractions
17
+ from typing import List, Optional, Tuple, Union
18
+
19
+ from sequence_layers.tensorflow import convolution
20
+ from sequence_layers.tensorflow import types
21
+ from sequence_layers.tensorflow import utils
22
+ import tensorflow.compat.v2 as tf
23
+
24
+
25
+ class BasePooling1D(types.SequenceLayer):
26
+ """A 1D pooling layer."""
27
+
28
+ def __init__(
29
+ self,
30
+ pool_layer: tf.keras.layers.Layer,
31
+ pool_size: int,
32
+ strides: int,
33
+ padding: str,
34
+ name=None,
35
+ ):
36
+ super().__init__(name=name)
37
+ if pool_size <= 0:
38
+ raise ValueError('pool_size must be positive, got: %d' % pool_size)
39
+ if strides <= 0:
40
+ raise ValueError('strides must be positive, got: %d' % strides)
41
+ self._pool_size = pool_size
42
+ self._strides = strides
43
+ self._padding = types.validate_padding(padding)
44
+ self._layer = pool_layer
45
+ self._buffer_width = self._pool_size - 1
46
+
47
+ @property
48
+ def supports_step(self) -> bool:
49
+ return self._padding == types.PaddingMode.CAUSAL.value
50
+
51
+ @property
52
+ def block_size(self) -> int:
53
+ return self._strides
54
+
55
+ @property
56
+ def output_ratio(self) -> fractions.Fraction:
57
+ return fractions.Fraction(1, self._strides)
58
+
59
+ def get_initial_state(
60
+ self, x: types.Sequence, constants: Optional[types.Constants] = None
61
+ ) -> types.State:
62
+ # Special case pool_size 1 since it is stateless.
63
+ if self._pool_size == 1:
64
+ return ()
65
+ # When executing a conv1d step-by-step, we need a buffer for tracking
66
+ # the current causal convolution window.
67
+ batch_size = utils.smart_dimension_size(x.values, 0)
68
+ return types.Sequence(
69
+ tf.zeros(
70
+ (batch_size, self._buffer_width, x.values.shape.dims[2].value),
71
+ dtype=x.values.dtype,
72
+ ),
73
+ tf.ones((batch_size, self._buffer_width), dtype=x.values.dtype),
74
+ )
75
+
76
+ def get_output_shape(
77
+ self,
78
+ input_shape: tf.TensorShape,
79
+ constants: Optional[types.Constants] = None,
80
+ ) -> tf.TensorShape:
81
+ if input_shape.rank != 1:
82
+ raise ValueError(
83
+ '1D pooling requires rank 3 input got: %s'
84
+ % tf.TensorShape([None, None]).concatenate(input_shape)
85
+ )
86
+ return input_shape
87
+
88
+ def _apply_pool(
89
+ self,
90
+ x: tf.Tensor,
91
+ explicit_padding: tuple[int, int],
92
+ ) -> tf.Tensor:
93
+ if explicit_padding[0] != 0 or explicit_padding[1] != 0:
94
+ x = tf.pad(x, ((0, 0), explicit_padding, (0, 0)))
95
+ return self._layer(x)
96
+
97
+ @tf.Module.with_name_scope
98
+ def step(
99
+ self,
100
+ x: types.Sequence,
101
+ state: types.State,
102
+ training: bool,
103
+ constants: Optional[types.Constants] = None,
104
+ ) -> Tuple[types.Sequence, types.State]:
105
+ # Special case pool_size 1 since it is stateless.
106
+ if self._pool_size == 1:
107
+ values = self._apply_pool(x.values, (0, 0))
108
+ mask = convolution.compute_conv_mask(
109
+ x.mask,
110
+ self._pool_size,
111
+ self._strides,
112
+ dilation_rate=1,
113
+ padding=self._padding,
114
+ )
115
+ return types.Sequence(values, mask).mask_invalid(), state
116
+
117
+ # Concatenate the new frames with the previous buffer_width frames.
118
+ state = state.concatenate(x)
119
+
120
+ # Compute the output for the current timestep.
121
+ values = self._apply_pool(state.values, (0, 0))
122
+ mask = convolution.compute_conv_mask(
123
+ state.mask,
124
+ self._pool_size,
125
+ self._strides,
126
+ dilation_rate=1,
127
+ padding=self._padding,
128
+ )
129
+
130
+ # Keep the last (pool_size - stride) frames for the next step.
131
+ state = state[:, -self._buffer_width :]
132
+
133
+ return types.Sequence(values, mask).mask_invalid(), state
134
+
135
+ @tf.Module.with_name_scope
136
+ def layer(
137
+ self,
138
+ x: types.Sequence,
139
+ training: bool,
140
+ initial_state: Optional[types.State] = None,
141
+ constants: Optional[types.Constants] = None,
142
+ ) -> types.Sequence:
143
+ explicit_padding = utils.convolution_explicit_padding(
144
+ self._padding,
145
+ self._pool_size,
146
+ dilation_rate=1,
147
+ )
148
+
149
+ values = self._apply_pool(x.values, explicit_padding)
150
+
151
+ # In causal mode, x.mask is padded and compute_conv_mask uses a VALID
152
+ # convolution. In SAME mode, x.mask is not padded, and compute_conv_mask
153
+ # uses a strided slice mask[:, ::time_stride].
154
+ if self._padding == types.PaddingMode.CAUSAL.value:
155
+ # We can't use convolutional padding here since its value is 0.0, not 1.0.
156
+ mask = tf.pad(
157
+ x.mask,
158
+ [[0, 0], [self._buffer_width, 0]],
159
+ mode='constant',
160
+ constant_values=1.0,
161
+ )
162
+ else:
163
+ mask = x.mask
164
+
165
+ mask = convolution.compute_conv_mask(
166
+ mask,
167
+ self._pool_size,
168
+ self._strides,
169
+ dilation_rate=1,
170
+ padding=self._padding,
171
+ )
172
+ return types.Sequence(values, mask).mask_invalid()
173
+
174
+
175
+ class MaxPooling1D(BasePooling1D):
176
+ """A 1D max pooling layer."""
177
+
178
+ @classmethod
179
+ def _default_name(cls):
180
+ """The default module name for this class."""
181
+ return 'max_pooling_1d'
182
+
183
+ def __init__(
184
+ self,
185
+ pool_size: int,
186
+ strides: int,
187
+ padding: str = 'causal',
188
+ name: Optional[str] = None,
189
+ ):
190
+ super().__init__(
191
+ # We perform padding outside of Keras.
192
+ tf.keras.layers.MaxPooling1D(pool_size, strides, padding='valid'),
193
+ pool_size,
194
+ strides,
195
+ padding,
196
+ name=name,
197
+ )
198
+
199
+
200
+ class AveragePooling1D(BasePooling1D):
201
+ """A 1D average pooling layer."""
202
+
203
+ @classmethod
204
+ def _default_name(cls):
205
+ """The default module name for this class."""
206
+ return 'average_pooling_1d'
207
+
208
+ def __init__(
209
+ self,
210
+ pool_size: int,
211
+ strides: int,
212
+ padding: str = 'causal',
213
+ name: Optional[str] = None,
214
+ ):
215
+ super().__init__(
216
+ # We perform padding outside of Keras.
217
+ tf.keras.layers.AveragePooling1D(pool_size, strides, padding='valid'),
218
+ pool_size,
219
+ strides,
220
+ padding,
221
+ name=name,
222
+ )
223
+
224
+
225
+ class BasePooling2D(types.SequenceLayer):
226
+ """A 2D pooling layer."""
227
+
228
+ def __init__(
229
+ self,
230
+ pool_layer: tf.keras.layers.Layer,
231
+ pool_size: Union[int, List[int], Tuple[int, int]],
232
+ strides: Union[int, List[int], Tuple[int, int]],
233
+ time_padding: str,
234
+ spatial_padding: str,
235
+ name=None,
236
+ ):
237
+ super().__init__(name=name)
238
+
239
+ def normalize_2tuple(
240
+ x: Union[int, List[int], Tuple[int, int]]
241
+ ) -> Tuple[int, int]:
242
+ if isinstance(x, int):
243
+ return (x, x)
244
+ result = tuple(x)
245
+ if len(result) != 2:
246
+ raise ValueError('Expected a 2-element iterable, got: %r' % x)
247
+ return result
248
+
249
+ self._pool_size = normalize_2tuple(pool_size)
250
+ self._strides = normalize_2tuple(strides)
251
+ if any(pool_size <= 0 for pool_size in self._pool_size):
252
+ raise ValueError('pool_size must be positive, got: %s' % self._pool_size)
253
+ if any(stride <= 0 for stride in self._strides):
254
+ raise ValueError('strides must be positive, got: %s' % self._strides)
255
+ self._time_padding = types.validate_padding(time_padding)
256
+ self._spatial_padding = types.validate_padding(spatial_padding)
257
+ self._layer = pool_layer
258
+ self._buffer_width = self._pool_size[0] - 1
259
+
260
+ @property
261
+ def supports_step(self) -> bool:
262
+ return self._time_padding == types.PaddingMode.CAUSAL.value
263
+
264
+ @property
265
+ def block_size(self) -> int:
266
+ return self._strides[0]
267
+
268
+ @property
269
+ def output_ratio(self) -> fractions.Fraction:
270
+ return fractions.Fraction(1, self._strides[0])
271
+
272
+ def get_initial_state(
273
+ self, x: types.Sequence, constants: Optional[types.Constants] = None
274
+ ) -> types.State:
275
+ # Special case pool_size 1 since it is stateless.
276
+ if self._pool_size[0] == 1:
277
+ return ()
278
+ # When executing a conv1d step-by-step, we need a buffer for tracking
279
+ # the current causal pooling window.
280
+ batch_size = utils.smart_dimension_size(x.values, 0)
281
+ return types.Sequence(
282
+ tf.zeros(
283
+ (
284
+ batch_size,
285
+ self._buffer_width,
286
+ x.values.shape.dims[2].value,
287
+ x.values.shape.dims[3].value,
288
+ ),
289
+ dtype=x.values.dtype,
290
+ ),
291
+ tf.ones((batch_size, self._buffer_width), dtype=x.mask.dtype),
292
+ )
293
+
294
+ def get_output_shape(
295
+ self,
296
+ input_shape: tf.TensorShape,
297
+ constants: Optional[types.Constants] = None,
298
+ ) -> tf.TensorShape:
299
+ if input_shape.rank != 2:
300
+ raise ValueError(
301
+ '2D pooling requires rank 4 input got: %s'
302
+ % tf.TensorShape([None, None]).concatenate(input_shape)
303
+ )
304
+ spatial_output_size = utils.convolution_padding_output_size(
305
+ input_shape.dims[0].value,
306
+ self._spatial_padding,
307
+ kernel_size=self._pool_size[1],
308
+ stride=self._strides[1],
309
+ dilation_rate=1,
310
+ )
311
+ return tf.TensorShape([spatial_output_size, input_shape.dims[1].value])
312
+
313
+ def _apply_pool(
314
+ self,
315
+ x: tf.Tensor,
316
+ explicit_padding: tuple[tuple[int, int], tuple[int, int]],
317
+ ) -> tf.Tensor:
318
+ x = tf.pad(x, [(0, 0), explicit_padding[0], explicit_padding[1], (0, 0)])
319
+ return self._layer(x)
320
+
321
+ @tf.Module.with_name_scope
322
+ def step(
323
+ self,
324
+ x: types.Sequence,
325
+ state: types.State,
326
+ training: bool,
327
+ constants: Optional[types.Constants] = None,
328
+ ) -> Tuple[types.Sequence, types.State]:
329
+ # In step mode, causal padding is handled by the state that is concatenated
330
+ # below.
331
+ time_padding = (0, 0)
332
+ spatial_padding = utils.convolution_explicit_padding(
333
+ self._spatial_padding, self._pool_size[1], dilation_rate=1
334
+ )
335
+
336
+ # Special case pool_size 1 since it is stateless.
337
+ if self._pool_size[0] == 1:
338
+ values = self._apply_pool(x.values, (time_padding, spatial_padding))
339
+ mask = convolution.compute_conv_mask(
340
+ x.mask,
341
+ self._pool_size[0],
342
+ self._strides[0],
343
+ dilation_rate=1,
344
+ padding=self._time_padding,
345
+ )
346
+ return types.Sequence(values, mask).mask_invalid(), state
347
+
348
+ # Concatenate the new frames with the previous buffer_width frames.
349
+ state = state.concatenate(x)
350
+
351
+ # Compute the output for the current timestep.
352
+ values = self._apply_pool(state.values, (time_padding, spatial_padding))
353
+ mask = convolution.compute_conv_mask(
354
+ state.mask,
355
+ self._pool_size[0],
356
+ self._strides[0],
357
+ dilation_rate=1,
358
+ padding=self._time_padding,
359
+ )
360
+
361
+ # Keep the last (pool_size - stride) frames for the next step.
362
+ state = state[:, -self._buffer_width :]
363
+
364
+ return types.Sequence(values, mask).mask_invalid(), state
365
+
366
+ @tf.Module.with_name_scope
367
+ def layer(
368
+ self,
369
+ x: types.Sequence,
370
+ training: bool,
371
+ initial_state: Optional[types.State] = None,
372
+ constants: Optional[types.Constants] = None,
373
+ ) -> types.Sequence:
374
+ time_padding = utils.convolution_explicit_padding(
375
+ self._time_padding,
376
+ self._pool_size[0],
377
+ dilation_rate=1,
378
+ )
379
+ spatial_padding = utils.convolution_explicit_padding(
380
+ self._spatial_padding, self._pool_size[1], dilation_rate=1
381
+ )
382
+ values = self._apply_pool(x.values, (time_padding, spatial_padding))
383
+
384
+ # In causal mode, x.mask is padded and compute_conv_mask uses a VALID
385
+ # convolution. In SAME mode, x.mask is not padded, and compute_conv_mask
386
+ # uses a strided slice mask[:, ::time_stride].
387
+ if self._time_padding == types.PaddingMode.CAUSAL.value:
388
+ # We can't use convolutional padding here since its value is 0.0, not 1.0.
389
+ mask = tf.pad(
390
+ x.mask,
391
+ [[0, 0], [self._buffer_width, 0]],
392
+ mode='constant',
393
+ constant_values=1.0,
394
+ )
395
+ else:
396
+ mask = x.mask
397
+
398
+ mask = convolution.compute_conv_mask(
399
+ mask,
400
+ self._pool_size[0],
401
+ self._strides[0],
402
+ dilation_rate=1,
403
+ padding=self._time_padding,
404
+ )
405
+
406
+ return types.Sequence(values, mask).mask_invalid()
407
+
408
+
409
+ class MaxPooling2D(BasePooling2D):
410
+ """A 2D max pooling layer."""
411
+
412
+ @classmethod
413
+ def _default_name(cls):
414
+ """The default module name for this class."""
415
+ return 'max_pooling_2d'
416
+
417
+ def __init__(
418
+ self,
419
+ pool_size: Union[int, List[int], Tuple[int, int]],
420
+ strides: Union[int, List[int], Tuple[int, int]],
421
+ *,
422
+ time_padding: str = 'causal',
423
+ spatial_padding: str = 'valid',
424
+ name: Optional[str] = None,
425
+ ):
426
+ super().__init__(
427
+ # We perform padding outside of Keras.
428
+ tf.keras.layers.MaxPooling2D(pool_size, strides, padding='valid'),
429
+ pool_size,
430
+ strides,
431
+ time_padding,
432
+ spatial_padding,
433
+ name=name,
434
+ )
435
+
436
+
437
+ class AveragePooling2D(BasePooling2D):
438
+ """A 2D average pooling layer."""
439
+
440
+ @classmethod
441
+ def _default_name(cls):
442
+ """The default module name for this class."""
443
+ return 'average_pooling_2d'
444
+
445
+ def __init__(
446
+ self,
447
+ pool_size: Union[int, List[int], Tuple[int, int]],
448
+ strides: Union[int, List[int], Tuple[int, int]],
449
+ *,
450
+ time_padding: str = 'causal',
451
+ spatial_padding: str = 'valid',
452
+ name: Optional[str] = None,
453
+ ):
454
+ super().__init__(
455
+ # We perform padding outside of Keras.
456
+ tf.keras.layers.AveragePooling2D(pool_size, strides, padding='valid'),
457
+ pool_size,
458
+ strides,
459
+ time_padding,
460
+ spatial_padding,
461
+ name=name,
462
+ )