meteor-p150 / code /scripts /rm_handoff_probe.py
changh95's picture
tt-model push meteor-p150 (container)
8eeb550 verified
Raw History Blame Contribute Delete
6.51 kB
#!/usr/bin/env python3
"""CONV_RM bring-up probe (OPT_PLAN #1 (a), round 3): ROW_MAJOR 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 ``[N, H, W, C]`` output
back to flat. In TILE layout at widths that are not multiples of 32 both reshapes are real copies (ReshapeView); in
ROW_MAJOR they are views. Per shape, every variant is compared bit for bit with the stock TILE path and timed as a
traced replay (device time of one call, p50 over ``--reps`` replays):
- ``stock`` : TILE flat in -> conv -> TILE flat out (two ReshapeView copies inside the op);
- ``rm_in`` : untilize the input (one program), conv on the ROW_MAJOR input -> TILE out;
- ``rm_io`` : ROW_MAJOR in -> conv with ``output_layout=ROW_MAJOR`` -> ROW_MAJOR flat out (both reshapes views);
- ``rm_iot`` : ``rm_io`` + a tilize of the output (the hand-off to a TILE consumer).
- ``chain`` : two convs, stock vs ROW_MAJOR hand-off between them (``rm_io`` then a ROW_MAJOR-input conv).
METEOR_DEVICE_OK=1 bin/devrun -t 600 -- python -u code/scripts/rm_handoff_probe.py --shapes 64,48,32,32
"""
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",
help="H,W,Cin,Cout[;H,W,Cin,Cout ...] (BEV: 800,500,96,96;800,500,96,64;400,250,192,192)")
ap.add_argument("--reps", type=int, default=10)
ap.add_argument("--dtype", default="bfloat16", help="output dtype of the probed convs")
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):
out = fn() # eager x2 (compile, then the cached programs)
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")
return res, float(np.median(ts))
for spec in a.shapes.split(";"):
h, w, cin, cout = (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)
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=a.dtype, conv_config=CONV_CONFIG)
c1 = Conv2d(wts, b, name="c1", **kw)
c2 = Conv2d(wts2, b, name="c2", **dict(kw, output_dtype="bfloat16"))
fm = FeatureMap(xt, 1, h, w, cin)
def run(conv, f, out_layout):
conv.output_layout = out_layout
return conv(f).tensor
def stock():
return run(c1, fm, "tile")
def rm_in():
r = ttnn.to_layout(xt, ttnn.ROW_MAJOR_LAYOUT)
y = run(c1, fm.with_tensor(r), "tile")
ttnn.deallocate(r)
return y
def rm_io():
r = ttnn.to_layout(xt, ttnn.ROW_MAJOR_LAYOUT)
y = run(c1, fm.with_tensor(r), "row_major")
ttnn.deallocate(r)
return y
def rm_iot():
y = rm_io()
t = ttnn.to_layout(y, ttnn.TILE_LAYOUT)
ttnn.deallocate(y, False)
return t
def rm_out():
return run(c1, fm, "row_major")
def rm_outt():
y = rm_out()
t = ttnn.to_layout(y, ttnn.TILE_LAYOUT)
ttnn.deallocate(y, False)
return t
def chain_stock():
y = c1(fm)
c1.output_layout = "tile"
z = run(c2, y, "tile")
ttnn.deallocate(y.tensor)
return z
def chain_rm():
r = ttnn.to_layout(xt, ttnn.ROW_MAJOR_LAYOUT)
y = FeatureMap(run(c1, fm.with_tensor(r), "row_major"), 1, h, w, cout)
ttnn.deallocate(r)
z = run(c2, y, "tile")
ttnn.deallocate(y.tensor)
return z
ref, t_ref = timed(stock, "stock")
print(f"[{h}x{w} {cin}->{cout}] stock {t_ref:.3f} ms", flush=True)
for name, fn in (("rm_in", rm_in), ("rm_io", rm_io), ("rm_iot", rm_iot), ("rm_out", rm_out),
("rm_outt", rm_outt)):
out, t = timed(fn, name)
same = np.array_equal(out[: ref.shape[0]], ref)
bad += 0 if same else 1
print(f" {name:7s} {t:8.3f} ms ({t - t_ref:+.3f}) {'IDENTICAL' if same else 'DIFFERENT'}",
flush=True)
if a.dtype == "bfloat16":
cref, tc_ref = timed(chain_stock, "chain_stock")
cout_, tc = timed(chain_rm, "chain_rm")
same = np.array_equal(cout_, cref)
bad += 0 if same else 1
print(f" chain stock {tc_ref:.3f} ms rm {tc:.3f} ms ({tc - tc_ref:+.3f}) "
f"{'IDENTICAL' if same else 'DIFFERENT'}", flush=True)
for c in (c1, c2):
c.release()
ttnn.deallocate(xt)
ttnn.close_device(dev)
print("RESULT", "PASS" if bad == 0 else f"FAIL ({bad})")
return 0 if bad == 0 else 1
if __name__ == "__main__":
sys.exit(main())