Repository navigation
Studio: Stop at the requested stop text on transformers models - #10812
Conversation
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
@codex review |
|
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 |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 5067dcf19d
ℹ️ 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".
| ) | ||
| + 1 | ||
| ) | ||
| self._publish(cut) |
There was a problem hiding this comment.
Withhold rewrite-prone suffixes before publishing
When decoding cleanup rewrites an already-streamed suffix, this publishes text that can no longer be retracted. For example, tokens decoding incrementally as "Hello world", " ", "." publish the space here, but the cumulative decode is "Hello world."; with stop ".", the response therefore becomes "Hello world " instead of "Hello world". Fresh evidence in this revision is test_a_stop_created_by_decode_cleanup_of_settled_text_still_matches, which explicitly asserts that extraneous space after the claimed fix. Keep enough undecided suffix context to avoid publishing characters that a subsequent decode may rewrite.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not changing this. The streamed output here is identical to transformers' own TextIteratorStreamer without any stop, which also publishes up to the last space and cannot retract it. On 5067dcf with the real GPT-2 and Llama-3.2 tokenizers, the stock streamer and this wrapper (with an unmatched stop) produced the same text in all 12 cases checked, cleanup on and off. That includes the lone space token followed by "." under cleanup, where both return "Hello world More text after", and natural text with spaces before punctuation, where both equal the full decode. The earlier full-decode version of this wrapper also returned "Hello world " for stop ["."]. So this is existing streaming behavior for every transformers request, needs the model to sample a standalone space token before punctuation, and costs one extra space. Withholding suffixes only when a stop is set would make stop requests stream differently from the stock path. The test documents that parity.
|
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". |
Review + GitHub Actions reproductionPinned review:
The chat UI never sends GitHub Actions A/B (same workflow and probe on both branches; the only difference is whether this PR is merged onto
Real Studio on an L4 GPU (
Stop matching cost on an L4 (same model, 6,000 token replies, alternating requests with no
The overhead of the full re-decode grows with reply length (CPU decode alone is ~8 ms/token at 32k tokens), so long reasoning replies are where it matters. Tests: all 16 tests in Conclusion: stop sequences are now honored for transformers text and vision generation, generation ends early instead of running to the token limit, and requests without |
UI evidence: Studio API monitorThe chat page itself cannot show this change, because Studio's chat UI never sends a stop sequence. The change is visible in Studio's API monitor ( Real Studio on an NVIDIA L4 (Linux, CUDA, so the model runs on the transformers backend; macOS would send it to MLX),
Result: before this PR the transformers backend ignored The Studio chat page itself is unchanged (it sends no |
|
Confirmed that on main the stop field is gated out at studio/backend/core/inference/worker.py so transformers-served models run past it to the token limit, and the API monitor before/after you posted shows the request ending with finish_reason stop. Will get this reviewed. |
Refresh the branch onto main b3dfd08 so CI re-runs on a current base. The 2026-09-11 Repo tests (CPU) failure on this PR was a pre-existing flake: the same job failed on main d7e5c6b and passes on the two newest main runs, and the repo suite gives an identical 22 failed / 18590 passed on the merge base and on this head locally. No source change.
Independent verificationReviewed The gap is real and the fix is complete end to end. Qwen2.5-0.5B-Instruct, greedy, stop lifted out of the control reply, 80 token budget:
Same result on CPU (base 39 tokens including the stop word, head 15). Vision on a real The two things your own tests stop short of, both clean.
Differential simulation. I drove The only differences found: on the two SentencePiece tokenizers with 4-space indented code, a request that carries a One version note. The comment at Non-regression. Studio backend suite on the pinned transformers: head 41,261 passed vs base 41,246, identical failure sets apart from one head-only On the red Cross-platform, the 16 tests with Not covered, to be explicit: native MLX on Apple Silicon, a real AMD/ROCm GPU, WSL, and gpt-oss Harmony with real weights (covered only through the real One follow-up, out of scope here: a tools or |
|
@codex security review |
|
CI after the main merge: 30 of 32 green, one pending, and one failure that is not this PR. Backend CI The earlier |
clean_up_tokenization_spaces deletes the space in " .", " ?", " !", " ,", " ' ", " n't", " 'm", " 's", " 've" and " 're". Split across tokens, such a rewrite is invisible from the short window: with ids decoding as "ca", " ", "n" and "'t", the prefix is "n" and the window "n't", so startswith holds, the concatenation keeps the space and settled text stays "ca n't" while a full decode gives "can't". A stop of "can't" then never matches and generation runs on to the token limit, which is the behaviour this feature exists to prevent. Re-read the few tokens behind the join, but only when the join looks like one of those rules (a space within the last four characters of settled text and new text starting with one of .?!,'n), so ordinary prose keeps the short window: measured 3.0 decoded ids per token over a 1,201 token reply, unchanged. Reproduced before the fix with the real gpt2, Llama-3.2 and Qwen2.5 tokenizers on transformers 5.5.0, where the full decode is "can't" and the wrapper streamed "ca n't" with the stop unmatched; after it, all three match.
The previous guard watched only the character right after the space, so it caught " n't" (which completes one character later) and missed " 've" and " 's" when the apostrophe is its own token: with ids decoding as "we", " ", "'", "v", "e" the settled text stays "we 've" while a full decode gives "we've", and a stop of "we've" is never found. Confirmed with the real gpt2 and Llama-3.2 tokenizers on transformers 5.5.0 for can't, we've, it's and we're, all four unmatched before and matched after. Watch instead for any rule that could still complete at the end of the text, and gate the whole thing on the decoder actually applying cleanup, which is pure cost otherwise: Qwen, Gemma, Mistral and gpt-oss ship it off, and transformers 5.17 ignores it for every BPE tokenizer. Measured 3.0 decoded ids per token over a 1,201 token reply with cleanup on and off alike, unchanged.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: c0076e0432
ℹ️ 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".
| cut, matched = _mlx_stop_cut(self.text[start:], self.sequences) | ||
| self.cut = start + cut |
There was a problem hiding this comment.
Match stop strings after removing protocol framing
For Harmony and recipient-channel reasoning models, self.text is the raw decoded protocol rather than the text emitted to the client, so this search can match hidden framing. For example, Muse/Glimmer transitions to its answer with to=user<|message|>; a request using stop=["user"] therefore terminates at that header before emitting the answer even though user never appears in the visible response. Stop matching should mask protocol controls or operate on the normalized channel content while still excluding synthetic tags.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not changing this here. The behaviour is real, but it is the MLX backend's shipped behaviour, and matching MLX is the point of this PR.
On main, the MLX path builds sampled from native_token_decoder.decode_stream_token(...), which preserves the native channel tokens, and then calls _mlx_stop_cut(sampled, sequences) on exactly that text (studio/backend/core/inference/mlx_inference.py:2968-2982). So a stop of "user" already cuts at a to=user<|message|> header on Apple Silicon today. Masking framing on the transformers side alone would make the same request behave differently on the two backends, which is the divergence #9262 and this PR exist to close.
Whether stop should match raw protocol or normalized channel content is a real question, but it is one decision for both backends, so it belongs in its own issue and change rather than in the PR that brings transformers up to parity. Happy to open that separately.
| elif len(window) > len(prefix): | ||
| self.settled += window[len(prefix) :] | ||
| self.prefix_offset = self.read_offset | ||
| self.read_offset = len(self.token_ids) |
There was a problem hiding this comment.
Avoid copying the settled reply for every token
For any stop-enabled response, each decoded tail is appended to an immutable cumulative string here while self.text still aliases the previous value. This forces the entire settled reply to be copied on every token, making long generations quadratic in output length despite the bounded decode window; the added performance test only counts tokenizer decoding work and does not detect these string copies. Accumulating decoded chunks in a linear-time buffer would avoid increasingly expensive per-token work.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Measured, and it does not show up. Real Qwen2.5 tokenizer, one token per put, an unmatched stop, wall clock per token:
| reply tokens | this wrapper | the streamer it wraps, no stop, today's code |
|---|---|---|
| 2,000 | 12.9 us/token | 158 us/token |
| 8,000 | 13.0 us/token | 591 us/token |
| 16,000 | 13.1 us/token | 1,164 us/token |
| 32,000 | 13.6 us/token | 2,315 us/token |
The wrapper is flat across a 16x range (12.9 to 13.6 us/token, +5%), so the copy is there but is not the cost of the loop; 32,000 tokens cost 436 ms of CPU in total, against roughly ten minutes of generation for that many tokens on a GPU. The stock TextIteratorStreamer on the same ids is the genuinely quadratic one, because it re-decodes its whole token cache every token: 74 seconds for the same 32,000 tokens, about 170x the wrapper. The consumer side does the same thing already, since _append_stream_delta yields the whole cumulative cleaned reply every token.
So this would trade readability for an effect that is under a percent of the path it sits in, while a much larger quadratic term next to it is untouched. Worth doing as its own change across the streaming path if long replies ever become CPU bound, not here.
|
Codex Review: Didn't find any major issues. Hooray! 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". |


Chat requests can ask the reply to stop at certain text. On NVIDIA GPUs, models run with transformers ignored this, because the stop setting was never passed to them. The reply kept going past the stop text until the model finished or hit the token limit, and then reported that it ran out of tokens. #9262 notes that this backend was separate work.
Now the stop text is passed through for text and vision models. Streamed text that could turn into the stop text is held back briefly, the reply ends right before it, and generation stops so no extra tokens are spent. The reply then reports that it stopped normally.
Requests without stop text are unchanged, and audio input requests still ignore it. Tested on a GPU with Qwen2.5 0.5B and the stop word "sleek". Before, the reply ran for all 80 tokens and included the word. After, it ended after 17 tokens, right before the word.
Maintainer verification: API monitor, before and after
Two isolated Studio installs built from this PR's own tree, BEFORE at merge base
b3dfd088band AFTER at head89a38d3c8, each with its own home, port and password, both servingunsloth/Qwen2.5-0.5B-Instructat 4,096 ctx. The chat page cannot show this change because it never sends a stop sequence, so the surface photographed is the API monitor, which records what the OpenAI-compatible server actually did.The request in the detail pane is
Count from one to one hundred in words, one number per line.withstop=["twenty"], temperature 0 and a 200 token budget.b3dfd088b89a38d3c8The sentence request in the same run (
Describe a red sports car in one sentence.,stop=["sleek"]) goes from 30 completion tokens whose reply contains "sleek" to 2 tokens ending before it. The control request with no stop returns the identical reply and the identical 30 tokens on both sides.Numbers read back from each server's own
/api/inference/monitor, not off the picture.