"""Persistent CPU-parallel batch driver for the VSI encoder. Without a scene argument, processes manifest scenes with all required inference caches. CPU-bound encoding defaults to one worker per available CPU, with nested numerical threads budgeted across workers. """ from __future__ import annotations import argparse import json import multiprocessing as mp import os from pathlib import Path import subprocess 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 # noqa: E402 def _scenes(): with open(config.JSONL) as f: return list(dict.fromkeys(str(json.loads(line)["scene_name"]) for line in f)) def _video_cache_files(scene, depth, tracking): """Return full-video perception-cache files for the selected axes.""" return ( Path(config.video_da3_cache_file(scene, depth)), Path(config.video_sam3_cache_file(scene, tracking)), ) def _has_required_caches( scene, depth, input_selection, tracking, frame_count, video=False ): """Return whether all inference caches needed for encoding exist.""" if video: paths = _video_cache_files(scene, depth, tracking) else: paths = ( config.sam3_cache_file(scene, input_selection, tracking, frame_count), config.da3_cache_file(scene, depth, input_selection, frame_count), ) return all(os.path.isfile(path) for path in paths) def _scenes_with_required_caches( depth, input_selection, tracking, frame_count, video=False ): """Return manifest scenes having every cache required by this encoder run.""" return [ scene for scene in _scenes() if _has_required_caches( scene, depth, input_selection, tracking, frame_count, video ) ] def _available_cpu_count(): """Return the CPUs available to this process, respecting affinity and overrides.""" configured = os.environ.get("VSI_CPU_WORKERS") if configured is not None: count = int(configured) 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 _visible_gpus(): configured = os.environ.get("CUDA_VISIBLE_DEVICES") if configured is not None: return [ x.strip() for x in configured.split(",") if x.strip() and x.strip() != "-1" ] try: out = subprocess.check_output( ["nvidia-smi", "--query-gpu=index", "--format=csv,noheader"], text=True, stderr=subprocess.DEVNULL, ) return [line.strip() for line in out.splitlines() if line.strip()] except (FileNotFoundError, subprocess.SubprocessError): return [] def _worker( task_queue, result_queue, depth, input_selection, tracking, frame_count, rebuild, cpu_threads, video, ): for variable in ("OMP_NUM_THREADS", "MKL_NUM_THREADS", "OPENBLAS_NUM_THREADS"): os.environ[variable] = str(cpu_threads) import cv2 cv2.setNumThreads(cpu_threads) os.environ["VSI_KD_WORKERS"] = str(cpu_threads) # torch ignores the OMP/MKL/OPENBLAS env vars above (and sched_getaffinity/cgroup # limits) -- it defaults both its intra-op and inter-op pools to the machine's full # logical core count. adapters._load_native_sam3 imports torch to read the SAM3 # cache, so every worker would otherwise spin up its own full-width thread pool on # top of the budget already enforced for numpy/cv2/scipy. import torch torch.set_num_threads(cpu_threads) try: torch.set_num_interop_threads(cpu_threads) except RuntimeError: pass # already used/set once in this process; not worth failing the worker over from encoder import render from encoder.adapters import EmptySceneError while True: scene = task_queue.get() if scene is None: return try: _, how, path = render.write_spatial_code_for( scene, depth, input_selection, tracking, frame_count, rebuild, video, ) result_queue.put((scene, "done", f"{how} -> {path}")) except EmptySceneError: result_queue.put((scene, "skipped", "cache produced no instances")) except Exception: result_queue.put((scene, "failed", traceback.format_exc())) def _launch(args, selected): label = ( f"{args.depth}/{args.tracking}/video" if args.video else f"{args.depth}/{args.tracking}/{args.input_selection}/{args.frames}" ) pending = [] completed = 0 for scene in selected: output_exists = os.path.exists( config.spatial_code_path( scene, args.depth, args.input_selection, args.tracking, args.frame_count, "explicit", ) ) if output_exists and not args.rebuild: completed += 1 print(f"[{label} {completed}/{len(selected)}] {scene}: skipped", flush=True) else: pending.append(scene) if not pending: print(f"[{label}] DONE: {len(selected)} ok, 0 failed") return cpu_count = _available_cpu_count() worker_count = args.workers or cpu_count if worker_count < 1: raise ValueError("--workers must be positive or zero for automatic") worker_count = min(worker_count, len(pending)) cpu_threads = max(1, cpu_count // worker_count) for variable in ("OMP_NUM_THREADS", "MKL_NUM_THREADS", "OPENBLAS_NUM_THREADS"): os.environ[variable] = str(cpu_threads) print( f"[{label}] starting {worker_count} persistent CPU worker(s); " f"threads per worker={cpu_threads}", flush=True, ) context = mp.get_context("spawn") tasks, results = context.Queue(), context.Queue() for scene in pending: tasks.put(scene) for _ in range(worker_count): tasks.put(None) processes = [ context.Process( target=_worker, args=( tasks, results, args.depth, args.input_selection, args.tracking, args.frame_count, args.rebuild, cpu_threads, args.video, ), ) for _ in range(worker_count) ] for process in processes: process.start() failed = [] skipped = 0 for _ in pending: scene, status, detail = results.get() completed += 1 if status == "failed": failed.append(scene) elif status == "skipped": skipped += 1 display_status = "FAILED" if status == "failed" else status print( f"[{label} {completed}/{len(selected)}] {scene}: " f"{display_status}\n{detail}", flush=True, ) for process in processes: process.join() succeeded = len(selected) - len(failed) - skipped print( f"[{label}] DONE: {succeeded} ok, {skipped} skipped, " f"{len(failed)} failed" ) if failed: raise SystemExit(1) def main(): parser = argparse.ArgumentParser() parser.add_argument("scene", nargs="?") parser.add_argument("--depth", choices=config.DEPTH_VARIANTS) parser.add_argument( "--input", choices=config.INPUT_SELECTIONS, dest="input_selection", ) input_mode = parser.add_mutually_exclusive_group(required=True) input_mode.add_argument("--frames", type=int) input_mode.add_argument( "--video", action="store_true", help="use full-video DA3 and SAM3 caches", ) parser.add_argument("--tracking", choices=config.TRACKING_MODES) parser.add_argument( "--workers", type=int, default=0, help="persistent workers (default: all available CPUs)", ) parser.add_argument("--rebuild", action="store_true") args = parser.parse_args() if args.depth is None: parser.error("--depth is required") if args.tracking is None: parser.error("--tracking is required") if args.video: if args.input_selection is not None: parser.error("--input cannot be used with --video") args.input_selection = config.VIDEO_INPUT_SELECTION elif args.input_selection is None: parser.error("--input is required with --frames") if args.frames is not None and args.frames < 1: parser.error("--frames must be positive") args.frame_count = args.frames if args.workers < 0: parser.error("--workers must be positive or zero for automatic") selected = ( [args.scene] if args.scene else _scenes_with_required_caches( args.depth, args.input_selection, args.tracking, args.frame_count, args.video, ) ) if not selected: print("DONE: no manifest scenes have all required caches") return _launch(args, selected) if __name__ == "__main__": main()