Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: add Mmap/Mlock, draft KV cache dtype, Checkpoints and Cache RAM to Run settings (#9410)
Daniel Han5786a0eade07
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.pyindex 77d253aec67..04e8378f7d2 100644--- a/studio/backend/core/inference/llama_cpp.py+++ b/studio/backend/core/inference/llama_cpp.py@@ -65,7 +65,9 @@ from core.inference.llama_server_args import (_effective_tensor_parallel,_flag_name,_tensor_parallel_matches_loaded,+ apply_load_mode_policy,apply_model_memory_policy,+ resolve_ctx_checkpoints,extra_args_disable_mmproj,fit_is_enabled_in,memory_state_satisfies_settings,@@ -413,6 +415,12 @@ class GgufLoadIntent:# none follows the llama.cpp defaults (2048 / 512)n_batch: Optional[int] = Nonen_ubatch: Optional[int] = None+ # llama-server tuning group; none follows the llama.cpp defaults+ # (auto / f16 / 32 / 8192).+ load_mode: Optional[str] = None+ spec_draft_cache_type: Optional[str] = None+ ctx_checkpoints: Optional[int] = None+ cache_ram: Optional[int] = Noneextra_args: Optional[tuple[str, ...]] = None# The route materialises inherited extras from the live server, so the list alone# cannot say whether the caller named it. Duplicate-load checks need the difference:@@ -3895,6 +3903,27 @@ def _extra_args_mtp_draft_source(return None, False+def _normalized_load_mode(value: Optional[str]) -> Optional[str]:+ """Canonical --load-mode, with llama.cpp's own default reading as unset.++ "auto" IS the default, so a load asking for it and a load asking for nothing+ launch the same command; the dedupe has to see them as equal or picking Auto+ would reload a server already running it.+ """+ if value is None:+ return None+ mode = str(value).strip().lower()+ return None if mode in {"", "auto"} else mode+++# The KV cache dtypes llama.cpp can map, shared by the emission guard and the+# budget. Module level because both the draft-cache block and the MTP reserve+# need it, and the main cache path's copy is a local inside load_model.+_VALID_KV_CACHE_TYPES: frozenset[str] = frozenset(+ {"f16", "bf16", "q8_0", "q4_0", "q4_1", "q5_0", "q5_1", "iq4_nl", "f32"}+)++def _extra_args_draft_cache_types(extra_args: Optional[Iterable[str]], env: Optional[Mapping[str, str]] = None) -> tuple[Optional[str], Optional[str]]:@@ -4653,6 +4682,13 @@ class LlamaCppBackend:# --batch-size / --ubatch-size the last load asked for; none = defaults or extras / envself._requested_n_batch: Optional[int] = Noneself._requested_n_ubatch: Optional[int] = None+ # The tuning group the last load asked for; none = defaults, or left to+ # extras / env. What was REQUESTED, not what ran: Model Memory can replace+ # the load mode, and Windows full-offload tuning owns the two cache knobs.+ self._requested_load_mode: Optional[str] = None+ self._requested_spec_draft_cache_type: Optional[str] = None+ self._requested_ctx_checkpoints: Optional[int] = None+ self._requested_cache_ram: Optional[int] = Noneself._chat_template: Optional[str] = Noneself._markup_tokens: list = []self._markup_profile = None@@ -5032,6 +5068,29 @@ class LlamaCppBackend:"""--ubatch-size the last load asked for; None means llama.cpp default."""return self._requested_n_ubatch+ @property+ def requested_load_mode(self) -> Optional[str]:+ """--load-mode the last load asked for; None means llama.cpp's own auto.+ The Model Memory settings may have replaced it, which the settings route+ reports; this stays the caller's intent so the dedupe compares like with+ like."""+ return self._requested_load_mode++ @property+ def requested_spec_draft_cache_type(self) -> Optional[str]:+ """Draft KV cache dtype the last load asked for; None means f16."""+ return self._requested_spec_draft_cache_type++ @property+ def requested_ctx_checkpoints(self) -> Optional[int]:+ """--ctx-checkpoints the last load asked for; None means the default 32."""+ return self._requested_ctx_checkpoints++ @property+ def requested_cache_ram(self) -> Optional[int]:+ """--cache-ram (MiB) the last load asked for; None means the default 8192."""+ return self._requested_cache_ram+@propertydef max_context_length(self) -> Optional[int]:"""Return the largest context that fits on this hardware at load time.@@ -5061,6 +5120,10 @@ class LlamaCppBackend:self._requested_n_parallel = 1self._requested_n_batch = Noneself._requested_n_ubatch = None+ self._requested_load_mode = None+ self._requested_spec_draft_cache_type = None+ self._requested_ctx_checkpoints = None+ self._requested_cache_ram = None@staticmethoddef _read_rss_bytes(pid: int) -> Optional[int]:@@ -5431,6 +5494,19 @@ class LlamaCppBackend:self._requested_n_batch != intent.n_batch or self._requested_n_ubatch != intent.n_ubatch):return False+ # Same rule for the tuning group: requested against requested, so a server+ # launched with a different value is a reload. Compared even when the+ # intent is blank, unlike spec_draft_n_max above: blank is the llama.cpp+ # default and both sides hold what was requested, so two loads that asked+ # for nothing still match, while clearing a knob relaunches.+ if not self._is_diffusion and (+ _normalized_load_mode(self._requested_load_mode)+ != _normalized_load_mode(intent.load_mode)+ or self._requested_spec_draft_cache_type != intent.spec_draft_cache_type+ or self._requested_ctx_checkpoints != intent.ctx_checkpoints+ or self._requested_cache_ram != intent.cache_ram+ ):+ return Falsedef _norm(value):if value is None:@@ -6022,6 +6098,8 @@ class LlamaCppBackend:"supports_no_mmproj_offload": False,"supports_load_mode": False,"spec_draft_ngl_flag": None,+ "spec_draft_cache_k_flag": None,+ "spec_draft_cache_v_flag": None,"flags": {},"help_probe_ok": False,}@@ -6066,6 +6144,8 @@ class LlamaCppBackend:supports_no_mmproj_offload = Falsesupports_load_mode = Falsespec_draft_ngl_flag = None+ spec_draft_cache_k_flag = None+ spec_draft_cache_v_flag = Nonesaw_spec_type = Falseprobe_ok = Falsehelp_text = ""@@ -6276,6 +6356,18 @@ class LlamaCppBackend:if _is_real(_alias):spec_draft_ngl_flag = _aliasbreak+ # Same alias dance for the draft KV cache pair: --spec-draft-type-* is+ # the modern spelling, --cache-type-*-draft the older, and a build with+ # only one exits on the other. K and V probed independently (upstream+ # renamed them together; a fork need not have). Long forms only.+ for _alias in ("--spec-draft-type-k", "--cache-type-k-draft"):+ if _is_real(_alias):+ spec_draft_cache_k_flag = _alias+ break+ for _alias in ("--spec-draft-type-v", "--cache-type-v-draft"):+ if _is_real(_alias):+ spec_draft_cache_v_flag = _alias+ breakexcept (OSError, subprocess.SubprocessError) as exc:logger.debug(f"llama-server --help probe failed: {exc}")saw_spec_type = False@@ -6337,6 +6429,8 @@ class LlamaCppBackend:"supports_no_mmproj_offload": supports_no_mmproj_offload,"supports_load_mode": supports_load_mode,"spec_draft_ngl_flag": spec_draft_ngl_flag,+ "spec_draft_cache_k_flag": spec_draft_cache_k_flag,+ "spec_draft_cache_v_flag": spec_draft_cache_v_flag,# The whole parsed catalogue, not just the booleans above. The UI# validates pass-through args against THIS build rather than a list# bundled with Unsloth, since a custom or newer llama.cpp is exactly@@ -10875,6 +10969,12 @@ class LlamaCppBackend:self._n_ubatch = self._DEFAULT_N_UBATCHself._requested_n_batch = Noneself._requested_n_ubatch = None+ # The diffusion runner builds its own command and passes none of these,+ # so a previous GGUF's values must not be reported against it.+ self._requested_load_mode = None+ self._requested_spec_draft_cache_type = None+ self._requested_ctx_checkpoints = None+ self._requested_cache_ram = Noneself._flash_attn_enabled = Trueself._effective_cache_types = ("f16", "f16")self._kv_cache_context_total = None@@ -14704,6 +14804,10 @@ class LlamaCppBackend:n_parallel = intent.n_paralleln_batch = intent.n_batchn_ubatch = intent.n_ubatch+ load_mode = intent.load_mode+ spec_draft_cache_type = intent.spec_draft_cache_type+ ctx_checkpoints = intent.ctx_checkpoints+ cache_ram = intent.cache_ramextra_args = list(intent.extra_args) if intent.extra_args is not None else Nonepreserve_multi_gpu_on_layer = intent.preserve_multi_gpu_on_layer# Serialise the whole load so concurrent /load calls never leave two@@ -15377,6 +15481,15 @@ class LlamaCppBackend:)_effective_ubatch = _ubatch_for_slots(n_parallel)+ # What the SWA checkpoint reserve is priced against. Extras beat the+ # field, as at launch: the control emits its flag before them, so a+ # typed --ctx-checkpoints is what the child allocates. Only an+ # explicit request counts at all: the estimator has always charged 0,+ # and adopting llama.cpp's default of 32 would move the fit for every+ # model.+ _effective_ctx_checkpoints = resolve_ctx_checkpoints(+ extra_args, ctx_checkpoints+ )# --embedding forces n_batch = n_ubatch, which aborts a load below the slots.if (self.is_embedding_gguf@@ -16093,6 +16206,16 @@ class LlamaCppBackend:_mtp_draft_weights = 0# Draft K/V types (f16 by default; independent extras overrides)._mtp_draft_ck, _mtp_draft_cv = _extra_args_draft_cache_types(extra_args)+ # The control underneath them: emitted before the extras, so an+ # extra still last-wins and the reserve prices what will run.+ _budget_draft_cache = (+ spec_draft_cache_type.strip().lower()+ if spec_draft_cache_type+ else None+ )+ if _budget_draft_cache in _VALID_KV_CACHE_TYPES:+ _mtp_draft_ck = _mtp_draft_ck or _budget_draft_cache+ _mtp_draft_cv = _mtp_draft_cv or _budget_draft_cache# Byte-accurate reserve when dims allow, else None -> flat fallback.mtp_overhead_fn: Optional[Callable[[int], int]] = None@@ -16672,6 +16795,7 @@ class LlamaCppBackend:n_parallel = n_parallel,kv_unified = planned_kv_unified,n_ubatch = _effective_ubatch,+ ctx_checkpoints = _effective_ctx_checkpoints,flash_attn = planned_flash_attn,mtp_engaged = False,mtp_overhead_fn = None,@@ -16752,6 +16876,7 @@ class LlamaCppBackend:n_parallel = n_parallel,kv_unified = planned_kv_unified,n_ubatch = _effective_ubatch,+ ctx_checkpoints = _effective_ctx_checkpoints,flash_attn = planned_flash_attn,mtp_engaged = True,mtp_overhead_fn = mtp_overhead_fn,@@ -16979,6 +17104,7 @@ class LlamaCppBackend:n_parallel = n_parallel,kv_unified = planned_kv_unified,n_ubatch = _effective_ubatch,+ ctx_checkpoints = _effective_ctx_checkpoints,flash_attn = planned_flash_attn,mtp_engaged = _mtp_reserves_gpu,mtp_overhead_fn = mtp_overhead_fn,@@ -17066,6 +17192,7 @@ class LlamaCppBackend:n_parallel = n_parallel,kv_unified = planned_kv_unified,n_ubatch = _effective_ubatch,+ ctx_checkpoints = _effective_ctx_checkpoints,flash_attn = planned_flash_attn,mtp_engaged = _mtp_reserves_gpu,mtp_overhead_fn = mtp_overhead_fn,@@ -17208,6 +17335,7 @@ class LlamaCppBackend:n_parallel = n_parallel,kv_unified = planned_kv_unified,n_ubatch = _effective_ubatch,+ ctx_checkpoints = _effective_ctx_checkpoints,flash_attn = planned_flash_attn,mtp_engaged = _mtp_reserves_gpu,mtp_overhead_fn = mtp_overhead_fn,@@ -17683,6 +17811,26 @@ class LlamaCppBackend:server_caps = _launch_caps(binary)+ # Before the extras, like the batch pair: a hand-typed flag still+ # last-wins over the control. Each is gated on the capability+ # probe, because a build that predates the flag exits on it.+ if ctx_checkpoints is not None:+ if server_caps.get("supports_ctx_checkpoints"):+ cmd.extend(["--ctx-checkpoints", str(int(ctx_checkpoints))])+ else:+ logger.info(+ "llama-server has no --ctx-checkpoints; skipping the requested %s.",+ ctx_checkpoints,+ )+ if cache_ram is not None:+ if server_caps.get("supports_cache_ram"):+ cmd.extend(["--cache-ram", str(int(cache_ram))])+ else:+ logger.info(+ "llama-server has no --cache-ram; skipping the requested %s MiB.",+ cache_ram,+ )+# Report a clean public model id (matching GET /v1/models) rather# than the raw -m path in llama-server's own /v1/models and the# "model" field of its chat/completions responses.@@ -18052,6 +18200,45 @@ class LlamaCppBackend:# Restore the requested view, or the spec-mode compare never matches.if _extra_args_set_spec_type(_pv_suppressed_spec_extra_args):self._requested_spec_mode = None+ # The draft KV cache dtype sizes the DRAFT context, so it means+ # nothing without --model-draft. Judged on the flags actually built,+ # not the requested mode: a mode that fell back to no drafter emits+ # nothing, and an MTP load that did attach one is covered.+ # Normalized and allow-listed like the main cache dtype above, and+ # for the same reason: llama-server exits during argument parsing on+ # a value it cannot map, and by then the resident model is gone. An+ # unknown value emits nothing instead, so the load still comes up.+ _draft_cache_type = (+ spec_draft_cache_type.strip().lower() if spec_draft_cache_type else None+ )+ if _draft_cache_type and _draft_cache_type not in _VALID_KV_CACHE_TYPES:+ logger.warning(+ "Ignoring unsupported draft KV cache type %r", spec_draft_cache_type+ )+ _draft_cache_type = None+ if _draft_cache_type and any(+ _flag_name(tok) in _LOCAL_DRAFT_FLAGS for tok in spec_flags+ ):+ _draft_k_flag = server_caps.get("spec_draft_cache_k_flag")+ _draft_v_flag = server_caps.get("spec_draft_cache_v_flag")+ if _draft_k_flag and _draft_v_flag:+ # Both axes together: llama.cpp refuses K != V on an MLA+ # draft context, and the control is one dtype for the pair.+ spec_flags.extend(+ [+ str(_draft_k_flag),+ _draft_cache_type,+ str(_draft_v_flag),+ _draft_cache_type,+ ]+ )+ logger.info("Draft KV cache dtype: %s", _draft_cache_type)+ else:+ logger.info(+ "llama-server has no draft KV cache flags; skipping the "+ "requested %s.",+ _draft_cache_type,+ )# Remember where the spec block sits so a drafter-load failure# can be retried with these flags swapped out (see below)._spec_start = len(cmd)@@ -18223,11 +18410,18 @@ class LlamaCppBackend:# a repeated prompt is not re-prefilled on every request. #5692.if sys.platform == "win32" and full_offload_tuning_active:unsupported_cache_flags: list[str] = []- if server_caps.get("supports_cache_ram"):+ # An explicit control wins over the platform tuning: llama.cpp+ # is last-wins, so a 0 emitted after it would overrule the panel+ # while the panel still showed the value that was typed.+ if cache_ram is not None:+ pass+ elif server_caps.get("supports_cache_ram"):cmd.extend(["--cache-ram", "0"])else:unsupported_cache_flags.append("--cache-ram")- if server_caps.get("supports_ctx_checkpoints"):+ if ctx_checkpoints is not None:+ pass+ elif server_caps.get("supports_ctx_checkpoints"):cmd.extend(["--ctx-checkpoints", "0"])else:unsupported_cache_flags.append("--ctx-checkpoints")@@ -18342,6 +18536,15 @@ class LlamaCppBackend:supports_load_mode = bool(server_caps.get("supports_load_mode")),weights_in_host_memory = _mem_host_resident,)+ # After Model Memory and on the extras it returned, because it+ # defers to those settings: while either one owns host placement+ # the per-model pick emits nothing at all.+ _load_mode_managed, _mem_extras = apply_load_mode_policy(+ _mem_extras,+ supports_load_mode = bool(server_caps.get("supports_load_mode")),+ weights_in_host_memory = _mem_host_resident,+ requested_load_mode = load_mode,+ )# Remembered so the reload hint and the duplicate-load comparator do# not demand an mlock this launch deliberately skipped.self._memory_mlock_applicable = _mem_host_resident@@ -18357,6 +18560,9 @@ class LlamaCppBackend:"Model Memory: keeping weights pinned in place (%s)"," ".join(_mem_managed),)+ if _load_mode_managed:+ cmd.extend(_load_mode_managed)+ logger.info("Load mode: %s", " ".join(_load_mode_managed))# User pass-through args go last. Placement flags are removed# below when the Studio picker owns the GPU selection.@@ -19470,6 +19676,10 @@ class LlamaCppBackend:_retry_managed, _ = apply_model_memory_policy(extra_args,supports_load_mode = bool(server_caps.get("supports_load_mode")),+ # Not the requested load mode: the first launch+ # emitted it and this call only ADDS, so a second+ # copy would land after the extras and mark+ # _memory_policy_active for a launch it never touched.weights_in_host_memory = _retry_host_resident,)if _retry_managed:@@ -20011,6 +20221,10 @@ class LlamaCppBackend:self._vram_fraction_pending = Noneself._requested_n_batch = intent.n_batchself._requested_n_ubatch = intent.n_ubatch+ self._requested_load_mode = intent.load_mode+ self._requested_spec_draft_cache_type = intent.spec_draft_cache_type+ self._requested_ctx_checkpoints = intent.ctx_checkpoints+ self._requested_cache_ram = intent.cache_ram# Commit the known-good snapshot + whether MTP+tensor is live, then# watch this load for a mid-generation crash. The verified-cache hint is# dropped: a respawn replays this snapshot arbitrarily later, so recoverydiff --git a/studio/backend/core/inference/llama_server_args.py b/studio/backend/core/inference/llama_server_args.pyindex cd00b711b72..bbdc21845e3 100644--- a/studio/backend/core/inference/llama_server_args.py+++ b/studio/backend/core/inference/llama_server_args.py@@ -13,10 +13,13 @@ Ref: https://github.com/ggml-org/llama.cpp/blob/master/tools/server/README.mdfrom __future__ import annotations+import loggingimport osimport sysfrom typing import Iterable, Mapping, Optional+logger = logging.getLogger(__name__)+# Valid llama-server --parallel range, shared with LoadRequest.n_parallel.# Mirrored by callers that cannot import this: run.py and unsloth_cli/commands/# studio.py (_PARALLEL_MIN/MAX), per-model-config.ts (N_PARALLEL_MIN/MAX);@@ -28,6 +31,12 @@ PARALLEL_MAX = 64BATCH_MIN = 1BATCH_MAX = 65536+# Sanity bounds, not upstream ones: a stray keystroke fails here rather than in the+# child. --cache-ram floors at -1 ("no limit"); 0 disables the cache. Mirrored by+# CTX_CHECKPOINTS_MAX / CACHE_RAM_MAX in per-model-config.ts.+CTX_CHECKPOINTS_MAX = 256+CACHE_RAM_MAX_MIB = 1024 * 1024+# Each group = every alias (short + long) of one hard-denied flag.# Extend the matching group when llama.cpp adds a new alias._DENYLIST_GROUPS: tuple[frozenset[str], ...] = (@@ -523,11 +532,12 @@ _SPEC_FLAGS: frozenset[str] = frozenset(# and HF --spec-draft-hf aliases) are Unsloth-managed since the separate-# drafter support (Gemma 4): an inherited copy must not last-wins-override# the auto-detected drafter. Explicit extras for the current load are never- # stripped. The per-drafter tuning knobs (--spec-draft-type-*, -ngld,- # --spec-draft-device) are deliberately NOT stripped: the VRAM budget reads- # them via the same parsers the child honors, so they stay consistent on- # inherit, and stripping them would silently move a CPU-offloaded drafter- # back onto the GPU.+ # stripped. The per-drafter tuning knobs (-ngld, --spec-draft-device) are+ # deliberately NOT stripped: the VRAM budget reads them via the same parsers+ # the child honors, so they stay consistent on inherit, and stripping them+ # would silently move a CPU-offloaded drafter back onto the GPU. The draft+ # cache dtype is in that group too, and has its own toggle used only when+ # spec_draft_cache_type is set, the same rule the batch pair follows."--model-draft","-md","--spec-draft-model",@@ -577,6 +587,21 @@ _GPU_LAYER_FLAGS: frozenset[str] = frozenset({"-ngl", "--gpu-layers", "--n-gpu-l# inherited copies of these shadow n_batch / n_ubatch, stripped only when the field is set_BATCH_FLAGS: frozenset[str] = frozenset({"-b", "--batch-size"})_UBATCH_FLAGS: frozenset[str] = frozenset({"-ub", "--ubatch-size"})+# Same rule for the tuning group: stripped only when its field is supplied.+# --swa-checkpoints is upstream's older spelling of --ctx-checkpoints.+_CTX_CHECKPOINTS_FLAGS: frozenset[str] = frozenset(+ {"-ctxcp", "--ctx-checkpoints", "--swa-checkpoints"}+)+_CACHE_RAM_FLAGS: frozenset[str] = frozenset({"-cram", "--cache-ram"})+# One group: the control sets a single dtype, so an inherited pair that split K+# from V has to go whole.+_SPEC_DRAFT_CACHE_K_FLAGS: frozenset[str] = frozenset(+ {"-ctkd", "--cache-type-k-draft", "--spec-draft-type-k"}+)+_SPEC_DRAFT_CACHE_V_FLAGS: frozenset[str] = frozenset(+ {"-ctvd", "--cache-type-v-draft", "--spec-draft-type-v"}+)+_SPEC_DRAFT_CACHE_FLAGS: frozenset[str] = _SPEC_DRAFT_CACHE_K_FLAGS | _SPEC_DRAFT_CACHE_V_FLAGS_FIT_FLAGS: frozenset[str] = frozenset({"-fit", "--fit"})_LAYER_OFFLOAD_FLAGS: frozenset[str] = _GPU_LAYER_FLAGS | _FIT_FLAGS_MOE_OFFLOAD_FLAGS: frozenset[str] = frozenset({"-ncmoe", "--n-cpu-moe", "-cmoe", "--cpu-moe"})@@ -677,6 +702,33 @@ def parse_ctx_override(args: Optional[Iterable[str]]) -> Optional[int]:return override+def parse_ctx_checkpoints_override(args: Optional[Iterable[str]]) -> Optional[int]:+ """Return the last user-supplied ``--ctx-checkpoints`` value, or None.++ The control emits its flag before the extras, so a copy typed for this load+ last-wins at launch. Sizing has to price that value, not the field, or a+ ``--ctx-checkpoints 256`` in the extras allocates 256 per-slot snapshots+ against a fit that budgeted the field's count.+ """+ value = _last_flag_value(args, _CTX_CHECKPOINTS_FLAGS)+ if value is None:+ return None+ try:+ parsed = int(str(value).strip())+ except ValueError:+ # Malformed extras are refused at the boundary; sizing must not raise here.+ return None+ return max(0, parsed)+++def resolve_ctx_checkpoints(+ args: Optional[Iterable[str]], requested: Optional[int]+) -> int:+ """The checkpoint count the launch will actually run: extras beat the field."""+ override = parse_ctx_checkpoints_override(args)+ return int(override if override is not None else (requested or 0))++def resolve_requested_ctx(args: Optional[Iterable[str]], fallback_n_ctx: int) -> int:"""Return the context size load_model should treat as requested.@@ -953,6 +1005,9 @@ def strip_shadowing_flags(strip_load_mode: bool = False,strip_batch: bool = False,strip_ubatch: bool = False,+ strip_ctx_checkpoints: bool = False,+ strip_cache_ram: bool = False,+ strip_spec_draft_cache: bool = False,) -> list[str]:"""Strip flags that shadow first-class Unsloth settings.@@ -1003,6 +1058,12 @@ def strip_shadowing_flags(shadowing |= _BATCH_FLAGSif strip_ubatch:shadowing |= _UBATCH_FLAGS+ if strip_ctx_checkpoints:+ shadowing |= _CTX_CHECKPOINTS_FLAGS+ if strip_cache_ram:+ shadowing |= _CACHE_RAM_FLAGS+ if strip_spec_draft_cache:+ shadowing |= _SPEC_DRAFT_CACHE_FLAGStokens = [str(a) for a in (args or [])]out: list[str] = []@@ -1083,6 +1144,9 @@ def apply_model_memory_policy("Don't reserve system RAM" drops ``--mlock`` / ``--no-mmap``, leaving thedefault mmap path. With both off nothing is stripped, so a hand-typed flagstill applies.++ The per-model Mmap/Mlock control is resolved separately, by+ ``apply_load_mode_policy``, which runs after this and defers to it."""try:from utils.model_memory_settings import get_model_memory_settings@@ -1127,6 +1191,77 @@ def apply_model_memory_policy(return managed, tokens+def apply_load_mode_policy(+ extra_args: Optional[Iterable[str]],+ *,+ supports_load_mode: bool = False,+ weights_in_host_memory: bool = True,+ requested_load_mode: Optional[str] = None,+) -> tuple[list[str], list[str]]:+ """Resolve the per-model Mmap/Mlock control into llama-server flags.++ Returns ``(managed_flags, extras)``, like ``apply_model_memory_policy``, and+ is meant to run straight after it on the extras that call returned.++ The Model Memory settings win, which is what the Run settings panel tells the+ user, so changing the order without changing ``loadModeOverrideNotice`` makes+ that note wrong. "Keep model in GPU memory" owns the mode outright while it+ applies; "Don't reserve system RAM" vetoes the values holding a full host copy+ (``none``, ``mlock``, ``mmap+mlock``) and leaves ``mmap`` and ``dio`` alone.++ ``auto`` emits nothing: it IS llama.cpp's default, so pinning it would freeze+ what a later build may redefine. An unknown value is dropped rather than passed+ through, since llama-server exits on one.+ """+ tokens = list(extra_args or [])+ mode = _normalize_load_mode_value(requested_load_mode)+ if not mode:+ return [], tokens+ try:+ from utils.model_memory_settings import get_model_memory_settings+ keep_resident, no_ram_reserve = get_model_memory_settings()+ except Exception:+ # Settings unavailable (bare unit-test import): nothing to defer to.+ keep_resident, no_ram_reserve = False, False+ if keep_resident and not no_ram_reserve and weights_in_host_memory:+ logger.info(+ "Model Memory: 'Keep model in GPU memory' owns the load mode; "+ "ignoring the requested %r.",+ mode,+ )+ return [], tokens+ if no_ram_reserve and mode in _LOAD_MODE_MLOCK_VALUES | _LOAD_MODE_RESERVING_VALUES:+ logger.info(+ "Model Memory: 'Don't reserve system RAM' drops the requested load mode %r.",+ mode,+ )+ return [], tokens+ if not supports_load_mode:+ # A build predating the enum understands the spellings it replaced, and+ # only for the values that had one.+ legacy = _LEGACY_LOAD_MODE_FLAGS.get(mode)+ if not legacy:+ logger.info("llama-server has no --load-mode; skipping the requested %r mode.", mode)+ return [], tokens+ return list(legacy), tokens+ # Emitted BEFORE the extras and stripping nothing, like every other control+ # here: a flag typed for THIS load is appended after and last-wins, which is+ # what the panel's diagnostics promise. An INHERITED copy is a different+ # thing, and the route drops that one before it ever reaches here.+ return ["--load-mode", mode], tokens+++def _normalize_load_mode_value(value: Optional[str]) -> str:+ """Canonical --load-mode, or "" for "no opinion" (unset, auto, unknown)."""+ mode = (value or "").strip().lower()+ if mode in {"", "auto"}:+ return ""+ if mode not in _LOAD_MODE_VALUES:+ logger.warning("Ignoring unknown load mode %r", value)+ return ""+ return mode++def _strip_reserving_load_modes(tokens: list[str]) -> list[str]:"""Drop only ``--load-mode`` values that lock or reserve host RAM.@@ -1322,6 +1457,18 @@ def scrub_memory_env(env: dict) -> list[str]:_ENV_TRUE_VALUES = frozenset({"on", "enabled", "true", "1"})_ENV_FALSE_VALUES = frozenset({"off", "disabled", "false", "0"})+# Every --load-mode value llama-server documents, so an unknown one is dropped+# here rather than exiting the child. Mirrored by LOAD_MODES in per-model-config.ts.+_LOAD_MODE_VALUES = frozenset({"auto", "none", "mmap", "mlock", "mmap+mlock", "dio"})+# What each mode meant before the enum existed, for a build that predates it.+# "auto" is the default and needs no flag; "mmap+mlock" is what a bare --mlock+# asked for alongside the default mmap. There is no pre-enum spelling for plain+# "mmap" or for "dio", so those are skipped rather than approximated.+_LEGACY_LOAD_MODE_FLAGS: dict[str, list[str]] = {+ "none": ["--no-mmap"],+ "mlock": ["--no-mmap", "--mlock"],+ "mmap+mlock": ["--mlock"],+}_LOAD_MODE_MLOCK_VALUES = frozenset({"mlock", "mmap+mlock"})# Modes that read the weights into a full host buffer. "dio" streams via# DirectIO and "mmap" maps, so neither reserves RAM for the whole model.diff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.pyindex 7f2d445658b..43a40bdc308 100644--- a/studio/backend/models/inference.py+++ b/studio/backend/models/inference.py@@ -19,7 +19,14 @@ from pydantic import (model_validator,)-from core.inference.llama_server_args import BATCH_MAX, BATCH_MIN, PARALLEL_MAX, PARALLEL_MIN+from core.inference.llama_server_args import (+ BATCH_MAX,+ BATCH_MIN,+ CACHE_RAM_MAX_MIB,+ CTX_CHECKPOINTS_MAX,+ PARALLEL_MAX,+ PARALLEL_MIN,+)from core.inference.video_families import MAX_VIDEO_NUM_FRAMESfrom picker.schemas import MAX_CHAT_TEMPLATE_BYTES@@ -179,6 +186,54 @@ class LoadRequest(BaseModel):"Ignored for non-GGUF models."),)+ load_mode: Optional[Literal["auto", "none", "mmap", "mlock", "mmap+mlock", "dio"]] = Field(+ None,+ description = (+ "How llama-server reads the weights off disk (--load-mode). 'auto' "+ "memory-maps unless a device cannot, 'mmap' forces the mapping, "+ "'mlock' keeps the model in RAM rather than letting it swap or "+ "compress, 'mmap+mlock' does both, 'dio' uses DirectIO where "+ "available and 'none' asks for no special mode. Omit for the "+ "llama.cpp default. The Model Memory settings own host placement, so "+ "'Keep model in GPU memory' replaces this with mmap+mlock and "+ "'Don't reserve system RAM' drops a mode that would hold a full host "+ "copy. Ignored for non-GGUF models."+ ),+ )+ spec_draft_cache_type: Optional[str] = Field(+ None,+ description = (+ "KV cache dtype for the DRAFT model's context "+ "(--spec-draft-type-k / --spec-draft-type-v), for example 'q8_0'. "+ "Separate from cache_type_kv, which is the target model's. Only "+ "reaches the command line when the load attaches a separate draft "+ "model; omit for the llama.cpp default (f16). Ignored for non-GGUF "+ "models."+ ),+ )+ ctx_checkpoints: Optional[int] = Field(+ None,+ ge = 0,+ le = CTX_CHECKPOINTS_MAX,+ description = (+ "Context checkpoints kept per slot (--ctx-checkpoints), which let a "+ "sliding-window model rewind instead of re-processing the prompt. "+ "Omit for the llama.cpp default (32); 0 disables them. "+ "Each costs host memory, and a model without a sliding window "+ "ignores it. Ignored for non-GGUF models."+ ),+ )+ cache_ram: Optional[int] = Field(+ None,+ ge = -1,+ le = CACHE_RAM_MAX_MIB,+ description = (+ "Host memory in MiB llama-server may spend caching prompt state it "+ "has evicted from a slot (--cache-ram). Omit for the llama.cpp "+ "default (8192); 0 disables the cache and -1 lifts the limit. "+ "Ignored for non-GGUF models."+ ),+ )tensor_parallel: bool = Field(False,description = (@@ -249,7 +304,7 @@ class LoadRequest(BaseModel):),)- @field_validator("n_batch", "n_ubatch", mode = "before")+ @field_validator("n_batch", "n_ubatch", "ctx_checkpoints", "cache_ram", mode = "before")@classmethoddef _no_booleans(cls, value: Any) -> Any:# bool subclasses int and pydantic parses non-strictly, so `true` arrives as 1 and@@ -433,6 +488,27 @@ class ValidateModelRequest(BaseModel):le = 16,description = "Draft depth intended for the follow-up load; sizes the draft KV.",)+ spec_draft_cache_type: Optional[str] = Field(+ None,+ description = (+ "Draft KV cache dtype intended for the follow-up load. Sent so this "+ "preflight strips the same inherited draft-cache flags /load would, "+ "and so approves the command the load actually runs. The coexistence "+ "estimate prices the drafter's weights but not its KV, so the value "+ "itself does not move the number."+ ),+ )+ ctx_checkpoints: Optional[int] = Field(+ None,+ ge = 0,+ le = CTX_CHECKPOINTS_MAX,+ description = (+ "Checkpoints (--ctx-checkpoints) intended for the follow-up load, so "+ "the coexistence estimate sizes the SWA cache like /load. Each one is "+ "a per-slot snapshot that scales with the slot's context, so a load "+ "asking for them needs materially more memory than one that does not."+ ),+ )include_context_length: bool = Field(False,description = "Also read the native context length from the local GGUF header. "@@ -446,7 +522,7 @@ class ValidateModelRequest(BaseModel):"guard. Only the leased file's own embedded template is read, never sibling sidecars.",)- _no_booleans = field_validator("n_batch", "n_ubatch", mode = "before")(+ _no_booleans = field_validator("n_batch", "n_ubatch", "ctx_checkpoints", mode = "before")(LoadRequest._no_booleans.__func__)@@ -925,6 +1001,36 @@ class _InferenceRuntimeFields(BaseModel):"when the load left it at the llama.cpp default (or to extra args / env)."),)+ requested_load_mode: Optional[str] = Field(+ None,+ description = (+ "Load mode (--load-mode) the load was invoked with, or None when the "+ "load left it at the llama.cpp default. This is what was REQUESTED: "+ "the Model Memory settings can replace it, and what they emit is "+ "reported by the model-memory settings route instead."+ ),+ )+ requested_spec_draft_cache_type: Optional[str] = Field(+ None,+ description = (+ "Draft KV cache dtype the load was invoked with, or None when the "+ "load left it at the llama.cpp default (or attached no drafter)."+ ),+ )+ requested_ctx_checkpoints: Optional[int] = Field(+ None,+ description = (+ "Checkpoints (--ctx-checkpoints) the load was invoked with, or None "+ "when the load left it at the llama.cpp default."+ ),+ )+ requested_cache_ram: Optional[int] = Field(+ None,+ description = (+ "Host prompt cache size in MiB (--cache-ram) the load was invoked "+ "with, or None when the load left it at the llama.cpp default."+ ),+ )requested_llama_extra_args: Optional[List[str]] = Field(None,description = (diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex cc2147f6519..5cfcbc33ac7 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -5393,6 +5393,11 @@ def _active_gguf_intent(strip_split_mode = False,strip_batch = "n_batch" in request_fields_set,strip_ubatch = "n_ubatch" in request_fields_set,+ strip_ctx_checkpoints = "ctx_checkpoints" in request_fields_set,+ strip_cache_ram = "cache_ram" in request_fields_set,+ strip_spec_draft_cache = "spec_draft_cache_type" in request_fields_set,+ strip_load_mode = "load_mode" in request_fields_set,+ strip_load_mode_aliases = "load_mode" in request_fields_set,)# a strip that changed the list is an override, so the dedupe compares the stripped onebatch_overrides_inherit = batch_stripped_extra != effective_extra@@ -6986,6 +6991,7 @@ def _estimate_gguf_kv_gb(tensor_parallel: bool = False,n_batch: Optional[int] = None,n_ubatch: Optional[int] = None,+ ctx_checkpoints: Optional[int] = None,n_devices: int = 1,is_diffusion: bool = False,) -> float:@@ -6997,7 +7003,10 @@ def _estimate_gguf_kv_gb(context-linear term; ``is_diffusion`` skips them, since the diffusionrunner ignores the llama-server batch flags. 0 if metadata is unreadable."""try:- from core.inference.llama_server_args import parse_ctx_override+ from core.inference.llama_server_args import (+ parse_ctx_override,+ resolve_ctx_checkpoints,+ )probe = LlamaCppBackend()probe._read_gguf_metadata(gguf_path)@@ -7075,6 +7084,11 @@ def _estimate_gguf_kv_gb(default = managed_kv_unified,),n_ubatch = effective_ubatch,+ # Extras beat the field, as at launch: the control emits its flag+ # before them. Per-slot SWA snapshots scale with the slot's context, so+ # a load asking for them needs materially more memory than one that+ # does not.+ ctx_checkpoints = resolve_ctx_checkpoints(llama_extra_args, ctx_checkpoints),flash_attn = False,)# the load reserves ubatch-scaled compute buffers, so they count against training too@@ -7253,6 +7267,7 @@ def _estimate_gguf_required_gb(tensor_parallel: bool = False,n_batch: Optional[int] = None,n_ubatch: Optional[int] = None,+ ctx_checkpoints: Optional[int] = None,n_devices: int = 1,is_diffusion: bool = False,disable_vision: bool = False,@@ -7531,8 +7546,9 @@ def _estimate_gguf_required_gb(tensor_parallel,n_batch,n_ubatch,- n_devices,- is_diffusion,+ ctx_checkpoints = ctx_checkpoints,+ n_devices = n_devices,+ is_diffusion = is_diffusion,)repo = getattr(config, "gguf_hf_repo", None)@@ -8155,7 +8171,20 @@ def _inherited_batch_flags_stripped(request) -> bool:fields_set = getattr(request, "model_fields_set", set())strip_batch = "n_batch" in fields_setstrip_ubatch = "n_ubatch" in fields_set- if not (strip_batch or strip_ubatch):+ # The llama-server tuning group shadows the same way, so an inherited copy of+ # one of its flags counts as an override here too.+ strip_ctx_checkpoints = "ctx_checkpoints" in fields_set+ strip_cache_ram = "cache_ram" in fields_set+ strip_spec_draft_cache = "spec_draft_cache_type" in fields_set+ strip_load_mode = "load_mode" in fields_set+ if not (+ strip_batch+ or strip_ubatch+ or strip_ctx_checkpoints+ or strip_cache_ram+ or strip_spec_draft_cache+ or strip_load_mode+ ):return Falsestored = list(getattr(get_llama_cpp_backend(), "extra_args", None) or ())if not stored:@@ -8170,6 +8199,11 @@ def _inherited_batch_flags_stripped(request) -> bool:strip_split_mode = False,strip_batch = strip_batch,strip_ubatch = strip_ubatch,+ strip_ctx_checkpoints = strip_ctx_checkpoints,+ strip_cache_ram = strip_cache_ram,+ strip_spec_draft_cache = strip_spec_draft_cache,+ strip_load_mode = strip_load_mode,+ strip_load_mode_aliases = strip_load_mode,)!= stored)@@ -8415,6 +8449,7 @@ def _guard_chat_load_against_training(# getattr: older callers hand this guard a bare request doublen_batch = getattr(request, "n_batch", None),n_ubatch = getattr(request, "n_ubatch", None),+ ctx_checkpoints = getattr(request, "ctx_checkpoints", None),tensor_parallel = guard_tensor_parallel,# size the compute buffers for the split the loader would budgetn_devices = guard_n_devices,@@ -8569,6 +8604,13 @@ def _resolve_inherited_extra_args(# a set field emits its own flag; an inherited -b / -ub would last-wins-override itstrip_batch = "n_batch" in fields_set,strip_ubatch = "n_ubatch" in fields_set,+ # same rule for the llama-server tuning group. The load mode strips its+ # deprecated aliases too, because a trailing one resets the whole mode.+ strip_ctx_checkpoints = "ctx_checkpoints" in fields_set,+ strip_cache_ram = "cache_ram" in fields_set,+ strip_spec_draft_cache = "spec_draft_cache_type" in fields_set,+ strip_load_mode = "load_mode" in fields_set,+ strip_load_mode_aliases = "load_mode" in fields_set,)# Inherited, not sent: a flag denylisted since it was stored loses only# itself. The previous behaviour dropped the whole list, so one name addeddiff --git a/studio/backend/tests/test_chat_load_during_training.py b/studio/backend/tests/test_chat_load_during_training.pyindex ae9a554d0c7..f7732762b97 100644--- a/studio/backend/tests/test_chat_load_during_training.py+++ b/studio/backend/tests/test_chat_load_during_training.py@@ -2773,9 +2773,11 @@ class TestEstimateGgufRequiredGb(unittest.TestCase):swa_full = False,kv_unified = False,n_ubatch = None,+ ctx_checkpoints = 0,flash_attn = True,):seen["ctx"] = ctx+ seen["ctx_checkpoints"] = ctx_checkpointsseen["cache_type"] = cache_typeseen["n_parallel"] = n_parallelseen["swa_full"] = swa_fulldiff --git a/studio/backend/tests/test_server_tuning_flags.py b/studio/backend/tests/test_server_tuning_flags.pynew file mode 100644index 00000000000..105198e7d85--- /dev/null+++ b/studio/backend/tests/test_server_tuning_flags.py@@ -0,0 +1,459 @@+# 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 four first-class llama-server tuning fields.++load_mode (--load-mode), spec_draft_cache_type (--spec-draft-type-k/-v),+ctx_checkpoints (--ctx-checkpoints) and cache_ram (--cache-ram): pydantic bounds,+the Model Memory precedence the Run settings panel promises, shadow stripping,+reload dedupe and the stored-override mapping.++Sibling of test_batch_sizes_per_load.py, which covers the same shape for the+batch pair.+"""++from __future__ import annotations++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")+_structlog_stub.get_logger = lambda *a, **k: __import__("logging").getLogger("stub")+sys.modules.setdefault("structlog", _structlog_stub)++import httpx # noqa: F401++from core.inference.llama_cpp import (+ GgufLoadIntent,+ LlamaCppBackend,+ _normalized_load_mode,+)+from core.inference import llama_server_args as lsa+from core.inference.llama_server_args import (+ CACHE_RAM_MAX_MIB,+ CTX_CHECKPOINTS_MAX,+ apply_load_mode_policy,+ parse_ctx_checkpoints_override,+ resolve_ctx_checkpoints,+ strip_shadowing_flags,+)+from models.inference import LoadRequest+from utils.openai_auto_switch_settings import (+ model_override_load_kwargs,+ normalize_model_override,+)+++# --------------------------------------------------------------------------- request+++def test_load_request_defaults_are_unset():+ request = LoadRequest(model_path = "owner/repo")+ assert request.load_mode is None+ assert request.spec_draft_cache_type is None+ assert request.ctx_checkpoints is None+ assert request.cache_ram is None++[email protected]("mode", ["auto", "none", "mmap", "mlock", "mmap+mlock", "dio"])+def test_load_request_accepts_every_documented_mode(mode):+ assert LoadRequest(model_path = "owner/repo", load_mode = mode).load_mode == mode+++def test_load_request_refuses_an_unknown_mode():+ with pytest.raises(ValueError):+ LoadRequest(model_path = "owner/repo", load_mode = "mmap + mlock")+++def test_ctx_checkpoints_and_cache_ram_bounds():+ assert LoadRequest(model_path = "owner/repo", ctx_checkpoints = 0).ctx_checkpoints == 0+ assert (+ LoadRequest(model_path = "owner/repo", ctx_checkpoints = CTX_CHECKPOINTS_MAX).ctx_checkpoints+ == CTX_CHECKPOINTS_MAX+ )+ # -1 is "no limit" and 0 disables the cache, so both are inside the range+ assert LoadRequest(model_path = "owner/repo", cache_ram = -1).cache_ram == -1+ assert LoadRequest(model_path = "owner/repo", cache_ram = 0).cache_ram == 0+ for field, bad in (+ ("ctx_checkpoints", -1),+ ("ctx_checkpoints", CTX_CHECKPOINTS_MAX + 1),+ ("cache_ram", -2),+ ("cache_ram", CACHE_RAM_MAX_MIB + 1),+ ):+ with pytest.raises(ValueError):+ LoadRequest(model_path = "owner/repo", **{field: bad})++[email protected]("field", ["ctx_checkpoints", "cache_ram"])+def test_integer_fields_reject_json_booleans(field):+ # bool subclasses int, so lax pydantic would turn `true` into 1 and launch the+ # child with a number nobody typed. Same guard the batch pair carries.+ with pytest.raises(ValueError):+ LoadRequest(model_path = "owner/repo", **{field: True})+ assert getattr(LoadRequest(model_path = "owner/repo", **{field: "16"}), field) == 16+++# ------------------------------------------------------------------- load mode policy+++def memory_settings(monkeypatch):+ """Stand in for utils.model_memory_settings, which needs the settings DB."""+ state = {"keep_resident": False, "no_ram_reserve": False}+ module = _types.ModuleType("utils.model_memory_settings")+ module.get_model_memory_settings = lambda: (+ state["keep_resident"],+ state["no_ram_reserve"],+ )+ monkeypatch.setitem(sys.modules, "utils.model_memory_settings", module)+ return state+++def test_load_mode_is_emitted_when_no_setting_objects(memory_settings):+ managed, extras = apply_load_mode_policy(+ [], supports_load_mode = True, requested_load_mode = "mlock"+ )+ assert managed == ["--load-mode", "mlock"]+ assert extras == []+++def test_auto_and_unknown_modes_emit_nothing(memory_settings):+ for mode in (None, "", "auto", "AUTO", "mmap + mlock"):+ assert apply_load_mode_policy(+ ["--top-k", "20"], supports_load_mode = True, requested_load_mode = mode+ ) == ([], ["--top-k", "20"])+++def test_an_explicitly_typed_load_mode_still_wins(memory_settings):+ # The control emits BEFORE the extras, so a flag typed for THIS load is+ # appended after it and last-wins, which is what the panel's diagnostics+ # promise. Only the route strips, and only an INHERITED copy.+ managed, extras = apply_load_mode_policy(+ ["--load-mode", "dio", "--top-k", "20"],+ supports_load_mode = True,+ requested_load_mode = "mmap",+ )+ assert managed == ["--load-mode", "mmap"]+ assert extras == ["--load-mode", "dio", "--top-k", "20"]+++def test_the_route_strips_an_inherited_load_mode(memory_settings):+ # A trailing alias resets the whole mode in llama.cpp, so an INHERITED copy+ # would silently undo the pick. The route drops it when the field is set, the+ # same rule the batch pair follows; the policy itself strips nothing.+ inherited = ["--no-mmap", "--mlock", "--top-k", "20"]+ assert strip_shadowing_flags(+ inherited,+ strip_context = False,+ strip_cache = False,+ strip_spec = False,+ strip_template = False,+ strip_split_mode = False,+ strip_load_mode = True,+ strip_load_mode_aliases = True,+ ) == ["--mlock", "--top-k", "20"]+++def test_keep_resident_owns_the_mode(memory_settings):+ memory_settings["keep_resident"] = True+ assert apply_load_mode_policy([], supports_load_mode = True, requested_load_mode = "dio") == (+ [],+ [],+ )+++def test_keep_resident_releases_the_mode_when_the_weights_are_not_host_resident(memory_settings):+ # The page-lock is skipped for a fully offloaded model, so nothing else is+ # claiming the mode and the pick applies.+ memory_settings["keep_resident"] = True+ managed, _ = apply_load_mode_policy(+ [],+ supports_load_mode = True,+ weights_in_host_memory = False,+ requested_load_mode = "dio",+ )+ assert managed == ["--load-mode", "dio"]++[email protected]("mode", ["none", "mlock", "mmap+mlock"])+def test_no_ram_reserve_vetoes_the_reserving_modes(memory_settings, mode):+ memory_settings["no_ram_reserve"] = True+ assert apply_load_mode_policy([], supports_load_mode = True, requested_load_mode = mode) == ([], [])++[email protected]("mode", ["mmap", "dio"])+def test_no_ram_reserve_leaves_the_non_reserving_modes(memory_settings, mode):+ # Neither holds a full host copy, so there is nothing for the setting to veto.+ memory_settings["no_ram_reserve"] = True+ managed, _ = apply_load_mode_policy([], supports_load_mode = True, requested_load_mode = mode)+ assert managed == ["--load-mode", mode]+++def test_a_build_without_load_mode_falls_back_to_the_deprecated_spellings(memory_settings):+ assert apply_load_mode_policy([], supports_load_mode = False, requested_load_mode = "mmap+mlock")[+ 0+ ] == ["--mlock"]+ assert apply_load_mode_policy([], supports_load_mode = False, requested_load_mode = "none")[0] == [+ "--no-mmap"+ ]+ # No pre-enum spelling for these two, so they are skipped rather than approximated+ for mode in ("mmap", "dio"):+ assert (+ apply_load_mode_policy([], supports_load_mode = False, requested_load_mode = mode)[0] == []+ )+++def test_the_panel_and_the_policy_agree_on_which_modes_no_reserve_vetoes():+ # The Run settings note names the setting that wins, so the two sets have to+ # be the same one. RAM_RESERVING_LOAD_MODES in model-config-page.tsx.+ ui = (+ Path(_BACKEND_DIR).parent+ / "frontend"+ / "src"+ / "features"+ / "model-picker"+ / "components"+ / "model-config-page.tsx"+ ).read_text(encoding = "utf-8")+ listed = ui.split("const RAM_RESERVING_LOAD_MODES = new Set([", 1)[1].split("]")[0]+ assert {value.strip().strip('"') for value in listed.split(",") if value.strip()} == set(+ lsa._LOAD_MODE_MLOCK_VALUES | lsa._LOAD_MODE_RESERVING_VALUES+ )+++# ---------------------------------------------------------------------- shadow strips+++def test_strip_shadowing_flags_tuning_toggles():+ args = [+ "--ctx-checkpoints",+ "8",+ "--cache-ram=2048",+ "--spec-draft-type-k",+ "q8_0",+ "-ctvd",+ "q8_0",+ "--top-k",+ "20",+ ]+ assert strip_shadowing_flags(args, strip_ctx_checkpoints = True) == args[2:]+ assert "--cache-ram=2048" not in strip_shadowing_flags(args, strip_cache_ram = True)+ stripped = strip_shadowing_flags(args, strip_spec_draft_cache = True)+ assert stripped == ["--ctx-checkpoints", "8", "--cache-ram=2048", "--top-k", "20"]+ # nothing is stripped by default, so an inherited flag survives a load that+ # sets none of these fields+ assert strip_shadowing_flags(args) == args+++def test_swa_checkpoints_is_the_same_setting():+ # upstream's older spelling of --ctx-checkpoints+ assert strip_shadowing_flags(["--swa-checkpoints", "4"], strip_ctx_checkpoints = True) == []+++def test_the_effective_checkpoint_count_comes_from_the_extras():+ """A typed --ctx-checkpoints wins at launch, so it has to win in the sizing.++ The control emits its flag before the extras and llama.cpp is last-wins, so+ ctx_checkpoints=0 with "--ctx-checkpoints 256" in the extras allocates 256+ per-slot snapshots. Budgeting the field there under-reserves the fit.+ """+ assert parse_ctx_checkpoints_override(["--ctx-checkpoints", "256"]) == 256+ assert parse_ctx_checkpoints_override(["--swa-checkpoints=8"]) == 8+ # last-wins, like every other override parser here+ assert parse_ctx_checkpoints_override(["-ctxcp", "4", "--ctx-checkpoints", "16"]) == 16+ assert parse_ctx_checkpoints_override(["--top-k", "20"]) is None+ # malformed extras are refused at the boundary; sizing must not raise+ assert parse_ctx_checkpoints_override(["--ctx-checkpoints", "many"]) is None++ assert resolve_ctx_checkpoints(["--ctx-checkpoints", "256"], 0) == 256+ assert resolve_ctx_checkpoints(None, 8) == 8+ assert resolve_ctx_checkpoints([], None) == 0+++def test_an_unsupported_draft_cache_dtype_is_dropped_not_launched():+ """llama-server exits on a dtype it cannot map, and by then the old model is gone."""+ import inspect++ from core.inference import llama_cpp++ assert "Q8_0".strip().lower() in llama_cpp._VALID_KV_CACHE_TYPES+ assert "fp16" not in llama_cpp._VALID_KV_CACHE_TYPES+ source = inspect.getsource(llama_cpp.LlamaCppBackend.load_model)+ # normalized and allow-listed before emission, like the main cache dtype+ assert "_draft_cache_type not in _VALID_KV_CACHE_TYPES" in source+ assert "Ignoring unsupported draft KV cache type" in source+++# ----------------------------------------------------------------------------- dedupe+++def _loaded_backend() -> LlamaCppBackend:+ backend = LlamaCppBackend()+ backend._process = object()+ backend._healthy = True+ backend._model_identifier = "owner/repo"+ backend._hf_variant = "Q4_K_M"+ backend._requested_n_ctx = 8192+ backend._requested_spec_mode = "auto"+ return backend+++def _intent(**kwargs) -> GgufLoadIntent:+ return GgufLoadIntent(+ model_identifier = "owner/repo",+ hf_variant = "Q4_K_M",+ n_ctx = 8192,+ speculative_type = "auto",+ **kwargs,+ )+++def test_dedupe_matches_the_same_tuning():+ backend = _loaded_backend()+ backend._requested_load_mode = "dio"+ backend._requested_ctx_checkpoints = 8+ backend._requested_cache_ram = 2048+ assert (+ backend._runtime_matches_intent(+ _intent(load_mode = "dio", ctx_checkpoints = 8, cache_ram = 2048), None+ )+ is True+ )+++def test_dedupe_reads_auto_and_unset_as_the_same_load():+ # Both launch the same command, so picking Auto must not reload a server+ # already running it.+ backend = _loaded_backend()+ assert backend._runtime_matches_intent(_intent(load_mode = "auto"), None) is True+ assert _normalized_load_mode("AUTO ") is None+++ "changed",+ [+ {"load_mode": "mlock"},+ {"ctx_checkpoints": 16},+ {"cache_ram": 0},+ ],+)+def test_dedupe_reloads_on_a_tuning_change(changed):+ backend = _loaded_backend()+ backend._requested_load_mode = "dio"+ backend._requested_ctx_checkpoints = 8+ backend._requested_cache_ram = 2048+ intent = _intent(**{"load_mode": "dio", "ctx_checkpoints": 8, "cache_ram": 2048, **changed})+ assert backend._runtime_matches_intent(intent, None) is False+++def test_dedupe_reloads_when_the_draft_cache_is_cleared():+ # Clearing the control back to the f16 default has to relaunch, or the server+ # keeps the quantized draft cache the panel no longer shows. Both sides hold+ # what was REQUESTED, so a load that asked for nothing still matches one that+ # asked for nothing.+ backend = _loaded_backend()+ backend._requested_spec_draft_cache_type = "q8_0"+ assert backend._runtime_matches_intent(_intent(), None) is False+ assert backend._runtime_matches_intent(_intent(spec_draft_cache_type = "q8_0"), None) is True+ assert backend._runtime_matches_intent(_intent(spec_draft_cache_type = "q4_0"), None) is False+ backend._requested_spec_draft_cache_type = None+ assert backend._runtime_matches_intent(_intent(), None) is True+++def test_dedupe_ignores_the_tuning_for_diffusion():+ # The diffusion runner builds its own command and passes none of these.+ backend = _loaded_backend()+ backend._is_diffusion = True+ backend._diffusion_requested_ngl = None+ backend._gpu_layers = -1+ assert backend._runtime_matches_intent(_intent(load_mode = "mlock"), None) is True+++def test_the_coexistence_estimate_charges_the_requested_checkpoints():+ """The training guard must size the SWA checkpoints the load will ask for.++ Checkpoints are per-slot snapshots whose size scales with the slot's context+ (ggml-org/llama.cpp#21690 is an OOM caused by exactly this), so an estimate+ that assumes zero can admit a load beside training that then runs out of VRAM.+ """+ import inspect++ from routes import inference as inference_routes++ # threaded end to end: the guard reads the field, the estimator forwards it,+ # and the KV sizing charges it+ assert (+ "ctx_checkpoints"+ in inspect.signature(inference_routes._estimate_gguf_required_gb).parameters+ )+ assert "ctx_checkpoints" in inspect.signature(inference_routes._estimate_gguf_kv_gb).parameters+ source = inspect.getsource(inference_routes._guard_chat_load_against_training)+ assert 'ctx_checkpoints = getattr(request, "ctx_checkpoints", None)' in source+ kv_source = inspect.getsource(inference_routes._estimate_gguf_kv_gb)+ # priced on what the launch runs, so a typed --ctx-checkpoints wins here too+ assert "resolve_ctx_checkpoints(llama_extra_args, ctx_checkpoints)" in kv_source+++# ------------------------------------------------------------------- override storage+++def test_override_store_round_trip():+ entry = normalize_model_override(+ {+ "load_mode": "MMAP+MLOCK",+ "ctx_checkpoints": 0,+ "cache_ram": -1,+ "speculative_type": "dspark",+ "spec_draft_cache_type": "Q8_0",+ }+ )+ assert entry["load_mode"] == "mmap+mlock"+ # 0 and -1 are values, not "unset", so both are stored+ assert entry["ctx_checkpoints"] == 0+ assert entry["cache_ram"] == -1+ assert entry["spec_draft_cache_type"] == "q8_0"+++def test_override_store_drops_values_the_loader_would_refuse():+ entry = normalize_model_override(+ {+ "load_mode": "swap",+ "ctx_checkpoints": True,+ "cache_ram": -2,+ }+ )+ assert "load_mode" not in entry+ assert "ctx_checkpoints" not in entry+ assert "cache_ram" not in entry+++def test_override_store_drops_a_draft_dtype_without_a_separate_drafter():+ # ngram loads no draft model, so there is no draft context for the dtype to+ # apply to; storing it would show an edit the loader ignores.+ entry = normalize_model_override({"speculative_type": "ngram", "spec_draft_cache_type": "q8_0"})+ assert "spec_draft_cache_type" not in entry+++def test_override_kwargs_are_gguf_only():+ override = {+ "load_mode": "dio",+ "spec_draft_cache_type": "q8_0",+ "ctx_checkpoints": 8,+ "cache_ram": 2048,+ }+ kwargs = model_override_load_kwargs(override, is_gguf = True)+ for key, value in override.items():+ assert kwargs[key] == value+ # the flags are llama-server's, so a transformers load carries none of them+ assert not set(override) & set(model_override_load_kwargs(override, is_gguf = False))diff --git a/studio/backend/utils/openai_auto_switch_settings.py b/studio/backend/utils/openai_auto_switch_settings.pyindex 5e93687cffa..e9e35c7510b 100644--- a/studio/backend/utils/openai_auto_switch_settings.py+++ b/studio/backend/utils/openai_auto_switch_settings.py@@ -430,6 +430,16 @@ VALID_SPECULATIVE_TYPES = frozenset(DRAFT_N_MAX_SPEC_TYPES = frozenset({"mtp", "mtp+ngram", "draft-mtp", "dspark", "draft-dspark", "dflash", "draft-dflash"})+# Only these load a separate draft model, and so a draft context for the dtype to+# apply to (mirrors SEPARATE_DRAFT_MODEL_SPEC_TYPES in the UI).+SEPARATE_DRAFT_MODEL_SPEC_TYPES = frozenset({"dspark", "draft-dspark", "dflash", "draft-dflash"})+# Mirrors _LOAD_MODE_VALUES in llama_server_args.py. "auto" is the llama.cpp+# default and is not stored: an entry holding it would pin what a build may redefine.+VALID_LOAD_MODES = frozenset({"none", "mmap", "mlock", "mmap+mlock", "dio"})+# Mirrors CTX_CHECKPOINTS_MAX / CACHE_RAM_MAX_MIB in llama_server_args.py.+CTX_CHECKPOINTS_MAX = 256+CACHE_RAM_MIN_MIB = -1+CACHE_RAM_MAX_MIB = 1024 * 1024VALID_GPU_MEMORY_MODES = frozenset({"auto", "manual"})# Mirrors MLX_KV_BITS_CHOICES in core/inference/mlx_inference.py; a set, not a range.VALID_MLX_KV_BITS = frozenset({8, 6, 5, 4, 3, 2})@@ -523,6 +533,14 @@ def normalize_model_override(spec_draft_n_max = _bounded_int(payload.get("spec_draft_n_max"), minimum = 1, maximum = 16)if spec_draft_n_max:entry["spec_draft_n_max"] = spec_draft_n_max+ # Same rule, narrower set: the dtype needs a separate draft model, and only+ # the sidecar modes always load one.+ if speculative_type in SEPARATE_DRAFT_MODEL_SPEC_TYPES:+ spec_draft_cache_type = _clean_str(+ payload.get("spec_draft_cache_type"), VALID_KV_CACHE_DTYPES+ )+ if spec_draft_cache_type:+ entry["spec_draft_cache_type"] = spec_draft_cache_type# Blank or out of range means "follow the server-wide --parallel default".n_parallel = _bounded_int(@@ -537,6 +555,24 @@ def normalize_model_override(if parsed:entry[key] = parsed+ load_mode = _clean_str(payload.get("load_mode"), VALID_LOAD_MODES)+ if load_mode:+ entry["load_mode"] = load_mode++ # 0 and -1 are meaningful (no checkpoints; no cache limit), so these store on+ # "is not None" rather than on truth, unlike the batch sizes above.+ ctx_checkpoints = _bounded_int(+ payload.get("ctx_checkpoints"), minimum = 0, maximum = CTX_CHECKPOINTS_MAX+ )+ if ctx_checkpoints is not None:+ entry["ctx_checkpoints"] = ctx_checkpoints++ cache_ram = _bounded_int(+ payload.get("cache_ram"), minimum = CACHE_RAM_MIN_MIB, maximum = CACHE_RAM_MAX_MIB+ )+ if cache_ram is not None:+ entry["cache_ram"] = cache_ram+if _coerce_bool(payload.get("tensor_parallel")):entry["tensor_parallel"] = True@@ -661,6 +697,10 @@ def model_override_load_kwargs(override: dict[str, Any], *, is_gguf: bool) -> dikwargs["n_batch"] = override["n_batch"]if override.get("n_ubatch") is not None:kwargs["n_ubatch"] = override["n_ubatch"]+ # llama-server flags too, so GGUF-only like the rest of this block+ for key in ("load_mode", "spec_draft_cache_type", "ctx_checkpoints", "cache_ram"):+ if override.get(key) is not None:+ kwargs[key] = override[key]if override.get("gpu_memory_mode") is not None:kwargs["gpu_memory_mode"] = override["gpu_memory_mode"]if override.get("gpu_layers") is not None:@@ -696,6 +736,9 @@ def model_override_load_kwargs(override: dict[str, Any], *, is_gguf: bool) -> distrip_split_mode = bool(kwargs.get("tensor_parallel")),strip_batch = "n_batch" in kwargs,strip_ubatch = "n_ubatch" in kwargs,+ strip_ctx_checkpoints = "ctx_checkpoints" in kwargs,+ strip_cache_ram = "cache_ram" in kwargs,+ strip_spec_draft_cache = "spec_draft_cache_type" in kwargs,)return kwargsdiff --git a/studio/frontend/src/features/api-monitor/components/saved-model-settings.tsx b/studio/frontend/src/features/api-monitor/components/saved-model-settings.tsxindex d6d52d5080f..76d094d90cc 100644--- a/studio/frontend/src/features/api-monitor/components/saved-model-settings.tsx+++ b/studio/frontend/src/features/api-monitor/components/saved-model-settings.tsx@@ -40,6 +40,21 @@ function describeOverride(override: ApiModelOverride): string[] {if (override.n_ubatch) {parts.push(`ubatch ${override.n_ubatch}`);}+ if (override.load_mode) {+ parts.push(`load ${override.load_mode}`);+ }+ if (override.spec_draft_cache_type) {+ parts.push(`draft KV ${override.spec_draft_cache_type}`);+ }+ // Both compared against undefined rather than tested for truth: 0 is a value the+ // user can pick for either (no checkpoints, no host cache) and would otherwise+ // be listed as unset.+ if (override.ctx_checkpoints !== undefined) {+ parts.push(`${override.ctx_checkpoints} checkpoints`);+ }+ if (override.cache_ram !== undefined) {+ parts.push(`cache RAM ${override.cache_ram} MiB`);+ }if (override.tensor_parallel) {parts.push("tensor parallel");}diff --git a/studio/frontend/src/features/chat/api/chat-adapter.ts b/studio/frontend/src/features/chat/api/chat-adapter.tsindex d91a90b34b0..b9b1c2c5c94 100644--- a/studio/frontend/src/features/chat/api/chat-adapter.ts+++ b/studio/frontend/src/features/chat/api/chat-adapter.ts@@ -2,6 +2,11 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import { mlxRuntimeStateFrom } from "../lib/mlx-runtime-state";+import {+ clearedServerTuningState,+ committedServerTuningState,+ serverTuningLoadPayload,+} from "../lib/server-tuning-fields";import { getAuthToken } from "@/features/auth";import { prepareHfTokenForUse } from "@/features/hf-auth";import { DOWNLOAD_KIND } from "@/features/hub/download-manager/constants";@@ -2027,6 +2032,14 @@ const VISIBLE_MODEL_RUNTIME_KEYS = ["loadedNBatch","nUbatch","loadedNUbatch",+ "specDraftCacheDtype",+ "loadedSpecDraftCacheDtype",+ "loadMode",+ "loadedLoadMode",+ "ctxCheckpoints",+ "loadedCtxCheckpoints",+ "cacheRam",+ "loadedCacheRam","tensorParallel","loadedTensorParallel","loadedDisableVision",@@ -2965,6 +2978,10 @@ async function autoLoadSmallestModel(options?: AutoLoadOptions): Promise<{// omitted when blank: a null counts as set and strips inherited -b / -ub...(config.nBatch != null ? { n_batch: config.nBatch } : {}),...(config.nUbatch != null ? { n_ubatch: config.nUbatch } : {}),+ // Same omit-when-blank rule, and the same values the load sends:+ // the draft cache dtype changes what the estimate charges the+ // drafter, so a preflight without it disagrees with the launch.+ ...serverTuningLoadPayload(config),// Checked with the same arguments the load below sends, or a list// the backend refuses would pass this gate and fail the launch....(resolvedExtraArgs !== undefined@@ -3016,6 +3033,9 @@ async function autoLoadSmallestModel(options?: AutoLoadOptions): Promise<{n_parallel: config.nParallel ?? null,...(config.nBatch != null ? { n_batch: config.nBatch } : {}),...(config.nUbatch != null ? { n_ubatch: config.nUbatch } : {}),+ // Remembered like the rest of this block, or the auto-load reverts+ // an override the user asked to be remembered.+ ...serverTuningLoadPayload(config),// Remembered pass-through arguments, for the same reason as the rest of// this block: nothing is resident at startup, so the omission path has// nothing to inherit them from and the model would come up without the@@ -3134,6 +3154,7 @@ async function autoLoadSmallestModel(options?: AutoLoadOptions): Promise<{loadedNBatch: committedNBatch,nUbatch: committedNUbatch,loadedNUbatch: committedNUbatch,+ ...committedServerTuningState(config, loadResp.is_diffusion ?? false),// What this launch is running, for a later rollback. The status applier// cannot seed it: the model-loading lease is held for the whole of this// load, which is exactly the guard that stops a mid-switch poll writing@@ -3188,6 +3209,7 @@ async function autoLoadSmallestModel(options?: AutoLoadOptions): Promise<{loadedNBatch: null,nUbatch: null,loadedNUbatch: null,+ ...clearedServerTuningState(),// Same reason, and the baseline has to be cleared rather than left: a// rollback to THIS model must not resend a GGUF's arguments.loadedLlamaExtraArgs: null,@@ -3518,6 +3540,7 @@ async function autoLoadSmallestModel(options?: AutoLoadOptions): Promise<{loadedNBatch: null,nUbatch: null,loadedNUbatch: null,+ ...clearedServerTuningState(),tensorParallel: loadResp.tensor_parallel ?? false,loadedTensorParallel: loadResp.tensor_parallel ?? false,loadedDisableVision: loadResp.disable_vision ?? false,diff --git a/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts b/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.tsindex f6e412c1e27..f1d6196c2cb 100644--- a/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts+++ b/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts@@ -2,6 +2,12 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import { mlxRuntimeStateFrom } from "../lib/mlx-runtime-state";+import {+ type ServerTuningValues,+ clearedServerTuningState,+ committedServerTuningState,+ serverTuningLoadPayload,+} from "../lib/server-tuning-fields";import { createElement, useCallback, useEffect, useRef, useState } from "react";import { toast } from "@/lib/toast";import { subscribeModelLifecycle } from "@/lib/model-lifecycle-events";@@ -1082,6 +1088,12 @@ export function useChatModelRuntime() {typeof selection !== "string" && selection.previousConfig? (selection.previousConfig.nUbatch ?? null): useChatRuntimeStore.getState().nUbatch;+ // The outgoing tuning intent, read the same way and for the same+ // reason: a rollback restores the control, not the echo.+ const previousServerTuning: ServerTuningValues =+ typeof selection !== "string" && selection.previousConfig+ ? selection.previousConfig+ : useChatRuntimeStore.getState();// Same reason: the rollback echo would overwrite an edit staged against it.const previousMlxKvBits =typeof selection !== "string" && selection.previousConfig@@ -1252,6 +1264,16 @@ export function useChatModelRuntime() {pendingLoadConfig?.nBatch ?? stateBeforeUnload.nBatch;let loadNUbatch =pendingLoadConfig?.nUbatch ?? stateBeforeUnload.nUbatch;+ let loadServerTuning: ServerTuningValues = {+ loadMode: pendingLoadConfig?.loadMode ?? stateBeforeUnload.loadMode,+ specDraftCacheDtype:+ pendingLoadConfig?.specDraftCacheDtype ??+ stateBeforeUnload.specDraftCacheDtype,+ ctxCheckpoints:+ pendingLoadConfig?.ctxCheckpoints ??+ stateBeforeUnload.ctxCheckpoints,+ cacheRam: pendingLoadConfig?.cacheRam ?? stateBeforeUnload.cacheRam,+ };try {// Lightweight pre-flight validation: avoid unloading a working model// if the new identifier is clearly invalid (e.g. bad HF id / path).@@ -1293,6 +1315,16 @@ export function useChatModelRuntime() {const validateNUbatch = resetsPerModelSettings? (pendingLoadConfig?.nUbatch ?? null): loadNUbatch;+ const validateServerTuning: ServerTuningValues =+ resetsPerModelSettings+ ? {+ loadMode: pendingLoadConfig?.loadMode ?? null,+ specDraftCacheDtype:+ pendingLoadConfig?.specDraftCacheDtype ?? null,+ ctxCheckpoints: pendingLoadConfig?.ctxCheckpoints ?? null,+ cacheRam: pendingLoadConfig?.cacheRam ?? null,+ }+ : loadServerTuning;const validateMaxSeqLength = resolveFitMaxSeqLength(isGguf,loadGpuMemoryMode,@@ -1336,6 +1368,9 @@ export function useChatModelRuntime() {...(validateNUbatch != null? { n_ubatch: validateNUbatch }: {}),+ // Same omit-when-blank rule, and the same values: the preflight+ // has to approve the command the follow-up /load sends.+ ...serverTuningLoadPayload(validateServerTuning),// The same list the load below sends. A --ctx-size or cache// override in here changes the memory this preflight estimates,// so omitting it approves a different command: during training@@ -1438,6 +1473,9 @@ export function useChatModelRuntime() {loadedNBatch: null,nUbatch: null,loadedNUbatch: null,+ // Per-model too, and cleared in both halves: a baseline left from+ // the model that just went would be re-sent by a later rollback.+ ...clearedServerTuningState(),// Per-model GPU knobs must not follow onto a different model// (gpuMemoryMode is a standing preference and is kept).selectedGpuIds: null,@@ -1457,6 +1495,13 @@ export function useChatModelRuntime() {loadNParallel = pendingLoadConfig?.nParallel ?? null;loadNBatch = pendingLoadConfig?.nBatch ?? null;loadNUbatch = pendingLoadConfig?.nUbatch ?? null;+ loadServerTuning = {+ loadMode: pendingLoadConfig?.loadMode ?? null,+ specDraftCacheDtype:+ pendingLoadConfig?.specDraftCacheDtype ?? null,+ ctxCheckpoints: pendingLoadConfig?.ctxCheckpoints ?? null,+ cacheRam: pendingLoadConfig?.cacheRam ?? null,+ };// Both payload-only. The store keeps its values: a width is dormant// preset state off MLX, and a completed load rewrites both anyway.loadMlxKvBits = pendingLoadConfig?.mlxKvBits ?? null;@@ -1554,6 +1599,11 @@ export function useChatModelRuntime() {...(isGguf && loadNUbatch != null? { n_ubatch: loadNUbatch }: {}),+ // llama-server's own, so gated like the extras above: GGUF, and not+ // the diffusion runner, which builds its command without them.+ ...(isGguf && !targetIsDiffusion+ ? serverTuningLoadPayload(loadServerTuning)+ : {}),tensor_parallel: loadTensorParallel,disable_vision: loadDisableVision,gpu_memory_mode: loadGpuMemoryMode,@@ -1654,6 +1704,11 @@ export function useChatModelRuntime() {!(loadResponse.is_diffusion ?? false)? (loadNUbatch ?? null): null;+ const committedServerTuning =+ (loadResponse.is_gguf ?? false) &&+ !(loadResponse.is_diffusion ?? false)+ ? committedServerTuningState(loadServerTuning)+ : clearedServerTuningState();const nativeCtx = loadResponse.is_gguf? (loadResponse.context_length ?? 131072): null;@@ -1754,6 +1809,7 @@ export function useChatModelRuntime() {loadedNParallel: committedSlots,nBatch: committedNBatch,loadedNBatch: committedNBatch,+ ...committedServerTuning,// What this model is running, for the rollback below. An omitted field// inherited the resident process's list, so the last thing we knew// still holds unless this was a different model.@@ -1890,6 +1946,13 @@ export function useChatModelRuntime() {...(stateBeforeUnload.loadedNUbatch != null? { n_ubatch: stateBeforeUnload.loadedNUbatch }: {}),+ ...serverTuningLoadPayload({+ loadMode: stateBeforeUnload.loadedLoadMode,+ specDraftCacheDtype:+ stateBeforeUnload.loadedSpecDraftCacheDtype,+ ctxCheckpoints: stateBeforeUnload.loadedCtxCheckpoints,+ cacheRam: stateBeforeUnload.loadedCacheRam,+ }),// Explicit, unlike the batch pair above: the failed switch left the// TARGET resident, so an omitted field here inherits across models,// which the route refuses, and the previous model would come back@@ -1943,6 +2006,19 @@ export function useChatModelRuntime() {loadedNBatch: stateBeforeUnload.loadedNBatch ?? null,nUbatch: previousNUbatch,loadedNUbatch: stateBeforeUnload.loadedNUbatch ?? null,+ // Same split: the controls keep the outgoing model's intent and+ // the baselines come from what that model was launched with.+ loadMode: previousServerTuning.loadMode ?? null,+ loadedLoadMode: stateBeforeUnload.loadedLoadMode ?? null,+ specDraftCacheDtype:+ previousServerTuning.specDraftCacheDtype ?? null,+ loadedSpecDraftCacheDtype:+ stateBeforeUnload.loadedSpecDraftCacheDtype ?? null,+ ctxCheckpoints: previousServerTuning.ctxCheckpoints ?? null,+ loadedCtxCheckpoints:+ stateBeforeUnload.loadedCtxCheckpoints ?? null,+ cacheRam: previousServerTuning.cacheRam ?? null,+ loadedCacheRam: stateBeforeUnload.loadedCacheRam ?? null,loadedSpeculativeType: rollbackSpeculativeType,loadedSpecDraftNMax:rollbackResponse.spec_draft_n_max ?? null,diff --git a/studio/frontend/src/features/chat/lib/apply-inference-status-to-store.ts b/studio/frontend/src/features/chat/lib/apply-inference-status-to-store.tsindex 41ac07bc329..eb20aa0b1bb 100644--- a/studio/frontend/src/features/chat/lib/apply-inference-status-to-store.ts+++ b/studio/frontend/src/features/chat/lib/apply-inference-status-to-store.ts@@ -263,6 +263,44 @@ export function applyActiveModelStatusToStore(seedLoadParams,modelChanged: slotsModelChanged,});+ // The llama-server tuning group follows the same rule, and resolveBatchSizeSeed+ // is generic in the value type for exactly this: each one is an echo of what the+ // load REQUESTED, which is what makes the steady-poll and dirty-control cases+ // identical to the batch pair's.+ const loadModeSeed = resolveBatchSizeSeed<string>({+ incoming: status.requested_load_mode,+ isGguf: status.is_gguf ?? true,+ previous: { value: prevState.loadMode, loaded: prevState.loadedLoadMode },+ seedLoadParams,+ modelChanged: slotsModelChanged,+ });+ const specDraftCacheSeed = resolveBatchSizeSeed<string>({+ incoming: status.requested_spec_draft_cache_type,+ isGguf: status.is_gguf ?? true,+ previous: {+ value: prevState.specDraftCacheDtype,+ loaded: prevState.loadedSpecDraftCacheDtype,+ },+ seedLoadParams,+ modelChanged: slotsModelChanged,+ });+ const ctxCheckpointsSeed = resolveBatchSizeSeed({+ incoming: status.requested_ctx_checkpoints,+ isGguf: status.is_gguf ?? true,+ previous: {+ value: prevState.ctxCheckpoints,+ loaded: prevState.loadedCtxCheckpoints,+ },+ seedLoadParams,+ modelChanged: slotsModelChanged,+ });+ const cacheRamSeed = resolveBatchSizeSeed({+ incoming: status.requested_cache_ram,+ isGguf: status.is_gguf ?? true,+ previous: { value: prevState.cacheRam, loaded: prevState.loadedCacheRam },+ seedLoadParams,+ modelChanged: slotsModelChanged,+ });// A Manual + Auto-layers load sent its positive context pin as max_seq_length,// and status only exposes the RESOLVED context; re-seed the pin from the// requested value (parity with the load paths' keepCustomCtx). Baselines@@ -528,6 +566,26 @@ export function applyActiveModelStatusToStore(loadedNUbatch: nUbatchSeed.loaded ?? null,}),...("value" in nUbatchSeed && { nUbatch: nUbatchSeed.value ?? null }),+ ...("loaded" in loadModeSeed && {+ loadedLoadMode: loadModeSeed.loaded ?? null,+ }),+ ...("value" in loadModeSeed && { loadMode: loadModeSeed.value ?? null }),+ ...("loaded" in specDraftCacheSeed && {+ loadedSpecDraftCacheDtype: specDraftCacheSeed.loaded ?? null,+ }),+ ...("value" in specDraftCacheSeed && {+ specDraftCacheDtype: specDraftCacheSeed.value ?? null,+ }),+ ...("loaded" in ctxCheckpointsSeed && {+ loadedCtxCheckpoints: ctxCheckpointsSeed.loaded ?? null,+ }),+ ...("value" in ctxCheckpointsSeed && {+ ctxCheckpoints: ctxCheckpointsSeed.value ?? null,+ }),+ ...("loaded" in cacheRamSeed && {+ loadedCacheRam: cacheRamSeed.loaded ?? null,+ }),+ ...("value" in cacheRamSeed && { cacheRam: cacheRamSeed.value ?? null }),// A swap under this tab resets the controls too, but that clear belongs INSIDE// resolveBatchSizeSeed (modelChanged), not after it: unlike the slot count above,// the batch echo is the REQUESTED size, so a blanket null here would also discarddiff --git a/studio/frontend/src/features/chat/lib/resident-config-match.ts b/studio/frontend/src/features/chat/lib/resident-config-match.tsindex 0fe1e346cd9..b393b6ef163 100644--- a/studio/frontend/src/features/chat/lib/resident-config-match.ts+++ b/studio/frontend/src/features/chat/lib/resident-config-match.ts@@ -23,6 +23,10 @@ type ResidentRuntime = Pick<| "requested_parallel_slots"| "requested_n_batch"| "requested_n_ubatch"+ | "requested_load_mode"+ | "requested_spec_draft_cache_type"+ | "requested_ctx_checkpoints"+ | "requested_cache_ram"| "tensor_parallel"| "disable_vision"| "chat_template_override"@@ -335,6 +339,37 @@ const SETTING_CHECKS: SettingCheck[] = [pinned: () => true,agrees: (c, s) => (c.nUbatch ?? null) === (s.requested_n_ubatch ?? null),},+ {+ chatOnly: true,+ // Same shape as the batch pair above: a blank control means the llama.cpp+ // default, and the status echoes what the load asked for rather than what it+ // resolved to, so null on both sides is agreement and anything else reloads.+ pinned: () => true,+ agrees: (c, s) => (c.loadMode ?? null) === (s.requested_load_mode ?? null),+ },+ {+ chatOnly: true,+ // Always pinned, unlike spec_draft_n_max: the status echoes what the load+ // REQUESTED, so a resident server that asked for nothing reports null and a+ // blank control agrees with it. Reading blank as "no opinion" instead would+ // mean clearing the dtype back to the f16 default never relaunched, leaving+ // the server on the quantized draft cache the panel no longer shows.+ pinned: () => true,+ agrees: (c, s) =>+ (c.specDraftCacheDtype ?? null) ===+ (s.requested_spec_draft_cache_type ?? null),+ },+ {+ chatOnly: true,+ pinned: () => true,+ agrees: (c, s) =>+ (c.ctxCheckpoints ?? null) === (s.requested_ctx_checkpoints ?? null),+ },+ {+ chatOnly: true,+ pinned: () => true,+ agrees: (c, s) => (c.cacheRam ?? null) === (s.requested_cache_ram ?? null),+ },{// Not nullable, so it always has an opinion; a status omitting it ran without.pinned: () => true,diff --git a/studio/frontend/src/features/chat/lib/resolve-batch-size-seed.ts b/studio/frontend/src/features/chat/lib/resolve-batch-size-seed.tsindex f67a45614f5..57bc00e82f9 100644--- a/studio/frontend/src/features/chat/lib/resolve-batch-size-seed.ts+++ b/studio/frontend/src/features/chat/lib/resolve-batch-size-seed.ts@@ -1,24 +1,32 @@// 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 a fresh /api/inference/status does to one batch control/baseline pair+// what a fresh /api/inference/status does to one load control/baseline pair-export interface BatchSizeSeedState {+/**+ * Generic in the value type because the rule is about the ECHO, not about batch+ * sizes: the string tuning controls beside them (load mode, draft cache dtype)+ * follow the same steady-echo, dirty-control and model-change logic. Defaults to+ * number, so existing call sites read unchanged.+ */+export interface BatchSizeSeedState<T extends number | string = number> {/** The editable control: what the next load or Apply would send. */- value: number | null;+ value: T | null;/** What the resident server was invoked with, as this tab last saw it. */- loaded: number | null;+ loaded: T | null;}/** The subset of the pair to write back; empty means leave the store alone. */-export type BatchSizeSeed = Partial<BatchSizeSeedState>;+export type BatchSizeSeed<T extends number | string = number> = Partial<+ BatchSizeSeedState<T>+>;-export function resolveBatchSizeSeed(options: {+export function resolveBatchSizeSeed<T extends number | string = number>(options: {/** ``status.requested_n_batch`` / ``_n_ubatch``; undefined on a backend that omits the field. */- incoming: number | null | undefined;+ incoming: T | null | undefined;/** ``status.is_gguf``: a non-GGUF (or diffusion, which echoes null) never has the flag. */isGguf: boolean;- previous: BatchSizeSeedState;+ previous: BatchSizeSeedState<T>;/** No load of this tab's own is in flight (``!modelLoading``). */seedLoadParams: boolean;/** The model/variant changed underneath this tab. Nothing staged against the@@ -26,7 +34,7 @@ export function resolveBatchSizeSeed(options: {* the control adopts it even when a pending edit would otherwise hold, and* even when the new model happens to report the count the old one ran. */modelChanged?: boolean;-}): BatchSizeSeed {+}): BatchSizeSeed<T> {const {incoming,isGguf,diff --git a/studio/frontend/src/features/chat/lib/server-tuning-fields.ts b/studio/frontend/src/features/chat/lib/server-tuning-fields.tsnew file mode 100644index 00000000000..74960be235b--- /dev/null+++ b/studio/frontend/src/features/chat/lib/server-tuning-fields.ts@@ -0,0 +1,104 @@+// 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 four llama-server tuning knobs every GGUF load carries: --load-mode, the+ * draft context's KV cache dtype, --ctx-checkpoints and --cache-ram.+ *+ * One module because they are always sent, committed and cleared as a group, and+ * every load path would otherwise repeat the same four lines with three chances+ * to forget one. State still lives in the runtime store.+ */++/** The subset of a config these read; satisfied by PerModelConfig and the store. */+export interface ServerTuningValues {+ loadMode?: string | null;+ specDraftCacheDtype?: string | null;+ ctxCheckpoints?: number | null;+ cacheRam?: number | null;+}++/** The request fields, in the backend's spelling. */+export interface ServerTuningPayload {+ load_mode?: string;+ spec_draft_cache_type?: string;+ ctx_checkpoints?: number;+ cache_ram?: number;+}++/**+ * What to send on /load, blank knobs omitted rather than nulled: the route reads+ * ``model_fields_set`` to decide whether the control owns the flag, and a null+ * counts as set, stripping the flag out of any inherited extra arguments.+ */+export function serverTuningLoadPayload(+ values: ServerTuningValues,+): ServerTuningPayload {+ return {+ ...(values.loadMode != null ? { load_mode: values.loadMode } : {}),+ ...(values.specDraftCacheDtype != null+ ? { spec_draft_cache_type: values.specDraftCacheDtype }+ : {}),+ ...(values.ctxCheckpoints != null+ ? { ctx_checkpoints: values.ctxCheckpoints }+ : {}),+ ...(values.cacheRam != null ? { cache_ram: values.cacheRam } : {}),+ };+}++/** The control/baseline pairs the store keeps for these four. */+export interface ServerTuningState {+ loadMode: string | null;+ loadedLoadMode: string | null;+ specDraftCacheDtype: string | null;+ loadedSpecDraftCacheDtype: string | null;+ ctxCheckpoints: number | null;+ loadedCtxCheckpoints: number | null;+ cacheRam: number | null;+ loadedCacheRam: number | null;+}++/**+ * What a launch committed: click-time values, not a backend echo, like the batch+ * sizes. Diffusion commits nothing (it launches no llama-server, and a value+ * recorded here would ride a saved preset onto the next GGUF).+ */+export function committedServerTuningState(+ values: ServerTuningValues,+ isDiffusion = false,+): ServerTuningState {+ if (isDiffusion) {+ return clearedServerTuningState();+ }+ const loadMode = values.loadMode ?? null;+ const specDraftCacheDtype = values.specDraftCacheDtype ?? null;+ const ctxCheckpoints = values.ctxCheckpoints ?? null;+ const cacheRam = values.cacheRam ?? null;+ return {+ loadMode,+ loadedLoadMode: loadMode,+ specDraftCacheDtype,+ loadedSpecDraftCacheDtype: specDraftCacheDtype,+ ctxCheckpoints,+ loadedCtxCheckpoints: ctxCheckpoints,+ cacheRam,+ loadedCacheRam: cacheRam,+ };+}++/**+ * The pairs a load that sent none of them leaves behind. Both halves, or a+ * rollback re-sends the departed model's baseline as if this server ran it.+ */+export function clearedServerTuningState(): ServerTuningState {+ return {+ loadMode: null,+ loadedLoadMode: null,+ specDraftCacheDtype: null,+ loadedSpecDraftCacheDtype: null,+ ctxCheckpoints: null,+ loadedCtxCheckpoints: null,+ cacheRam: null,+ loadedCacheRam: null,+ };+}diff --git a/studio/frontend/src/features/chat/presets/preset-load-config.ts b/studio/frontend/src/features/chat/presets/preset-load-config.tsindex d8d5f703926..e4736f18604 100644--- a/studio/frontend/src/features/chat/presets/preset-load-config.ts+++ b/studio/frontend/src/features/chat/presets/preset-load-config.ts@@ -16,6 +16,9 @@ import {N_BATCH_MIN,N_PARALLEL_MAX,N_PARALLEL_MIN,+ canonicalizeLoadMode,+ normalizeCacheRam,+ normalizeCtxCheckpoints,normalizeMaxSeqLength,type PerModelConfig,} from "@/features/model-picker/model-config/per-model-config";@@ -41,6 +44,10 @@ export type PresetLoadConfig = Pick<| "nParallel"| "nBatch"| "nUbatch"+ | "loadMode"+ | "specDraftCacheDtype"+ | "ctxCheckpoints"+ | "cacheRam"| "tensorParallel"| "disableVision"| "gpuMemoryMode"@@ -61,6 +68,10 @@ export const EMPTY_PRESET_LOAD_CONFIG: PresetLoadConfig = {nParallel: null,nBatch: null,nUbatch: null,+ loadMode: null,+ specDraftCacheDtype: null,+ ctxCheckpoints: null,+ cacheRam: null,tensorParallel: false,disableVision: false,};@@ -145,6 +156,16 @@ export function normalizePresetLoadConfig(typeof partial.nUbatch === "number" && Number.isFinite(partial.nUbatch)? Math.max(N_BATCH_MIN, Math.min(N_BATCH_MAX, Math.round(partial.nUbatch))): null,+ // Through the same normalizers the per-model store uses, so a hand-edited or+ // older preset cannot smuggle in a mode or dtype the panel cannot show.+ loadMode: canonicalizeLoadMode(partial.loadMode),+ specDraftCacheDtype:+ typeof partial.specDraftCacheDtype === "string" &&+ VALID_KV_CACHE_DTYPES.has(partial.specDraftCacheDtype)+ ? partial.specDraftCacheDtype+ : null,+ ctxCheckpoints: normalizeCtxCheckpoints(partial.ctxCheckpoints),+ cacheRam: normalizeCacheRam(partial.cacheRam),tensorParallel:typeof partial.tensorParallel === "boolean"? partial.tensorParallel@@ -198,6 +219,10 @@ export function capturePresetLoadConfig(): PresetLoadConfig | undefined {nParallel: snapshot.nParallel ?? null,nBatch: snapshot.nBatch ?? null,nUbatch: snapshot.nUbatch ?? null,+ loadMode: snapshot.loadMode ?? null,+ specDraftCacheDtype: snapshot.specDraftCacheDtype ?? null,+ ctxCheckpoints: snapshot.ctxCheckpoints ?? null,+ cacheRam: snapshot.cacheRam ?? null,tensorParallel: snapshot.tensorParallel ?? false,disableVision: snapshot.disableVision ?? false,...(snapshot.gpuMemoryMode === "manual"@@ -257,6 +282,10 @@ export function applyPresetLoadConfig(nParallel: config.nParallel ?? null,nBatch: config.nBatch ?? null,nUbatch: config.nUbatch ?? null,+ loadMode: config.loadMode ?? null,+ specDraftCacheDtype: config.specDraftCacheDtype ?? null,+ ctxCheckpoints: config.ctxCheckpoints ?? null,+ cacheRam: config.cacheRam ?? null,tensorParallel: config.tensorParallel ?? false,disableVision: config.disableVision ?? false,chatTemplateOverride: null,@@ -296,6 +325,18 @@ export function formatPresetLoadConfigSummary(if (config.nUbatch != null) {parts.push(`uBatch ${config.nUbatch}`);}+ if (config.loadMode) {+ parts.push(`Load ${config.loadMode}`);+ }+ if (config.specDraftCacheDtype) {+ parts.push(`Draft KV ${config.specDraftCacheDtype}`);+ }+ if (config.ctxCheckpoints != null) {+ parts.push(`${config.ctxCheckpoints} checkpoints`);+ }+ if (config.cacheRam != null) {+ parts.push(`Cache RAM ${config.cacheRam}`);+ }if (config.gpuMemoryMode === "manual") {parts.push("GPU manual");}diff --git a/studio/frontend/src/features/chat/shared-composer.tsx b/studio/frontend/src/features/chat/shared-composer.tsxindex 8c00e00c934..93913dc5aa6 100644--- a/studio/frontend/src/features/chat/shared-composer.tsx+++ b/studio/frontend/src/features/chat/shared-composer.tsx@@ -2,6 +2,11 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import { mlxRuntimeStateFrom } from "./lib/mlx-runtime-state";+import {+ clearedServerTuningState,+ committedServerTuningState,+ serverTuningLoadPayload,+} from "./lib/server-tuning-fields";import { TooltipIconButton } from "@/components/assistant-ui/tooltip-icon-button";import {thinkEffortAriaLabel,@@ -1477,6 +1482,7 @@ export function SharedComposer({...(ownConfig.nUbatch != null? { n_ubatch: ownConfig.nUbatch }: {}),+ ...serverTuningLoadPayload(ownConfig),}: {}),});@@ -1565,6 +1571,7 @@ export function SharedComposer({...(ownConfig.nUbatch != null? { n_ubatch: ownConfig.nUbatch }: {}),+ ...serverTuningLoadPayload(ownConfig),}: {}),});@@ -1636,6 +1643,9 @@ export function SharedComposer({loadedNBatch: committedNBatch,nUbatch: committedNUbatch,loadedNUbatch: committedNUbatch,+ ...(targetIsGguf && !(resp.is_diffusion ?? false)+ ? committedServerTuningState(ownConfig)+ : clearedServerTuningState()),// What this pane's launch is running, for a later rollback: the status// applier is held off for the whole load, so nothing else records it, and// a switch straight after would snapshot the other model's list.diff --git a/studio/frontend/src/features/chat/stores/chat-runtime-store.ts b/studio/frontend/src/features/chat/stores/chat-runtime-store.tsindex 0175468a27d..65e06454aec 100644--- a/studio/frontend/src/features/chat/stores/chat-runtime-store.ts+++ b/studio/frontend/src/features/chat/stores/chat-runtime-store.ts@@ -2620,6 +2620,24 @@ type ChatRuntimeStore = {nUbatch: number | null;/** micro-batch size the last successful load sent (null = default) */loadedNUbatch: number | null;+ /** user --spec-draft-type-k/-v override, the DRAFT context's KV cache dtype+ * (null = llama.cpp default f16). Separate from kvCacheDtype, which is the+ * target model's. */+ specDraftCacheDtype: string | null;+ /** draft cache dtype the last successful load sent (null = default) */+ loadedSpecDraftCacheDtype: string | null;+ /** user --load-mode override (null = llama.cpp's own `auto`) */+ loadMode: string | null;+ /** load mode the last successful load sent (null = default) */+ loadedLoadMode: string | null;+ /** user --ctx-checkpoints override (null = llama.cpp default 32) */+ ctxCheckpoints: number | null;+ /** checkpoint count the last successful load sent (null = default) */+ loadedCtxCheckpoints: number | null;+ /** user --cache-ram override in MiB (null = llama.cpp default 8192) */+ cacheRam: number | null;+ /** host prompt cache size the last successful load sent (null = default) */+ loadedCacheRam: number | null;/** Tensor-parallel split (--split-mode tensor) toggle, GGUF multi-GPU only. */tensorParallel: boolean;/** Backend-reported tensor-parallel state; null until first hydrated. */@@ -3728,6 +3746,14 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({loadedLlamaExtraArgs: null,nUbatch: null,loadedNUbatch: null,+ specDraftCacheDtype: null,+ loadedSpecDraftCacheDtype: null,+ loadMode: null,+ loadedLoadMode: null,+ ctxCheckpoints: null,+ loadedCtxCheckpoints: null,+ cacheRam: null,+ loadedCacheRam: null,tensorParallel: false,loadedTensorParallel: null,loadedDisableVision: null,@@ -4488,6 +4514,14 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({loadedLlamaExtraArgs: null,nUbatch: null,loadedNUbatch: null,+ specDraftCacheDtype: null,+ loadedSpecDraftCacheDtype: null,+ loadMode: null,+ loadedLoadMode: null,+ ctxCheckpoints: null,+ loadedCtxCheckpoints: null,+ cacheRam: null,+ loadedCacheRam: null,tensorParallel: false,loadedTensorParallel: null,loadedDisableVision: null,diff --git a/studio/frontend/src/features/chat/types/api.ts b/studio/frontend/src/features/chat/types/api.tsindex c9f65729e58..5417384b771 100644--- a/studio/frontend/src/features/chat/types/api.ts+++ b/studio/frontend/src/features/chat/types/api.ts@@ -92,6 +92,17 @@ export interface LoadModelRequest {n_batch?: number | null;/** prompt micro-batch size (--ubatch-size), 1..65536; omit/null = llama.cpp default 512, capped at the batch size */n_ubatch?: number | null;+ /** weight loading mode (--load-mode): auto/none/mmap/mlock/mmap+mlock/dio.+ * Omit/null = llama.cpp's own `auto`. Settings -> Model Memory overrides it. */+ load_mode?: string | null;+ /** KV cache dtype for the DRAFT model's context (--spec-draft-type-k/-v);+ * omit/null = llama.cpp default f16. Only reaches the command line when the+ * load attaches a separate draft model. */+ spec_draft_cache_type?: string | null;+ /** context checkpoints per slot (--ctx-checkpoints); omit/null = default 32, 0 disables */+ ctx_checkpoints?: number | null;+ /** host prompt cache size in MiB (--cache-ram); omit/null = default 8192, 0 disables, -1 unlimited */+ cache_ram?: number | null;/*** Pass-through llama-server args, one argv token per entry, appended after* Unsloth's own flags so llama.cpp's last-wins parser takes these. Flags Unsloth@@ -291,6 +302,14 @@ export interface LoadModelResponse {requested_n_batch?: number | null;/** micro-batch size (--ubatch-size) the load was invoked with; null = default */requested_n_ubatch?: number | null;+ /** load mode (--load-mode) the load was invoked with; null = default */+ requested_load_mode?: string | null;+ /** draft KV cache dtype the load was invoked with; null = default */+ requested_spec_draft_cache_type?: string | null;+ /** checkpoints (--ctx-checkpoints) the load was invoked with; null = default */+ requested_ctx_checkpoints?: number | null;+ /** host prompt cache (--cache-ram) the load was invoked with; null = default */+ requested_cache_ram?: number | null;/** Pass-through llama-server arguments the running load was invoked with. */requested_llama_extra_args?: string[] | null;}@@ -390,6 +409,14 @@ export interface InferenceStatusResponse {requested_n_batch?: number | null;/** micro-batch size (--ubatch-size) the active load was invoked with; null = default */requested_n_ubatch?: number | null;+ /** load mode (--load-mode) the active load was invoked with; null = default */+ requested_load_mode?: string | null;+ /** draft KV cache dtype the active load was invoked with; null = default */+ requested_spec_draft_cache_type?: string | null;+ /** checkpoints (--ctx-checkpoints) the active load was invoked with; null = default */+ requested_ctx_checkpoints?: number | null;+ /** host prompt cache (--cache-ram) the active load was invoked with; null = default */+ requested_cache_ram?: number | null;/** Pass-through llama-server arguments the running load was invoked with. */requested_llama_extra_args?: string[] | null;n_layers?: number | null;diff --git a/studio/frontend/src/features/model-picker/api/model-overrides.ts b/studio/frontend/src/features/model-picker/api/model-overrides.tsindex e614938f690..63d7119e650 100644--- a/studio/frontend/src/features/model-picker/api/model-overrides.ts+++ b/studio/frontend/src/features/model-picker/api/model-overrides.ts@@ -39,6 +39,14 @@ export interface ApiModelOverride {// biome-ignore lint/style/useNamingConvention: API scheman_ubatch?: number;// biome-ignore lint/style/useNamingConvention: API schema+ load_mode?: string;+ // biome-ignore lint/style/useNamingConvention: API schema+ spec_draft_cache_type?: string;+ // biome-ignore lint/style/useNamingConvention: API schema+ ctx_checkpoints?: number;+ // biome-ignore lint/style/useNamingConvention: API schema+ cache_ram?: number;+ // biome-ignore lint/style/useNamingConvention: API schematensor_parallel?: boolean;// biome-ignore lint/style/useNamingConvention: API schemadisable_vision?: boolean;@@ -303,6 +311,21 @@ export function toApiOverride(config: PerModelConfig | null): ApiModelOverride {if (config.nUbatch && config.nUbatch > 0) {payload.n_ubatch = config.nUbatch;}+ // Blank follows llama.cpp's own default for each: auto, f16, 32 and 8192.+ // cacheRam is compared against null rather than tested for truth, because 0 and+ // -1 are both meaningful values here (disable, and no limit).+ if (config.loadMode) {+ payload.load_mode = config.loadMode;+ }+ if (config.specDraftCacheDtype) {+ payload.spec_draft_cache_type = config.specDraftCacheDtype;+ }+ if (config.ctxCheckpoints != null && config.ctxCheckpoints >= 0) {+ payload.ctx_checkpoints = config.ctxCheckpoints;+ }+ if (config.cacheRam != null) {+ payload.cache_ram = config.cacheRam;+ }if (config.tensorParallel) {payload.tensor_parallel = true;}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.tsxindex d9cd1fa588b..9f41031b3a1 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@@ -86,11 +86,19 @@ import {import { perModelConfigsEqual } from "../model-config/apply-per-model-config";import { ggufQuantLabel } from "../model-config/model-identity";import {+ CACHE_RAM_LLAMA_DEFAULT,+ CACHE_RAM_MAX,+ CACHE_RAM_MIN,CONTEXT_LENGTH_MIN,+ CTX_CHECKPOINTS_LLAMA_DEFAULT,+ CTX_CHECKPOINTS_MAX,+ CTX_CHECKPOINTS_MIN,DEFAULT_MAX_SEQ_LENGTH,DEFAULT_PER_MODEL_CONFIG,DRAFT_N_MAX_SPEC_TYPES,KV_CACHE_DTYPES,+ LOAD_MODES,+ LOAD_MODE_DEFAULT,MAX_SEQ_LENGTH_MAX,MAX_SEQ_LENGTH_MIN,MAX_SEQ_LENGTH_STEP,@@ -101,6 +109,7 @@ import {N_PARALLEL_MAX,N_PARALLEL_MIN,type PerModelConfig,+ SEPARATE_DRAFT_MODEL_SPEC_TYPES,SPECULATIVE_TYPES,deletePerModelConfig,floorMaxSeqLength,@@ -148,6 +157,45 @@ const SPECULATIVE_TYPE_LABELS: Record<off: "Off",};+// Lower-case where the value is the flag's own spelling, so the pick reads the+// same as the launch command.+const LOAD_MODE_LABELS: Record<(typeof LOAD_MODES)[number], string> = {+ auto: "Auto",+ none: "None",+ mmap: "mmap",+ mlock: "mlock",+ "mmap+mlock": "mmap+mlock",+ dio: "DirectIO",+};++// What "Don't reserve system RAM" vetoes: mmap maps and dio streams, so neither+// holds a full host copy. Mirrors _LOAD_MODE_MLOCK_VALUES |+// _LOAD_MODE_RESERVING_VALUES in llama_server_args.py.+const RAM_RESERVING_LOAD_MODES = new Set(["none", "mlock", "mmap+mlock"]);++/**+ * What Model Memory does to this load mode, or null when the pick reaches the+ * command line untouched: a row showing the pick alone would name a flag the+ * child never sees. Keep resident is first because it wins outright.+ */+function loadModeOverrideNotice(+ mode: string | null,+ settings: ModelMemorySettings | null,+): string | null {+ if (mode == null || settings == null) {+ return null;+ }+ if (settings.keepResident && !settings.noRamReserve) {+ return mode === "mmap+mlock"+ ? null+ : "This will be replaced by mmap+mlock: Keep model in GPU memory, in Settings, owns how the weights are held.";+ }+ if (settings.noRamReserve && RAM_RESERVING_LOAD_MODES.has(mode)) {+ return "This will be removed and the load runs the default mmap path: Don't reserve system RAM, in Settings, owns how the weights are held.";+ }+ return null;+}+/*** The batch size llama-server will not go below for this load.*@@ -177,9 +225,13 @@ function hasNonDefaultAdvanced(config: PerModelConfig): boolean {config.kvCacheDtype != null ||(config.speculativeType ?? "auto") !== "auto" ||config.specDraftNMax != null ||+ config.specDraftCacheDtype != null ||config.nParallel != null ||config.nBatch != null ||config.nUbatch != null ||+ config.loadMode != null ||+ config.ctxCheckpoints != null ||+ config.cacheRam != null ||config.tensorParallel ||config.disableVision ||config.chatTemplateOverride != null ||@@ -910,10 +962,90 @@ function MlxAdvancedSettings({);}+/**+ * Mmap/Mlock, with the note that says when Settings wins. Its own component+ * because it subscribes to the Model Memory settings and must keep following+ * them: the settings page is reachable without unmounting this panel.+ */+function LoadModeRow({+ config,+ update,+}: {+ config: PerModelConfig;+ update: (patch: Partial<PerModelConfig>) => void;+}) {+ const adviceId = useId();+ const [modelMemory, setModelMemory] = useState<ModelMemorySettings | null>(+ null,+ );+ useEffect(() => {+ let cancelled = false;+ loadModelMemorySettings()+ .then((loaded) => {+ if (!cancelled) {+ setModelMemory(loaded);+ }+ })+ .catch(() => {});+ const unsubscribe = subscribeModelMemorySettings(setModelMemory);+ return () => {+ cancelled = true;+ unsubscribe();+ };+ }, []);+ const notice = loadModeOverrideNotice(config.loadMode ?? null, modelMemory);+ return (+ <div className="space-y-1">+ <div className={ROW_CLASS}>+ <div className="flex min-w-0 items-center gap-1.5">+ <span className={LABEL_CLASS}>Mmap/Mlock</span>+ <InfoHint>+ How the weights are read off disk (--load-mode). Auto memory-maps+ unless a device cannot, which is the default. mmap forces the+ mapping, mlock keeps the model in RAM rather than letting it swap or+ compress, mmap+mlock does both, DirectIO streams the file where the+ platform supports it, and None asks for no special mode. Model+ Memory, in Settings, owns this when either of its toggles is on.+ </InfoHint>+ </div>+ <Select+ value={config.loadMode ?? LOAD_MODE_DEFAULT}+ onValueChange={(v) =>+ update({ loadMode: v === LOAD_MODE_DEFAULT ? null : v })+ }+ >+ <SelectTrigger+ animateRadius={false}+ icon={ChevronDownStandardIcon}+ iconClassName="size-3.5"+ className={`w-[124px] shrink-0 ${SELECT_TRIGGER_CLASS}`}+ aria-describedby={notice ? adviceId : undefined}+ >+ <SelectValue />+ </SelectTrigger>+ <SelectContent className="menu-soft-surface ring-0 border-0 rounded-lg">+ {LOAD_MODES.map((mode) => (+ <SelectItem key={mode} value={mode}>+ {LOAD_MODE_LABELS[mode]}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </div>+ {notice && (+ <p id={adviceId} className="text-ui-11 text-amber-500">+ {notice}+ </p>+ )}+ </div>+ );+}+function GgufAdvancedSettings({config,update,showDraftTokens,+ showSpecDraftCacheDtype,speculativeFallback,onEditTemplate,layerCount,@@ -927,6 +1059,7 @@ function GgufAdvancedSettings({config: PerModelConfig;update: (patch: Partial<PerModelConfig>) => void;showDraftTokens: boolean;+ showSpecDraftCacheDtype: boolean;speculativeFallback: string;onEditTemplate: () => void;layerCount: number | null;@@ -1019,6 +1152,11 @@ function GgufAdvancedSettings({specDraftNMax: DRAFT_N_MAX_SPEC_TYPES.has(v)? config.specDraftNMax: null,+ // Dropped with the drafter, like the depth above: the draft+ // context exists only while a separate model is loaded.+ specDraftCacheDtype: SEPARATE_DRAFT_MODEL_SPEC_TYPES.has(v)+ ? config.specDraftCacheDtype+ : null,})}>@@ -1073,6 +1211,49 @@ function GgufAdvancedSettings({</div>)}+ {showSpecDraftCacheDtype && (+ <div className={ROW_CLASS}>+ <div className="flex min-w-0 items-center gap-1.5">+ <span className={LABEL_CLASS_WRAP}>Spec Decoding KV Cache Dtype</span>+ <InfoHint>+ KV cache precision for the draft model's own context+ (--spec-draft-type-k / --spec-draft-type-v). Separate from the KV+ Cache Dtype above, which is the target model's. f16 is the+ default; bf16 and f32 are full precision; q8_0 through iq4_nl are+ quantized, and a quantized draft cache saves VRAM on a drafter+ whose output is verified by the target anyway.+ </InfoHint>+ </div>+ <Select+ value={config.specDraftCacheDtype ?? KV_CACHE_DTYPE_DEFAULT}+ onValueChange={(v) =>+ update({+ specDraftCacheDtype: v === KV_CACHE_DTYPE_DEFAULT ? null : v,+ })+ }+ >+ <SelectTrigger+ animateRadius={false}+ icon={ChevronDownStandardIcon}+ iconClassName="size-3.5"+ className={`w-[92px] shrink-0 ${SELECT_TRIGGER_CLASS}`}+ >+ <SelectValue />+ </SelectTrigger>+ <SelectContent className="menu-soft-surface ring-0 border-0 rounded-lg">+ <SelectItem value={KV_CACHE_DTYPE_DEFAULT}>+ {KV_CACHE_DTYPE_DEFAULT}+ </SelectItem>+ {KV_CACHE_DTYPES.map((dtype) => (+ <SelectItem key={dtype} value={dtype}>+ {dtype}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </div>+ )}+<div className={ROW_CLASS}><div className="flex min-w-0 items-center gap-1.5"><span className={LABEL_CLASS}>Parallel Slots</span>@@ -1255,6 +1436,94 @@ function GgufAdvancedSettings({<ChatTemplateSetting config={config} onEditTemplate={onEditTemplate} />+ {/* Host-side knobs, after the ones that shape the model itself. All three+ are llama-server's own, and the diffusion runner launches no+ llama-server, so they are hidden for it like the batch sizes above. */}+ {!isDiffusion && (+ <>+ <LoadModeRow config={config} update={update} />++ <div className={ROW_CLASS}>+ <div className="flex min-w-0 items-center gap-1.5">+ <span className={LABEL_CLASS}>Checkpoints</span>+ <InfoHint>+ Context checkpoints kept per slot (--ctx-checkpoints), which let+ a sliding-window model rewind instead of re-processing the+ prompt. Leave blank for the llama.cpp default (+ {CTX_CHECKPOINTS_LLAMA_DEFAULT}); 0 disables them. Each one costs+ host memory, and models without a sliding window ignore the+ setting.+ </InfoHint>+ </div>+ <input+ type="number"+ min={CTX_CHECKPOINTS_MIN}+ max={CTX_CHECKPOINTS_MAX}+ step={1}+ value={config.ctxCheckpoints ?? ""}+ placeholder="auto"+ onChange={(event) => {+ const raw = event.target.value;+ if (raw === "") {+ update({ ctxCheckpoints: null });+ return;+ }+ const parsed = Number.parseInt(raw, 10);+ if (Number.isFinite(parsed)) {+ update({+ ctxCheckpoints: Math.max(+ CTX_CHECKPOINTS_MIN,+ Math.min(CTX_CHECKPOINTS_MAX, parsed),+ ),+ });+ }+ }}+ aria-label="Context checkpoints per slot"+ className={NUMBER_INPUT_CLASS}+ />+ </div>++ <div className={ROW_CLASS}>+ <div className="flex min-w-0 items-center gap-1.5">+ <span className={LABEL_CLASS}>Cache RAM</span>+ <InfoHint>+ Host memory in MiB llama-server may spend caching prompt state it+ has evicted from a slot (--cache-ram), so a returning+ conversation is not re-processed. Leave blank for the llama.cpp+ default ({CACHE_RAM_LLAMA_DEFAULT}); 0 disables the cache and -1+ lifts the limit.+ </InfoHint>+ </div>+ <input+ type="number"+ min={CACHE_RAM_MIN}+ max={CACHE_RAM_MAX}+ step={1}+ value={config.cacheRam ?? ""}+ placeholder="auto"+ onChange={(event) => {+ const raw = event.target.value;+ if (raw === "") {+ update({ cacheRam: null });+ return;+ }+ const parsed = Number.parseInt(raw, 10);+ if (Number.isFinite(parsed)) {+ update({+ cacheRam: Math.max(+ CACHE_RAM_MIN,+ Math.min(CACHE_RAM_MAX, parsed),+ ),+ });+ }+ }}+ aria-label="Host prompt cache size in MiB"+ className={NUMBER_INPUT_CLASS}+ />+ </div>+ </>+ )}+{/* Last, because it is the escape hatch for everything the rows above do notcover, and because llama.cpp's last-wins parsing means these really areappended after them. GGUF only: the flags are llama-server's. */}@@ -2002,6 +2271,12 @@ export function ModelConfigPage({const showDraftTokens =config.speculativeType != null &&DRAFT_N_MAX_SPEC_TYPES.has(config.speculativeType);+ // Narrower than the row above: the dtype needs a second context, and only the+ // sidecar modes always load one. MTP may read baked-in heads out of the target+ // GGUF, which the loader knows and this panel does not.+ const showSpecDraftCacheDtype =+ config.speculativeType != null &&+ SEPARATE_DRAFT_MODEL_SPEC_TYPES.has(config.speculativeType);const nativeContextLength =target.meta.contextLength ?? stagedDims?.contextLength ?? null;const activeLoadedContext =@@ -2371,6 +2646,7 @@ export function ModelConfigPage({config={config}update={update}showDraftTokens={showDraftTokens}+ showSpecDraftCacheDtype={showSpecDraftCacheDtype}speculativeFallback={speculativeFallback}onEditTemplate={() => setTemplateOpen(true)}layerCount={stagedDims?.layerCount ?? null}diff --git a/studio/frontend/src/features/model-picker/hooks/use-active-model-config.ts b/studio/frontend/src/features/model-picker/hooks/use-active-model-config.tsindex 92ad1975141..6521942967a 100644--- a/studio/frontend/src/features/model-picker/hooks/use-active-model-config.ts+++ b/studio/frontend/src/features/model-picker/hooks/use-active-model-config.ts@@ -28,6 +28,12 @@ export function useActiveModelConfig(): ActiveModelConfigState {const nParallel = useChatRuntimeStore((s) => s.nParallel);const nBatch = useChatRuntimeStore((s) => s.nBatch);const nUbatch = useChatRuntimeStore((s) => s.nUbatch);+ const specDraftCacheDtype = useChatRuntimeStore(+ (s) => s.specDraftCacheDtype,+ );+ const loadMode = useChatRuntimeStore((s) => s.loadMode);+ const ctxCheckpoints = useChatRuntimeStore((s) => s.ctxCheckpoints);+ const cacheRam = useChatRuntimeStore((s) => s.cacheRam);const tensorParallel = useChatRuntimeStore((s) => s.tensorParallel);const disableVision = useChatRuntimeStore((s) => s.disableVision);const chatTemplateOverride = useChatRuntimeStore(@@ -66,6 +72,10 @@ export function useActiveModelConfig(): ActiveModelConfigState {nParallel: nParallel ?? null,nBatch: nBatch ?? null,nUbatch: nUbatch ?? null,+ specDraftCacheDtype: specDraftCacheDtype ?? null,+ loadMode: loadMode ?? null,+ ctxCheckpoints: ctxCheckpoints ?? null,+ cacheRam: cacheRam ?? null,tensorParallel: tensorParallel ?? false,disableVision: disableVision ?? false,chatTemplateOverride: chatTemplateOverride ?? null,@@ -93,6 +103,10 @@ export function useActiveModelConfig(): ActiveModelConfigState {nParallel,nBatch,nUbatch,+ specDraftCacheDtype,+ loadMode,+ ctxCheckpoints,+ cacheRam,tensorParallel,disableVision,chatTemplateOverride,diff --git a/studio/frontend/src/features/model-picker/model-config/apply-per-model-config.ts b/studio/frontend/src/features/model-picker/model-config/apply-per-model-config.tsindex ce5892b17e2..347d2670273 100644--- a/studio/frontend/src/features/model-picker/model-config/apply-per-model-config.ts+++ b/studio/frontend/src/features/model-picker/model-config/apply-per-model-config.ts@@ -55,10 +55,16 @@ export function applyPerModelConfigToRuntime(normalizeSpeculativeType(config.speculativeType) ??readPersistedSpeculativeType(),specDraftNMax: config.specDraftNMax ?? null,+ specDraftCacheDtype: config.specDraftCacheDtype ?? null,nParallel: config.nParallel ?? null,// the diffusion runner ignores the llama-server batch flagsnBatch: options.isDiffusion ? null : (config.nBatch ?? null),nUbatch: options.isDiffusion ? null : (config.nUbatch ?? null),+ // Same reason as the batch flags: these are llama-server's own, and the+ // diffusion runner never launches one.+ loadMode: options.isDiffusion ? null : (config.loadMode ?? null),+ ctxCheckpoints: options.isDiffusion ? null : (config.ctxCheckpoints ?? null),+ cacheRam: options.isDiffusion ? null : (config.cacheRam ?? null),tensorParallel: options.isDiffusion? false: (config.tensorParallel ?? false),@@ -112,9 +118,13 @@ export function currentRuntimePerModelConfig(mlxKvBits: s.mlxKvBits ?? null,speculativeType: normalizeSpeculativeType(s.speculativeType),specDraftNMax: s.specDraftNMax ?? null,+ specDraftCacheDtype: s.specDraftCacheDtype ?? null,nParallel: s.nParallel ?? null,nBatch: s.nBatch ?? null,nUbatch: s.nUbatch ?? null,+ loadMode: s.loadMode ?? null,+ ctxCheckpoints: s.ctxCheckpoints ?? null,+ cacheRam: s.cacheRam ?? null,tensorParallel: s.tensorParallel ?? false,disableVision: s.disableVision ?? false,chatTemplateOverride: cleanTemplate(s.chatTemplateOverride),@@ -142,9 +152,13 @@ export function perModelConfigsEqual(normalizeSpeculativeType(a.speculativeType) ===normalizeSpeculativeType(b.speculativeType) &&(a.specDraftNMax ?? null) === (b.specDraftNMax ?? null) &&+ (a.specDraftCacheDtype ?? null) === (b.specDraftCacheDtype ?? null) &&(a.nParallel ?? null) === (b.nParallel ?? null) &&(a.nBatch ?? null) === (b.nBatch ?? null) &&(a.nUbatch ?? null) === (b.nUbatch ?? null) &&+ (a.loadMode ?? null) === (b.loadMode ?? null) &&+ (a.ctxCheckpoints ?? null) === (b.ctxCheckpoints ?? null) &&+ (a.cacheRam ?? null) === (b.cacheRam ?? null) &&Boolean(a.tensorParallel) === Boolean(b.tensorParallel) &&Boolean(a.disableVision) === Boolean(b.disableVision) &&cleanTemplate(a.chatTemplateOverride) ===diff --git a/studio/frontend/src/features/model-picker/model-config/config-signature.ts b/studio/frontend/src/features/model-picker/model-config/config-signature.tsindex fcf0d71d341..65b4c06b505 100644--- a/studio/frontend/src/features/model-picker/model-config/config-signature.ts+++ b/studio/frontend/src/features/model-picker/model-config/config-signature.ts@@ -54,9 +54,13 @@ export function loadedConfigSignature(config.mlxKvBits ?? "",config.speculativeType ?? "",config.specDraftNMax ?? "",+ config.specDraftCacheDtype ?? "",config.nParallel ?? "",config.nBatch ?? "",config.nUbatch ?? "",+ config.loadMode ?? "",+ config.ctxCheckpoints ?? "",+ config.cacheRam ?? "",config.tensorParallel ? "1" : "0",config.disableVision ? "1" : "0",config.chatTemplateOverride == nulldiff --git a/studio/frontend/src/features/model-picker/model-config/llama-extra-args.ts b/studio/frontend/src/features/model-picker/model-config/llama-extra-args.tsindex a3578da41b6..0ee22e6af7f 100644--- a/studio/frontend/src/features/model-picker/model-config/llama-extra-args.ts+++ b/studio/frontend/src/features/model-picker/model-config/llama-extra-args.ts@@ -651,6 +651,22 @@ const CONTROL_OWNED_FLAGS: Record<string, string> = {"--spec-draft-n-max": "Draft Tokens","--chat-template": "Chat Template","--chat-template-file": "Chat Template",+ "--load-mode": "Mmap/Mlock",+ "-lm": "Mmap/Mlock",+ // Both halves, since the control sets one dtype for the pair, and both+ // spellings, since which one a build understands is a version question.+ "--spec-draft-type-k": "Spec Decoding KV Cache Dtype",+ "-ctkd": "Spec Decoding KV Cache Dtype",+ "--cache-type-k-draft": "Spec Decoding KV Cache Dtype",+ "--spec-draft-type-v": "Spec Decoding KV Cache Dtype",+ "-ctvd": "Spec Decoding KV Cache Dtype",+ "--cache-type-v-draft": "Spec Decoding KV Cache Dtype",+ "--ctx-checkpoints": "Checkpoints",+ "-ctxcp": "Checkpoints",+ // upstream's older spelling of the same flag+ "--swa-checkpoints": "Checkpoints",+ "--cache-ram": "Cache RAM",+ "-cram": "Cache RAM",};/**@@ -744,6 +760,14 @@ const VALUE_REQUIRED_FLAGS = new Set(["-ctv","--split-mode","-sm",+ "--load-mode",+ "-lm",+ "--spec-draft-type-k",+ "-ctkd",+ "--cache-type-k-draft",+ "--spec-draft-type-v",+ "-ctvd",+ "--cache-type-v-draft",]);/** The pass-through spellings of the batch size the floor above applies to. */@@ -762,6 +786,12 @@ const INTEGER_VALUE_FLAGS = new Set(["-b","--ubatch-size","-ub",+ "--ctx-checkpoints",+ "-ctxcp",+ "--swa-checkpoints",+ // -1 (no limit) and 0 (disable) are both valid, so only integer-ness is checked+ "--cache-ram",+ "-cram",]);/** Sampling belongs to the conversation, not the launch. */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.tsindex e6cfadf6646..839fdae3900 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@@ -10,7 +10,10 @@ import {publicModelId,} from "./model-identity";import type { GpuIndexKind } from "@/hooks/use-gpu-info";-import { DRAFT_N_MAX_SPEC_TYPES } from "@/lib/speculative-modes";+import {+ DRAFT_N_MAX_SPEC_TYPES,+ SEPARATE_DRAFT_MODEL_SPEC_TYPES,+} from "@/lib/speculative-modes";export interface PerModelConfig {customContextLength: number | null;@@ -20,9 +23,19 @@ export interface PerModelConfig {mlxKvBits?: number | null;speculativeType: string | null;specDraftNMax: number | null;+ /** KV cache dtype for the DRAFT context (--spec-draft-type-k/-v), sized and+ * quantized independently of kvCacheDtype. Optional so older blobs parse. */+ specDraftCacheDtype?: string | null;nParallel: number | null;nBatch: number | null;nUbatch: number | null;+ /** --load-mode; null follows llama.cpp's own `auto`, so a build that redefines+ * auto is followed rather than pinned. */+ loadMode?: string | null;+ /** --ctx-checkpoints; null follows the llama.cpp default (32). */+ ctxCheckpoints?: number | null;+ /** --cache-ram in MiB; null follows the llama.cpp default (8192). */+ cacheRam?: number | null;tensorParallel: boolean;/** Load a vision GGUF without its mmproj, freeing the projector's VRAM. */disableVision: boolean;@@ -55,9 +68,13 @@ export const DEFAULT_PER_MODEL_CONFIG: PerModelConfig = {mlxKvBits: null,speculativeType: null,specDraftNMax: null,+ specDraftCacheDtype: null,nParallel: null,nBatch: null,nUbatch: null,+ loadMode: null,+ ctxCheckpoints: null,+ cacheRam: null,tensorParallel: false,disableVision: false,chatTemplateOverride: null,@@ -157,18 +174,47 @@ export const KV_CACHE_DTYPES = [export const MLX_KV_BITS: readonly number[] = [8, 6, 5, 4, 3, 2];const VALID_KV_CACHE_DTYPES = new Set<string>(KV_CACHE_DTYPES);+// llama-server's --load-mode enum, in --help order. "auto" is both a real value+// and the default, so the UI shows it while storage keeps null: emitting nothing+// follows whatever auto means in the build that runs.+export const LOAD_MODES = [+ "auto",+ "none",+ "mmap",+ "mlock",+ "mmap+mlock",+ "dio",+] as const;+export const LOAD_MODE_DEFAULT = "auto";+const VALID_LOAD_MODES = new Set<string>(LOAD_MODES);++// --ctx-checkpoints: per-slot snapshots of the sliding-window cache, so the count+// is small. 0 disables them; the ceiling is a sanity bound, not an upstream one.+export const CTX_CHECKPOINTS_MIN = 0;+export const CTX_CHECKPOINTS_MAX = 256;+export const CTX_CHECKPOINTS_LLAMA_DEFAULT = 32;++// --cache-ram in MiB: -1 is "no limit" and 0 disables the host prompt cache, so+// the floor is -1. The 1 TiB ceiling fails a stray keystroke before the child does.+export const CACHE_RAM_MIN = -1;+export const CACHE_RAM_MAX = 1024 * 1024;+export const CACHE_RAM_LLAMA_DEFAULT = 8192;+export {DRAFT_N_MAX_SPEC_TYPES,+ SEPARATE_DRAFT_MODEL_SPEC_TYPES,SPECULATIVE_TYPES,} from "@/lib/speculative-modes";const STORAGE_KEY = "unsloth_model_configs";const LEGACY_STORAGE_KEY = "unsloth_load_settings";const LEGACY_MIGRATION_FLAG = "unsloth_model_configs_migrated";-// v2 added nBatch / nUbatch, v3 llamaExtraArgs and v4 disableVision; a client-// from before any of them would normalize the field it does not know straight-// back out of the record.-const STORAGE_SCHEMA_VERSION = 4;+// v2 added nBatch / nUbatch, v3 llamaExtraArgs, v4 disableVision and v5 the+// llama-server tuning group (loadMode / specDraftCacheDtype / ctxCheckpoints /+// cacheRam); a client from before any of them would normalize the field it does+// not know straight back out of the record.+const STORAGE_SCHEMA_VERSION = 5;+const PRE_SERVER_TUNING_SCHEMA_VERSION = 4;const PRE_VISION_SCHEMA_VERSION = 3;const PRE_EXTRA_ARGS_SCHEMA_VERSION = 2;const PRE_BATCH_SCHEMA_VERSION = 1;@@ -190,9 +236,13 @@ const STORED_CONFIG_FIELDS = new Set(["mlxKvBits","speculativeType","specDraftNMax",+ "specDraftCacheDtype","nParallel","nBatch","nUbatch",+ "loadMode",+ "ctxCheckpoints",+ "cacheRam","tensorParallel","disableVision","chatTemplateOverride",@@ -303,6 +353,44 @@ function canonicalizeSpeculativeType(value: string): string | null {return null;}+/**+ * Canonicalize a stored --load-mode, or null to follow the llama.cpp default.+ *+ * "auto" folds to null like Speculative Decoding's: it IS the default, so storing+ * it would pin a value the build may redefine and read as an override everywhere.+ */+export function canonicalizeLoadMode(value: unknown): string | null {+ if (typeof value !== "string") {+ return null;+ }+ // Whitespace and case only: "mmap + mlock" is not a spelling llama-server+ // accepts, so it is refused rather than repaired.+ const mode = value.trim().toLowerCase();+ if (!mode || mode === LOAD_MODE_DEFAULT) {+ return null;+ }+ return VALID_LOAD_MODES.has(mode) ? mode : null;+}++function normalizeIntegerInRange(+ value: unknown,+ min: number,+ max: number,+): number | null {+ if (typeof value !== "number" || !Number.isFinite(value)) {+ return null;+ }+ return Math.max(min, Math.min(max, Math.round(value)));+}++export function normalizeCtxCheckpoints(value: unknown): number | null {+ return normalizeIntegerInRange(value, CTX_CHECKPOINTS_MIN, CTX_CHECKPOINTS_MAX);+}++export function normalizeCacheRam(value: unknown): number | null {+ return normalizeIntegerInRange(value, CACHE_RAM_MIN, CACHE_RAM_MAX);+}+export function normalizeMaxSeqLength(value: unknown): number | null {if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) {return null;@@ -679,6 +767,15 @@ function normalizeV1(partial: RawConfig): PerModelConfig {Number.isFinite(partial.specDraftNMax)? Math.max(1, Math.min(16, Math.round(partial.specDraftNMax))): null;+ // Tied to the mode like specDraftNMax: a dtype stored under a mode with no+ // separate drafter shows a row for a context that never exists.+ const specDraftCacheDtype =+ speculativeType != null &&+ SEPARATE_DRAFT_MODEL_SPEC_TYPES.has(speculativeType) &&+ typeof partial.specDraftCacheDtype === "string" &&+ VALID_KV_CACHE_DTYPES.has(partial.specDraftCacheDtype)+ ? partial.specDraftCacheDtype+ : null;return {customContextLength:typeof partial.customContextLength === "number" &&@@ -699,6 +796,10 @@ function normalizeV1(partial: RawConfig): PerModelConfig {: null,speculativeType,specDraftNMax,+ specDraftCacheDtype,+ loadMode: canonicalizeLoadMode(partial.loadMode),+ ctxCheckpoints: normalizeCtxCheckpoints(partial.ctxCheckpoints),+ cacheRam: normalizeCacheRam(partial.cacheRam),nParallel:typeof partial.nParallel === "number" &&Number.isFinite(partial.nParallel)@@ -762,13 +863,22 @@ function toStoredConfig(config: PerModelConfig): StoredPerModelConfig {// is what a pre-vision client reconstructs anyway, so a record that merely// carries the key at its default loses nothing by staying in that client's// reach -- and stamping every record v4 would put the whole store out of it.- const version = normalized.disableVision+ // The tuning group above it follows the same rule: only a record that actually+ // sets one of the four is put out of a pre-v5 client's reach.+ const hasServerTuning =+ normalized.loadMode != null ||+ normalized.specDraftCacheDtype != null ||+ normalized.ctxCheckpoints != null ||+ normalized.cacheRam != null;+ const version = hasServerTuning? STORAGE_SCHEMA_VERSION- : normalized.llamaExtraArgs != null && normalized.llamaExtraArgs.length > 0- ? PRE_VISION_SCHEMA_VERSION- : normalized.nBatch != null || normalized.nUbatch != null- ? PRE_EXTRA_ARGS_SCHEMA_VERSION- : PRE_BATCH_SCHEMA_VERSION;+ : normalized.disableVision+ ? PRE_SERVER_TUNING_SCHEMA_VERSION+ : normalized.llamaExtraArgs != null && normalized.llamaExtraArgs.length > 0+ ? PRE_VISION_SCHEMA_VERSION+ : normalized.nBatch != null || normalized.nUbatch != null+ ? PRE_EXTRA_ARGS_SCHEMA_VERSION+ : PRE_BATCH_SCHEMA_VERSION;return {version,...normalized,diff --git a/studio/frontend/src/lib/speculative-modes.ts b/studio/frontend/src/lib/speculative-modes.tsindex 85ca49753f8..83b21cd7927 100644--- a/studio/frontend/src/lib/speculative-modes.ts+++ b/studio/frontend/src/lib/speculative-modes.ts@@ -33,3 +33,18 @@ export const DRAFT_N_MAX_SPEC_TYPES: ReadonlySet<string> = new Set(["dspark","dflash",]);++/**+ * The modes that always launch a SEPARATE draft model, and so a second context+ * with its own KV cache for the draft cache dtype to apply to.+ *+ * MTP is left out: whether it loads a drafter file (Gemma) or reads baked-in+ * heads out of the target GGUF (Qwen) is a property of the model, known only once+ * the loader has read its metadata. The backend emits the draft cache flags+ * wherever it emits --model-draft, so a stored setting still reaches an MTP load+ * that does attach one.+ */+export const SEPARATE_DRAFT_MODEL_SPEC_TYPES: ReadonlySet<string> = new Set([+ "dspark",+ "dflash",+]);diff --git a/studio/frontend/tests/resident-config-match-accelerator-matrix.test.ts b/studio/frontend/tests/resident-config-match-accelerator-matrix.test.tsindex 664c21ea717..ff124e40476 100644--- a/studio/frontend/tests/resident-config-match-accelerator-matrix.test.ts+++ b/studio/frontend/tests/resident-config-match-accelerator-matrix.test.ts@@ -185,6 +185,30 @@ const FIELDS: FieldCase[] = [same: 512,different: 256,},+ {+ key: "loadMode",+ statusKey: "requested_load_mode",+ same: "mmap+mlock",+ different: "mmap",+ },+ {+ key: "specDraftCacheDtype",+ statusKey: "requested_spec_draft_cache_type",+ same: "q8_0",+ different: "f16",+ },+ {+ key: "ctxCheckpoints",+ statusKey: "requested_ctx_checkpoints",+ same: 8,+ different: 32,+ },+ {+ key: "cacheRam",+ statusKey: "requested_cache_ram",+ same: 4096,+ different: 8192,+ },{key: "chatTemplateOverride",statusKey: "chat_template_override",diff --git a/studio/frontend/tests/server-tuning-settings.test.ts b/studio/frontend/tests/server-tuning-settings.test.tsnew file mode 100644index 00000000000..7bda7e2f7e5--- /dev/null+++ b/studio/frontend/tests/server-tuning-settings.test.ts@@ -0,0 +1,200 @@+// 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 four llama-server tuning controls in Run settings: Mmap/Mlock, the draft+// KV cache dtype, Checkpoints and Cache RAM. Normalization (what a stored blob+// can and cannot say), the load payload's omit-when-blank rule, and the+// extra-arguments diagnostics that name the control a typed flag duplicates.++import assert from "node:assert/strict";+import { readFileSync } from "node:fs";+import test from "node:test";+import { fileURLToPath } from "node:url";++import { registerBundlerResolver } from "./helpers/kit.ts";++registerBundlerResolver();++const {+ CACHE_RAM_MAX,+ CACHE_RAM_MIN,+ CTX_CHECKPOINTS_MAX,+ LOAD_MODES,+ canonicalizeLoadMode,+ normalizeCacheRam,+ normalizeCtxCheckpoints,+ normalizePerModelConfig,+} = await import(+ "../src/features/model-picker/model-config/per-model-config.ts"+);+const { loadedConfigSignature } = await import(+ "../src/features/model-picker/model-config/config-signature.ts"+);+const { diagnoseExtraArgs } = await import(+ "../src/features/model-picker/model-config/llama-extra-args.ts"+);+const {+ clearedServerTuningState,+ committedServerTuningState,+ serverTuningLoadPayload,+} = await import("../src/features/chat/lib/server-tuning-fields.ts");++test("every documented load mode is offered, and auto is the unset sentinel", () => {+ assert.deepEqual(+ [...LOAD_MODES],+ ["auto", "none", "mmap", "mlock", "mmap+mlock", "dio"],+ );+ // "auto" IS llama.cpp's default, so it is stored as null and never emitted.+ assert.equal(canonicalizeLoadMode("auto"), null);+ assert.equal(canonicalizeLoadMode(" MMAP+MLOCK "), "mmap+mlock");+ // Repaired spellings are refused, not guessed at: llama-server exits on one.+ assert.equal(canonicalizeLoadMode("mmap + mlock"), null);+ assert.equal(canonicalizeLoadMode("swap"), null);+ assert.equal(canonicalizeLoadMode(42), null);+});++test("checkpoints and cache RAM clamp instead of refusing", () => {+ assert.equal(normalizeCtxCheckpoints(0), 0);+ assert.equal(normalizeCtxCheckpoints(1e6), CTX_CHECKPOINTS_MAX);+ assert.equal(normalizeCtxCheckpoints(-5), 0);+ assert.equal(normalizeCtxCheckpoints(null), null);+ // -1 (no limit) and 0 (disabled) are values here, not "unset"+ assert.equal(normalizeCacheRam(-1), CACHE_RAM_MIN);+ assert.equal(normalizeCacheRam(0), 0);+ assert.equal(normalizeCacheRam(-99), CACHE_RAM_MIN);+ assert.equal(normalizeCacheRam(1e12), CACHE_RAM_MAX);+ assert.equal(normalizeCacheRam("2048"), null);+});++test("a stored draft cache dtype needs a mode that loads a separate drafter", () => {+ const kept = normalizePerModelConfig({+ speculativeType: "dspark",+ specDraftCacheDtype: "q8_0",+ });+ assert.equal(kept.specDraftCacheDtype, "q8_0");+ // ngram loads no draft model, so there is no draft context for it to apply to.+ const dropped = normalizePerModelConfig({+ speculativeType: "ngram",+ specDraftCacheDtype: "q8_0",+ });+ assert.equal(dropped.specDraftCacheDtype, null);+ // and a dtype llama.cpp has no cache for is dropped whatever the mode+ assert.equal(+ normalizePerModelConfig({+ speculativeType: "dflash",+ specDraftCacheDtype: "q3_k",+ }).specDraftCacheDtype,+ null,+ );+});++test("the four take part in the editor's identity", () => {+ // loadedConfigSignature keys the Run settings instance, so a field missing from+ // it leaves the panel showing saved values over a model running different ones,+ // and Apply then writes those back. (The reload comparison itself is swept by+ // resident-config-match-accelerator-matrix.test.ts.)+ const base = loadedConfigSignature(normalizePerModelConfig({}));+ for (const patch of [+ { loadMode: "dio" },+ { ctxCheckpoints: 8 },+ { cacheRam: 0 },+ { speculativeType: "dspark", specDraftCacheDtype: "q8_0" },+ ]) {+ assert.notEqual(+ loadedConfigSignature(normalizePerModelConfig(patch)),+ base,+ `${JSON.stringify(patch)} must read as a change`,+ );+ }+ assert.equal(loadedConfigSignature(normalizePerModelConfig({})), base);+});++test("a record only claims the new schema version when it carries one", () => {+ // toStoredConfig stamps the OLDEST version that understands every field+ // present, so an older client can still rewrite a record it fully knows.+ const source = readFileSync(+ fileURLToPath(+ new URL(+ "../src/features/model-picker/model-config/per-model-config.ts",+ import.meta.url,+ ),+ ),+ "utf8",+ );+ assert.match(source, /const STORAGE_SCHEMA_VERSION = 5;/);+ assert.match(source, /const PRE_SERVER_TUNING_SCHEMA_VERSION = 4;/);+ assert.match(source, /hasServerTuning\s*\n?\s*\?\s*STORAGE_SCHEMA_VERSION/);+});++test("blank knobs are omitted from the load payload", () => {+ // A null counts as SET on the backend, which strips the matching flag out of+ // any inherited extra arguments. Blank means "no opinion", so it must not be+ // present at all.+ assert.deepEqual(+ serverTuningLoadPayload({+ loadMode: null,+ specDraftCacheDtype: null,+ ctxCheckpoints: null,+ cacheRam: null,+ }),+ {},+ );+ assert.deepEqual(+ serverTuningLoadPayload({+ loadMode: "dio",+ specDraftCacheDtype: "q8_0",+ ctxCheckpoints: 0,+ cacheRam: -1,+ }),+ {+ // biome-ignore lint/style/useNamingConvention: API schema+ load_mode: "dio",+ // biome-ignore lint/style/useNamingConvention: API schema+ spec_draft_cache_type: "q8_0",+ // biome-ignore lint/style/useNamingConvention: API schema+ ctx_checkpoints: 0,+ // biome-ignore lint/style/useNamingConvention: API schema+ cache_ram: -1,+ },+ );+});++test("a launch commits the click-time values, and diffusion commits none", () => {+ const values = { loadMode: "mmap", ctxCheckpoints: 8, cacheRam: 2048 };+ const committed = committedServerTuningState(values);+ assert.equal(committed.loadMode, "mmap");+ // control and baseline move together: the baseline is what the rollback resends+ assert.equal(committed.loadedLoadMode, "mmap");+ assert.equal(committed.loadedCtxCheckpoints, 8);+ // The diffusion runner launches no llama-server, so a value recorded against+ // it would be carried onto the next GGUF by a saved preset.+ assert.deepEqual(+ committedServerTuningState(values, true),+ clearedServerTuningState(),+ );+});++test("a typed flag is told which control it duplicates", () => {+ const named = (text: string) =>+ diagnoseExtraArgs(text, null, {})+ .map((entry) => entry.message)+ .join(" ");+ assert.match(named("--ctx-checkpoints 8"), /Checkpoints/);+ assert.match(named("-cram 2048"), /Cache RAM/);+ assert.match(named("--spec-draft-type-k q8_0"), /Spec Decoding KV Cache Dtype/);+ assert.match(named("--swa-checkpoints 4"), /Checkpoints/);+ // Not a denial: the extras are appended last, so the typed flag is what runs.+ assert.match(named("--ctx-checkpoints 8"), /wins/);+});++test("the load mode is reported as removed, not as winning, under Model Memory", () => {+ // apply_model_memory_policy runs before the extras reach the command line, so+ // saying a typed --load-mode wins would be false.+ const messages = diagnoseExtraArgs("--load-mode dio", null, {+ keepResident: true,+ }).map((entry) => entry.message);+ assert.ok(+ messages.some((message) => /removed/.test(message)),+ messages.join(" "),+ );+});