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.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Fix main: price the serving-slot reduction at the fit floor, not the Auto offload context (#9594)
Daniel Han7208e2b33c10
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.pyindex b855a384f49..15752faea7e 100644--- a/studio/backend/core/inference/llama_cpp.py+++ b/studio/backend/core/inference/llama_cpp.py@@ -17813,28 +17813,54 @@ class LlamaCppBackend:and self._can_estimate_kv()and effective_ctx > 0):+ # The PROBE context for the search below, not the context the load+ # runs at: the re-fit further down awards that, from the final slot+ # count. So price the search at the fit search floor, never at+ # _AUTO_OFFLOAD_CTX.+ #+ # _AUTO_OFFLOAD_CTX is what Auto settles for once offload really is+ # unavoidable. Asking this search at that value asks the wrong+ # question, because this block exists to OVERTURN "offload is+ # unavoidable" by re-asking at fewer slots -- a higher probe can only+ # make it fail, and its failure is all-or-nothing: no reduction and+ # --fit on, so the load keeps the slot count it could not afford and+ # offloads anyway. Measured on a 12 GiB card, probing at 8192 instead+ # of the floor moves the hybrid 10,900-11,100 MiB and dense+ # 9,800-10,500 MiB bands from fully GPU-resident to host offload, the+ # ~3x decode collapse (#6718) this whole block was written to avoid.+ #+ # An explicit context is the exception: it launches verbatim, so the+ # search has to be priced at the context that will actually run or the+ # slot count it picks is one the card cannot hold.+ #+ # _FIT_MIN_CTX rather than a literal: _largest_ctx below starts its+ # binary search at the same floor, and the two must agree or the+ # search can pick a slot count the re-fit then refuses to confirm.+ _reduce_ctx = (+ effective_ctx if explicit_ctx else min(effective_ctx, _FIT_MIN_CTX)+ )# Slot-independent footprint (folded compute buffer and the MTP# reserve swapped out so the helper re-prices both per candidate)._base_footprint = (- model_size_fit - _compute_buffer_pipeline + _cc_bytes(effective_ctx)+ model_size_fit - _compute_buffer_pipeline + _cc_bytes(_reduce_ctx))_gi_slots, _uf_slots, _slots = self._slots_that_fit_on_gpu(n_parallel,- effective_ctx,+ _reduce_ctx,gpus,total_by_idx,_base_footprint,cache_type_kv,_pin_fraction,- _pipeline_overhead_bytes + _cc_bytes(effective_ctx),+ _pipeline_overhead_bytes + _cc_bytes(_reduce_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(effective_ctx),+ split_extra_bytes = _cc_split_extra(_reduce_ctx),ubatch_for_slots = _ubatch_for_slots,- mtp_bytes_for_slots = lambda s, ub: _mtp_bytes(effective_ctx, s, ub),+ mtp_bytes_for_slots = lambda s, ub: _mtp_bytes(_reduce_ctx, s, ub),ctx_checkpoints = _effective_ctx_checkpoints,)if not _uf_slots:@@ -17884,8 +17910,8 @@ class LlamaCppBackend:is not always the one that binds it, and a GGUF with nonative length would arrive with the 0 sentinel and searchnothing."""- _native = self._context_length or effective_ctx- _lo = max(1, min(4096, _native) // 256)+ _native = self._context_length or _reduce_ctx+ _lo = max(1, min(_FIT_MIN_CTX, _native) // 256)_hi = _native // 256_best = Nonewhile _lo <= _hi:@@ -17904,18 +17930,22 @@ class LlamaCppBackend:_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,- )+ # Explicit contexts are never rewritten. Otherwise the re-fit is+ # the answer, in both directions: it is the largest context the+ # FINAL slot count holds on the cards the reduction chose, so+ # taking anything else launches a context that was never priced.+ # Not gated on it being an increase over effective_ctx -- that+ # gate was safe only while the search and effective_ctx shared a+ # value, and _AUTO_OFFLOAD_CTX above the probe floor is exactly+ # the case where the re-fit legitimately comes back lower.+ if _refit is not None and not explicit_ctx:+ if _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.@@ -17934,7 +17964,14 @@ class LlamaCppBackend:_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])+ # Replaces the anchor rather than raising it. Reaching here+ # means the offload fallback set max_available_ctx for a plan+ # this block just superseded, and max() would keep publishing+ # that plan's number: with _AUTO_OFFLOAD_CTX above what the+ # final slot count holds, the sheet would advertise a context+ # the launched plan cannot serve, which is the same ceiling /+ # selection inversion #9492 removed, pointing the other way.+ max_available_ctx = _ceiling[0]# Pass the final slot and micro-batch values instead of the defaults# captured before slot reduction.diff --git a/studio/backend/tests/test_compute_buffer.py b/studio/backend/tests/test_compute_buffer.pyindex 34e91b5b53d..7f8d7fc2c1a 100644--- a/studio/backend/tests/test_compute_buffer.py+++ b/studio/backend/tests/test_compute_buffer.py@@ -1184,16 +1184,38 @@ class TestSplitRateRecheckAfterSelection:# 4096 ctx: the 18 MiB of extra masks changes no decision.assert self._pin(40_000, 2, ctx = 4096) == self._pin(40_000, 2, recheck = False, ctx = 4096)- def test_wired_into_both_call_sites(self):+ def test_wired_into_every_call_site(self):+ import astimport inspect-- 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+ import re+ import textwrap++ source = inspect.getsource(LlamaCppBackend.load_model)+ load = "".join(source.split())+ # Read the call sites out of the parse tree. Counting spellings said the same+ # thing while it lasted, but it also reddened on a rename that changed nothing+ # about the rule: the three sites price at three different contexts and the+ # names they use for them are not the contract.+ wired = [+ ast.unparse(keyword.value)+ for node in ast.walk(ast.parse(textwrap.dedent(source)))+ if isinstance(node, ast.Call)+ for keyword in node.keywords+ if keyword.arg == "split_extra_bytes"+ ]+ # Projector floor pin, explicit-context pin, reduced-slot retry, per-candidate+ # re-fit. A fifth has to come here and say which context it prices at.+ #+ # Four, not the three the counting version asserted. It counted two spellings,+ # `_cc_split_extra(effective_ctx)` and `_cc_split_extra(ctx),`, and the+ # projector-floor site spells its context `_mm_floor_ctx`, so it was invisible+ # to the check that claimed to cover every call site. It has been wired+ # correctly the whole time; nothing was holding it there.+ assert len(wired) == 4, wired+ # Each passes the step at a context of its own, so none is exempt and none+ # hardcodes one: `_cc_split_extra(4096)` would not match.+ for expression in wired:+ assert re.fullmatch(r"_cc_split_extra\(\w+\)", expression), expressionassert "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 loaddiff --git a/studio/backend/tests/test_slot_reduction_context_refit.py b/studio/backend/tests/test_slot_reduction_context_refit.pyindex 261f83854b5..814a3bd9d2f 100644--- a/studio/backend/tests/test_slot_reduction_context_refit.py+++ b/studio/backend/tests/test_slot_reduction_context_refit.py@@ -19,6 +19,7 @@ if _TESTS_DIR not in sys.path:import pytest # noqa: E402+import core.inference.llama_cpp as llama_cpp # noqa: E402from test_llama_cpp_placement import _backend, _launch # noqa: E402MIB = 1024 * 1024@@ -206,8 +207,13 @@ class TestWhatMustNotMove: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)+ # The launched context stays a literal: honouring the request verbatim IS the+ # contract, so a derived value here would assert nothing.assert (got["ctx"], got["slots"], got["fit"]) == (32768, 4, "on")- assert got["ceiling"] == 4096+ # The ceiling is the published safe zone, which no reduction reached, so it is+ # the offload fallback. Tracks the constant; #9492 moved it 4096 -> 8192.+ assert got["ceiling"] == min(llama_cpp._AUTO_OFFLOAD_CTX, NATIVE_CTX)+ assert got["ceiling"] < got["ctx"], "the sheet must still warn above the safe zone"def test_a_count_that_needs_no_reduction_is_untouched(self, tmp_path):"""A plan that needs no slot reduction is unchanged."""@@ -215,9 +221,20 @@ class TestWhatMustNotMove: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."""+ """Oversized weights still fall back to offload, at the Auto offload context.++ The one case in this file that reads the constant rather than the reduction:+ no slot count places these weights, so the block below never fires and the+ context is the fallback itself. Tracked rather than hardcoded, since #9492+ moved it from 4096 to 8192 and a literal here is a re-edit every time.+ """got = _plan(tmp_path, weights_mib = 11_400, n_parallel = 4, spec = "off")- assert (got["fit"], got["ctx"], got["ceiling"]) == ("on", 4096, 4096)+ offload_ctx = min(llama_cpp._AUTO_OFFLOAD_CTX, NATIVE_CTX)+ assert (got["fit"], got["ctx"], got["ceiling"]) == ("on", offload_ctx, offload_ctx)+ # The case is still the one this name claims: nothing was rescued, and the+ # native length really was cut down to the fallback.+ assert got["slots"] == 4, "the reduction fired; this is no longer the offload case"+ assert got["ctx"] < NATIVE_CTX@pytest.mark.parametrize("weights_mib,slots,ctx",@@ -232,6 +249,80 @@ class TestWhatMustNotMove:assert (got["slots"], got["ctx"]) == (slots, ctx)+class TestTheReductionIsPricedAtTheFitFloor:+ """The search that picks the slot count must not be priced at _AUTO_OFFLOAD_CTX.++ That constant is what Auto settles for once offload is unavoidable. This block+ exists to overturn that verdict by re-asking at fewer slots, so a higher probe+ context can only make the search fail -- and its failure is all-or-nothing: no+ reduction, `--fit on`, and the slot count kept at the ask it could not afford.++ #9492 raised the constant 4096 -> 8192 and, through this one shared read, moved+ placement. The arithmetic, on the 12 GiB card these tests use (budget+ 12288 x 0.97 = 11,919.36 MiB) at 10,200 MiB of weights: the candidates are+ 707 MiB apart (557.75 MiB of per-slot compute buffer plus 149.625 MiB of per-slot+ Mamba state), while probing 256 tokens higher costs a uniform 64 KiB/token. The+ 2-slot candidate is 11,685.0 MiB at 4096 and 11,947.0 MiB at 8192, so a display+ constant moved it across the budget by 27.6 MiB.+ """++ # A band that a reduction rescues from offload. Every one of these launched+ # `--fit off` before #9492 and `--fit on` after it, which is the ~3x decode+ # collapse (#6718) the reduction was written to avoid.+ RESCUED = [+ (10_900, HYBRID),+ (11_000, HYBRID),+ (11_100, HYBRID),+ (9_800, DENSE),+ (10_000, DENSE),+ (10_500, DENSE),+ ]++ @pytest.mark.parametrize("offload_ctx", [4096, 8192, 16384, 32768])+ def test_moving_the_offload_fallback_does_not_move_the_placement(+ self, tmp_path, monkeypatch, offload_ctx+ ):+ """Sweeping the constant leaves slots, residency, context and cards alone.++ Pinned against the sweep rather than against one value, so this cannot be+ satisfied by re-baselining the constant into the expectation.+ """+ monkeypatch.setattr(llama_cpp, "_AUTO_OFFLOAD_CTX", offload_ctx)+ got = _plan(tmp_path, weights_mib = 10_200, n_parallel = 4, spec = "off")+ assert (got["slots"], got["fit"], got["ctx"], got["devices"]) == (2, "off", 7_680, "0")++ @pytest.mark.parametrize("weights_mib,metadata", RESCUED)+ @pytest.mark.parametrize("offload_ctx", [4096, 8192])+ def test_a_load_the_reduction_can_rescue_never_offloads(+ self, tmp_path, monkeypatch, weights_mib, metadata, offload_ctx+ ):+ monkeypatch.setattr(llama_cpp, "_AUTO_OFFLOAD_CTX", offload_ctx)+ got = _plan(tmp_path, weights_mib = weights_mib, n_parallel = 4, spec = "off", metadata = metadata)+ assert got["fit"] == "off", "a placeable load was handed to --fit offload"+ # It was rescued BY the reduction rather than fitting outright, or the row+ # would prove nothing about this block.+ assert got["slots"] < 4++ def test_weights_past_the_band_still_offload(self, tmp_path):+ """The counterweight: the rows above are not green because everything is.++ Without this, RESCUED could drift into sizes that place at the full ask and+ the assertions there would hold for the wrong reason.+ """+ got = _plan(tmp_path, weights_mib = 11_400, n_parallel = 4, spec = "off")+ assert (got["fit"], got["slots"]) == ("on", 4)++ def test_asking_for_more_slots_never_returns_fewer(self, tmp_path):+ """Monotone in the ask. At head, asking for 2 got 2 and asking for 3 got 1."""+ finals = [+ _plan(tmp_path, weights_mib = 10_200, n_parallel = n, spec = "off")["slots"]+ for n in (1, 2, 3, 4, 6, 8)+ ]+ assert finals == sorted(finals), finals+ # Not a row of identical numbers, which would sort trivially.+ assert len(set(finals)) > 1, finals++class TestTheSearchPredicate:def test_include_requested_answers_for_the_count_itself(self):"""The helper can test the requested slot count itself."""