#!/usr/bin/env python3 """PACK bring-up probe (OPT round 4 R4.2; hang protocol: smallest shapes first, eager x2, then a 2-call trace). ``tt.pack.pack`` against the stock ``ttaw.trace.pack_outputs`` on random outputs of the frame's kinds (TILE fp32 of narrow and wide channel counts, one-row TILE, ROW_MAJOR fp32 and uint32 class maps, a bf16 TILE map): every unpacked array must be bit-identical. ``--scale model`` uses the frame's output shapes. bin/devrun -t 600 -- python -u code/scripts/pack_probe.py --scale small """ from __future__ import annotations import argparse import sys import time import numpy as np SMALL = [("a", (1, 1, 64, 9), "f32", "tile"), ("b", (1, 1, 1, 42), "f32", "tile"), ("c", (1, 1, 64, 32), "f32", "rm"), ("d", (1, 1, 96, 32), "u32", "rm"), ("e", (1, 1, 96, 160), "f32", "tile"), ("f", (1, 1, 32, 14), "bf16", "tile"), ("g", (1, 1, 1, 4), "f32", "tile"), ("h", (1, 1, 4128, 1), "f32", "tile")] MODEL = [("lane", (1, 1, 12512, 32), "f32", "rm"), ("seg2d", (1, 1, 5184, 32), "u32", "rm"), ("depth", (1, 1, 5184, 32), "u32", "rm"), ("depth_mean", (1, 1, 41472, 1), "f32", "tile"), ("hm_reg", (1, 1, 100000, 8), "f32", "tile"), ("det2d_s0", (1, 1, 165888, 14), "f32", "tile"), ("det2d_s1", (1, 1, 41472, 14), "f32", "tile"), ("det2d_s2", (1, 1, 10368, 14), "f32", "tile"), ("ego", (1, 1, 1, 42), "f32", "tile"), ("occ", (1, 1, 40000, 160), "f32", "tile"), ("traj", (1, 1, 100000, 39), "f32", "tile"), ("stationary", (1, 1, 100000, 1), "f32", "tile"), ("tl", (1, 1, 1, 4), "f32", "tile"), ("risk", (1, 1, 100000, 1), "f32", "tile"), ("lane_logit", (1, 1, 400000, 9), "f32", "tile")] def main() -> int: ap = argparse.ArgumentParser() ap.add_argument("--scale", default="small", choices=("small", "model")) ap.add_argument("--trace", action="store_true") ap.add_argument("--reps", type=int, default=5) ap.add_argument("--cm", action="store_true", help="R4.3: channel-major (NCHW) entries") ap.add_argument("--version", type=int, default=1, choices=(1, 2), help="2: kernels/pack_rows2.cpp (OPT2 R4.3)") a = ap.parse_args() import torch import ttnn from tt_meteor.tt import pack from tt_meteor.tt.model import READ_SEG_BYTES, join_segments from tt_meteor.ttaw.device import open_device from tt_meteor.ttaw.trace import pack_outputs dev = open_device(dispatch="eth", trace_region_size=64 << 20) rng = np.random.default_rng(0) spec = SMALL if a.scale == "small" else MODEL seg_rows = READ_SEG_BYTES // 4096 if a.scale == "model" else 3 from tt_meteor.tt.unpack import CHANNEL_MAJOR cmap = {} if a.cm: cmap = dict(CHANNEL_MAJOR) if a.scale == "model" else {"a": (4, 1, 16), "e": (1, 6, 16), "h": (3, 86, 16)} outs, ref = {}, {} for name, shp, dt, lay in spec: if dt == "u32": x = rng.integers(0, 64, shp).astype(np.int32) t = ttnn.from_torch(torch.from_numpy(x), dtype=ttnn.uint32, layout=ttnn.ROW_MAJOR_LAYOUT, device=dev, memory_config=ttnn.DRAM_MEMORY_CONFIG) else: x = rng.standard_normal(shp).astype(np.float32) x.flat[::7] = -0.0 t = ttnn.from_torch(torch.from_numpy(x), dtype=ttnn.float32 if dt == "f32" else ttnn.bfloat16, layout=ttnn.TILE_LAYOUT if lay == "tile" else ttnn.ROW_MAJOR_LAYOUT, device=dev, memory_config=ttnn.DRAM_MEMORY_CONFIG) outs[name] = t p = pack_outputs(outs) want = p.layout.unpack(ttnn.to_torch(p.tensor).numpy()) bad = 0 def layout_cm(layout): return {e.name for e in layout.entries if e.name in cmap and len(e.shape) == 4 and e.shape[0] == cmap[e.name][0] and tuple(e.shape[2:]) == tuple(cmap[e.name][1:])} def check(tag, segs, layout): nonlocal bad got = join_segments([ttnn.to_torch(s).numpy() for s in segs], layout) ok = True for k, v in want.items(): g = got[k] if k in layout_cm(layout): n_, h_, w_ = cmap[k] v = np.ascontiguousarray(v.reshape(n_, h_, w_, -1).transpose(0, 3, 1, 2)) same = g.shape == v.shape and np.array_equal(np.ascontiguousarray(g).view(np.uint32), np.ascontiguousarray(v).view(np.uint32)) if not same: ok = False bad += 1 print(f" {tag} {k}: DIFFERENT shape {g.shape} vs {v.shape}", flush=True) print(f" {tag}: {'IDENTICAL' if ok else 'DIFFERENT'} ({len(segs)} segments, channel-major " f"{sorted(layout_cm(layout))})", flush=True) print(f"[pack] {a.scale}: {len(spec)} outputs, grid {dev.compute_with_storage_grid_size()}", flush=True) for i in range(2): segs, lay = pack.pack(outs, seg_rows, cmap or None, version=a.version) check(f"eager{i + 1}", segs, lay) for s in segs: ttnn.deallocate(s) for ver in ((a.version, 1) if a.trace and a.version == 2 else (a.version,) if a.trace else ()): box = {} print(f" [kernel version {ver}]", flush=True) def body(): box["segs"], box["lay"] = pack.pack(outs, seg_rows, cmap or None, version=ver) body() for s in box["segs"]: ttnn.deallocate(s) tid = ttnn.begin_trace_capture(dev, cq_id=0) body() ttnn.end_trace_capture(dev, tid, cq_id=0) for i in range(2): ttnn.execute_trace(dev, tid, cq_id=0, blocking=True) check(f"trace{i}", box["segs"], box["lay"]) 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 ms: p50 {np.median(ts):.3f} min {min(ts):.3f}", flush=True) ttnn.release_trace(dev, tid) for s in box["segs"]: ttnn.deallocate(s) if a.trace: # stock chain timing under trace sbox = {} def sbody(): sbox["p"] = pack_outputs(outs) sbody() tid = ttnn.begin_trace_capture(dev, cq_id=0) sbody() ttnn.end_trace_capture(dev, tid, cq_id=0) 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" stock pack_outputs trace replay ms: p50 {np.median(ts):.3f} min {min(ts):.3f}", flush=True) ttnn.release_trace(dev, tid) ttnn.close_device(dev) print("ALL IDENTICAL" if bad == 0 else f"{bad} DIFFERENT") return 0 if bad == 0 else 1 if __name__ == "__main__": sys.exit(main())