# Copyright (c) 2026 LlamaIndex, Inc. All rights reserved. # Licensed under the OCRia-1 Model and Code License (LICENSE at the root of this repository). # This is not open-source software: see the license for permitted uses. """Teacher-forced attention of ocria over the page image, per text unit (GPU; torch + transformers imported lazily). The answer is appended as the assistant turn after the system prompt and the image-only user turn, and ONE forward pass is run. A decoder's attention at a position depends only on the tokens before it, so this is the attention the model had while writing that text (teacher forcing and the model's own decoding gave the same box quality). For each unit (a char span: a word, or a whole image reference) and each chosen (layer, head): the mean softmax over image tokens of the queries that GENERATE the unit's tokens (query i-1 predicts token i), divided by that head's total image mass for the unit; the unit's map is the sum over the chosen heads. Only Qwen3.5's full-attention layers have attention maps (the Gated DeltaNet layers have none); the probe runs inside those layers' attention call and computes q.k only for the chosen heads. """ from __future__ import annotations import numpy as np CHUNK = 256 class Grounder: def __init__(self, model_dir: str, heads: list[tuple[int, int]], system_prompt: str, device: str = "cuda"): import torch from transformers import AttentionInterface, AutoProcessor, Qwen3_5ForConditionalGeneration from transformers.integrations.sdpa_attention import sdpa_attention_forward self.torch, self.device, self.ctx = torch, device, {} self.by_layer: dict[int, list[int]] = {} for layer, head in heads: self.by_layer.setdefault(int(layer), []).append(int(head)) ctx = self.ctx def probe(module, query, key, value, attention_mask=None, scaling=None, **kwargs): out, w = sdpa_attention_forward(module, query, key, value, attention_mask=attention_mask, scaling=scaling, **kwargs) hs = self.by_layer.get(module.layer_idx) if not hs or "W" not in ctx or query.shape[2] == 1: return out, w g = query.shape[1] // key.shape[1] hsel = torch.tensor(hs, device=query.device) k = key[0, hsel // g].float() # (h, T, d): each query head's own kv head (GQA) T = k.shape[1] img, q0, W = ctx["img"], ctx["q0"], ctx["W"] acc = torch.zeros(W.shape[0], len(hs), int(img.sum()), device=query.device) for c0 in range(q0, T, CHUNK): q = query[0, hsel, c0:c0 + CHUNK].float() pos = torch.arange(c0, c0 + q.shape[1], device=query.device) s = torch.einsum("hqd,htd->hqt", q, k) * scaling s = s.masked_fill(torch.arange(T, device=query.device)[None, None, :] > pos[None, :, None], float("-inf")) p = s.softmax(-1)[..., img] acc += torch.einsum("uc,hcn->uhn", W[:, c0 - q0:c0 - q0 + q.shape[1]], p) acc = acc / acc.sum(-1, keepdim=True).clamp_min(1e-9) ctx["maps"] += acc.sum(1) return out, w AttentionInterface.register("ocria_ground_probe", probe) self.model = Qwen3_5ForConditionalGeneration.from_pretrained( model_dir, dtype=torch.bfloat16, attn_implementation="sdpa").to(device).eval() self.model.config.text_config._attn_implementation = "ocria_ground_probe" self.proc = AutoProcessor.from_pretrained(model_dir) full = [i for i, t in enumerate(self.model.config.text_config.layer_types) if t == "full_attention"] bad = sorted(set(self.by_layer) - set(full)) if bad: raise ValueError(f"heads on layers {bad}, which have no attention map (full-attention layers: {full})") self.prompt = self.proc.apply_chat_template( [{"role": "system", "content": [{"type": "text", "text": system_prompt}]}, {"role": "user", "content": [{"type": "image"}]}], add_generation_prompt=True, enable_thinking=False) def unit_maps(self, image, answer: str, units: list[tuple[int, int]]) -> tuple[np.ndarray, tuple[int, int], np.ndarray]: """(maps [U, gh, gw] float32, (gh, gw), has_tokens [U] bool) for char spans `units` of `answer`.""" torch, dev = self.torch, self.device enc = self.proc(text=[self.prompt], images=[image.convert("RGB")], return_tensors="pt") tok = self.proc.tokenizer(answer, add_special_tokens=False, return_offsets_mapping=True) ans = torch.tensor([tok["input_ids"]]) offs = tok["offset_mapping"] start = enc["input_ids"].shape[1] enc["input_ids"] = torch.cat([enc["input_ids"], ans], 1) enc["attention_mask"] = torch.cat([enc["attention_mask"], torch.ones_like(ans)], 1) if "mm_token_type_ids" in enc: enc["mm_token_type_ids"] = torch.cat([enc["mm_token_type_ids"], torch.zeros_like(ans)], 1) enc = {k: v.to(dev) for k, v in enc.items()} img = enc["input_ids"][0] == self.model.config.image_token_id thw = enc["image_grid_thw"][0].tolist() gh, gw = thw[1] // 2, thw[2] // 2 assert int(img.sum()) == gh * gw, (int(img.sum()), gh, gw) T, q0 = start + ans.shape[1], start - 1 W = torch.zeros(len(units), T - q0, device=dev) has = np.zeros(len(units), bool) tok_starts = np.array([a for a, b in offs]) if offs else np.zeros(0) tok_ends = np.array([b for a, b in offs]) if offs else np.zeros(0) for u, (s, e) in enumerate(units): t = np.nonzero((tok_starts < e) & (tok_ends > s) & (tok_ends > tok_starts))[0] if len(t): W[u, torch.as_tensor(start + t - 1 - q0, device=dev)] = 1.0 / len(t) has[u] = True self.ctx.update(W=W, img=img, q0=q0, maps=torch.zeros(len(units), gh * gw, device=dev)) try: with torch.no_grad(): self.model(**enc, use_cache=False, logits_to_keep=1) maps = self.ctx["maps"].reshape(len(units), gh, gw).float().cpu().numpy() finally: self.ctx.clear() return maps, (gh, gw), has