Download code/scripts/serve_check.py from changh95/gaze-lle-p150: direct link, hf CLI and curl.
- Browser
- Download file 4.54 kB
-
https://huggingface.co/changh95/gaze-lle-p150/resolve/main/code/scripts/serve_check.py
- Command line
-
hf download hf://changh95/gaze-lle-p150/code/scripts/serve_check.py
-
curl -L -o serve_check.py https://huggingface.co/changh95/gaze-lle-p150/resolve/main/code/scripts/serve_check.py
4.54 kB
| # SPDX-License-Identifier: Apache-2.0 | |
| """Served-path check against a RUNNING server: correctness vs the torch fp32 reference + timing. | |
| python scripts/serve_check.py --url http://127.0.0.1:20000 [--heads 1,3,5,10] [--reqs 30] | |
| For each N, POSTs media/source_1.png with the first N boxes (heatmap_format=json), compares every head's | |
| 64x64 heatmap with the torch reference fed the server's own float preprocessing (PCC) and the in/out score, | |
| then times ``reqs`` requests (heatmap_format=png, the default) and prints the median/min of the server's | |
| timing_ms (preprocess / inference / encode / total) and the client wall time. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import base64 | |
| import io | |
| import json | |
| import os | |
| import statistics | |
| import sys | |
| import time | |
| import urllib.request | |
| from pathlib import Path | |
| import numpy as np | |
| import torch | |
| from PIL import Image | |
| sys.path.insert(0, str(Path(__file__).resolve().parents[1])) | |
| from gaze_lle.reference.load_pretrained import load_pretrained # noqa: E402 | |
| from gaze_lle.reference.torch_gaze_lle import build_gaze_lle # noqa: E402 | |
| ROOT = Path(__file__).resolve().parents[2] | |
| BOXES = [[116, 28, 176, 104], [269, 37, 301, 81], [87, 57, 107, 76], [190, 33, 265, 143], [200, 50, 300, 200], | |
| [50, 33, 100, 100], [350, 33, 400, 100], [150, 67, 300, 167], [25, 167, 75, 234], [425, 167, 475, 234]] | |
| MEAN, STD = (0.485, 0.456, 0.406), (0.229, 0.224, 0.225) | |
| def post(url, payload): | |
| req = urllib.request.Request(url + "/predict", data=json.dumps(payload).encode(), | |
| headers={"Content-Type": "application/json"}, method="POST") | |
| t0 = time.perf_counter() | |
| with urllib.request.urlopen(req, timeout=120) as r: | |
| body = json.loads(r.read()) | |
| return body, (time.perf_counter() - t0) * 1e3 | |
| def pcc(a, b): | |
| a = a.flatten() - a.mean() | |
| b = b.flatten() - b.mean() | |
| return float((a @ b) / (np.linalg.norm(a) * np.linalg.norm(b) + 1e-12)) | |
| def main(): | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--url", default="http://127.0.0.1:20000") | |
| ap.add_argument("--heads", default="1,3,5,10") | |
| ap.add_argument("--reqs", type=int, default=30) | |
| ap.add_argument("--image", default=str(ROOT / "media" / "source_1.png")) | |
| args = ap.parse_args() | |
| torch.set_grad_enabled(False) | |
| raw = open(args.image, "rb").read() | |
| b64 = base64.b64encode(raw).decode() | |
| im = Image.open(io.BytesIO(raw)).convert("RGB") | |
| w, h = im.size | |
| x = np.asarray(im.resize((448, 448), Image.BILINEAR), dtype=np.float32) / 255.0 | |
| x = (x - np.asarray(MEAN, np.float32)) / np.asarray(STD, np.float32) | |
| x = torch.from_numpy(np.ascontiguousarray(x.transpose(2, 0, 1)))[None] | |
| wdir = os.environ.get("TT_GAZE_LLE_WEIGHTS", str(ROOT / "weights")) | |
| ref = build_gaze_lle("vitb14", inout=True).eval() | |
| load_pretrained(ref, os.path.join(wdir, "dinov2_vitb14_pretrain.pth"), | |
| os.path.join(wdir, "gazelle_dinov2_vitb14_inout.pt"), verbose=False) | |
| info = json.loads(urllib.request.urlopen(args.url + "/info", timeout=10).read()) | |
| print("INFO device_input:", info.get("limits", {}).get("device_input")) | |
| ok = True | |
| for n in [int(v) for v in args.heads.split(",")]: | |
| boxes = BOXES[:n] | |
| body, _ = post(args.url, {"image": b64, "bboxes": boxes, "heatmap_format": "json"}) | |
| norm = [(b[0] / w, b[1] / h, b[2] / w, b[3] / h) for b in boxes] | |
| r = ref(x.expand(n, -1, -1, -1), norm) | |
| pccs, ioerr = [], 0.0 | |
| for i, p in enumerate(body["predictions"]): | |
| pccs.append(pcc(np.asarray(p["heatmap"], np.float64), r["heatmap"][i].double().numpy())) | |
| ioerr = max(ioerr, abs(p["inout"] - float(r["inout"][i]))) | |
| ts = {k: [] for k in ("preprocess", "inference", "encode", "total", "wall")} | |
| for _ in range(3): | |
| post(args.url, {"image": b64, "bboxes": boxes}) | |
| for _ in range(args.reqs): | |
| b, wall = post(args.url, {"image": b64, "bboxes": boxes}) | |
| for k in ("preprocess", "inference", "encode", "total"): | |
| ts[k].append(b["timing_ms"][k]) | |
| ts["wall"].append(wall) | |
| tstr = " ".join(f"{k} {statistics.median(v):.2f} ({min(v):.2f})" for k, v in ts.items()) | |
| good = len(body["predictions"]) == n and min(pccs) > 0.85 | |
| ok &= good | |
| print(f"RESULT N={n} {'PASS' if good else 'FAIL'} pcc_min {min(pccs):.4f} pcc_mean {np.mean(pccs):.4f} " | |
| f"inout_maxabs {ioerr:.4f} | {tstr}") | |
| sys.exit(0 if ok else 1) | |
| if __name__ == "__main__": | |
| main() | |