File size: 3,099 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
# SPDX-License-Identifier: Apache-2.0
"""CPU only: float32 reference outputs for golden cases that have no official golden for a size (``img_375x500_pad``
exists for S / B only). Uses the clean-room reference (matches the official code to 6e-6, SPEC §1) on the S golden's
input. Writes ``assets/depthpro2/baseline_ref/<case>__<size>.safetensors`` (+ .json) with the golden key names
(x_norm, inverse_depth, fov_deg, focallength_px) so ``test_device_baseline.py`` treats them like goldens.

    python bundles/depthpro2/code/tt_depthpro2/tests/make_baseline_refs.py --case img_375x500_pad --sizes L,H
"""

from __future__ import annotations

import argparse
import json
import os
import sys
import time

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))

import torch  # noqa: E402
from safetensors.torch import save_file  # noqa: E402

import baseline_helpers as H  # noqa: E402
from tt_depthpro2.reference import model as ref  # noqa: E402

OUT = os.path.join(H.ROOT, "assets/depthpro2/baseline_ref")


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--case", default="img_375x500_pad")
    ap.add_argument("--sizes", default="L,H")
    a = ap.parse_args()
    os.makedirs(OUT, exist_ok=True)
    g, _ = H.load_golden(a.case, "S")
    x = g["x_norm"]
    fw = ref.load_safetensors(os.path.join(H.fov_dir(), "model.safetensors"))
    torch.set_grad_enabled(False)
    for size in a.sizes.split(","):
        t0 = time.time()
        m = ref.DepthPro2Reference(size, ref.load_safetensors(os.path.join(H.size_dir(size), "model.safetensors")), fw)
        out = m.infer(g["input_u8"].round().to(torch.uint8).numpy())
        fov = m.fov_deg(x)
        t = x.shape[0]
        # the FOV estimator is shared by all sizes (DepthPro2-focal): keep the OFFICIAL S golden's fov / focal length
        rec = {"x_norm": x.contiguous(), "inverse_depth": out["inverse_depth"].reshape(t, *x.shape[-2:]).contiguous().squeeze(0)
               if t == 1 else out["inverse_depth"].contiguous(), "fov_deg": g["fov_deg"].contiguous(),
               "focallength_px": g["focallength_px"].reshape(1).contiguous()}
        print(size, "reference fov_deg", fov.tolist(), "vs official", g["fov_deg"].tolist())
        base = os.path.join(OUT, f"{a.case}__{size}")
        save_file(rec, base + ".safetensors")
        meta = {"case": a.case, "size": size, "source": "clean-room reference (float32 CPU) on the S golden input",
                "focallength_px": float(g["focallength_px"]), "fov_source": "official S golden (shared FOV estimator)",
                "seconds": round(time.time() - t0, 1),
                "keys": {k: list(v.shape) for k, v in rec.items()}}
        with open(base + ".json", "w") as f:
            json.dump(meta, f, indent=1)
        print(size, meta, flush=True)
        # sanity: the input reproduces the S golden's x_norm
        assert torch.allclose(ref.preprocess(g["input_u8"].numpy().astype("uint8")), x, atol=1e-6)


if __name__ == "__main__":
    main()