File size: 5,584 Bytes
5b65ff7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Compare torch, ONNX and C streaming on one wav.

Text: word error rate of every backend against the first one listed.
Numeric: C mel features and encoder output against the ONNX stream.
"""

from __future__ import annotations

import argparse
import subprocess
import sys
import time
from pathlib import Path

import numpy as np

ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT))

from stream_transcribe import SAMPLE_RATE, create_stream, load_wav, run_stream  # noqa: E402


def edit_distance(reference, hypothesis):
    row = list(range(len(hypothesis) + 1))
    for i, expected in enumerate(reference, 1):
        previous, row[0] = row[0], i
        for j, actual in enumerate(hypothesis, 1):
            previous, row[j] = row[j], min(
                row[j] + 1, row[j - 1] + 1, previous + (expected != actual)
            )
    return row[-1]


def word_error_rate(reference, hypothesis):
    words = reference.split()
    return edit_distance(words, hypothesis.split()) / max(len(words), 1)


def capture_encoder(stream, taps):
    """Record the mel packets and encoder frames of a Python stream."""
    encoder = stream.model.encoder
    forward = encoder.forward

    def recording(signal, lengths, *args, **kwargs):
        encoded, valid, state = forward(signal, lengths, *args, **kwargs)
        taps["mel"].append(np.asarray(signal[0]).T.copy())
        taps["encoded"].append(np.asarray(encoded[0]).T.copy())
        return encoded, valid, state

    encoder.forward = recording


def run_python(backend, args, context_ms, audio):
    started = time.perf_counter()
    stream = create_stream(backend, args.model_dir, args.onnx_dir, context_ms)
    taps = {"mel": [], "encoded": []}
    capture_encoder(stream, taps)
    texts, timings = run_stream(stream, audio, context_ms)
    print(
        f"  {backend}: {time.perf_counter() - started:.1f}s"
        f" (RTF {sum(timings) * SAMPLE_RATE / len(audio):.3f})",
        file=sys.stderr,
    )
    return texts, {name: np.concatenate(parts) for name, parts in taps.items()}


def run_c(args, context_ms):
    prefix = Path(args.work_dir) / f"c_{context_ms}"
    command = [
        str(args.bench),
        str(args.bin),
        str(args.wav),
        "--context-ms",
        str(context_ms),
        "--out",
        str(prefix),
        "--dump",
        str(prefix),
    ]
    result = subprocess.run(command, capture_output=True, text=True, check=True)
    print("  c: " + result.stderr.strip().splitlines()[0], file=sys.stderr)
    texts = {
        head: Path(f"{prefix}.{head}.txt").read_text().rstrip("\n")
        for head in ("e2e", "raw")
    }
    taps = {
        "mel": np.fromfile(f"{prefix}.mel.f32", dtype=np.float32).reshape(-1, 64),
        "encoded": np.fromfile(f"{prefix}.encoded.f32", dtype=np.float32).reshape(-1, 768),
    }
    return texts, taps


def numeric_report(name, reference, actual):
    if reference.shape != actual.shape:
        return f"{name}: shape {actual.shape} != {reference.shape}"
    diff = np.abs(reference - actual)
    cosine = np.sum(reference * actual, axis=1) / (
        np.linalg.norm(reference, axis=1) * np.linalg.norm(actual, axis=1) + 1e-12
    )
    return (
        f"{name} {reference.shape}: max|diff| {diff.max():.2e}, mean|diff| {diff.mean():.2e},"
        f" min cosine {cosine.min():.6f}"
    )


def compare_context(args, context_ms, audio):
    print(f"\n== context {context_ms} ms ==")
    results = {}
    for backend in args.backends:
        results[backend] = (
            run_c(args, context_ms)
            if backend == "c"
            else run_python(backend, args, context_ms, audio)
        )
    reference = args.backends[0]
    ok = True
    for backend in args.backends[1:]:
        for head, text in results[backend][0].items():
            expected = results[reference][0][head]
            wer = word_error_rate(expected, text)
            same = text == expected
            ok &= wer <= args.max_wer
            print(
                f"{backend} vs {reference} [{head}]: WER {100 * wer:.2f}%"
                f" ({len(expected.split())} words){' identical' if same else ''}"
            )
    if "c" in results and "onnx" in results:
        for name in ("mel", "encoded"):
            print("c vs onnx " + numeric_report(name, results["onnx"][1][name], results["c"][1][name]))
    return ok


def parse_args(argv=None):
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--wav", required=True, help="16 kHz mono wav")
    parser.add_argument("--model-dir", default=str(ROOT / "model"))
    parser.add_argument("--onnx-dir", default=str(ROOT / "onnx"))
    parser.add_argument("--bin", default=str(ROOT / "build" / "gigaam-v4-rnnt.gigaam"))
    parser.add_argument("--bench", default=str(ROOT / "build" / "gigaam_bench"))
    parser.add_argument("--work-dir", default=str(ROOT / "out"))
    parser.add_argument("--contexts", type=int, nargs="+", default=[640])
    parser.add_argument(
        "--backends", nargs="+", choices=("torch", "onnx", "c"), default=["torch", "onnx", "c"]
    )
    parser.add_argument("--max-wer", type=float, default=0.0, help="fail above this WER")
    return parser.parse_args(argv)


def main(argv=None):
    args = parse_args(argv)
    Path(args.work_dir).mkdir(parents=True, exist_ok=True)
    audio = load_wav(args.wav)
    ok = all([compare_context(args, context, audio) for context in args.contexts])
    print("\nRESULT: " + ("PASS" if ok else "FAIL"))
    raise SystemExit(0 if ok else 1)


if __name__ == "__main__":
    main()