from __future__ import annotations import os import subprocess import time from dataclasses import dataclass from pathlib import Path from typing import TextIO from packages.core.file_lock import lock_file NVIDIA_SMI_QUERY = "index,name,memory.total,memory.used,memory.free,utilization.gpu" @dataclass(frozen=True, slots=True) class GpuInfo: index: int name: str memory_total_mb: int memory_used_mb: int memory_free_mb: int utilization_percent: int def parse_nvidia_smi(output: str) -> list[GpuInfo]: gpus: list[GpuInfo] = [] for line_number, raw_line in enumerate(output.splitlines(), start=1): line = raw_line.strip() if not line: continue parts = [part.strip() for part in line.split(",")] if len(parts) != 6: raise ValueError(f"invalid nvidia-smi row {line_number}: {raw_line!r}") try: gpus.append( GpuInfo( index=int(parts[0]), name=parts[1], memory_total_mb=int(parts[2]), memory_used_mb=int(parts[3]), memory_free_mb=int(parts[4]), utilization_percent=int(parts[5]), ) ) except ValueError as exc: raise ValueError(f"invalid nvidia-smi row {line_number}: {raw_line!r}") from exc return gpus def select_gpus( gpus: list[GpuInfo], *, allowed_ids: set[int] | None, max_gpus: int, min_free_vram_mb: int, max_used_vram_mb: int, max_utilization_percent: int, ) -> list[GpuInfo]: if max_gpus < 0: raise ValueError("max_gpus must be non-negative (0 means all eligible GPUs)") candidates = [ gpu for gpu in gpus if (allowed_ids is None or gpu.index in allowed_ids) and gpu.memory_free_mb >= min_free_vram_mb and gpu.memory_used_mb <= max_used_vram_mb and gpu.utilization_percent <= max_utilization_percent ] candidates.sort(key=lambda gpu: (gpu.utilization_percent, -gpu.memory_free_mb, gpu.index)) return candidates if max_gpus == 0 else candidates[:max_gpus] def probe_gpus() -> list[GpuInfo]: completed = subprocess.run( [ "nvidia-smi", f"--query-gpu={NVIDIA_SMI_QUERY}", "--format=csv,noheader,nounits", ], check=True, capture_output=True, text=True, ) return parse_nvidia_smi(completed.stdout) @dataclass(slots=True) class GpuLease: gpu: GpuInfo handle: TextIO def close(self) -> None: if not self.handle.closed: self.handle.close() def __enter__(self) -> GpuLease: return self def __exit__(self, *_: object) -> None: self.close() class DynamicGpuPool: """Cross-process GPU leasing with a fresh memory check before every lease.""" def __init__( self, lock_root: Path, *, allowed_ids: set[int] | None = None, min_free_vram_mb: int = 8192, max_used_vram_mb: int = 1 << 30, max_utilization_percent: int = 100, ) -> None: self.lock_root = lock_root self.allowed_ids = allowed_ids self.min_free_vram_mb = min_free_vram_mb self.max_used_vram_mb = max_used_vram_mb self.max_utilization_percent = max_utilization_percent self.lock_root.mkdir(parents=True, exist_ok=True) def try_acquire(self, *, excluded_ids: set[int] | None = None) -> GpuLease | None: excluded_ids = excluded_ids or set() candidates = select_gpus( probe_gpus(), allowed_ids=( None if self.allowed_ids is None else self.allowed_ids - excluded_ids ), max_gpus=0, min_free_vram_mb=self.min_free_vram_mb, max_used_vram_mb=self.max_used_vram_mb, max_utilization_percent=self.max_utilization_percent, ) if self.allowed_ids is None: candidates = [gpu for gpu in candidates if gpu.index not in excluded_ids] for gpu in candidates: path = self.lock_root / f"gpu-{gpu.index}.lock" handle = path.open("a+", encoding="utf-8") if not lock_file(handle, blocking=False): handle.close() continue handle.seek(0) handle.truncate() handle.write( f"pid={os.getpid()} gpu={gpu.index} acquired_unix={time.time():.3f}\n" ) handle.flush() return GpuLease(gpu=gpu, handle=handle) return None def acquire( self, *, timeout_s: float, poll_interval_s: float = 5.0, excluded_ids: set[int] | None = None, ) -> GpuLease: deadline = time.monotonic() + timeout_s while True: lease = self.try_acquire(excluded_ids=excluded_ids) if lease is not None: return lease if time.monotonic() >= deadline: raise TimeoutError("no GPU satisfied the lease requirements before timeout") time.sleep(min(poll_interval_s, max(0.0, deadline - time.monotonic())))