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,1686 @@
1
+ # Copyright 2024 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 abc
17
+ import dataclasses
18
+ import fractions
19
+ import math
20
+ from typing import Callable, Literal
21
+
22
+ import flax.linen as nn
23
+ import jax
24
+ import jax.numpy as jnp
25
+ import numpy as np
26
+ from sequence_layers.jax import convolution
27
+ from sequence_layers.jax import signal
28
+ from sequence_layers.jax import types
29
+
30
+ __all__ = (
31
+ # go/keep-sorted start
32
+ 'Delay',
33
+ 'FFT',
34
+ 'Frame',
35
+ 'IFFT',
36
+ 'IRFFT',
37
+ 'InverseSTFT',
38
+ 'LinearToMelSpectrogram',
39
+ 'Lookahead',
40
+ 'OverlapAdd',
41
+ 'RFFT',
42
+ 'STFT',
43
+ 'Window',
44
+ # go/keep-sorted end
45
+ )
46
+
47
+ _DEFAULT_FFT_PADDING = 'right'
48
+
49
+ FFTPaddingString = Literal['center', 'right']
50
+
51
+
52
+ class Frame(types.PreservesType, types.SequenceLayer):
53
+ """Produce a sequence of overlapping frames of the input sequence."""
54
+
55
+ @dataclasses.dataclass(frozen=True)
56
+ class Config(types.SequenceLayerConfig):
57
+ """Config for Frame layer."""
58
+
59
+ # The length of frames to generate.
60
+ frame_length: int
61
+ # The step or stride of the frames.
62
+ frame_step: int
63
+ # Padding to use for the framing. If explicit padding is provided it must
64
+ # sum to frame_length - 1. If 'causal_valid', 'reverse_causal_valid',
65
+ # 'causal', 'reverse_causal', 'semicausal' or if the explicit padding sums
66
+ # to `frame_length - 1`, then the `Frame` is streamable.
67
+ # TODO(b/407645797): Support explicit padding in general.
68
+ padding: tuple[int, int] | types.PaddingModeString = (
69
+ types.PaddingMode.REVERSE_CAUSAL_VALID.value
70
+ )
71
+ # TODO(b/407645797): Remove this and migrate all users to SAME-like padding
72
+ # in explicit mode.
73
+ explicit_padding_is_same_like: bool = False
74
+ # An optional name for the layer.
75
+ name: str | None = None
76
+
77
+ def __post_init__(self):
78
+ if isinstance(self.padding, str):
79
+ object.__setattr__(
80
+ self, 'padding', types.validate_padding(self.padding)
81
+ )
82
+ elif sum(self.padding) != self.frame_length - 1:
83
+ raise NotImplementedError(
84
+ f'{self.padding=} must sum to {self.frame_length - 1=}'
85
+ )
86
+
87
+ def make(self) -> 'Frame':
88
+ return Frame(self, name=self.name)
89
+
90
+ config: Config
91
+
92
+ def setup(self) -> None:
93
+ if self.config.frame_length <= 0:
94
+ raise ValueError(
95
+ 'frame_length must be positive, got: %d' % self.config.frame_length
96
+ )
97
+ if self.config.frame_step <= 0:
98
+ raise ValueError(
99
+ 'frame_step must be positive, got: %d' % self.config.frame_step
100
+ )
101
+
102
+ @property
103
+ def supports_step(self) -> bool:
104
+ if isinstance(self.config.padding, str):
105
+ return self.config.padding in (
106
+ types.PaddingMode.CAUSAL_VALID.value,
107
+ types.PaddingMode.REVERSE_CAUSAL_VALID.value,
108
+ types.PaddingMode.CAUSAL.value,
109
+ types.PaddingMode.REVERSE_CAUSAL.value,
110
+ types.PaddingMode.SEMICAUSAL.value,
111
+ )
112
+ else:
113
+ past_pad, future_pad = self.config.padding
114
+ # Allow stepping as long as total padding is frame_length - 1.
115
+ return past_pad + future_pad == self.config.frame_length - 1
116
+
117
+ @property
118
+ def block_size(self) -> int:
119
+ return self.config.frame_step
120
+
121
+ @property
122
+ def output_ratio(self) -> fractions.Fraction:
123
+ return fractions.Fraction(1, self.config.frame_step)
124
+
125
+ @property
126
+ def input_latency(self) -> int:
127
+ if not isinstance(self.config.padding, str):
128
+ past_pad, _ = self.config.padding
129
+ return max(0, (self.config.frame_length - 1) - past_pad)
130
+ match self.config.padding:
131
+ case (
132
+ types.PaddingMode.CAUSAL_VALID.value
133
+ | types.PaddingMode.CAUSAL.value
134
+ | types.PaddingMode.SEMICAUSAL.value
135
+ ):
136
+ # Causal padding eliminates latency.
137
+ return 0
138
+ case (
139
+ types.PaddingMode.REVERSE_CAUSAL_VALID.value
140
+ | types.PaddingMode.REVERSE_CAUSAL.value
141
+ ):
142
+ # Reverse causal introduces no past padding in layer-wise mode, so we
143
+ # need a full effective_kernel_size kernel to compute the first output
144
+ # layer-wise processing would produce. Since we do not count the current
145
+ # input as part of the latency, the input latency is one smaller than
146
+ # the effective kernel size.
147
+ return self.config.frame_length - 1
148
+ case types.PaddingMode.SEMICAUSAL_FULL.value:
149
+ # SEMICAUSAL_FULL padding only needs to wait for frame_step samples.
150
+ return self.config.frame_step - 1
151
+ case _:
152
+ # Unsupported.
153
+ return 0
154
+
155
+ @property
156
+ def output_latency(self) -> int:
157
+ """Returns the output latency of this layer.
158
+
159
+ Output latency is defined as the number of output timesteps before the
160
+ step-wise output of the layer matches its layer-wise output.
161
+ """
162
+ match self.config.padding:
163
+ case types.PaddingMode.SEMICAUSAL_FULL.value:
164
+ # The semicausal-full padding has both left and right padding, which
165
+ # requires a different output_latency for correct operations.
166
+ # It only requires to wait for strides[0] - 1 samples, and the
167
+ # output_ratio is also strides[0], which means the latency is 0.
168
+ return 0
169
+ case _:
170
+ # Other cases are handled in the parent class.
171
+ return super().output_latency
172
+
173
+ @property
174
+ def receptive_field_per_step(self) -> dict[int, types.ReceptiveField]:
175
+ return convolution.conv_receptive_field_per_step(
176
+ self.config.frame_length, self.config.frame_step, 1, self.config.padding
177
+ )
178
+
179
+ @property
180
+ def _buffer_width(self) -> int:
181
+ if not isinstance(self.config.padding, str):
182
+ past_pad, future_pad = self.config.padding
183
+ assert past_pad + future_pad == self.config.frame_length - 1
184
+ return (
185
+ self.config.frame_length - 1 - (future_pad % self.config.frame_step)
186
+ )
187
+
188
+ match self.config.padding:
189
+ case types.PaddingMode.SEMICAUSAL.value:
190
+ return max(self.config.frame_length - self.config.frame_step, 0)
191
+ case (
192
+ types.PaddingMode.REVERSE_CAUSAL.value
193
+ | types.PaddingMode.REVERSE_CAUSAL_VALID.value
194
+ ):
195
+ return (
196
+ (self.config.frame_length - 1)
197
+ // self.config.frame_step
198
+ * self.config.frame_step
199
+ )
200
+ case (
201
+ types.PaddingMode.CAUSAL.value | types.PaddingMode.CAUSAL_VALID.value
202
+ ):
203
+ return self.config.frame_length - 1
204
+ case _:
205
+ raise NotImplementedError(
206
+ f'Unsupported padding mode: {self.config.padding}'
207
+ )
208
+
209
+ def get_initial_state(
210
+ self,
211
+ batch_size: int,
212
+ input_spec: types.ChannelSpec,
213
+ *,
214
+ training: bool,
215
+ constants: types.Constants | None = None,
216
+ ) -> types.State:
217
+ # Special case kernel_size 1 since it is stateless.
218
+ if not (buffer_width := self._buffer_width):
219
+ return ()
220
+
221
+ match self.config.padding:
222
+ case (
223
+ types.PaddingMode.CAUSAL_VALID.value
224
+ | types.PaddingMode.REVERSE_CAUSAL_VALID.value
225
+ | types.PaddingMode.SEMICAUSAL_FULL.value
226
+ ):
227
+ # For CAUSAL_VALID and REVERSE_CAUSAL_VALID, since the mask calculation
228
+ # is a windowed logical-AND, we have to prepend the mask with valid
229
+ # samples, otherwise the first output timesteps that touch this padding
230
+ # become invalid.
231
+ mask = jnp.ones((batch_size, buffer_width), dtype=types.MASK_DTYPE)
232
+ case (
233
+ types.PaddingMode.CAUSAL.value
234
+ | types.PaddingMode.REVERSE_CAUSAL.value
235
+ | types.PaddingMode.SEMICAUSAL.value
236
+ ):
237
+ mask = jnp.zeros((batch_size, buffer_width), dtype=types.MASK_DTYPE)
238
+ case (unused_pad_left, unused_pad_right):
239
+ if self.config.explicit_padding_is_same_like:
240
+ mask = jnp.zeros((batch_size, buffer_width), dtype=types.MASK_DTYPE)
241
+ else:
242
+ mask = jnp.ones((batch_size, buffer_width), dtype=types.MASK_DTYPE)
243
+ case _:
244
+ raise ValueError(
245
+ 'Stepwise processing is not supported with padding:'
246
+ f' {self._paddings[0]}'
247
+ )
248
+
249
+ return types.MaskedSequence(
250
+ jnp.zeros(
251
+ (batch_size, buffer_width) + input_spec.shape,
252
+ dtype=input_spec.dtype,
253
+ ),
254
+ mask,
255
+ )
256
+
257
+ @nn.nowrap
258
+ def get_output_shape(
259
+ self,
260
+ input_shape: types.ShapeLike,
261
+ *,
262
+ constants: types.Constants | None = None,
263
+ ) -> types.Shape:
264
+ return (self.config.frame_length,) + tuple(input_shape)
265
+
266
+ @types.check_step
267
+ def step(
268
+ self,
269
+ x: types.Sequence,
270
+ state: types.State,
271
+ *,
272
+ training: bool,
273
+ constants: types.Constants | None = None,
274
+ ) -> tuple[types.Sequence, types.State]:
275
+ if self.config.frame_length > 1:
276
+ x = x.mask_invalid()
277
+
278
+ if buffer_width := self._buffer_width:
279
+ # Concatenate the new frames with the previous buffer_width frames.
280
+ state = state.concatenate(x)
281
+ else:
282
+ state = x
283
+
284
+ values = signal.frame(
285
+ state.values,
286
+ frame_length=self.config.frame_length,
287
+ frame_step=self.config.frame_step,
288
+ # Padding is already applied via the state.
289
+ pad_mode=types.PaddingMode.VALID.value,
290
+ axis=1,
291
+ )
292
+ mask = convolution.compute_conv_mask(
293
+ state.mask,
294
+ kernel_size=self.config.frame_length,
295
+ stride=self.config.frame_step,
296
+ dilation_rate=1,
297
+ padding=self.config.padding,
298
+ is_step=True,
299
+ )
300
+
301
+ # Keep the trailing buffer_width samples for the next step.
302
+ if buffer_width:
303
+ state = state[:, -buffer_width:]
304
+ else:
305
+ state = ()
306
+
307
+ # Framing can leave unmasked values with non-zero values.
308
+ return types.Sequence(values, mask), state
309
+
310
+ @types.check_layer
311
+ def layer(
312
+ self,
313
+ x: types.Sequence,
314
+ *,
315
+ training: bool,
316
+ constants: types.Constants | None = None,
317
+ ) -> types.Sequence:
318
+ # Mask inputs if receptive field is greater than 1.
319
+ if self.config.frame_length > 1:
320
+ x = x.mask_invalid()
321
+
322
+ values = signal.frame(
323
+ x.values,
324
+ frame_length=self.config.frame_length,
325
+ frame_step=self.config.frame_step,
326
+ pad_mode=self.config.padding,
327
+ axis=1,
328
+ )
329
+ mask = convolution.compute_conv_mask(
330
+ x.mask,
331
+ kernel_size=self.config.frame_length,
332
+ stride=self.config.frame_step,
333
+ dilation_rate=1,
334
+ padding=self.config.padding,
335
+ is_step=False,
336
+ )
337
+
338
+ # If the frame receptive field is 1 then preserve the input mask state.
339
+ result_type = types.Sequence if self.config.frame_length > 1 else type(x)
340
+ return result_type(values, mask)
341
+
342
+
343
+ class OverlapAdd(types.PreservesType, types.SequenceLayer):
344
+ """Overlap adds windows of [b, t, frame_length, ...].
345
+
346
+ For a [b, ti, frame_length, ...] input signal, the resulting sequence has
347
+ shape [b, to, ...], where:
348
+
349
+ to = (ti - 1) * frame_step + frame_length
350
+
351
+ Since OverlapAdd.step can only produce frame_step samples at a time, we trim
352
+ the output of layer() to drop the final `frame_length - frame_step` timesteps.
353
+ """
354
+
355
+ @dataclasses.dataclass(frozen=True)
356
+ class Config(types.SequenceLayerConfig):
357
+ """Config for OverlapAdd layer."""
358
+
359
+ # The length of frames to overlap-add.
360
+ frame_length: int
361
+ # The step or stride of the overlap-add operation.
362
+ frame_step: int
363
+ # Padding to use for the overlap-add. Only 'causal', 'valid', and
364
+ # 'semicausal_full' are supported.
365
+ # The 'semicausal_full' padding will trim (frame_length - frame_step)
366
+ # samples from the right side of the signal. This behavior is intended
367
+ # to remove the part that was padded by an hypothetical Frame layer also
368
+ # using the same padding type. This allows sample aligned reconstruction in
369
+ # layer mode.
370
+ padding: types.PaddingModeString = types.PaddingMode.VALID.value
371
+ # An optional name for the layer.
372
+ name: str | None = None
373
+
374
+ def __post_init__(self):
375
+ object.__setattr__(self, 'padding', types.validate_padding(self.padding))
376
+
377
+ if self.padding not in (
378
+ types.PaddingMode.CAUSAL.value,
379
+ types.PaddingMode.VALID.value,
380
+ types.PaddingMode.SEMICAUSAL_FULL.value,
381
+ ):
382
+ raise ValueError(f'Unsupported padding mode: {self.padding}')
383
+
384
+ def make(self) -> 'OverlapAdd':
385
+ return OverlapAdd(self, name=self.name)
386
+
387
+ config: Config
388
+
389
+ def setup(self) -> None:
390
+ if self.config.frame_length <= 0:
391
+ raise ValueError(
392
+ 'frame_length must be positive, got: %d' % self.config.frame_length
393
+ )
394
+ if self.config.frame_step <= 0:
395
+ raise ValueError(
396
+ 'frame_step must be positive, got: %d' % self.config.frame_step
397
+ )
398
+ # TODO(rryan): Fix issues with frame_length < frame_step.
399
+ if self.config.frame_length < self.config.frame_step:
400
+ raise ValueError('frame_length must be at least frame_step.')
401
+
402
+ @property
403
+ def supports_step(self) -> bool:
404
+ return self.config.padding == types.PaddingMode.CAUSAL.value
405
+
406
+ @property
407
+ def output_ratio(self) -> fractions.Fraction:
408
+ return fractions.Fraction(self.config.frame_step)
409
+
410
+ @property
411
+ def receptive_field_per_step(self) -> dict[int, types.ReceptiveField]:
412
+ if self.config.padding == types.PaddingMode.SEMICAUSAL_FULL.value:
413
+ past = 0
414
+ future = (
415
+ math.ceil(float(self.config.frame_length) / self.config.frame_step)
416
+ - 1
417
+ )
418
+ return {0: (past, future)}
419
+ return convolution.transpose_conv_receptive_field_per_step(
420
+ self.config.frame_length,
421
+ self.config.frame_step,
422
+ 1,
423
+ self.config.padding,
424
+ )
425
+
426
+ @nn.nowrap
427
+ def _validate_input_shape(self, input_shape: types.ShapeLike) -> None:
428
+ if not input_shape or input_shape[0] != self.config.frame_length:
429
+ raise ValueError(
430
+ 'OverlapAdd expects an input of shape (frame_length, ...), got:'
431
+ f' {input_shape=}'
432
+ )
433
+
434
+ @nn.nowrap
435
+ def get_output_shape(
436
+ self,
437
+ input_shape: types.ShapeLike,
438
+ *,
439
+ constants: types.Constants | None = None,
440
+ ) -> types.Shape:
441
+ self._validate_input_shape(input_shape)
442
+ return tuple(input_shape[1:])
443
+
444
+ @property
445
+ def _buffer_width(self) -> int:
446
+ return max(0, self.config.frame_length - self.config.frame_step)
447
+
448
+ def get_initial_state(
449
+ self,
450
+ batch_size: int,
451
+ input_spec: types.ChannelSpec,
452
+ *,
453
+ training: bool,
454
+ constants: types.Constants | None = None,
455
+ ) -> types.State:
456
+ self._validate_input_shape(input_spec.shape)
457
+ if buffer_width := self._buffer_width:
458
+ output_spec = self.get_output_spec(input_spec, constants=constants)
459
+ return jnp.zeros(
460
+ (batch_size, buffer_width) + output_spec.shape,
461
+ dtype=output_spec.dtype,
462
+ )
463
+ else:
464
+ return ()
465
+
466
+ @types.check_layer
467
+ def layer(
468
+ self,
469
+ x: types.Sequence,
470
+ *,
471
+ training: bool,
472
+ constants: types.Constants | None = None,
473
+ ) -> types.Sequence:
474
+ self._validate_input_shape(x.channel_spec.shape)
475
+
476
+ if self.config.frame_length > 1:
477
+ x = x.mask_invalid()
478
+
479
+ # Transpose [num_frames, frame_length] to end.
480
+ if x.ndim > 3:
481
+ values = jnp.moveaxis(x.values, (1, 2), (-2, -1))
482
+ else:
483
+ values = x.values
484
+ values = signal.overlap_and_add(values, self.config.frame_step)
485
+ # Move overlapped axis back if we moved it.
486
+ if x.ndim > 3:
487
+ values = jnp.moveaxis(values, -1, 1)
488
+
489
+ mask = convolution.compute_conv_transpose_mask(
490
+ x.mask,
491
+ self.config.frame_length,
492
+ self.config.frame_step,
493
+ dilation_rate=1,
494
+ padding=self.config.padding,
495
+ )
496
+
497
+ trim = max(self.config.frame_length - self.config.frame_step, 0)
498
+ match self.config.padding:
499
+ case types.PaddingMode.CAUSAL.value:
500
+ # Trim the last frame_length - frame_step samples since we don't produce
501
+ # these in step mode (we can only produce frame_step samples at a time
502
+ # in step mode, so we can't produce the final frame_length - frame_step
503
+ # samples).
504
+ if trim:
505
+ values = values[:, :-trim]
506
+
507
+ case types.PaddingMode.SEMICAUSAL_FULL.value:
508
+ # Remove the front padding that should be zero and invalid.
509
+ if trim:
510
+ values = values[:, trim:]
511
+ mask = mask[:, trim:]
512
+
513
+ size = min(values.shape[1], mask.shape[1])
514
+ return types.Sequence(values[:, :size], mask[:, :size])
515
+
516
+ case _:
517
+ pass
518
+
519
+ # Overlap add leaves padding with nonzero values.
520
+ y = types.Sequence(values, mask)
521
+
522
+ return y
523
+
524
+ @types.check_step
525
+ @nn.nowrap
526
+ def step(
527
+ self,
528
+ x: types.Sequence,
529
+ state: types.State,
530
+ *,
531
+ training: bool,
532
+ constants: types.Constants | None = None,
533
+ ) -> tuple[types.Sequence, types.State]:
534
+
535
+ if self.config.frame_length > 1:
536
+ x = x.mask_invalid()
537
+
538
+ # Transpose [num_frames, frame_length] to end.
539
+ if x.ndim > 3:
540
+ values = jnp.moveaxis(x.values, (1, 2), (-2, -1))
541
+ else:
542
+ values = x.values
543
+ values = signal.overlap_and_add(values, self.config.frame_step)
544
+ # Move overlapped axis back if we moved it.
545
+ if x.ndim > 3:
546
+ values = jnp.moveaxis(values, -1, 1)
547
+
548
+ mask = convolution.compute_conv_transpose_mask(
549
+ x.mask,
550
+ self.config.frame_length,
551
+ self.config.frame_step,
552
+ dilation_rate=1,
553
+ padding=self.config.padding,
554
+ )
555
+
556
+ if self._buffer_width:
557
+ time = x.shape[1]
558
+
559
+ # Pad the state to extend it to the length of the layer output.
560
+ # output_time is at least frame_length and buffer_width is at most
561
+ # frame_length - 1, so output_time - buffer_width is positive.
562
+ paddings = [(0, 0)] * state.ndim
563
+ paddings[1] = (0, values.shape[1] - self._buffer_width)
564
+ state = jnp.pad(state, paddings)
565
+
566
+ # Overlap-add outputs from previous timesteps into values.
567
+ values = values + state
568
+
569
+ # Stride samples are "ready" for output after one timestep, so the number
570
+ # of output samples for the block is stride * time.
571
+ output_samples = self.config.frame_step * time
572
+
573
+ # We need to store (effective_kernel_size - stride) samples for future
574
+ # steps, since their value depends on future inputs.
575
+ values, state = jnp.split(values, [output_samples], axis=1)
576
+
577
+ # Overlap add leaves padding with nonzero values.
578
+ return types.Sequence(values, mask), state
579
+
580
+
581
+ def _validate_and_normalize_axis(
582
+ axis: int,
583
+ input_shape: types.Shape,
584
+ ) -> int:
585
+ """Normalizes user-provided axis and checks batch/time are not specified."""
586
+ if axis < 0:
587
+ axis += len(input_shape)
588
+ if axis < 0 or axis > len(input_shape) - 1:
589
+ raise ValueError(
590
+ f'Axis out of range {axis=} for {axis=} with {input_shape=}.'
591
+ )
592
+ if axis in (0, 1):
593
+ raise ValueError(
594
+ 'Computing FFTs over the batch or time dimension is '
595
+ f'not allowed. Got: {axis}'
596
+ )
597
+ return axis
598
+
599
+
600
+ def _pad_or_truncate_for_fft(
601
+ x: types.Sequence,
602
+ normalized_axis: int,
603
+ required_input_length: int,
604
+ padding: str,
605
+ ) -> types.Sequence:
606
+ """Pads or truncates the provided sequence for an FFT/IFFT/RFFT/IRFFT."""
607
+ assert normalized_axis > 1 and normalized_axis < x.ndim
608
+ input_dim = x.shape[normalized_axis]
609
+ if input_dim == required_input_length:
610
+ return x
611
+ if input_dim < required_input_length:
612
+ pad_amount = required_input_length - input_dim
613
+ if padding == 'center': # Center padding.
614
+ pad_left = pad_amount // 2
615
+ pad_right = pad_amount - pad_left
616
+ else:
617
+ assert padding == 'right'
618
+ pad_left = 0
619
+ pad_right = pad_amount
620
+ paddings = [(0, 0)] * x.ndim
621
+ paddings[normalized_axis] = (pad_left, pad_right)
622
+ return x.apply_values_masked(jnp.pad, paddings)
623
+ else:
624
+ assert input_dim > required_input_length
625
+
626
+ def slice_in_dim(v, start, length):
627
+ return jax.lax.slice_in_dim(
628
+ v, start_index=start, limit_index=start + length, axis=normalized_axis
629
+ )
630
+
631
+ if padding == 'center':
632
+ trim_left = (input_dim - required_input_length) // 2
633
+ return x.apply_values(slice_in_dim, trim_left, required_input_length)
634
+ else:
635
+ assert padding == 'right'
636
+ return x.apply_values(slice_in_dim, 0, required_input_length)
637
+
638
+
639
+ def _validate(fft_length: int, padding: str):
640
+ if fft_length is not None and fft_length <= 0:
641
+ raise ValueError('fft_length must be positive, got: %d' % fft_length)
642
+ if padding not in ('center', 'right'):
643
+ raise ValueError('padding must be "center" or "right", got: %s' % padding)
644
+
645
+
646
+ class FFTBase(types.Stateless, metaclass=abc.ABCMeta):
647
+ """A base class for shared FFT logic."""
648
+
649
+ @property
650
+ @abc.abstractmethod
651
+ def _axis(self) -> int:
652
+ pass
653
+
654
+ @property
655
+ @abc.abstractmethod
656
+ def _fft_length(self) -> int | None:
657
+ pass
658
+
659
+ @property
660
+ @abc.abstractmethod
661
+ def _padding(self) -> str:
662
+ pass
663
+
664
+ @abc.abstractmethod
665
+ def _get_fft_fn(self) -> Callable[..., types.Sequence]:
666
+ pass
667
+
668
+ @abc.abstractmethod
669
+ def _get_output_length(self, input_size: int) -> int:
670
+ pass
671
+
672
+ @nn.nowrap
673
+ def _get_fft_length(self, input_size: int) -> int:
674
+ return self._fft_length or input_size
675
+
676
+ @nn.nowrap
677
+ def get_output_shape(
678
+ self,
679
+ input_shape: types.ShapeLike,
680
+ *,
681
+ constants: types.Constants | None = None,
682
+ ) -> tuple[int, ...]:
683
+ input_shape = list(input_shape)
684
+ axis = _validate_and_normalize_axis(
685
+ self._axis, (None, None) + tuple(input_shape)
686
+ )
687
+ axis -= 2
688
+ input_shape[axis] = self._get_output_length(input_shape[axis])
689
+ return tuple(input_shape)
690
+
691
+ @types.check_layer
692
+ def layer(
693
+ self,
694
+ x: types.Sequence,
695
+ *,
696
+ training: bool,
697
+ constants: types.Constants | None = None,
698
+ ) -> types.Sequence:
699
+ del training
700
+ if x.ndim <= 2:
701
+ raise ValueError('FFT requires an input of rank at least 3.')
702
+
703
+ axis = _validate_and_normalize_axis(self._axis, x.shape)
704
+ fft_fn = self._get_fft_fn()
705
+ return fft_fn(x, axis=axis)
706
+
707
+
708
+ class FFT(types.PreservesType, FFTBase):
709
+ """A layer that applies an FFT to the channels dimension."""
710
+
711
+ @dataclasses.dataclass(frozen=True)
712
+ class Config(types.SequenceLayerConfig):
713
+ fft_length: int | None = None
714
+ axis: int = -1
715
+ padding: FFTPaddingString = _DEFAULT_FFT_PADDING
716
+ name: str | None = None
717
+
718
+ def make(self) -> 'FFT':
719
+ return FFT(self, name=self.name)
720
+
721
+ config: Config
722
+
723
+ @property
724
+ def _axis(self) -> int:
725
+ return self.config.axis
726
+
727
+ @property
728
+ def _fft_length(self) -> int | None:
729
+ return self.config.fft_length
730
+
731
+ @property
732
+ def _padding(self) -> str:
733
+ return self.config.padding
734
+
735
+ def _get_output_length(self, input_size: int) -> int:
736
+ return self.config.fft_length or input_size
737
+
738
+ def _get_fft_fn(self) -> Callable[..., types.Sequence]:
739
+ def fft_fn(x, axis):
740
+ required_length = self._get_output_length(x.shape[axis])
741
+ x = _pad_or_truncate_for_fft(
742
+ x, axis, required_length, self.config.padding
743
+ )
744
+ return x.apply_values(jnp.fft.fft, axis=axis)
745
+
746
+ return fft_fn
747
+
748
+
749
+ class IFFT(types.PreservesType, FFTBase):
750
+ """A layer that applies an IFFT to the channels dimension."""
751
+
752
+ @dataclasses.dataclass(frozen=True)
753
+ class Config(types.SequenceLayerConfig):
754
+ fft_length: int | None = None
755
+ frame_length: int | None = None
756
+ axis: int = -1
757
+ padding: FFTPaddingString = _DEFAULT_FFT_PADDING
758
+ name: str | None = None
759
+
760
+ def make(self) -> 'IFFT':
761
+ return IFFT(self, name=self.name)
762
+
763
+ config: Config
764
+
765
+ @property
766
+ def _axis(self) -> int:
767
+ return self.config.axis
768
+
769
+ @property
770
+ def _fft_length(self) -> int | None:
771
+ return self.config.fft_length
772
+
773
+ @property
774
+ def _padding(self) -> str:
775
+ return self.config.padding
776
+
777
+ def _get_output_length(self, input_size: int) -> int:
778
+ return self.config.frame_length or input_size
779
+
780
+ def _get_fft_fn(self) -> Callable[..., types.Sequence]:
781
+ def ifft_fn(a, axis):
782
+ a = a.apply_values(jnp.fft.ifft, axis=axis)
783
+ required_length = self._get_output_length(a.shape[axis])
784
+ return _pad_or_truncate_for_fft(
785
+ a, axis, required_length, self.config.padding
786
+ )
787
+
788
+ return ifft_fn
789
+
790
+
791
+ class RFFT(FFTBase):
792
+ """A layer that applies an RFFT to the channels dimension."""
793
+
794
+ @dataclasses.dataclass(frozen=True)
795
+ class Config(types.SequenceLayerConfig):
796
+ fft_length: int | None = None
797
+ axis: int = -1
798
+ padding: FFTPaddingString = _DEFAULT_FFT_PADDING
799
+ name: str | None = None
800
+
801
+ def make(self) -> 'RFFT':
802
+ return RFFT(self, name=self.name)
803
+
804
+ config: Config
805
+
806
+ @property
807
+ def _axis(self) -> int:
808
+ return self.config.axis
809
+
810
+ @property
811
+ def _fft_length(self) -> int | None:
812
+ return self.config.fft_length
813
+
814
+ @property
815
+ def _padding(self) -> str:
816
+ return self.config.padding
817
+
818
+ def _get_fft_length(self, input_size: int) -> int:
819
+ return self.config.fft_length or input_size
820
+
821
+ def _get_output_length(self, input_size: int) -> int:
822
+ return self._get_fft_length(input_size) // 2 + 1
823
+
824
+ def _get_fft_fn(self) -> Callable[..., types.Sequence]:
825
+
826
+ def rfft(a, axis=-1):
827
+ # Cast input if the dtype is not supported by rfft.
828
+ fft_length = self._get_fft_length(a.shape[axis])
829
+ a = _pad_or_truncate_for_fft(a, axis, fft_length, self.config.padding)
830
+ rfft_inner = lambda v: jnp.fft.rfft(v, n=fft_length, axis=axis)
831
+ if a.dtype == jnp.bfloat16:
832
+ return a.apply_values(lambda v: rfft_inner(v.astype(jnp.float32)))
833
+ return a.apply_values(rfft_inner)
834
+
835
+ return rfft
836
+
837
+ @nn.nowrap
838
+ def get_output_dtype(self, input_dtype: types.DType) -> types.DType:
839
+ match input_dtype:
840
+ case jnp.bfloat16:
841
+ return jnp.complex64
842
+ case jnp.float16:
843
+ return jnp.complex64
844
+ case jnp.float32:
845
+ return jnp.complex64
846
+ case jnp.float64:
847
+ return jnp.complex128
848
+ case _:
849
+ raise ValueError(f'Unsupported input dtype: {input_dtype}')
850
+
851
+
852
+ class IRFFT(FFTBase):
853
+ """A layer that applies an IRFFT to the channels dimension."""
854
+
855
+ @dataclasses.dataclass(frozen=True)
856
+ class Config(types.SequenceLayerConfig):
857
+ fft_length: int | None = None
858
+ frame_length: int | None = None
859
+ axis: int = -1
860
+ padding: FFTPaddingString = _DEFAULT_FFT_PADDING
861
+ name: str | None = None
862
+
863
+ def make(self) -> 'IRFFT':
864
+ return IRFFT(self, name=self.name)
865
+
866
+ config: Config
867
+
868
+ @property
869
+ def _axis(self) -> int:
870
+ return self.config.axis
871
+
872
+ @property
873
+ def _fft_length(self) -> int | None:
874
+ return self.config.fft_length
875
+
876
+ @property
877
+ def _padding(self) -> str:
878
+ return self.config.padding
879
+
880
+ def setup(self) -> None:
881
+ _validate(self.config.fft_length, self.config.padding)
882
+
883
+ @nn.nowrap
884
+ def get_output_dtype(self, input_dtype: types.DType) -> types.DType:
885
+ match input_dtype:
886
+ case jnp.complex64:
887
+ return jnp.float32
888
+ case jnp.complex128:
889
+ return jnp.float64
890
+ case _:
891
+ raise ValueError(f'Unsupported input dtype: {input_dtype}')
892
+
893
+ @nn.nowrap
894
+ def _get_fft_length(self, input_size: int) -> int:
895
+ return self.config.fft_length or (input_size - 1) * 2
896
+
897
+ @nn.nowrap
898
+ def _get_output_length(self, input_size: int) -> int:
899
+ return self.config.frame_length or self._get_fft_length(input_size)
900
+
901
+ @nn.nowrap
902
+ def _get_fft_fn(self) -> Callable[..., types.Sequence]:
903
+ def irfft_fn(a, axis=-1):
904
+ fft_length = self._get_fft_length(a.shape[axis])
905
+ a = a.apply_values(jnp.fft.irfft, axis=axis, n=fft_length)
906
+ required_length = self.config.frame_length or a.shape[axis]
907
+ return _pad_or_truncate_for_fft(
908
+ a, axis, required_length, self.config.padding
909
+ )
910
+
911
+ return irfft_fn
912
+
913
+
914
+ class STFT(types.SequenceLayer):
915
+ """Computes the Short-time Fourier Transform of input signals.
916
+
917
+ When used with 'right' FFT padding, equivalent to tf.signal.stft.
918
+
919
+ For an input batch of multi-channel signals shaped [b, t, ...], this layer
920
+ produces a [b, t // frame_step, fft_length // 2 + 1, ...] batch of
921
+ multi-channel output STFTs, where the STFT for each channel in ... is computed
922
+ independently.
923
+ """
924
+
925
+ @dataclasses.dataclass(frozen=True)
926
+ class Config(types.SequenceLayerConfig):
927
+ """Config for STFT layer."""
928
+
929
+ # The frame length of the STFT.
930
+ frame_length: int
931
+ # The frame step of the STFT.
932
+ frame_step: int
933
+ # The FFT length of the STFT.
934
+ fft_length: int
935
+ # The window to use in the STFT. A callable that takes a window length and
936
+ # returns a [window_length] array of samples. If None, no windowing is used.
937
+ # The default is a periodic hann window.
938
+ window_fn: Callable[..., jax.Array | np.ndarray] | None = signal.hann_window
939
+ # Time padding to apply to the sequence. If 'causal_valid',
940
+ # 'reverse_causal_valid', 'causal', 'reverse_causal', or 'semicausal' then
941
+ # the STFT is streamable.
942
+ time_padding: types.PaddingModeString = (
943
+ types.PaddingMode.REVERSE_CAUSAL_VALID.value
944
+ )
945
+ # One of 'right' or 'center'. Whether to pad inputs to `fft_length` by
946
+ # padding with zeros from the right or equally on both sides.
947
+ fft_padding: FFTPaddingString = _DEFAULT_FFT_PADDING
948
+ # If true, outputs a magnitude STFT (i.e. a spectrogram).
949
+ output_magnitude: bool = False
950
+ # An optional name for the layer.
951
+ name: str | None = None
952
+
953
+ def __post_init__(self):
954
+ object.__setattr__(
955
+ self, 'time_padding', types.validate_padding(self.time_padding)
956
+ )
957
+
958
+ def make(self) -> 'STFT':
959
+ return STFT(self, name=self.name)
960
+
961
+ config: Config
962
+
963
+ def setup(self) -> None:
964
+ self.framer = Frame.Config(
965
+ frame_length=self.config.frame_length,
966
+ frame_step=self.config.frame_step,
967
+ padding=self.config.time_padding,
968
+ ).make()
969
+ self.fft = RFFT.Config(
970
+ self.config.fft_length, axis=2, padding=self.config.fft_padding
971
+ ).make()
972
+
973
+ @property
974
+ def supports_step(self) -> bool:
975
+ return self.framer.supports_step and self.fft.supports_step
976
+
977
+ @property
978
+ def block_size(self) -> int:
979
+ return self.framer.block_size
980
+
981
+ @property
982
+ def output_ratio(self) -> fractions.Fraction:
983
+ return self.framer.output_ratio
984
+
985
+ @property
986
+ def input_latency(self) -> int:
987
+ return self.framer.input_latency
988
+
989
+ @property
990
+ def receptive_field_per_step(self) -> dict[int, types.ReceptiveField]:
991
+ if self.config.window_fn:
992
+ window = self.config.window_fn(self.config.frame_length)
993
+ else:
994
+ window = np.ones(self.config.frame_length)
995
+ receptive_field = self.framer.receptive_field
996
+ assert receptive_field is not None, 'Layer has no receptive field.'
997
+ past, future = receptive_field
998
+ receptive_field_list = np.array(range(past, future + 1)).astype(np.int32)
999
+
1000
+ if self.config.fft_length < self.config.frame_length:
1001
+ if self.config.fft_padding == 'center':
1002
+ trim_left = (self.config.frame_length - self.config.fft_length) // 2
1003
+ trim_right = (
1004
+ self.config.frame_length - self.config.fft_length - trim_left
1005
+ )
1006
+ elif self.config.fft_padding == 'right':
1007
+ trim_left = 0
1008
+ trim_right = (
1009
+ self.config.frame_length - self.config.fft_length - trim_left
1010
+ )
1011
+ else:
1012
+ raise ValueError(f'Unsupported FFT padding: {self.config.fft_padding}')
1013
+ trim_mask = np.array(
1014
+ [0] * trim_left
1015
+ + [1] * (self.config.frame_length - trim_left - trim_right)
1016
+ + [0] * trim_right
1017
+ )
1018
+ window = window * trim_mask
1019
+
1020
+ receptive_field_list = receptive_field_list[window > 0]
1021
+ if receptive_field_list.size > 0:
1022
+ past = np.nanmin(receptive_field_list).astype(np.int32).item()
1023
+ future = np.nanmax(receptive_field_list).astype(np.int32).item()
1024
+ else:
1025
+ # Indicating no receptive field.
1026
+ past = np.inf
1027
+ future = -np.inf
1028
+ return {0: (past, future)}
1029
+
1030
+ def get_initial_state(
1031
+ self,
1032
+ batch_size: int,
1033
+ input_spec: types.ChannelSpec,
1034
+ *,
1035
+ training: bool,
1036
+ constants: types.Constants | None = None,
1037
+ ) -> types.State:
1038
+ return self.framer.get_initial_state(
1039
+ batch_size, input_spec, training=training, constants=constants
1040
+ )
1041
+
1042
+ @nn.nowrap
1043
+ def get_output_shape(
1044
+ self,
1045
+ input_shape: types.ShapeLike,
1046
+ *,
1047
+ constants: types.Constants | None = None,
1048
+ ) -> types.Shape:
1049
+ frame_shape = self.framer.get_output_shape(input_shape, constants=constants)
1050
+ return self.fft.get_output_shape(frame_shape, constants=constants)
1051
+
1052
+ def get_output_dtype(self, input_dtype: types.DType) -> types.DType:
1053
+ fft_output_type = self.fft.get_output_dtype(input_dtype)
1054
+
1055
+ if self.config.output_magnitude:
1056
+ match fft_output_type:
1057
+ case jnp.complex64:
1058
+ return jnp.float32
1059
+ case jnp.complex128:
1060
+ return jnp.float64
1061
+ case _:
1062
+ raise ValueError(
1063
+ f'Unsupported FFT output dtype: {input_dtype=} {fft_output_type=}'
1064
+ )
1065
+ else:
1066
+ output_type = fft_output_type
1067
+ return output_type
1068
+
1069
+ @nn.nowrap
1070
+ def _apply_window(self, x: types.Sequence) -> types.Sequence:
1071
+ if self.config.window_fn:
1072
+ window = self.config.window_fn(self.config.frame_length).reshape(
1073
+ (1, 1, self.config.frame_length) + (1,) * (x.ndim - 3)
1074
+ )
1075
+ window = jnp.asarray(window, x.dtype)
1076
+ return x.apply_values_masked(lambda v: v * window)
1077
+ return x
1078
+
1079
+ @types.check_step
1080
+ def step(
1081
+ self,
1082
+ x: types.Sequence,
1083
+ state: types.State,
1084
+ *,
1085
+ training: bool,
1086
+ constants: types.Constants | None = None,
1087
+ ) -> tuple[types.Sequence, types.State]:
1088
+ framed, state = self.framer.step(
1089
+ x, state, training=training, constants=constants
1090
+ )
1091
+ framed = self._apply_window(framed)
1092
+ dft, _ = self.fft.step(framed, (), training=training, constants=constants)
1093
+ if self.config.output_magnitude:
1094
+ dft = dft.apply_values_masked(jnp.abs)
1095
+ return dft, state
1096
+
1097
+ @types.check_layer
1098
+ def layer(
1099
+ self,
1100
+ x: types.Sequence,
1101
+ *,
1102
+ training: bool,
1103
+ constants: types.Constants | None = None,
1104
+ ) -> types.Sequence:
1105
+ framed = self.framer.layer(x, training=training, constants=constants)
1106
+ framed = self._apply_window(framed)
1107
+ dft = self.fft.layer(framed, training=training, constants=constants)
1108
+ if self.config.output_magnitude:
1109
+ dft = dft.apply_values_masked(jnp.abs)
1110
+ return dft
1111
+
1112
+
1113
+ class InverseSTFT(types.SequenceLayer):
1114
+ """Computes the inverse Short-time Fourier Transform of input signals.
1115
+
1116
+ When used with 'right' FFT padding, equivalent to tf.signal.inverse_stft.
1117
+
1118
+ For an input batch of multi-channel STFTs shaped [b, t, fft_length // 2 + 1,
1119
+ ...], this layer produces a [b, t * frame_step, ...] batch of multi-channel
1120
+ output signals, where the inverse STFT for each channel in ... is computed
1121
+ independently.
1122
+ """
1123
+
1124
+ @dataclasses.dataclass(frozen=True)
1125
+ class Config(types.SequenceLayerConfig):
1126
+ """Config for the InverseSTFT layer."""
1127
+
1128
+ # The frame length of the inverse STFT.
1129
+ frame_length: int
1130
+ # The frame step of the inverse STFT.
1131
+ frame_step: int
1132
+ # The FFT length of the inverse STFT.
1133
+ fft_length: int
1134
+ # The window to use for the inverse STFT. A callable that takes a window
1135
+ # length and returns a [window_length] array of samples. If None, no
1136
+ # windowing is used. The default is a periodic hann window, but it is best
1137
+ # to adjust the desired window function for an inverse STFT with
1138
+ # signal.inverse_stft_window_fn to achieve invertibility.
1139
+ window_fn: Callable[..., jax.Array | np.ndarray] | None = signal.hann_window
1140
+ # Time padding to apply to the sequence. If 'causal' then the inverse STFT
1141
+ # is streamable. Only 'causal' and 'valid' are supported.
1142
+ time_padding: types.PaddingModeString = types.PaddingMode.CAUSAL.value
1143
+ # One of 'right' or 'center'. Whether to pad inputs to `fft_length` by
1144
+ # padding with zeros from the right or equally on both sides.
1145
+ fft_padding: FFTPaddingString = _DEFAULT_FFT_PADDING
1146
+ # An optional name for the layer.
1147
+ name: str | None = None
1148
+
1149
+ def __post_init__(self):
1150
+ object.__setattr__(
1151
+ self, 'time_padding', types.validate_padding(self.time_padding)
1152
+ )
1153
+
1154
+ def make(self) -> 'InverseSTFT':
1155
+ return InverseSTFT(self, name=self.name)
1156
+
1157
+ config: Config
1158
+
1159
+ def setup(self) -> None:
1160
+ self.overlap_add = OverlapAdd.Config(
1161
+ frame_length=self.config.frame_length,
1162
+ frame_step=self.config.frame_step,
1163
+ padding=self.config.time_padding,
1164
+ ).make()
1165
+ self.irfft = IRFFT.Config(
1166
+ self.config.fft_length,
1167
+ self.config.frame_length,
1168
+ axis=2,
1169
+ padding=self.config.fft_padding,
1170
+ ).make()
1171
+
1172
+ @property
1173
+ def supports_step(self) -> bool:
1174
+ return self.overlap_add.supports_step and self.irfft.supports_step
1175
+
1176
+ @property
1177
+ def block_size(self) -> int:
1178
+ assert self.irfft.block_size == 1
1179
+ return self.overlap_add.block_size
1180
+
1181
+ @property
1182
+ def output_ratio(self) -> fractions.Fraction:
1183
+ assert self.irfft.output_ratio == 1
1184
+ return self.overlap_add.output_ratio
1185
+
1186
+ @property
1187
+ def receptive_field_per_step(self) -> dict[int, types.ReceptiveField]:
1188
+ fft_length = self.config.fft_length
1189
+ frame_length = self.config.frame_length
1190
+ frame_step = self.config.frame_step
1191
+ time_padding = self.config.time_padding
1192
+ fft_padding = self.config.fft_padding
1193
+
1194
+ explicit_padding = convolution.transpose_conv_explicit_padding(
1195
+ frame_length,
1196
+ frame_step,
1197
+ 1,
1198
+ time_padding,
1199
+ )
1200
+ # Shift in the transpoed frame in OverlapAdd in the first step, i.e., the
1201
+ # number of frame items that are that are unused in the first step.
1202
+ shift_left = frame_length - explicit_padding[0] - 1
1203
+ if (pad_amount := frame_length - fft_length) > 0:
1204
+ if fft_padding == 'right':
1205
+ pad_left = 0
1206
+ pad_right = pad_amount
1207
+ elif fft_padding == 'center':
1208
+ pad_left = pad_amount // 2
1209
+ pad_right = pad_amount - pad_left
1210
+ else:
1211
+ raise ValueError(f'Unsupported FFT padding: {fft_padding}')
1212
+ else:
1213
+ pad_left = 0
1214
+ pad_right = 0
1215
+
1216
+ if self.config.window_fn:
1217
+ window = self.config.window_fn(frame_length, dtype=jnp.int32)
1218
+ if pad_amount > 0:
1219
+ window = np.array([
1220
+ v if pad_left <= i < pad_left + fft_length else 0
1221
+ for i, v in enumerate(window)
1222
+ ])
1223
+ window_mask = window != 0
1224
+ else:
1225
+ window_mask = jnp.ones(frame_length, dtype=jnp.bool_)
1226
+
1227
+ p = -math.ceil(float(explicit_padding[0] + 1) / frame_step) + 1
1228
+ f = math.ceil(float(shift_left) / frame_step) - 1
1229
+ rf_per_step = {}
1230
+ for i in range(frame_step):
1231
+ if (explicit_padding[0] + 1) % frame_step == 0 or (
1232
+ i < ((explicit_padding[0] + 1)) % frame_step
1233
+ ):
1234
+ p_i = p
1235
+ else:
1236
+ p_i = p + 1
1237
+ f_i = f if i < -shift_left % frame_step else f + 1
1238
+
1239
+ if pad_amount > 0:
1240
+ padding_mask = np.array(
1241
+ [0] * pad_left + [1] * fft_length + [0] * pad_right, dtype=jnp.bool_
1242
+ )
1243
+ else:
1244
+ padding_mask = jnp.ones(frame_length, dtype=jnp.bool_)
1245
+ rf_frame_index = (i + shift_left) - np.arange(p_i, f_i + 1) * frame_step
1246
+ rf_frame_index_mask = (window_mask & padding_mask)[rf_frame_index]
1247
+ receptive_field_list = np.array(range(p_i, f_i + 1)).astype(np.int32)
1248
+ receptive_field_list = receptive_field_list[rf_frame_index_mask]
1249
+ if receptive_field_list.size > 0:
1250
+ p_i = np.nanmin(receptive_field_list).astype(np.int32).item()
1251
+ f_i = np.nanmax(receptive_field_list).astype(np.int32).item()
1252
+ rf_per_step[i] = (p_i, f_i) if p_i <= f_i else None
1253
+ else:
1254
+ rf_per_step[i] = None
1255
+ return rf_per_step
1256
+
1257
+ def get_initial_state(
1258
+ self,
1259
+ batch_size: int,
1260
+ input_spec: types.ChannelSpec,
1261
+ *,
1262
+ training: bool,
1263
+ constants: types.Constants | None = None,
1264
+ ) -> types.State:
1265
+ irfft_spec = self.irfft.get_output_spec(input_spec, constants=constants)
1266
+ # IRFFT output is padded or truncated to frame_length.
1267
+ irfft_shape = list(irfft_spec.shape)
1268
+ irfft_shape[0] = self.config.frame_length
1269
+ irfft_spec = types.ShapeDType(
1270
+ irfft_shape,
1271
+ irfft_spec.dtype,
1272
+ )
1273
+ return self.overlap_add.get_initial_state(
1274
+ batch_size, irfft_spec, training=training, constants=constants
1275
+ )
1276
+
1277
+ @nn.nowrap
1278
+ def get_output_shape(
1279
+ self,
1280
+ input_shape: types.ShapeLike,
1281
+ *,
1282
+ constants: types.Constants | None = None,
1283
+ ) -> types.Shape:
1284
+ irfft_shape = list(
1285
+ self.irfft.get_output_shape(input_shape, constants=constants)
1286
+ )
1287
+ # IRFFT output is padded or truncated to frame_length.
1288
+ irfft_shape[0] = self.config.frame_length
1289
+ return self.overlap_add.get_output_shape(irfft_shape, constants=constants)
1290
+
1291
+ def get_output_dtype(self, input_dtype: types.DType) -> types.DType:
1292
+ return self.irfft.get_output_dtype(input_dtype)
1293
+
1294
+ @nn.nowrap
1295
+ def _apply_window(self, irfft: types.Sequence) -> types.Sequence:
1296
+ # Pad or truncate the resulting fft_length vectors to frame_length.
1297
+ fft_length = irfft.shape[2]
1298
+ if fft_length > self.config.frame_length:
1299
+ # Trim to frame_length.
1300
+ irfft = irfft.apply_values_masked(
1301
+ lambda v: v[:, :, : self.config.frame_length]
1302
+ )
1303
+ elif fft_length < self.config.frame_length:
1304
+ pad_amount = self.config.frame_length - fft_length
1305
+ match self.config.fft_padding:
1306
+ case 'right':
1307
+ pad_left, pad_right = 0, pad_amount
1308
+ case 'center':
1309
+ pad_left, pad_right = pad_amount // 2, pad_amount - pad_amount // 2
1310
+ case _:
1311
+ raise ValueError(
1312
+ f'Unsupported FFT padding: {self.config.fft_padding=}'
1313
+ )
1314
+
1315
+ paddings = [(0, 0)] * irfft.ndim
1316
+ paddings[2] = (pad_left, pad_right)
1317
+ irfft = irfft.apply_values_masked(jnp.pad, paddings)
1318
+
1319
+ if self.config.window_fn:
1320
+ window = self.config.window_fn(
1321
+ self.config.frame_length, dtype=irfft.dtype
1322
+ ).reshape((1, 1, self.config.frame_length) + (1,) * (irfft.ndim - 3))
1323
+ window = jnp.asarray(window, irfft.dtype)
1324
+ irfft = irfft.apply_values_masked(lambda v: v * window)
1325
+ return irfft
1326
+
1327
+ @types.check_step
1328
+ def step(
1329
+ self,
1330
+ x: types.Sequence,
1331
+ state: types.State,
1332
+ *,
1333
+ training: bool,
1334
+ constants: types.Constants | None = None,
1335
+ ) -> tuple[types.Sequence, types.State]:
1336
+ if x.ndim < 3:
1337
+ raise ValueError(
1338
+ f'Expected [b, t, num_frequency_bins, ...] input, but got {x.shape=}'
1339
+ )
1340
+
1341
+ irfft, _ = self.irfft.step(x, (), training=training, constants=constants)
1342
+ irfft = self._apply_window(irfft)
1343
+ ola, state = self.overlap_add.step(
1344
+ irfft, state, training=training, constants=constants
1345
+ )
1346
+ return ola, state
1347
+
1348
+ @types.check_layer
1349
+ def layer(
1350
+ self,
1351
+ x: types.Sequence,
1352
+ *,
1353
+ training: bool,
1354
+ constants: types.Constants | None = None,
1355
+ ) -> types.Sequence:
1356
+ if x.ndim < 3:
1357
+ raise ValueError(
1358
+ f'Expected [b, t, num_frequency_bins, ...] input, but got {x.shape=}'
1359
+ )
1360
+
1361
+ irfft = self.irfft.layer(x, training=training, constants=constants)
1362
+ irfft = self._apply_window(irfft)
1363
+ ola = self.overlap_add.layer(irfft, training=training, constants=constants)
1364
+ return ola
1365
+
1366
+
1367
+ class LinearToMelSpectrogram(types.PreservesType, types.Stateless):
1368
+ """Converts linear-scale spectrogram to a mel-scale spectrogram.
1369
+
1370
+ The spectrogram magnitudes should be uncompressed, *not* log compressed.
1371
+ Summation is performed across bands, which in log magnitdue would be
1372
+ multiplication.
1373
+ """
1374
+
1375
+ @dataclasses.dataclass(frozen=True)
1376
+ class Config(types.SequenceLayerConfig):
1377
+ """Config for LinearToMelSpectrogram layer."""
1378
+
1379
+ # The number of mel bins to compute.
1380
+ num_mel_bins: int
1381
+ # The sample rate of the spectrum.
1382
+ sample_rate: float
1383
+ # Lower bound on the frequencies to be included in the mel spectrum. This
1384
+ # corresponds to the lower edge of the lowest triangular band.
1385
+ lower_edge_hertz: float
1386
+ # The desired top edge of the highest frequency band.
1387
+ upper_edge_hertz: float
1388
+ # An optional name for the layer.
1389
+ name: str | None = None
1390
+
1391
+ def make(self) -> 'LinearToMelSpectrogram':
1392
+ return LinearToMelSpectrogram(self, name=self.name)
1393
+
1394
+ config: Config
1395
+
1396
+ @nn.nowrap
1397
+ def get_output_shape(
1398
+ self,
1399
+ input_shape: types.ShapeLike,
1400
+ *,
1401
+ constants: types.Constants | None = None,
1402
+ ) -> types.ShapeLike:
1403
+ if not input_shape:
1404
+ raise ValueError(
1405
+ f'{self} requires input with at least rank 1, got: {input_shape}'
1406
+ )
1407
+ return tuple(input_shape[:-1]) + (self.config.num_mel_bins,)
1408
+
1409
+ @types.check_layer
1410
+ def layer(
1411
+ self,
1412
+ x: types.Sequence,
1413
+ *,
1414
+ training: bool,
1415
+ constants: types.Constants | None = None,
1416
+ ) -> types.Sequence:
1417
+ num_spectrogram_bins = x.shape[-1]
1418
+
1419
+ linear_to_mel = jnp.asarray(
1420
+ signal.linear_to_mel_weight_matrix(
1421
+ num_mel_bins=self.config.num_mel_bins,
1422
+ num_spectrogram_bins=num_spectrogram_bins,
1423
+ sample_rate=self.config.sample_rate,
1424
+ lower_edge_hertz=self.config.lower_edge_hertz,
1425
+ upper_edge_hertz=self.config.upper_edge_hertz,
1426
+ dtype=np.float64,
1427
+ ),
1428
+ x.dtype,
1429
+ )
1430
+
1431
+ # No masking is required because a weight matrix applied to a masked
1432
+ # timestep is also masked.
1433
+ return x.apply_values_masked(
1434
+ lambda v: jnp.einsum('...a,ab->...b', v, linear_to_mel)
1435
+ )
1436
+
1437
+
1438
+ class Delay(types.PreservesShape, types.PreservesType, types.SequenceLayer):
1439
+ """A layer that delays its input by `length` timesteps.
1440
+
1441
+ In contrast to sl.Lookahead, which drops `length` timesteps from the start of
1442
+ the sequence, sl.Delay inserts `length` invalid timesteps at the start of the
1443
+ sequence (delaying the input sequence by `length`).
1444
+ """
1445
+
1446
+ @dataclasses.dataclass(frozen=True)
1447
+ class Config(types.SequenceLayerConfig):
1448
+ """Config for Delay layer."""
1449
+
1450
+ # The non-negative length of the delay to apply. A length of zero is a
1451
+ # no-op.
1452
+ length: int
1453
+ # If true, delays layer-wise outputs by the specified amount. If false, the
1454
+ # delay is only inserted in the step-wise processing. This is useful if the
1455
+ # Delay is intended to support matching latency of a layer that introduces
1456
+ # step-wise latency but no layer-wise latency (such as
1457
+ # LocalDotProductSelfAttention with max_future_horizon > 0, or a convolution
1458
+ # with reverse_causal padding).
1459
+ delay_layer_output: bool = True
1460
+ # An optional name for the layer.
1461
+ name: str | None = None
1462
+
1463
+ def make(self) -> 'Delay':
1464
+ return Delay(self, name=self.name)
1465
+
1466
+ config: Config
1467
+
1468
+ @property
1469
+ def input_latency(self) -> int:
1470
+ # The delay length is the amount of input latency we introduce.
1471
+ return self.config.length
1472
+
1473
+ @property
1474
+ def output_latency(self) -> int:
1475
+ # The current definitions of input and output latency are very confusing.
1476
+ # Output latency is defined as the number of output timesteps before the
1477
+ # step-wise output of the layer matches its layer-wise output. Since delay
1478
+ # is added in both layer() and step(), the layer-wise and step-wise outputs
1479
+ # match immediately and therefore have 0 output latency.
1480
+ if self.config.delay_layer_output:
1481
+ return 0
1482
+ else:
1483
+ return self.config.length
1484
+
1485
+ @property
1486
+ def receptive_field_per_step(self):
1487
+ if self.config.delay_layer_output:
1488
+ return {0: (-self.config.length, -self.config.length)}
1489
+ else:
1490
+ return {0: (0, 0)}
1491
+
1492
+ def setup(self) -> None:
1493
+ if self.config.length < 0:
1494
+ raise ValueError(f'Expected nonnegative delay length. Got: {self.config}')
1495
+
1496
+ def get_initial_state(
1497
+ self,
1498
+ batch_size: int,
1499
+ input_spec: types.ChannelSpec,
1500
+ *,
1501
+ training: bool,
1502
+ constants: types.Constants | None = None,
1503
+ ) -> types.State:
1504
+ # Special case no delay.
1505
+ if not self.config.length:
1506
+ return ()
1507
+ return types.Sequence(
1508
+ jnp.zeros(
1509
+ (batch_size, self.config.length) + input_spec.shape,
1510
+ dtype=input_spec.dtype,
1511
+ ),
1512
+ jnp.zeros((batch_size, self.config.length), types.MASK_DTYPE),
1513
+ )
1514
+
1515
+ @types.check_step
1516
+ def step(
1517
+ self,
1518
+ x: types.Sequence,
1519
+ state: types.State,
1520
+ *,
1521
+ training: bool,
1522
+ constants: types.Constants | None = None,
1523
+ ) -> tuple[types.Sequence, types.State]:
1524
+ if not self.config.length:
1525
+ return x, state
1526
+
1527
+ state = state.concatenate(x)
1528
+ y_values, state_values = jnp.split(state.values, [x.shape[1]], axis=1)
1529
+ y_mask, state_mask = jnp.split(state.mask, [x.shape[1]], axis=1)
1530
+ y = types.Sequence(y_values, y_mask)
1531
+ state = types.Sequence(state_values, state_mask)
1532
+ return y, state
1533
+
1534
+ @types.check_layer
1535
+ def layer(
1536
+ self,
1537
+ x: types.Sequence,
1538
+ *,
1539
+ training: bool,
1540
+ constants: types.Constants | None = None,
1541
+ ) -> types.Sequence:
1542
+ if self.config.delay_layer_output:
1543
+ return x.pad_time(self.config.length, 0, valid=False)
1544
+ else:
1545
+ return x
1546
+
1547
+
1548
+ class Lookahead(types.PreservesShape, types.PreservesType, types.SequenceLayer):
1549
+ """A layer that drops the first `length` timesteps from its input.
1550
+
1551
+ In contrast to sl.Delay, which inserts `length` invalid timesteps at the start
1552
+ of the sequence (delaying the input sequence by `length`), sl.Lookahead drops
1553
+ `length` timesteps from the start of the sequence.
1554
+ """
1555
+
1556
+ @dataclasses.dataclass(frozen=True)
1557
+ class Config(types.SequenceLayerConfig):
1558
+ """Config for Lookahead layer."""
1559
+
1560
+ # The non-negative length of the lookahead to apply. A length of zero is a
1561
+ # no-op.
1562
+ length: int
1563
+ # An optional name for the layer.
1564
+ name: str | None = None
1565
+
1566
+ def make(self) -> 'Lookahead':
1567
+ return Lookahead(self, name=self.name)
1568
+
1569
+ config: Config
1570
+
1571
+ @property
1572
+ def input_latency(self) -> int:
1573
+ return 0
1574
+
1575
+ @property
1576
+ def output_latency(self) -> int:
1577
+ return self.config.length
1578
+
1579
+ @property
1580
+ def receptive_field_per_step(self) -> dict[int, types.ReceptiveField]:
1581
+ return {0: (self.config.length, self.config.length)}
1582
+
1583
+ def setup(self) -> None:
1584
+ if self.config.length < 0:
1585
+ raise ValueError(
1586
+ f'Expected nonnegative lookahead length. Got: {self.config}'
1587
+ )
1588
+
1589
+ def get_initial_state(
1590
+ self,
1591
+ batch_size: int,
1592
+ input_spec: types.ChannelSpec,
1593
+ *,
1594
+ training: bool,
1595
+ constants: types.Constants | None = None,
1596
+ ) -> types.State:
1597
+ # Special case no lookahead.
1598
+ if not self.config.length:
1599
+ return ()
1600
+ return jnp.full((batch_size,), jnp.array(self.config.length + 1, jnp.int32))
1601
+
1602
+ @types.check_step
1603
+ def step(
1604
+ self,
1605
+ x: types.Sequence,
1606
+ state: types.State,
1607
+ *,
1608
+ training: bool,
1609
+ constants: types.Constants | None = None,
1610
+ ) -> tuple[types.Sequence, types.State]:
1611
+ if not self.config.length:
1612
+ return x, state
1613
+ assert x.shape[1] > 0
1614
+
1615
+ increments = jnp.cumsum(x.mask, axis=1)
1616
+ countdown = jnp.maximum(0, state[:, jnp.newaxis] - increments)
1617
+ mask = jnp.logical_and(x.mask, countdown == 0)
1618
+ y = types.Sequence(x.values, mask)
1619
+ state = countdown[:, -1]
1620
+ return y, state
1621
+
1622
+ @types.check_layer
1623
+ def layer(
1624
+ self,
1625
+ x: types.Sequence,
1626
+ *,
1627
+ training: bool,
1628
+ constants: types.Constants | None = None,
1629
+ ) -> types.Sequence:
1630
+ if not self.config.length:
1631
+ return x
1632
+ return x[:, self.config.length :]
1633
+
1634
+
1635
+ class Window(types.PreservesShape, types.PreservesType, types.Stateless):
1636
+ """Applies a window function as in the STFT/InverseSTFT."""
1637
+
1638
+ @dataclasses.dataclass(frozen=True, slots=True)
1639
+ class Config(types.SequenceLayerConfig):
1640
+ """Config of this layer."""
1641
+
1642
+ # The axis onto which the window is applied.
1643
+ axis: int
1644
+ # The window function to use.
1645
+ window_fn: Callable[..., jax.Array | np.ndarray] | None = signal.hann_window
1646
+ # Optional name for this layer.
1647
+ name: str | None = None
1648
+
1649
+ def make(self) -> 'Window':
1650
+ return Window(self, name=self.name)
1651
+
1652
+ config: Config
1653
+
1654
+ def _get_axis(self, x: types.Sequence):
1655
+ axis = self.config.axis
1656
+ if axis < 0:
1657
+ axis = x.ndim + axis
1658
+
1659
+ if axis in (0, 1):
1660
+ raise ValueError(
1661
+ f'The axis cannot be 0 (batch) or 1 (time) (got {self.config.axis}).'
1662
+ )
1663
+
1664
+ if axis >= x.ndim:
1665
+ raise ValueError(
1666
+ f'Axis {self.config.axis} larger than inputs ndim ({{x.ndim}})'
1667
+ )
1668
+
1669
+ return axis
1670
+
1671
+ @types.check_layer
1672
+ def layer(
1673
+ self,
1674
+ x: types.Sequence,
1675
+ *,
1676
+ training: bool,
1677
+ constants: types.Constants | None = None,
1678
+ ) -> types.Sequence:
1679
+
1680
+ axis = self._get_axis(x)
1681
+
1682
+ window = self.config.window_fn(x.shape[axis], dtype=x.dtype)
1683
+ shape_broadcast = [jnp.newaxis] * x.ndim
1684
+ shape_broadcast[axis] = slice(None, None)
1685
+
1686
+ return x.apply_values(lambda v: v * window[tuple(shape_broadcast)])