# SPDX-License-Identifier: Apache-2.0 """FOV stage, megakernel engine (``engine={"fov": "mk"}``). Stage contract (BASELINE.md ยง2, same as ``tt/ttnn_fov.py``): * ``FOV.in`` ``fpatches`` ``[1, 1, T * Nfp, 768]`` bf16 TILE DRAM (``reference.fov_resize`` frames, unfolded like ``ENC.in``; rows ``>= gh * gw`` of each frame zero); * ``FOV.out`` ``logits`` ``[1, 1, T, 2]`` float32 TILE DRAM. Trunk: the ENC megakernel in FOV mode (:class:`tt.mk_enc.MkEnc`, ``mode="fov"``: DINOv3 ViT-S/16, blocks 5 / 7 / 9 / 11 keep their input prefix, no joint attention, taps after blocks 2 / 5 / 8 / 11 incl. the prefix). Its taps are ``[1, 1, T * (32 + Np), 384]`` bf16: per frame one prefix tile (rows 0..4 = cls, reg0..3; rows 5..31 finite filler) and then the ``Np`` patch rows (rows ``>= N`` finite filler). Head: the float32 head of ``tt/ttnn_fov.py`` (its methods are reused unchanged through a subclass that skips the ttnn trunk); only the constant gather / pooling matrix differs (it reads the megakernel's tap layout). Frames are independent, so a T-frame program serves any n <= T frames (zero frames in the unused slots, outputs ``[:n]``). """ from __future__ import annotations from types import SimpleNamespace from typing import Optional, Tuple import torch from ...reference import model as ref from .. import NUM_PREFIX, StageShape, ceil32 from .. import ttnn_fov from ..mk_enc.program import MkEnc, MkEncWeights from ..ttnn_enc import Configs, _ttnn, exact_layer_norm, full_view, same_buffer from ..weights import FOV_HD, FovHeadWeights, dev_tensor, upload_fov_head TRUNK_DIM = ref.FOV_TRUNK.dim # 384 def mk_head_gather(gh: int, gw: int, np_: int) -> Tuple[torch.Tensor, int]: """``G^T`` ``[32 + Np, S_hp]`` (float32) and ``S_h`` for the megakernel's FOV tap layout: head row 0 = query slot (zero), rows 1..5 = prefix rows 0..4, rows 6.. = ceil-mode 2x2 average of the patch grid (patch p at row 32 + p); weights 1, 1/2, 1/4 (exact in bf16). Same head sequence as ``ttnn_fov.head_gather``.""" lm = 32 + np_ ph, pw = -(-gh // 2), -(-gw // 2) s_h = 1 + NUM_PREFIX + ph * pw g = torch.zeros(ceil32(s_h), lm) for j in range(NUM_PREFIX): g[1 + j, j] = 1.0 for a in range(ph): for b in range(pw): rows = [r for r in (2 * a, 2 * a + 1) if r < gh] cols = [c for c in (2 * b, 2 * b + 1) if c < gw] wgt = 1.0 / (len(rows) * len(cols)) for r in rows: for c in cols: g[1 + NUM_PREFIX + a * pw + b, 32 + r * gw + c] = wgt return g.t().contiguous(), s_h class MkFovWeights: """FOV weights uploaded once: the trunk's megakernel arenas (:class:`MkEncWeights`, mode "fov") and the ttnn float32 head weights (``weights.upload_fov_head``); shared by every FOV shape.""" def __init__(self, device, host_weights, rb: int = 0): self.trunk = MkEncWeights(device, host_weights, "S", "fov", rb=rb) self.head: FovHeadWeights = upload_fov_head(device, host_weights) self.size, self.mode = "S", "fov" class _Head(ttnn_fov.Engine): """The ttnn FOV head (``ttnn_fov.Engine`` methods ``_ln`` / ``_lin`` / ``_attn32`` / ``_head_block``) without its ttnn trunk, on the megakernel's tap layout.""" def __init__(self, device, head: FovHeadWeights, shape: StageShape, np_: int): # noqa: D401 (no super().__init__) ttnn = _ttnn() self.device = device self.shape = shape self.w = SimpleNamespace(head=head) self.cfgs = Configs(device) self.mem = ttnn.DRAM_MEMORY_CONFIG gt, s_h = mk_head_gather(shape.gh, shape.gw, np_) self.s_h, self.s_hp = s_h, gt.shape[1] self.gather_t = dev_tensor(gt.reshape(1, 1, *gt.shape), device) ph, pw = -(-shape.gh // 2), -(-shape.gw // 2) add = torch.zeros(1, 1, self.s_hp, FOV_HD) add[0, 0, 0] = head.query_host add[0, 0, 1:1 + NUM_PREFIX] = head.prefix_embed_host add[0, 0, 1 + NUM_PREFIX:s_h] = ref.sincos_2d(ph, pw, FOV_HD) self.head_add_host = add self.head_pc = self.cfgs.sdpa_program(s_h, s_h) import os self.head32 = os.environ.get("DEPTHPRO2_TTNN_FOV_HEAD", "fp32") == "fp32" self.act = ttnn.float32 if self.head32 else ttnn.bfloat16 self.head_add = dev_tensor(add, device, dtype=self.act) if self.head32: cm = torch.ones(1, 1, 1, FOV_HD) self.colmask = dev_tensor(cm, device, dtype=ttnn.float32) def head(self, taps) -> object: """4 megakernel taps ``[1, 1, T * (32 + Np), 384]`` -> logits ``[1, 1, T, 2]`` float32 (``ttnn_fov.Engine.run`` after its trunk).""" ttnn = _ttnn() T = self.shape.frames hw = self.w.head lm = taps[0].padded_shape[-2] // T normed = [] for i, t in enumerate(taps): # the taps are the megakernel's persistent outputs: views only, never freed v = ttnn.reshape(t, [T, 1, lm, TRUNK_DIM]) normed.append(exact_layer_norm(v, hw.tap_n_w[i], hw.tap_n_b[i], ref.LN_EPS, self.mem, self.cfgs.ln)) if not same_buffer(v, t): ttnn.deallocate(v) cat = ttnn.concat(normed, dim=-1, memory_config=self.mem) # [T, 1, Lm, 1536] for t in normed: ttnn.deallocate(t) y = self._lin(cat, hw.proj_w, hw.proj_b) # [T, 1, Lm, 248] ttnn.deallocate(cat) yt = ttnn.transpose(y, -2, -1, memory_config=self.mem) # [T, 1, 248, Lm] ttnn.deallocate(y) zt = ttnn.matmul(yt, self.gather_t, memory_config=self.mem, dtype=self.act, compute_kernel_config=self.cfgs.mm) ttnn.deallocate(yt) z = ttnn.transpose(zt, -2, -1, memory_config=self.mem) # [T, 1, S_hp, 248] ttnn.deallocate(zt) x = ttnn.add(z, self.head_add, memory_config=self.mem) ttnn.deallocate(z) for p in hw.blocks: x2 = self._head_block(x, p) ttnn.deallocate(x) x = x2 q0 = ttnn.slice(full_view(x), [0, 0, 0, 0], [T, 1, 32, FOV_HD], memory_config=self.mem) ttnn.deallocate(x) h = self._ln(q0, hw.norm_w, hw.norm_b) ttnn.deallocate(q0) lg = ttnn.linear(h, hw.out_w, bias=hw.out_b, memory_config=self.mem, dtype=ttnn.float32, compute_kernel_config=self.cfgs.mm) # [T, 1, 32, 2] float32 ttnn.deallocate(h) r0 = ttnn.slice(lg, [0, 0, 0, 0], [T, 1, 1, 2], memory_config=self.mem) ttnn.deallocate(lg) return ttnn.reshape(r0, [1, 1, T, 2], memory_config=self.mem) class Engine: """FOV stage engine for one :class:`StageShape` (the fov-resized size): ``run(fpatches) -> logits [1, 1, T, 2]`` float32. ``weights``: :meth:`prepare_weights` (shared by every shape) or the DepthPro2-focal host dict.""" def __init__(self, device, weights, shape: StageShape, size: Optional[str] = None, **kw): if isinstance(weights, dict): weights = Engine.prepare_weights(device, weights) self.shape = shape self.weights = weights self.mk = MkEnc(device, weights.trunk, "S", shape.frames, shape.gh, shape.gw, mode="fov", **kw) self._head = _Head(device, weights.head, shape, self.mk.geo.Np) @staticmethod def prepare_weights(device, host_weights, size: str = "fov") -> MkFovWeights: return MkFovWeights(device, host_weights) def input_spec(self): return (1, 1, self.shape.frames * self.mk.geo.Np, 768), "bf16 TILE DRAM" def run(self, fpatches) -> object: return self._head.head(self.mk.run(fpatches))