Download scripts/r5_loopguard/lg_accept.py from treoa/turkic-ocr-code: direct link, hf CLI and curl.
- Browser
- Download file 10.4 kB
-
https://huggingface.co/treoa/turkic-ocr-code/resolve/main/scripts/r5_loopguard/lg_accept.py
- Command line
-
hf download hf://treoa/turkic-ocr-code/scripts/r5_loopguard/lg_accept.py
-
curl -L -o lg_accept.py https://huggingface.co/treoa/turkic-ocr-code/resolve/main/scripts/r5_loopguard/lg_accept.py
10.4 kB
| """LOOPGUARD-1 acceptance checks on VALIDATION, run before any score is read (design protocol.acceptance_checks_before_any_score_is_read, | |
| as amended on 26 Nov 2026, records/R5/LOOPGUARD/design_amendments.json AM1): | |
| 1 the fresh unguarded control A0 (all 450 validation pages, run in the same GPU job before A1), A1 and A2: every page of | |
| gen_val (300) and school_val (150) written, none with an error field; | |
| 2 A2 byte identity against the FRESH A0: every page on which the guard did not fire has raw_unprocessed byte-identical to | |
| the fresh A0 output. Any difference stops the job (no scoring, no selection, no unseal). Every differing page is logged | |
| with its edit distance; | |
| 3 determinism log, NOT a stop condition: the fresh A0 against the stored A0 outputs of job 55172 (identical pages, every | |
| differing page id with its edit distance, share, and whether the share is within --tol = 1%); | |
| 4 A2 fires per page, compared with the predicted list (the pages where the fresh A0 hit the cap; the 55172 capped pages are | |
| listed too); | |
| descriptive: A1 pages differing from the fresh A0, pages still hitting the cap, batch fallbacks. | |
| Writes JSON (ids and numbers only); exit 0 if checks 1 and 2 pass, else 4. | |
| usage: lg_accept.py --a0 FRESH_A0_DIR --a1 DIR --a2 DIR --stored DIR_55172 --out JSON [--tol 0.01] [--ids a,b,c (dry run)] | |
| lg_accept.py --selftest DIR (synthetic cases, written under DIR) | |
| """ | |
| import argparse | |
| import json | |
| import os | |
| import sys | |
| EXPECTED = {"gen_val": 300, "school_val": 150} | |
| def read(p): | |
| out = {} | |
| if not os.path.exists(p): | |
| return out | |
| 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 edit(a, b): | |
| from rapidfuzz.distance import Levenshtein | |
| return int(Levenshtein.distance(a or "", b or "")) | |
| def accept(a0, a1, a2, stored, tol=0.01, ids="", expected=None): | |
| expected = expected or EXPECTED | |
| want = set(x for x in ids.split(",") if x) | |
| rep = {"design": "LOOPGUARD-1", "amendment": "AM1 (26 Nov 2026): A1 and A2 are compared with the fresh A0 of this job; the " | |
| "comparison with job 55172 is a logged determinism check only", "tol_logged": tol, "sets": {}} | |
| ok_written = True | |
| n_nonfired, differing = 0, [] | |
| det = {"pages": 0, "identical_to_55172": 0, "differing": []} | |
| for s, n in expected.items(): | |
| A0, A1, A2, ST = (read(os.path.join(d, s + ".jsonl")) for d in (a0, a1, a2, stored)) | |
| idl = sorted(want & set(ST)) if want else sorted(ST) | |
| exp_n = len(idl) if want else n | |
| cell = {"expected_pages": exp_n} | |
| for arm, P in (("A0_fresh", A0), ("A1", A1), ("A2", A2)): | |
| got = [i for i in idl if i in P] | |
| cell[arm] = {"written": len(got), "complete": len(got) == exp_n, | |
| "error_pages": sorted(i for i in got if P[i].get("error")), | |
| "hit_cap_pages": sorted(i for i in got if P[i].get("hit_cap")), | |
| "batch_fallback_single_pages": sorted(i for i in got if P[i].get("batch_fallback_single"))} | |
| ok_written &= cell[arm]["complete"] and not cell[arm]["error_pages"] | |
| fired = sorted(i for i in idl if i in A2 and A2[i].get("guard_events")) | |
| nofire = [i for i in idl if i in A2 and not A2[i].get("guard_events")] | |
| n_nonfired += len(nofire) | |
| diff_here = [] | |
| for i in nofire: | |
| if i not in A0: | |
| diff_here.append({"set": s, "id": i, "fresh_A0_missing": True}) | |
| elif A2[i].get("raw_unprocessed") != A0[i]["raw"]: | |
| diff_here.append({"set": s, "id": i, "edit_distance_to_fresh_A0": edit(A2[i].get("raw_unprocessed"), A0[i]["raw"])}) | |
| differing += diff_here | |
| for i in idl: | |
| if i in A0 and i in ST: | |
| det["pages"] += 1 | |
| if A0[i]["raw"] == ST[i]["raw"]: | |
| det["identical_to_55172"] += 1 | |
| else: | |
| det["differing"].append({"set": s, "id": i, "edit_distance_to_55172": edit(A0[i]["raw"], ST[i]["raw"]), | |
| "hit_cap_fresh": bool(A0[i].get("hit_cap")), "hit_cap_55172": bool(ST[i].get("hit_cap"))}) | |
| predicted = sorted(i for i in idl if i in A0 and A0[i].get("hit_cap")) | |
| cell["A2"].update({"fired_pages": fired, "fires_total": sum(len(A2[i]["guard_events"]) for i in fired), | |
| "fires_per_page": {i: len(A2[i]["guard_events"]) for i in fired}, | |
| "not_fired_pages": len(nofire), "not_fired_pages_differing_from_fresh_A0": [d["id"] for d in diff_here], | |
| "predicted_fire_pages_fresh_A0_cap": predicted, | |
| "capped_pages_55172": sorted(i for i in idl if ST[i].get("hit_cap")), | |
| "fired_not_predicted": sorted(set(fired) - set(predicted)), | |
| "predicted_not_fired": sorted(set(predicted) - set(fired))}) | |
| a1_changed = sorted(i for i in idl if i in A1 and i in A0 and A1[i]["raw"] != A0[i]["raw"]) | |
| cell["A1"].update({"pages_differing_from_fresh_A0": len(a1_changed), | |
| "non_capped_A0_pages_changed": sorted(i for i in a1_changed if not A0[i].get("hit_cap"))}) | |
| rep["sets"][s] = cell | |
| rep["a2_byte_identity_vs_fresh_A0"] = {"non_fired_pages": n_nonfired, "differing_pages": differing, "pass": not differing} | |
| share = len(det["differing"]) / float(det["pages"]) if det["pages"] else 0.0 | |
| det.update({"differing_share": round(share, 5), "within_1pct_logged_only": share <= tol}) | |
| rep["determinism_fresh_A0_vs_55172_logged"] = det | |
| rep["all_written_no_error"] = bool(ok_written) | |
| rep["passed"] = bool(ok_written and not differing) | |
| return rep | |
| def selftest(d): | |
| os.makedirs(d, exist_ok=True) | |
| cases = {} | |
| def write(folder, s, rows): | |
| os.makedirs(folder, exist_ok=True) | |
| with open(os.path.join(folder, s + ".jsonl"), "w", encoding="utf-8") as f: | |
| for r in rows: | |
| f.write(json.dumps(r) + "\n") | |
| n = 200 | |
| exp = {"gen_val": n} | |
| base = [{"id": "p%03d" % k, "raw": "line %d<|LOC_1|>" % k, "hit_cap": False} for k in range(n)] | |
| def run(name, a0_mut, a2_mut, want, a0_err=None, a2_drop=None, a2_fire=None): | |
| root = os.path.join(d, name) | |
| a0 = [dict(r, raw=a0_mut.get(r["id"], r["raw"])) for r in base] | |
| if a0_err: | |
| a0 = [dict(r, error="boom") if r["id"] == a0_err else r for r in a0] | |
| a2 = [] | |
| for r in a0: | |
| raw = a2_mut.get(r["id"], r["raw"]) | |
| x = {"id": r["id"], "raw": raw, "raw_unprocessed": raw, "guard_events": [], "hit_cap": False} | |
| if a2_fire and r["id"] == a2_fire: | |
| x["guard_events"] = [{"line": 0, "why": "length"}] | |
| x["raw_unprocessed"] = "different" | |
| if r["id"] != a2_drop: | |
| a2.append(x) | |
| write(root + "/stored", "gen_val", base) | |
| write(root + "/a0", "gen_val", a0) | |
| write(root + "/a1", "gen_val", [dict(r) for r in a0]) | |
| write(root + "/a2", "gen_val", a2) | |
| rep = accept(root + "/a0", root + "/a1", root + "/a2", root + "/stored", 0.01, "", exp) | |
| cases[name] = {"passed": rep["passed"], "expected": want, | |
| "a2_differing": len(rep["a2_byte_identity_vs_fresh_A0"]["differing_pages"]), | |
| "fresh_vs_55172_differing": len(rep["determinism_fresh_A0_vs_55172_logged"]["differing"]), | |
| "within_1pct_logged": rep["determinism_fresh_A0_vs_55172_logged"]["within_1pct_logged_only"]} | |
| run("all_identical", {}, {}, True) | |
| run("a2_differs_from_fresh_A0", {}, {"p010": "x"}, False) | |
| run("fresh_A0_differs_from_55172_on_3_pages_A2_equal_to_fresh", {"p001": "a", "p002": "b", "p003": "c"}, {}, True) | |
| run("fired_page_may_differ", {}, {}, True, a2_fire="p020") | |
| run("fresh_A0_page_with_error", {}, {}, False, a0_err="p005") | |
| run("a2_page_missing", {}, {}, False, a2_drop="p007") | |
| ok = all(v["passed"] == v["expected"] for v in cases.values()) and \ | |
| cases["fresh_A0_differs_from_55172_on_3_pages_A2_equal_to_fresh"]["within_1pct_logged"] is False and \ | |
| cases["fresh_A0_differs_from_55172_on_3_pages_A2_equal_to_fresh"]["fresh_vs_55172_differing"] == 3 | |
| json.dump({"cases": cases, "passed": ok}, open(os.path.join(d, "accept_selftest.json"), "w"), indent=1) | |
| print(json.dumps({"accept_selftest_passed": ok, "cases": cases})) | |
| return 0 if ok else 2 | |
| if __name__ == "__main__": | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--a0") | |
| ap.add_argument("--a1") | |
| ap.add_argument("--a2") | |
| ap.add_argument("--stored") | |
| ap.add_argument("--out") | |
| ap.add_argument("--tol", type=float, default=0.01) | |
| ap.add_argument("--ids", default="") | |
| ap.add_argument("--selftest", default="") | |
| a = ap.parse_args() | |
| if a.selftest: | |
| sys.exit(selftest(a.selftest)) | |
| rep = accept(a.a0, a.a1, a.a2, a.stored, a.tol, a.ids) | |
| json.dump(rep, open(a.out, "w"), indent=1) | |
| for d in rep["a2_byte_identity_vs_fresh_A0"]["differing_pages"]: | |
| print("A2 non-fired page differing from the fresh A0: %s %s edit distance %s" % (d["set"], d["id"], d.get("edit_distance_to_fresh_A0", "n/a (A0 missing)"))) | |
| det = rep["determinism_fresh_A0_vs_55172_logged"] | |
| for d in det["differing"]: | |
| print("determinism log: fresh A0 differs from 55172 on %s %s, edit distance %d" % (d["set"], d["id"], d["edit_distance_to_55172"])) | |
| print(json.dumps({"passed": rep["passed"], "all_written_no_error": rep["all_written_no_error"], | |
| "a2_nonfired": rep["a2_byte_identity_vs_fresh_A0"]["non_fired_pages"], | |
| "a2_differing_from_fresh_A0": len(rep["a2_byte_identity_vs_fresh_A0"]["differing_pages"]), | |
| "fresh_A0_identical_to_55172": "%d/%d" % (det["identical_to_55172"], det["pages"]), | |
| "within_1pct_logged_only": det["within_1pct_logged_only"], | |
| "sets": {s: {"A2_fired": len(c["A2"]["fired_pages"]), "A1_changed": c["A1"]["pages_differing_from_fresh_A0"]} | |
| for s, c in rep["sets"].items()}})) | |
| sys.exit(0 if rep["passed"] else 4) | |