# SPDX-License-Identifier: Apache-2.0 """The DEC megakernel: ONE persistent ``ttnn.generic_op`` program per (size, T, Hp, Wp) that runs DepthPro2's whole decoder stage (reassemble + DPT fusion decoder + head) for all T frames and writes the float32 inverse depth. ``MkDecWeights(device, host_weights, size)`` builds the weight arena (every layer's tile stream, plan.static_cfg) and the constants once per size; ``MkDec(device, weights, shape)`` plans the shape (plan.Plan), allocates the persistent DRAM maps (zero-initialized: their pads / guard rows are never written), the HC selector tiles and the plan table; ``run(taps)`` only enqueues the program (no host sync, trace-capturable) and returns ``inv`` ``[T, Hp, Wp]`` float32 TILE DRAM (a new tensor per call: ``tt/model.py`` deallocates the warm-up output). Contract (SPEC section 3): taps ``[1, 1, T * Np, C]`` bf16 TILE DRAM (frame t's patch rows t * Np .. t * Np + N - 1 in raster order, rows >= N ignored). """ from __future__ import annotations import os import time from typing import Dict, List, Optional, Sequence, Tuple import torch from . import plan as P from . import wprep as WP # DEPTHPRO2_MK_DEC_KDIR: development copy of the kernel directory (same md_defs.hpp layout); default kernels/ _KDIR = os.environ.get("DEPTHPRO2_MK_DEC_KDIR", P.KDIR) KERNELS = {r: os.path.join(_KDIR, f"md_{r}.cpp") for r in ("ncrisc", "brisc", "trisc")} def _opt_level(name: str): from ttnn._ttnn.operations.experimental.fabric_mux import KernelBuildOptLevel return getattr(KernelBuildOptLevel, name) def env_options() -> Dict: """``DEPTHPRO2_MK_DEC_OPTS`` (comma-separated ``key=value``): ``fid`` (HiFi4 / HiFi3 / HiFi2).""" out: Dict = {} for kv in os.environ.get("DEPTHPRO2_MK_DEC_OPTS", "").split(","): if "=" not in kv: continue k, v = (t.strip() for t in kv.split("=", 1)) if k == "fid": out["fidelity"] = v else: raise ValueError(f"DEPTHPRO2_MK_DEC_OPTS: unknown key {k!r}") return out def _ref_layers(size: str, gx: int, gy: int) -> List[P.Layer]: """the layer list of a size (shape-independent stream parameters; any bucket gives the same list)""" return P.Plan(size, 1, 64, 64, gx, gy).layers class MkDecWeights: """The weight arena (bf16 ROW_MAJOR pages of 8 tiles) and constants of one size, shared by every shape.""" def __init__(self, device, host_weights: Dict[str, torch.Tensor], size: str, timings: Optional[Dict] = None): import ttnn t0 = time.perf_counter() g = device.compute_with_storage_grid_size() self.size, self.grid = size, (int(g.x), int(g.y)) layers = _ref_layers(size, *self.grid) arena = WP.build_arena(layers, host_weights) consts = WP.const_tiles(host_weights) t1 = time.perf_counter() dram = ttnn.DRAM_MEMORY_CONFIG self.arena = ttnn.from_torch(arena.reshape(1, 1, *arena.shape).contiguous(), dtype=ttnn.bfloat16, layout=ttnn.ROW_MAJOR_LAYOUT, device=device, memory_config=dram) self.consts = ttnn.from_torch(consts.reshape(-1, 32).contiguous(), dtype=ttnn.bfloat16, layout=ttnn.TILE_LAYOUT, device=device, memory_config=dram) self.pages = arena.shape[0] self.dram_bytes = arena.numel() * 2 self.layer_sig = [(L.name, L.kc, L.nbw, L.wpg) for L in layers] if timings is not None: timings["mk_dec_fold_s"] = t1 - t0 timings["mk_dec_upload_s"] = time.perf_counter() - t1 class MkDec: def __init__(self, device, weights: MkDecWeights, size: str, T: int, hp: int, wp: int, fidelity: str = "HiFi4", opt: str = "O2", dm_opt: str = "Os", group: Optional[int] = None, defines: Sequence[Tuple[str, str]] = ()): import ttnn self.device = device g = device.compute_with_storage_grid_size() self.grid = (int(g.x), int(g.y)) env = env_options() fidelity = env.pop("fidelity", fidelity) if (weights.size, weights.grid) != (size, self.grid): raise ValueError(f"prepared weights {weights.size}/{weights.grid} do not match {size}/{self.grid}") self.weights = weights self.plan = pl = P.Plan(size, T, hp, wp, *self.grid, group=group) if [(L.name, L.kc, L.nbw, L.wpg) for L in pl.layers] != weights.layer_sig: raise RuntimeError("weight-arena layout differs from the shape's plan (static_cfg must not depend on shape)") self.T, self.hp, self.wp = T, hp, wp self.fidelity, self.opt, self.dm_opt = fidelity, opt, dm_opt self.extra_defines = list(defines) self._noc: Dict[Tuple[int, int], Tuple[int, int]] = {} for x in range(self.grid[0]): for y in range(self.grid[1]): c = device.worker_core_from_logical_core(ttnn.CoreCoord(x, y)) self._noc[(x, y)] = (int(c.x), int(c.y)) for x in range(self.grid[0] - 1): # logical order must be NoC order (rectangles map corner to corner) if self._noc[(x, 0)][0] >= self._noc[(x + 1, 0)][0]: raise RuntimeError("logical x order differs from NoC x order") for y in range(self.grid[1] - 1): if self._noc[(0, y)][1] >= self._noc[(0, y + 1)][1]: raise RuntimeError("logical y order differs from NoC y order") dram = ttnn.DRAM_MEMORY_CONFIG self.maps = [] for m in pl.maps: self.maps.append(ttnn.zeros([1, 1, m.pages, 32 * m.C], dtype=ttnn.bfloat16, layout=ttnn.ROW_MAJOR_LAYOUT, device=device, memory_config=dram)) sel = WP.sel_tiles(hp, wp) self.sel = ttnn.from_torch(sel.reshape(-1, 32).contiguous(), dtype=ttnn.bfloat16, layout=ttnn.TILE_LAYOUT, device=device, memory_config=dram) table = pl.table() self.plan_words = len(table) pad = max(-len(table) % 8, P.MIN_REQ // 4 - len(table)) # one >= 2 KB DRAM read tw = torch.tensor(table + [0] * pad, dtype=torch.int64).to(torch.int32).reshape(1, -1) self.plan_t = ttnn.from_torch(tw, dtype=ttnn.uint32, layout=ttnn.ROW_MAJOR_LAYOUT, device=device, memory_config=dram) self.plan_bytes = tw.shape[1] * 4 nc = self.grid[0] * self.grid[1] # one 2 KB page per core (every DRAM write of the program is >= 2 KB); the first DBG_WORDS words are used self.dbg = ttnn.from_torch(torch.zeros(1, 1, nc, P.DBG_PAGE, dtype=torch.int32), dtype=ttnn.uint32, layout=ttnn.ROW_MAJOR_LAYOUT, device=device, memory_config=dram) self.spin = int(os.environ.get("DEPTHPRO2_MK_DEC_SPIN", str(1 << 26))) self.prof_t = ttnn.from_torch(torch.zeros(1, 1, nc, P.PROF_WORDS, dtype=torch.int32), dtype=ttnn.uint32, layout=ttnn.ROW_MAJOR_LAYOUT, device=device, memory_config=dram) self._acc = list(ttnn.TensorAccessorArgs(self.weights.arena).get_compile_time_args()) self._desc: Dict[Tuple, object] = {} self.cb = self._cb_sizes() # ------------------------------------------------------------------ L1 def _cb_sizes(self) -> Dict[str, int]: sz = self.plan.cb_sizes() band = -(-sz["band"] // P.T16) * P.T16 # a second band page lets the BRISC read unit k + 1's band while the TRISC computes unit k rest = sum(v for k, v in sz.items() if k != "band") + P.T16 + 4096 pages = 2 if (os.environ.get("DEPTHPRO2_MK_DEC_PIPE", "0") == "1" and rest + 2 * band <= int(os.environ.get("DEPTHPRO2_MK_DEC_L1_KB", "1380")) * 1024) else 1 self.band_pages = pages return dict(w=sz["w"], band=band, band_total=pages * band, tapa_cap=pages * band // P.T16, a_cap=sz["a"] // P.T16 + 1, res=sz["res"], acc_cap=sz["acc"] // P.T32, sel_cap=sz["sel"] // P.T16, plan=-(-self.plan_bytes // 16) * 16) def cb_table(self): cb = self.cb T16, T32 = P.T16, P.T32 return [ (((P.CB_W, "bf16", T16, False),), cb["w"]), (((P.CB_BAND, "raw", cb["band"], False), (P.CB_TAPA, "bf16", T16, False)), cb["band_total"]), (((P.CB_A, "bf16", T16, False),), cb["a_cap"] * T16), (((P.CB_RES, "raw", cb["res"], False),), cb["res"]), (((P.CB_ACC, "fp32", T32, True),), cb["acc_cap"] * T32), (((P.CB_OUT, "bf16", T16, False),), P.OUT_CAP * T16), (((P.CB_CONST, "bf16", T16, False),), P.N_CONST * T16), (((P.CB_SEL, "bf16", T16, False),), cb["sel_cap"] * T16), (((P.CB_Z, "bf16", T16, False),), 16 * T16), (((P.CB_HO, "fp32", T32, False),), 2 * T32), (((P.CB_SYNC, "raw", P.SYNC_BYTES, False),), P.SYNC_BYTES), (((P.CB_PLAN, "raw", cb["plan"], False),), cb["plan"]), ] def l1_bytes(self) -> int: return sum(n for _, n in self.cb_table()) # ------------------------------------------------------------------ args def noc(self, xy) -> Tuple[int, int]: return self._noc[tuple(xy)] def persistent(self) -> List: return [self.weights.arena, self.weights.consts, self.sel, self.plan_t, self.dbg, self.prof_t, *self.maps] def common_args(self, taps, out, nl: int) -> List[int]: gx, gy = self.grid c = [0] * (P.N_COMMON_FIXED + len(self.maps)) x0, y0 = self.noc((0, 0)) x1, y1 = self.noc((gx - 1, gy - 1)) c[P.K_ALL_X0], c[P.K_ALL_Y0], c[P.K_ALL_X1], c[P.K_ALL_Y1] = x0, y0, x1, y1 c[P.K_N_ALL] = gx * gy c[P.K_HUB_X], c[P.K_HUB_Y] = self.noc((0, 0)) c[P.K_NL] = int(nl) c[P.K_WTS] = self.weights.arena.buffer_address() c[P.K_CONST] = self.weights.consts.buffer_address() c[P.K_SEL] = self.sel.buffer_address() c[P.K_OUT] = out.buffer_address() for i in range(4): c[P.K_TAP0 + i] = taps[i].buffer_address() c[P.K_PLANA] = self.plan_t.buffer_address() c[P.K_PLANB] = self.plan_bytes c[P.K_DBG] = self.dbg.buffer_address() c[P.K_SPIN] = self.spin c[P.K_PROF] = self.prof_t.buffer_address() for i, m in enumerate(self.maps): c[P.K_MAP0 + i] = m.buffer_address() return c def core_args(self) -> Dict[Tuple[int, int], List[int]]: gx, gy = self.grid out = {} for y in range(gy): for x in range(gx): a = [0] * P.N_RT_ARGS a[P.A_IDX] = y * gx + x a[P.A_ROLE] = (P.R_FEED if x == 0 else 0) | (P.R_HUB if (x, y) == (0, 0) else 0) a[P.A_X], a[P.A_Y] = x, y a[P.A_ROWX0] = self.noc((min(1, gx - 1), y))[0] a[P.A_ROWX1] = self.noc((gx - 1, y))[0] a[P.A_ROWY] = self.noc((0, y))[1] a[P.A_FX], a[P.A_FY] = self.noc((0, y)) out[(x, y)] = a return out def defines(self) -> List[Tuple[str, str]]: gx, gy = self.grid cb = self.cb d = [("MD_GX", str(gx)), ("MD_GY", str(gy)), ("MD_A_CAP", str(cb["a_cap"])), ("MD_ACC_CAP", str(cb["acc_cap"])), ("MD_TAPA_CAP", str(cb["tapa_cap"])), ("MD_SEL_CAP", str(cb["sel_cap"])), ("MD_OPT_" + self.opt, "1"), ("MD_DMOPT_" + self.dm_opt, "1")] # the JIT disk cache key ignores opt_level # opt-in experiments (DEPTHPRO2_MK_DEC_PIPE=1: BRISC unit pipelining; _FEED_DEPTH: feeder DRAM reads in flight) if os.environ.get("DEPTHPRO2_MK_DEC_PIPE", "0") == "1": d.append(("MD_PIPE", "1")) ms = os.environ.get("DEPTHPRO2_MK_DEC_MCAST_SAFE", "0") if ms in ("1", "2"): # 1: unlinked + acked before the flag, 2: unlinked, ordered by the static VC d.append(("MD_MCAST_SAFE", ms)) if os.environ.get("DEPTHPRO2_MK_DEC_FEED_SERIAL", "0") == "1": d.append(("MD_FEED_SERIAL", "1")) if os.environ.get("DEPTHPRO2_MK_DEC_FEED_DEPTH"): d.append(("MD_FEED_DEPTH", str(int(os.environ["DEPTHPRO2_MK_DEC_FEED_DEPTH"])))) fid = {"LoFi": 0, "HiFi2": 2, "HiFi3": 3, "HiFi4": 4}[self.fidelity] if fid != 4: d.append(("MD_FID", str(fid))) return d + self.extra_defines def program(self, taps, out, nl: Optional[int] = None): import ttnn nl = len(self.plan.layers) if nl is None else int(nl) common = self.common_args(taps, out, nl) key = tuple(common) if key in self._desc: return self._desc[key] gx, gy = self.grid cores = ttnn.CoreRangeSet([ttnn.CoreRange(ttnn.CoreCoord(0, 0), ttnn.CoreCoord(gx - 1, gy - 1))]) fmt = {"bf16": ttnn.bfloat16, "fp32": ttnn.float32, "raw": ttnn.bfloat16} cbs = [] modes = [ttnn.UnpackToDestMode.Default] * 64 for ids, total in self.cb_table(): fds = [] for cb_id, f, page, unpack32 in ids: fds.append(ttnn.CBFormatDescriptor(buffer_index=cb_id, data_format=fmt[f], page_size=page)) if unpack32: modes[cb_id] = ttnn.UnpackToDestMode.UnpackToDestFp32 cbs.append(ttnn.CBDescriptor(total_size=total, core_ranges=cores, format_descriptors=fds)) ct = list(self._acc) args = self.core_args() rt = ttnn.RuntimeArgs() for x in range(gx): for y in range(gy): rt[x][y] = args[(x, y)] cc = ttnn.ComputeConfigDescriptor(math_fidelity=getattr(ttnn.MathFidelity, self.fidelity), fp32_dest_acc_en=True, dst_full_sync_en=False, math_approx_mode=False) cc.unpack_to_dest_mode = modes defines = self.defines() fp = ttnn.KernelDescriptor.SourceType.FILE_PATH dm = ttnn.DataMovementConfigDescriptor kernels = [ ttnn.KernelDescriptor(kernel_source=KERNELS["ncrisc"], source_type=fp, core_ranges=cores, compile_time_args=ct, runtime_args=rt, common_runtime_args=common, defines=defines, config=dm(processor=ttnn.DataMovementProcessor.RISCV_1, noc=ttnn.NOC.NOC_0), opt_level=_opt_level(self.dm_opt)), ttnn.KernelDescriptor(kernel_source=KERNELS["brisc"], source_type=fp, core_ranges=cores, compile_time_args=ct, runtime_args=rt, common_runtime_args=common, defines=defines, config=dm(processor=ttnn.DataMovementProcessor.RISCV_0, noc=ttnn.NOC.NOC_1), opt_level=_opt_level(self.dm_opt)), ttnn.KernelDescriptor(kernel_source=KERNELS["trisc"], source_type=fp, core_ranges=cores, compile_time_args=ct, runtime_args=rt, common_runtime_args=common, defines=defines, config=cc, opt_level=_opt_level(self.opt)), ] sems = [ttnn.SemaphoreDescriptor(id=i, core_ranges=cores, initial_value=0) for i in (0, 1)] desc = ttnn.ProgramDescriptor(kernels=kernels, semaphores=sems, cbs=cbs) self._desc[key] = desc return desc def alloc_out(self): import ttnn return ttnn.allocate_tensor_on_device(ttnn.Shape([self.T, self.hp, self.wp]), ttnn.float32, ttnn.TILE_LAYOUT, self.device, ttnn.DRAM_MEMORY_CONFIG) def run(self, taps, out=None, nl: Optional[int] = None): """Enqueue the DEC program (one ``generic_op``) and return the inverse depth ``[T, Hp, Wp]`` float32 TILE (``out`` given: written in place). ``nl`` < number of layers (debug): run only the first ``nl`` layers (the maps they produce are readable with :meth:`read_map`).""" import ttnn taps = list(taps) if out is None: out = self.alloc_out() io = [*self.persistent(), *taps, out] ttnn.generic_op(io, self.program(taps, out, nl)) return out # ------------------------------------------------------------------ debug readers def read_map(self, name: str, f: int = 0) -> torch.Tensor: """map ``name`` of group frame f as ``[C, H, W]`` float32 (interior pixels)""" import ttnn g = next(m for m in self.plan.maps if m.name == name) st = ttnn.to_torch(self.maps[g.idx]).float().reshape(g.frames, g.fpix, g.C)[f] img = torch.stack([st[g.g(y, 0):g.g(y, 0) + g.W] for y in range(g.H)]) return img.permute(2, 0, 1) def read_dbg(self) -> torch.Tensor: """per-core abort diagnostics [NC, DBG_WORDS] (all zero = no bounded wait gave up)""" import ttnn return ttnn.to_torch(self.dbg).reshape(-1, P.DBG_PAGE)[:, :P.DBG_WORDS].to(torch.int64) & 0xFFFFFFFF def read_prof(self) -> torch.Tensor: """MD_PROF builds: [NC, PROF_WORDS] wall-clock ticks (md_defs.hpp PROF_WORDS layout)""" import ttnn return ttnn.to_torch(self.prof_t).reshape(-1, P.PROF_WORDS).to(torch.int64) & 0xFFFFFFFF def aborts(self) -> List[Tuple[int, List[int]]]: d = self.read_dbg() out = [] for i in range(d.shape[0]): w = d[i].tolist() if w[0] or w[2] or w[4] or w[6] or w[11] or w[13]: out.append((i, w[:10] + [w[11] | w[13]])) # [..., exit-barrier timeout bits] return out def read_storage(self, name: str) -> torch.Tensor: import ttnn g = next(m for m in self.plan.maps if m.name == name) return ttnn.to_torch(self.maps[g.idx]).float().reshape(g.frames, g.fpix, g.C) class Engine: """SPEC section 3 stage-engine adapter (``tt/__init__.py`` contract): ``Engine(device, weights, shape)`` with ``weights`` = :meth:`prepare_weights` (shared by every shape) or the host dict (+ ``size``); ``run(taps)`` -> ``inv`` ``[T, Hp, Wp]`` float32 TILE DRAM (a new tensor per call).""" def __init__(self, device, weights, shape, size: Optional[str] = None, **kw): if isinstance(weights, dict): if size is None: raise ValueError("size is required with host weights") weights = MkDecWeights(device, weights, size) self.shape = shape self.mk = MkDec(device, weights, weights.size, shape.frames, shape.hp, shape.wp, **kw) @staticmethod def prepare_weights(device, host_weights, size: str) -> MkDecWeights: return MkDecWeights(device, host_weights, size) def run(self, taps): return self.mk.run(taps)