Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: read the NVIDIA inventory from NVML or the CUDA driver when nvidia-smi cannot answer (#10985)
Daniel Han1e07231872e0
diff --git a/.github/workflows/cross-platform-parity-ci.yml b/.github/workflows/cross-platform-parity-ci.ymlindex 867f642bf29..01777020919 100644--- a/.github/workflows/cross-platform-parity-ci.yml+++ b/.github/workflows/cross-platform-parity-ci.yml@@ -85,6 +85,7 @@ on:# above is only the entrypoint; these two are the rest of what it loads.- 'tests/studio/install/test_keep_install_backcompat_9979.py'- 'studio/prebuilt_core.py'+ - 'studio/nvidia_probe.py'- 'studio/backend/utils/prebuilt/llama_backend.py'- 'tests/sh/test_install_rollback_lifecycle.sh'- 'tests/studio/test_install_rollback_lifecycle.ps1'@@ -162,6 +163,7 @@ on:# above is only the entrypoint; these two are the rest of what it loads.- 'tests/studio/install/test_keep_install_backcompat_9979.py'- 'studio/prebuilt_core.py'+ - 'studio/nvidia_probe.py'- 'studio/backend/utils/prebuilt/llama_backend.py'- 'tests/sh/test_install_rollback_lifecycle.sh'- 'tests/studio/test_install_rollback_lifecycle.ps1'diff --git a/studio/backend/tests/conftest.py b/studio/backend/tests/conftest.pyindex e34ed020d8f..488691e20bd 100644--- a/studio/backend/tests/conftest.py+++ b/studio/backend/tests/conftest.py@@ -65,6 +65,8 @@ os.environ.setdefault("UNSLOTH_IS_PRESENT", "1")os.environ.setdefault("UNSLOTH_DIFFUSION_ATTENTION_INSTALL", "0")# Avoid a cold torch subprocess in unrelated RAG tests. The probe tests re-enable it.os.environ.setdefault("UNSLOTH_STUDIO_DISABLE_DEVICE_PROBE", "1")+# A test that hides nvidia-smi to fake a CPU host must not find the real GPUs through NVML.+os.environ.setdefault("UNSLOTH_NVIDIA_LIBRARY_PROBE", "0")# settled_snapshot_device_memory spaces its retried VRAM reads a real second apart so a# transient tenant on a live card has time to clear. Under test the snapshots are stubs# whose answers do not change with time, so the wait buys nothing and the max() over thediff --git a/studio/install_llama_prebuilt.py b/studio/install_llama_prebuilt.pyindex a253a43a0fe..0d4b3eb620d 100644--- a/studio/install_llama_prebuilt.py+++ b/studio/install_llama_prebuilt.py@@ -53,6 +53,30 @@ if _STUDIO_DIR not in sys.path:sys.path.insert(0, _STUDIO_DIR)import prebuilt_core as _core # noqa: E402++try:+ import nvidia_probe as _nvidia_probe # noqa: E402+except Exception: # an older checkout beside a newer setup script+ _nvidia_probe = None+++def nvidia_library_inventory():+ """The NVML / CUDA driver inventory, or None. A seam, so tests can hide the real host."""+ return _nvidia_probe.probe() if _nvidia_probe is not None else None+++def proc_driver_version() -> str:+ if _nvidia_probe is None or not _nvidia_probe.enabled():+ return ""+ return _nvidia_probe.proc_driver_version()+++def cuda_version_for_driver(driver_version: str) -> tuple[int, int] | None:+ if _nvidia_probe is None:+ return None+ return _nvidia_probe.cuda_version_for_driver(driver_version)++from backend.utils.prebuilt.llama_backend import ( # noqa: E402INSTALL_KIND_BACKENDS,REQUESTABLE_BACKENDS,@@ -2692,10 +2716,7 @@ def detect_host(*, probe_rocm_with_nvidia: bool = False) -> HostInfo:# nvidia-smi is absent from PATH, wedged, or failing is still recognised as# NVIDIA. Mirrors the fallback added to install.sh / install_python_stack.py# in PR 6174 so the prebuilt installer does not misroute such hosts to ROCm- # or CPU. driver_cuda_version / compute_caps stay unset here; downstream- # CUDA asset selection treats unknown SMs as "prefer portable" and an- # unknown driver runtime line as "no published CUDA match" (returns None,- # no crash), so planning falls back to a source build with GGML_CUDA=ON.+ # or CPU. driver_cuda_version / compute_caps are filled below where they can be.if is_linux and not has_physical_nvidia:try:proc_gpu_dir = "/proc/driver/nvidia/gpus"@@ -2705,6 +2726,51 @@ def detect_host(*, probe_rocm_with_nvidia: bool = False) -> HostInfo:except OSError:pass+ # What nvidia-smi could not say (absent, stale, hung, non-zero exit), the driver's own+ # libraries can. NVML is the physical inventory, like nvidia-smi, so the mask applies.+ if (is_linux or is_windows) and (+ not has_physical_nvidia or driver_cuda_version is None or not physical_compute_caps+ ):+ inventory = nvidia_library_inventory()+ if inventory is not None and inventory.devices:+ log(+ f"NVIDIA inventory read through {inventory.source}: "+ f"{len(inventory.devices)} GPU(s), CUDA driver {inventory.cuda_driver_version}"+ )+ rows = [(d["index"], d["uuid"], d["compute_cap"]) for d in inventory.devices]+ if inventory.source == "nvml":+ visible_rows = select_visible_gpu_rows(rows, visible_device_tokens)+ else:+ visible_rows = rows+ if not has_physical_nvidia:+ has_physical_nvidia = True+ # As the nvidia-smi rows are read: a mask NVML rows cannot name (a MIG+ # UUID) leaves the GPU usable.+ has_usable_nvidia = bool(visible_rows) or (+ visible_device_tokens is not None+ and visible_device_tokens != []+ and not supports_explicit_visible_device_matching(visible_device_tokens)+ )+ for _index, _uuid, cap in rows:+ normalized_cap = normalize_compute_cap(cap)+ if normalized_cap is not None and normalized_cap not in physical_compute_caps:+ physical_compute_caps.append(normalized_cap)+ if not compute_caps:+ for _index, _uuid, cap in visible_rows:+ normalized_cap = normalize_compute_cap(cap)+ if normalized_cap is not None and normalized_cap not in compute_caps:+ compute_caps.append(normalized_cap)+ if inventory is not None and driver_cuda_version is None:+ driver_cuda_version = inventory.cuda_driver_version+ if is_linux and has_physical_nvidia and driver_cuda_version is None:+ # The kernel module names its release even when every library call fails, and the+ # release bounds the CUDA major (R580 carries 13, R525 carries 12).+ driver_cuda_version = cuda_version_for_driver(proc_driver_version())+ if driver_cuda_version is not None:+ log(+ f"CUDA driver version {driver_cuda_version} inferred from /proc/driver/nvidia/version"+ )+# Detect AMD ROCm (HIP) -- require actual GPU, not just tools installed.# NVIDIA takes precedence for automatic selection: when an NVIDIA GPU is# usable, skip ROCm probing so co-installed ROCm tools cannot misroute thediff --git a/studio/install_python_stack.py b/studio/install_python_stack.pyindex 0adf6fa9d8f..11b88f968a2 100644--- a/studio/install_python_stack.py+++ b/studio/install_python_stack.py@@ -40,6 +40,17 @@ for _dir in (_BACKEND_DIR, _STUDIO_DIR):# setup.sh/setup.ps1 invoke this by path, so its directory is sys.path[0].import install_manifest # noqa: E402+try:+ import nvidia_probe as _nvidia_probe # noqa: E402+except Exception: # an older checkout beside a newer setup script+ _nvidia_probe = None+++def _nvidia_library_inventory():+ """The NVML / CUDA driver inventory, or None. A seam, so tests can hide the real host."""+ return _nvidia_probe.probe() if _nvidia_probe is not None else None++from backend.utils.wheel_utils import (flash_attn_package_version,flash_attn_wheel_url,@@ -2533,7 +2544,18 @@ def _has_usable_nvidia_gpu() -> bool:return Trueexcept OSError:pass- return False+ # Last: the driver's own libraries, which ship without the nvidia-smi utility.+ inventory = _nvidia_library_inventory()+ if inventory is None or not inventory.devices:+ return False+ if inventory.source != "nvml" or cvd is None:+ return True # the CUDA driver rows already honour the mask+ # NVML rows are physical: an explicit index or GPU- UUID mask must name one of them.+ # A mask they cannot name (a MIG UUID) is left usable, as the probes above leave it.+ tokens = [t.strip().lower() for t in cvd.split(",") if t.strip()]+ if not all(t.isdigit() or t.startswith("gpu-") for t in tokens):+ return True+ return any(row["index"] in tokens or row["uuid"].lower() in tokens for row in inventory.devices)# Which probe answered the last _detect_amd_gfx_codes() call: only rocminfo is subject@@ -3452,21 +3474,27 @@ def _span_covers(span: "tuple[int, int]", sms: "list[int]") -> bool:return all(span[0] <= sm <= span[1] for sm in sms)-def _cap_cuda_family_for_pre_turing(family: str, exe: "str | None") -> str:+def _cap_cuda_family_for_pre_turing(+ family: str,+ exe: "str | None",+ sms: "list[int] | None" = None,+) -> str:"""Use cu126 when it covers every physical GPU missed by the selected family.CUDA_VISIBLE_DEVICES is intentionally ignored. Non-x86_64 hosts retain the- driver-derived family because their wheel matrices differ.+ driver-derived family because their wheel matrices differ. `sms` is the inventory+ already in hand (the library probe); otherwise it is read from `exe`."""if platform.machine().lower() not in ("x86_64", "amd64"):return familyspan = _cuda_family_sm_range(family)- if span is None or exe is None:+ if span is None or (exe is None and sms is None):return familyif span[0] <= _CU126_SM_RANGE[0]:return family # nothing lower to fall back tofloor = span[0]- sms = _nvidia_compute_sms(exe)+ if sms is None:+ sms = _nvidia_compute_sms(exe)if not sms or all(sm >= floor for sm in sms):return family # no GPU here sits under the family's floorif not _span_covers(_CU126_SM_RANGE, sms):@@ -3484,6 +3512,21 @@ def _cap_cuda_family_for_pre_turing(family: str, exe: "str | None") -> str:return "cu126"+def _torch_family_for_cuda_version(major: int, minor: int) -> str:+ """install.sh::get_torch_index_url's CUDA ladder, from the driver's CUDA version."""+ if major >= 13:+ return "cu130"+ if major == 12 and minor >= 8:+ return "cu128"+ if major == 12 and minor >= 6:+ return "cu126"+ if major >= 12:+ return "cu124"+ if major >= 11:+ return "cu118"+ return "cpu" # ancient driver: no usable CUDA wheels++def _detect_cuda_torch_index_url() -> str:"""Return the pytorch.org CUDA wheel index URL for the host's NVIDIA driver.@@ -3531,20 +3574,23 @@ def _detect_cuda_torch_index_url() -> str:m = re.search(r"CUDA(?: UMD)? Version:\s*(\d+)\.(\d+)", result.stdout)if m is None:continue- major, minor = int(m.group(1)), int(m.group(2))- if major >= 13:- tag = "cu130"- elif major == 12 and minor >= 8:- tag = "cu128"- elif major == 12 and minor >= 6:- tag = "cu126"- elif major >= 12:- tag = "cu124"- elif major >= 11:- tag = "cu118"- else:- tag = "cpu" # ancient driver: no usable CUDA wheels+ tag = _torch_family_for_cuda_version(int(m.group(1)), int(m.group(2)))return f"{_PYTORCH_WHL_BASE}/{_cap_cuda_family_for_pre_turing(tag, exe)}"+ # No nvidia-smi: the driver libraries carry the same version and the SMs the pre-Turing+ # cap needs. Defaulting to cu126 gave Blackwell a kernel-less wheel; without SMs the+ # default stays, since cu128+ has none for Maxwell, Pascal or Volta either.+ inventory = _nvidia_library_inventory()+ if inventory is not None and inventory.cuda_driver_version:+ sms = []+ for row in inventory.devices:+ m = re.fullmatch(r"(\d+)\.(\d+)", row.get("compute_cap", ""))+ if m is None:+ sms = []+ break+ sms.append(int(m.group(1)) * 10 + int(m.group(2)))+ if sms:+ family = _torch_family_for_cuda_version(*inventory.cuda_driver_version)+ return f"{_PYTORCH_WHL_BASE}/{_cap_cuda_family_for_pre_turing(family, None, sms)}"return f"{_PYTORCH_WHL_BASE}/{tag}"diff --git a/studio/nvidia_probe.py b/studio/nvidia_probe.pynew file mode 100644index 00000000000..9496016a652--- /dev/null+++ b/studio/nvidia_probe.py@@ -0,0 +1,288 @@+#!/usr/bin/env python3+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0+"""NVIDIA inventory read from the driver's own libraries, for a host nvidia-smi cannot answer for.++An absent, stale or hanging nvidia-smi read as a CPU host, which is fatal to the install.+Ollama, Jan and lemonade ask NVML or the CUDA driver API instead, which ship with the driver.++* NVML (`libnvidia-ml.so.1` / `nvml.dll`): the PHYSICAL inventory, unmasked like nvidia-smi;+ the caller applies CUDA_VISIBLE_DEVICES.+* the CUDA driver API (`libcuda.so.1` / `nvcuda.dll`): honours the mask; used when NVML is+ unavailable.++Always a child process with a deadline: these libraries block in-process in the states that+hang nvidia-smi. Failing both, `/proc/driver/nvidia/version` names the driver, and the driver+major bounds the CUDA major (13 needs R580+, 12 R525+, 11 R450+).+"""++from __future__ import annotations++import ctypes+import json+import os+import re+import subprocess+import sys+from dataclasses import dataclass, field+++@dataclass+class NvidiaLibraryInventory:+ source: str # "nvml" or "cuda"+ cuda_driver_version: tuple[int, int] | None+ driver_version: str+ # index, uuid, name, compute_cap ("8.9"); NVML order is physical and unmasked.+ devices: list[dict[str, str]] = field(default_factory = list)+++def _library_candidates(kind: str) -> list[str]:+ if sys.platform == "darwin":+ return []+ if sys.platform == "win32":+ system32 = os.path.join(os.environ.get("SystemRoot", r"C:\Windows"), "System32")+ if kind == "nvml":+ nvsmi = [+ os.path.join(root, "NVIDIA Corporation", "NVSMI", "nvml.dll")+ for root in (os.environ.get("ProgramW6432"), os.environ.get("ProgramFiles"))+ if root+ ]+ return [os.path.join(system32, "nvml.dll"), *nvsmi, "nvml.dll"]+ return [os.path.join(system32, "nvcuda.dll"), "nvcuda.dll"]+ if kind == "nvml":+ return ["libnvidia-ml.so.1", "libnvidia-ml.so"]+ return ["libcuda.so.1", "libcuda.so"]+++def _load(kind: str) -> ctypes.CDLL | None:+ for name in _library_candidates(kind):+ try:+ return ctypes.CDLL(name)+ except OSError:+ continue+ return None+++def _split_cuda_version(packed: int) -> tuple[int, int] | None:+ # 13010 -> (13, 1), as CUDA packs it.+ if packed <= 0:+ return None+ return packed // 1000, (packed % 1000) // 10+++def _probe_nvml() -> dict | None:+ nvml = _load("nvml")+ if nvml is None:+ return None+ init = getattr(nvml, "nvmlInit_v2", None) or getattr(nvml, "nvmlInit", None)+ if init is None or init() != 0:+ return None+ try:+ version = ""+ buf = ctypes.create_string_buffer(96)+ if nvml.nvmlSystemGetDriverVersion(buf, 96) == 0:+ version = buf.value.decode("ascii", "replace")+ cuda = None+ packed = ctypes.c_int(0)+ get_cuda = getattr(nvml, "nvmlSystemGetCudaDriverVersion_v2", None) or getattr(+ nvml, "nvmlSystemGetCudaDriverVersion", None+ )+ if get_cuda is not None and get_cuda(ctypes.byref(packed)) == 0:+ cuda = _split_cuda_version(packed.value)+ count = ctypes.c_uint(0)+ get_count = getattr(nvml, "nvmlDeviceGetCount_v2", None) or nvml.nvmlDeviceGetCount+ if get_count(ctypes.byref(count)) != 0:+ return None+ get_handle = getattr(nvml, "nvmlDeviceGetHandleByIndex_v2", None) or (+ nvml.nvmlDeviceGetHandleByIndex+ )+ devices = []+ for index in range(count.value):+ handle = ctypes.c_void_p()+ if get_handle(index, ctypes.byref(handle)) != 0:+ continue+ name = ctypes.create_string_buffer(96)+ uuid = ctypes.create_string_buffer(96)+ major, minor = ctypes.c_int(0), ctypes.c_int(0)+ nvml.nvmlDeviceGetName(handle, name, 96)+ nvml.nvmlDeviceGetUUID(handle, uuid, 96)+ cap = ""+ if (+ nvml.nvmlDeviceGetCudaComputeCapability(+ handle, ctypes.byref(major), ctypes.byref(minor)+ )+ == 0+ ):+ cap = f"{major.value}.{minor.value}"+ devices.append(+ {+ "index": str(index),+ "uuid": uuid.value.decode("ascii", "replace"),+ "name": name.value.decode("utf-8", "replace"),+ "compute_cap": cap,+ }+ )+ return {+ "source": "nvml",+ "cuda_driver_version": list(cuda) if cuda else None,+ "driver_version": version,+ "devices": devices,+ }+ finally:+ try:+ nvml.nvmlShutdown()+ except Exception:+ pass+++def _probe_cuda_driver() -> dict | None:+ cuda = _load("cuda")+ if cuda is None or cuda.cuInit(0) != 0:+ return None+ packed = ctypes.c_int(0)+ version = None+ if cuda.cuDriverGetVersion(ctypes.byref(packed)) == 0:+ version = _split_cuda_version(packed.value)+ count = ctypes.c_int(0)+ if cuda.cuDeviceGetCount(ctypes.byref(count)) != 0:+ count.value = 0+ devices = []+ for index in range(count.value):+ device = ctypes.c_int(0)+ if cuda.cuDeviceGet(ctypes.byref(device), index) != 0:+ continue+ name = ctypes.create_string_buffer(96)+ cuda.cuDeviceGetName(name, 96, device)+ major, minor = ctypes.c_int(0), ctypes.c_int(0)+ # CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MAJOR = 75, _MINOR = 76.+ ok = cuda.cuDeviceGetAttribute(ctypes.byref(major), 75, device) == 0+ ok = ok and cuda.cuDeviceGetAttribute(ctypes.byref(minor), 76, device) == 0+ devices.append(+ {+ "index": str(index),+ "uuid": "",+ "name": name.value.decode("utf-8", "replace"),+ "compute_cap": f"{major.value}.{minor.value}" if ok else "",+ }+ )+ return {+ "source": "cuda",+ "cuda_driver_version": list(version) if version else None,+ "driver_version": "",+ "devices": devices,+ }+++def probe_in_process() -> dict | None:+ """The raw inventory, read in THIS process. Prefer `probe`, which bounds it."""+ for reader in (_probe_nvml, _probe_cuda_driver):+ try:+ result = reader()+ except Exception:+ result = None+ if result is not None:+ return result+ return None+++def _from_payload(payload: object) -> NvidiaLibraryInventory | None:+ if not isinstance(payload, dict) or payload.get("source") not in ("nvml", "cuda"):+ return None+ version = payload.get("cuda_driver_version")+ cuda = tuple(int(part) for part in version[:2]) if isinstance(version, list) else None+ devices = [+ {key: str(row.get(key, "")) for key in ("index", "uuid", "name", "compute_cap")}+ for row in payload.get("devices") or []+ if isinstance(row, dict)+ ]+ return NvidiaLibraryInventory(+ source = str(payload["source"]),+ cuda_driver_version = cuda if cuda and len(cuda) == 2 else None,+ driver_version = str(payload.get("driver_version") or ""),+ devices = devices,+ )+++def enabled() -> bool:+ """UNSLOTH_NVIDIA_LIBRARY_PROBE=0 turns every source here off, the /proc bound included.++ The test suites set it, so a test faking a CPU host does not find the real GPUs here.+ """+ return os.environ.get("UNSLOTH_NVIDIA_LIBRARY_PROBE", "1") != "0"+++def probe(timeout: float = 20) -> NvidiaLibraryInventory | None:+ """The inventory, read in a child with a deadline. None when nothing answered in time."""+ if sys.platform == "darwin" or not enabled():+ return None+ kwargs: dict = {}+ if sys.platform == "win32":+ kwargs["creationflags"] = getattr(subprocess, "CREATE_NO_WINDOW", 0)+ try:+ result = subprocess.run(+ [sys.executable, "-I", os.path.abspath(__file__), "--json"],+ capture_output = True,+ text = True,+ encoding = "utf-8",+ errors = "replace",+ timeout = timeout,+ **kwargs,+ )+ except Exception:+ return None+ if result.returncode not in (0, 1):+ return None+ try:+ return _from_payload(json.loads(result.stdout or "null"))+ except ValueError:+ return None+++_DRIVER_MAJOR_CUDA = (+ (580, (13, 0)),+ (570, (12, 8)),+ (560, (12, 6)),+ (555, (12, 5)),+ (550, (12, 4)),+ (545, (12, 3)),+ (535, (12, 2)),+ (525, (12, 0)),+ (450, (11, 0)),+)+++def cuda_version_for_driver(driver_version: str) -> tuple[int, int] | None:+ """The CUDA version a driver of this release is known to carry (a floor, never above)."""+ match = re.match(r"\s*(\d+)\.", driver_version or "")+ if match is None:+ return None+ major = int(match.group(1))+ for floor, cuda in _DRIVER_MAJOR_CUDA:+ if major >= floor:+ return cuda+ return None+++def proc_driver_version(path: str = "/proc/driver/nvidia/version") -> str:+ """The kernel module's version from /proc, or "": present on Linux whenever the driver is."""+ try:+ with open(path, encoding = "utf-8", errors = "replace") as handle:+ head = handle.readline()+ except OSError:+ return ""+ match = re.search(r"\s(\d+\.\d+(?:\.\d+)?)\s", head)+ return match.group(1) if match else ""+++def main(argv: list[str]) -> int:+ payload = probe_in_process()+ if "--json" in argv:+ print(json.dumps(payload))+ elif payload and payload["devices"]:+ for row in payload["devices"]:+ print(f"GPU {row['index']}: {row['name']} (compute {row['compute_cap']})")+ return 0 if payload and payload["devices"] else 1+++if __name__ == "__main__":+ sys.exit(main(sys.argv[1:]))diff --git a/studio/setup.sh b/studio/setup.shindex 87d7e4a0647..a8cb8d54b1c 100755--- a/studio/setup.sh+++ b/studio/setup.sh@@ -655,6 +655,11 @@ _setup_has_physical_nvidia_gpu() {[ -n "$(ls -A /proc/driver/nvidia/gpus 2>/dev/null)" ]; thenreturn 0fi+ # Last: NVML / the CUDA driver API, which ship with the driver and not with nvidia-smi.+ if [ "${UNSLOTH_NVIDIA_LIBRARY_PROBE:-1}" != "0" ] && [ -f "$SCRIPT_DIR/nvidia_probe.py" ] \+ && command -v python3 >/dev/null 2>&1; then+ _setup_run_smi python3 -I "$SCRIPT_DIR/nvidia_probe.py" >/dev/null 2>&1 && return 0+ fireturn 1}diff --git a/tests/conftest.py b/tests/conftest.pyindex acbb4224aae..ccfb087f864 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -49,6 +49,9 @@ import typesimport pytest+# A test that hides nvidia-smi to fake a CPU host must not find the real GPUs through NVML.+os.environ.setdefault("UNSLOTH_NVIDIA_LIBRARY_PROBE", "0")+@pytest.fixture(autouse = True)def _contain_installer_venv_root(tmp_path_factory, monkeypatch):diff --git a/tests/studio/install/test_nvidia_library_probe.py b/tests/studio/install/test_nvidia_library_probe.pynew file mode 100644index 00000000000..dc5b937a3d1--- /dev/null+++ b/tests/studio/install/test_nvidia_library_probe.py@@ -0,0 +1,474 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""The installers read the NVIDIA inventory from the driver's libraries when nvidia-smi cannot answer.++Measured on a 8x B200 host (driver 590.48.01, CUDA 13.1) with a stub nvidia-smi that exits 1:+main resolved no prebuilt at all ("runnable by this driver=none", a source build or the CPU)+and picked the cu126 torch index; with the probe it resolves the cuda13 bundle and cu130.+"""++from __future__ import annotations++import importlib.util+import json+import os+import shutil+import subprocess+import sys+from pathlib import Path++import pytest+++PACKAGE_ROOT = Path(__file__).resolve().parents[3]+STUDIO = PACKAGE_ROOT / "studio"+++def _load(name, filename):+ spec = importlib.util.spec_from_file_location(name, STUDIO / filename)+ module = importlib.util.module_from_spec(spec)+ sys.modules[name] = module+ spec.loader.exec_module(module)+ return module+++PROBE = _load("studio_nvidia_probe", "nvidia_probe.py")+ILP = _load("studio_install_llama_prebuilt", "install_llama_prebuilt.py")+IPS = _load("studio_install_python_stack", "install_python_stack.py")+++def _inventory(+ source = "nvml",+ cuda = (12, 8),+ caps = ("8.9",),+ uuids = None,+):+ devices = [+ {+ "index": str(i),+ "uuid": (uuids or [f"GPU-{i:04d}" for i in range(len(caps))])[i],+ "name": "NVIDIA test",+ "compute_cap": cap,+ }+ for i, cap in enumerate(caps)+ ]+ return PROBE.NvidiaLibraryInventory(+ source = source, cuda_driver_version = cuda, driver_version = "570.1", devices = devices+ )+++# ── the probe module ──+++class TestProbeModule:+ def test_the_payload_round_trips(self):+ payload = {+ "source": "nvml",+ "cuda_driver_version": [13, 1],+ "driver_version": "590.48.01",+ "devices": [{"index": "0", "uuid": "GPU-x", "name": "B200", "compute_cap": "10.0"}],+ }+ inv = PROBE._from_payload(payload)+ assert inv.cuda_driver_version == (13, 1)+ assert inv.devices == payload["devices"]+ assert PROBE._from_payload(None) is None+ assert PROBE._from_payload({"source": "other"}) is None++ def test_cuda_packs_as_major_thousand_minor_ten(self):+ assert PROBE._split_cuda_version(13010) == (13, 1)+ assert PROBE._split_cuda_version(12080) == (12, 8)+ assert PROBE._split_cuda_version(0) is None++ @pytest.mark.parametrize(+ ("driver", "cuda"),+ [+ ("590.48.01", (13, 0)),+ ("580.65.06", (13, 0)),+ ("575.57.08", (12, 8)),+ ("570.26", (12, 8)),+ ("560.35.03", (12, 6)),+ ("550.54.14", (12, 4)),+ ("535.104.05", (12, 2)),+ ("525.60.13", (12, 0)),+ ("470.182.03", (11, 0)),+ ("440.33", None),+ ("", None),+ ("garbage", None),+ ],+ )+ def test_the_driver_release_bounds_the_cuda_version(self, driver, cuda):+ # NVIDIA's minor-version-compatibility table: CUDA 13.x needs R580+, 12.x R525+, 11.x R450+.+ assert PROBE.cuda_version_for_driver(driver) == cuda++ def test_the_proc_version_line_is_read(self, tmp_path):+ path = tmp_path / "version"+ path.write_text(+ "NVRM version: NVIDIA UNIX Open Kernel Module for x86_64 590.48.01 Release Build\n"+ "GCC version: gcc version 13.3.0\n",+ encoding = "utf-8",+ )+ assert PROBE.proc_driver_version(str(path)) == "590.48.01"+ assert PROBE.proc_driver_version(str(tmp_path / "missing")) == ""++ def test_probe_runs_the_module_in_a_child_with_a_deadline(self, monkeypatch):+ seen = {}++ def fake_run(cmd, **kwargs):+ seen["cmd"] = cmd+ seen["timeout"] = kwargs.get("timeout")+ return subprocess.CompletedProcess(+ cmd,+ 0,+ stdout = json.dumps(+ {+ "source": "cuda",+ "cuda_driver_version": [12, 4],+ "driver_version": "",+ "devices": [],+ }+ ),+ stderr = "",+ )++ monkeypatch.setattr(PROBE.subprocess, "run", fake_run)+ monkeypatch.setattr(PROBE.sys, "platform", "linux")+ monkeypatch.delenv("UNSLOTH_NVIDIA_LIBRARY_PROBE", raising = False)+ inv = PROBE.probe(timeout = 7)+ assert seen["cmd"][0] == sys.executable and seen["cmd"][-1] == "--json"+ assert "-I" in seen["cmd"]+ assert seen["timeout"] == 7+ assert inv.source == "cuda" and inv.cuda_driver_version == (12, 4)++ def test_a_hung_or_broken_child_is_none(self, monkeypatch):+ def hang(cmd, **kwargs):+ raise subprocess.TimeoutExpired(cmd, kwargs.get("timeout"))++ monkeypatch.setattr(PROBE.subprocess, "run", hang)+ monkeypatch.setattr(PROBE.sys, "platform", "linux")+ monkeypatch.delenv("UNSLOTH_NVIDIA_LIBRARY_PROBE", raising = False)+ assert PROBE.probe() is None+ monkeypatch.setattr(+ PROBE.subprocess,+ "run",+ lambda cmd, **k: subprocess.CompletedProcess(cmd, 0, stdout = "not json", stderr = ""),+ )+ assert PROBE.probe() is None++ def test_macos_never_probes(self, monkeypatch):+ monkeypatch.setattr(PROBE.sys, "platform", "darwin")+ monkeypatch.setattr(PROBE.subprocess, "run", lambda *a, **k: pytest.fail("ran"))+ assert PROBE.probe() is None++ def test_the_switch_turns_it_off(self, monkeypatch):+ # The suites set it, so a test faking a CPU host cannot find the real GPUs.+ monkeypatch.setattr(PROBE.sys, "platform", "linux")+ monkeypatch.setattr(PROBE.subprocess, "run", lambda *a, **k: pytest.fail("ran"))+ monkeypatch.setenv("UNSLOTH_NVIDIA_LIBRARY_PROBE", "0")+ assert PROBE.probe() is None++ def test_the_cli_exits_by_gpu_presence(self, monkeypatch, capsys):+ monkeypatch.setattr(PROBE, "probe_in_process", lambda: None)+ assert PROBE.main(["--json"]) == 1+ assert capsys.readouterr().out.strip() == "null"+ monkeypatch.setattr(+ PROBE,+ "probe_in_process",+ lambda: {+ "source": "nvml",+ "cuda_driver_version": [12, 8],+ "driver_version": "570",+ "devices": [{"index": "0", "uuid": "u", "name": "RTX", "compute_cap": "8.9"}],+ },+ )+ assert PROBE.main([]) == 0+ assert "GPU 0: RTX (compute 8.9)" in capsys.readouterr().out++ @pytest.mark.skipif(+ sys.platform == "darwin" or not shutil.which("nvidia-smi"),+ reason = "needs a real NVIDIA host",+ )+ def test_on_a_real_host_the_library_agrees_with_nvidia_smi(self, monkeypatch):+ monkeypatch.delenv("UNSLOTH_NVIDIA_LIBRARY_PROBE", raising = False)+ listing = subprocess.run(["nvidia-smi", "-L"], capture_output = True, text = True, timeout = 60)+ if listing.returncode != 0 or "GPU " not in listing.stdout:+ pytest.skip("nvidia-smi lists no GPU here")+ inv = PROBE.probe()+ assert inv is not None and inv.source == "nvml"+ assert len(inv.devices) == sum(+ 1 for line in listing.stdout.splitlines() if line.startswith("GPU ")+ )+ assert inv.cuda_driver_version is not None and inv.cuda_driver_version[0] >= 11+++# ── detect_host ──+++_HOST_TOOLS = {"nvidia-smi", "rocminfo", "amd-smi", "rocm-smi", "hipinfo", "vulkaninfo", "nvcc"}+++def _hide_the_real_host(monkeypatch, *, nvidia_smi):+ """A Linux x86_64 host with no ROCm and no DRM vendors; nvidia-smi is `nvidia_smi`."""+ monkeypatch.setattr(ILP.platform, "system", lambda: "Linux")+ monkeypatch.setattr(ILP.platform, "machine", lambda: "x86_64")+ which = ILP.shutil.which+ monkeypatch.setattr(+ ILP.shutil,+ "which",+ lambda name, *a, **k: (nvidia_smi if name == "nvidia-smi" else None)+ if name in _HOST_TOOLS+ else which(name, *a, **k),+ )+ isdir = ILP.os.path.isdir+ monkeypatch.setattr(ILP.os.path, "isdir", lambda p: False if "nvidia" in str(p) else isdir(p))+ exists = ILP.os.path.exists+ monkeypatch.setattr(+ ILP.os.path,+ "exists",+ lambda p: False if ("rocm" in str(p) or "kfd" in str(p)) else exists(p),+ )+ monkeypatch.setattr(ILP.os, "access", lambda p, mode, *a, **k: False)+ monkeypatch.setattr(ILP.glob, "glob", lambda *a, **k: [])+++def _failing_smi(monkeypatch, *, exit_code = 1):+ def run_capture(command, **kwargs):+ if command and "nvidia-smi" in str(command[0]):+ return subprocess.CompletedProcess(command, exit_code, stdout = "", stderr = "failed")+ return subprocess.CompletedProcess(command, 1, stdout = "", stderr = "")++ monkeypatch.setattr(ILP, "run_capture", run_capture)+++class TestDetectHostFallsBackToTheLibraries:+ def test_a_failing_nvidia_smi_no_longer_reads_as_no_gpu(self, monkeypatch):+ _hide_the_real_host(monkeypatch, nvidia_smi = "/usr/bin/nvidia-smi")+ _failing_smi(monkeypatch)+ monkeypatch.setattr(+ ILP, "nvidia_library_inventory", lambda: _inventory(caps = ("8.9", "8.6"))+ )+ monkeypatch.delenv("CUDA_VISIBLE_DEVICES", raising = False)+ host = ILP.detect_host()+ assert host.has_physical_nvidia and host.has_usable_nvidia+ assert host.driver_cuda_version == (12, 8)+ assert host.compute_caps == ["89", "86"]+ assert host.physical_compute_caps == ["89", "86"]++ def test_an_absent_nvidia_smi_is_the_same(self, monkeypatch):+ _hide_the_real_host(monkeypatch, nvidia_smi = None)+ monkeypatch.setattr(ILP, "nvidia_library_inventory", lambda: _inventory())+ monkeypatch.delenv("CUDA_VISIBLE_DEVICES", raising = False)+ host = ILP.detect_host()+ assert host.has_usable_nvidia and host.driver_cuda_version == (12, 8)++ def test_nvml_rows_are_masked_like_nvidia_smi_rows(self, monkeypatch):+ # NVML is the physical inventory; an emptied mask leaves the GPU physical, not usable.+ _hide_the_real_host(monkeypatch, nvidia_smi = None)+ monkeypatch.setattr(+ ILP, "nvidia_library_inventory", lambda: _inventory(caps = ("8.9", "6.1"))+ )+ monkeypatch.setenv("CUDA_VISIBLE_DEVICES", "")+ host = ILP.detect_host()+ assert host.has_physical_nvidia and not host.has_usable_nvidia+ assert host.compute_caps == [] and host.physical_compute_caps == ["89", "61"]+ monkeypatch.setenv("CUDA_VISIBLE_DEVICES", "1")+ host = ILP.detect_host()+ assert host.has_usable_nvidia and host.compute_caps == ["61"]++ def test_a_mask_nvml_rows_cannot_name_keeps_the_gpu_usable(self, monkeypatch):+ # A MIG UUID names a slice, not the parent GPU NVML lists: usable, as with nvidia-smi.+ _hide_the_real_host(monkeypatch, nvidia_smi = None)+ monkeypatch.setattr(ILP, "nvidia_library_inventory", lambda: _inventory(caps = ("9.0",)))+ monkeypatch.setenv("CUDA_VISIBLE_DEVICES", "MIG-4b3c2a1d-0000-1111-2222-333344445555")+ host = ILP.detect_host()+ assert host.has_physical_nvidia and host.has_usable_nvidia+ assert host.compute_caps == [] and host.physical_compute_caps == ["90"]+ # An explicit UUID that matches nothing stays unusable.+ monkeypatch.setenv("CUDA_VISIBLE_DEVICES", "GPU-00000000-0000-0000-0000-000000000000")+ assert not ILP.detect_host().has_usable_nvidia++ def test_the_cuda_driver_api_rows_are_already_masked(self, monkeypatch):+ _hide_the_real_host(monkeypatch, nvidia_smi = None)+ monkeypatch.setattr(+ ILP, "nvidia_library_inventory", lambda: _inventory(source = "cuda", caps = ("7.5",))+ )+ monkeypatch.setenv("CUDA_VISIBLE_DEVICES", "0")+ host = ILP.detect_host()+ assert host.has_usable_nvidia and host.compute_caps == ["75"]++ def test_a_working_nvidia_smi_is_not_second_guessed(self, monkeypatch):+ _hide_the_real_host(monkeypatch, nvidia_smi = "/usr/bin/nvidia-smi")++ def run_capture(command, **kwargs):+ args = command[1:]+ if args == ["-L"]:+ out = "GPU 0: NVIDIA RTX (UUID: GPU-abc)\n"+ elif not args:+ out = "NVIDIA-SMI 570 Driver Version: 570.1 CUDA Version: 12.8\n"+ else:+ out = "0, GPU-abc, 8.9\n"+ return subprocess.CompletedProcess(command, 0, stdout = out, stderr = "")++ monkeypatch.setattr(ILP, "run_capture", run_capture)+ monkeypatch.setattr(ILP, "nvidia_library_inventory", lambda: pytest.fail("probed"))+ monkeypatch.delenv("CUDA_VISIBLE_DEVICES", raising = False)+ host = ILP.detect_host()+ assert host.driver_cuda_version == (12, 8) and host.compute_caps == ["89"]++ def test_the_kernel_module_release_bounds_the_driver_version(self, monkeypatch):+ # nvidia-smi and the libraries both failed; /proc/driver/nvidia/gpus says NVIDIA.+ _hide_the_real_host(monkeypatch, nvidia_smi = None)+ isdir = ILP.os.path.isdir+ monkeypatch.setattr(+ ILP.os.path,+ "isdir",+ lambda p: True+ if str(p) == "/proc/driver/nvidia/gpus"+ else (False if "nvidia" in str(p) else isdir(p)),+ )+ monkeypatch.setattr(+ ILP.os, "listdir", lambda p: ["0000:01:00.0"] if "nvidia" in str(p) else []+ )+ monkeypatch.setattr(ILP, "nvidia_library_inventory", lambda: None)+ monkeypatch.setenv("UNSLOTH_NVIDIA_LIBRARY_PROBE", "1")+ monkeypatch.setattr(ILP._nvidia_probe, "proc_driver_version", lambda: "580.65.06")+ monkeypatch.delenv("CUDA_VISIBLE_DEVICES", raising = False)+ host = ILP.detect_host()+ assert host.has_physical_nvidia and host.driver_cuda_version == (13, 0)++ def test_a_cpu_host_stays_cpu(self, monkeypatch):+ _hide_the_real_host(monkeypatch, nvidia_smi = None)+ monkeypatch.setattr(ILP, "nvidia_library_inventory", lambda: None)+ monkeypatch.setattr(ILP, "proc_driver_version", lambda: "")+ host = ILP.detect_host()+ assert not host.has_physical_nvidia and host.driver_cuda_version is None+++# ── install_python_stack ──+++class TestTorchIndexFallsBackToTheLibraries:+ def _no_smi(self, monkeypatch):+ monkeypatch.delenv("UNSLOTH_TORCH_INDEX_URL", raising = False)+ monkeypatch.delenv("UNSLOTH_TORCH_INDEX_FAMILY", raising = False)+ monkeypatch.setattr(IPS, "_nvidia_smi_usable_candidates", lambda: [])+ monkeypatch.setattr(IPS.platform, "machine", lambda: "x86_64")++ def test_the_library_version_picks_the_family(self, monkeypatch):+ self._no_smi(monkeypatch)+ monkeypatch.setattr(+ IPS, "_nvidia_library_inventory", lambda: _inventory(cuda = (13, 1), caps = ("10.0",))+ )+ assert IPS._detect_cuda_torch_index_url().endswith("/cu130")+ monkeypatch.setattr(+ IPS, "_nvidia_library_inventory", lambda: _inventory(cuda = (12, 6), caps = ("8.6",))+ )+ assert IPS._detect_cuda_torch_index_url().endswith("/cu126")++ def test_the_pre_turing_cap_reads_the_library_sms(self, monkeypatch):+ self._no_smi(monkeypatch)+ monkeypatch.setattr(+ IPS, "_nvidia_library_inventory", lambda: _inventory(cuda = (13, 0), caps = ("6.1",))+ )+ assert IPS._detect_cuda_torch_index_url().endswith("/cu126")++ def test_without_compute_caps_the_default_stays(self, monkeypatch):+ # A driver version alone cannot rule out Maxwell, Pascal or Volta, which cu128+ drop.+ self._no_smi(monkeypatch)+ monkeypatch.setattr(IPS.sys, "platform", "linux")+ monkeypatch.setenv("UNSLOTH_NVIDIA_LIBRARY_PROBE", "1")+ monkeypatch.setattr(IPS._nvidia_probe, "proc_driver_version", lambda: "580.65.06")+ capless = PROBE.NvidiaLibraryInventory("cuda", (13, 0), "", [{"compute_cap": ""}])+ for inventory in (None, capless):+ monkeypatch.setattr(IPS, "_nvidia_library_inventory", lambda inv = inventory: inv)+ assert IPS._detect_cuda_torch_index_url().endswith("/cu126")++ def test_nothing_at_all_still_defaults_to_cu126(self, monkeypatch):+ self._no_smi(monkeypatch)+ monkeypatch.setattr(IPS, "_nvidia_library_inventory", lambda: None)+ monkeypatch.setattr(IPS._nvidia_probe, "proc_driver_version", lambda: "")+ assert IPS._detect_cuda_torch_index_url().endswith("/cu126")++ def test_presence_falls_back_to_the_libraries(self, monkeypatch):+ monkeypatch.delenv("CUDA_VISIBLE_DEVICES", raising = False)+ monkeypatch.setattr(IPS, "_nvidia_smi_candidates", lambda: [])+ monkeypatch.setattr(IPS.os.path, "isdir", lambda p: False)+ monkeypatch.setattr(IPS, "_nvidia_library_inventory", lambda: _inventory())+ assert IPS._has_usable_nvidia_gpu() is True+ monkeypatch.setattr(IPS, "_nvidia_library_inventory", lambda: None)+ assert IPS._has_usable_nvidia_gpu() is False++ def test_presence_applies_an_explicit_mask_to_the_nvml_rows(self, monkeypatch):+ monkeypatch.setattr(IPS, "_nvidia_smi_candidates", lambda: [])+ monkeypatch.setattr(IPS.os.path, "isdir", lambda p: False)+ monkeypatch.setattr(+ IPS, "_nvidia_library_inventory", lambda: _inventory(caps = ("8.9", "6.1"))+ )+ for mask, usable in (+ ("1", True),+ ("gpu-0001", True),+ ("5", False),+ ("GPU-ffff", False),+ ("MIG-4b3c2a1d-0000-1111-2222-333344445555", True),+ ):+ monkeypatch.setenv("CUDA_VISIBLE_DEVICES", mask)+ assert IPS._has_usable_nvidia_gpu() is usable, mask+ # The CUDA driver rows are already masked, so a miss there is not second-guessed.+ monkeypatch.setenv("CUDA_VISIBLE_DEVICES", "5")+ monkeypatch.setattr(IPS, "_nvidia_library_inventory", lambda: _inventory(source = "cuda"))+ assert IPS._has_usable_nvidia_gpu() is True+++# ── setup.sh ──+++SETUP_TEXT = (STUDIO / "setup.sh").read_text(encoding = "utf-8")+++def test_setup_sh_asks_the_library_last():+ start = SETUP_TEXT.index("_setup_has_physical_nvidia_gpu() {")+ body = SETUP_TEXT[start : SETUP_TEXT.index("\n}\n", start)]+ assert body.index("/proc/driver/nvidia/gpus") < body.index("nvidia_probe.py")+ assert '_setup_run_smi python3 -I "$SCRIPT_DIR/nvidia_probe.py"' in body+++ shutil.which("bash") is None or sys.platform == "win32",+ reason = "a POSIX bash is required (Windows resolves bash to WSL)",+)+def test_setup_sh_probe_hook_runs(tmp_path):+ start = SETUP_TEXT.index("_setup_run_smi() {")+ runner = SETUP_TEXT[start : SETUP_TEXT.index("\n}\n", start) + 3]+ start = SETUP_TEXT.index("_setup_has_physical_nvidia_gpu() {")+ # The real /proc would answer for this host; point the fallback at an empty dir.+ fn = SETUP_TEXT[start : SETUP_TEXT.index("\n}\n", start) + 3].replace(+ "/proc/driver/nvidia/gpus", str(tmp_path / "nogpus")+ )+ script_dir = tmp_path / "studio"+ script_dir.mkdir()+ (script_dir / "nvidia_probe.py").write_text("import sys; sys.exit(int(sys.argv[-1] != 'x'))\n")+ stub_bin = tmp_path / "bin"+ stub_bin.mkdir()+ (stub_bin / "python3").write_text('#!/bin/sh\nexit "$PROBE_RC"\n')+ (stub_bin / "python3").chmod(0o755)+ (stub_bin / "nvidia-smi").write_text("#!/bin/sh\nexit 1\n")+ (stub_bin / "nvidia-smi").chmod(0o755)+ harness = (+ runner+ + fn+ + '\nSCRIPT_DIR="$1"\nif _setup_has_physical_nvidia_gpu; then echo GPU; else echo NONE; fi\n'+ )+ for rc, expect in (("0", "GPU"), ("1", "NONE")):+ result = subprocess.run(+ ["bash", "-c", harness, "h", str(script_dir)],+ env = {+ **os.environ,+ "PATH": f"{stub_bin}:{os.environ['PATH']}",+ "PROBE_RC": rc,+ "UNSLOTH_NVIDIA_LIBRARY_PROBE": "1",+ },+ capture_output = True,+ text = True,+ timeout = 60,+ )+ assert result.stdout.strip() == expect, result.stderrdiff --git a/tests/test_installer_interactive_prompts.py b/tests/test_installer_interactive_prompts.pyindex 107bdf0500b..56b6b322304 100644--- a/tests/test_installer_interactive_prompts.py+++ b/tests/test_installer_interactive_prompts.py@@ -50,6 +50,7 @@ SCANNED_SCRIPTS = ENTRY_POINTS + ("studio/install_python_stack.py","studio/install_sd_cpp_prebuilt.py","studio/install_whisper_prebuilt.py",+ "studio/nvidia_probe.py",# install_python_stack runs this one with sys.executable."studio/backend/requirements/single-env/patch_metadata.py",)