# SPDX-License-Identifier: Apache-2.0 """Speed of the packaged Gaze-LLE on one p150, through the public Python API (batch 1, warm). python scripts/bench_p150.py --image media/source_1.png --json bench.json [--heads 1,3,10] [--iters 500] Opens the chip the way ``GazeLLE.from_pretrained()`` does (ETH dispatch when available, 1 command queue, 12x10 grid, pinned weights from the HF cache) and reports p50 / p99 / min / mean (ms) of: * ``device``: device time per forward = back-to-back replays of the captured whole-forward trace of the head-count bucket (``--replays`` replays queued without waiting, one synchronize; per-replay time over ``--rounds`` rounds); * ``replay_sync``: one trace replay followed by a synchronize (dispatch + device + completion round trip); * ``call_*``: the Python ``model(image, boxes)`` call, end to end (host preprocessing, upload, trace, readback, output decoding) for these inputs: - ``call_png``: the sample PNG path (decode + resize to 448x448) with its head boxes in pixels (``--boxes``); - ``call_array``: the sample decoded once to a uint8 RGB array (resize per call) with the same boxes; - ``call_u8_448_N``: a 448x448 uint8 array (no host resize) with N head boxes, for each N of ``--heads``. The sample's outputs (gaze targets, in/out) are stored too, to compare with the served response. """ from __future__ import annotations import argparse import json import os import platform import statistics import time from pathlib import Path import numpy as np from PIL import Image SAMPLE_BOXES = "116,28,176,104;269,37,301,81;87,57,107,76" # media/source_1.png, pixels (the smoke test's boxes) # Normalised boxes for the N-head rows: the 3 sample faces first, then 7 more distinct boxes (each covers cells of # the 32x32 feature grid). EXTRA_BOXES = [(0.232, 0.084, 0.352, 0.311), (0.538, 0.111, 0.602, 0.243), (0.174, 0.171, 0.214, 0.228), (0.38, 0.10, 0.53, 0.43), (0.40, 0.15, 0.60, 0.60), (0.1, 0.1, 0.2, 0.3), (0.7, 0.1, 0.8, 0.3), (0.3, 0.2, 0.6, 0.5), (0.05, 0.5, 0.15, 0.7), (0.85, 0.5, 0.95, 0.7)] def stats(ts): ts = sorted(ts) n = len(ts) return {"n": n, "p50": statistics.median(ts), "p99": ts[min(n - 1, int(round(0.99 * (n - 1))))], "min": ts[0], "max": ts[-1], "mean": statistics.fmean(ts)} def timed(fn, iters, warmup): for _ in range(warmup): fn() ts = [] for _ in range(iters): t0 = time.perf_counter() fn() ts.append((time.perf_counter() - t0) * 1e3) return stats(ts) def fmt(name, s): return f"{name:<22} p50 {s['p50']:8.3f} p99 {s['p99']:8.3f} min {s['min']:8.3f} mean {s['mean']:8.3f} ms (n={s['n']})" def main(): ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) ap.add_argument("--image", default="media/source_1.png", help="sample image (PNG/JPEG)") ap.add_argument("--boxes", default=SAMPLE_BOXES, help="head boxes of the sample, pixels: x1,y1,x2,y2;...") ap.add_argument("--heads", default="1,3,10", help="head counts for the device and 448x448-array rows") ap.add_argument("--iters", type=int, default=500, help="timed Python calls per row") ap.add_argument("--warmup", type=int, default=20, help="untimed calls before each row") ap.add_argument("--rounds", type=int, default=20, help="device rows: rounds of back-to-back replays") ap.add_argument("--replays", type=int, default=500, help="device rows: replays per round") ap.add_argument("--dispatch", default=os.environ.get("GAZE_LLE_DISPATCH", "auto")) ap.add_argument("--json", default=None, help="write all results here") args = ap.parse_args() import torch import ttnn from gaze_lle import GazeLLE heads = [int(h) for h in args.heads.split(",")] boxes_px = [[float(v) for v in b.split(",")] for b in args.boxes.split(";")] torch.set_grad_enabled(False) t0 = time.perf_counter() model = GazeLLE.from_pretrained(dispatch=args.dispatch, max_heads=max(10, max(heads))) load_s = time.perf_counter() - t0 info = model.info() g = model.device.compute_with_storage_grid_size() res = {"script": "scripts/bench_p150.py", "args": vars(args), "load_s": round(load_s, 2), "dispatch": info.get("dispatch"), "grid": f"{g.x}x{g.y}", "input": info.get("input"), "torch_threads": torch.get_num_threads(), "host": platform.node(), "python": platform.python_version(), "loadavg_start": os.getloadavg(), "rows": {}} print(f"model ready in {load_s:.1f} s: dispatch={res['dispatch']} grid={res['grid']} input={res['input']}", flush=True) tt = model._tt dev = model.device # ---- device rows: back-to-back replays of the merged whole-forward trace (uint8 input kind) for n in heads: b = model._bucket_of(n) d = tt._full[("u8", b)] tid = d["trace"] ttnn.execute_trace(dev, tid, cq_id=0, blocking=False) ttnn.synchronize_device(dev) per = [] for _ in range(args.rounds): t = time.perf_counter() for _ in range(args.replays): ttnn.execute_trace(dev, tid, cq_id=0, blocking=False) ttnn.synchronize_device(dev) per.append((time.perf_counter() - t) * 1e3 / args.replays) res["rows"][f"device_{n}"] = dict(stats(per), bucket=b, replays_per_round=args.replays) print(fmt(f"device N={n} (b{b})", res["rows"][f"device_{n}"]), flush=True) def replay_sync(): ttnn.execute_trace(dev, tid, cq_id=0, blocking=False) ttnn.synchronize_device(dev) res["rows"][f"replay_sync_{n}"] = dict(timed(replay_sync, args.iters, args.warmup), bucket=b) print(fmt(f"replay+sync N={n}", res["rows"][f"replay_sync_{n}"]), flush=True) # ---- Python model() calls img_path = str(Path(args.image)) with Image.open(img_path) as im: arr = np.asarray(im.convert("RGB")).copy() res["sample"] = {"image": img_path, "size": [int(arr.shape[1]), int(arr.shape[0])], "boxes_px": boxes_px} r = model(img_path, boxes_px, bbox_format="pixels") res["sample"]["gaze_xy"] = np.round(r.gaze_xy, 2).tolist() res["sample"]["inout"] = [round(float(v), 4) for v in r.inout] res["sample"]["score"] = [round(float(v), 4) for v in r.score] print("sample:", r, flush=True) res["rows"]["call_png"] = timed(lambda: model(img_path, boxes_px, bbox_format="pixels").gaze_xy, args.iters, args.warmup) print(fmt(f"model(png path) N={len(boxes_px)}", res["rows"]["call_png"]), flush=True) res["rows"]["call_array"] = timed(lambda: model(arr, boxes_px, bbox_format="pixels").gaze_xy, args.iters, args.warmup) print(fmt(f"model(array) N={len(boxes_px)}", res["rows"]["call_array"]), flush=True) a448 = np.asarray(Image.fromarray(arr).resize((448, 448), Image.BILINEAR)).copy() for n in heads: bx = EXTRA_BOXES[:n] res["rows"][f"call_u8_448_{n}"] = timed(lambda: model(a448, bx).gaze_xy, args.iters, args.warmup) print(fmt(f"model(u8 448) N={n}", res["rows"][f"call_u8_448_{n}"]), flush=True) res["loadavg_end"] = os.getloadavg() model.close() if args.json: Path(args.json).write_text(json.dumps(res, indent=1)) print("wrote", args.json) if __name__ == "__main__": main()