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,439 @@
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
+ """Time-varying layers."""
15
+
16
+ from sequence_layers.tensorflow import types
17
+ from sequence_layers.tensorflow import utils
18
+ import tensorflow.compat.v2 as tf
19
+
20
+
21
+ class SequenceEmbedding(types.SequenceLayer):
22
+ """Computes sequence embeddings of integer input codes.
23
+
24
+ Provides step-dependent embeddings with num_groups embeddings, where sequence
25
+ step specifies the group index, and for steps above num_groups - 1, we use the
26
+ last group (i.e., group_index = num_groups - 1). So, this layer is appropriate
27
+ for fixed length sequences, where num_groups is set to the fixed length.
28
+ """
29
+
30
+ def __init__(
31
+ self,
32
+ dimension: int,
33
+ num_embeddings: int,
34
+ num_groups: int,
35
+ embeddings_initializer='uniform',
36
+ embeddings_regularizer=None,
37
+ activity_regularizer=None,
38
+ embeddings_constraint=None,
39
+ trainable: bool = True,
40
+ name: str | None = None,
41
+ ):
42
+ super().__init__(name)
43
+ self._num_groups = num_groups
44
+ # Reserve one embedding for masking token, in this case, -1 will be used for
45
+ # padding outside this function
46
+ self._num_embeddings = num_embeddings
47
+ with self.name_scope:
48
+ self._embedding = tf.keras.layers.Embedding(
49
+ input_dim=self._num_embeddings * self._num_groups,
50
+ output_dim=dimension,
51
+ embeddings_initializer=embeddings_initializer,
52
+ embeddings_regularizer=embeddings_regularizer,
53
+ activity_regularizer=activity_regularizer,
54
+ embeddings_constraint=embeddings_constraint,
55
+ trainable=trainable,
56
+ name='embedding',
57
+ )
58
+
59
+ def get_output_shape(
60
+ self,
61
+ input_shape: tf.TensorShape,
62
+ constants: types.Constants | None = None,
63
+ ) -> tf.TensorShape:
64
+ return input_shape.concatenate(self._embedding.output_dim)
65
+
66
+ def get_output_dtype(self, input_dtype: tf.DType) -> tf.DType:
67
+ assert input_dtype in [tf.uint8, tf.int32, tf.int64]
68
+ return utils.compute_dtype()
69
+
70
+ def get_initial_state(
71
+ self, x: types.Sequence, constants: types.Constants | None = None
72
+ ) -> types.State:
73
+ return tf.zeros(shape=(), dtype=tf.int32)
74
+
75
+ def _time_wise_embed(
76
+ self, values: tf.Tensor, start_time: tf.Tensor | int, training: bool
77
+ ) -> tf.Tensor:
78
+ tf.debugging.assert_greater_equal(
79
+ values, 0, message='Out of range lookup index (< 0).'
80
+ )
81
+ tf.debugging.assert_less(
82
+ values,
83
+ self._num_embeddings,
84
+ message='Out of range lookup index (>= num_embeddings).',
85
+ )
86
+ values = tf.cast(values, tf.int32)
87
+
88
+ block_size = utils.smart_dimension_size(values, 1)
89
+ # [t].
90
+ steps = start_time + tf.range(block_size, dtype=tf.int32)
91
+ steps = tf.minimum(steps, self._num_groups - 1)
92
+
93
+ # Reshape into [t, 1, ..., 1].
94
+ steps = tf.reshape(
95
+ steps, tf.stack([block_size, *([1] * (values.shape.rank - 2))], axis=0)
96
+ )
97
+
98
+ # The lookup indices are broadcast-added into shape of values ([b, t, ...])
99
+ # and embeddings is shaped [b, t, ..., embedding_dim].
100
+ embeddings = self._embedding(
101
+ values + steps * self._num_embeddings, training=training
102
+ )
103
+ return embeddings
104
+
105
+ @tf.Module.with_name_scope
106
+ def step(
107
+ self,
108
+ x: types.Sequence,
109
+ state: types.State,
110
+ training: bool,
111
+ constants: types.Constants | None = None,
112
+ ) -> tuple[types.Sequence, types.State]:
113
+ """Steps forward, input shape: [..., block_size, num_groups]."""
114
+ x = x.apply_values(
115
+ lambda v: self._time_wise_embed(v, state, training=training)
116
+ ).mask_invalid()
117
+ time = utils.smart_dimension_size(x.values, 1)
118
+ return x, state + time
119
+
120
+ @tf.Module.with_name_scope
121
+ def layer(
122
+ self,
123
+ x: types.Sequence,
124
+ training: bool,
125
+ initial_state: types.State | None = None,
126
+ constants: types.Constants | None = None,
127
+ ) -> types.Sequence:
128
+ del initial_state
129
+ del constants
130
+ return x.apply_values(
131
+ lambda v: self._time_wise_embed(v, 0, training=training)
132
+ ).mask_invalid()
133
+
134
+
135
+ class SequenceDense(types.SequenceLayer):
136
+ """Step-dependent Dense layer.
137
+
138
+ Provides step-dependent Dense layers up to num_steps, where the sequence
139
+ step determines which Dense layer is used. This layer can be used with fixed
140
+ length sequences, where num_steps is set to the fixed length. For variable
141
+ length sequences, set num_steps to the maximum sequence length.
142
+
143
+ Each step-dependent Dense layer only operates on the inputs at the associated
144
+ timestep, i.e., y[t] = Dense_t(x[t]), where Dense_t is the Dense layer
145
+ used for timestep t.
146
+ """
147
+
148
+ def __init__(
149
+ self,
150
+ units: int,
151
+ num_steps: int,
152
+ activation=None,
153
+ use_bias: bool = True,
154
+ kernel_initializer='glorot_uniform',
155
+ bias_initializer='zeros',
156
+ name: str | None = None,
157
+ ):
158
+ super().__init__(name=name)
159
+ self._units = units
160
+ self._num_steps = num_steps
161
+ self._activation_fn = tf.keras.activations.get(activation)
162
+ self._use_bias = use_bias
163
+ self._kernel_initializer = tf.keras.initializers.get(kernel_initializer)
164
+ self._bias_initializer = tf.keras.initializers.get(bias_initializer)
165
+
166
+ self._kernel = None
167
+ self._bias = None
168
+ self._built = False
169
+
170
+ def _build(self, x: types.Sequence):
171
+ if self._built:
172
+ return
173
+ with self.name_scope:
174
+ # TODO(ebattenberg): Support additional channel dims like standard Dense
175
+ # layer.
176
+ if x.values.shape.rank != 3:
177
+ raise ValueError('SequenceDense requires rank 3 input.')
178
+ input_dim = x.values.shape[2]
179
+ kernel_shape = [self._num_steps, input_dim, self._units]
180
+ self._kernel = tf.Variable(
181
+ lambda: self._kernel_initializer(kernel_shape),
182
+ name='kernel',
183
+ )
184
+ if self._use_bias:
185
+ self._bias = tf.Variable(
186
+ lambda: self._bias_initializer([self._num_steps, self._units]),
187
+ name='bias',
188
+ )
189
+ self._built = True
190
+
191
+ def get_output_shape(
192
+ self,
193
+ input_shape: tf.TensorShape,
194
+ constants: types.Constants | None = None,
195
+ ) -> tf.TensorShape:
196
+ del constants
197
+ input_shape.with_rank_at_least(1)
198
+ return input_shape[:-1].concatenate(self._units)
199
+
200
+ def get_initial_state(
201
+ self, x: types.Sequence, constants: types.Constants | None = None
202
+ ) -> types.State:
203
+ del x, constants
204
+ return tf.zeros(shape=(), dtype=tf.int32)
205
+
206
+ @tf.Module.with_name_scope
207
+ def step(
208
+ self,
209
+ x: types.Sequence,
210
+ state: types.State,
211
+ training: bool,
212
+ constants: types.Constants | None = None,
213
+ ) -> tuple[types.Sequence, types.State]:
214
+ """Steps forward, input shape: [..., block_size, num_groups]."""
215
+ del training, constants
216
+ self._build(x)
217
+
218
+ start_time = state
219
+ time_delta = utils.smart_dimension_size(x.values, 1)
220
+ _check_step_bounds(start_time, start_time + time_delta, self._num_steps)
221
+
222
+ # Slice [T, I, O] kernel to be used with current timesteps.
223
+ step_kernel = tf.slice(
224
+ # self._units is required to prevent loss of channel dim shape.
225
+ self._kernel, [start_time, 0, 0], [time_delta, -1, self._units]
226
+ )
227
+ net = tf.einsum('BTI,TIO->BTO', x.values, step_kernel)
228
+ if self._use_bias:
229
+ # Slice [T, O] bias to be used with current timesteps.
230
+ step_bias = tf.slice(
231
+ self._bias, [start_time, 0], [time_delta, self._units]
232
+ )
233
+ net += step_bias
234
+ net = self._activation_fn(net)
235
+ y = types.Sequence(values=net, mask=x.mask).mask_invalid()
236
+
237
+ return y, start_time + time_delta
238
+
239
+ @tf.Module.with_name_scope
240
+ def layer(
241
+ self,
242
+ x: types.Sequence,
243
+ training: bool,
244
+ initial_state: types.State | None = None,
245
+ constants: types.Constants | None = None,
246
+ ) -> types.Sequence:
247
+ if initial_state is None:
248
+ initial_state = self.get_initial_state(x, constants)
249
+ y, _ = self.step(x, initial_state, training, constants)
250
+ return y
251
+
252
+
253
+ class MaskedDense(types.SequenceLayer):
254
+ """Step-dependent causal masked Dense layers.
255
+
256
+ Provides step-dependent masked Dense layers up to num_steps, where the
257
+ sequence step determines which masked Dense layer is used. This layer can be
258
+ used with fixed length sequences, where num_steps is set to the fixed length.
259
+ For variable length sequences, set num_steps to the maximum sequence length.
260
+
261
+ Masked Dense layers are causally masked so that y[t] (the output at time=t)
262
+ is a Dense transformation of x[0:t+1] (the input from time=0 up to time=t,
263
+ inclusive.); i.e., y[t] = Dense_t(x[0,...,t]), where Dense_t is the Dense
264
+ layer used for timestep t.
265
+
266
+ Note:
267
+ This layer uses a masked kernel variable in order to maintain the
268
+ autoregressive property, and therefore, half of the weights are unused and
269
+ have zero gradient. This could affect the behavior of certain optimizers or
270
+ normalization schemes (e.g., AdaFactor).
271
+ """
272
+
273
+ def __init__(
274
+ self,
275
+ units: int,
276
+ num_steps: int,
277
+ activation=None,
278
+ use_bias: bool = True,
279
+ kernel_initializer='glorot_uniform',
280
+ bias_initializer='zeros',
281
+ name: str | None = None,
282
+ ):
283
+ super().__init__(name=name)
284
+ self._units = units
285
+ self._num_steps = num_steps
286
+ self._activation_fn = tf.keras.activations.get(activation)
287
+ self._use_bias = use_bias
288
+ self._kernel_initializer = tf.keras.initializers.get(kernel_initializer)
289
+ self._bias_initializer = tf.keras.initializers.get(bias_initializer)
290
+
291
+ self._kernel = None
292
+ self._bias = None
293
+ self._input_dim = None
294
+ self._built = False
295
+
296
+ def _get_mask(self) -> tf.Tensor:
297
+ # Construct a [T, T', 1, 1] upper triangular autoregressive mask matrix,
298
+ # where T represents the input time dimension and T' represents the output
299
+ # time dimension, and T = T' = num_steps.
300
+ num_steps = self._num_steps
301
+ mask = tf.linalg.band_part(tf.ones([num_steps, num_steps]), 0, -1)
302
+ return tf.reshape(mask, [num_steps, num_steps, 1, 1], name='mask')
303
+
304
+ def _build(self, x: types.Sequence):
305
+ if self._built:
306
+ return
307
+ with self.name_scope:
308
+ # TODO(ebattenberg): Support additional channel dims like standard Dense.
309
+ if x.values.shape.rank != 3:
310
+ raise ValueError('MaskedDense requires rank 3 input.')
311
+ self._input_dim = x.values.shape[2]
312
+ num_steps = self._num_steps
313
+
314
+ # TODO(ebattenberg): Consider ways to eliminate unused (masked off)
315
+ # weights (e.g., construct a masked kernel Tensor from smaller
316
+ # sub-variables.)
317
+
318
+ # Construct a [T, T', I, O] kernel tensor to project [B, T, I] input to
319
+ # [B, T', O] output, where T represents the input time dimension and T'
320
+ # represents the output time dimension, and T = T' = num_steps.
321
+ kernel_shape = [num_steps, num_steps, self._input_dim, self._units]
322
+ # Note that the mask is applied to the initializer and as a constraint to
323
+ # keep the masked values from drifting due to things like weight decay.
324
+ self._kernel = tf.Variable(
325
+ lambda: self._get_mask() * self._kernel_initializer(kernel_shape),
326
+ constraint=lambda x: self._get_mask() * x,
327
+ name='kernel',
328
+ )
329
+ if self._use_bias:
330
+ # Bias is applied to [B, T', O] kernel output.
331
+ self._bias = tf.Variable(
332
+ lambda: self._bias_initializer([num_steps, self._units]),
333
+ name='bias',
334
+ )
335
+ self._built = True
336
+
337
+ def get_output_shape(
338
+ self,
339
+ input_shape: tf.TensorShape,
340
+ constants: types.Constants | None = None,
341
+ ) -> tf.TensorShape:
342
+ del constants
343
+ input_shape.with_rank_at_least(1)
344
+ return input_shape[:-1].concatenate(self._units)
345
+
346
+ def get_initial_state(
347
+ self, x: types.Sequence, constants: types.Constants | None = None
348
+ ) -> types.State:
349
+ del constants
350
+ self._build(x)
351
+
352
+ batch_size = utils.smart_dimension_size(x.values, 0)
353
+ # When executing step-by-step, we need a buffer for tracking past inputs.
354
+ t0 = tf.zeros(shape=(), dtype=tf.int32)
355
+ input_buffer = types.Sequence(
356
+ tf.zeros(
357
+ (batch_size, self._num_steps, self._input_dim),
358
+ dtype=x.values.dtype,
359
+ ),
360
+ tf.zeros((batch_size, self._num_steps), dtype=x.mask.dtype),
361
+ )
362
+ return t0, input_buffer
363
+
364
+ @tf.Module.with_name_scope
365
+ def step(
366
+ self,
367
+ x: types.Sequence,
368
+ state: types.State,
369
+ training: bool,
370
+ constants: types.Constants | None = None,
371
+ ) -> tuple[types.Sequence, types.State]:
372
+ """Steps forward, input shape: [..., block_size, num_groups]."""
373
+ del training, constants
374
+ self._build(x)
375
+
376
+ start_time, input_buffer = state
377
+ time_delta = utils.smart_dimension_size(x.values, 1)
378
+ end_time = start_time + time_delta
379
+ _check_step_bounds(start_time, end_time, self._num_steps)
380
+
381
+ # Append new input to end of buffer and truncate at the front:
382
+ # e.g., [0, 0, x0, x1] -> [0, x0, x1, x2], where new input is [x2].
383
+ input_buffer = input_buffer.concatenate(x)
384
+ input_buffer = input_buffer[:, -self._num_steps:]
385
+ # Roll buffer so padding is at the end:
386
+ # e.g., [0, x0, x1, x2] -> [x0, x1, x2, 0]
387
+ step_input = tf.roll(input_buffer.values, shift=end_time, axis=1)
388
+
389
+ # Slice kernel and mask to produce current output timesteps.
390
+ # Kernel is [T, T', I, O], mask is [T, T', 1, 1], where T represents the
391
+ # input time dimension and T' represents the output time dimension,
392
+ # and T = T' = num_steps.
393
+ # step_kernel = self._kernel[:, start_time:end_time]
394
+ step_kernel = tf.slice(
395
+ # self._units is required to prevent loss of channel dim shape.
396
+ self._kernel, [0, start_time, 0, 0], [-1, time_delta, -1, self._units]
397
+ )
398
+ # step_mask = self._get_mask()[:, start_time:end_time]
399
+ step_mask = tf.slice(
400
+ self._get_mask(), [0, start_time, 0, 0], [-1, time_delta, 1, 1]
401
+ )
402
+ # Even though the kernel tf.Variable has a mask constraint,
403
+ # we still mask the op here to ensure the gradients to the masked off
404
+ # regions are zero as well (so we don't pollute the gradient statistics).
405
+ masked_step_kernel = step_mask * step_kernel
406
+
407
+ net = tf.einsum('BTI,TtIO->BtO', step_input, masked_step_kernel)
408
+ if self._use_bias:
409
+ # Bias is [T', O]. Slice for current output timesteps.
410
+ step_bias = tf.slice(
411
+ self._bias, [start_time, 0], [time_delta, self._units]
412
+ )
413
+ net += step_bias
414
+ net = self._activation_fn(net)
415
+ y = types.Sequence(values=net, mask=x.mask).mask_invalid()
416
+
417
+ state = (end_time, input_buffer)
418
+ return y, state
419
+
420
+ @tf.Module.with_name_scope
421
+ def layer(
422
+ self,
423
+ x: types.Sequence,
424
+ training: bool,
425
+ initial_state: types.State | None = None,
426
+ constants: types.Constants | None = None,
427
+ ) -> types.Sequence:
428
+ if initial_state is None:
429
+ initial_state = self.get_initial_state(x, constants)
430
+ y, _ = self.step(x, initial_state, training, constants)
431
+ return y
432
+
433
+
434
+ def _check_step_bounds(start_time, end_time, num_steps):
435
+ """Check that step indices are within range."""
436
+ tf.debugging.assert_greater_equal(
437
+ start_time, 0, message='Out of range step index (< 0).')
438
+ tf.debugging.assert_less_equal(
439
+ end_time, num_steps, message='Out of range step index (> num_steps).')