File size: 14,077 Bytes
b48c9f8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
#!/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())