#!/usr/bin/env python3 # SPDX-License-Identifier: Apache-2.0 """Conv placement / blocking configs at METEOR 2's real conv shapes (bin/devrun). Each (shape, config) runs in its own process (a failed L1 attempt can leave L1 fragmented), traced, random weights; reports the replay time and the PCC against torch. bin/devrun python scripts/dev_bench_conv.py # the whole table -> /logs/bench_conv.jsonl bin/devrun python scripts/dev_bench_conv.py --one SHAPE CFG # one case (what the driver spawns) """ import argparse import json import os import subprocess import sys import time import numpy as np # name: (N, H, W, Cin, Cout, k, stride, dilation) SHAPES = { "bev64": (1, 400, 250, 64, 64, 3, 1, 1), "bev96": (1, 400, 250, 96, 96, 3, 1, 1), "bev64to96": (1, 400, 250, 64, 96, 3, 1, 1), "bev96to208": (1, 400, 250, 96, 208, 3, 1, 1), "bev48": (1, 400, 250, 48, 48, 3, 1, 1), "b1_128": (1, 200, 125, 128, 128, 3, 1, 1), "b1_128d4": (1, 200, 125, 128, 128, 3, 1, 4), "b1_s2": (1, 400, 250, 64, 128, 3, 2, 1), "lane32to48": (1, 800, 500, 32, 48, 3, 1, 1), "lane48to32": (1, 800, 500, 48, 32, 3, 1, 1), "lane32d2": (1, 800, 500, 32, 32, 3, 1, 2), "occ96to128": (1, 200, 200, 96, 128, 3, 1, 1), "occ128": (1, 200, 200, 128, 128, 3, 1, 1), "img128": (8, 162, 288, 128, 128, 3, 1, 1), "img128to192": (8, 162, 288, 128, 192, 3, 1, 1), "img96": (8, 162, 288, 96, 96, 3, 1, 1), "img64": (8, 162, 288, 64, 64, 3, 1, 1), "l2_128": (8, 81, 144, 128, 128, 3, 1, 1), "l3_256": (8, 41, 72, 256, 256, 3, 1, 1), "l4_512": (8, 21, 36, 512, 512, 3, 1, 1), "stem_s2d": (8, 327, 579, 12, 64, 4, 1, 1), } # name: dict of Conv2d kwargs (slicing) + conv_config fields CONFIGS = { "dram": {}, "dram_hs": {"conv_config": {"shard_layout": "HEIGHT_SHARDED"}}, "dram_bs": {"conv_config": {"shard_layout": "BLOCK_SHARDED"}}, "l1": {"slicing": "l1"}, "l1_abh32": {"slicing": "l1", "conv_config": {"act_block_h_override": 32}}, "l1_hs_abh64": {"slicing": "l1", "conv_config": {"shard_layout": "HEIGHT_SHARDED", "act_block_h_override": 64}}, "l1_bs": {"slicing": "l1", "conv_config": {"shard_layout": "BLOCK_SHARDED"}}, "dram_h8": {"slicing": ("height", 8)}, "dram_h16": {"slicing": ("height", 16)}, "dram_h32": {"slicing": ("height", 32)}, "dram_w8": {"slicing": ("width", 8)}, "dram_hs_abh64": {"conv_config": {"shard_layout": "HEIGHT_SHARDED", "act_block_h_override": 64}}, "dram_hs_abh128": {"conv_config": {"shard_layout": "HEIGHT_SHARDED", "act_block_h_override": 128}}, "dram_hs_abh256": {"conv_config": {"shard_layout": "HEIGHT_SHARDED", "act_block_h_override": 256}}, } def one(shape_name: str, cfg_name: str) -> dict: import torch import ttnn sys.path.insert(0, "/work") from tt_meteor2.ttaw.device import close_device, open_device from tt_meteor2.ttaw.metrics import pcc from tt_meteor2.ttaw.ops.conv import Conv2d, FeatureMap, fmap_from_numpy, fmap_to_numpy n, h, w, ci, co, k, s, d = SHAPES[shape_name] cfg = dict(CONFIGS[cfg_name]) cc = dict(cfg.pop("conv_config", {})) if "shard_layout" in cc: cc["shard_layout"] = getattr(ttnn.TensorMemoryLayout, cc["shard_layout"]) rng = np.random.default_rng(0) x = rng.standard_normal((n, ci, h, w)).astype(np.float32) wt = (rng.standard_normal((co, ci, k, k)) / np.sqrt(ci * k * k)).astype(np.float32) b = rng.standard_normal(co).astype(np.float32) * 0.1 pad = 0 if k % 2 == 0 else d * (k // 2) dev = open_device(0, dispatch="eth", l1_small_size=32768, trace_region_size=64 << 20) res = {"shape": shape_name, "config": cfg_name} try: fm = fmap_from_numpy(x, dev) conv = Conv2d(wt, b, stride=s, padding=pad, dilation=d, activation="relu", conv_config=cc or None, **cfg) out = conv(fm) ttnn.synchronize_device(dev) got = fmap_to_numpy(out) ttnn.deallocate(out.tensor) tid = ttnn.begin_trace_capture(dev, cq_id=0) out = conv(fm) ttnn.end_trace_capture(dev, tid, cq_id=0) ts = [] for _ in range(7): t = time.perf_counter() ttnn.execute_trace(dev, tid, cq_id=0, blocking=False) ttnn.synchronize_device(dev) ts.append((time.perf_counter() - t) * 1e3) ttnn.release_trace(dev, tid) ref = torch.relu(torch.nn.functional.conv2d(torch.from_numpy(x), torch.from_numpy(wt), torch.from_numpy(b), stride=s, padding=pad, dilation=d)).numpy() res.update(ms=float(np.median(ts)), pcc=float(pcc(got, ref)), ok=True) except Exception as e: # noqa: BLE001 res.update(ok=False, error=f"{type(e).__name__}: {str(e).splitlines()[0][:160]}") finally: close_device(dev) return res def main(): ap = argparse.ArgumentParser() ap.add_argument("--one", nargs=2) ap.add_argument("--shapes", nargs="*", default=list(SHAPES)) ap.add_argument("--configs", nargs="*", default=list(CONFIGS)) ap.add_argument("--out", default="/logs/bench_conv.jsonl") a = ap.parse_args() if a.one: print("RESULT " + json.dumps(one(*a.one)), flush=True) return with open(a.out, "a") as f: for sh in a.shapes: for cf in a.configs: p = subprocess.run([sys.executable, os.path.abspath(__file__), "--one", sh, cf], capture_output=True, text=True, timeout=600) line = [l for l in p.stdout.splitlines() if l.startswith("RESULT ")] r = json.loads(line[-1][7:]) if line else {"shape": sh, "config": cf, "ok": False, "error": f"exit {p.returncode}: {p.stderr[-200:]}"} f.write(json.dumps(r) + "\n") f.flush() print(f"{sh:12s} {cf:12s} " + (f"{r['ms']:7.3f} ms pcc {r['pcc']:.6f}" if r.get("ok") else f"FAILED {r.get('error', '')[:110]}"), flush=True) if __name__ == "__main__": main()