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 images: render on the NVIDIA card when torch drives no GPU (#16853)
Debojyoti Banerjee5a110a6e1e48
diff --git a/studio/backend/core/inference/diffusion_engine_router.py b/studio/backend/core/inference/diffusion_engine_router.pyindex fc63f451b0b..aee787e692b 100644--- a/studio/backend/core/inference/diffusion_engine_router.py+++ b/studio/backend/core/inference/diffusion_engine_router.py@@ -351,15 +351,41 @@ def _nvidia_adapter_present() -> bool:return False+_CUDA_SD_CPP_PLATFORMS = frozenset({("linux", "x86_64"), ("win32", "amd64")})+++def _cuda_gpu_for_cpu_torch() -> bool:+ """No GPU torch beside an NVIDIA card llama.cpp's CUDA build runs on (proves the driver, #16803)."""+ # Gated with the Vulkan route: the CPU rung below a failed CUDA build is the same ladder.+ if not sd_cpp_vulkan_fallback_enabled():+ return False+ if (sys.platform, platform.machine().lower()) not in _CUDA_SD_CPP_PLATFORMS:+ return False+ mask = os.environ.get("CUDA_VISIBLE_DEVICES")+ if mask is not None and mask.strip() in ("", "-1"):+ return False+ from core.inference.sd_cpp_engine import llama_cpp_cuda_major++ if not llama_cpp_cuda_major():+ return False+ inventory = _physical_inventory()+ return any(+ isinstance(device, dict) and device.get("vendor") == "nvidia"+ for device in inventory.get("devices") or ()+ )++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,- else Vulkan for a CPU torch beside an AMD or Arc GPU. Video keeps ``_install_accelerator_for``,- since torch places its loads."""+ else Vulkan for a CPU torch beside an AMD or Arc GPU, or CUDA beside an NVIDIA card llama.cpp+ already renders on. Video keeps ``_install_accelerator_for``, since torch places its loads."""off_torch = off_torch_sd_cpp_device(backend)if off_torch is not None:return off_torch.acceleratorif backend == "cpu" and _vulkan_gpu_for_cpu_torch():return "vulkan"+ if backend == "cpu" and _cuda_gpu_for_cpu_torch():+ return "cuda"return _install_accelerator_for(backend)@@ -903,37 +929,58 @@ def select_and_activate_engine(return Nonereturn usable_or_recorded_failure(candidate, install_accelerator, selected_card)- server_binary = _accept(- ensure_sd_server_binary(- allow_install = _install_allowed(),- accelerator = install_accelerator,- )- )- unlaunchable_server: Optional[str] = None- if server_binary and not _server_binary_runnable(server_binary):- logger.warning(- "sd-server at %s is present but not runnable; not using it", server_binary- )- # Held for the single recorder below.- unlaunchable_server = server_binary- server_binary = None- # Probe runnability first, else a non-runnable binary fails inside the background load.- binary = _accept(- ensure_sd_cpp_binary(- allow_install = _install_allowed() and server_binary is None,- accelerator = install_accelerator,+ # A CPU torch has nothing else on the card: a GPU build that cannot start steps down now.+ for _rung in range(2):+ server_binary = _accept(+ ensure_sd_server_binary(+ allow_install = _install_allowed(),+ accelerator = install_accelerator,+ ))- )- unlaunchable_cli: Optional[str] = None- if binary and SdCppEngine(binary = binary).version() is None:- logger.warning("sd-cli at %s is present but not runnable; not using it", binary)- unlaunchable_cli = binary- binary = None- if binary is None and server_binary is None and (unlaunchable_cli or unlaunchable_server):- # One strike per bundle, only when neither executable runs.- note_unlaunchable_accelerator_build(- unlaunchable_cli or unlaunchable_server, card = selected_card+ unlaunchable_server: Optional[str] = None+ if server_binary and not _server_binary_runnable(server_binary):+ logger.warning(+ "sd-server at %s is present but not runnable; not using it", server_binary+ )+ # Held for the single recorder below.+ unlaunchable_server = server_binary+ server_binary = None+ # Probe runnability first, else a non-runnable binary fails inside the background load.+ binary = _accept(+ ensure_sd_cpp_binary(+ allow_install = _install_allowed() and server_binary is None,+ accelerator = install_accelerator,+ ))+ unlaunchable_cli: Optional[str] = None+ if binary and SdCppEngine(binary = binary).version() is None:+ logger.warning("sd-cli at %s is present but not runnable; not using it", binary)+ unlaunchable_cli = binary+ binary = None+ if (+ binary is None+ and server_binary is None+ and (unlaunchable_cli or unlaunchable_server)+ ):+ # One strike per bundle, only when neither executable runs.+ note_unlaunchable_accelerator_build(+ unlaunchable_cli or unlaunchable_server, card = selected_card+ )+ stepped = preferred_accelerator(image_install_accelerator(backend), selected_card)+ if (+ backend == "cpu"+ and off_torch is None+ and _rung == 0+ and stepped != install_accelerator+ ):+ logger.warning(+ "the %s sd.cpp build cannot start here; using the %s build",+ install_accelerator,+ stepped,+ )+ install_accelerator = stepped+ continue+ break# Runnable is not capable: an old build is never upgraded and fails late on new families.for name, candidate in (("sd-server", server_binary), ("sd-cli", binary)):if candidate and not sd_cpp_binary_runs_family(candidate, fam):diff --git a/studio/backend/core/inference/sd_cpp_backend.py b/studio/backend/core/inference/sd_cpp_backend.pyindex e80f57bf2d7..0085d973201 100644--- a/studio/backend/core/inference/sd_cpp_backend.py+++ b/studio/backend/core/inference/sd_cpp_backend.py@@ -1332,7 +1332,8 @@ def _note_failed_upgrade(accelerator: str) -> None:# 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. 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"}+# "cuda" -> "cpu" is the CPU-torch route's rung only (_cuda_cpu_rung_applies): a CUDA torch has diffusers.+_ACCELERATOR_FALLBACK: dict[str, str] = {"rocm": "vulkan", "vulkan": "cpu", "cuda": "cpu"}def _vulkan_cpu_rung_applies() -> bool:@@ -1345,6 +1346,15 @@ def _vulkan_cpu_rung_applies() -> bool:return True+def _cuda_cpu_rung_applies() -> bool:+ """Only a CPU torch (routed to CUDA beside llama.cpp's) may step a CUDA build down to CPU."""+ try:+ from utils.hardware.hardware import DeviceType, get_device+ return get_device() == DeviceType.CPU+ except Exception: # noqa: BLE001+ return False++# The sonames the upstream ROCm archive imports and does not ship._ROCM_RUNTIME_SONAMES: tuple[str, ...] = ("libamdhip64.so.7",@@ -1492,6 +1502,9 @@ def sd_cpp_listed_device(def accelerator_probe_failure_is_decisive(accelerator: Optional[str]) -> bool:"""A CPU-only probe is decisive only if the ROCm runtime is proven absent; else two strikes apply."""klass = _accelerator_class_of(accelerator)+ if klass == "cuda":+ # llama.cpp's CUDA build already proved the driver, so the sd.cpp build is at fault.+ return fallback_accelerator_for(klass) == "cpu"if klass != "rocm" or not fallback_accelerator_for(klass):return Falsereturn rocm_runtime_resolvable() is False@@ -1509,6 +1522,8 @@ def fallback_accelerator_for(accelerator: Optional[str]) -> Optional[str]:want = _installer_module().accelerator_class(accelerator)except Exception: # noqa: BLE001want = (accelerator or "").strip().lower()+ if want == "cuda" and not _cuda_cpu_rung_applies():+ return Nonenxt = _ACCELERATOR_FALLBACK.get(want)return nxt if nxt and nxt != want else None@@ -1845,6 +1860,8 @@ def note_accelerator_runtime_failure(klass = _accelerator_class_of(accelerator)if not klass or klass not in _ACCELERATOR_FALLBACK:return+ if klass == "cuda" and not _cuda_cpu_rung_applies():+ returnfingerprint = dict(fingerprint) if isinstance(fingerprint, dict) else _accelerator_fingerprint()records = _stored_accelerator_runtime_failures()records.update({k: v for k, v in _accelerator_runtime_failures.items() if k not in records})@@ -1965,6 +1982,8 @@ def _applicable_record(klass: str, record: Optional[dict]) -> Optional[dict]:record = _record_under_current_rule(klass, record)if klass == "vulkan" and not _vulkan_cpu_rung_applies():return _decisive_evidence_only(record)+ if klass == "cuda" and not _cuda_cpu_rung_applies():+ return Nonereturn record@@ -3738,10 +3757,12 @@ class SdCppDiffusionBackend: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+ # A CPU torch running a GPU 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+ unmeasured = (+ torch_device == "cpu" and off_torch is None and klass in ("vulkan", "cuda")+ )+ placed = klass if unmeasured 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"):@@ -3750,7 +3771,7 @@ class SdCppDiffusionBackend:if placed == "cpu":return placed, ()return placed, tuple(- offload_flags(_memory_policy(memory_mode, cpu_offload or vulkan))+ offload_flags(_memory_policy(memory_mode, cpu_offload or unmeasured)))device, offload = _placement(*_running())diff --git a/studio/backend/core/inference/sd_cpp_engine.py b/studio/backend/core/inference/sd_cpp_engine.pyindex 40ba44151c4..c796a11a70b 100644--- a/studio/backend/core/inference/sd_cpp_engine.py+++ b/studio/backend/core/inference/sd_cpp_engine.py@@ -363,8 +363,8 @@ def host_cuda_runtime_dirs() -> list[str]:return []-def host_cuda_runtime_major() -> Optional[str]:- """CUDA major the installed llama.cpp links, else torch's."""+def llama_cpp_cuda_major() -> Optional[str]:+ """CUDA major the installed llama.cpp links, None when it is not a CUDA build (or unreadable)."""binary = _llama_server_binary()if binary:try:@@ -376,6 +376,14 @@ def host_cuda_runtime_major() -> Optional[str]:return match.group(1)except Exception: # noqa: BLE001pass+ return None+++def host_cuda_runtime_major() -> Optional[str]:+ """CUDA major the installed llama.cpp links, else torch's."""+ major = llama_cpp_cuda_major()+ if major:+ return majorversion = getattr(getattr(sys.modules.get("torch"), "version", None), "cuda", None)return version.split(".")[0] if isinstance(version, str) and version else Nonediff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex cb8494c28c7..68156c6999a 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -48537,18 +48537,18 @@ 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 = (+ # So does a GPU sd.cpp build a CPU torch is routed to (Vulkan beside AMD / Arc, CUDA beside+ # NVIDIA) or retains, unless the ladder has moved it to the CPU build.+ gpu_build_on_cpu_torch = (device == "cpu"and off_torch is Noneand await asyncio.to_thread(- lambda: preferred_accelerator(image_install_accelerator("cpu"), None) == "vulkan"- or managed_sd_cpp_accelerator() == "vulkan"+ lambda: preferred_accelerator(image_install_accelerator("cpu"), None)+ in ("vulkan", "cuda")+ or managed_sd_cpp_accelerator() in ("vulkan", "cuda")))- if pending_name == ENGINE_SD_CPP and vulkan_on_cpu_torch:+ if pending_name == ENGINE_SD_CPP and gpu_build_on_cpu_torch:needs_gpu = True# A GPU torch whose GPU builds have all failed here runs the managed CPU bundle: no claim.@@ -48726,10 +48726,10 @@ async def load_diffusion_model_gated(_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.+ # retained CPU bundle after a failed Vulkan or CUDA install, takes no GPU.needs_gpu = (activated == ENGINE_SD_CPP- and vulkan_on_cpu_torch+ and gpu_build_on_cpu_torchand not await asyncio.to_thread(sd_cpp_binaries_all_cpu))if activated == ENGINE_MLX:diff --git a/studio/backend/tests/test_sd_cpp_cuda_cpu_torch.py b/studio/backend/tests/test_sd_cpp_cuda_cpu_torch.pynew file mode 100644index 00000000000..39d5515ea5e--- /dev/null+++ b/studio/backend/tests/test_sd_cpp_cuda_cpu_torch.py@@ -0,0 +1,337 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""No GPU torch beside an NVIDIA card running llama.cpp's CUDA build gets the CUDA sd.cpp build (#16803)."""++from __future__ import annotations++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 import sd_cpp_engine+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",+ "CUDA_VISIBLE_DEVICES",+)++_RTX = {"vendor": "nvidia", "index": 0, "name": "NVIDIA GeForce RTX 3060"}+_VEGA = {"vendor": "amd", "index": 0, "name": None, "source": "sysfs-drm"}+++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 _nvidia_host_with_cuda_llama(monkeypatch):+ for e in _ENVS:+ monkeypatch.delenv(e, raising = False)+ _platform(monkeypatch, "win32", "AMD64")+ monkeypatch.setattr(r, "_physical_inventory", lambda: _host(_RTX))+ # The Vulkan route is never taken beside NVIDIA; keep its own probes off the real host.+ monkeypatch.setattr(r, "_nvidia_adapter_present", lambda: True)+ _llama_marker(monkeypatch, "cuda13")+++def _llama_marker(monkeypatch, runtime_line):+ import utils.llama_cpp_freshness as freshness+ monkeypatch.setattr(sd_cpp_engine, "_llama_server_binary", lambda: "/opt/llama/llama-server")+ monkeypatch.setattr(freshness, "read_install_marker", lambda _b: {"runtime_line": runtime_line})+++def _empty_failure_records(monkeypatch, stored = None):+ monkeypatch.setattr(sd_cpp_backend, "_accelerator_runtime_failures", {})+ monkeypatch.setattr(+ sd_cpp_backend, "_stored_accelerator_runtime_failures", lambda: dict(stored or {})+ )+ monkeypatch.setattr(sd_cpp_backend, "_persist_accelerator_runtime_failures", lambda _r: None)+ monkeypatch.setattr(sd_cpp_backend, "_accelerator_fingerprint", lambda *_a: {"bundle": "t"})++[email protected]("system,machine", [("win32", "AMD64"), ("linux", "x86_64")])+def test_a_cpu_torch_beside_cuda_llama_installs_the_cuda_build(monkeypatch, system, machine):+ _platform(monkeypatch, system, machine)+ assert r.image_install_accelerator("cpu") == "cuda"+++def test_llama_cpp_without_cuda_keeps_cpu(monkeypatch):+ # A CPU or Vulkan llama.cpp proves nothing about the CUDA driver.+ _llama_marker(monkeypatch, "vulkan")+ assert r.image_install_accelerator("cpu") == "auto"+++ "inventory",+ [+ _host(),+ _host(_VEGA),+ _host(unknown = True),+ _host(unanswered = ["nvidia"]),+ ],+)+def test_no_listed_nvidia_card_keeps_cpu(monkeypatch, inventory):+ monkeypatch.setattr(r, "_physical_inventory", lambda: inventory)+ assert r.image_install_accelerator("cpu") == "auto"++[email protected]("value", ["", "-1", " -1 "])+def test_a_mask_hiding_every_card_keeps_cpu(monkeypatch, value):+ monkeypatch.setenv("CUDA_VISIBLE_DEVICES", value)+ assert r.image_install_accelerator("cpu") == "auto"+++def test_a_mask_naming_a_card_still_uses_it(monkeypatch):+ monkeypatch.setenv("CUDA_VISIBLE_DEVICES", "0")+ assert r.image_install_accelerator("cpu") == "cuda"+++ "system,machine", [("linux", "aarch64"), ("darwin", "arm64"), ("win32", "ARM64")]+)+def test_hosts_without_a_cuda_bundle_keep_cpu(monkeypatch, system, machine):+ _platform(monkeypatch, system, machine)+ assert r.image_install_accelerator("cpu") == "auto"+++def test_the_fallback_knob_opts_out(monkeypatch):+ # Without the CPU rung a CUDA build that cannot run would leave the host with nothing.+ monkeypatch.setenv("UNSLOTH_DIFFUSION_SD_CPP_VULKAN_FALLBACK", "0")+ assert r.image_install_accelerator("cpu") == "auto"+++ "backend,expected", [("cuda", "cuda"), ("rocm", "rocm"), ("xpu", "vulkan"), ("mps", "auto")]+)+def test_gpu_torch_backends_are_unchanged(backend, expected):+ assert r.image_install_accelerator(backend) == expected+++def test_an_off_torch_card_still_wins(monkeypatch):+ monkeypatch.setenv("UNSLOTH_DIFFUSION_SD_CPP_DEVICE", "nvidia:0")+ assert r.image_install_accelerator("cpu") == "cuda"+++def test_video_keeps_torchs_build():+ assert r._install_accelerator_for("cpu") == "auto"+++def test_a_cuda_build_that_cannot_run_falls_to_cpu_only_on_a_cpu_torch(monkeypatch):+ _empty_failure_records(monkeypatch)+ monkeypatch.setattr(sd_cpp_backend, "_cuda_cpu_rung_applies", lambda: True)+ assert sd_cpp_backend.fallback_accelerator_for("cuda") == "cpu"+ assert sd_cpp_backend.preferred_accelerator("cuda") == "cuda"+ sd_cpp_backend.note_accelerator_runtime_failure("cuda", proven = True)+ assert sd_cpp_backend.preferred_accelerator("cuda") == "cpu"+ # A CUDA torch keeps diffusers on the card: the CPU rung is never its fallback.+ monkeypatch.setattr(sd_cpp_backend, "_cuda_cpu_rung_applies", lambda: False)+ assert sd_cpp_backend.fallback_accelerator_for("cuda") is None+ assert sd_cpp_backend.preferred_accelerator("cuda") == "cuda"+++def test_a_cuda_torch_records_no_cuda_failure(monkeypatch):+ _empty_failure_records(monkeypatch)+ monkeypatch.setattr(sd_cpp_backend, "_cuda_cpu_rung_applies", lambda: False)+ sd_cpp_backend.note_accelerator_runtime_failure("cuda", proven = True)+ assert sd_cpp_backend._accelerator_runtime_failures == {}+++def test_two_ambiguous_cuda_strikes_move_a_cpu_torch_host(monkeypatch):+ _empty_failure_records(monkeypatch)+ monkeypatch.setattr(sd_cpp_backend, "_cuda_cpu_rung_applies", lambda: True)+ sd_cpp_backend.note_accelerator_runtime_failure("cuda", proven = False)+ assert sd_cpp_backend.preferred_accelerator("cuda") == "cuda"+ sd_cpp_backend.note_accelerator_runtime_failure("cuda", proven = False)+ assert sd_cpp_backend.preferred_accelerator("cuda") == "cpu"+++def test_a_cuda_build_the_loader_refuses_installs_the_cpu_one(monkeypatch):+ _empty_failure_records(monkeypatch)+ monkeypatch.setattr(sd_cpp_backend, "_cuda_cpu_rung_applies", lambda: True)+ inst = sd_cpp_backend._installer_module()+ calls: list[str] = []++ def _install(**kwargs):+ calls.append(kwargs["accelerator"])+ if kwargs["accelerator"] == "cuda":+ raise inst.UnrunnableBuildError(+ "STATUS_DLL_NOT_FOUND", accelerator = "cuda", asset = "x", tag = "t"+ )+ return "/opt/sd/sd-cli"++ monkeypatch.setattr(sd_cpp_engine, "host_cuda_runtime_major", lambda: "13")+ path, used = sd_cpp_backend._install_down_the_ladder(_install, "cuda")+ assert (path, used) == ("/opt/sd/sd-cli", "cpu")+ assert calls == ["cuda", "cpu"]+ assert sd_cpp_backend.preferred_accelerator("cuda") == "cpu"+++def test_the_cuda_install_asks_for_llama_cpps_cuda_line(monkeypatch):+ monkeypatch.setattr(sd_cpp_engine, "host_cuda_runtime_major", lambda: "13")+ assert sd_cpp_backend._install_kwargs("cuda") == {"accelerator": "cuda", "cuda_major": "13"}+++def test_host_cuda_runtime_major_prefers_llama_then_torch(monkeypatch):+ monkeypatch.setattr(sd_cpp_engine, "llama_cpp_cuda_major", lambda: "12")+ assert sd_cpp_engine.host_cuda_runtime_major() == "12"+ monkeypatch.setattr(sd_cpp_engine, "llama_cpp_cuda_major", lambda: None)+ fake_torch = SimpleNamespace(version = SimpleNamespace(cuda = "13.0"))+ monkeypatch.setitem(sys.modules, "torch", fake_torch)+ assert sd_cpp_engine.host_cuda_runtime_major() == "13"+++def test_llama_cpp_cuda_major_reads_the_install_marker(monkeypatch):+ markers = {"cuda13": "13", "cuda12": "12", "vulkan": None, "cpu": None}+ for line, expected in markers.items():+ _llama_marker(monkeypatch, line)+ assert sd_cpp_engine.llama_cpp_cuda_major() == expected+ monkeypatch.setattr(sd_cpp_engine, "_llama_server_binary", lambda: None)+ assert sd_cpp_engine.llama_cpp_cuda_major() is None+++def test_selection_installs_the_cuda_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: "cuda")+ 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) == {"cuda"}+++_PINNED_RELEASE_ASSETS = [+ "sd-master-982-0518b34-uaba3a1c-bin-Linux-Ubuntu-22.04-x86_64-cuda12.zip",+ "sd-master-982-0518b34-uaba3a1c-bin-Linux-Ubuntu-22.04-x86_64-cuda13.zip",+ "sd-master-982-0518b34-uaba3a1c-bin-Linux-Ubuntu-22.04-x86_64-vulkan.zip",+ "sd-master-982-0518b34-uaba3a1c-bin-Linux-Ubuntu-22.04-x86_64.zip",+ "sd-master-982-0518b34-uaba3a1c-bin-Linux-Ubuntu-24.04-aarch64.zip",+ "sd-master-982-0518b34-uaba3a1c-bin-win-cpu-x64.zip",+ "sd-master-982-0518b34-uaba3a1c-bin-win-cuda12-x64.zip",+ "sd-master-982-0518b34-uaba3a1c-bin-win-cuda13-x64.zip",+ "sd-master-982-0518b34-uaba3a1c-bin-win-vulkan-x64.zip",+]+++ "system,machine,major,expected",+ [+ ("Windows", "AMD64", "13", "sd-master-982-0518b34-uaba3a1c-bin-win-cuda13-x64.zip"),+ ("Windows", "AMD64", "12", "sd-master-982-0518b34-uaba3a1c-bin-win-cuda12-x64.zip"),+ (+ "Linux",+ "x86_64",+ "13",+ "sd-master-982-0518b34-uaba3a1c-bin-Linux-Ubuntu-22.04-x86_64-cuda13.zip",+ ),+ ("Linux", "aarch64", "13", None),+ ],+)+def test_the_pinned_release_has_the_cuda_bundle_it_routes_to(system, machine, major, expected):+ inst = sd_cpp_backend._installer_module()+ assert (+ inst.resolve_release_asset(+ _PINNED_RELEASE_ASSETS,+ system = system,+ machine = machine,+ accelerator = "cuda",+ cuda_major = major,+ )+ == expected+ )+++def test_a_cuda_build_that_cannot_start_steps_down_within_the_same_load(monkeypatch):+ """Without torch nothing but sd.cpp renders, so the first load must not end on diffusers."""+ _empty_failure_records(monkeypatch)+ monkeypatch.setattr(sd_cpp_backend, "_cuda_cpu_rung_applies", lambda: True)+ 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: b.split("/")[2] if b else None+ )+ 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 b, *_a, **_k: "/cuda/" not in b)+ monkeypatch.setattr(+ r,+ "SdCppEngine",+ lambda binary = None, **_: SimpleNamespace(+ version = lambda: None if "/cuda/" in binary else "sd-cli v0"+ ),+ )+ asked: list[str] = []++ def _ensure(stem):+ def _inner(**kwargs):+ asked.append(kwargs["accelerator"])+ klass = "cpu" if kwargs["accelerator"] in ("auto", "cpu") else kwargs["accelerator"]+ return f"/sd/{klass}/{stem}"++ return _inner++ monkeypatch.setattr(r, "ensure_sd_server_binary", _ensure("sd-server"))+ monkeypatch.setattr(r, "ensure_sd_cpp_binary", _ensure("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[:2] == ["cuda", "cuda"]+ assert asked[2:] and set(asked[2:]) == {"cpu"}+ # Proven on the spot: the next load starts at the CPU build.+ assert sd_cpp_backend.preferred_accelerator("cuda") == "cpu"diff --git a/studio/backend/tests/test_sd_cpp_rocm_vulkan_fallback.py b/studio/backend/tests/test_sd_cpp_rocm_vulkan_fallback.pyindex 023d4bf0e56..7626f0c4608 100644--- a/studio/backend/tests/test_sd_cpp_rocm_vulkan_fallback.py+++ b/studio/backend/tests/test_sd_cpp_rocm_vulkan_fallback.py@@ -6,6 +6,7 @@from __future__ import annotationsimport inspect+import reimport threadingimport typesfrom pathlib import Path@@ -316,8 +317,12 @@ def test_clearing_the_note_restores_the_host_accelerator(fake_settings):"accelerator,expected",[("rocm", "vulkan"), ("vulkan", "cpu"), ("cuda", None), ("cpu", None), ("auto", None)],)-def test_only_rocm_and_vulkan_have_a_rung_below_them(accelerator, expected):+def test_only_rocm_and_vulkan_have_a_rung_below_them(accelerator, expected, monkeypatch):+ from core.inference import sd_cpp_backendfrom core.inference.sd_cpp_backend import fallback_accelerator_for++ # A CUDA torch: CUDA's CPU rung belongs to the CPU-torch route only (#16803).+ monkeypatch.setattr(sd_cpp_backend, "_cuda_cpu_rung_applies", lambda: False, raising = False)assert fallback_accelerator_for(accelerator) == expected@@ -2538,8 +2543,12 @@ class TestRocmRuntimePreflight:monkeypatch.setattr(sd_backend, "rocm_runtime_resolvable", lambda: called.append(1) or False)+ monkeypatch.setattr(sd_backend, "_cuda_cpu_rung_applies", lambda: False)assert sd_backend.accelerator_probe_failure_is_decisive("cuda") is Falseassert sd_backend.accelerator_probe_failure_is_decisive("vulkan") is False+ # The CPU-torch CUDA route (#16803) is decided without the ROCm preflight too.+ monkeypatch.setattr(sd_backend, "_cuda_cpu_rung_applies", lambda: True)+ assert sd_backend.accelerator_probe_failure_is_decisive("cuda") is Trueassert called == []def test_the_off_switch_beats_the_preflight(self, monkeypatch):@@ -2840,10 +2849,11 @@ class TestTheRouterRecordsTheBundleNotTheServer:)def test_a_bundle_where_nothing_runs_is_still_recorded(self):- source = self._selection_source()- assert (- "if binary is None and server_binary is None and (unlaunchable_cli or unlaunchable_server):"- in source+ source = " ".join(self._selection_source().split())+ assert re.search(+ r"if \(? ?binary is None and server_binary is None and "+ r"\(unlaunchable_cli or unlaunchable_server\)",+ source,)diff --git a/studio/backend/tests/test_sd_cpp_vulkan_cpu_torch.py b/studio/backend/tests/test_sd_cpp_vulkan_cpu_torch.pyindex 0d898ecb975..e49dce332ba 100644--- a/studio/backend/tests/test_sd_cpp_vulkan_cpu_torch.py+++ b/studio/backend/tests/test_sd_cpp_vulkan_cpu_torch.py@@ -71,6 +71,10 @@ def _pinned_host(monkeypatch):monkeypatch.setattr(r, "_hardware_vulkan_driver", lambda vendors: True)monkeypatch.setattr(r, "_nvidia_adapter_present", lambda: False)monkeypatch.setattr(r, "_reachable_intel_arc_render_node", lambda: True, raising = False)+ # Keeps the CUDA route beside NVIDIA (#16803) off the real llama.cpp install.+ from core.inference import sd_cpp_engine++ monkeypatch.setattr(sd_cpp_engine, "_llama_server_binary", lambda: None)@pytest.mark.parametrize(