6ff8f34666af0f9d72d40cf40cee5c98ad090dc0 / bench/tasks/reasoning.py · 15008 bytes · raw
#!/usr/bin/env python3
"""
reasoning.py - computing-knowledge multiple choice, graded on content (the reasoning text never is).
mmlu-pro-cs TIGER-Lab/MMLU-Pro test, category "computer science", 60 items, options A-J (MIT)
Note (2026-10-12): only computing-relevant reasoning stays. AIME 2026, MuSR, ZebraLogic and the
other MMLU-Pro categories were removed (stored runs of them still read in reports). Selection is
deterministic (no RNG): sort by sha256(f"{set}:{native_id}") and take the first N. The selected
items are cached (gitignored) and pinned by a committed manifest
(bench/data/reasoning/<set>.manifest.json) holding a sha256 per item.
Commands: fetch (download + pin), validate (offline, cache vs manifest), run (one run per set).
"""
import argparse
import gzip
import hashlib
import json
import os
import re
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
from bench.core import client, results
HERE = os.path.dirname(os.path.abspath(__file__))
DATA_DIR = os.path.join(os.path.dirname(HERE), "data", "reasoning")
CACHE_DIR = os.path.join(DATA_DIR, "cache")
HF = "https://datasets-server.huggingface.co"
INSTRUMENT = "reasoning"
ALL_SETS = ["mmlu-pro-cs"]
MMLU_CS_N = 60
SPEC = {
"mmlu-pro-cs": {"dataset": "TIGER-Lab/MMLU-Pro", "config": "default", "splits": ["test"],
"rule": f"first {MMLU_CS_N} of category 'computer science' by "
"sha256('mmlu-pro-cs:<question_id>')"},
}
# ---------------------------------------------------------------- hashing / selection
def canon(obj):
return json.dumps(obj, sort_keys=True, separators=(",", ":"), ensure_ascii=False)
def item_sha(item):
return hashlib.sha256(canon(item).encode("utf-8")).hexdigest()
def sel_key(set_name, native_id):
return hashlib.sha256(f"{set_name}:{native_id}".encode("utf-8")).hexdigest()
def select(set_name, candidates, n):
"""candidates: [(native_id, stratum, item)]. First n per stratum by hash order.
Returns items sorted by (stratum order of first appearance, hash)."""
by = {}
for native_id, stratum, item in candidates:
by.setdefault(stratum, []).append((sel_key(set_name, native_id), native_id, item))
out = []
for stratum in by:
for _k, native_id, item in sorted(by[stratum], key=lambda t: (t[0], str(t[1])))[:n]:
out.append(item)
return out
def manifest_hash(manifest):
h = hashlib.sha256()
for it in manifest["items"]:
h.update((it["item_id"] + ":" + it["sha256"] + "\n").encode())
return h.hexdigest()[:12]
# ---------------------------------------------------------------- normalizers
def build_items(set_name, rows_by_split):
"""rows_by_split: {split: [raw rows in dataset order]} -> selected normalized items."""
if set_name != "mmlu-pro-cs":
raise ValueError(set_name)
cands = []
for r in rows_by_split["test"]:
if r["category"] != "computer science":
continue
nid = str(r["question_id"])
cands.append((nid, "cs", {
"item_id": f"mmlu-pro-cs/{nid}", "native_id": nid, "category": "cs",
"question": r["question"], "options": list(r["options"]),
"answer": r["answer"], "answer_index": int(r["answer_index"]), "src": r.get("src")}))
return select(set_name, cands, MMLU_CS_N)
# ---------------------------------------------------------------- fetch
def _get_json(url, tries=12):
err = None
for i in range(tries):
try:
req = urllib.request.Request(url, headers={"User-Agent": "llm-bench/reasoning"})
with urllib.request.urlopen(req, timeout=60) as r:
return json.load(r)
except urllib.error.HTTPError as e:
err = e
if e.code not in (429, 500, 502, 503, 504):
raise
if e.code == 429:
try:
time.sleep(min(float(e.headers.get("Retry-After", 0)), 60))
except ValueError:
pass
time.sleep(min(5 * (i + 1), 30))
except Exception as e: # noqa: BLE001
err = e
time.sleep(1.5 * (i + 1))
raise RuntimeError(f"GET {url} failed: {err!r}")
def fetch_split(dataset, config, split):
q = urllib.parse.urlencode({"dataset": dataset, "config": config, "split": split})
total = _get_json(f"{HF}/size?{urllib.parse.urlencode({'dataset': dataset})}")
n = None
for c in total["size"]["configs"]:
if c["config"] == config:
n = c["num_rows"]
splits = total["size"].get("splits") or []
for s in splits:
if s["config"] == config and s["split"] == split:
n = s["num_rows"]
if n is None:
raise RuntimeError(f"no row count for {dataset}/{config}/{split}")
rows = []
for off in range(0, n, 100):
page = _get_json(f"{HF}/rows?{q}&offset={off}&length=100")
rows.extend(x["row"] for x in page["rows"])
time.sleep(0.5)
if len(rows) != n:
raise RuntimeError(f"{dataset}/{split}: got {len(rows)} rows, expected {n}")
return rows
def write_set(set_name, items, spec=None):
spec = spec or SPEC[set_name]
os.makedirs(CACHE_DIR, exist_ok=True)
with open(os.path.join(CACHE_DIR, f"{set_name}.jsonl"), "w", encoding="utf-8") as f:
for it in items:
f.write(json.dumps(it, ensure_ascii=False) + "\n")
manifest = {
"set": set_name,
"source": {"dataset": spec["dataset"], "config": spec["config"], "splits": spec["splits"]},
"selection_rule": "sort by sha256(f'<set>:<native_id>'), take first N per stratum. "
+ spec["rule"],
"n": len(items),
"items": [{"item_id": it["item_id"], "native_id": it["native_id"],
"category": it["category"], "sha256": item_sha(it)} for it in items],
}
manifest["manifest_hash"] = manifest_hash(manifest)
path = os.path.join(DATA_DIR, f"{set_name}.manifest.json")
with open(path, "w") as f:
json.dump(manifest, f, indent=1, ensure_ascii=False)
f.write("\n")
return manifest
def cmd_fetch(sets):
for s in sets:
spec = SPEC[s]
rows = {sp: fetch_split(spec["dataset"], spec["config"], sp) for sp in spec["splits"]}
items = build_items(s, rows)
old = _load_manifest(s, missing_ok=True)
m = write_set(s, items)
note = ""
if old and old.get("manifest_hash") != m["manifest_hash"]:
note = f" (CHANGED vs previous manifest {old.get('manifest_hash')})"
cats = {}
for it in m["items"]:
cats[it["category"]] = cats.get(it["category"], 0) + 1
print(f"{s}: {m['n']} items, manifest {m['manifest_hash']}{note}")
for c in sorted(cats):
print(f" {c}: {cats[c]}")
return 0
# ---------------------------------------------------------------- load / validate
def _load_manifest(set_name, missing_ok=False):
p = os.path.join(DATA_DIR, f"{set_name}.manifest.json")
if not os.path.exists(p):
if missing_ok:
return None
raise FileNotFoundError(f"{p} missing - run `reasoning fetch`")
with open(p) as f:
return json.load(f)
def load_items(set_name):
"""Cache items, verified against the manifest. Raises ValueError on any drift."""
manifest = _load_manifest(set_name)
p = os.path.join(CACHE_DIR, f"{set_name}.jsonl")
if not os.path.exists(p):
raise FileNotFoundError(f"{p} missing - run `reasoning fetch --sets {set_name}`")
with open(p, encoding="utf-8") as f:
items = [json.loads(l) for l in f if l.strip()]
problems = check_items(items, manifest)
if problems:
raise ValueError(f"{set_name}: cache does not match manifest: " + "; ".join(problems[:5]))
return items, manifest
def check_items(items, manifest):
problems = []
want = {m["item_id"]: m for m in manifest["items"]}
got = {}
for it in items:
got[it["item_id"]] = it
if len(items) != len(got):
problems.append("duplicate item_ids in cache")
for iid in want:
if iid not in got:
problems.append(f"missing {iid}")
elif item_sha(got[iid]) != want[iid]["sha256"]:
problems.append(f"hash mismatch {iid}")
for iid in got:
if iid not in want:
problems.append(f"extra {iid}")
if manifest.get("n") != len(manifest["items"]):
problems.append("manifest n != len(items)")
if manifest.get("manifest_hash") != manifest_hash(manifest):
problems.append("manifest_hash stale")
return problems
def cmd_validate(sets):
bad = 0
for s in sets:
try:
items, m = load_items(s)
cats = {}
for it in items:
cats[it["category"]] = cats.get(it["category"], 0) + 1
print(f"{s}: OK {len(items)} items, manifest {m['manifest_hash']}, "
f"{len(cats)} categories")
except (FileNotFoundError, ValueError) as e:
bad += 1
print(f"{s}: FAIL {e}")
return 1 if bad else 0
# ---------------------------------------------------------------- prompts
LETTERS = "ABCDEFGHIJ"
def mc_prompt(body, options):
opts = "\n".join(f"{LETTERS[i]}. {o}" for i, o in enumerate(options))
return (f"{body}\n\nOptions:\n{opts}\n\n"
"Think it through, then end your reply with a line 'ANSWER: <letter>' "
"(a single letter, e.g. 'ANSWER: C').")
def prompt_hash():
"""Hash of the prompt templates. Part of item_set, so runs asked with different
wording are never pooled or paired by the report."""
import inspect
src = "".join(inspect.getsource(f) for f in (mc_prompt, build_prompt))
return hashlib.sha256(src.encode()).hexdigest()[:8]
def build_prompt(item):
if item["item_id"].startswith("mmlu-pro-cs/"):
return mc_prompt(item["question"], item["options"])
raise ValueError(item["item_id"])
# ---------------------------------------------------------------- extraction / grading
# "ANSWER: C" / "ANSWER: (C)" / "answer: c". An uppercase letter may be followed by more text
# ("ANSWER: C. Mia"); a lowercase letter only counts when it is the whole answer, so
# "ANSWER: a long story" is not read as option A.
_ANS_UP = re.compile(r"ANSWER\s*:\s*[*_`\s]*\(?([A-J])\b", re.I)
_ANS_LOW = re.compile(r"ANSWER\s*:\s*[*_`\s]*\(?([a-j])\)?[.*_`\s]*$", re.I)
_LONE = re.compile(r"^[\s*_`(\[]*([A-Ja-j])[\s*_`)\].]*$")
def extract_letter(content):
"""Last 'ANSWER: X' (X in A-J, upper or lowercase), else a lone letter on the last
non-empty line, else None."""
last = None
for line in (content or "").splitlines():
hit = None
for m in _ANS_UP.finditer(line):
if m.group(1).isupper():
hit = m.group(1)
if hit is None:
m = _ANS_LOW.search(line)
if m:
hit = m.group(1)
if hit:
last = hit.upper()
if last:
return last
lines = [l for l in (content or "").splitlines() if l.strip()]
if lines:
m = _LONE.match(lines[-1])
if m:
return m.group(1).upper()
return None
def grade(item, content):
"""-> dict(correct, score, extracted, gold)."""
letter = extract_letter(content)
gold = LETTERS[item["answer_index"]]
return {"correct": letter == gold, "score": None, "extracted": letter, "gold": gold}
# ---------------------------------------------------------------- run
def _attempt(store, lane, item, k):
def check(resp):
content = client.content(resp) or ""
reasoning = client.reasoning(resp) or ""
row = dict(grade(item, content), content_tail=content[-600:],
reasoning_head=reasoning[:400], reasoning_tail=reasoning[-400:])
if store.run["args"].get("keep_reasoning") and reasoning:
row["reasoning_file"] = _write_reasoning(store, item["item_id"], k, reasoning)
return row
results.call_attempt(store, lane, item["item_id"], k, item["category"],
[{"role": "user", "content": build_prompt(item)}], check)
def _write_reasoning(store, item_id, k, text):
name = f"{results.safe_label(item_id)}-{k}.reasoning.txt.gz"
with gzip.open(os.path.join(store.dir, name), "wt", encoding="utf-8") as f:
f.write(text)
return name
def run_set(set_name, items, manifest, *, lane=None, samples=1, concurrency=None,
resume_dir=None, keep_reasoning=False, item_ids=None):
"""One run over one set -> (store, summary). On resume the args come from run.json."""
iset = f"{set_name}@{manifest['manifest_hash']}.p{prompt_hash()}"
args = {"sets": [set_name], "samples": samples, "concurrency": concurrency,
"items": item_ids, "keep_reasoning": keep_reasoning}
plan = lambda _args: (iset, [(it["item_id"], it) for it in items]) # noqa: E731
return results.run_attempts(INSTRUMENT, args, plan, _attempt, resume=resume_dir, lane=lane)
def cmd_run(args):
sets = _parse_sets(args.sets)
if args.resume:
with open(os.path.join(args.resume, "run.json")) as f:
sets = [json.load(f)["item_set"].split("@")[0]]
want = [x for x in args.items.split(",") if x]
for s in sets:
items, manifest = load_items(s)
sel = [i for i in want if i in {it["item_id"] for it in items}]
if want and not sel and not args.resume:
continue
_store, summary = run_set(s, items, manifest, samples=args.samples,
concurrency=args.concurrency, resume_dir=args.resume,
keep_reasoning=args.keep_reasoning, item_ids=sel or None)
if summary["stopped"]:
print("budget stop - remaining sets not run", file=sys.stderr)
return 3
return 0
def _parse_sets(s):
if not s:
return list(ALL_SETS)
out = [x.strip() for x in s.split(",") if x.strip()]
for x in out:
if x not in SPEC:
raise SystemExit(f"unknown set {x!r}; choose from {ALL_SETS}")
return out
def main(argv=None):
p = argparse.ArgumentParser(prog="bench.py reasoning")
sub = p.add_subparsers(dest="cmd", required=True)
for name in ("fetch", "validate", "run"):
sp = sub.add_parser(name)
sp.add_argument("--sets", default=None, help="comma list of: " + ",".join(ALL_SETS))
if name == "run":
results.add_run_args(sp, concurrency=None)
sp.add_argument("--keep-reasoning", action="store_true")
args = p.parse_args(sys.argv[1:] if argv is None else argv)
if args.cmd == "fetch":
rc = cmd_fetch(_parse_sets(args.sets))
elif args.cmd == "validate":
rc = cmd_validate(_parse_sets(args.sets))
else:
rc = cmd_run(args)
sys.exit(rc)
if __name__ == "__main__":
main()