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: honor MLX KV cache quantization and chat template overrides (#8007)
Long Yixing34a709295d84
diff --git a/studio/backend/core/inference/mlx_inference.py b/studio/backend/core/inference/mlx_inference.pyindex 1b582073506..fa873611755 100644--- a/studio/backend/core/inference/mlx_inference.py+++ b/studio/backend/core/inference/mlx_inference.py@@ -133,6 +133,11 @@ def _render_registered_vlm_prompt(# Rate the chat route decodes uploads to; mlx-vlm does not resample arrays._AUDIO_INPUT_SAMPLE_RATE = 16000_AUDIO_PROBE_MESSAGES = [{"role": "user", "content": "audio"}]+# Same turn with and without an image part, so a diff isolates the image marker.+_IMAGE_PROBE_MESSAGES = [+ {"role": "user", "content": [{"type": "image"}, {"type": "text", "text": "hi"}]}+]+_TEXT_PROBE_MESSAGES = [{"role": "user", "content": [{"type": "text", "text": "hi"}]}]def _classify_mlx_audio_type(@@ -313,6 +318,441 @@ def _build_generation_stats(PROMPT_CACHE_ENTRIES = 6++# Every bit width mx.quantize supports; unrelated to llama.cpp's cache_type_kv names.+MLX_KV_BITS_CHOICES = (8, 6, 5, 4, 3, 2)+# Quantization group size; a head dim that is not a multiple makes mx.quantize raise.+MLX_KV_GROUP_SIZE = 64+# Surfaced with the resolved setting so an API client sees the reuse cost too.+MLX_KV_QUANT_NO_REUSE = (+ "The installed mlx-lm cannot measure a quantized cache entry, so prompt-cache "+ "reuse across turns is disabled while this is on."+)+MLX_KV_QUANT_VLM_CACHE_NOTE = (+ "On vision models, quantization starts once the cache reaches {start} tokens."+)+++def _kv_entry_nbytes(entry):+ """Bytes held by one cache entry, or None when it cannot be measured.++ Read straight off the property, because that is what decides admission:+ upstream's LRUPromptCache.insert_cache sums ``c.nbytes`` itself, so an+ entry whose property raises (mlx-lm 0.31.2's QuantizedKVCache, a missing+ tree_reduce import) cannot enter the cache however else it could be sized.+ Measuring it another way here would only promise reuse that never happens.+ """+ try:+ return int(entry.nbytes)+ except Exception:+ return None+++def _normalize_mlx_kv_bits(value):+ """Supported bit width, or None when unset or out of domain."""+ if value is None:+ return None+ try:+ bits = int(value)+ except (TypeError, ValueError):+ logger.warning("MLX kv_bits=%r is not an integer; ignoring", value)+ return None+ if bits not in MLX_KV_BITS_CHOICES:+ logger.warning(+ "MLX kv_bits=%s unsupported (choose %s); ignoring",+ bits,+ " or ".join(str(b) for b in MLX_KV_BITS_CHOICES),+ )+ return None+ return bits+++def _kv_quant_probe(language_model, entries, bits):+ """Attempt the conversion the runtime will perform, on a real cache.++ Static proxies proved wrong in both directions: a model can declare a+ head_dim it does not use for the cache, and a window can be spelled+ differently from entry to entry. So populate one token and try the+ conversion that generation would do.++ Returns ``(converted, skipped, failure, retainable)``. ``retainable`` is+ False when a converted entry's size cannot be read, because the prompt+ cache budgets by size and upstream recomputes it internally.+ """+ import mlx.core as mx++ convertible = [entry for entry in entries if getattr(entry, "to_quantized", None) is not None]+ if not convertible:+ # Verdict already known, so skip the cost of a full model call.+ return 0, len(entries), None, True+ if any(+ getattr(entry, name, None) is not None+ for entry in convertible+ for name in ("max_size", "window_size")+ ):+ # A bounded ring cannot be probed unwrapped, and wrapped its conversion+ # keeps an absolute offset past its storage. Refuse before the forward pass.+ return 0, 0, "it uses a bounded sliding window", True++ # The forward pass below draws random numbers, so keep sampled output stable.+ # mx.random.state is mutated in place, so restore element-wise, not by rebinding.+ rng_state = list(mx.random.state)+ try:+ try:+ language_model(mx.array([[0]]), cache = entries)+ mx.eval([getattr(entry, "state", None) for entry in entries])+ except Exception as exc:+ return 0, 0, f"its cache could not be exercised ({type(exc).__name__})", True++ converted = skipped = 0+ retainable = True+ for entry in entries:+ convert = getattr(entry, "to_quantized", None)+ if convert is None:+ skipped += 1+ continue+ try:+ quantized = convert(group_size = MLX_KV_GROUP_SIZE, bits = bits)+ mx.eval(quantized.state)+ converted += 1+ except Exception as exc:+ return converted, skipped, f"MLX cannot quantize it ({type(exc).__name__})", True+ # Same helper insertion uses, so the caveat matches what insertion sees.+ if retainable and _kv_entry_nbytes(quantized) is None:+ retainable = False+ return converted, skipped, None, retainable+ finally:+ mx.random.state[:] = rng_state+++def _kv_quant_eligibility(+ model,+ is_vlm,+ bits = MLX_KV_BITS_CHOICES[0],+):+ """Whether KV quantization can apply to this model, before generating.++ Returns ``(verdict, reason, retainable)``, verdict in+ full/partial/none/refused. Eligibility only: what the runtime converts stays+ its own decision. Refusing here is what stops an ineligible model raising+ mid-generation, once the leading entries are already converted.+ """+ language_model = getattr(model, "language_model", model) if is_vlm else model+ try:+ if is_vlm:+ from mlx_vlm.models import cache as vlm_cache+ entries = vlm_cache.make_prompt_cache(language_model)+ else:+ from mlx_lm.models import cache as lm_cache+ entries = lm_cache.make_prompt_cache(language_model)+ except Exception as exc:+ logger.warning("MLX KV quantization eligibility probe failed: %s", exc)+ return "none", "this model's KV cache layout could not be inspected", True++ if not entries:+ return "none", "this model builds no KV cache to quantize", True++ converted, skipped, failure, retainable = _kv_quant_probe(language_model, entries, bits)+ # Released only here, once the probe's own locals are gone, or the pages stay+ # in the allocator.+ import mlx.core as mx++ entries.clear()+ del entries+ mx.clear_cache()+ if failure is not None:+ return "refused", f"this model's KV cache cannot be quantized: {failure}", True+ if not converted:+ return "none", "this model's KV cache layout cannot be quantized", True+ verdict = "partial" if skipped else "full"+ reason = "only some of this model's layers use a quantizable KV cache" if skipped else ""+ return verdict, reason, retainable+++def _vlm_quantized_kv_start():+ """Token offset at which mlx-vlm begins quantizing, per its own default."""+ try:+ from mlx_vlm.generate.common import DEFAULT_QUANTIZED_KV_START+ return int(DEFAULT_QUANTIZED_KV_START)+ except Exception:+ return 5000+++# An override replaces an existing template, never creates one: both render+# selectors pick their target by whether a template is present, so creating one+# would silently move the render to a different object.+_TEMPLATE_NOT_CAPTURED = object()+MLX_TEMPLATE_NO_TARGET = (+ "this model builds its prompt without a chat template, and supplying one "+ "would drop the markers that place its images and audio"+)+MLX_TEMPLATE_CALLABLE = (+ "the installed mlx-lm supplies this model's template as code rather than text, "+ "and prefers it over any override"+)+MLX_TEMPLATE_NAMED_SET = (+ "this model ships a set of named templates rather than one, and replacing the "+ "set with a single template would lose its tool-calling variant"+)+MLX_TEMPLATE_RENDER_FAILED = "it could not render a conversation: {error}"+MLX_TEMPLATE_NOT_SETTABLE = "this model's template cannot be replaced: {error}"+MLX_TEMPLATE_DROPS_IMAGE = (+ "it does not mark where images go, so this model could not accept image input with it"+)+MLX_TEMPLATE_DROPS_AUDIO = (+ "it does not mark where audio goes, so this model could not accept audio input with it"+)+++def _template_install_targets(tokenizer, processor):+ """Objects whose chat_template would be read at render time.++ The processor and the tokenizer can be the same object when a processor+ exposes no nested tokenizer, so the result is de-duplicated by identity.+ """+ seen, targets = [], []+ for candidate in (processor, tokenizer):+ if candidate is None:+ continue+ if any(candidate is other for other in seen):+ continue+ seen.append(candidate)+ targets.append(candidate)+ return targets+++def _template_render_targets(tokenizer, processor):+ """Objects a render selector would actually read the template from.++ Deferred to chat_render_target rather than restated (#7066): it also+ requires the processor to be able to render, and mlx-vlm's+ get_chat_template applies the same rule for audio.+ """+ from core.inference.chat_template_helpers import chat_render_target++ target = chat_render_target(processor, tokenizer)+ return [target] if target is not None else []+++def _usable_template(value):+ """Whether a chat_template value is one this override can replace."""+ return isinstance(value, str) and value.strip() != ""+++def _native_template_source(tokenizer, processor):+ """The object whose chat_template is this model's default.++ The render target, so the editor's "model default" is the text generation+ really uses. Falls back to the tokenizer when that target holds no usable+ string, keeping the nested template reported for a processor carrying a+ named set rather than reporting none at all.+ """+ for target in _template_render_targets(tokenizer, processor):+ if _usable_template(getattr(target, "chat_template", None)):+ return target+ return tokenizer+++def _template_override_status(override, tokenizer, processor):+ """Resolve a requested override against this model, without applying it.++ Returns the targets to install onto and a status dict; an empty target list+ with a reason means the override cannot be honored.+ """+ status = {+ "requested": override,+ "applied": None,+ "reason": None,+ # Kept so a later check (the audio marker) can put the model back.+ "restore": [],+ }+ if not override or not override.strip():+ return [], status+ try:+ candidates = _template_install_targets(tokenizer, processor)+ existing = [(c, getattr(c, "chat_template", None)) for c in candidates]+ rendering = _template_render_targets(tokenizer, processor)+ except Exception as exc:+ status["reason"] = MLX_TEMPLATE_NOT_SETTABLE.format(error = exc)+ return [], status+ # Judge only the objects that render: an unreplaceable template on an object+ # nothing reads would reject a working override.+ blocked = [(c, getattr(c, "chat_template", None)) for c in rendering]+ if any(getattr(c, "_chat_template", None) is not None for c in rendering):+ # apply_chat_template prefers a callable template over the attribute, so+ # an assignment would be inert.+ status["reason"] = MLX_TEMPLATE_CALLABLE+ return [], status+ if any(isinstance(value, (dict, list)) for _, value in blocked):+ status["reason"] = MLX_TEMPLATE_NAMED_SET+ return [], status+ if not any(_usable_template(value) for _, value in blocked):+ # Nothing to replace. Honorable on a text model, which cannot chat without+ # one. Not with a processor: creating one takes the render away from+ # mlx-vlm's fallback, which is what places the markers.+ if processor is not None or not blocked:+ status["reason"] = MLX_TEMPLATE_NO_TARGET+ return [], status+ return [c for c, _ in blocked], status+ # Install on every object holding a replaceable string, so both selectors keep+ # choosing what they chose before.+ return [c for c, value in existing if _usable_template(value)], status+++def _audio_marker_survives(processor, model):+ """Whether the installed template still marks where audio goes."""+ if processor is None:+ return True+ args = (processor, model, _AUDIO_PROBE_MESSAGES, 0)+ try:+ marked = _render_registered_vlm_prompt(*args, num_audios = 1)+ return bool(marked) and marked != _render_registered_vlm_prompt(*args, num_audios = 0)+ except BaseException:+ # A load must never fail on a probe, matching _classify_mlx_audio_type.+ return False+++def _image_placeholder(tokenizer, processor):+ """The model's own image placeholder, when it names one."""+ for source in (processor, tokenizer):+ token = getattr(source, "image_token", None)+ if isinstance(token, str) and token:+ return token+ return None+++def _image_marker_survives(+ tokenizer,+ processor,+ placeholder = None,+):+ """Whether the installed template still marks where an image goes.++ Rendered through the target generation uses, so this sees what a real image+ request would. Three ways to fail: rendering an image the same as no image,+ emitting the structured content object instead of a marker, and dropping+ the placeholder the model names. A bare difference is not enough on its+ own, since a template can render the image as ordinary prose.+ """+ from core.inference.chat_template_helpers import apply_chat_template_for_generation++ targets = _template_render_targets(tokenizer, processor)+ if not targets:+ return True+ target = targets[0]+ try:+ marked = apply_chat_template_for_generation(target, _IMAGE_PROBE_MESSAGES)+ if not marked or marked == apply_chat_template_for_generation(target, _TEXT_PROBE_MESSAGES):+ return False+ if _vlm_prompt_issue(marked, _IMAGE_PROBE_MESSAGES):+ return False+ return placeholder is None or placeholder in marked+ except BaseException:+ # A load must never fail on a probe, matching _audio_marker_survives.+ return False+++def _revoke_override_dropping(status, survives, reason):+ """Undo an installed override that stopped marking where media goes.++ Capability was classified against the native template, so an override that+ no longer renders the marker would leave the model advertising an input it+ can no longer place.+ """+ if not status["applied"] or survives():+ return status+ _restore_templates(status["restore"])+ status["applied"] = None+ status["restore"] = []+ status["reason"] = reason+ return status+++def _revoke_override_that_drops_audio(status, processor, model):+ return _revoke_override_dropping(+ status,+ lambda: _audio_marker_survives(processor, model),+ MLX_TEMPLATE_DROPS_AUDIO,+ )+++def _revoke_override_that_drops_image(+ status,+ tokenizer,+ processor,+ placeholder = None,+):+ return _revoke_override_dropping(+ status,+ lambda: _image_marker_survives(tokenizer, processor, placeholder),+ MLX_TEMPLATE_DROPS_IMAGE,+ )+++def _restore_templates(installed):+ """Put back the templates an install replaced, newest first."""+ for target, value in reversed(installed):+ target.chat_template = value+++def _install_template_override(override, tokenizer, processor, probe):+ """Install a chat template override, or report why it was not honored.++ ``probe`` renders a short conversation with whatever is installed; a+ template that cannot render would otherwise raise on every generation+ instead of once here, which is how a hand-edited template usually fails.+ """+ targets, status = _template_override_status(override, tokenizer, processor)+ if not targets:+ return status+ # Restore only what was actually assigned: a target that refused the assignment+ # would refuse the restore too, masking the real error.+ installed = []+ template = MLX_TEMPLATE_RENDER_FAILED+ try:+ for target in targets:+ original = target.chat_template+ template = MLX_TEMPLATE_NOT_SETTABLE+ target.chat_template = override+ template = MLX_TEMPLATE_RENDER_FAILED+ installed.append((target, original))+ probe()+ except Exception as exc:+ _restore_templates(installed)+ status["reason"] = template.format(error = exc)+ return status+ status["applied"] = override+ status["restore"] = installed+ return status+++def _kv_quant_status(requested_bits, model, is_vlm):+ """Resolve a requested bit width against this model into a status dict."""+ status = {+ "requested_kv_bits": requested_bits,+ "kv_bits": None,+ "eligibility": None,+ "reason": "",+ "note": "",+ }+ if requested_bits is None:+ return status+ verdict, reason, retainable = _kv_quant_eligibility(model, is_vlm, requested_bits)+ status["eligibility"] = verdict+ status["reason"] = reason+ if verdict in ("full", "partial"):+ status["kv_bits"] = requested_bits+ notes = []+ if is_vlm:+ notes.append(MLX_KV_QUANT_VLM_CACHE_NOTE.format(start = _vlm_quantized_kv_start()))+ if not retainable:+ notes.append(MLX_KV_QUANT_NO_REUSE)+ status["note"] = " ".join(notes)+ else:+ logger.info("MLX KV quantization not applied: %s", reason)+ return status++PROMPT_CACHE_MEMORY_FRACTION = 0.15PROMPT_CACHE_FALLBACK_BYTES = 2 * 1024**3@@ -398,7 +838,11 @@ class _MLXPromptCacheHistory:def insert(self, key, tokens, cache):# An over-budget entry evicts itself and every other conversation.- nbytes = sum(getattr(entry, "nbytes", 0) for entry in cache)+ sizes = [_kv_entry_nbytes(entry) for entry in cache]+ if any(size is None for size in sizes):+ logger.debug("MLX prompt cache: skipping state whose size is unmeasurable")+ return+ nbytes = sum(sizes)if nbytes > self._max_bytes:logger.debug("MLX prompt cache: skipping %.2f GB entry over the %.2f GB budget",@@ -528,6 +972,12 @@ class MLXInferenceBackend:# Recorded for unload to release pinned memory back to the OS.self._memory_limits_applied = {}+ # Load-time runtime knobs; every generation path reads them from here rather+ # than from per-request kwargs. Bound now so a load that fails before+ # installing leaves readers a dict rather than raising.+ self._kv_quant = _kv_quant_status(None, None, False)+ self._template_override = _template_override_status(None, None, None)[1]+self._prompt_cache_history = Noneself._prompt_cache_unavailable = False@@ -577,6 +1027,15 @@ class MLXInferenceBackend:return prompt, None, None, None, 0return rest, cache, key, tokens, len(tokens) - len(rest)+ def _kv_quant_generate_kwargs(self):+ """Load-time runtime knobs for a generate call, empty when unset.++ quantized_kv_start is deliberately not passed: mlx-lm and mlx-vlm ship+ different defaults (0 and 5000) and each runtime keeps its own.+ """+ kv_bits = (getattr(self, "_kv_quant", None) or {}).get("kv_bits")+ return {} if kv_bits is None else {"kv_bits": kv_bits}+def _configure_memory_limits(self):"""Apply Metal memory caps before loading a model.@@ -619,6 +1078,8 @@ class MLXInferenceBackend:dtype = None,parallel_mode = None,distributed_group = None,+ kv_bits = None,+ chat_template_override = None,) -> bool:import mlx.core as mx@@ -722,6 +1183,54 @@ class MLXInferenceBackend:is_vision,config_audio_type = getattr(config, "audio_type", None),)+ # Classify before the first generation: an ineligible cache would otherwise+ # raise inside maybe_quantize_kv_cache mid-stream, after converting the+ # leading entries.+ self._kv_quant = _kv_quant_status(_normalize_mlx_kv_bits(kv_bits), self._model, is_vision)+ if self._kv_quant["kv_bits"] is not None:+ logger.info(+ "MLX KV cache quantization: %s-bit (%s eligibility)",+ self._kv_quant["kv_bits"],+ self._kv_quant["eligibility"],+ )++ # Captured before installing, so chat_template_info keeps reporting what the+ # model shipped with. From the render target, not the nested tokenizer: on a+ # processor owning its own template those differ, and saving the wrong+ # default back would install the tokenizer's template over the processor.+ native_source = _native_template_source(self._tokenizer, self._processor)+ native_template = getattr(native_source, "chat_template", None)+ native_marks_audio = bool(+ chat_template_override+ and is_audio_input_type(_audio_type)+ and _audio_marker_survives(self._processor, self._model)+ )+ image_placeholder = _image_placeholder(self._tokenizer, self._processor)+ self._template_override = _install_template_override(+ chat_template_override,+ self._tokenizer,+ self._processor,+ lambda: self._render_template_probe(is_vision),+ )+ if native_marks_audio:+ _revoke_override_that_drops_audio(self._template_override, self._processor, self._model)+ # Unconditional for vision, unlike audio: a native template that marks+ # nothing still renders images through _generate_vlm's recovery, but an+ # override rendering plain text drops the image in silence, so gating on+ # the native template would skip exactly the models needing the check.+ if is_vision:+ _revoke_override_that_drops_image(+ self._template_override, self._tokenizer, self._processor, image_placeholder+ )+ # Released once the media checks are done: the pairs reference the tokenizer+ # and processor, so keeping them would outlive the unload that nulls both.+ self._template_override["restore"] = []+ if self._template_override["reason"]:+ logger.info(+ "MLX chat template override not applied: %s",+ self._template_override["reason"],+ )+self.active_model_name = model_nameself.models[model_name] = {# Per-model token for the native-template fallback (matches transformers).@@ -742,18 +1251,55 @@ class MLXInferenceBackend:"audio_type": _audio_type,"has_audio_input": is_audio_input_type(_audio_type),"context_length": runtime_context_length(self._model, max_seq_length),+ "mlx_kv_bits": self._kv_quant["kv_bits"],+ "mlx_kv_bits_requested": self._kv_quant["requested_kv_bits"],+ "mlx_kv_quant_eligibility": self._kv_quant["eligibility"],+ "mlx_kv_quant_reason": self._kv_quant["reason"],+ "mlx_kv_quant_note": self._kv_quant["note"],+ "chat_template_override_requested": self._template_override["requested"],+ "chat_template_override_reason": self._template_override["reason"],}# Capture chat_template_info for the worker IPC reply and route capability classification.- self._populate_chat_template_info(model_name)+ self._populate_chat_template_info(model_name, native_template)logger.info("Model %s loaded successfully", model_name)return True- def _populate_chat_template_info(self, model_name: str) -> None:+ def _render_template_probe(self, is_vision: bool) -> str:+ """Render a short conversation through the path generation will use.++ Must use the same target the real request does. The recovery renderer+ returns None instead of raising for a model outside mlx-vlm's family+ list, so probing it would pass a template that cannot render at all.+ """+ from core.inference.chat_template_helpers import (+ apply_chat_template_for_generation,+ chat_render_target,+ )++ messages = [{"role": "user", "content": "hi"}]+ target = (+ chat_render_target(self._processor)+ if is_vision and self._processor is not None+ else self._tokenizer+ )+ rendered = apply_chat_template_for_generation(target, messages)+ if not rendered or not rendered.strip():+ raise ValueError("the template produced an empty prompt")+ return rendered++ def _populate_chat_template_info(+ self,+ model_name: str,+ native_template = _TEMPLATE_NOT_CAPTURED,+ ) -> None:"""Mirror InferenceBackend._load_chat_template_info for MLX.- Stores ``chat_template_info`` on ``self.models[model_name]`` with the- resolved ``tokenizer.chat_template``."""+ Stores ``chat_template_info`` on ``self.models[model_name]``. The+ template recorded is the one the model shipped with, not an override:+ the capability classification and the editor's notion of "default"+ both read it, so an override installed on the tokenizer must not+ show up here."""entry = self.models.get(model_name)if not entry:return@@ -769,7 +1315,11 @@ class MLXInferenceBackend:"template_name": None,}try:- tpl = getattr(tok, "chat_template", None)+ tpl = (+ getattr(tok, "chat_template", None)+ if native_template is _TEMPLATE_NOT_CAPTURED+ else native_template+ )if tpl:info["has_template"] = Trueinfo["template"] = tpl@@ -1029,6 +1579,7 @@ class MLXInferenceBackend:max_tokens = max_new_tokens,sampler = sampler,)+ gen_kwargs.update(self._kv_quant_generate_kwargs())if prompt_cache is not None:gen_kwargs["prompt_cache"] = prompt_cacheif logits_processors is not None:@@ -1216,6 +1767,7 @@ class MLXInferenceBackend:top_k = int(top_k or 0),min_p = float(min_p or 0.0),)+ vlm_kwargs.update(self._kv_quant_generate_kwargs())_rep_active = repetition_penalty is not None and float(repetition_penalty) not in (0.0,1.0,@@ -1338,7 +1890,9 @@ class MLXInferenceBackend:prompt,audio = [audio_array],max_tokens = max_new_tokens,+ # Greedy; the knobs below are load-time state, not caller kwargs.temperature = 0.0,+ **self._kv_quant_generate_kwargs(),):final_response = responsetoken_text = response.text if hasattr(response, "text") else str(response)diff --git a/studio/backend/core/inference/orchestrator.py b/studio/backend/core/inference/orchestrator.pyindex 2ee827ee181..8f00a722c0c 100644--- a/studio/backend/core/inference/orchestrator.py+++ b/studio/backend/core/inference/orchestrator.py@@ -61,6 +61,27 @@ _DISPATCH_DRAIN_TIMEOUT = 5.0_UNLOAD_GEN_LOCK_TIMEOUT = 15.0+_MLX_RUNTIME_MIRROR_FIELDS = (+ "mlx_kv_bits",+ "mlx_kv_bits_requested",+ "mlx_kv_quant_eligibility",+ "mlx_kv_quant_reason",+ "mlx_kv_quant_note",+ "chat_template_override_requested",+ "chat_template_override_reason",+)+++def _mlx_runtime_mirror_fields(model_info: dict) -> dict:+ """MLX runtime state the parent mirrors, omitting what was not reported.++ Only the MLX backend sends these. Creating the keys for every backend would+ make the reload comparison see a None the backend never stored, and reload+ on every identical request.+ """+ return {key: model_info[key] for key in _MLX_RUNTIME_MIRROR_FIELDS if key in model_info}++class GenStreamError(str):"""A stream chunk carrying a real backend/generation error, not model text.@@ -1179,6 +1200,8 @@ class InferenceOrchestrator:subject: Optional[str] = None,tensor_parallel: bool = False,mlx_distributed: bool = False,+ mlx_kv_bits: Optional[int] = None,+ chat_template_override: Optional[str] = None,) -> bool:"""Load a model for inference.@@ -1212,6 +1235,8 @@ class InferenceOrchestrator:"mlx_parallel_mode": ("tensor" if tensor_parallel else "pipeline")if mlx_distributedelse None,+ "mlx_kv_bits": mlx_kv_bits,+ "chat_template_override": chat_template_override,}resolved_gpu_ids, gpu_selection = prepare_gpu_selection(gpu_ids,@@ -1358,6 +1383,9 @@ class InferenceOrchestrator:"has_audio_input": model_info.get("has_audio_input", False),"context_length": model_info.get("context_length"),}+ self.models[self.active_model_name].update(+ _mlx_runtime_mirror_fields(model_info)+ )# Mirror chat_template_info so routes can classify caps# without re-entering the subprocess._tpl_info = model_info.get("chat_template_info")diff --git a/studio/backend/core/inference/worker.py b/studio/backend/core/inference/worker.pyindex 9a1ec35f0fc..d45fe8abbbb 100644--- a/studio/backend/core/inference/worker.py+++ b/studio/backend/core/inference/worker.py@@ -404,6 +404,8 @@ def _handle_load(backend, config: dict, resp_queue: Any) -> None:if getattr(backend, "device", None) == "mlx":load_kwargs["parallel_mode"] = config.get("mlx_parallel_mode")load_kwargs["distributed_group"] = config.get("_mlx_distributed_group")+ load_kwargs["kv_bits"] = config.get("mlx_kv_bits")+ load_kwargs["chat_template_override"] = config.get("chat_template_override")success = backend.load_model(**load_kwargs)finally:heartbeat_stop.set()@@ -435,6 +437,22 @@ def _handle_load(backend, config: dict, resp_queue: Any) -> None:model_info.update({k: _entry[k] for k in ("is_audio", "audio_type", "has_audio_input") if k in _entry})+ # Resolved MLX runtime knobs; only the backend knows what it honored.+ model_info.update(+ {+ k: _entry[k]+ for k in (+ "mlx_kv_bits",+ "mlx_kv_bits_requested",+ "mlx_kv_quant_eligibility",+ "mlx_kv_quant_reason",+ "mlx_kv_quant_note",+ "chat_template_override_requested",+ "chat_template_override_reason",+ )+ if k in _entry+ }+ )# Forward chat_template_info so the parent can classify capabilities.try:_tpl_info = _entry.get("chat_template_info")diff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.pyindex d5d1ec65755..43deb6831da 100644--- a/studio/backend/models/inference.py+++ b/studio/backend/models/inference.py@@ -76,6 +76,16 @@ class LoadRequest(BaseModel):"(e.g. 'f16', 'bf16', 'q8_0', 'q4_0', 'q4_1', 'q5_0', 'q5_1', 'iq4_nl', 'f32')"),)+ mlx_kv_bits: Optional[int] = Field(+ None,+ description = (+ "MLX KV cache quantization bit width (8, 6, 5, 4, 3 or 2). MLX takes a bit "+ "width rather than a llama.cpp dtype name, so this is separate from "+ "cache_type_kv. Omit for an unquantized cache. Ignored by non-MLX "+ "backends; a model whose cache layout cannot be quantized reports "+ "the reason instead of applying it."+ ),+ )gpu_ids: Optional[List[int]] = Field(None,description = (@@ -536,6 +546,49 @@ class _InferenceRuntimeFields(BaseModel):"(e.g. 'f16', 'bf16', 'q8_0', 'q4_0', 'q4_1', 'q5_0', 'q5_1', 'iq4_nl', 'f32')"),)+ is_mlx: bool = Field(False, description = "Whether the active model is served by the MLX backend")+ mlx_kv_bits: Optional[int] = Field(+ None, description = "MLX KV quantization bit width actually applied, if any"+ )+ mlx_kv_bits_requested: Optional[int] = Field(+ None,+ description = (+ "MLX KV quantization bit width the load asked for. Differs from "+ "mlx_kv_bits when the model could not honor it, which is exactly "+ "when the reason matters."+ ),+ )+ chat_template_override: Optional[str] = Field(+ None,+ description = "Chat template override this model was loaded with. llama.cpp reports what it applied; MLX reports what was requested, since a refusal applies nothing and the reason accompanies it",+ )+ chat_template_override_reason: Optional[str] = Field(+ None,+ description = (+ "Why a requested chat template override was not applied: the "+ "runtime supplies the template as code, the model ships a named "+ "set rather than one template, it renders without a template, or "+ "the override could not render a conversation."+ ),+ )+ mlx_kv_quant_eligibility: Optional[str] = Field(+ None,+ description = (+ "Whether this model's KV cache could be quantized: full, partial, "+ "none or refused. Describes eligibility, not the exact set of "+ "converted layers, which the runtime decides."+ ),+ )+ mlx_kv_quant_reason: Optional[str] = Field(+ None,+ description = (+ "Why KV quantization was not applied in full: the model's cache "+ "layout, or the layers it could not cover when eligibility is partial"+ ),+ )+ mlx_kv_quant_note: Optional[str] = Field(+ None, description = "Caveat that applies when KV quantization is active"+ )chat_template: Optional[str] = Field(None,description = "Jinja2 chat template string (from GGUF metadata or tokenizer)",@@ -685,10 +738,6 @@ class InferenceStatusResponse(_InferenceRuntimeFields):inference: Optional[Dict[str, Any]] = Field(None, description = "Recommended inference parameters for the active model")- chat_template_override: Optional[str] = Field(- None,- description = "Active chat template override applied at load time, or None if model is using its default",- )requested_context_length: Optional[int] = Field(None,description = (diff --git a/studio/backend/routes/chat_history.py b/studio/backend/routes/chat_history.pyindex 4180518837f..cb235281145 100644--- a/studio/backend/routes/chat_history.py+++ b/studio/backend/routes/chat_history.py@@ -168,6 +168,7 @@ class ChatPresetLoadConfig(BaseModel):customContextLength: Optional[int] = Field(default = None, gt = 0)maxSeqLength: Optional[float] = NonekvCacheDtype: Optional[str] = None+ mlxKvBits: Optional[Literal[8, 6, 5, 4, 3, 2]] = NonespeculativeType: Optional[str] = NonespecDraftNMax: Optional[int] = Field(default = None, ge = 1, le = 16)nParallel: Optional[int] = Field(default = None, ge = PARALLEL_MIN, le = PARALLEL_MAX)diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex 266c6d954f8..7839d9cea94 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -3658,6 +3658,14 @@ def _llama_runtime_fields(llama_backend: LlamaCppBackend) -> dict:if hasattr(llama_backend, name) or hasattr(llama_backend, f"_{name}")}fields.update(+ # Not MLX, so the MLX runtime fields report as absent.+ is_mlx = False,+ mlx_kv_bits = None,+ mlx_kv_bits_requested = None,+ mlx_kv_quant_eligibility = None,+ mlx_kv_quant_reason = None,+ mlx_kv_quant_note = None,+ chat_template_override_reason = None,speculative_type = llama_backend.requested_spec_mode,requested_parallel_slots = (None if llama_backend.is_diffusion else llama_backend.requested_parallel_slots@@ -6098,6 +6106,24 @@ async def get_active_generations(}+def _mlx_runtime_settings_match(backend, request) -> bool:+ """Whether a loaded model already runs the request's MLX runtime settings.++ Only the MLX backend records these, so a backend that never stored them+ (GGUF, CUDA safetensors) always matches and reuse is unaffected. Both sides+ are normalized, otherwise an out-of-domain value would differ from the+ stored None on every request and reload forever.+ """+ entry = backend.models.get(backend.active_model_name, {}) or {}+ if "mlx_kv_bits_requested" not in entry:+ return True+ from core.inference.mlx_inference import _normalize_mlx_kv_bits++ return entry["mlx_kv_bits_requested"] == _normalize_mlx_kv_bits(request.mlx_kv_bits) and (+ entry.get("chat_template_override_requested") or None+ ) == (request.chat_template_override or None)++@router.post("/load", response_model = LoadResponse)async def load_model(request: LoadRequest,@@ -6303,6 +6329,7 @@ async def _load_model_impl(if (backend.active_model_nameand backend.active_model_name.lower() == model_identifier.lower()+ and _mlx_runtime_settings_match(backend, request)):api_monitor.discard(_load_event) # nothing loaded, no monitor rowlogger.info(f"Model already loaded (Unsloth): {model_log_label}, skipping reload")@@ -6335,6 +6362,16 @@ async def _load_model_impl(is_audio = _model_info.get("is_audio", False),audio_type = _model_info.get("audio_type"),has_audio_input = _model_info.get("has_audio_input", False),+ is_mlx = bool(_model_info.get("is_mlx", False)),+ mlx_kv_bits = _model_info.get("mlx_kv_bits"),+ mlx_kv_bits_requested = _model_info.get("mlx_kv_bits_requested"),+ mlx_kv_quant_eligibility = _model_info.get("mlx_kv_quant_eligibility"),+ mlx_kv_quant_reason = _model_info.get("mlx_kv_quant_reason"),+ mlx_kv_quant_note = _model_info.get("mlx_kv_quant_note"),+ # Requested, as /status reports it: a null override would read+ # as "using the default".+ chat_template_override = _model_info.get("chat_template_override_requested"),+ chat_template_override_reason = _model_info.get("chat_template_override_reason"),inference = inference_config,requires_trust_remote_code = _resolve_loaded_trust_remote_code(backend.active_model_name, _model_info, inference_config@@ -6726,6 +6763,8 @@ async def _load_model_impl(approved_remote_code_fingerprint = request.approved_remote_code_fingerprint,gpu_ids = placement.requested_gpu_ids,subject = current_subject,+ mlx_kv_bits = request.mlx_kv_bits,+ chat_template_override = request.chat_template_override,)if not success:@@ -6817,6 +6856,16 @@ async def _load_model_impl(is_audio = _model_info.get("is_audio", config.is_audio),audio_type = _model_info.get("audio_type", config.audio_type),has_audio_input = _model_info.get("has_audio_input", config.has_audio_input),+ is_mlx = bool(_model_info.get("is_mlx", False)),+ mlx_kv_bits = _model_info.get("mlx_kv_bits"),+ mlx_kv_bits_requested = _model_info.get("mlx_kv_bits_requested"),+ mlx_kv_quant_eligibility = _model_info.get("mlx_kv_quant_eligibility"),+ mlx_kv_quant_reason = _model_info.get("mlx_kv_quant_reason"),+ mlx_kv_quant_note = _model_info.get("mlx_kv_quant_note"),+ # Requested, as /status reports it: a null override would read as+ # "using the default".+ chat_template_override = _model_info.get("chat_template_override_requested"),+ chat_template_override_reason = _model_info.get("chat_template_override_reason"),inference = inference_config,requires_trust_remote_code = _requires_rc,supports_reasoning = _sf_flags["supports_reasoning"],@@ -8046,6 +8095,14 @@ async def get_status(current_subject: str = Depends(get_current_subject)):is_audio = is_audio,audio_type = audio_type,has_audio_input = has_audio_input,+ is_mlx = bool(model_info.get("is_mlx", False)),+ mlx_kv_bits = model_info.get("mlx_kv_bits"),+ mlx_kv_bits_requested = model_info.get("mlx_kv_bits_requested"),+ mlx_kv_quant_eligibility = model_info.get("mlx_kv_quant_eligibility"),+ mlx_kv_quant_reason = model_info.get("mlx_kv_quant_reason"),+ mlx_kv_quant_note = model_info.get("mlx_kv_quant_note"),+ chat_template_override = model_info.get("chat_template_override_requested"),+ chat_template_override_reason = model_info.get("chat_template_override_reason"),loading = list(getattr(backend, "loading_models", set())),loaded = list(backend.models.keys()),inference = inference_config,diff --git a/studio/backend/routes/settings.py b/studio/backend/routes/settings.pyindex 542710710ee..5caf4a39700 100644--- a/studio/backend/routes/settings.py+++ b/studio/backend/routes/settings.py@@ -176,6 +176,8 @@ class ModelOverridePayload(BaseModel):max_seq_length: Optional[int] = Field(default = None, ge = 1, le = 1048576)custom_context_length: Optional[int] = Field(default = None, ge = 1, le = 1048576)kv_cache_dtype: Optional[str] = Field(default = None, max_length = 32)+ # A discrete set, enforced by the normalizer; these bounds only block absurd values.+ mlx_kv_bits: Optional[int] = Field(default = None, ge = 2, le = 8)speculative_type: Optional[str] = Field(default = None, max_length = 32)spec_draft_n_max: Optional[int] = Field(default = None, ge = 1, le = 16)# Parallel decode slots (llama-server --parallel), GGUF-only; None follows the server default.@@ -607,6 +609,7 @@ def update_openai_auto_switch_override(max_seq_length = payload.max_seq_length,custom_context_length = payload.custom_context_length,kv_cache_dtype = payload.kv_cache_dtype,+ mlx_kv_bits = payload.mlx_kv_bits,speculative_type = payload.speculative_type,spec_draft_n_max = payload.spec_draft_n_max,n_parallel = payload.n_parallel,diff --git a/studio/backend/tests/test_chat_history_routes.py b/studio/backend/tests/test_chat_history_routes.pyindex d59008cd76f..4b85bbc8ba5 100644--- a/studio/backend/tests/test_chat_history_routes.py+++ b/studio/backend/tests/test_chat_history_routes.py@@ -136,6 +136,31 @@ def test_chat_settings_payload_accepts_preset_load_config():assert dumped["customPresets"][0]["loadConfig"]["kvCacheDtype"] == "q8_0"+def test_chat_settings_payload_accepts_mlx_kv_bits():+ from pydantic import ValidationError++ # extra="forbid" rejects the whole settings write on an undeclared key.+ payload = chat_history.ChatSettingsPayload.model_validate(+ {+ "customPresets": [+ {+ "name": "MLX preset",+ "params": {"temperature": 0.7},+ "loadConfig": {"mlxKvBits": 8},+ },+ ],+ }+ )+ dumped = payload.model_dump(exclude_unset = True)+ assert dumped["customPresets"][0]["loadConfig"]["mlxKvBits"] == 8++ for width in (4, None):+ chat_history.ChatPresetLoadConfig.model_validate({"mlxKvBits": width})+ # Only the widths MLX supports.+ with pytest.raises(ValidationError):+ chat_history.ChatPresetLoadConfig.model_validate({"mlxKvBits": 7})++def test_chat_settings_payload_accepts_nudge_tool_calls():# extra="forbid" 400s PUT /api/chat/settings on unknown keys, so the# frontend's persisted nudgeToolCalls needs a payload field (likediff --git a/studio/backend/tests/test_gguf_load_cache_reuse.py b/studio/backend/tests/test_gguf_load_cache_reuse.pyindex 5df008f885f..84cea1d754a 100644--- a/studio/backend/tests/test_gguf_load_cache_reuse.py+++ b/studio/backend/tests/test_gguf_load_cache_reuse.py@@ -810,6 +810,42 @@ class TestLoadHubDownloadExclusion:with pytest.raises(AttributeError, match = "runtime response fields"):route._llama_runtime_fields(incomplete_backend)+ def test_real_backend_resolves_every_runtime_response_field(self):+ # The shipped class, not a fake: an unresolved field 500s every load and poll.+ from core.inference.llama_cpp import LlamaCppBackend+ from models.inference import _InferenceRuntimeFields++ route = _load_route_module(+ "inference_route_module_for_real_backend_projection_test",+ "routes/inference.py",+ )++ backend = LlamaCppBackend.__new__(LlamaCppBackend)+ backend.__init__()+ supplied = {+ "requires_trust_remote_code",+ "speculative_type",+ "requested_parallel_slots",+ "parallel_slots",+ "is_mlx",+ "mlx_kv_bits",+ "mlx_kv_bits_requested",+ "mlx_kv_quant_eligibility",+ "mlx_kv_quant_reason",+ "mlx_kv_quant_note",+ "chat_template_override_reason",+ }+ unresolved = sorted(+ name+ for name in _InferenceRuntimeFields.model_fields+ if name not in supplied and not (hasattr(backend, name) or hasattr(backend, f"_{name}"))+ )+ assert unresolved == []++ fields = route._llama_runtime_fields(backend)+ assert fields["is_mlx"] is False+ assert fields["mlx_kv_bits_requested"] is None+def test_in_flight_marker_counts_and_normalizes_case(self):assert not hf_gguf_load_in_flight(REPO)with gguf_load_in_flight(REPO):diff --git a/studio/backend/tests/test_mlx_inference_backend.py b/studio/backend/tests/test_mlx_inference_backend.pyindex c933a1e9ef9..0eff3b7208e 100644--- a/studio/backend/tests/test_mlx_inference_backend.py+++ b/studio/backend/tests/test_mlx_inference_backend.py@@ -1812,3 +1812,748 @@ def test_worker_forwards_use_adapter_on_the_audio_command():src = inspect.getsource(worker._handle_generate_audio_input)assert 'cmd.get("use_adapter")' in srcassert '"use_adapter"' in src+++def test_kv_quant_status_applies_only_when_eligible_and_notes_vlm_cost(monkeypatch):+ from core.inference import mlx_inference++ monkeypatch.setattr(+ mlx_inference, "_kv_quant_eligibility", lambda m, v, b = None: ("full", "", True)+ )+ # Unset stays unset: no kwarg, so generation is byte-identical to today.+ assert mlx_inference._kv_quant_status(None, object(), False)["kv_bits"] is None+ # Out of domain degrades rather than raising.+ assert mlx_inference._normalize_mlx_kv_bits(7) is None+ assert mlx_inference._normalize_mlx_kv_bits("eight") is None+ assert mlx_inference._normalize_mlx_kv_bits(8) == 8+ # Every width the runtime accepts is offered; mlx-lm adds no domain of its own.+ assert [mlx_inference._normalize_mlx_kv_bits(b) for b in (2, 3, 5, 6)] == [2, 3, 5, 6]++ text = mlx_inference._kv_quant_status(8, object(), False)+ vlm = mlx_inference._kv_quant_status(8, object(), True)+ assert text["kv_bits"] == 8 and not text["note"]+ # The threshold caveat rides with the resolved value, so an API client sees it.+ assert vlm["kv_bits"] == 8 and "vision models" in vlm["note"]+ assert str(mlx_inference._vlm_quantized_kv_start()) in vlm["note"]++ monkeypatch.setattr(+ mlx_inference,+ "_kv_quant_eligibility",+ lambda m, v, b = None: ("refused", "rotating cache", True),+ )+ refused = mlx_inference._kv_quant_status(8, object(), False)+ assert refused["kv_bits"] is None and refused["eligibility"] == "refused"+ assert refused["requested_kv_bits"] == 8 # what the reload decision compares+++def _tiny_lm(cache_factory, dim = 128):+ """Minimal model whose forward populates whatever cache it is given."""+ import mlx.core as mx++ class _LM:+ def make_cache(self):+ return cache_factory()++ def __call__(+ self,+ inputs,+ cache = None,+ ):+ for entry in cache or ():+ target = getattr(entry, "update_and_fetch", None)+ if target is not None:+ k = mx.zeros((1, 2, inputs.shape[1], dim))+ target(k, k)+ return mx.zeros((1, inputs.shape[1], 8))++ return _LM()+++def test_reload_comparison_and_response_carry_the_resolved_setting():+ """A load-time knob must force a reload and reach the client.++ Both were silently broken: the comparator tripped on a mirror key CUDA+ never stored, and the response fields sat on a request model.+ """+ from routes.inference import _mlx_runtime_settings_match+ from models.inference import LoadRequest, LoadResponse++ # The real request model, not a stand-in, so it stays in step with real loads.+ def req(**knobs):+ return LoadRequest(model = "m", model_path = "m", **knobs)++ be = SimpleNamespace(active_model_name = "m", models = {"m": {"mlx_kv_bits_requested": 8}})+ assert _mlx_runtime_settings_match(be, req(mlx_kv_bits = 8))+ assert not _mlx_runtime_settings_match(be, req(mlx_kv_bits = 4))+ be.models["m"] = {"mlx_kv_bits_requested": None}+ assert _mlx_runtime_settings_match(be, req(mlx_kv_bits = 7)) # both normalize away+ assert _mlx_runtime_settings_match(+ SimpleNamespace(active_model_name = "m", models = {"m": {}}),+ req(mlx_kv_bits = 8),+ )++ # Compared against the REQUESTED value, or a refused template reloads every request.+ be.models["m"] = {+ "mlx_kv_bits_requested": None,+ "chat_template_override_requested": "{{ custom }}",+ }+ assert _mlx_runtime_settings_match(be, req(chat_template_override = "{{ custom }}"))+ assert not _mlx_runtime_settings_match(be, req(chat_template_override = "{{ other }}"))+ assert not _mlx_runtime_settings_match(be, req())+ # A refusal records the request, so the same request still matches.+ be.models["m"] = {+ "mlx_kv_bits_requested": None,+ "chat_template_override_requested": "{{ refused }}",+ "chat_template_override_reason": "it could not render a conversation",+ }+ assert _mlx_runtime_settings_match(be, req(chat_template_override = "{{ refused }}"))++ resp = LoadResponse(+ status = "loaded",+ model = "m",+ display_name = "m",+ inference = {},+ mlx_kv_bits = 8,+ mlx_kv_quant_eligibility = "full",+ mlx_kv_quant_note = "n",+ )+ assert resp.mlx_kv_bits == 8 and resp.mlx_kv_quant_note == "n"+++def test_kv_quant_probe_reports_what_the_runtime_would_really_do(monkeypatch):+ """Attempt the conversion instead of predicting it from config or names.++ Static proxies were wrong both ways: a declared head_dim a model ignores,+ and windows spelled differently from `max_size`.+ """+ pytest.importorskip("mlx_lm")+ from mlx_lm.models import cache as lm_cache+ from core.inference import mlx_inference++ def elig(factory, dim = 128):+ lm = _tiny_lm(factory, dim)+ monkeypatch.setattr(lm_cache, "make_prompt_cache", lambda m, **_: lm.make_cache())+ return mlx_inference._kv_quant_eligibility(lm, False, 8)[0]++ assert elig(lambda: [lm_cache.KVCache(), lm_cache.KVCache()]) == "full"+ # A width mx.quantize rejects is caught by attempting it, not by naming it.+ assert elig(lambda: [lm_cache.KVCache()], dim = 80) == "refused"+ # A container the quantizer never descends into is skipped, not fatal.+ assert elig(lambda: [lm_cache.CacheList(lm_cache.KVCache())]) == "none"+ # Mixed quantizable/non-quantizable is a real success, reported as partial.+ assert elig(lambda: [lm_cache.KVCache(), lm_cache.CacheList(lm_cache.KVCache())]) == "partial"+++def test_parent_mirror_omits_runtime_fields_a_backend_never_reported():+ """A CUDA load must not gain a None the reload comparison then trips on."""+ from core.inference.orchestrator import _mlx_runtime_mirror_fields++ assert _mlx_runtime_mirror_fields({"is_vision": False}) == {}+ assert _mlx_runtime_mirror_fields(+ {"mlx_kv_bits": 8, "mlx_kv_bits_requested": 8, "other": 1}+ ) == {"mlx_kv_bits": 8, "mlx_kv_bits_requested": 8}+++def test_chat_template_override_installs_only_where_one_already_exists():+ """Replace a template; never create one.++ Both render selectors choose their target by whether a template is+ present, so creating one where there was none moves the render to a+ different object -- on the vision side, to one that never selects the+ tool_use variant.+ """+ from core.inference import mlx_inference++ tokenizer = SimpleNamespace(chat_template = "native")+ # A processor with no template of its own must be left alone, or+ # chat_render_target would start selecting it.+ processor = SimpleNamespace(chat_template = None, tokenizer = tokenizer)+ status = mlx_inference._install_template_override(+ "custom", tokenizer, processor, lambda: "rendered"+ )+ assert status["applied"] == "custom"+ assert tokenizer.chat_template == "custom"+ assert processor.chat_template is None++ # A processor that already renders from its own template receives it too.+ own = SimpleNamespace(chat_template = "native")+ owner = SimpleNamespace(chat_template = "native", tokenizer = own)+ mlx_inference._install_template_override("custom", own, owner, lambda: "ok")+ assert own.chat_template == "custom" and owner.chat_template == "custom"++ # Unset must not touch anything.+ untouched = SimpleNamespace(chat_template = "native")+ assert (+ mlx_inference._install_template_override(None, untouched, None, lambda: "")["applied"]+ is None+ )+ assert untouched.chat_template == "native"+++def test_chat_template_override_reports_each_way_it_cannot_apply():+ from core.inference import mlx_inference++ def reason(+ tok,+ proc = None,+ probe = lambda: "ok",+ ):+ return mlx_inference._install_template_override("custom", tok, proc, probe)["reason"]++ # mlx-lm holds the template as code and prefers it over the attribute.+ callable_tpl = SimpleNamespace(chat_template = "native", _chat_template = lambda: "x")+ assert reason(callable_tpl) == mlx_inference.MLX_TEMPLATE_CALLABLE++ # A named set would lose its tool_use variant if flattened to one string.+ assert reason(SimpleNamespace(chat_template = {"default": "a", "tool_use": "b"})) == (+ mlx_inference.MLX_TEMPLATE_NAMED_SET+ )++ # ...but only on the object that RENDERS. Real models (aya-vision) keep a named set+ # on a nested tokenizer nothing reads. Without apply_chat_template the processor+ # cannot render, so the nested tokenizer's set does veto.+ nested_set = SimpleNamespace(chat_template = {"default": "a"})+ renders_string = SimpleNamespace(+ chat_template = "native", apply_chat_template = lambda *a, **k: "", tokenizer = nested_set+ )+ targets, status = mlx_inference._template_override_status("custom", nested_set, renders_string)+ assert status["reason"] is None+ assert renders_string in targets and nested_set not in targets++ cannot_render = SimpleNamespace(chat_template = "native", tokenizer = nested_set)+ assert (+ mlx_inference._template_override_status("custom", nested_set, cannot_render)[1]["reason"]+ == mlx_inference.MLX_TEMPLATE_NAMED_SET+ )++ # The same for a callable held by an object that does not render.+ nested_callable = SimpleNamespace(chat_template = "t", _chat_template = lambda: "x")+ renders_own = SimpleNamespace(+ chat_template = "native",+ apply_chat_template = lambda *a, **k: "",+ tokenizer = nested_callable,+ )+ assert (+ mlx_inference._template_override_status("custom", nested_callable, renders_own)[1]["reason"]+ is None+ )++ # Nothing to replace, processor present: creating one takes the render from+ # mlx-vlm's fallback, which places the markers.+ bare = SimpleNamespace(chat_template = None)+ assert reason(bare, SimpleNamespace(chat_template = None, tokenizer = bare)) == (+ mlx_inference.MLX_TEMPLATE_NO_TARGET+ )++ # A text model has no selector to move and cannot chat without a template.+ for empty in (None, "", " "):+ blank = SimpleNamespace(chat_template = empty)+ targets, status = mlx_inference._template_override_status("custom", blank, None)+ assert status["reason"] is None, empty+ assert targets == [blank]++ # The probe turns invalid Jinja into one load-time reason, and restores the original.+ broken = SimpleNamespace(chat_template = "native")+ got = reason(broken, probe = lambda: (_ for _ in ()).throw(ValueError("bad tag")))+ assert "could not render" in got and "bad tag" in got+ assert broken.chat_template == "native"+++def test_chat_template_override_crosses_both_ipc_hops():+ """The backend runs in a subprocess; the parent rebuilds its entry from an+ enumerated key set at each hop, and /status and the reload check read the+ parent's copy."""+ import inspect++ from core.inference import orchestrator, worker+ from models.inference import LoadRequest++ assert (+ "chat_template_override"+ in inspect.signature(orchestrator.InferenceOrchestrator.load_model).parameters+ )+ orch = inspect.getsource(orchestrator.InferenceOrchestrator.load_model)+ assert '"chat_template_override": chat_template_override' in orch++ # The applied value is not carried: /status and the reload decision key on requested.+ reported = (+ "chat_template_override_requested",+ "chat_template_override_reason",+ )+ worker_source = inspect.getsource(worker)+ # Whole statements, not name presence: each name is a prefix of another here.+ assert (+ 'load_kwargs["chat_template_override"] = config.get(\n'+ ' "chat_template_override"\n'+ " )"+ in worker_source+ or 'load_kwargs["chat_template_override"] = config.get("chat_template_override")'+ in worker_source+ )+ for name in reported:+ assert f'"{name}",' in worker_source+ assert [n for n in reported if n not in orchestrator._MLX_RUNTIME_MIRROR_FIELDS] == []+ assert "chat_template_override" in LoadRequest.model_fields+++def test_template_probe_renders_through_the_path_generation_uses(monkeypatch):+ """The probe must exercise the real renderer, and reject an empty prompt.++ Rendering through the VLM recovery renderer instead would pass for a model+ outside mlx-vlm's family list, because that helper returns None rather than+ raising -- so an unrenderable template would be recorded as applied and+ then throw on every generation.+ """+ from core.inference import mlx_inference++ seen = {}++ def fake_render(target, messages, **kwargs):+ seen["target"] = target+ tpl = getattr(target, "chat_template", None)+ if tpl == "empty":+ return ""+ # Whitespace only, which the vision path also treats as an empty prompt.+ return " \n " if tpl == "blank" else "rendered"++ monkeypatch.setattr(+ "core.inference.chat_template_helpers.apply_chat_template_for_generation",+ fake_render,+ )+ backend = mlx_inference.MLXInferenceBackend.__new__(mlx_inference.MLXInferenceBackend)++ # Text: the tokenizer is the render target.+ backend._tokenizer = SimpleNamespace(chat_template = "t")+ backend._processor = None+ assert backend._render_template_probe(False) == "rendered"+ assert seen["target"] is backend._tokenizer++ # Vision: whatever chat_render_target selects, not the recovery renderer.+ nested = SimpleNamespace(chat_template = "t")+ processor = SimpleNamespace(+ chat_template = "own", tokenizer = nested, apply_chat_template = lambda *a, **k: ""+ )+ backend._tokenizer = nested+ backend._processor = processor+ backend._render_template_probe(True)+ assert seen["target"] is processor++ # A template that renders nothing is a failure, not a pass.+ for empty in ("empty", "blank"):+ backend._tokenizer = SimpleNamespace(chat_template = empty)+ backend._processor = None+ with pytest.raises(ValueError):+ backend._render_template_probe(False)+++def test_the_audio_refusal_puts_the_native_template_back(monkeypatch):+ """The refusal itself, not just the marker check.++ Capability was classified against the native template, so an override that+ stops marking audio has to be undone -- otherwise the model keeps+ advertising an input it can no longer place.+ """+ from core.inference import mlx_inference++ marks = {"audio": False}+ monkeypatch.setattr(+ mlx_inference,+ "_render_registered_vlm_prompt",+ lambda p, m, msgs, imgs, num_audios = 0: (+ "<audio> hi" if num_audios and marks["audio"] else "hi"+ ),+ )+ tok = SimpleNamespace(chat_template = "custom")+ status = {+ "requested": "custom",+ "applied": "custom",+ "reason": None,+ "restore": [(tok, "native")],+ }+ mlx_inference._revoke_override_that_drops_audio(status, object(), object())+ assert status["applied"] is None+ assert status["reason"] == mlx_inference.MLX_TEMPLATE_DROPS_AUDIO+ assert tok.chat_template == "native", "the model must be left as if unset"+ assert status["restore"] == []++ # An override that keeps the marker is left alone.+ marks["audio"] = True+ kept = SimpleNamespace(chat_template = "custom")+ keep = {+ "requested": "custom",+ "applied": "custom",+ "reason": None,+ "restore": [(kept, "native")],+ }+ mlx_inference._revoke_override_that_drops_audio(keep, object(), object())+ assert keep["applied"] == "custom" and kept.chat_template == "custom"++ # Nothing installed: no reason invented even when the marker is absent.+ marks["audio"] = False+ unset = {"requested": None, "applied": None, "reason": None, "restore": []}+ mlx_inference._revoke_override_that_drops_audio(unset, object(), object())+ assert unset["reason"] is None+++def test_a_created_template_is_not_reported_as_the_model_default():+ """A model that shipped no template must keep reporting none.++ The override is installed on the tokenizer for text models, so reading the+ live object back would report the user's own template as the model's+ default -- which makes the editor treat it as the default and clear it on+ the next save, leaving the model unchattable again.+ """+ from core.inference import mlx_inference++ backend = mlx_inference.MLXInferenceBackend.__new__(mlx_inference.MLXInferenceBackend)+ tokenizer = SimpleNamespace(chat_template = None)+ backend.models = {"m": {"tokenizer": tokenizer, "processor": None}}++ # What load_model does: capture first, install, then record.+ native = getattr(tokenizer, "chat_template", None)+ tokenizer.chat_template = "{{ user_supplied }}"+ backend._populate_chat_template_info("m", native)++ info = backend.models["m"]["chat_template_info"]+ assert info["template"] is None, "the override is not the model's template"+ assert info["has_template"] is False++ # A model that did ship one still reports its own, not the override.+ shipped = SimpleNamespace(chat_template = "{{ native }}")+ backend.models["n"] = {"tokenizer": shipped, "processor": None}+ native = getattr(shipped, "chat_template", None)+ shipped.chat_template = "{{ user_supplied }}"+ backend._populate_chat_template_info("n", native)+ assert backend.models["n"]["chat_template_info"]["template"] == "{{ native }}"++ # Called without a capture at all, it still reads the live object.+ plain = SimpleNamespace(chat_template = "{{ live }}")+ backend.models["o"] = {"tokenizer": plain, "processor": None}+ backend._populate_chat_template_info("o")+ assert backend.models["o"]["chat_template_info"]["template"] == "{{ live }}"+++def _marker_renderer(monkeypatch, marks_image):+ """Stand in for the real render: only marks_image=True reacts to an image part."""++ def render(target, messages, **kwargs):+ parts = messages[0]["content"]+ text = "".join(p["text"] for p in parts if p["type"] == "text")+ images = sum(1 for p in parts if p["type"] == "image")+ return f"<img>{text}" if (marks_image and images) else text++ monkeypatch.setattr(+ "core.inference.chat_template_helpers.apply_chat_template_for_generation", render+ )+++def test_an_override_that_stops_marking_images_is_revoked(monkeypatch):+ """A text-only probe renders fine while the image placeholder is gone.++ The failure would otherwise land on the first image request, inside a+ processor that counts markers against image features.+ """+ from core.inference import mlx_inference++ processor = SimpleNamespace(+ chat_template = "{{ native }}",+ apply_chat_template = lambda *a, **k: "",+ tokenizer = SimpleNamespace(chat_template = "{{ nested }}"),+ )+ tokenizer = processor.tokenizer++ _marker_renderer(monkeypatch, marks_image = True)+ assert mlx_inference._image_marker_survives(tokenizer, processor) is True++ status = mlx_inference._install_template_override(+ "{{ blind }}", tokenizer, processor, lambda: None+ )+ assert status["applied"] == "{{ blind }}"++ # The override renders text but never places the image.+ _marker_renderer(monkeypatch, marks_image = False)+ mlx_inference._revoke_override_that_drops_image(status, tokenizer, processor)+ assert status["applied"] is None+ assert status["reason"] == mlx_inference.MLX_TEMPLATE_DROPS_IMAGE+ assert processor.chat_template == "{{ native }}"+ assert tokenizer.chat_template == "{{ nested }}"+++def test_an_override_that_keeps_the_image_marker_is_left_alone(monkeypatch):+ from core.inference import mlx_inference++ processor = SimpleNamespace(+ chat_template = "{{ native }}",+ apply_chat_template = lambda *a, **k: "",+ tokenizer = SimpleNamespace(chat_template = "{{ nested }}"),+ )+ _marker_renderer(monkeypatch, marks_image = True)+ status = mlx_inference._install_template_override(+ "{{ good }}", processor.tokenizer, processor, lambda: None+ )+ mlx_inference._revoke_override_that_drops_image(status, processor.tokenizer, processor)+ assert status["applied"] == "{{ good }}"+ assert processor.chat_template == "{{ good }}"+++def test_the_model_default_comes_from_the_object_that_renders():+ """A processor owning its own template is what generation reads.++ Reporting the nested tokenizer's instead lets "reset to default" install the+ tokenizer's template over the processor, losing its media and tool variants.+ """+ from core.inference import mlx_inference++ nested = SimpleNamespace(chat_template = "{{ nested }}")+ processor = SimpleNamespace(+ chat_template = "{{ processor }}",+ apply_chat_template = lambda *a, **k: "",+ tokenizer = nested,+ )+ assert mlx_inference._native_template_source(nested, processor) is processor++ # No processor template: the nested tokenizer is both render target and default.+ bare = SimpleNamespace(chat_template = None, tokenizer = nested)+ assert mlx_inference._native_template_source(nested, bare) is nested++ # A named set renders but is not an editable default, so report the nested string.+ named = SimpleNamespace(+ chat_template = {"default": "{{ a }}"},+ apply_chat_template = lambda *a, **k: "",+ tokenizer = nested,+ )+ assert mlx_inference._native_template_source(nested, named) is nested++ # Text model: no processor at all.+ assert mlx_inference._native_template_source(nested, None) is nested+++def test_template_targets_follow_the_object_that_can_actually_render():+ """A processor holding a template it cannot render with is not the target.++ chat_render_target falls back to the nested tokenizer there, so judging+ eligibility against the processor would install onto an object nothing+ reads and then pass a probe rendered from the untouched native template.+ """+ from core.inference import mlx_inference++ nested = SimpleNamespace(chat_template = "{{ nested }}")+ # chat_template but no apply_chat_template: it cannot render.+ unrenderable = SimpleNamespace(chat_template = "{{ processor }}", tokenizer = nested)+ assert mlx_inference._template_render_targets(nested, unrenderable) == [nested]++ renderable = SimpleNamespace(+ chat_template = "{{ processor }}",+ apply_chat_template = lambda *a, **k: "",+ tokenizer = nested,+ )+ assert mlx_inference._template_render_targets(nested, renderable) == [renderable]+ assert mlx_inference._template_render_targets(nested, None) == [nested]++ # A named set on the unusable target still reports the nested string.+ named = SimpleNamespace(+ chat_template = {"default": "{{ a }}"},+ apply_chat_template = lambda *a, **k: "",+ tokenizer = nested,+ )+ assert mlx_inference._native_template_source(nested, named) is nested+++def test_an_entry_the_upstream_lru_cannot_size_is_not_retainable(monkeypatch):+ """Upstream LRUPromptCache.insert_cache sums entry.nbytes itself.++ So an mlx-lm whose QuantizedKVCache.nbytes raises cannot admit the entry+ however else it could be measured, and measuring it another way here would+ drop the no-reuse caveat while every quantized turn still failed to insert.+ """+ from core.inference import mlx_inference++ class _Broken:+ state = ()+ keys = SimpleNamespace(nbytes = 64)+ values = SimpleNamespace(nbytes = 64)++ @property+ def nbytes(self):+ raise NameError("tree_reduce")++ assert mlx_inference._kv_entry_nbytes(_Broken()) is None+ assert mlx_inference._kv_entry_nbytes(SimpleNamespace(nbytes = 128)) == 128++ _install_fake_mlx(monkeypatch)+ mx = sys.modules["mlx.core"]+ mx.random = SimpleNamespace(state = [0])+ mx.array = lambda v: v+ mx.eval = lambda *a: None+ mx.clear_cache = lambda: None++ def probe(quantized):+ entry = SimpleNamespace(+ to_quantized = lambda group_size, bits: quantized,+ max_size = None,+ window_size = None,+ state = (),+ )+ return mlx_inference._kv_quant_probe(lambda *a, **k: None, [entry], 8)++ converted, skipped, failure, retainable = probe(_Broken())+ assert (converted, skipped, failure) == (1, 0, None)+ assert retainable is False++ # A working property is retainable, so the caveat is not blanket.+ assert probe(SimpleNamespace(state = (), nbytes = 128))[3] is True+++def test_a_successful_override_does_not_pin_the_tokenizer_past_load(monkeypatch):+ """The restore pairs hold the tokenizer, so unload_model cannot free it.++ Nothing reads them once the audio and image checks have run, and the worker+ outlives the model, so holding them defeats part of what unload releases.+ """+ _install_fake_mlx(monkeypatch)+ _install_fake_fast_mlx(monkeypatch, [])+ # A text model with no template of its own is the one case an override may create.+ monkeypatch.setattr(_DummyTokenizer, "chat_template", None, raising = False)+ monkeypatch.setattr(+ "core.inference.chat_template_helpers.apply_chat_template_for_generation",+ lambda target, messages, **kwargs: "rendered",+ )+ from core.inference.mlx_inference import MLXInferenceBackend++ backend = MLXInferenceBackend()+ config = SimpleNamespace(identifier = "fake/text", is_vision = False, is_lora = False)+ assert backend.load_model(config, chat_template_override = "{{ custom }}")++ status = backend._template_override+ assert status["applied"] == "{{ custom }}"+ assert status["restore"] == []+ assert backend._tokenizer.chat_template == "{{ custom }}"+++def test_an_override_that_renders_the_image_as_prose_is_not_a_marker(monkeypatch):+ """A difference between the two probes is not proof of a placeholder.++ A template emitting "Image attached", or the content dict itself, renders+ differently from the text-only probe while placing nothing the processor+ can bind the image to.+ """+ from core.inference import mlx_inference++ nested = SimpleNamespace(chat_template = "{{ nested }}")+ processor = SimpleNamespace(+ chat_template = "{{ native }}",+ apply_chat_template = lambda *a, **k: "",+ tokenizer = nested,+ image_token = "<|image_pad|>",+ )+ assert mlx_inference._image_placeholder(nested, processor) == "<|image_pad|>"++ def render_as(text_for_image):+ def render(target, messages, **kwargs):+ parts = messages[0]["content"]+ text = "".join(p["text"] for p in parts if p["type"] == "text")+ images = sum(1 for p in parts if p["type"] == "image")+ return (text_for_image * images) + text++ monkeypatch.setattr(+ "core.inference.chat_template_helpers.apply_chat_template_for_generation", render+ )++ survives = lambda: mlx_inference._image_marker_survives(nested, processor, "<|image_pad|>")++ render_as("<|image_pad|>")+ assert survives() is True++ # Differs from the text-only render, but places no placeholder.+ render_as("Image attached. ")+ assert survives() is False++ # Ignores the image entirely.+ render_as("")+ assert survives() is False++ # Emits the structured content object, which _vlm_prompt_issue already names.+ render_as(str({"type": "image"}))+ assert survives() is False++ # A model naming no placeholder still gets the weaker difference test.+ del processor.image_token+ assert mlx_inference._image_placeholder(nested, processor) is None+ render_as("Image attached. ")+ assert mlx_inference._image_marker_survives(nested, processor, None) is True+++def test_the_load_response_declares_every_runtime_field_status_reports():+ """A field only /status declares is silently dropped from a load response.++ Pydantic ignores an extra keyword, so a route can construct the echo and+ the client still sees nothing, with no error anywhere to notice it by.+ """+ from models.inference import (+ InferenceStatusResponse,+ LoadResponse,+ _InferenceRuntimeFields,+ )++ shared = set(_InferenceRuntimeFields.model_fields)+ runtime = {+ name+ for name in InferenceStatusResponse.model_fields+ if name.startswith(("mlx_", "chat_template_override")) or name == "is_mlx"+ }+ assert runtime <= shared, f"declared on status only: {sorted(runtime - shared)}"+ assert runtime <= set(LoadResponse.model_fields)++ loaded = LoadResponse(+ success = True,+ status = "loaded",+ model = "m",+ display_name = "m",+ inference = {},+ chat_template_override = "{{ custom }}",+ chat_template_override_reason = "why",+ )+ assert loaded.model_dump()["chat_template_override"] == "{{ custom }}"+++def test_a_vision_override_is_checked_even_when_the_native_render_needs_recovery(monkeypatch):+ """Gating the check on the native template skipped the models that need it.++ A native template that places nothing still renders images, because+ _generate_vlm falls back to the registered renderer once _vlm_prompt_issue+ fires. An override rendering plain text fires nothing, so the image goes+ unplaced with no error, and recovery is unavailable anyway once tools or+ reasoning controls are set.+ """+ _install_fake_mlx(monkeypatch)+ _install_fake_fast_mlx(monkeypatch, [])+ monkeypatch.setattr(_DummyProcessor, "chat_template", "{{ native }}", raising = False)+ monkeypatch.setattr(_DummyProcessor, "apply_chat_template", lambda *a, **k: "", raising = False)+ monkeypatch.setattr(_DummyTokenizer, "chat_template", "{{ nested }}", raising = False)++ def render(target, messages, **kwargs):+ # The native template serializes the content dict, so it only works via recovery.+ content = messages[0]["content"]+ if isinstance(content, str):+ return content+ text = "".join(p["text"] for p in content if p["type"] == "text")+ images = [p for p in content if p["type"] == "image"]+ if getattr(target, "chat_template", None) == "{{ blind }}":+ return text+ return "".join(str(p) for p in images) + text++ monkeypatch.setattr(+ "core.inference.chat_template_helpers.apply_chat_template_for_generation", render+ )+ from core.inference import mlx_inference++ # The native template fails the check, which used to skip the override's.+ assert mlx_inference._image_marker_survives(_DummyTokenizer(), _DummyProcessor(), None) is False++ backend = mlx_inference.MLXInferenceBackend()+ config = SimpleNamespace(identifier = "fake/vlm", is_vision = True, is_lora = False)+ assert backend.load_model(config, chat_template_override = "{{ blind }}")++ assert backend._template_override["applied"] is None+ assert backend._template_override["reason"] == mlx_inference.MLX_TEMPLATE_DROPS_IMAGE+ assert backend._processor.chat_template == "{{ native }}"diff --git a/studio/backend/tests/test_openai_auto_switch.py b/studio/backend/tests/test_openai_auto_switch.pyindex 3c48da7ac05..a0788f1ded7 100644--- a/studio/backend/tests/test_openai_auto_switch.py+++ b/studio/backend/tests/test_openai_auto_switch.py@@ -6842,3 +6842,21 @@ def test_two_spellings_of_one_cached_quant_do_not_delete_each_others_save(monkeystored = settings.get_model_overrides()assert list(stored) in ([repo], [snapshot]), storedassert stored[list(stored)[0]]["max_seq_length"] in (4096, 8192)+++def test_mlx_kv_bits_survives_the_whole_override_projection():+ # Dropped here, an API auto-switch would load a remembered MLX model at full+ # precision while the picker honored the width.+ for bits in (8, 6, 5, 4, 3, 2):+ assert settings.normalize_model_override({"mlx_kv_bits": bits}) == {"mlx_kv_bits": bits}++ # A discrete set, so an in-range width can still be one mx.quantize rejects.+ # bool is an int subclass, and a string width would reach LoadRequest untyped.+ for rejected in (7, 1, 0, 9, True, False, "4", 4.5, None):+ assert settings.normalize_model_override({"mlx_kv_bits": rejected}) == {}++ # Ungated on is_gguf, matching the picker's own load payload.+ for is_gguf in (True, False):+ kwargs = settings.model_override_load_kwargs({"mlx_kv_bits": 4}, is_gguf = is_gguf)+ assert kwargs["mlx_kv_bits"] == 4+ assert LoadRequest(model_path = "unsloth/A", **kwargs).mlx_kv_bits == 4diff --git a/studio/backend/utils/openai_auto_switch_settings.py b/studio/backend/utils/openai_auto_switch_settings.pyindex fbd54629d1f..09c35dd6e94 100644--- a/studio/backend/utils/openai_auto_switch_settings.py+++ b/studio/backend/utils/openai_auto_switch_settings.py@@ -279,6 +279,8 @@ VALID_SPECULATIVE_TYPES = frozenset(# Only these consume spec_draft_n_max (mirrors DRAFT_N_MAX_SPEC_TYPES in the UI).DRAFT_N_MAX_SPEC_TYPES = frozenset({"mtp", "mtp+ngram", "draft-mtp", "dspark", "draft-dspark"})VALID_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})# Mirrors PARALLEL_MIN/MAX in llama_server_args.py. Mirrored not imported: that module owns# the extra-args allow-list this one must stay out of.@@ -340,6 +342,11 @@ def normalize_model_override(payload: dict[str, Any]) -> dict[str, Any]:if kv_cache_dtype:entry["kv_cache_dtype"] = kv_cache_dtype+ # MLX quantizes by bit width, not by a llama.cpp dtype name, so it is its own field.+ mlx_kv_bits = payload.get("mlx_kv_bits")+ if not isinstance(mlx_kv_bits, bool) and mlx_kv_bits in VALID_MLX_KV_BITS:+ entry["mlx_kv_bits"] = int(mlx_kv_bits)+speculative_type = _clean_str(payload.get("speculative_type"), VALID_SPECULATIVE_TYPES)if speculative_type:entry["speculative_type"] = speculative_type@@ -439,6 +446,8 @@ def model_override_load_kwargs(override: dict[str, Any], *, is_gguf: bool) -> difor source, target in (("llama_extra_args", "llama_extra_args"),("kv_cache_dtype", "cache_type_kv"),+ # Ungated like the UI's own load payload: non-MLX backends ignore it.+ ("mlx_kv_bits", "mlx_kv_bits"),("speculative_type", "speculative_type"),("spec_draft_n_max", "spec_draft_n_max"),("tensor_parallel", "tensor_parallel"),diff --git a/studio/frontend/src/features/chat/api/chat-adapter.ts b/studio/frontend/src/features/chat/api/chat-adapter.tsindex fb0116e3234..3fafca43458 100644--- a/studio/frontend/src/features/chat/api/chat-adapter.ts+++ b/studio/frontend/src/features/chat/api/chat-adapter.ts@@ -1,6 +1,7 @@// SPDX-License-Identifier: AGPL-3.0-only// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0+import { mlxRuntimeStateFrom } from "../lib/mlx-runtime-state";import { getAuthToken } from "@/features/auth";import { prepareHfTokenForUse } from "@/features/hf-auth";import { resolveInitialConfig } from "@/features/model-picker";@@ -1747,6 +1748,13 @@ const VISIBLE_MODEL_RUNTIME_KEYS = ["defaultChatTemplate","chatTemplateOverride","loadedChatTemplateOverride",+ "chatTemplateOverrideReason",+ // The rest of the group mlxRuntimeStateFrom writes, or a background autoload+ // leaves its width and verdict on the restored model.+ "mlxKvBits",+ "loadedMlxKvBitsRequested",+ "mlxKvQuantReason",+ "mlxKvQuantNote","loadedIsMultimodal","loadedIsDiffusion","speculativeType",@@ -2145,6 +2153,7 @@ async function autoLoadSmallestModel(options?: AutoLoadOptions): Promise<{trust_remote_code: trustRemoteCode,chat_template_override: effectiveChatTemplateOverride,cache_type_kv: config.kvCacheDtype,+ mlx_kv_bits: config.mlxKvBits ?? null,speculative_type: effectiveSpeculativeType,spec_draft_n_max: effectiveSpecDraftNMax,tensor_parallel: effectiveTensorParallel,@@ -2248,6 +2257,7 @@ async function autoLoadSmallestModel(options?: AutoLoadOptions): Promise<{...resolveToolsEnabledOnLoad(loadResp.supports_tools ?? false),kvCacheDtype: loadResp.cache_type_kv ?? null,loadedKvCacheDtype: loadResp.cache_type_kv ?? null,+ ...mlxRuntimeStateFrom(loadResp),// Click-time value, not the resolved backend echo (see performLoad).nParallel: committedSlots,loadedNParallel: committedSlots,@@ -2278,6 +2288,7 @@ async function autoLoadSmallestModel(options?: AutoLoadOptions): Promise<{...resolveToolsEnabledOnLoad(loadResp.supports_tools ?? false),kvCacheDtype: loadResp.cache_type_kv ?? null,loadedKvCacheDtype: loadResp.cache_type_kv ?? null,+ ...mlxRuntimeStateFrom(loadResp),// GGUF-only and never sent here: a staged override would be saved for// a model that cannot use it.nParallel: null,@@ -2602,6 +2613,7 @@ async function autoLoadSmallestModel(options?: AutoLoadOptions): Promise<{...resolveToolsEnabledOnLoad(loadResp.supports_tools ?? false),kvCacheDtype: loadResp.cache_type_kv ?? null,loadedKvCacheDtype: loadResp.cache_type_kv ?? null,+ ...mlxRuntimeStateFrom(loadResp),// The request above omits n_parallel: a staged override left from a// preset would read as applied and be re-sent by the next Apply.nParallel: null,diff --git a/studio/frontend/src/features/chat/chat-settings-sheet.tsx b/studio/frontend/src/features/chat/chat-settings-sheet.tsxindex 7817734fff5..84acbe34b48 100644--- a/studio/frontend/src/features/chat/chat-settings-sheet.tsx+++ b/studio/frontend/src/features/chat/chat-settings-sheet.tsx@@ -42,7 +42,12 @@ import { Slider } from "@/components/ui/slider";import { Switch } from "@/components/ui/switch";import { Textarea } from "@/components/ui/textarea";import { Tooltip, TooltipContent } from "@/components/ui/tooltip";-import { NumericValueInput, snapToStep } from "@/features/model-picker";+import { usePlatformStore } from "@/config/env";+import {+ NumericValueInput,+ presetLoadSettingNames,+ snapToStep,+} from "@/features/model-picker";import { RetrievalSettingsSection } from "@/features/rag";import { useLlamaUpdateCheck } from "@/hooks/use-llama-update-check";import {@@ -486,6 +491,13 @@ export function ChatSettingsPanel({isLoadedGguf ||ggufContextLength != null ||(currentCheckpoint?.toLowerCase().endsWith(".gguf") ?? false);+ const platformDeviceType = usePlatformStore((s) => s.deviceType);+ const platformChatOnlyReason = usePlatformStore((s) => s.chatOnlyReason);+ const loadSettingNames = presetLoadSettingNames(+ isGguf,+ platformDeviceType,+ platformChatOnlyReason,+ );// activeModelIsLocal is the backend's own classification and covers native// picks. Two things must not decide this: activeNativePathToken, which// status reconciliation keeps across a switch to a remote GGUF (no@@ -498,6 +510,7 @@ export function ChatSettingsPanel({);const customContextLength = useChatRuntimeStore((s) => s.customContextLength);const kvCacheDtype = useChatRuntimeStore((s) => s.kvCacheDtype);+ const mlxKvBits = useChatRuntimeStore((s) => s.mlxKvBits);const gpuMemoryMode = useChatRuntimeStore((s) => s.gpuMemoryMode);const gpuLayers = useChatRuntimeStore((s) => s.gpuLayers);const nCpuMoe = useChatRuntimeStore((s) => s.nCpuMoe);@@ -629,6 +642,7 @@ export function ChatSettingsPanel({customContextLength,ggufContextLength,kvCacheDtype,+ mlxKvBits,gpuMemoryMode,gpuLayers,nCpuMoe,@@ -648,6 +662,7 @@ export function ChatSettingsPanel({customContextLength,ggufContextLength,kvCacheDtype,+ mlxKvBits,gpuMemoryMode,gpuLayers,nCpuMoe,@@ -980,8 +995,8 @@ export function ChatSettingsPanel({label="Preset"headerAction={<InfoHint>- Saving a preset also stores current load settings (context length,- KV cache dtype, speculative decoding, GPU layers).+ Saving a preset also stores current load settings (+ {loadSettingNames}).{currentLoadSummary ? (<>{" "}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 7a5063f4c5d..342facfcdd0 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@@ -1,6 +1,7 @@// SPDX-License-Identifier: AGPL-3.0-only// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0+import { mlxRuntimeStateFrom } from "../lib/mlx-runtime-state";import { createElement, useCallback, useRef, useState } from "react";import { toast } from "@/lib/toast";import { confirmRemoteCodeIfNeeded } from "@/features/security";@@ -778,6 +779,11 @@ export function useChatModelRuntime() {typeof selection !== "string" && selection.previousConfig? (selection.previousConfig.nParallel ?? null): useChatRuntimeStore.getState().nParallel;+ // Same reason: the rollback echo would overwrite an edit staged against it.+ const previousMlxKvBits =+ typeof selection !== "string" && selection.previousConfig+ ? (selection.previousConfig.mlxKvBits ?? null)+ : useChatRuntimeStore.getState().mlxKvBits;if (isGguf && isDiffusion === undefined) {// Prepare the token exactly as validateModel/loadModel do (and as// the compare path does): the Hub rejects an invalid Authorization@@ -850,12 +856,16 @@ export function useChatModelRuntime() {// (validation, the trust dialog, unload). When the picker staged a// config payload, prefer it over the store: React may not have// flushed NumericValueInput's blur commit into state yet.- const loadChatTemplateOverride =+ // Per-model: a template is written against one model's tokens.+ let loadChatTemplateOverride =pendingLoadConfig?.chatTemplateOverride?.trim()? pendingLoadConfig.chatTemplateOverride: stateBeforeUnload.chatTemplateOverride;const loadKvCacheDtype =pendingLoadConfig?.kvCacheDtype ?? stateBeforeUnload.kvCacheDtype;+ // Per-model, not a standing preference: eligibility is decided per model.+ let loadMlxKvBits =+ pendingLoadConfig?.mlxKvBits ?? stateBeforeUnload.mlxKvBits;// gpuMemoryMode is a standing preference (kept across a model switch);// the rest are per-model knobs the reset below clears, so they are// re-baselined there in lock-step with the store.@@ -1084,6 +1094,13 @@ export function useChatModelRuntime() {: persistedSpeculativeType;loadSpecDraftNMax = pendingLoadConfig?.specDraftNMax ?? null;loadNParallel = pendingLoadConfig?.nParallel ?? 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;+ loadChatTemplateOverride =+ pendingLoadConfig?.chatTemplateOverride?.trim()+ ? pendingLoadConfig.chatTemplateOverride+ : null;// Keep the click-time snapshot in lock-step with the store reset so// the load below sizes against the cleared per-model knobs, not the// previous model's (gpuMemoryMode is standing, so left as captured).@@ -1156,6 +1173,7 @@ export function useChatModelRuntime() {approved_remote_code_fingerprint: approvedRemoteCodeFingerprint,chat_template_override: effectiveChatTemplateOverride,cache_type_kv: loadKvCacheDtype,+ mlx_kv_bits: loadMlxKvBits ?? null,speculative_type: loadSpeculativeType,spec_draft_n_max: loadSpecDraftNMax,// GGUF-only: slots mean nothing for a transformers load.@@ -1303,6 +1321,7 @@ export function useChatModelRuntime() {: resolveToolsEnabledOnLoad(supportsTools)),kvCacheDtype: loadedKv,loadedKvCacheDtype: loadedKv,+ ...mlxRuntimeStateFrom(loadResponse),tensorParallel: loadedTp,loadedTensorParallel: loadedTp,...loadedGpuMemoryFields(loadResponse),@@ -1419,6 +1438,7 @@ export function useChatModelRuntime() {chat_template_override:stateBeforeUnload.loadedChatTemplateOverride,cache_type_kv: stateBeforeUnload.loadedKvCacheDtype,+ mlx_kv_bits: stateBeforeUnload.loadedMlxKvBitsRequested,speculative_type:stateBeforeUnload.loadedSpeculativeType,spec_draft_n_max:@@ -1459,6 +1479,10 @@ export function useChatModelRuntime() {loadedSpecDraftNMax:rollbackResponse.spec_draft_n_max ?? null,loadedKvCacheDtype: rollbackResponse.cache_type_kv ?? null,+ ...mlxRuntimeStateFrom(rollbackResponse),+ // After the spread, which seeds the control from the echo; the+ // control keeps its intent, like nParallel above.+ mlxKvBits: previousMlxKvBits,loadedChatTemplateOverride:stateBeforeUnload.loadedChatTemplateOverride,...loadedGpuMemoryFields(rollbackResponse),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 734e792508b..3238a8ee4ec 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@@ -354,6 +354,43 @@ export function applyActiveModelStatusToStore(tensorParallel: status.tensor_parallel,loadedTensorParallel: status.tensor_parallel,}),+ // Hydration only, so a steady poll never rewrites settings the store owns.+ // Width, verdict and request move together; a late reply can overwrite a newer one.+ ...(seedLoadParams &&+ hydratingExistingModel &&+ status.mlx_kv_bits !== undefined &&+ (status.is_mlx === true+ ? {+ mlxKvBits: status.mlx_kv_bits_requested ?? null,+ loadedMlxKvBitsRequested: status.mlx_kv_bits_requested ?? null,+ mlxKvQuantReason: status.mlx_kv_quant_reason ?? null,+ chatTemplateOverrideReason:+ status.chat_template_override_reason ?? null,+ mlxKvQuantNote: status.mlx_kv_quant_note ?? null,+ }+ : {+ // The verdict retires; the editable width is dormant, not wrong.+ loadedMlxKvBitsRequested: null,+ mlxKvQuantReason: null,+ chatTemplateOverrideReason: null,+ mlxKvQuantNote: null,+ })),+ // Recovery for a hydration this tab never saw, and only when nothing is+ // staged: re-seeding over an earlier edit would discard it.+ ...(seedLoadParams &&+ !hydratingExistingModel &&+ status.is_mlx === true &&+ status.mlx_kv_bits !== undefined &&+ prevState.mlxKvBits === null &&+ prevState.loadedMlxKvBitsRequested === null &&+ prevState.mlxKvQuantReason === null &&+ prevState.chatTemplateOverrideReason === null && {+ mlxKvBits: status.mlx_kv_bits_requested ?? null,+ loadedMlxKvBitsRequested: status.mlx_kv_bits_requested ?? null,+ mlxKvQuantReason: status.mlx_kv_quant_reason ?? null,+ chatTemplateOverrideReason: status.chat_template_override_reason ?? null,+ mlxKvQuantNote: status.mlx_kv_quant_note ?? null,+ }),// Baseline only, never the control: the echo is the RESOLVED count and would// pin a blank "server default" control. The rollback re-sends the baseline,// so without this a rollback after a tab reload loses the override.diff --git a/studio/frontend/src/features/chat/lib/mlx-runtime-state.ts b/studio/frontend/src/features/chat/lib/mlx-runtime-state.tsnew file mode 100644index 00000000000..b9278f2bdab--- /dev/null+++ b/studio/frontend/src/features/chat/lib/mlx-runtime-state.ts@@ -0,0 +1,43 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import type { LoadModelResponse } from "../types/api";++type MlxRuntimeResponse = Pick<+ LoadModelResponse,+ | "is_mlx"+ | "mlx_kv_bits_requested"+ | "mlx_kv_quant_reason"+ | "chat_template_override_reason"+ | "mlx_kv_quant_note"+>;++/** MLX KV-quantization state a load response establishes.+ *+ * A non-MLX response retires the verdict but omits mlxKvBits: the width is dormant+ * there, not wrong, and a preset carrying it must survive the round-trip.+ */+export function mlxRuntimeStateFrom(resp: MlxRuntimeResponse): {+ mlxKvBits?: number | null;+ loadedMlxKvBitsRequested: number | null;+ mlxKvQuantReason: string | null;+ chatTemplateOverrideReason: string | null;+ mlxKvQuantNote: string | null;+} {+ if (resp.is_mlx !== true) {+ return {+ loadedMlxKvBitsRequested: null,+ mlxKvQuantReason: null,+ chatTemplateOverrideReason: null,+ mlxKvQuantNote: null,+ };+ }+ return {+ // Requested, not applied: a refusal applies no width but still has a reason.+ mlxKvBits: resp.mlx_kv_bits_requested ?? null,+ loadedMlxKvBitsRequested: resp.mlx_kv_bits_requested ?? null,+ mlxKvQuantReason: resp.mlx_kv_quant_reason ?? null,+ chatTemplateOverrideReason: resp.chat_template_override_reason ?? null,+ mlxKvQuantNote: resp.mlx_kv_quant_note ?? 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 9c366d4c165..293fd97a00a 100644--- a/studio/frontend/src/features/chat/presets/preset-load-config.ts+++ b/studio/frontend/src/features/chat/presets/preset-load-config.ts@@ -11,6 +11,7 @@ import {DEFAULT_PER_MODEL_CONFIG,DEFAULT_MAX_SEQ_LENGTH,KV_CACHE_DTYPES,+ MLX_KV_BITS,N_PARALLEL_MAX,N_PARALLEL_MIN,normalizeMaxSeqLength,@@ -32,6 +33,7 @@ export type PresetLoadConfig = Pick<| "customContextLength"| "maxSeqLength"| "kvCacheDtype"+ | "mlxKvBits"| "speculativeType"| "specDraftNMax"| "nParallel"@@ -48,6 +50,7 @@ export const EMPTY_PRESET_LOAD_CONFIG: PresetLoadConfig = {customContextLength: null,maxSeqLength: null,kvCacheDtype: null,+ mlxKvBits: null,speculativeType: null,specDraftNMax: null,nParallel: null,@@ -103,6 +106,11 @@ export function normalizePresetLoadConfig(? Math.max(CONTEXT_LENGTH_MIN, Math.floor(partial.customContextLength)): null,maxSeqLength: normalizeMaxSeqLength(partial.maxSeqLength as number | null),+ mlxKvBits:+ typeof partial.mlxKvBits === "number" &&+ MLX_KV_BITS.includes(partial.mlxKvBits)+ ? partial.mlxKvBits+ : null,kvCacheDtype:typeof partial.kvCacheDtype === "string" &&VALID_KV_CACHE_DTYPES.has(partial.kvCacheDtype)@@ -164,6 +172,7 @@ export function capturePresetLoadConfig(): PresetLoadConfig | undefined {customContextLength: effectiveContextLength ?? null,maxSeqLength: normalizeMaxSeqLength(snapshot.maxSeqLength),kvCacheDtype: snapshot.kvCacheDtype ?? null,+ mlxKvBits: snapshot.mlxKvBits ?? null,speculativeType: normalizeSpeculativeType(snapshot.speculativeType),specDraftNMax: snapshot.specDraftNMax ?? null,nParallel: snapshot.nParallel ?? null,@@ -219,6 +228,7 @@ export function applyPresetLoadConfig(maxSeqLength: normalizeMaxSeqLength(config.maxSeqLength) ?? DEFAULT_MAX_SEQ_LENGTH,customContextLength: config.customContextLength ?? null,kvCacheDtype: config.kvCacheDtype ?? null,+ mlxKvBits: config.mlxKvBits ?? null,speculativeType: config.speculativeType ?? null,specDraftNMax: config.specDraftNMax ?? null,nParallel: config.nParallel ?? null,@@ -245,6 +255,9 @@ export function formatPresetLoadConfigSummary(if (config.kvCacheDtype) {parts.push(`KV ${config.kvCacheDtype}`);}+ if (config.mlxKvBits) {+ parts.push(`MLX KV ${config.mlxKvBits}-bit`);+ }if (config.speculativeType && config.speculativeType !== "auto") {parts.push(`Spec ${config.speculativeType}`);}diff --git a/studio/frontend/src/features/chat/shared-composer.tsx b/studio/frontend/src/features/chat/shared-composer.tsxindex 567f588463e..0fba501a3ec 100644--- a/studio/frontend/src/features/chat/shared-composer.tsx+++ b/studio/frontend/src/features/chat/shared-composer.tsx@@ -1,6 +1,7 @@// SPDX-License-Identifier: AGPL-3.0-only// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0+import { mlxRuntimeStateFrom } from "./lib/mlx-runtime-state";import { TooltipIconButton } from "@/components/assistant-ui/tooltip-icon-button";import {thinkEffortAriaLabel,@@ -1405,6 +1406,7 @@ export function SharedComposer({approved_remote_code_fingerprint: approvedRemoteCodeFingerprint,chat_template_override: effectiveChatTemplateOverride,cache_type_kv: ownConfig.kvCacheDtype ?? null,+ mlx_kv_bits: ownConfig.mlxKvBits ?? null,speculative_type: effectiveSpeculativeType,spec_draft_n_max: effectiveSpecDraftNMax,tensor_parallel: effectiveTensorParallel,@@ -1463,6 +1465,7 @@ export function SharedComposer({supportsTools: resp.supports_tools ?? false,kvCacheDtype: resp.cache_type_kv ?? null,loadedKvCacheDtype: resp.cache_type_kv ?? null,+ ...mlxRuntimeStateFrom(resp),// Click-time value, not the resolved echo (see the single-model load).nParallel: committedSlots,loadedNParallel: committedSlots,diff --git a/studio/frontend/src/features/chat/stores/chat-runtime-store.ts b/studio/frontend/src/features/chat/stores/chat-runtime-store.tsindex 1c4c1d2e87d..9abef48f720 100644--- a/studio/frontend/src/features/chat/stores/chat-runtime-store.ts+++ b/studio/frontend/src/features/chat/stores/chat-runtime-store.ts@@ -1035,6 +1035,12 @@ type ChatRuntimeStore = {maxToolCallsPerMessage: number;toolCallTimeout: number;kvCacheDtype: string | null;+ mlxKvBits: number | null;+ /** Width the backend was last asked for; the verdict belongs beside it. */+ loadedMlxKvBitsRequested: number | null;+ mlxKvQuantReason: string | null;+ chatTemplateOverrideReason: string | null;+ mlxKvQuantNote: string | null;loadedKvCacheDtype: string | null;speculativeType: string | null;loadedSpeculativeType: string | null;@@ -1597,6 +1603,11 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({maxToolCallsPerMessage: 25,toolCallTimeout: 5,kvCacheDtype: null,+ mlxKvBits: null,+ loadedMlxKvBitsRequested: null,+ mlxKvQuantReason: null,+ chatTemplateOverrideReason: null,+ mlxKvQuantNote: null,loadedKvCacheDtype: null,speculativeType: readPersistedSpeculativeType(),loadedSpeculativeType: null,@@ -2049,6 +2060,11 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({toolFullOutput: {},activeDiffusionCanvasByThreadId: {},kvCacheDtype: null,+ mlxKvBits: null,+ loadedMlxKvBitsRequested: null,+ mlxKvQuantReason: null,+ chatTemplateOverrideReason: null,+ mlxKvQuantNote: null,loadedKvCacheDtype: null,speculativeType: readPersistedSpeculativeType(),loadedSpeculativeType: null,diff --git a/studio/frontend/src/features/chat/types/api.ts b/studio/frontend/src/features/chat/types/api.tsindex ed7e75747bb..2dfba7e1fd4 100644--- a/studio/frontend/src/features/chat/types/api.ts+++ b/studio/frontend/src/features/chat/types/api.ts@@ -52,6 +52,7 @@ export interface LoadModelRequest {approved_remote_code_fingerprint?: string | null;chat_template_override?: string | null;cache_type_kv?: string | null;+ mlx_kv_bits?: number | null;/*** Speculative decoding mode for GGUF models. Canonical values: "auto"* (platform-aware: MTP on MTP GGUFs, ngram-mod fallback for sub-3B), "mtp"@@ -163,6 +164,7 @@ export function isMultimodalResponse(}export interface LoadModelResponse {+ is_mlx?: boolean;status: string;model: string;display_name: string;@@ -200,6 +202,12 @@ export interface LoadModelResponse {supports_preserve_thinking?: boolean;supports_tools?: boolean;cache_type_kv?: string | null;+ mlx_kv_bits?: number | null;+ mlx_kv_bits_requested?: number | null;+ mlx_kv_quant_eligibility?: string | null;+ mlx_kv_quant_reason?: string | null;+ chat_template_override_reason?: string | null;+ mlx_kv_quant_note?: string | null;chat_template?: string | null;/** Canonical UI-facing mode the load request resolved to. See LoadModelRequest. */speculative_type?: string | null;@@ -233,6 +241,7 @@ export interface UnloadModelRequest {}export interface InferenceStatusResponse {+ is_mlx?: boolean;active_model: string | null;model_identifier?: string | null;is_vision: boolean;@@ -272,6 +281,12 @@ export interface InferenceStatusResponse {max_context_length?: number | null;native_context_length?: number | null;cache_type_kv?: string | null;+ mlx_kv_bits?: number | null;+ mlx_kv_bits_requested?: number | null;+ mlx_kv_quant_eligibility?: string | null;+ mlx_kv_quant_reason?: string | null;+ chat_template_override_reason?: string | null;+ mlx_kv_quant_note?: string | null;chat_template_override?: string | null;/** Canonical UI-facing mode currently active. See LoadModelRequest. */speculative_type?: string | 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 b8fae42cd46..d9320473f2d 100644--- a/studio/frontend/src/features/model-picker/api/model-overrides.ts+++ b/studio/frontend/src/features/model-picker/api/model-overrides.ts@@ -26,6 +26,8 @@ export interface ApiModelOverride {// biome-ignore lint/style/useNamingConvention: API schemakv_cache_dtype?: string;// biome-ignore lint/style/useNamingConvention: API schema+ mlx_kv_bits?: number;+ // biome-ignore lint/style/useNamingConvention: API schemaspeculative_type?: string;// biome-ignore lint/style/useNamingConvention: API schemaspec_draft_n_max?: number;@@ -90,6 +92,11 @@ export function toApiOverride(config: PerModelConfig | null): ApiModelOverride {if (config.kvCacheDtype) {payload.kv_cache_dtype = config.kvCacheDtype;}+ // Travels beside kv_cache_dtype, or an API auto-switch loads a remembered MLX+ // model at full precision.+ if (config.mlxKvBits != null) {+ payload.mlx_kv_bits = config.mlxKvBits;+ }if (config.speculativeType) {payload.speculative_type = config.speculativeType;}diff --git a/studio/frontend/src/features/model-picker/components/chat-template-editor-dialog.tsx b/studio/frontend/src/features/model-picker/components/chat-template-editor-dialog.tsxindex 3dad635aeed..cc9d48b911c 100644--- a/studio/frontend/src/features/model-picker/components/chat-template-editor-dialog.tsx+++ b/studio/frontend/src/features/model-picker/components/chat-template-editor-dialog.tsx@@ -114,7 +114,7 @@ export function ChatTemplateEditorDialog({</DialogTitle><DialogDescription>{readOnly- ? "This is the model's chat template. Custom templates apply to GGUF models for now, so it is view only for safetensors models."+ ? "This is the model's chat template. This model's backend cannot take a custom one, so it is view only.": "Override the model's chat template with custom Jinja. The change applies when the model loads. Saving an empty template or one that matches the default clears the override."}</DialogDescription></DialogHeader>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 0bf8705d631..b54ac4acf1d 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@@ -13,6 +13,7 @@ import {} from "@/components/ui/select";import { Slider } from "@/components/ui/slider";import { Switch } from "@/components/ui/switch";+import { usePlatformStore } from "@/config/env";import {GPU_LAYERS_AUTO,fetchGgufStagedMetadata,@@ -57,6 +58,7 @@ import {MAX_SEQ_LENGTH_MAX,MAX_SEQ_LENGTH_MIN,MAX_SEQ_LENGTH_STEP,+ MLX_KV_BITS,N_PARALLEL_MAX,N_PARALLEL_MIN,type PerModelConfig,@@ -64,6 +66,7 @@ import {deletePerModelConfig,floorMaxSeqLength,isDefaultConfig,+ isServedByMlx,normalizeMaxSeqLength,normalizePerModelConfig,readAdvancedSettingsOpen,@@ -191,7 +194,7 @@ function ChatTemplateSetting({<span className={LABEL_CLASS}>Chat Template</span><InfoHint>{readOnly- ? "Preview the model's chat template. Custom overrides apply to GGUF models for now."+ ? "Preview the model's chat template. This model's backend cannot take a custom one.": "Override the model's chat template with custom Jinja. Applies when the model loads."}</InfoHint></div>@@ -495,6 +498,111 @@ function GpuMemorySettings({);}+const MLX_KV_BITS_AUTO = "auto";++function AdvancedSettingsToggle({+ checked,+ onCheckedChange,+}: {+ checked: boolean;+ onCheckedChange: (next: boolean) => void;+}) {+ return (+ <div className={ROW_CLASS}>+ <div className="flex min-w-0 items-center gap-1.5">+ <span className="min-w-0 text-ui-13 font-medium leading-[1.25] tracking-nav text-muted-foreground">+ Advanced settings+ </span>+ <InfoHint>+ Extra options for how the model loads. Most setups don't need these.+ </InfoHint>+ </div>+ <Switch+ className="panel-switch shrink-0"+ checked={checked}+ onCheckedChange={onCheckedChange}+ aria-label="Show advanced settings"+ />+ </div>+ );+}++function MlxAdvancedSettings({+ config,+ update,+ outcome,+ servedByMlx,+ onEditTemplate,+ templateOutcome,+}: {+ config: PerModelConfig;+ update: (patch: Partial<PerModelConfig>) => void;+ /** What the backend reported for this exact setting on the loaded model. */+ outcome: string | null;+ /** KV quantization is MLX-only; a CUDA safetensors model has no such control. */+ servedByMlx: boolean;+ onEditTemplate: () => void;+ /** Why the loaded model could not take the override it was given. */+ templateOutcome: string | null;+}) {+ return (+ <div className="flex flex-col gap-1">+ {servedByMlx && (+ <>+ <div className={ROW_CLASS}>+ <div className="flex min-w-0 items-center gap-1.5">+ <span className={LABEL_CLASS}>KV Cache Dtype</span>+ <InfoHint>+ Lower KV cache precision to save memory at the cost of some+ quality. Auto keeps full precision; 8-bit is the safest reduction,+ and lower widths save more memory.+ </InfoHint>+ </div>+ <Select+ value={config.mlxKvBits ? String(config.mlxKvBits) : MLX_KV_BITS_AUTO}+ onValueChange={(v) =>+ update({ mlxKvBits: v === MLX_KV_BITS_AUTO ? null : Number(v) })+ }+ >+ <SelectTrigger+ animateRadius={false}+ icon={ChevronDownStandardIcon}+ iconClassName="size-3.5"+ className={`w-[92px] ${SELECT_TRIGGER_CLASS}`}+ >+ <SelectValue />+ </SelectTrigger>+ <SelectContent className="menu-soft-surface ring-0 border-0 rounded-lg">+ <SelectItem value={MLX_KV_BITS_AUTO}>Auto</SelectItem>+ {MLX_KV_BITS.map((bits) => (+ <SelectItem key={bits} value={String(bits)}>+ {bits}-bit+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </div>+ {outcome ? (+ <p className="text-[11px] leading-snug text-muted-foreground">+ {outcome}+ </p>+ ) : null}+ </>+ )}+ <ChatTemplateSetting+ config={config}+ onEditTemplate={onEditTemplate}+ readOnly={!servedByMlx}+ />+ {templateOutcome ? (+ <p className="text-[11px] leading-snug text-muted-foreground">+ {templateOutcome}+ </p>+ ) : null}+ </div>+ );+}+function GgufAdvancedSettings({config,update,@@ -728,6 +836,19 @@ export function ModelConfigPage({showHeader = true,}: ModelConfigPageProps) {const rememberId = useId();+ const platformDeviceType = usePlatformStore((s) => s.deviceType);+ const platformChatOnlyReason = usePlatformStore((s) => s.chatOnlyReason);+ const mlxKvQuantReason = useChatRuntimeStore((s) => s.mlxKvQuantReason);+ const chatTemplateOverrideReason = useChatRuntimeStore(+ (s) => s.chatTemplateOverrideReason,+ );+ const loadedChatTemplateOverride = useChatRuntimeStore(+ (s) => s.loadedChatTemplateOverride,+ );+ const mlxKvQuantNote = useChatRuntimeStore((s) => s.mlxKvQuantNote);+ const loadedMlxKvBitsRequested = useChatRuntimeStore(+ (s) => s.loadedMlxKvBitsRequested,+ );const isActiveModel = loadedConfig != null;const hfToken = useChatRuntimeStore((s) => s.hfToken);const activeNativePathToken = useChatRuntimeStore(@@ -765,6 +886,26 @@ export function ModelConfigPage({const [savedRemember, setSavedRemember] = useState(() => initial.remembered);const [speculativeFallback] = useState(readPersistedSpeculativeType);const [templateOpen, setTemplateOpen] = useState(false);+ // Compare against what the backend was asked for, not what it applied: staging a+ // new value must retire a verdict that answered a different request.+ const chatTemplateOutcome =+ isActiveModel &&+ (configState.chatTemplateOverride ?? null) ===+ (loadedChatTemplateOverride ?? null)+ ? chatTemplateOverrideReason+ : null;+ const mlxKvQuantOutcome =+ isActiveModel &&+ (configState.mlxKvBits ?? null) === (loadedMlxKvBitsRequested ?? null)+ ? // Both, not either: dropping the note promises savings before the offset+ // where quantization actually starts.+ [mlxKvQuantReason, mlxKvQuantNote].filter(Boolean).join(". ") || null+ : null;+ const servedByMlx = isServedByMlx(+ target.isGguf,+ platformDeviceType,+ platformChatOnlyReason,+ );// Read live, not snapshotted at mount: the sidebar copy stays mounted while collapsed.const advancedPreference = useSyncExternalStore(subscribeAdvancedSettingsOpen,@@ -774,7 +915,14 @@ export function ModelConfigPage({// Until the switch is used anywhere, a model carrying non-default advanced values opens the// section itself. Frozen at mount so editing a field back to its default cannot close it.const [autoOpenAdvanced] = useState(() => hasNonDefaultAdvanced(configState));- const showAdvanced = advancedPreference ?? autoOpenAdvanced;+ // Frozen like the rest of the auto-open decision, so editing the width does not+ // reopen the section the user just closed.+ const [initialMlxKvBits] = useState(() => configState.mlxKvBits ?? null);+ // Applicability stays live, unlike the snapshot above: MLX can become available+ // after mount, and a width that starts applying then has to surface.+ const autoOpenForMlxKvBits = servedByMlx && initialMlxKvBits != null;+ const showAdvanced =+ advancedPreference ?? (autoOpenAdvanced || autoOpenForMlxKvBits);const toggleAdvanced = saveAdvancedSettingsOpen;const contextInputRef = useRef<NumericValueInputHandle>(null);const maxSeqLengthInputRef = useRef<NumericValueInputHandle>(null);@@ -1210,23 +1358,10 @@ export function ModelConfigPage({/>)}- <div className={ROW_CLASS}>- <div className="flex min-w-0 items-center gap-1.5">- <span className="min-w-0 text-ui-13 font-medium leading-[1.25] tracking-nav text-muted-foreground">- Advanced settings- </span>- <InfoHint>- Extra options for how the model loads. Most setups don't need- these.- </InfoHint>- </div>- <Switch- className="panel-switch shrink-0"- checked={showAdvanced}- onCheckedChange={toggleAdvanced}- aria-label="Show advanced settings"- />- </div>+ <AdvancedSettingsToggle+ checked={showAdvanced}+ onCheckedChange={toggleAdvanced}+ /></>)}{!target.isGguf && (@@ -1242,10 +1377,19 @@ export function ModelConfigPage({})}/>- <ChatTemplateSetting- config={config}- onEditTemplate={() => setTemplateOpen(true)}- readOnly={true}+ {showAdvanced && (+ <MlxAdvancedSettings+ config={config}+ update={update}+ outcome={mlxKvQuantOutcome}+ servedByMlx={servedByMlx}+ onEditTemplate={() => setTemplateOpen(true)}+ templateOutcome={chatTemplateOutcome}+ />+ )}+ <AdvancedSettingsToggle+ checked={showAdvanced}+ onCheckedChange={toggleAdvanced}/></>)}@@ -1309,7 +1453,7 @@ export function ModelConfigPage({value={config.chatTemplateOverride}defaultTemplate={resolvedDefaultTemplate}defaultLoading={resolvedDefaultLoading}- readOnly={!target.isGguf}+ readOnly={!target.isGguf && !servedByMlx}onSave={(override) => update({ chatTemplateOverride: override })}/></div>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 927e1693b53..bae0c7a1e16 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@@ -3,7 +3,9 @@import { isExternalModelId, useChatRuntimeStore } from "@/features/chat";import { useMemo } from "react";+import { usePlatformStore } from "@/config/env";import type { PerModelConfig } from "../model-config/per-model-config";+import { isServedByMlx } from "../model-config/per-model-config";export interface ActiveModelConfigState {checkpoint: string | null;@@ -13,11 +15,14 @@ export interface ActiveModelConfigState {export function useActiveModelConfig(): ActiveModelConfigState {const checkpoint = useChatRuntimeStore((s) => s.params.checkpoint) || null;+ const deviceType = usePlatformStore((s) => s.deviceType);+ const chatOnlyReason = usePlatformStore((s) => s.chatOnlyReason);const maxSeqLength = useChatRuntimeStore((s) => s.params.maxSeqLength);const activeGgufVariant = useChatRuntimeStore((s) => s.activeGgufVariant);const ggufContextLength = useChatRuntimeStore((s) => s.ggufContextLength);const customContextLength = useChatRuntimeStore((s) => s.customContextLength);const kvCacheDtype = useChatRuntimeStore((s) => s.kvCacheDtype);+ const mlxKvBits = useChatRuntimeStore((s) => s.mlxKvBits);const speculativeType = useChatRuntimeStore((s) => s.speculativeType);const specDraftNMax = useChatRuntimeStore((s) => s.specDraftNMax);const nParallel = useChatRuntimeStore((s) => s.nParallel);@@ -38,6 +43,12 @@ export function useActiveModelConfig(): ActiveModelConfigState {ggufContextLength != null ||(checkpoint?.toLowerCase().endsWith(".gguf") ?? false);+ // Off-backend this stays null, or the model compares unequal to its own defaults+ // over a field it cannot show.+ const effectiveMlxKvBits = isServedByMlx(isGguf, deviceType, chatOnlyReason)+ ? (mlxKvBits ?? null)+ : null;+const config = useMemo<PerModelConfig | null>(() => {if (!checkpoint || isExternalModelId(checkpoint)) {return null;@@ -46,6 +57,7 @@ export function useActiveModelConfig(): ActiveModelConfigState {customContextLength: customContextLength ?? null,maxSeqLength: isGguf ? null : maxSeqLength,kvCacheDtype: kvCacheDtype ?? null,+ mlxKvBits: effectiveMlxKvBits,speculativeType: speculativeType ?? "auto",specDraftNMax: specDraftNMax ?? null,nParallel: nParallel ?? null,@@ -69,6 +81,7 @@ export function useActiveModelConfig(): ActiveModelConfigState {maxSeqLength,customContextLength,kvCacheDtype,+ effectiveMlxKvBits,speculativeType,specDraftNMax,nParallel,diff --git a/studio/frontend/src/features/model-picker/index.ts b/studio/frontend/src/features/model-picker/index.tsindex dbd4cc2b9a0..8bb912c6834 100644--- a/studio/frontend/src/features/model-picker/index.ts+++ b/studio/frontend/src/features/model-picker/index.ts@@ -46,6 +46,8 @@ export {normalizeMaxSeqLength,type PerModelConfig,adoptLegacyConfigKey,+ isServedByMlx,+ presetLoadSettingNames,resolveInitialConfig,resolveResidentInitialConfig,} from "./model-config/per-model-config";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 78a427724de..55754e310e3 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@@ -49,6 +49,7 @@ export function applyPerModelConfigToRuntime(: { ids: null, indexKind: null };useChatRuntimeStore.setState({customContextLength: config.customContextLength ?? null,+ mlxKvBits: config.mlxKvBits ?? null,kvCacheDtype: config.kvCacheDtype ?? null,speculativeType:normalizeSpeculativeType(config.speculativeType) ??@@ -100,6 +101,7 @@ export function currentRuntimePerModelConfig(? normalizeMaxSeqLength(s.params.maxSeqLength): null,kvCacheDtype: s.kvCacheDtype ?? null,+ mlxKvBits: s.mlxKvBits ?? null,speculativeType: normalizeSpeculativeType(s.speculativeType),specDraftNMax: s.specDraftNMax ?? null,nParallel: s.nParallel ?? null,@@ -125,6 +127,7 @@ export function perModelConfigsEqual(normalizeMaxSeqLength(a.maxSeqLength) ===normalizeMaxSeqLength(b.maxSeqLength) &&(a.kvCacheDtype ?? null) === (b.kvCacheDtype ?? null) &&+ (a.mlxKvBits ?? null) === (b.mlxKvBits ?? null) &&normalizeSpeculativeType(a.speculativeType) ===normalizeSpeculativeType(b.speculativeType) &&(a.specDraftNMax ?? null) === (b.specDraftNMax ?? null) &&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 c914ca37afb..8131f33c72c 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@@ -51,6 +51,7 @@ export function loadedConfigSignature(config.customContextLength ?? "",config.maxSeqLength ?? "",config.kvCacheDtype ?? "",+ config.mlxKvBits ?? "",config.speculativeType ?? "",config.specDraftNMax ?? "",config.nParallel ?? "",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 207a619ce65..70220ad04f8 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@@ -16,6 +16,8 @@ export interface PerModelConfig {customContextLength: number | null;maxSeqLength: number | null;kvCacheDtype: string | null;+ /** MLX KV cache quantization width. Optional so older blobs still parse. */+ mlxKvBits?: number | null;speculativeType: string | null;specDraftNMax: number | null;nParallel: number | null;@@ -34,6 +36,7 @@ export const DEFAULT_PER_MODEL_CONFIG: PerModelConfig = {customContextLength: null,maxSeqLength: null,kvCacheDtype: null,+ mlxKvBits: null,speculativeType: null,specDraftNMax: null,nParallel: null,@@ -53,6 +56,43 @@ export const MAX_SEQ_LENGTH_STEP = 128;export const DEFAULT_MAX_SEQ_LENGTH = 4096;export const CONTEXT_LENGTH_MIN = 128;+// Reasons a Mac still cannot serve with MLX.+const NO_MLX_REASONS = new Set([+ "mlx_unavailable",+ "intel_mac",+ "detection_failed",+]);++/** Whether MLX will serve this model, and so whether MLX-only settings apply.+ *+ * Every non-GGUF model loads through MLX on a working Mac stack, including plain+ * safetensors repos, so `!isGguf` alone would show these controls to CUDA users.+ */+export function isServedByMlx(+ isGguf: boolean,+ deviceType: string | null | undefined,+ chatOnlyReason?: string | null,+): boolean {+ return (+ !isGguf &&+ deviceType === "mac" &&+ !NO_MLX_REASONS.has(chatOnlyReason ?? "")+ );+}++export function presetLoadSettingNames(+ isGguf: boolean,+ deviceType: string | null | undefined,+ chatOnlyReason?: string | null,+): string {+ if (isGguf) {+ return "context length, KV cache dtype, speculative decoding, GPU layers";+ }+ return isServedByMlx(isGguf, deviceType, chatOnlyReason)+ ? "max seq length, KV cache dtype"+ : "max seq length";+}+// Matches studio/backend/core/inference/llama_cpp.py _valid_cache_types (f16 is the UI default).export const KV_CACHE_DTYPES = ["bf16",@@ -64,6 +104,10 @@ export const KV_CACHE_DTYPES = ["iq4_nl","f32",] as const;++// Every width mx.quantize supports. By bit width, not a dtype name, hence separate+// from 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);export {@@ -90,6 +134,7 @@ const STORED_CONFIG_FIELDS = new Set(["customContextLength","maxSeqLength","kvCacheDtype",+ "mlxKvBits","speculativeType","specDraftNMax","nParallel",@@ -558,6 +603,11 @@ function normalizeV1(partial: RawConfig): PerModelConfig {? Math.max(CONTEXT_LENGTH_MIN, Math.floor(partial.customContextLength)): null,maxSeqLength: normalizeMaxSeqLength(partial.maxSeqLength),+ mlxKvBits:+ typeof partial.mlxKvBits === "number" &&+ MLX_KV_BITS.includes(partial.mlxKvBits)+ ? partial.mlxKvBits+ : null,kvCacheDtype:typeof partial.kvCacheDtype === "string" &&VALID_KV_CACHE_DTYPES.has(partial.kvCacheDtype)@@ -716,6 +766,7 @@ export function isDefaultConfig(config: PerModelConfig): boolean {config.customContextLength == null &&config.maxSeqLength == null &&(config.kvCacheDtype ?? null) === DEFAULT_PER_MODEL_CONFIG.kvCacheDtype &&+ (config.mlxKvBits ?? null) === DEFAULT_PER_MODEL_CONFIG.mlxKvBits &&config.speculativeType === DEFAULT_PER_MODEL_CONFIG.speculativeType &&config.specDraftNMax == null &&config.nParallel == null &&diff --git a/studio/frontend/tests/model-config-instance-key.test.ts b/studio/frontend/tests/model-config-instance-key.test.tsindex f8d12a646b9..d0ac05141e3 100644--- a/studio/frontend/tests/model-config-instance-key.test.ts+++ b/studio/frontend/tests/model-config-instance-key.test.ts@@ -97,6 +97,7 @@ test("every mirrored setting moves the instance key", () => {{ ...LIVE, customContextLength: 8192 },{ ...LIVE, maxSeqLength: 4096 },{ ...LIVE, kvCacheDtype: "f16" },+ { ...LIVE, mlxKvBits: 4 },{ ...LIVE, speculativeType: "off" },{ ...LIVE, specDraftNMax: 4 },{ ...LIVE, nParallel: 1 },