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,834 @@
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
+ """Test utilities for SequenceLayers."""
15
+
16
+ import contextlib
17
+ from typing import Any, Callable, List, Optional, Tuple
18
+
19
+ import numpy as np
20
+ import sequence_layers.tensorflow as sl
21
+ from sequence_layers.tensorflow import utils
22
+ import tensorflow.compat.v1 as tf1
23
+ import tensorflow.compat.v2 as tf
24
+
25
+
26
+ # List of Keras mixed precision policies SequenceLayers supports.
27
+ # https://www.tensorflow.org/guide/mixed_precision
28
+ SUPPORTED_PRECISION_POLICIES = ('float32', 'mixed_bfloat16', 'bfloat16')
29
+
30
+
31
+ def _grad_ys(sequence: sl.Sequence) -> tf.Tensor:
32
+ if sequence.values.dtype.is_complex:
33
+ return tf.ones_like(sequence.values) + 1j * tf.ones_like(sequence.values)
34
+ else:
35
+ return tf.ones_like(sequence.values)
36
+
37
+
38
+ def _tf_gradients(y: sl.Sequence, x: sl.Sequence) -> sl.Sequence:
39
+ return sl.Sequence(
40
+ tf.gradients(y.values, x.values, grad_ys=_grad_ys(y))[0], x.mask
41
+ ).mask_invalid()
42
+
43
+
44
+ def _tape_gradient(
45
+ tape: tf.GradientTape, y: sl.Sequence, x: sl.Sequence
46
+ ) -> sl.Sequence:
47
+ def grad_fn(values: tf.Tensor) -> tf.Tensor:
48
+ grad = tape.gradient(y.values, values, _grad_ys(y))
49
+ if grad is None:
50
+ raise ValueError('Gradient of y with respect to x does not exist.')
51
+ return grad
52
+
53
+ return x.apply_values(grad_fn).mask_invalid()
54
+
55
+
56
+ class SequenceLayerTest(tf.test.TestCase):
57
+ """Helper functions for SequenceLayer tests."""
58
+
59
+ def assertAllFinite(self, a):
60
+ """Assert that all entries in a `Tensor` are finite.
61
+
62
+ Args:
63
+ a: A `Tensor` whose entries are checked for finiteness.
64
+ """
65
+ is_finite = np.isfinite(self._GetNdArray(a))
66
+ all_true = np.ones_like(is_finite, dtype=bool)
67
+ self.assertAllEqual(all_true, is_finite)
68
+
69
+ def assertAllNan(self, a):
70
+ """Assert that every entry in a `Tensor` is NaN.
71
+
72
+ Args:
73
+ a: A `Tensor` whose entries must be verified as NaN.
74
+ """
75
+ is_nan = np.isnan(self._GetNdArray(a))
76
+ all_true = np.ones_like(is_nan, dtype=bool)
77
+ self.assertAllEqual(all_true, is_nan)
78
+
79
+ def verify_contract(
80
+ self,
81
+ l: sl.SequenceLayer,
82
+ x: sl.Sequence,
83
+ *,
84
+ training: bool,
85
+ constants: sl.Constants = None,
86
+ test_causality: bool = True,
87
+ pad_nan: bool = True,
88
+ pad_constants: bool = False,
89
+ pad_constants_ratio: int = 1,
90
+ test_gradients: bool = True,
91
+ rtol=1e-6,
92
+ atol=1e-6,
93
+ grad_rtol=None,
94
+ grad_atol=None,
95
+ ) -> Tuple[sl.Sequence, sl.Sequence]:
96
+ """Verifies the SequenceLayer contract outlined in go/tf-sequence-layers.
97
+
98
+ In graph mode, x is modified so that batch and time dimension are unknown.
99
+
100
+ Args:
101
+ l: The SequenceLayer to test.
102
+ x: A Sequence to use as input.
103
+ training: Whether to run the layer in training mode.
104
+ constants: A dictionary of constant name to tf.Tensor or sl.Sequence.
105
+ Values or sequences that are "constant" with respect to the
106
+ SequenceLayer, but may affect its processing. For example, for an
107
+ Attention layer this may contain the key/value sequence to attend to.
108
+ test_causality: Whether to test causality.
109
+ pad_nan: Whether to test causality by padding x with NaNs and verifying
110
+ that NaNs do not leak into valid regions of the sequence.
111
+ pad_constants: Whether to pad sl.Sequence instances in constants along
112
+ with padding x with NaNs, when verifying causality.
113
+ pad_constants_ratio: The ratio between the time dimension of x and
114
+ sequences in constants.
115
+ test_gradients: Whether to compute and compare the gradients for l applied
116
+ to x in step-wise and layer-wise mode.
117
+ rtol: The relative tolerance to test layer/step equivalence to.
118
+ atol: The absolute tolerance to test layer/step equivalence to.
119
+ grad_rtol: Optional relative tolerance to test layer/step gradient
120
+ equivalence to. Uses rtol if not specified.
121
+ grad_atol: Optional absolute tolerance to test layer/step gradient
122
+ equivalence to. Uses atol if not specified.
123
+
124
+ Returns:
125
+ x: The input Sequence, converted to numpy arrays.
126
+ y_layer: The result of running x layer-by-layer, converted to numpy
127
+ arrays. If the function returns without throwing an exception then
128
+ layer-by-layer processing is equivalent to step-by-step processing
129
+ (up to rtol/atol).
130
+ """
131
+ if not tf.executing_eagerly():
132
+ raise ValueError('verify_contract is only supported in eager mode.')
133
+
134
+ if grad_rtol is None:
135
+ grad_rtol = rtol
136
+ if grad_atol is None:
137
+ grad_atol = atol
138
+ # Forget batch and time dimension inside tf.function.
139
+ unknown_batch_and_time_spec = sl.Sequence(
140
+ tf.TensorSpec(
141
+ tf.TensorShape([None, None]).concatenate(x.channel_shape),
142
+ x.values.dtype,
143
+ ),
144
+ tf.TensorSpec(tf.TensorShape([None, None]), x.mask.dtype),
145
+ )
146
+
147
+ @tf.function(input_signature=[unknown_batch_and_time_spec])
148
+ def layer_fn(x):
149
+ y = l.layer(x, training=training, initial_state=s0, constants=constants)
150
+ if not y.channel_shape.is_fully_defined():
151
+ raise ValueError(
152
+ f'Sequence enters {l}.layer with shape {x.values.shape} '
153
+ f'and loses channel shape information: {y.values.shape}'
154
+ )
155
+ if test_gradients:
156
+ return y, _tf_gradients(y, x)
157
+ else:
158
+ return y
159
+
160
+ @tf.function(input_signature=[unknown_batch_and_time_spec])
161
+ def step_fn(x):
162
+ y, _, _ = utils.step_by_step_dynamic(
163
+ l, x, training, s0, constants=constants
164
+ )
165
+ if not y.channel_shape.is_fully_defined():
166
+ raise ValueError(
167
+ f'Sequence enters {l}.step with shape {x.values.shape} '
168
+ f'and loses channel shape information: {y.values.shape}'
169
+ )
170
+ if test_gradients:
171
+ return y, _tf_gradients(y, x)
172
+ else:
173
+ return y
174
+
175
+ s0 = l.get_initial_state(x, constants)
176
+ output_spec = l.get_output_spec_for_sequence(x, constants)
177
+
178
+ # Compute outputs layer-by-layer, step-by-step, and step-by-step with a
179
+ # block size of 2x its minimum.
180
+ with tf.GradientTape(persistent=True) as tape:
181
+ tape.watch(x)
182
+ y_layer = l.layer(x, training, initial_state=s0, constants=constants)
183
+ if l.supports_step:
184
+ y_step, _, _ = utils.step_by_step_dynamic(
185
+ l, x, training, s0, constants=constants
186
+ )
187
+ y_step_2x, _, _ = utils.step_by_step_dynamic(
188
+ l, x, training, s0, blocks_per_step=2, constants=constants
189
+ )
190
+ if test_gradients:
191
+ y_layer_fn, y_layer_fn_grad = layer_fn(x)
192
+ if l.supports_step:
193
+ y_step_fn, y_step_fn_grad = step_fn(x)
194
+ else:
195
+ y_layer_fn, y_layer_fn_grad = layer_fn(x), None
196
+ if l.supports_step:
197
+ y_step_fn, y_step_fn_grad = step_fn(x), None
198
+
199
+ # The actual layer output spec matches get_output_spec.
200
+ self.assertEqual(y_layer.channel_spec, output_spec)
201
+ self.assertEqual(y_layer_fn.channel_spec, output_spec)
202
+ if l.supports_step:
203
+ self.assertEqual(y_step.channel_spec, output_spec)
204
+ self.assertEqual(y_step_2x.channel_spec, output_spec)
205
+ self.assertEqual(y_step_fn.channel_spec, output_spec)
206
+
207
+ x_np = x.apply(lambda v, m: (v.numpy(), m.numpy()))
208
+ # In Eager mode we use the above GradientTape to compute gradients.
209
+ if test_gradients:
210
+ y_layer_grad = _tape_gradient(tape, y_layer, x)
211
+ if l.supports_step:
212
+ y_step_grad = _tape_gradient(tape, y_step, x)
213
+ y_step_2x_grad = _tape_gradient(tape, y_step_2x, x)
214
+
215
+ # 1. Layer-wise / step-wise equivalent (values, masks, gradients).
216
+ if l.supports_step:
217
+ self.assertSequencesClose(y_layer, y_step, rtol=rtol, atol=atol)
218
+ self.assertSequencesClose(y_layer, y_step_2x, rtol=rtol, atol=atol)
219
+ self.assertSequencesClose(y_layer, y_step_fn, rtol=rtol, atol=atol)
220
+ self.assertSequencesClose(y_layer, y_layer_fn, rtol=rtol, atol=atol)
221
+
222
+ if test_gradients:
223
+ if l.supports_step:
224
+ self.assertSequencesClose(
225
+ y_layer_grad, y_step_grad, rtol=grad_rtol, atol=grad_atol
226
+ )
227
+ self.assertSequencesClose(
228
+ y_layer_grad, y_step_2x_grad, rtol=grad_rtol, atol=grad_atol
229
+ )
230
+ self.assertSequencesClose(
231
+ y_layer_grad, y_step_fn_grad, rtol=grad_rtol, atol=grad_atol
232
+ )
233
+ self.assertSequencesClose(
234
+ y_layer_grad, y_layer_fn_grad, rtol=grad_rtol, atol=grad_atol
235
+ )
236
+
237
+ # 6. Masking.
238
+ self.verify_masked(y_layer)
239
+ self.verify_masked(y_layer_fn)
240
+ if l.supports_step:
241
+ self.verify_masked(y_step)
242
+ self.verify_masked(y_step_2x)
243
+ self.verify_masked(y_step_fn)
244
+
245
+ # 2. No implicit end padding.
246
+ # TODO(rryan): Change mask to test this?
247
+
248
+ # 3. Causality.
249
+ # 5. Tensor shape invariance.
250
+ # Check causality and tensor shape invariance by replacing all padding with
251
+ # NaN and padding with a block of NaNs.
252
+ # TODO(rryan): Make this test stronger by padding with valid NaNs at the
253
+ # end of the sequence to show that they don't "leak" backwards.
254
+
255
+ # Causality is only required if stepping is supported.
256
+ if test_causality and l.supports_step:
257
+ pad_value = np.nan if pad_nan else tf.cast(1e9, dtype=x.values.dtype)
258
+ # Replace all masked values with NaN and pad with one block of invalid
259
+ # NaNs.
260
+ x_nan = x.apply_values(
261
+ lambda v: tf.where(
262
+ x.expanded_mask() > 0.0, v, tf.ones_like(v) * pad_value
263
+ )
264
+ )
265
+
266
+ def _pad(x, pad_back):
267
+ return x.pad_time(0, pad_back, valid=False, pad_value=pad_value)
268
+
269
+ x_nan = _pad(x_nan, l.block_size * pad_constants_ratio)
270
+ if constants is not None and pad_constants:
271
+ constants_nan = {
272
+ k: _pad(v, l.block_size) if isinstance(v, sl.Sequence) else v
273
+ for k, v in constants.items()
274
+ }
275
+ else:
276
+ constants_nan = constants
277
+
278
+ y_layer_nan = l.layer(
279
+ x_nan, training, initial_state=s0, constants=constants_nan
280
+ )
281
+ # Replace NaNs in the padding with zeros.
282
+ y_layer_nan = y_layer_nan.apply_values(
283
+ lambda v: tf.where(
284
+ y_layer_nan.expanded_mask() > 0.0, v, tf.zeros_like(v)
285
+ )
286
+ )
287
+ self.assertSequencesClose(y_layer_nan, y_layer, rtol=rtol, atol=atol)
288
+
289
+ y_step_nan, _, _ = utils.step_by_step_dynamic(
290
+ l, x_nan, training, s0, constants=constants_nan
291
+ )
292
+ # Replace NaNs in the padding with zeros.
293
+ y_step_nan = y_step_nan.apply_values(
294
+ lambda v: tf.where(
295
+ y_step_nan.expanded_mask() > 0.0, v, tf.zeros_like(v)
296
+ )
297
+ )
298
+ self.assertSequencesClose(y_step_nan, y_step, rtol=rtol, atol=atol)
299
+
300
+ # 4. Time alignment.
301
+ # TODO(rryan): How? Layer specific. Maybe pad with a block size and verify
302
+ # a right shift?
303
+
304
+ # Return the input and layer-by-layer result so that tests can check for
305
+ # correctness.
306
+ return x_np, y_layer
307
+
308
+ def verify_masked(self, x: sl.Sequence):
309
+ zeros = tf.zeros_like(x.values)
310
+ invalid_mask = tf.broadcast_to(1.0 - x.expanded_mask(), tf.shape(x.values))
311
+ unmasked = tf.where(invalid_mask > 0.0, x.values, zeros)
312
+ self.assertAllEqual(unmasked, zeros)
313
+
314
+ def verify_tflite_step(
315
+ self,
316
+ l: sl.SequenceLayer,
317
+ x: sl.Sequence,
318
+ constants: sl.Constants = None,
319
+ allow_custom_ops: bool = False,
320
+ use_flex: bool = False,
321
+ rtol: float = 1e-7,
322
+ atol: float = 1e-7,
323
+ ):
324
+ """Builds a tf.lite model for a step and verifies identical outputs."""
325
+ if not l.supports_step:
326
+ return
327
+
328
+ if constants is None:
329
+ constants = {}
330
+
331
+ def fn(
332
+ x: sl.Sequence, state: sl.State, constants: sl.Constants
333
+ ) -> Tuple[sl.Sequence, sl.State]:
334
+ return l.step(x, state, training=False, constants=constants)
335
+
336
+ x_block_shape = tf.TensorShape(
337
+ [x.values.shape.dims[0].value, l.block_size]
338
+ ).concatenate(x.channel_shape)
339
+ x_block = self.random_sequence(
340
+ *x_block_shape.as_list(), dtype=x.values.dtype
341
+ )
342
+ s0 = l.get_initial_state(x_block, constants)
343
+ y_step_tf, s1_tf = l.step(x_block, s0, training=False, constants=constants)
344
+
345
+ tflite_model = tflite_convert(
346
+ fn,
347
+ input_templates=[x_block, s0, constants],
348
+ allow_custom_ops=allow_custom_ops,
349
+ use_flex=use_flex,
350
+ )
351
+
352
+ tflite_flat_outputs = evaluate_tflite_model(
353
+ tflite_model, tf.nest.flatten([x_block, s0, constants])
354
+ )
355
+ y_step_tflite, s1_tflite = tf.nest.pack_sequence_as(
356
+ [y_step_tf, s1_tf], tflite_flat_outputs
357
+ )
358
+
359
+ self.assertAllClose(
360
+ y_step_tflite.values, y_step_tf.values, rtol=rtol, atol=atol
361
+ )
362
+ self.assertAllEqual(y_step_tflite.mask, y_step_tf.mask)
363
+ tf.nest.map_structure(
364
+ lambda a, b: self.assertAllClose(a, b, rtol=rtol, atol=atol),
365
+ s1_tflite,
366
+ s1_tf,
367
+ )
368
+
369
+ def random_sequence(self, *args, **kwargs) -> sl.Sequence:
370
+ return random_sequence(*args, **kwargs)
371
+
372
+ def assertEmitsCompatible(self, emit_specs: sl.EmitSpecs, emits: sl.Emits):
373
+ tf.nest.assert_same_structure(emit_specs, emits)
374
+
375
+ def _check_spec(spec: tf.TensorSpec, emit: tf.Tensor):
376
+ actual_spec = tf.TensorSpec(emit.shape[2:], emit.dtype)
377
+ if not spec.is_compatible_with(actual_spec):
378
+ raise ValueError(
379
+ f"{emit}'s spec ({actual_spec}) does not match expected ({spec})."
380
+ )
381
+
382
+ tf.nest.map_structure(_check_spec, emit_specs, emits)
383
+
384
+ def assertSequencesClose(
385
+ self,
386
+ a: sl.Sequence,
387
+ b: sl.Sequence,
388
+ atol: float = 1e-6,
389
+ rtol: float = 1e-6,
390
+ msg: Optional[str] = None,
391
+ ):
392
+ """After padding, checks sequence values are close and masks are equal."""
393
+ a_time = a.values.shape[1]
394
+ b_time = b.values.shape[1]
395
+ max_time = max(a_time, b_time)
396
+ a = a.pad_time(0, max_time - a_time, valid=False)
397
+ b = b.pad_time(0, max_time - b_time, valid=False)
398
+ a, b = self.evaluate([a, b])
399
+ self.assertAllClose(a.values, b.values, atol=atol, rtol=rtol, msg=msg)
400
+ self.assertAllEqual(a.mask, b.mask)
401
+
402
+ def assertSequencesNotClose(
403
+ self,
404
+ a: sl.Sequence,
405
+ b: sl.Sequence,
406
+ atol: float = 1e-6,
407
+ rtol: float = 1e-6,
408
+ msg: Optional[str] = None,
409
+ ):
410
+ """After padding, check sequence values aren't close and masks are equal."""
411
+ a_time = a.values.shape[1]
412
+ b_time = b.values.shape[1]
413
+ max_time = max(a_time, b_time)
414
+ a = a.pad_time(0, max_time - a_time, valid=False)
415
+ b = b.pad_time(0, max_time - b_time, valid=False)
416
+ a, b = self.evaluate([a, b])
417
+ self.assertNotAllClose(a.values, b.values, atol=atol, rtol=rtol, msg=msg)
418
+ self.assertAllEqual(a.mask, b.mask)
419
+
420
+ def assertSequencesEqual(
421
+ self, a: sl.Sequence, b: sl.Sequence, msg: Optional[str] = None
422
+ ):
423
+ """After padding, checks sequence values are equal and masks are equal."""
424
+ a_time = a.values.shape[1]
425
+ b_time = b.values.shape[1]
426
+ max_time = max(a_time, b_time)
427
+ a = a.pad_time(0, max_time - a_time, valid=False)
428
+ b = b.pad_time(0, max_time - b_time, valid=False)
429
+ a, b = self.evaluate([a, b])
430
+ self.assertAllEqual(a.values, b.values, msg=msg)
431
+ self.assertAllEqual(a.mask, b.mask)
432
+
433
+ def assertSequencesNotEqual(
434
+ self, a: sl.Sequence, b: sl.Sequence, msg: Optional[str] = None
435
+ ):
436
+ """After padding, checks sequence values aren't equal, masks are equal."""
437
+ a_time = a.values.shape[1]
438
+ b_time = b.values.shape[1]
439
+ max_time = max(a_time, b_time)
440
+ a = a.pad_time(0, max_time - a_time, valid=False)
441
+ b = b.pad_time(0, max_time - b_time, valid=False)
442
+ a, b = self.evaluate([a, b])
443
+ self.assertNotAllEqual(a.values, b.values, msg=msg)
444
+ self.assertAllEqual(a.mask, b.mask)
445
+
446
+
447
+ def random_sequence(*dims, **kwargs) -> sl.Sequence:
448
+ """Generates a random Sequence with dims dimension.
449
+
450
+ Each batch item has a randomly generated length in [0, dims[1]) which is used
451
+ to compute the mask.
452
+
453
+ Args:
454
+ *dims: The dimensions of the sequence.
455
+ **kwargs: An optional "dtype" keyword argument.
456
+
457
+ Returns:
458
+ A Sequence with the specified dimensions and type. Invalid values timesteps
459
+ are masked.
460
+ """
461
+ # TODO(rryan): Once we switch to Python 3 add this as a kwarg.
462
+ dtype = kwargs.pop('dtype', tf.float32)
463
+ # If random_mask is disabled, default to random_lengths.
464
+ random_mask = kwargs.pop('random_mask', False)
465
+ random_lengths = kwargs.pop('random_lengths', not random_mask)
466
+ if random_mask and random_lengths:
467
+ raise ValueError('Must not specify random_mask and random_lengths.')
468
+ if len(dims) < 2:
469
+ raise ValueError(
470
+ 'random_sequence expects at least 2 dimensions, got: %s' % (dims,)
471
+ )
472
+ if dtype.is_complex:
473
+ np_values = np.random.normal(size=dims) + 1j * np.random.normal(size=dims)
474
+ elif dtype.is_integer:
475
+ low = kwargs.pop('low', 0)
476
+ high = kwargs.pop('high', 10)
477
+ np_values = np.random.randint(low, high, size=dims)
478
+ else:
479
+ np_values = np.random.normal(size=dims)
480
+
481
+ batch_size, time = dims[0], dims[1]
482
+ values = tf.convert_to_tensor(np_values.astype(dtype.as_numpy_dtype))
483
+ if random_mask:
484
+ mask = tf.cast(
485
+ np.random.uniform(size=(batch_size, time)) > 0.5, dtype=sl.MASK_DTYPE
486
+ )
487
+ else:
488
+ if time > 0:
489
+ if random_lengths:
490
+ low_length = kwargs.pop('low_length', 0)
491
+ high_length = kwargs.pop('high_length', time)
492
+ lengths = tf.convert_to_tensor(
493
+ np.random.randint(low_length, high_length, size=[batch_size]),
494
+ tf.int32,
495
+ )
496
+ else:
497
+ lengths = tf.fill(
498
+ [batch_size], tf.convert_to_tensor(time, dtype=tf.int32)
499
+ )
500
+ else:
501
+ lengths = tf.fill([batch_size], tf.convert_to_tensor(0, dtype=tf.int32))
502
+ mask = tf.sequence_mask(lengths, time, dtype=sl.MASK_DTYPE)
503
+ return sl.Sequence(values, mask).mask_invalid()
504
+
505
+
506
+ def tflite_convert(
507
+ fn: Callable[..., Any],
508
+ input_templates: List[Any],
509
+ allow_custom_ops: bool = False,
510
+ use_flex: bool = False,
511
+ ) -> bytes:
512
+ """Converts the provided fn to a tf.lite model.
513
+
514
+ Args:
515
+ fn: A callable that expects a list of inputs like input_templates that
516
+ returns a tensor or structure of tensors.
517
+ input_templates: A list of Tensors, ndarrays or TensorSpecs describing the
518
+ inputs that fn expects. The actual values of the Tensors or ndarrays are
519
+ unused.
520
+ allow_custom_ops: Whether to allow custom ops.
521
+ use_flex: Enable tf.lite flex ops. Requires linking
522
+ //third_party/tensorflow/lite/delegates/flex:delegate
523
+
524
+ Returns:
525
+ The serialized tf.lite model.
526
+ """
527
+ fn = tf.function(fn)
528
+ concrete_func = fn.get_concrete_function(*input_templates)
529
+ converter = tf.lite.TFLiteConverter([concrete_func])
530
+ converter.allow_custom_ops = allow_custom_ops
531
+ if use_flex:
532
+ converter.target_spec.supported_ops.add(tf.lite.OpsSet.SELECT_TF_OPS)
533
+ return converter.convert()
534
+
535
+
536
+ def evaluate_tflite_model(
537
+ tflite_model: bytes, input_ndarrays: List[np.ndarray]
538
+ ) -> List[np.ndarray]:
539
+ """Evaluates the provided tf.lite model with the given input ndarrays.
540
+
541
+ Args:
542
+ tflite_model: bytes. The serialized tf.lite model.
543
+ input_ndarrays: A list of NumPy arrays to feed as input to the model.
544
+
545
+ Returns:
546
+ A list of ndarrays produced by the model.
547
+
548
+ Raises:
549
+ ValueError: If the number of input arrays does not match the number of
550
+ inputs the model expects.
551
+ """
552
+ the_interpreter = tf.lite.Interpreter(model_content=tflite_model)
553
+ the_interpreter.allocate_tensors()
554
+
555
+ input_details = the_interpreter.get_input_details()
556
+ output_details = the_interpreter.get_output_details()
557
+
558
+ if len(input_details) != len(input_ndarrays):
559
+ raise ValueError(
560
+ 'Wrong number of inputs: provided=%s, '
561
+ 'input_details=%s output_details=%s'
562
+ % (input_ndarrays, input_details, output_details)
563
+ )
564
+ for input_tensor, data in zip(input_details, input_ndarrays):
565
+ the_interpreter.set_tensor(input_tensor['index'], data)
566
+ the_interpreter.invoke()
567
+ return [
568
+ the_interpreter.get_tensor(details['index']) for details in output_details
569
+ ]
570
+
571
+
572
+ def conv1d_mask(
573
+ mask: tf.Tensor,
574
+ kernel_size: int,
575
+ stride: int,
576
+ dilation_rate: int,
577
+ padding: str,
578
+ ) -> tf.Tensor:
579
+ """Output timesteps are valid iff they only touch valid input timesteps."""
580
+ if padding == sl.PaddingMode.SAME.value:
581
+ return tf.nn.conv1d(
582
+ mask[:, :, tf.newaxis],
583
+ tf.ones([1, 1, 1]),
584
+ stride=stride,
585
+ dilations=dilation_rate,
586
+ padding='VALID',
587
+ )[:, :, 0]
588
+ else:
589
+ if padding == sl.PaddingMode.CAUSAL.value:
590
+ # We assume causal padding has been applied outside of this method.
591
+ explicit_padding = (0, 0)
592
+ else:
593
+ explicit_padding = convolution_explicit_padding(
594
+ padding, kernel_size, dilation_rate
595
+ )
596
+
597
+ # Use conv2d since conv1d doesn't support explicit padding.
598
+ mask_golden = tf.nn.conv2d(
599
+ mask[:, :, tf.newaxis, tf.newaxis],
600
+ tf.ones([kernel_size, 1, 1, 1]),
601
+ strides=[stride, 1],
602
+ dilations=[dilation_rate, 1],
603
+ padding=[(0, 0), explicit_padding, (0, 0), (0, 0)],
604
+ )[:, :, 0, 0]
605
+ # Only timesteps that add up to kernel_size are valid.
606
+ return tf.cast(mask_golden > kernel_size - 1e-3, mask_golden.dtype)
607
+
608
+
609
+ def conv1d_transpose_mask(
610
+ mask: tf.Tensor, kernel_size: int, stride: int, padding: str
611
+ ) -> tf.Tensor:
612
+ """Output timesteps are valid iff they only touch valid input timesteps."""
613
+ padding = sl.validate_padding(padding)
614
+ if kernel_size <= stride or padding == 'same':
615
+ return tf.repeat(mask, stride, axis=1)
616
+ batch_size, time = tf.unstack(tf.shape(mask))
617
+ # Based on tf-keras (tf_keras/utils/conv_utils.py).
618
+ if padding == 'same':
619
+ output_time = time * stride
620
+ else:
621
+ output_time = time * stride + max(kernel_size - stride, 0)
622
+ # Upsample the "invalid" mask so we can tell which timesteps are affected by
623
+ # invalid timesteps.
624
+ mask_golden = tf.nn.conv2d_transpose(
625
+ 1.0 - mask[:, :, tf.newaxis, tf.newaxis],
626
+ tf.ones([kernel_size, 1, 1, 1]),
627
+ output_shape=[batch_size, output_time, 1, 1],
628
+ strides=stride,
629
+ padding='SAME' if padding == 'same' else 'VALID',
630
+ )[:, :, 0, 0]
631
+ # Any timesteps that have invalid timesteps "mixed" into them are invalid.
632
+ return tf.where(
633
+ mask_golden > 0.0, tf.zeros_like(mask_golden), tf.ones_like(mask_golden)
634
+ )
635
+
636
+
637
+ class AssertConstantsLayer(sl.StatelessPointwise):
638
+ """Identity layer that raises ValueError if 'test' is not in constants."""
639
+
640
+ def get_initial_state(
641
+ self, x: sl.Sequence, constants: sl.Constants = None
642
+ ) -> sl.State:
643
+ if constants is None or 'test' not in constants:
644
+ raise ValueError('constant not present')
645
+ return super(AssertConstantsLayer, self).get_initial_state(x, constants)
646
+
647
+ def get_output_shape(
648
+ self, x: sl.Sequence, constants: sl.Constants = None
649
+ ) -> tf.TensorShape:
650
+ if constants is None or 'test' not in constants:
651
+ raise ValueError('constant not present')
652
+ return super(AssertConstantsLayer, self).get_output_shape(x, constants)
653
+
654
+ def layer(
655
+ self,
656
+ x: sl.Sequence,
657
+ training: bool,
658
+ initial_state: sl.State = None,
659
+ constants: sl.Constants = None,
660
+ ) -> sl.Sequence:
661
+ del training
662
+ del initial_state
663
+ if constants is None or 'test' not in constants:
664
+ raise ValueError('constant not present')
665
+ return x
666
+
667
+
668
+ class NonSteppableLayer(sl.StatelessPointwise):
669
+ """A test layer that does not support stepping."""
670
+
671
+ @property
672
+ def supports_step(self):
673
+ return False
674
+
675
+ def layer(
676
+ self,
677
+ x: sl.Sequence,
678
+ training: bool,
679
+ initial_state: sl.State = None,
680
+ constants: sl.Constants = None,
681
+ ) -> sl.Sequence:
682
+ del training
683
+ del initial_state
684
+ del constants
685
+ return x
686
+
687
+
688
+ def rtol_atol_for_dtype(dtype: tf.DType) -> tuple[float, float]:
689
+ rtol_atol_for_size = {
690
+ 2: (1e-2, 1e-2),
691
+ 4: (1e-6, 1e-6),
692
+ }
693
+ assert dtype.is_floating
694
+ return rtol_atol_for_size[dtype.size]
695
+
696
+
697
+ @contextlib.contextmanager
698
+ def keras_precision_policy_scope(
699
+ policy: str | tf.keras.mixed_precision.Policy,
700
+ ):
701
+ old_policy = tf.keras.mixed_precision.global_policy()
702
+ try:
703
+ tf.keras.mixed_precision.set_global_policy(policy)
704
+ yield
705
+ finally:
706
+ tf.keras.mixed_precision.set_global_policy(old_policy)
707
+
708
+
709
+ def _flatten(structure):
710
+ """Wrapper around nest.flatten for TPU in/outfeeds.
711
+
712
+ Args:
713
+ structure: An arbitrarily nested structure or a scalar object.
714
+
715
+ Returns:
716
+ A Python list, the flattened version of the input.
717
+ """
718
+ flat_sequence = tf1.nest.flatten(structure)
719
+ # TODO(rryan): Handle tf1.SparseTensor.
720
+ return [
721
+ t
722
+ for t in flat_sequence
723
+ if t is not None and isinstance(t, tf1.Tensor) and t.dtype != tf1.string
724
+ ]
725
+
726
+
727
+ def _pack_sequence_as(template, flat_structure):
728
+ """Wrapper around nest.pack_sequence_as for TPU in/out-feeds.
729
+
730
+ Args:
731
+ template: Nested structure, whose structure is given by nested lists,
732
+ tuples, and dicts.
733
+ flat_structure: A flat sequence of tensors to pack into the same structure
734
+ as template.
735
+
736
+ Returns:
737
+ A structure with the same structure as template, but whose flattened form
738
+ equals flat_structure: i.e.
739
+ structure = _pack_sequence_as(template, flat_structure)
740
+ tf1.nest.assert_same_structure(structure, template)
741
+ tf1.nest.flatten(structure) == flat_structure
742
+ """
743
+ flat_template = tf1.nest.flatten(template)
744
+ fields = []
745
+ flat_structure = list(flat_structure)
746
+ for index, t in enumerate(flat_template):
747
+ if t is None or not isinstance(t, tf1.Tensor) or t.dtype == tf1.string:
748
+ # For non-Tensors, use the value from the template.
749
+ # TODO(rryan): Handle tf1.SparseTensor.
750
+ fields.append(t if not isinstance(t, tf1.Tensor) else None)
751
+ else:
752
+ entry = flat_structure.pop(0)
753
+ if entry.dtype != t.dtype:
754
+ raise ValueError(
755
+ (
756
+ 'flat_utterance dtype (%s) does not match the %d-th element'
757
+ ' of the template (%s).'
758
+ )
759
+ % (entry.dtype, index, t.dtype)
760
+ )
761
+ if t.shape.ndims == 0:
762
+ # Squeeze the entry because the template expects a scalar.
763
+ entry = tf1.squeeze(entry)
764
+ fields.append(entry)
765
+ return tf1.nest.pack_sequence_as(template, fields)
766
+
767
+
768
+ def structured_tpu_rewrite(
769
+ fn,
770
+ inputs: Optional[List[Any]] = None,
771
+ rewrite_fn=tf1.tpu.rewrite,
772
+ **rewrite_kwargs,
773
+ ):
774
+ """Call rewrite_fn on a function with non-Tensor or tf1.string inputs/outputs.
775
+
776
+ tpu.rewrite can only handle functions where every input/output element can be
777
+ converted to a tensor (and tf1.string is unsupported). This wrapper makes it
778
+ convenient to call on functions where some inputs or return values may
779
+ optionally be non-Tensors (protos, None, etc.) or tf1.string.
780
+
781
+ Args:
782
+ fn: A callable taking nested inputs and returning nested outputs.
783
+ inputs: Optional list of inputs to fn.
784
+ rewrite_fn: A replicating or sharding rewrite fn, such as tf1.tpu.rewrite or
785
+ tf1.tpu.batch_parallel, or tpu_utils.tpu_partitioned_call_rewrite_fn.
786
+ **rewrite_kwargs: kwargs to pass through to rewrite_fn.
787
+
788
+ Returns:
789
+ The outputs of the rewritten fn.
790
+ """
791
+ # List for capturing the true output structure from the user-provided fn.
792
+ output_template = []
793
+
794
+ def compute(*flat_inputs):
795
+ device_inputs = []
796
+ if inputs is not None:
797
+ device_inputs = _pack_sequence_as(inputs, flat_inputs)
798
+ ret = fn(*device_inputs)
799
+ output_template.append(ret)
800
+ return _flatten(ret)
801
+
802
+ flat_output_shapes = []
803
+
804
+ def batch_fn(*flat_inputs):
805
+ flat_outputs = rewrite_fn(compute, list(flat_inputs), **rewrite_kwargs)
806
+ flat_output_shapes.extend(t.shape for t in flat_outputs)
807
+ return flat_outputs
808
+
809
+ flat_inputs = _flatten(inputs) if inputs is not None else []
810
+ flat_outputs = batch_fn(*flat_inputs)
811
+ for t, shape in zip(flat_outputs, flat_output_shapes):
812
+ t.set_shape(shape)
813
+ return _pack_sequence_as(output_template[0], flat_outputs)
814
+
815
+
816
+ def convolution_explicit_padding(
817
+ padding: str, kernel_size: int, dilation_rate: int
818
+ ) -> tuple[int, int]:
819
+ """Returns the amount of padding to add for the desired padding mode."""
820
+ effective_kernel_size = (kernel_size - 1) * dilation_rate + 1
821
+ match padding:
822
+ case sl.PaddingMode.CAUSAL.value:
823
+ return (effective_kernel_size - 1, 0)
824
+ case sl.PaddingMode.REVERSE_CAUSAL.value:
825
+ return (0, effective_kernel_size - 1)
826
+ case sl.PaddingMode.SAME.value:
827
+ pad_amount = effective_kernel_size - 1
828
+ pad_left = pad_amount // 2
829
+ pad_right = pad_amount - pad_left
830
+ return pad_left, pad_right
831
+ case sl.PaddingMode.VALID.value:
832
+ return 0, 0
833
+ case _:
834
+ raise ValueError(f'Unsupported padding: {padding}')