from __future__ import annotations import json import os import shutil import shlex import subprocess from dataclasses import dataclass from pathlib import Path from typing import Literal from packages.adapters.protocols import NotConfiguredError from packages.core.files import atomic_write_text from packages.runtime.gpu_scheduler import GpuInfo, parse_nvidia_smi MODEL_CACHE = Path(os.environ.get("XDG_CACHE_HOME", str(Path.home() / ".cache"))) / "robohomegen" DEFAULT_SAM3_CHECKPOINT = MODEL_CACHE / "models/sam3/sam3.pt" DEFAULT_SAM3D_PIPELINE = MODEL_CACHE / "models/sam-3d-objects/checkpoints/pipeline.yaml" Sam3DMemoryStrategy = Literal["single_gpu", "staged_process", "fsdp"] @dataclass(frozen=True, slots=True) class Sam3DSettings: command: tuple[str, ...] sam3_checkpoint: Path = DEFAULT_SAM3_CHECKPOINT pipeline_config: Path = DEFAULT_SAM3D_PIPELINE minimum_vram_gb: float = 32.0 memory_strategy: Sam3DMemoryStrategy = "single_gpu" stage_gpu_ids: tuple[int, ...] = () @classmethod def from_env(cls) -> Sam3DSettings: command = tuple(shlex.split(os.environ.get("SAM3D_COMMAND", ""))) minimum_vram_gb = float(os.environ.get("SAM3D_MIN_VRAM_GB", "32")) if minimum_vram_gb <= 0: raise ValueError("SAM3D_MIN_VRAM_GB must be positive") memory_strategy = os.environ.get("SAM3D_MEMORY_STRATEGY", "single_gpu") if memory_strategy not in {"single_gpu", "staged_process", "fsdp"}: raise ValueError("SAM3D_MEMORY_STRATEGY must be single_gpu, staged_process, or fsdp") stage_gpu_ids = tuple( int(item) for item in os.environ.get("SAM3D_STAGE_GPU_IDS", "").split(",") if item ) return cls( command=command, sam3_checkpoint=Path(os.environ.get("SAM3_CHECKPOINT", str(DEFAULT_SAM3_CHECKPOINT))), pipeline_config=Path( os.environ.get("SAM3D_PIPELINE_CONFIG", str(DEFAULT_SAM3D_PIPELINE)) ), minimum_vram_gb=minimum_vram_gb, memory_strategy=memory_strategy, # type: ignore[arg-type] stage_gpu_ids=stage_gpu_ids, ) def query_gpus() -> list[GpuInfo]: if os.environ.get("RHG_CPU_ONLY") == "1" or shutil.which("nvidia-smi") is None: return [] result = subprocess.run( [ "nvidia-smi", "--query-gpu=index,name,memory.total,memory.used,memory.free,utilization.gpu", "--format=csv,noheader,nounits", ], check=False, capture_output=True, text=True, ) if result.returncode: return [] return parse_nvidia_smi(result.stdout) def probe_sam3d(settings: Sam3DSettings | None = None) -> dict[str, object]: settings = settings or Sam3DSettings.from_env() gpus = query_gpus() minimum_vram_mb = int(settings.minimum_vram_gb * 1024) capable_gpus = [gpu.index for gpu in gpus if gpu.memory_total_mb >= minimum_vram_mb] strategy_supported = settings.memory_strategy != "fsdp" if settings.memory_strategy == "staged_process": # Process isolation removes the simultaneous SAM3 + SAM3D residency. The # reconstruction peak is still determined by the upstream SAM3D pipeline. capable_gpus = [gpu.index for gpu in gpus if gpu.memory_total_mb >= 23 * 1024] checkpoints_ready = settings.sam3_checkpoint.is_file() and settings.pipeline_config.is_file() return { "configured": bool(settings.command), "ready": ( bool(settings.command) and checkpoints_ready and bool(capable_gpus) and strategy_supported ), "command_configured": bool(settings.command), "sam3_checkpoint": str(settings.sam3_checkpoint), "sam3_checkpoint_ready": settings.sam3_checkpoint.is_file(), "pipeline_config": str(settings.pipeline_config), "pipeline_config_ready": settings.pipeline_config.is_file(), "minimum_vram_gb": settings.minimum_vram_gb, "memory_strategy": settings.memory_strategy, "strategy_supported": strategy_supported, "strategy_note": ( "FSDP is not supported by the upstream single-process sparse inference pipeline" if settings.memory_strategy == "fsdp" else "SAM3 and SAM3D run in isolated processes" if settings.memory_strategy == "staged_process" else "upstream single-GPU execution" ), "stage_gpu_ids": list(settings.stage_gpu_ids), "capable_gpu_ids": capable_gpus, "detected_gpu_vram_gb": [round(gpu.memory_total_mb / 1024, 2) for gpu in gpus], } class Sam3DAdapter: """File-protocol adapter for SAM 3D Objects in an isolated CUDA environment.""" def __init__(self, settings: Sam3DSettings | None = None) -> None: self.settings = settings or Sam3DSettings.from_env() def generate( self, image: Path, output_dir: Path, *, prompt: str | None = None, mask: Path | None = None, seed: int = 42, ) -> Path: if not image.is_file(): raise FileNotFoundError(image) if mask is not None and not mask.is_file(): raise FileNotFoundError(mask) status = probe_sam3d(self.settings) if not self.settings.command: raise NotConfiguredError("SAM3D_COMMAND is not configured") if not self.settings.sam3_checkpoint.is_file(): raise NotConfiguredError(f"SAM3 checkpoint not found: {self.settings.sam3_checkpoint}") if not self.settings.pipeline_config.is_file(): raise NotConfiguredError( f"SAM 3D Objects pipeline config not found: {self.settings.pipeline_config}" ) if not status["capable_gpu_ids"]: raise RuntimeError( f"SAM3D requires a GPU with at least {self.settings.minimum_vram_gb:g} GB VRAM; " f"detected {status['detected_gpu_vram_gb']} GB" ) if not status["strategy_supported"]: raise RuntimeError(str(status["strategy_note"])) output_dir.mkdir(parents=True, exist_ok=True) request_path = output_dir / "sam3d_request.json" manifest_path = output_dir / "sam3d_manifest.json" request = { "schema_version": "1.0", "image": str(image.resolve()), "mask": str(mask.resolve()) if mask is not None else None, "prompt": prompt, "seed": seed, "sam3_checkpoint": str(self.settings.sam3_checkpoint.resolve()), "pipeline_config": str(self.settings.pipeline_config.resolve()), "memory_strategy": self.settings.memory_strategy, } atomic_write_text(request_path, json.dumps(request, indent=2, sort_keys=True) + "\n") stages = ( ("mask", "reconstruct") if self.settings.memory_strategy == "staged_process" else ("full",) ) for index, stage in enumerate(stages): environment = os.environ.copy() if self.settings.stage_gpu_ids: environment["CUDA_VISIBLE_DEVICES"] = str( self.settings.stage_gpu_ids[min(index, len(self.settings.stage_gpu_ids) - 1)] ) environment.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True") command = [ *self.settings.command, "--request", str(request_path), "--output", str(output_dir), ] if self.settings.memory_strategy == "staged_process": command.extend(("--stage", stage)) result = subprocess.run( command, check=False, capture_output=True, text=True, env=environment, ) if result.returncode: details = (result.stdout + "\n" + result.stderr)[-2000:] raise RuntimeError( f"SAM3D {stage} worker failed ({result.returncode}): {details}" ) if not manifest_path.is_file(): raise RuntimeError("SAM3D worker did not produce sam3d_manifest.json") json.loads(manifest_path.read_text(encoding="utf-8")) return manifest_path