File size: 20,235 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 | """R5 VLMA harness, shared parts: model registry, loading with native transformers classes, ONE prompt builder used
by training and evaluation, the end-of-answer token, and the training batch with loss on target tokens only.
Design (VLMA plan, amendment 3.2 C1):
- instruction for every model: INSTR below, one image, the model's own processor chat template, generation prompt on;
- target = label text tokens + the token(s) that end the assistant turn in that model's chat template, up to and
including the first token that generation stops on (falls back to the tokenizer's end-of-sequence token);
- loss on target tokens only (labels -100 on prompt and padding);
- trust_remote_code is never set; safetensors only; no token in the environment.
"""
import csv
import os
import unicodedata
for _k in ("HF_TOKEN", "HUGGING_FACE_HUB_TOKEN"):
os.environ.pop(_k, None)
os.environ.setdefault("HF_HUB_OFFLINE", "1")
os.environ.setdefault("TOKENIZERS_PARALLELISM", "false")
import torch
import transformers
from PIL import Image
# Performance only: the cuDNN backend of scaled_dot_product_attention builds a new execution plan for every new
# sequence shape (7-9 ms CPU per call; 20 s of a 22 s MiniCPM-OCR step in the smoke profile of 2026-11-20,
# DATA/outputs/r5/vlma/runs/smoke_minicpm_ocr_1_0/smoke/profile_step4.txt). Variable crop sizes give new shapes every
# step, so the flash / memory-efficient / math backends are used instead.
torch.backends.cuda.enable_cudnn_sdp(False)
SDPA_NOTE = "cuDNN SDPA backend disabled (torch.backends.cuda.enable_cudnn_sdp(False)); flash / mem-efficient / math backends"
INSTR ="Transcribe the text in this image exactly."
# same overrides as the J2 screen (CODE/scripts/j2/run_screen.py), which were checked there
CARD_CLASS = {"lightonocr_3_0_8b": "Qwen3_5ForConditionalGeneration", "lightonocr_3_1b": "LightOnOcrForConditionalGeneration"}
CARD_PROC = {"lightonocr_3_1b": "LightOnOcrProcessor"}
TWO_STEP = {"granite_docling_258m"} # card: apply_chat_template(text) then processor(text, images)
PER_TOKEN_KEYS = ("token_type_ids", "mm_token_type_ids")
SENTINEL = "QZXSENTINELQZX"
def read_registry(path):
with open(path, encoding="utf-8", newline="") as f:
return {r["short"]: r for r in csv.DictReader(f, delimiter="\t")}
def read_manifest(path):
"""Shared R5 manifest: id, image, text, lang, script, kind, source, split, group, unit (header required)."""
rows = []
with open(path, encoding="utf-8", newline="") as f:
rd = csv.DictReader(f, delimiter="\t", quoting=csv.QUOTE_NONE)
for r in rd:
r["text"] = unicodedata.normalize("NFC", r.get("text") or "")
rows.append(r)
return rows
def load_processor(short, path):
pcls = getattr(transformers, CARD_PROC.get(short, ""), None) or transformers.AutoProcessor
proc = pcls.from_pretrained(path, trust_remote_code=False)
tok = getattr(proc, "tokenizer", proc)
if getattr(tok, "pad_token_id", None) is None:
tok.pad_token = tok.eos_token
return proc, tok
def model_class(short):
cls = getattr(transformers, CARD_CLASS[short], None) if short in CARD_CLASS else None
return cls or transformers.AutoModelForImageTextToText
def load_model(short, path, dtype, info=False):
assert not any(f.endswith(".py") for f in os.listdir(path)), "a .py file in the model folder"
out = model_class(short).from_pretrained(path, dtype=dtype, trust_remote_code=False, use_safetensors=True,
attn_implementation="sdpa", output_loading_info=info)
return out
def export_key_check(model, folder):
"""After save_pretrained: every state-dict key of the model must be in the saved safetensors files (or be tied to
a saved key), and no saved key may be unknown to the model. Returns (missing, unexpected)."""
import glob as _glob
from safetensors import safe_open
saved = set()
for fn in _glob.glob(os.path.join(folder, "*.safetensors")):
with safe_open(fn, "pt") as f:
saved |= set(f.keys())
sd = model.state_dict()
by_ptr = {}
for k, v in sd.items():
by_ptr.setdefault((v.data_ptr(), tuple(v.shape)), []).append(k)
missing = [k for k in sd if k not in saved and not any(o in saved for o in by_ptr[(sd[k].data_ptr(), tuple(sd[k].shape))])]
unexpected = sorted(k for k in saved if k not in sd)
return missing, unexpected
def template_kwargs(proc, tok):
"""enable_thinking=False for every model whose chat template uses that variable (the Qwen3.5-type readers);
others get no extra variable."""
texts = []
for o in (proc, tok):
ct = getattr(o, "chat_template", None)
if isinstance(ct, dict):
texts.extend(str(v) for v in ct.values())
elif ct:
texts.append(str(ct))
return {"enable_thinking": False} if any("enable_thinking" in t for t in texts) else {}
def prompt_batch(short, proc, imgs, tmpl_kw):
"""The one prompt builder (training and evaluation): user turn = one image + INSTR, generation prompt on."""
if short in TWO_STEP:
convs = [[{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": INSTR}]}] for _ in imgs]
texts = [proc.apply_chat_template(c, add_generation_prompt=True, **tmpl_kw) for c in convs]
return proc(text=texts, images=[[im] for im in imgs], return_tensors="pt", padding=True)
convs = [[{"role": "user", "content": [{"type": "image", "image": im}, {"type": "text", "text": INSTR}]}] for im in imgs]
return proc.apply_chat_template(convs, add_generation_prompt=True, tokenize=True, return_dict=True,
return_tensors="pt", padding=True, **tmpl_kw)
def rendered_prompt(short, proc, tmpl_kw):
conv = [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": INSTR}]}]
return proc.apply_chat_template(conv, add_generation_prompt=True, tokenize=False, **tmpl_kw)
def stop_ids(model_gen_cfg, tok):
s = set()
for e in (getattr(model_gen_cfg, "eos_token_id", None), getattr(tok, "eos_token_id", None)):
if isinstance(e, (list, tuple)):
s.update(int(x) for x in e)
elif e is not None:
s.add(int(e))
return s
def answer_suffix(short, proc, tok, gen_cfg, tmpl_kw):
"""Token ids that end an assistant answer in this model's chat template, up to and including the first token in
the generation stop set. Returns (ids, how, template_suffix_text)."""
stops = stop_ids(gen_cfg, tok)
suffix = None
for content in ([{"type": "text", "text": SENTINEL}], SENTINEL):
conv = [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": INSTR}]},
{"role": "assistant", "content": content}]
try:
txt = proc.apply_chat_template(conv, add_generation_prompt=False, tokenize=False, **tmpl_kw)
except Exception: # noqa: BLE001
continue
if SENTINEL in txt:
tail = txt.split(SENTINEL, 1)[1]
# a template that prints list content as a Python repr (HunyuanOCR) leaks "'}]" after the text: use the
# plain-string content form instead
if tail.startswith(("'}", '"}')):
continue
suffix = tail
break
if suffix:
ids = tok(suffix, add_special_tokens=False).input_ids
for j, t in enumerate(ids):
if t in stops:
return ids[: j + 1], "chat template turn end (first stop token included)", suffix
if getattr(tok, "eos_token_id", None) is not None and tok.eos_token_id in stops:
return [int(tok.eos_token_id)], "tokenizer eos (template suffix has no stop token)", suffix
return [sorted(stops)[0]], "first generation-config stop id (fallback)", suffix
def target_ids(tok, label, suffix_ids):
ids = tok(label, add_special_tokens=False).input_ids if label else []
return list(ids) + list(suffix_ids)
def build_train_batch(short, proc, tok, imgs, labels, suffix_ids, tmpl_kw):
"""Prompt batch from the processor (its own pixel format), then label ids + suffix appended at the id level,
right padding. Returns (model_inputs dict, labels tensor, n_target_tokens)."""
enc = prompt_batch(short, proc, imgs, tmpl_kw)
ids, am = enc["input_ids"], enc["attention_mask"]
B = ids.shape[0]
extra = [k for k in enc.keys() if k in PER_TOKEN_KEYS and torch.is_tensor(enc[k]) and tuple(enc[k].shape[:2]) == tuple(ids.shape)]
tg = [target_ids(tok, lab, suffix_ids) for lab in labels]
lens = [int(am[i].sum()) + len(tg[i]) for i in range(B)]
L = max(lens)
pad = tok.pad_token_id
new_ids = torch.full((B, L), pad, dtype=ids.dtype)
new_am = torch.zeros((B, L), dtype=am.dtype)
lab = torch.full((B, L), -100, dtype=torch.long)
new_extra = {k: torch.zeros((B, L) + tuple(enc[k].shape[2:]), dtype=enc[k].dtype) for k in extra}
for i in range(B):
m = am[i].bool()
p = ids[i][m]
n = p.shape[0]
t = torch.tensor(tg[i], dtype=ids.dtype)
new_ids[i, :n] = p
new_ids[i, n:n + len(t)] = t
new_am[i, :n + len(t)] = 1
lab[i, n:n + len(t)] = t.long()
for k in extra:
new_extra[k][i, :n] = enc[k][i][m]
out = {k: v for k, v in enc.items()}
out["input_ids"] = new_ids
out["attention_mask"] = new_am
out.update(new_extra)
return out, lab, sum(len(t) for t in tg)
def target_loss_sum(logits, labels):
"""Sum of token cross-entropies over target positions (next-token shift), in fp32."""
lg = logits[:, :-1, :]
lb = labels[:, 1:].to(lg.device)
m = lb != -100
sel = lg[m].float()
return torch.nn.functional.cross_entropy(sel, lb[m], reduction="sum"), int(m.sum())
# ---------------- minimum patch grid (bug fix of 2026-11-21, LightOnOCR-3-1B crash at step 1414) ----------------
# arm -> kernel of its vision patch merger, for arms whose image processor can return a patch grid smaller than that
# kernel (the merger then crashes: unfold over a 1-row grid). Filled from the probe (DATA/outputs/r5/vlma/probe_grid.json).
# For every other arm the padding below is a no-op.
GRID_PAD = {"lightonocr_3_1b": 2, # probe: Pixtral resize gives 1-row grids (e.g. sequence row 45,241, 395x13 px -> 1x29)
"lightonocr_3_0_8b": 2} # probe: never below 2x2 (Qwen-style minimum size); listed as a guard, expected no-op
def proc_grid(proc, img):
"""[rows, cols] of the patch grid the image processor makes for one image (before merging), or None."""
ip = getattr(proc, "image_processor", None)
if ip is None:
return None
out = ip(images=[img], return_tensors="pt")
if "image_grid_thw" in out:
t, h, w = [int(x) for x in out["image_grid_thw"][0].tolist()]
return [h, w]
if "image_sizes" in out:
h, w = [int(x) for x in out["image_sizes"][0].tolist()]
ps = getattr(ip, "patch_size", 14)
if isinstance(ps, dict):
ph, pw = int(ps.get("height", 14)), int(ps.get("width", 14))
else:
ph = pw = int(ps)
return [h // ph, w // pw]
return None
def pad_min_grid(short, proc, img):
"""White, centred padding of the too-small side(s) up to the SMALLEST size whose patch grid reaches the merger
kernel; returns (image, 1 if padded else 0). Only for arms in GRID_PAD; an image whose grid already fits is returned
unchanged. Pre-filter (exact for the Pixtral resize of LightOnOCR-3-1B, longest edge 1540, patch 14): an image with
aspect ratio below 8 and both sides above 64 px cannot give a grid below 2 x 2, so it is not checked."""
import math
k = GRID_PAD.get(short)
if not k:
return img, 0
w, h = img.size
if max(w, h) / max(1, min(w, h)) < 8 and min(w, h) > 64:
return img, 0
g = proc_grid(proc, img)
if g is None or (g[0] >= k and g[1] >= k):
return img, 0
need_h, need_w = g[0] < k, g[1] < k
def dims(t):
return (max(w, int(math.ceil(w * t))) if need_w else w, max(h, int(math.ceil(h * t))) if need_h else h)
def padded(nw, nh):
c = Image.new("RGB", (nw, nh), (255, 255, 255))
c.paste(img, ((nw - w) // 2, (nh - h) // 2))
return c
def ok(t):
gg = proc_grid(proc, padded(*dims(t)))
return gg is not None and gg[0] >= k and gg[1] >= k
hi, n = 2.0, 0
while not ok(hi) and n < 20:
hi *= 2.0
n += 1
lo = 1.0
for _ in range(16):
mid = (lo + hi) / 2.0
if ok(mid):
hi = mid
else:
lo = mid
return padded(*dims(hi)), 1
MAXNEW = {"word": 48, "line": 192}
CONF_DEF = ("conf = mean natural-log probability of the generated tokens, from the processed scores of each greedy step "
"(generate(output_scores=True)); tokens counted up to and including the first stop token, or all "
"max_new_tokens if none; conf_min = the minimum of the same per-token log-probabilities; n_tokens = that "
"token count; hit_cap = 1 if generation reached max_new_tokens without a stop token, else 0")
def gen_setup(model, tok, suffix_ids=None):
"""Greedy generation config shared by evaluation and learning-curve points. Stops on the generation-config end
ids, the tokenizer eos and the trained answer-end token."""
import copy
gc = copy.deepcopy(model.generation_config)
gc.do_sample = False
gc.num_beams = 1
gc.repetition_penalty = 1.0
gc.no_repeat_ngram_size = 0
gc.temperature = None
gc.top_p = None
gc.top_k = None
gc.use_cache = True
if gc.pad_token_id is None:
gc.pad_token_id = tok.pad_token_id
stops = stop_ids(model.generation_config, tok)
if suffix_ids:
stops.add(int(suffix_ids[-1]))
gc.eos_token_id = sorted(stops)
stop_set = set(stops)
if gc.pad_token_id is not None:
stop_set.add(gc.pad_token_id)
return gc, sorted(stops), stop_set
def generate_batch(short, model, proc, tok, imgs, max_new, tmpl_kw, gc, stop_set, dev, temperature=None):
"""Greedy reading of a batch (tokenizer padding side must be 'left'). Returns per image: raw text, n_new,
hit_cap, conf, conf_min (CONF_DEF). temperature: sampling at that temperature instead of greedy (top-k and top-p
off), used only by the cap-retry rule (r5_posttrain_experiment.txt); conf is then taken from the processed
(temperature-scaled) scores of the sampled path."""
import copy
inputs = prompt_batch(short, proc, imgs, tmpl_kw)
am = inputs["attention_mask"]
assert bool(am[:, -1].all()), "padding is not on the left"
inputs = inputs.to(dev, dtype=torch.bfloat16)
g = copy.deepcopy(gc)
g.max_new_tokens = max_new
if temperature:
g.do_sample = True
g.temperature = float(temperature)
g.top_k = None
g.top_p = None
with torch.inference_mode():
out = model.generate(**inputs, generation_config=g, output_scores=True, return_dict_in_generate=True)
new = out.sequences[:, inputs["input_ids"].shape[1]:]
lp = torch.stack([torch.log_softmax(s.float(), dim=-1).gather(1, new[:, t:t + 1]).squeeze(1)
for t, s in enumerate(out.scores[: new.shape[1]])], dim=1).cpu()
texts = tok.batch_decode(new, skip_special_tokens=True, clean_up_tokenization_spaces=False)
recs = []
for r in range(new.shape[0]):
row = new[r].tolist()
n_new, hit = len(row), False
for j, t in enumerate(row):
if t in stop_set:
n_new, hit = j + 1, True
break
v = lp[r, :n_new]
recs.append({"raw": texts[r], "n_new": n_new, "hit_cap": (not hit) and n_new >= max_new,
"conf": round(float(v.mean()), 6) if n_new else None,
"conf_min": round(float(v.min()), 6) if n_new else None})
return recs
def sample_n(short, model, proc, tok, imgs, max_new, tmpl_kw, gc, stop_set, dev, n, temperature):
"""n samples per image at the given temperature (top-k and top-p off). Returns, per image, a list of n dicts
{ids: generated token ids up to and including the first stop token (all ids if none), text, hit_cap}.
Tokenizer padding side must be 'left'."""
import copy
inputs = prompt_batch(short, proc, imgs, tmpl_kw)
assert bool(inputs["attention_mask"][:, -1].all()), "padding is not on the left"
inputs = inputs.to(dev, dtype=torch.bfloat16)
g = copy.deepcopy(gc)
g.max_new_tokens = max_new
g.do_sample = True
g.temperature = float(temperature)
g.top_k = None
g.top_p = None
g.num_return_sequences = int(n)
with torch.inference_mode():
out = model.generate(**inputs, generation_config=g)
new = out[:, inputs["input_ids"].shape[1]:].tolist()
res = []
for i in range(len(imgs)):
grp = []
for row in new[i * n:(i + 1) * n]:
cut, hit = len(row), False
for j, t in enumerate(row):
if t in stop_set:
cut, hit = j + 1, True
break
ids = row[:cut]
grp.append({"ids": ids, "text": tok.decode(ids, skip_special_tokens=True, clean_up_tokenization_spaces=False),
"hit_cap": not hit})
res.append(grp)
return res
def build_batch_ids(short, proc, tok, imgs, tgt_lists, tmpl_kw):
"""As build_train_batch, but the targets are given as token-id lists (sampled outputs or label + answer end).
Returns (model inputs, labels with -100 outside the targets)."""
enc = prompt_batch(short, proc, imgs, tmpl_kw)
ids, am = enc["input_ids"], enc["attention_mask"]
B = ids.shape[0]
extra = [k for k in enc.keys() if k in PER_TOKEN_KEYS and torch.is_tensor(enc[k]) and tuple(enc[k].shape[:2]) == tuple(ids.shape)]
L = max(int(am[i].sum()) + len(tgt_lists[i]) for i in range(B))
new_ids = torch.full((B, L), tok.pad_token_id, dtype=ids.dtype)
new_am = torch.zeros((B, L), dtype=am.dtype)
lab = torch.full((B, L), -100, dtype=torch.long)
new_extra = {k: torch.zeros((B, L) + tuple(enc[k].shape[2:]), dtype=enc[k].dtype) for k in extra}
for i in range(B):
m = am[i].bool()
p = ids[i][m]
n = p.shape[0]
t = torch.tensor(list(tgt_lists[i]), dtype=ids.dtype)
new_ids[i, :n] = p
new_ids[i, n:n + len(t)] = t
new_am[i, :n + len(t)] = 1
lab[i, n:n + len(t)] = t.long()
for k in extra:
new_extra[k][i, :n] = enc[k][i][m]
out = {k: v for k, v in enc.items()}
out["input_ids"] = new_ids
out["attention_mask"] = new_am
out.update(new_extra)
return out, lab
def seq_logprobs(logits, labels):
"""Log-probabilities of the target tokens (next-token shift), in fp32, computed only at target positions.
Returns (per-row sums [B], per-row token counts [B], per-token log-probs [N], row index of each token [N])."""
lg = logits[:, :-1, :]
lb = labels[:, 1:].to(lg.device)
m = lb != -100
tok_lp = torch.log_softmax(lg[m].float(), dim=-1).gather(1, lb[m].unsqueeze(1)).squeeze(1)
rows = m.nonzero()[:, 0]
sums = torch.zeros(lg.shape[0], device=lg.device, dtype=torch.float32).index_add(0, rows, tok_lp)
return sums, m.sum(1), tok_lp, rows
def write_pred_tsv(path, rows, done, plain_ref, plain_output):
"""Shared prediction format: id, ref (N0), hyp (N0 of raw greedy output), conf, conf_min, hit_cap, n_tokens."""
def _c(x):
return "" if x is None else str(x)
with open(path, "w", encoding="utf-8") as f:
f.write("id\tref\thyp\tconf\tconf_min\thit_cap\tn_tokens\n")
for r in rows:
if r["id"] in done:
d = done[r["id"]]
f.write(f"{r['id']}\t{plain_ref(r['text'])}\t{plain_output(d['raw'])}\t{_c(d.get('conf'))}\t"
f"{_c(d.get('conf_min'))}\t{int(bool(d.get('hit_cap')))}\t{_c(d.get('n_new'))}\n")
def unique_params(model):
seen, n = set(), 0
for p in model.parameters():
if id(p) not in seen:
seen.add(id(p))
n += p.numel()
return n
|