File size: 5,981 Bytes
a45b7c9 02cbb89 a45b7c9 02cbb89 8e80498 02cbb89 a45b7c9 02cbb89 a45b7c9 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 | """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()
|