Download code/scripts/first_call_bench.py from changh95/gaze-lle-p150: direct link, hf CLI and curl.
- Browser
- Download file 5.6 kB
-
https://huggingface.co/changh95/gaze-lle-p150/resolve/main/code/scripts/first_call_bench.py
- Command line
-
hf download hf://changh95/gaze-lle-p150/code/scripts/first_call_bench.py
-
curl -L -o first_call_bench.py https://huggingface.co/changh95/gaze-lle-p150/resolve/main/code/scripts/first_call_bench.py
5.6 kB
| # SPDX-License-Identifier: Apache-2.0 | |
| """First-call latency of the Python API in a FRESH process (one variant per process). | |
| # from the model repo root, in a tt-metal environment with this package installed | |
| timeout -s INT 600 python code/scripts/first_call_bench.py --heads 3 --input png --out /tmp/x.pt | |
| Times ``GazeLLE.from_pretrained()``, then calls 1..10 of ONE variant (head count N, input kind), each with a NEW | |
| real image (repo media/ pictures and their mirror images; none of them is the warm-up input) and new boxes, then | |
| ``--steady`` more calls for the steady median. Prints one JSON line; ``--out`` saves the call 1..10 outputs (for the | |
| bit-identical check before/after a change). | |
| Input kinds: u8 = (448, 448, 3) uint8 array (device fast path); pil = PIL image at the original size (host resize); | |
| png / jpg = file path (decode + resize); f32 = float (H, W, 3) array in [0, 1]; batch = predict_batch of 4 images. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| import os | |
| import statistics | |
| import sys | |
| import tempfile | |
| import time | |
| from pathlib import Path | |
| T0 = time.perf_counter() | |
| REPO = Path(__file__).resolve().parents[2] | |
| def _write_files(kind: str, tmp: Path) -> list: | |
| """png / jpg inputs: written by a CHILD process, so this process has not used PIL's decoders before the API.""" | |
| import subprocess | |
| code = (f"import sys; sys.path.insert(0, {str(Path(__file__).parent)!r}); from first_call_bench import _images; " | |
| f"_images({kind!r}, __import__('pathlib').Path({str(tmp)!r}), write=True)") | |
| subprocess.run([sys.executable, "-c", code], check=True) | |
| return [str(p) for p in sorted(tmp.glob(f"im*.{kind}"), key=lambda p: int(p.stem[2:]))] | |
| def _images(kind: str, tmp: Path, write: bool = False): | |
| if kind in ("png", "jpg") and not write: | |
| return _write_files(kind, tmp) | |
| import numpy as np | |
| from PIL import Image | |
| srcs = sorted((REPO / "media").glob("*.png")) | |
| ims = [] | |
| for p in srcs: | |
| with Image.open(p) as im: | |
| ims.append(im.convert("RGB")) | |
| ims += [im.transpose(Image.FLIP_LEFT_RIGHT) for im in ims] # 16 distinct real pictures | |
| out = [] | |
| for i, im in enumerate(ims): | |
| if kind == "u8": | |
| out.append(np.array(im.resize((448, 448), Image.BILINEAR), dtype=np.uint8)) | |
| elif kind in ("pil", "batch"): | |
| out.append(im) | |
| elif kind == "f32": | |
| out.append(np.asarray(im, dtype=np.float32) / 255.0) | |
| elif kind in ("png", "jpg"): | |
| f = tmp / f"im{i}.{kind}" | |
| im.save(f, quality=90) if kind == "jpg" else im.save(f) | |
| out.append(str(f)) | |
| else: | |
| raise SystemExit(f"unknown --input {kind}") | |
| return out | |
| def _boxes(rng, n): | |
| bs = [] | |
| for _ in range(n): | |
| w, h = rng.uniform(0.08, 0.2), rng.uniform(0.08, 0.2) | |
| x, y = rng.uniform(0, 1 - w), rng.uniform(0, 1 - h) | |
| bs.append([x, y, x + w, y + h]) | |
| return bs | |
| def main() -> None: | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--heads", type=int, default=1) | |
| ap.add_argument("--input", default="u8") | |
| ap.add_argument("--steady", type=int, default=96) | |
| ap.add_argument("--out", default="") | |
| ap.add_argument("--kwargs", default="{}", help="JSON kwargs for from_pretrained") | |
| args = ap.parse_args() | |
| import numpy as np | |
| tmp = Path(tempfile.mkdtemp(prefix="gaze_fc_")) | |
| images = _images(args.input, tmp) | |
| rng = np.random.default_rng(1000 + args.heads) | |
| boxes = [_boxes(rng, args.heads) for _ in range(len(images))] | |
| t_import0 = time.perf_counter() | |
| from gaze_lle import GazeLLE | |
| t_import = time.perf_counter() - t_import0 | |
| t = time.perf_counter() | |
| model = GazeLLE.from_pretrained(**json.loads(args.kwargs)) | |
| t_fp = time.perf_counter() - t | |
| lat, outs = [], [] | |
| def call(i): | |
| im, bb = images[i % len(images)], boxes[i % len(boxes)] | |
| t = time.perf_counter() | |
| if args.input == "batch": | |
| j = [(i * 4 + k) % len(images) for k in range(4)] | |
| r = model.predict_batch([images[k] for k in j], [boxes[k] for k in j]) | |
| _ = [x.gaze_xy for x in r] | |
| dt = time.perf_counter() - t | |
| return dt, r | |
| r = model(im, bb) | |
| _ = r.gaze_xy | |
| return time.perf_counter() - t, [r] | |
| for i in range(10): | |
| dt, r = call(i) | |
| lat.append(dt * 1e3) | |
| outs.append([(x.heatmap.clone(), x.inout.clone()) for x in r]) | |
| steady = [call(10 + i)[0] * 1e3 for i in range(args.steady)] | |
| med = statistics.median(steady) | |
| # same picture as call 1 (image sizes differ, so host resize / decode time differs per picture) | |
| same = [steady[i] for i in range(len(steady)) if (10 + i) % len(images) == 0] | |
| same_med = statistics.median(same) if same else float("nan") | |
| rec = dict(heads=args.heads, input=args.input, kwargs=json.loads(args.kwargs), import_s=round(t_import, 2), | |
| from_pretrained_s=round(t_fp, 2), call1_ms=round(lat[0], 3), call2_ms=round(lat[1], 3), | |
| call10_ms=round(lat[9], 3), steady_median_ms=round(med, 3), steady_min_ms=round(min(steady), 3), | |
| first_over_median=round(lat[0] / med, 3), | |
| same_image_median_ms=round(same_med, 3), first_over_same_image=round(lat[0] / same_med, 3), calls_ms=[round(x, 3) for x in lat], | |
| info_buckets=model.info().get("fused", {}).get("trace_buckets")) | |
| model.close() | |
| if args.out: | |
| import torch | |
| torch.save(outs, args.out) | |
| print("RESULT " + json.dumps(rec), flush=True) | |
| if __name__ == "__main__": | |
| main() | |