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: improve Auto context selection and share remembered model settings (#9492)

oobabooga1f475d7f11bf
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.py
index c05e63240bd..b855a384f49 100644
--- a/studio/backend/core/inference/llama_cpp.py
+++ b/studio/backend/core/inference/llama_cpp.py
@@ -2821,6 +2821,27 @@ _APPLE_UNIFIED_MEMORY_FRACTION = 0.85
_FIT_MIN_CTX = 4096
_FIT_FLOOR_MIN_CTX = 256
+# Auto only reaches this path when no discrete-GPU subset can hold the model.
+# llama.cpp must offload layers to host RAM either way, so prefer a context that
+# remains useful for chat. Separate from _FIT_MIN_CTX: that value is also a search
+# and Apple unified-memory safety floor.
+_AUTO_OFFLOAD_CTX = 8192
+
+# Keep this at or above the fit search floor. Not a style rule, a correctness one:
+# the Auto offload branch re-checks whether a subset holds the model at the reduced
+# context, and that re-check can only award residency BELOW the floor, since a subset
+# winnable at or above it was already taken by the fit loop that runs first. Moving
+# this constant is therefore free of placement changes only while it stays on the dead
+# side of that floor. Below it the re-check hands over a device and flips --fit off,
+# which is a placement decision rather than a display one.
+#
+# The floor in question is the ``min_ctx = 4096`` DEFAULT on _fit_context_to_vram and
+# _cap_ctx_to_per_device_reserve, not _FIT_MIN_CTX: neither auto call site passes the
+# argument, and _FIT_MIN_CTX is only handed in explicitly on the Apple arm. The three
+# numbers agree today and nothing here makes them; test_auto_offload_ctx_invariants.py
+# pins both defaults to _FIT_MIN_CTX and this constant above it, so the agreement
+# cannot lapse silently.
+
# How far amd-smi's total VRAM may sit from HIP's before the two are reporting
# different memory scopes rather than one pool (an APU carve-out against the GTT
# pool, a partition against the whole card). Same 10% margin
@@ -16814,7 +16835,12 @@ class LlamaCppBackend:
#
# AUTO gets the FLOOR, which makes this a residency question and
# not a context one. Auto shrinks the CONTEXT before it spills
- # layers, reaching `--fit on` only once even 4096 will not place.
+ # layers, reaching `--fit on` only once even _FIT_MIN_CTX will
+ # not place -- and then RAISES the context to _AUTO_OFFLOAD_CTX,
+ # since offload is already unavoidable by that point. So this
+ # floor is deliberately the residency floor and not the context
+ # the load ends up running at; the projector's bytes are charged
+ # again at the real context through _subset_model_size below.
# Pricing at the native length would answer "does not fit" for a
# load merely heading for a smaller context and pin a projector
# that was resident all along -- 8.8x on image encode for nothing.
@@ -17409,9 +17435,15 @@ class LlamaCppBackend:
max_available_ctx = best_cap
else:
# Weights exceed 90% of every GPU subset, so no
- # context fits. Anchor the UI "safe zone" at 4096
- # so the slider warns above the fallback.
- max_available_ctx = min(4096, native_ctx_for_cap)
+ # context fits. Anchor the UI "safe zone" at the
+ # Auto offload fallback so the slider warns ABOVE
+ # what Auto itself selects: anchoring below it
+ # makes every Auto load in this branch exceed its
+ # own published ceiling, and the chat sheet reads
+ # that as "context exceeds the estimated VRAM
+ # capacity" while advising the user to leave it
+ # on Auto.
+ max_available_ctx = min(_AUTO_OFFLOAD_CTX, native_ctx_for_cap)
if explicit_ctx:
# Honor the requested context verbatim. If it fits,
@@ -17529,10 +17561,10 @@ class LlamaCppBackend:
use_fit = False
break
else:
- # Native ctx doesn't fit. Drop to 4096 and
- # re-check before --fit on: a model overflowing
- # at 131k may pin fine with a 4096 KV (#5106).
- effective_ctx = min(4096, effective_ctx)
+ # No discrete-GPU subset holds the model at a fitted
+ # context. Prefer a useful chat context before
+ # handing placement to --fit on and host offload.
+ effective_ctx = min(_AUTO_OFFLOAD_CTX, effective_ctx)
if effective_ctx > 0:
for n_gpus in range(_auto_min_gpus, len(ranked) + 1):
subset = ranked[:n_gpus]
@@ -17578,9 +17610,13 @@ class LlamaCppBackend:
min_gpus = _layer_min_gpus,
)
if use_fit and not explicit_ctx:
- # Weights don't fit on any subset; default UI to 4096
- # so the slider isn't on an unusable native ctx.
- effective_ctx = min(4096, effective_ctx) if effective_ctx > 0 else 4096
+ # Without KV metadata, llama.cpp owns the fit. Keep the
+ # same useful Auto default as the measured offload path.
+ effective_ctx = (
+ min(_AUTO_OFFLOAD_CTX, effective_ctx)
+ if effective_ctx > 0
+ else _AUTO_OFFLOAD_CTX
+ )
elif _apple_budget_mib > 0 and effective_ctx > 0:
# No GPU on Metal: the branches above are skipped and the context
diff --git a/studio/backend/routes/settings.py b/studio/backend/routes/settings.py
index 785a2c37603..af40fbd6b52 100644
--- a/studio/backend/routes/settings.py
+++ b/studio/backend/routes/settings.py
@@ -66,6 +66,9 @@ from utils.vram_budget_settings import (
from utils.openai_auto_switch_settings import (
BATCH_SIZE_MAX,
BATCH_SIZE_MIN,
+ CACHE_RAM_MAX_MIB,
+ CACHE_RAM_MIN_MIB,
+ CTX_CHECKPOINTS_MAX,
DEFAULT_AUTO_UNLOAD_API_ONLY,
DEFAULT_AUTO_UNLOAD_KEEP_KV,
DEFAULT_MEDIA_AUTO_SWITCH_ENABLED,
@@ -76,6 +79,7 @@ from utils.openai_auto_switch_settings import (
PARALLEL_SLOTS_MAX,
PARALLEL_SLOTS_MIN,
cached_repo_alias_keys,
+ is_cache_load_path_key,
get_auto_unload_api_only,
get_auto_unload_idle_seconds,
get_auto_unload_keep_kv,
@@ -721,6 +725,25 @@ class ModelOverridePayload(BaseModel):
# prompt batch sizes (--batch-size / --ubatch-size), gguf-only; none = llama.cpp defaults
n_batch: Optional[int] = Field(default = None, ge = BATCH_SIZE_MIN, le = BATCH_SIZE_MAX)
n_ubatch: Optional[int] = Field(default = None, ge = BATCH_SIZE_MIN, le = BATCH_SIZE_MAX)
+ # The remaining llama-server tuning the picker remembers. model_override_load_kwargs
+ # already applies all four off a stored row, so a route that drops them leaves the
+ # setting reaching a picker load and nothing else, and the panel reads the gap back
+ # as unset. Load mode is a discrete set, left to the normalizer like the KV dtype.
+ load_mode: Optional[str] = Field(default = None, max_length = 32)
+ spec_draft_cache_type: Optional[str] = Field(default = None, max_length = 32)
+ # Stored on "is not None", not on truth: 0 checkpoints and a 0 or -1 cache are
+ # meaningful values (none kept; cache disabled; no limit). Bounds mirror LoadRequest.
+ ctx_checkpoints: Optional[int] = Field(default = None, ge = 0, le = CTX_CHECKPOINTS_MAX)
+ cache_ram: Optional[int] = Field(default = None, ge = CACHE_RAM_MIN_MIB, le = CACHE_RAM_MAX_MIB)
+ # Does this client know the four above exist? A save REPLACES the entry, so an
+ # omission from a build that predates them is indistinguishable from a user
+ # clearing them, and during an upgrade -- a cached bundle, or another LAN client
+ # still on the old build -- that silently deletes settings it never sent. Only a
+ # client that sets this may clear by omission; for anyone else the stored values
+ # are carried over. Default False so an old payload, which cannot set it, is the
+ # safe case. Not a blanket carry-over: that would make clearing impossible for
+ # everyone, trading a mixed-version window for a permanent bug.
+ mirrors_server_tuning: bool = False
tensor_parallel: bool = False
disable_vision: bool = False
# Validated in bytes below: pydantic counts characters, so a multi-byte template would pass.
@@ -757,6 +780,8 @@ class ModelOverridePayload(BaseModel):
"n_parallel",
"n_batch",
"n_ubatch",
+ "ctx_checkpoints",
+ "cache_ram",
"gpu_layers",
"n_cpu_moe",
"gpu_ids",
@@ -1449,10 +1474,17 @@ def update_openai_auto_switch_override(
raise ValueError("fill_absent_fields cannot be combined with remove.")
# Only model_id is the documented "remove"; otherwise omitted flags carry over.
requested_extra_args = payload.llama_extra_args
- # fill_absent_fields is a write mode, not a saved field: leaving it in would make
- # every payload look non-empty and break the legacy "no fields means remove".
+ # fill_absent_fields and mirrors_server_tuning are write modes, not saved fields:
+ # leaving either in would make every payload look non-empty (they are bools, so
+ # exclude_none does not drop them) and break the legacy "no fields means remove".
saved_fields = payload.model_dump(
- exclude = {"model_id", "llama_extra_args", "remove", "fill_absent_fields"},
+ exclude = {
+ "model_id",
+ "llama_extra_args",
+ "remove",
+ "fill_absent_fields",
+ "mirrors_server_tuning",
+ },
exclude_none = True,
)
if payload.remove is not None:
@@ -1512,6 +1544,51 @@ def update_openai_auto_switch_override(
)
else:
extra_args = validate_extra_args(requested_extra_args)
+ # Same shape as the extra-args carry-over above, for the same reason: a save
+ # replaces the entry, so a field the caller never knew about must survive it.
+ # A client that declares it mirrors these clears by omission as usual; an
+ # older one keeps whatever is stored. On a remove the whole entry goes, so
+ # there is nothing to preserve.
+ # Gated on is_removal, not on payload.remove: the documented legacy contract is a
+ # payload carrying only model_id, which leaves remove None while is_removal is
+ # true. Carrying anything over there would rebuild a non-empty row and the clear
+ # would silently do nothing.
+ _tuning_fields = ("load_mode", "spec_draft_cache_type", "ctx_checkpoints", "cache_ram")
+ _kept_tuning = {name: getattr(payload, name) for name in _tuning_fields}
+ if not payload.mirrors_server_tuning and not is_removal:
+ # The same spellings the extra-args carry-over walks, and in the same order.
+ # A cached repo is not an ordinary folded match, so a save under the repo id
+ # while the row sits under the snapshot path finds nothing here and then
+ # retires that alias below, taking the tuning with it.
+ _alias_ids = [payload.model_id]
+ for _candidate in (
+ _bare_model_id(payload.model_id),
+ _legacy_standalone_gguf_key(payload.model_id),
+ *cached_repo_alias_keys(payload.model_id),
+ ):
+ if _candidate and _candidate not in _alias_ids:
+ _alias_ids.append(_candidate)
+ # Load order, not the order they were collected in. A lookup reads the
+ # concrete load path before the advertised repo id, so on a cache upgraded
+ # from a build that keyed rows by path, the snapshot row is the one that
+ # applies and the one the retirement block below clears. Reading the repo
+ # row first would adopt tuning no load has ever used and drop the tuning
+ # that was live. Stable, so every other spelling keeps its position.
+ _alias_ids.sort(key = lambda _key: not is_cache_load_path_key(_key))
+ # Taken as a unit from the first row that exists, not field by field down
+ # the list. A load stops at the first non-empty row (resolve_override_for_load)
+ # rather than merging, so tuning in a row that never wins is dormant, and
+ # filling a gap in the winner from a loser would switch it on as a side effect
+ # of saving something unrelated. Single-valued above, so the distinction only
+ # shows up here.
+ for _alias_id in _alias_ids:
+ _stored_tuning = get_model_override(_alias_id)
+ if not _stored_tuning:
+ continue
+ for name in _tuning_fields:
+ if _kept_tuning[name] is None:
+ _kept_tuning[name] = _stored_tuning.get(name)
+ break
if payload.remove is True:
# An explicit remove wins over any other field. Remove the key a load resolves to,
# not the literal one sent (the browser normalizes casing), and every spelling:
@@ -1584,6 +1661,10 @@ def update_openai_auto_switch_override(
n_parallel = payload.n_parallel,
n_batch = payload.n_batch,
n_ubatch = payload.n_ubatch,
+ load_mode = _kept_tuning["load_mode"],
+ spec_draft_cache_type = _kept_tuning["spec_draft_cache_type"],
+ ctx_checkpoints = _kept_tuning["ctx_checkpoints"],
+ cache_ram = _kept_tuning["cache_ram"],
tensor_parallel = payload.tensor_parallel,
disable_vision = payload.disable_vision,
chat_template_override = payload.chat_template_override,
diff --git a/studio/backend/tests/test_auto_offload_ctx_fit_floor_coupling.py b/studio/backend/tests/test_auto_offload_ctx_fit_floor_coupling.py
new file mode 100644
index 00000000000..b53aee690b8
--- /dev/null
+++ b/studio/backend/tests/test_auto_offload_ctx_fit_floor_coupling.py
@@ -0,0 +1,232 @@
+# 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 coupling that makes the Auto host-offload context safe for placement.
+
+The failure mode guarded: ``_AUTO_OFFLOAD_CTX`` is read inside the placement
+decision. The measured-KV subset loop falls through to it, lowers the context to
+that value, and then RE-CHECKS whether any GPU subset can hold the model at the
+lower context. That re-check can award residency, so the constant is not merely
+cosmetic -- it is an input to which devices a load pins.
+
+What makes it cosmetic in practice is a coupling that is nowhere written down:
+
+ _AUTO_OFFLOAD_CTX >= the fit helpers' minimum context
+
+The subset loop above the fallback already tried every subset at a context the fit
+helpers floored at that minimum. Footprint is monotone in context, so a subset that
+failed at the floor fails at anything at or above it, and the re-check can only ever
+award below the floor. While the fallback was the literal 4096 the two were the same
+number by accident of spelling. This change gave the fallback a name and left the
+floor as a bare default argument on two helpers, so nothing connects them any more.
+Lower the fallback (or raise the floor) and the re-check re-enters the live region
+where 4096 and 8192 place a model differently.
+
+Two tests, deliberately paired: one pins the invariant, one proves the invariant is
+load-bearing rather than vacuous by breaking it and measuring what comes back.
+"""
+
+from __future__ import annotations
+
+import importlib.util
+import inspect
+from pathlib import Path
+
+import pytest
+
+_TESTS_DIR = Path(__file__).resolve().parent
+_spec = importlib.util.spec_from_file_location(
+ "_auto_offload_matrix_for_floor", _TESTS_DIR / "test_auto_offload_ctx_platform_matrix.py"
+)
+_matrix = importlib.util.module_from_spec(_spec)
+import sys as _sys # noqa: E402
+
+# dataclasses resolves annotations through sys.modules, so the module has to be
+# registered before it executes.
+_sys.modules["_auto_offload_matrix_for_floor"] = _matrix
+_spec.loader.exec_module(_matrix)
+
+from core.inference import llama_cpp as _llama_cpp # noqa: E402
+from core.inference.llama_cpp import ( # noqa: E402
+ _AUTO_OFFLOAD_CTX,
+ _FIT_MIN_CTX,
+ LlamaCppBackend,
+)
+
+Accelerator = _matrix.Accelerator
+MIB = _matrix.MIB
+PLATFORMS = _matrix.PLATFORMS
+LINUX = next(p for p in PLATFORMS if p[0] == "linux")
+
+# One 24 GB card with 20000 MiB free is 19280 MiB of pooled budget after the
+# occupancy reserve. 17000 MiB of weights leaves 2280 MiB, which holds the KV of
+# 4560 tokens at the 0.5 MiB/token rate the matrix harness prices: over the floor,
+# under 8192. That is exactly the window in which the fallback value decides
+# placement, and it is empty only because the floor closes it.
+CARD = Accelerator("nvidia-single", False, ((0, 20_000, 24_000),))
+MODEL_MIB = 17_000
+
+
+def _fit_helper_floors() -> dict:
+ """The minimum context each fit helper applies when the caller names none.
+
+ Read from the signatures rather than hardcoded, because the auto loop's calls
+ pass no ``min_ctx`` at all: these defaults, not ``_FIT_MIN_CTX``, are what
+ actually floors the search on the path the fallback sits on.
+ """
+ return {
+ name: inspect.signature(getattr(LlamaCppBackend, name)).parameters["min_ctx"].default
+ for name in ("_fit_context_to_vram", "_cap_ctx_to_per_device_reserve")
+ }
+
+
+def _award_at(
+ tmp_path,
+ monkeypatch,
+ offload_ctx: int,
+ *,
+ model_mib: int = MODEL_MIB,
+):
+ """Run the fallback with the constant set to ``offload_ctx``; report the award."""
+ monkeypatch.setattr(_llama_cpp, "_AUTO_OFFLOAD_CTX", offload_ctx)
+ backend, gguf = _matrix.cell_backend(
+ _matrix._subdir(tmp_path, f"ctx-{offload_ctx}-{model_mib}"),
+ monkeypatch,
+ LINUX,
+ CARD,
+ model_fraction = 1.0,
+ )
+ backend._get_gguf_size_bytes = lambda _path: model_mib * MIB
+ result, hits = _matrix._traced(lambda: _matrix._launch(backend, gguf, n_ctx = 0))
+ assert _matrix.SITE_A in hits, "the cell no longer reaches the fallback"
+ return {
+ "awarded": _matrix.SITE_A_AWARD in hits,
+ "fit": _matrix._flag(result["cmd"], "--fit"),
+ "devices": _matrix._selected_devices(result["cmd"], result["env"]),
+ }
+
+
+def test_the_offload_context_never_sits_below_the_fit_search_floor():
+ """The invariant itself. Nothing else in the tree states it.
+
+ Both halves matter. ``_FIT_MIN_CTX`` is the named floor and the one a reader
+ would check; the bare defaults on the two helpers are the ones the auto loop
+ actually gets, because neither of its calls passes ``min_ctx``. Breaking either
+ relation puts the re-check back in the region where the fallback moves devices.
+ """
+ floors = _fit_helper_floors()
+
+ assert _AUTO_OFFLOAD_CTX >= _FIT_MIN_CTX, (
+ f"_AUTO_OFFLOAD_CTX ({_AUTO_OFFLOAD_CTX}) dropped below _FIT_MIN_CTX "
+ f"({_FIT_MIN_CTX}); the Site A re-check can now award GPU residency and the "
+ "fallback is a placement decision, not a context default"
+ )
+ for name, floor in floors.items():
+ assert _AUTO_OFFLOAD_CTX >= floor, (
+ f"_AUTO_OFFLOAD_CTX ({_AUTO_OFFLOAD_CTX}) dropped below the default "
+ f"min_ctx of {name} ({floor})"
+ )
+ # The helpers' defaults are what _FIT_MIN_CTX documents. If they ever diverge,
+ # the comment on _FIT_MIN_CTX is wrong and so is the reasoning above.
+ assert set(floors.values()) == {_FIT_MIN_CTX}, floors
+
+
+ "offload_ctx,expect_award",
+ [
+ (256, True),
+ (512, True),
+ (1024, True),
+ (2048, True),
+ (3072, True),
+ (_FIT_MIN_CTX, False),
+ (6144, False),
+ (_AUTO_OFFLOAD_CTX, False),
+ ],
+)
+def test_the_floor_is_the_only_thing_keeping_the_fallback_out_of_placement(
+ tmp_path, monkeypatch, offload_ctx, expect_award
+):
+ """The invariant is load-bearing, measured rather than argued.
+
+ Same host, same model, same everything but the constant. Below the fit floor the
+ re-check hands the model a device and turns ``--fit`` off, which is a placement
+ change of exactly the kind the change is claimed not to make; at the floor and
+ above it never does. This is why the test above is not a tautology.
+ """
+ outcome = _award_at(tmp_path, monkeypatch, offload_ctx)
+
+ assert outcome["awarded"] is expect_award
+ if expect_award:
+ # Residency awarded: Studio owns placement and llama.cpp's fitter is off.
+ assert outcome["fit"] == "off"
+ assert outcome["devices"] == (0,)
+ else:
+ assert outcome["fit"] == "on"
+ assert outcome["devices"] is None
+
+
+ "free_mib,total_mib",
+ [(20_000, 24_000), (12_000, 16_000), (9_000, 0)],
+ ids = ["24g-card", "16g-card", "shared-pool"],
+)
+def test_no_model_size_awards_residency_at_or_above_the_floor(
+ tmp_path, monkeypatch, free_mib, total_mib
+):
+ """The same claim swept over model sizes, on three cards including a shared pool
+ reporting ``total_mib == 0``.
+
+ Counted rather than asserted cell by cell, because "awards below the floor" is
+ true only in the band where the weights leave room for a small KV and not a
+ large one, and which fractions land in that band depends on the card. What has
+ to hold everywhere is the pair: zero awards at the floor and above it, and a
+ non-zero number below it on every card, so no card is silent merely because
+ nothing there could ever be awarded.
+ """
+ card = Accelerator(f"card-{free_mib}", False, ((0, free_mib, total_mib),))
+ fractions = (0.70, 0.75, 0.80, 0.85, 0.90, 0.95)
+ below_floor = (256, 1024, 2048)
+ awards = {"below": 0, "at-or-above": 0}
+ reached = 0
+
+ for fraction in fractions:
+ model_mib = int(fraction * free_mib)
+ for offload_ctx in (*below_floor, _FIT_MIN_CTX, _AUTO_OFFLOAD_CTX):
+ monkeypatch.setattr(_llama_cpp, "_AUTO_OFFLOAD_CTX", offload_ctx)
+ backend, gguf = _matrix.cell_backend(
+ _matrix._subdir(tmp_path, f"{free_mib}-{model_mib}-{offload_ctx}"),
+ monkeypatch,
+ LINUX,
+ card,
+ model_fraction = 1.0,
+ )
+ backend._get_gguf_size_bytes = lambda _path: model_mib * MIB
+ _result, hits = _matrix._traced(lambda: _matrix._launch(backend, gguf, n_ctx = 0))
+ if _matrix.SITE_A not in hits:
+ continue
+ reached += 1
+ if _matrix.SITE_A_AWARD in hits:
+ awards["below" if offload_ctx < _FIT_MIN_CTX else "at-or-above"] += 1
+
+ assert reached, "no cell on this card reached the fallback"
+ assert awards["at-or-above"] == 0
+ assert awards["below"] > 0
+
+
+def test_the_projector_residency_floor_is_the_fit_floor_and_not_the_offload_context():
+ """``_MMPROJ_FIT_FLOOR_CTX`` happened to equal the old fallback; it does not
+ follow the new one, and must not.
+
+ The projector probe decides whether a vision encoder stays on the GPU by pricing
+ the load at that floor. The number it wants is the LOWEST context at which
+ placement can still award GPU residency, and that is the fit floor: the subset
+ loop's fit bottoms out there and returns it whenever it fits. The offload
+ fallback is what the loop emits after it has already surrendered and handed
+ placement to ``--fit``, which is past the point the probe is asking about.
+
+ Pinned here because the two constants were the same literal before this change,
+ so a reader could reasonably assume they still move together.
+ """
+ assert LlamaCppBackend._MMPROJ_FIT_FLOOR_CTX == _FIT_MIN_CTX
+ assert LlamaCppBackend._MMPROJ_FIT_FLOOR_CTX != _AUTO_OFFLOAD_CTX
diff --git a/studio/backend/tests/test_auto_offload_ctx_invariants.py b/studio/backend/tests/test_auto_offload_ctx_invariants.py
new file mode 100644
index 00000000000..9427893b142
--- /dev/null
+++ b/studio/backend/tests/test_auto_offload_ctx_invariants.py
@@ -0,0 +1,150 @@
+# 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 two invariants that make ``_AUTO_OFFLOAD_CTX`` safe to move.
+
+Raising the Auto offload context from 4096 to 8192 changes no GPU placement, but
+not because the value is unimportant. It is safe because of a coupling that was
+previously implicit in the two numbers being the same literal:
+
+1. ``_AUTO_OFFLOAD_CTX >= _FIT_MIN_CTX``. The Auto offload branch re-checks
+ whether some subset holds the model at the reduced context. That re-check can
+ only ever award residency BELOW ``_FIT_MIN_CTX``, because both
+ ``_fit_context_to_vram`` and ``_cap_ctx_to_per_device_reserve`` floor there,
+ so a subset winnable at or above the floor was already taken by the fit loop
+ that runs first. Once the constant drops under the floor the re-check re-enters
+ the live region and the Auto context starts deciding which GPUs hold the model,
+ which is a different and much larger change than picking a chat length.
+
+2. The published UI ceiling tracks the same constant. ``max_context_length`` is
+ the threshold the chat settings sheet warns above. If it is anchored below the
+ context Auto actually selects, every Auto load in this branch exceeds its own
+ published ceiling and warns about itself, telling the user to lower the context
+ or leave it on Auto when Auto is what produced the value.
+
+Neither invariant is expressible as a type, and both are one edited literal away
+from silently breaking, so they are pinned here. No GPU, subprocess or GGUF I/O.
+Cross-platform: Linux, macOS, Windows, WSL.
+"""
+
+from __future__ import annotations
+
+import inspect
+import re
+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)
+
+_loggers_stub = _types.ModuleType("loggers")
+_loggers_stub.get_logger = lambda name: __import__("logging").getLogger(name)
+sys.modules.setdefault("loggers", _loggers_stub)
+
+_structlog_stub = _types.ModuleType("structlog")
+sys.modules.setdefault("structlog", _structlog_stub)
+
+from core.inference.llama_cpp import ( # noqa: E402
+ _AUTO_OFFLOAD_CTX,
+ _FIT_MIN_CTX,
+ LlamaCppBackend,
+)
+
+# Reuse the two existing mirrors rather than growing a third. Both stub the same
+# way this file does, so importing them costs no extra setup. Sibling imports need
+# the tests dir on the path: pytest inserts rootdir, not this package.
+_TESTS_DIR = str(Path(__file__).resolve().parent)
+if _TESTS_DIR not in sys.path:
+ sys.path.insert(0, _TESTS_DIR)
+
+from test_llama_cpp_context_fit import _drive # noqa: E402
+from test_llama_cpp_max_context_threshold import ( # noqa: E402
+ _compute_max_available_ctx,
+)
+
+
+def test_auto_offload_context_is_not_below_the_fit_floor():
+ """Invariant 1. Below the floor, the offload re-check starts awarding GPU
+ residency again and the constant stops being a display choice."""
+ assert _AUTO_OFFLOAD_CTX >= _FIT_MIN_CTX
+
+
+def test_the_fit_helpers_still_floor_where_the_invariant_assumes():
+ """Invariant 1 holds against a floor that is NOT ``_FIT_MIN_CTX``.
+
+ Neither auto call site passes ``min_ctx``, so what actually bounds the search
+ is the bare default on each helper; ``_FIT_MIN_CTX`` is only handed in
+ explicitly on the Apple arm. The two agree today, which is what lets the
+ constant above stand in for the floor, and this is where that agreement is
+ pinned. A default lowered here moves the dead region without touching either
+ constant, and nothing else in the tree would notice.
+ """
+ for func in (
+ LlamaCppBackend._fit_context_to_vram,
+ LlamaCppBackend._cap_ctx_to_per_device_reserve,
+ ):
+ params = inspect.signature(func).parameters
+ min_ctx = params.get("min_ctx")
+ assert min_ctx is not None, (
+ f"{func.__qualname__} no longer takes min_ctx; the Auto offload "
+ "re-check's dead region is defined by that floor"
+ )
+ assert min_ctx.default == _FIT_MIN_CTX, (
+ f"{func.__qualname__} defaults min_ctx to {min_ctx.default}, not "
+ f"_FIT_MIN_CTX ({_FIT_MIN_CTX}). The Auto offload re-check awards GPU "
+ "residency below the floor, so the two must not drift apart"
+ )
+
+
+def test_the_published_ui_ceiling_tracks_the_auto_offload_context():
+ """Invariant 2, asserted on the source because the value is produced deep
+ inside ``load_model`` and the failure is a stale literal, not a bad number.
+ """
+ source = inspect.getsource(LlamaCppBackend.load_model)
+ anchor = re.search(
+ r"max_available_ctx\s*=\s*min\(\s*([A-Za-z_0-9]+)\s*,\s*native_ctx_for_cap",
+ source,
+ )
+ assert anchor is not None, "the no-fit UI safe-zone anchor moved or was renamed"
+ assert anchor.group(1) == "_AUTO_OFFLOAD_CTX", (
+ "the UI safe zone is anchored at a literal again; it must follow the "
+ "Auto offload context or every Auto load in this branch warns about itself"
+ )
+
+
+ "native, model_gib, gpus",
+ [
+ # MiniMax-like: weights alone dwarf a single large card.
+ (196608, 131, [(0, 97_000)]),
+ # Nothing fits even pooled across four cards.
+ (131072, 400, [(0, 80_000), (1, 80_000), (2, 80_000), (3, 80_000)]),
+ # Mixed sizes, so the ranked-subset walk runs before giving up.
+ (131072, 200, [(0, 48_000), (1, 24_000), (2, 8_000)]),
+ # Native below the fallback: both sides must land on native, not 8192.
+ (2048, 200, [(0, 80_000)]),
+ ],
+)
+def test_auto_never_publishes_a_ceiling_below_the_context_it_runs(native, model_gib, gpus):
+ """The behavioural half of invariant 2, driven through both real mirrors.
+
+ ``_max_context_length`` is what the status route serves as
+ ``max_context_length``, and the chat sheet warns when the running context
+ exceeds it. On an offloading model the running context IS the Auto fallback,
+ so a ceiling computed from a different constant makes the load warn about
+ itself. Drive the ceiling probe and the context decision from the same inputs
+ and require that they agree.
+ """
+ published = _compute_max_available_ctx(native_ctx = native, model_gib = model_gib, gpus = gpus)
+ plan = _drive(n_ctx = 0, model_gib = model_gib, gpus = gpus, native_ctx = native)
+ running = plan["c_arg"]
+
+ assert running > 0
+ assert running <= published, (
+ f"Auto runs at {running} but publishes a ceiling of {published}, "
+ "so the chat sheet warns on a context Auto chose itself"
+ )
diff --git a/studio/backend/tests/test_auto_offload_ctx_platform_matrix.py b/studio/backend/tests/test_auto_offload_ctx_platform_matrix.py
new file mode 100644
index 00000000000..ecf1ba5ab9f
--- /dev/null
+++ b/studio/backend/tests/test_auto_offload_ctx_platform_matrix.py
@@ -0,0 +1,608 @@
+# 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 GPU vendor] for the Auto host-offload context (``_AUTO_OFFLOAD_CTX``).
+
+The failure mode guarded: raising the context Auto settles on when no discrete-GPU
+subset can hold the model (4096 -> 8192) is a change to a value that is read inside
+the *placement* decision, so it could move which devices a load pins, whether
+``--fit`` owns placement, or which arm of ``load_model``'s placement chain runs at
+all. It must not. The only thing allowed to differ is the emitted context, and only
+on the two arms that reach one of the two sites.
+
+The chain under test, in source order:
+
+ 1. tensor-parallel -- ``_plan_tensor_parallel`` owns everything
+ 2. measured-KV -- gpus + ``_can_estimate_kv()``; holds SITE A, the
+ subset loop's ``else:`` plus its residency re-check
+ 3. file-size-only -- gpus, no KV metadata; holds SITE B, which only
+ relabels the context ``--fit`` was already given
+ 4. Apple unified memory -- no gpus, a Metal budget; hardcoded 4096s, untouched
+ 5. (no arm) -- no gpus and no Metal budget: CPU, no context math
+
+Each cell records the arm taken, the emitted context, ``--fit`` and the pinned
+device list. The arm is read from a line tracer over ``load_model`` rather than
+inferred from the output, because "the arm ran and changed nothing" and "the arm
+never ran" produce the same argv on most cells.
+
+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, Metal 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``. No ROCm runtime, no Metal device
+and no Windows kernel is exercised. 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 dataclasses
+import importlib.util
+import inspect
+import sys
+from pathlib import Path
+from typing import Optional
+
+import pytest
+
+# Both harnesses already exist; by path, because the tests dir is not a package.
+# test_llama_cpp_placement owns the module stubs, the fake GGUF, the fake GPU probe
+# and the captured Popen; test_llama_extra_args_platforms owns the OS seam and the
+# accelerator list this file extends rather than replaces.
+_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
+
+
+_placement = _load("_placement_harness_auto_offload", "test_llama_cpp_placement.py")
+_platforms = _load("_platform_harness_auto_offload", "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 ( # noqa: E402
+ _AUTO_OFFLOAD_CTX,
+ _FIT_MIN_CTX,
+ _IGPU_HOST_RESERVE_MIB,
+ LlamaCppBackend,
+ _apply_igpu_host_reserve_mib,
+)
+from utils.hardware import hardware as _hw # noqa: E402
+
+GIB = 1024**3
+MIB = 1024**2
+
+
+# ── the arm tracer ───────────────────────────────────────────────────────────
+#
+# load_model is one function with the whole placement chain inside it, so the arm
+# taken is not observable from the outside: an arm that ran and left placement
+# alone emits the same argv as one that was skipped. A line tracer over that single
+# code object is the cheapest thing that can tell them apart.
+#
+# Anchors are resolved by source search at import time, not by hardcoded line
+# numbers, and every one of them is asserted unique-or-known-count below. A rename
+# that moves an anchor fails loudly with the anchor named, which is the intended
+# behaviour: the table this file prints would otherwise silently start describing
+# the wrong branch.
+
+_LOAD_MODEL = inspect.unwrap(LlamaCppBackend.load_model)
+_SOURCE_LINES, _SOURCE_FIRST = inspect.getsourcelines(_LOAD_MODEL)
+
+
+def _anchor_lines(needle: str) -> list[int]:
+ return [_SOURCE_FIRST + offset for offset, line in enumerate(_SOURCE_LINES) if needle in line]
+
+
+def _one_anchor(needle: str) -> int:
+ hits = _anchor_lines(needle)
+ assert len(hits) == 1, f"anchor is no longer unique in load_model: {needle!r} -> {hits}"
+ return hits[0]
+
+
+# Both the measured-KV arm and the Apple arm open by re-reading the native context,
+# so one search yields both, ordered by position in the chain.
+_NATIVE_CTX_ANCHORS = _anchor_lines("native_ctx_for_cap = self._context_length or effective_ctx")
+assert len(_NATIVE_CTX_ANCHORS) == 2, _NATIVE_CTX_ANCHORS
+
+# First executable statement of each arm's body, so a hit means the arm was TAKEN.
+# An `elif` header line would only mean its condition was evaluated.
+ARM_ANCHORS = {
+ "tensor-parallel": _one_anchor("self._plan_tensor_parallel("),
+ "measured-kv": min(_NATIVE_CTX_ANCHORS),
+ "file-size-only": _one_anchor("Falling back to file-size-only GPU selection"),
+ "apple-metal": _one_anchor("_apple_fit_budget_mib = int("),
+}
+
+# Site A: the measured-KV subset loop's `else:`, which lowers the context and then
+# re-checks whether any subset can hold the model at that lower context.
+SITE_A = _one_anchor("effective_ctx = min(_AUTO_OFFLOAD_CTX, effective_ctx)")
+# The line the re-check awards residency on. Two subset loops assign it; the award
+# is the one after Site A.
+_AWARDS = _anchor_lines("gpu_indices = sorted(idx for idx, _ in subset)")
+assert len(_AWARDS) == 2 and max(_AWARDS) > SITE_A, (_AWARDS, SITE_A)
+SITE_A_AWARD = max(_AWARDS)
+# Site B: the file-size-only arm's relabel. Placement was already decided by
+# _select_gpus on the line above, so nothing downstream of this can move a device.
+SITE_B = _one_anchor("if use_fit and not explicit_ctx:")
+
+
+def _traced(call):
+ """Run ``call`` and return ``(result, executed_line_numbers)`` for load_model."""
+ hits: set[int] = set()
+
+ def _local(frame, event, _arg):
+ if event == "line":
+ hits.add(frame.f_lineno)
+ return _local
+
+ def _global(frame, _event, _arg):
+ return _local if frame.f_code is _LOAD_MODEL.__code__ else None
+
+ previous = sys.gettrace()
+ sys.settrace(_global)
+ try:
+ return call(), hits
+ finally:
+ # Restored unconditionally: leaking a trace function would slow, and under
+ # a coverage run silently displace, every test that follows this one.
+ sys.settrace(previous)
+
+
+# ── the matrix ───────────────────────────────────────────────────────────────
+
+# Both shared-memory cells report their pool through the same helper the real
+# probes use, so the numbers in the table are the product's own arithmetic rather
+# than invented ones. An APU's HIP free reading is unusable (Windows reports
+# free == total, #7072), so system RAM caps it first; a Vulkan iGPU's reading is
+# already host RAM, so only the reserve applies.
+HOST_AVAILABLE_MIB = 24_000
+APU_RAW_FREE_MIB = 32_768
+APU_FREE_MIB = _apply_igpu_host_reserve_mib(min(APU_RAW_FREE_MIB, HOST_AVAILABLE_MIB), True)
+IGPU_RAW_FREE_MIB = 12_000
+IGPU_FREE_MIB = _apply_igpu_host_reserve_mib(IGPU_RAW_FREE_MIB, True)
+
+
[email protected](frozen = True)
+class Accelerator:
+ """One column of the matrix.
+
+ ``memory`` rows are ``(index, free_mib, total_mib)`` exactly as
+ ``_get_gpu_memory`` answers. A ``total_mib`` of 0 is the shared-pool marker both
+ the Vulkan iGPU and the ROCm APU paths emit, because that "total" would be
+ system RAM; the placement math reads it as "no absolute headroom known".
+ """
+
+ label: str
+ vulkan: bool
+ memory: tuple
+ apple_budget_bytes: int = 0
+ is_rocm: bool = False
+
+
+# The four the extra-args matrix already ships, kept byte-identical so both suites
+# describe the same hardware, plus the four this change makes worth separating.
+ACCELERATORS = [
+ Accelerator(label, vulkan, tuple(memory)) for label, vulkan, memory in _platforms.ACCELERATORS
+] + [
+ # ROCm without Vulkan: the torch fallback probe, not amd-smi, and the only
+ # vendor for which sys.platform changes the free VRAM figure (see G6 below).
+ Accelerator("amd-rocm", False, ((0, 12_000, 16_000),), is_rocm = True),
+ # Unified-memory APU: no dedicated VRAM at all.
+ Accelerator("amd-apu", False, ((0, APU_FREE_MIB, 0),), is_rocm = True),
+ Accelerator("vulkan-igpu", True, ((0, IGPU_FREE_MIB, 0),)),
+ # Apple Silicon: nothing enumerates, and the Metal budget is the only signal.
+ Accelerator("apple-metal", False, (), apple_budget_bytes = 16 * GIB),
+]
+
+MATRIX = [
+ pytest.param(platform, accelerator, id = f"{platform[0]}-{accelerator.label}")
+ for platform in PLATFORMS
+ for accelerator in ACCELERATORS
+]
+
+# What every cell loads. "fits" is small enough for the cell's own pool, so the
+# subset loop awards residency and no site is reached; "overflows" is large enough
+# that nothing holds it, which is the only way to reach Site A.
+FITS = 0.35
+OVERFLOWS = 1.30
+NATIVE_CTX = 131_072
+# KV linear in the context at 0.5 MiB per token, so the fit has something to price
+# and a lower context genuinely buys room. Any monotone function would do.
+KV_MIB_PER_CTX = 0.5
+
+
[email protected](frozen = True)
+class Outcome:
+ arm: str
+ site: Optional[str]
+ ctx: Optional[int]
+ fit: Optional[str]
+ gpu_indices: Optional[tuple]
+ awarded: bool
+
+ def placement(self) -> tuple:
+ """Everything the constant is forbidden to move."""
+ return (self.arm, self.site, self.fit, self.gpu_indices, self.awarded)
+
+
+def _flag(cmd, *names) -> Optional[str]:
+ for index, token in enumerate(cmd):
+ if token in names and index + 1 < len(cmd):
+ return cmd[index + 1]
+ return None
+
+
+def _selected_devices(cmd, env) -> Optional[tuple]:
+ """The devices placement actually chose, as the child sees them.
+
+ ``backend.gpu_ids`` only carries an explicit user pick, so an automatic
+ selection is invisible there. What placement emits instead is a visibility
+ mask (CUDA / HIP / ROCR) or, on a Vulkan build, ``--device VulkanN``. A mask of
+ -1 is the deliberate CPU pin. Note that a Vulkan build names its devices even
+ when ``--fit`` owns placement, so this is the device set the child may use, not
+ proof that residency was awarded; ``Outcome.awarded`` is that proof.
+ """
+ device = _flag(cmd, "--device", "-dev")
+ if device:
+ return tuple(
+ int(name.strip().lower().removeprefix("vulkan"))
+ for name in device.split(",")
+ if name.strip()
+ )
+ for name in ("CUDA_VISIBLE_DEVICES", "HIP_VISIBLE_DEVICES", "ROCR_VISIBLE_DEVICES"):
+ mask = env.get(name)
+ if mask:
+ return tuple(int(part) for part in mask.split(",") if part.strip())
+ return None
+
+
+def _subdir(tmp_path, name):
+ path = tmp_path / name
+ path.mkdir(parents = True, exist_ok = True)
+ return path
+
+
+def cell_backend(
+ tmp_path,
+ monkeypatch,
+ platform,
+ accelerator: Accelerator,
+ *,
+ model_fraction: float = OVERFLOWS,
+ estimate_kv: bool = True,
+ native_ctx: int = NATIVE_CTX,
+):
+ """A backend wearing one cell's platform and accelerator."""
+ _apply_platform(monkeypatch, platform)
+ # No inherited visibility mask: a mask in the child env has to be one THIS
+ # launch wrote, or "placement pinned nothing" reads as a pin on any developer
+ # box that exports CUDA_VISIBLE_DEVICES.
+ for name in ("CUDA_VISIBLE_DEVICES", "HIP_VISIBLE_DEVICES", "ROCR_VISIBLE_DEVICES"):
+ monkeypatch.delenv(name, raising = False)
+ monkeypatch.setattr(_hw, "IS_ROCM", accelerator.is_rocm, raising = False)
+ monkeypatch.setattr(
+ LlamaCppBackend,
+ "_apple_metal_memory_budget_bytes",
+ staticmethod(lambda: accelerator.apple_budget_bytes),
+ )
+ backend, gguf = _backend(tmp_path, vulkan = accelerator.vulkan, memory = list(accelerator.memory))
+
+ # Sized against the cell's own reported free memory so "fits" and "overflows"
+ # mean the same thing on a 12 GB card and on a 24 GB shared pool. With no GPU
+ # the size decides nothing, so a fixed 16 GB stands in.
+ free_mib = sum(row[1] for row in accelerator.memory) or 16_384
+ model_bytes = int(model_fraction * free_mib * MIB)
+ backend._get_gguf_size_bytes = lambda _path: model_bytes
+ backend._read_gguf_metadata = lambda _path: setattr(backend, "_context_length", native_ctx)
+ backend._can_estimate_kv = lambda: estimate_kv
+ backend._estimate_kv_cache_bytes = lambda ctx, *_a, **_kw: int(ctx * KV_MIB_PER_CTX * MIB)
+ # Held at zero so the context that comes out is the KV decision alone; the
+ # compute buffer has its own suite (test_compute_buffer.py).
+ backend._compute_buffer_ctx_bytes = lambda *_a, **_kw: 0
+ backend._estimate_compute_buffer_bytes = lambda **_kw: 1
+ return backend, gguf
+
+
+def run_cell(tmp_path, monkeypatch, platform, accelerator: Accelerator, **kwargs) -> Outcome:
+ """Drive one cell through the real ``load_model`` and report what it did."""
+ load_kwargs = kwargs.pop("load_kwargs", {})
+ backend, gguf = cell_backend(tmp_path, monkeypatch, platform, accelerator, **kwargs)
+ result, hits = _traced(lambda: _launch(backend, gguf, n_ctx = 0, **load_kwargs))
+ arms = [name for name, line in ARM_ANCHORS.items() if line in hits]
+ assert len(arms) <= 1, f"more than one placement arm ran: {arms}"
+ site = "A" if SITE_A in hits else ("B" if SITE_B in hits else None)
+ ctx = _flag(result["cmd"], "-c", "--ctx-size")
+ return Outcome(
+ arm = arms[0] if arms else "none",
+ site = site,
+ ctx = int(ctx) if ctx is not None else None,
+ fit = _flag(result["cmd"], "--fit"),
+ gpu_indices = _selected_devices(result["cmd"], result["env"]),
+ awarded = SITE_A_AWARD in hits,
+ )
+
+
+# ── G1 / G4 / G5: the arm and the placement on every cell ────────────────────
+
+
[email protected]("platform,accelerator", MATRIX)
+def test_an_overflowing_model_reaches_the_expected_arm_and_pins_nothing(
+ tmp_path, monkeypatch, platform, accelerator
+):
+ """G1. A model no subset can hold: the placement half of the answer.
+
+ This is the only shape that reaches Site A, so it is the shape where the
+ constant could do damage. On every cell the answer is the same one the 4096
+ fallback gave: no device is pinned and ``--fit`` owns placement.
+ """
+ outcome = run_cell(tmp_path, monkeypatch, platform, accelerator)
+
+ if accelerator.memory:
+ assert outcome.arm == "measured-kv"
+ assert outcome.site == "A"
+ # The whole claim of the change: it buys context, never residency. The
+ # re-check under Site A is the only code that could award any, and it does
+ # not fire on a single cell of this matrix.
+ assert outcome.awarded is False
+ assert outcome.fit == "on"
+ assert outcome.ctx == _AUTO_OFFLOAD_CTX
+ elif accelerator.apple_budget_bytes:
+ # G3: Metal is a mutually exclusive arm and never sees the constant.
+ assert outcome.arm == "apple-metal"
+ assert outcome.site is None
+ else:
+ # G4: no device and no Metal budget falls off the end of the chain.
+ assert outcome.arm == "none"
+ assert outcome.site is None
+
+
[email protected]("platform,accelerator", MATRIX)
+def test_a_model_that_fits_never_reaches_either_site(tmp_path, monkeypatch, platform, accelerator):
+ """G1. The far more common shape: the subset loop awards, so the constant is
+ never read. Pinned devices and ``--fit off`` are the evidence the loop won."""
+ outcome = run_cell(tmp_path, monkeypatch, platform, accelerator, model_fraction = FITS)
+
+ assert outcome.site is None
+ if accelerator.memory:
+ assert outcome.arm == "measured-kv"
+ assert outcome.gpu_indices == (accelerator.memory[0][0],)
+ assert outcome.fit == "off"
+ # A fitted context, not the fallback: the two must not be confusable.
+ assert outcome.ctx is not None and outcome.ctx > _AUTO_OFFLOAD_CTX
+
+
[email protected]("accelerator", ACCELERATORS, ids = [a.label for a in ACCELERATORS])
+def test_wsl_is_indistinguishable_from_native_linux(tmp_path, monkeypatch, accelerator):
+ """G5. The only WSL detector on this path is a loader-path decision, so the
+ context math must not be able to tell the two apart on any accelerator."""
+ linux = next(p for p in PLATFORMS if p[0] == "linux")
+ wsl2 = next(p for p in PLATFORMS if p[0] == "wsl2")
+
+ for fraction in (FITS, OVERFLOWS):
+ on_linux = run_cell(
+ _subdir(tmp_path, f"linux-{fraction}"),
+ monkeypatch,
+ linux,
+ accelerator,
+ model_fraction = fraction,
+ )
+ on_wsl = run_cell(
+ _subdir(tmp_path, f"wsl-{fraction}"),
+ monkeypatch,
+ wsl2,
+ accelerator,
+ model_fraction = fraction,
+ )
+ assert on_wsl == on_linux
+
+
[email protected]("platform", PLATFORMS, ids = [p[0] for p in PLATFORMS])
+def test_the_file_size_only_arm_relabels_the_context_without_moving_a_device(
+ tmp_path, monkeypatch, platform
+):
+ """Site B. Reached only without KV metadata, and inert with respect to
+ placement by construction: ``_select_gpus`` has already returned above it and
+ nothing below re-runs it. Only the number the UI is told changes."""
+ accelerator = next(a for a in ACCELERATORS if a.label == "nvidia-single")
+ outcome = run_cell(tmp_path, monkeypatch, platform, accelerator, estimate_kv = False)
+
+ assert outcome.arm == "file-size-only"
+ assert outcome.site == "B"
+ assert outcome.gpu_indices is None
+ assert outcome.fit == "on"
+ assert outcome.ctx == _AUTO_OFFLOAD_CTX
+
+
+# ── G3: the Metal asymmetry, measured ────────────────────────────────────────
+
+
[email protected]("platform", PLATFORMS, ids = [p[0] for p in PLATFORMS])
+def test_metal_auto_still_floors_at_the_fit_minimum(tmp_path, monkeypatch, platform):
+ """G3. Pins the CURRENT Metal behaviour so it cannot drift silently.
+
+ The Apple arm keeps its own floor and never reads ``_AUTO_OFFLOAD_CTX``, so an
+ offloading model gets ``_FIT_MIN_CTX`` here and ``_AUTO_OFFLOAD_CTX`` on a
+ discrete GPU: half the context on the same model. That asymmetry is deliberate
+ (unified memory is shared with the OS, so a larger KV is charged to the same
+ pool the weights and the compositor live in) and this test exists to make any
+ future change to it explicit rather than incidental.
+
+ Parametrised over every platform on purpose: the arm is gated on a non-zero
+ Metal budget, not on ``sys.platform``, and that is worth having on record.
+ """
+ metal = next(a for a in ACCELERATORS if a.label == "apple-metal")
+ on_metal = run_cell(_subdir(tmp_path, "metal"), monkeypatch, platform, metal)
+
+ assert on_metal.arm == "apple-metal"
+ assert on_metal.ctx == _FIT_MIN_CTX
+
+ discrete = next(a for a in ACCELERATORS if a.label == "nvidia-single")
+ on_discrete = run_cell(_subdir(tmp_path, "discrete"), monkeypatch, platform, discrete)
+ assert on_discrete.ctx == _AUTO_OFFLOAD_CTX
+ assert on_discrete.ctx == 2 * on_metal.ctx
+
+
+# ── G7: manual memory mode ───────────────────────────────────────────────────
+
+
[email protected]("platform", PLATFORMS, ids = [p[0] for p in PLATFORMS])
[email protected]("gpu_layers", [-1, 8], ids = ["auto-layers", "explicit-layers"])
+def test_manual_memory_mode_bypasses_both_sites_on_a_gpu_box(
+ tmp_path, monkeypatch, platform, gpu_layers
+):
+ """G7. Two sites clear ``gpus`` before the chain, so a manual load takes no arm
+ at all even with cards enumerated, and neither site can be reached."""
+ accelerator = next(a for a in ACCELERATORS if a.label == "nvidia-multi")
+ outcome = run_cell(
+ tmp_path,
+ monkeypatch,
+ platform,
+ accelerator,
+ load_kwargs = {"gpu_memory_mode": "manual", "gpu_layers": gpu_layers},
+ )
+
+ assert outcome.arm == "none"
+ assert outcome.site is None
+ assert outcome.gpu_indices is None
+
+
+# ── G8: the ROCm arch gate ───────────────────────────────────────────────────
+
+
[email protected]("platform", PLATFORMS, ids = [p[0] for p in PLATFORMS])
+def test_the_rocm_arch_gate_drops_an_amd_host_onto_the_cpu_path(tmp_path, monkeypatch, platform):
+ """G8. Every present device gated out (#7624) empties ``_gpu_mem``, so an AMD
+ box with real cards takes the same no-arm path a CPU-only box takes and never
+ reaches either site."""
+ accelerator = next(a for a in ACCELERATORS if a.label == "amd-rocm")
+ _apply_platform(monkeypatch, platform)
+ monkeypatch.setattr(_hw, "IS_ROCM", True, raising = False)
+ monkeypatch.setattr(
+ LlamaCppBackend, "_apple_metal_memory_budget_bytes", staticmethod(lambda: 0)
+ )
+ for name in ("CUDA_VISIBLE_DEVICES", "HIP_VISIBLE_DEVICES", "ROCR_VISIBLE_DEVICES"):
+ monkeypatch.delenv(name, raising = False)
+ backend, gguf = _backend(tmp_path, vulkan = False, memory = list(accelerator.memory))
+ present = list(accelerator.memory)
+
+ # The gate's own shape: the llama-server probe returns nothing, the ungated one
+ # still sees the cards, and no installed arch covers them.
+ backend._get_gpu_memory = lambda _binary = None, for_llama_server = False, **_kw: (
+ [] if for_llama_server else list(present)
+ )
+ backend._host_torch_is_rocm = lambda: True
+ backend._installed_llama_gfx_archs = lambda _binary: frozenset({"gfx1030"})
+ backend._rocm_arch_by_physical_id = lambda: {row[0]: "gfx1033" for row in present}
+ backend._get_gguf_size_bytes = lambda _path: int(OVERFLOWS * 12_000 * MIB)
+ backend._read_gguf_metadata = lambda _path: setattr(backend, "_context_length", NATIVE_CTX)
+ backend._can_estimate_kv = lambda: True
+ backend._estimate_kv_cache_bytes = lambda ctx, *_a, **_kw: int(ctx * KV_MIB_PER_CTX * MIB)
+ backend._compute_buffer_ctx_bytes = lambda *_a, **_kw: 0
+ backend._estimate_compute_buffer_bytes = lambda **_kw: 1
+
+ result, hits = _traced(lambda: _launch(backend, gguf, n_ctx = 0))
+
+ assert not [name for name, line in ARM_ANCHORS.items() if line in hits]
+ assert SITE_A not in hits and SITE_B not in hits
+ # -1 is the CPU mask the gate writes so the child cannot enumerate the cards
+ # it has no kernels for. Placement chose CPU, not a device.
+ assert _selected_devices(result["cmd"], result["env"]) == (-1,)
+
+
+# ── G9: the two shared-memory pools that are not Metal ───────────────────────
+
+
+def test_the_shared_memory_cells_carry_a_zero_total_and_a_reduced_free():
+ """G9. Documents the numbers the two shared-pool cells above were built from,
+ so a change to the reserve or to the APU cap shows up here rather than as a
+ silently different matrix. Both reach the sites with ``total_mib == 0``."""
+ apu = next(a for a in ACCELERATORS if a.label == "amd-apu")
+ igpu = next(a for a in ACCELERATORS if a.label == "vulkan-igpu")
+
+ assert apu.memory[0][2] == 0 and igpu.memory[0][2] == 0
+ # The APU's HIP reading is capped by system RAM before the reserve is taken.
+ assert APU_FREE_MIB == HOST_AVAILABLE_MIB - _IGPU_HOST_RESERVE_MIB == 22_976
+ # The iGPU's reading is already host RAM, so only the reserve applies.
+ assert IGPU_FREE_MIB == IGPU_RAW_FREE_MIB - _IGPU_HOST_RESERVE_MIB == 10_976
+ # A discrete card is never touched by the reserve.
+ assert _apply_igpu_host_reserve_mib(12_000, False) == 12_000
+
+
+# ── G6: Windows ROCm reaches the fallback more often than Linux ROCm ─────────
+
+
+def _rocm_torch(free_mib: int, total_mib: int, reserved_mib: int):
+ """The two readings ``trusted_mem_get_info`` consults, and nothing else."""
+ import types
+
+ torch = types.ModuleType("torch")
+ torch.cuda = types.SimpleNamespace(
+ mem_get_info = lambda _device = None: (free_mib * MIB, total_mib * MIB),
+ memory_reserved = lambda _device = None: reserved_mib * MIB,
+ )
+ return torch
+
+
+ "os_key,expected_free_mib",
+ [("linux", 16_000), ("win32", 10_384)],
+ ids = ["linux-rocm", "windows-rocm"],
+)
+def test_windows_rocm_feeds_a_smaller_free_reading_into_the_planner(
+ monkeypatch, os_key, expected_free_mib
+):
+ """G6, first half: identical hardware, two different numbers.
+
+ ``rocm_windows_free_is_untrusted`` is True only for win32 + IS_ROCM, and
+ ``trusted_mem_get_info`` then caps free at ``total - reserved``. WDDM
+ virtualises video memory, so the driver's 16000 is the process's own budget
+ rather than the card's residency; the cap is the only ceiling there is.
+ """
+ monkeypatch.setitem(sys.modules, "torch", _rocm_torch(16_000, 16_384, 6_000))
+ monkeypatch.setattr(_hw.sys, "platform", os_key)
+ monkeypatch.setattr(_hw, "IS_ROCM", True, raising = False)
+
+ assert _hw.rocm_windows_free_is_untrusted() is (os_key == "win32")
+ free_bytes, total_bytes = _hw.trusted_mem_get_info(0)
+ assert free_bytes // MIB == expected_free_mib
+ assert total_bytes // MIB == 16_384
+
+
+def test_the_windows_rocm_cap_is_what_pushes_a_load_into_the_fallback(tmp_path, monkeypatch):
+ """G6, second half: the smaller number changes the outcome.
+
+ Same card, same model. Linux keeps the driver's 16000 MiB and the subset loop
+ awards residency; Windows sees 10384 MiB, nothing holds the model, and the load
+ lands on Site A. So Windows AMD users meet the new Auto offload context on
+ hardware where Linux AMD users never see it. Not a regression the constant
+ introduced -- the same asymmetry sent them to 4096 before -- but it is the cell
+ where the new value is most often visible.
+ """
+ windows = next(p for p in PLATFORMS if p[0] == "windows")
+ linux = next(p for p in PLATFORMS if p[0] == "linux")
+ # 12 GiB of weights: inside a 16000 MiB budget with room for a KV, outside the
+ # 10384 MiB one before any context is priced at all.
+ model_mib = 12 * 1024
+
+ def _run(platform, free_mib, subdir):
+ accelerator = Accelerator("amd-rocm", False, ((0, free_mib, 16_384),), is_rocm = True)
+ backend, gguf = cell_backend(
+ _subdir(tmp_path, subdir), monkeypatch, platform, accelerator, model_fraction = 1.0
+ )
+ backend._get_gguf_size_bytes = lambda _path: model_mib * MIB
+ result, hits = _traced(lambda: _launch(backend, gguf, n_ctx = 0))
+ return _selected_devices(result["cmd"], result["env"]), SITE_A in hits
+
+ on_linux = _run(linux, 16_000, "linux")
+ on_windows = _run(windows, 10_384, "windows")
+
+ assert on_linux == ((0,), False)
+ assert on_windows == (None, True)
diff --git a/studio/backend/tests/test_compute_buffer.py b/studio/backend/tests/test_compute_buffer.py
index 1f96c770a12..34e91b5b53d 100644
--- a/studio/backend/tests/test_compute_buffer.py
+++ b/studio/backend/tests/test_compute_buffer.py
@@ -56,7 +56,7 @@ except ImportError:
)
sys.modules["httpx"] = _httpx_stub
-from core.inference.llama_cpp import LlamaCppBackend
+from core.inference.llama_cpp import _FIT_MIN_CTX, LlamaCppBackend
MIB = 1024 * 1024
GIB = 1024 * MIB
@@ -847,10 +847,16 @@ class TestPerDeviceSplitReserve:
min_gpus = 2,
enforce = True,
):
- """Mirror of the reduced-to-4096 loop the native loop falls through to. Same
- pooled admission, so it needs the same per-device gate."""
+ """Mirror of the Auto offload loop the native loop falls through to. Same
+ pooled admission, so it needs the same per-device gate.
+
+ Driven at the fit search floor rather than at ``_AUTO_OFFLOAD_CTX``: what
+ this exercises is the per-device reserve gate, and the floor is the lowest
+ context the loop above can still be admitted at, so it is the value that
+ makes the gate decide anything.
+ """
frac = LlamaCppBackend._GPU_PIN_VRAM_FRACTION
- ctx = 4096
+ ctx = _FIT_MIN_CTX
def usable(g):
return g[1] - (1.0 - frac) * totals[g[0]]
diff --git a/studio/backend/tests/test_llama_cpp_context_fit.py b/studio/backend/tests/test_llama_cpp_context_fit.py
index be6c3358951..e6da59447b9 100644
--- a/studio/backend/tests/test_llama_cpp_context_fit.py
+++ b/studio/backend/tests/test_llama_cpp_context_fit.py
@@ -6,7 +6,7 @@
Guards two regressions in ``LlamaCppBackend.load_model``:
1. Auto mode (``n_ctx == 0``) when weights exceed every GPU subset's free
- memory: auto-pick should fall back to 4096 (a usable slider value) rather
+ memory: auto-pick should fall back to 8192 (a useful chat context) rather
than leaving native ctx. User can still drag higher onto ``--fit on``.
2. Explicit ctx must never be silently shrunk: when KV overflows fittable
weights, honor the explicit ctx with ``--fit on`` flexing ``-ngl``.
@@ -76,6 +76,7 @@ except ImportError:
sys.modules.setdefault("httpx", _httpx_stub)
from core.inference.llama_cpp import (
+ _AUTO_OFFLOAD_CTX,
_APPLE_UNIFIED_MEMORY_FRACTION,
_CTX_FIT_VRAM_FRACTION,
LlamaCppBackend,
@@ -89,7 +90,7 @@ from core.inference.llama_server_args import parse_ctx_override, resolve_request
# ---------------------------------------------------------------------------
GIB = 1024**3
-FALLBACK_CTX = 4096
+FIT_MIN_CTX = 4096
def _make_backend(
@@ -218,8 +219,8 @@ def _drive(
matched = True
break
if not matched:
- effective_ctx = min(FALLBACK_CTX, effective_ctx)
- # Mirror llama_cpp.py: re-check fit at FALLBACK_CTX.
+ effective_ctx = min(_AUTO_OFFLOAD_CTX, effective_ctx)
+ # Mirror llama_cpp.py: re-check fit at the Auto offload context.
if effective_ctx > 0:
for n_gpus in range(1, len(ranked) + 1):
subset = ranked[:n_gpus]
@@ -233,10 +234,12 @@ def _drive(
elif gpus:
gpu_indices, use_fit = inst._select_gpus(model_size, gpus)
if use_fit and not explicit_ctx:
- effective_ctx = min(FALLBACK_CTX, effective_ctx) if effective_ctx > 0 else FALLBACK_CTX
+ effective_ctx = (
+ min(_AUTO_OFFLOAD_CTX, effective_ctx) if effective_ctx > 0 else _AUTO_OFFLOAD_CTX
+ )
elif apple_budget_mib > 0 and effective_ctx > 0:
# Mirrors the Apple unified-memory branch in load_model: flat MTP reserve
- # off the budget up front (no-op at 0), sparse-KV floors to FALLBACK_CTX,
+ # off the budget up front (no-op at 0), sparse-KV floors to FIT_MIN_CTX,
# only auto context shrinks.
native_ctx_for_cap = context_length or effective_ctx
apple_fit_budget_mib = int(apple_budget_mib * max(0.0, 1.0 - flat_mtp_reserve))
@@ -254,10 +257,10 @@ def _drive(
max_available_ctx = (
cap
if cap_footprint_mib <= apple_fit_budget_mib
- else min(FALLBACK_CTX, native_ctx_for_cap)
+ else min(FIT_MIN_CTX, native_ctx_for_cap)
)
else:
- max_available_ctx = min(FALLBACK_CTX, native_ctx_for_cap)
+ max_available_ctx = min(FIT_MIN_CTX, native_ctx_for_cap)
if not explicit_ctx:
effective_ctx = max_available_ctx
@@ -286,7 +289,7 @@ class TestAutoModeWeightsExceedVRAM:
gpus = [(0, 97_000)],
native_ctx = 196608,
)
- assert plan["c_arg"] == FALLBACK_CTX
+ assert plan["c_arg"] == _AUTO_OFFLOAD_CTX
assert plan["use_fit"] is True
assert plan["gpu_indices"] is None
# UI slider ceiling stays at native: user can drag higher and get
@@ -300,12 +303,12 @@ class TestAutoModeWeightsExceedVRAM:
gpus = [(0, 80_000), (1, 80_000), (2, 80_000), (3, 80_000)],
native_ctx = 131072,
)
- assert plan["c_arg"] == FALLBACK_CTX
+ assert plan["c_arg"] == _AUTO_OFFLOAD_CTX
assert plan["use_fit"] is True
assert plan["gpu_indices"] is None
def test_no_kv_metadata_auto(self):
- """File-size-only fallback path also defaults to 4096."""
+ """File-size-only fallback path uses the same 8192 default."""
plan = _drive(
n_ctx = 0,
model_gib = 131,
@@ -313,7 +316,7 @@ class TestAutoModeWeightsExceedVRAM:
native_ctx = 196608,
can_estimate_kv = False,
)
- assert plan["c_arg"] == FALLBACK_CTX
+ assert plan["c_arg"] == _AUTO_OFFLOAD_CTX
assert plan["use_fit"] is True
@@ -362,12 +365,12 @@ class TestExplicitCtxRespectsUser:
def test_explicit_at_fallback_on_too_big(self):
plan = _drive(
- n_ctx = FALLBACK_CTX,
+ n_ctx = _AUTO_OFFLOAD_CTX,
model_gib = 131,
gpus = [(0, 97_000)],
native_ctx = 196608,
)
- assert plan["c_arg"] == FALLBACK_CTX
+ assert plan["c_arg"] == _AUTO_OFFLOAD_CTX
assert plan["use_fit"] is True
def test_explicit_below_floor_honored(self):
@@ -438,7 +441,7 @@ class TestFittableAutoPickRegressions:
)
assert plan["use_fit"] is False
assert plan["gpu_indices"] == [0]
- assert plan["c_arg"] > FALLBACK_CTX
+ assert plan["c_arg"] > FIT_MIN_CTX
def test_medium_model_needs_multi_gpu(self):
plan = _drive(
@@ -913,7 +916,7 @@ class TestAppleBranchEndToEnd:
native_ctx = 262144,
apple_budget_mib = 20_000,
)
- assert plan["c_arg"] == FALLBACK_CTX
+ assert plan["c_arg"] == FIT_MIN_CTX
assert plan["use_fit"] is True
assert plan["gpu_indices"] is None
@@ -973,8 +976,7 @@ class TestAppleMtpFlatReserve:
class TestAppleNoKvMetadataFloor:
- """Sparse KV metadata floors the auto context to FALLBACK_CTX (like the
- discrete file-size-only fallback) instead of launching at native."""
+ """Sparse KV metadata keeps Apple's safety floor instead of native context."""
def test_sparse_kv_floors_auto_context(self):
plan = _drive(
@@ -985,7 +987,7 @@ class TestAppleNoKvMetadataFloor:
can_estimate_kv = False,
apple_budget_mib = 23_000,
)
- assert plan["c_arg"] == FALLBACK_CTX # not native 262144
+ assert plan["c_arg"] == FIT_MIN_CTX # not native 262144
assert plan["use_fit"] is True
assert plan["gpu_indices"] is None
diff --git a/studio/backend/tests/test_llama_cpp_max_context_threshold.py b/studio/backend/tests/test_llama_cpp_max_context_threshold.py
index 8a08e8aca3f..de824f3132b 100644
--- a/studio/backend/tests/test_llama_cpp_max_context_threshold.py
+++ b/studio/backend/tests/test_llama_cpp_max_context_threshold.py
@@ -12,9 +12,14 @@ The ctx slider in the chat settings sheet reads
When weights fit on some GPU subset, the threshold is the largest ctx that
fits fully in VRAM (the binary-search cap from ``_fit_context_to_vram``).
When weights exceed 90% of every GPU subset's free memory, the warning must
-fire as soon as the user drags above the 4096 spec default (otherwise loading
-e.g. MiniMax-M2.7 on a 97 GB GPU shows a slider up to 196608 with no hint that
-any value above 4096 triggers ``--fit on`` and degrades performance).
+fire as soon as the user drags above what Auto itself selects (otherwise
+loading e.g. MiniMax-M2.7 on a 97 GB GPU shows a slider up to 196608 with no
+hint that any larger value triggers ``--fit on`` and degrades performance).
+
+The threshold therefore tracks ``_AUTO_OFFLOAD_CTX`` and is not a literal.
+Anchoring it below that constant is worse than having no warning: Auto's own
+context then exceeds the ceiling Auto published, so every load in this branch
+warns about itself while advising the user to leave it on Auto.
These tests pin both cases. No GPU probing, subprocess, or GGUF I/O.
Cross-platform: Linux, macOS, Windows, WSL.
@@ -82,7 +87,11 @@ try:
except ImportError:
sys.modules.setdefault("httpx", _httpx_stub)
-from core.inference.llama_cpp import _CTX_FIT_VRAM_FRACTION, LlamaCppBackend
+from core.inference.llama_cpp import (
+ _AUTO_OFFLOAD_CTX,
+ _CTX_FIT_VRAM_FRACTION,
+ LlamaCppBackend,
+)
# Helpers
@@ -153,7 +162,7 @@ def _compute_max_available_ctx(
if best_cap > 0:
max_available_ctx = best_cap
else:
- max_available_ctx = min(4096, native_ctx_for_cap)
+ max_available_ctx = min(_AUTO_OFFLOAD_CTX, native_ctx_for_cap)
return max_available_ctx
@@ -162,8 +171,8 @@ def _compute_max_available_ctx(
class TestMaxContextLengthForWeightsExceedVRAM:
- """UI ``max_context_length`` must fall back to 4096 so the warning fires
- as soon as the user drags above the spec default.
+ """UI ``max_context_length`` must fall back to the Auto offload context so
+ the warning fires as soon as the user drags above what Auto selects.
"""
def test_minimax_like(self):
@@ -173,7 +182,7 @@ class TestMaxContextLengthForWeightsExceedVRAM:
model_gib = 131,
gpus = [(0, 97_000)],
)
- assert got == 4096
+ assert got == _AUTO_OFFLOAD_CTX
def test_multi_gpu_all_subsets_fail(self):
"""400 GB weights across a 4x80 GB pool (320 GB total, still too small)."""
@@ -182,11 +191,11 @@ class TestMaxContextLengthForWeightsExceedVRAM:
model_gib = 400,
gpus = [(0, 80_000), (1, 80_000), (2, 80_000), (3, 80_000)],
)
- assert got == 4096
+ assert got == _AUTO_OFFLOAD_CTX
def test_native_below_fallback_is_preserved(self):
- """If native ctx is itself below 4096, don't advertise a larger value
- than the model supports."""
+ """If native ctx is itself below the fallback, don't advertise a larger
+ value than the model supports."""
got = _compute_max_available_ctx(
native_ctx = 2048,
model_gib = 200,
@@ -209,7 +218,7 @@ class TestMaxContextLengthForFittableModels:
gpus = [(0, 24_000)],
kv_per_token_bytes = 8192,
)
- assert got > 4096
+ assert got > _AUTO_OFFLOAD_CTX
assert got <= 131072
def test_medium_model_multi_gpu(self):
@@ -220,7 +229,7 @@ class TestMaxContextLengthForFittableModels:
gpus = [(0, 40_000), (1, 40_000)],
kv_per_token_bytes = 8192,
)
- assert got > 4096
+ assert got > _AUTO_OFFLOAD_CTX
def test_tiny_model_on_huge_gpu_near_native(self):
"""2 GB model, 80 GB GPU, negligible KV: should approach native."""
diff --git a/studio/backend/tests/test_mmproj_placement_policy.py b/studio/backend/tests/test_mmproj_placement_policy.py
index d9b0c48a6ca..662305ede75 100644
--- a/studio/backend/tests/test_mmproj_placement_policy.py
+++ b/studio/backend/tests/test_mmproj_placement_policy.py
@@ -25,6 +25,7 @@ import pytest
from core.inference.llama_cpp import (
GgufLoadIntent,
LlamaCppBackend,
+ _AUTO_OFFLOAD_CTX,
_resolved_mmproj_offload,
)
from models.inference import InferenceStatusResponse, LoadResponse
@@ -670,7 +671,11 @@ def test_a_user_demanding_gpu_offload_still_pays_for_it(tmp_path):
cmd = _launch(backend, gguf, extra_args = ["--mmproj-offload"])["cmd"]
- assert cmd[cmd.index("-c") + 1] == "4096"
+ # Charging the projector leaves nothing that fits, so this lands on the Auto
+ # offload fallback. The value is that constant, not a literal: the point of the
+ # assertion is that the context shrank to pay for the projector, and pinning the
+ # number here only records which release the test was written in.
+ assert cmd[cmd.index("-c") + 1] == str(_AUTO_OFFLOAD_CTX)
def test_the_last_placement_spelling_is_what_gets_budgeted(tmp_path):
diff --git a/studio/backend/tests/test_model_override_schema_compatibility.py b/studio/backend/tests/test_model_override_schema_compatibility.py
new file mode 100644
index 00000000000..f3ac00eea65
--- /dev/null
+++ b/studio/backend/tests/test_model_override_schema_compatibility.py
@@ -0,0 +1,348 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""What an install running two different builds against one override map loses.
+
+The override map is a single unversioned JSON blob in ``app_settings``, and
+``set_model_override`` REPLACES the entry it writes rather than merging into it. That
+was harmless while every field the row could hold also had a control in every build
+that wrote it. The llama-server tuning group broke the symmetry: four fields the
+loader has always applied are now written by the settings route, so a client that
+predates the route change sends a payload that simply lacks them, and the replace
+takes them out.
+
+The rule the suite encodes: a field a build does not KNOW ABOUT is dropped harmlessly
+on read (a row is a whitelist rebuild, never a schema contract), but a field a build
+does not SEND is deleted on write, and nothing on the server puts it back. The first
+is forward compatibility working. The second is the exposure this schema shape
+creates, and it is pinned here so that a later fix has something to change.
+
+The identity rules a hydrating panel depends on are pinned too: the panel now asks
+this module which row its model resolves to, so the browser's own fold and this one
+have to agree on every path shape or the panel hydrates from another model's row.
+"""
+
+from __future__ import annotations
+
+import sys
+from pathlib import Path
+
+import pytest
+
+import utils.openai_auto_switch_settings as settings
+
+_TESTS_DIR = str(Path(__file__).resolve().parent)
+if _TESTS_DIR not in sys.path:
+ sys.path.insert(0, _TESTS_DIR)
+
+# Reuse the in-memory override store and the route-level PUT helper.
+from test_openai_auto_switch import _put, override_store # noqa: E402, F401
+
+MODEL = "unsloth/Repo-GGUF:Q4_K_M"
+
+# The group the settings route learned to forward. Named once, because every case
+# below is about the difference between a build that sends these and one that does not.
+SERVER_TUNING_FIELDS = ("load_mode", "spec_draft_cache_type", "ctx_checkpoints", "cache_ram")
+
+# Everything a build from before the group already sent, at values it would send.
+# spec_draft_cache_type needs a mode that loads a separate drafter, so dspark is
+# part of the shared payload rather than part of the tuning group.
+PRE_TUNING_PAYLOAD = dict(
+ custom_context_length = 8192,
+ kv_cache_dtype = "q8_0",
+ speculative_type = "dspark",
+ spec_draft_n_max = 4,
+ n_batch = 4096,
+ tensor_parallel = True,
+)
+
+# The four at values that are falsy but meaningful: no checkpoints kept, no cache
+# limit. A test that used only truthy values would pass against a route that stored
+# them on truth rather than on "is not None".
+TUNING_PAYLOAD = dict(
+ load_mode = "mmap",
+ spec_draft_cache_type = "q8_0",
+ ctx_checkpoints = 0,
+ cache_ram = -1,
+)
+
+
+def test_a_row_written_before_the_tuning_group_still_loads(override_store):
+ # P1, the base case every other row here is measured against. The normalizer is a
+ # whitelist rebuild, so a row from an install that never held the four is not
+ # "missing" anything: it produces exactly the load it always did.
+ legacy_row = {
+ "llama_extra_args": ["--numa", "distribute"],
+ "max_seq_length": 4096,
+ "kv_cache_dtype": "q8_0",
+ }
+
+ assert settings.normalize_model_override(legacy_row) == legacy_row
+ kwargs = settings.model_override_load_kwargs(legacy_row, is_gguf = True)
+ assert kwargs == {
+ "max_seq_length": 4096,
+ "llama_extra_args": ["--numa", "distribute"],
+ "cache_type_kv": "q8_0",
+ }
+ # And none of the four is invented at a default, which would pin a knob the user
+ # never touched for a model that has been loading without it.
+ for field in SERVER_TUNING_FIELDS:
+ assert field not in kwargs
+
+
+def test_a_field_from_a_newer_build_is_ignored_rather_than_fatal(override_store):
+ # P2. There is no version stamp to check, so forward compatibility rests entirely
+ # on both readers iterating keys they know. A row written by a build that has
+ # learned a fifth knob has to load on this one, minus that knob.
+ from_the_future = {
+ "custom_context_length": 8192,
+ "load_mode": "mmap",
+ "future_knob_from_a_newer_build": {"nested": [1, 2]},
+ }
+
+ assert settings.normalize_model_override(from_the_future) == {
+ "custom_context_length": 8192,
+ "load_mode": "mmap",
+ }
+ # The load path reads the raw stored row, not the normalized one, so it is the
+ # one that would raise on an unexpected key if either reader enumerated the dict.
+ assert settings.model_override_load_kwargs(from_the_future, is_gguf = True) == {
+ "max_seq_length": 8192,
+ "load_mode": "mmap",
+ }
+
+
+def test_a_client_that_does_not_know_the_tuning_group_cannot_erase_it(override_store):
+ """P3 and P4: the cell this whole file exists for.
+
+ A frontend from before the settings route forwarded the four sends a payload that
+ omits them, and ``set_model_override`` replaces the entry rather than merging. The
+ row carries no version stamp, so the route cannot tell that omission apart from a
+ user clearing the fields -- except that a build which knows them says so.
+
+ Reachable two ways, and neither needs a deliberate downgrade: a second machine on
+ the LAN still running the old build, and a browser holding a cached bundle against
+ a server that has been upgraded under it.
+ """
+ _put(MODEL, **PRE_TUNING_PAYLOAD, **TUNING_PAYLOAD, mirrors_server_tuning = True)
+ before = settings.get_model_override(MODEL)
+ for field, value in TUNING_PAYLOAD.items():
+ assert before[field] == value
+
+ # The old client: every field its build knows, and nothing it does not. It cannot
+ # set the flag, which is why the flag defaults to the safe answer.
+ _put(MODEL, **PRE_TUNING_PAYLOAD)
+ after = settings.get_model_override(MODEL)
+
+ for field, value in TUNING_PAYLOAD.items():
+ assert after[field] == value, f"{field} was deleted by a save that never mentioned it"
+ assert after == before
+ # And they still reach the command line.
+ kwargs = settings.model_override_load_kwargs(after, is_gguf = True)
+ for field, value in TUNING_PAYLOAD.items():
+ assert kwargs[field] == value
+
+
+def test_a_client_that_does_know_them_still_clears_by_omission(override_store):
+ # The other side of the trade. Preserving on every omission would be simpler and
+ # wrong: the panel clears one of these by sending nothing for it, so a blanket
+ # carry-over would swap a mixed-version window for a field no one can ever unset.
+ _put(MODEL, **PRE_TUNING_PAYLOAD, **TUNING_PAYLOAD, mirrors_server_tuning = True)
+ assert settings.get_model_override(MODEL)["load_mode"] == TUNING_PAYLOAD["load_mode"]
+
+ _put(MODEL, **PRE_TUNING_PAYLOAD, mirrors_server_tuning = True)
+ after = settings.get_model_override(MODEL)
+ for field in SERVER_TUNING_FIELDS:
+ assert field not in after, f"{field} survived an explicit clear"
+
+
+def test_the_preservation_flag_is_not_itself_a_saved_field(override_store):
+ # It is a write mode, like fill_absent_fields. Both are bools, so exclude_none does
+ # not drop them, and either one left in saved_fields would make every payload look
+ # non-empty and break the legacy "no fields means remove".
+ _put(MODEL, **PRE_TUNING_PAYLOAD, **TUNING_PAYLOAD, mirrors_server_tuning = True)
+ assert settings.get_model_override(MODEL)
+
+ _put(MODEL, mirrors_server_tuning = True)
+ assert settings.get_model_override(MODEL) == {}
+
+
+def test_a_legacy_model_id_only_clear_is_not_undone_by_preservation(override_store):
+ # The documented pre-`remove` contract: a payload carrying only model_id clears the
+ # override. That leaves payload.remove None while is_removal is true, so a gate on
+ # the field rather than the verdict would carry the tuning forward and rebuild a
+ # non-empty row -- the request succeeds and the settings keep applying.
+ _put(MODEL, **PRE_TUNING_PAYLOAD, **TUNING_PAYLOAD, mirrors_server_tuning = True)
+ assert settings.get_model_override(MODEL)
+
+ _put(MODEL)
+ assert settings.get_model_override(MODEL) == {}
+
+
+def test_tuning_carries_over_from_the_bare_repo_entry(override_store):
+ # A save under repo:QUANT reads flags off a bare `repo` row and retires it, so the
+ # preservation has to reach the same spellings the extra-args carry-over does. A
+ # lookup on the sent id alone finds nothing here and the tuning goes down with the
+ # row. Same shape for the snapshot-path and cached-alias spellings that walk beside
+ # it, which need HF cache state to reach and are covered by the alias sweep tests.
+ bare_id = "unsloth/Repo-GGUF"
+ _put(bare_id, **PRE_TUNING_PAYLOAD, **TUNING_PAYLOAD, mirrors_server_tuning = True)
+ assert settings.get_model_override(bare_id)["load_mode"] == TUNING_PAYLOAD["load_mode"]
+
+ # The older client saving the qualified key: it never sends the group, and its row
+ # does not exist yet, so everything it keeps has to come off the bare entry.
+ _put(MODEL, **PRE_TUNING_PAYLOAD)
+ kept = settings.get_model_override(MODEL)
+ for field, value in TUNING_PAYLOAD.items():
+ assert kept[field] == value, f"{field} was lost saving under the qualified key"
+
+
+def test_carry_over_does_not_activate_tuning_from_a_row_no_load_reads(override_store):
+ # The carry-over above walks a list of spellings, but a load does not: it stops at
+ # the first non-empty row (resolve_override_for_load) rather than merging across
+ # them. So tuning sitting in a row the qualified key shadows is dormant, and pulling
+ # it up into the winning row would switch it on -- from a save that was about
+ # something else entirely, on a client with no control for these fields to show it.
+ bare_id = "unsloth/Repo-GGUF"
+ _put(bare_id, **PRE_TUNING_PAYLOAD, **TUNING_PAYLOAD, mirrors_server_tuning = True)
+ # The qualified row exists and wins, and has none of the group.
+ _put(MODEL, **PRE_TUNING_PAYLOAD, mirrors_server_tuning = True)
+ _, active = settings.resolve_override_for_load(MODEL)
+ assert active, "precondition: the qualified row is what a load resolves to"
+ assert not any(field in active for field in SERVER_TUNING_FIELDS)
+
+ # The older client saves the qualified key, sending none of the group.
+ _put(MODEL, **PRE_TUNING_PAYLOAD)
+
+ kept = settings.get_model_override(MODEL)
+ for field in SERVER_TUNING_FIELDS:
+ assert field not in kept, f"{field} was promoted out of a row no load reads"
+ # And the row it came from is left exactly as it was, still dormant behind the
+ # qualified key rather than emptied by having been read.
+ for field, value in TUNING_PAYLOAD.items():
+ assert settings.get_model_override(bare_id)[field] == value
+
+
+def test_carry_over_reads_the_cached_spelling_a_load_would_resolve_to(override_store):
+ # An upgraded cache holds both spellings of one quant: the snapshot path an older
+ # build keyed rows by, and the repo id a Settings save writes. A lookup tries the
+ # load path FIRST, so the snapshot row is the live one and the repo row is dormant.
+ # The carry-over walks its own list, and if that list leads with the sent id it
+ # takes the unit off the dormant row -- and then the retirement block clears the
+ # snapshot row, so the tuning that was actually applying is gone and tuning that
+ # never applied takes its place. Neither row is visibly wrong afterwards, which is
+ # what makes it worth pinning.
+ snapshot_id = "/cache/models--org--Repo-GGUF/snapshots/abc:Q4_K_M"
+ repo_id = "org/Repo-GGUF:Q4_K_M"
+ live_tuning = dict(TUNING_PAYLOAD, load_mode = "mmap", cache_ram = -1)
+ dormant_tuning = dict(TUNING_PAYLOAD, load_mode = "direct", cache_ram = 4096)
+
+ # Written straight to the store rather than through the route: a save under either
+ # spelling retires the other, which is the very cleanup this test is about, so the
+ # route cannot be used to build the two-row state an upgrade leaves behind.
+ settings.set_model_override(snapshot_id, **PRE_TUNING_PAYLOAD, **live_tuning)
+ settings.set_model_override(repo_id, **PRE_TUNING_PAYLOAD, **dormant_tuning)
+ # Precondition: the two really are the pair, and the path really is the winner.
+ assert snapshot_id in settings.cached_repo_alias_keys(repo_id)
+ assert settings.is_cache_load_path_key(snapshot_id)
+ assert not settings.is_cache_load_path_key(repo_id)
+
+ # The older client saves the repo-id spelling, sending none of the group.
+ _put(repo_id, **PRE_TUNING_PAYLOAD)
+
+ kept = settings.get_model_override(repo_id)
+ assert kept["load_mode"] == "mmap", "took the dormant row's tuning, not the live one"
+ assert kept["cache_ram"] == -1
+
+
+def test_a_fill_pass_adds_the_tuning_group_without_disturbing_the_row(override_store):
+ # The one merge path there is, and the one the backfill uses. A fill must not be
+ # able to cause the erasure above, or the upgrade pass itself would strip the row
+ # it was run to complete.
+ _put(MODEL, **TUNING_PAYLOAD, speculative_type = "dspark")
+ _put(MODEL, custom_context_length = 8192, fill_absent_fields = True)
+
+ stored = settings.get_model_override(MODEL)
+ assert stored["custom_context_length"] == 8192
+ for field, value in TUNING_PAYLOAD.items():
+ assert stored[field] == value
+
+
+ "speculative_type",
+ # Every mode that does NOT load a separate drafter, plus the unset case.
+ ["ngram", "mtp", "mtp+ngram", "off", None],
+)
+def test_the_draft_cache_dtype_is_dropped_under_a_mode_with_no_drafter(
+ override_store, speculative_type
+):
+ """P10: the dtype needs a mode that loads a separate drafter, or it goes.
+
+ Pre-existing in the normalizer, but this PR is what carries the field to the
+ server at all, so the drop is now visible as a server row that silently lacks a
+ value the panel showed. Storing it anyway would show an edit for a draft context
+ that never exists, so the drop is right; the point of pinning it is that it is
+ SILENT, and a user who sets the dtype and then changes the mode is not told.
+ """
+ _put(MODEL, spec_draft_cache_type = "q8_0", speculative_type = speculative_type)
+
+ assert "spec_draft_cache_type" not in settings.get_model_override(MODEL)
+
+
+def test_the_draft_cache_dtype_survives_a_mode_that_does_load_a_drafter(override_store):
+ # The other side of P10, so the parametrize above cannot pass by dropping the
+ # field unconditionally.
+ for mode in sorted(settings.SEPARATE_DRAFT_MODEL_SPEC_TYPES):
+ _put(MODEL, spec_draft_cache_type = "q8_0", speculative_type = mode)
+ assert settings.get_model_override(MODEL)["spec_draft_cache_type"] == "q8_0"
+
+
+# P13. Each row is (stored key, key a load asks under, whether they name one model).
+# The browser folds before it stores and this module folds before it reads, so a
+# disagreement is a panel hydrating from another model's row. Mirrors foldOverrideKey
+# in features/model-picker/api/model-overrides.ts, which is pinned from the other end
+# in tests/llama-extra-args-override-lookup.test.ts.
+OVERRIDE_KEY_FOLDS = [
+ # A Windows volume is case-insensitive and its separators interchange.
+ ("C:\\models\\Foo.gguf", "c:/models/foo.gguf", True),
+ ("C:\\models\\Foo.gguf", "C:\\models\\Foo.gguf\\", True),
+ # A UNC share is the same volume however it is spelled.
+ ("//share/models/Foo.gguf", "\\\\SHARE\\models\\foo.gguf", True),
+ # A WSL drive mount IS the Windows volume it exposes.
+ ("/mnt/c/models/Foo.gguf", "/mnt/C/models/foo.gguf", True),
+ # A POSIX path is not: two files can differ only in case, and replaying one
+ # model's context and GPU pin onto the other is worse than finding nothing.
+ ("/models/Foo.gguf", "/models/foo.gguf", False),
+ # A repo id folds whole; the browser lowercases it before storing.
+ ("unsloth/Repo-GGUF", "UNSLOTH/repo-gguf", True),
+ # And the quant suffix folds with it.
+ ("unsloth/Repo-GGUF:Q4_K_M", "unsloth/repo-gguf:q4_k_m", True),
+ # A path never folds onto a repo id, in either direction: "models/foo.gguf" is a
+ # legal repo id and "/models/foo.gguf" is a file, and one is not the other.
+ ("/models/foo.gguf", "models/foo.gguf", False),
+ ("models/foo.gguf", "/models/foo.gguf", False),
+]
+
+
[email protected](("stored_key", "lookup_key", "same_model"), OVERRIDE_KEY_FOLDS)
+def test_an_override_key_resolves_the_way_the_browser_folds_it(
+ override_store, stored_key, lookup_key, same_model
+):
+ settings.set_model_override(stored_key, max_seq_length = 4096)
+
+ resolved = settings.resolve_model_override_key(lookup_key)
+ if same_model:
+ assert resolved == stored_key
+ assert settings.get_model_override(lookup_key) == {"max_seq_length": 4096}
+ else:
+ assert resolved is None
+ assert settings.get_model_override(lookup_key) == {}
+
+
+def test_two_keys_that_fold_together_resolve_to_nothing(override_store):
+ # An upgrade can leave both casings behind. Picking one at enumeration order is
+ # another model's settings half the time, so an ambiguous fold matches nothing.
+ settings.set_model_override("C:\\models\\Foo.gguf", max_seq_length = 4096)
+ settings.set_model_override("C:\\models\\FOO.gguf", max_seq_length = 8192)
+
+ assert settings.resolve_model_override_key("c:/models/foo.gguf") is None
diff --git a/studio/backend/tests/test_openai_auto_switch.py b/studio/backend/tests/test_openai_auto_switch.py
index 023a9e42537..b6e9b7d7dc2 100644
--- a/studio/backend/tests/test_openai_auto_switch.py
+++ b/studio/backend/tests/test_openai_auto_switch.py
@@ -1084,6 +1084,46 @@ def test_override_route_rejects_managed_flag_and_removes(monkeypatch):
assert "unsloth/B-GGUF" not in resp2.overrides
+def test_override_route_stores_llama_server_tuning(override_store):
+ """Load mode, draft KV dtype, checkpoints and cache RAM survive the route.
+
+ The picker has a control for each and mirrors all four, and
+ ``model_override_load_kwargs`` already applies them off a stored row, so a
+ payload that drops them leaves the setting reaching a picker load and nothing
+ else -- and the panel, which hydrates from this row, reads it back as unset.
+ """
+ _put(
+ "unsloth/B-GGUF",
+ load_mode = "mmap+mlock",
+ speculative_type = "dspark",
+ spec_draft_cache_type = "q8_0",
+ # Both meaningful at their falsy values: no checkpoints, and no cache limit.
+ ctx_checkpoints = 0,
+ cache_ram = -1,
+ )
+ stored = settings.get_model_override("unsloth/B-GGUF")
+ assert stored["load_mode"] == "mmap+mlock"
+ assert stored["spec_draft_cache_type"] == "q8_0"
+ assert stored["ctx_checkpoints"] == 0
+ assert stored["cache_ram"] == -1
+ # And they reach a load, rather than being stored where nothing reads them.
+ kwargs = settings.model_override_load_kwargs(stored, is_gguf = True)
+ assert kwargs["load_mode"] == "mmap+mlock"
+ assert kwargs["spec_draft_cache_type"] == "q8_0"
+ assert kwargs["ctx_checkpoints"] == 0
+ assert kwargs["cache_ram"] == -1
+
+
+def test_override_route_keeps_a_row_holding_only_tuning(override_store):
+ """One of the four on its own is a saved field, not an empty payload.
+
+ ``is_removal`` counts what the payload carries, so a field it did not declare
+ would read as "nothing set" and delete the model's row instead of writing it.
+ """
+ _put("unsloth/B-GGUF", cache_ram = 0)
+ assert settings.get_model_override("unsloth/B-GGUF") == {"cache_ram": 0}
+
+
def test_model_override_rejects_zero_max_seq_length():
# 0 is not a valid sequence length and the setter drops a falsy value, so the
# payload must reject it at the boundary instead of accepting then discarding it.
diff --git a/studio/backend/utils/openai_auto_switch_settings.py b/studio/backend/utils/openai_auto_switch_settings.py
index e9e35c7510b..f29607e5a9f 100644
--- a/studio/backend/utils/openai_auto_switch_settings.py
+++ b/studio/backend/utils/openai_auto_switch_settings.py
@@ -997,6 +997,26 @@ def _cached_repo_override_identity(model_id: str) -> Optional[tuple[str, str]]:
return repo.strip().casefold(), quant.strip().casefold()
+def is_cache_load_path_key(model_id: str) -> bool:
+ """True when ``model_id`` spells a cached quant as the path a load actually opens.
+
+ The two spellings of one cached repo are not interchangeable in a lookup:
+ ``override_lookup_candidates`` tries the load path before the advertised repo id,
+ so of a pair only the path row is ever read and the repo-id row sits dormant. A
+ caller choosing between stored rows has to know which side it is holding, and
+ ``cached_repo_alias_keys`` deliberately does not say, since it answers "the other
+ spelling" in either direction.
+
+ Lives here for the reason the rest of the resolution does: the ordering rule is
+ this module's, and a second copy of it would drift.
+ """
+ from core.inference.model_ids import hf_cache_repo_id
+
+ split = split_quant_suffix(model_id)
+ base = split[0] if split else model_id
+ return hf_cache_repo_id(base) is not None
+
+
def cached_repo_alias_keys(model_id: str) -> list[str]:
"""Stored keys that name the same cached quant as ``model_id`` under the other spelling.
diff --git a/studio/frontend/src/components/ui/slider.tsx b/studio/frontend/src/components/ui/slider.tsx
index b921b259427..d3d39188efc 100644
--- a/studio/frontend/src/components/ui/slider.tsx
+++ b/studio/frontend/src/components/ui/slider.tsx
@@ -18,6 +18,18 @@ function getThumbInBoundsOffset(width: number, percent: number) {
return halfWidth - (percent / halfPercent) * halfWidth;
}
+type SliderProps = React.ComponentProps<typeof SliderPrimitive.Root> & {
+ /**
+ * What a screen reader should say instead of the bare number.
+ *
+ * Radix does not synthesise `aria-valuetext`, so a slider whose positions mean
+ * something other than their value announces the value and nothing else. The
+ * context slider's leftmost position means Auto, which without this reads as
+ * "0" -- a context length no model has.
+ */
+ thumbValueText?: (value: number, index: number) => string;
+};
+
function Slider({
className,
defaultValue,
@@ -26,8 +38,9 @@ function Slider({
max = 100,
orientation = "horizontal",
onValueChange,
+ thumbValueText,
...props
-}: React.ComponentProps<typeof SliderPrimitive.Root>) {
+}: SliderProps) {
const isControlled = Array.isArray(value);
const [uncontrolledValues, setUncontrolledValues] =
React.useState<number[]>(() =>
@@ -103,6 +116,14 @@ function Slider({
<SliderPrimitive.Thumb
data-slot="slider-thumb"
key={index}
+ // The thumb is the element carrying role="slider", so the name and the
+ // spoken value belong here. Everything else spreads onto Root, which is
+ // a plain div: an aria-label passed to this component reached that div
+ // and left the actual control unnamed, and Radix only fills in a label
+ // of its own for multi-thumb ranges.
+ aria-label={props["aria-label"]}
+ aria-labelledby={props["aria-labelledby"]}
+ aria-valuetext={thumbValueText?.(values[index] ?? min, index)}
className="ring-ring/50 relative z-10 size-4 rounded-4xl bg-white shadow-sm block shrink-0 select-none cursor-pointer disabled:pointer-events-none disabled:opacity-50 transition-transform duration-100 ease-out hover:scale-110 hover:ring-4 active:scale-95 focus-visible:ring-1 focus-visible:outline-hidden"
/>
))}
diff --git a/studio/frontend/src/features/model-picker/api/model-overrides.ts b/studio/frontend/src/features/model-picker/api/model-overrides.ts
index 63d7119e650..18ef6daf10b 100644
--- a/studio/frontend/src/features/model-picker/api/model-overrides.ts
+++ b/studio/frontend/src/features/model-picker/api/model-overrides.ts
@@ -12,7 +12,11 @@ import {
normalizeModelIdentity,
splitQuantSuffix,
} from "../model-config/model-identity";
-import type { PerModelConfig } from "../model-config/per-model-config";
+import {
+ DEFAULT_PER_MODEL_CONFIG,
+ type PerModelConfig,
+ normalizePerModelConfig,
+} from "../model-config/per-model-config";
const OVERRIDES_URL = "/api/settings/openai-auto-switch/overrides";
@@ -76,16 +80,6 @@ export function modelOverrideKey(
return ggufVariant ? `${modelId}:${ggufVariant}` : modelId;
}
-/**
- * The stored pass-through args for a model, under any key the backend would resolve.
- *
- * The overrides route folds identities before it reads a row: a repo id and a quant
- * differing only in case resolve to the same entry, and it falls back from
- * `repo:QUANT` to the bare repo. A literal lookup on the two keys this panel happens
- * to use would show an empty box for a model that will launch with arguments, and
- * the first edit would then replace a list nobody saw. Keys are tried most specific
- * first, then folded, mirroring that order.
- */
/**
* A path that names one file whatever the casing, folded for comparison, or null
* when the path is case-sensitive.
@@ -158,10 +152,19 @@ function resolvedFrom(entry: ApiModelOverride): ResolvedExtraArgs {
return { tokens: tokens ?? [], explicit: Array.isArray(tokens) };
}
-export function resolveStoredExtraArgs(
+function presentOverride(
+ value: ApiModelOverride | undefined | null,
+): ApiModelOverride | null {
+ return value && Object.keys(value).length > 0 ? value : null;
+}
+
+export function resolveStoredOverride(
overrides: ApiModelOverrides,
keys: readonly string[],
-): ResolvedExtraArgs {
+): ApiModelOverride | null {
+ // The overrides route folds identities before it reads a row: a repo id and a
+ // quant differing only in case resolve to the same entry, and it falls back from
+ // `repo:QUANT` to the bare repo. Keys are tried most specific first, then folded.
// Whole ENTRIES, in the order the backend tries them, stopping at the first one
// that exists. The auto-switch loader breaks on the first non-empty override and
// reads its fields from there, so falling through to a bare repo id because the
@@ -169,11 +172,9 @@ export function resolveStoredExtraArgs(
// API load would not use.
// An entry with no fields is skipped rather than stopping the search, because
// that is what `if override: break` does on the server.
- const present = (value: ApiModelOverride | undefined | null) =>
- value && Object.keys(value).length > 0 ? value : null;
const folded = new Map<string, ApiModelOverride | null>();
for (const [key, value] of Object.entries(overrides)) {
- if (!present(value)) {
+ if (!presentOverride(value)) {
continue;
}
const foldedKey = foldOverrideKey(key);
@@ -183,9 +184,9 @@ export function resolveStoredExtraArgs(
folded.set(foldedKey, folded.has(foldedKey) ? null : value);
}
for (const key of keys) {
- const exact = present(overrides[key]);
+ const exact = presentOverride(overrides[key]);
if (exact) {
- return resolvedFrom(exact);
+ return exact;
}
// Folding, by the same rule the backend resolves with: a POSIX path is
// case-sensitive, so lowercasing one whole would hand /models/foo.gguf the
@@ -194,10 +195,18 @@ export function resolveStoredExtraArgs(
// lowercases before storing.
const match = folded.get(foldOverrideKey(key));
if (match) {
- return resolvedFrom(match);
+ return match;
}
}
- return { tokens: [], explicit: false };
+ return null;
+}
+
+export function resolveStoredExtraArgs(
+ overrides: ApiModelOverrides,
+ keys: readonly string[],
+): ResolvedExtraArgs {
+ const resolved = resolveStoredOverride(overrides, keys);
+ return resolved ? resolvedFrom(resolved) : { tokens: [], explicit: false };
}
export async function fetchModelOverrides(): Promise<ApiModelOverrides> {
@@ -223,12 +232,12 @@ export async function fetchModelOverrides(): Promise<ApiModelOverrides> {
* Falls back to resolving locally against the whole map when the backend predates
* the parameter, which is the same answer in every case but the exotic ones.
*/
-export async function fetchLoadExtraArgs(
+export async function fetchLoadModelOverride(
loadId: string,
aliasId: string,
ggufVariant?: string | null,
fallbackKeys: readonly string[] = [],
-): Promise<ResolvedExtraArgs> {
+): Promise<ApiModelOverride | null> {
const query = new URLSearchParams({ model_id: loadId, alias_id: aliasId });
if (ggufVariant) {
query.set("gguf_variant", ggufVariant);
@@ -246,10 +255,7 @@ export async function fetchLoadExtraArgs(
resolved_key?: string | null;
};
if (body.resolved !== undefined) {
- // An explicit empty list is a cleared box, not an absence, and the caller has
- // to send it as one: omitting the field lets /load carry the resident model's
- // arguments over, which is exactly what was cleared.
- return resolvedFrom(body.resolved ?? {});
+ return presentOverride(body.resolved);
}
// A backend that predates the resolved field answers with the whole map, and the
// caller has to say which keys to look under. Derived here when it did not: the
@@ -266,7 +272,91 @@ export async function fetchLoadExtraArgs(
loadId,
aliasId,
].filter((key, index, all) => all.indexOf(key) === index);
- return resolveStoredExtraArgs(body.overrides ?? {}, derived);
+ return resolveStoredOverride(body.overrides ?? {}, derived);
+}
+
+export async function fetchLoadExtraArgs(
+ loadId: string,
+ aliasId: string,
+ ggufVariant?: string | null,
+ fallbackKeys: readonly string[] = [],
+): Promise<ResolvedExtraArgs> {
+ const resolved = await fetchLoadModelOverride(
+ loadId,
+ aliasId,
+ ggufVariant,
+ fallbackKeys,
+ );
+ // An explicit empty list is a cleared box, not an absence, and the caller has
+ // to send it as one: omitting the field lets /load carry the resident model's
+ // arguments over, which is exactly what was cleared.
+ return resolvedFrom(resolved ?? {});
+}
+
+/**
+ * Translate one server-resolved override into the config shape the picker uses.
+ *
+ * The row is authoritative for the fields it CARRIES, and only for those. An absent
+ * field is not evidence the user chose the default: the mirror is best-effort and
+ * lossy, so a PUT that never landed, a value this build's normalizer refused, and a
+ * row written before a field reached the route all leave the same gap. `localConfig`
+ * fills it, or opening the panel would delete settings the user typed here -- a
+ * migrated legacy config, or one whose mirror failed, came back as bare defaults and
+ * was then persisted over the original. The cost is that clearing ONE field on another
+ * origin does not travel until this one saves again, which the schema cannot express
+ * anyway: an omitted field and an app default are written the same way.
+ */
+export function fromApiOverride(
+ override: ApiModelOverride,
+ localConfig?: PerModelConfig,
+): PerModelConfig {
+ const local = localConfig ?? DEFAULT_PER_MODEL_CONFIG;
+ // Three states, so the winning source is chosen once and restored below: the row's
+ // list when it has one, else whatever this browser held.
+ const extraArgs = Array.isArray(override.llama_extra_args)
+ ? override.llama_extra_args
+ : local.llamaExtraArgs;
+ // Only a physical pin travels (toApiOverride drops the rest), so a row without ids
+ // says nothing about placement and a local Vulkan ordinal keeps its own namespace.
+ const serverGpuIds = override.gpu_ids?.length ? override.gpu_ids : null;
+ const normalized = normalizePerModelConfig({
+ ...DEFAULT_PER_MODEL_CONFIG,
+ customContextLength:
+ override.custom_context_length ?? local.customContextLength,
+ maxSeqLength: override.max_seq_length ?? local.maxSeqLength,
+ kvCacheDtype: override.kv_cache_dtype ?? local.kvCacheDtype,
+ mlxKvBits: override.mlx_kv_bits ?? local.mlxKvBits,
+ speculativeType: override.speculative_type ?? local.speculativeType,
+ specDraftNMax: override.spec_draft_n_max ?? local.specDraftNMax,
+ specDraftCacheDtype:
+ override.spec_draft_cache_type ?? local.specDraftCacheDtype,
+ nParallel: override.n_parallel ?? local.nParallel,
+ nBatch: override.n_batch ?? local.nBatch,
+ nUbatch: override.n_ubatch ?? local.nUbatch,
+ loadMode: override.load_mode ?? local.loadMode,
+ ctxCheckpoints: override.ctx_checkpoints ?? local.ctxCheckpoints,
+ cacheRam: override.cache_ram ?? local.cacheRam,
+ // Both are stored only when true, so an absent one is a gap like any other.
+ tensorParallel: override.tensor_parallel ?? local.tensorParallel,
+ disableVision: override.disable_vision ?? local.disableVision,
+ chatTemplateOverride:
+ override.chat_template_override ?? local.chatTemplateOverride,
+ llamaExtraArgs: extraArgs,
+ gpuMemoryMode: override.gpu_memory_mode ?? local.gpuMemoryMode,
+ gpuLayers: override.gpu_layers ?? local.gpuLayers,
+ nCpuMoe: override.n_cpu_moe ?? local.nCpuMoe,
+ selectedGpuIds: serverGpuIds ?? local.selectedGpuIds ?? null,
+ selectedGpuIndexKind: serverGpuIds
+ ? "physical"
+ : (local.selectedGpuIndexKind ?? null),
+ });
+ // normalizePerModelConfig intentionally collapses an empty list to null. The server
+ // uses [] as a tombstone that stops fallback to a broader override, so hydration
+ // must retain that third state.
+ if (Array.isArray(extraArgs)) {
+ normalized.llamaExtraArgs = [...extraArgs];
+ }
+ return normalized;
}
/**
@@ -427,6 +517,13 @@ async function sendModelOverride(
body: JSON.stringify({
// biome-ignore lint/style/useNamingConvention: API schema
model_id: modelOverrideKey(modelId, ggufVariant),
+ // This build mirrors the llama-server tuning group, so an omission here is the
+ // user clearing it rather than a client that predates the fields. Without this
+ // the backend preserves the stored values, which is what stops a cached older
+ // bundle from deleting settings it never knew to send. An older backend ignores
+ // the key.
+ // biome-ignore lint/style/useNamingConvention: API schema
+ mirrors_server_tuning: true,
// Only sent when set, so an older backend is not handed an unknown key every save.
...(options?.fillAbsentFields
? // biome-ignore lint/style/useNamingConvention: API schema
diff --git a/studio/frontend/src/features/model-picker/components/model-config-page.tsx b/studio/frontend/src/features/model-picker/components/model-config-page.tsx
index 4f12133858b..104bd698a6f 100644
--- a/studio/frontend/src/features/model-picker/components/model-config-page.tsx
+++ b/studio/frontend/src/features/model-picker/components/model-config-page.tsx
@@ -68,7 +68,8 @@ import {
subscribeLlamaFlagCatalog,
} from "../api/llama-flags";
import {
- fetchLoadExtraArgs,
+ fetchLoadModelOverride,
+ fromApiOverride,
modelOverrideKey,
syncModelOverride,
} from "../api/model-overrides";
@@ -143,6 +144,8 @@ const CONTROL_SURFACE =
const SELECT_TRIGGER_CLASS = `grid h-8 min-w-0 grid-cols-[minmax(0,1fr)_auto] items-center gap-1 ${CONTROL_SURFACE} pl-3 pr-2 py-0 text-ui-13! font-medium text-nav-fg focus-visible:ring-0 focus-visible:border-transparent [&_[data-slot=select-value]]:min-w-0 [&_[data-slot=select-value]]:truncate [&>svg]:shrink-0`;
const NUMBER_INPUT_CLASS = `h-8 w-[92px] ${CONTROL_SURFACE} pl-3 pr-2 py-0 text-right text-ui-13 font-medium text-nav-fg outline-none focus-visible:ring-0`;
+// Mirrors the backend's Auto default once GPU-only placement is impossible.
+const AUTO_OFFLOAD_CONTEXT_LENGTH = 8192;
const KV_CACHE_DTYPE_DEFAULT = "f16";
const SPECULATIVE_TYPE_LABELS: Record<
(typeof SPECULATIVE_TYPES)[number],
@@ -1805,6 +1808,8 @@ export function ModelConfigPage({
configRef.current = configState;
const [remember, setRemember] = useState(() => initial.remembered);
const [savedRemember, setSavedRemember] = useState(() => initial.remembered);
+ const rememberRef = useRef(remember);
+ rememberRef.current = remember;
const [speculativeFallback] = useState(readPersistedSpeculativeType);
const [templateOpen, setTemplateOpen] = useState(false);
// Raised by the extra-arguments row when what is typed is something
@@ -2043,10 +2048,10 @@ export function ModelConfigPage({
hiddenCatalogEpoch,
]);
- // Here rather than in the row that displays it: that row is inside Advanced
- // settings, which is not rendered while the section is collapsed, so a panel
- // opened closed would never fetch and a cold load would launch without the stored
- // arguments. The row seeds its textarea from the config either way.
+ // The server copy is shared by Desktop, LAN, and tunnel origins. Hydrate the
+ // whole remembered GGUF config here; localStorage is only the immediate seed.
+ // This also has to run while Advanced is closed because extra arguments live in
+ // that section but affect every load.
const extraArgsHydrated = useRef<string | null>(null);
// biome-ignore lint/correctness/useExhaustiveDependencies: the model is the identity
useEffect(() => {
@@ -2087,7 +2092,18 @@ export function ModelConfigPage({
// it was typed by the user while it was in flight, and sanitizing that would
// rewrite live input: typing --agent during the window cleared the box instead
// of showing the error, and a long paste could be trimmed behind the cursor.
- const localAtStart = configRef.current.llamaExtraArgs;
+ const configAtStart = configRef.current;
+ // What STORAGE holds for this model, which is not always what the panel shows:
+ // an active model seeds the panel from loadedConfig, the config the resident
+ // model is running with. The hydrated record is written against this instead,
+ // or opening the panel replaces settings the user never touched here -- a legacy
+ // config just migrated in, one saved from another origin -- with the runtime.
+ const storedAtStart = resolveInitialConfig(
+ configId,
+ target.ggufVariant,
+ ).config;
+ const rememberAtStart = rememberRef.current;
+ const localAtStart = configAtStart.llamaExtraArgs;
// The denylist, not the catalogue: sanitizing a stored list needs only the flags
// Unsloth refuses, and that route answers without running `llama-server --help`.
// Waiting on the probe instead would hold Load shut for as long as a cold --help
@@ -2099,10 +2115,10 @@ export function ModelConfigPage({
Promise.all([
// Resolved by the backend, which owns the rules: the local resolver stays as
// the fallback for a backend that predates the parameter.
- fetchLoadExtraArgs(loadId, configId, target.ggufVariant, keys),
+ fetchLoadModelOverride(loadId, configId, target.ggufVariant, keys),
loadManagedLlamaFlags(),
])
- .then(([resolvedArgs, managed]) => {
+ .then(([resolvedOverride, managed]) => {
// Marked here rather than before the request: StrictMode replays the effect
// (setup, cleanup, setup), so a key marked up front would leave the first
// fetch cancelled and the second setup returning early, and the box would
@@ -2111,6 +2127,10 @@ export function ModelConfigPage({
return;
}
extraArgsHydrated.current = identity;
+ const resolvedArgs = {
+ tokens: resolvedOverride?.llama_extra_args ?? [],
+ explicit: Array.isArray(resolvedOverride?.llama_extra_args),
+ };
// Through the resolver, not a literal lookup: the backend folds identities
// and reads whole entries in its own order before it reads a field.
//
@@ -2135,6 +2155,10 @@ export function ModelConfigPage({
// is the same treatment for the one already in hand, which nothing else
// would catch while Advanced stays collapsed.
const local = configRef.current.llamaExtraArgs;
+ // Kept for the merge below as well as for the box: a row that carries no
+ // arguments leaves the local list standing, and handing back the list this
+ // build refuses would re-enable Load for a request /load answers 400 on.
+ let sanitizedLocal = localAtStart;
if (local != null && local.length > 0 && local === localAtStart) {
const cleaned = sanitizeStoredExtraArgs(
local,
@@ -2145,13 +2169,121 @@ export function ModelConfigPage({
},
);
if (cleaned.length !== local.length) {
+ sanitizedLocal = cleaned.length > 0 ? cleaned : null;
setConfig((current) =>
current.llamaExtraArgs === local
- ? { ...current, llamaExtraArgs: cleaned.length > 0 ? cleaned : null }
+ ? { ...current, llamaExtraArgs: sanitizedLocal }
: current,
);
}
}
+ // The row as it should be read: its own fields, with the arguments it carries
+ // sanitized against what this build refuses.
+ const resolvedRow = resolvedOverride
+ ? {
+ ...resolvedOverride,
+ ...(resolvedArgs.explicit ? { llama_extra_args: stored } : {}),
+ }
+ : null;
+ const serverConfig = resolvedRow
+ ? fromApiOverride(resolvedRow, {
+ ...configAtStart,
+ llamaExtraArgs: sanitizedLocal,
+ })
+ : null;
+ // What hydration would leave in the config: the row's list when it carries
+ // one, this browser's when it does not, since a row that says nothing about
+ // arguments cannot overrule the list already here. Judged as a whole, or a
+ // local flag the expanded row has ALREADY refused is declared loadable by a
+ // verdict read off the empty server list, and the row republishes its own
+ // only when its verdict changes, so the objection never comes back.
+ const hydratedArgs = serverConfig?.llamaExtraArgs ?? stored;
+ const hydratedIsLoadable =
+ hydratedArgs.length === 0
+ ? true
+ : extraArgsAreLoadable(
+ diagnoseExtraArgs(
+ formatExtraArgs(hydratedArgs),
+ {
+ flags: {},
+ managed: managed?.managed ?? new Set<string>(),
+ switches: new Set<string>(),
+ maxBytes: managed?.maxBytes ?? 0,
+ windowsCommandBudget: managed?.windowsCommandBudget ?? 0,
+ defaultParallelSlots: managed?.defaultParallelSlots ?? 0,
+ parallelSlotsClamped:
+ managed?.parallelSlotsClamped ?? false,
+ probeOk: false,
+ },
+ {
+ batchFloor: effectiveBatchFloor(
+ serverConfig?.nParallel ?? configRef.current.nParallel,
+ managed,
+ ),
+ },
+ ),
+ );
+
+ // The shared row outranks the local seed for every field it carries, so LAN
+ // and Desktop cannot show different remembered values; fromApiOverride keeps
+ // the rest of this browser's config rather than resetting it, since an
+ // absent field is as much a gap in the mirror as a chosen default. Never
+ // over an edit made while the request was in flight.
+ if (
+ resolvedRow &&
+ serverConfig &&
+ configRef.current === configAtStart &&
+ rememberRef.current === rememberAtStart
+ ) {
+ setExtraArgsLoadable(hydratedIsLoadable);
+ setConfig(serverConfig);
+ setRemember(true);
+ setSavedRemember(true);
+ if (hasNonDefaultAdvanced(serverConfig)) {
+ setAutoOpenAdvanced(true);
+ }
+ // Onto the stored record, not the shown one: see storedAtStart. The row
+ // outranks both, so the shared settings still land in local storage for
+ // the load paths that never open this panel.
+ //
+ // Unconditionally, because savePerModelConfig says "no settings" by
+ // DELETING the entry: a merge that comes out default is a clear that has
+ // to travel, not a write to skip. Clearing a model's only remembered
+ // flag leaves the row as an explicit empty list, which is exactly that
+ // case, and skipping it stranded the old flag here for model-selector's
+ // quick select to reload without ever opening this panel. Writing when
+ // no record exists is already a no-op.
+ const rememberedConfig = fromApiOverride(resolvedRow, storedAtStart);
+ // Same budget as any other write, so the same clean-up: eviction is silent
+ // and still reports success, and a dropped model would keep applying its
+ // server row to API loads while the picker showed defaults, with nothing
+ // able to forget it. Not a Forget, only the mirrored fields go.
+ const hydrationEvicted: {
+ modelId: string;
+ ggufVariant: string | null;
+ }[] = [];
+ // Checked for the same reason the Save path checks it: the write can fail
+ // outright (storage full or unavailable, or a record from a newer build that
+ // must not be replaced) and say so in the return rather than throwing. Marked
+ // saved regardless, the panel would claim the server settings are remembered
+ // here while quick select and background loads, which read resolveInitialConfig
+ // and never open this panel, still saw the stale record or none. Leaving it
+ // unsaved makes it a pending change instead, so Save is reachable and reports
+ // the failure the way every other write does.
+ const hydrationSaved = savePerModelConfig(
+ configId,
+ target.ggufVariant,
+ rememberedConfig,
+ hydrationEvicted,
+ );
+ setSavedRemember(hydrationSaved);
+ for (const dropped of hydrationEvicted) {
+ syncModelOverride(dropped.modelId, dropped.ggufVariant, null, {
+ keepLaunchFlags: true,
+ });
+ }
+ return;
+ }
if (stored.length === 0) {
// An EXPLICIT empty row is a decision, not an absence: the settings page
// writes one when the box is cleared for a quant whose bare-repository
@@ -2170,35 +2302,6 @@ export function ModelConfigPage({
}
return;
}
- // Judged here as well as in the row: with Advanced collapsed the row never
- // mounts, so nothing would object to a stored list this build refuses (an
- // override written through the API is only structurally validated), and
- // Load would be live for a request that comes back 400. The managed set is
- // enough for that: the value checks do not need the binary's catalogue.
- const hydratedIsLoadable = extraArgsAreLoadable(
- diagnoseExtraArgs(formatExtraArgs(stored), {
- flags: {},
- managed: managed?.managed ?? new Set<string>(),
- // Read without the probe, so nothing here knows which flags are
- // switches, and nothing may be called a typo either.
- switches: new Set<string>(),
- maxBytes: managed?.maxBytes ?? 0,
- windowsCommandBudget: managed?.windowsCommandBudget ?? 0,
- defaultParallelSlots: managed?.defaultParallelSlots ?? 0,
- // Carried from the managed-only read, which knows it: a build that
- // serves one slot however many are asked for floors the batch at 2,
- // and hydration must judge a stored list the same way the row does.
- parallelSlotsClamped: managed?.parallelSlotsClamped ?? false,
- probeOk: false,
- },
- {
- // The slot floor is already known here, and the backend refuses a batch
- // below it deterministically. Left out, this released Load on a stored
- // "--batch-size 2" against a four-slot server, and a click in the window
- // before the full catalogue check lands reaches that 400.
- batchFloor: effectiveBatchFloor(configRef.current.nParallel, managed),
- }),
- );
// Read from a ref rather than inside the updater below: an updater must stay
// free of side effects (StrictMode calls it twice), and this decides one.
if (configRef.current.llamaExtraArgs !== undefined) {
@@ -2235,7 +2338,13 @@ export function ModelConfigPage({
cancelled = true;
clearTimeout(release);
};
- }, [configId, target.id, target.ggufVariant, target.isGguf, resolvedIsDiffusion]);
+ }, [
+ configId,
+ target.id,
+ target.ggufVariant,
+ target.isGguf,
+ resolvedIsDiffusion,
+ ]);
const config = reconcileConfigGpuSelection(
configState,
resolvedIsDiffusion,
@@ -2305,18 +2414,28 @@ export function ModelConfigPage({
),
maxContext,
);
+ const contextIsAuto = config.customContextLength == null;
+ const contextInputValue = contextIsAuto
+ ? Math.min(
+ Math.max(
+ activeLoadedContext ?? AUTO_OFFLOAD_CONTEXT_LENGTH,
+ minContext,
+ ),
+ maxContext,
+ )
+ : contextValue;
+ const contextSliderValue = contextIsAuto ? 0 : contextValue;
const setContextLength = (v: number) => update({ customContextLength: v });
+ const setContextSliderValue = (v: number) =>
+ update({ customContextLength: v === 0 ? null : v });
const rawBaseline = loadedConfig ?? DEFAULT_PER_MODEL_CONFIG;
const baseline = resolvedIsDiffusion
? withoutUnsupportedDiffusionSettings(rawBaseline, gpuIndexKind)
: rawBaseline;
const atBaseline = perModelConfigsEqual(config, baseline);
- // An explicit customContextLength equal to the native ceiling is still an override (Reset stays
- // enabled). "At default" means no override at all AND the shown context matches native.
- const contextAtDefault =
- !target.isGguf ||
- (config.customContextLength == null &&
- (nativeContextLength == null || contextValue === nativeContextLength));
+ // The fitted value is an outcome, not an override. Auto stays at the default even
+ // when a loaded model reports less than its native context.
+ const contextAtDefault = !target.isGguf || config.customContextLength == null;
const atDefault =
contextAtDefault &&
perModelConfigsEqual(
@@ -2584,7 +2703,13 @@ export function ModelConfigPage({
<div className="flex min-w-0 items-center gap-1.5">
<span className={LABEL_CLASS}>Context Length</span>
<InfoHint>
- Tokens of context to allocate. Higher uses more VRAM.
+ Drag all the way left for Auto, which chooses a context that
+ fits while prioritizing GPU speed. Custom values request an
+ exact context; higher values use more memory and may move
+ model layers to system RAM.
+ {contextIsAuto && activeLoadedContext != null
+ ? ` Auto currently selected ${activeLoadedContext.toLocaleString()} tokens.`
+ : ""}
{nativeContextLength != null
? ` This model's native context is ${nativeContextLength.toLocaleString()} tokens.`
: ""}
@@ -2592,39 +2717,48 @@ export function ModelConfigPage({
</div>
<NumericValueInput
ref={contextInputRef}
- value={contextValue}
+ value={contextInputValue}
min={minContext}
max={maxContext}
step={1}
onChange={setContextLength}
- displayValue={
- config.customContextLength == null &&
- nativeContextLength == null &&
- activeLoadedContext == null
- ? "Auto"
- : undefined
- }
+ displayValue={contextIsAuto ? "Auto" : undefined}
ariaLabel="Context Length"
className={NUMBER_INPUT_CLASS}
size={8}
/>
</div>
{nativeContextLength != null ? (
- <Slider
- min={minContext}
- max={maxContext}
- step={128}
- value={[contextValue]}
- onValueChange={([v]) => setContextLength(v)}
- className="panel-slider"
- aria-label="Context Length"
- />
+ <div className="space-y-1.5">
+ <Slider
+ min={0}
+ max={maxContext}
+ step={128}
+ value={[contextSliderValue]}
+ onValueChange={([v]) => setContextSliderValue(v)}
+ className="panel-slider"
+ aria-label="Context Length"
+ // Position 0 is Auto, not a zero-token context, so
+ // aria-valuenow alone reads as a length no model has. The
+ // number is only spoken once one exists: before a load
+ // contextInputValue is the offload fallback used to seed the
+ // input, not a selection, and Auto may still fit native.
+ thumbValueText={(v) =>
+ v !== 0
+ ? `${v.toLocaleString()} tokens`
+ : activeLoadedContext != null
+ ? `Auto, currently ${contextInputValue.toLocaleString()} tokens`
+ : "Auto"
+ }
+ />
+ <div className="flex justify-between text-ui-10 text-muted-foreground">
+ <span>Auto</span>
+ <span>{maxContext.toLocaleString()}</span>
+ </div>
+ </div>
) : null}
- <p className="text-ui-11 leading-relaxed text-muted-foreground">
- Unsloth automatically fits the context to your device, using the
- full context when memory allows.
- </p>
- {isActiveModel &&
+ {!contextIsAuto &&
+ isActiveModel &&
loadedMaxContextLength != null &&
contextValue > loadedMaxContextLength && (
<p className="text-ui-11 text-amber-500">
diff --git a/studio/frontend/src/features/model-picker/model-config/per-model-config.ts b/studio/frontend/src/features/model-picker/model-config/per-model-config.ts
index 839fdae3900..02c261e9e3c 100644
--- a/studio/frontend/src/features/model-picker/model-config/per-model-config.ts
+++ b/studio/frontend/src/features/model-picker/model-config/per-model-config.ts
@@ -994,6 +994,15 @@ export function isDefaultConfig(config: PerModelConfig): boolean {
config.nParallel == null &&
config.nBatch == null &&
config.nUbatch == null &&
+ // The llama-server tuning group, for the same reason as the arguments below:
+ // savePerModelConfig deletes an entry it judges default, so a config whose only
+ // change was one of these was dropped on the way to storage while the settings
+ // page reported that defaults were kept. Compared against null, not truth: 0
+ // checkpoints and a 0 or -1 cache are values, not blanks.
+ (config.specDraftCacheDtype ?? null) === null &&
+ (config.loadMode ?? null) === null &&
+ config.ctxCheckpoints == null &&
+ config.cacheRam == null &&
Boolean(config.tensorParallel) ===
Boolean(DEFAULT_PER_MODEL_CONFIG.tensorParallel) &&
Boolean(config.disableVision) ===
diff --git a/studio/frontend/tests/context-mode-ux.test.ts b/studio/frontend/tests/context-mode-ux.test.ts
new file mode 100644
index 00000000000..0072f1c73a3
--- /dev/null
+++ b/studio/frontend/tests/context-mode-ux.test.ts
@@ -0,0 +1,69 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import path from "node:path";
+import { test } from "node:test";
+import { fileURLToPath } from "node:url";
+
+const here = path.dirname(fileURLToPath(import.meta.url));
+const panel = readFileSync(
+ path.join(
+ here,
+ "..",
+ "src/features/model-picker/components/model-config-page.tsx",
+ ),
+ "utf8",
+);
+const panelCode = panel.replace(/\s+/g, " ");
+
+test("the far-left slider position is Auto", () => {
+ assert.match(
+ panelCode,
+ /const contextIsAuto = config\.customContextLength == null;/,
+ );
+ assert.match(
+ panelCode,
+ /const contextSliderValue = contextIsAuto \? 0 : contextValue/,
+ );
+ assert.match(panelCode, /<Slider min=\{0\}/);
+ assert.match(panelCode, /customContextLength: v === 0 \? null : v/);
+ assert.match(panelCode, /<span>Auto<\/span>/);
+});
+
+test("moving right or typing a number creates a custom context", () => {
+ assert.match(
+ panelCode,
+ /onValueChange=\{\(\[v\]\) => setContextSliderValue\(v\)\}/,
+ );
+ assert.match(
+ panelCode,
+ /const setContextLength = \(v: number\) => update\(\{ customContextLength: v \}\)/,
+ );
+ assert.match(
+ panelCode,
+ /displayValue=\{contextIsAuto \? "Auto" : undefined\}/,
+ );
+ assert.doesNotMatch(panelCode, /ariaLabel="Context length mode"/);
+});
+
+test("the Auto number editor opens at the fitted or safe offload context", () => {
+ assert.match(
+ panelCode,
+ /activeLoadedContext \?\? AUTO_OFFLOAD_CONTEXT_LENGTH/,
+ );
+ assert.match(panelCode, /const AUTO_OFFLOAD_CONTEXT_LENGTH = 8192;/);
+});
+
+test("the existing info hint owns the mode explanation and fitted result", () => {
+ assert.match(
+ panelCode,
+ /<InfoHint> Drag all the way left for Auto,[\s\S]*Custom values request an exact context;[\s\S]*Auto currently selected \$\{activeLoadedContext\.toLocaleString\(\)\} tokens\.[\s\S]*<\/InfoHint>/,
+ );
+ assert.match(panelCode, /\{!contextIsAuto && isActiveModel/);
+ assert.doesNotMatch(
+ panelCode,
+ /<p className="text-ui-11 leading-relaxed text-muted-foreground">/,
+ );
+});
diff --git a/studio/frontend/tests/hydration-clears-stale-local-record.test.ts b/studio/frontend/tests/hydration-clears-stale-local-record.test.ts
new file mode 100644
index 00000000000..c3d369d12e0
--- /dev/null
+++ b/studio/frontend/tests/hydration-clears-stale-local-record.test.ts
@@ -0,0 +1,169 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Hydration must be able to CLEAR a local record, not only overwrite one.
+//
+// savePerModelConfig says "no settings" by deleting the entry, so a merge that comes
+// out default IS the clear. Skipping the write there strands the old value, and
+// model-selector's quick select reads it via resolveInitialConfig without opening the
+// panel, handing a flag cleared on another origin back to the next launch.
+//
+// Reachable shape: a model whose only setting is its extra arguments. Clearing them
+// leaves an explicit empty list, which is a default config.
+
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import test from "node:test";
+
+import { installLocalStorageFake, registerStoreStubResolver } from "./helpers/kit.ts";
+
+registerStoreStubResolver();
+const { storage } = installLocalStorageFake();
+
+const { fromApiOverride } = await import(
+ "../src/features/model-picker/api/model-overrides.ts"
+);
+const {
+ DEFAULT_PER_MODEL_CONFIG,
+ isDefaultConfig,
+ resolveInitialConfig,
+ savePerModelConfig,
+} = await import("../src/features/model-picker/model-config/per-model-config.ts");
+
+const MODEL = "unsloth/Model-GGUF";
+const VARIANT = "q4_k_m";
+
+test("an explicit server clear leaves a config the panel must still persist", () => {
+ // What this browser remembers: one flag, nothing else.
+ const stored = { ...DEFAULT_PER_MODEL_CONFIG, llamaExtraArgs: ["--flash-attn"] };
+ // What another origin left behind after clearing it. [] is the tombstone the
+ // route uses for an explicit clear, distinct from an absent field.
+ const merged = fromApiOverride({ llama_extra_args: [] }, stored);
+
+ assert.deepEqual(merged.llamaExtraArgs, [], "the clear must survive the merge");
+ // And the merged config is default, which is what makes the write conditional
+ // on !isDefaultConfig skip precisely the case that needs to travel.
+ assert.equal(isDefaultConfig(merged), true);
+});
+
+test("persisting that config removes the stale entry rather than keeping it", () => {
+ savePerModelConfig(MODEL, VARIANT, {
+ ...DEFAULT_PER_MODEL_CONFIG,
+ llamaExtraArgs: ["--flash-attn"],
+ });
+ assert.deepEqual(
+ resolveInitialConfig(MODEL, VARIANT).config.llamaExtraArgs,
+ ["--flash-attn"],
+ "precondition: the stale record exists",
+ );
+
+ const merged = fromApiOverride(
+ { llama_extra_args: [] },
+ resolveInitialConfig(MODEL, VARIANT).config,
+ );
+ savePerModelConfig(MODEL, VARIANT, merged);
+
+ const after = resolveInitialConfig(MODEL, VARIANT);
+ assert.equal(
+ after.remembered,
+ false,
+ "the cleared flag must not survive for quick select to reload",
+ );
+ assert.ok(
+ after.config.llamaExtraArgs == null ||
+ after.config.llamaExtraArgs.length === 0,
+ );
+});
+
+test("the hydration write is not gated on the merge being non-default", () => {
+ // The guard is what decides whether the clear reaches storage at all, so assert
+ // it at the source. savePerModelConfig already no-ops when there is nothing to
+ // delete, which is why it does not need a caller-side default check.
+ const panel = new URL(
+ "../src/features/model-picker/components/model-config-page.tsx",
+ import.meta.url,
+ );
+ const src = readFileSync(panel, "utf8").replace(/\s+/g, " ");
+ assert.doesNotMatch(
+ src,
+ /if \(!isDefaultConfig\(rememberedConfig\)\) \{ savePerModelConfig\(/,
+ "a default merge is exactly the clear that has to be written",
+ );
+});
+
+test("a hydration write can fail, and says so in its return rather than throwing", () => {
+ // The failure the panel has to notice. savePerModelConfig returns false for a full
+ // or unavailable store and for a record from a newer build it must not replace; it
+ // does not throw, so an unchecked call is indistinguishable from a successful one.
+ savePerModelConfig(MODEL, VARIANT, {
+ ...DEFAULT_PER_MODEL_CONFIG,
+ llamaExtraArgs: ["--flash-attn"],
+ });
+ const original = storage.setItem;
+ storage.setItem = () => {
+ // What a browser raises at the quota, and Safari in private mode on any write.
+ throw new DOMException("QuotaExceededError", "QuotaExceededError");
+ };
+ try {
+ assert.equal(
+ savePerModelConfig(MODEL, VARIANT, {
+ ...DEFAULT_PER_MODEL_CONFIG,
+ llamaExtraArgs: ["--numa", "distribute"],
+ }),
+ false,
+ "a failed write has to be reported, not swallowed",
+ );
+ } finally {
+ storage.setItem = original;
+ }
+ // And the record the panel would be claiming to have replaced is still the old one.
+ assert.deepEqual(resolveInitialConfig(MODEL, VARIANT).config.llamaExtraArgs, [
+ "--flash-attn",
+ ]);
+});
+
+test("hydration does not mark itself saved when the write failed", () => {
+ // setRemember/setSavedRemember run before the write, so an ignored false left the
+ // panel claiming the server settings were remembered while quick select and
+ // background loads -- which read resolveInitialConfig and never open this panel --
+ // still saw the stale record or none at all. Feeding the result back in makes it a
+ // pending change instead, which is what puts Save (and its error toast) in reach.
+ const src = readFileSync(
+ new URL(
+ "../src/features/model-picker/components/model-config-page.tsx",
+ import.meta.url,
+ ),
+ "utf8",
+ ).replace(/\s+/g, " ");
+
+ assert.match(
+ src,
+ /const hydrationSaved = savePerModelConfig\( configId, target\.ggufVariant, rememberedConfig, hydrationEvicted, \); setSavedRemember\(hydrationSaved\);/,
+ );
+});
+
+test("hydration propagates what its own write evicted", () => {
+ // Storage is capped at 500 entries and 1 MiB, and savePerModelConfig evicts to stay
+ // inside it, silently, still reporting success. The save handler collects those and
+ // clears their mirrored fields; hydration writes through the same budget, so a model
+ // dropped here would keep applying its server row to API loads while quick select
+ // read defaults for it, with nothing in the UI able to forget it.
+ const src = readFileSync(
+ new URL(
+ "../src/features/model-picker/components/model-config-page.tsx",
+ import.meta.url,
+ ),
+ "utf8",
+ ).replace(/\s+/g, " ");
+
+ // The write hands savePerModelConfig somewhere to report evictions.
+ assert.match(
+ src,
+ /savePerModelConfig\( configId, target\.ggufVariant, rememberedConfig, hydrationEvicted, \)/,
+ );
+ // And they are cleared the way the save path clears them: mirrored fields only.
+ assert.match(
+ src,
+ /for \(const dropped of hydrationEvicted\) \{ syncModelOverride\(dropped\.modelId, dropped\.ggufVariant, null, \{ keepLaunchFlags: true, \}\); \}/,
+ );
+});
diff --git a/studio/frontend/tests/llama-extra-args-diagnostics.test.ts b/studio/frontend/tests/llama-extra-args-diagnostics.test.ts
index 2357ee7a4fe..e0e0a10415d 100644
--- a/studio/frontend/tests/llama-extra-args-diagnostics.test.ts
+++ b/studio/frontend/tests/llama-extra-args-diagnostics.test.ts
@@ -600,7 +600,10 @@ test("the box is filled from the stored flags, not left looking empty", () => {
// set is to ask. An empty box would read as "no flags" and the first edit would
// submit a list that dropped them.
// Resolved by the backend, whose folding rules are the ones the load applies.
- assert.match(body, /fetchLoadExtraArgs\(loadId, configId, target\.ggufVariant, keys\)/);
+ assert.match(
+ body,
+ /fetchLoadModelOverride\(loadId, configId, target\.ggufVariant, keys\)/,
+ );
// Through the resolver, not a literal lookup: the backend folds identities and
// falls back from repo:QUANT to the bare repo before it reads a row.
// The candidate keys still travel, as the fallback for a backend that predates
@@ -821,7 +824,20 @@ test("a hydrated list is judged even when the row cannot be", () => {
// With Advanced collapsed the row never mounts, so nothing objects to a stored
// list this build refuses (the overrides route only validates its shape), and
// Load would be live for a request that comes back 400.
- assert.match(body, /const hydratedIsLoadable = extraArgsAreLoadable\( diagnoseExtraArgs\(formatExtraArgs\(stored\)/);
+ //
+ // Judged on the list hydration ADOPTS, not on the row's: a row carrying no
+ // arguments leaves the local ones standing, and reading the verdict off the empty
+ // server list called them loadable. That one lands even with Advanced expanded,
+ // where the row has already refused the list and republishes only on a change of
+ // its own verdict, so nothing puts the objection back.
+ assert.match(
+ body,
+ /const hydratedArgs = serverConfig\?\.llamaExtraArgs \?\? stored;/,
+ );
+ assert.match(
+ body,
+ /const hydratedIsLoadable = hydratedArgs\.length === 0 \? true : extraArgsAreLoadable\( diagnoseExtraArgs\( formatExtraArgs\(hydratedArgs\)/,
+ );
// But not over an edit made while the request was out: the row is judging that
// text, and replacing its verdict re-enabled Load for invalid input.
assert.match(
diff --git a/studio/frontend/tests/llama-extra-args-override-lookup.test.ts b/studio/frontend/tests/llama-extra-args-override-lookup.test.ts
index b9b716142b9..f5356522fd9 100644
--- a/studio/frontend/tests/llama-extra-args-override-lookup.test.ts
+++ b/studio/frontend/tests/llama-extra-args-override-lookup.test.ts
@@ -19,9 +19,8 @@ import { registerStoreStubResolver } from "./helpers/kit.ts";
registerStoreStubResolver();
-const { resolveStoredExtraArgs } = await import(
- "../src/features/model-picker/api/model-overrides.ts"
-);
+const { fromApiOverride, resolveStoredExtraArgs, resolveStoredOverride } =
+ await import("../src/features/model-picker/api/model-overrides.ts");
const ARGS = ["--numa", "distribute"];
@@ -209,3 +208,87 @@ test("a matched row with other fields but no arguments is not explicit", () => {
{ tokens: [], explicit: false },
);
});
+
+test("the full resolved row uses the same identity rules as extra arguments", () => {
+ const row = {
+ custom_context_length: 32768,
+ kv_cache_dtype: "q8_0",
+ };
+ assert.equal(
+ resolveStoredOverride({ "unsloth/Model-GGUF:Q4_K_M": row }, [
+ "unsloth/model-gguf:q4_k_m",
+ ]),
+ row,
+ );
+});
+
+test("a server override converts into one normalized picker config", () => {
+ const config = fromApiOverride({
+ custom_context_length: 32768,
+ kv_cache_dtype: "q8_0",
+ n_parallel: 4,
+ gpu_memory_mode: "manual",
+ gpu_layers: 20,
+ gpu_ids: [1],
+ llama_extra_args: [],
+ });
+ assert.equal(config.customContextLength, 32768);
+ assert.equal(config.kvCacheDtype, "q8_0");
+ assert.equal(config.nParallel, 4);
+ assert.equal(config.gpuMemoryMode, "manual");
+ assert.equal(config.gpuLayers, 20);
+ assert.deepEqual(config.selectedGpuIds, [1]);
+ assert.equal(config.selectedGpuIndexKind, "physical");
+ assert.deepEqual(config.llamaExtraArgs, []);
+});
+
+test("server hydration preserves a local Vulkan ordinal pin", () => {
+ const local = fromApiOverride({});
+ local.selectedGpuIds = [1];
+ local.selectedGpuIndexKind = "vulkan";
+
+ const config = fromApiOverride({ kv_cache_dtype: "q8_0" }, local);
+ assert.equal(config.kvCacheDtype, "q8_0");
+ assert.deepEqual(config.selectedGpuIds, [1]);
+ assert.equal(config.selectedGpuIndexKind, "vulkan");
+});
+
+test("a server physical GPU pin replaces a local Vulkan pin", () => {
+ const local = fromApiOverride({});
+ local.selectedGpuIds = [1];
+ local.selectedGpuIndexKind = "vulkan";
+
+ const config = fromApiOverride({ gpu_ids: [0] }, local);
+ assert.deepEqual(config.selectedGpuIds, [0]);
+ assert.equal(config.selectedGpuIndexKind, "physical");
+});
+
+test("a row that carries less than the local config does not erase the rest", () => {
+ // The mirror is best-effort: a PUT that never landed, a legacy config migrated
+ // into this browser, a field the backend normalizer refused. Hydration adopting
+ // the row wholesale wrote those gaps back over the local copy and persisted it,
+ // so a remembered context disappeared on the next panel open.
+ const local = fromApiOverride({
+ custom_context_length: 4096,
+ kv_cache_dtype: "q8_0",
+ });
+ const config = fromApiOverride({ tensor_parallel: true }, local);
+ assert.equal(config.customContextLength, 4096);
+ assert.equal(config.kvCacheDtype, "q8_0");
+ assert.equal(config.tensorParallel, true);
+});
+
+test("the row still wins for every field it does carry", () => {
+ const local = fromApiOverride({ custom_context_length: 4096 });
+ const config = fromApiOverride({ custom_context_length: 32768 }, local);
+ assert.equal(config.customContextLength, 32768);
+});
+
+test("a cleared extra-arguments box survives a row that carries no arguments", () => {
+ // [] is a decision (the box was emptied) and stops the fallback to a broader row,
+ // so it must not come back as "never read" because the row said nothing.
+ const local = fromApiOverride({ llama_extra_args: [] });
+ assert.deepEqual(local.llamaExtraArgs, []);
+ const config = fromApiOverride({ kv_cache_dtype: "q8_0" }, local);
+ assert.deepEqual(config.llamaExtraArgs, []);
+});
diff --git a/studio/frontend/tests/llama-extra-args-panel-hydration.test.ts b/studio/frontend/tests/llama-extra-args-panel-hydration.test.ts
index 243ec46a60a..f23512c8f4b 100644
--- a/studio/frontend/tests/llama-extra-args-panel-hydration.test.ts
+++ b/studio/frontend/tests/llama-extra-args-panel-hydration.test.ts
@@ -27,8 +27,11 @@ test("a list typed while hydration was in flight is not sanitized", () => {
// refuses. But if the user typed during the window, that value is live input:
// rewriting it cleared the box on "--agent" instead of showing the error, and could
// trim a long paste behind the cursor. The snapshot tells the two apart.
- assert.match(PANEL, /const localAtStart = configRef\.current\.llamaExtraArgs;/);
- assert.match(PANEL, /local !== null && local\.length > 0 && local === localAtStart|local != null && local\.length > 0 && local === localAtStart/);
+ assert.match(PANEL, /const localAtStart = configAtStart\.llamaExtraArgs;/);
+ assert.match(
+ PANEL,
+ /local !== null && local\.length > 0 && local === localAtStart|local != null && local\.length > 0 && local === localAtStart/,
+ );
});
test("a collapsed section is re-judged once the catalogue lands", () => {
@@ -36,7 +39,10 @@ test("a collapsed section is re-judged once the catalogue lands", () => {
// still go out with the load. A verdict reached before the probe answered did not
// know which flags this build documents, and collapsing froze it: a bare --threads
// kept Load enabled and failed at llama-server startup instead.
- assert.match(PANEL, /if \(showAdvanced \|\| !target\.isGguf \|\| resolvedIsDiffusion\) \{/);
+ assert.match(
+ PANEL,
+ /if \(showAdvanced \|\| !target\.isGguf \|\| resolvedIsDiffusion\) \{/,
+ );
assert.match(PANEL, /loadLlamaFlagCatalog\(\)\.then\(\(catalog\) => \{/);
});
@@ -119,7 +125,10 @@ test("the hidden validation re-runs when the binary changes", () => {
// The row's own subscription cannot help here: it is unmounted whenever this
// check is the one running, so an in-app llama.cpp update with Advanced collapsed
// left a verdict reached against the previous binary standing.
- assert.match(PANEL, /subscribeLlamaFlagCatalog\(\(\) =>\s*\n?\s*setHiddenCatalogEpoch/);
+ assert.match(
+ PANEL,
+ /subscribeLlamaFlagCatalog\(\(\) =>\s*\n?\s*setHiddenCatalogEpoch/,
+ );
assert.match(PANEL, /hiddenCatalogEpoch,\n\s*\]\);/);
});
@@ -144,10 +153,54 @@ test("the hidden hydration check knows the slot floor", () => {
// reaches that 400.
assert.match(
PANEL,
- /batchFloor: effectiveBatchFloor\(configRef\.current\.nParallel, managed\)/,
+ /serverConfig\?\.nParallel \?\? configRef\.current\.nParallel/,
);
});
+test("the panel adopts a shared server config without overwriting a live edit", () => {
+ assert.match(PANEL, /fetchLoadModelOverride\(/);
+ assert.match(
+ PANEL,
+ /const serverConfig = resolvedRow\s*\n?\s*\? fromApiOverride\(resolvedRow, \{/,
+ );
+ // The panel's config is the merge base for what it SHOWS, so a field the row does
+ // not carry keeps the value this browser holds instead of coming back as an app
+ // default. It travels sanitized: a row that says nothing about arguments leaves
+ // the local list standing, and a flag this build refuses would re-enable Load for
+ // a 400.
+ assert.match(
+ PANEL,
+ /\.\.\.configAtStart,\s*\n?\s*llamaExtraArgs: sanitizedLocal,/,
+ );
+ assert.match(PANEL, /let sanitizedLocal = localAtStart;/);
+ assert.match(
+ PANEL,
+ /sanitizedLocal = cleaned\.length > 0 \? cleaned : null;/,
+ );
+ // What it WRITES is merged onto the stored record instead. An active model seeds
+ // the panel from loadedConfig, so persisting the shown config replaced remembered
+ // settings this browser never touched (a just-migrated legacy config among them)
+ // with whatever the resident model is running.
+ assert.match(
+ PANEL,
+ /const storedAtStart = resolveInitialConfig\(\s*\n?\s*configId,\s*\n?\s*target\.ggufVariant,\s*\n?\s*\)\.config;/,
+ );
+ assert.match(
+ PANEL,
+ /const rememberedConfig = fromApiOverride\(resolvedRow, storedAtStart\);/,
+ );
+ // Whitespace-tolerant: the call carries an eviction list now, so it spans lines.
+ assert.match(
+ PANEL,
+ /savePerModelConfig\(\s*configId,\s*target\.ggufVariant,\s*rememberedConfig,/,
+ );
+ assert.match(PANEL, /configRef\.current === configAtStart/);
+ assert.match(PANEL, /rememberRef\.current === rememberAtStart/);
+ assert.match(PANEL, /setConfig\(serverConfig\);/);
+ assert.match(PANEL, /setRemember\(true\);/);
+ assert.match(PANEL, /setSavedRemember\(true\);/);
+});
+
test("a build that serves one slot does not raise the floor", () => {
// The published default is already effective, but an EXPLICIT Slots value is not:
// a build without --kv-unified serves one slot however many are asked for, so
@@ -191,7 +244,7 @@ test("a stored empty list hydrates as a clear, not as nothing stored", () => {
// callers left llamaExtraArgs undefined, omitted the field on /load, and the
// route carried the resident model's arguments over, the ones just cleared.
assert.match(OVERRIDES, /explicit: Array\.isArray\(tokens\)/);
- assert.match(OVERRIDES, /return \{ tokens: \[\], explicit: false \};/);
+ assert.match(OVERRIDES, /\{ tokens: \[\], explicit: false \}/);
assert.match(PANEL, /resolvedArgs\.explicit && local === undefined/);
assert.match(ADAPTER, /\} else if \(stored\.explicit\) \{/);
assert.match(COMPOSER, /\} else if \(resolvedArgs\.explicit\) \{/);
@@ -207,9 +260,18 @@ test("a launch that only applies the remembered config still carries its argumen
// inherits them from the SAME resident model, so a cold launch or a switch from
// another model ran without the arguments this model was remembered with. Both
// paths that load through the runtime alone now pass the config itself.
- assert.match(HUB, /\.\.\.\(rememberedConfig \? \{ config: rememberedConfig \} : \{\}\),/);
- assert.match(CHAT_PAGE, /const remembered = rememberedConfigFor\(selection\);/);
- assert.match(CHAT_PAGE, /\.\.\.\(remembered \? \{ config: remembered \} : \{\}\),/);
+ assert.match(
+ HUB,
+ /\.\.\.\(rememberedConfig \? \{ config: rememberedConfig \} : \{\}\),/,
+ );
+ assert.match(
+ CHAT_PAGE,
+ /const remembered = rememberedConfigFor\(selection\);/,
+ );
+ assert.match(
+ CHAT_PAGE,
+ /\.\.\.\(remembered \? \{ config: remembered \} : \{\}\),/,
+ );
// Nothing is invented when there is no remembered config: the field stays absent,
// which is what lets /load keep a resident model's own flags.
assert.doesNotMatch(HUB, /config: rememberedConfig \?\? null/);
diff --git a/studio/frontend/tests/server-tuning-settings.test.ts b/studio/frontend/tests/server-tuning-settings.test.ts
index 7bda7e2f7e5..b526e5adae4 100644
--- a/studio/frontend/tests/server-tuning-settings.test.ts
+++ b/studio/frontend/tests/server-tuning-settings.test.ts
@@ -19,8 +19,10 @@ const {
CACHE_RAM_MAX,
CACHE_RAM_MIN,
CTX_CHECKPOINTS_MAX,
+ DEFAULT_PER_MODEL_CONFIG,
LOAD_MODES,
canonicalizeLoadMode,
+ isDefaultConfig,
normalizeCacheRam,
normalizeCtxCheckpoints,
normalizePerModelConfig,
@@ -198,3 +200,27 @@ test("the load mode is reported as removed, not as winning, under Model Memory",
messages.join(" "),
);
});
+
+test("a config whose only change is one of the four is not read as default", () => {
+ // savePerModelConfig DELETES an entry it judges default, so a tuning-only save
+ // never reached storage: Run settings reported that defaults were kept and
+ // unticked Remember, while the server row it had just mirrored held the value.
+ for (const patch of [
+ { loadMode: "mmap" },
+ { specDraftCacheDtype: "q8_0", speculativeType: "dspark" },
+ { ctxCheckpoints: 0 },
+ { ctxCheckpoints: 64 },
+ { cacheRam: 0 },
+ { cacheRam: -1 },
+ ]) {
+ const config = normalizePerModelConfig({
+ ...DEFAULT_PER_MODEL_CONFIG,
+ ...patch,
+ });
+ assert.equal(isDefaultConfig(config), false, JSON.stringify(patch));
+ }
+ assert.equal(
+ isDefaultConfig(normalizePerModelConfig({ ...DEFAULT_PER_MODEL_CONFIG })),
+ true,
+ );
+});
diff --git a/studio/frontend/tests/server-tuning-upgrade-downgrade-compat.test.ts b/studio/frontend/tests/server-tuning-upgrade-downgrade-compat.test.ts
new file mode 100644
index 00000000000..3a09a5252ac
--- /dev/null
+++ b/studio/frontend/tests/server-tuning-upgrade-downgrade-compat.test.ts
@@ -0,0 +1,671 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// S2 for the llama-server tuning group: no user setting may be lost on any upgrade
+// or downgrade path, and no client may destroy a record it cannot read. Hidden is
+// acceptable, lost is not.
+//
+// Two directions changed at once. The four fields (load mode, draft KV dtype,
+// checkpoints, cache RAM) stopped being judged default, so they reach storage at
+// all; and the server row became authoritative on panel open. Together they move
+// data across builds, across origins, and into a backfill that used to skip it.
+//
+// There is no migration step, so each direction holds on its own: the version stamp
+// is a downgrade LOCK, correct only while toStoredConfig stamps the OLDEST version
+// that understands the record.
+
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import path from "node:path";
+import test from "node:test";
+import { fileURLToPath } from "node:url";
+
+import type { PerModelConfig } from "../src/features/model-picker/model-config/per-model-config.ts";
+import type { StorageFake } from "./helpers/kit.ts";
+import {
+ installLocalStorageFake,
+ registerStoreStubResolver,
+} from "./helpers/kit.ts";
+
+registerStoreStubResolver();
+const { store, storage } = installLocalStorageFake();
+
+const {
+ DEFAULT_PER_MODEL_CONFIG,
+ deletePerModelConfig,
+ isDefaultConfig,
+ listPerModelConfigs,
+ normalizePerModelConfig,
+ resolveInitialConfig,
+ savePerModelConfig,
+} = await import(
+ "../src/features/model-picker/model-config/per-model-config.ts"
+);
+const { fromApiOverride, resolveStoredOverride, toApiOverride } = await import(
+ "../src/features/model-picker/api/model-overrides.ts"
+);
+const { backfillModelOverrides } = await import(
+ "../src/features/model-picker/api/migrate-model-overrides.ts"
+);
+const { setAuthFetchHandler } = await import("./helpers/store-stubs/auth.ts");
+
+const STORAGE_KEY = "unsloth_model_configs";
+const BACKFILL_FLAG = "unsloth_model_overrides_backfilled_v1";
+const MODEL = "unsloth/Repo-GGUF";
+const VARIANT = "Q4_K_M";
+
+// Ceiling shipped by the last build BEFORE the group. A record stamped at or below
+// it is readable, and therefore erasable, by that build.
+const PRE_TUNING_CEILING = 4;
+
+// Each of the four on its own, at a value a user can actually choose. The falsy ones
+// are in here deliberately: 0 checkpoints and a 0 or -1 cache are decisions, and a
+// version stamp or a default check written against truth passes without them.
+const TUNING_ONLY_PATCHES: Partial<PerModelConfig>[] = [
+ { loadMode: "mmap" },
+ { ctxCheckpoints: 0 },
+ { ctxCheckpoints: 64 },
+ { cacheRam: 0 },
+ { cacheRam: -1 },
+ // The dtype is tied to a mode that loads a separate drafter, so it cannot be the
+ // sole difference from default; the mode travels with it.
+ { specDraftCacheDtype: "q8_0", speculativeType: "dspark" },
+];
+
+function config(overrides: Partial<PerModelConfig> = {}): PerModelConfig {
+ return { ...DEFAULT_PER_MODEL_CONFIG, ...overrides };
+}
+
+function readMap(): Record<string, Record<string, unknown>> {
+ return JSON.parse(store.get(STORAGE_KEY) ?? "{}");
+}
+
+function writeMap(map: Record<string, unknown>): void {
+ store.set(STORAGE_KEY, JSON.stringify(map));
+}
+
+function onlyEntry(): Record<string, unknown> {
+ const entries = Object.values(readMap());
+ assert.equal(entries.length, 1, `expected one record, got ${entries.length}`);
+ return entries[0];
+}
+
+/** resolveInitialConfig is the public read path; loadPerModelConfig is module-private. */
+function load(): PerModelConfig | null {
+ const initial = resolveInitialConfig(MODEL, VARIANT);
+ return initial.remembered ? initial.config : null;
+}
+
+// ---------------------------------------------------------------------------
+// A. A NEW client reading OLD records. Nothing may be dropped.
+// ---------------------------------------------------------------------------
+
+test("a v0 record with no version key at all still loads the tuning it carried", () => {
+ store.clear();
+ // Pre-versioning shape. No migration step exists, so the guards read
+ // storedConfigVersion() === 0 and normalizeV1 rebuilds the record as it stands.
+ writeMap({
+ [`${MODEL}::${VARIANT}`]: {
+ loadMode: "mmap",
+ ctxCheckpoints: 0,
+ cacheRam: -1,
+ speculativeType: "dspark",
+ specDraftCacheDtype: "q8_0",
+ },
+ });
+
+ const loaded = load();
+ assert.ok(loaded, "a v0 record must remain readable");
+ assert.equal(loaded.loadMode, "mmap");
+ assert.equal(loaded.ctxCheckpoints, 0);
+ assert.equal(loaded.cacheRam, -1);
+ assert.equal(loaded.specDraftCacheDtype, "q8_0");
+});
+
+test("a v4 record loads unchanged and is re-stamped v4, not silently upgraded", () => {
+ store.clear();
+ writeMap({
+ [`${MODEL}::${VARIANT}`]: {
+ version: PRE_TUNING_CEILING,
+ customContextLength: 4096,
+ disableVision: true,
+ },
+ });
+ const loaded = load();
+ assert.ok(loaded);
+ assert.equal(loaded.customContextLength, 4096);
+ assert.equal(loaded.disableVision, true);
+ // The fields that did not exist yet read as unset, not as a bogus default: a
+ // fabricated 32 checkpoints would be pinned onto every load of this model.
+ assert.equal(loaded.loadMode, null);
+ assert.equal(loaded.ctxCheckpoints, null);
+ assert.equal(loaded.cacheRam, null);
+
+ // Re-saving without touching a tuning field must NOT poison the record for the
+ // build that wrote it: the stamp is a lock, and over-stamping locks that build out
+ // of a record it can still read in full.
+ assert.ok(savePerModelConfig(MODEL, VARIANT, loaded));
+ assert.equal(onlyEntry().version, PRE_TUNING_CEILING);
+});
+
+// ---------------------------------------------------------------------------
+// B. The property the whole scheme rests on.
+// ---------------------------------------------------------------------------
+
+test("only a record that actually carries tuning is stamped v5", () => {
+ // Annotated rather than `as const`: the latter makes llamaExtraArgs a readonly
+ // tuple, which Partial<PerModelConfig> will not take.
+ const cases: [Partial<PerModelConfig>, number][] = [
+ [{ kvCacheDtype: "q8_0" }, 1],
+ [{ nBatch: 4096 }, 2],
+ [{ llamaExtraArgs: ["--numa", "distribute"] }, 3],
+ [{ disableVision: true }, 4],
+ [{ loadMode: "mmap" }, 5],
+ [{ ctxCheckpoints: 0 }, 5],
+ [{ cacheRam: -1 }, 5],
+ [{ specDraftCacheDtype: "q8_0", speculativeType: "dspark" }, 5],
+ ];
+ for (const [patch, expected] of cases) {
+ store.clear();
+ assert.ok(savePerModelConfig(MODEL, VARIANT, config(patch)));
+ assert.equal(
+ onlyEntry().version,
+ expected,
+ `version for ${JSON.stringify(patch)}`,
+ );
+ }
+});
+
+test("a record with no tuning stays inside a pre-v5 build's reach", () => {
+ // The other half of the rule. Stamping every record v5 would quarantine the whole
+ // store from the build the user just downgraded to, which loses far more than it
+ // protects.
+ store.clear();
+ assert.ok(savePerModelConfig(MODEL, VARIANT, config({ nParallel: 8 })));
+ assert.ok((onlyEntry().version as number) <= PRE_TUNING_CEILING);
+});
+
+// ---------------------------------------------------------------------------
+// C. A pre-v5 client meeting a v5 record. Hidden is fine; destroyed is not.
+// ---------------------------------------------------------------------------
+
+test("a v5 record is out of a pre-v5 build's reach in the first place", () => {
+ // Replay what that build actually does: read every record it is allowed to
+ // interpret, drop the keys it does not know, write the result back. It must find
+ // nothing to rewrite.
+ store.clear();
+ assert.ok(savePerModelConfig(MODEL, VARIANT, config({ cacheRam: -1 })));
+
+ const map = readMap();
+ let rewrote = false;
+ for (const key of Object.keys(map)) {
+ const version =
+ typeof map[key].version === "number" ? (map[key].version as number) : 0;
+ if (version > PRE_TUNING_CEILING) {
+ continue;
+ }
+ const {
+ loadMode: _loadMode,
+ specDraftCacheDtype: _specDraftCacheDtype,
+ ctxCheckpoints: _ctxCheckpoints,
+ cacheRam: _cacheRam,
+ ...known
+ } = map[key];
+ map[key] = known;
+ rewrote = true;
+ }
+ writeMap(map);
+
+ assert.equal(rewrote, false, "the pre-v5 build was able to rewrite the record");
+ assert.equal(load()?.cacheRam, -1);
+});
+
+test("every entry point declines a record stamped beyond this build", () => {
+ // The five guards, exercised together. Any one of them missing is an older client
+ // silently destroying a newer record, and the record is the only copy on origins
+ // the server row does not reach.
+ store.clear();
+ assert.ok(savePerModelConfig(MODEL, VARIANT, config({ loadMode: "mmap" })));
+ const map = readMap();
+ map[Object.keys(map)[0]].version = 99;
+ writeMap(map);
+ const untouched = store.get(STORAGE_KEY);
+
+ assert.equal(load(), null, "load hides a future record");
+ assert.equal(
+ savePerModelConfig(MODEL, VARIANT, config({ nParallel: 1 })),
+ false,
+ "save must refuse rather than overwrite a future record",
+ );
+ assert.equal(
+ deletePerModelConfig(MODEL, VARIANT),
+ false,
+ "delete must refuse a future record",
+ );
+ assert.deepEqual(
+ listPerModelConfigs(),
+ [],
+ "a future record must not be reported to the backfill either",
+ );
+ assert.equal(store.get(STORAGE_KEY), untouched, "the stored bytes must be untouched");
+
+ // And once the client understands the schema again, the settings come back.
+ const restored = readMap();
+ restored[Object.keys(restored)[0]].version = 5;
+ writeMap(restored);
+ assert.equal(load()?.loadMode, "mmap");
+});
+
+// ---------------------------------------------------------------------------
+// D. What the change of default judgement moves.
+// ---------------------------------------------------------------------------
+
+test("a tuning-only config is stored rather than deleted on the way in", () => {
+ // savePerModelConfig DELETES an entry it judges default. Before the four were
+ // counted, a save whose only change was one of them reported success, wrote
+ // nothing, and came back unremembered on the next open.
+ for (const patch of TUNING_ONLY_PATCHES) {
+ store.clear();
+ const normalized = normalizePerModelConfig(config(patch));
+ assert.equal(isDefaultConfig(normalized), false, JSON.stringify(patch));
+ assert.ok(savePerModelConfig(MODEL, VARIANT, normalized));
+ assert.equal(
+ resolveInitialConfig(MODEL, VARIANT).remembered,
+ true,
+ `not remembered for ${JSON.stringify(patch)}`,
+ );
+ }
+});
+
+test("the one-time backfill now uploads a tuning-only config", async () => {
+ // A behaviour change on the first launch after upgrade, and the reason it is
+ // pinned rather than merely noted: the backfill gates on isDefaultConfig, so
+ // counting the four made it start mirroring configs it used to filter out. It is
+ // the right answer -- an API auto-switch of this model would otherwise run without
+ // the tuning the picker shows -- but it happens once, unprompted, and only ever
+ // adds fields, so it has to be deliberate.
+ store.clear();
+ assert.ok(savePerModelConfig(MODEL, VARIANT, config({ cacheRam: -1 })));
+
+ const puts: Record<string, unknown>[] = [];
+ setAuthFetchHandler((_input, init) => {
+ if (init?.method === "PUT") {
+ puts.push(JSON.parse(String(init.body)));
+ return new Response(JSON.stringify({ overrides: {} }), { status: 200 });
+ }
+ // The pre-read: an install upgrading into this has a row with no tuning in it.
+ return new Response(
+ JSON.stringify({
+ overrides: {
+ [`${MODEL.toLowerCase()}:${VARIANT.toLowerCase()}`]: {
+ // biome-ignore lint/style/useNamingConvention: API schema
+ max_seq_length: 4096,
+ },
+ },
+ }),
+ { status: 200 },
+ );
+ });
+ try {
+ await backfillModelOverrides();
+ } finally {
+ setAuthFetchHandler(null);
+ }
+
+ assert.equal(puts.length, 1, "the tuning-only config must be offered to the server");
+ assert.equal(puts[0].cache_ram, -1);
+ // Fill, never replace: the server copy is the newer authority, so the pass may add
+ // the field this browser holds and must not touch the max_seq_length already there.
+ assert.equal(puts[0].fill_absent_fields, true);
+ assert.equal(puts[0].remove, false);
+ assert.equal(store.get(BACKFILL_FLAG), "1", "a completed pass must not run again");
+});
+
+test("an all-default config is still filtered out of the backfill", async () => {
+ // The gate the case above walks through has to stay shut for everything else, or
+ // every model the user ever opened is mirrored on first launch.
+ store.clear();
+ assert.ok(savePerModelConfig(MODEL, VARIANT, config()));
+ assert.deepEqual(readMap(), {}, "a default config must not be written");
+
+ setAuthFetchHandler(() => {
+ throw new Error("the backfill must not reach the network with nothing to send");
+ });
+ try {
+ await backfillModelOverrides();
+ } finally {
+ setAuthFetchHandler(null);
+ }
+ assert.equal(store.get(BACKFILL_FLAG), "1");
+});
+
+// ---------------------------------------------------------------------------
+// E. Storage that refuses, and storage that is full.
+// ---------------------------------------------------------------------------
+
+test("the eviction loop terminates when the budget needs a future record", () => {
+ // deleteOldestEvictableEntry skips a future-schema entry, so a map made entirely of
+ // them cannot be brought inside either cap. The loop has to give up rather than
+ // spin on a candidate it will never take: an infinite loop here hangs the tab on a
+ // save, on a browser profile that has merely been downgraded.
+ for (const overBudget of [
+ // The entry-count cap: 505 records against MAX_ENTRIES = 500.
+ () => {
+ const map: Record<string, unknown> = {};
+ for (let index = 0; index < 505; index += 1) {
+ map[`unsloth/Model-${index}-GGUF::${VARIANT}`] = {
+ version: 99,
+ cacheRam: index,
+ };
+ }
+ return map;
+ },
+ // The byte cap: 20 records of 60 KiB each against MAX_PER_MODEL_CONFIG_STORAGE_BYTES.
+ () => {
+ const map: Record<string, unknown> = {};
+ for (let index = 0; index < 20; index += 1) {
+ map[`unsloth/Model-${index}-GGUF::${VARIANT}`] = {
+ version: 99,
+ chatTemplateOverride: "x".repeat(60_000),
+ };
+ }
+ return map;
+ },
+ ]) {
+ store.clear();
+ const map = overBudget();
+ writeMap(map);
+ const untouched = store.get(STORAGE_KEY);
+
+ // Reached at all, which is the termination assertion: node:test kills the process
+ // on a hang rather than reporting one, so the failure mode is the run not ending.
+ assert.equal(
+ savePerModelConfig("unsloth/New-GGUF", VARIANT, config({ cacheRam: 1 })),
+ false,
+ "a save that cannot fit must fail rather than evict a future record",
+ );
+ assert.equal(
+ store.get(STORAGE_KEY),
+ untouched,
+ "nothing may be written when the budget could not be met",
+ );
+ }
+});
+
+test("eviction takes the readable records and leaves the future ones", () => {
+ // The same cap with a way out. Only the records this build could rewrite anyway are
+ // candidates, and they go oldest first.
+ store.clear();
+ const map: Record<string, unknown> = {};
+ map["unsloth/Old-A-GGUF::Q4_K_M"] = { version: 1, nParallel: 2 };
+ map["unsloth/Future-GGUF::Q4_K_M"] = { version: 99, cacheRam: 7 };
+ map["unsloth/Old-B-GGUF::Q4_K_M"] = { version: 1, nParallel: 3 };
+ for (let index = 0; index < 499; index += 1) {
+ map[`unsloth/Filler-${index}-GGUF::${VARIANT}`] = { version: 1, nParallel: 1 };
+ }
+ writeMap(map);
+
+ const evicted: { modelId: string; ggufVariant: string | null }[] = [];
+ assert.ok(
+ savePerModelConfig("unsloth/New-GGUF", VARIANT, config({ cacheRam: 1 }), evicted),
+ );
+
+ const after = readMap();
+ assert.equal(Object.keys(after).length, 500);
+ assert.deepEqual(after["unsloth/Future-GGUF::Q4_K_M"], {
+ version: 99,
+ cacheRam: 7,
+ });
+ // Reported back, because eviction is silent and still returns success: without the
+ // list the server override of a dropped model keeps applying with nothing in the UI
+ // able to forget it.
+ assert.deepEqual(evicted, [
+ { modelId: "unsloth/Old-A-GGUF", ggufVariant: "Q4_K_M" },
+ { modelId: "unsloth/Old-B-GGUF", ggufVariant: "Q4_K_M" },
+ { modelId: "unsloth/Filler-0-GGUF", ggufVariant: "Q4_K_M" },
+ ]);
+});
+
+// ---------------------------------------------------------------------------
+// F. The server row as the authority, and what that costs the local copy.
+// ---------------------------------------------------------------------------
+
+test("a row that carries no tuning leaves this browser's tuning standing", () => {
+ // The mirror is lossy in both directions: a PUT that never landed, a save from a
+ // build that did not forward the four, a row written before the route learned them.
+ // All three leave the same gap, and reading a gap as a choice deletes settings.
+ const local = fromApiOverride({
+ // biome-ignore lint/style/useNamingConvention: API schema
+ load_mode: "mmap",
+ // biome-ignore lint/style/useNamingConvention: API schema
+ ctx_checkpoints: 0,
+ // biome-ignore lint/style/useNamingConvention: API schema
+ cache_ram: -1,
+ });
+ const hydrated = fromApiOverride(
+ // biome-ignore lint/style/useNamingConvention: API schema
+ { custom_context_length: 32768 },
+ local,
+ );
+
+ assert.equal(hydrated.customContextLength, 32768);
+ assert.equal(hydrated.loadMode, "mmap");
+ assert.equal(hydrated.ctxCheckpoints, 0);
+ assert.equal(hydrated.cacheRam, -1);
+});
+
+test("a row's tuning outranks this browser's for the fields it does carry", () => {
+ const local = fromApiOverride({
+ // biome-ignore lint/style/useNamingConvention: API schema
+ load_mode: "mmap",
+ // biome-ignore lint/style/useNamingConvention: API schema
+ cache_ram: 4096,
+ });
+ const hydrated = fromApiOverride(
+ {
+ // biome-ignore lint/style/useNamingConvention: API schema
+ load_mode: "mlock",
+ // biome-ignore lint/style/useNamingConvention: API schema
+ cache_ram: 0,
+ },
+ local,
+ );
+
+ assert.equal(hydrated.loadMode, "mlock");
+ // 0 is a value (the host prompt cache off), so it has to beat a local 4096 rather
+ // than read as absent and lose to it.
+ assert.equal(hydrated.cacheRam, 0);
+});
+
+test("a server value this build refuses falls to the app default, not the local one", () => {
+ // The merge takes the server value first and normalizeV1 clamps afterwards, so a
+ // refusal is indistinguishable from a chosen default by the time the local value
+ // could have been used. The reachable case is not a corrupt row: it is a row
+ // carrying a speculative mode with no separate drafter, which invalidates a draft
+ // KV dtype this browser legitimately holds.
+ const local = fromApiOverride({
+ // biome-ignore lint/style/useNamingConvention: API schema
+ speculative_type: "dspark",
+ // biome-ignore lint/style/useNamingConvention: API schema
+ spec_draft_cache_type: "q8_0",
+ });
+ assert.equal(local.specDraftCacheDtype, "q8_0");
+
+ // biome-ignore lint/style/useNamingConvention: API schema
+ const hydrated = fromApiOverride({ speculative_type: "ngram" }, local);
+ assert.equal(hydrated.speculativeType, "ngram");
+ assert.equal(
+ hydrated.specDraftCacheDtype,
+ null,
+ "the dtype belongs to a draft context this mode never creates",
+ );
+
+ // Same shape for a load mode the two builds disagree about: the row wins, and
+ // losing means the app default rather than what this browser had.
+ const pinned = fromApiOverride({
+ // biome-ignore lint/style/useNamingConvention: API schema
+ load_mode: "mmap",
+ });
+ // biome-ignore lint/style/useNamingConvention: API schema
+ const refused = fromApiOverride({ load_mode: "swap" }, pinned);
+ assert.equal(refused.loadMode, null);
+});
+
+test("an out-of-range server value clamps rather than falling through", () => {
+ // The other resolution, and the reason the case above is worth stating separately:
+ // a numeric knob is clamped into range instead of being refused, so the row still
+ // wins and the user gets the nearest legal value.
+ const local = fromApiOverride({
+ // biome-ignore lint/style/useNamingConvention: API schema
+ ctx_checkpoints: 64,
+ });
+ // biome-ignore lint/style/useNamingConvention: API schema
+ const hydrated = fromApiOverride({ ctx_checkpoints: 1_000_000 }, local);
+ assert.equal(hydrated.ctxCheckpoints, 256);
+});
+
+test("an empty server argument list clears a local list rather than being ignored", () => {
+ // [] is the tombstone that stops the server's fallback to a broader row, and
+ // normalizePerModelConfig collapses an empty list to null, so hydration has to
+ // reinstall it. Without that a cleared box comes back holding the legacy bare
+ // repository row's flags on the next open.
+ const local = fromApiOverride({
+ // biome-ignore lint/style/useNamingConvention: API schema
+ llama_extra_args: ["--numa", "distribute"],
+ });
+ assert.deepEqual(local.llamaExtraArgs, ["--numa", "distribute"]);
+
+ // biome-ignore lint/style/useNamingConvention: API schema
+ const hydrated = fromApiOverride({ llama_extra_args: [] }, local);
+ assert.deepEqual(hydrated.llamaExtraArgs, []);
+ // Distinct from "this copy never read the value", which must stay omitted so the
+ // route preserves whatever flags the server holds.
+ assert.notEqual(hydrated.llamaExtraArgs, undefined);
+});
+
+test("an empty server GPU list does not clear a local pin", () => {
+ // Deliberate, and worth pinning next to the tombstone above so the two are not
+ // "fixed" into agreement: only a PHYSICAL pin travels, so a row without ids says
+ // nothing about placement and a Vulkan ordinal keeps its own namespace.
+ const local = fromApiOverride({});
+ local.selectedGpuIds = [1];
+ local.selectedGpuIndexKind = "vulkan";
+
+ // biome-ignore lint/style/useNamingConvention: API schema
+ const hydrated = fromApiOverride({ gpu_ids: [] }, local);
+ assert.deepEqual(hydrated.selectedGpuIds, [1]);
+ assert.equal(hydrated.selectedGpuIndexKind, "vulkan");
+ // And toApiOverride is why: a Vulkan pin is never sent, so a row that lacks ids is
+ // exactly what a browser holding one produces.
+ assert.equal(toApiOverride(local).gpu_ids, undefined);
+});
+
+// The identity table the panel's hydration now depends on, mirrored from
+// tests/test_model_override_schema_compatibility.py::OVERRIDE_KEY_FOLDS. The server
+// resolves the row and the browser has to agree on which model it belongs to, or the
+// panel hydrates from another model's settings.
+const OVERRIDE_KEY_FOLDS: [string, string, boolean][] = [
+ ["C:\\models\\Foo.gguf", "c:/models/foo.gguf", true],
+ ["C:\\models\\Foo.gguf", "C:\\models\\Foo.gguf\\", true],
+ ["//share/models/Foo.gguf", "\\\\SHARE\\models\\foo.gguf", true],
+ ["/mnt/c/models/Foo.gguf", "/mnt/C/models/foo.gguf", true],
+ ["/models/Foo.gguf", "/models/foo.gguf", false],
+ ["unsloth/Repo-GGUF", "UNSLOTH/repo-gguf", true],
+ ["unsloth/Repo-GGUF:Q4_K_M", "unsloth/repo-gguf:q4_k_m", true],
+ ["/models/foo.gguf", "models/foo.gguf", false],
+ ["models/foo.gguf", "/models/foo.gguf", false],
+];
+
+for (const [storedKey, lookupKey, sameModel] of OVERRIDE_KEY_FOLDS) {
+ const reach = sameModel ? "is reached from" : "is not reached from";
+ test(`${JSON.stringify(storedKey)} ${reach} ${JSON.stringify(lookupKey)}`, () => {
+ // biome-ignore lint/style/useNamingConvention: API schema
+ const row = { cache_ram: -1 };
+ assert.equal(
+ resolveStoredOverride({ [storedKey]: row }, [lookupKey]),
+ sameModel ? row : null,
+ );
+ });
+}
+
+// The panel is a component this suite has no renderer for, so the one behaviour that
+// only exists inside its effect is read off the source, as the rest of its hydration
+// rules are in tests/llama-extra-args-panel-hydration.test.ts.
+const PANEL = readFileSync(
+ path.join(
+ path.dirname(fileURLToPath(import.meta.url)),
+ "..",
+ "src/features/model-picker/components/model-config-page.tsx",
+ ),
+ "utf8",
+);
+
+test("opening the panel ticks Remember for any model with a resolvable row", () => {
+ // Nothing in the guard asks whether the user ever chose to remember this model:
+ // a row exists, the panel has not been edited since the request went out, and
+ // Remember goes on and is persisted. That is defensible -- a row IS a remembered
+ // setting, whichever origin wrote it -- but it is unconditional, so a later change
+ // that wants user intent in the decision has to come through here.
+ // Spelled out term by term rather than as one long pattern, so a guard that grows
+ // a fourth condition fails on the whole-block match below and names which one.
+ const adoptGuard = [
+ "if \\(",
+ "resolvedRow &&",
+ "serverConfig &&",
+ "configRef\\.current === configAtStart &&",
+ "rememberRef\\.current === rememberAtStart",
+ "\\) \\{",
+ ].join("\\s*\\n\\s*");
+ assert.match(PANEL, new RegExp(adoptGuard));
+ assert.match(PANEL, /setRemember\(true\);\s*\n\s*setSavedRemember\(true\);/);
+ // The write is local only. An erased server field is therefore NOT restored by
+ // opening the panel, even though this browser still holds it: that takes a save.
+ // Unconditional, because savePerModelConfig expresses "no settings" by deleting
+ // the entry, so a merge that comes out default is a clear that has to travel.
+ assert.match(
+ PANEL,
+ /savePerModelConfig\(\s*configId,\s*target\.ggufVariant,\s*rememberedConfig,/,
+ );
+ // Whatever that write evicted is cleared before the block returns, or a dropped
+ // model keeps applying its server row with nothing able to forget it.
+ assert.match(PANEL, /for \(const dropped of hydrationEvicted\)[\s\S]*?return;/);
+});
+
+// ---------------------------------------------------------------------------
+// G. Storage that refuses every call. Last, because it replaces the fake.
+// ---------------------------------------------------------------------------
+
+test("a localStorage that throws degrades on every path instead of propagating", () => {
+ // Private mode, a disabled-storage policy, and a full quota all arrive as a throw
+ // from getItem or setItem. The hydration effect calls savePerModelConfig from a
+ // promise callback and ignores what it returns, so a throw here is an unhandled
+ // rejection in a panel the user has merely opened.
+ const throwing: StorageFake = {
+ getItem: () => {
+ throw new Error("SecurityError");
+ },
+ setItem: () => {
+ const error = new Error("QuotaExceededError");
+ error.name = "QuotaExceededError";
+ throw error;
+ },
+ removeItem: () => undefined,
+ };
+ const asWindow = globalThis as unknown as { window: { localStorage: StorageFake } };
+ Object.assign(globalThis, { localStorage: throwing });
+ asWindow.window.localStorage = throwing;
+ try {
+ assert.equal(savePerModelConfig(MODEL, VARIANT, config({ cacheRam: -1 })), false);
+ assert.deepEqual(resolveInitialConfig(MODEL, VARIANT), {
+ config: { ...DEFAULT_PER_MODEL_CONFIG },
+ remembered: false,
+ });
+ assert.deepEqual(listPerModelConfigs(), []);
+ // Nothing was stored, so there is nothing to forget: a refusal here would leave
+ // the settings page unable to clear a model it can already not read.
+ assert.equal(deletePerModelConfig(MODEL, VARIANT), true);
+ } finally {
+ Object.assign(globalThis, { localStorage: storage });
+ asWindow.window.localStorage = storage;
+ }
+});
diff --git a/studio/frontend/tests/slider-thumb-accessible-value.test.ts b/studio/frontend/tests/slider-thumb-accessible-value.test.ts
new file mode 100644
index 00000000000..560e61fd3ae
--- /dev/null
+++ b/studio/frontend/tests/slider-thumb-accessible-value.test.ts
@@ -0,0 +1,73 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// What the slider says to a screen reader. Two gaps a sighted reviewer cannot see:
+//
+// 1. Radix puts role="slider" on the Thumb while the wrapper spreads props onto
+// Root, so an aria-label reached a plain div and the control was unnamed. Radix
+// only synthesises its own label for multi-thumb ranges.
+// 2. Radix does not synthesise aria-valuetext, so the Auto position announced as
+// "0" -- the one stop on that track whose number is not a context length.
+//
+// Asserted on source: the failure is a missing attribute on an element node:test
+// cannot render.
+
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import path from "node:path";
+import { test } from "node:test";
+import { fileURLToPath } from "node:url";
+
+const here = path.dirname(fileURLToPath(import.meta.url));
+const read = (relative: string) =>
+ readFileSync(path.join(here, "..", relative), "utf8").replace(/\s+/g, " ");
+
+const slider = read("src/components/ui/slider.tsx");
+const panel = read(
+ "src/features/model-picker/components/model-config-page.tsx",
+);
+
+test("the thumb carries the accessible name, not just the root", () => {
+ // Both spellings: a caller may name the slider either way.
+ assert.match(
+ slider,
+ /<SliderPrimitive\.Thumb[^>]*aria-label=\{props\["aria-label"\]\}/,
+ );
+ assert.match(
+ slider,
+ /<SliderPrimitive\.Thumb[^>]*aria-labelledby=\{props\["aria-labelledby"\]\}/,
+ );
+});
+
+test("the wrapper can express a spoken value for a position", () => {
+ assert.match(
+ slider,
+ /thumbValueText\?:\s*\(value: number, index: number\) => string/,
+ );
+ assert.match(slider, /aria-valuetext=\{thumbValueText\?\.\(/);
+});
+
+test("the context slider says Auto rather than zero", () => {
+ // aria-valuenow carries the raw position, so Auto needs saying in words.
+ assert.match(panel, /thumbValueText=\{\(v\) =>/);
+ assert.match(panel, /v !== 0 \? `\$\{v\.toLocaleString\(\)\} tokens`/);
+ assert.match(panel, /: "Auto"/);
+});
+
+test("Auto announces a current value only once one exists", () => {
+ // Before a load contextInputValue is the offload fallback that seeds the input,
+ // not a selection: Auto may still fit the model's native context. Announcing it
+ // as "currently N" tells a screen-reader user a number no other user is shown.
+ assert.match(
+ panel,
+ /activeLoadedContext != null \? `Auto, currently \$\{contextInputValue\.toLocaleString\(\)\} tokens` : "Auto"/,
+ );
+});
+
+test("no slider is left announcing a bare number for a named position", () => {
+ // If the wrapper stops forwarding value text, every such caller regresses at once.
+ assert.ok(
+ slider.includes("aria-valuetext"),
+ "the shared Slider must keep forwarding aria-valuetext to the thumb",
+ );
+});
diff --git a/tests/studio/playwright_model_config.py b/tests/studio/playwright_model_config.py
index 7f2e4631c5b..e220b28c883 100644
--- a/tests/studio/playwright_model_config.py
+++ b/tests/studio/playwright_model_config.py
@@ -823,10 +823,11 @@ with sync_playwright() as p:
# ─────────────────────────────────────────────────────
# 3b. Re-typing the value already shown must not pin an override (HARD).
- # Entering the currently displayed native/default context commits no
- # onChange (the value is unchanged), so the cached blur value must not be
- # replayed into a stored override on Load. Otherwise re-typing the shown
- # number, or doing so before a Reset, recreates a phantom context pin.
+ # Entering the currently displayed context commits no onChange (the value is
+ # unchanged), so the cached blur value must not be replayed into a stored
+ # override on Load. Otherwise re-typing the shown number, or doing so before a
+ # Reset, recreates a phantom context pin. The box shows "Auto" while nothing is
+ # pinned, so the number it edits is read from the focused input below.
# ─────────────────────────────────────────────────────
step("re-typing the shown context does not pin an override")
# Own its state instead of inheriting the step above: the previous step commits a
@@ -839,6 +840,12 @@ with sync_playwright() as p:
native_default = None
else:
ctx_in = context_input(popover)
+ # With no override stored the box reads "Auto", and only reveals the number it
+ # would edit (the fitted context) once it has focus. Click first, or there is
+ # nothing numeric to re-type and the step skips the regression it guards.
+ if ctx_in is not None:
+ ctx_in.click()
+ page.wait_for_timeout(200)
native_default = _as_int(ctx_in.input_value()) if ctx_in else None
if ctx_in is None or native_default is None:
# A skip here is not a pass: this step is the only guard on the phantom-pin
diff --git a/tests/studio/test_model_picker_contracts.py b/tests/studio/test_model_picker_contracts.py
index 6529dd0d444..85b0290d6ad 100644
--- a/tests/studio/test_model_picker_contracts.py
+++ b/tests/studio/test_model_picker_contracts.py
@@ -151,6 +151,45 @@ def test_model_config_page_floors_the_context_ceiling():
assert "normalizeMaxSeqLength(modelMaxPosition.maxPositionEmbeddings)" not in src
+def test_auto_offload_context_matches_picker_custom_seed():
+ """Custom's safe seed must track the backend Auto offload context."""
+ frontend = _read("features/model-picker/components/model-config-page.tsx")
+ backend = _read_backend("core/inference/llama_cpp.py")
+ frontend_value = re.search(r"\bAUTO_OFFLOAD_CONTEXT_LENGTH\s*=\s*(\d+)", frontend)
+ backend_value = re.search(r"\b_AUTO_OFFLOAD_CTX\s*=\s*(\d+)", backend)
+ assert frontend_value is not None
+ assert backend_value is not None
+ assert frontend_value.group(1) == backend_value.group(1)
+
+
+def test_ui_safe_zone_anchor_tracks_the_auto_offload_context():
+ """The published ceiling and the context Auto runs must come from one constant.
+
+ ``max_context_length`` is the threshold the chat settings sheet warns above.
+ When no GPU subset fits, Auto runs at ``_AUTO_OFFLOAD_CTX`` and the ceiling is
+ anchored in the same branch. A literal there drifts the moment the constant
+ moves, and the symptom is every Auto load warning about a context Auto chose
+ for itself, so pin the reference rather than the value.
+ """
+ backend = _read_backend("core/inference/llama_cpp.py")
+ anchor = re.search(
+ r"max_available_ctx\s*=\s*min\(\s*([A-Za-z_0-9]+)\s*,\s*native_ctx_for_cap",
+ backend,
+ )
+ assert anchor is not None, "the no-fit UI safe-zone anchor moved or was renamed"
+ assert anchor.group(1) == "_AUTO_OFFLOAD_CTX"
+
+
+def test_auto_offload_context_is_not_below_the_fit_floor():
+ """Raising the Auto offload context is placement-neutral only above the fit
+ floor: below it, the offload re-check starts awarding GPU residency again."""
+ backend = _read_backend("core/inference/llama_cpp.py")
+ auto = re.search(r"\b_AUTO_OFFLOAD_CTX\s*=\s*(\d+)", backend)
+ floor = re.search(r"\b_FIT_MIN_CTX\s*=\s*(\d+)", backend)
+ assert auto is not None and floor is not None
+ assert int(auto.group(1)) >= int(floor.group(1))
+
+
def test_compare_load_clears_stale_native_lease():
"""A compare-pane load never comes from the desktop file picker, so it must
clear any prior picked file's lease token + expiry, otherwise a reload can
@@ -927,11 +966,7 @@ def test_reset_enabled_for_explicit_context_pin_at_native():
"""An explicit customContextLength that equals the native ceiling is still a user
override, so contextAtDefault must require customContextLength == null."""
src = " ".join(_read("features/model-picker/components/model-config-page.tsx").split())
- assert (
- "const contextAtDefault = !target.isGguf || "
- "(config.customContextLength == null && "
- "(nativeContextLength == null || contextValue === nativeContextLength));" in src
- )
+ assert "const contextAtDefault = !target.isGguf || config.customContextLength == null;" in src
# The old form that ignored an explicit pin equal to native must not return.
assert (
"(nativeContextLength == null ? config.customContextLength == null : "