"""Load or build one flat per-scene cache file for the selected model.""" from __future__ import annotations import argparse import gzip import hashlib import os from pathlib import Path import pickle import sys # Single-scene CLI runs (unlike launch.py's budgeted batch workers) otherwise inherit # whatever thread defaults numpy/BLAS/scipy pick -- typically "use every core" -- which # thrashes when geometric.py makes many small parallel-dispatched calls (cv2 ops per # mask, KD-tree queries per class pair). setdefault() so launch.py's explicit # per-worker budget (set before it imports this module via render.py) always wins. for _var in ("OMP_NUM_THREADS", "MKL_NUM_THREADS", "OPENBLAS_NUM_THREADS"): os.environ.setdefault(_var, "1") os.environ.setdefault("VSI_KD_WORKERS", "1") WORKSPACE_ROOT = Path(__file__).resolve().parent.parent if str(WORKSPACE_ROOT) not in sys.path: sys.path.insert(0, str(WORKSPACE_ROOT)) from encoder import adapters # noqa: E402 from encoder import config # noqa: E402 PROVENANCE_KEY = "source_provenance" PROVENANCE_VERSION = 1 def _source_record(path): """Describe one native cache without copying its payload.""" source = Path(path) size = source.stat().st_size digest = hashlib.sha256() with source.open("rb") as stream: for chunk in iter(lambda: stream.read(1024 * 1024), b""): digest.update(chunk) return {"path": str(source), "size": size, "sha256": digest.hexdigest()} def _source_provenance(scene, mode, paths): """Record the exact native caches used to derive a combined cache.""" return { "format_version": PROVENANCE_VERSION, "scene": scene, "mode": mode, "sources": {name: _source_record(path) for name, path in paths.items()}, } def _verify_source_provenance(provenance): """Ensure every referenced native cache still matches byte-for-byte.""" if ( not isinstance(provenance, dict) or provenance.get("format_version") != PROVENANCE_VERSION ): raise ValueError("combined cache has unsupported source provenance") sources = provenance.get("sources") if not isinstance(sources, dict) or set(sources) != {"sam3", "depth-anything-3"}: raise ValueError("combined cache source provenance is incomplete") for name, expected in sources.items(): if not isinstance(expected, dict) or "path" not in expected: raise ValueError(f"combined cache source {name!r} has invalid provenance") try: actual = _source_record(expected["path"]) except FileNotFoundError as exc: raise FileNotFoundError( f"combined cache source {name!r} is missing: {expected['path']}" ) from exc if ( actual["size"] != expected.get("size") or actual["sha256"] != expected.get("sha256") ): raise ValueError( f"combined cache source {name!r} no longer matches its provenance" ) def cache_or_load( scene, depth, input_selection, tracking, frame_count=config.FRAMES_PER_VIDEO, rebuild=False, ): """Return canonical geometry for one specific set of input dimensions.""" path = config.cache_file( scene, depth, input_selection, tracking, frame_count ) if os.path.exists(path) and not rebuild: with gzip.open(path, "rb") as stream: cached = pickle.load(stream) provenance = cached.get(PROVENANCE_KEY) if isinstance(cached, dict) else None if provenance is not None: _verify_source_provenance(provenance) return adapters.validate(cached), "loaded" # Legacy combined caches are rebuilt to attach exact source provenance. raw_cache = { "scene": scene, "root": str(config.CACHE_ROOT), "rebuild": rebuild, "da3_path": config.da3_cache_file( scene, depth, input_selection, frame_count ), "sam3_path": config.sam3_cache_file( scene, input_selection, tracking, frame_count ), } geometry = adapters.adapt(config.MODEL, **raw_cache) mode = f"{input_selection}:{frame_count}:{tracking}" geometry[PROVENANCE_KEY] = _source_provenance( scene, mode, { "sam3": raw_cache["sam3_path"], "depth-anything-3": raw_cache["da3_path"], }, ) geometry[PROVENANCE_KEY].update( { "depth": depth, "input": input_selection, "tracking": tracking, "frames": frame_count, } ) _verify_source_provenance(geometry[PROVENANCE_KEY]) os.makedirs(os.path.dirname(path), exist_ok=True) with gzip.open(path, "wb") as stream: pickle.dump(geometry, stream, protocol=pickle.HIGHEST_PROTOCOL) return geometry, "built" def main(): parser = argparse.ArgumentParser() parser.add_argument("scene") parser.add_argument("--depth", required=True, choices=config.DEPTH_VARIANTS) parser.add_argument( "--input", required=True, choices=config.INPUT_SELECTIONS, dest="input_selection", ) parser.add_argument("--frames", type=int, default=config.FRAMES_PER_VIDEO) parser.add_argument("--tracking", required=True, choices=config.TRACKING_MODES) parser.add_argument( "--format", choices=config.SPATIAL_CODE_FORMATS, default="explicit", dest="spatial_code_format", ) parser.add_argument("--rebuild", action="store_true") args = parser.parse_args() if args.frames < 1: parser.error("--frames must be positive") from encoder import render import cv2 cv2.setNumThreads(1) # see thread-budget note near the top imports import torch # torch ignores the OMP/MKL/OPENBLAS env vars set above torch.set_num_threads(1) try: torch.set_num_interop_threads(1) except RuntimeError: pass geometry, how = cache_or_load( args.scene, args.depth, args.input_selection, args.tracking, args.frames, args.rebuild, ) count = sum(len(values) for values in geometry["instances"].values()) print( f"[{args.scene}] depth={args.depth} input={args.input_selection} " f"frames={args.frames} tracking={args.tracking} cache={how} " f"classes={len(geometry['instances'])} instances={count}" ) _, _, path = render.write_spatial_code_for( args.scene, args.depth, args.input_selection, args.tracking, args.frames, False, args.spatial_code_format, ) print(f"[{args.scene}] spatial_code={path}") if __name__ == "__main__": main()