frnet-p150 / code /scripts /diag /skip_bringup.py
changh95's picture
tt-model push frnet-p150 (container)
7a24154 verified
Raw History Blame Contribute Delete
6.25 kB
#!/usr/bin/env python3
# SPDX-License-Identifier: Apache-2.0
"""Bring-up / bit-identity check of HEAD-SKIP (OPT round 3): the KCAT operand kernel's mode 2 (``tt.kcat.Sum2``: fp32
``x + skip`` added in DEST, then the two-term split) against the stock ``ttnn.add(x, skip)`` followed by the mode-0
operand kernel (the path it replaces).
bin/devrun -t 600 -- env TT_METAL_WATCHER=2 python -u code/scripts/diag/skip_bringup.py --stage small
bin/devrun -t 900 -- python -u code/scripts/diag/skip_bringup.py --stage real
small: 64 / 256 rows, eager x2, then a 2-call trace on new data; real: FRHead's widths at N_cap = 160,000 + timing.
"""
from __future__ import annotations
import argparse
import sys
import time
import numpy as np
import torch
sys.path.insert(0, __file__.rsplit("/scripts/", 1)[0])
import ttnn # noqa: E402
from tt_frnet.tt.kcat import Sum2, build_operand # noqa: E402
from tt_frnet.ttaw.device import close_device, open_device # noqa: E402
def dev_t(a, dev, dt=None):
return ttnn.from_torch(torch.from_numpy(a), dtype=dt or ttnn.float32, layout=ttnn.TILE_LAYOUT, device=dev,
memory_config=ttnn.DRAM_MEMORY_CONFIG)
def host(t):
return ttnn.to_torch(t).float().numpy()
def rand(rng, n, k, scale=3.0):
return (rng.standard_normal((1, 1, n, k)) * scale).astype(np.float32)
def stock(x, s):
y = ttnn.add(x, s, memory_config=ttnn.DRAM_MEMORY_CONFIG)
out = build_operand([y], mode="kernel")
ttnn.deallocate(y)
return out
def check(dev, rng, n, k, label):
x, s = dev_t(rand(rng, n, k), dev), dev_t(rand(rng, n, k), dev)
a1 = host(build_operand([Sum2((x, s))], mode="kernel"))
a2 = host(build_operand([Sum2((x, s))], mode="kernel"))
b = host(stock(x, s))
st = host(build_operand([Sum2((x, s))], mode="stock"))
same = a1.shape == b.shape and np.array_equal(a1.view(np.uint32), b.view(np.uint32))
if not same:
xs, ss = host(x).reshape(-1, k), host(s).reshape(-1, k)
ys = host(ttnn.add(x, s, memory_config=ttnn.DRAM_MEMORY_CONFIG)).reshape(-1, k)
np_sum = (xs + ss).astype(np.float32)
print(f" device add == numpy fp32 add: {np.array_equal(ys, np_sum)}", flush=True)
A, Bm = a1.reshape(-1, 3 * k), b.reshape(-1, 3 * k)
for j, nm in enumerate(("hi", "hi2", "lo")):
d = A[:, j * k:(j + 1) * k] != Bm[:, j * k:(j + 1) * k]
print(f" {nm}: {int(d.sum())} / {d.size} differ; kernel sample {A[:2, j * k:j * k + 4]} vs "
f"{Bm[:2, j * k:j * k + 4]}", flush=True)
print(f" x {xs[:2, :4]} s {ss[:2, :4]} sum {np_sum[:2, :4]}", flush=True)
d = (A[:, :k] != Bm[:, :k])
r, c = np.nonzero(d)
print(f" differing rows {sorted(set((r % 32).tolist()))[:40]} tile rows {sorted(set((r // 32).tolist()))} "
f"cols%32 {sorted(set((c % 32).tolist()))[:40]} tile cols {sorted(set((c // 32).tolist()))}", flush=True)
i = (r[0], c[0])
print(f" first diff at {i}: kernel {A[i]} stock {Bm[i]} sum {np_sum[i]} x {xs[i]} s {ss[i]}", flush=True)
rep = np.array_equal(a1.view(np.uint32), a2.view(np.uint32))
same_st = np.array_equal(a1.view(np.uint32), st.view(np.uint32))
print(f"sum2 {label} n={n} k={k}: shape {a1.shape} == add+kernel {same}, eager x2 {rep}, == stock operand "
f"{same_st}", flush=True)
assert same and rep and same_st, label
return x, s
def check_mixed(dev, rng, n):
p = dev_t(rand(rng, n, 128), dev, ttnn.bfloat16)
x, s = dev_t(rand(rng, n, 128), dev), dev_t(rand(rng, n, 128), dev)
a = host(build_operand([p, Sum2((x, s))], mode="kernel"))
y = ttnn.add(x, s, memory_config=ttnn.DRAM_MEMORY_CONFIG)
b = host(build_operand([p, y], mode="kernel"))
same = np.array_equal(a.view(np.uint32), b.view(np.uint32))
print(f"mixed [bf16, sum2] n={n}: bit-identical {same}", flush=True)
assert same
def check_trace(dev, rng, n, k):
x, s = dev_t(rand(rng, n, k), dev), dev_t(rand(rng, n, k), dev)
build_operand([Sum2((x, s))], mode="kernel") # compile outside the capture
tid = ttnn.begin_trace_capture(dev, cq_id=0)
yt = build_operand([Sum2((x, s))], mode="kernel")
ttnn.end_trace_capture(dev, tid, cq_id=0)
for it in range(2):
for t in (x, s):
ttnn.copy_host_to_device_tensor(ttnn.from_torch(torch.from_numpy(rand(rng, n, k)), dtype=ttnn.float32,
layout=ttnn.TILE_LAYOUT), t)
ttnn.execute_trace(dev, tid, cq_id=0, blocking=True)
ok = np.array_equal(host(yt).view(np.uint32), host(stock(x, s)).view(np.uint32))
print(f"trace call {it}: replay == add + kernel {ok}", flush=True)
assert ok
ttnn.release_trace(dev, tid)
def timing(dev, rng, n, k, reps=20):
x, s = dev_t(rand(rng, n, k), dev), dev_t(rand(rng, n, k), dev)
res = {}
for name, fn in (("add+op", lambda: stock(x, s)), ("sum2", lambda: build_operand([Sum2((x, s))], mode="kernel"))):
ttnn.deallocate(fn())
ttnn.synchronize_device(dev)
t0 = time.perf_counter()
for _ in range(reps):
ttnn.deallocate(fn())
ttnn.synchronize_device(dev)
res[name] = (time.perf_counter() - t0) * 1e3 / reps
print(f"timing n={n} k={k}: " + ", ".join(f"{a} {b:.3f} ms" for a, b in res.items()), flush=True)
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--stage", choices=("small", "real"), default="small")
a = ap.parse_args()
rng = np.random.default_rng(0)
dev = open_device(0, dispatch="eth", trace_region_size=64 << 20)
try:
if a.stage == "small":
for _ in range(2):
check(dev, rng, 64, 128, "small")
check(dev, rng, 256, 64, "small64")
check_mixed(dev, rng, 256)
check_trace(dev, rng, 256, 128)
else:
n = 160000
for k in (128, 256, 128, 64):
check(dev, rng, n, k, "head")
check_trace(dev, rng, n, 128)
for k in (128, 256, 64):
timing(dev, rng, n, k)
print("ALL OK", flush=True)
finally:
close_device(dev)
if __name__ == "__main__":
main()