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

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

11
import common_utils
12

13
14
15

def _not_available(cmd):
    return shutil.which(cmd) is None
16
17
18
19
20
21
22
23
24
25
26


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


27
def _run_kaldi(command, input_type, input_value):
28
29
    """Run provided Kaldi command, pass a tensor and get the resulting tensor

30
31
32
33
34
35
    Arguments:
        input_type: str
            'ark' or 'scp'
        input_value:
            Tensor for 'ark'
            string for 'scp' (path to an audio file)
36
    """
37
    key = 'foo'
38
    process = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
39
    if input_type == 'ark':
moto's avatar
moto committed
40
        kaldi_io.write_mat(process.stdin, input_value.cpu().numpy(), key=key)
41
42
43
44
    elif input_type == 'scp':
        process.stdin.write(f'{key} {input_value}'.encode('utf8'))
    else:
        raise NotImplementedError('Unexpected type')
45
46
47
48
49
    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
50
class Kaldi(common_utils.TestBaseMixin):
51
52
53
54
    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)

55
    @unittest.skipIf(_not_available('apply-cmvn-sliding'), '`apply-cmvn-sliding` not available')
56
57
58
59
60
61
62
63
64
    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
65
        tensor = torch.randn(40, 10, dtype=self.dtype, device=self.device)
66
67
        result = F.sliding_window_cmn(tensor, **kwargs)
        command = ['apply-cmvn-sliding'] + _convert_args(**kwargs) + ['ark:-', 'ark:-']
68
        kaldi_result = _run_kaldi(command, 'ark', tensor)
69
        self.assert_equal(result, expected=kaldi_result)
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

    @unittest.skipIf(_not_available('compute-fbank-feats'), '`compute-fbank-feats` not available')
    def test_fbank(self):
        """fbank should be numerically compatible with compute-fbank-feats"""
        kwargs = {
            'blackman_coeff': 4.3926,
            'dither': 0.0,
            'energy_floor': 2.0617,
            'frame_length': 0.5625,
            'frame_shift': 0.0625,
            'high_freq': 4253,
            'htk_compat': True,
            'low_freq': 1367,
            'num_mel_bins': 5,
            'preemphasis_coefficient': 0.84,
            'raw_energy': False,
            'remove_dc_offset': True,
            'round_to_power_of_two': True,
            'snip_edges': True,
            'subtract_mean': False,
            'use_energy': True,
            'use_log_fbank': True,
            'use_power': False,
            'vtln_high': 2112,
            'vtln_low': 1445,
            'vtln_warp': 1.0000,
            'window_type': 'hamming',

        }
        wave_file = common_utils.get_asset_path('kaldi_file.wav')
moto's avatar
moto committed
100
101
        waveform = torchaudio.load_wav(wave_file)[0].to(dtype=self.dtype, device=self.device)
        result = torchaudio.compliance.kaldi.fbank(waveform, **kwargs)
102
103
        command = ['compute-fbank-feats'] + _convert_args(**kwargs) + ['scp:-', 'ark:-']
        kaldi_result = _run_kaldi(command, 'scp', wave_file)
104
        self.assert_equal(result, expected=kaldi_result, rtol=1e-4, atol=1e-8)