File size: 22,844 Bytes
4e189ca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
#!/usr/bin/env python3
"""Regenerate every number, table and figure in paper.tex from the item-level evidence.

  python3 figures/make_figures.py --decl <batch1 decl dir> --decl <batch2 decl dir> \
      --items <dir holding every run's items.jsonl> [--p100-decl <dir>]

Writes figures/*.pdf + *.png, tables/*.tex and build/numbers.json (plus tables/numbers.tex,
a file of \\newcommand macros that paper.tex \\input's, so no number in the text is typed by hand).
Everything is rebuilt from the per-item runs and cross-checked against the signed-capsule
declarations by xhw.load(); a mismatch aborts.
"""
from __future__ import annotations

import argparse
import collections
import json
import math
import os
import sys

HERE = os.path.dirname(os.path.abspath(__file__))
ROOT = os.path.dirname(HERE)
sys.path.insert(0, HERE)
import xhw  # noqa: E402

import matplotlib  # noqa: E402
matplotlib.use("Agg")
import matplotlib.pyplot as plt  # noqa: E402

# palette: validated with the dataviz validator (light surface, adjacent pairs, all hard gates pass)
C_IDENT, C_RAWONLY, C_SWAP, C_FLIP = "#2a78d6", "#1baf7a", "#4a3aa7", "#eb6834"
INK, INK2, MUTED, GRID = "#0b0b0b", "#52514e", "#898781", "#e1e0d9"
SEQ = ["#fcfcfb", "#cde2fb", "#9ec5f4", "#6da7ec", "#3987e5", "#256abf", "#184f95", "#0d366b"]

plt.rcParams.update({
    "font.family": "DejaVu Sans", "font.size": 8, "axes.edgecolor": "#c3c2b7", "axes.labelcolor": INK2,
    "xtick.color": INK2, "ytick.color": INK2, "axes.spines.top": False, "axes.spines.right": False,
    "axes.grid": False, "pdf.fonttype": 42, "savefig.dpi": 200,
})

# Read from the T4 ollama serve logs (print_info: file type; load_tensors: CUDA0/CUDA1 model buffer).
# The same GGUF blobs (same manifest digest) ran on the 3090; the 3090-side layout is UNRECORDED.
QUANT = {"mistral-nemo:12b": "Q4_0", "gemma3:12b": "Q4_K_M", "gemma3:4b": "Q4_K_M", "llama3.1:8b": "Q4_K_M",
         "llama3.2:3b": "Q4_K_M", "mistral:7b": "Q4_K_M", "phi3.5:3.8b": "Q4_0", "qwen2.5:0.5b-instruct": "Q4_K_M",
         "qwen2.5:1.5b": "Q4_K_M", "qwen2.5:7b": "Q4_K_M", "qwen3:8b": "Q4_K_M"}
T4_SPLIT = {"mistral-nemo:12b": True, "gemma3:12b": True, "phi3.5:3.8b": True}
PARAMS_B = {"mistral-nemo:12b": 12.2, "gemma3:12b": 12.2, "gemma3:4b": 4.3, "llama3.1:8b": 8.0, "llama3.2:3b": 3.2,
            "mistral:7b": 7.2, "phi3.5:3.8b": 3.8, "qwen2.5:0.5b-instruct": 0.5, "qwen2.5:1.5b": 1.5,
            "qwen2.5:7b": 7.6, "qwen3:8b": 8.2}


def wilson(k: int, n: int, z: float = 1.96) -> tuple[float, float]:
    if n == 0:
        return (float("nan"), float("nan"))
    p = k / n
    d = 1 + z * z / n
    c = (p + z * z / (2 * n)) / d
    h = z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) / d
    return (c - h, c + h)


def binom_two_sided(k: int, n: int) -> float:
    """Exact two-sided sign test p-value, H0 p = 1/2."""
    tail = sum(math.comb(n, i) for i in range(0, min(k, n - k) + 1)) / 2 ** n
    return min(1.0, 2 * tail)


def pct(a: int, b: int, d: int = 1) -> str:
    return f"{100 * a / b:.{d}f}" if b else "--"


def common_prefix(a: str, b: str) -> int:
    n = min(len(a), len(b))
    i = 0
    while i < n and a[i] == b[i]:
        i += 1
    return i


def tex_escape(s: str) -> str:
    return s.replace("_", r"\_").replace("%", r"\%").replace("&", r"\&")


def model_order(cards):
    return sorted({c.model for c in cards}, key=lambda m: (PARAMS_B.get(m, 0), m))


def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("--decl", action="append", required=True)
    ap.add_argument("--items", action="append", required=True)
    ap.add_argument("--p100-decl", default=None, help="third-runtime declarations, when the P100 run completes")
    a = ap.parse_args()

    cards = xhw.load(a.decl, a.items)
    os.makedirs(os.path.join(ROOT, "build"), exist_ok=True)
    os.makedirs(os.path.join(ROOT, "tables"), exist_ok=True)
    N = {}

    # ------------------------------------------------------------------ totals
    def tally(cs):
        t = collections.Counter()
        for c in cs:
            p = c.pair()
            for k in ("n", "raw_eq", "label_eq", "grade_eq", "status_eq", "flips", "flips_up", "flips_down", "swaps"):
                t[k] += p[k]
            t["cards"] += 1
            t["itemwise"] += p["itemwise_grade_equal"]
            t["admit_item"] += p["admitted_item_rule"]
            t["admit_count"] += p["admitted_count_rule"]
            t["agg_only"] += p["aggregate_equal"] and not p["itemwise_grade_equal"]
            t["itemwise_not_agg"] += p["itemwise_grade_equal"] and not p["aggregate_equal"]
            t["raw_identical_cards"] += p["raw_eq"] == p["n"]
            t["n30"] += c.decl["n"] >= 30
            t["admit_item_n30"] += p["admitted_item_rule"] and c.decl["n"] >= 30
        return t

    for label, cs in (("all", cards), ("b1", [c for c in cards if c.batch == "batch1"]),
                      ("b2", [c for c in cards if c.batch == "batch2"])):
        t = tally(cs)
        for k, v in t.items():
            N[f"{label}_{k}"] = v
        N[f"{label}_raw_eq_pct"] = pct(t["raw_eq"], t["n"])
        N[f"{label}_grade_eq_pct"] = pct(t["grade_eq"], t["n"])
        N[f"{label}_label_eq_pct"] = pct(t["label_eq"], t["n"])
        N[f"{label}_status_eq_pct"] = pct(t["status_eq"], t["n"])
        lo, hi = wilson(t["n"] - t["grade_eq"], t["n"])
        N[f"{label}_flip_rate_pct"] = pct(t["n"] - t["grade_eq"], t["n"], 2)
        N[f"{label}_flip_rate_ci"] = f"{100*lo:.2f}--{100*hi:.2f}"
        N[f"{label}_models"] = len({c.model for c in cs})
        N[f"{label}_axes"] = len({c.axis for c in cs})
    N["sign_test_p"] = f"{binom_two_sided(N['all_flips_up'], N['all_flips']):.2f}"

    # raw differs -> how often does the grade move?
    raw_diff = N["all_n"] - N["all_raw_eq"]
    N["all_raw_diff"] = raw_diff
    N["raw_diff_grade_moves_pct"] = pct(N["all_n"] - N["all_grade_eq"], raw_diff)

    # ------------------------------------------------------------------ repeat
    rep = collections.defaultdict(collections.Counter)
    rep_flip_overlap = 0
    for c in cards:
        if not c.has_repeat():
            continue
        q = c.pair("t4", "t4_repeat")
        r = rep[c.model]
        r["cards"] += 1
        r["items"] += q["n"]
        r["nonident_cards"] += q["raw_eq"] < q["n"]
        r["raw_diff"] += q["n"] - q["raw_eq"]
        r["grade_diff"] += q["n"] - q["grade_eq"]
        r["status_diff"] += q["n"] - q["status_eq"]
        r["count_diff_cards"] += not q["aggregate_equal"]
        r["itemwise_fail_cards"] += q["grade_eq"] < q["n"]
        unstable = {i for i in c.order() if c.items[i]["t4"]["raw_output_sha256"] != c.items[i]["t4_repeat"]["raw_output_sha256"]}
        rep_flip_overlap += len(unstable & set(c.pair()["flip_ids"]))
    R = collections.Counter()
    for m in rep.values():
        R.update(m)
    for k, v in R.items():
        N[f"rep_{k}"] = v
    N["rep_missing_cards"] = sum(1 for c in cards if not c.has_repeat())
    N["rep_flip_overlap"] = rep_flip_overlap
    N["rep_b1_nonident"] = sum(1 for c in cards if c.batch == "batch1" and c.has_repeat()
                               and c.pair("t4", "t4_repeat")["raw_eq"] < len(c.items))
    N["rep_models_nonident"] = sum(1 for m in rep.values() if m["nonident_cards"])

    # ------------------------------------------------------------------ swaps and first divergence
    swap_rows, prefixes, prefix_len_stop = [], [], collections.Counter()
    length_items = length_raw_diff = stop_items = stop_raw_diff = 0
    for c in cards:
        p = c.pair()
        for i in p["swap_ids"]:
            x, y = c.items[i]["rtx3090"], c.items[i]["t4"]
            swap_rows.append((c, i, xhw.item_status(x), xhw.item_status(y)))
        for i in c.order():
            x, y = c.items[i]["rtx3090"], c.items[i]["t4"]
            is_len = "length" in (x["done_reason"], y["done_reason"])
            if is_len:
                length_items += 1
                length_raw_diff += x["raw_output_sha256"] != y["raw_output_sha256"]
            else:
                stop_items += 1
                stop_raw_diff += x["raw_output_sha256"] != y["raw_output_sha256"]
            if x["raw_output_sha256"] != y["raw_output_sha256"]:
                k = common_prefix(x["raw_output"], y["raw_output"])
                prefixes.append((k, x["grade"] != y["grade"]))
    N["swaps_total"] = len(swap_rows)
    N["swaps_pe_on_3090"] = sum(1 for r in swap_rows if r[2] == "excluded")
    N["swaps_pe_on_t4"] = sum(1 for r in swap_rows if r[3] == "excluded")
    N["swap_cards"] = len({r[0].card_id for r in swap_rows})
    N["len_items"], N["len_raw_diff_pct"] = length_items, pct(length_raw_diff, length_items)
    N["stop_items"], N["stop_raw_diff_pct"] = stop_items, pct(stop_raw_diff, stop_items)
    ks = sorted(k for k, _ in prefixes)
    N["prefix_median"] = ks[len(ks) // 2]
    N["prefix_zero"] = sum(1 for k in ks if k == 0)
    N["prefix_zero_pct"] = pct(N["prefix_zero"], len(ks))

    # cards whose item-level disagreement is hidden by the total, and the size of the total's error
    hidden = [c for c in cards if c.pair()["aggregate_equal"] and not c.pair()["itemwise_grade_equal"]]
    N["hidden_cards"] = len(hidden)
    N["hidden_flips"] = sum(c.pair()["flips"] for c in hidden)
    N["hidden_b1_list"] = ", ".join(f"\\texttt{{{c.axis}}}" for c in hidden if c.batch == "batch1")
    within = beyond = 0
    dacc = []
    for c in cards:
        p = c.pair()
        if p["itemwise_grade_equal"] and p["aggregate_equal"]:
            continue
        a3, a4 = c.accuracy("rtx3090"), c.accuracy("t4")
        n3 = c.counts("rtx3090")["graded_n"]
        se = math.sqrt(max(a3 * (1 - a3), 1e-9) / n3) if n3 else float("inf")
        d = abs(a4 - a3)
        dacc.append(d)
        within += d <= 1.96 * se
        beyond += d > 1.96 * se
    N["dacc_cards"], N["dacc_within_ci"], N["dacc_beyond_ci"] = len(dacc), within, beyond
    N["dacc_max_pp"] = f"{100 * max(dacc):.1f}"
    N["dacc_median_pp"] = f"{100 * sorted(dacc)[len(dacc) // 2]:.1f}"

    # ------------------------------------------------------------------ tables
    models = model_order(cards)
    rows = []
    for m in models:
        cs = [c for c in cards if c.model == m]
        t = tally(cs)
        r = rep.get(m, collections.Counter())
        rows.append((m, cs[0].digest[:12], QUANT[m], "2" if T4_SPLIT.get(m) else "1", t, r))
    with open(os.path.join(ROOT, "tables", "models.tex"), "w") as fh:
        fh.write("\\begin{tabular}{lllrrr}\n\\toprule\n")
        fh.write("Model (Ollama tag) & Manifest digest & Quant. & T4s & Cards & Items \\\\\n\\midrule\n")
        for m, dg, q, sp, t, _ in rows:
            fh.write(f"\\texttt{{{tex_escape(m)}}} & \\texttt{{{dg}}}\\ldots & {tex_escape(q)} & {sp} & {t['cards']} & {t['n']:,} \\\\\n".replace(",", "{,}"))
        fh.write(f"\\midrule\nTotal & & & & {N['all_cards']} & {N['all_n']:,} \\\\\n".replace(",", "{,}"))
        fh.write("\\bottomrule\n\\end{tabular}\n")
    with open(os.path.join(ROOT, "tables", "per_model.tex"), "w") as fh:
        fh.write("\\begin{tabular}{lrrrrrrrr}\n\\toprule\n")
        fh.write(" & & \\multicolumn{3}{c}{Items equal (\\%)} & \\multicolumn{2}{c}{Flips} & \\multicolumn{2}{c}{Cards (of 14)} \\\\\n")
        fh.write("\\cmidrule(lr){3-5}\\cmidrule(lr){6-7}\\cmidrule(lr){8-9}\n")
        fh.write("Model & Items & Raw & Label & Grade & $\\uparrow$ & $\\downarrow$ & Item-eq. & Hidden \\\\\n\\midrule\n")
        for m, _, _, _, t, _ in rows:
            fh.write(f"\\texttt{{{tex_escape(m)}}} & {t['n']:,} & {pct(t['raw_eq'], t['n'])} & {pct(t['label_eq'], t['n'])} & "
                     f"{pct(t['grade_eq'], t['n'])} & {t['flips_up']} & {t['flips_down']} & {t['itemwise']} & {t['agg_only']} \\\\\n".replace(",", "{,}"))
        T = tally(cards)
        fh.write(f"\\midrule\nAll & {T['n']:,} & {pct(T['raw_eq'], T['n'])} & {pct(T['label_eq'], T['n'])} & {pct(T['grade_eq'], T['n'])} & "
                 f"{T['flips_up']} & {T['flips_down']} & {T['itemwise']} & {T['agg_only']} \\\\\n".replace(",", "{,}"))
        fh.write("\\bottomrule\n\\end{tabular}\n")
    axes = sorted({c.axis for c in cards})
    with open(os.path.join(ROOT, "tables", "per_axis.tex"), "w") as fh:
        fh.write("\\begin{tabular}{lrrrrrrr}\n\\toprule\n")
        fh.write("Axis & Items/card & Raw\\,\\% & Grade\\,\\% & Flips & Swaps & Item-eq. & Hidden \\\\\n\\midrule\n")
        for ax in axes:
            cs = [c for c in cards if c.axis == ax]
            t = tally(cs)
            ipc = sorted({len(c.items) for c in cs})
            ipc_s = str(ipc[0]) if len(ipc) == 1 else f"{ipc[0]}--{ipc[-1]}"
            fh.write(f"\\texttt{{{ax}}} & {ipc_s} & {pct(t['raw_eq'], t['n'])} & {pct(t['grade_eq'], t['n'])} & {t['flips']} & "
                     f"{t['swaps']} & {t['itemwise']}/{t['cards']} & {t['agg_only']} \\\\\n")
        fh.write("\\bottomrule\n\\end{tabular}\n")
    with open(os.path.join(ROOT, "tables", "repeat.tex"), "w") as fh:
        fh.write("\\begin{tabular}{lrrrrrr}\n\\toprule\n")
        fh.write("Model & Cards & Items & Cards not & Items raw & Items grade & Cards count \\\\\n")
        fh.write(" & repeated & & byte-identical & differs & differs & differs \\\\\n\\midrule\n")
        for m in models:
            r = rep[m]
            fh.write(f"\\texttt{{{tex_escape(m)}}} & {r['cards']} & {r['items']:,} & {r['nonident_cards']} & {r['raw_diff']} & {r['grade_diff']} & {r['count_diff_cards']} \\\\\n".replace(",", "{,}"))
        fh.write(f"\\midrule\nAll & {R['cards']} & {R['items']:,} & {R['nonident_cards']} & {R['raw_diff']} & {R['grade_diff']} & {R['count_diff_cards']} \\\\\n".replace(",", "{,}"))
        fh.write("\\bottomrule\n\\end{tabular}\n")
    # admission: counts-only rule vs item-level rule, per batch
    with open(os.path.join(ROOT, "tables", "admission.tex"), "w") as fh:
        fh.write("\\begin{tabular}{lrrr}\n\\toprule\n")
        fh.write("Outcome & Batch 1 & Batch 2 & All \\\\\n\\midrule\n")

        def row(name, key):
            fh.write(f"{name} & {N['b1_' + key]} & {N['b2_' + key]} & {N['all_' + key]} \\\\\n")
        row("Cards compared", "cards")
        row("Raw output byte-identical on every item", "raw_identical_cards")
        row("Grade equal on every item", "itemwise")
        row("Totals equal (counts-only rule admits)", "admit_count")
        row("\\quad of which an item's grade differs (hidden flips)", "agg_only")
        row("Grade equal on every item but totals differ (swaps)", "itemwise_not_agg")
        row("Admitted under the item-level rule", "admit_item")
        row("\\quad of which $n \\ge 30$", "admit_item_n30")
        fh.write("\\bottomrule\n\\end{tabular}\n")
    # the swaps, one row each (small)
    with open(os.path.join(ROOT, "tables", "swaps_by_model.tex"), "w") as fh:
        by = collections.Counter((r[0].model, r[2], r[3]) for r in swap_rows)
        fh.write("\\begin{tabular}{lrr}\n\\toprule\n")
        fh.write("Model & PE on 3090, wrong on T4 & wrong on 3090, PE on T4 \\\\\n\\midrule\n")
        for m in models:
            a1 = by[(m, "excluded", "wrong")]
            a2 = by[(m, "wrong", "excluded")]
            if a1 or a2:
                fh.write(f"\\texttt{{{tex_escape(m)}}} & {a1} & {a2} \\\\\n")
        fh.write(f"\\midrule\nAll & {N['swaps_pe_on_3090']} & {N['swaps_pe_on_t4']} \\\\\n\\bottomrule\n\\end{{tabular}}\n")

    # ------------------------------------------------------------------ figures
    fig, ax = plt.subplots(figsize=(6.3, 3.3))
    ys = list(range(len(models)))[::-1]
    for y, (m, _, _, _, t, _) in zip(ys, rows):
        n = t["n"]
        seg = [(t["raw_eq"], C_IDENT), (t["grade_eq"] - t["raw_eq"] - 0, C_RAWONLY), (0, C_SWAP), (t["flips"], C_FLIP)]
        # grade-equal but raw-differs splits into status-equal and status-swapped
        seg = [(t["raw_eq"], C_IDENT), (t["grade_eq"] - t["raw_eq"] - t["swaps"], C_RAWONLY), (t["swaps"], C_SWAP), (t["flips"], C_FLIP)]
        left = 0.0
        for v, col in seg:
            w = 100 * v / n
            if w > 0:
                ax.barh(y, w, left=left, height=0.62, color=col, edgecolor="#fcfcfb", linewidth=1.0)
            left += w
        ax.text(101, y, f"{100 * (n - t['grade_eq']) / n:.1f}% flip", va="center", fontsize=7, color=INK2)
    ax.set_yticks(ys)
    ax.set_yticklabels(models, fontsize=7.5)
    ax.set_xlim(0, 112)
    ax.set_xticks([0, 20, 40, 60, 80, 100])
    ax.set_xlabel("share of items (%)  -  RTX 3090 vs. Tesla T4, same digest, prompts, decode settings")
    from matplotlib.patches import Patch
    ax.legend(handles=[Patch(color=C_IDENT, label="raw output byte-identical"),
                       Patch(color=C_RAWONLY, label="raw differs, same grade and status"),
                       Patch(color=C_SWAP, label="same grade, parse-error <-> wrong swap"),
                       Patch(color=C_FLIP, label="grade flips")],
              loc="upper center", bbox_to_anchor=(0.45, 1.2), ncol=2, frameon=False, fontsize=7)
    fig.tight_layout()
    for ext in ("pdf", "png"):
        fig.savefig(os.path.join(HERE, f"fig_per_model.{ext}"))
    plt.close(fig)

    # fig 2: flips vs net change, one point per card
    fig, ax = plt.subplots(figsize=(3.3, 2.8))
    pts = collections.Counter()
    for c in cards:
        p = c.pair()
        net = abs(c.counts("t4")["correct"] - c.counts("rtx3090")["correct"])
        pts[(p["flips"], net, p["aggregate_equal"])] += 1
    def _kind(f, agg):
        return "hidden" if (agg and f > 0) else ("equal" if (f == 0 and agg) else "other")
    for want in ("other", "equal", "hidden"):
        for (f, net, agg), k in sorted(pts.items()):
            if _kind(f, agg) != want:
                continue
            col = {"hidden": C_FLIP, "equal": C_IDENT, "other": MUTED}[want]
            ax.scatter(f, net, s=12 + 40 * math.sqrt(k), color=col, edgecolor="#fcfcfb", linewidth=0.8, zorder=3)
    mx = max(f for f, _, _ in pts)
    ax.plot([0, mx], [0, mx], color=GRID, lw=1, zorder=1)
    ax.set_xlabel("items whose grade flipped")
    ax.set_ylabel("|change in correct count|")
    ax.text(mx * 0.98, mx * 0.9, "flips all in\none direction", ha="right", va="top", fontsize=6.5, color=MUTED)
    ax.annotate(f"orange: {N['hidden_cards']} cards whose totals\nare equal but items are not", xy=(4.3, 0.3), xytext=(6.5, 6.5),
                fontsize=6.5, color=INK2, arrowprops=dict(arrowstyle="-", color=MUTED, lw=0.6))
    fig.tight_layout()
    for ext in ("pdf", "png"):
        fig.savefig(os.path.join(HERE, f"fig_flips_vs_net.{ext}"))
    plt.close(fig)

    # fig 3: model x axis heatmap of grade-flip rate
    fig, ax = plt.subplots(figsize=(6.3, 3.1))
    from matplotlib.colors import ListedColormap, BoundaryNorm
    grid = []
    for m in models:
        row_ = []
        for axn in axes:
            cs = [c for c in cards if c.model == m and c.axis == axn]
            if not cs:
                row_.append(float("nan"))
                continue
            p = cs[0].pair()
            row_.append(100 * (p["n"] - p["grade_eq"] + p["swaps"]) / p["n"])
        grid.append(row_)
    bounds = [0, 0.001, 2, 4, 6, 8, 12, 20, 100]
    cmap = ListedColormap(SEQ)
    im = ax.imshow(grid, cmap=cmap, norm=BoundaryNorm(bounds, cmap.N), aspect="auto")
    for yi, m in enumerate(models):
        for xi, axn in enumerate(axes):
            cs = [c for c in cards if c.model == m and c.axis == axn]
            if not cs:
                continue
            p = cs[0].pair()
            k = p["n"] - p["grade_eq"]
            s = p["swaps"]
            lab = f"{k}" + (f"+{s}" if s else "")
            ax.text(xi, yi, lab if (k or s) else "", ha="center", va="center", fontsize=5.5,
                    color="#ffffff" if grid[yi][xi] >= 6 else INK)
    ax.set_xticks(range(len(axes)))
    ax.set_xticklabels(axes, rotation=40, ha="right", fontsize=6.5)
    ax.set_yticks(range(len(models)))
    ax.set_yticklabels(models, fontsize=6.5)
    ax.tick_params(length=0)
    for s in ax.spines.values():
        s.set_visible(False)
    cb = fig.colorbar(im, ax=ax, fraction=0.03, pad=0.02, ticks=bounds[1:-1])
    cb.ax.set_yticklabels([">0", "2", "4", "6", "8", "12", "20"])
    cb.ax.tick_params(labelsize=6)
    cb.set_label("% of items with a grade flip or a status swap", fontsize=6.5)
    fig.tight_layout()
    for ext in ("pdf", "png"):
        fig.savefig(os.path.join(HERE, f"fig_heatmap.{ext}"))
    plt.close(fig)

    # fig 4: where raw outputs first diverge (characters of common prefix), ECDF
    fig, ax = plt.subplots(figsize=(3.3, 2.5))
    for flag, col, lab in ((False, C_RAWONLY, "grade unchanged"), (True, C_FLIP, "grade flipped")):
        v = sorted(k for k, f in prefixes if f == flag)
        if not v:
            continue
        ax.step(v, [(i + 1) / len(v) for i in range(len(v))], where="post", color=col, lw=1.6,
                label=f"{lab} (n={len(v):,})")
    ax.set_xscale("symlog", linthresh=1)
    ax.set_xlim(0, 3000)
    ax.set_xticks([0, 1, 10, 100, 1000])
    ax.set_xticklabels(["0", "1", "10", "100", "1000"])
    ax.set_xlabel("characters before the two raw outputs diverge")
    ax.set_ylabel("cumulative share of items")
    ax.legend(frameon=False, fontsize=6.5, loc="lower right")
    fig.tight_layout()
    for ext in ("pdf", "png"):
        fig.savefig(os.path.join(HERE, f"fig_divergence.{ext}"))
    plt.close(fig)

    N["prefix_flip_median"] = sorted(k for k, f in prefixes if f)[len([1 for _, f in prefixes if f]) // 2]
    N["prefix_n"] = len(prefixes)

    # ------------------------------------------------------------------ P100 (third runtime), if present
    N["p100_status"] = "PENDING"
    if a.p100_decl and os.path.isdir(a.p100_decl):
        N["p100_status"] = "PRESENT"  # the three-way analysis is filled in when the run lands

    with open(os.path.join(ROOT, "build", "numbers.json"), "w") as fh:
        json.dump(N, fh, indent=1, sort_keys=True, default=str)
    # LaTeX macros: \N<key> with non-letters removed and digits spelled out
    def macro(k: str) -> str:
        spell = {"0": "Zero", "1": "One", "2": "Two", "3": "Three", "4": "Four", "5": "Five", "6": "Six",
                 "7": "Seven", "8": "Eight", "9": "Nine"}
        return "\\N" + "".join(spell.get(ch, ch.upper() if i == 0 or k[i - 1] == "_" else ch)
                               for i, ch in enumerate(k) if ch.isalnum())
    with open(os.path.join(ROOT, "tables", "numbers.tex"), "w") as fh:
        fh.write("% generated by figures/make_figures.py -- do not edit\n")
        for k, v in sorted(N.items()):
            if isinstance(v, int):
                v = f"{v:,}".replace(",", "{,}")
            fh.write(f"\\newcommand{{{macro(k)}}}{{{v}}}\n")
    print(json.dumps(N, indent=1, sort_keys=True, default=str))


if __name__ == "__main__":
    main()