# SPDX-License-Identifier: Apache-2.0 """Device tests of the ENC megakernel (``tt/mk_enc``): the 4 taps against the float32 goldens / reference, FOV-trunk mode, determinism (repeated runs and trace replays bitwise identical), runtime valid-frame count (set_valid_frames). Run through the device lock, naming this file explicitly: bin/devrun -t 1800 -- python -m pytest -x -q bundles/depthpro2/code/tt_depthpro2/tests/test_device_mk_enc.py \ -o faulthandler_timeout=1500 [-k S] """ from __future__ import annotations import os import pytest import torch from tt_depthpro2.reference import model as R from tt_depthpro2.tests import mk_enc_ref as H ttnn = pytest.importorskip("ttnn") if not os.path.isfile(H.weights_path("S")) or not os.path.isdir(H.GOLDEN): pytest.skip("DepthPro2 weights / goldens not found: set DEPTHPRO2_TEST_WEIGHTS (parent of DepthPro2-/) and " "DEPTHPRO2_GOLDEN (Apple's float32 goldens)", allow_module_level=True) #: minimum tap PCC vs the float32 golden (bf16 weights / activations; the official bf16 run drifts similarly) TAP_PCC = float(os.environ.get("MK_ENC_TAP_PCC", "0.995")) CASES = [ ("S", "img_384x512", "depth"), ("S", "clip4_240x320", "depth"), ("S", "img_vga", "depth"), ("B", "img_vga", "depth"), ("B", "clip4_240x320", "depth"), ("L", "img_vga", "depth"), ("L", "clip4_240x320", "depth"), ("H", "img_vga", "depth"), ("H", "clip4_240x320", "depth"), ("S", "img_384x512", "fov"), ("S", "clip4_240x320", "fov"), ] @pytest.fixture(scope="module") def device(): from tt_depthpro2.tests import baseline_helpers as BH dev = ttnn.open_device(device_id=0, dispatch_core_config=ttnn.DispatchCoreConfig(ttnn.DispatchCoreType.ETH), l1_small_size=BH.L1_SMALL_SIZE, trace_region_size=224 << 20) yield dev ttnn.close_device(dev) _W = {} def weights(size: str): if size not in _W: _W.clear() _W[size] = H.load_weights(size) return _W[size] def frames(case: str, size: str, mode: str) -> torch.Tensor: g = H.load_case(case, "S" if mode == "fov" else size) x = g["x_norm"].float() return R.fov_resize(x) if mode == "fov" else R.pad_to_multiple(x) def golden_taps(case: str, size: str, mode: str, w, x): if mode == "depth": g = H.load_case(case, size) return [g[f"tap{i}"].float() for i in range(4)] _, taps = H.ref_run(w, x, size, 12, mode) return taps def run_taps(dev, w, size: str, x: torch.Tensor, mode: str): from tt_depthpro2.tt.mk_enc import arena as A from tt_depthpro2.tt.mk_enc.program import MkEnc T, _, hp, wp = x.shape mk = MkEnc(dev, w, size, T, hp // 16, wp // 16, mode=mode) patches = ttnn.from_torch(A.patchify(x).to(torch.bfloat16), dtype=ttnn.bfloat16, layout=ttnn.TILE_LAYOUT, device=dev, memory_config=ttnn.DRAM_MEMORY_CONFIG) taps = mk.run(patches) out = [H.taps_from_device(ttnn.to_torch(t).float(), mk.geo) for t in taps] return mk, patches, out @pytest.mark.parametrize("size,case,mode", CASES, ids=[f"{s}-{c}-{m}" for s, c, m in CASES]) def test_taps(device, size, case, mode): w = weights("fov" if mode == "fov" else size) x = frames(case, size, mode) _, _, taps = run_taps(device, w, size, x, mode) ref = golden_taps(case, size, mode, w, x) for i, (d, r) in enumerate(zip(taps, ref)): p, e = H.pcc(d, r), H.rel_err(d, r) print(f"{size} {case} {mode} tap{i}: pcc {p:.6f} rel {e:.3e}") assert p >= TAP_PCC, f"tap{i} pcc {p}" @pytest.mark.parametrize("size,case", [("S", "img_384x512")]) def test_determinism_and_trace(device, size, case): w = weights(size) x = frames(case, size, "depth") mk, patches, first = run_taps(device, w, size, x, "depth") raw = [ttnn.to_torch(t).clone() for t in mk.taps] for _ in range(3): mk.run(patches) for a, t in zip(raw, mk.taps): assert torch.equal(a, ttnn.to_torch(t)), "eager rerun not bitwise identical" tid = ttnn.begin_trace_capture(device, cq_id=0) mk.run(patches) ttnn.end_trace_capture(device, tid, cq_id=0) for _ in range(5): ttnn.execute_trace(device, tid, cq_id=0, blocking=True) for a, t in zip(raw, mk.taps): assert torch.equal(a, ttnn.to_torch(t)), "trace replay not bitwise identical" ttnn.release_trace(device, tid) @pytest.mark.parametrize("size,case", [("S", "clip4_240x320")]) def test_valid_frames(device, size, case): """T-frame program + set_valid_frames(n) == the exact n-frame program (taps of frames < n), n = T unchanged.""" from tt_depthpro2.tt.mk_enc import arena as A from tt_depthpro2.tt.mk_enc.program import MkEnc, MkEncWeights x = frames(case, size, "depth") T, _, hp, wp = x.shape wts = MkEncWeights(device, weights(size), size, "depth") def dev_patches(f): return ttnn.from_torch(A.patchify(f).to(torch.bfloat16), dtype=ttnn.bfloat16, layout=ttnn.TILE_LAYOUT, device=device, memory_config=ttnn.DRAM_MEMORY_CONFIG) def taps(mk): return [ttnn.to_torch(t).float().reshape(mk.geo.T, mk.geo.Np, -1)[:, :mk.geo.N] for t in mk.taps] mk = MkEnc(device, wts, size, T, hp // 16, wp // 16) full_in = dev_patches(x) mk.run(full_in) first = [ttnn.to_torch(t).clone() for t in mk.taps] for n in (2, 3): xn = x.clone() xn[n:] = 0 mk.set_valid_frames(n) mk.run(dev_patches(xn)) got = taps(mk) ex = MkEnc(device, wts, size, n, hp // 16, wp // 16) ex.run(dev_patches(x[:n])) for i, want in enumerate(taps(ex)): p = H.pcc(got[i][:n], want) print(f"valid frames {n}/{T} tap{i}: pcc vs exact T={n} {p:.7f}") assert p >= 0.9999 mk.set_valid_frames(T) mk.run(full_in) for a, t in zip(first, mk.taps): assert torch.equal(a, ttnn.to_torch(t)), "n = T after n < T runs not bitwise identical" def test_serve_configuration(device): """Regression of the serve-pkg device smoke (S, buckets 480x640 / 640x480 / 256x320, window 4, clip lengths 1 / 4, KV cache): every bucket x n = 1..3 clip on the T = 4 programs vs the fp32 reference, the golden clip4 between them and after ttnn KV steps (tests/mk_enc_serve_repro.py).""" from tt_depthpro2.tests.mk_enc_serve_repro import run_repro assert run_repro(device, "S", "mk", "ttnn") @pytest.mark.parametrize("case", ["img_vga", "clip4_240x320", "img_375x500_pad"]) def test_mk_fov(device, case): """tt/mk_fov (FOV-mode megakernel trunk + ttnn fp32 head): f_px within max(1 %, 2 x official bf16 drift).""" from tt_depthpro2.tests import baseline_helpers as BH from tt_depthpro2.tt import StageShape, mk_fov from tt_depthpro2.tt.mk_enc import arena as A g, _ = BH.load_golden(case, "S") x = g["x_norm"].float() T, _, h, w = x.shape y = R.fov_resize(x) eng = mk_fov.Engine(device, weights("fov"), StageShape(T, y.shape[-2], y.shape[-1])) fp = ttnn.from_torch(A.patchify(y).to(torch.bfloat16).reshape(1, 1, -1, 768), dtype=ttnn.bfloat16, layout=ttnn.TILE_LAYOUT, device=device, memory_config=ttnn.DRAM_MEMORY_CONFIG) lg = ttnn.to_torch(eng.run(fp)).float().reshape(T, 2) deg = R.fov_logits_to_deg(lg, (h, w), tuple(y.shape[-2:])) f_rel = abs(float(R.median_focal_length_px(deg, h, w)) / float(g["focallength_px"]) - 1) budget, _ = BH.fov_budget(case) print(f"mk_fov {case}: f_rel {f_rel:.4%} (budget {budget:.2%})") assert f_rel <= budget