"""Measures the streaming model against today's Muaalem mini on the test windows (windows.py). For each window, today's model decodes it at full context (what the app does now) and the streaming model decodes it chunk by chunk from an empty state (as if listening started at the window's start). Reported: how many units the streaming model gets the same as today's (1 - edit distance / today's length), per chunk size and per kind of window. Also writes each decode as a TSV in the format of the app's recordings test (kind, surah, ayah, reciter, units), for the app-side check later. python eval_streaming.py --cache DIR --stats norm_stats.json \\ [--checkpoint ckpt.pt] [--chunks 16 32 64] [--other DIR] [--out DIR] """ from __future__ import annotations import argparse import time from collections import defaultdict from pathlib import Path import torch from features import Fbank, NormStats, running_normalize, stack_pairs, whole_clip_normalize from streaming_model import StreamingMuaalem, download, load_muaalem, vocab from units import edit_distance, split_units from windows import windows def load_streaming(checkpoint: Path | None, left: int) -> StreamingMuaalem: model = StreamingMuaalem(load_muaalem(download()), left=left) if checkpoint: state = torch.load(checkpoint, map_location="cpu", weights_only=True) model.load_state_dict(state.get("ema", state.get("model", state))) return model.eval() def letters(ids, chars: list[str]) -> str: out, prev = [], None for i in ids: i = int(i) if i != prev and i != 0: out.append(chars[i]) prev = i return "".join(out) @torch.no_grad() def main() -> None: parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument("--cache", type=Path, required=True, help="everyayah MP3 cache") parser.add_argument("--stats", type=Path, required=True, help="norm_stats.json from prepare_data.py") parser.add_argument("--checkpoint", type=Path) parser.add_argument("--chunks", type=int, nargs="+", default=[16, 32, 64]) parser.add_argument("--left", type=int, default=192) parser.add_argument("--other", type=Path, help="non-recitation clips (*.pcm)") parser.add_argument("--out", type=Path, default=Path("results")) args = parser.parse_args() snapshot = download() chars = vocab(snapshot) today = StreamingMuaalem(load_muaalem(snapshot)).eval() stream = load_streaming(args.checkpoint, args.left) stats = NormStats.load(args.stats) fbank = Fbank() rows = defaultdict(list) # name -> TSV lines same = defaultdict(lambda: defaultdict(lambda: [0, 0])) # chunk -> kind -> [errors, total] timing = defaultdict(list) for kind, surah, ayah, source, samples in windows(args.cache, other=args.other): audio = torch.from_numpy(samples.astype("float32") / 32768)[None] raw = fbank(audio) n = raw.shape[1] - raw.shape[1] % 2 full = stack_pairs(whole_clip_normalize(raw[:, :n], torch.tensor([n]))) logits, _ = today(full, torch.tensor([full.shape[1]]), chunk=full.shape[1], left=0) reference = split_units(letters(logits[0].argmax(-1), chars)) rows["today"].append(f"{kind}\t{surah}\t{ayah}\t{source}\t{' '.join(reference) or '-'}") for chunk in args.chunks: # Only whole chunks: the app decodes a chunk once it has all of it. m = n // (2 * chunk) * (2 * chunk) if m == 0: # shorter than one chunk: nothing decoded yet got = [] else: features = stack_pairs(running_normalize(raw[:, :m], torch.tensor([m]), 2 * chunk, stats)) started = time.perf_counter() logits, _ = stream(features, torch.tensor([features.shape[1]]), chunk=chunk) timing[chunk].append((time.perf_counter() - started) / (m // (2 * chunk))) got = split_units(letters(logits[0].argmax(-1), chars)) rows[f"chunk{chunk}"].append(f"{kind}\t{surah}\t{ayah}\t{source}\t{' '.join(got) or '-'}") if kind != "none": errors = edit_distance(reference, got) for key in (kind, "all"): same[chunk][key][0] += errors same[chunk][key][1] += len(reference) print(f"{len(rows['today'])} {kind} {surah}:{ayah} {source}", flush=True) args.out.mkdir(parents=True, exist_ok=True) for name, lines in rows.items(): (args.out / f"decodes_{name}.tsv").write_text("\n".join(lines) + "\n", encoding="utf-8") label = args.checkpoint.name if args.checkpoint else "untrained" report = [f"streaming model: {label}, {args.left} frames remembered"] for chunk in args.chunks: parts = ", ".join( f"{key} {100 * (1 - e / t):.1f}%" for key, (e, t) in sorted(same[chunk].items()) if t ) ms = 1000 * sum(timing[chunk]) / len(timing[chunk]) report.append(f"chunk {chunk} ({chunk / 50:.2f} s): units same as today: {parts}; {ms:.0f} ms per chunk (batch, this machine)") text = "\n".join(report) (args.out / f"report_{label}.txt").write_text(text + "\n") print(text) if __name__ == "__main__": main()