Spaces:
Running
Running
Download evaluate.py from Banafo/KrokoMusci-OpenASR: direct link, hf CLI and curl.
- Browser
- Download file 14.6 kB
-
https://huggingface.co/spaces/Banafo/KrokoMusci-OpenASR/resolve/main/evaluate.py
- Command line
-
hf download hf://spaces/Banafo/KrokoMusci-OpenASR/evaluate.py
-
curl -L -o evaluate.py https://huggingface.co/spaces/Banafo/KrokoMusci-OpenASR/resolve/main/evaluate.py
14.6 kB
| #!/usr/bin/env python3 | |
| """Run the pinned Kroko evaluation suite, preserving each completed split. | |
| --dry-run requires only Python's standard library and never downloads or runs a model. | |
| Full and smoke runs must use separate, new output directories. | |
| """ | |
| import argparse | |
| from datetime import datetime, timezone | |
| import hashlib | |
| import importlib.metadata | |
| import json | |
| import math | |
| import os | |
| from pathlib import Path | |
| import re | |
| import subprocess | |
| import sys | |
| ROOT = Path(__file__).resolve().parent | |
| NONDEFAULT_PUBLIC = {"librispeech_clean", "librispeech_other", "urgent2024_clean"} | |
| def now(): | |
| return datetime.now(timezone.utc).isoformat() | |
| def write_json(path, value): | |
| temporary = path.with_suffix(path.suffix + ".tmp") | |
| temporary.write_text(json.dumps(value, indent=2, sort_keys=True) + "\n") | |
| temporary.replace(path) | |
| def parse_args(argv=None): | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument("--model-id", required=True) | |
| parser.add_argument("--model-revision", required=True) | |
| parser.add_argument("--output-dir", type=Path, required=True) | |
| parser.add_argument("--mode", choices=("smoke", "full"), default="smoke") | |
| parser.add_argument("--batch-size", type=int) | |
| parser.add_argument("--workers", type=int) | |
| parser.add_argument("--beam", type=int, default=6, | |
| help="RNN-T beam width; must match the exported ONNX bundle") | |
| parser.add_argument("--precision", choices=("fp16", "fp32", "bf16"), default="fp16") | |
| parser.add_argument("--min-audio-seconds", type=float, default=0.1) | |
| parser.add_argument("--opt-audio-seconds", type=float, default=10.0) | |
| parser.add_argument("--max-audio-seconds", type=float, default=40.0) | |
| parser.add_argument("--warmup-steps", type=int, default=5) | |
| parser.add_argument("--engine-cache", type=Path, default=Path("/tmp/kroko-engines")) | |
| parser.add_argument("--dry-run", action="store_true") | |
| args = parser.parse_args(argv) | |
| include_voicecode = os.environ.get("KM_INCLUDE_VOICECODE", "0") | |
| if include_voicecode not in ("0", "1"): | |
| parser.error("KM_INCLUDE_VOICECODE must be 0 or 1") | |
| args.include_voicecode = args.mode == "full" and include_voicecode == "1" | |
| if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.-]*/[A-Za-z0-9][A-Za-z0-9_.-]*", args.model_id): | |
| parser.error("--model-id must be owner/repository") | |
| if not re.fullmatch(r"[0-9a-f]{40}", args.model_revision): | |
| parser.error("--model-revision must be an immutable 40-character Hub commit SHA") | |
| args.batch_size = args.batch_size if args.batch_size is not None else (2 if args.mode == "smoke" else 256) | |
| args.workers = args.workers if args.workers is not None else (1 if args.mode == "smoke" else 3) | |
| profile = (args.min_audio_seconds, args.opt_audio_seconds, args.max_audio_seconds) | |
| if not all(math.isfinite(x) and x > 0 for x in profile) or tuple(sorted(profile)) != profile: | |
| parser.error("Expected finite 0 < min <= opt <= max audio duration") | |
| if args.batch_size < 1 or args.workers < 1 or args.warmup_steps < 1 or args.beam < 1: | |
| parser.error("Batch size, workers, beam and warmup steps must be positive") | |
| args.output_dir = args.output_dir.resolve() | |
| args.engine_cache = args.engine_cache.resolve() | |
| return args | |
| def load_suite(): | |
| suite = json.loads((ROOT / "suite.json").read_text()) | |
| rows = suite["datasets"] | |
| if len(rows) != 10 or len({row["id"] for row in rows}) != 10: | |
| raise ValueError("The complete suite must contain ten unique test sets") | |
| all_rows = rows + suite.get("optional_datasets", []) | |
| if len({row["id"] for row in all_rows}) != len(all_rows): | |
| raise ValueError("Dataset IDs must also be unique across optional test sets") | |
| for row in all_rows: | |
| if not re.fullmatch(r"[0-9a-f]{40}", suite["dataset_revisions"][row["repo"]]): | |
| raise ValueError("Every evaluation dataset must have an immutable revision") | |
| return suite | |
| def build_plan(args): | |
| suite = load_suite() | |
| rows = suite["datasets"] | |
| if args.mode == "smoke": | |
| rows = [row for row in rows if row["id"] == "librispeech_clean"] | |
| elif getattr(args, "include_voicecode", False): | |
| voicecode, = [row for row in suite["optional_datasets"] if row["id"] == "voice_code_bench"] | |
| rows = [rows[0], voicecode, *rows[1:]] | |
| plan = [] | |
| for row in rows: | |
| command = [sys.executable, str(ROOT / "run_eval.py"), | |
| "--model-id", args.model_id, "--model-revision", args.model_revision, | |
| "--report-name", args.model_id + f" (fast-gpu-asr, RNN-T beam {args.beam})", | |
| "--model-family", "zipformer", | |
| "--decoder-type", "transducer_modified_beam_search", "--beam", str(args.beam), | |
| "--blank-penalty", "0.0", "--batch-size", str(args.batch_size), | |
| "--workers", str(args.workers), "--precision", args.precision, | |
| "--device", "0", "--optimization-level", "5", | |
| "--min-audio-seconds", str(args.min_audio_seconds), | |
| "--opt-audio-seconds", str(args.opt_audio_seconds), | |
| "--max-audio-seconds", str(args.max_audio_seconds), | |
| "--warmup-steps", str(args.warmup_steps), | |
| "--engine-cache", str(args.engine_cache), | |
| "--dataset-path", row["repo"], "--dataset", row["config"], | |
| "--dataset-revision", suite["dataset_revisions"][row["repo"]], | |
| "--split", row["split"], "--max-eval-samples", "3" if args.mode == "smoke" else "-1"] | |
| plan.append({"dataset": row, "command": command, "cwd": str(args.output_dir / row["id"])}) | |
| return plan | |
| def validate_manifest(rows, metadata, expected_revision): | |
| if not rows or len(rows) != metadata["samples"]: | |
| raise ValueError("Manifest count does not match the evaluator's filtered input count") | |
| if metadata["revision"] != expected_revision: | |
| raise ValueError("Evaluated model revision differs from the requested release") | |
| for row in rows: | |
| if not isinstance(row.get("text"), str) or not isinstance(row.get("pred_text"), str): | |
| raise ValueError("Manifest must retain raw reference and prediction strings") | |
| for key in ("duration", "time"): | |
| if not isinstance(row.get(key), (int, float)) or not math.isfinite(row[key]) or row[key] <= 0: | |
| raise ValueError(f"Invalid measured {key}") | |
| if any("parent_id" in row for row in rows): | |
| parents = {} | |
| for row in rows: | |
| if "parent_id" not in row or "chunk_index" not in row: | |
| raise ValueError("Incomplete chunk metadata") | |
| parents.setdefault(row["parent_id"], []).append(row) | |
| for chunks in parents.values(): | |
| if sorted(row["chunk_index"] for row in chunks) != list(range(len(chunks))): | |
| raise ValueError("Missing or duplicate chunks in an Earnings22 session") | |
| if len({row["text"] for row in chunks}) != 1: | |
| raise ValueError("Conflicting parent transcripts in an Earnings22 session") | |
| seconds = sum(row["duration"] for row in rows) | |
| elapsed = sum(row["time"] for row in rows) | |
| if not math.isclose(seconds, metadata["audio_seconds"], rel_tol=1e-8, abs_tol=1e-5): | |
| raise ValueError("Audio-duration metadata differs from the result manifest") | |
| return seconds, elapsed | |
| def score_split(item, model_revision): | |
| from kaldialign import batch_error_rate | |
| from normalizer import EnglishTextNormalizer | |
| from normalizer.eval_utils import read_manifest, merge_chunked_manifest | |
| result_dir = Path(item["cwd"]) / "results" | |
| manifests = list(result_dir.glob("*.jsonl")) | |
| if len(manifests) != 1: | |
| raise ValueError(f"Expected exactly one result manifest: {result_dir}") | |
| manifest = manifests[0] | |
| metadata = json.loads(manifest.with_suffix(".metadata.json").read_text()) | |
| rows = read_manifest(manifest) | |
| seconds, elapsed = validate_manifest(rows, metadata, model_revision) | |
| sessions = merge_chunked_manifest(rows) | |
| if item["dataset"]["id"] == "voice_code_bench": | |
| from normalizer.voice_code_data import DATASET_REVISION, RECORDINGS | |
| if (len(sessions) != RECORDINGS or len({row.get("audio_id") for row in sessions}) != RECORDINGS | |
| or any(not row.get("audio_id") or row.get("voice_code_bench_revision") != DATASET_REVISION | |
| for row in sessions)): | |
| raise ValueError("VoiceCodeBench requires one prediction for each of its 300 pinned recordings") | |
| normalizer = EnglishTextNormalizer() | |
| refs = [tuple(normalizer(row["text"]).split()) for row in sessions] | |
| predictions = [tuple(normalizer(row["pred_text"]).split()) for row in sessions] | |
| errors = batch_error_rate(refs, predictions, merge_compounds=True) | |
| wer = float(errors["err_rate"]) * 100 | |
| if not math.isfinite(wer) or wer < 0: | |
| raise ValueError("Invalid WER result") | |
| with manifest.open("rb") as handle: | |
| manifest_sha = hashlib.file_digest(handle, "sha256").hexdigest() | |
| return {**item["dataset"], "WER_percent": wer, "RTFx": seconds / elapsed, | |
| "input_clips": len(rows), "scored_sessions": len(sessions), | |
| "audio_seconds": seconds, "inference_seconds": elapsed, | |
| "manifest": str(manifest.relative_to(Path(item["cwd"]).parent)), | |
| "manifest_sha256": manifest_sha, "hardware": metadata["hardware"], | |
| "export_settings": metadata["export_settings"]} | |
| def execute(args, *, release_check=None, run_command=None, score=None): | |
| plan = build_plan(args) | |
| if args.dry_run: | |
| print(json.dumps({"mode": args.mode, "jobs": plan}, indent=2)) | |
| return | |
| if args.output_dir.exists(): | |
| raise ValueError("Output directory already exists; select a new run ID to preserve prior results") | |
| args.output_dir.mkdir(parents=True) | |
| if release_check is None: | |
| from preflight_model import check_release | |
| release_check = check_release | |
| run_command = run_command or subprocess.run | |
| score = score or score_split | |
| status = {"state": "preflight", "mode": args.mode, "started_at": now(), | |
| "model_id": args.model_id, "model_revision": args.model_revision, | |
| "completed_datasets": [], "expected_datasets": len(plan)} | |
| write_json(args.output_dir / "status.json", status) | |
| write_json(args.output_dir / "plan.json", {"suite": load_suite(), "jobs": plan}) | |
| try: | |
| receipt = release_check(args.model_id, args.model_revision) | |
| write_json(args.output_dir / "model-release.json", receipt) | |
| if receipt.get("language") != "en": | |
| raise ValueError("This ten-set suite requires an English model; other languages need their own datasets and normalization") | |
| if receipt.get("export", {}).get("beam") != args.beam: | |
| raise ValueError("Requested beam does not match the exported ONNX bundle") | |
| packages = {} | |
| for name in ("torch", "fast-gpu-asr", "tensorrt-cu13", "tensorrt-cu13-bindings", "cupy-cuda13x", "datasets", "huggingface-hub", "kaldialign"): | |
| try: | |
| packages[name] = importlib.metadata.version(name) | |
| except importlib.metadata.PackageNotFoundError: | |
| packages[name] = None | |
| write_json(args.output_dir / "environment.json", {"python": sys.version, "packages": packages}) | |
| results = [] | |
| for item in plan: | |
| target = Path(item["cwd"]) | |
| target.mkdir() | |
| status.update(state="evaluating", current_dataset=item["dataset"]["id"]) | |
| write_json(args.output_dir / "status.json", status) | |
| with (target / "evaluation.log").open("w") as log: | |
| run_command(item["command"], cwd=target, stdout=log, stderr=subprocess.STDOUT, | |
| env={**os.environ, "PYTHONUNBUFFERED": "1"}, check=True) | |
| row = score(item, args.model_revision) | |
| write_json(target / "score.json", row) | |
| results.append(row) | |
| status["completed_datasets"].append(row["id"]) | |
| write_json(args.output_dir / "status.json", status) | |
| print(f"{row['id']}: WER {row['WER_percent']:.4f}%, RTFx {row['RTFx']:.2f}", flush=True) | |
| if len(results) != len(plan): | |
| raise ValueError("A partial suite cannot be marked complete") | |
| historical_ids = {row["id"] for row in load_suite()["datasets"]} | |
| historical = [row for row in results if row["id"] in historical_ids] | |
| seconds = sum(row["audio_seconds"] for row in historical) | |
| elapsed = sum(row["inference_seconds"] for row in historical) | |
| summary = {"model_id": args.model_id, "model_revision": args.model_revision, | |
| "mode": args.mode, "complete": True, "completed_at": now(), | |
| "scope": "ten public test sets" if args.mode == "full" else "three-clip smoke test; not a benchmark", | |
| "official_leaderboard_result": False, "datasets": results, | |
| "macro_WER_percent": sum(row["WER_percent"] for row in historical) / len(historical), | |
| "pooled_RTFx": seconds / elapsed, "audio_seconds": seconds, "inference_seconds": elapsed, | |
| "beam": args.beam, | |
| "notes": f"RNN-T beam {args.beam}. This explicitly defined public-suite mean is not the live leaderboard default aggregate."} | |
| if args.mode == "full": | |
| default_public = [row for row in historical if row["id"] not in NONDEFAULT_PUBLIC] | |
| if len(default_public) != 7: | |
| raise ValueError("Expected seven default public Open ASR splits") | |
| summary["open_asr_public"] = { | |
| name: { | |
| "macro_WER_percent": math.fsum(round(row["WER_percent"], 2) for row in rows) / len(rows), | |
| "pooled_RTFx": math.fsum(row["audio_seconds"] for row in rows) | |
| / math.fsum(row["inference_seconds"] for row in rows), | |
| } | |
| for name, rows in (("default_seven", default_public), ("all_ten", historical)) | |
| } | |
| write_json(args.output_dir / "summary.json", summary) | |
| status.update(state="complete", finished_at=now()) | |
| status.pop("current_dataset", None) | |
| write_json(args.output_dir / "status.json", status) | |
| except BaseException as error: | |
| # Error details can contain authenticated URLs: retain type and dataset only. | |
| status.update(state="failed", error_type=type(error).__name__, finished_at=now()) | |
| write_json(args.output_dir / "status.json", status) | |
| raise | |
| def main(argv=None): | |
| execute(parse_args(argv)) | |
| if __name__ == "__main__": | |
| main() | |