torchaudio 2.9.1__cp310-cp310-macosx_11_0_arm64.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.
- torchaudio/.dylibs/libc++.1.0.dylib +0 -0
- torchaudio/__init__.py +204 -0
- torchaudio/_extension/__init__.py +61 -0
- torchaudio/_extension/utils.py +133 -0
- torchaudio/_internal/__init__.py +10 -0
- torchaudio/_internal/module_utils.py +171 -0
- torchaudio/_torchcodec.py +340 -0
- torchaudio/compliance/__init__.py +5 -0
- torchaudio/compliance/kaldi.py +813 -0
- torchaudio/datasets/__init__.py +47 -0
- torchaudio/datasets/cmuarctic.py +157 -0
- torchaudio/datasets/cmudict.py +186 -0
- torchaudio/datasets/commonvoice.py +86 -0
- torchaudio/datasets/dr_vctk.py +121 -0
- torchaudio/datasets/fluentcommands.py +108 -0
- torchaudio/datasets/gtzan.py +1118 -0
- torchaudio/datasets/iemocap.py +147 -0
- torchaudio/datasets/librilight_limited.py +111 -0
- torchaudio/datasets/librimix.py +133 -0
- torchaudio/datasets/librispeech.py +174 -0
- torchaudio/datasets/librispeech_biasing.py +189 -0
- torchaudio/datasets/libritts.py +168 -0
- torchaudio/datasets/ljspeech.py +107 -0
- torchaudio/datasets/musdb_hq.py +139 -0
- torchaudio/datasets/quesst14.py +136 -0
- torchaudio/datasets/snips.py +157 -0
- torchaudio/datasets/speechcommands.py +183 -0
- torchaudio/datasets/tedlium.py +218 -0
- torchaudio/datasets/utils.py +54 -0
- torchaudio/datasets/vctk.py +143 -0
- torchaudio/datasets/voxceleb1.py +309 -0
- torchaudio/datasets/yesno.py +89 -0
- torchaudio/functional/__init__.py +130 -0
- torchaudio/functional/_alignment.py +128 -0
- torchaudio/functional/filtering.py +1685 -0
- torchaudio/functional/functional.py +2505 -0
- torchaudio/lib/__init__.py +0 -0
- torchaudio/lib/_torchaudio.so +0 -0
- torchaudio/lib/libtorchaudio.so +0 -0
- torchaudio/models/__init__.py +85 -0
- torchaudio/models/_hdemucs.py +1008 -0
- torchaudio/models/conformer.py +293 -0
- torchaudio/models/conv_tasnet.py +330 -0
- torchaudio/models/decoder/__init__.py +64 -0
- torchaudio/models/decoder/_ctc_decoder.py +568 -0
- torchaudio/models/decoder/_cuda_ctc_decoder.py +187 -0
- torchaudio/models/deepspeech.py +84 -0
- torchaudio/models/emformer.py +884 -0
- torchaudio/models/rnnt.py +816 -0
- torchaudio/models/rnnt_decoder.py +339 -0
- torchaudio/models/squim/__init__.py +11 -0
- torchaudio/models/squim/objective.py +326 -0
- torchaudio/models/squim/subjective.py +150 -0
- torchaudio/models/tacotron2.py +1046 -0
- torchaudio/models/wav2letter.py +72 -0
- torchaudio/models/wav2vec2/__init__.py +45 -0
- torchaudio/models/wav2vec2/components.py +1167 -0
- torchaudio/models/wav2vec2/model.py +1579 -0
- torchaudio/models/wav2vec2/utils/__init__.py +7 -0
- torchaudio/models/wav2vec2/utils/import_fairseq.py +213 -0
- torchaudio/models/wav2vec2/utils/import_huggingface.py +134 -0
- torchaudio/models/wav2vec2/wavlm_attention.py +214 -0
- torchaudio/models/wavernn.py +409 -0
- torchaudio/pipelines/__init__.py +102 -0
- torchaudio/pipelines/_source_separation_pipeline.py +109 -0
- torchaudio/pipelines/_squim_pipeline.py +156 -0
- torchaudio/pipelines/_tts/__init__.py +16 -0
- torchaudio/pipelines/_tts/impl.py +385 -0
- torchaudio/pipelines/_tts/interface.py +255 -0
- torchaudio/pipelines/_tts/utils.py +230 -0
- torchaudio/pipelines/_wav2vec2/__init__.py +0 -0
- torchaudio/pipelines/_wav2vec2/aligner.py +87 -0
- torchaudio/pipelines/_wav2vec2/impl.py +1699 -0
- torchaudio/pipelines/_wav2vec2/utils.py +346 -0
- torchaudio/pipelines/rnnt_pipeline.py +380 -0
- torchaudio/transforms/__init__.py +78 -0
- torchaudio/transforms/_multi_channel.py +467 -0
- torchaudio/transforms/_transforms.py +2138 -0
- torchaudio/utils/__init__.py +4 -0
- torchaudio/utils/download.py +89 -0
- torchaudio/version.py +2 -0
- torchaudio-2.9.1.dist-info/METADATA +133 -0
- torchaudio-2.9.1.dist-info/RECORD +86 -0
- torchaudio-2.9.1.dist-info/WHEEL +5 -0
- torchaudio-2.9.1.dist-info/licenses/LICENSE +25 -0
- torchaudio-2.9.1.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,2505 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
|
|
3
|
+
import math
|
|
4
|
+
import warnings
|
|
5
|
+
from collections.abc import Sequence
|
|
6
|
+
from typing import List, Optional, Tuple, Union
|
|
7
|
+
|
|
8
|
+
import torch
|
|
9
|
+
import torchaudio
|
|
10
|
+
from torch import Tensor
|
|
11
|
+
from torchaudio._internal.module_utils import dropping_support
|
|
12
|
+
|
|
13
|
+
from .filtering import highpass_biquad, treble_biquad
|
|
14
|
+
|
|
15
|
+
__all__ = [
|
|
16
|
+
"spectrogram",
|
|
17
|
+
"inverse_spectrogram",
|
|
18
|
+
"griffinlim",
|
|
19
|
+
"amplitude_to_DB",
|
|
20
|
+
"DB_to_amplitude",
|
|
21
|
+
"compute_deltas",
|
|
22
|
+
"melscale_fbanks",
|
|
23
|
+
"linear_fbanks",
|
|
24
|
+
"create_dct",
|
|
25
|
+
"compute_deltas",
|
|
26
|
+
"detect_pitch_frequency",
|
|
27
|
+
"DB_to_amplitude",
|
|
28
|
+
"mu_law_encoding",
|
|
29
|
+
"mu_law_decoding",
|
|
30
|
+
"phase_vocoder",
|
|
31
|
+
"mask_along_axis",
|
|
32
|
+
"mask_along_axis_iid",
|
|
33
|
+
"sliding_window_cmn",
|
|
34
|
+
"spectral_centroid",
|
|
35
|
+
"resample",
|
|
36
|
+
"edit_distance",
|
|
37
|
+
"loudness",
|
|
38
|
+
"pitch_shift",
|
|
39
|
+
"rnnt_loss",
|
|
40
|
+
"psd",
|
|
41
|
+
"mvdr_weights_souden",
|
|
42
|
+
"mvdr_weights_rtf",
|
|
43
|
+
"rtf_evd",
|
|
44
|
+
"rtf_power",
|
|
45
|
+
"apply_beamforming",
|
|
46
|
+
"fftconvolve",
|
|
47
|
+
"convolve",
|
|
48
|
+
"add_noise",
|
|
49
|
+
"speed",
|
|
50
|
+
"preemphasis",
|
|
51
|
+
"deemphasis",
|
|
52
|
+
]
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def spectrogram(
|
|
56
|
+
waveform: Tensor,
|
|
57
|
+
pad: int,
|
|
58
|
+
window: Tensor,
|
|
59
|
+
n_fft: int,
|
|
60
|
+
hop_length: int,
|
|
61
|
+
win_length: int,
|
|
62
|
+
power: Optional[float],
|
|
63
|
+
normalized: Union[bool, str],
|
|
64
|
+
center: bool = True,
|
|
65
|
+
pad_mode: str = "reflect",
|
|
66
|
+
onesided: bool = True,
|
|
67
|
+
return_complex: Optional[bool] = None,
|
|
68
|
+
) -> Tensor:
|
|
69
|
+
r"""Create a spectrogram or a batch of spectrograms from a raw audio signal.
|
|
70
|
+
The spectrogram can be either magnitude-only or complex.
|
|
71
|
+
|
|
72
|
+
.. devices:: CPU CUDA
|
|
73
|
+
|
|
74
|
+
.. properties:: Autograd TorchScript
|
|
75
|
+
|
|
76
|
+
Args:
|
|
77
|
+
waveform (Tensor): Tensor of audio of dimension `(..., time)`
|
|
78
|
+
pad (int): Two sided padding of signal
|
|
79
|
+
window (Tensor): Window tensor that is applied/multiplied to each frame/window
|
|
80
|
+
n_fft (int): Size of FFT
|
|
81
|
+
hop_length (int): Length of hop between STFT windows
|
|
82
|
+
win_length (int): Window size
|
|
83
|
+
power (float or None): Exponent for the magnitude spectrogram,
|
|
84
|
+
(must be > 0) e.g., 1 for magnitude, 2 for power, etc.
|
|
85
|
+
If None, then the complex spectrum is returned instead.
|
|
86
|
+
normalized (bool or str): Whether to normalize by magnitude after stft. If input is str, choices are
|
|
87
|
+
``"window"`` and ``"frame_length"``, if specific normalization type is desirable. ``True`` maps to
|
|
88
|
+
``"window"``. When normalized on ``"window"``, waveform is normalized upon the window's L2 energy. If
|
|
89
|
+
normalized on ``"frame_length"``, waveform is normalized by dividing by
|
|
90
|
+
:math:`(\text{frame\_length})^{0.5}`.
|
|
91
|
+
center (bool, optional): whether to pad :attr:`waveform` on both sides so
|
|
92
|
+
that the :math:`t`-th frame is centered at time :math:`t \times \text{hop\_length}`.
|
|
93
|
+
Default: ``True``
|
|
94
|
+
pad_mode (string, optional): controls the padding method used when
|
|
95
|
+
:attr:`center` is ``True``. Default: ``"reflect"``
|
|
96
|
+
onesided (bool, optional): controls whether to return half of results to
|
|
97
|
+
avoid redundancy. Default: ``True``
|
|
98
|
+
return_complex (bool, optional):
|
|
99
|
+
Deprecated and not used.
|
|
100
|
+
|
|
101
|
+
Returns:
|
|
102
|
+
Tensor: Dimension `(..., freq, time)`, freq is
|
|
103
|
+
``n_fft // 2 + 1`` and ``n_fft`` is the number of
|
|
104
|
+
Fourier bins, and time is the number of window hops (n_frame).
|
|
105
|
+
"""
|
|
106
|
+
if return_complex is not None:
|
|
107
|
+
warnings.warn(
|
|
108
|
+
"`return_complex` argument is now deprecated and is not effective."
|
|
109
|
+
"`torchaudio.functional.spectrogram(power=None)` always returns a tensor with "
|
|
110
|
+
"complex dtype. Please remove the argument in the function call."
|
|
111
|
+
)
|
|
112
|
+
|
|
113
|
+
if pad > 0:
|
|
114
|
+
# TODO add "with torch.no_grad():" back when JIT supports it
|
|
115
|
+
waveform = torch.nn.functional.pad(waveform, (pad, pad), "constant")
|
|
116
|
+
|
|
117
|
+
frame_length_norm, window_norm = _get_spec_norms(normalized)
|
|
118
|
+
|
|
119
|
+
# pack batch
|
|
120
|
+
shape = waveform.size()
|
|
121
|
+
waveform = waveform.reshape(-1, shape[-1])
|
|
122
|
+
|
|
123
|
+
# default values are consistent with librosa.core.spectrum._spectrogram
|
|
124
|
+
spec_f = torch.stft(
|
|
125
|
+
input=waveform,
|
|
126
|
+
n_fft=n_fft,
|
|
127
|
+
hop_length=hop_length,
|
|
128
|
+
win_length=win_length,
|
|
129
|
+
window=window,
|
|
130
|
+
center=center,
|
|
131
|
+
pad_mode=pad_mode,
|
|
132
|
+
normalized=frame_length_norm,
|
|
133
|
+
onesided=onesided,
|
|
134
|
+
return_complex=True,
|
|
135
|
+
)
|
|
136
|
+
|
|
137
|
+
# unpack batch
|
|
138
|
+
spec_f = spec_f.reshape(shape[:-1] + spec_f.shape[-2:])
|
|
139
|
+
|
|
140
|
+
if window_norm:
|
|
141
|
+
spec_f /= window.pow(2.0).sum().sqrt()
|
|
142
|
+
if power is not None:
|
|
143
|
+
if power == 1.0:
|
|
144
|
+
return spec_f.abs()
|
|
145
|
+
return spec_f.abs().pow(power)
|
|
146
|
+
return spec_f
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def inverse_spectrogram(
|
|
150
|
+
spectrogram: Tensor,
|
|
151
|
+
length: Optional[int],
|
|
152
|
+
pad: int,
|
|
153
|
+
window: Tensor,
|
|
154
|
+
n_fft: int,
|
|
155
|
+
hop_length: int,
|
|
156
|
+
win_length: int,
|
|
157
|
+
normalized: Union[bool, str],
|
|
158
|
+
center: bool = True,
|
|
159
|
+
pad_mode: str = "reflect",
|
|
160
|
+
onesided: bool = True,
|
|
161
|
+
) -> Tensor:
|
|
162
|
+
r"""Create an inverse spectrogram or a batch of inverse spectrograms from the provided
|
|
163
|
+
complex-valued spectrogram.
|
|
164
|
+
|
|
165
|
+
.. devices:: CPU CUDA
|
|
166
|
+
|
|
167
|
+
.. properties:: Autograd TorchScript
|
|
168
|
+
|
|
169
|
+
Args:
|
|
170
|
+
spectrogram (Tensor): Complex tensor of audio of dimension (..., freq, time).
|
|
171
|
+
length (int or None): The output length of the waveform.
|
|
172
|
+
pad (int): Two sided padding of signal. It is only effective when ``length`` is provided.
|
|
173
|
+
window (Tensor): Window tensor that is applied/multiplied to each frame/window
|
|
174
|
+
n_fft (int): Size of FFT
|
|
175
|
+
hop_length (int): Length of hop between STFT windows
|
|
176
|
+
win_length (int): Window size
|
|
177
|
+
normalized (bool or str): Whether the stft output was normalized by magnitude. If input is str, choices are
|
|
178
|
+
``"window"`` and ``"frame_length"``, dependent on normalization mode. ``True`` maps to
|
|
179
|
+
``"window"``.
|
|
180
|
+
center (bool, optional): whether the waveform was padded on both sides so
|
|
181
|
+
that the :math:`t`-th frame is centered at time :math:`t \times \text{hop\_length}`.
|
|
182
|
+
Default: ``True``
|
|
183
|
+
pad_mode (string, optional): controls the padding method used when
|
|
184
|
+
:attr:`center` is ``True``. This parameter is provided for compatibility with the
|
|
185
|
+
spectrogram function and is not used. Default: ``"reflect"``
|
|
186
|
+
onesided (bool, optional): controls whether spectrogram was done in onesided mode.
|
|
187
|
+
Default: ``True``
|
|
188
|
+
|
|
189
|
+
Returns:
|
|
190
|
+
Tensor: Dimension `(..., time)`. Least squares estimation of the original signal.
|
|
191
|
+
"""
|
|
192
|
+
|
|
193
|
+
frame_length_norm, window_norm = _get_spec_norms(normalized)
|
|
194
|
+
|
|
195
|
+
if not spectrogram.is_complex():
|
|
196
|
+
raise ValueError("Expected `spectrogram` to be complex dtype.")
|
|
197
|
+
|
|
198
|
+
if window_norm:
|
|
199
|
+
spectrogram = spectrogram * window.pow(2.0).sum().sqrt()
|
|
200
|
+
|
|
201
|
+
# pack batch
|
|
202
|
+
shape = spectrogram.size()
|
|
203
|
+
spectrogram = spectrogram.reshape(-1, shape[-2], shape[-1])
|
|
204
|
+
|
|
205
|
+
# default values are consistent with librosa.core.spectrum._spectrogram
|
|
206
|
+
waveform = torch.istft(
|
|
207
|
+
input=spectrogram,
|
|
208
|
+
n_fft=n_fft,
|
|
209
|
+
hop_length=hop_length,
|
|
210
|
+
win_length=win_length,
|
|
211
|
+
window=window,
|
|
212
|
+
center=center,
|
|
213
|
+
normalized=frame_length_norm,
|
|
214
|
+
onesided=onesided,
|
|
215
|
+
length=length + 2 * pad if length is not None else None,
|
|
216
|
+
return_complex=False,
|
|
217
|
+
)
|
|
218
|
+
|
|
219
|
+
if length is not None and pad > 0:
|
|
220
|
+
# remove padding from front and back
|
|
221
|
+
waveform = waveform[:, pad:-pad]
|
|
222
|
+
|
|
223
|
+
# unpack batch
|
|
224
|
+
waveform = waveform.reshape(shape[:-2] + waveform.shape[-1:])
|
|
225
|
+
|
|
226
|
+
return waveform
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def _get_spec_norms(normalized: Union[str, bool]):
|
|
230
|
+
frame_length_norm, window_norm = False, False
|
|
231
|
+
if torch.jit.isinstance(normalized, str):
|
|
232
|
+
if normalized not in ["frame_length", "window"]:
|
|
233
|
+
raise ValueError("Invalid normalized parameter: {}".format(normalized))
|
|
234
|
+
if normalized == "frame_length":
|
|
235
|
+
frame_length_norm = True
|
|
236
|
+
elif normalized == "window":
|
|
237
|
+
window_norm = True
|
|
238
|
+
elif torch.jit.isinstance(normalized, bool):
|
|
239
|
+
if normalized:
|
|
240
|
+
window_norm = True
|
|
241
|
+
else:
|
|
242
|
+
raise TypeError("Input type not supported")
|
|
243
|
+
return frame_length_norm, window_norm
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def _get_complex_dtype(real_dtype: torch.dtype):
|
|
247
|
+
if real_dtype == torch.double:
|
|
248
|
+
return torch.cdouble
|
|
249
|
+
if real_dtype == torch.float:
|
|
250
|
+
return torch.cfloat
|
|
251
|
+
if real_dtype == torch.half:
|
|
252
|
+
return torch.complex32
|
|
253
|
+
raise ValueError(f"Unexpected dtype {real_dtype}")
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def griffinlim(
|
|
257
|
+
specgram: Tensor,
|
|
258
|
+
window: Tensor,
|
|
259
|
+
n_fft: int,
|
|
260
|
+
hop_length: int,
|
|
261
|
+
win_length: int,
|
|
262
|
+
power: float,
|
|
263
|
+
n_iter: int,
|
|
264
|
+
momentum: float,
|
|
265
|
+
length: Optional[int],
|
|
266
|
+
rand_init: bool,
|
|
267
|
+
) -> Tensor:
|
|
268
|
+
r"""Compute waveform from a linear scale magnitude spectrogram using the Griffin-Lim transformation.
|
|
269
|
+
|
|
270
|
+
.. devices:: CPU CUDA
|
|
271
|
+
|
|
272
|
+
.. properties:: Autograd TorchScript
|
|
273
|
+
|
|
274
|
+
Implementation ported from
|
|
275
|
+
*librosa* :cite:`brian_mcfee-proc-scipy-2015`, *A fast Griffin-Lim algorithm* :cite:`6701851`
|
|
276
|
+
and *Signal estimation from modified short-time Fourier transform* :cite:`1172092`.
|
|
277
|
+
|
|
278
|
+
Args:
|
|
279
|
+
specgram (Tensor): A magnitude-only STFT spectrogram of dimension `(..., freq, frames)`
|
|
280
|
+
where freq is ``n_fft // 2 + 1``.
|
|
281
|
+
window (Tensor): Window tensor that is applied/multiplied to each frame/window
|
|
282
|
+
n_fft (int): Size of FFT, creates ``n_fft // 2 + 1`` bins
|
|
283
|
+
hop_length (int): Length of hop between STFT windows. (
|
|
284
|
+
Default: ``win_length // 2``)
|
|
285
|
+
win_length (int): Window size. (Default: ``n_fft``)
|
|
286
|
+
power (float): Exponent for the magnitude spectrogram,
|
|
287
|
+
(must be > 0) e.g., 1 for magnitude, 2 for power, etc.
|
|
288
|
+
n_iter (int): Number of iteration for phase recovery process.
|
|
289
|
+
momentum (float): The momentum parameter for fast Griffin-Lim.
|
|
290
|
+
Setting this to 0 recovers the original Griffin-Lim method.
|
|
291
|
+
Values near 1 can lead to faster convergence, but above 1 may not converge.
|
|
292
|
+
length (int or None): Array length of the expected output.
|
|
293
|
+
rand_init (bool): Initializes phase randomly if True, to zero otherwise.
|
|
294
|
+
|
|
295
|
+
Returns:
|
|
296
|
+
Tensor: waveform of `(..., time)`, where time equals the ``length`` parameter if given.
|
|
297
|
+
"""
|
|
298
|
+
if not 0 <= momentum < 1:
|
|
299
|
+
raise ValueError("momentum must be in range [0, 1). Found: {}".format(momentum))
|
|
300
|
+
|
|
301
|
+
momentum = momentum / (1 + momentum)
|
|
302
|
+
|
|
303
|
+
# pack batch
|
|
304
|
+
shape = specgram.size()
|
|
305
|
+
specgram = specgram.reshape([-1] + list(shape[-2:]))
|
|
306
|
+
|
|
307
|
+
specgram = specgram.pow(1 / power)
|
|
308
|
+
|
|
309
|
+
# initialize the phase
|
|
310
|
+
if rand_init:
|
|
311
|
+
angles = torch.rand(specgram.size(), dtype=_get_complex_dtype(specgram.dtype), device=specgram.device)
|
|
312
|
+
else:
|
|
313
|
+
angles = torch.full(specgram.size(), 1, dtype=_get_complex_dtype(specgram.dtype), device=specgram.device)
|
|
314
|
+
|
|
315
|
+
# And initialize the previous iterate to 0
|
|
316
|
+
tprev = torch.tensor(0.0, dtype=specgram.dtype, device=specgram.device)
|
|
317
|
+
for _ in range(n_iter):
|
|
318
|
+
# Invert with our current estimate of the phases
|
|
319
|
+
inverse = torch.istft(
|
|
320
|
+
specgram * angles, n_fft=n_fft, hop_length=hop_length, win_length=win_length, window=window, length=length
|
|
321
|
+
)
|
|
322
|
+
|
|
323
|
+
# Rebuild the spectrogram
|
|
324
|
+
rebuilt = torch.stft(
|
|
325
|
+
input=inverse,
|
|
326
|
+
n_fft=n_fft,
|
|
327
|
+
hop_length=hop_length,
|
|
328
|
+
win_length=win_length,
|
|
329
|
+
window=window,
|
|
330
|
+
center=True,
|
|
331
|
+
pad_mode="reflect",
|
|
332
|
+
normalized=False,
|
|
333
|
+
onesided=True,
|
|
334
|
+
return_complex=True,
|
|
335
|
+
)
|
|
336
|
+
|
|
337
|
+
# Update our phase estimates
|
|
338
|
+
angles = rebuilt
|
|
339
|
+
if momentum:
|
|
340
|
+
angles = angles - tprev.mul_(momentum)
|
|
341
|
+
angles = angles.div(angles.abs().add(1e-16))
|
|
342
|
+
|
|
343
|
+
# Store the previous iterate
|
|
344
|
+
tprev = rebuilt
|
|
345
|
+
|
|
346
|
+
# Return the final phase estimates
|
|
347
|
+
waveform = torch.istft(
|
|
348
|
+
specgram * angles, n_fft=n_fft, hop_length=hop_length, win_length=win_length, window=window, length=length
|
|
349
|
+
)
|
|
350
|
+
|
|
351
|
+
# unpack batch
|
|
352
|
+
waveform = waveform.reshape(shape[:-2] + waveform.shape[-1:])
|
|
353
|
+
|
|
354
|
+
return waveform
|
|
355
|
+
|
|
356
|
+
|
|
357
|
+
def amplitude_to_DB(
|
|
358
|
+
x: Tensor, multiplier: float, amin: float, db_multiplier: float, top_db: Optional[float] = None
|
|
359
|
+
) -> Tensor:
|
|
360
|
+
r"""Turn a spectrogram from the power/amplitude scale to the decibel scale.
|
|
361
|
+
|
|
362
|
+
.. devices:: CPU CUDA
|
|
363
|
+
|
|
364
|
+
.. properties:: Autograd TorchScript
|
|
365
|
+
|
|
366
|
+
The output of each tensor in a batch depends on the maximum value of that tensor,
|
|
367
|
+
and so may return different values for an audio clip split into snippets vs. a full clip.
|
|
368
|
+
|
|
369
|
+
Args:
|
|
370
|
+
|
|
371
|
+
x (Tensor): Input spectrogram(s) before being converted to decibel scale.
|
|
372
|
+
The expected shapes are ``(freq, time)``, ``(channel, freq, time)`` or
|
|
373
|
+
``(..., batch, channel, freq, time)``.
|
|
374
|
+
|
|
375
|
+
.. note::
|
|
376
|
+
|
|
377
|
+
When ``top_db`` is specified, cut-off values are computed for each audio
|
|
378
|
+
in the batch. Therefore if the input shape is 4D (or larger), different
|
|
379
|
+
cut-off values are used for audio data in the batch.
|
|
380
|
+
If the input shape is 2D or 3D, a single cutoff value is used.
|
|
381
|
+
|
|
382
|
+
multiplier (float): Use 10. for power and 20. for amplitude
|
|
383
|
+
amin (float): Number to clamp ``x``
|
|
384
|
+
db_multiplier (float): Log10(max(reference value and amin))
|
|
385
|
+
top_db (float or None, optional): Minimum negative cut-off in decibels. A reasonable number
|
|
386
|
+
is 80. (Default: ``None``)
|
|
387
|
+
|
|
388
|
+
Returns:
|
|
389
|
+
Tensor: Output tensor in decibel scale
|
|
390
|
+
"""
|
|
391
|
+
x_db = multiplier * torch.log10(torch.clamp(x, min=amin))
|
|
392
|
+
x_db -= multiplier * db_multiplier
|
|
393
|
+
|
|
394
|
+
if top_db is not None:
|
|
395
|
+
# Expand batch
|
|
396
|
+
shape = x_db.size()
|
|
397
|
+
packed_channels = shape[-3] if x_db.dim() > 2 else 1
|
|
398
|
+
x_db = x_db.reshape(-1, packed_channels, shape[-2], shape[-1])
|
|
399
|
+
|
|
400
|
+
x_db = torch.max(x_db, (x_db.amax(dim=(-3, -2, -1)) - top_db).view(-1, 1, 1, 1))
|
|
401
|
+
|
|
402
|
+
# Repack batch
|
|
403
|
+
x_db = x_db.reshape(shape)
|
|
404
|
+
|
|
405
|
+
return x_db
|
|
406
|
+
|
|
407
|
+
|
|
408
|
+
def DB_to_amplitude(x: Tensor, ref: float, power: float) -> Tensor:
|
|
409
|
+
r"""Turn a tensor from the decibel scale to the power/amplitude scale.
|
|
410
|
+
|
|
411
|
+
.. devices:: CPU CUDA
|
|
412
|
+
|
|
413
|
+
.. properties:: TorchScript
|
|
414
|
+
|
|
415
|
+
Args:
|
|
416
|
+
x (Tensor): Input tensor before being converted to power/amplitude scale.
|
|
417
|
+
ref (float): Reference which the output will be scaled by.
|
|
418
|
+
power (float): If power equals 1, will compute DB to power. If 0.5, will compute DB to amplitude.
|
|
419
|
+
|
|
420
|
+
Returns:
|
|
421
|
+
Tensor: Output tensor in power/amplitude scale.
|
|
422
|
+
"""
|
|
423
|
+
return ref * torch.pow(torch.pow(10.0, 0.1 * x), power)
|
|
424
|
+
|
|
425
|
+
|
|
426
|
+
def _hz_to_mel(freq: float, mel_scale: str = "htk") -> float:
|
|
427
|
+
r"""Convert Hz to Mels.
|
|
428
|
+
|
|
429
|
+
Args:
|
|
430
|
+
freqs (float): Frequencies in Hz
|
|
431
|
+
mel_scale (str, optional): Scale to use: ``htk`` or ``slaney``. (Default: ``htk``)
|
|
432
|
+
|
|
433
|
+
Returns:
|
|
434
|
+
mels (float): Frequency in Mels
|
|
435
|
+
"""
|
|
436
|
+
|
|
437
|
+
if mel_scale not in ["slaney", "htk"]:
|
|
438
|
+
raise ValueError('mel_scale should be one of "htk" or "slaney".')
|
|
439
|
+
|
|
440
|
+
if mel_scale == "htk":
|
|
441
|
+
return 2595.0 * math.log10(1.0 + (freq / 700.0))
|
|
442
|
+
|
|
443
|
+
# Fill in the linear part
|
|
444
|
+
f_min = 0.0
|
|
445
|
+
f_sp = 200.0 / 3
|
|
446
|
+
|
|
447
|
+
mels = (freq - f_min) / f_sp
|
|
448
|
+
|
|
449
|
+
# Fill in the log-scale part
|
|
450
|
+
min_log_hz = 1000.0
|
|
451
|
+
min_log_mel = (min_log_hz - f_min) / f_sp
|
|
452
|
+
logstep = math.log(6.4) / 27.0
|
|
453
|
+
|
|
454
|
+
if freq >= min_log_hz:
|
|
455
|
+
mels = min_log_mel + math.log(freq / min_log_hz) / logstep
|
|
456
|
+
|
|
457
|
+
return mels
|
|
458
|
+
|
|
459
|
+
|
|
460
|
+
def _mel_to_hz(mels: Tensor, mel_scale: str = "htk") -> Tensor:
|
|
461
|
+
"""Convert mel bin numbers to frequencies.
|
|
462
|
+
|
|
463
|
+
Args:
|
|
464
|
+
mels (Tensor): Mel frequencies
|
|
465
|
+
mel_scale (str, optional): Scale to use: ``htk`` or ``slaney``. (Default: ``htk``)
|
|
466
|
+
|
|
467
|
+
Returns:
|
|
468
|
+
freqs (Tensor): Mels converted in Hz
|
|
469
|
+
"""
|
|
470
|
+
|
|
471
|
+
if mel_scale not in ["slaney", "htk"]:
|
|
472
|
+
raise ValueError('mel_scale should be one of "htk" or "slaney".')
|
|
473
|
+
|
|
474
|
+
if mel_scale == "htk":
|
|
475
|
+
return 700.0 * (10.0 ** (mels / 2595.0) - 1.0)
|
|
476
|
+
|
|
477
|
+
# Fill in the linear scale
|
|
478
|
+
f_min = 0.0
|
|
479
|
+
f_sp = 200.0 / 3
|
|
480
|
+
freqs = f_min + f_sp * mels
|
|
481
|
+
|
|
482
|
+
# And now the nonlinear scale
|
|
483
|
+
min_log_hz = 1000.0
|
|
484
|
+
min_log_mel = (min_log_hz - f_min) / f_sp
|
|
485
|
+
logstep = math.log(6.4) / 27.0
|
|
486
|
+
|
|
487
|
+
log_t = mels >= min_log_mel
|
|
488
|
+
freqs[log_t] = min_log_hz * torch.exp(logstep * (mels[log_t] - min_log_mel))
|
|
489
|
+
|
|
490
|
+
return freqs
|
|
491
|
+
|
|
492
|
+
|
|
493
|
+
def _create_triangular_filterbank(
|
|
494
|
+
all_freqs: Tensor,
|
|
495
|
+
f_pts: Tensor,
|
|
496
|
+
) -> Tensor:
|
|
497
|
+
"""Create a triangular filter bank.
|
|
498
|
+
|
|
499
|
+
Args:
|
|
500
|
+
all_freqs (Tensor): STFT freq points of size (`n_freqs`).
|
|
501
|
+
f_pts (Tensor): Filter mid points of size (`n_filter`).
|
|
502
|
+
|
|
503
|
+
Returns:
|
|
504
|
+
fb (Tensor): The filter bank of size (`n_freqs`, `n_filter`).
|
|
505
|
+
"""
|
|
506
|
+
# Adopted from Librosa
|
|
507
|
+
# calculate the difference between each filter mid point and each stft freq point in hertz
|
|
508
|
+
f_diff = f_pts[1:] - f_pts[:-1] # (n_filter + 1)
|
|
509
|
+
slopes = f_pts.unsqueeze(0) - all_freqs.unsqueeze(1) # (n_freqs, n_filter + 2)
|
|
510
|
+
# create overlapping triangles
|
|
511
|
+
zero = torch.zeros(1)
|
|
512
|
+
down_slopes = (-1.0 * slopes[:, :-2]) / f_diff[:-1] # (n_freqs, n_filter)
|
|
513
|
+
up_slopes = slopes[:, 2:] / f_diff[1:] # (n_freqs, n_filter)
|
|
514
|
+
fb = torch.max(zero, torch.min(down_slopes, up_slopes))
|
|
515
|
+
|
|
516
|
+
return fb
|
|
517
|
+
|
|
518
|
+
|
|
519
|
+
def melscale_fbanks(
|
|
520
|
+
n_freqs: int,
|
|
521
|
+
f_min: float,
|
|
522
|
+
f_max: float,
|
|
523
|
+
n_mels: int,
|
|
524
|
+
sample_rate: int,
|
|
525
|
+
norm: Optional[str] = None,
|
|
526
|
+
mel_scale: str = "htk",
|
|
527
|
+
) -> Tensor:
|
|
528
|
+
r"""Create a frequency bin conversion matrix.
|
|
529
|
+
|
|
530
|
+
.. devices:: CPU
|
|
531
|
+
|
|
532
|
+
.. properties:: TorchScript
|
|
533
|
+
|
|
534
|
+
Note:
|
|
535
|
+
For the sake of the numerical compatibility with librosa, not all the coefficients
|
|
536
|
+
in the resulting filter bank has magnitude of 1.
|
|
537
|
+
|
|
538
|
+
.. image:: https://download.pytorch.org/torchaudio/doc-assets/mel_fbanks.png
|
|
539
|
+
:alt: Visualization of generated filter bank
|
|
540
|
+
|
|
541
|
+
Args:
|
|
542
|
+
n_freqs (int): Number of frequencies to highlight/apply
|
|
543
|
+
f_min (float): Minimum frequency (Hz)
|
|
544
|
+
f_max (float): Maximum frequency (Hz)
|
|
545
|
+
n_mels (int): Number of mel filterbanks
|
|
546
|
+
sample_rate (int): Sample rate of the audio waveform
|
|
547
|
+
norm (str or None, optional): If "slaney", divide the triangular mel weights by the width of the mel band
|
|
548
|
+
(area normalization). (Default: ``None``)
|
|
549
|
+
mel_scale (str, optional): Scale to use: ``htk`` or ``slaney``. (Default: ``htk``)
|
|
550
|
+
|
|
551
|
+
Returns:
|
|
552
|
+
Tensor: Triangular filter banks (fb matrix) of size (``n_freqs``, ``n_mels``)
|
|
553
|
+
meaning number of frequencies to highlight/apply to x the number of filterbanks.
|
|
554
|
+
Each column is a filterbank so that assuming there is a matrix A of
|
|
555
|
+
size (..., ``n_freqs``), the applied result would be
|
|
556
|
+
``A @ melscale_fbanks(A.size(-1), ...)``.
|
|
557
|
+
|
|
558
|
+
"""
|
|
559
|
+
|
|
560
|
+
if norm is not None and norm != "slaney":
|
|
561
|
+
raise ValueError('norm must be one of None or "slaney"')
|
|
562
|
+
|
|
563
|
+
# freq bins
|
|
564
|
+
all_freqs = torch.linspace(0, sample_rate // 2, n_freqs)
|
|
565
|
+
|
|
566
|
+
# calculate mel freq bins
|
|
567
|
+
m_min = _hz_to_mel(f_min, mel_scale=mel_scale)
|
|
568
|
+
m_max = _hz_to_mel(f_max, mel_scale=mel_scale)
|
|
569
|
+
|
|
570
|
+
m_pts = torch.linspace(m_min, m_max, n_mels + 2)
|
|
571
|
+
f_pts = _mel_to_hz(m_pts, mel_scale=mel_scale)
|
|
572
|
+
|
|
573
|
+
# create filterbank
|
|
574
|
+
fb = _create_triangular_filterbank(all_freqs, f_pts)
|
|
575
|
+
|
|
576
|
+
if norm is not None and norm == "slaney":
|
|
577
|
+
# Slaney-style mel is scaled to be approx constant energy per channel
|
|
578
|
+
enorm = 2.0 / (f_pts[2 : n_mels + 2] - f_pts[:n_mels])
|
|
579
|
+
fb *= enorm.unsqueeze(0)
|
|
580
|
+
|
|
581
|
+
if (fb.max(dim=0).values == 0.0).any():
|
|
582
|
+
warnings.warn(
|
|
583
|
+
"At least one mel filterbank has all zero values. "
|
|
584
|
+
f"The value for `n_mels` ({n_mels}) may be set too high. "
|
|
585
|
+
f"Or, the value for `n_freqs` ({n_freqs}) may be set too low."
|
|
586
|
+
)
|
|
587
|
+
|
|
588
|
+
return fb
|
|
589
|
+
|
|
590
|
+
|
|
591
|
+
def linear_fbanks(
|
|
592
|
+
n_freqs: int,
|
|
593
|
+
f_min: float,
|
|
594
|
+
f_max: float,
|
|
595
|
+
n_filter: int,
|
|
596
|
+
sample_rate: int,
|
|
597
|
+
) -> Tensor:
|
|
598
|
+
r"""Creates a linear triangular filterbank.
|
|
599
|
+
|
|
600
|
+
.. devices:: CPU
|
|
601
|
+
|
|
602
|
+
.. properties:: TorchScript
|
|
603
|
+
|
|
604
|
+
Note:
|
|
605
|
+
For the sake of the numerical compatibility with librosa, not all the coefficients
|
|
606
|
+
in the resulting filter bank has magnitude of 1.
|
|
607
|
+
|
|
608
|
+
.. image:: https://download.pytorch.org/torchaudio/doc-assets/lin_fbanks.png
|
|
609
|
+
:alt: Visualization of generated filter bank
|
|
610
|
+
|
|
611
|
+
Args:
|
|
612
|
+
n_freqs (int): Number of frequencies to highlight/apply
|
|
613
|
+
f_min (float): Minimum frequency (Hz)
|
|
614
|
+
f_max (float): Maximum frequency (Hz)
|
|
615
|
+
n_filter (int): Number of (linear) triangular filter
|
|
616
|
+
sample_rate (int): Sample rate of the audio waveform
|
|
617
|
+
|
|
618
|
+
Returns:
|
|
619
|
+
Tensor: Triangular filter banks (fb matrix) of size (``n_freqs``, ``n_filter``)
|
|
620
|
+
meaning number of frequencies to highlight/apply to x the number of filterbanks.
|
|
621
|
+
Each column is a filterbank so that assuming there is a matrix A of
|
|
622
|
+
size (..., ``n_freqs``), the applied result would be
|
|
623
|
+
``A * linear_fbanks(A.size(-1), ...)``.
|
|
624
|
+
"""
|
|
625
|
+
# freq bins
|
|
626
|
+
all_freqs = torch.linspace(0, sample_rate // 2, n_freqs)
|
|
627
|
+
|
|
628
|
+
# filter mid-points
|
|
629
|
+
f_pts = torch.linspace(f_min, f_max, n_filter + 2)
|
|
630
|
+
|
|
631
|
+
# create filterbank
|
|
632
|
+
fb = _create_triangular_filterbank(all_freqs, f_pts)
|
|
633
|
+
|
|
634
|
+
return fb
|
|
635
|
+
|
|
636
|
+
|
|
637
|
+
def create_dct(n_mfcc: int, n_mels: int, norm: Optional[str]) -> Tensor:
|
|
638
|
+
r"""Create a DCT transformation matrix with shape (``n_mels``, ``n_mfcc``),
|
|
639
|
+
normalized depending on norm.
|
|
640
|
+
|
|
641
|
+
.. devices:: CPU
|
|
642
|
+
|
|
643
|
+
.. properties:: TorchScript
|
|
644
|
+
|
|
645
|
+
Args:
|
|
646
|
+
n_mfcc (int): Number of mfc coefficients to retain
|
|
647
|
+
n_mels (int): Number of mel filterbanks
|
|
648
|
+
norm (str or None): Norm to use (either "ortho" or None)
|
|
649
|
+
|
|
650
|
+
Returns:
|
|
651
|
+
Tensor: The transformation matrix, to be right-multiplied to
|
|
652
|
+
row-wise data of size (``n_mels``, ``n_mfcc``).
|
|
653
|
+
"""
|
|
654
|
+
|
|
655
|
+
if norm is not None and norm != "ortho":
|
|
656
|
+
raise ValueError('norm must be either "ortho" or None')
|
|
657
|
+
|
|
658
|
+
# http://en.wikipedia.org/wiki/Discrete_cosine_transform#DCT-II
|
|
659
|
+
n = torch.arange(float(n_mels))
|
|
660
|
+
k = torch.arange(float(n_mfcc)).unsqueeze(1)
|
|
661
|
+
dct = torch.cos(math.pi / float(n_mels) * (n + 0.5) * k) # size (n_mfcc, n_mels)
|
|
662
|
+
|
|
663
|
+
if norm is None:
|
|
664
|
+
dct *= 2.0
|
|
665
|
+
else:
|
|
666
|
+
dct[0] *= 1.0 / math.sqrt(2.0)
|
|
667
|
+
dct *= math.sqrt(2.0 / float(n_mels))
|
|
668
|
+
return dct.t()
|
|
669
|
+
|
|
670
|
+
|
|
671
|
+
def mu_law_encoding(x: Tensor, quantization_channels: int) -> Tensor:
|
|
672
|
+
r"""Encode signal based on mu-law companding.
|
|
673
|
+
|
|
674
|
+
.. devices:: CPU CUDA
|
|
675
|
+
|
|
676
|
+
.. properties:: TorchScript
|
|
677
|
+
|
|
678
|
+
For more info see the
|
|
679
|
+
`Wikipedia Entry <https://en.wikipedia.org/wiki/%CE%9C-law_algorithm>`_
|
|
680
|
+
|
|
681
|
+
This algorithm expects the signal has been scaled to between -1 and 1 and
|
|
682
|
+
returns a signal encoded with values from 0 to quantization_channels - 1.
|
|
683
|
+
|
|
684
|
+
Args:
|
|
685
|
+
x (Tensor): Input tensor
|
|
686
|
+
quantization_channels (int): Number of channels
|
|
687
|
+
|
|
688
|
+
Returns:
|
|
689
|
+
Tensor: Input after mu-law encoding
|
|
690
|
+
"""
|
|
691
|
+
mu = quantization_channels - 1.0
|
|
692
|
+
if not x.is_floating_point():
|
|
693
|
+
warnings.warn(
|
|
694
|
+
"The input Tensor must be of floating type. \
|
|
695
|
+
This will be an error in the v0.12 release."
|
|
696
|
+
)
|
|
697
|
+
x = x.to(torch.float)
|
|
698
|
+
mu = torch.tensor(mu, dtype=x.dtype)
|
|
699
|
+
x_mu = torch.sign(x) * torch.log1p(mu * torch.abs(x)) / torch.log1p(mu)
|
|
700
|
+
x_mu = ((x_mu + 1) / 2 * mu + 0.5).to(torch.int64)
|
|
701
|
+
return x_mu
|
|
702
|
+
|
|
703
|
+
|
|
704
|
+
def mu_law_decoding(x_mu: Tensor, quantization_channels: int) -> Tensor:
|
|
705
|
+
r"""Decode mu-law encoded signal.
|
|
706
|
+
|
|
707
|
+
.. devices:: CPU CUDA
|
|
708
|
+
|
|
709
|
+
.. properties:: TorchScript
|
|
710
|
+
|
|
711
|
+
For more info see the
|
|
712
|
+
`Wikipedia Entry <https://en.wikipedia.org/wiki/%CE%9C-law_algorithm>`_
|
|
713
|
+
|
|
714
|
+
This expects an input with values between 0 and quantization_channels - 1
|
|
715
|
+
and returns a signal scaled between -1 and 1.
|
|
716
|
+
|
|
717
|
+
Args:
|
|
718
|
+
x_mu (Tensor): Input tensor
|
|
719
|
+
quantization_channels (int): Number of channels
|
|
720
|
+
|
|
721
|
+
Returns:
|
|
722
|
+
Tensor: Input after mu-law decoding
|
|
723
|
+
"""
|
|
724
|
+
mu = quantization_channels - 1.0
|
|
725
|
+
if not x_mu.is_floating_point():
|
|
726
|
+
x_mu = x_mu.to(torch.float)
|
|
727
|
+
mu = torch.tensor(mu, dtype=x_mu.dtype)
|
|
728
|
+
x = ((x_mu) / mu) * 2 - 1.0
|
|
729
|
+
x = torch.sign(x) * (torch.exp(torch.abs(x) * torch.log1p(mu)) - 1.0) / mu
|
|
730
|
+
return x
|
|
731
|
+
|
|
732
|
+
|
|
733
|
+
def phase_vocoder(complex_specgrams: Tensor, rate: float, phase_advance: Tensor) -> Tensor:
|
|
734
|
+
r"""Given a STFT tensor, speed up in time without modifying pitch by a factor of ``rate``.
|
|
735
|
+
|
|
736
|
+
.. devices:: CPU CUDA
|
|
737
|
+
|
|
738
|
+
.. properties:: Autograd TorchScript
|
|
739
|
+
|
|
740
|
+
Args:
|
|
741
|
+
complex_specgrams (Tensor):
|
|
742
|
+
A tensor of dimension `(..., freq, num_frame)` with complex dtype.
|
|
743
|
+
rate (float): Speed-up factor
|
|
744
|
+
phase_advance (Tensor): Expected phase advance in each bin. Dimension of `(freq, 1)`
|
|
745
|
+
|
|
746
|
+
Returns:
|
|
747
|
+
Tensor:
|
|
748
|
+
Stretched spectrogram. The resulting tensor is of the same dtype as the input
|
|
749
|
+
spectrogram, but the number of frames is changed to ``ceil(num_frame / rate)``.
|
|
750
|
+
|
|
751
|
+
Example
|
|
752
|
+
>>> freq, hop_length = 1025, 512
|
|
753
|
+
>>> # (channel, freq, time)
|
|
754
|
+
>>> complex_specgrams = torch.randn(2, freq, 300, dtype=torch.cfloat)
|
|
755
|
+
>>> rate = 1.3 # Speed up by 30%
|
|
756
|
+
>>> phase_advance = torch.linspace(
|
|
757
|
+
>>> 0, math.pi * hop_length, freq)[..., None]
|
|
758
|
+
>>> x = phase_vocoder(complex_specgrams, rate, phase_advance)
|
|
759
|
+
>>> x.shape # with 231 == ceil(300 / 1.3)
|
|
760
|
+
torch.Size([2, 1025, 231])
|
|
761
|
+
"""
|
|
762
|
+
if rate == 1.0:
|
|
763
|
+
return complex_specgrams
|
|
764
|
+
|
|
765
|
+
# pack batch
|
|
766
|
+
shape = complex_specgrams.size()
|
|
767
|
+
complex_specgrams = complex_specgrams.reshape([-1] + list(shape[-2:]))
|
|
768
|
+
|
|
769
|
+
# Figures out the corresponding real dtype, i.e. complex128 -> float64, complex64 -> float32
|
|
770
|
+
# Note torch.real is a view so it does not incur any memory copy.
|
|
771
|
+
real_dtype = torch.real(complex_specgrams).dtype
|
|
772
|
+
time_steps = torch.arange(0, complex_specgrams.size(-1), rate, device=complex_specgrams.device, dtype=real_dtype)
|
|
773
|
+
|
|
774
|
+
alphas = time_steps % 1.0
|
|
775
|
+
phase_0 = complex_specgrams[..., :1].angle()
|
|
776
|
+
|
|
777
|
+
# Time Padding
|
|
778
|
+
complex_specgrams = torch.nn.functional.pad(complex_specgrams, [0, 2])
|
|
779
|
+
|
|
780
|
+
# (new_bins, freq, 2)
|
|
781
|
+
complex_specgrams_0 = complex_specgrams.index_select(-1, time_steps.long())
|
|
782
|
+
complex_specgrams_1 = complex_specgrams.index_select(-1, (time_steps + 1).long())
|
|
783
|
+
|
|
784
|
+
angle_0 = complex_specgrams_0.angle()
|
|
785
|
+
angle_1 = complex_specgrams_1.angle()
|
|
786
|
+
|
|
787
|
+
norm_0 = complex_specgrams_0.abs()
|
|
788
|
+
norm_1 = complex_specgrams_1.abs()
|
|
789
|
+
|
|
790
|
+
phase = angle_1 - angle_0 - phase_advance
|
|
791
|
+
phase = phase - 2 * math.pi * torch.round(phase / (2 * math.pi))
|
|
792
|
+
|
|
793
|
+
# Compute Phase Accum
|
|
794
|
+
phase = phase + phase_advance
|
|
795
|
+
phase = torch.cat([phase_0, phase[..., :-1]], dim=-1)
|
|
796
|
+
phase_acc = torch.cumsum(phase, -1)
|
|
797
|
+
|
|
798
|
+
mag = alphas * norm_1 + (1 - alphas) * norm_0
|
|
799
|
+
|
|
800
|
+
complex_specgrams_stretch = torch.polar(mag, phase_acc)
|
|
801
|
+
|
|
802
|
+
# unpack batch
|
|
803
|
+
complex_specgrams_stretch = complex_specgrams_stretch.reshape(shape[:-2] + complex_specgrams_stretch.shape[1:])
|
|
804
|
+
return complex_specgrams_stretch
|
|
805
|
+
|
|
806
|
+
|
|
807
|
+
def _get_mask_param(mask_param: int, p: float, axis_length: int) -> int:
|
|
808
|
+
if p == 1.0:
|
|
809
|
+
return mask_param
|
|
810
|
+
else:
|
|
811
|
+
return min(mask_param, int(axis_length * p))
|
|
812
|
+
|
|
813
|
+
|
|
814
|
+
def mask_along_axis_iid(
|
|
815
|
+
specgrams: Tensor,
|
|
816
|
+
mask_param: int,
|
|
817
|
+
mask_value: Union[float, Tensor],
|
|
818
|
+
axis: int,
|
|
819
|
+
p: float = 1.0,
|
|
820
|
+
) -> Tensor:
|
|
821
|
+
r"""Apply a mask along ``axis``.
|
|
822
|
+
|
|
823
|
+
.. devices:: CPU CUDA
|
|
824
|
+
|
|
825
|
+
.. properties:: Autograd TorchScript
|
|
826
|
+
|
|
827
|
+
Mask will be applied from indices ``[v_0, v_0 + v)``,
|
|
828
|
+
where ``v`` is sampled from ``uniform(0, max_v)`` and
|
|
829
|
+
``v_0`` from ``uniform(0, specgrams.size(axis) - v)``,
|
|
830
|
+
with ``max_v = mask_param`` when ``p = 1.0`` and
|
|
831
|
+
``max_v = min(mask_param, floor(specgrams.size(axis) * p))`` otherwise.
|
|
832
|
+
|
|
833
|
+
Args:
|
|
834
|
+
specgrams (Tensor): Real spectrograms `(..., freq, time)`, with at least 3 dimensions.
|
|
835
|
+
mask_param (int): Number of columns to be masked will be uniformly sampled from [0, mask_param]
|
|
836
|
+
mask_value (float): Value to assign to the masked columns
|
|
837
|
+
axis (int): Axis to apply masking on, which should be the one of the last two dimensions.
|
|
838
|
+
p (float, optional): maximum proportion of columns that can be masked. (Default: 1.0)
|
|
839
|
+
|
|
840
|
+
Returns:
|
|
841
|
+
Tensor: Masked spectrograms with the same dimensions as input specgrams Tensor`
|
|
842
|
+
"""
|
|
843
|
+
|
|
844
|
+
dim = specgrams.dim()
|
|
845
|
+
|
|
846
|
+
if dim < 3:
|
|
847
|
+
raise ValueError(f"Spectrogram must have at least three dimensions ({dim} given).")
|
|
848
|
+
|
|
849
|
+
if axis not in [dim - 2, dim - 1]:
|
|
850
|
+
raise ValueError(
|
|
851
|
+
f"Only Frequency and Time masking are supported (axis {dim-2} and axis {dim-1} supported; {axis} given)."
|
|
852
|
+
)
|
|
853
|
+
|
|
854
|
+
if not 0.0 <= p <= 1.0:
|
|
855
|
+
raise ValueError(f"The value of p must be between 0.0 and 1.0 ({p} given).")
|
|
856
|
+
|
|
857
|
+
mask_param = _get_mask_param(mask_param, p, specgrams.shape[axis])
|
|
858
|
+
if mask_param < 1:
|
|
859
|
+
return specgrams
|
|
860
|
+
|
|
861
|
+
device = specgrams.device
|
|
862
|
+
dtype = specgrams.dtype
|
|
863
|
+
|
|
864
|
+
value = torch.rand(specgrams.shape[: (dim - 2)], device=device, dtype=dtype) * mask_param
|
|
865
|
+
min_value = torch.rand(specgrams.shape[: (dim - 2)], device=device, dtype=dtype) * (specgrams.size(axis) - value)
|
|
866
|
+
|
|
867
|
+
# Create broadcastable mask
|
|
868
|
+
mask_start = min_value.long()[..., None, None]
|
|
869
|
+
mask_end = (min_value.long() + value.long())[..., None, None]
|
|
870
|
+
mask = torch.arange(0, specgrams.size(axis), device=device, dtype=dtype)
|
|
871
|
+
|
|
872
|
+
# Per batch example masking
|
|
873
|
+
specgrams = specgrams.transpose(axis, -1)
|
|
874
|
+
# this aims to avoid CPU-GPU sync from upstream
|
|
875
|
+
specgrams = (
|
|
876
|
+
torch.where((mask >= mask_start) & (mask < mask_end), mask_value.repeat(specgrams.shape), specgrams)
|
|
877
|
+
if isinstance(mask_value, Tensor)
|
|
878
|
+
else specgrams.masked_fill((mask >= mask_start) & (mask < mask_end), mask_value)
|
|
879
|
+
)
|
|
880
|
+
specgrams = specgrams.transpose(axis, -1)
|
|
881
|
+
|
|
882
|
+
return specgrams
|
|
883
|
+
|
|
884
|
+
|
|
885
|
+
def mask_along_axis(
|
|
886
|
+
specgram: Tensor,
|
|
887
|
+
mask_param: int,
|
|
888
|
+
mask_value: float,
|
|
889
|
+
axis: int,
|
|
890
|
+
p: float = 1.0,
|
|
891
|
+
) -> Tensor:
|
|
892
|
+
r"""Apply a mask along ``axis``.
|
|
893
|
+
|
|
894
|
+
.. devices:: CPU CUDA
|
|
895
|
+
|
|
896
|
+
.. properties:: Autograd TorchScript
|
|
897
|
+
|
|
898
|
+
Mask will be applied from indices ``[v_0, v_0 + v)``,
|
|
899
|
+
where ``v`` is sampled from ``uniform(0, max_v)`` and
|
|
900
|
+
``v_0`` from ``uniform(0, specgram.size(axis) - v)``, with
|
|
901
|
+
``max_v = mask_param`` when ``p = 1.0`` and
|
|
902
|
+
``max_v = min(mask_param, floor(specgram.size(axis) * p))``
|
|
903
|
+
otherwise.
|
|
904
|
+
All examples will have the same mask interval.
|
|
905
|
+
|
|
906
|
+
Args:
|
|
907
|
+
specgram (Tensor): Real spectrograms `(..., freq, time)`, with at least 2 dimensions.
|
|
908
|
+
mask_param (int): Number of columns to be masked will be uniformly sampled from [0, mask_param]
|
|
909
|
+
mask_value (float): Value to assign to the masked columns
|
|
910
|
+
axis (int): Axis to apply masking on, which should be the one of the last two dimensions.
|
|
911
|
+
p (float, optional): maximum proportion of columns that can be masked. (Default: 1.0)
|
|
912
|
+
|
|
913
|
+
Returns:
|
|
914
|
+
Tensor: Masked spectrograms with the same dimensions as input specgram Tensor
|
|
915
|
+
"""
|
|
916
|
+
dim = specgram.dim()
|
|
917
|
+
|
|
918
|
+
if dim < 2:
|
|
919
|
+
raise ValueError(f"Spectrogram must have at least two dimensions (time and frequency) ({dim} given).")
|
|
920
|
+
|
|
921
|
+
if axis not in [dim - 2, dim - 1]:
|
|
922
|
+
raise ValueError(
|
|
923
|
+
f"Only Frequency and Time masking are supported (axis {dim-2} and axis {dim-1} supported; {axis} given)."
|
|
924
|
+
)
|
|
925
|
+
|
|
926
|
+
if not 0.0 <= p <= 1.0:
|
|
927
|
+
raise ValueError(f"The value of p must be between 0.0 and 1.0 ({p} given).")
|
|
928
|
+
|
|
929
|
+
mask_param = _get_mask_param(mask_param, p, specgram.shape[axis])
|
|
930
|
+
if mask_param < 1:
|
|
931
|
+
return specgram
|
|
932
|
+
|
|
933
|
+
# pack batch
|
|
934
|
+
shape = specgram.size()
|
|
935
|
+
specgram = specgram.reshape([-1] + list(shape[-2:]))
|
|
936
|
+
# After packing, specgram is a 3D tensor, and the axis corresponding to the to-be-masked dimension
|
|
937
|
+
# is now (axis - dim + 3), e.g. a tensor of shape (10, 2, 50, 10, 2) becomes a tensor of shape (1000, 10, 2).
|
|
938
|
+
value = torch.rand(1) * mask_param
|
|
939
|
+
min_value = torch.rand(1) * (specgram.size(axis - dim + 3) - value)
|
|
940
|
+
|
|
941
|
+
mask_start = (min_value.long()).squeeze()
|
|
942
|
+
mask_end = (min_value.long() + value.long()).squeeze()
|
|
943
|
+
mask = torch.arange(0, specgram.shape[axis - dim + 3], device=specgram.device, dtype=specgram.dtype)
|
|
944
|
+
mask = (mask >= mask_start) & (mask < mask_end)
|
|
945
|
+
# unsqueeze the mask if the axis is frequency
|
|
946
|
+
if axis == dim - 2:
|
|
947
|
+
mask = mask.unsqueeze(-1)
|
|
948
|
+
|
|
949
|
+
if mask_end - mask_start >= mask_param:
|
|
950
|
+
raise ValueError("Number of columns to be masked should be less than mask_param")
|
|
951
|
+
|
|
952
|
+
specgram = specgram.masked_fill(mask, mask_value)
|
|
953
|
+
|
|
954
|
+
# unpack batch
|
|
955
|
+
specgram = specgram.reshape(shape[:-2] + specgram.shape[-2:])
|
|
956
|
+
|
|
957
|
+
return specgram
|
|
958
|
+
|
|
959
|
+
|
|
960
|
+
def compute_deltas(specgram: Tensor, win_length: int = 5, mode: str = "replicate") -> Tensor:
|
|
961
|
+
r"""Compute delta coefficients of a tensor, usually a spectrogram:
|
|
962
|
+
|
|
963
|
+
.. devices:: CPU CUDA
|
|
964
|
+
|
|
965
|
+
.. properties:: TorchScript
|
|
966
|
+
|
|
967
|
+
.. math::
|
|
968
|
+
d_t = \frac{\sum_{n=1}^{\text{N}} n (c_{t+n} - c_{t-n})}{2 \sum_{n=1}^{\text{N}} n^2}
|
|
969
|
+
|
|
970
|
+
where :math:`d_t` is the deltas at time :math:`t`,
|
|
971
|
+
:math:`c_t` is the spectrogram coeffcients at time :math:`t`,
|
|
972
|
+
:math:`N` is ``(win_length-1)//2``.
|
|
973
|
+
|
|
974
|
+
Args:
|
|
975
|
+
specgram (Tensor): Tensor of audio of dimension `(..., freq, time)`
|
|
976
|
+
win_length (int, optional): The window length used for computing delta (Default: ``5``)
|
|
977
|
+
mode (str, optional): Mode parameter passed to padding (Default: ``"replicate"``)
|
|
978
|
+
|
|
979
|
+
Returns:
|
|
980
|
+
Tensor: Tensor of deltas of dimension `(..., freq, time)`
|
|
981
|
+
|
|
982
|
+
Example
|
|
983
|
+
>>> specgram = torch.randn(1, 40, 1000)
|
|
984
|
+
>>> delta = compute_deltas(specgram)
|
|
985
|
+
>>> delta2 = compute_deltas(delta)
|
|
986
|
+
"""
|
|
987
|
+
device = specgram.device
|
|
988
|
+
dtype = specgram.dtype
|
|
989
|
+
|
|
990
|
+
# pack batch
|
|
991
|
+
shape = specgram.size()
|
|
992
|
+
specgram = specgram.reshape(1, -1, shape[-1])
|
|
993
|
+
|
|
994
|
+
if win_length < 3:
|
|
995
|
+
raise ValueError(f"Window length should be greater than or equal to 3. Found win_length {win_length}")
|
|
996
|
+
|
|
997
|
+
n = (win_length - 1) // 2
|
|
998
|
+
|
|
999
|
+
# twice sum of integer squared
|
|
1000
|
+
denom = n * (n + 1) * (2 * n + 1) / 3
|
|
1001
|
+
|
|
1002
|
+
specgram = torch.nn.functional.pad(specgram, (n, n), mode=mode)
|
|
1003
|
+
|
|
1004
|
+
kernel = torch.arange(-n, n + 1, 1, device=device, dtype=dtype).repeat(specgram.shape[1], 1, 1)
|
|
1005
|
+
|
|
1006
|
+
output = torch.nn.functional.conv1d(specgram, kernel, groups=specgram.shape[1]) / denom
|
|
1007
|
+
|
|
1008
|
+
# unpack batch
|
|
1009
|
+
output = output.reshape(shape)
|
|
1010
|
+
|
|
1011
|
+
return output
|
|
1012
|
+
|
|
1013
|
+
|
|
1014
|
+
def _compute_nccf(waveform: Tensor, sample_rate: int, frame_time: float, freq_low: int) -> Tensor:
|
|
1015
|
+
r"""
|
|
1016
|
+
Compute Normalized Cross-Correlation Function (NCCF).
|
|
1017
|
+
|
|
1018
|
+
.. math::
|
|
1019
|
+
\phi_i(m) = \frac{\sum_{n=b_i}^{b_i + N-1} w(n) w(m+n)}{\sqrt{E(b_i) E(m+b_i)}},
|
|
1020
|
+
|
|
1021
|
+
where
|
|
1022
|
+
:math:`\phi_i(m)` is the NCCF at frame :math:`i` with lag :math:`m`,
|
|
1023
|
+
:math:`w` is the waveform,
|
|
1024
|
+
:math:`N` is the length of a frame,
|
|
1025
|
+
:math:`b_i` is the beginning of frame :math:`i`,
|
|
1026
|
+
:math:`E(j)` is the energy :math:`\sum_{n=j}^{j+N-1} w^2(n)`.
|
|
1027
|
+
"""
|
|
1028
|
+
|
|
1029
|
+
EPSILON = 10 ** (-9)
|
|
1030
|
+
|
|
1031
|
+
# Number of lags to check
|
|
1032
|
+
lags = int(math.ceil(sample_rate / freq_low))
|
|
1033
|
+
|
|
1034
|
+
frame_size = int(math.ceil(sample_rate * frame_time))
|
|
1035
|
+
|
|
1036
|
+
waveform_length = waveform.size()[-1]
|
|
1037
|
+
num_of_frames = int(math.ceil(waveform_length / frame_size))
|
|
1038
|
+
|
|
1039
|
+
p = lags + num_of_frames * frame_size - waveform_length
|
|
1040
|
+
waveform = torch.nn.functional.pad(waveform, (0, p))
|
|
1041
|
+
|
|
1042
|
+
# Compute lags
|
|
1043
|
+
output_lag = []
|
|
1044
|
+
for lag in range(1, lags + 1):
|
|
1045
|
+
s1 = waveform[..., :-lag].unfold(-1, frame_size, frame_size)[..., :num_of_frames, :]
|
|
1046
|
+
s2 = waveform[..., lag:].unfold(-1, frame_size, frame_size)[..., :num_of_frames, :]
|
|
1047
|
+
|
|
1048
|
+
output_frames = (
|
|
1049
|
+
(s1 * s2).sum(-1)
|
|
1050
|
+
/ (EPSILON + torch.linalg.vector_norm(s1, ord=2, dim=-1)).pow(2)
|
|
1051
|
+
/ (EPSILON + torch.linalg.vector_norm(s2, ord=2, dim=-1)).pow(2)
|
|
1052
|
+
)
|
|
1053
|
+
|
|
1054
|
+
output_lag.append(output_frames.unsqueeze(-1))
|
|
1055
|
+
|
|
1056
|
+
nccf = torch.cat(output_lag, -1)
|
|
1057
|
+
|
|
1058
|
+
return nccf
|
|
1059
|
+
|
|
1060
|
+
|
|
1061
|
+
def _combine_max(a: Tuple[Tensor, Tensor], b: Tuple[Tensor, Tensor], thresh: float = 0.99) -> Tuple[Tensor, Tensor]:
|
|
1062
|
+
"""
|
|
1063
|
+
Take value from first if bigger than a multiplicative factor of the second, elementwise.
|
|
1064
|
+
"""
|
|
1065
|
+
mask = a[0] > thresh * b[0]
|
|
1066
|
+
values = mask * a[0] + ~mask * b[0]
|
|
1067
|
+
indices = mask * a[1] + ~mask * b[1]
|
|
1068
|
+
return values, indices
|
|
1069
|
+
|
|
1070
|
+
|
|
1071
|
+
def _find_max_per_frame(nccf: Tensor, sample_rate: int, freq_high: int) -> Tensor:
|
|
1072
|
+
r"""
|
|
1073
|
+
For each frame, take the highest value of NCCF,
|
|
1074
|
+
apply centered median smoothing, and convert to frequency.
|
|
1075
|
+
|
|
1076
|
+
Note: If the max among all the lags is very close
|
|
1077
|
+
to the first half of lags, then the latter is taken.
|
|
1078
|
+
"""
|
|
1079
|
+
|
|
1080
|
+
lag_min = int(math.ceil(sample_rate / freq_high))
|
|
1081
|
+
|
|
1082
|
+
# Find near enough max that is smallest
|
|
1083
|
+
|
|
1084
|
+
best = torch.max(nccf[..., lag_min:], -1)
|
|
1085
|
+
|
|
1086
|
+
half_size = nccf.shape[-1] // 2
|
|
1087
|
+
half = torch.max(nccf[..., lag_min:half_size], -1)
|
|
1088
|
+
|
|
1089
|
+
best = _combine_max(half, best)
|
|
1090
|
+
indices = best[1]
|
|
1091
|
+
|
|
1092
|
+
# Add back minimal lag
|
|
1093
|
+
indices += lag_min
|
|
1094
|
+
# Add 1 empirical calibration offset
|
|
1095
|
+
indices += 1
|
|
1096
|
+
|
|
1097
|
+
return indices
|
|
1098
|
+
|
|
1099
|
+
|
|
1100
|
+
def _median_smoothing(indices: Tensor, win_length: int) -> Tensor:
|
|
1101
|
+
r"""
|
|
1102
|
+
Apply median smoothing to the 1D tensor over the given window.
|
|
1103
|
+
"""
|
|
1104
|
+
|
|
1105
|
+
# Centered windowed
|
|
1106
|
+
pad_length = (win_length - 1) // 2
|
|
1107
|
+
|
|
1108
|
+
# "replicate" padding in any dimension
|
|
1109
|
+
indices = torch.nn.functional.pad(indices, (pad_length, 0), mode="constant", value=0.0)
|
|
1110
|
+
|
|
1111
|
+
indices[..., :pad_length] = torch.cat(pad_length * [indices[..., pad_length].unsqueeze(-1)], dim=-1)
|
|
1112
|
+
roll = indices.unfold(-1, win_length, 1)
|
|
1113
|
+
|
|
1114
|
+
values, _ = torch.median(roll, -1)
|
|
1115
|
+
return values
|
|
1116
|
+
|
|
1117
|
+
|
|
1118
|
+
def detect_pitch_frequency(
|
|
1119
|
+
waveform: Tensor,
|
|
1120
|
+
sample_rate: int,
|
|
1121
|
+
frame_time: float = 10 ** (-2),
|
|
1122
|
+
win_length: int = 30,
|
|
1123
|
+
freq_low: int = 85,
|
|
1124
|
+
freq_high: int = 3400,
|
|
1125
|
+
) -> Tensor:
|
|
1126
|
+
r"""Detect pitch frequency.
|
|
1127
|
+
|
|
1128
|
+
.. devices:: CPU CUDA
|
|
1129
|
+
|
|
1130
|
+
.. properties:: TorchScript
|
|
1131
|
+
|
|
1132
|
+
It is implemented using normalized cross-correlation function and median smoothing.
|
|
1133
|
+
|
|
1134
|
+
Args:
|
|
1135
|
+
waveform (Tensor): Tensor of audio of dimension `(..., freq, time)`
|
|
1136
|
+
sample_rate (int): The sample rate of the waveform (Hz)
|
|
1137
|
+
frame_time (float, optional): Duration of a frame (Default: ``10 ** (-2)``).
|
|
1138
|
+
win_length (int, optional): The window length for median smoothing (in number of frames) (Default: ``30``).
|
|
1139
|
+
freq_low (int, optional): Lowest frequency that can be detected (Hz) (Default: ``85``).
|
|
1140
|
+
freq_high (int, optional): Highest frequency that can be detected (Hz) (Default: ``3400``).
|
|
1141
|
+
|
|
1142
|
+
Returns:
|
|
1143
|
+
Tensor: Tensor of freq of dimension `(..., frame)`
|
|
1144
|
+
"""
|
|
1145
|
+
# pack batch
|
|
1146
|
+
shape = list(waveform.size())
|
|
1147
|
+
waveform = waveform.reshape([-1] + shape[-1:])
|
|
1148
|
+
|
|
1149
|
+
nccf = _compute_nccf(waveform, sample_rate, frame_time, freq_low)
|
|
1150
|
+
indices = _find_max_per_frame(nccf, sample_rate, freq_high)
|
|
1151
|
+
indices = _median_smoothing(indices, win_length)
|
|
1152
|
+
|
|
1153
|
+
# Convert indices to frequency
|
|
1154
|
+
EPSILON = 10 ** (-9)
|
|
1155
|
+
freq = sample_rate / (EPSILON + indices.to(torch.float))
|
|
1156
|
+
|
|
1157
|
+
# unpack batch
|
|
1158
|
+
freq = freq.reshape(shape[:-1] + list(freq.shape[-1:]))
|
|
1159
|
+
|
|
1160
|
+
return freq
|
|
1161
|
+
|
|
1162
|
+
|
|
1163
|
+
def sliding_window_cmn(
|
|
1164
|
+
specgram: Tensor,
|
|
1165
|
+
cmn_window: int = 600,
|
|
1166
|
+
min_cmn_window: int = 100,
|
|
1167
|
+
center: bool = False,
|
|
1168
|
+
norm_vars: bool = False,
|
|
1169
|
+
) -> Tensor:
|
|
1170
|
+
r"""
|
|
1171
|
+
Apply sliding-window cepstral mean (and optionally variance) normalization per utterance.
|
|
1172
|
+
|
|
1173
|
+
.. devices:: CPU CUDA
|
|
1174
|
+
|
|
1175
|
+
.. properties:: TorchScript
|
|
1176
|
+
|
|
1177
|
+
Args:
|
|
1178
|
+
specgram (Tensor): Tensor of spectrogram of dimension `(..., time, freq)`
|
|
1179
|
+
cmn_window (int, optional): Window in frames for running average CMN computation (int, default = 600)
|
|
1180
|
+
min_cmn_window (int, optional): Minimum CMN window used at start of decoding (adds latency only at start).
|
|
1181
|
+
Only applicable if center == false, ignored if center==true (int, default = 100)
|
|
1182
|
+
center (bool, optional): If true, use a window centered on the current frame
|
|
1183
|
+
(to the extent possible, modulo end effects). If false, window is to the left. (bool, default = false)
|
|
1184
|
+
norm_vars (bool, optional): If true, normalize variance to one. (bool, default = false)
|
|
1185
|
+
|
|
1186
|
+
Returns:
|
|
1187
|
+
Tensor: Tensor matching input shape `(..., freq, time)`
|
|
1188
|
+
"""
|
|
1189
|
+
input_shape = specgram.shape
|
|
1190
|
+
num_frames, num_feats = input_shape[-2:]
|
|
1191
|
+
specgram = specgram.view(-1, num_frames, num_feats)
|
|
1192
|
+
num_channels = specgram.shape[0]
|
|
1193
|
+
|
|
1194
|
+
dtype = specgram.dtype
|
|
1195
|
+
device = specgram.device
|
|
1196
|
+
last_window_start = last_window_end = -1
|
|
1197
|
+
cur_sum = torch.zeros(num_channels, num_feats, dtype=dtype, device=device)
|
|
1198
|
+
cur_sumsq = torch.zeros(num_channels, num_feats, dtype=dtype, device=device)
|
|
1199
|
+
cmn_specgram = torch.zeros(num_channels, num_frames, num_feats, dtype=dtype, device=device)
|
|
1200
|
+
for t in range(num_frames):
|
|
1201
|
+
window_start = 0
|
|
1202
|
+
window_end = 0
|
|
1203
|
+
if center:
|
|
1204
|
+
window_start = t - cmn_window // 2
|
|
1205
|
+
window_end = window_start + cmn_window
|
|
1206
|
+
else:
|
|
1207
|
+
window_start = t - cmn_window
|
|
1208
|
+
window_end = t + 1
|
|
1209
|
+
if window_start < 0:
|
|
1210
|
+
window_end -= window_start
|
|
1211
|
+
window_start = 0
|
|
1212
|
+
if not center:
|
|
1213
|
+
if window_end > t:
|
|
1214
|
+
window_end = max(t + 1, min_cmn_window)
|
|
1215
|
+
if window_end > num_frames:
|
|
1216
|
+
window_start -= window_end - num_frames
|
|
1217
|
+
window_end = num_frames
|
|
1218
|
+
if window_start < 0:
|
|
1219
|
+
window_start = 0
|
|
1220
|
+
if last_window_start == -1:
|
|
1221
|
+
input_part = specgram[:, window_start : window_end - window_start, :]
|
|
1222
|
+
cur_sum += torch.sum(input_part, 1)
|
|
1223
|
+
if norm_vars:
|
|
1224
|
+
cur_sumsq += torch.cumsum(input_part**2, 1)[:, -1, :]
|
|
1225
|
+
else:
|
|
1226
|
+
if window_start > last_window_start:
|
|
1227
|
+
frame_to_remove = specgram[:, last_window_start, :]
|
|
1228
|
+
cur_sum -= frame_to_remove
|
|
1229
|
+
if norm_vars:
|
|
1230
|
+
cur_sumsq -= frame_to_remove**2
|
|
1231
|
+
if window_end > last_window_end:
|
|
1232
|
+
frame_to_add = specgram[:, last_window_end, :]
|
|
1233
|
+
cur_sum += frame_to_add
|
|
1234
|
+
if norm_vars:
|
|
1235
|
+
cur_sumsq += frame_to_add**2
|
|
1236
|
+
window_frames = window_end - window_start
|
|
1237
|
+
last_window_start = window_start
|
|
1238
|
+
last_window_end = window_end
|
|
1239
|
+
cmn_specgram[:, t, :] = specgram[:, t, :] - cur_sum / window_frames
|
|
1240
|
+
if norm_vars:
|
|
1241
|
+
if window_frames == 1:
|
|
1242
|
+
cmn_specgram[:, t, :] = torch.zeros(num_channels, num_feats, dtype=dtype, device=device)
|
|
1243
|
+
else:
|
|
1244
|
+
variance = cur_sumsq
|
|
1245
|
+
variance = variance / window_frames
|
|
1246
|
+
variance -= (cur_sum**2) / (window_frames**2)
|
|
1247
|
+
variance = torch.pow(variance, -0.5)
|
|
1248
|
+
cmn_specgram[:, t, :] *= variance
|
|
1249
|
+
|
|
1250
|
+
cmn_specgram = cmn_specgram.view(input_shape[:-2] + (num_frames, num_feats))
|
|
1251
|
+
if len(input_shape) == 2:
|
|
1252
|
+
cmn_specgram = cmn_specgram.squeeze(0)
|
|
1253
|
+
return cmn_specgram
|
|
1254
|
+
|
|
1255
|
+
|
|
1256
|
+
def spectral_centroid(
|
|
1257
|
+
waveform: Tensor,
|
|
1258
|
+
sample_rate: int,
|
|
1259
|
+
pad: int,
|
|
1260
|
+
window: Tensor,
|
|
1261
|
+
n_fft: int,
|
|
1262
|
+
hop_length: int,
|
|
1263
|
+
win_length: int,
|
|
1264
|
+
) -> Tensor:
|
|
1265
|
+
r"""Compute the spectral centroid for each channel along the time axis.
|
|
1266
|
+
|
|
1267
|
+
.. devices:: CPU CUDA
|
|
1268
|
+
|
|
1269
|
+
.. properties:: Autograd TorchScript
|
|
1270
|
+
|
|
1271
|
+
The spectral centroid is defined as the weighted average of the
|
|
1272
|
+
frequency values, weighted by their magnitude.
|
|
1273
|
+
|
|
1274
|
+
Args:
|
|
1275
|
+
waveform (Tensor): Tensor of audio of dimension `(..., time)`
|
|
1276
|
+
sample_rate (int): Sample rate of the audio waveform
|
|
1277
|
+
pad (int): Two sided padding of signal
|
|
1278
|
+
window (Tensor): Window tensor that is applied/multiplied to each frame/window
|
|
1279
|
+
n_fft (int): Size of FFT
|
|
1280
|
+
hop_length (int): Length of hop between STFT windows
|
|
1281
|
+
win_length (int): Window size
|
|
1282
|
+
|
|
1283
|
+
Returns:
|
|
1284
|
+
Tensor: Dimension `(..., time)`
|
|
1285
|
+
"""
|
|
1286
|
+
specgram = spectrogram(
|
|
1287
|
+
waveform,
|
|
1288
|
+
pad=pad,
|
|
1289
|
+
window=window,
|
|
1290
|
+
n_fft=n_fft,
|
|
1291
|
+
hop_length=hop_length,
|
|
1292
|
+
win_length=win_length,
|
|
1293
|
+
power=1.0,
|
|
1294
|
+
normalized=False,
|
|
1295
|
+
)
|
|
1296
|
+
freqs = torch.linspace(0, sample_rate // 2, steps=1 + n_fft // 2, device=specgram.device).reshape((-1, 1))
|
|
1297
|
+
freq_dim = -2
|
|
1298
|
+
return (freqs * specgram).sum(dim=freq_dim) / specgram.sum(dim=freq_dim)
|
|
1299
|
+
|
|
1300
|
+
|
|
1301
|
+
_CPU = torch.device("cpu")
|
|
1302
|
+
|
|
1303
|
+
|
|
1304
|
+
def _get_sinc_resample_kernel(
|
|
1305
|
+
orig_freq: int,
|
|
1306
|
+
new_freq: int,
|
|
1307
|
+
gcd: int,
|
|
1308
|
+
lowpass_filter_width: int = 6,
|
|
1309
|
+
rolloff: float = 0.99,
|
|
1310
|
+
resampling_method: str = "sinc_interp_hann",
|
|
1311
|
+
beta: Optional[float] = None,
|
|
1312
|
+
device: torch.device = _CPU,
|
|
1313
|
+
dtype: Optional[torch.dtype] = None,
|
|
1314
|
+
):
|
|
1315
|
+
if not (int(orig_freq) == orig_freq and int(new_freq) == new_freq):
|
|
1316
|
+
raise Exception(
|
|
1317
|
+
"Frequencies must be of integer type to ensure quality resampling computation. "
|
|
1318
|
+
"To work around this, manually convert both frequencies to integer values "
|
|
1319
|
+
"that maintain their resampling rate ratio before passing them into the function. "
|
|
1320
|
+
"Example: To downsample a 44100 hz waveform by a factor of 8, use "
|
|
1321
|
+
"`orig_freq=8` and `new_freq=1` instead of `orig_freq=44100` and `new_freq=5512.5`. "
|
|
1322
|
+
"For more information, please refer to https://github.com/pytorch/audio/issues/1487."
|
|
1323
|
+
)
|
|
1324
|
+
|
|
1325
|
+
if resampling_method in ["sinc_interpolation", "kaiser_window"]:
|
|
1326
|
+
method_map = {
|
|
1327
|
+
"sinc_interpolation": "sinc_interp_hann",
|
|
1328
|
+
"kaiser_window": "sinc_interp_kaiser",
|
|
1329
|
+
}
|
|
1330
|
+
warnings.warn(
|
|
1331
|
+
f'"{resampling_method}" resampling method name is being deprecated and replaced by '
|
|
1332
|
+
f'"{method_map[resampling_method]}" in the next release. '
|
|
1333
|
+
"The default behavior remains unchanged.",
|
|
1334
|
+
stacklevel=3,
|
|
1335
|
+
)
|
|
1336
|
+
elif resampling_method not in ["sinc_interp_hann", "sinc_interp_kaiser"]:
|
|
1337
|
+
raise ValueError("Invalid resampling method: {}".format(resampling_method))
|
|
1338
|
+
|
|
1339
|
+
orig_freq = int(orig_freq) // gcd
|
|
1340
|
+
new_freq = int(new_freq) // gcd
|
|
1341
|
+
|
|
1342
|
+
if lowpass_filter_width <= 0:
|
|
1343
|
+
raise ValueError("Low pass filter width should be positive.")
|
|
1344
|
+
base_freq = min(orig_freq, new_freq)
|
|
1345
|
+
# This will perform antialiasing filtering by removing the highest frequencies.
|
|
1346
|
+
# At first I thought I only needed this when downsampling, but when upsampling
|
|
1347
|
+
# you will get edge artifacts without this, as the edge is equivalent to zero padding,
|
|
1348
|
+
# which will add high freq artifacts.
|
|
1349
|
+
base_freq *= rolloff
|
|
1350
|
+
|
|
1351
|
+
# The key idea of the algorithm is that x(t) can be exactly reconstructed from x[i] (tensor)
|
|
1352
|
+
# using the sinc interpolation formula:
|
|
1353
|
+
# x(t) = sum_i x[i] sinc(pi * orig_freq * (i / orig_freq - t))
|
|
1354
|
+
# We can then sample the function x(t) with a different sample rate:
|
|
1355
|
+
# y[j] = x(j / new_freq)
|
|
1356
|
+
# or,
|
|
1357
|
+
# y[j] = sum_i x[i] sinc(pi * orig_freq * (i / orig_freq - j / new_freq))
|
|
1358
|
+
|
|
1359
|
+
# We see here that y[j] is the convolution of x[i] with a specific filter, for which
|
|
1360
|
+
# we take an FIR approximation, stopping when we see at least `lowpass_filter_width` zeros crossing.
|
|
1361
|
+
# But y[j+1] is going to have a different set of weights and so on, until y[j + new_freq].
|
|
1362
|
+
# Indeed:
|
|
1363
|
+
# y[j + new_freq] = sum_i x[i] sinc(pi * orig_freq * ((i / orig_freq - (j + new_freq) / new_freq))
|
|
1364
|
+
# = sum_i x[i] sinc(pi * orig_freq * ((i - orig_freq) / orig_freq - j / new_freq))
|
|
1365
|
+
# = sum_i x[i + orig_freq] sinc(pi * orig_freq * (i / orig_freq - j / new_freq))
|
|
1366
|
+
# so y[j+new_freq] uses the same filter as y[j], but on a shifted version of x by `orig_freq`.
|
|
1367
|
+
# This will explain the F.conv1d after, with a stride of orig_freq.
|
|
1368
|
+
width = math.ceil(lowpass_filter_width * orig_freq / base_freq)
|
|
1369
|
+
# If orig_freq is still big after GCD reduction, most filters will be very unbalanced, i.e.,
|
|
1370
|
+
# they will have a lot of almost zero values to the left or to the right...
|
|
1371
|
+
# There is probably a way to evaluate those filters more efficiently, but this is kept for
|
|
1372
|
+
# future work.
|
|
1373
|
+
idx_dtype = dtype if dtype is not None else torch.float64
|
|
1374
|
+
|
|
1375
|
+
idx = torch.arange(-width, width + orig_freq, dtype=idx_dtype, device=device)[None, None] / orig_freq
|
|
1376
|
+
|
|
1377
|
+
t = torch.arange(0, -new_freq, -1, dtype=dtype, device=device)[:, None, None] / new_freq + idx
|
|
1378
|
+
t *= base_freq
|
|
1379
|
+
t = t.clamp_(-lowpass_filter_width, lowpass_filter_width)
|
|
1380
|
+
|
|
1381
|
+
# we do not use built in torch windows here as we need to evaluate the window
|
|
1382
|
+
# at specific positions, not over a regular grid.
|
|
1383
|
+
if resampling_method == "sinc_interp_hann":
|
|
1384
|
+
window = torch.cos(t * math.pi / lowpass_filter_width / 2) ** 2
|
|
1385
|
+
else:
|
|
1386
|
+
# sinc_interp_kaiser
|
|
1387
|
+
if beta is None:
|
|
1388
|
+
beta = 14.769656459379492
|
|
1389
|
+
beta_tensor = torch.tensor(float(beta))
|
|
1390
|
+
window = torch.i0(beta_tensor * torch.sqrt(1 - (t / lowpass_filter_width) ** 2)) / torch.i0(beta_tensor)
|
|
1391
|
+
|
|
1392
|
+
t *= math.pi
|
|
1393
|
+
|
|
1394
|
+
scale = base_freq / orig_freq
|
|
1395
|
+
kernels = torch.where(t == 0, torch.tensor(1.0).to(t), t.sin() / t)
|
|
1396
|
+
kernels *= window * scale
|
|
1397
|
+
|
|
1398
|
+
if dtype is None:
|
|
1399
|
+
kernels = kernels.to(dtype=torch.float32)
|
|
1400
|
+
|
|
1401
|
+
return kernels, width
|
|
1402
|
+
|
|
1403
|
+
|
|
1404
|
+
def _apply_sinc_resample_kernel(
|
|
1405
|
+
waveform: Tensor,
|
|
1406
|
+
orig_freq: int,
|
|
1407
|
+
new_freq: int,
|
|
1408
|
+
gcd: int,
|
|
1409
|
+
kernel: Tensor,
|
|
1410
|
+
width: int,
|
|
1411
|
+
):
|
|
1412
|
+
if not waveform.is_floating_point():
|
|
1413
|
+
raise TypeError(f"Expected floating point type for waveform tensor, but received {waveform.dtype}.")
|
|
1414
|
+
|
|
1415
|
+
orig_freq = int(orig_freq) // gcd
|
|
1416
|
+
new_freq = int(new_freq) // gcd
|
|
1417
|
+
|
|
1418
|
+
# pack batch
|
|
1419
|
+
shape = waveform.size()
|
|
1420
|
+
waveform = waveform.view(-1, shape[-1])
|
|
1421
|
+
|
|
1422
|
+
num_wavs, length = waveform.shape
|
|
1423
|
+
waveform = torch.nn.functional.pad(waveform, (width, width + orig_freq))
|
|
1424
|
+
resampled = torch.nn.functional.conv1d(waveform[:, None], kernel, stride=orig_freq)
|
|
1425
|
+
resampled = resampled.transpose(1, 2).reshape(num_wavs, -1)
|
|
1426
|
+
target_length = torch.ceil(torch.as_tensor(new_freq * length / orig_freq)).long()
|
|
1427
|
+
resampled = resampled[..., :target_length]
|
|
1428
|
+
|
|
1429
|
+
# unpack batch
|
|
1430
|
+
resampled = resampled.view(shape[:-1] + resampled.shape[-1:])
|
|
1431
|
+
return resampled
|
|
1432
|
+
|
|
1433
|
+
|
|
1434
|
+
def resample(
|
|
1435
|
+
waveform: Tensor,
|
|
1436
|
+
orig_freq: int,
|
|
1437
|
+
new_freq: int,
|
|
1438
|
+
lowpass_filter_width: int = 6,
|
|
1439
|
+
rolloff: float = 0.99,
|
|
1440
|
+
resampling_method: str = "sinc_interp_hann",
|
|
1441
|
+
beta: Optional[float] = None,
|
|
1442
|
+
) -> Tensor:
|
|
1443
|
+
r"""Resamples the waveform at the new frequency using bandlimited interpolation. :cite:`RESAMPLE`.
|
|
1444
|
+
|
|
1445
|
+
.. devices:: CPU CUDA
|
|
1446
|
+
|
|
1447
|
+
.. properties:: Autograd TorchScript
|
|
1448
|
+
|
|
1449
|
+
Note:
|
|
1450
|
+
``transforms.Resample`` precomputes and reuses the resampling kernel, so using it will result in
|
|
1451
|
+
more efficient computation if resampling multiple waveforms with the same resampling parameters.
|
|
1452
|
+
|
|
1453
|
+
Args:
|
|
1454
|
+
waveform (Tensor): The input signal of dimension `(..., time)`
|
|
1455
|
+
orig_freq (int): The original frequency of the signal
|
|
1456
|
+
new_freq (int): The desired frequency
|
|
1457
|
+
lowpass_filter_width (int, optional): Controls the sharpness of the filter, more == sharper
|
|
1458
|
+
but less efficient. (Default: ``6``)
|
|
1459
|
+
rolloff (float, optional): The roll-off frequency of the filter, as a fraction of the Nyquist.
|
|
1460
|
+
Lower values reduce anti-aliasing, but also reduce some of the highest frequencies. (Default: ``0.99``)
|
|
1461
|
+
resampling_method (str, optional): The resampling method to use.
|
|
1462
|
+
Options: [``"sinc_interp_hann"``, ``"sinc_interp_kaiser"``] (Default: ``"sinc_interp_hann"``)
|
|
1463
|
+
beta (float or None, optional): The shape parameter used for kaiser window.
|
|
1464
|
+
|
|
1465
|
+
Returns:
|
|
1466
|
+
Tensor: The waveform at the new frequency of dimension `(..., time).`
|
|
1467
|
+
"""
|
|
1468
|
+
|
|
1469
|
+
if orig_freq <= 0.0 or new_freq <= 0.0:
|
|
1470
|
+
raise ValueError("Original frequency and desired frequecy should be positive")
|
|
1471
|
+
|
|
1472
|
+
if orig_freq == new_freq:
|
|
1473
|
+
return waveform
|
|
1474
|
+
|
|
1475
|
+
gcd = math.gcd(int(orig_freq), int(new_freq))
|
|
1476
|
+
|
|
1477
|
+
kernel, width = _get_sinc_resample_kernel(
|
|
1478
|
+
orig_freq,
|
|
1479
|
+
new_freq,
|
|
1480
|
+
gcd,
|
|
1481
|
+
lowpass_filter_width,
|
|
1482
|
+
rolloff,
|
|
1483
|
+
resampling_method,
|
|
1484
|
+
beta,
|
|
1485
|
+
waveform.device,
|
|
1486
|
+
waveform.dtype,
|
|
1487
|
+
)
|
|
1488
|
+
resampled = _apply_sinc_resample_kernel(waveform, orig_freq, new_freq, gcd, kernel, width)
|
|
1489
|
+
return resampled
|
|
1490
|
+
|
|
1491
|
+
|
|
1492
|
+
@torch.jit.unused
|
|
1493
|
+
def edit_distance(seq1: Sequence, seq2: Sequence) -> int:
|
|
1494
|
+
"""
|
|
1495
|
+
Calculate the word level edit (Levenshtein) distance between two sequences.
|
|
1496
|
+
|
|
1497
|
+
.. devices:: CPU
|
|
1498
|
+
|
|
1499
|
+
The function computes an edit distance allowing deletion, insertion and
|
|
1500
|
+
substitution. The result is an integer.
|
|
1501
|
+
|
|
1502
|
+
For most applications, the two input sequences should be the same type. If
|
|
1503
|
+
two strings are given, the output is the edit distance between the two
|
|
1504
|
+
strings (character edit distance). If two lists of strings are given, the
|
|
1505
|
+
output is the edit distance between sentences (word edit distance). Users
|
|
1506
|
+
may want to normalize the output by the length of the reference sequence.
|
|
1507
|
+
|
|
1508
|
+
Args:
|
|
1509
|
+
seq1 (Sequence): the first sequence to compare.
|
|
1510
|
+
seq2 (Sequence): the second sequence to compare.
|
|
1511
|
+
Returns:
|
|
1512
|
+
int: The distance between the first and second sequences.
|
|
1513
|
+
"""
|
|
1514
|
+
len_sent2 = len(seq2)
|
|
1515
|
+
dold = list(range(len_sent2 + 1))
|
|
1516
|
+
dnew = [0 for _ in range(len_sent2 + 1)]
|
|
1517
|
+
|
|
1518
|
+
for i in range(1, len(seq1) + 1):
|
|
1519
|
+
dnew[0] = i
|
|
1520
|
+
for j in range(1, len_sent2 + 1):
|
|
1521
|
+
if seq1[i - 1] == seq2[j - 1]:
|
|
1522
|
+
dnew[j] = dold[j - 1]
|
|
1523
|
+
else:
|
|
1524
|
+
substitution = dold[j - 1] + 1
|
|
1525
|
+
insertion = dnew[j - 1] + 1
|
|
1526
|
+
deletion = dold[j] + 1
|
|
1527
|
+
dnew[j] = min(substitution, insertion, deletion)
|
|
1528
|
+
|
|
1529
|
+
dnew, dold = dold, dnew
|
|
1530
|
+
|
|
1531
|
+
return int(dold[-1])
|
|
1532
|
+
|
|
1533
|
+
|
|
1534
|
+
def loudness(waveform: Tensor, sample_rate: int):
|
|
1535
|
+
r"""Measure audio loudness according to the ITU-R BS.1770-4 recommendation.
|
|
1536
|
+
|
|
1537
|
+
.. devices:: CPU CUDA
|
|
1538
|
+
|
|
1539
|
+
.. properties:: TorchScript
|
|
1540
|
+
|
|
1541
|
+
Args:
|
|
1542
|
+
waveform(torch.Tensor): audio waveform of dimension `(..., channels, time)`
|
|
1543
|
+
sample_rate (int): sampling rate of the waveform
|
|
1544
|
+
|
|
1545
|
+
Returns:
|
|
1546
|
+
Tensor: loudness estimates (LKFS)
|
|
1547
|
+
|
|
1548
|
+
Reference:
|
|
1549
|
+
- https://www.itu.int/rec/R-REC-BS.1770-4-201510-I/en
|
|
1550
|
+
"""
|
|
1551
|
+
|
|
1552
|
+
if waveform.size(-2) > 5:
|
|
1553
|
+
raise ValueError("Only up to 5 channels are supported.")
|
|
1554
|
+
|
|
1555
|
+
gate_duration = 0.4
|
|
1556
|
+
overlap = 0.75
|
|
1557
|
+
gamma_abs = -70.0
|
|
1558
|
+
kweight_bias = -0.691
|
|
1559
|
+
gate_samples = int(round(gate_duration * sample_rate))
|
|
1560
|
+
step = int(round(gate_samples * (1 - overlap)))
|
|
1561
|
+
|
|
1562
|
+
# Apply K-weighting
|
|
1563
|
+
waveform = treble_biquad(waveform, sample_rate, 4.0, 1500.0, 1 / math.sqrt(2))
|
|
1564
|
+
waveform = highpass_biquad(waveform, sample_rate, 38.0, 0.5)
|
|
1565
|
+
|
|
1566
|
+
# Compute the energy for each block
|
|
1567
|
+
energy = torch.square(waveform).unfold(-1, gate_samples, step)
|
|
1568
|
+
energy = torch.mean(energy, dim=-1)
|
|
1569
|
+
|
|
1570
|
+
# Compute channel-weighted summation
|
|
1571
|
+
g = torch.tensor([1.0, 1.0, 1.0, 1.41, 1.41], dtype=waveform.dtype, device=waveform.device)
|
|
1572
|
+
g = g[: energy.size(-2)]
|
|
1573
|
+
|
|
1574
|
+
energy_weighted = torch.sum(g.unsqueeze(-1) * energy, dim=-2)
|
|
1575
|
+
loudness = -0.691 + 10 * torch.log10(energy_weighted)
|
|
1576
|
+
|
|
1577
|
+
# Apply absolute gating of the blocks
|
|
1578
|
+
gated_blocks = loudness > gamma_abs
|
|
1579
|
+
gated_blocks = gated_blocks.unsqueeze(-2)
|
|
1580
|
+
|
|
1581
|
+
energy_filtered = torch.sum(gated_blocks * energy, dim=-1) / torch.count_nonzero(gated_blocks, dim=-1)
|
|
1582
|
+
energy_weighted = torch.sum(g * energy_filtered, dim=-1)
|
|
1583
|
+
gamma_rel = kweight_bias + 10 * torch.log10(energy_weighted) - 10
|
|
1584
|
+
|
|
1585
|
+
# Apply relative gating of the blocks
|
|
1586
|
+
gated_blocks = torch.logical_and(gated_blocks.squeeze(-2), loudness > gamma_rel.unsqueeze(-1))
|
|
1587
|
+
gated_blocks = gated_blocks.unsqueeze(-2)
|
|
1588
|
+
|
|
1589
|
+
energy_filtered = torch.sum(gated_blocks * energy, dim=-1) / torch.count_nonzero(gated_blocks, dim=-1)
|
|
1590
|
+
energy_weighted = torch.sum(g * energy_filtered, dim=-1)
|
|
1591
|
+
LKFS = kweight_bias + 10 * torch.log10(energy_weighted)
|
|
1592
|
+
return LKFS
|
|
1593
|
+
|
|
1594
|
+
|
|
1595
|
+
def pitch_shift(
|
|
1596
|
+
waveform: Tensor,
|
|
1597
|
+
sample_rate: int,
|
|
1598
|
+
n_steps: int,
|
|
1599
|
+
bins_per_octave: int = 12,
|
|
1600
|
+
n_fft: int = 512,
|
|
1601
|
+
win_length: Optional[int] = None,
|
|
1602
|
+
hop_length: Optional[int] = None,
|
|
1603
|
+
window: Optional[Tensor] = None,
|
|
1604
|
+
) -> Tensor:
|
|
1605
|
+
"""
|
|
1606
|
+
Shift the pitch of a waveform by ``n_steps`` steps.
|
|
1607
|
+
|
|
1608
|
+
.. devices:: CPU CUDA
|
|
1609
|
+
|
|
1610
|
+
.. properties:: TorchScript
|
|
1611
|
+
|
|
1612
|
+
Args:
|
|
1613
|
+
waveform (Tensor): The input waveform of shape `(..., time)`.
|
|
1614
|
+
sample_rate (int): Sample rate of `waveform`.
|
|
1615
|
+
n_steps (int): The (fractional) steps to shift `waveform`.
|
|
1616
|
+
bins_per_octave (int, optional): The number of steps per octave (Default: ``12``).
|
|
1617
|
+
n_fft (int, optional): Size of FFT, creates ``n_fft // 2 + 1`` bins (Default: ``512``).
|
|
1618
|
+
win_length (int or None, optional): Window size. If None, then ``n_fft`` is used. (Default: ``None``).
|
|
1619
|
+
hop_length (int or None, optional): Length of hop between STFT windows. If None, then
|
|
1620
|
+
``win_length // 4`` is used (Default: ``None``).
|
|
1621
|
+
window (Tensor or None, optional): Window tensor that is applied/multiplied to each frame/window.
|
|
1622
|
+
If None, then ``torch.hann_window(win_length)`` is used (Default: ``None``).
|
|
1623
|
+
|
|
1624
|
+
|
|
1625
|
+
Returns:
|
|
1626
|
+
Tensor: The pitch-shifted audio waveform of shape `(..., time)`.
|
|
1627
|
+
"""
|
|
1628
|
+
waveform_stretch = _stretch_waveform(
|
|
1629
|
+
waveform,
|
|
1630
|
+
n_steps,
|
|
1631
|
+
bins_per_octave,
|
|
1632
|
+
n_fft,
|
|
1633
|
+
win_length,
|
|
1634
|
+
hop_length,
|
|
1635
|
+
window,
|
|
1636
|
+
)
|
|
1637
|
+
rate = 2.0 ** (-float(n_steps) / bins_per_octave)
|
|
1638
|
+
waveform_shift = resample(waveform_stretch, int(sample_rate / rate), sample_rate)
|
|
1639
|
+
|
|
1640
|
+
return _fix_waveform_shape(waveform_shift, waveform.size())
|
|
1641
|
+
|
|
1642
|
+
|
|
1643
|
+
def _stretch_waveform(
|
|
1644
|
+
waveform: Tensor,
|
|
1645
|
+
n_steps: int,
|
|
1646
|
+
bins_per_octave: int = 12,
|
|
1647
|
+
n_fft: int = 512,
|
|
1648
|
+
win_length: Optional[int] = None,
|
|
1649
|
+
hop_length: Optional[int] = None,
|
|
1650
|
+
window: Optional[Tensor] = None,
|
|
1651
|
+
) -> Tensor:
|
|
1652
|
+
"""
|
|
1653
|
+
Pitch shift helper function to preprocess and stretch waveform before resampling step.
|
|
1654
|
+
|
|
1655
|
+
Args:
|
|
1656
|
+
See pitch_shift arg descriptions.
|
|
1657
|
+
|
|
1658
|
+
Returns:
|
|
1659
|
+
Tensor: The preprocessed waveform stretched prior to resampling.
|
|
1660
|
+
"""
|
|
1661
|
+
if hop_length is None:
|
|
1662
|
+
hop_length = n_fft // 4
|
|
1663
|
+
if win_length is None:
|
|
1664
|
+
win_length = n_fft
|
|
1665
|
+
if window is None:
|
|
1666
|
+
window = torch.hann_window(window_length=win_length, device=waveform.device)
|
|
1667
|
+
|
|
1668
|
+
# pack batch
|
|
1669
|
+
shape = waveform.size()
|
|
1670
|
+
waveform = waveform.reshape(-1, shape[-1])
|
|
1671
|
+
|
|
1672
|
+
ori_len = shape[-1]
|
|
1673
|
+
rate = 2.0 ** (-float(n_steps) / bins_per_octave)
|
|
1674
|
+
spec_f = torch.stft(
|
|
1675
|
+
input=waveform,
|
|
1676
|
+
n_fft=n_fft,
|
|
1677
|
+
hop_length=hop_length,
|
|
1678
|
+
win_length=win_length,
|
|
1679
|
+
window=window,
|
|
1680
|
+
center=True,
|
|
1681
|
+
pad_mode="reflect",
|
|
1682
|
+
normalized=False,
|
|
1683
|
+
onesided=True,
|
|
1684
|
+
return_complex=True,
|
|
1685
|
+
)
|
|
1686
|
+
phase_advance = torch.linspace(0, math.pi * hop_length, spec_f.shape[-2], device=spec_f.device)[..., None]
|
|
1687
|
+
spec_stretch = phase_vocoder(spec_f, rate, phase_advance)
|
|
1688
|
+
len_stretch = int(round(ori_len / rate))
|
|
1689
|
+
waveform_stretch = torch.istft(
|
|
1690
|
+
spec_stretch, n_fft=n_fft, hop_length=hop_length, win_length=win_length, window=window, length=len_stretch
|
|
1691
|
+
)
|
|
1692
|
+
return waveform_stretch
|
|
1693
|
+
|
|
1694
|
+
|
|
1695
|
+
def _fix_waveform_shape(
|
|
1696
|
+
waveform_shift: Tensor,
|
|
1697
|
+
shape: List[int],
|
|
1698
|
+
) -> Tensor:
|
|
1699
|
+
"""
|
|
1700
|
+
PitchShift helper function to process after resampling step to fix the shape back.
|
|
1701
|
+
|
|
1702
|
+
Args:
|
|
1703
|
+
waveform_shift(Tensor): The waveform after stretch and resample
|
|
1704
|
+
shape (List[int]): The shape of initial waveform
|
|
1705
|
+
|
|
1706
|
+
Returns:
|
|
1707
|
+
Tensor: The pitch-shifted audio waveform of shape `(..., time)`.
|
|
1708
|
+
"""
|
|
1709
|
+
ori_len = shape[-1]
|
|
1710
|
+
shift_len = waveform_shift.size()[-1]
|
|
1711
|
+
if shift_len > ori_len:
|
|
1712
|
+
waveform_shift = waveform_shift[..., :ori_len]
|
|
1713
|
+
else:
|
|
1714
|
+
waveform_shift = torch.nn.functional.pad(waveform_shift, [0, ori_len - shift_len])
|
|
1715
|
+
|
|
1716
|
+
# unpack batch
|
|
1717
|
+
waveform_shift = waveform_shift.view(shape[:-1] + waveform_shift.shape[-1:])
|
|
1718
|
+
return waveform_shift
|
|
1719
|
+
|
|
1720
|
+
|
|
1721
|
+
class RnntLoss(torch.autograd.Function):
|
|
1722
|
+
@staticmethod
|
|
1723
|
+
def forward(ctx, *args):
|
|
1724
|
+
output, saved = torch.ops.torchaudio.rnnt_loss_forward(*args)
|
|
1725
|
+
ctx.save_for_backward(saved)
|
|
1726
|
+
return output
|
|
1727
|
+
|
|
1728
|
+
@staticmethod
|
|
1729
|
+
def backward(ctx, dy):
|
|
1730
|
+
grad = ctx.saved_tensors[0]
|
|
1731
|
+
grad_out = dy.view((-1, 1, 1, 1))
|
|
1732
|
+
result = grad * grad_out
|
|
1733
|
+
return (result, None, None, None, None, None, None, None)
|
|
1734
|
+
|
|
1735
|
+
|
|
1736
|
+
def _rnnt_loss(
|
|
1737
|
+
logits: Tensor,
|
|
1738
|
+
targets: Tensor,
|
|
1739
|
+
logit_lengths: Tensor,
|
|
1740
|
+
target_lengths: Tensor,
|
|
1741
|
+
blank: int = -1,
|
|
1742
|
+
clamp: float = -1,
|
|
1743
|
+
reduction: str = "mean",
|
|
1744
|
+
fused_log_softmax: bool = True,
|
|
1745
|
+
):
|
|
1746
|
+
"""Compute the RNN Transducer loss from *Sequence Transduction with Recurrent Neural Networks*
|
|
1747
|
+
:cite:`graves2012sequence`.
|
|
1748
|
+
|
|
1749
|
+
.. devices:: CPU CUDA
|
|
1750
|
+
|
|
1751
|
+
.. properties:: Autograd TorchScript
|
|
1752
|
+
|
|
1753
|
+
The RNN Transducer loss extends the CTC loss by defining a distribution over output
|
|
1754
|
+
sequences of all lengths, and by jointly modelling both input-output and output-output
|
|
1755
|
+
dependencies.
|
|
1756
|
+
|
|
1757
|
+
Args:
|
|
1758
|
+
logits (Tensor): Tensor of dimension `(batch, max seq length, max target length + 1, class)`
|
|
1759
|
+
containing output from joiner
|
|
1760
|
+
targets (Tensor): Tensor of dimension `(batch, max target length)` containing targets with zero padded
|
|
1761
|
+
logit_lengths (Tensor): Tensor of dimension `(batch)` containing lengths of each sequence from encoder
|
|
1762
|
+
target_lengths (Tensor): Tensor of dimension `(batch)` containing lengths of targets for each sequence
|
|
1763
|
+
blank (int, optional): blank label (Default: ``-1``)
|
|
1764
|
+
clamp (float, optional): clamp for gradients (Default: ``-1``)
|
|
1765
|
+
reduction (string, optional): Specifies the reduction to apply to the output:
|
|
1766
|
+
``"none"`` | ``"mean"`` | ``"sum"``. (Default: ``"mean"``)
|
|
1767
|
+
fused_log_softmax (bool): set to False if calling log_softmax outside of loss (Default: ``True``)
|
|
1768
|
+
Returns:
|
|
1769
|
+
Tensor: Loss with the reduction option applied. If ``reduction`` is ``"none"``, then size `(batch)`,
|
|
1770
|
+
otherwise scalar.
|
|
1771
|
+
"""
|
|
1772
|
+
if reduction not in ["none", "mean", "sum"]:
|
|
1773
|
+
raise ValueError('reduction should be one of "none", "mean", or "sum"')
|
|
1774
|
+
|
|
1775
|
+
if blank < 0: # reinterpret blank index if blank < 0.
|
|
1776
|
+
blank = logits.shape[-1] + blank
|
|
1777
|
+
|
|
1778
|
+
costs = RnntLoss.apply(logits, targets, logit_lengths, target_lengths, blank, clamp, fused_log_softmax)
|
|
1779
|
+
|
|
1780
|
+
if reduction == "mean":
|
|
1781
|
+
return costs.mean()
|
|
1782
|
+
elif reduction == "sum":
|
|
1783
|
+
return costs.sum()
|
|
1784
|
+
|
|
1785
|
+
return costs
|
|
1786
|
+
|
|
1787
|
+
|
|
1788
|
+
def psd(
|
|
1789
|
+
specgram: Tensor,
|
|
1790
|
+
mask: Optional[Tensor] = None,
|
|
1791
|
+
normalize: bool = True,
|
|
1792
|
+
eps: float = 1e-10,
|
|
1793
|
+
) -> Tensor:
|
|
1794
|
+
"""Compute cross-channel power spectral density (PSD) matrix.
|
|
1795
|
+
|
|
1796
|
+
.. devices:: CPU CUDA
|
|
1797
|
+
|
|
1798
|
+
.. properties:: Autograd TorchScript
|
|
1799
|
+
|
|
1800
|
+
Args:
|
|
1801
|
+
specgram (torch.Tensor): Multi-channel complex-valued spectrum.
|
|
1802
|
+
Tensor with dimensions `(..., channel, freq, time)`.
|
|
1803
|
+
mask (torch.Tensor or None, optional): Time-Frequency mask for normalization.
|
|
1804
|
+
Tensor with dimensions `(..., freq, time)`. (Default: ``None``)
|
|
1805
|
+
normalize (bool, optional): If ``True``, normalize the mask along the time dimension. (Default: ``True``)
|
|
1806
|
+
eps (float, optional): Value to add to the denominator in mask normalization. (Default: ``1e-15``)
|
|
1807
|
+
|
|
1808
|
+
Returns:
|
|
1809
|
+
torch.Tensor: The complex-valued PSD matrix of the input spectrum.
|
|
1810
|
+
Tensor with dimensions `(..., freq, channel, channel)`
|
|
1811
|
+
"""
|
|
1812
|
+
specgram = specgram.transpose(-3, -2) # shape (freq, channel, time)
|
|
1813
|
+
# outer product:
|
|
1814
|
+
# (..., ch_1, time) x (..., ch_2, time) -> (..., time, ch_1, ch_2)
|
|
1815
|
+
psd = torch.einsum("...ct,...et->...tce", [specgram, specgram.conj()])
|
|
1816
|
+
|
|
1817
|
+
if mask is not None:
|
|
1818
|
+
if mask.shape[:-1] != specgram.shape[:-2] or mask.shape[-1] != specgram.shape[-1]:
|
|
1819
|
+
raise ValueError(
|
|
1820
|
+
"The dimensions of mask except the channel dimension should be the same as specgram."
|
|
1821
|
+
f"Found {mask.shape} for mask and {specgram.shape} for specgram."
|
|
1822
|
+
)
|
|
1823
|
+
# Normalized mask along time dimension:
|
|
1824
|
+
if normalize:
|
|
1825
|
+
mask = mask / (mask.sum(dim=-1, keepdim=True) + eps)
|
|
1826
|
+
|
|
1827
|
+
psd = psd * mask[..., None, None]
|
|
1828
|
+
|
|
1829
|
+
psd = psd.sum(dim=-3)
|
|
1830
|
+
return psd
|
|
1831
|
+
|
|
1832
|
+
|
|
1833
|
+
# Expose both deprecated wrapper as well as original because torchscript breaks on
|
|
1834
|
+
# wrapped functions.
|
|
1835
|
+
rnnt_loss = dropping_support(_rnnt_loss)
|
|
1836
|
+
|
|
1837
|
+
|
|
1838
|
+
def _compute_mat_trace(input: torch.Tensor, dim1: int = -1, dim2: int = -2) -> torch.Tensor:
|
|
1839
|
+
r"""Compute the trace of a Tensor along ``dim1`` and ``dim2`` dimensions.
|
|
1840
|
+
|
|
1841
|
+
Args:
|
|
1842
|
+
input (torch.Tensor): Tensor with dimensions `(..., channel, channel)`.
|
|
1843
|
+
dim1 (int, optional): The first dimension of the diagonal matrix.
|
|
1844
|
+
(Default: ``-1``)
|
|
1845
|
+
dim2 (int, optional): The second dimension of the diagonal matrix.
|
|
1846
|
+
(Default: ``-2``)
|
|
1847
|
+
|
|
1848
|
+
Returns:
|
|
1849
|
+
Tensor: The trace of the input Tensor.
|
|
1850
|
+
"""
|
|
1851
|
+
if input.ndim < 2:
|
|
1852
|
+
raise ValueError("The dimension of the tensor must be at least 2.")
|
|
1853
|
+
if input.shape[dim1] != input.shape[dim2]:
|
|
1854
|
+
raise ValueError("The size of ``dim1`` and ``dim2`` must be the same.")
|
|
1855
|
+
input = torch.diagonal(input, 0, dim1=dim1, dim2=dim2)
|
|
1856
|
+
return input.sum(dim=-1)
|
|
1857
|
+
|
|
1858
|
+
|
|
1859
|
+
def _tik_reg(mat: torch.Tensor, reg: float = 1e-7, eps: float = 1e-8) -> torch.Tensor:
|
|
1860
|
+
"""Perform Tikhonov regularization (only modifying real part).
|
|
1861
|
+
|
|
1862
|
+
Args:
|
|
1863
|
+
mat (torch.Tensor): Input matrix with dimensions `(..., channel, channel)`.
|
|
1864
|
+
reg (float, optional): Regularization factor. (Default: 1e-8)
|
|
1865
|
+
eps (float, optional): Value to avoid the correlation matrix is all-zero. (Default: ``1e-8``)
|
|
1866
|
+
|
|
1867
|
+
Returns:
|
|
1868
|
+
Tensor: Regularized matrix with dimensions `(..., channel, channel)`.
|
|
1869
|
+
"""
|
|
1870
|
+
# Add eps
|
|
1871
|
+
C = mat.size(-1)
|
|
1872
|
+
eye = torch.eye(C, dtype=mat.dtype, device=mat.device)
|
|
1873
|
+
epsilon = _compute_mat_trace(mat).real[..., None, None] * reg
|
|
1874
|
+
# in case that correlation_matrix is all-zero
|
|
1875
|
+
epsilon = epsilon + eps
|
|
1876
|
+
mat = mat + epsilon * eye[..., :, :]
|
|
1877
|
+
return mat
|
|
1878
|
+
|
|
1879
|
+
|
|
1880
|
+
def _assert_psd_matrices(psd_s: torch.Tensor, psd_n: torch.Tensor) -> None:
|
|
1881
|
+
"""Assertion checks of the PSD matrices of target speech and noise.
|
|
1882
|
+
|
|
1883
|
+
Args:
|
|
1884
|
+
psd_s (torch.Tensor): The complex-valued power spectral density (PSD) matrix of target speech.
|
|
1885
|
+
Tensor with dimensions `(..., freq, channel, channel)`.
|
|
1886
|
+
psd_n (torch.Tensor): The complex-valued power spectral density (PSD) matrix of noise.
|
|
1887
|
+
Tensor with dimensions `(..., freq, channel, channel)`.
|
|
1888
|
+
"""
|
|
1889
|
+
if psd_s.ndim < 3 or psd_n.ndim < 3:
|
|
1890
|
+
raise ValueError(
|
|
1891
|
+
"Expected at least 3D Tensor (..., freq, channel, channel) for psd_s and psd_n. "
|
|
1892
|
+
f"Found {psd_s.shape} for psd_s and {psd_n.shape} for psd_n."
|
|
1893
|
+
)
|
|
1894
|
+
if not (psd_s.is_complex() and psd_n.is_complex()):
|
|
1895
|
+
raise TypeError(
|
|
1896
|
+
"The type of psd_s and psd_n must be ``torch.cfloat`` or ``torch.cdouble``. "
|
|
1897
|
+
f"Found {psd_s.dtype} for psd_s and {psd_n.dtype} for psd_n."
|
|
1898
|
+
)
|
|
1899
|
+
if psd_s.shape != psd_n.shape:
|
|
1900
|
+
raise ValueError(
|
|
1901
|
+
f"The dimensions of psd_s and psd_n should be the same. Found {psd_s.shape} and {psd_n.shape}."
|
|
1902
|
+
)
|
|
1903
|
+
if psd_s.shape[-1] != psd_s.shape[-2]:
|
|
1904
|
+
raise ValueError(f"The last two dimensions of psd_s should be the same. Found {psd_s.shape}.")
|
|
1905
|
+
|
|
1906
|
+
|
|
1907
|
+
def mvdr_weights_souden(
|
|
1908
|
+
psd_s: Tensor,
|
|
1909
|
+
psd_n: Tensor,
|
|
1910
|
+
reference_channel: Union[int, Tensor],
|
|
1911
|
+
diagonal_loading: bool = True,
|
|
1912
|
+
diag_eps: float = 1e-7,
|
|
1913
|
+
eps: float = 1e-8,
|
|
1914
|
+
) -> Tensor:
|
|
1915
|
+
r"""Compute the Minimum Variance Distortionless Response (*MVDR* :cite:`capon1969high`) beamforming weights
|
|
1916
|
+
by the method proposed by *Souden et, al.* :cite:`souden2009optimal`.
|
|
1917
|
+
|
|
1918
|
+
.. devices:: CPU CUDA
|
|
1919
|
+
|
|
1920
|
+
.. properties:: Autograd TorchScript
|
|
1921
|
+
|
|
1922
|
+
Given the power spectral density (PSD) matrix of target speech :math:`\bf{\Phi}_{\textbf{SS}}`,
|
|
1923
|
+
the PSD matrix of noise :math:`\bf{\Phi}_{\textbf{NN}}`, and a one-hot vector that represents the
|
|
1924
|
+
reference channel :math:`\bf{u}`, the method computes the MVDR beamforming weight martrix
|
|
1925
|
+
:math:`\textbf{w}_{\text{MVDR}}`. The formula is defined as:
|
|
1926
|
+
|
|
1927
|
+
.. math::
|
|
1928
|
+
\textbf{w}_{\text{MVDR}}(f) =
|
|
1929
|
+
\frac{{{\bf{\Phi}_{\textbf{NN}}^{-1}}(f){\bf{\Phi}_{\textbf{SS}}}}(f)}
|
|
1930
|
+
{\text{Trace}({{{\bf{\Phi}_{\textbf{NN}}^{-1}}(f) \bf{\Phi}_{\textbf{SS}}}(f))}}\bm{u}
|
|
1931
|
+
|
|
1932
|
+
Args:
|
|
1933
|
+
psd_s (torch.Tensor): The complex-valued power spectral density (PSD) matrix of target speech.
|
|
1934
|
+
Tensor with dimensions `(..., freq, channel, channel)`.
|
|
1935
|
+
psd_n (torch.Tensor): The complex-valued power spectral density (PSD) matrix of noise.
|
|
1936
|
+
Tensor with dimensions `(..., freq, channel, channel)`.
|
|
1937
|
+
reference_channel (int or torch.Tensor): Specifies the reference channel.
|
|
1938
|
+
If the dtype is ``int``, it represents the reference channel index.
|
|
1939
|
+
If the dtype is ``torch.Tensor``, its shape is `(..., channel)`, where the ``channel`` dimension
|
|
1940
|
+
is one-hot.
|
|
1941
|
+
diagonal_loading (bool, optional): If ``True``, enables applying diagonal loading to ``psd_n``.
|
|
1942
|
+
(Default: ``True``)
|
|
1943
|
+
diag_eps (float, optional): The coefficient multiplied to the identity matrix for diagonal loading.
|
|
1944
|
+
It is only effective when ``diagonal_loading`` is set to ``True``. (Default: ``1e-7``)
|
|
1945
|
+
eps (float, optional): Value to add to the denominator in the beamforming weight formula.
|
|
1946
|
+
(Default: ``1e-8``)
|
|
1947
|
+
|
|
1948
|
+
Returns:
|
|
1949
|
+
torch.Tensor: The complex-valued MVDR beamforming weight matrix with dimensions `(..., freq, channel)`.
|
|
1950
|
+
"""
|
|
1951
|
+
_assert_psd_matrices(psd_s, psd_n)
|
|
1952
|
+
|
|
1953
|
+
if diagonal_loading:
|
|
1954
|
+
psd_n = _tik_reg(psd_n, reg=diag_eps)
|
|
1955
|
+
numerator = torch.linalg.solve(psd_n, psd_s) # psd_n.inv() @ psd_s
|
|
1956
|
+
# ws: (..., C, C) / (...,) -> (..., C, C)
|
|
1957
|
+
ws = numerator / (_compute_mat_trace(numerator)[..., None, None] + eps)
|
|
1958
|
+
if torch.jit.isinstance(reference_channel, int):
|
|
1959
|
+
beamform_weights = ws[..., :, reference_channel]
|
|
1960
|
+
elif torch.jit.isinstance(reference_channel, Tensor):
|
|
1961
|
+
reference_channel = reference_channel.to(psd_n.dtype)
|
|
1962
|
+
# h: (..., F, C_1, C_2) x (..., C_2) -> (..., F, C_1)
|
|
1963
|
+
beamform_weights = torch.einsum("...c,...c->...", [ws, reference_channel[..., None, None, :]])
|
|
1964
|
+
else:
|
|
1965
|
+
raise TypeError(f'Expected "int" or "Tensor" for reference_channel. Found: {type(reference_channel)}.')
|
|
1966
|
+
|
|
1967
|
+
return beamform_weights
|
|
1968
|
+
|
|
1969
|
+
|
|
1970
|
+
def mvdr_weights_rtf(
|
|
1971
|
+
rtf: Tensor,
|
|
1972
|
+
psd_n: Tensor,
|
|
1973
|
+
reference_channel: Optional[Union[int, Tensor]] = None,
|
|
1974
|
+
diagonal_loading: bool = True,
|
|
1975
|
+
diag_eps: float = 1e-7,
|
|
1976
|
+
eps: float = 1e-8,
|
|
1977
|
+
) -> Tensor:
|
|
1978
|
+
r"""Compute the Minimum Variance Distortionless Response (*MVDR* :cite:`capon1969high`) beamforming weights
|
|
1979
|
+
based on the relative transfer function (RTF) and power spectral density (PSD) matrix of noise.
|
|
1980
|
+
|
|
1981
|
+
.. devices:: CPU CUDA
|
|
1982
|
+
|
|
1983
|
+
.. properties:: Autograd TorchScript
|
|
1984
|
+
|
|
1985
|
+
Given the relative transfer function (RTF) matrix or the steering vector of target speech :math:`\bm{v}`,
|
|
1986
|
+
the PSD matrix of noise :math:`\bf{\Phi}_{\textbf{NN}}`, and a one-hot vector that represents the
|
|
1987
|
+
reference channel :math:`\bf{u}`, the method computes the MVDR beamforming weight martrix
|
|
1988
|
+
:math:`\textbf{w}_{\text{MVDR}}`. The formula is defined as:
|
|
1989
|
+
|
|
1990
|
+
.. math::
|
|
1991
|
+
\textbf{w}_{\text{MVDR}}(f) =
|
|
1992
|
+
\frac{{{\bf{\Phi}_{\textbf{NN}}^{-1}}(f){\bm{v}}(f)}}
|
|
1993
|
+
{{\bm{v}^{\mathsf{H}}}(f){\bf{\Phi}_{\textbf{NN}}^{-1}}(f){\bm{v}}(f)}
|
|
1994
|
+
|
|
1995
|
+
where :math:`(.)^{\mathsf{H}}` denotes the Hermitian Conjugate operation.
|
|
1996
|
+
|
|
1997
|
+
Args:
|
|
1998
|
+
rtf (torch.Tensor): The complex-valued RTF vector of target speech.
|
|
1999
|
+
Tensor with dimensions `(..., freq, channel)`.
|
|
2000
|
+
psd_n (torch.Tensor): The complex-valued power spectral density (PSD) matrix of noise.
|
|
2001
|
+
Tensor with dimensions `(..., freq, channel, channel)`.
|
|
2002
|
+
reference_channel (int or torch.Tensor): Specifies the reference channel.
|
|
2003
|
+
If the dtype is ``int``, it represents the reference channel index.
|
|
2004
|
+
If the dtype is ``torch.Tensor``, its shape is `(..., channel)`, where the ``channel`` dimension
|
|
2005
|
+
is one-hot.
|
|
2006
|
+
diagonal_loading (bool, optional): If ``True``, enables applying diagonal loading to ``psd_n``.
|
|
2007
|
+
(Default: ``True``)
|
|
2008
|
+
diag_eps (float, optional): The coefficient multiplied to the identity matrix for diagonal loading.
|
|
2009
|
+
It is only effective when ``diagonal_loading`` is set to ``True``. (Default: ``1e-7``)
|
|
2010
|
+
eps (float, optional): Value to add to the denominator in the beamforming weight formula.
|
|
2011
|
+
(Default: ``1e-8``)
|
|
2012
|
+
|
|
2013
|
+
Returns:
|
|
2014
|
+
torch.Tensor: The complex-valued MVDR beamforming weight matrix with dimensions `(..., freq, channel)`.
|
|
2015
|
+
"""
|
|
2016
|
+
if rtf.ndim < 2:
|
|
2017
|
+
raise ValueError(f"Expected at least 2D Tensor (..., freq, channel) for rtf. Found {rtf.shape}.")
|
|
2018
|
+
if psd_n.ndim < 3:
|
|
2019
|
+
raise ValueError(f"Expected at least 3D Tensor (..., freq, channel, channel) for psd_n. Found {psd_n.shape}.")
|
|
2020
|
+
if not (rtf.is_complex() and psd_n.is_complex()):
|
|
2021
|
+
raise TypeError(
|
|
2022
|
+
"The type of rtf and psd_n must be ``torch.cfloat`` or ``torch.cdouble``. "
|
|
2023
|
+
f"Found {rtf.dtype} for rtf and {psd_n.dtype} for psd_n."
|
|
2024
|
+
)
|
|
2025
|
+
if rtf.shape != psd_n.shape[:-1]:
|
|
2026
|
+
raise ValueError(
|
|
2027
|
+
"The dimensions of rtf and the dimensions withou the last dimension of psd_n should be the same. "
|
|
2028
|
+
f"Found {rtf.shape} for rtf and {psd_n.shape} for psd_n."
|
|
2029
|
+
)
|
|
2030
|
+
if psd_n.shape[-1] != psd_n.shape[-2]:
|
|
2031
|
+
raise ValueError(f"The last two dimensions of psd_n should be the same. Found {psd_n.shape}.")
|
|
2032
|
+
|
|
2033
|
+
if diagonal_loading:
|
|
2034
|
+
psd_n = _tik_reg(psd_n, reg=diag_eps)
|
|
2035
|
+
# numerator = psd_n.inv() @ stv
|
|
2036
|
+
numerator = torch.linalg.solve(psd_n, rtf.unsqueeze(-1)).squeeze(-1) # (..., freq, channel)
|
|
2037
|
+
# denominator = stv^H @ psd_n.inv() @ stv
|
|
2038
|
+
denominator = torch.einsum("...d,...d->...", [rtf.conj(), numerator])
|
|
2039
|
+
beamform_weights = numerator / (denominator.real.unsqueeze(-1) + eps)
|
|
2040
|
+
# normalize the numerator
|
|
2041
|
+
if reference_channel is not None:
|
|
2042
|
+
if torch.jit.isinstance(reference_channel, int):
|
|
2043
|
+
scale = rtf[..., reference_channel].conj()
|
|
2044
|
+
elif torch.jit.isinstance(reference_channel, Tensor):
|
|
2045
|
+
reference_channel = reference_channel.to(psd_n.dtype)
|
|
2046
|
+
scale = torch.einsum("...c,...c->...", [rtf.conj(), reference_channel[..., None, :]])
|
|
2047
|
+
else:
|
|
2048
|
+
raise TypeError(f'Expected "int" or "Tensor" for reference_channel. Found: {type(reference_channel)}.')
|
|
2049
|
+
|
|
2050
|
+
beamform_weights = beamform_weights * scale[..., None]
|
|
2051
|
+
|
|
2052
|
+
return beamform_weights
|
|
2053
|
+
|
|
2054
|
+
|
|
2055
|
+
def rtf_evd(psd_s: Tensor) -> Tensor:
|
|
2056
|
+
r"""Estimate the relative transfer function (RTF) or the steering vector by eigenvalue decomposition.
|
|
2057
|
+
|
|
2058
|
+
.. devices:: CPU CUDA
|
|
2059
|
+
|
|
2060
|
+
.. properties:: TorchScript
|
|
2061
|
+
|
|
2062
|
+
Args:
|
|
2063
|
+
psd_s (Tensor): The complex-valued power spectral density (PSD) matrix of target speech.
|
|
2064
|
+
Tensor of dimension `(..., freq, channel, channel)`
|
|
2065
|
+
|
|
2066
|
+
Returns:
|
|
2067
|
+
Tensor: The estimated complex-valued RTF of target speech.
|
|
2068
|
+
Tensor of dimension `(..., freq, channel)`
|
|
2069
|
+
"""
|
|
2070
|
+
if not psd_s.is_complex():
|
|
2071
|
+
raise TypeError(f"The type of psd_s must be ``torch.cfloat`` or ``torch.cdouble``. Found {psd_s.dtype}.")
|
|
2072
|
+
if psd_s.shape[-1] != psd_s.shape[-2]:
|
|
2073
|
+
raise ValueError(f"The last two dimensions of psd_s should be the same. Found {psd_s.shape}.")
|
|
2074
|
+
_, v = torch.linalg.eigh(psd_s) # v is sorted along with eigenvalues in ascending order
|
|
2075
|
+
rtf = v[..., -1] # choose the eigenvector with max eigenvalue
|
|
2076
|
+
return rtf
|
|
2077
|
+
|
|
2078
|
+
|
|
2079
|
+
def rtf_power(
|
|
2080
|
+
psd_s: Tensor,
|
|
2081
|
+
psd_n: Tensor,
|
|
2082
|
+
reference_channel: Union[int, Tensor],
|
|
2083
|
+
n_iter: int = 3,
|
|
2084
|
+
diagonal_loading: bool = True,
|
|
2085
|
+
diag_eps: float = 1e-7,
|
|
2086
|
+
) -> Tensor:
|
|
2087
|
+
r"""Estimate the relative transfer function (RTF) or the steering vector by the power method.
|
|
2088
|
+
|
|
2089
|
+
.. devices:: CPU CUDA
|
|
2090
|
+
|
|
2091
|
+
.. properties:: Autograd TorchScript
|
|
2092
|
+
|
|
2093
|
+
Args:
|
|
2094
|
+
psd_s (torch.Tensor): The complex-valued power spectral density (PSD) matrix of target speech.
|
|
2095
|
+
Tensor with dimensions `(..., freq, channel, channel)`.
|
|
2096
|
+
psd_n (torch.Tensor): The complex-valued power spectral density (PSD) matrix of noise.
|
|
2097
|
+
Tensor with dimensions `(..., freq, channel, channel)`.
|
|
2098
|
+
reference_channel (int or torch.Tensor): Specifies the reference channel.
|
|
2099
|
+
If the dtype is ``int``, it represents the reference channel index.
|
|
2100
|
+
If the dtype is ``torch.Tensor``, its shape is `(..., channel)`, where the ``channel`` dimension
|
|
2101
|
+
is one-hot.
|
|
2102
|
+
diagonal_loading (bool, optional): If ``True``, enables applying diagonal loading to ``psd_n``.
|
|
2103
|
+
(Default: ``True``)
|
|
2104
|
+
diag_eps (float, optional): The coefficient multiplied to the identity matrix for diagonal loading.
|
|
2105
|
+
It is only effective when ``diagonal_loading`` is set to ``True``. (Default: ``1e-7``)
|
|
2106
|
+
|
|
2107
|
+
Returns:
|
|
2108
|
+
torch.Tensor: The estimated complex-valued RTF of target speech.
|
|
2109
|
+
Tensor of dimension `(..., freq, channel)`.
|
|
2110
|
+
"""
|
|
2111
|
+
_assert_psd_matrices(psd_s, psd_n)
|
|
2112
|
+
if n_iter <= 0:
|
|
2113
|
+
raise ValueError("The number of iteration must be greater than 0.")
|
|
2114
|
+
|
|
2115
|
+
# Apply diagonal loading to psd_n to improve robustness.
|
|
2116
|
+
if diagonal_loading:
|
|
2117
|
+
psd_n = _tik_reg(psd_n, reg=diag_eps)
|
|
2118
|
+
# phi is regarded as the first iteration
|
|
2119
|
+
phi = torch.linalg.solve(psd_n, psd_s) # psd_n.inv() @ psd_s
|
|
2120
|
+
if torch.jit.isinstance(reference_channel, int):
|
|
2121
|
+
rtf = phi[..., reference_channel]
|
|
2122
|
+
elif torch.jit.isinstance(reference_channel, Tensor):
|
|
2123
|
+
reference_channel = reference_channel.to(psd_n.dtype)
|
|
2124
|
+
rtf = torch.einsum("...c,...c->...", [phi, reference_channel[..., None, None, :]])
|
|
2125
|
+
else:
|
|
2126
|
+
raise TypeError(f'Expected "int" or "Tensor" for reference_channel. Found: {type(reference_channel)}.')
|
|
2127
|
+
rtf = rtf.unsqueeze(-1) # (..., freq, channel, 1)
|
|
2128
|
+
if n_iter >= 2:
|
|
2129
|
+
# The number of iterations in the for loop is `n_iter - 2`
|
|
2130
|
+
# because the `phi` above and `torch.matmul(psd_s, rtf)` are regarded as
|
|
2131
|
+
# two iterations.
|
|
2132
|
+
for _ in range(n_iter - 2):
|
|
2133
|
+
rtf = torch.matmul(phi, rtf)
|
|
2134
|
+
rtf = torch.matmul(psd_s, rtf)
|
|
2135
|
+
else:
|
|
2136
|
+
# if there is only one iteration, the rtf is the psd_s[..., referenc_channel]
|
|
2137
|
+
# which is psd_n @ phi @ ref_channel
|
|
2138
|
+
rtf = torch.matmul(psd_n, rtf)
|
|
2139
|
+
return rtf.squeeze(-1)
|
|
2140
|
+
|
|
2141
|
+
|
|
2142
|
+
def apply_beamforming(beamform_weights: Tensor, specgram: Tensor) -> Tensor:
|
|
2143
|
+
r"""Apply the beamforming weight to the multi-channel noisy spectrum to obtain the single-channel enhanced spectrum.
|
|
2144
|
+
|
|
2145
|
+
.. devices:: CPU CUDA
|
|
2146
|
+
|
|
2147
|
+
.. properties:: Autograd TorchScript
|
|
2148
|
+
|
|
2149
|
+
.. math::
|
|
2150
|
+
\hat{\textbf{S}}(f) = \textbf{w}_{\text{bf}}(f)^{\mathsf{H}} \textbf{Y}(f)
|
|
2151
|
+
|
|
2152
|
+
where :math:`\textbf{w}_{\text{bf}}(f)` is the beamforming weight for the :math:`f`-th frequency bin,
|
|
2153
|
+
:math:`\textbf{Y}` is the multi-channel spectrum for the :math:`f`-th frequency bin.
|
|
2154
|
+
|
|
2155
|
+
Args:
|
|
2156
|
+
beamform_weights (Tensor): The complex-valued beamforming weight matrix.
|
|
2157
|
+
Tensor of dimension `(..., freq, channel)`
|
|
2158
|
+
specgram (Tensor): The multi-channel complex-valued noisy spectrum.
|
|
2159
|
+
Tensor of dimension `(..., channel, freq, time)`
|
|
2160
|
+
|
|
2161
|
+
Returns:
|
|
2162
|
+
Tensor: The single-channel complex-valued enhanced spectrum.
|
|
2163
|
+
Tensor of dimension `(..., freq, time)`
|
|
2164
|
+
"""
|
|
2165
|
+
if beamform_weights.shape[:-2] != specgram.shape[:-3]:
|
|
2166
|
+
raise ValueError(
|
|
2167
|
+
"The dimensions except the last two dimensions of beamform_weights should be the same "
|
|
2168
|
+
"as the dimensions except the last three dimensions of specgram. "
|
|
2169
|
+
f"Found {beamform_weights.shape} for beamform_weights and {specgram.shape} for specgram."
|
|
2170
|
+
)
|
|
2171
|
+
|
|
2172
|
+
if not (beamform_weights.is_complex() and specgram.is_complex()):
|
|
2173
|
+
raise TypeError(
|
|
2174
|
+
"The type of beamform_weights and specgram must be ``torch.cfloat`` or ``torch.cdouble``. "
|
|
2175
|
+
f"Found {beamform_weights.dtype} for beamform_weights and {specgram.dtype} for specgram."
|
|
2176
|
+
)
|
|
2177
|
+
|
|
2178
|
+
# (..., freq, channel) x (..., channel, freq, time) -> (..., freq, time)
|
|
2179
|
+
specgram_enhanced = torch.einsum("...fc,...cft->...ft", [beamform_weights.conj(), specgram])
|
|
2180
|
+
return specgram_enhanced
|
|
2181
|
+
|
|
2182
|
+
|
|
2183
|
+
def _check_shape_compatible(x: torch.Tensor, y: torch.Tensor) -> None:
|
|
2184
|
+
if x.ndim != y.ndim:
|
|
2185
|
+
raise ValueError(f"The operands must be the same dimension (got {x.ndim} and {y.ndim}).")
|
|
2186
|
+
|
|
2187
|
+
for i in range(x.ndim - 1):
|
|
2188
|
+
xi = x.size(i)
|
|
2189
|
+
yi = y.size(i)
|
|
2190
|
+
if xi == yi or xi == 1 or yi == 1:
|
|
2191
|
+
continue
|
|
2192
|
+
raise ValueError(f"Leading dimensions of x and y are not broadcastable (got {x.shape} and {y.shape}).")
|
|
2193
|
+
|
|
2194
|
+
|
|
2195
|
+
def _check_convolve_mode(mode: str) -> None:
|
|
2196
|
+
valid_convolve_modes = ["full", "valid", "same"]
|
|
2197
|
+
if mode not in valid_convolve_modes:
|
|
2198
|
+
raise ValueError(f"Unrecognized mode value '{mode}'. Please specify one of {valid_convolve_modes}.")
|
|
2199
|
+
|
|
2200
|
+
|
|
2201
|
+
def _apply_convolve_mode(conv_result: torch.Tensor, x_length: int, y_length: int, mode: str) -> torch.Tensor:
|
|
2202
|
+
valid_convolve_modes = ["full", "valid", "same"]
|
|
2203
|
+
if mode == "full":
|
|
2204
|
+
return conv_result
|
|
2205
|
+
elif mode == "valid":
|
|
2206
|
+
target_length = max(x_length, y_length) - min(x_length, y_length) + 1
|
|
2207
|
+
start_idx = (conv_result.size(-1) - target_length) // 2
|
|
2208
|
+
return conv_result[..., start_idx : start_idx + target_length]
|
|
2209
|
+
elif mode == "same":
|
|
2210
|
+
start_idx = (conv_result.size(-1) - x_length) // 2
|
|
2211
|
+
return conv_result[..., start_idx : start_idx + x_length]
|
|
2212
|
+
else:
|
|
2213
|
+
raise ValueError(f"Unrecognized mode value '{mode}'. Please specify one of {valid_convolve_modes}.")
|
|
2214
|
+
|
|
2215
|
+
|
|
2216
|
+
def fftconvolve(x: torch.Tensor, y: torch.Tensor, mode: str = "full") -> torch.Tensor:
|
|
2217
|
+
r"""
|
|
2218
|
+
Convolves inputs along their last dimension using FFT. For inputs with large last dimensions, this function
|
|
2219
|
+
is generally much faster than :meth:`convolve`.
|
|
2220
|
+
Note that, in contrast to :meth:`torch.nn.functional.conv1d`, which actually applies the valid cross-correlation
|
|
2221
|
+
operator, this function applies the true `convolution`_ operator.
|
|
2222
|
+
Also note that this function can only output float tensors (int tensor inputs will be cast to float).
|
|
2223
|
+
|
|
2224
|
+
.. devices:: CPU CUDA
|
|
2225
|
+
|
|
2226
|
+
.. properties:: Autograd TorchScript
|
|
2227
|
+
|
|
2228
|
+
Args:
|
|
2229
|
+
x (torch.Tensor): First convolution operand, with shape `(..., N)`.
|
|
2230
|
+
y (torch.Tensor): Second convolution operand, with shape `(..., M)`
|
|
2231
|
+
(leading dimensions must be broadcast-able with those of ``x``).
|
|
2232
|
+
mode (str, optional): Must be one of ("full", "valid", "same").
|
|
2233
|
+
|
|
2234
|
+
* "full": Returns the full convolution result, with shape `(..., N + M - 1)`. (Default)
|
|
2235
|
+
* "valid": Returns the segment of the full convolution result corresponding to where
|
|
2236
|
+
the two inputs overlap completely, with shape `(..., max(N, M) - min(N, M) + 1)`.
|
|
2237
|
+
* "same": Returns the center segment of the full convolution result, with shape `(..., N)`.
|
|
2238
|
+
|
|
2239
|
+
Returns:
|
|
2240
|
+
torch.Tensor: Result of convolving ``x`` and ``y``, with shape `(..., L)`, where
|
|
2241
|
+
the leading dimensions match those of ``x`` and `L` is dictated by ``mode``.
|
|
2242
|
+
|
|
2243
|
+
.. _convolution:
|
|
2244
|
+
https://en.wikipedia.org/wiki/Convolution
|
|
2245
|
+
"""
|
|
2246
|
+
_check_shape_compatible(x, y)
|
|
2247
|
+
_check_convolve_mode(mode)
|
|
2248
|
+
|
|
2249
|
+
n = x.size(-1) + y.size(-1) - 1
|
|
2250
|
+
fresult = torch.fft.rfft(x, n=n) * torch.fft.rfft(y, n=n)
|
|
2251
|
+
result = torch.fft.irfft(fresult, n=n)
|
|
2252
|
+
return _apply_convolve_mode(result, x.size(-1), y.size(-1), mode)
|
|
2253
|
+
|
|
2254
|
+
|
|
2255
|
+
def convolve(x: torch.Tensor, y: torch.Tensor, mode: str = "full") -> torch.Tensor:
|
|
2256
|
+
r"""
|
|
2257
|
+
Convolves inputs along their last dimension using the direct method.
|
|
2258
|
+
Note that, in contrast to :meth:`torch.nn.functional.conv1d`, which actually applies the valid cross-correlation
|
|
2259
|
+
operator, this function applies the true `convolution`_ operator.
|
|
2260
|
+
|
|
2261
|
+
.. devices:: CPU CUDA
|
|
2262
|
+
|
|
2263
|
+
.. properties:: Autograd TorchScript
|
|
2264
|
+
|
|
2265
|
+
Args:
|
|
2266
|
+
x (torch.Tensor): First convolution operand, with shape `(..., N)`.
|
|
2267
|
+
y (torch.Tensor): Second convolution operand, with shape `(..., M)`
|
|
2268
|
+
(leading dimensions must be broadcast-able with those of ``x``).
|
|
2269
|
+
mode (str, optional): Must be one of ("full", "valid", "same").
|
|
2270
|
+
|
|
2271
|
+
* "full": Returns the full convolution result, with shape `(..., N + M - 1)`. (Default)
|
|
2272
|
+
* "valid": Returns the segment of the full convolution result corresponding to where
|
|
2273
|
+
the two inputs overlap completely, with shape `(..., max(N, M) - min(N, M) + 1)`.
|
|
2274
|
+
* "same": Returns the center segment of the full convolution result, with shape `(..., N)`.
|
|
2275
|
+
|
|
2276
|
+
Returns:
|
|
2277
|
+
torch.Tensor: Result of convolving ``x`` and ``y``, with shape `(..., L)`, where
|
|
2278
|
+
the leading dimensions match those of ``x`` and `L` is dictated by ``mode``.
|
|
2279
|
+
|
|
2280
|
+
.. _convolution:
|
|
2281
|
+
https://en.wikipedia.org/wiki/Convolution
|
|
2282
|
+
"""
|
|
2283
|
+
_check_shape_compatible(x, y)
|
|
2284
|
+
_check_convolve_mode(mode)
|
|
2285
|
+
|
|
2286
|
+
x_size, y_size = x.size(-1), y.size(-1)
|
|
2287
|
+
|
|
2288
|
+
if x.size(-1) < y.size(-1):
|
|
2289
|
+
x, y = y, x
|
|
2290
|
+
|
|
2291
|
+
if x.shape[:-1] != y.shape[:-1]:
|
|
2292
|
+
new_shape = [max(i, j) for i, j in zip(x.shape[:-1], y.shape[:-1])]
|
|
2293
|
+
x = x.broadcast_to(new_shape + [x.shape[-1]])
|
|
2294
|
+
y = y.broadcast_to(new_shape + [y.shape[-1]])
|
|
2295
|
+
|
|
2296
|
+
num_signals = torch.tensor(x.shape[:-1]).prod()
|
|
2297
|
+
reshaped_x = x.reshape((int(num_signals), x.size(-1)))
|
|
2298
|
+
reshaped_y = y.reshape((int(num_signals), y.size(-1)))
|
|
2299
|
+
output = torch.nn.functional.conv1d(
|
|
2300
|
+
input=reshaped_x,
|
|
2301
|
+
weight=reshaped_y.flip(-1).unsqueeze(1),
|
|
2302
|
+
stride=1,
|
|
2303
|
+
groups=reshaped_x.size(0),
|
|
2304
|
+
padding=reshaped_y.size(-1) - 1,
|
|
2305
|
+
)
|
|
2306
|
+
output_shape = x.shape[:-1] + (-1,)
|
|
2307
|
+
result = output.reshape(output_shape)
|
|
2308
|
+
return _apply_convolve_mode(result, x_size, y_size, mode)
|
|
2309
|
+
|
|
2310
|
+
|
|
2311
|
+
def add_noise(
|
|
2312
|
+
waveform: torch.Tensor, noise: torch.Tensor, snr: torch.Tensor, lengths: Optional[torch.Tensor] = None
|
|
2313
|
+
) -> torch.Tensor:
|
|
2314
|
+
r"""Scales and adds noise to waveform per signal-to-noise ratio.
|
|
2315
|
+
|
|
2316
|
+
Specifically, for each pair of waveform vector :math:`x \in \mathbb{R}^L` and noise vector
|
|
2317
|
+
:math:`n \in \mathbb{R}^L`, the function computes output :math:`y` as
|
|
2318
|
+
|
|
2319
|
+
.. math::
|
|
2320
|
+
y = x + a n \, \text{,}
|
|
2321
|
+
|
|
2322
|
+
where
|
|
2323
|
+
|
|
2324
|
+
.. math::
|
|
2325
|
+
a = \sqrt{ \frac{ ||x||_{2}^{2} }{ ||n||_{2}^{2} } \cdot 10^{-\frac{\text{SNR}}{10}} } \, \text{,}
|
|
2326
|
+
|
|
2327
|
+
with :math:`\text{SNR}` being the desired signal-to-noise ratio between :math:`x` and :math:`n`, in dB.
|
|
2328
|
+
|
|
2329
|
+
Note that this function broadcasts singleton leading dimensions in its inputs in a manner that is
|
|
2330
|
+
consistent with the above formulae and PyTorch's broadcasting semantics.
|
|
2331
|
+
|
|
2332
|
+
.. devices:: CPU CUDA
|
|
2333
|
+
|
|
2334
|
+
.. properties:: Autograd TorchScript
|
|
2335
|
+
|
|
2336
|
+
Args:
|
|
2337
|
+
waveform (torch.Tensor): Input waveform, with shape `(..., L)`.
|
|
2338
|
+
noise (torch.Tensor): Noise, with shape `(..., L)` (same shape as ``waveform``).
|
|
2339
|
+
snr (torch.Tensor): Signal-to-noise ratios in dB, with shape `(...,)`.
|
|
2340
|
+
lengths (torch.Tensor or None, optional): Valid lengths of signals in ``waveform`` and ``noise``, with shape
|
|
2341
|
+
`(...,)` (leading dimensions must match those of ``waveform``). If ``None``, all elements in ``waveform``
|
|
2342
|
+
and ``noise`` are treated as valid. (Default: ``None``)
|
|
2343
|
+
|
|
2344
|
+
Returns:
|
|
2345
|
+
torch.Tensor: Result of scaling and adding ``noise`` to ``waveform``, with shape `(..., L)`
|
|
2346
|
+
(same shape as ``waveform``).
|
|
2347
|
+
"""
|
|
2348
|
+
|
|
2349
|
+
if not (waveform.ndim - 1 == noise.ndim - 1 == snr.ndim and (lengths is None or lengths.ndim == snr.ndim)):
|
|
2350
|
+
raise ValueError("Input leading dimensions don't match.")
|
|
2351
|
+
|
|
2352
|
+
L = waveform.size(-1)
|
|
2353
|
+
|
|
2354
|
+
if L != noise.size(-1):
|
|
2355
|
+
raise ValueError(f"Length dimensions of waveform and noise don't match (got {L} and {noise.size(-1)}).")
|
|
2356
|
+
|
|
2357
|
+
# compute scale
|
|
2358
|
+
if lengths is not None:
|
|
2359
|
+
mask = torch.arange(0, L, device=lengths.device).expand(waveform.shape) < lengths.unsqueeze(
|
|
2360
|
+
-1
|
|
2361
|
+
) # (*, L) < (*, 1) = (*, L)
|
|
2362
|
+
masked_waveform = waveform * mask
|
|
2363
|
+
masked_noise = noise * mask
|
|
2364
|
+
else:
|
|
2365
|
+
masked_waveform = waveform
|
|
2366
|
+
masked_noise = noise
|
|
2367
|
+
|
|
2368
|
+
energy_signal = torch.linalg.vector_norm(masked_waveform, ord=2, dim=-1) ** 2 # (*,)
|
|
2369
|
+
energy_noise = torch.linalg.vector_norm(masked_noise, ord=2, dim=-1) ** 2 # (*,)
|
|
2370
|
+
original_snr_db = 10 * (torch.log10(energy_signal) - torch.log10(energy_noise))
|
|
2371
|
+
scale = 10 ** ((original_snr_db - snr) / 20.0) # (*,)
|
|
2372
|
+
|
|
2373
|
+
# scale noise
|
|
2374
|
+
scaled_noise = scale.unsqueeze(-1) * noise # (*, 1) * (*, L) = (*, L)
|
|
2375
|
+
|
|
2376
|
+
return waveform + scaled_noise # (*, L)
|
|
2377
|
+
|
|
2378
|
+
|
|
2379
|
+
def speed(
|
|
2380
|
+
waveform: torch.Tensor, orig_freq: int, factor: float, lengths: Optional[torch.Tensor] = None
|
|
2381
|
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
|
|
2382
|
+
r"""Adjusts waveform speed.
|
|
2383
|
+
|
|
2384
|
+
.. devices:: CPU CUDA
|
|
2385
|
+
|
|
2386
|
+
.. properties:: Autograd TorchScript
|
|
2387
|
+
|
|
2388
|
+
Args:
|
|
2389
|
+
waveform (torch.Tensor): Input signals, with shape `(..., time)`.
|
|
2390
|
+
orig_freq (int): Original frequency of the signals in ``waveform``.
|
|
2391
|
+
factor (float): Factor by which to adjust speed of input. Values greater than 1.0
|
|
2392
|
+
compress ``waveform`` in time, whereas values less than 1.0 stretch ``waveform`` in time.
|
|
2393
|
+
lengths (torch.Tensor or None, optional): Valid lengths of signals in ``waveform``, with shape `(...)`.
|
|
2394
|
+
If ``None``, all elements in ``waveform`` are treated as valid. (Default: ``None``)
|
|
2395
|
+
|
|
2396
|
+
Returns:
|
|
2397
|
+
(torch.Tensor, torch.Tensor or None):
|
|
2398
|
+
torch.Tensor
|
|
2399
|
+
Speed-adjusted waveform, with shape `(..., new_time).`
|
|
2400
|
+
torch.Tensor or None
|
|
2401
|
+
If ``lengths`` is not ``None``, valid lengths of signals in speed-adjusted waveform,
|
|
2402
|
+
with shape `(...)`; otherwise, ``None``.
|
|
2403
|
+
"""
|
|
2404
|
+
|
|
2405
|
+
source_sample_rate = int(factor * orig_freq)
|
|
2406
|
+
target_sample_rate = int(orig_freq)
|
|
2407
|
+
|
|
2408
|
+
gcd = math.gcd(source_sample_rate, target_sample_rate)
|
|
2409
|
+
source_sample_rate = source_sample_rate // gcd
|
|
2410
|
+
target_sample_rate = target_sample_rate // gcd
|
|
2411
|
+
|
|
2412
|
+
if lengths is None:
|
|
2413
|
+
out_lengths = None
|
|
2414
|
+
else:
|
|
2415
|
+
out_lengths = torch.ceil(lengths * target_sample_rate / source_sample_rate).to(lengths.dtype)
|
|
2416
|
+
|
|
2417
|
+
return resample(waveform, source_sample_rate, target_sample_rate), out_lengths
|
|
2418
|
+
|
|
2419
|
+
|
|
2420
|
+
def preemphasis(waveform, coeff: float = 0.97) -> torch.Tensor:
|
|
2421
|
+
r"""Pre-emphasizes a waveform along its last dimension, i.e.
|
|
2422
|
+
for each signal :math:`x` in ``waveform``, computes
|
|
2423
|
+
output :math:`y` as
|
|
2424
|
+
|
|
2425
|
+
.. math::
|
|
2426
|
+
y[i] = x[i] - \text{coeff} \cdot x[i - 1]
|
|
2427
|
+
|
|
2428
|
+
.. devices:: CPU CUDA
|
|
2429
|
+
|
|
2430
|
+
.. properties:: Autograd TorchScript
|
|
2431
|
+
|
|
2432
|
+
Args:
|
|
2433
|
+
waveform (torch.Tensor): Waveform, with shape `(..., N)`.
|
|
2434
|
+
coeff (float, optional): Pre-emphasis coefficient. Typically between 0.0 and 1.0.
|
|
2435
|
+
(Default: 0.97)
|
|
2436
|
+
|
|
2437
|
+
Returns:
|
|
2438
|
+
torch.Tensor: Pre-emphasized waveform, with shape `(..., N)`.
|
|
2439
|
+
"""
|
|
2440
|
+
waveform = waveform.clone()
|
|
2441
|
+
waveform[..., 1:] -= coeff * waveform[..., :-1]
|
|
2442
|
+
return waveform
|
|
2443
|
+
|
|
2444
|
+
|
|
2445
|
+
def deemphasis(waveform, coeff: float = 0.97) -> torch.Tensor:
|
|
2446
|
+
r"""De-emphasizes a waveform along its last dimension.
|
|
2447
|
+
Inverse of :meth:`preemphasis`. Concretely, for each signal
|
|
2448
|
+
:math:`x` in ``waveform``, computes output :math:`y` as
|
|
2449
|
+
|
|
2450
|
+
.. math::
|
|
2451
|
+
y[i] = x[i] + \text{coeff} \cdot y[i - 1]
|
|
2452
|
+
|
|
2453
|
+
.. devices:: CPU CUDA
|
|
2454
|
+
|
|
2455
|
+
.. properties:: Autograd TorchScript
|
|
2456
|
+
|
|
2457
|
+
Args:
|
|
2458
|
+
waveform (torch.Tensor): Waveform, with shape `(..., N)`.
|
|
2459
|
+
coeff (float, optional): De-emphasis coefficient. Typically between 0.0 and 1.0.
|
|
2460
|
+
(Default: 0.97)
|
|
2461
|
+
|
|
2462
|
+
Returns:
|
|
2463
|
+
torch.Tensor: De-emphasized waveform, with shape `(..., N)`.
|
|
2464
|
+
"""
|
|
2465
|
+
a_coeffs = torch.tensor([1.0, -coeff], dtype=waveform.dtype, device=waveform.device)
|
|
2466
|
+
b_coeffs = torch.tensor([1.0, 0.0], dtype=waveform.dtype, device=waveform.device)
|
|
2467
|
+
return torchaudio.functional.filtering.lfilter(waveform, a_coeffs=a_coeffs, b_coeffs=b_coeffs)
|
|
2468
|
+
|
|
2469
|
+
|
|
2470
|
+
def frechet_distance(mu_x, sigma_x, mu_y, sigma_y):
|
|
2471
|
+
r"""Computes the Fréchet distance between two multivariate normal distributions :cite:`dowson1982frechet`.
|
|
2472
|
+
|
|
2473
|
+
Concretely, for multivariate Gaussians :math:`X(\mu_X, \Sigma_X)`
|
|
2474
|
+
and :math:`Y(\mu_Y, \Sigma_Y)`, the function computes and returns :math:`F` as
|
|
2475
|
+
|
|
2476
|
+
.. math::
|
|
2477
|
+
F(X, Y) = || \mu_X - \mu_Y ||_2^2
|
|
2478
|
+
+ \text{Tr}\left( \Sigma_X + \Sigma_Y - 2 \sqrt{\Sigma_X \Sigma_Y} \right)
|
|
2479
|
+
|
|
2480
|
+
Args:
|
|
2481
|
+
mu_x (torch.Tensor): mean :math:`\mu_X` of multivariate Gaussian :math:`X`, with shape `(N,)`.
|
|
2482
|
+
sigma_x (torch.Tensor): covariance matrix :math:`\Sigma_X` of :math:`X`, with shape `(N, N)`.
|
|
2483
|
+
mu_y (torch.Tensor): mean :math:`\mu_Y` of multivariate Gaussian :math:`Y`, with shape `(N,)`.
|
|
2484
|
+
sigma_y (torch.Tensor): covariance matrix :math:`\Sigma_Y` of :math:`Y`, with shape `(N, N)`.
|
|
2485
|
+
|
|
2486
|
+
Returns:
|
|
2487
|
+
torch.Tensor: the Fréchet distance between :math:`X` and :math:`Y`.
|
|
2488
|
+
"""
|
|
2489
|
+
if len(mu_x.size()) != 1:
|
|
2490
|
+
raise ValueError(f"Input mu_x must be one-dimensional; got dimension {len(mu_x.size())}.")
|
|
2491
|
+
if len(sigma_x.size()) != 2:
|
|
2492
|
+
raise ValueError(f"Input sigma_x must be two-dimensional; got dimension {len(sigma_x.size())}.")
|
|
2493
|
+
if sigma_x.size(0) != sigma_x.size(1) != mu_x.size(0):
|
|
2494
|
+
raise ValueError("Each of sigma_x's dimensions must match mu_x's size.")
|
|
2495
|
+
if mu_x.size() != mu_y.size():
|
|
2496
|
+
raise ValueError(f"Inputs mu_x and mu_y must have the same shape; got {mu_x.size()} and {mu_y.size()}.")
|
|
2497
|
+
if sigma_x.size() != sigma_y.size():
|
|
2498
|
+
raise ValueError(
|
|
2499
|
+
f"Inputs sigma_x and sigma_y must have the same shape; got {sigma_x.size()} and {sigma_y.size()}."
|
|
2500
|
+
)
|
|
2501
|
+
|
|
2502
|
+
a = (mu_x - mu_y).square().sum()
|
|
2503
|
+
b = sigma_x.trace() + sigma_y.trace()
|
|
2504
|
+
c = torch.linalg.eigvals(sigma_x @ sigma_y).sqrt().real.sum()
|
|
2505
|
+
return a + b - 2 * c
|