File size: 18,616 Bytes
b7e49b8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d5afa0d
 
 
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
# SPDX-License-Identifier: Apache-2.0
"""Host tests of the HTTP server (no device): the real app with the API on the CPU engine (Depth Pro 2 S): routes,
/health before and after start-up, /info and /config, ``/predict`` (every output format; API == server), the 16-bit
PNG route, ``/predict_video`` (buffered, one clip, a stream across requests and its limit), the 400 / 422 / 429 / 500
/ 503 answers, start-up refusals, and the stdlib smoke test against the app served over real HTTP by uvicorn.

    PYTHONPATH=<workspace>/research/packaging/scripts:code TT_VISIBLE_DEVICES=none \
        python -m pytest -p fake_ttnn_plugin code/tt_depthpro2/tests/test_host_server.py
"""
from __future__ import annotations

import base64
import contextlib
import io
import json
import socket
import threading
from pathlib import Path

import numpy as np
import pytest

fastapi = pytest.importorskip("fastapi")
from fastapi.testclient import TestClient  # noqa: E402

from tt_depthpro2.api import DepthPro2, load_sample  # noqa: E402
from tt_depthpro2.server import app as server  # noqa: E402
from tt_depthpro2.tests.host_helpers import WEIGHTS_ROOT, golden, need_weights, rel_err  # noqa: E402

SMOKE = Path(server.__file__).resolve().parent / "smoke_test.py"
ENV = {"DEPTHPRO2_SIZE": "S", "DEPTHPRO2_RESOLUTIONS": "480x640,240x320", "DEPTHPRO2_WINDOW": "2",
       "DEPTHPRO2_OVERLAP": "1", "DEPTHPRO2_BACKEND": "cpu", "DEPTHPRO2_MAX_FRAMES": "8", "DEPTHPRO2_MAX_STREAMS": "1",
       "DEPTHPRO2_WEIGHTS_DIR": str(WEIGHTS_ROOT), "DEPTHPRO2_FOV_WEIGHTS_DIR": str(WEIGHTS_ROOT)}
FAKE_DEVICE = {"dispatch": "eth", "grid": "12x10", "cores": 120, "num_command_queues": 1, "backend": "cpu"}


def cpu_factory(cfg, warmup=False):
    """``default_model_factory`` on the CPU engine (without the warm-up unless asked), reporting the p150's device
    fields (the smoke test asserts ETH dispatch and the 12x10 grid)."""
    m = cfg.model
    model = DepthPro2.from_pretrained(m.size, resolutions=m.resolutions, window=m.window, overlap=m.overlap,
                                      fov=m.fov, video_modes=m.video_modes, clip_lengths=m.clip_lengths,
                                      weights_dir=cfg.weights_dir, fov_weights_dir=cfg.fov_weights_dir,
                                      backend="cpu", warmup=warmup)
    model.device_info = dict(FAKE_DEVICE)
    return model


@contextlib.contextmanager
def client_with(monkeypatch, factory=cpu_factory, **env):
    need_weights("S")
    for k, v in dict(ENV, **env).items():
        if v is None:
            monkeypatch.delenv(k, raising=False)
        else:
            monkeypatch.setenv(k, v)
    st = server.app.state.dp2
    old = (st.model_factory, st.model, st.config, st.ready, st.error)
    st.model_factory, st.model, st.config, st.ready, st.error = factory, None, None, False, None
    try:
        with TestClient(server.app) as c:
            yield c
    finally:
        st.model_factory, st.model, st.config, st.ready, st.error = old
        st.streams.clear()


@pytest.fixture(scope="module")
def mp_module():
    mp = pytest.MonkeyPatch()
    yield mp
    mp.undo()


@pytest.fixture(scope="module")
def client(mp_module):
    with client_with(mp_module) as c:
        yield c


def b64(raw: bytes) -> str:
    return base64.b64encode(raw).decode("ascii")


def png_bytes(a: np.ndarray) -> bytes:
    from PIL import Image

    buf = io.BytesIO()
    Image.fromarray(a).save(buf, format="PNG")
    return buf.getvalue()


def npy(d):
    return np.load(io.BytesIO(base64.b64decode(d["data"])))


SAMPLE = load_sample().read_bytes()


def test_routes_health_info(client):
    assert "POST /predict_video" in client.get("/").json()["routes"]
    h = client.get("/health").json()
    assert h["status"] == "ok" and h["device"]["grid"] == "12x10"
    assert client.get("/v1/health").json()["status"] == "ok"
    info = client.get("/info").json()
    assert info["model"] == "depthpro2" and info["size"] == "S" and info["backend"] == "cpu"
    assert info["configuration"]["resolutions"] == [[480, 640], [240, 320]]
    assert info["configuration"]["clip_lengths"] == [1, 2] and info["weights"]["repo"] == "apple/DepthPro2-focal"
    assert info["server"]["limits"]["max_frames_per_request"] == 8
    assert "Research Model License" in info["license"]["notice"]
    cfg = client.get("/config").json()
    assert cfg["configuration"]["window"] == 2 and cfg["limits"]["max_streams"] == 1
    # the encoder precision is reported (default high; the CPU backend sets no megakernel options)
    assert info["configuration"]["enc_precision"] == cfg["configuration"]["enc_precision"] == "high"
    assert cfg["configuration"]["env"]["DEPTHPRO2_ENC_PRECISION"] == "high"
    assert client.get("/v1/models").json()["data"][0]["id"] == "apple/DepthPro2-S"


def test_predict_equals_the_api(client):
    r = client.post("/predict", json={"image": b64(SAMPLE), "include_inverse_depth": True})
    assert r.status_code == 200, r.text
    body = r.json()
    assert body["input_size"] == [480, 640] and not body["resized"] and body["focal_source"] == "fov"
    assert set(body["timing_ms"]) >= {"decode", "preprocess", "device", "fov", "postprocess", "encode", "total"}
    api = server.app.state.dp2.model.infer(load_sample()).to_dict(include_inverse_depth=True)
    assert body["depth"]["data"] == api["depth"]["data"] and body["inverse_depth"]["data"] == api["inverse_depth"]["data"]
    assert body["focallength_px"] == api["focallength_px"] and body["stats_m"] == api["stats_m"]
    d = npy(body["depth"])
    assert d.dtype == np.float16 and d.shape == (480, 640) and np.isinf(d).any()


def test_predict_options(client):
    r = client.post("/predict", json={"image": b64(SAMPLE), "f_px": 400.0, "output_format": "npy32"}).json()
    assert r["focal_source"] == "request" and r["focallength_px"] == 400.0 and npy(r["depth"]).dtype == np.float32
    r2 = client.post("/predict", json={"image": b64(SAMPLE), "f_px": 800.0, "output_format": "none"}).json()
    assert r2["depth"] is None and abs(r2["stats_m"]["median"] / r["stats_m"]["median"] - 2) < 1e-4
    r3 = client.post("/predict", json={"image": b64(SAMPLE), "output_format": "png16", "png_scale": 100}).json()
    assert r3["depth"]["format"] == "png16" and r3["depth"]["scale"] == 100.0
    # an image of another size: resized to the nearest-aspect bucket and back
    small = np.full((300, 400, 3), 120, np.uint8)
    small[150:] = 60
    r4 = client.post("/predict", json={"image": b64(png_bytes(small))}).json()
    assert r4["resized"] and r4["bucket"] == [240, 320] and npy(r4["depth"]).shape == (300, 400)


def test_predict_png(client):
    r = client.post("/predict_png?png_scale=1000", content=SAMPLE)
    assert r.status_code == 200, r.text
    assert r.headers["content-type"] == "image/png"
    from PIL import Image

    im = np.asarray(Image.open(io.BytesIO(r.content)))
    assert im.shape == (480, 640) and int(r.headers["x-infinite-pixels"]) == int((im == 0).sum())
    assert float(r.headers["x-focal-length-px"]) > 0 and json.loads(r.headers["x-stats-m"])["median"] > 0
    assert client.post("/predict_png", content=b"").status_code == 400
    assert client.post("/predict_png", content=b"garbage").status_code == 400
    assert client.post("/predict_png?f_px=-3", content=SAMPLE).status_code == 400
    assert client.post("/predict_png?colour=1", content=SAMPLE).status_code == 400


def test_predict_video_modes(client):
    g = golden("stream_buf_w4o1_n10__S")
    frames = [b64(png_bytes(a)) for a in g["input_u8"].numpy()[:3]]
    r = client.post("/predict_video", json={"frames": frames, "include_inverse_depth": True})
    assert r.status_code == 200, r.text
    body = r.json()
    assert body["frames"] == 3 and body["frame_indices"] == [0, 1, 2] and body["window"] == 2
    assert body["overlap"] == 1 and len(body["stats_m"]) == 3 and npy(body["depth"]).shape == (3, 240, 320)
    model = server.app.state.dp2.model
    api = list(model.infer_video(list(g["input_u8"].numpy()[:3])))
    inv = npy(body["inverse_depth"]).astype(np.float32)
    want = np.stack([o.inverse_depth.numpy() for o in api])
    assert rel_err(inv, want) < 2e-3  # float16 encoding
    # the same frames as a .npy clip, and as ONE clip (2 frames = the window)
    buf = io.BytesIO()
    np.save(buf, g["input_u8"].numpy()[:2])
    r2 = client.post("/predict_video", json={"clip": {"format": "npy", "data": b64(buf.getvalue())},
                                             "mode": "clip", "f_px": 300.0}).json()
    assert r2["frames"] == 2 and r2["focal_source"] == "request" and r2["window"] == 2
    r3 = client.post("/predict_video", json={"frames": frames, "mode": "clip"})
    assert r3.status_code == 400 and "window" in r3.json()["detail"]  # 3 frames: longer than the window


def test_video_stream_across_requests(client):
    g = golden("stream_buf_w4o1_n10__S")
    frames = [b64(png_bytes(a)) for a in g["input_u8"].numpy()[:5]]
    r1 = client.post("/predict_video", json={"frames": frames[:1], "stream": {"id": "cam0"}}).json()
    assert r1["frames"] == 0 and r1["stream"]["pending"] == 1 and r1["depth"] is None
    busy = client.post("/predict_video", json={"frames": frames[:1], "stream": {"id": "cam1"}})
    assert busy.status_code == 429  # DEPTHPRO2_MAX_STREAMS=1
    bad = client.post("/predict_video", json={"frames": frames[:1], "stream": {"id": "cam0"}, "f_px": 3.0})
    assert bad.status_code == 400
    r2 = client.post("/predict_video", json={"frames": frames[1:3], "stream": {"id": "cam0"}}).json()
    r3 = client.post("/predict_video", json={"frames": frames[3:], "stream": {"id": "cam0", "end": True}}).json()
    got = r1["frame_indices"] + r2["frame_indices"] + r3["frame_indices"]
    assert got == [0, 1, 2, 3, 4] and r3["stream"]["ended"] and r3["stream"]["pending"] == 0
    assert server.app.state.dp2.streams == {}
    whole = client.post("/predict_video", json={"frames": frames, "output_format": "npy32",
                                                "include_inverse_depth": True}).json()
    parts = [client.post("/predict_video", json={"frames": frames[a:b], "stream": {"id": "x", "end": b == 5},
                                                 "output_format": "npy32", "include_inverse_depth": True}).json()
             for a, b in ((0, 2), (2, 5))]
    inv_parts = np.concatenate([npy(p["inverse_depth"]) for p in parts if p["frames"]])
    assert np.array_equal(inv_parts, npy(whole["inverse_depth"]))  # same clips, same cross-fade


def test_errors(client):
    good = {"image": b64(SAMPLE)}
    cases = [
        ("/predict", {"image": "not base64!"}, 400), ("/predict", {"image": b64(b"hello")}, 400),
        ("/predict", dict(good, f_px=-1.0), 400), ("/predict", dict(good, f_px=0), 400),
        ("/predict", dict(good, png_scale=0), 400), ("/predict", dict(good, temperature=1), 422),
        ("/predict", dict(good, output_format="jpeg"), 422), ("/predict", {}, 422), ("/predict", {"image": 3}, 422),
        ("/predict_video", {"frames": [b64(SAMPLE), b64(png_bytes(np.zeros((32, 32, 3), np.uint8)))]}, 400),
        ("/predict_video", {"frames": [b64(SAMPLE)] * 9}, 400), ("/predict_video", {}, 400),
        ("/predict_video", {"frames": []}, 400),
        ("/predict_video", {"frames": [b64(SAMPLE)], "mode": "live"}, 422),
        ("/predict_video", {"frames": [b64(SAMPLE)], "window": 3}, 400),
        ("/predict_video", {"frames": [b64(SAMPLE)], "mode": "clip", "overlap": 0}, 400),
        ("/predict_video", {"clip": {"format": "npy", "data": b64(b"xx")}}, 400),
        ("/predict_video", {"frames": [b64(SAMPLE)], "stream": {"id": "s", "end": True}, "mode": "clip"}, 400),
    ]
    for route, payload, want in cases:
        r = client.post(route, json=payload)
        assert r.status_code == want, (route, list(payload), r.status_code, r.text[:200])
        if want == 400:
            assert r.json()["detail"]


def test_unbuffered_stream_over_http(client):
    g = golden("stream_unbuf_w4_n6__S")
    frames = [b64(png_bytes(a)) for a in g["input_u8"].numpy()[:3]]
    info = client.get("/info").json()["configuration"]
    assert info["video_modes"] == ["buffered", "unbuffered"] and info["kv_streams"] == 1
    assert info["kv_cache"]["caches"] == 2  # one per bucket
    got = []
    for k, f in enumerate(frames):
        r = client.post("/predict_video", json={"frames": [f], "mode": "unbuffered", "f_px": 300.0 if k == 0 else None,
                                                "include_inverse_depth": True, "stream": {"id": "u", "end": k == 2}})
        assert r.status_code == 200, r.text
        body = r.json()
        assert body["frame_indices"] == [k] and body["stream"]["mode"] == "unbuffered"  # returned at once
        got.append(npy(body["inverse_depth"])[0].astype(np.float32))
        if k == 0:
            busy = client.post("/predict_video", json={"frames": [f], "mode": "unbuffered", "stream": {"id": "u2"}})
            assert busy.status_code == 429  # DEPTHPRO2_MAX_STREAMS=1 here (KV_STREAMS=1 as well)
            whole = client.post("/predict_video", json={"frames": [f], "mode": "unbuffered"})
            assert whole.status_code == 429 and "KV_STREAMS" in whole.json()["detail"]  # needs a cache too
            wrong = client.post("/predict_video", json={"frames": [f], "stream": {"id": "u"}})
            assert wrong.status_code == 400  # a buffered request on the unbuffered stream
    # the same frames through the API in one unbuffered video (window 2 = the server's window)
    model = server.app.state.dp2.model
    api = [o.inverse_depth.numpy() for o in model.infer_video(list(g["input_u8"].numpy()[:3]), mode="unbuffered",
                                                                f_px=300.0)]
    assert rel_err(np.stack(got), np.stack(api)) < 2e-3
    assert model._kv_open == 0 and server.app.state.dp2.streams == {}


def test_buffered_only_server_refuses_unbuffered(monkeypatch):
    with client_with(monkeypatch, DEPTHPRO2_VIDEO_MODES="buffered") as c:
        assert c.get("/config").json()["configuration"]["video_modes"] == ["buffered"]
        r = c.post("/predict_video", json={"frames": [b64(SAMPLE)], "mode": "unbuffered"})
        assert r.status_code == 400 and "not enabled" in r.json()["detail"]


def test_body_limit(monkeypatch):
    with client_with(monkeypatch, DEPTHPRO2_MAX_BODY_MB="1") as c:
        r = c.post("/predict", json={"image": "A" * (2 << 20)})
        assert r.status_code == 400 and "MAX_BODY_MB" in r.json()["detail"]


def test_device_failure_is_500_and_starting_is_503(monkeypatch):
    def failing(cfg):
        m = cpu_factory(cfg)

        def boom(x):
            raise RuntimeError("device hung")

        m.engine.inverse_depth = boom
        return m

    with client_with(monkeypatch, failing) as c:
        r = c.post("/predict", json={"image": b64(SAMPLE)})
        assert r.status_code == 500 and "RuntimeError: device hung" in r.json()["detail"]
        st = server.app.state.dp2
        st.ready = False
        assert c.post("/predict", json={"image": b64(SAMPLE)}).status_code == 503
        assert c.get("/health").json()["status"] == "starting"
        st.ready = True


def test_startup_refuses_a_bad_configuration(monkeypatch):
    with pytest.raises(RuntimeError, match="DEPTHPRO2_WINDOW"):
        with client_with(monkeypatch, DEPTHPRO2_WINDOW="99"):
            pass
    with pytest.raises(RuntimeError, match="DEPTHPRO2_ENC_PRECISION"):
        server.load_config({"DEPTHPRO2_ENC_PRECISION": "medium"})
    assert server.load_config({"DEPTHPRO2_ENC_PRECISION": "fast"}).model.enc_precision == "fast"
    assert server.app.state.dp2.error is None  # restored by client_with


def test_shutdown_closes_the_model(monkeypatch):
    with client_with(monkeypatch) as c:
        m = server.app.state.dp2.model
        r = c.post("/predict_video", json={"frames": [b64(SAMPLE)], "stream": {"id": "open"}})
        assert r.status_code == 200, r.text
        st = server.app.state.dp2
        assert st.streams  # the open stream is closed at shutdown too
    assert m.closed and server.app.state.dp2.model is not m


def _free_port() -> int:
    with socket.socket() as s:
        s.bind(("127.0.0.1", 0))
        return s.getsockname()[1]


def test_smoke_test_passes_over_http(monkeypatch, tmp_path):
    """The stdlib smoke test (what container_smoke.sh runs) against the app served by uvicorn on the CPU engine."""
    need_weights("S")
    uvicorn = pytest.importorskip("uvicorn")
    import importlib.util

    for k, v in dict(ENV, DEPTHPRO2_RESOLUTIONS="vga", DEPTHPRO2_MAX_STREAMS="2").items():
        monkeypatch.setenv(k, v)
    st = server.app.state.dp2
    old = (st.model_factory, st.model, st.config, st.ready, st.error)
    st.model_factory, st.model, st.config, st.ready, st.error = (lambda cfg: cpu_factory(cfg, warmup=True)), None, \
        None, False, None
    port = _free_port()
    srv = uvicorn.Server(uvicorn.Config(server.app, host="127.0.0.1", port=port, log_level="warning", lifespan="on"))
    t = threading.Thread(target=srv.run, daemon=True)
    t.start()
    try:
        spec = importlib.util.spec_from_file_location("dp2_smoke", SMOKE)
        smoke = importlib.util.module_from_spec(spec)
        spec.loader.exec_module(smoke)
        out = tmp_path / "smoke.json"
        # a staged-manifest stand-in pinning profile s (what tt-model writes: container.serve(.env), serve_profiles)
        man = tmp_path / "tt_kernel_manifest.json"
        from tt_depthpro2 import config as C

        man.write_text(json.dumps({
            "name": "depthpro2", "weights": {"repo": "apple/DepthPro2-focal", "revision": C.WEIGHTS["focal"][1]},
            "auxiliary_weights": [{"repo": r, "revision": v} for k, (r, v) in C.WEIGHTS.items() if k != "focal"],
            "container": {"serve": {"env": {"DEPTHPRO2_DISPATCH": "eth", "DEPTHPRO2_NUM_CQS": "1",
                                            "DEPTHPRO2_RESOLUTIONS": "vga", "DEPTHPRO2_WINDOW": "2",
                                            "DEPTHPRO2_OVERLAP": "1"}},
                          "serve_profiles": [{"name": "s", "env": {"DEPTHPRO2_SIZE": "S"}}], "default_profile": "s"}}))
        rc = smoke.main(["--url", f"http://127.0.0.1:{port}", "--wait", "300", "--out", str(out),
                         "--manifest", str(man)])
        assert rc == 0
        body = json.loads(out.read_text())
        assert body["size"] == "S" and "<" in body["depth"]["data"]  # arrays elided
    finally:
        srv.should_exit = True
        t.join(timeout=60)
        st.model_factory, st.model, st.config, st.ready, st.error = old