Repository navigation
Studio: honor MLX KV cache quantization and chat template overrides - #8007
Conversation
Whether MLX will serve a model is not the same question as whether its repo name says MLX: on a Mac with a working MLX stack every non-GGUF model loads through MLX, including plain safetensors repos. Callers gating MLX-only behaviour need that distinction, and `!isGguf` alone would extend it to CUDA hosts. Exported from the feature index so other features can import it without reaching past the barrel.
…ility probe Adds an MLX-native `mlx_kv_bits` load setting (8 or 4) applying KV cache quantization to the text, vision and audio generation paths on Apple Silicon. MLX takes a bit width rather than a llama.cpp dtype name, so this is a separate field from `cache_type_kv` and the GGUF path is untouched. Unset leaves generation byte-identical to before. Eligibility is probed, not predicted. At load the backend builds the cache the runtime will build, runs a single-token forward, and attempts the real `to_quantized` conversion on each top-level entry. Deriving it from config vocabulary or class attributes is unreliable in both directions: a model can declare a head dimension it does not use for the cache, a sliding window can be spelled differently between implementations, and unrecognised vocabularies would refuse models that work. It also catches the case that matters most, since a sliding-window model such as Gemma 3 mixes plain and rotating entries and quantizing it raises mid-generation only after the leading entries have already been converted. The probe restores the random stream it borrows and releases its caches, so asking about a setting neither perturbs sampling nor retains memory. The resolved value, its eligibility and any reason or caveat cross the worker and orchestrator mirrors into the load and status responses, and join the already-loaded check so changing the setting reloads the model. A model that cannot honor the setting reports why instead of appearing to apply it, including when an mlx-lm build cannot measure a quantized entry and cross-turn prompt-cache reuse is therefore unavailable. Measured on Apple Silicon: KV bytes fall from 645.9 MB to 343.1 MB (46.9%) over a 5,410-token prompt on Qwen3-0.6B, while Gemma 3 270M is refused with its rotating-cache reason.
Adds an "MLX Advanced Settings" section offering the KV cache quantization width (off / 8-bit / 4-bit) for models served by MLX, and plumbs it through load requests, the runtime store, per-model config and presets. The backend already honored the width; until now nothing could set it from the UI. The section keys on the backend that will serve the model rather than the repo name: on Apple Silicon a plain safetensors repo loads through MLX too, so `!isGguf` alone would offer the control to CUDA users and miss ordinary MLX repos. Hosts whose MLX stack cannot serve — Intel Macs, a broken install, or failed hardware detection — are excluded. The editable width and the width the backend was last asked for are kept as separate state. They diverge as soon as the user stages an edit, and a refusal applies no width at all, so neither can stand in for the other: the refusal reason is shown only beside the request it actually answers, and staging a different width retires it. Status responses adopt this state when the tab takes up a model it was not already tracking, matching the surrounding load settings; a tab that missed that moment recovers on a later poll, but only when nothing would be lost. A non-MLX response retires the verdict while keeping the width itself, which is dormant on another backend rather than wrong, so a preset survives a round-trip through a model that cannot consume it. That dormant value is excluded where a model's own config is captured, so a GGUF model never compares unequal to its own defaults over a setting it does not show. Two response boundaries needed the new fields. `ChatPresetLoadConfig` forbids unknown keys, so a preset carrying the width would have failed the whole chat-settings write; and the llama.cpp runtime projection raises on any field it cannot resolve, which would have turned every GGUF load and status poll into a 500. A llama.cpp backend now reports the MLX fields as absent, and a test exercises the real backend class rather than a stand-in, since a permissive fake proves nothing about the shipped one. On vision models the control discloses that prompt-cache reuse may be reduced, worded conditionally because the effect depends on the model's cache mode.
Offers every KV cache width the runtime supports rather than 8 and 4. mx.quantize accepts 2, 3, 4, 5, 6 and 8, each verified round-tripping through QuantizedKVCache rather than through mx.quantize alone, since the cache does its own packing arithmetic. mlx-lm forwards --kv-bits without imposing a domain, so the earlier pair was this code's restriction and not the runtime's. The request schema, the preset schema and the API description widen with it, so a width the control offers cannot be rejected downstream. Renames the control to "KV Cache Dtype" and its unset option to "Auto", matching the llama.cpp control users see in the same place. MLX still takes a bit width rather than a dtype name, but the two are never visible at once, so shared vocabulary reads better than a distinction that only makes sense to someone who knows both backends. Moves the MLX section behind the "Advanced settings" toggle and puts the chat template inside it, so both backends present the same shape: base settings, an advanced block behind the switch, then the switch. Previously the MLX controls were always visible while their llama.cpp equivalents were tucked away. The toggle row is now one component shared by both branches; it was duplicated markup, which is how the two would drift. Shortens the tip to the length of the one beside it. The vision-model caveat it used to carry is already attached to the load response and rendered under the control, so it appears when it applies instead of in a tooltip on every model.
Lets an MLX-served model be loaded with a custom chat template, which until now only llama.cpp accepted. The frontend already sent the value for these models; nothing received it. The override is installed onto the objects that render, once, when the model loads. Every render site reads the template at call time and the backend keeps the same objects it renders with, so one install governs the text, vision and audio paths — including audio, which bypasses the shared rendering helper entirely and would need its own plumbing otherwise. It replaces a template that already exists and never creates one. Two different selectors decide which object renders, and both choose by whether a template is present: giving one to an object that had none moves the render somewhere else, and on the vision side to an object that never selects a template's tool-calling variant. Replacing an existing template moves neither. Six ways it cannot be honored are reported rather than left to look like success: the runtime supplies the template as code and prefers it over the attribute; the model ships a set of named templates, which flattening to one string would strip of its tool-calling variant; nothing holds a template to replace; the template cannot be replaced at all; the override does not render, which is how a hand-edited template usually fails and would otherwise raise on every generation instead of once at load; and it stops marking where audio goes, which would leave the model advertising an input it can no longer place. Anything already replaced is put back before the reason is reported. The audio case is judged against the native template rather than in isolation. Several model families render without consulting the audio count at all, so an absolute check would answer the same for every template and refuse an override identical to the one the model shipped with. The template reported to clients still means the one the model shipped with. It is captured before installing, because the capability classification and the settings editor's notion of "default" both read it, and because an override that drops tool markup would otherwise turn off tool support and with it the fallback that rescues tool rendering. The value crosses both process boundaries in both directions. The backend runs in the load subprocess and the parent rebuilds its record from an enumerated set of keys at each hop, so a value not named at both never reaches the parent — which is what the status endpoint and the reload decision read. That decision compares the requested override rather than the honored one, so a refused template does not differ from itself on every request and reload forever.
Unlocks the chat template editor for MLX-served models, inside the MLX advanced settings where the control already lives, and surfaces the reason when the backend could not take the template it was given. The editor's read-only test was "not a GGUF model", which lumped together two different backends: MLX, which now accepts an override, and CUDA safetensors, which does not. It keys on the serving backend instead, the same test the rest of that section uses. The copy no longer says overrides are a GGUF feature, since for two of the three backends they are not. The reason travels the same route as the KV quantization verdict, across the response type, the shared response mapper, the runtime store and the status adoption. Each of those is an enumerated list that has to name the field, which is where every repeat defect on this branch has come from, so both status branches carry it: one to set it, one to retire it when the active model changes backend. It is shown only while the editor's template still matches the one the backend answered, so staging an edit retires the old verdict rather than leaving it under a template it never described.
The Preset hint listed llama.cpp's controls unconditionally, so an MLX model was told a preset stores context length, speculative decoding and GPU layers -- none of which that backend exposes -- while omitting max seq length, which it does store. Resolve the list against the backend actually serving the model: GGUF keeps its existing text, MLX gets max seq length and KV cache dtype, and a non-GGUF model MLX cannot serve gets max seq length alone. The names match the panel's own labels so a user can find the controls the sentence promises.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 0a9cfa4458
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
VISIBLE_MODEL_RUNTIME_KEYS is the sole input to snapshotVisibleModelState, and restoreVisibleModelState spreads its output back, so a key missing from the list is neither captured before a background autoload nor restored after it. The MLX KV width and its verdict were missing, leaving the background load's values attached to the restored visible model.
Switching to a model with no staged or remembered config snapshotted the outgoing model's MLX KV width and chat template override and sent both in the new model's load payload, so it loaded quantized to a width whose eligibility was never checked for it, under a template written against another model's tokens. Both are re-baselined in the existing per-model reset. The payload variables only: the store keeps its values, since off MLX the width is dormant state a preset carries, neither editable control has a rollback path that restores it, and a completed load rewrites each control and its baseline from the response.
Advanced settings auto-open when a model carries a non-default advanced value, but the MLX KV width was never added to that check, so reopening a model whose only non-default setting was a remembered width showed the section closed and the active lower-precision setting hidden. Applicability is read live rather than frozen with the rest of the decision: MLX can become available after the page mounts, and a width that starts applying then has to surface without waiting for a remount. The width snapshot itself stays frozen, so editing the field cannot reopen a section the user just closed. The eligibility reason and the note beside it were also treated as alternatives, so a partial verdict on a vision model reported only that some layers are quantizable and dropped the note carrying the token offset where quantization begins -- promising savings on prompts too short to ever reach it. Both are rendered now.
|
Correct, fixed — The fix isn't quite the one-liner it looks like, and the detour is worth recording. Adding a bare So the two concerns need separating: the config snapshot must freeze (or editing the field would reopen a section the user closed), while applicability must stay live (or a transition is stuck until a remount). const [autoOpenAdvanced] = useState(() => hasNonDefaultAdvanced(config));
const [initialMlxKvBits] = useState(() => config.mlxKvBits ?? null);
const autoOpenForMlxKvBits = servedByMlx && initialMlxKvBits != null;
const showAdvanced = advancedPreference ?? (autoOpenAdvanced || autoOpenForMlxKvBits);Verified across both MLX transition directions, a dormant width off MLX, and a saved preference in either position — the preference still wins over auto-open in all cases. Since incomplete enumeration has bitten this branch repeatedly, I checked the whole predicate rather than just the reported field: One residual, deliberately left: for a model already resident while MLX is unavailable, |
|
Codex Review: Something went wrong. Try again later by commenting “@codex review”. ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
|
Codex Review: Didn't find any major issues. 👍 Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
…ced-settings # Conflicts: # studio/frontend/src/features/model-picker/components/model-config-page.tsx
…mplate that drops the image marker Three fixes on top of the branch. mlx_kv_bits was persisted in browser storage but dropped by every stage of the server-side override projection, so an OpenAI-API auto-switch loaded a remembered MLX model at full precision while the picker honored the width. It now travels beside kv_cache_dtype through toApiOverride, ModelOverridePayload, normalize_model_override and model_override_load_kwargs, validated against the same discrete set mx.quantize takes. The load-time template probe rendered a text-only turn and rejected only an empty result, so an override that renders text but emits no image placeholder installed cleanly and failed later on the first image request. Vision now gets the paired native-versus-override marker check the audio path already had, sharing one revoke helper. The native template was captured from the nested tokenizer while generation renders through chat_render_target, so on a processor owning its own template the editor showed the wrong default and saving it would install the tokenizer's template over the processor. Capture follows the render target, falling back to the tokenizer when that target holds no editable string. Also binds _template_override in __init__ beside _kv_quant, so a load failing before the install leaves the entry writer reading a dict rather than raising.
/status already reports chat_template_override from the mirrored chat_template_override_requested, but the fresh-load and already-loaded responses set only the refusal reason, so an API client saw a reason next to a null override and could read that as the model using its default. Only the MLX backend records the requested key, so llama.cpp responses are unchanged.
|
Reviewed this and pushed three commits to the branch. Nice work on the probe design: resolving eligibility by attempting the real conversion on a real cache, rather than predicting it from config values, is the right call, and it holds up under execution. Verified on real Apple Silicon
What I changedServer-side override projection. Vision image marker. The load-time probe rendered a text-only turn and rejected only an empty result, so an override that renders text but emits no image placeholder installed cleanly and failed later on the first image request. Reproduced on two real processors before touching anything: Native template capture. The capture read the nested tokenizer while generation renders through Load response echo. Also bound Two notes on the testsBoth defects I fixed in the template path were invisible to the tests that cover it. Separately, Pre-existing, not from this branch
I would also like to add a macOS leg for this file to CI, separately from this PR. Local runs on the merged branch: backend targeted suites 120 passed / 9 skipped, |
…ceholder Reverts the previous round's retainability change, which was wrong. Upstream LRUPromptCache.insert_cache computes its own total with sum(c.nbytes for c in prompt_cache), so an entry whose property raises can never be admitted however well a local fallback measures it. Measuring it another way only dropped the no-reuse caveat while every quantized turn still failed to insert. _kv_entry_nbytes now reads the property that decides admission, which also retires a workaround that could not work. The image check accepted any difference between the image-bearing and text-only probes, so a template rendering the image as prose, or emitting the content dict, passed while placing nothing the processor can bind an image to. It now also rejects a prompt _vlm_prompt_issue flags and, when the model names an image_token, requires that placeholder to survive. A model naming none keeps the difference test.
The echo added earlier was inert: only InferenceStatusResponse declared the field, so pydantic dropped it as an extra keyword from both load responses and the client saw nothing, with no error to notice it by. Moved to _InferenceRuntimeFields, which both responses inherit, so the declaration cannot drift again. The guard asserts every is_mlx / mlx_ / chat_template_override field status reports is on the shared base, and round-trips the echo through a real LoadResponse rather than trusting the constructor call to mean anything.
…ecovery, and keep the staged MLX width through a rollback
|
Codex Review: Didn't find any major issues. Delightful! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
|
Codex Review: Didn't find any major issues. 👍 Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
_llama_runtime_fields() returns one entry per field on _InferenceRuntimeFields and get_status splats it. #8007 added chat_template_override to that model while get_status was already passing the same keyword explicitly, so the call raised TypeError: got multiple values for keyword argument 'chat_template_override'. Every status poll with a GGUF loaded returned 500. The chat UI showed 'Failed to get status' plus 'Failed to refresh models', and the model picker rendered empty, which is what took studio-windows-ui-smoke red on main. Assign into the dict before splatting. Pinning the duplicate to None would not help: two values for one keyword is a TypeError whatever the values are. Adds a source-level contract so any future field added to _InferenceRuntimeFields cannot collide with an explicit keyword at a splat site.
#8007 added mlxRuntimeStateFrom to chat-adapter.ts. The sliced region the harness compiles imports it, so all 16 scenarios in test_chat_autoload_failure_gate.py fail on main with the harness's own "add a stub to PREAMBLE" assertion. Stub mirrors ../lib/mlx-runtime-state. No scenario here loads an MLX model, so only the non-MLX branch is reached, but the symbol has to exist.
Repo tests (CPU) is red on every open PR, and none of it is the PRs. - #8025 added Minus/Square/X to the titlebar's lucide-react import; the contract pinned the whole import line. Check the two icon names it actually cares about instead. - #8007 added mlxRuntimeStateFrom to chat-adapter.ts; the autoload harness has no stub for it, so 16 scenarios died as ReferenceErrors. Stub mirrors the real one: a non-MLX response retires the verdict but leaves mlxKvBits absent, and returning {} would keep a stale width alive and pass for the wrong reason. - model-config-page.tsx grew two raw text-[11px] utilities, which ignore the UI font size preference. Swapped for the text-ui-11 token. Co-authored-by: danielhanchen <[email protected]>
unslothai#8007 added chat_template_override to _InferenceRuntimeFields, so _llama_runtime_fields supplies it from the backend attribute and the explicit keyword beside the spread became a duplicate: every GGUF status call raised TypeError and returned 500, which is the four Python jobs red on every open PR. The computed value has to win, since the raw attribute is exactly what must not be reported: it would surface Unsloth's auto-applied bundled family template as a user-authored override and the frontend would re-send it for an unrelated model. So the helper's dict is hoisted to a local and that one key overridden before the spread. test_status_path pinned the call inside the constructor parentheses; it now accepts either spelling but still requires the fields to come from the shared helper.
unslothai#8007 added chat_template_override to _InferenceRuntimeFields, so _llama_runtime_fields supplies it from the backend attribute and the explicit keyword beside the spread became a duplicate: every GGUF status call raised TypeError and returned 500, which is the four Python jobs red on every open PR. The computed value has to win, since the raw attribute is exactly what must not be reported: it would surface Unsloth's auto-applied bundled family template as a user-authored override and the frontend would re-send it for an unrelated model. So the helper's dict is hoisted to a local and that one key overridden before the spread. test_status_path pinned the call inside the constructor parentheses; it now accepts either spelling but still requires the fields to come from the shared helper.
Studio's Run Settings offered MLX models a subset of controls that either did nothing or belonged to another backend. This branch gives the MLX path two settings it can actually honor — KV cache quantization and a custom chat template — and corrects the preset hint that described neither of them accurately.
What changed
KV cache quantization. MLX quantizes the KV cache by bit width rather than by a llama.cpp dtype name, so the setting is a separate field (
mlx_kv_bits) with its own domain: every widthmx.quantizesupports, since mlx-lm forwards--kv-bitswithout a domain of its own. Not every model can take it — a bounded sliding-window cache cannot be converted once wrapped, and some caches hold state the quantizer never descends into — so eligibility is resolved at load time by attempting the conversion on a real cache rather than predicting it from config values. Static proxies were wrong in both directions: models declare ahead_dimthey then ignore, and window caches spell their bound differently frommax_size. An ineligible model would otherwise raise insidemaybe_quantize_kv_cachemid-stream, after the leading entries had already been converted.The probe runs the model's own layers, some of which draw random numbers even in eval, so it snapshots and restores
mx.random.stateelement-wise — merely asking about a setting must not change later sampled output.Chat template override. The template editor was gated on
!isGguf, which offered it to CUDA safetensors models whose backend has no override support at all. It is now gated on the backend that will serve the model, and MLX honors the override at load time.An override replaces a template that already exists; it never creates one. Both render selectors —
chat_render_targetfor vision, mlx-vlm'sget_chat_templatefor audio — choose their target by whether a template is present, so creating one where there was none would silently move the render to a different object, and on the vision side to one that never selects the tool_use variant. Refusals are judged only against the objects that actually render: a model can carry an unreplaceable template on an object nothing reads — a processor rendering from its own string while its nested tokenizer holds a named set — and refusing on that would reject a template that works. A text model with no template is the one case where supplying one is the point rather than something to refuse, since it cannot chat at all without one.A hand-edited template usually fails by being invalid Jinja, which installs cleanly and then raises on every generation. A load-time probe renders a short conversation through the path generation will actually use and converts that into one reported reason, restoring the original template. The probe deliberately does not use mlx-vlm's recovery renderer, which returns
Noneinstead of raising for a model outside its family list and would therefore pass a template that cannot render at all.Capability is classified against the native template, so an override that stops marking where audio goes is revoked and the native template restored — otherwise the model would keep advertising an input it can no longer place.
Preset hint. The hint under Preset listed llama.cpp's controls unconditionally, so an MLX model was told a preset stores context length, speculative decoding and GPU layers — none of which that backend exposes — while omitting max seq length, which it does store. The list now resolves against the serving backend, and the names match the panel's own labels so the controls are findable.
isServedByMlxis introduced in its own commit. Whether MLX will serve a model is not the same question as whether its repo name says MLX: on a Mac with a working MLX stack every non-GGUF model loads through MLX, including plain safetensors repos.!isGgufalone would extend MLX-only controls to CUDA hosts.Reviewer notes and known limitations
max_seq_lengthis reported, not enforced, on the MLX path. It is stored on the model and surfaced ascontext_length, and it bounds the Max Tokens slider, but nothing truncates the prompt or sizes the KV cache. This predates the branch and is unchanged by it.applyPresetLoadConfigclears it explicitly. Also pre-existing, but more visible now that MLX has a template control beside the settings that are stored.Validation
Eligibility, refusal and restore paths were exercised against real MLX runtime objects rather than fakes, including the case where a processor renders from its own template while a nested tokenizer holds a named set. The template-override classification was measured across every model in a local Hugging Face cache (71 repos) to confirm the two render selectors agree on target selection and that no working template is refused.
chat_template_infowas verified to be unchanged frommainin every case, so no downstream consumer observes a difference.Added tests are kept below 30% of the added lines; the wider probe and cache-audit runs are recorded validation rather than repository tests.