Download code/scripts/terms_epi_probe.py from changh95/meteor-p150: direct link, hf CLI and curl.
- Browser
- Download file 6.94 kB
-
https://huggingface.co/changh95/meteor-p150/resolve/main/code/scripts/terms_epi_probe.py
- Command line
-
hf download hf://changh95/meteor-p150/code/scripts/terms_epi_probe.py
-
curl -L -o terms_epi_probe.py https://huggingface.co/changh95/meteor-p150/resolve/main/code/scripts/terms_epi_probe.py
6.94 kB
| #!/usr/bin/env python3 | |
| """TERMS_EPI bring-up probe (OPT_PLAN #2; hang protocol: smallest shape first, eager x2, then a 2-call trace). | |
| Part 1 (kernel): ``tt.epi.epilogue`` against the stock ops it replaces on random fp32 maps (incl. exact ties, -0.0 | |
| and negatives for the ReLU), every form: sum of 3 / 2 parts (+ ReLU), + residual + ReLU, split only, main + split, | |
| the plain split. Bit-identity required. | |
| Part 2 (layer): a :class:`tt.layers.TermsConv` pair as a ResNet basic block (conv1 + ReLU -> conv2 + identity + ReLU) | |
| and a ConvBlock, built with ``TERMS_EPI`` stock / epi / fused, outputs compared bit for bit. | |
| bin/devrun -t 600 -- python -u code/scripts/terms_epi_probe.py --rows 64 --cols 64 # smallest first | |
| """ | |
| 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", help="also a 2-call trace of the kernel forms") | |
| ap.add_argument("--layer", default="", help="N,H,W,C of the layer probe (empty: skip)") | |
| 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 | |
| shape = (1, 1, a.rows, a.cols) | |
| def rnd(): | |
| x = rng.standard_normal(shape).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) # a bf16 tie | |
| return x | |
| ps = [up(rnd()) for _ in range(3)] | |
| res = up(rnd()) | |
| relu = [ttnn.UnaryWithParam(ttnn.UnaryOpType.RELU)] | |
| def stock_split(t): | |
| hi = ttnn.typecast(t, ttnn.bfloat16) | |
| lo = ttnn.typecast(ttnn.subtract(t, ttnn.typecast(hi, ttnn.float32)), ttnn.bfloat16) | |
| return hi, lo | |
| def stock(n, r, act): | |
| s = ttnn.add(ps[0], ps[1], activations=relu if (act and n == 2 and not r) else [], | |
| memory_config=ttnn.DRAM_MEMORY_CONFIG) | |
| if n == 3: | |
| s = ttnn.add(s, ps[2], activations=relu if (act and not r) else [], memory_config=ttnn.DRAM_MEMORY_CONFIG) | |
| if r: | |
| s = ttnn.add(s, res, activations=relu if act else []) | |
| return s | |
| forms = [(3, False, True), (3, False, False), (2, False, True), (3, True, True), (3, True, False)] | |
| def run_kernel(tag): | |
| for n, r, act in forms: | |
| want = stock(n, r, act) | |
| for sp, mn in ((False, True), (True, True), (True, False)): | |
| out, hi, lo = epi.epilogue(ps[:n], residual=res if r else None, relu=act, split=sp, main=mn) | |
| name = f"{tag} np{n} res{int(r)} relu{int(act)} split{int(sp)} main{int(mn)}" | |
| ok = True | |
| if mn: | |
| ok &= same(name + " main", out, want) | |
| if sp: | |
| h0, l0 = stock_split(want) | |
| ok &= same(name + " hi", hi, h0) | |
| ok &= same(name + " lo", lo, l0) | |
| print(f" {name}: {'IDENTICAL' if ok else 'DIFFERENT'}") | |
| h0, l0 = stock_split(ps[0]) | |
| hi, lo = epi.split(ps[0]) | |
| print(f" {tag} split: {'IDENTICAL' if same(tag + ' split hi', hi, h0) & same(tag + ' split lo', lo, l0) else 'DIFFERENT'}") | |
| print(f"[kernel] shape {shape}, grid {dev.compute_with_storage_grid_size()}") | |
| run_kernel("eager1") | |
| run_kernel("eager2") | |
| if a.trace: | |
| out_s = stock(3, True, True) | |
| out = {} | |
| def body(): | |
| m, h, l_ = epi.epilogue(ps, residual=res, relu=True, split=True, main=True) | |
| out["m"], out["h"], out["l"] = m, h, l_ | |
| body() # compile eager | |
| 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) | |
| h0, l0 = stock_split(out_s) | |
| ok = same("trace main", out["m"], out_s) & same("trace hi", out["h"], h0) & same("trace lo", out["l"], l0) | |
| print(f" trace replay {i}: {'IDENTICAL' if ok else 'DIFFERENT'}") | |
| ttnn.release_trace(dev, tid) | |
| if 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_, h_, w_, c_ = (int(v) for v in a.layer.split(",")) | |
| x_np = np.abs(rng.standard_normal((1, 1, n_ * h_ * w_, c_)).astype(np.float32)) | |
| wts = {k: (rng.standard_normal((c_, c_, 3, 3)).astype(np.float32) * 0.05, | |
| rng.standard_normal(c_).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 ("stock", "epi", "fused"): | |
| L.set_opts(TERMS_EPI=mode) | |
| blk = BasicBlock(provider, {"block": "b", "conv1": "conv1", "conv2": "conv2"}, has_downsample=False, | |
| factory=L.terms_factory()) | |
| if mode == "fused": | |
| blk.__class__ = TermsBasicBlock | |
| x = FeatureMap(up(x_np), n_, h_, w_, c_) | |
| for rep in range(2): | |
| y = blk(x) | |
| outs[(mode, rep)] = host(y.tensor) | |
| L.free(y) | |
| L.set_opts(TERMS_EPI=None) | |
| base = outs[("stock", 0)].view(np.uint32) | |
| for k, v in outs.items(): | |
| ok = np.array_equal(base, v.view(np.uint32)) | |
| bad += 0 if ok else 1 | |
| print(f" [layer {a.layer}] {k}: {'IDENTICAL' if ok else 'DIFFERENT max|d| %.3g' % np.abs(v - outs[('stock', 0)]).max()}") | |
| 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()) | |