# SPDX-License-Identifier: Apache-2.0 """ttnn baseline of the vision tower (16 Gemma-4 ViT layers) + 3x3 position pooling + embed_vision, one program per packed-patch bucket P. Packing: the images / frames of a launch are concatenated (P_total <= P); attention is block-diagonal per image via SDPA ``cu_window_seqlens``. Patches are **re-ordered on the host** so that the 9 patches of every pooled cell are consecutive and cells follow the official output-slot order (row-major over the pooled grid): attention is permutation-equivariant (positions enter only through the per-patch position embedding and RoPE), so the pooler becomes a static block matrix (1/9) and the output rows come out in placeholder order. 2-D RoPE as a standard 64-wide rotate_half rope: the q / k head dims are permuted at load time ([0:16, 32:48, 16:32, 48:64]) so that the pairs of both 32-wide axial ropes become (i, i + 32); the cos / sin tables are then [x-freqs, y-freqs, x-freqs, y-freqs] per patch. q . k is invariant under a common permutation. Per-launch input: fp32 ROW_MAJOR [P, 768 + 128] = 2p - 1 | cos (64) | sin (64), and the patch x / y indices (uint32 [1, P] each) for the on-device position-embedding gathers (ttnn.embedding on the two bf16 tables). Output: [P/9 (padded to 32), 512] fp32 rows (embed_vision applied).""" from __future__ import annotations from typing import Dict, List, Sequence, Tuple import numpy as np from .. import model_spec as S from ..preprocess.image import Patches from .common import ckc, knobs, mat, norm_w MAX_IMAGES = 64 IN_W = S.V_HIDDEN + 2 * S.V_HEAD_DIM + MAX_IMAGES # 960 = 30 tiles COL_PIX, COL_COS, COL_SIN = 0, S.V_HIDDEN, S.V_HIDDEN + S.V_HEAD_DIM COL_SEG = S.V_HIDDEN + 2 * S.V_HEAD_DIM # one-hot image index per patch (attention mask) CU_LEN = MAX_IMAGES + 2 PERM = np.r_[0:16, 32:48, 16:32, 48:64] def _inv_freq(): dim = S.V_HEAD_DIM // 2 return 1.0 / (S.V_ROPE_THETA ** (np.arange(0, dim, 2, dtype=np.float64) / dim)) # 16 def pool_permutation(p: Patches) -> np.ndarray: """Patch order with the 9 patches of each pooled cell consecutive, cells in output-slot order.""" k = S.V_POOL nh, nw = p.grid x, y = p.positions[:, 0].astype(np.int64), p.positions[:, 1].astype(np.int64) slot = (x // k) + (nw // k) * (y // k) within = (y % k) * k + (x % k) return np.lexsort((within, slot)) class VisionHost: """Host side: the per-launch input rows (pixels, rope tables) and patch indices.""" def __init__(self, W: Dict = None): self.inv = _inv_freq() self.inv32 = self.inv.astype(np.float32) def rows(self, p: Patches, out: np.ndarray = None): """Fill ``out`` [n, IN_W] (or a new array) for one image; -> (rows, x indices, y indices).""" perm = pool_permutation(p) pos = p.positions[perm] n = len(perm) if out is None: out = np.empty((n, IN_W), np.float32) out[:, COL_PIX:COL_COS] = p.pixels[perm] out[:, COL_PIX:COL_COS] *= 2.0 out[:, COL_PIX:COL_COS] -= 1.0 fx = pos[:, 0:1].astype(np.float32) * self.inv32[None, :] fy = pos[:, 1:2].astype(np.float32) * self.inv32[None, :] ang = np.concatenate([fx, fy, fx, fy], axis=1) # [P, 64] in the permuted head layout out[:, COL_COS:COL_SIN] = np.cos(ang) out[:, COL_SIN:COL_SEG] = np.sin(ang) out[:, COL_SEG:] = 0.0 return out, pos[:, 0].astype(np.uint32), pos[:, 1].astype(np.uint32) def pack(self, patches: Sequence[Patches], P: int): if len(patches) > MAX_IMAGES: raise ValueError(f"at most {MAX_IMAGES} images per vision launch") buf = np.empty((P, IN_W), np.float32) idx = np.zeros((2, P), np.uint32) cu = np.full((CU_LEN,), P, np.int32) cu[0] = 0 off = 0 toks = [] for i, p in enumerate(patches): n = p.n_patches if off + n > P: raise ValueError(f"{off + n} patches > bucket {P}") _, idx[0, off: off + n], idx[1, off: off + n] = self.rows(p, buf[off: off + n]) buf[off: off + n, COL_SEG + i] = 1.0 off += n cu[i + 1] = off toks.append(p.n_tokens) buf[off:] = 0.0 return (buf, idx), cu, toks class VisionWeights: def __init__(self, device, W: Dict, wdt: str = "bf16"): import torch p = "vision_tower." perm = torch.as_tensor(PERM) self.layers = [] for l in range(S.V_LAYERS): q = f"{p}encoder.layers.{l}." g = lambda n: W[q + n].float() # noqa: E731 def permute_heads(w): # [12 * 64, 768] -> permute each head's 64 output rows return w.view(S.V_HEADS, S.V_HEAD_DIM, -1)[:, perm].reshape(S.V_HEADS * S.V_HEAD_DIM, -1) qkv = torch.cat([permute_heads(g("self_attn.q_proj.linear.weight")), permute_heads(g("self_attn.k_proj.linear.weight")), g("self_attn.v_proj.linear.weight")], 0) self.layers.append({ "qkv": mat(device, qkv, wdt), "o": mat(device, g("self_attn.o_proj.linear.weight"), wdt), "gate": mat(device, g("mlp.gate_proj.linear.weight"), wdt), "up": mat(device, g("mlp.up_proj.linear.weight"), wdt), "down": mat(device, g("mlp.down_proj.linear.weight"), wdt), "n_in": norm_w(device, g("input_layernorm.weight")), "n_pa": norm_w(device, g("post_attention_layernorm.weight")), "n_pf": norm_w(device, g("pre_feedforward_layernorm.weight")), "n_pff": norm_w(device, g("post_feedforward_layernorm.weight")), "n_q": norm_w(device, g("self_attn.q_norm.weight")[perm]), "n_k": norm_w(device, g("self_attn.k_norm.weight")[perm]), }) self.win = mat(device, W[p + "patch_embedder.input_proj.weight"].float(), wdt) import ttnn tab = W[p + "patch_embedder.position_embedding_table"] self.tab = [ttnn.from_torch(tab[i].contiguous().to(torch.bfloat16), dtype=ttnn.bfloat16, layout=ttnn.ROW_MAJOR_LAYOUT, device=device, memory_config=ttnn.DRAM_MEMORY_CONFIG) for i in (0, 1)] self.ev = mat(device, W["embed_vision.embedding_projection.weight"].float(), "bf16") class VisionProgram: """attn: "mask" (one image per launch: SDPA with the key-padding mask, 64-row chunks) or "cu" (several images: SDPA cu_window_seqlens skips the cross-image blocks).""" def __init__(self, device, vw: VisionWeights, P: int, fidelity: str = "HiFi4", attn: str = "mask"): import torch import ttnn if P % 288: raise ValueError("vision buckets must be multiples of 288 (9 x 32)") self.device, self.vw, self.P = device, vw, int(P) kn = knobs() self.attn = kn["vattn"] if kn.get("vattn") else attn self.vattn = None if self.attn == "mk": from .mk_vattn.program import VAttn self.vattn = VAttn(device, self.P, S.V_HEADS, fast_exp=kn.get("vfastexp", "1") == "1") self.R = self.P // 9 self.ck = ckc(device, knobs()["vfid"] or fidelity) # SDPA compute: "acc" = HiFi4 + fp32 DST (the op's standard kernel), "fast" = HiFi2 + bf16 DST + approximate # exp (the op's streaming kernel, its default; ttaw P7: 1.35-1.45x faster, max error 2x) self.ck_sdpa = ckc(device, "HiFi2", fp32_acc=False, approx=True) if knobs()["sdpa_ck"] == "fast" \ else ckc(device, "HiFi4") self.in_dev = ttnn.allocate_tensor_on_device(ttnn.Shape([1, 1, self.P, IN_W]), ttnn.float32, ttnn.ROW_MAJOR_LAYOUT, device, ttnn.DRAM_MEMORY_CONFIG) self.cu_dev = ttnn.allocate_tensor_on_device(ttnn.Shape([CU_LEN]), ttnn.int32, ttnn.ROW_MAJOR_LAYOUT, device, ttnn.DRAM_MEMORY_CONFIG) self.idx_dev = [ttnn.allocate_tensor_on_device(ttnn.Shape([1, self.P]), ttnn.uint32, ttnn.ROW_MAJOR_LAYOUT, device, ttnn.DRAM_MEMORY_CONFIG) for _ in (0, 1)] pm = np.zeros((self.R, self.P), np.float32) for r in range(self.R): pm[r, 9 * r: 9 * r + 9] = 1.0 / 9.0 self.pm = ttnn.from_torch(torch.from_numpy(pm).reshape(1, 1, self.R, self.P), dtype=ttnn.bfloat16, layout=ttnn.TILE_LAYOUT, device=device, memory_config=ttnn.DRAM_MEMORY_CONFIG) self.trace_id = None self.out = None def _sdpa_cfg(self): """Full grid, q64 x k128 chunks (k64 under 1,000 keys) + additive mask (measured 1.8 ms vs 2.6 ms for the cu windows at 2592 rows; ttaw P7 chunk rule).""" import ttnn g = self.device.compute_with_storage_grid_size() kn = knobs() q = int(kn["sdpa"]) if kn.get("sdpa") else 64 k = int(kn["sdpa_k"]) if kn.get("sdpa_k") else 128 # A/B 2026-11-30: best speed and accuracy at 864 and 2592 if self.attn == "cu": q, k = 128, 128 return ttnn.SDPAProgramConfig(compute_with_storage_grid_size=ttnn.CoreCoord(g.x, g.y), q_chunk_size=q, k_chunk_size=k, exp_approx_mode=knobs()["sdpa_ck"] == "fast") def forward(self): import ttnn vw, P, ck = self.vw, self.P, self.ck inp = ttnn.to_layout(self.in_dev, ttnn.TILE_LAYOUT) pix = ttnn.typecast(ttnn.slice(inp, [0, 0, 0, COL_PIX], [1, 1, P, COL_COS]), ttnn.bfloat16) pos = [ttnn.embedding(self.idx_dev[i], vw.tab[i], layout=ttnn.TILE_LAYOUT, dtype=ttnn.bfloat16) for i in (0, 1)] pos = ttnn.reshape(ttnn.add(pos[0], pos[1], dtype=ttnn.float32), [1, 1, P, S.V_HIDDEN]) cos = ttnn.typecast(ttnn.slice(inp, [0, 0, 0, COL_COS], [1, 1, P, COL_SIN]), ttnn.bfloat16) sin = ttnn.typecast(ttnn.slice(inp, [0, 0, 0, COL_SIN], [1, 1, P, COL_SEG]), ttnn.bfloat16) mask = None if self.attn == "mk": seg0 = ttnn.slice(inp, [0, 0, 0, COL_SEG], [1, 1, P, COL_SEG + 1]) # [P, 1] image 0 mrow = ttnn.transpose(ttnn.multiply(ttnn.subtract(seg0, 1.0), 1e9), -2, -1) # [1, P] 0 / -1e9 mask = ttnn.typecast(mrow, ttnn.bfloat16) if self.attn == "mask": seg = ttnn.slice(inp, [0, 0, 0, COL_SEG], [1, 1, P, IN_W]) # [P, 64] one-hot same = ttnn.matmul(seg, seg, transpose_b=True, compute_kernel_config=ck, dtype=ttnn.float32) mask = ttnn.typecast(ttnn.multiply(ttnn.subtract(same, 1.0), 1e9), ttnn.bfloat16) # 0 / -1e9 x = ttnn.add(ttnn.linear(pix, vw.win, compute_kernel_config=ck, dtype=ttnn.float32), pos, dtype=ttnn.float32) x = ttnn.typecast(x, ttnn.bfloat16) cfg = self._sdpa_cfg() for L in vw.layers: h = ttnn.rms_norm(x, epsilon=S.EPS, weight=L["n_in"], compute_kernel_config=ck) qkv = ttnn.linear(h, L["qkv"], compute_kernel_config=ck, dtype=ttnn.bfloat16) q, k, v = ttnn.experimental.nlp_create_qkv_heads(qkv, num_heads=S.V_HEADS, num_kv_heads=S.V_HEADS, transpose_k_heads=False) ttnn.deallocate(qkv) q = ttnn.experimental.rotary_embedding( ttnn.rms_norm(q, epsilon=S.EPS, weight=L["n_q"], compute_kernel_config=ck), cos, sin, compute_kernel_config=ck) k = ttnn.experimental.rotary_embedding( ttnn.rms_norm(k, epsilon=S.EPS, weight=L["n_k"], compute_kernel_config=ck), cos, sin, compute_kernel_config=ck) v = ttnn.rms_norm(v, epsilon=S.EPS, compute_kernel_config=ck) if self.attn == "mk": a = ttnn.allocate_tensor_on_device(ttnn.Shape([1, S.V_HEADS, P, S.V_HEAD_DIM]), ttnn.bfloat16, ttnn.TILE_LAYOUT, self.device, ttnn.DRAM_MEMORY_CONFIG) self.vattn(q, k, v, mask, a) elif self.attn == "cu": a = ttnn.transformer.scaled_dot_product_attention( q, k, v, is_causal=False, scale=1.0, cu_window_seqlens=self.cu_dev, program_config=cfg, compute_kernel_config=self.ck_sdpa) else: a = ttnn.transformer.scaled_dot_product_attention( q, k, v, attn_mask=mask, is_causal=False, scale=1.0, program_config=cfg, compute_kernel_config=self.ck_sdpa) a = ttnn.experimental.nlp_concat_heads(a) o = ttnn.linear(a, L["o"], compute_kernel_config=ck, dtype=ttnn.bfloat16) x = ttnn.add(x, ttnn.rms_norm(o, epsilon=S.EPS, weight=L["n_pa"], compute_kernel_config=ck)) h = ttnn.rms_norm(x, epsilon=S.EPS, weight=L["n_pf"], compute_kernel_config=ck) # gelu_tanh(gate) * up (two linears + gelu + multiply measured faster than one fused linear + geglu) f = ttnn.multiply(ttnn.gelu(ttnn.linear(h, L["gate"], compute_kernel_config=ck, dtype=ttnn.bfloat16), variant=ttnn.GeluVariant.Tanh), ttnn.linear(h, L["up"], compute_kernel_config=ck, dtype=ttnn.bfloat16)) d = ttnn.linear(f, L["down"], compute_kernel_config=ck, dtype=ttnn.bfloat16) x = ttnn.add(x, ttnn.rms_norm(d, epsilon=S.EPS, weight=L["n_pff"], compute_kernel_config=ck)) pooled = ttnn.matmul(self.pm, x, compute_kernel_config=ck, dtype=ttnn.float32) # [R, 768] pooled = ttnn.rms_norm(pooled, epsilon=S.EPS, compute_kernel_config=ck) return ttnn.linear(pooled, vw.ev, compute_kernel_config=ck, dtype=ttnn.float32) # [R, 512] def load(self, inp, cu): import torch import ttnn buf, idx = inp ttnn.copy_host_to_device_tensor(ttnn.from_torch(torch.from_numpy(buf).reshape(1, 1, self.P, IN_W), dtype=ttnn.float32, layout=ttnn.ROW_MAJOR_LAYOUT), self.in_dev) for i in (0, 1): ttnn.copy_host_to_device_tensor(ttnn.from_torch(torch.from_numpy(idx[i].astype(np.int64)).reshape( 1, self.P).to(torch.int32), dtype=ttnn.uint32, layout=ttnn.ROW_MAJOR_LAYOUT), self.idx_dev[i]) ttnn.copy_host_to_device_tensor(ttnn.from_torch(torch.from_numpy(cu), dtype=ttnn.int32, layout=ttnn.ROW_MAJOR_LAYOUT), self.cu_dev) def compile(self): """Eager forward (program compile, prepared weights); no trace may have been captured before this on the device (persistent allocations must not land in a trace's intermediate region).""" import ttnn self.forward() ttnn.synchronize_device(self.device) def capture(self): import ttnn tid = ttnn.begin_trace_capture(self.device, cq_id=0) self.out = self.forward() ttnn.end_trace_capture(self.device, tid, cq_id=0) self.trace_id = tid def run(self, buf, cu, toks: Sequence[int]) -> List[np.ndarray]: import ttnn self.load(buf, cu) if self.trace_id is not None: ttnn.execute_trace(self.device, self.trace_id, cq_id=0, blocking=False) out = self.out else: out = self.forward() rows = ttnn.to_torch(out).float().reshape(-1, S.HIDDEN).numpy() res, off = [], 0 for n in toks: res.append(rows[off: off + n].copy()) off += n return res def release(self): import ttnn if self.trace_id is not None: ttnn.release_trace(self.device, self.trace_id) self.trace_id = None