DepthPro2 / code /tt_depthpro2 /tests /mk_dec_run.py
changh95's picture
tt-model push depthpro2 (container)
b7e49b8 verified
Raw History Blame Contribute Delete
11.4 kB
# 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()