Skip to content

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.

Studio: cache and coalesce nvidia-smi reads in the backend (#11995)

Daniel Han0d2905f182a5
diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.py
index 7d7c90b2673..2057c25b7db 100644
--- a/studio/backend/core/inference/diffusion.py
+++ b/studio/backend/core/inference/diffusion.py
@@ -38,6 +38,7 @@ from core._torchao_stub import (
)
from hub.utils.hf_errors import modelscope_missing
from loggers import get_logger
+from utils.gpu_memory_events import invalidates_gpu_memory as _invalidates_gpu_memory
from utils.account_context import account_thread, current_account_id
from utils.hardware import clear_gpu_cache
@@ -4929,6 +4930,7 @@ class DiffusionBackend:
return DiffusionBackend._union_over_cached_revs(base, _params, staged_dir) * 2
+ @_invalidates_gpu_memory("diffusion load")
@_account_owned_load
def load_pipeline(
self,
@@ -9150,6 +9152,7 @@ class DiffusionBackend:
cancel.set()
return True
+ @_invalidates_gpu_memory("diffusion unload")
def unload(self, *, expected_account: Optional[str] = None) -> dict[str, Any]:
# fenced, and the try that owns it, start BEFORE the counter moves: a leaked _unload_waiters
# would make _wait_for_pending_unloads block every later load for the life of the process,
diff --git a/studio/backend/core/inference/inference.py b/studio/backend/core/inference/inference.py
index 913d38d0efb..2efc064d4ea 100644
--- a/studio/backend/core/inference/inference.py
+++ b/studio/backend/core/inference/inference.py
@@ -66,6 +66,7 @@ from core.inference.mlx_inference import _mlx_stop_cut, _mlx_stop_sequences
from io import StringIO
import structlog
from loggers import get_logger
+from utils.gpu_memory_events import invalidates_gpu_memory as _invalidates_gpu_memory
logger = get_logger(__name__)
@@ -636,6 +637,7 @@ class InferenceBackend:
repaired,
)
+ @_invalidates_gpu_memory("transformers load")
def load_model(
self,
config: ModelConfig,
@@ -965,6 +967,7 @@ class InferenceBackend:
raise Exception(error_msg)
+ @_invalidates_gpu_memory("transformers unload")
def unload_model(self, model_name: str) -> bool:
"""Remove a model from the registry and clear GPU memory."""
if model_name in self.models:
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.py
index ddc125afdbd..02e4f9a800e 100644
--- a/studio/backend/core/inference/llama_cpp.py
+++ b/studio/backend/core/inference/llama_cpp.py
@@ -21,6 +21,8 @@ import os
import re
import struct
from loggers import get_logger
+from utils.gpu_memory_events import invalidate_gpu_memory as _invalidate_gpu_memory
+from utils.gpu_memory_events import invalidates_gpu_memory as _invalidates_gpu_memory
import shutil
import signal
import socket
@@ -11300,8 +11302,11 @@ class LlamaCppBackend:
the GPU columns are the leading run of GPU<n> header labels and only GPU<n>
rows are read."""
try:
- result = subprocess.run(
+ from utils.hardware import gpu_query
+
+ result = gpu_query.run_nvidia_smi(
["nvidia-smi", "topo", "-m"],
+ cache = False,
capture_output = True,
text = True,
encoding = "utf-8",
@@ -11965,7 +11970,9 @@ class LlamaCppBackend:
"""Physical id -> SM (90 for sm_90) via nvidia-smi, honoring
CUDA_VISIBLE_DEVICES; {} when unknown. Never raises."""
try:
- result = subprocess.run(
+ from utils.hardware import gpu_query
+
+ result = gpu_query.run_nvidia_smi(
["nvidia-smi", "--query-gpu=index,compute_cap", "--format=csv,noheader"],
capture_output = True,
text = True,
@@ -13329,7 +13336,10 @@ class LlamaCppBackend:
return LlamaCppBackend._get_gpu_free_memory_vulkan(binary)
# ── NVIDIA via nvidia-smi ────────────────────────────────────
try:
- result = subprocess.run(
+ from utils.hardware import gpu_query
+
+ # Placement / fit: never a cached reading. A hung CLI raises so the MIG-aware NVML branch runs.
+ result = gpu_query.run_nvidia_smi(
[
"nvidia-smi",
"--query-gpu=index,memory.free,memory.total",
@@ -15270,7 +15280,11 @@ class LlamaCppBackend:
if time.monotonic() >= deadline:
return None
try:
- return LlamaCppBackend._get_gpu_free_memory()
+ from utils.hardware import gpu_query
+
+ # Consecutive samples are compared: a cached one would read as settled.
+ with gpu_query.fresh_reads():
+ return LlamaCppBackend._get_gpu_free_memory()
except Exception:
return None
@@ -18344,6 +18358,7 @@ class LlamaCppBackend:
**_child_popen_kwargs(),
)
self._process = _spawned
+ _invalidate_gpu_memory("llama-server spawned")
# macOS has no parent-death signal, so only this record reaps a runner
# holding the GPU. Under the lock: adopting after the sweep re-adds a
# pid it just forgot.
@@ -22707,6 +22722,7 @@ class LlamaCppBackend:
**_child_popen_kwargs(),
)
self._process = _spawned
+ _invalidate_gpu_memory("llama-server spawned")
# Cross-session backstop for when parent-death cleanup did not run.
# Under the lock: see _spawn_and_wait.
self._record_server_pid(_spawned.pid)
@@ -22752,6 +22768,7 @@ class LlamaCppBackend:
# finished load could blank the marker of a queued one that had published.
self._memory_pending_launch = None
+ @_invalidates_gpu_memory("llama.cpp load")
@_with_gguf_load_marker
def load_model(
self,
@@ -29176,6 +29193,7 @@ class LlamaCppBackend:
**_child_popen_kwargs(),
)
self._process = _spawned
+ _invalidate_gpu_memory("llama-server spawned")
# Inside the lock: written after a sweep reaped the child,
# _pid_start_identity yields no start time, and the bare pid
# left behind is one a later launch kills blind.
@@ -31751,6 +31769,7 @@ class LlamaCppBackend:
avoid restarting a load the user just cancelled."""
return self._cancel_event.is_set()
+ @_invalidates_gpu_memory("llama.cpp unload")
def unload_model(self) -> bool:
"""Terminate the subprocess and cancel any in-flight download."""
self._cancel_event.set()
@@ -32104,6 +32123,7 @@ class LlamaCppBackend:
return is_process_shutting_down()
+ @_invalidates_gpu_memory("llama.cpp stop")
def _kill_process(self, *, teardown: bool = False):
"""Terminate the subprocess if running.
diff --git a/studio/backend/core/inference/native_audio.py b/studio/backend/core/inference/native_audio.py
index f324a877a1b..031f4166324 100644
--- a/studio/backend/core/inference/native_audio.py
+++ b/studio/backend/core/inference/native_audio.py
@@ -25,6 +25,7 @@ remote-code security gates have run.
from __future__ import annotations
import gc
+from utils.gpu_memory_events import invalidates_gpu_memory as _invalidates_gpu_memory
import io
import json
import logging
@@ -901,6 +902,7 @@ class NativeAudioBackend:
torch.backends.cuda.enable_math_sdp(True)
torch.backends.cuda.enable_cudnn_sdp(False)
+ @_invalidates_gpu_memory("audio load")
def load_model(
self,
config,
@@ -1443,6 +1445,7 @@ class NativeAudioBackend:
cancel_hook.remove()
return audio, entry["sample_rate"]
+ @_invalidates_gpu_memory("audio unload")
def unload_model(self, model_name: str) -> bool:
entry = self.models.pop(model_name, None)
if entry is not None:
diff --git a/studio/backend/core/inference/orchestrator.py b/studio/backend/core/inference/orchestrator.py
index 2424e5b6a79..2ec80c61d12 100644
--- a/studio/backend/core/inference/orchestrator.py
+++ b/studio/backend/core/inference/orchestrator.py
@@ -12,6 +12,7 @@ import base64
import os
import signal
from loggers import get_logger
+from utils.gpu_memory_events import invalidates_gpu_memory as _invalidates_gpu_memory
import multiprocessing as mp
import queue
import re
@@ -724,11 +725,13 @@ class InferenceOrchestrator:
return None
request_id = str(uuid.uuid4())
with self._send_order_lock:
- from utils.hardware import get_visible_gpu_utilization
+ from utils.hardware import get_visible_gpu_utilization, gpu_query
live_free: dict[int, float] = {}
total_by_index: dict[int, float] = {}
- for device in get_visible_gpu_utilization().get("devices", []):
+ with gpu_query.fresh_reads():
+ _live_devices = get_visible_gpu_utilization().get("devices", [])
+ for device in _live_devices:
try:
index = int(device["index"])
total = float(device["vram_total_gb"])
@@ -862,8 +865,13 @@ class InferenceOrchestrator:
if time.monotonic() >= deadline:
return None
try:
+ from utils.hardware import gpu_query
+
result: dict[int, int] = {}
- for device in get_visible_gpu_utilization().get("devices", []):
+ # Consecutive samples are compared: a cached one would read as settled.
+ with gpu_query.fresh_reads():
+ devices = get_visible_gpu_utilization().get("devices", [])
+ for device in devices:
index = int(device["index"])
total = float(device["vram_total_gb"])
used = float(device["vram_used_gb"])
@@ -1838,6 +1846,7 @@ class InferenceOrchestrator:
# get unloaded by the swap.
load_generation: int = 0
+ @_invalidates_gpu_memory("inference load")
def load_model(
self,
config,
@@ -2219,6 +2228,7 @@ class InferenceOrchestrator:
from core.inference import stt_registry
return stt_registry.resident()
+ @_invalidates_gpu_memory("inference unload")
def unload_model(self, model_name: str) -> bool:
# active_model_name can differ in case from the client's raw /unload name (the load path canonicalizes
# casing). Match case-insensitively and use the canonical spelling so the guard, unload command, and cleanup
diff --git a/studio/backend/core/inference/sd_cpp_backend.py b/studio/backend/core/inference/sd_cpp_backend.py
index fcab6fc5ec5..ff734f4299b 100644
--- a/studio/backend/core/inference/sd_cpp_backend.py
+++ b/studio/backend/core/inference/sd_cpp_backend.py
@@ -85,6 +85,7 @@ from core.inference.sd_cpp_engine import (
)
from core.inference.sd_cpp_server import SdCppServer
from loggers import get_logger
+from utils.gpu_memory_events import invalidates_gpu_memory as _invalidates_gpu_memory
from utils.account_context import account_thread, current_account_id
from utils.subprocess_compat import windows_hidden_subprocess_kwargs
@@ -2525,6 +2526,7 @@ class SdCppDiffusionBackend:
).start()
return self.status()
+ @_invalidates_gpu_memory("sd.cpp load")
def _run_load(
self,
*,
@@ -3997,6 +3999,7 @@ class SdCppDiffusionBackend:
# ── Unload / status ──────────────────────────────────────────────────────
+ @_invalidates_gpu_memory("sd.cpp unload")
def unload(self, *, expected_account: Optional[str] = None) -> dict[str, Any]:
with self._lock:
if expected_account is not None:
diff --git a/studio/backend/core/inference/stt_registry.py b/studio/backend/core/inference/stt_registry.py
index e3559ab8717..cdf30396718 100644
--- a/studio/backend/core/inference/stt_registry.py
+++ b/studio/backend/core/inference/stt_registry.py
@@ -16,6 +16,7 @@ import threading
from typing import Any, Optional, Sequence
from loggers import get_logger
+from utils.gpu_memory_events import invalidates_gpu_memory as _invalidates_gpu_memory
logger = get_logger(__name__)
@@ -40,6 +41,7 @@ def sidecar_for(engine: str) -> Any:
return get_stt_sidecar()
+@_invalidates_gpu_memory("stt load")
def load(
model: Optional[str],
engine: str,
@@ -99,6 +101,7 @@ def _model_is_downloaded(engine: str, model: str) -> bool:
return False
+@_invalidates_gpu_memory("stt unload")
def unload(
engines: Optional[Sequence[str]] = None,
*,
diff --git a/studio/backend/core/inference/video.py b/studio/backend/core/inference/video.py
index 2fe21c5b1ff..e8eeacc2c63 100644
--- a/studio/backend/core/inference/video.py
+++ b/studio/backend/core/inference/video.py
@@ -46,6 +46,7 @@ from typing import Any, Optional
from hub.utils.hf_errors import modelscope_missing
from loggers import get_logger
+from utils.gpu_memory_events import invalidates_gpu_memory as _invalidates_gpu_memory
from .diffusion_attention import (
SDPA_MATH_ONLY_MESSAGE,
@@ -4310,6 +4311,7 @@ class VideoBackend:
# ── the load itself ──────────────────────────────────────────────────────
+ @_invalidates_gpu_memory("video load")
def load_pipeline(
self,
repo_id: str,
@@ -7678,6 +7680,7 @@ class VideoBackend:
release_pinned_host_memory()
reclaim_host_memory(logger = logger)
+ @_invalidates_gpu_memory("video unload")
def unload(self, *, expected_account: Optional[str] = None) -> dict[str, Any]:
with self._lock:
if expected_account is not None:
diff --git a/studio/backend/core/rag/embed_llama_server.py b/studio/backend/core/rag/embed_llama_server.py
index b8e7a506b62..c992bd5b82b 100644
--- a/studio/backend/core/rag/embed_llama_server.py
+++ b/studio/backend/core/rag/embed_llama_server.py
@@ -17,6 +17,7 @@ from __future__ import annotations
from core.training.account_jobs import account_path, managed_account
from utils.account_context import account_thread
+from utils.gpu_memory_events import invalidates_gpu_memory as _invalidates_gpu_memory
import atexit
import logging
import os
@@ -903,6 +904,7 @@ class LlamaServerBackend:
except Exception: # noqa: BLE001 - drain thread must never raise
pass
+ @_invalidates_gpu_memory("embedding server start")
def _spawn(self, model_name: str | None = None) -> None:
"""Start the embed server (caller holds the lock). A failed GPU start falls
back to CPU once, unless ``RAG_EMBED_DEVICE`` is the literal ``gpu``."""
@@ -1061,6 +1063,7 @@ class LlamaServerBackend:
self._kill_process()
self._spawn(model_name)
+ @_invalidates_gpu_memory("embedding server stop")
def _kill_process(self) -> None:
proc = self._process
if proc is None:
diff --git a/studio/backend/core/training/diffusion_training_service.py b/studio/backend/core/training/diffusion_training_service.py
index 67f31573edf..5bbb76572c6 100644
--- a/studio/backend/core/training/diffusion_training_service.py
+++ b/studio/backend/core/training/diffusion_training_service.py
@@ -29,6 +29,7 @@ from core.training.account_jobs import (
worker_alive,
)
from utils.account_context import account_thread
+from utils.gpu_memory_events import invalidates_gpu_memory as _invalidates_gpu_memory
import contextlib
import json
import math
@@ -605,6 +606,7 @@ class DiffusionTrainingService:
with self._lock:
self._gpu_admissions = max(0, self._gpu_admissions - 1)
+ @_invalidates_gpu_memory("diffusion training start")
@owned_job()
def start(self, config: dict) -> str:
"""Validate ``config``, spawn the trainer, and start pumping its events.
@@ -689,6 +691,7 @@ class DiffusionTrainingService:
self._pump.start()
return job_id
+ @_invalidates_gpu_memory("diffusion training stop")
@job_control
def stop(self, save: bool = True) -> bool:
"""Request a clean stop: the trainer finishes the current step, then either saves
diff --git a/studio/backend/core/training/training.py b/studio/backend/core/training/training.py
index 405d61b6826..1a0f65a98bb 100644
--- a/studio/backend/core/training/training.py
+++ b/studio/backend/core/training/training.py
@@ -38,6 +38,7 @@ import traceback
from contextlib import contextmanager, nullcontext
from datetime import datetime, timezone
from loggers import get_logger
+from utils.gpu_memory_events import invalidates_gpu_memory as _invalidates_gpu_memory
from dataclasses import dataclass, field, replace
from pathlib import Path
from typing import Optional, Tuple, Any, Callable, Union, TYPE_CHECKING, Literal, Iterator
@@ -1655,6 +1656,7 @@ class TrainingBackend:
del self._start_requests[request_id]
overflow -= 1
+ @_invalidates_gpu_memory("training start")
@owned_job()
def start_training(
self,
@@ -2006,6 +2008,7 @@ class TrainingBackend:
)
return True
+ @_invalidates_gpu_memory("training stop")
@job_control
def stop_training(
self,
diff --git a/studio/backend/main.py b/studio/backend/main.py
index e1b17d5e86e..cb9beba83f5 100644
--- a/studio/backend/main.py
+++ b/studio/backend/main.py
@@ -2174,7 +2174,15 @@ def _get_cached_system_gpu_info(
visibility_info = {"available": False, "devices": []}
try:
- utilization_info = get_visible_gpu_utilization() or {"devices": []}
+ import contextlib
+
+ from utils.hardware import gpu_query
+
+ # Already behind a 10 s cache: no stale-while-revalidate on top.
+ with (
+ contextlib.nullcontext() if refresh_memory else gpu_query.display_reads(max_stale = 0)
+ ):
+ utilization_info = get_visible_gpu_utilization() or {"devices": []}
except Exception as e:
logger.debug(f"Failed to get GPU utilization info: {e}")
utilization_info = {"devices": []}
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index cf94a0941a4..687b0b168aa 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -14172,7 +14172,10 @@ def _native_audio_post_handoff_free_gb() -> Optional[_NativeAudioAvailability]:
reclaimable: dict[int, float] = {}
def _read_live() -> bool:
- utilization = hardware.get_visible_gpu_utilization()
+ from utils.hardware import gpu_query
+
+ with gpu_query.fresh_reads():
+ utilization = hardware.get_visible_gpu_utilization()
live.clear()
for device in utilization.get("devices", []):
try:
@@ -14338,7 +14341,9 @@ def _wait_for_native_audio_gpu_free_gb(
deadline = time.monotonic() + max(max_wait, 0.0)
while True:
try:
- devices = get_visible_gpu_utilization().get("devices", [])
+ from utils.hardware import gpu_query
+ with gpu_query.fresh_reads():
+ devices = get_visible_gpu_utilization().get("devices", [])
for device in devices:
if int(device["index"]) != int(gpu_index):
continue
diff --git a/studio/backend/routes/training.py b/studio/backend/routes/training.py
index 92d25e8ee30..e61e464f0d1 100644
--- a/studio/backend/routes/training.py
+++ b/studio/backend/routes/training.py
@@ -1316,19 +1316,21 @@ async def get_hardware_utilization(current_subject: str = Depends(get_current_su
Polled by the frontend during training.
"""
- from utils.hardware import get_gpu_utilization
+ from utils.hardware import get_gpu_utilization, gpu_query
# Off-loop: the first call blocks on detection while the warm is importing torch.
- return await asyncio.to_thread(get_gpu_utilization)
+ with gpu_query.display_reads():
+ return await asyncio.to_thread(get_gpu_utilization)
@router.get("/hardware/visible")
async def get_visible_hardware_utilization(current_subject: str = Depends(get_current_subject)):
- from utils.hardware import get_visible_gpu_utilization
+ from utils.hardware import get_visible_gpu_utilization, gpu_query
# Off the event loop: the ROCm fallbacks shell out (Windows perf counters, sysfs) and the System view polls this
# route.
- return await asyncio.to_thread(get_visible_gpu_utilization)
+ with gpu_query.display_reads():
+ return await asyncio.to_thread(get_visible_gpu_utilization)
@router.get("/start-requests/{start_request_id}", response_model = TrainingStartRequestStatus)
diff --git a/studio/backend/tests/conftest.py b/studio/backend/tests/conftest.py
index ad270a128cf..f7ff36d4934 100644
--- a/studio/backend/tests/conftest.py
+++ b/studio/backend/tests/conftest.py
@@ -157,6 +157,23 @@ def _contain_installer_venv_root(tmp_path_factory, monkeypatch):
contain_installer_venv_root(monkeypatch, tmp_path_factory)
[email protected](autouse = True)
+def _reset_gpu_query_cache():
+ # Only when already imported: importing utils.hardware would change import-order tests.
+ def _reset():
+ gpu_query = sys.modules.get("utils.hardware.gpu_query")
+ if gpu_query is not None:
+ gpu_query.reset()
+ hw = sys.modules.get("utils.hardware.hardware")
+ if hw is not None and hasattr(hw, "_last_good_visible_info"):
+ with hw._last_good_visible_lock:
+ hw._last_good_visible_info.clear()
+
+ _reset()
+ yield
+ _reset()
+
+
@pytest.fixture(autouse = True)
def _isolate_studio_home(_studio_home_root, monkeypatch):
home = _studio_home_root / f"home-{next(_studio_home_counter)}"
diff --git a/studio/backend/tests/test_gpu_inventory_stale.py b/studio/backend/tests/test_gpu_inventory_stale.py
new file mode 100644
index 00000000000..2e83e34dad1
--- /dev/null
+++ b/studio/backend/tests/test_gpu_inventory_stale.py
@@ -0,0 +1,133 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""A slow or failing GPU probe must not turn a detected GPU into "No GPU detected"."""
+
+from __future__ import annotations
+
+import time
+
+import pytest
+
+import utils.hardware.hardware as hw
+from utils.hardware import nvidia
+
+B200 = {"index": 0, "name": "NVIDIA B200", "memory_total_gb": 178.35}
+
+
[email protected](autouse = True)
+def _cuda_host(monkeypatch):
+ monkeypatch.setattr(hw, "get_device", lambda: hw.DeviceType.CUDA)
+ monkeypatch.setattr(hw, "IS_ROCM", False)
+ monkeypatch.setattr(hw, "get_parent_visible_gpu_ids", lambda: [0])
+ monkeypatch.setattr(
+ hw,
+ "_get_parent_visible_gpu_spec",
+ lambda: {"raw": "0", "numeric_ids": [0], "supports_explicit_gpu_ids": True},
+ )
+ monkeypatch.setattr(hw, "_repair_smi_visible_devices", lambda devices, ids: True)
+ monkeypatch.setenv("CUDA_VISIBLE_DEVICES", "0")
+ monkeypatch.setattr(hw, "_last_good_visible_info", {})
+ monkeypatch.setattr(hw, "_torch_get_device_inventory", lambda idx: [])
+ monkeypatch.setattr(hw, "_torch_get_physical_gpu_count", lambda: None)
+
+
+def _smi(monkeypatch, rows):
+ """rows: a list (nvidia-smi answered), None (timed out / failed) or NVIDIA_SMI_ABSENT."""
+ monkeypatch.setattr(nvidia, "_query_gpu_inventory", lambda caller: rows)
+
+
+def test_failed_probe_after_a_good_read_keeps_the_gpu(monkeypatch):
+ _smi(monkeypatch, [dict(B200)])
+ good = hw.get_backend_visible_gpu_info()
+ assert good["available"] and [d["name"] for d in good["devices"]] == ["NVIDIA B200"]
+ assert "stale" not in good
+
+ _smi(monkeypatch, None) # timeout / non-zero exit
+ kept = hw.get_backend_visible_gpu_info()
+ assert kept["available"] is True and kept["stale"] is True
+ assert [d["name"] for d in kept["devices"]] == ["NVIDIA B200"]
+ assert kept["devices"][0]["memory_total_gb"] == 178.35
+ for key in ("probe_failed", "smi_absent", "_confirmed_empty"):
+ assert key not in kept
+
+ _smi(monkeypatch, [dict(B200)]) # answers again: fresh, no longer stale
+ assert "stale" not in hw.get_backend_visible_gpu_info()
+
+
+def test_failed_probe_with_no_prior_read_claims_no_gpu(monkeypatch):
+ _smi(monkeypatch, None)
+ info = hw.get_backend_visible_gpu_info()
+ assert info["available"] is False and info["devices"] == [] and "stale" not in info
+
+
+def test_nvidia_smi_answering_zero_rows_reports_none(monkeypatch):
+ _smi(monkeypatch, [dict(B200)])
+ assert hw.get_backend_visible_gpu_info()["available"]
+ _smi(monkeypatch, []) # the driver answered: no card under this mask
+ info = hw.get_backend_visible_gpu_info()
+ assert info["available"] is False and info["devices"] == [] and "stale" not in info
+ _smi(monkeypatch, None) # and a later failure does not resurrect it
+ assert hw.get_backend_visible_gpu_info()["available"] is False
+
+
+ "mask",
+ ["CUDA_VISIBLE_DEVICES", "HIP_VISIBLE_DEVICES", "ROCR_VISIBLE_DEVICES", "ZE_AFFINITY_MASK"],
+)
+def test_a_different_mask_does_not_inherit_the_inventory(monkeypatch, mask):
+ _smi(monkeypatch, [dict(B200)])
+ assert hw.get_backend_visible_gpu_info()["available"]
+ monkeypatch.setenv(mask, "7")
+ _smi(monkeypatch, None)
+ assert hw.get_backend_visible_gpu_info()["available"] is False
+
+
+def test_nvidia_marks_failure_and_absence_apart(monkeypatch):
+ _smi(monkeypatch, None)
+ assert nvidia.get_backend_visible_gpu_info([0], "0")["probe_failed"] is True
+ _smi(monkeypatch, nvidia.NVIDIA_SMI_ABSENT)
+ absent = nvidia.get_backend_visible_gpu_info([0], "0")
+ assert absent["smi_absent"] is True and "probe_failed" not in absent
+ _smi(monkeypatch, [])
+ empty = nvidia.get_backend_visible_gpu_info([0], "0")
+ assert empty["available"] is False and "probe_failed" not in empty and "smi_absent" not in empty
+
+
+def test_an_older_probe_does_not_bring_back_a_gpu_a_newer_one_ruled_out(monkeypatch):
+ import threading
+
+ release = threading.Event()
+ found = {"available": True, "devices": [dict(B200)], "index_kind": "physical"}
+ empty = {"available": False, "devices": [], "index_kind": "physical"}
+
+ def slow_probe(device):
+ release.wait(5)
+ return dict(found, devices = [dict(B200)])
+
+ monkeypatch.setattr(hw, "_probe_backend_visible_gpu_info", slow_probe)
+ older = threading.Thread(target = hw.get_backend_visible_gpu_info)
+ older.start()
+ time.sleep(0.2)
+ monkeypatch.setattr(
+ hw, "_probe_backend_visible_gpu_info", lambda d: dict(empty, _confirmed_empty = True)
+ )
+ assert hw.get_backend_visible_gpu_info()["available"] is False
+ release.set()
+ older.join(5)
+ monkeypatch.setattr(
+ hw, "_probe_backend_visible_gpu_info", lambda d: dict(empty, probe_failed = True)
+ )
+ assert hw.get_backend_visible_gpu_info()["available"] is False
+
+
[email protected]("rocm, device", [(True, "CUDA"), (False, "XPU")])
+def test_non_nvidia_hosts_keep_mains_behaviour(monkeypatch, rocm, device):
+ monkeypatch.setattr(hw, "IS_ROCM", rocm)
+ monkeypatch.setattr(hw, "get_device", lambda: getattr(hw.DeviceType, device))
+ found = {"available": True, "devices": [dict(B200)], "index_kind": "physical"}
+ monkeypatch.setattr(hw, "_probe_backend_visible_gpu_info", lambda d: dict(found))
+ assert hw.get_backend_visible_gpu_info()["available"]
+ empty = {"available": False, "devices": [], "index_kind": "physical"}
+ monkeypatch.setattr(hw, "_probe_backend_visible_gpu_info", lambda d: dict(empty))
+ assert hw.get_backend_visible_gpu_info()["available"] is False
diff --git a/studio/backend/tests/test_gpu_query_cache.py b/studio/backend/tests/test_gpu_query_cache.py
new file mode 100644
index 00000000000..1dc243448b3
--- /dev/null
+++ b/studio/backend/tests/test_gpu_query_cache.py
@@ -0,0 +1,690 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+"""Cached, coalesced nvidia-smi reads, driven by a real fake ``nvidia-smi`` on PATH."""
+
+from __future__ import annotations
+
+import json
+import os
+import subprocess
+import sys
+import threading
+import time
+from pathlib import Path
+
+import pytest
+
+from core.inference.llama_cpp import LlamaCppBackend
+from utils import gpu_memory_events
+from utils.hardware import gpu_query, nvidia
+
+_FAKE = r"""#!{python}
+import json, os, sys, time
+state = json.load(open({state!r}))
+with open({calls!r}, "a") as f:
+ f.write(" ".join(sys.argv[1:]) + "\n")
+time.sleep(state.get("delay", 0))
+if state.get("exit"):
+ sys.stderr.write("NVIDIA-SMI has failed\n")
+ sys.exit(state["exit"])
+args = sys.argv[1:]
+gpus = state["gpus"]
+if args[:1] == ["-L"]:
+ for i, g in enumerate(gpus):
+ print(f"GPU {{i}}: {{g['name']}} (UUID: {{g['uuid']}})")
+ sys.exit(0)
+if args[:1] == ["topo"]:
+ print("\tGPU0\tGPU1\nGPU0\t X \tNV18\nGPU1\tNV18\t X \n\nLegend:\n")
+ sys.exit(0)
+fields = [a.split("=", 1)[1].split(",") for a in args if a.startswith("--query-gpu=")][0]
+nounits = any("nounits" in a for a in args if a.startswith("--format="))
+for i, g in enumerate(gpus):
+ total = g["total"]
+ free = g["free"]
+ vals = {{
+ "index": str(i), "uuid": g["uuid"], "name": g["name"], "compute_cap": "10.0",
+ "memory.total": str(total), "memory.free": str(free), "memory.used": str(total - free),
+ "utilization.gpu": str(g.get("util", 0)), "temperature.gpu": "40",
+ "power.draw": "100.0", "power.limit": "1000.0",
+ }}
+ out = []
+ for name in fields:
+ v = vals[name]
+ if not nounits and name.startswith("memory."):
+ v += " MiB"
+ out.append(v)
+ print(", ".join(out))
+"""
+
+
+class FakeSmi:
+ def __init__(self, root: Path):
+ self.root = root
+ self.state_path = root / "state.json"
+ self.calls_path = root / "calls.log"
+ self.calls_path.write_text("")
+ self.state = {
+ "delay": 0,
+ "exit": 0,
+ "gpus": [
+ {"name": "NVIDIA B200", "uuid": "GPU-aaaa", "total": 183359, "free": 180000},
+ {"name": "NVIDIA B200", "uuid": "GPU-bbbb", "total": 183359, "free": 170000},
+ ],
+ }
+ self.save()
+ exe = root / "nvidia-smi"
+ exe.write_text(
+ _FAKE.format(
+ python = sys.executable, state = str(self.state_path), calls = str(self.calls_path)
+ )
+ )
+ exe.chmod(0o755)
+
+ def save(self):
+ self.state_path.write_text(json.dumps(self.state))
+
+ def set(self, **kw):
+ self.state.update(kw)
+ self.save()
+
+ def set_free(self, *free_mib):
+ for gpu, free in zip(self.state["gpus"], free_mib):
+ gpu["free"] = free
+ self.save()
+
+ def calls(self, needle: str = "") -> int:
+ return sum(1 for line in self.calls_path.read_text().splitlines() if needle in line)
+
+
+def smi(tmp_path, monkeypatch):
+ fake = FakeSmi(tmp_path)
+ monkeypatch.setenv("PATH", f"{tmp_path}{os.pathsep}{os.environ.get('PATH', '')}")
+ monkeypatch.delenv("UNSLOTH_GPU_QUERY_CACHE", raising = False)
+ monkeypatch.delenv("CUDA_VISIBLE_DEVICES", raising = False)
+ # No NVML child unless a test asks for one: it would read this host's real driver.
+ monkeypatch.setenv("UNSLOTH_NVIDIA_LIBRARY_PROBE", "0")
+ monkeypatch.setattr(nvidia, "_nvidia_smi_executable", lambda: "nvidia-smi")
+ gpu_query.reset()
+ yield fake
+ gpu_query.reset()
+
+
+def llama_probe(monkeypatch):
+ monkeypatch.setattr(LlamaCppBackend, "_is_vulkan_backend", staticmethod(lambda b = None: False))
+ monkeypatch.setattr(
+ LlamaCppBackend, "_find_llama_server_binary", staticmethod(lambda: "/opt/llama-server")
+ )
+ monkeypatch.setattr(LlamaCppBackend, "_get_gpu_memory_nvml", staticmethod(lambda: []))
+ monkeypatch.setattr(
+ LlamaCppBackend, "_get_gpu_memory_amd_smi", staticmethod(lambda *a, **k: [])
+ )
+ monkeypatch.setattr(
+ LlamaCppBackend, "_widen_integrated_cuda_rows", staticmethod(lambda rows: rows)
+ )
+ monkeypatch.setitem(sys.modules, "torch", None)
+ return LlamaCppBackend._get_gpu_memory
+
+
+def _free_by_index(result):
+ return {d["index"]: round(d["vram_total_gb"] - d["vram_used_gb"], 2) for d in result["devices"]}
+
+
+def test_classification():
+ assert gpu_query.classify(["nvidia-smi", "-L"]) == gpu_query.STATIC
+ assert gpu_query.classify(["nvidia-smi", "topo", "-m"]) == gpu_query.STATIC
+ assert (
+ gpu_query.classify(["nvidia-smi", "--query-gpu=index,name,memory.total", "--format=csv"])
+ == gpu_query.STATIC
+ )
+ assert (
+ gpu_query.classify(["nvidia-smi", "--query-gpu=index,compute_cap", "--format=csv"])
+ == gpu_query.STATIC
+ )
+ live = ["nvidia-smi", "--query-gpu=index,memory.free,memory.total", "--format=csv"]
+ assert gpu_query.classify(live) == gpu_query.CRITICAL
+ with gpu_query.display_reads():
+ assert gpu_query.classify(live) == gpu_query.DISPLAY
+ assert gpu_query.classify(["nvidia-smi", "-q"]) == gpu_query.CRITICAL
+
+
+def test_concurrent_identical_display_queries_start_one_child(smi):
+ smi.set(delay = 0.6)
+ results, errors = [], []
+
+ def worker():
+ try:
+ with gpu_query.display_reads():
+ results.append(nvidia.get_visible_gpu_utilization([0, 1]))
+ except Exception as e: # pragma: no cover - surfaced below
+ errors.append(e)
+
+ threads = [threading.Thread(target = worker) for _ in range(16)]
+ for t in threads:
+ t.start()
+ for t in threads:
+ t.join(10)
+ assert not errors
+ assert len(results) == 16
+ assert all(r == results[0] for r in results)
+ assert results[0]["available"] is True
+ assert smi.calls("--query-gpu") == 1
+ assert gpu_query.stats()["coalesced"] >= 1
+
+
+def test_concurrent_fit_checks_each_run_the_cli(smi, llama_probe):
+ smi.set(delay = 0.3)
+ threads = [threading.Thread(target = llama_probe) for _ in range(4)]
+ for t in threads:
+ t.start()
+ for t in threads:
+ t.join(10)
+ assert smi.calls("memory.free") == 4
+
+
+def test_concurrent_fit_checks_never_answer_from_before_they_started(smi, llama_probe):
+ lock = threading.Lock()
+ current = [1000]
+ stop = threading.Event()
+
+ def writer():
+ while not stop.is_set():
+ with lock:
+ current[0] += 1
+ for gpu in smi.state["gpus"]:
+ gpu["free"] = current[0]
+ tmp = smi.state_path.with_suffix(".tmp")
+ tmp.write_text(json.dumps(smi.state))
+ os.replace(tmp, smi.state_path)
+ time.sleep(0.01)
+
+ violations, errors = [], []
+
+ def reader():
+ for _ in range(5):
+ with lock:
+ floor = current[0]
+ try:
+ rows = llama_probe()
+ except Exception as e: # pragma: no cover - surfaced below
+ errors.append(e)
+ continue
+ if not rows or rows[0][1] < floor:
+ violations.append((floor, rows))
+
+ w = threading.Thread(target = writer)
+ w.start()
+ readers = [threading.Thread(target = reader) for _ in range(16)]
+ for t in readers:
+ t.start()
+ for t in readers:
+ t.join(60)
+ stop.set()
+ w.join(5)
+ assert not errors
+ assert violations == []
+ assert smi.calls("memory.free") == 80
+
+
+def test_different_queries_are_not_merged(smi):
+ nvidia.get_visible_gpu_utilization([0, 1])
+ nvidia.get_primary_gpu_utilization()
+ assert smi.calls("--query-gpu") == 2
+
+
+def test_fit_checks_always_read_afresh(smi, llama_probe):
+ """Another process's allocation raises no Studio event, so the next fit check must see it."""
+ assert llama_probe() == [(0, 180000, 183359), (1, 170000, 183359)]
+ smi.set_free(1000, 1000) # another process took nearly all of both GPUs, no invalidation
+ assert llama_probe() == [(0, 1000, 183359), (1, 1000, 183359)]
+ assert smi.calls("memory.free") == 2
+
+
+def test_display_reads_are_served_stale_while_one_child_refreshes(smi, monkeypatch):
+ monkeypatch.setenv("UNSLOTH_GPU_QUERY_DISPLAY_TTL", "0.2")
+ with gpu_query.display_reads():
+ first = _free_by_index(nvidia.get_visible_gpu_utilization([0, 1]))
+ smi.set(delay = 0.5)
+ smi.set_free(2048, 2048)
+ time.sleep(0.3)
+ t0 = time.monotonic()
+ with gpu_query.display_reads():
+ stale = _free_by_index(nvidia.get_visible_gpu_utilization([0, 1]))
+ assert time.monotonic() - t0 < 0.3
+ assert stale == first
+ deadline = time.monotonic() + 5
+ while gpu_query.stats()["inflight"] and time.monotonic() < deadline:
+ time.sleep(0.05)
+ with gpu_query.display_reads():
+ refreshed = _free_by_index(nvidia.get_visible_gpu_utilization([0, 1]))
+ assert refreshed == {0: 2.0, 1: 2.0}
+
+
+def test_display_ttl_does_not_leak_into_fit_checks(smi, monkeypatch):
+ monkeypatch.setenv("UNSLOTH_GPU_QUERY_DISPLAY_TTL", "60")
+ with gpu_query.display_reads():
+ nvidia.get_visible_gpu_utilization([0, 1])
+ smi.set_free(512, 512)
+ fresh = _free_by_index(nvidia.get_visible_gpu_utilization([0, 1]))
+ assert fresh == {0: 0.5, 1: 0.5}
+
+
+def test_static_inventory_is_cached_until_redetection(smi):
+ first = nvidia.get_physical_gpu_inventory()
+ assert [d["name"] for d in first["devices"]] == ["NVIDIA B200", "NVIDIA B200"]
+ assert nvidia.get_physical_gpu_count() == 2
+ for _ in range(5):
+ nvidia.get_physical_gpu_inventory()
+ nvidia.get_physical_gpu_count()
+ LlamaCppBackend._cuda_compute_caps()
+ LlamaCppBackend._probe_nvlink_topology()
+ assert smi.calls("memory.total") == 1
+ assert smi.calls("-L") == 1
+ assert smi.calls("compute_cap") == 1
+ assert smi.calls("topo") == 5
+ gpu_memory_events.invalidate_gpu_memory("load")
+ nvidia.get_physical_gpu_inventory()
+ assert smi.calls("memory.total") == 1
+ gpu_query.invalidate_static("redetect")
+ nvidia.get_physical_gpu_inventory()
+ assert smi.calls("memory.total") == 2
+
+
+def test_an_answered_empty_inventory_replaces_the_cached_one(smi, monkeypatch):
+ monkeypatch.setenv("UNSLOTH_GPU_QUERY_STATIC_TTL", "0")
+ assert nvidia.get_physical_gpu_count() == 2
+ smi.set(gpus = [])
+ counts = []
+ for _ in range(20):
+ counts.append(nvidia.get_physical_gpu_count())
+ if counts[-1] in (0, None):
+ break
+ time.sleep(0.1)
+ assert counts[-1] in (0, None), counts
+
+
+def test_a_static_read_after_redetection_does_not_join_an_older_child(smi):
+ smi.set(delay = 0.6)
+ first = threading.Thread(target = nvidia.get_physical_gpu_count)
+ first.start()
+ time.sleep(0.2)
+ smi.state["gpus"] = smi.state["gpus"][:1] # a GPU went away; re-detection follows
+ smi.save()
+ gpu_query.invalidate_static("redetect")
+ assert nvidia.get_physical_gpu_count() == 1
+ first.join(5)
+ assert smi.calls("-L") == 2
+
+
+def test_display_after_a_load_reads_afresh_inside_the_ttl(smi, monkeypatch):
+ monkeypatch.setenv("UNSLOTH_GPU_QUERY_DISPLAY_TTL", "3600")
+ with gpu_query.display_reads():
+ nvidia.get_visible_gpu_utilization([0, 1])
+
+ @gpu_memory_events.invalidates_gpu_memory("test load")
+ def load_model():
+ smi.set_free(1024, 1024) # the model now occupies the cards
+
+ load_model()
+ with gpu_query.display_reads():
+ after = _free_by_index(nvidia.get_visible_gpu_utilization([0, 1]))
+ assert after == {0: 1.0, 1: 1.0}
+ assert smi.calls("--query-gpu") == 2
+
+
+def test_studio_load_unload_and_training_methods_invalidate():
+ from core.inference import diffusion, inference, orchestrator, video
+ from core.inference import native_audio, sd_cpp_backend
+ from core.rag import embed_llama_server
+ from core.inference import stt_registry
+ from core.training import diffusion_training_service, training
+
+ methods = [
+ LlamaCppBackend.load_model,
+ LlamaCppBackend.unload_model,
+ LlamaCppBackend._kill_process,
+ orchestrator.InferenceOrchestrator.load_model,
+ orchestrator.InferenceOrchestrator.unload_model,
+ training.TrainingBackend.start_training,
+ training.TrainingBackend.stop_training,
+ diffusion.DiffusionBackend.load_pipeline,
+ diffusion.DiffusionBackend.unload,
+ video.VideoBackend.load_pipeline,
+ video.VideoBackend.unload,
+ sd_cpp_backend.SdCppDiffusionBackend._run_load,
+ sd_cpp_backend.SdCppDiffusionBackend.unload,
+ embed_llama_server.LlamaServerBackend._spawn,
+ embed_llama_server.LlamaServerBackend._kill_process,
+ inference.InferenceBackend.load_model,
+ inference.InferenceBackend.unload_model,
+ native_audio.NativeAudioBackend.load_model,
+ native_audio.NativeAudioBackend.unload_model,
+ stt_registry.load,
+ stt_registry.unload,
+ diffusion_training_service.DiffusionTrainingService.start,
+ diffusion_training_service.DiffusionTrainingService.stop,
+ ]
+ for method in methods:
+ code = method.__code__
+ assert (
+ code is gpu_memory_events.invalidates_gpu_memory("x")(lambda: None).__code__
+ ), method.__qualname__
+
+
+def test_invalidation_happens_even_when_the_load_fails():
+ before = gpu_memory_events.generation()
+
+ @gpu_memory_events.invalidates_gpu_memory("failing load")
+ def load():
+ raise RuntimeError("boom")
+
+ with pytest.raises(RuntimeError):
+ load()
+ assert gpu_memory_events.generation() == before + 2
+
+
+def test_a_child_started_before_an_invalidation_is_not_joined(smi, llama_probe):
+ """A display read arriving after a load must not share a CLI call that began before it."""
+ smi.set(delay = 0.5)
+ first_result = []
+
+ def display_probe():
+ with gpu_query.display_reads():
+ return llama_probe()
+
+ t = threading.Thread(target = lambda: first_result.append(display_probe()))
+ t.start()
+ time.sleep(0.15)
+ smi.set_free(64, 64)
+ gpu_memory_events.invalidate_gpu_memory("load")
+ second = display_probe()
+ t.join(5)
+ assert first_result == [[(0, 180000, 183359), (1, 170000, 183359)]]
+ assert second == [(0, 64, 183359), (1, 64, 183359)]
+ assert smi.calls("memory.free") == 2
+
+
+def test_fresh_reads_always_run_the_cli(smi):
+ for _ in range(3):
+ with gpu_query.fresh_reads():
+ nvidia.get_visible_gpu_utilization([0, 1])
+ assert smi.calls("--query-gpu") == 3
+
+
+def test_a_fit_check_waits_its_whole_timeout_on_a_slow_driver(smi):
+ smi.set(delay = 1.5)
+ argv = ["nvidia-smi", "--query-gpu=index,memory.free", "--format=csv,noheader,nounits"]
+ with pytest.raises(subprocess.TimeoutExpired):
+ gpu_query.run_nvidia_smi(argv, timeout = 0.5, capture_output = True, text = True)
+ assert gpu_query.driver_slow()
+ out = gpu_query.run_nvidia_smi(argv, timeout = 5, capture_output = True, text = True)
+ assert out.stdout.split() == ["0,", "180000", "1,", "170000"]
+
+
+def test_a_slow_cli_holds_the_caller_only_for_its_timeout(smi, monkeypatch):
+ monkeypatch.setattr(gpu_query, "_background_timeout", lambda: 3.0)
+ smi.set(delay = 2.0)
+ t0 = time.monotonic()
+ with pytest.raises(subprocess.TimeoutExpired):
+ gpu_query.run_nvidia_smi(
+ ["nvidia-smi", "--query-gpu=index,memory.free", "--format=csv,noheader,nounits"],
+ timeout = 0.3,
+ capture_output = True,
+ text = True,
+ )
+ assert time.monotonic() - t0 < 1.0
+ assert gpu_query.driver_slow()
+
+
+def test_a_child_the_kernel_cannot_reap_does_not_hold_the_caller(monkeypatch):
+ gpu_query.reset()
+ monkeypatch.delenv("UNSLOTH_GPU_QUERY_CACHE", raising = False)
+ monkeypatch.setenv("UNSLOTH_NVIDIA_LIBRARY_PROBE", "0")
+ calls = []
+
+ def unreapable(argv, **kwargs):
+ calls.append(argv)
+ time.sleep(12.0)
+ raise subprocess.TimeoutExpired(argv, kwargs.get("timeout"))
+
+ monkeypatch.setattr(subprocess, "run", unreapable)
+ for _ in range(2):
+ t0 = time.monotonic()
+ out = nvidia.get_visible_gpu_utilization([0, 1])
+ assert out["available"] is False
+ assert time.monotonic() - t0 < 7.0
+ assert len(calls) == 2
+ gpu_query.reset()
+
+
+def test_slow_cli_answers_a_display_read_from_the_last_good_value(smi, monkeypatch):
+ with gpu_query.display_reads():
+ good = nvidia.get_visible_gpu_utilization([0, 1])
+ monkeypatch.setenv("UNSLOTH_GPU_QUERY_DISPLAY_TTL", "0")
+ monkeypatch.setattr(gpu_query, "_background_timeout", lambda: 4.0)
+ smi.set(delay = 12.0)
+ monkeypatch.setattr(gpu_query, "run_nvidia_smi", _with_timeout(gpu_query.run_nvidia_smi, 0.5))
+ t0 = time.monotonic()
+ with gpu_query.display_reads():
+ out = nvidia.get_visible_gpu_utilization([0, 1])
+ assert time.monotonic() - t0 < 2.0
+ assert out == good
+
+
+def test_slow_cli_never_shows_a_pre_load_reading_after_a_load(smi, monkeypatch):
+ with gpu_query.display_reads():
+ nvidia.get_visible_gpu_utilization([0, 1])
+ monkeypatch.setenv("UNSLOTH_GPU_QUERY_DISPLAY_TTL", "0")
+ gpu_memory_events.invalidate_gpu_memory("load")
+ monkeypatch.setattr(gpu_query, "_background_timeout", lambda: 4.0)
+ smi.set(delay = 12.0)
+ monkeypatch.setattr(gpu_query, "run_nvidia_smi", _with_timeout(gpu_query.run_nvidia_smi, 0.5))
+ t0 = time.monotonic()
+ with gpu_query.display_reads():
+ out = nvidia.get_visible_gpu_utilization([0, 1])
+ assert time.monotonic() - t0 < 2.0
+ assert out["available"] is False
+
+
+def test_a_failed_answer_replaces_the_cached_inventory(smi, monkeypatch):
+ monkeypatch.setenv("UNSLOTH_GPU_QUERY_STATIC_TTL", "0")
+ assert nvidia.get_physical_gpu_count() == 2
+ smi.set(exit = 6) # real nvidia-smi on a host with no GPU: "No devices were found", exit 6
+ counts = []
+ for _ in range(20):
+ counts.append(nvidia.get_physical_gpu_count())
+ if counts[-1] is None:
+ break
+ time.sleep(0.1)
+ assert counts[-1] is None, counts
+
+
+def test_an_expired_inventory_is_not_served_after_a_card_goes_away(smi, monkeypatch):
+ monkeypatch.setenv("UNSLOTH_GPU_QUERY_STATIC_TTL", "0.2")
+ assert nvidia.get_physical_gpu_count() == 2
+ time.sleep(0.5)
+ smi.state["gpus"] = smi.state["gpus"][:1] # an eGPU detached
+ smi.save()
+ assert nvidia.get_physical_gpu_count() == 1
+
+
+def test_a_check_true_failure_replaces_the_cached_answer(smi, monkeypatch):
+ monkeypatch.setenv("UNSLOTH_GPU_QUERY_DISPLAY_TTL", "0")
+ argv = ["nvidia-smi", "--query-gpu=index,memory.used", "--format=csv,noheader"]
+
+ def run():
+ with gpu_query.display_reads():
+ return gpu_query.run_nvidia_smi(
+ argv, capture_output = True, text = True, timeout = 5, check = True
+ )
+
+ run()
+ smi.set(exit = 6)
+ for _ in range(20):
+ try:
+ run()
+ except subprocess.CalledProcessError:
+ break
+ time.sleep(0.1)
+ with pytest.raises(subprocess.CalledProcessError):
+ run()
+
+
[email protected]("code, failed", [(6, False), (9, True)])
+def test_no_devices_found_is_an_answer_not_a_failure(smi, code, failed):
+ assert nvidia.get_backend_visible_gpu_info([0, 1], "0,1")["available"]
+ smi.set(exit = code) # 6: "No devices were found"; 9: driver not loaded
+ gpu_query.invalidate_static("redetect")
+ out = nvidia.get_backend_visible_gpu_info([0, 1], "0,1")
+ assert out["available"] is False
+ assert bool(out.get("probe_failed")) is failed
+
+
+def test_a_read_after_a_hung_child_does_not_wait_on_it(smi, monkeypatch):
+ argv = ["nvidia-smi", "--query-gpu=index,compute_cap", "--format=csv,noheader"]
+
+ def run(timeout):
+ return gpu_query.run_nvidia_smi(argv, capture_output = True, text = True, timeout = timeout)
+
+ monkeypatch.setattr(gpu_query, "_background_timeout", lambda: 10.0)
+ smi.set(delay = 8.0)
+ with pytest.raises(subprocess.TimeoutExpired):
+ run(0.5)
+ smi.set(delay = 0) # the driver recovered; the first child is still running
+ t0 = time.monotonic()
+ assert run(0.5).stdout.split()[0] == "0,"
+ assert time.monotonic() - t0 < 1.0
+
+
+def test_display_reads_without_stale_wait_for_a_new_reading(smi, monkeypatch):
+ monkeypatch.setenv("UNSLOTH_GPU_QUERY_DISPLAY_TTL", "0.2")
+ with gpu_query.display_reads(max_stale = 0):
+ first = _free_by_index(nvidia.get_visible_gpu_utilization([0, 1]))
+ time.sleep(0.4)
+ smi.set_free(1000, 1000) # another process allocated; no Studio event
+ with gpu_query.display_reads(max_stale = 0):
+ after = _free_by_index(nvidia.get_visible_gpu_utilization([0, 1]))
+ assert after != first
+ assert smi.calls("--query-gpu") == 2
+
+
+def test_display_reads_without_stale_still_survive_a_hung_cli(smi, monkeypatch):
+ monkeypatch.setenv("UNSLOTH_GPU_QUERY_DISPLAY_TTL", "0")
+ with gpu_query.display_reads(max_stale = 0):
+ good = nvidia.get_visible_gpu_utilization([0, 1])
+ monkeypatch.setattr(gpu_query, "_background_timeout", lambda: 4.0)
+ smi.set(delay = 12.0)
+ monkeypatch.setattr(gpu_query, "run_nvidia_smi", _with_timeout(gpu_query.run_nvidia_smi, 0.5))
+ t0 = time.monotonic()
+ with gpu_query.display_reads(max_stale = 0):
+ out = nvidia.get_visible_gpu_utilization([0, 1])
+ assert time.monotonic() - t0 < 2.0
+ assert out == good
+
+
+def test_an_older_answer_does_not_overwrite_a_newer_empty_one(smi, monkeypatch):
+ monkeypatch.setenv("UNSLOTH_GPU_QUERY_DISPLAY_TTL", "3600")
+ argv = ["nvidia-smi", "--query-gpu=index,memory.used", "--format=csv,noheader"]
+
+ def run():
+ return gpu_query.run_nvidia_smi(argv, capture_output = True, text = True, timeout = 5)
+
+ smi.set(delay = 1.0)
+ older = threading.Thread(target = run) # fit checks never share a child
+ older.start()
+ time.sleep(0.3)
+ smi.set(delay = 0, gpus = [])
+ assert run().stdout == ""
+ older.join(5)
+ with gpu_query.display_reads():
+ assert run().stdout == ""
+
+
+def test_slow_cli_never_answers_a_fit_check_from_an_old_reading(smi, llama_probe, monkeypatch):
+ """Another process can allocate between readings, so no earlier sample may stand in."""
+ monkeypatch.setattr(gpu_query, "_background_timeout", lambda: 4.0)
+ assert llama_probe() == [(0, 180000, 183359), (1, 170000, 183359)]
+ smi.set_free(1000, 1000) # another process took nearly all of both GPUs
+ smi.set(delay = 12.0)
+ monkeypatch.setattr(gpu_query, "run_nvidia_smi", _with_timeout(gpu_query.run_nvidia_smi, 0.5))
+ assert llama_probe() == []
+ assert gpu_query.stats()["stale_served"] == 0
+
+
+def test_a_fit_check_does_not_join_an_older_child(smi, monkeypatch):
+ monkeypatch.setattr(gpu_query, "_background_timeout", lambda: 4.0)
+ smi.set(delay = 3.0)
+ argv = ["nvidia-smi", "--query-gpu=index,memory.free", "--format=csv,noheader,nounits"]
+ kw = dict(timeout = 5, capture_output = True, text = True)
+ first = threading.Thread(target = lambda: gpu_query.run_nvidia_smi(argv, **kw))
+ first.start()
+ time.sleep(0.5)
+ smi.set(delay = 0)
+ smi.set_free(1000, 1000)
+ out = gpu_query.run_nvidia_smi(argv, **kw)
+ assert out.stdout.split() == ["0,", "1000", "1,", "1000"]
+ first.join()
+ assert smi.calls("--query-gpu=index,memory.free") == 2
+
+
+def test_no_stale_fit_answer_across_a_load(smi, llama_probe, monkeypatch):
+ monkeypatch.setattr(gpu_query, "_background_timeout", lambda: 4.0)
+ llama_probe()
+ gpu_memory_events.invalidate_gpu_memory("load")
+ smi.set(delay = 12.0)
+ monkeypatch.setattr(gpu_query, "run_nvidia_smi", _with_timeout(gpu_query.run_nvidia_smi, 0.5))
+ assert llama_probe() == []
+
+
+def test_a_hung_cli_leaves_llama_cpp_its_own_mig_aware_fallback(smi, llama_probe, monkeypatch):
+ monkeypatch.setattr(gpu_query, "_background_timeout", lambda: 4.0)
+ slice_rows = [(0, 5000, 10240)]
+ monkeypatch.setattr(LlamaCppBackend, "_get_gpu_memory_nvml", staticmethod(lambda: slice_rows))
+ monkeypatch.setenv("UNSLOTH_NVIDIA_LIBRARY_PROBE", "1")
+ whole_gpu = [{"index": 0, "memory_total_mib": 81920, "memory_free_mib": 70000}]
+ monkeypatch.setattr(gpu_query, "_nvml_rows", lambda timeout: whole_gpu, raising = False)
+ smi.set(delay = 12.0)
+ monkeypatch.setattr(gpu_query, "run_nvidia_smi", _with_timeout(gpu_query.run_nvidia_smi, 0.5))
+ assert llama_probe() == slice_rows
+
+
+def _with_timeout(fn, timeout):
+ def wrapped(argv, **kwargs):
+ kwargs["timeout"] = timeout
+ return fn(argv, **kwargs)
+
+ return wrapped
+
+
+def test_failing_cli_is_not_cached(smi):
+ smi.set(exit = 9)
+ for _ in range(3):
+ assert nvidia.get_visible_gpu_utilization([0, 1])["available"] is False
+ assert smi.calls("--query-gpu") == 3
+ smi.set(exit = 0)
+ assert nvidia.get_visible_gpu_utilization([0, 1])["available"] is True
+
+
+def test_missing_cli_is_reported_absent(monkeypatch, tmp_path):
+ monkeypatch.setenv("PATH", str(tmp_path))
+ monkeypatch.setattr(nvidia, "_nvidia_smi_executable", lambda: "nvidia-smi")
+ gpu_query.reset()
+ assert nvidia._query_gpu_inventory("test") is nvidia.NVIDIA_SMI_ABSENT
+ assert nvidia.get_physical_gpu_count() is None
+
+
+def test_cache_can_be_turned_off(smi, monkeypatch):
+ monkeypatch.setenv("UNSLOTH_GPU_QUERY_CACHE", "0")
+ for _ in range(3):
+ nvidia.get_visible_gpu_utilization([0, 1])
+ nvidia.get_physical_gpu_inventory()
+ assert smi.calls("--query-gpu") == 6
+
+
+def test_results_are_copies(smi):
+ argv = ["nvidia-smi", "--query-gpu=index,memory.free", "--format=csv,noheader,nounits"]
+ a = gpu_query.run_nvidia_smi(argv, timeout = 5, capture_output = True, text = True)
+ a.stdout = "mutated"
+ b = gpu_query.run_nvidia_smi(argv, timeout = 5, capture_output = True, text = True)
+ assert b.stdout.startswith("0, 180000")
diff --git a/studio/backend/utils/gpu_memory_events.py b/studio/backend/utils/gpu_memory_events.py
new file mode 100644
index 00000000000..f04467fa19f
--- /dev/null
+++ b/studio/backend/utils/gpu_memory_events.py
@@ -0,0 +1,42 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Generation counter bumped when Studio changes what is resident on the GPUs.
+Import-free so backends can decorate load/unload without pulling in utils.hardware."""
+
+import functools
+import threading
+from typing import Any, Callable, TypeVar
+
+_F = TypeVar("_F", bound = Callable[..., Any])
+
+_lock = threading.Lock()
+_generation = 0
+
+
+def generation() -> int:
+ return _generation
+
+
+def invalidate_gpu_memory(reason: str = "") -> int:
+ global _generation
+ with _lock:
+ _generation += 1
+ return _generation
+
+
+def invalidates_gpu_memory(reason: str) -> Callable[[_F], _F]:
+ """Invalidate on entry and on exit (success or failure)."""
+
+ def decorate(fn: _F) -> _F:
+ @functools.wraps(fn)
+ def wrapper(*args: Any, **kwargs: Any) -> Any:
+ invalidate_gpu_memory(reason)
+ try:
+ return fn(*args, **kwargs)
+ finally:
+ invalidate_gpu_memory(reason)
+
+ return wrapper # type: ignore[return-value]
+
+ return decorate
diff --git a/studio/backend/utils/hardware/gpu_query.py b/studio/backend/utils/hardware/gpu_query.py
new file mode 100644
index 00000000000..4120e646679
--- /dev/null
+++ b/studio/backend/utils/hardware/gpu_query.py
@@ -0,0 +1,453 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Cached, coalesced nvidia-smi reads: drop-in for ``subprocess.run`` with a bounded wait.
+
+Categories: ``static`` (inventory fields, TTL 60 s like the eGPU-aware physical inventory),
+``display`` (live fields inside :func:`display_reads`, TTL 3 s, stale-while-revalidate),
+``critical`` (live fields anywhere else: never cached or joined, since another process's
+allocation raises no Studio event). ``subprocess.run(timeout=...)`` waits unboundedly for a
+killed child on a blocked driver, so the child runs on a daemon thread. Failures are never
+served and replace older answers. ``UNSLOTH_GPU_QUERY_CACHE=0`` disables all of this.
+"""
+
+from __future__ import annotations
+
+import contextlib
+import copy
+import contextvars
+import os
+import shutil
+import subprocess
+import threading
+import time
+from dataclasses import dataclass, field
+from typing import Any, Iterator, Optional, Sequence
+
+from loggers import get_logger
+from utils import gpu_memory_events as _events
+
+logger = get_logger(__name__)
+
+# Bound at import: tests stubbing threading.Thread must not stop foreground reads.
+_Thread = threading.Thread
+
+STATIC = "static"
+DISPLAY = "display"
+CRITICAL = "critical"
+
+_STATIC_FIELDS = frozenset(
+ {
+ "index",
+ "uuid",
+ "gpu_uuid",
+ "name",
+ "gpu_name",
+ "serial",
+ "pci.bus_id",
+ "gpu_bus_id",
+ "memory.total",
+ "compute_cap",
+ "driver_version",
+ "vbios_version",
+ "count",
+ }
+)
+_STATIC_SUBCOMMANDS = frozenset({"-L", "--list-gpus", "topo"})
+
+_DISPLAY_MAX_STALE_S = 60.0
+_SLOW_BACKOFF_S = 30.0
+_SLOW_WAIT_S = 1.0
+
+
+def _env_float(name: str, default: float) -> float:
+ raw = os.environ.get(name)
+ if raw is None or not raw.strip():
+ return default
+ try:
+ value = float(raw)
+ except ValueError:
+ return default
+ return value if value >= 0 else default
+
+
+def enabled() -> bool:
+ return os.environ.get("UNSLOTH_GPU_QUERY_CACHE", "1").strip().lower() not in (
+ "0",
+ "false",
+ "no",
+ "off",
+ )
+
+
+def ttl_for(kind: str) -> float:
+ if kind == STATIC:
+ return _env_float("UNSLOTH_GPU_QUERY_STATIC_TTL", 60.0)
+ return _env_float("UNSLOTH_GPU_QUERY_DISPLAY_TTL", 3.0)
+
+
+def _background_timeout() -> float:
+ return _env_float("UNSLOTH_GPU_QUERY_BACKGROUND_TIMEOUT", 120.0)
+
+
+# None outside display_reads(); inside, the oldest reading (seconds) served while one refreshes.
+_display_mode: contextvars.ContextVar[Optional[float]] = contextvars.ContextVar(
+ "unsloth_gpu_query_display", default = None
+)
+_fresh_mode: contextvars.ContextVar[bool] = contextvars.ContextVar(
+ "unsloth_gpu_query_fresh", default = False
+)
+
+
+def display_reads(max_stale: float = _DISPLAY_MAX_STALE_S) -> Iterator[None]:
+ """Live reads may be seconds old. Never wrap anything that decides placement or fit.
+
+ ``max_stale`` caps the reading served while one refresh runs; a hung CLI may still get
+ the last good reading up to 60 s old."""
+ token = _display_mode.set(float(max_stale))
+ try:
+ yield
+ finally:
+ _display_mode.reset(token)
+
+
+def fresh_reads() -> Iterator[None]:
+ """Every live read runs the CLI (settle loops, fenced paired readings)."""
+ token = _fresh_mode.set(True)
+ try:
+ yield
+ finally:
+ _fresh_mode.reset(token)
+
+
+def classify(argv: Sequence[str]) -> str:
+ args = list(argv[1:])
+ if args and args[0] in _STATIC_SUBCOMMANDS:
+ return STATIC
+ fields = _query_fields(argv)
+ if fields and set(fields) <= _STATIC_FIELDS:
+ return STATIC
+ return DISPLAY if _display_mode.get() is not None else CRITICAL
+
+
+def _query_fields(argv: Sequence[str]) -> list[str]:
+ for arg in argv[1:]:
+ if arg.startswith("--query-gpu="):
+ return [f.strip() for f in arg.split("=", 1)[1].split(",") if f.strip()]
+ return []
+
+
+def _nounits(argv: Sequence[str]) -> bool:
+ return any(arg.startswith("--format=") and "nounits" in arg for arg in argv[1:])
+
+
+@dataclass
+class _Entry:
+ # None = the CLI's latest answer had no rows (failed or empty): never served, only orders writers.
+ result: Optional[subprocess.CompletedProcess]
+ at: float
+ gen: int
+ static_gen: int
+ started: float = 0.0
+
+
+@dataclass
+class _Flight:
+ key: tuple
+ gen: int
+ static_gen: int
+ started: float
+ epoch: int = 0
+ done: threading.Event = field(default_factory = threading.Event)
+ result: Optional[subprocess.CompletedProcess] = None
+ exc: Optional[BaseException] = None
+
+
+@dataclass
+class _Stats:
+ calls: int = 0
+ spawned: int = 0
+ hits: int = 0
+ coalesced: int = 0
+ stale_served: int = 0
+ timeouts: int = 0
+ background_refreshes: int = 0
+
+
+_lock = threading.Lock()
+_cache: dict[tuple, _Entry] = {}
+_inflight: dict[tuple, _Flight] = {}
+_static_gen = 0
+# Bumped by reset(): a child that outlives a reset must not refill the emptied cache.
+_reset_epoch = 0
+_slow_until = 0.0
+_stats = _Stats()
+
+
+def invalidate_gpu_memory(reason: str = "") -> None:
+ _events.invalidate_gpu_memory(reason)
+ if reason:
+ logger.debug("GPU memory readings invalidated: %s", reason)
+
+
+def invalidate_static(reason: str = "") -> None:
+ global _static_gen
+ _events.invalidate_gpu_memory(reason)
+ with _lock:
+ _static_gen += 1
+ if reason:
+ logger.debug("GPU inventory readings invalidated: %s", reason)
+
+
+def reset() -> None:
+ global _static_gen, _slow_until, _stats, _reset_epoch
+ _events.invalidate_gpu_memory("reset")
+ with _lock:
+ _reset_epoch += 1
+ _cache.clear()
+ _inflight.clear()
+ _static_gen += 1
+ _slow_until = 0.0
+ _stats = _Stats()
+
+
+def stats() -> dict[str, Any]:
+ with _lock:
+ out = dict(_stats.__dict__)
+ out["driver_slow"] = time.monotonic() < _slow_until
+ out["cached_keys"] = len(_cache)
+ out["inflight"] = len(_inflight)
+ return out
+
+
+def driver_slow() -> bool:
+ return time.monotonic() < _slow_until
+
+
+def _mark_slow() -> None:
+ global _slow_until
+ with _lock:
+ _stats.timeouts += 1
+ _slow_until = time.monotonic() + _SLOW_BACKOFF_S
+
+
+def _resolved(exe: str) -> str:
+ """Never raises: a cache key must not add a failure the direct call lacked."""
+ try:
+ return shutil.which(exe) or exe
+ except Exception:
+ return exe
+
+
+def _copy(result: Any) -> Any:
+ return copy.copy(result)
+
+
+def _entry_fresh(entry: _Entry, kind: str, now: float) -> bool:
+ if entry.result is None or now - entry.at > ttl_for(kind):
+ return False
+ if kind == STATIC:
+ return entry.static_gen == _static_gen
+ return entry.gen == _events.generation()
+
+
+def _run_child(flight: _Flight, argv: list, kind: str, kwargs: dict) -> None:
+ try:
+ with _lock:
+ _stats.spawned += 1
+ # Looked up at call time so a patched subprocess.run (tests) is honoured.
+ result = subprocess.run(argv, **kwargs)
+ flight.result = result
+ stdout = getattr(result, "stdout", None)
+ if isinstance(stdout, str):
+ # Failed / empty answers (exit 6: no devices) are never served but replace older ones.
+ good = getattr(result, "returncode", None) == 0 and bool(stdout.strip())
+ with _lock:
+ if flight.epoch != _reset_epoch:
+ return
+ existing = _cache.get(flight.key)
+ # A slow child that began before the current entry's must not replace it.
+ if existing is None or existing.started <= flight.started:
+ _cache[flight.key] = _Entry(
+ result = result if good else None,
+ at = flight.started,
+ gen = flight.gen,
+ static_gen = flight.static_gen,
+ started = flight.started,
+ )
+ except BaseException as exc: # handed to the waiters, never raised on this thread
+ flight.exc = exc
+ if isinstance(
+ exc, subprocess.CalledProcessError
+ ): # check=True: a failed answer all the same
+ with _lock:
+ existing = _cache.get(flight.key)
+ if flight.epoch == _reset_epoch and (
+ existing is None or existing.started <= flight.started
+ ):
+ _cache[flight.key] = _Entry(
+ result = None,
+ at = flight.started,
+ gen = flight.gen,
+ static_gen = flight.static_gen,
+ started = flight.started,
+ )
+ if isinstance(exc, subprocess.TimeoutExpired) and flight.epoch == _reset_epoch:
+ _mark_slow()
+ finally:
+ with _lock:
+ if _inflight.get(flight.key) is flight:
+ del _inflight[flight.key]
+ flight.done.set()
+
+
+def _start_or_join(key: tuple, argv: list, kind: str, kwargs: dict, timeout: float) -> _Flight:
+ """Never joins a child started before the last invalidation of its kind."""
+ with _lock:
+ flight = _inflight.get(key)
+ # A child already running longer than this caller may wait is presumed hung: start another.
+ if (
+ flight is not None
+ and time.monotonic() - flight.started <= timeout
+ and (
+ flight.static_gen == _static_gen
+ if kind == STATIC
+ else flight.gen == _events.generation()
+ )
+ ):
+ _stats.coalesced += 1
+ return flight
+ flight = _Flight(
+ key = key,
+ gen = _events.generation(),
+ static_gen = _static_gen,
+ started = time.monotonic(),
+ epoch = _reset_epoch,
+ )
+ _inflight[key] = flight
+ child_kwargs = dict(kwargs)
+ child_kwargs["timeout"] = max(float(timeout), _background_timeout())
+ thread = _Thread(
+ target = _run_child,
+ args = (flight, argv, kind, child_kwargs),
+ name = "nvidia-smi-query",
+ daemon = True,
+ )
+ thread.start()
+ return flight
+
+
+def _flight_outcome(flight: _Flight, argv: list, timeout: float) -> subprocess.CompletedProcess:
+ if flight.exc is not None:
+ exc = flight.exc
+ if isinstance(exc, subprocess.TimeoutExpired):
+ raise subprocess.TimeoutExpired(argv, timeout) from None
+ raise exc
+ assert flight.result is not None
+ return _copy(flight.result)
+
+
+def _fallback(key: tuple, kind: str) -> Optional[subprocess.CompletedProcess]:
+ now = time.monotonic()
+ with _lock:
+ entry = _cache.get(key)
+ if entry is not None and entry.result is not None:
+ if kind == STATIC and entry.static_gen == _static_gen:
+ with _lock:
+ _stats.stale_served += 1
+ return _copy(entry.result)
+ if (
+ kind == DISPLAY
+ and now - entry.at <= _DISPLAY_MAX_STALE_S
+ and entry.gen == _events.generation()
+ ):
+ with _lock:
+ _stats.stale_served += 1
+ return _copy(entry.result)
+ return None
+
+
+def run_nvidia_smi(
+ argv: Sequence[str],
+ *,
+ timeout: float,
+ kind: Optional[str] = None,
+ cache: bool = True,
+ **kwargs: Any,
+) -> subprocess.CompletedProcess:
+ """Drop-in for ``subprocess.run``. ``cache=False``: CLI always runs, only the bounded wait applies."""
+ argv = list(argv)
+ if not enabled():
+ return subprocess.run(argv, timeout = timeout, **kwargs)
+ kind = kind or classify(argv)
+ text_mode = bool(
+ kwargs.get("text") or kwargs.get("encoding") or kwargs.get("universal_newlines")
+ )
+ # Runner object (not id: ids are reused) and resolved binary keyed so swapped fakes / PATH never share.
+ key = (subprocess.run, _resolved(argv[0]), tuple(argv), text_mode)
+
+ if not cache or kind == CRITICAL or (_fresh_mode.get() and kind != STATIC):
+ flight = _Flight(
+ key = key,
+ gen = _events.generation(),
+ static_gen = _static_gen,
+ started = time.monotonic(),
+ epoch = _reset_epoch,
+ )
+ child_kwargs = dict(kwargs)
+ child_kwargs["timeout"] = timeout
+ _Thread(
+ target = _run_child,
+ args = (flight, argv, kind, child_kwargs),
+ name = "nvidia-smi-query",
+ daemon = True,
+ ).start()
+ # Whole caller timeout (+1 s reap grace): a slow driver that answers must still be heard.
+ if not flight.done.wait(timeout + 1.0):
+ _mark_slow()
+ raise subprocess.TimeoutExpired(argv, timeout)
+ return _flight_outcome(flight, argv, timeout)
+
+ now = time.monotonic()
+ with _lock:
+ _stats.calls += 1
+ entry = _cache.get(key)
+ if entry is not None and _entry_fresh(entry, kind, now):
+ _stats.hits += 1
+ return _copy(entry.result)
+ # Display only: an expired inventory waits for a new answer, so a detached card is not reported.
+ serve_stale = (
+ entry is not None
+ and entry.result is not None
+ and kind == DISPLAY
+ and now - entry.at <= min(_display_mode.get() or 0.0, _DISPLAY_MAX_STALE_S)
+ and entry.gen == _events.generation()
+ )
+ if serve_stale:
+ with _lock:
+ _stats.stale_served += 1
+ _stats.background_refreshes += 1
+ _start_or_join(key, argv, kind, kwargs, timeout)
+ return _copy(entry.result)
+
+ flight = _start_or_join(key, argv, kind, kwargs, timeout)
+ first_wait = min(timeout, _SLOW_WAIT_S) if driver_slow() else timeout
+ if not flight.done.wait(first_wait):
+ if first_wait < timeout:
+ answer = _fallback(key, kind)
+ if answer is not None:
+ return answer
+ flight.done.wait(max(timeout - first_wait, 0.0))
+ if not flight.done.is_set():
+ _mark_slow()
+ answer = _fallback(key, kind)
+ if answer is not None:
+ return answer
+ raise subprocess.TimeoutExpired(argv, timeout)
+ if isinstance(flight.exc, subprocess.TimeoutExpired):
+ answer = _fallback(key, kind)
+ if answer is not None:
+ return answer
+ return _flight_outcome(flight, argv, timeout)
diff --git a/studio/backend/utils/hardware/hardware.py b/studio/backend/utils/hardware/hardware.py
index 2590b3cbc51..4413af1b1af 100644
--- a/studio/backend/utils/hardware/hardware.py
+++ b/studio/backend/utils/hardware/hardware.py
@@ -67,6 +67,9 @@ DETECTION_EPOCH = 0
def invalidate_detection() -> int:
"""Retire any detection in flight. Returns the new epoch."""
global DETECTION_EPOCH
+ from . import gpu_query
+
+ gpu_query.invalidate_static("hardware re-detection")
with _EPOCH_LOCK:
DETECTION_EPOCH += 1
return DETECTION_EPOCH
@@ -5948,14 +5951,62 @@ def _repair_smi_visible_devices(
return all(dev.get("memory_total_gb") is not None for dev in devices)
+# (probe start, inventory or None once confirmed empty) per (device, mask); newer wins.
+_last_good_visible_info: Dict[tuple, tuple] = {}
+_last_good_visible_lock = threading.Lock()
+
+
def get_backend_visible_gpu_info() -> Dict[str, Any]:
+ """Backend-visible GPU inventory; an unproven empty probe returns the last one, marked ``stale``."""
device = get_device()
+ key = (
+ str(device),
+ os.environ.get("CUDA_VISIBLE_DEVICES"),
+ os.environ.get("HIP_VISIBLE_DEVICES"),
+ os.environ.get("ROCR_VISIBLE_DEVICES"),
+ os.environ.get("ZE_AFFINITY_MASK"),
+ )
+ started = time.monotonic()
+ info = _probe_backend_visible_gpu_info(device)
+ confirmed_empty = info.pop("_confirmed_empty", False)
+ info.pop("probe_failed", None)
+ info.pop("smi_absent", None)
+ found = bool(info.get("available") and info.get("devices"))
+ if found or confirmed_empty:
+ with _last_good_visible_lock:
+ prior = _last_good_visible_info.get(key)
+ if prior is None or prior[0] <= started:
+ _last_good_visible_info[key] = (started, copy.deepcopy(info) if found else None)
+ return info
+ # NVIDIA only: elsewhere no probe can prove a device went away, and those paths keep main's behaviour.
+ if device != DeviceType.CUDA or IS_ROCM:
+ return info
+ with _last_good_visible_lock:
+ last = (_last_good_visible_info.get(key) or (0.0, None))[1]
+ if last is None:
+ return info
+ logger.warning(
+ "GPU inventory probe came back empty after an earlier read found %d device(s); "
+ "keeping that inventory (marked stale) instead of reporting no GPU.",
+ len(last.get("devices") or []),
+ )
+ stale = copy.deepcopy(last)
+ stale["stale"] = True
+ for dev in stale.get("devices") or []:
+ for k in ("vram_used_gb", "vram_free_gb", "vram_utilization_pct"):
+ if k in dev:
+ dev[k] = None
+ return stale
+
+def _probe_backend_visible_gpu_info(device) -> Dict[str, Any]:
if device in (DeviceType.CUDA, DeviceType.XPU):
parent_visible_ids = get_parent_visible_gpu_ids()
# Held back in case torch cannot size them either: an unknown total is a poor
# answer, but losing the card outright is worse than the pre-repair behaviour.
unrepaired_smi_result: Optional[Dict[str, Any]] = None
+ # nvidia-smi answered and listed no card under this mask: the one proof of "no GPU".
+ smi_answered_empty = False
# Try native SMI first (nvidia-smi; skipped for ROCm).
if device == DeviceType.CUDA and not IS_ROCM:
try:
@@ -5966,6 +6017,12 @@ def get_backend_visible_gpu_info() -> Dict[str, Any]:
parent_visible_spec["numeric_ids"],
parent_visible_spec["raw"],
)
+ smi_answered_empty = (
+ not result.get("available")
+ and not result.get("probe_failed")
+ and not result.get("smi_absent")
+ and result.get("index_kind") != "unresolved"
+ )
if result.get("available"):
if _repair_smi_visible_devices(
result.get("devices") or [], parent_visible_spec["numeric_ids"]
@@ -6077,6 +6134,7 @@ def get_backend_visible_gpu_info() -> Dict[str, Any]:
"parent_visible_gpu_ids": parent_visible_ids,
"devices": [],
"index_kind": "physical",
+ "_confirmed_empty": smi_answered_empty,
}
if device == DeviceType.MLX:
diff --git a/studio/backend/utils/hardware/nvidia.py b/studio/backend/utils/hardware/nvidia.py
index 1a68a2ab632..654a7f3fb7b 100644
--- a/studio/backend/utils/hardware/nvidia.py
+++ b/studio/backend/utils/hardware/nvidia.py
@@ -5,10 +5,13 @@ import os
import platform
import shutil
import subprocess
+import threading
from typing import Any, Optional
from loggers import get_logger
+from . import gpu_query
+
from utils.native_path_leases import child_env_without_native_path_secret
from utils.subprocess_compat import (
windows_hidden_subprocess_kwargs as _windows_hidden_subprocess_kwargs,
@@ -75,7 +78,7 @@ def _uuid_visible_ordinal_map(
def get_physical_gpu_count() -> Optional[int]:
"""Return physical GPU count via nvidia-smi, or None on failure."""
try:
- result = subprocess.run(
+ result = gpu_query.run_nvidia_smi(
["nvidia-smi", "-L"],
capture_output = True,
text = True,
@@ -98,7 +101,7 @@ def get_physical_gpu_count() -> Optional[int]:
def get_primary_gpu_utilization() -> dict[str, Any]:
try:
- result = subprocess.run(
+ result = gpu_query.run_nvidia_smi(
[
"nvidia-smi",
"--query-gpu=utilization.gpu,temperature.gpu,"
@@ -147,7 +150,7 @@ def get_visible_gpu_utilization(
"utilization.gpu,temperature.gpu,memory.used,memory.total,power.draw,power.limit"
)
try:
- result = subprocess.run(
+ result = gpu_query.run_nvidia_smi(
[
"nvidia-smi",
f"--query-gpu={query_fields}",
@@ -267,6 +270,10 @@ def _nvidia_smi_executable() -> str:
NVIDIA_SMI_ABSENT = object()
+# This thread's last inventory exit code: exit 6 is nvidia-smi's own "No devices were found".
+_inventory_exit = threading.local()
+
+
def _query_gpu_inventory(caller: str) -> Any:
"""``[{index, name, memory_total_gb}]`` for every GPU nvidia-smi enumerates.
@@ -275,7 +282,7 @@ def _query_gpu_inventory(caller: str) -> Any:
Split out of get_backend_visible_gpu_info so the same rows can be read WITHOUT a ``DeviceType.CUDA`` precondition: get_physical_gpu_inventory below is reached on exactly the host where torch reports no CUDA device, and that host still has its GPUs. Rows a caller cannot make sense of are dropped rather than raised on: a name holding commas is rejoined, and a malformed index or memory column skips the row.
"""
try:
- result = subprocess.run(
+ result = gpu_query.run_nvidia_smi(
[
_nvidia_smi_executable(),
"--query-gpu=index,name,memory.total",
@@ -297,6 +304,7 @@ def _query_gpu_inventory(caller: str) -> Any:
# Past this point an nvidia-smi WAS found, so a failure is a real fault on this host.
logger.warning("nvidia-smi query failed in %s: %s", caller, e)
return None
+ _inventory_exit.code = result.returncode
if result.returncode != 0:
return None
@@ -397,15 +405,22 @@ def get_backend_visible_gpu_info(
"index_kind": "unresolved",
}
visible_ordinals = _visible_ordinal_map(parent_visible_ids)
+ _inventory_exit.code = None
rows = _query_gpu_inventory("get_backend_visible_gpu_info")
if rows is None or rows is NVIDIA_SMI_ABSENT:
- return {
+ out = {
"available": False,
"backend_cuda_visible_devices": backend_cuda_visible_devices,
"parent_visible_gpu_ids": parent_visible_ids or [],
"devices": [],
"index_kind": "physical",
}
+ if rows is NVIDIA_SMI_ABSENT:
+ out["smi_absent"] = True
+ elif getattr(_inventory_exit, "code", None) != 6:
+ # No answer is unknown, not "no cards"; exit 6 ("No devices were found") is an answer.
+ out["probe_failed"] = True
+ return out
devices = []
for row in rows: