"""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. LOOPGUARD-1 copy (scripts/r5_loopguard): identical to scripts/r5_onemodel/om_common.py except generate_pages' two opt-in keyword arguments and _generate_pages_lg; om_text and om_guard are imported from this folder. """ 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, gen_overrides=None, guard=None): """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. LOOPGUARD-1: gen_overrides (dict set on the copied GenerationConfig, arm A1: {'no_repeat_ngram_size': 20}) and guard (dict k, p_max, t_line, observe_only: arm A2, or A0 observe-only) are opt-in; with both None the body below runs exactly as in scripts/r5_onemodel/om_common.py.""" if gen_overrides is not None or guard is not None: return _generate_pages_lg(model, proc, tok, imgs, max_new, tmpl_kw, gc, stop_set, dev, instr, gen_overrides, guard) 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 def _generate_pages_lg(model, proc, tok, imgs, max_new, tmpl_kw, gc, stop_set, dev, instr, gen_overrides, guard): """LOOPGUARD-1 arms. Same prompt, processor size, device/dtype move, greedy config copy and stop rule as generate_pages; adds the overrides and/or the guard. Per image additionally: new_ids (generated ids up to and including the first stop token), guard_events, raw_unprocessed (decode of new_ids) and, for the enforced guard, raw = decode(clean_ids(...)).""" import om_guard as G from transformers import LogitsProcessorList 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) g = copy.deepcopy(gc) g.max_new_tokens = int(max_new) for k, v in (gen_overrides or {}).items(): assert hasattr(g, k), "GenerationConfig has no field %s" % k setattr(g, k, v) kw = {} lg = None stops = list(g.eos_token_id) if isinstance(g.eos_token_id, (list, tuple)) else [g.eos_token_id] ids_info = G.token_ids(tok, stops, stop_set) if guard is not None: lg = G.LineLoopGuard(prompt_len=enc["input_ids"].shape[1], batch=len(imgs), ids=ids_info, k=guard["k"], p_max=guard["p_max"], t_line=guard["t_line"], observe_only=guard["observe_only"]) kw["logits_processor"] = LogitsProcessorList([lg]) with torch.inference_mode(): out = model.generate(**enc, generation_config=g, **kw) 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] raw_u = tok.decode(ids, skip_special_tokens=False, clean_up_tokenization_spaces=False) ev = lg.events(r) if lg is not None else [] raw = raw_u if lg is not None and not guard["observe_only"] and ev: raw = tok.decode(G.clean_ids(ids, ev, ids_info["newline"], ids_info["loc0"], ids_info["loc1"], ids_info["end_ids"]), skip_special_tokens=False, clean_up_tokenization_spaces=False) recs.append({"raw": raw, "n_new": cut, "hit_cap": (not hit) and cut >= int(max_new), "n_visual": nvis[r], "new_ids": ids, "guard_events": ev, "raw_unprocessed": raw_u, "guard_masked_steps_batch": (lg.masked_steps if lg is not None else None)}) return recs