File size: 11,367 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 | # SPDX-License-Identifier: Apache-2.0
"""DEC megakernel bring-up / debug run on one golden case: the stage on the golden taps vs the float32 golden
``head.out`` (and the CPU emulator's maps, layer by layer), optional trace timing and replay determinism.
bin/devrun -t 900 -- python -u bundles/depthpro2/code/tt_depthpro2/tests/mk_dec_run.py --size S \
--case img_384x512 [--nl N] [--maps] [--reps 20]
"""
from __future__ import annotations
import argparse
import json
import os
import sys
import time
import torch
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..")))
from tt_depthpro2.reference import model as R # noqa: E402
from tt_depthpro2.tests import baseline_helpers as BH # noqa: E402
from tt_depthpro2.tests import mk_dec_emu as EMU # noqa: E402
from tt_depthpro2.tt.mk_dec import plan as P # noqa: E402
EMU_DIR = os.path.join(BH.ROOT, "assets/depthpro2/mk_dec_emu")
LOG = os.path.join(BH.ROOT, "logs/depthpro2/mk_dec/runs.jsonl")
def emu_maps(size: str, case: str, plan: P.Plan, w, g):
os.makedirs(EMU_DIR, exist_ok=True)
# _pa: page-aligned map rows (storage layout of round 7)
path = os.path.join(EMU_DIR, f"{case}__{size}__{plan.hp}x{plan.wp}_T{plan.T}_G{plan.G}_pa.pt")
if os.path.exists(path):
return torch.load(path, weights_only=True)
t0 = time.time()
emu = EMU.Emu(plan, w)
inv = emu.run(EMU.golden_taps(g, plan.np_))
out = {"inv": inv, **{m.name: emu.maps[m.idx] for m in plan.maps}}
torch.save(out, path)
print(f"emulator {time.time() - t0:.0f} s -> {path}", flush=True)
return out
def rand_taps(size: str, T: int, hp: int, wp: int, seed: int = 0):
"""taps [T, N, C] with DINOv3-like scale (per-channel spread), deterministic (tests/mk_dec_cmp.py uses the same)"""
gen = torch.Generator().manual_seed(seed)
n = (hp // 16) * (wp // 16)
c = R.SIZES[size].dim
out = []
for i in range(4):
sc = torch.rand(c, generator=gen) * 2.0 + 0.25
out.append(torch.randn(T, n, c, generator=gen) * sc)
return out
def print_prof(mk):
"""per layer: wall time (hub barrier exits), max core work time, TRISC split (max over cores, us)"""
pf = mk.read_prof().double() # [NC, PROF_WORDS] ticks
clk = 1.0e3 # wall-clock ticks per us (Blackhole: 1 GHz reference)
names = [L.name for L in mk.plan.layers]
prev = 0.0
tot = {k: 0.0 for k in ("wall", "barrier", "wwait", "inwait", "tilize", "mm", "epi")}
print(f"{'layer':8s} {'wall':>7s} {'work':>7s} {'bar':>6s} | trisc max: {'w_wait':>7s} {'in_wait':>7s} "
f"{'tilize':>7s} {'mm':>7s} {'epi':>7s} (us)")
for l, nm in enumerate(names[:32]):
done = pf[:, 8 * l + 0].max().item() / clk
bar = pf[0, 8 * l + 1].item() / clk
sl = [pf[:, 8 * l + k].max().item() / clk for k in range(2, 7)]
wall = bar - prev
tot["wall"] += wall
tot["barrier"] += bar - done
for k, v in zip(("wwait", "inwait", "tilize", "mm", "epi"), sl):
tot[k] += v
print(f"{nm:8s} {wall:7.1f} {done - prev:7.1f} {bar - done:6.1f} | {sl[0]:16.1f} {sl[1]:7.1f} {sl[2]:7.1f} "
f"{sl[3]:7.1f} {sl[4]:7.1f}")
prev = bar
print("totals (us): " + ", ".join(f"{k} {v:.0f}" for k, v in tot.items()), flush=True)
def show_aborts(mk, ab, n=12):
"""abort codes per core (md_defs.hpp AB_*; 7 = released by another RISC of the core), exit-barrier timeouts"""
for i, wv in ab[:n]:
print(f" core {i} (x {i % mk.grid[0]}, y {i // mk.grid[0]}): brisc {wv[0]}/{wv[1]} ncrisc {wv[2]}/{wv[3]} "
f"unpack {wv[4]}/{wv[5]} pack {wv[6]}/{wv[7]} layer {wv[8]} exit-bits {wv[10]}", flush=True)
if ab:
codes = {}
for _, wv in ab:
k = tuple(wv[j] for j in (0, 2, 4, 6))
codes[k] = codes.get(k, 0) + 1
print(f" abort-code histogram (brisc, ncrisc, unpack, pack): {codes}", flush=True)
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--size", default="S")
ap.add_argument("--case", default="img_384x512")
ap.add_argument("--nl", type=int, default=None)
ap.add_argument("--maps", action="store_true", help="compare every map with the CPU emulator")
ap.add_argument("--reps", type=int, default=0, help="trace replays for timing / determinism")
ap.add_argument("--eager", type=int, default=0, help="extra eager runs (no trace), each checked for aborts / equality")
ap.add_argument("--fid", default="HiFi4")
ap.add_argument("--dump", default="", help="save the device storage of these maps (comma list, 'all') to EMU_DIR")
ap.add_argument("--prof", action="store_true", help="profiling build (MD_PROF): per-layer timing table")
ap.add_argument("--dispatch", default="eth", choices=("eth", "worker"),
help="dispatch cores: eth (12x10 grid, default) or worker (11x10)")
ap.add_argument("--shape", default="", help="HxWxT: random taps (seed 0) instead of a golden case; the output is "
"saved for tests/mk_dec_cmp.py (CPU reference decode of the same taps)")
args = ap.parse_args()
torch.set_num_threads(8)
import ttnn
from tt_depthpro2.tt.mk_dec.program import MkDec, MkDecWeights
w = R.load_safetensors(os.path.join(BH.size_dir(args.size), "model.safetensors"))
if args.shape:
hp, wp, T = (int(v) for v in args.shape.split("x"))
args.case = f"rand_{hp}x{wp}x{T}"
g = {f"tap{i}": t for i, t in enumerate(rand_taps(args.size, T, hp, wp))}
g["head.out"] = None
else:
g, _ = BH.load_golden(args.case, args.size)
x = R.pad_to_multiple(g["x_norm"])
T, _, hp, wp = x.shape
dct = ttnn.DispatchCoreType.ETH if args.dispatch == "eth" else ttnn.DispatchCoreType.WORKER
dev = ttnn.open_device(device_id=0, dispatch_core_config=ttnn.DispatchCoreConfig(dct),
l1_small_size=32768, trace_region_size=16 << 20)
rec = {"size": args.size, "case": args.case, "T": T, "hp": hp, "wp": wp, "fid": args.fid, "dispatch": args.dispatch,
"time": time.strftime("%Y-%m-%d %H:%M:%S")}
try:
t0 = time.perf_counter()
wts = MkDecWeights(dev, w, args.size)
mk = MkDec(dev, wts, args.size, T, hp, wp, fidelity=args.fid,
defines=[("MD_PROF", "1")] if args.prof else ())
print(mk.plan.summary(), flush=True)
print(f"weights {wts.dram_bytes / 2**20:.1f} MB, L1 {mk.l1_bytes() / 1024:.0f} KB, prep {time.perf_counter() - t0:.1f} s",
flush=True)
n_p = mk.plan.np_
taps = []
for i in range(4):
t = g[f"tap{i}"].float()
z = torch.zeros(T, n_p, t.shape[-1])
z[:, :t.shape[1]] = t
taps.append(ttnn.from_torch(z.reshape(1, 1, T * n_p, -1).to(torch.bfloat16), dtype=ttnn.bfloat16,
layout=ttnn.TILE_LAYOUT, device=dev, memory_config=ttnn.DRAM_MEMORY_CONFIG))
t0 = time.perf_counter()
out = mk.run(taps, nl=args.nl)
ttnn.synchronize_device(dev)
rec["first_run_s"] = time.perf_counter() - t0
ab = mk.aborts()
rec["aborts"] = len(ab)
print(f"first run {rec['first_run_s']:.1f} s; aborted cores {len(ab)}", flush=True)
show_aborts(mk, ab)
inv = ttnn.to_torch(out).float().reshape(T, hp, wp)
rec["finite"] = bool(torch.isfinite(inv).all())
if args.shape:
os.makedirs(EMU_DIR, exist_ok=True)
path = os.path.join(EMU_DIR, f"dev_{args.case}__{args.size}.pt")
torch.save({"inv": inv}, path)
print(f"saved {path} finite {rec['finite']} (compare: tests/mk_dec_cmp.py)", flush=True)
elif args.nl is None:
ref = g["head.out"][:, 0]
rec["inv_pcc"] = BH.pcc(inv, ref)
rec["inv_max_rel"] = BH.max_rel(inv, ref)
print(f"inv vs golden: pcc {rec['inv_pcc']:.7f} max_rel {rec['inv_max_rel']:.3e} finite {rec['finite']}",
flush=True)
if args.maps:
em = emu_maps(args.size, args.case, mk.plan, w, g)
nl = len(mk.plan.layers) if args.nl is None else args.nl
done = {mk.plan.layers[i].dst for i in range(nl) if mk.plan.layers[i].dst >= 0}
res = {}
for m in mk.plan.maps:
if m.idx not in done:
continue
d = mk.read_storage(m.name)
e = em[m.name]
# interior only
mask = torch.zeros(m.fpix, dtype=torch.bool)
for yy in range(m.H):
mask[m.g(yy, 0):m.g(yy, 0) + m.W] = True
dd, ee = d[:, mask], e[:, mask]
pads_ok = bool((d[:, ~mask] == 0).all())
res[m.name] = (BH.pcc(dd, ee), BH.max_rel(dd, ee), pads_ok)
print(f" map {m.name:4s} pcc {res[m.name][0]:.7f} max_rel {res[m.name][1]:.2e} pads_zero {pads_ok}",
flush=True)
if args.nl is None:
print(f" inv vs emu: pcc {BH.pcc(inv, em['inv']):.7f} max_rel {BH.max_rel(inv, em['inv']):.2e}")
rec["maps"] = res
if args.dump:
names = [m.name for m in mk.plan.maps] if args.dump == "all" else args.dump.split(",")
dump = {nm: mk.read_storage(nm) for nm in names}
dump["inv"] = inv
path = os.path.join(EMU_DIR, f"dev_{args.case}__{args.size}.pt")
torch.save(dump, path)
print(f"dumped {names} -> {path}", flush=True)
for i in range(args.eager):
t0 = time.perf_counter()
o3 = mk.run(taps, nl=args.nl)
ttnn.synchronize_device(dev)
same = torch.equal(ttnn.to_torch(o3).float().reshape(T, hp, wp), inv)
ab = mk.aborts()
print(f"eager rerun {i + 1}: {1e3 * (time.perf_counter() - t0):.1f} ms, aborted cores {len(ab)}, "
f"bit-exact {same}", flush=True)
show_aborts(mk, ab)
ttnn.deallocate(o3)
if args.prof:
print_prof(mk)
if args.reps:
raw = inv.clone()
tid = ttnn.begin_trace_capture(dev, cq_id=0)
o2 = mk.run(taps, nl=args.nl)
ttnn.end_trace_capture(dev, tid, cq_id=0)
ttnn.execute_trace(dev, tid, cq_id=0, blocking=True)
t0 = time.perf_counter()
for _ in range(args.reps):
ttnn.execute_trace(dev, tid, cq_id=0, blocking=False)
ttnn.synchronize_device(dev)
rec["dec_ms"] = 1e3 * (time.perf_counter() - t0) / args.reps
same = torch.equal(ttnn.to_torch(o2).float().reshape(T, hp, wp), raw)
rec["replay_bitexact"] = same
ab = mk.aborts()
rec["aborts_after_trace"] = len(ab)
show_aborts(mk, ab)
ttnn.release_trace(dev, tid)
print(f"trace: {rec['dec_ms']:.3f} ms / run, replay bit-exact {same}, aborted cores after the replays "
f"{rec['aborts_after_trace']}", flush=True)
finally:
ttnn.close_device(dev)
os.makedirs(os.path.dirname(LOG), exist_ok=True)
with open(LOG, "a") as f:
f.write(json.dumps({k: v for k, v in rec.items() if k != "maps"}) + "\n")
if __name__ == "__main__":
main()
|