Download scripts/compare_backends.py from eschmidbauer/GigaAM-v4-c: direct link, hf CLI and curl.
- Browser
- Download file 5.58 kB
-
https://huggingface.co/eschmidbauer/GigaAM-v4-c/resolve/main/scripts/compare_backends.py
- Command line
-
hf download hf://eschmidbauer/GigaAM-v4-c/scripts/compare_backends.py
-
curl -L -o compare_backends.py https://huggingface.co/eschmidbauer/GigaAM-v4-c/resolve/main/scripts/compare_backends.py
5.58 kB
| """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() | |