File size: 22,876 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
"""R5 VLMA: validation predictions of one checkpoint on every VALIDATION set of the registry (never a test set).

- Refuses a set that is locked, whose registry split is not val, or whose manifest has any row with split != val.
- V1 (KOHTD screen set) first, so the leader choice never waits for the other sets.
- Greedy, one beam, no repetition penalty; max_new_tokens 48 for unit=word, 192 for unit=line; unit=page is skipped
  and logged (cap to be set separately). Same prompt builder as training (vlm_common.prompt_batch), left
  padding, stop on the generation-config end ids + tokenizer eos + the trained answer-end token.
- Writes after every batch and resumes: <preds_root>/<arm>/<ckpt>/<set>.raw.jsonl, then <set>.tsv (id, ref, hyp; hyp =
  PLAIN-normalised greedy output), <set>.score.json (plain and post-processed CER/WER, postproc.py), meta.json.
- Speed: images per second at batch 16 on V1 (all batches but the first; image loading + processor + generate).
  Peak memory at batch 1: max_memory_allocated over 32 V1 crops at batch 1 after the peak counter is reset.

usage: eval_vlm.py --short S --arm A --ckpt NAME --model-dir DIR --registry R --evalsets JSON --preds-root P [options]
       eval_vlm.py ... --smoke-seq SEQ.tsv --smoke-n 16 --smoke-out FILE   (export/reload check on train rows only)
"""
import argparse
import copy
import json
import os
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", required=True)
ap.add_argument("--ckpt", required=True)
ap.add_argument("--model-dir", required=True)
ap.add_argument("--registry", required=True)
ap.add_argument("--evalsets", default=None)
ap.add_argument("--preds-root", default=None)
ap.add_argument("--batch", type=int, default=16)
ap.add_argument("--deadline-utc", default="2026-11-22T18:58:00Z")
ap.add_argument("--sets", default="", help="comma list of set names to run (default: all validation sets)")
ap.add_argument("--device", default="cuda")
ap.add_argument("--smoke-seq", default=None)
ap.add_argument("--smoke-n", type=int, default=16)
ap.add_argument("--smoke-out", default=None)
ap.add_argument("--limit", type=int, default=0, help="test only: first N rows of each set")
ap.add_argument("--test-maxnew", type=int, default=0, help="test only: force this token cap (to exercise the cap-retry path)")
args = ap.parse_args()

dev = args.device
use_cuda = dev == "cuda"
deadline = datetime.strptime(args.deadline_utc, "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=timezone.utc).timestamp()
reg = vc.read_registry(args.registry)[args.short]
MAXNEW = vc.MAXNEW
if args.test_maxnew:  # test only; never used for a reported figure
    MAXNEW = {u: args.test_maxnew for u in vc.MAXNEW}


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


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


t_load = time.time()
proc, tok = vc.load_processor(args.short, args.model_dir)
tok.padding_side = "left"
exp_meta = {}
if os.path.exists(os.path.join(args.model_dir, "r5_export.json")):
    exp_meta = json.load(open(os.path.join(args.model_dir, "r5_export.json")))
tmpl_kw = exp_meta.get("chat_template_kwargs", vc.template_kwargs(proc, tok))
model, load_info = vc.load_model(args.short, args.model_dir, torch.bfloat16, info=True)
model = model.to(dev).eval()
load_seconds = time.time() - t_load
if exp_meta:  # an exported fine-tuned checkpoint must reload exactly (no missing / unexpected / mismatched key)
    bad_keys = {k: list(load_info.get(k, []))[:10] for k in ("missing_keys", "unexpected_keys", "mismatched_keys") if load_info.get(k)}
    if bad_keys:
        say("REFUSED: exported checkpoint does not reload exactly:", json.dumps(bad_keys)[:600])
        sys.exit(4)
gc, stops, stop_set = vc.gen_setup(model, tok, exp_meta.get("answer_suffix_ids"))


def gen(imgs, max_new):
    return vc.generate_batch(args.short, model, proc, tok, imgs, max_new, tmpl_kw, gc, stop_set, dev)


CONF_DEF = vc.CONF_DEF
RETRY_T = 0.3
RETRY_SEED = 20261121
RETRY_RULE = ("cap-retry rule (records/R5/RULE/r5_posttrain_experiment.txt, adopted 2026-11-21): when greedy decoding stops at "
              "the token cap without an end-of-sequence token, decode once more at temperature 0.3 (sampling, top-k and "
              "top-p off, torch seed 20261121 set before each set's retries) and keep that output if it ends with a stop "
              "token; otherwise keep the greedy output. A separate post-processed figure; the decision figure stays greedy.")


def cap_retry(e, name, rows, done):
    """Write <ckpt>_retry/<set>.* : greedy predictions, except hit_cap rows re-decoded once at temperature 0.3 and kept
    if they end properly. Resumable; re-running on a finished checkpoint only adds the retries (catch-up)."""
    rdir = os.path.join(args.preds_root, args.arm, args.ckpt + "_retry")
    os.makedirs(rdir, exist_ok=True)
    rpath = os.path.join(rdir, name + ".raw.jsonl")
    rdone = {}
    if os.path.exists(rpath):
        for line in open(rpath, encoding="utf-8"):
            try:
                d = json.loads(line)
                rdone[d["id"]] = d
            except Exception:  # noqa: BLE001
                pass
    need = [r for r in rows if done[r["id"]].get("hit_cap") and r["id"] not in rdone]
    torch.manual_seed(RETRY_SEED)
    with open(rpath, "a", encoding="utf-8") as fp:
        for u in sorted(set(r.get("unit", "word") for r in need)):
            ru = [r for r in need if r.get("unit", "word") == u]
            for b in range(0, len(ru), args.batch):
                if time.time() >= deadline:
                    break
                bb = ru[b:b + args.batch]
                recs = vc.generate_batch(args.short, model, proc, tok, [load_img(r["image"]) for r in bb], MAXNEW[u],
                                         tmpl_kw, gc, stop_set, dev, temperature=RETRY_T)
                for r, x in zip(bb, recs):
                    kept = not x["hit_cap"]
                    keep = x if kept else done[r["id"]]
                    rec = {"id": r["id"], "raw": keep["raw"], "n_new": keep.get("n_new"), "hit_cap": keep.get("hit_cap"),
                           "conf": keep.get("conf"), "conf_min": keep.get("conf_min"), "retried": True,
                           "retry_kept": kept, "retry_raw": x["raw"], "greedy_raw": done[r["id"]]["raw"]}
                    fp.write(json.dumps(rec, ensure_ascii=False) + "\n")
                    rdone[r["id"]] = rec
                fp.flush()
    final = {r["id"]: rdone.get(r["id"], done[r["id"]]) for r in rows}
    complete_r = all((not done[r["id"]].get("hit_cap")) or r["id"] in rdone for r in rows)
    vc.write_pred_tsv(os.path.join(rdir, name + ".tsv"), rows, final, pp.plain_ref, pp.plain_output)
    sc = pp.score([r["text"] for r in rows], [final[r["id"]]["raw"] for r in rows])
    n_ret = sum(1 for r in rows if r["id"] in rdone)
    n_kept = sum(1 for r in rows if rdone.get(r["id"], {}).get("retry_kept"))
    sc.update({"set": name, "complete": complete_r, "rows": len(rows), "retried": n_ret, "retry_kept": n_kept,
               "rule": RETRY_RULE})
    json.dump(sc, open(os.path.join(rdir, name + ".score.json"), "w"), indent=1)
    mp = os.path.join(rdir, "meta.json")
    rm = json.load(open(mp)) if os.path.exists(mp) else {}
    rm.update({"arm": args.arm, "checkpoint": args.ckpt + "_retry", "greedy_checkpoint_folder": args.ckpt,
               "rule": RETRY_RULE, "samples_seen": meta.get("samples_seen"), "samples_total": meta.get("samples_total"),
               "data_order_seed": meta.get("data_order_seed"), "seed_index": meta.get("seed_index"),
               "learning_rate": meta.get("learning_rate"), "model_repo": meta.get("model_repo"),
               "base_revision": meta.get("base_revision"), "peak_mem_reserved_batch1_GiB": meta.get("peak_mem_reserved_batch1_GiB"),
               "tsv_columns": meta.get("tsv_columns"), "conf_definition": CONF_DEF + " (retried rows: sampled path at T 0.3)",
               "updated_utc": utc()})
    rm.setdefault("sets", {})[name] = {"complete": complete_r, "rows": len(rows), "retried": n_ret, "retry_kept": n_kept,
                                       "plain_cer": sc["plain"]["cer"], "pp_cer": sc["pp"]["cer"],
                                       "plain_wer": sc["plain"]["wer"], "pp_wer": sc["pp"]["wer"]}
    json.dump(rm, open(mp, "w"), indent=1, ensure_ascii=False)
    say(f"{name}: cap-retry {n_ret} rows re-decoded, {n_kept} kept; plain CER {sc['plain']['cer']}")


PADDED = {"n": 0}


def load_img(p):
    """the same minimum-patch-grid padding as training (vlm_common.pad_min_grid; no-op for arms not in GRID_PAD)."""
    im, npad = vc.pad_min_grid(args.short, proc, Image.open(p).convert("RGB"))
    PADDED["n"] += npad
    return im


if args.smoke_seq:
    rows = []
    with open(args.smoke_seq, encoding="utf-8") as f:
        hdr = f.readline().rstrip("\n").split("\t")
        ix = {h: i for i, h in enumerate(hdr)}
        for line in f:
            p = line.rstrip("\n").split("\t")
            rows.append((p[ix["id"]], p[ix["image"]], p[ix["text"]]))
            if len(rows) >= args.smoke_n:
                break
    t0 = time.time()
    recs = []
    for b in range(0, len(rows), args.batch):
        bb = rows[b:b + args.batch]
        recs += gen([load_img(r[1]) for r in bb], 48)
    res = {"rows": len(rows), "seconds": round(time.time() - t0, 2), "load_seconds": round(load_seconds, 1),
           "score_train_rows_not_a_result": pp.score([r[2] for r in rows], [x["raw"] for x in recs]),
           "examples": [{"id": r[0], "ref": r[2], "raw": x["raw"], "n_new": x["n_new"], "hit_cap": x["hit_cap"],
                         "conf": x.get("conf"), "conf_min": x.get("conf_min")} for r, x in zip(rows, recs)]}
    json.dump(res, open(args.smoke_out, "w"), indent=1, ensure_ascii=False)
    say("smoke generation", json.dumps(res["examples"][:4], ensure_ascii=False))
    sys.exit(0)

# ---------------- registry ----------------
reg_doc = json.load(open(args.evalsets, encoding="utf-8"))
if isinstance(reg_doc, dict) and isinstance(reg_doc.get("sets"), list):
    entries = reg_doc["sets"]
elif isinstance(reg_doc, dict) and isinstance(reg_doc.get("evalsets"), list):
    entries = reg_doc["evalsets"]
elif isinstance(reg_doc, list):
    entries = reg_doc
else:
    entries = [dict(v, name=v.get("name", k)) for k, v in reg_doc.items() if isinstance(v, dict)]
want = [s for s in args.sets.split(",") if s]
# amendment 3.3 D9: a short (P_short) checkpoint is validated on these sets only; the full kohtd_val, hkr_val,
# chd_val and school_val are read only at the leaders' final checkpoints (any other checkpoint name gets every set)
D9_SHORT_SETS = ["V1", "synth_hand_val", "synth_typed_val", "synth_clutter_val", "print_real_val", "hkr_val_s2000",
                 "chd_val_s2000", "school_val_s2000"]
if not want and args.ckpt in ("short", "short_seed2"):
    want = list(D9_SHORT_SETS)
VAL = {"val", "validation"}
todo, refused = [], []
for e in entries:
    name = e.get("name")
    if want and name not in want:
        continue
    if e.get("locked") is True or str(e.get("split", "")).lower() not in VAL:
        refused.append({"name": name, "why": "locked or registry split is not val"})
        continue
    if not e.get("manifest") or not os.path.exists(e["manifest"]):
        refused.append({"name": name, "why": "manifest missing: %s" % e.get("manifest")})
        continue
    todo.append(e)


def is_v1(e):
    return e.get("name") in ("V1", "kohtd_screen_v1") or os.path.basename(e.get("manifest", "")) == "kohtd_screen_v1.tsv"


PRIORITY = ["V1", "V1lm", "kohtd_val", "hkr_val_s2000", "chd_val_s2000", "school_val_s2000", "synth_hand_val",
            "synth_typed_val", "synth_clutter_val", "print_real_val", "hkr_val", "chd_val", "school_val"]
todo.sort(key=lambda e: (not is_v1(e), PRIORITY.index(e["name"]) if e.get("name") in PRIORITY else len(PRIORITY), e.get("name")))
# the same image (same path and unit) in two sets is read once per call: e.g. V1 and V1lm lie inside kohtd_val, the
# s2000 sets inside the full sets (greedy output of one batch is reused; batch composition differs, nothing else)
CACHE = {}
out_dir = os.path.join(args.preds_root, args.arm, args.ckpt)
os.makedirs(out_dir, exist_ok=True)
meta_path = os.path.join(out_dir, "meta.json")
meta = json.load(open(meta_path)) if os.path.exists(meta_path) else {}
meta.update({
    "arm": args.arm, "short": args.short, "model_repo": reg["repo"], "base_revision": reg["revision"], "checkpoint": args.ckpt,
    "checkpoint_dir": args.model_dir, "samples_seen": exp_meta.get("samples_seen"), "learning_rate": exp_meta.get("lr"),
    "train_flag": exp_meta.get("flag"), "samples_total": exp_meta.get("samples_total", exp_meta.get("samples_seen")),
    "data_order_seed": exp_meta.get("data_order_seed"), "seed_index": exp_meta.get("seed_index"),
    "decoding": {"greedy": True, "num_beams": 1, "max_new_tokens": MAXNEW,
                                                    "batch": args.batch, "stop_ids": sorted(stops)},
    "instruction": vc.INSTR, "chat_template_kwargs": tmpl_kw, "gpu": torch.cuda.get_device_name(0) if use_cuda else "cpu",
    "transformers": transformers.__version__, "torch": torch.__version__, "load_seconds": round(load_seconds, 1),
    "postproc_sha256_file": "records/R5/VLMA/postproc.sha256", "refused_sets": refused,
    "tsv_columns": "id, ref (N0: NFC + whitespace collapse), hyp (N0 of the raw greedy output), conf, conf_min, hit_cap, n_tokens",
    "conf_definition": CONF_DEF, "attention": vc.SDPA_NOTE,
    "memory_note": "gate G (clarification G6) uses peak_mem_reserved_batch1_GiB (torch.cuda.max_memory_reserved); peak_mem_batch1_GiB is max_memory_allocated; H100, not RTX 5090",
})
meta.setdefault("sets", {})
t_all = time.time()
# Gate G (clarification G6): peak memory reading ONE V1 crop at a time, measured first, right after loading and before
# any batch-16 work (the caching allocator would otherwise keep what batch 16 reserved)
v1e = [e for e in todo if is_v1(e)]


def image_sizes(manifest):
    """width x height of every image of a manifest (headers only), cached per manifest path + mtime."""
    cdir = os.path.join(os.path.dirname(os.path.abspath(args.preds_root)), "vlma", "image_sizes")
    os.makedirs(cdir, exist_ok=True)
    key = os.path.basename(manifest) + "_%d.json" % int(os.path.getmtime(manifest))
    cp = os.path.join(cdir, key)
    if os.path.exists(cp):
        return json.load(open(cp))
    out = {}
    for r in vc.read_manifest(manifest):
        try:
            with Image.open(r["image"]) as im:
                out[r["id"]] = [im.width, im.height, r.get("unit", "word"), r["image"]]
        except Exception:  # noqa: BLE001
            pass
    json.dump(out, open(cp, "w"))
    return out


if todo and use_cuda and "peak_mem_reserved_batch1_GiB" not in meta:
    # clarification H6: peak max_memory_reserved at batch 1 on the LARGEST validation input (pixels), plus 32 V1 crops
    cands = []
    for e in todo:
        for rid, (w, h, unit, path) in image_sizes(e["manifest"]).items():
            if unit in MAXNEW:
                cands.append((w * h, rid, e["name"], w, h, unit, path))
    cands.sort(reverse=True)
    largest, seen_paths = [], set()
    for c in cands:  # three DISTINCT images (the same image can sit in several sets)
        if c[6] not in seen_paths:
            seen_paths.add(c[6])
            largest.append(c)
        if len(largest) == 3:
            break
    r32 = vc.read_manifest(v1e[0]["manifest"])[:32] if v1e else []
    torch.cuda.synchronize()
    torch.cuda.empty_cache()
    torch.cuda.reset_peak_memory_stats()
    t0 = time.time()
    for c in largest:
        gen([load_img(c[6])], MAXNEW[c[5]])
    t_large = time.time() - t0
    t0 = time.time()
    for r in r32:
        gen([load_img(r["image"])], MAXNEW[r.get("unit", "word")])
    torch.cuda.synchronize()
    meta["peak_mem_batch1_GiB"] = round(torch.cuda.max_memory_allocated() / 2**30, 3)
    meta["peak_mem_reserved_batch1_GiB"] = round(torch.cuda.max_memory_reserved() / 2**30, 3)
    meta["latency_batch1_s_mean_32_V1"] = round((time.time() - t0) / max(len(r32), 1), 4)
    meta["latency_batch1_s_largest_inputs"] = round(t_large / max(len(largest), 1), 4)
    meta["peak_mem_largest_inputs"] = [{"id": c[1], "set": c[2], "width": c[3], "height": c[4], "unit": c[5]} for c in largest]
    meta["peak_mem_batch1_how"] = ("clarification H6: batch 1 on the 3 largest validation inputs (pixels) of the sets of this "
                                   "call, then 32 V1 crops; before any batch-16 pass, after empty_cache and "
                                   "reset_peak_memory_stats; gate G uses peak_mem_reserved_batch1_GiB (reader only; detector "
                                   "not added)")
for e in todo:
    name = e["name"]
    pad0 = PADDED["n"]
    rows = vc.read_manifest(e["manifest"])
    bad = [r for r in rows if str(r.get("split", "")).lower() not in VAL]
    if args.limit:
        rows = rows[: args.limit]
    if bad:
        refused.append({"name": name, "why": "%d manifest rows with split != val" % len(bad)})
        say(f"REFUSED {name}: {len(bad)} rows not val")
        continue
    units = sorted(set(r.get("unit", "word") for r in rows))
    if any(u not in MAXNEW for u in units):
        refused.append({"name": name, "why": "unit %s has no fixed token cap here (needs a manual decision)" % units})
        say(f"SKIPPED {name}: units {units}")
        continue
    raw_path = os.path.join(out_dir, name + ".raw.jsonl")
    done = {}
    if os.path.exists(raw_path):
        for line in open(raw_path, encoding="utf-8"):
            try:
                d = json.loads(line)
                done[d["id"]] = d
            except Exception:  # noqa: BLE001
                pass
    for r in rows:
        if r["id"] in done:
            CACHE[(r["image"], r.get("unit", "word"))] = done[r["id"]]
    pend = [r for r in rows if r["id"] not in done]
    reused = 0
    with open(raw_path, "a", encoding="utf-8") as fp:
        for r in pend:
            c = CACHE.get((r["image"], r.get("unit", "word")))
            if c is not None:
                x = dict(c, id=r["id"], reused_from_other_set=True)
                fp.write(json.dumps(x, ensure_ascii=False) + "\n")
                done[r["id"]] = x
                reused += 1
    pend = [r for r in pend if r["id"] not in done]
    pend.sort(key=lambda r: r.get("unit", "word"))
    say(f"{name}: {len(rows)} rows, {len(done)} done ({reused} reused from another set), units {units}")
    timing = []
    with open(raw_path, "a", encoding="utf-8") as fp:
        for b in range(0, len(pend), args.batch):
            if time.time() >= deadline:
                say("deadline reached; stopping")
                break
            bb = pend[b:b + args.batch]
            u = bb[0].get("unit", "word")
            same = [r for r in bb if r.get("unit", "word") == u]
            t0 = time.time()
            if use_cuda:
                torch.cuda.synchronize()
            try:
                recs = gen([load_img(r["image"]) for r in same], MAXNEW[u])
            except Exception as ex:  # noqa: BLE001
                say(f"batch failed {repr(ex)[:150]}; one at a time")
                recs = []
                for r in same:
                    try:
                        recs += gen([load_img(r["image"])], MAXNEW[u])
                    except Exception as ex2:  # noqa: BLE001
                        recs.append({"raw": "", "n_new": 0, "hit_cap": False, "error": repr(ex2)[:200]})
            if use_cuda:
                torch.cuda.synchronize()
            timing.append((len(same), time.time() - t0))
            for r, x in zip(same, recs):
                x["id"] = r["id"]
                fp.write(json.dumps(x, ensure_ascii=False) + "\n")
                done[r["id"]] = x
                CACHE[(r["image"], u)] = x
            fp.flush()
            rest = [r for r in bb if r.get("unit", "word") != u]
            if rest:
                recs = gen([load_img(r["image"]) for r in rest], MAXNEW[rest[0].get("unit", "word")])
                for r, x in zip(rest, recs):
                    x["id"] = r["id"]
                    fp.write(json.dumps(x, ensure_ascii=False) + "\n")
                    done[r["id"]] = x
                    CACHE[(r["image"], r.get("unit", "word"))] = x
                fp.flush()
    complete = all(r["id"] in done for r in rows)
    refs = [r["text"] for r in rows if r["id"] in done]
    raws = [done[r["id"]]["raw"] for r in rows if r["id"] in done]
    vc.write_pred_tsv(os.path.join(out_dir, name + ".tsv"), rows, done, pp.plain_ref, pp.plain_output)
    sc = pp.score(refs, raws)
    n_changed = sum(1 for x in raws if pp.pp_output(x) != pp.plain_output(x))
    sc.update({"set": name, "manifest": e["manifest"], "complete": complete, "rows": len(rows), "done": len(refs),
               "postproc_changed_outputs": n_changed,
               "hit_cap_share": sum(done[r["id"]].get("hit_cap", False) for r in rows if r["id"] in done) / max(len(refs), 1),
               "errors": sum(1 for r in rows if r["id"] in done and "error" in done[r["id"]])})
    json.dump(sc, open(os.path.join(out_dir, name + ".score.json"), "w"), indent=1)
    ms = {"complete": complete, "rows": len(rows), "done": len(refs), "plain_cer": sc["plain"]["cer"],
          "pp_cer": sc["pp"]["cer"], "plain_wer": sc["plain"]["wer"], "pp_wer": sc["pp"]["wer"],
          "postproc_changed_outputs": n_changed, "hit_cap_share": sc["hit_cap_share"],
          "padded_images_this_call": PADDED["n"] - pad0}
    if is_v1(e) and len(timing) > 1:
        n = sum(t[0] for t in timing[1:])
        s = sum(t[1] for t in timing[1:])
        if args.batch == 16 and n:
            meta["images_per_second_batch16_V1"] = round(n / s, 3)
            meta["images_per_second_note"] = "H100, not RTX 5090; image loading + processor + generate, first batch excluded"
    meta["sets"][name] = ms
    say(f"{name}: plain CER {sc['plain']['cer']} pp CER {sc['pp']['cer']} complete {complete}")
    meta["refused_sets"] = refused
    meta["wall_seconds_this_call"] = round(time.time() - t_all, 1)
    meta["updated_utc"] = utc()
    json.dump(meta, open(meta_path, "w"), indent=1, ensure_ascii=False)
    if complete and time.time() < deadline:
        cap_retry(e, name, rows, done)
    if time.time() >= deadline:
        break
json.dump(meta, open(meta_path, "w"), indent=1, ensure_ascii=False)
say("done", json.dumps(meta.get("sets", {})))