File size: 20,771 Bytes
b7e49b8 d5afa0d b7e49b8 | 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 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 | #!/usr/bin/env python3
# SPDX-License-Identifier: Apache-2.0
"""Smoke test of a running DepthPro2 server (standard library only; any Python 3.9+, no numpy).
python3 code/tt_depthpro2/server/smoke_test.py --url http://127.0.0.1:20000 --wait 1800
# a served container package, one serve profile (what code/scripts/container_smoke.sh runs):
python3 code/tt_depthpro2/server/smoke_test.py --url http://127.0.0.1:20000 --wait 600 \\
--manifest <out>/depthpro2/tt_kernel_manifest.json [--profile l] --out /tmp/depthpro2.json
Checks (every failure is collected; prints ONE line ``PASS ...`` / ``FAIL ...``, exit code 0 / 1):
* ``/health`` is ``ok`` (waiting up to ``--wait`` s); ``/info``, ``/config`` and ``/v1/models`` answer;
* ``/info`` reports ETH dispatch and the 12x10 grid; with ``--manifest`` also what the package pins for the profile
(``DEPTHPRO2_SIZE``, ``_RESOLUTIONS``, ``_WINDOW``, ``_OVERLAP``, ``_DISPATCH``, ``_NUM_CQS``, the weights commits of
the size and of the focal estimator) and a warm-up latency for every bucket and clip length;
* ``POST /predict`` of the shipped sample (480 x 640, the ``vga`` bucket when served; else resized) answers 200 with
a finite float16 depth map of the input size; its inverse depth agrees with the stored float32 CPU reference of
the served size (``samples/kropa_street/reference.<size>.npy``, 4 x 4 average-pooled) to PCC >= 0.999, and its
FOV focal length with the reference's within 1.5 %; the same request again gives identical bytes; ``f_px`` given
is used and scales the depth linearly;
* ``POST /predict_png`` answers a 16-bit PNG of the input size with the focal length in its headers;
* ``POST /predict_video`` of ``window`` copies of the sample (buffered) returns one finite depth map per frame, in
order; when unbuffered video is enabled, a 3-request unbuffered stream returns each frame at once and a second
stream beyond ``DEPTHPRO2_KV_STREAMS`` = 1 is refused with 429;
* bad requests answer 400 with a reason (undecodable base64, not an image, a negative f_px, frames of different
sizes, an uncompiled clip length, a disabled video mode) and an unknown field 422.
"""
from __future__ import annotations
import argparse
import ast
import base64
import importlib.util
import json
import math
import struct
import sys
import time
from pathlib import Path
from typing import Any, Dict, List, Optional, Sequence, Tuple
HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE.parent / "ttaw" / "server"))
import client as ttaw_client # noqa: E402 (stdlib-only modules of the vendored ttaw)
import smoke as ttaw_smoke # noqa: E402
def _load(name: str, path: Path):
"""A stdlib-only module of this package, loaded by path under its own name (the host python3 that runs the
smoke test has neither numpy nor this package installed)."""
spec = importlib.util.spec_from_file_location(name, path)
mod = importlib.util.module_from_spec(spec)
sys.modules[name] = mod # before exec: dataclasses look their module up there
spec.loader.exec_module(mod)
return mod
C = _load("dp2_config", HERE.parent / "config.py")
dp2_client = _load("dp2_client", HERE / "client.py")
MODEL = C.MODEL_NAME
ENV_PREFIX = C.ENV_PREFIX
EXPECT_DISPATCH, EXPECT_GRID = "eth", "12x10" # the p150 target; deliberately not a command-line option
SAMPLE_DIR = HERE.parent / "samples" / "kropa_street"
POOL = 4
GATES = {"min_pcc_inverse_depth": 0.999, "max_rel_focal": 0.015}
def parse_npy(raw: bytes) -> Tuple[Tuple[int, ...], List[float]]:
"""A little-endian float16 / float32 C-order ``.npy`` -> ``(shape, values)``."""
if raw[:6] != b"\x93NUMPY":
raise ValueError("not a .npy file")
major = raw[6]
if major == 1:
(hlen,) = struct.unpack("<H", raw[8:10])
off = 10
else:
(hlen,) = struct.unpack("<I", raw[8:12])
off = 12
header = ast.literal_eval(raw[off:off + hlen].decode("latin1"))
descr, shape = header["descr"], tuple(header["shape"])
if header.get("fortran_order"):
raise ValueError("fortran-order .npy")
code = {"<f2": "e", "<f4": "f", "|u1": "B", "<u2": "H"}.get(descr)
if code is None:
raise ValueError(f"dtype {descr} not handled")
n = 1
for d in shape:
n *= d
data = raw[off + hlen:]
return shape, list(struct.unpack(f"<{n}{code}", data[:n * struct.calcsize(code)]))
def decode_npy_field(d: Dict[str, Any]) -> Tuple[Tuple[int, ...], List[float]]:
return parse_npy(base64.b64decode(d["data"]))
def avg_pool(values: Sequence[float], h: int, w: int, k: int) -> List[float]:
"""k x k average pooling of an (h, w) map (h, w divisible by k), row-major."""
oh, ow = h // k, w // k
out = [0.0] * (oh * ow)
for y in range(oh * k):
row = values[y * w:(y + 1) * w]
base = (y // k) * ow
for x in range(ow * k):
out[base + x // k] += row[x]
s = 1.0 / (k * k)
return [v * s for v in out]
def pcc(a: Sequence[float], b: Sequence[float]) -> float:
n = len(a)
ma, mb = sum(a) / n, sum(b) / n
sab = saa = sbb = 0.0
for x, y in zip(a, b):
dx, dy = x - ma, y - mb
sab += dx * dy
saa += dx * dx
sbb += dy * dy
return sab / math.sqrt(saa * sbb) if saa > 0 and sbb > 0 else (1.0 if saa == sbb == 0 else 0.0)
def finite(vals: Sequence[float]) -> List[float]:
return [v for v in vals if math.isfinite(v)]
def sample_bytes() -> bytes:
meta = json.loads((SAMPLE_DIR / "sample.json").read_text())
return (SAMPLE_DIR / meta["file"]).read_bytes()
def png_ihdr(raw: bytes) -> Tuple[int, int, int, int]:
"""``(width, height, bit depth, colour type)`` of a PNG."""
if raw[:8] != b"\x89PNG\r\n\x1a\n" or raw[12:16] != b"IHDR":
raise ValueError("not a PNG")
w, h, depth, ctype = struct.unpack(">IIBB", raw[16:26])
return w, h, depth, ctype
def manifest_pins(manifest: Path, profile: Optional[str]) -> Dict[str, Any]:
"""The profile's env (serve.env + the profile's), the focal repo's commit and the auxiliary repos' commits."""
pinned = ttaw_smoke.pinned_config(manifest, profile)
m = json.loads(Path(manifest).read_text())
aux = {}
for r in m.get("auxiliary_weights") or []:
aux[r.get("repo_id") or r.get("repo")] = r.get("revision")
pinned["auxiliary"] = aux
return pinned
def check_info(info: Dict[str, Any], pins: Optional[Dict[str, Any]]) -> List[str]:
fails = []
cfgd = info.get("configuration") or {}
env = (pins or {}).get("env") or {}
size = env.get(f"{ENV_PREFIX}_SIZE")
if size and C.normalize_size(size) != info.get("size"):
fails.append(f"/info size {info.get('size')!r}, the profile pins {ENV_PREFIX}_SIZE={size}")
res = env.get(f"{ENV_PREFIX}_RESOLUTIONS")
if res:
want = [list(x) for x in C.parse_resolutions(res)]
if cfgd.get("resolutions") != want:
fails.append(f"/info resolutions {cfgd.get('resolutions')} != pinned {want}")
eng = env.get(f"{ENV_PREFIX}_ENGINE")
if eng is not None and info.get("engine") != C.parse_engine(eng):
fails.append(f"/info engine {info.get('engine')} != pinned {ENV_PREFIX}_ENGINE={eng}")
encp = env.get(f"{ENV_PREFIX}_ENC_PRECISION")
if encp and cfgd.get("enc_precision") != encp.strip().lower():
fails.append(f"/info enc_precision {cfgd.get('enc_precision')!r} != pinned {ENV_PREFIX}_ENC_PRECISION={encp}")
for key, name in (("window", "WINDOW"), ("overlap", "OVERLAP")):
v = env.get(f"{ENV_PREFIX}_{name}")
if v and str(cfgd.get(key)) != v.strip():
fails.append(f"/info {key} {cfgd.get(key)} != pinned {ENV_PREFIX}_{name}={v}")
w = info.get("weights") or {}
if pins:
rev = (pins.get("weights") or {}).get("revision")
got = (w.get("focal") or {}).get("revision")
if rev and w.get("focal") is not None and got != rev:
fails.append(f"focal weights revision {got!r} != the package pin {rev!r}")
sw = w.get("size") or {}
want = (pins.get("auxiliary") or {}).get(sw.get("repo"))
if want and sw.get("revision") != want:
fails.append(f"{sw.get('repo')} revision {sw.get('revision')!r} != the package pin {want!r}")
# dispatch / CQs (the weights commits are checked above, per repo)
fails += ttaw_smoke.check_pinned(info, dict(pins, weights={}), ENV_PREFIX)
lat = info.get("warmup_latency_ms") or {}
compiled = cfgd.get("compiled_clip_lengths") or cfgd.get("clip_lengths") or []
want_keys = {f"{h}x{w_}/T{t}" for h, w_ in (cfgd.get("resolutions") or []) for t in compiled}
if want_keys and not want_keys <= set(lat):
fails.append(f"/info warmup_latency_ms misses {sorted(want_keys - set(lat))}")
return fails
def check_predict(base: str, size: str, ref_dir: Path) -> Tuple[Dict[str, Any], Dict[str, Any], List[str]]:
fails: List[str] = []
metrics: Dict[str, Any] = {}
img = sample_bytes()
req = {"image": base64.b64encode(img).decode("ascii"), "include_inverse_depth": True}
t0 = time.perf_counter()
code, body = dp2_client.post_json(base, "/predict", req)
metrics["rtt_ms"] = round((time.perf_counter() - t0) * 1e3, 1)
if code != 200:
return {}, metrics, [f"/predict HTTP {code}: {str(body)[:300]}"]
for k in ("depth", "inverse_depth", "focallength_px", "stats_m", "input_size", "timing_ms"):
if k not in body:
fails.append(f"/predict: missing {k!r}")
if fails:
return body, metrics, fails
shape, depth = decode_npy_field(body["depth"])
_, inv = decode_npy_field(body["inverse_depth"])
h, w = body["input_size"]
if list(shape) != [h, w] or [h, w] != [480, 640]:
fails.append(f"depth shape {shape} / input_size {body['input_size']} != [480, 640]")
return body, metrics, fails
if not finite(depth) or min(finite(depth)) <= 0:
fails.append("depth has no positive finite values")
if any(not math.isfinite(v) or v < 0 for v in inv):
fails.append("inverse depth has negative or non-finite values")
metrics["focal_px"] = round(body["focallength_px"], 2)
metrics["focal_source"] = body.get("focal_source")
ref_json = ref_dir / f"reference.{size}.json"
ref_npy = ref_dir / f"reference.{size}.npy"
if ref_json.is_file() and ref_npy.is_file():
ref = json.loads(ref_json.read_text())
rshape, rinv = parse_npy(ref_npy.read_bytes())
got = avg_pool(inv, h, w, POOL)
if list(rshape) != [h // POOL, w // POOL]:
fails.append(f"reference {ref_npy.name} has shape {rshape}")
else:
p = pcc(got, rinv)
metrics["pcc_inverse_depth"] = round(p, 6)
if p < GATES["min_pcc_inverse_depth"]:
fails.append(f"inverse depth PCC {p:.6f} vs the CPU reference < {GATES['min_pcc_inverse_depth']}")
fr = ref.get("focallength_px")
if fr and body.get("focal_source") == "fov":
rel = abs(body["focallength_px"] - fr) / fr
metrics["focal_rel_err"] = round(rel, 5)
if rel > GATES["max_rel_focal"]:
fails.append(f"focal length {body['focallength_px']:.2f} vs the reference's {fr:.2f}: "
f"{100 * rel:.2f} % > {100 * GATES['max_rel_focal']} %")
else:
fails.append(f"no stored reference for size {size} ({ref_json.name}, {ref_npy.name})")
code2, body2 = dp2_client.post_json(base, "/predict", req)
if code2 != 200 or body2.get("depth", {}).get("data") != body["depth"]["data"]:
fails.append("the same /predict twice gave different depth maps")
f0 = body["focallength_px"]
code3, body3 = dp2_client.post_json(base, "/predict", {"image": req["image"], "f_px": 2 * f0,
"output_format": "npy32"})
if code3 != 200 or body3.get("focal_source") != "request":
fails.append(f"/predict with f_px: HTTP {code3}, focal_source {body3.get('focal_source')!r}")
else:
m0, m1 = body["stats_m"]["median"], body3["stats_m"]["median"]
if not (m0 and m1 and abs(m1 / m0 - 2.0) < 0.01):
fails.append(f"doubling f_px changed the median depth {m0} -> {m1} (expected x2)")
metrics["server_total_ms"] = body["timing_ms"].get("total")
return body, metrics, fails
def check_png(base: str) -> List[str]:
code, raw, headers = dp2_client.post_png(base, sample_bytes())
if code != 200:
return [f"/predict_png HTTP {code}: {raw[:200]!r}"]
try:
w, h, depth, ctype = png_ihdr(raw)
except ValueError as e:
return [f"/predict_png: {e}"]
fails = []
if (w, h, depth, ctype) != (640, 480, 16, 0):
fails.append(f"/predict_png: {w}x{h} bit depth {depth} colour type {ctype}, expected 640x480 16-bit grey")
hdr = {k.lower(): v for k, v in headers.items()}
if "x-focal-length-px" not in hdr or "x-depth-scale" not in hdr:
fails.append(f"/predict_png: missing X-Focal-Length-Px / X-Depth-Scale headers ({sorted(hdr)})")
return fails
def check_video(base: str, info: Dict[str, Any]) -> Tuple[Dict[str, Any], List[str]]:
cfgd = info.get("configuration") or {}
win = int(cfgd.get("window") or 1)
if "buffered" not in (cfgd.get("video_modes") or []):
return {}, []
b64 = base64.b64encode(sample_bytes()).decode("ascii")
t0 = time.perf_counter()
code, body = dp2_client.post_json(base, "/predict_video", {"frames": [b64] * win, "output_format": "none"})
rtt = round((time.perf_counter() - t0) * 1e3, 1)
if code != 200:
return {}, [f"/predict_video ({win} frames) HTTP {code}: {str(body)[:300]}"]
fails = []
if body.get("frames") != win or body.get("frame_indices") != list(range(win)):
fails.append(f"/predict_video: {body.get('frames')} frames {body.get('frame_indices')} != {win} in order")
stats = body.get("stats_m") or []
if len(stats) != win or not all(s.get("median") and s["median"] > 0 for s in stats):
fails.append("/predict_video: missing or non-positive per-frame depth statistics")
return {"video_frames": win, "video_rtt_ms": rtt, "video_server_ms": (body.get("timing_ms") or {}).get("total")}, \
fails
def check_unbuffered(base: str, info: Dict[str, Any]) -> Tuple[Dict[str, Any], List[str]]:
"""An unbuffered stream across requests returns every frame at once; a stream beyond DEPTHPRO2_KV_STREAMS is
refused with 429; ending the stream frees its cache."""
cfgd = info.get("configuration") or {}
if "unbuffered" not in (cfgd.get("video_modes") or []):
return {}, []
b64 = base64.b64encode(sample_bytes()).decode("ascii")
fails, times = [], []
sid = "smoke-unbuffered"
for k in range(3):
t0 = time.perf_counter()
code, body = dp2_client.post_json(base, "/predict_video", {"frames": [b64], "mode": "unbuffered",
"output_format": "none",
"stream": {"id": sid, "end": k == 2}})
times.append(round((time.perf_counter() - t0) * 1e3, 1))
if code != 200 or body.get("frame_indices") != [k]:
fails.append(f"unbuffered stream request {k}: HTTP {code} {str(body)[:200]}")
break
if k == 0 and int(cfgd.get("kv_streams") or 1) == 1:
c2, b2 = dp2_client.post_json(base, "/predict_video", {"frames": [b64], "mode": "unbuffered",
"output_format": "none",
"stream": {"id": sid + "-2"}})
if c2 != 429:
fails.append(f"a second unbuffered stream with DEPTHPRO2_KV_STREAMS=1: HTTP {c2} (expected 429)")
return {"unbuffered_rtt_ms": times}, fails
def check_refusals(base: str, info: Dict[str, Any]) -> List[str]:
b64 = base64.b64encode(sample_bytes()).decode("ascii")
cfgd = info.get("configuration") or {}
lengths = cfgd.get("clip_lengths") or [1]
missing_t = next((t for t in range(2, 65) if t not in lengths), None)
tiny = _tiny_png(32, 32)
cases = [
("/predict", "undecodable base64", {"image": "not base64!"}, 400),
("/predict", "not an image", {"image": base64.b64encode(b"hello world").decode()}, 400),
("/predict", "negative f_px", {"image": b64, "f_px": -5.0}, 400),
("/predict", "unknown field", {"image": b64, "temperature": 0.5}, 422),
("/predict", "bad output_format", {"image": b64, "output_format": "jpeg"}, 422),
("/predict_video", "frames of two sizes", {"frames": [b64, base64.b64encode(tiny).decode()]}, 400),
("/predict_video", "frames and clip", {"frames": [b64], "clip": {"format": "npy", "data": "AAAA"}}, 400),
]
if missing_t is not None:
cases.append(("/predict_video", f"uncompiled clip length {missing_t}",
{"frames": [b64] * missing_t, "mode": "clip", "output_format": "none"}, 400))
if "unbuffered" not in (cfgd.get("video_modes") or []):
cases.append(("/predict_video", "disabled unbuffered mode", {"frames": [b64], "mode": "unbuffered"}, 400))
fails = []
for route, name, payload, want in cases:
code, body = dp2_client.post_json(base, route, payload)
if code != want:
fails.append(f"{route} {name}: HTTP {code} (expected {want}): {str(body)[:160]}")
elif want == 400 and not str(body.get("detail") or ""):
fails.append(f"{route} {name}: 400 without a reason")
return fails
def _tiny_png(w: int, h: int) -> bytes:
import zlib
def chunk(kind: bytes, data: bytes) -> bytes:
return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", zlib.crc32(kind + data) & 0xFFFFFFFF)
raw = b"".join(b"\x00" + bytes([90, 120, 150]) * w for _ in range(h))
return (b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", w, h, 8, 2, 0, 0, 0))
+ chunk(b"IDAT", zlib.compress(raw)) + chunk(b"IEND", b""))
def main(argv: Optional[List[str]] = None) -> int:
ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
ap.add_argument("--url", default="http://127.0.0.1:20000")
ap.add_argument("--manifest", type=Path, help="staged tt_kernel_manifest.json: /info must run what it pins")
ap.add_argument("--profile", help="serve profile being smoke-tested (default: the package's default)")
ap.add_argument("--wait", type=float, default=0.0, help="seconds to wait for /health == ok")
ap.add_argument("--out", type=Path, help="write the sample's /predict response (arrays elided) here")
ap.add_argument("--reference-dir", type=Path, default=SAMPLE_DIR)
a = ap.parse_args(argv)
base = a.url.rstrip("/")
health = ttaw_client.wait_ready(base, wait_s=a.wait)
if health.get("status") != "ok":
print(ttaw_client.smoke_line(MODEL, f"/health status={health.get('status')!r}",
[f"not ready after {a.wait:.0f} s (error: {health.get('error')})"]))
return 1
info, fails = ttaw_client.check_service(base, expect_dispatch=EXPECT_DISPATCH, expect_grid=EXPECT_GRID)
if not info:
print(ttaw_client.smoke_line(MODEL, "/info unreachable", fails))
return 1
try:
ttaw_client.get_json(base + "/config")
except Exception as e: # noqa: BLE001
fails.append(f"/config: {e}")
pins, profile = None, a.profile
if a.manifest:
try:
pins = manifest_pins(a.manifest, a.profile)
profile = pins["profile"]
except (OSError, ValueError) as e:
fails.append(f"manifest: {e}")
fails += check_info(info, pins)
size = info.get("size") or "?"
body, metrics, more = check_predict(base, size, a.reference_dir)
fails += more
if a.out and body:
a.out.write_text(json.dumps(dp2_client.summarize(body), indent=1))
fails += check_png(base)
vm, more = check_video(base, info)
metrics.update(vm)
fails += more
um, more = check_unbuffered(base, info)
metrics.update(um)
fails += more
fails += check_refusals(base, info)
device = info.get("device") or {}
m = " ".join(f"{k}={v}" for k, v in metrics.items())
summary = (f"profile={profile or '-'} size={size} dispatch={device.get('dispatch')} grid={device.get('grid')} "
f"engine={','.join(f'{k}={v}' for k, v in (info.get('engine') or {}).items())} {m}")
print(ttaw_client.smoke_line(MODEL, summary, fails))
return 1 if fails else 0
if __name__ == "__main__":
sys.exit(main())
|