llm-bench

#!/usr/bin/env python3
"""Capability-profile report over stored runs.

  python3 bench.py report [--instruments a,b] [--lanes x,y] [--ref claude-opus]
                          [--out PATH.md] [--json PATH] [--csv PATH]
                          [--include-incomplete] [--boot N] [--seed N]

Rows = (instrument, category), columns = lanes. Per-item value = mean of `score` (when
present) else of `correct` over graded samples; a category/lane value = mean over items.
Samples are pooled across runs of the same (lane, instrument, item_set). Differently named
item sets (`fix-easy@..`, `fix-hard@..`) are separate suites sharing the lane's column; two versions
of one name are never pooled (they become separate columns `lane[item_set]`, with a warning). Resumed runs: per (run_id, item_id, sample_idx) the last non-infra row wins,
else the last row. See bench/core/stats.py for CI / McNemar details. Conformance runs are the
preflight, not a capability: they stay out of the profile, and each lane's latest one is listed
in its own section (WARN = the model's own miss, which no other table shows).
"""
import argparse
import csv
import json
import sys
from collections import defaultdict

from bench.core import results, stats
from bench.core.results import is_infra


# ---------------------------------------------------------------- loading ----

def sample_value(r):
    """Graded value of one attempt: score if present, else correct; None if not graded."""
    if is_infra(r.get("status")):
        return None
    if r.get("score") is not None:
        return float(r["score"])
    if r.get("correct") is not None:
        return float(bool(r["correct"]))
    return None


def sample_pass(r):
    """Binary pass of one attempt (correct), None if not graded."""
    if is_infra(r.get("status")):
        return None
    if r.get("correct") is not None:
        return float(bool(r["correct"]))
    if r.get("score") is not None:
        return float(r["score"] >= 1.0)
    return None


def build_items(rows):
    """Deduped rows of one group -> {item_id: item dict}."""
    by = defaultdict(list)
    for r in rows:
        by[r["item_id"]].append(r)
    items = {}
    for iid, rs in by.items():
        vals = [v for v in map(sample_value, rs) if v is not None]
        pas = [v for v in map(sample_pass, rs) if v is not None]
        cats = [r.get("category") for r in rs if r.get("category")]
        walls = [r["wall_s"] for r in rs if r.get("wall_s") is not None]
        costs = [r["cost_usd"] for r in rs if r.get("cost_usd") is not None]
        items[iid] = {
            "category": cats[-1] if cats else "(none)",
            "value": stats.mean(vals), "pass": stats.mean(pas),
            "n_graded": len(vals), "n_attempts": len(rs),
            "n_ctx_overflow": sum(1 for r in rs if r.get("status") == "ctx_overflow"),
            "wall_s": walls, "cost_usd": costs,
        }
    return items


class Data:
    """Grouped runs: groups[(lane, instrument, item_set)] -> dict(runs, raw, rows, items)."""

    def __init__(self):
        self.groups = {}
        self.preflight = {}     # lane -> (run, rows) of its latest conformance run
        self.warnings = []

    def add(self, run, rows):
        key = (run["lane"]["lane_id"], run["instrument"], run.get("item_set"))
        g = self.groups.setdefault(key, {"runs": [], "raw": [], "rows": [], "items": None})
        g["runs"].append(run)
        g["raw"].extend(rows)
        g["rows"].extend(results.dedupe(rows))

    def finalize(self):
        for key, g in self.groups.items():
            g["items"] = build_items(g["rows"])
        # Differently named sets (agentic-fix's fix-easy / fix-hard, ...) are separate suites and share
        # the lane's column; only versions of the same name conflict. A category emitted by two
        # names would collide in one cell, so those groups get suffixed columns too.
        self._suffixed = set()
        versions = defaultdict(set)
        cat_owner = defaultdict(set)
        for (lane, inst, iset), g in self.groups.items():
            versions[(lane, inst, set_name(iset))].add(iset)
            for it in g["items"].values():
                cat_owner[(lane, inst, it["category"])].add(iset)
        for (lane, inst, name), s in sorted(versions.items(), key=str):
            if len(s) > 1:
                self._suffixed |= {(lane, inst, i) for i in s}
                self.warnings.append(
                    f"WARNING: lane {lane!r} instrument {inst!r} has runs with different "
                    f"item_set values {sorted(map(str, s))}; NOT pooled, reported separately.")
        for (lane, inst, cat), s in sorted(cat_owner.items(), key=str):
            if len({set_name(i) for i in s}) > 1:
                self._suffixed |= {(lane, inst, i) for i in s}
                self.warnings.append(
                    f"WARNING: lane {lane!r} instrument {inst!r} category {cat!r} comes from "
                    f"item sets {sorted(map(str, s))}; reported separately.")
        return self

    def col_name(self, lane, inst, iset):
        return f"{lane}[{iset}]" if (lane, inst, iset) in self._suffixed else lane


def set_name(iset):
    """'fix-easy@3f0c9a1d2b7e' -> 'fix-easy' (the suite); the rest is its version."""
    return iset.split("@", 1)[0] if isinstance(iset, str) else iset


def collect(instruments=None, lanes=None, include_incomplete=False):
    d = Data()
    for run, rows in results.load_runs(instruments, lanes, include_incomplete):
        if run.get("instrument") != "conformance":
            d.add(run, rows)
            continue
        lane = run["lane"]["lane_id"]
        if lane not in d.preflight or run.get("started_at", "") >= d.preflight[lane][0].get("started_at", ""):
            d.preflight[lane] = (run, rows)
    return d.finalize()


# ------------------------------------------------------------ aggregation ----

def _cell(items_by_id, n_boot, seed):
    ids = sorted(items_by_id)
    vals = [items_by_id[i]["value"] for i in ids if items_by_id[i]["value"] is not None]
    if not vals:
        return None
    binary = all(v in (0.0, 1.0) for v in vals)
    if binary:
        ci = stats.wilson(int(sum(vals)), len(vals))
        method = "wilson"
    else:
        ci = stats.bootstrap_ci(vals, n_boot=n_boot, seed=seed)
        method = "bootstrap"
    return {"value": stats.mean(vals), "ci_lo": ci[0], "ci_hi": ci[1], "ci_method": method,
            "n_items": len(vals)}


def profile(data, ref=None, n_boot=2000, seed=0):
    """-> dict with cols, rows[(inst,cat)] -> {col: cell}, deltas."""
    cells = defaultdict(dict)       # (inst, cat) -> col -> cell
    itemvals = defaultdict(dict)    # (inst, cat) -> col -> {item_id: item}
    colset = {}                     # (col, inst, cat) -> iset
    cols = set()
    for (lane, inst, iset), g in sorted(data.groups.items(), key=str):
        col = data.col_name(lane, inst, iset)
        cols.add(col)
        bycat = defaultdict(dict)
        for iid, it in g["items"].items():
            if it["value"] is not None:
                bycat[it["category"]][iid] = it
        for cat, items in bycat.items():
            colset[(col, inst, cat)] = iset
            cells[(inst, cat)][col] = _cell(items, n_boot, seed)
            itemvals[(inst, cat)][col] = items
    cols = sorted(cols)
    deltas = defaultdict(dict)
    if ref:
        for (inst, cat), by_col in itemvals.items():
            refcols = [c for c in by_col if c == ref or c.startswith(ref + "[")]
            if not refcols:
                continue
            rcol = refcols[0]
            for col, items in by_col.items():
                if col == rcol:
                    continue
                if colset.get((col, inst, cat)) != colset.get((rcol, inst, cat)):
                    deltas[(inst, cat)][col] = {"skipped": "item_set differs from ref"}
                    continue
                a = {i: v["value"] for i, v in items.items()}
                b = {i: v["value"] for i, v in by_col[rcol].items()}
                d = stats.paired_delta(a, b, n_boot=n_boot, seed=seed)
                ap = {i: v["pass"] for i, v in items.items()}
                bp = {i: v["pass"] for i, v in by_col[rcol].items()}
                mc = stats.mcnemar_items(ap, bp)
                d["mcnemar_p"] = mc["p"] if mc["n"] else None
                d["mcnemar"] = mc
                d["sig"] = (d["n"] > 0 and (d["ci_lo"] > 0 or d["ci_hi"] < 0))
                d["ref_col"] = rcol
                deltas[(inst, cat)][col] = d
    return {"cols": cols, "cells": cells, "deltas": deltas}


def status_table(data):
    per = defaultdict(lambda: {"n": 0, "truncated": 0, "ctx_overflow": 0, "infra": defaultdict(int)})
    for (lane, inst, iset), g in data.groups.items():
        t = per[lane]
        for r in g["rows"]:
            t["n"] += 1
            st = r.get("status")
            if st == "truncated":
                t["truncated"] += 1
            if st == "ctx_overflow":
                t["ctx_overflow"] += 1
            if is_infra(st):
                t["infra"][st] += 1
    return per


def speed_table(data):
    per = {}
    rows_by_lane = defaultdict(lambda: {"raw": [], "rows": []})
    for (lane, _inst, _iset), g in data.groups.items():
        rows_by_lane[lane]["raw"].extend(g["raw"])
        rows_by_lane[lane]["rows"].extend(g["rows"])
    for lane, d in rows_by_lane.items():
        rows = [r for r in d["rows"] if not is_infra(r.get("status"))]
        costs = [r["cost_usd"] for r in d["raw"] if r.get("cost_usd") is not None]

        def cached_heavy(r):
            pt, ct = r.get("prompt_tokens"), r.get("cached_tokens")
            return bool(pt) and ct is not None and ct > 0.5 * pt
        per[lane] = {
            "cost_usd": sum(costs) if costs else None, "cost_rows": len(costs),
            "wall_s_median": stats.median(r["wall_s"] for r in rows if r.get("wall_s") is not None),
            "decode_ps_median": stats.median(r["decode_ps"] for r in rows
                                             if r.get("decode_ps") is not None),
            "prefill_ps_median": stats.median(
                r["prefill_ps"] for r in rows
                if r.get("prefill_ps") is not None and not cached_heavy(r)),
            "completion_tokens_mean": stats.mean(r["completion_tokens"] for r in rows
                                                 if r.get("completion_tokens") is not None),
            "reasoning_tokens_mean": stats.mean(r["reasoning_tokens"] for r in rows
                                                if r.get("reasoning_tokens") is not None),
        }
    return per


def _find(d, key):
    """First value for `key` anywhere in nested dict d."""
    if isinstance(d, dict):
        if key in d and not isinstance(d[key], (dict, list)):
            return d[key]
        for v in d.values():
            r = _find(v, key)
            if r is not None:
                return r
    return None


def preflight_table(data):
    """lane -> {run_id, started_at, checks: {check: verdict}} of its latest conformance run."""
    return {lane: {"run_id": run["run_id"], "started_at": run.get("started_at"),
                   "checks": {r["item_id"]: r.get("verdict") for r in results.dedupe(rows)}}
            for lane, (run, rows) in data.preflight.items()}


def provenance(data):
    out = []
    for (lane, inst, iset), g in sorted(data.groups.items(), key=str):
        run = sorted(g["runs"], key=lambda r: r.get("started_at") or "")[-1]
        ln = run.get("lane", {})
        h = run.get("harness", {})
        n_ctx = _find(run.get("server", {}), "n_ctx")
        if n_ctx is None:
            n_ctx = (ln.get("context") or {}).get("n_ctx")
        out.append({
            "lane": lane, "instrument": inst, "item_set": iset,
            "run_ids": sorted(r["run_id"] for r in g["runs"]),
            "quant": (ln.get("weights") or {}).get("quant"),
            "runtime": (ln.get("runtime") or {}).get("engine"),
            "build": (ln.get("runtime") or {}).get("build"),
            "git_sha": h.get("git_sha"), "dirty": h.get("dirty"),
            "server_n_ctx": n_ctx,
        })
    return out


# ------------------------------------------------------------- rendering ----

def _f(x, nd=2):
    return "-" if x is None else f"{x:.{nd}f}"


def _sg(x, nd=2):
    return "-" if x is None else f"{x:+.{nd}f}"


def render_markdown(data, prof, ref, status, speed, prov):
    L = ["# Capability profile", ""]
    for w in data.warnings:
        L.append(f"> {w}")
    if data.warnings:
        L.append("")
    cols = prof["cols"]
    L += ["## Profile (value [95% CI] n_items)", "",
          "Wilson CI when every item is binary, else paired-item bootstrap. "
          "Per-item value = mean score/correct over graded samples.", ""]
    L.append("| instrument | category | " + " | ".join(cols) + " |")
    L.append("|---|---|" + "---|" * len(cols))
    for (inst, cat) in sorted(prof["cells"]):
        row = []
        for c in cols:
            ce = prof["cells"][(inst, cat)].get(c)
            row.append("" if not ce else
                       f"{ce['value']:.2f} [{ce['ci_lo']:.2f},{ce['ci_hi']:.2f}] n={ce['n_items']}")
        L.append(f"| {inst} | {cat} | " + " | ".join(row) + " |")
    if ref and not prof["deltas"]:
        L += ["", f"## Delta vs `{ref}`", "", f"No category has runs of both `{ref}` and another lane."]
    elif ref:
        L += ["", f"## Delta vs `{ref}` (paired on shared items)", "",
              "cell = mean delta [95% bootstrap CI] n=paired items, McNemar exact p "
              "(per-item majority outcome); `*` = CI excludes 0.", ""]
        others = [c for c in cols if not (c == ref or c.startswith(ref + "["))]
        L.append("| instrument | category | " + " | ".join(others) + " |")
        L.append("|---|---|" + "---|" * len(others))
        for (inst, cat) in sorted(prof["deltas"]):
            row = []
            for c in others:
                d = prof["deltas"][(inst, cat)].get(c)
                if not d:
                    row.append("")
                elif "skipped" in d:
                    row.append(d["skipped"])
                elif d["n"] == 0:
                    row.append("no shared items")
                else:
                    p = "-" if d["mcnemar_p"] is None else f"{d['mcnemar_p']:.3f}"
                    row.append(f"{_sg(d['mean_delta'])} [{_sg(d['ci_lo'])},{_sg(d['ci_hi'])}] "
                               f"n={d['n']} p={p}{' *' if d['sig'] else ''}")
            L.append(f"| {inst} | {cat} | " + " | ".join(row) + " |")
    pre = preflight_table(data)
    if pre:
        L += ["", "## Preflight (latest conformance run per lane)", "",
              "FAIL = a pipeline or lane-settings problem (blocks runs); WARN = the model's own miss.", "",
              "| lane | run | pass | warn | fail | WARN / FAIL checks |", "|---|---|---|---|---|---|"]
        for lane, p in sorted(pre.items()):
            n = defaultdict(list)
            for check, verdict in sorted(p["checks"].items()):
                n[verdict].append(check)
            flagged = ", ".join(f"{c} ({v})" for v in ("FAIL", "WARN") for c in n[v]) or "-"
            L.append(f"| {lane} | {p['run_id']} | {len(n['PASS'])} | {len(n['WARN'])} | "
                     f"{len(n['FAIL'])} | {flagged} |")
    L += ["", "## Status per lane", "",
          "| lane | attempts | truncated % | infra % | ctx_overflow | infra by status |",
          "|---|---|---|---|---|---|"]
    for lane in sorted(status):
        t = status[lane]
        n = t["n"] or 1
        infra_n = sum(t["infra"].values())
        by = ", ".join(f"{k}={v}" for k, v in sorted(t["infra"].items())) or "-"
        L.append(f"| {lane} | {t['n']} | {100 * t['truncated'] / n:.1f} | "
                 f"{100 * infra_n / n:.1f} | {t['ctx_overflow']} | {by} |")
    L += ["", "## Cost / speed per lane", "",
          "cost = sum of reported cost_usd (estimated from usage when the provider reports none); "
          "prefill median excludes rows with cached_tokens > 50% of prompt_tokens.", "",
          "| lane | cost_usd | median wall_s | median decode t/s | median prefill t/s "
          "| mean completion tok | mean reasoning tok |", "|---|---|---|---|---|---|---|"]
    for lane in sorted(speed):
        s = speed[lane]
        L.append(f"| {lane} | {_f(s['cost_usd'], 4)} | {_f(s['wall_s_median'], 1)} | "
                 f"{_f(s['decode_ps_median'], 1)} | {_f(s['prefill_ps_median'], 1)} | "
                 f"{_f(s['completion_tokens_mean'], 0)} | {_f(s['reasoning_tokens_mean'], 0)} |")
    L += ["", "## Provenance", "",
          "| lane | instrument | item_set | runs | quant | runtime/build | harness git | n_ctx |",
          "|---|---|---|---|---|---|---|---|"]
    for p in prov:
        sha = (p["git_sha"] or "?")[:9] + ("+dirty" if p["dirty"] else "")
        L.append(f"| {p['lane']} | {p['instrument']} | {p['item_set']} | "
                 f"{', '.join(p['run_ids'])} | {p['quant'] or '-'} | "
                 f"{p['runtime'] or '-'} {p['build'] or ''} | {sha} | {p['server_n_ctx'] or '-'} |")
    return "\n".join(L) + "\n"


def to_json(data, prof, ref, status, speed, prov):
    def key(k):
        return "|".join(map(str, k))
    return {
        "ref": ref, "warnings": data.warnings, "columns": prof["cols"],
        "profile": {key(k): v for k, v in prof["cells"].items()},
        "deltas": {key(k): v for k, v in prof["deltas"].items()},
        "status": {l: dict(t, infra=dict(t["infra"])) for l, t in status.items()},
        "speed": speed, "provenance": prov, "preflight": preflight_table(data),
    }


def write_csv(data, path):
    with open(path, "w", newline="") as f:
        w = csv.writer(f)
        w.writerow(["lane", "instrument", "category", "item_id", "value", "n_samples"])
        for (lane, inst, iset), g in sorted(data.groups.items(), key=str):
            col = data.col_name(lane, inst, iset)
            for iid, it in sorted(g["items"].items()):
                if it["value"] is not None:
                    w.writerow([col, inst, it["category"], iid, f"{it['value']:.6g}", it["n_graded"]])


def main(argv=None):
    ap = argparse.ArgumentParser(prog="bench.py report", description=__doc__.split("\n\n")[0])
    ap.add_argument("--instruments")
    ap.add_argument("--lanes")
    ap.add_argument("--ref", default="claude-opus")
    ap.add_argument("--out")
    ap.add_argument("--json")
    ap.add_argument("--csv")
    ap.add_argument("--include-incomplete", action="store_true")
    ap.add_argument("--boot", type=int, default=2000)
    ap.add_argument("--seed", type=int, default=0)
    a = ap.parse_args(sys.argv[1:] if argv is None else argv)
    insts = set(a.instruments.split(",")) if a.instruments else None
    lanes = set(a.lanes.split(",")) if a.lanes else None
    if lanes and a.ref:
        lanes.add(a.ref)
    data = collect(insts, lanes, a.include_incomplete)
    if not data.groups and not data.preflight:
        print("no runs found (complete runs only unless --include-incomplete)")
        raise SystemExit(1)
    ref = a.ref if a.ref else None
    prof = profile(data, ref, a.boot, a.seed)
    status, speed, prov = status_table(data), speed_table(data), provenance(data)
    md = render_markdown(data, prof, ref, status, speed, prov)
    print(md)
    if a.out:
        with open(a.out, "w") as f:
            f.write(md)
    if a.json:
        with open(a.json, "w") as f:
            json.dump(to_json(data, prof, ref, status, speed, prov), f, indent=2, default=str)
    if a.csv:
        write_csv(data, a.csv)


if __name__ == "__main__":
    main()