# SPDX-License-Identifier: Apache-2.0 """Captured-trace accuracy and speed of each network (run under bin/devrun): python -m tt_visionpilot.tests.dev_bench [--nets ...] [--weight-terms 1|2] [--iters 50] [--json OUT] Per network: build the ``NetRunner`` (trace), capture, then for every golden sample run the full call (upload of the uint8 image, replay, packed readback, host tail) and compare the outputs with the onnxruntime golden of the published file; then time ``iters`` calls (median / p90 / max) and the device part alone (upload + replay + read). """ from __future__ import annotations import argparse import json import time from pathlib import Path import numpy as np from ..graph import Graph from ..models import IMAGENET_MEAN, IMAGENET_STD, NETWORKS def to_u8_rgb(x: np.ndarray, imagenet: bool) -> np.ndarray: """The golden float32 NCHW input back to the uint8 RGB image it came from (exact).""" a = x[0].transpose(1, 2, 0).astype(np.float64) if imagenet: a = a * np.asarray(IMAGENET_STD) + np.asarray(IMAGENET_MEAN) return np.clip(np.rint(a * 255.0), 0, 255).astype(np.uint8) def rel_l2(a, b) -> float: return float(np.linalg.norm(np.asarray(a, np.float64) - b) / max(np.linalg.norm(b), 1e-30)) def main(argv=None) -> int: from ..tt.runner import NetRunner from ..ttaw.device import close_device, describe_device, open_device ap = argparse.ArgumentParser() ap.add_argument("--nets", nargs="*", default=list(NETWORKS)) ap.add_argument("--data", default="/weights/port") ap.add_argument("--weight-terms", type=int, default=1) ap.add_argument("--iters", type=int, default=50) ap.add_argument("--json", default=None) args = ap.parse_args(argv) dev = open_device(0, dispatch="eth", num_command_queues=1, l1_small_size=32768, trace_region_size=96 << 20, allow_fallback=False) print(json.dumps(describe_device(dev))) report = {} try: for name in args.nets: spec = NETWORKS[name] g = Graph(Path(args.data) / "folded" / f"{name}.onnx") z = np.load(Path(args.data) / "golden" / f"{name}.npz") samples = sorted({int(k.split("/")[0]) for k in z.files}) t0 = time.perf_counter() r = NetRunner(dev, spec, g, weight_terms=args.weight_terms) r.capture() t_build = time.perf_counter() - t0 acc = [] for k in samples: imgs = {i: to_u8_rgb(z[f"{k}/in/{i}"], spec.imagenet) for i in spec.inputs} outs = r(imgs) acc.append({o: {"rel_l2": rel_l2(outs[o], z[f"{k}/out/{o}"]), "max_abs": float(np.abs(outs[o] - z[f"{k}/out/{o}"]).max()), "ref_absmax": float(np.abs(z[f"{k}/out/{o}"]).max()), "got": np.asarray(outs[o]).ravel()[:4].tolist(), "ref": z[f"{k}/out/{o}"].ravel()[:4].tolist()} for o in g.outputs}) imgs = {i: to_u8_rgb(z[f"0/in/{i}"], spec.imagenet) for i in spec.inputs} full, dev_only = [], [] for _ in range(args.iters): t = time.perf_counter() r(imgs) full.append((time.perf_counter() - t) * 1e3) for _ in range(args.iters): t = time.perf_counter() r.run_device(imgs) dev_only.append((time.perf_counter() - t) * 1e3) # replay alone (no upload, no read), back to back r.runner.replay(r.key, n=1) import ttnn ttnn.synchronize_device(dev) t = time.perf_counter() r.runner.replay(r.key, n=args.iters) ttnn.synchronize_device(dev) replay_ms = (time.perf_counter() - t) * 1e3 / args.iters st = lambda v: {"median": float(np.median(v)), "p90": float(np.percentile(v, 90)), "max": float(max(v))} report[name] = {"build_capture_s": t_build, "accuracy": acc, "full_ms": st(full), "device_ms": st(dev_only), "replay_ms": replay_ms, "steps": len(r.plan.steps), "weight_terms": args.weight_terms} print(f"== {name} (weight_terms={args.weight_terms}): build+capture {t_build:.1f} s, replay " f"{replay_ms:.2f} ms, device call median {st(dev_only)['median']:.2f} ms, full call median " f"{st(full)['median']:.2f} ms (p90 {st(full)['p90']:.2f}, max {st(full)['max']:.2f})") for k, a in enumerate(acc): print(" sample", k, {o: f"relL2 {v['rel_l2']:.3g} max|d| {v['max_abs']:.3g} (|ref| {v['ref_absmax']:.3g})" for o, v in a.items()}) r.release() finally: close_device(dev) if args.json: Path(args.json).write_text(json.dumps(report, indent=1)) return 0 if __name__ == "__main__": raise SystemExit(main())