amharic-asr-benchmark / scripts /bootstrap_ci.py
Chapimenge's picture
Benchmark results, method, limitations and the failure log
84bf7b1 verified
Raw
History Blame
3.15 kB
#!/usr/bin/env python3
"""Bootstrap confidence intervals and paired significance for benchmark CERs.
A leaderboard that reports 0.0946 against 0.0991 without saying whether that gap
survives resampling is not a benchmark. And the naive check is wrong: marginal
confidence intervals for these two models OVERLAP, yet the difference is real,
because both are scored on the same clips. Pairing is what makes it visible.
"""
from __future__ import annotations
import csv
import glob
import json
import random
import re
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
import geez_eval # noqa: E402
import jiwer # noqa: E402
TAG = re.compile(r"^\s*\[[A-Z]{2,4}\]\s*")
B = 2000
def norm(t: str) -> str:
return geez_eval.normalize(TAG.sub("", t or ""), fold_geez=True)
def per_clip(refs, hyps):
"""Edit count and reference length per clip, so we resample clips."""
out = []
for r, h in zip(refs, hyps):
R, H = norm(r), norm(h)
if not R:
continue
out.append((float(jiwer.cer(R, H)) * len(R), len(R)))
return out
def analyse(refs, model_hyps: dict[str, list[str]], seed: int = 11) -> dict:
models = {m: per_clip(refs, h) for m, h in model_hyps.items()}
cer = {m: sum(e for e, _ in v) / sum(n for _, n in v)
for m, v in models.items()}
order = sorted(cer, key=cer.get)
n = len(models[order[0]])
rng = random.Random(seed)
idx = [[rng.randrange(n) for _ in range(n)] for _ in range(B)]
samples = {m: [sum(models[m][i][0] for i in ix) / sum(models[m][i][1] for i in ix)
for ix in idx] for m in order}
out = {"n_clips": n, "bootstrap_resamples": B, "models": {}, "pairs": []}
for m in order:
s = sorted(samples[m])
out["models"][m] = {"cer": cer[m], "ci_low": s[int(.025 * B)],
"ci_high": s[int(.975 * B)]}
for a, b in zip(order, order[1:]):
d = sorted(x - y for x, y in zip(samples[a], samples[b]))
out["pairs"].append({
"better": a, "worse": b, "mean_diff": sum(d) / B,
"ci_low": d[int(.025 * B)], "ci_high": d[int(.975 * B)],
"p_not_better": sum(1 for x in d if x >= 0) / B,
"distinguishable": d[int(.975 * B)] < 0,
})
return out
def main() -> None:
rel = Path(sys.argv[1] if len(sys.argv) > 1 else
"build/am-v0.2.0")
hyp_dir = sys.argv[2] if len(sys.argv) > 2 else "/tmp/benchres"
refs = [r["sentence"] for r in
csv.DictReader((rel / "metadata.csv").open(encoding="utf-8"))
if r["split"] == "test"]
hyps = {}
for f in sorted(glob.glob(f"{hyp_dir}/hyp*.json")):
d = json.load(open(f))
# A 440-token rerun supersedes the truncated pass for the same model.
if d["model"] in hyps and not Path(f).name.startswith("hyp440"):
continue
hyps[d["model"]] = d["hyps"]
res = analyse(refs, hyps)
Path(f"{hyp_dir}/bootstrap.json").write_text(json.dumps(res, indent=2))
print(json.dumps(res, indent=2)[:1500])
if __name__ == "__main__":
main()