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
Studio: report confirmed explicit GGUF context (#9713)
Doud-FR5449d35eda8e
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.pyindex 35af433050b..eb3054b9b9c 100644--- a/studio/backend/core/inference/llama_cpp.py+++ b/studio/backend/core/inference/llama_cpp.py@@ -21906,7 +21906,9 @@ class LlamaCppBackend:# Clear first, or a swap into a model without video inherits# the previous server's answer.self._has_video_input = False- self._reconcile_effective_ctx_with_server()+ # The explicit override, not the field fallback: only a flag after+ # Studio's own -c can allocate past the fit, so it is the ceiling.+ self._reconcile_effective_ctx_with_server(ctx_override or 0)if self._kv_cache_context_total is not None:self._n_ubatch = min(self._n_ubatch,@@ -24517,28 +24519,56 @@ class LlamaCppBackend:n_ctx = settings.get("n_ctx")return int(n_ctx) if n_ctx else None- def _reconcile_effective_ctx_with_server(self) -> None:- """Adopt the server's real ``n_ctx`` when it is below Unsloth's value.+ def _reconcile_effective_ctx_with_server(self, requested_n_ctx: int = 0) -> None:+ """Adopt the server's real ``n_ctx`` within an explicit requested ceiling.Keeps ``context_length`` (load response, status route, passthrough``max_tokens`` ceiling) honest; clients sized to the requested value- would otherwise hit ``exceed_context_size_error`` 400s early.+ would otherwise hit ``exceed_context_size_error`` 400s early. A trailing+ pass-through ``--ctx-size`` can also make the server larger than Studio's+ pre-launch VRAM-fit estimate; publish that confirmed allocation without+ advertising beyond the user's resolved explicit request.++ ``requested_n_ctx`` is the EXPLICIT pass-through override (0 when absent),+ not ``resolve_requested_ctx``'s field fallback: only a flag emitted after+ Studio's own ``-c`` can allocate past the fit, so gating on the flag keeps+ llama.cpp's context padding from being published as an override that does+ not exist.++ ``_max_context_length`` deliberately stays put: /props confirms what was+ ALLOCATED, not that it fits VRAM without spilling, so the "may use system+ RAM" warning is right and ``max_context_length < context_length`` is legal."""actual_n_ctx = self._query_server_n_ctx()if not actual_n_ctx or actual_n_ctx <= 0:returnslots = 1 if self._kv_cache_unified else self.effective_parallel_slotsself._kv_cache_context_total = actual_n_ctx * slots- if self._effective_context_length and actual_n_ctx < self._effective_context_length:+ effective_n_ctx = self._effective_context_length+ if not effective_n_ctx:+ # Same ceiling as the raise below, or a missing seed would advertise+ # past the explicit request.+ self._effective_context_length = (+ min(actual_n_ctx, requested_n_ctx) if requested_n_ctx > 0 else actual_n_ctx+ )+ return+ if actual_n_ctx < effective_n_ctx:logger.warning("llama-server allocated a smaller per-request context than "- f"requested ({self._effective_context_length} -> {actual_n_ctx}; "+ f"requested ({effective_n_ctx} -> {actual_n_ctx}; ""memory fit or --parallel slot split); clients must treat "f"{actual_n_ctx} as the real context window.")self._effective_context_length = actual_n_ctx- elif not self._effective_context_length:- self._effective_context_length = actual_n_ctx+ return+ if requested_n_ctx > effective_n_ctx:+ confirmed_n_ctx = min(actual_n_ctx, requested_n_ctx)+ if confirmed_n_ctx > effective_n_ctx:+ logger.info(+ "llama-server confirmed a larger per-request context from "+ f"the explicit override ({effective_n_ctx} -> {confirmed_n_ctx})."+ )+ self._effective_context_length = confirmed_n_ctx# ── Message building (OpenAI format) ──────────────────────────diff --git a/studio/backend/core/inference/llama_server_args.py b/studio/backend/core/inference/llama_server_args.pyindex 900cb5a42a4..0fe84b7f0da 100644--- a/studio/backend/core/inference/llama_server_args.py+++ b/studio/backend/core/inference/llama_server_args.py@@ -16,7 +16,7 @@ from __future__ import annotationsimport loggingimport osimport sys-from typing import Iterable, Mapping, Optional+from typing import Any, Iterable, Mapping, Optionallogger = logging.getLogger(__name__)@@ -745,6 +745,29 @@ def resolve_requested_ctx(args: Optional[Iterable[str]], fallback_n_ctx: int) ->return override if override is not None else fallback_n_ctx+def matches_explicit_ctx_override(args: Optional[Iterable[str]], n_ctx: Any) -> bool:+ """Whether a pass-through ``-c``/``--ctx-size`` matches the context the caller+ is already sending as a first-class field.++ Context is the one first-class field whose load-time value is a VRAM-fit+ TARGET, so a matching flag is not a stale shadow but the user's standing+ decision to run past the estimated threshold. Both strippers ask here rather+ than mirroring the test, so auto-switch and /load inheritance cannot drift.++ False for anything unconfirmable, which is the pre-existing strip: no flag, a+ malformed one, or a non-positive/non-int ``n_ctx``. That last case is real --+ override rows are coerced on write but returned verbatim on read, so a row+ from an older build can hold any JSON type and must not raise here.+ """+ if isinstance(n_ctx, bool) or not isinstance(n_ctx, int) or n_ctx <= 0:+ return False+ try:+ return parse_ctx_override(args) == n_ctx+ except ValueError:+ # Malformed extras are refused at the boundary; this must not raise here.+ return False++def _last_flag_value(args: Optional[Iterable[str]], flags: frozenset[str]) -> Optional[str]:"""Return the last-wins string value among ``flags`` in extras, or None.diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex 8fe0a716cf2..109bbaf6b03 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -9500,9 +9500,18 @@ def _resolve_inherited_extra_args(# so strip the inherited --chat-template-file then too -- else the stale arg# (appended last) shadows the bundled template while Unsloth reports its caps.fields_set = getattr(request, "model_fields_set", set())+ # A MATCHING inherited -c/--ctx-size is the user's opt-in to exceed the+ # VRAM-fit estimate, so it survives here as it does on auto-switch.+ # Stripping it relaunched an Apply at the fit estimate, silently collapsing+ # the confirmed context while the stored override still said otherwise.+ from core.inference.llama_server_args import matches_explicit_ctx_override+stripped = strip_shadowing_flags(stored_args,- strip_context = "max_seq_length" in fields_set,+ strip_context = "max_seq_length" in fields_set+ and not matches_explicit_ctx_override(+ stored_args, getattr(request, "max_seq_length", None)+ ),strip_cache = "cache_type_kv" in fields_set,strip_spec = ("speculative_type" in fields_set or "spec_draft_n_max" in fields_set),strip_template = (diff --git a/studio/backend/tests/test_llama_cpp_props_readback.py b/studio/backend/tests/test_llama_cpp_props_readback.pyindex f5831e59830..e79e45170d6 100644--- a/studio/backend/tests/test_llama_cpp_props_readback.py+++ b/studio/backend/tests/test_llama_cpp_props_readback.py@@ -230,10 +230,49 @@ def test_larger_server_ctx_does_not_inflate_advertised_value(monkeypatch):monkeypatch,body = {"default_generation_settings": {"n_ctx": 65536}},)- inst._reconcile_effective_ctx_with_server()+ inst._reconcile_effective_ctx_with_server(requested_n_ctx = 32768)assert inst._effective_context_length == 32768+def test_explicit_extra_arg_ctx_adopts_larger_confirmed_server_value(monkeypatch):+ """A trailing --ctx-size can override Studio's earlier VRAM-fit ``-c``.++ The resolved explicit request is 100352, Studio's pre-launch estimate is+ 65983, and /props confirms that llama-server actually allocated 100352.+ Publish the real window while retaining the VRAM warning threshold.+ """+ inst = _make_backend(effective_ctx = 65983)+ inst._max_context_length = 65983+ _stub_props(+ monkeypatch,+ body = {"default_generation_settings": {"n_ctx": 100352}},+ )++ inst._reconcile_effective_ctx_with_server(requested_n_ctx = 100352)++ assert inst._effective_context_length == 100352+ assert inst.context_length == 100352+ assert inst.max_context_length == 65983+++def test_no_explicit_flag_never_adopts_a_larger_server_value(monkeypatch):+ """The ceiling is the pass-through flag, not the first-class field.++ Only a --ctx-size emitted after Studio's own -c can make the child allocate+ past the fit, so a load with no flag passes 0 and llama.cpp's own context+ padding cannot be reported as an override the user never wrote.+ """+ inst = _make_backend(effective_ctx = 65983)+ _stub_props(+ monkeypatch,+ body = {"default_generation_settings": {"n_ctx": 66048}},+ )++ inst._reconcile_effective_ctx_with_server(requested_n_ctx = 0)++ assert inst._effective_context_length == 65983++def test_unset_effective_ctx_adopts_server_value(monkeypatch):inst = _make_backend(effective_ctx = None)inst._context_length = None@@ -245,6 +284,20 @@ def test_unset_effective_ctx_adopts_server_value(monkeypatch):assert inst._effective_context_length == 40960+def test_unset_effective_ctx_still_honours_the_explicit_ceiling(monkeypatch):+ """The unset arm publishes too, so the same ceiling has to bind there."""+ inst = _make_backend(effective_ctx = None)+ inst._context_length = None+ _stub_props(+ monkeypatch,+ body = {"default_generation_settings": {"n_ctx": 8192}},+ )++ inst._reconcile_effective_ctx_with_server(requested_n_ctx = 4096)++ assert inst._effective_context_length == 4096++def test_props_failure_keeps_studio_value(monkeypatch):"""A flaky /props must never wipe the computed context."""inst = _make_backend(effective_ctx = 98304)diff --git a/studio/backend/tests/test_llama_extra_args_compatibility.py b/studio/backend/tests/test_llama_extra_args_compatibility.pyindex b7a0473800d..665654dd598 100644--- a/studio/backend/tests/test_llama_extra_args_compatibility.py+++ b/studio/backend/tests/test_llama_extra_args_compatibility.py@@ -167,6 +167,73 @@ def test_the_inherited_load_path_drops_only_the_denied_flag(monkeypatch):assert resolved == ["--numa", "distribute"]+def _inherit_with_ctx_flag(monkeypatch, stored, fields_set, max_seq_length):+ """Drive the real resolver for a same-model reload that inherits its extras."""+ import routes.inference as inference_route++ class _Backend:+ extra_args = list(stored)+ extra_args_source = ("local/x", "")++ class _Config:+ is_gguf = True+ gguf_variant = ""++ class _Request:+ llama_extra_args = None+ gguf_variant = ""+ gpu_memory_mode = "auto"+ model_fields_set = set(fields_set)++ _Request.max_seq_length = max_seq_length+ monkeypatch.setattr(inference_route, "get_llama_cpp_backend", lambda: _Backend())+ return inference_route._resolve_inherited_extra_args(_Request(), _Config(), "local/x", None)+++def test_a_matching_inherited_ctx_flag_survives_an_apply(monkeypatch):+ """The opt-in has to be durable, or the PR's own fix undoes itself.++ An Apply that re-sends the SAME Context Length is not a fresh save that the+ stored flag would outrank -- it is the same decision, and stripping it here+ relaunched at the VRAM-fit estimate while the stored override still said+ otherwise. Mirrors model_override_load_kwargs on the API auto-switch path;+ both ask matches_explicit_ctx_override so the two cannot drift.+ """+ stored = ["--ctx-size", "100352", "--top-k", "40"]++ assert _inherit_with_ctx_flag(monkeypatch, stored, {"max_seq_length"}, 100352) == [+ "--ctx-size",+ "100352",+ "--top-k",+ "40",+ ]++ # And still stripped alongside another set field, which was the reachable gap.+ assert _inherit_with_ctx_flag(+ monkeypatch, stored, {"max_seq_length", "cache_type_kv"}, 100352+ ) == ["--ctx-size", "100352", "--top-k", "40"]+++def test_a_stale_inherited_ctx_flag_still_loses_to_a_fresh_context(monkeypatch):+ """Only a MATCHING value is the opt-in; a different one is a stale shadow."""+ stored = ["--ctx-size", "8192", "--top-k", "40"]++ assert _inherit_with_ctx_flag(monkeypatch, stored, {"max_seq_length"}, 32768) == [+ "--top-k",+ "40",+ ]+++def test_a_malformed_inherited_ctx_flag_is_stripped_not_raised(monkeypatch):+ """parse_ctx_override raises on a flag with no value; a load must not."""+ stored = ["--ctx-size", "--top-k", "40"]++ assert _inherit_with_ctx_flag(monkeypatch, stored, {"max_seq_length"}, 32768) == [+ "--top-k",+ "40",+ ]++def test_the_override_save_carries_over_without_refusing(monkeypatch):# A user changing Context Length on a model whose stored flags predate the# denylist must not get a 400 about a flag they are not editing.diff --git a/studio/backend/tests/test_llama_server_args.py b/studio/backend/tests/test_llama_server_args.pyindex f6d7012f800..6c468d0d3a4 100644--- a/studio/backend/tests/test_llama_server_args.py+++ b/studio/backend/tests/test_llama_server_args.py@@ -1217,3 +1217,37 @@ def test_the_projector_env_twins_survive_the_scrub():)def test_memory_env_selects_load_mode(env, expected):assert _lsa.memory_env_selects_load_mode(env) is expected+++# --- the shared "is this ctx flag the user's opt-in?" test ----------------------+# Both stripping paths (model_override_load_kwargs on the API auto-switch, and+# _resolve_inherited_extra_args on /load) ask this one function, so a value that+# survives one reload survives the other.+++def test_matching_ctx_override_confirms_only_an_exact_positive_int():+ assert _lsa.matches_explicit_ctx_override(["--ctx-size", "100352"], 100352)+ assert _lsa.matches_explicit_ctx_override(["-c", "100352"], 100352)+ # llama.cpp folds the underscore spelling, and so does the matcher.+ assert _lsa.matches_explicit_ctx_override(["--ctx_size", "100352"], 100352)+ # Last-wins, exactly as the launch parses it.+ assert _lsa.matches_explicit_ctx_override(+ ["--ctx-size", "8192", "--ctx-size", "100352"], 100352+ )+ assert not _lsa.matches_explicit_ctx_override(+ ["--ctx-size", "100352", "--ctx-size", "8192"], 100352+ )+ # A different value is a stale shadow, not an opt-in.+ assert not _lsa.matches_explicit_ctx_override(["--ctx-size", "8192"], 100352)+ assert not _lsa.matches_explicit_ctx_override(["--top-k", "40"], 100352)+ assert not _lsa.matches_explicit_ctx_override(None, 100352)+++def test_matching_ctx_override_is_total_over_stored_junk():+ # Override rows are coerced on write but returned verbatim on read, so this is+ # reached with whatever JSON an older build, the API or a hand edit left behind.+ # None of it may raise inside a load, and none of it counts as confirmed.+ for n_ctx in (None, 0, -1, "100352", "", "x", 100352.0, True, False, [100352], {"v": 1}):+ assert not _lsa.matches_explicit_ctx_override(["--ctx-size", "100352"], n_ctx), n_ctx+ # A malformed flag raises in parse_ctx_override; the matcher answers False.+ assert not _lsa.matches_explicit_ctx_override(["--ctx-size", "--top-k"], 100352)diff --git a/studio/backend/tests/test_openai_auto_switch.py b/studio/backend/tests/test_openai_auto_switch.pyindex 9a84af06d1d..627f2c47cd1 100644--- a/studio/backend/tests/test_openai_auto_switch.py+++ b/studio/backend/tests/test_openai_auto_switch.py@@ -6018,6 +6018,78 @@ def test_a_carried_ctx_flag_cannot_outrank_a_freshly_saved_context(monkeypatch):assert request.llama_extra_args == ["--top-k", "40"]+def test_a_matching_explicit_ctx_flag_survives_auto_switch(monkeypatch):+ """A matching stored flag is the opt-in that bypasses the VRAM-fit ceiling."""+ _mock_override_store(monkeypatch)+ _put(+ "unsloth/B-GGUF:Q4_K_M",+ llama_extra_args = ["--ctx-size", "100352", "--spec-draft-n-max", "3"],+ custom_context_length = 100352,+ speculative_type = "mtp",+ spec_draft_n_max = 3,+ )++ backend = _FakeBackend(None)+ rec = _LoadRecorder(backend)+ _wire(+ monkeypatch,+ enabled = True,+ resolves_to = ("unsloth/B-GGUF", "Q4_K_M", "unsloth/B-GGUF"),+ backend = backend,+ recorder = rec,+ )++ _run_hook("unsloth/B-GGUF")+ request = rec.calls[0]+ assert request.max_seq_length == 100352+ # The matching context opt-in survives. The redundant speculative flag is+ # still stripped because its first-class fields are unconditional.+ assert request.llama_extra_args == ["--ctx-size", "100352"]+++ "stored_max_seq_length",+ ["100352", "not-a-number", 100352.0, True, [100352], {"v": 100352}],+)+def test_a_legacy_override_row_cannot_break_the_loader(stored_max_seq_length):+ """Rows are coerced on write but returned verbatim on read (get_model_overrides),+ so an entry written by an older build, by hand or through the API can hold any+ JSON type. Comparing the context against one must degrade, never raise: a raise+ here fails every auto-switch load of that model with a 500 the user cannot clear.+ A value that is not a plain positive int cannot be confirmed as matching, so the+ shadowing flag is stripped exactly as it was before the opt-in existed.+ """+ from utils.openai_auto_switch_settings import model_override_load_kwargs++ out = model_override_load_kwargs(+ {+ "llama_extra_args": ["--ctx-size", "100352", "--top-k", "40"],+ "max_seq_length": stored_max_seq_length,+ },+ is_gguf = True,+ )+ assert "--ctx-size" not in out["llama_extra_args"]+ assert "--top-k" in out["llama_extra_args"]++[email protected]("stored_max_seq_length", ["", False, None, 0])+def test_a_falsy_legacy_context_leaves_the_flag_as_the_only_control(stored_max_seq_length):+ """These resolve to "no context field sent", so there is nothing to shadow and+ the pass-through flag stays the user's only way to set the knob -- the same+ answer this path gave before the opt-in existed.+ """+ from utils.openai_auto_switch_settings import model_override_load_kwargs++ out = model_override_load_kwargs(+ {+ "llama_extra_args": ["--ctx-size", "100352", "--top-k", "40"],+ "max_seq_length": stored_max_seq_length,+ },+ is_gguf = True,+ )+ assert out["llama_extra_args"] == ["--ctx-size", "100352", "--top-k", "40"]++def test_load_kwargs_strip_only_the_shadow_groups_the_override_supplies():# Same rule the /load route applies to inherited extras: one group per first-class# field actually being sent, so a flag with nothing to shadow still passes through.diff --git a/studio/backend/utils/openai_auto_switch_settings.py b/studio/backend/utils/openai_auto_switch_settings.pyindex f29607e5a9f..72eff7e5ef0 100644--- a/studio/backend/utils/openai_auto_switch_settings.py+++ b/studio/backend/utils/openai_auto_switch_settings.py@@ -721,13 +721,26 @@ def model_override_load_kwargs(override: dict[str, Any], *, is_gguf: bool) -> di# (_resolve_inherited_extra_args); the stripper is imported rather than mirrored so# the two paths cannot drift over which flag belongs to which group -- the allow-list# this module stays out of is validate_extra_args, which remains the caller's job.- from core.inference.llama_server_args import strip_shadowing_flags+ from core.inference.llama_server_args import (+ matches_explicit_ctx_override,+ strip_shadowing_flags,+ )++ # Context's load-time value is a VRAM-fit target, not an allocation, so a+ # MATCHING -c/--ctx-size is the user's opt-in to exceed the safe threshold+ # and survives; /props then publishes what was really allocated. Stale and+ # malformed flags are still stripped. The test lives beside the stripper+ # because /load's inheritance path asks it too and must not drift.+ matching_explicit_ctx = matches_explicit_ctx_override(+ kwargs["llama_extra_args"], kwargs.get("max_seq_length")+ )+kwargs["llama_extra_args"] = strip_shadowing_flags(kwargs["llama_extra_args"],# Only the groups this override actually supplies, as the route gates on its# request's set fields: a flag with no first-class field behind it is the user's# only way to set that knob and still passes through.- strip_context = "max_seq_length" in kwargs,+ strip_context = "max_seq_length" in kwargs and not matching_explicit_ctx,strip_cache = "cache_type_kv" in kwargs,strip_spec = "speculative_type" in kwargs or "spec_draft_n_max" in kwargs,strip_template = "chat_template_override" in kwargs,