Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: load GGUF on CPU when the auto-selected Vulkan driver hangs or has no device (#14521)
Daniel Han21b0577924a3
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.pyindex 4b6f4a82cf0..811aad00f5c 100644--- a/studio/backend/core/inference/llama_cpp.py+++ b/studio/backend/core/inference/llama_cpp.py@@ -8371,6 +8371,9 @@ def _arm_load_probe_memo() -> None:against VRAM that has since been allocated. `_load_probe_memo_scope` on the loadcall owns the lifetime, so this never has to be unwound by hand."""+ # Already armed this load: keep the rows the launch reuses.+ if _load_probe_memo_armed():+ return_LOAD_PROBE_STATE.armed = True_LOAD_PROBE_STATE.rows = {}@@ -16189,6 +16192,7 @@ class LlamaCppBackend:return _memobinary_dir = _llama_lib_dir(binary)if not _lib_dir_has_ggml_backend(binary_dir, "vulkan"):+ _load_probe_memo_put("vulkan_outcome", binary, "error")_load_probe_memo_put("vulkan", binary, [])return []@@ -16220,12 +16224,24 @@ class LlamaCppBackend:logger.debug(f"vulkan GPU probe exited {result.returncode}: {result.stderr.strip()}")+ # Suspect only, never proof: a driver can fault on exit after listing a device.+ _crashed = LlamaCppBackend._is_signal_crash(result.returncode) or (+ sys.platform == "win32" and LlamaCppBackend._is_abort_exit(result.returncode)+ )+ _load_probe_memo_put("vulkan_outcome", binary, "crashed" if _crashed else "error")_load_probe_memo_put("vulkan", binary, [])return []+ except subprocess.TimeoutExpired as e:+ # Suspect, not absent: a healthy discrete card can take longer than this.+ logger.info(f"vulkan GPU probe timed out: {e}")+ _load_probe_memo_put("vulkan_outcome", binary, "timeout")+ _load_probe_memo_put("vulkan", binary, [])+ return []except Exception as e:logger.debug(f"vulkan GPU probe failed: {e}")# Memoised too: an unanswered probe comes straight back here, so an uncached# timeout is paid twice over and again per rung.+ _load_probe_memo_put("vulkan_outcome", binary, "error")_load_probe_memo_put("vulkan", binary, [])return []@@ -16254,9 +16270,28 @@ class LlamaCppBackend:except ValueError:continuerows.sort(key = lambda r: r["index"])+ if rows:+ _outcome = "devices"+ else:+ # Unparseable output is not proof of zero devices.+ _outcome = "error" if result.stdout.strip() else "none"+ _load_probe_memo_put("vulkan_outcome", binary, _outcome)_load_probe_memo_put("vulkan", binary, rows)return rows+ @staticmethod+ def _vulkan_probe_outcome(binary: Optional[str] = None) -> str:+ """``devices``, ``none`` (enumerated zero), ``timeout``, ``crashed`` or ``error``,+ from this load's probe memo. Unarmed (outside a load) only ``devices`` / ``error``.+ """+ binary = binary or LlamaCppBackend._find_llama_server_binary()+ if not binary:+ return "error"+ if LlamaCppBackend._run_vulkan_probe(binary):+ return "devices"+ outcome = _load_probe_memo_get("vulkan_outcome", binary)+ return outcome if outcome in ("none", "timeout", "crashed") else "error"+@staticmethoddef vulkan_device_inventory(binary: Optional[str] = None) -> list[dict]:"""UI-facing Vulkan device list: the devices llama-server will actually@@ -25634,6 +25669,12 @@ class LlamaCppBackend:return intentif not source_matches and not self.matches_load_source(intent):return intent+ # Decided by this load's own probe: only a zero-device answer takes the CPU route.+ if not source_matches and self._cpu_fallback_reason in (+ "vulkan_no_device",+ "vulkan_startup_stall",+ ):+ return intentextras = 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@@ -25661,6 +25702,7 @@ class LlamaCppBackend:mmproj_has_audio: bool,disable_vision: bool,vision_disabled_by_user: bool,+ reason: str = "vulkan_startup_crash",) -> GgufLoadIntent:intent = self._as_cpu_fallback_intent(intent)self._gpu_memory_mode = intent.gpu_memory_mode@@ -25679,7 +25721,7 @@ class LlamaCppBackend:# disable_vision request then fails runtime matching and reloads the model.self._disable_vision = bool(disable_vision)self._vision_disabled_by_user = bool(vision_disabled_by_user)- self._cpu_fallback_reason = "vulkan_startup_crash"+ self._cpu_fallback_reason = reasonreturn intent@staticmethod@@ -27655,6 +27697,9 @@ class LlamaCppBackend:# `--fit on`, yet `gpu_indices` is restored from `gpu_ids` below# so the pin happens anyway. A pinned uncovered GPU is the user's# call and already reports "device kernel image is invalid".+ # After the download, so the launch reuses fresh rows instead of re-probing (15 s).+ if self._is_vulkan_backend(binary):+ _arm_load_probe_memo()_gpu_mem = self._get_gpu_memory(binary, for_llama_server = not gpu_ids)_held_by_others = self._other_planned_vram_mib()_shared_gpus = frozenset(_held_by_others)@@ -33156,6 +33201,7 @@ class LlamaCppBackend:extra_args,env,)+ _vulkan_suspect = False# 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,@@ -33932,6 +33978,27 @@ class LlamaCppBackend:# Memoed only when the load ends terminally, so a recovering fallback is not blocked._sched_abort_seen = False+ def _vulkan_wait_args(label):+ """(timeout, kwargs) for a health wait: a stuck Vulkan driver burns CPU+ and touches pages forever (#142), so auto-Vulkan launches get a ceiling."""+ timeout = self._HEALTH_STALL_TIMEOUT_S+ if not _cpu_fallback_eligible or intent.cpu_fallback or label == "-cpu":+ return timeout, {}+ per_gib = self._AUTO_VULKAN_START_S_PER_GIB+ floor = timeout+ if _vulkan_suspect and not label:+ timeout = min(timeout, self._SUSPECT_VULKAN_STALL_TIMEOUT_S)+ floor = timeout+ elif not _vulkan_suspect:+ # Listed device: ends with advice only, so CPU work (shader compile) is progress.+ per_gib *= self._LISTED_VULKAN_CEILING_FACTOR+ floor = timeout * self._LISTED_VULKAN_CEILING_FACTOR+ ceiling = (model_size or 0) / (1 << 30) * per_gib+ return timeout, {+ "cpu_counts_as_progress": not _vulkan_suspect,+ "max_total_s": max(floor, ceiling),+ }+def _spawn_and_wait(run_cmd, *, label = ""):"""Start llama-server with run_cmd and wait for health.@@ -34060,8 +34127,11 @@ class LlamaCppBackend:target = self._drain_stdout, daemon = True, name = "llama-stdout")self._stdout_thread.start()+ _wait_timeout, _wait_kwargs = _vulkan_wait_args(label)if self._wait_for_health(- timeout = self._HEALTH_STALL_TIMEOUT_S, cancelled = _load_cancelled+ timeout = _wait_timeout,+ cancelled = _load_cancelled,+ **_wait_kwargs,):if _did_rocm_retry:# Proved on this host: every later child skips the@@ -34356,6 +34426,34 @@ class LlamaCppBackend:self._vram_fraction_pending = Noneraise RuntimeError(detail)+ def _recover_vulkan_stall(stalled_cmd: list[str]) -> bool:+ """A probe that could not enumerate plus no loading work replays on CPU (True+ once up, False if it could not start); any other stall fails with advice."""+ if (+ _vulkan_suspect+ and getattr(self, "_health_wait_stall_kind", None) == "no_progress"+ ):+ return _try_auto_vulkan_cpu_fallback(stalled_cmd, None, stalled = True)+ _why = (+ "startup time limit reached"+ if getattr(self, "_health_wait_stall_kind", None) == "ceiling"+ else "no loading progress"+ )+ _raise_terminal_load_failure(+ "llama-server did not finish starting on the auto-selected Vulkan "+ f"backend ({_why}). If this keeps happening, choose CPU "+ "in Settings > GGUF inference engine to run models without the "+ "Vulkan driver."+ )++ def _vulkan_stall_pending() -> bool:+ return (+ getattr(self, "_health_wait_stalled", False)+ and _cpu_fallback_eligible+ and not intent.cpu_fallback+ and not _load_cancelled()+ )+def _cleanup_cancelled_load(message: str) -> None:logger.info(message)self._cleanup_failed_cpu_fallback()@@ -34374,12 +34472,15 @@ class LlamaCppBackend:failed_rc: Optional[int],*,terminal: bool = True,+ stalled: bool = False,) -> 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.+ worth replaying. ``stalled`` replays a child that never became+ healthy and made no loading progress (already reaped by the+ caller), the hang a crash gate cannot see."""nonlocal intent, gpu_memory_mode, gpu_layers, n_cpu_moenonlocal _replay_pageable_override@@ -34387,8 +34488,9 @@ class LlamaCppBackend:# 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)+ _crashed = stalled or (+ 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 _load_cancelled():return False@@ -34423,8 +34525,9 @@ class LlamaCppBackend:_cpu_pageable_note = _cpu_pageable_note or _replay_pageable_overridelogger.warning(- "The auto-selected Vulkan backend hard-crashed during "- "startup; retrying once with llama.cpp devices disabled."+ "The auto-selected Vulkan backend %s during startup; "+ "retrying once with llama.cpp devices disabled.",+ "stopped making progress" if stalled else "hard-crashed",)if not _spawn_and_wait(replay, label = "-cpu"):if _finish_cancelled_health_wait(@@ -34471,6 +34574,7 @@ class LlamaCppBackend:self._record_memory_state(_last_spawn_cmd, env)intent = self._apply_cpu_fallback_state(intent,+ reason = "vulkan_startup_stall" if stalled else "vulkan_startup_crash",is_vision = fallback_has_mmproj,mmproj_has_audio = (_launched_mmproj_has_audio if fallback_has_mmproj else False@@ -34512,8 +34616,9 @@ class LlamaCppBackend:self._mtp_draft_suppressed_reason = _suppressed_draft_reasonlogger.warning("llama-server loaded successfully on CPU after the "- "auto-selected Vulkan backend crashed. GPU acceleration "- "is disabled for this model session."+ "auto-selected Vulkan backend %s. GPU acceleration "+ "is disabled for this model session.",+ "stalled" if stalled else "crashed",)return True@@ -34632,6 +34737,26 @@ class LlamaCppBackend:else:self._record_load_warning(_cuda_ctx_notice)+ # Zero Vulkan devices: the bundle would still init a driver that can hang (#7213).+ _cpu_route_reason = None+ if not intent.cpu_fallback and _cpu_fallback_eligible:+ _vk_outcome = self._vulkan_probe_outcome(binary)+ _vulkan_suspect = _vk_outcome in ("timeout", "crashed")+ # Only when a replay can be built, so the block below never fails the load.+ if (+ _vk_outcome == "none"+ and self._cpu_isolated_replay(cmd, dict(env), server_caps) is not None+ and self._cpu_isolated_binary(binary) is not None+ ):+ logger.warning(+ "The auto-selected Vulkan backend has no usable device "+ "(probe: %s); starting llama.cpp on CPU without loading the "+ "Vulkan runtime.",+ _vk_outcome,+ )+ intent = replace(intent, cpu_fallback = True)+ _cpu_route_reason = "vulkan_no_device"+# 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@@ -34695,6 +34820,11 @@ class LlamaCppBackend:vision_disabled_by_user = bool(is_vision and disable_vision and _dv_dropped_image_projector),+ reason = (+ _cpu_route_reason+ or self._cpu_fallback_reason+ or "vulkan_startup_crash"+ ),)gpu_memory_mode = intent.gpu_memory_modegpu_layers = intent.gpu_layers@@ -34734,6 +34864,16 @@ class LlamaCppBackend:"Load cancelled during the llama-server health wait"):return False+ # Stalled auto-Vulkan launch (#142): every rung below relaunches the same driver.+ if not healthy and _vulkan_stall_pending():+ _stalled_cmd = list(_last_spawn_cmd)+ self._kill_process()+ if _recover_vulkan_stall(_stalled_cmd):+ healthy = True+ elif _finish_cancelled_health_wait(+ "Load cancelled during the CPU replay health wait"+ ):+ return False# #6415 split-mode tensor warmup abort. Latch it on THIS first spawn:# the flash-attn-off retry below can't run tensor (needs flash_attn),# so its output drops the marker and recording later would miss it,@@ -35579,6 +35719,17 @@ class LlamaCppBackend:)extra_args = _fb_stripped_extras+ # A stalled later retry: a live child has no exit code for the crash gate.+ if not healthy and _vulkan_stall_pending():+ _stalled_cmd = list(_last_spawn_cmd)+ self._kill_process()+ if _recover_vulkan_stall(_stalled_cmd):+ healthy = True+ elif _finish_cancelled_health_wait(+ "Load cancelled during the CPU replay health wait"+ ):+ return False+# Keep a multimodal model multimodal when only its GPU projector# placement fails. llama.cpp owns mmproj offload separately from# --gpu-layers, so retry it on CPU before removing --mmproj.@@ -35745,8 +35896,11 @@ class LlamaCppBackend:# the old child the teardown is clearing._cleanup_cancelled_load("App shut down during the text-only retry")return False+ _textonly_timeout, _textonly_kwargs = _vulkan_wait_args("-textonly")if self._wait_for_health(- timeout = self._HEALTH_STALL_TIMEOUT_S, cancelled = _load_cancelled+ timeout = _textonly_timeout,+ cancelled = _load_cancelled,+ **_textonly_kwargs,):healthy = True# The child that serves this session never read the@@ -35781,10 +35935,22 @@ class LlamaCppBackend:"Load cancelled during the text-only retry health wait"):return False+ if _vulkan_stall_pending():+ if _recover_vulkan_stall(+ _last_spawn_cmd if _projector_msg else _vision_gpu_cmd+ ):+ healthy = True+ # The replay carries the original vision argv, as below.+ if not _projector_msg:+ self._mmproj_fallback_reason = None+ elif _finish_cancelled_health_wait(+ "Load cancelled during the CPU replay health wait"+ ):+ return False# 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):+ if not healthy and self._is_signal_crash(_retry_rc):_cpu_replay_cmd = (_last_spawn_cmd if _projector_msg else _vision_gpu_cmd)@@ -39157,6 +39323,12 @@ class LlamaCppBackend:# Extend the health deadline while startup work continues._HEALTH_STALL_TIMEOUT_S = 600.0+ # First auto-Vulkan launch after the probe timed out or faulted.+ _SUSPECT_VULKAN_STALL_TIMEOUT_S = 300.0+ # Unrenewable auto-Vulkan ceiling per GiB of model (never below the stall window).+ _AUTO_VULKAN_START_S_PER_GIB = 60.0+ # The ceiling's multiple when the probe listed a device (that stall ends with advice only).+ _LISTED_VULKAN_CEILING_FACTOR = 3.0_STARTUP_PROGRESS_SAMPLE_S = 5.0# Ignore activity from the health probes themselves._STARTUP_PROGRESS_MIN_BYTES = 1 << 20@@ -39213,14 +39385,21 @@ class LlamaCppBackend:@classmethoddef _made_startup_progress(- cls, before: tuple[float, int, int, int], after: tuple[float, int, int, int], elapsed: float+ cls,+ before: tuple[float, int, int, int],+ after: tuple[float, int, int, int],+ elapsed: float,+ cpu_counts: bool = True,) -> bool:# RSS is a high-water mark so evicted pages are not counted twice.return (after[1] - before[1] >= cls._STARTUP_PROGRESS_MIN_BYTESor after[2] - before[2] >= cls._STARTUP_PROGRESS_MIN_BYTESor after[3] - before[3] >= cls._STARTUP_PROGRESS_MIN_PAGE_FAULTS- or after[0] - before[0] >= cls._STARTUP_PROGRESS_MIN_CPU_FRACTION * elapsed+ or (+ cpu_counts+ and after[0] - before[0] >= cls._STARTUP_PROGRESS_MIN_CPU_FRACTION * elapsed+ ))def _wait_for_health(@@ -39228,9 +39407,20 @@ class LlamaCppBackend:timeout: float = 120.0,interval: float = 0.5,cancelled: Optional[Callable[[], bool]] = None,+ cpu_counts_as_progress: bool = True,+ max_total_s: Optional[float] = None,) -> bool:- """Poll /health until success, exit, cancellation, or a startup stall."""+ """Poll /health until success, exit, cancellation, or a startup stall.++ ``cpu_counts_as_progress`` False renews only on loading work (RSS, reads, faults):+ a spinning GPU driver burns CPU forever (#142). ``max_total_s`` caps the whole wait.+ """deadline = time.monotonic() + timeout+ ceiling = deadline - timeout + max_total_s if max_total_s is not None else None+ self._health_wait_stalled = False+ # "no_progress" (the stall window passed with no loading work) or "ceiling".+ self._health_wait_stall_kind = None+ clipped_by_ceiling = Falsework_sample = Nonework_sampled_at = Nonework_checked_at = None@@ -39306,9 +39496,15 @@ class LlamaCppBackend:sample = self._startup_work_sample(process)if sample is not None:if work_sample is not None and self._made_startup_progress(- work_sample, sample, now - work_sampled_at+ work_sample,+ sample,+ now - work_sampled_at,+ cpu_counts = cpu_counts_as_progress,):deadline = now + timeout+ if ceiling is not None and deadline > ceiling:+ deadline = ceiling+ clipped_by_ceiling = Truepeak = sample[1] if work_sample is None else max(work_sample[1], sample[1])work_sample = (sample[0], peak, sample[2], sample[3])work_sampled_at = now@@ -39360,12 +39556,28 @@ class LlamaCppBackend:self._health_wait_cancelled = Truereturn False+ # Exited during the last probe or interval: a crash for the crash recovery, not a stall.+ if process is not None and process.poll() is not None:+ if self._stdout_thread is not None:+ self._stdout_thread.join(timeout = 2)+ logger.error(+ f"llama-server exited with code {process.returncode} at the health-check deadline. "+ f"Output (tail): {chr(10).join(self._stdout_lines[-50:])[-2000:]}"+ )+ return False+# Leave a marker so _classify_llama_start_failure tells a live but# never-healthy load (too large, or a proxy hijacking the loopback# probe) apart from a bad GGUF (#5740).marker = f"llama-server health check timed out: no startup progress for {timeout:g}s"+ stall_kind = "no_progress"+ if clipped_by_ceiling:+ marker = f"llama-server health check timed out: not healthy after {max_total_s:g}s"+ stall_kind = "ceiling"self._stdout_lines.append(marker)logger.error(marker)+ self._health_wait_stalled = True+ self._health_wait_stall_kind = stall_kindreturn False@staticmethoddiff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.pyindex fdf7b443a81..25b796ca898 100644--- a/studio/backend/models/inference.py+++ b/studio/backend/models/inference.py@@ -1981,12 +1981,17 @@ class _InferenceRuntimeFields(BaseModel):"deliberate placement can arrive with gpu_memory_mode still 'auto'."),)- cpu_fallback_reason: Optional[Literal["vulkan_startup_crash"]] = Field(+ cpu_fallback_reason: Optional[+ Literal["vulkan_startup_crash", "vulkan_startup_stall", "vulkan_no_device"]+ ] = 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."+ "hard-crashed and the same launch became healthy with GPU devices disabled. "+ "'vulkan_startup_stall' means that launch stopped making startup progress. "+ "'vulkan_no_device' means the Vulkan probe found no usable device, so the "+ "load started on CPU without initialising the Vulkan runtime."),)diff --git a/studio/backend/tests/test_gpu_init_crash_message.py b/studio/backend/tests/test_gpu_init_crash_message.pyindex 5d0eb7306e6..d175108beaa 100644--- a/studio/backend/tests/test_gpu_init_crash_message.py+++ b/studio/backend/tests/test_gpu_init_crash_message.py@@ -103,7 +103,13 @@ def _run_cpu_fallback_load(cancel_in_prepare = False,platform = None,sink = None,+ stall_launches = (),+ stall_kind = "no_progress",+ gpu_memory = None,):+ """``stall_launches``: 0-based launch indexes whose child stays alive while the+ health wait reports a startup stall (a hung driver rather than a crash), ended+ the way ``stall_kind`` says (``no_progress`` or ``ceiling``)."""if platform is not None:monkeypatch.setattr(llama_cpp.sys, "platform", platform)@@ -118,7 +124,11 @@ def _run_cpu_fallback_load(mmproj.write_bytes(b"projector")backend = LlamaCppBackend()- backend._get_gpu_memory = lambda _binary = None, **_kw: []+ backend._get_gpu_memory = (+ (lambda _binary = None, **_kw: [])+ if gpu_memory is None+ else (lambda _binary = None, **_kw: gpu_memory(backend, _binary, **_kw))+ )backend._get_gpu_free_memory = lambda _binary = None, **_kw: []backend._read_gguf_metadata = lambda _path: Nonebackend._can_estimate_kv = lambda: False@@ -155,6 +165,8 @@ def _run_cpu_fallback_load(launches = []fallback_sources = []+ health_kwargs = []+ health_timeouts = []class _Process:pid = 123@@ -181,10 +193,18 @@ def _run_cpu_fallback_load(return _Process(returncodes[index])def _wait_for_health(timeout, **_kw):+ health_kwargs.append(dict(_kw))+ health_timeouts.append(timeout)+ backend._health_wait_stalled = False+ backend._health_wait_stall_kind = Noneif 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()+ if len(launches) - 1 in stall_launches:+ backend._health_wait_stalled = True+ backend._health_wait_stall_kind = stall_kind+ return Falsereturn returncodes[len(launches) - 1] is Nonecleanups = []@@ -210,8 +230,13 @@ def _run_cpu_fallback_load(sink["launches"] = launchessink["fallback_sources"] = fallback_sourcessink["cleanups"] = cleanups+ sink["health_kwargs"] = health_kwargs+ sink["health_timeouts"] = health_timeoutsif resident_fallback:- backend._cpu_fallback_reason = "vulkan_startup_crash"+ # A string seeds that reason; True keeps the crash it always meant.+ backend._cpu_fallback_reason = (+ resident_fallback if isinstance(resident_fallback, str) else "vulkan_startup_crash"+ )loaded = backend.load_model(GgufLoadIntent(diff --git a/studio/backend/tests/test_vulkan_no_device_cpu_route.py b/studio/backend/tests/test_vulkan_no_device_cpu_route.pynew file mode 100644index 00000000000..6ca00a98236--- /dev/null+++ b/studio/backend/tests/test_vulkan_no_device_cpu_route.py@@ -0,0 +1,725 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""An auto-selected Vulkan bundle on a host whose driver cannot answer (#142).++Two paths reach the staged CPU runtime without a crash: the Vulkan probe completed+and listed no device, or the probe could not enumerate (timed out or faulted) and the+first Vulkan child then did no loading work for the whole stall window. A stall after+a probe that listed a device fails with advice instead: it does not prove the GPU+unusable. Nothing is remembered across loads.+"""++from __future__ import annotations++import subprocess+import sys+from types import SimpleNamespace++import pytest++from .test_gpu_init_crash_message import ( # noqa: F401 (stubs loggers on import)+ _run_cpu_fallback_load,+)+from core.inference import llama_cpp+from core.inference.llama_cpp import LlamaCppBackend+from models.inference import LoadResponse+++def _probe_dir(tmp_path):+ bindir = tmp_path / "bin"+ bindir.mkdir()+ binary = bindir / "llama-server"+ binary.write_bytes(b"binary")+ # The name _lib_dir_has_ggml_backend looks for on this platform.+ (bindir / ("ggml-vulkan.dll" if sys.platform == "win32" else "libggml-vulkan.so")).write_bytes(+ b"vulkan"+ )+ return str(binary)+++def _outcome(monkeypatch, tmp_path, run):+ binary = _probe_dir(tmp_path)+ monkeypatch.setattr(llama_cpp.subprocess, "run", run)+ with llama_cpp._load_probe_memo_scope():+ llama_cpp._arm_load_probe_memo()+ rows = LlamaCppBackend._run_vulkan_probe(binary)+ outcome = LlamaCppBackend._vulkan_probe_outcome(binary)+ return rows, outcome+++def _completed(returncode, stdout = ""):+ return lambda *a, **k: SimpleNamespace(returncode = returncode, stdout = stdout, stderr = "")+++def test_zero_enumerated_devices_reads_none(monkeypatch, tmp_path):+ assert _outcome(monkeypatch, tmp_path, _completed(0, "")) == ([], "none")+++def test_listed_device_reads_devices(monkeypatch, tmp_path):+ line = "0\t1073741824\t1\t2147483648\tIntel(R) HD Graphics 530\t1"+ rows, outcome = _outcome(monkeypatch, tmp_path, _completed(0, line))+ assert outcome == "devices"+ assert rows[0]["name"] == "Intel(R) HD Graphics 530"+++def test_timeout_reads_timeout(monkeypatch, tmp_path):+ def _hang(*a, **k):+ raise subprocess.TimeoutExpired(cmd = "probe", timeout = 15)++ assert _outcome(monkeypatch, tmp_path, _hang) == ([], "timeout")++[email protected]("rc", [-11, 0xC0000005])+def test_driver_fault_reads_crashed(monkeypatch, tmp_path, rc):+ assert _outcome(monkeypatch, tmp_path, _completed(rc)) == ([], "crashed")+++def test_ordinary_failure_reads_error(monkeypatch, tmp_path):+ assert _outcome(monkeypatch, tmp_path, _completed(1)) == ([], "error")+++def test_unparseable_output_is_not_zero_devices(monkeypatch, tmp_path):+ assert _outcome(monkeypatch, tmp_path, _completed(0, "garbage")) == ([], "error")+++def test_outcome_outside_a_load_never_claims_no_device(monkeypatch, tmp_path):+ """Unarmed memo: nothing recorded, so nothing acts on it."""+ binary = _probe_dir(tmp_path)+ monkeypatch.setattr(llama_cpp.subprocess, "run", _completed(0, ""))+ assert LlamaCppBackend._run_vulkan_probe(binary) == []+ assert LlamaCppBackend._vulkan_probe_outcome(binary) == "error"+++def _route_env(monkeypatch, outcome):+ monkeypatch.setattr(+ LlamaCppBackend, "_binary_revision", staticmethod(lambda _binary: ("rev", 1))+ )+ monkeypatch.setattr(+ LlamaCppBackend, "_vulkan_probe_outcome", staticmethod(lambda _binary = None: outcome)+ )+ monkeypatch.setattr(+ LlamaCppBackend, "_cpu_isolated_binary", lambda self, _binary: "/staged/llama-server"+ )+++def test_no_usable_device_starts_on_the_cpu_runtime(monkeypatch, tmp_path):+ _route_env(monkeypatch, "none")+ sink = {}+ backend, loaded, launches, fallback_sources = _run_cpu_fallback_load(+ monkeypatch, tmp_path, returncodes = [None], sink = sink+ )+ assert loaded is True+ assert len(launches) == 1+ assert launches[0][0][0] == "/staged/llama-server"+ assert len(fallback_sources) == 1+ assert backend._cpu_fallback_reason == "vulkan_no_device"+ assert backend._gpu_memory_mode == "manual" and backend._gpu_layers == 0+ # The CPU child keeps the ordinary progress rule.+ assert sink["health_kwargs"][0].get("cpu_counts_as_progress", True) is True++[email protected]("outcome", ["devices", "error", "timeout", "crashed"])+def test_a_listed_device_or_unproven_probe_keeps_vulkan(monkeypatch, tmp_path, outcome):+ """A timed-out probe is not proof: a healthy discrete card can be that slow, and a+ driver can fault on exit after listing a working device."""+ _route_env(monkeypatch, outcome)+ sink = {}+ backend, loaded, launches, fallback_sources = _run_cpu_fallback_load(+ monkeypatch, tmp_path, returncodes = [None], sink = sink+ )+ assert loaded is True+ assert launches[0][0][0] == "/fake/llama-server"+ assert fallback_sources == []+ assert backend._cpu_fallback_reason is None+ # Suspect only after a timeout or a fault: the shorter stall window.+ expected = (+ min(+ LlamaCppBackend._HEALTH_STALL_TIMEOUT_S,+ LlamaCppBackend._SUSPECT_VULKAN_STALL_TIMEOUT_S,+ )+ if outcome in ("timeout", "crashed")+ else LlamaCppBackend._HEALTH_STALL_TIMEOUT_S+ )+ assert sink["health_timeouts"][0] == expected+ # Every Vulkan launch of an eligible load is capped, renewals included.+ assert sink["health_kwargs"][0]["max_total_s"] >= expected+ # Only a suspect probe stops CPU work from renewing the stall window.+ assert sink["health_kwargs"][0]["cpu_counts_as_progress"] is (+ outcome not in ("timeout", "crashed")+ )+ if outcome not in ("timeout", "crashed"):+ # That stall only ever fails with advice: a slow disk gets three times the room.+ assert sink["health_kwargs"][0]["max_total_s"] >= (+ expected * LlamaCppBackend._LISTED_VULKAN_CEILING_FACTOR+ )+++def test_a_lowered_stall_window_still_governs_a_suspect_launch(monkeypatch, tmp_path):+ _route_env(monkeypatch, "timeout")+ monkeypatch.setattr(LlamaCppBackend, "_HEALTH_STALL_TIMEOUT_S", 60.0)+ sink = {}+ _run_cpu_fallback_load(monkeypatch, tmp_path, returncodes = [None], sink = sink)+ assert sink["health_timeouts"][0] == 60.0++[email protected]("outcome", ["timeout", "crashed"])+def test_a_hung_suspect_launch_replays_on_cpu(monkeypatch, tmp_path, outcome):+ _route_env(monkeypatch, outcome)+ sink = {}+ backend, loaded, launches, fallback_sources = _run_cpu_fallback_load(+ monkeypatch, tmp_path, returncodes = [None, None], stall_launches = (0,), sink = sink+ )+ assert loaded is True+ assert len(launches) == 2+ assert backend._cpu_fallback_reason == "vulkan_startup_stall"+ assert sink["health_timeouts"][0] == LlamaCppBackend._SUSPECT_VULKAN_STALL_TIMEOUT_S+ assert sink["health_timeouts"][1] == LlamaCppBackend._HEALTH_STALL_TIMEOUT_S+++def test_a_user_chosen_vulkan_install_is_not_routed(monkeypatch, tmp_path):+ """A Vulkan bundle picked in Settings is not auto-selected, so not eligible.++ The helper forces auto-selection True, so the eligibility gate it feeds is+ what this patches (the marker reading itself is covered elsewhere)."""+ _route_env(monkeypatch, "none")+ monkeypatch.setattr(+ LlamaCppBackend,+ "_auto_vulkan_cpu_fallback_eligible",+ classmethod(lambda cls, *a, **k: False),+ )+ backend, loaded, launches, fallback_sources = _run_cpu_fallback_load(+ monkeypatch, tmp_path, returncodes = [None]+ )+ assert loaded is True+ assert launches[0][0][0] == "/fake/llama-server"+ assert fallback_sources == []+ assert backend._cpu_fallback_reason is None+++def test_explicit_device_placement_is_not_routed(monkeypatch, tmp_path):+ _route_env(monkeypatch, "none")+ backend, loaded, launches, fallback_sources = _run_cpu_fallback_load(+ monkeypatch, tmp_path, returncodes = [None], extra_args = ["--device", "Vulkan0"]+ )+ assert loaded is True+ assert launches[0][0][0] == "/fake/llama-server"+ assert fallback_sources == []+ assert backend._cpu_fallback_reason is None+++def test_no_cpu_library_to_stage_keeps_vulkan(monkeypatch, tmp_path):+ monkeypatch.setattr(+ LlamaCppBackend, "_vulkan_probe_outcome", staticmethod(lambda _binary = None: "none")+ )+ monkeypatch.setattr(LlamaCppBackend, "_cpu_isolated_binary", lambda self, _binary: None)+ backend, loaded, launches, fallback_sources = _run_cpu_fallback_load(+ monkeypatch, tmp_path, returncodes = [None]+ )+ assert loaded is True+ assert launches[0][0][0] == "/fake/llama-server"+ assert backend._cpu_fallback_reason is None+++def test_a_reload_keeps_the_no_device_reason(monkeypatch, tmp_path):+ _route_env(monkeypatch, "devices")+ backend, loaded, launches, _ = _run_cpu_fallback_load(+ monkeypatch,+ tmp_path,+ returncodes = [None],+ cpu_fallback = True,+ resident_fallback = "vulkan_no_device",+ )+ assert loaded is True+ assert launches[0][0][0] == "/staged/llama-server"+ assert backend._cpu_fallback_reason == "vulkan_no_device"++[email protected]("outcome", ["devices", "error"])+def test_a_stall_after_a_listed_device_fails_without_a_cpu_replay(monkeypatch, tmp_path, outcome):+ """The probe saw a working device, so a slow start is not proof of a broken driver:+ no CPU replay, no relaunch into the same hang, and the error points at Settings."""+ _route_env(monkeypatch, outcome)+ sink = {}+ with pytest.raises(+ RuntimeError, match = r"no loading progress\)\. .*Settings > GGUF inference engine"+ ):+ _run_cpu_fallback_load(+ monkeypatch,+ tmp_path,+ returncodes = [None, None],+ stall_launches = (0,),+ sink = sink,+ )+ assert [argv[0] for argv, _env in sink["launches"]] == ["/fake/llama-server"]+ assert sink["fallback_sources"] == []+ # A listed device counts CPU work (a first shader compile); the ceiling ends a spinning driver.+ assert sink["health_kwargs"][0]["cpu_counts_as_progress"] is True+++def test_a_suspect_launch_cut_off_by_the_ceiling_fails_without_a_cpu_replay(monkeypatch, tmp_path):+ """Still loading when the ceiling hit: that is progress, not a dead driver."""+ _route_env(monkeypatch, "timeout")+ sink = {}+ with pytest.raises(+ RuntimeError, match = r"startup time limit reached\)\. .*Settings > GGUF inference engine"+ ):+ _run_cpu_fallback_load(+ monkeypatch,+ tmp_path,+ returncodes = [None, None],+ stall_launches = (0,),+ stall_kind = "ceiling",+ sink = sink,+ )+ assert len(sink["launches"]) == 1+ assert sink["fallback_sources"] == []+++def test_a_recovered_stall_is_not_remembered(monkeypatch, tmp_path):+ """The next load re-probes and launches Vulkan again; one bad start never pins a+ build to CPU."""+ _route_env(monkeypatch, "timeout")+ (tmp_path / "a").mkdir()+ (tmp_path / "b").mkdir()+ first, loaded, launches, _ = _run_cpu_fallback_load(+ monkeypatch, tmp_path / "a", returncodes = [None, None], stall_launches = (0,)+ )+ assert loaded is True+ assert first._cpu_fallback_reason == "vulkan_startup_stall"+ _route_env(monkeypatch, "devices")+ backend, loaded, launches, fallback_sources = _run_cpu_fallback_load(+ monkeypatch, tmp_path / "b", returncodes = [None]+ )+ assert loaded is True+ assert len(launches) == 1+ assert launches[0][0][0] == "/fake/llama-server"+ assert fallback_sources == []+ assert backend._cpu_fallback_reason is None+++def test_a_stalled_cpu_replay_is_terminal(monkeypatch, tmp_path):+ _route_env(monkeypatch, "timeout")+ sink = {}+ with pytest.raises(RuntimeError):+ _run_cpu_fallback_load(+ monkeypatch,+ tmp_path,+ returncodes = [None] * 6,+ stall_launches = tuple(range(6)),+ sink = sink,+ )+ # One Vulkan launch, one CPU replay, nothing after.+ assert [argv[0] for argv, _env in sink["launches"]] == [+ "/fake/llama-server",+ "/staged/llama-server",+ ]+ assert len(sink["fallback_sources"]) == 1+++def test_the_text_only_retry_is_bounded_too(monkeypatch, tmp_path):+ """The projector recovery starts its text-only child outside _spawn_and_wait."""+ _route_env(monkeypatch, "devices")+ sink = {}+ backend, loaded, launches, _ = _run_cpu_fallback_load(+ monkeypatch,+ tmp_path,+ returncodes = [1, None],+ first_output = "projector-incompatible",+ mmproj_from_argv = True,+ sink = sink,+ )+ assert loaded is True+ assert "--mmproj" not in launches[1][0]+ assert sink["health_kwargs"][1]["cpu_counts_as_progress"] is True+ assert "max_total_s" in sink["health_kwargs"][1]+++def test_a_stall_on_a_non_vulkan_runtime_keeps_cpu_progress(monkeypatch, tmp_path):+ _route_env(monkeypatch, "devices")+ sink = {}+ with pytest.raises(RuntimeError):+ _run_cpu_fallback_load(+ monkeypatch,+ tmp_path,+ # Whatever rungs a stall reaches on another backend respawn and fail.+ returncodes = [None] + [1] * 8,+ stall_launches = (0,),+ vulkan = False,+ sink = sink,+ )+ assert sink["fallback_sources"] == []+ assert sink["health_kwargs"][0].get("cpu_counts_as_progress", True) is True+++def test_a_stall_with_explicit_placement_does_not_replay(monkeypatch, tmp_path):+ _route_env(monkeypatch, "devices")+ sink = {}+ with pytest.raises(RuntimeError):+ _run_cpu_fallback_load(+ monkeypatch,+ tmp_path,+ returncodes = [None],+ stall_launches = (0,),+ extra_args = ["--device", "Vulkan0"],+ sink = sink,+ )+ assert sink["fallback_sources"] == []+ assert sink["health_kwargs"][0].get("cpu_counts_as_progress", True) is True+++def test_a_cancel_during_the_stall_never_spawns_the_replay(monkeypatch, tmp_path):+ _route_env(monkeypatch, "devices")+ sink = {}+ with pytest.raises(RuntimeError):+ _run_cpu_fallback_load(+ monkeypatch,+ tmp_path,+ returncodes = [None, None],+ stall_launches = (0,),+ cancel_after = 1,+ sink = sink,+ )+ assert len(sink["launches"]) == 1+ assert sink["fallback_sources"] == []+++class _Clock:+ def __init__(self):+ self.now = 0.0++ def monotonic(self):+ return self.now+++def _wait(+ monkeypatch,+ *,+ cpu_counts,+ rss_growth = 0,+ max_total_s = None,+ healthy_at = None,+):+ """A live child that burns CPU (and optionally allocates); returns whether the+ wait gave up."""+ clock = _Clock()+ monkeypatch.setattr(llama_cpp.time, "monotonic", clock.monotonic)++ class _Event:+ def clear(self):+ pass++ def wait(self, interval):+ clock.now += interval++ def _no_server(*a, **k):+ if healthy_at is not None and clock.now >= healthy_at:+ return SimpleNamespace(status_code = 200)+ raise llama_cpp.httpx.ConnectError("refused")++ monkeypatch.setattr(llama_cpp.httpx, "get", _no_server)+ cpu = {"t": 0.0}++ def _sample(cls, _process):+ # Half a core of CPU per second, RSS growing by ``rss_growth`` per second.+ cpu["t"] = clock.now * 0.5+ return (cpu["t"], (100 << 20) + int(clock.now * rss_growth), 0, 0)++ monkeypatch.setattr(LlamaCppBackend, "_startup_work_sample", classmethod(_sample))+ backend = LlamaCppBackend()+ backend._process = SimpleNamespace(poll = lambda: None, pid = 1)+ backend._health_probe_event = _Event()+ backend._stdout_lines = []+ backend._cancel_event = None+ healthy = backend._wait_for_health(+ timeout = 30.0,+ interval = 1.0,+ cancelled = lambda: clock.now > 600,+ cpu_counts_as_progress = cpu_counts,+ **({"max_total_s": max_total_s} if max_total_s is not None else {}),+ )+ return healthy, clock.now, backend+++def test_cpu_only_activity_does_not_renew_a_flagged_wait(monkeypatch):+ healthy, elapsed, backend = _wait(monkeypatch, cpu_counts = False)+ assert healthy is False+ assert backend._health_wait_stalled is True+ assert elapsed < 60+++def test_cpu_only_activity_still_renews_the_default_wait(monkeypatch):+ healthy, elapsed, backend = _wait(monkeypatch, cpu_counts = True)+ assert healthy is False+ assert backend._health_wait_stalled is False+ assert elapsed > 600+++def test_a_driver_that_keeps_allocating_still_hits_the_ceiling(monkeypatch):+ """Shader compilation touches fresh pages, so RSS alone renews the stall window;+ only the ceiling ends it."""+ healthy, elapsed, backend = _wait(+ monkeypatch, cpu_counts = False, rss_growth = 1 << 20, max_total_s = 120.0+ )+ assert healthy is False+ assert backend._health_wait_stalled is True+ assert 120 <= elapsed < 130+ assert "not healthy after 120s" in backend._stdout_lines[-1]+ assert backend._health_wait_stall_kind == "ceiling"++[email protected]("max_total_s", [None, 30.0, 120.0])+def test_a_child_doing_no_loading_work_reads_no_progress(monkeypatch, max_total_s):+ """Including a ceiling no longer than the window: nothing renewed, so it never cut+ anything off."""+ healthy, elapsed, backend = _wait(monkeypatch, cpu_counts = False, max_total_s = max_total_s)+ assert healthy is False+ assert backend._health_wait_stalled is True+ assert backend._health_wait_stall_kind == "no_progress"+++def test_a_slow_but_loading_child_comes_up_on_its_device(monkeypatch):+ """Loading work renews the window well past it, so a slow healthy start is not a stall."""+ healthy, elapsed, backend = _wait(+ monkeypatch, cpu_counts = False, rss_growth = 1 << 20, max_total_s = 600.0, healthy_at = 200+ )+ assert healthy is True+ assert 200 <= elapsed < 210+ assert backend._health_wait_stalled is False+ assert backend._health_wait_stall_kind is None+++def test_an_allocating_child_without_a_ceiling_keeps_renewing(monkeypatch):+ healthy, elapsed, backend = _wait(monkeypatch, cpu_counts = False, rss_growth = 1 << 20)+ assert backend._health_wait_stalled is False+ assert elapsed > 600+++def test_loading_progress_renews_a_flagged_wait():+ before = (0.0, 100 << 20, 0, 0)+ assert LlamaCppBackend._made_startup_progress(+ before, (0.0, 200 << 20, 0, 0), 5.0, cpu_counts = False+ )+ assert not LlamaCppBackend._made_startup_progress(+ before, (5.0, 100 << 20, 0, 0), 5.0, cpu_counts = False+ )+ assert LlamaCppBackend._made_startup_progress(before, (5.0, 100 << 20, 0, 0), 5.0)++[email protected]("reason", ["vulkan_no_device", "vulkan_startup_stall"])+def test_response_accepts_the_new_reasons(reason):+ response = LoadResponse(+ status = "loaded",+ model = "m",+ display_name = "m",+ inference = {},+ cpu_fallback_reason = reason,+ )+ assert response.model_dump()["cpu_fallback_reason"] == reason+++def test_a_child_exiting_at_the_deadline_is_a_crash_not_a_stall(monkeypatch):+ """Exited during the last probe: the crash recovery decides, the stall branch must not."""+ clock = _Clock()+ monkeypatch.setattr(llama_cpp.time, "monotonic", clock.monotonic)+ polls = {"n": 0}++ class _Event:+ def clear(self):+ pass++ def wait(self, interval):+ clock.now += interval++ def _poll():+ # Alive for every in-loop check, gone by the deadline re-check.+ polls["n"] += 1+ return None if clock.now < 30.0 else -11++ monkeypatch.setattr(+ llama_cpp.httpx,+ "get",+ lambda *a, **k: (_ for _ in ()).throw(llama_cpp.httpx.ConnectError("refused")),+ )+ monkeypatch.setattr(+ LlamaCppBackend, "_startup_work_sample", classmethod(lambda cls, p: (0.0, 100 << 20, 0, 0))+ )+ backend = LlamaCppBackend()+ backend._process = SimpleNamespace(poll = _poll, pid = 1, returncode = -11)+ backend._health_probe_event = _Event()+ backend._stdout_lines = []+ backend._cancel_event = None+ healthy = backend._wait_for_health(+ timeout = 30.0, interval = 30.0, cancelled = lambda: False, cpu_counts_as_progress = False+ )+ assert healthy is False+ assert backend._health_wait_stalled is False++[email protected]("reason", ["vulkan_no_device", "vulkan_startup_stall"])+def test_a_reload_after_a_vulkan_cpu_route_leaves_the_decision_to_its_own_probe(+ monkeypatch, tmp_path, reason+):+ """No probe here: the load's single memoised probe decides, so a hung driver costs one+ timeout and a device that appeared since is seen."""+ from core.inference.llama_cpp import GgufLoadIntent++ gguf = tmp_path / "model.gguf"+ gguf.write_bytes(b"GGUF")+ backend = LlamaCppBackend()+ backend._process = SimpleNamespace(poll = lambda: None)+ backend._healthy = True+ backend._model_identifier = "owner/model"+ backend._gguf_path = str(gguf)+ backend._cpu_fallback_reason = reason+ probes = []+ monkeypatch.setattr(LlamaCppBackend, "matches_load_source", lambda self, intent: True)+ monkeypatch.setattr(+ LlamaCppBackend, "_find_llama_server_binary", staticmethod(lambda: "/fake/llama-server")+ )+ monkeypatch.setattr(+ LlamaCppBackend,+ "_run_vulkan_probe",+ staticmethod(lambda binary: probes.append(binary) or []),+ )+ monkeypatch.setattr(+ LlamaCppBackend,+ "_vulkan_probe_outcome",+ staticmethod(lambda _binary = None: probes.append(_binary) or "none"),+ )+ intent = GgufLoadIntent(+ model_identifier = "owner/model", gguf_path = str(gguf), n_ctx = 4096, gpu_memory_mode = "auto"+ )+ assert backend._preserve_cpu_fallback_intent(intent).cpu_fallback is False+ assert probes == []+ # A crash recovery is still sticky for the same source.+ backend._cpu_fallback_reason = "vulkan_startup_crash"+ assert backend._preserve_cpu_fallback_intent(intent).cpu_fallback is True+++def test_a_stalled_text_only_retry_after_a_timed_out_probe_replays_on_cpu(monkeypatch, tmp_path):+ """The stall rule follows every bounded retry, not only the first launch."""+ _route_env(monkeypatch, "timeout")+ sink = {}+ backend, loaded, launches, fallback_sources = _run_cpu_fallback_load(+ monkeypatch,+ tmp_path,+ returncodes = [1, None, None],+ first_output = "projector-incompatible",+ mmproj_from_argv = True,+ stall_launches = (1,),+ sink = sink,+ )+ assert loaded is True+ assert launches[-1][0][0] == "/staged/llama-server"+ assert len(fallback_sources) == 1+ assert backend._cpu_fallback_reason == "vulkan_startup_stall"+++def test_a_stalled_text_only_retry_after_a_listed_device_fails_with_advice(monkeypatch, tmp_path):+ _route_env(monkeypatch, "devices")+ with pytest.raises(RuntimeError, match = "Settings > GGUF inference engine"):+ _run_cpu_fallback_load(+ monkeypatch,+ tmp_path,+ returncodes = [1, None, None],+ first_output = "projector-incompatible",+ mmproj_from_argv = True,+ stall_launches = (1,),+ )+++ "outcome, cpu_route",+ [("none", True), ("timeout", False), ("crashed", False), ("error", False), ("devices", False)],+)+def test_a_reload_after_a_stall_is_routed_by_the_loads_one_probe(+ monkeypatch, tmp_path, outcome, cpu_route+):+ """Same-source reload after a stall replay: one probe, and only a conclusive none goes to CPU."""+ _route_env(monkeypatch, outcome)+ calls = []+ real = LlamaCppBackend._vulkan_probe_outcome+ monkeypatch.setattr(+ LlamaCppBackend,+ "_vulkan_probe_outcome",+ staticmethod(lambda _binary = None: calls.append(_binary) or real(_binary)),+ )+ monkeypatch.setattr(LlamaCppBackend, "matches_load_source", lambda self, intent: True)+ real_init = LlamaCppBackend.__init__++ def _init_after_a_stall(self, *a, **k):+ real_init(self, *a, **k)+ self._cpu_fallback_reason = "vulkan_startup_stall"++ monkeypatch.setattr(LlamaCppBackend, "__init__", _init_after_a_stall)+ backend, loaded, launches, fallback_sources = _run_cpu_fallback_load(+ monkeypatch, tmp_path, returncodes = [None]+ )+ assert loaded is True+ assert len(calls) == 1+ assert (launches[0][0][0] == "/staged/llama-server") is cpu_route+ assert (len(fallback_sources) == 1) is cpu_route+++def test_one_vulkan_probe_per_load(monkeypatch, tmp_path):+ """Placement and the launch's outcome read share one answer (a hung probe costs one timeout)."""+ probes = []++ def _probe(binary):+ probes.append(binary)+ llama_cpp._load_probe_memo_put("vulkan_outcome", binary, "timeout")+ llama_cpp._load_probe_memo_put("vulkan", binary, [])+ return []++ real_outcome = LlamaCppBackend._vulkan_probe_outcome+ monkeypatch.setattr(LlamaCppBackend, "_binary_revision", staticmethod(lambda _b: ("rev", 1)))+ monkeypatch.setattr(+ LlamaCppBackend, "_cpu_isolated_binary", lambda self, _binary: "/staged/llama-server"+ )++ def _memo_probe(binary):+ memo = llama_cpp._load_probe_memo_get("vulkan", binary)+ return memo if memo is not None else _probe(binary)++ monkeypatch.setattr(LlamaCppBackend, "_run_vulkan_probe", staticmethod(_memo_probe))+ monkeypatch.setattr(LlamaCppBackend, "_vulkan_probe_outcome", staticmethod(real_outcome))+ sink = {}++ def _placement_probe(+ self,+ binary = None,+ **_kw,+ ):+ LlamaCppBackend._run_vulkan_probe(binary or "/fake/llama-server")+ return []++ with llama_cpp._load_probe_memo_scope():+ backend, loaded, launches, _ = _run_cpu_fallback_load(+ monkeypatch,+ tmp_path,+ returncodes = [None],+ sink = sink,+ gpu_memory = _placement_probe,+ )+ assert loaded is True+ assert probes == ["/fake/llama-server"]+++def test_a_stall_replay_with_the_vision_argv_clears_the_text_only_diagnosis(monkeypatch, tmp_path):+ """A guessed projector fault, then a stalled text-only retry after a timed-out probe: the CPU+ replay runs with the original projector, so vision is back and the text-only reason must go."""+ _route_env(monkeypatch, "timeout")+ sink = {}+ backend, loaded, launches, fallback_sources = _run_cpu_fallback_load(+ monkeypatch,+ tmp_path,+ returncodes = [-11, None, None],+ mmproj_from_argv = True,+ stall_launches = (1,),+ sink = sink,+ )+ assert loaded is True+ assert "--mmproj" in fallback_sources[0]+ assert backend._cpu_fallback_reason == "vulkan_startup_stall"+ assert backend._mmproj_fallback_reason is Nonediff --git a/studio/frontend/src/features/chat/lib/gpu-placement.ts b/studio/frontend/src/features/chat/lib/gpu-placement.tsindex a852687e331..98601c14998 100644--- a/studio/frontend/src/features/chat/lib/gpu-placement.ts+++ b/studio/frontend/src/features/chat/lib/gpu-placement.ts@@ -8,10 +8,26 @@// --fit. The Manual default; "all on GPU" is the slider's max.export const GPU_LAYERS_AUTO = -1;+/** Why an automatic GGUF load runs on the CPU (`cpu_fallback_reason`); every reason is the same+ * CPU replay. Here, not in types/api.ts, because this module stays import-free for node:test. */+export const CPU_FALLBACK_REASONS = [+ "vulkan_startup_crash",+ "vulkan_no_device",+ "vulkan_startup_stall",+] as const;++export type CpuFallbackReason = (typeof CPU_FALLBACK_REASONS)[number];++export function isCpuFallbackReason(+ value: unknown,+): value is CpuFallbackReason {+ return (CPU_FALLBACK_REASONS as readonly unknown[]).includes(value);+}+export function shouldHydrateGpuPlacementControls(- cpuFallbackReason: "vulkan_startup_crash" | null | undefined,+ cpuFallbackReason: CpuFallbackReason | null | undefined,): boolean {- return cpuFallbackReason !== "vulkan_startup_crash";+ return !isCpuFallbackReason(cpuFallbackReason);}/** GPU placement a compare pane loads with. `own` is the pane's per-model config; `shared` is thediff --git a/studio/frontend/src/features/chat/lib/partial-offload.ts b/studio/frontend/src/features/chat/lib/partial-offload.tsindex 7f91ab545d5..7f7791d45c4 100644--- a/studio/frontend/src/features/chat/lib/partial-offload.ts+++ b/studio/frontend/src/features/chat/lib/partial-offload.ts@@ -3,7 +3,7 @@import { formatGiB } from "../../../lib/memory/format";import type { LoadedPlacement } from "../stores/chat-runtime-store";-import { CPU_FALLBACK_MESSAGE } from "../utils/mmproj-fallback";+import { cpuFallbackMessage } from "../utils/mmproj-fallback";// React-free so node:test can import it; shared by every model load path.@@ -50,7 +50,7 @@ export interface OffloadWarning {}/** Why a loaded model is not fully on the GPU, or `null`. A known cpu_fallback_reason- * wins over the counts: a recovered Vulkan crash also logs 0/M, and is not a size problem.+ * wins over the counts: a Vulkan CPU fallback also logs 0/M, and is not a size problem.* Manual pins only count with gpuLayers >= 0 (Manual + Auto layers is llama.cpp's fit). */export function offloadWarning(counts: OffloadCounts): OffloadWarning | null {const {@@ -62,10 +62,11 @@ export function offloadWarning(counts: OffloadCounts): OffloadWarning | null {cpuFallbackReason,gpuBackendUnavailable,} = counts;- if (cpuFallbackReason === "vulkan_startup_crash") {+ const cpuFallbackDescription = cpuFallbackMessage(cpuFallbackReason);+ if (cpuFallbackDescription) {return {titleSuffix: " on CPU",- description: CPU_FALLBACK_MESSAGE,+ description: cpuFallbackDescription,};}// An unrecognised reason is still a reason: say nothing rather than guess at it.diff --git a/studio/frontend/src/features/chat/lib/resident-config-match.ts b/studio/frontend/src/features/chat/lib/resident-config-match.tsindex e2b23d7247e..c82a176793c 100644--- a/studio/frontend/src/features/chat/lib/resident-config-match.ts+++ b/studio/frontend/src/features/chat/lib/resident-config-match.ts@@ -20,6 +20,7 @@ import {} from "@/lib/speculative-modes";import type { InferenceStatusResponse } from "../types/api";+import { isCpuFallbackReason } from "./gpu-placement";/** The resident load's own invocation, as `/api/inference/status` echoes it. */type ResidentRuntime = Pick<@@ -586,15 +587,15 @@ function diffusionManualNgl(}/** Whether the backend would rewrite this request into the resident CPU fallback.- * `adopt_load_intent_if_matched` runs `_preserve_cpu_fallback_intent` first, so after a- * Vulkan startup crash an Auto request becomes the resident manual/zero-layer intent and+ * `adopt_load_intent_if_matched` runs `_preserve_cpu_fallback_intent` first, so after any+ * Vulkan CPU fallback an Auto request becomes the resident manual/zero-layer intent and* dedupes. Mirrors `_cpu_fallback_request_eligible` minus its environment terms. */function cpuFallbackPlacementPreserved(config: PerModelConfig,status: ResidentRuntime,standing: StandingConfigDefaults,): boolean {- if (status.cpu_fallback_reason !== "vulkan_startup_crash") {+ if (!isCpuFallbackReason(status.cpu_fallback_reason)) {return false;}const mode = config.gpuMemoryMode ?? standing.gpuMemoryMode;diff --git a/studio/frontend/src/features/chat/stores/chat-runtime-store.ts b/studio/frontend/src/features/chat/stores/chat-runtime-store.tsindex 3b84af1d85e..04b873dcbe2 100644--- a/studio/frontend/src/features/chat/stores/chat-runtime-store.ts+++ b/studio/frontend/src/features/chat/stores/chat-runtime-store.ts@@ -29,7 +29,9 @@ import { DRAFT_N_MAX_SPEC_TYPES } from "@/lib/speculative-modes";import { create } from "zustand";import { getChatSettings } from "../api/chat-settings-api";import {+ type CpuFallbackReason,GPU_LAYERS_AUTO,+ isCpuFallbackReason,recoverDroppedDiffusionSplit,shouldHydrateGpuPlacementControls,} from "../lib/gpu-placement";@@ -2360,7 +2362,7 @@ export function loadedGpuMemoryFields(resp: {is_diffusion?: boolean;gpu_memory_mode?: "auto" | "manual";gpu_layers?: number;- cpu_fallback_reason?: "vulkan_startup_crash" | null;+ cpu_fallback_reason?: CpuFallbackReason | null;n_cpu_moe?: number;tensor_split?: number[] | null;n_layers?: number | null;@@ -2461,7 +2463,7 @@ export function loadedGpuMemoryFields(resp: {: { gpuMemoryMode: mode }: {}),loadedGpuMemoryMode: mode,- loadedCpuFallback: resp.cpu_fallback_reason === "vulkan_startup_crash",+ loadedCpuFallback: isCpuFallbackReason(resp.cpu_fallback_reason),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,diff --git a/studio/frontend/src/features/chat/types/api.ts b/studio/frontend/src/features/chat/types/api.tsindex ecbe754700c..e2c7f44de15 100644--- a/studio/frontend/src/features/chat/types/api.ts+++ b/studio/frontend/src/features/chat/types/api.ts@@ -4,8 +4,9 @@import type { TransformersUpgradeInfo } from "@/features/transformers-upgrade";import type { ManagedEngineOffer } from "@/features/model-picker";import type { CustomReasoningConfig } from "../custom-reasoning";+import type { CpuFallbackReason } from "../lib/gpu-placement";-export type CpuFallbackReason = "vulkan_startup_crash";+export type { CpuFallbackReason };export type MmprojFallbackReason =| "cpu_offload"diff --git a/studio/frontend/src/features/chat/utils/mmproj-fallback.ts b/studio/frontend/src/features/chat/utils/mmproj-fallback.tsindex 7d62fee6ca3..cf1b06b799e 100644--- a/studio/frontend/src/features/chat/utils/mmproj-fallback.ts+++ b/studio/frontend/src/features/chat/utils/mmproj-fallback.ts@@ -9,6 +9,23 @@ import type { CpuFallbackReason, MmprojFallbackReason } from "../types/api";export const CPU_FALLBACK_MESSAGE ="The auto-selected Vulkan backend crashed during startup, so GPU acceleration is disabled for this model session.";+const CPU_FALLBACK_MESSAGES: Record<CpuFallbackReason, string> = {+ vulkan_startup_crash: CPU_FALLBACK_MESSAGE,+ vulkan_no_device:+ "No usable Vulkan GPU was found, so this model runs on the CPU. Generation will be slower than on a GPU.",+ vulkan_startup_stall:+ "The auto-selected Vulkan backend stopped responding during startup, so GPU acceleration is disabled for this model session.",+};++/** The sentence for a CPU fallback reason, or null for one this build does not know. */+export function cpuFallbackMessage(+ reason: string | null | undefined,+): string | null {+ return reason && Object.hasOwn(CPU_FALLBACK_MESSAGES, reason)+ ? CPU_FALLBACK_MESSAGES[reason as CpuFallbackReason]+ : null;+}+const MMPROJ_FALLBACK_MESSAGES: Record<MmprojFallbackReason, string> = {// Three routes reach this one placement: the fit estimate predicting the projector will not fit// in VRAM, a GPU allocation failure at startup, and a bare signal crash with no non-projector@@ -86,7 +103,7 @@ export function loadFallbackNotice(// Both sentences, CPU first: it is the broader condition, and the projector sentence reads as a detail under it.const parts: string[] = [];if (cpuFallbackReason) {- parts.push(CPU_FALLBACK_MESSAGE);+ parts.push(cpuFallbackMessage(cpuFallbackReason) ?? CPU_FALLBACK_MESSAGE);}if (offload) {parts.push(offload.description);diff --git a/studio/frontend/src/features/settings/api/llama-backend-payload.ts b/studio/frontend/src/features/settings/api/llama-backend-payload.tsindex 0f0d1d4eb44..8fd1aa16856 100644--- a/studio/frontend/src/features/settings/api/llama-backend-payload.ts+++ b/studio/frontend/src/features/settings/api/llama-backend-payload.ts@@ -169,7 +169,7 @@ export function parseLlamaBackendSwitchStarted(};}-/** Show installable options and preserve the selected value if it became unavailable. */+/** Keep the selected value as an item even with no options: a Select whose value has no item renders blank. */export function visibleLlamaBackendOptions(status: LlamaBackendStatus | null,selected: LlamaBackend | null,@@ -177,7 +177,17 @@ export function visibleLlamaBackendOptions(if (!status) {return [];}- return status.options.filter(+ const visible = status.options.filter((option) => option.available || option.backend === selected,);+ if (selected && !visible.some((option) => option.backend === selected)) {+ visible.push({+ backend: selected,+ available: false,+ resolvedBackend: selected === "auto" ? status.backend : null,+ releaseTag: null,+ downloadSizeBytes: null,+ });+ }+ return visible;}diff --git a/studio/frontend/src/features/settings/components/llama-backend-section.tsx b/studio/frontend/src/features/settings/components/llama-backend-section.tsxindex e26ab481e64..e7feb36e71c 100644--- a/studio/frontend/src/features/settings/components/llama-backend-section.tsx+++ b/studio/frontend/src/features/settings/components/llama-backend-section.tsx@@ -237,7 +237,13 @@ export function LlamaBackendSection() {// Null means the marker holds a choice a newer Unsloth wrote. Show it as// unknown rather than as Automatic, and let it be replaced deliberately.const unknownRecorded = status?.backendRequest === null;- const value = selected ?? status?.backendRequest ?? "unknown";+ // A value with no item renders a blank Select that reads as "no backends at all".+ const statusPending = !status && !loadError;+ const value = status+ ? (selected ?? status.backendRequest ?? "unknown")+ : statusPending+ ? "loading"+ : "unknown";const options = visibleLlamaBackendOptions(status,selected ?? status?.backendRequest ?? null,@@ -282,7 +288,12 @@ export function LlamaBackendSection() {<SelectValue /></SelectTrigger><SelectContent>- {unknownRecorded ? (+ {statusPending ? (+ <SelectItem value="loading" disabled>+ {t("common.loading")}+ </SelectItem>+ ) : null}+ {unknownRecorded || (!status && loadError) ? (<SelectItem value="unknown">{t("settings.resources.environment.unknown")}</SelectItem>diff --git a/studio/frontend/tests/gpu-placement.test.ts b/studio/frontend/tests/gpu-placement.test.tsindex a1ef8eec5c6..a3075923bb9 100644--- a/studio/frontend/tests/gpu-placement.test.ts+++ b/studio/frontend/tests/gpu-placement.test.ts@@ -20,6 +20,9 @@ test("a Vulkan CPU fallback does not replace the standing GPU intent", () => {shouldHydrateGpuPlacementControls("vulkan_startup_crash"),false,);+ for (const reason of ["vulkan_no_device", "vulkan_startup_stall"] as const) {+ assert.equal(shouldHydrateGpuPlacementControls(reason), false);+ }assert.equal(shouldHydrateGpuPlacementControls(null), true);});diff --git a/studio/frontend/tests/llama-backend-payload.test.ts b/studio/frontend/tests/llama-backend-payload.test.tsindex a9daa184250..519f1b71d28 100644--- a/studio/frontend/tests/llama-backend-payload.test.ts+++ b/studio/frontend/tests/llama-backend-payload.test.ts@@ -115,6 +115,29 @@ test("the selected backend stays listed even when it stops being installable", ();});+test("a selection with no options left is still listed, not rendered blank", () => {+ // No options while resolution is pending or failed, or a job runs: the recorded choice+ // still needs an item, and automatic names what the install runs on.+ const status = parseLlamaBackendStatus({+ ...FULL_PAYLOAD,+ backend: "vulkan",+ options: [],+ });++ const [auto] = visibleLlamaBackendOptions(status, "auto");+ assert.equal(auto.backend, "auto");+ assert.equal(auto.available, false);+ assert.equal(auto.resolvedBackend, "vulkan");+ assert.deepEqual(+ visibleLlamaBackendOptions(status, "cpu").map((option) => [+ option.backend,+ option.resolvedBackend,+ ]),+ [["cpu", null]],+ );+ assert.equal(visibleLlamaBackendOptions(null, "auto").length, 0);+});+test("automatic can be applied again when it now resolves differently", () => {const status = parseLlamaBackendStatus({...FULL_PAYLOAD,diff --git a/studio/frontend/tests/mmproj-fallback.test.ts b/studio/frontend/tests/mmproj-fallback.test.tsindex 5d5f0664783..02ec5b2c62f 100644--- a/studio/frontend/tests/mmproj-fallback.test.ts+++ b/studio/frontend/tests/mmproj-fallback.test.ts@@ -15,6 +15,7 @@ const {mmprojLoadNotice,loadFallbackNotice,CPU_FALLBACK_MESSAGE,+ cpuFallbackMessage,} = await import("../src/features/chat/utils/mmproj-fallback.ts");const IMAGE_INPUT_AVAILABLE = /Image input remains available/;@@ -155,6 +156,23 @@ test("a CPU-offloaded projector under a CPU fallback does not claim vision is acassert.equal(notice.degraded, true);});+test("every CPU fallback reason says why the model is on the CPU", () => {+ const noDevice = loadFallbackNotice("X loaded", "vulkan_no_device", null);+ assert.equal(noDevice.title, "X loaded on CPU");+ assert.equal(noDevice.description, cpuFallbackMessage("vulkan_no_device"));+ assert.match(noDevice.description ?? "", /No usable Vulkan GPU was found/);+ assert.equal(noDevice.degraded, true);++ const stall = loadFallbackNotice("X loaded", "vulkan_startup_stall", "cpu_offload");+ assert.equal(stall.title, "X loaded on CPU");+ assert.match(stall.description ?? "", /stopped responding during startup/);+ assert.match(stall.description ?? "", /Image input remains available/);++ assert.equal(cpuFallbackMessage("vulkan_startup_crash"), CPU_FALLBACK_MESSAGE);+ assert.equal(cpuFallbackMessage("something"), null);+ assert.equal(cpuFallbackMessage(null), null);+});+test("each fallback alone still reads exactly as it did before", () => {const cpuOnly = loadFallbackNotice("X loaded", "vulkan_startup_crash", null);assert.equal(cpuOnly.title, "X loaded on CPU");diff --git a/studio/frontend/tests/partial-offload.test.ts b/studio/frontend/tests/partial-offload.test.tsindex 65d03da34c7..914a48aa09f 100644--- a/studio/frontend/tests/partial-offload.test.ts+++ b/studio/frontend/tests/partial-offload.test.ts@@ -154,6 +154,14 @@ test("a known reason for the CPU wins over the counts", () => {assert.equal(warning?.titleSuffix, " on CPU");assert.match(warning?.description ?? "", /Vulkan backend crashed/);assert.doesNotMatch(warning?.description ?? "", /smaller quantization/);+ for (const [reason, text] of [+ ["vulkan_no_device", /No usable Vulkan GPU was found/],+ ["vulkan_startup_stall", /stopped responding during startup/],+ ] as const) {+ const other = offloadWarning({ offloaded: 0, total: 60, cpuFallbackReason: reason });+ assert.equal(other?.titleSuffix, " on CPU");+ assert.match(other?.description ?? "", text);+ }assert.equal(offloadWarning({ offloaded: 0, total: 60, cpuFallbackReason: "something" }),null,