llm-bench

#!/usr/bin/env python3
"""Router oracle labels: which lanes pass each item, and the cheapest one that does.

  python3 bench.py oracle --order lane-a,lane-b,... [--lanes a,b] [--instruments x,y]
                          [--theta 0.67] [--lambda-usd X] [--out PATH.jsonl] [--simulate]
                          [--include-incomplete]

Per (instrument, item_id) and lane: pass_rate = mean of `correct` over graded samples
(pooled across runs of one item_set). A lane whose only evidence is ctx_overflow gets
pass_rate 0 (it cannot take the item); any other infra-only item is unknown (None).
feasible = lanes with pass_rate >= theta. oracle = first feasible lane in --order, or with
--lambda-usd the feasible lane minimising median wall_s + lambda * mean cost_usd.
Per item-set name (`fix-easy`, `fix-hard`, ... -- the part before `@`) only runs of ONE version are
used (the one covering most lanes; others are dropped with a warning).
"""
import argparse
import json
import os
import sys
import time
from collections import Counter, defaultdict

from bench.core import results, stats
from bench.tasks import report


def _pass_rate(it):
    if it["n_graded"] and it["pass"] is not None:
        return it["pass"]
    if it["n_ctx_overflow"]:
        return 0.0
    return None


def pick_item_sets(data):
    """(instrument, set name) -> chosen item_set version; warnings for dropped groups."""
    cover = defaultdict(lambda: defaultdict(set))
    for (lane, inst, iset) in data.groups:
        cover[(inst, report.set_name(iset))][iset].add(lane)
    chosen, warns = {}, []
    for (inst, name), by in cover.items():
        best = sorted(by, key=lambda s: (len(by[s]), str(s)))[-1]
        chosen[(inst, name)] = best
        for s in by:
            if s != best:
                warns.append(f"WARNING: {inst}: item_set {s!r} (lanes {sorted(by[s])}) "
                             f"differs from chosen {best!r}; excluded from labels.")
    return chosen, warns


def _lane_medians(data, chosen):
    """(lane, inst, set name) -> (median wall_s, mean cost) over that lane's items; fallbacks."""
    out = {}
    for (lane, inst, iset), g in data.groups.items():
        name = report.set_name(iset)
        if chosen.get((inst, name)) != iset:
            continue
        w = [x for it in g["items"].values() for x in it["wall_s"]]
        c = [x for it in g["items"].values() for x in it["cost_usd"]]
        out[(lane, inst, name)] = (stats.median(w), stats.mean(c))
    return out


def derive(data, order, theta=0.67, lambda_usd=None):
    """-> (label rows, warnings). Pure function of a report.Data; order = lanes, cheapest first."""
    chosen, warns = pick_item_sets(data)
    lm = _lane_medians(data, chosen)
    per = defaultdict(lambda: defaultdict(dict))  # (inst, set name, iid) -> lane -> item
    cat = {}
    for (lane, inst, iset), g in data.groups.items():
        name = report.set_name(iset)
        if chosen.get((inst, name)) != iset:
            continue
        for iid, it in g["items"].items():
            per[(inst, name, iid)][lane] = it
            cat[(inst, name, iid)] = it["category"]
    all_lanes = sorted({k[0] for k in data.groups})
    rank = {l: i for i, l in enumerate(order)}
    rows = []
    for (inst, name, iid) in sorted(per):
        lanes = per[(inst, name, iid)]
        pr, wall, cost, ns = {}, {}, {}, {}
        for lane in all_lanes:
            it = lanes.get(lane)
            if it is None:
                pr[lane] = None
                continue
            pr[lane] = _pass_rate(it)
            lw, lc = lm.get((lane, inst, name), (None, None))
            wall[lane] = stats.median(it["wall_s"]) if it["wall_s"] else lw
            cost[lane] = stats.mean(it["cost_usd"]) if it["cost_usd"] else lc
            ns[lane] = it["n_graded"]
        feasible = [l for l in all_lanes if pr.get(l) is not None and pr[l] >= theta]
        if lambda_usd is not None:
            def key(l):
                w = wall.get(l)
                return (float("inf") if w is None else w + lambda_usd * (cost.get(l) or 0.0),
                        rank.get(l, 1e9), l)
        else:
            def key(l):
                return (rank.get(l, 1e9), l)
        # lanes in --order first; lanes not in the order list only matter if nothing else
        cand = sorted(feasible, key=key)
        if lambda_usd is None:
            cand = [l for l in cand if l in rank] + [l for l in cand if l not in rank]
        oracle = cand[0] if cand else None
        rows.append({"instrument": inst, "item_set": chosen[(inst, name)], "item_id": iid,
                     "category": cat[(inst, name, iid)], "pass_rate": pr, "feasible": feasible,
                     "difficulty": len(feasible), "oracle": oracle,
                     "label": oracle if oracle else "none",
                     "unknown_lanes": [l for l in all_lanes if pr.get(l) is None],
                     "n_samples": ns, "median_wall_s": wall, "mean_cost_usd": cost})
    return rows, warns


def histogram(rows):
    h = defaultdict(Counter)
    for r in rows:
        h[(r["instrument"], r["category"])][r["label"]] += 1
    return h


# ------------------------------------------------------------- simulation ----

def _tc(r, lane):
    return (r["median_wall_s"].get(lane) or 0.0, r["mean_cost_usd"].get(lane) or 0.0)


def cascade_eval(items, order):
    """items: label rows restricted to complete cases. Returns (success, latency, total_cost).
    Success prob of a lane = pass_rate; attempts are independent; stop at first success."""
    succ = lat = cost = 0.0
    for r in items:
        reach = 1.0
        for lane in order:
            p = r["pass_rate"][lane]
            t, c = _tc(r, lane)
            lat += reach * t
            cost += reach * c
            succ += reach * p
            reach *= 1 - p
    n = len(items)
    return succ / n, lat / n, cost


def simulate(rows, order, lanes=None):
    """Policy comparison on items where every simulated lane has data.
    -> dict(n_items, n_dropped, policies=[{policy, success, latency_s, cost_usd}])"""
    all_lanes = sorted({l for r in rows for l in r["pass_rate"]})
    lanes = [l for l in (lanes or all_lanes) if l in all_lanes]
    items = [r for r in rows if all(r["pass_rate"].get(l) is not None for l in lanes)]
    ordered = [l for l in order if l in lanes] + [l for l in lanes if l not in order]
    pols = []
    if not items:
        return {"n_items": 0, "n_dropped": len(rows), "policies": pols, "lanes": lanes}
    n = len(items)
    for l in lanes:
        pols.append({"policy": f"always-{l}",
                     "success": sum(r["pass_rate"][l] for r in items) / n,
                     "latency_s": sum(_tc(r, l)[0] for r in items) / n,
                     "cost_usd": sum(_tc(r, l)[1] for r in items)})
    # oracle: label lane among simulated lanes; items with none -> highest pass_rate lane
    s = t = c = 0.0
    for r in items:
        cand = [l for l in ordered if l in r["feasible"]]
        lane = cand[0] if cand else max(reversed(ordered), key=lambda x: r["pass_rate"][x])
        s += r["pass_rate"][lane]
        t += _tc(r, lane)[0]
        c += _tc(r, lane)[1]
    pols.append({"policy": "oracle", "success": s / n, "latency_s": t / n, "cost_usd": c})
    cs, cl, cc = cascade_eval(items, ordered)
    pols.append({"policy": "cascade(" + ">".join(ordered) + ")", "success": cs,
                 "latency_s": cl, "cost_usd": cc})
    return {"n_items": n, "n_dropped": len(rows) - n, "policies": pols, "lanes": lanes}


def render_simulation(sim):
    L = [f"Simulation on {sim['n_items']} items with data for all of {sim['lanes']} "
         f"({sim['n_dropped']} dropped)", "",
         f"{'policy':<60} {'success':>8} {'latency_s':>10} {'total_usd':>10}"]
    for p in sim["policies"]:
        L.append(f"{p['policy']:<60} {p['success']:>8.3f} {p['latency_s']:>10.1f} {p['cost_usd']:>10.4f}")
    return "\n".join(L)


def render_histogram(h):
    L = ["Label histogram per (instrument, category):"]
    for (inst, cat) in sorted(h):
        L.append(f"  {inst:<18} {cat:<28} " + ", ".join(f"{k}={v}" for k, v in sorted(h[(inst, cat)].items())))
    return "\n".join(L)


def main(argv=None):
    ap = argparse.ArgumentParser(prog="bench.py oracle", description=__doc__.split("\n\n")[0])
    ap.add_argument("--lanes")
    ap.add_argument("--instruments")
    ap.add_argument("--theta", type=float, default=0.67)
    ap.add_argument("--order", required=True, help="lanes, cheapest first (comma-separated)")
    ap.add_argument("--lambda-usd", type=float, default=None)
    ap.add_argument("--out")
    ap.add_argument("--simulate", action="store_true")
    ap.add_argument("--include-incomplete", action="store_true")
    a = ap.parse_args(sys.argv[1:] if argv is None else argv)
    data = report.collect(set(a.instruments.split(",")) if a.instruments else None,
                          set(a.lanes.split(",")) if a.lanes else None, a.include_incomplete)
    if not data.groups:
        print("no runs found (complete runs only unless --include-incomplete)")
        raise SystemExit(1)
    order = a.order.split(",")
    rows, warns = derive(data, order, a.theta, a.lambda_usd)
    for w in data.warnings + warns:
        print(w)
    out = a.out or os.path.join(results.RESULTS_DIR, "_oracle",
                                time.strftime("oracle-%Y%m%d-%H%M%S.jsonl"))
    os.makedirs(os.path.dirname(os.path.abspath(out)), exist_ok=True)
    with open(out, "w") as f:
        for r in rows:
            f.write(json.dumps(r) + "\n")
    print(f"wrote {len(rows)} labels -> {out}")
    print(render_histogram(histogram(rows)))
    if a.simulate:
        print()
        print(render_simulation(simulate(rows, order, a.lanes.split(",") if a.lanes else None)))


if __name__ == "__main__":
    main()