# SPDX-License-Identifier: Apache-2.0 """Device tests of the DEC megakernel (``tt/mk_dec``): the stage on the golden taps vs the float32 golden ``head.out`` (SPEC section 5 stage gate: PCC >= 0.99999, max rel <= 1 %), the Engine contract (persistent-free output, trace capture) and trace-replay determinism. Run through the device lock, naming this file explicitly: bin/devrun -t 3600 -- python -m pytest -x -q -s bundles/depthpro2/code/tt_depthpro2/tests/test_device_mk_dec.py \ -o faulthandler_timeout=3000 [-k S] Records are appended to ``logs/depthpro2/mk_dec/results.jsonl``. """ from __future__ import annotations import json import os import time import pytest import torch from tt_depthpro2.reference import model as R from tt_depthpro2.tests import baseline_helpers as BH from tt_depthpro2.tt import StageShape ttnn = pytest.importorskip("ttnn") RESULTS = os.path.join(BH.ROOT, "logs/depthpro2/mk_dec/results.jsonl") STAGE_PCC = float(os.environ.get("MK_DEC_STAGE_PCC", "0.99999")) STAGE_REL = float(os.environ.get("MK_DEC_STAGE_REL", "0.01")) DET_REPLAYS = int(os.environ.get("MK_DEC_DET_REPLAYS", "500")) CASES = [ ("S", "img_384x512"), ("S", "img_vga"), ("S", "clip4_240x320"), ("S", "img_375x500_pad"), ("B", "img_vga"), ("B", "clip4_240x320"), ("B", "img_375x500_pad"), ("L", "img_vga"), ("L", "clip4_240x320"), ("H", "img_vga"), ("H", "clip4_240x320"), ] 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)) @pytest.fixture(scope="module") def device(): dev = ttnn.open_device(device_id=0, dispatch_core_config=ttnn.DispatchCoreConfig(ttnn.DispatchCoreType.ETH), l1_small_size=32768, trace_region_size=32 << 20) yield dev ttnn.close_device(dev) _W = {} def prepared(device, size: str): from tt_depthpro2.tt import mk_dec if size not in _W: _W.clear() w = R.load_safetensors(os.path.join(BH.size_dir(size), "model.safetensors")) _W[size] = mk_dec.Engine.prepare_weights(device, w, size) return _W[size] def golden_taps(device, g, shape: StageShape): out = [] for i in range(4): t = g[f"tap{i}"].float() z = torch.zeros(shape.frames, shape.np_, t.shape[-1]) z[:, :t.shape[1]] = t out.append(ttnn.from_torch(z.reshape(1, 1, -1, t.shape[-1]).to(torch.bfloat16), dtype=ttnn.bfloat16, layout=ttnn.TILE_LAYOUT, device=device, memory_config=ttnn.DRAM_MEMORY_CONFIG)) return out @pytest.mark.parametrize("size,case", CASES, ids=[f"{s}-{c}" for s, c in CASES]) def test_stage(device, size, case): from tt_depthpro2.tt import mk_dec g, _ = BH.load_golden(case, size) x = R.pad_to_multiple(g["x_norm"]) t, _, hp, wp = x.shape shape = StageShape(t, hp, wp) eng = mk_dec.Engine(device, prepared(device, size), shape) taps = golden_taps(device, g, shape) out = ttnn.to_torch(eng.run(taps)).float().reshape(t, hp, wp) ref = g["head.out"][:, 0] r = {"pcc": BH.pcc(out, ref), "max_rel": BH.max_rel(out, ref), "aborts": len(eng.mk.aborts())} # cropped inverse depth (what the user sees) with the SPEC metrics h, w = g["inverse_depth"].shape[-2:] r["crop"] = BH.drift_metrics(out[:, :h, :w], g["inverse_depth"].reshape(t, h, w)) record("stage_dec_mk", size=size, case=case, **r) assert r["aborts"] == 0 assert r["pcc"] >= STAGE_PCC and r["max_rel"] <= STAGE_REL, r def test_trace_determinism(device): """``DET_REPLAYS`` trace replays of the stage are bitwise identical (and equal to the eager run).""" from tt_depthpro2.tt import mk_dec g, _ = BH.load_golden("img_vga", "S") x = R.pad_to_multiple(g["x_norm"]) t, _, hp, wp = x.shape shape = StageShape(t, hp, wp) eng = mk_dec.Engine(device, prepared(device, "S"), shape) taps = golden_taps(device, g, shape) first = ttnn.to_torch(eng.run(taps)).float() tid = ttnn.begin_trace_capture(device, cq_id=0) out = eng.run(taps) ttnn.end_trace_capture(device, tid, cq_id=0) bad = 0 try: for _ in range(DET_REPLAYS): ttnn.execute_trace(device, tid, cq_id=0, blocking=False) bad += int(not torch.equal(ttnn.to_torch(out).float(), first)) finally: ttnn.release_trace(device, tid) record("determinism_mk_dec", size="S", case="img_vga", replays=DET_REPLAYS, mismatches=bad) assert bad == 0