"""numpy versions of everything the page computes outside the ONNX graphs (the JS port is checked against these, and these against transformers): vision position tables, M-RoPE ids and tables, mask.""" from __future__ import annotations import numpy as np NUM_GRID = 48 # sqrt(num_position_embeddings 2304) MERGE = 2 def vision_tables(gh: int, gw: int): """gh, gw: patch grid (before the 2x2 merge). Returns idx [4,N] i64, w [4,N] f32 (bilinear position embedding lookups) and cos, sin [N,64] f32, all in merge order, as Qwen3VLVisionModel builds them.""" hs = np.linspace(0, NUM_GRID - 1, gh, dtype=np.float32) ws = np.linspace(0, NUM_GRID - 1, gw, dtype=np.float32) hf, wf = hs.astype(np.int32), ws.astype(np.int32) hc, wc = np.minimum(hf + 1, NUM_GRID - 1), np.minimum(wf + 1, NUM_GRID - 1) dh, dw = hs - hf, ws - wf idx = [(hf[:, None] * NUM_GRID + wf[None]), (hf[:, None] * NUM_GRID + wc[None]), (hc[:, None] * NUM_GRID + wf[None]), (hc[:, None] * NUM_GRID + wc[None])] wt = [((1 - dh)[:, None] * (1 - dw)[None]), ((1 - dh)[:, None] * dw[None]), (dh[:, None] * (1 - dw)[None]), (dh[:, None] * dw[None])] def merge_order(a): # [gh,gw] -> (gh/2, gw/2, 2, 2) flattened return a.reshape(gh // MERGE, MERGE, gw // MERGE, MERGE).transpose(0, 2, 1, 3).reshape(-1) idx = np.stack([merge_order(i) for i in idx]).astype(np.int64) wt = np.stack([merge_order(w) for w in wt]).astype(np.float32) rows = merge_order(np.broadcast_to(np.arange(gh)[:, None], (gh, gw))) cols = merge_order(np.broadcast_to(np.arange(gw)[None], (gh, gw))) inv = (1.0 / (10000.0 ** (np.arange(0, 32, 2, dtype=np.float32) / 32))).astype(np.float32) # head_dim//2 = 32 -> 16 freqs table = np.outer(np.arange(max(gh, gw), dtype=np.float32), inv).astype(np.float32) emb = np.concatenate([table[rows], table[cols]], axis=1) # [N, 32] emb = np.concatenate([emb, emb], axis=1) # [N, 64] return idx, wt, np.cos(emb).astype(np.float32), np.sin(emb).astype(np.float32) def positions(n_before: int, gh: int, gw: int, n_after: int): """get_rope_index for [text * n_before][image gh x gw merged tokens][text * n_after] -> [3, S] int64. gh, gw here are merged-token grid sizes.""" t = np.arange(n_before) pos = [np.stack([t, t, t])] cur = n_before n = gh * gw pos.append(np.stack([np.full(n, cur), cur + np.repeat(np.arange(gh), gw), cur + np.tile(np.arange(gw), gh)])) cur += max(gh, gw) t = np.arange(n_after) + cur pos.append(np.stack([t, t, t])) return np.concatenate(pos, axis=1).astype(np.int64) def text_tables(pos: np.ndarray, theta: float = 5e6, section=(24, 20, 20), dim: int = 128): """pos [3,S] -> cos, sin [S,128] float32 with interleaved M-RoPE (T H W T H W ... then T).""" inv = 1.0 / (theta ** (np.arange(0, dim, 2, dtype=np.float32) / dim)) # [64] freqs = pos[:, :, None].astype(np.float32) * inv[None, None, :] # [3,S,64] ft = freqs[0].copy() for d, off in ((1, 1), (2, 2)): sl = slice(off, section[d] * 3, 3) ft[:, sl] = freqs[d][:, sl] emb = np.concatenate([ft, ft], axis=-1) return np.cos(emb).astype(np.float32), np.sin(emb).astype(np.float32) def mask(prompt_len: int, n_per: int = 9, n_groups: int = 3, total: int | None = None): """Additive attention mask [S,S]: causal, and the three query groups cannot see each other.""" s = total or prompt_len + n_per * n_groups NEG = np.float32(np.finfo(np.float32).min) m = np.triu(np.full((s, s), NEG, np.float32), 1) for i in range(n_groups): for j in range(n_groups): if i != j: m[prompt_len + i * n_per: prompt_len + (i + 1) * n_per, prompt_len + j * n_per: prompt_len + (j + 1) * n_per] = NEG return m