Download code/tt_depthpro2/tests/test_host_api.py from changh95/DepthPro2: direct link, hf CLI and curl.
- Browser
- Download file 19 kB
-
https://huggingface.co/changh95/DepthPro2/resolve/main/code/tt_depthpro2/tests/test_host_api.py
- Command line
-
hf download hf://changh95/DepthPro2/code/tt_depthpro2/tests/test_host_api.py
-
curl -L -o test_host_api.py https://huggingface.co/changh95/DepthPro2/resolve/main/code/tt_depthpro2/tests/test_host_api.py
19 kB
| # 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 | |
| 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) | |