File size: 6,394 Bytes
8eeb550 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 | #!/usr/bin/env python3
"""TERMS_ST2 bring-up probe (OPT round 4 R4.1; hang protocol: smallest shape first, eager x2, then a 2-call trace).
Part 1 (kernel): ``tt.epi.epilogue`` with column-range parts (the stacked ``[hi*W_hi | hi*W_lo]`` output read twice
plus the ``lo*W_hi`` part) against the plain epilogue of the sliced halves; every form. Bit-identity required.
Part 2 (layer): a TermsConv basic block (conv1 + ReLU -> conv2 + identity + ReLU) with ``TERMS_ST2`` off vs all,
per ``--layer N,H,W,C[,stride]`` (several allowed), outputs compared bit for bit.
bin/devrun -t 600 -- python -u code/scripts/st2_probe.py --rows 64 --cols 64
"""
from __future__ import annotations
import argparse
import sys
import numpy as np
def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("--rows", type=int, default=64)
ap.add_argument("--cols", type=int, default=64)
ap.add_argument("--trace", action="store_true")
ap.add_argument("--layer", action="append", default=[], help="N,H,W,C of a layer probe")
a = ap.parse_args()
import torch
import ttnn
from tt_meteor.tt import epi
from tt_meteor.ttaw.device import open_device
dev = open_device(dispatch="eth", trace_region_size=64 << 20)
rng = np.random.default_rng(0)
bad = 0
def up(x, dt=ttnn.float32):
return ttnn.from_torch(torch.from_numpy(np.ascontiguousarray(x)), dtype=dt, layout=ttnn.TILE_LAYOUT,
device=dev, memory_config=ttnn.DRAM_MEMORY_CONFIG)
def host(t):
return ttnn.to_torch(t).float().numpy() if t.dtype != ttnn.float32 else ttnn.to_torch(t).numpy()
def same(name, x, y):
nonlocal bad
xa, ya = host(x), host(y)
ok = np.array_equal(xa.view(np.uint32) if xa.dtype == np.float32 else xa,
ya.view(np.uint32) if ya.dtype == np.float32 else ya)
if not ok:
bad += 1
d = np.abs(xa.astype(np.float64) - ya.astype(np.float64))
print(f" {name}: DIFFERENT max|d| {d.max():.3g} frac {np.mean(xa != ya):.4g}")
return ok
r_, c_ = a.rows, a.cols
def rnd(cols):
x = rng.standard_normal((1, 1, r_, cols)).astype(np.float32) * np.float32(3.0)
x.flat[::17] = 0.0
x.flat[1::19] = -0.0
x.flat[2::23] = np.float32(1.0) + np.float32(2.0 ** -9)
return x
st = up(rnd(2 * c_))
plo = up(rnd(c_))
res = up(rnd(c_))
h0 = ttnn.slice(st, [0, 0, 0, 0], [1, 1, r_, c_])
h1 = ttnn.slice(st, [0, 0, 0, c_], [1, 1, r_, 2 * c_])
forms = [(3, False, True), (3, True, True), (2, False, True), (2, True, False), (3, False, False)]
def run_kernel(tag):
for n, r, act in forms:
parts_c = [st, st, plo][:n]
parts_p = [h0, h1, plo][:n]
cols = [0, c_, 0][:n]
for sp, mn in ((False, True), (True, True), (True, False)):
kw = dict(residual=res if r else None, relu=act, split=sp, main=mn)
assert epi.supported(parts_c, kw["residual"], cols, c_)
o1 = epi.epilogue(parts_c, cols=cols, width=c_, **kw)
o0 = epi.epilogue(parts_p, **kw)
ok = True
for x, y, nm in zip(o1, o0, ("main", "hi", "lo")):
if x is not None:
ok &= same(f"{tag} np{n} res{int(r)} relu{int(act)} {nm}", x, y)
print(f" {tag} np{n} res{int(r)} relu{int(act)} split{int(sp)} main{int(mn)}: "
f"{'IDENTICAL' if ok else 'DIFFERENT'}", flush=True)
print(f"[kernel] rows {r_} cols {c_}, grid {dev.compute_with_storage_grid_size()}", flush=True)
run_kernel("eager1")
run_kernel("eager2")
if a.trace:
out = {}
def body():
out["c"] = epi.epilogue([st, st, plo], cols=[0, c_, 0], width=c_, residual=res, relu=True, split=True)
body()
want = epi.epilogue([h0, h1, plo], residual=res, relu=True, split=True)
tid = ttnn.begin_trace_capture(dev, cq_id=0)
body()
ttnn.end_trace_capture(dev, tid, cq_id=0)
for i in range(2):
ttnn.execute_trace(dev, tid, cq_id=0, blocking=True)
ok = all(same(f"trace {nm}", x, y) for x, y, nm in zip(out["c"], want, ("main", "hi", "lo")))
print(f" trace replay {i}: {'IDENTICAL' if ok else 'DIFFERENT'}", flush=True)
ttnn.release_trace(dev, tid)
for spec in a.layer:
from tt_meteor.tt import layers as L
from tt_meteor.tt.image import TermsBasicBlock
from tt_meteor.ttaw.models.resnet import BasicBlock, ConvParams
from tt_meteor.ttaw.ops.conv import FeatureMap
n_, hh, ww, cc = (int(v) for v in spec.split(","))
x_np = np.abs(rng.standard_normal((1, 1, n_ * hh * ww, cc)).astype(np.float32))
wts = {k: (rng.standard_normal((cc, cc, 3, 3)).astype(np.float32) * 0.05,
rng.standard_normal(cc).astype(np.float32) * 0.1) for k in ("conv1", "conv2")}
def provider(name):
w, b = wts[name]
return ConvParams(w, b, (1, 1), (1, 1, 1, 1))
outs = {}
for mode in ("off", "all"):
L.set_opts(TERMS_EPI="fused", TERMS_ST2=mode)
blk = BasicBlock(provider, {"block": "b", "conv1": "conv1", "conv2": "conv2"}, has_downsample=False,
factory=L.terms_factory())
blk.__class__ = TermsBasicBlock
x = FeatureMap(up(x_np), n_, hh, ww, cc)
for rep in range(2):
y = blk(x)
outs[(mode, rep)] = host(y.tensor)
L.free(y)
print(f" [layer {spec}] {mode}: st2 {blk.conv1.st2}, placements "
f"{[getattr(c, 'placement', '-') for c in (blk.conv1.st, blk.conv1.hh, blk.conv1.lh)]}", flush=True)
L.set_opts(TERMS_EPI=None, TERMS_ST2=None)
base = outs[("off", 0)]
for k, v in outs.items():
ok = np.array_equal(base.view(np.uint32), v.view(np.uint32))
bad += 0 if ok else 1
print(f" [layer {spec}] {k}: {'IDENTICAL' if ok else 'DIFFERENT max|d| %.3g' % np.abs(v - base).max()}",
flush=True)
ttnn.close_device(dev)
print("ALL IDENTICAL" if bad == 0 else f"{bad} DIFFERENT")
return 0 if bad == 0 else 1
if __name__ == "__main__":
sys.exit(main())
|