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: gate --flash-attn, --no-context-shift and --jinja on the binary (#8710)

Daniel Han70a0f1a1b321
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.py
index 61bfe93a0e8..1c1d08b3828 100644
--- a/studio/backend/core/inference/llama_cpp.py
+++ b/studio/backend/core/inference/llama_cpp.py
@@ -4834,6 +4834,27 @@ class LlamaCppBackend:
_capability_retry_after: dict[tuple[str, int, int], float] = {}
_capability_cache_lock = threading.Lock()
+ # The value form of the flash-attention flag. Newer llama.cpp declares it
+ # with an enum, "-fa, --flash-attn [on|off|auto]"; older builds take a bare
+ # boolean and reject a following "on" as a stray positional, which is an
+ # immediate "invalid argument" exit rather than a degraded launch.
+ _FLASH_ATTN_ENUM_RE = re.compile(
+ r"(?im)^[^\n]*--flash-attn[^\n]*\bon\b[ \t]*\|[ \t]*\boff\b[^\n]*$"
+ )
+
+ @classmethod
+ def _flash_attn_takes_value(cls, help_text: str) -> bool:
+ """Whether this build's --flash-attn accepts on/off/auto.
+
+ Fails open: a build whose help never mentions the flag at all keeps
+ today's behaviour, because the pinned prebuilt is the value form and a
+ wrong answer there would break the supported path for a hypothetical
+ one.
+ """
+ if not help_text or "--flash-attn" not in help_text:
+ return True
+ return bool(cls._FLASH_ATTN_ENUM_RE.search(help_text))
+
@classmethod
def probe_server_capabilities(cls, binary: Optional[str] = None) -> dict[str, object]:
"""Parse `llama-server --help` for feature flags. Returns
@@ -4870,6 +4891,13 @@ class LlamaCppBackend:
"supports_ngram_mod": False,
"spec_draft_n_max_flag": None,
"supports_kv_unified": False,
+ # Fail OPEN, unlike every key above. These three are emitted on
+ # every launch today, so a failed probe must keep emitting them;
+ # only a build whose --help positively lacks one drops it.
+ "supports_no_context_shift": True,
+ "supports_jinja": True,
+ "supports_flash_attn": True,
+ "flash_attn_takes_value": True,
"supports_fit_ctx": False,
"supports_fit_target": False,
"supports_cache_ram": False,
@@ -4906,6 +4934,11 @@ class LlamaCppBackend:
ngram_mod_flavor: Optional[str] = None
spec_draft_n_max_flag: Optional[str] = None
supports_kv_unified = False
+ # See the fallback dict: these fail open.
+ supports_no_context_shift = True
+ supports_jinja = True
+ supports_flash_attn = True
+ flash_attn_takes_value = True
supports_fit_ctx = False
supports_fit_target = False
supports_cache_ram = False
@@ -5042,6 +5075,19 @@ class LlamaCppBackend:
spec_draft_n_max_flag = "--draft-max"
supports_kv_unified = _is_real("--kv-unified")
+ # Only once the help actually parsed AND `--help` succeeded. Empty
+ # `blocks` means the probe told us nothing, and a nonzero exit means
+ # the listing may be a fragment; neither may read as "absent" for a
+ # flag we would otherwise always send. A real llama-server prints
+ # usage and exits 0, so this costs no supported build anything.
+ if probe_ok and blocks:
+ supports_no_context_shift = _is_real("--no-context-shift")
+ supports_jinja = _is_real("--jinja")
+ # Two answers, not one: whether the flag exists, and whether its
+ # declaration takes a value. A build predating flash attention
+ # has neither, and emitting the flag there is an immediate exit.
+ supports_flash_attn = _is_real("--flash-attn")
+ flash_attn_takes_value = cls._flash_attn_takes_value(help_text)
supports_fit_ctx = _is_real("--fit-ctx")
supports_fit_target = _is_real("--fit-target")
supports_cache_ram = _is_real("--cache-ram")
@@ -5107,6 +5153,10 @@ class LlamaCppBackend:
"supports_ngram_mod": ngram_mod_flavor is not None,
"spec_draft_n_max_flag": spec_draft_n_max_flag,
"supports_kv_unified": supports_kv_unified,
+ "supports_no_context_shift": supports_no_context_shift,
+ "supports_jinja": supports_jinja,
+ "supports_flash_attn": supports_flash_attn,
+ "flash_attn_takes_value": flash_attn_takes_value,
"supports_fit_ctx": supports_fit_ctx,
"supports_fit_target": supports_fit_target,
"supports_cache_ram": supports_cache_ram,
@@ -11199,52 +11249,21 @@ class LlamaCppBackend:
return out if found else None
@staticmethod
- def _with_flash_attn_off(cmd: list[str]) -> Optional[list[str]]:
- """Return cmd with flash attention forced off, or None when its effective
- (last-wins) value is already off/absent so there is nothing to retry. FA
- kernels hard-crash at startup on some ROCm builds; disabling FA keeps
- vision and MTP, the least destructive rung. A bare --flash-attn/-fa reads
- as on, so it counts toward the effective value and is neutralised too;
- every form is flipped in place (length preserved for downstream slices)."""
+ def _reset_quantized_v_cache(cmd: list[str], reason: str) -> list[str]:
+ """Return cmd with any quantized V cache reset to f16, for a launch that
+ runs without flash attention.
+
+ A quantized V cache requires flash attention in llama.cpp: the init aborts
+ with "V cache quantization requires flash_attn". A quantized K cache has no
+ such requirement and runs fine without FA, so it is left untouched --
+ resetting it would needlessly enlarge the K cache and can OOM a
+ memory-constrained config. Main and draft are both reset (the draft context
+ shares the global --flash-attn flag, so its V cache aborts too) to f16 (the
+ llama.cpp default); non-quantized types -- f16/bf16/f32 -- run fine without
+ FA and are left untouched. The value is rewritten in place so the list
+ length is preserved for downstream slices.
+ """
out = list(cmd)
-
- def explicit(i):
- nxt = out[i + 1] if i + 1 < len(out) else None
- return nxt if nxt in _LLAMA_ARG_TRUE_FALSE_AUTO_VALUES else None
-
- effective = None
- for i, tok in enumerate(out):
- name = _flag_name(tok)
- if name in ("--flash-attn", "-fa") and "=" in tok:
- effective = tok.partition("=")[2]
- elif name in ("--flash-attn", "-fa"):
- effective = explicit(i) or "on"
- if effective not in _LLAMA_ARG_TRUE_OR_AUTO_VALUES:
- return None
- for i, tok in enumerate(out):
- name = _flag_name(tok)
- if name in ("--flash-attn", "-fa") and "=" in tok:
- flag, _, value = tok.partition("=")
- if value in _LLAMA_ARG_TRUE_OR_AUTO_VALUES:
- out[i] = f"{flag}=off"
- elif name in ("--flash-attn", "-fa"):
- if explicit(i) in _LLAMA_ARG_TRUE_OR_AUTO_VALUES:
- out[i + 1] = "off"
- elif explicit(i) is None: # bare flag (reads as on) -> explicit off
- out[i] = f"{tok}=off"
-
- # A quantized V cache requires flash attention in llama.cpp: the init
- # aborts with "V cache quantization requires flash_attn". A quantized K
- # cache has no such requirement and runs fine without FA, so it is left
- # untouched -- resetting it would needlessly enlarge the K cache and can
- # OOM a memory-constrained config. Studio launches with FA on, so a
- # quantized --cache-type-v is legal at launch but would make THIS FA-off
- # retry crash on init instead of recovering. Reset a quantized V cache --
- # main and draft (the draft context shares the global --flash-attn flag,
- # so its V cache aborts too) -- to f16 (the llama.cpp default);
- # non-quantized types -- f16/bf16/f32 -- run fine without FA and are left
- # untouched. The value is rewritten in place so the list length is
- # preserved for downstream slices, matching the flash-attn flip above.
_v_cache_flags = (
"--cache-type-v",
"-ctv",
@@ -11274,12 +11293,65 @@ class LlamaCppBackend:
_cache_reset = True
if _cache_reset:
logger.info(
- "V cache dtype reset to f16 because flash attention was disabled "
- "by the crash-recovery fallback (quantized V cache requires flash "
- "attention in llama.cpp; the K cache is left untouched)."
+ "V cache dtype reset to f16 because flash attention is off (%s): a "
+ "quantized V cache requires flash attention in llama.cpp. The K "
+ "cache is left untouched.",
+ reason,
)
return out
+ @staticmethod
+ def _with_flash_attn_off(cmd: list[str]) -> Optional[list[str]]:
+ """Return cmd with flash attention forced off, or None when its effective
+ (last-wins) value is already off/absent so there is nothing to retry. FA
+ kernels hard-crash at startup on some ROCm builds; disabling FA keeps
+ vision and MTP, the least destructive rung. A bare --flash-attn/-fa reads
+ as on, so it counts toward the effective value and is neutralised too --
+ by dropping it, since only the older boolean builds accept the bare form
+ and they take no value. Valued forms are flipped in place."""
+ out = list(cmd)
+
+ def explicit(i):
+ nxt = out[i + 1] if i + 1 < len(out) else None
+ return nxt if nxt in _LLAMA_ARG_TRUE_FALSE_AUTO_VALUES else None
+
+ effective = None
+ for i, tok in enumerate(out):
+ name = _flag_name(tok)
+ if name in ("--flash-attn", "-fa") and "=" in tok:
+ effective = tok.partition("=")[2]
+ elif name in ("--flash-attn", "-fa"):
+ effective = explicit(i) or "on"
+ if effective not in _LLAMA_ARG_TRUE_OR_AUTO_VALUES:
+ return None
+ # A bare flag cannot be turned off in place: llama.cpp looks each argv
+ # token up verbatim (only '_' -> '-'), so --flash-attn=off is "invalid
+ # argument" everywhere, and the boolean builds that are the only ones
+ # accepting the bare form take no value at all. Dropping the token is
+ # what disables FA there. Collected first, removed back to front, so the
+ # indices stay valid.
+ bare_at: list[int] = []
+ for i, tok in enumerate(out):
+ name = _flag_name(tok)
+ if name in ("--flash-attn", "-fa") and "=" in tok:
+ flag, _, value = tok.partition("=")
+ if value in _LLAMA_ARG_TRUE_OR_AUTO_VALUES:
+ out[i] = f"{flag}=off"
+ elif name in ("--flash-attn", "-fa"):
+ if explicit(i) in _LLAMA_ARG_TRUE_OR_AUTO_VALUES:
+ out[i + 1] = "off"
+ elif explicit(i) is None: # bare flag (reads as on) -> drop it
+ bare_at.append(i)
+ for i in reversed(bare_at):
+ del out[i]
+
+ # Studio launches with FA on, so a quantized --cache-type-v is legal at
+ # launch but would make THIS FA-off retry crash on init instead of
+ # recovering.
+ return LlamaCppBackend._reset_quantized_v_cache(
+ out, "disabled by the crash-recovery fallback"
+ )
+
@staticmethod
def _drop_env_quantized_v_cache(env: MutableMapping[str, str]) -> bool:
"""Drop an inherited quantized V-cache env var (main or draft) in place
@@ -11302,6 +11374,19 @@ class LlamaCppBackend:
dropped = True
return dropped
+ @staticmethod
+ def _drop_env_flash_attn(env: MutableMapping[str, str]) -> bool:
+ """Drop an inherited LLAMA_ARG_FLASH_ATTN in place before a flash-attn-off
+ retry, returning True if anything was removed.
+
+ On the older builds whose --flash-attn takes no value the argv rewrite can
+ only drop the flag, never negate it, and llama.cpp reads the env var before
+ parsing argv, so LLAMA_ARG_FLASH_ATTN=1 would turn the kernel that just
+ crashed straight back on. Newer builds get an explicit --flash-attn off,
+ which already beats the env, so dropping it changes nothing there.
+ """
+ return env.pop("LLAMA_ARG_FLASH_ATTN", None) is not None
+
@staticmethod
def _strip_mmproj_args(cmd: list[str]) -> list[str]:
"""Return cmd without the '--mmproj <path>' pair (text-only retry).
@@ -12042,6 +12127,11 @@ class LlamaCppBackend:
# clamp before an HF download, command build after), and with a 30s window a
# later success would otherwise erase an earlier one that already degraded it.
_launch_probe_inconclusive = False
+ # Set where flash attention ends up off with the argv unable to say
+ # so: a build that has no --flash-attn at all, and the crash-recovery
+ # retry on a build whose flag takes no value, which disables FA by
+ # dropping it. Either way the default below has to carry the answer.
+ _flash_attn_known_off = False
def _launch_caps(bin_path):
nonlocal _launch_probe_inconclusive
@@ -14143,6 +14233,14 @@ class LlamaCppBackend:
except Exception as e:
logger.debug(f"mmproj audio-capability read failed: {e}")
+ # Gated like every other optional flag, but failing OPEN: these
+ # are emitted on every launch, so an unreadable --help keeps
+ # today's command and only a build that positively lacks one
+ # drops it. Harmless for the pinned prebuilt, which has all
+ # three; the case this covers is a stale or user-supplied
+ # LLAMA_SERVER_PATH, where an unknown argument is an immediate
+ # exit rather than a degraded launch.
+ _caps = _launch_caps(binary)
cmd = [
binary,
"-m",
@@ -14151,11 +14249,23 @@ class LlamaCppBackend:
str(self._port),
"--parallel",
str(n_parallel),
- "--flash-attn",
- "on", # Force flash attention for speed
- # Error out at n_ctx instead of silently rotating the KV cache; frontend catches it and points the user at "Context Length".
- "--no-context-shift",
]
+ # Force flash attention for speed. Two separate answers: whether
+ # the build has the flag at all (predates flash attention, or a
+ # wrapper that never exposed it), and whether its declaration
+ # takes a value -- older builds take -fa as a bare boolean and
+ # read a following "on" as a stray positional.
+ if _caps.get("supports_flash_attn", True):
+ cmd.append("--flash-attn")
+ if _caps.get("flash_attn_takes_value", True):
+ cmd.append("on")
+ else:
+ # Only ever reached on an authoritative --help that has no
+ # flash attention to lose, so there is no speed to give up.
+ _flash_attn_known_off = True
+ # Error out at n_ctx instead of silently rotating the KV cache; frontend catches it and points the user at "Context Length".
+ if _caps.get("supports_no_context_shift", True):
+ cmd.append("--no-context-shift")
# A positive context is always passed (in auto-fit, --fit then
# optimizes the gpu-layer offload around it). When auto-fit has
# no explicit context, omit -c so --fit sizes it to fit VRAM:
@@ -14340,7 +14450,8 @@ class LlamaCppBackend:
cmd.extend(["--threads", str(n_threads)])
# Enable Jinja chat template rendering
- cmd.extend(["--jinja"])
+ if _caps.get("supports_jinja", True):
+ cmd.extend(["--jinja"])
# KV cache data type
_valid_cache_types = {
@@ -14837,6 +14948,18 @@ class LlamaCppBackend:
if _pv_device_pin:
cmd.extend(_pv_device_pin)
+ # A build with no --flash-attn cannot run a quantized V cache
+ # either: llama.cpp aborts init with "V cache quantization
+ # requires flash_attn", and the KV type is emitted from the
+ # user's setting with no flash-attn coupling. The crash-recovery
+ # rung resets V for exactly that abort, but it only fires when
+ # the argv had a flag to turn off, so on a build that never had
+ # one nothing would catch it. Before the log below, so what is
+ # logged is what launches; length is preserved, so _spec_start
+ # still indexes the same tokens.
+ if _flash_attn_known_off:
+ cmd = self._reset_quantized_v_cache(cmd, "this build has no --flash-attn")
+
kv_cache_unified = _kv_unified_from_args(cmd)
logger.info(f"Starting llama-server: {' '.join(self._redacted_cmd_for_log(cmd))}")
@@ -14892,6 +15015,23 @@ class LlamaCppBackend:
# arg handler and silently force hardware_concurrency(). #5692
if "--threads" not in cmd:
env.pop("LLAMA_ARG_THREADS", None)
+ # A build whose help has no --flash-attn never registers the option,
+ # so it never reads LLAMA_ARG_FLASH_ATTN either (llama.cpp resolves
+ # each env var through the arg that declares it). Leaving an
+ # inherited one in place would only fool the accounting below, which
+ # reads env plus argv and would then record flash attention as on for
+ # a server running without it, under-sizing the padded V cache.
+ if _flash_attn_known_off and self._drop_env_flash_attn(env):
+ logger.info(
+ "Dropped inherited LLAMA_ARG_FLASH_ATTN: this build has no --flash-attn."
+ )
+ # Same for an env-only quantized V cache, which the argv reset
+ # above cannot reach.
+ if _flash_attn_known_off and self._drop_env_quantized_v_cache(env):
+ logger.info(
+ "Dropped inherited quantized V-cache env: this build has "
+ "no --flash-attn."
+ )
# Reconcile the inherited LLAMA_ARG_* env with Unsloth's final
# decision: stripping CLI extras on a tensor->layer downgrade
@@ -15739,6 +15879,15 @@ class LlamaCppBackend:
"Dropped inherited quantized V-cache env for the "
"--flash-attn off retry (requires flash attention)."
)
+ # Same reach problem for the flag itself: where the rewrite
+ # could only drop a bare --flash-attn, the env var alone
+ # still enables it.
+ if self._drop_env_flash_attn(env):
+ logger.info(
+ "Dropped inherited LLAMA_ARG_FLASH_ATTN for the "
+ "--flash-attn off retry."
+ )
+ _flash_attn_known_off = True
cmd = _fa_cmd
healthy = _spawn_and_wait(_fa_cmd, label = "-noflash")
@@ -15794,6 +15943,15 @@ class LlamaCppBackend:
"Dropped inherited quantized V-cache env for the "
"--flash-attn off retry (requires flash attention)."
)
+ # Same reach problem for the flag itself: where the rewrite
+ # could only drop a bare --flash-attn, the env var alone
+ # still enables it.
+ if self._drop_env_flash_attn(env):
+ logger.info(
+ "Dropped inherited LLAMA_ARG_FLASH_ATTN for the "
+ "--flash-attn off retry."
+ )
+ _flash_attn_known_off = True
cmd = _fa_cmd
healthy = (
_spawn_and_wait(_fa_cmd, label = "-noflash-mtp")
@@ -16040,7 +16198,9 @@ class LlamaCppBackend:
int(self._DEFAULT_N_UBATCH if _launched_ubatch is None else _launched_ubatch),
)
self._flash_attn_enabled = (
- _flash_attn_enabled_from_args(_last_spawn_cmd, env = env)
+ _flash_attn_enabled_from_args(
+ _last_spawn_cmd, default = not _flash_attn_known_off, env = env
+ )
and self._architecture != "grok"
)
self._effective_cache_types = _effective_main_cache_types(
diff --git a/studio/backend/tests/test_launch_flags_are_capability_gated.py b/studio/backend/tests/test_launch_flags_are_capability_gated.py
new file mode 100644
index 00000000000..492c4d88419
--- /dev/null
+++ b/studio/backend/tests/test_launch_flags_are_capability_gated.py
@@ -0,0 +1,441 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Every launch flag is gated on the binary advertising it.
+
+The probe checks 17 optional flags with _is_real before emitting them, but
+--flash-attn, --no-context-shift and --jinja were emitted unconditionally. That
+is fine for the pinned prebuilt, which has all three. It is not fine for a stale
+or user-supplied LLAMA_SERVER_PATH, which Studio explicitly supports: an unknown
+argument makes llama-server exit immediately rather than start degraded, and the
+user sees a generic startup failure.
+
+These three differ from the other 17 in one important way: they are part of
+today's command on every launch, so their gates FAIL OPEN. An unreadable or
+unparseable --help must keep emitting them; only a build whose help positively
+lacks one may drop it.
+"""
+
+from __future__ import annotations
+
+import ast
+import inspect
+import logging
+import subprocess
+import sys
+import textwrap
+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)
+
+_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 import llama_cpp as llama_cpp_module # noqa: E402
+from core.inference.llama_cpp import ( # noqa: E402
+ LlamaCppBackend,
+ _flash_attn_enabled_from_args,
+)
+
+GATED = (
+ "supports_no_context_shift",
+ "supports_jinja",
+ "supports_flash_attn",
+ "flash_attn_takes_value",
+)
+
+# Help text as llama.cpp actually prints it: the declaration starts at column 0
+# and its description is padded to column 40 (common_arg::to_string).
+NEW_HELP = (
+ "usage: llama-server [options]\n"
+ "\n"
+ "-m, --model FNAME model path\n"
+ "-fa, --flash-attn [on|off|auto] set Flash Attention use ('on', 'off', or\n"
+ " 'auto', default: 'auto')\n"
+ "--context-shift, --no-context-shift whether to use context shift on infinite\n"
+ " text generation (default: disabled)\n"
+ "--jinja, --no-jinja whether to use jinja template engine for\n"
+ " chat (default: disabled)\n"
+)
+# The pre-enum vintage: -fa is a bare boolean and there is no --jinja.
+OLD_HELP = (
+ "usage: llama-server [options]\n"
+ "\n"
+ "-m, --model FNAME model path\n"
+ "-fa, --flash-attn enable Flash Attention (default: disabled)\n"
+ "--no-context-shift disables context shift on infinite text\n"
+ " generation\n"
+)
+# A build predating flash attention: the flag does not exist at all.
+NO_FLASH_ATTN_HELP = (
+ "usage: llama-server [options]\n"
+ "\n"
+ "-m, --model FNAME model path\n"
+ "-c, --ctx-size N size of the prompt context\n"
+ "--no-context-shift disables context shift on infinite text\n"
+ " generation\n"
+)
+# What a wrapper prints before it gives up: real flags, but only some of them.
+PARTIAL_HELP = (
+ "usage: llama-server [options]\n\n-m, --model FNAME model path\n"
+)
+
+
+def probe(
+ tmp_path,
+ monkeypatch,
+ help_text,
+ returncode = 0,
+ stream = "stdout",
+):
+ """Run the real probe against a stubbed ``llama-server --help``.
+
+ ``subprocess`` is stubbed rather than a script dropped on disk so the test
+ means the same thing on Windows, where a shebang file is not executable.
+ """
+ binary = tmp_path / "llama-server"
+ binary.write_text("")
+ completed = subprocess.CompletedProcess(
+ args = [str(binary), "--help"],
+ returncode = returncode,
+ stdout = help_text if stream == "stdout" else "",
+ stderr = help_text if stream == "stderr" else "",
+ )
+ monkeypatch.setattr(llama_cpp_module.subprocess, "run", lambda *a, **k: completed)
+ return LlamaCppBackend.probe_server_capabilities(str(binary))
+
+
+class TestTheGatesFailOpen:
+ """A failed or unreadable probe must not silently drop a flag."""
+
+ @pytest.mark.parametrize(
+ "label,help_text,returncode",
+ [
+ ("nothing at all", "", 1),
+ ("a banner but no flags", "Segmentation fault\n", 2),
+ ("a partial listing", PARTIAL_HELP, 1),
+ ("a full listing", NEW_HELP, 1),
+ ("an old-shaped partial listing", PARTIAL_HELP, 3),
+ ],
+ )
+ @pytest.mark.parametrize("key", GATED)
+ def test_a_nonzero_help_keeps_every_flag(
+ self, tmp_path, monkeypatch, label, help_text, returncode, key
+ ):
+ """A partial listing is still a FAILED probe.
+
+ The wrapper case that motivates this: it prints a few parseable options
+ and then exits nonzero. ``blocks`` is non-empty, but nothing in it is
+ authoritative, and reading it as "flag absent" would drop
+ ``--no-context-shift`` (context silently rotates again) or ``--jinja``
+ (no template rendering) on a launch the probe never understood.
+ """
+ assert probe(tmp_path, monkeypatch, help_text, returncode)[key] is True
+
+ @pytest.mark.parametrize("key", GATED)
+ def test_an_empty_help_does_not_read_as_absent(self, tmp_path, monkeypatch, key):
+ """Exit 0 with no output means the probe told us nothing, not "missing"."""
+ assert probe(tmp_path, monkeypatch, "", 0)[key] is True
+
+ @pytest.mark.parametrize("key", GATED)
+ def test_an_unprobeable_binary_keeps_every_flag(self, tmp_path, key):
+ assert LlamaCppBackend.probe_server_capabilities(str(tmp_path / "absent"))[key] is True
+
+ @pytest.mark.parametrize(
+ "key,default",
+ [
+ ("supports_no_context_shift", True),
+ ("supports_jinja", True),
+ ("supports_flash_attn", True),
+ ("flash_attn_takes_value", True),
+ ],
+ )
+ def test_the_emission_site_reads_the_key_with_a_true_default(self, key, default):
+ src = inspect.getsource(LlamaCppBackend.load_model)
+ assert f'_caps.get("{key}", {default})' in src
+
+
+class TestASuccessfulProbeIsAuthoritative:
+ """Exit 0 with a parseable listing is the one case that may drop a flag."""
+
+ def test_a_current_binary_keeps_all_three(self, tmp_path, monkeypatch):
+ caps = probe(tmp_path, monkeypatch, NEW_HELP)
+ assert caps["supports_no_context_shift"] is True
+ assert caps["supports_jinja"] is True
+ assert caps["flash_attn_takes_value"] is True
+
+ def test_an_older_binary_drops_what_it_lacks(self, tmp_path, monkeypatch):
+ caps = probe(tmp_path, monkeypatch, OLD_HELP)
+ assert caps["supports_no_context_shift"] is True
+ assert caps["supports_jinja"] is False
+ assert caps["supports_flash_attn"] is True
+ assert caps["flash_attn_takes_value"] is False
+
+ def test_a_build_without_flash_attention_drops_the_flag_itself(self, tmp_path, monkeypatch):
+ """The value form is not the only way -fa breaks a launch.
+
+ llama.cpp gained flash attention in b2775; anything older has no flag to
+ emit, and emitting it is an immediate "invalid argument" exit. Gating the
+ value alone would still send the flag. There is no speed to protect here:
+ the build the probe just read has no flash attention at all.
+ """
+ caps = probe(tmp_path, monkeypatch, NO_FLASH_ATTN_HELP)
+ assert caps["supports_flash_attn"] is False
+ assert caps["supports_no_context_shift"] is True
+
+ def test_the_missing_flag_still_fails_open_on_a_failed_probe(self, tmp_path, monkeypatch):
+ caps = probe(tmp_path, monkeypatch, NO_FLASH_ATTN_HELP, returncode = 1)
+ assert caps["supports_flash_attn"] is True
+
+ def test_help_on_stderr_reads_the_same(self, tmp_path, monkeypatch):
+ caps = probe(tmp_path, monkeypatch, NEW_HELP, stream = "stderr")
+ assert caps["supports_jinja"] is True
+ assert caps["flash_attn_takes_value"] is True
+
+ def test_windows_line_endings_read_the_same(self, tmp_path, monkeypatch):
+ caps = probe(tmp_path, monkeypatch, OLD_HELP.replace("\n", "\r\n"))
+ assert caps["supports_no_context_shift"] is True
+ assert caps["supports_jinja"] is False
+ assert caps["flash_attn_takes_value"] is False
+
+
+class TestFlashAttentionValueForm:
+ """The value form is the part that actually breaks an older binary."""
+
+ VALUE = "-fa, --flash-attn [on|off|auto] set flash attention"
+ BOOLEAN = "-fa, --flash-attn enable flash attention"
+
+ def test_an_enum_means_the_value_is_accepted(self):
+ assert LlamaCppBackend._flash_attn_takes_value(self.VALUE) is True
+
+ def test_a_bare_boolean_declaration_drops_the_value(self):
+ assert LlamaCppBackend._flash_attn_takes_value(self.BOOLEAN) is False
+
+ @pytest.mark.parametrize("help_text", ["", "-m, --model FNAME", "unrelated output"])
+ def test_it_fails_open_when_the_flag_is_not_mentioned(self, help_text):
+ assert LlamaCppBackend._flash_attn_takes_value(help_text) is True
+
+ def test_the_flag_and_its_value_are_gated_separately(self):
+ """Two independent answers, so a build that has the flag but not the
+ enum keeps flash attention, and one that has neither drops both."""
+ src = inspect.getsource(LlamaCppBackend.load_model)
+ assert '_caps.get("supports_flash_attn", True)' in src
+ assert 'cmd.append("--flash-attn")' in src
+ assert '_caps.get("flash_attn_takes_value", True)' in src
+
+ def test_the_real_master_declaration_reads_as_the_value_form(self):
+ assert LlamaCppBackend._flash_attn_takes_value(NEW_HELP) is True
+
+ def test_the_real_pre_enum_declaration_reads_as_boolean(self):
+ assert LlamaCppBackend._flash_attn_takes_value(OLD_HELP) is False
+
+
+class TestTheCrashRecoveryMatchesTheEmittedForm:
+ """``_with_flash_attn_off`` has to speak the same dialect the launch does.
+
+ llama.cpp looks every argv token up verbatim (only ``_`` becomes ``-``); it
+ never splits on ``=``. So ``--flash-attn=off`` is "invalid argument" on every
+ build, and the bare form only exists on builds whose flag takes no value at
+ all. The retry therefore drops a bare flag instead of giving it a value.
+ """
+
+ @pytest.mark.parametrize("flag", ["--flash-attn", "-fa"])
+ def test_a_bare_flag_is_dropped(self, flag):
+ assert LlamaCppBackend._with_flash_attn_off(
+ ["llama-server", "-m", "m.gguf", flag, "--no-context-shift"]
+ ) == ["llama-server", "-m", "m.gguf", "--no-context-shift"]
+
+ @pytest.mark.parametrize("value", ["on", "auto", "1", "true", "enabled"])
+ def test_a_valued_flag_is_flipped_in_place(self, value):
+ assert LlamaCppBackend._with_flash_attn_off(
+ ["llama-server", "--flash-attn", value, "--jinja"]
+ ) == ["llama-server", "--flash-attn", "off", "--jinja"]
+
+ @pytest.mark.parametrize(
+ "cmd",
+ [
+ ["llama-server", "-m", "m.gguf", "--flash-attn"],
+ ["llama-server", "-m", "m.gguf", "-fa"],
+ ["llama-server", "--flash-attn", "on"],
+ ["llama-server", "-fa", "--flash-attn", "auto"],
+ ],
+ )
+ def test_the_retry_never_carries_an_equals_form(self, cmd):
+ retry = LlamaCppBackend._with_flash_attn_off(cmd)
+ assert retry is not None
+ assert not [t for t in retry if t.startswith("-") and "=" in t]
+
+ @pytest.mark.parametrize(
+ "cmd",
+ [
+ ["llama-server", "--flash-attn", "off"],
+ ["llama-server", "-fa", "off"],
+ ["llama-server", "-m", "m.gguf"],
+ ],
+ )
+ def test_nothing_to_retry_stays_none(self, cmd):
+ assert LlamaCppBackend._with_flash_attn_off(cmd) is None
+
+ def test_the_env_goes_with_the_dropped_flag(self):
+ """Dropping a bare flag is not enough on its own: llama.cpp applies
+ LLAMA_ARG_FLASH_ATTN before argv, and argv can no longer say "off"."""
+ env = {"LLAMA_ARG_FLASH_ATTN": "1", "LLAMA_ARG_CTX_SIZE": "4096"}
+ assert LlamaCppBackend._drop_env_flash_attn(env) is True
+ assert env == {"LLAMA_ARG_CTX_SIZE": "4096"}
+
+ def test_dropping_an_absent_env_is_a_no_op(self):
+ env = {"LLAMA_ARG_CTX_SIZE": "4096"}
+ assert LlamaCppBackend._drop_env_flash_attn(env) is False
+ assert env == {"LLAMA_ARG_CTX_SIZE": "4096"}
+
+
+def _flash_attn_env_scrub(*, known_off: bool) -> dict:
+ """Run load_model's real inherited-flash-attention env scrub, and report the env."""
+ source = textwrap.dedent(inspect.getsource(LlamaCppBackend.load_model))
+ blocks = [
+ node
+ for node in ast.walk(ast.parse(source))
+ if isinstance(node, ast.If)
+ and "_drop_env_flash_attn"
+ in {a.attr for a in ast.walk(node) if isinstance(a, ast.Attribute)}
+ and "_flash_attn_known_off"
+ in {n.id for n in ast.walk(node.test) if isinstance(n, ast.Name)}
+ ]
+ assert len(blocks) == 1, f"expected one scrub block, found {len(blocks)}"
+ scope = {
+ "self": LlamaCppBackend,
+ "logger": logging.getLogger(__name__),
+ "_flash_attn_known_off": known_off,
+ "env": {"LLAMA_ARG_FLASH_ATTN": "1", "LLAMA_ARG_CTX_SIZE": "4096"},
+ }
+ exec(ast.unparse(ast.Module(body = blocks, type_ignores = [])), scope)
+ return scope["env"]
+
+
+class TestAFlaglessBuildIgnoresTheFlashAttentionEnv:
+ """A build with no --flash-attn never reads LLAMA_ARG_FLASH_ATTN either.
+
+ llama.cpp resolves each LLAMA_ARG_* variable through the common_arg that
+ declares it, so a binary predating the flag registers neither. Studio still
+ reads the inherited env when it records what the child is running, and a
+ recorded-on flash attention under-sizes the padded V cache the resume-slot
+ estimate is capped on.
+ """
+
+ # What the gate leaves on the command line for such a build: no -fa at all.
+ CMD = ["llama-server", "-m", "m.gguf", "--no-context-shift", "-c", "8192"]
+
+ def test_the_inherited_value_is_dropped(self):
+ env = _flash_attn_env_scrub(known_off = True)
+ assert "LLAMA_ARG_FLASH_ATTN" not in env
+ # ...and nothing else in the inherited env is touched.
+ assert env == {"LLAMA_ARG_CTX_SIZE": "4096"}
+
+ def test_the_recorded_state_then_matches_the_launch(self):
+ env = _flash_attn_env_scrub(known_off = True)
+ assert _flash_attn_enabled_from_args(self.CMD, default = False, env = env) is False
+
+ @pytest.mark.parametrize("value", ["1", "on", "auto", "true"])
+ def test_every_enabling_spelling_would_otherwise_win(self, value):
+ """The unscrubbed env overrides the default on all of llama.cpp's truthy forms."""
+ env = {"LLAMA_ARG_FLASH_ATTN": value}
+ assert _flash_attn_enabled_from_args(self.CMD, default = False, env = env) is True
+
+ def test_a_build_that_has_the_flag_keeps_the_inherited_value(self):
+ """The scrub is scoped to the flagless build: everywhere else a deliberate
+ LLAMA_ARG_FLASH_ATTN must reach llama-server untouched."""
+ env = _flash_attn_env_scrub(known_off = False)
+ assert env["LLAMA_ARG_FLASH_ATTN"] == "1"
+
+
+def _flagless_v_cache_fixup(*, known_off: bool, cmd: list, env: dict) -> tuple:
+ """Run load_model's real flagless-build V-cache fixup over cmd and env."""
+ source = textwrap.dedent(inspect.getsource(LlamaCppBackend.load_model))
+ blocks = [
+ node
+ for node in ast.walk(ast.parse(source))
+ if isinstance(node, ast.If)
+ and {a.attr for a in ast.walk(node) if isinstance(a, ast.Attribute)}
+ & {"_reset_quantized_v_cache", "_drop_env_quantized_v_cache"}
+ and "_flash_attn_known_off"
+ in {n.id for n in ast.walk(node.test) if isinstance(n, ast.Name)}
+ ]
+ assert len(blocks) == 2, f"expected two V-cache fixup blocks, found {len(blocks)}"
+ scope = {
+ "self": LlamaCppBackend,
+ "logger": logging.getLogger(__name__),
+ "_flash_attn_known_off": known_off,
+ "cmd": list(cmd),
+ "env": dict(env),
+ }
+ exec(ast.unparse(ast.Module(body = blocks, type_ignores = [])), scope)
+ return scope["cmd"], scope["env"]
+
+
+class TestAFlaglessBuildCannotRunAQuantizedVCache:
+ """Dropping --flash-attn has to take the quantized V cache with it.
+
+ llama.cpp aborts init with "V cache quantization requires flash_attn", and
+ the KV type is emitted straight from the user's setting with no flash-attn
+ coupling. The crash-recovery rung resets V for exactly this abort, but
+ _with_flash_attn_off returns None when the argv has no flag to turn off, so
+ on a build that never had one nothing downstream would catch it.
+ """
+
+ CMD = [
+ "llama-server",
+ "-m",
+ "m.gguf",
+ "--cache-type-k",
+ "q8_0",
+ "--cache-type-v",
+ "q8_0",
+ ]
+
+ def test_the_v_cache_is_reset_and_the_k_cache_is_not(self):
+ cmd, _ = _flagless_v_cache_fixup(known_off = True, cmd = self.CMD, env = {})
+ assert cmd[cmd.index("--cache-type-v") + 1] == "f16"
+ assert cmd[cmd.index("--cache-type-k") + 1] == "q8_0"
+
+ def test_the_recovery_rung_would_not_have_caught_it(self):
+ assert LlamaCppBackend._with_flash_attn_off(self.CMD) is None
+
+ def test_the_inherited_quantized_v_env_goes_too(self):
+ _, env = _flagless_v_cache_fixup(
+ known_off = True,
+ cmd = self.CMD,
+ env = {"LLAMA_ARG_CACHE_TYPE_V": "q8_0", "LLAMA_ARG_CACHE_TYPE_K": "q8_0"},
+ )
+ assert "LLAMA_ARG_CACHE_TYPE_V" not in env
+ assert env["LLAMA_ARG_CACHE_TYPE_K"] == "q8_0"
+
+ def test_a_build_that_has_the_flag_keeps_its_quantized_v_cache(self):
+ cmd, env = _flagless_v_cache_fixup(
+ known_off = False,
+ cmd = self.CMD,
+ env = {"LLAMA_ARG_CACHE_TYPE_V": "q8_0"},
+ )
+ assert cmd == self.CMD
+ assert env == {"LLAMA_ARG_CACHE_TYPE_V": "q8_0"}
+
+ @pytest.mark.parametrize("value", ["f16", "bf16", "f32"])
+ def test_an_unquantized_v_cache_is_left_alone(self, value):
+ cmd = [c if c != "q8_0" else value for c in self.CMD]
+ assert _flagless_v_cache_fixup(known_off = True, cmd = cmd, env = {})[0] == cmd
+
+ def test_the_reset_lands_before_the_launch_is_logged(self):
+ """Otherwise "Starting llama-server: ..." names a V cache type the child
+ never runs, and the log is the only record of what was launched."""
+ src = inspect.getsource(LlamaCppBackend.load_model)
+ assert src.index("_reset_quantized_v_cache") < src.index("Starting llama-server")
diff --git a/studio/backend/tests/test_llama_cpp_mmproj_fallback.py b/studio/backend/tests/test_llama_cpp_mmproj_fallback.py
index f39baddcb44..47d4ffafae1 100644
--- a/studio/backend/tests/test_llama_cpp_mmproj_fallback.py
+++ b/studio/backend/tests/test_llama_cpp_mmproj_fallback.py
@@ -252,14 +252,16 @@ class TestFlashAttnOff:
def test_neutralizes_trailing_bare_flag(self):
# A bare --flash-attn reads as on under last-wins; it must be neutralized
- # too, else the retry re-enables FA and re-crashes.
+ # too, else the retry re-enables FA and re-crashes. It is dropped rather
+ # than valued: llama.cpp matches argv tokens verbatim, so --flash-attn=off
+ # is "invalid argument", and a build accepting the bare form takes no value.
out = _flash_off(["llama-server", "--flash-attn", "on", "--flash-attn"])
- assert out == ["llama-server", "--flash-attn", "off", "--flash-attn=off"]
+ assert out == ["llama-server", "--flash-attn", "off"]
assert "on" not in out
def test_bare_flag_only(self):
- assert _flash_off(["llama-server", "--flash-attn"]) == ["llama-server", "--flash-attn=off"]
- assert _flash_off(["llama-server", "-fa"]) == ["llama-server", "-fa=off"]
+ assert _flash_off(["llama-server", "--flash-attn"]) == ["llama-server"]
+ assert _flash_off(["llama-server", "-fa"]) == ["llama-server"]
_drop_env_v = LlamaCppBackend._drop_env_quantized_v_cache
diff --git a/studio/backend/tests/test_llama_cpp_no_context_shift.py b/studio/backend/tests/test_llama_cpp_no_context_shift.py
index 662c9183052..6b6022584fa 100644
--- a/studio/backend/tests/test_llama_cpp_no_context_shift.py
+++ b/studio/backend/tests/test_llama_cpp_no_context_shift.py
@@ -88,49 +88,71 @@ def test_no_context_shift_is_in_load_model():
)
-def test_flag_sits_inside_the_base_cmd_list():
- """Pin the flag's location so a refactor can't move it into a branch that
- only fires on some code paths.
-
- We slice from ``cmd = [`` to the first ``]`` at the same indent. Since
- ``inspect.getsource`` gives the function its own string with no siblings, a
- plain bracket search would also work -- anchoring on the trailing indent just
- keeps the slice from wandering into a later expression if the opening literal
- ever grows a trailing in-line comment.
+def test_the_flag_is_emitted_unless_the_build_lacks_it():
+ """The gate replaces the old "must be a literal in the base list" pin.
+
+ It used to sit unconditionally inside ``cmd = [...]``, which meant a stale
+ or user-supplied LLAMA_SERVER_PATH without the flag got it anyway and
+ exited on an unknown argument. It is now gated, but the gate FAILS OPEN:
+ the capability defaults to True everywhere, so an unreadable --help keeps
+ today's command and only a build whose help positively lacks the flag
+ drops it.
+ """
+ source = _load_model_source()
+ assert 'cmd.append("--no-context-shift")' in source
+ assert (
+ 'if _caps.get("supports_no_context_shift", True):' in source
+ ), "the gate must default to True, so a failed probe still emits the flag"
+ # And the default really is True in both places the probe can return.
+ probe_src = inspect.getsource(llama_cpp_module.LlamaCppBackend.probe_server_capabilities)
+ assert '"supports_no_context_shift": True' in probe_src
+ assert "supports_no_context_shift = True" in probe_src
+
+
+def test_the_base_cmd_list_still_leads_straight_into_the_context_flag():
+ """-c must stay grouped with the base list.
+
+ auto-fit must omit -c entirely, because "-c 0" pins the full native context
+ and disables --fit's VRAM-based sizing, so the emission needs to stay where
+ that reasoning is visible.
"""
source = _load_model_source()
start = source.find("cmd = [")
assert start >= 0, "could not find the base cmd = [...] block"
- # Find the first line containing only ``]`` (possibly indented).
rest = source[start:]
end_rel = -1
for line_start, line in _iter_lines_with_offset(rest):
if line_start == 0:
- # Skip the opening ``cmd = [`` line itself.
continue
if line.strip() == "]":
end_rel = line_start
break
assert end_rel > 0, "could not find end of cmd = [...] block"
- block = rest[:end_rel]
- assert '"--no-context-shift"' in block, (
- "--no-context-shift must be in the base cmd list, not in a "
- "conditional branch -- otherwise some code paths would still "
- "run with silent context shift enabled."
- )
- assert '"--flash-attn"' in block
- # -c is emitted in the conditional right after the base list, not inside
- # it: auto-fit (--fit on with no pinned context) must omit -c entirely,
- # because "-c 0" pins the full native context and disables --fit's
- # VRAM-based sizing. Pin that it still sits next to the base block so the
- # context grouping stays intact.
- after = rest[end_rel : end_rel + 1000]
+ # Wide enough to span the gated flags and their comments that now sit between
+ # the base list and -c; the point is that -c is still emitted here rather than
+ # somewhere else entirely.
+ after = rest[end_rel : end_rel + 2400]
assert '"-c"' in after, (
- "-c must still be emitted in the conditional immediately after the "
- "base cmd list (omitted only in auto-fit, where --fit sizes context)."
+ "-c must still be emitted near the base cmd list (omitted only in "
+ "auto-fit, where --fit sizes context)."
)
+def test_flash_attention_drops_its_value_only_for_a_boolean_build():
+ """Older builds take -fa as a bare boolean and read "on" as a positional.
+
+ That is an immediate "invalid argument" exit, not a degraded launch.
+ """
+ value_form = "-fa, --flash-attn [on|off|auto] set flash attention"
+ boolean_form = "-fa, --flash-attn enable flash attention"
+ assert llama_cpp_module.LlamaCppBackend._flash_attn_takes_value(value_form) is True
+ assert llama_cpp_module.LlamaCppBackend._flash_attn_takes_value(boolean_form) is False
+ # Fail open when the help says nothing about it, since the pinned prebuilt
+ # is the value form and guessing wrong there breaks the supported path.
+ assert llama_cpp_module.LlamaCppBackend._flash_attn_takes_value("-m, --model FNAME") is True
+ assert llama_cpp_module.LlamaCppBackend._flash_attn_takes_value("") is True
+
+
def _iter_lines_with_offset(text: str):
"""Yield (offset, line) pairs over ``text`` without losing offsets."""
offset = 0