File size: 11,339 Bytes
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
# SPDX-License-Identifier: Apache-2.0
"""Host tests of the bundle wiring (no device, no weights): the vendored ttaw copy is intact; the server, config and
smoke modules import without ttnn / torch; tt-model.yaml agrees with config.py (weights pins, serve env, profiles)
and its serve env starts the server's configuration; the shipped sample, its references and the licence notices
are what tt-model.yaml verifies; the stdlib helpers of the smoke test and the client work; container_smoke.sh
parses; the pip project is the repo-root pyproject.toml.

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

import fnmatch
import hashlib
import importlib.util
import io
import json
import os
import subprocess
import sys
from pathlib import Path

import numpy as np
import pytest

import tt_depthpro2
from tt_depthpro2 import config as C

PKG_DIR = Path(tt_depthpro2.__file__).resolve().parent
CODE_DIR, BUNDLE_DIR, TTAW_DIR = PKG_DIR.parent, PKG_DIR.parents[1], PKG_DIR / "ttaw"
YAML = BUNDLE_DIR / "tt-model.yaml"
SAMPLE = PKG_DIR / "samples" / "kropa_street"
VENDOR_IGNORE = ("__pycache__", "*.pyc", "*.pyo", ".pytest_cache", "*.bin", "*.log", ".DS_Store", "VENDORED.json")

BLOCKER = """
import importlib, importlib.abc, sys
BLOCKED = set(sys.argv[2].split(","))
class Block(importlib.abc.MetaPathFinder):
    def find_spec(self, name, path, target=None):
        if name.split(".")[0] in BLOCKED:
            raise ImportError("blocked import of " + name)
sys.meta_path.insert(0, Block())
sys.path.insert(0, sys.argv[1])
for module in sys.argv[3:]:
    importlib.import_module(module)
print("ok")
"""


def _yaml():
    yaml = pytest.importorskip("yaml")
    return yaml.safe_load(YAML.read_text())


def _load(name, path):
    spec = importlib.util.spec_from_file_location(name, path)
    mod = importlib.util.module_from_spec(spec)
    sys.modules[name] = mod
    spec.loader.exec_module(mod)
    return mod


def test_vendored_ttaw_is_intact():
    rec = json.loads((TTAW_DIR / "VENDORED.json").read_text())
    assert rec["package"] == "ttaw" and not rec["source_dirty"] and len(rec["source_commit"]) == 40
    have = {}
    for p in sorted(TTAW_DIR.rglob("*")):
        rel = p.relative_to(TTAW_DIR)
        if p.is_file() and not any(fnmatch.fnmatch(part, pat) for part in rel.parts for pat in VENDOR_IGNORE):
            have[rel.as_posix()] = hashlib.sha256(p.read_bytes()).hexdigest()
    assert have == rec["files"], "the vendored ttaw was edited: re-vendor with common/tools/vendor.py"


def _same_path_env():
    """The subprocess sees the modules this process sees (pytest may run with a PYTHONPATH that lacks, e.g., the
    directory providing fastapi while conftest / plugins added others to sys.path)."""
    import os

    env = dict(os.environ)
    env["PYTHONPATH"] = os.pathsep.join(p for p in sys.path if p)
    return env


def test_imports_without_ttnn_and_torch():
    import importlib.util

    mods = ["tt_depthpro2", "tt_depthpro2.config", "tt_depthpro2.io", "tt_depthpro2.device", "tt_depthpro2.server"]
    if importlib.util.find_spec("fastapi") is not None:  # the server needs the [server] extras
        mods.append("tt_depthpro2.server.app")
    r = subprocess.run([sys.executable, "-c", BLOCKER, str(CODE_DIR), "ttnn,torch"] + mods, capture_output=True,
                       text=True, env=_same_path_env())
    assert r.returncode == 0 and r.stdout.strip() == "ok", r.stderr[-2000:]
    # the API module imports without ttnn (torch only when a model is built)
    r = subprocess.run([sys.executable, "-c", BLOCKER, str(CODE_DIR), "ttnn,torch", "tt_depthpro2.api"],
                       capture_output=True, text=True, env=_same_path_env())
    assert r.returncode == 0, r.stderr[-2000:]


def test_stdlib_scripts_run_under_plain_python():
    """smoke_test.py and client.py run with the host's python3 (no numpy, no package installed)."""
    blocker = BLOCKER.replace("for module in sys.argv[3:]:\n    importlib.import_module(module)\n", "")
    for script in (PKG_DIR / "server" / "smoke_test.py", PKG_DIR / "server" / "client.py"):
        code = blocker + f"\nimport runpy, sys\nsys.argv = ['{script.name}', '--help']\n" \
                         f"try:\n    runpy.run_path({str(script)!r}, run_name='__main__')\nexcept SystemExit as e:\n" \
                         f"    assert e.code in (0, None), e.code\n"
        r = subprocess.run([sys.executable, "-I", "-c", code, "/nonexistent", "numpy,torch,ttnn,tt_depthpro2,PIL"],
                           capture_output=True, text=True, cwd="/")
        assert r.returncode == 0, (script.name, r.stderr[-2000:])


def test_manifest_agrees_with_config():
    y = _yaml()
    assert y["repo"] == C.PACKAGE_REPO and y["name"] == C.MODEL_NAME and y["kind"] == "tt-dit-server"
    assert (y["weights"]["repo"], y["weights"]["revision"]) == C.WEIGHTS["focal"]
    aux = {(a["repo"], a["revision"]) for a in y["auxiliary_weights"]}
    assert aux == {C.WEIGHTS[s] for s in C.SIZES}
    for w in [y["weights"]] + y["auxiliary_weights"]:
        assert w["allow_patterns"] == C.ALLOW_PATTERNS
    env = y["serve"]["env"]
    assert env["TT_WEIGHTS_REVISION"] == C.WEIGHTS["focal"][1] and env["DEPTHPRO2_DISPATCH"] == "eth"
    assert {p["name"]: p["env"]["DEPTHPRO2_SIZE"] for p in y["serve_profiles"]} == {k: v for k, v in C.PROFILES.items()}
    assert y["default_profile"] == "l"
    assert y["runtime"]["app"] == "tt_depthpro2.server.app:app"
    for path in y["source"]["extra_code"][0]["paths"]:
        assert (CODE_DIR / path).exists(), path
    card = y["card"]
    assert card["license"]["id"] == "other" and card["license"]["name"] and "LICENSE" in card["license"]["link"]
    assert card["pipeline_tag"] == "depth-estimation"
    assert set(card["base_model"]) == {C.WEIGHTS[k][0] for k in C.WEIGHTS}
    for field in ("attribution", "licensing"):
        text = " ".join(card[field].split())
        assert C.LICENSE_NOTICE in text, field
    assert "research purposes only" in card["licensing"] and "not affiliated with or endorsed by Apple" in \
        " ".join(card["attribution"].split())


def test_serve_env_starts_the_pinned_configuration():
    pytest.importorskip("fastapi")
    from tt_depthpro2.server.app import load_config

    y = _yaml()
    aux = ",".join(f"{a['repo']}@{a['revision']}" for a in y["auxiliary_weights"])
    for p in y["serve_profiles"]:
        env = dict(y["serve"]["env"], **p["env"], TT_AUXILIARY_WEIGHTS=aux,
                   TT_MODEL_WEIGHTS_REVISION=y["weights"]["revision"], HF_MODEL=y["weights"]["repo"],
                   TT_MESH_SHAPE="1x1")
        c = load_config(env)
        size = C.PROFILES[p["name"]]
        assert c.model.size == size and c.revision == C.WEIGHTS[size][1] and c.fov_revision == C.WEIGHTS["focal"][1]
        assert (c.model.resolutions, c.model.window, c.model.overlap) == (((480, 640), (640, 480)), 16, 4)


def test_sample_references_and_licences():
    y = _yaml()
    meta = json.loads((SAMPLE / "sample.json").read_text())
    img = SAMPLE / meta["file"]
    sha = hashlib.sha256(img.read_bytes()).hexdigest()
    assert any(sha in v for v in y["verify"]), "tt-model.yaml verifies another sample image"
    assert "CC0" in meta["license"] and "CC0" in (SAMPLE / "PROVENANCE.md").read_text()
    from PIL import Image

    with Image.open(img) as im:
        assert im.size == (640, 480) and not dict(im.getexif())  # no EXIF (the original had GPS)
    for s in C.SIZES:
        ref = json.loads((SAMPLE / f"reference.{s}.json").read_text())
        arr = np.load(SAMPLE / f"reference.{s}.npy")
        assert ref["size"] == s and ref["input_size"] == [480, 640] and arr.shape == (120, 160)
        assert arr.dtype == np.float16 and np.isfinite(arr).all() and (arr >= 0).all()
        assert ref["weights"]["size"]["revision"] == C.WEIGHTS[s][1]
        assert ref["weights"]["focal"]["revision"] == C.WEIGHTS["focal"][1] and ref["focal_source"] == "fov"
    notice = " ".join((PKG_DIR / "licenses" / "NOTICE.md").read_text().split())
    assert C.LICENSE_NOTICE in notice and "not made, affiliated with, endorsed or supported by Apple" in notice
    lic = (PKG_DIR / "licenses" / "APPLE_MLR_MODEL_LICENSE.txt").read_bytes()
    assert b"Research Purposes" in lic and b"Model Derivatives" in lic
    # Apple's software licence of ml-depth-pro-2, under which streaming.py follows the structure of Apple's streaming.py
    sw = (PKG_DIR / "licenses" / "APPLE_SOFTWARE_LICENSE.txt").read_bytes()
    assert sw.startswith(b"Copyright (C) 2026 Apple Inc.") and b'"Apple Software"' in sw
    assert "APPLE_SOFTWARE_LICENSE.txt" in notice and "streaming.py" in notice
    assert "APPLE_SOFTWARE_LICENSE.txt" in (PKG_DIR / "streaming.py").read_text().split('"""')[0]
    # optional cross-checks against the upstream files (DEPTHPRO2_UPSTREAM_LICENSE: the model repo's LICENSE,
    # DEPTHPRO2_UPSTREAM_CODE_LICENSE: ml-depth-pro-2's LICENSE)
    for var, data in (("DEPTHPRO2_UPSTREAM_LICENSE", lic), ("DEPTHPRO2_UPSTREAM_CODE_LICENSE", sw)):
        upstream = Path(os.environ.get(var) or "/nonexistent")
        if upstream.is_file():
            assert upstream.read_bytes() == data, var


def test_smoke_helpers():
    smoke = _load("dp2_smoke_t", PKG_DIR / "server" / "smoke_test.py")
    for dt in (np.float16, np.float32):
        a = (np.arange(48, dtype=np.float32).reshape(6, 8) / 7).astype(dt)
        buf = io.BytesIO()
        np.save(buf, a)
        shape, vals = smoke.parse_npy(buf.getvalue())
        assert shape == (6, 8) and np.allclose(vals, a.astype(np.float32).ravel())
        pooled = smoke.avg_pool(vals, 6, 8, 2)
        assert np.allclose(pooled, a.astype(np.float32).reshape(3, 2, 4, 2).mean(axis=(1, 3)).ravel(), atol=1e-6)
    x = list(np.random.default_rng(0).normal(size=100))
    assert abs(smoke.pcc(x, [2 * v + 1 for v in x]) - 1) < 1e-12
    tiny = smoke._tiny_png(32, 32)
    assert smoke.png_ihdr(tiny) == (32, 32, 8, 2)
    from PIL import Image

    assert Image.open(io.BytesIO(tiny)).size == (32, 32)


def test_client_requests():
    client = _load("dp2_client_t", PKG_DIR / "server" / "client.py")
    body = client.sample_request(f_px=400.0, output_format="npy32")
    assert body["f_px"] == 400.0 and body["output_format"] == "npy32" and len(body["image"]) > 1000
    tiny = _load("dp2_smoke_t2", PKG_DIR / "server" / "smoke_test.py")._tiny_png(16, 16)
    frames = client.png_frames_from_stream(tiny * 3)
    assert frames == [tiny] * 3
    v = client.build_video_request([tiny, tiny], mode="clip", stream_id="a", end=True)
    assert v["mode"] == "clip" and len(v["frames"]) == 2 and v["stream"] == {"id": "a", "end": True}
    assert "image" not in client.summarize({"depth": {"data": "x" * 10}})


def test_container_smoke_script_and_pyproject():
    r = subprocess.run(["bash", "-n", str(CODE_DIR / "scripts" / "container_smoke.sh")], capture_output=True)
    assert r.returncode == 0, r.stderr
    assert (BUNDLE_DIR / "pyproject.toml").is_file() and not (CODE_DIR / "pyproject.toml").exists()
    text = (BUNDLE_DIR / "pyproject.toml").read_text()
    assert 'include = ["tt_depthpro2*"]' in text and '"tt_depthpro2" = ["samples/*/*", "licenses/*"]' in text