File size: 31,365 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
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
"""R5 VLMA: one generic full fine-tune for every natively loadable document VLM (amendment 3.2 C1).

- Native transformers class, trust_remote_code never set, safetensors only, offline, no token.
- Precision ("bf16" of C1): model weights and compute in bf16; the optimizer keeps an fp32 master copy of every weight
  and fp32 AdamW moments (standard mixed precision; pure-bf16 AdamW updates at lr 1e-5 would round to zero).
  Gradients of each micro-batch are added into fp32 master gradients.
- All weights train (requires_grad on every parameter). Gradient checkpointing on (non-reentrant).
- AdamW (betas 0.9/0.999, eps 1e-8, weight decay 0), cosine schedule to 0 with 3% linear warm-up over the planned
  steps, gradient-norm clip 1.0, effective batch 32 = micro-batch x accumulation (micro-batch halves on CUDA OOM;
  the effective batch never changes). Loss = summed token cross-entropy over target tokens / target tokens of the
  effective batch.
- Data: rows [start_row, start_row + n_samples) of one sequence file (identical for every arm); step k uses rows
  start_row + 32k ... + 32k + 31. Resume restores weights, optimizer, scheduler, step, samples and training seconds.
- Time cap counts training-loop seconds only (not loading, checkpoint saving or export). Checkpoint every
  --save-every-min minutes of wall time, atomically (write <dir>.tmp, then rename), keeping only the latest.
- SIGTERM/SIGINT or the absolute UTC deadline: finish the step, save, export, exit 0 with a flag.

usage: train_vlm.py --short S --registry R --models-dir M --seq SEQ.tsv --ckpt-root C --out-root O [options]
"""
import argparse
import json
import math
import os
import signal
import sys
import time
from datetime import datetime, timezone

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import vlm_common as vc  # noqa: E402
import postproc as pp  # noqa: E402

import torch  # noqa: E402
import transformers  # noqa: E402
from PIL import Image  # noqa: E402

ap = argparse.ArgumentParser()
ap.add_argument("--short", required=True)
ap.add_argument("--arm", default=None)
ap.add_argument("--registry", required=True)
ap.add_argument("--models-dir", required=True)
ap.add_argument("--seq", required=True)
ap.add_argument("--ckpt-root", required=True)
ap.add_argument("--out-root", required=True)
ap.add_argument("--phase", default="short")
ap.add_argument("--start-row", type=int, default=0)
ap.add_argument("--n-samples", type=int, default=150000)
ap.add_argument("--eff-batch", type=int, default=32)
ap.add_argument("--micro-batch", type=int, default=32)
ap.add_argument("--lr", type=float, default=None)
ap.add_argument("--warmup-frac", type=float, default=0.03)
ap.add_argument("--cap-hours", type=float, default=3.0)
ap.add_argument("--deadline-utc", default="2026-11-22T18:55:00Z")
ap.add_argument("--save-every-min", type=float, default=30.0)
ap.add_argument("--stop-after-steps", type=int, default=0, help="smoke test: save and exit after this many steps")
ap.add_argument("--init-state", default=None, help="continuation: start weights (and optimizer) from this state dir")
ap.add_argument("--init-optimizer", action="store_true", help="continuation: also load the optimizer moments")
ap.add_argument("--no-export", action="store_true")
ap.add_argument("--device", default="cuda")
ap.add_argument("--workers", type=int, default=8, help="DataLoader workers (12 until the 2026-11-21 host-memory fix)")
ap.add_argument("--threads", type=int, default=0)
ap.add_argument("--check-labels", type=int, default=3, help="decode and log the loss positions of this many rows")
ap.add_argument("--curve-manifest", default="/path/to/TURKIC_OCR_DATA/data/processed/r5/manifests/curve_v1.tsv")
ap.add_argument("--preds-root", default="/path/to/TURKIC_OCR_DATA/outputs/r5/preds")
ap.add_argument("--curve-points", default="37500,75000,112500,150000", help="learning-curve points (phase short only)")
ap.add_argument("--data-order-seed", type=int, default=20261121, help="seed of the sequence file (recorded only)")
ap.add_argument("--seed-index", type=int, default=1, help="1 = first seed of this arm, 2 = repeat run (amendment 3.3 D2)")
args = ap.parse_args()

arm = args.arm or args.short
dev = args.device
use_cuda = dev == "cuda"
if args.threads:
    torch.set_num_threads(args.threads)
elif use_cuda:
    torch.set_num_threads(4)  # the main process does little CPU math; leave the cores to the loader workers
reg = vc.read_registry(args.registry)[args.short]
lr = args.lr if args.lr is not None else float(reg["lr"])
deadline = datetime.strptime(args.deadline_utc, "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=timezone.utc).timestamp()
model_path = os.path.join(args.models_dir, args.short)
state_dir = os.path.join(args.ckpt_root, arm, args.phase + "_state")
export_dir = os.path.join(args.ckpt_root, arm, args.phase)
run_dir = os.path.join(args.out_root, arm, args.phase)
os.makedirs(run_dir, exist_ok=True)
log_path = os.path.join(run_dir, "train_log.jsonl")
run_json = os.path.join(run_dir, "run.json")
job_id = os.environ.get("SLURM_JOB_ID", "")
STOP = {"flag": False, "why": ""}


def _sig(signum, frame):  # noqa: ARG001
    STOP["flag"] = True
    STOP["why"] = "signal %d" % signum


def _sig_leaders(signum, frame):  # noqa: ARG001
    STOP["flag"] = True
    STOP["why"] = "leaders"


signal.signal(signal.SIGTERM, _sig)
signal.signal(signal.SIGINT, _sig)
signal.signal(signal.SIGUSR1, _sig_leaders)


def utc():
    return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")


def log(rec):
    rec["utc"] = utc()
    with open(log_path, "a", encoding="utf-8") as f:
        f.write(json.dumps(rec, ensure_ascii=False) + "\n")


def say(*a):
    print(f"[{arm}/{args.phase} {utc()}]", *a, flush=True)


# ---------------- sequence ----------------
def read_seq(path, start, n):
    rows = []
    with open(path, encoding="utf-8", newline="") as f:
        hdr = f.readline().rstrip("\n").split("\t")
        ix = {h: i for i, h in enumerate(hdr)}
        for k, line in enumerate(f):
            if k < start:
                continue
            if k >= start + n:
                break
            p = line.rstrip("\n").split("\t")
            rows.append({"id": p[ix["id"]], "image": p[ix["image"]], "text": p[ix["text"]], "unit": p[ix.get("unit", ix["id"])]})
    assert len(rows) == n, f"sequence has {len(rows)} rows from {start}, need {n}"
    return rows


rows = read_seq(args.seq, args.start_row, args.n_samples)
total_steps = math.ceil(args.n_samples / args.eff_batch)
warmup = round(args.warmup_frac * total_steps)

# ---------------- model, processor ----------------
t_load = time.time()
proc, tok = vc.load_processor(args.short, model_path)
tmpl_kw = vc.template_kwargs(proc, tok)
model = vc.load_model(args.short, model_path, torch.bfloat16)
suffix_ids, suffix_how, suffix_text = vc.answer_suffix(args.short, proc, tok, model.generation_config, tmpl_kw)
model.to(dev)
model.config.use_cache = False
try:
    model.gradient_checkpointing_enable(gradient_checkpointing_kwargs={"use_reentrant": False})
    gc_on = True
except Exception as e:  # noqa: BLE001
    gc_on = "failed: " + repr(e)[:200]
for p in model.parameters():
    p.requires_grad_(True)
model.train()
named = list(model.named_parameters())
names = [n for n, _ in named]
params = [p for _, p in named]
n_unique = vc.unique_params(model)
master = [torch.nn.Parameter(p.detach().float().clone(), requires_grad=True) for p in params]
opt = torch.optim.AdamW(master, lr=lr, betas=(0.9, 0.999), eps=1e-8, weight_decay=0.0, fused=use_cuda)
sched = transformers.get_cosine_schedule_with_warmup(opt, warmup, total_steps)
load_seconds = time.time() - t_load


def master_fingerprint():
    with torch.no_grad():
        return float(sum(m.double().sum().item() for m in master[:: max(1, len(master) // 16)]))


# ---------------- state ----------------
st = {"step": 0, "samples_seen": 0, "train_seconds": 0.0, "micro_batch": args.micro_batch, "saves": 0,
      "oom_events": [], "job_ids": [], "resumed_from_step": [], "fingerprint_at_save": None,
      "curve_done": [], "curve_seconds": 0.0}


def load_state(d, with_opt=True, with_counters=True):
    sd = torch.load(os.path.join(d, "master.pt"), map_location="cpu", weights_only=True)
    with torch.no_grad():
        for n, m, p in zip(names, master, params):
            m.copy_(sd[n].to(m.device))
            p.copy_(m)
    del sd
    if with_opt:
        opt.load_state_dict(torch.load(os.path.join(d, "optim.pt"), map_location=dev, weights_only=True))
    if with_counters:
        sched.load_state_dict(torch.load(os.path.join(d, "sched.pt"), weights_only=True))
        st.update(json.load(open(os.path.join(d, "state.json"))))


def save_state(d, extra=None):
    t0 = time.time()
    tmp = d + ".tmp"
    old = d + ".old"
    os.makedirs(tmp, exist_ok=True)
    # host-memory fix 2026-11-21: serialise the GPU tensors directly (torch.save copies one storage at a time) instead of
    # building a full host copy of every fp32 master weight first; load_state maps them to the CPU as before
    torch.save({n: m.detach() for n, m in zip(names, master)}, os.path.join(tmp, "master.pt"))
    torch.save(opt.state_dict(), os.path.join(tmp, "optim.pt"))
    torch.save(sched.state_dict(), os.path.join(tmp, "sched.pt"))
    st["saves"] += 1
    st["fingerprint_at_save"] = master_fingerprint()
    rec = dict(st)
    if extra:
        rec.update(extra)
    json.dump(rec, open(os.path.join(tmp, "state.json"), "w"), indent=1)
    if os.path.isdir(d):
        os.rename(d, old)
    os.rename(tmp, d)
    if os.path.isdir(old):
        import shutil
        shutil.rmtree(old, ignore_errors=True)
    return time.time() - t0


import shutil  # noqa: E402

for leftover in (state_dir + ".tmp",):
    if os.path.isdir(leftover):
        shutil.rmtree(leftover, ignore_errors=True)
if not os.path.isdir(state_dir) and os.path.isdir(state_dir + ".old"):
    os.rename(state_dir + ".old", state_dir)

resumed = False
if os.path.isdir(state_dir):
    load_state(state_dir)
    fp = master_fingerprint()
    say(f"resumed at step {st['step']} samples {st['samples_seen']} train_s {st['train_seconds']:.0f}; fingerprint "
        f"saved {st['fingerprint_at_save']!r} now {fp!r}")
    st["resumed_from_step"].append(st["step"])
    st["resume_fingerprint_match"] = (st["fingerprint_at_save"] == fp)
    resumed = True
elif args.init_state:
    load_state(args.init_state, with_opt=args.init_optimizer, with_counters=False)
    say(f"initialised from {args.init_state} (optimizer moments {'loaded' if args.init_optimizer else 'fresh'})")
if job_id and job_id not in st["job_ids"]:
    st["job_ids"].append(job_id)

run_meta = {
    "arm": arm, "short": args.short, "phase": args.phase, "repo": reg["repo"], "revision": reg["revision"],
    "model_class": type(model).__module__ + "." + type(model).__name__, "processor_class": type(proc).__name__,
    "params_unique": n_unique, "lr": lr, "lr_source": reg.get("lr_source", ""), "eff_batch": args.eff_batch,
    "n_samples_planned": args.n_samples, "start_row": args.start_row, "total_steps": total_steps, "warmup_steps": warmup,
    "schedule": "cosine to 0 with linear warm-up (transformers.get_cosine_schedule_with_warmup)",
    "optimizer": "torch AdamW betas (0.9,0.999) eps 1e-8 weight_decay 0, fp32 master weights and moments, clip 1.0",
    "precision": "bf16 weights and compute; fp32 master copy for the update", "grad_checkpointing": gc_on,
    "attention": vc.SDPA_NOTE,
    "instruction": vc.INSTR, "chat_template_kwargs": tmpl_kw, "answer_suffix_ids": suffix_ids,
    "answer_suffix_tokens": [tok.decode([i]) for i in suffix_ids], "answer_suffix_how": suffix_how,
    "template_suffix_text": suffix_text, "rendered_prompt": vc.rendered_prompt(args.short, proc, tmpl_kw),
    "seq_file": args.seq, "cap_hours": args.cap_hours, "deadline_utc": args.deadline_utc,
    "save_every_min": args.save_every_min, "load_seconds": round(load_seconds, 1), "transformers": transformers.__version__,
    "torch": torch.__version__, "gpu": torch.cuda.get_device_name(0) if use_cuda else "cpu", "job_id": job_id,
    "started_utc": utc(), "resumed": resumed, "init_state": args.init_state,
    "data_order_seed": args.data_order_seed, "seed_index": args.seed_index,
}
json.dump(run_meta, open(os.path.join(run_dir, "run_meta_%s.json" % (job_id or "local")), "w"), indent=1, ensure_ascii=False)
say(f"LR {lr} ({reg.get('lr_source', '')}); planned steps {total_steps} (warm-up {warmup}); params {n_unique}; "
    f"answer suffix {run_meta['answer_suffix_tokens']} ({suffix_how}); template kwargs {tmpl_kw}")
log({"event": "start", "lr": lr, "lr_source": reg.get("lr_source", ""), "step": st["step"], "resumed": resumed})


# ---------------- data ----------------
class DS(torch.utils.data.Dataset):
    def __init__(self, rr):
        self.rr = rr

    def __len__(self):
        return len(self.rr)

    def __getitem__(self, i):
        r = self.rr[i]
        im = Image.open(r["image"]).convert("RGB")
        im, npad = vc.pad_min_grid(args.short, proc, im)  # no-op unless the arm's patch grid would be below the merger kernel
        return im, r["text"], r["id"], npad


def collate(batch):
    imgs = [b[0] for b in batch]
    labs = [b[1] for b in batch]
    inp, lab, ntok = vc.build_train_batch(args.short, proc, tok, imgs, labs, suffix_ids, tmpl_kw)
    return inp, lab, ntok, labs, [b[2] for b in batch], sum(b[3] for b in batch)


PARENT_PID = os.getpid()


def _worker_init(_):
    # 2026-11-21 fix: a worker dies with its parent (SIGKILL on parent death, Linux prctl PR_SET_PDEATHSIG = 1), so a
    # killed run leaves no orphaned workers holding host memory (orphans of a killed run filled the job's 96 GB and
    # got later arms killed by the cgroup OOM killer)
    try:
        import ctypes
        ctypes.CDLL("libc.so.6", use_errno=True).prctl(1, signal.SIGKILL, 0, 0, 0)
        if os.getppid() != PARENT_PID:  # the parent died before prctl took effect
            os._exit(0)
    except Exception:  # noqa: BLE001
        pass
    # loader workers yield the CPU to the main process, which launches the GPU kernels (performance only)
    try:
        os.nice(10)
    except Exception:  # noqa: BLE001
        pass
    torch.set_num_threads(1)


def make_loader(first_row, mb):
    sub = torch.utils.data.Subset(DS(rows), range(first_row, len(rows)))
    kw = dict(batch_size=mb, shuffle=False, collate_fn=collate, num_workers=args.workers, drop_last=False)
    if args.workers > 0:
        # host-memory fix 2026-11-21: prefetch 2 (was 4), no pinned buffers (were pinned on CUDA)
        kw.update(prefetch_factor=2, persistent_workers=False, pin_memory=False, worker_init_fn=_worker_init)
    return iter(torch.utils.data.DataLoader(sub, **kw))


def to_dev(inp):
    out = {}
    for k, v in inp.items():
        if torch.is_tensor(v):
            v = v.to(dev, non_blocking=True)
            if v.is_floating_point():
                v = v.to(torch.bfloat16)
        out[k] = v
    return out


# ---------------- learning-curve points (request 2026-11-20 ~23:45 UTC) ----------------
if args.phase in ("short", "short_seed2"):
    CURVE_POINTS = [int(x) for x in args.curve_points.split(",") if x]
elif args.phase == "smoke":
    CURVE_POINTS = [320]  # code-path test on 32 TRAIN rows of the smoke sequence, written under the run folder only
else:
    CURVE_POINTS = []


def run_curve(label):
    """Pause training, read the curve set greedily with the current (bf16) weights, write the shared prediction
    format, resume. Its time is logged as curve_seconds and never counted in train_seconds (the 3 h cap)."""
    t0 = time.time()
    rec = {"event": "curve", "label": label, "samples": st["samples_seen"], "step": st["step"]}
    try:
        if args.phase == "smoke":
            crow = []
            with open(args.seq, encoding="utf-8") as f:
                h = f.readline().rstrip("\n").split("\t")
                ix = {k: i for i, k in enumerate(h)}
                for line in f:
                    p_ = line.rstrip("\n").split("\t")
                    crow.append({"id": p_[ix["id"]], "image": p_[ix["image"]], "text": p_[ix["text"]], "unit": "word", "split": "train"})
                    if len(crow) >= 32:
                        break
            out_dir = os.path.join(run_dir, "curve_test")
            set_name = "smoke_train_rows"
        else:
            if not os.path.exists(args.curve_manifest):
                rec["skipped"] = "curve manifest missing: " + args.curve_manifest
                st["curve_done"].append(label)
                log(rec)
                say("curve point", label, "skipped: manifest missing")
                return
            crow = vc.read_manifest(args.curve_manifest)
            if any(str(r.get("split", "")).lower() == "test" for r in crow):
                rec["skipped"] = "curve manifest has test rows: refused"
                st["curve_done"].append(label)
                log(rec)
                return
            # scorer convention: a second seed is a checkpoint of the same arm named <checkpoint>_seed2
            out_dir = os.path.join(args.preds_root, arm, "curve_%d" % label + ("_seed2" if args.seed_index == 2 else ""))
            set_name = os.path.splitext(os.path.basename(args.curve_manifest))[0]
        rows_ok = [r for r in crow if r.get("unit", "word") in vc.MAXNEW]
        model.eval()
        old_side = tok.padding_side
        tok.padding_side = "left"
        gcv, stops_v, stop_set_v = vc.gen_setup(model, tok, suffix_ids)
        done_c = {}
        try:
            for u in sorted(set(r.get("unit", "word") for r in rows_ok)):
                ru = [r for r in rows_ok if r.get("unit", "word") == u]
                for b in range(0, len(ru), 16):
                    bb = ru[b:b + 16]
                    recs = vc.generate_batch(args.short, model, proc, tok,
                                             [vc.pad_min_grid(args.short, proc, Image.open(r["image"]).convert("RGB"))[0] for r in bb],
                                             vc.MAXNEW[u], tmpl_kw, gcv, stop_set_v, dev)
                    for r, x in zip(bb, recs):
                        x["id"] = r["id"]
                        done_c[r["id"]] = x
        finally:
            tok.padding_side = old_side
            model.train()
            if use_cuda:
                torch.cuda.empty_cache()
        os.makedirs(out_dir, exist_ok=True)
        with open(os.path.join(out_dir, set_name + ".raw.jsonl"), "w", encoding="utf-8") as f:
            for r in rows_ok:
                f.write(json.dumps(done_c[r["id"]], ensure_ascii=False) + "\n")
        vc.write_pred_tsv(os.path.join(out_dir, set_name + ".tsv"), rows_ok, done_c, pp.plain_ref, pp.plain_output)
        sc = pp.score([r["text"] for r in rows_ok], [done_c[r["id"]]["raw"] for r in rows_ok])
        dt = time.time() - t0
        meta = {"arm": arm, "short": args.short, "model_repo": reg["repo"], "base_revision": reg["revision"],
                "checkpoint": "curve_%s (in-memory weights during training, not saved)" % label, "curve_point_nominal": label,
                "samples_seen": st["samples_seen"], "samples_total": args.start_row + st["samples_seen"],
                "data_order_seed": args.data_order_seed, "seed_index": args.seed_index,
                "step": st["step"], "learning_rate": lr, "lr_now": sched.get_last_lr()[0],
                "set": set_name, "manifest": args.curve_manifest if args.phase != "smoke" else args.seq,
                "rows": len(crow), "rows_scored": len(rows_ok), "rows_skipped_unit": len(crow) - len(rows_ok),
                "decoding": {"greedy": True, "num_beams": 1, "max_new_tokens": vc.MAXNEW, "batch": 16, "stop_ids": stops_v},
                "conf_definition": vc.CONF_DEF, "attention": vc.SDPA_NOTE, "plain_cer": sc["plain"]["cer"],
                "pp_cer": sc["pp"]["cer"], "plain_wer": sc["plain"]["wer"], "pp_wer": sc["pp"]["wer"],
                "curve_eval_seconds": round(dt, 1), "gpu": torch.cuda.get_device_name(0) if use_cuda else "cpu",
                "note": "evaluation time not counted in the 3 h training cap", "utc": utc()}
        json.dump(meta, open(os.path.join(out_dir, "meta.json"), "w"), indent=1, ensure_ascii=False)
        st["curve_seconds"] += dt
        st["curve_done"].append(label)
        rec.update({"plain_cer": sc["plain"]["cer"], "pp_cer": sc["pp"]["cer"], "rows": len(rows_ok), "curve_eval_seconds": round(dt, 1)})
        log(rec)
        say(f"curve point {label}: {len(rows_ok)} rows, plain CER {sc['plain']['cer']}, {dt:.0f}s (not counted in the cap)")
    except Exception as ex:  # noqa: BLE001  a failed curve point never stops training
        st["curve_done"].append(label)
        rec["failed"] = repr(ex)[:300]
        log(rec)
        say("curve point", label, "FAILED", repr(ex)[:200])
        model.train()


# ---------------- training loop ----------------
cap_s = args.cap_hours * 3600.0
last_save = time.time()
mb = st["micro_batch"]
loader = make_loader(st["samples_seen"], mb)
checked = 0
flag = None
if use_cuda:
    torch.cuda.reset_peak_memory_stats()
while st["step"] < total_steps:
    if st["train_seconds"] >= cap_s:
        flag = "short of P (3.0 h training cap reached)"
        break
    if time.time() >= deadline:
        flag = "stopped at the absolute deadline " + args.deadline_utc
        break
    if STOP["flag"]:
        flag = "interrupted (%s)" % STOP["why"]
        break
    prof = None
    if args.phase == "smoke" and not resumed and use_cuda and st["step"] == 3:
        prof = torch.profiler.profile(activities=[torch.profiler.ProfilerActivity.CPU, torch.profiler.ProfilerActivity.CUDA],
                                      with_stack=False, record_shapes=False)
        prof.__enter__()
    t_step = time.time()
    first = st["samples_seen"]
    n_rows = min(args.eff_batch, len(rows) - first)
    n_mb = math.ceil(n_rows / mb)
    try:
        t0 = time.time()
        mbs = [next(loader) for _ in range(n_mb)]
        t_data = time.time() - t0
        ntok_all = sum(x[2] for x in mbs)
        loss_tot = 0.0
        ph = {"fwd": 0.0, "bwd": 0.0, "acc": 0.0}
        pad_step = sum(x[5] for x in mbs)
        for inp, lab, ntok, labs, ids, _npad in mbs:
            tp = time.time()
            out = model(**to_dev(inp), use_cache=False)
            ls, nt = vc.target_loss_sum(out.logits, lab)
            if use_cuda:
                torch.cuda.synchronize()
            ph["fwd"] += time.time() - tp
            assert nt == ntok, f"target tokens {nt} != {ntok}"
            if checked < args.check_labels:
                lb = lab[:, 1:]
                for r in range(min(lab.shape[0], args.check_labels - checked)):
                    pos = lb[r] != -100
                    dec = tok.decode(lb[r][pos].tolist(), skip_special_tokens=False)
                    exp = labs[r] + "".join(tok.decode([i], skip_special_tokens=False) for i in suffix_ids)
                    ok = tok.decode(lb[r][pos].tolist()[: len(lb[r][pos]) - len(suffix_ids)], skip_special_tokens=False) == labs[r]
                    log({"event": "label_check", "id": ids[r], "label": labs[r], "decoded_loss_positions": dec,
                         "expected": exp, "label_part_equal": ok, "prompt_len": int((lab[r] == -100).sum())})
                    say(f"label check {ids[r]}: label part equal {ok}; decoded {dec!r}")
                    checked += 1
            tp = time.time()
            (ls / ntok_all).backward()
            loss_tot += float(ls.detach())
            ph["bwd"] += time.time() - tp
            del out, ls
            tp = time.time()
            for p, m in zip(params, master):
                if p.grad is not None:
                    if m.grad is None:
                        m.grad = p.grad.detach().float()
                    else:
                        m.grad.add_(p.grad.detach())
                    p.grad = None
            if use_cuda:
                torch.cuda.synchronize()
            ph["acc"] += time.time() - tp
        tp = time.time()
        gnorm = float(torch.nn.utils.clip_grad_norm_(master, 1.0))
        opt.step()
        sched.step()
        with torch.no_grad():
            for p, m in zip(params, master):
                p.copy_(m)
        opt.zero_grad(set_to_none=True)
        if use_cuda:
            torch.cuda.synchronize()
        ph["opt"] = time.time() - tp
    except torch.cuda.OutOfMemoryError as e:
        for p in params:
            p.grad = None
        opt.zero_grad(set_to_none=True)
        torch.cuda.empty_cache()
        if mb == 1:
            raise
        st["oom_events"].append({"step": st["step"], "micro_batch": mb, "utc": utc()})
        say(f"OOM at micro-batch {mb} (step {st['step']}): halving; {repr(e)[:120]}")
        mb //= 2
        st["micro_batch"] = mb
        loader = make_loader(st["samples_seen"], mb)
        continue
    dt = time.time() - t_step
    if prof is not None:
        prof.__exit__(None, None, None)
        try:
            ka = prof.key_averages()
            with open(os.path.join(run_dir, "profile_step4.txt"), "w") as fpf:
                fpf.write("step 4 wall %.3f s\n\nTOP BY SELF CPU TIME\n" % dt)
                fpf.write(ka.table(sort_by="self_cpu_time_total", row_limit=35))
                fpf.write("\n\nTOP BY CUDA TIME\n")
                fpf.write(ka.table(sort_by="cuda_time_total", row_limit=20))
        except Exception as ex:  # noqa: BLE001
            say("profile write failed", repr(ex)[:200])
        prof = None
    st["step"] += 1
    st["samples_seen"] += n_rows
    st["train_seconds"] += dt
    rec = {"step": st["step"], "samples": st["samples_seen"], "loss": loss_tot / max(ntok_all, 1), "tgt_tokens": ntok_all,
           "lr": sched.get_last_lr()[0], "grad_norm": gnorm, "step_s": round(dt, 3), "data_wait_s": round(t_data, 3),
           "micro_batch": mb, "train_s": round(st["train_seconds"], 1), "phase_s": {k: round(v, 3) for k, v in ph.items()}}
    if pad_step:
        st["padded_images"] = st.get("padded_images", 0) + pad_step
        rec["padded_images"] = pad_step
    if use_cuda:
        rec["max_mem_GiB"] = round(torch.cuda.max_memory_allocated() / 2**30, 2)
    log(rec)
    if st["step"] <= 3 or st["step"] % 50 == 0:
        say(f"step {st['step']}/{total_steps} loss {rec['loss']:.4f} lr {rec['lr']:.2e} {dt:.2f}s (data {t_data:.2f}s) mb {mb}")
    if not math.isfinite(rec["loss"]):
        flag = "non-finite loss"
        break
    for pt in CURVE_POINTS:
        if pt not in st["curve_done"] and st["samples_seen"] >= pt:
            run_curve(pt)
    if args.stop_after_steps and st["step"] >= args.stop_after_steps and st["step"] < total_steps:
        flag = "stopped after %d steps (smoke save-and-resume test)" % args.stop_after_steps
        break
    if time.time() - last_save >= args.save_every_min * 60:
        s = save_state(state_dir)
        last_save = time.time()
        log({"event": "save", "step": st["step"], "save_seconds": round(s, 1)})
        say(f"saved at step {st['step']} in {s:.0f}s")

done = st["step"] >= total_steps
st["flag"] = "complete" if done else flag
if (args.phase in ("short", "short_seed2") and not done and st["samples_seen"] > 0 and st["samples_seen"] not in st["curve_done"]
        and str(flag).startswith(("short of P", "stopped at the absolute deadline", "interrupted (leaders"))):
    run_curve(st["samples_seen"])  # extra curve point at the samples a capped or stopped run reached
s = save_state(state_dir, {"finished_utc": utc()})
log({"event": "final_save", "step": st["step"], "save_seconds": round(s, 1), "flag": st["flag"]})
say(f"state saved ({s:.0f}s); flag {st['flag']}")

exported = False
if not args.no_export and (done or not (args.stop_after_steps and flag and flag.startswith("stopped after"))):
    t0 = time.time()
    tmp = export_dir + ".tmp"
    shutil.rmtree(tmp, ignore_errors=True)
    model.config.use_cache = True
    # the class's own key names (save_original_format=False): the reverse key mapping of transformers 5.23 wrote
    # LightOnOCR-3-1B's language model under names its own loader does not map back (smoke test 2026-11-20 23:40Z)
    model.save_pretrained(tmp, safe_serialization=True, save_original_format=False)
    proc.save_pretrained(tmp)
    miss, unexp = vc.export_key_check(model, tmp)
    log({"event": "export_key_check", "missing": miss[:20], "n_missing": len(miss), "unexpected": unexp[:20], "n_unexpected": len(unexp)})
    if miss or unexp:
        say(f"EXPORT KEY CHECK FAILED: {len(miss)} missing, {len(unexp)} unexpected; export not used")
        shutil.rmtree(tmp, ignore_errors=True)
        raise SystemExit(3)
    json.dump({"arm": arm, "short": args.short, "phase": args.phase, "repo": reg["repo"], "base_revision": reg["revision"],
               "steps": st["step"], "samples_seen": st["samples_seen"], "lr": lr, "flag": st["flag"],
               "train_seconds": st["train_seconds"], "answer_suffix_ids": suffix_ids, "chat_template_kwargs": tmpl_kw,
               "instruction": vc.INSTR, "exported_utc": utc(), "start_row": args.start_row,
               "samples_total": args.start_row + st["samples_seen"], "data_order_seed": args.data_order_seed,
               "seed_index": args.seed_index}, open(os.path.join(tmp, "r5_export.json"), "w"), indent=1)
    shutil.rmtree(export_dir, ignore_errors=True)
    os.rename(tmp, export_dir)
    exported = True
    say(f"exported bf16 model to {export_dir} in {time.time() - t0:.0f}s")

steps_log = [json.loads(l) for l in open(log_path, encoding="utf-8") if '"step_s"' in l]
times = sorted(r["step_s"] for r in steps_log[3:]) if len(steps_log) > 5 else sorted(r["step_s"] for r in steps_log)
med = times[len(times) // 2] if times else None
summary = {"arm": arm, "short": args.short, "phase": args.phase, "lr": lr, "lr_source": reg.get("lr_source", ""),
           "start_row": args.start_row, "samples_total": args.start_row + st["samples_seen"],
           "data_order_seed": args.data_order_seed, "seed_index": args.seed_index,
           "samples_seen": st["samples_seen"], "steps": st["step"], "total_steps": total_steps,
           "train_seconds": round(st["train_seconds"], 1), "flag": st["flag"], "micro_batch": st["micro_batch"],
           "curve_points_done": st.get("curve_done"), "curve_seconds_not_in_cap": round(st.get("curve_seconds", 0.0), 1),
           "padded_images_min_grid": st.get("padded_images", 0),
           "min_grid_padding": "vlm_common.GRID_PAD kernel %s (bug fix 2026-11-21)" % vc.GRID_PAD.get(args.short) if vc.GRID_PAD.get(args.short) else "not applicable",
           "oom_events": st["oom_events"], "median_step_seconds": med,
           "projected_hours_for_planned_steps": (med * total_steps / 3600.0) if med else None,
           "exported": exported, "export_dir": export_dir if exported else None, "state_dir": state_dir,
           "resumed_from_step": st["resumed_from_step"], "resume_fingerprint_match": st.get("resume_fingerprint_match"),
           "job_ids": st["job_ids"], "updated_utc": utc()}
if use_cuda:
    summary["max_mem_GiB_train"] = round(torch.cuda.max_memory_allocated() / 2**30, 2)
    summary["max_mem_reserved_GiB_train"] = round(torch.cuda.max_memory_reserved() / 2**30, 2)
json.dump(summary, open(run_json, "w"), indent=1)
say("summary", json.dumps(summary))