File size: 52,426 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
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
"""Extracts the figures that verdictlib.decide() needs from score JSONs (written by score.py) and the selection and endpoint files,
including the second seed of two-seed arms (amendment 3.3 D4), the reference arms R1 and R2 and the comparison with the published methods we re-ran (D5, H11, H12),
the second comparison with the gated character LM (H10), the same-data comparison at equal samples (H13) and the descriptive ranking of the VLM arms at P_short (H14).
Extra roles: R1_iii and R2_iii (reference arms trained on mix_v1, 150,000 samples); roles may carry short_checkpoint and short_seed2_checkpoint (default short).

selection.json  {"roles": {"A1": {"arm": ..., "checkpoint": ..., "seed2_checkpoint": "long_seed2" (optional), "unique_params_b": ...},
                           "A2", "A3", "A4", "A1s", "B1", "B2",
                           "R1": HTR-Flor trained on our form split (variant i), "R2": SVTR-Tiny (variant i),
                           "R1_rand", "R2_rand": variant ii, scored on the random-split test part (kohtd_rand_test)}}
                B1, B2, the line roles and the six reference roles R1, R2, R1_rand, R2_rand, R1_iii, R2_iii (REF's folders ours, rand, mix) are all written by
                select_b1b2.py (validation data only; selection.REFERENCE_ROLES). A reference role that is missing makes its comparison blocks 'not evaluable'.
endpoints.json  which evaluation sets play the roles T1, T2 (typed), clutter, validation, T1_rand; the audited languages; the margin;
                the published numbers of R1 and R2 (reference_arms).
Score files of locked sets are read only when the test-pass gate is open (or in synthetic mode, which marks the verdict as synthetic).
Per-arm figures of a two-seed arm: mean over its seeds, except HR4 (the larger of the two seeds, so one looping seed is not averaged away).
"""
import json
import math
import os

import numpy as np

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

MAIN_ROLES = ("A1", "A2", "A3", "A4", "A1s", "B1", "B2")
REF_ROLES = ("R1", "R2", "R1_rand", "R2_rand", "R1_iii", "R2_iii")
REPRO_MULT = 1.25       # clarification H12: a reference arm is reproduced if its CER on the replication test is at most 1.25 x the published figure
ROLES = MAIN_ROLES + REF_ROLES
SHIPPABLE = ("A1", "A2", "A3", "A4", "B1")      # B2 cannot ship under the rule, A1s is a control, R1 and R2 are references


def _meta_value(meta, test):
    if isinstance(meta, dict):
        for k, v in meta.items():
            if isinstance(v, (int, float)) and not isinstance(v, bool) and test(str(k).lower()):
                return v
        for v in meta.values():
            if isinstance(v, dict):
                r = _meta_value(v, test)
                if r is not None:
                    return r
    return None


def _ratio(m):
    """value of a metric record, from num/den when the record is flagged rare (a veto figure must be a number)."""
    if not m:
        return None
    if m.get("value") is not None:
        return m["value"]
    if m.get("den"):
        return m["num"] / m["den"]
    return None


def _mean(xs):
    xs = [x for x in xs if x is not None]
    return sum(xs) / len(xs) if xs else None


class Gather:
    def __init__(self, scores_dir, selection, endpoints, refs_mode="repaired", test_pass_ok=False, synthetic=False, B=None, seed=None):
        self.dir = scores_dir
        self.sel = selection
        self.ep = endpoints
        self.refs_mode = refs_mode
        self.ok_locked = bool(test_pass_ok or synthetic)
        self.test_pass_ok = bool(test_pass_ok)
        self.B = B or endpoints.get("B", stats.B_DEFAULT)
        self.seed = seed or endpoints.get("seed", stats.SEED_BASE)
        self._cache = {}
        self._cmp = {}
        self.notes = []
        self.roles = {r: v for r, v in selection.get("roles", {}).items() if r in ROLES and v and v.get("arm")}
        for r, v in list(self.roles.items()):
            # amendment 3.4 E5: 'long2x' exists for seed 1 only; a second seed at another budget (long_seed2) is never paired with it
            # (long2x_seed2, or long2x in the arm folder <arm>_s2, is a second seed at the SAME budget and is kept)
            if v.get("checkpoint") == "long2x" and v.get("seed2_checkpoint") and v["seed2_checkpoint"] not in ("long2x_seed2", "long2x", "long2x_s2"):
                self.roles[r] = {k: x for k, x in v.items() if k not in ("seed2_checkpoint", "seed2_arm")}
                self.notes.append("%s: seed 2 checkpoint %s is at another budget than long2x and is not paired with it: single seed (G1)" % (r, v["seed2_checkpoint"]))
        # clarification J1: a line role carries two checkpoints. 'checkpoint' (the P_long checkpoint) is read in section 3 (A2 against A1, A3, A4, A1s); the line-branch choice enters
        # section 4 and the H10 block at its furthest checkpoint, a second role '<arm>@s4' made here from section4_checkpoint (seed 2 only if one exists at that checkpoint)
        self.s4 = {}
        for r in ("A1", "A2", "A3", "A4"):
            v = self.roles.get(r)
            if v and v.get("section4_checkpoint") and v["section4_checkpoint"] != v["checkpoint"]:
                al = {k: x for k, x in v.items() if k not in ("seed2_checkpoint", "seed2_arm")}
                al["checkpoint"] = v["section4_checkpoint"]
                if v.get("section4_seed2_checkpoint"):
                    al["seed2_checkpoint"] = v["section4_seed2_checkpoint"]
                    if v.get("section4_seed2_arm"):
                        al["seed2_arm"] = v["section4_seed2_arm"]
                    if al["checkpoint"] == "long2x" and al["seed2_checkpoint"] not in ("long2x_seed2", "long2x", "long2x_s2"):       # never a second seed at another budget
                        self.notes.append("%s@s4: seed 2 checkpoint %s is at another budget than long2x and is not paired with it: single seed (G1)" % (r, al["seed2_checkpoint"]))
                        al.pop("seed2_checkpoint")
                        al.pop("seed2_arm", None)
                self.roles[r + "@s4"] = al
                if self.score(r + "@s4", "T1"):
                    self.s4[r] = r + "@s4"
                else:
                    self.roles.pop(r + "@s4")
                    for k in [k for k in self._cache if k[0] == r + "@s4"]:
                        self._cache.pop(k)
                    self.notes.append("%s: no test scores at its section-4 checkpoint %s: section 4 and the H10 block read the section-3 checkpoint %s instead (clarification J1 could not be applied)"
                                      % (r, v["section4_checkpoint"], v["checkpoint"]))

    # ---- loading ----
    def _load(self, role, stem, seed):
        r = self.roles.get(role)
        if not r:
            return None
        ck = r["checkpoint"] if seed == 1 else r.get("seed2_checkpoint")
        if not ck:
            return None
        key = (role, stem, seed)
        if key not in self._cache:
            # the score file is found by what it scored (registry name without a trailing '(...)', file stem or manifest basename), not by its file name
            # the second seed of a maker-code VLM arm or of a line arm is the arm folder <arm>_s2 (seed2_arm in the role); of a VLMA arm a checkpoint <ckpt>_seed2 of the same arm
            arm = r["arm"] if seed == 1 else (r.get("seed2_arm") or r["arm"])
            sc = ioutil.find_score(os.path.join(self.dir, arm, ck), [stem])
            if sc is not None and sc.get("locked") and not self.ok_locked:
                self.notes.append("%s on %s: locked score file ignored (test pass gate closed)" % (role, stem))
                sc = None
            self._cache[key] = sc
        return self._cache[key]

    def score(self, role, key, seed=1):
        """Score JSONs of a role on the evaluation sets of endpoint group `key` (T1, T2, clutter, T1_rand) for one seed."""
        out = []
        for stem in self.ep.get(key, {}).get("evalsets", []):
            sc = self._load(role, stem, seed)
            if sc is not None:
                out.append(sc)
        return out

    def seeds_with(self, role, key="T1"):
        return [s for s in (1, 2) if self.score(role, key, s)]

    def val_score(self, role, key, seed=1):
        r = self.roles.get(role)
        ck = (r or {}).get("checkpoint") if seed == 1 else (r or {}).get("seed2_checkpoint")
        if not r or not ck:
            return None
        arm = r["arm"] if seed == 1 else (r.get("seed2_arm") or r["arm"])
        sc = ioutil.find_score(os.path.join(self.dir, arm, ck), list(self.ep.get("validation", {}).get(key, [key])))
        return sc if (sc is None or not sc.get("locked")) else None

    def profile(self, sc, which="cer"):
        """The profile that carries the decision figure: plain or, for P1 and P2, repaired references (rule 0.6(c))."""
        if which == "cer" and self.refs_mode == "repaired":
            rr = sc["profiles"].get("repaired_refs", {})
            if "groups" in rr:
                return "repaired_refs"
        return "plain"

    # ---- paired comparison ----
    def _group(self, ep, key="T1"):
        if ep == "P1":
            return self.ep[key].get("P1_group", "all")
        return self.ep[key].get("P2_group", "slice:P2")

    def _seed_arrays(self, role, ep, key="T1"):
        """List over seeds of (cluster ids, dist, ref_len, score JSON) for the endpoint; None if a score file or group is missing."""
        out = []
        for s in self.seeds_with(role, key):
            sc = self.score(role, key, s)[0]
            if not sc["coverage"]["complete"]:
                self.notes.append("%s seed %d: predictions on %s are incomplete" % (role, s, key))
                return None
            p = self.profile(sc)
            try:
                cs = sc["profiles"][p]["cluster_sums"][self._group(ep, key)]
                out.append((sc["profiles"][p]["cluster_ids"], np.asarray(cs["dist"]), np.asarray(cs["ref_len"]), sc, p))
            except KeyError:
                return None
        return out or None

    @staticmethod
    def _align(ids, cid, num, den):
        pos = {c: i for i, c in enumerate(cid)}
        n = np.zeros(len(ids))
        d = np.zeros(len(ids))
        for i, c in enumerate(ids):
            j = pos.get(c)
            if j is not None:
                n[i], d[i] = num[j], den[j]
        return n, d

    def cmp(self, x, y, ep, mode="auto", key="T1"):
        """Paired comparison of role x against role y on P1 or P2. mode 'auto': two seeds each -> section 1 as written (seed variance,
        t quantile; amendment 3.3 D4); otherwise form bootstrap only (clarification G1), seed-averaged when an arm has two seeds.
        mode 'bootstrap': always the form-bootstrap percentile interval (used by the comparison with the published methods)."""
        ck = (x, y, ep, mode, key)
        if ck in self._cmp:
            return self._cmp[ck]
        res = None
        ax, ay = self._seed_arrays(x, ep, key), self._seed_arrays(y, ep, key)
        if ax and ay:
            ids = sorted(set().union(*[set(a[0]) for a in ax + ay]))
            nx, dx = zip(*[self._align(ids, a[0], a[1], a[2]) for a in ax])
            ny, dy = zip(*[self._align(ids, a[0], a[1], a[2]) for a in ay])
            same = all(np.array_equal(dx[0], d) for d in list(dx) + list(dy))
            if not same:
                self.notes.append("%s vs %s on %s: reference lengths differ between score files (profiles %s)" % (x, y, ep, sorted({a[4] for a in ax + ay})))
            else:
                if mode == "auto" and len(nx) >= 2 and len(ny) >= 2:
                    res = stats.paired_two_seed_t(list(nx), list(dx), list(ny), list(dy), B=self.B, seed=self.seed)
                elif len(nx) >= 2 or len(ny) >= 2:
                    res = stats.paired_seed_mean_difference(list(nx), list(dx), list(ny), list(dy), B=self.B, seed=self.seed)
                else:
                    res = stats.paired_ratio_difference(nx[0], dx[0], ny[0], dy[0], B=self.B, seed=self.seed)
                res["profile"] = ax[0][4]
                res["group"] = self._group(ep, key)
                res["seeds_x"], res["seeds_y"] = len(nx), len(ny)
        self._cmp[ck] = res
        return res

    def seed_cers(self, role, ep):
        a = self._seed_arrays(role, ep)
        if not a or len(a) < 2:
            return None
        return [float(s[1].sum() / s[2].sum()) if s[2].sum() > 0 else None for s in a]

    # ---- figures per role ----
    def _veto_seed(self, role, seed):
        f = {"hr1": None, "hr2": None, "hr3": None, "hr4_T1": None, "hr4_T2": None}
        t1, t2, cl = self.score(role, "T1", seed), self.score(role, "T2", seed), self.score(role, "clutter", seed)
        if cl:
            f["hr1"] = _ratio(cl[0]["profiles"]["plain"]["groups"].get("all", {}).get("metrics", {}).get("hr1"))
        sets = t1[:1] + t2

        def pooled(metric, ss):
            n = d = 0.0
            for s in ss:
                m = s["profiles"]["plain"]["groups"].get("all", {}).get("metrics", {}).get(metric)
                if m and m.get("den"):
                    n += m["num"]
                    d += m["den"]
            return n / d if d else None
        f["hr2"], f["hr3"] = pooled("ins_rate", sets), pooled("hr3", sets)
        if t1:
            f["hr4_T1"] = pooled("hr4", t1[:1])
        if t2:
            f["hr4_T2"] = pooled("hr4", t2)
        f["sets_used_for_hr2_hr3"] = [s["evalset"] for s in sets]
        return f

    def veto_figs(self, role):
        per = [self._veto_seed(role, s) for s in (1, 2) if self.score(role, "T1", s) or self.score(role, "clutter", s)]
        if not per:
            return {"hr1": None, "hr2": None, "hr3": None, "hr4_T1": None, "hr4_T2": None}
        out = {k: _mean([p[k] for p in per]) for k in ("hr1", "hr2", "hr3")}
        for k in ("hr4_T1", "hr4_T2"):
            vals = [p[k] for p in per if p[k] is not None]
            out[k] = max(vals) if vals else None
        out["sets_used_for_hr2_hr3"] = per[0]["sets_used_for_hr2_hr3"]
        out["n_seeds"] = len(per)
        return out

    def typed_by_lang(self, role):
        per = []
        for s in (1, 2):
            d = {}
            for sc in self.score(role, "T2", s):
                prof = sc["profiles"].get("n2fold") or sc["profiles"]["plain"]
                for g, rec in prof["groups"].items():
                    if g.startswith("lang:"):
                        m = rec["metrics"].get("cer")
                        if m and m.get("den"):
                            d[g[5:]] = m["num"] / m["den"]
            if d:
                per.append(d)
        if not per:
            return {}
        langs = set(per[0]).intersection(*[set(p) for p in per[1:]]) if len(per) > 1 else set(per[0])
        return {l: _mean([p[l] for p in per]) for l in langs}

    def gate_figs(self, role):
        r = self.roles.get(role)
        if not r:
            return {}
        vals, pipes = [], []
        for seed in (1, 2):
            meta = None
            for key in ("T1", "T2", "clutter"):
                for s in self.score(role, key, seed):
                    mp = (s.get("inputs") or {}).get("meta_path")
                    if mp and os.path.exists(mp):
                        meta = json.load(open(mp, encoding="utf-8"))
                        break
                if meta:
                    break
            if meta is None:
                v = self.val_score(role, "V1", seed)
                mp = ((v or {}).get("inputs") or {}).get("meta_path")
                if mp and os.path.exists(mp):
                    meta = json.load(open(mp, encoding="utf-8"))
            if meta is not None:
                vals.append(metautil.memory(meta)["reserved_gib"])
                pipes.append(metautil.pipeline_memory(meta))
        vals = [v for v in vals if v is not None]
        pipes = [v for v in pipes if v is not None]
        return {"reader_gib": max(vals) if vals else None, "pipeline_gib": max(pipes) if pipes else None}

    def _cer_figs(self, role, ep):
        v = []
        for s in self.seeds_with(role):
            sc = self.score(role, "T1", s)[0]
            g = sc["profiles"][self.profile(sc)]["groups"]
            v.append(_ratio(g.get(self._group(ep), {}).get("metrics", {}).get("cer")))
        return _mean(v)

    def figures(self):
        present = {r for r in self.roles if r in MAIN_ROLES and self.score(r, "T1")}
        cer, val, params, veto, typed, gate = {}, {}, {}, {}, {}, {}
        for role in list(present) + list(self.s4.values()):          # the section-4 roles (<arm>@s4) get their figures too but are not 'present' arms of the rule
            cer[role] = {"P1": self._cer_figs(role, "P1"), "P2": self._cer_figs(role, "P2")}
            vs = [self.val_score(role, "kohtd_val", s) for s in (1, 2)]
            vals = [_ratio(x["profiles"]["plain"]["groups"]["all"]["metrics"].get("cer")) for x in vs if x]
            if vals:
                val[role] = _mean(vals)
            params[role] = self.roles[role].get("unique_params_b")
            veto[role] = self.veto_figs(role)
            typed[role] = self.typed_by_lang(role)
            gate[role] = self.gate_figs(role)
        return {"present": present, "section4_ref": dict(self.s4), "cmp_fn": self.cmp, "seed_cers_fn": self.seed_cers, "veto": veto, "typed": typed,
                "audited": self.ep.get("T2", {}).get("audited_languages"), "gate": gate, "cer": cer, "val_cer": val, "params": params,
                "reader_only_counts": bool(self.ep.get("reader_only_counts_as_pipeline", False))}

    def descriptive(self):
        """All headline figures per role with their intervals, for the report (no decision)."""
        out = {}
        for role in self.roles:
            t1 = self.score(role, "T1")
            if not t1:
                continue
            sc = t1[0]
            rec = {"arm": self.roles[role]["arm"], "checkpoint": self.roles[role]["checkpoint"], "complete_T1": sc["coverage"]["complete"],
                   "seeds_scored_on_T1": self.seeds_with(role)}
            for prof in ("plain", "repaired_refs"):
                p = sc["profiles"].get(prof, {})
                if "groups" not in p:
                    continue
                for g in ("all", "slice:P2", "slice:P2b", "slice:P2_literal", "slice:registry_P2", "slice:registry_P2b"):
                    m = p["groups"].get(g, {}).get("metrics", {}).get("cer")
                    if m:
                        rec["%s|%s" % (prof, g)] = {k: m.get(k) for k in ("value", "lo", "hi", "num", "den")}
            if role in MAIN_ROLES:
                rec["veto_figures"] = self.veto_figs(role)
                rec["typed_cer_by_language"] = self.typed_by_lang(role)
                rec["gate_figures"] = self.gate_figs(role)
            out[role] = rec
        return out

    # ---- amendment 3.3 D5 with clarifications H10 to H14 ----
    def meta_of(self, role, key="T1"):
        scs = self.score(role, key)
        mp = ((scs[0].get("inputs") or {}).get("meta_path")) if scs else None
        if mp and os.path.exists(mp):
            return json.load(open(mp, encoding="utf-8"))
        return {}

    def final_budgets(self):
        """The final checkpoint of each arm of the rule with its budget (amendments 3.4 E4 and E5): samples reached, seeds, and '2 x P_long' for a line arm's long2x.
        The line-branch choice of section 3 and section 4 use these checkpoints; the budget is stated next to the verdict."""
        from . import selection as selmod
        out = {}
        for role in ("A1", "A2", "B1", "B2"):
            r = self.roles.get(role)
            if not r:
                continue
            m = self.meta_of(role)
            s = total_samples(m) if isinstance(m, dict) else None
            bud = r.get("budget")
            if role in ("A1", "A2"):
                bud = selmod.budget_of(self.dir, None, r["arm"], r["checkpoint"], samples=s)
                label = bud["label"]
                s = bud["samples_seen"] if s is None else s
            else:
                label = "samples reached: %s" % (format(int(s), ",") if s else "unknown")
            out[role] = {"arm": r["arm"], "checkpoint": r["checkpoint"], "samples_seen": s, "budget": label, "seeds": 2 if r.get("seed2_checkpoint") else 1,
                         "seed2_checkpoint": r.get("seed2_checkpoint")}
            if role in ("A1", "A2") and r["checkpoint"] == "long2x" and not r.get("seed2_checkpoint"):
                out[role]["note"] = "single seed at this budget (long2x exists for seed 1 only): form bootstrap only (G1)"
            elif not r.get("seed2_checkpoint"):
                out[role]["note"] = "single seed: form bootstrap only (G1)"
            if role in self.s4:                      # clarification J1: the same line arm at the checkpoint that enters section 4 and the H10 block
                a4 = self.roles[self.s4[role]]
                s4m = total_samples(self.meta_of(self.s4[role]))
                b4 = selmod.budget_of(self.dir, None, a4["arm"], a4["checkpoint"], long_samples=s, samples=s4m)
                out[role].update({"section3_checkpoint": r["checkpoint"], "section4_checkpoint": a4["checkpoint"], "section4_samples_seen": b4["samples_seen"],
                                  "section4_budget": b4["label"], "section4_seeds": 2 if a4.get("seed2_checkpoint") else 1})
                if not a4.get("seed2_checkpoint"):
                    out[role]["section4_note"] = "single seed at the section-4 checkpoint: form bootstrap only (G1), as confirmed in clarification J1"
        return out

    def line_branch_j1(self, decision, margin):
        """Clarification J1: which checkpoint of which line arm was read where, the P_long figure of the line-branch choice beside its section-4 figure, A2 against A1 at the
        section-4 checkpoints (descriptive only, at the samples each reached), and B1 against the choice at its section-4 checkpoint when the choice is neither A1 nor A4
        (section 4 as written compares B1 with A1, and with A4 when A4 is the choice; this extra comparison is descriptive)."""
        out = {"label": "clarification J1: section 3 reads the P_long checkpoints; the line-branch choice enters section 4 and the H10 block at its furthest checkpoint",
               "section4_roles": dict(self.s4)}
        choice = decision.get("line_branch_choice")
        if not choice or choice not in self.roles:
            out["reason"] = "no line-branch choice"
            return out

        def cer_fig(role, ep):
            scs = self.score(role, "T1", 1)
            if not scs or self.roles.get(role) is None:
                return None
            sc = scs[0]
            g = sc["profiles"][self.profile(sc)]["groups"].get(self._group(ep), {}).get("metrics", {}).get("cer")
            if not g:
                return None
            f = {k: g.get(k) for k in ("value", "lo", "hi")}
            f["seeds"] = len(self.seeds_with(role))
            if f["seeds"] >= 2:
                f["mean_over_seeds"] = self.seed_cers(role, ep)
            return f

        def block(role):
            r = self.roles[role]
            from . import selection as selmod
            sm = total_samples(self.meta_of(role))
            return {"role": role, "arm": r["arm"], "checkpoint": r["checkpoint"], "budget": selmod.budget_of(self.dir, None, r["arm"], r["checkpoint"], samples=sm),
                    "seeds": len(self.seeds_with(role)), "P1_cer": cer_fig(role, "P1"), "P2_cer": cer_fig(role, "P2")}
        out["choice"] = choice
        out["section3_checkpoint_P_long"] = block(choice)
        out["section4_checkpoint_furthest"] = block(self.s4.get(choice, choice))
        out["section4_uses_a_further_checkpoint"] = choice in self.s4
        out["reading"] = ("%s enters section 4 and the H10 block at %s (single seed there unless a second seed exists at that checkpoint: G1); its P_long figure at %s is shown beside it"
                          % (choice, out["section4_checkpoint_furthest"]["checkpoint"], out["section3_checkpoint_P_long"]["checkpoint"]))
        a1_4, a2_4 = self.s4.get("A1", "A1"), self.s4.get("A2", "A2")
        if a1_4 in self.roles and a2_4 in self.roles and self.score(a1_4, "T1") and self.score(a2_4, "T1"):
            out["A2_vs_A1_at_section4_checkpoints_descriptive_only"] = {
                "A1": block(a1_4), "A2": block(a2_4),
                "P1": self._cmp_fig(self.cmp(a2_4, a1_4, "P1")), "P2": self._cmp_fig(self.cmp(a2_4, a1_4, "P2")),
                "note": "descriptive only, at the samples each arm reached (they may differ); no clause rests on it"}
        if choice not in ("A1", "A4") and "B1" in self.roles and self.s4.get(choice):
            out["B1_vs_choice_at_its_section4_checkpoint_descriptive"] = {"P1": self._cmp_fig(self.cmp("B1", self.s4[choice], "P1")), "P2": self._cmp_fig(self.cmp("B1", self.s4[choice], "P2"))}
        return out

    def add_role(self, name, d):
        self.roles[name] = d
        for k in [k for k in self._cmp if name in k[:2]]:
            self._cmp.pop(k)
        for k in [k for k in self._cache if k[0] == name]:
            self._cache.pop(k)

    def paper_figures(self, role):
        """Figures of a role on the replication split's test part (kohtd_rand_test) in the paper's own metrics."""
        scs = self.score(role, "T1_rand")
        if not scs:
            return None
        g = scs[0]["profiles"]["plain"]["groups"].get("all", {}).get("metrics", {})

        def pct(k):
            v = _ratio(g.get(k))
            return None if v is None else 100.0 * v
        return {"n4_htrflor_cer_percent": pct("n4_htrflor_cer"), "n4_htrflor_wer_percent": pct("n4_htrflor_wer"), "n4_htrflor_ser_percent": pct("n4_htrflor_ser"),
                "pooled_cer_percent": pct("cer"), "image_error_rate_percent": None if _ratio(g.get("exact_match")) is None else 100.0 * (1.0 - _ratio(g["exact_match"])),
                "crops": scs[0]["coverage"]["scored_rows"], "complete": scs[0]["coverage"]["complete"]}

    @staticmethod
    def _limit(pub):
        """Replication gate of clarification H12: 1.25 x the published CER, rounded half up to two decimals (8.15 for 6.52, 5.74 for 4.59)."""
        if not pub or pub.get("cer_percent") is None:
            return None
        return math.floor(REPRO_MULT * pub["cer_percent"] * 100 + 0.5 + 1e-9) / 100.0

    @staticmethod
    def _cmp_fig(c):
        if not c:
            return None
        f = verdictlib._fig(c)
        if c.get("d_abs") is not None:
            f["difference_points"] = 100.0 * c["d_abs"]
        if c.get("d_abs_ci95"):
            f["difference_points_ci95"] = [100.0 * c["d_abs_ci95"][0], 100.0 * c["d_abs_ci95"][1]]
        return f

    def published_comparison(self, decision, shippable_info, checklist, attest):
        """Is the shipped candidate better than the two published methods we re-ran on our split (R1 HTR-Flor and R2 SVTR-Tiny, variant i)?
        Clarification H11: this wording only (no claim about the best published result). H12: a reference arm counts as reproduced only if its CER on the
        replication test under the paper's own metric is at most 1.25 x the published figure; the candidate must beat BOTH reference arms (i)."""
        out = {"label": "amendment 3.3 D5 with clarifications H11 and H12: is the shipped candidate better than the two published methods we re-ran on our split?",
               "wording_rule": "only 'better (or not) than the two published methods we re-ran on our split' (H11); a reference arm that did not reproduce its published figure is "
                               "compared as 'our re-run', never as 'the published method' (H12); the candidate must beat BOTH reference arms (i)",
               "reference_arms_note": "R1 (HTR-Flor) and R2 (SVTR-Tiny) re-run on KOHTD train of our form split; they cannot ship and enter no clause of sections 3 to 5"}
        refs = self.ep.get("reference_arms", {})
        names = {"R1": (refs.get("R1") or {}).get("name", "HTR-Flor"), "R2": (refs.get("R2") or {}).get("name", "SVTR-Tiny")}
        rep = {}
        for base, rr in (("R1", "R1_rand"), ("R2", "R2_rand")):
            pf = self.paper_figures(rr)
            pub = (refs.get(base) or {}).get("published")
            key = "n4_htrflor_cer_percent" if base == "R1" else "pooled_cer_percent"
            fig_ = (pf or {}).get(key)
            limit = self._limit(pub)
            reproduced = None if (fig_ is None or limit is None or not (pf or {}).get("complete")) else bool(fig_ <= limit + 1e-9)
            meta_r = self.meta_of(rr, "T1_rand")
            rep[base] = {"name": names[base], "re_run_on_random_split": pf, "published": pub, "paper_metric_used": "HTR-Flor style (lower case, longer-string denominator, mean over crops)"
                         if base == "R1" else "pooled CER (S+I+D)/N", "re_run_cer_percent": fig_, "limit_percent": limit, "multiplier": REPRO_MULT, "reproduced": reproduced,
                         "samples_seen_variant_ii": total_samples(meta_r), "train_flag_variant_ii": meta_r.get("train_flag")}
            if pf and pub:
                rep[base]["differences_percent_points"] = {k: (None if pf.get(m) is None else pf[m] - pub[k]) for k, m in
                                                            ((("cer_percent", "n4_htrflor_cer_percent"), ("wer_percent", "n4_htrflor_wer_percent"), ("ser_percent", "n4_htrflor_ser_percent"))
                                                             if base == "R1" else (("cer_percent", "pooled_cer_percent"), ("wer_percent", "image_error_rate_percent"))) if k in pub}
            rep[base]["wording"] = ("reproduced: the re-run is within 1.25 x the published CER" if reproduced else
                                    ("our re-run did not reproduce the published figure" if reproduced is False else "reproduction not established (figure missing)"))
            rep[base]["note"] = "replication check only: the random split's test crops overlap our training forms, so these figures are never compared with our arms"
        out["replication_check"] = rep
        # candidate: the arm that ships under section 5, else the shippable arm with the lowest P1 CER
        ship = decision.get("ship")
        cand = ship if ship in SHIPPABLE else None
        basis = "the arm named by section 5" if cand else None
        if cand is None and shippable_info:
            ok = [r for r in SHIPPABLE if r in shippable_info and shippable_info[r]["veto"] != "fail" and shippable_info[r]["gate"] != "not met" and shippable_info[r].get("p1") is not None]
            if ok:
                cand = min(ok, key=lambda r: shippable_info[r]["p1"])
                basis = "section 5 is %s, so the shippable arm with the lowest P1 CER among those that do not fail the veto or gate G" % ship
        out["candidate"] = {"role": cand, "basis": basis}
        # condition 1: beat BOTH reference arms (i)
        per = {}
        for r in ("R1", "R2"):
            if not self.score(r, "T1"):
                per[r] = {"result": verdictlib.NOT_EVAL, "reason": "no %s scored on T1" % r}
                continue
            c = self.cmp(cand, r, "P1", mode="bootstrap") if cand else None
            c2 = self.cmp(cand, r, "P2", mode="bootstrap") if cand else None
            if not c or c.get("d_abs_ci95") is None:
                per[r] = {"result": verdictlib.NOT_EVAL, "reason": "no candidate" if not cand else "comparison not computable (incomplete predictions or missing group)"}
                continue
            res = verdictlib.MET if c["d_abs_ci95"][1] < 0 else verdictlib.NOT_MET
            per[r] = {"result": res, "name": names[r], "p1_cer_candidate": c["cer_x"], "p1_cer_reference": c["cer_y"], "difference_points": 100.0 * c["d_abs"],
                      "difference_points_ci95": [100.0 * c["d_abs_ci95"][0], 100.0 * c["d_abs_ci95"][1]], "relative_difference": c["d_rel"], "method": c.get("kind"), "B": c["B"],
                      "P2_figures": self._cmp_fig(c2), "reproduced": rep[r]["reproduced"],
                      "against": ("the published method re-run on our split" if rep[r]["reproduced"] else "our re-run (it did not reproduce the published figure)"
                                  if rep[r]["reproduced"] is False else "our re-run (reproduction not established)"),
                      "samples_seen_variant_i": total_samples(self.meta_of(r)), "train_flag_variant_i": self.meta_of(r).get("train_flag"),
                      "rule": "the 95% form-bootstrap interval of (candidate - reference) must lie below zero"}
        out["reference_comparisons"] = per
        rs = [per[r]["result"] for r in ("R1", "R2")]
        c1 = verdictlib.NOT_MET if verdictlib.NOT_MET in rs else (verdictlib.MET if all(x == verdictlib.MET for x in rs) else verdictlib.NOT_EVAL)
        out["condition_1"] = {"result": c1, "rule": "the candidate must beat BOTH reference arms (i) (H12)", "per_reference": {r: per[r]["result"] for r in per}}
        # checklist: listed for the reader; under H11 no claim about the published numbers is made, so it no longer gates the wording
        items = []
        t1c = self.score(cand, "T1")[0] if cand and self.score(cand, "T1") else None
        t1b = self.score("R1", "T1")[0] if self.score("R1", "T1") else None
        rand_ok = all(self.paper_figures(r) is not None for r in ("R1_rand", "R2_rand"))
        both = t1c is not None and t1b is not None
        for it in checklist.get("items", []):
            cid = it["id"]
            st, ev = None, None
            if cid == "C01" and both:
                same = t1c["inputs"]["manifest_sha256"] == t1b["inputs"]["manifest_sha256"]
                st, ev = ("holds" if same else "fails"), ("identical test manifest (sha256 %s) for the candidate and the re-run reference arms; the published results used a split nobody published (H11): "
                                                         "no claim about the published numbers is made" % t1c["inputs"]["manifest_sha256"][:12])
            elif cid == "C02" and both:
                ok = all("repaired_refs" in s["profiles"] for s in (t1c, t1b))
                st, ev = ("holds" if ok else "fails"), "scores on the manifest references and on look-alike-repaired references exist for both arms"
            elif cid in ("C03", "C04") and both:
                same_code = t1c["scorer"]["code_sha256"] == t1b["scorer"]["code_sha256"]
                if not rand_ok:
                    st, ev = "not evaluable", "the competitor-style (paper metric) figures on kohtd_rand_test are missing for R1 or R2"
                else:
                    st, ev = ("holds" if same_code else "fails"), "one scorer for all arms (scoring-code sha256 %s); micro, macro and the competitor-style figure are all computed" % t1c["scorer"]["code_sha256"][:12]
            elif cid == "C05" and both:
                ok = t1c["set_info"]["unit"] == ["word"] and t1b["set_info"]["unit"] == ["word"]
                st, ev = ("holds" if ok else "fails"), "both scored on the same KOHTD word crops"
            elif cid == "C09":
                ok = self.test_pass_ok and both and all(s.get("test_pass") for s in (t1c, t1b))
                st, ev = ("holds" if ok else "not evaluable"), "test scores written inside the gated single pass with one scorer; the gate file exists: %s" % self.test_pass_ok
            elif cid == "C10" and per.get("R1", {}).get("difference_points_ci95"):
                st, ev = "holds", "paired form-bootstrap interval computed on the same test items; Holm applies to the primary family of section 1"
            elif cid == "C11":
                pr = [self.roles.get(r, {}).get("unique_params_b") for r in (cand, "R1", "R2") if r]
                gf = self.gate_figs(cand) if cand else {}
                ok = bool(pr) and all(p is not None for p in pr) and gf.get("reader_gib") is not None
                st, ev = ("holds" if ok else "not evaluable"), "unique parameters and peak memory of the candidate and the reference arms (H100, not RTX 5090)"
            elif cid == "C13":
                st, ev = ("holds" if rand_ok else "not evaluable"), "the published numbers of R1 and R2 were re-run on the random split (see replication_check; reproduced: R1 %s, R2 %s)" % (rep["R1"]["reproduced"], rep["R2"]["reproduced"])
            elif cid == "C14" and t1c is not None:
                mm = t1c["profiles"]["plain"]["groups"]["all"]["metrics"]
                ok = any(k.startswith("sl|") for k in mm) and "hr3" in mm and "hr4" in mm
                st, ev = ("holds" if ok else "fails"), "special-letter, hallucination, loop, wrong-script and omission figures are in the score file"
            elif cid == "C15":
                st, ev = "holds", "seeds stated: %s" % ("two seeds" if cand and len(self.seeds_with(cand)) >= 2 else "single seed")
            if st is None:
                a = (attest or {}).get(cid)
                if a is not None and a.get("holds") is not None:
                    st, ev = ("holds" if a["holds"] else "fails"), "attested: %s" % a.get("note", "")
                else:
                    st, ev = "not evaluable", "needs an attestation (sota_attestations.json): %s" % it.get("check", "")[:140]
            items.append({"id": cid, "required": bool(it.get("required")), "status": st, "evidence": ev, "check": it.get("check")})
        req = [i for i in items if i["required"]]
        out["condition_2"] = {"result": verdictlib.MET if req and all(i["status"] == "holds" for i in req) else (verdictlib.NOT_MET if any(i["status"] == "fails" for i in req) else verdictlib.NOT_EVAL),
                              "items": items, "required_items_holding": "%d of %d" % (sum(1 for i in req if i["status"] == "holds"), len(req)),
                              "all_items_holding": "%d of %d" % (sum(1 for i in items if i["status"] == "holds"), len(items)),
                              "note": "the evidence checklist, listed for the reader. Under clarification H11 it no longer gates the wording: the claim is only about our re-runs on our split"}
        # wording (H11, H12)
        out["claim_allowed"] = bool(c1 == verdictlib.MET)
        out["claim_allowed_means"] = "the candidate beat both reference arms (i) with 95% intervals below zero"

        def phrase(r):
            p = per[r]
            if "difference_points" not in p:
                return "%s: %s" % (names[r], p.get("reason", p["result"]))
            return "%s re-run %.2f%% (candidate %.2f points %s, 95%% interval [%.2f, %.2f], %s)" % (
                names[r], 100 * p["p1_cer_reference"], abs(p["difference_points"]), "lower" if p["difference_points"] < 0 else "higher", p["difference_points_ci95"][0],
                p["difference_points_ci95"][1], p["against"])
        if c1 == verdictlib.MET:
            all_rep = all(rep[r]["reproduced"] for r in ("R1", "R2"))
            if all_rep:
                out["wording"] = "%s (P1 CER %.2f%%) is better than the two published methods we re-ran on our split: %s; %s." % (cand, 100 * per["R1"]["p1_cer_candidate"], phrase("R1"), phrase("R2"))
            else:
                notrep = [names[r] + " (re-run %.2f%% against the limit %.2f%% for the published %.2f%%)" % (rep[r]["re_run_cer_percent"], rep[r]["limit_percent"], rep[r]["published"]["cer_percent"])
                          for r in ("R1", "R2") if rep[r]["reproduced"] is False and rep[r]["re_run_cer_percent"] is not None]
                out["wording"] = ("%s (P1 CER %.2f%%) is better than our re-runs of the two methods on our split: %s; %s. Our re-run did not reproduce the published figure of: %s, so for %s this is "
                                  "a comparison against our re-run, not against the published method."
                                  % (cand, 100 * per["R1"]["p1_cer_candidate"], phrase("R1"), phrase("R2"), "; ".join(notrep) or "reproduction not established for at least one method",
                                     "that method" if len(notrep) == 1 else "those methods"))
        else:
            failed = [r for r in ("R1", "R2") if per[r]["result"] != verdictlib.MET]
            out["wording"] = ("%s is not shown to be better than the two published methods we re-ran on our split: %s."
                              % (cand or "no candidate", "; ".join(phrase(r) for r in ("R1", "R2"))))
            out["failed_conditions"] = ["against %s: %s" % (names[r], per[r]["result"]) for r in failed]
        return out

    # ---- clarification H10: the line-branch choice with the gated character LM against B1, beside the binding greedy verdict ----
    def decoding_block(self, decision, margin):
        out = {"label": "clarification H10: second comparison, pre-declared, beside the binding greedy verdict: the line-branch choice WITH the gated character LM against B1 (same statistics)",
               "binding_verdict_unchanged": True, "binding_decoding": "greedy (rule 0.3)"}
        choice = decision.get("line_branch_choice")
        if not choice or choice not in self.roles or "B1" not in self.roles:
            out.update({"result": verdictlib.NOT_EVAL, "reason": "no line-branch choice or no B1 scored", "depends_on_decoding": None})
            return out
        choice4 = self.s4.get(choice, choice)             # clarification J1: the choice enters the H10 block at its furthest checkpoint (long2x if it exists)
        base = dict(self.roles[choice4])
        suffix = self.ep.get("lm_gated_suffix", "_lm_gated")
        lm = dict(base, checkpoint=base["checkpoint"] + suffix)
        if base.get("seed2_checkpoint"):
            lm["seed2_checkpoint"] = base["seed2_checkpoint"] + suffix
        self.add_role("LINE_LM", lm)
        out["line_branch_choice"] = choice
        out["line_branch_choice_checkpoint"] = base["checkpoint"]
        out["lm_gated_checkpoint"] = lm["checkpoint"]

        def one(y):
            cs = {ep: self.cmp("B1", y, ep) for ep in ("P1", "P2")}
            ps = {ep: (c["p_better"] if (c and c.get("p_better") is not None) else 1.0) for ep, c in cs.items()}
            hol = stats.holm_adjust(ps, 0.05)
            figs, flags = {}, []
            for ep, c in cs.items():
                f = self._cmp_fig(c) or {}
                f["holm_rank"], f["holm_threshold"] = hol[ep]["rank"], hol[ep]["threshold"]
                f["holm_reject"] = bool(hol[ep]["reject"] and c and c.get("p_better") is not None)
                figs[ep] = f
                if not c or c.get("d_rel") is None or c.get("p_better") is None:
                    flags.append(None)
                else:
                    flags.append(bool(c["d_rel"] <= -margin + verdictlib.EPS and hol[ep]["reject"]))
            res = verdictlib.NOT_EVAL if None in flags else (verdictlib.MET if all(flags) else verdictlib.NOT_MET)
            return {"result": res, "figures": figs, "family": "Holm over the two endpoints P1 and P2 at alpha 0.05"}
        g, l = one(choice4), one("LINE_LM")
        out["greedy"], out["lm_gated"] = g, l
        out["rule"] = "B1 beats the line-branch arm by at least M = %d%% (d <= -M) on P1 and on P2, each with a Holm-adjusted upper bound below zero" % round(margin * 100)
        both = g["result"] in (verdictlib.MET, verdictlib.NOT_MET) and l["result"] in (verdictlib.MET, verdictlib.NOT_MET)
        out["depends_on_decoding"] = bool(both and g["result"] != l["result"]) if both else None
        word = {verdictlib.MET: "B1 beats it by the margin", verdictlib.NOT_MET: "B1 does not beat it by the margin", verdictlib.NOT_EVAL: "not evaluable"}
        if out["depends_on_decoding"]:
            out["text"] = "the verdict depends on decoding: with greedy decoding %s (%s); with the gated character LM %s (%s)" % (word[g["result"]], choice, word[l["result"]], choice + " with LM")
        elif both:
            out["text"] = "the verdict does not depend on decoding: with greedy decoding and with the gated character LM, %s" % word[g["result"]].replace("B1 ", "B1 ", 1)
        else:
            out["text"] = "not evaluable for both decodings (greedy: %s; gated LM: %s); LM decoding must cover every test crop of the sets it is reported on, with no line cap" % (word[g["result"]], word[l["result"]])
        out["result"] = verdictlib.NOT_EVAL if not both else (verdictlib.MET if out["depends_on_decoding"] is False else verdictlib.NOT_MET)
        out["result_means"] = "met = the two decodings agree; not met = the verdict depends on decoding; not evaluable = a comparison is missing"
        return out

    # ---- clarification H13: same-data comparison at equal samples ----
    def same_data_block(self):
        out = {"label": "clarification H13: same-data comparison at equal samples: R(iii) (trained on mix_v1, 150,000 samples) against our arms' P_short checkpoints (same data, same samples)",
               "rule": "against our final checkpoints the comparison is reported only as 'different budgets', with no claim"}
        refs = [r for r in ("R1_iii", "R2_iii") if self.roles.get(r) and self.score(r, "T1")]
        if not refs:
            out.update({"result": verdictlib.NOT_EVAL, "reason": "no R1(iii) or R2(iii) scored on T1"})
            return out
        mains = []
        for r in MAIN_ROLES:
            d = self.roles.get(r)
            if not d:
                continue
            short = dict(d, checkpoint=d.get("short_checkpoint", "short"))
            if d.get("short_seed2_checkpoint"):
                short["seed2_checkpoint"] = d["short_seed2_checkpoint"]
                short["seed2_arm"] = d.get("short_seed2_arm") or d["arm"]
            else:
                short.pop("seed2_checkpoint", None)
                short.pop("seed2_arm", None)
            self.add_role(r + "@short", short)
            if self.score(r + "@short", "T1"):
                mains.append(r)
        out["reference_arms"] = {}
        for ref in refs:
            meta = self.meta_of(ref)
            n = total_samples(meta)
            rows = {}
            for r in mains:
                row = {"vs_P_short": {}, "label_P_short": "same data (mix_v1) and equal samples", "vs_final_checkpoint": {}, "label_final": "different budgets: reported only, no claim"}
                for ep in ("P1", "P2"):
                    c = self.cmp(r + "@short", ref, ep, mode="bootstrap")
                    f = self._cmp_fig(c)
                    if f and c.get("d_abs_ci95"):
                        f["ours_is_lower_interval_below_zero"] = bool(c["d_abs_ci95"][1] < 0)
                        f["ours_is_higher_interval_above_zero"] = bool(c["d_abs_ci95"][0] > 0)
                    row["vs_P_short"][ep] = f
                    row["vs_final_checkpoint"][ep] = self._cmp_fig(self.cmp(r, ref, ep, mode="bootstrap")) if r in self.roles and self.score(r, "T1") else None
                rows[r] = row
            equal = isinstance(n, (int, float)) and abs(n - 150000) <= 0.01 * 150000
            best = None
            for r, row in rows.items():
                f = row["vs_P_short"].get("P1")
                if f and f.get("cer_x") is not None and (best is None or f["cer_x"] < rows[best]["vs_P_short"]["P1"]["cer_x"]):
                    best = r
            out["reference_arms"][ref] = {"samples_seen": n, "train_flag": meta.get("train_flag"), "equal_samples_to_P_short": equal,
                                          "note": None if equal else "samples seen differ from 150,000: the comparison with P_short checkpoints is not an equal-samples comparison",
                                          "best_P_short_arm_on_P1": best,
                                          "best_arm_beats_it_on_P1": bool(best and rows[best]["vs_P_short"]["P1"].get("ours_is_lower_interval_below_zero")), "per_arm": rows}
        out["result"] = "reported"
        return out

    # ---- clarification H14: descriptive ranking of all VLM arms on the test P_short scores ----
    def vlm_ranking(self):
        out = {"label": "descriptive (clarification H14): all VLM arms at their P_short checkpoint on the test pass, with 95% form-bootstrap intervals; no decision rests on it"}
        table = self.sel.get("table") or []
        rows = []
        for t in table:
            arm = t.get("arm")
            if t.get("vlm_candidate") is False:
                continue                   # not in the VLM allow-list: not a VLM arm of this ranking
            ck = t.get("short_checkpoint") or "short"
            ckd = os.path.join(self.dir, arm, ck)
            sc = ioutil.find_score(ckd, list(self.ep.get("T1", {}).get("evalsets", [])))
            if sc is not None and sc.get("locked") and not self.ok_locked:
                sc = None
            row = {"arm": arm, "checkpoint": ck, "unique_params_b": t.get("unique_params_b"), "scored": sc is not None}
            if sc is not None:
                p = self.profile(sc)
                g = sc["profiles"][p]["groups"]

                def f(group):
                    m = (g.get(group, {}).get("metrics", {}) or {}).get("cer")
                    return {"cer": m.get("value") if m else None, "lo": m.get("lo") if m else None, "hi": m.get("hi") if m else None,
                            "crops": g.get(group, {}).get("n_items")} if m else None
                row.update({"P1": f(self.ep["T1"].get("P1_group", "all")), "P2": f(self.ep["T1"].get("P2_group", "slice:P2")), "complete": sc["coverage"]["complete"]})
            rows.append(row)
        scored = sorted([r for r in rows if r["scored"] and r.get("P1") and r["P1"].get("cer") is not None], key=lambda r: (r["P1"]["cer"], r["arm"]))
        for i, r in enumerate(scored, start=1):
            r["rank_by_P1"] = i
            nxt = scored[i] if i < len(scored) else None
            r["interval_overlaps_next"] = bool(nxt and r["P1"]["hi"] is not None and nxt["P1"]["lo"] is not None and r["P1"]["hi"] >= nxt["P1"]["lo"])
        out["rows"] = scored + [r for r in rows if r not in scored]
        out["note"] = "intervals of neighbouring rows overlap in most places: the order is not a ranking that the data separate"
        return out


def run(scores_dir, selection, endpoints, refs_mode="repaired", test_pass_ok=False, synthetic=False, B=None, seed=None, checklist=None, attestations=None):
    g = Gather(scores_dir, selection, endpoints, refs_mode, test_pass_ok, synthetic, B, seed)
    F = g.figures()
    res = verdictlib.decide(F, margin=endpoints.get("margin", verdictlib.MARGIN_M))
    ship_info = {}
    for r in F["present"]:
        if r in SHIPPABLE:
            ship_info[r] = {"veto": res.get("veto", {}).get(r, {}).get("result"), "gate": res.get("gate", {}).get(r, {}).get("result"), "p1": F["cer"].get(r, {}).get("P1")}
    res["published_method_comparison"] = g.published_comparison(res["decision"], ship_info, checklist or {"items": []}, attestations or {})
    res["decoding_comparison_H10"] = g.decoding_block(res["decision"], endpoints.get("margin", verdictlib.MARGIN_M))
    res["same_data_comparison_H13"] = g.same_data_block()
    res["vlm_ranking_P_short_descriptive_H14"] = g.vlm_ranking()
    res["final_checkpoint_budgets"] = g.final_budgets()
    res["line_branch_section4_J1"] = g.line_branch_j1(res["decision"], endpoints.get("margin", verdictlib.MARGIN_M))
    # section 3.5: A1s is the from-scratch control; d(A4 vs A1s) and d(A1 vs A1s) are the effects of size and of pretraining (reported, no clause)
    ctl = {}
    for x, y in (("A4", "A1s"), ("A1", "A1s")):
        for ep in ("P1", "P2"):
            c = g.cmp(x, y, ep)
            if c:
                ctl["%s_vs_%s_%s" % (x, y, ep)] = {k: c.get(k) for k in ("kind", "cer_x", "cer_y", "d_rel", "d_rel_ci95", "d_abs", "p_better", "se", "df", "K", "B")}
    res["control_comparisons_3_5"] = {"figures": ctl, "reading": "d(A1 vs A1s) = effect of the released base weights (pretraining); d(A4 vs A1s) = effect of size at equal initialisation; unadjusted intervals, secondary"}
    res["notes"] = g.notes
    res["descriptive"] = g.descriptive()
    res["refs_mode"] = refs_mode
    res["seed_note"] = ("arms with two seeds use version 3 section 1 as written (seed variance, t quantile with pooled seed degrees of freedom); arms with one seed keep "
                        "clarification G1; HR1 to HR3 and the typed figures are means over seeds, HR4 the larger of the two seeds")
    return res