File size: 4,896 Bytes
3aa087b | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 | #!/usr/bin/env python3
# SPDX-FileCopyrightText: 2026 Tenstorrent USA, Inc.
# SPDX-License-Identifier: Apache-2.0
"""Served latency of ``POST /predict`` (stdlib only).
One keep-alive HTTP connection on loopback, one request at a time. For each ``--steps``
setting: ``--warmup`` untimed requests, then ``--n`` timed ones with the same body (the
image sent as all 3 views, the instruction, an all-zero 8-D state and a fixed seed).
Reports the client round trip and the server's own ``timing_ms`` (preprocess, inference,
total) as p50 / p90 / p99 / mean / min / max, and how many distinct action chunks came back
(1 = deterministic for a fixed seed).
python scripts/bench_http.py --url http://127.0.0.1:20000 --image media/pusht_synthetic.png \\
--steps 1,10 --n 200 --out bench_http.json
"""
from __future__ import annotations
import argparse
import base64
import hashlib
import http.client
import json
import socket
import statistics
import time
import urllib.parse
from pathlib import Path
def _pct(xs: list[float], q: float) -> float:
s = sorted(xs)
k = (len(s) - 1) * q
lo, hi = int(k), min(int(k) + 1, len(s) - 1)
return s[lo] + (s[hi] - s[lo]) * (k - lo)
def summary(xs: list[float]) -> dict:
return dict(n=len(xs), p50=_pct(xs, 0.5), p90=_pct(xs, 0.9), p99=_pct(xs, 0.99), mean=statistics.fmean(xs),
min=min(xs), max=max(xs))
def main() -> int:
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--url", required=True)
ap.add_argument("--image", required=True, type=Path, help="PNG/JPEG sent as all 3 views")
ap.add_argument("--instruction", default="push the T")
ap.add_argument("--state-dim", type=int, default=8)
ap.add_argument("--steps", default="1,10", help="num_denoising_steps settings, comma-separated")
ap.add_argument("--n", type=int, default=200, help="timed requests per setting")
ap.add_argument("--warmup", type=int, default=5)
ap.add_argument("--seed", type=int, default=42)
ap.add_argument("--timeout", type=float, default=300.0)
ap.add_argument("--out", type=Path, default=None)
a = ap.parse_args()
u = urllib.parse.urlparse(a.url)
conn = http.client.HTTPConnection(u.hostname, u.port or 80, timeout=a.timeout)
conn.connect()
conn.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) # no Nagle delay on small writes
img = base64.b64encode(a.image.read_bytes()).decode("ascii")
def get(path: str) -> dict:
conn.request("GET", path)
r = conn.getresponse()
return json.loads(r.read())
result = dict(url=a.url, image=a.image.name, image_bytes=a.image.stat().st_size, views=3,
instruction=a.instruction, state_dim=a.state_dim, seed=a.seed, n=a.n, warmup=a.warmup,
health=get("/health"), info=get("/info"), started=time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
per_steps={})
for st in [int(x) for x in a.steps.split(",") if x.strip()]:
body = json.dumps(dict(images=[img] * 3, instruction=a.instruction, state=[0.0] * a.state_dim,
num_denoising_steps=st, seed=a.seed)).encode()
rt, pre, inf, tot, hashes = [], [], [], [], set()
for i in range(a.warmup + a.n):
t0 = time.perf_counter()
conn.request("POST", "/predict", body=body, headers={"Content-Type": "application/json"})
r = conn.getresponse()
raw = r.read()
dt = (time.perf_counter() - t0) * 1e3
if r.status != 200:
raise SystemExit(f"steps {st} request {i}: HTTP {r.status} {raw[:300]!r}")
if i < a.warmup:
continue
out = json.loads(raw)
rt.append(dt)
tm = out["timing_ms"]
pre.append(tm["preprocess"]); inf.append(tm["inference"]); tot.append(tm["total"])
hashes.add(hashlib.sha256(json.dumps(out["actions"]).encode()).hexdigest())
result["per_steps"][str(st)] = dict(client_round_trip_ms=summary(rt), server_preprocess_ms=summary(pre),
server_inference_ms=summary(inf), server_total_ms=summary(tot),
distinct_outputs=len(hashes), body_bytes=len(body))
c, s = result["per_steps"][str(st)]["client_round_trip_ms"], result["per_steps"][str(st)]["server_total_ms"]
print(f"steps {st:>2}: client p50 {c['p50']:.2f} p99 {c['p99']:.2f} ms | server total p50 {s['p50']:.2f} "
f"p99 {s['p99']:.2f} ms | n {a.n} | distinct outputs {len(hashes)}", flush=True)
result["ended"] = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
if a.out:
a.out.write_text(json.dumps(result, indent=1))
return 0
if __name__ == "__main__":
raise SystemExit(main())
|