Download code/scripts/dev_bench_lift.py from changh95/METEOR-2-p150: direct link, hf CLI and curl.
- Browser
- Download file 8.71 kB
-
https://huggingface.co/changh95/METEOR-2-p150/resolve/main/code/scripts/dev_bench_lift.py
- Command line
-
hf download hf://changh95/METEOR-2-p150/code/scripts/dev_bench_lift.py
-
curl -L -o dev_bench_lift.py https://huggingface.co/changh95/METEOR-2-p150/resolve/main/code/scripts/dev_bench_lift.py
8.71 kB
| #!/usr/bin/env python3 | |
| # SPDX-License-Identifier: Apache-2.0 | |
| """Micro-benchmarks of the polar product and the lift (stock-op variants), on real ctx / prob from one frame. | |
| bin/devrun python scripts/dev_bench_lift.py --name valday_0040 | |
| """ | |
| import argparse | |
| import os | |
| import sys | |
| import time | |
| import numpy as np | |
| sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..")) | |
| def main(): | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--name", default="valday_0040") | |
| a = ap.parse_args() | |
| import torch | |
| import ttnn | |
| from tt_meteor2.host.calib import lift_tables | |
| from tt_meteor2.reference import config as C | |
| from tt_meteor2.reference.weights import Meteor2Weights | |
| from tt_meteor2.tt.model import TtMeteor2 | |
| from tt_meteor2.ttaw.device import close_device, open_device | |
| from tt_meteor2.ttaw.metrics import pcc | |
| from tt_meteor2.ttaw.ops.conv import FeatureMap | |
| from tt_meteor2.ttaw.precision import compute_kernel_config | |
| z = dict(np.load(f"/data/inputs/{a.name}.npz")) | |
| gold = np.load(f"/data/goldens/gather/{a.name}.npz") | |
| w = Meteor2Weights("/weights/meteor2_gather.onnx") | |
| dev = open_device(0, dispatch="eth", l1_small_size=32768, trace_region_size=128 << 20) | |
| try: | |
| m = TtMeteor2(dev, w) | |
| tb = lift_tables(z["K"][0], z["T_cam_ego"][0], w.bev_points(), w.paint_z_fill()) | |
| m.set_calibration(tb) | |
| xt, geo = m.host_input(z["imgs"]) | |
| x = ttnn.from_torch(xt, dtype=ttnn.bfloat16, layout=ttnn.ROW_MAJOR_LAYOUT, device=dev) | |
| c1, fx = m.image(FeatureMap(x, *geo)) | |
| ctx, prob, paint = m.heads2d(c1, fx) | |
| pol = m.polar(ctx, prob) | |
| ttnn.synchronize_device(dev) | |
| def bench(name, fn, n=5): | |
| r = fn() | |
| ttnn.synchronize_device(dev) | |
| tid = ttnn.begin_trace_capture(dev, cq_id=0) | |
| r = fn() | |
| ttnn.end_trace_capture(dev, tid, cq_id=0) | |
| ts = [] | |
| for _ in range(n): | |
| t = time.perf_counter() | |
| ttnn.execute_trace(dev, tid, cq_id=0, blocking=False) | |
| ttnn.synchronize_device(dev) | |
| ts.append((time.perf_counter() - t) * 1e3) | |
| ttnn.release_trace(dev, tid) | |
| print(f"{name:48s} {np.median(ts):7.2f} ms", flush=True) | |
| return r | |
| n, h, wd = ctx.batch, ctx.height, ctx.width | |
| ckc = compute_kernel_config("HiFi4", fp32_acc=True, packer_l1_acc=True) | |
| ckc2 = compute_kernel_config("HiFi2", fp32_acc=True, packer_l1_acc=True) | |
| def per_col(fm): | |
| t = ttnn.reshape(ttnn.to_layout(fm.tensor, ttnn.ROW_MAJOR_LAYOUT), (n, h, wd, fm.channels)) | |
| t = ttnn.permute(t, (0, 2, 1, 3)) | |
| return ttnn.to_layout(ttnn.reshape(t, (n * wd, h, fm.channels)), ttnn.TILE_LAYOUT) | |
| pc = bench("polar: per-column prob (rm permute + tile)", lambda: per_col(prob)) | |
| cc = per_col(ctx) | |
| bench("polar: matmul transpose_a HiFi4", lambda: ttnn.matmul(pc, cc, transpose_a=True, dtype=ttnn.bfloat16, | |
| compute_kernel_config=ckc)) | |
| pct = bench("polar: ttnn.transpose(-2,-1) of A", lambda: ttnn.transpose(pc, -2, -1)) | |
| bench("polar: matmul pre-transposed A HiFi4", lambda: ttnn.matmul(pct, cc, dtype=ttnn.bfloat16, | |
| compute_kernel_config=ckc)) | |
| bench("polar: matmul pre-transposed A HiFi2", lambda: ttnn.matmul(pct, cc, dtype=ttnn.bfloat16, | |
| compute_kernel_config=ckc2)) | |
| # 4-D batch [8, 288, 64, 192] x [8, 288, 192, 64] | |
| pct4 = ttnn.reshape(pct, (n, wd, 64, int(pct.shape[-1]))) | |
| cc4 = ttnn.reshape(cc, (n, wd, int(cc.shape[-2]), 64)) | |
| bench("polar: matmul 4-D batch pre-transposed", lambda: ttnn.matmul(pct4, cc4, dtype=ttnn.bfloat16, | |
| compute_kernel_config=ckc)) | |
| # ---- lift variants | |
| # tap tables: 4 bilinear taps per (cam, cell), K = 4 * max cams slots, rows of the polar map [n, b, w] | |
| g = tb.lift_grid.reshape(C.N_CAM, -1, 2).astype(np.float64) # same taps as host.calib | |
| col = (g[..., 0] + 1) * C.FEAT_W / 2 - 0.5 | |
| bn = (g[..., 1] + 1) * C.N_BINS / 2 - 0.5 | |
| ok = g[..., 0] > -2 | |
| cnt = ok.sum(0) | |
| kmax = 4 * int(cnt.max()) | |
| sent = C.N_CAM * C.N_BINS * C.FEAT_W | |
| idx = np.full((kmax, C.BEV_CELLS), sent, np.uint32) | |
| wt = np.zeros((kmax, C.BEV_CELLS), np.float32) | |
| fill = np.zeros(C.BEV_CELLS, np.int64) | |
| inv = 0.5 / np.maximum(cnt, 1) | |
| for cam in range(C.N_CAM): | |
| cells = np.nonzero(ok[cam])[0] | |
| x0 = np.floor(col[cam, cells]).astype(np.int64) | |
| y0 = np.floor(bn[cam, cells]).astype(np.int64) | |
| fxx = col[cam, cells] - x0 | |
| fyy = bn[cam, cells] - y0 | |
| for dy, wy in ((0, 1 - fyy), (1, fyy)): | |
| for dx, wx in ((0, 1 - fxx), (1, fxx)): | |
| xi = np.clip(x0 + dx, 0, C.FEAT_W - 1) | |
| yi = np.clip(y0 + dy, 0, C.N_BINS - 1) | |
| k = fill[cells] | |
| idx[k, cells] = ((cam * C.N_BINS + yi) * C.FEAT_W + xi).astype(np.uint32) | |
| wt[k, cells] = (wx * wy * inv[cells]).astype(np.float32) | |
| fill[cells] += 1 | |
| print("tap slots", kmax, "cells by camera count", np.bincount(cnt).tolist(), flush=True) | |
| idx_d = ttnn.from_torch(torch.from_numpy(idx.reshape(1, -1)), dtype=ttnn.uint32, layout=ttnn.ROW_MAJOR_LAYOUT, | |
| device=dev) | |
| wt_full = np.repeat(wt.reshape(-1, 1), 64, 1)[None, None] | |
| wt_b = ttnn.from_torch(torch.from_numpy(wt_full), dtype=ttnn.bfloat16, layout=ttnn.TILE_LAYOUT, device=dev) | |
| wt_f = ttnn.from_torch(torch.from_numpy(wt_full), dtype=ttnn.float32, layout=ttnn.TILE_LAYOUT, device=dev) | |
| wt_col = ttnn.from_torch(torch.from_numpy(wt.reshape(1, 1, -1, 1).copy()), dtype=ttnn.float32, | |
| layout=ttnn.TILE_LAYOUT, device=dev) | |
| rows = ttnn.reshape(pol, (1, 1, sent, 64)) | |
| table = bench("lift: polar rows + zero row (pad)", lambda: ttnn.pad(rows, [(0, 0), (0, 0), (0, 1), (0, 0)], 0.0)) | |
| def gathered(): | |
| gr = ttnn.embedding(idx_d, table, layout=ttnn.TILE_LAYOUT, padding_idx=sent, | |
| embeddings_type=ttnn.EmbeddingsType.PADDED) | |
| return ttnn.reshape(gr, (1, 1, kmax * C.BEV_CELLS, 64)) | |
| gr = bench(f"lift: embedding {kmax} x 100000 rows", gathered) | |
| def wsum_bf16(): | |
| p = ttnn.multiply(gr, wt_b) | |
| return ttnn.sum(ttnn.reshape(p, (kmax, 1, C.BEV_CELLS, 64)), dim=0, keepdim=True) | |
| rb = bench("lift: x bf16 weights + slot sum", wsum_bf16) | |
| def wsum_f32(): | |
| p = ttnn.multiply(ttnn.typecast(gr, ttnn.float32), wt_f) | |
| return ttnn.sum(ttnn.reshape(p, (kmax, 1, C.BEV_CELLS, 64)), dim=0, keepdim=True) | |
| rf = bench("lift: x fp32 weights + slot sum (fp32)", wsum_f32) | |
| try: | |
| rc = bench("lift: x fp32 column-broadcast weights", lambda: ttnn.multiply(ttnn.typecast(gr, ttnn.float32), wt_col)) | |
| except Exception as e: # noqa: BLE001 | |
| print("column broadcast failed:", type(e).__name__, str(e)[:200]) | |
| # no zero row: unused slots read row 0 with weight 0 (GENERIC embedding, no pad) | |
| idx0 = np.where(idx == sent, 0, idx).astype(np.uint32) | |
| idx0_d = ttnn.from_torch(torch.from_numpy(idx0.reshape(1, -1)), dtype=ttnn.uint32, layout=ttnn.ROW_MAJOR_LAYOUT, | |
| device=dev) | |
| def gathered_generic(): | |
| gr = ttnn.embedding(idx0_d, rows, layout=ttnn.TILE_LAYOUT) | |
| return ttnn.reshape(gr, (1, 1, kmax * C.BEV_CELLS, 64)) | |
| gr2 = bench(f"lift: embedding GENERIC {kmax} x 100000 rows (no pad)", gathered_generic) | |
| def wsum_generic(): | |
| p = ttnn.multiply(gr2, wt_b) | |
| return ttnn.sum(ttnn.reshape(p, (kmax, 1, C.BEV_CELLS, 64)), dim=0, keepdim=True) | |
| rg = bench("lift: GENERIC x bf16 weights + slot sum", wsum_generic) | |
| ref = gold["tap.lift.bev"][0].reshape(64, -1).T | |
| for name, r in (("bf16 weights", rb), ("fp32 weights", rf), ("generic no-pad", rg)): | |
| v = ttnn.to_torch(r).float().numpy().reshape(-1, 64)[: C.BEV_CELLS] | |
| print(f" accuracy {name}: pcc {pcc(v, ref):.7f} max_abs {np.abs(v - ref).max():.3e}") | |
| finally: | |
| close_device(dev) | |
| if __name__ == "__main__": | |
| main() | |