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: fall back to CPU when auto-selected Vulkan crashes (#8050)

oobabooga738413ab087c
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.py
index 52c6ef79d00..3e62d4edaa0 100644
--- a/studio/backend/core/inference/llama_cpp.py
+++ b/studio/backend/core/inference/llama_cpp.py
@@ -23,6 +23,7 @@ import signal
import socket
import subprocess
import sys
+import tempfile
import threading
import time
import uuid
@@ -38,6 +39,7 @@ from typing import (
Mapping,
MutableMapping,
NamedTuple,
+ NoReturn,
Optional,
Union,
)
@@ -176,6 +178,7 @@ class GgufLoadIntent:
extra_args_inherited: bool = False
preserve_multi_gpu_on_layer: bool = False
compare_mtp_draft: bool = False
+ cpu_fallback: bool = False
def __post_init__(self):
for key in ("tensor_split", "gpu_ids", "extra_args"):
@@ -186,6 +189,15 @@ class GgufLoadIntent:
object.__setattr__(self, "gpu_ids", None)
+class _CpuFallbackRuntime(NamedTuple):
+ tempdir: tempfile.TemporaryDirectory
+ source_binary: Path
+ staged_binary: Path
+ # An update swaps the install dir in place, so the path alone cannot tell a
+ # refreshed build from the staged copy of the old one.
+ source_stamp: tuple
+
+
# Shared so the from_identifier preflight and the load-time raise stay in sync.
LLAMA_SERVER_NOT_FOUND_DETAIL = (
"This is a GGUF model, but the llama.cpp runtime (llama-server) is not "
@@ -1915,6 +1927,23 @@ _CPU_PLACEMENT_PRESENCE_FLAGS = (_MOE_OFFLOAD_FLAGS - _CPU_MOE_COUNT_FLAGS) | fr
)
_CPU_PLACEMENT_FLAGS = _MOE_OFFLOAD_FLAGS | frozenset({"-ot", "--override-tensor"})
_THREAD_OVERRIDE_FLAGS = frozenset({"-t", "--threads"})
+
+
+def _strip_flag_pairs(args: Iterable[str], flags: frozenset[str]) -> list[str]:
+ """Drop each ``flag value`` pair naming one of ``flags``."""
+ out: list[str] = []
+ skip = False
+ for arg in args:
+ if skip:
+ skip = False
+ continue
+ if str(arg) in flags:
+ skip = True
+ continue
+ out.append(str(arg))
+ return out
+
+
# common_params defaults in the bundled llama.cpp runtime.
_DEFAULT_LLAMA_N_BATCH = 2048
_DEFAULT_LLAMA_N_UBATCH = 512
@@ -2973,14 +3002,8 @@ def _apply_igpu_host_reserve_mib(free_mib: int, is_igpu: bool) -> int:
return max(0, free_mib - _IGPU_HOST_RESERVE_MIB)
-def _llama_lib_dir(binary: str) -> Path:
- # The installer exposes llama-server as a top-level entrypoint into build/bin/,
- # where the ggml backend libs live, so callers looking for sibling libs (Vulkan
- # detection, LD_LIBRARY_PATH, probe bindir) need the real dir. It is normally a
- # symlink (resolve() reaches build/bin), but create_exec_entrypoint falls back to
- # a shell wrapper (exec "$(dirname "$0")/build/bin/llama-server" "$@") when it
- # cannot symlink, and resolve() stops at the wrapper file. Follow the wrapper's
- # exec target too, so a wrapper-based install still finds build/bin.
+def _resolve_llama_binary(binary: str) -> Path:
+ """Resolve a managed symlink or shell entrypoint to the real server."""
resolved = Path(binary).resolve()
try:
with open(resolved, "rb") as _f:
@@ -2988,10 +3011,61 @@ def _llama_lib_dir(binary: str) -> Path:
if _head.startswith(b"#!"):
_m = re.search(r'exec "\$\(dirname "\$0"\)/([^"]+)"', _head.decode("utf-8", "ignore"))
if _m:
- return (resolved.parent / _m.group(1)).resolve().parent
+ return (resolved.parent / _m.group(1)).resolve()
except OSError:
pass
- return resolved.parent
+ return resolved
+
+
+def _llama_lib_dir(binary: str) -> Path:
+ return _resolve_llama_binary(binary).parent
+
+
+_CPU_RUNTIME_OWNER_FILE = "UNSLOTH_OWNER_PID"
+
+
+def _cpu_runtime_owner_alive(staged_dir: Path) -> bool:
+ """Whether a live process still owns this staged CPU-fallback runtime."""
+ try:
+ pid = int((staged_dir / _CPU_RUNTIME_OWNER_FILE).read_text(encoding = "utf-8").strip())
+ except (OSError, ValueError):
+ # No owner stamp: written by an older Studio, so leave it alone.
+ return True
+ if pid == os.getpid():
+ return True
+ # 0 and negatives address process groups, never an owner.
+ if pid <= 0:
+ return False
+ if sys.platform == "win32":
+ import ctypes
+
+ kernel32 = ctypes.WinDLL("kernel32", use_last_error = True)
+ ctypes.set_last_error(0)
+ handle = kernel32.OpenProcess(0x00100000, False, pid)
+ if not handle:
+ return ctypes.get_last_error() != 87 # ERROR_INVALID_PARAMETER
+ kernel32.CloseHandle(handle)
+ return True
+ try:
+ os.kill(pid, 0)
+ except ProcessLookupError:
+ return False
+ except OSError:
+ return True
+ return True
+
+
+def _sweep_abandoned_cpu_runtimes(runtime_root: Path) -> None:
+ """Delete staged runtimes whose owning Studio is gone (kill -9, host crash)."""
+ try:
+ candidates = list(runtime_root.glob("llama-cpu-*"))
+ except OSError:
+ return
+ for staged_dir in candidates:
+ if not staged_dir.is_dir() or _cpu_runtime_owner_alive(staged_dir):
+ continue
+ with contextlib.suppress(OSError):
+ shutil.rmtree(staged_dir, ignore_errors = True)
def _lib_dir_has_ggml_backend(lib_dir: Path, backend: str) -> bool:
@@ -3085,6 +3159,10 @@ class LlamaCppBackend:
self._spec_fallback_reason: Optional[str] = None
self._spec_drafter_kind: Optional[str] = None
self._dspark_sidecar_absent: bool = False
+ # Set after an auto-Vulkan crash recovers with all devices disabled.
+ self._cpu_fallback_reason: Optional[str] = None
+ self._cpu_fallback_runtime: Optional[_CpuFallbackRuntime] = None
+ self._pending_cpu_fallback_cleanups: list = []
self._hf_variant: Optional[str] = None
self._is_vision: bool = False
# Block-diffusion model (e.g. DiffusionGemma): served by the diffusion
@@ -4461,6 +4539,23 @@ class LlamaCppBackend:
return total
+ @staticmethod
+ def _installed_ggml_backends(binary: Optional[str] = None) -> frozenset[str]:
+ """Backend libraries shipped beside llama-server."""
+ binary = binary or LlamaCppBackend._find_llama_server_binary()
+ if not binary:
+ return frozenset()
+ try:
+ files = tuple(path.name for path in _llama_lib_dir(binary).iterdir() if path.is_file())
+ except OSError:
+ return frozenset()
+ backends = set()
+ for backend in ("base", "cpu", "cuda", "hip", "vulkan"):
+ stem = f"ggml-{backend}.dll" if sys.platform == "win32" else f"libggml-{backend}.so"
+ if any(name == stem or name.startswith(stem + ".") for name in files):
+ backends.add(backend)
+ return frozenset(backends)
+
@staticmethod
def _is_vulkan_backend(binary: Optional[str] = None) -> bool:
"""True if the installed llama.cpp build is Vulkan-only.
@@ -4471,16 +4566,8 @@ class LlamaCppBackend:
multi-backend build with a CUDA or HIP ggml lib alongside Vulkan, defer
to that backend (torch-usable, better-understood probe/pin).
"""
- binary = binary or LlamaCppBackend._find_llama_server_binary()
- if not binary:
- return False
- lib_dir = _llama_lib_dir(binary)
- if not _lib_dir_has_ggml_backend(lib_dir, "vulkan"):
- return False
- for _backend in ("cuda", "hip"):
- if _lib_dir_has_ggml_backend(lib_dir, _backend):
- return False
- return True
+ backends = LlamaCppBackend._installed_ggml_backends(binary)
+ return "vulkan" in backends and not backends.intersection({"cuda", "hip"})
@staticmethod
def _resolve_visible_physical_ids() -> Optional[list[int]]:
@@ -4947,12 +5034,10 @@ class LlamaCppBackend:
binary = binary or LlamaCppBackend._find_llama_server_binary()
if not binary:
return False
- lib_dir = _llama_lib_dir(binary)
- if not lib_dir or not lib_dir.is_dir():
- return False
- if any(_lib_dir_has_ggml_backend(lib_dir, b) for b in ("vulkan", "cuda", "hip")):
- return False
- return any(_lib_dir_has_ggml_backend(lib_dir, b) for b in ("cpu", "base"))
+ backends = LlamaCppBackend._installed_ggml_backends(binary)
+ return bool(backends.intersection({"cpu", "base"})) and not backends.intersection(
+ {"cuda", "hip", "vulkan"}
+ )
def is_vulkan_build(self) -> bool:
"""Whether the resolved llama-server uses Vulkan ordinals."""
@@ -5409,6 +5494,15 @@ class LlamaCppBackend:
"LLAMA_ARG_FIT_CTX",
)
+ # Eligibility must reject every inherited placement value replay removes.
+ _CPU_FALLBACK_MAIN_PLACEMENT_ENV_VARS = (
+ *_MANUAL_PLACEMENT_ENV_VARS,
+ "LLAMA_ARG_DEVICE",
+ "LLAMA_ARG_MAIN_GPU",
+ "LLAMA_ARG_SPLIT_MODE",
+ "LLAMA_ARG_OVERRIDE_TENSOR",
+ )
+
# (binary, mtime, model) that aborted on --split-mode tensor this process (#6415
# geometry limit, e.g. MQA n_head_kv=1). Model-keyed so one model's abort doesn't
# skip tensor for others; tensor is tried by default, recorded only on a real abort.
@@ -8691,6 +8785,404 @@ class LlamaCppBackend:
out.append(tok)
return out
+ @staticmethod
+ def _vulkan_prebuilt_was_auto_selected(binary: Optional[str]) -> bool:
+ """Whether setup chose this managed Vulkan bundle without an override.
+
+ Explicit selections set an override or marker. The managed marker also
+ excludes custom and PATH binaries.
+ """
+ if not binary:
+ return False
+ if os.environ.get("UNSLOTH_FORCE_VULKAN", "").strip().lower() in {
+ "1",
+ "true",
+ "yes",
+ "on",
+ }:
+ return False
+ if (os.environ.get("UNSLOTH_LLAMA_CPP_BACKEND") or "").strip().lower() in {
+ "cpu",
+ "vulkan",
+ "hip",
+ "rocm",
+ }:
+ return False
+ try:
+ from utils.llama_cpp_update import _llama_install_root
+
+ install_root = _llama_install_root(binary)
+ if install_root is None:
+ return False
+ marker = json.loads(
+ (install_root / "UNSLOTH_PREBUILT_INFO.json").read_text(encoding = "utf-8")
+ )
+ except (OSError, ValueError, TypeError):
+ return False
+ return (
+ isinstance(marker, dict)
+ and not bool(marker.get("force_cpu"))
+ and marker.get("llama_backend") in (None, "", "auto")
+ )
+
+ @staticmethod
+ def _strip_cpu_fallback_main_placement(args: Iterable[str]) -> list[str]:
+ """Remove every raw main-model placement choice the CPU replay replaces."""
+ stripped = strip_shadowing_flags(
+ args,
+ strip_context = False,
+ strip_cache = False,
+ strip_spec = False,
+ strip_template = False,
+ strip_split_mode = True,
+ strip_offload = True,
+ strip_device = True,
+ )
+ return _paravirtual_strip_gpu_overrides(stripped, log_dropped = False) or []
+
+ @classmethod
+ def _cpu_fallback_request_eligible(
+ cls,
+ intent: GgufLoadIntent,
+ extra_args: Optional[Iterable[str]],
+ env: Optional[Mapping[str, str]] = None,
+ *,
+ allow_manual_cpu: bool = False,
+ ) -> bool:
+ """Whether CPU recovery may replace the requested placement."""
+ args = [str(arg) for arg in (extra_args or ())]
+ companion_placement_flags = {
+ *_OVERRIDE_TENSOR_FLAGS,
+ "--spec-draft-device",
+ "-devd",
+ "--device-draft",
+ "--spec-draft-ngl",
+ "-ngld",
+ "--gpu-layers-draft",
+ "--n-gpu-layers-draft",
+ "--mmproj-offload",
+ "--no-mmproj-offload",
+ }
+ child_env = os.environ if env is None else env
+ placement_eligible = intent.gpu_memory_mode == "auto" or (
+ allow_manual_cpu and intent.gpu_memory_mode == "manual" and intent.gpu_layers == 0
+ )
+ return bool(
+ placement_eligible
+ and not intent.gpu_ids
+ and not intent.tensor_parallel
+ and not intent.tensor_split
+ and intent.n_cpu_moe == 0
+ and cls._strip_cpu_fallback_main_placement(args) == args
+ and not _extra_args_set_any_flag(args, companion_placement_flags)
+ and not any(
+ str(child_env.get(name) or "").strip()
+ for name in (
+ *cls._CPU_FALLBACK_MAIN_PLACEMENT_ENV_VARS,
+ "LLAMA_ARG_N_GPU_LAYERS_DRAFT",
+ "LLAMA_ARG_MMPROJ_OFFLOAD",
+ "GGML_BACKEND_PATH",
+ )
+ )
+ )
+
+ @classmethod
+ def _auto_vulkan_cpu_fallback_eligible(
+ cls,
+ binary: Optional[str],
+ intent: GgufLoadIntent,
+ extra_args: Optional[Iterable[str]],
+ env: Optional[Mapping[str, str]] = None,
+ *,
+ allow_manual_cpu: bool = False,
+ ) -> bool:
+ """Whether a signal may replace automatic Vulkan placement with CPU."""
+ return bool(
+ cls._cpu_fallback_request_eligible(
+ intent, extra_args, env, allow_manual_cpu = allow_manual_cpu
+ )
+ and cls._is_vulkan_backend(binary)
+ and cls._vulkan_prebuilt_was_auto_selected(binary)
+ )
+
+ @staticmethod
+ def _as_cpu_fallback_intent(intent: GgufLoadIntent) -> GgufLoadIntent:
+ return replace(
+ intent,
+ gpu_memory_mode = "manual",
+ gpu_layers = 0,
+ n_cpu_moe = 0,
+ tensor_parallel = False,
+ tensor_split = None,
+ gpu_ids = None,
+ cpu_fallback = True,
+ )
+
+ def _preserve_cpu_fallback_intent(
+ self,
+ intent: GgufLoadIntent,
+ *,
+ source_matches: bool = False,
+ ) -> GgufLoadIntent:
+ if not self._cpu_fallback_reason:
+ return intent
+ if not source_matches and not self.matches_load_source(intent):
+ return intent
+ extras = list(intent.extra_args) if intent.extra_args is not None else None
+ # Judge the env the replay runs with, not this process's: _cpu_isolated_replay
+ # pops every main-model placement var first. Using os.environ would drop the
+ # recovery over a value no child saw, re-running the crash on every reload.
+ replay_env = {
+ name: value
+ for name, value in os.environ.items()
+ if name not in self._CPU_FALLBACK_MAIN_PLACEMENT_ENV_VARS
+ and name != "GGML_BACKEND_PATH"
+ }
+ if not self._cpu_fallback_request_eligible(
+ intent,
+ extras,
+ replay_env,
+ allow_manual_cpu = True,
+ ):
+ return intent
+ return self._as_cpu_fallback_intent(intent)
+
+ def _apply_cpu_fallback_state(
+ self, intent: GgufLoadIntent, *, is_vision: bool, mmproj_has_audio: bool
+ ) -> GgufLoadIntent:
+ intent = self._as_cpu_fallback_intent(intent)
+ self._gpu_memory_mode = intent.gpu_memory_mode
+ self._gpu_layers = intent.gpu_layers
+ self._n_cpu_moe = intent.n_cpu_moe
+ self._tensor_split = intent.tensor_split
+ self._tensor_parallel = intent.tensor_parallel
+ self._gpu_ids = intent.gpu_ids
+ self._requested_gpu_ids = None
+ self._layer_preserves_tensor_intent = False
+ self._is_vision = is_vision
+ self._mmproj_has_audio = mmproj_has_audio
+ self._cpu_fallback_reason = "vulkan_startup_crash"
+ return intent
+
+ @staticmethod
+ def _launch_has_mmproj(cmd: Iterable[str], env: Mapping[str, str]) -> bool:
+ """Whether this launch receives a projector from argv or the environment."""
+ return _extra_args_set_any_flag(cmd, {"--mmproj", "-mm"}) or any(
+ str(env.get(name) or "").strip()
+ for name in ("LLAMA_ARG_MMPROJ", "LLAMA_ARG_MMPROJ_URL")
+ )
+
+ @classmethod
+ def _cpu_isolated_replay(
+ cls,
+ cmd: Iterable[str],
+ env: dict[str, str],
+ server_caps: Mapping[str, object],
+ *,
+ drop_full_offload_threads: bool = False,
+ ) -> Optional[list[str]]:
+ """Build a replay that cannot initialize or schedule on a GPU.
+
+ Unlike ``-ngl 0``, ``--device none`` removes GPU devices. Refuse companions
+ that this binary cannot pin to CPU.
+ """
+ original = [str(arg) for arg in cmd]
+ has_mmproj = cls._launch_has_mmproj(original, env)
+ if has_mmproj and not _paravirtual_mmproj_pinnable(server_caps):
+ return None
+ has_draft = _extra_args_mtp_draft_path(original, env = env) is not None
+ draft_ngl_flag = _paravirtual_draft_ngl_flag(server_caps) if has_draft else None
+ if has_draft and draft_ngl_flag is None:
+ return None
+
+ replay = cls._strip_cpu_fallback_main_placement(original)
+ if drop_full_offload_threads:
+ # Windows full-offload tuning pins 2 threads and PASSIVE OpenMP because
+ # the GPU was doing the work, so a CPU replay would decode on 2 cores.
+ # Only Unsloth's own values: a user --threads override is reported by
+ # the caller, and the env vars were setdefault'd.
+ replay = _strip_flag_pairs(replay, _THREAD_OVERRIDE_FLAGS)
+ for name in ("OMP_NUM_THREADS", "OMP_WAIT_POLICY"):
+ env.pop(name, None)
+ replay.extend(["--gpu-layers", "0", "--fit", "off", "--device", "none"])
+ if has_mmproj:
+ replay.append("--no-mmproj-offload")
+ if has_draft:
+ replay.extend([str(draft_ngl_flag), "0", "--device-draft", "none"])
+
+ for name in (*cls._CPU_FALLBACK_MAIN_PLACEMENT_ENV_VARS, "GGML_BACKEND_PATH"):
+ env.pop(name, None)
+ return replay
+
+ def _prepare_cpu_fallback_launch(
+ self,
+ binary: Optional[str],
+ cmd: Iterable[str],
+ env: dict[str, str],
+ server_caps: Mapping[str, object],
+ *,
+ drop_full_offload_threads: bool = False,
+ ) -> Optional[tuple[list[str], Optional[str]]]:
+ # Staging only removes GPU backends; a non-Vulkan install would report a
+ # Vulkan crash that never happened.
+ if not self._is_vulkan_backend(binary):
+ return None
+ replay = self._cpu_isolated_replay(
+ cmd, env, server_caps, drop_full_offload_threads = drop_full_offload_threads
+ )
+ if replay is None:
+ return None
+ cpu_binary = self._cpu_isolated_binary(binary)
+ if cpu_binary is None:
+ return None
+ loader_env = self._llama_server_env_for_binary(cpu_binary)
+ loader_path = "PATH" if sys.platform == "win32" else "LD_LIBRARY_PATH"
+ env[loader_path] = loader_env[loader_path]
+ replay[0] = cpu_binary
+ # Staging covers only the executable and libraries, so keep Studio's working
+ # directory: relative paths in user extra args resolve against it.
+ return replay, None
+
+ def _cpu_isolated_binary(self, binary: Optional[str]) -> Optional[str]:
+ """Stage managed llama.cpp without GPU backend libraries.
+
+ Backend loading precedes ``--device none``, so isolation prevents the
+ Vulkan plugin from loading first.
+ """
+ if not binary or not self._is_unsloth_managed_binary(binary):
+ return None
+ source_binary = _resolve_llama_binary(binary)
+ source_stamp = self._binary_stamp(source_binary)
+ runtime = self._cpu_fallback_runtime
+ if (
+ runtime is not None
+ and runtime.source_binary == source_binary
+ and runtime.source_stamp == source_stamp
+ ):
+ if runtime.staged_binary.is_file():
+ return str(runtime.staged_binary)
+ self._cleanup_cpu_fallback_runtime()
+ staged_runtime = None
+ try:
+ runtime_root = _swa_cache_path().parent / "runtime"
+ runtime_root.mkdir(parents = True, exist_ok = True)
+ _sweep_abandoned_cpu_runtimes(runtime_root)
+ staged_runtime = tempfile.TemporaryDirectory(
+ prefix = "llama-cpu-",
+ dir = runtime_root,
+ )
+ staged_dir = Path(staged_runtime.name)
+ # A kill -9 skips TemporaryDirectory's atexit hook, so stamp the owner
+ # and let the next stage collect what no live Studio holds.
+ (staged_dir / _CPU_RUNTIME_OWNER_FILE).write_text(str(os.getpid()), encoding = "utf-8")
+ lib_dir = _llama_lib_dir(str(source_binary))
+ gpu_backend = re.compile(
+ r"^(?:lib)?ggml-(?:cuda|hip|vulkan|metal|sycl|opencl|musa|cann|virtgpu)"
+ )
+ cpu_library_present = False
+ for source in lib_dir.iterdir():
+ try:
+ resolved = source.resolve(strict = True)
+ except OSError:
+ continue
+ name = source.name
+ is_shared = name.endswith((".dll", ".dylib")) or ".so" in name
+ if resolved != source_binary and not is_shared:
+ continue
+ if gpu_backend.match(name.lower()):
+ continue
+ destination = staged_dir / name
+ if destination.exists():
+ continue
+ try:
+ os.link(resolved, destination)
+ except OSError:
+ shutil.copy2(resolved, destination)
+ if name.lower().startswith(("libggml-cpu", "ggml-cpu")):
+ cpu_library_present = True
+ staged_binary = staged_dir / source_binary.name
+ if not staged_binary.is_file() or not cpu_library_present:
+ staged_runtime.cleanup()
+ return None
+ except (OSError, ValueError):
+ if staged_runtime is not None:
+ with contextlib.suppress(Exception):
+ staged_runtime.cleanup()
+ return None
+ self._cpu_fallback_runtime = _CpuFallbackRuntime(
+ tempdir = staged_runtime,
+ source_binary = source_binary,
+ staged_binary = staged_binary,
+ source_stamp = source_stamp,
+ )
+ return str(staged_binary)
+
+ @staticmethod
+ def _binary_stamp(path: Path) -> tuple:
+ try:
+ stat = path.stat()
+ except OSError:
+ return ()
+ return (stat.st_ino, stat.st_size, stat.st_mtime_ns)
+
+ def _cleanup_cpu_fallback_runtime(self) -> None:
+ runtime = getattr(self, "_cpu_fallback_runtime", None)
+ self._cpu_fallback_runtime = None
+ # cleanup() detaches its finalizer before removing the tree, so dropping a
+ # failed one (locked DLL on Windows) orphans it. Retry it on the next call.
+ pending = getattr(self, "_pending_cpu_fallback_cleanups", [])
+ if runtime is not None:
+ pending.append(runtime.tempdir)
+ retry = []
+ for tempdir in pending:
+ try:
+ tempdir.cleanup()
+ except Exception:
+ retry.append(tempdir)
+ self._pending_cpu_fallback_cleanups = retry
+
+ def _cleanup_failed_cpu_fallback(self) -> None:
+ """Remove every process and staged artifact from a terminal CPU replay."""
+ self._kill_process()
+ self._cpu_fallback_reason = None
+ self._cleanup_cpu_fallback_runtime()
+
+ @staticmethod
+ def _gpu_init_crash_message(binary: Optional[str] = None) -> str:
+ """Return backend-specific advice for a GPU initialization crash."""
+ base = (
+ "llama-server crashed at startup on both the vision and text-only "
+ "attempts -- a GPU driver/runtime initialization crash, not a model "
+ "or vision-projector problem. "
+ )
+ backends = LlamaCppBackend._installed_ggml_backends(binary)
+ backend = next((name for name in ("cuda", "hip", "vulkan") if name in backends), None)
+ if backend == "vulkan":
+ return base + (
+ "This build uses Vulkan, which Unsloth selects when it detects an "
+ "Intel or AMD GPU. Older integrated GPUs and their drivers can fault "
+ "inside Vulkan device initialization. Update your Vulkan driver (Mesa "
+ "on Linux), or reinstall llama.cpp on CPU with "
+ "UNSLOTH_LLAMA_CPP_BACKEND=cpu unsloth studio update."
+ )
+ if backend == "hip":
+ return base + (
+ "This often means an unsupported secondary GPU; on AMD/ROCm, hide it "
+ "with ROCR_VISIBLE_DEVICES (e.g. ROCR_VISIBLE_DEVICES=0 exposes only "
+ "the first GPU) before launching Unsloth Studio."
+ )
+ if backend == "cuda":
+ return base + (
+ "This often means an unsupported secondary GPU or a driver/CUDA "
+ "runtime mismatch; hide the extra GPU with CUDA_VISIBLE_DEVICES (e.g. "
+ "CUDA_VISIBLE_DEVICES=0 exposes only the first GPU) before launching "
+ "Unsloth Studio, or update the NVIDIA driver."
+ )
+ return base + (
+ "Check the llama-server log and your GPU driver, and make sure the "
+ "installed llama.cpp build matches this machine's GPU."
+ )
+
@staticmethod
def _redacted_cmd_for_log(cmd: "list[str]") -> "list[str]":
"""Copy of cmd with the value after --api-key replaced by <redacted>."""
@@ -8798,6 +9290,14 @@ class LlamaCppBackend:
if getattr(self, "_llama_update_in_progress", False):
raise RuntimeError("llama.cpp is updating; try again in a moment.")
+ intent = self._preserve_cpu_fallback_intent(intent)
+ tensor_parallel = intent.tensor_parallel
+ gpu_memory_mode = intent.gpu_memory_mode
+ gpu_layers = intent.gpu_layers
+ n_cpu_moe = intent.n_cpu_moe
+ tensor_split = list(intent.tensor_split) if intent.tensor_split is not None else None
+ gpu_ids = list(intent.gpu_ids) if intent.gpu_ids is not None else None
+
# A virtualised Apple GPU corrupts every offloaded layer, so pin GGUF
# inference to CPU there; physical Apple Silicon is untouched. Settled
# ABOVE the duplicate-load check (and the KV estimates) so the compared
@@ -9021,8 +9521,12 @@ class LlamaCppBackend:
raise ValueError(_PARAVIRTUAL_DIFFUSION_NO_NGL_ERROR)
# ── Phase 1: kill old process (under lock, fast) ──────────
+ _replaying_cpu_fallback = intent.cpu_fallback
with self._lock:
self._kill_process()
+ if not _replaying_cpu_fallback:
+ self._cpu_fallback_reason = None
+ self._cleanup_cpu_fallback_runtime()
# ── Phase 2: download (NO lock held, so cancel can proceed) ──
# mtp_draft_path arrives set for local Gemma loads (detected
@@ -10440,16 +10944,19 @@ class LlamaCppBackend:
raise RuntimeError(_ram_msg)
# Audio input straight from the mmproj (clip.has_audio_encoder),
- # independent of token names.
+ # independent of token names. A projector passed only via
+ # LLAMA_ARG_MMPROJ misses launch_mmproj_path, so probe that too,
+ # but never one the unpinnable guard just dropped.
self._mmproj_has_audio = False
- if launch_mmproj_path:
+ _audio_probe = launch_mmproj_path or (
+ "" if _pv_mmproj_unpinnable else (os.environ.get("LLAMA_ARG_MMPROJ") or "")
+ )
+ if launch_mmproj_path or os.path.isfile(_audio_probe):
try:
from utils.models.gguf_metadata import (
read_mmproj_audio_capability,
)
- self._mmproj_has_audio = bool(
- read_mmproj_audio_capability(launch_mmproj_path)
- )
+ self._mmproj_has_audio = bool(read_mmproj_audio_capability(_audio_probe))
except Exception as e:
logger.debug(f"mmproj audio-capability read failed: {e}")
@@ -10617,6 +11124,13 @@ class LlamaCppBackend:
)
threads_overridden = _extra_args_set_any_flag(extra_args, _THREAD_OVERRIDE_FLAGS)
full_offload_tuning_active = fully_gpu_offloaded and not offload_overridden
+ # The CPU replay must undo what this launch pins for an absent GPU;
+ # a user's own --threads still wins.
+ _drop_full_offload_threads = (
+ sys.platform == "win32"
+ and full_offload_tuning_active
+ and not threads_overridden
+ )
# Thread count: an unset --threads makes llama.cpp pick physical
# cores (common_cpu_get_num_math), but an explicit --threads -1
@@ -11233,6 +11747,15 @@ class LlamaCppBackend:
if gpu_ids is not None:
self._clear_device_placement_env(env)
+ # After the scrubs above, so a placement this launch already dropped
+ # cannot disqualify the replay of a child that never saw it.
+ _cpu_fallback_eligible = self._auto_vulkan_cpu_fallback_eligible(
+ binary,
+ intent,
+ extra_args,
+ env,
+ )
+
# The unpinnable-drafter drop above rewrites argv, which cannot reach the
# drafter the child picks up from its own env. The spec type goes too,
# for the same reason the CLI one did: llama.cpp appends types rather
@@ -11351,6 +11874,7 @@ class LlamaCppBackend:
# passed an explicit fit flag via extra args.
# Argv actually launched (post --fit off / MTP); text-only retry strips this.
_last_spawn_cmd = list(cmd)
+ _spawn_cwd: Optional[str] = None
def _spawn_and_wait(run_cmd, *, label = ""):
"""Start llama-server with run_cmd and wait for health.
@@ -11406,6 +11930,7 @@ class LlamaCppBackend:
encoding = "utf-8",
errors = "replace",
env = env,
+ cwd = _spawn_cwd,
**_windows_hidden_subprocess_kwargs(),
**_child_popen_kwargs(),
)
@@ -11528,6 +12053,96 @@ class LlamaCppBackend:
continue
return False
+ _launched_mmproj_has_audio = self._mmproj_has_audio
+
+ def _raise_terminal_load_failure(detail: str) -> NoReturn:
+ if intent.cpu_fallback:
+ self._cleanup_failed_cpu_fallback()
+ raise RuntimeError(detail)
+
+ def _try_auto_vulkan_cpu_fallback(
+ failed_cmd: list[str],
+ failed_rc: Optional[int],
+ *,
+ terminal: bool = True,
+ ) -> bool:
+ """Replay an eligible signal crash without devices.
+
+ ``terminal`` off reports a failed CPU spawn as "not recovered"
+ instead of raising, for a caller that still holds another argv
+ worth replaying.
+ """
+ nonlocal intent, gpu_memory_mode, gpu_layers, n_cpu_moe
+ nonlocal tensor_parallel, tensor_split, gpu_indices, use_fit, _spawn_cwd
+ # GGML_ASSERT is a signal on POSIX and a CRT abort (exit 3) on
+ # MSVC, so Windows needs both. Cancel-checked like every retry
+ # here: an /unload racing the crash must not leave a server up.
+ _crashed = self._is_signal_crash(failed_rc) or (
+ sys.platform == "win32" and self._is_abort_exit(failed_rc)
+ )
+ if not _crashed or not _cpu_fallback_eligible or self._cancel_event.is_set():
+ return False
+ fallback_has_mmproj = self._launch_has_mmproj(failed_cmd, env)
+ prepared = self._prepare_cpu_fallback_launch(
+ binary,
+ failed_cmd,
+ env,
+ server_caps,
+ drop_full_offload_threads = _drop_full_offload_threads,
+ )
+ if prepared is None:
+ return False
+ if self._cancel_event.is_set():
+ # Staging copies a whole runtime, so an /unload can land after
+ # the gate above with no runtime yet for unload_model() to
+ # remove; take it back here.
+ self._cleanup_cpu_fallback_runtime()
+ return False
+ replay, _spawn_cwd = prepared
+
+ logger.warning(
+ "The auto-selected Vulkan backend hard-crashed during "
+ "startup; retrying once with llama.cpp devices disabled."
+ )
+ if not _spawn_and_wait(replay, label = "-cpu"):
+ if not terminal:
+ # This argv's drafter may be why it cannot start at all,
+ # which the GPU crash says nothing about. Reap the child
+ # and keep the staged runtime for the caller's next argv.
+ self._kill_process()
+ return False
+ cpu_rc = self._process.poll() if self._process is not None else None
+ detail = self._classify_llama_start_failure(
+ "\n".join(self._stdout_lines[-50:]),
+ gguf_path,
+ self._model_identifier,
+ cpu_rc,
+ binary,
+ )
+ self._cleanup_failed_cpu_fallback()
+ raise RuntimeError(detail)
+
+ intent = self._apply_cpu_fallback_state(
+ intent,
+ is_vision = fallback_has_mmproj,
+ mmproj_has_audio = (
+ _launched_mmproj_has_audio if fallback_has_mmproj else False
+ ),
+ )
+ gpu_memory_mode = intent.gpu_memory_mode
+ gpu_layers = intent.gpu_layers
+ n_cpu_moe = intent.n_cpu_moe
+ tensor_parallel = intent.tensor_parallel
+ tensor_split = intent.tensor_split
+ gpu_indices = None
+ use_fit = False
+ logger.warning(
+ "llama-server loaded successfully on CPU after the "
+ "auto-selected Vulkan backend crashed. GPU acceleration "
+ "is disabled for this model session."
+ )
+ return True
+
# Store the resolved on-disk path, not the caller's kwarg: in
# HF mode gguf_path is None and ``model_path`` is what
# llama-server mmap's, which downstream consumers need. Must be
@@ -11560,6 +12175,49 @@ class LlamaCppBackend:
max_available_ctx if max_available_ctx > 0 else self._effective_context_length
)
+ # LoadRequest carries this flag, so a stale rollback, an API caller or
+ # a swapped-out runtime can ask for a replay that never happened. Hold
+ # it to the crash path's bar (managed auto Vulkan, no explicit
+ # placement) and otherwise run the request as sent.
+ if intent.cpu_fallback:
+ if self._auto_vulkan_cpu_fallback_eligible(
+ binary, intent, extra_args, env, allow_manual_cpu = True
+ ):
+ prepared = self._prepare_cpu_fallback_launch(
+ binary,
+ cmd,
+ env,
+ server_caps,
+ drop_full_offload_threads = _drop_full_offload_threads,
+ )
+ if prepared is None:
+ _raise_terminal_load_failure(
+ "The prior Vulkan CPU fallback could not be reconstructed; run "
+ "`unsloth studio update` to repair the managed llama.cpp runtime."
+ )
+ cmd, _spawn_cwd = prepared
+ # Same normalization the crash path applies, so a client that
+ # sent only the flag cannot leave a CPU-only server reporting
+ # an Auto/GPU placement (which then fails holds_no_vram).
+ intent = self._apply_cpu_fallback_state(
+ intent,
+ is_vision = self._is_vision,
+ mmproj_has_audio = self._mmproj_has_audio,
+ )
+ gpu_memory_mode = intent.gpu_memory_mode
+ gpu_layers = intent.gpu_layers
+ n_cpu_moe = intent.n_cpu_moe
+ tensor_parallel = intent.tensor_parallel
+ tensor_split = intent.tensor_split
+ gpu_indices = None
+ use_fit = False
+ else:
+ # Phase 1 kept recovery state for a replay this request does
+ # not qualify for. Drop it, or this load reports the old crash
+ # and _preserve_cpu_fallback_intent rewrites later reloads.
+ intent = replace(intent, cpu_fallback = False)
+ self._cpu_fallback_reason = None
+ self._cleanup_cpu_fallback_runtime()
# The placement above is now fixed for this child, but _process
# is not set until Popen. Without this, a save landing in that
# window sees no active backend and reports no reload while the
@@ -11682,11 +12340,16 @@ class LlamaCppBackend:
# _requested_spec_mode so a duplicate /load doesn't thrash. The
# cancel check stops an /unload-killed attempt respawning. A
# decode-probe failure above also routes here.
+ # The retry replaces _last_spawn_cmd with a drafterless argv, but a GPU
+ # init crash is not the drafter's fault: keep the requested launch so
+ # the CPU replay below can still run it.
+ _spec_cpu_replay_cmd: Optional[List[str]] = None
if (
not healthy
and (_spec_requested_mtp or _spec_requested_dspark)
and not self._cancel_event.is_set()
):
+ _spec_cpu_replay_cmd = list(_last_spawn_cmd)
# Blame the binary only when the output shows MTP itself
# failing (unknown arch / draft or context build); an
# unrelated crash (e.g. OOM) gets a neutral message.
@@ -11809,6 +12472,7 @@ class LlamaCppBackend:
and not self._cancel_event.is_set()
and (_projector_msg or _signal_mmproj_guess)
):
+ _vision_cpu_replay_cmd = list(_last_spawn_cmd)
if _projector_msg:
logger.warning(
"llama-server could not load this model's vision "
@@ -11836,43 +12500,65 @@ class LlamaCppBackend:
# an OS-killed text-only retry still gets the OOM message.
_retry_rc = self._process.poll() if self._process is not None else None
self._kill_process()
- # If the text-only retry ALSO hard-crashed (a signal, not
- # OOM/timeout), the vision projector was never the cause:
- # llama-server is faulting during GPU/driver init. Say so
- # -- with the ROCm fix -- instead of blaming the mmproj.
+ # A text-only signal crash is independent evidence of a GPU
+ # startup fault. Keep a confirmed bad projector out of the
+ # replay; a guessed one still gets a CPU try with vision.
if self._is_signal_crash(_retry_rc):
- raise RuntimeError(
- "llama-server crashed at startup on both the vision "
- "and text-only attempts -- a GPU driver/runtime "
- "initialization crash, not a model or vision-projector "
- "problem. This often means an unsupported secondary "
- "GPU; on AMD/ROCm, hide it with ROCR_VISIBLE_DEVICES "
- "(e.g. ROCR_VISIBLE_DEVICES=0 exposes only the first "
- "GPU) before launching Unsloth Studio."
+ _cpu_replay_cmd = (
+ _last_spawn_cmd if _projector_msg else _vision_cpu_replay_cmd
)
- _retry_detail = self._classify_llama_start_failure(
- "\n".join(self._stdout_lines[-50:]),
- gguf_path,
- self._model_identifier,
- _retry_rc,
- binary,
- )
- raise RuntimeError(
- self._mmproj_retry_failure_message(
- projector_confirmed = _projector_msg,
- detail = _retry_detail,
+ if _try_auto_vulkan_cpu_fallback(
+ _cpu_replay_cmd,
+ _retry_rc,
+ ):
+ healthy = True
+ else:
+ _raise_terminal_load_failure(
+ self._gpu_init_crash_message(binary)
+ )
+ if not healthy:
+ _retry_detail = self._classify_llama_start_failure(
+ "\n".join(self._stdout_lines[-50:]),
+ gguf_path,
+ self._model_identifier,
+ _retry_rc,
+ binary,
+ )
+ _raise_terminal_load_failure(
+ self._mmproj_retry_failure_message(
+ projector_confirmed = _projector_msg,
+ detail = _retry_detail,
+ )
)
- )
else:
- raise RuntimeError(
- self._classify_llama_start_failure(
- out,
- gguf_path,
- self._model_identifier,
- _crash_rc,
- binary,
+ # Try the drafter launch first, non-terminally: a build that
+ # can neither pin one to CPU nor start with it still recovers
+ # on the drafterless argv. Snapshot that argv, since a spawned
+ # replay rebinds _last_spawn_cmd to its own command line.
+ _drafterless_cpu_replay_cmd = list(_last_spawn_cmd)
+ _replayed = _spec_cpu_replay_cmd is not None and (
+ _try_auto_vulkan_cpu_fallback(
+ _spec_cpu_replay_cmd, _crash_rc, terminal = False
)
)
+ if _replayed:
+ # The drafter came back with the replay, so the
+ # speculative-disable diagnosis no longer holds.
+ self._spec_fallback_reason = None
+ elif _try_auto_vulkan_cpu_fallback(_drafterless_cpu_replay_cmd, _crash_rc):
+ _replayed = True
+ if _replayed:
+ healthy = True
+ else:
+ _raise_terminal_load_failure(
+ self._classify_llama_start_failure(
+ out,
+ gguf_path,
+ self._model_identifier,
+ _crash_rc,
+ binary,
+ )
+ )
self._healthy = True
self._commit_effective_parallel_slots(n_parallel)
@@ -12404,6 +13090,7 @@ class LlamaCppBackend:
"""Match live state and adopt the caller's compatible GPU placement."""
if not self.matches_load_source(intent):
return False
+ intent = self._preserve_cpu_fallback_intent(intent, source_matches = True)
# The stored state is what LAUNCHED, and on a virtualised Metal device that is
# the CPU-pinned rewrite, not the request. Apply the same rewrite here
# (idempotent, so load_model's own call is a no-op) or a client that keeps
@@ -12553,10 +13240,15 @@ class LlamaCppBackend:
mmproj, and GPU drafters can still make the server hold VRAM. The counted
offload classifier cannot see those allocations. This uses the same
predicate as the launch-time zero-VRAM mask; None means no GPU signal."""
+ if LlamaCppBackend._is_vulkan_backend():
+ # Unlike -ngl 0, the recovery's last-wins --device none removes Vulkan.
+ main_device = (_extra_args_main_device(spawn_cmd) or "").strip().lower()
+ if main_device in ("cpu", "none"):
+ return LlamaCppBackend._zero_offload_keeps_gpu_visible(spawn_cmd, env)
+ if detected_gpus:
+ return True
if not detected_gpus:
return None
- if LlamaCppBackend._is_vulkan_backend():
- return True
return LlamaCppBackend._zero_offload_keeps_gpu_visible(spawn_cmd, env)
def load_cancelled(self) -> bool:
@@ -12571,6 +13263,7 @@ class LlamaCppBackend:
with self._lock:
self._unload_epoch += 1
self._kill_process()
+ self._cleanup_cpu_fallback_runtime()
logger.info(f"Unloaded GGUF model: {self._model_identifier}")
self._model_identifier = None
self._gguf_path = None
@@ -12580,6 +13273,7 @@ class LlamaCppBackend:
self._spec_fallback_reason = None
self._spec_drafter_kind = None
self._dspark_sidecar_absent = False
+ self._cpu_fallback_reason = None
self._last_load_intent = None
self._mtp_runtime_fallback_active = False
self._hf_variant = None
@@ -13136,6 +13830,9 @@ class LlamaCppBackend:
logging.raiseExceptions = False
try:
self._kill_process()
+ # TemporaryDirectory's exit hook runs first and cannot delete a staged
+ # runtime whose server is alive (Windows locks the exe). Retry post-kill.
+ self._cleanup_cpu_fallback_runtime()
except Exception:
# atexit swallows this anyway, and there is nowhere left to report it.
pass
diff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.py
index 576bec318b0..539494788e3 100644
--- a/studio/backend/models/inference.py
+++ b/studio/backend/models/inference.py
@@ -194,6 +194,13 @@ class LoadRequest(BaseModel):
"llama.cpp's --fit. Ignored unless gpu_memory_mode is 'manual'."
),
)
+ cpu_fallback: bool = Field(
+ False,
+ description = (
+ "Replay a previously recovered automatic Vulkan load in its managed CPU-only "
+ "runtime. Used when restoring that model after a failed switch."
+ ),
+ )
n_cpu_moe: int = Field(
0,
ge = 0,
@@ -677,6 +684,14 @@ class _InferenceRuntimeFields(BaseModel):
-1,
description = "Manual mode: requested --gpu-layers value (-1 = Auto/--fit, or when not manual).",
)
+ cpu_fallback_reason: Optional[Literal["vulkan_startup_crash"]] = Field(
+ None,
+ description = (
+ "Why an automatic GGUF load was downgraded to CPU. "
+ "'vulkan_startup_crash' means a managed, auto-selected Vulkan launch "
+ "hard-crashed and the same launch became healthy with GPU devices disabled."
+ ),
+ )
n_cpu_moe: int = Field(
0,
description = "Manual mode: MoE expert layers pinned to CPU (--n-cpu-moe); 0 = none.",
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index 48ce4206bcc..fc073338fd8 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -7175,6 +7175,9 @@ async def _load_model_impl(
# An Images/Video acquire can land in the gap between the acquire above and load_model clearing the cancel event, so
# its cancellation is lost. Ownership survives that gap, so this load undoes itself. A zero-VRAM load never yields.
+ # Recovery may turn an automatic GPU request into a zero-VRAM load.
+ if llama_backend.holds_no_vram:
+ chat_load_needs_gpu = False
if chat_load_needs_gpu and current_owner() != CHAT:
await asyncio.to_thread(llama_backend.unload_model)
raise HTTPException(
@@ -7185,7 +7188,7 @@ async def _load_model_impl(
),
)
if not chat_load_needs_gpu:
- # Zero-VRAM load done, so drop a now-stale CHAT claim: leaving it would make the next image/video load "evict" a server holding nothing. Owner-guarded.
+ # Drop the stale CHAT claim after any zero-VRAM load.
await asyncio.to_thread(release, CHAT)
logger.info(
diff --git a/studio/backend/tests/test_gpu_init_crash_message.py b/studio/backend/tests/test_gpu_init_crash_message.py
new file mode 100644
index 00000000000..0eab14b266d
--- /dev/null
+++ b/studio/backend/tests/test_gpu_init_crash_message.py
@@ -0,0 +1,1463 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Tests for GPU-init crash recovery and backend-specific advice."""
+
+from __future__ import annotations
+
+import asyncio
+import importlib.util
+import json
+import os
+import struct
+import subprocess
+import sys
+import types as _types
+from contextlib import nullcontext
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+
+_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)
+if _BACKEND_DIR not in sys.path:
+ sys.path.insert(0, _BACKEND_DIR)
+
+
+# Allow importing the module in a lightweight environment without fastapi.
+class _LoggerStub:
+ def bind(self, *args, **kwargs):
+ return self
+
+ def __getattr__(self, _name):
+ return lambda *args, **kwargs: None
+
+
+_loggers_stub = _types.ModuleType("loggers")
+_loggers_stub.get_logger = lambda name: _LoggerStub()
+sys.modules.setdefault("loggers", _loggers_stub)
+_structlog_stub = _types.ModuleType("structlog")
+_structlog_stub.get_logger = lambda *a, **k: _LoggerStub()
+sys.modules.setdefault("structlog", _structlog_stub)
+if not hasattr(sys.modules["structlog"], "get_logger"):
+ sys.modules["structlog"].get_logger = _structlog_stub.get_logger
+
+from core.inference import llama_cpp # noqa: E402
+from core.inference.llama_cpp import GgufLoadIntent, LlamaCppBackend # noqa: E402
+from models.inference import InferenceStatusResponse, LoadRequest, LoadResponse # noqa: E402
+
+
+_RAW_MAIN_PLACEMENT_ARGS = (
+ ("--tensor-split", "1,1"),
+ ("-ts", "1,1"),
+ ("--fit", "off"),
+ ("-fit", "off"),
+ ("--cpu-moe",),
+ ("-cmoe",),
+ ("--n-cpu-moe", "4"),
+ ("-ncmoe", "4"),
+)
+
+
+def _managed_runtime(monkeypatch, tmp_path):
+ install = tmp_path / "install" / "build" / "bin"
+ install.mkdir(parents = True)
+ binary = install / "llama-server"
+ binary.write_bytes(b"binary")
+ binary.chmod(0o755)
+ (install / "libggml-base.so").write_bytes(b"base")
+ (install / "libggml-cpu-haswell.so").write_bytes(b"cpu")
+ (install / "libggml-vulkan.so").write_bytes(b"vulkan")
+ monkeypatch.setattr(
+ LlamaCppBackend,
+ "_is_unsloth_managed_binary",
+ staticmethod(lambda _binary: True),
+ )
+ monkeypatch.setattr(
+ llama_cpp,
+ "_swa_cache_path",
+ lambda: tmp_path / "studio" / "swa_cache.json",
+ )
+ return binary
+
+
+def _run_cpu_fallback_load(
+ monkeypatch,
+ tmp_path,
+ *,
+ returncodes,
+ first_output = "",
+ mmproj_from_argv = False,
+ mmproj_env = None,
+ cpu_fallback_available = True,
+ extra_args = None,
+ vulkan = True,
+ cpu_fallback = False,
+ resident_fallback = False,
+ cancel_after = None,
+ cancel_in_prepare = False,
+ platform = None,
+ sink = None,
+):
+ if platform is not None:
+ monkeypatch.setattr(llama_cpp.sys, "platform", platform)
+
+ def _gguf_string(value: str) -> bytes:
+ encoded = value.encode()
+ return struct.pack("<Q", len(encoded)) + encoded
+
+ metadata = _gguf_string("general.architecture") + struct.pack("<I", 8) + _gguf_string("llama")
+ gguf = tmp_path / "model.gguf"
+ gguf.write_bytes(struct.pack("<IIQQ", 0x46554747, 3, 0, 1) + metadata)
+ mmproj = tmp_path / "mmproj.gguf"
+ mmproj.write_bytes(b"projector")
+
+ backend = LlamaCppBackend()
+ backend._get_gpu_memory = lambda _binary = None: []
+ backend._get_gpu_free_memory = lambda _binary = None: []
+ backend._read_gguf_metadata = lambda _path: None
+ backend._can_estimate_kv = lambda: False
+ backend._get_gguf_size_bytes = lambda _path: 1024
+ backend._mmproj_vram_bytes = lambda _path: 0
+ backend._resolve_launch_mmproj_path = lambda **_kwargs: (
+ str(mmproj) if mmproj_from_argv else None
+ )
+ backend._apu_ram_shortfall_message = lambda *_args, **_kwargs: None
+ backend._amd_apu_wants_unified_memory = lambda *_args, **_kwargs: False
+ backend._find_llama_server_binary = lambda include_denied = False: "/fake/llama-server"
+ monkeypatch.setattr(
+ LlamaCppBackend,
+ "_is_vulkan_backend",
+ staticmethod(lambda _binary = None: vulkan),
+ )
+ monkeypatch.setattr(
+ LlamaCppBackend,
+ "_vulkan_prebuilt_was_auto_selected",
+ staticmethod(lambda _binary: True),
+ )
+ backend._fit_off_retry_eligible = lambda *_args, **_kwargs: False
+ backend.probe_server_capabilities = lambda _binary: {
+ "found": True,
+ "supports_no_mmproj_offload": True,
+ }
+ backend._record_server_pid = lambda _pid: None
+ backend._clear_server_pid = lambda: None
+ backend._llama_server_env_for_binary = lambda _binary: {
+ "PATH": os.environ.get("PATH", ""),
+ **(mmproj_env or {}),
+ }
+ backend._is_projector_incompatibility = lambda output: "projector-incompatible" in output
+
+ launches = []
+ fallback_sources = []
+
+ class _Process:
+ pid = 123
+ stdout = ()
+
+ def __init__(self, returncode):
+ self.returncode = returncode
+
+ def poll(self):
+ return self.returncode
+
+ def terminate(self):
+ return None
+
+ def wait(self, timeout = None):
+ return self.returncode
+
+ def kill(self):
+ return None
+
+ def _popen(cmd, **kwargs):
+ index = len(launches)
+ launches.append((list(cmd), dict(kwargs["env"])))
+ return _Process(returncodes[index])
+
+ def _wait_for_health(timeout):
+ if len(launches) == 1 and first_output:
+ backend._stdout_lines = [first_output]
+ if cancel_after is not None and len(launches) >= cancel_after:
+ backend._cancel_event.set()
+ return returncodes[len(launches) - 1] is None
+
+ cleanups = []
+
+ def _prepare_cpu_fallback(_binary, failed_cmd, _env, _server_caps, **_kwargs):
+ fallback_sources.append(list(failed_cmd))
+ if cancel_in_prepare:
+ # An /unload landing while the runtime is being staged.
+ backend._cancel_event.set()
+ # A callable decides per command, for builds that can only replay some.
+ available = (
+ cpu_fallback_available(failed_cmd)
+ if callable(cpu_fallback_available)
+ else cpu_fallback_available
+ )
+ if not available:
+ return None
+ return ["/staged/llama-server", "--device", "none"], None
+
+ backend._wait_for_health = _wait_for_health
+ backend._prepare_cpu_fallback_launch = _prepare_cpu_fallback
+ backend._cleanup_cpu_fallback_runtime = lambda: cleanups.append(True)
+ monkeypatch.setattr(subprocess, "Popen", _popen)
+ # Lets a test that expects the load to raise still read what was spawned.
+ if sink is not None:
+ sink["launches"] = launches
+ sink["fallback_sources"] = fallback_sources
+ sink["cleanups"] = cleanups
+ if resident_fallback:
+ backend._cpu_fallback_reason = "vulkan_startup_crash"
+
+ loaded = backend.load_model(
+ GgufLoadIntent(
+ gguf_path = str(gguf),
+ mmproj_path = str(mmproj) if mmproj_from_argv else None,
+ model_identifier = "owner/model",
+ is_vision = mmproj_from_argv,
+ extra_args = list(extra_args) if extra_args else None,
+ cpu_fallback = cpu_fallback,
+ )
+ )
+ return backend, loaded, launches, fallback_sources
+
+
+class TestGpuInitCrashMessage:
+ def _message(self, monkeypatch, backend):
+ monkeypatch.setattr(
+ LlamaCppBackend,
+ "_installed_ggml_backends",
+ staticmethod(lambda *a: frozenset({backend}) if backend else frozenset()),
+ )
+ return LlamaCppBackend._gpu_init_crash_message("/opt/llama/llama-server")
+
+ def test_vulkan_host_gets_no_rocm_advice(self, monkeypatch):
+ message = self._message(monkeypatch, "vulkan")
+ assert "ROCR_VISIBLE_DEVICES" not in message
+ assert "CUDA_VISIBLE_DEVICES" not in message
+ assert "Vulkan" in message
+ assert "UNSLOTH_LLAMA_CPP_BACKEND=cpu" in message
+
+ def test_rocm_host_keeps_the_original_advice(self, monkeypatch):
+ message = self._message(monkeypatch, "hip")
+ assert "ROCR_VISIBLE_DEVICES=0" in message
+
+ def test_cuda_host_gets_cuda_advice(self, monkeypatch):
+ message = self._message(monkeypatch, "cuda")
+ assert "CUDA_VISIBLE_DEVICES" in message
+ assert "ROCR_VISIBLE_DEVICES" not in message
+
+ @pytest.mark.parametrize("backend", [None, "sycl"])
+ def test_unknown_backend_gives_neutral_advice(self, monkeypatch, backend):
+ # Metal's .dylib is not detected, so macOS also gets neutral advice.
+ message = self._message(monkeypatch, backend)
+ assert "ROCR_VISIBLE_DEVICES" not in message
+ assert "CUDA_VISIBLE_DEVICES" not in message
+
+ def test_every_variant_still_names_the_gpu_as_the_cause(self, monkeypatch):
+ for backend in ("vulkan", "hip", "cuda", None):
+ message = self._message(monkeypatch, backend)
+ assert "GPU driver/runtime initialization crash" in message
+
+
+class TestPlatformMatrix:
+ """Every OS and runtime flavour Studio ships, so the recovery cannot leak
+ into a path that already worked."""
+
+ # (platform, library prefix, library suffix, binary name)
+ OSES = {
+ "linux": ("linux", "lib", "so", "llama-server"),
+ "windows": ("win32", "", "dll", "llama-server.exe"),
+ "macos": ("darwin", "lib", "dylib", "llama-server"),
+ }
+ RUNTIMES = {
+ "vulkan": ("base", "cpu", "vulkan"),
+ "cuda": ("base", "cpu", "cuda"),
+ "hip": ("base", "cpu", "hip"),
+ "cpu": ("base", "cpu"),
+ # A custom multi-backend build defers to CUDA/HIP, never to Vulkan.
+ "vulkan+cuda": ("base", "cpu", "vulkan", "cuda"),
+ }
+
+ def _install(self, monkeypatch, tmp_path, os_key, runtime):
+ platform, prefix, suffix, exe = self.OSES[os_key]
+ bindir = tmp_path / "install" / "build" / "bin"
+ bindir.mkdir(parents = True)
+ binary = bindir / exe
+ binary.write_bytes(b"llama-server")
+ binary.chmod(0o755)
+ for backend in self.RUNTIMES[runtime]:
+ stem = "cpu-haswell" if backend == "cpu" else backend
+ (bindir / f"{prefix}ggml-{stem}.{suffix}").write_bytes(backend.encode())
+ if backend == "cpu":
+ (bindir / f"{prefix}ggml-cpu.{suffix}").write_bytes(b"cpu")
+ (bindir / f"{prefix}llama.{suffix}").write_bytes(b"llama")
+ monkeypatch.setattr(llama_cpp.sys, "platform", platform)
+ monkeypatch.setattr(
+ LlamaCppBackend, "_is_unsloth_managed_binary", staticmethod(lambda _binary: True)
+ )
+ monkeypatch.setattr(
+ llama_cpp, "_swa_cache_path", lambda: tmp_path / "studio" / "swa_cache.json"
+ )
+ return binary
+
+ @pytest.mark.parametrize("os_key", list(OSES))
+ @pytest.mark.parametrize("runtime", list(RUNTIMES))
+ def test_only_a_vulkan_only_build_is_ever_staged(self, monkeypatch, tmp_path, os_key, runtime):
+ binary = self._install(monkeypatch, tmp_path, os_key, runtime)
+ backend = LlamaCppBackend()
+ backend._llama_server_env_for_binary = lambda _binary: {
+ "PATH": "/staged",
+ "LD_LIBRARY_PATH": "/staged",
+ }
+
+ prepared = backend._prepare_cpu_fallback_launch(
+ str(binary), [str(binary), "-m", "m.gguf"], {}, {"found": True}
+ )
+
+ # Backend detection reads .so / .dll only, so a macOS bundle is never Vulkan.
+ expected = os_key != "macos" and runtime == "vulkan"
+ assert (prepared is not None) is expected
+ if not expected:
+ assert backend._cpu_fallback_runtime is None
+ return
+ staged = {p.name.lower() for p in Path(prepared[0][0]).parent.iterdir()}
+ assert not any("ggml-vulkan" in n or "ggml-cuda" in n or "ggml-hip" in n for n in staged)
+ assert any("ggml-cpu" in n for n in staged)
+ assert any(n.startswith(("libllama", "llama.")) for n in staged)
+ backend._cleanup_cpu_fallback_runtime()
+
+ @pytest.mark.parametrize(
+ "marker,eligible",
+ [
+ ({"llama_backend": None}, True), # auto Intel, post-#7188
+ ({"llama_backend": "auto"}, True), # auto AMD, post-#8050
+ ({}, True), # pre-#7188, key absent
+ ({"llama_backend": ""}, True),
+ ({"llama_backend": "vulkan"}, False), # explicit choice
+ ({"llama_backend": "cuda"}, False), # unknown/future value
+ ({"llama_backend": None, "force_cpu": True}, False),
+ ],
+ )
+ def test_marker_states_old_and_new(self, monkeypatch, tmp_path, marker, eligible):
+ binary = self._install(monkeypatch, tmp_path, "linux", "vulkan")
+ payload = {"asset": "llama-b1-bin-ubuntu-vulkan-x64.tar.gz", "force_cpu": False}
+ payload.update(marker)
+ (tmp_path / "UNSLOTH_PREBUILT_INFO.json").write_text(json.dumps(payload))
+ import utils.llama_cpp_update as update
+
+ monkeypatch.setattr(update, "_llama_install_root", lambda _binary: tmp_path)
+ for name in ("UNSLOTH_FORCE_VULKAN", "UNSLOTH_LLAMA_CPP_BACKEND"):
+ monkeypatch.delenv(name, raising = False)
+
+ assert (
+ LlamaCppBackend._auto_vulkan_cpu_fallback_eligible(
+ str(binary), GgufLoadIntent(model_identifier = "owner/model"), None, {}
+ )
+ is eligible
+ )
+
+ @pytest.mark.parametrize("marker_text", ["not json", "", "[]", '{"llama_backend": 7}'])
+ def test_a_corrupt_marker_is_ineligible_and_never_raises(
+ self, monkeypatch, tmp_path, marker_text
+ ):
+ binary = self._install(monkeypatch, tmp_path, "linux", "vulkan")
+ (tmp_path / "UNSLOTH_PREBUILT_INFO.json").write_text(marker_text)
+ import utils.llama_cpp_update as update
+
+ monkeypatch.setattr(update, "_llama_install_root", lambda _binary: tmp_path)
+
+ assert (
+ LlamaCppBackend._auto_vulkan_cpu_fallback_eligible(
+ str(binary), GgufLoadIntent(model_identifier = "owner/model"), None, {}
+ )
+ is False
+ )
+
+
+class TestAutoVulkanCpuFallbackGate:
+ def _managed_marker(self, monkeypatch, tmp_path, **values):
+ marker = {
+ "asset": "llama-b9999-bin-ubuntu-vulkan-x64.tar.gz",
+ "force_cpu": False,
+ **values,
+ }
+ (tmp_path / "UNSLOTH_PREBUILT_INFO.json").write_text(json.dumps(marker))
+ import utils.llama_cpp_update as update
+
+ monkeypatch.setattr(update, "_llama_install_root", lambda _binary: tmp_path)
+
+ def test_managed_auto_selected_marker_is_eligible(self, monkeypatch, tmp_path):
+ self._managed_marker(monkeypatch, tmp_path)
+ monkeypatch.setattr(
+ LlamaCppBackend, "_is_vulkan_backend", staticmethod(lambda _binary = None: True)
+ )
+ intent = GgufLoadIntent(model_identifier = "owner/model")
+ assert LlamaCppBackend._auto_vulkan_cpu_fallback_eligible(
+ "/managed/llama-server", intent, None, {}
+ )
+
+ def test_automatic_windows_amd_marker_is_eligible(self, monkeypatch, tmp_path):
+ self._managed_marker(monkeypatch, tmp_path, llama_backend = "auto")
+ monkeypatch.setattr(
+ LlamaCppBackend, "_is_vulkan_backend", staticmethod(lambda _binary = None: True)
+ )
+ assert LlamaCppBackend._auto_vulkan_cpu_fallback_eligible(
+ "/managed/llama-server",
+ GgufLoadIntent(model_identifier = "m"),
+ None,
+ {},
+ )
+
+ @pytest.mark.parametrize(
+ "name,value",
+ [
+ ("LLAMA_ARG_N_GPU_LAYERS", "20"),
+ ("LLAMA_ARG_DEVICE", "Vulkan0"),
+ ("LLAMA_ARG_MAIN_GPU", "1"),
+ ("LLAMA_ARG_SPLIT_MODE", "tensor"),
+ ("LLAMA_ARG_TENSOR_SPLIT", "1,1"),
+ ("LLAMA_ARG_OVERRIDE_TENSOR", ".*=Vulkan0"),
+ ("LLAMA_ARG_CPU_MOE", "true"),
+ ("LLAMA_ARG_N_CPU_MOE", "4"),
+ ("LLAMA_ARG_FIT", "off"),
+ ("LLAMA_ARG_FIT_TARGET", "1024"),
+ ("LLAMA_ARG_FIT_CTX", "4096"),
+ ],
+ )
+ def test_inherited_main_placement_never_downgrades(self, monkeypatch, tmp_path, name, value):
+ self._managed_marker(monkeypatch, tmp_path)
+ monkeypatch.setattr(
+ LlamaCppBackend, "_is_vulkan_backend", staticmethod(lambda _binary = None: True)
+ )
+ assert not LlamaCppBackend._auto_vulkan_cpu_fallback_eligible(
+ "/managed/llama-server",
+ GgufLoadIntent(model_identifier = "m"),
+ None,
+ {name: value},
+ )
+
+ @pytest.mark.parametrize(
+ "intent, extras",
+ [
+ (GgufLoadIntent(model_identifier = "m", gpu_ids = (0,)), None),
+ (GgufLoadIntent(model_identifier = "m", gpu_memory_mode = "manual"), None),
+ (GgufLoadIntent(model_identifier = "m", tensor_parallel = True), None),
+ (GgufLoadIntent(model_identifier = "m"), ["--device", "Vulkan0"]),
+ (GgufLoadIntent(model_identifier = "m"), ["-ngl", "20"]),
+ (GgufLoadIntent(model_identifier = "m"), ["-sm", "tensor"]),
+ ],
+ )
+ def test_explicit_gpu_placement_never_downgrades(self, monkeypatch, tmp_path, intent, extras):
+ self._managed_marker(monkeypatch, tmp_path)
+ monkeypatch.setattr(
+ LlamaCppBackend, "_is_vulkan_backend", staticmethod(lambda _binary = None: True)
+ )
+ assert not LlamaCppBackend._auto_vulkan_cpu_fallback_eligible(
+ "/managed/llama-server", intent, extras
+ )
+
+ @pytest.mark.parametrize("extras", _RAW_MAIN_PLACEMENT_ARGS)
+ def test_raw_main_placement_never_downgrades(self, monkeypatch, tmp_path, extras):
+ self._managed_marker(monkeypatch, tmp_path)
+ monkeypatch.setattr(
+ LlamaCppBackend, "_is_vulkan_backend", staticmethod(lambda _binary = None: True)
+ )
+ assert not LlamaCppBackend._auto_vulkan_cpu_fallback_eligible(
+ "/managed/llama-server",
+ GgufLoadIntent(model_identifier = "m"),
+ extras,
+ )
+
+ @pytest.mark.parametrize(
+ "extras",
+ [
+ ("--spec-draft-ngl", "12"),
+ ("-ngld", "12"),
+ ("--gpu-layers-draft", "12"),
+ ("--n-gpu-layers-draft", "12"),
+ ("--mmproj-offload",),
+ ("--no-mmproj-offload",),
+ ],
+ )
+ def test_explicit_companion_placement_never_downgrades(self, monkeypatch, tmp_path, extras):
+ self._managed_marker(monkeypatch, tmp_path)
+ monkeypatch.setattr(
+ LlamaCppBackend, "_is_vulkan_backend", staticmethod(lambda _binary = None: True)
+ )
+ assert not LlamaCppBackend._auto_vulkan_cpu_fallback_eligible(
+ "/managed/llama-server",
+ GgufLoadIntent(model_identifier = "m"),
+ extras,
+ {},
+ )
+
+ @pytest.mark.parametrize(
+ "name,value",
+ [
+ ("LLAMA_ARG_N_GPU_LAYERS_DRAFT", "12"),
+ ("LLAMA_ARG_MMPROJ_OFFLOAD", "1"),
+ ("LLAMA_ARG_MMPROJ_OFFLOAD", "0"),
+ ("GGML_BACKEND_PATH", "/custom/ggml/backends"),
+ ],
+ )
+ def test_inherited_companion_placement_never_downgrades(
+ self, monkeypatch, tmp_path, name, value
+ ):
+ self._managed_marker(monkeypatch, tmp_path)
+ monkeypatch.setattr(
+ LlamaCppBackend, "_is_vulkan_backend", staticmethod(lambda _binary = None: True)
+ )
+ assert not LlamaCppBackend._auto_vulkan_cpu_fallback_eligible(
+ "/managed/llama-server",
+ GgufLoadIntent(model_identifier = "m"),
+ None,
+ {name: value},
+ )
+
+ def test_persisted_explicit_vulkan_choice_never_downgrades(self, monkeypatch, tmp_path):
+ self._managed_marker(monkeypatch, tmp_path, llama_backend = "vulkan")
+ monkeypatch.setattr(
+ LlamaCppBackend, "_is_vulkan_backend", staticmethod(lambda _binary = None: True)
+ )
+ assert not LlamaCppBackend._auto_vulkan_cpu_fallback_eligible(
+ "/managed/llama-server", GgufLoadIntent(model_identifier = "m"), None
+ )
+
+ def test_custom_markerless_binary_never_downgrades(self, monkeypatch):
+ import utils.llama_cpp_update as update
+
+ monkeypatch.setattr(update, "_llama_install_root", lambda _binary: None)
+ monkeypatch.setattr(
+ LlamaCppBackend, "_is_vulkan_backend", staticmethod(lambda _binary = None: True)
+ )
+ assert not LlamaCppBackend._auto_vulkan_cpu_fallback_eligible(
+ "/custom/llama-server", GgufLoadIntent(model_identifier = "m"), None
+ )
+
+
+class TestCpuIsolatedReplay:
+ @pytest.mark.parametrize("name", ["LLAMA_ARG_MMPROJ", "LLAMA_ARG_MMPROJ_URL"])
+ def test_env_projector_counts_as_a_vision_launch(self, name):
+ assert LlamaCppBackend._launch_has_mmproj(
+ ["llama-server", "-m", "model.gguf"],
+ {name: "projector.gguf"},
+ )
+
+ @pytest.mark.parametrize(
+ "platform,loader_path",
+ [("linux", "LD_LIBRARY_PATH"), ("win32", "PATH")],
+ )
+ def test_prepared_launch_retargets_the_native_library_path(
+ self, monkeypatch, platform, loader_path
+ ):
+ backend = LlamaCppBackend()
+ monkeypatch.setattr(llama_cpp.sys, "platform", platform)
+ monkeypatch.setattr(
+ LlamaCppBackend, "_is_vulkan_backend", staticmethod(lambda _binary = None: True)
+ )
+ monkeypatch.setattr(
+ backend,
+ "_cpu_isolated_replay",
+ lambda _cmd, _env, _caps, **_kwargs: ["original", "--device", "none"],
+ )
+ monkeypatch.setattr(backend, "_cpu_isolated_binary", lambda _binary: "/staged/server")
+ monkeypatch.setattr(
+ backend,
+ "_llama_server_env_for_binary",
+ lambda _binary: {loader_path: "/staged/libs"},
+ )
+ env = {"PATH": "/original/bin", "LD_LIBRARY_PATH": "/original/lib", "KEEP": "1"}
+
+ prepared = backend._prepare_cpu_fallback_launch("/original/server", ["original"], env, {})
+
+ assert prepared == (["/staged/server", "--device", "none"], None)
+ assert env[loader_path] == "/staged/libs"
+ assert env["KEEP"] == "1"
+
+ def test_text_launch_removes_every_gpu_placement(self):
+ env = {
+ "LLAMA_ARG_N_GPU_LAYERS": "99",
+ "LLAMA_ARG_DEVICE": "Vulkan0",
+ "LLAMA_ARG_MAIN_GPU": "0",
+ "LLAMA_ARG_SPLIT_MODE": "tensor",
+ "LLAMA_ARG_TENSOR_SPLIT": "1,1",
+ "LLAMA_ARG_OVERRIDE_TENSOR": ".*=Vulkan0",
+ "LLAMA_ARG_CPU_MOE": "true",
+ "LLAMA_ARG_N_CPU_MOE": "4",
+ "LLAMA_ARG_FIT": "off",
+ "LLAMA_ARG_FIT_TARGET": "1024",
+ "LLAMA_ARG_FIT_CTX": "4096",
+ "PATH": "/usr/bin",
+ }
+ replay = LlamaCppBackend._cpu_isolated_replay(
+ [
+ "llama-server",
+ "-m",
+ "model.gguf",
+ "-ngl",
+ "99",
+ "--device",
+ "Vulkan0",
+ "-sm",
+ "tensor",
+ "-ot",
+ ".*=Vulkan0",
+ ],
+ env,
+ {"found": True},
+ )
+ assert replay is not None
+ assert replay[-6:] == ["--gpu-layers", "0", "--fit", "off", "--device", "none"]
+ assert "Vulkan0" not in replay
+ assert not set(LlamaCppBackend._CPU_FALLBACK_MAIN_PLACEMENT_ENV_VARS) & env.keys()
+ assert env["PATH"] == "/usr/bin"
+
+ def test_vision_and_drafter_get_independent_cpu_pins(self):
+ env = {}
+ replay = LlamaCppBackend._cpu_isolated_replay(
+ [
+ "llama-server",
+ "-m",
+ "model.gguf",
+ "--mmproj",
+ "mmproj.gguf",
+ "--model-draft",
+ "draft.gguf",
+ ],
+ env,
+ {
+ "found": True,
+ "supports_no_mmproj_offload": True,
+ "spec_draft_ngl_flag": "--spec-draft-ngl",
+ "mtp_probe_inconclusive": False,
+ },
+ )
+ assert replay is not None
+ assert "--mmproj" in replay
+ assert "--no-mmproj-offload" in replay
+ assert replay[replay.index("--spec-draft-ngl") + 1] == "0"
+ assert replay[replay.index("--device-draft") + 1] == "none"
+
+ def test_vision_replay_is_refused_when_projector_cannot_be_cpu_pinned(self):
+ replay = LlamaCppBackend._cpu_isolated_replay(
+ ["llama-server", "--mmproj", "mmproj.gguf"],
+ {},
+ {"found": True, "supports_no_mmproj_offload": False},
+ )
+ assert replay is None
+
+ @pytest.mark.parametrize("name", ["LLAMA_ARG_MMPROJ", "LLAMA_ARG_MMPROJ_URL"])
+ def test_env_projector_gets_a_cpu_pin(self, name):
+ env = {name: "projector.gguf"}
+ replay = LlamaCppBackend._cpu_isolated_replay(
+ ["llama-server", "-m", "model.gguf"],
+ env,
+ {"found": True, "supports_no_mmproj_offload": True},
+ )
+
+ assert replay is not None
+ assert "--no-mmproj-offload" in replay
+ assert env[name] == "projector.gguf"
+
+ def test_staged_runtime_excludes_the_gpu_backend(self, monkeypatch, tmp_path):
+ binary = _managed_runtime(monkeypatch, tmp_path)
+ backend = LlamaCppBackend()
+ staged = backend._cpu_isolated_binary(str(binary))
+ assert staged is not None
+ staged_dir = Path(staged).parent
+ assert (staged_dir / "libggml-cpu-haswell.so").is_file()
+ assert not (staged_dir / "libggml-vulkan.so").exists()
+ backend._cleanup_cpu_fallback_runtime()
+ assert not staged_dir.exists()
+
+ def test_a_replay_request_on_a_non_vulkan_runtime_loads_normally(self, monkeypatch, tmp_path):
+ """Switching the managed build must not turn a rollback into a failure."""
+ backend, loaded, launches, fallback_sources = _run_cpu_fallback_load(
+ monkeypatch,
+ tmp_path,
+ returncodes = [None],
+ vulkan = False,
+ cpu_fallback = True,
+ )
+
+ assert loaded is True
+ assert fallback_sources == []
+ assert backend._cpu_fallback_reason is None
+
+ def test_the_windows_full_offload_thread_cap_is_undone(self, monkeypatch, tmp_path):
+ """Two threads and PASSIVE OpenMP are tuned for a GPU doing the work, so
+ a CPU replay that kept them would decode on two cores."""
+ env = {"OMP_NUM_THREADS": "2", "OMP_WAIT_POLICY": "PASSIVE", "KEEP": "1"}
+ cmd = ["llama-server", "-m", "m.gguf", "--threads", "2", "--jinja"]
+
+ replay = LlamaCppBackend._cpu_isolated_replay(
+ cmd, env, {"found": True}, drop_full_offload_threads = True
+ )
+
+ assert "--threads" not in replay
+ assert "--jinja" in replay
+ assert "OMP_NUM_THREADS" not in env
+ assert "OMP_WAIT_POLICY" not in env
+ assert env["KEEP"] == "1"
+
+ def test_a_user_thread_choice_survives_the_cpu_replay(self, monkeypatch, tmp_path):
+ """The caller only reports the cap as ours when the user set no override."""
+ env = {"OMP_NUM_THREADS": "8"}
+ cmd = ["llama-server", "-m", "m.gguf", "--threads", "8"]
+
+ replay = LlamaCppBackend._cpu_isolated_replay(cmd, env, {"found": True})
+
+ assert replay[replay.index("--threads") + 1] == "8"
+ assert env["OMP_NUM_THREADS"] == "8"
+
+ def test_non_vulkan_managed_runtime_is_never_staged(self, monkeypatch, tmp_path):
+ binary = _managed_runtime(monkeypatch, tmp_path)
+ monkeypatch.setattr(
+ LlamaCppBackend, "_is_vulkan_backend", staticmethod(lambda _binary = None: False)
+ )
+ backend = LlamaCppBackend()
+
+ prepared = backend._prepare_cpu_fallback_launch(
+ str(binary), [str(binary), "-m", "model.gguf"], {}, {"found": True}
+ )
+
+ assert prepared is None
+ assert backend._cpu_fallback_runtime is None
+
+ def test_an_updated_install_restages_instead_of_reusing(self, monkeypatch, tmp_path):
+ binary = _managed_runtime(monkeypatch, tmp_path)
+ backend = LlamaCppBackend()
+ first = backend._cpu_isolated_binary(str(binary))
+ assert first is not None
+ assert backend._cpu_isolated_binary(str(binary)) == first
+
+ # An update swaps the tree in place, so the path is unchanged.
+ binary.unlink()
+ binary.write_bytes(b"rebuilt binary")
+ binary.chmod(0o755)
+
+ second = backend._cpu_isolated_binary(str(binary))
+ assert second is not None and second != first
+ assert Path(second).read_bytes() == b"rebuilt binary"
+ assert not Path(first).parent.exists()
+
+ def test_a_runtime_abandoned_by_a_dead_studio_is_swept(self, monkeypatch, tmp_path):
+ binary = _managed_runtime(monkeypatch, tmp_path)
+ runtime_root = tmp_path / "studio" / "runtime"
+ runtime_root.mkdir(parents = True)
+ dead = runtime_root / "llama-cpu-dead"
+ dead.mkdir()
+ # A pid no live process can hold, so the sweep must collect it.
+ (dead / "UNSLOTH_OWNER_PID").write_text("0")
+ legacy = runtime_root / "llama-cpu-legacy"
+ legacy.mkdir()
+
+ staged = LlamaCppBackend()._cpu_isolated_binary(str(binary))
+
+ assert staged is not None
+ assert not dead.exists()
+ # No owner stamp means an older Studio wrote it; leave it alone.
+ assert legacy.exists()
+
+ def test_a_live_owner_keeps_its_runtime(self, monkeypatch, tmp_path):
+ binary = _managed_runtime(monkeypatch, tmp_path)
+ one = LlamaCppBackend()
+ first = Path(one._cpu_isolated_binary(str(binary))).parent
+
+ second = Path(LlamaCppBackend()._cpu_isolated_binary(str(binary))).parent
+
+ assert first != second
+ assert first.exists()
+ assert (first / "UNSLOTH_OWNER_PID").read_text() == str(os.getpid())
+
+ def test_a_failed_cleanup_is_retried_rather_than_orphaned(self, monkeypatch, tmp_path):
+ binary = _managed_runtime(monkeypatch, tmp_path)
+ backend = LlamaCppBackend()
+ assert backend._cpu_isolated_binary(str(binary)) is not None
+ tempdir = backend._cpu_fallback_runtime.tempdir
+ staged_dir = Path(tempdir.name)
+ attempts = []
+ real_cleanup = tempdir.cleanup
+
+ def _cleanup():
+ attempts.append(True)
+ if len(attempts) == 1:
+ raise PermissionError("locked")
+ real_cleanup()
+
+ monkeypatch.setattr(tempdir, "cleanup", _cleanup)
+
+ backend._cleanup_cpu_fallback_runtime()
+ assert staged_dir.exists()
+ assert backend._pending_cpu_fallback_cleanups == [tempdir]
+
+ backend._cleanup_cpu_fallback_runtime()
+ assert not staged_dir.exists()
+ assert backend._pending_cpu_fallback_cleanups == []
+
+ def test_terminal_cpu_replay_failure_removes_staged_runtime(self, monkeypatch, tmp_path):
+ binary = _managed_runtime(monkeypatch, tmp_path)
+ backend = LlamaCppBackend()
+ staged = backend._cpu_isolated_binary(str(binary))
+ assert staged is not None
+ staged_dir = Path(staged).parent
+ backend._cpu_fallback_reason = "vulkan_startup_crash"
+
+ backend._cleanup_failed_cpu_fallback()
+
+ assert backend._cpu_fallback_reason is None
+ assert backend._cpu_fallback_runtime is None
+ assert not staged_dir.exists()
+
+ @pytest.mark.skipif(sys.platform == "win32", reason = "shell wrapper fallback is POSIX")
+ def test_wrapper_based_runtime_stages_the_real_executable(self, monkeypatch, tmp_path):
+ install = tmp_path / "install"
+ bindir = install / "build" / "bin"
+ bindir.mkdir(parents = True)
+ binary = bindir / "llama-server"
+ binary.write_text("#!/bin/sh\nprintf 'healthy\\n'\n")
+ binary.chmod(0o755)
+ (bindir / "libggml-base.so").write_bytes(b"base")
+ (bindir / "libggml-cpu-haswell.so").write_bytes(b"cpu")
+ (bindir / "libggml-vulkan.so").write_bytes(b"vulkan")
+ wrapper = install / "llama-server"
+ wrapper.write_text('#!/bin/sh\nexec "$(dirname "$0")/build/bin/llama-server" "$@"\n')
+ wrapper.chmod(0o755)
+ monkeypatch.setattr(
+ LlamaCppBackend,
+ "_is_unsloth_managed_binary",
+ staticmethod(lambda _binary: True),
+ )
+ monkeypatch.setattr(
+ llama_cpp,
+ "_swa_cache_path",
+ lambda: tmp_path / "studio" / "swa_cache.json",
+ )
+
+ backend = LlamaCppBackend()
+ staged = backend._cpu_isolated_binary(str(wrapper))
+ assert staged is not None
+ staged_dir = Path(staged).parent
+ assert Path(staged).read_bytes() == binary.read_bytes()
+ assert not (staged_dir / "libggml-vulkan.so").exists()
+ completed = subprocess.run(
+ [staged],
+ check = True,
+ capture_output = True,
+ text = True,
+ )
+ assert completed.stdout == "healthy\n"
+ backend._cleanup_cpu_fallback_runtime()
+ assert not staged_dir.exists()
+
+
+def test_confirmed_projector_failure_replays_the_text_command_on_cpu(monkeypatch, tmp_path):
+ backend, loaded, launches, fallback_sources = _run_cpu_fallback_load(
+ monkeypatch,
+ tmp_path,
+ returncodes = [1, -11, None],
+ first_output = "projector-incompatible",
+ mmproj_from_argv = True,
+ )
+
+ assert loaded is True
+ assert len(launches) == 3
+ assert "--mmproj" in launches[0][0]
+ assert "--mmproj" not in launches[1][0]
+ assert len(fallback_sources) == 1
+ assert "--mmproj" not in fallback_sources[0]
+ assert backend._is_vision is False
+
+
+def test_confirmed_projector_signal_retry_keeps_gpu_init_diagnosis(monkeypatch, tmp_path):
+ with pytest.raises(RuntimeError, match = "GPU driver/runtime initialization crash"):
+ _run_cpu_fallback_load(
+ monkeypatch,
+ tmp_path,
+ returncodes = [1, -11],
+ first_output = "projector-incompatible",
+ mmproj_from_argv = True,
+ cpu_fallback_available = False,
+ )
+
+
[email protected]("name", ["LLAMA_ARG_MMPROJ", "LLAMA_ARG_MMPROJ_URL"])
+def test_env_projector_cpu_recovery_preserves_vision_state(monkeypatch, tmp_path, name):
+ backend, loaded, launches, fallback_sources = _run_cpu_fallback_load(
+ monkeypatch,
+ tmp_path,
+ returncodes = [-11, -11, None],
+ mmproj_env = {name: "projector.gguf"},
+ )
+
+ assert loaded is True
+ assert len(launches) == 3
+ assert len(fallback_sources) == 1
+ assert "--mmproj" not in fallback_sources[0]
+ assert backend._is_vision is True
+
+
+def test_env_projector_cpu_recovery_keeps_audio_input(monkeypatch, tmp_path):
+ """An audio projector handed over by env must not report as text-only."""
+ projector = tmp_path / "env-mmproj.gguf"
+ projector.write_bytes(b"projector")
+ read = []
+ import utils.models.gguf_metadata as gguf_metadata
+
+ monkeypatch.setattr(
+ gguf_metadata, "read_mmproj_audio_capability", lambda path: read.append(path) or True
+ )
+ monkeypatch.setenv("LLAMA_ARG_MMPROJ", str(projector))
+
+ backend, loaded, launches, fallback_sources = _run_cpu_fallback_load(
+ monkeypatch,
+ tmp_path,
+ returncodes = [-11, -11, None],
+ mmproj_env = {"LLAMA_ARG_MMPROJ": str(projector)},
+ )
+
+ assert loaded is True
+ assert read == [str(projector)]
+ assert backend._is_vision is True
+ assert backend._mmproj_has_audio is True
+
+
+def test_inherited_split_mode_dropped_before_spawn_still_recovers(monkeypatch, tmp_path):
+ """A stale env value this launch scrubs never reached the crashed child."""
+ backend, loaded, launches, fallback_sources = _run_cpu_fallback_load(
+ monkeypatch,
+ tmp_path,
+ returncodes = [-11, -11, None],
+ mmproj_env = {"LLAMA_ARG_SPLIT_MODE": "tensor"},
+ )
+
+ assert loaded is True
+ assert "LLAMA_ARG_SPLIT_MODE" not in launches[0][1]
+ assert len(fallback_sources) == 1
+ assert backend._cpu_fallback_reason == "vulkan_startup_crash"
+
+
+def test_drafter_survives_the_cpu_replay(monkeypatch, tmp_path):
+ """The speculative retry must not become the source of the CPU replay."""
+ backend, loaded, launches, fallback_sources = _run_cpu_fallback_load(
+ monkeypatch,
+ tmp_path,
+ returncodes = [-11, -11, -11, None],
+ extra_args = ["--spec-type", "mtp"],
+ )
+
+ assert loaded is True
+ assert len(fallback_sources) == 1
+ assert "--spec-default" not in fallback_sources[0]
+ assert backend._spec_fallback_reason is None
+
+
+def test_drafter_replay_falls_back_to_the_stripped_command(monkeypatch, tmp_path):
+ """A build that cannot CPU-pin a drafter still recovers, drafterless."""
+ backend, loaded, launches, fallback_sources = _run_cpu_fallback_load(
+ monkeypatch,
+ tmp_path,
+ returncodes = [-11, -11, -11, None],
+ extra_args = ["--spec-type", "mtp"],
+ cpu_fallback_available = lambda cmd: "--spec-default" in cmd,
+ )
+
+ assert loaded is True
+ assert len(fallback_sources) == 2
+ assert "--spec-default" not in fallback_sources[0]
+ assert "--spec-default" in fallback_sources[1]
+ assert backend._cpu_fallback_reason == "vulkan_startup_crash"
+
+
+def test_a_drafter_that_cannot_start_anywhere_still_recovers(monkeypatch, tmp_path):
+ """The drafter replay can be staged and still die of the drafter, so the
+ drafterless argv must get its own attempt rather than the load aborting."""
+ backend, loaded, launches, fallback_sources = _run_cpu_fallback_load(
+ monkeypatch,
+ tmp_path,
+ # The speculative CPU replay (4th launch) dies too; the drafterless one wins.
+ returncodes = [-11, -11, -11, 1, None],
+ extra_args = ["--spec-type", "mtp"],
+ )
+
+ assert loaded is True
+ assert len(fallback_sources) == 2
+ assert "--spec-default" not in fallback_sources[0]
+ assert "--spec-default" in fallback_sources[1]
+ assert backend._cpu_fallback_reason == "vulkan_startup_crash"
+
+
+def test_a_replay_request_needs_the_same_bar_as_the_crash_path(monkeypatch, tmp_path):
+ """cpu_fallback is client-supplied, so an explicitly GPU-pinned request must
+ not be silently staged onto CPU and reported as a Vulkan crash."""
+ backend, loaded, launches, fallback_sources = _run_cpu_fallback_load(
+ monkeypatch,
+ tmp_path,
+ returncodes = [None],
+ cpu_fallback = True,
+ extra_args = ["--device", "Vulkan0"],
+ )
+
+ assert loaded is True
+ assert fallback_sources == []
+ assert backend._cpu_fallback_reason is None
+
+
+def test_a_cancelled_load_never_spawns_the_cpu_replay(monkeypatch, tmp_path):
+ """An /unload racing the crash must not leave a CPU server behind."""
+ sink = {}
+ with pytest.raises(Exception):
+ _run_cpu_fallback_load(
+ monkeypatch,
+ tmp_path,
+ returncodes = [-11, -11, None],
+ cancel_after = 1,
+ sink = sink,
+ )
+
+ assert sink["fallback_sources"] == []
+
+
+def test_the_exit_handler_removes_the_runtime_after_the_kill():
+ """TemporaryDirectory's exit hook is registered later, so it runs first and
+ cannot delete a runtime whose server is still holding the files open."""
+ backend = LlamaCppBackend()
+ order = []
+ backend._kill_process = lambda: order.append("kill")
+ backend._cleanup_cpu_fallback_runtime = lambda: order.append("clean")
+
+ backend._cleanup()
+
+ assert order == ["kill", "clean"]
+
+
+def test_an_unload_during_staging_takes_the_runtime_back(monkeypatch, tmp_path):
+ """Staging copies a whole runtime, so /unload can land after the first gate
+ and find nothing registered to clean up."""
+ sink = {}
+ with pytest.raises(Exception):
+ _run_cpu_fallback_load(
+ monkeypatch,
+ tmp_path,
+ returncodes = [-11, -11, None],
+ cancel_in_prepare = True,
+ sink = sink,
+ )
+
+ assert len(sink["fallback_sources"]) == 1 # staged
+ assert len(sink["launches"]) == 2 # never spawned
+ assert sink["cleanups"] # and handed back
+
+
+def test_a_windows_ggml_assert_reaches_the_cpu_replay(monkeypatch, tmp_path):
+ """MSVC turns GGML_ASSERT into a CRT abort (exit 3), not a signal."""
+ _backend, loaded, launches, fallback_sources = _run_cpu_fallback_load(
+ monkeypatch,
+ tmp_path,
+ returncodes = [3, None],
+ platform = "win32",
+ )
+
+ assert loaded is True
+ assert len(fallback_sources) == 1
+ assert "--device" in launches[-1][0]
+
+
+def test_a_posix_exit_three_is_not_a_crash(monkeypatch, tmp_path):
+ """Exit 3 is an ordinary failure everywhere except the MSVC runtime."""
+ with pytest.raises(Exception):
+ _run_cpu_fallback_load(
+ monkeypatch,
+ tmp_path,
+ returncodes = [3, None],
+ platform = "linux",
+ )
+
+
+def test_an_accepted_replay_request_normalizes_the_placement(monkeypatch, tmp_path):
+ """A client that sends only the flag must still end up on manual/0, or the
+ session reports an Auto GPU placement for a CPU-only server."""
+ backend, loaded, launches, fallback_sources = _run_cpu_fallback_load(
+ monkeypatch,
+ tmp_path,
+ returncodes = [None],
+ cpu_fallback = True,
+ )
+
+ assert loaded is True
+ assert backend._cpu_fallback_reason == "vulkan_startup_crash"
+ assert backend._gpu_memory_mode == "manual"
+ assert backend._gpu_layers == 0
+ assert backend._gpu_ids is None
+ assert backend._last_load_intent.cpu_fallback is True
+
+
+def test_an_ineligible_replay_request_drops_the_recovery_state(monkeypatch, tmp_path):
+ """The kill phase keeps the staged recovery for a replay. A request that then
+ fails the eligibility bar must not leave the next model wearing it."""
+ backend, loaded, launches, fallback_sources = _run_cpu_fallback_load(
+ monkeypatch,
+ tmp_path,
+ returncodes = [None],
+ cpu_fallback = True,
+ resident_fallback = True,
+ extra_args = ["--device", "Vulkan0"],
+ )
+
+ assert loaded is True
+ assert fallback_sources == []
+ assert backend._cpu_fallback_reason is None
+ assert backend._cpu_fallback_runtime is None
+ assert backend._last_load_intent.cpu_fallback is False
+
+
+def test_preserving_a_recovery_ignores_env_the_replay_strips(monkeypatch, tmp_path):
+ """The replay pops every main-model placement var, so an inherited one must
+ not stop the resident CPU intent from being carried into a reload."""
+ monkeypatch.setenv("LLAMA_ARG_SPLIT_MODE", "tensor")
+ backend = LlamaCppBackend()
+ backend._cpu_fallback_reason = "vulkan_startup_crash"
+ intent = GgufLoadIntent(
+ model_identifier = "owner/model",
+ gguf_path = str(tmp_path / "model.gguf"),
+ )
+
+ preserved = backend._preserve_cpu_fallback_intent(intent, source_matches = True)
+
+ assert preserved.cpu_fallback is True
+ assert preserved.gpu_memory_mode == "manual"
+ assert preserved.gpu_layers == 0
+
+
+ "placement_env,extra_args",
+ [
+ ({"LLAMA_ARG_CPU_MOE": "true"}, None),
+ ({"LLAMA_ARG_N_CPU_MOE": "4"}, None),
+ ({"LLAMA_ARG_N_GPU_LAYERS": "20"}, None),
+ ({"LLAMA_ARG_TENSOR_SPLIT": "1"}, None),
+ ({"LLAMA_ARG_FIT": "off"}, None),
+ ({"LLAMA_ARG_FIT_TARGET": "1024"}, None),
+ ({"LLAMA_ARG_FIT_CTX": "4096"}, None),
+ ({"LLAMA_ARG_DEVICE": "Vulkan0"}, None),
+ ({"LLAMA_ARG_MAIN_GPU": "0"}, None),
+ ({"LLAMA_ARG_SPLIT_MODE": "tensor"}, None),
+ ({"LLAMA_ARG_SPLIT_MODE": "row"}, None),
+ ({"LLAMA_ARG_OVERRIDE_TENSOR": ".*=Vulkan0"}, None),
+ (
+ {
+ "LLAMA_ARG_SPLIT_MODE": "tensor",
+ "LLAMA_ARG_TENSOR_SPLIT": "1",
+ },
+ None,
+ ),
+ *(({}, extras) for extras in _RAW_MAIN_PLACEMENT_ARGS),
+ ],
+)
+def test_terminal_signal_with_explicit_child_placement_does_not_replay(
+ monkeypatch, tmp_path, placement_env, extra_args
+):
+ def _gguf_string(value: str) -> bytes:
+ encoded = value.encode()
+ return struct.pack("<Q", len(encoded)) + encoded
+
+ metadata = _gguf_string("general.architecture") + struct.pack("<I", 8) + _gguf_string("llama")
+ gguf = tmp_path / "model.gguf"
+ gguf.write_bytes(struct.pack("<IIQQ", 0x46554747, 3, 0, 1) + metadata)
+
+ backend = LlamaCppBackend()
+ backend._get_gpu_memory = lambda _binary = None: [(0, 8_000, 16_000)]
+ backend._get_gpu_free_memory = lambda _binary = None: [(0, 8_000)]
+ backend._read_gguf_metadata = lambda _path: None
+ backend._can_estimate_kv = lambda: False
+ backend._get_gguf_size_bytes = lambda _path: 1024
+ backend._mmproj_vram_bytes = lambda _path: 0
+ backend._resolve_launch_mmproj_path = lambda **_kwargs: None
+ backend._apu_ram_shortfall_message = lambda *_args, **_kwargs: None
+ backend._amd_apu_wants_unified_memory = lambda *_args, **_kwargs: False
+ backend._find_llama_server_binary = lambda include_denied = False: "/fake/llama-server"
+ backend._is_vulkan_backend = lambda _binary = None: True
+ backend._vulkan_prebuilt_was_auto_selected = lambda _binary: True
+ backend.probe_server_capabilities = lambda _binary: {"found": True}
+ backend._wait_for_health = lambda timeout: False
+ backend._record_server_pid = lambda _pid: None
+ backend._clear_server_pid = lambda: None
+ backend._llama_server_env_for_binary = lambda _binary: {
+ "PATH": os.environ.get("PATH", ""),
+ **placement_env,
+ }
+ isolated_replay_calls = []
+ backend._cpu_isolated_binary = lambda _binary: isolated_replay_calls.append(_binary)
+
+ launches = []
+
+ class _SignalProcess:
+ pid = 123
+ returncode = -11
+ stdout = ()
+
+ def poll(self):
+ return self.returncode
+
+ def terminate(self):
+ return None
+
+ def wait(self, timeout = None):
+ return self.returncode
+
+ def kill(self):
+ return None
+
+ def _popen(cmd, **kwargs):
+ launches.append((list(cmd), dict(kwargs["env"])))
+ return _SignalProcess()
+
+ monkeypatch.setattr(subprocess, "Popen", _popen)
+
+ with pytest.raises(RuntimeError):
+ backend.load_model(
+ GgufLoadIntent(
+ gguf_path = str(gguf),
+ model_identifier = "owner/model",
+ extra_args = extra_args,
+ )
+ )
+
+ assert launches
+ assert all(cmd[0] == "/fake/llama-server" for cmd, _env in launches)
+ assert isolated_replay_calls == []
+
+
+def test_vulkan_device_none_is_recorded_as_zero_vram(monkeypatch):
+ monkeypatch.setattr(
+ LlamaCppBackend, "_is_vulkan_backend", staticmethod(lambda _binary = None: True)
+ )
+ assert (
+ LlamaCppBackend._zero_offload_gpu_flag(
+ ["llama-server", "--gpu-layers", "0", "--device", "none"],
+ [(0, 4096)],
+ {},
+ )
+ is False
+ )
+
+
[email protected]("device", ["none", "cpu"])
+def test_vulkan_cpu_device_is_zero_vram_when_probe_is_empty(monkeypatch, device):
+ monkeypatch.setattr(
+ LlamaCppBackend, "_is_vulkan_backend", staticmethod(lambda _binary = None: True)
+ )
+ assert (
+ LlamaCppBackend._zero_offload_gpu_flag(
+ ["llama-server", "--gpu-layers", "0", "--device", device],
+ [],
+ {},
+ )
+ is False
+ )
+ assert LlamaCppBackend._zero_offload_gpu_flag(["llama-server", "-ngl", "0"], [], {}) is None
+
+
+def test_empty_probe_cpu_recovery_releases_chat_ownership(monkeypatch):
+ route_path = Path(_BACKEND_DIR) / "routes" / "inference.py"
+ spec = importlib.util.spec_from_file_location(
+ "inference_route_for_empty_probe_cpu_recovery", route_path
+ )
+ route = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(route)
+
+ backend = LlamaCppBackend()
+ backend.matches_load_source = lambda _intent: False
+
+ def _recover_on_cpu(*, intent):
+ backend._gpu_memory_mode = "manual"
+ backend._gpu_layers = 0
+ backend._gpu_offload_active = backend._zero_offload_gpu_flag(
+ ["llama-server", "--gpu-layers", "0", "--device", "none"],
+ [],
+ {},
+ )
+ backend._cpu_fallback_reason = "vulkan_startup_crash"
+ return True
+
+ backend.load_model = _recover_on_cpu
+ unsloth_backend = SimpleNamespace(active_model_name = None)
+ config = SimpleNamespace(
+ identifier = "owner/model.gguf",
+ display_name = "model.gguf",
+ is_gguf = True,
+ is_lora = False,
+ is_vision = False,
+ is_audio = False,
+ is_local = True,
+ gguf_hf_repo = None,
+ gguf_file = "/models/model.gguf",
+ gguf_mmproj_file = None,
+ gguf_mtp_file = None,
+ gguf_variant = None,
+ )
+ intent = GgufLoadIntent(
+ model_identifier = config.identifier,
+ gguf_path = config.gguf_file,
+ )
+ response = object()
+ owner = [None]
+ acquired = []
+ released = []
+
+ async def _inline_to_thread(func, /, *args, **kwargs):
+ return func(*args, **kwargs)
+
+ async def _prepare_load_placement(*_args, **_kwargs):
+ return route._LoadPlacement(None, None, False, False)
+
+ async def _wait_for_model_switch_idle(**_kwargs):
+ return None
+
+ def _acquire(requested, register = None):
+ if register is not None:
+ register()
+ owner[0] = requested
+ acquired.append(requested)
+
+ def _release(requested):
+ if owner[0] == requested:
+ owner[0] = None
+ released.append(requested)
+
+ import core.inference.gpu_arbiter as arbiter
+ import core.inference.llama_keepwarm as keepwarm
+
+ monkeypatch.setattr(
+ LlamaCppBackend, "_is_vulkan_backend", staticmethod(lambda _binary = None: True)
+ )
+ monkeypatch.setattr(route.asyncio, "to_thread", _inline_to_thread)
+ monkeypatch.setattr(
+ route,
+ "_resolve_model_identifier_for_request",
+ lambda *_args, **_kwargs: (config.identifier, config.identifier, False),
+ )
+ monkeypatch.setattr(route, "resolve_effective_chat_template_override", lambda **_kwargs: None)
+ monkeypatch.setattr(route, "get_inference_backend", lambda: unsloth_backend)
+ monkeypatch.setattr(route, "get_llama_cpp_backend", lambda: backend)
+ monkeypatch.setattr(
+ route,
+ "ModelConfig",
+ SimpleNamespace(from_identifier = lambda **_kwargs: config),
+ )
+ monkeypatch.setattr(route, "_hf_offline_if_unreachable_for", lambda *_args: nullcontext())
+ monkeypatch.setattr(route, "_resolve_inherited_extra_args", lambda *_args: None)
+ monkeypatch.setattr(route, "_prepare_load_placement", _prepare_load_placement)
+ monkeypatch.setattr(route, "_resolve_gguf_load_intent", lambda *_args, **_kwargs: intent)
+ monkeypatch.setattr(route, "_guard_chat_load_against_training", lambda *_args, **_kwargs: None)
+ monkeypatch.setattr(route, "_raise_if_sidecar_swap_in_progress", lambda: None)
+ monkeypatch.setattr(route, "_wait_for_model_switch_idle", _wait_for_model_switch_idle)
+ monkeypatch.setattr(route, "_close_load_event", lambda *_args, **_kwargs: None)
+ monkeypatch.setattr(route, "_gguf_load_response", lambda *_args, **_kwargs: response)
+ monkeypatch.setattr(route.api_monitor, "record_lifecycle", lambda **_kwargs: object())
+ monkeypatch.setattr(route, "_request_used_api_key", lambda _request: False)
+ monkeypatch.setattr(keepwarm, "note_model_loaded", lambda _backend: None)
+ monkeypatch.setattr(arbiter, "acquire_for", _acquire)
+ monkeypatch.setattr(arbiter, "current_owner", lambda: owner[0])
+ monkeypatch.setattr(arbiter, "release", _release)
+
+ request = route.LoadRequest(model_path = config.identifier)
+ fastapi_request = SimpleNamespace(
+ app = SimpleNamespace(state = SimpleNamespace(llama_parallel_slots = 1))
+ )
+ result = asyncio.run(
+ route._load_model_impl(request, fastapi_request, current_subject = "test-user")
+ )
+
+ assert result is response
+ assert backend.holds_no_vram is True
+ assert acquired == [arbiter.CHAT]
+ assert released == [arbiter.CHAT]
+ assert owner[0] is None
+
+
+def test_duplicate_auto_request_matches_recovered_cpu_server(tmp_path):
+ class _LiveProcess:
+ def poll(self):
+ return None
+
+ backend = LlamaCppBackend()
+ gguf = tmp_path / "model.gguf"
+ gguf.write_bytes(b"GGUF")
+ backend._process = _LiveProcess()
+ backend._healthy = True
+ backend._model_identifier = "owner/model"
+ backend._gguf_path = str(gguf)
+ backend._requested_n_ctx = 4096
+ backend._requested_n_parallel = 1
+ backend._requested_spec_mode = "auto"
+ backend._gpu_memory_mode = "manual"
+ backend._gpu_layers = 0
+ backend._cpu_fallback_reason = "vulkan_startup_crash"
+ assert backend.adopt_load_intent_if_matched(
+ GgufLoadIntent(
+ model_identifier = "owner/model",
+ gguf_path = str(gguf),
+ n_ctx = 4096,
+ gpu_memory_mode = "auto",
+ )
+ )
+
+ preserved = backend._preserve_cpu_fallback_intent(
+ GgufLoadIntent(
+ model_identifier = "owner/model",
+ gguf_path = str(gguf),
+ n_ctx = 8192,
+ gpu_memory_mode = "manual",
+ gpu_layers = 0,
+ )
+ )
+ assert preserved.n_ctx == 8192
+ assert preserved.cpu_fallback is True
+
+ explicit_gpu = backend._preserve_cpu_fallback_intent(
+ GgufLoadIntent(
+ model_identifier = "owner/model",
+ gguf_path = str(gguf),
+ n_ctx = 8192,
+ gpu_memory_mode = "manual",
+ gpu_layers = 1,
+ )
+ )
+ assert explicit_gpu.cpu_fallback is False
+
+
+def test_cpu_fallback_request_keeps_the_replay_intent():
+ route_path = Path(_BACKEND_DIR) / "routes" / "inference.py"
+ spec = importlib.util.spec_from_file_location(
+ "inference_route_for_cpu_fallback_rollback", route_path
+ )
+ route = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(route)
+ request = LoadRequest(
+ model_path = "owner/model",
+ gpu_memory_mode = "manual",
+ gpu_layers = 0,
+ cpu_fallback = True,
+ )
+ intent = route._gguf_request_intent(
+ GgufLoadIntent(model_identifier = "owner/model"),
+ request,
+ chat_template_override = None,
+ extra_args = None,
+ gpu_ids = None,
+ n_parallel = 1,
+ )
+ assert intent.cpu_fallback is True
+
+
[email protected]("model_cls", [LoadResponse, InferenceStatusResponse])
+def test_success_response_reports_cpu_downgrade(model_cls):
+ kwargs = {"cpu_fallback_reason": "vulkan_startup_crash"}
+ if model_cls is LoadResponse:
+ kwargs.update(status = "loaded", model = "owner/model", display_name = "model", inference = {})
+ response = model_cls(**kwargs)
+ assert response.model_dump()["cpu_fallback_reason"] == "vulkan_startup_crash"
diff --git a/studio/backend/tests/test_install_resolve_prebuilt.py b/studio/backend/tests/test_install_resolve_prebuilt.py
index cb1ce8b63ba..41126a1f8ec 100644
--- a/studio/backend/tests/test_install_resolve_prebuilt.py
+++ b/studio/backend/tests/test_install_resolve_prebuilt.py
@@ -13,6 +13,7 @@ because nothing in-tree mirrors it, and skips when that release is unreachable.
from __future__ import annotations
+import dataclasses
import importlib
import json
import sys
@@ -1218,7 +1219,7 @@ def test_route_to_vulkan_prebuilt_auto_fallback_for_legacy_amd_gfx():
host = _windows_amd_host(rocm_gfx_target = "gfx803", rocm_gfx_targets = ["gfx803"])
routed, repo, _tag, persist = ilp._route_to_vulkan_prebuilt(host, FORK, "pin", force_cpu = False)
assert repo == FORK
- assert persist == "vulkan"
+ assert persist == "auto"
assert routed.has_intel_gpu is True
assert routed.has_rocm is False
@@ -1257,7 +1258,7 @@ def test_route_to_vulkan_prebuilt_auto_fallback_when_no_amd_gpu_reaches_floor():
)
routed, repo, _tag, persist = ilp._route_to_vulkan_prebuilt(host, FORK, "pin", force_cpu = False)
assert repo == FORK
- assert persist == "vulkan"
+ assert persist == "auto"
assert routed.has_rocm is False
@@ -1342,6 +1343,24 @@ def test_route_to_vulkan_prebuilt_hip_masked_host_still_honours_explicit_optin(m
assert persist == "vulkan"
+def test_forced_vulkan_on_an_auto_routing_amd_host_persists_as_automatic(monkeypatch):
+ # This box has no HIP-capable AMD GPU, so it routes to Vulkan either way. Persisting
+ # that as automatic keeps pre-#8050 installs (whose updates re-assert
+ # --llama-backend vulkan) eligible for the Vulkan CPU crash recovery.
+ monkeypatch.delenv("UNSLOTH_FORCE_VULKAN", raising = False)
+ host = _windows_amd_host(rocm_gfx_target = "gfx1034", rocm_gfx_targets = ["gfx1034"])
+ _routed, _repo, _tag, persist = ilp._route_to_vulkan_prebuilt(
+ host, UPSTREAM, "pin", force_cpu = False, llama_backend = "vulkan"
+ )
+ assert persist == "auto"
+ # A host that can run HIP keeps the explicit choice explicit.
+ supported = _windows_amd_host(rocm_gfx_target = "gfx1100", rocm_gfx_targets = ["gfx1100"])
+ _routed, _repo, _tag, persist = ilp._route_to_vulkan_prebuilt(
+ supported, UPSTREAM, "pin", force_cpu = False, llama_backend = "vulkan"
+ )
+ assert persist == "vulkan"
+
+
def test_auto_vulkan_is_repository_specific_for_fork_only_gfx():
# gfx1034 is served only by the fork's gfx103X bundle: ggml-org's windows-hip radeon
# build does not target it and direct_upstream_release_plan() offers win-hip then CPU
@@ -1456,7 +1475,7 @@ def test_direct_upstream_windows_amd_legacy_gfx_routes_to_vulkan():
],
)
plan = ilp.direct_upstream_release_plan(rel, routed, repo, "latest")
- assert persist == "vulkan"
+ assert persist == "auto"
assert plan.attempts[0].install_kind == "windows-vulkan"
@@ -1676,7 +1695,7 @@ def test_forwarded_gfx_on_unprobed_host_still_auto_vulkans(monkeypatch):
assert ilp._should_auto_vulkan_for_amd_windows(host, FORK) is True
_routed, repo, _tag, persist = ilp._route_to_vulkan_prebuilt(host, FORK, "pin", force_cpu = False)
assert repo == FORK
- assert persist == "vulkan"
+ assert persist == "auto"
def test_forwarded_gfx_still_fills_an_unprobed_arch(monkeypatch):
@@ -1818,6 +1837,10 @@ def test_persisted_llama_backend_passes_none_through():
assert ilp.persisted_llama_backend(None, _choice("windows-vulkan")) is None
+def test_persisted_llama_backend_keeps_automatic_vulkan_distinct():
+ assert ilp.persisted_llama_backend("auto", _choice("windows-vulkan")) == "auto"
+
+
def test_marker_records_no_backend_when_vulkan_fell_back_to_cpu(tmp_path):
# End to end over write_prebuilt_metadata: describe the CPU attempt that actually won,
# so the next update re-detects instead of re-asserting Vulkan forever.
@@ -1858,6 +1881,165 @@ def test_marker_records_no_backend_when_vulkan_fell_back_to_cpu(tmp_path):
assert marker["llama_backend"] == "vulkan"
+def test_automatic_amd_vulkan_marker_records_the_routing_gfx(tmp_path, monkeypatch):
+ """An "auto" Vulkan marker must carry the arch that produced it.
+
+ The Windows AMD hosts that route here have no arch probe of their own
+ (setup.ps1 skips amd-smi without a HIP SDK and hipinfo is absent), so the
+ forwarded --rocm-gfx is the only evidence. The Vulkan asset name has no gfx
+ for rocm_install_args() to recover, so an update that re-detects the host
+ would find no ROCm at all and drop the bundle to CPU.
+ """
+ monkeypatch.delenv("UNSLOTH_FORCE_VULKAN", raising = False)
+ monkeypatch.delenv("HIP_VISIBLE_DEVICES", raising = False)
+ monkeypatch.delenv("ROCR_VISIBLE_DEVICES", raising = False)
+ monkeypatch.delenv("CUDA_VISIBLE_DEVICES", raising = False)
+ # A driver-only host: nothing probed, the arch arrived over --rocm-gfx.
+ unprobed = ilp.HostInfo(
+ system = "Windows",
+ machine = "amd64",
+ is_windows = True,
+ is_linux = False,
+ is_macos = False,
+ is_x86_64 = True,
+ is_arm64 = False,
+ nvidia_smi = None,
+ driver_cuda_version = None,
+ compute_caps = [],
+ visible_cuda_devices = None,
+ has_physical_nvidia = False,
+ has_usable_nvidia = False,
+ has_rocm = False,
+ has_intel_gpu = False,
+ )
+ host = ilp._apply_host_overrides(unprobed, override_rocm_gfx = "gfx1034")
+ assert ilp._should_auto_vulkan_for_amd_windows(host, UPSTREAM) is True
+ gfx = ilp._active_rocm_gfx_target(host)
+ routed, _repo, _tag, persist = ilp._route_to_vulkan_prebuilt(
+ host, UPSTREAM, "pin", force_cpu = False
+ )
+ assert persist == "auto"
+ # The route drops the arch, so it must be read before it, not after.
+ assert ilp._active_rocm_gfx_target(routed) is None
+ assert gfx == "gfx1034"
+
+ checksums = ilp.ApprovedReleaseChecksums(
+ repo = UPSTREAM,
+ release_tag = "b9925",
+ upstream_tag = "b9925",
+ source_repo = UPSTREAM,
+ source_repo_url = f"https://github.com/{UPSTREAM}",
+ )
+ ilp.write_prebuilt_metadata(
+ tmp_path,
+ requested_tag = "latest",
+ llama_tag = "b9925",
+ release_tag = "b9925",
+ choice = _choice("windows-vulkan", "llama-b9925-bin-win-vulkan-x64.zip"),
+ approved_checksums = checksums,
+ prebuilt_fallback_used = False,
+ llama_backend = persist,
+ rocm_gfx = gfx,
+ )
+ marker = json.loads((tmp_path / "UNSLOTH_PREBUILT_INFO.json").read_text())
+ assert marker["llama_backend"] == "auto"
+ assert marker["rocm_gfx"] == "gfx1034"
+
+ # Replaying the marker's arch reaches the same route on a re-detected host.
+ replayed = ilp._apply_host_overrides(unprobed, override_rocm_gfx = marker["rocm_gfx"])
+ assert ilp._should_auto_vulkan_for_amd_windows(replayed, UPSTREAM) is True
+ # Without it the update re-detects a ROCm-less host and leaves Vulkan behind.
+ assert ilp._should_auto_vulkan_for_amd_windows(unprobed, UPSTREAM) is False
+ assert ilp._route_to_vulkan_prebuilt(unprobed, UPSTREAM, "pin", force_cpu = False)[3] is None
+
+
+def test_a_remembered_arch_never_outranks_a_live_probe(monkeypatch):
+ """The updater replays the marker's arch, which is a stale probe result, not
+ an operator override: a host whose GPU changed must keep what it reports."""
+ monkeypatch.delenv("UNSLOTH_ROCM_GFX_ARCH", raising = False)
+ unprobed = dataclasses.replace(
+ _windows_amd_host(rocm_gfx_target = None, rocm_gfx_targets = []), has_rocm = False
+ )
+ monkeypatch.setenv("UNSLOTH_ROCM_GFX_REMEMBERED", "gfx1034")
+
+ # No probe of its own: the remembered arch fills the gap.
+ filled = ilp._apply_host_overrides(unprobed)
+ assert ilp._active_rocm_gfx_target(filled) == "gfx1034"
+ assert filled.has_rocm is True
+
+ # A live probe wins, so a replaced card is not routed as the old one.
+ probed = _windows_amd_host(rocm_gfx_target = "gfx1100", rocm_gfx_targets = ["gfx1100"])
+ assert ilp._active_rocm_gfx_target(ilp._apply_host_overrides(probed)) == "gfx1100"
+
+
+def test_reusing_an_install_still_records_the_routing_gfx(tmp_path):
+ """The reuse paths skip write_prebuilt_metadata, so they must sync it too."""
+ marker_path = tmp_path / "UNSLOTH_PREBUILT_INFO.json"
+ marker_path.write_text(json.dumps({"llama_backend": "auto", "asset": "win-vulkan.zip"}))
+
+ ilp.sync_marker_rocm_gfx(tmp_path, "gfx1034")
+ assert json.loads(marker_path.read_text())["rocm_gfx"] == "gfx1034"
+
+ # Nothing to record leaves the marker untouched.
+ ilp.sync_marker_rocm_gfx(tmp_path, None)
+ assert json.loads(marker_path.read_text())["rocm_gfx"] == "gfx1034"
+
+
[email protected]("backend", ["vulkan", None, "hip"])
+def test_only_the_automatic_route_records_a_routing_gfx(tmp_path, backend):
+ """Every other install names its arch in the asset. A stale copy there would
+ assert ROCm on a host whose AMD GPU is gone."""
+ marker_path = tmp_path / "UNSLOTH_PREBUILT_INFO.json"
+ marker_path.write_text(json.dumps({"llama_backend": backend, "asset": "win-hip.zip"}))
+
+ ilp.sync_marker_rocm_gfx(tmp_path, "gfx1034")
+
+ assert "rocm_gfx" not in json.loads(marker_path.read_text())
+
+ checksums = ilp.ApprovedReleaseChecksums(
+ repo = UPSTREAM,
+ release_tag = "b9925",
+ upstream_tag = "b9925",
+ source_repo = UPSTREAM,
+ source_repo_url = f"https://github.com/{UPSTREAM}",
+ )
+ ilp.write_prebuilt_metadata(
+ tmp_path,
+ requested_tag = "latest",
+ llama_tag = "b9925",
+ release_tag = "b9925",
+ choice = _choice("windows-vulkan", "llama-b9925-bin-win-vulkan-x64.zip"),
+ approved_checksums = checksums,
+ prebuilt_fallback_used = False,
+ llama_backend = backend,
+ rocm_gfx = "gfx1034",
+ )
+ assert "rocm_gfx" not in json.loads(marker_path.read_text())
+
+
+def test_non_amd_installs_record_no_routing_gfx(tmp_path):
+ """The key is absent unless an arch actually routed the install."""
+ checksums = ilp.ApprovedReleaseChecksums(
+ repo = UPSTREAM,
+ release_tag = "b9925",
+ upstream_tag = "b9925",
+ source_repo = UPSTREAM,
+ source_repo_url = f"https://github.com/{UPSTREAM}",
+ )
+ ilp.write_prebuilt_metadata(
+ tmp_path,
+ requested_tag = "latest",
+ llama_tag = "b9925",
+ release_tag = "b9925",
+ choice = _choice("windows-vulkan", "llama-b9925-bin-win-vulkan-x64.zip"),
+ approved_checksums = checksums,
+ prebuilt_fallback_used = False,
+ llama_backend = None,
+ )
+ marker = json.loads((tmp_path / "UNSLOTH_PREBUILT_INFO.json").read_text())
+ assert "rocm_gfx" not in marker
+
+
# setup translates UNSLOTH_LLAMA_CPP_BACKEND=cpu into --force-cpu to pin the
# CPU-only bundle on a GPU host, which is what keeps Intel iGPU Vulkan crashes
# away (#7213). Vulkan is opt-in, so no trigger may outrank that flag on any host.
diff --git a/studio/backend/tests/test_llama_cpp_update.py b/studio/backend/tests/test_llama_cpp_update.py
index 01a1b2ac3d2..0f6a810399c 100644
--- a/studio/backend/tests/test_llama_cpp_update.py
+++ b/studio/backend/tests/test_llama_cpp_update.py
@@ -84,6 +84,8 @@ def _write_install(
asset: str | None = None,
release_tag: str | None = None,
force_cpu: bool | None = None,
+ llama_backend: str | None = None,
+ include_llama_backend: bool = False,
) -> str:
"""Create a fake prebuilt install and return the llama-server path."""
bin_dir = dir_ / "build" / "bin"
@@ -102,6 +104,8 @@ def _write_install(
marker["asset"] = asset
if force_cpu is not None:
marker["force_cpu"] = force_cpu
+ if include_llama_backend or llama_backend is not None:
+ marker["llama_backend"] = llama_backend
(dir_ / MARKER).write_text(json.dumps(marker))
return str(binary)
@@ -457,16 +461,31 @@ def test_start_update_happy_path(monkeypatch, tmp_path):
assert popen_kwargs["env"]["UNSLOTH_PROGRESS_PERCENT_STEP"] == "5"
-def test_start_update_preserves_vulkan_via_env(monkeypatch, tmp_path):
- # A Vulkan install (marker asset carries 'vulkan') must re-assert
- # UNSLOTH_FORCE_VULKAN on update, or detect_host on a GPU box re-routes to
- # CUDA/ROCm and silently replaces the Vulkan build.
+ "llama_backend,include_llama_backend,expect_forced",
+ [
+ (None, False, True),
+ (None, True, False),
+ ("vulkan", True, True),
+ ("auto", True, False),
+ ],
+)
+def test_start_update_preserves_vulkan_selection(
+ monkeypatch, tmp_path, llama_backend, include_llama_backend, expect_forced
+):
+ # A legacy markerless Vulkan asset was an explicit selection. New automatic Intel
+ # and Windows AMD installs carry llama_backend (None or "auto") and rerun hardware
+ # detection so they stay eligible for CPU crash recovery.
+ monkeypatch.delenv("UNSLOTH_FORCE_VULKAN", raising = False)
+ monkeypatch.delenv("UNSLOTH_LLAMA_CPP_BACKEND", raising = False)
install_dir = tmp_path / "llama.cpp"
binary = _write_install(
install_dir,
"b9493",
repo = "ggml-org/llama.cpp",
asset = "llama-b9493-bin-ubuntu-vulkan-x64.tar.gz",
+ llama_backend = llama_backend,
+ include_llama_backend = include_llama_backend,
)
monkeypatch.setattr(upd, "_find_binary", lambda: binary)
monkeypatch.setattr(upd, "_installer_script", lambda: tmp_path / "install_llama_prebuilt.py")
@@ -479,6 +498,7 @@ def test_start_update_preserves_vulkan_via_env(monkeypatch, tmp_path):
"b9518",
repo = "ggml-org/llama.cpp",
asset = "llama-b9518-bin-ubuntu-vulkan-x64.tar.gz",
+ llama_backend = llama_backend,
)
captured: dict = {}
@@ -498,9 +518,14 @@ def test_start_update_preserves_vulkan_via_env(monkeypatch, tmp_path):
break
time.sleep(0.05)
assert job["state"] == "success", job
- assert popen_kwargs["env"]["UNSLOTH_FORCE_VULKAN"] == "1"
- assert popen_kwargs["env"]["UNSLOTH_LLAMA_CPP_BACKEND"] == "vulkan"
- assert "--llama-backend" in captured["cmd"] and "vulkan" in captured["cmd"]
+ if expect_forced:
+ assert popen_kwargs["env"]["UNSLOTH_FORCE_VULKAN"] == "1"
+ assert popen_kwargs["env"]["UNSLOTH_LLAMA_CPP_BACKEND"] == "vulkan"
+ assert "--llama-backend" in captured["cmd"] and "vulkan" in captured["cmd"]
+ else:
+ assert "UNSLOTH_FORCE_VULKAN" not in popen_kwargs["env"]
+ assert "UNSLOTH_LLAMA_CPP_BACKEND" not in popen_kwargs["env"]
+ assert "--llama-backend" not in captured["cmd"]
@pytest.mark.parametrize(
diff --git a/studio/backend/tests/test_metal_paravirtual_guard.py b/studio/backend/tests/test_metal_paravirtual_guard.py
index c5cb2a325e2..e3c0344d394 100644
--- a/studio/backend/tests/test_metal_paravirtual_guard.py
+++ b/studio/backend/tests/test_metal_paravirtual_guard.py
@@ -636,7 +636,10 @@ def test_the_drop_precedes_everything_the_projector_feeds():
gate_at = src.index("_pv_mmproj_unpinnable = bool(")
assert gate_at < src.index('cmd.extend(["--mmproj", launch_mmproj_path])')
assert gate_at < src.index("self._mmproj_vram_bytes(launch_mmproj_path)")
- assert gate_at < src.index("read_mmproj_audio_capability(launch_mmproj_path)")
+ # The probe reads launch_mmproj_path, or the env projector only if the gate dropped
+ # nothing, so both the gate and that choice precede it.
+ assert gate_at < src.index("_audio_probe = launch_mmproj_path or (")
+ assert gate_at < src.index("read_mmproj_audio_capability(_audio_probe)")
# ...and the session flag the frontend reads follows the same variable.
assert "self._is_vision = effective_is_vision" in src
diff --git a/studio/backend/utils/llama_cpp_update.py b/studio/backend/utils/llama_cpp_update.py
index f5e373fcff0..9d363924803 100644
--- a/studio/backend/utils/llama_cpp_update.py
+++ b/studio/backend/utils/llama_cpp_update.py
@@ -412,6 +412,7 @@ def _run_llama_phase(
set_progress,
force_cpu: bool = False,
llama_backend: Optional[str] = None,
+ rocm_gfx: Optional[str] = None,
) -> dict:
"""The llama phase of a chained update: put the backend into a maintenance
state, run the installer for the latest prebuilt, then refresh caches so the
@@ -474,10 +475,16 @@ def _run_llama_phase(
logger.info("llama update: installing", cmd = " ".join(cmd))
env = dict(os.environ, UNSLOTH_PROGRESS_PERCENT_STEP = "5")
# Preserve a Vulkan install across updates: detect_host on a CUDA/ROCm box would
- # otherwise re-route and silently replace it. Re-assert via setup's env/CLI flags.
- if llama_backend == "vulkan" or (asset and "vulkan" in asset.lower()):
+ # otherwise replace it. An "auto" marker reruns hardware detection instead.
+ if llama_backend == "vulkan":
env["UNSLOTH_FORCE_VULKAN"] = "1"
env["UNSLOTH_LLAMA_CPP_BACKEND"] = "vulkan"
+ # A Vulkan asset name carries no arch, so the marker is the only record of the
+ # gfx an automatic AMD route used. Automatic only: elsewhere the asset has the
+ # arch, and replaying it would assert ROCm on a host whose AMD GPU is gone.
+ # Advisory even then, applied only if this host's own probe finds none.
+ if rocm_gfx and llama_backend == "auto":
+ env["UNSLOTH_ROCM_GFX_REMEMBERED"] = rocm_gfx
_flow.stream_installer(
cmd,
env,
@@ -611,7 +618,12 @@ def _plan_llama_phase() -> dict:
asset = marker.get("asset")
force_cpu = bool(marker.get("force_cpu"))
llama_backend = marker.get("llama_backend")
- if llama_backend == "vulkan" or (asset and "vulkan" in str(asset).lower()):
+ rocm_gfx = marker.get("rocm_gfx")
+ # Markers written before #7188 lack llama_backend, so an explicit Vulkan
+ # choice is indistinguishable from the old automatic Intel route: keep the
+ # existing bundle rather than switching backends. Newer automatic installs
+ # carry the key as null and rerun detection to stay eligible for CPU recovery.
+ if "llama_backend" not in marker and asset and "vulkan" in str(asset).lower():
llama_backend = "vulkan"
# Install exactly the release the banner offered: the installer's own
# "latest" is commit-date ordered and can lag the published_at pick
@@ -657,6 +669,7 @@ def _plan_llama_phase() -> dict:
# Source builds carry no forced-CPU marker, so nothing to preserve here.
force_cpu = False
llama_backend = None
+ rocm_gfx = None
# No pin: source-build detection resolves via --resolve-prebuilt latest,
# the same resolver the unpinned apply uses, so the two already agree.
pin_release_tag = None
@@ -680,6 +693,7 @@ def _plan_llama_phase() -> dict:
"from_tag": from_tag,
"force_cpu": force_cpu,
"llama_backend": llama_backend,
+ "rocm_gfx": rocm_gfx,
}
}
@@ -733,6 +747,7 @@ def start_update() -> dict:
set_progress,
force_cpu = llama_spec.get("force_cpu", False),
llama_backend = llama_spec.get("llama_backend"),
+ rocm_gfx = llama_spec.get("rocm_gfx"),
)
)
if llama_spec
diff --git a/studio/frontend/src/features/chat/api/chat-adapter.ts b/studio/frontend/src/features/chat/api/chat-adapter.ts
index a0d86f6e942..b21529882f1 100644
--- a/studio/frontend/src/features/chat/api/chat-adapter.ts
+++ b/studio/frontend/src/features/chat/api/chat-adapter.ts
@@ -100,6 +100,7 @@ import {
import type { ModelType } from "../types";
import { isMultimodalResponse } from "../types/api";
import type {
+ CpuFallbackReason,
GgufVariantDetail,
OpenAIChatCompletionsRequest,
OpenAIChatMessage,
@@ -1752,6 +1753,7 @@ const VISIBLE_MODEL_RUNTIME_KEYS = [
"loadedTensorParallel",
"gpuMemoryMode",
"loadedGpuMemoryMode",
+ "loadedCpuFallback",
"gpuLayers",
"loadedGpuLayers",
"nCpuMoe",
@@ -2365,17 +2367,26 @@ async function autoLoadSmallestModel(options?: AutoLoadOptions): Promise<{
: undefined,
});
};
- const showAutoLoadSuccess = (message: string): void => {
+ // Like the interactive load toast: an auto-load that lost GPU acceleration
+ // must not read as a plain success.
+ const showAutoLoadSuccess = (
+ message: string,
+ cpuFallbackReason?: CpuFallbackReason | null,
+ ): void => {
const options = {
- description: undefined,
+ description: cpuFallbackReason
+ ? "The auto-selected Vulkan backend crashed during startup, so GPU acceleration is disabled for this model session."
+ : undefined,
duration: 5000,
icon: undefined,
};
+ const showToast = cpuFallbackReason ? toast.warning : toast.success;
+ const title = cpuFallbackReason ? `${message} on CPU` : message;
if (autoLoadToastDismissed) {
- toast.success(message, options);
+ showToast(title, options);
return;
}
- toast.success(message, { ...options, id: toastId });
+ showToast(title, { ...options, id: toastId });
};
let blockedByTrustRemoteCode = false;
let hadNonTrustFailure = false;
@@ -2807,7 +2818,7 @@ async function autoLoadSmallestModel(options?: AutoLoadOptions): Promise<{
ggufVariant: candidate.ggufVariant,
});
}
- showAutoLoadSuccess(candidate.successLabel);
+ showAutoLoadSuccess(candidate.successLabel, loadResp.cpu_fallback_reason);
});
return true;
}
@@ -3116,6 +3127,7 @@ async function autoLoadSmallestModel(options?: AutoLoadOptions): Promise<{
});
showAutoLoadSuccess(
`Loaded ${DEFAULT_CHAT_MODEL_LABEL} (${DEFAULT_CHAT_MODEL_VARIANT})`,
+ loadResp.cpu_fallback_reason,
);
});
return { loaded: true, blockedByTrustRemoteCode: false };
diff --git a/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts b/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts
index c8c2f3007a8..8e31180cf5f 100644
--- a/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts
+++ b/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts
@@ -66,9 +66,7 @@ import {
import { recordLastLocalModelLoad } from "../utils/last-local-model-load";
import { refreshContextUsage } from "../utils/refresh-context-usage";
import { ensureGpuDeviceCache } from "@/hooks/use-gpu-info";
-import {
- isMultimodalResponse,
-} from "../types/api";
+import { type CpuFallbackReason, isMultimodalResponse } from "../types/api";
import { isExternalModelId } from "../external-providers";
import {
applyPerModelConfigToRuntime,
@@ -767,6 +765,7 @@ export function useChatModelRuntime() {
const abortCtrl = new AbortController();
loadAbortRef.current = abortCtrl;
const postLoadRefresh = { needed: false };
+ let cpuFallbackReason: CpuFallbackReason | null = null;
try {
async function performLoad(): Promise<void> {
if (abortCtrl.signal.aborted) throw new Error("Cancelled");
@@ -1226,6 +1225,7 @@ export function useChatModelRuntime() {
gpu_ids: loadSelectedGpuIds ?? undefined,
force_cancel_active: forceCancelActive,
});
+ cpuFallbackReason = loadResponse.cpu_fallback_reason ?? null;
// If cancelled while loading, don't update UI to show
// the model as active -- it's being unloaded.
@@ -1516,6 +1516,9 @@ export function useChatModelRuntime() {
// Restore the previous model's GPU Memory placement, not backend defaults.
gpu_memory_mode: stateBeforeUnload.loadedGpuMemoryMode ?? "auto",
gpu_layers: stateBeforeUnload.loadedGpuLayers ?? GPU_LAYERS_AUTO,
+ // A recovered Vulkan model needs its staged CPU-only runtime back
+ // after the failed target load unloaded the live server.
+ cpu_fallback: stateBeforeUnload.loadedCpuFallback,
n_cpu_moe: stateBeforeUnload.loadedNCpuMoe ?? 0,
tensor_split: stateBeforeUnload.loadedSplitRatio ?? undefined,
gpu_ids: stateBeforeUnload.loadedGpuIds ?? undefined,
@@ -1844,15 +1847,23 @@ export function useChatModelRuntime() {
await performLoad();
// User cancelled mid-refresh; cancelLoading handles teardown.
if (abortCtrl.signal.aborted) return;
+ const loadedTitle = cpuFallbackReason
+ ? `${toastDisplayName} loaded on CPU`
+ : `${toastDisplayName} loaded`;
+ const loadedDescription = cpuFallbackReason
+ ? "The auto-selected Vulkan backend crashed during startup, so GPU acceleration is disabled for this model session."
+ : undefined;
+ const showLoadedToast = cpuFallbackReason ? toast.warning : toast.success;
if (loadToastDismissedRef.current) {
- toast.success(`${toastDisplayName} loaded`, {
+ showLoadedToast(loadedTitle, {
+ description: loadedDescription,
closeButton: true,
duration: 8000,
});
} else {
- toast.success(`${toastDisplayName} loaded`, {
+ showLoadedToast(loadedTitle, {
id: toastId,
- description: undefined,
+ description: loadedDescription,
cancel: undefined,
closeButton: true,
duration: 8000,
diff --git a/studio/frontend/src/features/chat/lib/gpu-placement.ts b/studio/frontend/src/features/chat/lib/gpu-placement.ts
index fc5b3b45152..fdcbf1f2596 100644
--- a/studio/frontend/src/features/chat/lib/gpu-placement.ts
+++ b/studio/frontend/src/features/chat/lib/gpu-placement.ts
@@ -8,6 +8,12 @@
// llama.cpp's --fit). The Manual default; "all on GPU" is the slider's max.
export const GPU_LAYERS_AUTO = -1;
+export function shouldHydrateGpuPlacementControls(
+ cpuFallbackReason: "vulkan_startup_crash" | null | undefined,
+): boolean {
+ return cpuFallbackReason !== "vulkan_startup_crash";
+}
+
/** GPU placement a compare pane loads with.
*
* `own` is the pane's per-model config; `shared` is the live-store snapshot taken at
diff --git a/studio/frontend/src/features/chat/stores/chat-runtime-store.ts b/studio/frontend/src/features/chat/stores/chat-runtime-store.ts
index 9193b98b2b3..9c122aa58e2 100644
--- a/studio/frontend/src/features/chat/stores/chat-runtime-store.ts
+++ b/studio/frontend/src/features/chat/stores/chat-runtime-store.ts
@@ -14,6 +14,7 @@ import { create } from "zustand";
import {
GPU_LAYERS_AUTO,
recoverDroppedDiffusionSplit,
+ shouldHydrateGpuPlacementControls,
} from "../lib/gpu-placement";
import { isExternalModelId, parseExternalModelId } from "../external-providers";
import {
@@ -682,6 +683,7 @@ export function loadedGpuMemoryFields(resp: {
is_diffusion?: boolean;
gpu_memory_mode?: "auto" | "manual";
gpu_layers?: number;
+ cpu_fallback_reason?: "vulkan_startup_crash" | null;
n_cpu_moe?: number;
tensor_split?: number[] | null;
n_layers?: number | null;
@@ -706,6 +708,7 @@ export function loadedGpuMemoryFields(resp: {
loadedGpuIds: null,
loadedGpuIndexKind: null,
loadedGpuMemoryMode: null,
+ loadedCpuFallback: false,
gpuLayers: GPU_LAYERS_AUTO,
loadedGpuLayers: null,
nCpuMoe: 0,
@@ -717,6 +720,9 @@ export function loadedGpuMemoryFields(resp: {
};
}
const mode = resp.gpu_memory_mode ?? "auto";
+ const hydratePlacementControls = shouldHydrateGpuPlacementControls(
+ resp.cpu_fallback_reason,
+ );
// Keep the user's placement pool editable across status/load hydration.
// gpu_ids remains the effective fitted subset for diagnostics.
const reportedGpuIds = requestedGpuIdsFromResponse(resp);
@@ -750,9 +756,13 @@ export function loadedGpuMemoryFields(resp: {
loadedGpuLayers: resp.gpu_layers ?? null,
loadedNCpuMoe: resp.n_cpu_moe ?? null,
loadedSplitRatio: resp.tensor_split ?? null,
- gpuLayers: resp.gpu_layers ?? GPU_LAYERS_AUTO,
- nCpuMoe: resp.n_cpu_moe ?? 0,
- splitRatio: resp.tensor_split ?? null,
+ ...(hydratePlacementControls
+ ? {
+ gpuLayers: resp.gpu_layers ?? GPU_LAYERS_AUTO,
+ nCpuMoe: resp.n_cpu_moe ?? 0,
+ splitRatio: resp.tensor_split ?? null,
+ }
+ : {}),
}
: {
loadedGpuLayers: null,
@@ -779,12 +789,15 @@ export function loadedGpuMemoryFields(resp: {
// A diffusion GGUF reporting "auto" ran on the runner's defaults, so an inert standing
// manual preference must survive it. But "manual" means a split was actually applied
// (#7574): adopt it, or a refresh hydrates back to "auto" while the runner serves one.
- ...(resp.is_diffusion && mode !== "manual"
- ? droppedSplit != null
- ? { gpuMemoryMode: "manual" as const }
- : {}
- : { gpuMemoryMode: mode }),
+ ...(hydratePlacementControls
+ ? resp.is_diffusion && mode !== "manual"
+ ? droppedSplit != null
+ ? { gpuMemoryMode: "manual" as const }
+ : {}
+ : { gpuMemoryMode: mode }
+ : {}),
loadedGpuMemoryMode: mode,
+ loadedCpuFallback: resp.cpu_fallback_reason === "vulkan_startup_crash",
ggufLayerCount: resp.n_layers ?? null,
// MoE expert-layer count: the n_cpu_moe slider max, and 0 hides the slider.
moeLayerCount: resp.n_moe_layers ?? null,
@@ -1083,6 +1096,8 @@ type ChatRuntimeStore = {
gpuMemoryMode: "auto" | "manual";
/** Backend-reported gpu memory mode; null until first hydrated. */
loadedGpuMemoryMode: "auto" | "manual" | null;
+ /** The active model must use the staged CPU-only runtime when it is reloaded. */
+ loadedCpuFallback: boolean;
/** Manual mode: layers to offload to GPU. -1 = Auto (--fit); >= model layer
* count = all. */
gpuLayers: number;
@@ -1633,6 +1648,7 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({
loadedTensorParallel: null,
gpuMemoryMode: readPersistedGpuMemoryMode(),
loadedGpuMemoryMode: null,
+ loadedCpuFallback: false,
gpuLayers: GPU_LAYERS_AUTO,
loadedGpuLayers: null,
nCpuMoe: 0,
@@ -2095,6 +2111,7 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({
// Standing preference: survives unload, unlike the per-model knobs above.
gpuMemoryMode: readPersistedGpuMemoryMode(),
loadedGpuMemoryMode: null,
+ loadedCpuFallback: false,
gpuLayers: GPU_LAYERS_AUTO,
loadedGpuLayers: null,
nCpuMoe: 0,
diff --git a/studio/frontend/src/features/chat/types/api.ts b/studio/frontend/src/features/chat/types/api.ts
index 023ef18223d..c2da6e3438b 100644
--- a/studio/frontend/src/features/chat/types/api.ts
+++ b/studio/frontend/src/features/chat/types/api.ts
@@ -3,6 +3,8 @@
import type { TransformersUpgradeInfo } from "@/features/transformers-upgrade";
+export type CpuFallbackReason = "vulkan_startup_crash";
+
export interface BackendModelDetails {
id: string;
name?: string | null;
@@ -87,6 +89,8 @@ export interface LoadModelRequest {
gpu_memory_mode?: "auto" | "manual";
/** Manual mode: layers to offload to GPU (--gpu-layers, --fit off); -1 = Auto (--fit). */
gpu_layers?: number;
+ /** Restore a previous automatic Vulkan CPU recovery after a failed model switch. */
+ cpu_fallback?: boolean;
/** Manual mode: MoE expert layers to keep on CPU (--n-cpu-moe); 0 = none. */
n_cpu_moe?: number;
/** Manual mode: relative model share per GPU (--tensor-split), in GPU order. */
@@ -220,6 +224,8 @@ export interface LoadModelResponse {
tensor_parallel?: boolean;
gpu_memory_mode?: "auto" | "manual";
gpu_layers?: number;
+ /** Set when an automatic Vulkan startup crash was recovered by loading on CPU. */
+ cpu_fallback_reason?: CpuFallbackReason | null;
n_cpu_moe?: number;
tensor_split?: number[] | null;
n_layers?: number | null;
@@ -303,6 +309,8 @@ export interface InferenceStatusResponse {
tensor_parallel?: boolean;
gpu_memory_mode?: "auto" | "manual";
gpu_layers?: number;
+ /** Set while the active model is a recovered CPU-only Vulkan load. */
+ cpu_fallback_reason?: CpuFallbackReason | null;
n_cpu_moe?: number;
tensor_split?: number[] | null;
/** n_ctx the active GGUF load was invoked with (0 = Auto); re-seeds a
diff --git a/studio/frontend/tests/auto-load-cpu-fallback-toast.test.ts b/studio/frontend/tests/auto-load-cpu-fallback-toast.test.ts
new file mode 100644
index 00000000000..f47bda2b7ee
--- /dev/null
+++ b/studio/frontend/tests/auto-load-cpu-fallback-toast.test.ts
@@ -0,0 +1,32 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import test from "node:test";
+import { fileURLToPath } from "node:url";
+
+// Asserted against the source like the other chat-adapter tests: importing the
+// module would drag in the stores and the toast layer for one closure.
+const source = readFileSync(
+ fileURLToPath(
+ new URL("../src/features/chat/api/chat-adapter.ts", import.meta.url),
+ ),
+ "utf8",
+);
+
+test("an auto-load that fell back to CPU warns instead of claiming plain success", () => {
+ const start = source.indexOf("const showAutoLoadSuccess = (");
+ assert.ok(start >= 0, "showAutoLoadSuccess is no longer defined");
+ const helper = source.slice(start, source.indexOf("\n };", start));
+ assert.match(helper, /cpuFallbackReason \? toast\.warning : toast\.success/);
+ assert.match(helper, /GPU acceleration is disabled for this model session/);
+});
+
+test("every auto-load path forwards the load response's fallback reason", () => {
+ const calls = source.match(/\n\s*showAutoLoadSuccess\([\s\S]*?\);/g) ?? [];
+ assert.ok(calls.length > 0, "no showAutoLoadSuccess call sites found");
+ for (const call of calls) {
+ assert.match(call, /cpu_fallback_reason/);
+ }
+});
diff --git a/studio/frontend/tests/gpu-placement.test.ts b/studio/frontend/tests/gpu-placement.test.ts
index ef3e6bc7077..0d6d314b540 100644
--- a/studio/frontend/tests/gpu-placement.test.ts
+++ b/studio/frontend/tests/gpu-placement.test.ts
@@ -9,12 +9,21 @@ import {
resolveComparePlacement,
recoverDroppedDiffusionSplit,
resolveStagedDiffusionClassification,
+ shouldHydrateGpuPlacementControls,
shouldPinDiffusionPlacement,
} from "../src/features/chat/lib/gpu-placement.ts";
// The Send-time snapshot: Manual with 12 of another chat GGUF's layers on GPU.
const shared = { gpuMemoryMode: "manual" as const, gpuLayers: 12 };
+test("a Vulkan CPU fallback does not replace the standing GPU intent", () => {
+ assert.equal(
+ shouldHydrateGpuPlacementControls("vulkan_startup_crash"),
+ false,
+ );
+ assert.equal(shouldHydrateGpuPlacementControls(null), true);
+});
+
test("a diffusion pane never inherits another model's layer split", () => {
// An unremembered pane carries neither key, so `??` would fall through to shared.
assert.deepEqual(resolveComparePlacement({}, shared, true), {
diff --git a/studio/install_llama_prebuilt.py b/studio/install_llama_prebuilt.py
index cc9ed6e73f6..5709d889d75 100644
--- a/studio/install_llama_prebuilt.py
+++ b/studio/install_llama_prebuilt.py
@@ -2773,6 +2773,17 @@ def _apply_host_overrides(
# [gfx], so the driver-only host the forward exists for keeps auto-Vulkan.
rocm_gfx_targets = list(dict.fromkeys([*_physical, gfx])),
)
+ # The arch a previous install recorded, replayed by the updater. A remembered
+ # probe result, not an operator override, so it only fills a gap: a host whose
+ # GPU changed keeps whatever its own probe now reports.
+ remembered = _normalize_forwarded_gfx(os.environ.get("UNSLOTH_ROCM_GFX_REMEMBERED"))
+ if remembered and not _active_rocm_gfx_target(host):
+ return dataclasses_replace(
+ host,
+ has_rocm = True,
+ rocm_gfx_target = remembered,
+ rocm_gfx_targets = list(dict.fromkeys([*_host_rocm_gfx_targets(host), remembered])),
+ )
if override_has_rocm and not host.has_rocm:
return dataclasses_replace(host, has_rocm = True)
return host
@@ -5736,6 +5747,7 @@ def write_prebuilt_metadata(
prebuilt_fallback_used: bool,
force_cpu: bool = False,
llama_backend: str | None = None,
+ rocm_gfx: str | None = None,
) -> None:
source_asset_name, source_sha256 = selected_source_archive_metadata(
approved_checksums,
@@ -5754,6 +5766,7 @@ def write_prebuilt_metadata(
)
if fingerprint is None:
raise PrebuiltFallback(f"cannot compute install fingerprint for {choice.name}")
+ _persisted_backend = persisted_llama_backend(llama_backend, choice)
metadata = {
"requested_tag": requested_tag,
"tag": llama_tag,
@@ -5764,9 +5777,15 @@ def write_prebuilt_metadata(
# so a forced CPU install is not re-routed to a GPU bundle (#7213). An automatic
# --cpu-fallback (e.g. arm64 GPU-build recovery) stays False so it can heal to GPU.
"force_cpu": force_cpu,
- # Deliberate or auto-selected Vulkan backend (#7357); the updater re-asserts it so
- # AMD hosts are not swapped back to HIP. Dropped if the winning attempt was not Vulkan.
- "llama_backend": persisted_llama_backend(llama_backend, choice),
+ # Explicit Vulkan is recorded as "vulkan"; automatic Windows AMD routing is
+ # recorded as "auto" so runtime recovery can distinguish them.
+ "llama_backend": _persisted_backend,
+ # The AMD gfx an AUTOMATIC route was decided on. A Vulkan asset name carries
+ # no arch, and the Windows driver-only hosts that reach Vulkan automatically
+ # have no probe (hipinfo/amd-smi absent), so the updater would re-detect a
+ # ROCm-less host and drop to CPU. Automatic only: elsewhere the asset names
+ # the arch, and a stale copy would outlive its GPU.
+ **({"rocm_gfx": rocm_gfx} if rocm_gfx and _persisted_backend == "auto" else {}),
"asset_sha256": choice.expected_sha256,
"source": choice.source_label,
# Binary-side repo/tag for non-fork sources (e.g. the ggml-org upstream
@@ -5906,6 +5925,31 @@ def sync_marker_llama_backend(install_dir: Path, llama_backend: str | None) -> N
log(f"existing install reused; recorded llama_backend={llama_backend!r} from this run")
+def sync_marker_rocm_gfx(install_dir: Path, rocm_gfx: str | None) -> None:
+ """Sync the routing AMD arch when the bundle is reused unchanged. A Vulkan
+ asset name carries no arch, so a reuse that skipped write_prebuilt_metadata
+ would leave an automatic marker the next update cannot route from."""
+ if not rocm_gfx:
+ return
+ marker_path = install_dir / "UNSLOTH_PREBUILT_INFO.json"
+ try:
+ marker = json.loads(marker_path.read_text(encoding = "utf-8"))
+ except (OSError, ValueError):
+ return
+ if not isinstance(marker, dict) or marker.get("rocm_gfx") == rocm_gfx:
+ return
+ # Only the automatic route needs it: elsewhere the asset names the arch, and a
+ # stale one would outlive the GPU it describes.
+ if marker.get("llama_backend") != "auto":
+ return
+ marker["rocm_gfx"] = rocm_gfx
+ if not _write_marker(marker_path, marker):
+ log(
+ f"WARNING: could not record rocm_gfx={rocm_gfx!r} in {marker_path}; "
+ "a later update may not reproduce this GPU routing"
+ )
+
+
def recorded_ggml_tree(
approved_checksums: ApprovedReleaseChecksums, choice: AssetChoice
) -> str | None:
@@ -6258,6 +6302,7 @@ def validate_prebuilt_choice(
quantized_path: Path,
force_cpu: bool = False,
llama_backend: str | None = None,
+ rocm_gfx: str | None = None,
) -> tuple[Path, Path]:
source_repo, source_ref, source_archive, exact_source = preferred_source_archive(
approved_checksums, llama_tag
@@ -6304,6 +6349,7 @@ def validate_prebuilt_choice(
prebuilt_fallback_used = prebuilt_fallback_used,
force_cpu = force_cpu,
llama_backend = llama_backend,
+ rocm_gfx = rocm_gfx,
)
# Hashless external prebuilts are not in the approved-sha256
# manifest and rely on the functional smoke test as their only integrity gate,
@@ -6392,6 +6438,7 @@ def validate_prebuilt_attempts(
existing_install_dir: Path | None = None,
force_cpu: bool = False,
llama_backend: str | None = None,
+ rocm_gfx: str | None = None,
) -> tuple[AssetChoice, Path, bool]:
attempt_list = list(attempts)
if not attempt_list:
@@ -6454,6 +6501,7 @@ def validate_prebuilt_attempts(
quantized_path = quantized_path,
force_cpu = force_cpu,
llama_backend = llama_backend,
+ rocm_gfx = rocm_gfx,
)
except Exception as exc:
remove_tree(staging_dir)
@@ -6701,11 +6749,12 @@ def _route_to_vulkan_prebuilt(
the install marker when updates must re-assert Vulkan.
"""
forced = force_vulkan_requested(llama_backend)
- # Auto-fall back only when the run named no backend: an explicit hip/cpu is the opt-out.
explicit_backend = resolved_llama_backend(llama_backend)
- auto_no_hip = explicit_backend is None and _should_auto_vulkan_for_amd_windows(
- host, published_repo
- )
+ # Host-only test, so a forced Vulkan run can still tell this box would have
+ # routed itself to Vulkan anyway.
+ amd_no_hip_host = _should_auto_vulkan_for_amd_windows(host, published_repo)
+ # Auto-fall back only when the run named no backend: an explicit hip/cpu is the opt-out.
+ auto_no_hip = explicit_backend is None and amd_no_hip_host
# No PHYSICAL NVIDIA, not merely no usable one: Vulkan ignores CUDA_VISIBLE_DEVICES, so
# auto-routing a host that hides its NVIDIA card would let it grab the reserved GPU.
auto_intel = (
@@ -6737,14 +6786,17 @@ def _route_to_vulkan_prebuilt(
f"({active}); installing the Vulkan llama.cpp prebuilt instead"
)
host = _vulkan_only_host(host)
- persist_backend = "vulkan"
+ persist_backend = "auto"
elif forced:
log(
"Vulkan llama.cpp backend requested; installing the Vulkan "
"prebuilt instead of the detected GPU backend"
)
host = _vulkan_only_host(host)
- persist_backend = "vulkan"
+ # A host with no HIP-capable AMD GPU routes here anyway, so the bundle is the
+ # same. Persist it as automatic so pre-#8050 installs (and the --llama-backend
+ # vulkan every update re-asserts) stay eligible for the CPU crash recovery.
+ persist_backend = "auto" if amd_no_hip_host else "vulkan"
else:
log("Intel GPU detected; installing the Vulkan llama.cpp prebuilt")
persist_backend = None
@@ -6944,6 +6996,9 @@ def install_prebuilt(
# An explicit Vulkan choice only. The Windows-AMD auto-fallback is a rescue
# from a missing HIP arch, so it must keep the CPU plans it can still use.
strict_vulkan = force_vulkan_requested(llama_backend) and not force_cpu and not host.is_macos
+ # Read before the route, which rewrites the host to Vulkan-only and drops the AMD
+ # arch. Kept in the marker so the next update forwards the same --rocm-gfx.
+ persist_rocm_gfx = _active_rocm_gfx_target(host)
host, published_repo, published_release_tag, persist_llama_backend = _route_to_vulkan_prebuilt(
host,
published_repo,
@@ -7045,6 +7100,7 @@ def install_prebuilt(
install_dir,
recorded_ggml_tree(current.approved_checksums, current.attempts[0]),
)
+ sync_marker_rocm_gfx(install_dir, persist_rocm_gfx)
return
with scratch_dir("unsloth-llama-prebuilt-") as work_dir:
probe_path = work_dir / "stories260K.gguf"
@@ -7073,6 +7129,7 @@ def install_prebuilt(
install_dir,
recorded_ggml_tree(plan.approved_checksums, choice),
)
+ sync_marker_rocm_gfx(install_dir, persist_rocm_gfx)
return
log(
"selected "
@@ -7096,6 +7153,7 @@ def install_prebuilt(
# Persist only the deliberate choice, not a transient fallback.
force_cpu = persist_force_cpu,
llama_backend = persist_llama_backend,
+ rocm_gfx = persist_rocm_gfx,
)
except ExistingInstallSatisfied as satisfied:
# Third reuse path: the reinstall was skipped, so
@@ -7104,6 +7162,7 @@ def install_prebuilt(
install_dir,
recorded_ggml_tree(plan.approved_checksums, satisfied.choice),
)
+ sync_marker_rocm_gfx(install_dir, persist_rocm_gfx)
return
except PrebuiltFallback as exc:
if _environment_fatal_reason(exc):