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,644 @@
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
+ """Conditioning layers."""
15
+
16
+ import enum
17
+ from typing import Optional, Tuple, Union
18
+
19
+ from sequence_layers.tensorflow import dense
20
+ from sequence_layers.tensorflow import simple
21
+ from sequence_layers.tensorflow import types
22
+ from sequence_layers.tensorflow import utils
23
+ import tensorflow.compat.v2 as tf
24
+
25
+
26
+ def _get_conditioning(
27
+ layer: types.SequenceLayer,
28
+ conditioning_name: str,
29
+ constants: types.Constants,
30
+ ) -> Union[tf.Tensor, types.Sequence]:
31
+ """Gets the conditioning from constants and does basic validation."""
32
+ if constants is None:
33
+ raise ValueError(
34
+ f'{layer} requires the conditioning to be provided via '
35
+ f'constants, got: {constants}'
36
+ )
37
+ conditioning = constants.get(conditioning_name)
38
+ if conditioning is None:
39
+ raise ValueError(
40
+ f'{layer} expected {conditioning_name} to be present in '
41
+ f'constants, got: {constants}'
42
+ )
43
+ elif isinstance(conditioning, tf.Tensor):
44
+ # Conditioning is expected to be [batch_size, ...] where ... is conditioning
45
+ # information for the channels of the input sequence. Bare tensors cannot be
46
+ # treated as sequences.
47
+ conditioning.shape[1:].assert_is_fully_defined()
48
+ elif isinstance(conditioning, types.Sequence):
49
+ conditioning.channel_shape.assert_is_fully_defined()
50
+ else:
51
+ raise ValueError(f'Unexpected conditioning of type: {type(conditioning)}')
52
+ return conditioning
53
+
54
+
55
+ def _time_slice(
56
+ x: types.Sequence,
57
+ begin: tf.Tensor,
58
+ size: tf.Tensor,
59
+ name: Optional[str] = None,
60
+ ) -> types.Sequence:
61
+ """Gathers a slice of time dimension of the sequence."""
62
+ with tf.name_scope(name or 'time_slice'):
63
+ begin = tf.convert_to_tensor(begin, name='begin')
64
+ size = tf.convert_to_tensor(size, name='size')
65
+ begin.shape.assert_has_rank(0)
66
+ size.shape.assert_has_rank(0)
67
+ time = utils.smart_dimension_size(x.values, 1)
68
+
69
+ available = tf.maximum(time - begin, 0)
70
+ valid_size = tf.minimum(size, available)
71
+
72
+ # Use tf.range(size) and clip indices that are out of range instead of
73
+ # tf.range(valid_size) so that shapes are fixed (therefore TPU compatible).
74
+ # TODO(rryan): Handle zero length?
75
+ time_indices = tf.minimum(begin + tf.range(size), tf.maximum(0, time - 1))
76
+ time_indices.shape.assert_has_rank(1)
77
+
78
+ # Make a mask that is zero if the index went beyond the end.
79
+ valid_mask = tf.sequence_mask([valid_size], size, dtype=types.MASK_DTYPE)
80
+
81
+ return types.Sequence(
82
+ tf.gather(x.values, time_indices, axis=1),
83
+ valid_mask * tf.gather(x.mask, time_indices, axis=1),
84
+ )
85
+
86
+
87
+ def _upsample_tensor(x: tf.Tensor, upsample_ratio: int) -> tf.Tensor:
88
+ """Upsample x by a factor of upsample_ratio (simply repeating)."""
89
+ with tf.name_scope('upsample_tensor'):
90
+ x = tf.convert_to_tensor(x)
91
+ x.shape.with_rank_at_least(2)
92
+ if upsample_ratio == 1:
93
+ return x
94
+ return tf.repeat(x, upsample_ratio, axis=1)
95
+
96
+
97
+ def _tensor_to_fake_sequence(t: tf.Tensor) -> types.Sequence:
98
+ batch_size = utils.smart_dimension_size(t, 0)
99
+ return types.Sequence(
100
+ t[:, tf.newaxis],
101
+ tf.fill([batch_size, 1], tf.constant(1.0, dtype=types.MASK_DTYPE)),
102
+ )
103
+
104
+
105
+ class BaseConditioning(types.SequenceLayer):
106
+ """Base class for conditioning types."""
107
+
108
+ @enum.unique
109
+ class Projection(enum.Enum):
110
+ """The type of projection to perform."""
111
+
112
+ # No projection.
113
+ IDENTITY = 1
114
+ # Dense projection from every element of c at a given time step, to a tensor
115
+ # of the same shape as x at given time step (c.channel_shape.num_elements()
116
+ # to x.channel_shape.num_elements()).
117
+ LINEAR = 2
118
+ # Dense projection from every element of c at a given time step, to a tensor
119
+ # of shape [2, x.shape...] at given time step (
120
+ # c.channel_shape.num_elements() to 2 * x.channel_shape.num_elements()).
121
+ LINEAR_AFFINE = 3
122
+
123
+ @enum.unique
124
+ class Combination(enum.Enum):
125
+ """The type of combination to perform."""
126
+
127
+ # Broadcast-add conditioning.
128
+ ADD = 1
129
+ # Broadcast-concat conditioning.
130
+ CONCAT = 2
131
+ # Affine conditioning. Requires LINEAR_AFFINE projection.
132
+ AFFINE = 3
133
+
134
+ def __init__(
135
+ self,
136
+ conditioning_name: str | None,
137
+ projection: Projection,
138
+ combination: Combination,
139
+ name: Optional[str] = None,
140
+ ):
141
+ super().__init__(name=name)
142
+ self._conditioning_name = conditioning_name
143
+ self._projection = projection
144
+ self._combination = combination
145
+ self._dense_shaped = None
146
+ self._projection_fn = None
147
+ self._built = False
148
+
149
+ if (
150
+ combination == self.Combination.AFFINE
151
+ and projection != self.Projection.LINEAR_AFFINE
152
+ ):
153
+ raise ValueError('AFFINE combination requires LINEAR_AFFINE projection.')
154
+
155
+ def _projected_condition_shape(
156
+ self, input_shape: tf.TensorShape, condition_shape: tf.TensorShape
157
+ ) -> tf.TensorShape:
158
+ return {
159
+ self.Projection.IDENTITY: condition_shape,
160
+ self.Projection.LINEAR: input_shape,
161
+ self.Projection.LINEAR_AFFINE: tf.TensorShape([2]).concatenate(
162
+ input_shape
163
+ ),
164
+ }[self._projection]
165
+
166
+ def _get_conditioning_channel_shape(
167
+ self, constants: types.Constants
168
+ ) -> tf.TensorShape:
169
+ conditioning = _get_conditioning(self, self._conditioning_name, constants)
170
+ # PyType is confused by isinstance(conditioning, tf.Tensor).
171
+ if isinstance(conditioning, types.Sequence):
172
+ return conditioning.channel_shape
173
+ else:
174
+ return conditioning.shape[1:]
175
+
176
+ def get_output_shape(
177
+ self,
178
+ input_shape: tf.TensorShape,
179
+ constants: Optional[types.Constants] = None,
180
+ ) -> tf.TensorShape:
181
+ input_shape.assert_is_fully_defined()
182
+ conditioning_channel_shape = self._get_conditioning_channel_shape(constants)
183
+ projected_conditioning_shape = self._projected_condition_shape(
184
+ input_shape, conditioning_channel_shape
185
+ )
186
+ if self._combination == self.Combination.ADD:
187
+ return tf.broadcast_static_shape(
188
+ input_shape, projected_conditioning_shape
189
+ )
190
+ elif self._combination == self.Combination.CONCAT:
191
+ input_inner_dim = input_shape[-1] if input_shape.rank else 1
192
+ projected_conditioning_inner_dim = (
193
+ projected_conditioning_shape[-1]
194
+ if projected_conditioning_shape.rank
195
+ else 1
196
+ )
197
+ output_inner_dim = input_inner_dim + projected_conditioning_inner_dim
198
+ output_outer_shape = tf.broadcast_static_shape(
199
+ input_shape[:-1], projected_conditioning_shape[:-1]
200
+ )
201
+ return output_outer_shape + output_inner_dim
202
+ elif self._combination == self.Combination.AFFINE:
203
+ projected_conditioning_shape = projected_conditioning_shape[1:]
204
+ return tf.broadcast_static_shape(
205
+ input_shape, projected_conditioning_shape
206
+ )
207
+ else:
208
+ raise ValueError(f'Unsupported combination: {self._combination}')
209
+
210
+ def _build(
211
+ self, input_shape: tf.TensorShape, conditioning_shape: tf.TensorShape
212
+ ):
213
+ if self._built:
214
+ return
215
+ self._built = True
216
+ if self._projection == self.Projection.LINEAR:
217
+ self._dense_shaped = dense.DenseShaped(input_shape, name='dense')
218
+ linear_projection = self._dense_shaped.layer
219
+ elif self._projection == self.Projection.LINEAR_AFFINE:
220
+ self._dense_shaped = dense.DenseShaped(
221
+ tf.TensorShape([2]).concatenate(input_shape), name='dense'
222
+ )
223
+ linear_projection = self._dense_shaped.layer
224
+ else:
225
+ linear_projection = None
226
+ self._projection_fn = {
227
+ self.Projection.IDENTITY: lambda s, _: s,
228
+ self.Projection.LINEAR: linear_projection,
229
+ self.Projection.LINEAR_AFFINE: linear_projection,
230
+ }[self._projection]
231
+
232
+ def _project(
233
+ self, conditioning: types.Sequence, training: bool
234
+ ) -> types.Sequence:
235
+ if self._projection_fn is None:
236
+ raise ValueError('self._projection_fn is None, _build() not called')
237
+ return self._projection_fn(conditioning, training)
238
+
239
+ def _combine(
240
+ self, x: types.Sequence, conditioning: types.Sequence
241
+ ) -> types.Sequence:
242
+ def _affine_fn(x, conditioning):
243
+ scale, shift = tf.unstack(conditioning.values, axis=2)
244
+ # Offset scale by 1.0
245
+ scale = types.Sequence(1.0 + scale, conditioning.mask)
246
+ shift = types.Sequence(shift, conditioning.mask)
247
+ return utils.sequence_broadcast_affine(x, scale, shift)
248
+
249
+ return {
250
+ self.Combination.ADD: utils.sequence_broadcast_add,
251
+ self.Combination.CONCAT: utils.sequence_broadcast_concat,
252
+ self.Combination.AFFINE: _affine_fn,
253
+ }[self._combination](x, conditioning).mask_invalid()
254
+
255
+
256
+ class Conditioning(BaseConditioning):
257
+ """Conditions the sequence x on a conditioning sequence c.
258
+
259
+ Conditioning is done in a time-synchronized way, where each time step of x is
260
+ conditioned on the corresponding time step of c.
261
+
262
+ Conditioning is defined as Combine(x, Project(c)), where supported projection
263
+ and combination functions are available in Projection and Combination enums
264
+ above.
265
+
266
+ All valid broadcasts between x and c channel_shapes are supported, e.g.:
267
+ - Projection=IDENTITY, Combination=ADD:
268
+ - (x: [b, t_x, 3], c: [b, t_c, 3]) -> c_x: [b, t_x, 3]
269
+ - (x: [b, t_x, 3, 1, 5], c: [b, t_c, 2, 5]) -> c_x: [b, t_x, 3, 2, 5]
270
+ - Projection=IDENTITY, Combination=CONCAT:
271
+ - (x: [b, t_x, 3], c: [b, t_c, 7]) -> c_x: [b, t_x, 10]
272
+ - (x: [b, t_x, 3, 1, 5], c: [b, t_c, 2, 7]) -> c_x: [b, t_x, 3, 2, 12]
273
+ - Projection=LINEAR, Combination=ADD:
274
+ - (x: [b, t_x, 3], c: [b, t_c, 7]) -> c_x: [b, t_x, 3]
275
+ - (x: [b, t_x, 3, 1, 5], c: [b, t_c, 2, 7]) -> c_x: [b, t_x, 3, 1, 5]
276
+ - Projection=LINEAR, Combination=CONCAT:
277
+ - (x: [b, t_x, 3], c: [b, t_c, 7]) -> c_x: [b, t_x, 6]
278
+ - (x: [b, t_x, 3, 1, 5], c: [b, t_c, 2, 7]) -> c_x: [b, t_x, 3, 1, 10]
279
+
280
+ Where t_x = t_c. For t_x != t_c, see UpsampleConditioning.
281
+ """
282
+
283
+ def get_initial_state(
284
+ self, x: types.Sequence, constants: Optional[types.Constants] = None
285
+ ) -> types.State:
286
+ conditioning = _get_conditioning(self, self._conditioning_name, constants)
287
+ if isinstance(conditioning, types.Sequence):
288
+ return tf.convert_to_tensor(0, dtype=tf.int32)
289
+ else:
290
+ return ()
291
+
292
+ @tf.Module.with_name_scope
293
+ def layer(
294
+ self,
295
+ x: types.Sequence,
296
+ training: bool,
297
+ initial_state: Optional[types.State] = None,
298
+ constants: Optional[types.Constants] = None,
299
+ ) -> types.Sequence:
300
+ conditioning = _get_conditioning(self, self._conditioning_name, constants)
301
+ # PyType is confused by isinstance(conditioning, tf.Tensor).
302
+ if not isinstance(conditioning, types.Sequence):
303
+ conditioning = _tensor_to_fake_sequence(conditioning)
304
+ broadcasted_shape = tf.broadcast_static_shape(
305
+ x.values.shape[:2], conditioning.values.shape[:2]
306
+ )
307
+ x.values.shape[:2].assert_is_compatible_with(broadcasted_shape)
308
+ self._build(x.channel_shape, conditioning.channel_shape)
309
+ conditioned_x = self._combine(x, self._project(conditioning, training))
310
+ return conditioned_x
311
+
312
+ @tf.Module.with_name_scope
313
+ def step(
314
+ self,
315
+ x: types.Sequence,
316
+ state: types.State,
317
+ training: bool,
318
+ constants: Optional[types.Constants] = None,
319
+ ) -> Tuple[types.Sequence, types.State]:
320
+ conditioning = _get_conditioning(self, self._conditioning_name, constants)
321
+ # PyType is confused by isinstance(conditioning, tf.Tensor).
322
+ if not isinstance(conditioning, types.Sequence):
323
+ conditioning_batch_shape = conditioning.shape[:1]
324
+ conditioning_channel_shape = conditioning.shape[1:]
325
+ conditioning = _tensor_to_fake_sequence(conditioning)
326
+ else:
327
+ time_index = state
328
+ conditioning_batch_shape = conditioning.values.shape[:1]
329
+ conditioning_channel_shape = conditioning.channel_shape
330
+ step_size = tf.compat.dimension_value(x.values.shape[1])
331
+ conditioning = _time_slice(
332
+ conditioning, time_index, step_size, name='cond_slice'
333
+ )
334
+ state = time_index + step_size
335
+ x.values.shape[:1].assert_is_compatible_with(conditioning_batch_shape)
336
+ self._build(x.channel_shape, conditioning_channel_shape)
337
+ conditioned_x = self._combine(x, self._project(conditioning, training))
338
+ return conditioned_x, state
339
+
340
+
341
+ class UpsampleConditioning(BaseConditioning):
342
+ """Conditions the sequence x on an upsampled conditioning sequence c.
343
+
344
+ Conditioning is done in a time-synchronized way, where each time step t_x of x
345
+ is conditioned on `t_c = t_x // upsample_ratio` from c.
346
+
347
+ Conditioning is defined as Combine(x, Upsample(Project(c))), where supported
348
+ projection and combination functions are available in Projection and
349
+ Combination enums above.
350
+
351
+ All valid broadcasts between x and c channel_shapes are supported, e.g.:
352
+ - Projection=IDENTITY, Combination=ADD:
353
+ - (x: [b, t_x, 3], c: [b, t_c, 3]) -> c_x: [b, t_x, 3]
354
+ - (x: [b, t_x, 3, 1, 5], c: [b, t_c, 2, 5]) -> c_x: [b, t_x, 3, 2, 5]
355
+ - Projection=IDENTITY, Combination=CONCAT:
356
+ - (x: [b, t_x, 3], c: [b, t_c, 7]) -> c_x: [b, t_x, 10]
357
+ - (x: [b, t_x, 3, 1, 5], c: [b, t_c, 2, 7]) -> c_x: [b, t_x, 3, 2, 12]
358
+ - Projection=LINEAR, Combination=ADD:
359
+ - (x: [b, t_x, 3], c: [b, t_c, 7]) -> c_x: [b, t_x, 3]
360
+ - (x: [b, t_x, 3, 1, 5], c: [b, t_c, 2, 7]) -> c_x: [b, t_x, 3, 1, 5]
361
+ - Projection=LINEAR, Combination=CONCAT:
362
+ - (x: [b, t_x, 3], c: [b, t_c, 7]) -> c_x: [b, t_x, 6]
363
+ - (x: [b, t_x, 3, 1, 5], c: [b, t_c, 2, 7]) -> c_x: [b, t_x, 3, 1, 10]
364
+
365
+ Where t_x = t_c * upsample_ratio.
366
+ """
367
+
368
+ def __init__(
369
+ self,
370
+ conditioning_name: str,
371
+ projection: BaseConditioning.Projection,
372
+ combination: BaseConditioning.Combination,
373
+ upsample_ratio: int,
374
+ name: Optional[str] = None,
375
+ ):
376
+ super().__init__(conditioning_name, projection, combination, name=name)
377
+ self._upsample_ratio = upsample_ratio
378
+
379
+ def _get_conditioning(
380
+ self, constants: Optional[types.Constants]
381
+ ) -> types.Sequence:
382
+ conditioning = _get_conditioning(self, self._conditioning_name, constants)
383
+ if isinstance(conditioning, tf.Tensor):
384
+ raise ValueError(
385
+ f'{self} expected a conditioning Sequence to upsample, '
386
+ f'got: {conditioning}'
387
+ )
388
+ return conditioning
389
+
390
+ def get_initial_state(
391
+ self, x: types.Sequence, constants: Optional[types.Constants] = None
392
+ ) -> types.State:
393
+ batch_size = utils.smart_dimension_size(x.values, 0)
394
+ x.channel_shape.assert_is_fully_defined()
395
+ x.channel_shape.with_rank_at_least(1)
396
+ conditioning = self._get_conditioning(constants)
397
+ projected_conditioning_shape = self._projected_condition_shape(
398
+ x.channel_shape, conditioning.channel_shape
399
+ )
400
+ # State is a 3-tuple of:
401
+ # x_t: The current timestep we are processing in the overall sequence.
402
+ # prev_cond_t: The conditioning timestep that prev_cond is computed
403
+ # from. Initialized to -1 to indicate that it is invalid.
404
+ # cond_slice: The cached projection of conditioning timestep prev_cond_t.
405
+ return (
406
+ tf.convert_to_tensor(0, dtype=tf.int32),
407
+ tf.convert_to_tensor(-1, dtype=tf.int32),
408
+ types.Sequence(
409
+ tf.zeros(
410
+ [batch_size, 1] + projected_conditioning_shape.as_list(),
411
+ dtype=x.values.dtype,
412
+ ),
413
+ tf.ones((batch_size, 1), dtype=types.MASK_DTYPE),
414
+ ),
415
+ )
416
+
417
+ @tf.Module.with_name_scope
418
+ def layer(
419
+ self,
420
+ x: types.Sequence,
421
+ training: bool,
422
+ initial_state: Optional[types.State] = None,
423
+ constants: Optional[types.Constants] = None,
424
+ ) -> types.Sequence:
425
+ conditioning = self._get_conditioning(constants)
426
+ self._build(x.channel_shape, conditioning.channel_shape)
427
+
428
+ # Optionally project the conditioning input.
429
+ projected_conditioning = self._project(conditioning, training)
430
+
431
+ # Upsample the conditioning input to the input rate.
432
+ upsampled = types.Sequence(
433
+ _upsample_tensor(projected_conditioning.values, self._upsample_ratio),
434
+ _upsample_tensor(projected_conditioning.mask, self._upsample_ratio),
435
+ )
436
+
437
+ if not x.values.shape[:2].is_compatible_with(upsampled.values.shape[:2]):
438
+ raise ValueError(
439
+ f'{self} received an input ({x}) and conditioning '
440
+ f'({conditioning}) that are incompatible with upsample '
441
+ f'ratio {self._upsample_ratio}.'
442
+ )
443
+
444
+ # Combine x and upsampled conditioning. self._combine masks its result.
445
+ return self._combine(x, upsampled)
446
+
447
+ @tf.Module.with_name_scope
448
+ def step(
449
+ self,
450
+ x: types.Sequence,
451
+ state: types.State,
452
+ training: bool,
453
+ constants: Optional[types.Constants] = None,
454
+ ) -> Tuple[types.Sequence, types.State]:
455
+ conditioning = self._get_conditioning(constants)
456
+ self._build(x.channel_shape, conditioning.channel_shape)
457
+
458
+ block_size = utils.smart_dimension_size(x.values, 1)
459
+ x_t, prev_cond_t, prev_cond_slice = state
460
+
461
+ if not isinstance(block_size, tf.Tensor) and block_size == 1:
462
+ # Faster path for single timestep.
463
+ output, cond_t, cond_slice = self._read_project_and_combine_cached(
464
+ x_t, x, conditioning, training, prev_cond_t, prev_cond_slice
465
+ )
466
+ state = (x_t + 1, cond_t, cond_slice)
467
+ return output, state
468
+
469
+ # If block_size > 1, process (upsample_ratio - x_t % upsample_ratio) samples
470
+ # at a time until we hit the block size.
471
+ def cond(i, x_t, prev_cond_t, prev_cond, values_ta, mask_ta):
472
+ del x_t
473
+ del prev_cond_t
474
+ del prev_cond
475
+ del values_ta
476
+ del mask_ta
477
+ return i < block_size
478
+
479
+ def body(i, x_t, prev_cond_t, prev_cond_slice, values_ta, mask_ta):
480
+ # The number of samples to condition with cond_t.
481
+ x_t_remaining = self._upsample_ratio - x_t % self._upsample_ratio
482
+ block_remaining = block_size - i
483
+ x_t_size = tf.minimum(x_t_remaining, block_remaining)
484
+
485
+ # Read the slice of samples to transform.
486
+ x_slice = _time_slice(x, i, x_t_size, name='x_slice')
487
+
488
+ output, cond_t, cond_slice = self._read_project_and_combine_cached(
489
+ x_t, x_slice, conditioning, training, prev_cond_t, prev_cond_slice
490
+ )
491
+
492
+ write_indices = i + tf.range(x_t_size)
493
+ values_time_major = tf.transpose(
494
+ output.values, [1, 0] + list(range(2, output.values.shape.rank))
495
+ )
496
+ mask_time_major = tf.transpose(output.mask, [1, 0])
497
+
498
+ values_ta = values_ta.scatter(write_indices, values_time_major)
499
+ mask_ta = mask_ta.scatter(write_indices, mask_time_major)
500
+
501
+ return (
502
+ i + x_t_size,
503
+ x_t + x_t_size,
504
+ cond_t,
505
+ cond_slice,
506
+ values_ta,
507
+ mask_ta,
508
+ )
509
+
510
+ # TODO(rryan): Simplify with SequenceArray.
511
+ values_ta = tf.TensorArray(x.dtype, size=block_size)
512
+ mask_ta = tf.TensorArray(tf.float32, size=block_size)
513
+ # TODO(rryan): Consider static unroll of this loop for small sizes.
514
+ i = tf.constant(0, tf.int32)
515
+ _, x_t, cond_t, cond_slice, values_ta, mask_ta = tf.while_loop(
516
+ cond,
517
+ body,
518
+ (i, x_t, prev_cond_t, prev_cond_slice, values_ta, mask_ta),
519
+ maximum_iterations=block_size,
520
+ )
521
+ state = (x_t, cond_t, cond_slice)
522
+ values = values_ta.stack()
523
+ mask = mask_ta.stack()
524
+ output = types.Sequence(
525
+ tf.transpose(values, [1, 0] + list(range(2, values.shape.rank))),
526
+ tf.transpose(mask, [1, 0]),
527
+ )
528
+ return output.mask_invalid(), state
529
+
530
+ def _read_project_and_combine_cached(
531
+ self,
532
+ x_t: tf.Tensor,
533
+ x: types.Sequence,
534
+ conditioning: types.Sequence,
535
+ training: bool,
536
+ prev_cond_t: tf.Tensor,
537
+ prev_cond_slice: types.Sequence,
538
+ ) -> Tuple[types.Sequence, tf.Tensor, types.Sequence]:
539
+ cond_t = x_t // self._upsample_ratio
540
+
541
+ def read_and_project():
542
+ cond_slice = _time_slice(conditioning, cond_t, 1, name='cond_slice')
543
+ cond_slice = self._project(cond_slice, training=training)
544
+
545
+ def ensure_shape(values, mask):
546
+ values = tf.ensure_shape(values, prev_cond_slice.values.shape)
547
+ mask = tf.ensure_shape(mask, prev_cond_slice.mask.shape)
548
+ return values, mask
549
+
550
+ return cond_t, cond_slice.apply(ensure_shape)
551
+
552
+ def reuse_cached():
553
+ return prev_cond_t, prev_cond_slice
554
+
555
+ cond_t, cond_slice = tf.cond(
556
+ tf.equal(prev_cond_t, cond_t), reuse_cached, read_and_project
557
+ )
558
+ output = self._combine(x, cond_slice)
559
+ return output, cond_t, cond_slice
560
+
561
+
562
+ class NoiseConditioning(BaseConditioning):
563
+ """Conditions the sequence x on a noise sequence.
564
+
565
+ Conditioning is done in a time-synchronized way, where each time step of x is
566
+ conditioned on the corresponding time step of the sampled noise sequence, c.
567
+
568
+ Conditioning is defined as Combine(x, Project(c)), where supported projection
569
+ and combination functions are available in Projection and Combination enums
570
+ above.
571
+
572
+ All valid broadcasts between x and c channel_shapes are supported, e.g.:
573
+ - Projection=IDENTITY, Combination=ADD:
574
+ - (x: [b, t, 3], c: [b, t, 3]) -> c_x: [b, t, 3]
575
+ - (x: [b, t, 3, 1, 5], c: [b, t, 2, 5]) -> c_x: [b, t, 3, 2, 5]
576
+ - Projection=IDENTITY, Combination=CONCAT:
577
+ - (x: [b, t, 3], c: [b, t, 7]) -> c_x: [b, t, 10]
578
+ - (x: [b, t, 3, 1, 5], c: [b, t, 2, 7]) -> c_x: [b, t, 3, 2, 12]
579
+ - Projection=LINEAR, Combination=ADD:
580
+ - (x: [b, t, 3], c: [b, t, 7]) -> c_x: [b, t, 3]
581
+ - (x: [b, t, 3, 1, 5], c: [b, t, 2, 7]) -> c_x: [b, t, 3, 1, 5]
582
+ - Projection=LINEAR, Combination=CONCAT:
583
+ - (x: [b, t, 3], c: [b, t, 7]) -> c_x: [b, t, 6]
584
+ - (x: [b, t, 3, 1, 5], c: [b, t, 2, 7]) -> c_x: [b, t, 3, 1, 10]
585
+ """
586
+
587
+ def __init__(
588
+ self,
589
+ noise_channel_shape: tf.TensorShape | list[int] | tuple[int, ...],
590
+ noise_sampler: simple.NoiseSampler,
591
+ projection: BaseConditioning.Projection,
592
+ combination: BaseConditioning.Combination,
593
+ name: str | None = None,
594
+ ):
595
+ super().__init__(None, projection, combination, name=name)
596
+ self._noise_channel_shape = tf.TensorShape(noise_channel_shape)
597
+ self._noise_sampler = noise_sampler
598
+
599
+ def _get_conditioning_channel_shape(
600
+ self, constants: types.Constants
601
+ ) -> tf.TensorShape:
602
+ del constants
603
+ return self._noise_channel_shape
604
+
605
+ def _get_noise_sequence(self, x: types.Sequence) -> types.Sequence:
606
+ batch, time = utils.smart_dimension_size(x.values, dim=[0, 1])
607
+ noise_shape = [batch, time] + self._noise_channel_shape.as_list()
608
+ sample_spec = simple.SampleSpec(noise_shape, x.dtype)
609
+ samples = self._noise_sampler.sample(sample_spec)
610
+ return types.Sequence(samples, x.mask).mask_invalid()
611
+
612
+ def get_initial_state(
613
+ self, x: types.Sequence, constants: types.Constants | None = None
614
+ ) -> types.State:
615
+ return ()
616
+
617
+ @tf.Module.with_name_scope
618
+ def layer(
619
+ self,
620
+ x: types.Sequence,
621
+ training: bool,
622
+ initial_state: Optional[types.State] = None,
623
+ constants: Optional[types.Constants] = None,
624
+ ) -> types.Sequence:
625
+ del initial_state
626
+ conditioning = self._get_noise_sequence(x)
627
+ broadcasted_shape = tf.broadcast_static_shape(
628
+ x.values.shape[:2], conditioning.values.shape[:2]
629
+ )
630
+ x.values.shape[:2].assert_is_compatible_with(broadcasted_shape)
631
+ self._build(x.channel_shape, conditioning.channel_shape)
632
+ conditioned_x = self._combine(x, self._project(conditioning, training))
633
+ return conditioned_x
634
+
635
+ @tf.Module.with_name_scope
636
+ def step(
637
+ self,
638
+ x: types.Sequence,
639
+ state: types.State,
640
+ training: bool,
641
+ constants: Optional[types.Constants] = None,
642
+ ) -> Tuple[types.Sequence, types.State]:
643
+ conditioned_x = self.layer(x, training, state, constants)
644
+ return conditioned_x, ()