#!/usr/bin/env python3 """OPT2 MK4 follow-up probe (stock ops only, OPT_PLAN A7): a full-resolution ConvBlock (3x3 conv + ReLU twice, bf16 weights at HiFi2 as the ``fast`` profile's BEV trunk) run as row bands whose two convs take ttnn's L1 path (``Conv2dL1FullSliceConfig``) instead of two DRAM-sliced convs (each with its PaddedSlice / Halo / Move / Untilize / SliceWrite glue per slice). A band [r0, r1) slices input rows [r0 - 2, r1 + 2) (the two convs' halo), runs both convs, keeps output rows [r0, r1) and the bands are concatenated. Prints traced times and the output difference against the DRAM-sliced chain. METEOR_DEVICE_OK=1 bin/devrun -t 900 -- python -u code/scripts/bandchain_probe.py --bands 4,5,8 """ from __future__ import annotations import argparse import sys import time import numpy as np FAST = "HiFi2+fp32+l1acc:w=bfloat16" def main() -> int: ap = argparse.ArgumentParser() ap.add_argument("--hw", default="800,500") ap.add_argument("--ch", default="96,96,96", help="Cin, Cmid, Cout") ap.add_argument("--bands", default="4,5,8") ap.add_argument("--reps", type=int, default=10) ap.add_argument("--layout", default="rm", choices=("rm", "t4"), help="input layout of the map") a = ap.parse_args() h, w = (int(v) for v in a.hw.split(",")) c0, c1, c2 = (int(v) for v in a.ch.split(",")) import torch import ttnn 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=128 << 20) rng = np.random.default_rng(0) x = rng.standard_normal((1, h, w, c0)).astype(np.float32) wa = (rng.standard_normal((c1, c0, 3, 3)) / np.sqrt(9 * c0)).astype(np.float32) wb = (rng.standard_normal((c2, c1, 3, 3)) / np.sqrt(9 * c1)).astype(np.float32) ba = (rng.standard_normal(c1) * 0.3).astype(np.float32) bb = (rng.standard_normal(c2) * 0.3).astype(np.float32) lay = ttnn.ROW_MAJOR_LAYOUT if a.layout == "rm" else ttnn.TILE_LAYOUT xd = ttnn.from_torch(torch.from_numpy(x).to(torch.bfloat16), dtype=ttnn.bfloat16, layout=lay, device=dev, memory_config=ttnn.DRAM_MEMORY_CONFIG) cfg = {"config_tensors_in_dram": True} def mk(wt, bt, slicing, out_layout): return Conv2d(wt, bt, stride=1, padding=1, activation="relu", precision=FAST, output_dtype="bfloat16", output_layout=out_layout, slicing=slicing, conv_config=cfg, name="c") sa, sb = mk(wa, ba, "auto", "row_major"), mk(wb, bb, "auto", "row_major") def stock(): ya = sa(FeatureMap(xd, 1, h, w, c0)) yb = sb(ya) ttnn.deallocate(ya.tensor) return yb.tensor la, lb = mk(wa, ba, "l1", "tile"), mk(wb, bb, "l1", "tile") def banded(nb): br = -(-h // nb) parts = [] for k in range(nb): r0, r1 = k * br, min(h, k * br + br) if r0 >= r1: break lo, hi = max(0, r0 - 2), min(h, r1 + 2) xb = ttnn.slice(xd, [0, lo, 0, 0], [1, hi, w, c0], memory_config=ttnn.DRAM_MEMORY_CONFIG) ya = la(FeatureMap(xb, 1, hi - lo, w, c0)) ttnn.deallocate(xb) yb = lb(ya) ttnn.deallocate(ya.tensor) t = yb.tensor if t.memory_config().buffer_type != ttnn.BufferType.DRAM or t.is_sharded(): t2 = ttnn.to_memory_config(t, ttnn.DRAM_MEMORY_CONFIG) ttnn.deallocate(t) t = t2 keep = ttnn.slice(t, [0, 0, (r0 - lo) * w, 0], [1, 1, (r0 - lo + r1 - r0) * w, c2], memory_config=ttnn.DRAM_MEMORY_CONFIG) ttnn.deallocate(t) parts.append(keep) out = ttnn.concat(parts, dim=2, memory_config=ttnn.DRAM_MEMORY_CONFIG) for p in parts: ttnn.deallocate(p) return out def run(fn): o = fn() r = ttnn.to_torch(o).float().numpy().reshape(h, w, c2) ttnn.deallocate(o) return r def timed(fn): fn_out = fn() ttnn.deallocate(fn_out) tid = ttnn.begin_trace_capture(dev, cq_id=0) o = 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) r = ttnn.to_torch(o).float().numpy().reshape(h, w, c2) ttnn.release_trace(dev, tid) ttnn.deallocate(o) return r, float(np.median(ts)) ref = run(stock) rs, ts = timed(stock) print(f"stock DRAM-sliced chain [{h}x{w} {c0}->{c1}->{c2}, {a.layout} input]: traced {ts:.3f} ms, " f"traced == eager {np.array_equal(rs, ref)}", flush=True) for nb in (int(v) for v in a.bands.split(",")): try: y = run(lambda: banded(nb)) except RuntimeError as e: print(f"bands {nb}: FAILED to run ({str(e).splitlines()[0][:200]})", flush=True) continue d = np.abs(y - ref) _, tb = timed(lambda: banded(nb)) print(f"bands {nb}: traced {tb:.3f} ms (stock {ts:.3f}); vs stock: identical {np.array_equal(y, ref)}, " f"max|d| {float(d.max()):.4g}, mismatches {int(np.count_nonzero(d))}", flush=True) ttnn.close_device(dev) return 0 if __name__ == "__main__": sys.exit(main())