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: run native image generation on Vulkan when torch is CPU-only on an AMD or Arc GPU (#13697)

Daniel Han81cfe76dd577
diff --git a/studio/backend/core/inference/diffusion_engine_router.py b/studio/backend/core/inference/diffusion_engine_router.py
index c840363093a..22527bcee08 100644
--- a/studio/backend/core/inference/diffusion_engine_router.py
+++ b/studio/backend/core/inference/diffusion_engine_router.py
@@ -32,6 +32,7 @@ from __future__ import annotations
import functools
import importlib.util
import os
+import re
import platform
import sys
import threading
@@ -58,6 +59,7 @@ from core.inference.sd_cpp_backend import (
off_torch_build_mismatch,
preferred_accelerator,
sd_cpp_binary_runs_family,
+ sd_cpp_vulkan_fallback_enabled,
usable_or_recorded_failure,
)
from core.inference.sd_cpp_engine import (
@@ -162,11 +164,189 @@ def off_torch_sd_cpp_device(backend: Optional[str] = None) -> Optional[OffTorchD
return OffTorchDevice(vendor = vendor, index = index, accelerator = accelerator)
+# Hosts the pinned release ships a Vulkan sd.cpp bundle for.
+_VULKAN_SD_CPP_PLATFORMS = frozenset({("linux", "x86_64"), ("win32", "amd64")})
+
+
[email protected]_cache(maxsize = 1)
+def _vulkan_loader_loads() -> bool:
+ """Whether the Vulkan loader library opens here. The Vulkan build links it, so without it
+ neither sd-cli nor sd-server would start."""
+ import ctypes
+ try:
+ if sys.platform == "win32":
+ ctypes.WinDLL("vulkan-1.dll")
+ else:
+ ctypes.CDLL("libvulkan.so.1")
+ return True
+ except Exception: # noqa: BLE001
+ return False
+
+
+def _masked_vendors() -> set:
+ """Vendors a set runtime mask applies to (HIP honours CUDA_VISIBLE_DEVICES too). Vulkan reads
+ none of them, so a card hidden by one stays hidden. Unreadable counts as every vendor."""
+ try:
+ from utils.hardware.hardware import _VISIBILITY_MASK_VENDORS, _ze_affinity_mask
+
+ masked = set()
+ for var, vendors in _VISIBILITY_MASK_VENDORS.items():
+ value = _ze_affinity_mask() if var == "ZE_AFFINITY_MASK" else os.environ.get(var)
+ if value is not None:
+ masked |= vendors
+ return masked
+ except Exception: # noqa: BLE001
+ return {"amd", "intel", "nvidia"}
+
+
+# PCI vendors of the cards this route renders on.
+_RENDER_NODE_VENDORS = {"0x1002": "amd", "0x8086": "intel"}
+
+
+def _accessible_render_vendors(vendors) -> set:
+ """Which of ``vendors`` have a readable and writable /dev/dri render node. A container can list
+ a card in sysfs without mounting its node, and Vulkan then sees no device. Empty when another
+ vendor's GPU (virtio, VMware) also has an openable node, since unpinned sd.cpp could take it first."""
+ import glob
+
+ found = set()
+ for node in glob.glob("/dev/dri/renderD*"):
+ accessible = os.access(node, os.R_OK | os.W_OK)
+ try:
+ with open(
+ f"/sys/class/drm/{os.path.basename(node)}/device/vendor", encoding = "utf-8"
+ ) as f:
+ pci_vendor = f.read().strip().lower()
+ except OSError:
+ # An openable node of unknown vendor could be the device sd.cpp picks first.
+ if accessible:
+ return set()
+ continue
+ vendor = _RENDER_NODE_VENDORS.get(pci_vendor)
+ if vendor is None:
+ if accessible:
+ return set()
+ continue
+ if vendor in vendors and accessible:
+ found.add(vendor)
+ return found
+
+
+def _vulkan_gpu_for_cpu_torch() -> bool:
+ """True when torch is CPU-only but the host has a GPU the Vulkan sd.cpp build can render on:
+ an AMD card (Vega, RDNA1 and Polaris get no ROCm wheel) or an Intel Arc. Never beside NVIDIA,
+ which Vulkan could enumerate first, nor under a mask Vulkan does not read (#13666)."""
+ if not sd_cpp_vulkan_fallback_enabled():
+ return False
+ if (sys.platform, platform.machine().lower()) not in _VULKAN_SD_CPP_PLATFORMS:
+ return False
+ # ggml reads this one itself; anything but a list of ordinals selects nothing or throws. Its
+ # ordinals index the raw Vulkan list, so it never vouches for which card a mixed host gets.
+ vk_mask = os.environ.get("GGML_VK_VISIBLE_DEVICES")
+ if vk_mask is not None and not re.fullmatch(r"\s*\d+\s*(,\s*\d+\s*)*", vk_mask):
+ return False
+ inventory = _physical_inventory()
+ if inventory.get("unknown") or "nvidia" in (inventory.get("unanswered") or ()):
+ return False
+ devices = [d for d in inventory.get("devices") or () if isinstance(d, dict)]
+ if any(d.get("vendor") == "nvidia" for d in devices) or _nvidia_adapter_present():
+ return False
+
+ def _renders(device: dict) -> bool:
+ if device.get("vendor") == "amd":
+ return True
+ if device.get("vendor") != "intel":
+ return False
+ # Arc only: a UHD iGPU renders slower than the CPU build. Linux carries the PCI class,
+ # the Windows registry only the name.
+ if "xpu_class" in device:
+ return device.get("xpu_class") is True
+ return "arc" in str(device.get("name") or "").lower().replace("(tm)", " ").split()
+
+ gpus = [d for d in devices if d.get("vendor") in ("amd", "intel")]
+ if sys.platform != "win32":
+ # Vulkan only sees cards whose render node this process can open (a container may mount
+ # one vendor's), and the node and the driver must belong to the same vendor.
+ reachable = _accessible_render_vendors({d.get("vendor") for d in gpus})
+ gpus = [d for d in gpus if d.get("vendor") in reachable]
+ masked = _masked_vendors()
+ # Unpinned sd.cpp takes the first Vulkan device, which may be a UHD iGPU beside the card.
+ if not gpus or any(d.get("vendor") in masked for d in gpus):
+ return False
+ if not all(_renders(d) for d in gpus):
+ return False
+ return _hardware_vulkan_driver({d.get("vendor") for d in gpus}) and _vulkan_loader_loads()
+
+
+# The ICD manifests that drive each vendor's cards (RADV as radeon_icd or radv_icd, AMDVLK /
+# Adrenalin, ANV); a software rasteriser or another vendor's driver lists none of them.
+_VENDOR_ICD_NEEDLES = {"amd": ("radeon", "radv", "amd"), "intel": ("intel",)}
+
+
+def _hardware_vulkan_driver(vendors) -> bool:
+ """Whether the loader, under its active filters, would load a driver for one of ``vendors``.
+ Windows registers drivers in ways the manifest walk may not read, so an empty walk there is no
+ evidence."""
+ try:
+ from utils.hardware.amd import _loadable_icd_manifests, _vulkan_icd_manifest_paths
+
+ if not _vulkan_icd_manifest_paths():
+ # A driver filter the walk cannot apply may leave the loader with none.
+ filtered = os.environ.get("VK_LOADER_DRIVERS_SELECT") or os.environ.get(
+ "VK_LOADER_DRIVERS_DISABLE"
+ )
+ return sys.platform == "win32" and not filtered
+ needles = [n for vendor in vendors for n in _VENDOR_ICD_NEEDLES.get(vendor, ())]
+ return any(
+ any(needle in os.path.basename(str(path)).lower() for needle in needles)
+ for path in _loadable_icd_manifests()
+ )
+ except Exception: # noqa: BLE001
+ return False
+
+
+def _nvidia_adapter_present() -> bool:
+ """An NVIDIA card nvidia-smi cannot see (Nouveau, no proprietary driver, no nvidia-smi) is still
+ a Vulkan device. Unanswerable counts as present."""
+ if sys.platform == "win32":
+ try:
+ from utils.hardware.hardware import (
+ _windows_amd_adapter_records_by_luid,
+ _windows_live_adapter_names,
+ )
+
+ records = _windows_amd_adapter_records_by_luid(0x10DE, distinguish_failure = True)
+ if records is None:
+ return True
+ if not records:
+ return False
+ # The registry outlives the hardware, so a record only counts if the live scan agrees.
+ live = _windows_live_adapter_names()
+ return live is None or any("nvidia" in name.lower() for name in live)
+ except Exception: # noqa: BLE001
+ return True
+ import glob
+
+ for vendor_file in glob.glob("/sys/class/drm/card*/device/vendor"):
+ try:
+ with open(vendor_file, encoding = "utf-8") as f:
+ if f.read().strip().lower() == "0x10de":
+ return True
+ except OSError:
+ continue
+ return False
+
+
def image_install_accelerator(backend: str) -> str:
- """The sd.cpp build the IMAGE engine wants: the off-torch card's when one is set, else torch's.
- Video keeps ``_install_accelerator_for``, since torch places its loads."""
+ """The sd.cpp build the IMAGE engine wants: the off-torch card's when one is set, else torch's,
+ else Vulkan for a CPU torch beside an AMD or Arc GPU. Video keeps ``_install_accelerator_for``,
+ since torch places its loads."""
off_torch = off_torch_sd_cpp_device(backend)
- return off_torch.accelerator if off_torch is not None else _install_accelerator_for(backend)
+ if off_torch is not None:
+ return off_torch.accelerator
+ if backend == "cpu" and _vulkan_gpu_for_cpu_torch():
+ return "vulkan"
+ return _install_accelerator_for(backend)
# The engine the current load committed to, and why a non-native choice was made. Mutated only under _lock.
@@ -475,7 +655,7 @@ def select_and_activate_engine(
# Once, so server and CLI cannot disagree.
selected_card = _selected_card(gpu_ordinal)
install_accelerator = preferred_accelerator(
- _install_accelerator_for(backend), selected_card
+ image_install_accelerator(backend), selected_card
)
if off_torch is not None:
install_accelerator = preferred_accelerator(off_torch.accelerator, selected_card)
diff --git a/studio/backend/core/inference/sd_cpp_backend.py b/studio/backend/core/inference/sd_cpp_backend.py
index 024449d6e39..c97373226cb 100644
--- a/studio/backend/core/inference/sd_cpp_backend.py
+++ b/studio/backend/core/inference/sd_cpp_backend.py
@@ -1010,8 +1010,9 @@ def _note_failed_upgrade(accelerator: str) -> None:
# kernels for 27 gfx targets but bundles no HIP/BLAS runtime (NEEDED libhipblas.so.3,
# librocblas.so.5, libamdhip64.so.7 from the HOST), so any host without a matching ROCm userspace
# fails it. Linux: exits 0 listing CPU only (caught by the device probe). Windows: exits 0xC0000135
-# with no output (caught by exit status). One-way and one-deep; CUDA needs no rung.
-_ACCELERATOR_FALLBACK: dict[str, str] = {"rocm": "vulkan"}
+# with no output (caught by exit status). One-way and one-deep; CUDA needs no rung. Vulkan falls
+# to CPU: a CPU-torch host is routed to it, and one that cannot start it must not lose sd.cpp.
+_ACCELERATOR_FALLBACK: dict[str, str] = {"rocm": "vulkan", "vulkan": "cpu"}
# The sonames the upstream ROCm archive imports and does not ship.
@@ -1065,7 +1066,7 @@ def rocm_runtime_missing_sonames() -> Optional[list[str]]:
ACCELERATOR_FALLBACK_CLEAR_HINT = (
- "to retry the ROCm build after fixing that, clear the record with "
+ "to retry the failed GPU build after fixing that, clear the record with "
"DELETE /api/settings/diffusion-accelerator-fallback (or restart with "
"UNSLOTH_DIFFUSION_SD_CPP_VULKAN_FALLBACK=0 to never fall back)"
)
@@ -1665,6 +1666,9 @@ _ACCELERATOR_DECISIVE_FAILURE_MARKERS: tuple[str, ...] = (
"hiperrornobinaryforgpu",
"no kernel image is available",
"invalid device function",
+ # vulkan-hpp's spellings and the C enum: this driver cannot run the Vulkan build.
+ "errorincompatibledriver",
+ "vk_error_incompatible_driver",
)
# AMBIGUOUS: names a GPU fault without establishing the BUILD as the cause. #9278 with offload on
@@ -1676,6 +1680,10 @@ _ACCELERATOR_AMBIGUOUS_FAILURE_MARKERS: tuple[str, ...] = (
"rocm error",
"rocblas error",
"memory access fault by gpu node",
+ "errordevicelost",
+ "vk_error_device_lost",
+ "errorinitializationfailed",
+ "vk_error_initialization_failed",
)
# Windows loader deaths print nothing, so only the exit status shows them. DECISIVE.
@@ -1764,11 +1772,17 @@ def preferred_accelerator(accelerator: Optional[str], card: Optional[str] = None
A function of the stored record only, never of the live host: the loader preflight is applied
where the runtime verdict is interpreted, so this stays reproducible."""
- klass = _accelerator_class_of(accelerator) or (accelerator or "auto")
- nxt = fallback_accelerator_for(klass)
- if nxt and accelerator_runtime_failed(klass, card):
- return nxt
- return accelerator or "auto"
+ chosen = accelerator or "auto"
+ klass = _accelerator_class_of(accelerator) or chosen
+ seen: set[str] = set()
+ # Walk the ladder (rocm -> vulkan -> cpu) past every rung already shown unrunnable.
+ while klass not in seen:
+ seen.add(klass)
+ nxt = fallback_accelerator_for(klass)
+ if not (nxt and accelerator_runtime_failed(klass, card)):
+ break
+ chosen = klass = nxt
+ return chosen
def _incomplete_tree_replacement(exc: BaseException) -> bool:
@@ -2126,6 +2140,29 @@ def sd_cpp_binary_runs_family(binary: Optional[str], fam: Any) -> bool:
return binary_carries_marker(binary, getattr(fam, "sd_cpp_arch_marker", None))
+def managed_sd_cpp_accelerator() -> Optional[str]:
+ """The accelerator class of the managed sd-server install, else of the managed sd-cli (an
+ unowned SD_SERVER_PATH the router drops leaves the CLI to run), or None."""
+ try:
+ for binary in (find_sd_server_binary(), find_sd_cpp_binary()):
+ accelerator = _installed_accelerator_of(binary) if binary else None
+ if accelerator:
+ return accelerator
+ except Exception: # noqa: BLE001
+ pass
+ return None
+
+
+def sd_cpp_binaries_all_cpu() -> bool:
+ """Whether every sd.cpp binary a load could run (server, else CLI) is a managed CPU install.
+ An unowned SD_SERVER_PATH / SD_CLI_PATH build may render on a GPU, so it never counts."""
+ try:
+ binaries = [b for b in (find_sd_server_binary(), find_sd_cpp_binary()) if b]
+ return bool(binaries) and all(_installed_accelerator_of(b) == "cpu" for b in binaries)
+ except Exception: # noqa: BLE001
+ return False
+
+
def _installed_accelerator_of(binary: Optional[str]) -> Optional[str]:
"""The accelerator class recorded for the managed install ``binary`` belongs to.
@@ -3161,16 +3198,49 @@ class SdCppDiffusionBackend:
# A paravirtual Mac GPU runs sd.cpp on the CPU backend (see metal_text_encoder_flags), so record that.
if sd_cpp_args_mod.forces_cpu_backend(device):
device = "cpu"
+ torch_device = device
+
+ def _running() -> tuple[Optional[str], Optional[str]]:
+ if mode == "server":
+ return server_accelerator, server_binary
+ return engine_accelerator, getattr(engine, "binary", None)
+
+ def _placement(
+ run_accelerator: Optional[str], binary: Optional[str]
+ ) -> tuple[str, tuple[str, ...]]:
+ # Read off the build this load runs, never the requested one. SD_SERVER_PATH /
+ # SD_CLI_PATH builds carry no install record, so their own device listing says.
+ if run_accelerator is None and binary:
+ run_accelerator = sd_cpp_listed_device(binary)[0]
+ klass = _accelerator_class_of(run_accelerator) if run_accelerator else None
+ # A CPU torch running the Vulkan build renders on a card torch never measured, so
+ # auto offloads.
+ vulkan = torch_device == "cpu" and off_torch is None and klass == "vulkan"
+ placed = "vulkan" if vulkan else torch_device
+ # The fallback ladder can leave a CUDA / XPU torch running the CPU build. Not
+ # MPS: the macOS bundle is recorded as cpu and still renders on Metal.
+ if klass == "cpu" and off_torch is None and torch_device in ("cuda", "xpu"):
+ placed = "cpu"
+ # Honor speed everywhere; offload only off-CPU (on CPU weights are resident, so the flags are no-ops)
+ if placed == "cpu":
+ return placed, ()
+ return placed, tuple(
+ offload_flags(_memory_policy(memory_mode, cpu_offload or vulkan))
+ )
+
+ device, offload = _placement(*_running())
spawn_env = off_torch.child_env() if off_torch is not None else None
- # Honor speed everywhere; offload only off-CPU (on CPU weights are resident, so the flags are no-ops)
- offload: tuple[str, ...] = ()
- if device != "cpu":
- offload = tuple(offload_flags(_memory_policy(memory_mode, cpu_offload)))
# The device pin is NOT folded in here: the binary can still change below, through the deferred
# accelerator install, the post-download re-resolve, or a server start that falls back to one-shot, and
# the ggml device names come from whichever build ends up running. It is added at each point the flags are
# handed to a binary instead.
- gpu_ordinal = gpu_ordinal if device == "cuda" else None
+ # The route's card, applied only while the placement is CUDA: a deferred upgrade can move
+ # a load placed on the CPU bundle back onto the selected GPU.
+ selected_ordinal = gpu_ordinal
+
+ def _ordinal() -> Optional[int]:
+ return selected_ordinal if device == "cuda" else None
+
native_speed = _native_speed_for(speed_mode)
# Tear down the old model then commit the new one under _generate_lock: abort and WAIT for a generation
@@ -3206,6 +3276,8 @@ class SdCppDiffusionBackend:
# archive.
server_accelerator = _installed_accelerator_of(server_binary)
engine_accelerator = _installed_accelerator_of(getattr(engine, "binary", None))
+ # The upgrade may have landed or kept the old build; place for whichever runs.
+ device, offload = _placement(*_running())
# A new checkpoint earns a fresh attempt on the GPU backend: the previous abort says nothing about
# this graph.
self._cpu_backend_forced = False
@@ -3244,6 +3316,7 @@ class SdCppDiffusionBackend:
engine_accelerator = _installed_accelerator_of(
getattr(engine, "binary", None)
)
+ device, offload = _placement(*_running())
elif _installed_accelerator_of(server_binary) != server_accelerator:
raise RuntimeError(
"The stable-diffusion.cpp server binary was replaced by an install "
@@ -3284,7 +3357,7 @@ class SdCppDiffusionBackend:
files,
vae_format = fam.sd_cpp_vae_format,
offload = _offload_with_device_pin_impl(
- offload, server_binary, gpu_ordinal
+ offload, server_binary, _ordinal()
),
native_speed = native_speed,
threads = _default_threads(),
@@ -3318,6 +3391,12 @@ class SdCppDiffusionBackend:
# which re-resolves sd-cli and reads its real accelerator, rejected it as a
# different-accelerator replacement: the load reports success and then cannot generate.
fallback: Optional[SdCppEngine] = None
+ cached = getattr(self._engine, "binary", None)
+ if cached and _installed_accelerator_of(
+ cached
+ ) != self._resolved_accelerator(self._loading_card):
+ # The failure just recorded can move the preferred build off a cached sd-cli.
+ self._engine = None
try:
fallback = self._resolve_engine()
usable = fallback.version() is not None
@@ -3333,6 +3412,7 @@ class SdCppDiffusionBackend:
getattr(fallback, "binary", None)
)
mode = "oneshot"
+ device, offload = _placement(*_running())
finally:
if not started_ok:
with self._lock:
@@ -3354,7 +3434,7 @@ class SdCppDiffusionBackend:
_offload_with_device_pin_impl(
offload,
server_binary if mode == "server" else getattr(engine, "binary", None),
- gpu_ordinal,
+ _ordinal(),
)
)
state = _SdState(
@@ -3390,7 +3470,7 @@ class SdCppDiffusionBackend:
_resolved_server_physical_gpu_id(
server_binary,
device,
- gpu_ordinal,
+ _ordinal(),
committed_offload_flags,
)
if mode == "server" and off_torch is None
diff --git a/studio/backend/core/inference/video.py b/studio/backend/core/inference/video.py
index dc2d06116af..9394023be2d 100644
--- a/studio/backend/core/inference/video.py
+++ b/studio/backend/core/inference/video.py
@@ -4010,7 +4010,8 @@ class VideoBackend:
listed_accelerator = accelerator_verdict_keeps_gpu(accelerator_verdict)
if not accelerator_verdict:
fallback = fallback_accelerator_for(accelerator)
- if fallback:
+ # The CPU rung is the branch below, which also releases the GPU placement.
+ if fallback and fallback != "cpu":
# Before the fallback ensure replaces the tree and its bundle tag.
failed_fingerprint = _accelerator_fingerprint(binary)
fallback_binary = usable_or_recorded_failure(
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index 15ef11d4a77..87b6260d358 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -47022,6 +47022,7 @@ async def load_diffusion_model_gated(
annotate_status,
begin_load_on,
engine_for,
+ image_install_accelerator,
off_torch_sd_cpp_device,
predict_engine,
select_and_activate_engine,
@@ -47035,6 +47036,12 @@ async def load_diffusion_model_gated(
from core.inference.media_keepwarm import note_load_origin as note_media_load_origin
from hub.utils.gguf import extract_quant_token
from core.inference.sd_cpp_args import forces_cpu_backend
+ from core.inference.sd_cpp_backend import (
+ managed_sd_cpp_accelerator,
+ preferred_accelerator,
+ sd_cpp_binaries_all_cpu,
+ selected_card_identity,
+ )
from core.inference.sd_cpp_engine import ENGINE_DIFFUSERS, ENGINE_MLX, ENGINE_SD_CPP
from utils.native_path_leases import redact_native_paths
@@ -47115,6 +47122,41 @@ async def load_diffusion_model_gated(
# MLX drives the Apple GPU itself even where torch resolved "cpu": take the arbiter.
if pending_name == ENGINE_MLX:
needs_gpu = True
+ # So does the Vulkan sd.cpp build a CPU torch is routed to beside an AMD or Arc card,
+ # unless that build has failed here and the ladder runs the CPU one instead.
+ # A retained managed Vulkan build also renders on the card, whatever this load requested.
+ vulkan_on_cpu_torch = (
+ device == "cpu"
+ and off_torch is None
+ and await asyncio.to_thread(
+ lambda: preferred_accelerator(image_install_accelerator("cpu"), None) == "vulkan"
+ or managed_sd_cpp_accelerator() == "vulkan"
+ )
+ )
+ if pending_name == ENGINE_SD_CPP and vulkan_on_cpu_torch:
+ needs_gpu = True
+ # A GPU torch whose GPU builds have all failed here runs the managed CPU bundle: no claim.
+ def _runs_cpu_rung() -> bool:
+ try:
+ torch_backend = getattr(resolve_diffusion_device_target(), "backend", device)
+ return (
+ preferred_accelerator(
+ image_install_accelerator(torch_backend),
+ selected_card_identity(gpu_ordinal),
+ )
+ == "cpu"
+ and sd_cpp_binaries_all_cpu()
+ )
+ except Exception: # noqa: BLE001 -- unknown keeps the claim
+ return False
+
+ cpu_rung_on_gpu_torch = (
+ device not in ("cpu", "mps")
+ and off_torch is None
+ and await asyncio.to_thread(_runs_cpu_rung)
+ )
+ if pending_name == ENGINE_SD_CPP and cpu_rung_on_gpu_torch:
+ needs_gpu = False
# Before selection: switching to diffusers would unload the resident off-torch model, then refuse.
if off_torch is not None and pending_name != ENGINE_SD_CPP:
_guard_diffusion_load_against_training()
@@ -47233,8 +47275,18 @@ async def load_diffusion_model_gated(
needs_gpu = False
else:
_guard_diffusion_load_against_training()
+ if device == "cpu" and off_torch is None:
+ # Re-settled on what selection activated and installed: a CPU diffusers fallback, or a
+ # retained CPU bundle after a failed Vulkan install, takes no GPU.
+ needs_gpu = (
+ activated == ENGINE_SD_CPP
+ and vulkan_on_cpu_torch
+ and not await asyncio.to_thread(sd_cpp_binaries_all_cpu)
+ )
if activated == ENGINE_MLX:
needs_gpu = True
+ if activated == ENGINE_SD_CPP and cpu_rung_on_gpu_torch:
+ needs_gpu = False
# sd.cpp runs a paravirtual Mac GPU on the CPU backend, so it takes no DIFFUSION claim.
if (
activated == ENGINE_SD_CPP
diff --git a/studio/backend/tests/test_diffusion_routes.py b/studio/backend/tests/test_diffusion_routes.py
index 7ad803603f3..0da728385ec 100644
--- a/studio/backend/tests/test_diffusion_routes.py
+++ b/studio/backend/tests/test_diffusion_routes.py
@@ -1363,13 +1363,115 @@ def test_cpu_native_load_skips_gpu_arbiter(client, monkeypatch):
# A native sd.cpp load on a pure-CPU host never touches the GPU, so the route must NOT evict the resident chat model.
from core.inference.sd_cpp_engine import ENGINE_SD_CPP
+ import core.inference.diffusion_engine_router as router
+
backend = diffusion_module.get_diffusion_backend()
acquired = _force_engine(monkeypatch, backend, engine_name = ENGINE_SD_CPP, device = "cpu")
+ monkeypatch.setattr(router, "image_install_accelerator", lambda backend: "auto")
+ import core.inference.sd_cpp_backend as sd_backend
+
+ monkeypatch.setattr(sd_backend, "managed_sd_cpp_accelerator", lambda: None)
resp = _post_load(client, model_path = "x/z-image", gguf_filename = "q.gguf")
assert resp.status_code == 200
assert acquired == [] # no arbiter handoff for a CPU native load
+def test_cpu_torch_vulkan_native_load_takes_arbiter(client, monkeypatch):
+ # #13666: a CPU torch routed to the Vulkan sd.cpp build renders on the AMD / Arc card.
+ import core.inference.diffusion_engine_router as router
+ from core.inference.sd_cpp_engine import ENGINE_SD_CPP
+
+ backend = diffusion_module.get_diffusion_backend()
+ acquired = _force_engine(monkeypatch, backend, engine_name = ENGINE_SD_CPP, device = "cpu")
+ monkeypatch.setattr(router, "image_install_accelerator", lambda backend: "vulkan")
+ resp = _post_load(client, model_path = "x/z-image", gguf_filename = "q.gguf")
+ assert resp.status_code == 200
+ assert acquired == [gpu_arbiter.DIFFUSION]
+
+
+def test_a_retained_vulkan_build_takes_arbiter_even_when_cpu_is_requested(client, monkeypatch):
+ # A failed or disabled CPU install keeps the managed Vulkan build, which renders on the card.
+ import core.inference.diffusion_engine_router as router
+ import core.inference.sd_cpp_backend as sd_backend
+ from core.inference.sd_cpp_engine import ENGINE_SD_CPP
+
+ backend = diffusion_module.get_diffusion_backend()
+ acquired = _force_engine(monkeypatch, backend, engine_name = ENGINE_SD_CPP, device = "cpu")
+ monkeypatch.setattr(router, "image_install_accelerator", lambda backend: "auto")
+ monkeypatch.setattr(sd_backend, "managed_sd_cpp_accelerator", lambda: "vulkan")
+ resp = _post_load(client, model_path = "x/z-image", gguf_filename = "q.gguf")
+ assert resp.status_code == 200
+ assert acquired == [gpu_arbiter.DIFFUSION]
+
+
+def test_cpu_torch_load_after_a_failed_vulkan_build_skips_arbiter(client, monkeypatch):
+ # The ladder runs the CPU build once Vulkan is recorded unrunnable, so no GPU is taken.
+ import core.inference.diffusion_engine_router as router
+ import core.inference.sd_cpp_backend as sd_backend
+ from core.inference.sd_cpp_engine import ENGINE_SD_CPP
+
+ backend = diffusion_module.get_diffusion_backend()
+ acquired = _force_engine(monkeypatch, backend, engine_name = ENGINE_SD_CPP, device = "cpu")
+ monkeypatch.setattr(router, "image_install_accelerator", lambda backend: "vulkan")
+ monkeypatch.setattr(sd_backend, "preferred_accelerator", lambda accelerator, card = None: "cpu")
+ monkeypatch.setattr(sd_backend, "managed_sd_cpp_accelerator", lambda: "cpu")
+ resp = _post_load(client, model_path = "x/z-image", gguf_filename = "q.gguf")
+ assert resp.status_code == 200
+ assert acquired == []
+
+
+def test_cpu_torch_diffusers_fallback_after_a_vulkan_prediction_skips_arbiter(client, monkeypatch):
+ # Predicted the Vulkan sd.cpp build, but selection fell back to diffusers on the CPU.
+ import core.inference.diffusion_engine_router as router
+ from core.inference.sd_cpp_engine import ENGINE_DIFFUSERS, ENGINE_SD_CPP
+
+ backend = diffusion_module.get_diffusion_backend()
+ acquired = _force_engine(monkeypatch, backend, engine_name = ENGINE_DIFFUSERS, device = "cpu")
+ monkeypatch.setattr(router, "predict_engine", lambda fam, **kw: ENGINE_SD_CPP)
+ monkeypatch.setattr(router, "image_install_accelerator", lambda backend: "vulkan")
+ monkeypatch.setattr(backend, "assert_precision_available", lambda *a, **k: None)
+ resp = _post_load(client, model_path = "x/z-image", gguf_filename = "q.gguf")
+ assert resp.status_code == 200
+ assert acquired == []
+
+
+def test_cpu_torch_vulkan_route_on_a_retained_cpu_bundle_skips_arbiter(client, monkeypatch):
+ # The Vulkan install failed after selection and the usable CPU bundle was kept.
+ import core.inference.diffusion_engine_router as router
+ import core.inference.sd_cpp_backend as sd_backend
+ from core.inference.sd_cpp_engine import ENGINE_SD_CPP
+
+ backend = diffusion_module.get_diffusion_backend()
+ acquired = _force_engine(monkeypatch, backend, engine_name = ENGINE_SD_CPP, device = "cpu")
+ monkeypatch.setattr(router, "image_install_accelerator", lambda backend: "vulkan")
+ monkeypatch.setattr(sd_backend, "sd_cpp_binaries_all_cpu", lambda: True)
+ resp = _post_load(client, model_path = "x/z-image", gguf_filename = "q.gguf")
+ assert resp.status_code == 200
+ assert acquired == []
+
+
+def test_gpu_torch_load_on_the_cpu_rung_skips_arbiter(client, monkeypatch):
+ # ROCm and Vulkan both recorded unrunnable: the managed CPU bundle runs, so no GPU is taken.
+ import core.inference.diffusion_engine_router as router
+ import core.inference.sd_cpp_backend as sd_backend
+ from core.inference.sd_cpp_engine import ENGINE_SD_CPP
+
+ backend = diffusion_module.get_diffusion_backend()
+ acquired = _force_engine(monkeypatch, backend, engine_name = ENGINE_SD_CPP, device = "cuda")
+ monkeypatch.setattr(router, "image_install_accelerator", lambda backend: "rocm")
+ monkeypatch.setattr(sd_backend, "preferred_accelerator", lambda accelerator, card = None: "cpu")
+ monkeypatch.setattr(sd_backend, "sd_cpp_binaries_all_cpu", lambda: True)
+ resp = _post_load(client, model_path = "x/z-image", gguf_filename = "q.gguf")
+ assert resp.status_code == 200
+ assert acquired == []
+ # A GPU build, or an unowned binary, may still be what runs: keep the claim.
+ monkeypatch.setattr(sd_backend, "sd_cpp_binaries_all_cpu", lambda: False)
+ acquired.clear()
+ resp = _post_load(client, model_path = "x/z-image", gguf_filename = "q.gguf")
+ assert resp.status_code == 200
+ assert acquired == [gpu_arbiter.DIFFUSION]
+
+
def test_gpu_native_load_takes_arbiter(client, monkeypatch):
# A force-native sd.cpp load on a GPU box DOES use the GPU, so the arbiter is acquired, like the always-GPU diffusers path.
from core.inference.sd_cpp_engine import ENGINE_SD_CPP
diff --git a/studio/backend/tests/test_sd_cpp_backend.py b/studio/backend/tests/test_sd_cpp_backend.py
index 744adb5ed08..7660b2ccfd5 100644
--- a/studio/backend/tests/test_sd_cpp_backend.py
+++ b/studio/backend/tests/test_sd_cpp_backend.py
@@ -1576,6 +1576,67 @@ def test_paravirtual_mac_load_records_the_cpu_device(monkeypatch):
assert b._state.device == "mps"
[email protected]("accelerator", ["vulkan", "auto"])
+def test_cpu_torch_on_the_vulkan_build_offloads_by_default(monkeypatch, accelerator):
+ # #13666: the card's VRAM was never measured, so auto streams weights instead of assuming they fit.
+ monkeypatch.setattr(bk, "_installed_accelerator_of", lambda binary: accelerator)
+ b = SdCppDiffusionBackend()
+ _run_server_load(monkeypatch, b, [], device = "cpu")
+ if accelerator == "vulkan":
+ assert b._state.device == "vulkan"
+ assert "--offload-to-cpu" in b._state.offload_flags
+ else:
+ assert b._state.device == "cpu"
+ assert b._state.offload_flags == ()
+
+
[email protected]("lands", [True, False])
+def test_cpu_torch_placement_follows_a_deferred_vulkan_install(monkeypatch, lands):
+ # The deferred upgrade may land the Vulkan build or keep the resident CPU one; place for what runs.
+ installed = {"accelerator": "cpu"}
+ monkeypatch.setattr(bk, "_installed_accelerator_of", lambda binary: installed["accelerator"])
+
+ def _upgrade(self, server_binary, **_kw):
+ if lands:
+ installed["accelerator"] = "vulkan"
+ return server_binary
+
+ monkeypatch.setattr(SdCppDiffusionBackend, "_upgraded_or_refused", _upgrade)
+ monkeypatch.setattr(
+ SdCppDiffusionBackend, "_resolved_accelerator", staticmethod(lambda card = None: "vulkan")
+ )
+ monkeypatch.setattr(bk, "_managed_tree_in_use", lambda: True) # a resident server defers it
+ b = SdCppDiffusionBackend()
+ _run_server_load(monkeypatch, b, [], device = "cpu")
+ assert b._state.device == ("vulkan" if lands else "cpu")
+ assert ("--offload-to-cpu" in b._state.offload_flags) is lands
+
+
[email protected]("listed,expected", [("vulkan", "vulkan"), (None, "cpu")])
+def test_an_unowned_build_on_cpu_torch_places_by_its_device_listing(monkeypatch, listed, expected):
+ # SD_SERVER_PATH builds carry no install record; their --list-devices says what they render on.
+ monkeypatch.setattr(bk, "_installed_accelerator_of", lambda binary: None)
+ monkeypatch.setattr(bk, "sd_cpp_listed_device", lambda binary, *a, **k: (listed, None))
+ monkeypatch.setattr(
+ SdCppDiffusionBackend, "_resolved_accelerator", staticmethod(lambda card = None: "vulkan")
+ )
+ b = SdCppDiffusionBackend()
+ _run_server_load(monkeypatch, b, [], device = "cpu")
+ assert b._state.device == expected
+
+
[email protected]("device,expected", [("cuda", "cpu"), ("xpu", "cpu"), ("mps", "mps")])
+def test_the_cpu_build_on_a_gpu_torch_places_on_cpu(monkeypatch, device, expected):
+ # The ladder can leave a CUDA / XPU torch on the CPU build; the macOS bundle is recorded cpu
+ # but renders on Metal.
+ monkeypatch.setattr(bk, "_installed_accelerator_of", lambda binary: "cpu")
+ b = SdCppDiffusionBackend()
+ _run_server_load(monkeypatch, b, [], device = device)
+ assert b._state.device == expected
+ if expected == "cpu":
+ assert b._state.offload_flags == ()
+
+
def test_server_load_spawns_once_and_status_reports_mode(monkeypatch):
b = SdCppDiffusionBackend()
servers: list = []
@@ -2659,3 +2720,140 @@ def test_a_rejected_concurrent_load_cannot_move_the_family_the_worker_validates_
other.join(timeout = 5)
seen["worker"] = backend._loading_family
assert seen["worker"] is worker_family, "another thread's family reached this worker"
+
+
+def test_server_failure_drops_a_cached_sd_cli_of_the_failed_build(monkeypatch):
+ # An earlier one-shot load cached the Vulkan sd-cli; the Vulkan server now fails and the
+ # recorded failure moves the preferred build to CPU, so the fallback must not reuse the cache.
+ b = SdCppDiffusionBackend()
+ monkeypatch.setattr(bk, "find_sd_server_binary", lambda: "/x/sd-server")
+ monkeypatch.setattr(bk, "_server_binary_runnable", lambda *_a, **_k: True)
+
+ class _BadServer:
+ def __init__(self, binary):
+ pass
+
+ def start(self, *a, **k):
+ raise RuntimeError("ggml_vulkan: No devices found")
+
+ def stop(self):
+ pass
+
+ monkeypatch.setattr(bk, "SdCppServer", _BadServer)
+ fake = _FakeEngine()
+ fake.binary = "/vk/sd-cli"
+ _shared_setup_1(b, fake, monkeypatch)
+ monkeypatch.setattr(b, "_resolve_engine", SdCppDiffusionBackend._resolve_engine.__get__(b))
+ b._engine = fake
+ accelerators = {"/vk/sd-cli": "vulkan", "/cpu/sd-cli": "cpu"}
+ monkeypatch.setattr(bk, "_installed_accelerator_of", lambda binary: accelerators.get(binary))
+ monkeypatch.setattr(b, "_resolved_accelerator", lambda card = None: "cpu")
+ asked = []
+
+ def _ensure(**kwargs):
+ asked.append(kwargs.get("accelerator"))
+ return "/cpu/sd-cli"
+
+ monkeypatch.setattr(bk, "ensure_sd_cpp_binary", _ensure)
+ monkeypatch.setattr(b, "_refuse_incapable_build", lambda *_a, **_k: None)
+
+ class _CpuEngine(_FakeEngine):
+ def __init__(self, binary):
+ super().__init__()
+ self.binary = binary
+
+ monkeypatch.setattr(bk, "SdCppEngine", _CpuEngine)
+ fam = detect_family("z-image")
+ b._load_token = 1
+ _shared_setup_2(b, fam)
+ assert asked == ["cpu"]
+ assert b._state is not None and b._state.mode == "oneshot"
+ assert b._state.sd_accelerator == "cpu"
+
+
+def test_a_deferred_cuda_upgrade_keeps_the_selected_card(monkeypatch):
+ # A CUDA load starts on the resident CPU bundle (placed on the CPU) and the deferred upgrade then
+ # lands the CUDA build: the server must still be pinned to the card the route selected.
+ b = SdCppDiffusionBackend()
+ monkeypatch.setattr(bk, "find_sd_server_binary", lambda: "/x/sd-server")
+ monkeypatch.setattr(bk, "_server_binary_runnable", lambda *_a, **_k: True)
+ monkeypatch.setattr(bk, "ensure_sd_server_binary", lambda **_k: "/x/sd-server")
+ started = []
+
+ class _Server:
+ def __init__(self, binary):
+ pass
+
+ def start(self, *a, **k):
+ started.append(k.get("offload"))
+
+ def stop(self):
+ pass
+
+ monkeypatch.setattr(bk, "SdCppServer", _Server)
+ fake = _FakeEngine()
+ _shared_setup_1(b, fake, monkeypatch)
+ monkeypatch.setattr(
+ bk, "resolve_diffusion_device_target", lambda: types.SimpleNamespace(device = "cuda")
+ )
+ installed = {"/x/sd-server": "cpu"}
+ monkeypatch.setattr(bk, "_installed_accelerator_of", lambda binary: installed.get(binary))
+
+ def _upgrade(server_binary, **_k):
+ installed["/x/sd-server"] = "cuda"
+ return server_binary
+
+ monkeypatch.setattr(b, "_upgraded_or_refused", _upgrade)
+ monkeypatch.setattr(b, "_resolved_accelerator", lambda card = None: "cuda")
+ pins = []
+ monkeypatch.setattr(
+ bk,
+ "_offload_with_device_pin_impl",
+ lambda offload, binary, ordinal: pins.append(ordinal) or list(offload),
+ )
+ # The resident CPU bundle is in use, so _resolve_backend defers the upgrade to the teardown.
+ monkeypatch.setattr(bk, "_managed_tree_in_use", lambda: True)
+ fam = detect_family("z-image")
+ b._load_token = 1
+ b._run_load(
+ repo_id = "unsloth/Z-Image-Turbo-GGUF",
+ gguf_filename = "z.gguf",
+ base = fam.base_repo,
+ fam = fam,
+ hf_token = None,
+ _load_token = 1,
+ gpu_ordinal = 1,
+ )
+ assert started, "the server must start"
+ assert pins and all(p == 1 for p in pins), pins
+ assert b._state is not None and b._state.device == "cuda"
+
+
+def test_the_arbiter_preflight_reads_the_cli_behind_an_unowned_server(monkeypatch):
+ # SD_SERVER_PATH names a build the installer does not own; the router can drop it and run
+ # the managed sd-cli, so that CLI's record is the answer.
+ monkeypatch.setattr(bk, "find_sd_server_binary", lambda: "/custom/sd-server")
+ monkeypatch.setattr(bk, "find_sd_cpp_binary", lambda: "/managed/sd-cli")
+ records = {"/managed/sd-cli": "vulkan"}
+ monkeypatch.setattr(bk, "_installed_accelerator_of", lambda binary: records.get(binary))
+ assert bk.managed_sd_cpp_accelerator() == "vulkan"
+ records["/custom/sd-server"] = "cpu"
+ assert bk.managed_sd_cpp_accelerator() == "cpu"
+ records.clear()
+ assert bk.managed_sd_cpp_accelerator() is None
+
+
+def test_only_managed_cpu_binaries_count_as_cpu_only(monkeypatch):
+ monkeypatch.setattr(bk, "find_sd_server_binary", lambda: "/custom/sd-server")
+ monkeypatch.setattr(bk, "find_sd_cpp_binary", lambda: "/managed/sd-cli")
+ records = {"/managed/sd-cli": "cpu"}
+ monkeypatch.setattr(bk, "_installed_accelerator_of", lambda binary: records.get(binary))
+ # The unowned SD_SERVER_PATH build may render on a GPU.
+ assert bk.sd_cpp_binaries_all_cpu() is False
+ records["/custom/sd-server"] = "cpu"
+ assert bk.sd_cpp_binaries_all_cpu() is True
+ records["/managed/sd-cli"] = "vulkan"
+ assert bk.sd_cpp_binaries_all_cpu() is False
+ monkeypatch.setattr(bk, "find_sd_server_binary", lambda: None)
+ monkeypatch.setattr(bk, "find_sd_cpp_binary", lambda: None)
+ assert bk.sd_cpp_binaries_all_cpu() is False
diff --git a/studio/backend/tests/test_sd_cpp_rocm_vulkan_fallback.py b/studio/backend/tests/test_sd_cpp_rocm_vulkan_fallback.py
index 71a447e3431..cc0dbb312ef 100644
--- a/studio/backend/tests/test_sd_cpp_rocm_vulkan_fallback.py
+++ b/studio/backend/tests/test_sd_cpp_rocm_vulkan_fallback.py
@@ -317,9 +317,9 @@ def test_clearing_the_note_restores_the_host_accelerator(fake_settings):
@pytest.mark.parametrize(
"accelerator,expected",
- [("rocm", "vulkan"), ("vulkan", None), ("cuda", None), ("cpu", None), ("auto", None)],
+ [("rocm", "vulkan"), ("vulkan", "cpu"), ("cuda", None), ("cpu", None), ("auto", None)],
)
-def test_only_rocm_has_a_rung_below_it(accelerator, expected):
+def test_only_rocm_and_vulkan_have_a_rung_below_them(accelerator, expected):
from core.inference.sd_cpp_backend import fallback_accelerator_for
assert fallback_accelerator_for(accelerator) == expected
@@ -2309,7 +2309,7 @@ def test_the_route_tells_the_selection_which_card_it_picked(fake_settings):
body = inspect.getsource(router.select_and_activate_engine)
assert "_selected_card(gpu_ordinal)" in body
assert (
- "preferred_accelerator(\n _install_accelerator_for(backend), selected_card\n )"
+ "preferred_accelerator(\n image_install_accelerator(backend), selected_card\n )"
in body
)
diff --git a/studio/backend/tests/test_sd_cpp_vulkan_cpu_torch.py b/studio/backend/tests/test_sd_cpp_vulkan_cpu_torch.py
new file mode 100644
index 00000000000..4087e1462d9
--- /dev/null
+++ b/studio/backend/tests/test_sd_cpp_vulkan_cpu_torch.py
@@ -0,0 +1,435 @@
+# 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 CPU torch beside an AMD or Arc GPU installs the Vulkan sd.cpp build (#13666).
+
+Vega, RDNA1 and Polaris get no ROCm wheel, so torch is CPU-only there while llama.cpp already
+renders on the card through Vulkan. Every hardware answer is stubbed."""
+
+from __future__ import annotations
+
+import io
+import sys
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+
+from core.inference import diffusion_engine_router as r
+from core.inference import sd_cpp_backend
+from core.inference.diffusion_families import detect_family
+from core.inference.sd_cpp_engine import ENGINE_SD_CPP
+
+_STUDIO = Path(__file__).resolve().parents[2]
+if str(_STUDIO) not in sys.path:
+ sys.path.insert(0, str(_STUDIO))
+
+_ENVS = (
+ "UNSLOTH_DIFFUSION_ENGINE",
+ "UNSLOTH_DIFFUSION_SD_CPP",
+ "UNSLOTH_DIFFUSION_SD_CPP_DEVICE",
+ "UNSLOTH_DIFFUSION_SD_CPP_VULKAN_FALLBACK",
+ "ROCR_VISIBLE_DEVICES",
+ "HIP_VISIBLE_DEVICES",
+ "CUDA_VISIBLE_DEVICES",
+ "ZE_AFFINITY_MASK",
+ "GGML_VK_VISIBLE_DEVICES",
+)
+
+_VEGA = {"vendor": "amd", "index": 0, "name": None, "source": "sysfs-drm"}
+_ARC_LINUX = {"vendor": "intel", "index": 0, "name": None, "xpu_class": True}
+_UHD_LINUX = {"vendor": "intel", "index": 0, "name": None, "xpu_class": False}
+_ARC_WINDOWS = {"vendor": "intel", "index": 0, "name": "Intel(R) Arc(TM) A770 Graphics"}
+_UHD_WINDOWS = {"vendor": "intel", "index": 0, "name": "Intel(R) UHD Graphics 770"}
+_RTX = {"vendor": "nvidia", "index": 0, "name": "NVIDIA GeForce RTX 3060"}
+
+
+def _host(
+ *devices,
+ unanswered = (),
+ unknown = False,
+):
+ return {"unknown": unknown, "unanswered": list(unanswered), "devices": list(devices)}
+
+
+def _platform(monkeypatch, system, machine):
+ monkeypatch.setattr(r, "sys", SimpleNamespace(platform = system, modules = sys.modules))
+ monkeypatch.setattr(r, "platform", SimpleNamespace(machine = lambda: machine))
+
+
[email protected](autouse = True)
+def _pinned_host(monkeypatch):
+ for e in _ENVS:
+ monkeypatch.delenv(e, raising = False)
+ _platform(monkeypatch, "linux", "x86_64")
+ monkeypatch.setattr(r, "_physical_inventory", lambda: _host(_VEGA))
+ monkeypatch.setattr(r, "_vulkan_loader_loads", lambda: True)
+ monkeypatch.setattr(r, "_accessible_render_vendors", lambda vendors: set(vendors))
+ import utils.hardware.amd as amd
+
+ monkeypatch.setattr(amd, "the_vulkan_loader_has_no_usable_driver", lambda: False)
+ monkeypatch.setattr(r, "_hardware_vulkan_driver", lambda vendors: True)
+ monkeypatch.setattr(r, "_nvidia_adapter_present", lambda: False)
+
+
+ "devices,expected",
+ [
+ ((_VEGA,), "vulkan"),
+ ((_ARC_LINUX,), "vulkan"),
+ # Unpinned sd.cpp could take the UHD iGPU first.
+ ((_UHD_LINUX, _VEGA), "auto"),
+ ((_ARC_LINUX, _VEGA), "vulkan"),
+ ((_UHD_LINUX,), "auto"),
+ ((), "auto"),
+ ((_VEGA, _RTX), "auto"),
+ ((_RTX,), "auto"),
+ ],
+)
+def test_cpu_torch_vulkan_follows_the_cards(monkeypatch, devices, expected):
+ monkeypatch.setattr(r, "_physical_inventory", lambda: _host(*devices))
+ assert r.image_install_accelerator("cpu") == expected
+
+
[email protected]("device,expected", [(_ARC_WINDOWS, "vulkan"), (_UHD_WINDOWS, "auto")])
+def test_windows_intel_is_read_by_name(monkeypatch, device, expected):
+ _platform(monkeypatch, "win32", "AMD64")
+ monkeypatch.setattr(r, "_physical_inventory", lambda: _host(device))
+ assert r.image_install_accelerator("cpu") == expected
+
+
+ "inventory",
+ [_host(_VEGA, unanswered = ["nvidia"]), _host(unknown = True)],
+)
+def test_an_unanswered_nvidia_probe_keeps_cpu(monkeypatch, inventory):
+ monkeypatch.setattr(r, "_physical_inventory", lambda: inventory)
+ assert r.image_install_accelerator("cpu") == "auto"
+
+
+ "var,value",
+ [
+ ("ROCR_VISIBLE_DEVICES", "0"),
+ ("HIP_VISIBLE_DEVICES", "0"),
+ ("CUDA_VISIBLE_DEVICES", "0"),
+ ("ZE_AFFINITY_MASK", "0"),
+ ("GGML_VK_VISIBLE_DEVICES", ""),
+ ],
+)
+def test_a_mask_vulkan_does_not_read_keeps_cpu(monkeypatch, var, value):
+ if var == "ZE_AFFINITY_MASK":
+ monkeypatch.setattr(r, "_physical_inventory", lambda: _host(_ARC_LINUX))
+ monkeypatch.setenv(var, value)
+ assert r.image_install_accelerator("cpu") == "auto"
+
+
+ "device,var",
+ [
+ (_ARC_LINUX, "CUDA_VISIBLE_DEVICES"),
+ (_ARC_LINUX, "HIP_VISIBLE_DEVICES"),
+ (_ARC_LINUX, "ROCR_VISIBLE_DEVICES"),
+ (_VEGA, "ZE_AFFINITY_MASK"),
+ ],
+)
+def test_a_mask_for_another_vendor_leaves_the_card_alone(monkeypatch, device, var):
+ monkeypatch.setattr(r, "_physical_inventory", lambda: _host(device))
+ monkeypatch.setenv(var, "0")
+ assert r.image_install_accelerator("cpu") == "vulkan"
+
+
+def test_an_unmounted_uhd_node_does_not_block_the_amd_card(monkeypatch):
+ monkeypatch.setattr(r, "_physical_inventory", lambda: _host(_UHD_LINUX, _VEGA))
+ monkeypatch.setattr(r, "_accessible_render_vendors", lambda vendors: {"amd"} & set(vendors))
+ assert r.image_install_accelerator("cpu") == "vulkan"
+ # Both nodes mounted: the UHD iGPU could be taken first.
+ monkeypatch.setattr(r, "_accessible_render_vendors", lambda vendors: set(vendors))
+ assert r.image_install_accelerator("cpu") == "auto"
+
+
[email protected]("value", ["", "default"])
+def test_an_unset_equivalent_ze_mask_is_not_a_mask(monkeypatch, value):
+ monkeypatch.setenv("ZE_AFFINITY_MASK", value)
+ assert r.image_install_accelerator("cpu") == "vulkan"
+
+
[email protected]("value", ["abc", "-1", "0,x", ""])
+def test_a_malformed_ggml_vulkan_mask_keeps_cpu(monkeypatch, value):
+ # Selects nothing or throws.
+ monkeypatch.setenv("GGML_VK_VISIBLE_DEVICES", value)
+ assert r.image_install_accelerator("cpu") == "auto"
+
+
+ "output",
+ [
+ "vk::Queue::submit: ErrorDeviceLost",
+ "VK_ERROR_DEVICE_LOST",
+ "vk::createInstance: ErrorIncompatibleDriver",
+ ],
+)
+def test_vulkan_failures_are_recognised(output):
+ assert sd_cpp_backend.output_shows_accelerator_failure(output)
+
+
+def test_an_incompatible_vulkan_driver_is_decisive():
+ assert sd_cpp_backend.output_shows_decisive_accelerator_failure("ErrorIncompatibleDriver")
+ assert not sd_cpp_backend.output_shows_decisive_accelerator_failure("ErrorDeviceLost")
+ assert not sd_cpp_backend.output_shows_accelerator_failure("VK_ERROR_OUT_OF_DEVICE_MEMORY")
+
+
+def test_a_ggml_vulkan_mask_is_honoured_but_never_vouches_for_a_mixed_host(monkeypatch):
+ # Its ordinals index the raw Vulkan list, so they cannot say which card a UHD + Radeon host gets.
+ monkeypatch.setenv("GGML_VK_VISIBLE_DEVICES", "1")
+ assert r.image_install_accelerator("cpu") == "vulkan"
+ monkeypatch.setattr(r, "_physical_inventory", lambda: _host(_UHD_LINUX, _VEGA))
+ assert r.image_install_accelerator("cpu") == "auto"
+
+
+def test_an_nvidia_card_nvidia_smi_cannot_see_keeps_cpu(monkeypatch):
+ monkeypatch.setattr(r, "_nvidia_adapter_present", lambda: True)
+ assert r.image_install_accelerator("cpu") == "auto"
+
+
+ "vendors,manifests,expected",
+ [
+ ({"amd"}, ["/usr/share/vulkan/icd.d/radeon_icd.x86_64.json"], True),
+ ({"amd"}, ["/usr/share/vulkan/icd.d/radv_icd.x86_64.json"], True),
+ ({"amd"}, ["/etc/vulkan/icd.d/amd_icd64.json"], True),
+ ({"amd"}, ["/usr/share/vulkan/icd.d/lvp_icd.x86_64.json"], False),
+ # VK_ICD_FILENAMES picked another vendor's driver: it lists no AMD card.
+ ({"amd"}, ["/etc/vulkan/icd.d/intel_icd.json"], False),
+ (
+ {"intel"},
+ ["/usr/share/vulkan/icd.d/lvp_icd.x86_64.json", "/etc/vulkan/icd.d/intel_icd.json"],
+ True,
+ ),
+ ({"amd"}, [], False),
+ ],
+)
+def test_only_a_driver_for_the_listed_cards_counts(monkeypatch, vendors, manifests, expected):
+ import utils.hardware.amd as amd
+
+ monkeypatch.undo()
+ _platform(monkeypatch, "linux", "x86_64")
+ monkeypatch.setattr(amd, "_vulkan_icd_manifest_paths", lambda: list(manifests))
+ monkeypatch.setattr(amd, "_loadable_icd_manifests", lambda paths = None: list(manifests))
+ assert r._hardware_vulkan_driver(vendors) is expected
+
+
+def test_an_unmounted_render_node_keeps_cpu(monkeypatch):
+ monkeypatch.setattr(r, "_accessible_render_vendors", lambda vendors: set())
+ assert r.image_install_accelerator("cpu") == "auto"
+ _platform(monkeypatch, "win32", "AMD64")
+ assert r.image_install_accelerator("cpu") == "vulkan"
+
+
+ "system,machine", [("linux", "aarch64"), ("win32", "ARM64"), ("darwin", "arm64")]
+)
+def test_hosts_without_a_vulkan_bundle_keep_cpu(monkeypatch, system, machine):
+ _platform(monkeypatch, system, machine)
+ assert r.image_install_accelerator("cpu") == "auto"
+
+
+def test_no_vulkan_driver_or_loader_keeps_cpu(monkeypatch):
+ import utils.hardware.amd as amd
+
+ monkeypatch.setattr(r, "_hardware_vulkan_driver", lambda vendors: False)
+ assert r.image_install_accelerator("cpu") == "auto"
+ monkeypatch.setattr(r, "_hardware_vulkan_driver", lambda vendors: True)
+ monkeypatch.setattr(r, "_vulkan_loader_loads", lambda: False)
+ assert r.image_install_accelerator("cpu") == "auto"
+
+
+def test_the_fallback_knob_opts_out(monkeypatch):
+ monkeypatch.setenv("UNSLOTH_DIFFUSION_SD_CPP_VULKAN_FALLBACK", "0")
+ assert r.image_install_accelerator("cpu") == "auto"
+
+
+ "backend,expected", [("cuda", "cuda"), ("rocm", "rocm"), ("xpu", "vulkan")]
+)
+def test_gpu_torch_backends_are_unchanged(backend, expected):
+ assert r.image_install_accelerator(backend) == expected
+
+
+def test_video_keeps_torchs_build():
+ assert r._install_accelerator_for("cpu") == "auto"
+
+
+def test_a_vulkan_build_that_cannot_run_falls_to_cpu(monkeypatch):
+ monkeypatch.setattr(sd_cpp_backend, "_accelerator_runtime_failures", {})
+ monkeypatch.setattr(sd_cpp_backend, "_stored_accelerator_runtime_failures", lambda: {})
+ monkeypatch.setattr(sd_cpp_backend, "_persist_accelerator_runtime_failures", lambda _r: None)
+ monkeypatch.setattr(sd_cpp_backend, "_accelerator_fingerprint", lambda *_a: {"bundle": "t"})
+ assert sd_cpp_backend.fallback_accelerator_for("vulkan") == "cpu"
+ assert sd_cpp_backend.preferred_accelerator("vulkan") == "vulkan"
+ sd_cpp_backend.note_accelerator_runtime_failure("vulkan", proven = True)
+ assert sd_cpp_backend.preferred_accelerator("vulkan") == "cpu"
+ # A ROCm host whose Vulkan rung also failed reaches CPU instead of retrying Vulkan.
+ assert sd_cpp_backend.preferred_accelerator("rocm") == "rocm"
+ sd_cpp_backend.note_accelerator_runtime_failure("rocm", proven = True)
+ assert sd_cpp_backend.preferred_accelerator("rocm") == "cpu"
+
+
+def test_selection_installs_the_vulkan_build(monkeypatch):
+ monkeypatch.setattr(
+ r, "resolve_diffusion_device_target", lambda: SimpleNamespace(backend = "cpu", device = "cpu")
+ )
+ monkeypatch.setattr(r, "_off_torch_warned", set())
+ monkeypatch.setattr(sd_cpp_backend, "_installed_accelerator_of", lambda _b: "vulkan")
+ monkeypatch.setattr(
+ r,
+ "get_active_diffusion_engine",
+ lambda: SimpleNamespace(
+ status = lambda: {"loaded": False, "repo_id": None}, unload = lambda: None
+ ),
+ )
+ monkeypatch.setattr(r, "_server_binary_runnable", lambda *_a, **_k: True)
+ monkeypatch.setattr(r, "SdCppEngine", lambda **_: SimpleNamespace(version = lambda: "sd-cli v0"))
+ asked: list[str] = []
+
+ def _ensure(**kwargs):
+ asked.append(kwargs["accelerator"])
+ return None
+
+ monkeypatch.setattr(r, "ensure_sd_server_binary", _ensure)
+ monkeypatch.setattr(
+ r, "ensure_sd_cpp_binary", lambda **kw: asked.append(kw["accelerator"]) or "/opt/sd/sd-cli"
+ )
+ saved = (r._active_engine_name, r._fallback_reason)
+ try:
+ r.select_and_activate_engine(detect_family("z-image"))
+ assert r.active_engine_name() == ENGINE_SD_CPP
+ finally:
+ r._active_engine_name, r._fallback_reason = saved
+ assert asked and set(asked) == {"vulkan"}
+
+
+_PINNED_RELEASE_ASSETS = [
+ "sd-master-951-f89d9b1-uafac7a7-bin-Linux-Ubuntu-22.04-x86_64-cuda12.zip",
+ "sd-master-951-f89d9b1-uafac7a7-bin-Linux-Ubuntu-22.04-x86_64-vulkan.zip",
+ "sd-master-951-f89d9b1-uafac7a7-bin-Linux-Ubuntu-22.04-x86_64.zip",
+ "sd-master-951-f89d9b1-uafac7a7-bin-Linux-Ubuntu-24.04-aarch64.zip",
+ "sd-master-951-f89d9b1-uafac7a7-bin-win-cpu-x64.zip",
+ "sd-master-951-f89d9b1-uafac7a7-bin-win-cuda12-x64.zip",
+ "sd-master-951-f89d9b1-uafac7a7-bin-win-vulkan-x64.zip",
+]
+
+
+ "system,machine,expected",
+ [
+ (
+ "Linux",
+ "x86_64",
+ "sd-master-951-f89d9b1-uafac7a7-bin-Linux-Ubuntu-22.04-x86_64-vulkan.zip",
+ ),
+ ("Windows", "AMD64", "sd-master-951-f89d9b1-uafac7a7-bin-win-vulkan-x64.zip"),
+ ("Linux", "aarch64", None),
+ ],
+)
+def test_the_pinned_release_has_the_vulkan_bundle_it_routes_to(system, machine, expected):
+ from install_sd_cpp_prebuilt import resolve_release_asset
+ assert (
+ resolve_release_asset(
+ _PINNED_RELEASE_ASSETS, system = system, machine = machine, accelerator = "vulkan"
+ )
+ == expected
+ )
+
+
+def test_only_a_render_node_of_the_listed_vendor_counts(monkeypatch, tmp_path):
+ import builtins
+ import glob
+
+ monkeypatch.undo() # the real helper, not the fixture's stub
+ vendors = {"renderD128": "0x8086", "renderD129": "0x1002"} # Intel, then AMD
+ real_open = builtins.open
+
+ def _open(path, *a, **k):
+ name = str(path).split("/")[-3] if str(path).startswith("/sys/class/drm/") else None
+ if name in vendors:
+ return io.StringIO(vendors[name] + "\n")
+ return real_open(path, *a, **k)
+
+ accessible = set()
+ monkeypatch.setattr(glob, "glob", lambda pattern: [f"/dev/dri/{n}" for n in vendors])
+ monkeypatch.setattr(builtins, "open", _open)
+ monkeypatch.setattr(r.os, "access", lambda node, mode: node in accessible)
+ accessible.add("/dev/dri/renderD128")
+ assert r._accessible_render_vendors({"amd"}) == set()
+ accessible.add("/dev/dri/renderD129")
+ assert r._accessible_render_vendors({"amd"}) == {"amd"}
+ assert r._accessible_render_vendors({"amd", "intel"}) == {"amd", "intel"}
+ # A virtio-gpu (Venus) node beside the card: unpinned sd.cpp could pick it.
+ vendors["renderD130"] = "0x1af4"
+ assert r._accessible_render_vendors({"amd"}) == {"amd"} # not openable here
+ accessible.add("/dev/dri/renderD130")
+ assert r._accessible_render_vendors({"amd"}) == set()
+ del vendors["renderD130"]
+ # A node whose vendor cannot be read: unknown, so it blocks only while openable.
+ nodes = [*vendors, "renderD999"]
+ monkeypatch.setattr(glob, "glob", lambda pattern: [f"/dev/dri/{n}" for n in nodes])
+ assert r._accessible_render_vendors({"amd"}) == {"amd"}
+ accessible.add("/dev/dri/renderD999")
+ assert r._accessible_render_vendors({"amd"}) == set()
+
+
[email protected]("var", ["VK_LOADER_DRIVERS_DISABLE", "VK_LOADER_DRIVERS_SELECT"])
+def test_a_windows_driver_filter_the_walk_cannot_apply_keeps_cpu(monkeypatch, var):
+ import utils.hardware.amd as amd
+
+ monkeypatch.undo()
+ _platform(monkeypatch, "win32", "AMD64")
+ monkeypatch.setattr(amd, "_vulkan_icd_manifest_paths", lambda: [])
+ assert r._hardware_vulkan_driver({"amd"}) is True
+ monkeypatch.setenv(var, "*")
+ assert r._hardware_vulkan_driver({"amd"}) is False
+
+
+def test_the_render_node_and_the_driver_must_share_a_vendor(monkeypatch):
+ # AMD + Arc: only the AMD node is mounted and only an Intel driver loads.
+ monkeypatch.setattr(r, "_physical_inventory", lambda: _host(_VEGA, _ARC_LINUX))
+ monkeypatch.setattr(r, "_accessible_render_vendors", lambda vendors: {"amd"} & set(vendors))
+ monkeypatch.setattr(r, "_hardware_vulkan_driver", lambda vendors: "intel" in vendors)
+ assert r.image_install_accelerator("cpu") == "auto"
+ monkeypatch.setattr(r, "_hardware_vulkan_driver", lambda vendors: "amd" in vendors)
+ assert r.image_install_accelerator("cpu") == "vulkan"
+
+
+ "records,live,expected",
+ [
+ ({}, None, False),
+ (None, ["AMD Radeon RX 7900 XTX"], True), # registry unreadable
+ (
+ {1: {"name": "NVIDIA GeForce RTX 4090"}},
+ ["AMD Radeon RX 7900 XTX", "NVIDIA GeForce RTX 4090"],
+ True,
+ ),
+ # A stale record of a card that was removed.
+ ({1: {"name": "NVIDIA GeForce RTX 3060"}}, ["AMD Radeon RX 7900 XTX"], False),
+ ({1: {"name": "NVIDIA GeForce RTX 3060"}}, None, True),
+ ],
+)
+def test_windows_nvidia_without_nvidia_smi_is_found_in_the_adapter_registry(
+ monkeypatch, records, live, expected
+):
+ import utils.hardware.hardware as hw
+
+ monkeypatch.undo()
+ _platform(monkeypatch, "win32", "AMD64")
+ seen = []
+
+ def _records(vendor_id, distinguish_failure = False):
+ seen.append(vendor_id)
+ return records
+
+ monkeypatch.setattr(hw, "_windows_amd_adapter_records_by_luid", _records)
+ monkeypatch.setattr(hw, "_windows_live_adapter_names", lambda: live)
+ assert r._nvidia_adapter_present() is expected
+ assert seen == [0x10DE]