kaldi_compatibility_impl.py 4.36 KB
Newer Older
1
2
3
4
5
6
"""Test suites for checking numerical compatibility against Kaldi"""
import subprocess

import kaldi_io
import torch
import torchaudio.functional as F
7
import torchaudio.compliance.kaldi
8

9
from . import common_utils
moto's avatar
moto committed
10
11
from .common_utils import load_params
from parameterized import parameterized
12

13

14
15
16
17
18
19
20
21
22
def _convert_args(**kwargs):
    args = []
    for key, value in kwargs.items():
        key = '--' + key.replace('_', '-')
        value = str(value).lower() if value in [True, False] else str(value)
        args.append('%s=%s' % (key, value))
    return args


23
def _run_kaldi(command, input_type, input_value):
24
25
    """Run provided Kaldi command, pass a tensor and get the resulting tensor

26
27
28
29
30
31
    Arguments:
        input_type: str
            'ark' or 'scp'
        input_value:
            Tensor for 'ark'
            string for 'scp' (path to an audio file)
32
    """
33
    key = 'foo'
34
    process = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
35
    if input_type == 'ark':
moto's avatar
moto committed
36
        kaldi_io.write_mat(process.stdin, input_value.cpu().numpy(), key=key)
37
38
39
40
    elif input_type == 'scp':
        process.stdin.write(f'{key} {input_value}'.encode('utf8'))
    else:
        raise NotImplementedError('Unexpected type')
41
42
43
44
45
    process.stdin.close()
    result = dict(kaldi_io.read_mat_ark(process.stdout))['foo']
    return torch.from_numpy(result.copy())  # copy supresses some torch warning


moto's avatar
moto committed
46
class Kaldi(common_utils.TestBaseMixin):
moto's avatar
moto committed
47
48
    backend = 'sox'

49
50
51
52
    def assert_equal(self, output, *, expected, rtol=None, atol=None):
        expected = expected.to(dtype=self.dtype, device=self.device)
        self.assertEqual(output, expected, rtol=rtol, atol=atol)

53
    @common_utils.skipIfNoExec('apply-cmvn-sliding')
54
55
56
57
58
59
60
61
62
    def test_sliding_window_cmn(self):
        """sliding_window_cmn should be numerically compatible with apply-cmvn-sliding"""
        kwargs = {
            'cmn_window': 600,
            'min_cmn_window': 100,
            'center': False,
            'norm_vars': False,
        }

moto's avatar
moto committed
63
        tensor = torch.randn(40, 10, dtype=self.dtype, device=self.device)
64
65
        result = F.sliding_window_cmn(tensor, **kwargs)
        command = ['apply-cmvn-sliding'] + _convert_args(**kwargs) + ['ark:-', 'ark:-']
66
        kaldi_result = _run_kaldi(command, 'ark', tensor)
67
        self.assert_equal(result, expected=kaldi_result)
68

moto's avatar
moto committed
69
    @parameterized.expand(load_params('kaldi_test_fbank_args.json'))
70
    @common_utils.skipIfNoExec('compute-fbank-feats')
71
    def test_fbank(self, kwargs):
72
73
        """fbank should be numerically compatible with compute-fbank-feats"""
        wave_file = common_utils.get_asset_path('kaldi_file.wav')
moto's avatar
moto committed
74
75
        waveform = torchaudio.load_wav(wave_file)[0].to(dtype=self.dtype, device=self.device)
        result = torchaudio.compliance.kaldi.fbank(waveform, **kwargs)
76
77
        command = ['compute-fbank-feats'] + _convert_args(**kwargs) + ['scp:-', 'ark:-']
        kaldi_result = _run_kaldi(command, 'scp', wave_file)
78
        self.assert_equal(result, expected=kaldi_result, rtol=1e-4, atol=1e-8)
79

moto's avatar
moto committed
80
    @parameterized.expand(load_params('kaldi_test_spectrogram_args.json'))
81
    @common_utils.skipIfNoExec('compute-spectrogram-feats')
82
83
84
85
86
87
88
89
90
    def test_spectrogram(self, kwargs):
        """spectrogram should be numerically compatible with compute-spectrogram-feats"""
        wave_file = common_utils.get_asset_path('kaldi_file.wav')
        waveform = torchaudio.load_wav(wave_file)[0].to(dtype=self.dtype, device=self.device)
        result = torchaudio.compliance.kaldi.spectrogram(waveform, **kwargs)
        command = ['compute-spectrogram-feats'] + _convert_args(**kwargs) + ['scp:-', 'ark:-']
        kaldi_result = _run_kaldi(command, 'scp', wave_file)
        self.assert_equal(result, expected=kaldi_result, rtol=1e-4, atol=1e-8)

moto's avatar
moto committed
91
    @parameterized.expand(load_params('kaldi_test_mfcc_args.json'))
92
    @common_utils.skipIfNoExec('compute-mfcc-feats')
93
94
95
96
97
98
99
100
    def test_mfcc(self, kwargs):
        """mfcc should be numerically compatible with compute-mfcc-feats"""
        wave_file = common_utils.get_asset_path('kaldi_file.wav')
        waveform = torchaudio.load_wav(wave_file)[0].to(dtype=self.dtype, device=self.device)
        result = torchaudio.compliance.kaldi.mfcc(waveform, **kwargs)
        command = ['compute-mfcc-feats'] + _convert_args(**kwargs) + ['scp:-', 'ark:-']
        kaldi_result = _run_kaldi(command, 'scp', wave_file)
        self.assert_equal(result, expected=kaldi_result, rtol=1e-4, atol=1e-8)