File size: 4,214 Bytes
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
# SPDX-License-Identifier: Apache-2.0
"""Helpers of the host tests (no device): where the weights and Apple's float32 goldens are, a cache of CPU-engine
models, comparisons. Tests that need weights or goldens skip when they are absent.

``DEPTHPRO2_TEST_WEIGHTS`` (a parent of ``DepthPro2-<size>/`` and ``DepthPro2-focal/``; else ``DEPTHPRO2_WEIGHTS_DIR``,
else ``code/weights`` next to the package) and ``DEPTHPRO2_GOLDEN`` (Apple's float32 goldens, ``<case>__<size>.safetensors``;
default ``code/golden`` next to the package) say where they are.
"""
from __future__ import annotations

import os
from pathlib import Path
from typing import Any, Dict, Tuple

import pytest

_CODE = Path(__file__).resolve().parents[2]  # code/ (the package's parent)
WEIGHTS_ROOT = Path(os.environ.get("DEPTHPRO2_TEST_WEIGHTS") or os.environ.get("DEPTHPRO2_WEIGHTS_DIR")
                    or str(_CODE / "weights"))
GOLDEN = Path(os.environ.get("DEPTHPRO2_GOLDEN") or str(_CODE / "golden"))

_MODELS: Dict[Tuple, Any] = {}


def have_weights(size: str = "S", fov: bool = True) -> bool:
    ok = (WEIGHTS_ROOT / f"DepthPro2-{size}" / "model.safetensors").is_file()
    return ok and (not fov or (WEIGHTS_ROOT / "DepthPro2-focal" / "model.safetensors").is_file())


def need_weights(size: str = "S", fov: bool = True) -> None:
    if not have_weights(size, fov):
        pytest.skip(f"DepthPro2-{size} weights not under {WEIGHTS_ROOT}")


def need_golden(name: str) -> Path:
    p = GOLDEN / f"{name}.safetensors"
    if not p.is_file():
        pytest.skip(f"golden {name} not under {GOLDEN}")
    return p


def golden(name: str) -> Dict[str, Any]:
    from safetensors.torch import load_file

    return load_file(str(need_golden(name)))


def cpu_model(size: str = "S", **kw: Any):
    """A CPU-engine model (cached per configuration; never closed by the tests that share it)."""
    need_weights(size, kw.get("fov", True) is not False)
    from tt_depthpro2.api import DepthPro2

    key = (size, tuple(sorted((k, str(v)) for k, v in kw.items())))
    if key not in _MODELS:
        kw.setdefault("warmup", False)
        _MODELS[key] = DepthPro2.from_pretrained(size, backend="cpu", weights_dir=str(WEIGHTS_ROOT),
                                                 fov_weights_dir=str(WEIGHTS_ROOT), **kw)
    return _MODELS[key]


def new_cpu_model(size: str = "S", **kw: Any):
    """A fresh CPU-engine model (the caller closes it)."""
    need_weights(size, kw.get("fov", True) is not False)
    from tt_depthpro2.api import DepthPro2

    kw.setdefault("warmup", False)
    return DepthPro2.from_pretrained(size, backend="cpu", weights_dir=str(WEIGHTS_ROOT),
                                     fov_weights_dir=str(WEIGHTS_ROOT), **kw)


def rel_err(a, b) -> float:
    """max |a - b| / max |b| over the elements finite in both."""
    import torch

    a, b = torch.as_tensor(a).double().flatten(), torch.as_tensor(b).double().flatten()
    f = torch.isfinite(a) & torch.isfinite(b)
    return float((a[f] - b[f]).abs().max() / b[f].abs().max().clamp_min(1e-30))


def depth_rel_err_valid(depth, ref_depth, ref_inverse_depth) -> float:
    """max |depth - ref| / ref over the valid pixels: reference inverse depth >= 1 % of its maximum (depth within 100
    times the nearest, the AbsRel mask of the accuracy gates). Outside it (towards the sky) the inverse depth tends to
    0 and depth = f / (w * inverse depth) magnifies the float32 summation-order noise of the CPU engine, which changes
    with the torch thread count, without bound. Inside it an inverse-depth error of e relative to the maximum gives at
    most a 100 e relative depth error, plus the focal length's relative error."""
    import torch

    d, r = torch.as_tensor(depth).double().flatten(), torch.as_tensor(ref_depth).double().flatten()
    inv = torch.as_tensor(ref_inverse_depth).double().flatten()
    valid = inv >= 0.01 * inv.max()
    return float(((d[valid] - r[valid]).abs() / r[valid]).max())


def pcc(a, b) -> float:
    import torch

    a, b = torch.as_tensor(a).double().flatten(), torch.as_tensor(b).double().flatten()
    f = torch.isfinite(a) & torch.isfinite(b)
    return float(torch.corrcoef(torch.stack([a[f], b[f]]))[0, 1])