File size: 29,740 Bytes
24aaa76
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Tests of report_cards.py: status labels (each status and its boundary), language and learning-curve flags, gallery sources,
comparison matrix ranks, failure-mode shares, and operation with the reduced prediction set of amendment 3.3 D9.
usage: python -I test_report_cards.py [workdir]. Synthetic data only."""
import hashlib
import json
import os
import shutil
import subprocess
import sys
import tempfile
import traceback

HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
sys.path.insert(0, os.path.join(HERE, "..", "src"))
import synth_world as sw  # noqa: E402
from r5eval import cards, verdictlib  # noqa: E402

SCORE = os.path.join(HERE, "..", "scripts", "r5eval", "score.py")
CARDS = os.path.join(HERE, "..", "scripts", "r5eval", "report_cards.py")
RESULTS = []
W = {}


def test(fn):
    try:
        fn()
        RESULTS.append((fn.__name__, True))
        print("PASS", fn.__name__)
    except Exception:  # noqa: BLE001
        RESULTS.append((fn.__name__, False))
        print("FAIL", fn.__name__)
        print(traceback.format_exc())
    return fn


# ------------------------------------------------------------------------------------------- units: status boundaries
def fake_sets(cer, hr4=0.0, hr1=None):
    s = {"V1": {"coverage": {"complete": True}, "profiles": {"plain": {"groups": {"all": {"metrics": {
        "cer": {"value": cer, "num": cer * 1000, "den": 1000}, "hr4": {"value": hr4, "num": 0, "den": 1000}}}}}}}}
    if hr1 is not None:
        s["synth_clutter_val"] = {"coverage": {"complete": True}, "profiles": {"plain": {"groups": {"all": {"metrics": {
            "hr1": {"value": hr1, "num": hr1 * 100, "den": 100}}}}}}}
    return s


def status(cer, lowest=0.10, info=None, meta=None, hr1=None, hr4=0.0, hr1_a1=0.0, cls_low=None, arm="vlm_x", params=1.0):
    info = dict({"unique_params_b": params}, **(info or {}))
    ctx = {"lowest": lowest, "lowest_by_class": cls_low if cls_low is not None else {"middle": 0.0001}, "hr1_a1": hr1_a1}
    return cards.assign_status(arm, info, fake_sets(cer, hr4, hr1), meta or {}, ctx, None)


@test
def t_status_order_and_boundaries():
    assert status(0.15)[0] == "COMPETITIVE" and status(0.1500001)[0] == "NOT COMPETITIVE"       # 1.5 x the lowest
    assert status(0.11)[0] == "PROMISING" and status(0.1101)[0] == "COMPETITIVE"                # within 10%
    assert status(0.14, cls_low={"middle": 0.14})[0] == "PROMISING"                              # lowest in its size class
    assert status(0.14, cls_low={"large": 0.14}, params=2.0)[0] == "PROMISING"
    assert status(0.14, cls_low={"middle": 0.13})[0] == "COMPETITIVE"
    # an arm with no parameter count has no size class: the class rule is not applied to it
    s_, f_, n_ = status(0.14, cls_low={None: 0.14}, params=None)
    assert s_ == "COMPETITIVE" and f_["size_class"].startswith("unknown")
    assert status(0.2, arm="A2", cls_low={"line": 0.2})[0] == "NOT COMPETITIVE"                  # the 1.5 rule comes before the class rule
    assert status(0.12, arm="A2", cls_low={"line": 0.12})[0] == "PROMISING"
    # 1 and 2 before everything
    assert status(0.1, info={"not_trained_reason": "failed 20 steps"})[0] == "NOT TRAINED"
    assert status(0.1, meta={"train_flag": "short of P"})[0] == "PROMISING"                      # the time cap is not a broken run
    assert status(0.1, meta={"train_flag": "loss became nan at step 30"})[0] == "BROKEN RUN"
    assert status(0.1, info={"broken_run_reason": "killed"})[0] == "BROKEN RUN"
    # 3 no gain: V1 CER not lower than the arm's own zero-shot
    assert status(0.1, info={"zero_shot_v1_cer": 0.1})[0] == "NO GAIN"
    assert status(0.1, info={"zero_shot_v1_cer": 0.1001})[0] != "NO GAIN"
    assert status(0.1, info={"zero_shot_v1_cer": 1.07})[0] == "PROMISING"
    # 4 memory gate before hallucination: 24 GB read as 22.35 GiB
    big = {"peak_mem_reserved_batch1_GiB": 22.36}
    assert status(0.1, meta=big, hr1=0.5)[0] == "FAILS MEMORY GATE"
    assert status(0.1, meta={"peak_mem_reserved_batch1_GiB": 22.35})[0] == "PROMISING"
    # 5 hallucination: HR1 above max(2 x A1, A1 + 2 points) or above 5%, HR4 above 0.1% on V1
    assert status(0.1, hr1=0.03, hr1_a1=0.01)[0] == "PROMISING" and status(0.1, hr1=0.0301, hr1_a1=0.01)[0] == "HALLUCINATES"
    assert status(0.1, hr1=0.05, hr1_a1=0.04)[0] == "PROMISING" and status(0.1, hr1=0.0501, hr1_a1=0.04)[0] == "HALLUCINATES"
    assert status(0.1, hr4=0.001)[0] == "PROMISING" and status(0.1, hr4=0.0011)[0] == "HALLUCINATES"
    s, figs, note = status(0.1, hr4=0.0011)
    assert any("HR4" in r for r in figs["reasons"])
    # no V1 yet: no status is invented
    assert cards.assign_status("x", {}, {}, {}, {"lowest": None, "lowest_by_class": {}, "hr1_a1": None}, None)[0] is None


@test
def t_ranks_with_ties():
    assert cards.ranks({"a": 0.1, "b": 0.1, "c": 0.2, "d": None}, "lower") == {"a": 1, "b": 1, "c": 3}
    assert cards.ranks({"a": 5.0, "b": 9.0}, "higher") == {"b": 1, "a": 2}


# ------------------------------------------------------------------------------------------- world through score.py
LANGS = [("kk", "Cyrl"), ("ky", "Cyrl"), ("tr", "Latn")]
TRV = ["çay", "ışık", "İstanbul", "gözlük", "şeker", "üzüm", "öğrenci", "ağaç", "kitap", "okul"]


def order_key(r):
    return hashlib.md5(r["id"].encode()).hexdigest()


def damage(text, e):
    chars = list(text)
    for i in range(min(e, len(chars))):
        chars[i] = "ъ" if chars[i] != "ъ" else "ы"
    return "".join(chars)


def write_edits(path, rows, edits_fn, clutter_frac=0.0, conf=True):
    """Deterministic damage: edits_fn(row, rank) -> edits (substitutions at the start of the text). Rows are ranked by a hash of
    their id, so every arm damages the same rows first and CER ratios between arms are exact."""
    ranked = {r["id"]: k for k, r in enumerate(sorted(rows, key=order_key))}
    n_clu = sum(1 for r in rows if r["text"] == "")
    os.makedirs(os.path.dirname(path), exist_ok=True)
    with open(path, "w", encoding="utf-8", newline="") as f:
        f.write("id\tref\thyp" + ("\tconf\tconf_min\thit_cap\tn_tokens" if conf else "") + "\n")
        for r in rows:
            k = ranked[r["id"]]
            if r["text"] == "":
                hyp = "ааа" if k < clutter_frac * len(rows) else ""
            else:
                hyp = damage(r["text"], edits_fn(r, k))
            line = [r["id"], r["text"], hyp]
            if conf:
                lp = -0.05 if hyp == r["text"] else -1.0
                line += ["%.3f" % lp, "%.3f" % (lp - 0.2), "0", str(len(hyp) + 1)]
            f.write("\t".join(line) + "\n")


def build_world(root):
    W["root"] = root
    man = os.path.join(root, "manifests")
    W["preds"], W["out"], W["cards"] = os.path.join(root, "preds"), os.path.join(root, "scores"), os.path.join(root, "cards")
    v1 = sw.make_manifest(os.path.join(man, "kohtd_screen_v1.tsv"), "v1", 30, 10, seed=1)
    hand_rows, typed_rows = [], []
    for lang, script in LANGS:
        hand_rows += sw.make_manifest(os.path.join(man, "h_%s.tsv" % lang), "hs_" + lang, 10, 6, lang=lang, script=script, kind="hand_synth",
                                      unit="line", seed=hash(lang) % 50, vocab=TRV if script == "Latn" else sw.VOCAB)
        typed_rows += sw.make_manifest(os.path.join(man, "t_%s.tsv" % lang), "ts_" + lang, 5, 8, lang=lang, script=script, kind="typed_synth",
                                       unit="line", seed=7 + hash(lang) % 50, vocab=TRV if script == "Latn" else sw.VOCAB)
    for name, rows in (("synth_hand_val", hand_rows), ("synth_typed_val", typed_rows)):
        with open(os.path.join(man, name + ".tsv"), "w", encoding="utf-8", newline="") as f:
            f.write("\t".join(sw.HDR) + "\n")
            for r in rows:
                f.write("\t".join(r[c] for c in sw.HDR) + "\n")
    with open(os.path.join(man, "synth_hand_val.meta.tsv"), "w", encoding="utf-8", newline="") as f:
        f.write("id\tfont_id\tfont_group\teffects\tpage_type\n")
        for i, r in enumerate(hand_rows):
            f.write("%s\tfont%d\t%s\t%s\tnotebook\n" % (r["id"], i % 4, "unseen" if i % 2 else "seen", "pattern:ruled|stains" if i % 3 == 0 else ""))
    clu = sw.make_manifest(os.path.join(man, "synth_clutter_val.tsv"), "cv", 10, 10, clutter=True, kind="clutter", unit="line")
    cur_h = sw.make_manifest(os.path.join(man, "curve_h.tsv"), "ch", 20, 10, seed=3)
    cur_c = sw.make_manifest(os.path.join(man, "curve_c.tsv"), "cc", 5, 10, clutter=True, kind="clutter", unit="line")
    with open(os.path.join(man, "curve_v1.tsv"), "w", encoding="utf-8", newline="") as f:
        f.write("\t".join(sw.HDR) + "\n")
        for r in cur_h + cur_c:
            f.write("\t".join(r[c] for c in sw.HDR) + "\n")
    sets = [("V1", "kohtd_screen_v1"), ("synth_hand_val", "synth_hand_val"), ("synth_typed_val", "synth_typed_val"),
            ("synth_clutter_val", "synth_clutter_val"), ("curve_v1", "curve_v1")]
    sw.write_registry(os.path.join(root, "evalsets.json"), [{"name": n, "manifest": os.path.join(man, m + ".tsv"), "split": "val", "locked": False}
                                                           for n, m in sets])
    W["rows"] = {"V1": v1, "hand": hand_rows, "typed": typed_rows, "clutter": clu, "curve": cur_h + cur_c}


def add_arm(arm, ck, v1_edits, hand_fn=None, clutter=0.0, curve_edits=None, mem=9.0, samples=150000, ips=40.0):
    base = os.path.join(W["preds"], arm, ck)
    write_edits(os.path.join(base, "kohtd_screen_v1.tsv"), W["rows"]["V1"], lambda r, k: 1 if k < v1_edits else 0)
    write_edits(os.path.join(base, "V1.tsv"), W["rows"]["V1"], lambda r, k: 1 if k < v1_edits else 0)
    os.remove(os.path.join(base, "kohtd_screen_v1.tsv"))
    hf = hand_fn or (lambda r, k: 1 if k < 20 else 0)
    write_edits(os.path.join(base, "synth_hand_val.tsv"), W["rows"]["hand"], hf)
    write_edits(os.path.join(base, "synth_typed_val.tsv"), W["rows"]["typed"], lambda r, k: 1 if k < 8 else 0)
    write_edits(os.path.join(base, "synth_clutter_val.tsv"), W["rows"]["clutter"], lambda r, k: 0, clutter_frac=clutter, conf=False)
    if curve_edits is not None:
        write_edits(os.path.join(base, "curve_v1.tsv"), W["rows"]["curve"], lambda r, k: 1 if k < curve_edits else 0, conf=False)
    sw.write_meta(os.path.join(base, "meta.json"), peak_mem_reserved_batch1_GiB=mem, samples_seen=samples, images_per_second_batch16_V1=ips)


@test
def t_world_scores_and_cards():
    root = sys.argv[1] if len(sys.argv) > 1 else tempfile.mkdtemp(prefix="r5eval_cards_")
    shutil.rmtree(root, ignore_errors=True)
    os.makedirs(root)
    build_world(root)
    # V1 has 300 crops; v1_edits is the number of one-edit damaged crops, so CER = v1_edits / total reference characters
    add_arm("A1", "short", 130, hand_fn=lambda r, k: (4 if r["lang"] == "ky" else (1 if k < 12 else 0)), curve_edits=100, ips=900.0)
    add_arm("big_vlm", "short_25", 280, curve_edits=280, samples=37500)
    add_arm("big_vlm", "short_50", 200, curve_edits=200, samples=75000)
    add_arm("big_vlm", "short_75", 120, curve_edits=120, samples=112500)
    add_arm("big_vlm", "short", 100, curve_edits=40, hand_fn=lambda r, k: (2 if "unseen" and int(r["id"].split("_")[-1]) % 2 else 1) if k < 30 else 0)
    add_arm("mid_vlm", "short", 104, curve_edits=60)
    add_arm("mid_vlm", "short_75", 108, curve_edits=60, samples=112500)
    add_arm("comp_vlm", "short", 140, curve_edits=100)
    add_arm("slow_vlm", "short", 300, curve_edits=100)
    add_arm("halluc_vlm", "short", 101, clutter=0.5)
    add_arm("mem_vlm", "short", 102, clutter=0.5, mem=30.0)
    add_arm("nogain_vlm", "short", 105)
    add_arm("A1", "long", 100, hand_fn=lambda r, k: 1 if k < 12 else 0, samples=1584384)   # the line arm's long checkpoint (another budget)
    add_arm("A1", "long2x", 90, hand_fn=lambda r, k: 1 if k < 12 else 0, samples=3168768)  # amendment 3.4 E5: seed 1 continued to 2 x P_long
    add_arm("A1", "short_lm_gated", 60, hand_fn=lambda r, k: 1 if k < 12 else 0)           # extra rows read by the cards: the gated character LM
    add_arm("A1", "short_lm", 55, clutter=1.0)                                             # the LM as decoded writes on every empty image
    add_arm("big_vlm", "short_retry", 98)                                                  # the cap-retry decoding of the same checkpoint (not a retrained run)
    cmd = [sys.executable, "-I", SCORE, "--registry", os.path.join(root, "evalsets.json"), "--preds", W["preds"], "--out", W["out"], "--B", "200",
           "--settle", "0", "--workers", "4", "--ktrain", os.path.join(root, "no_ktrain.json")]      # on the cluster the default K_train exists: the test world has none
    p = subprocess.run(cmd, capture_output=True, text=True)
    assert p.returncode == 0, p.stdout[-800:] + p.stderr[-1500:]
    # a locked score file must be skipped by the cards
    os.makedirs(os.path.join(W["out"], "A1", "short"), exist_ok=True)
    json.dump({"locked": True, "status": "scored", "arm": "A1", "checkpoint": "short", "evalset": "kohtd_test", "profiles": {}},
              open(os.path.join(W["out"], "A1", "short", "kohtd_test.json"), "w"))
    json.dump({"_what": "a comment key with a string value, as in config/arms_info_vlmb_params.json: must be ignored, not treated as an arm",
               "big_vlm": {"unique_params_b": 2.0}, "mid_vlm": {"unique_params_b": 1.0}, "comp_vlm": {"unique_params_b": 1.0},
               "slow_vlm": {"unique_params_b": 1.0}, "halluc_vlm": {"unique_params_b": 1.0}, "mem_vlm": {"unique_params_b": 1.0},
               "nogain_vlm": {"unique_params_b": 1.0, "zero_shot_v1_cer": 0.02}, "broken_vlm": {"broken_run_reason": "loss became nan at step 12"},
               "dead_vlm": {"not_trained_reason": "failed the 20-step save-and-resume test"}}, open(os.path.join(root, "arms_info.json"), "w"))
    cmd = [sys.executable, "-I", CARDS, "--scores", W["out"], "--preds", W["preds"], "--out", W["cards"], "--arms-info", os.path.join(root, "arms_info.json"),
           "--leaders", "big_vlm,mid_vlm"]
    p = subprocess.run(cmd, capture_output=True, text=True)
    assert p.returncode == 0, p.stdout[-800:] + p.stderr[-2500:]


def card(arm):
    return json.load(open(os.path.join(W["cards"], arm + ".json"), encoding="utf-8"))


@test
def t_statuses_from_real_scores():
    st = {a: card(a)["status"] for a in ("A1", "big_vlm", "mid_vlm", "comp_vlm", "slow_vlm", "halluc_vlm", "mem_vlm", "nogain_vlm", "broken_vlm", "dead_vlm")}
    assert st["big_vlm"] == "PROMISING" and st["mid_vlm"] == "PROMISING"
    assert st["comp_vlm"] == "COMPETITIVE", (st, card("comp_vlm")["status_figures"])
    assert st["slow_vlm"] == "NOT COMPETITIVE"
    assert st["A1"] == "PROMISING", card("A1")["status_figures"]            # 1.3 x the lowest, but the lowest of the line arms
    assert st["halluc_vlm"] == "HALLUCINATES"
    assert st["mem_vlm"] == "FAILS MEMORY GATE"                            # also hallucinates, but the memory gate is checked first
    assert st["nogain_vlm"] == "NO GAIN"
    assert st["broken_vlm"] == "BROKEN RUN" and st["dead_vlm"] == "NOT TRAINED"
    c = card("big_vlm")
    assert c["validation_only"] is True and c["locked_score_files_skipped"] >= 1
    assert c["status_figures"]["why_promising"].startswith("V1 CER within 10%")
    idx = json.load(open(os.path.join(W["cards"], "status_index.json")))
    assert idx["arms"]["dead_vlm"]["status"] == "NOT TRAINED"


@test
def t_flags_curve_language_leader():
    a1 = card("A1")
    assert any(f["flag"] == "weak on ky" and f["set"] == "synth_hand_val" for f in a1["flags"]), a1["flags"]
    big, mid = card("big_vlm"), card("mid_vlm")
    assert big["learning_curve"]["flag"] == "still improving" and len(big["learning_curve"]["points"]) == 4
    assert [p["samples_seen"] for p in big["learning_curve"]["points"]] == [37500, 75000, 112500, 150000]
    assert mid["learning_curve"]["flag"] == "plateaued"
    assert any(f["flag"] == "LEADER" for f in big["flags"]) and not any(f["flag"] == "LEADER" for f in card("A1")["flags"])


@test
def t_sections_present_with_reduced_prediction_set():
    c = card("big_vlm")
    assert "kohtd_val" not in c["headline"] and "V1" in c["headline"] and c["headline"]["V1"]["cer"]["value"] > 0
    assert set(c["per_language"]["synth_hand_val"]["languages"]) == {"kk", "ky", "tr"}
    assert c["error_types"]["V1"]["share_of_errors"]["substitution"] == 1.0          # every damage was a substitution
    assert c["top_confusions"]["V1"] and c["special_letters"]["V1"]["kk"]
    assert c["look_alikes"]["V1"]["homoglyph_sub_rate"] is not None
    assert c["hallucination"]["synth_clutter_val"]["HR1_text_on_empty_images"]["value"] == 0.0
    assert "V1" in c["calibration"] and c["calibration"]["V1"]["conf_kind"] == "logprob"
    assert c["speed_memory"]["peak_mem_reserved_gib"] == 9.0 and c["speed_memory"]["images_per_second_batch16"] == 40.0
    assert c["postprocessing_changes"]["V1"]["outputs_changed_by_postproc_total"] == 0
    g = c["gaps"]
    assert g["unseen_font"]["all_scripts"]["gap_abs"] is not None and g["unseen_font"]["all_scripts"]["gap_abs"] > 0     # unseen fonts damaged more
    assert "needs K_train" in g["unseen_word"]["note"]
    lb = c["length_and_noise"]["by_noise_effect_and_attribute"]["synth_hand_val"]
    assert "effect:pattern:ruled" in lb and "effect:none" in lb and "fontgroup:unseen" in lb
    assert c["length_and_noise"]["by_length_bucket"]["V1"]


@test
def t_gallery_uses_only_allowed_sets():
    for arm in ("A1", "big_vlm", "comp_vlm"):
        gal = card(arm)["error_gallery"]
        ex = gal["examples"]
        assert 6 <= len(ex) <= 12, len(ex)
        assert all(e["set"] in cards.GALLERY_SETS for e in ex)
        assert not any(e["set"] in ("V1", "kohtd_val", "hkr_val", "chd_val", "school_val", "curve_v1") for e in ex)
        for e in ex:
            assert "".join(s["ref"] for s in e["diff"]) == e["reference"] and "".join(s["out"] for s in e["diff"]) == e["output"]
            assert e["character_errors"] > 0 and e["image"].startswith("/nonexistent")
    txt = open(os.path.join(W["cards"], "big_vlm.json"), encoding="utf-8").read()
    assert "v1_form_" not in json.dumps(card("big_vlm")["error_gallery"])           # no KOHTD form id in the gallery


@test
def t_matrix_and_failure_modes():
    m = json.load(open(os.path.join(W["cards"], "comparison_matrix.json")))
    a = m["arms"]
    # edits on V1: big 100, halluc 101, mem 102, mid 104, nogain 105, A1 130, comp 140, slow 300
    assert [a[x]["v1_cer"]["rank"] for x in ("big_vlm", "halluc_vlm", "mem_vlm", "mid_vlm", "nogain_vlm", "A1", "comp_vlm", "slow_vlm")] == [1, 2, 3, 4, 5, 6, 7, 8]
    assert a["dead_vlm"]["v1_cer"]["value"] is None and a["dead_vlm"]["v1_cer"]["rank"] is None
    assert a["A1"]["images_per_second"]["rank"] == 1               # higher is better
    assert a["mem_vlm"]["peak_mem_reserved_gib"]["rank"] == max(x["peak_mem_reserved_gib"]["rank"] or 0 for x in a.values())
    assert {x["key"] for x in m["metrics"]} >= {"v1_cer", "hr1_clutter", "unseen_font_gap", "ece_v1", "images_per_second", "unique_params_b"}
    fm = json.load(open(os.path.join(W["cards"], "failure_modes.json")))["arms"]
    part = fm["big_vlm"]["V1"]["partition_of_character_errors"]
    assert abs(sum(part.values()) - 1.0) < 1e-12
    assert fm["big_vlm"]["V1"]["character_errors"] == 100 and fm["slow_vlm"]["V1"]["character_errors"] == 300


@test
def t_rule_file_hash_is_checked():
    bad = os.path.join(W["root"], "not_the_rule.txt")
    open(bad, "w").write("not the rule")
    p = subprocess.run([sys.executable, "-I", CARDS, "--scores", W["out"], "--preds", W["preds"], "--out", os.path.join(W["root"], "c2"), "--labels-rule", bad],
                       capture_output=True, text=True)
    assert p.returncode != 0 and "refusing" in (p.stderr + p.stdout)


@test
def t_language_flag_needs_at_least_20_errors():
    def sets_with(errors_ky):
        macro = {"value": 0.1, "per_language": {"kk": 0.05, "ky": 0.5}}
        return {"synth_hand_val": {"profiles": {"plain": {"macro": {"macro_language_cer": macro},
                                                            "groups": {"lang:ky": {"metrics": {"cer": {"num": errors_ky, "den": 100, "lo": 0.3, "hi": 0.7, "value": 0.5}}}}}}}}
    flags, sup = cards.language_flags(sets_with(20), with_suppressed=True)
    assert [f["flag"] for f in flags] == ["weak on ky"] and flags[0]["character_errors"] == 20 and flags[0]["cer_ci95"] == [0.3, 0.7] and not sup
    flags, sup = cards.language_flags(sets_with(19), with_suppressed=True)
    assert flags == [] and [f["flag"] for f in sup] == ["weak on ky"]


@test
def t_labels_carry_the_interval_of_the_deciding_figures():
    c = card("comp_vlm")
    f = c["status_figures"]
    assert f["v1_cer_ci95"][0] < f["v1_cer_at_P_short"] < f["v1_cer_ci95"][1] and f["interval_method"].startswith("95% cluster bootstrap")
    assert f["ratio_to_lowest_ci95"][0] <= f["ratio_to_lowest"] <= f["ratio_to_lowest_ci95"][1]
    assert isinstance(f["interval_crosses"], list)
    h = card("halluc_vlm")["status_figures"]
    assert h["hr1_clutter_val_ci95"] is not None and "95% interval" in h["reasons"][0]
    assert card("big_vlm")["status_figures"]["ratio_to_lowest_ci95"] == [1.0, 1.0]                 # the lowest arm against itself
    assert "interval" in card("mem_vlm")["status_figures"]["peak_mem_note"] or "no interval" in card("mem_vlm")["status_figures"]["peak_mem_note"]
    idx = json.load(open(os.path.join(W["cards"], "status_index.json")))
    assert idx["arms"]["comp_vlm"]["deciding_figures_with_intervals"]["ratio_to_lowest_ci95"] is not None


@test
def t_line_arm_long_budget_row_and_extra_rows():
    a1 = card("A1")
    lb = a1["long_budget_row"]
    assert lb["row"] == "long budget" and lb["checkpoint"] == "long2x" and lb["status"] is not None and "different budget" in lb["note"]      # the final checkpoint: long2x
    assert "(long budget)" in lb["status_figures"]["checkpoint"] and lb["status_figures"]["v1_cer_ci95"] is not None
    rows = {r["checkpoint"]: r for r in a1["long_budget_rows"]}                                    # amendment 3.4 E5: a row per long checkpoint, each with its budget
    assert list(rows) == ["long", "long2x"] and rows["long2x"]["budget"] == "2 x P_long (3,168,768 samples)" and rows["long"]["budget"] == "samples reached: 1,584,384"
    assert rows["long2x"]["is_final_checkpoint"] is True and rows["long"]["is_final_checkpoint"] is False
    assert a1["long_budget_row"]["budget"] == rows["long2x"]["budget"]
    assert "long2x" in a1["long_budget_row"]["context_best_checkpoint_by_arm"]["A1"]
    # clarification J1: two checkpoints per line arm. The row of the section-3 checkpoint (P_long) and the row of the section-4 checkpoint (the furthest) are marked
    assert [(r["checkpoint"], r["is_section3_checkpoint"], r["is_section4_checkpoint"]) for r in a1["long_budget_rows"]] == [("long", True, False), ("long2x", False, True)]
    out2 = os.path.join(W["root"], "cards_pinned")                                                 # arms_info pins final_checkpoint to long (section 3): the section-4 row stays long2x
    json.dump({"A1": {"final_checkpoint": "long"}}, open(os.path.join(W["root"], "arms_pin.json"), "w"))
    p2 = subprocess.run([sys.executable, "-I", CARDS, "--scores", W["out"], "--preds", W["preds"], "--out", out2, "--arms-info", os.path.join(W["root"], "arms_pin.json")],
                        capture_output=True, text=True)
    assert p2.returncode == 0, p2.stderr[-1500:]
    pin = json.load(open(os.path.join(out2, "A1.json")))
    assert pin["long_budget_row"]["checkpoint"] == "long2x" and [(r["is_section3_checkpoint"], r["is_section4_checkpoint"]) for r in pin["long_budget_rows"]] == [(True, False), (False, True)]
    assert pin["long_budget_row"]["context_best_checkpoint_by_arm"]["A1"] == "long2x"             # the context checkpoint of a line arm is its furthest, not the section-3 pin
    out3 = os.path.join(W["root"], "cards_pinned4")                                                # an explicit section4_checkpoint moves the section-4 row
    json.dump({"A1": {"final_checkpoint": "long", "section4_checkpoint": "long"}}, open(os.path.join(W["root"], "arms_pin4.json"), "w"))
    p3 = subprocess.run([sys.executable, "-I", CARDS, "--scores", W["out"], "--preds", W["preds"], "--out", out3, "--arms-info", os.path.join(W["root"], "arms_pin4.json")],
                        capture_output=True, text=True)
    assert p3.returncode == 0, p3.stderr[-1500:]
    pin4 = json.load(open(os.path.join(out3, "A1.json")))
    assert pin4["long_budget_row"]["checkpoint"] == "long" and [(r["is_section3_checkpoint"], r["is_section4_checkpoint"]) for r in pin4["long_budget_rows"]] == [(True, True), (False, False)]
    assert card("big_vlm")["long_budget_row"] is None                                              # only the line arms get the row
    kinds = {r["checkpoint"]: r["kind"] for r in a1["variant_rows"]}
    assert kinds == {"short_lm": "character LM as decoded", "short_lm_gated": "gated character LM (H9)"}
    rows = {r["checkpoint"]: r for r in a1["variant_rows"]}
    assert rows["short_lm"]["hr1_clutter"]["value"] == 1.0 and rows["short_lm_gated"]["hr1_clutter"]["value"] == 0.0     # the gate removes text on empty images
    kind_retry = {r["checkpoint"]: r["kind"] for r in card("big_vlm")["variant_rows"]}
    assert kind_retry == {"short_retry": "cap-retry decoding at temperature 0.3 (outputs that hit the token cap without an end token are re-decoded once; r5_posttrain_experiment.txt)"}
    assert "retry of the run" not in kind_retry["short_retry"] and "rerun" not in kind_retry["short_retry"].lower() and "retrained" not in kind_retry["short_retry"]
    m = json.load(open(os.path.join(W["cards"], "comparison_matrix.json")))
    assert m["variants"]["A1"]["short_lm"]["hr1_clutter"] == 1.0 and m["variants"]["A1"]["short_lm_gated"]["hr1_clutter"] == 0.0
    assert "short_retry" in m["variants"]["big_vlm"] and m["variants"]["big_vlm"]["short_retry"]["v1_cer_ci95"][0] is not None
    idx = json.load(open(os.path.join(W["cards"], "status_index.json")))
    assert idx["arms"]["A1"]["long_budget"]["checkpoint"] == "long2x" and idx["arms"]["A1"]["long_budget"]["budget"].startswith("2 x P_long")
    assert [r["checkpoint"] for r in idx["arms"]["A1"]["long_budget_rows"]] == ["long", "long2x"]


@test
def t_load_scores_drops_the_cluster_arrays_where_the_cards_do_not_need_them():
    """23 Nov: report_cards.py was OOM-killed at 16 GB on the 2.5 GB of score files. The per-cluster arrays are kept for V1, kohtd_val and synth_hand_val only."""
    from r5eval import cards
    by, _ = cards.load_scores(W["out"])
    sets = by[("A1", "short")]
    assert "cluster_sums" in sets["V1"]["profiles"]["plain"] and "cluster_ids" in sets["V1"]["profiles"]["plain"] and "cluster_sums" in sets["synth_hand_val"]["profiles"]["plain"]
    for name in ("synth_clutter_val", "synth_typed_val", "curve_v1"):
        assert name in sets and all("cluster_sums" not in p_ and "cluster_ids" not in p_ for p_ in sets[name]["profiles"].values() if isinstance(p_, dict)), name
        assert "groups" in sets[name]["profiles"]["plain"] and sets[name]["coverage"]["complete"] is True                 # everything else is untouched
    assert cards.gaps(sets)["unseen_font"]["all_scripts"] is not None                                                          # the gaps still work


@test
def t_h16_notes_synthetic_versus_real():
    c = card("big_vlm")
    ids = [n["id"] for n in c["reading_notes"]]
    assert ids == ["H16.a", "H16.b", "H16.c"]
    b = c["reading_notes"][1]
    assert "KOHTD handwriting (Kazakh)" in b["figures"]["real_over_synthetic"] and "not a proxy for real handwriting" in b["text"]
    assert "442 real lines" in c["reading_notes"][0]["text"] and "uninformative" in c["reading_notes"][2]["text"]
    assert "uninformative" in c["gaps"]["unseen_font"]["reading_H16"] and c["gaps"]["unseen_font"]["held_out_no_worse_than_seen"] is False
    assert "synthetic handwriting" in c["per_language"]["synth_hand_val"]["what_is_measured"]


@test
def t_reference_arm_is_not_labelled_not_ranked_and_never_the_lowest():
    add_arm("R1", "short", 10)                     # far lower V1 CER than every arm: must not shift any label
    cmd = [sys.executable, "-I", SCORE, "--registry", os.path.join(W["root"], "evalsets.json"), "--preds", W["preds"], "--out", W["out"], "--B", "200",
           "--settle", "0", "--workers", "2", "--ktrain", os.path.join(W["root"], "no_ktrain.json")]
    assert subprocess.run(cmd, capture_output=True, text=True).returncode == 0
    out = os.path.join(W["root"], "cards_ref")
    cmd = [sys.executable, "-I", CARDS, "--scores", W["out"], "--preds", W["preds"], "--out", out, "--arms-info", os.path.join(W["root"], "arms_info.json")]
    p = subprocess.run(cmd, capture_output=True, text=True)
    assert p.returncode == 0, p.stderr[-1500:]
    c = json.load(open(os.path.join(out, "R1.json")))
    assert c["status"] is None and any(f["flag"] == "reference arm" for f in c["flags"])
    big = json.load(open(os.path.join(out, "big_vlm.json")))
    assert big["status"] == "PROMISING" and big["status_figures"]["ratio_to_lowest"] == 1.0           # the lowest is still big_vlm, not R1
    m = json.load(open(os.path.join(out, "comparison_matrix.json")))
    assert m["arms"]["R1"]["v1_cer"]["rank"] is None and m["arms"]["R1"]["v1_cer"]["value"] is not None and m["arms"]["big_vlm"]["v1_cer"]["rank"] == 1
    assert m["reference_arms_not_ranked"] == ["R1"]


if __name__ == "__main__":
    bad = [r for r in RESULTS if not r[1]]
    print("tests: %d passed, %d failed" % (len(RESULTS) - len(bad), len(bad)))
    sys.exit(1 if bad else 0)