"""Train one line-recognizer arm on mix_v1: phase 1 to P_short samples (checkpoint "short"), phase 2 on to P_long (checkpoint "long"). One process per arm. Resumable: resume.pt is rewritten every 20 minutes and at each phase end; the sample stream is a function of (seed, sample count), so a restart continues on the same batches. Usage: python -m linedet.train_arm --arm A1 --mix [--p_short 150000 --p_long 2000000] """ import argparse import json import math import os import sys import time import torch from torch.utils.data import DataLoader from . import data as D from .common import CODE, DATA, LD_CKPT, LD_OUT, load_json, save_json, utcnow from .models import build_arm, cosine_factor, layer_report, n_params # stated defaults (written to the run log before the run); see the report for their sources RECIPE = { "A1": dict(bs=32, lr=5e-4, min_lr=1e-6, opt="kraken AdamW+Muon (wd 0.01, momentum 0.95) + NRTR guide loss", source="kraken 7.2 configs/ppocr.py: lrate 5e-4 for medium, batch size 32 (kraken default 64; chosen on the smoke runs), cosine to 1e-6"), "A2": dict(bs=32, lr=5e-4, min_lr=1e-6, opt="kraken AdamW+Muon (wd 0.01, momentum 0.95) + NRTR guide loss", source="kraken 7.2 configs/ppocr.py: lrate 5e-4 for small, batch size 32 (kraken default 64; chosen on the smoke runs), cosine to 1e-6"), "A1s": dict(bs=32, lr=5e-4, min_lr=1e-6, opt="kraken AdamW+Muon (wd 0.01, momentum 0.95) + NRTR guide loss", source="same recipe as A1 (control)"), "A3": dict(bs=32, lr=1e-3, min_lr=1e-6, opt="AdamW wd 0.01, grad clip 5", source="own default (stated before the run)"), "A4": dict(bs=128, lr=1e-3, min_lr=1e-7, opt="SAM(rho 0.05)+AdamW(betas 0.9/0.99, wd 0.5), EMA 0.9999, span mask 0.4/8", source="HTR-VT paper section 4 'Implementation details' and run/lam.sh"), } WARMUP_FRACTION = 0.03 # amendment 3.2 C1 uses 3 % warm-up for the VLM arms; the same value is used here # columns (samples x padded width in pixels) allowed in one micro-batch; a larger batch is split and its gradients accumulated. # A4 images have a fixed width, so a fixed number of chunks is used instead. MICRO_COLUMNS = {"A1": 16000, "A1s": 16000, "A2": 24000, "A3": 40000, "A4": None} FIXED_CHUNKS = {"A4": 2} def split_batch(batch, k): """Split a collated batch into k micro-batches, longest images first, each trimmed to its own maximum width.""" import numpy as np B = len(batch["gid"]) if k <= 1: return [batch] order = np.argsort(-batch["seq_lens"].numpy(), kind="stable") tl = batch["target_lens"] offs = np.concatenate([[0], np.cumsum(tl.numpy())]) chunks = [] for ix in np.array_split(order, k): if len(ix) == 0: continue sl = batch["seq_lens"][ix] W = int(sl.max()) tg = torch.cat([batch["target"][offs[i]:offs[i + 1]] for i in ix]) if int(tl[ix].sum()) else batch["target"][:0] chunks.append({"image": batch["image"][ix][..., :W].contiguous(), "seq_lens": sl, "target": tg, "target_lens": tl[ix], "gid": [batch["gid"][i] for i in ix], "text": [batch["text"][i] for i in ix]}) return chunks STOP = {"flag": False} def _on_term(signum, frame): STOP["flag"] = True class _BS: def __init__(self, stream, start): self.stream, self.start = stream, start def __iter__(self): return self.stream.batches(self.start) def save_atomic(obj, path): os.makedirs(os.path.dirname(path), exist_ok=True) tmp = path + ".tmp" torch.save(obj, tmp) os.replace(tmp, path) def main(): ap = argparse.ArgumentParser() ap.add_argument("--arm", required=True) ap.add_argument("--mix", required=True) ap.add_argument("--codec", default=LD_OUT + "/codec_union.json") ap.add_argument("--p_short", type=int, default=150000) ap.add_argument("--p_long", type=int, default=2000000) ap.add_argument("--seed", type=int, default=20261121) ap.add_argument("--workers", type=int, default=5) ap.add_argument("--ckpt_dir", default=LD_CKPT) ap.add_argument("--log_dir", default=LD_OUT + "/train_logs") ap.add_argument("--max_seconds", type=float, default=0, help="stop gracefully after this many seconds of this process") ap.add_argument("--ckpt_minutes", type=float, default=20) ap.add_argument("--device", default="cuda") ap.add_argument("--tag", default="") ap.add_argument("--log_every", type=int, default=50) ap.add_argument("--no_amp", action="store_true", help="fp32 instead of bf16 autocast") ap.add_argument("--lr", type=float, default=0, help="peak learning rate instead of the recipe's (diagnostic variants only)") ap.add_argument("--a4_no_output_ln", action="store_true", help="A4 variant: no parameter-free layer norm of the logits") ap.add_argument("--a4_stretch", action="store_true", help="A4 variant: crops stretched to fill the fixed width") ap.add_argument("--resume_from", default="", help="extension run (amendment 3.4 E5): start from this resume.pt (model, optimizer, step, samples seen) but write to --ckpt_dir") ap.add_argument("--extend_to", type=int, default=0, help="extension run: total number of samples to train to (the sample stream continues where resume_from stopped)") ap.add_argument("--ext_peak_lr", type=float, default=0, help="extension run: peak learning rate of the warm restart") ap.add_argument("--ext_min_lr", type=float, default=1e-6) ap.add_argument("--ext_warmup", type=float, default=0.03, help="share of the extension's progress used for linear warm-up") ap.add_argument("--a4_opts_file", default="", help="JSON with keys no_output_ln, stretch, lr, no_amp (the chosen A4b variant)") ap.add_argument("--stop_after_phase1", action="store_true", help="save the short checkpoint and resume.pt, then stop (phase 2 is a second process)") ap.add_argument("--p_long_file", default="", help="JSON with key p_long_final (written by plan_long) that replaces --p_long") a = ap.parse_args() import signal from . import models as _models if a.no_amp: _models.AMP["on"] = False signal.signal(signal.SIGTERM, _on_term) t_proc0 = time.time() if a.p_long_file: a.p_long = int(load_json(a.p_long_file)["p_long_final"]) if a.a4_opts_file: o = load_json(a.a4_opts_file) a.a4_no_output_ln = a.a4_no_output_ln or bool(o.get("no_output_ln")) a.a4_stretch = a.a4_stretch or bool(o.get("stretch")) a.no_amp = a.no_amp or bool(o.get("no_amp")) a.lr = a.lr or float(o.get("lr", 0)) if a.no_amp: _models.AMP["on"] = False if a.a4_no_output_ln: _models.A4_OPTS["output_ln"] = False if a.a4_stretch: D.SPECS["A4"].stretch = True arm_name = a.arm rec = dict(RECIPE[arm_name]) if a.lr: rec["lr"] = a.lr rec["source"] = rec["source"] + " | peak lr overridden to %g (diagnostic variant)" % a.lr spec = D.SPECS[arm_name] dev = torch.device(a.device) torch.manual_seed(a.seed + sum(map(ord, arm_name))) ckdir = os.path.join(a.ckpt_dir, arm_name + a.tag) os.makedirs(ckdir, exist_ok=True) os.makedirs(a.log_dir, exist_ok=True) logp = os.path.join(a.log_dir, arm_name + a.tag + ".jsonl") def log(**kw): kw["t"] = utcnow() with open(logp, "a") as f: f.write(json.dumps(kw, ensure_ascii=False) + "\n") print(json.dumps(kw, ensure_ascii=False), flush=True) from kraken.lib.codec import PytorchCodec codec_file = load_json(a.codec) codec = PytorchCodec({k: v for k, v in codec_file["c2l"].items()}) arm = build_arm(arm_name, codec, DATA).to(dev) arm.train() opt = arm.make_optimizer(rec["lr"]) comps = D.load_components(D.load_mix(a.mix), "train") stream = D.MixStream(comps, rec["bs"], a.seed) flat = D.FlatItems(comps) ds = D.LineDS(flat, spec, codec, train=True, seed=a.seed) steps1 = -(-a.p_short // rec["bs"]) # ceil: samples seen at "short" is at least P_short steps2 = -(-a.p_long // rec["bs"]) - steps1 wu1 = max(1, int(WARMUP_FRACTION * steps1)) wu2 = max(1, int(WARMUP_FRACTION * steps2)) minr = rec["min_lr"] / rec["lr"] step = 0 seen = 0 wall_train = 0.0 resume = os.path.join(ckdir, "resume.pt") if a.extend_to and not os.path.exists(resume): if not (a.resume_from and os.path.exists(a.resume_from)): raise SystemExit("extension run needs --resume_from ") src_resume = a.resume_from else: src_resume = resume if os.path.exists(src_resume): ck = torch.load(src_resume, map_location="cpu", weights_only=False) arm.load_state(ck["state"], with_opt=True) step, seen, wall_train = ck["step"], ck["seen"], ck["wall_train"] log(event="resumed", step=step, samples_seen=seen) log(event="start", arm=arm_name, recipe=rec, bs=rec["bs"], p_short=a.p_short, p_long=a.p_long, steps_phase1=steps1, steps_phase2=steps2, warmup_phase1=wu1, warmup_phase2=wu2, codec_size=codec.max_label, comps=[(c["name"], round(c["share"], 4), len(c["items"])) for c in comps], params_deployed=n_params(arm.net), groups=arm.group_report, mix=a.mix, spec=vars(spec), seed=a.seed) # learning-curve checkpoints at 25, 50 and 75 % of P_short (the 100 % point is the short checkpoint) curve_steps = {-(-int(f * a.p_short) // rec["bs"]) for f in (0.25, 0.5, 0.75)} def lr_at(s): if s < steps1: return rec["lr"] * cosine_factor(s, steps1, wu1, minr) return rec["lr"] * cosine_factor(s - steps1, steps2, wu2, minr) def save_resume(): save_atomic({"state": arm.state(), "step": step, "seen": seen, "wall_train": wall_train, "arm": arm_name, "codec_c2l": codec.c2l}, resume) def save_final(tag): if device_is_cuda: peak = torch.cuda.max_memory_allocated() / 2 ** 30 peak_res = torch.cuda.max_memory_reserved() / 2 ** 30 else: peak = peak_res = None save_atomic({"arm": arm_name, "ckpt": tag, "state": arm.inference_state(), "codec_c2l": codec.c2l, "samples_seen": seen, "steps": step, "lr_peak": (a.ext_peak_lr if a.extend_to else rec["lr"]), "wall_train_seconds": wall_train, "peak_gpu_gib_training": peak, "peak_gpu_gib_training_reserved": peak_res, "recipe": rec, "height": spec.height, "created": utcnow(), "opts": {"a4_output_ln": not a.a4_no_output_ln, "a4_stretch": bool(a.a4_stretch), "no_amp": bool(a.no_amp)}}, os.path.join(ckdir, tag + ".pt")) log(event="saved", ckpt=tag, samples_seen=seen, step=step, wall_train_seconds=wall_train, peak_gpu_gib_training=peak, peak_gpu_gib_training_reserved=peak_res) device_is_cuda = dev.type == "cuda" if not a.extend_to and seen >= a.p_long: log(event="already_done") return if a.extend_to and seen >= a.extend_to: log(event="already_done_extension", samples_seen=seen) return loader = DataLoader(ds, batch_sampler=_BS(stream, seen), num_workers=a.workers, collate_fn=D.collate, pin_memory=device_is_cuda, prefetch_factor=4 if a.workers else None, persistent_workers=False) last_ck = time.time() t_win = time.time() n_win = 0 bad = 0 n_oom = 0 budget = {"cols": int(os.environ.get("LINEDET_MICRO_COLUMNS", 0)) or MICRO_COLUMNS[arm_name] or 10 ** 9} t_step0 = time.time() ext = {"t0": None} def ext_lr(p): """warm restart with a time-aware cosine: progress p = max(share of the extension's samples done, share of the time budget used); linear warm-up over the first ext_warmup of p, then cosine from ext_peak_lr down to ext_min_lr at p = 1, so the checkpoint is annealed whichever limit comes first""" w = a.ext_warmup minr_e = a.ext_min_lr / a.ext_peak_lr if p < w: return a.ext_peak_lr * max(p / w, 1e-3) return a.ext_peak_lr * (minr_e + (1 - minr_e) * 0.5 * (1 + math.cos(math.pi * (p - w) / (1 - w)))) for batch in loader: if a.extend_to: if ext["t0"] is None: ext["t0"], ext["seen0"] = time.time(), seen ext["budget_s"] = max(60.0, a.max_seconds - (ext["t0"] - t_proc0) - 30.0) log(event="extension_plan", seen0=seen, extend_to=a.extend_to, ext_peak_lr=a.ext_peak_lr, ext_min_lr=a.ext_min_lr, ext_warmup=a.ext_warmup, time_budget_s=ext["budget_s"], resumed_from=src_resume) p_ext = max((seen - ext["seen0"]) / float(a.extend_to - ext["seen0"]), (time.time() - ext["t0"]) / ext["budget_s"]) if p_ext >= 1.0: save_final("long2x") save_resume() log(event="extension_done", samples_seen=seen, step=step, reached_target=(seen >= a.extend_to), wall_train_seconds=wall_train) break lr = ext_lr(p_ext) else: lr = lr_at(step) B_now = len(batch["gid"]) cols = B_now * int(batch["seq_lens"].max()) k = FIXED_CHUNKS.get(arm_name) or max(1, -(-cols // budget["cols"])) while True: try: info = arm.train_chunks(split_batch(batch, min(k, B_now)), B_now, dev, lr) break except torch.OutOfMemoryError: arm.clear_grads() torch.cuda.empty_cache() n_oom += 1 log(event="oom_retry", step=step, columns=cols, chunks_before=k) if k >= B_now: raise k = min(k * 2, B_now) if budget["cols"]: budget["cols"] = max(2000, min(budget["cols"], cols // k)) # later batches use the smaller micro-batch arm.after_step(step) step += 1 bs_now = len(batch["gid"]) seen += bs_now n_win += bs_now if not math.isfinite(info["loss"]): bad += 1 if bad > 200: raise RuntimeError("loss not finite for 200 steps") else: bad = 0 now = time.time() wall_train += now - t_step0 t_step0 = now if step % a.log_every == 0: log(event="step", step=step, samples_seen=seen, lr=lr, samples_per_s=n_win / (now - t_win), **info, gpu_gib=(torch.cuda.max_memory_allocated() / 2 ** 30 if device_is_cuda else None), gpu_gib_reserved=(torch.cuda.max_memory_reserved() / 2 ** 30 if device_is_cuda else None)) t_win, n_win = now, 0 if step in curve_steps and step < steps1: tag = "curve_%d" % seen if not os.path.exists(os.path.join(ckdir, tag + ".pt")): try: save_final(tag) # learning-curve point inside phase 1 (the learning rate is still high there); never overwritten except Exception as e: # a failed side file must not stop the training log(event="curve_save_failed", tag=tag, error=str(e)[:200]) t_step0 = time.time() if step == steps1 and not os.path.exists(os.path.join(ckdir, "short.pt")): save_final("short") save_resume() if a.stop_after_phase1: log(event="phase1_done", step=step, samples_seen=seen, wall_train_seconds=wall_train) break last_ck = time.time() # restart the iteration clock so saving does not count as training time t_step0 = time.time() if not a.extend_to and step >= steps1 + steps2: save_final("long") save_resume() break if time.time() - last_ck > a.ckpt_minutes * 60: save_resume() last_ck = time.time() t_step0 = time.time() if STOP["flag"] or (a.max_seconds and not a.extend_to and time.time() - t_proc0 > a.max_seconds): save_resume() save_final("partial") # inference weights at the stop point; the samples seen are in the file log(event="stopped_for_time", step=step, samples_seen=seen) break log(event="end", step=step, samples_seen=seen, wall_train_seconds=wall_train) if __name__ == "__main__": main()