Download scripts/run_mc.py from HappyWindman555/d3-hub-evals: direct link, hf CLI and curl.
- Browser
- Download file 7.75 kB
-
https://huggingface.co/datasets/HappyWindman555/d3-hub-evals/resolve/main/scripts/run_mc.py
- Command line
-
hf download hf://datasets/HappyWindman555/d3-hub-evals/scripts/run_mc.py
-
curl -L -o run_mc.py https://huggingface.co/datasets/HappyWindman555/d3-hub-evals/resolve/main/scripts/run_mc.py
7.75 kB
| """Score a closed-set Hub benchmark with a d3 decision model over /v1/systemone. | |
| Each item becomes one System One request with a single `choice` question; the | |
| predicted answer is the argmax of the returned option probabilities. | |
| """ | |
| import argparse | |
| import ast | |
| import base64 | |
| import concurrent.futures as cf | |
| import hashlib | |
| import io | |
| import json | |
| import random | |
| import time | |
| import urllib.request | |
| from pathlib import Path | |
| import pyarrow.parquet as pq | |
| DATA = Path(__file__).parent / "data" | |
| LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" | |
| def as_list(v): | |
| return list(v) if not isinstance(v, str) else ast.literal_eval(v) | |
| def evasion(seed): | |
| rows = pq.read_table(DATA / "EvasionBench/evasionbench_17k_eva4b_labels_dedup.parquet").to_pylist() | |
| for r in rows: | |
| labels = as_list(r["choices"]) | |
| yield { | |
| "id": r["uid"], | |
| "state": f"Question: {r['question']}\n\nAnswer: {r['answer']}", | |
| "instructions": "You are a financial analyst. Detect evasive answers in financial Q&A: how directly does the answer address the question?", | |
| "options": {lab: None for lab in labels}, | |
| "gold": r["eva4b_label"], | |
| } | |
| def mmlu_pro(seed): | |
| rows = pq.read_table(DATA / "MMLU-Pro/data/test-00000-of-00001.parquet").to_pylist() | |
| for r in rows: | |
| opts = as_list(r["options"]) | |
| yield { | |
| "id": str(r["question_id"]), | |
| "state": r["question"], | |
| "instructions": "Which option correctly answers the question?", | |
| "options": {LETTERS[i]: o for i, o in enumerate(opts)}, | |
| "gold": r["answer"], | |
| "group": r["category"], | |
| } | |
| def lexam_mcq4(seed): | |
| rows = pq.read_table(DATA / "LEXam/mcq_4_choices/test-00000-of-00001.parquet").to_pylist() | |
| for r in rows: | |
| opts = as_list(r["choices"]) | |
| yield { | |
| "id": r["id"], | |
| "state": r["question"], | |
| "instructions": "Which option correctly answers the question?", | |
| "options": {LETTERS[i]: o for i, o in enumerate(opts)}, | |
| "gold": LETTERS[int(r["gold"])], | |
| "group": r["language"], | |
| } | |
| REENCODE = False # set by --reencode-images for servers that reject >8 MB or MPO images | |
| def _img(v): | |
| b = v["bytes"] if isinstance(v, dict) else v | |
| head = b[:12] | |
| if REENCODE and (len(b) > 7_500_000 or b"MPF\x00" in b[:65536]): | |
| from PIL import Image | |
| im = Image.open(io.BytesIO(b)) | |
| im.seek(0) | |
| im = im.convert("RGB") | |
| scale = min(1.0, (1_638_400 / (im.width * im.height)) ** 0.5) | |
| if scale < 1: | |
| im = im.resize((round(im.width * scale), round(im.height * scale)), Image.BICUBIC) | |
| buf = io.BytesIO() | |
| im.save(buf, "PNG") | |
| b, head = buf.getvalue(), b"\x89PNG" | |
| mime = "image/png" if head.startswith(b"\x89PNG") else "image/webp" if head[8:12] == b"WEBP" else "image/jpeg" | |
| return f"data:{mime};base64,{base64.b64encode(b).decode()}" | |
| def mmmu_pro(config): | |
| def gen(seed): | |
| files = sorted((DATA / "MMMU_Pro" / config).glob("test-*.parquet")) | |
| for f in files: | |
| for batch in pq.ParquetFile(f).iter_batches(batch_size=64): | |
| for r in batch.to_pylist(): | |
| opts = as_list(r["options"]) | |
| if config == "vision": | |
| images, state = [_img(r["image"])], "Answer the multiple-choice question shown in the image." | |
| else: | |
| images = [_img(r[f"image_{i}"]) for i in range(1, 8) if r.get(f"image_{i}")] | |
| state = r["question"] | |
| yield { | |
| "id": r["id"], | |
| "state": state, | |
| "images": images, | |
| "instructions": "Which option correctly answers the question?", | |
| "options": {LETTERS[i]: o for i, o in enumerate(opts)}, | |
| "gold": r["answer"], | |
| "group": r.get("subject"), | |
| } | |
| return gen | |
| BENCH = { | |
| "evasion_bench": evasion, | |
| "mmlu_pro": mmlu_pro, | |
| "lexam_mcq4": lexam_mcq4, | |
| "mmmu_pro_standard_10": mmmu_pro("standard (10 options)"), | |
| "mmmu_pro_standard_4": mmmu_pro("standard (4 options)"), | |
| "mmmu_pro_vision": mmmu_pro("vision"), | |
| } | |
| def ask(endpoint, model, item, timeout): | |
| body = { | |
| "model": model, | |
| "state": item["state"], | |
| "questions": {"answer": {"type": "choice", "instructions": item["instructions"], "criteria": item["options"]}}, | |
| } | |
| if item.get("images"): | |
| body["images"] = item["images"] | |
| req = urllib.request.Request(f"{endpoint}/v1/systemone", json.dumps(body).encode(), {"Content-Type": "application/json"}) | |
| t0 = time.monotonic() | |
| for attempt in range(3): | |
| try: | |
| with urllib.request.urlopen(req, timeout=timeout) as resp: | |
| ans = json.load(resp)["answers"]["answer"] | |
| probs = ans["probabilities"] | |
| return {"pred": max(probs, key=probs.get), "probs": probs, "latency_s": time.monotonic() - t0} | |
| except Exception as e: # noqa: BLE001 - recorded per item | |
| err = f"{type(e).__name__}: {getattr(e, 'read', lambda: b'')()[:300]!r} {e}" | |
| time.sleep(1 + attempt) | |
| return {"error": err, "latency_s": time.monotonic() - t0} | |
| def main(): | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--bench", required=True, choices=BENCH) | |
| ap.add_argument("--model", required=True) | |
| ap.add_argument("--endpoint", default="http://127.0.0.1:8000") | |
| ap.add_argument("--out", required=True) | |
| ap.add_argument("--limit", type=int) | |
| ap.add_argument("--seed", type=int, default=0) | |
| ap.add_argument("--concurrency", type=int, default=16) | |
| ap.add_argument("--timeout", type=float, default=300) | |
| ap.add_argument("--reencode-images", action="store_true") | |
| a = ap.parse_args() | |
| global REENCODE | |
| REENCODE = a.reencode_images | |
| items = list(BENCH[a.bench](a.seed)) | |
| if a.limit: | |
| items = random.Random(a.seed).sample(items, min(a.limit, len(items))) | |
| out = Path(a.out) | |
| out.parent.mkdir(parents=True, exist_ok=True) | |
| done = {} | |
| if out.exists(): | |
| for line in out.open(): | |
| r = json.loads(line) | |
| if "error" not in r: | |
| done[r["id"]] = r | |
| todo = [it for it in items if it["id"] not in done] | |
| print(f"{a.bench} {a.model}: {len(items)} items, {len(done)} cached, {len(todo)} to run", flush=True) | |
| with out.open("a") as f, cf.ThreadPoolExecutor(a.concurrency) as pool: | |
| futs = {pool.submit(ask, a.endpoint, a.model, it, a.timeout): it for it in todo} | |
| for n, fut in enumerate(cf.as_completed(futs), 1): | |
| it = futs[fut] | |
| r = {"id": it["id"], "gold": it["gold"], "group": it.get("group"), **fut.result()} | |
| f.write(json.dumps(r) + "\n") | |
| done[it["id"]] = r | |
| if n % 500 == 0: | |
| print(f" {n}/{len(todo)}", flush=True) | |
| ids = {it["id"] for it in items} | |
| rows = [done[i] for i in ids if i in done] | |
| ok = [r for r in rows if "error" not in r] | |
| correct = sum(r["pred"] == r["gold"] for r in ok) | |
| lat = sorted(r["latency_s"] for r in ok) | |
| summary = { | |
| "bench": a.bench, "model": a.model, "n": len(items), "answered": len(ok), | |
| "errors": len(items) - len(ok), "correct": correct, | |
| "accuracy": correct / len(items), | |
| "latency_p50_s": lat[len(lat) // 2] if lat else None, | |
| "results_sha256": hashlib.sha256(out.read_bytes()).hexdigest(), | |
| } | |
| print(json.dumps(summary), flush=True) | |
| out.with_suffix(".summary.json").write_text(json.dumps(summary, indent=1)) | |
| if __name__ == "__main__": | |
| main() | |