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,1207 @@
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
+ """Simple layers."""
15
+
16
+ import abc
17
+ import dataclasses
18
+ import fractions
19
+ import math
20
+ from typing import Any, Callable, List, Optional, Sequence, Tuple, Union
21
+
22
+ import numpy as np
23
+ from sequence_layers.tensorflow import dense
24
+ from sequence_layers.tensorflow import types
25
+ from sequence_layers.tensorflow import utils
26
+ import tensorflow.compat.v2 as tf
27
+
28
+
29
+ class Scale(types.StatelessPointwise):
30
+ """Scales the input by a provided constant."""
31
+
32
+ # PEP 484 says to use complex when you mean any numeric type.
33
+ def __init__(self, scale: complex, name: Optional[str] = None):
34
+ super().__init__(name=name)
35
+ self._scale = scale
36
+
37
+ @tf.Module.with_name_scope
38
+ def layer(
39
+ self,
40
+ x: types.Sequence,
41
+ training: bool,
42
+ initial_state: Optional[types.State] = None,
43
+ constants: Optional[types.Constants] = None,
44
+ ) -> types.Sequence:
45
+ del training
46
+ del initial_state
47
+ # No masking required since x is already masked and we're multiplying.
48
+ return x.apply_values(lambda v: v * tf.cast(self._scale, v.dtype))
49
+
50
+
51
+ class Translate(types.StatelessPointwise):
52
+ """Translates the input by a provided constant."""
53
+
54
+ # PEP 484 says to use complex when you mean any numeric type.
55
+ def __init__(self, shift: complex, name: Optional[str] = None):
56
+ super().__init__(name=name)
57
+ self._shift = shift
58
+
59
+ @tf.Module.with_name_scope
60
+ def layer(
61
+ self,
62
+ x: types.Sequence,
63
+ training: bool,
64
+ initial_state: Optional[types.State] = None,
65
+ constants: Optional[types.Constants] = None,
66
+ ) -> types.Sequence:
67
+ del training
68
+ del initial_state
69
+ x = x.apply_values(lambda v: v + tf.cast(self._shift, v.dtype))
70
+ return x.mask_invalid()
71
+
72
+
73
+ class Abs(types.StatelessPointwiseFunctor):
74
+ """Absolute value."""
75
+
76
+ def fn(
77
+ self, values: tf.Tensor, mask: tf.Tensor
78
+ ) -> Tuple[tf.Tensor, tf.Tensor]:
79
+ return tf.math.abs(values), mask
80
+
81
+ def get_output_dtype(self, input_dtype: tf.DType) -> tf.DType:
82
+ # The absolute value of complex numbers is a real magnitude.
83
+ return input_dtype.real_dtype
84
+
85
+
86
+ class Tanh(types.StatelessPointwiseFunctor):
87
+ """Tanh activation."""
88
+
89
+ def fn(
90
+ self, values: tf.Tensor, mask: tf.Tensor
91
+ ) -> Tuple[tf.Tensor, tf.Tensor]:
92
+ return tf.nn.tanh(values), mask
93
+
94
+
95
+ class Relu(types.StatelessPointwiseFunctor):
96
+ """Relu activation."""
97
+
98
+ def fn(
99
+ self, values: tf.Tensor, mask: tf.Tensor
100
+ ) -> Tuple[tf.Tensor, tf.Tensor]:
101
+ return tf.nn.relu(values), mask
102
+
103
+
104
+ class LeakyRelu(types.StatelessPointwiseFunctor):
105
+ """Leaky Relu activation."""
106
+
107
+ def __init__(self, alpha: complex, name: Optional[str] = None):
108
+ super().__init__(name=name)
109
+ self._alpha = alpha
110
+
111
+ def fn(
112
+ self, values: tf.Tensor, mask: tf.Tensor
113
+ ) -> Tuple[tf.Tensor, tf.Tensor]:
114
+ return tf.nn.leaky_relu(values, alpha=self._alpha), mask
115
+
116
+
117
+ class Elu(types.StatelessPointwiseFunctor):
118
+ """Elu activation."""
119
+
120
+ def fn(
121
+ self, values: tf.Tensor, mask: tf.Tensor
122
+ ) -> Tuple[tf.Tensor, tf.Tensor]:
123
+ return tf.nn.elu(values), mask
124
+
125
+
126
+ class Exp(types.StatelessPointwiseFunctor):
127
+ """Exp."""
128
+
129
+ def fn(
130
+ self, values: tf.Tensor, mask: tf.Tensor
131
+ ) -> Tuple[tf.Tensor, tf.Tensor]:
132
+ return tf.math.exp(values), mask
133
+
134
+
135
+ class Log(types.StatelessPointwiseFunctor):
136
+ """Log."""
137
+
138
+ def fn(
139
+ self, values: tf.Tensor, mask: tf.Tensor
140
+ ) -> Tuple[tf.Tensor, tf.Tensor]:
141
+ # TODO(rryan): There has to be a better way to clear NaNs from invalid
142
+ # regions.
143
+ mask_expanded = types.Sequence(values, mask).expanded_mask()
144
+ return (
145
+ tf.where(mask_expanded > 0.0, tf.math.log(values), 0),
146
+ mask,
147
+ )
148
+
149
+
150
+ class Sigmoid(types.StatelessPointwiseFunctor):
151
+ """Sigmoid."""
152
+
153
+ def fn(
154
+ self, values: tf.Tensor, mask: tf.Tensor
155
+ ) -> Tuple[tf.Tensor, tf.Tensor]:
156
+ return tf.nn.sigmoid(values), mask
157
+
158
+
159
+ class Softplus(types.StatelessPointwiseFunctor):
160
+ """Softplus."""
161
+
162
+ def fn(
163
+ self, values: tf.Tensor, mask: tf.Tensor
164
+ ) -> Tuple[tf.Tensor, tf.Tensor]:
165
+ return tf.math.softplus(values), mask
166
+
167
+
168
+ class Softmax(types.StatelessPointwiseFunctor):
169
+ """Softmax."""
170
+
171
+ def fn(
172
+ self, values: tf.Tensor, mask: tf.Tensor
173
+ ) -> Tuple[tf.Tensor, tf.Tensor]:
174
+ return tf.math.softmax(values), mask
175
+
176
+
177
+ class Swish(types.StatelessPointwiseFunctor):
178
+ """Swish."""
179
+
180
+ def fn(
181
+ self, values: tf.Tensor, mask: tf.Tensor
182
+ ) -> Tuple[tf.Tensor, tf.Tensor]:
183
+ return tf.nn.swish(values), mask
184
+
185
+
186
+ class Gelu(types.StatelessPointwiseFunctor):
187
+ """Gaussian Error Linear Unit (GELU)."""
188
+
189
+ def __init__(self, approximate: bool = False, name: str | None = None):
190
+ super().__init__(name=name)
191
+ self._approximate = approximate
192
+
193
+ def fn(
194
+ self, values: tf.Tensor, mask: tf.Tensor
195
+ ) -> Tuple[tf.Tensor, tf.Tensor]:
196
+ return tf.nn.gelu(values, approximate=self._approximate), mask
197
+
198
+
199
+ class Cast(types.StatelessPointwiseFunctor):
200
+ """Cast input values to the specified type."""
201
+
202
+ def __init__(self, dtype, name: Optional[str] = None):
203
+ super().__init__(name=name)
204
+ self._dtype = dtype
205
+
206
+ def fn(
207
+ self, values: tf.Tensor, mask: tf.Tensor
208
+ ) -> Tuple[tf.Tensor, tf.Tensor]:
209
+ return tf.cast(values, self._dtype), mask
210
+
211
+ def get_output_dtype(self, input_dtype: tf.DType) -> tf.DType:
212
+ return self._dtype
213
+
214
+
215
+ class GatedUnit(types.Stateless):
216
+ """Computes a generalized Gated Unit, reducing the input channels by 2x."""
217
+
218
+ def __init__(
219
+ self,
220
+ feature_activation: Callable[[tf.Tensor], tf.Tensor] | None,
221
+ gate_activation: Callable[[tf.Tensor], tf.Tensor] | None,
222
+ name: str | None = None,
223
+ ):
224
+ super().__init__(name=name)
225
+ self._feature_activation = feature_activation
226
+ self._gate_activation = gate_activation
227
+
228
+ @tf.Module.with_name_scope
229
+ def layer(
230
+ self,
231
+ x: types.Sequence,
232
+ training: bool,
233
+ initial_state: Optional[types.State] = None,
234
+ constants: Optional[types.Constants] = None,
235
+ ) -> types.Sequence:
236
+ feature, gate = tf.split(x.values, 2, axis=-1)
237
+ if self._feature_activation:
238
+ feature = self._feature_activation(feature)
239
+ if self._gate_activation:
240
+ gate = self._gate_activation(gate)
241
+ values = feature * gate
242
+ return types.Sequence(values, x.mask).mask_invalid()
243
+
244
+ def get_output_shape(
245
+ self,
246
+ input_shape: tf.TensorShape,
247
+ constants: Optional[types.Constants] = None,
248
+ ) -> tf.TensorShape:
249
+ channels_static = input_shape.dims[-1].value
250
+ if channels_static is None:
251
+ raise ValueError(
252
+ '%s depends on input shape, but input has unknown '
253
+ 'channels dimension: %s' % (self, input_shape)
254
+ )
255
+ if channels_static % 2 != 0:
256
+ raise ValueError(
257
+ 'Input to %s must have an even number of channels: %s'
258
+ % (self, input_shape)
259
+ )
260
+ return input_shape[:-1].concatenate(channels_static // 2)
261
+
262
+
263
+ class GatedLinearUnit(GatedUnit):
264
+ """Computes a Gated Linear Unit, reducing the input channels by 2x."""
265
+
266
+ def __init__(self, name: Optional[str] = None):
267
+ super().__init__(None, tf.nn.sigmoid, name=name)
268
+
269
+
270
+ class GatedTanhUnit(GatedUnit):
271
+ """Computes a Gated Tanh Unit, reducing the input channels by 2x."""
272
+
273
+ def __init__(self, name: Optional[str] = None):
274
+ super().__init__(tf.nn.tanh, tf.nn.sigmoid, name=name)
275
+
276
+
277
+ class Dropout(types.StatelessPointwise):
278
+ """Computes stateful (i.e. using stateful random ops) dropout."""
279
+
280
+ def __init__(
281
+ self,
282
+ rate: float = 0.5,
283
+ noise_shape: Optional[Sequence[Optional[int]]] = None,
284
+ seed: Optional[int] = None,
285
+ name: Optional[str] = None,
286
+ ):
287
+ super().__init__(name=name)
288
+ with self.name_scope as name_scope:
289
+ self._layer = tf.keras.layers.Dropout(
290
+ rate, noise_shape=noise_shape, seed=seed, name=name_scope
291
+ )
292
+
293
+ @tf.Module.with_name_scope
294
+ def layer(
295
+ self,
296
+ x: types.Sequence,
297
+ training: bool,
298
+ initial_state: Optional[types.State] = None,
299
+ constants: Optional[types.Constants] = None,
300
+ ) -> types.Sequence:
301
+ # No masking required since dropout only zeros values.
302
+ # PyType does not think that Dropout.__call__ exists when passing it as the
303
+ # map_fn to apply_values.
304
+ return x.apply_values(lambda v: self._layer(v, training=training))
305
+
306
+
307
+ class DeterministicDropout(types.SequenceLayer):
308
+ """Computes deterministic (i.e. using stateless random ops) dropout."""
309
+
310
+ SEED_DTYPE = tf.int32
311
+
312
+ def __init__(
313
+ self,
314
+ rate: float = 0.5,
315
+ initial_seed_name: str = '',
316
+ noise_shape: Optional[Sequence[Optional[int]]] = None,
317
+ always_dropout: bool = False,
318
+ name: Optional[str] = None,
319
+ ):
320
+ super().__init__(name=name)
321
+ if not initial_seed_name:
322
+ raise ValueError('initial_seed_name is required.')
323
+ if rate < 0.0 or rate >= 1.0:
324
+ raise ValueError(f'Rate must be in [0.0, 1.0). Got: {rate}')
325
+
326
+ self._rate = rate
327
+ self._initial_seed_name = initial_seed_name
328
+ self._always_dropout = always_dropout
329
+
330
+ if noise_shape:
331
+ if any(d is not None and d <= 0 for d in noise_shape):
332
+ raise ValueError(
333
+ 'noise_shape values should be positive integers or '
334
+ f'None. Got: {noise_shape}'
335
+ )
336
+ if noise_shape[1] is not None:
337
+ raise ValueError(
338
+ 'Specifying noise_shape for the time dimension is unsupported. '
339
+ f'Set it to None. Got: {noise_shape}'
340
+ )
341
+
342
+ self._noise_shape = None if noise_shape is None else tuple(noise_shape)
343
+
344
+ def get_output_shape(
345
+ self, input_shape: tf.TensorShape, constants: types.Constants = None
346
+ ) -> tf.TensorShape:
347
+ if not input_shape.is_fully_defined():
348
+ raise ValueError(
349
+ '%s depends on input shape, but input has unknown '
350
+ 'channels dimension: %s' % (self, input_shape)
351
+ )
352
+ return input_shape
353
+
354
+ @tf.Module.with_name_scope
355
+ def get_initial_state(
356
+ self, x: types.Sequence, constants: types.Constants = None
357
+ ) -> types.State:
358
+ if self._rate > 0.0:
359
+ return tf.constant(0, self.SEED_DTYPE, name='t')
360
+ else:
361
+ return ()
362
+
363
+ def _validate(self, x: types.Sequence):
364
+ if not x.values.dtype.is_floating:
365
+ raise ValueError('Dropout required floating point sequences.')
366
+
367
+ def _get_initial_seed(self, constants: types.Constants):
368
+ if constants is None:
369
+ raise ValueError('constants is required.')
370
+ initial_seed = constants.get(self._initial_seed_name)
371
+ if initial_seed is None:
372
+ raise ValueError(
373
+ f'Expected a {self._initial_seed_name} entry in constants. '
374
+ f'Got: {constants}'
375
+ )
376
+ initial_seed = tf.cast(initial_seed, self.SEED_DTYPE)
377
+ initial_seed.shape.assert_has_rank(0)
378
+ return initial_seed
379
+
380
+ def _get_seed(self, t: tf.Tensor, constants: types.Constants) -> tf.Tensor:
381
+ initial_seed = self._get_initial_seed(constants)
382
+ initial_seed = tf.broadcast_to(initial_seed, tf.shape(t))
383
+ return tf.stack([initial_seed, t], axis=-1)
384
+
385
+ def _get_noise_shape(self, input_shape: Sequence[Union[tf.Tensor, int]]):
386
+ if self._noise_shape is None:
387
+ return input_shape
388
+
389
+ if len(self._noise_shape) != len(input_shape):
390
+ raise ValueError(
391
+ 'Expected noise_shape to match input shape. '
392
+ f'{self._noise_shape} != {input_shape}.'
393
+ )
394
+
395
+ # Use noise_shape[i] if it's non-None, else the original input shape.
396
+ return tuple(
397
+ n_d if n_d else i_d for n_d, i_d in zip(self._noise_shape, input_shape)
398
+ )
399
+
400
+ def _dropout(
401
+ self, x: types.Sequence, t: tf.Tensor, constants: types.Constants
402
+ ) -> Tuple[types.Sequence, types.State]:
403
+ t = tf.convert_to_tensor(t, dtype=self.SEED_DTYPE)
404
+ t.shape.assert_has_rank(0)
405
+
406
+ input_shape = utils.smart_dimension_size(x.values)
407
+ num_steps = input_shape[1]
408
+ noise_shape = self._get_noise_shape(input_shape)
409
+
410
+ ts = t + tf.range(num_steps, dtype=t.dtype)
411
+ seeds = self._get_seed(ts, constants)
412
+
413
+ def noise_fn(seed_t):
414
+ noise_shape_t = (noise_shape[0],) + noise_shape[2:]
415
+ return tf.random.stateless_uniform(
416
+ noise_shape_t, seed=seed_t, dtype=x.values.dtype
417
+ )
418
+
419
+ # Manually unroll small numbers of steps when num_steps is statically known.
420
+ if isinstance(num_steps, int) and num_steps < 128:
421
+ noise = tf.stack([noise_fn(seeds[i]) for i in range(num_steps)], axis=1)
422
+ else:
423
+ noise = tf.map_fn(noise_fn, seeds, dtype=x.values.dtype)
424
+ noise = tf.transpose(noise, [1, 0] + list(range(2, len(noise_shape))))
425
+
426
+ assert self._rate > 0.0
427
+ keep_rate = 1.0 - self._rate
428
+ scale = tf.cast(1.0 / keep_rate, x.values.dtype)
429
+
430
+ # Use >= to match tf.nn.dropout.
431
+ keep = noise >= self._rate
432
+
433
+ # No masking required since dropout only zeros values.
434
+ y = x.apply_values(lambda v: v * scale * tf.cast(keep, v.dtype))
435
+
436
+ if not tf.executing_eagerly():
437
+ y.values.set_shape(x.values.shape)
438
+
439
+ return y, t + num_steps
440
+
441
+ @tf.Module.with_name_scope
442
+ def step(
443
+ self,
444
+ x: types.Sequence,
445
+ state: types.State,
446
+ training: bool,
447
+ constants: types.Constants = None,
448
+ ) -> Tuple[types.Sequence, types.State]:
449
+ self._validate(x)
450
+ if (not self._always_dropout and not training) or self._rate == 0.0:
451
+ return x, state
452
+
453
+ return self._dropout(x, state, constants)
454
+
455
+ @tf.Module.with_name_scope
456
+ def layer(
457
+ self,
458
+ x: types.Sequence,
459
+ training: bool,
460
+ initial_state: Optional[types.State] = None,
461
+ constants: Optional[types.Constants] = None,
462
+ ) -> types.Sequence:
463
+ self._validate(x)
464
+ if (not self._always_dropout and not training) or self._rate == 0.0:
465
+ return x
466
+
467
+ y, _ = self._dropout(x, 0, constants)
468
+ return y
469
+
470
+
471
+ class TacotronDropoutAtEval(Dropout):
472
+ """Computes dropout in both training and eval/inference, as in Tacotron.
473
+
474
+ This is a nonstandard use of dropout, which you probably don't intend to use.
475
+ USE WITH CAUTION.
476
+ """
477
+
478
+ @tf.Module.with_name_scope
479
+ def layer(
480
+ self,
481
+ x: types.Sequence,
482
+ training: bool,
483
+ initial_state: Optional[types.State] = None,
484
+ constants: Optional[types.Constants] = None,
485
+ ) -> types.Sequence:
486
+ return super().layer(
487
+ x, training=True, initial_state=initial_state, constants=constants
488
+ )
489
+
490
+
491
+ @dataclasses.dataclass
492
+ class SampleSpec:
493
+ shape: Any
494
+ dtype: Any
495
+
496
+
497
+ class NoiseSampler(metaclass=abc.ABCMeta):
498
+
499
+ @abc.abstractmethod
500
+ def sample(self, spec: SampleSpec) -> tf.Tensor:
501
+ pass
502
+
503
+
504
+ @dataclasses.dataclass
505
+ class UniformSampler(NoiseSampler):
506
+ minval: float
507
+ maxval: float
508
+
509
+ def sample(self, spec: SampleSpec) -> tf.Tensor:
510
+ return tf.random.uniform(
511
+ spec.shape,
512
+ tf.cast(self.minval, spec.dtype),
513
+ tf.cast(self.maxval, spec.dtype),
514
+ dtype=spec.dtype,
515
+ )
516
+
517
+
518
+ @dataclasses.dataclass
519
+ class NormalSampler(NoiseSampler):
520
+ mean: float
521
+ stddev: float
522
+
523
+ def sample(self, spec: SampleSpec) -> tf.Tensor:
524
+ return tf.random.normal(
525
+ spec.shape,
526
+ tf.cast(self.mean, spec.dtype),
527
+ tf.cast(self.stddev, spec.dtype),
528
+ dtype=spec.dtype,
529
+ )
530
+
531
+
532
+ @dataclasses.dataclass
533
+ class TruncatedNormalSampler(NoiseSampler):
534
+ mean: float
535
+ stddev: float
536
+
537
+ def sample(self, spec: SampleSpec) -> tf.Tensor:
538
+ return tf.random.truncated_normal(
539
+ spec.shape,
540
+ tf.cast(self.mean, spec.dtype),
541
+ tf.cast(self.stddev, spec.dtype),
542
+ dtype=spec.dtype,
543
+ )
544
+
545
+
546
+ class Noise(types.StatelessPointwise):
547
+ """Adds noise to inputs from a specified distribution.
548
+
549
+ Uses the provided NoiseSampler instance to generate noise of a specified type
550
+ and shape.
551
+ """
552
+
553
+ def __init__(
554
+ self,
555
+ sampler: NoiseSampler,
556
+ training_only: bool,
557
+ name: Optional[str] = None,
558
+ ):
559
+ super().__init__(name=name)
560
+ self._sampler = sampler
561
+ self._training_only = training_only
562
+
563
+ @tf.Module.with_name_scope
564
+ def layer(
565
+ self,
566
+ x: types.Sequence,
567
+ training: bool,
568
+ initial_state: Optional[types.State] = None,
569
+ constants: Optional[types.Constants] = None,
570
+ ) -> types.Sequence:
571
+ # If we're only applying noise in training then skip if we're not training.
572
+ if self._training_only and not training:
573
+ return x
574
+ noise = self._sampler.sample(SampleSpec(tf.shape(x.values), x.dtype))
575
+ return x.apply_values(lambda v: v + noise).mask_invalid()
576
+
577
+
578
+ class Slice(types.Stateless):
579
+ """Slices the channels dimensions of input tensors."""
580
+
581
+ def __init__(self, the_slice=None, name: Optional[str] = None):
582
+ super().__init__(name=name)
583
+ self._slice = the_slice
584
+
585
+ def __getitem__(self, the_slice):
586
+ """Convenience method for setting the layer's slice."""
587
+ # TODO(rryan): This might be too unintuitive, but making slice() objects
588
+ # manually is also unintuitive.
589
+ assert self._slice is None
590
+ if isinstance(the_slice, slice):
591
+ self._slice = (the_slice,)
592
+ else:
593
+ self._slice = the_slice
594
+ return self
595
+
596
+ def _validate_slice_for_input_shape(self, input_shape: tf.TensorShape):
597
+ # None (tf.newaxis) dimensions are expansions.
598
+ non_none_dimensions = sum(1 for s in self._slice if s is not None)
599
+ if non_none_dimensions != input_shape.rank:
600
+ raise ValueError(
601
+ 'Slice has wrong size for input: input_shape=%s slice=%s'
602
+ % (input_shape, self._slice)
603
+ )
604
+
605
+ def get_output_shape(
606
+ self,
607
+ input_shape: tf.TensorShape,
608
+ constants: Optional[types.Constants] = None,
609
+ ) -> tf.TensorShape:
610
+ if not input_shape.is_fully_defined():
611
+ raise ValueError(
612
+ '%s requires fully defined input shape: %s' % (self, input_shape)
613
+ )
614
+
615
+ self._validate_slice_for_input_shape(input_shape)
616
+ output_dims = []
617
+ input_index = 0
618
+
619
+ # Compute the output shape:
620
+ # - int: Remove the current input dimension.
621
+ # - slice: Compute the output dimension size using slice.indices.
622
+ # - None (tf.newaxis): Add a dimension.
623
+ for the_slice in self._slice:
624
+ if isinstance(the_slice, slice):
625
+ # Use slice.indices(dim_size) to figure out the new length of the
626
+ # dimension.
627
+ output_dims.append(
628
+ len(range(*the_slice.indices(input_shape.dims[input_index].value)))
629
+ )
630
+ input_index += 1
631
+ elif isinstance(the_slice, int):
632
+ # Skip this input dimension.
633
+ input_index += 1
634
+ elif the_slice is None:
635
+ # Add a dimension.
636
+ output_dims.append(1)
637
+ else:
638
+ raise NotImplementedError(
639
+ f'Unsupported slice type: {type(the_slice)}, {the_slice}'
640
+ )
641
+ return tf.TensorShape(output_dims)
642
+
643
+ @tf.Module.with_name_scope
644
+ def layer(
645
+ self,
646
+ x: types.Sequence,
647
+ training: bool,
648
+ initial_state: Optional[types.State] = None,
649
+ constants: Optional[types.Constants] = None,
650
+ ) -> types.Sequence:
651
+ # Slice the batch and time dimensions with [:, :].
652
+ full_slice = (
653
+ slice(None, None, None),
654
+ slice(None, None, None),
655
+ ) + self._slice
656
+ self._validate_slice_for_input_shape(x.channel_shape)
657
+ return x.apply_values(lambda v: v.__getitem__(full_slice))
658
+
659
+
660
+ class Flatten(types.Stateless):
661
+ """Flattens the channel dimensions of the input sequence.
662
+
663
+ An input sequence with shape [batch_size, time, ...] is reshaped to
664
+ [batch_size, time, prod(...)]. The mask is unchanged.
665
+ """
666
+
667
+ def get_output_shape(
668
+ self,
669
+ input_shape: tf.TensorShape,
670
+ constants: Optional[types.Constants] = None,
671
+ ) -> tf.TensorShape:
672
+ return tf.TensorShape(input_shape.num_elements())
673
+
674
+ @tf.Module.with_name_scope
675
+ def layer(
676
+ self,
677
+ x: types.Sequence,
678
+ training: bool,
679
+ initial_state: Optional[types.State] = None,
680
+ constants: Optional[types.Constants] = None,
681
+ ) -> types.Sequence:
682
+ del training
683
+ del initial_state
684
+ batch_size, time = utils.smart_dimension_size(x.values, [0, 1])
685
+ num_elements = x.channel_shape.num_elements()
686
+ return x.apply_values(
687
+ lambda v: tf.reshape(v, [batch_size, time, num_elements])
688
+ )
689
+
690
+
691
+ class Transpose(types.Stateless):
692
+ """Transposes the channel dimensions of the input sequence.
693
+
694
+ E.g., with perm = [1, 0], the effective perm is [0, 1, 3, 2] to keep the batch
695
+ and time dimensions as is, and only transpose the channel dimensions.
696
+ """
697
+
698
+ def __init__(
699
+ self,
700
+ perm: List[int],
701
+ name: Optional[str] = None,
702
+ ):
703
+ super().__init__(name=name)
704
+ if any([p < 0 for p in perm]):
705
+ raise ValueError(f'Transpose does not accept negative indices: {perm=}')
706
+ self._channel_perm = perm
707
+
708
+ def get_output_shape(
709
+ self,
710
+ input_shape: tf.TensorShape,
711
+ constants: Optional[types.Constants] = None,
712
+ ) -> tf.TensorShape:
713
+ if not input_shape.is_fully_defined():
714
+ raise ValueError(
715
+ '%s requires fully defined input shape: %s' % (self, input_shape)
716
+ )
717
+ channel_perm_rank = len(self._channel_perm)
718
+ input_channel_rank = input_shape.rank
719
+ if channel_perm_rank != input_channel_rank:
720
+ raise ValueError(f'{channel_perm_rank=} != {input_channel_rank}')
721
+ return tf.TensorShape([input_shape[d] for d in self._channel_perm])
722
+
723
+ @tf.Module.with_name_scope
724
+ def layer(
725
+ self,
726
+ x: types.Sequence,
727
+ training: bool,
728
+ initial_state: Optional[types.State] = None,
729
+ constants: Optional[types.Constants] = None,
730
+ ) -> types.Sequence:
731
+ del training
732
+ del initial_state
733
+ # Adjust permutation to take into account batch and time dimensions.
734
+ perm = [0, 1] + [d + 2 for d in self._channel_perm]
735
+ return x.apply_values(lambda v: tf.transpose(v, perm=perm))
736
+
737
+
738
+ class Reshape(types.Stateless):
739
+ """Reshapes the channel dimensions of the input sequence.
740
+
741
+ E.g., with shape = [4, 3], tensor of shape [8, 6, 2, 6] is reshaped to
742
+ [8, 6, 4, 3].
743
+ """
744
+
745
+ def __init__(
746
+ self,
747
+ shape: Sequence[int],
748
+ name: Optional[str] = None,
749
+ ):
750
+ super().__init__(name=name)
751
+ if all([s >= 0 for s in shape]):
752
+ pass
753
+ elif not (
754
+ # Only one negative dim which is set to 1.
755
+ (sum([s < 0 for s in shape]) == sum([s == -1 for s in shape]) == 1)
756
+ # No dim is set to 0.
757
+ and (all([s != 0 for s in shape]))
758
+ ):
759
+ raise ValueError(f'Invalid target shape: {shape}')
760
+ self._shape = list(shape)
761
+
762
+ def get_output_shape(
763
+ self,
764
+ input_shape: tf.TensorShape,
765
+ constants: Optional[types.Constants] = None,
766
+ ) -> tf.TensorShape:
767
+ shape = self._shape.copy()
768
+ if any([s < 0 for s in shape]):
769
+ shape[shape.index(-1)] = input_shape.num_elements() // np.prod(
770
+ [s if s != -1 else 1 for s in shape]
771
+ )
772
+ if input_shape.num_elements() != tf.TensorShape(shape).num_elements():
773
+ raise ValueError(f'Shape mismatch: {input_shape=}, target_shape={shape}.')
774
+ return tf.TensorShape(shape)
775
+
776
+ @tf.Module.with_name_scope
777
+ def layer(
778
+ self,
779
+ x: types.Sequence,
780
+ training: bool,
781
+ initial_state: Optional[types.State] = None,
782
+ constants: Optional[types.Constants] = None,
783
+ ) -> types.Sequence:
784
+ del training
785
+ del initial_state
786
+ batch, time = utils.smart_dimension_size(x.values, [0, 1])
787
+ shape = tf.stack([batch, time] + self._shape)
788
+ # Preserve channels dimension shape information when batch or time are
789
+ # unknown.
790
+ static_shape = [None, None] + self.get_output_shape_for_sequence(
791
+ x, constants=constants
792
+ )
793
+ ret = x.apply_values(lambda v: tf.reshape(v, shape=shape))
794
+ return ret.apply_values(lambda v: tf.ensure_shape(v, static_shape))
795
+
796
+
797
+ class Emit(types.StatelessEmitting):
798
+ """An identity layer that emits its input."""
799
+
800
+ def get_output_shape(
801
+ self,
802
+ input_shape: tf.TensorShape,
803
+ constants: Optional[types.Constants] = None,
804
+ ) -> tf.TensorShape:
805
+ return input_shape
806
+
807
+ def get_emit_specs(
808
+ self,
809
+ input_spec: tf.TensorSpec,
810
+ constants: Optional[types.Constants] = None,
811
+ ) -> types.Sequence:
812
+ return types.Sequence(
813
+ tf.TensorSpec(
814
+ self.get_output_shape(input_spec.shape, constants), input_spec.dtype
815
+ ),
816
+ tf.TensorSpec(tf.TensorShape([]), types.MASK_DTYPE),
817
+ )
818
+
819
+ def layer_with_emits(
820
+ self,
821
+ x: types.Sequence,
822
+ training: bool,
823
+ initial_state: Optional[types.State] = None,
824
+ constants: Optional[types.Constants] = None,
825
+ ) -> Tuple[types.Sequence, types.Sequence]:
826
+ return x, x
827
+
828
+
829
+ class OneHot(types.Stateless):
830
+ """Computes one-hot vector of the input."""
831
+
832
+ def __init__(self, depth: int, name: Optional[str] = None):
833
+ super().__init__(name)
834
+ self._depth = depth
835
+
836
+ def get_output_shape(
837
+ self,
838
+ input_shape: tf.TensorShape,
839
+ constants: Optional[types.Constants] = None,
840
+ ) -> tf.TensorShape:
841
+ return input_shape.concatenate(self._depth)
842
+
843
+ def get_output_dtype(self, input_dtype: tf.DType) -> tf.DType:
844
+ assert input_dtype in [tf.uint8, tf.int32, tf.int64]
845
+ # TODO(soroosho): Add remaining arguments of tf.one_hot like on/off_value
846
+ # and set output_dtype based on that. Default values are tf.float32.
847
+ return utils.compute_dtype()
848
+
849
+ @tf.Module.with_name_scope
850
+ def layer(
851
+ self,
852
+ x: types.Sequence,
853
+ training: bool,
854
+ initial_state: Optional[types.State] = None,
855
+ constants: Optional[types.Constants] = None,
856
+ ) -> types.Sequence:
857
+ del training
858
+ del initial_state
859
+ # "0" is mapped to "[1] + [0] * (depth - 1)", so we mask_invalid it.
860
+ return x.apply_values(
861
+ lambda v: tf.one_hot(v, self._depth, dtype=utils.compute_dtype())
862
+ ).mask_invalid()
863
+
864
+
865
+ class Embedding(types.Stateless):
866
+ """Computes embeddings of integer input codes."""
867
+
868
+ def __init__(
869
+ self,
870
+ dimension: int,
871
+ num_embeddings: int,
872
+ embeddings_initializer='uniform',
873
+ embeddings_regularizer=None,
874
+ activity_regularizer=None,
875
+ embeddings_constraint=None,
876
+ trainable: bool = True,
877
+ name: Optional[str] = None,
878
+ ):
879
+ super().__init__(name)
880
+ with self.name_scope:
881
+ self._embedding = tf.keras.layers.Embedding(
882
+ input_dim=num_embeddings,
883
+ output_dim=dimension,
884
+ embeddings_initializer=embeddings_initializer,
885
+ embeddings_regularizer=embeddings_regularizer,
886
+ activity_regularizer=activity_regularizer,
887
+ embeddings_constraint=embeddings_constraint,
888
+ trainable=trainable,
889
+ name='embedding',
890
+ )
891
+
892
+ def get_output_shape(
893
+ self,
894
+ input_shape: tf.TensorShape,
895
+ constants: Optional[types.Constants] = None,
896
+ ) -> tf.TensorShape:
897
+ return input_shape.concatenate(self._embedding.output_dim)
898
+
899
+ def get_output_dtype(self, input_dtype: tf.DType) -> tf.DType:
900
+ assert input_dtype in [tf.uint8, tf.int32, tf.int64]
901
+ return utils.compute_dtype()
902
+
903
+ @tf.Module.with_name_scope
904
+ def layer(
905
+ self,
906
+ x: types.Sequence,
907
+ training: bool,
908
+ initial_state: Optional[types.State] = None,
909
+ constants: Optional[types.Constants] = None,
910
+ ) -> types.Sequence:
911
+ del initial_state
912
+ return x.apply_values(
913
+ lambda v: self._embedding(v, training=training)
914
+ ).mask_invalid()
915
+
916
+
917
+ class StyleToken(types.Stateless):
918
+ """Projects input onto a "style token" bottleneck.
919
+
920
+ The inputs are used to predict a soft-weighting of a set of N style token
921
+ vectors. This is equivalent to projecting the input onto an N-dimensional
922
+ simplex formed by the style token vectors.
923
+
924
+ Based on: https://arxiv.org/abs/1803.09017
925
+ """
926
+
927
+ def __init__(
928
+ self,
929
+ num_style_tokens: int,
930
+ num_heads: int,
931
+ units_per_head: int,
932
+ name=None,
933
+ ):
934
+ super().__init__(name=name)
935
+ self._num_heads = num_heads
936
+ self._units_per_head = units_per_head
937
+ with self.name_scope:
938
+ # The original style tokens implementation used glorot_uniform
939
+ # initialization, which initializes with U[-limit, limit],
940
+ # limit = sqrt(6 / (num_style_tokens + units_per_head)).
941
+ # The scale shouldn't depend on the number of tokens so we use fan_out
942
+ # here to initialize with limit = sqrt(6 / units_per_head).
943
+ self._style_tokens = tf.Variable(
944
+ tf.keras.initializers.variance_scaling(
945
+ mode='fan_out', distribution='uniform'
946
+ )((num_style_tokens, units_per_head)),
947
+ name='style_tokens',
948
+ )
949
+ # Traditionally the key vectors are a projection from the style tokens
950
+ # themselves, but making the keys a disconnected variable is
951
+ # equally (potentially more?) flexible and more efficient.
952
+ # Since this variable represents a batch of projection matrices,
953
+ # compute the limit as glorot_uniform for a
954
+ # [num_style_tokens, units_per_head] matrix.
955
+ limit = math.sqrt(6.0 / (num_style_tokens + units_per_head))
956
+ self._style_token_keys = tf.Variable(
957
+ tf.keras.initializers.RandomUniform(minval=-limit, maxval=limit)(
958
+ (1, 1, num_heads, num_style_tokens, units_per_head)
959
+ ),
960
+ name='style_token_keys',
961
+ )
962
+ self._q_proj = dense.DenseShaped(
963
+ [num_heads, 1, units_per_head], name='query_projection'
964
+ )
965
+ self._to_logits = dense.Dense(1, name='to_logits')
966
+
967
+ def get_output_shape(
968
+ self,
969
+ input_shape: tf.TensorShape,
970
+ constants: Optional[types.Constants] = None,
971
+ ) -> tf.TensorShape:
972
+ return tf.TensorShape([self._num_heads, self._units_per_head])
973
+
974
+ @tf.Module.with_name_scope
975
+ def layer(
976
+ self,
977
+ x: types.Sequence,
978
+ training: bool,
979
+ initial_state: Optional[types.State] = None,
980
+ constants: Optional[types.Constants] = None,
981
+ ) -> types.Sequence:
982
+ del initial_state
983
+ del constants
984
+
985
+ # Terminology for shapes below:
986
+ # b: Batch size.
987
+ # t: Query time.
988
+ # n: Number of heads.
989
+ # s: Number of style tokens.
990
+ # h: Units per head.
991
+
992
+ # Project x to per-head queries: [b, t, n, s=1, h]
993
+ q = self._q_proj.layer(x, training)
994
+
995
+ # Broadcast-add the key vector across batch, query time, and style tokens
996
+ # and apply tanh nonlinearity. [b, t, n, s, h]
997
+ q = q.apply_values(lambda v: tf.tanh(v + self._style_token_keys))
998
+
999
+ # Project the inner h dimension to a single dimension, then squeeze.
1000
+ # [b, t, n, s]
1001
+ logits = self._to_logits.layer(q, training).apply_values(tf.squeeze, -1)
1002
+
1003
+ # Normalize the logits to probabilities with softmax.
1004
+ # [b, t, n, s]
1005
+ probabilities = logits.apply_values(tf.nn.softmax)
1006
+
1007
+ # Compute weighted sums of the style tokens.
1008
+ context_vector = probabilities.apply_values(
1009
+ lambda v: tf.einsum('BTNS,SH->BTNH', v, self._style_tokens)
1010
+ )
1011
+ return context_vector.mask_invalid()
1012
+
1013
+
1014
+ class Identity(types.StatelessPointwise):
1015
+ """Identity pass-through of the input."""
1016
+
1017
+ @tf.Module.with_name_scope
1018
+ def layer(
1019
+ self,
1020
+ x: types.Sequence,
1021
+ training: bool,
1022
+ initial_state: Optional[types.State] = None,
1023
+ constants: Optional[types.Constants] = None,
1024
+ ) -> types.Sequence:
1025
+ del training
1026
+ del initial_state
1027
+ return x
1028
+
1029
+
1030
+ class ReverseSequence(types.SequenceLayer):
1031
+ """Reverses the sequence.
1032
+
1033
+ Note: this layer does not support running step by step.
1034
+ """
1035
+
1036
+ @property
1037
+ def block_size(self) -> int:
1038
+ raise NotImplementedError(
1039
+ 'The block_size property is undefined for ReverseSequence since it '
1040
+ 'does not support running step by step.'
1041
+ )
1042
+
1043
+ def step(
1044
+ self,
1045
+ x: types.Sequence,
1046
+ state: types.State,
1047
+ training: bool,
1048
+ constants: Optional[types.Constants] = None,
1049
+ ) -> Tuple[types.Sequence, types.State]:
1050
+ raise NotImplementedError(
1051
+ 'ReverseSequence does not support running step by step.'
1052
+ )
1053
+
1054
+ def get_initial_state(
1055
+ self, x: types.Sequence, constants: Optional[types.Constants] = None
1056
+ ) -> types.State:
1057
+ return ()
1058
+
1059
+ def get_output_shape(
1060
+ self,
1061
+ input_shape: tf.TensorShape,
1062
+ constants: Optional[types.Constants] = None,
1063
+ ) -> tf.TensorShape:
1064
+ if not input_shape.is_fully_defined():
1065
+ raise ValueError(
1066
+ '%s depends on input shape, but input has unknown '
1067
+ 'channels dimension: %s' % (self, input_shape)
1068
+ )
1069
+ return input_shape
1070
+
1071
+ @tf.Module.with_name_scope
1072
+ def layer(
1073
+ self,
1074
+ x: types.Sequence,
1075
+ training: bool,
1076
+ initial_state: Optional[types.State] = None,
1077
+ constants: Optional[types.Constants] = None,
1078
+ ) -> types.Sequence:
1079
+ return x.apply_values(
1080
+ lambda v: tf.reverse_sequence(v, x.lengths(), seq_axis=1, batch_axis=0)
1081
+ )
1082
+
1083
+
1084
+ class Upsample1D(types.Stateless):
1085
+ """Upsamples input by repeating each frame 'rate' times."""
1086
+
1087
+ @classmethod
1088
+ def _default_name(cls):
1089
+ """The default module name for this class."""
1090
+ return 'upsample1d'
1091
+
1092
+ def __init__(self, rate: int, name=None):
1093
+ super().__init__(name=name)
1094
+ self._rate = rate
1095
+
1096
+ @property
1097
+ def output_ratio(self) -> fractions.Fraction:
1098
+ """The number of output frames for one input frame."""
1099
+ return fractions.Fraction(self._rate)
1100
+
1101
+ def get_output_shape(
1102
+ self,
1103
+ input_shape: tf.TensorShape,
1104
+ constants: Optional[types.Constants] = None,
1105
+ ) -> tf.TensorShape:
1106
+ return input_shape
1107
+
1108
+ @tf.Module.with_name_scope
1109
+ def layer(
1110
+ self,
1111
+ x: types.Sequence,
1112
+ training: bool,
1113
+ initial_state: Optional[types.State] = None,
1114
+ constants: Optional[types.Constants] = None,
1115
+ ) -> types.Sequence:
1116
+ def _repeat(x):
1117
+ return tf.repeat(x, self._rate, axis=1)
1118
+
1119
+ return x.apply(lambda x, mask: (_repeat(x), _repeat(mask)))
1120
+
1121
+
1122
+ class Snake(types.StatelessPointwise):
1123
+ """The "snake" activation, i.e.
1124
+
1125
+ x + 1/beta * sin^2(x*alpha) activation.
1126
+
1127
+ Originally proposed in: https://arxiv.org/abs/2006.08195
1128
+
1129
+ Follows the extension in BigVGAN: https://arxiv.org/abs/2206.04658
1130
+ which uses a separate beta, models a parameter per channel dimension, and
1131
+ learns the parameters in log scale.
1132
+ """
1133
+
1134
+ def __init__(self, separate_beta: bool, name: Optional[str] = None):
1135
+ super().__init__(name=name)
1136
+ self._built = False
1137
+ self._separate_beta = separate_beta
1138
+ self._alpha = None
1139
+ self._beta = None
1140
+
1141
+ def _build(self, channels_shape: tf.TensorShape):
1142
+ if self._built:
1143
+ return
1144
+ with self.name_scope:
1145
+ self._alpha = tf.Variable(lambda: tf.zeros(channels_shape), name='alpha')
1146
+ if self._separate_beta:
1147
+ self._beta = tf.Variable(lambda: tf.zeros(channels_shape), name='beta')
1148
+ self._built = True
1149
+
1150
+ @tf.Module.with_name_scope
1151
+ def layer(
1152
+ self,
1153
+ x: types.Sequence,
1154
+ training: bool,
1155
+ initial_state: Optional[types.State] = None,
1156
+ constants: Optional[types.Constants] = None,
1157
+ ) -> types.Sequence:
1158
+ del training
1159
+ del initial_state
1160
+ self._build(x.channel_shape)
1161
+
1162
+ alpha = tf.math.exp(self._alpha[tf.newaxis, tf.newaxis, ...])
1163
+ if self._separate_beta:
1164
+ beta = tf.math.exp(self._beta[tf.newaxis, tf.newaxis, ...])
1165
+ else:
1166
+ beta = alpha
1167
+
1168
+ sin2_xa = tf.math.square(tf.math.sin(x.values * alpha))
1169
+ values = tf.math.divide(sin2_xa, beta + 1e-12)
1170
+ x = x.apply_values(lambda v: v + values).mask_invalid()
1171
+ return x
1172
+
1173
+
1174
+ class AssertChannelSpec(types.StatelessPointwise):
1175
+ """Assert that the channel dimension has a particular shape and dtype."""
1176
+
1177
+ def __init__(
1178
+ self,
1179
+ expected_channel_shape: tf.TensorShape | None = None,
1180
+ expected_dtype: tf.DType | None = None,
1181
+ name: str | None = None,
1182
+ ):
1183
+ super().__init__(name=name)
1184
+ self._expected_channel_shape = expected_channel_shape
1185
+ self._expected_dtype = expected_dtype
1186
+
1187
+ @tf.Module.with_name_scope
1188
+ def layer(
1189
+ self,
1190
+ x: types.Sequence,
1191
+ training: bool,
1192
+ initial_state: Optional[types.State] = None,
1193
+ constants: Optional[types.Constants] = None,
1194
+ ) -> types.Sequence:
1195
+ del training
1196
+ del initial_state
1197
+
1198
+ if (
1199
+ self._expected_channel_shape
1200
+ and x.channel_shape != self._expected_channel_shape
1201
+ ):
1202
+ raise ValueError(f'{x} does not have {self._expected_channel_shape=}')
1203
+
1204
+ if self._expected_dtype and x.dtype != self._expected_dtype:
1205
+ raise ValueError(f'{x} does not have {self._expected_dtype=}')
1206
+
1207
+ return x