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.

Fix low VRAM mmproj fallback in Studio (#9173)

Wasim Yousef Said077593612ced
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.py
index 5a6a41db55a..100bdad6b22 100644
--- a/studio/backend/core/inference/llama_cpp.py
+++ b/studio/backend/core/inference/llama_cpp.py
@@ -186,6 +186,8 @@ class GgufLoadIntent:
extra_args_inherited: bool = False
preserve_multi_gpu_on_layer: bool = False
compare_mtp_draft: bool = False
+ force_reload: bool = False
+
cpu_fallback: bool = False
def __post_init__(self):
@@ -3672,6 +3674,10 @@ class LlamaCppBackend:
# llama.cpp" hint in the UI. "binary_no_mtp" / "binary_outdated" ->
# a newer prebuilt would help; "runtime_error" -> it may not.
self._spec_fallback_reason: Optional[str] = None
+
+ # How a requested multimodal projector recovered at startup. `cpu_offload`
+ # keeps vision; the other values accompany a deliberate text-only retry.
+ self._mmproj_fallback_reason: Optional[str] = None
# Whether THIS load ran against a probe that did not answer, rather than one
# that answered "no". An inconclusive probe reports every capability absent, so it
# silently degrades speculative decoding, the DSpark sidecar and the --kv-unified
@@ -3978,6 +3984,11 @@ class LlamaCppBackend:
"""Why MTP was disabled on the last MTP-requesting load, else None."""
return self._spec_fallback_reason
+ @property
+ def mmproj_fallback_reason(self) -> Optional[str]:
+ """How the active model recovered from an mmproj startup failure, else None."""
+ return self._mmproj_fallback_reason
+
def _binary_changed_since_launch(self) -> bool:
"""Whether a different llama-server is installed than the live one was launched
from. False when either side is unreadable, so an install still in flight is not
@@ -4474,6 +4485,9 @@ class LlamaCppBackend:
self, intent: GgufLoadIntent, effective_extra_args: Optional[list[str]]
) -> bool:
"""Whether active runtime settings satisfy one resolved caller intent."""
+
+ if intent.force_reload:
+ return False
if self._requested_n_ctx != int(intent.n_ctx):
return False
if not self._is_diffusion and self._requested_n_parallel != max(1, int(intent.n_parallel)):
@@ -12287,6 +12301,66 @@ class LlamaCppBackend:
tensor_split = adj
return effective_ctx, max_available_ctx, gpu_indices, tensor_split
+ @staticmethod
+ def _with_mmproj_offload_disabled(
+ cmd: Sequence[str], env: Optional[Mapping[str, str]] = None
+ ) -> Optional[List[str]]:
+ """Return a vision-preserving retry with the projector pinned to CPU.
+
+ llama.cpp's boolean placement flags are last-wins, so the recovery pin
+ must follow pass-through arguments that may have enabled GPU offload.
+ None means no projector is present or it already runs on CPU.
+ """
+ args = [str(arg) for arg in cmd]
+
+ def _flag(token: str) -> str:
+ return token.split("=", 1)[0].replace("_", "-").lower()
+
+ if not any(_flag(arg) in ("--mmproj", "-mm") for arg in args):
+ return None
+ placements = [
+ _flag(arg) for arg in args if _flag(arg) in ("--mmproj-offload", "--no-mmproj-offload")
+ ]
+ if placements and placements[-1] == "--no-mmproj-offload":
+ return None
+ if not placements:
+ env_value = str((env or {}).get("LLAMA_ARG_MMPROJ_OFFLOAD") or "").strip().lower()
+ if env_value in ("0", "false", "off", "no"):
+ return None
+ return args + ["--no-mmproj-offload"]
+
+ @staticmethod
+ def _is_gpu_memory_start_failure(output: str) -> bool:
+ """Whether startup output ties allocation pressure to a GPU backend."""
+ lines = (output or "").lower().splitlines()
+ allocation_markers = (
+ "out of memory",
+ "failed to allocate",
+ "cudamalloc failed",
+ "hiperroroutofmemory",
+ "vk_error_out_of_device_memory",
+ )
+ gpu_markers = (
+ "cuda",
+ "hiperror",
+ "hipmalloc",
+ "ggml_backend_hip",
+ "rocm",
+ "vulkan",
+ "vk_",
+ "metal",
+ "sycl",
+ "oneapi",
+ "musa",
+ "gpu",
+ "device memory",
+ )
+ return any(
+ any(marker in line for marker in allocation_markers)
+ and any(marker in line for marker in gpu_markers)
+ for line in lines
+ )
+
@staticmethod
def _is_projector_incompatibility(output: str) -> bool:
"""True when llama-server aborted because it cannot load the model's
@@ -13686,6 +13760,8 @@ class LlamaCppBackend:
if not _replaying_cpu_fallback:
self._cpu_fallback_reason = None
self._cleanup_cpu_fallback_runtime()
+
+ self._mmproj_fallback_reason = None
# Both describe the process just killed, so they are reset HERE rather than
# where the binary is resolved: everything above can bail with the old server
# still running (a stand-down, a non-chat refusal, a cancel), and resetting on
@@ -17757,8 +17833,9 @@ class LlamaCppBackend:
)
extra_args = _fb_stripped_extras
- # A too-old llama.cpp can reject a model's --mmproj projector
- # (format message or a bare SIGSEGV); retry once text-only.
+ # 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.
if not healthy:
out = "\n".join(self._stdout_lines[-50:])
# Read the crash code before _kill_process() clears _process.
@@ -17767,75 +17844,148 @@ class LlamaCppBackend:
# The #6415 split-axis abort is latched earlier (first spawn).
# Skip if a cancel/unload is pending (mirrors the MTP guard).
_projector_msg = self._is_projector_incompatibility(out)
+ _projector_memory = self._is_gpu_memory_start_failure(out)
_signal_mmproj_guess = self._is_signal_crash(
_crash_rc
) and not self._output_has_nonprojector_diagnostic(out)
if (
launched_with_mmproj
and not _load_cancelled()
- and (_projector_msg or _signal_mmproj_guess)
+ and (_projector_msg or _projector_memory 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 "
- "projector (--mmproj). The installed llama.cpp build is "
- "likely too old for it. Loading text-only for this "
- "session; run 'unsloth studio update' to enable vision."
+ _vision_gpu_cmd = list(_last_spawn_cmd)
+ _cpu_projector_cmd = None
+ if not _projector_msg and _paravirtual_mmproj_pinnable(server_caps):
+ _cpu_projector_cmd = self._with_mmproj_offload_disabled(
+ _vision_gpu_cmd, env
)
- else:
+
+ if _cpu_projector_cmd is not None:
logger.warning(
- "llama-server crashed while loading this model's vision "
- "projector (--mmproj). Retrying text-only for this "
- "session; if this persists, run 'unsloth studio update' "
- "or check GPU/driver logs."
+ "llama-server failed while loading this model's GPU "
+ "vision projector (--mmproj); retrying with the "
+ "projector on CPU to preserve image input."
)
- cmd = self._strip_mmproj_args(_last_spawn_cmd)
- # This retry bypasses _spawn_and_wait, so refresh the
- # launched-argv snapshot itself -- the zero-offload
- # classification below must not see the stripped --mmproj.
- _last_spawn_cmd = list(cmd)
- self._is_vision = False
- self._mmproj_has_audio = False
- self._start_llama_process(cmd, env)
- if not self._wait_for_health(timeout = 600.0):
- # Read the exit code before _kill_process() clears it, so
- # 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()
- # 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):
- _cpu_replay_cmd = (
- _last_spawn_cmd if _projector_msg else _vision_cpu_replay_cmd
+ cmd = _cpu_projector_cmd
+ healthy = _spawn_and_wait(cmd, label = "-mmproj-cpu")
+ if healthy:
+ self._mmproj_fallback_reason = "cpu_offload"
+ logger.warning(
+ "Vision projector loaded on CPU after GPU startup "
+ "failed; image input remains available for this session."
)
- if _try_auto_vulkan_cpu_fallback(
- _cpu_replay_cmd,
- _retry_rc,
- ):
- healthy = True
- else:
+ else:
+ _cpu_projector_out = "\n".join(self._stdout_lines[-50:])
+ _cpu_projector_rc = (
+ self._process.poll() if self._process is not None else None
+ )
+ self._kill_process()
+ if _load_cancelled():
+ return False
+ if self._is_projector_incompatibility(_cpu_projector_out):
+ _projector_msg = True
+ elif self._is_gpu_memory_start_failure(_cpu_projector_out):
+ # The projector was already off the GPU, so removing it
+ # cannot repair this allocation failure; keep the real error.
_raise_terminal_load_failure(
- self._gpu_init_crash_message(binary)
+ self._classify_llama_start_failure(
+ _cpu_projector_out,
+ gguf_path,
+ self._model_identifier,
+ _cpu_projector_rc,
+ binary,
+ self._llama_log_path,
+ (self._api_key,),
+ self._extra_args,
+ )
)
- if not healthy:
- _retry_detail = self._classify_llama_start_failure(
- "\n".join(self._stdout_lines[-50:]),
+ elif _projector_memory and _paravirtual_mmproj_pinnable(server_caps):
+ # An env/argv pin already put mmproj on CPU. Text-only
+ # cannot free additional GPU memory, so surface the OOM.
+ _raise_terminal_load_failure(
+ self._classify_llama_start_failure(
+ out,
gguf_path,
self._model_identifier,
- _retry_rc,
+ _crash_rc,
binary,
self._llama_log_path,
(self._api_key,),
self._extra_args,
)
- _raise_terminal_load_failure(
- self._mmproj_retry_failure_message(
- projector_confirmed = _projector_msg,
- detail = _retry_detail,
- )
+ )
+
+ if not healthy:
+ if _projector_msg:
+ logger.warning(
+ "llama-server could not load this model's vision "
+ "projector (--mmproj). The installed llama.cpp build is "
+ "likely too old for it. Loading text-only for this "
+ "session; run 'unsloth studio update' to enable vision."
)
+ self._mmproj_fallback_reason = "projector_incompatible"
+ else:
+ logger.warning(
+ "llama-server could not start with this model's vision "
+ "projector (--mmproj), including the CPU-projector "
+ "recovery when available. Retrying text-only for this "
+ "session; check memory, GPU/driver logs, or update Studio."
+ )
+ self._mmproj_fallback_reason = "projector_startup_failure"
+ cmd = self._strip_mmproj_args(_vision_gpu_cmd)
+ # This retry bypasses _spawn_and_wait, so refresh the
+ # launched-argv snapshot itself -- the zero-offload
+ # classification below must not see the stripped --mmproj.
+ _last_spawn_cmd = list(cmd)
+ self._is_vision = False
+ self._mmproj_has_audio = False
+ self._start_llama_process(cmd, env)
+ if self._wait_for_health(timeout = 600.0):
+ healthy = True
+ else:
+ # Read the exit code before _kill_process() clears it, so
+ # 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()
+ # 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):
+ _cpu_replay_cmd = (
+ _last_spawn_cmd if _projector_msg else _vision_gpu_cmd
+ )
+ if _try_auto_vulkan_cpu_fallback(
+ _cpu_replay_cmd,
+ _retry_rc,
+ ):
+ healthy = True
+ # A whole-runtime CPU replay with the original
+ # vision argv supersedes the text-only diagnosis.
+ if not _projector_msg:
+ self._mmproj_fallback_reason = None
+ 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,
+ self._llama_log_path,
+ (self._api_key,),
+ self._extra_args,
+ )
+ _raise_terminal_load_failure(
+ self._mmproj_retry_failure_message(
+ projector_confirmed = _projector_msg,
+ detail = _retry_detail,
+ )
+ )
else:
# Try the drafter launch first, non-terminally: a build that
# can neither pin one to CPU nor start with it still recovers
@@ -18781,6 +18931,8 @@ class LlamaCppBackend:
self._mtp_draft_path = None
self._mtp_draft_suppressed_path = None
self._spec_fallback_reason = None
+
+ self._mmproj_fallback_reason = None
self._capability_probe_inconclusive = False
self._spec_drafter_kind = None
self._dspark_sidecar_absent = False
diff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.py
index 73023ff8c65..925142bcd0b 100644
--- a/studio/backend/models/inference.py
+++ b/studio/backend/models/inference.py
@@ -35,6 +35,11 @@ class LoadRequest(BaseModel):
pattern = r"^[A-Za-z0-9][A-Za-z0-9._:-]*$",
description = "Opaque client attempt ID for scoped in-flight cancellation",
)
+
+ force_reload: bool = Field(
+ False,
+ description = "Start a fresh runtime even when the active settings already match",
+ )
native_path_lease: Optional[str] = Field(
None, description = "Frontend-visible signed native path grant"
)
@@ -808,6 +813,18 @@ class _InferenceRuntimeFields(BaseModel):
"hard-crashed and the same launch became healthy with GPU devices disabled."
),
)
+
+ mmproj_fallback_reason: Optional[
+ Literal["cpu_offload", "projector_incompatible", "projector_startup_failure"]
+ ] = Field(
+ None,
+ description = (
+ "How an automatic GGUF multimodal-projector recovery changed the load. "
+ "'cpu_offload' keeps vision with the projector on CPU; "
+ "'projector_incompatible' and 'projector_startup_failure' mean the "
+ "model recovered text-only."
+ ),
+ )
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/tests/test_inference_status_loaded_gguf.py b/studio/backend/tests/test_inference_status_loaded_gguf.py
index 5d3d58456d8..4c35afc6090 100644
--- a/studio/backend/tests/test_inference_status_loaded_gguf.py
+++ b/studio/backend/tests/test_inference_status_loaded_gguf.py
@@ -195,6 +195,28 @@ def test_an_explicit_empty_list_is_not_a_missing_one(status_route):
assert status_route(backend).requested_llama_extra_args is None
+def test_status_publishes_mmproj_cpu_recovery(status_route):
+ backend = _StatusBackend("org/Vision-GGUF")
+ backend.is_vision = True
+ backend.mmproj_fallback_reason = "cpu_offload"
+
+ status = status_route(backend)
+
+ assert status.is_vision is True
+ assert status.mmproj_fallback_reason == "cpu_offload"
+
+
+def test_status_publishes_an_explicit_text_only_mmproj_fallback(status_route):
+ backend = _StatusBackend("org/Vision-GGUF")
+ backend.is_vision = False
+ backend.mmproj_fallback_reason = "projector_startup_failure"
+
+ status = status_route(backend)
+
+ assert status.is_vision is False
+ assert status.mmproj_fallback_reason == "projector_startup_failure"
+
+
def test_the_diffusion_runner_reports_none(status_route):
# It appends none of them, so publishing a list would describe a command that
# does not exist.
diff --git a/studio/backend/tests/test_llama_cpp_mmproj_fallback.py b/studio/backend/tests/test_llama_cpp_mmproj_fallback.py
index 47d4ffafae1..b28837b1620 100644
--- a/studio/backend/tests/test_llama_cpp_mmproj_fallback.py
+++ b/studio/backend/tests/test_llama_cpp_mmproj_fallback.py
@@ -1,16 +1,14 @@
# 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 the llama-server mmproj text-only fallback.
-
-A GGUF vision model is launched with ``--mmproj <projector>``. When the
-installed llama.cpp prebuilt is older than the model's projector format,
-llama-server aborts at startup with ``clip.cpp:NNNN: Unknown projector
-type`` (exit -6). load_model now retries once WITHOUT ``--mmproj`` so the
-base model still loads text-only, warns the user to update llama.cpp, and
-marks the session non-vision. These tests pin the two decision helpers:
-``_is_projector_incompatibility`` (when to retry) and ``_strip_mmproj_args``
-(how the retry argv is built). Unrelated failures must NOT trigger a retry.
+"""Tests for llama-server multimodal-projector startup recovery.
+
+A GGUF vision model launches with ``--mmproj <projector>``. When GPU memory
+cannot hold the projector, Studio first retries with ``--no-mmproj-offload``
+so image input remains available. Incompatible projectors, or startup crashes
+that also fail that CPU-projector retry, keep the existing text-only fallback.
+These tests pin the diagnostics, argv rewrites, fallback ordering, and runtime
+state exposed to the UI. Unrelated failures must not trigger a projector retry.
"""
from __future__ import annotations
@@ -36,7 +34,7 @@ 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.llama_cpp import LlamaCppBackend # noqa: E402
+from core.inference.llama_cpp import GgufLoadIntent, LlamaCppBackend # noqa: E402
_detect = LlamaCppBackend._is_projector_incompatibility
_strip = LlamaCppBackend._strip_mmproj_args
@@ -44,6 +42,9 @@ _signal_crash = LlamaCppBackend._is_signal_crash
_flash_off = LlamaCppBackend._with_flash_attn_off
_nonproj = LlamaCppBackend._output_has_nonprojector_diagnostic
+_mmproj_cpu = LlamaCppBackend._with_mmproj_offload_disabled
+_gpu_memory_failure = LlamaCppBackend._is_gpu_memory_start_failure
+
# Real abort captured loading gemma-4 on a 3-day-old prebuilt (build b9496).
_GEMMA4_OLD_LLAMACPP_OUT = (
"srv load_model: loading model 'gemma-4-E2B-it-UD-Q4_K_XL.gguf'\n"
@@ -146,6 +147,98 @@ _VISION_CMD = [
]
+class TestMmprojCpuOffload:
+ """The low-VRAM recovery keeps the projector but pins it to CPU."""
+
+ def test_appends_cpu_pin_last_and_keeps_vision(self):
+ retry = _mmproj_cpu(_VISION_CMD, {})
+ assert retry is not None
+ assert retry[-1] == "--no-mmproj-offload"
+ assert "--mmproj" in retry
+ assert "/cache/mmproj-F16.gguf" in retry
+ assert retry[:-1] == _VISION_CMD
+
+ def test_noop_without_a_projector(self):
+ assert _mmproj_cpu(["llama-server", "-m", "/cache/model.gguf"], {}) is None
+
+ def test_noop_when_projector_is_already_on_cpu(self):
+ cmd = _VISION_CMD + ["--no-mmproj-offload"]
+ assert _mmproj_cpu(cmd, {}) is None
+
+ def test_last_flag_wins_when_gpu_was_reenabled(self):
+ cmd = _VISION_CMD + ["--no-mmproj-offload", "--mmproj-offload"]
+ retry = _mmproj_cpu(cmd, {})
+ assert retry is not None
+ assert retry[-1] == "--no-mmproj-offload"
+
+ @pytest.mark.parametrize("value", ["0", "false", "off", "no"])
+ def test_noop_when_environment_already_pins_cpu(self, value):
+ assert _mmproj_cpu(_VISION_CMD, {"LLAMA_ARG_MMPROJ_OFFLOAD": value}) is None
+
+ @pytest.mark.parametrize("value", ["1", "true", "on", "yes"])
+ def test_command_pin_overrides_gpu_environment(self, value):
+ retry = _mmproj_cpu(_VISION_CMD, {"LLAMA_ARG_MMPROJ_OFFLOAD": value})
+ assert retry is not None
+ assert retry[-1] == "--no-mmproj-offload"
+
+
+class TestGpuMemoryStartFailure:
+ @pytest.mark.parametrize(
+ "out",
+ [
+ _OOM_OUT,
+ "ggml_backend_cuda_buffer_type_alloc: failed to allocate buffer",
+ "CUDA error: out of memory",
+ ],
+ )
+ def test_gpu_allocation_errors_match(self, out):
+ assert _gpu_memory_failure(out) is True
+
+ @pytest.mark.parametrize(
+ "out",
+ [
+ "ggml_alloc: failed to allocate 512.00 MiB",
+ "std::bad_alloc: out of memory",
+ ],
+ )
+ def test_host_allocation_errors_do_not_match(self, out):
+ assert _gpu_memory_failure(out) is False
+
+ def test_unrelated_gpu_banner_does_not_reclassify_host_oom(self):
+ out = "ggml_cuda_init: found 1 CUDA device\nstd::bad_alloc: out of memory"
+ assert _gpu_memory_failure(out) is False
+
+ @pytest.mark.parametrize("out", [_BAD_ARCH_OUT, _PORT_OUT, _MISSING_OUT, ""])
+ def test_unrelated_startup_errors_do_not_match(self, out):
+ assert _gpu_memory_failure(out) is False
+
+
+class TestMmprojExplicitReload:
+ @staticmethod
+ def _backend() -> LlamaCppBackend:
+ backend = LlamaCppBackend()
+ backend._requested_n_ctx = 8192
+ backend._requested_spec_mode = "auto"
+ return backend
+
+ @staticmethod
+ def _intent(*, force_reload: bool = False) -> GgufLoadIntent:
+ return GgufLoadIntent(
+ model_identifier = "owner/vision-model",
+ n_ctx = 8192,
+ speculative_type = "auto",
+ force_reload = force_reload,
+ )
+
+ def test_normal_duplicate_still_matches(self):
+ backend = self._backend()
+ assert backend._runtime_matches_intent(self._intent(), None) is True
+
+ def test_explicit_reload_bypasses_runtime_deduplication(self):
+ backend = self._backend()
+ assert backend._runtime_matches_intent(self._intent(force_reload = True), None) is False
+
+
class TestStripMmprojArgs:
def test_removes_mmproj_pair(self):
stripped = _strip(_VISION_CMD)
@@ -504,10 +597,15 @@ class TestRetryContract:
assert "--mmproj" not in retry_cmd
assert "-m" in retry_cmd and "--jinja" in retry_cmd
- def test_oom_does_not_retry_text_only(self):
- # An OOM with --mmproj present must NOT be treated as a projector
- # problem: load_model errors out instead of dropping vision.
+ def test_oom_retries_with_the_projector_on_cpu_before_text_only(self):
+ # A concrete GPU allocation failure is not projector incompatibility,
+ # but it is exactly when --no-mmproj-offload can preserve image input.
assert _detect(_OOM_OUT) is False
+ assert _gpu_memory_failure(_OOM_OUT) is True
+ retry_cmd = _mmproj_cpu(_VISION_CMD, {})
+ assert retry_cmd is not None
+ assert retry_cmd[-1] == "--no-mmproj-offload"
+ assert "--mmproj" in retry_cmd
def test_bare_segfault_with_mmproj_yields_text_only_retry(self):
# Field report: a -11 SIGSEGV on --mmproj has no projector line; the
@@ -519,12 +617,14 @@ class TestRetryContract:
retry_cmd = _strip(_VISION_CMD)
assert "--mmproj" not in retry_cmd and "-m" in retry_cmd
- def test_signal_crash_with_oom_output_keeps_the_real_error(self):
- # A hard fault that already printed an OOM must surface it, not silently
- # drop --mmproj and tell the user to update llama.cpp.
+ def test_signal_crash_with_oom_output_uses_the_cpu_projector_rung(self):
+ # OOM remains excluded from the ambiguous signal-only diagnosis, but
+ # has its own recovery: keep --mmproj and move that projector to CPU.
assert _signal_crash(-6) is True
- should_retry = _detect(_OOM_OUT) or (_signal_crash(-6) and not _nonproj(_OOM_OUT))
- assert should_retry is False
+ signal_only = _detect(_OOM_OUT) or (_signal_crash(-6) and not _nonproj(_OOM_OUT))
+ assert signal_only is False
+ assert _gpu_memory_failure(_OOM_OUT) is True
+ assert "--mmproj" in _mmproj_cpu(_VISION_CMD, {})
def test_signal_crash_with_bad_arch_does_not_drop_vision(self):
should_retry = _detect(_BAD_ARCH_OUT) or (_signal_crash(-6) and not _nonproj(_BAD_ARCH_OUT))
@@ -534,15 +634,18 @@ class TestRetryContract:
# Clean non-zero exit (bad path, port bind) is not a hard crash; stay message-based.
assert (_detect(_MISSING_OUT) or _signal_crash(1)) is False
- def test_signal_crash_tries_flash_attn_off_before_dropping_vision(self):
- # Ladder order: a hard fault retries FA-off FIRST (keeps vision + MTP);
- # only if THAT is None/fails do we fall back to stripping --mmproj.
+ def test_signal_crash_tries_non_destructive_rungs_before_dropping_vision(self):
+ # Ladder order: FA-off first, then projector-on-CPU. Only if both fail
+ # does Studio remove --mmproj and become text-only.
assert _signal_crash(-11) is True
fa_retry = _flash_off(_VISION_CMD)
assert fa_retry is not None
- assert "--mmproj" in fa_retry # vision preserved at this rung
- # Last resort still available and strictly more destructive.
- text_only = _strip(fa_retry)
+ assert "--mmproj" in fa_retry
+ cpu_projector = _mmproj_cpu(fa_retry, {})
+ assert cpu_projector is not None
+ assert "--mmproj" in cpu_projector
+ assert cpu_projector[-1] == "--no-mmproj-offload"
+ text_only = _strip(cpu_projector)
assert "--mmproj" not in text_only
def test_external_kill_skips_flash_attn_retry(self):
@@ -550,6 +653,15 @@ class TestRetryContract:
assert _signal_crash(-9) is False
+class TestMmprojFallbackLifecycle:
+ def test_unload_clears_the_runtime_outcome(self):
+ backend = LlamaCppBackend()
+ backend._mmproj_fallback_reason = "cpu_offload"
+
+ assert backend.unload_model() is True
+ assert backend.mmproj_fallback_reason is None
+
+
class TestMmprojRetryFailureMessage:
"""#7302: bare mmproj crashes must not be reported as projector-format."""
diff --git a/studio/frontend/src/features/chat/api/chat-adapter.ts b/studio/frontend/src/features/chat/api/chat-adapter.ts
index ebfb22b65b5..460fac0da77 100644
--- a/studio/frontend/src/features/chat/api/chat-adapter.ts
+++ b/studio/frontend/src/features/chat/api/chat-adapter.ts
@@ -138,6 +138,7 @@ import type { ModelType, ThreadRecord } from "../types";
import { isMultimodalResponse } from "../types/api";
import type {
CpuFallbackReason,
+ MmprojFallbackReason,
GgufVariantDetail,
OpenAIChatCompletionsRequest,
OpenAIChatMessage,
@@ -145,6 +146,7 @@ import type {
OpenAIReasoningContentPart,
} from "../types/api";
import type { ChatModelSummary } from "../types/runtime";
+import { mmprojFallbackMessage } from "../utils/mmproj-fallback";
import {
getStoredChatThread,
getStoredChatThreadReadResult,
@@ -2607,16 +2609,26 @@ async function autoLoadSmallestModel(options?: AutoLoadOptions): Promise<{
const showAutoLoadSuccess = (
message: string,
cpuFallbackReason?: CpuFallbackReason | null,
+ mmprojFallbackReason?: MmprojFallbackReason | null,
): void => {
const options = {
- description: cpuFallbackReason
- ? "The auto-selected Vulkan backend crashed during startup, so GPU acceleration is disabled for this model session."
- : undefined,
+ description: mmprojFallbackReason
+ ? mmprojFallbackMessage(mmprojFallbackReason)
+ : 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;
+ const showToast =
+ mmprojFallbackReason || cpuFallbackReason ? toast.warning : toast.success;
+ const title = mmprojFallbackReason
+ ? mmprojFallbackReason === "cpu_offload"
+ ? `${message} with vision on CPU`
+ : `${message} without vision`
+ : cpuFallbackReason
+ ? `${message} on CPU`
+ : message;
if (autoLoadToastDismissed) {
showToast(title, options);
return;
@@ -3086,6 +3098,7 @@ async function autoLoadSmallestModel(options?: AutoLoadOptions): Promise<{
// override; null stays null (auto/VRAM-fit).
customContextLength: config.customContextLength,
loadedIsMultimodal: isMultimodalResponse(loadResp),
+ mmprojFallbackReason: loadResp.mmproj_fallback_reason ?? null,
loadedIsDiffusion: loadResp.is_diffusion ?? false,
activeModelIsLocal: loadResp.is_local_model ?? false,
...resolveLoadedSpeculativeSettings(loadResp),
@@ -3125,6 +3138,7 @@ async function autoLoadSmallestModel(options?: AutoLoadOptions): Promise<{
customContextLength: null,
...resolveLoadedSpeculativeSettings(loadResp),
loadedIsMultimodal: isMultimodalResponse(loadResp),
+ mmprojFallbackReason: loadResp.mmproj_fallback_reason ?? null,
loadedIsDiffusion: loadResp.is_diffusion ?? false,
activeModelIsLocal: loadResp.is_local_model ?? false,
});
@@ -3136,7 +3150,11 @@ async function autoLoadSmallestModel(options?: AutoLoadOptions): Promise<{
ggufVariant: candidate.ggufVariant,
});
}
- showAutoLoadSuccess(candidate.successLabel, loadResp.cpu_fallback_reason);
+ showAutoLoadSuccess(
+ candidate.successLabel,
+ loadResp.cpu_fallback_reason,
+ loadResp.mmproj_fallback_reason,
+ );
});
return true;
}
@@ -3437,6 +3455,7 @@ async function autoLoadSmallestModel(options?: AutoLoadOptions): Promise<{
defaultChatTemplate: loadResp.chat_template ?? null,
chatTemplateOverride: null,
loadedIsMultimodal: isMultimodalResponse(loadResp),
+ mmprojFallbackReason: loadResp.mmproj_fallback_reason ?? null,
activeModelIsLocal: loadResp.is_local_model ?? false,
...resolveLoadedSpeculativeSettings(loadResp),
});
@@ -3448,6 +3467,7 @@ async function autoLoadSmallestModel(options?: AutoLoadOptions): Promise<{
showAutoLoadSuccess(
`Loaded ${DEFAULT_CHAT_MODEL_LABEL} (${DEFAULT_CHAT_MODEL_VARIANT})`,
loadResp.cpu_fallback_reason,
+ loadResp.mmproj_fallback_reason,
);
});
return { loaded: true, blockedByTrustRemoteCode: false };
@@ -4508,6 +4528,7 @@ export function createOpenAIStreamAdapter(
loadedIsMultimodal: runtime.loadedIsMultimodal,
modelLoaded: !!params.checkpoint && !runtime.modelLoading,
loadError: runtime.lastModelLoadError,
+ mmprojFallbackReason: runtime.mmprojFallbackReason,
});
if (imageGateReason) {
toast.error(imageGateReason);
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 963b5ed0ebf..f2436737c73 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
@@ -79,10 +79,12 @@ import {
resolveManualAutoCtxPin,
} from "../presets/preset-policy";
import { recordLastLocalModelLoad } from "../utils/last-local-model-load";
+import { mmprojLoadNotice } from "../utils/mmproj-fallback";
import { refreshContextUsage } from "../utils/refresh-context-usage";
import { ensureGpuDeviceCache } from "@/hooks/use-gpu-info";
import {
type CpuFallbackReason,
+ type MmprojFallbackReason,
type InferenceStatusResponse,
isMultimodalResponse,
} from "../types/api";
@@ -1045,6 +1047,7 @@ export function useChatModelRuntime() {
loadAbortRef.current = abortCtrl;
const postLoadRefresh = { needed: false };
let cpuFallbackReason: CpuFallbackReason | null = null;
+ let mmprojFallbackReason: MmprojFallbackReason | null = null;
try {
async function performLoad(): Promise<void> {
if (abortCtrl.signal.aborted) throw new Error("Cancelled");
@@ -1524,8 +1527,11 @@ export function useChatModelRuntime() {
tensor_split: loadSplitRatio ?? undefined,
gpu_ids: loadSelectedGpuIds ?? undefined,
force_cancel_active: forceCancelActive,
+
+ force_reload: forceReload,
});
cpuFallbackReason = loadResponse.cpu_fallback_reason ?? null;
+ mmprojFallbackReason = loadResponse.mmproj_fallback_reason ?? null;
// If cancelled while loading, don't update UI to show
// the model as active -- it's being unloaded.
@@ -1729,6 +1735,7 @@ export function useChatModelRuntime() {
chatTemplateOverride: effectiveChatTemplateOverride,
loadedChatTemplateOverride: effectiveChatTemplateOverride,
loadedIsMultimodal: isMultimodalResponse(loadResponse),
+ mmprojFallbackReason: loadResponse.mmproj_fallback_reason ?? null,
loadedIsDiffusion: loadResponse.is_diffusion ?? false,
activeModelIsLocal: loadResponse.is_local_model ?? false,
activeLoadId: loadPath === modelId ? null : loadPath,
@@ -2194,13 +2201,21 @@ 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;
+ const mmprojNotice = mmprojFallbackReason
+ ? mmprojLoadNotice(toastDisplayName, mmprojFallbackReason)
+ : null;
+ const loadedTitle = mmprojNotice
+ ? mmprojNotice.title
+ : cpuFallbackReason
+ ? `${toastDisplayName} loaded on CPU`
+ : `${toastDisplayName} loaded`;
+ const loadedDescription = mmprojNotice
+ ? mmprojNotice.description
+ : cpuFallbackReason
+ ? "The auto-selected Vulkan backend crashed during startup, so GPU acceleration is disabled for this model session."
+ : undefined;
+ const showLoadedToast =
+ mmprojNotice || cpuFallbackReason ? toast.warning : toast.success;
if (loadToastDismissedRef.current) {
showLoadedToast(loadedTitle, {
description: loadedDescription,
diff --git a/studio/frontend/src/features/chat/lib/apply-inference-status-to-store.ts b/studio/frontend/src/features/chat/lib/apply-inference-status-to-store.ts
index 702616fab00..6883dbab3cf 100644
--- a/studio/frontend/src/features/chat/lib/apply-inference-status-to-store.ts
+++ b/studio/frontend/src/features/chat/lib/apply-inference-status-to-store.ts
@@ -362,6 +362,7 @@ export function applyActiveModelStatusToStore(
loadedIsDiffusion: status.is_diffusion ?? false,
activeModelIsLocal: status.is_local_model ?? false,
specFallbackReason: status.spec_fallback_reason ?? null,
+ mmprojFallbackReason: status.mmproj_fallback_reason ?? null,
specDrafterKind: status.spec_drafter_kind ?? null,
// The spec / KV seeds share the GPU-fields reseed mechanism below: a
// non-GGUF status leaves their loaded baselines null, so the "unseeded"
diff --git a/studio/frontend/src/features/chat/runtime-provider.tsx b/studio/frontend/src/features/chat/runtime-provider.tsx
index 9de0442e88a..f7733e2e64d 100644
--- a/studio/frontend/src/features/chat/runtime-provider.tsx
+++ b/studio/frontend/src/features/chat/runtime-provider.tsx
@@ -218,6 +218,7 @@ class VisionImageAdapter implements AttachmentAdapter {
loadedIsMultimodal: state.loadedIsMultimodal,
modelLoaded,
loadError: state.lastModelLoadError,
+ mmprojFallbackReason: state.mmprojFallbackReason,
});
if (unavailableReason) {
toast.error(unavailableReason);
diff --git a/studio/frontend/src/features/chat/shared-composer.tsx b/studio/frontend/src/features/chat/shared-composer.tsx
index 480b2ef4d94..4a40d1da19f 100644
--- a/studio/frontend/src/features/chat/shared-composer.tsx
+++ b/studio/frontend/src/features/chat/shared-composer.tsx
@@ -592,6 +592,9 @@ export function SharedComposer({
);
const lastModelLoadError = useChatRuntimeStore((s) => s.lastModelLoadError);
const loadedIsMultimodal = useChatRuntimeStore((s) => s.loadedIsMultimodal);
+ const mmprojFallbackReason = useChatRuntimeStore(
+ (s) => s.mmprojFallbackReason,
+ );
const supportsReasoning = useChatRuntimeStore((s) => s.supportsReasoning);
const reasoningAlwaysOn = useChatRuntimeStore((s) => s.reasoningAlwaysOn);
const reasoningEnabled = useChatRuntimeStore((s) => s.reasoningEnabled);
@@ -671,6 +674,7 @@ export function SharedComposer({
loadedIsMultimodal,
modelLoaded,
loadError: lastModelLoadError,
+ mmprojFallbackReason,
});
const isCompareMode = Boolean(model1?.id || model2?.id);
// Attach-time gate. Compare mode defers to send: the catalog can lag a
@@ -1621,6 +1625,8 @@ export function SharedComposer({
// GPU fields on every load path so the gate can't read stale.
loadedIsDiffusion: resp.is_diffusion ?? false,
loadedIsMultimodal: isMultimodalResponse(resp),
+
+ mmprojFallbackReason: resp.mmproj_fallback_reason ?? null,
activeModelIsLocal: resp.is_local_model ?? false,
// Record the context this pane loaded with (like the single-model path)
// so when it becomes the active model, the UI and later reload/save use
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 2a22659e96a..72ce9dd92ce 100644
--- a/studio/frontend/src/features/chat/stores/chat-runtime-store.ts
+++ b/studio/frontend/src/features/chat/stores/chat-runtime-store.ts
@@ -74,6 +74,7 @@ import {
type ModelLifecycleLease,
} from "../utils/model-lifecycle-gate";
import { shouldAdvanceQueuedSettingsEpoch } from "../utils/queued-settings-epoch";
+import type { MmprojFallbackReason } from "../types/api";
import type { ResearchWebsitePolicy } from "../types/research";
import { useExternalProvidersStore } from "./external-providers-store";
import { PLUS_MENU_PINS_STORAGE_KEY } from "./plus-menu-prefs-store";
@@ -2304,6 +2305,8 @@ type ChatRuntimeStore = {
* Mirrors InferenceStatusResponse.spec_fallback_reason.
*/
specFallbackReason: string | null;
+ /** Projector recovery outcome for the active GGUF, or null. */
+ mmprojFallbackReason: MmprojFallbackReason | null;
/**
* Which drafter the loaded model's speculative resolution was about: "mtp",
* "dspark" or "dflash". Paired with specFallbackReason: the reason alone cannot name the
@@ -3392,6 +3395,7 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({
speculativeType: readPersistedSpeculativeType(),
loadedSpeculativeType: null,
specFallbackReason: null,
+ mmprojFallbackReason: null,
specDrafterKind: null,
specDraftNMax: null,
loadedSpecDraftNMax: null,
@@ -3861,6 +3865,7 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({
contextUsageByThreadId: {},
activeModelIsLocal: false,
specFallbackReason: null,
+ mmprojFallbackReason: null,
specDrafterKind: null,
}
: {}),
@@ -4103,6 +4108,7 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({
speculativeType: readPersistedSpeculativeType(),
loadedSpeculativeType: null,
specFallbackReason: null,
+ mmprojFallbackReason: null,
specDrafterKind: null,
specDraftNMax: null,
loadedSpecDraftNMax: null,
diff --git a/studio/frontend/src/features/chat/types/api.ts b/studio/frontend/src/features/chat/types/api.ts
index 24bafe455b6..190107b8213 100644
--- a/studio/frontend/src/features/chat/types/api.ts
+++ b/studio/frontend/src/features/chat/types/api.ts
@@ -5,6 +5,11 @@ import type { TransformersUpgradeInfo } from "@/features/transformers-upgrade";
export type CpuFallbackReason = "vulkan_startup_crash";
+export type MmprojFallbackReason =
+ | "cpu_offload"
+ | "projector_incompatible"
+ | "projector_startup_failure";
+
export interface BackendModelDetails {
id: string;
name?: string | null;
@@ -41,6 +46,9 @@ export interface LoadModelRequest {
model_path: string;
/** Opaque client attempt ID used to cancel only this in-flight load. */
load_request_id?: string | null;
+
+ /** Start a fresh runtime even when the active settings already match. */
+ force_reload?: boolean;
/**
* Stop any chats still generating instead of getting a 409: a load replaces the single
* llama-server they all decode on. Set only after the user confirms.
@@ -247,6 +255,8 @@ export interface LoadModelResponse {
gpu_layers?: number;
/** Set when an automatic Vulkan startup crash was recovered by loading on CPU. */
cpu_fallback_reason?: CpuFallbackReason | null;
+ /** How Studio recovered after a multimodal projector failed at startup. */
+ mmproj_fallback_reason?: MmprojFallbackReason | null;
n_cpu_moe?: number;
tensor_split?: number[] | null;
n_layers?: number | null;
@@ -336,6 +346,8 @@ export interface InferenceStatusResponse {
gpu_layers?: number;
/** Set while the active model is a recovered CPU-only Vulkan load. */
cpu_fallback_reason?: CpuFallbackReason | null;
+ /** How the active GGUF recovered after a multimodal projector startup failure. */
+ mmproj_fallback_reason?: MmprojFallbackReason | 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/src/features/chat/utils/image-input-support.ts b/studio/frontend/src/features/chat/utils/image-input-support.ts
index 9ce6de39bad..0f44e489e3b 100644
--- a/studio/frontend/src/features/chat/utils/image-input-support.ts
+++ b/studio/frontend/src/features/chat/utils/image-input-support.ts
@@ -3,6 +3,20 @@
import type { ChatModelSummary } from "../types/runtime";
+import type { MmprojFallbackReason } from "../types/api";
+import { isTextOnlyMmprojFallback } from "./mmproj-fallback";
+
+function textOnlyMmprojUnavailableReason(
+ activeModel: ChatModelSummary | undefined,
+ reason: MmprojFallbackReason | null | undefined,
+): string | null {
+ if (!isTextOnlyMmprojFallback(reason)) {
+ return null;
+ }
+ const label = activeModel?.name || activeModel?.id || "This vision model";
+ return `${label}'s vision projector failed to start, so Studio reloaded it in text-only mode. Free memory or update Studio, then reload the model before attaching images.`;
+}
+
export function getImageInputUnavailableReason({
activeModel,
isExternalModel,
@@ -11,6 +25,7 @@ export function getImageInputUnavailableReason({
loadedIsMultimodal,
modelLoaded,
loadError,
+ mmprojFallbackReason,
}: {
activeModel?: ChatModelSummary;
isExternalModel: boolean;
@@ -24,6 +39,7 @@ export function getImageInputUnavailableReason({
modelLoaded: boolean;
// Runtime lastModelLoadError; lets the no-model branch flag a failed load.
loadError?: string | null;
+ mmprojFallbackReason?: MmprojFallbackReason | null;
}): string | null {
if (isExternalModel) {
const explicitlyNonVision =
@@ -49,6 +65,14 @@ export function getImageInputUnavailableReason({
}
return "Load a model before adding images.";
}
+ const fallbackReason = textOnlyMmprojUnavailableReason(
+ activeModel,
+ mmprojFallbackReason,
+ );
+ if (fallbackReason) {
+ return fallbackReason;
+ }
+
// loadedIsMultimodal is true for vision OR audio; that one flag can't tell
// them apart, so only block when activeModel confirms audio-only (audio
// capability set AND isVision === false). Otherwise trust the load
@@ -57,12 +81,16 @@ export function getImageInputUnavailableReason({
const isAudioOnly =
Boolean(activeModel?.isAudio || activeModel?.hasAudioInput) &&
activeModel?.isVision === false;
- if (!isAudioOnly) return null;
+ if (!isAudioOnly) {
+ return null;
+ }
}
-
const label = activeModel?.name || activeModel?.id || "Current model";
const suffix = activeModel?.isGguf
? " with a valid mmproj before attaching images."
: " before attaching images.";
- return `${label} cannot accept images. Load a vision-capable model${suffix}`;
+ return (
+ fallbackReason ??
+ `${label} cannot accept images. Load a vision-capable model${suffix}`
+ );
}
diff --git a/studio/frontend/src/features/chat/utils/mmproj-fallback.ts b/studio/frontend/src/features/chat/utils/mmproj-fallback.ts
new file mode 100644
index 00000000000..c0c6259b6da
--- /dev/null
+++ b/studio/frontend/src/features/chat/utils/mmproj-fallback.ts
@@ -0,0 +1,39 @@
+// 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 type { MmprojFallbackReason } from "../types/api";
+
+const MMPROJ_FALLBACK_MESSAGES: Record<MmprojFallbackReason, string> = {
+ cpu_offload:
+ "The vision projector could not start on the GPU, so Studio moved it to system memory. Image input remains available, but image processing may be slower.",
+ projector_incompatible:
+ "The vision projector is incompatible with the installed llama.cpp build, so Studio reloaded this model in text-only mode. Update Studio, then reload the model to restore image input.",
+ projector_startup_failure:
+ "The vision projector could not start on the GPU or CPU, so Studio reloaded this model in text-only mode. Free memory or check the GPU logs, then reload the model to restore image input.",
+};
+
+export function isTextOnlyMmprojFallback(
+ reason: MmprojFallbackReason | null | undefined,
+): boolean {
+ return (
+ reason === "projector_incompatible" ||
+ reason === "projector_startup_failure"
+ );
+}
+
+export function mmprojFallbackMessage(reason: MmprojFallbackReason): string {
+ return MMPROJ_FALLBACK_MESSAGES[reason];
+}
+
+export function mmprojLoadNotice(
+ modelName: string,
+ reason: MmprojFallbackReason,
+): { title: string; description: string } {
+ return {
+ title:
+ reason === "cpu_offload"
+ ? `${modelName} loaded with vision on CPU`
+ : `${modelName} loaded without vision`,
+ description: mmprojFallbackMessage(reason),
+ };
+}
diff --git a/studio/frontend/tests/mmproj-fallback.test.ts b/studio/frontend/tests/mmproj-fallback.test.ts
new file mode 100644
index 00000000000..351f73b0d1b
--- /dev/null
+++ b/studio/frontend/tests/mmproj-fallback.test.ts
@@ -0,0 +1,117 @@
+import assert from "node:assert/strict";
+
+import { readFileSync } from "node:fs";
+import test from "node:test";
+import { registerBundlerResolver } from "./helpers/kit.ts";
+
+registerBundlerResolver();
+
+const { getImageInputUnavailableReason } = await import(
+ "../src/features/chat/utils/image-input-support.ts"
+);
+const { isTextOnlyMmprojFallback, mmprojFallbackMessage, mmprojLoadNotice } =
+ await import("../src/features/chat/utils/mmproj-fallback.ts");
+
+const IMAGE_INPUT_AVAILABLE = /Image input remains available/;
+const RELOADED_TEXT_ONLY = /reloaded this model in text-only mode/;
+const PROJECTOR_FAILED = /vision projector failed to start/;
+const TEXT_ONLY_MODE = /text-only mode/;
+const GENERIC_IMAGE_ERROR = /cannot accept images/;
+
+test("CPU projector fallback preserves image input and explains slower vision", () => {
+ assert.equal(isTextOnlyMmprojFallback("cpu_offload"), false);
+ const notice = mmprojLoadNotice("PaddleOCR", "cpu_offload");
+ assert.equal(notice.title, "PaddleOCR loaded with vision on CPU");
+ assert.match(notice.description, IMAGE_INPUT_AVAILABLE);
+});
+
+test("text-only projector fallback replaces the misleading generic mmproj error", () => {
+ assert.equal(isTextOnlyMmprojFallback("projector_startup_failure"), true);
+ assert.match(
+ mmprojFallbackMessage("projector_startup_failure"),
+ RELOADED_TEXT_ONLY,
+ );
+ const reason = getImageInputUnavailableReason({
+ activeModel: {
+ id: "PaddleOCR",
+ name: "PaddleOCR",
+ isVision: true,
+ isGguf: true,
+ isLora: false,
+ },
+ isExternalModel: false,
+ loadedIsMultimodal: false,
+ modelLoaded: true,
+ mmprojFallbackReason: "projector_startup_failure",
+ });
+ assert.match(reason ?? "", PROJECTOR_FAILED);
+ assert.match(reason ?? "", TEXT_ONLY_MODE);
+ assert.doesNotMatch(reason ?? "", GENERIC_IMAGE_ERROR);
+});
+
+test("text-only fallback overrides stale audio VLM capabilities", () => {
+ const reason = getImageInputUnavailableReason({
+ activeModel: {
+ id: "AudioVisionModel",
+ name: "AudioVisionModel",
+ isVision: true,
+ isGguf: true,
+ isLora: false,
+ isAudio: false,
+ hasAudioInput: true,
+ },
+ isExternalModel: false,
+ loadedIsMultimodal: true,
+ modelLoaded: true,
+ mmprojFallbackReason: "projector_startup_failure",
+ });
+ assert.match(reason ?? "", PROJECTOR_FAILED);
+ assert.match(reason ?? "", TEXT_ONLY_MODE);
+});
+
+function sourceBetween(path: string, start: string, end: string): string {
+ const source = readFileSync(new URL(path, import.meta.url), "utf8");
+ const startAt = source.indexOf(start);
+ assert.notEqual(startAt, -1, `Missing source marker: ${start}`);
+ const endAt = source.indexOf(end, startAt);
+ assert.notEqual(endAt, -1, `Missing source marker: ${end}`);
+ return source.slice(startAt, endAt);
+}
+
+test("attachment and send gates forward projector fallback state", () => {
+ const attachmentGate = sourceBetween(
+ "../src/features/chat/runtime-provider.tsx",
+ "const unavailableReason = getImageInputUnavailableReason({",
+ "if (unavailableReason)",
+ );
+ assert.match(
+ attachmentGate,
+ /mmprojFallbackReason:\s*state\.mmprojFallbackReason/,
+ );
+
+ const sendGate = sourceBetween(
+ "../src/features/chat/api/chat-adapter.ts",
+ "const imageGateReason = getImageInputUnavailableReason({",
+ "if (imageGateReason)",
+ );
+ assert.match(
+ sendGate,
+ /mmprojFallbackReason:\s*runtime\.mmprojFallbackReason/,
+ );
+ const compareLoadState = sourceBetween(
+ "../src/features/chat/shared-composer.tsx",
+ "useChatRuntimeStore.setState({",
+ "activeNativePathToken: null,",
+ );
+ assert.match(
+ compareLoadState,
+ /mmprojFallbackReason:\s*resp\.mmproj_fallback_reason\s*\?\?\s*null/,
+ );
+
+ const interactiveLoad = sourceBetween(
+ "../src/features/chat/hooks/use-chat-model-runtime.ts",
+ "loadResponse = await loadModel({",
+ "cpuFallbackReason = loadResponse.cpu_fallback_reason",
+ );
+ assert.match(interactiveLoad, /force_reload:\s*forceReload/);
+});