"""Adapter: tiiuae/Falcon-OCR (maker code, pinned revision 0bc28f89c90fbe8bdb063097fab144d4ce4c19b5). What the maker code gives: an inference-only forward (needs a KV cache, FlexAttention block masks built under inference_mode, and a Triton FFN kernel without a backward). So training uses a loss wrapper written here: TRAINING FORWARD (own code, same weights, same maths): - prompt: the maker's own tokenize_inputs() with the maker's prompt layout "<|image|>{instruction}\\n<|OCR_PLAIN|>", our instruction; target = label tokens + <|end_of_text|> (the tokenizer's eos, config.eos_id 11; one of the two stop tokens of the maker's decode loop). Left padding with <|pad|> as in the maker's process_batch(). - images: the maker's resize_image_if_necessary(min 64, max 1536 = generate() defaults) and ImageProcessor; patches padded to the largest image of the micro-batch instead of 1536x1536 (only valid patches are used; same result). - positions: the maker's get_pos_thw(); rotary: the maker's apply_3d_rotary_emb() and golden 2D frequencies. - attention mask: the maker's own mask_mod functions (causal AND document AND non-left-pad) OR image-prefix, evaluated on a dense (B,S,S) grid; rows with no allowed key (left pads) may attend to themselves only (they carry no loss and no real token attends to them). - attention: eager softmax attention with scale 1/sqrt(head_dim), plus the maker's sink scaling sigmoid(lse - sinks) through the maker's _post_attention(); FlexAttention's lse is the natural-log logsumexp of the scaled scores. - FFN: the maker's interleaved w13 split [gate, up, gate, up, ...] -> relu(gate)^2 * up in plain PyTorch (the Triton kernel computes exactly this but has no backward). - loss: mean next-token cross-entropy over target tokens. A GPU check (check_equivalence) compares the logits of this forward with the maker's forward on one batch. DECODING: the maker's own _generate_batch() (KV cache, compiled FlexAttention, Triton FFN), greedy, weights cast to bf16 as in the maker's README, with our instruction in the maker's prompt layout. """ import copy import importlib import math import sys import einops as E import torch import torch.nn.functional as F from torch.utils.checkpoint import checkpoint from transformers import AutoModelForCausalLM from .common import (INSTRUCTION, assert_no_token_env, autocast, target_loss_sum, fresh_builder, master_dtype, remote_files_check, restore_nonpersistent_buffers) NOTES = __doc__ class Adapter: NOTES = NOTES def __init__(self, model_dir, device, precision): assert_no_token_env() remote_files_check(model_dir) self.device = device self.model = AutoModelForCausalLM.from_pretrained(model_dir, trust_remote_code=True, dtype=master_dtype(precision), use_safetensors=True) cls, cfg = type(self.model), copy.deepcopy(self.model.config) fixed = restore_nonpersistent_buffers(self.model, fresh_builder(cls, cfg, model_dir)) self.NOTES = NOTES + "\nnon-persistent buffers restored after loading: " + ", ".join(fixed) self.model.to(device) self.model._weights_fused = False self.model._ensure_device_buffers() # recompute freqs_cis (non-persistent, lost by meta-device loading) pkg = type(self.model).__module__.rsplit(".", 1)[0] self.mp = importlib.import_module(pkg + ".processing_falcon_ocr") self.ma = importlib.import_module(pkg + ".attention") self.mr = importlib.import_module(pkg + ".rope") self.tok = self.model._get_tokenizer() self.pad_id = self.tok.convert_tokens_to_ids("<|pad|>") self.model._pad_token_id = self.pad_id self.eos_id = self.model.config.eos_id assert self.tok.convert_ids_to_tokens(self.eos_id) == "<|end_of_text|>" self.prompt = f"<|image|>{INSTRUCTION}\n<|OCR_PLAIN|>" self.gc = False self.min_dim, self.max_dim = 64, 1536 def enable_gradient_checkpointing(self): self.gc = True # ---- inputs ------------------------------------------------------------------------------------------------- def _build(self, images, texts): c = self.model.config proc = self.mp.ImageProcessor(16, 1) seqs, labs, pix = [], [], [] for im, tx in zip(images, texts): im = self.mp.resize_image_if_necessary(im, self.min_dim, self.max_dim) pv = proc.preprocess(images=[im]) ids, sel = self.mp.tokenize_inputs(self.prompt, pv, self.tok, c, 16, 1, c.max_seq_len) tgt = self.target_ids(tx) seqs.append(torch.cat([ids, torch.tensor(tgt, dtype=torch.long)])) labs.append(torch.tensor([-100] * len(ids) + tgt, dtype=torch.long)) pix.extend(sel) tokens = torch.nn.utils.rnn.pad_sequence(seqs, batch_first=True, padding_value=self.pad_id, padding_side="left") labels = torch.nn.utils.rnn.pad_sequence(labs, batch_first=True, padding_value=-100, padding_side="left") mh = max(p.shape[1] for p in pix) mw = max(p.shape[2] for p in pix) mh, mw = math.ceil(mh / 16) * 16, math.ceil(mw / 16) * 16 pr = proc.batch_images_with_mask(pix, mh, mw) pos_t, pos_hw = self.mp.get_pos_thw(tokens, pr["padding_mask"], c, 16, pad_token_id=self.pad_id) return tokens, labels, pr["pixel_values"], pr["padding_mask"], pos_t, pos_hw def _dense_mask(self, tokens): c = self.model.config B, S = tokens.shape causal = self.ma.and_masks(self.ma.get_causal_mask_mod(), self.ma.get_document_mask_mod(tokens, c.eos_id), self.ma.get_non_left_pad_mask_mod(tokens, self.pad_id)) img = self.ma.get_image_prefix_mask_mod(tokens, c.image_cls_token_id, c.img_end_id) mod = self.ma.or_masks(img, causal) b = torch.arange(B, device=tokens.device)[:, None, None] q = torch.arange(S, device=tokens.device)[None, :, None] kv = torch.arange(S, device=tokens.device)[None, None, :] h = torch.zeros((), dtype=torch.long, device=tokens.device) m = mod(b, h, q, kv) # (B,S,S) bool empty = ~m.any(-1) if empty.any(): eye = torch.eye(S, dtype=torch.bool, device=tokens.device)[None] m = m | (empty[:, :, None] & eye) return m # ---- training forward (own code over the maker's modules) ---------------------------------------------------- def _layer(self, layer, x, mask, freqs_cis, freqs_golden, pos_hw): att = layer.attention xq, xk, xv = att._pre_attention_qkv(x) xq, xk = self.mr.apply_3d_rotary_emb(xq, xk, freqs_cis, freqs_golden, pos_hw) q, k, v = (t.transpose(1, 2) for t in (xq, xk, xv)) # b h s d scale = 1.0 / math.sqrt(q.size(-1)) s = torch.matmul(q.float(), k.float().transpose(-1, -2)) * scale s = s.masked_fill(~mask[:, None], float("-inf")) lse = torch.logsumexp(s, dim=-1) p = torch.exp(s - lse[..., None]) out = torch.matmul(p.to(v.dtype), v) x = x + att._post_attention(out, lse) # lse stays fp32, as FlexAttention returns it ff = layer.feed_forward h = F.rms_norm(x, (x.size(-1),)) w13 = ff.w13(h) gate, up = w13[..., 0::2], w13[..., 1::2] x = x + ff.w2(torch.relu(gate).square() * up) return x def logits(self, tokens, pixel_values, pixel_mask, pos_t, pos_hw): m = self.model c = m.config d = self.device tokens, pixel_values, pixel_mask = tokens.to(d), pixel_values.to(d), pixel_mask.to(d) pos_t, pos_hw = pos_t.to(d), pos_hw.to(d) mask = self._dense_mask(tokens) h = m.tok_embeddings(tokens) pv = pixel_values.to(m.img_projector.weight.dtype) # same as the maker's forward + _scatter_img_tokens_with_projector, with the projector output cast to the # embedding dtype (under autocast the Linear returns bf16 while the fp32 embedding table returns fp32) patches = E.rearrange(pv, "n (t pt) (h ph) (w pw) c -> n (t h w) (pt ph pw c)", pt=c.temporal_patch_size, ph=c.spatial_patch_size, pw=c.spatial_patch_size) valid = E.reduce(pixel_mask, "n (t pt) (h ph) (w pw) -> (n t h w)", reduction="any", pt=c.temporal_patch_size, ph=c.spatial_patch_size, pw=c.spatial_patch_size) feats = m.img_projector(E.rearrange(patches, "n p c -> (n p) c")[valid.bool()]).to(h.dtype) imask = (tokens == c.img_id)[..., None].expand_as(h) assert feats.numel() == int(imask.sum()) h = torch.masked_scatter(h, imask, feats) freqs_cis = m.freqs_cis[pos_t.long()] # golden 2D rope frequencies computed with autocast OFF (VLMC fix, 22 Nov): the maker's function casts to # float32 and the maker's forward never runs under autocast, but under amp_bf16 (the runner's GPU check and the # OOM fallback) autocast turned its float32 einsum into bf16 and torch.polar rejects bf16 (GPU smoke of job # 50971, 21 Nov 22:47Z). With autocast off the call is exactly the maker's float32 computation. with torch.autocast(device_type=d.type, enabled=False): freqs_golden = self.mr.apply_golden_freqs_cis_to_visual_pos(m.freqs_cis_golden, pos_hw) for layer in m.layers.values(): if self.gc and m.training: h = checkpoint(self._layer, layer, h, mask, freqs_cis, freqs_golden, pos_hw, use_reentrant=False) else: h = self._layer(layer, h, mask, freqs_cis, freqs_golden, pos_hw) return m.output(m.norm(h)) def target_ids(self, text): return (self.tok.encode(text, add_special_tokens=False) if text else []) + [self.eos_id] def loss(self, images, texts): tokens, labels, pv, pm, pt, phw = self._build(images, texts) with autocast(self.device): lg = self.logits(tokens, pv, pm, pt, phw) return target_loss_sum(lg, labels) # ---- check against the maker's forward (GPU only: Triton kernel) ---------------------------------------------- @torch.no_grad() def check_equivalence(self, images, texts): m = self.model was = m.training m.eval() # both forwards in the master dtype WITHOUT autocast (fp32 under amp_bf16), so differences are numerical only tokens, labels, pv, pm, pt, phw = self._build(images, texts) mine = self.logits(tokens, pv, pm, pt, phw).float() d = self.device B, L = tokens.shape S = (L + 127) // 128 * 128 kv = sys.modules[type(m).__module__].KVCache(max_batch_size=B, max_seq_length=S, n_heads=m.config.n_heads, head_dim=m.config.head_dim, num_layers=m.config.n_layers) padded = torch.full((B, S), self.pad_id, dtype=tokens.dtype, device=d) padded[:, :L] = tokens.to(d) if d.type == "cuda": am = m.get_attention_mask(padded, max_len=S) else: # the maker's create_attention_mask hard-wires device "cuda"; same mask_mods, built on CPU c = m.config ma = self.ma causal = ma.and_masks(ma.get_causal_mask_mod(), ma.get_document_mask_mod(padded, c.eos_id), ma.get_non_left_pad_mask_mod(padded, self.pad_id)) mod = ma.or_masks(ma.get_image_prefix_mask_mod(padded, c.image_cls_token_id, c.img_end_id), causal) am = ma.create_block_mask(mod, B, None, S, S, device="cpu") ff_cls = type(next(iter(m.layers.values())).feed_forward) orig_ff = ff_cls.forward if d.type == "cpu": # the Triton FFN kernel needs a GPU; on CPU the reference uses the same PyTorch FFN def _ff(self_, x): w = self_.w13(F.rms_norm(x, (x.size(-1),))) return self_.w2(torch.relu(w[..., 0::2]).square() * w[..., 1::2]) ff_cls.forward = _ff try: ref = m.forward(tokens=tokens.to(d), attention_mask=am, kv_cache=kv, rope_pos_t=pt.to(d), rope_pos_hw=phw.to(d), pixel_values=pv.to(d), pixel_mask=pm.to(d)).float() finally: ff_cls.forward = orig_ff sel = labels.to(d) != -100 diff = (mine - ref).abs()[sel[:, :]] agree = (mine.argmax(-1) == ref.argmax(-1))[sel].float().mean() m.train(was) return {"max_abs_logit_diff_on_targets": float(diff.max()), "mean_abs": float(diff.mean()), "argmax_agreement_on_targets": float(agree), "ref_logit_abs_mean": float(ref.abs()[sel].mean())} # ---- decoding (maker's loop) ----------------------------------------------------------------------------------- def prepare_eval(self): self.model.eval() self.model.to(torch.bfloat16) self.model._weights_fused = False self.model._ensure_device_buffers() # complex freqs_cis again after the dtype cast @torch.inference_mode() def generate(self, images, max_new_tokens, temperature=None): """temperature=None: greedy, unchanged. Else the cap-retry path (VLMC, 21 Nov): the maker's sample_next_token at that temperature, top_k None (no top-k cut), seed None so torch's global generator (seeded per set by the eval script) is used. Returns text only: whether the retry ended properly is the eval script's re-tokenised estimate.""" pairs = [(im, self.prompt) for im in images] if temperature is not None: return self.model._generate_batch(pairs, max_new_tokens=max_new_tokens, temperature=float(temperature), top_k=None, min_dimension=self.min_dim, max_dimension=self.max_dim, seed=None) return self.model._generate_batch(pairs, max_new_tokens=max_new_tokens, temperature=0.0, top_k=None, min_dimension=self.min_dim, max_dimension=self.max_dim, seed=42)