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: stop dropping quantized KV cache on tensor split (#8939)

kissa0114c9b7379741
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.py
index 0c3a851f70a..644f875632e 100644
--- a/studio/backend/core/inference/llama_cpp.py
+++ b/studio/backend/core/inference/llama_cpp.py
@@ -2948,21 +2948,27 @@ def _kv_cache_cell_layout(n_ctx: int, n_parallel: int, kv_unified: bool) -> tupl
def _env_main_cache_type_for_budget(env: Optional[Mapping[str, str]] = None) -> Optional[str]:
- """Heavier of the inherited LLAMA_ARG_CACHE_TYPE_K/_V env types when it
- exceeds the f16 default, else None. Unsloth emits --cache-type only for the
- param/extras path, so a heavier env (f32) would otherwise reach the child
- unbudgeted; quantized env types stay over-reserved by f16 (-> None)."""
+ """Heavier (max bytes/elem) of the set LLAMA_ARG_CACHE_TYPE_K/_V env types
+ when it budgets differently from the f16 default, else None. Unsloth emits
+ --cache-type only for the param/extras path, so an env type would otherwise
+ reach the child unbudgeted: f32 under-reserves the KV, and a quantized type
+ skips the dequant compute scratch (on Inkling the dense fallback it forces
+ dwarfs the banded rate). The caller adopts the type for the reserve only;
+ _cache_type_from_env keeps it out of the emitted flags."""
e = os.environ if env is None else env
- f16_bpe = _kv_bytes_per_elem("f16")
- heaviest: Optional[str] = None
- heaviest_bpe = f16_bpe
- for var in ("LLAMA_ARG_CACHE_TYPE_K", "LLAMA_ARG_CACHE_TYPE_V"):
- raw = (e.get(var) or "").strip().lower()
- if not raw:
- continue
- bpe = _kv_bytes_per_elem(raw)
- if bpe > heaviest_bpe:
- heaviest, heaviest_bpe = raw, bpe
+ # An UNSET axis is not absent, it is llama.cpp's f16 default, so it joins the max.
+ # Dropping it let a lone CACHE_TYPE_V=q4_0 return q4_0 and price K as q4 while the
+ # child ran it at f16, under-reserving the larger tensor when key_length >
+ # value_length -- and tensor mode has no --fit valve to absorb that.
+ axis_types = [
+ (e.get(var) or "").strip().lower() or "f16"
+ for var in ("LLAMA_ARG_CACHE_TYPE_K", "LLAMA_ARG_CACHE_TYPE_V")
+ ]
+ if all(t == "f16" for t in axis_types):
+ return None
+ heaviest = max(axis_types, key = _kv_bytes_per_elem)
+ if _kv_bytes_per_elem(heaviest) == _kv_bytes_per_elem("f16"):
+ return None
return heaviest
@@ -3012,6 +3018,31 @@ def _planned_main_cache_types(
return _effective_main_cache_types(args, env)
+# What kv_cache_type_from_str accepts, so the only types Studio emits. Module scope
+# because the budget must know whether a type will reach the child before the command
+# is assembled.
+_VALID_CACHE_TYPES = frozenset(
+ {"f16", "bf16", "q8_0", "q4_0", "q4_1", "q5_0", "q5_1", "iq4_nl", "f32"}
+)
+
+
+def _planned_scratch_cache_type(
+ cache_type_kv: Optional[str],
+ extra_args: Optional[Iterable[str]] = None,
+ env: Optional[Mapping[str, str]] = None,
+) -> str:
+ """LIGHTEST planned axis: the type that decides the compute-buffer scratch rate.
+
+ The KV-byte reserve takes the HEAVIER axis (max over _planned_main_cache_types),
+ which is conservative for storage but hides a paired quantized axis -- an f16
+ budget hides a q4_0 K. _compute_buffer_ctx_bytes charges the per-device dequant
+ scratch only when its cache type is under f16, so handing it the heavier axis
+ silently drops that scratch for an asymmetric pair. Taking the lighter axis here
+ makes any quantized axis select the quantized rate, leaving the two terms
+ independently conservative (heavier for bytes, lighter for scratch)."""
+ return min(_planned_main_cache_types(cache_type_kv, extra_args, env), key = _kv_bytes_per_elem)
+
+
def _auto_mode_drops_mtp(
req_mode: Optional[str],
size_b: Optional[float],
@@ -4921,6 +4952,8 @@ class LlamaCppBackend:
self._n_ubatch: int = self._DEFAULT_N_UBATCH
self._flash_attn_enabled: bool = True
self._effective_cache_types: tuple[str, str] = ("f16", "f16")
+ # The pair this load ASKED for, before any launch-time rewrite.
+ self._requested_cache_types: tuple[str, str] = ("f16", "f16")
# Total KV allocation context across all slots. _effective_context_length
# becomes the per-slot request limit after /props reconciliation.
self._kv_cache_context_total: Optional[int] = None
@@ -5582,16 +5615,8 @@ class LlamaCppBackend:
):
return False
- def _norm(value):
- if value is None:
- return None
- if isinstance(value, str):
- value = value.strip().lower()
- return value or None
- return value
-
- if _norm(self._cache_type_kv) != _norm(intent.cache_type_kv):
- return False
+ # The KV cache comparison waits for _invoked_extras below: the scalar
+ # self._cache_type_kv alone cannot describe this launch.
# Toggling vision changes which files the child opens, so it cannot be
# satisfied by a live server that was launched the other way. Not on the
@@ -5608,6 +5633,18 @@ class LlamaCppBackend:
# Judged on the flag, not on value equality: a caller that deliberately sends the
# stripped list is clearing the failed drafter and must not read as inheriting it.
_invoked_extras = self.requested_extra_args if intent.extra_args_inherited else extra_args
+ # Requested against requested, per axis, the same rule the tuning group above
+ # uses. The scalar self._cache_type_kv holds only what Studio emitted as a
+ # managed flag, so a cache set through extras or the env records None on one
+ # side and a type on the other, and an identical repeat /load tears down a
+ # healthy server. _requested_cache_types is what the live server was ASKED for,
+ # so two equal requests match even when the launch rewrote the cache underneath
+ # them. Before ggml-org/llama.cpp#23792 the tensor gate hid this by rewriting
+ # the cache away; a layer load has always had it.
+ if self._requested_cache_types != _planned_main_cache_types(
+ intent.cache_type_kv, _invoked_extras
+ ):
+ return False
# A virtualised Metal device never launches a tensor split (CPU-pinned, and
# --split-mode is overridden with the default layer split), so judge the
# normalized request there: an extras `-sm tensor`, which the pin deliberately
@@ -8843,10 +8880,6 @@ class LlamaCppBackend:
# tight layer split can't advertise a context that OOMs at load.
_PIPELINE_PER_DEVICE_OVERHEAD_MIB = 1024
- # KV cache types llama.cpp accepts in tensor mode. A quantized KV cache
- # aborts a --split-mode tensor load, so it's dropped for the tensor attempt.
- _TENSOR_PARALLEL_KV_TYPES = frozenset({"f16", "bf16", "f32"})
-
# V cache types that llama.cpp can run WITHOUT flash attention. Only the V
# axis has the dependency: a quantized V cache (q8_0/q4_0/q4_1/q5_0/q5_1/
# iq4_nl) aborts init with "V cache quantization requires flash_attn", while
@@ -8878,34 +8911,97 @@ class LlamaCppBackend:
"LLAMA_ARG_OVERRIDE_TENSOR",
)
- # (binary, mtime, model) that aborted on --split-mode tensor this process (#6415
- # geometry limit, e.g. MQA n_head_kv=1). Model-keyed so one model's abort doesn't
- # skip tensor for others; tensor is tried by default, recorded only on a real abort.
- _tensor_split_abort_keys: set[tuple[str, int, str]] = set()
+ # (binary, mtime, model, kv types) that aborted on --split-mode tensor this
+ # process (#6415 geometry limit, e.g. MQA n_head_kv=1). Model-keyed so one
+ # model's abort doesn't skip tensor for others; tensor is tried by default,
+ # recorded only on a real abort.
+ # KV-type-keyed too: since ggml-org/llama.cpp#23792 the type reaches the tensor
+ # child rather than being rewritten to f16, so an abort can be specific to one
+ # type. iq4_nl asserts on b10441 where q4_0 runs on the same binary and model
+ # (ggml-org/llama.cpp#27116); keyed only by (binary, model) that would disable
+ # tensor mode for the types that work.
+ _tensor_split_abort_keys: set[tuple[str, int, str, tuple[str, str]]] = set()
+
+ # (binary, mtime) that refused a quantized KV cache under --split-mode tensor.
+ # Coarser than _tensor_split_abort_keys on purpose: the pre-b9455 rejection is a
+ # missing capability of the BINARY, not of one model or type, so keying it per
+ # model+pair would pay another doomed full load for each new model and each
+ # q8_0 -> q4_0 switch. f16 still splits on such a binary, so this is consulted
+ # only when an axis is actually quantized.
+ _tensor_quant_kv_unsupported_binaries: set[tuple[str, int]] = set()
+
+ @classmethod
+ def _binary_key(cls, binary: Optional[str]) -> Optional[tuple[str, int]]:
+ """(path, mtime_ns); ns mtime re-probes a same-second binary swap."""
+ if not binary:
+ return None
+ try:
+ mtime = Path(binary).stat().st_mtime_ns
+ except OSError:
+ mtime = 0
+ return (binary, mtime)
+
+ @classmethod
+ def _record_tensor_quant_kv_unsupported(cls, binary: Optional[str]) -> None:
+ """Remember a binary that cannot run a quantized KV cache in tensor mode."""
+ key = cls._binary_key(binary)
+ if key is not None:
+ cls._tensor_quant_kv_unsupported_binaries.add(key)
+
+ @classmethod
+ def _tensor_quant_kv_unsupported_binary(
+ cls,
+ binary: Optional[str],
+ cache_types: tuple[str, str] = ("f16", "f16"),
+ ) -> bool:
+ """True if this binary already refused a quantized KV cache in tensor mode
+ AND this launch asks for one. A non-quantized pair is unaffected."""
+ if not any(_kv_bytes_per_elem(t) < _kv_bytes_per_elem("f16") for t in cache_types):
+ return False
+ key = cls._binary_key(binary)
+ return key is not None and key in cls._tensor_quant_kv_unsupported_binaries
@classmethod
def _tensor_split_cache_key(
- cls, binary: Optional[str], model: Optional[str]
- ) -> Optional[tuple[str, int, str]]:
- """(path, mtime_ns, model) key; ns mtime re-probes a same-second binary swap."""
+ cls,
+ binary: Optional[str],
+ model: Optional[str],
+ cache_types: tuple[str, str] = ("f16", "f16"),
+ ) -> Optional[tuple[str, int, str, tuple[str, str]]]:
+ """(path, mtime_ns, model, (type_k, type_v)) key; ns mtime re-probes a
+ same-second binary swap. ``cache_types`` defaults to llama.cpp's own
+ default pair, which is what a caller that sets no type gets."""
if not binary or not model:
return None
try:
mtime = Path(binary).stat().st_mtime_ns
except OSError:
mtime = 0
- return (binary, mtime, model)
+ k, v = cache_types
+ return (binary, mtime, model, (k.strip().lower(), v.strip().lower()))
@classmethod
- def _tensor_split_aborts(cls, binary: Optional[str], model: Optional[str]) -> bool:
- """True if (binary, model) aborted on --split-mode tensor this session."""
- key = cls._tensor_split_cache_key(binary, model)
+ def _tensor_split_aborts(
+ cls,
+ binary: Optional[str],
+ model: Optional[str],
+ cache_types: tuple[str, str] = ("f16", "f16"),
+ ) -> bool:
+ """True if this (binary, model, KV types) aborted on --split-mode tensor
+ this session. A different cache type is a different question, so it is
+ tried rather than assumed broken."""
+ key = cls._tensor_split_cache_key(binary, model, cache_types)
return key is not None and key in cls._tensor_split_abort_keys
@classmethod
- def _record_tensor_split_abort(cls, binary: Optional[str], model: Optional[str]) -> None:
- """Remember a (binary, model) that aborts on --split-mode tensor."""
- key = cls._tensor_split_cache_key(binary, model)
+ def _record_tensor_split_abort(
+ cls,
+ binary: Optional[str],
+ model: Optional[str],
+ cache_types: tuple[str, str] = ("f16", "f16"),
+ ) -> None:
+ """Remember a (binary, model, KV types) that aborts on --split-mode tensor."""
+ key = cls._tensor_split_cache_key(binary, model, cache_types)
if key is not None:
cls._tensor_split_abort_keys.add(key)
@@ -9894,9 +9990,9 @@ class LlamaCppBackend:
batch; the flat term only covers ctx -> 0. A quantized KV cache adds a
context-sized dequant scratch that scales with n_embd; f16/bf16/f32 pays only
the KQ mask, a flat n_ubatch*2 bytes per context token. ``cache_type_kv`` None
- -> f16 (llama.cpp's default; an env-set quantized cache is budgeted as f16 on
- the KV side, whose over-reservation absorbs the dequant scratch). Returns 0
- when dims are missing or ``n_ctx`` <= 0.
+ -> f16 (llama.cpp's default; env-set types are adopted by the caller via
+ ``_env_main_cache_type_for_budget``). Returns 0 when dims are missing or
+ ``n_ctx`` <= 0.
``layer_split`` adds the extra KQ-mask copies a multi-device split pays (see
``_CTX_COMPUTE_SPLIT_MULT``) on every architecture except deepseek4, whose own
@@ -11220,6 +11316,7 @@ class LlamaCppBackend:
self._requested_cache_ram = None
self._flash_attn_enabled = True
self._effective_cache_types = ("f16", "f16")
+ self._requested_cache_types = ("f16", "f16")
self._kv_cache_context_total = None
# False means "confirmed to hold no VRAM" and makes the training coordinator skip
# the unload, so it is claimed only for a zero-layer split.
@@ -13244,6 +13341,18 @@ class LlamaCppBackend:
"settings and reload."
)
+ # An older llama.cpp refusing a quantized KV cache under --split-mode tensor.
+ # Naming the build is the point: the remedy is an update, where the generic
+ # invalid-GGUF/OOM fallback sends the user to check their file or buy VRAM.
+ # After the arch gate above, a different marker for a permanent per-model limit.
+ if LlamaCppBackend._is_tensor_quant_kv_unsupported(lowered):
+ return (
+ "This llama.cpp build cannot use a quantized KV cache together "
+ "with Tensor Parallelism (support landed in b9455). Update "
+ "llama.cpp, or set the KV cache type to f16, or turn off Tensor "
+ "Parallelism in the model settings."
+ )
+
# llama.cpp prints the four bytes it found with %c, so a binary header arrives as
# unprintable characters; the generic fallback then blamed the user's memory (#8566).
if "invalid magic characters" in lowered:
@@ -13713,6 +13822,7 @@ class LlamaCppBackend:
kv_unified: bool = True,
flash_attn: bool = True,
vram_fraction: Optional[float] = None,
+ scratch_cache_type_kv: Optional[str] = None,
) -> tuple[int, int, list[int], Optional[list[int]]]:
"""Plan a ``--split-mode tensor`` load. Pure: no model or GPU needed.
@@ -13740,6 +13850,10 @@ class LlamaCppBackend:
the compute buffer. ``soft_overhead_bytes`` is the CUDA-context / mmproj /
MTP-draft-graph reserve the layer path folds into ``model_size_fit``;
charged against the pooled budget so tensor mode reserves the same overhead.
+ ``cache_type_kv`` is the HEAVIER planned axis (KV bytes);
+ ``scratch_cache_type_kv`` is the LIGHTER one and prices the dequant scratch,
+ so an asymmetric pair keeps both terms conservative. Defaults to
+ ``cache_type_kv`` when unset, which is the symmetric case.
"""
# Per-GPU usable budget: free - (1-frac)*total, else (unknown total, e.g. a
@@ -13823,16 +13937,22 @@ class LlamaCppBackend:
# replicates the compute graph on EVERY device (measured: the per-device
# buffer grows a flat n_ubatch*2 bytes/token, ~1024 B/tok on Qwen3.5-9B at
# f16, independent of n_embd), so the growth is n_dev x the per-device
- # term. cache_type_kv here is always non-quantized (tensor forces f16), so
- # _compute_buffer_ctx_bytes returns the light KQ-mask term, not the heavy
- # quantized dequant scratch. The flat reserve_mib above only covers ctx->0;
- # without this the fit over-pins and OOMs at high context on a tight pool
- # (0.5-4 GiB unreserved at 262k-1M across 2-4 GPUs), the tensor-mode analog
- # of the layer-split compute bug.
+ # term. The flat reserve_mib above only covers ctx->0; without this the fit
+ # over-pins and OOMs at high context on a tight pool (0.5-4 GiB unreserved
+ # at 262k-1M across 2-4 GPUs), the tensor-mode analog of the layer-split
+ # compute bug.
+ #
+ # Priced from the LIGHTER axis, not the heavier budget type: since
+ # ggml-org/llama.cpp#23792 an asymmetric -ctk q4_0 -ctv f16 reaches the child,
+ # and the heavier scalar (f16) would drop the dequant scratch the q4 axis
+ # allocates. No --fit valve here, so that under-reservation OOMs at startup.
n_dev = len(gpu_indices)
+ cc_cache_type = (
+ scratch_cache_type_kv if scratch_cache_type_kv is not None else cache_type_kv
+ )
def _cc_ctx(ctx: int) -> int:
- return n_dev * self._compute_buffer_ctx_bytes(ctx, n_ubatch, cache_type_kv)
+ return n_dev * self._compute_buffer_ctx_bytes(ctx, n_ubatch, cc_cache_type)
def _fit_ctx(ctx: int) -> int:
# Largest context whose KV (+ MTP draft reserve + context-linear
@@ -14029,9 +14149,32 @@ class LlamaCppBackend:
"failed to allocate",
"unknown model architecture",
"split_mode_tensor not implemented",
+ LlamaCppBackend._TENSOR_QUANT_KV_UNSUPPORTED_MARKER,
)
)
+ # llama.cpp before ggml-org/llama.cpp#23792 (build b9455) refused a quantized KV
+ # cache under --split-mode tensor outright, in llama_init_from_model:
+ # "simultaneous use of SPLIT_MODE_TENSOR and KV cache quantization not implemented"
+ # Unlike the #6415 split-axis abort this is a clean LLAMA_LOG_ERROR + return
+ # nullptr (exit 1, no signal), so _should_record_tensor_split_abort cannot see it.
+ # Matched on the middle of the string, so the surrounding log format is irrelevant.
+ # Studio dropped its own pre-emptive gate once #23792 shipped, so this marker is
+ # what keeps an older binary cheap: without it every load burns two doomed model
+ # loads (tensor attempt plus --fit retry) before the route's layer fallback.
+ _TENSOR_QUANT_KV_UNSUPPORTED_MARKER = (
+ "split_mode_tensor and kv cache quantization not implemented"
+ )
+
+ @classmethod
+ def _is_tensor_quant_kv_unsupported(cls, output: str) -> bool:
+ """True for the pre-b9455 refusal of a quantized KV cache in tensor mode.
+
+ Deterministic and binary-wide: only a different llama.cpp helps, so the
+ caller latches it and downgrades instead of retrying --fit or flash-attn.
+ """
+ return cls._TENSOR_QUANT_KV_UNSUPPORTED_MARKER in (output or "").lower()
+
@staticmethod
def _is_tensor_split_assert(output: str) -> bool:
"""True only for the #6415 split-axis warmup assert (GGML_BACKEND_SPLIT_AXIS_*),
@@ -15798,14 +15941,40 @@ class LlamaCppBackend:
_extras_cache = _extra_args_main_cache_type_for_budget(extra_args)
cache_type_kv = _extras_cache if _extras_cache is not None else cache_type_kv
_cache_type_from_env = False
+ # An unknown type is never emitted (see _VALID_CACHE_TYPES below), so the
+ # child falls through to whatever LLAMA_ARG_CACHE_TYPE_K/_V it inherits.
+ # Budgeting the unemittable string would price it at _kv_bytes_per_elem's
+ # 2.0 unknown default while the child allocates the inherited type: a 2x
+ # under-reservation against an inherited f32, in the mode with no --fit
+ # valve. Treat it as unset so the env adoption below sees it.
+ if cache_type_kv is not None and (
+ cache_type_kv.strip().lower() not in _VALID_CACHE_TYPES
+ ):
+ cache_type_kv = None
if cache_type_kv is None:
# Param/extras set nothing, so the child inherits
- # LLAMA_ARG_CACHE_TYPE_K/_V. Adopt a heavier env type (f32) for
- # the reserve only; the launch does NOT re-emit it (that would
- # rewrite an asymmetric K=f32,V=f16 env into symmetric flags),
- # so _cache_type_from_env keeps it out of the emitted flags.
+ # LLAMA_ARG_CACHE_TYPE_K/_V. Adopt an env type that budgets
+ # differently from f16 (f32, quantized) for the reserve only;
+ # the launch does NOT re-emit it (that would rewrite an
+ # asymmetric K=f32,V=f16 env into symmetric flags), so
+ # _cache_type_from_env keeps it out of the emitted flags.
cache_type_kv = _env_main_cache_type_for_budget()
_cache_type_from_env = cache_type_kv is not None
+ # The heavier axis above budgets KV BYTES; the dequant scratch keys off
+ # the LIGHTER axis instead. Since ggml-org/llama.cpp#23792 an asymmetric
+ # -ctk q4_0 -ctv f16 reaches the child, where the heavier scalar (f16)
+ # would price the scratch as if nothing were quantized. Same precedence.
+ _scratch_cache_type_kv = _planned_scratch_cache_type(
+ None if _cache_type_from_env else cache_type_kv,
+ extra_args,
+ )
+ # The (K, V) pair this launch will run, for the tensor-abort latch:
+ # since #23792 the type reaches the child, so an abort can be specific
+ # to it and the latch must not generalise across types.
+ _planned_cache_pair = _planned_main_cache_types(
+ None if _cache_type_from_env else cache_type_kv,
+ extra_args,
+ )
# A user --split-mode in extras last-wins-overrides the toggle, and
# an inherited tensor LLAMA_ARG_SPLIT_MODE flips it on (the child
# would run tensor unbudgeted otherwise). The duplicate-load matchers
@@ -15847,7 +16016,6 @@ class LlamaCppBackend:
# Manual offload skips the TP planner but still emits --split-mode
# tensor at launch; drop it when fewer than 2 GPUs are in use --
# tensor split is a no-op there and aborts on some architectures.
- # Done before the cache-drop below so a quantized KV survives.
if (
tensor_parallel
and gpu_memory_mode == "manual"
@@ -15859,9 +16027,6 @@ class LlamaCppBackend:
"than 2 GPUs are in use; ignoring (needs >= 2)."
)
tensor_parallel = False
- # Drop TP for manual + Auto layers before the cache-drop below (like
- # the <2-GPU guard above), so a requested quantized KV survives into
- # the --fit load rather than being stripped for a tensor attempt.
if tensor_parallel and gpu_memory_mode == "manual" and gpu_layers < 0:
logger.info(
"Manual mode with Auto layers hands memory management to "
@@ -15869,54 +16034,6 @@ class LlamaCppBackend:
"parallelism; ignoring the tensor split."
)
tensor_parallel = False
- # Tensor mode aborts on a quantized KV cache, so drop it for the
- # tensor attempt (and strip any inherited/explicit --cache-type
- # that would re-impose it when appended last). Layer split does
- # support it, so remember the dropped type and the original extras
- # to restore (verbatim, incl. an asymmetric K/V) if we later fall
- # back to layer split below.
- _tensor_dropped_cache_type_kv: Optional[str] = None
- _tensor_dropped_extra_args: Optional[list] = None
- # Tensor mode rejects any quantized axis. cache_type_kv is the
- # heavier-by-bytes budget type, which can mask a quantized axis (an
- # f16 budget hides a paired q4_0), so also test each explicit
- # --cache-type-k/-v extra, not just the budget type.
- _ck_extra, _cv_extra = parse_cache_override_per_axis(extra_args)
- _cache_non_tensor_safe = any(
- c and c.strip().lower() not in self._TENSOR_PARALLEL_KV_TYPES
- for c in (cache_type_kv, _ck_extra, _cv_extra)
- )
- if tensor_parallel and _cache_non_tensor_safe:
- logger.info(
- "Tensor parallelism requires a non-quantized KV cache; "
- "ignoring cache type %s for the tensor attempt.",
- cache_type_kv,
- )
- _tensor_dropped_cache_type_kv = cache_type_kv
- cache_type_kv = None
- if extra_args:
- # Keep the originals so a layer downgrade restores the real
- # (possibly asymmetric) --cache-type-k/-v the layer path
- # supports, not just the scalar heavier type.
- _tensor_dropped_extra_args = list(extra_args)
- extra_args = strip_shadowing_flags(
- extra_args,
- strip_context = False,
- strip_cache = True,
- strip_spec = False,
- strip_template = False,
- strip_split_mode = False,
- )
- # The launch keeps an inherited tensor-safe env cache type (the
- # env cleanup only pops quantized ones), so re-adopt a heavier
- # env type (f32) for the budget here too -- mirrors the initial
- # adoption, which was skipped because the param/extras set the
- # (now-dropped) quantized type. Else the child allocates f32 KV
- # against an f16 budget.
- _env_tensor_cache = _env_main_cache_type_for_budget()
- if _env_tensor_cache is not None:
- cache_type_kv = _env_tensor_cache
- _cache_type_from_env = True
if ctx_override is not None and ctx_override > 0:
logger.info(f"User --ctx-size {ctx_override} honored; skipping auto-reduce")
if cache_override is not None:
@@ -16246,8 +16363,6 @@ class LlamaCppBackend:
# True. An explicit context is honored (--fit optimizes around
# it); 0 lets --fit size it.
if gpu_memory_mode == "manual" and gpu_layers < 0:
- # Tensor parallelism was already dropped above (before the
- # cache-drop), so a quantized KV survives into this --fit load.
gpus = []
effective_ctx = requested_ctx if requested_ctx > 0 else 0
original_ctx = effective_ctx
@@ -16594,7 +16709,9 @@ class LlamaCppBackend:
# into model_size_fit only covers ctx -> 0. Charged per
# candidate context so the fit can't over-pin and spill. The
# rate depends on the KV cache type (quantized adds a dequant
- # scratch), so pass it through. In a layer split this buffer is
+ # scratch), so pass it through -- the LIGHTER axis, since any
+ # quantized axis allocates it and the heavier scalar hides a
+ # paired one. In a layer split this buffer is
# replicated on EVERY device (measured ~equal per GPU), so scale
# by the device count; a large model at high context otherwise
# under-reserves ~(n-1)x it (e.g. Qwen3.5-397B on 3 GPUs). The
@@ -16603,7 +16720,7 @@ class LlamaCppBackend:
return max(1, n_gpus) * self._compute_buffer_ctx_bytes(
ctx,
_effective_ubatch,
- cache_type_kv,
+ _scratch_cache_type_kv,
layer_split = n_gpus > 1 and not _pipeline_parallel_off,
)
@@ -16652,26 +16769,32 @@ class LlamaCppBackend:
# The two tensor -> layer downgrades that need nothing the probe
# decides run BEFORE it: the probe is gated on `not tensor_parallel`
- # and must answer for any load that ends up layer-split. Running them
- # first also hands it the restored KV type that load will use.
- def _restore_after_tensor_downgrade():
- # Restore the quantized KV + extras tensor dropped (layer
- # split supports them), minus --split-mode.
- nonlocal cache_type_kv, _cache_type_from_env, extra_args
- if _tensor_dropped_cache_type_kv is not None:
- cache_type_kv = _tensor_dropped_cache_type_kv
- _cache_type_from_env = False
- extra_args = strip_split_mode_only(
- _tensor_dropped_extra_args
- if _tensor_dropped_extra_args is not None
- else extra_args
- )
+ # and must answer for any load that ends up layer-split.
# The route fallback retry is tensor-off; keep it multi-GPU.
if preserve_multi_gpu_on_layer:
_layer_min_gpus = max(_layer_min_gpus, len(gpus))
- if tensor_parallel and self._tensor_split_aborts(binary, model_identifier):
+ if tensor_parallel and self._tensor_quant_kv_unsupported_binary(
+ binary, _planned_cache_pair
+ ):
+ # This build already refused a quantized KV cache under a tensor
+ # split; go straight to layer rather than reload the model to be
+ # told again. Keeps the quantized cache, which layer supports.
+ logger.info(
+ "Tensor parallelism skipped: this llama.cpp build cannot "
+ "use a quantized KV cache with --split-mode tensor "
+ "(needs b9455+); loading with a layer split."
+ )
+ tensor_parallel = False
+ # Like the split-axis skip below: a missing capability says
+ # nothing about capacity, so keep the multi-GPU request rather
+ # than let the layer planner settle on the first card it fits.
+ _layer_min_gpus = max(_layer_min_gpus, len(gpus))
+ extra_args = strip_split_mode_only(extra_args)
+ if tensor_parallel and self._tensor_split_aborts(
+ binary, model_identifier, _planned_cache_pair
+ ):
# Aborted on tensor for this model this session (#6415); skip
# tensor upfront, layer split serves it.
logger.info(
@@ -16681,9 +16804,10 @@ class LlamaCppBackend:
len(gpus),
)
tensor_parallel = False
- # Keep the multi-GPU request (gated on it, not the cache).
+ # The abort says nothing about capacity, so keep multi-GPU.
_layer_min_gpus = max(_layer_min_gpus, len(gpus))
- _restore_after_tensor_downgrade()
+ # An extras --split-mode tensor would re-engage tensor mode.
+ extra_args = strip_split_mode_only(extra_args)
# Tensor mode replicates a compute buffer on every GPU, so drop
# GPUs below that reserve from the set up front (gpu_indices
@@ -16732,10 +16856,7 @@ class LlamaCppBackend:
# _select_gpus caps unusable cards.
if len(gpus) >= 2:
_layer_min_gpus = max(_layer_min_gpus, len(gpus))
- # Layer split supports a quantized KV the tensor attempt
- # dropped; restore the original cache type + extras (minus
- # --split-mode) so the layer launch re-emits them.
- _restore_after_tensor_downgrade()
+ extra_args = strip_split_mode_only(extra_args)
# Normalize the speculative reserve BEFORE anything prices it.
# _mtp_bytes reads mtp_overhead_fn at call time, so leaving this
@@ -17309,37 +17430,16 @@ class LlamaCppBackend:
# usable tensor GPUs.
if len(tp_gpus) >= 2:
_layer_min_gpus = max(_layer_min_gpus, len(tp_gpus))
- # Restore the dropped quantized KV + cache extras (minus
- # --split-mode); layer split supports them.
- _restore_after_tensor_downgrade()
- # Layer split now, so the withheld verdict applies -- but
- # only where it is still true. It was measured before two
- # things this arm changes underneath it.
- #
- # _restore_after_tensor_downgrade just above put back a
- # quantized KV cache that tensor mode had dropped, and the
- # probe priced its floor against the heavier f16 the tensor
- # attempt ran with. That verdict is pessimistic by exactly
- # the cache difference, and acting on it would pin a
- # projector that fits, buying an 8.8x image encode for
- # nothing -- the one outcome this whole probe exists to
- # avoid.
- #
- # And the drafter-drop probe carries the same tensor
- # exclusion this one did, so it has not run either. The
- # documented order is projector first and drafter second;
- # pinning here without being able to re-ask the second half
- # pays the encoder cost AND still reaches --fit on.
- #
- # Re-running both probes against the restored cache is the
- # complete fix and is a larger change than this one. Until
- # then these two cases keep main's behaviour rather than act
- # on a stale answer.
- if (
- _mm_pin_deferred
- and _tensor_dropped_cache_type_kv is None
- and not _mtp_reserves_gpu
- ):
+ extra_args = strip_split_mode_only(extra_args)
+ # Layer split now, so the withheld verdict applies -- but not
+ # when a GPU drafter is still in play. The drafter-drop probe
+ # is gated off under tensor parallelism, so it has not run;
+ # the documented order is projector first and drafter second,
+ # and pinning here without being able to re-ask the second
+ # half pays the encoder cost AND still reaches --fit on.
+ # Re-running that probe after this downgrade is the complete
+ # fix.
+ if _mm_pin_deferred and not _mtp_reserves_gpu:
_apply_mmproj_cpu_pin(_mm_floor_ctx)
_mm_pin_deferred = False
# Rebuild what was derived from model_size before the
@@ -17384,6 +17484,7 @@ class LlamaCppBackend:
model_size,
target_ctx,
cache_type_kv = cache_type_kv,
+ scratch_cache_type_kv = _scratch_cache_type_kv,
n_parallel = n_parallel,
mtp_engaged = _mtp_reserves_gpu,
mtp_overhead_fn = mtp_overhead_fn,
@@ -18448,17 +18549,7 @@ class LlamaCppBackend:
cmd.extend(["--jinja"])
# KV cache data type
- _valid_cache_types = {
- "f16",
- "bf16",
- "q8_0",
- "q4_0",
- "q4_1",
- "q5_0",
- "q5_1",
- "iq4_nl",
- "f32",
- }
+ _valid_cache_types = _VALID_CACHE_TYPES
# Normalize like the budget does (_planned_main_cache_types): a
# case-sensitive match drops "Q8_0", emitting no flag, so llama.cpp
# runs f16 while the estimate priced q8_0. Emit the normalized
@@ -19203,9 +19294,40 @@ class LlamaCppBackend:
"Dropped inherited quantized V-cache env: this build has no --flash-attn."
)
+ # An inherited type kv_cache_type_from_str cannot parse aborts the child
+ # at argument parsing, and the layer retry inherits the same env, so
+ # BOTH attempts fail and the user is left with no server. The managed
+ # path has long been normalised and allow-listed (_VALID_CACHE_TYPES);
+ # the env path only stopped being scrubbed once the tensor gate went
+ # away, so give it the same two protections. Split-mode independent,
+ # since llama.cpp parses it identically either way.
+ for _ct_var in ("LLAMA_ARG_CACHE_TYPE_K", "LLAMA_ARG_CACHE_TYPE_V"):
+ # Compared against the ORIGINAL, not a stripped copy:
+ # common_arg::get_value_from_env hands the raw getenv string to
+ # kv_cache_type_from_str, which does an exact ggml_type_name(t) == s
+ # compare and throws otherwise. So " q8_0 " is as fatal as a typo,
+ # and normalising against an already-stripped copy would compare
+ # equal, write nothing back, and leave the whitespace on the child.
+ _ct_orig = env.get(_ct_var) or ""
+ _ct_norm = _ct_orig.strip().lower()
+ if not _ct_norm:
+ continue
+ if _ct_norm not in _VALID_CACHE_TYPES:
+ env.pop(_ct_var, None)
+ logger.info(
+ "Dropped inherited %s=%s: llama.cpp does not accept that "
+ "KV cache type, and it would abort the load.",
+ _ct_var,
+ _ct_orig,
+ )
+ elif _ct_norm != _ct_orig:
+ # Case and surrounding whitespace both matter to that
+ # compare, so "Q8_0" and " q8_0 " are rewritten alike.
+ env[_ct_var] = _ct_norm
+
# Reconcile the inherited LLAMA_ARG_* env with Unsloth's final
# decision: stripping CLI extras on a tensor->layer downgrade
- # can't remove env vars, so the child could run a mode/KV Unsloth
+ # can't remove env vars, so the child could run a mode Unsloth
# didn't budget.
if not tensor_parallel:
# Layer split: clear a non-layer inherited split mode (and any
@@ -19221,12 +19343,6 @@ class LlamaCppBackend:
# case can't be overridden by a stale env (the layer branch above
# clears it too).
env.pop("LLAMA_ARG_TENSOR_SPLIT", None)
- # Tensor split aborts on a quantized KV; clear an inherited
- # quantized cache type so the child uses the tensor-safe default.
- for _ct_var in ("LLAMA_ARG_CACHE_TYPE_K", "LLAMA_ARG_CACHE_TYPE_V"):
- _ct_raw = (env.get(_ct_var) or "").strip().lower()
- if _ct_raw and _ct_raw not in self._TENSOR_PARALLEL_KV_TYPES:
- env.pop(_ct_var, None)
# A gpu_ids pin also owns inherited device placement.
if gpu_ids is not None:
@@ -19623,14 +19739,20 @@ class LlamaCppBackend:
self._process.poll() is not None and self._process.returncode != 0
)
# A split-axis abort (#6415) is fit-independent: skip the
- # --fit off retry and let the caller latch it.
+ # --fit off retry and let the caller latch it. So is a
+ # pre-b9455 build refusing a quantized KV cache in tensor mode:
+ # a capability the binary lacks, where re-spawning to let it
+ # offload spends a second full model load on a theory unrelated
+ # to the failure. The caller latches both, so both skip alike.
_startup_output = "\n".join(self._stdout_lines[-50:])
- _split_axis_crash = self._is_tensor_split_assert(_startup_output)
+ _tensor_capability_crash = self._is_tensor_split_assert(
+ _startup_output
+ ) or self._is_tensor_quant_kv_unsupported(_startup_output)
_hip_rocr_mismatch = self._is_bundled_hip_rocr_mismatch(_startup_output)
if (
not _did_rocm_retry
and _startup_crashed
- and not _split_axis_crash
+ and not _tensor_capability_crash
and _hip_rocr_mismatch
):
# The prepend is what a shell launch does not do, which
@@ -19658,7 +19780,7 @@ class LlamaCppBackend:
not _did_fit_retry
and fully_gpu_offloaded
and _startup_crashed
- and not _split_axis_crash
+ and not _tensor_capability_crash
and not _hip_rocr_mismatch
):
# We forced --fit off because Unsloth's (conservative) VRAM
@@ -19709,7 +19831,7 @@ class LlamaCppBackend:
not _did_fit_retry
and _fit_retry_allowed
and _startup_crashed
- and not _split_axis_crash
+ and not _tensor_capability_crash
and not _hip_rocr_mismatch
):
logger.warning(
@@ -19982,12 +20104,30 @@ class LlamaCppBackend:
_ts_out = "\n".join(self._stdout_lines[-50:])
_ts_rc = self._process.poll() if self._process is not None else None
if self._should_record_tensor_split_abort(_ts_rc, _ts_out):
- LlamaCppBackend._record_tensor_split_abort(binary, model_identifier)
+ LlamaCppBackend._record_tensor_split_abort(
+ binary, model_identifier, _planned_cache_pair
+ )
self._kill_process()
raise RuntimeError(
"llama-server aborted on --split-mode tensor "
"(split-axis geometry); retrying with layer split."
)
+ # Pre-b9455 llama.cpp refusing a quantized KV cache in tensor mode.
+ # Latched on this first spawn for the same reason as the abort
+ # above: the retries below cannot fix a capability the binary
+ # lacks, and only the first spawn carries the marker.
+ if self._is_tensor_quant_kv_unsupported(_ts_out):
+ # Binary-wide: one detection spares every later model and
+ # every other quantized type the same doomed startup.
+ LlamaCppBackend._record_tensor_quant_kv_unsupported(binary)
+ self._kill_process()
+ raise RuntimeError(
+ "This llama.cpp build does not support a quantized KV "
+ "cache with --split-mode tensor (added in b9455, "
+ "ggml-org/llama.cpp#23792). Retrying with layer split; "
+ "update llama.cpp to use tensor parallelism with a "
+ "quantized cache."
+ )
# "device kernel image is invalid": the auto-pinned device's arch has
# no kernels in this binary (#7624: an iGPU whose shared-RAM "free
# memory" outranked the dGPU). The proactive mapped_targets gate cannot
@@ -20622,6 +20762,12 @@ class LlamaCppBackend:
_last_spawn_cmd,
env,
)
+ # The pair the REQUEST resolved to, kept beside the pair that launched.
+ # A launch-time rewrite makes them differ (no --flash-attn resets a
+ # quantized V cache to f16, as does the flash-attn crash recovery), and
+ # the matcher wants the request: comparing the running pair against an
+ # unrewritten request rejects every identical repeat load.
+ self._requested_cache_types = _planned_cache_pair
self._kv_cache_context_total = effective_ctx if effective_ctx > 0 else None
# Server is up: adopt the real per-request context it allocated
@@ -21571,6 +21717,7 @@ class LlamaCppBackend:
self._n_ubatch = self._DEFAULT_N_UBATCH
self._flash_attn_enabled = True
self._effective_cache_types = ("f16", "f16")
+ self._requested_cache_types = ("f16", "f16")
self._kv_cache_context_total = None
self._chat_template = None
self._markup_tokens = []
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index c44febb8916..1ea9ed08087 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -1387,6 +1387,7 @@ try:
_kv_unified_from_args,
_metal_device_is_paravirtual,
_planned_main_cache_types,
+ _planned_scratch_cache_type,
_swa_full_from_args_or_env,
detect_reasoning_flags,
paravirtual_normalized_request,
@@ -1441,6 +1442,7 @@ except ImportError:
_kv_unified_from_args,
_metal_device_is_paravirtual,
_planned_main_cache_types,
+ _planned_scratch_cache_type,
_swa_full_from_args_or_env,
detect_reasoning_flags,
paravirtual_normalized_request,
@@ -7255,26 +7257,12 @@ def _estimate_gguf_kv_gb(
if ctx <= 0:
return 0.0
slots = max(1, n_parallel or 1)
- planned_cache_types = _planned_main_cache_types(
- cache_type_kv,
- llama_extra_args,
- )
- if tensor_parallel and any(
- cache_type not in LlamaCppBackend._TENSOR_PARALLEL_KV_TYPES
- for cache_type in planned_cache_types
- ):
- # Tensor mode strips quantized axes, but a layer fallback restores
- # the original settings. Size for the larger successful outcome.
- tensor_cache_types = _planned_main_cache_types(None, None)
- cache_type_for_budget = max(
- (*planned_cache_types, *tensor_cache_types, "f16"),
- key = _kv_bytes_per_elem,
- )
- else:
- cache_type_for_budget = max(
- planned_cache_types,
- key = _kv_bytes_per_elem,
- )
+ planned_cache_types = _planned_main_cache_types(cache_type_kv, llama_extra_args)
+ # KV bytes take the heavier axis (conservative for storage); the dequant
+ # scratch takes the lighter one, because any quantized axis allocates it and
+ # the heavier scalar hides a paired q4_0 behind an f16.
+ cache_type_for_budget = max(planned_cache_types, key = _kv_bytes_per_elem)
+ cache_type_for_scratch = _planned_scratch_cache_type(cache_type_kv, llama_extra_args)
# the loader raises --batch-size to max(slots, 2) before launch, and llama.cpp
# caps the micro-batch against it, so budget from the emitted value. Diffusion
# takes neither flag, and SWA metadata prices the KV against the micro-batch,
@@ -7369,7 +7357,7 @@ def _estimate_gguf_kv_gb(
# mirrors _plan_tensor_parallel: per-device buffer and ctx growth on every device
compute = devices * (
_flat_buffer(True)
- + probe._compute_buffer_ctx_bytes(ctx, effective_ubatch, cache_type_for_budget)
+ + probe._compute_buffer_ctx_bytes(ctx, effective_ubatch, cache_type_for_scratch)
)
else:
# mirrors the layer fit: flat buffer once, then per extra device, ctx growth per
@@ -7386,7 +7374,7 @@ def _estimate_gguf_kv_gb(
* probe._compute_buffer_ctx_bytes(
ctx,
effective_ubatch,
- cache_type_for_budget,
+ cache_type_for_scratch,
layer_split = devices > 1 and not pipeline_parallel_off,
)
)
diff --git a/studio/backend/tests/test_chat_load_during_training.py b/studio/backend/tests/test_chat_load_during_training.py
index f7732762b97..9e095910a55 100644
--- a/studio/backend/tests/test_chat_load_during_training.py
+++ b/studio/backend/tests/test_chat_load_during_training.py
@@ -2752,7 +2752,6 @@ class TestEstimateGgufRequiredGb(unittest.TestCase):
class _FakeBackend:
_context_length = 2048
- _TENSOR_PARALLEL_KV_TYPES = frozenset({"f16", "bf16", "f32"})
supports_kv_unified = True
def _read_gguf_metadata(self, path):
@@ -2854,13 +2853,15 @@ class TestEstimateGgufRequiredGb(unittest.TestCase):
):
r._estimate_gguf_kv_gb("m", 4096)
self.assertEqual(seen["cache_type"], "q4_0")
+ # Tensor mode passes the requested type through, so the budget matches it.
r._estimate_gguf_kv_gb(
"m",
4096,
["--cache-type-k", "q4_0", "--cache-type-v", "q4_0"],
tensor_parallel = True,
)
- self.assertEqual(seen["cache_type"], "f16")
+ self.assertEqual(seen["cache_type"], "q4_0")
+ # The heavier axis still wins, tensor or not.
r._estimate_gguf_kv_gb(
"m",
4096,
diff --git a/studio/backend/tests/test_compute_buffer.py b/studio/backend/tests/test_compute_buffer.py
index 7f8d7fc2c1a..30bab5228a0 100644
--- a/studio/backend/tests/test_compute_buffer.py
+++ b/studio/backend/tests/test_compute_buffer.py
@@ -56,7 +56,13 @@ except ImportError:
)
sys.modules["httpx"] = _httpx_stub
-from core.inference.llama_cpp import _FIT_MIN_CTX, LlamaCppBackend
+from core.inference.llama_cpp import (
+ _FIT_MIN_CTX,
+ _kv_bytes_per_elem,
+ _planned_main_cache_types,
+ _planned_scratch_cache_type,
+ LlamaCppBackend,
+)
MIB = 1024 * 1024
GIB = 1024 * MIB
@@ -79,6 +85,31 @@ def _backend(
return b
+def _backend_from_gguf_local(
+ n_layers = 80,
+ embd = 8192,
+ n_kv_heads = 8,
+ head_dim = 128,
+):
+ """Backend that can also estimate KV bytes, for the planner cells below.
+
+ A real ``__init__`` (not ``__new__`` like ``_backend`` above) so every
+ attribute the KV estimator reads exists at its default; only the handful of
+ dims these cells vary are overridden. These tests are about which cache type
+ is priced, not about GGUF parsing.
+ """
+ b = LlamaCppBackend()
+ b._vocab_size = 248_320
+ b._embedding_length = embd
+ b._n_layers = n_layers
+ b._n_kv_heads = n_kv_heads
+ b._kv_key_length = head_dim
+ b._kv_value_length = head_dim
+ b._context_length = 262_144
+ assert b._can_estimate_kv()
+ return b
+
+
# Measured ground truth (MiB) the estimate must upper-bound.
_PIPELINE_MEASURED = {1: 36, 2: 492, 4: 1388, 8: 3220}
_TENSOR_MEASURED_PER_DEVICE = 600
@@ -1222,3 +1253,124 @@ class TestSplitRateRecheckAfterSelection:
slots = "".join(inspect.getsource(LlamaCppBackend._slots_that_fit_on_gpu).split())
assert "self._select_gpus_split_aware(" in slots
assert "split_extra_bytes=split_extra_bytes," in slots
+
+
+# ── The scratch rate keys off the LIGHTER axis ───────────────────────────────
+#
+# Since ggml-org/llama.cpp#23792 Studio no longer rewrites the requested type for the
+# tensor attempt, so an asymmetric pair is reachable in the one mode with no --fit
+# valve. The budget resolves ONE scalar, the heavier axis, for KV bytes; handing that
+# to _compute_buffer_ctx_bytes prices a q4_0 K cache as if nothing were quantized,
+# because the dequant branch gates on bytes/elem < 2.0.
+
+
+class TestScratchTakesTheLighterAxis:
+ """_planned_scratch_cache_type is the seam that keeps the two terms honest:
+ heavier axis for KV bytes, lighter axis for the dequant scratch."""
+
+ @pytest.mark.parametrize(
+ "k,v,expected",
+ [
+ ("f16", "f16", "f16"),
+ ("q8_0", "q8_0", "q8_0"),
+ ("q4_0", "f16", "q4_0"), # the shape the heavier scalar hides
+ ("f16", "q4_0", "q4_0"), # and with the axes swapped
+ ("q8_0", "q4_0", "q4_0"),
+ ("f32", "q8_0", "q8_0"),
+ ],
+ )
+ def test_it_picks_the_quantized_axis_whichever_side_it_is_on(self, k, v, expected):
+ extras = ["--cache-type-k", k, "--cache-type-v", v]
+ assert _planned_scratch_cache_type(None, extras) == expected
+ # And the budget still takes the heavier one, so the two disagree exactly
+ # when they should.
+ heavier = max(_planned_main_cache_types(None, extras), key = _kv_bytes_per_elem)
+ assert (heavier != expected) == (_kv_bytes_per_elem(k) != _kv_bytes_per_elem(v))
+
+ def test_a_managed_symmetric_request_leaves_both_terms_equal(self):
+ """Studio emits one type on both axes, so nothing changes for the common
+ case -- this fix must not move the fit for a plain q8_0 load."""
+ for kv in ("f16", "q8_0", "q4_0", "iq4_nl"):
+ assert _planned_scratch_cache_type(kv, None) == kv
+
+ def test_extras_beat_the_managed_field_per_axis(self):
+ """Extras are appended last and win per axis, so the scratch must follow
+ them, not the field the UI sent."""
+ assert _planned_scratch_cache_type("f16", ["--cache-type-k", "q4_0"]) == "q4_0"
+
+ def test_it_reads_the_inherited_env_when_nothing_else_sets_a_type(self):
+ env = {"LLAMA_ARG_CACHE_TYPE_K": "q4_0", "LLAMA_ARG_CACHE_TYPE_V": "f16"}
+ assert _planned_scratch_cache_type(None, None, env) == "q4_0"
+
+ @pytest.mark.parametrize("k,v", [("q4_0", "f16"), ("f16", "q4_0")])
+ def test_the_asymmetric_pair_selects_the_dequant_rate(self, k, v):
+ """The point of the seam: at the same context the asymmetric pair must
+ cost what the quantized axis really allocates, not the KQ-mask floor."""
+ b = _backend()
+ extras = ["--cache-type-k", k, "--cache-type-v", v]
+ heavier = max(_planned_main_cache_types(None, extras), key = _kv_bytes_per_elem)
+ lighter = _planned_scratch_cache_type(None, extras)
+
+ heavy_rate = b._compute_buffer_ctx_bytes(131_072, 2048, heavier)
+ light_rate = b._compute_buffer_ctx_bytes(131_072, 2048, lighter)
+
+ assert light_rate > heavy_rate, (light_rate, heavy_rate)
+ # Same answer as a symmetric quantized cache: the scratch is per-tensor
+ # work on the quantized axis, not something the f16 axis discounts.
+ assert light_rate == b._compute_buffer_ctx_bytes(131_072, 2048, "q4_0")
+
+
+class TestTensorFitPricesTheQuantizedAxis:
+ """End to end through the planner: the advertised context must not exceed
+ what an honest per-axis price allows. Tensor mode has no --fit valve, so an
+ optimistic context OOMs at startup instead of spilling."""
+
+ @staticmethod
+ def _plan(
+ b,
+ cache_type,
+ scratch_type,
+ ub,
+ ngpu = 4,
+ per_gpu = 48_000,
+ ):
+ return b._plan_tensor_parallel(
+ gpus = [(i, per_gpu) for i in range(ngpu)],
+ model_size = 60 * 1024**3,
+ target_ctx = 262_144,
+ max_target_ctx = 262_144,
+ total_by_idx = {i: per_gpu for i in range(ngpu)},
+ cache_type_kv = cache_type,
+ scratch_cache_type_kv = scratch_type,
+ n_parallel = 1,
+ swa_full = False,
+ kv_unified = True,
+ n_ubatch = ub,
+ flash_attn = False,
+ )
+
+ def test_an_asymmetric_pair_is_capped_like_its_quantized_axis(self):
+ """-ctk q4_0 -ctv f16 at a raised micro-batch. Priced from the heavier
+ axis alone the planner advertises the full 262144; the quantized axis
+ cannot hold it."""
+ b = _backend_from_gguf_local()
+ optimistic = self._plan(b, "f16", None, 2048)[0]
+ honest = self._plan(b, "f16", "q4_0", 2048)[0]
+
+ assert honest < optimistic, (honest, optimistic)
+ # Still a real context, not the 2048 floor: the fix must not collapse the
+ # fit, only stop it over-advertising.
+ assert honest > 2048, honest
+ # It comes out BELOW a symmetric q4_0 load, which is right and worth
+ # pinning: the asymmetric pair pays f16 KV bytes on both axes (the heavier
+ # axis budgets storage) AND the full quantized dequant scratch. Both terms
+ # conservative is the point; neither one alone describes this launch.
+ assert honest < self._plan(b, "q4_0", "q4_0", 2048)[0]
+
+ def test_a_symmetric_request_is_unchanged(self):
+ """Default and explicit scratch type agree when both axes match, so no
+ existing load moves."""
+ b = _backend_from_gguf_local()
+ for kv in ("f16", "q8_0", "q4_0"):
+ for ub in (512, 2048):
+ assert self._plan(b, kv, None, ub) == self._plan(b, kv, kv, ub)
diff --git a/studio/backend/tests/test_gguf_reload_inheritance.py b/studio/backend/tests/test_gguf_reload_inheritance.py
index d8d3108f68b..da64f6e3fee 100644
--- a/studio/backend/tests/test_gguf_reload_inheritance.py
+++ b/studio/backend/tests/test_gguf_reload_inheritance.py
@@ -14,6 +14,8 @@ 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)
@@ -274,3 +276,105 @@ def test_already_in_target_state_explicit_extras_match():
def test_extra_args_source_default_is_none():
backend = LlamaCppBackend()
assert backend.extra_args_source is None
+
+
+class TestRepeatLoadMatchesTheEffectiveCache:
+ """A repeat /load of an identical request must reuse the healthy server.
+
+ self._cache_type_kv records only what Studio emitted as a MANAGED flag, so a
+ cache set through extras or the environment leaves it None on one side and a
+ type on the other; the old scalar-against-scalar comparison then read an
+ identical repeat as a mismatch and tore the server down to relaunch the same
+ thing. Before ggml-org/llama.cpp#23792 the tensor gate hid this by rewriting
+ the cache away; a layer load has always had it.
+ """
+
+ @staticmethod
+ def _backend_running(effective):
+ """A backend carrying only the field the comparison reads: the per-axis
+ pair the live child was launched with."""
+ from core.inference.llama_cpp import LlamaCppBackend
+
+ b = LlamaCppBackend.__new__(LlamaCppBackend)
+ b._effective_cache_types = effective
+ return b
+
+ @pytest.mark.parametrize(
+ "extras,managed",
+ [
+ (["--cache-type-k", "q8_0", "--cache-type-v", "q8_0"], None), # extras only
+ (["--cache-type-k", "q4_0", "--cache-type-v", "f16"], None), # asymmetric
+ ([], "q8_0"), # managed only
+ ([], None), # nothing set
+ ],
+ )
+ def test_the_same_request_resolves_to_the_running_pair(self, extras, managed):
+ from core.inference.llama_cpp import _planned_main_cache_types
+
+ planned = _planned_main_cache_types(managed, extras)
+ running = self._backend_running(planned)
+
+ # The comparison the matcher makes, isolated: same request in, same pair out.
+ assert running._effective_cache_types == _planned_main_cache_types(managed, extras)
+
+ def test_a_changed_cache_still_reloads(self):
+ from core.inference.llama_cpp import _planned_main_cache_types
+ running = self._backend_running(("q8_0", "q8_0"))
+
+ assert running._effective_cache_types != _planned_main_cache_types(
+ None, ["--cache-type-k", "f16", "--cache-type-v", "f16"]
+ )
+
+ def test_the_matcher_compares_the_pair_not_the_managed_scalar(self):
+ """Source-pinned: the scalar cannot describe an extras-only or env cache,
+ so reintroducing it here would bring the spurious reload back."""
+ import inspect
+
+ from core.inference.llama_cpp import LlamaCppBackend
+
+ src = "".join(inspect.getsource(LlamaCppBackend._runtime_matches_intent).split())
+ assert "self._requested_cache_types!=_planned_main_cache_types(" in src
+ assert "_norm(self._cache_type_kv)!=_norm(intent.cache_type_kv)" not in src
+
+ def test_a_launch_time_rewrite_does_not_force_a_reload(self):
+ """The comparison is requested-against-requested, so a rewrite the launch
+ performed does not make the next identical request look different.
+
+ A build with no --flash-attn resets a quantized V cache to f16 before the
+ spawn (and the flash-attn crash recovery does the same), so the pair that
+ LAUNCHED is not the pair that was ASKED for. Comparing the running pair
+ would then reject every repeat and redo that normalization each time.
+ """
+ from core.inference.llama_cpp import (
+ LlamaCppBackend,
+ _effective_main_cache_types,
+ _planned_main_cache_types,
+ )
+
+ extras = ["--cache-type-k", "q8_0", "--cache-type-v", "q8_0"]
+ asked = _planned_main_cache_types(None, extras)
+ cmd = ["llama-server", "-m", "/x.gguf", *extras]
+ b = LlamaCppBackend.__new__(LlamaCppBackend)
+ b._architecture = None
+ launched = _effective_main_cache_types(
+ LlamaCppBackend._reset_quantized_v_cache(
+ cmd, "this build has no --flash-attn", mla = False, draft_mla = None
+ ),
+ {},
+ )
+
+ assert asked == ("q8_0", "q8_0")
+ assert launched == ("q8_0", "f16"), launched
+ # The matcher reads the first, not the second.
+ b._requested_cache_types = asked
+ assert b._requested_cache_types == _planned_main_cache_types(None, extras)
+
+ def test_the_requested_pair_is_recorded_next_to_the_effective_one(self):
+ """Both are recorded on the same success path, so one cannot drift."""
+ import inspect
+
+ from core.inference.llama_cpp import LlamaCppBackend
+
+ load = "".join(inspect.getsource(LlamaCppBackend.load_model).split())
+ assert "self._effective_cache_types=_effective_main_cache_types(" in load
+ assert "self._requested_cache_types=_planned_cache_pair" in load
diff --git a/studio/backend/tests/test_gpu_memory_mode.py b/studio/backend/tests/test_gpu_memory_mode.py
index 53cfa03d621..3c0ddd5e1dc 100644
--- a/studio/backend/tests/test_gpu_memory_mode.py
+++ b/studio/backend/tests/test_gpu_memory_mode.py
@@ -215,16 +215,9 @@ def test_auto_layers_branch_empties_gpus_and_drops_tensor_parallel():
# The branch sits before GPU selection assigns gpu_indices; --fit on is its emission.
assert gate < src.find("gpu_indices, use_fit = None, True")
assert 'cmd.extend(["--fit", "on"])' in src
- # TP drops for this path, but at a guard BEFORE the quantized-KV cache-drop, so
- # a requested quantized cache survives into the --fit load.
tp_drop = src.find('if tensor_parallel and gpu_memory_mode == "manual" and gpu_layers < 0:')
assert tp_drop != -1, "manual + Auto layers must drop tensor_parallel"
assert "tensor_parallel = False" in src[tp_drop : tp_drop + 400]
- cache_drop = src.find("Tensor parallelism requires a non-quantized KV cache")
- assert cache_drop != -1
- assert (
- tp_drop < cache_drop
- ), "TP must drop before the cache-drop so a quantized KV survives --fit"
def test_auto_layers_never_sends_ctx_size_zero():
diff --git a/studio/backend/tests/test_llama_cpp_placement.py b/studio/backend/tests/test_llama_cpp_placement.py
index 0a4849fba68..fb4b28b2bec 100644
--- a/studio/backend/tests/test_llama_cpp_placement.py
+++ b/studio/backend/tests/test_llama_cpp_placement.py
@@ -1347,6 +1347,55 @@ def test_a_single_gpu_tensor_request_is_probed_as_the_layer_load_it_is(tmp_path)
assert backend.spec_fallback_reason == "drafter_no_vram"
+ "n_gpus, model_gb, aborts, load_kwargs",
+ [
+ # One row per strip site in load_model. Placement is the whole point, so
+ # the rows are the sites, not the drop reasons -- two manual-mode drops
+ # share a strip and would be one row's worth of coverage twice.
+ (2, 1, True, {}), # a recorded --split-mode tensor abort
+ (1, 1, False, {}), # fewer than 2 GPUs clear the compute-buffer reserve
+ (2, 80, False, {}), # pooled VRAM cannot hold the weights
+ (2, 1, False, {"gpu_memory_mode": "manual"}), # Auto layers: --fit owns memory
+ # gpu_ids, not n_gpus: this guard counts the selection (or torch's visible
+ # devices), so without a pin it passes only because torch is absent here.
+ (2, 1, False, {"gpu_memory_mode": "manual", "gpu_layers": 20, "gpu_ids": [0]}),
+ ],
+)
+def test_a_dropped_tensor_request_launches_as_a_layer_split(
+ tmp_path, n_gpus, model_gb, aborts, load_kwargs
+):
+ """A downgrade has to land a working layer split, not merely lose a flag: the
+ server comes up in layer mode and the user's unrelated extras still reach it.
+ Extras are appended last, so a --split-mode tensor left among them would
+ re-engage the mode the downgrade just dropped."""
+ backend, gguf = _backend(
+ tmp_path,
+ vulkan = False,
+ memory = [(i, 24_000, 24_000) for i in range(n_gpus)],
+ )
+ backend._tensor_split_aborts = lambda *args, **kwargs: aborts
+ # _backend stubs the weights at 1 KB; only a real size trips the pooled-VRAM case.
+ backend._get_gguf_size_bytes = lambda _path: model_gb * 1024**3
+
+ cmd = _launch(
+ backend,
+ gguf,
+ tensor_parallel = True,
+ extra_args = ["--split-mode", "tensor", "--tensor-split", "3,1", "--top-k", "5"],
+ **load_kwargs,
+ )["cmd"]
+
+ # The load is the layer split the downgrade chose ...
+ assert backend.tensor_parallel is False
+ # ... it still carries the user's unrelated extras ...
+ assert "--top-k" in cmd
+ # ... and not the split-mode group -- --tensor-split rides with the mode, so a
+ # strip narrowed to --split-mode alone leaves the user's ratio behind.
+ assert "--split-mode" not in cmd
+ assert "--tensor-split" not in cmd
+
+
def test_the_probe_prices_the_drafter_at_a_context_the_weakest_card_can_hold(tmp_path):
"""The compute buffer is replicated on every device of a layer split, so a
pooled budget can price a context the smallest card cannot hold; the placement
@@ -2317,3 +2366,76 @@ def test_a_paravirtual_metal_launch_prices_the_whole_model(tmp_path, monkeypatch
assert backend._launch_host_shortfall_message(argv, [], {}) is None
assert backend._launch_host_shortfall_message(argv, [], {}, child_has_no_gpu = True) is not None
+
+
+# ── Tensor parallelism keeps the requested KV cache type ─────────────
+
+
+def _tensor_backend(tmp_path):
+ backend, gguf = _backend(
+ tmp_path,
+ vulkan = False,
+ memory = [(0, 24_000, 24_000), (1, 24_000, 24_000)],
+ )
+ backend._tensor_split_aborts = lambda *args, **kwargs: False
+ return backend, gguf
+
+
[email protected]("kv_type", ["q8_0", "q4_0"])
+def test_tensor_mode_emits_the_requested_quantized_kv(tmp_path, kv_type):
+ """llama.cpp runs a quantized KV cache under --split-mode tensor (ggml-org/
+ llama.cpp#23792), so the requested type reaches the child verbatim. Two types,
+ so a q8_0-only carve-out cannot pass."""
+ backend, gguf = _tensor_backend(tmp_path)
+
+ cmd = _launch(backend, gguf, tensor_parallel = True, cache_type_kv = kv_type)["cmd"]
+
+ assert cmd[cmd.index("--split-mode") + 1] == "tensor"
+ assert cmd[cmd.index("--cache-type-k") + 1] == kv_type
+ assert cmd[cmd.index("--cache-type-v") + 1] == kv_type
+ # The recorded type /status reports and the reload matcher compares against.
+ assert backend.cache_type_kv == kv_type
+
+
+def test_an_unknown_kv_type_is_still_refused_in_tensor_mode(tmp_path):
+ """_valid_cache_types drops a type llama.cpp's kv_cache_type_from_str does not
+ know, emitting no flag rather than aborting the child. Tensor mode does not
+ widen it."""
+ backend, gguf = _tensor_backend(tmp_path)
+
+ cmd = _launch(backend, gguf, tensor_parallel = True, cache_type_kv = "q3_K")["cmd"]
+
+ assert cmd[cmd.index("--split-mode") + 1] == "tensor"
+ assert "--cache-type-k" not in cmd
+ assert "--cache-type-v" not in cmd
+ assert backend.cache_type_kv is None
+
+
+def test_tensor_mode_keeps_an_inherited_quantized_kv_env(tmp_path, monkeypatch):
+ """The tensor-branch env scrub owns the split, not the cache type: an
+ LLAMA_ARG_CACHE_TYPE_K/_V reaches the child untouched, while the tensor split
+ Unsloth emits itself is still cleared. The inherited type also reaches tensor
+ placement accounting -- priced as banded/f16 instead, an Inkling child's dense
+ fallback OOMs an auto context the plan advertised as fitting."""
+ monkeypatch.setenv("LLAMA_ARG_CACHE_TYPE_K", "q8_0")
+ monkeypatch.setenv("LLAMA_ARG_CACHE_TYPE_V", "q8_0")
+ monkeypatch.setenv("LLAMA_ARG_TENSOR_SPLIT", "9,1")
+ backend, gguf = _tensor_backend(tmp_path)
+ planned = {}
+ real_plan = backend._plan_tensor_parallel
+
+ with patch.object(
+ backend,
+ "_plan_tensor_parallel",
+ side_effect = lambda *a, **kw: planned.update(kw) or real_plan(*a, **kw),
+ ):
+ captured = _launch(backend, gguf, tensor_parallel = True)
+ env, cmd = captured["env"], captured["cmd"]
+
+ assert env["LLAMA_ARG_CACHE_TYPE_K"] == "q8_0"
+ assert env["LLAMA_ARG_CACHE_TYPE_V"] == "q8_0"
+ assert "LLAMA_ARG_TENSOR_SPLIT" not in env
+ assert planned["cache_type_kv"] == "q8_0"
+ # Budget-only adoption: the env stays the source of truth for the child.
+ assert "--cache-type-k" not in cmd
+ assert "--cache-type-v" not in cmd
diff --git a/studio/backend/tests/test_llama_cpp_start_failure_classification.py b/studio/backend/tests/test_llama_cpp_start_failure_classification.py
index b33db7b1e0e..c6c5785b8f7 100644
--- a/studio/backend/tests/test_llama_cpp_start_failure_classification.py
+++ b/studio/backend/tests/test_llama_cpp_start_failure_classification.py
@@ -1852,3 +1852,57 @@ class TestArgumentErrorsAreQuotedShort:
assert "--tempp" in msg
assert "..." not in msg
+
+
+class TestTensorSplitQuantizedKvUnsupported:
+ """llama.cpp before ggml-org/llama.cpp#23792 (b9455) refused a quantized KV
+ cache under --split-mode tensor. Studio no longer pre-empts that refusal, so
+ the message has to name the remedy: the generic invalid-GGUF/OOM fallback sends
+ the user to check their file or buy VRAM, neither of which is the problem."""
+
+ # Verbatim from the guard #23792 deleted in src/llama-context.cpp.
+ _OUT = (
+ "llama_init_from_model: simultaneous use of SPLIT_MODE_TENSOR and "
+ "KV cache quantization not implemented\n"
+ )
+
+ def test_the_legacy_refusal_names_the_build_and_the_remedies(self):
+ msg = _classify(self._OUT, "/models/x.gguf", "local/x", 2)
+
+ assert "b9455" in msg
+ assert "quantized KV cache" in msg
+ # All three ways out, because which one is available depends on whether the
+ # user controls the binary.
+ assert "Update" in msg
+ assert "f16" in msg
+ assert "Tensor Parallelism" in msg
+ # Not the fallback it used to get.
+ assert "GGUF file is valid" not in msg
+
+ def test_it_does_not_shadow_the_architecture_gate(self):
+ """A different, permanent, per-model limit with its own remedy."""
+ out = "llama_init_from_model: split_mode_tensor not implemented for this arch\n"
+ msg = _classify(out, "/models/x.gguf", "local/x", 2)
+
+ assert "architecture" in msg
+ assert "b9455" not in msg
+
+ def test_the_marker_is_matched_case_insensitively(self):
+ """llama.cpp prints SPLIT_MODE_TENSOR upper-case; the classifier lowers."""
+ assert LlamaCppBackend._is_tensor_quant_kv_unsupported(self._OUT)
+ assert LlamaCppBackend._is_tensor_quant_kv_unsupported(self._OUT.lower())
+ assert not LlamaCppBackend._is_tensor_quant_kv_unsupported("")
+ assert not LlamaCppBackend._is_tensor_quant_kv_unsupported(
+ "split_mode_tensor not implemented"
+ )
+
+ def test_a_hard_crash_carrying_it_is_not_retried_as_a_projector_fault(self):
+ """_output_has_nonprojector_diagnostic gates the text-only vision retry.
+ Without the marker a doomed tensor load would also pay that retry."""
+ assert LlamaCppBackend._output_has_nonprojector_diagnostic(self._OUT)
+
+ def test_it_is_not_the_signal_crash_the_split_axis_latch_requires(self):
+ """It is LLAMA_LOG_ERROR + return nullptr, so exit 1 with no signal --
+ which is why it needs its own recording path rather than the #6415 one."""
+ assert not LlamaCppBackend._should_record_tensor_split_abort(1, self._OUT)
+ assert not LlamaCppBackend._is_tensor_split_assert(self._OUT)
diff --git a/studio/backend/tests/test_mmproj_placement_policy.py b/studio/backend/tests/test_mmproj_placement_policy.py
index 662305ede75..52504a79894 100644
--- a/studio/backend/tests/test_mmproj_placement_policy.py
+++ b/studio/backend/tests/test_mmproj_placement_policy.py
@@ -1554,7 +1554,10 @@ def test_both_cpu_recovery_call_sites_pass_the_vision_state(tmp_path):
assert source.count("disable_vision = disable_vision,") == calls
-def test_a_tensor_load_downgraded_to_layer_split_still_gives_the_projector_up(tmp_path):
[email protected]("cache_type_kv", [None, "q8_0"])
+def test_a_tensor_load_downgraded_to_layer_split_still_gives_the_projector_up(
+ tmp_path, cache_type_kv
+):
"""The corner the probe's TP exclusion used to leave at main's behaviour.
Tensor parallelism is requested, so the probe withholds its answer: layer-split
@@ -1564,12 +1567,15 @@ def test_a_tensor_load_downgraded_to_layer_split_still_gives_the_projector_up(tm
downgrade is final the load is layer split, the probe's answer applies, and the
projector goes to the CPU instead of the model spilling layers around it.
+ Both cache types, because the downgrade leaves the requested one alone: the probe
+ prices the cache that actually loads, so the verdict holds for either.
+
Two cards too small to pool the 6 GiB model with its 1 GiB projector, but large
enough to hold the model alone once the encoder moves.
"""
backend, gguf = _backend(tmp_path, memory = [(0, 4_400, 8_192), (1, 4_400, 8_192)])
- cmd = _launch(backend, gguf, tensor_parallel = True)["cmd"]
+ cmd = _launch(backend, gguf, tensor_parallel = True, cache_type_kv = cache_type_kv)["cmd"]
# Reachable ONLY through the deferred application: with tensor_parallel requested
# the probe never applies its verdict at the probe site.
@@ -1597,27 +1603,11 @@ def test_a_surviving_tensor_load_keeps_its_projector(tmp_path):
assert "--no-mmproj-offload" not in cmd
-def test_a_dropped_quantized_cache_holds_the_deferred_pin_back(tmp_path):
- """The verdict was measured against the f16 cache the tensor attempt ran with.
-
- _restore_after_tensor_downgrade puts the quantized cache back before layer
- placement, so the footprint the verdict priced is heavier than the one that
- actually loads. Acting on it would pin a projector that fits and buy an 8.8x
- image encode for nothing, which is the outcome this probe exists to avoid.
- """
- backend, gguf = _backend(tmp_path, memory = [(0, 4_400, 8_192), (1, 4_400, 8_192)])
-
- cmd = _launch(backend, gguf, tensor_parallel = True, cache_type_kv = "q8_0")["cmd"]
-
- assert "--mmproj" in cmd
- assert "--no-mmproj-offload" not in cmd
-
-
def test_a_gpu_drafter_holds_the_deferred_pin_back(tmp_path):
- """The drafter-drop probe carries the same tensor exclusion this one did, so it
- has not run either. The documented order is projector first and drafter second;
- pinning without being able to re-ask the second half pays the encoder cost and
- still reaches --fit on."""
+ """The drafter-drop probe is gated off under tensor parallelism, so it has not
+ run. The documented order is projector first and drafter second; pinning without
+ being able to re-ask the second half pays the encoder cost and still reaches
+ --fit on."""
backend, gguf = _drafter_backend(tmp_path, [(0, 4_400, 8_192), (1, 4_400, 8_192)])
cmd = _launch(
diff --git a/studio/backend/tests/test_mtp_vram_budget.py b/studio/backend/tests/test_mtp_vram_budget.py
index e479aeab942..eed8b9d8869 100644
--- a/studio/backend/tests/test_mtp_vram_budget.py
+++ b/studio/backend/tests/test_mtp_vram_budget.py
@@ -988,8 +988,9 @@ class TestExtraArgsMtpDetection:
def test_env_main_cache_type_for_budget(self):
# The child inherits LLAMA_ARG_CACHE_TYPE_K/_V, but Unsloth emits no
- # --cache-type when neither param nor extras set it -> a heavier env
- # main KV (f32) must be adopted so the reserve matches the child.
+ # --cache-type when neither param nor extras set it -> an env type that
+ # budgets differently from f16 must be adopted so the reserve matches
+ # the child.
assert _env_main_cache_type_for_budget(env = {}) is None
# f32 exceeds the f16 default -> adopt it (lower-cased so the launch
# re-emits it via _valid_cache_types).
@@ -1002,9 +1003,35 @@ class TestExtraArgsMtpDetection:
)
== "f32"
)
- # Quantized env types are <= f16 -> already over-reserved by the default.
+ # Quantized env types now launch and flip the scratch pricing, so adopt them,
+ # but only when the PAIR is heavier-different from f16. One quantized axis
+ # leaves the other at the f16 default, so the heavier axis IS f16 and its
+ # reserve is already safe; adopting q4_0 would price that untouched axis as
+ # quantized and under-reserve it, worst when key_length > value_length puts
+ # the cheap type on the larger tensor. The scratch term reads the pair per
+ # axis, so leaving the KV scalar at the default loses nothing.
assert _env_main_cache_type_for_budget(env = {"LLAMA_ARG_CACHE_TYPE_K": "q4_0"}) is None
assert _env_main_cache_type_for_budget(env = {"LLAMA_ARG_CACHE_TYPE_V": "q8_0"}) is None
+ assert (
+ _env_main_cache_type_for_budget(
+ env = {"LLAMA_ARG_CACHE_TYPE_K": "q4_0", "LLAMA_ARG_CACHE_TYPE_V": "q4_0"}
+ )
+ == "q4_0"
+ )
+ assert (
+ _env_main_cache_type_for_budget(
+ env = {"LLAMA_ARG_CACHE_TYPE_K": "q4_0", "LLAMA_ARG_CACHE_TYPE_V": "q8_0"}
+ )
+ == "q8_0"
+ )
+ # Heavier-axis rule as for extras: a set f16/f32 beside a quantized axis
+ # wins, keeping the KV reserve safe for the heavier axis.
+ assert (
+ _env_main_cache_type_for_budget(
+ env = {"LLAMA_ARG_CACHE_TYPE_K": "q8_0", "LLAMA_ARG_CACHE_TYPE_V": "f32"}
+ )
+ == "f32"
+ )
assert _env_main_cache_type_for_budget(env = {"LLAMA_ARG_CACHE_TYPE_K": "f16"}) is None
# Unknown env type self-neutralizes (treated as f16 by _kv_bytes_per_elem).
assert _env_main_cache_type_for_budget(env = {"LLAMA_ARG_CACHE_TYPE_K": "wat"}) is None
@@ -1086,28 +1113,6 @@ class TestExtraArgsMtpDetection:
load = "".join(inspect.getsource(LlamaCppBackend.load_model).split())
assert "_extra_args_main_cache_type_for_budget(extra_args)" in load
- def test_load_model_tensor_drops_any_quantized_cache_axis(self):
- # The heavier-by-bytes budget type can mask a quantized axis (an f16
- # budget hides a paired q4_0), so the tensor-safety drop must test each
- # --cache-type-k/-v extra, not just cache_type_kv -- else the quantized
- # axis survives into tensor mode and crashes the load (#6312).
- load = "".join(inspect.getsource(LlamaCppBackend.load_model).split())
- assert "_ck_extra,_cv_extra=parse_cache_override_per_axis(extra_args)" in load
- assert "forcin(cache_type_kv,_ck_extra,_cv_extra)" in load
- assert "iftensor_paralleland_cache_non_tensor_safe:" in load
-
- def test_load_model_layer_downgrade_restores_original_cache_extras(self):
- # Tensor mode strips asymmetric --cache-type-k/-v (it rejects quantized),
- # but layer split supports them, so a downgrade must restore the ORIGINAL
- # extras, not just the scalar heavier type (else q4_0/f16 silently becomes
- # f16/f16 on the layer fallback) (#6312).
- load = "".join(inspect.getsource(LlamaCppBackend.load_model).split())
- assert "_tensor_dropped_extra_args=list(extra_args)" in load
- # The original extras are restored via one shared closure, called at all
- # three tensor->layer downgrade points.
- assert "strip_split_mode_only(_tensor_dropped_extra_argsif" in load
- assert load.count("_restore_after_tensor_downgrade()") >= 3
-
def test_load_model_tensor_skips_reserve_for_cpu_drafter(self):
# A separate CPU-offloaded drafter (no embedded head) uses no GPU, so the
# tensor reserve must be suppressed like the layer path -- else tensor mode
@@ -1157,16 +1162,6 @@ class TestExtraArgsMtpDetection:
assert 'env.pop("LLAMA_ARG_SPLIT_MODE",None)' in compact
assert 'env.pop("LLAMA_ARG_TENSOR_SPLIT",None)' in compact
- def test_load_model_clears_quantized_kv_env_for_tensor(self):
- # Cluster B: tensor mode aborts on quantized KV. An inherited quantized
- # LLAMA_ARG_CACHE_TYPE_K/_V must be popped from the child env so it cannot
- # crash the tensor child (and matches the tensor-safe budget).
- # Whitespace-stripped for formatter.
- compact = "".join(inspect.getsource(LlamaCppBackend.load_model).split())
- assert '("LLAMA_ARG_CACHE_TYPE_K","LLAMA_ARG_CACHE_TYPE_V")' in compact
- assert "_ct_rawnotinself._TENSOR_PARALLEL_KV_TYPES" in compact
- assert "env.pop(_ct_var,None)" in compact
-
def test_load_model_clears_tensor_split_env_in_tensor_mode(self):
# review run3 #2: Unsloth owns the tensor split. When it emits no
# --tensor-split (even split), a stale inherited LLAMA_ARG_TENSOR_SPLIT must
@@ -1248,3 +1243,118 @@ def test_mtp_draft_budget_prefers_user_extras_drafter():
assert "_cli_draft_for_budgetor_studio_draft_for_budgetor_env_draft_for_budget" in compact
# The env must not be consulted before Unsloth's resolved drafter.
assert "_extra_args_mtp_draft_path(extra_args)ormtp_draft_path" not in compact
+
+
+class TestUnemittableCacheTypeFallsBackToTheEnvBudget:
+ """A type llama.cpp's kv_cache_type_from_str does not know is never emitted
+ (_VALID_CACHE_TYPES), so the child inherits LLAMA_ARG_CACHE_TYPE_K/_V instead.
+
+ Before ggml-org/llama.cpp#23792 Studio's tensor gate happened to cover this:
+ it dropped any type outside {f16,bf16,f32} -- including an unknown one -- and
+ then re-adopted the heavier env type for the reserve, with the comment "Else
+ the child allocates f32 KV against an f16 budget." Removing the gate removed
+ that re-adoption too, so the budget has to notice on its own.
+ """
+
+ @staticmethod
+ def _budget_type(cache_type_kv, env):
+ """The cache type load_model resolves for the reserve, via the same
+ precedence chain: extras, then the field, then a heavier inherited env."""
+ from core.inference.llama_cpp import (
+ _VALID_CACHE_TYPES,
+ _env_main_cache_type_for_budget,
+ )
+
+ resolved = cache_type_kv
+ if resolved is not None and resolved.strip().lower() not in _VALID_CACHE_TYPES:
+ resolved = None
+ if resolved is None:
+ resolved = _env_main_cache_type_for_budget(env)
+ return resolved
+
+ def test_an_unknown_type_does_not_shadow_a_heavier_inherited_env(self):
+ """q3_K is not emittable, so the child really runs the inherited f32.
+ Budgeting "q3_K" prices it at _kv_bytes_per_elem's 2.0 unknown default --
+ a clean 2x under-reservation, in the one mode with no --fit valve."""
+ env = {"LLAMA_ARG_CACHE_TYPE_K": "f32", "LLAMA_ARG_CACHE_TYPE_V": "f32"}
+ assert self._budget_type("q3_K", env) == "f32"
+
+ def test_an_emittable_type_still_wins_over_the_env(self):
+ """q8_0 IS emitted, so it overrides the env on both axes and must be what
+ the budget prices -- the whole point of #8939."""
+ env = {"LLAMA_ARG_CACHE_TYPE_K": "f32", "LLAMA_ARG_CACHE_TYPE_V": "f32"}
+ assert self._budget_type("q8_0", env) == "q8_0"
+
+ def test_an_unknown_type_with_no_env_is_left_at_the_f16_default(self):
+ assert self._budget_type("q3_K", {}) is None
+
+ def test_the_loader_applies_the_guard_before_the_env_adoption(self):
+ """Source-pinned: the order is what makes it work. Adopting the env first
+ would leave the unemittable string in place."""
+ load = "".join(inspect.getsource(LlamaCppBackend.load_model).split())
+ guard = load.find("notin_VALID_CACHE_TYPES")
+ adopt = load.find("cache_type_kv=_env_main_cache_type_for_budget()")
+ assert guard != -1, "the unemittable-type guard is gone"
+ assert adopt != -1
+ assert guard < adopt, (guard, adopt)
+
+
+class TestAnUnsetInheritedCacheAxisIsStillF16:
+ """_env_main_cache_type_for_budget takes the heavier axis, so an axis that is
+ not set has to take part in that max at its real default, f16. Dropping it
+ lets one quantized axis carry the whole scalar, and the caller then prices the
+ OTHER axis as quantized too."""
+
+ @staticmethod
+ def _budget(env):
+ from core.inference.llama_cpp import _env_main_cache_type_for_budget
+ return _env_main_cache_type_for_budget(env)
+
+ @pytest.mark.parametrize("var", ["LLAMA_ARG_CACHE_TYPE_K", "LLAMA_ARG_CACHE_TYPE_V"])
+ def test_one_quantized_axis_alone_does_not_adopt_a_lighter_scalar(self, var):
+ """The effective pair is (q4_0, f16) either way round, whose heavier axis
+ is f16 -- the f16 default reserve, which is already conservative."""
+ assert self._budget({var: "q4_0"}) is None
+ assert self._budget({var: "q8_0"}) is None
+
+ @pytest.mark.parametrize("var", ["LLAMA_ARG_CACHE_TYPE_K", "LLAMA_ARG_CACHE_TYPE_V"])
+ def test_one_heavier_axis_alone_is_still_adopted(self, var):
+ """f32 on one axis is heavier than the f16 default on the other, so it
+ must still be budgeted -- the case the helper exists for."""
+ assert self._budget({var: "f32"}) == "f32"
+
+ def test_both_axes_quantized_is_adopted(self):
+ assert (
+ self._budget(
+ {
+ "LLAMA_ARG_CACHE_TYPE_K": "q4_0",
+ "LLAMA_ARG_CACHE_TYPE_V": "q4_0",
+ }
+ )
+ == "q4_0"
+ )
+
+ def test_an_asymmetric_quantized_pair_takes_the_heavier_axis(self):
+ assert (
+ self._budget(
+ {
+ "LLAMA_ARG_CACHE_TYPE_K": "q4_0",
+ "LLAMA_ARG_CACHE_TYPE_V": "q8_0",
+ }
+ )
+ == "q8_0"
+ )
+
+ def test_nothing_set_is_still_none(self):
+ assert self._budget({}) is None
+ assert self._budget({"LLAMA_ARG_CACHE_TYPE_K": "f16"}) is None
+
+ def test_the_under_reservation_it_prevents(self):
+ """On an arch with key_length > value_length the swap lands the cheap type
+ on the LARGER tensor. Driven through the real estimator."""
+ from core.inference.llama_cpp import _effective_main_cache_types
+
+ env = {"LLAMA_ARG_CACHE_TYPE_V": "q4_0"}
+ assert _effective_main_cache_types(None, env) == ("f16", "q4_0")
+ # The scalar the loader adopts must not be the quantized one.
+ assert self._budget(env) is None
diff --git a/studio/backend/tests/test_tensor_parallel.py b/studio/backend/tests/test_tensor_parallel.py
index e5564ef7a59..f06f9efc647 100644
--- a/studio/backend/tests/test_tensor_parallel.py
+++ b/studio/backend/tests/test_tensor_parallel.py
@@ -1699,13 +1699,251 @@ def test_load_model_reserves_pipeline_per_device_overhead():
assert "_subset_model_size(n_gpus)" in compact # used in the layer-split fit
-def test_load_model_restores_quantized_kv_on_tensor_downgrade():
- # A quantized KV dropped for the tensor attempt must be restored if tensor
- # downgrades to layer split (Finding D); captured once, restored at both the
- # GPU-count and capacity-gate downgrades.
- compact = "".join(inspect.getsource(LlamaCppBackend.load_model).split())
- assert "_tensor_dropped_cache_type_kv=cache_type_kv" in compact # captured pre-null
- # Restore is shared in one closure, called at every tensor->layer downgrade.
- assert "cache_type_kv=_tensor_dropped_cache_type_kv" in compact # restored in the closure
- assert "def_restore_after_tensor_downgrade():" in compact # one shared restore helper
- assert compact.count("_restore_after_tensor_downgrade()") >= 3 # called at each downgrade
+def test_load_model_does_not_gate_the_kv_cache_on_tensor_mode():
+ # llama.cpp runs a quantized KV cache under --split-mode tensor (ggml-org/
+ # llama.cpp#23792), so Unsloth must not carry its own whitelist.
+ assert not hasattr(LlamaCppBackend, "_TENSOR_PARALLEL_KV_TYPES")
+
+
+# ── Pre-b9455 llama.cpp: one doomed attempt, latched, then never again ───────
+
+
+class TestLegacyBuildQuantizedKvInTensorMode:
+ """Studio stopped pre-emptively rewriting a quantized KV cache for the tensor
+ attempt (ggml-org/llama.cpp#23792, b9455), so an older binary now refuses the
+ load itself. That refusal is a clean LLAMA_LOG_ERROR + return nullptr, not a
+ GGML_ASSERT, so nothing in the #6415 path can see it -- these pin the marker's
+ own handling: skip the --fit retry, latch it, and hand the route a message that
+ names the remedy.
+
+ The child is a captured Popen; no llama-server runs.
+ """
+
+ _REJECTION = (
+ "llama_init_from_model: simultaneous use of SPLIT_MODE_TENSOR and "
+ "KV cache quantization not implemented"
+ )
+ _QUANTIZED = ("q8_0", "q4_0", "q4_1", "q5_0", "q5_1", "iq4_nl")
+
+ @classmethod
+ def _doomed(cls, cmd) -> bool:
+ """What a pre-#23792 llama-server rejects: tensor split + a quantized axis."""
+ if "--split-mode" not in cmd or cmd[cmd.index("--split-mode") + 1] != "tensor":
+ return False
+ return any(
+ flag in ("--cache-type-k", "--cache-type-v") and cmd[i + 1] in cls._QUANTIZED
+ for i, flag in enumerate(cmd[:-1])
+ )
+
+ def _run(self, tmp_path, monkeypatch):
+ """One load_model call against a legacy child; returns the spawned commands."""
+ import subprocess
+ from unittest.mock import patch
+
+ import importlib.util
+ from pathlib import Path as _Path
+
+ spec = importlib.util.spec_from_file_location(
+ "_placement_harness_legacy_build",
+ _Path(__file__).resolve().parent / "test_llama_cpp_placement.py",
+ )
+ placement = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(placement)
+
+ backend, gguf = placement._backend(
+ tmp_path, vulkan = False, memory = [(0, 24_000, 24_000), (1, 24_000, 24_000)]
+ )
+ real_popen = subprocess.Popen
+ spawns: list[list[str]] = []
+
+ def fake_popen(cmd, **kwargs):
+ if not cmd or str(cmd[0]) != "/fake/llama-server":
+ return real_popen(cmd, **kwargs)
+ cmd = list(cmd)
+ spawns.append(cmd)
+ doomed = self._doomed(cmd)
+ if doomed:
+ backend._stdout_lines = [self._REJECTION, "srv load_model: failed to load model"]
+ return type(
+ "Process",
+ (),
+ {
+ "pid": 123,
+ "stdout": (),
+ "returncode": 1 if doomed else None,
+ "poll": lambda _self, _d = doomed: 1 if _d else None,
+ "terminate": lambda _self: None,
+ "wait": lambda _self, timeout = None: 1 if doomed else 0,
+ "kill": lambda _self: None,
+ },
+ )()
+
+ backend._wait_for_health = lambda timeout: not self._doomed(spawns[-1])
+ error: list[BaseException] = []
+ with patch.object(subprocess, "Popen", side_effect = fake_popen):
+ try:
+ backend.load_model(
+ GgufLoadIntent(
+ gguf_path = str(gguf),
+ model_identifier = "test",
+ tensor_parallel = True,
+ cache_type_kv = "q8_0",
+ )
+ )
+ except BaseException as exc: # noqa: BLE001
+ error.append(exc)
+ return backend, gguf, spawns, (error[0] if error else None)
+
+ @pytest.fixture(autouse = True)
+ def _clear_latch(self):
+ """Both latches are class-level and process-wide; a leak would make the
+ second cell pass for the first cell's reason (an already-latched binary
+ skips tensor up front, so no doomed spawn happens at all)."""
+ LlamaCppBackend._tensor_split_abort_keys.clear()
+ LlamaCppBackend._tensor_quant_kv_unsupported_binaries.clear()
+ yield
+ LlamaCppBackend._tensor_split_abort_keys.clear()
+ LlamaCppBackend._tensor_quant_kv_unsupported_binaries.clear()
+
+ def test_the_refusal_costs_exactly_one_spawn(self, tmp_path, monkeypatch):
+ """Not two. The --fit off -> --fit on retry cannot fix a missing capability,
+ and on a 27B each doomed attempt is a full model-load cycle."""
+ _backend, _gguf, spawns, error = self._run(tmp_path, monkeypatch)
+
+ assert len(spawns) == 1, [c[c.index("--split-mode") + 1] for c in spawns]
+ assert isinstance(error, RuntimeError), error
+
+ def test_it_raises_to_the_route_fallback_naming_the_build(self, tmp_path, monkeypatch):
+ """load_with_tensor_fallback catches the raise and relaunches layer-split;
+ the message is what reaches the user if anything reports it."""
+ _backend, _gguf, _spawns, error = self._run(tmp_path, monkeypatch)
+
+ assert "b9455" in str(error)
+ assert "layer split" in str(error)
+
+ def test_the_binary_is_latched_so_the_next_load_skips_tensor(self, tmp_path, monkeypatch):
+ """Without this the doomed attempt repeats on every load, forever."""
+ backend, gguf, _spawns, _error = self._run(tmp_path, monkeypatch)
+
+ # Binary-wide, not model-and-pair: the refusal is a capability this
+ # llama.cpp lacks for every model and every quantized type.
+ assert LlamaCppBackend._tensor_quant_kv_unsupported_binary(
+ "/fake/llama-server", ("q8_0", "q8_0")
+ )
+ assert LlamaCppBackend._tensor_quant_kv_unsupported_binary(
+ "/fake/llama-server", ("q4_0", "q4_0")
+ )
+ # But f16 runs fine under a tensor split on such a binary, so the latch
+ # must not take tensor mode away from a config that works.
+ assert not LlamaCppBackend._tensor_quant_kv_unsupported_binary(
+ "/fake/llama-server", ("f16", "f16")
+ )
+ # The model+pair latch stays clean: this was never a geometry abort.
+ assert not LlamaCppBackend._tensor_split_abort_keys
+
+ def test_a_current_build_is_untouched(self, tmp_path, monkeypatch):
+ """The guard must not cost anything on a binary that supports the pair:
+ one spawn, tensor mode kept, quantized cache emitted."""
+ import importlib.util
+ from pathlib import Path as _Path
+
+ spec = importlib.util.spec_from_file_location(
+ "_placement_harness_current_build",
+ _Path(__file__).resolve().parent / "test_llama_cpp_placement.py",
+ )
+ placement = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(placement)
+
+ backend, gguf = placement._backend(
+ tmp_path, vulkan = False, memory = [(0, 24_000, 24_000), (1, 24_000, 24_000)]
+ )
+ backend._tensor_split_aborts = lambda *a, **k: False
+ cmd = placement._launch(backend, gguf, tensor_parallel = True, cache_type_kv = "q8_0")["cmd"]
+
+ assert cmd[cmd.index("--split-mode") + 1] == "tensor"
+ assert cmd[cmd.index("--cache-type-k") + 1] == "q8_0"
+ assert not LlamaCppBackend._tensor_split_abort_keys
+
+
+class TestLegacyBuildLatchIsBinaryWide:
+ """The pre-b9455 refusal is a missing capability of the BINARY: llama.cpp
+ refuses every quantized type for every model on it. Keying it per model and
+ per cache pair (like the #6415 split-axis abort, which really is specific to
+ both) would pay another doomed full model load for each new model and each
+ q8_0 -> q4_0 switch."""
+
+ @pytest.fixture(autouse = True)
+ def _clear(self):
+ LlamaCppBackend._tensor_quant_kv_unsupported_binaries.clear()
+ yield
+ LlamaCppBackend._tensor_quant_kv_unsupported_binaries.clear()
+
+ def test_one_detection_covers_other_models_and_other_types(self, tmp_path):
+ binary = str(tmp_path / "llama-server")
+ Path(binary).write_text("x")
+ LlamaCppBackend._record_tensor_quant_kv_unsupported(binary)
+
+ # Same model, a different quantized type.
+ assert LlamaCppBackend._tensor_quant_kv_unsupported_binary(binary, ("q4_0", "q4_0"))
+ # A completely different model.
+ assert LlamaCppBackend._tensor_quant_kv_unsupported_binary(binary, ("q8_0", "q8_0"))
+ # One quantized axis is enough, since llama.cpp checks both.
+ assert LlamaCppBackend._tensor_quant_kv_unsupported_binary(binary, ("q4_0", "f16"))
+ assert LlamaCppBackend._tensor_quant_kv_unsupported_binary(binary, ("f16", "q4_0"))
+
+ def test_a_non_quantized_pair_still_gets_a_tensor_split(self, tmp_path):
+ """f16 runs fine under a tensor split on such a binary -- the refusal is
+ about quantization, so latching it must not cost the working config."""
+ binary = str(tmp_path / "llama-server")
+ Path(binary).write_text("x")
+ LlamaCppBackend._record_tensor_quant_kv_unsupported(binary)
+
+ assert not LlamaCppBackend._tensor_quant_kv_unsupported_binary(binary, ("f16", "f16"))
+ assert not LlamaCppBackend._tensor_quant_kv_unsupported_binary(binary, ("bf16", "f32"))
+
+ def test_a_replaced_binary_is_re_probed(self, tmp_path):
+ """An update is exactly what fixes this, so the mtime must invalidate it."""
+ import os
+ import time
+
+ binary = str(tmp_path / "llama-server")
+ Path(binary).write_text("old")
+ LlamaCppBackend._record_tensor_quant_kv_unsupported(binary)
+ assert LlamaCppBackend._tensor_quant_kv_unsupported_binary(binary, ("q8_0", "q8_0"))
+
+ time.sleep(0.01)
+ Path(binary).write_text("new")
+ os.utime(binary, ns = (time.time_ns(), time.time_ns()))
+
+ assert not LlamaCppBackend._tensor_quant_kv_unsupported_binary(binary, ("q8_0", "q8_0"))
+
+ def test_an_unseen_binary_is_not_latched(self, tmp_path):
+ assert not LlamaCppBackend._tensor_quant_kv_unsupported_binary(
+ str(tmp_path / "never-seen"), ("q8_0", "q8_0")
+ )
+ assert not LlamaCppBackend._tensor_quant_kv_unsupported_binary(None, ("q8_0", "q8_0"))
+
+ def test_the_skip_keeps_the_multi_gpu_request(self):
+ """A missing capability says nothing about capacity, so the layer load it
+ falls back to must still spread. Without the _layer_min_gpus bump the auto
+ layer planner starts at one GPU and stops there as soon as the model fits,
+ silently collapsing a multi-GPU request onto one card -- the same reason
+ the adjacent split-axis skip raises it."""
+ load = "".join(inspect.getsource(LlamaCppBackend.load_model).split())
+ gate = load.find("self._tensor_quant_kv_unsupported_binary(")
+ assert gate != -1
+ # The bump sits inside this skip's own body, before the next gate.
+ nxt = load.find("self._tensor_split_aborts(", gate)
+ assert nxt != -1
+ assert "_layer_min_gpus=max(_layer_min_gpus,len(gpus))" in load[gate:nxt]
+
+ def test_the_loader_consults_it_before_spawning(self):
+ """Source-pinned: the whole point is to skip the doomed load, so the check
+ has to sit at the up-front gate, not after a spawn."""
+ load = "".join(inspect.getsource(LlamaCppBackend.load_model).split())
+ gate = load.find("self._tensor_quant_kv_unsupported_binary(")
+ assert gate != -1, "the binary-wide gate is gone"
+ # Ahead of the first spawn.
+ assert gate < load.find("healthy=_spawn_and_wait(cmd)")
+ # And the skip must strip the split-mode group like every other TP drop.
+ assert "extra_args=strip_split_mode_only(extra_args)" in load
diff --git a/studio/backend/tests/test_tensor_quant_kv_platform_matrix.py b/studio/backend/tests/test_tensor_quant_kv_platform_matrix.py
new file mode 100644
index 00000000000..ec1264e64f4
--- /dev/null
+++ b/studio/backend/tests/test_tensor_quant_kv_platform_matrix.py
@@ -0,0 +1,413 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""OS x accelerator x cache-type matrix for the tensor-split quantized KV cache.
+
+llama.cpp runs a quantized KV cache under ``--split-mode tensor`` since
+ggml-org/llama.cpp#23792 (build b9455), so Unsloth stopped rewriting the requested
+type for the tensor attempt. That removal touches no platform-conditional code, but
+it changes the argv emitted on every platform, and the cells where tensor mode is
+dropped BEFORE the cache is ever considered (CPU-only, single GPU, Apple) are the
+ones most likely to regress silently: they emit the same command either way, so only
+a per-cell record shows the drop still happens for the right reason.
+
+Each cell records the emitted split mode and BOTH cache axes, because the whole
+class of bug this file guards against is an axis being rewritten -- and the two
+axes only differ when the user sets them separately.
+
+Simulation notice: this suite runs on one host. Only Linux/NVIDIA is native. Windows,
+WSL2 and macOS are ``sys.platform`` / ``platform.release`` monkeypatches via the
+shared ``_apply_platform`` seam, Apple unified memory is a non-zero
+``_apple_metal_memory_budget_bytes`` with an empty GPU probe, and every AMD cell is a
+memory shape plus ``utils.hardware.IS_ROCM`` or the Vulkan flag. No ROCm runtime, no
+Metal device, no Windows kernel and no llama-server process is exercised -- the child
+is a captured ``Popen``. The authoritative signal for those remains the per-OS CI
+matrix on real runners; this is the branch coverage one host can give.
+"""
+
+from __future__ import annotations
+
+import importlib.util
+from pathlib import Path
+
+import pytest
+
+_TESTS_DIR = Path(__file__).resolve().parent
+
+
+def _load(module_name: str, file_name: str):
+ spec = importlib.util.spec_from_file_location(module_name, _TESTS_DIR / file_name)
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ return module
+
+
+# Both harnesses already exist; by path, because the tests dir is not a package.
+_placement = _load("_placement_harness_tp_quant_kv", "test_llama_cpp_placement.py")
+_platforms = _load("_platform_harness_tp_quant_kv", "test_llama_extra_args_platforms.py")
+
+_backend = _placement._backend
+_launch = _placement._launch
+_apply_platform = _platforms._apply_platform
+PLATFORMS = _platforms.PLATFORMS
+
+from core.inference.llama_cpp import LlamaCppBackend # noqa: E402
+from utils.hardware import hardware as _hw # noqa: E402
+
+
+# (label, vulkan, is_rocm, apple_budget_bytes, memory, tensor_is_viable)
+# tensor_is_viable is the expectation, not an input: tensor mode needs >= 2 devices,
+# so every single-device and device-less cell must come out layer-split whatever the
+# cache type is.
+ACCELERATORS = [
+ ("nvidia-multi", False, False, 0, [(0, 20_000, 24_000), (1, 20_000, 24_000)], True),
+ ("nvidia-single", False, False, 0, [(0, 20_000, 24_000)], False),
+ ("amd-rocm-multi", False, True, 0, [(0, 20_000, 24_000), (1, 20_000, 24_000)], True),
+ ("amd-vulkan-multi", True, False, 0, [(0, 12_000, 16_000), (1, 12_000, 16_000)], True),
+ ("apple-unified", False, False, 32 * 1024**3, [], False),
+ ("cpu-only", False, False, 0, [], False),
+]
+
+# The types the launcher will emit (_VALID_CACHE_TYPES), plus the two shapes that
+# only became reachable once the tensor gate was removed.
+CACHE_CELLS = [
+ ("f16", "f16", "f16"),
+ ("q8_0", "q8_0", "q8_0"),
+ ("q4_0", "q4_0", "q4_0"),
+ ("q5_1", "q5_1", "q5_1"),
+ # iq4_nl is in _VALID_CACHE_TYPES, so the gate removal admits it. ggml-org/
+ # llama.cpp#27116 reports it still asserting under a tensor split on b10441;
+ # that abort carries split_axis, so _should_record_tensor_split_abort latches
+ # it and the route falls back. Studio's job is only to emit what was asked.
+ ("iq4_nl", "iq4_nl", "iq4_nl"),
+]
+
+MATRIX = [
+ pytest.param(p, a, c, id = f"{p[0]}-{a[0]}-{c[0]}")
+ for p in PLATFORMS
+ for a in ACCELERATORS
+ for c in CACHE_CELLS
+]
+
+
+def _cell_backend(tmp_path, monkeypatch, platform, accelerator):
+ _label, vulkan, is_rocm, apple_budget, memory, _viable = accelerator
+ _apply_platform(monkeypatch, platform)
+ # An inherited visibility mask would make "placement pinned nothing" read as a
+ # pin on any box that exports CUDA_VISIBLE_DEVICES.
+ for name in ("CUDA_VISIBLE_DEVICES", "HIP_VISIBLE_DEVICES", "ROCR_VISIBLE_DEVICES"):
+ monkeypatch.delenv(name, raising = False)
+ for name in ("LLAMA_ARG_CACHE_TYPE_K", "LLAMA_ARG_CACHE_TYPE_V", "LLAMA_ARG_SPLIT_MODE"):
+ monkeypatch.delenv(name, raising = False)
+ monkeypatch.setattr(_hw, "IS_ROCM", is_rocm, raising = False)
+ monkeypatch.setattr(
+ LlamaCppBackend,
+ "_apple_metal_memory_budget_bytes",
+ staticmethod(lambda: apple_budget),
+ )
+ backend, gguf = _backend(tmp_path, vulkan = vulkan, memory = list(memory))
+ # A session latch from another cell would silently turn a tensor cell into a
+ # layer cell and the assertion below would still pass for the wrong reason.
+ backend._tensor_split_aborts = lambda *args, **kwargs: False
+ return backend, gguf
+
+
+def _axes(cmd: list[str]) -> tuple[list[str], list[str]]:
+ """Every --cache-type-k and --cache-type-v value, in emission order."""
+ return (
+ [cmd[i + 1] for i, a in enumerate(cmd) if a == "--cache-type-k"],
+ [cmd[i + 1] for i, a in enumerate(cmd) if a == "--cache-type-v"],
+ )
+
+
[email protected]("platform,accelerator,cache", MATRIX)
+def test_the_requested_cache_reaches_every_platform_unchanged(
+ tmp_path, monkeypatch, platform, accelerator, cache
+):
+ """No OS and no accelerator rewrites the requested KV cache type.
+
+ Studio emits one type on both axes for a managed request, so both must equal
+ what was asked, on every cell, whether or not tensor mode survives.
+ """
+ tensor_viable = accelerator[5]
+ kv_type, expect_k, expect_v = cache
+ backend, gguf = _cell_backend(tmp_path, monkeypatch, platform, accelerator)
+
+ cmd = _launch(backend, gguf, tensor_parallel = True, cache_type_kv = kv_type)["cmd"]
+ ks, vs = _axes(cmd)
+
+ assert ks[-1:] == [expect_k], f"K axis rewritten: {ks}"
+ assert vs[-1:] == [expect_v], f"V axis rewritten: {vs}"
+ assert backend.cache_type_kv == kv_type
+ # Tensor mode is a >= 2-device feature; below that the split-mode group must be
+ # gone entirely, not just set to layer, so an extras --tensor-split cannot
+ # re-engage it.
+ if tensor_viable:
+ assert cmd[cmd.index("--split-mode") + 1] == "tensor"
+ else:
+ assert "--split-mode" not in cmd
+ assert "--tensor-split" not in cmd
+
+
[email protected]("platform,accelerator,cache", MATRIX)
+def test_asymmetric_axes_reach_every_platform_unchanged(
+ tmp_path, monkeypatch, platform, accelerator, cache
+):
+ """A per-axis request survives on every cell, with the quantized axis on K.
+
+ The pre-#23792 gate tested EVERY axis and rewrote both, so an asymmetric pair
+ is the shape that regresses first if a whitelist is ever reintroduced -- under
+ any name, which is why this asserts the axes rather than the absence of an
+ attribute.
+ """
+ tensor_viable = accelerator[5]
+ kv_type, _k, _v = cache
+ if kv_type == "f16":
+ pytest.skip("f16/f16 is not an asymmetric pair")
+ backend, gguf = _cell_backend(tmp_path, monkeypatch, platform, accelerator)
+
+ cmd = _launch(
+ backend,
+ gguf,
+ tensor_parallel = True,
+ extra_args = ["--cache-type-k", kv_type, "--cache-type-v", "f16", "--top-k", "5"],
+ )["cmd"]
+ ks, vs = _axes(cmd)
+
+ # Extras are appended last and win per axis.
+ assert ks[-1] == kv_type, f"K axis rewritten: {ks}"
+ assert vs[-1] == "f16", f"V axis rewritten: {vs}"
+ assert cmd[cmd.index("--top-k") + 1] == "5", "unrelated user extras dropped"
+ if tensor_viable:
+ assert cmd[cmd.index("--split-mode") + 1] == "tensor"
+ else:
+ assert "--split-mode" not in cmd
+
+
+ "platform,accelerator",
+ [pytest.param(p, a, id = f"{p[0]}-{a[0]}") for p in PLATFORMS for a in ACCELERATORS],
+)
+def test_an_inherited_quantized_kv_env_survives_on_every_platform(
+ tmp_path, monkeypatch, platform, accelerator
+):
+ """The tensor-branch env scrub owns the split, not the cache type.
+
+ LLAMA_ARG_CACHE_TYPE_K/_V must reach the child on every cell, while the tensor
+ split Unsloth generates itself is still cleared so a stale one cannot override
+ the ratio this launch computed.
+ """
+ tensor_viable = accelerator[5]
+ backend, gguf = _cell_backend(tmp_path, monkeypatch, platform, accelerator)
+ monkeypatch.setenv("LLAMA_ARG_CACHE_TYPE_K", "q8_0")
+ monkeypatch.setenv("LLAMA_ARG_CACHE_TYPE_V", "q4_0")
+ monkeypatch.setenv("LLAMA_ARG_TENSOR_SPLIT", "9,1")
+
+ out = _launch(backend, gguf, tensor_parallel = True)
+ env = out["env"]
+
+ assert env["LLAMA_ARG_CACHE_TYPE_K"] == "q8_0"
+ assert env["LLAMA_ARG_CACHE_TYPE_V"] == "q4_0"
+ if tensor_viable:
+ # Tensor mode owns the ratio it computed, so a stale inherited one goes.
+ assert "LLAMA_ARG_TENSOR_SPLIT" not in env
+ else:
+ # A layer load only clears inherited placement when it also inherited a
+ # non-layer LLAMA_ARG_SPLIT_MODE; a bare ratio is a valid layer ratio and
+ # is left to the child. Pinned so the cache assertions above cannot be
+ # read as a claim about placement.
+ assert env["LLAMA_ARG_TENSOR_SPLIT"] == "9,1"
+ # Env-only: Studio emits no flag of its own, so it records no type. Pinned
+ # because /status and the reload matcher both read this, and the matcher
+ # compares it against an intent field that is also None for this shape.
+ assert backend.cache_type_kv is None
+
+
+ "platform,accelerator",
+ [pytest.param(p, a, id = f"{p[0]}-{a[0]}") for p in PLATFORMS for a in ACCELERATORS],
+)
+def test_a_quantized_cache_survives_the_tensor_to_layer_downgrade(
+ tmp_path, monkeypatch, platform, accelerator
+):
+ """A downgrade removes the split-mode group and nothing else.
+
+ Layer split has always supported a quantized cache. Before #23792 the tensor
+ attempt dropped it and a downgrade restored it; now it is never dropped. Both
+ routes have to end at the same command, so this pins the outcome rather than
+ the mechanism -- the assertion the restore-path test used to carry.
+ """
+ backend, gguf = _cell_backend(tmp_path, monkeypatch, platform, accelerator)
+ # The session latch is the cheapest downgrade to force and needs no VRAM shape.
+ backend._tensor_split_aborts = lambda *args, **kwargs: True
+
+ cmd = _launch(
+ backend,
+ gguf,
+ tensor_parallel = True,
+ extra_args = ["--cache-type-k", "q4_0", "--cache-type-v", "f16", "--top-k", "5"],
+ )["cmd"]
+ ks, vs = _axes(cmd)
+
+ assert "--split-mode" not in cmd
+ assert "--tensor-split" not in cmd
+ assert ks[-1] == "q4_0", f"downgrade rewrote the K axis: {ks}"
+ assert vs[-1] == "f16", f"downgrade rewrote the V axis: {vs}"
+ assert cmd[cmd.index("--top-k") + 1] == "5"
+
+
[email protected]("platform,accelerator,cache", MATRIX)
+def test_a_tensor_launch_never_pairs_a_disabled_flash_attn(
+ tmp_path, monkeypatch, platform, accelerator, cache
+):
+ """llama.cpp hard-errors on --flash-attn off under --split-mode tensor.
+
+ Verified against current master (src/llama-context.cpp): the quantized-KV guard
+ #23792 deleted is gone, but the one directly above it is not --
+ "SPLIT_MODE_TENSOR requires flash_attn to be enabled" still returns nullptr, and
+ AUTO is upgraded to ENABLED. A quantized V axis independently needs FA too, so
+ this pair became reachable in tensor mode only once the cache stopped being
+ rewritten. Pinned on every cell because the remedy differs per platform and the
+ failure is a startup abort, not a downgrade.
+ """
+ tensor_viable = accelerator[5]
+ kv_type, _k, _v = cache
+ backend, gguf = _cell_backend(tmp_path, monkeypatch, platform, accelerator)
+
+ cmd = _launch(backend, gguf, tensor_parallel = True, cache_type_kv = kv_type)["cmd"]
+
+ if not tensor_viable:
+ return # layer split; llama.cpp imposes nothing here
+ assert cmd[cmd.index("--split-mode") + 1] == "tensor"
+ if "--flash-attn" in cmd:
+ assert cmd[cmd.index("--flash-attn") + 1] != "off", _stable_join(cmd)
+ assert "-fa" not in cmd or cmd[cmd.index("-fa") + 1] != "off"
+
+
+def _stable_join(cmd: list[str]) -> str:
+ return " ".join(cmd)
+
+
+# ── Old installs ────────────────────────────────────────────────────────────
+
+
+def test_a_config_saved_by_a_pre_23792_studio_still_loads(tmp_path, monkeypatch):
+ """Upgrading Studio must not invalidate a saved model config.
+
+ A user who set "Tensor Parallelism + q8_0" before this change had it silently
+ coerced to f16. The same saved config now gets what it asked for -- which is
+ the fix -- and nothing about reading it changes: no field is added, removed or
+ renamed, so an old config loads here and a new one loads on an old Studio.
+ """
+ backend, gguf = _cell_backend(tmp_path, monkeypatch, PLATFORMS[0], ACCELERATORS[0])
+
+ # Exactly the fields a pre-#23792 Studio wrote for this combination.
+ cmd = _launch(backend, gguf, tensor_parallel = True, cache_type_kv = "q8_0")["cmd"]
+
+ assert cmd[cmd.index("--split-mode") + 1] == "tensor"
+ assert cmd[cmd.index("--cache-type-k") + 1] == "q8_0"
+
+
+def test_the_load_intent_gained_no_field(tmp_path):
+ """Schema tripwire for both directions of the upgrade.
+
+ The fix threads a second cache type through the planner, and the cheap way to
+ do that would have been a new GgufLoadIntent field -- which an older Studio
+ reading a newer config would reject. It is a function parameter instead; this
+ fails if that ever changes.
+ """
+ from dataclasses import fields
+
+ from core.inference.llama_cpp import GgufLoadIntent
+
+ names = {f.name for f in fields(GgufLoadIntent)}
+
+ assert "scratch_cache_type_kv" not in names
+ # The one the UI does own is still there and still spelled the same.
+ assert "cache_type_kv" in names
+ assert "tensor_parallel" in names
+
+
+# ── An inherited cache type llama.cpp cannot parse must not kill both attempts ──
+
+
+ "platform,accelerator",
+ [pytest.param(p, a, id = f"{p[0]}-{a[0]}") for p in PLATFORMS for a in ACCELERATORS],
+)
[email protected]("bad", ["q3_K", "typo", ""])
+def test_an_unparseable_inherited_cache_type_is_dropped(
+ tmp_path, monkeypatch, platform, accelerator, bad
+):
+ """kv_cache_type_from_str aborts the child on an unknown type, at argument
+ parsing -- and the layer retry inherits the same env, so BOTH attempts would
+ fail and the user would be left with no server at all.
+
+ The managed path has always been allow-listed at emission; the env path was
+ only scrubbed as a side effect of the tensor-mode gate, so it needs the check
+ on its own now. Split-mode independent: llama.cpp parses it the same way.
+ """
+ backend, gguf = _cell_backend(tmp_path, monkeypatch, platform, accelerator)
+ monkeypatch.setenv("LLAMA_ARG_CACHE_TYPE_K", bad)
+ monkeypatch.setenv("LLAMA_ARG_CACHE_TYPE_V", "q8_0")
+
+ env = _launch(backend, gguf, tensor_parallel = True)["env"]
+
+ assert env.get("LLAMA_ARG_CACHE_TYPE_K") in (None, "")
+ # The valid axis is untouched -- this drops what llama.cpp rejects, nothing more.
+ assert env["LLAMA_ARG_CACHE_TYPE_V"] == "q8_0"
+
+
+ "platform,accelerator",
+ [pytest.param(p, a, id = f"{p[0]}-{a[0]}") for p in PLATFORMS for a in ACCELERATORS],
+)
+def test_a_miscased_inherited_cache_type_is_normalised_not_dropped(
+ tmp_path, monkeypatch, platform, accelerator
+):
+ """kv_cache_type_from_str is case-sensitive, so "Q8_0" aborts the child just as
+ hard as a typo -- but the user clearly meant a type that exists, and the managed
+ path already lowercases for exactly this reason. Match it rather than dropping
+ the request on a capitalisation."""
+ backend, gguf = _cell_backend(tmp_path, monkeypatch, platform, accelerator)
+ monkeypatch.setenv("LLAMA_ARG_CACHE_TYPE_K", "Q8_0")
+ monkeypatch.setenv("LLAMA_ARG_CACHE_TYPE_V", "IQ4_NL")
+
+ env = _launch(backend, gguf, tensor_parallel = True)["env"]
+
+ assert env["LLAMA_ARG_CACHE_TYPE_K"] == "q8_0"
+ assert env["LLAMA_ARG_CACHE_TYPE_V"] == "iq4_nl"
+
+
+# ── An inherited value llama.cpp cannot parse verbatim ──────────────────────
+
+
+ "platform,accelerator",
+ [pytest.param(p, a, id = f"{p[0]}-{a[0]}") for p in PLATFORMS for a in ACCELERATORS],
+)
+ "raw,expected",
+ [
+ (" q8_0 ", "q8_0"), # surrounding whitespace
+ ("\tq4_0\n", "q4_0"), # any whitespace, not just spaces
+ (" Q8_0 ", "q8_0"), # whitespace AND case together
+ ],
+)
+def test_a_whitespace_padded_inherited_cache_type_is_rewritten(
+ tmp_path, monkeypatch, platform, accelerator, raw, expected
+):
+ """common_arg::get_value_from_env hands the raw getenv string straight to
+ kv_cache_type_from_str, which compares it to ggml_type_name(t) exactly and
+ throws otherwise -- neither side trims. So " q8_0 " aborts the child just as
+ a typo does, and normalising against an already-stripped copy would compare
+ equal and leave the padding on the child.
+ """
+ backend, gguf = _cell_backend(tmp_path, monkeypatch, platform, accelerator)
+ monkeypatch.setenv("LLAMA_ARG_CACHE_TYPE_K", raw)
+ monkeypatch.setenv("LLAMA_ARG_CACHE_TYPE_V", "q8_0")
+
+ env = _launch(backend, gguf, tensor_parallel = True)["env"]
+
+ assert env["LLAMA_ARG_CACHE_TYPE_K"] == expected
+ assert env["LLAMA_ARG_CACHE_TYPE_V"] == "q8_0"
diff --git a/studio/backend/tests/test_tp_vision_regression.py b/studio/backend/tests/test_tp_vision_regression.py
index 205db1bc75e..72bbad179e3 100644
--- a/studio/backend/tests/test_tp_vision_regression.py
+++ b/studio/backend/tests/test_tp_vision_regression.py
@@ -9,8 +9,10 @@ any mmproj/MTP GGUF that fit on one card. The fix makes the skip self-healing:
tensor is tried by default and recorded per (binary, model) only on a real abort.
load_model is too entangled to drive end-to-end, so these tests inspect the
-source / drive the pure helpers. The headline test pins the set of TP-drop
-conditions, so a new silent drop fails CI. No GPU; fully deterministic.
+source / drive the pure helpers. That holds for ordering and binding invariants;
+anything observable in the launched argv belongs in test_llama_cpp_placement.py
+instead, driven through its _launch harness. The headline test pins the set of
+TP-drop conditions, so a new silent drop fails CI. No GPU; fully deterministic.
"""
from __future__ import annotations
@@ -123,19 +125,24 @@ def _tensor_parallel_false_drop_guards() -> list[str]:
# Every condition that may flip a requested tensor_parallel back to False. Adding
-# one must be conscious: update this allowlist and keep multi-GPU where possible.
+# one must be conscious: update this allowlist, keep multi-GPU where possible, and
+# strip the extras split-mode group so the drop cannot be undone by a user flag.
_ALLOWED_TP_DROP_GUARDS = {
# Capability: --split-mode tensor aborted for this (binary, model) (#6415).
# Self-healing -- tried by default, skipped only after a real abort (vs #6416).
- "tensor_parallel and self._tensor_split_aborts(binary, model_identifier)",
+ "tensor_parallel and self._tensor_split_aborts(binary, model_identifier, _planned_cache_pair)",
+ # Capability: this llama.cpp already refused a quantized KV cache under a
+ # tensor split (pre-b9455, ggml-org/llama.cpp#23792). Binary-wide rather than
+ # per model+pair, since the refusal covers every model and every quantized
+ # type; a non-quantized pair still gets its tensor split.
+ "tensor_parallel and self._tensor_quant_kv_unsupported_binary(binary, _planned_cache_pair)",
# Capacity: tensor needs >= 2 GPUs clearing the compute-buffer reserve. Gated
# on plan_tp (not raw tensor_parallel) so manual mode skips this planner (#6414).
"plan_tp and len(tp_gpus) < 2",
# Capacity: pooled usable VRAM can't hold weights + MTP reserve -> layer split.
"_tp_weight_budget_mib <= _tp_required_mib",
# Manual mode, Auto layers: --fit owns memory and is incompatible with a
- # tensor split, so TP is dropped (surfaced via logger.info) before the
- # cache-drop, so a quantized KV survives into the --fit load (#6414).
+ # tensor split, so TP is dropped (surfaced via logger.info) (#6414).
"tensor_parallel and gpu_memory_mode == 'manual' and (gpu_layers < 0)",
# Manual mode, explicit layers: a tensor split still needs >= 2 GPUs in use.
"tensor_parallel and gpu_memory_mode == 'manual' and (gpu_layers >= 0) and (self._effective_gpu_count(sorted(gpu_ids) if gpu_ids else None) < 2)",
@@ -161,8 +168,9 @@ def test_tensor_parallel_drop_sites_match_allowlist():
f" unexpected (new) : {sorted(found - _ALLOWED_TP_DROP_GUARDS)}\n"
f" missing (removed): {sorted(_ALLOWED_TP_DROP_GUARDS - found)}\n"
"A new drop means a user's TP request is ignored for a new reason -- "
- "review it, keep multi-GPU where possible, surface it, then update "
- "_ALLOWED_TP_DROP_GUARDS."
+ "review it, keep multi-GPU where possible, surface it, strip the extras "
+ "split-mode group with strip_split_mode_only so the drop cannot be undone "
+ "by a user flag, then update _ALLOWED_TP_DROP_GUARDS."
)
@@ -202,7 +210,10 @@ def test_tensor_split_gate_is_self_healing_not_blanket():
"""Skip is conditional on a recorded (binary, model) abort, not a blanket
is_vision disable (the #6416 regression)."""
src = inspect.getsource(LlamaCppBackend.load_model)
- assert "self._tensor_split_aborts(binary, model_identifier)" in src
+ assert "self._tensor_split_aborts(" in src
+ # Keyed by the planned KV pair too: since ggml-org/llama.cpp#23792 a tensor
+ # abort can be specific to one cache type, so the latch must not generalise.
+ assert "binary, model_identifier, _planned_cache_pair" in src
assert "if tensor_parallel and is_vision:" not in src
assert "if tensor_parallel and effective_is_vision:" not in src
@@ -210,7 +221,7 @@ def test_tensor_split_gate_is_self_healing_not_blanket():
def test_tensor_split_skip_documents_layer_split_fallback():
"""When the skip fires (known-bad binary+model), it states the fallback."""
src = inspect.getsource(LlamaCppBackend.load_model)
- gate = src.find("self._tensor_split_aborts(binary, model_identifier)")
+ gate = src.find("self._tensor_split_aborts(")
assert gate != -1
block = src[gate : gate + 600]
assert "layer split" in block, "the skip should state it falls back to layer split"
@@ -220,9 +231,11 @@ def test_tensor_split_abort_recorded_early_on_first_spawn():
"""Recorded on the first spawn showing the marker, before the flash-attn-off
retry (which can't run tensor so drops the marker) -- else it loops (oobabooga, #6659)."""
src = inspect.getsource(LlamaCppBackend.load_model)
- idx = src.find("_record_tensor_split_abort(binary, model_identifier)")
+ idx = src.find("LlamaCppBackend._record_tensor_split_abort(")
assert idx != -1, "load_model must record a (binary, model) tensor-split abort"
- guard = src[max(0, idx - 600) : idx]
+ # 900, not 600: the block now also explains why the pre-b9455 quantized-KV
+ # refusal is latched here rather than by the signal-crash helper below it.
+ guard = src[max(0, idx - 900) : idx]
assert "self._tensor_parallel" in guard
assert (
"_should_record_tensor_split_abort" in guard
@@ -388,7 +401,7 @@ def test_tensor_split_abort_raises_early_to_layer_fallback():
# gated on the marker-plus-crash helper, which also drives the record just above
guard = src[max(0, raise_idx - 600) : raise_idx]
assert "_should_record_tensor_split_abort" in guard
- rec_idx = src.find("_record_tensor_split_abort(binary, model_identifier)")
+ rec_idx = src.find("LlamaCppBackend._record_tensor_split_abort(")
assert rec_idx != -1 and rec_idx < raise_idx
@@ -431,7 +444,7 @@ def test_tensor_split_layer_min_gpus_bump_requires_tensor_request():
for node in ast.walk(fn):
if isinstance(node, ast.If):
test_src = ast.unparse(node.test)
- if "self._tensor_split_aborts(binary, model_identifier)" not in test_src:
+ if "self._tensor_split_aborts(" not in test_src:
continue
body = "\n".join(ast.unparse(n) for n in node.body)
if "_layer_min_gpus" in body:
@@ -600,17 +613,27 @@ def test_should_record_tensor_split_abort_decision():
assert f(0xC0000005, "") is False
-def test_fit_off_retry_skipped_on_split_axis_abort():
+def test_fit_off_retry_skipped_on_a_tensor_capability_crash():
"""The fit-independent --fit off retry is skipped on the split-axis marker, else
- the model crashes a second time before the latch records it (reviewer.py, #6659)."""
+ the model crashes a second time before the latch records it (reviewer.py, #6659).
+
+ The same skip now also covers the pre-b9455 refusal of a quantized KV cache in
+ tensor mode (ggml-org/llama.cpp#23792): both are capabilities the binary lacks,
+ so a second spawn to let it offload cannot help and costs a full model load.
+ Hence the guard's name is _tensor_capability_crash rather than the split-axis
+ one it started as.
+ """
src = inspect.getsource(LlamaCppBackend.load_model)
retry = src.find('run_cmd = [*run_cmd, "--fit", "off"]')
assert retry != -1
guard = src[max(0, retry - 1000) : retry]
assert "_fit_retry_allowed" in guard and "_startup_crashed" in guard
assert (
- "not _split_axis_crash" in guard
- ), "the fit-off retry must be skipped when the crash is a split-axis abort"
+ "not _tensor_capability_crash" in guard
+ ), "the fit-off retry must be skipped when the crash is a tensor capability limit"
+ # Both markers feed it, so neither can be dropped without this failing.
+ assert "_is_tensor_split_assert" in src
+ assert "_is_tensor_quant_kv_unsupported" in src
def test_is_abort_exit_recognizes_windows_crt_abort():