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,285 @@
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
+ """Dense layers."""
15
+
16
+ from typing import List, Optional, Union
17
+
18
+ from sequence_layers.tensorflow import types
19
+ from sequence_layers.tensorflow import utils
20
+ import tensorflow.compat.v2 as tf
21
+
22
+
23
+ class Dense(types.Stateless):
24
+ """A simple dense layer."""
25
+
26
+ def __init__(
27
+ self,
28
+ units: int,
29
+ activation=None,
30
+ use_bias=True,
31
+ kernel_initializer='glorot_uniform',
32
+ bias_initializer='zeros',
33
+ kernel_regularizer=None,
34
+ bias_regularizer=None,
35
+ activity_regularizer=None,
36
+ kernel_constraint=None,
37
+ bias_constraint=None,
38
+ trainable=True,
39
+ name=None,
40
+ ):
41
+ super().__init__(name=name)
42
+ self._units = units
43
+ with self.name_scope as name_scope:
44
+ # Keras layers do not follow standard TF name scoping rules. Provide it a
45
+ # fully scoped name.
46
+ self._layer = tf.keras.layers.Dense(
47
+ units,
48
+ activation=activation,
49
+ use_bias=use_bias,
50
+ kernel_initializer=kernel_initializer,
51
+ bias_initializer=bias_initializer,
52
+ kernel_regularizer=kernel_regularizer,
53
+ bias_regularizer=bias_regularizer,
54
+ activity_regularizer=activity_regularizer,
55
+ kernel_constraint=kernel_constraint,
56
+ bias_constraint=bias_constraint,
57
+ trainable=trainable,
58
+ name=name_scope,
59
+ )
60
+
61
+ @tf.Module.with_name_scope
62
+ def layer(
63
+ self,
64
+ x: types.Sequence,
65
+ training: bool,
66
+ initial_state: Optional[types.State] = None,
67
+ constants: Optional[types.Constants] = None,
68
+ ) -> types.Sequence:
69
+ x.channel_shape.with_rank_at_least(1)
70
+ return x.apply_values(self._layer).mask_invalid()
71
+
72
+ def get_output_shape(
73
+ self,
74
+ input_shape: tf.TensorShape,
75
+ constants: Optional[types.Constants] = None,
76
+ ) -> tf.TensorShape:
77
+ input_shape.with_rank_at_least(1)
78
+ return input_shape[:-1].concatenate(self._units)
79
+
80
+
81
+ class DenseShaped(types.Stateless):
82
+ """A dense layer to project to a specific shape.
83
+
84
+ Dense connection between every element in input_shape to
85
+ every element in output_shape, at each time step.
86
+ """
87
+
88
+ def __init__(
89
+ self,
90
+ output_shape: Union[tf.TensorShape, List[int], tuple[int, ...]],
91
+ activation=None,
92
+ use_bias=True,
93
+ kernel_initializer='glorot_uniform',
94
+ bias_initializer='zeros',
95
+ kernel_regularizer=None,
96
+ bias_regularizer=None,
97
+ activity_regularizer=None,
98
+ kernel_constraint=None,
99
+ bias_constraint=None,
100
+ trainable=True,
101
+ name=None,
102
+ ):
103
+ super().__init__(name=name)
104
+ self._output_shape = tf.TensorShape(output_shape)
105
+ with self.name_scope as name_scope:
106
+ # Keras layers do not follow standard TF name scoping rules. Provide it a
107
+ # fully scoped name.
108
+ self._layer = tf.keras.layers.Dense(
109
+ self._output_shape.num_elements(),
110
+ activation=activation,
111
+ use_bias=use_bias,
112
+ kernel_initializer=kernel_initializer,
113
+ bias_initializer=bias_initializer,
114
+ kernel_regularizer=kernel_regularizer,
115
+ bias_regularizer=bias_regularizer,
116
+ activity_regularizer=activity_regularizer,
117
+ kernel_constraint=kernel_constraint,
118
+ bias_constraint=bias_constraint,
119
+ trainable=trainable,
120
+ name=name_scope,
121
+ )
122
+
123
+ @tf.Module.with_name_scope
124
+ def layer(
125
+ self,
126
+ x: types.Sequence,
127
+ training: bool,
128
+ initial_state: Optional[types.State] = None,
129
+ constants: Optional[types.Constants] = None,
130
+ ) -> types.Sequence:
131
+ batch_size, time = utils.smart_dimension_size(x.values, [0, 1])
132
+
133
+ def shaped_projection(values):
134
+ if values.shape.rank != 3:
135
+ values = tf.reshape(
136
+ values, [batch_size, time, values.shape[2:].num_elements()]
137
+ )
138
+ values_projected = self._layer(values)
139
+ if self._output_shape.rank == 1:
140
+ return values_projected
141
+ else:
142
+ return tf.reshape(
143
+ values_projected, [batch_size, time] + self._output_shape.as_list()
144
+ )
145
+
146
+ return x.apply_values(shaped_projection).mask_invalid()
147
+
148
+ def get_output_shape(
149
+ self,
150
+ input_shape: tf.TensorShape,
151
+ constants: Optional[types.Constants] = None,
152
+ ) -> tf.TensorShape:
153
+ return self._output_shape
154
+
155
+
156
+ class EinsumDense(types.Stateless):
157
+ """Applies an EinsumDense layer to the channels dimension of each timestep.
158
+
159
+ Differences from tf.keras.layers.EinsumDense:
160
+ - Equation input and output specs must have leading ellipses to broadcast over
161
+ the batch and time dimension.
162
+
163
+ Example:
164
+
165
+ Input sequence: [b, t, c1, c2, c3]
166
+ - equation = '...abc,bd->...bd'
167
+ - output_shape = [None, c4]
168
+ - bias_axes = 'd'
169
+ Output sequence: [b, t, c2, c4]
170
+
171
+ Kernel shape: [c2, c4]
172
+ Bias shape: [c4]
173
+
174
+ Interpretation: Every [c1, c2, c3] tensor per timestep is transformed with the
175
+ einsum formula abc,bd->bd.
176
+ """
177
+
178
+ def __init__(
179
+ self,
180
+ equation: str,
181
+ output_shape: list[Optional[int]],
182
+ activation=None,
183
+ bias_axes=None,
184
+ kernel_initializer='glorot_uniform',
185
+ bias_initializer='zeros',
186
+ kernel_regularizer=None,
187
+ bias_regularizer=None,
188
+ activity_regularizer=None,
189
+ kernel_constraint=None,
190
+ bias_constraint=None,
191
+ trainable: bool = True,
192
+ name: Optional[str] = None,
193
+ ):
194
+ super().__init__(name)
195
+ with self.name_scope:
196
+ self._layer = tf.keras.layers.EinsumDense(
197
+ equation=equation,
198
+ output_shape=output_shape,
199
+ activation=activation,
200
+ bias_axes=bias_axes,
201
+ kernel_initializer=kernel_initializer,
202
+ bias_initializer=bias_initializer,
203
+ kernel_regularizer=kernel_regularizer,
204
+ bias_regularizer=bias_regularizer,
205
+ activity_regularizer=activity_regularizer,
206
+ kernel_constraint=kernel_constraint,
207
+ bias_constraint=bias_constraint,
208
+ trainable=trainable,
209
+ name='einsum_dense',
210
+ )
211
+ self._parse_and_validate_equation(equation)
212
+ if not output_shape:
213
+ raise ValueError(f'output_shape is required, got: {output_shape}')
214
+
215
+ def _parse_and_validate_equation(self, equation) -> tuple[str, str, str]:
216
+ if '->' not in equation:
217
+ raise ValueError(f'equation is not valid for EinsumDense: {equation}')
218
+ left, output_spec = equation.split('->')
219
+ input_spec, kernel_spec = left.split(',')
220
+ if not input_spec.startswith('...') or not output_spec.startswith('...'):
221
+ raise ValueError('Equation must be of the form "...X,Y->...Z".')
222
+ return input_spec, kernel_spec, output_spec
223
+
224
+ def _get_and_validate_output_shape(
225
+ self, input_shape: tf.TensorShape
226
+ ) -> tf.TensorShape:
227
+ equation = self._layer.equation
228
+ input_spec, _, output_spec = self._parse_and_validate_equation(equation)
229
+ assert input_spec.startswith('...')
230
+ assert output_spec.startswith('...')
231
+ # Trim '...' off.
232
+ input_spec, output_spec = input_spec[3:], output_spec[3:]
233
+
234
+ if len(input_spec) != len(input_shape):
235
+ raise ValueError(
236
+ f'Equation {input_spec=} does not match {input_shape=} rank.'
237
+ )
238
+
239
+ input_dims = {
240
+ d: input_shape.dims[i].value for i, d in enumerate(input_spec)
241
+ }
242
+ assert len(input_dims) == len(input_spec)
243
+
244
+ output_shape = tf.TensorShape(self._layer.partial_output_shape).as_list()
245
+ if len(output_spec) != len(output_shape):
246
+ raise ValueError(
247
+ f'Equation {output_spec=} does not match {output_shape=}.'
248
+ )
249
+
250
+ for i, d in enumerate(output_spec):
251
+ if output_shape[i] is None:
252
+ output_shape[i] = input_dims[d]
253
+ elif d in input_dims and output_shape[i] != input_dims[d]:
254
+ raise ValueError(
255
+ 'Input shape and output shape inconsistent for dimension '
256
+ f'{d=}. {output_shape=} {input_shape=}'
257
+ )
258
+ output_shape = tf.TensorShape(output_shape)
259
+ if not output_shape.is_fully_defined():
260
+ raise ValueError(
261
+ f'Could not fully determine {output_shape=} from {input_shape=}. '
262
+ f'{equation=} {self._layer.partial_output_shape=}'
263
+ )
264
+ return output_shape
265
+
266
+ def get_output_shape(
267
+ self,
268
+ input_shape: tf.TensorShape,
269
+ constants: Optional[types.Constants] = None,
270
+ ) -> tf.TensorShape:
271
+ return self._get_and_validate_output_shape(input_shape)
272
+
273
+ @tf.Module.with_name_scope
274
+ def layer(
275
+ self,
276
+ x: types.Sequence,
277
+ training: bool,
278
+ initial_state: Optional[types.State] = None,
279
+ constants: Optional[types.Constants] = None,
280
+ ) -> types.Sequence:
281
+ del initial_state
282
+ self._get_and_validate_output_shape(x.channel_shape)
283
+ return x.apply_values(
284
+ lambda v: self._layer(v, training=training)
285
+ ).mask_invalid()