meteor-p150 / code /scripts /wpass_probe.py
changh95's picture
tt-model push meteor-p150 (container)
8eeb550 verified
Raw History Blame Contribute Delete
4.78 kB
#!/usr/bin/env python3
"""R6.3 probe: Resize2d's batched W-pass matmul at C % 32 != 0 (``[1, B, C, W] x [W, W']``) on the whole grid.
ttnn places the batched fp32 matmul with a broadcast ``[W, W']`` on few cores (seg_refine's 48-channel resize:
16 cores, 2.9 ms; the 144-channel one: 20 cores). Explicit program configs that fuse the batch into M (``fuse_batch``:
the padded per-batch tile rows) spread it over the device grid. Each config is compared bit for bit with the stock
call and timed as a traced replay (p50 of ``--reps``).
METEOR_DEVICE_OK=1 bin/devrun -t 600 -- python -u code/scripts/wpass_probe.py --shapes 4,48,250,500
"""
from __future__ import annotations
import argparse
import math
import sys
import time
import numpy as np
def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("--shapes", default="4,48,250,500", help="B,C,W,W2[;...] (METEOR: 400,48,250,500;100,144,63,125)")
ap.add_argument("--reps", type=int, default=10)
a = ap.parse_args()
import torch
import ttnn
from tt_meteor.ttaw.device import open_device
from tt_meteor.ttaw.precision import Precision
dev = open_device(dispatch="eth", trace_region_size=64 << 20)
cfg = Precision.parse("accurate").compute_kernel_config()
g = dev.compute_with_storage_grid_size()
gx, gy = int(g.x), int(g.y)
rng = np.random.default_rng(0)
def timed(fn):
try:
out = fn()
except RuntimeError as e:
return None, float("nan"), str(e).splitlines()[0][:100]
ttnn.deallocate(out)
out = fn()
res = ttnn.to_torch(out).float().numpy()
ttnn.deallocate(out)
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 = ttnn.to_torch(tout).float().numpy()
ttnn.release_trace(dev, tid)
ttnn.deallocate(tout)
return res, float(np.median(ts)), "" if np.array_equal(res, tres) else "trace != eager"
bad = 0
for spec in a.shapes.split(";"):
b, c, w, w2 = (int(v) for v in spec.split(","))
x = ttnn.from_torch(torch.from_numpy(rng.standard_normal((1, b, c, w)).astype(np.float32)),
dtype=ttnn.float32, layout=ttnn.TILE_LAYOUT, device=dev)
m = ttnn.from_torch(torch.from_numpy(rng.random((w, w2)).astype(np.float32)), dtype=ttnn.float32,
layout=ttnn.TILE_LAYOUT, device=dev)
mt = b * math.ceil(c / 32)
kt, nt = math.ceil(w / 32), math.ceil(w2 / 32)
ref, t_ref, _ = timed(lambda: ttnn.matmul(x, m, compute_kernel_config=cfg))
print(f"[B{b} C{c} {w}->{w2}] Mt {mt} Kt {kt} Nt {nt}: stock {t_ref:.3f} ms", flush=True)
variants = []
for k in sorted({1, 2, 4, kt} | ({kt // 2} if kt % 2 == 0 else set())):
if kt % k:
continue
ncores = gx * gy
pm = math.ceil(mt / ncores)
sw = max(s for s in (1, 2, 4, 8) if nt % s == 0 and s <= 4)
variants.append((f"1d k{k}", ttnn.MatmulMultiCoreReuseMultiCast1DProgramConfig(
compute_with_storage_grid_size=ttnn.CoreCoord(gx, gy), in0_block_w=k, out_subblock_h=1,
out_subblock_w=sw if nt % sw == 0 else 1, per_core_M=pm, per_core_N=nt, fuse_batch=True,
fused_activation=None, mcast_in0=False)))
pm2, pn2 = math.ceil(mt / gy), math.ceil(nt / gx)
sw2 = max(s for s in (1, 2, 4) if pn2 % s == 0)
variants.append((f"2d k{k}", ttnn.MatmulMultiCoreReuseMultiCastProgramConfig(
compute_with_storage_grid_size=ttnn.CoreCoord(gx, gy), in0_block_w=k, out_subblock_h=1,
out_subblock_w=sw2, per_core_M=pm2, per_core_N=pn2, transpose_mcast=False, fused_activation=None,
fuse_batch=True)))
for name, pc in variants:
out, t, msg = timed(lambda: ttnn.matmul(x, m, compute_kernel_config=cfg, program_config=pc))
if out is None:
print(f" {name:8s} rejected ({msg})", flush=True)
continue
same = np.array_equal(out, ref)
d = float(np.max(np.abs(out.astype(np.float64) - ref))) if not same else 0.0
print(f" {name:8s} {t:7.3f} ms ({t - t_ref:+.3f}) {'IDENTICAL' if same else f'DIFFERENT max|d| {d:.3g}'} "
f"{msg}", flush=True)
ttnn.deallocate(x)
ttnn.deallocate(m)
ttnn.close_device(dev)
print("RESULT done")
return 0
if __name__ == "__main__":
sys.exit(main())