#!/usr/bin/env python3 """REF_EPI probe (OPT2 round 6 R6.5): the seg refiner stem's epilogue in the fast profile, relu(s + range_bias) cast to bf16 on the 4-D [800, 500, 48] fp32 map, as ONE BinaryNg (``fused``: add with a ReLU post-activation and a bf16 output) instead of add, relu and typecast (``stock``: three programs, 0.70 + 0.51 + 0.35 ms in the profile). Checked bit-identical (the same fp32 add and ReLU in DEST; the bf16 rounding at the pack), then both timed traced. METEOR_DEVICE_OK=1 bin/devrun -t 300 -- python -u code/scripts/stem_epi_probe.py --shape 1,8,40,48 METEOR_DEVICE_OK=1 bin/devrun -t 600 -- python -u code/scripts/stem_epi_probe.py --shape 1,800,500,48 --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,40,48") ap.add_argument("--trace", action="store_true") ap.add_argument("--reps", type=int, default=10) ap.add_argument("--cases", default="stock,fused,mstock,mfused") a = ap.parse_args() import torch import ttnn from tt_meteor.ttaw.device import open_device shp = tuple(int(v) for v in a.shape.split(",")) dev = open_device(dispatch="eth", trace_region_size=64 << 20) rng = np.random.default_rng(0) s = rng.standard_normal(shp).astype(np.float32) * 3 b = rng.standard_normal(shp).astype(np.float32) s.reshape(-1)[:64] = -b.reshape(-1)[:64] # exact zeros (-0.0 / +0.0 paths) s.reshape(-1)[64:96] = np.float32(1.00390625) - b.reshape(-1)[64:96] # bf16 rounding ties td = lambda x: ttnn.from_torch(torch.from_numpy(x), dtype=ttnn.float32, layout=ttnn.TILE_LAYOUT, device=dev, memory_config=ttnn.DRAM_MEMORY_CONFIG) sd, bd = td(s), td(b) def stock(): t = ttnn.relu(ttnn.add(sd, bd)) y = ttnn.typecast(t, ttnn.bfloat16) ttnn.deallocate(t) return y def fused(): return ttnn.add(sd, bd, activations=[ttnn.UnaryWithParam(ttnn.UnaryOpType.RELU)], dtype=ttnn.bfloat16) # the image branch's Fp32StemBlock tail: bf16(relu(fp32(z_bf16) + idt_fp32)) (four programs) vs one mixed add zd = ttnn.from_torch(torch.from_numpy(s).to(torch.bfloat16), dtype=ttnn.bfloat16, layout=ttnn.TILE_LAYOUT, device=dev, memory_config=ttnn.DRAM_MEMORY_CONFIG) def mstock(): z32 = ttnn.typecast(zd, ttnn.float32) t = ttnn.relu(ttnn.add(z32, bd)) ttnn.deallocate(z32) y = ttnn.typecast(t, ttnn.bfloat16) ttnn.deallocate(t) return y def mfused(): return ttnn.add(zd, bd, activations=[ttnn.UnaryWithParam(ttnn.UnaryOpType.RELU)], dtype=ttnn.bfloat16) fns = {"stock": stock, "fused": fused, "mstock": mstock, "mfused": mfused} cases = [(n, fns[n]) for n in a.cases.split(",")] got = {} for name, fn in cases: y = fn() got[name] = ttnn.to_torch(y).view(torch.int16).numpy() print(f" {name}: {list(y.shape)} {y.dtype} {y.layout}", flush=True) ttnn.deallocate(y) ref = torch.from_numpy(np.maximum(s + b, 0)).to(torch.bfloat16).view(torch.int16).numpy() for k, v in got.items(): print(f" {k} vs torch RNE bf16: {np.mean(v == ref):.6f} equal", flush=True) bad = 0 for x, y in (("stock", "fused"), ("mstock", "mfused")): if x not in got or y not in got: continue same = np.array_equal(got[x], got[y]) print(f"[{a.shape}] {y} vs {x}: {'IDENTICAL' if same else 'DIFFERENT (%d)' % np.sum(got[x] != got[y])}", flush=True) bad += 0 if same else 1 if a.trace: for name, fn in cases: ttnn.deallocate(fn()) 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: okt = np.array_equal(ttnn.to_torch(y).view(torch.int16).numpy(), got[name]) 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 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())