File size: 39,821 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
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
"""Choice of the leaders (amendment 3.4 E2) and of B1 and B2 (amendment 3.2 C6 as amended by 3.4 E4, rule 0.9), from VALIDATION scores only.

LEADERS (leaders(), script select_leaders.py), read at the P_short checkpoint 'short' (plain greedy V1 CER, strict order, the arm name breaks an exact tie):
(a) the two arms with the lowest V1 CER; (b) the arm with the lowest V1 CER among the arms whose size class contains neither leader; (c) the next lowest
arm not yet chosen, in any class. Only arms that reached the full P_short of 150,000 samples are eligible (an arms_info flag or a meta train_flag that
says 'short of P', or samples_seen below 150,000, excludes an arm). The leaders get two seeds, the extra arms (b) and (c) one.

B1 = the VLM arm with the lowest V1 CER (plain greedy figure) among the FINAL checkpoints at leader length; arms left at P_short can not become B1.
A tie within 5% (relative) of the lowest is broken in favour of the arm with the most word crops per second (batch 16, one H100, from meta.json); the
pool of the tie is every leader-length arm whose CER is at most 1.05 x the lowest. B2 = the same rule over the leader-length arms whose size class
differs from B1's; only when no arm of another size class reached leader length may an arm left at P_short be B2 (then flagged 'different budget').
An arm with two seeds enters with the mean of its two seeds. Size classes (rule 0.9): small below 0.5B unique parameters, middle 0.5B to 1.5B,
large above 1.5B. No test figure enters. The result is written to selection.json and must be frozen (hashed) before the scoring pass; verdict.py only
reads that file. Line arms (clarification J1): section 3 reads 'long' (arms_info final_checkpoint), section 4 and the H10 block read section4_checkpoint (auto: long2x if it has a
complete V1 score, else the arm's section-3 checkpoint). The six reference roles R1, R2, R1_rand, R2_rand, R1_iii, R2_iii (REFERENCE_ROLES: folders R1/ours, R2/ours, R1/rand, R2/rand,
R1/mix, R2/mix) are written by select() too, because verdict.py reads them from selection.json (AUDIT check 8, gap G2).
"""
import json
import os
import re

import numpy as np

from . import ioutil, metautil, stats
from .summary import total_samples

LINE_ARMS = ("A1", "A2", "A3", "A4", "A1s")
V1_STEMS = ("V1", "kohtd_screen_v1")
P_SHORT = 150000                 # samples of the P_short checkpoint (amendment 3.2 C1)
P_LONG_FROM_E5 = 1584384         # 3,168,768 / 2 (amendment 3.4 E5); used only when the 'long' checkpoint's meta.json has no samples_seen
LINE_FINAL_ORDER = ("long2x", "long")
EQUAL_BUDGET_TOLERANCE = 0.01    # the six final checkpoints end at the same P_lead (amendment 3.4 E3): a spread above 1% is flagged


def size_class(params_b):
    if params_b is None:
        return None
    return "small" if params_b < 0.5 else ("middle" if params_b <= 1.5 else "large")


def ignored_name(name):
    """Directories that are never scored or ranked (the rule of the scorer): a leading underscore, or smoke, tmp or scratch in the name."""
    n = name.lower()
    return name.startswith("_") or "smoke" in n or "tmp" in n or "scratch" in n


def clean_arms_info(raw):
    """arms_info.json without its comment keys (a key that starts with an underscore, or a value that is not an object)."""
    return {k: v for k, v in (raw or {}).items() if not str(k).startswith("_") and isinstance(v, dict)}


def fill_params(info, params):
    """Unique parameter counts (billions) from the models tables unless arms_info gives them."""
    for arm, p in params.items():
        info.setdefault(arm, {})
        if info[arm].get("unique_params_b") is None:
            info[arm]["unique_params_b"] = p
    return info


def read_params(paths):
    """unique parameters (billions) from one or more models tables (a comma-separated list; the first table that names an arm wins)."""
    from . import cards
    out = {}
    for p in [x for x in (paths or "").split(",") if x]:
        for arm, v in cards.read_models_tsv(p).items():
            out.setdefault(arm, v)
    return out


def meta_for(doc, preds_dir, arm, ck):
    """(total samples, meta) of a checkpoint: the meta.json named in its score file, else the one beside its predictions. The samples are counted from the start of training
    (summary.total_samples: samples_total when it exists)."""
    paths = []
    mp = ((doc or {}).get("inputs") or {}).get("meta_path")
    if mp:
        paths.append(mp)
    if preds_dir:
        paths.append(os.path.join(preds_dir, arm, ck, "meta.json"))
    for p in paths:
        if p and os.path.exists(p):
            try:
                m = json.load(open(p, encoding="utf-8"))
            except ValueError:
                continue
            return total_samples(m), m          # samples counted from the start (a leader checkpoint: samples_total = P_lead, not the samples of its call only)
    return None, {}


def seed2_base(name, present):
    """The base arm if `name` is a seed-2 ARM FOLDER (convention 2 and 3 below), else None. Only when the base arm folder exists, so an arm
    whose own name happens to end in _s2 is not folded away."""
    if name.endswith("_s2") and len(name) > 3 and name[:-3] in present:
        return name[:-3]
    return None


def seed2_folders(*dirs):
    """Seed-2 arm folders found in the given scores or predictions folders: {folder name: base arm}."""
    present = set()
    for d in dirs:
        if d and os.path.isdir(d):
            present |= {n for n in os.listdir(d) if os.path.isdir(os.path.join(d, n)) and not ignored_name(n)}
    return {n: seed2_base(n, present) for n in sorted(present) if seed2_base(n, present)}


def find_seed2(scores_dir, arm, ck):
    """(arm2, checkpoint2) of the second seed of the checkpoint `ck` of `arm`, else None. Seed-2 runs arrive under three naming conventions and all mean seed 2 of the same arm:
      1. VLMA arms:                         preds/<arm>/<ckpt>_seed2        (short_seed2, leader_seed2, long_seed2)
      2. maker-code VLM arms (VLMB, VLMC) run by the leader runner, and
      3. line arms from LINEDET:            preds/<arm>_s2/<ckpt>           (preds/<short>_s2/leader, preds/A1_s2/long)
    A checkpoint folder <ckpt>_s2 inside the arm folder is accepted as well. The first form whose score folder exists wins."""
    for a2, c2 in ((arm, ck + "_seed2"), (arm + "_s2", ck), (arm, ck + "_s2")):
        if os.path.isdir(os.path.join(scores_dir, a2, c2)):
            return a2, c2
    return None


def short_of_p_reason(info, meta, samples):
    """Why an arm did not reach the full P_short of 150,000 samples, else None: a flag text 'short of P' in arms_info flags or in meta train_flag, or
    samples_seen below 150,000."""
    for t in list((info or {}).get("flags") or []) + [(meta or {}).get("train_flag")]:
        if isinstance(t, str) and "short of p" in t.lower():
            return t
    if samples is not None and samples < P_SHORT:
        return "samples_seen %d is below the full P_short of %d" % (samples, P_SHORT)
    return None


def _load(p):
    return json.load(open(p, encoding="utf-8"))


def _speed(meta_path):
    if meta_path and os.path.exists(meta_path):
        m = _load(meta_path)
        return metautil.speed(m)["images_per_second"], m
    return None, {}


REF_ARM_RE = re.compile(r"^R[12]($|[_a-zA-Z0-9])")


def is_vlm_arm(arm, arms_info, vlm_allow):
    """B1 and B2 are chosen among VLM arms only. With an allow-list (models_r5.tsv plus VLMB's arms plus arms_info entries marked role vlm)
    only those arms count. Without one: not a line arm, not a reference arm (amendment 3.3 D5: R1 and R2 can never be B1 or B2), and not
    marked role reference or line in arms_info."""
    role = (arms_info.get(arm) or {}).get("role")
    if role in ("reference", "line"):
        return False
    if role == "vlm":
        return True
    if arm in LINE_ARMS or REF_ARM_RE.match(arm):
        return False
    return (arm in vlm_allow) if vlm_allow else True


def vlm_table(scores_dir, arms_info, final_order=("final", "leader", "long", "short"), vlm_allow=None, preds_dir=None):
    rows = []
    folded = seed2_folders(scores_dir)
    for arm in sorted(os.listdir(scores_dir)):
        ap = os.path.join(scores_dir, arm)
        if not os.path.isdir(ap) or arm.startswith("_"):
            continue
        if arm in folded:
            continue                       # a seed-2 arm folder (<arm>_s2) is the second seed of its base arm, not an arm of its own
        if not is_vlm_arm(arm, arms_info, vlm_allow):
            role = (arms_info.get(arm) or {}).get("role")
            if arm in LINE_ARMS or REF_ARM_RE.match(arm) or role in ("reference", "line"):
                continue                   # line and reference arms are not VLM candidates: not listed
            rows.append({"arm": arm, "checkpoint": None, "unique_params_b": None, "size_class": None, "flags": [], "included": False, "vlm_candidate": False, "v1_cer": None,
                         "images_per_second": None, "reason": "not in the VLM allow-list (models_r5.tsv, --vlm-arms, arms_info role vlm): not a candidate for B1 or B2"})
            continue
        info = arms_info.get(arm, {})
        cks = [c for c in sorted(os.listdir(ap)) if os.path.isdir(os.path.join(ap, c)) and not c.endswith(("_lm", "_pp"))]
        ck = info.get("final_checkpoint")
        if ck is None:
            ck = next((c for c in final_order if c in cks), None)
        row = {"arm": arm, "checkpoint": ck, "unique_params_b": info.get("unique_params_b"), "size_class": size_class(info.get("unique_params_b")),
               "flags": info.get("flags", []), "included": False, "reason": None, "v1_cer": None, "images_per_second": None}
        if ck is None:
            row["reason"] = "no checkpoint with scores"
            rows.append(row)
            continue
        sc = ioutil.find_score(os.path.join(ap, ck), list(V1_STEMS))
        p = ((sc or {}).get("inputs") or {}).get("pred_path")
        if sc is None or sc.get("status") != "scored":
            row["reason"] = "no V1 score file"
        elif sc.get("locked"):
            row["reason"] = "V1 score file marked locked (refused)"
        elif not sc["coverage"]["complete"]:
            row["reason"] = "V1 predictions incomplete (%d of %d crops)" % (sc["coverage"]["scored_rows"], sc["coverage"]["manifest_rows"])
        else:
            m = sc["profiles"]["plain"]["groups"]["all"]["metrics"]["cer"]
            row["v1_cer"] = m["num"] / m["den"]
            row["v1_cer_ci95"] = [m.get("lo"), m.get("hi")]
            row["included"] = True
            row["v1_score_file"] = p
            row["_docs"] = [sc]
            row["seeds"] = 1
            samples, _m = meta_for(sc, preds_dir, arm, ck)
            row["samples_seen"] = samples
            # amendment 3.4 E4: only a final checkpoint at leader length (more samples than P_short) can be B1; one that stayed at P_short keeps its short figure
            row["at_leader_length"] = (ck != "short") and (samples is None or samples > P_SHORT * 1.01)
            if ck != "short" and samples is None:
                row["flags"] = list(row["flags"]) + ["samples_seen missing in meta.json: leader length assumed from the checkpoint name"]
            # amendment 3.3 D2: for a leader with two seeds, 'its V1 CER' is the mean over its two seeds
            # the second seed is found under any of the three naming conventions (find_seed2); arms_info may name it explicitly (seed2_checkpoint, seed2_arm)
            s2 = (info.get("seed2_arm") or arm, info["seed2_checkpoint"]) if info.get("seed2_checkpoint") else find_seed2(scores_dir, arm, ck)
            sc2 = ioutil.find_score(os.path.join(scores_dir, s2[0], s2[1]), list(V1_STEMS)) if s2 else None
            if sc2 is not None:
                if not sc2.get("locked") and sc2["coverage"]["complete"]:
                    m2 = sc2["profiles"]["plain"]["groups"]["all"]["metrics"]["cer"]
                    row["v1_cer_seeds"] = [row["v1_cer"], m2["num"] / m2["den"]]
                    row["v1_cer"] = sum(row["v1_cer_seeds"]) / 2.0
                    row["seed2_checkpoint"] = s2[1]
                    if s2[0] != arm:
                        row["seed2_arm"] = s2[0]
                    row["seeds"] = 2
                    row["_docs"].append(sc2)
                else:
                    row["flags"] = list(row["flags"]) + ["seed 2 present but incomplete: seed 1 alone used"]
            sp, meta = _speed((sc.get("inputs") or {}).get("meta_path"))
            row["images_per_second"] = sp
            fl = meta.get("train_flag")
            if fl:
                row["flags"] = list(row["flags"]) + [fl]
        rows.append(row)
    return rows


def pick(rows, tie=0.05):
    inc = [r for r in rows if r["included"]]
    if not inc:
        return None, None
    best = min(inc, key=lambda r: (r["v1_cer"], r["arm"]))
    pool = [r for r in inc if r["v1_cer"] <= (1.0 + tie) * best["v1_cer"] + 1e-15]
    with_speed = [r for r in pool if r["images_per_second"] is not None]
    if len(pool) > 1 and len(with_speed) == len(pool):
        chosen = max(pool, key=lambda r: (r["images_per_second"], -r["v1_cer"], r["arm"]))
        why = "tie within 5%% of the lowest CER among %d arms, broken by images per second" % len(pool)
    elif len(pool) > 1:
        chosen = best
        why = "tie within 5%% among %d arms but speed missing for some: lowest CER kept (flag)" % len(pool)
    else:
        chosen = best
        why = "lowest V1 CER, no tie"
    return chosen, why


def _arrays(doc):
    p = doc["profiles"]["plain"]
    cs = p["cluster_sums"]["all"]
    return p["cluster_ids"], np.asarray(cs["dist"], dtype=float), np.asarray(cs["ref_len"], dtype=float)


def pairwise_top(rows, k=6, B=stats.B_DEFAULT):
    """Paired form-bootstrap intervals of the V1 CER difference for every pair among the k VLM arms with the lowest V1 CER (clarification H14).
    The same form resamples are applied to both arms; an arm with two seeds enters with the mean of its two seeds. d = CER of the arm with the
    lower V1 CER minus CER of the other, so a negative difference whose interval lies below zero means the first arm is better. Descriptive, unadjusted."""
    inc = sorted([r for r in rows if r["included"] and r.get("_docs")], key=lambda r: (r["v1_cer"], r["arm"]))[:k]
    pairs = []
    for i in range(len(inc)):
        for j in range(i + 1, len(inc)):
            x, y = inc[i], inc[j]
            ax = [_arrays(d) for d in x["_docs"]]
            ay = [_arrays(d) for d in y["_docs"]]
            ids = sorted(set().union(*[set(a[0]) for a in ax + ay]))

            def put(a):
                pos = {c: n for n, c in enumerate(a[0])}
                num, den = np.zeros(len(ids)), np.zeros(len(ids))
                for n, c in enumerate(ids):
                    m = pos.get(c)
                    if m is not None:
                        num[n], den[n] = a[1][m], a[2][m]
                return num, den
            px, py = [put(a) for a in ax], [put(a) for a in ay]
            if not all(np.array_equal(px[0][1], d[1]) for d in px + py):
                pairs.append({"first": x["arm"], "second": y["arm"], "note": "reference lengths differ between the two V1 score files: not compared"})
                continue
            r = stats.paired_seed_mean_difference([a[0] for a in px], [a[1] for a in px], [a[0] for a in py], [a[1] for a in py], B=B)
            ci = r.get("d_abs_ci95")
            pairs.append({"first": x["arm"], "second": y["arm"], "cer_first": r["cer_x"], "cer_second": r["cer_y"], "d_abs": r["d_abs"], "d_abs_ci95": ci,
                          "d_rel": r["d_rel"], "d_rel_ci95": r.get("d_rel_ci95"), "p_first_better": r.get("p_better"),
                          "interval_below_zero_first_is_better": bool(ci and ci[1] < 0), "interval_above_zero_second_is_better": bool(ci and ci[0] > 0),
                          "seeds": [len(px), len(py)]})
    return {"arms_in_order_of_V1_CER": [r["arm"] for r in inc], "pairs": pairs, "B": B, "label": "descriptive; paired form bootstrap, 95%% percentile intervals, not adjusted for the "
            "%d pairs; the pick of B1 and B2 follows the rule of amendment 3.2 C6, not these intervals" % len(pairs)}


def _v1_state(ck_dir):
    """(score document, reason): the complete V1 score of a checkpoint folder, or why there is none."""
    sc = ioutil.find_score(ck_dir, list(V1_STEMS))
    if sc is None:
        return None, "no V1 score file"
    if sc.get("locked"):
        return None, "V1 score file marked locked (refused)"
    if not sc["coverage"]["complete"]:
        return None, "V1 predictions incomplete (%d of %d crops)" % (sc["coverage"]["scored_rows"], sc["coverage"]["manifest_rows"])
    return sc, None


def short_table(scores_dir, preds_dir, arms_info, vlm_allow=None, ck="short"):
    """One row per VLM arm that has a P_short checkpoint (scores or predictions): V1 CER with its interval, size class, samples reached, eligibility.
    Returns (rows, outside_allow_list). Line arms and reference arms are not VLM arms and are not listed."""
    names = set()
    for d in (scores_dir, preds_dir):
        if d and os.path.isdir(d):
            names |= {n for n in os.listdir(d) if os.path.isdir(os.path.join(d, n)) and not ignored_name(n)}
    folded = seed2_folders(scores_dir, preds_dir)
    rows, outside = [], []
    for arm in sorted(names):
        if arm in folded:
            continue                                   # <arm>_s2 = the second seed of its base arm (see find_seed2), not an arm of its own
        role = (arms_info.get(arm) or {}).get("role")
        if arm in LINE_ARMS or REF_ARM_RE.match(arm) or role in ("reference", "line"):
            continue
        sdir = os.path.join(scores_dir, arm, ck) if scores_dir else ""
        pdir = os.path.join(preds_dir, arm, ck) if preds_dir else ""
        if not (os.path.isdir(sdir) or os.path.isdir(pdir)):
            continue                                   # no P_short checkpoint at all (for example an arm that only has curve folders)
        if not is_vlm_arm(arm, arms_info, vlm_allow):
            outside.append({"arm": arm, "reason": "has a '%s' checkpoint but is not in the VLM allow-list (models tables, --vlm-arms, arms_info role vlm): not a candidate" % ck,
                            "scored": os.path.isdir(sdir), "predictions": os.path.isdir(pdir)})
            continue
        info = arms_info.get(arm) or {}
        sc, why = _v1_state(sdir)
        samples, meta = meta_for(sc, preds_dir, arm, ck)
        row = {"arm": arm, "checkpoint": ck, "unique_params_b": info.get("unique_params_b"), "size_class": size_class(info.get("unique_params_b")),
               "samples_seen": samples, "train_flag": meta.get("train_flag"), "flags": [f for f in (info.get("flags") or []) if isinstance(f, str)],
               "predictions_present": os.path.isdir(pdir), "scored": sc is not None, "v1_cer": None, "v1_cer_ci95": None, "eligible": False, "reasons": []}
        if sc is None:
            row["reasons"].append("no complete V1 score at '%s': %s%s" % (ck, why, "; predictions exist, so r5_score.sbatch has to run before the pick" if row["predictions_present"] else ""))
        else:
            m = sc["profiles"]["plain"]["groups"]["all"]["metrics"]["cer"]
            row["v1_cer"] = m["num"] / m["den"]
            row["v1_cer_ci95"] = [m.get("lo"), m.get("hi")]
            row["_doc"] = sc
            rt, _ = _v1_state(os.path.join(scores_dir, arm, ck + "_retry"))
            if rt is not None:
                mr = rt["profiles"]["plain"]["groups"]["all"]["metrics"]["cer"]
                row["v1_cer_short_retry"] = mr["num"] / mr["den"]
        sp = short_of_p_reason(info, meta, samples)
        if sp:
            row["reasons"].append(sp if sp.lower().startswith("short of p") else "short of P: %s" % sp)
        if sc is not None and not sp:
            row["eligible"] = True
            if samples is None:
                row["reasons"].append("samples_seen not found in meta.json: eligibility rests on the absence of a 'short of P' flag")
        rows.append(row)
    return rows, outside


def _brief(r, role=None):
    if r is None:
        return None
    d = {k: r.get(k) for k in ("arm", "v1_cer", "v1_cer_ci95", "size_class", "unique_params_b", "samples_seen", "v1_cer_short_retry")}
    if role:
        d["role"] = role
        d["seeds"] = 2 if role == "leader" else 1
    return d


def leaders(scores_dir, preds_dir, arms_info, vlm_allow=None, ck="short", B=stats.B_DEFAULT):
    """Amendment 3.4 E2: the two leaders, the extra arm (b) and the extra arm (c) from the V1 CER at P_short. See the module docstring."""
    rows, outside = short_table(scores_dir, preds_dir, arms_info, vlm_allow, ck)
    warnings = []
    elig = sorted([r for r in rows if r["eligible"]], key=lambda r: (r["v1_cer"], r["arm"]))
    a = elig[:2]
    a_names = {r["arm"] for r in a}
    rest = [r for r in elig if r["arm"] not in a_names]
    lead_classes = {r["size_class"] for r in a}
    if None in lead_classes:
        warnings.append("a leader has no unique parameter count: its size class is unknown, so extra arm (b) may lie in its class (give unique_params_b in arms_info.json or the models tables)")
    b_pool = [r for r in rest if r["size_class"] is not None and r["size_class"] not in lead_classes]
    b = b_pool[0] if b_pool else None
    c_pool = [r for r in rest if b is None or r["arm"] != b["arm"]]
    c = c_pool[0] if c_pool else None
    if len(a) < 2:
        warnings.append("fewer than two eligible arms: %d leader(s) found" % len(a))
    if b is None:
        warnings.append("extra arm (b): no eligible arm in a size class that contains neither leader (classes of the leaders: %s)" % sorted(str(x) for x in lead_classes))
    if c is None:
        warnings.append("extra arm (c): no further eligible arm")
    # what the leaders would be if the eligibility filter were not applied (information only, not a choice)
    scored = sorted([r for r in rows if r["scored"]], key=lambda r: (r["v1_cer"], r["arm"]))
    unfiltered = [r["arm"] for r in scored[:2]]
    chosen = ([_brief(r, "leader") for r in a] + ([_brief(b, "extra_b")] if b else []) + ([_brief(c, "extra_c")] if c else []))
    top = elig[0]["v1_cer"] if elig else None
    within5 = [{"arm": r["arm"], "ratio_to_lowest": r["v1_cer"] / top} for r in elig if top and r["v1_cer"] <= 1.05 * top + 1e-15]
    pw_rows = [{"arm": r["arm"], "included": True, "v1_cer": r["v1_cer"], "_docs": [r["_doc"]]} for r in elig]
    pw = pairwise_top(pw_rows, k=6, B=B)
    ineligible = [{"arm": r["arm"], "reasons": r["reasons"], "v1_cer": r["v1_cer"], "v1_cer_ci95": r["v1_cer_ci95"], "samples_seen": r["samples_seen"],
                   "size_class": r["size_class"]} for r in rows if not r["eligible"]]
    expected = sorted(set(vlm_allow or ()) - {r["arm"] for r in rows})
    for r in rows:
        r.pop("_doc", None)
    not_scored = [r["arm"] for r in rows if not r["scored"]]
    if not_scored or expected:
        warnings.append("arms not scored or not finished at this pick: %s (clarification H14: the pick is a recorded deviation if it is made before they could finish)"
                        % ", ".join(not_scored + expected))
    if outside:
        warnings.append("arms with a '%s' checkpoint that are not in the VLM allow-list and were NOT considered: %s" % (ck, ", ".join(o["arm"] for o in outside)))
    return {"schema": "r5eval-leaders-selection-1", "rule": __doc__.strip().split("\n")[0:6], "checkpoint": ck, "metric": "V1 CER, plain greedy figure, form bootstrap 95% interval",
            "leaders": [_brief(r, "leader") for r in a], "extra_b": _brief(b, "extra_b"), "extra_c": _brief(c, "extra_c"),
            "runs_to_leader_length": chosen, "n_runs": sum(2 if x["role"] == "leader" else 1 for x in chosen),
            "leaders_if_the_eligibility_filter_were_not_applied": unfiltered,
            "eligibility_filter_changes_the_leaders": unfiltered != [r["arm"] for r in a],
            "within_5_percent_of_the_lowest_eligible": within5,
            "tie_note": "the order is strict (amendment 3.3 D2, 3.4 E2); the 5% speed tie-break of 3.2 C6 belongs to B1 and B2 and is not used here",
            "pairwise_top6_v1": pw, "table": sorted(rows, key=lambda r: (r["v1_cer"] is None, r["v1_cer"] if r["v1_cer"] is not None else 0, r["arm"])),
            "not_eligible": ineligible, "outside_allow_list": outside, "not_started_or_not_finished": expected, "warnings": warnings}


# The six reference roles of amendment 3.3 D5 and clarifications H5 and H12 (records/R5/RULE): role, arm folder, checkpoint folder, variant. The folders are the ones REF writes
# (DATA/outputs/r5/preds/R1/{ours,rand,mix}, R2/{ours,rand,mix}; REF's test_pass_commands.sh): (i) trained on our form split ('ours'), (ii) on the random replication split ('rand',
# scored on kohtd_rand_test), (iii) on mix_v1 to 150,016 samples ('mix'). The folders R1/<variant>_paperdec (beam search of HTR-Flor's own decoder) and the mix_curve_<n> folders are
# descriptive and no role: the rule scores the greedy decoding (rule 0.3) and reads the paper's own metric from the same predictions (scoreset N4).
REFERENCE_ROLES = (("R1", "R1", "ours", "i"), ("R2", "R2", "ours", "i"), ("R1_rand", "R1", "rand", "ii"), ("R2_rand", "R2", "rand", "ii"),
                   ("R1_iii", "R1", "mix", "iii"), ("R2_iii", "R2", "mix", "iii"))


def reference_roles(scores_dir, preds_dir, table=REFERENCE_ROLES):
    """(roles, warnings): the reference roles of amendment 3.3 D5 for selection.json, so that verdict.py can read the published-method comparison (D5, H11, H12) and the same-data
    comparison (H5, H13). A role is written when its checkpoint folder exists under the scores or the predictions; a missing one is listed in the warnings, never invented.
    unique_params_b comes from the checkpoint's meta.json: the parameters used at test time (R2: parameters_ctc_branch_used_at_test_time, the SAR head is a training aid), else parameters."""
    roles, warns = {}, []
    for role, arm, ck, variant in table:
        sdir = os.path.join(scores_dir, arm, ck) if scores_dir else ""
        pdir = os.path.join(preds_dir, arm, ck) if preds_dir else ""
        if not (os.path.isdir(sdir) or os.path.isdir(pdir)):
            warns.append("reference role %s not written: no folder %s/%s under the scores or the predictions (D5; verdict blocks that need it are not evaluable)" % (role, arm, ck))
            continue
        doc = ioutil.find_score(sdir, list(V1_STEMS)) if os.path.isdir(sdir) else None
        samples, meta = meta_for(doc, preds_dir, arm, ck)
        p = next((meta[k] for k in ("parameters_ctc_branch_used_at_test_time", "parameters") if isinstance(meta.get(k), (int, float)) and not isinstance(meta.get(k), bool)), None)
        roles[role] = {"arm": arm, "checkpoint": ck, "reference_variant": variant, "unique_params_b": (p / 1e9) if p is not None else None, "samples_seen": samples,
                       "unique_params_basis": "meta.json parameters used at test time" if p is not None else None}
    return roles, warns


def line_final(scores_dir, preds_dir, arm, arms_info, line_checkpoint="auto"):
    """Checkpoint of a line arm for SECTION 3 of version 3 (clarification J1): the P_long checkpoint 'long' (equal samples, two seeds for A1 and A2). --line-checkpoint
    overrides it when it is not 'auto'; else arms_info final_checkpoint; else 'long'. Returns (checkpoint, basis, warnings). A section-3 checkpoint of 'long2x' is
    warned about: J1 fixes section 3 at P_long, and A1 and A2 end at different sample counts at long2x."""
    info = arms_info.get(arm) or {}
    warns = []
    if line_checkpoint not in (None, "auto"):
        ck, basis = line_checkpoint, "--line-checkpoint"
    elif info.get("final_checkpoint"):
        ck, basis = info["final_checkpoint"], "arms_info final_checkpoint"
    else:
        ck, basis = "long", "default: the P_long checkpoint (clarification J1)"
    if ck == "long2x":
        warns.append("%s: section 3 is set to read 'long2x', but clarification J1 reads section 3 at the P_long checkpoint 'long' (equal samples); use section4_checkpoint for long2x" % arm)
    return ck, basis, warns


def line_section4(scores_dir, preds_dir, arm, arms_info, section4_checkpoint="auto", fallback="long"):
    """Checkpoint of a line arm for SECTION 4 and the H10 block (clarification J1): the furthest one, long2x if it has a complete V1 score, else the arm's section-3
    checkpoint (`fallback`: 'long', or for an arm pinned elsewhere, for example A4 at 'short', that checkpoint; never a name that does not exist). The arms_info key
    section4_checkpoint ('auto' or a checkpoint name) overrides the argument. Returns (checkpoint, basis)."""
    info = arms_info.get(arm) or {}
    key = info.get("section4_checkpoint") or section4_checkpoint or "auto"
    if key != "auto":
        return key, "arms_info section4_checkpoint" if info.get("section4_checkpoint") else "--section4-checkpoint"
    if _v1_state(os.path.join(scores_dir, arm, "long2x"))[0] is not None:
        return "long2x", "auto: the furthest checkpoint, long2x, has a complete V1 score"
    return fallback, "auto: no long2x with a complete V1 score, so the section-3 checkpoint (%s)" % fallback


def budget_of(scores_dir, preds_dir, arm, ck, long_samples=None, samples=None):
    """{'samples_seen', 'label'}: '2 x P_long' when the samples are at least twice those of the 'long' checkpoint (amendment 3.4 E5; the amendment's own
    figure when the long meta.json has none), else 'samples reached: N'. samples: the samples when the caller already read them (for example from the meta.json
    named in a test score file); then the V1 score file is not looked up."""
    if samples is not None:
        s = samples
    else:
        sc = ioutil.find_score(os.path.join(scores_dir, arm, ck), list(V1_STEMS))
        s, _ = meta_for(sc, preds_dir, arm, ck)
    if long_samples is None and samples is None:
        sl = ioutil.find_score(os.path.join(scores_dir, arm, "long"), list(V1_STEMS))
        long_samples, _ = meta_for(sl, preds_dir, arm, "long")
    p_long = long_samples if long_samples else P_LONG_FROM_E5
    if s is None:
        return {"samples_seen": None, "label": "samples unknown (no samples_seen in meta.json)"}
    if ck != "long" and s >= 2 * p_long:
        return {"samples_seen": s, "label": "2 x P_long (%s samples)" % format(int(s), ",")}
    return {"samples_seen": s, "label": "samples reached: %s" % format(int(s), ",")}


def select(scores_dir, arms_info, line_checkpoint="auto", line_arms=LINE_ARMS, final_order=("final", "leader", "long", "short"), vlm_allow=None, preds_dir=None,
           strict_final=True, section4_checkpoint="auto"):
    """B1, B2 and the line-arm roles. strict_final=True is the rule of amendment 3.4 E4 (B1 only among final checkpoints at leader length); False is a
    provisional dry run that also lets arms at P_short compete, marked 'provisional' in the output."""
    rows = vlm_table(scores_dir, arms_info, final_order, vlm_allow, preds_dir)
    inc = [r for r in rows if r["included"]]
    lead = [r for r in inc if r.get("at_leader_length")]
    pool1 = lead if strict_final else inc
    b1, why1 = pick(pool1)
    pw = pairwise_top(pool1)
    for r in rows:
        r.pop("_docs", None)
    not_ranked = [{"arm": r["arm"], "reason": r["reason"]} for r in rows if not r["included"]]
    sset = [r["samples_seen"] for r in lead if r.get("samples_seen")]
    equal = (not sset) or (max(sset) - min(sset) <= EQUAL_BUDGET_TOLERANCE * max(sset))
    out = {"schema": "r5eval-selection-2", "rule": __doc__.strip().split("\n")[0:3], "table": rows, "roles": {}, "B1": None, "B2": None,
           "provisional": (not strict_final), "B1_reason": why1, "B2_reason": None, "pairwise_top6_v1": pw,
           "final_checkpoint_budgets": {"arms_at_leader_length": [{"arm": r["arm"], "checkpoint": r["checkpoint"], "samples_seen": r.get("samples_seen"), "seeds": r.get("seeds")} for r in lead],
                                        "arms_left_at_P_short": [{"arm": r["arm"], "checkpoint": r["checkpoint"], "samples_seen": r.get("samples_seen")} for r in inc if not r.get("at_leader_length")],
                                        "equal_budget_E3": equal,
                                        "note": "amendment 3.4 E3: all runs at leader length end at the same P_lead; a spread of more than 1% in samples_seen is flagged here"},
           "arms_not_ranked_at_this_pick": not_ranked, "arms_not_ranked_note": "arms still running or without a complete V1 score at the pick are listed here (clarification H14); a pick made "
                                                                                 "before such an arm could finish is a deviation to be recorded",
           "decisions_needed": [], "warnings": []}
    if not equal:
        out["warnings"].append("the final checkpoints at leader length do not have equal samples_seen (%s): amendment 3.4 E3 says they end at the same P_lead" % sorted(set(sset)))
    if not strict_final:
        out["warnings"].append("PROVISIONAL: arms at P_short were allowed to compete; the rule of amendment 3.4 E4 allows only final checkpoints at leader length for B1")
    elif not lead:
        out["B1_reason"] = "no VLM arm has a final checkpoint at leader length yet (amendment 3.4 E4: an arm left at P_short can not become B1)"

    def role(r, extra=None):
        d = {"arm": r["arm"], "checkpoint": r["checkpoint"], "unique_params_b": r["unique_params_b"], "samples_seen": r.get("samples_seen"), "seeds": r.get("seeds"),
             "at_leader_length": bool(r.get("at_leader_length"))}
        if r.get("seed2_checkpoint"):
            d["seed2_checkpoint"] = r["seed2_checkpoint"]
            if r.get("seed2_arm"):
                d["seed2_arm"] = r["seed2_arm"]                 # convention 2 and 3: the second seed is the arm folder <arm>_s2
        if r.get("seeds") == 1:
            d["single_seed_note"] = "single seed: form bootstrap only (clarification G1); clause 4b is not evaluable with one seed"
        d.update(extra or {})
        return d
    if b1:
        out["B1"] = b1["arm"]
        out["roles"]["B1"] = role(b1)
        if b1["size_class"] is None:
            out["B2_reason"] = "B2 not evaluable: the unique parameter count of B1 is unknown (arms_info.json)"
        else:
            other = [r for r in inc if r["size_class"] is not None and r["size_class"] != b1["size_class"]]
            others_lead = [r for r in other if r.get("at_leader_length")]
            if strict_final and not others_lead and other:
                b2, why2 = pick(other)                      # amendment 3.4 E4: only when no arm of another size class reached leader length
                if b2:
                    why2 = "no arm of another size class reached leader length: chosen among arms left at P_short (%s)" % why2
                    out["warnings"].append("B2 %s is at P_short and B1 at leader length: DIFFERENT BUDGETS (amendment 3.4 E4)" % b2["arm"])
            else:
                b2, why2 = pick(others_lead if strict_final else other)
            if b2:
                out["B2"] = b2["arm"]
                out["roles"]["B2"] = role(b2)
                out["B2_reason"] = why2
            else:
                out["B2_reason"] = "no included arm in a size class other than B1's (%s)" % b1["size_class"]
    for b in ("B1", "B2"):                # the P_short checkpoint of each is the equal-data, equal-samples point (amendment 3.2 C8, clarification H13)
        if b in out["roles"]:
            out["roles"][b]["short_checkpoint"] = "short"
            s2s = find_seed2(scores_dir, out["roles"][b]["arm"], "short")
            if s2s:
                out["roles"][b]["short_seed2_checkpoint"] = s2s[1]
                if s2s[0] != out["roles"][b]["arm"]:
                    out["roles"][b]["short_seed2_arm"] = s2s[0]
    long2x_single = []
    for a in line_arms:
        if os.path.isdir(os.path.join(scores_dir, a)):
            ck, basis, warns = line_final(scores_dir, preds_dir, a, arms_info, line_checkpoint)
            out["warnings"] += warns
            out["roles"][a] = {"arm": a, "checkpoint": ck, "checkpoint_basis": basis, "unique_params_b": None, "short_checkpoint": "short",
                               "budget": budget_of(scores_dir, preds_dir, a, ck)}
            s2s = find_seed2(scores_dir, a, "short")
            if s2s:
                out["roles"][a]["short_seed2_checkpoint"] = s2s[1]
                if s2s[0] != a:
                    out["roles"][a]["short_seed2_arm"] = s2s[0]
            s2 = find_seed2(scores_dir, a, ck)          # amendment 3.3 D3: A1 and A2 have a second seed: <ck>_seed2 in the arm, or the arm folder <arm>_s2 (LINEDET)
            if s2:
                out["roles"][a]["seed2_checkpoint"] = s2[1]
                if s2[0] != a:
                    out["roles"][a]["seed2_arm"] = s2[0]
            # clarification J1: section 3 (A2 against A1, A3, A4, A1s) is read at the P_long checkpoint above (equal samples, two seeds); the line-branch choice that results
            # enters section 4 and the H10 block at its FURTHEST checkpoint (long2x if it exists), at the samples it reached, with the second seed only if one exists at that checkpoint
            ck4, basis4 = line_section4(scores_dir, preds_dir, a, arms_info, section4_checkpoint, fallback=ck)
            out["roles"][a]["section3_checkpoint"] = ck
            out["roles"][a]["section4_checkpoint"] = ck4
            out["roles"][a]["section4_checkpoint_basis"] = basis4
            out["roles"][a]["section4_budget"] = budget_of(scores_dir, preds_dir, a, ck4)
            if ck4 != ck:
                s24 = find_seed2(scores_dir, a, ck4)
                if s24:
                    out["roles"][a]["section4_seed2_checkpoint"] = s24[1]
                    if s24[0] != a:
                        out["roles"][a]["section4_seed2_arm"] = s24[0]
                elif a in ("A1", "A2"):
                    s2long = find_seed2(scores_dir, a, ck)
                    out["roles"][a]["seed_note"] = ("section 4 reads '%s' (seed 1 only, single seed: G1, form bootstrap only; confirmed in J1); section 3 reads '%s' with %s; the second seed at '%s' "
                                                    "(%s/%s, another budget) is never paired with '%s'" % ((ck4, ck, "two seeds", ck) + s2long + (ck4,)) if s2long else
                                                    "section 4 reads '%s' (seed 1 only, single seed: G1); section 3 reads '%s'" % (ck4, ck))
                    long2x_single.append(a)
            else:
                out["roles"][a]["section4_seed2_checkpoint"] = out["roles"][a].get("seed2_checkpoint")
                if out["roles"][a].get("seed2_arm"):
                    out["roles"][a]["section4_seed2_arm"] = out["roles"][a]["seed2_arm"]
    refs, ref_warns = reference_roles(scores_dir, preds_dir)           # gap G2 of AUDIT check 8: verdict.py reads R1, R2, R1_rand, R2_rand, R1_iii, R2_iii from selection.json
    out["roles"].update(refs)
    out["reference_roles"] = sorted(refs)
    out["warnings"] += ref_warns
    if long2x_single:
        out["notes"] = ["Clarification J1: section 3 reads the P_long checkpoint of every line arm; the line-branch choice enters section 4 and the H10 block at its furthest checkpoint, "
                        "which for %s is a single-seed checkpoint (form bootstrap only, G1; the single-seed reading was confirmed). The P_long figure of the same arm "
                        "is reported beside it, and A2 against A1 at that checkpoint is descriptive only." % " and ".join(long2x_single)]
    return out