Run this model with HF Jobs
Run naver-ai/ReadPoint-2B on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.
Paste one of these prompts into your coding agent:
Fine-tune on my dataset
Use HF Jobs to fine-tune https://huggingface.co/naver-ai/ReadPoint-2B. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.
Run batch inference
Use HF Jobs to run batch inference with https://huggingface.co/naver-ai/ReadPoint-2B on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
Evaluate on a benchmark
Use HF Jobs to evaluate https://huggingface.co/naver-ai/ReadPoint-2B. Ask me which benchmark to run, then save the scores and the per-example results to a new dataset repo. Run `hf jobs --help` first to learn the CLI.
Quantize for lower memory use
Use HF Jobs to create a 4-bit version of https://huggingface.co/naver-ai/ReadPoint-2B. Push it to a new model repo, then reload it from there and report its memory footprint. Run `hf jobs --help` first to learn the CLI.
Instructions to use naver-ai/ReadPoint-2B with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- PEFT
How to use naver-ai/ReadPoint-2B with PEFT:
Task type is invalid.
- Notebooks
- Google Colab
- Kaggle
File size: 13,528 Bytes
f021578 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 | # ReadPoint
# 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.
"""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.
This file is the minimal version (plain transformers + one CUDA graph). The image preprocessing and the vision encoder still run
eagerly here, so it is slower than the numbers in the paper. To reproduce the paper, load the model with the engine of
https://github.com/naver-ai/ReadPoint (GPU resize, vision graph, Raspberry Pi read, evaluation), which comes with the code release.
pip install torch transformers peft pillow flash-linear-attention causal-conv1d
python fast_read.py --image cat.jpg --target "the cat's left ear" [--adapter naver-ai/ReadPoint-0.8B] [--all]
"""
import argparse, json, os, time
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
m = AutoModelForImageTextToText.from_pretrained(base, dtype=dtype, device_map=device, attn_implementation="sdpa")
self.model = PeftModel.from_pretrained(m, path).merge_and_unload().eval()
self.plan = {}; _patch(self.model, self.plan)
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)]; self.dig = torch.tensor(self.D, device=device)
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 (",", "}")}
ends |= {self._ids(s)[0] for s in ("<|im_end|>", "<|endoftext|>", "\n", "\n\n", ".", " .") if len(self._ids(s)) == 1}
self.term = torch.tensor(sorted(ends), device=device)
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)
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
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--image", required=True); ap.add_argument("--target", required=True)
ap.add_argument("--adapter", default="naver-ai/ReadPoint-0.8B"); ap.add_argument("--max-pixels", type=int, default=147456)
ap.add_argument("--all", action="store_true", help="also read the box and the self-check (still one forward)")
ap.add_argument("--repeat", type=int, default=20)
a = ap.parse_args()
R = FastReader(a.adapter, a.max_pixels); img = Image.open(a.image).convert("RGB"); W, H = img.size
def timed(f):
f(); f(); ts = []
for _ in range(a.repeat):
torch.cuda.synchronize(); t = time.perf_counter(); out = f(); torch.cuda.synchronize(); ts.append(1000 * (time.perf_counter() - t))
return out, float(np.median(ts))
res, ms = timed(lambda: R.read(img, a.target, full=a.all))
x, y = res["point"]
print(f"point ({x:03d}, {y:03d}) /1000 = ({x * W / 1000:.0f}, {y * H / 1000:.0f}) px")
if a.all:
print(f"box {tuple(res['box'])} /1000"); print(f"P(yes) {res['p_yes']:.3f} (self-check: can it point precisely at this resolution?)")
print(f"read {ms:.1f} ms (one forward, image included; full distributions over 000..999)")
if __name__ == "__main__":
main()
|