"""The exported graph must reproduce SAVA's published reference outputs. Run ``export.py`` and ``quantize.py`` first; ``fixtures/`` holds the recording and expected logits from the SAVA repository (tests/fixtures). """ from pathlib import Path import numpy as np import pytest import soundfile as sf import sava_onnx BUILD = Path(__file__).parent / "build" FIXTURES = Path(__file__).parent / "fixtures" def _logits(model: Path) -> tuple[np.ndarray, np.ndarray, np.ndarray]: if not model.exists(): pytest.skip(f"{model.name} has not been built") audio, _ = sf.read(FIXTURES / "speech.wav", dtype="float32") session = sava_onnx.Session(str(model)) frames = [session.step(audio[i : i + 640]) for i in range(0, audio.size - 639, 640)] return tuple(np.array(column) for column in zip(*frames)) def test_full_precision_export_matches_the_reference_logits(): expected = np.load(FIXTURES / "speech_expected.npz") speech, lookahead, turn = _logits(BUILD / "sava.onnx") n = speech.size # 2e-4 is the tolerance the SAVA repository holds its own streaming path to. assert np.abs(speech - expected["speech"][:n]).max() < 2e-4 assert np.abs(turn - expected["turn"][:n]).max() < 2e-4 lag = sava_onnx.LAG_FRAMES assert np.abs(lookahead[lag:] - expected["lookahead"][lag:n]).max() < 2e-4 assert np.all(lookahead[:lag] == -30.0) # masked: they would judge frames before the stream def test_int8_version_agrees_with_the_reference_on_nearly_every_frame(): expected = np.load(FIXTURES / "speech_expected.npz") speech, lookahead, turn = _logits(BUILD / "sava.int8.onnx") n, lag = speech.size, sava_onnx.LAG_FRAMES speech_flips = ((lookahead[lag:] > 0) != (expected["lookahead"][lag:n] > 0)).mean() turn_flips = ((turn[:, 0] > 0) != (expected["turn"][:n, 0] > 0)).mean() assert speech_flips < 0.01 and turn_flips < 0.01 def test_session_streams_any_chunk_size_to_the_same_answer(): if not (BUILD / "sava.onnx").exists(): pytest.skip("sava.onnx has not been built") audio, _ = sf.read(FIXTURES / "speech.wav", dtype="float32") audio = audio[: 16000 * 4] whole = sava_onnx.Session(str(BUILD / "sava.onnx")) a = np.concatenate([whole.push(audio).speech, whole.flush().speech]) pieces = sava_onnx.Session(str(BUILD / "sava.onnx")) parts = [pieces.push(audio[i : i + 1000]).speech for i in range(0, audio.size, 1000)] b = np.concatenate([*parts, pieces.flush().speech]) assert a.shape == b.shape and np.array_equal(a, b) with pytest.raises(RuntimeError): pieces.push(audio)