# SPDX-License-Identifier: Apache-2.0 """ttnn baseline of DepthPro2 on the device: stage-level PCC (ENC / DEC / FOV, S) and end-to-end gates (SPEC §5) for every size through ``DepthPro2Device`` (traced), plus trace-replay determinism. Run through the workspace lock, naming this file: ``bin/devrun -t 5400 -- python -m pytest -q -s -o faulthandler_timeout=3000 \ bundles/depthpro2/code/tt_depthpro2/tests/test_device_baseline.py`` (``-k "stage"`` / ``-k "e2e and S"`` select subsets). Results are appended to ``logs/depthpro2/baseline/results.jsonl`` (``DEPTHPRO2_BASELINE_RESULTS`` overrides). """ from __future__ import annotations import json import os import sys import time import pytest import torch sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import baseline_helpers as H # noqa: E402 from tt_depthpro2.reference import model as ref # noqa: E402 from tt_depthpro2.tt import StageShape # noqa: E402 from tt_depthpro2.tt.weights import load_weights, unfold_patches # noqa: E402 pytestmark = pytest.mark.device RESULTS = os.environ.get("DEPTHPRO2_BASELINE_RESULTS", os.path.join(H.ROOT, "logs/depthpro2/baseline/results.jsonl")) E2E_CASES = ("img_vga", "clip4_240x320", "img_375x500_pad") def record(kind: str, **kw) -> None: kw = {"kind": kind, "time": time.strftime("%Y-%m-%d %H:%M:%S"), **kw} os.makedirs(os.path.dirname(RESULTS), exist_ok=True) with open(RESULTS, "a") as f: f.write(json.dumps(kw) + "\n") print(json.dumps(kw)) _W = {} def weights(name: str): if name not in _W: _W[name] = load_weights(H.fov_dir() if name == "fov" else H.size_dir(name)) return _W[name] def to_dev(t: torch.Tensor, device): import ttnn return ttnn.from_torch(t.to(torch.bfloat16), dtype=ttnn.bfloat16, layout=ttnn.TILE_LAYOUT, device=device, memory_config=ttnn.DRAM_MEMORY_CONFIG) # ----------------------------------------------------------------------------------------------- stage level (S) @pytest.mark.parametrize("case", ["img_384x512", "clip4_240x320"]) def test_enc_stage(device, case): import ttnn from tt_depthpro2.tt import ttnn_enc g, _ = H.load_golden(case, "S") x = ref.pad_to_multiple(g["x_norm"]) t, _, hp, wp = x.shape shape = StageShape(t, hp, wp) eng = ttnn_enc.Engine(device, ttnn_enc.Engine.prepare_weights(device, weights("S"), "S"), shape) blocks = {} eng.trunk.hook = lambda i, xt: blocks.__setitem__(i, ttnn.to_torch(xt).float()) taps = eng.run(to_dev(unfold_patches(x, shape.np_).reshape(1, 1, -1, 768), device)) n = shape.n blk = [] for i, xb in sorted(blocks.items()): dev_b = torch.cat([xb[:, 0, n:n + 5], xb[:, 0, :n]], dim=1) blk.append(round(H.pcc(dev_b, g[f"enc.block{i:02d}.out"]), 6)) res = [] for i, tp in enumerate(taps): d = ttnn.to_torch(tp).float().reshape(t, shape.np_, -1)[:, :n] res.append({"pcc": H.pcc(d, g[f"tap{i}"]), "max_rel": H.max_rel(d, g[f"tap{i}"])}) record("stage_enc", size="S", case=case, taps=res, block_pcc=blk) assert min(r["pcc"] for r in res) >= 0.999, res assert min(blk) >= 0.999, blk @pytest.mark.parametrize("case", ["img_384x512", "clip4_240x320", "img_vga"]) def test_dec_stage(device, case): import ttnn from tt_depthpro2.tt import ttnn_dec g, _ = H.load_golden(case, "S") x = ref.pad_to_multiple(g["x_norm"]) t, _, hp, wp = x.shape shape = StageShape(t, hp, wp) eng = ttnn_dec.Engine(device, ttnn_dec.Engine.prepare_weights(device, weights("S"), "S"), shape) taps = [] for i in range(4): tp = torch.zeros(t, shape.np_, g[f"tap{i}"].shape[-1]) tp[:, :shape.n] = g[f"tap{i}"] taps.append(to_dev(tp.reshape(1, 1, -1, tp.shape[-1]), device)) out = ttnn.to_torch(eng.run(taps)).float().reshape(t, hp, wp) ref_o = g["head.out"][:, 0] r = {"pcc": H.pcc(out, ref_o), "max_rel": H.max_rel(out, ref_o)} record("stage_dec", size="S", case=case, inv=r) assert r["pcc"] >= 0.9999, r @pytest.mark.parametrize("case", ["img_384x512", "clip4_240x320", "img_375x500_pad"]) def test_fov_stage(device, case): import ttnn from tt_depthpro2.tt import ttnn_fov g, _ = H.load_golden(case, "S") x = g["x_norm"] y = ref.fov_resize(x) t, _, h, w = y.shape shape = StageShape(t, h, w) fw = weights("fov") with torch.no_grad(): tok, grid = ref.fov_trunk(y, fw) lg_ref = ref.fov_head(tok, grid, fw) eng = ttnn_fov.Engine(device, ttnn_fov.Engine.prepare_weights(device, fw), shape) lg = ttnn.to_torch(eng.run(to_dev(unfold_patches(y, shape.np_).reshape(1, 1, -1, 768), device))).float().reshape(t, 2) deg = ref.fov_logits_to_deg(lg, tuple(x.shape[-2:]), (h, w)) f = float(ref.median_focal_length_px(deg, *x.shape[-2:])) f_ref = float(g["focallength_px"]) r = {"logit_maxabs": float((lg - lg_ref).abs().max()), "fov_deg_maxabs": float((deg - g["fov_deg"]).abs().max()), "f_px": f, "f_px_golden": f_ref, "f_rel": abs(f / f_ref - 1)} fbud, fwhy = H.fov_budget(case) r.update(f_rel_budget=fbud, f_budget_from=fwhy) record("stage_fov", case=case, fov=r) assert r["f_rel"] <= fbud, r # ----------------------------------------------------------------------------------------------- end to end def _cases(size: str): return [c for c in E2E_CASES if H.golden_path(c, size) is not None] @pytest.mark.parametrize("size", ["S", "B", "L", "H"]) def test_e2e(device, size): """DepthPro2Device (traced ENC + DEC, traced FOV) on every golden case of ``size``; SPEC §5 gates.""" from tt_depthpro2.tt.model import DepthPro2Device cases = _cases(size) goldens = {c: H.load_golden(c, size)[0] for c in cases} shapes = {c: ref.pad_to_multiple(g["x_norm"]).shape for c, g in goldens.items()} buckets = sorted({(s[-2], s[-1]) for s in shapes.values()}) fov_shapes = sorted({tuple(ref.fov_resize(g["x_norm"][:1]).shape[-2:]) for g in goldens.values()}) t0 = time.perf_counter() # T=1 everywhere up front; the clip (T=4) compiles on first use (exercises the release / recapture path) m = DepthPro2Device(device, size, weights(size), weights("fov"), buckets=buckets, max_frames=1, fov_shapes=fov_shapes) build_s = time.perf_counter() - t0 failures = [] try: for c in cases: g = goldens[c] x = g["x_norm"] t, _, h, w = x.shape t1 = time.perf_counter() inv = m.inverse_depth(ref.pad_to_multiple(x))[:, :h, :w] first_ms = (time.perf_counter() - t1) * 1e3 t1 = time.perf_counter() inv2 = m.inverse_depth(ref.pad_to_multiple(x))[:, :h, :w] call_ms = (time.perf_counter() - t1) * 1e3 met = H.drift_metrics(inv, g["inverse_depth"].reshape(t, h, w)) budget, why = H.absrel_budget(c, size) y = ref.fov_resize(x) lg = m.fov_logits(y) deg = ref.fov_logits_to_deg(lg, (h, w), tuple(y.shape[-2:])) f = float(ref.median_focal_length_px(deg, h, w)) f_rel = abs(f / float(g["focallength_px"]) - 1) fbud, fwhy = H.fov_budget(c) ok = met["pcc"] >= 0.999 and met["absrel_valid"] <= budget and f_rel <= fbud and torch.equal(inv, inv2) record("e2e", size=size, case=c, golden=os.path.basename(os.path.dirname(H.golden_path(c, size))), metrics=met, absrel_budget=budget, budget_from=why, f_px=f, f_px_golden=float(g["focallength_px"]), f_rel=f_rel, f_rel_budget=fbud, f_budget_from=fwhy, fov_deg_maxabs=float((deg - g["fov_deg"]).abs().max()), repeat_bitexact=bool(torch.equal(inv, inv2)), first_call_ms=first_ms, call_ms=call_ms, build_s=build_s, passed=ok) if not ok: failures.append(c) finally: m.close() assert not failures, failures def test_trace_determinism(device): """50 back-to-back replays of one traced configuration are bit-identical (the 500-run stress is in the bench).""" from tt_depthpro2.tt.model import DepthPro2Device g, _ = H.load_golden("img_vga", "S") x = ref.pad_to_multiple(g["x_norm"]) m = DepthPro2Device(device, "S", weights("S"), None, buckets=[tuple(x.shape[-2:])], max_frames=1) try: first = m.inverse_depth(x) diffs = sum(int(not torch.equal(first, m.inverse_depth(x))) for _ in range(50)) finally: m.close() record("determinism", size="S", case="img_vga", replays=50, mismatches=diffs) assert diffs == 0 @pytest.mark.parametrize("n", [2, 3]) def test_valid_frames(device, n): """One T=4 program serving an n-frame clip (runtime valid-frame count) == the exact T=n program.""" import ttnn from tt_depthpro2.tt import ttnn_dec, ttnn_enc g, _ = H.load_golden("clip4_240x320", "S") x = ref.pad_to_multiple(g["x_norm"])[:n] we = ttnn_enc.Engine.prepare_weights(device, weights("S"), "S") wd = ttnn_dec.Engine.prepare_weights(device, weights("S"), "S") def run(t): sh = StageShape(t, 256, 320) enc, dec = ttnn_enc.Engine(device, we, sh), ttnn_dec.Engine(device, wd, sh) xp = torch.cat([x, x.new_zeros(t - n, 3, 256, 320)]) if t > n else x enc.set_valid_frames(n) return ttnn.to_torch(dec.run(enc.run(to_dev(unfold_patches(xp, sh.np_).reshape(1, 1, -1, 768), device)))).float()[:n] exact, padded = run(n), run(4) r = {"pcc": H.pcc(padded, exact), "max_rel": H.max_rel(padded, exact)} record("valid_frames", size="S", case="clip4_240x320", n=n, program_T=4, vs_exact=r) assert r["pcc"] >= 0.99999, r def test_fov_any_t(device): """fov_logits on 1 frame and on the window (4) with the programs T in {1, 4}; 3 frames run in the T=4 program.""" from tt_depthpro2.tt.model import DepthPro2Device g, _ = H.load_golden("clip4_240x320", "S") y = ref.fov_resize(g["x_norm"]) fw = weights("fov") with torch.no_grad(): lg_ref = ref.fov_head(*ref.fov_trunk(y, fw), fw) m = DepthPro2Device(device, "S", weights("S"), fw, buckets=[(256, 320)], max_frames=4, frames=(1,)) try: res = {t: float((m.fov_logits(y[:t]) - lg_ref[:t]).abs().max()) for t in (1, 3, 4)} finally: m.close() record("fov_any_t", case="clip4_240x320", logit_maxabs=res) assert max(res.values()) < 0.02, res def test_kv_stream(device): """Unbuffered video (KV cache, window 4) through tt_depthpro2.streaming on stream_unbuf_w4_n6 (S): per frame PCC >= 0.999 and AbsRel <= max(2 x official clip4 drift, 0.01); a 2nd interleaved stream is bit-identical.""" from tt_depthpro2.streaming import DepthStream from tt_depthpro2.tt.model import DepthPro2Device g, _ = H.load_golden("stream_unbuf_w4_n6", "S") frames = ref.preprocess(g["input_u8"].round().to(torch.uint8).numpy()) m = DepthPro2Device(device, "S", weights("S"), None, buckets=[(256, 320)], max_frames=4, frames=(1,), kv_cache=True, kv_streams=2) times = [] def step(clip, cache): t0 = time.perf_counter() out = m.inverse_depth_step(ref.pad_to_multiple(clip), cache)[:, :240, :320] times.append((time.perf_counter() - t0) * 1e3) return out def run_stream(): st = DepthStream(lambda c: None, window=4, overlap=0, f_px=float(g["focallength_px"]), mode="unbuffered", predict_step=step, open_cache=lambda: m.kv_cache((256, 320), 4)) return st try: a, b = run_stream(), run_stream() # two open caches, steps interleaved pa, pb = [], [] for f in frames: pa += a.step(f) pb += b.step(f) pa += a.flush() pb += b.flush() a.close() b.close() nbytes = m.kv_cache_bytes() finally: m.close() d, src = H.official_drift_absrel("clip4_240x320", "S") budget = max(2 * (d or 0.0), 0.01) per = [] for p in pa: met = H.drift_metrics(p.inverse_depth, g["inverse_depth"][p.index]) per.append({"frame": p.index, "pcc": met["pcc"], "absrel_valid": met["absrel_valid"]}) same = all(torch.equal(x.inverse_depth, y.inverse_depth) for x, y in zip(pa, pb)) record("kv_stream", size="S", case="stream_unbuf_w4_n6", window=4, frames=per, absrel_budget=budget, budget_from=src, interleaved_bitexact=same, cache_bytes=nbytes, step_ms=times) assert len(per) == len(frames) and same assert all(r["pcc"] >= 0.999 and r["absrel_valid"] <= budget for r in per), per @pytest.mark.parametrize("size", ["S", "B", "L", "H"]) def test_vga_t16(device, size): """Regression (round 3): a 16-frame 480x640 clip on the T=16 program (n = 16) and its first 5 frames through the valid-frame path (n = 5), against the float32 reference (tests/make_clip16_refs.py). Every frame: finite, PCC >= 0.999.""" from safetensors.torch import load_file from tt_depthpro2.tt.model import DepthPro2Device path = os.path.join(H.BASELINE_REF, f"clip16_480x640__{size}.safetensors") if not os.path.exists(path): pytest.skip(f"{path} missing (tests/make_clip16_refs.py)") r = load_file(path) x = r["x_norm"] m = DepthPro2Device(device, size, weights(size), None, buckets=[(480, 640)], max_frames=16) res = {} try: for n, key in ((16, "inverse_depth"), (5, "inverse_depth_n5")): inv = m.inverse_depth(x[:n]) ref_inv = r[key] per = [H.pcc(inv[f], ref_inv[f]) for f in range(n)] met = [H.drift_metrics(inv[f], ref_inv[f]) for f in range(n)] # AbsRel (depth) is not gated: a few valid pixels (ref >= 1% of the max) at the seams of the rolled frames # come out 0 after the final ReLU, and 1 / 1e-9 dominates the mean; the inverse-depth p99 is reported. res[n] = {"finite": bool(torch.isfinite(inv).all()), "absmax": float(inv.abs().max()), "pcc_min": min(per), "pcc_frames": [round(p, 6) for p in per], "absrel_valid_median": float(torch.tensor([m["absrel_valid"] for m in met]).median()), "inv_rel_p99_valid_max": max(m["inv_rel_p99_valid"] for m in met)} finally: m.close() record("vga_t16", size=size, program_T=16, results=res) for n, v in res.items(): assert v["finite"] and v["pcc_min"] >= 0.999, (n, v) @pytest.mark.parametrize("size", ["L", "H"]) def test_startup_3buckets_kv(device, size): """Regression (round 3): start-up with 3 buckets (480x640, 640x480, 256x320), window 16, images, FOV and the KV cache (serve's DepthPro2 configuration), then one call per bucket and one KV step. Needs a trace region of ``trace_region_bytes`` (run with DEPTHPRO2_TRACE_REGION set accordingly).""" from tt_depthpro2.tt.model import DepthPro2Device, planned_frames, trace_region_bytes buckets = [(480, 640), (640, 480), (256, 320)] need = trace_region_bytes(size, buckets, planned_frames(16, clip_lengths="all"), kv_cache=True) have = int(os.environ.get("DEPTHPRO2_TRACE_REGION", "0") or 0) if have < need: pytest.skip(f"needs DEPTHPRO2_TRACE_REGION >= {need} (trace_region_bytes), have {have}") t0 = time.perf_counter() m = DepthPro2Device(device, size, weights(size), weights("fov"), buckets=buckets, max_frames=16, frames=(1,), clip_lengths="all", kv_cache=True) build = time.perf_counter() - t0 out = {} try: for hp, wp in buckets: inv = m.inverse_depth(torch.randn(1, 3, hp, wp) * 0.5) out[f"{hp}x{wp}"] = bool(torch.isfinite(inv).all()) c = m.kv_cache((256, 320), 4) st = m.inverse_depth_step(torch.randn(1, 3, 256, 320) * 0.5, c) out["kv_step"] = bool(torch.isfinite(st).all()) c.close() finally: m.close() record("startup_3buckets_kv", size=size, build_s=build, finite=out, trace_region_estimate_mb=need >> 20) assert all(out.values()), out def test_engine_switch(): from tt_depthpro2.tt import model as M assert M.parse_engine(None) == {"enc": "ttnn", "dec": "ttnn", "fov": "ttnn"} assert M.parse_engine("enc=mk,dec=ttnn") == {"enc": "mk", "dec": "ttnn", "fov": "ttnn"} assert M.parse_engine({"fov": "mk"})["fov"] == "mk" with pytest.raises(ValueError): M.parse_engine("enc=foo") for stage in ("enc", "dec", "fov"): assert M.engine_class(stage, "ttnn").__name__ == "Engine" try: cls = M.engine_class(stage, "mk") assert hasattr(cls, "run") except RuntimeError as e: # mk module absent / incomplete: a clear error naming the module assert f"mk_{stage}" in str(e)