# SPDX-License-Identifier: Apache-2.0 """CPU emulator of the DEC megakernel data path (tt/mk_dec): the exact storage layout of every map, the unit decomposition, the band / tilize offsets and the weight-arena stream indexing of every layer, with the device's arithmetic (bf16 operands, fp32 accumulation, bf16 maps). It is the reference the device kernels are debugged against (per layer: the maps it produces must match the device's maps). python -m tt_depthpro2.tests.mk_dec_emu --size S --case img_384x512 """ from __future__ import annotations import argparse import os import sys import time from typing import Dict, List, Optional import torch sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))) from tt_depthpro2.tt.mk_dec import plan as P # noqa: E402 from tt_depthpro2.tt.mk_dec import wprep as WP # noqa: E402 BF = torch.bfloat16 def bf(t: torch.Tensor) -> torch.Tensor: return t.to(BF).float() class Emu: def __init__(self, plan: P.Plan, w: Dict[str, torch.Tensor], arena: Optional[torch.Tensor] = None): self.p = plan self.arena = arena if arena is not None else WP.build_arena(plan.layers, w) self.tiles = WP.untilize(self.arena.reshape(-1, 1024).float()).reshape(self.arena.shape[0], P.PAGE_TILES, 32, 32) c = WP.const_tiles(w) self.const = bf(c) self.sel = WP.sel_tiles(plan.hp, plan.wp) self.maps = [torch.zeros(m.frames, m.fpix, m.C) for m in plan.maps] # ------------------------------------------------------------------ weight stream def wtile(self, L: P.Layer, nb: int, kb: int, idx: int) -> torch.Tensor: pg = P.block_page(L, nb, kb) return self.tiles[pg + idx // P.PAGE_TILES, idx % P.PAGE_TILES] def wblock(self, L: P.Layer, nb: int, kb: int) -> torch.Tensor: pg = P.block_page(L, nb, kb) npg = L.bp0 if kb == 0 else L.bp return self.tiles[pg:pg + npg].reshape(-1, 32, 32) # ------------------------------------------------------------------ helpers def gather_px(self, m: int, f: int, y: int, x0: int, n: int) -> torch.Tensor: """n storage pixels from (y, x0) of map m, frame f: [n, C]""" g = self.p.maps[m] s = g.g(y, x0) assert 0 <= s and s + n <= g.fpix, (g.name, y, x0, n) return self.maps[m][f, s:s + n] def write_px(self, m: int, f: int, y: int, x: int, vals: torch.Tensor, c0: int = 0): g = self.p.maps[m] assert 0 <= y < g.H and 0 <= x and x + vals.shape[0] <= g.W, (g.name, y, x, vals.shape) s = g.g(y, x) self.maps[m][f, s:s + vals.shape[0], c0:c0 + vals.shape[1]] = bf(vals) # ------------------------------------------------------------------ ops def run_layer(self, L: P.Layer, taps: List[torch.Tensor], grp: int, out: torch.Tensor): if L.op == P.OP_RA: # per token tile (the device's RA units are output pages; same numerics) for m in range(self.p.G * self.p.pt): self.unit_ra(L, m, taps, grp) return for u in range(L.u): if L.op == P.OP_UP: self.unit_up(L, u) else: self.unit_c3(L, u, grp, out) def unit_ra(self, L: P.Layer, m0: int, taps, grp: int): p = self.p tap = taps[L.src] kt = L.cin // 32 dst = p.maps[L.dst] for m in (m0,): f, pi = m // p.pt, m % p.pt row0 = (grp * p.G + f) * p.np_ + 32 * pi A = tap[row0:row0 + 32] # [32, C] for nb in range(L.n // L.nbw): acc = torch.zeros(32, L.nbw * 32, dtype=torch.float64) for kb in range(L.nkb): blk = self.wblock(L, nb, kb).double() off = L.nbias if kb == 0 else 0 if kb == 0: for n in range(L.nbw): acc[:, 32 * n:32 * n + 32] += self.const[P.C_E01].double() @ blk[n] for c in range(L.kc): a = A[:, (kb * L.kc + c) * 32:(kb * L.kc + c) * 32 + 32].double() for n in range(L.nbw): acc[:, 32 * n:32 * n + 32] += a @ blk[off + c * L.nbw + n] res = acc.float() for r in range(32): tok = 32 * pi + r if tok >= p.n: break self.write_px(L.dst, f, tok // p.gw, tok % p.gw, res[r:r + 1], nb * L.nbw * 32) def unit_up(self, L: P.Layer, u: int): p = self.p src, dst = p.maps[L.src], p.maps[L.dst] f, rem = divmod(u, L.yb * L.xb) yb, xb = divmod(rem, L.xb) y0, kx0 = yb * L.bh, xb * L.bw bh, bw = min(L.bh, L.ho - y0), min(L.bw, L.kxo - kx0) k = L.s cout = L.n * 32 // (k * k) for r in range(bh): y = y0 + r band = self.gather_px(L.src, f, y, 32 * kx0, 32 * bw) for kx in range(bw): A = band[32 * kx:32 * kx + 32].double() # [32, Cin] x0 = 32 * (kx0 + kx) for nb in range(L.n // L.nbw): blk = self.wblock(L, nb, 0).double() acc = torch.zeros(32, L.nbw * 32, dtype=torch.float64) for n in range(L.nbw): acc[:, 32 * n:32 * n + 32] += self.const[P.C_E01].double() @ blk[n] for c in range(L.kc): a = A[:, 32 * c:32 * c + 32] for n in range(L.nbw): acc[:, 32 * n:32 * n + 32] += a @ blk[L.nbias + c * L.nbw + n] res = acc.float() for rr in range(32): x = x0 + rr if x >= src.W: break for n in range(L.nbw): ch = (nb * L.nbw + n) * 32 gi, co = divmod(ch, cout) a_, b_ = divmod(gi, k) self.write_px(L.dst, f, k * y + a_, k * x + b_, res[rr:rr + 1, 32 * n:32 * n + 32], co) def unit_c3(self, L: P.Layer, u: int, grp: int, out: torch.Tensor): p = self.p src = p.maps[L.src] s = L.s f, rem = divmod(u, L.yb * L.xb) yb, xb = divmod(rem, L.xb) y0, kx0 = yb * L.bh, xb * L.bw bh, bw = min(L.bh, L.ho - y0), min(L.bw, L.kxo - kx0) rows = s * (bh - 1) + 3 px = s * (32 * bw - 1) + 3 band = torch.stack([self.gather_px(L.src, f, s * y0 - 1 + j, s * 32 * kx0 - 1, px) for j in range(rows)]) if L.flags & P.F_RELU_IN: band = band.clamp_min(0) def A(dx, j, kx, ct): i0 = s * 32 * kx + 1 + dx return band[j, i0:i0 + s * 32:s, 32 * ct:32 * ct + 32].double() hc = L.op == P.OP_HC nb_cnt = L.n // L.nbw for nb in range(nb_cnt): acc = torch.zeros(bh, bw, 32, L.nbw * 32, dtype=torch.float64) for kb in range(L.nkb): blk = self.wblock(L, nb, kb).double() off = L.nbias if kb == 0 else 0 for r in range(bh): for kx in range(bw): a_acc = acc[r, kx] if kb == 0: for n in range(L.nbw): if hc: y = y0 + r ycls = 0 if y == 0 else (2 if y == L.ho - 1 else 1) sel = self.sel[ycls * p.kx_hc + kx0 + kx].double() a_acc[:, 32 * n:32 * n + 32] += sel @ blk[n] else: a_acc[:, 32 * n:32 * n + 32] += self.const[P.C_E01].double() @ blk[n] for c in range(L.kc): ct = kb * L.kc + c if hc: for n in range(4): a_, b_ = divmod(n, 2) for o in range(4): oy, ox = a_ - 1 + o // 2, b_ - 1 + o % 2 a_acc[:, 32 * n:32 * n + 32] += A(ox, r + 1 + oy, kx, ct) @ blk[off + (c * 4 + n) * 4 + o] else: for t in range(9): dy, dx = t // 3 - 1, t % 3 - 1 a = A(dx, s * r + 1 + dy, kx, ct) for n in range(L.nbw): a_acc[:, 32 * n:32 * n + 32] += a @ blk[off + (c * 9 + t) * L.nbw + n] # residuals (added in fp32: bf16 maps) for rm in L.res: for r in range(bh): for kx in range(bw): x0 = 32 * (kx0 + kx) rv = self.gather_px(rm, f, y0 + r, x0, 32)[:, nb * L.nbw * 32:(nb + 1) * L.nbw * 32] acc[r, kx] += rv.double() res = acc.float() if L.flags & P.F_RELU_OUT: res = res.clamp_min(0) for r in range(bh): y = y0 + r for kx in range(bw): x0 = 32 * (kx0 + kx) nv = min(32, L.wo - x0) if hc: z = bf(res[r, kx].clamp_min(0)).double() # relu(head.2) -> bf16 (CB_Z) R = torch.zeros(32, 32, dtype=torch.float64) for sb in range(4): zs = z[:, 32 * sb:32 * sb + 32] R += (self.const[P.C_W4H + sb].double() + self.const[P.C_W4L + sb].double()) @ zs.t() R += self.const[P.C_E4].double() @ self.const[P.C_B4T].double().t() R = R.float().clamp_min(0) fr = grp * p.G + f for a_ in range(2): for b_ in range(2): out[fr, 2 * y + a_, 2 * x0 + b_:2 * (x0 + nv):2] = R[2 * a_ + b_, :nv] else: self.write_px(L.dst, f, y, x0, res[r, kx, :nv], nb * L.nbw * 32) def run(self, taps: List[torch.Tensor], nl: Optional[int] = None) -> torch.Tensor: p = self.p taps = [bf(t.reshape(-1, t.shape[-1])) for t in taps] out = torch.zeros(p.T, p.hp, p.wp) for grp in range(p.ngrp): for li, L in enumerate(p.layers): if nl is not None and li >= nl: break self.run_layer(L, taps, grp, out) return out def map_image(self, name: str, f: int = 0) -> torch.Tensor: """map ``name`` of frame f as [C, H, W] (interior)""" g = next(m for m in self.p.maps if m.name == name) st = self.maps[g.idx][f] img = torch.stack([st[g.g(y, 0):g.g(y, 0) + g.W] for y in range(g.H)]) # [H, W, C] return img.permute(2, 0, 1) def golden_taps(g, n_p: int) -> List[torch.Tensor]: out = [] for i in range(4): t = g[f"tap{i}"].float() T, N, C = t.shape z = torch.zeros(T, n_p, C) z[:, :N] = t out.append(z.reshape(T * n_p, C)) return out def main(): from tt_depthpro2.reference import model as R from tt_depthpro2.tests import baseline_helpers as BH ap = argparse.ArgumentParser() ap.add_argument("--size", default="S") ap.add_argument("--case", default="img_384x512") args = ap.parse_args() torch.set_num_threads(8) w = R.load_safetensors(os.path.join(BH.size_dir(args.size), "model.safetensors")) g, _ = BH.load_golden(args.case, args.size) x = R.pad_to_multiple(g["x_norm"]) T, _, hp, wp = x.shape t0 = time.time() plan = P.Plan(args.size, T, hp, wp, 12, 10) emu = Emu(plan, w) inv = emu.run(golden_taps(g, plan.np_)) ref = g["head.out"][:, 0] print(f"emu {time.time() - t0:.1f} s: inv pcc {BH.pcc(inv, ref):.7f} max_rel {BH.max_rel(inv, ref):.2e}") for i, nm in enumerate(("P0", "P1", "P2", "P3")): d = emu.map_image(nm) gr = g[f"reassemble{i}"][0] d = d[:gr.shape[0]] print(f" reassemble{i}: pcc {BH.pcc(d, gr):.7f} max_rel {BH.max_rel(d, gr):.2e}") d = emu.map_image("Z0") print(f" decoder.out: pcc {BH.pcc(d, g['decoder.out'][0]):.7f} max_rel {BH.max_rel(d, g['decoder.out'][0]):.2e}") if __name__ == "__main__": main()