File size: 19,034 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
# SPDX-License-Identifier: Apache-2.0
"""Host tests of the Python API (no device): ``DepthPro2`` on the CPU engine (``backend="cpu"``: the float32
reference through the whole host pipeline) against Apple's float32 goldens -- images at a bucket size, an image
replicate-padded to a multiple of 32, a given focal length, a 4-frame clip -- and the host pipeline's own rules: the
resize to the nearest-aspect bucket and back with the focal length scaled, infinite depth where the inverse depth is
0, the output encodings, the clip-length and video-mode checks, the arguments handed to the device engine, the
weights resolution, warm-up and lifetime.

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

import base64
import io
import json

import numpy as np
import pytest
import torch

from tt_depthpro2 import config as C
from tt_depthpro2.api import DepthPro2, load_sample, resolve_weight_dirs
from tt_depthpro2.cpu_engine import CPUEngine
from tt_depthpro2.io import CapacityError, InputError
from tt_depthpro2.tests.host_helpers import WEIGHTS_ROOT, cpu_model, golden, need_weights, new_cpu_model, pcc, rel_err

BUCKETS = "480x640,375x500,240x320"


def model():
    return cpu_model("S", resolutions=BUCKETS, window=4, overlap=1, clip_lengths="all")


# ---------------------------------------------------------------------------------------------- Apple's goldens


@pytest.mark.parametrize("case", ["img_vga__S", "img_375x500_pad__S"])
def test_image_matches_the_official_golden(case):
    g = golden(case)
    out = model().infer(g["input_u8"].numpy()[0])
    assert not out.resized and out.device_size == C.padded_hw(*out.input_size)
    assert out.inverse_depth.shape == g["inverse_depth"].shape
    assert rel_err(out.inverse_depth, g["inverse_depth"]) < 1e-5
    assert pcc(out.inverse_depth, g["inverse_depth"]) > 0.999999
    f_gold = float(g["focallength_px"])
    assert out.focal_source == "fov" and abs(out.focallength_px - f_gold) / f_gold < 1e-3
    assert rel_err(out.depth, g["depth"]) < 1e-3
    assert torch.equal(torch.isinf(out.depth), torch.isinf(g["depth"]))


def test_image_with_f_px_matches_the_official_golden():
    g = golden("img_vga_fpx__S")
    out = model().infer(g["input_u8"].numpy()[0], f_px=500.0)
    assert out.focal_source == "request" and out.focallength_px == 500.0 and out.fov_deg is None
    assert rel_err(out.depth, g["depth"]) < 1e-5


def test_clip_matches_the_official_golden():
    g = golden("clip4_240x320__S")
    m = model()
    out = m.infer_clip(g["input_u8"].numpy())
    assert out.frames == 4 and out.inverse_depth.shape == (4, 240, 320)
    assert rel_err(out.inverse_depth, g["inverse_depth"]) < 1e-5
    assert abs(out.focallength_px - float(g["focallength_px"])) / float(g["focallength_px"]) < 1e-3
    assert rel_err(out.depth, g["depth"]) < 1e-3
    assert len(out.fov_deg) == 4
    # a clip is not 4 images: the cross-frame blocks see all frames
    single = m.infer(g["input_u8"].numpy()[0])
    assert rel_err(single.inverse_depth, g["inverse_depth"][0]) > 1e-4


# ---------------------------------------------------------------------------------------------- host pipeline


def test_resize_to_bucket_and_back():
    g = golden("img_vga__S")
    m = model()
    u8 = g["input_u8"].numpy()[0]
    big = u8.repeat(2, axis=0).repeat(2, axis=1)  # 960 x 1280: same aspect as 480 x 640 -> resized
    out = m.infer(big)
    assert out.resized and out.bucket == (480, 640) and out.input_size == (960, 1280)
    assert out.inverse_depth.shape == (960, 1280) and out.depth.shape == (960, 1280)
    native = m.infer(u8)
    assert abs(out.focallength_px / (2 * native.focallength_px) - 1) < 0.02  # focal in input pixels
    pooled = torch.nn.functional.avg_pool2d(out.inverse_depth[None, None], 2)[0, 0]
    assert pcc(pooled, native.inverse_depth) > 0.995
    # the depth comes from the input-size inverse depth and the input-pixel focal length
    d = out.focallength_px / (1280 * out.inverse_depth)
    assert rel_err(out.depth, d) < 1e-6
    # a 3:4 portrait input goes to... no portrait bucket here: the nearest aspect is 375 x 500 / 480 x 640 (4:3)
    out2 = m.infer(np.ascontiguousarray(u8[:, :360]))  # 480 x 360
    assert out2.resized and out2.inverse_depth.shape == (480, 360)


def test_infinite_depth_where_inverse_depth_is_zero():
    m = model()
    out = m.infer(load_sample())  # the street photo has sky
    inv0 = out.inverse_depth == 0
    assert inv0.any() and torch.equal(torch.isinf(out.depth), inv0)
    assert bool((out.depth[~inv0] > 0).all())
    st = out.stats()
    assert st["infinite_pixels"] == int(inv0.sum()) and 0 < st["min"] < st["median"] < st["max"]


def test_reference_outputs_of_the_sample_are_current():
    """The stored CPU references of the sample (used by the smoke test) equal what the API computes now."""
    from tt_depthpro2.api import SAMPLE_DIR

    m = model()
    out = m.infer(load_sample())
    ref = json.loads((SAMPLE_DIR / "kropa_street" / "reference.S.json").read_text())
    pooled = np.load(SAMPLE_DIR / "kropa_street" / "reference.S.npy")
    got = torch.nn.functional.avg_pool2d(out.inverse_depth[None, None], 4)[0, 0].numpy()
    assert pooled.shape == (120, 160) and np.abs(got - pooled.astype(np.float32)).max() < 2e-3 * np.abs(got).max()
    assert abs(ref["focallength_px"] - out.focallength_px) < 1e-3
    assert ref["weights"]["size"]["revision"] == C.WEIGHTS["S"][1]
    assert ref["weights"]["focal"]["revision"] == C.WEIGHTS["focal"][1]


def test_output_encodings():
    m = model()
    out = m.infer(load_sample())
    body = out.to_dict()
    d = np.load(io.BytesIO(base64.b64decode(body["depth"]["data"])))
    assert d.dtype == np.float16 and d.shape == (480, 640) and body["depth"]["shape"] == [480, 640]
    ref = out.depth.numpy()
    fin = np.isfinite(ref) & (ref < 60000)
    assert np.allclose(d[fin], ref[fin], rtol=1e-3) and np.isinf(d[np.isinf(ref)]).all()
    b32 = out.to_dict("npy32", include_inverse_depth=True)
    assert np.array_equal(np.load(io.BytesIO(base64.b64decode(b32["depth"]["data"]))), ref)
    inv = np.load(io.BytesIO(base64.b64decode(b32["inverse_depth"]["data"])))
    assert np.array_equal(inv, out.inverse_depth.numpy())
    png = out.to_dict("png16", png_scale=100.0)
    from PIL import Image

    im = np.asarray(Image.open(io.BytesIO(base64.b64decode(png["depth"]["data"]))))
    assert im.shape == (480, 640) and im.dtype in (np.uint16, np.int32)
    assert (im[np.isinf(ref)] == 0).all() and png["depth"]["infinite_pixels"] == int(np.isinf(ref).sum())
    near = np.isfinite(ref) & (ref < 600)
    assert np.abs(im[near] / 100.0 - ref[near]).max() <= 0.006
    none = out.to_dict("none")
    assert none["depth"] is None and none["stats_m"]["median"] > 0
    json.dumps(body)  # JSON-serialisable
    with pytest.raises(InputError):
        out.to_dict("jpeg")


def test_input_checks():
    m = model()
    for bad in (-1.0, 0, float("nan"), float("inf"), "x", True):
        with pytest.raises(InputError):
            m.infer(load_sample(), f_px=bad)
    with pytest.raises(InputError):
        m.infer(b"not an image")
    with pytest.raises(InputError):
        m.infer(np.zeros((8, 8, 3), np.uint8))  # below the minimum side
    with pytest.raises(InputError):
        m.infer_clip([np.zeros((240, 320, 3), np.uint8), np.zeros((480, 640, 3), np.uint8)])
    with pytest.raises(InputError):
        m.infer_clip(np.zeros((5, 240, 320, 3), np.uint8))  # longer than the window
    with pytest.raises(InputError):
        list(m.infer_video([np.zeros((240, 320, 3), np.uint8)] * 3, mode="live"))  # not a video mode
    with pytest.raises(InputError):
        list(m.infer_video([np.zeros((240, 320, 3), np.uint8)] * 3, window=5))
    with pytest.raises(InputError):
        list(m.infer_video([np.zeros((240, 320, 3), np.uint8)] * 3, overlap=4))
    # float images in [0, 1] and (3, H, W) tensors are accepted
    x = torch.rand(3, 240, 320)
    a = m.infer(x, f_px=300.0)
    b = m.infer((x.permute(1, 2, 0).numpy() * 255).round().astype(np.uint8), f_px=300.0)
    assert torch.equal(a.inverse_depth, b.inverse_depth)


class ExactLengths(CPUEngine):
    """A device engine WITHOUT a runtime valid-frame count (enc=mk until it has one): exactly the asked lengths."""

    def __init__(self, *a, **kw):
        super().__init__(*a, valid_frames=False, **kw)


def test_valid_frames_serve_every_length():
    need_weights("S")
    with new_cpu_model("S", resolutions="240x320", window=4, overlap=1) as m:
        assert m.clip_lengths == (1, 2, 3, 4) and m.compiled_clip_lengths == (1, 4)
        assert m.info["configuration"]["valid_frames"] and m.info["configuration"]["compiled_clip_lengths"] == [1, 4]
        frames = [np.full((240, 320, 3), 100 + k, np.uint8) for k in range(3)]
        assert m.infer_clip(frames, f_px=200.0).frames == 3
        assert len(list(m.infer_video(frames, f_px=200.0))) == 3  # a video shorter than the window


def test_clip_lengths_are_enforced():
    need_weights("S")
    with new_cpu_model("S", resolutions="240x320", window=4, overlap=1, engine_factory=ExactLengths) as m:
        assert m.clip_lengths == (1, 4) and m.engine.clip_lengths == (1, 4)
        frames = [np.full((240, 320, 3), 100 + k, np.uint8) for k in range(5)]
        with pytest.raises(InputError, match="CLIP_LENGTHS"):
            m.infer_clip(frames[:2])
        out = m.infer_clip(frames[:4], f_px=200.0)
        assert out.frames == 4
        # a 3-frame video needs a 3-frame clip; a 7-frame one with overlap 1 only 4-frame clips
        with pytest.raises(InputError, match="needs a clip"):
            list(m.infer_video(frames[:3], f_px=200.0))
        assert len(list(m.infer_video(frames + frames[:2], f_px=200.0))) == 7
        # the FOV estimator runs in compiled chunks (frames are independent there): 3 frames = 3 x 1
        out = m.infer_video(frames + frames[:2])
        first = next(out)
        assert first.focal_source == "fov" and first.focallength_px > 0
        out.close()


class Recorder(CPUEngine):
    """A CPU engine with the plain DepthPro2Device constructor signature (no **kwargs): records what it was given."""

    seen = {}

    def __init__(self, device, size, size_weights, fov_weights, buckets, max_frames, engine=None, frames=None):
        Recorder.seen = dict(device=device, size=size, buckets=list(buckets), max_frames=max_frames, engine=engine,
                             frames=frames, fov=fov_weights is not None)
        super().__init__(device, size, size_weights, fov_weights, buckets, max_frames, engine, frames,
                         clip_lengths=None, valid_frames=False)


def test_engine_arguments():
    need_weights("S")
    m = DepthPro2.from_pretrained("s", resolutions="720p,240x320", window=6, overlap=2, clip_lengths="2",
                                  engine="enc=mk,dec=ttnn", backend="cpu", engine_factory=Recorder,
                                  weights_dir=str(WEIGHTS_ROOT), fov_weights_dir=str(WEIGHTS_ROOT), warmup=False)
    try:
        s = Recorder.seen
        assert s["size"] == "S" and s["buckets"] == [(736, 1280), (256, 320)] and s["max_frames"] == 6
        assert s["frames"] == (1, 2) and s["engine"] == {"enc": "mk", "dec": "ttnn", "fov": "mk"} and s["fov"]
        assert m.clip_lengths == (1, 2, 6)
        info = m.info
        json.dumps(info)
        cfg = info["configuration"]
        assert cfg["device_sizes"] == {"720x1280": [736, 1280], "240x320": [256, 320]}
        assert cfg["fov_sizes"]["720x1280"] == [512, 896] and cfg["clip_lengths"] == [1, 2, 6]
        assert info["weights"]["size"]["repo"] == "apple/DepthPro2-S" and info["license"]["notice"] == C.LICENSE_NOTICE
        assert not info["supports_unbuffered"] or True
    finally:
        m.close()
        m.close()  # idempotent
    with pytest.raises(RuntimeError):
        m.infer(np.zeros((240, 320, 3), np.uint8))
    # precision the engine does not take is refused, as is unbuffered video without a KV cache

    class NoKV(Recorder):
        supports_kv_cache = False

    with pytest.raises(ValueError, match="precision"):
        DepthPro2.from_pretrained("S", resolutions="qvga", window=2, precision="bfp8", backend="cpu",
                                  engine_factory=Recorder, weights_dir=str(WEIGHTS_ROOT),
                                  fov_weights_dir=str(WEIGHTS_ROOT))
    with pytest.raises(NotImplementedError):
        DepthPro2.from_pretrained("S", resolutions="qvga", window=2, video_modes="buffered,unbuffered",
                                  backend="cpu", engine_factory=NoKV, weights_dir=str(WEIGHTS_ROOT),
                                  fov_weights_dir=str(WEIGHTS_ROOT))


class EnvRecorder(Recorder):
    """Records ``DEPTHPRO2_MK_ENC_OPTS`` as the engine is built."""

    opts = None

    def __init__(self, device, size, size_weights, fov_weights, buckets, max_frames, engine=None, frames=None):
        import os

        EnvRecorder.opts = os.environ.get(C.MK_ENC_OPTS_ENV)
        super().__init__(device, size, size_weights, fov_weights, buckets, max_frames, engine, frames)


def test_enc_precision_maps_to_mk_enc_options(monkeypatch):
    need_weights("S")
    from tt_depthpro2 import api as A

    monkeypatch.setattr(A._device, "describe_device", lambda device, device_id=None: {"dispatch": "test"})
    monkeypatch.setenv(C.MK_ENC_OPTS_ENV, "exp=1,inx32=1")  # an A/B knob of the megakernel: kept; inx32 / klo set
    for prec, want in (("fast", "exp=1,inx32=0,klo=0"), ("high", "exp=1")):
        m = DepthPro2.from_pretrained("S", resolutions="qvga", window=2, enc_precision=prec, backend="tt",
                                      device=object(), engine_factory=EnvRecorder, weights_dir=str(WEIGHTS_ROOT),
                                      fov_weights_dir=str(WEIGHTS_ROOT), warmup=False)
        try:
            cfg = m.info["configuration"]
            assert EnvRecorder.opts == want and cfg["mk_enc_opts"] == want, (prec, EnvRecorder.opts)
            assert cfg["enc_precision"] == prec and cfg["env"]["DEPTHPRO2_ENC_PRECISION"] == prec
        finally:
            m.close()
    # the CPU backend leaves the variable alone
    m = DepthPro2.from_pretrained("S", resolutions="qvga", window=2, enc_precision="fast", backend="cpu",
                                  engine_factory=EnvRecorder, weights_dir=str(WEIGHTS_ROOT),
                                  fov_weights_dir=str(WEIGHTS_ROOT), warmup=False)
    try:
        assert EnvRecorder.opts == "exp=1" and m.info["configuration"]["mk_enc_opts"] is None
    finally:
        m.close()


def test_warmup_and_no_fov():
    need_weights("S", fov=False)
    with new_cpu_model("S", resolutions="qvga", window=2, overlap=0, fov=False, warmup=True) as m:
        assert set(m.warmup_latency_ms) == {"240x320/T1", "240x320/T2"}
        out = m.infer(np.full((240, 320, 3), 90, np.uint8))
        assert out.depth is None and out.focallength_px is None and out.to_dict()["depth"] is None
        assert m.infer(np.full((240, 320, 3), 90, np.uint8), f_px=250.0).depth is not None
        assert m.info["weights"]["focal"] is None


def test_weights_resolution(tmp_path, monkeypatch):
    need_weights("S")
    sw, fw = resolve_weight_dirs("S", weights_dir=str(WEIGHTS_ROOT))
    assert sw["repo"] == "apple/DepthPro2-S" and sw["local"] and sw["revision"] in (None, C.WEIGHTS["S"][1])
    sw2, _ = resolve_weight_dirs("S", fov=False, weights_dir=str(WEIGHTS_ROOT / "DepthPro2-S"))
    assert sw2["path"] == str(WEIGHTS_ROOT / "DepthPro2-S")
    monkeypatch.setenv("DEPTHPRO2_WEIGHTS_DIR", str(tmp_path))
    with pytest.raises(FileNotFoundError):
        resolve_weight_dirs("S", fov=False)
    monkeypatch.delenv("DEPTHPRO2_WEIGHTS_DIR")
    # a directory with another size's weights is refused at build
    with pytest.raises(ValueError, match="DepthPro2-B"):
        DepthPro2.from_pretrained("B", resolutions="qvga", window=2, backend="cpu",
                                  weights_dir=str(WEIGHTS_ROOT / "DepthPro2-S"), fov=False)
    with pytest.raises(ValueError):
        DepthPro2.from_pretrained("S", backend="gpu")
    with pytest.raises(TypeError):
        DepthPro2()


def test_unbuffered_streams_are_limited_by_kv_streams():
    need_weights("S")
    with new_cpu_model("S", resolutions="240x320", window=3, overlap=1, video_modes="buffered,unbuffered") as m:
        assert "unbuffered" in m.config.video_modes and m.config.kv_streams == 1
        f = np.full((240, 320, 3), 90, np.uint8)
        a = m.stream(f_px=200.0, mode="unbuffered")
        assert [o.frame_index for o in a.step(f)] == [0]
        b = m.stream(f_px=200.0, mode="unbuffered")
        with pytest.raises(CapacityError):
            b.step(f)
        b.close()
        with pytest.raises(CapacityError):
            list(m.infer_video([f, f], f_px=200.0, mode="unbuffered"))
        a.close()
        assert m._kv_open == 0
        assert len(list(m.infer_video([f, f], f_px=200.0, mode="unbuffered"))) == 2 and m._kv_open == 0
        plan = m.info["configuration"]["kv_cache"]
        assert plan["caches"] == 1 and plan["per_cache_bytes"] > 0


def test_auto_video_modes_follow_the_kv_budget():
    need_weights("S", fov=False)
    with new_cpu_model("S", resolutions="qvga", window=4, fov=False) as m:  # small caches: unbuffered on
        assert m.config.video_modes == ("buffered", "unbuffered") and "on" in m.video_modes_reason
    # 8 streams x 2 buckets of 1080p, window 16 (720 MB per S cache): far above the budget -> buffered only
    with new_cpu_model("S", resolutions="1080p,1080p_portrait", window=16, kv_streams=8, fov=False) as m:
        assert m.config.video_modes == ("buffered",) and "off" in m.video_modes_reason
        assert m.kv_cache_plan()["total_bytes"] > C.KV_BUDGET_BYTES
    # explicit modes are kept
    with new_cpu_model("S", resolutions="1080p", window=16, kv_streams=8, fov=False,
                       video_modes="buffered,unbuffered") as m:
        assert m.config.video_modes == ("buffered", "unbuffered")


def test_trace_region_is_sized_from_the_configuration(monkeypatch):
    from tt_depthpro2.device import trace_region_for

    monkeypatch.delenv("DEPTHPRO2_TRACE_REGION", raising=False)
    fov = [(480, 640), (640, 480)]
    small = trace_region_for("S", [(480, 640), (640, 480)], 16, clip_lengths=(1, 16), fov_shapes=fov)
    big = trace_region_for("L", [(480, 640), (640, 480)], 16, clip_lengths=(1, 16), fov_shapes=fov, kv_cache=True)
    huge = trace_region_for("H", [(1088, 1920)], 16, clip_lengths=(1, 16), fov_shapes=[(512, 896)], kv_cache=True)
    assert small % (32 << 20) == 0 and small < big < huge and huge > (256 << 20)  # the old fixed 256 MB is too small
    monkeypatch.setenv("DEPTHPRO2_TRACE_REGION", str(512 << 20))
    assert trace_region_for("S", [(480, 640)], 16) is None  # the environment wins (DeviceConfig.from_env reads it)