File size: 7,412 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 | """Train one RQ2 run: PP-OCRv6-medium (arm A1 of linedet) from the released weights at line height 32 or 64 px with the
typical (TrOCR) or the diacritic-safe augmentation policy, budget P samples (records/R5/RQ2/design.json).
linedet.train_arm.main() is run unchanged; this wrapper only replaces, in train_arm's and linedet.data's own namespaces:
linedet.data.SPECS['A1'] = ArmSpec('A1', H, 3, 4 if H == 32 else 8, 2560); env LINEDET_MICRO_COLUMNS 12000 / 24000
linedet.data.LineDS -> rq2.dataset.RQ2LineDS (the design's image path and seeded fallback; no kraken augmenter)
train_arm._BS -> rq2.dataset.OrdinalBS ((gid, sample ordinal) pairs)
train_arm.build_arm -> build_arm + 32 px pooling (rq2.geom.patch_pooling) + run hooks (counters, RNG in resume.pt)
Then: train_arm --arm A1 --mix mix_v1.yaml --p_short P --p_long P --stop_after_phase1 --seed S --workers W
--ckpt_dir CKPT_ROOT/<run> --log_dir LOG_ROOT/<run> [--max_seconds T]
Budget: P = 300,032 samples = 9,376 steps of 32 (design 'budget_and_cost'; --p_short 300000 would give 9,375 steps = 300,000).
Usage: .venv_kraken/bin/python -I rq2_train.py --height 32 --policy typical --seed 20261121 --run rq2_h32_typ_s1
"""
import argparse
import datetime
import functools
import json
import os
import sys
CODE = "/path/to/TURKIC_OCR_CODE"
DATA = "/path/to/TURKIC_OCR_DATA"
NEW_FILES = ["src/rq2/__init__.py", "src/rq2/aug.py", "src/rq2/geom.py", "src/rq2/dataset.py", "src/rq2/marks.py",
"scripts/r5_rq2/rq2_train.py"]
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--height", type=int, required=True, choices=[32, 64])
ap.add_argument("--policy", required=True, choices=["typical", "safe"])
ap.add_argument("--seed", type=int, required=True)
ap.add_argument("--run", required=True)
ap.add_argument("--budget", type=int, default=300032, help="P in samples (p_short = p_long = P)")
ap.add_argument("--max_seconds", type=float, default=0)
ap.add_argument("--workers", type=int, default=3)
ap.add_argument("--device", default="cuda")
ap.add_argument("--mix", default=DATA + "/data/processed/r5/mix_v1.yaml")
ap.add_argument("--codec", default=DATA + "/outputs/r5/linedet/codec_union.json")
ap.add_argument("--ckpt_root", default=DATA + "/checkpoints/rq2")
ap.add_argument("--log_root", default=DATA + "/outputs/rq2/train_logs")
ap.add_argument("--log_every", type=int, default=50)
ap.add_argument("--smoke_items", type=int, default=0, help="smoke only: keep the first N items of every mix component")
ap.add_argument("--stop_at_step", type=int, default=0, help="smoke only: stop (save resume.pt) after this many optimizer steps in total")
ap.add_argument("--trace", default="", help="smoke only: append one JSON line per step (sample ids, ordinals, slots, loss)")
a = ap.parse_args()
if a.smoke_items == 0 and (a.stop_at_step or a.trace):
raise SystemExit("REFUSED: --stop_at_step and --trace are smoke-test options (need --smoke_items)")
from rq2 import DESIGN_SHA256, SCOPE_NOTE
from rq2 import geom
pinned = geom.check_pinned(include_data=True)
if os.path.abspath(a.mix) != DATA + "/data/processed/r5/mix_v1.yaml" or os.path.abspath(a.codec) != DATA + "/outputs/r5/linedet/codec_union.json":
raise SystemExit("REFUSED: RQ2 uses mix_v1.yaml and codec_union.json only")
import linedet.data as D
import linedet.train_arm as TA
from rq2.dataset import OrdinalBS, RQ2LineDS, RunHooks
spec = geom.apply_spec(a.height)
run_dir = os.path.join(a.ckpt_root, a.run)
ck_dir = os.path.join(run_dir, "A1")
os.makedirs(ck_dir, exist_ok=True)
# the dataset of the design (step 1-5), the ordinal sampler
D.LineDS = functools.partial(RQ2LineDS, policy=a.policy, height=a.height)
TA._BS = OrdinalBS
_orig_lc = D.load_components
cache = {}
def load_components_rq2(mix_comps, use_split="train"):
"""linedet.data.load_components, read once per process (the wrapper needs the components for its counters before
train_arm reads them); smoke runs keep the first N items of every component."""
if use_split not in cache:
comps = _orig_lc(mix_comps, use_split)
if a.smoke_items:
for c in comps:
c["items"] = c["items"][:a.smoke_items]
cache[use_split] = comps
return cache[use_split]
D.load_components = load_components_rq2
state = {}
_orig_build = TA.build_arm
def build_arm_rq2(name, codec, data_dir):
arm = _orig_build(name, codec, data_dir)
geom.patch_pooling(arm, a.height)
# component of every flat item, for the counters (same flattening as FlatItems)
comps = state["comps"]
import numpy as np
comp_of = np.concatenate([[i] * len(c["items"]) for i, c in enumerate(comps)])
RunHooks(comp_of, [c["name"] for c in comps], ck_dir, trace_path=a.trace, stop_at_step=a.stop_at_step,
stop_flag=TA.STOP).install(arm)
return arm
# the components are loaded by train_arm after build_arm; load them once here with the same call for the counters
comps_for_ids = D.load_components(D.load_mix(a.mix), "train")
state["comps"] = comps_for_ids
TA.build_arm = build_arm_rq2
cfg = {"run": a.run, "height": a.height, "policy": a.policy, "seed": a.seed, "budget_samples": a.budget,
"steps": -(-a.budget // 32), "subsampling": spec.subsampling, "max_width": spec.max_width,
"micro_columns": int(os.environ["LINEDET_MICRO_COLUMNS"]),
"pooling": "avg_pool2d(kernel=(h, 1))" if a.height == 32 else "avg_pool2d(kernel=(h, 2))",
"torch_seed": a.seed + sum(map(ord, "A1")), "workers": a.workers, "device": a.device,
"smoke_items": a.smoke_items, "stop_at_step": a.stop_at_step, "design_sha256": DESIGN_SHA256, "scope": SCOPE_NOTE,
"pinned_sha256": pinned,
"new_files_sha256": {f: geom.sha256_file(os.path.join(CODE, f)) for f in NEW_FILES},
"written_utc": datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
"components": [(c["name"], round(c["share"], 6), len(c["items"])) for c in comps_for_ids]}
p = os.path.join(run_dir, "run_config.json")
if os.path.exists(p):
old = json.load(open(p))
for k in ("height", "policy", "seed", "budget_samples", "subsampling", "smoke_items"):
if old.get(k) != cfg[k]:
raise SystemExit("REFUSED: run_config.json of %s has %s=%r, now %r" % (a.run, k, old.get(k), cfg[k]))
cfg["first_written_utc"] = old.get("first_written_utc", old.get("written_utc"))
else:
cfg["first_written_utc"] = cfg["written_utc"]
tmp = p + ".tmp"
with open(tmp, "w") as f:
json.dump(cfg, f, indent=1)
os.replace(tmp, p)
argv = ["train_arm", "--arm", "A1", "--mix", a.mix, "--codec", a.codec, "--p_short", str(a.budget), "--p_long", str(a.budget),
"--stop_after_phase1", "--seed", str(a.seed), "--workers", str(a.workers), "--ckpt_dir", run_dir,
"--log_dir", os.path.join(a.log_root, a.run), "--device", a.device, "--log_every", str(a.log_every)]
if a.max_seconds:
argv += ["--max_seconds", str(a.max_seconds)]
sys.argv = argv
TA.main()
if __name__ == "__main__":
main()
|