Download code/scripts/make_sample_reference.py from changh95/DepthPro2: direct link, hf CLI and curl.
- Browser
- Download file 3.58 kB
-
https://huggingface.co/changh95/DepthPro2/resolve/main/code/scripts/make_sample_reference.py
- Command line
-
hf download hf://changh95/DepthPro2/code/scripts/make_sample_reference.py
-
curl -L -o make_sample_reference.py https://huggingface.co/changh95/DepthPro2/resolve/main/code/scripts/make_sample_reference.py
3.58 kB
| #!/usr/bin/env python3 | |
| # SPDX-License-Identifier: Apache-2.0 | |
| """Regenerate the stored CPU-reference outputs of the shipped sample (``samples/kropa_street/``), one per model size: | |
| reference.<S|B|L|H>.json focal length, FoV, focal source, depth statistics, weights commits, how it was made | |
| reference.<S|B|L|H>.npy the focal-normalized inverse depth, 4 x 4 average-pooled to 120 x 160, float16 | |
| They are the outputs of this package's host pipeline on the float32 CPU reference (``DepthPro2.from_pretrained(size, | |
| backend="cpu")``: the same decoding, bucket, normalization, padding, FOV and post-processing as the served model, | |
| with ``reference/model.py`` in place of the device), which ``server/smoke_test.py`` compares a served container | |
| with. No device, no Apple code. | |
| python code/scripts/make_sample_reference.py --sizes S,B,L,H [--weights-dir /path/to/apple-snapshots] | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import datetime as _dt | |
| import json | |
| import os | |
| import sys | |
| import time | |
| from pathlib import Path | |
| CODE = Path(__file__).resolve().parents[1] | |
| sys.path.insert(0, str(CODE)) | |
| POOL = 4 | |
| def main() -> int: | |
| ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) | |
| ap.add_argument("--sizes", default="S,B,L,H") | |
| ap.add_argument("--weights-dir", help="local snapshots (a parent of DepthPro2-<size>/ and DepthPro2-focal/); " | |
| "default: the Hugging Face cache / Hub at the pinned commits") | |
| ap.add_argument("--threads", type=int, default=os.cpu_count() or 4) | |
| a = ap.parse_args() | |
| sys.modules.setdefault("ttnn", None) # never the device | |
| import numpy as np | |
| import torch | |
| from torch.nn import functional as F | |
| from tt_depthpro2 import __version__ | |
| from tt_depthpro2.api import DepthPro2, load_sample | |
| torch.set_num_threads(a.threads) | |
| path = load_sample() | |
| out_dir = path.parent | |
| for size in [s.strip() for s in a.sizes.split(",") if s.strip()]: | |
| t0 = time.time() | |
| with DepthPro2.from_pretrained(size, backend="cpu", resolutions="vga,vga_portrait", window=1, overlap=0, | |
| weights_dir=a.weights_dir, fov_weights_dir=a.weights_dir) as m: | |
| out = m.infer(path) | |
| inv = out.inverse_depth | |
| pooled = F.avg_pool2d(inv[None, None], POOL)[0, 0].numpy().astype(np.float16) | |
| np.save(out_dir / f"reference.{m.size}.npy", pooled, allow_pickle=False) | |
| meta = out.meta() | |
| meta.pop("timing_ms", None) | |
| meta.update({ | |
| "stats_m": out.stats(), | |
| "inverse_depth_npy": f"reference.{m.size}.npy", | |
| "inverse_depth_pool": POOL, | |
| "inverse_depth_pooled_shape": list(pooled.shape), | |
| "weights": {k: ({kk: vv for kk, vv in v.items() if kk in ("repo", "revision")} if isinstance(v, dict) | |
| else v) for k, v in m.weights.items()}, | |
| "made_with": f"tt_depthpro2 {__version__}, backend cpu (float32 reference/model.py), torch " | |
| f"{torch.__version__}, {_dt.datetime.now(_dt.timezone.utc).strftime('%Y-%m-%d')}", | |
| "seconds": round(time.time() - t0, 1), | |
| }) | |
| (out_dir / f"reference.{m.size}.json").write_text(json.dumps(meta, indent=1) + "\n") | |
| print(f"{m.size}: f_px {out.focallength_px:.2f} ({out.focal_source}), median depth " | |
| f"{meta['stats_m']['median']:.3f} m, {meta['seconds']} s", flush=True) | |
| return 0 | |
| if __name__ == "__main__": | |
| sys.exit(main()) | |