DepthPro2 / code /tt_depthpro2 /tt /ttnn_fov.py
changh95's picture
tt-model push depthpro2 (container)
b7e49b8 verified
Raw History Blame Contribute Delete
10.9 kB
# SPDX-License-Identifier: Apache-2.0
"""FOV stage, ttnn baseline: DINOv3 ViT-S/16 trunk (taps incl. prefix) + attention head -> logits.
Stage contract (SPEC §3):
* ``FOV.in`` ``fpatches`` ``[1, 1, T * Nfp, 768]`` bf16 TILE DRAM, from the host-resized frames
(``reference.fov_resize``, then ``tt.weights.unfold_patches``); ``Nfp = ceil32(gh * gw)``.
* ``FOV.out`` ``logits`` ``[1, 1, T, 2]`` float32 TILE DRAM (``ttnn.to_torch(...).reshape(T, 2)``); degrees on the host
with ``reference.fov_logits_to_deg``.
Trunk: :class:`tt.ttnn_enc.Trunk` with ``joint_cross=False`` (blocks 5/7/9/11 keep their input prefix rows, no joint
attention). Head (``reference.fov_head``), all on the device:
* ``y = Linear(1536 -> 248)(cat_i LN_i(tap_i))`` on every token row ``[T, 1, Lp, 248]``;
* the head sequence ``[query ; prefix + prefix_embed ; avgpool2x2(patches) + sincos]`` is ONE matmul with a constant
gather / pooling matrix ``G`` (``[S_h, Lp]``: prefix-row selection and the ceil-mode 2x2 average weights 1, 1/2, 1/4,
all exact in bf16) plus a constant row tensor (query, prefix_embed, sincos code);
* 2 timm ViT blocks (dim 248, 4 heads of 62 dims zero-padded to 64 on the device, scale 1/sqrt(62)), LN, Linear(248 -> 2)
on the query row.
"""
from __future__ import annotations
import os
from typing import List, Optional, Tuple
import torch
from ..reference import model as ref
from . import NUM_PREFIX, StageShape, ceil32
from .ttnn_enc import Configs, Trunk, _ttnn, fp32_attn_blocks, full_view, sdpa_windowed, view
from .weights import FOV_HD, FOV_HDIM_P, FOV_HEADS, FovWeights, dev_tensor, fov_head_scale, upload_fov
def head_gather(shape: StageShape) -> Tuple[torch.Tensor, int]:
"""``G^T`` ``[Lp, S_hp]`` (float32) and ``S_h``: head row 0 = query slot (zero), rows 1..5 = prefix rows N..N+4,
rows 6.. = ceil-mode 2x2 average of the patch grid (raster order)."""
gh, gw, n, lp = shape.gh, shape.gw, shape.n, shape.lp
ph, pw = -(-gh // 2), -(-gw // 2)
s_h = 1 + NUM_PREFIX + ph * pw
g = torch.zeros(ceil32(s_h), lp)
for j in range(NUM_PREFIX):
g[1 + j, n + 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, r * gw + c] = wgt
return g.t().contiguous(), s_h
class Engine:
"""ttnn FOV engine for one :class:`StageShape` (the fov-resized frame size): ``run(fpatches) -> logits [1, 1, T, 2]``."""
def __init__(self, device, weights, shape: StageShape, size: Optional[str] = None):
ttnn = _ttnn()
if isinstance(weights, dict):
weights = Engine.prepare_weights(device, weights, "fov")
self.device = device
self.w: FovWeights = weights
self.shape = shape
self.cfgs = Configs(device)
self.mem = ttnn.DRAM_MEMORY_CONFIG
cfg = ref.FOV_TRUNK
self.trunk = Trunk(device, weights.trunk, shape, joint_cross=False, tap_blocks=cfg.reassembled_blocks,
cross_blocks=cfg.cross_frame_blocks, fp32_blocks=fp32_attn_blocks("fov"), cfgs=self.cfgs)
gt, s_h = head_gather(shape)
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] = weights.head.query_host
add[0, 0, 1:1 + NUM_PREFIX] = weights.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_add = dev_tensor(add, device)
self.head_pc = self.cfgs.sdpa_program(s_h, s_h)
self.head_cu = (self.trunk._dev_cu(torch.tensor([0, s_h], dtype=torch.int32))
if sdpa_windowed(shape.frames, FOV_HEADS) else None)
# DEPTHPRO2_TTNN_FOV_HEAD = fp32 (default: the official head runs in float32 -- fp32 activations, exact
# LayerNorm over the 248 columns, fp32-score attention on fp32 q / k / v) | bf16 (bf16 activations, SDPA)
self.head32 = os.environ.get("DEPTHPRO2_TTNN_FOV_HEAD", "fp32") == "fp32"
self.act = ttnn.float32 if self.head32 else ttnn.bfloat16
if self.head32:
cm = torch.zeros(1, 1, 1, FOV_HD)
cm[...] = 1.0
self.colmask = dev_tensor(cm, device, dtype=ttnn.float32) # logical 248 columns, padding 0
add = self.head_add_host
self.head_add = dev_tensor(add, device, dtype=ttnn.float32)
@staticmethod
def prepare_weights(device, host_weights, size: str = "fov") -> FovWeights:
return upload_fov(device, host_weights)
def _ln(self, x, w, b):
"""LayerNorm over the 248 logical columns (padding columns are zero in and out)."""
ttnn = _ttnn()
if not self.head32:
return ttnn.layer_norm(x, epsilon=ref.LN_EPS, weight=w, bias=b, memory_config=self.mem,
compute_kernel_config=self.cfgs.ln)
mem, cfg = self.mem, self.cfgs.ln
s1 = ttnn.sum(x, dim=-1, keepdim=True, memory_config=mem, compute_kernel_config=cfg)
mu = ttnn.multiply(s1, 1.0 / FOV_HD, memory_config=mem)
ttnn.deallocate(s1)
d = ttnn.subtract(x, mu, memory_config=mem)
ttnn.deallocate(mu)
xc = ttnn.multiply(d, self.colmask, memory_config=mem)
ttnn.deallocate(d)
sq = ttnn.multiply(xc, xc, memory_config=mem)
s2 = ttnn.sum(sq, dim=-1, keepdim=True, memory_config=mem, compute_kernel_config=cfg)
ttnn.deallocate(sq)
var = ttnn.multiply(s2, 1.0 / FOV_HD, memory_config=mem)
ttnn.deallocate(s2)
ve = ttnn.add(var, ref.LN_EPS, memory_config=mem)
ttnn.deallocate(var)
rs = ttnn.rsqrt(ve, memory_config=mem)
ttnn.deallocate(ve)
xn = ttnn.multiply(xc, rs, memory_config=mem)
ttnn.deallocate(xc)
ttnn.deallocate(rs)
y = ttnn.multiply(xn, w, memory_config=mem)
ttnn.deallocate(xn)
out = ttnn.add(y, b, memory_config=mem)
ttnn.deallocate(y)
return out
def _lin(self, x, w, b=None, act=None, dtype=None):
ttnn = _ttnn()
return ttnn.linear(x, w, bias=b, activation=act, memory_config=self.mem, dtype=dtype or self.act,
compute_kernel_config=self.cfgs.mm)
def _attn32(self, q, k, v):
"""fp32-score attention on fp32 q / k / v [T, 4, S_h (logical), 64] (scale 1/sqrt(62))."""
ttnn = _ttnn()
mem = self.mem
qs = ttnn.multiply(q, fov_head_scale(), memory_config=mem)
kt = ttnn.transpose(k, -2, -1, memory_config=mem)
sc = ttnn.matmul(qs, kt, memory_config=mem, dtype=ttnn.float32, compute_kernel_config=self.cfgs.mm)
ttnn.deallocate(qs)
ttnn.deallocate(kt)
pr = ttnn.softmax(sc, dim=-1, numeric_stable=True, memory_config=mem, compute_kernel_config=self.cfgs.mm)
ttnn.deallocate(sc)
o = ttnn.matmul(pr, v, memory_config=mem, dtype=ttnn.float32, compute_kernel_config=self.cfgs.mm)
ttnn.deallocate(pr)
return o
def _head_block(self, x, p):
ttnn = _ttnn()
T, s_h, s_hp = self.shape.frames, self.s_h, self.s_hp
h = self._ln(x, p["n1_w"], p["n1_b"])
qkv = self._lin(h, p["qkv_w"], p["qkv_b"])
ttnn.deallocate(h)
q, k, v = ttnn.experimental.nlp_create_qkv_heads(qkv, num_heads=FOV_HEADS, num_kv_heads=FOV_HEADS,
transpose_k_heads=False, memory_config=self.mem)
ttnn.deallocate(qkv)
shp, pad = [T, FOV_HEADS, s_h, FOV_HDIM_P], [T, FOV_HEADS, s_hp, FOV_HDIM_P]
if self.head32:
o = self._attn32(view(q, shp, pad), view(k, shp, pad), view(v, shp, pad))
else:
o = ttnn.transformer.scaled_dot_product_attention(view(q, shp, pad), view(k, shp, pad), view(v, shp, pad),
is_causal=False, scale=fov_head_scale(), program_config=self.head_pc,
compute_kernel_config=self.cfgs.sdpa, memory_config=self.mem,
cu_window_seqlens=self.head_cu)
for t in (q, k, v):
ttnn.deallocate(t)
a = ttnn.experimental.nlp_concat_heads(full_view(o), memory_config=self.mem)
ttnn.deallocate(o)
pr = self._lin(a, p["proj_w"], p["proj_b"])
ttnn.deallocate(a)
x1 = ttnn.add(x, pr, memory_config=self.mem)
ttnn.deallocate(pr)
h = self._ln(x1, p["n2_w"], p["n2_b"])
m = self._lin(h, p["fc1_w"], p["fc1_b"], act="gelu")
ttnn.deallocate(h)
f = self._lin(m, p["fc2_w"], p["fc2_b"])
ttnn.deallocate(m)
x2 = ttnn.add(x1, f, memory_config=self.mem)
ttnn.deallocate(f)
ttnn.deallocate(x1)
return x2
def run(self, fpatches) -> object:
ttnn = _ttnn()
T = self.shape.frames
hw = self.w.head
taps = self.trunk.run(fpatches) # 4 x [T, 1, Lp, 384], incl. prefix rows
normed = [self.trunk._ln(t, hw.tap_n_w[i], hw.tap_n_b[i]) for i, t in enumerate(taps)] # 384-wide: exact LN
for t in taps:
ttnn.deallocate(t)
cat = ttnn.concat(normed, dim=-1, memory_config=self.mem) # [T, 1, Lp, 1536]
for t in normed:
ttnn.deallocate(t)
y = self._lin(cat, hw.proj_w, hw.proj_b) # [T, 1, Lp, 248]
ttnn.deallocate(cat)
yt = ttnn.transpose(y, -2, -1, memory_config=self.mem) # [T, 1, 248, Lp]
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)