-
Notifications
You must be signed in to change notification settings - Fork 22
/
layers.py
339 lines (262 loc) · 10.4 KB
/
layers.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
import torch
import math
import torch.nn as nn
from .functional import stft, complex_norm, \
create_mel_filter, phase_vocoder, apply_filterbank
class _ModuleNoStateBuffers(nn.Module):
"""
Extension of nn.Module that removes buffers
from state_dict.
"""
def state_dict(self, destination=None, prefix='', keep_vars=False):
ret = super(_ModuleNoStateBuffers, self).state_dict(
destination, prefix, keep_vars)
for k in self._buffers:
del ret[prefix + k]
return ret
def _load_from_state_dict(self, state_dict, prefix, *args, **kwargs):
# temporarily hide the buffers; we do not want to restore them
buffers = self._buffers
self._buffers = {}
result = super(_ModuleNoStateBuffers, self)._load_from_state_dict(
state_dict, prefix, *args, **kwargs)
self._buffers = buffers
return result
class STFT(_ModuleNoStateBuffers):
"""
Compute the stft transform of a multi-channel signal or
batch of multi-channel signals.
Args:
fft_len (int): FFT window size. Defaults to 2048.
hop_len (int): Number audio of frames between stft columns.
Defaults to fft_len // 4.
frame_len (int): Size of stft window. Defaults to fft_len.
window (Tensor): 1-D tensor. Defaults to Hann Window
of size frame_len.
pad (int): Amount of padding to apply to signal. Defaults to 0.
pad_mode: padding method (see torch.nn.functional.pad).
Defaults to "reflect".
**kwargs: Other torch.stft parameters, see torch.stft for more details.
"""
def __init__(self, fft_len=2048, hop_len=None, frame_len=None,
window=None, pad=0, pad_mode="reflect", **kwargs):
super(STFT, self).__init__()
# Get default values, window so it can be registered as buffer
self.fft_len, self.hop_len, window = self._stft_defaults(
fft_len, hop_len, frame_len, window)
self.pad = pad
self.pad_mode = pad_mode
self.kwargs = kwargs
self.register_buffer('window', window)
def _stft_defaults(self, fft_len, hop_len, frame_len, window):
"""
Handle default values for STFT.
"""
hop_len = fft_len // 4 if hop_len is None else hop_len
if window is None:
length = fft_len if frame_len is None else frame_len
window = torch.hann_window(length)
if not isinstance(window, torch.Tensor):
raise TypeError('window must be a of type torch.Tensor')
return fft_len, hop_len, window
def forward(self, signal):
"""
Args:
signal (Tensor): (channel, time) or (batch, channel, time).
Returns:
spect (Tensor): (channel, time, freq, complex)
or (batch, channel, time, freq, complex).
"""
spect = stft(signal, self.fft_len, self.hop_len, window=self.window,
pad=self.pad, pad_mode=self.pad_mode, **self.kwargs)
return spect
def __repr__(self):
param_str = '(fft_len={}, hop_len={}, frame_len={})'.format(
self.fft_len, self.hop_len, self.window.size(0))
return self.__class__.__name__ + param_str
class ComplexNorm(nn.Module):
"""
Wrap torchaudio_contrib.complex_norm in an nn.Module.
"""
def __init__(self, power=1.0):
super(ComplexNorm, self).__init__()
self.power = power
def forward(self, stft):
return complex_norm(stft, self.power)
def __repr__(self):
return self.__class__.__name__ + '(power={})'.format(self.power)
class ApplyFilterbank(_ModuleNoStateBuffers):
"""
Applies a filterbank transform.
"""
def __init__(self, filterbank):
super(ApplyFilterbank, self).__init__()
self.register_buffer('filterbank', filterbank)
def forward(self, spect):
"""
Args:
spect (Tensor): (channel, time, freq) or (batch, channel, time, freq).
Returns:
(Tensor): freq -> filterbank.size(0)
"""
return apply_filterbank(spect, self.filterbank)
class Filterbank(object):
"""
Base class for providing a filterbank matrix.
"""
def __init__(self):
super(Filterbank, self).__init__()
def get_filterbank(self):
raise NotImplementedError
class MelFilterbank(Filterbank):
"""
Provides a filterbank matrix to convert a spectrogram into a mel frequency spectrogram.
Args:
num_bands (int): number of mel bins. Defaults to 128.
sample_rate (int): sample rate of audio signal. Defaults to 22050.
min_freq (float): minimum frequency. Defaults to 0.
max_freq (float, optional): maximum frequency. Defaults to sample_rate // 2.
num_bins (int, optional): number of filter banks from stft.
Defaults to 2048//2 + 1.
htk (bool, optional): use HTK formula instead of Slaney. Defaults to False.
"""
def __init__(self, num_bands=128, sample_rate=22050,
min_freq=0.0, max_freq=None, num_bins=1025, htk=False):
super(MelFilterbank, self).__init__()
self.num_bands = num_bands
self.sample_rate = sample_rate
self.min_freq = min_freq
self.max_freq = max_freq if max_freq else sample_rate // 2
self.num_bins = num_bins
self.htk = htk
def to_hertz(self, mel):
"""
Converting mel values into frequency
"""
mel = torch.as_tensor(mel).float()
if self.htk:
return 700. * (10**(mel / 2595.) - 1.)
f_min = 0.0
f_sp = 200.0 / 3
hz = f_min + f_sp * mel
min_log_hz = 1000.0
min_log_mel = (min_log_hz - f_min) / f_sp
logstep = math.log(6.4) / 27.0
return torch.where(mel >= min_log_mel, min_log_hz *
torch.exp(logstep * (mel - min_log_mel)), hz)
def from_hertz(self, hz):
"""
Converting frequency into mel values
"""
hz = torch.as_tensor(hz).float()
if self.htk:
return 2595. * torch.log10(torch.tensor(1.) + (hz / 700.))
f_min = 0.0
f_sp = 200.0 / 3
mel = (hz - f_min) / f_sp
min_log_hz = 1000.0
min_log_mel = (min_log_hz - f_min) / f_sp
logstep = math.log(6.4) / 27.0
return torch.where(hz >= min_log_hz, min_log_mel +
torch.log(hz / min_log_hz) / logstep, mel)
def get_filterbank(self):
return create_mel_filter(
num_bands=self.num_bands,
sample_rate=self.sample_rate,
min_freq=self.min_freq,
max_freq=self.max_freq,
num_bins=self.num_bins,
to_hertz=self.to_hertz,
from_hertz=self.from_hertz)
def __repr__(self):
param_str1 = '(num_bands={}, sample_rate={}'.format(
self.num_bands, self.sample_rate)
param_str2 = ', min_freq={}, max_freq={})'.format(
self.min_freq, self.max_freq)
return self.__class__.__name__ + param_str1 + param_str2
class StretchSpecTime(_ModuleNoStateBuffers):
"""
Stretch stft in time without modifying pitch for a given rate.
Args:
rate (float): rate to speed up or slow down by. Defaults to 1.
hop_len (int): Number audio of frames between STFT columns.
Defaults to 512.
num_bins (int, optional): number of filter banks from stft.
Defaults to 1025.
"""
def __init__(self, rate=1., hop_len=512, num_bins=1025):
super(StretchSpecTime, self).__init__()
self.rate = rate
phi_advance = torch.linspace(
0, math.pi * hop_len, num_bins)[..., None]
self.register_buffer('phi_advance', phi_advance)
def forward(self, spect, rate=None):
if rate is None:
rate = self.rate
return phase_vocoder(spect, rate, self.phi_advance)
def __repr__(self):
param_str = '(rate={})'.format(self.rate)
return self.__class__.__name__ + param_str
def Spectrogram(fft_len=2048, hop_len=None, frame_len=None,
window=None, pad=0, pad_mode="reflect", power=1., **kwargs):
"""
Get spectrogram module.
Args:
fft_len (int): FFT window size. Defaults to 2048.
hop_len (int): Number audio of frames between STFT columns.
Defaults to fft_len // 4.
frame_len (int): Size of stft window. Defaults to fft_len.
window (Tensor): 1-D tensor.
Defaults to Hann Window of size frame_len.
pad (int): Amount of padding to apply to signal. Defaults to 0.
pad_mode: padding method (see torch.nn.functional.pad).
Defaults to "reflect".
power (float): Exponent of the magnitude. Defaults to 1.
**kwargs: Other torch.stft parameters, see torch.stft for more details.
"""
return nn.Sequential(
STFT(
fft_len,
hop_len,
frame_len,
window,
pad,
pad_mode,
**kwargs),
ComplexNorm(power))
def Melspectrogram(
num_bands=128,
sample_rate=22050,
min_freq=0.0,
max_freq=None,
num_bins=None,
htk=False,
mel_filterbank=None,
**kwargs):
"""
Get melspectrogram module.
Args:
num_bands (int): number of mel bins. Defaults to 128.
sample_rate (int): sample rate of audio signal. Defaults to 22050.
min_freq (float): minimum frequency. Defaults to 0.
max_freq (float, optional): maximum frequency. Defaults to sample_rate // 2.
num_bins (int, optional): number of filter banks from stft.
Defaults to fft_len//2 + 1 if 'fft_len' in kwargs else 1025.
htk (bool, optional): use HTK formula instead of Slaney. Defaults to False.
mel_filterbank (class, optional): MelFilterbank class to build filterbank matrix
**kwargs: torchaudio_contrib.Spectrogram parameters.
"""
fft_len = kwargs.get('fft_len', None)
num_bins = fft_len // 2 + 1 if fft_len else 1025
# Check if custom MelFilterbank is passed
if mel_filterbank is None:
mel_filterbank = MelFilterbank
mel_fb_matrix = mel_filterbank(
num_bands,
sample_rate,
min_freq,
max_freq,
num_bins,
htk).get_filterbank()
return nn.Sequential(*Spectrogram(power=2., **kwargs),
ApplyFilterbank(mel_fb_matrix))