Download code/scripts/stem_fold_probe.py from changh95/meteor-p150: direct link, hf CLI and curl.
- Browser
- Download file 8.63 kB
-
https://huggingface.co/changh95/meteor-p150/resolve/main/code/scripts/stem_fold_probe.py
- Command line
-
hf download hf://changh95/meteor-p150/code/scripts/stem_fold_probe.py
-
curl -L -o stem_fold_probe.py https://huggingface.co/changh95/meteor-p150/resolve/main/code/scripts/stem_fold_probe.py
8.63 kB
| #!/usr/bin/env python3 | |
| """STEM=fold bring-up probe (OPT2 round 3 R3.1, OPT_PLAN A6; hang protocol: smallest shape first, eager x2, then a | |
| 2-call trace). | |
| Stock (round 2, fast profile): uint8 rows -> ``tt.kin.expand`` (8-channel bf16 pixels) -> the stem conv 7x7 / s2 / p3 | |
| (fp32 weights at HiFi4, fp32 out, ReLU) on ttnn's DRAM-sliced path. Fold: uint8 rows -> ``tt.kin.expand_fold`` | |
| (space-to-depth of the zero-padded image, 16-channel bf16 pixels) -> a 4x4 / s1 / p0 conv with ``fold_weights``. | |
| Checked: the folded map equals the host twin ``fold_host`` exactly; each stem output against a float64 CPU conv | |
| (max abs error) and against each other; eager x2 stable; then both input + conv stages timed as traced replays. | |
| METEOR_DEVICE_OK=1 bin/devrun -t 300 -- python -u code/scripts/stem_fold_probe.py --shape 1,8,64 | |
| METEOR_DEVICE_OK=1 bin/devrun -t 900 -- python -u code/scripts/stem_fold_probe.py --shape 8,432,768 --trace | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import sys | |
| import time | |
| import numpy as np | |
| PORT_PRECISION = "HiFi4+fp32+l1acc:w=fp32" | |
| 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") | |
| ap.add_argument("--cout", type=int, default=64) | |
| ap.add_argument("--t4", action="store_true", help="OPT2 R6.1: also the 4-D TILE folded input (STEM_IN=t4), " | |
| "checked identical to the ROW_MAJOR form and its conv output") | |
| a = ap.parse_args() | |
| import torch | |
| import ttnn | |
| from tt_meteor.tt import kin | |
| from tt_meteor.tt.layers import CONV_CONFIG | |
| from tt_meteor.ttaw.device import open_device | |
| from tt_meteor.ttaw.ops.conv import Conv2d, FeatureMap | |
| n, h, w = (int(v) for v in a.shape.split(",")) | |
| hf, wf = kin.fold_shape(h, w, 3) | |
| 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 | |
| rows = ttnn.from_torch(torch.from_numpy(np.ascontiguousarray(img.reshape(1, 1, n * h, w * 3))), dtype=ttnn.uint8, | |
| layout=ttnn.ROW_MAJOR_LAYOUT, device=dev, memory_config=ttnn.DRAM_MEMORY_CONFIG) | |
| bad = 0 | |
| def host(t): | |
| x = ttnn.to_torch(t) | |
| return x.float().numpy() if x.dtype != torch.float32 else x.numpy() | |
| xf = kin.expand_fold(rows, n, h, w) | |
| ref_f = kin.fold_host(img, 3).reshape(-1, kin.CO_FOLD) | |
| got = host(xf).reshape(-1, kin.CO_FOLD) | |
| ok = got.shape == ref_f.shape and np.array_equal(got, ref_f) and not np.any(np.signbit(got)) | |
| bad += 0 if ok else 1 | |
| if not ok and got.shape == ref_f.shape: | |
| idx = np.argwhere(got != ref_f) | |
| print(f" first mismatches (row, ch): {idx[:8].tolist()} of {len(idx)}", flush=True) | |
| print(f"[{a.shape}] expand_fold vs host fold [{n}x{hf}x{wf}x16]: {'IDENTICAL' if ok else 'DIFFERENT'}", flush=True) | |
| xf2 = kin.expand_fold(rows, n, h, w) | |
| ok2 = np.array_equal(host(xf2), host(xf)) | |
| bad += 0 if ok2 else 1 | |
| print(f" expand_fold eager x2: {'stable' if ok2 else 'UNSTABLE'}", flush=True) | |
| ttnn.deallocate(xf2) | |
| xt = None | |
| if a.t4: | |
| xt = kin.expand_fold(rows, n, h, w, layout="t4") | |
| gt = host(xt) | |
| okt4 = list(xt.shape) == [n, hf, wf, kin.CO_FOLD] and xt.layout == ttnn.TILE_LAYOUT and \ | |
| np.array_equal(gt.reshape(-1, kin.CO_FOLD), ref_f) | |
| bad += 0 if okt4 else 1 | |
| print(f" expand_fold t4 {list(xt.shape)} {xt.layout} vs host fold: {'IDENTICAL' if okt4 else 'DIFFERENT'}", | |
| flush=True) | |
| xt2 = kin.expand_fold(rows, n, h, w, layout="t4") | |
| okt42 = np.array_equal(host(xt2), gt) | |
| bad += 0 if okt42 else 1 | |
| print(f" expand_fold t4 eager x2: {'stable' if okt42 else 'UNSTABLE'}", flush=True) | |
| ttnn.deallocate(xt2) | |
| if not a.no_conv: | |
| co = a.cout | |
| wt = (rng.standard_normal((co, 3, 7, 7)) * 0.02 / 255.0 * 50).astype(np.float32) | |
| b = (rng.standard_normal(co) * 0.1).astype(np.float32) | |
| w8 = np.zeros((co, kin.CO, 7, 7), np.float32) | |
| w8[:, :3] = wt | |
| kw = dict(activation="relu", precision=PORT_PRECISION, output_dtype="float32", conv_config=CONV_CONFIG) | |
| c7 = Conv2d(w8, b, stride=2, padding=3, name="stem/stem.0", **kw) | |
| c4 = Conv2d(kin.fold_weights(wt), b, stride=1, padding=0, name="stem/stem.0:fold", **kw) | |
| x8 = kin.expand(rows, n, h, w) | |
| y7 = c7(FeatureMap(x8, n, h, w, kin.CO)) | |
| y4 = c4(FeatureMap(xf, n, hf, wf, kin.CO_FOLD)) | |
| print(f" stock out {list(y7.tensor.shape)} {y7.tensor.layout}, fold out {list(y4.tensor.shape)} " | |
| f"{y4.tensor.layout} {y4.height}x{y4.width}", flush=True) | |
| r7, r4 = host(y7.tensor), host(y4.tensor) | |
| ref = torch.nn.functional.relu(torch.nn.functional.conv2d( | |
| torch.from_numpy(img.astype(np.float64)).permute(0, 3, 1, 2), torch.from_numpy(wt.astype(np.float64)), | |
| torch.from_numpy(b.astype(np.float64)), stride=2, padding=3)).permute(0, 2, 3, 1).reshape(-1, co).numpy() | |
| r7 = r7.reshape(-1, co)[: ref.shape[0]] | |
| r4 = r4.reshape(-1, co)[: ref.shape[0]] | |
| scale = np.abs(ref).max() | |
| e7, e4 = np.abs(r7 - ref).max(), np.abs(r4 - ref).max() | |
| d = np.abs(r7.astype(np.float64) - r4) | |
| print(f" max|err| vs float64: stock {e7:.4g}, fold {e4:.4g} (max|ref| {scale:.4g}); stock vs fold max|d| " | |
| f"{d.max():.4g}, identical frac {np.mean(r7 == r4):.4f}", flush=True) | |
| good = e4 <= max(2.0 * e7, 1e-5 * scale) | |
| bad += 0 if good else 1 | |
| print(f" fold precision vs stock: {'OK' if good else 'WORSE'}", flush=True) | |
| if xt is not None: | |
| yt = c4(FeatureMap(xt, n, hf, wf, kin.CO_FOLD)) | |
| rt = host(yt.tensor).reshape(-1, co)[: ref.shape[0]] | |
| okc = np.array_equal(rt, r4) | |
| bad += 0 if okc else 1 | |
| print(f" fold conv on the t4 input {list(yt.tensor.shape)} vs the rm input: " | |
| f"{'IDENTICAL' if okc else 'DIFFERENT (max|d| %.4g)' % np.abs(rt - r4).max()}", flush=True) | |
| ttnn.deallocate(yt.tensor) | |
| y4b = c4(FeatureMap(xf, n, hf, wf, kin.CO_FOLD)) | |
| ok3 = np.array_equal(host(y4b.tensor).reshape(-1, co)[: ref.shape[0]], r4) | |
| bad += 0 if ok3 else 1 | |
| print(f" fold conv eager x2: {'stable' if ok3 else 'UNSTABLE'}", flush=True) | |
| for t in (y7.tensor, y4.tensor, y4b.tensor, x8): | |
| ttnn.deallocate(t) | |
| if a.trace: | |
| def stock(): | |
| x = kin.expand(rows, n, h, w) | |
| y = c7(FeatureMap(x, n, h, w, kin.CO)) | |
| ttnn.deallocate(x) | |
| return y.tensor | |
| def fold(): | |
| x = kin.expand_fold(rows, n, h, w) | |
| y = c4(FeatureMap(x, n, hf, wf, kin.CO_FOLD)) | |
| ttnn.deallocate(x) | |
| return y.tensor | |
| def fold_t4(): | |
| x = kin.expand_fold(rows, n, h, w, layout="t4") | |
| y = c4(FeatureMap(x, n, hf, wf, kin.CO_FOLD)) | |
| ttnn.deallocate(x) | |
| return y.tensor | |
| cases = [("stock", stock, r7), ("fold", fold, r4)] + ([("fold_t4", fold_t4, r4)] if a.t4 else []) | |
| for name, fn, want 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(host(y).reshape(-1, co)[: ref.shape[0]], want) | |
| 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} input + stem conv traced replay p50 {np.median(ts):.3f} ms (min {np.min(ts):.3f})", | |
| 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()) | |