workspace / encoder /launch.py
AntonioJun's picture
Add files using upload-large-folder tool
2f5ffdf verified
Raw
History Blame
8.68 kB
"""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 _has_required_caches(scene, depth, input_selection, tracking, frame_count):
"""Return whether all native inference caches needed for encoding exist."""
return all(
os.path.isfile(path)
for path in (
config.sam3_cache_file(
scene, input_selection, tracking, frame_count
),
config.da3_cache_file(
scene, depth, input_selection, frame_count
),
)
)
def _scenes_with_required_caches(
depth, input_selection, tracking, frame_count
):
"""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
)
]
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,
spatial_code_format,
):
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,
spatial_code_format,
)
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}/{args.input_selection}/{args.frames}/"
f"{args.spatial_code_format}"
)
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.frames,
args.spatial_code_format,
)
)
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.frames,
args.rebuild,
cpu_threads,
args.spatial_code_format,
),
)
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", 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(
"--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.frames < 1:
parser.error("--frames must be positive")
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.frames,
)
)
if not selected:
print("DONE: no manifest scenes have all required caches")
return
_launch(args, selected)
if __name__ == "__main__":
main()