"vscode:/vscode.git/clone" did not exist on "d38878523d484de8b05589ac8512b7c795022b08"
functional_cpu_test.py 14.3 KB
Newer Older
jamarshon's avatar
jamarshon committed
1
import math
2
import unittest
jamarshon's avatar
jamarshon committed
3
4
5

import torch
import torchaudio
6
import torchaudio.functional as F
7
from parameterized import parameterized
8
import pytest
jamarshon's avatar
jamarshon committed
9

10
from . import common_utils
11
from .functional_impl import Lfilter
12

jamarshon's avatar
jamarshon committed
13

moto's avatar
moto committed
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
def random_float_tensor(seed, size, a=22695477, c=1, m=2 ** 32):
    """ Generates random tensors given a seed and size
    https://en.wikipedia.org/wiki/Linear_congruential_generator
    X_{n + 1} = (a * X_n + c) % m
    Using Borland C/C++ values

    The tensor will have values between [0,1)
    Inputs:
        seed (int): an int
        size (Tuple[int]): the size of the output tensor
        a (int): the multiplier constant to the generator
        c (int): the additive constant to the generator
        m (int): the modulus constant to the generator
    """
    num_elements = 1
    for s in size:
        num_elements *= s

    arr = [(a * seed + c) % m]
    for i in range(num_elements - 1):
        arr.append((a * arr[i] + c) % m)

    return torch.tensor(arr).float().view(size) / m


moto's avatar
moto committed
39
class TestLFilterFloat32(Lfilter, common_utils.PytorchTestCase):
40
41
    dtype = torch.float32
    device = torch.device('cpu')
42
43


moto's avatar
moto committed
44
class TestLFilterFloat64(Lfilter, common_utils.PytorchTestCase):
45
46
    dtype = torch.float64
    device = torch.device('cpu')
47
48


moto's avatar
moto committed
49
class TestComputeDeltas(common_utils.TorchaudioTestCase):
moto's avatar
moto committed
50
51
52
53
54
    """Test suite for correctness of compute_deltas"""
    def test_one_channel(self):
        specgram = torch.tensor([[[1.0, 2.0, 3.0, 4.0]]])
        expected = torch.tensor([[[0.5, 1.0, 1.0, 0.5]]])
        computed = F.compute_deltas(specgram, win_length=3)
55
        torch.testing.assert_allclose(computed, expected)
Vincent QB's avatar
Vincent QB committed
56

moto's avatar
moto committed
57
58
59
60
61
62
    def test_two_channels(self):
        specgram = torch.tensor([[[1.0, 2.0, 3.0, 4.0],
                                  [1.0, 2.0, 3.0, 4.0]]])
        expected = torch.tensor([[[0.5, 1.0, 1.0, 0.5],
                                  [0.5, 1.0, 1.0, 0.5]]])
        computed = F.compute_deltas(specgram, win_length=3)
63
        torch.testing.assert_allclose(computed, expected)
64

Vincent QB's avatar
Vincent QB committed
65

moto's avatar
moto committed
66
67
68
def _compare_estimate(sound, estimate, atol=1e-6, rtol=1e-8):
    # trim sound for case when constructed signal is shorter than original
    sound = sound[..., :estimate.size(-1)]
69
    torch.testing.assert_allclose(estimate, sound, atol=atol, rtol=rtol)
Vincent QB's avatar
Vincent QB committed
70
71


moto's avatar
moto committed
72
73
74
75
76
def _test_istft_is_inverse_of_stft(kwargs):
    # generates a random sound signal for each tril and then does the stft/istft
    # operation to check whether we can reconstruct signal
    for data_size in [(2, 20), (3, 15), (4, 10)]:
        for i in range(100):
jamarshon's avatar
jamarshon committed
77

moto's avatar
moto committed
78
            sound = random_float_tensor(i, data_size)
jamarshon's avatar
jamarshon committed
79

moto's avatar
moto committed
80
81
            stft = torch.stft(sound, **kwargs)
            estimate = torchaudio.functional.istft(stft, length=sound.size(1), **kwargs)
Vincent QB's avatar
Vincent QB committed
82

moto's avatar
moto committed
83
            _compare_estimate(sound, estimate)
jamarshon's avatar
jamarshon committed
84
85


moto's avatar
moto committed
86
class TestIstft(common_utils.TorchaudioTestCase):
moto's avatar
moto committed
87
88
    """Test suite for correctness of istft with various input"""
    number_of_trials = 100
jamarshon's avatar
jamarshon committed
89
90
91
92
93
94
95
96
97
98
99
100
101

    def test_istft_is_inverse_of_stft1(self):
        # hann_window, centered, normalized, onesided
        kwargs1 = {
            'n_fft': 12,
            'hop_length': 4,
            'win_length': 12,
            'window': torch.hann_window(12),
            'center': True,
            'pad_mode': 'reflect',
            'normalized': True,
            'onesided': True,
        }
moto's avatar
moto committed
102
        _test_istft_is_inverse_of_stft(kwargs1)
jamarshon's avatar
jamarshon committed
103
104
105
106
107
108
109
110
111
112
113
114
115

    def test_istft_is_inverse_of_stft2(self):
        # hann_window, centered, not normalized, not onesided
        kwargs2 = {
            'n_fft': 12,
            'hop_length': 2,
            'win_length': 8,
            'window': torch.hann_window(8),
            'center': True,
            'pad_mode': 'reflect',
            'normalized': False,
            'onesided': False,
        }
moto's avatar
moto committed
116
        _test_istft_is_inverse_of_stft(kwargs2)
jamarshon's avatar
jamarshon committed
117
118
119
120
121
122
123
124
125
126
127
128
129

    def test_istft_is_inverse_of_stft3(self):
        # hamming_window, centered, normalized, not onesided
        kwargs3 = {
            'n_fft': 15,
            'hop_length': 3,
            'win_length': 11,
            'window': torch.hamming_window(11),
            'center': True,
            'pad_mode': 'constant',
            'normalized': True,
            'onesided': False,
        }
moto's avatar
moto committed
130
        _test_istft_is_inverse_of_stft(kwargs3)
jamarshon's avatar
jamarshon committed
131
132
133
134
135
136
137
138
139
140
141
142
143
144

    def test_istft_is_inverse_of_stft4(self):
        # hamming_window, not centered, not normalized, onesided
        # window same size as n_fft
        kwargs4 = {
            'n_fft': 5,
            'hop_length': 2,
            'win_length': 5,
            'window': torch.hamming_window(5),
            'center': False,
            'pad_mode': 'constant',
            'normalized': False,
            'onesided': True,
        }
moto's avatar
moto committed
145
        _test_istft_is_inverse_of_stft(kwargs4)
jamarshon's avatar
jamarshon committed
146
147
148
149
150
151
152
153
154
155
156
157
158
159

    def test_istft_is_inverse_of_stft5(self):
        # hamming_window, not centered, not normalized, not onesided
        # window same size as n_fft
        kwargs5 = {
            'n_fft': 3,
            'hop_length': 2,
            'win_length': 3,
            'window': torch.hamming_window(3),
            'center': False,
            'pad_mode': 'reflect',
            'normalized': False,
            'onesided': False,
        }
moto's avatar
moto committed
160
        _test_istft_is_inverse_of_stft(kwargs5)
jamarshon's avatar
jamarshon committed
161
162
163
164
165
166
167
168
169
170

    def test_istft_of_ones(self):
        # stft = torch.stft(torch.ones(4), 4)
        stft = torch.tensor([
            [[4., 0.], [4., 0.], [4., 0.], [4., 0.], [4., 0.]],
            [[0., 0.], [0., 0.], [0., 0.], [0., 0.], [0., 0.]],
            [[0., 0.], [0., 0.], [0., 0.], [0., 0.], [0., 0.]]
        ])

        estimate = torchaudio.functional.istft(stft, n_fft=4, length=4)
moto's avatar
moto committed
171
        _compare_estimate(torch.ones(4), estimate)
jamarshon's avatar
jamarshon committed
172
173
174
175
176
177

    def test_istft_of_zeros(self):
        # stft = torch.stft(torch.zeros(4), 4)
        stft = torch.zeros((3, 5, 2))

        estimate = torchaudio.functional.istft(stft, n_fft=4, length=4)
moto's avatar
moto committed
178
        _compare_estimate(torch.zeros(4), estimate)
jamarshon's avatar
jamarshon committed
179
180
181
182

    def test_istft_requires_overlap_windows(self):
        # the window is size 1 but it hops 20 so there is a gap which throw an error
        stft = torch.zeros((3, 5, 2))
moto's avatar
moto committed
183
        self.assertRaises(RuntimeError, torchaudio.functional.istft, stft, n_fft=4,
jamarshon's avatar
jamarshon committed
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
                          hop_length=20, win_length=1, window=torch.ones(1))

    def test_istft_requires_nola(self):
        stft = torch.zeros((3, 5, 2))
        kwargs_ok = {
            'n_fft': 4,
            'win_length': 4,
            'window': torch.ones(4),
        }

        kwargs_not_ok = {
            'n_fft': 4,
            'win_length': 4,
            'window': torch.zeros(4),
        }

        # A window of ones meets NOLA but a window of zeros does not. This should
        # throw an error.
        torchaudio.functional.istft(stft, **kwargs_ok)
moto's avatar
moto committed
203
        self.assertRaises(RuntimeError, torchaudio.functional.istft, stft, **kwargs_not_ok)
jamarshon's avatar
jamarshon committed
204
205

    def test_istft_requires_non_empty(self):
moto's avatar
moto committed
206
207
        self.assertRaises(RuntimeError, torchaudio.functional.istft, torch.zeros((3, 0, 2)), 2)
        self.assertRaises(RuntimeError, torchaudio.functional.istft, torch.zeros((0, 3, 2)), 2)
jamarshon's avatar
jamarshon committed
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226

    def _test_istft_of_sine(self, amplitude, L, n):
        # stft of amplitude*sin(2*pi/L*n*x) with the hop length and window size equaling L
        x = torch.arange(2 * L + 1, dtype=torch.get_default_dtype())
        sound = amplitude * torch.sin(2 * math.pi / L * x * n)
        # stft = torch.stft(sound, L, hop_length=L, win_length=L,
        #                   window=torch.ones(L), center=False, normalized=False)
        stft = torch.zeros((L // 2 + 1, 2, 2))
        stft_largest_val = (amplitude * L) / 2.0
        if n < stft.size(0):
            stft[n, :, 1] = -stft_largest_val

        if 0 <= L - n < stft.size(0):
            # symmetric about L // 2
            stft[L - n, :, 1] = stft_largest_val

        estimate = torchaudio.functional.istft(stft, L, hop_length=L, win_length=L,
                                               window=torch.ones(L), center=False, normalized=False)
        # There is a larger error due to the scaling of amplitude
moto's avatar
moto committed
227
        _compare_estimate(sound, estimate, atol=1e-3)
jamarshon's avatar
jamarshon committed
228
229
230
231
232
233
234
235
236
237

    def test_istft_of_sine(self):
        self._test_istft_of_sine(amplitude=123, L=5, n=1)
        self._test_istft_of_sine(amplitude=150, L=5, n=2)
        self._test_istft_of_sine(amplitude=111, L=5, n=3)
        self._test_istft_of_sine(amplitude=160, L=7, n=4)
        self._test_istft_of_sine(amplitude=145, L=8, n=5)
        self._test_istft_of_sine(amplitude=80, L=9, n=6)
        self._test_istft_of_sine(amplitude=99, L=10, n=7)

238
239
    def _test_linearity_of_istft(self, data_size, kwargs, atol=1e-6, rtol=1e-8):
        for i in range(self.number_of_trials):
moto's avatar
moto committed
240
241
            tensor1 = random_float_tensor(i, data_size)
            tensor2 = random_float_tensor(i * 2, data_size)
242
243
244
245
246
            a, b = torch.rand(2)
            istft1 = torchaudio.functional.istft(tensor1, **kwargs)
            istft2 = torchaudio.functional.istft(tensor2, **kwargs)
            istft = a * istft1 + b * istft2
            estimate = torchaudio.functional.istft(a * tensor1 + b * tensor2, **kwargs)
moto's avatar
moto committed
247
            _compare_estimate(istft, estimate, atol, rtol)
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

    def test_linearity_of_istft1(self):
        # hann_window, centered, normalized, onesided
        kwargs1 = {
            'n_fft': 12,
            'window': torch.hann_window(12),
            'center': True,
            'pad_mode': 'reflect',
            'normalized': True,
            'onesided': True,
        }
        data_size = (2, 7, 7, 2)
        self._test_linearity_of_istft(data_size, kwargs1)

    def test_linearity_of_istft2(self):
        # hann_window, centered, not normalized, not onesided
        kwargs2 = {
            'n_fft': 12,
            'window': torch.hann_window(12),
            'center': True,
            'pad_mode': 'reflect',
            'normalized': False,
            'onesided': False,
        }
        data_size = (2, 12, 7, 2)
        self._test_linearity_of_istft(data_size, kwargs2)

    def test_linearity_of_istft3(self):
        # hamming_window, centered, normalized, not onesided
        kwargs3 = {
            'n_fft': 12,
            'window': torch.hamming_window(12),
            'center': True,
            'pad_mode': 'constant',
            'normalized': True,
            'onesided': False,
        }
        data_size = (2, 12, 7, 2)
        self._test_linearity_of_istft(data_size, kwargs3)

    def test_linearity_of_istft4(self):
        # hamming_window, not centered, not normalized, onesided
        kwargs4 = {
            'n_fft': 12,
            'window': torch.hamming_window(12),
            'center': False,
            'pad_mode': 'constant',
            'normalized': False,
            'onesided': True,
        }
        data_size = (2, 7, 3, 2)
        self._test_linearity_of_istft(data_size, kwargs4, atol=1e-5, rtol=1e-8)

moto's avatar
moto committed
301

moto's avatar
moto committed
302
class TestDetectPitchFrequency(common_utils.TorchaudioTestCase):
303
304
305
306
307
308
309
310
311
312
313
314
    @parameterized.expand([(100,), (440,)])
    def test_pitch(self, frequency):
        sample_rate = 44100
        test_sine_waveform = common_utils.get_sinusoid(
            frequency=frequency, sample_rate=sample_rate, duration=5,
        )

        freq = torchaudio.functional.detect_pitch_frequency(test_sine_waveform, sample_rate)

        threshold = 1
        s = ((freq - frequency).abs() > threshold).sum()
        self.assertFalse(s)
Vincent QB's avatar
Vincent QB committed
315

moto's avatar
moto committed
316

moto's avatar
moto committed
317
class TestDB_to_amplitude(common_utils.TorchaudioTestCase):
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
    def test_DB_to_amplitude(self):
        # Make some noise
        x = torch.rand(1000)
        spectrogram = torchaudio.transforms.Spectrogram()
        spec = spectrogram(x)

        amin = 1e-10
        ref = 1.0
        db_multiplier = math.log10(max(amin, ref))

        # Waveform amplitude -> DB -> amplitude
        multiplier = 20.
        power = 0.5

        db = F.amplitude_to_DB(torch.abs(x), multiplier, amin, db_multiplier, top_db=None)
        x2 = F.DB_to_amplitude(db, ref, power)

335
        torch.testing.assert_allclose(x2, torch.abs(x), atol=5e-5, rtol=1e-5)
336
337
338
339
340

        # Spectrogram amplitude -> DB -> amplitude
        db = F.amplitude_to_DB(spec, multiplier, amin, db_multiplier, top_db=None)
        x2 = F.DB_to_amplitude(db, ref, power)

341
        torch.testing.assert_allclose(x2, spec, atol=5e-5, rtol=1e-5)
342
343
344
345
346
347
348
349

        # Waveform power -> DB -> power
        multiplier = 10.
        power = 1.

        db = F.amplitude_to_DB(x, multiplier, amin, db_multiplier, top_db=None)
        x2 = F.DB_to_amplitude(db, ref, power)

350
        torch.testing.assert_allclose(x2, torch.abs(x), atol=5e-5, rtol=1e-5)
351
352
353
354
355

        # Spectrogram power -> DB -> power
        db = F.amplitude_to_DB(spec, multiplier, amin, db_multiplier, top_db=None)
        x2 = F.DB_to_amplitude(db, ref, power)

356
        torch.testing.assert_allclose(x2, spec, atol=5e-5, rtol=1e-5)
357

358
359
360
361
362
363
364
365
366
367

@pytest.mark.parametrize('complex_tensor', [
    torch.randn(1, 2, 1025, 400, 2),
    torch.randn(1025, 400, 2)
])
@pytest.mark.parametrize('power', [1, 2, 0.7])
def test_complex_norm(complex_tensor, power):
    expected_norm_tensor = complex_tensor.pow(2).sum(-1).pow(power / 2)
    norm_tensor = F.complex_norm(complex_tensor, power)

368
    torch.testing.assert_allclose(norm_tensor, expected_norm_tensor, atol=1e-5, rtol=1e-5)
369
370


371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
@pytest.mark.parametrize('specgram', [
    torch.randn(2, 1025, 400),
    torch.randn(1, 201, 100)
])
@pytest.mark.parametrize('mask_param', [100])
@pytest.mark.parametrize('mask_value', [0., 30.])
@pytest.mark.parametrize('axis', [1, 2])
def test_mask_along_axis(specgram, mask_param, mask_value, axis):

    mask_specgram = F.mask_along_axis(specgram, mask_param, mask_value, axis)

    other_axis = 1 if axis == 2 else 2

    masked_columns = (mask_specgram == mask_value).sum(other_axis)
    num_masked_columns = (masked_columns == mask_specgram.size(other_axis)).sum()
moto's avatar
moto committed
386
    num_masked_columns //= mask_specgram.size(0)
387
388
389
390
391
392
393
394

    assert mask_specgram.size() == specgram.size()
    assert num_masked_columns < mask_param


@pytest.mark.parametrize('mask_param', [100])
@pytest.mark.parametrize('mask_value', [0., 30.])
@pytest.mark.parametrize('axis', [2, 3])
395
396
397
def test_mask_along_axis_iid(mask_param, mask_value, axis):
    torch.random.manual_seed(42)
    specgrams = torch.randn(4, 2, 1025, 400)
398
399
400
401
402
403
404
405
406
407
408
409

    mask_specgrams = F.mask_along_axis_iid(specgrams, mask_param, mask_value, axis)

    other_axis = 2 if axis == 3 else 3

    masked_columns = (mask_specgrams == mask_value).sum(other_axis)
    num_masked_columns = (masked_columns == mask_specgrams.size(other_axis)).sum(-1)

    assert mask_specgrams.size() == specgrams.size()
    assert (num_masked_columns < mask_param).sum() == num_masked_columns.numel()


jamarshon's avatar
jamarshon committed
410
411
if __name__ == '__main__':
    unittest.main()