File size: 25,568 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
"""Decision logic of the pre-registered rule: version 3 sections 1-5 with amendment 3.2 and clarifications G1-G7.

decide(F) is a pure function of a dictionary of figures F; the extraction of those figures from score JSONs is in
verdictgather.py. Every clause is returned as a record {id, section, plain, result, figures, note} with result one of
'met', 'not met', 'not evaluable'. Nothing is guessed: a missing input gives 'not evaluable'.

Units pinned here (and in tests/test_verdict.py at their boundaries). All rates are fractions, "points" are percentage points:
  typed non-inferiority: macro CER of X <= macro CER of A1 + 0.003  (0.3 points); no audited language worse by more than 0.01 (1.0 point)
  HR1 fails above max(2 x HR1_A1, HR1_A1 + 0.02) or above 0.05 absolute (the cap is dropped when HR1_A1 itself exceeds 0.05)
  HR2 fails above 1.5 x HR2_A1 AND above HR2_A1 + 0.003;  HR3 fails above HR3_A1 + 0.005;  HR4 fails above 0.001 on T1 or on T2
  margin M = 0.10 (relative): B1 needs d(B1 vs A1) <= -0.10 on P1 and P2
  gate G: 24 GB is read as 24e9 bytes = 22.35 GiB (the conservative reading; the figures of VLMA and LINEDET are in GiB);
          the 24 GiB reading is reported beside it
  boundaries: a rule that says "at most" passes at equality; "more than" and "above" fail only above the limit; equality is tested
          with a tolerance of 1e-12 in favour of the arm
"""
import numpy as np

from . import stats

EPS = 1e-12
GIB = 2.0 ** 30
GATE_DECIMAL_GIB = 24e9 / GIB
GATE_BINARY_GIB = 24.0
MARGIN_M = 0.10
ALPHA = 0.05
TYPED_MACRO_TOL = 0.003
TYPED_LANG_TOL = 0.01
HR1_REL, HR1_PP, HR1_CAP = 2.0, 0.02, 0.05
HR2_REL, HR2_PP = 1.5, 0.003
HR3_PP = 0.005
HR4_CAP = 0.001
FUTILITY = 1.10
MET, NOT_MET, NOT_EVAL = "met", "not met", "not evaluable"
FAMILY = [("B1", "P1"), ("B1", "P2"), ("A2", "P1"), ("A2", "P2")]       # versus A1; the Holm family of version 3 section 1


def _num(x):
    return x is not None and not (isinstance(x, float) and x != x)


# ---------------------------------------------------------------- section 2: the hallucination veto ------------------------
def veto(x, a1):
    """x, a1: dicts hr1, hr2, hr3, hr4_T1, hr4_T2 (float or None). Returns {'result': pass|fail|not evaluable, 'components': {...}}."""
    comps = {}
    # HR1
    if _num(x.get("hr1")) and _num(a1.get("hr1")):
        a = a1["hr1"]
        thr = max(HR1_REL * a, a + HR1_PP)
        cap_dropped = a > HR1_CAP + EPS
        fail = x["hr1"] > thr + EPS or ((not cap_dropped) and x["hr1"] > HR1_CAP + EPS)
        comps["HR1"] = {"result": "fail" if fail else "pass", "figure": x["hr1"], "relative_limit": thr, "absolute_cap": None if cap_dropped else HR1_CAP,
                        "cap_dropped_because_A1_exceeds_5_percent": cap_dropped}
    else:
        comps["HR1"] = {"result": "not evaluable", "reason": "no HR1 figure (clutter-only test crops) for this arm or for A1"}
    # HR2
    if _num(x.get("hr2")) and _num(a1.get("hr2")):
        a = a1["hr2"]
        fail = x["hr2"] > HR2_REL * a + EPS and x["hr2"] > a + HR2_PP + EPS
        comps["HR2"] = {"result": "fail" if fail else "pass", "figure": x["hr2"], "limit_relative": HR2_REL * a, "limit_absolute": a + HR2_PP}
    else:
        comps["HR2"] = {"result": "not evaluable", "reason": "no HR2 figure for this arm or for A1"}
    # HR3
    if _num(x.get("hr3")) and _num(a1.get("hr3")):
        a = a1["hr3"]
        fail = x["hr3"] > a + HR3_PP + EPS
        comps["HR3"] = {"result": "fail" if fail else "pass", "figure": x["hr3"], "limit": a + HR3_PP}
    else:
        comps["HR3"] = {"result": "not evaluable", "reason": "no HR3 figure for this arm or for A1"}
    # HR4: above 0.1% on T1 or on T2
    h1, h2 = x.get("hr4_T1"), x.get("hr4_T2")
    fails = [v for v in (h1, h2) if _num(v) and v > HR4_CAP + EPS]
    if fails:
        comps["HR4"] = {"result": "fail", "figure_T1": h1, "figure_T2": h2, "limit": HR4_CAP}
    elif _num(h1) and _num(h2):
        comps["HR4"] = {"result": "pass", "figure_T1": h1, "figure_T2": h2, "limit": HR4_CAP}
    else:
        comps["HR4"] = {"result": "not evaluable", "figure_T1": h1, "figure_T2": h2, "reason": "T1 or T2 figure missing and no figure above the limit"}
    results = [c["result"] for c in comps.values()]
    if "fail" in results:
        res = "fail"
    elif all(r == "pass" for r in results):
        res = "pass"
    else:
        res = "not evaluable"
    return {"result": res, "components": comps}


# ---------------------------------------------------------------- typed non-inferiority (clause c of 4 and of 3.1) ---------
def typed_noninferiority(x_by_lang, ref_by_lang, audited):
    """x_by_lang, ref_by_lang: language -> pooled CER on the typed test (profile n2fold). audited: list of languages or None."""
    if not audited:
        return {"result": NOT_EVAL, "reason": "no audited-language list exists (the list is fixed before training by the rule; endpoints.json audited_languages is empty)"}
    miss = [l for l in audited if l not in x_by_lang or l not in ref_by_lang or not _num(x_by_lang[l]) or not _num(ref_by_lang[l])]
    if miss:
        return {"result": NOT_EVAL, "reason": "typed CER missing for audited languages %s" % miss}
    mx = sum(x_by_lang[l] for l in audited) / len(audited)
    mr = sum(ref_by_lang[l] for l in audited) / len(audited)
    worst = max(x_by_lang[l] - ref_by_lang[l] for l in audited)
    ok_macro = mx <= mr + TYPED_MACRO_TOL + EPS
    ok_lang = worst <= TYPED_LANG_TOL + EPS
    return {"result": MET if (ok_macro and ok_lang) else NOT_MET, "macro_x": mx, "macro_ref": mr, "macro_difference": mx - mr,
            "macro_limit": TYPED_MACRO_TOL, "worst_language_difference": worst, "language_limit": TYPED_LANG_TOL,
            "audited_languages": list(audited), "macro_ok": ok_macro, "languages_ok": ok_lang}


# ---------------------------------------------------------------- gate G -------------------------------------------------
def gate_g(reader_reserved_gib, pipeline_reserved_gib=None, reader_only_counts=False):
    """24 GB read as 24e9 bytes (22.35 GiB); the 24 GiB reading is reported beside it."""
    v = pipeline_reserved_gib if _num(pipeline_reserved_gib) else None
    out = {"limit_decimal_gb_as_gib": GATE_DECIMAL_GIB, "limit_binary_gib": GATE_BINARY_GIB, "reader_reserved_gib": reader_reserved_gib,
           "pipeline_reserved_gib": pipeline_reserved_gib}
    if v is not None:
        out["result"] = MET if v <= GATE_DECIMAL_GIB + EPS else NOT_MET
        out["result_binary_reading"] = MET if v <= GATE_BINARY_GIB + EPS else NOT_MET
        out["basis"] = "whole pipeline"
        return out
    if not _num(reader_reserved_gib):
        out["result"] = NOT_EVAL
        out["reason"] = "no peak memory figure"
        return out
    out["basis"] = "reader only (no detector or layout stage was measured)"
    out["result_binary_reading"] = MET if reader_reserved_gib <= GATE_BINARY_GIB + EPS else NOT_MET
    if reader_reserved_gib > GATE_DECIMAL_GIB + EPS:
        out["result"] = NOT_MET
        out["reason"] = "the reader alone already exceeds the limit"
    elif reader_only_counts:
        out["result"] = MET
        out["reason"] = "reader-only figure counted as the pipeline figure (flag set by the caller)"
    else:
        out["result"] = NOT_EVAL
        out["reason"] = "reader alone is within the limit but the whole pipeline (detector plus reader) was not measured"
    return out


# ---------------------------------------------------------------- Holm family ----------------------------------------------
def holm_family(cmp_fn, alpha=ALPHA, ref=None):
    """Computes the four tests of the pre-registered family against A1 and applies Holm. A test that cannot be computed gets
    p = 1.0 (never rejected), which keeps the thresholds of the pre-registered family size 4. Returns dict key -> record.
    ref (clarification J1): {arm: reference role} for a test whose A1 is read at another checkpoint, for example {'B1': 'A1@s4'} (section 4 reads A1 at its
    furthest checkpoint, section 3 at P_long); the key names stay '<arm>_vs_A1_<endpoint>' and the record names the reference role."""
    recs, ps = {}, {}
    for arm, ep in FAMILY:
        key = "%s_vs_A1_%s" % (arm, ep)
        c = cmp_fn(arm, (ref or {}).get(arm, "A1"), ep)
        recs[key] = c
        ps[key] = c["p_better"] if (c and c.get("p_better") is not None) else 1.0
    adj = stats.holm_adjust(ps, alpha)
    out = {}
    for key, c in recs.items():
        a = adj[key]
        rec = {"evaluable": bool(c and c.get("p_better") is not None), "p_better": c.get("p_better") if c else None,
               "holm_rank": a["rank"], "holm_threshold": a["threshold"], "holm_reject": bool(a["reject"] and c and c.get("p_better") is not None),
               "d_rel": c.get("d_rel") if c else None, "d_rel_ci95": c.get("d_rel_ci95") if c else None, "cer_x": c.get("cer_x") if c else None,
               "cer_a1": c.get("cer_y") if c else None, "holm_upper_bound": None, "reference_role": (ref or {}).get(key.split("_vs_")[0], "A1")}
        if c:
            rec["method"] = c.get("kind")
        if c and c.get("kind") == "two_seed_t" and c.get("se") and c.get("df"):
            rec["holm_upper_bound"] = stats.holm_bound_t(c["d_rel"], c["se"], c["df"], a["rank"], a["m"], alpha)
            rec["se"], rec["df"] = c["se"], c["df"]
        elif c and c.get("_rel_reps") is not None and len(c["_rel_reps"]) >= 20:
            rec["holm_upper_bound"] = stats.holm_bound(c["_rel_reps"], a["rank"], a["m"], alpha)
        out[key] = rec
    return out


def _worst(results):
    if NOT_MET in results:
        return NOT_MET
    if all(r == MET for r in results):
        return MET
    return NOT_EVAL


def _fig(c):
    if not c:
        return None
    return {k: c.get(k) for k in ("kind", "cer_x", "cer_y", "d_rel", "d_rel_ci95", "d_abs", "p_better", "prob_improvement", "K", "B", "se", "df",
                                  "seed_cers_x", "seed_cers_y", "var_bootstrap", "relative_seed_sd_squared_pooled")}


def seed_pairs(F, x, y):
    """Clause 4b: x is better than y in every pairing of a seed of x with a seed of y, on P1 and on P2 (point CERs). Evaluated only when
    both arms have two seeds (amendment 3.3 D4); otherwise not evaluable (clarification G2)."""
    fn = F.get("seed_cers_fn")
    if fn is None:
        return NOT_EVAL, None, "no per-seed figures: reported as not evaluable, nothing substituted (G2)"
    figs, ok = {}, []
    for ep in ("P1", "P2"):
        a, b = fn(x, ep), fn(y, ep)
        if not a or not b or len(a) < 2 or len(b) < 2:
            return NOT_EVAL, None, "needs two seeds of both arms (amendment 3.3 D4); otherwise not evaluable, nothing substituted (G2)"
        figs[ep] = {"seed_cers_x": a, "seed_cers_y": b}
        ok.append(all(xi < yj for xi in a for yj in b))
    return (MET if all(ok) else NOT_MET), figs, "every pairing of a seed of %s with a seed of %s: 4 pairs on each of P1 and P2" % (x, y)


# ---------------------------------------------------------------- the decision --------------------------------------------
def decide(F, margin=MARGIN_M):
    """F keys: present (set of arm roles), cmp_fn(x, y, endpoint) -> dict or None, veto (role -> figures), typed (role -> by-language CER),
    audited (list or None), gate (role -> {reader_gib, pipeline_gib}), cer (role -> {'P1','P2'} point estimates), val_cer (role -> CER on all
    KOHTD validation crops), params (role -> unique parameters in billions), reader_only_counts (bool).
    Returns dict with clauses and the decision."""
    present = set(F["present"])
    C = []

    def add(cid, section, plain, result, figures=None, note=None, waivable=False):
        C.append({"id": cid, "section": section, "plain": plain, "result": result, "figures": figures, "note": note,
                  "waivable_when_not_evaluable": waivable})
        return C[-1]

    if "A1" not in present:
        add("0", "all", "The reference arm A1 has no scores: nothing can be compared.", NOT_EVAL)
        return {"clauses": C, "decision": {"line_branch_choice": None, "section4": NOT_EVAL, "ship": "undetermined: A1 has no scores",
                                           "ship_text": "undetermined: A1 has no scores (or its test scores are not readable)"},
                "holm_family": {}, "veto": {}, "typed": {}, "gate": {}}
    cmp_fn = F["cmp_fn"]
    # clarification J1: section 3 (A2 against A1, A3, A4, A1s) reads the line arms at P_long; section 4 (B1 against A1, and against A4 when A4 is the choice) and the H10 block read the
    # line arm at its furthest checkpoint. section4_ref maps a line role to its section-4 role (for example 'A1' -> 'A1@s4'); a missing entry means the same checkpoint as section 3.
    s4 = F.get("section4_ref") or {}
    a1_4, a4_4 = s4.get("A1", "A1"), s4.get("A4", "A4")
    fam = holm_family(cmp_fn, ref={"B1": a1_4})
    vetoes = {r: veto(F["veto"].get(r, {}), F["veto"].get("A1", {})) for r in present}
    typed = {r: typed_noninferiority(F["typed"].get(r, {}), F["typed"].get("A1", {}), F.get("audited")) for r in present}
    if "B1" in present and a1_4 != "A1":
        vetoes["B1"] = veto(F["veto"].get("B1", {}), F["veto"].get(a1_4, {}))
        typed["B1"] = typed_noninferiority(F["typed"].get("B1", {}), F["typed"].get(a1_4, {}), F.get("audited"))
    gate = {r: gate_g(F["gate"].get(r, {}).get("reader_gib"), F["gate"].get(r, {}).get("pipeline_gib"), F.get("reader_only_counts", False)) for r in present}
    # section 2
    for r in sorted(present):
        v = vetoes[r]
        add("2.veto." + r, "2", "Hallucination veto for %s against A1 (HR1 text on empty images, HR2 inserted characters, HR3 overlong or garbage output, HR4 loops)" % r,
            {"pass": MET, "fail": NOT_MET}.get(v["result"], NOT_EVAL), v["components"], note="'met' = passes the veto")
    # section 3.1
    choice, choice_status = "A1", "A1 is the line-branch choice by 3.2 (A2 was not shown to qualify)"
    if "A2" in present:
        k1, k2 = fam["A2_vs_A1_P1"], fam["A2_vs_A1_P2"]
        r_a = _worst([MET if (k["evaluable"] and k["holm_reject"]) else (NOT_MET if k["evaluable"] else NOT_EVAL) for k in (k1, k2)])
        add("3.1.a", "3.1", "A2 (small) is not worse than A1: the Holm-adjusted upper bound of d(A2 vs A1) is at most 0% on P1 and on P2", r_a,
            {"P1": k1, "P2": k2}, note="Holm family of 4 tests, alpha 0.05 (G1); single seed, form bootstrap only")
        r_b = typed["A2"]["result"]
        add("3.1.b", "3.1", "A2's typed macro CER is at most A1's + 0.3 points and no audited language is worse by more than 1.0 point", r_b, typed["A2"])
        r_c = {"pass": MET, "fail": NOT_MET}.get(vetoes["A2"]["result"], NOT_EVAL)
        add("3.1.c", "3.1", "A2 passes the hallucination veto", r_c, vetoes["A2"]["components"])
        r31 = _worst([r_a, r_b, r_c])
        add("3.1", "3.1", "A2 (small) is the line-branch choice", r31)
        if r31 == MET:
            choice, choice_status = "A2", "A2 qualifies under 3.1"
        elif r31 == NOT_EVAL:
            choice_status = "A1 by default; A2's qualification is not evaluable (see 3.1.a-c): provisional"
    else:
        add("3.1", "3.1", "A2 (small) is the line-branch choice", NOT_EVAL, note="A2 has no scores")
    # section 3.3 and 3.5: A3 and A4 replace the choice only if better with intervals excluding zero, passing N and the veto (and gate G for A4)
    for arm, sec in (("A3", "3.3"), ("A4", "3.5")):
        if arm not in present:
            add(sec, sec, "%s replaces the line-branch choice" % arm, NOT_EVAL, note="%s has no scores" % arm)
            continue
        c1, c2 = cmp_fn(arm, choice, "P1"), cmp_fn(arm, choice, "P2")
        def better(c):
            if not c or c.get("d_rel_ci95") is None:
                return NOT_EVAL
            return MET if c["d_rel_ci95"][1] < 0 else NOT_MET
        r_a = _worst([better(c1), better(c2)])
        r_n = typed_noninferiority(F["typed"].get(arm, {}), F["typed"].get(choice, {}), F.get("audited"))["result"]
        r_v = {"pass": MET, "fail": NOT_MET}.get(vetoes[arm]["result"], NOT_EVAL)
        parts = [r_a, r_n, r_v] + ([gate[arm]["result"]] if arm == "A4" else [])
        add(sec + ".a", sec, "%s is better than the choice (%s) on both P1 and P2 with the 95%% interval of d excluding zero in its favour" % (arm, choice), r_a,
            {"P1": _fig(c1), "P2": _fig(c2)}, note="interval unadjusted, secondary (outside the Holm family)")
        add(sec + ".n", sec, "%s passes the typed non-inferiority test against the choice" % arm, r_n)
        add(sec + ".v", sec, "%s passes the hallucination veto" % arm, r_v)
        if arm == "A4":
            add(sec + ".g", sec, "A4 passes gate G (24 GB)", gate[arm]["result"], gate[arm])
        r = _worst(parts)
        add(sec, sec, "%s replaces the line-branch choice" % arm, r)
        if r == MET:
            choice, choice_status = arm, "%s replaces the earlier choice under %s" % (arm, sec)
        elif r == NOT_EVAL:
            choice_status += "; %s's replacement test is not evaluable" % arm
    # knee probe 3.4
    if "A4" in present:
        add("3.4", "3.4", "Knee probe: A4 was trained, so it is the probe (see 3.5)", MET)
    elif "A2" in present:
        c = cmp_fn("A2", "A1", "P1")
        if c and c.get("d_rel") is not None and c.get("d_rel_ci95"):
            trig = c["d_rel"] >= 0.15 and c["d_rel_ci95"][0] >= 0.05
            add("3.4", "3.4", "A4 was not trained: a follow-up with a CTC model of 40M parameters or more is required when d(A2 vs A1) on P1 is at least +15% with its lower bound at least +5%",
                NOT_MET if trig else MET, _fig(c), note="'not met' = the follow-up is required before the size is frozen")
        else:
            add("3.4", "3.4", "Knee probe trigger", NOT_EVAL)
    # section 4: B1 against A1
    sec4_clauses = []
    incon = None
    if "B1" in present:
        k1, k2 = fam["B1_vs_A1_P1"], fam["B1_vs_A1_P2"]
        def a4(k):
            if not k["evaluable"]:
                return NOT_EVAL
            return MET if (k["d_rel"] is not None and k["d_rel"] <= -margin + EPS and k["holm_reject"]) else NOT_MET
        r4a = _worst([a4(k1), a4(k2)])
        sec4_clauses.append(add("4.a", "4", "B1 beats A1 by at least M = %d%% on P1 and on P2, each with a Holm-adjusted upper bound below zero" % round(margin * 100), r4a,
                                {"P1": k1, "P2": k2, "margin": margin}, note="single seed, form bootstrap only"))
        r4b, f4b, n4b = seed_pairs(F, "B1", a1_4)
        sec4_clauses.append(add("4.b", "4", "B1 is better than A1 in all seed pairs on P1 and P2", r4b, f4b, note=n4b, waivable=True))
        sec4_clauses.append(add("4.c", "4", "B1's typed macro CER is at most A1's + 0.3 points and no audited language is worse by more than 1.0 point",
                                typed["B1"]["result"], typed["B1"]))
        sec4_clauses.append(add("4.d", "4", "B1 passes the hallucination veto", {"pass": MET, "fail": NOT_MET}.get(vetoes["B1"]["result"], NOT_EVAL), vetoes["B1"]["components"]))
        sec4_clauses.append(add("4.e", "4", "B1 passes gate G (24 GB, whole pipeline)", gate["B1"]["result"], gate["B1"]))
        if choice == "A4":
            c1, c2 = cmp_fn("B1", a4_4, "P1"), cmp_fn("B1", a4_4, "P2")
            def a4b(c):
                if not c or c.get("d_rel_ci95") is None:
                    return NOT_EVAL
                return MET if (c["d_rel"] <= -margin + EPS and c["d_rel_ci95"][1] < 0) else NOT_MET
            sec4_clauses.append(add("4.a'", "4", "A4 is the line-branch choice: B1 also beats A4 by at least M on P1 and P2 (intervals unadjusted, secondary)",
                                    _worst([a4b(c1), a4b(c2)]), {"P1": _fig(c1), "P2": _fig(c2)}))
            r4bp, f4bp, n4bp = seed_pairs(F, "B1", a4_4)
            sec4_clauses.append(add("4.b'", "4", "B1 is better than A4 in all seed pairs", r4bp, f4bp, note=n4bp, waivable=True))
        # section 6.1 futility on all KOHTD validation forms
        b1v, a1v = F.get("val_cer", {}).get("B1"), F.get("val_cer", {}).get(a1_4, F.get("val_cer", {}).get("A1"))
        if _num(b1v) and _num(a1v) and a1v > 0:
            fut = b1v > FUTILITY * a1v + EPS
            add("6.1", "6", "Futility: B1's CER on all KOHTD validation forms is above 1.10 x A1's", MET if not fut else NOT_MET,
                {"B1_val_cer": b1v, "A1_val_cer": a1v, "ratio": b1v / a1v}, note="'not met' = futility triggers: section 4 is recorded as not met. Under amendment 3.2 no later run depends on it.")
            if fut:
                sec4_clauses.append(add("4.6.1", "4", "Section 4 is recorded as not met because the futility rule 6.1 triggers", NOT_MET))
        else:
            add("6.1", "6", "Futility check on KOHTD validation", NOT_EVAL, note="validation CER of B1 or A1 missing")
        g1, g2 = cmp_fn("B1", a1_4, "P1"), cmp_fn("B1", a1_4, "P2")
        two_seeds = bool(g1 and g1.get("kind") == "two_seed_t")
        grey = None
        incon = None
        if g1 and g2 and g1.get("d_rel") is not None and g2.get("d_rel") is not None:
            grey_d = any(-0.20 - EPS <= c["d_rel"] <= EPS for c in (g1, g2))
            cde = [c["result"] for c in C if c["id"] in ("4.c", "4.d", "4.e")]
            grey = bool(two_seeds and grey_d and all(r == MET for r in cde))
            incon = bool(two_seeds and any(c.get("d_rel_ci95") and c["d_rel_ci95"][0] <= -margin <= c["d_rel_ci95"][1] and c["d_rel_ci95"][0] <= 0 <= c["d_rel_ci95"][1]
                                           for c in (g1, g2)))
        add("6.2", "6", "Grey zone: a third B1 seed when d lies between 0% and -20% on P1 or P2 and clauses c, d, e hold", NOT_EVAL,
            {"grey_zone_condition_met": grey, "P1": _fig(g1), "P2": _fig(g2)},
            note="the third seed is not planned in R5 (amendment 3.3 has two seeds), so this clause is reported as not evaluable; the condition is shown for the reader" if two_seeds
            else "needs two seeds of B1 and of A1 (clarification G2)", waivable=True)
        add("6.3", "6", "Inconclusive: the interval of d on P1 or P2 contains both -M and 0", NOT_MET if incon else (MET if incon is False else NOT_EVAL),
            {"interval_contains_both": incon}, note="'not met' = inconclusive (the line-branch choice ships by default and the result is reported as inconclusive); only evaluated with two seeds", waivable=True)
    else:
        sec4_clauses.append(add("4", "4", "B1 against A1", NOT_EVAL, note="B1 has no scores (no B1 was chosen or trained)"))
    bad = [c for c in sec4_clauses if c["result"] == NOT_MET]
    nonwaivable_ne = [c for c in sec4_clauses if c["result"] == NOT_EVAL and not c["waivable_when_not_evaluable"]]
    if bad:
        sec4 = NOT_MET
    elif nonwaivable_ne:
        sec4 = NOT_EVAL
    elif all(c["result"] == MET for c in sec4_clauses if not c["waivable_when_not_evaluable"]) and "B1" in present:
        waived = [c["id"] for c in sec4_clauses if c["waivable_when_not_evaluable"] and c["result"] == NOT_EVAL]
        sec4 = ("met on every evaluable clause (%s not evaluable: single seed)" % ", ".join(waived)) if waived else "met on every clause (4b evaluated with two seeds)"
    else:
        sec4 = NOT_EVAL
    add("4", "4", "Section 4: B1 wins on accuracy", sec4 if sec4 in (NOT_MET, NOT_EVAL) else MET, note=sec4)
    # section 5
    if sec4 == NOT_MET:
        ship = choice
        teacher = None
        if "B1" in present:
            k1 = fam["B1_vs_A1_P1"]
            teacher = bool(k1["evaluable"] and k1["holm_reject"] and vetoes["B1"]["result"] == "pass")
        ship_text = "line-branch choice %s ships" % choice
    elif sec4 == NOT_EVAL:
        ship, teacher = "undetermined", None
        ship_text = "undetermined: a clause of section 4 is not evaluable for lack of data; the line-branch choice is %s" % choice
    else:
        ship, teacher = "B1", None
        ship_text = ("B1 ships (section 4 holds on every evaluable clause; %s not evaluable with one seed, so this is conditional on reading G2 as a waiver)" % ", ".join(waived)
                     if waived else "B1 ships (section 4 holds on every clause, including 4b with two seeds)")
    out = {"line_branch_choice": choice, "line_branch_choice_status": choice_status, "section4": sec4, "ship": ship, "ship_text": ship_text,
           "b1_handwriting_teacher_under_5": teacher, "inconclusive_6_3": incon,
           "section4_reference_roles": {"A1": a1_4, "A4": a4_4}}
    # B2 remarks of section 5
    if "B2" in present and "B1" in present:
        cb1, cb2 = F["cer"].get("B1", {}), F["cer"].get("B2", {})
        p1, p2 = F.get("params", {}).get("B1"), F.get("params", {}).get("B2")
        if all(_num(v) for v in (cb1.get("P1"), cb1.get("P2"), cb2.get("P1"), cb2.get("P2"))):
            near = cb2["P1"] <= 1.05 * cb1["P1"] + EPS and cb2["P2"] <= 1.05 * cb1["P2"] + EPS
            better = cb2["P1"] < cb1["P1"] and cb2["P2"] < cb1["P2"]
            out["b2_remarks"] = {"smaller_than_B1": (p2 < p1) if (_num(p1) and _num(p2)) else None, "within_5_percent_of_B1_on_P1_and_P2": near,
                                 "better_than_B1_on_P1_and_P2": better,
                                 "text": ("B2 is better than B1 on P1 and P2: a follow-up with seeds decides" if better else
                                          ("B2 is a smaller candidate for a follow-up" if (near and _num(p1) and _num(p2) and p2 < p1) else "no remark"))}
    return {"clauses": C, "decision": out, "holm_family": fam, "veto": vetoes, "typed": typed, "gate": gate}