meteor-p150 / code /scripts /attn_in_probe.py
changh95's picture
tt-model push meteor-p150 (container)
e91e989 verified
Raw History Blame Contribute Delete
3.95 kB
#!/usr/bin/env python3
"""ATTN_IN probe (OPT2 round 6 R6.2): the attention pools' W-pool matmul on the bf16 transposed map directly
(``bf16``: in0 bf16, in1 the fp32 pool matrix, fp32 output) instead of a typecast of the whole map to fp32 first
(``fp32``, 645 us for the ego pool's [800, 96, 500] map). bf16 values are exact in fp32 and in the FPU's TF32 source
format, so the products and the fp32 accumulation should be the same: checked bit-identical, then both timed traced.
METEOR_DEVICE_OK=1 bin/devrun -t 300 -- python -u code/scripts/attn_in_probe.py --shape 1,4,40,96
METEOR_DEVICE_OK=1 bin/devrun -t 600 -- python -u code/scripts/attn_in_probe.py --shape 1,800,500,96 --trace
"""
from __future__ import annotations
import argparse
import sys
import time
import numpy as np
def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("--shape", default="1,4,40,96")
ap.add_argument("--trace", action="store_true")
ap.add_argument("--reps", type=int, default=10)
a = ap.parse_args()
import torch
import ttnn
from tt_meteor.tt.layers import mm_config
from tt_meteor.ttaw.device import open_device
_, h, w, c = (int(v) for v in a.shape.split(","))
dev = open_device(dispatch="eth", trace_region_size=64 << 20)
rng = np.random.default_rng(0)
x = torch.from_numpy(rng.standard_normal((1, h, w, c)).astype(np.float32)).to(torch.bfloat16)
pw = rng.random((w, 16)).astype(np.float32)
pw /= pw.sum(0, keepdims=True)
x4 = ttnn.from_torch(x, dtype=ttnn.bfloat16, layout=ttnn.TILE_LAYOUT, device=dev,
memory_config=ttnn.DRAM_MEMORY_CONFIG)
pwd = ttnn.from_torch(torch.from_numpy(pw), dtype=ttnn.float32, layout=ttnn.TILE_LAYOUT, device=dev,
memory_config=ttnn.DRAM_MEMORY_CONFIG)
cfg = mm_config()
def run(mode):
xt = ttnn.transpose(x4, -2, -1)
if mode == "fp32":
x32 = ttnn.typecast(xt, ttnn.float32)
ttnn.deallocate(xt)
xt = x32
y = ttnn.matmul(ttnn.reshape(xt, (1, 1, h * c, w)), pwd, compute_kernel_config=cfg, dtype=ttnn.float32)
ttnn.deallocate(xt)
return y
bad = 0
got = {}
for m in ("fp32", "bf16"):
y = run(m)
got[m] = ttnn.to_torch(y).float().numpy()
print(f" {m}: out {list(y.shape)} {y.dtype}", flush=True)
ttnn.deallocate(y)
ref = np.einsum("hwc,wj->hcj", x.float().numpy()[0].astype(np.float64), pw.astype(np.float64)).reshape(h * c, 16)
for m in got:
print(f" {m} max|err| vs float64 {np.abs(got[m].reshape(h * c, 16) - ref).max():.3g}", flush=True)
same = np.array_equal(got["fp32"], got["bf16"])
bad += 0 if same else 1
print(f"[{a.shape}] bf16-in vs fp32-in: {'IDENTICAL' if same else 'DIFFERENT max|d| %.3g' % np.abs(got['fp32'] - got['bf16']).max()}",
flush=True)
if a.trace:
for m in ("fp32", "bf16"):
ttnn.deallocate(run(m))
tid = ttnn.begin_trace_capture(dev, cq_id=0)
y = run(m)
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(ttnn.to_torch(y).float().numpy(), got[m])
bad += 0 if okt else 1
print(f" {m} trace call {i + 1}: {'IDENTICAL' if okt else 'DIFFERENT'}", flush=True)
ttnn.release_trace(dev, tid)
ttnn.deallocate(y)
print(f" {m} transpose (+ typecast) + matmul traced p50 {np.median(ts):.3f} ms", 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())