File size: 12,584 Bytes
b7e49b8 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 | # 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()
|