#!/usr/bin/env python3 """LANE_LSM bring-up probe (OPT2 round 6, H4 of OPT_PLAN A7: the lane seg fusion's 9-class log-softmax on the device). The seg fusion (host.temporal.SegFusion) takes lp = v - (mx + log(sum_k exp(v_k - mx))) of the [800 x 500 x 9] fp32 lane logits every frame (6-7 ms of host time). Candidates on the device, on the refiner's fp32 TILE output [1, 1, 400000, 9]: ``moreh`` = ttnn.moreh_logsoftmax(dim=3); ``smlog`` = log(softmax(v, numeric_stable)). Checked: max |error| vs a float64 log-softmax next to the host numpy fp32 one, the argmax agreement, eager x2 stability, then each as a traced replay. METEOR_DEVICE_OK=1 bin/devrun -t 300 -- python -u code/scripts/lane_lsm_probe.py --rows 64 METEOR_DEVICE_OK=1 bin/devrun -t 600 -- python -u code/scripts/lane_lsm_probe.py --rows 400000 --trace """ from __future__ import annotations import argparse import sys import time import numpy as np def main() -> int: ap = argparse.ArgumentParser() ap.add_argument("--rows", type=int, default=64) ap.add_argument("--trace", action="store_true") ap.add_argument("--reps", type=int, default=10) ap.add_argument("--modes", default="moreh,smlog,manual,nomax") a = ap.parse_args() import torch import ttnn from tt_meteor.host.temporal import log_softmax9_planar from tt_meteor.tt.layers import mm_config from tt_meteor.ttaw.device import open_device dev = open_device(dispatch="eth", trace_region_size=64 << 20) rng = np.random.default_rng(0) n = a.rows v = np.clip(rng.standard_normal((n, 9)) * 8, -20, 20).astype(np.float32) + \ (8 * np.tanh(rng.standard_normal((n, 9)))).astype(np.float32) v[: min(n, 4)] = np.float32(3.25) # ties ref = v.astype(np.float64) ref = ref - (ref.max(1, keepdims=True) + np.log(np.exp(ref - ref.max(1, keepdims=True)).sum(1, keepdims=True))) host = log_softmax9_planar(v.T.reshape(9, 1, n)).reshape(9, n).T print(f"[{n}] host numpy fp32 max|err| vs float64 {np.abs(host - ref).max():.3g}", flush=True) x = ttnn.from_torch(torch.from_numpy(v.reshape(1, 1, n, 9)), dtype=ttnn.float32, layout=ttnn.TILE_LAYOUT, device=dev, memory_config=ttnn.DRAM_MEMORY_CONFIG) cfg = mm_config() def manual(t): # lse = mx + log(sum_k exp(v_k - mx)), lp = v - lse (the host's operations) mx = ttnn.max(t, dim=-1, keepdim=True) e = ttnn.exp(ttnn.subtract(t, mx)) se = ttnn.sum(e, dim=-1, keepdim=True, compute_kernel_config=cfg) return ttnn.subtract(t, ttnn.add(mx, ttnn.log(se))) def nomax(t): # |v| <= 28 after the refiner: exp cannot overflow without the max se = ttnn.sum(ttnn.exp(t), dim=-1, keepdim=True, compute_kernel_config=cfg) return ttnn.subtract(t, ttnn.log(se)) fns = {"moreh": lambda t: ttnn.moreh_logsoftmax(t, 3, compute_kernel_config=cfg), "smlog": lambda t: ttnn.log(ttnn.softmax(t, dim=-1, numeric_stable=True, compute_kernel_config=cfg)), "manual": manual, "nomax": nomax} bad = 0 res = {} for m in a.modes.split(","): try: y = fns[m](x) except Exception as e: # noqa: BLE001 print(f" {m}: FAILED {str(e).splitlines()[0][:200]}", flush=True) continue got = ttnn.to_torch(y).float().numpy().reshape(n, 9) err = np.abs(got - ref).max() agree = np.mean(np.argmax(got, 1) == np.argmax(v, 1)) y2 = fns[m](x) stable = np.array_equal(ttnn.to_torch(y2).float().numpy().reshape(n, 9), got) print(f" {m}: {list(y.shape)} {y.layout} {y.dtype}; max|err| vs float64 {err:.3g}, vs host fp32 " f"{np.abs(got - host).max():.3g}; argmax agreement {agree:.6f}; eager x2 {'stable' if stable else 'UNSTABLE'}", flush=True) bad += 0 if stable and np.isfinite(got).all() else 1 res[m] = got ttnn.deallocate(y) ttnn.deallocate(y2) if a.trace: ttnn.deallocate(fns[m](x)) tid = ttnn.begin_trace_capture(dev, cq_id=0) y = fns[m](x) 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).float().numpy().reshape(n, 9), got) bad += 0 if okt else 1 print(f" {m} trace call {i + 1}: {'IDENTICAL' if okt else 'DIFFERENT'}", flush=True) ttnn.release_trace(dev, tid) ttnn.deallocate(y) print(f" {m} 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())