"""CPU-saturating batch launcher for geometric hypothesis experiments.""" from __future__ import annotations import argparse import json import multiprocessing as mp import os from pathlib import Path import sys import traceback 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 config as encoder_config # noqa: E402 from experiments import config # noqa: E402 def available_cpu_count() -> int: """Use every CPU available through affinity unless explicitly overridden.""" override = os.environ.get("VSI_CPU_WORKERS") if override is not None: count = int(override) if count < 1: raise ValueError("VSI_CPU_WORKERS must be positive") return count try: return max(1, len(os.sched_getaffinity(0))) except AttributeError: return max(1, os.cpu_count() or 1) def configure_numerical_threads(count: int) -> None: """Give a worker its fair CPU share without nested-thread oversubscription.""" value = str(max(1, count)) for variable in ( "OMP_NUM_THREADS", "MKL_NUM_THREADS", "OPENBLAS_NUM_THREADS", "NUMEXPR_NUM_THREADS", ): os.environ[variable] = value os.environ["VSI_KD_WORKERS"] = value def scenes_with_existing_cache(depth, input_selection, tracking, frame_count): """Return scenes with both native caches, or an existing combined cache.""" with encoder_config.JSONL.open(encoding="utf-8") as stream: scenes = list( dict.fromkeys(str(json.loads(line)["scene_name"]) for line in stream) ) available = [] for scene in scenes: combined = Path( encoder_config.cache_file( scene, depth, input_selection, tracking, frame_count ) ) da3 = Path( encoder_config.da3_cache_file(scene, depth, input_selection, frame_count) ) sam3 = Path( encoder_config.sam3_cache_file( scene, input_selection, tracking, frame_count ) ) if combined.is_file() or (da3.is_file() and sam3.is_file()): available.append(scene) return available def _worker(tasks, results, settings, threads_per_worker): configure_numerical_threads(threads_per_worker) import cv2 cv2.setNumThreads(threads_per_worker) from experiments.run import run_scene while True: scene = tasks.get() if scene is None: return try: _, status, path = run_scene(scene=scene, **settings) results.put((scene, status, str(path))) except Exception: results.put((scene, "failed", traceback.format_exc())) def launch(settings, scenes, workers=0): """Run scenes in parallel; zero workers means all available CPUs.""" selected = list(scenes) if not selected: return {"built": 0, "loaded": 0, "failed": 0} cpu_count = available_cpu_count() worker_count = min(workers or cpu_count, len(selected)) if worker_count < 1: raise ValueError("workers must be non-negative") threads_per_worker = max(1, cpu_count // worker_count) context = mp.get_context("spawn") tasks, results = context.Queue(), context.Queue() for scene in selected: tasks.put(scene) for _ in range(worker_count): tasks.put(None) processes = [ context.Process( target=_worker, args=(tasks, results, settings, threads_per_worker), ) for _ in range(worker_count) ] for process in processes: process.start() totals = {"built": 0, "loaded": 0, "failed": 0} for completed in range(1, len(selected) + 1): scene, status, detail = results.get() totals[status] += 1 print( f"[{completed}/{len(selected)}] {scene}: {status} -> {detail}", flush=True ) for process in processes: process.join() if totals["failed"]: raise RuntimeError(f"{totals['failed']} experiment scene(s) failed") return totals def main() -> None: parser = argparse.ArgumentParser() parser.add_argument("--hypothesis", required=True) parser.add_argument( "--depth", default="metric", choices=encoder_config.DEPTH_VARIANTS ) parser.add_argument( "--input", default="uniform", choices=encoder_config.INPUT_SELECTIONS, dest="input_selection", ) parser.add_argument( "--tracking", default="tracking", choices=encoder_config.TRACKING_MODES ) parser.add_argument("--frames", type=int, default=64) parser.add_argument( "--format", default="explicit", choices=config.SPATIAL_CODE_FORMATS, dest="spatial_code_format", ) parser.add_argument( "--workers", type=int, default=0, help="worker processes; default 0 uses every available CPU", ) parser.add_argument("--rebuild", action="store_true") parser.add_argument("--scene", action="append", dest="scenes") args = parser.parse_args() if args.frames < 1: parser.error("--frames must be positive") if args.workers < 0: parser.error("--workers cannot be negative") scenes = args.scenes or scenes_with_existing_cache( args.depth, args.input_selection, args.tracking, args.frames ) settings = { "hypothesis": args.hypothesis, "depth": args.depth, "tracking": args.tracking, "input_selection": args.input_selection, "frame_count": args.frames, "rebuild": args.rebuild, "spatial_code_format": args.spatial_code_format, } totals = launch(settings, scenes, args.workers) print( f"DONE: {totals['built']} built, {totals['loaded']} loaded, " f"{totals['failed']} failed" ) if __name__ == "__main__": main()