# SPDX-License-Identifier: Apache-2.0 """Helpers for the ttnn-baseline device tests and benchmarks (paths, goldens, metrics, device open). Paths (no machine-specific defaults): * ``ROOT``: ``$TT_MODELS_ROOT``, else the nearest ancestor directory of this package that holds ``assets/depthpro2/`` (the workspace the bundle sits in), else ``code/`` (the package's parent). Goldens, reference outputs and logs of the device scripts live under it. * weights: ``$DEPTHPRO2_WEIGHTS`` (else ``$DEPTHPRO2_TEST_WEIGHTS`` / ``$DEPTHPRO2_WEIGHTS_DIR``), a parent of ``DepthPro2-/``; without one, each repo's Hugging Face cache snapshot at the package's pinned commit (``config.WEIGHTS``; cache only, nothing is downloaded). * ``GOLDEN``: ``$DEPTHPRO2_GOLDEN``, else ``ROOT/assets/depthpro2/golden``. """ from __future__ import annotations import json import math import os import sys from pathlib import Path from typing import Dict, Optional, Tuple import torch _CODE = Path(__file__).resolve().parents[2] # code/ (the package's parent) def _find_root() -> str: env = os.environ.get("TT_MODELS_ROOT") if env: return env for p in _CODE.parents: if (p / "assets" / "depthpro2").is_dir(): return str(p) return str(_CODE) ROOT = _find_root() #: a parent of DepthPro2-/ and DepthPro2-focal/, or None: the Hugging Face cache at the pinned commits WEIGHTS: Optional[str] = (os.environ.get("DEPTHPRO2_WEIGHTS") or os.environ.get("DEPTHPRO2_TEST_WEIGHTS") or os.environ.get("DEPTHPRO2_WEIGHTS_DIR") or None) GOLDEN = os.environ.get("DEPTHPRO2_GOLDEN", os.path.join(ROOT, "assets/depthpro2/golden")) SIZE_DIRS = {"S": "DepthPro2-S", "B": "DepthPro2-B", "L": "DepthPro2-L", "H": "DepthPro2-H"} FOV_DIR = "DepthPro2-focal" def _weights_dir(key: str) -> str: """The directory holding ``model.safetensors`` of a size (``"S"``..``"H"``) or of the focal estimator.""" if WEIGHTS: return os.path.join(WEIGHTS, FOV_DIR if key == "focal" else SIZE_DIRS[key]) try: from tt_depthpro2 import config as C except ImportError: # imported as a top-level module (tests/ on sys.path) sys.path.insert(0, str(_CODE)) from tt_depthpro2 import config as C from huggingface_hub import snapshot_download repo, pin = C.weights_pin(key) try: return snapshot_download(repo, revision=pin, local_files_only=True, allow_patterns=list(C.ALLOW_PATTERNS)) except Exception as e: # noqa: BLE001 -- not in the cache raise FileNotFoundError(f"{repo}@{pin} is not in the Hugging Face cache; set DEPTHPRO2_WEIGHTS to a parent " f"of {FOV_DIR if key == 'focal' else SIZE_DIRS[key]}/ ({e})") from None # device-open parameters the ttnn baseline needs (conv2d halo / config buffers; traces of every compiled shape) L1_SMALL_SIZE = 32768 TRACE_REGION_SIZE = int(os.environ.get("DEPTHPRO2_TRACE_REGION", str(256 << 20))) def size_dir(size: str) -> str: return _weights_dir(size) def fov_dir() -> str: return _weights_dir("focal") BASELINE_REF = os.path.join(ROOT, "assets/depthpro2/baseline_ref") # tests/make_baseline_refs.py (reference outputs) def golden_path(case: str, size: str) -> Optional[str]: """Official golden if present, else the clean-room reference output of ``make_baseline_refs.py``.""" for d in (GOLDEN, BASELINE_REF): base = os.path.join(d, f"{case}__{size}") if os.path.exists(base + ".json") and os.path.exists(base + ".safetensors"): return base return None def load_golden(case: str, size: str) -> Tuple[Dict[str, torch.Tensor], dict]: from safetensors.torch import load_file base = golden_path(case, size) if base is None: raise FileNotFoundError(f"no golden for {case}__{size}") with open(base + ".json") as f: meta = json.load(f) return {k: v.float() for k, v in load_file(base + ".safetensors").items()}, meta def bf16_drift() -> Optional[dict]: p = os.path.join(GOLDEN, "bf16_drift.json") if not os.path.exists(p): return None with open(p) as f: return json.load(f) def pcc(a: torch.Tensor, b: torch.Tensor) -> float: a = a.flatten().double() b = b.flatten().double() a = a - a.mean() b = b - b.mean() d = a.norm() * b.norm() return float((a * b).sum() / d) if d > 0 else (1.0 if torch.equal(a, b) else 0.0) def max_rel(a: torch.Tensor, b: torch.Tensor) -> float: """max |a - b| / max |b|.""" return float((a.double() - b.double()).abs().max() / (b.double().abs().max() + 1e-30)) def depth_absrel(inv: torch.Tensor, inv_ref: torch.Tensor, f_px: float, width: int) -> float: """AbsRel of depth = f / (W * inv) against the reference depth, over pixels where both are finite and > 0.""" d = f_px / (width * inv.double()) r = f_px / (width * inv_ref.double()) m = torch.isfinite(d) & torch.isfinite(r) & (r > 0) & (d > 0) return float(((d[m] - r[m]).abs() / r[m]).mean()) def drift_metrics(inv: torch.Tensor, ref: torch.Tensor) -> dict: """Same metrics as research/depthpro2/golden/bf16_drift.py (the gate's accuracy budget is in these units).""" a, b = inv.double().flatten(), ref.double().flatten() p = torch.corrcoef(torch.stack([a, b]))[0, 1].item() m = b >= 0.01 * b.max() # valid: within 100x of the nearest point (excludes sky) ad, bd = 1 / a[m].clamp_min(1e-9), 1 / b[m] absrel = ((ad - bd).abs() / bd).mean().item() d1 = (torch.maximum(ad / bd, bd / ad) < 1.25).double().mean().item() rel = (a[m] - b[m]).abs() / b[m] return {"pcc": p, "absrel_valid": absrel, "delta1_valid": d1, "inv_rel_p99_valid": rel.quantile(0.99).item(), "valid_frac": m.double().mean().item(), "max_rel_inv": ((a - b).abs().max() / b.abs().max()).item()} EMULATED_DRIFT = os.path.join(ROOT, "logs/depthpro2/baseline/bf16_drift_emulated.json") # tests/emulate_bf16_drift.py def official_drift_absrel(case: str, size: str) -> Tuple[Optional[float], str]: """The official bf16 drift AbsRel (valid pixels): bf16_drift.json ``absrel_valid``, else computed from the official bf16 outputs (``golden/bf16/__.safetensors``), else the CPU emulation (tests/emulate_bf16_drift.py, which reproduces the official numbers where both exist), else None.""" e = (bf16_drift() or {}).get(f"{case}__{size}") or {} if "absrel_valid" in e: return float(e["absrel_valid"]), "official bf16_drift.json" p = os.path.join(GOLDEN, "bf16", f"{case}__{size}.safetensors") if os.path.exists(p): from safetensors.torch import load_file b = load_file(p)["inverse_depth"].float() g, _ = load_golden(case, size) return drift_metrics(b, g["inverse_depth"].reshape(b.shape))["absrel_valid"], "official bf16 output" if os.path.exists(EMULATED_DRIFT): with open(EMULATED_DRIFT) as f: e = json.load(f).get(f"{case}__{size}") if e: return float(e["absrel_valid"]), "CPU bf16-autocast emulation" return None, "none" def fov_budget(case: str) -> Tuple[float, str]: """Gate (SPEC §5): f_px within 1 % of the golden's, or within 2 x the official bf16 drift (CPU emulation of the official bf16 FOV estimator: its fov_deg_maxabs reproduces bf16_drift.json; f_rel stored per case).""" if os.path.exists(EMULATED_DRIFT): with open(EMULATED_DRIFT) as f: e = json.load(f).get(f"fov__{case}") if e: return max(0.01, 2 * e["f_rel"]), f"max(1 %, 2 x {e['f_rel'] * 100:.3f} % bf16 emulation)" return 0.01, "1 %" def absrel_budget(case: str, size: str) -> Tuple[float, str]: """Gate (SPEC §5): depth AbsRel <= max(2 x official bf16 drift AbsRel, 0.01).""" d, src = official_drift_absrel(case, size) if d is None: return 0.01, "floor (no drift entry)" return max(2 * d, 0.01), f"2 x {d:.5f} ({src})" def open_device(dispatch: str = "eth", trace_region_size: int = TRACE_REGION_SIZE, l1_small_size: int = L1_SMALL_SIZE): import ttnn kw = dict(device_id=0, l1_small_size=l1_small_size, trace_region_size=trace_region_size) if dispatch == "eth": kw["dispatch_core_config"] = ttnn.DispatchCoreConfig(ttnn.DispatchCoreType.ETH) dev = ttnn.open_device(**kw) return dev def close_device(dev) -> None: import ttnn ttnn.close_device(dev) def fmt(x: float) -> str: if x == 0 or not math.isfinite(x): return str(x) return f"{x:.6f}" if abs(x) >= 1e-3 else f"{x:.2e}"