meteor-p150 / code /scripts /tgate_probe.py
changh95's picture
tt-model push meteor-p150 (container)
e91e989 verified
Raw History Blame Contribute Delete
6.05 kB
#!/usr/bin/env python3
"""TGATE bring-up probe (OPT2 round 3 R3.2; hang protocol: smallest shape first, eager x2, then a 2-call trace).
Stock (``bev.fuse``): the merged 1x1 conv (tfuse.0 rows, 4 gate logits; fp32 out) -> slice t, slice logits, softmax,
slice, x SCALE, t * gate, + b_t, ReLU, typecast bf16. Kernel: the same conv with the gate rows as logit differences
(``tgate.diff_weights``) -> ``tgate.fuse``. Both against a float64 host reference; eager x2; trace x2; the glue of
each timed as traced replays (the conv excluded).
METEOR_DEVICE_OK=1 bin/devrun -t 300 -- python -u code/scripts/tgate_probe.py --rows 64
METEOR_DEVICE_OK=1 bin/devrun -t 600 -- python -u code/scripts/tgate_probe.py --rows 400000 --trace
"""
from __future__ import annotations
import argparse
import os
import sys
import time
import numpy as np
PORT_PRECISION = "HiFi4+fp32+l1acc:w=fp32"
SCALE = 4.0
def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("--rows", type=int, default=64)
ap.add_argument("--trace", action="store_true")
ap.add_argument("--reps", type=int, default=10)
ap.add_argument("--logit-scale", type=float, default=1.0, help="spread of the gate logits")
a = ap.parse_args()
import torch
import ttnn
from tt_meteor.tt import tgate
from tt_meteor.tt.layers import CONV_CONFIG, mm_config, slice_cols
from tt_meteor.ttaw.device import open_device
from tt_meteor.ttaw.ops.conv import Conv2d, FeatureMap
r = a.rows
dev = open_device(dispatch="eth", trace_region_size=64 << 20)
rng = np.random.default_rng(0)
x = rng.standard_normal((r, 96)).astype(np.float32)
x = torch.from_numpy(x).bfloat16().float().numpy() # bf16 values (the raw map)
w = (rng.standard_normal((100, 96)) * 0.1).astype(np.float32)
w[96:] *= a.logit_scale
b = np.concatenate([np.zeros(96), rng.standard_normal(4) * a.logit_scale]).astype(np.float32)
bt = (rng.standard_normal(96) * 0.2).astype(np.float32)
wd, bd = tgate.diff_weights(w.reshape(100, 96, 1, 1), b)
# float64 reference
g64 = x.astype(np.float64) @ w.T.astype(np.float64) + b
lg = g64[:, 96:]
sm = np.exp(lg - lg.max(1, keepdims=True))
gate = sm[:, :1] / sm.sum(1, keepdims=True) * SCALE
ref = np.maximum(g64[:, :96] * gate + bt, 0.0)
xt = ttnn.from_torch(torch.from_numpy(x.reshape(1, 1, r, 96)), dtype=ttnn.bfloat16, layout=ttnn.TILE_LAYOUT,
device=dev, memory_config=ttnn.DRAM_MEMORY_CONFIG)
fm = FeatureMap(xt, 1, r // 32, 32, 96)
kw = dict(precision=PORT_PRECISION, output_dtype="float32", conv_config=CONV_CONFIG, padding=0)
c_stock = Conv2d(w.reshape(100, 96, 1, 1), b, name="tgate", **kw)
c_diff = Conv2d(wd, bd, name="tgate.diff", **kw)
btd = ttnn.from_torch(torch.from_numpy(bt.reshape(1, 1, 1, 96)), dtype=ttnn.float32, layout=ttnn.TILE_LAYOUT,
device=dev)
ones = ttnn.from_torch(torch.from_numpy(tgate.ones_tile()), dtype=ttnn.float32, layout=ttnn.TILE_LAYOUT,
device=dev)
bias = ttnn.from_torch(torch.from_numpy(tgate.bias_tiles(bt)), dtype=ttnn.float32, layout=ttnn.TILE_LAYOUT,
device=dev)
bad = 0
def host(t):
y = ttnn.to_torch(t)
return y.float().numpy().reshape(r, -1)
def stock_glue(g):
t = slice_cols(g, 0, 96)
logits = slice_cols(g, 96, 100)
smx = ttnn.softmax(logits, dim=-1, numeric_stable=True, compute_kernel_config=mm_config())
gt = ttnn.multiply(slice_cols(smx, 0, 1), SCALE)
t0 = ttnn.relu(ttnn.add(ttnn.multiply(t, gt), btd))
return ttnn.typecast(t0, ttnn.bfloat16)
g = c_stock(fm).tensor
gd = c_diff(fm).tensor
print(f"[{r}] conv outputs {list(g.shape)} / {list(gd.shape)} padded {list(gd.padded_shape)}; "
f"supported {tgate.supported(gd)}", flush=True)
ys = host(stock_glue(g))
yk_t = tgate.fuse(gd, ones, bias, SCALE)
yk = host(yk_t)
es, ek = np.abs(ys - ref).max(), np.abs(yk - ref).max()
rel = np.abs(yk - ref) / np.maximum(np.abs(ref), 1e-3)
print(f" max|err| vs float64: stock {es:.4g}, kernel {ek:.4g} (max|ref| {np.abs(ref).max():.4g}); kernel max rel "
f"{rel[np.abs(ref) > 1e-2].max():.4g}; stock == kernel {np.mean(ys == yk):.4f}; finite "
f"{np.isfinite(yk).all()}", flush=True)
ok = np.isfinite(yk).all() and ek <= max(1.5 * es, 1e-6)
if not ok and os.environ.get("TGATE_DUMP"):
np.savez(os.environ["TGATE_DUMP"], ys=ys, yk=yk, ref=ref, g64=g64, bt=bt, gd=host(gd), g=host(g))
bad += 0 if ok else 1
print(f" kernel precision vs stock: {'OK' if ok else 'WORSE'}", flush=True)
yk2 = host(tgate.fuse(gd, ones, bias, SCALE))
ok2 = np.array_equal(yk, yk2)
bad += 0 if ok2 else 1
print(f" kernel eager x2: {'stable' if ok2 else 'UNSTABLE'}", flush=True)
if a.trace:
for name, fn, src, want in (("stock", stock_glue, g, ys),
("kernel", lambda t: tgate.fuse(t, ones, bias, SCALE), gd, yk)):
ttnn.deallocate(fn(src))
tid = ttnn.begin_trace_capture(dev, cq_id=0)
y = fn(src)
ttnn.end_trace_capture(dev, tid, cq_id=0)
ts = []
for i in range(max(2, a.reps)):
t0 = time.perf_counter()
ttnn.execute_trace(dev, tid, cq_id=0, blocking=True)
ts.append((time.perf_counter() - t0) * 1e3)
if i < 2:
okt = np.array_equal(host(y), want)
bad += 0 if okt else 1
print(f" {name} trace call {i + 1}: {'IDENTICAL' if okt else 'DIFFERENT'}", flush=True)
ttnn.release_trace(dev, tid)
print(f" {name} glue traced replay p50 {np.median(ts):.3f} ms (min {np.min(ts):.3f})", flush=True)
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())