Spaces:
Running on Zero

readpoint / fast_read.py
multimodalart's picture
multimodalart HF Staff
Force peft adapter load onto CPU (torch_device='cpu') so the ZeroGPU main process never touches raw CUDA
06a4454 verified
Raw History Blame Contribute Delete
13 kB
# ReadPoint — vendored from the model repos (naver-ai/ReadPoint-0.8B, naver-ai/ReadPoint-2B)
# Copyright (c) 2026-present NAVER Cloud Corp.
# Released with the ReadPoint adapters under their license (CC BY-NC 4.0); the code release will carry its own license.
# Adapted for ZeroGPU: model loads on CPU and is moved with .to("cuda") (the ZeroGPU
# runtime streams it into VRAM on the first @spaces.GPU call); everything else is 1:1
# the authors' minimal reader.
"""Minimal ReadPoint inference for Qwen3.5 adapters: ONE forward pass reads the point (and, optionally, the box and the self-check).
Each coordinate answer is three digits, and every digit prefix the model could write is known in advance: per axis the
question, 10 one-digit prefixes and 100 two-digit prefixes. They are packed with the image and "Point to <target>." into one
sequence and run through the model once. Full-attention layers use a tree mask (each token sees only its own path), and the
Gated-DeltaNet layers continue every branch from its parent's state inside the same layer. The outputs give the exact
distribution over 000..999 for each axis; nothing is sampled or written.
"""
import json, os
import numpy as np
import torch
import torch.nn.functional as F
from PIL import Image
def _gdn(model): return [m for m in model.modules() if type(m).__name__.endswith("GatedDeltaNet")]
def _run(mod, x, conv, rec, chunk):
"""Gated-DeltaNet layer on rows x (B, n, d) continuing from conv / recurrent states (the module's own weights and kernels)."""
B, n, _ = x.shape
mixed = mod.in_proj_qkv(x).transpose(1, 2)
z = mod.in_proj_z(x).reshape(B, n, -1, mod.head_v_dim); b, a = mod.in_proj_b(x), mod.in_proj_a(x)
K = mod.conv_kernel_size; xe = torch.cat([conv[..., 1:].to(mixed.dtype), mixed], -1); new_conv = xe[..., -K:].contiguous()
mixed = F.silu(F.conv1d(xe, mod.conv1d.weight, mod.conv1d.bias, groups=xe.shape[1])).transpose(1, 2)
q, k, v = torch.split(mixed, [mod.key_dim, mod.key_dim, mod.value_dim], dim=-1)
q, k = q.reshape(B, n, -1, mod.head_k_dim), k.reshape(B, n, -1, mod.head_k_dim); v = v.reshape(B, n, -1, mod.head_v_dim)
g = -mod.A_log.float().exp() * F.softplus(a.float() + mod.dt_bias)
if mod.num_v_heads > mod.num_k_heads:
r = mod.num_v_heads // mod.num_k_heads; q, k = q.repeat_interleave(r, 2), k.repeat_interleave(r, 2)
rule = mod.chunk_gated_delta_rule if chunk else mod.recurrent_gated_delta_rule
o, last = rule(q, k, v, g=g, beta=b.sigmoid(), initial_state=rec, output_final_state=True, use_qk_l2norm_in_kernel=True)
o = mod.norm(o.reshape(-1, mod.head_v_dim), z.reshape(-1, mod.head_v_dim)).reshape(B, n, -1)
return mod.out_proj(o), new_conv, last
def _patch(model, plan):
"""Gated-DeltaNet layers run the packed sequence as a tree: prefix, then each question tail, then the digit nodes."""
for mod in _gdn(model):
def fwd(hidden_states, cache_params=None, attention_mask=None, _m=mod, **kw):
p = plan; h = hidden_states[0]; out = torch.empty_like(h)
conv0 = h.new_zeros(1, _m.conv1d.weight.shape[0], _m.conv_kernel_size)
rec0 = h.new_zeros(1, _m.num_v_heads, _m.head_k_dim, _m.head_v_dim, dtype=torch.float32)
o, cP, sP = _run(_m, h[None, :p["Lp"]], conv0, rec0, True); out[:p["Lp"]] = o[0]
ends_c, ends_s = [None] * len(p["tails"]), [None] * len(p["tails"])
for idx in p["groups"]: # tails of equal length run as one batch
s, n = p["tails"][idx[0]]; x = torch.stack([h[p["tails"][i][0]: p["tails"][i][0] + n] for i in idx])
o, c, st = _run(_m, x, cP.expand(len(idx), -1, -1), sP.expand(len(idx), -1, -1, -1), True)
for j, i in enumerate(idx): out[p["tails"][i][0]: p["tails"][i][0] + n] = o[j]; ends_c[i], ends_s[i] = c[j], st[j]
pc, ps = torch.stack(ends_c), torch.stack(ends_s)
for (s, cnt, par) in p["levels"]: # one-token digit nodes, each from its parent's end state
o, pc, ps = _run(_m, h[s: s + cnt, None], pc.index_select(0, par), ps.index_select(0, par), False)
out[s: s + cnt] = o[:, 0]
return out[None]
mod.forward = fwd
class FastReader:
def __init__(self, adapter="naver-ai/ReadPoint-0.8B", max_pixels=147456, device="cuda", dtype=torch.bfloat16):
from transformers import AutoProcessor, AutoModelForImageTextToText
from peft import PeftConfig, PeftModel
from huggingface_hub import snapshot_download
path = adapter if os.path.isdir(adapter) else snapshot_download(adapter)
base = PeftConfig.from_pretrained(path).base_model_name_or_path
self.dev = device
self.proc = AutoProcessor.from_pretrained(base, max_pixels=max_pixels); self.tok = self.proc.tokenizer
# ZeroGPU: load + merge on CPU (no accelerator is visible at import time), then .to(device):
# the hijack turns this into a registered fake-CUDA tensor whose CPU original the runtime
# packs to disk and streams into VRAM on the first @spaces.GPU call.
m = AutoModelForImageTextToText.from_pretrained(base, dtype=dtype, attn_implementation="sdpa")
# torch_device="cpu": peft otherwise infers the device via torch.cuda.is_available(), which the
# ZeroGPU hijack reports as True in the GPU-less main process -> a raw safetensors load onto
# "cuda" (not the .to("cuda") the hijack intercepts) crashes with "No CUDA GPUs are available".
m = PeftModel.from_pretrained(m, path, torch_device="cpu").merge_and_unload().eval()
self.model = m.to(device)
self.plan = {}; _patch(self.model, self.plan)
self._moved = False
self.lm = self.model.model.language_model; self.lm._update_linear_attn_mask = lambda *a, **k: None # avoids a host sync
self.graphs = {} if device == "cuda" else None # one CUDA graph per sequence layout: no per-kernel launch cost
cfg = json.load(open(os.path.join(path, "read_config.json")))
self.qtext = {n: cfg[n] for n in ("x", "y", "x1", "y1", "x2", "y2", "check")}
self.q = {n: self._ids(t) for n, t in self.qtext.items()}
self.yes, self.no = self._ids("Yes")[0], self._ids("No")[0]
self.D = [self._ids(str(d))[0] for d in range(10)]
vocab = self.tok.get_vocab() # an answer may also end after 1 or 2 digits: count those terminators as the reference reader does
ends = {i for s, i in vocab.items() if s[:1] in (",", "}")}
NL = chr(10) # newline (kept out of this literal so the line stays a single line)
ends |= {self._ids(s)[0] for s in ("<|im_end|>", NL, NL + NL, ".", " .") if len(self._ids(s)) == 1}
# kept on CPU here: a bare factory call with device="cuda" is not the .to("cuda") the
# ZeroGPU hijack intercepts at import time; read() moves them onto the (real) device.
self.dig = torch.tensor(self.D); self.term = torch.tensor(sorted(ends))
def _ids(self, s): return self.tok(s, add_special_tokens=False)["input_ids"]
def prompt(self, target):
t = target.strip().rstrip("."); t = t[len("point to "):] if t.lower().startswith("point to ") else t
msgs = [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": f"Point to {t}."}]}]
text = self.proc.apply_chat_template(msgs, add_generation_prompt=True, tokenize=False, enable_thinking=False)
return text[:text.rfind("<|im_end|>")] # the shared prefix: the questions start where the user turn ends
def _lm(self, emb, pos, mask, key):
"""The language model on the packed sequence; on CUDA, captured once per layout and replayed (same kernels, same output)."""
run = lambda e, p, m: self.lm(inputs_embeds=e, position_ids=p, attention_mask=m, use_cache=False).last_hidden_state
if self.graphs is None: return run(emb, pos, mask)
if key not in self.graphs:
st = [emb.clone(), pos.clone(), mask.clone()]; s = torch.cuda.Stream(); s.wait_stream(torch.cuda.current_stream())
with torch.cuda.stream(s):
for _ in range(2): run(*st)
torch.cuda.current_stream().wait_stream(s); g = torch.cuda.CUDAGraph()
with torch.cuda.graph(g): out = run(*st)
self.graphs[key] = (g, st, out, dict(self.plan)) # keeps the captured plan tensors alive
g, st, out, _ = self.graphs[key]
for a, b in zip(st, (emb, pos, mask)): a.copy_(b)
g.replay(); return out
@torch.no_grad()
def read(self, image, target, full=False):
"""One forward (full=True also reads the box edges and the self-check, still in the same forward). Sequence = [prefix | tail of each question | 10 one-digit nodes per axis | 100 two-digit nodes per axis]."""
names, check = (("x", "y", "x1", "y1", "x2", "y2"), True) if full else (("x", "y"), False)
if not self._moved: # first call runs inside the GPU worker: move the small constants onto the real device
self.dig, self.term = self.dig.to(self.dev), self.term.to(self.dev); self._moved = True
inp = self.proc(text=[self.prompt(target)], images=[image], return_tensors="pt").to(self.dev)
P = inp["input_ids"][0]; Lp = len(P); qs = list(names) + (["check"] if check else [])
ids, tails, par = [P], [], []
o = Lp
for n in qs: tails.append((o, len(self.q[n]))); ids.append(torch.tensor(self.q[n], device=self.dev)); o += len(self.q[n])
s1 = o; n1 = 10 * len(names); ids.append(self.dig.repeat(len(names))); o += n1
s2 = o; n2 = 100 * len(names); ids.append(self.dig.repeat(10 * len(names))); o += n2
ids = torch.cat(ids)[None]; N = ids.shape[1]
# tree mask (True = may attend) and positions
M = torch.zeros(N, N, dtype=torch.bool, device=self.dev); M[:Lp, :Lp] = torch.ones(Lp, Lp, device=self.dev).tril().bool()
pos3, _ = self.model.model.get_rope_index(inp["input_ids"], inp["mm_token_type_ids"], image_grid_thw=inp["image_grid_thw"])
base = int(pos3.max()) + 1; tp = torch.zeros(N, dtype=torch.long, device=self.dev)
for (s, n) in tails:
M[s:s + n, :Lp] = True; M[s:s + n, s:s + n] = torch.ones(n, n, device=self.dev).tril().bool(); tp[s:s + n] = base + torch.arange(n, device=self.dev)
par1 = torch.arange(len(names), device=self.dev).repeat_interleave(10) # node1 -> its tail
last = torch.tensor([s + n - 1 for s, n in tails[:len(names)]], device=self.dev)
r1 = s1 + torch.arange(n1, device=self.dev); M[r1] = M[last[par1]]; M[r1, r1] = True; tp[r1] = tp[last[par1]] + 1
par2 = torch.arange(n1, device=self.dev).repeat_interleave(10) # node2 -> its node1
r2 = s2 + torch.arange(n2, device=self.dev); M[r2] = M[r1[par2]]; M[r2, r2] = True; tp[r2] = tp[r1[par2]] + 1
pos = tp[None, None].repeat(3, 1, 1); pos[:, :, :Lp] = pos3
mm = torch.zeros_like(ids); mm[:, :Lp] = inp["mm_token_type_ids"]
lens = sorted({n for _, n in tails}); groups = [[i for i, (_, n) in enumerate(tails) if n == L] for L in lens]
self.plan.clear(); self.plan.update(Lp=Lp, tails=tails, groups=groups, levels=[(s1, n1, par1), (s2, n2, par2)])
emb = self.model.model.get_input_embeddings()(ids)
img = self.model.model.get_image_features(inp["pixel_values"], inp["image_grid_thw"]).pooler_output
emb = emb.masked_scatter((ids == self.model.config.image_token_id)[..., None], torch.cat(img).to(emb.dtype))
h = self._lm(emb, pos, M[None, None], (Lp, tuple(tails)))[0]
out = {}
for i, name in enumerate(names):
rows = torch.cat([last[i:i + 1], r1[10 * i: 10 * i + 10], r2[100 * i: 100 * i + 100]])
Pr = torch.softmax(self.model.lm_head(h[rows]).float(), -1)
root, Q1, Q2 = Pr[0], Pr[1:11], Pr[11:] # after the question / after the 1st digit / after 2 digits
r = root[self.dig] / root[self.dig].sum()
def split(p):
d, e = p[:, self.dig], p[:, self.term].sum(-1); z = d.sum(-1) + e; return d / z[:, None], e / z
g1, t1 = split(Q1); g2, t2 = split(Q2)
m = torch.zeros(1000, device=self.dev, dtype=torch.float64); two = (r[:, None] * g1).reshape(-1)
m[:10] += (r * t1).double(); m[:100] += (two * t2).double(); m += (two[:, None] * g2).reshape(-1).double()
out[name] = (m / m.sum()).cpu().numpy()
res = {"dist": out, "point": (int(out["x"].argmax()), int(out["y"].argmax())), "passes": 1}
if "x1" in out: res["box"] = tuple(int(out[e].argmax()) for e in ("x1", "y1", "x2", "y2"))
if check:
pc = torch.softmax(self.model.lm_head(h[tails[-1][0] + tails[-1][1] - 1]).float(), -1)
res["p_yes"] = float(pc[self.yes] / (pc[self.yes] + pc[self.no]))
return res