# SPDX-License-Identifier: Apache-2.0 """Feasibility bench on the p150: the BEVFormer port's fused MSDA kernel (``msda_k``) and the linears at AutoE2E's BEV encoder sizes (bin/devrun; the BEVFormer p150 package code at /bev). bin/devrun python -m tt_autoe2e.tests.dev_msda_bench [--out /logs/bench/msda.json] AutoE2E per encoder layer and BEV frame (recon.md section 6): 60,000 BEV queries (300 x 200), 8 heads of 32 channels; SCA = 6 cameras x 4 FPN levels (64^2, 32^2, 16^2, 8^2 for the 512 px views) x 8 points over the rebatched rows (the camera-visible queries; measured 24.7 % of 6 x 60,000 on the golden sample, front camera 49 %); TSA = 8 points (2 queues x 4) on the 300 x 200 BEV itself. Random positions inside the map (a pessimistic access pattern: the real offsets are small around each reference point) and random softmax weights; only the time is measured here. """ from __future__ import annotations import argparse import json import time import numpy as np def _timed(fn, dev, reps): import ttnn out = fn() # compile + first run ttnn.synchronize_device(dev) ttnn.deallocate(out) ts = [] for _ in range(reps): t = time.perf_counter() out = fn() ttnn.synchronize_device(dev) ts.append(time.perf_counter() - t) ttnn.deallocate(out) return float(np.median(ts)) * 1e3 def msda_case(dev, *, maps, hw, sub, rows, points=8, heads=8, reps=5, seed=0): import torch import ttnn from tt_bevformer.tt.msda_k import msda_kernel rng = np.random.default_rng(seed) h, w = hw value = ttnn.from_torch(torch.from_numpy(rng.standard_normal((maps, h, w, 32), dtype=np.float32)), dtype=ttnn.bfloat16, layout=ttnn.ROW_MAJOR_LAYOUT, device=dev, memory_config=ttnn.L1_MEMORY_CONFIG) loc = np.zeros((1, heads, rows, 32), np.int32) px = rng.uniform(-0.5, w - 0.5, size=(1, heads, rows, points)) py = rng.uniform(-0.5, h - 0.5, size=(1, heads, rows, points)) loc[..., 0:2 * points:2] = np.round(px * 65536).astype(np.int32) loc[..., 1:2 * points:2] = np.round(py * 65536).astype(np.int32) att = np.zeros((1, heads, rows, 32), np.float32) a = rng.uniform(0.0, 1.0, size=(1, heads, rows, points)).astype(np.float32) att[..., :points] = a / a.sum(-1, keepdims=True) loc_t = ttnn.from_torch(torch.from_numpy(loc), dtype=ttnn.int32, layout=ttnn.TILE_LAYOUT, device=dev, memory_config=ttnn.DRAM_MEMORY_CONFIG) att_t = ttnn.from_torch(torch.from_numpy(att), dtype=ttnn.float32, layout=ttnn.TILE_LAYOUT, device=dev, memory_config=ttnn.DRAM_MEMORY_CONFIG) ms = _timed(lambda: msda_kernel(value, loc_t, att_t, sub=sub, points=points, nq=rows), dev, reps) for t in (value, loc_t, att_t): ttnn.deallocate(t) return {"maps": maps, "hw": list(hw), "sub": sub, "rows": rows, "points": points, "ms": ms, "ns_per_point": ms * 1e6 / (rows * heads * points)} def linear_case(dev, *, rows, k, n, fidelity="HiFi2", dtype="bfloat16", reps=5): import torch import ttnn x = ttnn.from_torch(torch.randn(1, 1, rows, k), dtype=ttnn.bfloat16, layout=ttnn.TILE_LAYOUT, device=dev) wd = getattr(ttnn, dtype) wt = ttnn.from_torch(torch.randn(k, n) * 0.05, dtype=wd, layout=ttnn.TILE_LAYOUT, device=dev) b = ttnn.from_torch(torch.randn(1, n) * 0.05, dtype=wd, layout=ttnn.TILE_LAYOUT, device=dev) cfg = ttnn.init_device_compute_kernel_config(dev.arch(), math_fidelity=getattr(ttnn.MathFidelity, fidelity), math_approx_mode=False, fp32_dest_acc_en=True, packer_l1_acc=True) g = dev.compute_with_storage_grid_size() ms = _timed(lambda: ttnn.linear(x, wt, bias=b, compute_kernel_config=cfg, core_grid=ttnn.CoreGrid(y=g.y, x=g.x)), dev, reps) for t in (x, wt, b): ttnn.deallocate(t) return {"rows": rows, "k": k, "n": n, "fidelity": fidelity, "weights": dtype, "ms": ms, "tflops": 2 * rows * k * n / (ms * 1e-3) / 1e12} def main(argv=None) -> int: ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) ap.add_argument("--out", default="/logs/bench/msda.json") ap.add_argument("--reps", type=int, default=5) args = ap.parse_args(argv) from tt_bevformer.device import close_device, describe_device, open_device dev = open_device(trace_region_size=32 << 20) res = {"device": describe_device(dev), "sca": [], "tsa": [], "linear": []} try: # SCA: 48 value maps (8 heads x 6 cameras, n = head * 6 + camera), rows = 6 cameras x CAP for cap in (7680, 15360): for hw in ((64, 64), (32, 32), (16, 16), (8, 8)): r = msda_case(dev, maps=48, hw=hw, sub=6, rows=6 * cap, reps=args.reps) res["sca"].append(r) print("sca", r, flush=True) # TSA: 8 value maps (one per head) of the 300 x 200 BEV, 60,000 rows (+ pad to a multiple of 32) for rows in (30016, 60000): r = msda_case(dev, maps=8, hw=(300, 200), sub=1, rows=rows, reps=args.reps) res["tsa"].append(r) print("tsa", r, flush=True) # the per-layer linears on 60,000 rows: SCA offsets + weights (256 -> 512 + 256), TSA (512 -> 128 + 64), # value / output projections (256 -> 256), FFN (256 -> 512 -> 256) for k, n in ((256, 768), (512, 192), (256, 256), (256, 512), (512, 256)): for fid in ("HiFi2", "HiFi4"): r = linear_case(dev, rows=60000, k=k, n=n, fidelity=fid, reps=args.reps) res["linear"].append(r) print("linear", r, flush=True) finally: close_device(dev) import os os.makedirs(os.path.dirname(args.out), exist_ok=True) with open(args.out, "w") as f: json.dump(res, f, indent=1) print("wrote", args.out) return 0 if __name__ == "__main__": raise SystemExit(main())