Download code/scripts/bres_probe.py from changh95/meteor-p150: direct link, hf CLI and curl.
- Browser
- Download file 8.37 kB
-
https://huggingface.co/changh95/meteor-p150/resolve/main/code/scripts/bres_probe.py
- Command line
-
hf download hf://changh95/meteor-p150/code/scripts/bres_probe.py
-
curl -L -o bres_probe.py https://huggingface.co/changh95/meteor-p150/resolve/main/code/scripts/bres_probe.py
8.37 kB
| #!/usr/bin/env python3 | |
| """OPT2 round 2 probe: the BRES block-sparse resize kernel (tt/bresize.py) against its host model and the stock | |
| C18 Resize2d (fp32 separable matmuls), eager x2 and a traced replay, with traced timings. | |
| OPT2 round 5: ``--reader cache`` runs the cached reader (kernels/bres_reader2.cpp); ``--vs-v1`` also runs the v1 | |
| reader on the same input and requires bit-identical outputs (traced times of both printed). | |
| Hang protocol: the smallest shapes first (``--shapes small``) with ``TT_METAL_WATCHER=2`` and ``--max-cores 1``, | |
| then the grid, then the model shapes. | |
| METEOR_DEVICE_OK=1 bin/devrun -t 300 -- env TT_METAL_WATCHER=2 python -u code/scripts/bres_probe.py \ | |
| --shapes small --max-cores 1 | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import sys | |
| import time | |
| import numpy as np | |
| SMALL = "4,5,8,10,32,1,ff;8,40,16,80,64,1,ft;8,40,16,80,64,1,tt;7,9,14,18,48,2,ff" | |
| MODEL = ("400,250,800,500,96,1,ff;400,250,800,500,96,1,ft;200,125,400,250,192,1,ff;200,125,400,250,192,1,ft;" | |
| "400,250,800,500,64,1,ft;54,96,108,192,160,8,ff;27,48,108,192,160,8,ff;14,24,108,192,160,8,ff;" | |
| "27,48,54,96,192,8,ff;54,96,108,192,96,8,ff;400,250,800,500,48,1,ft;200,125,400,250,96,1,ff;" | |
| "100,63,200,125,144,1,ff;50,32,100,63,192,1,ff") | |
| def main() -> int: | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--shapes", default="small", help="small | model | h,w,H,W,C,N,io[;...] (io: f/t input, output)") | |
| ap.add_argument("--max-cores", type=int, default=0) | |
| ap.add_argument("--reps", type=int, default=10) | |
| ap.add_argument("--fid", default="HiFi4") | |
| ap.add_argument("--stock", action="store_true", help="also time / compare the stock Resize2d") | |
| ap.add_argument("--no-trace", action="store_true") | |
| ap.add_argument("--reader", default="v1", choices=("v1", "cache")) | |
| ap.add_argument("--vs-v1", action="store_true", help="also run the v1 reader; outputs must be bit-identical") | |
| a = ap.parse_args() | |
| shapes = SMALL if a.shapes == "small" else MODEL if a.shapes == "model" else a.shapes | |
| import torch | |
| import ttnn | |
| from tt_meteor.tt.bresize import BlockResize, _bf16_rne | |
| from tt_meteor.ttaw.device import open_device | |
| from tt_meteor.ttaw.ops.conv import FeatureMap | |
| from tt_meteor.ttaw.ops.upsample import Resize2d | |
| dev = open_device(dispatch="eth", trace_region_size=64 << 20) | |
| rng = np.random.default_rng(0) | |
| bad = 0 | |
| def timed(fn): | |
| ts = [] | |
| tid = ttnn.begin_trace_capture(dev, cq_id=0) | |
| out = fn() | |
| ttnn.end_trace_capture(dev, tid, cq_id=0) | |
| for _ in range(a.reps): | |
| t0 = time.perf_counter() | |
| ttnn.execute_trace(dev, tid, cq_id=0, blocking=True) | |
| ts.append((time.perf_counter() - t0) * 1e3) | |
| res = ttnn.to_torch(out.tensor).float().numpy() | |
| ttnn.release_trace(dev, tid) | |
| ttnn.deallocate(out.tensor) | |
| return res, float(np.median(ts)) | |
| for spec in shapes.split(";"): | |
| f = spec.split(",") | |
| h, w, h2, w2, c, n = (int(v) for v in f[:6]) | |
| it4, ot4 = f[6][0] == "t", f[6][1] == "t" | |
| f32 = len(f) > 7 and f[7] == "f32" # an fp32 map as its two bf16 terms (R2.2), fp32 output | |
| x = rng.standard_normal((n, h, w, c)).astype(np.float32) * 4 | |
| if not f32: | |
| x = _bf16_rne(x) | |
| xt = torch.from_numpy(x) if f32 else torch.from_numpy(x).to(torch.bfloat16) | |
| xd = ttnn.from_torch(xt if it4 else xt.reshape(1, 1, n * h * w, c), dtype=ttnn.float32 if f32 else ttnn.bfloat16, | |
| layout=ttnn.TILE_LAYOUT, device=dev, memory_config=ttnn.DRAM_MEMORY_CONFIG) | |
| fm = FeatureMap(xd, n, h, w, c) | |
| br = BlockResize((h, w), (h2, w2), channels=c, batch=n, fidelity=a.fid, max_cores=a.max_cores or None, | |
| output_dtype="float32" if f32 else "bfloat16", reader=a.reader) | |
| if f32: | |
| from tt_meteor.tt import epi | |
| xh, xl = epi.split(xd) | |
| fm_k, lo_k = FeatureMap(xh, n, h, w, c), xl | |
| else: | |
| fm_k, lo_k = fm, None | |
| ref = br.reference(x, it4, ot4) | |
| f64 = np.einsum("ph,nhwc,qw->npqc", br.plan(it4, ot4)["a_h"], x.astype(np.float64), | |
| br.plan(it4, ot4)["a_w"], optimize=True) | |
| outs = [] | |
| for _ in range(2): | |
| y = br(fm_k, out_t4=ot4, lo=lo_k) | |
| outs.append(ttnn.to_torch(y.tensor).float().numpy().reshape(n, h2, w2, c)) | |
| ttnn.deallocate(y.tensor) | |
| p = br.plan(it4, ot4) | |
| same2 = np.array_equal(outs[0], outs[1]) | |
| d = outs[0] - ref | |
| nmis = int(np.count_nonzero(d)) | |
| ulp = np.abs(d) / np.maximum(np.abs(ref) * 2.0 ** -7, 1e-30) | |
| err = float(np.abs(outs[0] - f64).max()) | |
| msg = (f"[{h}x{w} -> {h2}x{w2} C{c} N{n} in_t4={it4} out_t4={ot4}] KM {p['km']} NB {p['nb']} tiles " | |
| f"{p['weights'].shape[0]} terms {p['terms']}: eager x2 {'equal' if same2 else 'DIFFER'}; vs host model " | |
| f"{nmis} mismatches (max {float(ulp.max()) if nmis else 0:.2f} ulp); max|err| vs float64 {err:.4g}") | |
| rel = np.abs(outs[0] - f64) / np.maximum(np.abs(f64), 1e-6) | |
| wi = np.unravel_index(int(np.argmax(rel)), rel.shape) | |
| msg += (f"; worst rel {float(rel[wi]):.3g} at {tuple(int(v) for v in wi)}: dev {outs[0][wi]!r} model {ref[wi]!r} " | |
| f"f64 {f64[wi]:.6g}") | |
| # bound: the output rounding (half a bf16 ulp of the exact value) + the FPU's accumulation error, which is | |
| # relative to the operands (about 2^-16 of max|x| measured; the bound allows 2^-13) | |
| half = np.exp2(np.floor(np.log2(np.maximum(np.abs(f64), 1e-30))) - 8) | |
| excess = float((np.abs(outs[0] - f64) - half - 2.0 ** -13 * float(np.abs(x).max())).max()) | |
| msg += f"; excess over the bound {excess:.3g}" | |
| ok = same2 and excess <= 0 and np.isfinite(outs[0]).all() | |
| if not a.no_trace: | |
| tr, t_k = timed(lambda: br(fm_k, out_t4=ot4, lo=lo_k)) | |
| tr_ok = np.array_equal(tr.reshape(outs[0].shape), outs[0]) | |
| ok = ok and tr_ok | |
| msg += f"; traced {'equal' if np.array_equal(tr.reshape(outs[0].shape), outs[0]) else 'DIFFER'} {t_k:.3f} ms" | |
| if a.reader == "cache": | |
| msg += f"; cache {br.describe().get(f'cache_{int(it4)}{int(ot4)}_{1 if lo_k is None else 2}')}" | |
| if a.vs_v1: | |
| b1 = BlockResize((h, w), (h2, w2), channels=c, batch=n, fidelity=a.fid, max_cores=a.max_cores or None, | |
| output_dtype="float32" if f32 else "bfloat16", reader="v1") | |
| y1 = b1(fm_k, out_t4=ot4, lo=lo_k) | |
| o1 = ttnn.to_torch(y1.tensor).float().numpy().reshape(n, h2, w2, c) | |
| ttnn.deallocate(y1.tensor) | |
| ident = np.array_equal(o1.view(np.uint32), outs[0].view(np.uint32)) | |
| ok = ok and ident | |
| msg += f"; vs v1 {'IDENTICAL' if ident else 'DIFFER (%d)' % int(np.count_nonzero(o1 != outs[0]))}" | |
| if not a.no_trace: | |
| _, t_1 = timed(lambda: b1(fm_k, out_t4=ot4, lo=lo_k)) | |
| msg += f", v1 traced {t_1:.3f} ms" | |
| b1.release() | |
| if a.stock and not it4: | |
| rs = Resize2d((h, w), (h2, w2), channels=c, batch=n, w_pass="grid", rerow="kernel", | |
| output_dtype="float32" if f32 else "bfloat16") | |
| ys = rs(fm) | |
| st = ttnn.to_torch(ys.tensor).float().numpy().reshape(n, h2, w2, c) | |
| ttnn.deallocate(ys.tensor) | |
| es = float(np.abs(st - f64).max()) | |
| sx = float((np.abs(st - f64) - half - 2.0 ** -13 * float(np.abs(x).max())).max()) | |
| msg += f"; stock excess {sx:.3g}" | |
| ok = same2 and excess <= max(0.0, sx) and np.isfinite(outs[0]).all() | |
| msg += f"; stock max|err| {es:.4g}, kernel != stock {np.count_nonzero(st != outs[0])}" | |
| if not a.no_trace: | |
| _, t_s = timed(lambda: rs(fm)) | |
| msg += f", stock traced {t_s:.3f} ms" | |
| rs.release() | |
| if not a.no_trace: | |
| ok = ok and tr_ok | |
| print(("OK " if ok else "FAIL ") + msg, flush=True) | |
| bad += not ok | |
| br.release() | |
| ttnn.deallocate(xd) | |
| ttnn.close_device(dev) | |
| print(f"RESULT {'PASS' if bad == 0 else f'FAIL {bad}'}") | |
| return 1 if bad else 0 | |
| if __name__ == "__main__": | |
| sys.exit(main()) | |