DepthPro2 / code /tt_depthpro2 /tt /ttnn_enc.py
changh95's picture
tt-model push depthpro2 (container)
b7e49b8 verified
Raw History Blame Contribute Delete
34.1 kB
# SPDX-License-Identifier: Apache-2.0
"""ENC stage, ttnn baseline: patch embedding + prefix + every DINOv3 block (within-frame / cross-frame) -> 4 taps.
Stage contract (SPEC §3):
* ``ENC.in`` ``patches`` ``[1, 1, T * Np, 768]`` bf16 TILE DRAM, rows ``>= N`` of each frame zero
(host: ``tt.weights.unfold_patches``; columns in ``(c, ky, kx)`` order).
* ``ENC.out`` ``taps[i]`` ``[1, 1, T * Np, C]`` bf16 TILE DRAM, raster order of the grid, rows ``>= N`` of each frame
are garbage (here: the prefix tokens and finite padding).
Internal token layout (ttnn engine only): ``X`` ``[T, 1, Lp, C]`` with, per frame, rows ``[0, N)`` = patch tokens,
rows ``[N, N + 5)`` = cls + 4 registers, rows ``[N + 5, Lp)`` = finite padding, ``Lp = ceil32(N + 5)``. Attention is
order-invariant (RoPE is applied per row from a table whose prefix / padding rows are the identity), so a within-frame
block is one plain SDPA over the logical ``N + 5`` rows; the op masks the padded keys itself.
Cross-frame block, ``T > 1``: the joint sequence ``[pooled prefix (5) ; patches of frames 0..T-1 (T * N)]`` (patch
rows compacted with a tiled ``ttnn.reshape``, the pooled prefix concatenated in front) runs through ONE windowed
``ttnn.transformer.scaled_dot_product_attention`` (``cu_window_seqlens``); each frame's own prefix rows are carried
over unchanged. ``T == 1``: the joint sequence equals the frame's own sequence, so the block is a within-frame block
whose prefix-row updates are masked out.
Runtime valid-frame count (one T-frame program serves any n-frame clip, ``1 <= n <= T``): the host puts the n frames
in frame slots ``[0, n)`` (slots ``>= n``: zero patches) and calls ``Engine.set_valid_frames(n)`` before the run /
trace replay. Two persistent device tensors carry ``n`` (written with ``ttnn.copy_host_to_device_tensor``):
* ``vf_cu`` int32 ROW_MAJOR DRAM, shape ``[3]`` = ``[0, 5 + n * N, 5 + T * N]``: window 0 = pooled prefix + frames
``< n`` (the clip's joint keys / queries), window 1 = frames ``>= n`` (they only see each other: don't-care);
* ``vf_w`` float32 TILE DRAM, shape ``[T, 1, 1, 1]`` = ``1 / n`` for ``t < n`` else 0: pooled prefix =
``sum_t vf_w[t] * prefix_t``.
Within-frame blocks need nothing (frames are independent); taps / outputs of frames ``>= n`` are don't-care.
The same :class:`Trunk` runs the FOV trunk (``joint_cross=False``: blocks 5/7/9/11 freeze the prefix, no joint
attention; taps include the prefix rows).
"""
from __future__ import annotations
import os
from typing import Dict, List, Optional, Sequence, Tuple
import torch
from ..reference import model as ref
from . import NUM_PREFIX, StageShape, ceil32
from .weights import BlockWeights, TrunkWeights, dev_tensor, upload_trunk
HEAD_DIM = 64
#: Blocks whose attention logits reach 1e4..3e6 (|q|, |k| ~ 1e3 with a hard, RoPE-positional attention pattern; host scan
#: of every golden input, logs/depthpro2/baseline/BASELINE.md). The stock flash SDPA keeps its running row max in bf16
#: (ulp 2^-8 relative), so exp() overflows there (block 0 of S: PCC 0.36). These blocks run an fp32-score attention
#: (QK^T in fp32, fp32 softmax, bf16 P @ V), chunked over query rows. The max logit of every other block is < 700.
FP32_ATTN_BLOCKS = {"S": (0,), "B": (0,), "L": (1,), "H": (0, 1), "fov": (0,)}
def fp32_attn_blocks(key: str) -> Tuple[int, ...]:
"""``DEPTHPRO2_TTNN_FP32_ATTN`` = ``auto`` (table above) | ``none`` | ``all`` | comma list of block indices."""
o = _env("DEPTHPRO2_TTNN_FP32_ATTN", "auto")
if o == "auto":
return FP32_ATTN_BLOCKS[key]
if o == "none":
return ()
if o == "all":
return tuple(range(64))
return tuple(int(v) for v in o.split(",") if v.strip())
# ----------------------------------------------------------------------------------------------- shared ttnn helpers
def _ttnn():
import ttnn
return ttnn
def _env(name: str, default: str) -> str:
return os.environ.get(name, default)
def kernel_config(device, fidelity: str = "hifi4", fp32_acc: bool = True, approx: bool = False):
ttnn = _ttnn()
fid = {"hifi4": ttnn.MathFidelity.HiFi4, "hifi3": ttnn.MathFidelity.HiFi3, "hifi2": ttnn.MathFidelity.HiFi2,
"lofi": ttnn.MathFidelity.LoFi}[fidelity]
return ttnn.init_device_compute_kernel_config(device.arch(), math_fidelity=fid, math_approx_mode=approx,
fp32_dest_acc_en=fp32_acc, packer_l1_acc=True)
def view(t, logical: Sequence[int], padded: Optional[Sequence[int]] = None):
"""Logical-shape view of a TILE tensor (same buffer). ``padded`` defaults to the tensor's padded shape."""
ttnn = _ttnn()
padded = list(padded) if padded is not None else list(t.padded_shape)
padded[-1] = ceil32(padded[-1]) # TILE: the last dim is always padded to the tile width
return ttnn.reshape(t, ttnn.Shape(list(logical)), ttnn.Shape(padded))
def full_view(t):
"""View with logical shape == padded shape."""
return view(t, list(t.padded_shape))
def same_buffer(a, b) -> bool:
"""True if ``a`` and ``b`` share a device buffer (``ttnn.reshape`` returns a view for tile-aligned reshapes:
deallocating the source would free the view's memory)."""
try:
return a.buffer_address() == b.buffer_address()
except Exception: # noqa: BLE001
return a is b
def free_unless_shared(src, dst) -> None:
"""Deallocate ``src`` unless ``dst`` is a view of it."""
if not same_buffer(src, dst):
_ttnn().deallocate(src)
def sdpa_chunks(sq: int, sk: int, joint: int = 0) -> Tuple[int, int]:
"""(q_chunk, k_chunk) for an SDPA over ``sq`` queries / ``sk`` keys (+ ``joint`` keys of a joint SDPA, which the op
pads to a whole k chunk). The largest k chunk in {1024, 512, 256, 128} whose padding stays within 15 % (fewer
online-softmax rescales of the bf16 partial output: S block-4 attention rel. error 3.8e-3 at k256, 2.9e-3 at
k1024), else the least padding. ``DEPTHPRO2_TTNN_SDPA_CHUNKS=q,k`` overrides."""
o = _env("DEPTHPRO2_TTNN_SDPA_CHUNKS", "")
if o:
q, k = (int(v) for v in o.split(","))
return q, k
def padded(k):
return -(-sk // k) * k + (k if joint else 0)
need = sk + joint
for k in (1024, 512, 256, 128):
if padded(k) <= 1.15 * need:
return 64, k
return 64, min((1024, 512, 256, 128), key=lambda k: (padded(k), -k))
class Configs:
"""Compute-kernel configs of the baseline (accuracy first: HiFi4 + fp32 accumulation; env knobs for A/B)."""
def __init__(self, device):
self.mm = kernel_config(device, _env("DEPTHPRO2_TTNN_MM_FID", "hifi4"), True)
self.ln = kernel_config(device, "hifi4", True)
self.sdpa = kernel_config(device, _env("DEPTHPRO2_TTNN_SDPA_FID", "hifi4"), _env("DEPTHPRO2_TTNN_SDPA_FP32", "1") == "1")
self.eltwise = kernel_config(device, "hifi4", True)
self.grid = device.compute_with_storage_grid_size()
# DEPTHPRO2_TTNN_MM=minimal: trunk linears through ttnn.experimental.minimal_matmul (A/B knob)
self.minimal = None
if _env("DEPTHPRO2_TTNN_MM", "linear") == "minimal":
import ttnn
m, k, n, sh, sw = (int(v) for v in _env("DEPTHPRO2_TTNN_MM_BLOCKS", "8,4,4,1,4").split(","))
self.minimal = ttnn.MinimalMatmulConfig(M_block_size=m, K_block_size=k, N_block_size=n, subblock_h=sh,
subblock_w=sw, compute_with_storage_grid_size=self.grid)
def sdpa_program(self, sq: int, sk: int, joint: int = 0):
ttnn = _ttnn()
q, k = sdpa_chunks(sq, sk, joint)
return ttnn.SDPAProgramConfig(compute_with_storage_grid_size=self.grid, q_chunk_size=q, k_chunk_size=k,
exp_approx_mode=False)
#: SDPA mode. The plain (non-windowed) non-causal ttnn SDPA forwards K/V between the cores of a head ("KV chain
#: forwarding", sdpa_program_factory.cpp) and returns garbage (inf, or PCC 0.97-0.99 / ~0) for some heads with many
#: (q_chunk, k_chunk, batch, heads, S) combinations once batch x heads is large: q64/k256 at S = 1205 (480x640) with
#: B x heads = 80 (4 x 20), 96 (16 x 6, S at T = 16: inverse depth 5e35), 320 (16 x 20), 96 (1 x 96); q128/k512 at
#: 4 x 20; q64/k128 at 16 x 6, S = 773. The windowed program (``cu_window_seqlens``) never builds those chains, so it is
#: used whenever batch x heads > ``SDPA_PLAIN_MAX``, with one window over the whole sequence. Up to 24 (every T = 1
#: program: heads 6 / 12 / 16 / 20, FOV 6; S 256x320 T = 4) the plain op was correct in every probe (S 325 .. 8165,
#: q 64 / 128 / 256, k 128 .. 1024, per-head PCC > 0.9999) and is 1.3-2.2x faster (K/V forwarding: 0.15 vs 0.34 ms at
#: 1 x 6 x 1205). ``DEPTHPRO2_TTNN_SDPA_WINDOWED=0`` = plain everywhere (A/B only: wrong at T = 16),
#: ``DEPTHPRO2_TTNN_SDPA_PLAIN_MAX=0`` = windowed everywhere.
SDPA_WINDOWED = os.environ.get("DEPTHPRO2_TTNN_SDPA_WINDOWED", "1") == "1"
SDPA_PLAIN_MAX = int(os.environ.get("DEPTHPRO2_TTNN_SDPA_PLAIN_MAX", "24"))
def sdpa_windowed(batch: int, heads: int) -> bool:
"""Whether an SDPA over ``batch`` x ``heads`` (q, k, v [batch, heads, S, d]) must run windowed (see SDPA_WINDOWED)."""
return SDPA_WINDOWED and batch * heads > SDPA_PLAIN_MAX
def valid_frame_cu(T: int, n: int, n_patches: int) -> torch.Tensor:
"""``vf_cu`` (int32, 3 values): window boundaries of the joint sequence ``[pooled prefix (5) ; T x N patches]``:
window 0 = the pooled prefix and the first ``n`` frames (the clip), window 1 = frames ``n..T-1`` (masked out)."""
s = NUM_PREFIX + T * n_patches
return torch.tensor([0, NUM_PREFIX + n * n_patches, s], dtype=torch.int32)
def valid_frame_weights(T: int, n: int) -> torch.Tensor:
"""``vf_w`` (float32 ``[T, 1, 1, 1]``): pooled-prefix weight of each frame, ``1 / n`` for ``t < n`` else 0."""
w = torch.zeros(T, 1, 1, 1)
w[:n] = 1.0 / n
return w
def exact_layer_norm(x, w, b, eps: float, mem, cfg):
"""LayerNorm in float32 from elementwise / reduction ops (mean, x - mean, mean of squares, rsqrt): float32-exact
(rms rel. 7e-8 on DINOv3 block inputs). ``ttnn.layer_norm`` (HiFi4, fp32 acc) has a per-row scale error of
-1.8e-4 +- 3.3e-4 (BASELINE.md §4), which moves the global depth scale of sensitive images. ``w`` / ``b``: [1, C]."""
ttnn = _ttnn()
x32 = x if x.dtype == ttnn.float32 else ttnn.typecast(x, ttnn.float32, memory_config=mem)
mu = ttnn.mean(x32, dim=-1, keepdim=True, memory_config=mem, compute_kernel_config=cfg)
xc = ttnn.subtract(x32, mu, memory_config=mem)
ttnn.deallocate(mu)
if x32 is not x:
ttnn.deallocate(x32)
sq = ttnn.multiply(xc, xc, memory_config=mem)
var = ttnn.mean(sq, dim=-1, keepdim=True, memory_config=mem, compute_kernel_config=cfg)
ttnn.deallocate(sq)
ve = ttnn.add(var, 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)
if w is None:
return xn
y = ttnn.multiply(xn, w, memory_config=mem)
ttnn.deallocate(xn)
if b is None:
return y
out = ttnn.add(y, b, memory_config=mem)
ttnn.deallocate(y)
return out
def rope_rows(gh: int, gw: int, rows: int, repeat: int = 1, offset: int = 0) -> Tuple[torch.Tensor, torch.Tensor]:
"""cos / sin tables ``[1, 1, rows, 64]``: the reference ``rope_table`` repeated ``repeat`` times from row
``offset``, the identity (cos 1, sin 0) on every other row (prefix tokens and padding)."""
sin, cos = ref.rope_table(gh, gw)
n = sin.shape[0] * repeat
c = torch.ones(rows, HEAD_DIM)
s = torch.zeros(rows, HEAD_DIM)
c[offset:offset + n] = cos.repeat(repeat, 1)
s[offset:offset + n] = sin.repeat(repeat, 1)
return c.reshape(1, 1, rows, HEAD_DIM), s.reshape(1, 1, rows, HEAD_DIM)
# ----------------------------------------------------------------------------------------------- trunk
class Trunk:
"""A DINOv3 trunk on one :class:`StageShape` (T frames of ``gh x gw`` patches).
``run(patches)`` -> the token tensors ``X`` ``[T, 1, Lp, C]`` after each tap block (see module doc)."""
def __init__(self, device, tw: TrunkWeights, shape: StageShape, *, joint_cross: bool, tap_blocks: Sequence[int],
cross_blocks: Sequence[int], fp32_blocks: Sequence[int] = (), cfgs: Optional[Configs] = None):
ttnn = _ttnn()
self.device = device
self.tw = tw
self.cfg = tw.cfg
self.shape = shape
self.joint_cross = joint_cross
self.tap_blocks = tuple(tap_blocks)
self.cross_blocks = set(cross_blocks)
self.fp32_blocks = set(fp32_blocks)
if joint_cross and shape.frames > 1 and self.fp32_blocks & self.cross_blocks:
raise NotImplementedError(f"fp32 attention in a joint cross-frame block: {sorted(self.fp32_blocks & self.cross_blocks)}")
self.c = self.cfg.dim
self.heads = self.cfg.heads
self.cfgs = cfgs or Configs(device)
T, n, np_, lp = shape.frames, shape.n, shape.np_, shape.lp
self.T, self.n, self.np_, self.lp = T, n, np_, lp
self.mem = ttnn.DRAM_MEMORY_CONFIG
self.act_dtype = ttnn.bfloat16
# precision knob (DEPTHPRO2_TTNN_PREC): "bf16" = bf16 residual stream and activations; "fp32res" = fp32 residual
# stream (LN reads fp32); "fp32act" = fp32 residual + fp32 proj / fc1 / fc2 outputs (q / k / v stay bf16)
# default fp32act: local per-block error 1.24x the official bf16-autocast run's (bf16: ~1.6x); see BASELINE.md
prec = _env("DEPTHPRO2_TTNN_PREC", "fp32act")
self.prec = prec
self.resid_dtype = ttnn.float32 if prec in ("fp32res", "fp32act") else ttnn.bfloat16
self.branch_dtype = ttnn.float32 if prec == "fp32act" else ttnn.bfloat16
# DEPTHPRO2_TTNN_LN = exact (default: fp32 LayerNorm from eltwise / reduction ops) | op (ttnn.layer_norm)
self.ln_exact = _env("DEPTHPRO2_TTNN_LN", "exact") == "exact"
c = self.c
# row constant added to the bias-less patch matmul: rows < N: patch-embed bias; N..N+4: cls + registers; rest 0
e = torch.zeros(1, 1, lp, c)
e[0, 0, :n] = tw.pe_b_host
e[0, 0, n:n + NUM_PREFIX] = tw.prefix_host
self.embed_rows = dev_tensor(e, device, dtype=self.resid_dtype)
self.pad_rows = dev_tensor(torch.zeros(T, 1, lp - np_, 768), device) if lp > np_ else None
cos, sin = rope_rows(shape.gh, shape.gw, lp)
# RoPE (DEPTHPRO2_TTNN_ROPE): "eltwise" (default) = q * cos + swap_halves(q) * sin_signed with float32 tables
# and float32 math on the bf16 q / k, one bf16 rounding at the end (what torch autocast does);
# "op" = ttnn.experimental.rotary_embedding with bf16 tables; "op32" = the same op on fp32 qkv / tables.
# The bf16 op shifts the global depth scale of sensitive images by ~2 % per block (systematic per-position
# error of the rounded tables; logits up to ~500): BASELINE.md §4.
self.rope_mode = _env("DEPTHPRO2_TTNN_ROPE", "op32" if _env("DEPTHPRO2_TTNN_ROPE32", "0") == "1" else "eltwise")
self.rope32 = self.rope_mode == "op32"
self.tables = {}
self.tables32 = {}
self.add_rope_table("frame", cos, sin)
# patch-row mask (1 on rows < N): freezes the prefix rows (T == 1 cross-frame block, FOV prefix freeze)
m = torch.zeros(1, 1, lp, 1)
m[0, 0, :n] = 1.0
self.patch_mask = dev_tensor(m, device, dtype=self.resid_dtype)
self.cross_compact = joint_cross and T > 1
if self.cross_compact:
# joint sequence of a cross-frame block: [pooled prefix (5) ; patches of frames 0..T-1 (T * N)]
self.s_joint = NUM_PREFIX + T * n
cos_t, sin_t = rope_rows(shape.gh, shape.gw, ceil32(self.s_joint), repeat=T, offset=NUM_PREFIX)
self.add_rope_table("clip", cos_t, sin_t)
# runtime valid-frame count (set_valid_frames): windowed SDPA boundaries and pooled-prefix weights
self.vf_cu = self._dev_cu(valid_frame_cu(T, T, n))
self.vf_w = dev_tensor(valid_frame_weights(T, T), device, dtype=ttnn.float32)
self.valid_frames = T
self.hook = None # debug: hook(block_index, x) after every block (eager runs only)
# within-frame SDPA [T, heads, N + 5]: windowed (one window = the frame's N + 5 tokens) above SDPA_PLAIN_MAX
self.wf_cu = self._dev_cu(torch.tensor([0, n + NUM_PREFIX], dtype=torch.int32)) if sdpa_windowed(T, self.heads) else None
self.sdpa_pc = self.cfgs.sdpa_program(n + NUM_PREFIX, n + NUM_PREFIX)
# fp32-score attention: query rows per chunk so that one [T, H, rows, Lp] fp32 score tensor stays under the budget
budget = int(_env("DEPTHPRO2_TTNN_ATTN_BYTES", str(256 << 20)))
self.q_rows = max(32, min(lp, budget // (T * self.heads * lp * 4) // 32 * 32))
self.win_pc = self.cfgs.sdpa_program(self.s_joint, self.s_joint) if self.cross_compact else None
# -- constants / runtime inputs
def add_rope_table(self, name: str, cos: torch.Tensor, sin: torch.Tensor) -> None:
"""Register RoPE tables ``[1, 1, rows, 64]`` (bf16 for the ``op`` mode, fp32 / signed sin for ``eltwise``)."""
ttnn = _ttnn()
if self.rope_mode == "op":
self.tables[name] = (dev_tensor(cos, self.device), dev_tensor(sin, self.device))
elif self.rope32:
self.tables32[name] = (dev_tensor(cos, self.device, dtype=ttnn.float32), dev_tensor(sin, self.device, dtype=ttnn.float32))
elif self.rope_mode == "eltwise":
sin_signed = torch.cat([-sin[..., :HEAD_DIM // 2], sin[..., HEAD_DIM // 2:]], dim=-1)
self.tables32[name] = (dev_tensor(cos, self.device, dtype=ttnn.float32),
dev_tensor(sin_signed, self.device, dtype=ttnn.float32))
def _dev_cu(self, cu: torch.Tensor):
ttnn = _ttnn()
return ttnn.to_device(ttnn.from_torch(cu, dtype=ttnn.int32, layout=ttnn.ROW_MAJOR_LAYOUT), self.device,
memory_config=ttnn.DRAM_MEMORY_CONFIG)
def set_valid_frames(self, n: int) -> None:
"""Host call before a run / trace replay: frames ``[0, n)`` of the T-frame input form the clip (see the module
doc, "Runtime valid-frame count"). Writes ``vf_cu`` / ``vf_w`` in place (no allocation, no compile)."""
ttnn = _ttnn()
T = self.T
if not 1 <= n <= T:
raise ValueError(f"valid frames {n} outside 1..{T}")
if not self.cross_compact:
return
ttnn.copy_host_to_device_tensor(ttnn.from_torch(valid_frame_cu(T, n, self.n), dtype=ttnn.int32,
layout=ttnn.ROW_MAJOR_LAYOUT), self.vf_cu, cq_id=0)
ttnn.copy_host_to_device_tensor(ttnn.from_torch(valid_frame_weights(T, n), dtype=ttnn.float32,
layout=ttnn.TILE_LAYOUT), self.vf_w, cq_id=0)
self.valid_frames = n
# -- pieces
def _ln(self, x, w, b):
ttnn = _ttnn()
if self.ln_exact:
return exact_layer_norm(x, w, b, ref.LN_EPS, self.mem, self.cfgs.ln)
return ttnn.layer_norm(x, epsilon=ref.LN_EPS, weight=w, bias=b, memory_config=self.mem,
compute_kernel_config=self.cfgs.ln)
def _lin(self, x, w, b=None, act=None, dtype=None):
ttnn = _ttnn()
if self.cfgs.minimal is not None and x.dtype == w.dtype:
fa = None
if act == "gelu":
fa = ttnn.UnaryWithParam(ttnn.UnaryOpType.GELU, 0.0)
elif act == "silu":
fa = ttnn.UnaryWithParam(ttnn.UnaryOpType.SILU)
return ttnn.experimental.minimal_matmul(x, w, bias_tensor=b, fused_activation=fa, config=self.cfgs.minimal,
memory_config=self.mem, dtype=dtype or self.act_dtype,
compute_kernel_config=self.cfgs.mm)
return ttnn.linear(x, w, bias=b, activation=act, memory_config=self.mem, dtype=dtype or self.act_dtype,
compute_kernel_config=self.cfgs.mm)
def _mlp(self, h, bw: BlockWeights):
ttnn = _ttnn()
bd = self.branch_dtype
if self.cfg.swiglu:
g = self._lin(h, bw.fcg_w, bw.fcg_b, act="silu", dtype=bd)
u = self._lin(h, bw.fcx_w, bw.fcx_b, dtype=bd)
m = ttnn.multiply(g, u, memory_config=self.mem)
ttnn.deallocate(g)
ttnn.deallocate(u)
else:
m = self._lin(h, bw.fc1_w, bw.fc1_b, act="gelu", dtype=bd)
f = self._lin(m, bw.fc2_w, bw.fc2_b, dtype=bd)
ttnn.deallocate(m)
return f
def _rope_eltwise(self, x, cos, sin_signed):
"""x * cos + [x2, x1] * [-sin, sin] in float32 (x bf16 [B, H, R, 64]) -> bf16 (one RNE rounding)."""
ttnn = _ttnn()
xf = full_view(x)
b, h, r = xf.padded_shape[0], xf.padded_shape[1], xf.padded_shape[2]
half = HEAD_DIM // 2
x1 = ttnn.slice(xf, [0, 0, 0, 0], [b, h, r, half], memory_config=self.mem)
x2 = ttnn.slice(xf, [0, 0, 0, half], [b, h, r, HEAD_DIM], memory_config=self.mem)
sw = ttnn.concat([x2, x1], dim=-1, memory_config=self.mem)
ttnn.deallocate(x1)
ttnn.deallocate(x2)
a = ttnn.multiply(xf, cos, dtype=ttnn.float32, memory_config=self.mem)
c = ttnn.multiply(sw, sin_signed, dtype=ttnn.float32, memory_config=self.mem)
ttnn.deallocate(sw)
s = ttnn.add(a, c, dtype=ttnn.float32, memory_config=self.mem)
ttnn.deallocate(a)
ttnn.deallocate(c)
out = ttnn.typecast(s, ttnn.bfloat16, memory_config=self.mem)
ttnn.deallocate(s)
return out
def _qkv(self, h, bw: BlockWeights):
return self._lin(h, bw.qkv_w, bw.qkv_b, dtype=_ttnn().float32 if self.rope32 else None)
def _heads(self, qkv, rows: int, rows_p: int, batch: int, table: Optional[str] = None):
"""[B, 1, rows_p, 3C] -> q, k, v [B, H, rows (logical), 64] bf16 (RoPE table ``frame`` / ``clip`` on q / k)."""
ttnn = _ttnn()
q, k, v = ttnn.experimental.nlp_create_qkv_heads(qkv, num_heads=self.heads, num_kv_heads=self.heads,
transpose_k_heads=False, memory_config=self.mem)
f32 = qkv.dtype == ttnn.float32
if table is not None and self.rope_mode == "eltwise":
cos, sin_s = self.tables32[table]
q2, k2 = self._rope_eltwise(q, cos, sin_s), self._rope_eltwise(k, cos, sin_s)
ttnn.deallocate(q)
ttnn.deallocate(k)
q, k = q2, k2
elif table is not None:
cos, sin = (self.tables32 if f32 else self.tables)[table]
q2 = ttnn.experimental.rotary_embedding(q, cos, sin, memory_config=self.mem, compute_kernel_config=self.cfgs.eltwise)
k2 = ttnn.experimental.rotary_embedding(k, cos, sin, memory_config=self.mem, compute_kernel_config=self.cfgs.eltwise)
ttnn.deallocate(q)
ttnn.deallocate(k)
q, k = q2, k2
if f32:
outs = []
for a in (q, k, v):
outs.append(ttnn.typecast(a, ttnn.bfloat16, memory_config=self.mem))
ttnn.deallocate(a)
q, k, v = outs
shp = [batch, self.heads, rows, HEAD_DIM]
pad = [batch, self.heads, rows_p, HEAD_DIM]
return view(q, shp, pad), view(k, shp, pad), view(v, shp, pad)
def _attn_fp32(self, q, k, v):
"""softmax(q k^T / 8) v with fp32 scores and softmax; q, k, v [T, H, L (logical), 64] -> [T, H, L, 64]."""
ttnn = _ttnn()
T, H, lp = self.T, self.heads, self.lp
kt = ttnn.transpose(k, -2, -1, memory_config=self.mem) # [T, H, 64, L]
outs = []
for r0 in range(0, lp, self.q_rows):
r1 = min(lp, r0 + self.q_rows)
qc = q if (r0, r1) == (0, lp) else ttnn.slice(full_view(q), [0, 0, r0, 0], [T, H, r1, HEAD_DIM], memory_config=self.mem)
qs = ttnn.multiply(qc, HEAD_DIM ** -0.5, memory_config=self.mem) # exact (power of 2)
if qc is not q:
ttnn.deallocate(qc)
s = ttnn.matmul(qs, kt, memory_config=self.mem, dtype=ttnn.float32, compute_kernel_config=self.cfgs.mm)
ttnn.deallocate(qs)
p = ttnn.softmax(s, dim=-1, numeric_stable=True, memory_config=self.mem, compute_kernel_config=self.cfgs.mm)
ttnn.deallocate(s)
p16 = ttnn.typecast(p, ttnn.bfloat16, memory_config=self.mem)
ttnn.deallocate(p)
outs.append(ttnn.matmul(p16, v, memory_config=self.mem, dtype=ttnn.bfloat16, compute_kernel_config=self.cfgs.mm))
ttnn.deallocate(p16)
ttnn.deallocate(kt)
if len(outs) == 1:
return outs[0]
o = ttnn.concat([full_view(t) for t in outs], dim=2, memory_config=self.mem)
for t in outs:
ttnn.deallocate(t)
return o
# -- blocks
def block_within(self, x, bw: BlockWeights, freeze_prefix: bool = False, fp32_attn: bool = False):
"""Within-frame block on ``x`` [T, 1, Lp, C]; ``freeze_prefix`` keeps rows >= N (prefix) unchanged."""
ttnn = _ttnn()
T, lp, n = self.T, self.lp, self.n
h = self._ln(x, bw.n1_w, bw.n1_b)
qkv = self._qkv(h, bw)
ttnn.deallocate(h)
q, k, v = self._heads(qkv, n + NUM_PREFIX, lp, T, "frame")
ttnn.deallocate(qkv)
if fp32_attn:
o = self._attn_fp32(q, k, v)
else:
o = ttnn.transformer.scaled_dot_product_attention(q, k, v, is_causal=False, scale=HEAD_DIM ** -0.5,
program_config=self.sdpa_pc, compute_kernel_config=self.cfgs.sdpa,
memory_config=self.mem, cu_window_seqlens=self.wf_cu)
ttnn.deallocate(q)
ttnn.deallocate(k)
ttnn.deallocate(v)
a = ttnn.experimental.nlp_concat_heads(full_view(o), memory_config=self.mem)
ttnn.deallocate(o)
p = self._lin(a, bw.proj_w, bw.proj_b, dtype=self.branch_dtype)
ttnn.deallocate(a)
if freeze_prefix:
p2 = ttnn.multiply(p, self.patch_mask, memory_config=self.mem)
ttnn.deallocate(p)
p = p2
x1 = ttnn.add(x, p, memory_config=self.mem, dtype=self.resid_dtype)
ttnn.deallocate(p)
h = self._ln(x1, bw.n2_w, bw.n2_b)
f = self._mlp(h, bw)
ttnn.deallocate(h)
if freeze_prefix:
f2 = ttnn.multiply(f, self.patch_mask, memory_config=self.mem)
ttnn.deallocate(f)
f = f2
x2 = ttnn.add(x1, f, memory_config=self.mem, dtype=self.resid_dtype)
ttnn.deallocate(f)
ttnn.deallocate(x1)
return x2
def block_cross(self, x, bw: BlockWeights):
"""Cross-frame block, T > 1 (see module doc): ONE windowed SDPA over the joint sequence
``[pooled prefix (5) ; patches of frames 0..T-1]``; ``vf_cu`` puts the pooled prefix and frames ``< n`` in
window 0 and frames ``>= n`` in window 1, ``vf_w`` averages the prefix of frames ``< n``."""
ttnn = _ttnn()
T, n, c, lp = self.T, self.n, self.c, self.lp
tn, sj = T * n, self.s_joint
sjp = ceil32(sj)
prefix_in = ttnn.slice(x, [0, 0, n, 0], [T, 1, n + NUM_PREFIX, c], memory_config=self.mem) # [T, 1, 5, C]
if n % 32 == 0:
xc = view(ttnn.slice(x, [0, 0, 0, 0], [T, 1, n, c], memory_config=self.mem), [1, 1, tn, c], [1, 1, tn, c])
else:
xs = view(x, [T, 1, n, c], [T, 1, lp, c]) if lp == ceil32(n) else ttnn.slice(x, [0, 0, 0, 0], [T, 1, n, c], memory_config=self.mem)
xc = ttnn.reshape(xs, [1, 1, tn, c], memory_config=self.mem)
if lp != ceil32(n): # xs is a slice copy (else a view of x, which the caller owns)
free_unless_shared(xs, xc)
wp = ttnn.multiply(prefix_in, self.vf_w, memory_config=self.mem, dtype=self.resid_dtype)
pooled = ttnn.sum(wp, dim=0, keepdim=True, memory_config=self.mem) # [1, 1, 5, C]: mean over frames < n
ttnn.deallocate(wp)
xj = ttnn.concat([pooled, xc], dim=2, memory_config=self.mem) # [1, 1, 5 + T * N, C]
ttnn.deallocate(pooled)
ttnn.deallocate(xc)
h = self._ln(xj, bw.n1_w, bw.n1_b)
qkv = self._qkv(h, bw)
ttnn.deallocate(h)
q, k, v = self._heads(qkv, sj, sjp, 1, "clip")
ttnn.deallocate(qkv)
o = ttnn.transformer.scaled_dot_product_attention(
q, k, v, is_causal=False, scale=HEAD_DIM ** -0.5, program_config=self.win_pc,
compute_kernel_config=self.cfgs.sdpa, memory_config=self.mem, cu_window_seqlens=self.vf_cu)
for t in (q, k, v):
ttnn.deallocate(t)
a = ttnn.experimental.nlp_concat_heads(full_view(o), memory_config=self.mem) # [1, 1, sjp, C]
ttnn.deallocate(o)
p = self._lin(a, bw.proj_w, bw.proj_b, dtype=self.branch_dtype)
ttnn.deallocate(a)
x1 = ttnn.add(full_view(xj), p, memory_config=self.mem, dtype=self.resid_dtype)
ttnn.deallocate(p)
ttnn.deallocate(xj)
h = self._ln(x1, bw.n2_w, bw.n2_b)
f = self._mlp(h, bw)
ttnn.deallocate(h)
x2 = ttnn.add(x1, f, memory_config=self.mem, dtype=self.resid_dtype)
ttnn.deallocate(f)
ttnn.deallocate(x1)
# back to frames: [T, 1, N, C] ++ the unchanged block-input prefix rows
xpat = ttnn.slice(x2, [0, 0, NUM_PREFIX, 0], [1, 1, sj, c], memory_config=self.mem) # [1, 1, T * N, C]
ttnn.deallocate(x2)
xf = ttnn.reshape(xpat, [T, 1, n, c], memory_config=self.mem)
free_unless_shared(xpat, xf) # N % 32 == 0: xf is a view of xpat
out = ttnn.concat([xf, prefix_in], dim=2, memory_config=self.mem) # [T, 1, N + 5, C]
ttnn.deallocate(xf)
ttnn.deallocate(prefix_in)
return full_view(out)
def embed(self, patches):
"""``patches`` [1, 1, T * Np, 768] -> X [T, 1, Lp, C]."""
ttnn = _ttnn()
T, np_, lp, c = self.T, self.np_, self.lp, self.c
p = view(patches, [T, 1, np_, 768], [T, 1, np_, 768])
if self.pad_rows is not None:
p = ttnn.concat([p, self.pad_rows], dim=2, memory_config=self.mem)
e = ttnn.linear(p, self.tw.pe_w, memory_config=self.mem, dtype=self.act_dtype, compute_kernel_config=self.cfgs.mm)
if self.pad_rows is not None:
ttnn.deallocate(p)
x = ttnn.add(e, self.embed_rows, memory_config=self.mem, dtype=self.resid_dtype)
ttnn.deallocate(e)
return x
def run(self, patches) -> List[object]:
ttnn = _ttnn()
x = self.embed(patches)
taps = []
for i in range(self.cfg.depth):
bw = self.tw.blocks[i]
if i in self.cross_blocks:
if self.cross_compact:
y = self.block_cross(x, bw)
else:
y = self.block_within(x, bw, freeze_prefix=True, fp32_attn=i in self.fp32_blocks)
else:
y = self.block_within(x, bw, fp32_attn=i in self.fp32_blocks)
if not any(x is t for t in taps):
ttnn.deallocate(x)
x = y
if self.hook is not None:
self.hook(i, x)
if i in self.tap_blocks:
taps.append(x)
if not any(x is t for t in taps):
ttnn.deallocate(x)
return taps
# ----------------------------------------------------------------------------------------------- ENC engine
class Engine:
"""ttnn ENC engine for one :class:`StageShape`: ``run(patches) -> [tap0, tap1, tap2, tap3]`` (module doc).
Runtime valid-frame count: ``supports_valid_frames = True``; ``set_valid_frames(n)`` (host, before ``run`` / a
trace replay) makes the T-frame program process frames ``[0, n)`` as an n-frame clip (module doc)."""
supports_valid_frames = True
def __init__(self, device, weights, shape: StageShape, size: Optional[str] = None):
if isinstance(weights, dict):
if size is None:
raise ValueError("size is required with host weights")
weights = Engine.prepare_weights(device, weights, size)
self.device = device
self.shape = shape
self.weights = weights
cfg = weights.cfg
self.trunk = Trunk(device, weights, shape, joint_cross=True, tap_blocks=cfg.reassembled_blocks,
cross_blocks=cfg.cross_frame_blocks, fp32_blocks=fp32_attn_blocks(cfg.name))
@staticmethod
def prepare_weights(device, host_weights, size: str) -> TrunkWeights:
return upload_trunk(device, host_weights, ref.SIZES[size], "encoder.")
def set_valid_frames(self, n: int) -> None:
self.trunk.set_valid_frames(n)
def input_spec(self) -> Tuple[Tuple[int, ...], str]:
return (1, 1, self.shape.frames * self.shape.np_, 768), "bf16 TILE DRAM"
def run(self, patches) -> List[object]:
ttnn = _ttnn()
s = self.shape
T, np_, lp, c = s.frames, s.np_, s.lp, self.weights.cfg.dim
out = []
for x in self.trunk.run(patches):
if lp != np_:
y = ttnn.slice(x, [0, 0, 0, 0], [T, 1, np_, c], memory_config=ttnn.DRAM_MEMORY_CONFIG)
ttnn.deallocate(x)
else:
y = x
if y.dtype != ttnn.bfloat16: # fp32 residual stream -> bf16 taps (stage contract)
y2 = ttnn.typecast(y, ttnn.bfloat16, memory_config=ttnn.DRAM_MEMORY_CONFIG)
ttnn.deallocate(y)
y = y2
out.append(view(y, [1, 1, T * np_, c], [1, 1, T * np_, c]))
return out