treoa's picture
Release 1
24aaa76
Raw History Blame Contribute Delete
6.51 kB
"""ONEMODEL pilot (design ONEMODEL-pilot-1): the torch / transformers side shared by training, page evaluation, the baseline
and the smoke. Builds on CODE/scripts/r5_vlma/vlm_common.py (the leader's loader, crop prompt builder, crop training batch,
loss and greedy set-up), which is imported unchanged; its module global INSTR (the crop instruction) is never modified here.
Page samples use their own prompt builder: the same chat template and conversation layout as vlm_common.prompt_batch, with
the instruction 'Spotting:' and processor_kwargs {'images_kwargs': {'size': {shortest_edge 112896, longest_edge 1605632}}}
(the transformers 5.23 route of ProcessorMixin.apply_chat_template -> __call__ -> _merge_kwargs), so a pre-resized page is
not shrunk to the default 1,003,520-pixel cap. check_page_grids() asserts that per sample.
"""
import copy
import os
import sys
VLMA = "/path/to/TURKIC_OCR_CODE/scripts/r5_vlma"
if VLMA not in sys.path:
sys.path.insert(0, VLMA)
HERE = os.path.dirname(os.path.abspath(__file__))
if HERE not in sys.path:
sys.path.insert(0, HERE)
import torch # noqa: E402
import om_text as T # noqa: E402
import vlm_common as vc # noqa: E402
SHORT = "paddleocr_vl_1_6"
CODE = "/path/to/TURKIC_OCR_CODE"
DATA = "/path/to/TURKIC_OCR_DATA"
LEADER = DATA + "/checkpoints/r5/paddleocr_vl_1_6/leader"
BASE = DATA + "/hf_cache/j2_models/paddleocr_vl_1_6"
PAGE_PROC_KW = {"images_kwargs": {"size": {"shortest_edge": T.SPOT_MIN_PIXELS, "longest_edge": T.SPOT_MAX_PIXELS}}}
def load(path, dtype=torch.bfloat16, info=False):
proc, tok = vc.load_processor(SHORT, path)
m = vc.load_model(SHORT, path, dtype, info=info)
return proc, tok, m
def page_prompt_batch(proc, imgs, tmpl_kw, instr=T.SPOT_PROMPT):
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, processor_kwargs=copy.deepcopy(PAGE_PROC_KW), **tmpl_kw)
def check_page_grids(enc, imgs):
"""every page image must reach the model at its own size: image_grid_thw row == [1, H/14, W/14]"""
g = enc["image_grid_thw"].tolist()
assert len(g) == len(imgs), "grid rows %d != images %d" % (len(g), len(imgs))
for row, im in zip(g, imgs):
w, h = im.size
want = [1, h // 14, w // 14]
if [int(x) for x in row] != want:
raise AssertionError("page image %dx%d was resized by the processor: grid %s, expected %s" % (w, h, row, want))
def page_train_batch(proc, tok, imgs, tgt_lists, tmpl_kw):
"""As vlm_common.build_batch_ids (right padding, labels -100 outside the targets), with the page prompt builder.
tgt_lists: target token ids INCLUDING the end token."""
enc = page_prompt_batch(proc, imgs, tmpl_kw)
check_page_grids(enc, imgs)
ids, am = enc["input_ids"], enc["attention_mask"]
B = ids.shape[0]
extra = [k for k in enc.keys() if k in vc.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 label_mask_report(lab, tgt_lists, input_ids):
"""For each row: the label positions hold exactly the target ids (+ end token) and sit at the end of the
attended sequence; every other position is -100. Returns a list of dicts."""
rep = []
for r in range(lab.shape[0]):
pos = (lab[r] != -100).nonzero().flatten().tolist()
vals = lab[r][lab[r] != -100].tolist()
ok_vals = vals == list(tgt_lists[r])
contiguous = pos == list(range(pos[0], pos[0] + len(pos))) if pos else False
ids_match = input_ids[r, pos].tolist() == vals if pos else False
rep.append({"n_label_positions": len(pos), "n_target_ids": len(tgt_lists[r]), "labels_equal_target_plus_end": ok_vals,
"contiguous": contiguous, "input_ids_equal_labels": ids_match, "prompt_positions_masked": int((lab[r][:pos[0]] == -100).sum()) == pos[0] if pos else False})
return rep
def to_dev(inp, dev):
out = {}
for k, v in inp.items():
if torch.is_tensor(v):
v = v.to(dev)
if v.is_floating_point():
v = v.to(torch.bfloat16)
out[k] = v
return out
def generate_pages(model, proc, tok, imgs, max_new, tmpl_kw, gc, stop_set, dev, instr=T.SPOT_PROMPT):
"""Greedy page reading (tokenizer padding side must be 'left'). Returns per image: raw (decoded up to and including the
first stop token, special tokens KEPT), n_new, hit_cap, n_visual."""
enc = page_prompt_batch(proc, imgs, tmpl_kw, instr=instr)
check_page_grids(enc, imgs)
assert bool(enc["attention_mask"][:, -1].all()), "padding is not on the left"
nvis = [int(x[0] * x[1] * x[2]) // 4 for x in enc["image_grid_thw"].tolist()]
enc = enc.to(dev, dtype=torch.bfloat16) # as vlm_common.generate_batch: floating tensors to bf16 only
g = copy.deepcopy(gc)
g.max_new_tokens = int(max_new)
with torch.inference_mode():
out = model.generate(**enc, generation_config=g)
new = out[:, enc["input_ids"].shape[1]:].tolist()
recs = []
for r, row in enumerate(new):
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]
recs.append({"raw": tok.decode(ids, skip_special_tokens=False, clean_up_tokenization_spaces=False), "n_new": cut,
"hit_cap": (not hit) and cut >= int(max_new), "n_visual": nvis[r]})
return recs