#!/usr/bin/env python3 """R6 bring-up probe (OPT_PLAN round-6 rank 1): 4-D TILE hand-offs around ttnn's DRAM-sliced conv path. ttnn's DRAM conv path reshapes a flat ``[1, 1, N*H*W, C]`` input to ``[N, H, W, C]`` and its 4-D output back to flat; at widths that are not multiples of 32 both TILE reshapes are copies (ReshapeView, 0.9-1.7 ms at the BEV sizes). A 4-D TILE input makes the first reshape a no-op; a ROW_MAJOR output makes the second a view, and a tilize of the ROW_MAJOR ``[N, H, W, C]`` view gives the next conv its 4-D TILE input. ttnn picks the slice type from the output layout (TILE: height slicing for tall maps; ROW_MAJOR: width slicing), so the ROW_MAJOR-output variants pass an explicit height slice count. Per shape, every variant is compared bit for bit with the stock path and timed as a traced replay (p50 of ``--reps`` replays): - ``stock`` : flat TILE in -> conv (auto slices) -> flat TILE out; - ``t4`` : 4-D TILE in -> conv (auto) -> flat TILE out (the input reshape is a no-op); - ``tile_hN`` : 4-D TILE in -> conv (height, N) -> flat TILE out (which N the auto rule picks: same bits, same time); - ``rmo_hN`` : 4-D TILE in -> conv (height, N, ROW_MAJOR out) -> tilize of the 4-D view (the next conv's input); - ``chain`` : two convs, stock (4 reshapes) vs ``rmo_hN`` hand-off (flat TILE in, 4-D TILE between, flat TILE out). METEOR_DEVICE_OK=1 bin/devrun -t 600 -- python -u code/scripts/t4d_probe.py --shapes 64,48,32,32,1 """ from __future__ import annotations import argparse import sys import time import numpy as np def main() -> int: ap = argparse.ArgumentParser() ap.add_argument("--shapes", default="64,48,32,32,1", help="H,W,Cin,Cout,stride[;...] (BEV: 400,250,192,192,1;800,500,96,64,1;800,500,96,192,2)") ap.add_argument("--slices", default="2,3,4,5,6,8", help="explicit height slice counts tried") ap.add_argument("--reps", type=int, default=10) ap.add_argument("--no-trace", action="store_true") a = ap.parse_args() import torch import ttnn from tt_meteor.tt.layers import CONV_CONFIG from tt_meteor.tt.params import DEFAULT_PRECISION from tt_meteor.ttaw.device import open_device from tt_meteor.ttaw.ops.conv import Conv2d, FeatureMap dev = open_device(dispatch="eth", trace_region_size=256 << 20) rng = np.random.default_rng(0) bad = 0 def host(t): x = ttnn.to_torch(t).float().numpy() return x.reshape(-1, x.shape[-1]) def timed(fn, name): try: out = fn() # eager x2 (compile, then the cached programs) except RuntimeError as e: print(f" {name}: rejected ({str(e).splitlines()[0][:120]})", flush=True) return None, float("nan") ttnn.deallocate(out) out = fn() ttnn.synchronize_device(dev) res = host(out) ttnn.deallocate(out) if a.no_trace: return res, float("nan") tid = ttnn.begin_trace_capture(dev, cq_id=0) tout = fn() 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) tres = host(tout) ttnn.release_trace(dev, tid) ttnn.deallocate(tout) if not np.array_equal(res, tres): print(f" {name}: trace replay != eager", flush=True) return res, float(np.median(ts)) def report(name, out, t, ref, t_ref): nonlocal bad if out is None: return same = out.shape == ref.shape and np.array_equal(out, ref) bad += 0 if same else 1 print(f" {name:10s} {t:8.3f} ms ({t - t_ref:+.3f}) {'IDENTICAL' if same else 'DIFFERENT'}", flush=True) for spec in a.shapes.split(";"): h, w, cin, cout, s = (int(v) for v in spec.split(",")) x = rng.standard_normal((1, 1, h * w, cin)).astype(np.float32) xt = ttnn.from_torch(torch.from_numpy(x), dtype=ttnn.bfloat16, layout=ttnn.TILE_LAYOUT, device=dev, memory_config=ttnn.DRAM_MEMORY_CONFIG) x4 = ttnn.reshape(xt, (1, h, w, cin)) wts = (rng.standard_normal((cout, cin, 3, 3)) / np.sqrt(9 * cin)).astype(np.float32) wts2 = (rng.standard_normal((cout, cout, 3, 3)) / np.sqrt(9 * cout)).astype(np.float32) b = rng.standard_normal(cout).astype(np.float32) * 0.1 kw = dict(activation="relu", precision=DEFAULT_PRECISION, output_dtype="bfloat16", conv_config=CONV_CONFIG) c1 = Conv2d(wts, b, stride=s, padding=1, name="c1", **kw) c2 = Conv2d(wts2, b, name="c2", **kw) oh, ow = c1.out_hw(h, w) def run(conv, t, hh, ww, layout="tile", slicing="auto"): conv.output_layout, conv.slicing = layout, slicing return conv(FeatureMap(t, 1, hh, ww, conv.in_channels)).tensor def t4d(y, hh, ww, c): """ROW_MAJOR flat conv output -> its [1, H, W, C] view tilized (the next conv's 4-D TILE input).""" v = ttnn.reshape(y, (1, hh, ww, c)) t = ttnn.to_layout(v, ttnn.TILE_LAYOUT) ttnn.deallocate(y, False) return t ref, t_ref = timed(lambda: run(c1, xt, h, w), "stock") print(f"[{h}x{w} {cin}->{cout} s{s}] stock {t_ref:.3f} ms", flush=True) out, t = timed(lambda: run(c1, x4, h, w), "t4") report("t4", out, t, ref, t_ref) ok_n = [] for n in (int(v) for v in a.slices.split(",")): out, t = timed(lambda: run(c1, x4, h, w, slicing=("height", n)), f"tile_h{n}") report(f"tile_h{n}", out, t, ref, t_ref) if out is not None and np.array_equal(out, ref): ok_n.append(n) out, t = timed(lambda: run(c1, x4, h, w, "row_major", ("height", n)), f"rmo_h{n}") report(f"rmo_h{n}", out, t, ref, t_ref) out, t = timed(lambda: t4d(run(c1, x4, h, w, "row_major", ("height", n)), oh, ow, cout), f"rmo4_h{n}") if out is not None: out = out.reshape(1, oh, -1, cout)[:, :, :ow].reshape(-1, cout) # 4-D TILE pads W to 32 report(f"rmo4_h{n}", out, t, ref, t_ref) # chains: stock vs the 4-D hand-off (first conv's explicit n: the first identical one) cref, tc_ref = timed(lambda: run(c2, run(c1, xt, h, w), oh, ow), "chain_stock") print(f" chain stock {tc_ref:.3f} ms", flush=True) for n in ok_n[:3]: def chain_t4(n=n): y = t4d(run(c1, xt, h, w, "row_major", ("height", n)), oh, ow, cout) z = run(c2, y, oh, ow) ttnn.deallocate(y) return z out, t = timed(chain_t4, f"chain_h{n}") report(f"chain_h{n}", out, t, cref, tc_ref) for c in (c1, c2): c.release() ttnn.deallocate(x4, False) ttnn.deallocate(xt) ttnn.close_device(dev) print("RESULT", "PASS" if bad == 0 else f"DIFFS ({bad})") return 0 if __name__ == "__main__": sys.exit(main())