Download code/tt_depthpro2/tests/mk_enc_heldout.py from changh95/DepthPro2: direct link, hf CLI and curl.
- Browser
- Download file 5.45 kB
-
https://huggingface.co/changh95/DepthPro2/resolve/main/code/tt_depthpro2/tests/mk_enc_heldout.py
- Command line
-
hf download hf://changh95/DepthPro2/code/tt_depthpro2/tests/mk_enc_heldout.py
-
curl -L -o mk_enc_heldout.py https://huggingface.co/changh95/DepthPro2/resolve/main/code/tt_depthpro2/tests/mk_enc_heldout.py
5.45 kB
| # SPDX-License-Identifier: Apache-2.0 | |
| """Held-out check of the device engines through DepthPro2Device (default enc=mk, dec=mk, fov=mk) against Apple's | |
| float32 outputs, with the SPEC section 5 metric and gates: PCC >= 0.999 (0.99 when the reference's valid cv < 0.15), | |
| AbsRel_valid <= max(2 x Apple's bf16 AbsRel, 0.01), f_px within max(1 %, 2 x Apple's bf16 f_px error). | |
| Inputs: ``$DEPTHPRO2_HELDOUT/<case>__<size>__fp32.safetensors`` (``input_u8``, ``inverse_depth``, ``focallength_px``; | |
| the verifier's golden_heldout.py) and, when present, ``..__bf16.safetensors`` (Apple's own bf16 run: the budget). | |
| Weights: ``DEPTHPRO2_TEST_WEIGHTS`` (parent of DepthPro2-<size>/ and DepthPro2-focal/). | |
| bin/devrun -t 1800 -- python -u bundles/depthpro2/code/tt_depthpro2/tests/mk_enc_heldout.py --sizes S,B,L,H | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| import os | |
| import sys | |
| import time | |
| import torch | |
| sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))) | |
| from tt_depthpro2.reference import model as ref # noqa: E402 | |
| from tt_depthpro2.tests import mk_enc_ref as H # noqa: E402 | |
| CASES = ("ho_images_vga", "ho_kropa_vga", "ho_example_portrait", "ho_clip4_vga") | |
| def metrics(inv: torch.Tensor, r: torch.Tensor) -> dict: | |
| a, b = inv.double().flatten(), r.double().flatten() | |
| p = torch.corrcoef(torch.stack([a, b]))[0, 1].item() | |
| m = b >= 0.01 * b.max() | |
| ad, bd = 1 / a[m].clamp_min(1e-9), 1 / b[m] | |
| v = b[m] | |
| return {"pcc": p, "absrel_valid": ((ad - bd).abs() / bd).mean().item(), "cv": (v.std() / v.mean()).item()} | |
| def main(): | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--sizes", default="S,B,L,H") | |
| ap.add_argument("--cases", default=",".join(CASES)) | |
| ap.add_argument("--engine", default="enc=mk,dec=mk,fov=mk") | |
| ap.add_argument("--tag", default="") | |
| args = ap.parse_args() | |
| root = os.environ.get("DEPTHPRO2_HELDOUT") | |
| if not root or not os.path.isdir(root): | |
| raise SystemExit("set DEPTHPRO2_HELDOUT to the directory of <case>__<size>__fp32.safetensors") | |
| import ttnn | |
| from safetensors.torch import load_file | |
| from tt_depthpro2.tt.model import DepthPro2Device | |
| dev = ttnn.open_device(device_id=0, dispatch_core_config=ttnn.DispatchCoreConfig(ttnn.DispatchCoreType.ETH), | |
| l1_small_size=32768, trace_region_size=256 << 20) | |
| fw = H.load_weights("fov") | |
| allok = True | |
| try: | |
| for size in args.sizes.split(","): | |
| items = [] | |
| for c in args.cases.split(","): | |
| p = os.path.join(root, f"{c}__{size}__fp32.safetensors") | |
| if not os.path.exists(p): | |
| continue | |
| g = load_file(p) | |
| pb = os.path.join(root, f"{c}__{size}__bf16.safetensors") | |
| items.append((c, g, load_file(pb) if os.path.exists(pb) else None)) | |
| if not items: | |
| continue | |
| buckets = sorted({tuple(g["input_u8"].shape[-3:-1]) for _, g, _ in items}) | |
| frames = sorted({int(g["input_u8"].shape[0]) if g["input_u8"].ndim == 4 else 1 for _, g, _ in items}) | |
| m = DepthPro2Device(dev, size, H.load_weights(size), fw, buckets=buckets, max_frames=max(frames), | |
| frames=tuple(frames), engine=args.engine) | |
| for c, g, gb in items: | |
| u8 = g["input_u8"].numpy() | |
| x = ref.preprocess(u8) | |
| T, _, h, w = x.shape | |
| inv = m.inverse_depth(ref.pad_to_multiple(x))[:, :h, :w] | |
| inv2 = m.inverse_depth(ref.pad_to_multiple(x))[:, :h, :w] | |
| r = g["inverse_depth"].reshape(T, h, w) | |
| met = metrics(inv, r) | |
| y = ref.fov_resize(x) | |
| deg = ref.fov_logits_to_deg(m.fov_logits(y), (h, w), tuple(y.shape[-2:])) | |
| f = float(ref.median_focal_length_px(deg, h, w)) | |
| f_rel = abs(f / float(g["focallength_px"].reshape(-1)[0]) - 1) | |
| bf_abs, bf_f = None, None | |
| if gb is not None: | |
| bf_abs = metrics(gb["inverse_depth"].reshape(T, h, w), r)["absrel_valid"] | |
| bf_f = abs(float(gb["focallength_px"].reshape(-1)[0]) / float(g["focallength_px"].reshape(-1)[0]) - 1) | |
| pcc_gate = 0.99 if met["cv"] < 0.15 else 0.999 | |
| budget = max(2 * bf_abs, 0.01) if bf_abs is not None else 0.01 | |
| f_budget = max(0.01, 2 * bf_f) if bf_f is not None else 0.01 | |
| ok = (met["pcc"] >= pcc_gate and met["absrel_valid"] <= budget and f_rel <= f_budget | |
| and bool(torch.equal(inv, inv2)) and bool(torch.isfinite(inv).all())) | |
| allok = allok and ok | |
| rec = {"tag": args.tag, "size": size, "case": c, "engine": args.engine, "pcc": met["pcc"], | |
| "pcc_gate": pcc_gate, "cv": met["cv"], "absrel": met["absrel_valid"], "budget": budget, | |
| "apple_bf16_absrel": bf_abs, "f_rel": f_rel, "f_budget": f_budget, | |
| "repeat_bitexact": bool(torch.equal(inv, inv2)), "passed": ok, | |
| "time": time.strftime("%Y-%m-%d %H:%M:%S")} | |
| print(json.dumps(rec), flush=True) | |
| H.append_log("heldout.jsonl", rec) | |
| m.close() | |
| finally: | |
| ttnn.close_device(dev) | |
| print("ALL PASS" if allok else "SOME FAILED", flush=True) | |
| if __name__ == "__main__": | |
| main() | |