Download engine/bench/hfdi_speed.py from decisionmodels/REAX-1.4: direct link, hf CLI and curl.
- Browser
- Download file 11.5 kB
-
https://huggingface.co/decisionmodels/REAX-1.4/resolve/main/engine/bench/hfdi_speed.py
- Command line
-
hf download hf://decisionmodels/REAX-1.4/engine/bench/hfdi_speed.py
-
curl -L -o hfdi_speed.py https://huggingface.co/decisionmodels/REAX-1.4/resolve/main/engine/bench/hfdi_speed.py
11.5 kB
| #!/usr/bin/env python3 | |
| # SPDX-License-Identifier: MIT | |
| """HF Decision Index speed + decision-agreement bench for reax14 configs (job reax-engine-hfdi-speed-20261125). | |
| run one config over a fixed row list, one request at a time, CUDA-synchronized wall time per request (the maintainers' | |
| rule: single process, one request at a time; median, mean and p80 <= 1,000 ms). Writes one JSON line per row: | |
| {id, ms, status, answers: {qid: {option: p}}, parts_ms}. Startup, loading, graph capture and warm-up excluded. | |
| compare two run files on the rows both answered: per field argmax agreement (flips), max / mean |dp|, plus latency stats. | |
| sample a fixed sample of the public suite: --mode uniform (REAX 1.3's "uniform 1,000-call sample") or proportional | |
| (per benchmark family, largest remainders), seeded. | |
| python bench/hfdi_speed.py run --config reax14/reax14f-flash-fp8.json --model /model --rows lat.jsonl --out runs/x.jsonl \ | |
| [--warmup-rows warm.jsonl] [--limit N] | |
| python bench/hfdi_speed.py compare runs/ref.jsonl runs/x.jsonl [--out cmp.json] | |
| python bench/hfdi_speed.py sample --rows shard0.jsonl.gz shard1.jsonl.gz ... --n 1000 --seed 20261125 --out lat.jsonl | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import gzip | |
| import hashlib | |
| import json | |
| import math | |
| import random | |
| import sys | |
| import time | |
| from collections import defaultdict | |
| from pathlib import Path | |
| HERE = Path(__file__).resolve().parent | |
| ROOT = HERE.parent | |
| HF_LIMIT_MS = 1000.0 | |
| def percentile(xs, q): | |
| xs = sorted(xs) | |
| pos = (len(xs) - 1) * q / 100.0 | |
| lo, hi = math.floor(pos), math.ceil(pos) | |
| return xs[lo] + (xs[hi] - xs[lo]) * (pos - lo) | |
| def stats(ms): | |
| if not ms: | |
| return {"n": 0} | |
| n = len(ms) | |
| s = {"n": n, "median_ms": percentile(ms, 50), "mean_ms": math.fsum(ms) / n, "p80_ms": percentile(ms, 80), | |
| "p95_ms": percentile(ms, 95), "p99_ms": percentile(ms, 99), "max_ms": max(ms), "min_ms": min(ms), | |
| "seq_requests_per_s": 1000.0 * n / math.fsum(ms)} | |
| s["hf_rule_pass"] = s["median_ms"] <= HF_LIMIT_MS and s["mean_ms"] <= HF_LIMIT_MS and s["p80_ms"] <= HF_LIMIT_MS | |
| return s | |
| def load_rows(paths): | |
| rows = [] | |
| for p in paths: | |
| p = Path(p) | |
| opener = gzip.open if p.suffix == ".gz" else open | |
| with opener(p, "rt", encoding="utf-8") as f: | |
| rows.extend(json.loads(line) for line in f if line.strip()) | |
| return rows | |
| def row_id(r): | |
| return r.get("id") or r.get("_evaluation", {}).get("run_id") | |
| def probs_of(answer): | |
| """{option: p} of one kit answer (choice: probabilities; noul: {false, true}; score: probabilities).""" | |
| if answer.get("type") == "noul": | |
| p = float(answer["noul"]) | |
| return {"false": 1.0 - p, "true": p} | |
| return {str(k): float(v) for k, v in (answer.get("probabilities") or {}).items()} | |
| # ------------------------------------------------------------------------------------------------ run | |
| def cmd_run(a): | |
| sys.path.insert(0, str(ROOT / "reax14")) | |
| sys.path.insert(0, str(ROOT)) | |
| from reax14_engine import Reax14Engine | |
| import torch | |
| rows = load_rows([a.rows]) | |
| if a.limit: | |
| rows = rows[: a.limit] | |
| t0 = time.perf_counter() | |
| eng = Reax14Engine(config=a.config, model=a.model, **({"warmup_rows": a.warmup_rows} if a.warmup_rows else {})) | |
| load_s = time.perf_counter() - t0 | |
| print(json.dumps({"after_load": {"allocated_gib": round(torch.cuda.memory_allocated() / 2**30, 2), | |
| "reserved_gib": round(torch.cuda.memory_reserved() / 2**30, 2), | |
| "peak_allocated_gib": round(torch.cuda.max_memory_allocated() / 2**30, 2)}}), flush=True) | |
| eng.warmup() | |
| torch.cuda.synchronize() | |
| torch.cuda.reset_peak_memory_stats() | |
| out = Path(a.out) | |
| out.parent.mkdir(parents=True, exist_ok=True) | |
| ms_ok = [] | |
| run_peak = 0 | |
| with out.open("w") as f: | |
| for r in rows: | |
| torch.cuda.synchronize() | |
| torch.cuda.reset_peak_memory_stats() | |
| t = time.perf_counter() | |
| status, answers, prov = "ok", None, None | |
| try: | |
| resp, prov = eng(r["state"], r["questions"]) | |
| answers = {k: probs_of(v) for k, v in resp["answers"].items()} | |
| except ValueError as exc: # kit Unsupported is a ValueError | |
| status = "unsupported:" + str(exc)[:120] | |
| torch.cuda.synchronize() | |
| ms = 1000.0 * (time.perf_counter() - t) | |
| if status == "ok": | |
| ms_ok.append(ms) | |
| run_peak = max(run_peak, torch.cuda.max_memory_allocated()) | |
| parts_ms, part_p, tokens = {}, {}, {} | |
| if isinstance(prov, dict): | |
| parts_ms = prov.get("timings_ms") or {} | |
| part_p = prov.get("part_probabilities") or {} | |
| tokens = {n: v.get("tokens") for n, v in (prov.get("parts") or {}).items() if isinstance(v, dict)} | |
| f.write(json.dumps({"id": row_id(r), "ms": ms, "status": status, "answers": answers, "parts_ms": parts_ms, | |
| "part_probabilities": part_p, "tokens": tokens, "n_questions": len(r["questions"]), | |
| "peak_alloc_gib": round(torch.cuda.max_memory_allocated() / 2**30, 2)}, | |
| default=float) + "\n") | |
| summary = {"config": a.config, "config_sha256": hashlib.sha256(Path(a.config).read_bytes()).hexdigest(), | |
| "rows": a.rows, "rows_sha256": hashlib.sha256(Path(a.rows).read_bytes()).hexdigest(), "n_rows": len(rows), | |
| "load_s": round(load_s, 1), "stats": stats(ms_ok), "peak_allocated_bytes": max(run_peak, torch.cuda.max_memory_allocated()), | |
| "peak_reserved_bytes": torch.cuda.max_memory_reserved(), "gpu": torch.cuda.get_device_name(0), | |
| "torch": torch.__version__, "parts": eng.provenance.get("parts")} | |
| Path(str(out) + ".summary.json").write_text(json.dumps(summary, indent=1, default=str)) | |
| print(json.dumps({k: summary[k] for k in ("config", "n_rows", "load_s", "stats", "peak_allocated_bytes", "peak_reserved_bytes")}, indent=1)) | |
| eng.close() | |
| # ------------------------------------------------------------------------------------------------ compare | |
| def read_run(p): | |
| return {d["id"]: d for d in (json.loads(l) for l in Path(p).read_text().splitlines() if l.strip())} | |
| def _as_probs(d): | |
| if isinstance(d, dict): | |
| return {str(k): float(v) for k, v in d.items()} | |
| return {str(i): float(v) for i, v in enumerate(d)} | |
| def _select(run, part): | |
| """Use one part's distributions (`part`) instead of the mixed answer, where the run recorded them.""" | |
| if not part: | |
| return run | |
| out = {} | |
| for i, d in run.items(): | |
| pp = (d.get("part_probabilities") or {}).get(part) | |
| if d["status"] == "ok" and pp is not None: | |
| out[i] = dict(d, answers={q: _as_probs(v) for q, v in pp.items()}) | |
| return out | |
| def cmd_compare(a): | |
| A = _select(read_run(a.ref), a.ref_part) | |
| B = _select(read_run(a.cand), a.cand_part) | |
| both = [i for i in A if i in B and A[i]["status"] == "ok" and B[i]["status"] == "ok"] | |
| fields = flips = 0 | |
| maxdp, sumdp, ndp = 0.0, 0.0, 0 | |
| flip_list, missing = [], [] | |
| for i in both: | |
| for q, pa in A[i]["answers"].items(): | |
| pb = B[i]["answers"].get(q) | |
| if pb is None or set(pa) != set(pb): | |
| missing.append((i, q)) | |
| continue | |
| fields += 1 | |
| amax_a, amax_b = max(pa, key=pa.get), max(pb, key=pb.get) | |
| dp = max(abs(pa[k] - pb[k]) for k in pa) | |
| maxdp = max(maxdp, dp) | |
| sumdp += sum(abs(pa[k] - pb[k]) for k in pa) | |
| ndp += len(pa) | |
| if amax_a != amax_b: | |
| flips += 1 | |
| top = sorted(pa.values(), reverse=True) | |
| flip_list.append({"id": i, "q": q, "ref": amax_a, "cand": amax_b, "dp": dp, | |
| "ref_margin": top[0] - (top[1] if len(top) > 1 else 0.0)}) | |
| st_a = stats([A[i]["ms"] for i in both]) | |
| st_b = stats([B[i]["ms"] for i in both]) | |
| rep = {"ref": a.ref, "cand": a.cand, "rows_both_ok": len(both), | |
| "status_mismatch": sum(1 for i in A if i in B and (A[i]["status"] == "ok") != (B[i]["status"] == "ok")), | |
| "fields": fields, "flips": flips, "agreement": (1 - flips / fields) if fields else None, | |
| "max_abs_dp": maxdp, "mean_abs_dp": sumdp / ndp if ndp else None, "missing_fields": len(missing), | |
| "flip_list": flip_list[:50], "latency_ref": st_a, "latency_cand": st_b, | |
| "speedup_mean": st_a.get("mean_ms", 0) / st_b["mean_ms"] if st_b.get("mean_ms") else None, | |
| "speedup_median": st_a.get("median_ms", 0) / st_b["median_ms"] if st_b.get("median_ms") else None} | |
| text = json.dumps(rep, indent=1) | |
| if a.out: | |
| Path(a.out).write_text(text) | |
| print(text) | |
| # ------------------------------------------------------------------------------------------------ sample | |
| def cmd_sample(a): | |
| rows = load_rows(a.rows) | |
| rows.sort(key=lambda r: str(row_id(r))) # order-independent of the shard layout | |
| rng = random.Random(a.seed) | |
| if a.mode == "uniform": | |
| out = rng.sample(rows, a.n) | |
| else: | |
| by = defaultdict(list) | |
| for r in rows: | |
| by[r.get("family") or "?"].append(r) | |
| quota = {k: a.n * len(v) / len(rows) for k, v in by.items()} | |
| take = {k: int(q) for k, q in quota.items()} | |
| for k in sorted(quota, key=lambda k: (-(quota[k] - take[k]), k))[: a.n - sum(take.values())]: | |
| take[k] += 1 | |
| out = [] | |
| for k in sorted(by): | |
| out.extend(rng.sample(by[k], min(take[k], len(by[k])))) | |
| rng.shuffle(out) | |
| keep = ("id", "family", "state", "questions") | |
| Path(a.out).write_text("".join(json.dumps({k: r[k] for k in keep if k in r}, ensure_ascii=False) + "\n" for r in out)) | |
| fam = defaultdict(int) | |
| for r in out: | |
| fam[r.get("family")] += 1 | |
| print(json.dumps({"n": len(out), "from": len(rows), "families": len(fam), "multi_question_rows": sum(len(r["questions"]) > 1 for r in out), | |
| "sha256": hashlib.sha256(Path(a.out).read_bytes()).hexdigest()})) | |
| def main(argv=None): | |
| ap = argparse.ArgumentParser(description=__doc__.split("\n")[0]) | |
| sub = ap.add_subparsers(dest="cmd", required=True) | |
| r = sub.add_parser("run") | |
| r.add_argument("--config", required=True) | |
| r.add_argument("--model", default=None) | |
| r.add_argument("--rows", required=True) | |
| r.add_argument("--out", required=True) | |
| r.add_argument("--warmup-rows", default=None) | |
| r.add_argument("--limit", type=int, default=0) | |
| c = sub.add_parser("compare") | |
| c.add_argument("ref") | |
| c.add_argument("cand") | |
| c.add_argument("--out", default=None) | |
| c.add_argument("--ref-part", default=None, help="compare this part's distributions of the ref run (e.g. karpo)") | |
| c.add_argument("--cand-part", default=None) | |
| s = sub.add_parser("sample") | |
| s.add_argument("--rows", nargs="+", required=True) | |
| s.add_argument("--n", type=int, default=1000) | |
| s.add_argument("--seed", type=int, default=20261125) | |
| s.add_argument("--mode", choices=("uniform", "proportional"), default="uniform") | |
| s.add_argument("--out", required=True) | |
| a = ap.parse_args(argv) | |
| {"run": cmd_run, "compare": cmd_compare, "sample": cmd_sample}[a.cmd](a) | |
| if __name__ == "__main__": | |
| main() | |