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,740 @@
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
+ """DSP layers."""
15
+
16
+ import fractions
17
+ import functools
18
+ from typing import Callable, Optional, Tuple
19
+
20
+ import numpy as np
21
+ from sequence_layers.tensorflow import convolution
22
+ from sequence_layers.tensorflow import types
23
+ from sequence_layers.tensorflow import utils
24
+ import tensorflow.compat.v1 as tf1
25
+ import tensorflow.compat.v2 as tf
26
+
27
+
28
+ class Delay(types.SequenceLayer):
29
+ """A layer that delays its input by length timesteps."""
30
+
31
+ def __init__(self, length: int, name: Optional[str] = None):
32
+ super().__init__(name=name)
33
+ if length < 0:
34
+ raise ValueError(
35
+ f'Negative delay ({length}) is not supported by sl.Delay layer.'
36
+ )
37
+ self._length = length
38
+
39
+ def get_initial_state(
40
+ self, x: types.Sequence, constants: Optional[types.Constants] = None
41
+ ) -> types.State:
42
+ if self._length == 0:
43
+ return ()
44
+
45
+ channels_dims = x.values.shape.dims[2:]
46
+ batch_size = utils.smart_dimension_size(x.values, 0)
47
+ return types.Sequence(
48
+ tf.zeros(
49
+ [batch_size, self._length] + channels_dims, dtype=x.values.dtype
50
+ ),
51
+ tf.ones((batch_size, self._length), dtype=x.mask.dtype),
52
+ )
53
+
54
+ def get_output_shape(
55
+ self,
56
+ input_shape: tf.TensorShape,
57
+ constants: Optional[types.Constants] = None,
58
+ ) -> tf.TensorShape:
59
+ if not input_shape.is_fully_defined():
60
+ raise ValueError(
61
+ '%s depends on input shape, but input has unknown inner shape: %s'
62
+ % (self, input_shape)
63
+ )
64
+ return input_shape
65
+
66
+ @tf.Module.with_name_scope
67
+ def step(
68
+ self,
69
+ x: types.Sequence,
70
+ state: types.State,
71
+ training: bool,
72
+ constants: Optional[types.Constants] = None,
73
+ ) -> Tuple[types.Sequence, types.State]:
74
+ if self._length == 0:
75
+ return x, state
76
+ block_size = utils.smart_dimension_size(x.values, 1)
77
+ x = state.concatenate(x)
78
+ values, state_values = tf.split(
79
+ x.values, [block_size, self._length], axis=1
80
+ )
81
+ mask, state_mask = tf.split(x.mask, [block_size, self._length], axis=1)
82
+ state = types.Sequence(state_values, state_mask)
83
+ # No masking because timesteps are unchanged, just delayed.
84
+ return types.Sequence(values, mask), state
85
+
86
+ @tf.Module.with_name_scope
87
+ def layer(
88
+ self,
89
+ x: types.Sequence,
90
+ training: bool,
91
+ initial_state: Optional[types.State] = None,
92
+ constants: Optional[types.Constants] = None,
93
+ ) -> types.Sequence:
94
+ if self._length == 0:
95
+ return x
96
+ time = utils.smart_dimension_size(x.values, 1)
97
+ x = x.pad_time(self._length, 0, valid=True)
98
+ # No masking because timesteps are unchanged, just delayed.
99
+ return x[:, :time]
100
+
101
+
102
+ def _pad_or_truncate_for_fft(
103
+ x: types.Sequence, required_input_length: int, padding: str
104
+ ) -> types.Sequence:
105
+ """Pads or truncates the provided sequence for an FFT/IFFT/RFFT/IRFFT."""
106
+ input_dim = x.values.shape.dims[-1].value
107
+ if input_dim == required_input_length:
108
+ return x
109
+ if input_dim < required_input_length:
110
+ pad_amount = required_input_length - input_dim
111
+ if padding == 'center': # Center padding.
112
+ pad_left = pad_amount // 2
113
+ pad_right = pad_amount - pad_left
114
+ else:
115
+ assert padding == 'right'
116
+ pad_left = 0
117
+ pad_right = pad_amount
118
+ rank = x.values.shape.rank
119
+ return x.apply_values(
120
+ lambda v: tf.pad(v, [[0, 0]] * (rank - 1) + [[pad_left, pad_right]])
121
+ )
122
+ else:
123
+ assert input_dim > required_input_length
124
+
125
+ def slice_last_dim(v, start, length):
126
+ # Avoid a strided slice with ellipsis for tf.lite compatibility.
127
+ return tf.slice(
128
+ v,
129
+ [0] * (v.shape.rank - 1) + [start],
130
+ [-1] * (v.shape.rank - 1) + [length],
131
+ )
132
+
133
+ if padding == 'center':
134
+ trim_left = (input_dim - required_input_length) // 2
135
+ return x.apply_values(slice_last_dim, trim_left, required_input_length)
136
+ else:
137
+ assert padding == 'right'
138
+ return x.apply_values(slice_last_dim, 0, required_input_length)
139
+
140
+
141
+ def _validate(fft_length: int, padding: str):
142
+ if fft_length is not None and fft_length <= 0:
143
+ raise ValueError('fft_length must be positive, got: %d' % fft_length)
144
+ if padding not in ('center', 'right'):
145
+ raise ValueError('padding must be "center" or "right", got: %s' % padding)
146
+
147
+
148
+ class FFTBase(types.Stateless):
149
+ """A base class for shared FFT logic."""
150
+
151
+ def __init__(
152
+ self, fft_length: Optional[int] = None, padding: str = 'right', name=None
153
+ ):
154
+ """Creates an FFT layer.
155
+
156
+ Args:
157
+ fft_length: The length of the FFT to perform.
158
+ padding: One of 'right' or 'center'. Whether to pad inputs to `fft_length`
159
+ by padding with zeros from the right or equally on both sides.
160
+ name: An optional name for this layer.
161
+ """
162
+ super().__init__(name=name)
163
+ _validate(fft_length, padding)
164
+ self._fft_length = fft_length
165
+ self._padding = padding
166
+
167
+ def _get_fft_fn(self, fft_length: int) -> Callable[..., tf.Tensor]:
168
+ raise NotImplementedError
169
+
170
+ def _get_fft_length(self, input_shape: tf.TensorShape) -> int:
171
+ return self._fft_length or input_shape.dims[-1].value
172
+
173
+ def _get_required_input_length(self, input_shape: tf.TensorShape) -> int:
174
+ return self._get_fft_length(input_shape)
175
+
176
+ def get_output_shape(
177
+ self,
178
+ input_shape: tf.TensorShape,
179
+ constants: Optional[types.Constants] = None,
180
+ ) -> tf.TensorShape:
181
+ # FFT operates over the inner-most dimension.
182
+ return input_shape[:-1].concatenate(self._get_fft_length(input_shape))
183
+
184
+ @tf.Module.with_name_scope
185
+ def layer(
186
+ self,
187
+ x: types.Sequence,
188
+ training: bool,
189
+ initial_state: Optional[types.State] = None,
190
+ constants: Optional[types.Constants] = None,
191
+ ) -> types.Sequence:
192
+ del training
193
+ del initial_state
194
+ required_input_length = self._get_required_input_length(x.channel_shape)
195
+ fft_length = self._get_fft_length(x.channel_shape)
196
+ fft_fn = self._get_fft_fn(fft_length)
197
+ x = _pad_or_truncate_for_fft(x, required_input_length, self._padding)
198
+ return x.apply_values(fft_fn).mask_invalid()
199
+
200
+
201
+ class FFT(FFTBase):
202
+ """A layer that applies an FFT to the channels dimension."""
203
+
204
+ def _get_fft_fn(self, fft_length: int) -> Callable[..., tf.Tensor]:
205
+ del fft_length
206
+ return tf.signal.fft
207
+
208
+
209
+ class IFFT(FFTBase):
210
+ """A layer that applies an IFFT to the channels dimension."""
211
+
212
+ def _get_fft_fn(self, fft_length: int) -> Callable[..., tf.Tensor]:
213
+ del fft_length
214
+ return tf.signal.ifft
215
+
216
+
217
+ class RFFT(FFTBase):
218
+ """A layer that applies an RFFT to the channels dimension."""
219
+
220
+ def _get_fft_fn(self, fft_length: int) -> Callable[..., tf.Tensor]:
221
+ return functools.partial(tf.signal.rfft, fft_length=[fft_length])
222
+
223
+ def get_output_shape(
224
+ self,
225
+ input_shape: tf.TensorShape,
226
+ constants: Optional[types.Constants] = None,
227
+ ) -> tf.TensorShape:
228
+ return input_shape[:-1].concatenate(
229
+ self._get_fft_length(input_shape) // 2 + 1
230
+ )
231
+
232
+ def get_output_dtype(self, input_dtype: tf.DType) -> tf.DType:
233
+ return tf.complex64
234
+
235
+
236
+ class IRFFT(FFTBase):
237
+ """A layer that applies an IRFFT to the channels dimension."""
238
+
239
+ def get_output_dtype(self, input_dtype: tf.DType) -> tf.DType:
240
+ return tf.float32
241
+
242
+ def _get_fft_fn(self, fft_length: int):
243
+ return functools.partial(tf.signal.irfft, fft_length=[fft_length])
244
+
245
+ def _get_fft_length(self, input_shape: tf.TensorShape) -> int:
246
+ return self._fft_length or (input_shape.dims[-1].value - 1) * 2
247
+
248
+ def _get_required_input_length(self, input_shape: tf.TensorShape) -> int:
249
+ return self._get_fft_length(input_shape) // 2 + 1
250
+
251
+
252
+ class RDFT(types.Stateless):
253
+ """Computes the Real Discrete Fourier Transform using a matrix multiply.
254
+
255
+ This matches tf.signal.rfft's conventions in terms of normalization and
256
+ conjugation.
257
+ """
258
+
259
+ def __init__(
260
+ self,
261
+ dft_length: int,
262
+ padding: str = 'right',
263
+ output_magnitude: bool = False,
264
+ name=None,
265
+ ):
266
+ """Creates an RDFT layer.
267
+
268
+ Args:
269
+ dft_length: The length of the DFT to perform.
270
+ padding: One of 'right' or 'center'. Whether to pad inputs to `dft_length`
271
+ by padding with zeros from the right or equally on both sides.
272
+ output_magnitude: If true, output magnitude of the RDFT, otherwise the
273
+ complex spectrum.
274
+ name: An optional name for this layer.
275
+ """
276
+ super().__init__(name=name)
277
+ self._dft_length = dft_length
278
+ self._padding = padding
279
+ self._output_magnitude = output_magnitude
280
+ self._real_dft_tensor = None
281
+ self._imag_dft_tensor = None
282
+
283
+ def get_output_shape(
284
+ self,
285
+ input_shape: tf.TensorShape,
286
+ constants: Optional[types.Constants] = None,
287
+ ) -> tf.TensorShape:
288
+ return input_shape[:-1].concatenate(self._dft_length // 2 + 1)
289
+
290
+ def get_output_dtype(self, input_dtype):
291
+ return tf.float32 if self._output_magnitude else tf.complex64
292
+
293
+ def build(self, input_shape):
294
+ if self._real_dft_tensor is not None:
295
+ return
296
+
297
+ # See https://en.wikipedia.org/wiki/DFT_matrix
298
+ omega = (0 + 1j) * 2.0 * np.pi / float(self._dft_length)
299
+ # Don't include 1/sqrt(N) scaling, tf.signal.rfft doesn't apply it.
300
+ dft_matrix = np.exp(
301
+ omega
302
+ * np.outer(np.arange(self._dft_length), np.arange(self._dft_length))
303
+ )
304
+
305
+ # We are right-multiplying by the DFT matrix, and we are keeping
306
+ # only the first half ("positive frequencies").
307
+ # So discard the second half of rows, but transpose the array for
308
+ # right-multiplication.
309
+ # The DFT matrix is symmetric, so we could have done it more
310
+ # directly, but this reflects our intention better.
311
+ complex_dft_matrix_kept_values = dft_matrix[
312
+ : self._dft_length // 2 + 1, :
313
+ ].transpose()
314
+ self._real_dft_tensor = tf.constant(
315
+ np.real(complex_dft_matrix_kept_values).astype(np.float32),
316
+ name='real_dft_matrix',
317
+ )
318
+ self._imag_dft_tensor = tf.constant(
319
+ np.imag(complex_dft_matrix_kept_values).astype(np.float32),
320
+ name='imaginary_dft_matrix',
321
+ )
322
+
323
+ @tf.Module.with_name_scope
324
+ def layer(
325
+ self,
326
+ x: types.Sequence,
327
+ training: bool,
328
+ initial_state: Optional[types.State] = None,
329
+ constants: Optional[types.Constants] = None,
330
+ ) -> types.Sequence:
331
+ self.build(x.channel_shape)
332
+ padded_signal = _pad_or_truncate_for_fft(
333
+ x, self._dft_length, padding=self._padding
334
+ )
335
+ result_real_part = tf.matmul(padded_signal.values, self._real_dft_tensor)
336
+ result_imag_part = tf.matmul(padded_signal.values, self._imag_dft_tensor)
337
+ if self._output_magnitude:
338
+ values = tf.sqrt(
339
+ tf.square(result_real_part) + tf.square(result_imag_part)
340
+ )
341
+ else:
342
+ # For compatibility with tf.signal.rfft, use the conjugate.
343
+ values = tf.complex(result_real_part, -result_imag_part)
344
+ return types.Sequence(values, padded_signal.mask).mask_invalid()
345
+
346
+
347
+ class Frame(types.SequenceLayer):
348
+ """Produce a sequence of overlapping frames of the input sequence."""
349
+
350
+ def __init__(self, frame_length: int, frame_step: int, name=None):
351
+ """Creates a framing layer which produces overlapping frames of the input.
352
+
353
+ Args:
354
+ frame_length: The length of frames to generate.
355
+ frame_step: The step or stride of the frames.
356
+ name: An optional name for the layer.
357
+ """
358
+ super().__init__(name=name)
359
+ self._frame_length = frame_length
360
+ self._frame_step = frame_step
361
+ if frame_length <= 0:
362
+ raise ValueError('frame_length must be positive, got: %d' % frame_length)
363
+ if frame_step <= 0:
364
+ raise ValueError('frame_step must be positive, got: %d' % frame_step)
365
+ self._buffer_width = frame_length - 1
366
+
367
+ @property
368
+ def block_size(self) -> int:
369
+ return self._frame_step
370
+
371
+ @property
372
+ def output_ratio(self) -> fractions.Fraction:
373
+ return fractions.Fraction(1, self._frame_step)
374
+
375
+ def get_initial_state(
376
+ self, x: types.Sequence, constants: Optional[types.Constants] = None
377
+ ) -> types.State:
378
+ if self._buffer_width == 0:
379
+ return ()
380
+ inner_shape = x.channel_shape
381
+ batch_size = utils.smart_dimension_size(x.values, 0)
382
+ return types.Sequence(
383
+ tf.zeros(
384
+ [batch_size, self._buffer_width] + inner_shape.as_list(),
385
+ dtype=x.values.dtype,
386
+ ),
387
+ tf.ones((batch_size, self._buffer_width), dtype=x.mask.dtype),
388
+ )
389
+
390
+ def get_output_shape(
391
+ self,
392
+ input_shape: tf.TensorShape,
393
+ constants: Optional[types.Constants] = None,
394
+ ) -> tf.TensorShape:
395
+ if not input_shape.is_fully_defined():
396
+ raise ValueError(
397
+ '%s depends on input shape, but input has unknown inner shape: %s'
398
+ % (self, input_shape)
399
+ )
400
+ return tf.TensorShape([self._frame_length]).concatenate(input_shape)
401
+
402
+ @tf.Module.with_name_scope
403
+ def step(
404
+ self,
405
+ x: types.Sequence,
406
+ state: types.State,
407
+ training: bool,
408
+ constants: Optional[types.Constants] = None,
409
+ ) -> Tuple[types.Sequence, types.State]:
410
+ if self._buffer_width > 0:
411
+ state = state.concatenate(x)
412
+ else:
413
+ state = x
414
+ values = tf.signal.frame(
415
+ state.values,
416
+ frame_length=self._frame_length,
417
+ frame_step=self._frame_step,
418
+ pad_end=False,
419
+ axis=1,
420
+ )
421
+ mask = convolution.compute_conv_mask(
422
+ state.mask,
423
+ kernel_size=self._frame_length,
424
+ stride=self._frame_step,
425
+ dilation_rate=1,
426
+ padding='causal',
427
+ )
428
+
429
+ # Keep the last buffer_width samples as state.
430
+ if self._buffer_width > 0:
431
+ state = state[:, -self._buffer_width :]
432
+ else:
433
+ state = ()
434
+ return types.Sequence(values, mask).mask_invalid(), state
435
+
436
+ @tf.Module.with_name_scope
437
+ def layer(
438
+ self,
439
+ x: types.Sequence,
440
+ training: bool,
441
+ initial_state: Optional[types.State] = None,
442
+ constants: Optional[types.Constants] = None,
443
+ ) -> types.Sequence:
444
+ causal_padding = self._frame_length - 1
445
+ x = x.pad_time(causal_padding, 0, valid=True)
446
+ values = tf.signal.frame(
447
+ x.values,
448
+ frame_length=self._frame_length,
449
+ frame_step=self._frame_step,
450
+ pad_end=False,
451
+ axis=1,
452
+ )
453
+ mask = convolution.compute_conv_mask(
454
+ x.mask,
455
+ kernel_size=self._frame_length,
456
+ stride=self._frame_step,
457
+ dilation_rate=1,
458
+ padding='causal',
459
+ )
460
+ return types.Sequence(values, mask).mask_invalid()
461
+
462
+
463
+ class BaseSTFT(types.SequenceLayer):
464
+ """Base class for STFT-like logic."""
465
+
466
+ def __init__(
467
+ self,
468
+ frame_length: int,
469
+ frame_step: int,
470
+ fft_length: int,
471
+ window_fn,
472
+ padding: str,
473
+ use_dft_matrix: bool,
474
+ output_magnitude: bool,
475
+ name=None,
476
+ ):
477
+ """Creates a BaseSTFT layer."""
478
+ super().__init__(name=name)
479
+ self._frame_length = frame_length
480
+ self._framer = Frame(frame_length, frame_step)
481
+ self._window = None
482
+ self._window_fn = window_fn
483
+ self._output_magnitude = output_magnitude
484
+ if use_dft_matrix:
485
+ self._dft = RDFT(
486
+ fft_length, padding=padding, output_magnitude=output_magnitude
487
+ )
488
+ else:
489
+ self._dft = RFFT(fft_length, padding=padding)
490
+
491
+ @property
492
+ def block_size(self) -> int:
493
+ return self._framer.block_size
494
+
495
+ @property
496
+ def output_ratio(self) -> fractions.Fraction:
497
+ return self._framer.output_ratio
498
+
499
+ def get_initial_state(
500
+ self, x: types.Sequence, constants: Optional[types.Constants] = None
501
+ ) -> types.State:
502
+ return self._framer.get_initial_state(x, constants)
503
+
504
+ def get_output_shape(
505
+ self,
506
+ input_shape: tf.TensorShape,
507
+ constants: Optional[types.Constants] = None,
508
+ ) -> tf.TensorShape:
509
+ if input_shape.rank != 0:
510
+ raise ValueError(
511
+ 'Expected [b, t] input, but got %s:'
512
+ % tf.TensorShape([None, None]).concatenate(input_shape)
513
+ )
514
+ frame_shape = self._framer.get_output_shape(input_shape, constants)
515
+ dft_shape = self._dft.get_output_shape(frame_shape, constants)
516
+ return dft_shape
517
+
518
+ def get_output_dtype(self, input_dtype: tf.DType) -> tf.DType:
519
+ if self._output_magnitude:
520
+ return tf.float32
521
+ else:
522
+ return self._dft.get_output_dtype(input_dtype)
523
+
524
+ def build(self, input_shape):
525
+ if self._window is None and self._window_fn is not None:
526
+ self._window = self._window_fn(self._frame_length)
527
+
528
+ @tf.Module.with_name_scope
529
+ def step(
530
+ self,
531
+ x: types.Sequence,
532
+ state: types.State,
533
+ training: bool,
534
+ constants: Optional[types.Constants] = None,
535
+ ) -> Tuple[types.Sequence, types.State]:
536
+ self.build(x.channel_shape)
537
+ framed, state = self._framer.step(x, state, training, constants)
538
+ if self._window is not None:
539
+ framed = framed.apply_values(lambda v: v * self._window)
540
+ dft, _ = self._dft.step(framed, (), training, constants)
541
+ if self._output_magnitude and dft.values.dtype.is_complex:
542
+ dft = dft.apply_values(tf.abs)
543
+ return dft, state
544
+
545
+ @tf.Module.with_name_scope
546
+ def layer(
547
+ self,
548
+ x: types.Sequence,
549
+ training: bool,
550
+ initial_state: Optional[types.State] = None,
551
+ constants: Optional[types.Constants] = None,
552
+ ) -> types.Sequence:
553
+ self.build(x.channel_shape)
554
+ framed = self._framer.layer(
555
+ x, training, initial_state=initial_state, constants=constants
556
+ )
557
+ if self._window is not None:
558
+ framed = framed.apply_values(lambda v: v * self._window)
559
+ dft = self._dft.layer(framed, training, constants=constants)
560
+ if self._output_magnitude and dft.values.dtype.is_complex:
561
+ dft = dft.apply_values(tf.abs)
562
+ return dft
563
+
564
+
565
+ class STFT(BaseSTFT):
566
+ """Computes the Short-time Fourier Transform of input signals.
567
+
568
+ When used with 'right' padding, equivalent to tf.signal.stft.
569
+ """
570
+
571
+ def __init__(
572
+ self,
573
+ frame_length: int,
574
+ frame_step: int,
575
+ fft_length: int,
576
+ window_fn=tf.signal.hann_window,
577
+ padding: str = 'right',
578
+ use_dft_matrix: bool = False,
579
+ name=None,
580
+ ):
581
+ """Creates an STFT layer.
582
+
583
+ Args:
584
+ frame_length: The frame length of the STFT.
585
+ frame_step: The frame step of the STFT.
586
+ fft_length: The FFT length of the STFT.
587
+ window_fn: The window to use in the STFT. A callable that takes a window
588
+ length and a dtype keyword argument and returns a [window_length] Tensor
589
+ of samples. If None, no windowing is used.
590
+ padding: One of 'right' or 'center'. Whether to pad inputs to `fft_length`
591
+ by padding with zeros from the right or equally on both sides.
592
+ use_dft_matrix: If true, uses an RDFT matrix multiply to compute the
593
+ spectrum instead of an RFFT. Useful for tf.lite support.
594
+ name: An optional name for the layer.
595
+ """
596
+ super().__init__(
597
+ frame_length,
598
+ frame_step,
599
+ fft_length,
600
+ window_fn,
601
+ padding,
602
+ use_dft_matrix,
603
+ output_magnitude=False,
604
+ name=name,
605
+ )
606
+
607
+
608
+ class Spectrogram(BaseSTFT):
609
+ """Computes a magnitude spectrogram of input signals.
610
+
611
+ When used with 'right' padding, equivalent to tf.abs(tf.signal.stft(.)).
612
+ """
613
+
614
+ def __init__(
615
+ self,
616
+ frame_length: int,
617
+ frame_step: int,
618
+ fft_length: int,
619
+ window_fn=tf.signal.hann_window,
620
+ padding: str = 'right',
621
+ use_dft_matrix: bool = False,
622
+ name=None,
623
+ ):
624
+ """Creates a Spectrogram layer.
625
+
626
+ Args:
627
+ frame_length: The frame length of the STFT.
628
+ frame_step: The frame step of the STFT.
629
+ fft_length: The FFT length of the STFT.
630
+ window_fn: The window to use in the STFT. A callable that takes a window
631
+ length and a dtype keyword argument and returns a [window_length] Tensor
632
+ of samples. If None, no windowing is used.
633
+ padding: One of 'right' or 'center'. Whether to pad inputs to `fft_length`
634
+ by padding with zeros from the right or equally on both sides.
635
+ use_dft_matrix: If true, uses an RDFT matrix multiply to compute the
636
+ spectrum instead of an RFFT. Useful for tf.lite support.
637
+ name: An optional name for the layer.
638
+ """
639
+ super().__init__(
640
+ frame_length,
641
+ frame_step,
642
+ fft_length,
643
+ window_fn,
644
+ padding,
645
+ use_dft_matrix,
646
+ output_magnitude=True,
647
+ name=name,
648
+ )
649
+
650
+
651
+ class LinearToMelSpectrogram(types.Stateless):
652
+ """Converts linear-scale spectrogram to a mel-scale spectrogram.
653
+
654
+ The spectrogram magnitudes should be uncompressed, *not* log compressed.
655
+ Summation is performed across bands, which in log magnitdue would be
656
+ multiplication.
657
+ """
658
+
659
+ def __init__(
660
+ self,
661
+ num_mel_bins: int,
662
+ sample_rate: float,
663
+ lower_edge_hertz: float,
664
+ upper_edge_hertz: float,
665
+ name: Optional[str] = None,
666
+ ):
667
+ """Creates a LinearToMelSpectrogram layer.
668
+
669
+ Args:
670
+ num_mel_bins: The number of mel bins to compute.
671
+ sample_rate: The sample rate of the spectrum.
672
+ lower_edge_hertz: Lower bound on the frequencies to be included in the mel
673
+ spectrum. This corresponds to the lower edge of the lowest triangular
674
+ band.
675
+ upper_edge_hertz: The desired top edge of the highest frequency band.
676
+ name: An optional name for the layer.
677
+ """
678
+ super().__init__(name=name)
679
+ self._num_mel_bins = num_mel_bins
680
+ self._sample_rate = sample_rate
681
+ self._lower_edge_hertz = lower_edge_hertz
682
+ self._upper_edge_hertz = upper_edge_hertz
683
+ self._mel_kernel = None
684
+
685
+ def _get_mel_kernel(self, num_spectrogram_bins, dtype):
686
+ # TODO(rryan): Extract this into a general helper for caching tensors.
687
+ # We recompute the mel kernel if:
688
+ should_recompute = (
689
+ # We have not cached the mel kernel yet.
690
+ self._mel_kernel is None
691
+ or
692
+ # The dtype does not match the requested dtype.
693
+ self._mel_kernel.dtype != dtype
694
+ or
695
+ # We are in Eager mode but the cached tensor is not an EagerTensor.
696
+ (tf.executing_eagerly() and not hasattr(self._mel_kernel, 'numpy'))
697
+ or
698
+ # We are in graph mode, the cached tensor is not an Eager tensor and its
699
+ # graph is not this graph.
700
+ (
701
+ not tf.executing_eagerly()
702
+ and not hasattr(self._mel_kernel, 'numpy')
703
+ and self._mel_kernel.graph != tf1.get_default_graph()
704
+ )
705
+ )
706
+ if should_recompute:
707
+ self._mel_kernel = tf.signal.linear_to_mel_weight_matrix(
708
+ num_mel_bins=self._num_mel_bins,
709
+ num_spectrogram_bins=num_spectrogram_bins,
710
+ sample_rate=self._sample_rate,
711
+ lower_edge_hertz=self._lower_edge_hertz,
712
+ upper_edge_hertz=self._upper_edge_hertz,
713
+ dtype=dtype,
714
+ )
715
+ return self._mel_kernel
716
+
717
+ def get_output_shape(
718
+ self,
719
+ input_shape: tf.TensorShape,
720
+ constants: Optional[types.Constants] = None,
721
+ ) -> tf.TensorShape:
722
+ if input_shape.rank == 0:
723
+ raise ValueError(
724
+ f'{self} requires input with at least rank 1, got: {input_shape}'
725
+ )
726
+ return input_shape[:-1].concatenate(self._num_mel_bins)
727
+
728
+ def layer(
729
+ self,
730
+ x: types.Sequence,
731
+ training: bool,
732
+ initial_state: Optional[types.State] = None,
733
+ constants: Optional[types.Constants] = None,
734
+ ) -> types.Sequence:
735
+ num_spectrogram_bins = x.values.shape.dims[-1].value
736
+ # Do not cache the linear_to_mel matrix since we may be inside a FuncGraph.
737
+ linear_to_mel = self._get_mel_kernel(num_spectrogram_bins, x.values.dtype)
738
+ # No masking is required because a weight matrix applied to a masked
739
+ # timestep is also masked.
740
+ return x.apply_values(tf.tensordot, linear_to_mel, 1)