Skip to content

Studio: Stop at the requested stop text on transformers models - #10812

Merged
danielhanchen merged 8 commits into
unslothai:mainfrom
NilayYadav:transformers-stop-sequences
Sep 13, 2026
Merged

danielhanchen merged 8 commits into
unslothai:mainfrom
NilayYadav:transformers-stop-sequences

Conversation

@NilayYadav

@NilayYadav NilayYadav commented Sep 11, 2026 •

Copy link
Copy Markdown
Collaborator

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 b3dfd088b and AFTER at head 89a38d3c8, each with its own home, port and password, both serving unsloth/Qwen2.5-0.5B-Instruct at 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. with stop=["twenty"], temperature 0 and a 200 token budget.

PR 10812 API monitor, before and after

API monitor, counting request BEFORE b3dfd088b AFTER 89a38d3c8
Completion tokens 200 92
Stop reason length stop
Duration 3.0 s 1.5 s

The 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.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 11, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-13T18:06:42.167721Z c0076e0 Manual request
🔒 Security Review 🔄 Running since 2026-09-13T16:49:20.780703Z 89a38d3 Manual request
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 11, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 11, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 11, 2026
@NilayYadav

Copy link
Copy Markdown
Collaborator Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Something went wrong. Try again later by commenting “@codex review”.

Provided git ref 5067dcf19d2be5215d5f99173d1c51a76d79370b does not exist
ℹ️ 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".

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 11, 2026
@NilayYadav

Copy link
Copy Markdown
Collaborator Author

@codex review

1 similar comment
@NilayYadav

Copy link
Copy Markdown
Collaborator Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 11, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 11, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 🎉

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".

@NilayYadav

Copy link
Copy Markdown
Collaborator Author

Review + GitHub Actions reproduction

Pinned review: 5067dcf19d2be5215d5f99173d1c51a76d79370b. No blocking findings remain.

  • The two Codex P2 items on 396da3d were real bugs (both regression tests fail on that commit at their intended assertions) and are fixed in e9f7743.
  • The Codex P2 on f2ba855 (full re-decode per token) was also real: with the Qwen2.5/Qwen3 tokenizers the re-decode cost ~2 ms/token at 8k and ~8 ms/token at 32k generated tokens. 2f7ced2 decodes a bounded window per token. test_stop_matching_decodes_a_bounded_window_per_token decodes 2,001,000 ids for a 2,000 token reply on f2ba855 and passes after the fix. A differential fuzz against the old implementation matched output, stream chunks and stop position on every valid-text case (Qwen2.5 BPE: 2,500/2,500; SentencePiece llama: 2,805/2,805); differences appear only for injected invalid byte sequences.
  • The Codex P2 on 2f7ced2 (decode cleanup rewriting settled text) was real: with clean_up_tokenization_spaces=True (shipped default for Llama-3.2, Granite 3.3, StarCoder2, Phi-2) a standalone space followed by . decodes as " " then ".", so stop=["."] never matched. With the real GPT-2 tokenizer and cleanup on, 2f7ced2 consumed all 7 tokens and returned Hello world More text after; the full decode stops at token 4. The follow-up rebuilds settled text from all tokens when a window no longer starts with its prefix, and waits while a window still ends in unresolved bytes (SentencePiece byte fallback shows an unfinished emoji as replacement characters).
  • Differential fuzz of the final wrapper against a full decode every token, 1,000 cases per tokenizer, valid text plus injected random ids: 0 mismatches for GPT-2, Llama-3.2, Gemma-3, Mistral-v0.3, Phi-3.5, gpt-oss, Llama-2 SentencePiece and Qwen3 at their default cleanup setting, and for every byte-level tokenizer with cleanup forced on. On realistic prose/code replies of 6,000 tokens it decodes ~3 ids per token with 0 rebuilds. The only remaining differences are SentencePiece tokenizers with cleanup forced on (not the shipped default for any of them), where the old full decode already emitted garbled streamed text.
  • The Codex P2 on 5067dcf (withhold rewrite-prone suffixes before publishing) is left as is: the streamed text matches transformers' own TextIteratorStreamer without any stop in all 12 GPT-2/Llama-3.2 cases checked (cleanup on and off), including the lone space token before . where both return Hello world More text after; the earlier full-decode wrapper behaved the same. It is existing streaming behavior for every transformers request, not something this PR introduces.
  • f2ba855 only updates a stale gating comment in worker.py and drops a no-op line in the new test.

The chat UI never sends stop, so this change has no visible UI effect; the evidence below is API/backend output.

GitHub Actions A/B (same workflow and probe on both branches; the only difference is whether this PR is merged onto main bf87e29). The probe loads real Qwen/Qwen2.5-0.5B-Instruct on CPU with transformers 5.4.0 and sends the prompt through worker._handle_generate with stop=["sleek"], temperature 0, 80 token budget:

reply with stop=["sleek"] completion tokens truncated
main, expected-failing run A sleek red sports car is a masterpiece of design, with its sleek lines ... 27 (same as no-stop control) false
this PR at e9f7743, passing run A 2 false
this PR at 2f7ced2, passing run A 2 false
this PR at 5067dcf (final), passing run A 2 false

Real Studio on an L4 GPU (unsloth/Qwen2.5-0.5B-Instruct loaded through /api/inference/load, /v1/chat/completions, temperature 0; streaming and non-streaming gave identical results):

request main this PR
stop=["sleek"] full reply containing "sleek", 22 tokens A, 2 tokens, finish_reason: stop
minified JSON, stop=["}"], max_tokens=200 200 tokens, finish_reason: length, 7.1s 14 tokens, finish_reason: stop, 0.5s
no stop (control) 22 tokens identical text, 22 tokens

Stop matching cost on an L4 (same model, 6,000 token replies, alternating requests with no stop and with a stop that never matches, averaged after warmup; the two sides ran in different containers, so compare within a row):

code no stop stop=["ZQXJ-never"] overhead
full re-decode per token (f2ba855) 29.5 tok/s 28.8 tok/s −2.4%
bounded window (2f7ced2) 43.3 tok/s 43.6 tok/s none (noise)

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 test_transformers_stop_sequences.py pass on 5067dcf, and each regression test fails on the commit before its fix (the original 13 on main, the Codex-item tests on 396da3d, the bounded-window test on f2ba855, the cleanup test on 2f7ced2). Fork CI on the staged merge of 5067dcf onto main bf87e29: 14 of 15 workflows green (Core, Lint, Wheel, Unsloth API/UI/GGUF on Linux, Windows and macOS, Kaggle T4 GPU, Startup profile, studiobench, Workflow trigger lint); Backend CI passed 39,948 backend tests (+16 over main, the new stop tests) and 18,498 repo tests with one failure each. The two red tests there, test_pr5624_regressions.py::test_deepseek_r1_huge_fenceless_body_is_linear (a 1s timing budget on parse_tool_calls_from_text) and test_desktop_reliability_frontend_contract.py::test_tauri_collapse_removes_the_icon_rail_but_web_keeps_it (a frontend source check), fail identically on main itself (Backend CI on bf87e29) and do not touch the changed code.

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 stop are unchanged.

@NilayYadav

NilayYadav commented Sep 11, 2026 •

Copy link
Copy Markdown
Collaborator Author

UI evidence: Studio API monitor

The 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 (/api-monitor), which lists every request served through the OpenAI-compatible API with its completion tokens, duration and stop reason.

Real Studio on an NVIDIA L4 (Linux, CUDA, so the model runs on the transformers backend; macOS would send it to MLX), unsloth/Qwen2.5-0.5B-Instruct, headless Chromium at 1500×1000. Each side got the same two ordinary /v1/chat/completions requests at temperature 0, and the monitor page was then photographed with the JSON request open in the detail pane. Each side had its own Studio home, port and password; studio/frontend is byte-identical between the two commits, so one production build served both.

  • BEFORE: merge base 8ee07d6ae61e92544f63a733daf86f9b6a6b0ef2
  • AFTER: PR head 5067dcf19d2be5215d5f99173d1c51a76d79370b

PR 10812 API monitor request list and detail, before above after

Full API monitor page, side by side

PR 10812 API monitor before/after

API monitor BEFORE 8ee07d6 AFTER 5067dcf
JSON request, stop=["}"], max_tokens 200 (detail pane) 200 completion tokens, stop reason length, duration 11 s, generating 7.1 s 14 completion tokens, stop reason stop, duration 4.7 s, generating 1.0 s
Sentence request, stop=["sleek"] (top row) reply A sleek red sports car with a powerful engine and a sleek design, ready to take on the world., 22 tokens, 769 ms reply A, 2 tokens, 92 ms

Result: before this PR the transformers backend ignored stop and the monitor records the request running on to the token limit (length); with this PR the same request ends at the stop text and the monitor records stop with a fraction of the tokens and time. The values in the screenshots match the monitor's own records from the same servers. Facts: before, after.

The Studio chat page itself is unchanged (it sends no stop, and the same prompt renders the same reply on both commits).

@danielhanchen

Copy link
Copy Markdown
Member

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.
@danielhanchen

Copy link
Copy Markdown
Member

Independent verification

Reviewed 5067dcf19 against merge base 8ee07d6ae, then merged main b3dfd088b into the branch as 89a38d3c8 so CI re-runs on a current base. No source change was needed.

The gap is real and the fix is complete end to end. stop already reached the worker command on main (routes/inference.py:24988); the _backend_declares gate at worker.py:711 is what dropped it, because only MLX declared it. Reproduced both sides by emulating that same gate, so the "before" column is the real pre-PR path rather than an assumption.

Qwen2.5-0.5B-Instruct, greedy, stop lifted out of the control reply, 80 token budget:

case base 8ee07d6 head 5067dcf
stop=["exudes"] 38 tokens, reply contains the stop word 15 tokens, ends before it, finish_reason: stop
stop="exudes" bare string 38 tokens, ignored 15 tokens
stop=["}"] on compact JSON, 200 budget {"a":1,"b":[2,3]} {"a":1,"b":[2,3]
first word as stop 38 tokens, ignored empty reply, 2 tokens, no hang
stop=None / [] / [""] / unmatched 38 tokens byte-identical to base

Same result on CPU (base 39 tokens including the stop word, head 15). Vision on a real Qwen2.5-VL-3B-Instruct with an image: base returns the full sentence for every case, head returns The color of the for stop=["image"]. Qwen3-0.6B with thinking on: a stop inside the thinking block cuts 277 tokens to 104.

The two things your own tests stop short of, both clean.

  1. The settled-text rebuild does not desynchronise released. I searched real tokenizers for inputs that actually take the rebuild branch: 9 configurations do on the pinned transformers 5.5.0 (gpt2, Qwen2.5, Qwen3, Llama-3.2, gemma-3, gpt-oss with cleanup on, 2 to 3 rebuilds each). In all of them the stream equals the stock TextIteratorStreamer's, 0 characters lost, and a stop placed after the rewrite still never leaks. On transformers 5.17 that branch is unreachable because transformers now ignores clean_up_tokenization_spaces for BPE tokenizers.
  2. The now always-attached stopping criterion is inert. In-process interleaved medians, 5 reps: 128 tokens 50.94 tok/s with no stop vs 50.94 with an unmatched stop, 512 tokens 50.87 vs 50.94, and no-stop output byte-identical to base.

Differential simulation. I drove _StopSequenceStreamer the way generate does (one 2D prompt put, then per-step puts) against 8 real tokenizers, 3 streamer kinds, cleanup on and off, 1 and 3 token puts, about 90 built cases plus 400 fuzz cases per tokenizer, on transformers 5.5.0 and 5.17.0 in separate venvs: roughly 34,500 cases, 0 defects. Oracles were the stream cut at the first stop, parity with the stream the same code produces under an unmatchable stop, and the invariants that no stop is ever published and exactly one queue sentinel arrives. Covered overlapping (ABA/BAB over ABABA) and shared-prefix (END/ENDING) sets, earliest position beating list order, stop only in the prompt, a stop longer than the decode window, unfinished emoji and byte fallback runs, a literal U+FFFD, CJK, combining marks. Per-token cost stayed at 3.0 decoded ids per token over a 1,200 token reply with 0 rebuilds.

The only differences found: on the two SentencePiece tokenizers with 4-space indented code, a request that carries a stop now streams the correct 4 spaces where the stock streamer drops one (its token_cache resets on newline and loses SentencePiece prefix context). The wrapper matches the full decode, so that is an improvement, and it cannot affect requests without stop.

One version note. The comment at inference.py:297 is accurate on transformers 4.57.6 and 5.5.0, where _sample calls streamer.put before stopping_criteria. 5.17.0 reverses it via a new StopCheck helper. Measured cost there is at most one extra token generated and never streamed (completion_tokens 104 on 5.5.0 vs 105 on 5.17.0, identical text), and the DeferredStopCheck path that can undo and re-put tokens is MPS only. Nothing to change now, just worth remembering at the next transformers bump.

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 test_gpu_selection.py entry that passes 3 of 3 in isolation and is an xdist sharding flake. Repo suite: byte-identical 22 failed / 18,590 passed on base and head. No mlx* module enters sys.modules on Linux under any import order, and import time is unchanged (head 9.99 to 10.16s, base 10.09 to 10.34s over 5 fresh processes each).

On the red Repo tests (CPU) check: pre-existing, not this PR. Identical local base/head results, the same job failed on main itself (d7e5c6baa, run 34758370999), and the two newest main runs are green. That run's logs have expired and it cannot be re-run, which is why I merged main in.

Cross-platform, the 16 tests with torch, transformers==5.5.0 and unsloth_zoo installed, PR head merged onto fresh main: Linux x64 pass, Linux ARM64 pass, Windows x64 pass, macOS Apple Silicon pass, studio-live Playwright (chromium, firefox, webkit) pass. Windows ARM64 and Intel macOS fail before any test runs, on sqlite-vec having no ARM64 Windows wheel and on torch being unusable on the Intel macOS image, both pre-existing and unrelated.

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 unsloth/gpt-oss-20b tokenizer and HarmonyTextStreamer).

One follow-up, out of scope here: a tools or response_format request routes to generate_chat_completion_with_tools, which does not declare stop, so the safetensors tool loop still ignores it. That is also true on main.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 13, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 13, 2026
@unslothai unslothai deleted a comment from NilayYadav Sep 13, 2026
@unslothai unslothai deleted a comment from NilayYadav Sep 13, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 13, 2026
@unslothai unslothai deleted a comment from NilayYadav Sep 13, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 13, 2026
@unslothai unslothai deleted a comment from NilayYadav Sep 13, 2026
@unslothai unslothai deleted a comment from NilayYadav Sep 13, 2026
@unslothai unslothai deleted a comment from NilayYadav Sep 13, 2026
@unslothai unslothai deleted a comment from NilayYadav Sep 13, 2026
@danielhanchen

Copy link
Copy Markdown
Member

@codex security review

@danielhanchen

Copy link
Copy Markdown
Member

CI after the main merge: 30 of 32 green, one pending, and one failure that is not this PR.

Backend CI (Python 3.13) reports 1 failed, 41876 passed, and the failure is tests/test_video_shape_validation.py::test_generate_rejects_256x256_with_422_naming_the_presets with KeyError: 'active' on a video progress dict. Nothing in this diff touches video generation. That file passes 3 of 3 locally on this head and on the merge base, and it did not fail in my local full-suite run of the same head, so it is a race under the job's -n 4 sharding. The job cannot be re-run from here (fork PR), so it will clear on the next push.

The earlier Repo tests (CPU) red I mentioned is gone after the merge, which matches the reading that it was the same pre-existing flake that failed on main d7e5c6baa.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

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.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

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.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 13, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 13, 2026
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment on lines +353 to +354
cut, matched = _mlx_stop_cut(self.text[start:], self.sequences)
self.cut = start + cut

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +417 to +420
elif len(window) > len(prefix):
self.settled += window[len(prefix) :]
self.prefix_offset = self.read_offset
self.read_offset = len(self.token_ids)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Hooray!

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".

@danielhanchen
danielhanchen merged commit 9360dcc into unslothai:main Sep 13, 2026
32 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants