Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Studio: fall back to text-only when llama.cpp is too old for a model's vision projector (#6075)

Daniel Hanb21c419a51e2
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.py
index ead962aac79..3c582a695f6 100644
--- a/studio/backend/core/inference/llama_cpp.py
+++ b/studio/backend/core/inference/llama_cpp.py
@@ -2668,6 +2668,107 @@ class LlamaCppBackend:
"Check that the GGUF file is valid and you have enough memory."
)
+ @staticmethod
+ def _is_projector_incompatibility(output: str) -> bool:
+ """True when llama-server aborted because it cannot load the model's
+ vision/audio projector (mmproj), typically an installed llama.cpp
+ that predates the projector format. Conservative: only matches
+ projector-format errors so unrelated failures (OOM, bad GGUF, port
+ bind, ...) keep their own handling, and a bare 'clip'/'mmproj'
+ mention in a normal startup log does not match.
+ """
+ text = (output or "").lower()
+ if any(
+ m in text
+ for m in (
+ "unknown projector type",
+ "unsupported projector",
+ "unsupported mmproj",
+ )
+ ):
+ return True
+ # Builds that phrase it via clip.cpp without the exact words above.
+ return (
+ "clip" in text
+ and "projector" in text
+ and ("unknown" in text or "unsupported" in text or "not supported" in text)
+ )
+
+ @staticmethod
+ def _strip_mmproj_args(cmd: list[str]) -> list[str]:
+ """Return cmd without the '--mmproj <path>' pair (text-only retry).
+ Every other flag is preserved; a no-op when --mmproj is absent.
+ """
+ out: list[str] = []
+ skip_value = False
+ for tok in cmd:
+ if skip_value:
+ skip_value = False
+ continue
+ if tok == "--mmproj":
+ skip_value = True
+ continue
+ out.append(tok)
+ return out
+
+ def _start_llama_process(self, cmd: list[str], env: dict) -> None:
+ """Spawn llama-server from cmd and start draining its output.
+
+ Caller holds self._lock. Resets the stdout buffer, opens a fresh
+ per-attempt tee log, launches the process, and starts the drain
+ thread. Used for the initial start and the text-only mmproj retry.
+ """
+ # Defensive kill: if a concurrent load slipped past Phase 1
+ # (because its `self._process` was None at the time) and already
+ # stored a Popen handle here, drop that orphan before we overwrite
+ # the reference. See issue #5161.
+ self._kill_process()
+
+ self._stdout_lines = []
+ # Tee llama-server output to a dedicated log file so a post-mortem
+ # in CI (or after a remote-debug session) has the full subprocess
+ # trail even when the parent only stored the last 50 lines.
+ self._llama_log_fh = None
+ try:
+ log_dir = _swa_cache_path().parent / "logs" / "llama-server"
+ log_dir.mkdir(parents = True, exist_ok = True)
+ self._llama_log_path = log_dir / f"llama-{int(time.time())}-port-{self._port}.log"
+ self._llama_log_fh = open(
+ self._llama_log_path,
+ "w",
+ encoding = "utf-8",
+ buffering = 1,
+ )
+ logger.info(f"llama-server stdout/stderr -> {self._llama_log_path}")
+ except OSError as e:
+ # Best-effort; never block the load on logging.
+ logger.debug(f"Could not open llama-server log file: {e}")
+ self._llama_log_path = None
+
+ # Log the argv per attempt (the text-only mmproj retry re-enters here
+ # with --mmproj stripped), redacting the API key.
+ _log_cmd = list(cmd)
+ if "--api-key" in _log_cmd:
+ _ki = _log_cmd.index("--api-key") + 1
+ if _ki < len(_log_cmd):
+ _log_cmd[_ki] = "<redacted>"
+ logger.info(f"Starting llama-server: {' '.join(_log_cmd)}")
+
+ self._process = subprocess.Popen(
+ cmd,
+ stdout = subprocess.PIPE,
+ stderr = subprocess.STDOUT,
+ text = True,
+ env = env,
+ **_windows_hidden_subprocess_kwargs(),
+ )
+
+ # Start background thread to drain stdout and prevent pipe deadlock
+ self._stdout_thread = threading.Thread(
+ target = self._drain_stdout, daemon = True, name = "llama-stdout"
+ )
+ self._stdout_thread.start()
+
def load_model(
self,
*,
@@ -3346,6 +3447,9 @@ class LlamaCppBackend:
except Exception as e:
logger.debug("Failed to set ROCm visibility env vars for child: %s", e)
+ # Captured before any text-only fallback strips it from cmd.
+ launched_with_mmproj = "--mmproj" in cmd
+
# One-shot --fit off retry: recent llama.cpp runs a "fitting
# params to device memory" step by default (--fit defaults to
# 'on') even when -ngl is explicit. That step has aborted on
@@ -3520,15 +3624,43 @@ class LlamaCppBackend:
if healthy:
self._speculative_type = "default"
+ # A vision GGUF launched with --mmproj can abort when the
+ # installed llama.cpp is too old for the model's projector
+ # ("Unknown projector type"); in that one case retry once
+ # text-only rather than failing the whole load.
if not healthy:
+ out = "\n".join(self._stdout_lines[-50:])
self._kill_process()
- raise RuntimeError(
- self._classify_llama_start_failure(
- "\n".join(self._stdout_lines[-50:]),
- gguf_path,
- self._model_identifier,
+ if launched_with_mmproj and self._is_projector_incompatibility(out):
+ 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."
+ )
+ cmd = self._strip_mmproj_args(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):
+ self._kill_process()
+ raise RuntimeError(
+ "Vision projector incompatible with this llama.cpp "
+ "build, and the text-only retry also failed: "
+ + self._classify_llama_start_failure(
+ "\n".join(self._stdout_lines[-50:]),
+ gguf_path,
+ self._model_identifier,
+ )
+ )
+ else:
+ raise RuntimeError(
+ self._classify_llama_start_failure(
+ out,
+ gguf_path,
+ self._model_identifier,
+ )
)
- )
self._healthy = True
diff --git a/studio/backend/tests/test_llama_cpp_mmproj_fallback.py b/studio/backend/tests/test_llama_cpp_mmproj_fallback.py
new file mode 100644
index 00000000000..6ef94545fe1
--- /dev/null
+++ b/studio/backend/tests/test_llama_cpp_mmproj_fallback.py
@@ -0,0 +1,187 @@
+# 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.
+"""
+
+from __future__ import annotations
+
+import sys
+import types as _types
+from pathlib import Path
+
+import pytest
+
+_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)
+if _BACKEND_DIR not in sys.path:
+ sys.path.insert(0, _BACKEND_DIR)
+
+# Match the stubbing pattern in sibling tests so the module imports in a
+# lightweight env without fastapi.
+_loggers_stub = _types.ModuleType("loggers")
+_loggers_stub.get_logger = lambda name: __import__("logging").getLogger(name)
+sys.modules.setdefault("loggers", _loggers_stub)
+_structlog_stub = _types.ModuleType("structlog")
+_structlog_stub.get_logger = lambda *a, **k: __import__("logging").getLogger("structlog")
+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
+
+_detect = LlamaCppBackend._is_projector_incompatibility
+_strip = LlamaCppBackend._strip_mmproj_args
+
+# 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"
+ "/build_work/src/llama.cpp-b9496/tools/mtmd/clip.cpp:4391: "
+ "Unknown projector type\n"
+ "libggml-base.so.0(ggml_abort+0x152)\n"
+ "libmtmd.so.0(clip_n_mmproj_embd)\n"
+)
+# Unrelated failures that must keep their own handling (no projector retry).
+_OOM_OUT = (
+ "ggml_backend_cuda_buffer_type_alloc_buffer: allocating 12000.00 MiB on "
+ "device 0: cudaMalloc failed: out of memory"
+)
+_BAD_ARCH_OUT = "llama_model_load: error loading model: unknown model architecture: 'qwen_image'"
+_PORT_OUT = "srv start: failed to bind: address already in use"
+_MISSING_OUT = "error: failed to open GGUF file: no such file or directory"
+# A healthy startup log that merely mentions the projector must not match.
+_HEALTHY_VISION_OUT = (
+ "Using mmproj for vision: /cache/mmproj-F16.gguf\n"
+ "clip_model_loader: loaded meta data with 20 key-value pairs\n"
+ "srv update_slots: all slots are idle"
+)
+
+
+class TestProjectorIncompatibilityDetector:
+ def test_gemma4_on_old_llamacpp_triggers_retry(self):
+ # Headline case: a 3-day-old llama.cpp aborts on Gemma-4's projector.
+ assert _detect(_GEMMA4_OLD_LLAMACPP_OUT) is True
+
+ @pytest.mark.parametrize(
+ "out",
+ [
+ "clip.cpp:4391: Unknown projector type",
+ "error: unsupported projector type for this model",
+ "llama_mmproj: unsupported mmproj file version",
+ "clip.cpp: projector type 'gemma4' is not supported",
+ ],
+ )
+ def test_projector_format_errors_match(self, out):
+ assert _detect(out) is True
+
+ def test_case_insensitive(self):
+ assert _detect("UNKNOWN PROJECTOR TYPE") is True
+
+ @pytest.mark.parametrize(
+ "out",
+ [
+ _OOM_OUT,
+ _BAD_ARCH_OUT,
+ _PORT_OUT,
+ _MISSING_OUT,
+ _HEALTHY_VISION_OUT,
+ "",
+ # bare multimodal words without a failure term must not match
+ "loading clip model",
+ "mmproj file resolved from cache",
+ ],
+ )
+ def test_unrelated_failures_do_not_retry(self, out):
+ assert _detect(out) is False
+
+
+# A realistic vision launch argv (mirrors the live "Starting llama-server"
+# command), projector pair at the end.
+_VISION_CMD = [
+ "/home/u/.unsloth/llama.cpp/build/bin/llama-server",
+ "-m",
+ "/cache/gemma-4-E2B-it-UD-Q4_K_XL.gguf",
+ "--port",
+ "55473",
+ "-c",
+ "131072",
+ "--parallel",
+ "1",
+ "--flash-attn",
+ "on",
+ "--no-context-shift",
+ "-ngl",
+ "-1",
+ "--threads",
+ "-1",
+ "--jinja",
+ "--spec-default",
+ "--mmproj",
+ "/cache/mmproj-F16.gguf",
+]
+
+
+class TestStripMmprojArgs:
+ def test_removes_mmproj_pair(self):
+ stripped = _strip(_VISION_CMD)
+ assert "--mmproj" not in stripped
+ assert "/cache/mmproj-F16.gguf" not in stripped
+
+ def test_preserves_every_text_flag(self):
+ stripped = _strip(_VISION_CMD)
+ for flag in (
+ "-m",
+ "/cache/gemma-4-E2B-it-UD-Q4_K_XL.gguf",
+ "--port",
+ "55473",
+ "-c",
+ "131072",
+ "-ngl",
+ "-1",
+ "--jinja",
+ "--spec-default",
+ "--flash-attn",
+ "on",
+ ):
+ assert flag in stripped
+ # Exactly the two projector tokens are dropped.
+ assert len(stripped) == len(_VISION_CMD) - 2
+
+ def test_strips_mmproj_in_the_middle(self):
+ cmd = ["llama-server", "--mmproj", "/p/mm.gguf", "-c", "4096", "--jinja"]
+ assert _strip(cmd) == ["llama-server", "-c", "4096", "--jinja"]
+
+ def test_noop_when_no_mmproj(self):
+ cmd = ["llama-server", "-m", "/p/model.gguf", "-c", "4096", "--jinja"]
+ assert _strip(cmd) == cmd
+
+ def test_returns_new_list(self):
+ cmd = ["llama-server", "--mmproj", "/p/mm.gguf"]
+ out = _strip(cmd)
+ assert out is not cmd
+ assert cmd[-1] == "/p/mm.gguf" # input untouched
+
+
+class TestRetryContract:
+ """The two helpers compose into the load_model retry decision."""
+
+ def test_gemma4_failure_yields_valid_text_only_command(self):
+ # Old-llama.cpp projector abort -> retry, and the retry argv is a
+ # valid text-only launch (model + context kept, projector gone).
+ assert _detect(_GEMMA4_OLD_LLAMACPP_OUT) is True
+ retry_cmd = _strip(_VISION_CMD)
+ 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.
+ assert _detect(_OOM_OUT) is False