Repository navigation
Studio: honor the OpenAI sampling parameters on the MLX backend - #9262
Conversation
|
Codex Review: Didn't find any major issues. More of your lovely PRs please. 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". |
Studio accepts an OpenAI `seed` in the chat-completion schema but only ever forwarded it to llama-server, so a seeded request against an MLX model — including a safetensors model, which on Apple Silicon is served by the MLX backend — sampled non-deterministically with no indication the field had been dropped. Seeding uses a request-scoped `mx.random.key` rather than `mx.random.seed`. Global seeding mutates thread-local state that later requests inherit, so a request that sets no seed but follows a seeded one would silently become reproducible; `mx.random.state` cannot be reliably saved and restored either. A per-request key keeps determinism inside the request that asked for it, and works identically on text and vision without depending on the mlx-vlm version. The seeded sampler reuses mlx-lm's own top-p/min-p/top-k stages instead of reimplementing them. Supplying a sampler suppresses the chain mlx-lm and mlx-vlm would otherwise build — mlx-vlm constructs its temperature/top-p/min-p/top-k sampler only when no sampler is passed — so anything not reused here would be silently dropped from seeded requests alone. Seed values are reduced modulo 2**64 on the MLX path. The field is shared with llama-server, which forwards every non-null seed including -1, while `mx.random.key` rejects negatives and anything at or above 2**64; normalizing at the point of use keeps the shared schema unnarrowed so no request that works today starts failing. Forwarding is gated on the backend declaring a seed parameter. The transformers backend has neither `seed` nor `**kwargs`, so forwarding unconditionally would turn its existing "ignores the seed" behavior into a TypeError. External providers are untouched. Validated against mlx-community/Qwen2.5-0.5B-Instruct-4bit and mlx-community/Qwen2-VL-2B-Instruct-4bit on mlx-vlm 0.4.4: identical output for a repeated seed, differing output across seeds, -1 equivalent to 2**64-1, boundary seeds (0, 2**64, -2**63, 2**70) all completing, the sampling chain still applied under a seed, and an unseeded request following a seeded one still varying across runs.
…GUF backends Both fields were accepted by the chat-completions schema and then discarded by every local path, so a request setting either sampled exactly like one that did not. They now reach MLX text and vision, and llama-server through both the direct and passthrough request paths. Where Studio samples -- the MLX backends -- semantics follow the presence penalty already implemented here: score the whole completion, exclude the prompt. mlx-lm's own presence and frequency processors window the last 20 tokens *including* the prompt, so using them would make the same request sample differently depending on the backend. Occurrence counts are scaled in float32 and cast once, matching llama-server; casting counts into a float16 logits dtype first rounds them above 2048 and overflows past 65504 repeats. llama-server is not made to match: Studio only forwards its native penalty fields, and it seeds penalty history with the prompt and windows it, so an identical request may still sample differently there. `logit_bias` ids outside the model's logit width are dropped rather than rejected, because the vocabulary a client biases against is the tokenizer's, which can be narrower. On MLX that bound is load-bearing: MLX does no bounds checking, so indexing a stray id is undefined behavior. The schema no longer constrains ids to be non-negative either, since a negative id is just another id the processors discard. `presence_penalty` now accepts OpenAI's documented [-2, 2] instead of [0, 2]. Widening a bound only admits requests that were previously rejected, so nothing that works today changes; a negative value boosts repetition, which every backend that reads it honors. The transformers backend is deliberately untouched. It declares neither field and takes no `**kwargs`, so the worker forwards both only to a backend whose signature declares them, exactly as it already does for the per-request seed: a safetensors model on Apple Silicon is served by the MLX backend and honors them, while on a CUDA host the fields stay accepted and ignored as they were before. Each tool-calling wrapper and payload builder re-declares its own argument list, which is how these fields came to be accepted and then dropped in the first place. Validated on mlx-community/Qwen2.5-0.5B-Instruct-4bit under a fixed seed: a request setting neither field is byte-identical to the previous behavior, each knob changes the output, and out-of-range bias ids are dropped without crashing. Presence charges a token repeated three times once; frequency charges it three times; prompt tokens are untouched by both.
Every MLX completion reported `finish_reason="stop"`, including one cut off at `max_tokens`. A client had no way to tell a finished answer from a truncated one, and a truncated tool call looked like a complete one. The transformers backend has the same defect and is deliberately left alone here; it is unreachable on Apple Silicon, where a safetensors model is served by MLX. The reason is now derived where generation ends and travels on the existing generation-stats channel, so it reaches all four chat response sites: plain streaming and non-streaming, and both of the server-side tool loop's. mlx-lm reports the reason directly. mlx-vlm does not, and at the limit a token count cannot separate a stop token sampled as the final allowed token from ordinary exhaustion, so that case is decided by the last token's identity. Which ids count as stopping is taken from what the runtime actually stops on: the tokenizer's stopping criteria first, then the model config that seeds them, then the tokenizer attribute. These disagree in practice — Kimi-VL's config lists two ids and its tokenizer reports a different one, so reading the tokenizer alone would report a real stop as truncation — and each source may be a bare int (Qwen2-VL) or a collection. Truncation outranks the tool-call upgrade, matching the rule the GGUF path already documents: a call cut off at `max_tokens` keeps `"length"` so the client knows the arguments may be incomplete, while the healed call stays attached. All four sites share one resolver instead of repeating the policy inline. An explicit Stop is not a completion, so the streams no longer synthesize a terminal chunk for one. Cancellation is latched once where generation exits rather than reread at the emit site: a Stop arriving while the finalization chunks are still being yielded must not suppress the terminal chunk of a completion that already finished, and the same latched value now decides the recorded request status. Non-streaming cancellation is unchanged either way. The plain handler drains its generator synchronously, so a cancel cannot be delivered to it in-process at all. The server-side tool loop drains through a worker thread and does observe one -- it records the request as cancelled -- but still answers with the partial text under `stop`, because this field's five values have no member for it. Both behave exactly as they did before this change; giving a cancelled reply a truthful terminal state needs a contract these values do not yet have. Because the reason rides on the stats the nudge retry already saves and restores, a discarded retry cannot leave its terminal state behind. The audio path is untouched: it generates greedily and reports its own terminal state. Validated on mlx-community/Qwen2.5-0.5B-Instruct-4bit and mlx-community/Qwen2-VL-2B-Instruct-4bit: truncation at 10 and 12 tokens reports `length`, natural termination reports `stop`, and the vision runtime resolves its stopping ids from the integer-valued source that previously raised.
The request schema advertises `stop` and the llama-server path applies it, but the MLX backends had no such parameter, so the same request returned different text per backend with no error. mlx-lm and mlx-vlm stop on token ids only, so a sequence spanning two tokens -- or spelled by a tokenization the vocabulary does not use -- never ends the turn there. Both generators yield cumulative snapshots, so the sequence is found in the decoded text instead, and the reply is cut before it. Text that could still grow into a sequence is held back for the same reason llama-server holds it: a client cannot unsee a fragment that the next token completes. A trailing replacement character is never matched, even once the turn has ended. A decode prints the same character for one the model wrote and for bytes that never finished arriving, and neither runtime resolves that: mlx-lm decodes what is left over with `errors="replace"` when generation stops, so its closing text carries the stand-in too, and mlx-vlm suppresses any text ending in the character at all. A sequence that can only match on such a character therefore does not match, while the character itself is delivered exactly as it is when no sequence was asked for. That cost falls on a caller that names one; the alternative, ending a turn on a character the model may never have written, would fall on every reply cut off mid-character. A turn that ends without the sequence arriving hands that fragment back as the ordinary text it turned out to be, so asking to stop on a sequence the model never writes returns exactly what the request would have returned without it. The text path is delivered once when a request names sequences, rather than snapshot by snapshot. It re-decodes every id each step instead of appending, so a later snapshot can revise characters an earlier one showed -- joining two tokens into a word neither spelled alone. Its consumers, the streaming route and the tool loop both, turn snapshots into deltas by length, so handing them a revised snapshot splices two renderings into text no snapshot contained, which can spell the very sequence the request asked to stop on. Nothing can unsend that, so no sampled text is sent until the turn's text has settled -- the prompt's own `<think>` prefill still goes out first, since the prompt cannot be revised by a later token. A caller streaming such a request therefore sees the reply arrive at the end of the turn rather than as it is written. The alternative is to stream this path from an append-only decode instead, which would remove the revisions rather than wait them out; that changes how every plain reply on this path is delivered, including requests naming none of these parameters, so it belongs to its own change rather than to this one. Requests naming no sequences stream as before, as do the paths whose text only ever grows: the native reasoning channel, vision, and audio input. Audio-input chat is a separate parameter chain that ignored `stop` for the same reason, and it forwards incremental deltas rather than the snapshots the text and vision paths diff, so its deltas are reassembled before the same matching runs over them. Its orchestrator command carries the sequences and the worker forwards them only to a backend whose signature declares the option, as the text branch already does, so a backend that never took one keeps ignoring it rather than raising TypeError. A stop sequence applies to the completion the model produced, so each producer matches its own sampled text -- ahead of both rewrites this backend performs on the way out. One puts the open `<think>` a reasoning template left at the end of the prompt back in front of the reply, so the frontend renders the block; the other rewrites a model's native reasoning markers as `<think>`. Matching the delivered text instead would end a turn on markup the model never wrote, so `stop: ["<think>"]` would return nothing at all on a reasoning template, and would never find the native marker a caller did ask to stop on. The cut runs before the reasoning normalizer, so no sampled sequence reaches it; the markers the normalizer itself writes are this layer's own, and go unmatched for the same reason the prefill does. The sequences are normalized once, above the branch that picks a backend, so the paths that return from inside it cannot disagree with the text paths about what the request asked for. A turn cut this way reports `finish_reason: "stop"` rather than the reason the runtime would have named for the token it happened to be on, and a reasoning block the sequence landed inside is closed as any finished one is: the closing marker is this layer's to emit, not the model's, so leaving it out would hand the client markup it cannot render. Only a cancelled turn is still left unfinished, because there more text was coming.
The llama-server path drains `n` sequential generations for a non-streaming request; the non-GGUF path rejected `n > 1` outright, so the same request succeeded on one backend and 400'd on the other. Plain text generation now serves extra choices the same way: one full generation per choice, stopping early if the turn is cancelled. The prompt is shared, so its tokens are counted once and only generated tokens accumulate, matching what the llama-server drain reports. The rejection moves down onto the paths that answer something other than a sample -- an audio turn returns one waveform, a transcription one transcript, and the tool loop runs turns rather than samples -- and streaming keeps its existing refusal.
702f4c7 to
e39b79d
Compare
|
Confirmed the non-GGUF path in studio/backend/core/inference/worker.py only forwards temperature, top_p, top_k and repetition_penalty, so stop, seed, logit_bias and response_format are accepted and dropped, and the finish reason is reported as length regardless. The direction is right, but this lands stop matching, n > 1, response_format, seed, penalties and usage accounting in one branch; could you split it so the stop-sequence work lands on its own first? |
…e served
`response_format` reached the request only through `extra="allow"`, so it was absent from the schema and invisible to clients reading it. Declaring it documents the contract and fixes its shape, so a value of the wrong kind entirely -- a bare string, say -- is turned away rather than reaching a backend as junk. What is inside the object stays the serving path's business. The router reads the value by attribute rather than off the chat model's field, so a request type that does not declare one is read the same way.
Guided decoding is the llama.cpp grammar engine's. A non-GGUF backend cannot constrain decoding, and previously dropped the field and answered with free text that silently violated the contract -- worse than refusing, because the client has no way to tell. It now returns 400 naming the parameter. Only `{"type": "text"}` is exempt: it is the default spelled out, constrains nothing, and is served exactly as a request naming no format. Every other object is a contract, including one whose type this build does not recognize and a text format carrying members it does not know -- guessing that an unfamiliar object constrains nothing is how a contract gets dropped silently again. The branch that answers speech refuses it as well, and says so where it stands: it returns before the routing below it, so nothing there can decide the contract's fate, and no grammar constrains a waveform. The GGUF paths that are not the passthrough refuse it too. Only an explicit request for Unsloth's tool loop reaches them carrying a contract, and neither that loop, which runs its own turns and forwards none, nor the ordinary generator below it, which has no such parameter, can keep one -- including when the loop's tool selection resolves empty and the request falls through to that generator.
The GGUF router asks the same question. Selecting the llama-server passthrough on the mere presence of the field sent an unconstrained request down a path whose only purpose is the grammar engine, and that path serves strictly less: a request naming `{"type": "text"}` was refused the n > 1 the ordinary path answers. An unrecognized type still goes there, where llama-server answers or rejects it as it did before.
`ChatCompletion.usage` defaults to a zero-filled object, so a body built without it reports zeros rather than nothing -- a client cannot tell the difference between a real count and a missing one. All three non-streaming non-GGUF shapes -- the plain reply, the server-side tool loop, and the audio-input reply -- left it at that default while the counts they needed were already in hand, in the same stats the monitor reads from. The plain reply now builds one usage object, so whatever the monitor is told is that same object and a client and the speed popover cannot disagree about the same turn. The monitor is still told nothing when no choice published stats, which is how it already reported a turn whose token count is unknown. For n > 1 the object carries the totals the llama-server drain reports -- the shared prompt counted once, generated tokens summed -- and drops the timings, which describe only the last choice and so describe neither. The tool loop reports what the whole loop spent. Each of its turns published into the one holder, so the reply described only the last turn and hid the tokens that produced the tool call; the turns are summed instead, as the llama.cpp tool loop already counts them, with the prompt taken from the last turn since it already contains the tool results the earlier turns produced, and the reported rates recomputed from those totals rather than left describing the turn they arrived with. A turn is folded in when it reports, so a loop a cancel cuts short still reports the turns that finished: the interrupted turn's own report is discarded with the rest of its cancelled output, and folds in as nothing.
0075d9d to
5213842
Compare
Two conflicts, both from main's non-blocking generation work. `routes/inference.py`: unslothai#9312 moved the non-streaming safetensors drain onto `_run_blocking_generation` so health checks stay responsive, while this branch had replaced the same drain with a per-choice `_one_choice` for `n > 1`. `_one_choice` is now async and drives main's `_drain_generate` through `_run_blocking_generation`, once per choice and once more for a nudge retry, so each sampled answer keeps its own seed and stats without holding the event loop. `core/inference/llama_cpp.py`: main hoisted the streaming payload's `_reasoning_kwargs` call above the rolling-context preflight; the branch's `logit_bias` addition sits beside where it used to be. Kept main's hoist and dropped the duplicate assignment.
Follow-ups found while reviewing the branch. All of them sit on top of the
existing commits rather than changing their direction.
test_vlm_seed_rides_on_the_sampler_not_a_seed_kwarg lost its body: the penalty
commit appended its parametrize block onto the docstring, so the one test
covering the seed design has been passing vacuously since. Restored, and rebuilt
so it runs off Apple Silicon too by recording what reaches the sampler builder
rather than calling into mlx.
The two numerical processor tests importorskip mlx, so they skip on the ubuntu
backend CI and mlx-ci.yml never collected studio/backend/tests at all. That left
the seed and penalty work with no executed coverage in any job. mlx-ci.yml now
runs test_mlx_inference_backend.py on the Mac runner.
_summed_tool_loop_stats had no test anywhere: replacing its body with
`return turn`, which is the exact bug it exists to prevent, passed the whole
backend suite. Added direct tests over the fold, and fixed two cases they found.
A final turn carrying usage but no timings dropped the loop's accumulated
timings, and one carrying timings but no usage dropped prompt_tokens entirely
and collapsed total_tokens to the summed completions. llama.cpp folds these
unconditionally and does not have the hole. completion_tokens_details now sums
with the completion it describes instead of being carried from the last turn
against a count it does not cover.
The pre-switch tool-policy gate still read response_format with bool(), while
the router reads it with _response_format_constrains_decoding. The two disagreed
in both directions: {"type": "text"} passed the pre-switch guard and was then
rejected on the GGUF local path after an auto-switch may have reloaded the
resident model, which is what that guard exists to prevent, and {} took the
local-confirm rejection with the wrong param name. Both use the router's
predicate now, so they cannot diverge.
A successful nudge retry reported only the retry's usage. Both attempts were
generated, and this branch is what promotes that number from the monitor into
the OpenAI usage field a caller bills against, so both are now folded, with the
winning attempt's prompt. The discarded-retry branch is folded the same way for
symmetry; its test is renamed and keeps asserting the delivered attempt's prompt.
The MLX audio-input producer never derived a finish_reason, so a turn that
exhausted max_tokens reported "stop". Pre-existing, but text and vision are
fixed here and leaving audio out makes the three siblings disagree.
_mlx_stop_token_ids returned () when its first source was present but empty,
never consulted a singular tokenizer.eos_token_id, and could raise on a numpy
scalar from inside a caller's finally. An empty stop set misreads every real
stop as truncation. Token id 0 is kept, since 0 is a valid id.
The VLM path left a reasoning block unclosed when a stop sequence and a cancel
landed on the same step; the text and audio paths already guarded for this.
Also corrected the n loop comment: the non-GGUF drain guards index 0 so a
cancelled turn still answers with one choice, which the llama-server drain it
claimed parity with does not do.
|
Pushed a follow-up commit to this branch rather than listing everything inline. The direction here is right and most of the implementation holds up well under scrutiny, so the changes sit on top of your commits rather than redoing them. What holds up
The request-scoped The one that matters most
That compounds with a coverage hole in CI. I restored the seed test and rebuilt it to record what reaches the sampler builder rather than calling into mlx, so it now runs everywhere, and added Same shape of problem with One regression worth flagging
Separately, and I have left this one alone deliberately: Also in the commitA successful nudge retry reported only the retry's usage. Both attempts generated tokens, and this branch is what promotes that number out of the monitor and into the OpenAI The MLX audio-input producer never derived a
The VLM path left a reasoning block unclosed when a stop sequence and a cancel landed on the same step. Text and audio already guarded for this; TestingBackend suite, full CI leg reproduced locally with the workflow's ignore and Beyond the suite I built a platform matrix simulation, since the risk here is not MLX itself but what happens to everyone who is not on a Mac. The route now puts All 54 cases pass on this branch. The same file produces 23 failures on the merge base, so it is measuring something. Forcing the gate to always return True makes the transformers signature raise I also ran the pure helpers in a bare venv with no torch, no mlx and no numpy, on both Python 3.13 and the 3.11 CI floor, and confirmed no changed file imports mlx at module level or on any path a non-Apple install takes. Reverting each of my two production fixes makes the corresponding simulation checks fail, so they are pinned rather than decorative. Nothing here is a substitute for real MLX. Every numerical claim about sampling, RNG streams and kernels stays unverified until it runs on Apple Silicon, which is the reason for the mlx-ci change. On splittingStill worth doing, and the shape is a little more awkward than it first looks: |
Both sides appended tests at the end of test_mlx_inference_backend.py with no overlapping names, so the conflict resolves to keeping both. main's PRNG work is the KV quantization probe's mx.random.seed capture and rewind; this branch seeds per request with mx.random.key and never touches the global state the probe saves, so the two are independent.
Both from the Codex round on 5cd980b. The nudge retry saved the first attempt's stats with a read, not a take, so a retry that raised before publishing its own report left stats_holder pointing at that same object. The exception branch then folded it into itself and billed its completion tokens twice: a 3-token first attempt was reported as 6. Popped now, so a fresh report is distinguishable from the stale one and every branch folds at most two distinct reports. MLX puts its reused prefix inside usage.prompt_tokens but named the count only under timings.cache_n, so the usage object this branch newly returns reported cached_tokens 0 on every prompt-cache hit even though the backend had the number. llama-server already forwards the real count, so the two backends disagreed on a field a caller reads for cost attribution. _build_generation_stats now names it where the rest of the usage lives. That surfaced a latent split in the n loop: prompt_tokens was chosen last-truthy-wins while prompt_tokens_details was chosen first-non-None-wins, two rules over the same shared quantity. With MLX previously reporting no details it was unreachable; naming cached_tokens makes it reachable, and the nudge does rebuild a longer prompt for some choices, so a reply could claim more cached tokens than prompt tokens. Both now come from the choice that supplied the count. The same pairing is applied inside the tool-loop fold, where a turn that reports no prompt count of its own inherits the loop's details along with it. Three regression tests, each mutation-checked: reverting the pop doubles the count, splitting the selection rules reproduces cached_tokens 1100 against prompt_tokens 1000, and dropping the source field empties the details.
From the Codex round on a12a58f. A checkpoint's config is a dict on some models and an object on others, and it sits under config or _config: exactly the spread _mlx_vlm_model_config already walks to find a model_type, and the shape this file's own tests use. The EOS lookup read it with getattr only, so the dict half returned nothing and the search fell through to the tokenizer, which is the source the priority order exists to outrank when the two disagree. Reproduced: with a dict config listing [1, 2] and a tokenizer saying 9, the ids resolve to (9,) and an EOS of 2 sampled on the last allowed token reports finish_reason "length" instead of "stop", which is the reporting bug 02cc356 exists to fix. _mlx_config_field reads either representation across both attributes. The tokenizer stays the fallback when no config carries the field. Parametrized over all five shapes and mutation-checked: restoring the getattr-only read fails four of the six cases.
|
Codex Review: Didn't find any major issues. Can't wait for the next one! 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". |
Post-convergence comment pass over the comments added here, not the files they sit in. Comments only, AST-verified against 507c1e7 with docstring edits allowed: the one docstring touched is on an internal helper, not a route.
|
Round summary, so the state is on the record. ReviewsConverged on 507c1e7, then a comments-only commit landed on top so a final round is in flight to move the approval onto the true head. Three items across three rounds, all genuine, all fixed with a mutation-checked regression test:
Each fix is mutation-checked: reverting the pop doubles the count, splitting the selection rules reproduces cached 1100 against prompt 1000, and restoring the getattr-only read fails four of six config shapes. Cross-platformReplicated onto a staging repo rather than the org queue, per OS on the same head:
The macOS runner did not ship an mlx wheel, so its 12 skips are the same ones Linux reports. The MLX numerical tests still only execute where mlx is installed, which is what adding The three Windows failures are pre-existing, not this branch. All three sit in Repo tests (CPU)Red, and not from this branch. It fails two assertions in SplittingThe request stands, with one wrinkle worth naming: stop-first is not a clean cherry-pick. |
…e ones From the Codex round on 7cef801. _choice_seed exempted every negative seed from the per-choice offset on the llama-server drain, on the premise that llama-server reads a negative seed as "pick one at random". That is true of -1 only. The sampler seed is a uint32 (common/common.h: `uint32_t seed = LLAMA_DEFAULT_SEED`) and exactly one value, LLAMA_DEFAULT_SEED = 0xFFFFFFFF (include/llama.h), selects a random draw; the server README documents the sentinel as -1 specifically. -1 is the only request seed that converts to it. -2 lands on 0xFFFFFFFE, an ordinary fixed seed, so a GGUF request with seed -2 and n 3 sent the same fixed seed three times and returned three copies of one run. Exempting only -1 fixes that but introduces a second bug: the offset then walks onto the sentinel, so seed -2 with n 3 serves -2, -1, 0 and the middle choice samples at random where the caller asked for a fixed run. The offset is now taken in the same uint32 domain llama-server reads, modulo 0xFFFFFFFF, so the sentinel is unreachable by offsetting and consecutive choices stay distinct. Non-negative seeds below 2^32 are unchanged, choice 0 is still the caller's own seed, and the MLX side is untouched: it maps every seed onto its key domain, so nothing is exempt there. Regression test covers both failure modes; restoring `seed < 0` and dropping the uint32 offset each fail it.
|
Codex Review: Didn't find any major issues. More of your lovely PRs please. 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". |
|
Reviews have converged. Codex approved 979e68e and the only commit on top is a pre-commit.ci whitespace reformat, so there is no human change left to re-review. Six rounds, four items, all genuine, all fixed with a mutation-checked regression test, all replied to. Settled threads pruned. The last round found a good one. Worth recording that exempting only CIBoth red checks are pre-existing on main and are not fixable from this branch.
Both look worth their own issues, since they are red for every PR right now. |
modelReadsSamplingSeed dropped the seed for MLX, which reads one since unslothai#9262: generate_chat_response takes it, _make_seeded_mlx_sampler uses it, and worker.py's _backend_declares gate passes it through. The old predicate answered from activeGgufVariant, ggufContextLength and the .gguf suffix, none of which is true for a loaded MLX model, so the panel hid the control and the adapter stripped the pin. It now takes the models[] summary the request body already reads isGguf from for context_overflow and returns isGguf || isMlx, so there is one notion of "is this a GGUF" per request and both call sites pass the same argument. The transformers backend still declares no seed kwarg, so it is still the one that drops it. The Seed box keeps a raw draft while it is being typed into and clamps on blur. Clamping every keystroke rewrote the box mid-entry, which is the trap NumericValueInput's blur commit exists to avoid. The hint now names Parallel Slots at 1 and Speculative Decoding off. unslothai#9090's table shows seed plus temperature 0 plus top_k 1 still producing 3,960 against 150 characters without them, so the old wording promised more than the seed delivers. The ceiling test justified the bound with a run whose server-drawn seed could not be replayed. No chat path reports a seed back, so that comment is gone.
modelReadsSamplingSeed dropped the seed for MLX, which reads one since unslothai#9262: generate_chat_response takes it, _make_seeded_mlx_sampler uses it, and worker.py's _backend_declares gate passes it through. The old predicate answered from activeGgufVariant, ggufContextLength and the .gguf suffix, none of which is true for a loaded MLX model, so the panel hid the control and the adapter stripped the pin. It now takes the models[] summary the request body already reads isGguf from for context_overflow and returns isGguf || isMlx, so there is one notion of "is this a GGUF" per request and both call sites pass the same argument. The transformers backend still declares no seed kwarg, so it is still the one that drops it. The Seed box keeps a raw draft while it is being typed into and clamps on blur. Clamping every keystroke rewrote the box mid-entry, which is the trap NumericValueInput's blur commit exists to avoid. The hint now names Parallel Slots at 1 and Speculative Decoding off. unslothai#9090's table shows seed plus temperature 0 plus top_k 1 still producing 3,960 against 150 characters without them, so the old wording promised more than the seed delivers. The ceiling test justified the bound with a run whose server-drawn seed could not be replayed. No chat path reports a seed back, so that comment is gone.
* studio: add a sampling seed to the chat run settings InferenceParams had no seed, so a Studio generation could not be reproduced even though ChatCompletionRequest.seed already reached llama-server. Add the field, default null, and surface it in the Sampling section as a blank-means- random text box. The seed is sent only when set and only when the loaded model decodes through llama-server, which modelReadsSamplingSeed answers for the panel and the request body alike. Range is 0 to 4294967294: llama.cpp reads a uint32 and spends 0xFFFFFFFF on LLAMA_DEFAULT_SEED. Persisting it needed the storage sanitizer to range-check the value and pass an explicit null, ChatInferenceSettings to accept the key at all since it is extra="forbid", and PresetOwnedParams to carry it so a preset captures the pin. * studio: hide the sampling seed for audio-output models An audio-output GGUF (isAudio and no hasAudioInput) answers through the generateAudio branch in chat-adapter.ts, whose request carries no seed, so the control let a user pin and persist one that every audio run ignored. modelReadsSamplingSeed now takes the active model summary and excludes that case. A model that takes audio in still decodes through llama-server and keeps the field. * studio: offer the sampling seed on mlx and commit the field on blur modelReadsSamplingSeed dropped the seed for MLX, which reads one since #9262: generate_chat_response takes it, _make_seeded_mlx_sampler uses it, and worker.py's _backend_declares gate passes it through. The old predicate answered from activeGgufVariant, ggufContextLength and the .gguf suffix, none of which is true for a loaded MLX model, so the panel hid the control and the adapter stripped the pin. It now takes the models[] summary the request body already reads isGguf from for context_overflow and returns isGguf || isMlx, so there is one notion of "is this a GGUF" per request and both call sites pass the same argument. The transformers backend still declares no seed kwarg, so it is still the one that drops it. The Seed box keeps a raw draft while it is being typed into and clamps on blur. Clamping every keystroke rewrote the box mid-entry, which is the trap NumericValueInput's blur commit exists to avoid. The hint now names Parallel Slots at 1 and Speculative Decoding off. #9090's table shows seed plus temperature 0 plus top_k 1 still producing 3,960 against 150 characters without them, so the old wording promised more than the seed delivers. The ceiling test justified the bound with a run whose server-drawn seed could not be replayed. No chat path reports a seed back, so that comment is gone. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * studio: keep the sampling seed with the chat, not the installation The seed was persisted per model and installation-wide, so a pin taken in one chat fixed the draw for every other chat opened on that model, and reopening the first could not bring its own value back. Every other per-turn sampling control in the panel already travels with the conversation; maxTokens is out for a reason that does not apply here, since a context budget belongs to the model that loaded. seed joins THREAD_SCOPED_PARAM_KEYS and ChatThreadSettings, with the same 0 to 4294967294 bound and boolean guard the installation copy uses. It is the first thread-scoped value whose cleared state is null rather than absent, so the three fallbacks that read a snapshot key can no longer use ??: null there is the chat's own choice, and coalescing it would hand back the installation pin the user had just dropped. firstSetThreadScopedValue takes the first value that is not undefined instead. * studio: gate the sampling seed on a model with no catalog row, and save the seed being typed Two ways the seed reached the wrong answer. A locally scanned model is in neither /api/models/list nor the external ids, so its models[] summary is minted from the load or status response. Both hops that mint one, syncModelCapabilities and ensureActiveModelInStoreList, dropped is_mlx, so modelReadsSamplingSeed read false for a model MLX was serving: the panel hid the field and the adapter stripped the pin. Both now carry it, the same way hasVideoInput is carried for the GGUF row that /api/models/list leaves incomplete. Clicking Save on a preset blurs the seed box during mousedown, but React has not re-rendered by the time that button's onClick runs, so the save wrote the seed from before the entry, and over an otherwise-unmodified preset the button was still disabled and the first click did nothing at all. committedSeed computes what blur would land on, and the save, the unsaved-changes check and the blur handler all read it, so no two of them can answer differently. NumericValueInput bridges the same gap with commit(). * studio: report a thread setting the snapshot never held as absent, not as null The thread response dumped every unset field as null, which runtime-provider.tsx notes and sanitizeThreadScopedSettings drops. That worked while no thread-scoped setting had a meaningful null. seed does: null means this chat draws its own rather than taking the pin it would otherwise inherit, so a snapshot written before the field existed read as a chat that had cleared it, and opening one wiped the seed the chat should have inherited. A field_serializer on ChatThread.settings dumps with exclude_unset, so the three cases separate on the wire: absent for a key the snapshot never held, null for a pin the chat cleared, a number for one it set. thread_from_row validates the stored dict, so model_fields_set is exactly the stored keys, and the test drives it through a real response_model to cover FastAPI re-validating the return value. POST /threads stores payload.model_dump(), so a create now stores the keys it was sent instead of every key with nulls. The PATCH path already did that. * studio: carry the MLX flag through every model summary the seed gate reads QueuedModelCapabilities is a Pick over ChatModelSummary that left isMlx out, so a queued run adopting a resident MLX model with no catalog row minted a private summary that looked like a backend with no seed support, and the request dropped the pin. Enumerating the rest of the family found two more: the queued snapshot at snapshotVisibleModelState, and the compare composer's own models[] sync, which mints a row the same way. Four places mint or refresh a summary and three were missing the flag. Replaced the two spot checks with a rule over the capability cluster: every literal that writes hasVideoInput has to write isMlx too, named by file and line when it does not. Verified by dropping the flag at each of the five sites in turn. * studio: drop a sampling seed entry the box was taken away from Blur is the only commit the Seed field has, and a browser fires no blur when a focused element is removed: focus moves to the body and no handler runs. A draft left behind when the field goes away, or when the loaded model changes underneath it, therefore stayed in state with nothing able to clear it, went on answering for committedSeed, and so marked the preset modified with the field no longer on screen and handed a preset save a seed the user had abandoned. Discard the draft rather than commit it when the field's model or visibility changes: an entry walked away from was never confirmed, least of all for whichever model is loaded now. * studio: require the seed gate's flags on the rows the store holds `modelReadsSamplingSeed` answers from `isGguf`, `isMlx`, `isAudio` and `hasAudioInput`. All four were optional, so a row that left one out did not fail — it read as `false` and the gate answered wrong, hiding the seed field for a model whose backend does read one. Two commits on this branch are each a mint site that was missed that way, and the compiler had nothing to say about either. The flags stay optional on `ChatModelSummary`, because not every summary is a catalog row and some are built by tests with no opinion on a backend. What changes is the shape the store holds: `models[]` and `setModels` now take `ChatModelRow`, a summary that has stated the four, and the gate takes `SeedGateFlags` so it cannot be handed a shape that has not. Anything minting a row therefore has to answer, and answering is cheap — every mint site already holds the backend response the flags come from. That named a fifth site the earlier passes had not reached: the default-model row in the chat adapter stated neither `isMlx` nor `hasAudioInput`. * studio: share the boolean guard and the seed bound between the settings models The guard was copied into a third model with the sampling seed, and the uint32 ceiling was spelled out twice. Both are one rule: bool subclasses int, so lax mode takes `true` for a number nobody set, and llama.cpp keeps 0xFFFFFFFF for its draw-one sentinel. The bound sits inside the Optional rather than beside it. Outside, pydantic compares None against it and a cleared pin raises TypeError instead of validating -- the settings and thread-settings tests both catch that, which is how the placement was settled. * studio: trim sampling seed comments that the code already states Four comments repeated what the line beside them says. The seed bound in the thread-scoped table names a constant whose own definition carries the llama.cpp rationale; the preset entry said a preset captures the seed, which is the `Pick` above it, in place of saying why the value is normalised; the adopted-model row explained that the seed gate reads `isMlx`, which the summary type now requires outright; and the storage branch restated its own `null` test ahead of the reason that null is kept. The remaining comments record constraints the code cannot: the blur gap in the numeric input, the audio-output path that answers through generateAudio, the transformers backend's missing `seed` kwarg, and the hydration paths the bound applies to. * studio: say what the abandoned-draft test does not prove The test pins the shape of the seed-draft reset and read as though it proved the reset runs. It cannot: this project has no DOM environment, so nothing here mounts the panel or watches the effect fire. It now states that limit, and where the claim behind it actually comes from — removing a focused input was measured in a browser to run no blur and no focusout. --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Lyxot <[email protected]>
Problem
Studio's chat-completion schema advertises the OpenAI sampling parameters, but the MLX backend only ever forwarded some of them. The rest were accepted, dropped, and never mentioned again — so the same request returned materially different results depending on which backend happened to serve it, with no error and nothing in the response to say a parameter had been ignored. This covers safetensors models on Apple Silicon, which are served by the MLX backend rather than by transformers.
Two of the affected parameters were worse than merely ignored: a request naming
stopgot a completion that ran past the sequence it asked to stop on, and a request namingresponse_formatgot free text in place of the contract it asked for.This PR brings the MLX backend to parity with what the llama-server path already accepts, and fixes two reporting bugs found along the way.
Scope
The changes fall into two groups, and it is worth being precise about which reaches what:
stop,seed,frequency_penalty,logit_bias, and thefinish_reasonfix. The worker forwards these only to a backend whose signature declares them, so the transformers backend — which serves safetensors anywhere other than Apple Silicon — keeps its existing behavior of ignoring them rather than raisingTypeError. Bringing that backend to parity is separate work and is not attempted here.n > 1, theresponse_formatrefusal, and theusageobject on non-streaming replies. These sit above the backend switch, so transformers-served models get them too.What changed
stop(MLX) — mlx-lm and mlx-vlm stop on token ids only, so a sequence spanning two tokens, or one spelled by a tokenization the vocabulary does not use, never ended a turn there. Sequences are now found in the decoded text and the reply is cut before them, on the text, vision and audio-input producers. Text that could still grow into a sequence is held back, as llama-server holds it, and handed back as ordinary text if the turn ends without the sequence arriving — so naming a sequence the model never writes returns exactly what the same request returns withoutstop. A turn cut this way reportsfinish_reason: "stop", and a reasoning block the sequence landed inside is closed, since that closing marker is this layer's to emit rather than the model's.n > 1(every non-GGUF backend) — the per-choice body became a closure called in a loop;n = 1is unchanged. The prompt is counted once and completion tokens accumulate, matching what llama-server reports. The blanket rejection moved off the chat path and onto the paths that answer something other than a sample — audio, transcription, and the tool loop — which cannot serve more than one.response_format(every non-GGUF backend) — promoted frommodel_extrato a declared field, so the schema documents it and a backend without a grammar engine can refuse it by name with a 400 rather than silently answering free text.{"type": "text"}names the default and constrains nothing, so it is served as a no-op rather than routed as a contract; anything else is treated as a contract the caller expects to be kept.seed(MLX) — honored via a request-scopedmx.random.keyrather than the globalmx.random.seed, because global seeding mutates thread-local state that later requests inherit: an unseeded request following a seeded one would silently become reproducible. The seeded sampler reuses mlx-lm's own top-p/min-p/top-k stages, since supplying a sampler suppresses the chain the runtimes would otherwise build, and anything not reused would be dropped from seeded requests alone.frequency_penaltyandlogit_bias(MLX, and llama-server) — honored on both. Token ids are not range-checked, matching MLX, which drops a stray id at the logits processors rather than failing the request.finish_reason(MLX) — the MLX backends reported"length"for turns that ended for other reasons. It now reports"length"only when the token limit was actually reached.Token usage (every non-GGUF backend) — non-streaming non-GGUF replies carried no
usageobject at all, though the backend already had the counts in hand. They now report it. For the tool loop, every turn's generated tokens are summed with the last turn's prompt, as the llama.cpp tool loop reports them; reporting only the final turn hid the tokens that produced the tool call.Design notes and tradeoffs
Stop sequences match what the model sampled, not what the client is shown. This backend performs two rewrites on the way out: it puts the open
<think>a reasoning template left at the end of the prompt back in front of the reply, and it rewrites a model's native reasoning markers as<think>. Matching the delivered text instead would end turns on markup the model never produced —stop: ["<think>"]would return nothing at all on a reasoning template — and would never find the native marker a caller did ask to stop on. This matches llama-server, which likewise matches its own raw text.A
stoprequest on the plain MLX text path is delivered at the end of the turn rather than streamed. That path re-decodes every token id each step instead of appending, so a later snapshot can revise characters an earlier one showed — joining two tokens into a word neither spelled alone. Both consumers turn those snapshots into deltas by length, so handing them a revised snapshot splices two renderings into text that no snapshot contained, which can spell the very sequence the request asked to stop on. A stream cannot unsend, so nothing is sent until the text has settled. This is scoped to requests namingstopon that one path: requests naming none stream as before, as do the native reasoning-channel, vision and audio-input paths, whose text only ever grows. Streaming this path from an append-only decode would remove the revisions rather than wait them out, but that changes delivery for every plain reply on the path, so it is left to its own change.A trailing replacement character is never matched, though it is always delivered. A decode prints the same character for one the model wrote and for bytes that never finished arriving, and neither runtime distinguishes them: mlx-lm decodes what is left over with
errors="replace"when a turn ends, so its closing text carries the stand-in, while mlx-vlm suppresses any text ending in that character. Matching it would end turns on a character the model may never have written.Refusals are by name. Where a parameter cannot be served, the request is refused with a 400 naming the parameter rather than answered with something that quietly violates it. This applies to
response_formaton backends with no grammar engine, including the speech branch, which returns before the routing that would otherwise decide the contract's fate.Compatibility
Requests that name none of these parameters are unaffected. The existing rejections that moved did not become more permissive: each moved onto the specific path that cannot serve the parameter, so requests that were answered before are still answered. Widening the penalty range to OpenAI's documented
[-2, 2]only admits requests that were previously rejected.Forwarding is gated on the backend declaring the parameter, so a backend that never took one keeps ignoring it rather than raising
TypeError. The transformers backend is therefore untouched by the MLX-only half of this change: safetensors models served off Apple Silicon behave exactly as they do today.Validation
Focused suites for every touched component, plus a targeted union of every suite that references a changed symbol:
The one failure in that run,
test_mcp_servers.py::test_mcp_specs_match_the_installed_sdk_dump, reproduces identically onmainand is unrelated to this change.Each commit was also checked out and tested standing alone, and every added test was mutation-checked: the production change it covers was reverted or weakened, and the test confirmed to fail.
The parameters were then exercised end to end against real models rather than fakes:
unsloth/gemma-4-E2B-it-UD-MLX-4bit(MLX, vision and audio input) —stopcutting the reply and correcting the reason, a non-matchingstopreturning the unmodified baseline, bare-stringstop,n = 3with summed usage,response_formatrefused by name,{"type": "text"}served as a no-op, streaming with and withoutstop, image input, audio input, andseedreproducing across runs while an unseeded request following a seeded one still varies.mlx-community/Qwen2.5-0.5B-Instruct-4bit(MLX, plain text path) — the same set, including the end-of-turn delivery described above.unsloth/gemma-4-E2B-it-GGUF(llama-server) — audio input, for backend comparison.The transformers backend was not exercised, since the MLX-only parameters never reach it and the route-level changes are backend-agnostic.