Download code/scripts/diag/mkh_bringup.py from changh95/frnet-p150: direct link, hf CLI and curl.
- Browser
- Download file 8.72 kB
-
https://huggingface.co/changh95/frnet-p150/resolve/main/code/scripts/diag/mkh_bringup.py
- Command line
-
hf download hf://changh95/frnet-p150/code/scripts/diag/mkh_bringup.py
-
curl -L -o mkh_bringup.py https://huggingface.co/changh95/frnet-p150/resolve/main/code/scripts/diag/mkh_bringup.py
8.72 kB
| #!/usr/bin/env python3 | |
| # SPDX-License-Identifier: Apache-2.0 | |
| """Bring-up / bit-identity check of MK-H (OPT round 5, ``FRNET_POINT_MK=head``): FRHead as one row-streamed module | |
| megakernel (``tt/mk_head.py``, ``kernels/mkh_*.cpp``) against the round-4 path it replaces (P2P gather + 4 HEAD-SKIP | |
| ``Sum2`` operand kernels + 5 KCAT matmuls), on random weights / data of FRHead's widths. | |
| bin/devrun -t 600 -- env TT_METAL_WATCHER=2 python -u code/scripts/diag/mkh_bringup.py --stage tiny | |
| bin/devrun -t 600 -- env TT_METAL_WATCHER=2 python -u code/scripts/diag/mkh_bringup.py --stage small | |
| bin/devrun -t 900 -- python -u code/scripts/diag/mkh_bringup.py --stage real | |
| tiny: 32 rows (1 core) and 128 rows (4 cores), eager x2; small: 4,096 / 4,192 rows, eager x2, then a 2-call trace on | |
| new data; real: N = 160,000 / 120,000 / 40,000 rows + traced timing of both paths. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import sys | |
| import time | |
| import numpy as np | |
| import torch | |
| sys.path.insert(0, __file__.rsplit("/scripts/", 1)[0]) | |
| import ttnn # noqa: E402 | |
| from tt_frnet.reference.weights import Linear # noqa: E402 | |
| from tt_frnet.tt.kcat import Gathered, Sum2 # noqa: E402 | |
| from tt_frnet.tt.layers import PointLinear, free # noqa: E402 | |
| from tt_frnet.tt import mk_head # noqa: E402 | |
| from tt_frnet.tt.mk_head import run_head, supported # noqa: E402 | |
| from tt_frnet.tt.model import LOGIT_PAD, POINT_PRECISION # noqa: E402 | |
| from tt_frnet.ttaw.device import close_device, open_device # noqa: E402 | |
| WIDTHS = [(128, 128, True), (128, 256, True), (256, 128, True), (128, 64, True), (64, 27, False)] | |
| SKIPW = [128, 256, 128, 64] | |
| def make_lins(rng): | |
| lins = [] | |
| for i, (k, o, relu) in enumerate(WIDTHS): | |
| w = (rng.standard_normal((k, o)) / np.sqrt(k)).astype(np.float32) | |
| b = (rng.standard_normal(o) * 0.1).astype(np.float32) | |
| lin = Linear(name=f"mlp{i}", weight=w, bias=b, relu=relu, onnx_node="", onnx_output="") | |
| kw = dict(out_pad=LOGIT_PAD, pad_bias=-1e30) if i == len(WIDTHS) - 1 else {} | |
| lins.append(PointLinear(lin, precision=POINT_PRECISION, terms=2, kcat=2, kcat_mm=1, name=f"head.l{i}", **kw)) | |
| return lins | |
| def dev_t(a, dev, dt=ttnn.float32, layout=ttnn.TILE_LAYOUT): | |
| return ttnn.from_torch(torch.from_numpy(a), dtype=dt, layout=layout, device=dev, | |
| memory_config=ttnn.DRAM_MEMORY_CONFIG) | |
| def index_t(a, dev): | |
| return ttnn.from_torch(torch.from_numpy(a.astype(np.int64)).to(torch.int32), dtype=ttnn.uint32, | |
| layout=ttnn.ROW_MAJOR_LAYOUT, device=dev, memory_config=ttnn.DRAM_MEMORY_CONFIG) | |
| def host(t): | |
| return ttnn.to_torch(t).float().numpy() | |
| def stock_head(table, idx, skips, lins): | |
| h = Gathered(table, idx, owns=False) | |
| for lin, skip in zip(lins[:-1], skips): | |
| nxt = lin([h]) | |
| if isinstance(h, Sum2): | |
| free(h.x) | |
| h = Sum2((nxt, skip)) | |
| y = lins[-1]([h]) | |
| free(h.x) | |
| return y | |
| def data(rng, dev, n, v): | |
| table = dev_t(rng.standard_normal((1, 1, v, 128)).astype(np.float32), dev, ttnn.bfloat16, ttnn.ROW_MAJOR_LAYOUT) | |
| idx = index_t(rng.integers(0, v, size=(1, n), dtype=np.uint32), dev) | |
| skips = [dev_t(np.abs(rng.standard_normal((1, 1, n, k))).astype(np.float32), dev) for k in SKIPW] | |
| return table, idx, skips | |
| def compare(a, b, label): | |
| same = a.shape == b.shape and np.array_equal(a.view(np.uint32), b.view(np.uint32)) | |
| if not same: | |
| A, B = a.reshape(-1, a.shape[-1]), b.reshape(-1, b.shape[-1]) | |
| d = A != B | |
| r, c = np.nonzero(d) | |
| rel = np.abs(A[:, :27] - B[:, :27]).max() / max(1e-30, np.abs(B[:, :27]).max()) | |
| print(f" {label}: {int(d.sum())} / {d.size} differ; rows%32 {sorted(set((r % 32).tolist()))[:16]} " | |
| f"tile rows {sorted(set((r // 32).tolist()))[:16]} cols {sorted(set(c.tolist()))[:16]}; max rel {rel:.3e}; " | |
| f"argmax agree {np.mean(A[:, :27].argmax(1) == B[:, :27].argmax(1)) * 100:.4f} %", flush=True) | |
| if len(r): | |
| print(f" first diff ({r[0]}, {c[0]}): mk {A[r[0], c[0]]!r} stock {B[r[0], c[0]]!r}", flush=True) | |
| return same | |
| def check(dev, rng, lins, n, v, label, strict=True): | |
| table, idx, skips = data(rng, dev, n, v) | |
| assert supported(Gathered(table, idx, owns=False), skips, lins) | |
| a1 = host(run_head(Gathered(table, idx, owns=False), skips, lins)) | |
| a2 = host(run_head(Gathered(table, idx, owns=False), skips, lins)) | |
| b = host(stock_head(table, idx, skips, lins)) | |
| same = compare(a1, b, label) | |
| rep = np.array_equal(a1.view(np.uint32), a2.view(np.uint32)) | |
| print(f"mkh {label} n={n} v={v}: shape {a1.shape} == stock path {same}, eager x2 {rep}", flush=True) | |
| for t in (table, idx, *skips): | |
| ttnn.deallocate(t) | |
| if strict: | |
| assert rep, label | |
| return same and rep | |
| def check_trace(dev, rng, lins, n, v): | |
| table, idx, skips = data(rng, dev, n, v) | |
| run_head(Gathered(table, idx, owns=False), skips, lins) # compile outside the capture | |
| tid = ttnn.begin_trace_capture(dev, cq_id=0) | |
| yt = run_head(Gathered(table, idx, owns=False), skips, lins) | |
| ttnn.end_trace_capture(dev, tid, cq_id=0) | |
| ok_all = True | |
| for it in range(2): | |
| ia = rng.integers(0, v, size=(1, n), dtype=np.uint32) | |
| ttnn.copy_host_to_device_tensor(ttnn.from_torch(torch.from_numpy(ia.astype(np.int64)).to(torch.int32), | |
| dtype=ttnn.uint32, layout=ttnn.ROW_MAJOR_LAYOUT), idx) | |
| for s, k in zip(skips, SKIPW): | |
| ttnn.copy_host_to_device_tensor(ttnn.from_torch(torch.from_numpy( | |
| np.abs(rng.standard_normal((1, 1, n, k))).astype(np.float32)), dtype=ttnn.float32, | |
| layout=ttnn.TILE_LAYOUT), s) | |
| ttnn.execute_trace(dev, tid, cq_id=0, blocking=True) | |
| ok = compare(host(yt), host(stock_head(table, idx, skips, lins)), f"trace call {it}") | |
| print(f"trace call {it}: replay == stock path {ok}", flush=True) | |
| ok_all &= ok | |
| ttnn.release_trace(dev, tid) | |
| return ok_all | |
| def timing(dev, rng, lins, n, v, reps=30): | |
| table, idx, skips = data(rng, dev, n, v) | |
| res = {} | |
| for name, fn in (("stock (P2P + 4 Sum2 + 5 KCAT matmuls)", lambda: stock_head(table, idx, skips, lins)), | |
| ("MK-H", lambda: run_head(Gathered(table, idx, owns=False), skips, lins))): | |
| ttnn.deallocate(fn()) | |
| ttnn.synchronize_device(dev) | |
| tid = ttnn.begin_trace_capture(dev, cq_id=0) | |
| out = fn() | |
| ttnn.end_trace_capture(dev, tid, cq_id=0) | |
| ttnn.execute_trace(dev, tid, cq_id=0, blocking=True) | |
| t0 = time.perf_counter() | |
| for _ in range(reps): | |
| ttnn.execute_trace(dev, tid, cq_id=0, blocking=False) | |
| ttnn.synchronize_device(dev) | |
| res[name] = (time.perf_counter() - t0) * 1e3 / reps | |
| ttnn.release_trace(dev, tid) | |
| ttnn.deallocate(out) | |
| print(f"timing EB={mk_head.EB} n={n} (trace, {reps} replays): " + ", ".join(f"{a} {b:.3f} ms" for a, b in res.items()), flush=True) | |
| for t in (table, idx, *skips): | |
| ttnn.deallocate(t) | |
| def main(): | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--stage", choices=("tiny", "small", "real", "time"), default="tiny") | |
| ap.add_argument("--eb", type=int, nargs="*", default=[1, 2], help="epilogue tiles per DEST acquire to check") | |
| a = ap.parse_args() | |
| rng = np.random.default_rng(0) | |
| dev = open_device(0, dispatch="eth", trace_region_size=64 << 20) | |
| try: | |
| lins = make_lins(rng) | |
| ok = True | |
| for eb in a.eb: | |
| mk_head.EB = eb | |
| print(f"--- EB={eb}", flush=True) | |
| if a.stage == "tiny": | |
| for _ in range(2): | |
| ok &= check(dev, rng, lins, 32, 64, "tiny") | |
| ok &= check(dev, rng, lins, 128, 64, "tiny") | |
| elif a.stage == "small": | |
| for _ in range(2): | |
| ok &= check(dev, rng, lins, 4096, 2048, "small") | |
| ok &= check(dev, rng, lins, 4096 + 96, 512, "small") | |
| ok &= check_trace(dev, rng, lins, 4096, 2048) | |
| elif a.stage == "real": | |
| for n in (160000, 120000, 40000): | |
| ok &= check(dev, rng, lins, n, 131072, "real") | |
| ok &= check_trace(dev, rng, lins, 160000, 131072) | |
| for n in (160000, 120000, 40000): | |
| timing(dev, rng, lins, n, 131072) | |
| else: | |
| for n in (160000, 120000, 40000): | |
| timing(dev, rng, lins, n, 131072) | |
| print("ALL BIT-IDENTICAL" if ok else "DONE (NOT BIT-IDENTICAL)", flush=True) | |
| finally: | |
| close_device(dev) | |
| if __name__ == "__main__": | |
| main() | |