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: automatic GPU placement caches failed probes, skips MIG winners, never blocks the event loop (#14118)
Daniel Hana411258dd968
diff --git a/studio/backend/core/inference/diffusion_device.py b/studio/backend/core/inference/diffusion_device.pyindex 224bf740061..d6ff36eb24e 100644--- a/studio/backend/core/inference/diffusion_device.py+++ b/studio/backend/core/inference/diffusion_device.py@@ -465,6 +465,12 @@ def resolve_auto_cuda_ordinal() -> Optional[int]:best = max(free_by_ordinal.values())winner = min(o for o, free in free_by_ordinal.items() if best - free <= _AUTO_FREE_TIE_BYTES)if winner:+ # Physical rows hide MIG slices: a MIG card's row is the whole card, and its CUDA+ # ordinals are slices (or absent before R570), so a row-ranked winner is not a card+ # CUDA hands out. Unknown MIG status or a MIG card in the set keeps card 0 explicit.+ mig = hw._nvidia_mig_gpu_indices_or_none()+ if mig is None or set(visible) & mig:+ return 0return winner# Card 0 won. Identical cards (same capability and size) keep None, the unpinned path they always had,# while no thread was ever pinned elsewhere. Mixed cards, or a process where a pooled thread may sit on@@ -491,17 +497,36 @@ def auto_cuda_ranking_possible_cached() -> Optional[bool]:if hw.DEVICE is None:return None+ # From memory only: get_device() waits on _DETECT_LOCK, which a detection pass in flight+ # holds, and this runs on the event loop.if hw.IS_ROCM or hw.DEVICE != hw.DeviceType.CUDA:- return auto_cuda_ranking_possible()+ return False+ if not hw.DETECTION_COMPLETE.is_set():+ return Nonemask = os.environ.get("CUDA_VISIBLE_DEVICES")if mask is None:- if hw._physical_gpu_count is None:+ # A stray HIP/ROCR mask is then read as the mask: leave that to the worker gate.+ if hw._physical_gpu_count is None or {+ "HIP_VISIBLE_DEVICES",+ "ROCR_VISIBLE_DEVICES",+ } & set(os.environ):return None- elif not all(token.strip().isdigit() for token in mask.split(",") if token.strip()):+ # The count in memory: get_physical_gpu_count() may re-read nvidia-smi, the worker gate does.+ return hw._physical_gpu_count >= 2+ if not all(token.strip().isdigit() for token in mask.split(",") if token.strip()):return None+ # get_parent_visible_gpu_ids' CUDA rule, without its get_device(): an empty entry ends the+ # list and a repeat empties it.+ ids: list[int] = []+ for token in (token.strip() for token in mask.split(",")):+ if not token:+ break+ if int(token) in ids:+ return False+ ids.append(int(token))+ return len(ids) >= 2except Exception: # noqa: BLE001 -- let the worker-thread gate decidereturn None- return auto_cuda_ranking_possible()def auto_cuda_ranking_possible() -> bool:diff --git a/studio/backend/tests/test_diffusion_auto_gpu.py b/studio/backend/tests/test_diffusion_auto_gpu.pyindex 77d09e626ee..97b84605abe 100644--- a/studio/backend/tests/test_diffusion_auto_gpu.py+++ b/studio/backend/tests/test_diffusion_auto_gpu.py@@ -118,6 +118,8 @@ def _route(monkeypatch, device = "cuda"):)monkeypatch.setattr(dd, "resolve_auto_cuda_ordinal", lambda: 1)monkeypatch.setattr(dd, "auto_cuda_ranking_possible", lambda: True)+ # The event-loop gate reads live detection state; defer to the stubbed worker gate.+ monkeypatch.setattr(dd, "auto_cuda_ranking_possible_cached", lambda: None)monkeypatch.setattr(dd, "resolve_selected_cuda_ordinal", lambda ids, **_k: min(ids))return routes._selected_gpu_ordinal@@ -238,6 +240,7 @@ def test_route_pins_its_automatic_decision_for_the_backend(monkeypatch):answers = iter([None, 1])monkeypatch.setattr(dd, "resolve_auto_cuda_ordinal", lambda: next(answers))monkeypatch.setattr(dd, "auto_cuda_ranking_possible", lambda: True)+ monkeypatch.setattr(dd, "auto_cuda_ranking_possible_cached", lambda: None)real = dd.__dict__["_PLANNED_ORDINAL"]async def load():diff --git a/studio/backend/tests/test_media_auto_gpu_mig_and_event_loop.py b/studio/backend/tests/test_media_auto_gpu_mig_and_event_loop.pynew file mode 100644index 00000000000..88b1495a97e--- /dev/null+++ b/studio/backend/tests/test_media_auto_gpu_mig_and_event_loop.py@@ -0,0 +1,141 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Automatic image/video placement: a MIG card never wins by its whole-card row, and the event-loop gate+never waits on hardware detection."""++import threading+import time+import types++import pytest++from core.inference import diffusion_device as dd+from utils.hardware import hardware as hw+from utils.hardware import nvidia+from utils.hardware.hardware import DeviceType+++def _dev(index, total, used):+ return {"index": index, "vram_total_gb": total, "vram_used_gb": used}+++def _two_cards(monkeypatch, mig):+ """2x H100 under PCI_BUS_ID, card 0 busy, card 1 idle by its PHYSICAL row."""+ monkeypatch.setattr(dd, "_PLANNED_ORDINAL", dd._PLANNED_ORDINAL)+ monkeypatch.setattr(hw, "IS_ROCM", False)+ monkeypatch.setattr(hw, "get_parent_visible_gpu_ids", lambda: [0, 1])+ monkeypatch.setattr(hw, "_cuda_order_matches_smi", lambda: True)+ monkeypatch.setattr(hw, "_integrated_cuda_rows", lambda visible: ([], None))+ monkeypatch.setattr(+ hw, "_get_parent_visible_gpu_spec", lambda: {"numeric_ids": [0, 1], "raw": None}+ )+ monkeypatch.setattr(+ hw,+ "_smi_visible_utilization",+ lambda spec: {"devices": [_dev(0, 80.0, 60.0), _dev(1, 80.0, 2.0)]},+ )+ monkeypatch.setattr(nvidia, "get_compute_capabilities", lambda: {0: (9, 0), 1: (9, 0)})+ monkeypatch.setattr(hw, "_nvidia_mig_gpu_indices_or_none", lambda: mig)+++# G2-1: media auto placement ranks a MIG card by its whole-card row and returns a nonzero+# ordinal that CUDA does not map to that card (pre-R570: does not exist at all).+ "mig", [frozenset({1}), frozenset({0}), None], ids = ["card1_mig", "card0_mig", "mig_unknown"]+)+def test_media_rank_never_moves_off_card0_on_a_mig_host(monkeypatch, mig):+ _two_cards(monkeypatch, mig)+ assert dd.resolve_auto_cuda_ordinal() == 0+++def test_media_rank_still_moves_on_ordinary_two_card_host(monkeypatch):+ _two_cards(monkeypatch, frozenset())+ assert dd.resolve_auto_cuda_ordinal() == 1 # #13928's feature is kept+++# G2-2: the event-loop gate must not wait on _DETECT_LOCK while a detection pass runs.[email protected]("device", [DeviceType.MLX, DeviceType.CPU, DeviceType.CUDA])+def test_cached_gate_does_not_block_during_detection(monkeypatch, device):+ monkeypatch.setattr(hw, "DEVICE", device)+ monkeypatch.setattr(hw, "IS_ROCM", False)+ monkeypatch.setattr(hw, "_physical_gpu_count", 2)+ monkeypatch.delenv("CUDA_VISIBLE_DEVICES", raising = False)+ monkeypatch.setattr(hw, "_detect_hardware_locked", lambda: time.sleep(1.5) or device)+ was = hw.DETECTION_COMPLETE.is_set()+ t = threading.Thread(+ target = hw.detect_hardware, daemon = True+ ) # forced re-detect, DEVICE stays set+ t.start()+ time.sleep(0.2)+ try:+ t0 = time.monotonic()+ dd.auto_cuda_ranking_possible_cached()+ waited = time.monotonic() - t0+ finally:+ t.join()+ if was:+ hw.DETECTION_COMPLETE.set()+ else:+ hw.DETECTION_COMPLETE.clear()+ assert waited < 0.3, f"event-loop gate waited {waited:.2f}s on the detection lock"+++# A MIG-mode card with no instances has no `-L` MIG row and no CUDA device: its row is no ordinal.+def test_mig_mode_without_instances_counts_as_mig(monkeypatch):+ out = "0, Disabled\n1, Enabled\n"+ monkeypatch.setattr(nvidia, "get_mig_gpu_indices_or_none", lambda: set())+ monkeypatch.setattr(nvidia, "_mig_mode_entry", None)+ monkeypatch.setattr(+ nvidia.gpu_query,+ "run_nvidia_smi",+ lambda argv, **kw: types.SimpleNamespace(returncode = 0, stdout = out),+ )+ assert hw._nvidia_mig_gpu_indices_or_none() == {1}+++ "out, expected",+ [("0, [N/A]\n1, Disabled\n", set()), ("", None), ("Field is not valid\n", None)],+ ids = ["no_mig", "empty", "unsupported"],+)+def test_mig_mode_query_parsing(monkeypatch, out, expected):+ monkeypatch.setattr(nvidia, "_mig_mode_entry", None)+ monkeypatch.setattr(+ nvidia.gpu_query,+ "run_nvidia_smi",+ lambda argv, **kw: types.SimpleNamespace(returncode = 0, stdout = out),+ )+ assert nvidia.get_mig_mode_gpu_indices_or_none() == expected+++# The event-loop gate answers from memory and never calls get_device(), which waits on _DETECT_LOCK.+ "mask, count, expected",+ [+ (None, 2, True),+ (None, 1, False),+ ("0,1", None, True),+ ("1", None, False),+ ("0,0", None, False),+ ("0,,1", None, False),+ ("", None, False),+ ],+)+def test_cached_gate_never_calls_get_device(monkeypatch, mask, count, expected):+ settled = threading.Event()+ settled.set()+ monkeypatch.setattr(hw, "DETECTION_COMPLETE", settled)+ monkeypatch.setattr(hw, "DEVICE", DeviceType.CUDA)+ monkeypatch.setattr(hw, "IS_ROCM", False)+ monkeypatch.setattr(hw, "_physical_gpu_count", count)++ def _blocked():+ raise AssertionError("get_device() on the event loop")++ monkeypatch.setattr(hw, "get_device", _blocked)+ for name in ("CUDA_VISIBLE_DEVICES", "HIP_VISIBLE_DEVICES", "ROCR_VISIBLE_DEVICES"):+ monkeypatch.delenv(name, raising = False)+ if mask is not None:+ monkeypatch.setenv("CUDA_VISIBLE_DEVICES", mask)+ assert dd.auto_cuda_ranking_possible_cached() is expecteddiff --git a/studio/backend/tests/test_media_auto_gpu_ordinary_host.py b/studio/backend/tests/test_media_auto_gpu_ordinary_host.pyindex c94a87ec323..a207037f6d9 100644--- a/studio/backend/tests/test_media_auto_gpu_ordinary_host.py+++ b/studio/backend/tests/test_media_auto_gpu_ordinary_host.py@@ -177,6 +177,8 @@ def test_route_auto_still_ranks_on_a_multi_gpu_cuda_host(monkeypatch):from routes import inference as routes_ordinary(monkeypatch, visible = (0, 1))+ # The event-loop gate reads live detection state; defer to the worker gate _ordinary stubs.+ monkeypatch.setattr(dd, "auto_cuda_ranking_possible_cached", lambda: None)targets = _counting_target(monkeypatch, dd)ranks = _counting_rank(monkeypatch)@@ -398,6 +400,11 @@ def test_catalog_refresh_ranks_once_on_mixed_or_unknown_cards(monkeypatch, ident],)def test_cached_gate_defers_anything_that_could_probe(monkeypatch, device, count, mask, cached):+ import threading++ settled = threading.Event()+ settled.set()+ monkeypatch.setattr(hw, "DETECTION_COMPLETE", settled)monkeypatch.setattr(hw, "IS_ROCM", False)monkeypatch.setattr(hw, "DEVICE", device)monkeypatch.setattr(hw, "_physical_gpu_count", count)@@ -496,10 +503,15 @@ def test_mig_listing_parses_slices():from utils.hardware import nvidiaout = "GPU 0: A100 (UUID: GPU-a)\n MIG 3g.40gb Device 0: (UUID: MIG-x)\nGPU 1: A100 (UUID: GPU-b)\n"- with _patch.object(- nvidia.gpu_query,- "run_nvidia_smi",- lambda argv, **_k: types.SimpleNamespace(returncode = 0, stdout = out),+ with (+ _patch.object(+ nvidia.gpu_query,+ "run_nvidia_smi",+ lambda argv, **_k: types.SimpleNamespace(returncode = 0, stdout = out),+ ),+ _patch.object(nvidia.gpu_query, "enabled", lambda: False),+ _patch.object(nvidia, "_mig_entry", None),+ _patch.object(nvidia, "get_mig_mode_gpu_indices_or_none", lambda: set()),):assert hw._nvidia_mig_gpu_indices_or_none() == {0}diff --git a/studio/backend/tests/test_media_auto_gpu_probe_caches.py b/studio/backend/tests/test_media_auto_gpu_probe_caches.pynew file mode 100644index 00000000000..9fceca16e89--- /dev/null+++ b/studio/backend/tests/test_media_auto_gpu_probe_caches.py@@ -0,0 +1,79 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Automatic GPU placement probes: failures are cached, comma names parse, MIG discovery is shared."""++import subprocess++from utils.hardware import gpu_query, hardware as hw, nvidia+++def test_failed_bus_id_join_is_not_respawned(monkeypatch):+ calls = []++ def _rows():+ calls.append(1)+ return None++ monkeypatch.setattr(nvidia, "get_cuda_ordinal_smi_rows", _rows)+ monkeypatch.setattr(hw, "_cuda_ordinal_rows_cache", {})+ monkeypatch.setenv("CUDA_VISIBLE_DEVICES", "0,1")+ monkeypatch.setenv("CUDA_DEVICE_ORDER", "FASTEST_FIRST")+ for _ in range(3):+ assert hw._smi_rows_for_cuda_ordinals([0, 1]) is None+ assert len(calls) == 1+ # Hardware re-detection retires the negative answer.+ monkeypatch.setattr(gpu_query, "_static_gen", gpu_query._static_gen + 1)+ hw._smi_rows_for_cuda_ordinals([0, 1])+ assert len(calls) == 2+++def _smi(+ stdout,+ returncode = 0,+ calls = None,+):+ def _run(argv, **_kw):+ if calls is not None:+ calls.append(list(argv[1:]))+ return subprocess.CompletedProcess(argv, returncode, stdout, "")++ return _run+++def test_card_identity_keeps_a_name_with_commas(monkeypatch):+ out = (+ "0, NVIDIA Example GPU, 2-slot, 81559 MiB, 9.0, 1980 MHz\n"+ "1, NVIDIA Example GPU, 2-slot, 81559 MiB, 9.0, 1980 MHz\n"+ )+ monkeypatch.setattr(gpu_query, "run_nvidia_smi", _smi(out))+ ids = nvidia.get_card_identities()+ assert ids[0] == ("NVIDIA Example GPU, 2-slot", "81559 MiB", "9.0", "1980 MHz")+ assert ids[0] == ids[1]+++def test_card_identity_plain_names_unchanged(monkeypatch):+ out = "0, NVIDIA H100 80GB HBM3, 81559 MiB, 9.0, 1980 MHz\n1, NVIDIA A100-SXM4-40GB, 40960 MiB, 8.0, 1410 MHz\n"+ monkeypatch.setattr(gpu_query, "run_nvidia_smi", _smi(out))+ assert nvidia.get_card_identities() == {+ 0: ("NVIDIA H100 80GB HBM3", "81559 MiB", "9.0", "1980 MHz"),+ 1: ("NVIDIA A100-SXM4-40GB", "40960 MiB", "8.0", "1410 MHz"),+ }+++def test_failed_mig_listing_backs_off(monkeypatch):+ calls = []+ monkeypatch.setattr(gpu_query, "run_nvidia_smi", _smi("", returncode = 9, calls = calls))+ monkeypatch.setattr(nvidia, "_mig_entry", None)+ for _ in range(3):+ assert hw._nvidia_mig_gpu_indices_or_none() is None+ assert sum(1 for c in calls if c == ["-L"]) == 1+++def test_mig_listing_answer(monkeypatch):+ out = "GPU 0: NVIDIA H100 (UUID: GPU-0)\nGPU 1: NVIDIA H100 (UUID: GPU-1)\n MIG 3g.40gb Device 0: (UUID: MIG-1)\n"+ monkeypatch.setattr(gpu_query, "run_nvidia_smi", _smi(out))+ monkeypatch.setattr(gpu_query, "enabled", lambda: False)+ monkeypatch.setattr(nvidia, "_mig_entry", None)+ monkeypatch.setattr(nvidia, "get_mig_mode_gpu_indices_or_none", lambda: set())+ assert hw._nvidia_mig_gpu_indices_or_none() == {1}diff --git a/studio/backend/utils/hardware/hardware.py b/studio/backend/utils/hardware/hardware.pyindex ea473d4f104..bc4cb32f0ec 100644--- a/studio/backend/utils/hardware/hardware.py+++ b/studio/backend/utils/hardware/hardware.py@@ -2098,36 +2098,24 @@ def _cuda_cards_identical(gpu_ids: Optional[list[int]] = None) -> Optional[bool]def _nvidia_mig_gpu_indices_or_none() -> Optional[set[int]]:- """Physical indices of NVIDIA cards with MIG instances, from ``nvidia-smi -L``, or None when the- listing failed or came back empty (unknown, unlike a confirmed set with no MIG card)."""+ """Physical indices of NVIDIA cards with MIG instances or MIG mode on (an instance-less one has no+ CUDA device, so its row is no ordinal either), or None when discovery is unknown (a listing failed or+ came back empty, unlike a confirmed set with no MIG card). Shares nvidia's caches, so a failed+ listing backs off instead of re-running nvidia-smi per call."""try:from . import nvidia- result = nvidia.gpu_query.run_nvidia_smi(- [nvidia._nvidia_smi_executable(), "-L"],- capture_output = True,- text = True,- encoding = "utf-8",- errors = "replace",- timeout = 5,- env = nvidia.child_env_without_native_path_secret(),- **nvidia._windows_hidden_subprocess_kwargs(),- )++ instances = nvidia.get_mig_gpu_indices_or_none()+ if instances is None:+ return None+ mode = nvidia.get_mig_mode_gpu_indices_or_none()+ return None if mode is None else instances | modeexcept Exception:return None- if result.returncode != 0 or not isinstance(result.stdout, str) or not result.stdout.strip():- return None- indices: set[int] = set()- current: Optional[int] = None- for line in result.stdout.splitlines():- if line.startswith("GPU "):- head = line[4:].split(":", 1)[0].strip()- current = int(head) if head.isdecimal() else None- elif current is not None and line.strip().startswith("MIG "):- indices.add(current)- return indices-_cuda_ordinal_rows_cache: Dict[tuple, list[int]] = {}+_cuda_ordinal_rows_cache: Dict[tuple, tuple[Optional[list[int]], float]] = {}+_CUDA_ORDINAL_ROWS_RETRY_S = 300.0def _smi_rows_for_cuda_ordinals(parent_ids: list[int]) -> Optional[Dict[str, Any]]:@@ -2145,17 +2133,20 @@ def _smi_rows_for_cuda_ordinals(parent_ids: list[int]) -> Optional[Dict[str, Anyos.environ.get("CUDA_DEVICE_ORDER"),gpu_query._static_gen,)- rows = _cuda_ordinal_rows_cache.get(key)- if rows is None:+ hit = _cuda_ordinal_rows_cache.get(key)+ if hit is None or (hit[0] is None and time.monotonic() - hit[1] >= _CUDA_ORDINAL_ROWS_RETRY_S):try:from . import nvidiarows = nvidia.get_cuda_ordinal_smi_rows()except Exception:rows = None- if rows is None:- return None+ # A failed join is remembered too (briefly): each attempt spawns a driver-API child with a 15 s timeout._cuda_ordinal_rows_cache.clear()- _cuda_ordinal_rows_cache[key] = rows+ _cuda_ordinal_rows_cache[key] = (rows, time.monotonic())+ else:+ rows = hit[0]+ if rows is None:+ return Noneif not rows: # an integrated card: keep the pool-aware torch telemetryreturn Noneif len(rows) != len(parent_ids) or len(set(rows)) != len(rows):diff --git a/studio/backend/utils/hardware/nvidia.py b/studio/backend/utils/hardware/nvidia.pyindex 4c6676ab6fd..8be09ea2b09 100644--- a/studio/backend/utils/hardware/nvidia.py+++ b/studio/backend/utils/hardware/nvidia.py@@ -240,6 +240,53 @@ def _parse_mig_gpu_indices(stdout: Any) -> frozenset[int]:return frozenset(indices)+_mig_mode_entry: Optional[tuple[int, float, Optional[frozenset[int]]]] = None+++def get_mig_mode_gpu_indices_or_none() -> Optional[set[int]]:+ """Physical indices of cards in MIG mode, with instances or not, or None when the query fails.+ A MIG-mode card with no instances has no ``-L`` MIG row and no CUDA device either."""+ global _mig_mode_entry+ entry = _mig_mode_entry+ if entry is not None and entry[0] == gpu_query._static_gen:+ ttl = gpu_query.ttl_for(gpu_query.STATIC)+ if time.monotonic() - entry[1] < (+ ttl if entry[2] is not None else min(ttl, _MIG_FAILURE_RETRY_S)+ ):+ return None if entry[2] is None else set(entry[2])+ gen, indices = gpu_query._static_gen, None+ try:+ result = gpu_query.run_nvidia_smi(+ [+ _nvidia_smi_executable(),+ "--query-gpu=index,mig.mode.current",+ "--format=csv,noheader",+ ],+ capture_output = True,+ text = True,+ encoding = "utf-8",+ errors = "replace",+ timeout = 5,+ env = child_env_without_native_path_secret(),+ **_windows_hidden_subprocess_kwargs(),+ )+ stdout = getattr(result, "stdout", None)+ if getattr(result, "returncode", 1) == 0 and isinstance(stdout, str) and stdout.strip():+ found: set[int] = set()+ for line in stdout.splitlines():+ parts = [part.strip() for part in line.split(",")]+ if len(parts) != 2 or not parts[0].isdecimal():+ found = None+ break+ if parts[1].lower() == "enabled":+ found.add(int(parts[0]))+ indices = None if found is None else frozenset(found)+ except Exception:+ indices = None+ _mig_mode_entry = (gen, time.monotonic(), indices)+ return None if indices is None else set(indices)++def get_mig_gpu_indices() -> set[int]:"""Physical indices of GPUs with MIG instances (indented ``MIG`` rows under their``GPU N:`` row in ``nvidia-smi -L``). CUDA sees such a card as one slice, so its@@ -613,10 +660,11 @@ def get_card_identities() -> dict[int, tuple[str, ...]]:return {}identities: dict[int, tuple[str, ...]] = {}for line in result.stdout.strip().splitlines():- index, *fields = (part.strip() for part in line.split(","))- if not index.isdigit() or len(fields) != 4:+ parts = [part.strip() for part in line.split(",")]+ if len(parts) < 5 or not parts[0].isdigit():return {}- identities[int(index)] = tuple(fields)+ # nvidia-smi csv does not quote: a name holding commas spans several parts, so rejoin it.+ identities[int(parts[0])] = (", ".join(parts[1:-3]), *parts[-3:])return identities