stepmold-bench / code /summarize.py
ahkamboh's picture
Add stepmold-bench: 7 models, 3 arms, 5,418 case runs
b48c9f8 verified
Raw History Blame Contribute Delete
14.1 kB
#!/usr/bin/env python3
"""Summarise bench.py results per model and arm, overall and per pack.
python3 summarize.py results/*.jsonl [--out-dir results]
Writes summary.csv (one row per model x arm x pack, with pack "ALL" for the total) and
summary.md, and prints the overall table. Standard library only, Python 3.9 or newer.
"""
import argparse
import csv
import json
import math
import os
import statistics
import sys
from collections import Counter, OrderedDict
ARM_ORDER = ("stepmold", "plain", "plain_schema")
OUTCOMES = ("passed", "escalated", "silently_wrong", "crashed")
Z95 = 1.959963984540054
COLUMNS = (
"label", "model", "arm", "pack", "n", "passed", "pass_rate", "pass_ci_low",
"pass_ci_high", "escalated_rate", "escalated_not_passed_rate", "silently_wrong_rate",
"crashed_rate", "fields_matched_mean", "calls_per_case", "retries_per_case",
"rejected_calls_per_case", "latency_median_ms", "wall_median_ms",
"prompt_tokens_per_case", "completion_tokens_per_case", "reasoning_tokens_per_case",
"top_reject_reasons",
)
def case_key(record):
return (record.get("label"), record.get("arm"), record.get("pack"), record.get("case"),
record.get("run"))
def read(paths):
"""Case records (first copy of each case-run wins), their calls, open infra errors.
A call is kept only if its case-run has a case record: a case-run that was cut off
and re-run leaves orphan calls behind, and they are not part of any result.
"""
runs, cases, calls, infra = [], OrderedDict(), [], []
for path in paths:
with open(path, "r", encoding="utf-8") as handle:
for line in handle:
line = line.strip()
if not line:
continue
try:
record = json.loads(line)
except ValueError:
continue
kind = record.get("kind") if isinstance(record, dict) else None
if kind == "case":
cases.setdefault(case_key(record), record)
elif kind == "call":
calls.append(record)
elif kind == "infra_error":
infra.append(record)
elif kind == "run":
runs.append(record)
kept = set(record.get("case_run_id") for record in cases.values())
calls = [call for call in calls if call.get("case_run_id") in kept]
infra = [record for record in infra if case_key(record) not in cases]
return runs, list(cases.values()), calls, infra
def wilson(successes, total, z=Z95):
"""Wilson score interval for a proportion, as (low, high). (None, None) when empty."""
if not total:
return None, None
p = successes / float(total)
denominator = 1.0 + z * z / total
centre = (p + z * z / (2.0 * total)) / denominator
half = z * math.sqrt(p * (1.0 - p) / total + z * z / (4.0 * total * total)) / denominator
return max(0.0, centre - half), min(1.0, centre + half)
def _mean(values):
values = [value for value in values if isinstance(value, (int, float))]
return sum(values) / float(len(values)) if values else None
def _median(values):
values = [value for value in values if isinstance(value, (int, float))]
return statistics.median(values) if values else None
def reject_reasons(calls, top=3):
"""The commonest reasons a call's answer was not committed, as (text, count).
stepmold's own wording is kept (records hold it verbatim); only the kind is added in
front when the wording does not already start with it.
"""
counts = Counter()
for call in calls:
if call.get("accepted") is not False:
continue
kind = call.get("reject_kind") or "unknown"
reason = " ".join(str(call.get("reject_reason") or "no reason given").split())
reason = reason.replace(" — ", "; ")
if not reason.startswith(kind + ":"):
reason = "%s: %s" % (kind, reason)
counts[reason] += 1
return counts.most_common(top)
def metrics(cases, calls):
n = len(cases)
passed = sum(1 for case in cases if case.get("passed"))
low, high = wilson(passed, n)
outcomes = Counter(case.get("outcome") for case in cases)
def rate(count):
return count / float(n) if n else None
fields = [case["fields_matched"] / float(case["fields_total"])
for case in cases if case.get("fields_total")]
return OrderedDict([
("n", n),
("passed", passed),
("pass_rate", rate(passed)),
("pass_ci_low", low),
("pass_ci_high", high),
("escalated_rate", rate(sum(1 for case in cases if case.get("escalated")))),
("escalated_not_passed_rate", rate(outcomes.get("escalated", 0))),
("silently_wrong_rate", rate(outcomes.get("silently_wrong", 0))),
("crashed_rate", rate(outcomes.get("crashed", 0))),
("fields_matched_mean", _mean(fields)),
("calls_per_case", _mean([case.get("calls") for case in cases])),
("retries_per_case", _mean([case.get("retries") for case in cases])),
("rejected_calls_per_case", _mean([case.get("rejected_calls") for case in cases])),
("latency_median_ms", _median([call.get("latency_ms") for call in calls])),
("wall_median_ms", _median([case.get("wall_ms") for case in cases])),
("prompt_tokens_per_case", _mean([case.get("prompt_tokens") for case in cases])),
("completion_tokens_per_case",
_mean([case.get("completion_tokens") for case in cases])),
("reasoning_tokens_per_case", _mean([case.get("reasoning_tokens") for case in cases])),
("top_reject_reasons", reject_reasons(calls)),
])
def _arm_rank(arm):
return ARM_ORDER.index(arm) if arm in ARM_ORDER else len(ARM_ORDER)
def summarize(cases, calls):
"""One row per (label, arm, pack), plus pack "ALL" per (label, arm), in report order."""
calls_by_run = {}
for call in calls:
calls_by_run.setdefault(call.get("case_run_id"), []).append(call)
groups = OrderedDict()
for case in cases:
groups.setdefault((case.get("label"), case.get("arm")), []).append(case)
rows = []
for label, arm in sorted(groups, key=lambda key: (str(key[0]), _arm_rank(key[1]),
str(key[1]))):
group = groups[(label, arm)]
model = group[0].get("model")
packs = sorted(set(case.get("pack") for case in group))
for pack in ["ALL"] + packs:
subset = group if pack == "ALL" else [c for c in group if c.get("pack") == pack]
subset_calls = [call for case in subset
for call in calls_by_run.get(case.get("case_run_id"), ())]
row = OrderedDict([("label", label), ("model", model), ("arm", arm),
("pack", pack)])
row.update(metrics(subset, subset_calls))
rows.append(row)
return rows
# ---------------------------------------------------------------------------- output
def _csv_value(key, value):
if key == "top_reject_reasons":
return "; ".join("%s (%d)" % (reason, count) for reason, count in value)
if value is None:
return ""
if isinstance(value, float):
return "%.4f" % value
return value
def write_csv(rows, path):
with open(path, "w", newline="", encoding="utf-8") as handle:
writer = csv.writer(handle)
writer.writerow(COLUMNS)
for row in rows:
writer.writerow([_csv_value(key, row.get(key)) for key in COLUMNS])
def _pct(value):
return "n/a" if value is None else "%.1f%%" % (value * 100.0)
def _num(value, digits=2):
return "n/a" if value is None else ("%.*f" % (digits, value))
def _ms(value):
return "n/a" if value is None else "%.0f ms" % value
def _pass(row):
if row["pass_rate"] is None:
return "n/a"
return "%s (%.1f to %.1f)" % (_pct(row["pass_rate"]), row["pass_ci_low"] * 100.0,
row["pass_ci_high"] * 100.0)
HEADER = ("| %s | Arm | Case-runs | Pass rate (95%% CI) | Escalated, not passed | "
"Silently wrong | Crashed | Fields matched | Calls / case | Retries / case | "
"Median call latency |")
RULE = "|---|---|---:|---|---:|---:|---:|---:|---:|---:|---:|"
def _line(first, row):
return "| %s | %s | %d | %s | %s | %s | %s | %s | %s | %s | %s |" % (
first, row["arm"], row["n"], _pass(row), _pct(row["escalated_not_passed_rate"]),
_pct(row["silently_wrong_rate"]), _pct(row["crashed_rate"]),
_pct(row["fields_matched_mean"]), _num(row["calls_per_case"]),
_num(row["retries_per_case"]), _ms(row["latency_median_ms"]))
def markdown(rows, sources, infra):
overall = [row for row in rows if row["pack"] == "ALL"]
total = sum(row["n"] for row in overall)
out = ["# stepmold-bench summary", "",
"From %s: %d case-runs." % (", ".join("`%s`" % s for s in sources), total), ""]
if infra:
out += ["%d case-run(s) hit a transport or bench error and have no result yet. "
"Run bench.py again with the same arguments to retry them." % len(infra), ""]
out += ["## Overall", "", HEADER % "Model", RULE]
out += [_line(row["label"], row) for row in overall]
for label in sorted(set(row["label"] for row in rows), key=str):
out += ["", "## %s, by pack" % label, "", HEADER % "Pack", RULE]
packs = sorted(set(row["pack"] for row in rows
if row["label"] == label and row["pack"] != "ALL"))
for pack in packs:
out += [_line(pack, row) for row in rows
if row["label"] == label and row["pack"] == pack]
out += ["", "## Tokens per case-run", "",
"| Model | Arm | Prompt | Completion | Of which reasoning | Median case-run time |",
"|---|---|---:|---:|---:|---:|"]
for row in overall:
out.append("| %s | %s | %s | %s | %s | %s |" % (
row["label"], row["arm"], _num(row["prompt_tokens_per_case"], 0),
_num(row["completion_tokens_per_case"], 0),
_num(row["reasoning_tokens_per_case"], 0), _ms(row["wall_median_ms"])))
out += ["", "## Top reject reasons", ""]
for row in overall:
out.append("**%s, %s arm** (%s rejected calls per case-run)" % (
row["label"], row["arm"], _num(row["rejected_calls_per_case"])))
out.append("")
if not row["top_reject_reasons"]:
out += ["None.", ""]
continue
out += ["| Calls | Reason |", "|---:|---|"]
out += ["| %d | %s |" % (count, reason.replace("|", "\\|"))
for reason, count in row["top_reject_reasons"]]
out.append("")
out += [
"## How to read this", "",
"- **Pass rate** is the share of case-runs that `stepmold.eval` scores as passed: "
"every expected field matches and, when the case names one, the run reached the "
"expected end node. The interval is a Wilson 95% interval that treats every "
"case-run as independent. Repeated runs of the same case are not independent, so "
"the real interval is wider.",
"- **Escalated, not passed**: the case failed, but the run took an `on_fail` or "
"`on_unsure` edge on the way, so the workflow itself flagged it. A wrong answer "
"that was flagged.",
"- **Silently wrong**: the run reached an end node normally, took no escalation "
"edge, and the answer did not match the gold case.",
"- **Crashed**: the run stopped before any end node (no edge matched, a prompt "
"could not be rendered, a node with no `on_fail` spent its retries).",
"- Passed, escalated-not-passed, silently wrong and crashed add up to 100%.",
"- **Fields matched** is the mean share of a case's expected fields that came back "
"right. A crashed run counts as zero.",
"- **Calls / case** counts every model request, think passes included. "
"**Retries / case** counts stepmold's re-samples after a rejected answer. Gate "
"draws are not retries.",
"- In the plain arm a \"rejected\" call is one whose reply held no JSON object, so "
"nothing was committed. The plain arm never asks again.",
"",
]
return "\n".join(out)
def main(argv=None):
parser = argparse.ArgumentParser(
prog="summarize.py",
description="Summarise bench.py results into summary.csv and summary.md.")
parser.add_argument("files", nargs="+", help="results JSONL files from bench.py")
parser.add_argument("--out-dir", dest="out_dir", default=None,
help="where to write summary.csv and summary.md "
"(default: the first file's directory)")
args = parser.parse_args(argv)
missing = [path for path in args.files if not os.path.isfile(path)]
if missing:
sys.stderr.write("summarize: no such file: %s\n" % ", ".join(missing))
return 2
_, cases, calls, infra = read(args.files)
if not cases:
sys.stderr.write("summarize: no case records in %s\n" % ", ".join(args.files))
return 1
rows = summarize(cases, calls)
out_dir = args.out_dir or os.path.dirname(os.path.abspath(args.files[0]))
os.makedirs(out_dir, exist_ok=True)
write_csv(rows, os.path.join(out_dir, "summary.csv"))
text = markdown(rows, [os.path.basename(path) for path in args.files], infra)
with open(os.path.join(out_dir, "summary.md"), "w", encoding="utf-8") as handle:
handle.write(text)
overall = [row for row in rows if row["pack"] == "ALL"]
print(HEADER % "Model")
print(RULE)
for row in overall:
print(_line(row["label"], row))
print("\nwrote %s and %s" % (os.path.join(out_dir, "summary.csv"),
os.path.join(out_dir, "summary.md")))
return 0
if __name__ == "__main__":
sys.exit(main())