#!/usr/bin/env python3 """Broad public-benchmark suite for LOREA-cyber. Loads the model once and runs 22 benchmarks of the kind frontier models report. Results are written after EVERY benchmark, and completed benchmarks are skipped on re-run, so an interrupted session (or an OOM) costs one benchmark, not the whole suite. python3 eval/bench_suite.py --model [--adapter ] --tag v5.9 \ --output v59/eval/suite_v59.json [--only mmlu,gsm8k] [--limit 150] """ import argparse import json import os import random import re import subprocess import sys import tempfile import time import warnings warnings.filterwarnings("ignore") random.seed(20260802) SYS = "You are a helpful assistant. Answer accurately and concisely." CODE_SYS = "You are an expert Python programmer. Write correct, complete, runnable code." LETTERS = "ABCDEFGHIJKLMNOP" _THINK_CLOSE = re.compile(r"", re.I) def visible(text): """Return the answer, dropping any reasoning block. The chat template can open in the prompt, so a completion may contain only the closing tag. Everything before it is reasoning. """ text = text or "" m = list(_THINK_CLOSE.finditer(text)) return text[m[-1].end():].strip() if m else text.strip() def ds(repo, cfg=None, split="test"): from datasets import load_dataset return load_dataset(repo, cfg, split=split) if cfg else load_dataset(repo, split=split) def mc(q, options, answer_idx, meta=None): return {"q": q, "options": [str(o) for o in options], "answer_idx": answer_idx} # ---------------------------------------------------------------- MCQ loaders def l_mmlu(): return [mc(r["question"], r["choices"], r["answer"]) for r in ds("cais/mmlu", "all", "test")] def l_mmlu_pro(): out = [] for r in ds("TIGER-Lab/MMLU-Pro", split="test"): if r["options"] and r["answer_index"] is not None and r["answer_index"] < len(r["options"]): out.append(mc(r["question"], r["options"], r["answer_index"])) return out def _arc(cfg): out = [] for r in ds("allenai/ai2_arc", cfg, "test"): labels = list(r["choices"]["label"]); texts = list(r["choices"]["text"]) if r["answerKey"] in labels: out.append(mc(r["question"], texts, labels.index(r["answerKey"]))) return out def l_arc_challenge(): return _arc("ARC-Challenge") def l_arc_easy(): return _arc("ARC-Easy") def l_hellaswag(): out = [] for r in ds("Rowan/hellaswag", split="validation"): try: idx = int(r["label"]) except (TypeError, ValueError): continue out.append(mc(r["ctx"], r["endings"], idx)) return out def l_winogrande(): out = [] for r in ds("allenai/winogrande", "winogrande_xl", "validation"): if r["answer"] in ("1", "2"): out.append(mc(r["sentence"].replace("_", "____"), [r["option1"], r["option2"]], int(r["answer"]) - 1)) return out def l_piqa(): return [mc(r["goal"], [r["sol1"], r["sol2"]], int(r["label"])) for r in ds("baber/piqa", split="validation") if r["label"] in (0, 1, "0", "1")] def l_siqa(): out = [] for r in ds("lighteval/siqa", split="validation"): try: idx = int(r["label"]) - 1 except (TypeError, ValueError): continue if 0 <= idx < 3: out.append(mc(f"{r['context']} {r['question']}", [r["answerA"], r["answerB"], r["answerC"]], idx)) return out def l_openbookqa(): out = [] for r in ds("allenai/openbookqa", "main", "test"): labels = list(r["choices"]["label"]); texts = list(r["choices"]["text"]) if r["answerKey"] in labels: out.append(mc(r["question_stem"], texts, labels.index(r["answerKey"]))) return out def l_commonsense_qa(): out = [] for r in ds("tau/commonsense_qa", split="validation"): labels = list(r["choices"]["label"]); texts = list(r["choices"]["text"]) if r["answerKey"] in labels: out.append(mc(r["question"], texts, labels.index(r["answerKey"]))) return out def l_boolq(): return [mc(f"{r['passage']}\n\nQuestion: {r['question']}?", ["yes", "no"], 0 if r["answer"] else 1) for r in ds("google/boolq", split="validation")] def l_truthfulqa(): out = [] for r in ds("truthfulqa/truthful_qa", "multiple_choice", "validation"): t = r["mc1_targets"] ch, lb = list(t["choices"]), list(t["labels"]) if 1 in lb: out.append(mc(r["question"], ch, lb.index(1))) return out def l_race(): out = [] for r in ds("ehovy/race", "high", "test"): if r["answer"] in "ABCD" and len(r["options"]) == 4: out.append(mc(f"{r['article'][:1800]}\n\nQuestion: {r['question']}", r["options"], "ABCD".index(r["answer"]))) return out def l_sciq(): out = [] for r in ds("allenai/sciq", split="test"): opts = [r["correct_answer"], r["distractor1"], r["distractor2"], r["distractor3"]] order = list(range(4)); random.shuffle(order) out.append(mc(r["question"], [opts[i] for i in order], order.index(0))) return out def l_medmcqa(): out = [] for r in ds("openlifescienceai/medmcqa", split="validation"): opts = [r["opa"], r["opb"], r["opc"], r["opd"]] if r["cop"] is not None and 0 <= r["cop"] < 4 and all(opts): out.append(mc(r["question"], opts, r["cop"])) return out def l_secqa(): out = [] for cfg in ("secqa_v1", "secqa_v2"): try: rows = ds("zefang-liu/secqa", cfg, "test") except Exception: continue for r in rows: opts = [r.get("A"), r.get("B"), r.get("C"), r.get("D")] a = str(r.get("Answer", "")).strip().upper() if all(opts) and a in "ABCD": out.append(mc(r["Question"], opts, "ABCD".index(a))) return out def l_cybermetric(): import urllib.request for size in ("500", "2000", "80"): url = (f"https://raw.githubusercontent.com/cybermetric/CyberMetric/main/" f"CyberMetric-{size}-v1.json") try: with urllib.request.urlopen(url, timeout=45) as f: data = json.load(f) except Exception: continue qs = data.get("questions", data) if isinstance(data, dict) else data out = [] for r in qs: a = r.get("answers", {}); keys = sorted(a.keys()) sol = str(r.get("solution", "")).strip().upper() if sol in keys: out.append(mc(r["question"], [a[k] for k in keys], keys.index(sol))) if out: random.shuffle(out); return out return [] def l_cyber_mcq_local(): p = os.path.join(os.path.dirname(os.path.abspath(__file__)), "cyber_mcq_eval.jsonl") if not os.path.isfile(p): return [] out = [] for line in open(p): if not line.strip(): continue r = json.loads(line) a = r["answer"].strip().upper() if a in "ABCD": out.append(mc(r["question"], [r["A"], r["B"], r["C"], r["D"]], "ABCD".index(a))) return out def l_bbh(): subs = ["boolean_expressions", "causal_judgement", "date_understanding", "disambiguation_qa", "formal_fallacies", "logical_deduction_three_objects", "navigate", "sports_understanding"] out = [] for s in subs: try: rows = ds("lukaemon/bbh", s, "test") except Exception: continue for r in rows: out.append({"q": r["input"], "options": None, "answer_idx": None, "free_target": str(r["target"]).strip()}) return out # ------------------------------------------------------- generative loaders def l_gsm8k(): return [{"q": r["question"], "free_target": r["answer"].split("####")[-1].strip()} for r in ds("openai/gsm8k", "main", "test")] def l_humaneval(): return list(ds("openai/openai_humaneval", split="test")) def l_mbpp(): return list(ds("google-research-datasets/mbpp", "full", "test")) # ------------------------------------------------------------------ runners def mcq_prompt(q, options): lines = [q.strip(), ""] L = LETTERS[:len(options)] for i, o in enumerate(options): lines.append(f"{L[i]}) {o}") lines.append("\nRespond with ONLY the single letter of the correct answer.") return "\n".join(lines) def parse_letter(out, n): t = visible(out).upper() L = LETTERS[:n] m = re.search(rf"\b([{L}])\b", t) or re.search(rf"([{L}])", t) return m.group(1) if m else "?" def run_mcq(gen, items): ok = 0 for r in items: pred = parse_letter(gen(mcq_prompt(r["q"], r["options"]), 12), len(r["options"])) if pred == LETTERS[r["answer_idx"]]: ok += 1 return {"n": len(items), "correct": ok, "acc": round(ok / max(1, len(items)), 4)} def run_bbh(gen, items): ok = 0 for r in items: out = visible(gen(r["q"] + "\n\nAnswer with the final answer only.", 24)).strip() tgt = r["free_target"].strip() first = out.splitlines()[0].strip() if out else "" if tgt.lower() in out.lower()[:120] or first.lower() == tgt.lower(): ok += 1 return {"n": len(items), "correct": ok, "acc": round(ok / max(1, len(items)), 4)} def run_gsm8k(gen, items): ok = 0 for r in items: out = visible(gen(r["q"] + "\n\nSolve it, then give the final number on its own " "last line after '####'.", 400)) nums = re.findall(r"-?\d[\d,]*\.?\d*", out.replace("$", "")) tgt = r["free_target"].replace(",", "").strip() if nums and nums[-1].replace(",", "").strip() == tgt: ok += 1 return {"n": len(items), "correct": ok, "acc": round(ok / max(1, len(items)), 4)} def _exec(program, timeout=12): path = None try: with tempfile.NamedTemporaryFile("w", suffix=".py", delete=False) as f: f.write(program); path = f.name return subprocess.run([sys.executable, path], capture_output=True, timeout=timeout).returncode == 0 except Exception: return False finally: if path: try: os.unlink(path) except OSError: pass def _code_from(out): out = visible(out) m = re.search(r"```(?:python)?\n(.*?)```", out, re.S) return m.group(1) if m else out def run_humaneval(gen, items): ok = 0 for r in items: body = _code_from(gen(r["prompt"] + "\n\nComplete the function above. Give the full " "function in a ```python block.", 512, CODE_SYS)) prog = body if f"def {r['entry_point']}" in body else r["prompt"] + "\n" + body prog += "\n" + r["test"] + f"\ncheck({r['entry_point']})\n" ok += _exec(prog) return {"n": len(items), "correct": ok, "acc": round(ok / max(1, len(items)), 4)} def run_mbpp(gen, items): ok = 0 for r in items: tests = "\n".join(r["test_list"]) body = _code_from(gen(f"{r['text']}\n\nYour solution must satisfy:\n{tests}\n\n" f"Give the full function in a ```python block.", 512, CODE_SYS)) ok += _exec(body + "\n" + (r.get("test_setup_code") or "") + "\n" + tests + "\n") return {"n": len(items), "correct": ok, "acc": round(ok / max(1, len(items)), 4)} BENCHES = [ # name, loader, runner, default sample size ("mmlu", l_mmlu, run_mcq, 200), ("mmlu_pro", l_mmlu_pro, run_mcq, 200), ("arc_challenge", l_arc_challenge, run_mcq, 200), ("arc_easy", l_arc_easy, run_mcq, 200), ("hellaswag", l_hellaswag, run_mcq, 200), ("winogrande", l_winogrande, run_mcq, 200), ("piqa", l_piqa, run_mcq, 200), ("siqa", l_siqa, run_mcq, 200), ("openbookqa", l_openbookqa, run_mcq, 200), ("commonsense_qa", l_commonsense_qa, run_mcq, 200), ("boolq", l_boolq, run_mcq, 200), ("truthfulqa_mc1", l_truthfulqa, run_mcq, 200), ("race_high", l_race, run_mcq, 150), ("sciq", l_sciq, run_mcq, 200), ("medmcqa", l_medmcqa, run_mcq, 200), ("secqa", l_secqa, run_mcq, 200), ("cybermetric", l_cybermetric, run_mcq, 200), ("cyber_mcq_local", l_cyber_mcq_local, run_mcq, 150), ("bbh", l_bbh, run_bbh, 200), ("gsm8k", l_gsm8k, run_gsm8k, 150), ("humaneval", l_humaneval, run_humaneval, 100), ("mbpp", l_mbpp, run_mbpp, 100), ] def main(): ap = argparse.ArgumentParser() ap.add_argument("--model", required=True) ap.add_argument("--adapter", default=None) ap.add_argument("--tag", default="model") ap.add_argument("--output", required=True) ap.add_argument("--only", default="") ap.add_argument("--limit", type=int, default=0, help="override every sample size") args = ap.parse_args() want = [x.strip() for x in args.only.split(",") if x.strip()] todo = [b for b in BENCHES if not want or b[0] in want] # Resume: keep whatever a previous run already finished. results = {} if os.path.isfile(args.output): try: results = json.load(open(args.output)).get("results", {}) done = [k for k in results if results[k]] if done: print(f"resuming, already done: {', '.join(sorted(done))}", flush=True) except Exception: results = {} from mlx_lm import load, generate try: from mlx_lm.sample_utils import make_sampler sampler = make_sampler(temp=0.0) except Exception: sampler = None t0 = time.time() model, tok = load(args.model, adapter_path=args.adapter) print(f"[{args.tag}] model loaded in {time.time()-t0:.0f}s", flush=True) def gen(user, max_tokens, system=SYS): msgs = [{"role": "system", "content": system}, {"role": "user", "content": user}] try: p = tok.apply_chat_template(msgs, add_generation_prompt=True, tokenize=False, enable_thinking=False) except TypeError: p = tok.apply_chat_template(msgs, add_generation_prompt=True, tokenize=False) kw = dict(max_tokens=max_tokens, verbose=False) if sampler is not None: kw["sampler"] = sampler return generate(model, tok, prompt=p, **kw) def save(): os.makedirs(os.path.dirname(os.path.abspath(args.output)), exist_ok=True) with open(args.output, "w") as f: json.dump({"tag": args.tag, "model": args.model, "adapter": args.adapter, "results": results}, f, indent=2) for name, loader, runner, default_n in todo: if results.get(name): continue try: items = loader() except Exception as e: print(f" {name:16} LOAD FAILED: {str(e)[:70]}", flush=True) results[name] = None save() continue if not items: print(f" {name:16} no items", flush=True) results[name] = None save() continue n = args.limit or default_n random.shuffle(items) items = items[:n] s = time.time() try: r = runner(gen, items) except Exception as e: print(f" {name:16} RUN FAILED: {str(e)[:70]}", flush=True) results[name] = None save() continue r["seconds"] = round(time.time() - s, 1) results[name] = r print(f" {name:16} {r['acc']:7.1%} ({r['correct']}/{r['n']}) {r['seconds']:.0f}s", flush=True) save() # after EVERY benchmark, so a crash costs one benchmark print(f"\ntotal {time.time()-t0:.0f}s -> {args.output}", flush=True) if __name__ == "__main__": main()