File size: 8,585 Bytes
b7e49b8
d5afa0d
 
 
 
 
 
 
 
 
 
 
 
b7e49b8
 
 
 
 
 
d5afa0d
 
b7e49b8
 
 
 
d5afa0d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b7e49b8
 
 
 
d5afa0d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b7e49b8
 
 
 
 
 
d5afa0d
b7e49b8
 
 
d5afa0d
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
# 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-<S|B|L|H|focal>/``; 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-<size>/ 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/<case>__<size>.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}"