"""RQ2 pre-check (design 'rq2_precheck'), CPU only, no model: 1. CTC frames per component and height over the WHOLE training mix (train split) and the validation sets: clean geometry width' = max(int(w * H / h), 1) + 32 (linedet padding), frames = width' // subsampling (32 px: 4, 64 px: 8; also 8 at 32 px for reference); need = len(codec label) + adjacent repeats (linedet.data.frames_needed); also the share wider than 2,560 px. Image headers only (PIL size). 2. Batch identity: sha256 of the first 300 batches of (gid, sample ordinal) of the sampler each arm builds (OrdinalBS over MixStream(seed)) for the four arms of each seed; they must be equal within a seed. Also the slot sequence of those ordinals (default_rng([seed, 4242, ordinal])) and its histogram. Writes DATA/outputs/rq2/precheck.json (aggregates only). """ import argparse import datetime import hashlib import json import os import sys import unicodedata from multiprocessing import Pool import numpy as np CODE = "/path/to/TURKIC_OCR_CODE" DATA = "/path/to/TURKIC_OCR_DATA" MIX = DATA + "/data/processed/r5/mix_v1.yaml" CODEC = DATA + "/outputs/r5/linedet/codec_union.json" VAL = {"kohtd_val": DATA + "/data/processed/r5/manifests/kohtd_val.tsv", "synth_hand_val": DATA + "/data/processed/r5/frozen_eval_v1/synth_hand_val.tsv", "synth_typed_val": DATA + "/data/processed/r5/frozen_eval_v1/synth_typed_val.tsv"} SEEDS = [20261121, 20261122, 20261123] ARMS = [(32, "typical"), (32, "safe"), (64, "typical"), (64, "safe")] def _size(path): from PIL import Image try: with Image.open(path) as im: return im.size except Exception: return (0, 0) def frames_table(paths, needs, sizes): W = np.array([s[0] for s in sizes], float) Hn = np.array([s[1] for s in sizes], float) need = np.asarray(needs, float) ok = Hn > 0 out = {"items": int(len(paths)), "unreadable": int((~ok).sum())} for H, sub in ((32, 4), (32, 8), (64, 8)): wp = np.maximum((W[ok] * H / Hn[ok]).astype(int), 1) + 32 fr = wp // sub nd = need[ok] out["H%d_sub%d" % (H, sub)] = {"share_ctc_infeasible": float((nd > fr).mean()), "share_too_wide": float((wp > 2560).mean()), "median_frames_per_char": float(np.median(fr[nd > 0] / nd[nd > 0])) if (nd > 0).any() else None, "share_frames_below_1p5x_need": float((fr < 1.5 * nd).mean())} return out def main(): ap = argparse.ArgumentParser() ap.add_argument("--out", default=DATA + "/outputs/rq2/precheck.json") ap.add_argument("--batches", type=int, default=300) ap.add_argument("--procs", type=int, default=int(os.environ.get("SLURM_CPUS_PER_TASK", "8"))) ap.add_argument("--skip_frames", action="store_true") a = ap.parse_args() from kraken.lib.codec import PytorchCodec import linedet.data as D from linedet.common import load_json, read_manifest, to_train_text from rq2 import geom from rq2.aug import slot_rng, draw_slot, N_SLOTS from rq2.dataset import batches_digest pinned = geom.check_pinned(include_data=True) t0 = datetime.datetime.now(datetime.timezone.utc) doc = {"written_utc": t0.strftime("%Y-%m-%dT%H:%M:%SZ"), "pinned_sha256": pinned} comps = D.load_components(D.load_mix(MIX), "train") codec = PytorchCodec(load_json(CODEC)["c2l"]) # 2. batch identity (first, cheap) bi = {} for seed in SEEDS: per_arm = {} slots_ref = None for H, pol in ARMS: geom.apply_spec(H) # the arm's geometry is set, as in rq2_train.py; the sampler does not read it stream = D.MixStream(comps, 32, seed) dig, pairs = batches_digest(stream, a.batches) slots = [draw_slot(slot_rng(seed, o))[0] for _, o in pairs] sd = hashlib.sha256(json.dumps(slots).encode()).hexdigest() per_arm["h%d_%s" % (H, pol)] = {"batches_sha256": dig, "slots_sha256": sd} slots_ref = slots hist = np.bincount(np.asarray(slots_ref), minlength=N_SLOTS) bi[str(seed)] = {"per_arm": per_arm, "equal_across_arms": len({v["batches_sha256"] for v in per_arm.values()}) == 1 and len({v["slots_sha256"] for v in per_arm.values()}) == 1, "slot_histogram_first_batches": hist.tolist(), "samples": int(hist.sum())} doc["batch_identity"] = bi doc["batch_identity_note"] = "sampler output (requested gids and ordinals); the image-path fallback (design step 5) can replace a sample differently per arm, counted in each run's rq2_counters.json" seeds_differ = len({bi[str(s)]["per_arm"]["h32_typical"]["batches_sha256"] for s in SEEDS}) == len(SEEDS) doc["seeds_give_different_batches"] = seeds_differ # 1. frames over the whole mix and the validation sets if not a.skip_frames: jobs = [] enc_fail = {} def need_of(t, name): try: return D.frames_needed(codec.encode(t)) except Exception: enc_fail[name] = enc_fail.get(name, 0) + 1 return len(t) for c in comps: jobs.append((c["name"], [it[0] for it in c["items"]], [need_of(it[1], c["name"]) for it in c["items"]])) doc["codec_encode_failures"] = enc_fail for name, man in VAL.items(): rows = [r for r in read_manifest(man) if r.get("unit") != "page" and r.get("split") in ("val", "validation")] needs = [] for r in rows: t = to_train_text(r["text"]) try: needs.append(D.frames_needed(codec.encode(t))) except Exception: needs.append(len(t)) jobs.append(("VAL:" + name, [r["image"] for r in rows], needs)) allpaths = [p for _, ps, _ in jobs for p in ps] with Pool(a.procs) as pool: sizes = pool.map(_size, allpaths, chunksize=512) k = 0 ft = {} for name, ps, needs in jobs: ft[name] = frames_table(ps, needs, sizes[k:k + len(ps)]) k += len(ps) # pooled over the training mix, weighted by the mix shares tot = {} for H, sub in ((32, 4), (32, 8), (64, 8)): key = "H%d_sub%d" % (H, sub) tot[key] = {"share_ctc_infeasible_weighted_by_mix_share": float(sum(c["share"] * ft[c["name"]][key]["share_ctc_infeasible"] for c in comps)), "share_too_wide_weighted_by_mix_share": float(sum(c["share"] * ft[c["name"]][key]["share_too_wide"] for c in comps))} doc["frames"] = {"per_component": ft, "mix_weighted": tot, "items_total": len(allpaths)} doc["seconds"] = (datetime.datetime.now(datetime.timezone.utc) - t0).total_seconds() os.makedirs(os.path.dirname(a.out), exist_ok=True) with open(a.out, "w") as f: json.dump(doc, f, indent=1) print("wrote", a.out, "batch identity equal:", all(v["equal_across_arms"] for v in bi.values()), "seeds differ:", seeds_differ) if __name__ == "__main__": main()