File size: 24,547 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
"""ONEMODEL pilot (design ONEMODEL-pilot-1): fine-tune the R5 leader on whole pages in the spotting format, mixed 1:1 with its
own crop samples. Adapted from CODE/scripts/r5_vlma/train_vlm.py (same precision, optimiser, schedule, state files, export).

- Start: the leader folder (DATA/checkpoints/r5/paddleocr_vl_1_6/leader); native class, trust_remote_code never set.
- Step k uses page rows 16k..16k+15 of seq/page_seq.tsv and crop rows 16k..16k+15 of seq/crop_seq.tsv (mix_v1_seq rows from
  1,310,592). Page micro-batches of 4, one crop micro-batch of 16 (on CUDA out-of-memory, or a cuBLAS allocation failure,
  the failed micro-batch's graph is freed and only the failing stream's micro-batch is halved, down to 1; then exit 98; a
  resume whose fp32-master fingerprint does not match exits 96); pages and crops never share
  a micro-batch. Loss = page token-mean + crop token-mean (each over the step's target tokens of its stream).
- Pages: record image (pre-resized to <= 1,605,632 px) resized to spot_size(u x 1,605,632) with Lanczos (u from page_seq);
  prompt 'Spotting:' with the page processor size; target ids from the record (they end with </s>). Crops: vlm_common's own
  training batch (instruction 'Transcribe the text in this image exactly.', default processor size) - the leader's path.
- bf16 weights and compute, fp32 master weights and AdamW moments (0.9, 0.999, 1e-8, wd 0), clip 1.0, warm-up 3% then cosine to 0,
  gradient checkpointing (non-reentrant).
- State (master.pt, optim.pt, sched.pt, state.json) saved atomically every --save-every-min minutes, at --export-at steps, and
  when --max-seconds (process wall time) is reached or on SIGTERM/SIGUSR1; the process then exits 99 (the sbatch resubmits).
  Exports (bf16 HF folder + r5_export.json that eval_vlm.py reads) at --export-at steps, named ck_<page samples>; the last is
  also linked as 'final'. Exit 0 when all steps are done and the final export exists.
- --smoke: CPU code-path test (tiny page pixel cap, small batches, label-mask report, per-stream timing); --stop-after-steps N
  saves and exits 0 after step N (resume test).

usage: om_train.py --run pilot [--device cuda] [--max-seconds S] ...
"""
import argparse
import csv
import json
import math
import os
import shutil
import signal
import sys
import time
from datetime import datetime, timezone

HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
import om_common as C  # noqa: E402
import om_text as T  # noqa: E402

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

vc = C.vc
csv.field_size_limit(10 ** 9)

ap = argparse.ArgumentParser()
ap.add_argument("--run", required=True)
ap.add_argument("--model-dir", default=C.LEADER)
ap.add_argument("--data-root", default=C.DATA + "/data/processed/r6_onemodel")
ap.add_argument("--ckpt-root", default=C.DATA + "/checkpoints/r6_onemodel")
ap.add_argument("--out-root", default=C.DATA + "/outputs/r6_onemodel/train")
ap.add_argument("--page-batch", type=int, default=16)
ap.add_argument("--crop-batch", type=int, default=16)
ap.add_argument("--page-mb", type=int, default=4)
ap.add_argument("--crop-mb", type=int, default=16)
ap.add_argument("--page-samples", type=int, default=30000)
ap.add_argument("--lr", type=float, default=1e-5)
ap.add_argument("--warmup-frac", type=float, default=0.03)
ap.add_argument("--save-every-min", type=float, default=30.0)
ap.add_argument("--max-seconds", type=float, default=0.0)
ap.add_argument("--export-at", default="469,938,1407,1875")
ap.add_argument("--device", default="cuda")
ap.add_argument("--threads", type=int, default=0)
ap.add_argument("--workers", type=int, default=6, help="loader workers per stream")
ap.add_argument("--check-labels", type=int, default=4)
ap.add_argument("--smoke", action="store_true")
ap.add_argument("--smoke-max-pixels", type=int, default=200704, help="smoke only: page pixel cap (256 visual tokens)")
ap.add_argument("--stop-after-steps", type=int, default=0)
ap.add_argument("--state-dir", default="")
ap.add_argument("--no-export", action="store_true")
ap.add_argument("--seed", type=int, default=20261125)
args = ap.parse_args()

dev = args.device
use_cuda = dev == "cuda"
if args.threads:
    torch.set_num_threads(args.threads)
elif use_cuda:
    torch.set_num_threads(4)
torch.manual_seed(args.seed)
total_steps = math.ceil(args.page_samples / args.page_batch)
warmup = round(args.warmup_frac * total_steps)
export_at = sorted(int(x) for x in args.export_at.split(",") if x)
run_dir = os.path.join(args.out_root, args.run)
state_dir = args.state_dir or os.path.join(args.ckpt_root, args.run, "state")
os.makedirs(run_dir, exist_ok=True)
log_path = os.path.join(run_dir, "train_log.jsonl")
job_id = os.environ.get("SLURM_JOB_ID", "")
STOP = {"flag": False, "why": ""}
T_PROC = time.time()


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


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


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("[om %s %s]" % (args.run, utc()), *a, flush=True)


# ---------------- data ----------------
def read_tsv(p):
    T.guard_not_test(p)
    with open(p, encoding="utf-8", newline="") as f:
        return list(csv.DictReader(f, delimiter="\t", quoting=csv.QUOTE_NONE))


pages = {}
for s in ("gen_train", "school_train"):
    p = os.path.join(args.data_root, "records", s + ".jsonl")
    T.guard_not_test(p)
    with open(p, encoding="utf-8") as f:
        for line in f:
            r = json.loads(line)
            assert r["id"].startswith(("pg_train_", "school_train_")) and r["split"] == "train", r["id"]
            pages[r["id"]] = {"image": r["image"], "target_ids": r["target_ids"], "over_cap": r["over_cap"]}
page_rows = read_tsv(os.path.join(args.data_root, "seq", "page_seq.tsv"))
crop_rows = read_tsv(os.path.join(args.data_root, "seq", "crop_seq.tsv"))
need_p, need_c = total_steps * args.page_batch, total_steps * args.crop_batch
assert len(page_rows) >= need_p and len(crop_rows) >= need_c, "sequence files too short"
assert not any(pages[r["page_id"]]["over_cap"] for r in page_rows[:need_p]), "over-cap page in the sequence"

# ---------------- model ----------------
t_load = time.time()
proc, tok, model = C.load(args.model_dir)
tmpl_kw = vc.template_kwargs(proc, tok)
suffix_ids, suffix_how, suffix_text = vc.answer_suffix(C.SHORT, proc, tok, model.generation_config, tmpl_kw)
assert suffix_ids == [2], "answer suffix %s" % suffix_ids
assert vc.INSTR == T.CROP_INSTRUCTION, "crop instruction changed"
model.to(dev)
model.config.use_cache = False
model.gradient_checkpointing_enable(gradient_checkpointing_kwargs={"use_reentrant": False})
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]
master = [torch.nn.Parameter(p_.detach().float().clone(), requires_grad=True) for p_ in params]
opt = torch.optim.AdamW(master, lr=args.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 fingerprint():
    with torch.no_grad():
        return float(sum(m.double().sum().item() for m in master[:: max(1, len(master) // 16)]))


st = {"step": 0, "page_mb": args.page_mb, "crop_mb": args.crop_mb, "saves": 0, "oom_events": [], "job_ids": [], "resumed_from_step": [],
      "fingerprint_at_save": None, "train_seconds": 0.0, "exports": []}


def save_state(d, extra=None):
    t0 = time.time()
    tmp, old = d + ".tmp", d + ".old"
    shutil.rmtree(tmp, ignore_errors=True)
    os.makedirs(tmp, exist_ok=True)
    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"] = 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)
    shutil.rmtree(old, ignore_errors=True)
    return time.time() - t0


def load_state(d):
    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
    opt.load_state_dict(torch.load(os.path.join(d, "optim.pt"), map_location=dev, weights_only=True))
    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"))))


shutil.rmtree(state_dir + ".tmp", 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 = fingerprint()
    st["resumed_from_step"].append(st["step"])
    st["resume_fingerprint_match"] = st["fingerprint_at_save"] == fp
    resumed = True
    say("resumed at step %d; fingerprint saved %r now %r" % (st["step"], st["fingerprint_at_save"], fp))
    if not st["resume_fingerprint_match"]:
        say("REFUSED: the fp32 master weights loaded from %s do not match the fingerprint saved with them; exit 96" % state_dir)
        sys.exit(96)
if job_id and job_id not in st["job_ids"]:
    st["job_ids"].append(job_id)
meta = {"design": T.DESIGN_ID, "run": args.run, "model_dir": args.model_dir, "model_class": type(model).__name__,
        "processor_class": type(proc).__name__, "image_processor_class": type(proc.image_processor).__name__,
        "params_unique": vc.unique_params(model), "lr": args.lr, "total_steps": total_steps, "warmup_steps": warmup,
        "page_batch": args.page_batch, "crop_batch": args.crop_batch, "page_mb": st["page_mb"], "crop_mb": args.crop_mb,
        "page_samples": total_steps * args.page_batch, "crop_samples": total_steps * args.crop_batch,
        "loss": "page token-mean + crop token-mean", "export_at": export_at, "answer_suffix_ids": suffix_ids,
        "answer_suffix_how": suffix_how, "chat_template_kwargs": tmpl_kw, "page_prompt": T.SPOT_PROMPT, "crop_instruction": vc.INSTR,
        "page_processor_kwargs": C.PAGE_PROC_KW, "smoke": args.smoke, "smoke_max_pixels": args.smoke_max_pixels if args.smoke else None,
        "transformers": transformers.__version__, "torch": torch.__version__, "device": dev,
        "gpu": torch.cuda.get_device_name(0) if use_cuda else "cpu", "job_id": job_id, "resumed": resumed,
        "load_seconds": round(load_seconds, 1), "started_utc": utc(), "attention": vc.SDPA_NOTE}
json.dump(meta, open(os.path.join(run_dir, "run_meta_%s.json" % (job_id or "local_%d" % int(time.time()))), "w"), indent=1, ensure_ascii=False)
log({"event": "start", "step": st["step"], "resumed": resumed, "lr": args.lr, "total_steps": total_steps})
say("start: step %d of %d (warm-up %d), lr %g, params %d, resumed %s" % (st["step"], total_steps, warmup, args.lr, meta["params_unique"], resumed))


class PageDS(torch.utils.data.Dataset):
    def __len__(self):
        return len(page_rows)

    def __getitem__(self, i):
        r = page_rows[i]
        rec = pages[r["page_id"]]
        im = Image.open(rec["image"]).convert("RGB")
        cap = args.smoke_max_pixels if args.smoke else float(r["u"]) * T.SPOT_MAX_PIXELS
        w, h = T.fit_size(im.size[0], im.size[1], cap)
        if (w, h) != im.size:
            im = im.resize((w, h), Image.LANCZOS)
        return im, rec["target_ids"], r["page_id"]


class CropDS(torch.utils.data.Dataset):
    def __len__(self):
        return len(crop_rows)

    def __getitem__(self, i):
        r = crop_rows[i]       # rows of the frozen train mix (build job copies mix_v1_seq rows 1,310,592 ...)
        return Image.open(r["image"]).convert("RGB"), r["text"], r["id"]


def collate_page(batch):
    imgs, tg, ids = [b[0] for b in batch], [b[1] for b in batch], [b[2] for b in batch]
    inp, lab = C.page_train_batch(proc, tok, imgs, tg, tmpl_kw)
    return inp, lab, sum(len(t) for t in tg), tg, ids


def collate_crop(batch):
    imgs, labs, ids = [b[0] for b in batch], [b[1] for b in batch], [b[2] for b in batch]
    inp, lab, ntok = vc.build_train_batch(C.SHORT, proc, tok, imgs, labs, suffix_ids, tmpl_kw)
    tg = [vc.target_ids(tok, l_, suffix_ids) for l_ in labs]
    return inp, lab, ntok, tg, ids


PARENT = os.getpid()


def _wi(_):
    try:
        import ctypes
        ctypes.CDLL("libc.so.6", use_errno=True).prctl(1, signal.SIGKILL, 0, 0, 0)
        if os.getppid() != PARENT:
            os._exit(0)
    except Exception:  # noqa: BLE001
        pass
    try:
        os.nice(10)
    except Exception:  # noqa: BLE001
        pass
    torch.set_num_threads(1)


def make_loader(ds, first, mb, collate):
    sub = torch.utils.data.Subset(ds, range(first, len(ds)))
    kw = dict(batch_size=mb, shuffle=False, collate_fn=collate, num_workers=args.workers, drop_last=False)
    if args.workers > 0:
        kw.update(prefetch_factor=2, persistent_workers=False, pin_memory=False, worker_init_fn=_wi)
    return iter(torch.utils.data.DataLoader(sub, **kw))


def export(name):
    t0 = time.time()
    d = os.path.join(args.ckpt_root, args.run, name)
    tmp = d + ".tmp"
    shutil.rmtree(tmp, ignore_errors=True)
    model.config.use_cache = True
    model.save_pretrained(tmp, safe_serialization=True, save_original_format=False)
    model.config.use_cache = False
    proc.save_pretrained(tmp)
    miss, unexp = vc.export_key_check(model, tmp)
    if miss or unexp:
        shutil.rmtree(tmp, ignore_errors=True)
        log({"event": "export_key_check_failed", "missing": miss[:20], "unexpected": unexp[:20]})
        say("EXPORT KEY CHECK FAILED", len(miss), len(unexp))
        raise SystemExit(3)
    json.dump({"design": T.DESIGN_ID, "arm": "onemodel", "short": C.SHORT, "run": args.run, "phase": name,
               "repo": "PaddlePaddle/PaddleOCR-VL-1.6", "base_revision": "132c45f52c0a26ed5a6b2f6bd8e3985794cc27dd",
               "start_weights": args.model_dir, "steps": st["step"], "samples_seen": st["step"] * args.page_batch,
               "page_samples_seen": st["step"] * args.page_batch, "crop_samples_seen": st["step"] * args.crop_batch,
               "samples_total": st["step"] * args.page_batch, "lr": args.lr, "flag": "complete" if st["step"] >= total_steps else "partial",
               "train_seconds": st["train_seconds"], "answer_suffix_ids": suffix_ids, "chat_template_kwargs": tmpl_kw,
               "instruction": vc.INSTR, "spotting_prompt": T.SPOT_PROMPT, "page_max_pixels": T.SPOT_MAX_PIXELS,
               "data_order_seed": args.seed, "seed_index": 1, "exported_utc": utc(), "smoke": args.smoke},
              open(os.path.join(tmp, "r5_export.json"), "w"), indent=1)
    shutil.rmtree(d, ignore_errors=True)
    os.rename(tmp, d)
    st["exports"].append({"name": name, "step": st["step"], "utc": utc()})
    log({"event": "export", "name": name, "step": st["step"], "seconds": round(time.time() - t0, 1), "dir": d})
    say("exported %s at step %d in %.0fs" % (name, st["step"], time.time() - t0))
    return d


def micro(inp, lab):
    out = model(**C.to_dev(inp, dev), use_cache=False)
    ls, nt = vc.target_loss_sum(out.logits, lab)
    return out, ls, nt


def accumulate():
    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


def is_oom(e):
    """CUDA out-of-memory and allocation failures that arrive as RuntimeError (cuBLAS / cuDNN) are handled alike"""
    if isinstance(e, torch.cuda.OutOfMemoryError):
        return True
    t = str(e)
    return isinstance(e, RuntimeError) and ("CUBLAS_STATUS_ALLOC_FAILED" in t or "out of memory" in t)


checked = {"page": 0, "crop": 0}
smoke_rep = {"label_checks": [], "timing": []}
page_loader = make_loader(PageDS(), st["step"] * args.page_batch, st["page_mb"], collate_page)
crop_loader = make_loader(CropDS(), st["step"] * args.crop_batch, st["crop_mb"], collate_crop)
last_save = time.time()
exit_code = 0
if use_cuda:
    torch.cuda.reset_peak_memory_stats()
while st["step"] < total_steps:
    if STOP["flag"] or (args.max_seconds and time.time() - T_PROC > args.max_seconds):
        why = STOP["why"] or "max_seconds"
        s_ = save_state(state_dir, {"stopped_for": why})
        log({"event": "stopped_for_time", "step": st["step"], "why": why, "save_seconds": round(s_, 1)})
        say("stopped (%s) at step %d; state saved in %.0fs; exit 99" % (why, st["step"], s_))
        exit_code = 99
        break
    t_step = time.time()
    n_pmb = math.ceil(args.page_batch / st["page_mb"])
    n_cmb = math.ceil(args.crop_batch / st["crop_mb"])
    cur = "data"
    out = ls = None
    try:
        t0 = time.time()
        pmbs = [next(page_loader) for _ in range(n_pmb)]
        cmbs = [next(crop_loader) for _ in range(n_cmb)]
        t_data = time.time() - t0
        n_ptok = sum(x[2] for x in pmbs)
        n_ctok = sum(x[2] for x in cmbs)
        lp = lc = 0.0
        tim = {"page_fwd_bwd": 0.0, "crop_fwd_bwd": 0.0}
        for stream, mbs, ntot in (("page", pmbs, n_ptok), ("crop", cmbs, n_ctok)):
            for inp, lab, ntok, tg, ids in mbs:
                cur = stream
                tp = time.time()
                out, ls, nt = micro(inp, lab)
                assert nt == ntok, "target tokens %d != %d" % (nt, ntok)
                if checked[stream] < args.check_labels:
                    rep = C.label_mask_report(lab, tg, inp["input_ids"])
                    for r_, x in enumerate(rep):
                        lv = lab[r_][lab[r_] != -100].tolist()
                        x.update({"stream": stream, "id": ids[r_], "step": st["step"] + 1,
                                  "decoded_head": tok.decode(lv[:16], skip_special_tokens=False),
                                  "decoded_tail": tok.decode(lv[-12:], skip_special_tokens=False),
                                  "last_label_is_end_token": lv[-1:] == suffix_ids})
                        if stream == "page":
                            x["grid"] = inp["image_grid_thw"][r_].tolist()
                        log({"event": "label_check", **x})
                        smoke_rep["label_checks"].append(x)
                    checked[stream] += 1
                (ls / ntot).backward()
                if stream == "page":
                    lp += float(ls.detach())
                else:
                    lc += float(ls.detach())
                out = ls = None
                accumulate()
                if use_cuda:
                    torch.cuda.synchronize()
                tim[stream + "_fwd_bwd"] += time.time() - tp
        cur = "optimizer"
        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()
        tim["opt"] = time.time() - tp
    except (torch.cuda.OutOfMemoryError, RuntimeError) as e:
        if not is_oom(e):
            raise
        # free the failed micro-batch's graph and every partial gradient before the retry (the step is redone from its start;
        # the fp32 masters were not touched unless the optimiser itself failed, which is fatal below)
        out = ls = None
        pmbs = cmbs = None
        import gc as _gc
        _gc.collect()
        for p_ in params:
            p_.grad = None
        opt.zero_grad(set_to_none=True)
        if use_cuda:
            torch.cuda.empty_cache()
        key = {"page": "page_mb", "crop": "crop_mb"}.get(cur)
        if key is None or st[key] == 1:
            if key is not None:   # failed inside a micro-batch: the masters are untouched, the state is safe to save
                save_state(state_dir, {"stopped_for": "out of memory in %s (micro-batch 1)" % cur})
            log({"event": "oom_fatal", "step": st["step"], "where": cur, "error": repr(e)[:300]})
            say("OUT OF MEMORY in %s (%s); exit 98" % (cur, "state saved" if key else "state not saved, last periodic save kept"))
            exit_code = 98
            break
        st["oom_events"].append({"step": st["step"], "stream": cur, key: st[key], "utc": utc(), "error": repr(e)[:200]})
        st[key] //= 2
        say("out of memory in the %s stream (step %d): %s halved to %d; %s" % (cur, st["step"], key, st[key], repr(e)[:120]))
        page_loader = make_loader(PageDS(), st["step"] * args.page_batch, st["page_mb"], collate_page)
        crop_loader = make_loader(CropDS(), st["step"] * args.crop_batch, st["crop_mb"], collate_crop)
        continue
    dt = time.time() - t_step
    st["step"] += 1
    st["train_seconds"] += dt
    loss_p, loss_c = lp / max(n_ptok, 1), lc / max(n_ctok, 1)
    rec = {"step": st["step"], "loss": loss_p + loss_c, "loss_page": loss_p, "loss_crop": loss_c, "page_tokens": n_ptok,
           "crop_tokens": n_ctok, "lr": sched.get_last_lr()[0], "grad_norm": gnorm, "step_s": round(dt, 3),
           "data_wait_s": round(t_data, 3), "page_mb": st["page_mb"], "crop_mb": st["crop_mb"],
           "timing_s": {k: round(v, 3) for k, v in tim.items()}}
    if use_cuda:
        rec["max_mem_GiB"] = round(torch.cuda.max_memory_allocated() / 2 ** 30, 2)
        rec["max_mem_reserved_GiB"] = round(torch.cuda.max_memory_reserved() / 2 ** 30, 2)
    log(rec)
    smoke_rep["timing"].append(rec)
    if st["step"] <= 3 or st["step"] % 25 == 0:
        say("step %d/%d loss %.4f (page %.4f crop %.4f) lr %.2e %.2fs (data %.2fs) mb %d" % (
            st["step"], total_steps, rec["loss"], loss_p, loss_c, rec["lr"], dt, t_data, st["page_mb"]))
    if not math.isfinite(rec["loss"]):
        s_ = save_state(state_dir, {"stopped_for": "non-finite loss"})
        say("non-finite loss; exit 97")
        exit_code = 97
        break
    if st["step"] in export_at and not args.no_export:
        export("ck_%d" % (st["step"] * args.page_batch))
        save_state(state_dir)
        last_save = time.time()
    if args.stop_after_steps and st["step"] >= args.stop_after_steps and st["step"] < total_steps:
        s_ = save_state(state_dir, {"stopped_for": "stop_after_steps"})
        log({"event": "stopped_after_steps", "step": st["step"], "save_seconds": round(s_, 1)})
        say("stopped after %d steps (resume test); state saved" % st["step"])
        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)})

done = st["step"] >= total_steps
if done and exit_code == 0:
    if not args.no_export:
        final_name = "ck_%d" % (st["step"] * args.page_batch)
        d = os.path.join(args.ckpt_root, args.run, final_name)
        if not os.path.isdir(d):
            export(final_name)
        link = os.path.join(args.ckpt_root, args.run, "final")
        if not os.path.islink(link):
            os.symlink(final_name, link)
    save_state(state_dir, {"finished_utc": utc()})
    json.dump({"design": T.DESIGN_ID, "run": args.run, "steps": st["step"], "train_seconds": st["train_seconds"],
               "exports": st["exports"], "oom_events": st["oom_events"], "job_ids": st["job_ids"],
               "resumed_from_step": st["resumed_from_step"], "finished_utc": utc()},
              open(os.path.join(run_dir, "train.done.json"), "w"), indent=1)
    say("training complete")
if args.smoke:
    smoke_rep.update({"steps_done": st["step"], "resumed": resumed, "resume_fingerprint_match": st.get("resume_fingerprint_match"),
                      "load_seconds": round(load_seconds, 1)})
    json.dump(smoke_rep, open(os.path.join(run_dir, "smoke_train_%s.json" % ("resumed" if resumed else "fresh")), "w"),
              indent=1, ensure_ascii=False)
sys.exit(exit_code)