meteor-p150 / code /scripts /kin_probe.py
changh95's picture
tt-model push meteor-p150 (container)
8eeb550 verified
Raw History Blame Contribute Delete
6.13 kB
#!/usr/bin/env python3
"""IMG_IN bring-up probe (OPT round 3 R3.3; hang protocol: smallest shape first, eager x2, then a 2-call trace).
Stock: uint8 pixels ``[1, 1, N*H*W, 3]`` -> ``ttnn.typecast`` bf16 -> the stem TermsConv (7x7 / s2 / p3, 3 -> 64,
ReLU, fp32 out). Kernel: uint8 rows ``[1, 1, N*H, W*3]`` -> ``tt.kin.expand`` -> bf16 ``[1, 1, N*H*W, 8]`` -> the same
TermsConv with zero weights on input channels 3..7. Checked: the expanded pixels equal the typecast (channels 0..2)
and +0.0 (3..7), and the two stem outputs are bit-identical; then both input stages are timed as traced replays.
METEOR_DEVICE_OK=1 bin/devrun -t 600 -- python -u code/scripts/kin_probe.py --shape 1,8,64 # smallest
METEOR_DEVICE_OK=1 bin/devrun -t 600 -- python -u code/scripts/kin_probe.py --shape 8,432,768 --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,8,64", help="N,H,W")
ap.add_argument("--trace", action="store_true")
ap.add_argument("--reps", type=int, default=10)
ap.add_argument("--no-conv", action="store_true", help="only the input stage")
a = ap.parse_args()
import torch
import ttnn
from tt_meteor.tt import kin
from tt_meteor.tt.layers import TermsConv
from tt_meteor.ttaw.device import open_device
from tt_meteor.ttaw.ops.conv import FeatureMap
n, h, w = (int(v) for v in a.shape.split(","))
dev = open_device(dispatch="eth", trace_region_size=64 << 20)
rng = np.random.default_rng(0)
img = rng.integers(0, 256, size=(n, h, w, 3), dtype=np.uint8)
img[0, 0, :8] = 0
img[0, 1, :8] = 255
def up(x):
return ttnn.from_torch(torch.from_numpy(np.ascontiguousarray(x)), dtype=ttnn.uint8,
layout=ttnn.ROW_MAJOR_LAYOUT, device=dev, memory_config=ttnn.DRAM_MEMORY_CONFIG)
px = up(img.reshape(1, 1, n * h * w, 3))
rows = up(img.reshape(1, 1, n * h, w * 3))
bad = 0
def host(t):
x = ttnn.to_torch(t)
return x.float().numpy() if x.dtype != torch.float32 else x.numpy()
# input stage
x3 = ttnn.typecast(px, ttnn.bfloat16)
x8 = kin.expand(rows, n, h, w)
a3, a8 = host(x3).reshape(-1, 3), host(x8).reshape(-1, kin.CO)
ok = np.array_equal(a3, a8[:, :3]) and np.array_equal(a8[:, 3:], np.zeros_like(a8[:, 3:])) and \
not np.any(np.signbit(a8[:, 3:]))
ok = ok and np.array_equal(a3, img.reshape(-1, 3).astype(np.float32))
bad += 0 if ok else 1
print(f"[{a.shape}] expand vs typecast: {'IDENTICAL' if ok else 'DIFFERENT'}", flush=True)
x8b = kin.expand(rows, n, h, w)
ok2 = np.array_equal(host(x8b), host(x8))
bad += 0 if ok2 else 1
print(f" expand eager x2: {'stable' if ok2 else 'UNSTABLE'}", flush=True)
ttnn.deallocate(x8b)
if not a.no_conv:
wt = (rng.standard_normal((64, 3, 7, 7)) * 0.01).astype(np.float32)
b = (rng.standard_normal(64) * 0.1).astype(np.float32)
w8 = np.zeros((64, kin.CO, 7, 7), np.float32)
w8[:, :3] = wt
c3 = TermsConv(wt, b, stride=2, padding=3, activation="relu", name="stem/stem.0")
c8 = TermsConv(w8, b, stride=2, padding=3, activation="relu", name="stem/stem.0")
y3 = c3(FeatureMap(x3, n, h, w, 3))
y8 = c8(FeatureMap(x8, n, h, w, kin.CO))
r3, r8 = host(y3.tensor), host(y8.tensor)
same = np.array_equal(r3.view(np.uint32), r8.view(np.uint32))
bad += 0 if same else 1
d = np.abs(r3.astype(np.float64) - r8.astype(np.float64))
print(f" stem conv out (fp32 {list(y3.tensor.shape)}): {'IDENTICAL' if same else 'DIFFERENT'} "
f"(max|d| {d.max():.3g}, frac {np.mean(r3 != r8):.4g})", flush=True)
y8b = c8(FeatureMap(x8, n, h, w, kin.CO))
ok3 = np.array_equal(host(y8b.tensor), r8)
bad += 0 if ok3 else 1
print(f" kernel path eager x2: {'stable' if ok3 else 'UNSTABLE'}", flush=True)
for t in (y3.tensor, y8.tensor, y8b.tensor):
ttnn.deallocate(t)
if a.trace:
for name, fn in (("typecast", lambda: ttnn.typecast(px, ttnn.bfloat16)),
("expand", lambda: kin.expand(rows, n, h, w))):
fn_out = fn()
ttnn.deallocate(fn_out)
tid = ttnn.begin_trace_capture(dev, cq_id=0)
y = fn()
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:
r = host(y).reshape(-1, 3 if name == "typecast" else kin.CO)[:, :3]
okt = np.array_equal(r, a3)
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)
ttnn.deallocate(y)
print(f" {name} traced replay p50 {np.median(ts):.3f} ms (min {np.min(ts):.3f})", flush=True)
# upload time of the two input forms (host tensors prebuilt, as the trace runner's persistent inputs)
for name, arr in (("px", img.reshape(1, 1, n * h * w, 3)), ("rows", img.reshape(1, 1, n * h, w * 3))):
hst = ttnn.from_torch(torch.from_numpy(np.ascontiguousarray(arr)), dtype=ttnn.uint8,
layout=ttnn.ROW_MAJOR_LAYOUT)
dst = px if name == "px" else rows
ts = []
for _ in range(5):
t0 = time.perf_counter()
ttnn.copy_host_to_device_tensor(hst, dst)
ttnn.synchronize_device(dev)
ts.append((time.perf_counter() - t0) * 1e3)
print(f" H2D {name}: p50 {np.median(ts):.2f} 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())