Download source/shruti_coreml/benchmark.py from bingokingooo/shruti-coreml: direct link, hf CLI and curl.
- Browser
- Download file 4.63 kB
-
https://huggingface.co/bingokingooo/shruti-coreml/resolve/main/source/shruti_coreml/benchmark.py
- Command line
-
hf download hf://bingokingooo/shruti-coreml/source/shruti_coreml/benchmark.py
-
curl -L -o benchmark.py https://huggingface.co/bingokingooo/shruti-coreml/resolve/main/source/shruti_coreml/benchmark.py
4.63 kB
| """Run native Cactus and Core ML against identical 16 kHz PCM and references.""" | |
| import argparse | |
| import hashlib | |
| import importlib.metadata | |
| import json | |
| import os | |
| import platform | |
| import time | |
| from pathlib import Path | |
| import coremltools as ct | |
| import numpy as np | |
| from .runtime import CoreMLShruti, _upstream | |
| from .score import score_lattices, score_paired | |
| from .sources import ROOT, model_inputs | |
| def run(model_code, manifest, directory, language, limit, silence, compute): | |
| if limit is not None and limit < 1: | |
| raise ValueError("Limit must be positive") | |
| os.environ.setdefault("CACTUS_TELEMETRY", "0") | |
| os.environ.setdefault("NEEDLE_TELEMETRY", "0") | |
| from cactus import Whistle | |
| directory.mkdir(parents=True, exist_ok=True) | |
| source = model_inputs(model_code) | |
| native = Whistle(weights=str(next(source.glob("*.cact")))) | |
| coreml = CoreMLShruti(ROOT / "build" / model_code, getattr(ct.ComputeUnit, compute)) | |
| if silence: | |
| clips = [{"id": f"silence-{i}", "reference": ""} for i in range(100)] | |
| else: | |
| clips = [json.loads(line) for line in manifest.read_text().splitlines()] | |
| if limit: | |
| clips = clips[:limit] | |
| metadata = { | |
| "hardware": platform.machine(), "system": platform.platform(), | |
| "baseline_distribution": importlib.metadata.version("cactus-compute"), | |
| "coremltools": ct.__version__, "language": language, "model": model_code, | |
| "compute": compute, "silence_seed": 42 if silence else None, | |
| "manifest_sha256": None if silence else hashlib.sha256(manifest.read_bytes()).hexdigest(), | |
| "requested_clips": len(clips), "source": coreml.meta["source"], | |
| } | |
| (directory / "run.json").write_text(json.dumps(metadata, ensure_ascii=False, indent=2) + "\n") | |
| rows = [] | |
| rng = np.random.default_rng(42) | |
| with (directory / "clips.jsonl").open("w", buffering=1) as out: | |
| for idx, clip in enumerate(clips): | |
| if silence: | |
| pcm = np.zeros(64000, np.float32) if idx < 50 else rng.normal(0, 0.003, 64000).astype(np.float32) | |
| else: | |
| path = manifest.parent / clip["audio"] | |
| if "audio_sha256" in clip and hashlib.sha256(path.read_bytes()).hexdigest() != clip["audio_sha256"]: | |
| raise ValueError(f"Mismatched fixture: {path}") | |
| pcm = _upstream.read_audio(str(path)) | |
| row = {key: value for key, value in clip.items() if key != "audio"} | |
| row["audio_seconds"] = len(pcm) / 16000 | |
| variants = [("baseline", native), ("coreml", coreml)] | |
| if idx % 2: | |
| variants.reverse() | |
| for key, engine in variants: | |
| start = time.perf_counter() | |
| result = engine.transcribe(pcm, language=language) | |
| row[key] = { | |
| "text": result["text"], "language": result["language"], | |
| "seconds": time.perf_counter() - start, | |
| } | |
| out.write(json.dumps(row, ensure_ascii=False) + "\n") | |
| rows.append(row) | |
| if (idx + 1) % 25 == 0: | |
| print(f"{model_code}: processed {idx + 1}/{len(clips)} clips", flush=True) | |
| lattice = all("lattice" in row for row in rows) | |
| results = score_lattices(rows) if lattice else score_paired(rows) | |
| if not lattice and all("conversation" in row for row in rows): | |
| results["conversation_bootstrap"] = score_paired(rows, cluster_key="conversation") | |
| seconds = sum(row["audio_seconds"] for row in rows) | |
| if seconds: | |
| for key in ("baseline", "coreml"): | |
| results[key + "_wall_seconds"] = sum(row[key]["seconds"] for row in rows) | |
| results[key + "_real_time_factor"] = results[key + "_wall_seconds"] / seconds | |
| print(json.dumps(results, ensure_ascii=False, indent=2), flush=True) | |
| (directory / "summary.json").write_text(json.dumps(results, ensure_ascii=False, indent=2) + "\n") | |
| def main(): | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument("model") | |
| mode = parser.add_mutually_exclusive_group(required=True) | |
| mode.add_argument("--manifest", type=Path) | |
| mode.add_argument("--silence", action="store_true") | |
| parser.add_argument("--language") | |
| parser.add_argument("--limit", type=int) | |
| parser.add_argument("--output", type=Path, required=True) | |
| parser.add_argument("--compute", choices=("CPU_ONLY", "CPU_AND_NE", "CPU_AND_GPU", "ALL"), default="CPU_ONLY") | |
| args = parser.parse_args() | |
| run(args.model, args.manifest, args.output, args.language, args.limit, args.silence, args.compute) | |
| if __name__ == "__main__": | |
| main() | |