DepthPro2 / code /scripts /bench.py
changh95's picture
tt-model push depthpro2 (container)
b7e49b8 verified
Raw History Blame Contribute Delete
7.51 kB
#!/usr/bin/env python3
# SPDX-License-Identifier: Apache-2.0
"""Latency of DepthPro2 per bucket and clip length: the device engine alone (inverse depth, FOV), the Python call
(``model.infer`` / ``infer_clip``) and, with ``--url``, served requests. Prints a table and writes JSON.
# on the device (through the lock on the shared workspace box)
bin/devrun -t 3600 -- python code/scripts/bench.py --size L --resolutions vga,vga_portrait --window 16 \\
--iters 50 --json /tmp/bench_L.json
# a running server (no device access here): the shipped sample, 60 requests
python code/scripts/bench.py --url http://127.0.0.1:20000 --iters 60
# the host pipeline on the CPU reference (no device; slow): a dry run of this script
python code/scripts/bench.py --backend cpu --size S --resolutions qvga --window 2 --iters 2
Rows (median / p90 / p99 in ms; ``frames/s`` for clips):
* ``engine.inverse_depth`` -- upload, device programs, readback of one clip ``(T, 3, Hp, Wp)`` (back to back,
``--gap-ms`` between calls);
* ``engine.fov_logits`` -- the same for the focal-length estimator (when loaded);
* ``model.infer`` / ``model.infer_clip`` -- the whole Python call on uint8 frames (pre-processing, device, FOV,
post-processing), the shipped sample for the 480 x 640 bucket, a grey frame otherwise;
* ``POST /predict`` (``--url``) -- server ``timing_ms.total`` and the client round trip, the shipped sample.
"""
from __future__ import annotations
import argparse
import json
import os
import statistics
import sys
import time
from pathlib import Path
from typing import Any, Callable, Dict, List
CODE = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(CODE))
def pct(xs: List[float], q: float) -> float:
s = sorted(xs)
return s[min(len(s) - 1, max(0, int(round(q / 100.0 * (len(s) - 1)))))]
def row(name: str, shape: str, xs: List[float], frames: int = 1) -> Dict[str, Any]:
med = statistics.median(xs)
return {"what": name, "input": shape, "n": len(xs), "median_ms": round(med, 3), "p90_ms": round(pct(xs, 90), 3),
"p99_ms": round(pct(xs, 99), 3), "frames_per_s": round(1e3 * frames / med, 2) if med > 0 else None}
def timeit(fn: Callable[[], Any], iters: int, warm: int, gap_ms: float) -> List[float]:
for _ in range(warm):
fn()
out = []
for _ in range(iters):
if gap_ms:
time.sleep(gap_ms / 1e3)
t = time.perf_counter()
fn()
out.append((time.perf_counter() - t) * 1e3)
return out
def bench_model(a: argparse.Namespace) -> List[Dict[str, Any]]:
import numpy as np
import torch
from tt_depthpro2 import config as C
from tt_depthpro2.api import DepthPro2, load_sample
from tt_depthpro2.io import load_image
torch.set_num_threads(a.threads)
rows: List[Dict[str, Any]] = []
with DepthPro2.from_pretrained(a.size, resolutions=a.resolutions, window=a.window, overlap=a.overlap,
clip_lengths=a.clip_lengths, engine=a.engine, backend=a.backend,
weights_dir=a.weights_dir, fov_weights_dir=a.weights_dir) as m:
print(f"# {m!r} warm-up {m.warmup_ms} engine {m.info.get('engine')} device {m.device_info}", flush=True)
sample = load_image(load_sample()).rgb
for (h, w) in m.buckets:
hp, wp = C.padded_hw(h, w)
for t in m.clip_lengths:
if a.frames and t not in a.frames:
continue
x = torch.zeros((t, 3, hp, wp), dtype=torch.float32)
rows.append(row("engine.inverse_depth", f"{t}x3x{hp}x{wp}",
timeit(lambda: m.engine.inverse_depth(x), a.iters, a.warm, a.gap_ms), t))
if m.fov_enabled:
fh, fw = m.fov_shapes[(h, w)]
y = torch.zeros((t, 3, fh, fw), dtype=torch.float32)
rows.append(row("engine.fov_logits", f"{t}x3x{fh}x{fw}",
timeit(lambda: m.engine.fov_logits(y), a.iters, a.warm, a.gap_ms), t))
img = sample if sample.shape[:2] == (h, w) else np.full((h, w, 3), 128, np.uint8)
if t == 1:
rows.append(row("model.infer", f"{h}x{w} uint8",
timeit(lambda: m.infer(img), a.iters, a.warm, a.gap_ms)))
else:
clip = np.repeat(img[None], t, axis=0)
rows.append(row("model.infer_clip", f"{t}x{h}x{w} uint8",
timeit(lambda: m.infer_clip(clip), a.iters, a.warm, a.gap_ms), t))
print(json.dumps(rows[-1]), flush=True)
return rows
def bench_http(a: argparse.Namespace) -> List[Dict[str, Any]]:
sys.path.insert(0, str(CODE / "tt_depthpro2" / "server"))
import client as c # noqa: E402 (stdlib client of this package)
req = c.sample_request()
server, rtt = [], []
for i in range(a.warm + a.iters):
if a.gap_ms:
time.sleep(a.gap_ms / 1e3)
t = time.perf_counter()
code, body = c.post_json(a.url, "/predict", req)
dt = (time.perf_counter() - t) * 1e3
if code != 200:
raise SystemExit(f"/predict HTTP {code}: {str(body)[:300]}")
if i >= a.warm:
server.append(float(body["timing_ms"]["total"]))
rtt.append(dt)
return [row("POST /predict timing_ms.total", "sample 480x640 JPEG", server),
row("POST /predict client round trip", "sample 480x640 JPEG", rtt)]
def main() -> int:
ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
ap.add_argument("--size", default=os.environ.get("DEPTHPRO2_SIZE", "L"))
ap.add_argument("--resolutions", default=None, help="buckets (default $DEPTHPRO2_RESOLUTIONS or vga,vga_portrait)")
ap.add_argument("--window", type=int, default=None)
ap.add_argument("--overlap", type=int, default=None)
ap.add_argument("--clip-lengths", default=None, help="extra compiled clip lengths ('all', '2,4')")
ap.add_argument("--frames", type=lambda s: [int(x) for x in s.split(",")], default=None,
help="only these clip lengths")
ap.add_argument("--engine", default=None, help="per stage mk / ttnn, e.g. enc=mk,dec=ttnn,fov=mk")
ap.add_argument("--backend", default="tt", choices=["tt", "cpu"])
ap.add_argument("--weights-dir", default=None)
ap.add_argument("--iters", type=int, default=30)
ap.add_argument("--warm", type=int, default=3)
ap.add_argument("--gap-ms", type=float, default=0.0, help="idle time between calls (served-request pacing)")
ap.add_argument("--threads", type=int, default=4)
ap.add_argument("--url", help="benchmark a running server instead of building a model")
ap.add_argument("--json", type=Path, help="write the rows here")
a = ap.parse_args()
rows = bench_http(a) if a.url else bench_model(a)
print(f"\n| what | input | n | median ms | p90 ms | p99 ms | frames/s |\n| --- | --- | --- | --- | --- | --- | --- |")
for r in rows:
print(f"| {r['what']} | {r['input']} | {r['n']} | {r['median_ms']} | {r['p90_ms']} | {r['p99_ms']} | "
f"{r['frames_per_s']} |")
if a.json:
a.json.write_text(json.dumps({"args": {k: (str(v) if isinstance(v, Path) else v) for k, v in vars(a).items()},
"rows": rows}, indent=1))
return 0
if __name__ == "__main__":
sys.exit(main())