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: re-fit the context when Auto drops serving slots (#9345)

oobabooga1c06bc45c9cc
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.py
index 53ddc2f490e..f496305ccf9 100644
--- a/studio/backend/core/inference/llama_cpp.py
+++ b/studio/backend/core/inference/llama_cpp.py
@@ -9935,16 +9935,25 @@ class LlamaCppBackend:
split_extra_bytes: int = 0,
ubatch_for_slots: Optional[Callable[[int], Optional[int]]] = None,
mtp_bytes_for_slots: Optional[Callable[[int, Optional[int]], int]] = None,
+ ctx_checkpoints: int = 0,
+ include_requested: bool = False,
+ exact: bool = False,
) -> tuple[Optional[list[int]], bool, int]:
- """Largest serving-slot count in [1, n_parallel) whose fully-on-GPU footprint fits,
- so Unsloth keeps the model on GPU (-ngl -1) instead of --fit on, which offloads layers
- to host and collapses decode ~3x (oobabooga #6718). ``base_footprint_bytes`` is the
+ """Largest serving-slot count that fits fully on GPU, so Unsloth keeps the model on
+ GPU (-ngl -1) instead of --fit on, which offloads layers to host and collapses decode
+ ~3x (oobabooga #6718). The search runs over [1, n_parallel) by default, or over
+ [1, n_parallel] when ``include_requested`` is set. ``base_footprint_bytes`` is the
slot-independent footprint (weights + soft overhead + context-linear compute,
minus the folded compute buffer); each candidate re-adds the slot-sized compute buffer
and KV, then re-selects GPUs like the explicit-context path -- ``split_extra_bytes``
included, so a multi-GPU candidate is re-checked at the split rate. Returns
(gpu_indices, use_fit=False, slots) for the largest fitting count, else (None, True,
- n_parallel). Only ever reduces; unit-testable with synthetic VRAM maps.
+ n_parallel). Unit-testable with synthetic VRAM maps.
+ ``exact`` stops after the first candidate, for a caller that accepts only
+ ``n_parallel`` itself and would re-price every lower count just to discard it.
+ ``ctx_checkpoints`` mirrors --ctx-checkpoints, which allocates N SWA/recurrent
+ snapshots PER SLOT; omitting it under-prices every candidate, so the caller that
+ re-fits context off this predicate would spend bytes already promised to them.
``ubatch_for_slots`` re-derives the micro-batch per candidate: the emitted
--batch-size is raised to max(slots, 2), and llama.cpp caps the micro-batch
against it, so a batch below the requested slot count shrinks as the candidates
@@ -9957,7 +9966,7 @@ class LlamaCppBackend:
count, since a reduced candidate lowers the batch floor and so the ubatch too;
pricing the reserve at the requested pair over-charged every candidate, so one that
fits could be rejected and the load kept --fit."""
- for slots in range(n_parallel - 1, 0, -1):
+ for slots in range(n_parallel if include_requested else n_parallel - 1, 0, -1):
_ub = ubatch_for_slots(slots) if ubatch_for_slots else n_ubatch
cb = self._estimate_compute_buffer_bytes(
n_ubatch = _ub, n_parallel = slots, per_device_tensor = False
@@ -9975,6 +9984,7 @@ class LlamaCppBackend:
swa_full = swa_full,
kv_unified = kv_unified,
n_ubatch = _ub,
+ ctx_checkpoints = ctx_checkpoints,
flash_attn = flash_attn,
)
)
@@ -9989,6 +9999,8 @@ class LlamaCppBackend:
)
if not use_fit:
return gpu_indices, False, slots
+ if exact:
+ break
return None, True, n_parallel
def _fit_context_to_vram(
@@ -15700,8 +15712,14 @@ class LlamaCppBackend:
# typed --ctx-checkpoints is what the child allocates. Only an
# explicit request counts at all: the estimator has always charged 0,
# and adopting llama.cpp's default of 32 would move the fit for every
- # model.
- _effective_ctx_checkpoints = resolve_ctx_checkpoints(extra_args, ctx_checkpoints)
+ # model. Gated on the capability the argv builder emits the flag on:
+ # a build with neither alias allocates nothing, so pricing it costs
+ # slots and context for bytes no child holds.
+ _effective_ctx_checkpoints = (
+ resolve_ctx_checkpoints(extra_args, ctx_checkpoints)
+ if server_caps.get("ctx_checkpoints_flag")
+ else 0
+ )
# --embedding forces n_batch = n_ubatch, which aborts a load below the slots.
if (
self.is_embedding_gguf
@@ -17781,23 +17799,114 @@ class LlamaCppBackend:
split_extra_bytes = _cc_split_extra(effective_ctx),
ubatch_for_slots = _ubatch_for_slots,
mtp_bytes_for_slots = lambda s, ub: _mtp_bytes(effective_ctx, s, ub),
+ ctx_checkpoints = _effective_ctx_checkpoints,
)
if not _uf_slots:
+ _slots_asked = n_parallel
+ gpu_indices, use_fit, n_parallel = _gi_slots, False, _slots
+ # Fewer slots means a lower batch floor, so the launch runs a
+ # smaller micro-batch than the one this was sized at. Re-derive
+ # it, or the recorded _n_ubatch describes a graph never built.
+ _effective_ubatch = _ubatch_for_slots(n_parallel)
+ # Re-fit at the final slot count; the KV and compute closures
+ # read the values just rebound above.
+
+ def _slots_hold(
+ ctx: int, devices: list[tuple[int, int]]
+ ) -> Optional[list[int]]:
+ """Return the GPU subset if the final slot count fits."""
+ _gi, _uf, _got = self._slots_that_fit_on_gpu(
+ n_parallel,
+ ctx,
+ devices,
+ total_by_idx,
+ model_size_fit - _compute_buffer_pipeline + _cc_bytes(ctx),
+ cache_type_kv,
+ _pin_fraction,
+ _pipeline_overhead_bytes + _cc_bytes(ctx),
+ _layer_min_gpus,
+ _effective_ubatch,
+ swa_full = swa_full,
+ kv_unified = planned_kv_unified,
+ flash_attn = planned_flash_attn,
+ split_extra_bytes = _cc_split_extra(ctx),
+ ubatch_for_slots = _ubatch_for_slots,
+ mtp_bytes_for_slots = (lambda s, ub, c = ctx: _mtp_bytes(c, s, ub)),
+ ctx_checkpoints = _effective_ctx_checkpoints,
+ include_requested = True,
+ exact = True, # only n_parallel is accepted below
+ )
+ return _gi if not _uf and _got == n_parallel else None
+
+ def _largest_ctx(
+ devices: list[tuple[int, int]],
+ ) -> Optional[tuple[int, list[int]]]:
+ """Largest 256-aligned context these cards hold; the
+ footprint grows monotonically with context.
+
+ Bound here, not by the arm above: the arm that reaches this
+ is not always the one that binds it, and a GGUF with no
+ native length would arrive with the 0 sentinel and search
+ nothing."""
+ _native = self._context_length or effective_ctx
+ _lo = max(1, min(4096, _native) // 256)
+ _hi = _native // 256
+ _best = None
+ while _lo <= _hi:
+ _mid = (_lo + _hi) // 2
+ _held = _slots_hold(_mid * 256, devices)
+ if _held is None:
+ _hi = _mid - 1
+ else:
+ _best = (_mid * 256, _held)
+ _lo = _mid + 1
+ return _best
+
+ # Only the cards the reduction chose. Searching every GPU
+ # again buys context by pulling in another device -- the layer
+ # split this path avoids, and one a direct request never makes.
+ _kept = set(_gi_slots or ())
+ _plan_gpus = [g for g in gpus if g[0] in _kept]
+ _refit = _largest_ctx(_plan_gpus)
+ # Explicit contexts are never rewritten.
+ if (
+ _refit is not None
+ and not explicit_ctx
+ and _refit[0] > effective_ctx
+ ):
+ logger.info(
+ "Context re-fitted %d -> %d for %d serving slot(s).",
+ effective_ctx,
+ _refit[0],
+ n_parallel,
+ )
+ effective_ctx, gpu_indices = _refit
+ # After the re-fit, so it names the context that launches
+ # rather than one sized for slots this load dropped.
logger.info(
"Serving slots reduced %d -> %d to keep the model on GPU "
"(avoid --fit offload) at context %d.",
+ _slots_asked,
n_parallel,
- _slots,
effective_ctx,
)
- gpu_indices, use_fit, n_parallel = _gi_slots, False, _slots
- # Fewer slots means a lower batch floor, so the launch runs a
- # smaller micro-batch than the one this was sized at. Re-derive
- # it, or the recorded _n_ubatch describes a graph never built.
- _effective_ubatch = _ubatch_for_slots(n_parallel)
-
- # MTP reserve at the final context, for the logs below.
- _mtp_reserve_bytes = _mtp_bytes(effective_ctx) if _mtp_will_engage else 0
+ # Across every card at the final slot count, matching the
+ # best_cap sweep above; an explicit request that large does
+ # re-select GPUs and load. Not a hardware maximum -- a larger
+ # request can reduce slots further and free KV for more.
+ _ceiling = (
+ _refit if len(_plan_gpus) == len(gpus) else _largest_ctx(gpus)
+ )
+ if _ceiling is not None:
+ max_available_ctx = max(max_available_ctx, _ceiling[0])
+
+ # Pass the final slot and micro-batch values instead of the defaults
+ # captured before slot reduction.
+ _mtp_reserve_bytes = (
+ _mtp_bytes(effective_ctx, n_parallel, _effective_ubatch)
+ if _mtp_will_engage
+ else 0
+ )
if _mtp_will_engage:
_mtp_note = (
f"MTP reserve: {_mtp_reserve_bytes / (1024**3):.2f} GB "
@@ -18504,8 +18613,7 @@ class LlamaCppBackend:
logger.info("Draft KV cache dtype: %s", _draft_cache_type)
else:
logger.info(
- "llama-server has no draft KV cache flags; skipping the "
- "requested %s.",
+ "llama-server has no draft KV cache flags; skipping the requested %s.",
_draft_cache_type,
)
# Remember where the spec block sits so a drafter-load failure
diff --git a/studio/backend/tests/test_compute_buffer.py b/studio/backend/tests/test_compute_buffer.py
index 37f65de9e91..1f96c770a12 100644
--- a/studio/backend/tests/test_compute_buffer.py
+++ b/studio/backend/tests/test_compute_buffer.py
@@ -806,8 +806,8 @@ class TestPerDeviceSplitReserve:
subset = ranked[:n]
pool = sum(max(0.0, usable(g)) for g in subset)
ms = model_bytes + (n - 1) * self._OH
- cc = lambda c, n = n: n * b._compute_buffer_ctx_bytes(
- c, self._UB, "f16", layer_split = n > 1
+ cc = lambda c, n = n: (
+ n * b._compute_buffer_ctx_bytes(c, self._UB, "f16", layer_split = n > 1)
)
capped = b._fit_context_to_vram(
native_ctx,
@@ -976,9 +976,8 @@ class TestPerDeviceReserveCap:
def test_cap_is_exact_at_the_256_boundary(self):
b = self._fit_backend()
usable = 2_500 - 0.03 * 24_576 # 1762.72 MiB
- reserve = (
- lambda c: (self._OH + b._compute_buffer_ctx_bytes(c, self._UB, "f16", layer_split = True))
- / MIB
+ reserve = lambda c: (
+ (self._OH + b._compute_buffer_ctx_bytes(c, self._UB, "f16", layer_split = True)) / MIB
)
assert reserve(31_488) == 1762.0 <= usable
assert reserve(31_744) == 1768.0 > usable
@@ -1185,6 +1184,10 @@ class TestSplitRateRecheckAfterSelection:
load = "".join(inspect.getsource(LlamaCppBackend.load_model).split())
# Explicit-context pin and the reduced-slot retry both pass the step.
assert load.count("split_extra_bytes=_cc_split_extra(effective_ctx)") == 2
+ # The re-fit is a third call site, spelled `ctx` because it re-prices per
+ # candidate. Not exempt from the step; a rename that collapsed the two
+ # spellings would have to bump the count above.
+ assert load.count("split_extra_bytes=_cc_split_extra(ctx),") == 1
assert "gpu_indices,use_fit=self._select_gpus_split_aware(" in load
# The step rides _cc_bytes' pipelining gate, so it is 0 when llama.cpp declines.
assert "returnmax(0,_cc_bytes(ctx,2)//2-_cc_bytes(ctx))" in load
diff --git a/studio/backend/tests/test_slot_reduction_context_refit.py b/studio/backend/tests/test_slot_reduction_context_refit.py
new file mode 100644
index 00000000000..261f83854b5
--- /dev/null
+++ b/studio/backend/tests/test_slot_reduction_context_refit.py
@@ -0,0 +1,344 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Regression tests for context fitting after serving-slot reduction.
+
+The synthetic plans use Qwen3.8-27B metadata and capture the generated command.
+Each case names its speculative mode because unknown values resolve to Auto.
+"""
+
+from __future__ import annotations
+
+import re
+import sys
+from pathlib import Path
+
+_TESTS_DIR = str(Path(__file__).resolve().parent)
+if _TESTS_DIR not in sys.path:
+ sys.path.insert(0, _TESTS_DIR)
+
+import pytest # noqa: E402
+
+from test_llama_cpp_placement import _backend, _launch # noqa: E402
+
+MIB = 1024 * 1024
+NATIVE_CTX = 262144
+CARD_MIB = 12 * 1024 # usable 11,919 MiB at the 0.97 pin fraction
+MIXED_CARDS = (CARD_MIB, 1_280) # a primary plus a card too small to plan onto
+
+# Qwen3.8-27B-GGUF metadata.
+HYBRID = {
+ "_architecture": "qwen35",
+ "_vocab_size": 248320,
+ "_nextn_predict_layers": 1,
+ "_n_layers": 65,
+ "_n_kv_heads": 4,
+ "_n_heads": 24,
+ "_embedding_length": 5120,
+ "_kv_key_length": 256,
+ "_kv_value_length": 256,
+ "_key_length_mla": None,
+ "_context_length": NATIVE_CTX,
+ "_full_attention_interval": 4,
+ "_ssm_inner_size": 6144,
+ "_ssm_state_size": 128,
+ "_ssm_group_count": 16,
+ "_ssm_conv_kernel": 4,
+}
+DENSE = {
+ "_architecture": "qwen3",
+ "_vocab_size": 248320,
+ "_n_layers": 64,
+ "_n_kv_heads": 8,
+ "_n_heads": 32,
+ "_embedding_length": 5120,
+ "_kv_key_length": 128,
+ "_kv_value_length": 128,
+ "_key_length_mla": None,
+ "_context_length": NATIVE_CTX,
+}
+
+
+def _plan(
+ tmp_path,
+ *,
+ weights_mib,
+ n_parallel,
+ spec,
+ vram_mib = CARD_MIB,
+ n_ctx = 0,
+ metadata = HYBRID,
+ gpus = 1,
+):
+ """Return the generated placement plan. ``vram_mib`` may be a per-card sequence."""
+ cards = list(vram_mib) if isinstance(vram_mib, (tuple, list)) else [vram_mib] * gpus
+ memory = [(i, mib, mib) for i, mib in enumerate(cards)]
+ backend, gguf = _backend(tmp_path, vulkan = False, memory = memory)
+
+ def read(_path):
+ for key, value in metadata.items():
+ setattr(backend, key, value)
+
+ backend._read_gguf_metadata = read
+ backend._get_gguf_size_bytes = lambda _path: weights_mib * MIB
+ del backend._can_estimate_kv # the real one, now that the dims are set
+ backend.probe_server_capabilities = lambda _binary = None: {
+ "mtp_token": "draft-mtp",
+ "supports_ngram_mod": True,
+ "spec_draft_n_max_flag": "--spec-draft-n-max",
+ # Keep the requested slot count available to the planner.
+ "supports_kv_unified": True,
+ "supports_fit_ctx": True,
+ }
+ launched = _launch(backend, gguf, speculative_type = spec, n_ctx = n_ctx, n_parallel = n_parallel)
+ cmd = launched["cmd"]
+
+ def flag(name, default = None):
+ return cmd[cmd.index(name) + 1] if name in cmd else default
+
+ return {
+ "ctx": int(flag("-c", 0)),
+ "slots": int(flag("--parallel", 1)),
+ "fit": flag("--fit", "off"),
+ "spec": flag("--spec-type", "-"),
+ "ceiling": backend._max_context_length,
+ "devices": (launched["env"] or {}).get("CUDA_VISIBLE_DEVICES"),
+ }
+
+
+class TestTheLaunchedCountOwnsTheContext:
+ """Speculation is off so only slot reduction affects the context."""
+
+ @pytest.mark.parametrize(
+ "weights_mib,asked,slots,ctx",
+ [
+ (9_600, 4, 3, 5_888), # main: 3 slots, 4096
+ (10_200, 4, 2, 7_680), # main: 2 slots, 4096
+ (10_200, 8, 2, 7_680), # main: 2 slots, 4096
+ ],
+ )
+ def test_auto_context_follows_the_reduction(self, tmp_path, weights_mib, asked, slots, ctx):
+ got = _plan(tmp_path, weights_mib = weights_mib, n_parallel = asked, spec = "off")
+ assert (got["slots"], got["fit"]) == (slots, "off")
+ assert got["ctx"] == got["ceiling"] == ctx
+
+ @pytest.mark.parametrize("weights_mib,asked,final", [(9_600, 4, 3), (10_200, 4, 2)])
+ def test_reducing_to_a_count_matches_starting_at_it(self, tmp_path, weights_mib, asked, final):
+ """A reduced plan matches one started at its final slot count."""
+ reduced = _plan(tmp_path, weights_mib = weights_mib, n_parallel = asked, spec = "off")
+ direct = _plan(tmp_path, weights_mib = weights_mib, n_parallel = final, spec = "off")
+ assert reduced["slots"] == direct["slots"] == final
+ assert (reduced["ctx"], reduced["ceiling"]) == (direct["ctx"], direct["ceiling"])
+
+ def test_the_published_ceiling_is_not_the_4096_anchor(self, tmp_path):
+ """The published ceiling follows the final slot count."""
+ got = _plan(tmp_path, weights_mib = 10_200, n_parallel = 4, spec = "off")
+ assert got["ceiling"] == 7_680
+
+ def test_a_layer_split_across_two_cards_re_fits_the_same_way(self, tmp_path):
+ """The same invariant holds for a two-card layer split."""
+ reduced = _plan(
+ tmp_path, weights_mib = 14_000, n_parallel = 4, spec = "off", vram_mib = 8_704, gpus = 2
+ )
+ direct = _plan(
+ tmp_path, weights_mib = 14_000, n_parallel = 2, spec = "off", vram_mib = 8_704, gpus = 2
+ )
+ assert (reduced["slots"], reduced["fit"]) == (2, "off")
+ assert reduced["ctx"] == reduced["ceiling"] == 8_448
+ assert (reduced["ctx"], reduced["ceiling"]) == (direct["ctx"], direct["ceiling"])
+
+
+class TestTheRefitStaysOnTheCardsTheReductionChose:
+ """A 12 GiB primary next to a 1.25 GiB card: the reduced plan fits on the primary
+ alone, and only the small card can hold a longer context."""
+
+ def test_the_refit_does_not_pull_in_another_card(self, tmp_path):
+ got = _plan(tmp_path, weights_mib = 10_200, n_parallel = 4, spec = "off", vram_mib = MIXED_CARDS)
+ assert (got["slots"], got["fit"], got["devices"]) == (2, "off", "0")
+ assert got["ctx"] == 7_680
+
+ def test_it_matches_a_request_started_at_the_final_count(self, tmp_path):
+ reduced = _plan(
+ tmp_path, weights_mib = 10_200, n_parallel = 4, spec = "off", vram_mib = MIXED_CARDS
+ )
+ direct = _plan(tmp_path, weights_mib = 10_200, n_parallel = 2, spec = "off", vram_mib = MIXED_CARDS)
+ assert reduced["devices"] == direct["devices"] == "0"
+ assert (reduced["ctx"], reduced["ceiling"]) == (direct["ctx"], direct["ceiling"])
+
+ def test_the_ceiling_still_counts_the_card_the_launch_left_out(self, tmp_path):
+ """The ceiling keeps measuring across both cards, not just the launched one."""
+ mixed = _plan(tmp_path, weights_mib = 10_200, n_parallel = 4, spec = "off", vram_mib = MIXED_CARDS)
+ alone = _plan(tmp_path, weights_mib = 10_200, n_parallel = 4, spec = "off")
+ assert mixed["ctx"] == alone["ctx"] == 7_680
+ assert (mixed["ceiling"], alone["ceiling"]) == (9_472, 7_680)
+
+
+class TestAutoSpeculationStillDecidesBeforeTheReduction:
+ """Pin the existing behavior where Auto admits MTP before slot reduction."""
+
+ def test_a_direct_one_slot_request_drops_the_drafter_and_keeps_context(self, tmp_path):
+ got = _plan(tmp_path, weights_mib = 10_200, n_parallel = 1, spec = "auto")
+ assert (got["slots"], got["ctx"], got["spec"]) == (1, 18_688, "ngram-mod")
+
+ @pytest.mark.parametrize("asked", [4, 8])
+ def test_a_reduced_request_still_carries_the_drafter_it_admitted(self, tmp_path, asked):
+ got = _plan(tmp_path, weights_mib = 10_200, n_parallel = asked, spec = "auto")
+ assert (got["slots"], got["spec"]) == (1, "draft-mtp")
+ # The retained MTP reserve keeps this below the direct one-slot context.
+ assert got["ctx"] == 9_984
+
+ def test_the_gap_narrows_and_never_widens(self, tmp_path):
+ """The refit narrows the pre-existing gap."""
+ direct = _plan(tmp_path, weights_mib = 10_200, n_parallel = 1, spec = "auto")
+ reduced = _plan(tmp_path, weights_mib = 10_200, n_parallel = 4, spec = "auto")
+ assert reduced["ctx"] <= direct["ctx"]
+ assert direct["ctx"] - reduced["ctx"] < direct["ctx"] - 4096
+
+
+class TestWhatMustNotMove:
+ def test_an_explicit_context_is_still_honored_verbatim(self, tmp_path):
+ """An explicit context remains unchanged after slot reduction."""
+ got = _plan(tmp_path, weights_mib = 8_400, n_parallel = 4, spec = "off", n_ctx = 32768)
+ assert (got["ctx"], got["slots"], got["fit"]) == (32768, 2, "off")
+ # The measured ceiling still follows the final slot count.
+ assert got["ceiling"] == 35_840
+
+ def test_an_explicit_context_that_forces_offload_is_unchanged(self, tmp_path):
+ """An explicit context that requires offload is unchanged."""
+ got = _plan(tmp_path, weights_mib = 10_200, n_parallel = 4, spec = "off", n_ctx = 32768)
+ assert (got["ctx"], got["slots"], got["fit"]) == (32768, 4, "on")
+ assert got["ceiling"] == 4096
+
+ def test_a_count_that_needs_no_reduction_is_untouched(self, tmp_path):
+ """A plan that needs no slot reduction is unchanged."""
+ got = _plan(tmp_path, weights_mib = 6_000, n_parallel = 4, spec = "off")
+ assert (got["slots"], got["fit"], got["ctx"]) == (4, "off", 51_200)
+
+ def test_weights_that_fit_nowhere_still_offload(self, tmp_path):
+ """Oversized weights still fall back to offload."""
+ got = _plan(tmp_path, weights_mib = 11_400, n_parallel = 4, spec = "off")
+ assert (got["fit"], got["ctx"], got["ceiling"]) == ("on", 4096, 4096)
+
+ @pytest.mark.parametrize(
+ "weights_mib,slots,ctx",
+ [
+ (9_200, 3, 4_864), # main: 3 slots, 4096
+ (10_000, 1, 6_144), # main: 1 slot, 4096
+ ],
+ )
+ def test_a_dense_target_gains_only_its_compute_buffer(self, tmp_path, weights_mib, slots, ctx):
+ """Dense models also recover slot-scaled compute-buffer capacity."""
+ got = _plan(tmp_path, weights_mib = weights_mib, n_parallel = 4, spec = "off", metadata = DENSE)
+ assert (got["slots"], got["ctx"]) == (slots, ctx)
+
+
+class TestTheSearchPredicate:
+ def test_include_requested_answers_for_the_count_itself(self):
+ """The helper can test the requested slot count itself."""
+ from core.inference.llama_cpp import LlamaCppBackend
+
+ backend = LlamaCppBackend.__new__(LlamaCppBackend)
+ backend._vocab_size = 248320
+ backend._embedding_length = 5120
+ backend._key_length_mla = None
+ backend._estimate_kv_cache_bytes = lambda *_a, **_k: 0
+ backend._can_estimate_kv = lambda: True
+
+ def fit(include_requested):
+ return backend._slots_that_fit_on_gpu(
+ 2,
+ 4096,
+ [(0, 24576)],
+ {0: 24576},
+ 22_500 * MIB,
+ "q8_0",
+ LlamaCppBackend._GPU_PIN_VRAM_FRACTION,
+ 0,
+ 1,
+ n_ubatch = 512,
+ include_requested = include_requested,
+ )
+
+ assert fit(True) == ([0], False, 2)
+ assert fit(False) == ([0], False, 1)
+
+
+class TestTheLoggedReserveFollowsTheLaunch:
+ def test_identical_launches_log_the_same_reserve(self, tmp_path, monkeypatch):
+ """Equivalent final plans log the same final-slot MTP reserve."""
+ from core.inference.llama_cpp import logger as planner_logger
+
+ lines: list[str] = []
+
+ class _Recorder:
+ def __getattr__(self, _level):
+ def emit(msg, *args, **_kwargs):
+ lines.append(str(msg) % args if args else str(msg))
+
+ return emit
+
+ monkeypatch.setattr("core.inference.llama_cpp.logger", _Recorder())
+ assert planner_logger is not None # the real one is restored on teardown
+
+ seen = []
+ for asked in (2, 4, 8):
+ lines.clear()
+ got = _plan(tmp_path, weights_mib = 8_000, n_parallel = asked, spec = "auto", vram_mib = 9_728)
+ reserves = set(re.findall(r"MTP reserve: ([\d.]+) GB", "\n".join(lines)))
+ assert reserves, "the reserve was never logged"
+ seen.append((got["slots"], got["ctx"], got["spec"], reserves))
+
+ assert seen[0][:3] == (1, 5_632, "draft-mtp")
+ assert len({row[:3] for row in seen}) == 1, "the three launches differ"
+ assert len({frozenset(row[3]) for row in seen}) == 1, seen
+ assert seen[0][3] == {"0.31"}
+
+
+# KV-estimable metadata without a native context length.
+NO_NATIVE_CTX = {**DENSE, "_context_length": None}
+
+
+class TestAGgufWithNoNativeContext:
+ """Cover slot reduction when native-context metadata is absent."""
+
+ @pytest.mark.parametrize(
+ "vram_mib,weights_mib,asked,slots",
+ [
+ (12 * 1024, 9_000, 8, 3),
+ (16 * 1024, 12_000, 8, 5),
+ ],
+ )
+ def test_the_reduction_still_pins_without_a_native_context(
+ self, tmp_path, vram_mib, weights_mib, asked, slots
+ ):
+ got = _plan(
+ tmp_path,
+ weights_mib = weights_mib,
+ n_parallel = asked,
+ spec = "off",
+ vram_mib = vram_mib,
+ metadata = NO_NATIVE_CTX,
+ )
+ assert (got["slots"], got["fit"], got["ctx"]) == (slots, "off", 4096)
+
+ def test_no_planner_exception_is_swallowed(self, tmp_path, monkeypatch):
+ """The broad placement handler must not hide a planner failure."""
+ warnings: list[str] = []
+
+ class _Recorder:
+ def __getattr__(self, _level):
+ def emit(msg, *args, **_kwargs):
+ warnings.append(str(msg) % args if args else str(msg))
+
+ return emit
+
+ monkeypatch.setattr("core.inference.llama_cpp.logger", _Recorder())
+ _plan(
+ tmp_path,
+ weights_mib = 9_000,
+ n_parallel = 8,
+ spec = "off",
+ vram_mib = 12 * 1024,
+ metadata = NO_NATIVE_CTX,
+ )
+ assert not [w for w in warnings if "GPU selection failed" in w], warnings
diff --git a/studio/backend/tests/test_slot_refit_ctx_checkpoints.py b/studio/backend/tests/test_slot_refit_ctx_checkpoints.py
new file mode 100644
index 00000000000..f69dd23e52e
--- /dev/null
+++ b/studio/backend/tests/test_slot_refit_ctx_checkpoints.py
@@ -0,0 +1,215 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""The slot/context fit predicate has to charge the --ctx-checkpoints reserve.
+
+``--ctx-checkpoints N`` allocates N SWA/recurrent snapshots PER SLOT.
+``_slots_that_fit_on_gpu`` priced its candidates without it: survivable while the
+only consumer was the slot count, but the post-reduction re-fit uses the same
+predicate to pick the launched ``-c``, so it spent bytes already promised.
+
+The target is Gemma-3 shaped, since the reserve is charged only on SWA layers.
+"""
+
+from __future__ import annotations
+
+import sys
+from pathlib import Path
+
+_TESTS_DIR = str(Path(__file__).resolve().parent)
+if _TESTS_DIR not in sys.path:
+ sys.path.insert(0, _TESTS_DIR)
+
+import pytest # noqa: E402
+
+from test_llama_cpp_placement import _backend, _launch # noqa: E402
+
+MIB = 1024 * 1024
+NATIVE_CTX = 131072
+CARD_MIB = 12 * 1024
+
+SWA = {
+ "_architecture": "gemma3",
+ "_vocab_size": 262144,
+ "_n_layers": 62,
+ "_n_kv_heads": 4,
+ "_n_heads": 16,
+ "_embedding_length": 3840,
+ "_kv_key_length": 256,
+ "_kv_value_length": 256,
+ "_key_length_mla": None,
+ "_context_length": NATIVE_CTX,
+ "_sliding_window": 1024,
+}
+
+
+def _plan(
+ tmp_path,
+ *,
+ weights_mib,
+ n_parallel,
+ ctx_checkpoints,
+ vram_mib = CARD_MIB,
+ cache_type_kv = "q8_0",
+ ctx_checkpoints_flag = "--ctx-checkpoints",
+):
+ """Return the generated plan plus what its own context really costs."""
+ memory = [(0, vram_mib, vram_mib)]
+ backend, gguf = _backend(tmp_path, vulkan = False, memory = memory)
+
+ def read(_path):
+ for key, value in SWA.items():
+ setattr(backend, key, value)
+
+ backend._read_gguf_metadata = read
+ backend._get_gguf_size_bytes = lambda _path: weights_mib * MIB
+ del backend._can_estimate_kv # the real one, now that the dims are set
+ backend.probe_server_capabilities = lambda _binary = None: {
+ "mtp_token": "draft-mtp",
+ "supports_ngram_mod": True,
+ "spec_draft_n_max_flag": "--spec-draft-n-max",
+ "supports_kv_unified": True,
+ "supports_fit_ctx": True,
+ "supports_ctx_checkpoints": ctx_checkpoints_flag is not None,
+ "ctx_checkpoints_flag": ctx_checkpoints_flag,
+ }
+ launched = _launch(
+ backend,
+ gguf,
+ speculative_type = "off",
+ n_ctx = 0,
+ n_parallel = n_parallel,
+ cache_type_kv = cache_type_kv,
+ ctx_checkpoints = ctx_checkpoints,
+ )
+ cmd = launched["cmd"]
+
+ def flag(name, default = None):
+ return cmd[cmd.index(name) + 1] if name in cmd else default
+
+ ctx = int(flag("-c", 0))
+ slots = int(flag("--parallel", 1))
+ _cp = int(ctx_checkpoints or 0)
+ kv_kwargs = dict(
+ n_parallel = slots,
+ swa_full = False,
+ kv_unified = True,
+ n_ubatch = None,
+ flash_attn = True,
+ )
+ return {
+ "ctx": ctx,
+ "slots": slots,
+ "fit": flag("--fit", "off"),
+ "checkpoints": flag("--ctx-checkpoints"),
+ # What the launch reserves beyond the plain cache.
+ "reserve_bytes": (
+ backend._estimate_kv_cache_bytes(ctx, cache_type_kv, ctx_checkpoints = _cp, **kv_kwargs)
+ - backend._estimate_kv_cache_bytes(ctx, cache_type_kv, ctx_checkpoints = 0, **kv_kwargs)
+ ),
+ }
+
+
+def _prime(backend):
+ """Set every field the KV estimator reads on a bare backend."""
+ for key, value in SWA.items():
+ setattr(backend, key, value)
+ backend._kv_key_length_swa = None
+ backend._kv_value_length_swa = None
+ backend._sliding_window_pattern = None
+ backend._kv_lora_rank = None
+ backend._nextn_predict_layers = 0
+ backend._ssm_inner_size = None
+ backend._ssm_state_size = None
+ backend._ssm_group_count = None
+ backend._ssm_conv_kernel = None
+ backend._full_attention_interval = None
+ backend._shared_kv_layers = None
+
+
+class TestThePredicateChargesTheReserve:
+ """Straight at the helper, the way the include_requested case is tested."""
+
+ @staticmethod
+ def _fit(ctx_checkpoints):
+ from core.inference.llama_cpp import LlamaCppBackend
+
+ backend = LlamaCppBackend.__new__(LlamaCppBackend)
+ _prime(backend)
+ return backend._slots_that_fit_on_gpu(
+ 8,
+ 8192,
+ [(0, CARD_MIB)],
+ {0: CARD_MIB},
+ 6_000 * MIB,
+ "q8_0",
+ LlamaCppBackend._GPU_PIN_VRAM_FRACTION,
+ 0,
+ 1,
+ n_ubatch = 512,
+ ctx_checkpoints = ctx_checkpoints,
+ include_requested = True,
+ )
+
+ def test_charging_the_reserve_costs_slots(self):
+ """More memory per slot can only buy the same count or fewer."""
+ free = self._fit(0)
+ charged = self._fit(32)
+ assert free[2] > charged[2], (free, charged)
+
+ def test_the_reserve_is_not_free_on_this_fixture(self):
+ """Guards the two tests above from passing on a zero-cost shape."""
+ from core.inference.llama_cpp import LlamaCppBackend
+
+ backend = LlamaCppBackend.__new__(LlamaCppBackend)
+ _prime(backend)
+ kv = dict(n_parallel = 4, swa_full = False, kv_unified = True, flash_attn = True)
+ assert backend._estimate_kv_cache_bytes(
+ 8192, "q8_0", ctx_checkpoints = 32, **kv
+ ) > backend._estimate_kv_cache_bytes(8192, "q8_0", ctx_checkpoints = 0, **kv)
+
+
+class TestTheRefitDoesNotSpendTheReserve:
+ """End to end: the context the re-fit publishes has to leave room for it."""
+
+ @pytest.mark.parametrize("checkpoints", [4, 16, 32])
+ def test_a_checkpointed_launch_gets_less_context_than_an_uncheckpointed_one(
+ self, tmp_path, checkpoints
+ ):
+ """Unpriced, the two stay identical however large --ctx-checkpoints gets,
+ while the child allocates it anyway."""
+ free = _plan(tmp_path, weights_mib = 9_200, n_parallel = 4, ctx_checkpoints = 0)
+ charged = _plan(tmp_path, weights_mib = 9_200, n_parallel = 4, ctx_checkpoints = checkpoints)
+ assert charged["reserve_bytes"] > 0
+ assert charged["checkpoints"] == str(checkpoints)
+ assert charged["ctx"] < free["ctx"], (free, charged)
+
+ def test_a_plan_with_room_for_it_still_stays_on_gpu(self, tmp_path):
+ """The reserve costs context, not the GPU pin, while there is room."""
+ got = _plan(tmp_path, weights_mib = 6_800, n_parallel = 8, ctx_checkpoints = 16)
+ assert got["fit"] == "off"
+ assert got["ctx"] > 0
+ assert got["reserve_bytes"] > 0
+
+ def test_a_build_without_the_flag_is_not_charged(self, tmp_path):
+ """The argv builder drops the request, so the child allocates nothing."""
+ supported = _plan(tmp_path, weights_mib = 9_200, n_parallel = 4, ctx_checkpoints = 32)
+ skipped = _plan(
+ tmp_path,
+ weights_mib = 9_200,
+ n_parallel = 4,
+ ctx_checkpoints = 32,
+ ctx_checkpoints_flag = None,
+ )
+ none_asked = _plan(tmp_path, weights_mib = 9_200, n_parallel = 4, ctx_checkpoints = 0)
+ assert skipped["checkpoints"] is None # not emitted
+ assert (skipped["ctx"], skipped["slots"]) == (none_asked["ctx"], none_asked["slots"])
+ assert skipped["ctx"] > supported["ctx"]
+
+ def test_no_checkpoints_is_unchanged(self, tmp_path):
+ """The default (0) has to plan exactly as it did before."""
+ default = _plan(tmp_path, weights_mib = 9_200, n_parallel = 4, ctx_checkpoints = None)
+ zero = _plan(tmp_path, weights_mib = 9_200, n_parallel = 4, ctx_checkpoints = 0)
+ assert default["ctx"] == zero["ctx"]
+ assert default["slots"] == zero["slots"]
+ assert zero["reserve_bytes"] == 0
diff --git a/studio/backend/tests/test_slot_refit_platform_matrix.py b/studio/backend/tests/test_slot_refit_platform_matrix.py
new file mode 100644
index 00000000000..ea8b43612a6
--- /dev/null
+++ b/studio/backend/tests/test_slot_refit_platform_matrix.py
@@ -0,0 +1,224 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Which platforms the post-reduction context re-fit is allowed to touch.
+
+Its guard -- ``use_fit and n_parallel > 1 and gpus and self._can_estimate_kv()
+and effective_ctx > 0`` -- encodes a hardware claim that is easy to lose in a
+refactor. ``gpus`` is empty on Metal (no torch.cuda device is enumerated, which
+is why the Apple arm exists) and on any CPU-only host; tensor-parallel clears
+``use_fit`` first; manual memory mode empties ``gpus``. All are excluded.
+
+These watch the predicate, not the argv, so a cell that starts entering the
+block fails here even when its numbers happen not to move.
+"""
+
+from __future__ import annotations
+
+import platform as _platform
+import sys
+from contextlib import ExitStack
+from pathlib import Path
+from unittest.mock import patch
+
+_TESTS_DIR = str(Path(__file__).resolve().parent)
+if _TESTS_DIR not in sys.path:
+ sys.path.insert(0, _TESTS_DIR)
+
+import pytest # noqa: E402
+
+import core.inference.llama_cpp as llama_mod # noqa: E402
+from core.inference.llama_cpp import LlamaCppBackend # noqa: E402
+from test_llama_cpp_placement import _backend, _launch # noqa: E402
+
+MIB = 1024 * 1024
+NATIVE_CTX = 262144
+CARD_MIB = 12 * 1024
+
+DENSE = {
+ "_architecture": "qwen3",
+ "_vocab_size": 248320,
+ "_n_layers": 64,
+ "_n_kv_heads": 8,
+ "_n_heads": 32,
+ "_embedding_length": 5120,
+ "_kv_key_length": 128,
+ "_kv_value_length": 128,
+ "_key_length_mla": None,
+ "_context_length": NATIVE_CTX,
+}
+
+# (sys.platform, platform.system(), apple_silicon)
+OS_CELLS = {
+ "linux": ("linux", "Linux", False),
+ "wsl": ("linux", "Linux", False),
+ "windows": ("win32", "Windows", False),
+ "macos_arm": ("darwin", "Darwin", True),
+ "macos_intel": ("darwin", "Darwin", False),
+}
+# (vulkan, enumerates_a_gpu)
+VENDOR_CELLS = {
+ "nvidia": (False, True),
+ "amd": (False, True),
+ "vulkan": (True, True),
+ "cpu": (False, False),
+}
+
+REACHABLE = {
+ (os_key, vendor)
+ for os_key in ("linux", "wsl", "windows")
+ for vendor in ("nvidia", "amd", "vulkan")
+}
+ALL_CELLS = [(o, v) for o in OS_CELLS for v in VENDOR_CELLS]
+
+
+class _RefitSpy:
+ """Counts re-fit entries: only ``_slots_hold`` passes ``include_requested``."""
+
+ def __init__(self):
+ self.calls = 0
+
+ def __enter__(self):
+ real, spy = LlamaCppBackend._slots_that_fit_on_gpu, self
+
+ def wrapper(backend_self, *args, **kwargs):
+ if kwargs.get("include_requested"):
+ spy.calls += 1
+ return real(backend_self, *args, **kwargs)
+
+ self._patch = patch.object(LlamaCppBackend, "_slots_that_fit_on_gpu", wrapper)
+ self._patch.start()
+ return self
+
+ def __exit__(self, *exc):
+ self._patch.stop()
+ return False
+
+
+def _plan(
+ tmp_path,
+ *,
+ os_key,
+ vendor,
+ weights_mib = 10_200,
+ n_parallel = 4,
+ vram_mib = CARD_MIB,
+ n_ctx = 0,
+ tensor_parallel = False,
+ gpu_memory_mode = None,
+):
+ """Drive the real planner under a spoofed host. Returns (plan, refit_entries)."""
+ sys_platform, system, apple_silicon = OS_CELLS[os_key]
+ vulkan, enumerates_gpu = VENDOR_CELLS[vendor]
+
+ with ExitStack() as stack:
+ # Never os.name: it swaps pathlib's flavour and the temp GGUF stops opening.
+ stack.enter_context(patch.object(llama_mod.sys, "platform", sys_platform))
+ stack.enter_context(patch.object(_platform, "system", lambda: system))
+ # The Metal budget selects the Apple arm; 0 elsewhere keeps it inert.
+ stack.enter_context(
+ patch.object(
+ LlamaCppBackend,
+ "_apple_metal_memory_budget_bytes",
+ staticmethod(lambda: (48 * 1024 * MIB) if apple_silicon else 0),
+ )
+ )
+ stack.enter_context(patch.object(llama_mod, "_metal_device_is_paravirtual", lambda: False))
+
+ # macOS enumerates no torch.cuda device; a CPU-only host has none either.
+ cards = [] if (not enumerates_gpu or sys_platform == "darwin") else [vram_mib]
+ memory = [(i, mib, mib) for i, mib in enumerate(cards)]
+ backend, gguf = _backend(tmp_path, vulkan = vulkan, memory = memory)
+
+ def read(_path):
+ for key, value in DENSE.items():
+ setattr(backend, key, value)
+
+ backend._read_gguf_metadata = read
+ backend._get_gguf_size_bytes = lambda _path: weights_mib * MIB
+ del backend._can_estimate_kv # the real one, now that the dims are set
+ backend.probe_server_capabilities = lambda _binary = None: {
+ "mtp_token": "draft-mtp",
+ "supports_ngram_mod": True,
+ "spec_draft_n_max_flag": "--spec-draft-n-max",
+ "supports_kv_unified": True,
+ "supports_fit_ctx": True,
+ }
+
+ kwargs = {"speculative_type": "off", "n_ctx": n_ctx, "n_parallel": n_parallel}
+ if tensor_parallel:
+ kwargs["tensor_parallel"] = True
+ if gpu_memory_mode is not None:
+ kwargs["gpu_memory_mode"] = gpu_memory_mode
+
+ with _RefitSpy() as spy:
+ launched = _launch(backend, gguf, **kwargs)
+ cmd = launched["cmd"]
+
+ def flag(name, default = None):
+ return cmd[cmd.index(name) + 1] if name in cmd else default
+
+ return {
+ "ctx": int(flag("-c", 0)),
+ "slots": int(flag("--parallel", 1)),
+ "fit": flag("--fit", "off"),
+ "ngl": flag("-ngl"),
+ "threads": flag("--threads"),
+ "ceiling": backend._max_context_length,
+ }, spy.calls
+
+
+class TestWhoTheRefitIsAllowedToTouch:
+ @pytest.mark.parametrize("os_key,vendor", ALL_CELLS, ids = [f"{o}-{v}" for o, v in ALL_CELLS])
+ def test_only_a_gpu_host_enters_the_refit(self, tmp_path, os_key, vendor):
+ """Metal and CPU-only hosts must not reach the new block at all."""
+ _, entries = _plan(tmp_path, os_key = os_key, vendor = vendor)
+ if (os_key, vendor) in REACHABLE:
+ assert entries > 0, f"{os_key}/{vendor} should re-fit"
+ else:
+ assert entries == 0, f"{os_key}/{vendor} must not re-fit"
+
+ @pytest.mark.parametrize("os_key", ["macos_arm", "macos_intel"])
+ def test_macos_plans_exactly_as_it_did(self, tmp_path, os_key):
+ """No enumerated GPU means the Apple arm owns the plan, untouched."""
+ got, entries = _plan(tmp_path, os_key = os_key, vendor = "nvidia")
+ assert entries == 0
+ assert got["ngl"] is None # never pinned to a device that does not exist
+
+ def test_tensor_parallel_is_excluded(self, tmp_path):
+ """The tensor arm has no --fit valve, so the re-fit must stay out."""
+ _, entries = _plan(
+ tmp_path,
+ os_key = "linux",
+ vendor = "nvidia",
+ tensor_parallel = True,
+ vram_mib = 24 * 1024,
+ )
+ assert entries == 0
+
+ def test_manual_memory_mode_is_excluded(self, tmp_path):
+ """Manual mode is the caller taking the budget over."""
+ _, entries = _plan(tmp_path, os_key = "linux", vendor = "nvidia", gpu_memory_mode = "manual")
+ assert entries == 0
+
+ def test_a_single_slot_request_is_excluded(self, tmp_path):
+ """Nothing to reduce, so nothing to re-fit."""
+ _, entries = _plan(tmp_path, os_key = "linux", vendor = "nvidia", n_parallel = 1)
+ assert entries == 0
+
+
+class TestWindowsPlansLikeLinux:
+ """The re-fit must not newly arm the Windows full-offload thread cap."""
+
+ def test_the_thread_cap_tracks_the_slot_reduction_not_the_refit(self, tmp_path):
+ """--threads 2 rides fully_gpu_offloaded, which the reduction already set."""
+ win, win_entries = _plan(tmp_path, os_key = "windows", vendor = "nvidia")
+ linux, linux_entries = _plan(tmp_path, os_key = "linux", vendor = "nvidia")
+ assert win_entries == linux_entries > 0
+ # Same plan either way; only the Windows-only thread pin differs.
+ assert (win["ctx"], win["slots"], win["fit"]) == (
+ linux["ctx"],
+ linux["slots"],
+ linux["fit"],
+ )
+ assert linux["threads"] is None