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,511 @@
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
+ """Signal utilities, generally ported from tensorflow.signal."""
15
+
16
+ from collections.abc import Sequence
17
+ import functools
18
+ import math
19
+ from typing import Callable
20
+
21
+ import jax
22
+ import jax.numpy as jnp
23
+ import numpy as np
24
+ import numpy.typing as npt
25
+ from scipy import signal as sp_signal
26
+ from sequence_layers.jax import types
27
+ from sequence_layers.jax import utils
28
+
29
+ # Type for the name argument of the get_window function of scipy
30
+ # The functions covered by the alternative types are listed
31
+ # in the in-line comments.
32
+ _WindowNameT = (
33
+ str # Window function without parameters.
34
+ | float # Kaiser window's beta parameter.
35
+ | tuple[
36
+ str, float
37
+ ] # kaiser, kaiser_bessel_derived, gaussian, general_hamming, dpss, chebwin
38
+ | tuple[str, float, float] # general_gaussian
39
+ | tuple[str | Sequence[float]] # general_cosine
40
+ )
41
+
42
+
43
+ def _raised_cosine_window(
44
+ window_length: int,
45
+ periodic: bool,
46
+ dtype: npt.DTypeLike,
47
+ a: float,
48
+ b: float,
49
+ ) -> np.ndarray:
50
+ """Computes a raised cosine window. Ported from tf.signal."""
51
+ if window_length == 1:
52
+ return np.ones([1], dtype=dtype)
53
+
54
+ even = 1 - window_length % 2
55
+ n = np.asarray(window_length + int(periodic) * even - 1, dtype=dtype)
56
+ count = np.arange(window_length, dtype=dtype)
57
+ cos_arg = 2 * np.pi * count / n
58
+ return a - b * np.cos(cos_arg)
59
+
60
+
61
+ def hann_window(
62
+ window_length: int,
63
+ periodic: bool = True,
64
+ dtype: npt.DTypeLike = np.float32,
65
+ ) -> np.ndarray:
66
+ """Computes a hann window. Ported from tf.signal."""
67
+ # Note: numpy.hanning does not have the `periodic` and `dtype` parameters.
68
+ return _raised_cosine_window(window_length, periodic, dtype, 0.5, 0.5)
69
+
70
+
71
+ def hamming_window(
72
+ window_length: int,
73
+ periodic: bool = True,
74
+ dtype: npt.DTypeLike = np.float32,
75
+ ) -> np.ndarray:
76
+ """Computes a Hamming window."""
77
+ # The coefficient is chosen identical to scipy.signal.windows.
78
+ # Note: numpy.hamming does not have the `periodic` and `dtype` parameters.
79
+ a0 = 0.54
80
+ return _raised_cosine_window(window_length, periodic, dtype, a0, 1.0 - a0)
81
+
82
+
83
+ def get_window(
84
+ name: _WindowNameT,
85
+ window_length: int,
86
+ periodic: bool = True,
87
+ dtype: npt.DTypeLike = np.float32,
88
+ ) -> np.ndarray:
89
+ """A simple wrapper around scipy.signal.get_windwow.
90
+
91
+ This function wraps the scipy.signal.get_window function.
92
+ It can provide all the windows listed at the following link.
93
+ https://docs.scipy.org/doc/scipy/reference/signal.windows.html
94
+
95
+ If the window requires no parameters, then `name` can be a string.
96
+
97
+ If the window requires parameters, then `name` must be a tuple
98
+ with the first argument the string name of the window, and the next
99
+ arguments the needed parameters.
100
+
101
+ If `name` is a floating point number, it is interpreted as the beta
102
+ parameter of the `~scipy.signal.windows.kaiser` window.
103
+
104
+ The `periodic` argument is helpful to get windows that satisfy
105
+ the COLA (constant overlap-add) condition necessary to get perfect
106
+ reconstruction from overlap-add procedure with certain frame_step sizes.
107
+ https://ccrma.stanford.edu/~jos/sasp/Overlap_Add_Decomposition.html#22206
108
+ Note that COLA, is different from NOLA (non-zero overlap-add), which
109
+ is the required condition for perfect reconstruction from STFT/iSTFT.
110
+
111
+ Args:
112
+ name: The name of the window.
113
+ window_length: The length of the window.
114
+ periodic: Set to True if the window is to be used with an STFT.
115
+ dtype: Desired data type of the output array.
116
+
117
+ Returns:
118
+ An array containing the window of desired type and length.
119
+ """
120
+ even = window_length % 2 == 0
121
+ return np.asarray(
122
+ sp_signal.get_window(name, Nx=window_length, fftbins=even and periodic),
123
+ dtype=dtype,
124
+ )
125
+
126
+
127
+ def get_window_fn(
128
+ name: _WindowNameT,
129
+ ) -> Callable[..., np.ndarray]:
130
+ """Return an API compatible window function of the requested type.
131
+
132
+ This function wraps the scipy.signal.get_window function.
133
+ It can provide all the windows listed at the following link.
134
+ https://docs.scipy.org/doc/scipy/reference/signal.windows.html
135
+
136
+ Args:
137
+ name: The name of the window.
138
+
139
+ Returns:
140
+ A function taking as argument a length, a periodic flag, and a dtype.
141
+ """
142
+
143
+ return functools.partial(get_window, name)
144
+
145
+
146
+ def inverse_stft_window_fn(frame_step: int, forward_window_fn=hann_window):
147
+ """Generates a window function that can be used in `inverse_stft`.
148
+
149
+ Constructs a window that is equal to the forward window with a further
150
+ pointwise amplitude correction. `inverse_stft_window_fn` is equivalent to
151
+ `forward_window_fn` in the case where it would produce an exact inverse.
152
+
153
+ Args:
154
+ frame_step: The number of samples to step.
155
+ forward_window_fn: window_fn used in the forward STFT transform.
156
+
157
+ Returns:
158
+ A callable that takes a window length and a `dtype` keyword argument and
159
+ returns a `[window_length]` `Tensor` of samples in the provided datatype.
160
+ The returned window is suitable for reconstructing original waveform in
161
+ inverse_stft.
162
+ """
163
+
164
+ def inverse_stft_window_fn_inner(frame_length, dtype):
165
+ """Computes a window that can be used in `inverse_stft`.
166
+
167
+ Args:
168
+ frame_length: The window length in samples.
169
+ dtype: Data type of waveform passed to `stft`.
170
+
171
+ Returns:
172
+ A window suitable for reconstructing the original waveform with an inverse
173
+ STFT.
174
+ """
175
+ # Use equation 7 from Griffin + Lim.
176
+ forward_window = forward_window_fn(frame_length, dtype=dtype)
177
+ denom = jnp.square(forward_window)
178
+ overlaps = -(-frame_length // frame_step) # Ceiling division.
179
+ denom = jnp.pad(denom, [(0, overlaps * frame_step - frame_length)])
180
+ denom = jnp.reshape(denom, [overlaps, frame_step])
181
+ denom = jnp.sum(denom, 0, keepdims=True)
182
+ denom = jnp.tile(denom, [overlaps, 1])
183
+ denom = jnp.reshape(denom, [overlaps * frame_step])
184
+ denom = denom[:frame_length]
185
+ return jnp.where(denom == 0.0, 0, forward_window / denom)
186
+
187
+ return inverse_stft_window_fn_inner
188
+
189
+
190
+ def overlap_and_add(signal: jax.Array, frame_step: int) -> jax.Array:
191
+ """Reconstructs a signal from a framed representation.
192
+
193
+ Adds potentially overlapping frames of a signal with shape
194
+ `[..., frames, frame_length]`, offsetting subsequent frames by `frame_step`.
195
+ The resulting tensor has shape `[..., output_size]` where
196
+
197
+ output_size = (frames - 1) * frame_step + frame_length
198
+
199
+ Args:
200
+ signal: A [..., frames, frame_length] array.
201
+ frame_step: An integer denoting overlap offsets. Must be less than or equal
202
+ to `frame_length`.
203
+
204
+ Returns:
205
+ An array with shape `[..., output_size]` containing the overlap-added
206
+ frames of `signal`'s inner-most two dimensions.
207
+
208
+ Raises:
209
+ ValueError: If `signal`'s rank is less than 2, or `frame_step` is not a
210
+ scalar integer.
211
+ """
212
+ signal_shape = signal.shape
213
+
214
+ # All dimensions that are not part of the overlap-and-add. Can be empty for
215
+ # rank 2 inputs.
216
+ outer_dimensions = signal_shape[:-2]
217
+ outer_rank = len(outer_dimensions)
218
+
219
+ def full_shape(inner_shape):
220
+ return outer_dimensions + inner_shape
221
+
222
+ frame_length = signal_shape[-1]
223
+ frames = signal_shape[-2]
224
+
225
+ # Compute output length.
226
+ output_length = frame_length + frame_step * (frames - 1)
227
+
228
+ # If frame_length is equal to frame_step, there's no overlap so just
229
+ # reshape the tensor.
230
+ if frame_length == frame_step:
231
+ return jnp.reshape(signal, outer_dimensions + (output_length,))
232
+
233
+ # The following code is documented using this example:
234
+ #
235
+ # frame_step = 2
236
+ # signal.shape = (3, 5)
237
+ # a b c d e
238
+ # f g h i j
239
+ # k l m n o
240
+
241
+ # Compute the number of segments, per frame.
242
+ segments = -(-frame_length // frame_step) # Divide and round up.
243
+
244
+ # Pad the frame_length dimension to a multiple of the frame step.
245
+ # Pad the frames dimension by `segments` so that signal.shape = (6, 6)
246
+ # a b c d e 0
247
+ # f g h i j 0
248
+ # k l m n o 0
249
+ # 0 0 0 0 0 0
250
+ # 0 0 0 0 0 0
251
+ # 0 0 0 0 0 0
252
+ paddings = [[0, segments], [0, segments * frame_step - frame_length]]
253
+ outer_paddings = [(0, 0)] * outer_rank
254
+ signal = jnp.pad(signal, outer_paddings + paddings)
255
+
256
+ # Reshape so that signal.shape = (6, 3, 2)
257
+ # ab cd e0
258
+ # fg hi j0
259
+ # kl mn o0
260
+ # 00 00 00
261
+ # 00 00 00
262
+ # 00 00 00
263
+ shape = full_shape((frames + segments, segments, frame_step))
264
+ signal = jnp.reshape(signal, shape)
265
+
266
+ # Transpose dimensions so that signal.shape = (3, 6, 2)
267
+ # ab fg kl 00 00 00
268
+ # cd hi mn 00 00 00
269
+ # e0 j0 o0 00 00 00
270
+
271
+ perm = list(range(outer_rank)) + [
272
+ outer_rank + 1,
273
+ outer_rank + 0,
274
+ outer_rank + 2,
275
+ ]
276
+ signal = jnp.transpose(signal, perm)
277
+
278
+ # Reshape so that signal.shape = (18, 2)
279
+ # ab fg kl 00 00 00 cd hi mn 00 00 00 e0 j0 o0 00 00 00
280
+ shape = full_shape(((frames + segments) * segments, frame_step))
281
+ signal = jnp.reshape(signal, shape)
282
+
283
+ # Truncate so that signal.shape = (15, 2)
284
+ # ab fg kl 00 00 00 cd hi mn 00 00 00 e0 j0 o0
285
+ signal = signal[..., : (frames + segments - 1) * segments, :]
286
+
287
+ # Reshape so that signal.shape = (3, 5, 2)
288
+ # ab fg kl 00 00
289
+ # 00 cd hi mn 00
290
+ # 00 00 e0 j0 o0
291
+ shape = full_shape((segments, (frames + segments - 1), frame_step))
292
+ signal = jnp.reshape(signal, shape)
293
+
294
+ # Now, reduce over the columns, to achieve the desired sum.
295
+ signal = jnp.sum(signal, -3)
296
+
297
+ # Flatten the array.
298
+ shape = full_shape(((frames + segments - 1) * frame_step,))
299
+ signal = jnp.reshape(signal, shape)
300
+
301
+ # Truncate to final length.
302
+ signal = signal[..., :output_length]
303
+
304
+ return signal
305
+
306
+
307
+ def frame(
308
+ x: jax.Array,
309
+ frame_length: int,
310
+ frame_step: int,
311
+ axis: int = -1,
312
+ pad_mode: tuple[int, int] | str = 'reverse_causal_valid',
313
+ pad_value: complex = 0,
314
+ ) -> jax.Array:
315
+ """Expands `x`'s `axis` dimension into frames of `frame_length`.
316
+
317
+ This is a JAX version of `tf.signal.frame` with convolution-like padding
318
+ support. The output shape is exactly equivalent to convolution of kernel size
319
+ `frame_length` and stride `frame_step`, with padding mode `pad_mode`.
320
+
321
+ Args:
322
+ x: A `(..., samples, ...)` array. Rank must be at least 1.
323
+ frame_length: The frame length in samples.
324
+ frame_step: The frame hop size in samples.
325
+ axis: Indicating the axis to frame. Defaults to the last axis. Supports
326
+ negative values for indexing from the end.
327
+ pad_mode: The padding mode to use.
328
+ pad_value: The padding value to use.
329
+
330
+ Returns:
331
+ An array of frames, size `(..., num_frames, frame_length, ...)`.
332
+ """
333
+ if frame_length < 0:
334
+ raise ValueError('frame_length must be non-negative.')
335
+ if frame_step < 0:
336
+ raise ValueError('frame_step must be non-negative.')
337
+ if x.ndim < 1:
338
+ raise ValueError('signal must have rank at least 1.')
339
+
340
+ axis = axis % x.ndim
341
+ outer_dimensions = x.shape[:axis]
342
+ inner_dimensions = x.shape[axis + 1 :]
343
+
344
+ if isinstance(pad_mode, str):
345
+ pad_mode = types.validate_padding(pad_mode)
346
+ num_frames = utils.convolution_padding_output_size(
347
+ x.shape[axis], pad_mode, frame_length, frame_step, dilation_rate=1
348
+ )
349
+
350
+ if not num_frames:
351
+ return jnp.zeros(
352
+ outer_dimensions + (0, frame_length) + inner_dimensions,
353
+ dtype=x.dtype,
354
+ )
355
+
356
+ # Performance optimization: If frame_length and frame_step have common
357
+ # factors, we can reduce the number of gather indices by dividing frames into
358
+ # "subframes". This can speed up framing by up by 10-20x if frame_length is
359
+ # divisible by frame_step.
360
+ subframe_factor = math.gcd(frame_length, frame_step)
361
+
362
+ # If subframing is enabled, pad to a multiple of frame_length. This guarantees
363
+ # it is divisible by subframe_factor.
364
+ pad_left, pad_right = utils.convolution_explicit_padding(
365
+ pad_mode, frame_length, frame_step, dilation_rate=1
366
+ )
367
+ if subframe_factor > 1:
368
+ pad_right += (-x.shape[axis] - pad_left - pad_right) % frame_length
369
+
370
+ paddings = [(0, 0)] * x.ndim
371
+ paddings[axis] = (pad_left, pad_right)
372
+ x = jnp.pad(x, paddings, constant_values=jnp.array(pad_value, dtype=x.dtype))
373
+
374
+ if subframe_factor > 1:
375
+ assert x.shape[axis] % subframe_factor == 0, (x.shape, subframe_factor)
376
+ x = x.reshape(outer_dimensions + (-1, subframe_factor) + inner_dimensions)
377
+
378
+ # After extracting subframe_factor from the frame axis, divide the length
379
+ # and step appropriately.
380
+ frame_length = frame_length // subframe_factor
381
+ frame_step = frame_step // subframe_factor
382
+
383
+ # Build a [num_frames, frame_length] array of indices to take from x along
384
+ # the frame axis, where selector[i] corresponds to the range [frame_step *
385
+ # i, frame_step * i + frame_length).
386
+ start_indices = (np.arange(num_frames) * frame_step)[:, np.newaxis]
387
+ window_indices = np.arange(frame_length)[np.newaxis, :]
388
+ x = jnp.reshape(
389
+ jnp.take(x, indices=start_indices + window_indices, axis=axis),
390
+ outer_dimensions
391
+ + (-1, frame_length * subframe_factor)
392
+ + inner_dimensions,
393
+ )
394
+ return x
395
+
396
+
397
+ # mel spectrum constants.
398
+ _MEL_BREAK_FREQUENCY_HERTZ = 700.0
399
+ _MEL_HIGH_FREQUENCY_Q = 1127.0
400
+
401
+
402
+ def _hertz_to_mel(frequencies_hertz: float | int | np.ndarray) -> np.ndarray:
403
+ """Converts hertz to mel."""
404
+ return _MEL_HIGH_FREQUENCY_Q * np.log(
405
+ 1.0 + (frequencies_hertz / _MEL_BREAK_FREQUENCY_HERTZ)
406
+ )
407
+
408
+
409
+ def linear_to_mel_weight_matrix(
410
+ num_mel_bins: int = 20,
411
+ num_spectrogram_bins: int = 129,
412
+ sample_rate: int | float = 8000,
413
+ lower_edge_hertz: int | float = 125.0,
414
+ upper_edge_hertz: int | float = 3800.0,
415
+ dtype=np.float32,
416
+ ) -> np.ndarray:
417
+ r"""Numpy-port of `tf.signal.linear_to_mel_weight_matrix`.
418
+
419
+ Copied from google3/third_party/py/praxis/layers/asr/frontend.py.
420
+
421
+ Args:
422
+ num_mel_bins: Python int. How many bands in the resulting mel spectrum.
423
+ num_spectrogram_bins: An integer `Tensor`. How many bins there are in the
424
+ source spectrogram data, which is understood to be `fft_size // 2 + 1`,
425
+ i.e., the spectrogram only contains the nonredundant FFT bins.
426
+ sample_rate: An integer or float `Tensor`. Samples per second of the input
427
+ signal used to create the spectrogram. Used to figure out the frequencies
428
+ corresponding to each spectrogram bin, which dictates how they are mapped
429
+ into the mel scale.
430
+ lower_edge_hertz: Python float. Lower bound on the frequencies to be
431
+ included in the mel spectrum. This corresponds to the lower edge of the
432
+ lowest triangular band.
433
+ upper_edge_hertz: Python float. The desired top edge of the highest
434
+ frequency band.
435
+ dtype: The `DType` of the result matrix. Must be a floating point type.
436
+
437
+ Returns:
438
+ An array of shape `[num_spectrogram_bins, num_mel_bins]`.
439
+ Raises:
440
+ ValueError: If `num_mel_bins`/`num_spectrogram_bins`/`sample_rate` are not
441
+ positive, `lower_edge_hertz` is negative, frequency edges are incorrectly
442
+ ordered, `upper_edge_hertz` is larger than the Nyquist frequency.
443
+ [mel]: https://en.wikipedia.org/wiki/Mel_scale
444
+ """
445
+
446
+ # Input validator from tensorflow/python/ops/signal/mel_ops.py#L71
447
+ if num_mel_bins <= 0:
448
+ raise ValueError('num_mel_bins must be positive. Got: %s' % num_mel_bins)
449
+ if lower_edge_hertz < 0.0:
450
+ raise ValueError(
451
+ 'lower_edge_hertz must be non-negative. Got: %s' % lower_edge_hertz
452
+ )
453
+ if lower_edge_hertz >= upper_edge_hertz:
454
+ raise ValueError(
455
+ 'lower_edge_hertz %.1f >= upper_edge_hertz %.1f'
456
+ % (lower_edge_hertz, upper_edge_hertz)
457
+ )
458
+ if sample_rate <= 0.0:
459
+ raise ValueError('sample_rate must be positive. Got: %s' % sample_rate)
460
+ if upper_edge_hertz > sample_rate / 2:
461
+ raise ValueError(
462
+ 'upper_edge_hertz must not be larger than the Nyquist '
463
+ 'frequency (sample_rate / 2). Got %s for sample_rate: %s'
464
+ % (upper_edge_hertz, sample_rate)
465
+ )
466
+
467
+ # For better precision, we internally use float64. It will not slow down
468
+ # feature extraction because this function is called only once for obtaining
469
+ # a constant matrix.
470
+ internal_dtype = np.float64
471
+
472
+ # HTK excludes the spectrogram DC bin.
473
+ bands_to_zero = 1
474
+ nyquist_hertz = sample_rate / 2.0
475
+ linear_frequencies = np.linspace(
476
+ 0.0, nyquist_hertz, num_spectrogram_bins, dtype=internal_dtype
477
+ )[bands_to_zero:]
478
+ spectrogram_bins_mel = _hertz_to_mel(linear_frequencies)[:, np.newaxis]
479
+
480
+ # Compute num_mel_bins triples of (lower_edge, center, upper_edge). The
481
+ # center of each band is the lower and upper edge of the adjacent bands.
482
+ # Accordingly, we divide [lower_edge_hertz, upper_edge_hertz] into
483
+ # num_mel_bins + 2 pieces.
484
+ edges = np.linspace(
485
+ _hertz_to_mel(lower_edge_hertz),
486
+ _hertz_to_mel(upper_edge_hertz),
487
+ num_mel_bins + 2,
488
+ dtype=internal_dtype,
489
+ )
490
+
491
+ # Split the triples up and reshape them into [1, num_mel_bins] tensors.
492
+ lower_edge_mel, center_mel, upper_edge_mel = (
493
+ edges[:-2][np.newaxis, :],
494
+ edges[1:-1][np.newaxis, :],
495
+ edges[2:][np.newaxis, :],
496
+ )
497
+
498
+ # Calculate lower and upper slopes for every spectrogram bin.
499
+ # Line segments are linear in the mel domain, not Hertz.
500
+ lower_slopes = (spectrogram_bins_mel - lower_edge_mel) / (
501
+ center_mel - lower_edge_mel
502
+ )
503
+ upper_slopes = (upper_edge_mel - spectrogram_bins_mel) / (
504
+ upper_edge_mel - center_mel
505
+ )
506
+
507
+ # Intersect the line segments with each other and zero.
508
+ mel_weights_matrix = np.maximum(0.0, np.minimum(lower_slopes, upper_slopes))
509
+
510
+ # Re-add the zeroed lower bins we sliced out above.
511
+ return np.pad(mel_weights_matrix, [[bands_to_zero, 0], [0, 0]]).astype(dtype)