#!/usr/bin/env python3 """MK3 lift bring-up probe (the D19 module megakernel, tt/lift_mk.py; hang protocol: smallest shape first, eager x2, then a 2-call trace, then the frame shape). Synthetic 8-camera rig (the host tests' geometry) or a sample's calibration, random ctx (normal) and prob (softmax of normal logits) rounded to bf16. ``--nrb N`` runs the kernel on the first N row blocks of 32 cells only (the other cores exit at once). Checks the device output against the host emulation (``lift_mk3_numpy``: the kernel's fp32 order incl. the TF32 coefficient, then bf16) and, at the full shape, the stock lift (``TtLift`` taps ``lift.bev``) and both against the fp32 reference (``reference.port_form.lift_from_tables``). METEOR_DEVICE_OK=1 bin/devrun -t 600 -- python -u code/scripts/lift_mk3_probe.py --nrb 4 """ from __future__ import annotations import argparse import sys import time import numpy as np def synthetic_geom(): from tt_meteor.host.calib import lift_geometry rng = np.random.default_rng(3) K = np.tile(np.array([[400.0, 0, 384], [0, 400.0, 216], [0, 0, 1]], np.float32), (1, 8, 1, 1)) T = np.zeros((1, 8, 4, 4), np.float32) for i, yaw in enumerate(np.linspace(0, 2 * np.pi, 8, endpoint=False)): c, s = np.cos(yaw), np.sin(yaw) R_ego_cam = np.array([[-s, 0, c], [c, 0, s], [0, -1, 0]], np.float32) Tec = np.eye(4, dtype=np.float32) Tec[:3, :3], Tec[:3, 3] = R_ego_cam, [0.0, 0.0, 1.8 + 0.01 * rng.random()] T[0, i] = np.linalg.inv(Tec) return lift_geometry(K, T) def bf16(a): import torch return torch.from_numpy(np.ascontiguousarray(a, np.float32)).to(torch.bfloat16).float().numpy() def stats(name, y, ref): d = (y.astype(np.float64) - ref) rr = float(np.sqrt((d ** 2).mean() / max((ref ** 2).mean(), 1e-30))) pcc = float(np.corrcoef(y.reshape(-1), ref.reshape(-1))[0, 1]) if ref.std() > 0 else float("nan") print(f" {name}: max|d| {np.abs(d).max():.3e} rrmse {rr:.3e} pcc {pcc:.9f}", flush=True) return rr def main() -> int: ap = argparse.ArgumentParser() ap.add_argument("--nrb", type=int, default=4) ap.add_argument("--trace", action="store_true") ap.add_argument("--stock", action="store_true", help="also run the stock lift (full shape only)") ap.add_argument("--debug", default="", help="comma list of kernel defines LIFT_MK3_") ap.add_argument("--reps", type=int, default=10) ap.add_argument("--dump", default="", help="npz path: device output, emulation, inputs of eager 1") a = ap.parse_args() import torch import ttnn from tt_meteor.reference import config as C from tt_meteor.tt.lift_mk import MK_GEO, MK_IDX, NRB, lift_mk3, lift_mk3_numpy, mk3_tables from tt_meteor.ttaw.device import open_device geom = synthetic_geom() rng = np.random.default_rng(0) ctx = bf16(rng.standard_normal((8, C.FEAT_H, C.FEAT_W, C.CTX_C))) lg = rng.standard_normal((8, C.FEAT_H, C.FEAT_W, C.DEPTH_BINS)).astype(np.float32) * 2 prob = bf16(np.exp(lg) / np.exp(lg).sum(-1, keepdims=True)) dev = open_device(dispatch="eth", trace_region_size=64 << 20) g = dev.compute_with_storage_grid_size() nc = int(g.x) * int(g.y) nrb = min(int(a.nrb), NRB) tb = mk3_tables(geom, nc, nrb) print(f"cores {nc} ({g.x}x{g.y}), row blocks {nrb}, idx {tb[MK_IDX].shape}, geo {tb[MK_GEO].shape}", flush=True) def up(x, dtype, layout): tt = torch.from_numpy(np.ascontiguousarray(x)) return ttnn.from_torch(tt, dtype=dtype, layout=layout, device=dev, memory_config=ttnn.DRAM_MEMORY_CONFIG) ctx_t = up(ctx, ttnn.bfloat16, ttnn.ROW_MAJOR_LAYOUT) prob_t = up(prob, ttnn.bfloat16, ttnn.ROW_MAJOR_LAYOUT) idx_t = up(tb[MK_IDX].view(np.int32), ttnn.uint32, ttnn.ROW_MAJOR_LAYOUT) geo_t = up(tb[MK_GEO], ttnn.float32, ttnn.TILE_LAYOUT) rows = nrb * 32 emu = bf16(lift_mk3_numpy(ctx, prob, tb, nc, nrb=nrb))[:rows] dbg = tuple(x.strip() for x in a.debug.split(",") if x.strip()) bad = 0 y = None for i in range(2): t0 = time.perf_counter() y = lift_mk3(ctx_t, prob_t, idx_t, geo_t, debug=dbg, nrb=nrb) ttnn.synchronize_device(dev) dt = (time.perf_counter() - t0) * 1e3 yy = ttnn.to_torch(y).float().numpy().reshape(-1, C.CTX_C)[:rows] nd = int((yy != emu).sum()) ok_shape = not np.isnan(yy).any() print(f"eager{i + 1} ({dt:.1f} ms): {nd} / {yy.size} elements differ from the emulation; " f"max |d| {np.abs(yy - emu).max():.3e}; nan {not ok_shape}", flush=True) stats("vs emulation", yy, emu.astype(np.float64)) if a.dump and i == 0: np.savez(a.dump, y=yy, emu=emu, ctx=ctx, prob=prob, idx=tb[MK_IDX], geo=tb[MK_GEO], nc=nc, nrb=nrb) if nd > yy.size * 1e-3 or not ok_shape: bad += 1 if i == 0: ttnn.deallocate(y) if nrb == NRB: from tt_meteor.reference.port_form import lift_from_tables ref = lift_from_tables(torch.from_numpy(ctx.transpose(0, 3, 1, 2).copy()), torch.from_numpy(prob.transpose(0, 3, 1, 2).copy()), geom) ref = ref.numpy().reshape(C.CTX_C, -1).T.astype(np.float64) print("against the fp32 reference:", flush=True) stats("mk3", ttnn.to_torch(y).float().numpy().reshape(-1, C.CTX_C), ref) stats("emulation (fp32, before bf16)", lift_mk3_numpy(ctx, prob, tb, nc), ref) if a.stock: from tt_meteor.tt.lift import TtLift, lift_tables lt = lift_tables(geom) grid_t = up(lt["lift_grid"], ttnn.float32, ttnn.ROW_MAJOR_LAYOUT) tabs = [up(lt[k], ttnn.float32, ttnn.TILE_LAYOUT) for k in lt if k != "lift_grid"] lift = TtLift() taps = {} raw = lift(ctx_t, prob_t, grid_t, tabs, taps=taps) sb = ttnn.to_torch(taps["lift.bev"].tensor).float().numpy().reshape(-1, C.CTX_C) stats("stock lift", sb, ref) ttnn.deallocate(raw.tensor) if a.trace: ttnn.deallocate(y) from tt_meteor.reference import config as C2 from tt_meteor.ttaw.ops.conv import FeatureMap from tt_meteor.tt.lift import TtLift, lift_tables lift = TtLift() variants = {"mk3": lambda: lift_mk3(ctx_t, prob_t, idx_t, geo_t, debug=dbg, nrb=nrb)} if nrb == NRB: variants["mk3+resize"] = lambda: lift.resize(FeatureMap( lift_mk3(ctx_t, prob_t, idx_t, geo_t, debug=dbg), 1, C2.LIFT_H, C2.LIFT_W, C2.CTX_C)).tensor if a.stock: variants["stock"] = lambda: lift(ctx_t, prob_t, grid_t, tabs).tensor for name, fn in variants.items(): ttnn.deallocate(fn()) # warm the program cache box = {} tid = ttnn.begin_trace_capture(dev, cq_id=0) box["y"] = fn() ttnn.end_trace_capture(dev, tid, cq_id=0) for i in range(2): ttnn.execute_trace(dev, tid, cq_id=0, blocking=True) if name == "mk3": yy = ttnn.to_torch(box["y"]).float().numpy().reshape(-1, C.CTX_C)[:rows] nd = int((yy != emu).sum()) print(f"trace x2: {nd} elements differ from the emulation", flush=True) bad += nd > yy.size * 1e-3 ts = [] for _ in range(a.reps): t0 = time.perf_counter() ttnn.execute_trace(dev, tid, cq_id=0, blocking=True) ts.append((time.perf_counter() - t0) * 1e3) print(f"trace replay [{name}]: p50 {np.median(ts):.3f} ms, min {min(ts):.3f} ms ({a.reps} reps)", flush=True) ttnn.release_trace(dev, tid) ttnn.deallocate(box["y"]) print("RESULT", "FAIL" if bad else "OK", flush=True) ttnn.close_device(dev) return 1 if bad else 0 if __name__ == "__main__": sys.exit(main())