turkic-ocr-code / scripts /r5_loopguard /lg_smoke_check.py
treoa's picture
Release 1
24aaa76
Raw History Blame Contribute Delete
10.4 kB
"""LOOPGUARD-1 CPU smoke verdict (validation pages only). Reads the smoke outputs and writes smoke_check.json:
- self-test passed (om_guard.py --selftest)
- every arm's output parses (om_text.parse_output) and every page has a record without an error field
- A0 through the changed generate_pages with the observe-only guard is byte-identical to A0 without it (same CPU run)
- the guard fires on the looping page and on no clean page (A0 observe and A2)
- A2 closes a fired line with exactly 8 location tokens, then a newline or the end token, and reading continues
- A1: NoRepeatNGramLogitsProcessor(20) bans nothing at the first generated token of the smoke pages' prompts
- the dry run of lg_run_gpu.sh scored A1, A2 and B and wrote a selection without an unseal token; the test-only
resubmission path ran
- om_score (copy) with default arguments reproduces the stored page_scores_seed1_final.json (created_utc ignored) and its
per-page file
- the held-out sets are refused without the official unseal token (om_eval_pages, om_score, om_baseline, lg_flags)
- descriptive: CPU outputs against the stored GPU A0 outputs of the same pages
Prints counts only.
usage: lg_smoke_check.py --smoke DIR --ids a,b,c --loop-page ID --refusals JSON [--out JSON]
"""
import argparse
import json
import os
import sys
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
import om_text as T # noqa: E402
D = "/path/to/TURKIC_OCR_DATA"
ap = argparse.ArgumentParser()
ap.add_argument("--smoke", required=True)
ap.add_argument("--ids", required=True)
ap.add_argument("--loop-page", required=True)
ap.add_argument("--refusals", required=True)
ap.add_argument("--out", default="")
a = ap.parse_args()
SM = a.smoke
IDS = [x for x in a.ids.split(",") if x]
SETS = ("gen_val", "school_val")
def read_dir(d):
out = {}
for s in SETS:
p = os.path.join(d, s + ".jsonl")
if os.path.exists(p):
with open(p, encoding="utf-8") as f:
for line in f:
r = json.loads(line)
out[r["id"]] = r
return out
arms = {"A0": read_dir(SM + "/page_preds/smoke_A0"), "A0obs": read_dir(SM + "/page_preds/smoke_A0obs"),
"A1": read_dir(SM + "/dry/page_preds/A1"), "A2": read_dir(SM + "/dry/page_preds/A2")}
stored = read_dir(D + "/outputs/r6_onemodel/page_preds/seed1_final")
C, rep = {}, {"pages": IDS, "loop_page": a.loop_page, "arms": {}}
st = json.load(open(SM + "/selftest.json", encoding="utf-8"))
C["selftest_passed"] = bool(st.get("passed"))
for arm, P in arms.items():
x = {}
for i in IDS:
r = P.get(i)
if r is None:
x[i] = {"missing": True}
continue
inst = T.parse_output(r["raw"])
x[i] = {"n_new": r["n_new"], "hit_cap": r["hit_cap"], "instances": len(inst), "malformed": sum(1 for q in inst if q["malformed"]),
"events": r.get("guard_events"), "error": r.get("error"),
"equals_stored_gpu_A0": (r.get("raw_unprocessed", r["raw"]) == stored[i]["raw"]) if i in stored else None,
"stored_gpu_A0_hit_cap": stored.get(i, {}).get("hit_cap")}
rep["arms"][arm] = x
C["%s_all_pages_parsed_no_error" % arm] = all(not v.get("missing") and not v.get("error") and v["instances"] >= 0 for v in x.values())
C["A0_observe_byte_identical_to_A0"] = all(arms["A0"].get(i, {}).get("raw") == arms["A0obs"].get(i, {}).get("raw_unprocessed") ==
arms["A0obs"].get(i, {}).get("raw") for i in IDS)
clean = [i for i in IDS if i != a.loop_page]
for arm in ("A0obs", "A2"):
C["%s_fires_on_loop_page" % arm] = bool(arms[arm].get(a.loop_page, {}).get("guard_events"))
C["%s_no_fire_on_clean_pages" % arm] = all(not arms[arm].get(i, {}).get("guard_events") for i in clean)
# A2: a fired line is closed with 8 location tokens, then newline or end, and reading continues
close = []
r = arms["A2"].get(a.loop_page)
if r and r.get("guard_events"):
import om_guard as G
ids = r["new_ids"]
lines = G.split_lines(ids)
for e in r["guard_events"]:
ln = lines[e["line"]]
n_text = 0
while n_text < len(ln) and not (G.LOC0 <= ln[n_text] <= G.LOC1):
n_text += 1
rest = ln[n_text:]
last = e["line"] == len(lines) - 1
ends_ok = (not last) or (rest and rest[-1] in (2,)) or r["hit_cap"]
locs = [t for t in rest if G.LOC0 <= t <= G.LOC1]
close.append({"line": e["line"], "why": e["why"], "p": e["p"], "n_text": n_text, "loc_tokens_after": len(locs),
"non_loc_after_text": len(rest) - len(locs) - (1 if rest and rest[-1] == 2 else 0),
"followed_by_newline": not last, "lines_after": len(lines) - 1 - e["line"], "ends_ok": bool(ends_ok)})
rep["A2_line_closing"] = close
C["A2_closes_fired_lines_with_8_locations_then_newline_or_end"] = all(
(c["loc_tokens_after"] == 8 and c["non_loc_after_text"] == 0 and c["ends_ok"]) or (r["hit_cap"] and c["line"] == len(lines) - 1)
for c in close)
C["A2_continues_after_first_fire"] = close[0]["lines_after"] > 0 or not r["hit_cap"]
else:
C["A2_closes_fired_lines_with_8_locations_then_newline_or_end"] = False
C["A2_continues_after_first_fire"] = False
# A1 first step
fs = json.load(open(SM + "/a1_first_step.json", encoding="utf-8"))
rep["A1_first_step"] = fs
C["A1_no_ban_at_first_generated_token"] = fs.get("rows") and all(v == 0 for v in fs["banned_per_row"])
# dry run
sel = json.load(open(SM + "/dry/selection.json", encoding="utf-8")) if os.path.exists(SM + "/dry/selection.json") else {}
rep["dry_selection"] = {k: sel.get(k) for k in ("selected", "why", "acceptance_passed", "dry_run")}
C["dry_scored_A1_A2_B"] = all(os.path.exists(SM + "/dry/page_scores/page_scores_%s.json" % x) for x in ("A1", "A2", "B"))
C["dry_selection_written_no_unseal"] = bool(sel) and sel.get("dry_run") is True and not os.path.exists(T.OFFICIAL_UNSEAL) \
and not os.path.exists(SM + "/dry/UNSEAL")
acc = json.load(open(SM + "/dry/acceptance.json", encoding="utf-8")) if os.path.exists(SM + "/dry/acceptance.json") else {}
rep["dry_acceptance_descriptive_cpu_vs_gpu"] = {s: {k: c["A2"].get(k) for k in ("fired_pages", "not_fired_pages_differing_from_A0")}
for s, c in acc.get("sets", {}).items()}
bi = acc.get("a2_byte_identity_vs_fresh_A0", {})
det = acc.get("determinism_fresh_A0_vs_55172_logged", {})
rep["dry_a2_vs_fresh_A0"] = bi
rep["dry_determinism_vs_55172"] = det
fa0 = read_dir(SM + "/dry/page_preds/A0")
C["dry_fresh_A0_control_written"] = all(i in fa0 for i in IDS)
# same CPU numerics: A2 must equal the fresh A0 on every non-fired page, so the dry acceptance passes on CPU
C["dry_A2_byte_identical_to_fresh_A0_on_nonfired_pages"] = bi.get("pass") is True and bi.get("non_fired_pages", 0) >= 2
C["dry_acceptance_passed_on_cpu"] = acc.get("passed") is True
# CPU vs the stored GPU outputs differ: logged with edit distances, never a stop
C["dry_determinism_log_has_edit_distances"] = bool(det.get("differing")) and all(isinstance(d.get("edit_distance_to_55172"), int)
for d in det.get("differing", []))
C["dry_scored_fresh_A0"] = os.path.exists(SM + "/dry/page_scores/page_scores_A0.json")
ud = sel.get("unseal_decision", {})
rep["dry_unseal_decision"] = ud
C["dry_unseal_decision_recorded_and_false"] = bool(ud) and ud.get("write_unseal") is False
ast_ = json.load(open(SM + "/accept_selftest/accept_selftest.json", encoding="utf-8"))
rep["accept_selftest"] = ast_
C["accept_selftest_passed"] = bool(ast_.get("passed"))
# om_score --exclude-ids on validation (dummy file with 2 gen_val ids)
ex = json.load(open(SM + "/excl_test/page_scores_excl.json", encoding="utf-8"))
dummy = json.load(open(SM + "/excl_dummy.json", encoding="utf-8"))
g, sv = ex["sets"]["gen_val"], ex["sets"]["school_val"]
rep["exclude_ids_test"] = {"gen_val": {"candidate_pages": g["candidate"]["pages"], "baseline_pages": g["baseline"]["pages"],
"paired_M28_pages": (g["paired_candidate_minus_baseline"]["M28"] or {}).get("pages")},
"school_val": {"candidate_pages": sv["candidate"]["pages"], "baseline_pages": sv["baseline"]["pages"]},
"excluded_recorded": ex.get("excluded_pages"), "G1_inputs_complete": ex["gates"]["G1_page_cer"]["inputs_complete"]}
pp = [json.loads(x) for x in open(SM + "/excl_test/per_page_excl.jsonl", encoding="utf-8")]
C["exclude_ids_drops_exactly_the_listed_pages"] = (g["candidate"]["pages"] == 298 and g["baseline"]["pages"] == 298
and (g["paired_candidate_minus_baseline"]["M28"] or {}).get("pages") == 298
and sv["candidate"]["pages"] == 150 and sv["baseline"]["pages"] == 150
and not any(r["id"] in set(dummy["gen_val"]) for r in pp)
and ex["gates"]["G1_page_cer"]["inputs_complete"] is True)
rs = open(SM + "/dry2.log", encoding="utf-8").read() if os.path.exists(SM + "/dry2.log") else ""
C["dry_resubmission_test_only_path"] = "DRY RUN: test-only passed" in rs
# scorer reproduction
mine = json.load(open(SM + "/score_repro/page_scores_seed1_final.json", encoding="utf-8"))
theirs = json.load(open(D + "/outputs/r6_onemodel/page_scores/page_scores_seed1_final.json", encoding="utf-8"))
for d_ in (mine, theirs):
d_.pop("created_utc", None)
C["om_score_default_reproduces_stored_page_scores"] = mine == theirs
pp_m = open(SM + "/score_repro/per_page_seed1_final.jsonl", encoding="utf-8").read()
pp_t = open(D + "/outputs/r6_onemodel/page_scores/per_page_seed1_final.jsonl", encoding="utf-8").read()
C["om_score_default_reproduces_stored_per_page"] = pp_m == pp_t
# refusals
ref = json.load(open(a.refusals, encoding="utf-8"))
rep["refusals"] = ref
C["heldout_refused_without_token"] = all(v["rc"] != 0 and "REFUSED" in v["tail"] for v in ref.values())
rep["checks"] = C
rep["smoke_passed"] = all(bool(v) for v in C.values())
out = a.out or SM + "/smoke_check.json"
json.dump(rep, open(out, "w"), indent=1, ensure_ascii=False)
print(json.dumps({"smoke_passed": rep["smoke_passed"], "failed": [k for k, v in C.items() if not v]}, indent=1))