Download code/scripts/device_server_smoke.py from changh95/DepthPro2: direct link, hf CLI and curl.
- Browser
- Download file 28.4 kB
-
https://huggingface.co/changh95/DepthPro2/resolve/main/code/scripts/device_server_smoke.py
- Command line
-
hf download hf://changh95/DepthPro2/code/scripts/device_server_smoke.py
-
curl -L -o device_server_smoke.py https://huggingface.co/changh95/DepthPro2/resolve/main/code/scripts/device_server_smoke.py
28.4 kB
| #!/usr/bin/env python3 | |
| # SPDX-License-Identifier: Apache-2.0 | |
| """Serving gate of DepthPro2 on the host (no container): the real HTTP app, started in-process by uvicorn with the | |
| device model, answering requests compared with Apple's float32 goldens and with this package's float32 CPU engine. | |
| # 1. CPU references of the video requests (no device; minutes for L / H) | |
| python code/scripts/device_server_smoke.py --prepare --size L --golden <dir> --out-dir <logs> | |
| # 2. the server on the device, every request, then a clean shutdown (one device-lock window) | |
| bin/devrun -t 3600 -- python -u code/scripts/device_server_smoke.py --size L --golden <dir> --out-dir <logs> \\ | |
| [--engine enc=mk] [--resolutions vga,vga_portrait,qvga] | |
| Requests (each timed: client round trip and the server's ``timing_ms.total``): | |
| * ``/predict`` of the shipped sample (repeated; the first is the cold one) vs its stored CPU reference | |
| (``reference.<size>.npy``: inverse-depth PCC; focal length); | |
| * ``/predict`` of the golden ``img_vga`` frame (480 x 640 PNG) vs Apple's float32 output: inverse-depth PCC, depth | |
| AbsRel with the golden focal length (pixels within 100x of the nearest), focal-length error; | |
| * ``/predict_png`` of the sample (16-bit PNG, its size); | |
| * ``/predict_video`` mode ``clip`` of the golden ``clip4_240x320`` frames vs Apple's float32 clip output; | |
| * ``/predict_video`` buffered (window 4, overlap 1) of the golden ``stream_buf_w4o1_n10`` frames (S: vs Apple's | |
| output; other sizes: vs the CPU engine's output of the same request); | |
| * a 480 x 640 pan over the sample (``pan_frames``), EVERY frame vs the CPU engine: one clip of the server's window | |
| (16), a short clip of 5 frames (on the window's program), and a buffered video of window + 4 frames; | |
| * an unbuffered stream (``stream`` id, one frame per request, window 4) of the golden ``stream_unbuf_w4_n6`` frames | |
| (S: vs Apple's output; else vs the CPU engine), each frame returned at once, then a second stream refused (429); | |
| * the stdlib smoke test (``server/smoke_test.py``) against the same server. | |
| Writes ``device_smoke_<size>_<engine>_<UTC>.json`` (all metrics and timings) to ``--out-dir`` and prints a summary. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import base64 | |
| import datetime as _dt | |
| import io | |
| import json | |
| import os | |
| import socket | |
| import statistics | |
| import sys | |
| import threading | |
| import time | |
| from pathlib import Path | |
| from typing import Any, Dict, List, Optional | |
| import numpy as np | |
| CODE = Path(__file__).resolve().parents[1] | |
| sys.path.insert(0, str(CODE)) | |
| SAMPLE = CODE / "tt_depthpro2" / "samples" / "kropa_street" | |
| GATE_PCC = 0.999 | |
| UNBUF_FRAMES = 6 # frames of the unbuffered pan stream | |
| def png(a: np.ndarray) -> str: | |
| from PIL import Image | |
| buf = io.BytesIO() | |
| Image.fromarray(np.ascontiguousarray(a)).save(buf, format="PNG") | |
| return base64.b64encode(buf.getvalue()).decode("ascii") | |
| def npy(d: Dict[str, Any]) -> np.ndarray: | |
| return np.load(io.BytesIO(base64.b64decode(d["data"]))).astype(np.float32) | |
| def pcc(a, b) -> float: | |
| a, b = np.asarray(a, np.float64).ravel(), np.asarray(b, np.float64).ravel() | |
| f = np.isfinite(a) & np.isfinite(b) | |
| return float(np.corrcoef(a[f], b[f])[0, 1]) | |
| def absrel(inv: np.ndarray, gold_depth: np.ndarray, f_px: float, width: int) -> float: | |
| """Depth AbsRel of an inverse-depth prediction with the golden focal length, over the golden pixels within 100x | |
| of the nearest one (Apple's bf16-drift metric).""" | |
| g = gold_depth.astype(np.float64) | |
| valid = np.isfinite(g) & (g <= 100 * np.nanmin(np.where(np.isfinite(g), g, np.inf))) | |
| d = f_px / (width * np.clip(inv.astype(np.float64), 1e-9, None)) | |
| return float(np.mean(np.abs(d[valid] - g[valid]) / g[valid])) | |
| def golden(gdir: Path, name: str) -> Optional[Dict[str, np.ndarray]]: | |
| p = gdir / f"{name}.safetensors" | |
| if not p.is_file(): | |
| return None | |
| from safetensors.numpy import load_file | |
| return load_file(str(p)) | |
| def pan_frames(n: int = 20) -> np.ndarray: | |
| """``n`` distinct 480 x 640 frames of the shipped sample, as a camera pan: 640 x 480 windows sliding over the | |
| sample upscaled to 800 x 600 (bilinear), 8 px right and 5 px down per frame. Deterministic (uint8).""" | |
| from PIL import Image | |
| meta = json.loads((SAMPLE / "sample.json").read_text()) | |
| big = np.asarray(Image.open(SAMPLE / meta["file"]).convert("RGB").resize((800, 600), Image.Resampling.BILINEAR)) | |
| return np.stack([np.ascontiguousarray(big[5 * k:5 * k + 480, 8 * k:8 * k + 640]) for k in range(n)]) | |
| def short_clip(window: int) -> int: | |
| """The short clip's length: 5 frames, fewer than the window.""" | |
| return max(1, min(5, window - 1)) | |
| def per_frame(inv: np.ndarray, want: np.ndarray) -> Dict[str, Any]: | |
| """Per-frame agreement of an inverse-depth clip with a reference clip: every frame's PCC and largest relative | |
| error, all finite.""" | |
| p = [pcc(inv[k], want[k]) for k in range(len(want))] | |
| rel = [float(np.max(np.abs(inv[k] - want[k])) / max(float(np.max(np.abs(want[k]))), 1e-12)) | |
| for k in range(len(want))] | |
| return {"frames": len(want), "pcc_min": round(min(p), 6), "pcc_per_frame": [round(v, 6) for v in p], | |
| "max_rel_max": round(max(rel), 5), "finite": bool(np.isfinite(inv).all())} | |
| # ---------------------------------------------------------------------------------------------- CPU references | |
| def prepare(a: argparse.Namespace) -> int: | |
| """CPU-engine outputs of the video requests whose official golden exists only for S.""" | |
| sys.modules.setdefault("ttnn", None) | |
| import torch | |
| from tt_depthpro2.api import DepthPro2 | |
| torch.set_num_threads(os.cpu_count() or 8) | |
| path = a.out_dir / f"cpu_refs_{a.size}.npz" | |
| out: Dict[str, np.ndarray] = dict(np.load(path)) if path.is_file() else {} # incremental: missing groups only | |
| gb = golden(a.golden, "stream_buf_w4o1_n10__S") | |
| gu = golden(a.golden, "stream_unbuf_w4_n6__S") | |
| if "buf_inv" in out and "unbuf_inv" in out: | |
| gb = gu = None | |
| with DepthPro2.from_pretrained(a.size, backend="cpu", resolutions="qvga", window=4, overlap=1, | |
| video_modes="buffered,unbuffered", weights_dir=a.weights_dir, | |
| fov_weights_dir=a.weights_dir) as m: | |
| t0 = time.time() | |
| if gb is not None: | |
| outs = list(m.infer_video(list(gb["input_u8"]), window=4, overlap=1)) | |
| out["buf_inv"] = np.stack([o.inverse_depth.numpy() for o in outs]) | |
| out["buf_f"] = np.array([outs[0].focallength_px], np.float32) | |
| if gu is not None: | |
| s = m.stream(mode="unbuffered", window=4) | |
| got = [] | |
| for f in gu["input_u8"]: | |
| got += s.step(f) | |
| got += s.flush() | |
| s.close() | |
| out["unbuf_inv"] = np.stack([o.inverse_depth.numpy() for o in got]) | |
| print(f"CPU references of {a.size} in {time.time() - t0:.1f} s", flush=True) | |
| # the 480 x 640 pan clip of the run (pan_frames): one window-length clip, a short clip (short_clip) and a buffered | |
| # video of window + 4 frames (two clips, the second pulled back and cross-faded) | |
| pan = pan_frames(a.window + 4) | |
| with DepthPro2.from_pretrained(a.size, backend="cpu", resolutions="vga", window=a.window, | |
| overlap=min(4, a.window - 1), clip_lengths="all", weights_dir=a.weights_dir, | |
| fov_weights_dir=a.weights_dir, video_modes="buffered,unbuffered") as m: | |
| t0 = time.time() | |
| if "pan_unbuf_inv" not in out: # an unbuffered stream of the first UNBUF_FRAMES pan frames (window = the server's) | |
| s = m.stream(mode="unbuffered", f_px=500.0) | |
| got = [] | |
| for f in pan[:UNBUF_FRAMES]: | |
| got += s.step(f) | |
| got += s.flush() | |
| s.close() | |
| out["pan_unbuf_inv"] = np.stack([o.inverse_depth.numpy() for o in got]) | |
| print(f"CPU unbuffered pan stream of {a.size} in {time.time() - t0:.1f} s", flush=True) | |
| if f"pan_clip{a.window}_inv" in out and "pan_short_inv" in out and "pan_video_inv" in out: | |
| np.savez(path, **out) | |
| print(f"wrote {path}") | |
| return 0 | |
| o = m.infer_clip(pan[:a.window]) | |
| out[f"pan_clip{a.window}_inv"] = o.inverse_depth.numpy() | |
| out[f"pan_clip{a.window}_f"] = np.array([o.focallength_px], np.float32) | |
| o = m.infer_clip(pan[:short_clip(a.window)]) | |
| out["pan_short_inv"], out["pan_short_f"] = o.inverse_depth.numpy(), np.array([o.focallength_px], np.float32) | |
| outs = list(m.infer_video(list(pan))) | |
| out["pan_video_inv"] = np.stack([x.inverse_depth.numpy() for x in outs]) | |
| out["pan_video_f"] = np.array([outs[0].focallength_px], np.float32) | |
| print(f"CPU pan clips ({a.window}, 5 and a {len(pan)}-frame video) of {a.size} in {time.time() - t0:.1f} s", | |
| flush=True) | |
| np.savez(path, **out) | |
| print(f"wrote {path}") | |
| return 0 | |
| # ---------------------------------------------------------------------------------------------- the device run | |
| def free_port() -> int: | |
| with socket.socket() as s: | |
| s.bind(("127.0.0.1", 0)) | |
| return s.getsockname()[1] | |
| class Timer: | |
| def __init__(self): | |
| self.rows: List[Dict[str, Any]] = [] | |
| def post(self, client, base: str, route: str, body: Dict[str, Any], name: str): | |
| t = time.perf_counter() | |
| code, resp = client.post_json(base, route, body, timeout=1800) | |
| rtt = (time.perf_counter() - t) * 1e3 | |
| server = (resp.get("timing_ms") or {}).get("total") if isinstance(resp, dict) else None | |
| self.rows.append({"request": name, "http": code, "rtt_ms": round(rtt, 1), "server_ms": server}) | |
| if code != 200: | |
| raise RuntimeError(f"{name}: HTTP {code}: {str(resp)[:400]}") | |
| return resp | |
| def run(a: argparse.Namespace) -> int: | |
| env = {"DEPTHPRO2_SIZE": a.size, "DEPTHPRO2_RESOLUTIONS": a.resolutions, "DEPTHPRO2_WINDOW": str(a.window), | |
| "DEPTHPRO2_OVERLAP": str(min(4, a.window - 1)), "DEPTHPRO2_VIDEO_MODES": a.video_modes, "DEPTHPRO2_KV_STREAMS": "1", | |
| "DEPTHPRO2_DISPATCH": "eth", "DEPTHPRO2_NUM_CQS": "1", "HF_HUB_DISABLE_IMPLICIT_TOKEN": "1"} | |
| if a.engine: | |
| env["DEPTHPRO2_ENGINE"] = a.engine | |
| if a.weights_dir: | |
| env["DEPTHPRO2_WEIGHTS_DIR"] = env["DEPTHPRO2_FOV_WEIGHTS_DIR"] = str(a.weights_dir) | |
| os.environ.update(env) | |
| import uvicorn | |
| import importlib.util | |
| from tt_depthpro2.server import app as server | |
| from tt_depthpro2.server import client # this package's stdlib client | |
| spec = importlib.util.spec_from_file_location("dp2_smoke_test", CODE / "tt_depthpro2" / "server" / "smoke_test.py") | |
| smoke_test = importlib.util.module_from_spec(spec) | |
| sys.modules["dp2_smoke_test"] = smoke_test | |
| spec.loader.exec_module(smoke_test) | |
| report: Dict[str, Any] = {"size": a.size, "engine": a.engine or "default", "env": env, "checks": {}, | |
| "fails": []} | |
| port = free_port() | |
| base = f"http://127.0.0.1:{port}" | |
| srv = uvicorn.Server(uvicorn.Config(server.app, host="127.0.0.1", port=port, log_level="info", lifespan="on")) | |
| t_boot = time.perf_counter() | |
| from tt_depthpro2.ttaw.server import client as ttaw_client | |
| server_done = threading.Event() | |
| tm = Timer() | |
| fails = report["fails"] | |
| checks = report["checks"] | |
| stop: Dict[str, float] = {} | |
| def run_checks() -> None: | |
| """The requests, from a worker thread; the server (and so the device) lives in the main thread.""" | |
| health: Dict[str, Any] = {} | |
| deadline = time.time() + a.boot_timeout | |
| while not server_done.is_set() and time.time() < deadline: # a failed start-up ends srv.run() | |
| health = ttaw_client.wait_ready(base, wait_s=0, poll_s=1.0) | |
| if health.get("status") in ("ok", "error"): | |
| break | |
| time.sleep(2.0) | |
| report["boot_s"] = round(time.perf_counter() - t_boot, 1) | |
| if health.get("status") != "ok": | |
| fails.append(f"server not ready: {health}") | |
| stop["t"] = time.perf_counter() | |
| srv.should_exit = True | |
| return | |
| try: | |
| info = ttaw_client.get_json(base + "/info") | |
| report["info"] = {k: info.get(k) for k in ("size", "engine", "precision", "device", "configuration", | |
| "warmup_ms", "warmup_latency_ms", "trace_region_bytes")} | |
| # 1. the sample, repeated (the first request is the cold one) | |
| meta = json.loads((SAMPLE / "sample.json").read_text()) | |
| img = (SAMPLE / meta["file"]).read_bytes() | |
| req = {"image": base64.b64encode(img).decode(), "include_inverse_depth": True, "output_format": "npy32"} | |
| bodies = [tm.post(client, base, "/predict", req, f"predict sample #{k}") for k in range(a.repeat)] | |
| ref = np.load(SAMPLE / f"reference.{a.size}.npy").astype(np.float32) | |
| refj = json.loads((SAMPLE / f"reference.{a.size}.json").read_text()) | |
| inv = npy(bodies[0]["inverse_depth"]) | |
| pooled = inv.reshape(120, 4, 160, 4).mean(axis=(1, 3)) | |
| same = all(b["depth"]["data"] == bodies[0]["depth"]["data"] for b in bodies) | |
| checks["sample_vs_cpu_reference"] = { | |
| "pcc_inverse_depth": round(pcc(pooled, ref), 6), | |
| "f_px": bodies[0]["focallength_px"], "f_px_reference": refj["focallength_px"], | |
| "f_px_rel_err": round(abs(bodies[0]["focallength_px"] / refj["focallength_px"] - 1), 6), | |
| "median_m": bodies[0]["stats_m"]["median"], "median_m_reference": refj["stats_m"]["median"], | |
| "repeat_identical": same} | |
| if checks["sample_vs_cpu_reference"]["pcc_inverse_depth"] < GATE_PCC or not same: | |
| fails.append(f"sample: {checks['sample_vs_cpu_reference']}") | |
| # 2. the golden VGA frame | |
| g = golden(a.golden, f"img_vga__{a.size}") | |
| if g is not None: | |
| body = tm.post(client, base, "/predict", {"image": png(g["input_u8"][0]), "include_inverse_depth": True, | |
| "output_format": "npy32"}, "predict img_vga") | |
| inv = npy(body["inverse_depth"]) | |
| fg = float(g["focallength_px"][0]) | |
| c = {"pcc_inverse_depth": round(pcc(inv, g["inverse_depth"]), 6), | |
| "absrel_depth": round(absrel(inv, g["depth"], fg, 640), 5), | |
| "f_px_rel_err": round(abs(body["focallength_px"] / fg - 1), 6)} | |
| checks["img_vga_vs_official"] = c | |
| if c["pcc_inverse_depth"] < GATE_PCC: | |
| fails.append(f"img_vga: {c}") | |
| # 3. the 16-bit PNG route | |
| t = time.perf_counter() | |
| code, raw, headers = client.post_png(base, img) | |
| tm.rows.append({"request": "predict_png sample", "http": code, "rtt_ms": round((time.perf_counter() - t) * 1e3, 1), | |
| "server_ms": json.loads(headers.get("X-Timing-Ms") or headers.get("x-timing-ms") or "{}").get("total")}) | |
| from PIL import Image | |
| im = np.asarray(Image.open(io.BytesIO(raw))) if code == 200 else None | |
| checks["predict_png"] = {"http": code, "shape": None if im is None else list(im.shape), | |
| "focal_header": headers.get("X-Focal-Length-Px") or headers.get("x-focal-length-px")} | |
| if code != 200 or im.shape != (480, 640): | |
| fails.append(f"predict_png: {checks['predict_png']}") | |
| # the 240 x 320 golden frames run natively only with a 240x320 bucket; else they are resized (recorded only) | |
| native = [240, 320] in (report["info"]["configuration"].get("resolutions") or []) | |
| report["golden_240x320_native"] = native | |
| # 4. one clip (the golden clip4) | |
| g = golden(a.golden, f"clip4_240x320__{a.size}") | |
| if g is not None: | |
| frames = [png(f) for f in g["input_u8"]] | |
| body = tm.post(client, base, "/predict_video", {"frames": frames, "mode": "clip", "include_inverse_depth": | |
| True, "output_format": "npy32"}, "video clip4 (clip)") | |
| inv = npy(body["inverse_depth"]) | |
| fg = float(g["focallength_px"][0]) | |
| c = {"pcc_inverse_depth": round(min(pcc(inv[k], g["inverse_depth"][k]) for k in range(4)), 6), | |
| "absrel_depth": round(np.mean([absrel(inv[k], g["depth"][k], fg, 320) for k in range(4)]), 5), | |
| "f_px_rel_err": round(abs(body["focallength_px"] / fg - 1), 6)} | |
| checks["clip4_vs_official"] = c | |
| if c["pcc_inverse_depth"] < GATE_PCC and native: | |
| fails.append(f"clip4: {c}") | |
| # the same 4 frames as a buffered video with window 4 = one clip: equal to the clip | |
| body2 = tm.post(client, base, "/predict_video", {"frames": frames, "window": 4, "overlap": 1, | |
| "include_inverse_depth": True, "output_format": "npy32"}, | |
| "video clip4 (buffered, window 4)") | |
| checks["clip4_buffered_equals_clip"] = round(pcc(npy(body2["inverse_depth"]), inv), 7) | |
| # 5. buffered video (window 4, overlap 1) of the golden stream | |
| cpu = np.load(a.out_dir / f"cpu_refs_{a.size}.npz") if (a.out_dir / f"cpu_refs_{a.size}.npz").is_file() else None | |
| g = golden(a.golden, "stream_buf_w4o1_n10__S") | |
| if g is not None: | |
| frames = [png(f) for f in g["input_u8"]] | |
| body = tm.post(client, base, "/predict_video", {"frames": frames, "window": 4, "overlap": 1, | |
| "include_inverse_depth": True, "output_format": "npy32"}, | |
| "video stream_buf 10 frames (buffered w4 o1)") | |
| inv = npy(body["inverse_depth"]) | |
| want, src = (g["inverse_depth"], "official") if a.size == "S" else ( | |
| (cpu["buf_inv"], "cpu engine") if cpu is not None and "buf_inv" in cpu else (None, None)) | |
| c = {"frames": body["frames"], "frame_indices_ok": body["frame_indices"] == list(range(10)), | |
| "vs": src} | |
| if want is not None: | |
| c["pcc_inverse_depth_min"] = round(min(pcc(inv[k], want[k]) for k in range(10)), 6) | |
| if a.size == "S": | |
| fg = float(g["focallength_px"][0]) | |
| c["absrel_depth_mean"] = round(np.mean([absrel(inv[k], g["depth"][k], fg, 320) | |
| for k in range(10)]), 5) | |
| c["f_px_rel_err"] = round(abs(body["focallength_px"] / fg - 1), 6) | |
| if c["pcc_inverse_depth_min"] < GATE_PCC and native: | |
| fails.append(f"buffered stream: {c}") | |
| checks["buffered_stream"] = c | |
| # 6. a real multi-frame 480 x 640 clip (a pan over the sample), EVERY frame vs the CPU engine: one clip of | |
| # the window, a short clip (5 frames on the window's program), a buffered video of window + 4 frames | |
| win = int(report["info"]["configuration"]["window"]) | |
| pan = pan_frames(win + 4) | |
| pan_b64 = [png(f) for f in pan] | |
| ns = short_clip(win) | |
| for name, frames, mode, key in ((f"pan clip {win} (clip)", pan_b64[:win], "clip", f"pan_clip{win}"), | |
| (f"pan clip {ns} (clip, short)", pan_b64[:ns], "clip", "pan_short"), | |
| (f"pan video {win + 4} (buffered)", pan_b64, "buffered", "pan_video")): | |
| body = tm.post(client, base, "/predict_video", {"frames": frames, "mode": mode, | |
| "output_format": "npy32", | |
| "include_inverse_depth": True}, name) | |
| inv = npy(body["inverse_depth"]) | |
| c: Dict[str, Any] = {"frames": body["frames"], "f_px": body["focallength_px"], | |
| "frame_indices_ok": body["frame_indices"] == list(range(len(frames)))} | |
| if cpu is not None and f"{key}_inv" in cpu: | |
| c.update(per_frame(inv, cpu[f"{key}_inv"])) | |
| c["f_px_rel_err_vs_cpu"] = round(abs(body["focallength_px"] / float(cpu[f"{key}_f"][0]) - 1), 6) | |
| if (c["pcc_min"] < GATE_PCC or not c["finite"] or c["f_px_rel_err_vs_cpu"] > 0.01 | |
| or not c["frame_indices_ok"]): | |
| fails.append(f"{name}: {c}") | |
| else: | |
| c["finite"] = bool(np.isfinite(inv).all()) | |
| c["median_m_frame0"] = body["stats_m"][0]["median"] | |
| fails.append(f"{name}: no CPU reference (run --prepare first)") | |
| checks[key] = c | |
| # 7. an unbuffered stream, one frame per request | |
| g = golden(a.golden, "stream_unbuf_w4_n6__S") | |
| cfgd = report["info"]["configuration"] | |
| if g is not None and "unbuffered" in (cfgd.get("video_modes") or []): | |
| invs = [] | |
| for k, f in enumerate(g["input_u8"]): | |
| body = tm.post(client, base, "/predict_video", | |
| {"frames": [png(f)], "mode": "unbuffered", "include_inverse_depth": True, | |
| "output_format": "npy32", "window": 4 if k == 0 else None, | |
| "stream": {"id": "dev-unbuffered", "end": k == len(g["input_u8"]) - 1}}, | |
| f"unbuffered stream frame {k}") | |
| if body["frame_indices"] != [k]: | |
| fails.append(f"unbuffered frame {k}: indices {body['frame_indices']}") | |
| invs.append(npy(body["inverse_depth"])[0]) | |
| if k == 0: | |
| code, b2 = client.post_json(base, "/predict_video", {"frames": [png(f)], "mode": "unbuffered", | |
| "stream": {"id": "dev-unbuffered-2"}}) | |
| checks["second_unbuffered_stream_http"] = code | |
| if code != 429: | |
| fails.append(f"second unbuffered stream: HTTP {code}") | |
| inv = np.stack(invs) | |
| want, src = (g["inverse_depth"], "official") if a.size == "S" else ( | |
| (cpu["unbuf_inv"], "cpu engine") if cpu is not None and "unbuf_inv" in cpu else (None, None)) | |
| c = {"frames": len(invs), "vs": src} | |
| if want is not None: | |
| c["pcc_inverse_depth_min"] = round(min(pcc(inv[k], want[k]) for k in range(len(invs))), 6) | |
| if a.size == "S": | |
| fg = float(g["focallength_px"][0]) | |
| c["absrel_depth_mean"] = round(np.mean([absrel(inv[k], g["depth"][k], fg, 320) | |
| for k in range(len(invs))]), 5) | |
| if c["pcc_inverse_depth_min"] < GATE_PCC and native: | |
| fails.append(f"unbuffered stream: {c}") | |
| checks["unbuffered_stream"] = c | |
| # 7b. an unbuffered stream of 480 x 640 pan frames (native at the default buckets), every frame vs the CPU | |
| if "unbuffered" in (cfgd.get("video_modes") or []): | |
| invs = [] | |
| for k in range(UNBUF_FRAMES): | |
| body = tm.post(client, base, "/predict_video", | |
| {"frames": [pan_b64[k]], "mode": "unbuffered", "include_inverse_depth": True, | |
| "output_format": "npy32", "f_px": 500.0 if k == 0 else None, | |
| "stream": {"id": "dev-unbuffered-pan", "end": k == UNBUF_FRAMES - 1}}, | |
| f"unbuffered pan frame {k}") | |
| if body["frame_indices"] != [k]: | |
| fails.append(f"unbuffered pan frame {k}: indices {body['frame_indices']}") | |
| invs.append(npy(body["inverse_depth"])[0]) | |
| c = {"frames": len(invs)} | |
| if cpu is not None and "pan_unbuf_inv" in cpu: | |
| c.update(per_frame(np.stack(invs), cpu["pan_unbuf_inv"])) | |
| if c["pcc_min"] < GATE_PCC or not c["finite"]: | |
| fails.append(f"unbuffered pan stream: {c}") | |
| else: | |
| fails.append("unbuffered pan stream: no CPU reference (run --prepare first)") | |
| checks["pan_unbuffered"] = c | |
| # 8. the stdlib smoke test | |
| out = a.out_dir / f"smoke_{a.size}.json" | |
| rc = smoke_test.main(["--url", base, "--out", str(out)]) | |
| checks["smoke_test_rc"] = rc | |
| if rc: | |
| fails.append("server/smoke_test.py failed (see its FAIL line above)") | |
| except Exception as e: # noqa: BLE001 -- recorded; the server is still shut down cleanly | |
| import traceback | |
| traceback.print_exc() | |
| fails.append(f"{type(e).__name__}: {e}") | |
| finally: | |
| stop["t"] = time.perf_counter() | |
| srv.should_exit = True | |
| worker = threading.Thread(target=run_checks, daemon=True) | |
| worker.start() | |
| try: | |
| # the main thread runs uvicorn: the lifespan opens and closes the chip here (tt-metal's chip mutex belongs to | |
| # the thread that opened the device; closing it from another thread aborts the process at exit) | |
| srv.run() | |
| finally: | |
| server_done.set() | |
| report["shutdown_s"] = round(time.perf_counter() - stop.get("t", time.perf_counter()), 1) | |
| worker.join(timeout=60) | |
| report["shutdown_clean"] = server.app.state.dp2.model is None and not worker.is_alive() | |
| report["requests"] = tm.rows | |
| by: Dict[str, List[float]] = {} | |
| for r in tm.rows: | |
| key = r["request"].split(" #")[0] | |
| by.setdefault(key, []).append(r["rtt_ms"]) | |
| report["rtt_ms_median"] = {k: round(statistics.median(v), 1) for k, v in by.items()} | |
| stamp = _dt.datetime.now(_dt.timezone.utc).strftime("%Y%m%dT%H%M%SZ") | |
| path = a.out_dir / f"device_smoke_{a.size}_{(a.engine or 'default').replace('=', '-').replace(',', '_')}_{stamp}.json" | |
| path.write_text(json.dumps(report, indent=1, default=str)) | |
| print(json.dumps({k: report[k] for k in ("size", "engine", "boot_s", "checks", "rtt_ms_median", "shutdown_s", | |
| "shutdown_clean", "fails")}, indent=1, default=str)) | |
| print(f"{'PASS' if not fails else 'FAIL'} device server smoke {a.size} ({a.engine or 'default engine'}): {path}") | |
| return 0 if not fails and report["shutdown_clean"] else 1 | |
| def main() -> int: | |
| ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) | |
| ap.add_argument("--size", default="S") | |
| ap.add_argument("--engine", default=None, help="DEPTHPRO2_ENGINE, e.g. dec=ttnn (default: the package default, config.DEFAULT_ENGINE)") | |
| ap.add_argument("--resolutions", default="vga,vga_portrait,qvga") | |
| ap.add_argument("--window", type=int, default=16) | |
| ap.add_argument("--video-modes", default="auto") | |
| ap.add_argument("--repeat", type=int, default=10, help="requests of the sample image") | |
| ap.add_argument("--golden", type=Path, default=Path(os.environ.get("DEPTHPRO2_GOLDEN", str(CODE / "golden"))), | |
| help="Apple's float32 goldens (*.safetensors; default $DEPTHPRO2_GOLDEN or code/golden); " | |
| "checks whose golden is absent are skipped") | |
| ap.add_argument("--weights-dir", type=Path, default=None) | |
| ap.add_argument("--out-dir", type=Path, default=Path(".")) | |
| ap.add_argument("--boot-timeout", type=float, default=2400.0) | |
| ap.add_argument("--prepare", action="store_true", help="only compute the CPU references (no device)") | |
| a = ap.parse_args() | |
| a.out_dir.mkdir(parents=True, exist_ok=True) | |
| return prepare(a) if a.prepare else run(a) | |
| if __name__ == "__main__": | |
| sys.exit(main()) | |