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,858 @@
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
+ """Helper functions."""
15
+
16
+ import collections
17
+ import functools
18
+ from typing import Any, Callable, Iterable, List, Optional, Tuple, Union
19
+
20
+ import numpy as np
21
+ from sequence_layers.tensorflow import types
22
+ import tensorflow.compat.v2 as tf
23
+
24
+
25
+ def squeeze_mask(mask: tf.Tensor, factor: int) -> tf.Tensor:
26
+ with tf.name_scope('squeeze_mask'):
27
+ batch_size, time = smart_dimension_size(mask, [0, 1])
28
+ num_frames = (time + factor - 1) // factor
29
+ pad_amount = num_frames * factor - time
30
+ if isinstance(pad_amount, tf.Tensor) or pad_amount > 0:
31
+ mask = tf.pad(mask, [[0, 0], [0, pad_amount]])
32
+ mask = tf.reshape(mask, [batch_size, num_frames, factor])
33
+ return tf.reduce_min(mask, axis=2)
34
+
35
+
36
+ def unsqueeze_mask(mask: tf.Tensor, factor: int) -> tf.Tensor:
37
+ with tf.name_scope('unsqueeze_mask'):
38
+ batch_size, time = smart_dimension_size(mask)
39
+ return tf.reshape(
40
+ tf.tile(mask[:, :, tf.newaxis], [1, 1, factor]),
41
+ [batch_size, time * factor],
42
+ )
43
+
44
+
45
+ def convolution_effective_kernel_size(
46
+ kernel_size: int, dilation_rate: int
47
+ ) -> int:
48
+ """Returns kernel_size with dilation_rate holes inserted."""
49
+ return (kernel_size - 1) * dilation_rate + 1
50
+
51
+
52
+ def convolution_padding_output_size(
53
+ input_size: int,
54
+ padding: str,
55
+ kernel_size: int,
56
+ stride: int,
57
+ dilation_rate: int,
58
+ ) -> int:
59
+ """Returns the output size for a convolution over input_size."""
60
+ # Formula from: https://www.tensorflow.org/api_docs/python/tf/nn/convolution
61
+ # SAME: ceil(input_shape / stride)
62
+ # VALID: ceil((input_shape - (kernel_size - 1) * dilation_rate) / stride)
63
+ if padding in ('same', 'causal', 'reverse_causal'):
64
+ # Ceiling division.
65
+ return (input_size + stride - 1) // stride
66
+ else:
67
+ assert padding == 'valid'
68
+ output_size = input_size - (kernel_size - 1) * dilation_rate
69
+ # Ceiling division.
70
+ output_size = (output_size + stride - 1) // stride
71
+ return output_size
72
+
73
+
74
+ def convolution_explicit_padding(
75
+ padding: str, kernel_size: int, dilation_rate: int
76
+ ) -> tuple[int, int]:
77
+ """Returns explicit padding amounts to achieve the desired pad mode."""
78
+ effective_kernel_size = convolution_effective_kernel_size(
79
+ kernel_size, dilation_rate
80
+ )
81
+
82
+ if padding == types.PaddingMode.CAUSAL.value:
83
+ return effective_kernel_size - 1, 0
84
+ elif padding == types.PaddingMode.REVERSE_CAUSAL.value:
85
+ return 0, effective_kernel_size - 1
86
+ elif padding == types.PaddingMode.SAME.value:
87
+ pad_amount = effective_kernel_size - 1
88
+ left_padding = pad_amount // 2
89
+ right_padding = pad_amount - left_padding
90
+ return left_padding, right_padding
91
+ elif padding == types.PaddingMode.VALID.value:
92
+ return 0, 0
93
+ else:
94
+ raise ValueError(f'Unknown padding mode: {padding}')
95
+
96
+
97
+ def smart_dimension_size(
98
+ tensor: tf.Tensor, dim: Optional[Union[int, Iterable[int]]] = None
99
+ ):
100
+ """Return the sizes of one or more dimensions.
101
+
102
+ If the dimension size is known at graph construction time, then that value is
103
+ returned as an integer. Otherwise, the dynamic run-time size is returned as a
104
+ Tensor.
105
+
106
+ Args:
107
+ tensor: Tensor for which dimension sizes are to be computed.
108
+ dim: A Python int or iterable of ints, the dimensions to get the size of.
109
+ Integers may be negative to index from the back. If `None`, then the size
110
+ of all dimensions is returned.
111
+
112
+ Returns:
113
+ output: If dim is an int, a single value (int or scalar Tensor) is returned.
114
+ If dim is an iterable of ints, a tuple is returned containing the size
115
+ value for all dimensions in dim. If dim is `None`, then a tuple is
116
+ returned containing the size value for all dimensions.
117
+
118
+ Raises:
119
+ ValueError: If dim=None and tensor.shape.rank is None.
120
+ """
121
+ shape_tensor = tf.shape(tensor)
122
+
123
+ def get_dim(dim):
124
+ if tensor.shape.rank is not None:
125
+ dim_value = tf.compat.dimension_value(tensor.shape[dim])
126
+ if dim_value is not None:
127
+ return dim_value
128
+ return shape_tensor[dim]
129
+
130
+ if dim is None:
131
+ if tensor.shape.rank is None:
132
+ raise ValueError(
133
+ f'{tensor} rank must be known to extract all dimensions.'
134
+ )
135
+ return tuple(get_dim(d) for d in range(tensor.shape.rank))
136
+
137
+ # PyType is confused by using try/except TypeError to attempt to iterate dim.
138
+ if isinstance(dim, collections.abc.Iterable):
139
+ return tuple(get_dim(d) for d in dim)
140
+ else:
141
+ return get_dim(dim)
142
+
143
+
144
+ def step_by_step_fn_static(
145
+ transition_fn,
146
+ num_blocks: int,
147
+ input_block_size: int,
148
+ x: types.Sequence,
149
+ state: types.State,
150
+ ) -> Tuple[types.Sequence, types.State, types.Emits]:
151
+ """Sequentially applies transition_fn to blocks of x with static control flow.
152
+
153
+ Args:
154
+ transition_fn: A callable that takes a (Sequence, State) and returns a
155
+ (Sequence, State, Emits).
156
+ num_blocks: The number of blocks to split x into.
157
+ input_block_size: The size of each block.
158
+ x: The input (batch major) sequence to process.
159
+ state: The initial state.
160
+
161
+ Returns:
162
+ y: The output (batch major) sequence.
163
+ state: The state produced from the last block.
164
+ emits: The emits produced by transition_fn stacked across time.
165
+ """
166
+ # If static unrolling, run a for loop over num_blocks, strided slice
167
+ # the block from x, and run transition_fn to get the output block
168
+ # and next state.
169
+ output_blocks = []
170
+ output_emits = []
171
+
172
+ def read_block(b: int) -> types.Sequence:
173
+ start = b * input_block_size
174
+ end = start + input_block_size
175
+ return x[:, start:end]
176
+
177
+ for b in range(num_blocks):
178
+ x_block = read_block(b)
179
+ y_block, state, y_emit = transition_fn(x_block, state)
180
+ output_blocks.append(y_block)
181
+ output_emits.append(y_emit)
182
+
183
+ # Concatenate all timesteps.
184
+ output = types.Sequence.concatenate_sequences(output_blocks)
185
+ output_emits = tf.nest.map_structure(
186
+ lambda *ts: tf.concat(ts, axis=1), *output_emits
187
+ )
188
+ return output, state, output_emits
189
+
190
+
191
+ def _transpose_batch_and_time(
192
+ values: tf.Tensor, indices: List[int]
193
+ ) -> tf.Tensor:
194
+ """Swaps the batch and time dimension of values."""
195
+ return tf.transpose(values, [1, 0] + indices)
196
+
197
+
198
+ def _ta_scatter(ta, indices, values) -> tf.TensorArray:
199
+ """TODO(b/153504706): Replace with ta.scatter(indices, values)."""
200
+ for i in range(int(indices.shape[0])):
201
+ ta = ta.write(tf.gather(indices, i), tf.gather(values, i))
202
+ return ta
203
+
204
+
205
+ def _ta_gather(ta, indices) -> tf.Tensor:
206
+ """TODO(b/153504706): Replace with ta.gather(indices)."""
207
+ reads = []
208
+ for i in range(int(indices.shape[0])):
209
+ reads.append(ta.read(tf.gather(indices, i)))
210
+ return tf.stack(reads)
211
+
212
+
213
+ def step_by_step_fn_dynamic(
214
+ transition_fn,
215
+ input_time: Union[tf.Tensor, int],
216
+ input_shape: tf.TensorShape,
217
+ output_spec: tf.TensorSpec,
218
+ emit_specs: types.EmitSpecs,
219
+ num_blocks: Union[tf.Tensor, int],
220
+ input_block_size: int,
221
+ output_block_size: int,
222
+ x: types.Sequence,
223
+ state: types.State,
224
+ ) -> Tuple[types.Sequence, types.State, types.Emits]:
225
+ """Sequentially applies transition_fn to blocks of x with dynamic controlflow.
226
+
227
+ Args:
228
+ transition_fn: A callable that takes a (Sequence, State) and returns a
229
+ (Sequence, State, Emits).
230
+ input_time: The length of the input sequence.
231
+ input_shape: The shape of the channel dimensions of the input.
232
+ output_spec: A tf.TensorSpec for the channel dimensions of the output.
233
+ emit_specs: A nested structure of tf.TensorSpec produced by transition_fn.
234
+ num_blocks: The number of blocks to split x into.
235
+ input_block_size: The size of each input block.
236
+ output_block_size: The size of each output block.
237
+ x: The input (batch major) sequence to process.
238
+ state: The initial state.
239
+
240
+ Returns:
241
+ y: The output (batch major) sequence.
242
+ state: The state produced from the last block.
243
+ emits: The emits produced by the transition_fn stacked across time.
244
+ """
245
+ # Create a time-major TensorArray to store x's values and mask.
246
+ # TODO(rryan): Benchmark with and without a TensorArray for reads.
247
+ input_values_ta = tf.TensorArray(dtype=x.values.dtype, size=input_time)
248
+ input_mask_ta = tf.TensorArray(dtype=x.mask.dtype, size=input_time)
249
+
250
+ # The indices of the inner-dimensions of the input and output used for
251
+ # transposing batch and time dimensions of the input and output below.
252
+ input_shape_indices = list(range(2, 2 + input_shape.rank))
253
+ output_shape_indices = list(range(2, 2 + output_spec.shape.rank))
254
+ # Use TensorShape for the indices since nest doesn't flatten it.
255
+ emit_shapes_indices = tf.nest.map_structure(
256
+ lambda s: tf.TensorShape(range(2, 2 + s.shape.rank)), emit_specs
257
+ )
258
+
259
+ # Transpose values and mask to time-major and unstack into the TensorArrays.
260
+ input_values_time_major = _transpose_batch_and_time(
261
+ x.values, input_shape_indices
262
+ )
263
+ input_mask_time_major = _transpose_batch_and_time(x.mask, [])
264
+ input_values_ta = input_values_ta.unstack(input_values_time_major)
265
+ input_mask_ta = input_mask_ta.unstack(input_mask_time_major)
266
+
267
+ # Create time-major output TensorArrays to store blocks of the output
268
+ # sequence. The below while loop writes output_block_size entries at a time.
269
+ output_time = num_blocks * output_block_size
270
+ static_batch_size = x.values.shape.dims[0].value
271
+ output_values_ta = tf.TensorArray(
272
+ dtype=output_spec.dtype,
273
+ size=output_time,
274
+ element_shape=tf.TensorShape([static_batch_size]).concatenate(
275
+ output_spec.shape
276
+ ),
277
+ )
278
+ output_mask_ta = tf.TensorArray(
279
+ dtype=x.mask.dtype,
280
+ size=output_time,
281
+ element_shape=tf.TensorShape([static_batch_size]),
282
+ )
283
+
284
+ def _make_ta(s: tf.TensorSpec):
285
+ return tf.TensorArray(
286
+ dtype=s.dtype,
287
+ size=output_time,
288
+ element_shape=tf.TensorShape([static_batch_size]).concatenate(s.shape),
289
+ )
290
+
291
+ emit_tas = tf.nest.map_structure(_make_ta, emit_specs)
292
+
293
+ def read_block(b: tf.Tensor) -> types.Sequence:
294
+ """Reads batch-major Sequence block b from time-major input TensorArrays."""
295
+ start = b * input_block_size
296
+ # TPU compatible range.
297
+ input_indices = start + tf.range(input_block_size)
298
+ x_block_values_time_major = _ta_gather(input_values_ta, input_indices)
299
+ x_block_mask_time_major = _ta_gather(input_mask_ta, input_indices)
300
+ # Build a Sequence of batch-major values/mask for passing to transition_fn.
301
+ x_block = types.Sequence(
302
+ _transpose_batch_and_time(
303
+ x_block_values_time_major, input_shape_indices
304
+ ),
305
+ _transpose_batch_and_time(x_block_mask_time_major, []),
306
+ )
307
+
308
+ # TensorArray.gather can't tell that we're reading input_block_size samples.
309
+ def set_shape(v, m):
310
+ v.set_shape([None, input_block_size] + [None] * input_shape.rank)
311
+ m.set_shape([None, input_block_size])
312
+ return v, m
313
+
314
+ return x_block.apply(set_shape)
315
+
316
+ def write_block(
317
+ b: tf.Tensor,
318
+ y_block: types.Sequence,
319
+ emits: types.Emits,
320
+ values_ta: tf.TensorArray,
321
+ mask_ta: tf.TensorArray,
322
+ emit_tas: Union[tf.TensorArray, Any],
323
+ ) -> Tuple[tf.TensorArray, tf.TensorArray, Union[tf.TensorArray, Any]]:
324
+ """Writes batch-major Sequence block b to time-major values_ta / mask_ta."""
325
+ start = b * output_block_size
326
+ # TPU compatible range.
327
+ output_indices = start + tf.range(output_block_size)
328
+
329
+ y_block_values_time_major = _transpose_batch_and_time(
330
+ y_block.values, output_shape_indices
331
+ )
332
+ values_ta = _ta_scatter(
333
+ values_ta, output_indices, y_block_values_time_major
334
+ )
335
+
336
+ y_block_mask_time_major = _transpose_batch_and_time(y_block.mask, [])
337
+ mask_ta = _ta_scatter(mask_ta, output_indices, y_block_mask_time_major)
338
+
339
+ emits_time_major = tf.nest.map_structure(
340
+ lambda e, i: _transpose_batch_and_time(e, i.as_list()),
341
+ emits,
342
+ emit_shapes_indices,
343
+ )
344
+
345
+ def write_emit(emit_ta, emit_time_major):
346
+ return _ta_scatter(emit_ta, output_indices, emit_time_major)
347
+
348
+ emit_tas = tf.nest.map_structure(write_emit, emit_tas, emits_time_major)
349
+
350
+ return values_ta, mask_ta, emit_tas
351
+
352
+ def cond(b: tf.Tensor, *unused_args):
353
+ return b < num_blocks
354
+
355
+ def body(
356
+ b: tf.Tensor,
357
+ output_values_ta: tf.TensorArray,
358
+ output_mask_ta: tf.TensorArray,
359
+ emit_tas: Union[tf.TensorArray, Any],
360
+ state: types.State,
361
+ ):
362
+ """Performs the autoregressive loop."""
363
+ x_block = read_block(b)
364
+ y_block, state, y_emits = transition_fn(x_block, state)
365
+ output_values_ta, output_mask_ta, emit_tas = write_block(
366
+ b, y_block, y_emits, output_values_ta, output_mask_ta, emit_tas
367
+ )
368
+ return b + 1, output_values_ta, output_mask_ta, emit_tas, state
369
+
370
+ # Run a while loop for num_blocks timesteps. Each iteration:
371
+ # - reads input_block_size frames from input_values_ta / input_mask_ta
372
+ # - calls transition_fn(sequence, state)
373
+ # - writes the resulting output_block_size frames to
374
+ # output_values_ta / output_mask_ta
375
+ # - carries state over to the next iteration
376
+ _, output_values_ta, output_mask_ta, emit_tas, state = tf.while_loop(
377
+ cond,
378
+ body,
379
+ (0, output_values_ta, output_mask_ta, emit_tas, state),
380
+ maximum_iterations=num_blocks,
381
+ )
382
+
383
+ y = types.Sequence(
384
+ _transpose_batch_and_time(output_values_ta.stack(), output_shape_indices),
385
+ _transpose_batch_and_time(output_mask_ta.stack(), []),
386
+ )
387
+
388
+ emits_time_major = tf.nest.map_structure(
389
+ lambda emit_ta: emit_ta.stack(), emit_tas
390
+ )
391
+ emits = tf.nest.map_structure(
392
+ lambda e, i: _transpose_batch_and_time(e, i.as_list()),
393
+ emits_time_major,
394
+ emit_shapes_indices,
395
+ )
396
+ return y, state, emits
397
+
398
+
399
+ def _pad_to_multiple(
400
+ x: types.Sequence, block_size: int
401
+ ) -> Union[types.Sequence, tf.Tensor, tf.Tensor]:
402
+ """Pads x to multiple of block_size."""
403
+ time = smart_dimension_size(x.values, 1)
404
+ num_blocks = (time + block_size - 1) // block_size
405
+ padded_time = num_blocks * block_size
406
+ pad_amount = padded_time - time
407
+ x = x.pad_time(0, pad_amount, valid=False)
408
+ return x, padded_time, num_blocks
409
+
410
+
411
+ def step_by_step_static(
412
+ l: types.SequenceLayer,
413
+ x: types.Sequence,
414
+ training: bool,
415
+ initial_state: types.State = None,
416
+ blocks_per_step: int = 1,
417
+ constants: types.Constants = None,
418
+ ) -> Tuple[types.Sequence, types.State, types.Emits]:
419
+ """Executes a SequenceLayer timestep-by-timestep statically.
420
+
421
+ If the sequence length is not a multiple of l.block_size * blocks_per_step,
422
+ the sequence is padded to that length with invalid timesteps.
423
+
424
+ Args:
425
+ l: The SequenceLayer to invoke step-by-step.
426
+ x: The input Sequence to process step-by-step.
427
+ training: Whether we are in training mode.
428
+ initial_state: The initial state to use. If None, the initial state returned
429
+ by l.get_initial_state is used.
430
+ blocks_per_step: Runs the layer with this multiple of l.block_size timesteps
431
+ per step.
432
+ constants: The constants dictionary to provide to the step function.
433
+
434
+ Returns:
435
+ The resulting Sequence and emits.
436
+ """
437
+ if not l.supports_step:
438
+ raise ValueError(f'{l} cannot be stepped.')
439
+ if initial_state is None:
440
+ initial_state = l.get_initial_state(x, constants)
441
+ input_block_size = l.block_size * blocks_per_step
442
+ x, _, num_blocks = _pad_to_multiple(x, input_block_size)
443
+ transition_fn = functools.partial(
444
+ l.step_with_emits, training=training, constants=constants
445
+ )
446
+ outputs, state, emits = step_by_step_fn_static(
447
+ transition_fn, num_blocks, input_block_size, x, initial_state
448
+ )
449
+ return outputs, state, emits
450
+
451
+
452
+ def step_by_step_dynamic(
453
+ l: types.SequenceLayer,
454
+ x: types.Sequence,
455
+ training: bool,
456
+ initial_state: types.State = None,
457
+ blocks_per_step: int = 1,
458
+ constants: types.Constants = None,
459
+ ) -> Tuple[types.Sequence, types.State, types.Emits]:
460
+ """Executes a SequenceLayer timestep-by-timestep dynamically.
461
+
462
+ If the sequence length is not a multiple of l.block_size * blocks_per_step,
463
+ the sequence is padded to that length with invalid timesteps.
464
+
465
+ Args:
466
+ l: The SequenceLayer to invoke step-by-step.
467
+ x: The input Sequence to process step-by-step.
468
+ training: Whether we are in training mode.
469
+ initial_state: The initial state to use. If None, the initial state returned
470
+ by l.get_initial_state is used.
471
+ blocks_per_step: Runs the layer with this multiple of l.block_size timesteps
472
+ per step.
473
+ constants: The constants dictionary to provide to the step function.
474
+
475
+ Returns:
476
+ The resulting Sequence.
477
+ """
478
+ if not l.supports_step:
479
+ raise ValueError(f'{l} cannot be stepped.')
480
+
481
+ if initial_state is None:
482
+ initial_state = l.get_initial_state(x, constants)
483
+
484
+ output_spec = l.get_output_spec_for_sequence(x, constants)
485
+ emit_specs = l.get_emit_specs_for_sequence(x, constants)
486
+
487
+ input_block_size = l.block_size * blocks_per_step
488
+ output_block_size = int(input_block_size * l.output_ratio)
489
+ # Pad to a multiple of block_size timesteps.
490
+ x, time, num_blocks = _pad_to_multiple(x, input_block_size)
491
+
492
+ transition_fn = functools.partial(
493
+ l.step_with_emits, training=training, constants=constants
494
+ )
495
+
496
+ outputs, state, emits = step_by_step_fn_dynamic(
497
+ transition_fn,
498
+ time,
499
+ x.channel_shape,
500
+ output_spec,
501
+ emit_specs,
502
+ num_blocks,
503
+ input_block_size,
504
+ output_block_size,
505
+ x,
506
+ initial_state,
507
+ )
508
+ return outputs, state, emits
509
+
510
+
511
+ def _reshape_for_broadcast(
512
+ x: types.Sequence, y: types.Sequence
513
+ ) -> Tuple[types.Sequence, types.Sequence]:
514
+ """Reshapes channel dims of x and y to be broadcastable to each other."""
515
+ # The time dimensions may not match if we are broadcasting over time.
516
+ x.values.shape[:1].assert_is_compatible_with(y.values.shape[:1])
517
+ x.channel_shape.assert_is_fully_defined()
518
+ y.channel_shape.assert_is_fully_defined()
519
+ extra_dims = abs(x.channel_shape.rank - y.channel_shape.rank)
520
+
521
+ def _reshape(values: tf.Tensor) -> tf.Tensor:
522
+ batch_size, time = smart_dimension_size(values, [0, 1])
523
+ shape = [batch_size, time] + [1] * extra_dims + values.shape[2:].as_list()
524
+ return tf.reshape(values, shape)
525
+
526
+ if x.channel_shape.rank > y.channel_shape.rank:
527
+ y = y.apply_values(_reshape)
528
+ elif x.channel_shape.rank < y.channel_shape.rank:
529
+ x = x.apply_values(_reshape)
530
+ assert x.channel_shape.rank == y.channel_shape.rank
531
+ return x, y
532
+
533
+
534
+ def sequence_broadcast_add(
535
+ x: types.Sequence, y: types.Sequence
536
+ ) -> types.Sequence:
537
+ """Broadcast-add x and y."""
538
+ x, y = _reshape_for_broadcast(x, y)
539
+ return types.Sequence(x.values + y.values, combine_mask(x.mask, y.mask))
540
+
541
+
542
+ def sequence_broadcast_concat(
543
+ x: types.Sequence, y: types.Sequence
544
+ ) -> types.Sequence:
545
+ """Broadcast-concatenate x and y."""
546
+ x, y = _reshape_for_broadcast(x, y)
547
+ channel_outer_dims_broadcast_shape = tf.broadcast_static_shape(
548
+ x.channel_shape[:-1], y.channel_shape[:-1]
549
+ )
550
+
551
+ batch_size, time = smart_dimension_size(x.values, [0, 1])
552
+
553
+ def _broadcast_channel_outer_dims(values):
554
+ # Expand dim 2D tensors for concatenation.
555
+ if values.shape.rank == 2 and channel_outer_dims_broadcast_shape.rank == 0:
556
+ values = values[..., tf.newaxis]
557
+ shape = (
558
+ [batch_size, time]
559
+ + channel_outer_dims_broadcast_shape.as_list()
560
+ + [values.shape[-1]]
561
+ )
562
+ return tf.broadcast_to(values, shape)
563
+
564
+ x_values = _broadcast_channel_outer_dims(x.values)
565
+ y_values = _broadcast_channel_outer_dims(y.values)
566
+ return types.Sequence(
567
+ tf.concat([x_values, y_values], -1), combine_mask(x.mask, y.mask)
568
+ )
569
+
570
+
571
+ def sequence_broadcast_affine(
572
+ x: types.Sequence, scale: types.Sequence, shift: types.Sequence
573
+ ) -> types.Sequence:
574
+ """Affine transform of x."""
575
+ x, scale = _reshape_for_broadcast(x, scale)
576
+ x, shift = _reshape_for_broadcast(x, shift)
577
+ values = x.values * scale.values + shift.values
578
+ # Scale and shift are often derived from the same sequence so combine their
579
+ # mask first as an optimization.
580
+ mask = combine_mask(x.mask, combine_mask(scale.mask, shift.mask))
581
+ return types.Sequence(values, mask)
582
+
583
+
584
+ def dynamic_filter_conv1d(inputs, filters, stride=1, padding='SAME'):
585
+ """Apply different 1d convolution filters to each batch member.
586
+
587
+ The `filters` tensor has a batch dimension that determines which filters
588
+ are applied to the input from each batch member.
589
+
590
+ Args:
591
+ inputs: A [batch, in_width, in_channels] input tensor.
592
+ filters: A [batch, filt_width, in_channels, out_channels] filter tensor.
593
+ stride: The convolution stride as an int (default=1).
594
+ padding: A str that determines the padding mode (default='SAME').
595
+
596
+ Returns:
597
+ outputs: A [batch, out_width, out_channels] output tensor.
598
+ """
599
+ with tf.name_scope('dynamic_filter_conv1d'):
600
+ # Group the batch and in_chan dimensions together for the filters.
601
+ # [B, Wf, Ci, Co]
602
+ batch, filt_width, in_chan, out_chan = smart_dimension_size(filters)
603
+ # [B, Wf, Ci, Co] -> [Wf, B, Ci, Co]
604
+ filters = tf.transpose(filters, [1, 0, 2, 3])
605
+ # [W, B, Ci, Co] -> [H=1, Wf, B*Ci, Co]
606
+ filters = tf.reshape(filters, [1, filt_width, batch * in_chan, out_chan])
607
+
608
+ # Group the batch and in_chan dimensions together for the input.
609
+ # [B, Wi, Ci]
610
+ batch, in_width, in_chan = smart_dimension_size(inputs)
611
+ # [B, Wi, Ci] -> [W, B, Ci]
612
+ inputs = tf.transpose(inputs, [1, 0, 2])
613
+ # [Wi, B, Ci] -> [1, H=1, Wi, B*Ci] (Singleton leading batch dimension).
614
+ inputs = tf.reshape(inputs, [1, 1, in_width, batch * in_chan])
615
+
616
+ # Depthwise convolution with grouped batch and channel dims.
617
+ # [1, H=1, Wi, B*Ci] -> [1, H=1, Wo, B*Ci*Co]
618
+ outputs = tf.nn.depthwise_conv2d(
619
+ inputs, filters, strides=(1, 1, stride, 1), padding=padding
620
+ )
621
+
622
+ # Ungroup the batch and channel dimensions.
623
+ # [1, H=1, Wo, B*Ci*Co]
624
+ _, _, out_width, _ = smart_dimension_size(outputs)
625
+ # [1, H=1, Wo, B*Ci*Co] -> [Wo, B, Ci, Co]
626
+ outputs = tf.reshape(outputs, [out_width, batch, in_chan, out_chan])
627
+ # [Wo, B, Ci, Co] -> [B, Wo, Ci, Co]
628
+ outputs = tf.transpose(outputs, [1, 0, 2, 3])
629
+
630
+ # Sum across input channels after separating from batch dim.
631
+ # [B, Wo, Ci, Co] -> [B, Wo, Co]
632
+ outputs = tf.reduce_sum(outputs, axis=2)
633
+
634
+ return outputs
635
+
636
+
637
+ def log_without_underflow(
638
+ inputs: tf.Tensor, min_output: float, min_input: float | None = None
639
+ ) -> tf.Tensor:
640
+ """Natural logarithm preventing underflow.
641
+
642
+ Args:
643
+ inputs: Input tensor.
644
+ min_output: Minimum output value.
645
+ min_input: Minimum value that should be passed through the log function (a
646
+ positive number that won't lead to log underflow).
647
+
648
+ Returns:
649
+ outputs: The element-wise log of inputs. Outputs for input values less than
650
+ min_input are set to min_output.
651
+
652
+ Raises:
653
+ ValueError: If log(min_input) is less than min_output.
654
+ """
655
+ with tf.name_scope('log_without_underflow'):
656
+ if min_input is None:
657
+ # Smallest value that doesn't lead to log underflow for float32.
658
+ min_input = 1.775e-38
659
+
660
+ if np.log(min_input) < min_output:
661
+ raise ValueError('log(min_input) must not be less than min_output.')
662
+
663
+ outputs = tf.math.log(tf.maximum(inputs, min_input))
664
+ outputs = tf.where(inputs >= min_input, outputs, min_output)
665
+
666
+ return outputs
667
+
668
+
669
+ def combine_mask(x: tf.Tensor, y: tf.Tensor) -> tf.Tensor:
670
+ """Combines mask x and y (float32, shaped [b, t]) in a logical AND fashion."""
671
+ if x.dtype != types.MASK_DTYPE or x.shape.rank != 2:
672
+ raise ValueError(f'Expected x as a [b, t] float32 tensor, got: {x}')
673
+ if y.dtype != types.MASK_DTYPE or y.shape.rank != 2:
674
+ raise ValueError(f'Expected y as a [b, t] float32 tensor, got: {y}')
675
+ if x is y:
676
+ return x
677
+ return x * y
678
+
679
+
680
+ class LambdaTensor:
681
+
682
+ def __init__(self, value_fn: Callable[[], tf.Tensor]):
683
+ self._value_fn = value_fn
684
+
685
+ def to_tensor(self) -> tf.Tensor:
686
+ return self._value_fn()
687
+
688
+
689
+ def _lambdatensor_to_tensor(
690
+ value: LambdaTensor,
691
+ dtype: Optional[tf.DType] = None,
692
+ name: Optional[str] = None,
693
+ as_ref: bool = False,
694
+ ) -> tf.Tensor:
695
+ del as_ref
696
+ return tf.convert_to_tensor(value.to_tensor(), dtype=dtype, name=name)
697
+
698
+
699
+ tf.register_tensor_conversion_function(LambdaTensor, _lambdatensor_to_tensor)
700
+
701
+
702
+ class WeightNorm(tf.keras.layers.Wrapper):
703
+ """Decouple weight magnitude and direction.
704
+
705
+ Modified from tensor2tensor/tensor2tensor/layers/common_layers.py.
706
+
707
+ This wrapper reparameterizes a layer by decoupling the weight's
708
+ magnitude and direction. This speeds up convergence by improving the
709
+ conditioning of the optimization problem.
710
+
711
+ Weight Normalization: A Simple Reparameterization to Accelerate
712
+ Training of Deep Neural Networks: https://arxiv.org/abs/1602.07868
713
+ Tim Salimans, Diederik P. Kingma (2016)
714
+
715
+ Raises:
716
+ ValueError: If not initialized with a `Layer` instance.
717
+ ValueError: If `Layer` does not contain a `kernel` of weights
718
+ """
719
+
720
+ def __init__(self, layer: tf.keras.layers.Layer, **kwargs):
721
+ if not isinstance(layer, tf.keras.layers.Layer):
722
+ raise ValueError(
723
+ 'Please initialize `WeightNorm` layer with a '
724
+ '`Layer` instance. You passed: {input}'.format(input=layer)
725
+ )
726
+ super().__init__(layer, **kwargs)
727
+ self._track_trackable(layer, name='layer')
728
+
729
+ def _compute_weights(self) -> tf.Tensor:
730
+ """Generate weights with normalization."""
731
+ with tf.name_scope('compute_weights'):
732
+ return (
733
+ tf.nn.l2_normalize(self.layer.v, axis=self.norm_axes) * self.layer.g
734
+ )
735
+
736
+ def build(self, input_shape: Optional[tf.TensorShape] = None) -> None:
737
+ """Build `Layer`."""
738
+ if not self.layer.built:
739
+ self.layer.build(input_shape)
740
+ self.layer.built = False
741
+
742
+ if not hasattr(self.layer, 'kernel'):
743
+ raise ValueError(
744
+ '`WeightNorm` must wrap a layer that'
745
+ ' contains a `kernel` for weights'
746
+ )
747
+
748
+ # The kernel's filter or unit dimension is -1
749
+ self.layer_depth = int(self.layer.kernel.shape[-1])
750
+ self.norm_axes = list(range(self.layer.kernel.shape.rank - 1))
751
+
752
+ self.layer.v = self.layer.kernel
753
+ self.layer.g = self.layer.add_weight(
754
+ name='g',
755
+ shape=(self.layer_depth,),
756
+ initializer=tf.ones_initializer,
757
+ dtype=self.layer.kernel.dtype,
758
+ trainable=True,
759
+ )
760
+
761
+ # Replace the kernel with a LambdaTensor, which is converted to a tensor
762
+ # on the fly when evaluated with tf.convert_to_tensor, but does not store
763
+ # graph-specific tensors as member variables.
764
+ self.layer.kernel = LambdaTensor(self._compute_weights)
765
+
766
+ self.layer.built = True
767
+ self.input_spec = self.layer.input_spec
768
+
769
+ super().build()
770
+ assert self.built
771
+
772
+ def call(self, inputs: tf.Tensor) -> tf.Tensor:
773
+ return self.layer.call(inputs)
774
+
775
+ def compute_output_shape(self, input_shape: tf.TensorShape) -> tf.TensorShape:
776
+ return tf.TensorShape(
777
+ self.layer.compute_output_shape(input_shape).as_list()
778
+ )
779
+
780
+
781
+ def compute_dtype() -> tf.DType:
782
+ """Returns the global Keras precision policy's compute dtype."""
783
+ # In TF1, compute_dtype is None.
784
+ return tf.as_dtype(
785
+ tf.keras.mixed_precision.global_policy().compute_dtype or 'float32'
786
+ )
787
+
788
+
789
+ def variable_dtype() -> tf.DType:
790
+ """Returns the global Keras precision policy's variable dtype."""
791
+ # In TF1, variable_dtype is None.
792
+ return tf.as_dtype(
793
+ tf.keras.mixed_precision.global_policy().variable_dtype or 'float32'
794
+ )
795
+
796
+
797
+ def slice_and_pad_tensor(
798
+ tensor: tf.Tensor,
799
+ slices: list[tuple[int, tf.Tensor | int, int]],
800
+ pad_value: float,
801
+ tensor_is_pre_padded: bool,
802
+ name: str,
803
+ ) -> tf.Tensor:
804
+ """Slices tensor on multiple axes, padding to a specified size.
805
+
806
+ TODO(b/298748783): This function assumes tensor is of at least length (start +
807
+ length) on all axes to slice.
808
+
809
+ Args:
810
+ tensor: The tensor to slice and pad.
811
+ slices: A list of (axis, start, length) of slices to perform.
812
+ pad_value: A value to pad with when the tensor slice is incomplete.
813
+ tensor_is_pre_padded: Workaround for b/298748783. If true, avoids a dynamic
814
+ slice.
815
+ name: A name for this slice.
816
+
817
+ Returns:
818
+ A tensor with all axes in slices sliced and padded to the specified length.
819
+ """
820
+ with tf.name_scope(name):
821
+ rank = tensor.shape.rank
822
+ begin = [0] * rank
823
+ size = [-1] * rank
824
+ paddings = [[0, 0]] * rank
825
+ shape = smart_dimension_size(tensor)
826
+ static_shape = tensor.shape.as_list()
827
+
828
+ for slice_axis, slice_start, slice_length in slices:
829
+ assert isinstance(slice_axis, int)
830
+ assert isinstance(slice_length, int)
831
+ axis_size = shape[slice_axis]
832
+ begin[slice_axis] = slice_start
833
+ if (
834
+ isinstance(slice_start, int)
835
+ and isinstance(slice_length, int)
836
+ and isinstance(axis_size, int)
837
+ ):
838
+ size[slice_axis] = min(axis_size - slice_start, slice_length)
839
+ else:
840
+ # TODO(b/298748783): The slice will fail if slice_length elements are
841
+ # not available.
842
+ if tensor_is_pre_padded:
843
+ size[slice_axis] = slice_length
844
+ else:
845
+ size[slice_axis] = tf.minimum(axis_size - slice_start, slice_length)
846
+
847
+ paddings[slice_axis] = [0, slice_length - size[slice_axis]]
848
+ static_shape[slice_axis] = slice_length
849
+
850
+ chunk = tf.slice(tensor, begin, size)
851
+ chunk = tf.pad(
852
+ chunk, paddings, constant_values=tf.constant(pad_value, tensor.dtype)
853
+ )
854
+
855
+ # Check that the slice succeeds.
856
+ chunk = tf.ensure_shape(chunk, static_shape)
857
+
858
+ return chunk