"""Greedy validation predictions of one RQ2 run (final checkpoint 'short' = P samples; no checkpoint selection). Reads //run_config.json and reproduces the training geometry (linedet.data.SPECS['A1'] height and subsampling; the 32 px pooling via linedet.predict.build_arm_for_inference), checks it on dummy inputs, then runs linedet.predict.main() unchanged: --arm A1 --ckpt short --ckpt_dir --arm_label --only kohtd_val,synth_hand_val,synth_typed_val --pred_dir --logit_dir . Validation only: --test_pass is refused; every requested set must be unlocked with split val in evalsets.json and every manifest row must have split val. V1 is taken by id from the kohtd_val predictions by rq2_metrics.py. Exits 0 at once when //short/meta.json already exists for the same checkpoint (resubmitted jobs). """ import argparse import json import os import sys CODE = "/path/to/TURKIC_OCR_CODE" DATA = "/path/to/TURKIC_OCR_DATA" SETS = "kohtd_val,synth_hand_val,synth_typed_val" def geometry_selfcheck(arm, H, device): """Logit length of the loaded network for widths 101-104 and 1000-1003 equals rq2.geom.expected_frames.""" import torch from rq2.geom import expected_frames res = [] for W in (101, 102, 103, 104, 1000, 1001, 1002, 1003): x = torch.zeros(1, 3, H, W) lp, ol = arm.infer(x, torch.LongTensor([W]), device) res.append({"W": W, "T": int(lp.shape[1]), "out_len": int(ol[0]), "expected": expected_frames(W, H)}) ok = all(r["T"] == r["expected"] and r["out_len"] == r["expected"] for r in res) return ok, res def main(): if any(x.startswith("--test_pass") or x.startswith("--gate_file") for x in sys.argv[1:]): print("REFUSED: RQ2 predicts validation sets only (--test_pass is not allowed)") sys.exit(3) ap = argparse.ArgumentParser() ap.add_argument("--run", required=True) ap.add_argument("--ckpt", default="short") ap.add_argument("--ckpt_root", default=DATA + "/checkpoints/rq2") ap.add_argument("--pred_root", default=DATA + "/outputs/rq2/preds") ap.add_argument("--logit_root", default=DATA + "/outputs/rq2/topk") ap.add_argument("--only", default=SETS) ap.add_argument("--limit", type=int, default=0, help="smoke only") ap.add_argument("--bs", type=int, default=32) ap.add_argument("--workers", type=int, default=3) ap.add_argument("--device", default="cuda") ap.add_argument("--force", action="store_true") a = ap.parse_args() run_dir = os.path.join(a.ckpt_root, a.run) cfg = json.load(open(os.path.join(run_dir, "run_config.json"))) out_dir = os.path.join(a.pred_root, a.run, a.ckpt) meta_p = os.path.join(out_dir, "meta.json") ck_p = os.path.join(run_dir, "A1", a.ckpt + ".pt") if not a.force and os.path.exists(meta_p): m = json.load(open(meta_p)) want = [s for s in a.only.split(",") if s] if all(s in m.get("per_set", {}) and "cer" in m["per_set"][s] for s in want) and os.path.getmtime(meta_p) >= os.path.getmtime(ck_p): print("already predicted: %s (use --force to redo)" % meta_p) return from rq2 import geom geom.check_pinned(include_data=False) import torch import linedet.data as D import linedet.predict as P from linedet.common import load_json, read_manifest # validation-only guard ev = load_json(DATA + "/data/processed/r5/evalsets.json") sets = {s["name"]: s for s in (ev["sets"] if isinstance(ev, dict) and "sets" in ev else ev)} for name in [s for s in a.only.split(",") if s]: s = sets[name] if s.get("locked") or s.get("split") not in ("val", "validation"): raise SystemExit("REFUSED: %s is locked or not a validation set" % name) rows = [r for r in read_manifest(s["manifest"]) if r.get("unit") != "page"] bad = [r for r in rows if r.get("split") not in ("val", "validation")] if bad: raise SystemExit("REFUSED: %d rows of %s are not split val" % (len(bad), name)) H = int(cfg["height"]) spec = geom.apply_spec(H) assert spec.subsampling == cfg["subsampling"], (spec.subsampling, cfg["subsampling"]) ck = torch.load(ck_p, map_location="cpu", weights_only=False) if int(ck.get("height", -1)) != H: raise SystemExit("REFUSED: checkpoint height %s != run_config height %s" % (ck.get("height"), H)) _orig = P.build_arm_for_inference def build_for_inference_rq2(name, codec): arm = _orig(name, codec) geom.patch_pooling(arm, H) return arm P.build_arm_for_inference = build_for_inference_rq2 # geometry self-check on the real checkpoint (CPU, before the prediction run) from kraken.lib.codec import PytorchCodec arm = build_for_inference_rq2("A1", PytorchCodec(ck["codec_c2l"])) arm.load_inference_state(ck["state"]) arm.eval() ok, res = geometry_selfcheck(arm, H, torch.device("cpu")) os.makedirs(out_dir, exist_ok=True) with open(os.path.join(out_dir, "rq2_geometry_check.json"), "w") as f: json.dump({"run": a.run, "height": H, "subsampling": spec.subsampling, "pooling": arm.rq2_pooling, "ok": ok, "widths": res, "spec": vars(spec)}, f, indent=1) if not ok: raise SystemExit("REFUSED: logit lengths do not match the training geometry: %s" % res) del arm argv = ["predict", "--arm", "A1", "--ckpt", a.ckpt, "--ckpt_dir", run_dir, "--arm_label", a.run, "--only", a.only, "--pred_dir", a.pred_root, "--logit_dir", a.logit_root, "--bs", str(a.bs), "--workers", str(a.workers), "--device", a.device] if a.limit: argv += ["--limit", str(a.limit)] sys.argv = argv P.main() m = json.load(open(meta_p)) m["rq2"] = {"run_config": cfg, "geometry_check_ok": ok, "scope": cfg.get("scope")} tmp = meta_p + ".tmp" with open(tmp, "w") as f: json.dump(m, f, indent=1, ensure_ascii=False) os.replace(tmp, meta_p) if __name__ == "__main__": main()