File size: 15,314 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
"""LOOPGUARD-1: automatic selection of the arm (design protocol.selection_rule) and the held-out confirmation summary.

select  : reads <root>/page_scores/page_scores_{A1,A2,B}.json (om_score, validation) and <root>/acceptance.json.
          eligible = G1 as coded in om_score.py holds on gen_val AND school_val (round(M28, 4) <= pipeline and
          round(M29, 4) <= pipeline, inputs complete). Pick: among eligible one-weights arms (A1, A2) the lower school_val M28;
          tie -> lower school_val M29 -> A2. If neither: B, if B is eligible. Else nothing.
          Writes <root>/selection.json (with its unseal_decision) and .sha256, <root>/SELECTED (the arm, plain text) and,
          only if an arm is selected, the acceptance passed, A1, A2 and B are all present and complete, this is not a dry run
          and <root> is the official root, the unseal token <root>/UNSEAL. B is built from the fresh A0 of this job (AM1). Also writes <root>/diagnostics_val.json (design decision_rules.diagnostics_reported_whatever_happens).
confirm : reads the held-out score files page_scores_<S>_test.json (S = selected arm; for B page_scores_B_test.json), the
          descriptive A0_test and B_test files, and writes <root>/confirm.json: G1 on both held-out sets, the 95% interval of
          the school_test M28 difference, pages better / worse / equal, G2 and G3 (stored crop scores, carried over), the
          claim wording and release_candidate_with_one_set_of_weights. PRIMARY = without the pages of --exclude-ids (the
          2 generated test pages with near-duplicate training images; decision of 26 Nov 2026); the same
          figures on all pages (page_scores_<S>_test_all.json) are reported as the sensitivity line.

          confirm exits 2 and writes confirm_failed.json (no claim) if a primary or sensitivity file is missing or incomplete,
          and records held-out pages with an error field or a one-at-a-time read for S and A0obs.

usage: om_lg_select.py select --root DIR [--no-unseal] [--job-id ID] [--a0 FRESH_A0_DIR] [--stored DIR_55172]
       om_lg_select.py confirm --root DIR [--exclude-ids FILE]
"""
import argparse
import hashlib
import json
import os
import sys
import time

HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
import om_text as T  # noqa: E402

OFFICIAL_ROOT = os.path.dirname(T.OFFICIAL_UNSEAL)
VAL = {"gen_val": 300, "school_val": 150}
HELD = {"gen_test": 300, "school_test": 150}
BREAK_EVEN_SCHOOL = {"M28": 0.8604, "M29": 0.5117}      # records/R5/LOOPGUARD/analysis/lg_final_rule.json break_even_*


def utc():
    return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())


def sha(p):
    return hashlib.sha256(open(p, "rb").read()).hexdigest()


def load(p):
    return json.load(open(p, encoding="utf-8")) if os.path.exists(p) else None


def read_jsonl(p):
    out = {}
    if os.path.exists(p):
        with open(p, encoding="utf-8") as f:
            for line in f:
                try:
                    r = json.loads(line)
                except ValueError:
                    continue
                out[r["id"]] = r
    return out


def arm_status(res, sets):
    if res is None:
        return {"present": False, "eligible": False}
    g1 = res.get("gates", {}).get("G1_page_cer", {})
    st = {"present": True, "G1_pass": bool(g1.get("pass")), "inputs_complete": bool(g1.get("inputs_complete")), "per_set": {}}
    full = True
    for s, n in sets.items():
        c = res["sets"].get(s, {})
        cand, base = c.get("candidate", {}), c.get("baseline", {})
        full &= cand.get("pages") == n and base.get("pages") == n and bool(cand.get("complete")) and bool(base.get("complete"))
        st["per_set"][s] = {"M28": cand.get("M28"), "M29": cand.get("M29"), "M28_pipeline": base.get("M28"), "M29_pipeline": base.get("M29"),
                            "pages": cand.get("pages"), "G1_set_pass": (g1.get("per_set", {}).get(s) or {}).get("pass")}
    st["all_pages_present"] = full
    st["eligible"] = st["G1_pass"] and st["inputs_complete"] and full and set(g1.get("per_set", {})) == set(sets)
    return st


def diagnostics(root, a0_dir, stored_dir):
    """design decision_rules.diagnostics_reported_whatever_happens (validation). 'Formerly capped' = the pages capped in the
    stored 55172 outputs (where the break-even was computed); changes are counted against the fresh A0 of this job (AM1)."""
    d = {}
    A0 = {s: read_jsonl(os.path.join(a0_dir, s + ".jsonl")) for s in VAL}
    ST = {s: read_jsonl(os.path.join(stored_dir, s + ".jsonl")) for s in VAL}
    capped = {s: sorted(i for i, r in ST[s].items() if r.get("hit_cap")) for s in VAL}
    d["formerly_capped_pages_55172"] = capped
    d["capped_pages_fresh_A0"] = {s: sorted(i for i, r in A0[s].items() if r.get("hit_cap")) for s in VAL}
    for arm in ("A1", "A2"):
        P = {s: read_jsonl(os.path.join(root, "page_preds", arm, s + ".jsonl")) for s in VAL}
        x = {}
        for s in VAL:
            x[s] = {"pages_hitting_cap": sorted(i for i, r in P[s].items() if r.get("hit_cap")),
                    "fires_per_page": {i: len(r.get("guard_events") or []) for i, r in P[s].items() if r.get("guard_events")},
                    "pages_differing_from_A0": sum(1 for i, r in P[s].items() if i in A0[s] and r["raw"] != A0[s][i]["raw"]),
                    "non_capped_A0_pages_changed": sum(1 for i, r in P[s].items() if i in A0[s] and not A0[s][i].get("hit_cap")
                                                       and r["raw"] != A0[s][i]["raw"])}
        rows = read_jsonl_cells(os.path.join(root, "page_scores", "per_page_%s.jsonl" % arm))
        for s in VAL:
            cand = rows.get(s + "/candidate", {})
            sub = [cand[i] for i in capped[s] if i in cand]
            n = sum(r["nref"] for r in sub)
            x[s]["formerly_capped_cer"] = {"pages": len(sub), "M28": round(sum(r["ro"] for r in sub) / n, 4) if n else None,
                                           "M29": round(sum(r["of"] for r in sub) / n, 4) if n else None}
            if s == "school_val":
                x[s]["formerly_capped_cer"]["break_even"] = BREAK_EVEN_SCHOOL
            allr = list(cand.values())
            x[s]["lines_out_over_reference"] = round(sum(r["n_hyp"] for r in allr) / max(sum(r["n_ref"] for r in allr), 1), 4) if allr else None
        d[arm] = x
    return d


def read_jsonl_cells(p):
    out = {}
    if os.path.exists(p):
        with open(p, encoding="utf-8") as f:
            for line in f:
                r = json.loads(line)
                out.setdefault(r["cell"], {})[r["id"]] = r
    return out


def select(a):
    root = a.root
    sc = os.path.join(root, "page_scores")
    acc = load(os.path.join(root, "acceptance.json"))
    st = {arm: arm_status(load(os.path.join(sc, "page_scores_%s.json" % arm)), VAL) for arm in ("A1", "A2", "B")}
    one = [arm for arm in ("A1", "A2") if st[arm]["eligible"]]
    chosen, why = None, "no arm eligible: no confirmation, the held-out sets stay sealed"
    if one:
        def key(arm):
            v = st[arm]["per_set"]["school_val"]
            return (round(v["M28"], 6), round(v["M29"], 6), 0 if arm == "A2" else 1)
        chosen = sorted(one, key=key)[0]
        why = "eligible one-weights arms %s; lowest school_val M28 (tie: M29, then A2)" % one
    elif st["B"]["eligible"]:
        chosen, why = "B", "no one-weights arm eligible; B eligible"
    acc_ok = bool(acc and acc.get("passed"))
    complete3 = all(st[x]["present"] and st[x]["all_pages_present"] for x in ("A1", "A2", "B"))
    official = os.path.realpath(root) == os.path.realpath(OFFICIAL_ROOT)
    unseal = bool(chosen is not None and acc_ok and complete3 and not a.no_unseal and official)
    sel = {"design": T.LG_DESIGN_ID, "created_utc": utc(), "job_id": a.job_id, "root": root, "arms": st, "selected": chosen, "why": why,
           "acceptance_passed": acc_ok, "dry_run": bool(a.no_unseal),
           "unseal_decision": {"write_unseal": unseal, "arm_selected": chosen is not None, "acceptance_passed": acc_ok,
                               "A1_A2_B_all_present_and_complete": complete3, "dry_run": bool(a.no_unseal), "official_root": official},
           "inputs_sha256": {os.path.basename(p): sha(p) for p in [os.path.join(sc, "page_scores_%s.json" % x) for x in ("A0", "A1", "A2", "B")]
                             + [os.path.join(root, "acceptance.json")] if os.path.exists(p)},
           "rule": "eligible = G1 as coded in om_score.py on gen_val and school_val; pick lower school_val M28 among A1/A2, tie M29, then A2; else B if eligible; else none"}
    try:
        sel["diagnostics_file"] = os.path.join(root, "diagnostics_val.json")
        json.dump(diagnostics(root, a.a0, a.stored), open(sel["diagnostics_file"], "w"), indent=1)
    except Exception as e:  # noqa: BLE001  (diagnostics are descriptive; never block the selection)
        sel["diagnostics_error"] = repr(e)[:200]
    p = os.path.join(root, "selection.json")
    json.dump(sel, open(p, "w"), indent=1)
    h = sha(p)
    open(p + ".sha256", "w").write("%s  %s\n" % (h, p))
    open(os.path.join(root, "SELECTED"), "w").write((chosen or "NONE") + "\n")
    if unseal:
        roles = ["A0", "pipeline", "score"] + ([chosen] if chosen in ("A1", "A2") else [])
        json.dump({"design": T.LG_DESIGN_ID, "arm": chosen, "roles_allowed": roles, "selection": p, "selection_sha256": h,
                   "job_id": a.job_id, "created_utc": utc()}, open(T.OFFICIAL_UNSEAL, "w"), indent=1)
    print(json.dumps({"selected": chosen, "why": why, "acceptance_passed": acc_ok, "unseal_written": unseal,
                      "eligible": {x: st[x]["eligible"] for x in st}}))
    return 0


def confirm(a):
    root = a.root
    sc = os.path.join(root, "page_scores")
    sel = load(os.path.join(root, "selection.json"))
    S = sel["selected"]
    T.check_unsealed(T.OFFICIAL_UNSEAL, "score")
    excl = load(a.exclude_ids) if a.exclude_ids else {}
    held_n = {s: n - len(excl.get(s, []) if isinstance(excl.get(s), list) else []) for s, n in HELD.items()}
    prim = load(os.path.join(sc, "page_scores_%s_test.json" % S))
    out = {"design": T.LG_DESIGN_ID, "created_utc": utc(), "selected": S, "primary_comparison": "%s against the pipeline" % S,
           "primary_excludes": {"file": a.exclude_ids, "ids": {s: v for s, v in excl.items() if isinstance(v, list)}, "pages": held_n}}
    allp = load(os.path.join(sc, "page_scores_%s_test_all.json" % S))
    st_all = arm_status(allp, HELD)
    ci_all = (((allp or {}).get("sets", {}).get("school_test", {}).get("paired_candidate_minus_baseline") or {}).get("M28") or {})
    out["sensitivity_all_pages"] = {"G1_heldout_pass": bool(st_all.get("eligible")), "per_set": st_all.get("per_set"),
                                    "paired_intervals": {s: (allp or {}).get("sets", {}).get(s, {}).get("paired_candidate_minus_baseline") for s in HELD},
                                    "school_test_M28_difference": ci_all}
    st = arm_status(prim, held_n)
    if not (st.get("present") and st.get("all_pages_present") and st_all.get("present") and st_all.get("all_pages_present")):
        bad = {"design": T.LG_DESIGN_ID, "created_utc": utc(), "selected": S, "primary": st, "sensitivity_all_pages": st_all,
               "error": "a primary or sensitivity score file is missing or incomplete: no claim is written"}
        json.dump(bad, open(os.path.join(root, "confirm_failed.json"), "w"), indent=1)
        print(json.dumps({"confirm": "FAILED", "error": bad["error"]}))
        return 2
    # held-out page records with an error field or read one image at a time (ids and counts only)
    hp = {}
    for name in sorted(set(["A0obs"] + ([S] if S in ("A1", "A2") else []))):
        for s in HELD:
            p = os.path.join(root, "page_preds", name, s + ".jsonl")
            n_err = n_single = 0
            if os.path.exists(p):
                with T.open_sealed(p, T.OFFICIAL_UNSEAL, "score") as f:
                    for line in f:
                        try:
                            r = json.loads(line)
                        except ValueError:
                            continue
                        n_err += 1 if r.get("error") else 0
                        n_single += 1 if r.get("batch_fallback_single") else 0
            hp.setdefault(name, {})[s] = {"error_pages": n_err, "batch_fallback_single_pages": n_single}
    out["heldout_page_errors"] = hp
    g = (prim or {}).get("gates", {})
    g1 = bool(st.get("eligible"))
    ci = (((prim or {}).get("sets", {}).get("school_test", {}).get("paired_candidate_minus_baseline") or {}).get("M28") or {})
    bwe = {}
    rows = read_jsonl_cells(os.path.join(sc, "per_page_%s_test.jsonl" % S))
    for s in HELD:
        c, b = rows.get(s + "/candidate", {}), rows.get(s + "/baseline", {})
        for key in ("ro", "of"):
            better = sum(1 for i in c if i in b and c[i][key] < b[i][key])
            worse = sum(1 for i in c if i in b and c[i][key] > b[i][key])
            bwe.setdefault(s, {})["M28" if key == "ro" else "M29"] = {"better": better, "worse": worse, "equal": len(c) - better - worse}
    g2 = bool((g.get("G2_crop_cer_V1") or {}).get("pass"))
    g3 = bool((g.get("G3_clutter_nonempty") or {}).get("pass"))
    if g1 and ci.get("ci95") and ci["ci95"][1] < 0:
        claim = "beats the pipeline on real photographed pages"
    elif g1:
        claim = "not worse"
    else:
        claim = "not confirmed"
    out.update({"held_out": st, "G1_heldout_pass": g1, "school_test_M28_difference": ci,
                "paired_intervals": {s: (prim or {}).get("sets", {}).get(s, {}).get("paired_candidate_minus_baseline") for s in HELD},
                "pages_better_worse_equal": bwe, "G2": g.get("G2_crop_cer_V1"), "G3": g.get("G3_clutter_nonempty"),
                "claim": claim, "release_candidate_with_one_set_of_weights": bool(S in ("A1", "A2") and g1 and g2 and g3),
                "descriptive": {}})
    for tag in ("A0_test", "B_test", "A0_test_all", "B_test_all"):
        r = load(os.path.join(sc, "page_scores_%s.json" % tag))
        if r:
            out["descriptive"][tag] = {s: {k: (r["sets"].get(s, {}).get("candidate") or {}).get(k) for k in ("M28", "M29", "pages")} for s in HELD}
    json.dump(out, open(os.path.join(root, "confirm.json"), "w"), indent=1)
    print(json.dumps({k: out[k] for k in ("selected", "G1_heldout_pass", "claim", "release_candidate_with_one_set_of_weights")}))
    return 0


if __name__ == "__main__":
    ap = argparse.ArgumentParser()
    ap.add_argument("mode", choices=["select", "confirm"])
    ap.add_argument("--root", required=True)
    ap.add_argument("--no-unseal", action="store_true")
    ap.add_argument("--job-id", default=os.environ.get("SLURM_JOB_ID", "local"))
    ap.add_argument("--exclude-ids", default="")
    ap.add_argument("--a0", default="/path/to/TURKIC_OCR_DATA/outputs/r6_loopguard/page_preds/A0",
                    help="the fresh control arm A0 of this job (amendment AM1)")
    ap.add_argument("--stored", default="/path/to/TURKIC_OCR_DATA/outputs/r6_onemodel/page_preds/seed1_final",
                    help="job 55172's stored A0 outputs (formerly capped pages, determinism)")
    a = ap.parse_args()
    sys.exit(select(a) if a.mode == "select" else confirm(a))