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 image/video loads pick the freest GPU, and GPU picks respect what each card can run (#13928)
Daniel Hanc1dc27300216
diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.pyindex da47d3fe037..781d40161e1 100644--- a/studio/backend/core/inference/diffusion.py+++ b/studio/backend/core/inference/diffusion.py@@ -98,6 +98,7 @@ from .diffusion_device import (install_frame_pad_fix,pin_cuda_ordinal,placed_cuda_ordinal,+ resolve_auto_cuda_ordinal,resolve_diffusion_device_target,resolve_selected_cuda_ordinal,)@@ -3828,8 +3829,8 @@ class DiffusionBackend:# on another.if gpu_ordinal is None:gpu_ordinal = (- resolve_selected_cuda_ordinal(gpu_ids)- if gpu_ids and resolve_diffusion_device_target().device == "cuda"+ (resolve_selected_cuda_ordinal(gpu_ids) if gpu_ids else resolve_auto_cuda_ordinal())+ if resolve_diffusion_device_target().device == "cuda"else None)fam = self.validate_load_request(diff --git a/studio/backend/core/inference/diffusion_device.py b/studio/backend/core/inference/diffusion_device.pyindex 6da53836cc5..eacda51bb00 100644--- a/studio/backend/core/inference/diffusion_device.py+++ b/studio/backend/core/inference/diffusion_device.py@@ -13,6 +13,7 @@ from __future__ import annotationsimport osfrom contextlib import contextmanager+from contextvars import ContextVarfrom dataclasses import dataclassfrom typing import Any, Optional@@ -386,6 +387,78 @@ def resolve_selected_cuda_ordinal(return max(ordinals, key = lambda ordinal: (_free_vram(ordinal), -ordinal))+_UNPLANNED = object()+# Set by an auto-switch for its locality check and the load it starts (both copy this context), so free VRAM+# moving in between cannot rank the load onto a card whose precision picks an artifact the check never saw.+# A pinned None is a decision too (keep the current device), so the backend fallbacks honour it.+_PLANNED_ORDINAL: ContextVar[Any] = ContextVar("media_planned_gpu_ordinal", default = _UNPLANNED)++# Free-VRAM readings this close are noise, so the lower ordinal keeps an idle uniform host on card 0.+_AUTO_FREE_TIE_BYTES = 256 * 1024**2+++def resolve_auto_cuda_ordinal() -> Optional[int]:+ """The torch ordinal an AUTOMATIC diffusion load should run on, or None to keep the current device.++ Bare "cuda" is the current device, PCI slot 0 under Studio's PCI_BUS_ID order, so on a multi-GPU host+ the load budgeted against that card alone and offloaded to RAM beside an idle bigger one (#8235). Neither+ engine shards, so this picks ONE card: most free VRAM, like ``auto_select_gpu_ids`` and Ollama's+ single-GPU fit, ties to the lowest ordinal. Read from nvidia-smi alone (no CUDA context per card, so no+ torch fallback) and keyed through the parent-visible list, so a mask keeps deciding which cards exist.++ None on one visible card (unchanged), a UUID/MIG mask (no physical ids), ROCm (an APU's free reading is the+ shared host pool, which would outrank a discrete card), a CUDA order other than nvidia-smi's (its rows are+ then not torch's ordinals), an integrated GPU (its rows are a carve-out or N/A, and its real budget is the+ shared host pool), missing nvidia-smi telemetry and any failure. Never raises. Only cards at least as+ capable as the current one compete. A pinned plan (auto-switch, or the route's own ranking) is returned+ as is.+ """+ planned = _PLANNED_ORDINAL.get()+ if planned is not _UNPLANNED:+ return planned+ try:+ from utils.hardware import hardware as hw++ if hw.IS_ROCM:+ return None+ visible = hw.get_parent_visible_gpu_ids()+ if len(visible) < 2 or not hw._cuda_order_matches_smi():+ return None+ if hw._integrated_cuda_rows(visible)[0]:+ return None+ result = hw._smi_visible_utilization(hw._get_parent_visible_gpu_spec())+ devices = (result or {}).get("devices", [])+ from utils.hardware import nvidia++ caps = nvidia.get_compute_capabilities()+ except Exception: # noqa: BLE001 -- automatic placement falls back to the current device+ return None+ # CUDA stops a mask at an entry naming no card ("0,99,1" is just 0), so later ids are not ordinals.+ if not {d.get("index") for d in devices} >= set(visible):+ return None+ # Only cards at least as capable as the current one (ordinal 0): a freer older card can lack the+ # installed torch's kernels or a precision the request needs, where the current card works today.+ floor = caps.get(visible[0])+ if floor is None:+ return None+ free_by_ordinal: dict[int, float] = {}+ for device in devices:+ index, total, used = (+ device.get("index"),+ device.get("vram_total_gb"),+ device.get("vram_used_gb"),+ )+ if index not in visible or total is None or used is None:+ continue+ if caps.get(index, (0, 0)) < floor:+ continue+ free_by_ordinal[visible.index(index)] = max(float(total) - float(used), 0.0) * 1024**3+ if not free_by_ordinal:+ return None+ best = max(free_by_ordinal.values())+ return min(o for o, free in free_by_ordinal.items() if best - free <= _AUTO_FREE_TIE_BYTES)++@contextmanagerdef diffusion_device_scope(ordinal: Optional[int]):"""Make ``ordinal`` the current CUDA device for the block, then restore the previous one.diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.pyindex 9bbe43eea85..662c7ef117d 100644--- a/studio/backend/core/inference/llama_cpp.py+++ b/studio/backend/core/inference/llama_cpp.py@@ -13748,11 +13748,19 @@ class LlamaCppBackend:return {}@classmethod- def _cuda_sm_gate_error(cls, binary: Optional[str] = None) -> Optional[str]:+ def _cuda_sm_gate_error(+ cls,+ binary: Optional[str] = None,+ gpu_indices: Optional[Iterable[int]] = None,+ ) -> Optional[str]:"""Error message when every visible GPU is OLDER than the oldest arch theinstalled CUDA bundle was built for, or None to proceed. Fails open onunknown coverage or caps.+ ``gpu_indices`` (physical ids the child is pinned to) tightens "every+ visible" to "any pinned": the child places work on each pinned card, so one+ too-old card aborts the load even beside a supported one.+Only the too-old direction is broken. The bundles compile plain archnumbers, so each fatbin carries PTX beside its cubins, and the driver JITsthat PTX forward onto a newer card; ggml_cuda_highest_compiled_arch picks@@ -13770,7 +13778,12 @@ class LlamaCppBackend:return Nonecaps = cls._cuda_compute_caps()oldest = min(supported)- if not caps or any(sm >= oldest for sm in caps.values()):+ if gpu_indices is not None:+ pinned = {int(i) for i in gpu_indices}+ caps = {idx: sm for idx, sm in caps.items() if idx in pinned and sm < oldest}+ elif any(sm >= oldest for sm in caps.values()):+ return None+ if not caps:return Nonepresent = ", ".join(f"GPU {idx} is sm_{sm}" for idx, sm in sorted(caps.items()))# The updater cannot replace a pinned LLAMA_SERVER_PATH or a llama-server@@ -13781,6 +13794,30 @@ class LlamaCppBackend:f"newer GPU, so {cls._runtime_remedy(binary)}.")+ @classmethod+ def _cuda_sm_gate_keep(+ cls, binary: Optional[str], gpus: list[tuple[int, int, int]]+ ) -> list[tuple[int, int, int]]:+ """``gpus`` minus the CUDA cards older than the installed bundle's oldest+ arch, so auto placement cannot pin one beside a supported card (RTX 4090 ++ GTX 1060 under an sm_75+ build). Unchanged on unknown coverage or caps, and+ when no card survives: the gate then refuses with its own message."""+ supported = cls._installed_llama_cuda_sms(binary)+ if supported is None or not gpus:+ return gpus+ caps = cls._cuda_compute_caps()+ oldest = min(supported)+ kept = [g for g in gpus if caps.get(g[0], oldest) >= oldest]+ if not kept or len(kept) == len(gpus):+ return gpus+ for idx, _free, _total in gpus:+ if caps.get(idx, oldest) < oldest:+ logger.warning(+ f"Skipping GPU {idx} (sm_{caps[idx]}): installed llama.cpp "+ f"build only has GPU code for sm_{oldest} and newer"+ )+ return kept+@classmethoddef _arch_gate_survivors(cls, binary: Optional[str] = None) -> list[int]:"""Physical ids the ROCm arch gate leaves, or [] when there is nothing to@@ -15135,6 +15172,8 @@ class LlamaCppBackend:gpus.sort(key = lambda g: g[0])if gpus:LlamaCppBackend._GPU_IDS_ARE_PCI_INDICES = True+ if for_llama_server:+ gpus = LlamaCppBackend._cuda_sm_gate_keep(binary, gpus)# The CLI row is the carve-out, not the pool. Discrete rows unchanged.return LlamaCppBackend._widen_integrated_cuda_rows(gpus)except Exception as e:@@ -15144,6 +15183,8 @@ class LlamaCppBackend:nvml_gpus = LlamaCppBackend._get_gpu_memory_nvml()if nvml_gpus:LlamaCppBackend._GPU_IDS_ARE_PCI_INDICES = True+ if for_llama_server:+ nvml_gpus = LlamaCppBackend._cuda_sm_gate_keep(binary, nvml_gpus)# nvidia-smi IS NVML: same carve-out, same PCI indexing, same correction.return LlamaCppBackend._widen_integrated_cuda_rows(nvml_gpus)@@ -31817,8 +31858,14 @@ class LlamaCppBackend:# read as GPU-bearing there, only the resolved argv knows. Still# before every spawn below and outside the fit's try/except, so the# refusal cannot be swallowed into the --fit on fallback.+ # Pinned ids are checked against nvidia-smi's caps only in its index space+ # (torch-fallback ordinals are not); otherwise "any visible", as before.+ _sm_gate_ids_are_pci = not is_vulkan_backend and _p2p_ids_are_pciif not (_cpu_only_zero_offload or _arch_gate_forced_cpu):- _sm_gate = self._cuda_sm_gate_error(binary)+ # Pinned launches check the pinned cards, not "any visible".+ _sm_gate = self._cuda_sm_gate_error(+ binary, gpu_indices if _sm_gate_ids_are_pci else None+ )if _sm_gate:raise RuntimeError(_sm_gate)# The arch gate emptying the pool lands here for the same reason@@ -31940,6 +31987,11 @@ class LlamaCppBackend:"numbering; fitted the pinned mask to them: %s",_companion_widen,)+ # The widened mask can add a card the gate above never saw.+ if _sm_gate_ids_are_pci:+ _sm_gate = self._cuda_sm_gate_error(binary, _pin_ids)+ if _sm_gate:+ raise RuntimeError(_sm_gate)self._emit_child_gpu_visibility(env,LlamaCppBackend._child_visibility_for(_pin_ids),diff --git a/studio/backend/core/inference/media_auto_switch.py b/studio/backend/core/inference/media_auto_switch.pyindex c0647a7c7fa..520d1f4028c 100644--- a/studio/backend/core/inference/media_auto_switch.py+++ b/studio/backend/core/inference/media_auto_switch.py@@ -35,6 +35,7 @@ import timefrom typing import Any, Callable, Optionalfrom core.inference.gpu_arbiter import DIFFUSION, VIDEO+from core.inference import media_localityfrom core.inference.media_locality import is_edit_only, missing_download_bytesfrom core.inference.media_model_index import (IMAGE_TASK,@@ -340,6 +341,15 @@ async def _gated_start_load(openai_errors = openai_errors,):raise busy(kind, openai_errors)+ # Ranked once: the check below and the load it starts both use this card.+ planned = media_locality.pin_planned_gpu_ordinal(+ await bounded(+ asyncio.to_thread(media_locality.plan_gpu_ordinal),+ deadline,+ kind = kind,+ openai_errors = openai_errors,+ )+ )await _require_local(owner,pick,@@ -352,6 +362,7 @@ async def _gated_start_load(# begin_load, and holding both media gates and chat's that long blocks every unrelated request. On expiry# the load keeps going without them.setup = asyncio.ensure_future(_start_load(owner, pick, current_subject, hf_token))+ media_locality._PLANNED_ORDINAL.reset(planned) # the task copied the contextsetup.add_done_callback(_consume_detached_error)with contextlib.suppress(asyncio.TimeoutError):try:diff --git a/studio/backend/core/inference/media_locality.py b/studio/backend/core/inference/media_locality.pyindex e186ed209a3..0f379fe888f 100644--- a/studio/backend/core/inference/media_locality.py+++ b/studio/backend/core/inference/media_locality.py@@ -21,6 +21,8 @@ from dataclasses import replacefrom pathlib import Pathfrom typing import Any, Optional+# The auto-switch pin lives in diffusion_device, so every resolve_auto_cuda_ordinal caller sees it.+from core.inference.diffusion_device import _PLANNED_ORDINAL, _UNPLANNEDfrom core.inference.gpu_arbiter import DIFFUSION, VIDEOfrom core.inference.media_model_index import MediaModelPickfrom core.inference.media_switch_backends import backend_for@@ -253,20 +255,34 @@ def planners_for(owner: str, pick: MediaModelPick) -> list:return [engine_for(name) for name in names]+def pin_planned_gpu_ordinal(ordinal: Optional[int]) -> Any:+ """Carry ``ordinal`` into this context's plan and load; returns the reset token."""+ return _PLANNED_ORDINAL.set(ordinal)+++def planned_gpu_ordinal() -> tuple[bool, Optional[int]]:+ """(True, ordinal) when this context carries a pinned automatic ordinal, else (False, None)."""+ ordinal = _PLANNED_ORDINAL.get()+ return (False, None) if ordinal is _UNPLANNED else (True, ordinal)++def plan_gpu_ordinal() -> Optional[int]:"""The card the load route will rank for itself, so the plan sizes the same file set.Automatic precision is chosen per card, and a different card can select a different hostedpre-quantized artifact, which a plan plotted against the default device would omit."""+ pinned, ordinal = planned_gpu_ordinal()+ if pinned:+ return ordinalfrom core.inference.diffusion_device import (+ resolve_auto_cuda_ordinal,resolve_diffusion_device_target,- resolve_selected_cuda_ordinal,)if resolve_diffusion_device_target().device != "cuda":return None- return resolve_selected_cuda_ordinal(None)+ return resolve_auto_cuda_ordinal()def _pipeline_components_present(root: Path) -> bool:@@ -539,6 +555,8 @@ __all__ = ["is_edit_only","missing_download_bytes","normalized_pick",+ "pin_planned_gpu_ordinal","plan_gpu_ordinal",+ "planned_gpu_ordinal","planners_for",]diff --git a/studio/backend/core/inference/sd_cpp_backend.py b/studio/backend/core/inference/sd_cpp_backend.pyindex c97373226cb..7709a14606b 100644--- a/studio/backend/core/inference/sd_cpp_backend.py+++ b/studio/backend/core/inference/sd_cpp_backend.py@@ -34,6 +34,7 @@ from typing import Any, Optionalfrom core.inference.diffusion_auto_policy import build_resolved_record, format_generation_for_logfrom core.inference.diffusion_compat import flux2_inner_dim_for_pickfrom core.inference.diffusion_device import (+ resolve_auto_cuda_ordinal,resolve_diffusion_device_target,resolve_selected_cuda_ordinal,)@@ -2934,11 +2935,13 @@ class SdCppDiffusionBackend:# engine is the one engine that would drop the pick silently. Re-ranked only when nobody has, so a# route-resolved winner is never second-guessed against free VRAM that has moved since.if gpu_ordinal is None:- gpu_ordinal = (- resolve_selected_cuda_ordinal(gpu_ids)- if gpu_ids and resolve_diffusion_device_target().device == "cuda"- else None- )+ # Automatic ranks the torch cards too, unless sd.cpp runs on one torch cannot see.+ if off_torch is not None or resolve_diffusion_device_target().device != "cuda":+ gpu_ordinal = None+ elif gpu_ids:+ gpu_ordinal = resolve_selected_cuda_ordinal(gpu_ids)+ else:+ gpu_ordinal = resolve_auto_cuda_ordinal()if not gguf_filename:raise ValueError("gguf_filename is required: the native engine loads single-file GGUF checkpoints only."diff --git a/studio/backend/core/inference/video.py b/studio/backend/core/inference/video.pyindex 9671e50a6ae..1619ab708df 100644--- a/studio/backend/core/inference/video.py+++ b/studio/backend/core/inference/video.py@@ -100,6 +100,7 @@ from .diffusion_device import (install_rocm_vae_bf16_decode,pin_cuda_ordinal,placed_cuda_ordinal,+ resolve_auto_cuda_ordinal,resolve_diffusion_device_target,resolve_selected_cuda_ordinal,)@@ -3379,8 +3380,8 @@ class VideoBackend:# preflight and here, so resolving twice can approve a scheme against one card and place the weights on another.if gpu_ordinal is None:gpu_ordinal = (- resolve_selected_cuda_ordinal(gpu_ids)- if gpu_ids and resolve_diffusion_device_target().device == "cuda"+ (resolve_selected_cuda_ordinal(gpu_ids) if gpu_ids else resolve_auto_cuda_ordinal())+ if resolve_diffusion_device_target().device == "cuda"else None)fam = self.validate_load_request(diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex 99974fa639f..1327837179a 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -49157,16 +49157,29 @@ async def _selected_gpu_ordinal(gpu_ids, *, allow_ranking: bool = True) -> Optiotrainer holds the cards: the ids are still validated and translated (mask plus nvidia-smi, noCUDA context), so a bad pick is refused at the plan rather than tens of gigabytes later."""+ from core.inference import diffusion_devicefrom core.inference.diffusion_device import (resolve_diffusion_device_target,resolve_selected_cuda_ordinal,)- if not gpu_ids:+ if not gpu_ids and not allow_ranking:return Nonedevice = await asyncio.to_thread(lambda: resolve_diffusion_device_target().device)if device != "cuda":return None+ if not gpu_ids:+ # An auto-switch load uses the card its locality check planned against.+ from core.inference.media_locality import planned_gpu_ordinal++ pinned, ordinal = planned_gpu_ordinal()+ if pinned:+ return ordinal+ # Automatic ranks the visible cards too (#8235); the current device is PCI slot 0.+ # Pinned for this request, so begin_load's own fallback reuses it (None included).+ ordinal = await asyncio.to_thread(diffusion_device.resolve_auto_cuda_ordinal)+ diffusion_device._PLANNED_ORDINAL.set(ordinal)+ return ordinal# The keyword only when it is not the default, so the ordinary path calls the resolver with# the same one-argument shape it always had (a monkeypatched seam still fits it).if allow_ranking:diff --git a/studio/backend/tests/test_cuda_sm_gate_pinned.py b/studio/backend/tests/test_cuda_sm_gate_pinned.pynew file mode 100644index 00000000000..f06da964f2a--- /dev/null+++ b/studio/backend/tests/test_cuda_sm_gate_pinned.py@@ -0,0 +1,136 @@+# 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 CUDA SM gate checks the GPUs a launch is PINNED to, not "any visible".++RTX 4090 (sm_89, PCI 0) + GTX 1060 (sm_61, PCI 1) under a bundle whose oldest+arch is sm_75: the 4090 passed the old any-visible check for a pick that also+put work on the 1060, and the child aborted ("no kernel image"). Auto placement+now leaves the 1060 out of the pool; an explicit pick naming it is refused up+front. Homogeneous and single-GPU hosts see no change."""++import json+import subprocess+import sys+import types++import pytest++from core.inference.llama_cpp import LlamaCppBackend++_CAPS = {0: 89, 1: 61}+++def _binary(tmp_path, sms = ("75", "80", "86", "89", "90", "120")):+ (tmp_path / "UNSLOTH_PREBUILT_INFO.json").write_text(+ json.dumps({"supported_sms": list(sms)}), encoding = "utf-8"+ )+ return str(tmp_path / "build" / "bin" / "llama-server")++[email protected](autouse = True)+def _host(monkeypatch):+ monkeypatch.setattr(LlamaCppBackend, "_is_vulkan_backend", staticmethod(lambda b = None: False))+ monkeypatch.setattr(+ LlamaCppBackend, "_is_unsloth_managed_binary", staticmethod(lambda _b: True)+ )+ monkeypatch.setattr(+ LlamaCppBackend, "_get_gpu_memory_amd_smi", staticmethod(lambda *a, **k: [])+ )+ monkeypatch.setitem(sys.modules, "torch", None)+ monkeypatch.delenv("CUDA_VISIBLE_DEVICES", raising = False)+ monkeypatch.setenv("CUDA_DEVICE_ORDER", "PCI_BUS_ID")+++def _smi(+ monkeypatch,+ caps = _CAPS,+ free = {0: 20000, 1: 5800},+):+ def _run(cmd, **_kwargs):+ query = " ".join(cmd)+ if "compute_cap" in query:+ out = "\n".join(f"{i}, {sm // 10}.{sm % 10}" for i, sm in caps.items())+ else:+ out = "\n".join(f"{i}, {free[i]}, 24564" for i in caps)+ return types.SimpleNamespace(returncode = 0, stdout = out + "\n")++ monkeypatch.setattr(subprocess, "run", _run)+++class TestPinnedGate:+ def test_a_pin_including_the_old_card_is_refused(self, tmp_path, monkeypatch):+ _smi(monkeypatch)+ binary = _binary(tmp_path)+ error = LlamaCppBackend._cuda_sm_gate_error(binary, [0, 1])+ assert error is not None and "GPU 1 is sm_61" in error+ assert "GPU 0" not in error+ assert LlamaCppBackend._cuda_sm_gate_error(binary, [1]) is not None++ def test_a_pin_on_the_new_card_proceeds_and_unpinned_keeps_any_visible(+ self, tmp_path, monkeypatch+ ):+ _smi(monkeypatch)+ binary = _binary(tmp_path)+ assert LlamaCppBackend._cuda_sm_gate_error(binary, [0]) is None+ # Unpinned, --fit on owns placement; refusing would over-refuse a working 4090.+ assert LlamaCppBackend._cuda_sm_gate_error(binary) is None+ _smi(monkeypatch, caps = {0: 61}, free = {0: 5800})+ assert LlamaCppBackend._cuda_sm_gate_error(binary) is not None+ assert LlamaCppBackend._cuda_sm_gate_error(binary, [0]) is not None++ def test_unknown_coverage_or_caps_fail_open(self, tmp_path, monkeypatch):+ _smi(monkeypatch)+ assert LlamaCppBackend._cuda_sm_gate_error(str(tmp_path / "llama-server"), [1]) is None+ monkeypatch.setattr(LlamaCppBackend, "_cuda_compute_caps", staticmethod(lambda: {}))+ assert LlamaCppBackend._cuda_sm_gate_error(_binary(tmp_path), [1]) is None+++class TestAutoPool:+ def test_auto_pool_drops_the_card_the_build_cannot_run(self, tmp_path, monkeypatch):+ _smi(monkeypatch)+ binary = _binary(tmp_path)+ assert [g[0] for g in LlamaCppBackend._get_gpu_memory(binary, for_llama_server = True)] == [0]+ # Off the llama-server path (embeddings via torch) every card stays.+ assert [g[0] for g in LlamaCppBackend._get_gpu_memory(binary)] == [0, 1]+ # Every card too old: the pool stays, and the gate refuses with its message.+ _smi(monkeypatch, caps = {0: 61, 1: 61}, free = {0: 5800, 1: 5800})+ assert [g[0] for g in LlamaCppBackend._get_gpu_memory(binary, for_llama_server = True)] == [+ 0,+ 1,+ ]++ def test_homogeneous_and_ptx_forward_hosts_are_unchanged(self, tmp_path, monkeypatch):+ _smi(monkeypatch, caps = {0: 89, 1: 86}, free = {0: 20000, 1: 20000})+ binary = _binary(tmp_path)+ assert [g[0] for g in LlamaCppBackend._get_gpu_memory(binary, for_llama_server = True)] == [+ 0,+ 1,+ ]+ # A legacy sm_50-61 bundle JITs forward onto both: nothing is dropped.+ (tmp_path / "legacy").mkdir()+ legacy = _binary(tmp_path / "legacy", sms = ("50", "61"))+ _smi(monkeypatch)+ assert [g[0] for g in LlamaCppBackend._get_gpu_memory(legacy, for_llama_server = True)] == [+ 0,+ 1,+ ]+ assert LlamaCppBackend._cuda_sm_gate_error(legacy, [0, 1]) is None+++def test_the_launch_gate_receives_the_pinned_ids():+ import re+ from pathlib import Path++ import core.inference.llama_cpp as mod++ src = Path(mod.__file__).read_text(encoding = "utf-8")+ # Only ids in nvidia-smi's index space are checked against its caps (torch-fallback+ # ordinals are not), and a companion-widened mask is checked again.+ assert re.search(r"_sm_gate_ids_are_pci = not is_vulkan_backend and _p2p_ids_are_pci", src)+ assert re.search(+ r"self\._cuda_sm_gate_error\(\s*binary, gpu_indices if _sm_gate_ids_are_pci else None", src+ )+ widen = src[src.index("_pin_ids, _companion_widen = _widen_pin_ids_for_companion_devices(") :]+ widen = widen[: widen.index("self._emit_child_gpu_visibility(")]+ assert "self._cuda_sm_gate_error(binary, _pin_ids)" in widendiff --git a/studio/backend/tests/test_diffusion_auto_gpu.py b/studio/backend/tests/test_diffusion_auto_gpu.pynew file mode 100644index 00000000000..b43defe2e1a--- /dev/null+++ b/studio/backend/tests/test_diffusion_auto_gpu.py@@ -0,0 +1,234 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""#8235: an AUTOMATIC image / video load ranks the visible GPUs by free VRAM.++The picker on "auto" sends no gpu_ids, and bare "cuda" is the current device, PCI+slot 0 under Studio's PCI_BUS_ID order, so an 8 GB card 0 beside an idle 24 GB+card 1 budgeted the load against 8 GB and offloaded to RAM. Explicit picks and+masks keep winning; one visible card, UUID masks and ROCm are unchanged."""++import ast+import asyncio+import types+from pathlib import Path++import pytest++from core.inference import diffusion_device as dd+from utils.hardware import hardware as hw+++def _dev(index, total, used):+ return {"index": index, "vram_total_gb": total, "vram_used_gb": used}+++def _host(+ monkeypatch,+ visible,+ devices,+ rocm = False,+ order_matches = True,+ caps = None,+):+ from utils.hardware import nvidia++ if caps is None:+ caps = {d["index"]: (8, 6) for d in devices}+ monkeypatch.setattr(nvidia, "get_compute_capabilities", lambda: dict(caps))+ monkeypatch.setattr(hw, "IS_ROCM", rocm)+ monkeypatch.setattr(hw, "get_parent_visible_gpu_ids", lambda: list(visible))+ monkeypatch.setattr(hw, "_cuda_order_matches_smi", lambda: order_matches)+ monkeypatch.setattr(hw, "_integrated_cuda_rows", lambda ids: ({}, "index"))+ monkeypatch.setattr(hw, "_get_parent_visible_gpu_spec", lambda: {"numeric_ids": list(visible)})+ smi = {"available": True, "devices": devices}+ monkeypatch.setattr(hw, "_smi_visible_utilization", lambda spec: smi)+ monkeypatch.setattr(hw, "get_visible_gpu_utilization", lambda: smi)+++def test_auto_picks_the_card_with_the_most_free_vram(monkeypatch):+ _host(monkeypatch, [0, 1], [_dev(0, 8.0, 1.0), _dev(1, 24.0, 0.5)])+ assert dd.resolve_auto_cuda_ordinal() == 1+++def test_auto_maps_physical_ids_through_the_mask(monkeypatch):+ # CUDA_VISIBLE_DEVICES=5,2: physical 2 is torch ordinal 1.+ _host(monkeypatch, [5, 2], [_dev(2, 80.0, 0.0), _dev(5, 80.0, 70.0)])+ assert dd.resolve_auto_cuda_ordinal() == 1+++def test_auto_ties_keep_the_lowest_ordinal(monkeypatch):+ # An idle uniform host stays on card 0, MiB-level noise included.+ _host(monkeypatch, [0, 1, 2], [_dev(0, 80.0, 0.6), _dev(1, 80.0, 0.5), _dev(2, 80.0, 0.6)])+ assert dd.resolve_auto_cuda_ordinal() == 0+++ "visible, devices, rocm",+ [+ ([0], [_dev(0, 24.0, 1.0)], False), # one card: unchanged+ ([], [_dev(0, 24.0, 1.0), _dev(1, 24.0, 0.0)], False), # UUID/MIG mask+ ([0, 1], [_dev(0, 8.0, 7.0), _dev(1, 96.0, 0.0)], True), # ROCm APU pool+ ([0, 1], [], False), # no telemetry+ ],+)+def test_auto_keeps_the_current_device(monkeypatch, visible, devices, rocm):+ _host(monkeypatch, visible, devices, rocm = rocm)+ assert dd.resolve_auto_cuda_ordinal() is None+++def test_auto_never_raises(monkeypatch):+ _host(monkeypatch, [0, 1], [])++ def _boom(*_a):+ raise RuntimeError("nvidia-smi hung")++ monkeypatch.setattr(hw, "_smi_visible_utilization", _boom)+ assert dd.resolve_auto_cuda_ordinal() is None+++def test_auto_keeps_the_current_device_when_cuda_order_is_not_smi_order(monkeypatch):+ # CUDA_DEVICE_ORDER=FASTEST_FIRST: nvidia-smi rows are not torch ordinals, so no ranking.+ _host(monkeypatch, [0, 1], [_dev(0, 8.0, 1.0), _dev(1, 24.0, 0.5)], order_matches = False)+ assert dd.resolve_auto_cuda_ordinal() is None+++def test_auto_never_falls_back_to_torch_telemetry(monkeypatch):+ # No nvidia-smi: the hardware layer's torch fallback opens a CUDA context per card.+ _host(monkeypatch, [0, 1], [_dev(0, 8.0, 1.0), _dev(1, 24.0, 0.5)])+ monkeypatch.setattr(hw, "_smi_visible_utilization", lambda spec: None)+ assert dd.resolve_auto_cuda_ordinal() is None+++def _route(monkeypatch, device = "cuda"):+ from routes import inference as routes++ monkeypatch.setattr(+ dd, "resolve_diffusion_device_target", lambda: types.SimpleNamespace(device = device)+ )+ monkeypatch.setattr(dd, "resolve_auto_cuda_ordinal", lambda: 1)+ monkeypatch.setattr(dd, "resolve_selected_cuda_ordinal", lambda ids, **_k: min(ids))+ return routes._selected_gpu_ordinal+++def test_route_ranks_an_automatic_load(monkeypatch):+ resolve = _route(monkeypatch)+ assert asyncio.run(resolve(None)) == 1+ assert asyncio.run(resolve([])) == 1+++def test_route_explicit_pick_still_wins(monkeypatch):+ resolve = _route(monkeypatch)+ assert asyncio.run(resolve([0])) == 0+++def test_route_auto_stays_off_cuda_and_while_ranking_is_barred(monkeypatch):+ resolve = _route(monkeypatch, device = "mps")+ assert asyncio.run(resolve(None)) is None+ resolve = _route(monkeypatch)+ assert asyncio.run(resolve(None, allow_ranking = False)) is None+++def test_auto_keeps_the_current_device_beside_an_integrated_gpu(monkeypatch):+ # DGX Spark-class row: nvidia-smi says N/A (or a carve-out) for a part whose budget is host RAM.+ _host(monkeypatch, [0, 1], [_dev(0, None, None), _dev(1, 24.0, 0.5)])+ monkeypatch.setattr(+ hw, "_integrated_cuda_rows", lambda ids: ({0: {"total_gb": 121.0}}, "index")+ )+ assert dd.resolve_auto_cuda_ordinal() is None+++def test_backend_fallback_honours_a_pinned_none(monkeypatch):+ # The auto-switch planned "current device"; begin_load's own fallback must not re-rank.+ from core.inference import media_locality++ _host(monkeypatch, [0, 1], [_dev(0, 8.0, 1.0), _dev(1, 24.0, 0.5)])+ token = media_locality.pin_planned_gpu_ordinal(None)+ try:+ assert dd.resolve_auto_cuda_ordinal() is None+ finally:+ media_locality._PLANNED_ORDINAL.reset(token)+ assert dd.resolve_auto_cuda_ordinal() == 1+++def test_route_uses_the_ordinal_an_auto_switch_planned(monkeypatch):+ from core.inference import media_locality++ resolve = _route(monkeypatch)+ token = media_locality.pin_planned_gpu_ordinal(0)+ try:+ assert media_locality.plan_gpu_ordinal() == 0+ assert asyncio.run(resolve(None)) == 0+ assert asyncio.run(resolve([1])) == 1 # an explicit pick still wins+ finally:+ media_locality._PLANNED_ORDINAL.reset(token)+ assert asyncio.run(resolve(None)) == 1+++def test_plan_sizes_the_card_the_load_will_rank(monkeypatch):+ from core.inference import media_locality++ monkeypatch.setattr(+ dd, "resolve_diffusion_device_target", lambda: types.SimpleNamespace(device = "cuda")+ )+ _host(monkeypatch, [0, 1], [_dev(0, 8.0, 1.0), _dev(1, 24.0, 0.5)])+ assert media_locality.plan_gpu_ordinal() == 1+++ "rel",+ ["core/inference/diffusion.py", "core/inference/video.py", "core/inference/sd_cpp_backend.py"],+)+def test_direct_backend_loads_rank_automatic_too(rel):+ # A direct caller (MCP, plugin) passes neither gpu_ids nor an ordinal.+ src = (Path(dd.__file__).resolve().parents[2] / rel).read_text(encoding = "utf-8")+ calls = {+ node.func.id+ for node in ast.walk(ast.parse(src))+ if isinstance(node, ast.Call) and isinstance(node.func, ast.Name)+ }+ assert "resolve_auto_cuda_ordinal" in calls+++def test_auto_skips_a_freer_card_older_than_the_current_one(monkeypatch):+ # The current sm_86 card works today; a freer Pascal may lack the wheel's kernels or bf16.+ _host(+ monkeypatch, [0, 1], [_dev(0, 24.0, 20.0), _dev(1, 8.0, 0.0)], caps = {0: (8, 6), 1: (6, 1)}+ )+ assert dd.resolve_auto_cuda_ordinal() == 0+++def test_auto_a_newer_card_still_competes(monkeypatch):+ _host(+ monkeypatch, [0, 1], [_dev(0, 24.0, 20.0), _dev(1, 24.0, 0.0)], caps = {0: (8, 6), 1: (8, 9)}+ )+ assert dd.resolve_auto_cuda_ordinal() == 1+++def test_auto_keeps_the_current_device_without_capabilities(monkeypatch):+ _host(monkeypatch, [0, 1], [_dev(0, 8.0, 1.0), _dev(1, 24.0, 0.5)], caps = {})+ assert dd.resolve_auto_cuda_ordinal() is None+++def test_auto_keeps_the_current_device_when_a_mask_entry_names_no_card(monkeypatch):+ # CUDA_VISIBLE_DEVICES=0,99,1 is just card 0 to CUDA, so physical 1 is no ordinal at all.+ _host(monkeypatch, [0, 99, 1], [_dev(0, 8.0, 1.0), _dev(1, 24.0, 0.5)])+ assert dd.resolve_auto_cuda_ordinal() is None+++def test_route_pins_its_automatic_decision_for_the_backend(monkeypatch):+ # begin_load's own fallback must reuse the route's answer (None included), not re-rank.+ from routes import inference as routes++ monkeypatch.setattr(+ dd, "resolve_diffusion_device_target", lambda: types.SimpleNamespace(device = "cuda")+ )+ answers = iter([None, 1])+ monkeypatch.setattr(dd, "resolve_auto_cuda_ordinal", lambda: next(answers))+ real = dd.__dict__["_PLANNED_ORDINAL"]++ async def load():+ ordinal = await routes._selected_gpu_ordinal(None)+ return ordinal, real.get()++ assert asyncio.run(load()) == (None, None)diff --git a/studio/backend/tests/test_gpu_arch_gate_os_matrix_7624.py b/studio/backend/tests/test_gpu_arch_gate_os_matrix_7624.pyindex cdb3ebb06b1..44aef0457b0 100644--- a/studio/backend/tests/test_gpu_arch_gate_os_matrix_7624.py+++ b/studio/backend/tests/test_gpu_arch_gate_os_matrix_7624.py@@ -375,7 +375,7 @@ class TestOsVendorMatrix:(0, 22000, 24564),(1, 18000, 24564),]- assert marker_spy == []+ # The CUDA SM filter reads the marker too; the ROCm gate's own input stays unread.assert arch_map_spy == []@pytest.mark.parametrize("os_key", OS_KEYS)diff --git a/studio/backend/tests/test_gpu_ids_cuda_device_order.py b/studio/backend/tests/test_gpu_ids_cuda_device_order.pynew file mode 100644index 00000000000..0a7aa5834f9--- /dev/null+++ b/studio/backend/tests/test_gpu_ids_cuda_device_order.py@@ -0,0 +1,127 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""GPU ids handed to a worker select the card they were ranked on, whatever+CUDA_DEVICE_ORDER the user exported.++RTX 3060 (PCI 0) + RTX 4090 (PCI 1) with CUDA_DEVICE_ORDER=FASTEST_FIRST: auto+select ranks nvidia-smi rows (PCI order) and picks 1, and the worker, reading+CUDA_VISIBLE_DEVICES=1 fastest-first, got the 3060. Without an inherited mask the+worker now pins PCI_BUS_ID, as every other Studio child does. With a numeric mask+the ids are CUDA ordinals in the user's order, so telemetry comes from torch."""++import os+import sys+from unittest.mock import patch++import pytest++from utils.hardware import hardware as hw+from utils.hardware.hardware import DeviceType++[email protected](autouse = True)+def _nvidia_host(monkeypatch):+ monkeypatch.setattr(hw, "IS_ROCM", False)+ monkeypatch.setitem(sys.modules, "torch", None)+ monkeypatch.setattr(hw, "_unmasked_ids_are_smi_rows", lambda: True)+++def test_torch_fallback_ids_keep_the_explicit_order(monkeypatch):+ # No nvidia-smi: the picker listed torch ordinals in FASTEST_FIRST order, so pinning PCI+ # order would hand the worker a different card.+ monkeypatch.setattr(hw, "_unmasked_ids_are_smi_rows", lambda: False)+ with patch.dict(os.environ, {"CUDA_DEVICE_ORDER": "FASTEST_FIRST"}, clear = True):+ hw.apply_gpu_ids([1], backend = DeviceType.CUDA.value)+ assert os.environ["CUDA_VISIBLE_DEVICES"] == "1"+ assert os.environ["CUDA_DEVICE_ORDER"] == "FASTEST_FIRST"+++def test_unmasked_worker_pins_pci_order_under_fastest_first():+ with patch.dict(os.environ, {"CUDA_DEVICE_ORDER": "FASTEST_FIRST"}, clear = True):+ hw.apply_gpu_ids([1], backend = DeviceType.CUDA.value)+ assert os.environ["CUDA_VISIBLE_DEVICES"] == "1"+ assert os.environ["CUDA_DEVICE_ORDER"] == "PCI_BUS_ID"+ # The default order is unchanged.+ with patch.dict(os.environ, {"CUDA_DEVICE_ORDER": "PCI_BUS_ID"}, clear = True):+ hw.apply_gpu_ids([0], backend = DeviceType.CUDA.value)+ assert os.environ["CUDA_DEVICE_ORDER"] == "PCI_BUS_ID"+ assert os.environ["CUDA_VISIBLE_DEVICES"] == "0"+++def test_only_unmasked_cuda_workers_are_repinned(monkeypatch):+ with patch.dict(os.environ, {"CUDA_DEVICE_ORDER": "FASTEST_FIRST"}, clear = True):+ hw.apply_gpu_ids([0], backend = DeviceType.CUDA.value)+ assert os.environ["CUDA_DEVICE_ORDER"] == "PCI_BUS_ID"+ # An inherited mask keeps the user's order: the ids are its entries.+ env = {"CUDA_DEVICE_ORDER": "FASTEST_FIRST", "CUDA_VISIBLE_DEVICES": "0,1"}+ with patch.dict(os.environ, env, clear = True):+ hw.apply_gpu_ids([1], backend = DeviceType.CUDA.value)+ assert os.environ["CUDA_VISIBLE_DEVICES"] == "1"+ assert os.environ["CUDA_DEVICE_ORDER"] == "FASTEST_FIRST"+ with patch.dict(os.environ, {"CUDA_DEVICE_ORDER": "FASTEST_FIRST"}, clear = True):+ hw.apply_gpu_ids([1], backend = DeviceType.XPU.value)+ assert os.environ["CUDA_DEVICE_ORDER"] == "FASTEST_FIRST"+ monkeypatch.setattr(hw, "IS_ROCM", True)+ monkeypatch.setattr(hw, "_rocr_relative_visibility", lambda value: None)+ with patch.dict(os.environ, {"CUDA_DEVICE_ORDER": "FASTEST_FIRST"}, clear = True):+ hw.apply_gpu_ids([1], backend = DeviceType.CUDA.value)+ assert os.environ["CUDA_DEVICE_ORDER"] == "FASTEST_FIRST"+++def _torch_rows(indices):+ # Mask entry i is torch ordinal i: under FASTEST_FIRST entry 0 is the 4090.+ cards = [(24.0, 0.5), (12.0, 1.0)]+ return [+ {"index": idx, "visible_ordinal": o, "total_gb": cards[o][0], "used_gb": cards[o][1]}+ for o, idx in enumerate(indices)+ ]+++def _smi_utilization():+ # nvidia-smi rows by PCI index: 0 is the 3060, 1 the 4090.+ return {+ "devices": [+ {"index": 0, "vram_total_gb": 12.0, "vram_used_gb": 1.0},+ {"index": 1, "vram_total_gb": 24.0, "vram_used_gb": 0.5},+ ]+ }+++def _host(monkeypatch, physical = 2):+ monkeypatch.setattr(hw, "get_device", lambda: DeviceType.CUDA)+ monkeypatch.setattr(hw, "get_physical_gpu_count", lambda: physical)+ monkeypatch.setattr(hw, "_physical_gpu_count_from_smi", True)+ monkeypatch.setattr(hw, "rocm_gpu_ids_without_torch_kernels", lambda: set())+ monkeypatch.setattr(hw, "get_visible_gpu_utilization", _smi_utilization)+ monkeypatch.setattr(hw, "_torch_get_per_device_info", _torch_rows)+++def _auto(env):+ with patch.dict(os.environ, env, clear = True):+ ids, meta = hw.auto_select_gpu_ids("m", required_override_gb = 16.0)+ return ids+++_MISMATCHED = {"CUDA_DEVICE_ORDER": "FASTEST_FIRST", "CUDA_VISIBLE_DEVICES": "0,1"}+++def test_numeric_mask_under_fastest_first_ranks_the_cards_the_ids_select(monkeypatch):+ # The 16 GB load fits only the 4090, mask entry 0 under FASTEST_FIRST. Ranking the+ # SMI rows picked entry 1, which the worker resolves to the 3060.+ _host(monkeypatch)+ assert _auto(_MISMATCHED) == [0]+++ "env",+ [+ {"CUDA_DEVICE_ORDER": "PCI_BUS_ID", "CUDA_VISIBLE_DEVICES": "0,1"},+ {"CUDA_DEVICE_ORDER": "FASTEST_FIRST"}, # no mask: the worker pins PCI order+ ],+)+def test_smi_ranking_stays_where_its_ids_are_valid(monkeypatch, env):+ _host(monkeypatch)+ assert _auto(env) == [1]+ # The mismatched shape on the same host ranks through torch.+ assert _auto(_MISMATCHED) == [0]diff --git a/studio/backend/tests/test_media_auto_switch.py b/studio/backend/tests/test_media_auto_switch.pyindex a3b7df0e901..b8b19d20b00 100644--- a/studio/backend/tests/test_media_auto_switch.py+++ b/studio/backend/tests/test_media_auto_switch.py@@ -777,6 +777,46 @@ def test_the_download_plan_asks_the_engine_that_will_load_the_pick(cached_gguf,assert "allow_device_probe" not in asked[0][1]+def test_the_load_runs_on_the_card_the_locality_check_planned(+ cached_gguf, enabled, backend, monkeypatch+):+ # Free VRAM moves between the check and the load; re-ranking there could pick a card whose+ # automatic precision wants an artifact the check never confirmed was cached.+ import itertools++ from core.inference import diffusion_device as dd+ from routes import inference as routes++ monkeypatch.setattr(+ dd, "resolve_diffusion_device_target", lambda: types.SimpleNamespace(device = "cuda")+ )+ ranks = itertools.chain([1, 1], itertools.repeat(0))+ monkeypatch.setattr(dd, "resolve_auto_cuda_ordinal", lambda: next(ranks))+ planned: list = []+ backend.download_plan = lambda model_path, **kw: planned.append(kw["gpu_ordinal"]) or {+ "total_bytes": 0+ }+ loaded: list = []++ async def _start(+ owner,+ pick,+ current_subject,+ hf_token = None,+ ):+ loaded.append(await routes._selected_gpu_ordinal(None))+ backend.repo_id, backend.model_kind = pick.model_path, pick.model_kind+ backend.gguf_variant = index.published_token(pick) or None+ backend.phase = "ready"++ monkeypatch.setattr(mas, "_start_load", _start)+ _switch("city96/FLUX.1-dev-gguf")++ assert loaded and loaded == planned[-1:]+ # The pin does not outlive the switch.+ assert locality.planned_gpu_ordinal() == (False, None)++def test_two_bpw_builds_of_one_quant_are_not_confused(two_bpw, enabled, backend, loads):# The backend's published token collapses IQ4_XS-3.53bpw and -3.97bpw to IQ4_XS, so a# resident sibling can never be assumed to be ours and the skip stays refused. The loaddiff --git a/studio/backend/utils/hardware/hardware.py b/studio/backend/utils/hardware/hardware.pyindex 50d53e4df5a..1d8ef1dc89e 100644--- a/studio/backend/utils/hardware/hardware.py+++ b/studio/backend/utils/hardware/hardware.py@@ -2023,6 +2023,15 @@ def _cuda_order_matches_smi() -> bool:return False+def _mask_names_cuda_ordinals(parent_visible_spec: Dict[str, Any]) -> bool:+ """Whether a numeric CUDA_VISIBLE_DEVICES under an explicit non-PCI CUDA_DEVICE_ORDER names CUDA ordinals rather than nvidia-smi rows, so the SMI rows it filters are other cards and only torch can rank the ones the ids select. Unmasked ids stay SMI rows: apply_gpu_ids pins PCI_BUS_ID for them."""+ if IS_ROCM or not parent_visible_spec.get("numeric_ids"):+ return False+ if parent_visible_spec.get("raw") is None or "CUDA_DEVICE_ORDER" not in os.environ:+ return False+ return not _cuda_order_matches_smi()++def _amd_smi_ids_for_hip_ids(hip_ids: Optional[list[int]]) -> Optional[list[int]]:"""Translate visible HIP ordinals to amd-smi physical GPU IDs."""if hip_ids is None or not hip_ids:@@ -6087,7 +6096,20 @@ def auto_select_gpu_ids(metadata["selected_gpu_ids"] = parent_idsreturn parent_ids, metadata- utilization = get_visible_gpu_utilization()+ if _mask_names_cuda_ordinals(parent_visible_spec):+ # The display keeps the CLI rows; ranking needs the cards the worker will get.+ utilization = {+ "devices": [+ {+ "index": td["index"],+ "vram_total_gb": td["total_gb"],+ "vram_used_gb": td["used_gb"],+ }+ for td in _torch_get_per_device_info(get_parent_visible_gpu_ids())+ ]+ }+ else:+ utilization = get_visible_gpu_utilization()devices = [d for d in utilization.get("devices", []) if d.get("index") not in _uncovered]parent_ids = _covered(get_parent_visible_gpu_ids())@@ -6874,6 +6896,14 @@ def _rocr_relative_visibility(value: str) -> Optional[str]:return ",".join(str(agents.index(gpu_id)) for gpu_id in wanted)+def _unmasked_ids_are_smi_rows() -> bool:+ """Whether unmasked GPU ids came from nvidia-smi rows (PCI order) rather than the torch fallback, which lists ordinals in CUDA's own order. Out of process, no CUDA context; False on any failure."""+ try:+ return _smi_visible_utilization({"numeric_ids": None, "raw": None}) is not None+ except Exception:+ return False++def apply_gpu_ids(gpu_ids, backend: Optional[str] = None) -> None:if gpu_ids is None:return@@ -6948,6 +6978,17 @@ def apply_gpu_ids(gpu_ids, backend: Optional[str] = None) -> None:if _relative is not None:value = _relative+ # No inherited mask: the ids are nvidia-smi rows (PCI order), so pin the order the+ # way every other Studio child is pinned; an explicit FASTEST_FIRST would hand the+ # worker another card. An inherited mask keeps its order, the ids being its entries.+ # Without nvidia-smi the picker listed torch ordinals in the explicit order: keep it.+ if (+ not _rocm_build+ and os.environ.get("CUDA_VISIBLE_DEVICES") is None+ and os.environ.get("CUDA_DEVICE_ORDER", "PCI_BUS_ID") != "PCI_BUS_ID"+ and _unmasked_ids_are_smi_rows()+ ):+ os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"os.environ["CUDA_VISIBLE_DEVICES"] = value# Wider than the build check: writing HIP on NVIDIA is inert, a missed mirror is not._inherits_rocm_visibility = (diff --git a/studio/backend/utils/hardware/nvidia.py b/studio/backend/utils/hardware/nvidia.pyindex ab42fb8306e..e853a915b06 100644--- a/studio/backend/utils/hardware/nvidia.py+++ b/studio/backend/utils/hardware/nvidia.py@@ -429,6 +429,33 @@ def get_checkpoint_quant_formats() -> list[str]:return [fmt for fmt, needed in _CHECKPOINT_QUANT_MIN_CAPABILITY if floor >= needed]+def get_compute_capabilities() -> dict[int, tuple[int, int]]:+ """nvidia-smi row index -> (major, minor), no mask and no torch; {} when unreadable."""+ try:+ result = gpu_query.run_nvidia_smi(+ [_nvidia_smi_executable(), "--query-gpu=index,compute_cap", "--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(),+ )+ except (OSError, subprocess.TimeoutExpired):+ return {}+ if result.returncode != 0:+ return {}+ capabilities: dict[int, tuple[int, int]] = {}+ for line in result.stdout.strip().splitlines():+ index, _, cap = (part.strip() for part in line.partition(","))+ major, _, minor = cap.partition(".")+ if not (index.isdigit() and major.isdigit() and minor.isdigit()):+ return {}+ capabilities[int(index)] = (int(major), int(minor))+ return capabilities++def get_physical_gpu_inventory() -> dict[str, Any]:"""Every NVIDIA GPU the driver enumerates, with no visibility mask and no torch. Display-only inventory: ``index`` is nvidia-smi's own row number, a physical id and NOT something a caller may pin, because the whole point of this probe is that PyTorch cannot open these devices. A failed probe comes back as a structured unavailable result, so this never raises out of an endpoint."""rows = _query_gpu_inventory("get_physical_gpu_inventory")