"""Fail-fast GPU requirements. Never stops another process or silently falls back to CPU.""" import os import subprocess import xml.etree.ElementTree as ET import torch def check_gpu(cfg: dict) -> None: if not cfg.get("require_cuda"): return # historical CPU smoke tests remain supported if not torch.cuda.is_available(): raise RuntimeError("This run requires CUDA; CPU fallback is disabled") if cfg.get("exclusive_gpu"): try: # Check before creating a CUDA context / loading model weights. Single-card local profile. # Windows WDDM query-compute-apps can include all desktop graphics clients. # The XML process type separates pure compute workers; utilization/free VRAM # below also reject substantial work in mixed graphics/compute applications. result = subprocess.run(["nvidia-smi", "--id=0", "--query", "--xml-format"], capture_output=True, text=True, check=True, timeout=10) gpu = ET.fromstring(result.stdout).find("gpu") if gpu is None: raise ValueError("missing GPU telemetry") processes = gpu.findall("processes/process_info") pids = {int(p.findtext("pid")) for p in processes if p.findtext("type") == "C"} except (OSError, subprocess.SubprocessError, ET.ParseError, ValueError, TypeError) as exc: raise RuntimeError("Cannot verify exclusive GPU availability with nvidia-smi; training was not started") from exc other = sorted(pids - {os.getpid()}) if other: raise RuntimeError(f"GPU already has compute processes {other}; finish them before starting this run. No process was stopped") try: utilization = float(gpu.findtext("utilization/gpu_util").split()[0]) free = float(gpu.findtext("fb_memory_usage/free").split()[0]) * 1024**2 except (AttributeError, ValueError, TypeError) as exc: raise RuntimeError("GPU utilization/free-memory telemetry unavailable; training was not started") from exc if utilization > cfg.get("max_idle_gpu_util", 20): raise RuntimeError(f"GPU utilization is {utilization:.0f}%; wait for current GPU work to finish") required = cfg.get("min_free_vram_gb", 0) if free / 1e9 < required: raise RuntimeError(f"GPU has {free/1e9:.2f} GB free; this pilot requires {required} GB before profiling") return required = cfg.get("min_free_vram_gb", 0) if required: free, _ = torch.cuda.mem_get_info() if free / 1e9 < required: raise RuntimeError(f"GPU has {free/1e9:.2f} GB free; this pilot requires {required} GB before profiling")