DepthPro2 / code /tt_depthpro2 /tt /mk_enc /geometry.py
changh95's picture
tt-model push depthpro2 (container)
d5afa0d verified
Raw History Blame Contribute Delete
20.4 kB
# SPDX-License-Identifier: Apache-2.0
"""ENC megakernel geometry (host mirror of ``kernels/me_defs.hpp`` + the ``ME_*`` kernel defines): row tiles, waves,
per-column N splits, attention items, the CB table (L1 budget) and the runtime args, for one program
(size, T, gh, gw, mode) on a ``gx x gy`` grid (``device.compute_with_storage_grid_size()``, never hard-coded).
Row tiles (``ri``, 32 tokens each): ``ri < T`` prefix tile of frame ``ri``; ``T <= ri < T + T*Pt`` patch tile
``(t, p)`` (``ri = T + t*Pt + p``); ``ri = Mt - 1`` the pool tile (T > 1 with joint blocks). Wave ``w``, grid row
``y``, slot ``s`` -> ``ri = (w*RB + s)*R + y``.
"""
from __future__ import annotations
import math
import os
import re
from dataclasses import dataclass, field
from typing import Callable, Dict, List, Optional, Tuple
KDIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "kernels")
DEFS_PATH = os.path.join(KDIR, "me_defs.hpp")
def _parse_defs(path: str = DEFS_PATH) -> Dict[str, int]:
out = {}
pat = re.compile(r"^\s*constexpr\s+uint32_t\s+([A-Z0-9_]+)\s*=\s*([0-9]+)\s*;")
with open(path) as f:
for line in f:
m = pat.match(line)
if m:
out[m.group(1)] = int(m.group(2))
return out
D = _parse_defs()
globals().update(D)
Core = Tuple[int, int]
T16, T32 = 2048, 4096
PAGE_TILES = 8
PE_T = 24 # patch K tiles (768 = 3 * 16 * 16)
NUM_PREFIX = 5
L1_BUDGET = 1400 * 1024 # allocatable CB bytes we allow ourselves (default worker_l1_size ~1427 KB)
#: model sizes (reference/model.py SIZES; FOV trunk = ViT-S)
SIZE_CFG = {
"S": dict(dim=384, depth=12, heads=6, hidden=1536, swiglu=False, taps=(2, 5, 8, 11), cross=(5, 7, 9, 11)),
"B": dict(dim=768, depth=12, heads=12, hidden=3072, swiglu=False, taps=(2, 5, 8, 11), cross=(5, 7, 9, 11)),
"L": dict(dim=1024, depth=24, heads=16, hidden=4096, swiglu=False, taps=(5, 11, 17, 23),
cross=(9, 11, 13, 15, 17, 19, 21, 23)),
"H": dict(dim=1280, depth=32, heads=20, hidden=5120, swiglu=True, taps=(7, 15, 23, 31),
cross=(11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31)),
}
#: default slots per row and wave (L1 budget, MK_LOG 1.3)
RB_DEFAULT = {"S": 4, "B": 2, "L": 2, "H": 2}
#: LN-gather precision (round 10): fp32 x tiles (tf32 operand of QKV / FC1) instead of bf16(x). v1.1: L only (the
#: fresh held-out set: S and the FOV trunk regressed on multi-frame clips with it, MK_LOG round 11); every other size
#: and the FOV trunk keep v1 numerics. DEPTHPRO2_MK_ENC_OPTS inx32= / klo= override.
INX32_DEFAULT = {"S": False, "B": False, "L": True, "H": False}
#: keys in hi / lo (round 10): 0 off, 1 the special (prefix / pool) key tile of each segment, 2 every key
KLO_DEFAULT = {"S": 0, "B": 0, "L": 1, "H": 0}
#: blocks whose attention logits reach |s| > 1e3 on the goldens (S blk 0: 2.2e6, B 0: 2.1e5, L 1: 1.2e4, H 0 / 1:
#: 1.9e4 / 1.1e4, FOV trunk 0: 2.6e6; every other block < 700): they use the two-step (fp32-accurate) row max
GIANT = {"S": (0,), "B": (0,), "L": (1,), "H": (0, 1), "fov": (0,)}
def pow2_groups(n: int, gmax: int) -> List[int]:
"""n split into power-of-two groups <= gmax, largest first (keeps every group's per-k tiles inside one 8-tile
weight page when each op segment starts page-aligned; mirrored in me_trisc.cpp pow2_floor)"""
out = []
while n > 0:
g = 1
while g * 2 <= min(gmax, n):
g *= 2
out.append(g)
n -= g
return out
def pad8(t: int) -> int:
return -(-t // PAGE_TILES) * PAGE_TILES
def split(total: int, parts: int) -> List[int]:
return [total // parts + (1 if i < total % parts else 0) for i in range(parts)]
def starts(sizes: List[int]) -> List[int]:
out, a = [], 0
for s in sizes:
out.append(a)
a += s
return out
@dataclass
class Geometry:
size: str
T: int
gh: int
gw: int
mode: str # "depth" | "fov"
gx: int
gy: int
rb: int = 0
qb: int = 0
kc: int = 32
ring: int = 10
probe: bool = False
prof: bool = False
exp_mode: int = 1 # P = exp(S - m): 0 fp32-accurate exp, 1 exp_21f (bf16-accurate, max rel err 1.7e-3)
gelu_mode: int = 1 # 0 exact erf GELU (SFPU), 1 polynomial (max |err| 2.1e-4, MoGe-2 v5)
giant_all: bool = False # two-step row max in every block
alias_st: bool = True # the attention state FIFO (fp32) is a view of CB_INX's memory (bf16 LN gather)
fc1p_ok: bool = True # allow the pipelined FC1 epilogue (rb == 2, GELU)
inx32: Optional[bool] = None # LN-gather x tiles in fp32 (tf32 operand of QKV / FC1); None: per size (round 10)
klo: Optional[int] = None # keys in hi / lo: 0 off, 1 special key tiles, 2 every key; None: per size (round 10)
ring_first: bool = False # L1 budget: shrink the weight ring before the K / V chunk
derived: Dict = field(default_factory=dict)
def __post_init__(self):
if self.size not in SIZE_CFG:
raise ValueError(f"size {self.size!r}")
if self.mode not in ("depth", "fov"):
raise ValueError(f"mode {self.mode!r}")
if self.mode == "fov" and self.size != "S":
raise ValueError("the FOV trunk is ViT-S")
c = SIZE_CFG[self.size]
self.dim, self.L, self.H = c["dim"], c["depth"], c["heads"]
self.DT, self.FT = self.dim // 32, c["hidden"] // 32
self.swiglu = bool(c["swiglu"])
self.taps = tuple(c["taps"])
self.freeze = tuple(c["cross"])
self.joint = tuple(c["cross"]) if self.mode == "depth" else ()
if not 1 <= self.T <= 32:
raise ValueError(f"T={self.T}")
self.N = self.gh * self.gw
self.Np = -(-self.N // 32) * 32
self.Pt = self.Np // 32
self.nlast = self.N - (self.Pt - 1) * 32
self.pool = 1 if (self.T > 1 and self.joint) else 0
self.Mt = self.T + self.T * self.Pt + self.pool
self.C, self.R = self.gx, self.gy
self.NC = self.gx * self.gy
if self.rb == 0:
self.rb = RB_DEFAULT[self.size]
if self.inx32 is None: # the FOV trunk keeps v1 numerics whatever its size key
self.inx32 = False if self.mode == "fov" else INX32_DEFAULT[self.size]
if self.klo is None:
self.klo = 0 if self.mode == "fov" else KLO_DEFAULT[self.size]
if self.rb not in (1, 2, 4):
raise ValueError(f"rb={self.rb}")
self.W = -(-self.Mt // (self.R * self.rb))
# column splits (each op on its own, contiguous)
nh = split(3 * self.H, self.C)
nx = split(self.DT, self.C)
nf = split(self.FT, self.C)
if min(nh) < 1 or min(nx) < 1 or min(nf) < 1:
raise ValueError("more grid columns than op tiles")
self.nh, self.h0 = nh, starts(nh)
self.nx, self.n0 = nx, starts(nx)
self.nf, self.f0 = nf, starts(nf)
self.NXM, self.NHM, self.NFM = max(nx), max(nh), max(nf)
# DST groups
self.G = 8 // self.rb # proj / fc2 / embed n-group width (accumulators rb * G <= 8)
# FC1 f-block width: accumulators rb * FB (SwiGLU: 2 rb * FB) <= 4, rstd of the slots at DST 4 + s
self.FB = (2 // self.rb) if self.swiglu else (4 // self.rb)
# pipelined FC1 (GELU on the pack thread, half-sync DST): rb == 2 GELU sizes (B, L); weights per f tile
self.fc1p = (not self.swiglu) and self.rb == 2 and self.fc1p_ok
self.FBW = 1 if self.fc1p else self.FB
if self.FB < 1:
raise ValueError("SwiGLU needs rb <= 4")
# attention
self.q_per_head = self._q_tiles_per_head()
if self.qb == 0:
self.qb = self._best_qb()
if self.kc not in (8, 16, 32):
raise ValueError(f"kc={self.kc}: 8, 16 or 32 (the score region = kc tiles = also the 8-tile RAW CB)")
# no longer chunks than a within-frame segment needs (1 + Pt key tiles)
while self.kc > 8 and self.kc // 2 >= self.Pt + 1:
self.kc //= 2
self._check_budget()
# -------------------------------------------------------------- rows
def ri_of(self, w: int, y: int, s: int) -> int:
return (w * self.rb + s) * self.R + y
def slot_of(self, ri: int) -> Tuple[int, int, int]:
q, y = divmod(ri, self.R)
w, s = divmod(q, self.rb)
return w, y, s
def kind(self, ri: int) -> str:
if ri < self.T:
return "prefix"
if ri < self.T + self.T * self.Pt:
return "patch"
if self.pool and ri == self.Mt - 1:
return "pool"
return "empty"
@property
def pool_slot(self) -> Optional[Tuple[int, int, int]]:
return self.slot_of(self.Mt - 1) if self.pool else None
def _best_qb(self) -> int:
"""q tiles per core and attention job: minimizes rounds x qb (the per-core critical path) over the blocks,
preferring larger qb (fewer K / V reads) on ties"""
best, cost = 1, None
for qb in range(1, 9):
c = 0
for joint, nq in ((False, self.Pt + 1), (True, self.T * self.Pt)):
if joint and not self.joint:
continue
pairs = self.H if joint else self.H * self.T
jobs = pairs * -(-nq // (self.R * qb))
c += -(-jobs // self.C) * qb * ((self.T * self.Pt + 1) if joint else (self.Pt + 1))
if cost is None or c <= cost:
best, cost = qb, c
return best
def _q_tiles_per_head(self) -> int:
"""query tiles per head in a within-frame block (the larger case)"""
return self.T * (self.Pt + 1)
# -------------------------------------------------------------- weights per column (tiles, consumption order)
# every op segment is padded to whole pages (8 tiles): the block matmuls need each k row of a group in one page
def tiles_embed(self, x: int) -> int:
return pad8(self.nx[x] * (PE_T + 1))
def tiles_qkv(self, x: int) -> int:
return pad8(self.nh[x] * 2 * (self.DT + 1))
def tiles_proj(self, x: int) -> int:
return pad8(self.nx[x] * (self.DT + 1))
def tiles_fc1(self, x: int) -> int:
return pad8(self.nf[x] * (2 if self.swiglu else 1) * (self.DT + 1))
def tiles_fc2(self, x: int) -> int:
return pad8(self.nx[x] * (self.FT + 1))
def pages(self, tiles: int) -> int:
return -(-tiles // PAGE_TILES)
def arena_tiles(self, kind: str, x: int) -> int:
if kind == "E":
return self.tiles_embed(x) + self.tiles_qkv(x)
t = self.tiles_proj(x) + self.tiles_fc1(x) + self.tiles_fc2(x)
return t + (self.tiles_qkv(x) if kind == "B" else 0)
def arena_pages(self, kind: str, x: int) -> int:
return self.pages(self.arena_tiles(kind, x))
def page0(self, kind: str, x: int) -> int:
return sum(self.arena_pages(kind, i) for i in range(x))
def pages_total(self, kind: str) -> int:
return sum(self.arena_pages(kind, i) for i in range(self.C))
# -------------------------------------------------------------- CB table (bytes per core)
def cb_table(self) -> List[Tuple[Tuple[Tuple[int, str, bool], ...], int]]:
"""[(((cb id, fmt, unpack-to-dest fp32), ...), total bytes)]; ids in one entry share the allocation (the
attention-phase CBs KV / ST / AP are views of the wave-phase INF / INX / RAW memory; MK_LOG 1.7)."""
rb, nxm = self.rb, self.NXM
b = lambda i, n: (((i, "bf16", False),), n * T16) # noqa: E731
f = lambda i, n, u: (((i, "fp32", u),), n * T32) # noqa: E731
return [
b(CB_W, self.ring * PAGE_TILES),
] + ([(((CB_INX, self.fix, False), (CB_ST, "fp32", True)), self.inx_bytes)] if self.alias_st else [
(((CB_INX, self.fix, False),), self.rb * self.DT * self.tix),
f(CB_ST, (self.qb + 1) * 4, True),
]) + [
(((CB_INF, "bf16", False), (CB_KV, "bf16", False)), self.inf_tiles * T16),
f(CB_STAT, self.C, False),
f(CB_X, 2 * rb * nxm, True),
f(CB_SUMS, 4 * rb, False),
f(CB_STO, 1, False),
(((CB_OUTX, self.fix, False),), nxm * rb * self.tix),
(((CB_EXT, self.fix, False),), rb * self.tix),
f(CB_RSTD, rb, True),
(((CB_RAW, "fp32", True), (CB_S32, "fp32", True), (CB_S32F, "fp32", False), (CB_AP, "fp32", False)),
max(8, self.kc) * T32),
b(CB_OUT, 2 * 2 * rb), # double-buffered: the TRISC packs unit u + 1 while the BRISC writes unit u
b(CB_FO, 2 * self.FB * rb), # double-buffered
b(CB_CONST, N_CONST),
f(CB_CF32, N_CF32, True),
f(CB_TAB, 2 * rb, True),
f(CB_XO, nxm, True),
b(CB_TAP, nxm),
] + ([f(CB_PL, nxm, True)] if self.pool else []) + [
f(CB_PFX, nxm, True),
f(CB_XL, rb * nxm, True),
b(CB_AQ, 2 * self.qb * 2),
f(CB_MX, 1, False),
f(CB_MFN, 3, True),
f(CB_MF1, 1, True),
b(CB_SC, 6), # mu / rstd / std hi + lo: every value is a bf16 (hi = bf16(v), lo = bf16(v - hi))
] + ([b(CB_OUTLO, 2 * rb)] if self.klo else []) + [
b(CB_AO, self.qb * 2),
(((CB_SYNC, "raw", False),), SYNC_BYTES),
b(CB_TOK, 1),
] + ([f(CB_PRB, N_PROBE, False)] if self.probe else [])
@property
def inf_tiles(self) -> int:
"""CB_INF tiles (the wave gathers' capacity), rounded up to whole K / V chunks (4 KC tiles)"""
return -(-self.inf_cap // self.cht) * self.cht
@property
def cht(self) -> int:
"""tiles of one K / V chunk: [K 2 kc | V 2 kc | K lo]"""
return 4 * self.kc + (2 * self.kc if self.klo == 2 else 2 if self.klo == 1 else 0)
@property
def klo_rows(self) -> int:
"""row tiles of the k-lo staging"""
return self.Mt if self.klo == 2 else self.T + 1
@property
def inf_cap(self) -> int:
return self.rb * max(self.FT, self.DT, PE_T)
@property
def inx_bytes(self) -> int:
"""CB_INX bytes: the LN gather (rb * DT tiles, fp32 with inx32 else bf16) or the attention state FIFO
((qb + 1) * 4 fp32 tiles), whole 16 KB states"""
need = max(self.rb * self.DT * self.tix, (self.qb + 1) * 4 * T32)
return -(-need // (4 * T32)) * (4 * T32)
@property
def fix(self) -> str:
return "fp32" if self.inx32 else "bf16"
@property
def tix(self) -> int:
"""bytes of one LN-gather tile (CB_INX / CB_OUTX / CB_EXT)"""
return T32 if self.inx32 else T16
def cb_bytes(self) -> int:
return sum(n for _, n in self.cb_table())
def _check_budget(self):
"""shrink, in order: the K / V chunk (32 -> 16 key tiles), the weight ring (10 -> 6 pages), the chunk again
(16 -> 8), then the q tiles per attention job"""
steps = 0
if self.ring_first and self.cb_bytes() > L1_BUDGET: # keep the largest K / V chunk, the ring as large as fits
kc0, ring0 = self.kc, self.ring
for kc in (kc0, kc0 // 2, kc0 // 4):
for ring in range(ring0, 5, -2):
self.kc, self.ring = kc, ring
if self.cb_bytes() <= L1_BUDGET:
return
self.kc, self.ring = kc0, ring0
while self.cb_bytes() > L1_BUDGET:
if self.kc > 16:
self.kc //= 2
elif self.ring > 6:
self.ring -= 2
elif self.kc > 8 and self.qb <= 2:
self.kc //= 2
elif self.qb > 1:
self.qb -= 1
else:
raise ValueError(f"CBs need {self.cb_bytes() // 1024} KB > {L1_BUDGET // 1024} KB (size {self.size}, "
f"rb {self.rb})")
steps += 1
# -------------------------------------------------------------- attention items
def n_items(self, l: int) -> int:
"""attention jobs of block l"""
nq = self.T * self.Pt if l in self.joint else self.Pt + (0 if l in self.freeze else 1)
pairs = self.H if l in self.joint else self.H * self.T
return pairs * -(-nq // (self.R * self.qb))
# -------------------------------------------------------------- defines
def defines(self) -> List[Tuple[str, str]]:
jm = sum(1 << l for l in self.joint)
gm = sum(1 << l for l in range(self.L)) if self.giant_all else sum(
1 << l for l in GIANT["fov" if self.mode == "fov" else self.size])
fm = sum(1 << l for l in self.freeze)
d = {
"ME_DT": self.DT, "ME_FT": self.FT, "ME_H": self.H, "ME_L": self.L, "ME_SWIGLU": int(self.swiglu),
"ME_C": self.C, "ME_R": self.R, "ME_RB": self.rb, "ME_T": self.T, "ME_PT": self.Pt,
"ME_NLAST": self.nlast, "ME_W": self.W, "ME_POOL": self.pool, "ME_MT": self.Mt, "ME_QB": self.qb,
"ME_KC": self.kc, "ME_JOINT": f"{jm}u", "ME_GIANT": f"{gm}u", "ME_EXP": self.exp_mode, "ME_GELU": self.gelu_mode, "ME_FREEZE": f"{fm}u", "ME_FOV": int(self.mode == "fov"),
"ME_TAP0": self.taps[0], "ME_TAP1": self.taps[1], "ME_TAP2": self.taps[2], "ME_TAP3": self.taps[3],
"ME_NXM": self.NXM, "ME_NHM": self.NHM, "ME_NFM": self.NFM, "ME_G": self.G, "ME_FB": self.FB, "ME_FC1P": int(self.fc1p),
"ME_PROBE": int(self.probe), "ME_PROF": int(self.prof), "ME_RING": self.ring, "ME_NC": self.NC, "ME_INF": self.inf_cap, "ME_INFT": self.inf_tiles,
"ME_INXT": (self.inx_bytes if self.alias_st else self.rb * self.DT * self.tix) // self.tix,
"ME_INX32": int(bool(self.inx32)),
"ME_KLO": int(self.klo),
"ME_ABI_HOST": ME_ABI, # noqa: F821 (parsed from me_defs.hpp)
}
return [(k, str(v)) for k, v in d.items()]
# -------------------------------------------------------------- runtime args
def core_args(self, noc: Callable[[Core], Core]) -> Dict[Core, List[int]]:
out = {}
ks = split(self.DT, self.C)
ks0 = starts(ks)
pk = split(PE_T, self.C)
pk0 = starts(pk)
hub = (self.gx - 1, self.gy - 1)
for y in range(self.gy):
for x in range(self.gx):
a = [0] * N_RT_ARGS
role = 0
if y == 0:
role |= R_FEED
if y == self.gy - 1:
role |= R_KVR
if (x, y) == hub:
role |= R_HUB
a[A_IDX], a[A_ROLE], a[A_X], a[A_Y] = y * self.gx + x, role, x, y
a[A_H0], a[A_NH] = self.h0[x], self.nh[x]
a[A_N0], a[A_NX] = self.n0[x], self.nx[x]
a[A_F0], a[A_NF] = self.f0[x], self.nf[x]
a[A_KS0], a[A_KS1] = ks0[x], ks0[x] + ks[x]
a[A_PK0], a[A_PK1] = pk0[x], pk0[x] + pk[x]
a[A_ROWX0] = noc((0, y))[0]
a[A_ROWX1] = noc((self.gx - 1, y))[0]
a[A_ROWY] = noc((x, y))[1]
a[A_FX], a[A_FY] = noc((x, 0))
a[A_COLY0] = noc((x, 1))[1]
a[A_COLY1] = noc((x, self.gy - 1))[1]
py = self.pool_slot[1] if self.pool else 0
a[A_POOLX], a[A_POOLY] = noc((x, py))
a[A_P0E], a[A_NPE] = self.page0("E", x), self.arena_pages("E", x)
a[A_P0B], a[A_NPB] = self.page0("B", x), self.arena_pages("B", x)
a[A_P0BL], a[A_NPBL] = self.page0("BL", x), self.arena_pages("BL", x)
a[A_KRX], a[A_KRY] = noc((x, self.gy - 1))
a[A_KY0] = noc((x, 0))[1]
a[A_KY1] = noc((x, self.gy - 2))[1]
out[(x, y)] = a
return out
def hub(self) -> Core:
return (self.gx - 1, self.gy - 1)
def rect(self, noc: Callable[[Core], Core]) -> List[int]:
x0, y0 = noc((0, 0))
x1, y1 = noc((self.gx - 1, self.gy - 1))
return [min(x0, x1), min(y0, y1), max(x0, x1), max(y0, y1)]
def summary(self) -> str:
return (f"{self.size} {self.mode} T={self.T} grid {self.gh}x{self.gw} (N={self.N}, Pt={self.Pt}, "
f"nlast={self.nlast}) Mt={self.Mt} W={self.W} rb={self.rb} qb={self.qb} kc={self.kc} "
f"ring={self.ring} CB={self.cb_bytes() // 1024} KB")