beam-engram-tables / code /bench_local.py
chadstthomas's picture
Engram code
3bc7886 verified
Raw History Blame Contribute Delete
4.58 kB
#!/usr/bin/env python3
"""Local benchmark harness for Beam Q2: AIME 2026 and GPQA Diamond.
Calls an OpenAI-compatible llama-server, saves one JSONL record per item, and
grades with deterministic answer extraction. Run AIME with --effort high and
GPQA with --effort medium for the release card; record the effort in the output.
"""
import argparse, csv, hashlib, json, os, random, re, sys, threading, time, urllib.request
import concurrent.futures as cf
AIME = "/mnt/optane/bench/aime2026/data/train-00000-of-00001.parquet"
GPQA = "/mnt/optane/bench/gpqa/gpqa_diamond.csv"
ap = argparse.ArgumentParser()
ap.add_argument("bench", choices=["aime2026", "gpqa_diamond"])
ap.add_argument("out")
ap.add_argument("--url", default="http://100.74.68.37:18360/v1/chat/completions")
ap.add_argument("--effort", default="high")
ap.add_argument("--par", type=int, default=8)
ap.add_argument("--limit", type=int, default=0)
ap.add_argument("--max-tokens", type=int, default=8192)
A = ap.parse_args()
def load_aime():
import pyarrow.parquet as pq
rows = pq.read_table(AIME).to_pylist()
return [{"id": str(r["problem_idx"]), "q": r["problem"], "gold": str(int(r["answer"]))} for r in rows]
def load_gpqa():
rng = random.Random(20261021)
out = []
for i, r in enumerate(csv.DictReader(open(GPQA))):
opts = [r["Correct Answer"], r["Incorrect Answer 1"], r["Incorrect Answer 2"], r["Incorrect Answer 3"]]
rng.shuffle(opts)
gold = "ABCD"[opts.index(r["Correct Answer"])]
q = (r["Question"].strip() + "\n\n" + "\n".join(f"{'ABCD'[j]}) {o.strip()}" for j, o in enumerate(opts))
+ "\n\nAnswer with only the letter (A, B, C, or D).")
out.append({"id": r.get("Record ID") or str(i), "q": q, "gold": gold, "subdomain": r.get("Subdomain", "")})
return out
items = load_aime() if A.bench == "aime2026" else load_gpqa()
if A.limit:
items = items[:A.limit]
done = {json.loads(l)["id"] for l in open(A.out)} if os.path.exists(A.out) else set()
todo = [it for it in items if it["id"] not in done]
lock = threading.Lock()
SYS = ("You are an expert scientist and mathematician. Solve the problem carefully. "
"Put the final answer in the requested format.")
def extract(it):
a = it["answer"]
if A.bench == "aime2026":
s = a.strip()
if re.fullmatch(r"-?\d+", s.replace(",", "")):
pred = s.replace(",", "")
return pred, pred == it["gold"].strip()
ms = re.findall(r"\\boxed\{([^{}]*)\}", a)
if not ms:
ms = re.findall(r"(?:final answer|answer is)[^\d\-]{0,20}(-?\d+)", a, re.I)
if not ms:
return "", False
m = re.findall(r"-?\d+", ms[-1].replace(",", ""))
pred = m[-1] if m else ""
return pred, pred == it["gold"].strip()
m = re.findall(r"(?:final answer|answer|choice|option)\s*(?:is|:)?\s*[\(\[]?([ABCD])\b", a, re.I)
if not m:
m = re.findall(r"\b([ABCD])\b", a)
pred = m[-1].upper() if m else ""
return pred, pred == it["gold"]
def ask(it):
body = {"model": "beam-1.0", "max_tokens": A.max_tokens, "temperature": 0.7, "top_p": 0.99,
"chat_template_kwargs": {"reasoning_effort": A.effort},
"messages": [{"role": "system", "content": SYS}, {"role": "user", "content": it["q"]}]}
t0 = time.time()
try:
d = json.load(urllib.request.urlopen(urllib.request.Request(A.url, json.dumps(body).encode(),
{"Content-Type": "application/json"}), timeout=14400))
m = d["choices"][0]["message"]
ans, fin, n, err = (m.get("content") or "").strip(), d["choices"][0].get("finish_reason"), d["usage"]["completion_tokens"], None
except Exception as e:
ans, fin, n, err = "", "error", 0, str(e)[:300]
pred, ok = extract({"id": it["id"], "gold": it["gold"], "answer": ans})
rec = {"id": it["id"], "bench": A.bench, "effort": A.effort, "q": it["q"], "gold": it["gold"],
"answer": ans, "pred": pred, "correct": bool(ok), "finish": fin, "tokens": n,
"s": round(time.time() - t0, 1), "err": err}
with lock:
with open(A.out, "a") as f:
f.write(json.dumps(rec) + "\n")
print(f"{time.strftime('%H:%M:%S')} {it['id']} {pred!r} gold {it['gold']!r} {'OK' if ok else 'x'} {n} tok {rec['s']}s", flush=True)
print(f"{A.bench}: {len(items)} items, {len(done)} done, {len(todo)} to go, effort {A.effort}, par {A.par}", flush=True)
with cf.ThreadPoolExecutor(A.par) as ex:
list(ex.map(ask, todo))