"""Shared helpers for the post-SFT recipes (self-play, GRPO, data selection, merging). All of them work on Qwen-family OCR VLMs (the same models as common/vlm_sft.py) with a LoRA adapter, so the frozen base model doubles as the reference / opponent: `model.disable_adapter()`. """ import json import math from pathlib import Path import torch from PIL import Image from transformers import AutoModelForImageTextToText, AutoProcessor from .data_prep import choose_prompt from .vlm_sft import LM_LORA_TARGETS, best_dtype, resize_for DTYPES = {"bf16": torch.bfloat16, "fp16": torch.float16, "fp32": torch.float32} def read_jsonl(path, limit=0): with open(path, encoding="utf-8-sig") as fh: rows = [json.loads(line) for line in fh if line.strip()] return rows[:limit] if limit else rows def sharper_view_rows(rows, max_pixels): """Records whose image is larger than the student's resolution, so a higher-resolution teacher view actually shows more (a small line image looks the same at both resolutions).""" keep = [] for r in rows: with Image.open(r["image"]) as im: w, h = im.size if w * h > max_pixels: keep.append(r) return keep def write_jsonl(path, rows): Path(path).parent.mkdir(parents=True, exist_ok=True) with open(path, "w", encoding="utf-8") as fh: for r in rows: fh.write(json.dumps(r, ensure_ascii=False) + "\n") def load_policy(model_path, adapter=None, lora=0, dtype="auto", gradient_checkpointing=False, nora=False): """Base model + a trainable LoRA adapter (an existing one, or a new one of rank `lora`; `nora` = NoRA-init).""" from peft import LoraConfig, PeftModel, get_peft_model dtype = best_dtype() if dtype == "auto" else dtype processor = AutoProcessor.from_pretrained(model_path) model = AutoModelForImageTextToText.from_pretrained(model_path, dtype=DTYPES[dtype], attn_implementation="sdpa") model.config.use_cache = False if adapter: model = PeftModel.from_pretrained(model, adapter, is_trainable=True) else: r = lora or 16 model = get_peft_model(model, LoraConfig(r=r, lora_alpha=r if nora else 2 * r, lora_dropout=0.0, target_modules=LM_LORA_TARGETS, task_type="CAUSAL_LM")) if nora: nora_init(model) if gradient_checkpointing: model.gradient_checkpointing_enable(gradient_checkpointing_kwargs={"use_reentrant": False}) model.enable_input_require_grads() if torch.cuda.is_available(): model = model.to("cuda") return model, processor, dtype def resolve_prompt(prompt=None, prompt_file=None): """The page prompt from --prompt-file or --prompt; None means the default. Lines always use the line prompt.""" return Path(prompt_file).read_text(encoding="utf-8").strip() if prompt_file else prompt def scale_adapter(model, alpha): """Multiply every LoRA update by alpha: theta = base + alpha * delta (weight interpolation). alpha = 1 is the trained model, alpha = 0 the original one. Returns the number of scaled layers. """ from peft.tuners.lora import LoraLayer n = 0 for module in model.modules(): if isinstance(module, LoraLayer): for name in module.scaling: module.scaling[name] *= alpha n += 1 return n class Codec: """Turns (record, answer text) into model inputs; same prompt and resizing as common/vlm_sft.py.""" def __init__(self, processor, prompt=None, max_pixels=1280 * 1280, min_pixels=64 * 64): self.p = processor self.prompt = prompt ip = processor.image_processor self.factor = int(getattr(ip, "patch_size", 14)) * int(getattr(ip, "merge_size", 2)) self.max_pixels, self.min_pixels = max_pixels, min_pixels tok = processor.tokenizer self.end = "<|im_end|>" if "<|im_end|>" in tok.get_vocab() else tok.eos_token self.end_id = tok.convert_tokens_to_ids(self.end) def prompt_inputs(self, rec, device): prompt = choose_prompt(rec, self.prompt) msgs = [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": prompt}]}] text = self.p.apply_chat_template(msgs, tokenize=False, add_generation_prompt=True, enable_thinking=False) im = resize_for(Image.open(rec["image"]).convert("RGB"), self.factor, self.max_pixels, self.min_pixels) return self.p(text=[text], images=[im], return_tensors="pt").to(device) def answer_ids(self, text): """Token ids of a target answer, ending with the end-of-turn token.""" return self.p.tokenizer(text + self.end, add_special_tokens=False)["input_ids"] def decode(self, ids): return self.p.tokenizer.decode(ids, skip_special_tokens=True) def with_answer(enc, ans_ids): """Append answer token ids to prompt inputs (per-token keys are extended, image keys kept).""" ans = torch.tensor([ans_ids], device=enc["input_ids"].device) L0 = enc["input_ids"].shape[1] out = {} for k, v in enc.items(): if torch.is_tensor(v) and v.dim() == 2 and v.shape == (1, L0): pad = ans if k == "input_ids" else torch.ones_like(ans) if k == "attention_mask" else torch.zeros_like(ans) out[k] = torch.cat([v, pad], dim=1) else: out[k] = v return out, L0 def answer_logprobs(model, enc, ans_ids, positions=None): """log p(answer token k | image, prompt, answer[:k]) for k in `positions` (default: all). Only the needed logits are computed (`logits_to_keep` with indices), which keeps the vocabulary-sized logits out of memory for long pages. """ if positions is None: positions = list(range(len(ans_ids))) if not positions: return torch.zeros(0, device=enc["input_ids"].device) inputs, L0 = with_answer(enc, ans_ids) keep = torch.tensor([L0 - 1 + k for k in positions], device=inputs["input_ids"].device) logits = model(**inputs, logits_to_keep=keep, use_cache=False).logits[0].float() target = torch.tensor([ans_ids[k] for k in positions], device=logits.device) return torch.log_softmax(logits, -1).gather(1, target[:, None])[:, 0] @torch.no_grad() def generate(model, enc, max_new, end_id, n=1, temperature=0.0): """Answer token ids (ending with end_id when the model stopped) for n samples.""" kw = dict(do_sample=False) if temperature <= 0 else dict(do_sample=True, temperature=temperature, top_p=1.0, top_k=0) out = model.generate(**enc, max_new_tokens=max_new, num_return_sequences=n, use_cache=True, **kw) res = [] for seq in out[:, enc["input_ids"].shape[1]:].tolist(): if end_id in seq: seq = seq[: seq.index(end_id) + 1] else: seq = [t for t in seq if t != model.generation_config.pad_token_id] res.append(seq) return res # ---------------------------------------------------------------- NoRA (arXiv 2608.31036) def nora_init(model): """NoRA-init: give every LoRA down-projection A unit-norm columns along the rank dimension. Normalized Low-Rank Adaptation: with B = 0 at the start, A sets the effective per-input-coordinate learning rate of LoRA (preconditioner A^T A). Unit columns make its diagonal 1, matching full fine-tuning (scaling must be 1, i.e. lora_alpha = r). Initialisation-only: the adapter stays plain LoRA, so saving, loading and merging are unchanged. Returns the number of normalised matrices. """ from peft.tuners.lora import LoraLayer n = 0 with torch.no_grad(): for module in model.modules(): if isinstance(module, LoraLayer): for name, lin in module.lora_A.items(): w = lin.weight # (r, in_features) w.div_(w.norm(dim=0, keepdim=True).clamp_min(1e-8)) n += 1 return n # ---------------------------------------------------------------- memory-light forward passes def core_and_head(model): """The model body (returns normed hidden states) and its LM head; LoRA layers stay active inside.""" m = model.get_base_model() if hasattr(model, "get_base_model") else model return m.model, m.get_output_embeddings() def answer_hidden(model, inputs, prompt_len, n): """Final hidden states that predict the n answer tokens (one row per answer token). Calling the body instead of the full model skips the (tokens x vocabulary) logits, which for a 248k vocabulary and a 2k-token page would take ~2 GB; logits are then made in chunks by the caller.""" core, _ = core_and_head(model) h = core(**inputs, use_cache=False).last_hidden_state[0] return h[prompt_len - 1: prompt_len - 1 + n] def chunked_token_logprobs(head, hidden, ids, chunk=256): """log p(ids[t]) from hidden states, with the vocabulary logits made and freed chunk by chunk (activation checkpointing), so memory does not grow with page length.""" from torch.utils.checkpoint import checkpoint def piece(h, t): return torch.log_softmax(head(h).float(), -1).gather(1, t[:, None])[:, 0] out = [] for s in range(0, len(ids), chunk): t = torch.tensor(ids[s:s + chunk], device=hidden.device) h = hidden[s:s + chunk] out.append(checkpoint(piece, h, t, use_reentrant=False) if h.requires_grad else piece(h, t)) return torch.cat(out) if out else hidden.new_zeros(0) # ---------------------------------------------------------------- frozen teacher and the eyes-closed view class FrozenTeacher: """The starting model, frozen, as a teacher (on-policy self-distillation keeps the teacher at its initial weights; BlinkOPD found an EMA teacher 3 points worse). Starting from an adapter, a second copy of it is loaded as adapter "teacher" and switched to for teacher passes; starting from the base model, the teacher is the base with LoRA disabled.""" def __init__(self, model, adapter=None): self.model, self.named = model, bool(adapter) if adapter: model.load_adapter(adapter, adapter_name="teacher", is_trainable=False) model.set_adapter("default") def __enter__(self): if self.named: self.model.set_adapter("teacher", inference_mode=True) self._ctx = None else: self._ctx = self.model.disable_adapter() self._ctx.__enter__() return self def __exit__(self, *exc): if self.named: self.model.set_adapter("default") else: self._ctx.__exit__(*exc) return False def eyes_closed(model, inputs): """BlinkOPD's eyes-closed view (arXiv 2611.16402): the same sequence with only the image-content tokens removed. Vision start/end markers, prompt and answer stay, and every remaining token keeps the rotary position it had in the full sequence (Qwen M-RoPE positions are computed on the full sequence first). Returns (inputs without the image, number of removed tokens).""" m = model.get_base_model() if hasattr(model, "get_base_model") else model image_id = m.config.image_token_id ids = inputs["input_ids"] keep = ids[0] != image_id out = {"input_ids": ids[:, keep], "attention_mask": inputs["attention_mask"][:, keep]} rope = getattr(m.model, "get_rope_index", None) if rope is not None and "image_grid_thw" in inputs: pos, _ = rope(ids, mm_token_type_ids=inputs.get("mm_token_type_ids"), image_grid_thw=inputs["image_grid_thw"], attention_mask=inputs["attention_mask"]) out["position_ids"] = pos[..., keep] return out, int((~keep).sum()) # ---------------------------------------------------------------- divergences on top-K + tail def topk_tail(logp, idx): """Log-probabilities at idx plus one 'tail' bucket holding the remaining mass: a K+1-way distribution.""" sel = logp.gather(1, idx) tail = torch.log1p(-sel.exp().sum(-1, keepdim=True).clamp(max=1 - 1e-6)) return torch.cat([sel, tail], -1) def jsd(p_log, q_log, alpha=0.5): """Generalised Jensen-Shannon divergence per row between two distributions given as log-probs.""" m = torch.logsumexp(torch.stack([p_log + math.log(alpha), q_log + math.log(1 - alpha)]), 0) kl_pm = (p_log.exp() * (p_log - m)).sum(-1) kl_qm = (q_log.exp() * (q_log - m)).sum(-1) return alpha * kl_pm + (1 - alpha) * kl_qm