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

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

10
from . import common_utils
11
from parameterized import parameterized, param
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


46
47
48
49
50
def _load_params(path):
    with open(path, 'r') as file:
        return [param(json.loads(line)) for line in file]


moto's avatar
moto committed
51
class Kaldi(common_utils.TestBaseMixin):
moto's avatar
moto committed
52
53
    backend = 'sox'

54
55
56
57
    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)

58
    @common_utils.skipIfNoExec('apply-cmvn-sliding')
59
60
61
62
63
64
65
66
67
    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
68
        tensor = torch.randn(40, 10, dtype=self.dtype, device=self.device)
69
70
        result = F.sliding_window_cmn(tensor, **kwargs)
        command = ['apply-cmvn-sliding'] + _convert_args(**kwargs) + ['ark:-', 'ark:-']
71
        kaldi_result = _run_kaldi(command, 'ark', tensor)
72
        self.assert_equal(result, expected=kaldi_result)
73

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

85
    @parameterized.expand(_load_params(common_utils.get_asset_path('kaldi_test_spectrogram_args.json')))
86
    @common_utils.skipIfNoExec('compute-spectrogram-feats')
87
88
89
90
91
92
93
94
95
    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)

96
    @parameterized.expand(_load_params(common_utils.get_asset_path('kaldi_test_mfcc_args.json')))
97
    @common_utils.skipIfNoExec('compute-mfcc-feats')
98
99
100
101
102
103
104
105
    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)