Repository navigation
Studio: derive native reasoning-channel state from the rendered prompt - #8410
danielhanchen merged 1 commit into
Conversation
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 72f8d45633
ℹ️ 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".
72f8d45 to
2abe93e
Compare
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 2abe93e76d
ℹ️ 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".
2abe93e to
0a18481
Compare
|
@codex review |
|
Codex Review: Didn't find any major issues. What shall we delve into next? 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". |
Templates with a native reasoning channel can open it in the generation prompt itself. Gemma's template ends a post-tool generation prompt with `<|channel>thought\n`, so generation starts INSIDE the reasoning channel and emits only the closing `<channel|>`. `ReasoningChannelNormalizer` always started outside the channel and waited for an opening marker in the generated tokens, so after a tool call it treated the model's reasoning as visible answer text and passed the bare `<channel|>` marker straight through to the client. Ordinary first turns were unaffected because the model emits both markers there. The normalizer now accepts its initial channel state, and both the MLX and the safetensors streaming paths derive that state from the rendered prompt. Only the prompt tail decides: the channel is open when nothing but whitespace follows the last opening marker, the same rule `strip_open_reasoning_prefill` already applies to `<think>`. Marker position alone cannot distinguish a template's own prefill from replayed history, and an assistant turn keeps this markup through neutralization, so an opener with content after it is reported closed. That keeps replayed history from hiding a plain answer inside a think block, at the cost of leaving a spliced continuation that resumes inside a channel reported closed, as it was before. A turn resumed with `continue_final_message` never reads its tail at all: that prompt ends inside the client's own assistant text rather than on markup the template appended, so a partial ending on the opener would otherwise capture the whole continuation as reasoning and leave no visible answer. Detection uses the markers the renderer already selected from the active chat template, so no model name is hardcoded. A prompt-opened channel that generates no text emits no think block at all rather than an unmatched `</think>`. Thinking-disabled requests render no opener and are unchanged, as are cancellation draining, cumulative snapshot monotonicity, and markers split across stream chunks.
0a18481 to
940d5ba
Compare
|
@codex review |
|
Codex Review: Didn't find any major issues. Chef's kiss. 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". |
|
Validated this end to end on CUDA with real Gemma 4 weights. The fix is correct and I could reproduce both the bug and its absence. Reproduced on
Same thing straight through The prompt-tail claims hold against the live template. Rendering Tests. The eleven modules quoted in the description: 674 passed, 10 skipped here vs 664 at the merge base, so exactly the ten new tests and nothing regressed (the skips are pre-existing tests needing real One gap worth closing. The tenth mutation survives. Replacing continued = bool(continue_final_message),keeps all six reasoning and tool-loop suites green, but on the real template it puts the leak straight back for the exact case MLX has Minor. CI red on this PR is not from these changes. |
unslothai#8410 gave the reasoning normalizer a prompt-derived initial channel state while this branch was routing every construction site through a factory that picks the parser for the detected protocol. Both survive: the factory now takes in_reasoning and threads it to the marker-pair parser. The recipient-addressed parser does not take it. prompt_opens_reasoning_channel looks for its opener at the prompt tail, and for this protocol the opener is the recipient name "self", which an ordinary prompt can end on by chance. The template ends every generation prompt at "<|start|>assistant", so the model always writes its own header and this parser always starts between blocks.

The bug
On a model whose chat template drives reasoning through a native channel rather than
<think>tags (the Gemma 4 family), with thinking enabled and a tool call in the turn, everything the model reasoned after the tool result came back was rendered as part of the visible answer, immediately followed by a raw<channel|>marker and then the real reply. The first turn of a conversation looked correct, so the leak only appeared once a tool ran.Reproduced with
unsloth/gemma-4-E4B-it-UD-MLX-4bit, thinking and web search enabled, asking a question that triggersweb_search.Root cause
These templates can open the reasoning channel in the generation prompt itself. Gemma's template ends a post-tool generation prompt with the channel opener:
So generation starts inside the reasoning channel and emits only the closing
<channel|>.ReasoningChannelNormalizeralways began outside the channel and waited for an opening marker in the generated tokens, so it classified the post-tool reasoning as visible text and passed the bare closing marker straight through. Ordinary turns were unaffected because the model emits both markers there itself.Rendering the real checkpoint template confirms the two shapes:
<|turn>model\n<|channel>thought\n<tool_response|>This is reached through the native-template fallback: when the active template drops the requested tools, rendering falls back to the checkpoint's own template, which is the one that appends the bare opener.
The change
ReasoningChannelNormalizernow accepts its initial channel state, and both the MLX and safetensors streaming paths derive that state from the rendered prompt via a newprompt_opens_reasoning_channelhelper. Detection uses the markers the renderer already selected from the active chat template, so no model name is hardcoded and models that expose these control tokens without using the protocol are untouched.The shared safetensors/CUDA streamer had the same defect, so the fix is applied at the shared seam:
ReasoningTextIteratorStreamertakes the initial state, and_make_text_streamerreceives the rendered prompt from both the text and vision call sites.before:
after:
Why only the prompt tail decides
The channel counts as open only when nothing but whitespace follows the prompt's last opening marker — the same rule
strip_open_reasoning_prefillalready applies to the<think>protocol in this module.Marker position alone cannot distinguish a template's own prefill from replayed conversation history, and an assistant turn deliberately keeps this markup through
neutralize_control_markup_in_messages. Inferring state from "the last opener trails the last closer" is therefore unsafe: with a marker-aware template that renders assistant content verbatim, a client-supplied assistant message carrying an unclosed opener makes an ordinary turn report "open", which wraps a plain answer in a think block and hides it from the user entirely. Reporting an opener-with-content-after-it as closed avoids that.The tradeoff, stated in the helper's docstring: a spliced continuation that resumes inside a channel reads as closed, leaving that reasoning visible exactly as it is today. That path is unchanged by this PR rather than newly broken, and closing it belongs with the continuation splice, which strips open
<think>prefills but has no native-channel equivalent.One related detail: the protocol newline after an opening marker is consumed only when the model emits that marker itself. When the prompt supplies the opener, that newline is already in the prompt, so a streamed leading newline is model content and is preserved.
Compatibility
Thinking-disabled requests render no opener and are unchanged. Cancellation draining, cumulative snapshot monotonicity, and markers split across stream chunks all keep their existing behavior. A prompt-opened channel that generates no text emits no think block rather than an unmatched
</think>.Both templates bundled with Studio were checked against the rule across all four thinking/tool combinations: neither ever leaves the channel open (one emits a closed empty block when thinking is off, the other appends nothing after a tool response), and all eight shapes classify correctly.
Validation
Detection was verified against the real cached checkpoint template across seven message shapes, including two consecutive tool rounds, parallel tool calls, replayed reasoning history, and thinking-disabled turns.
Every added test was mutation-checked — reverting or weakening the matching production change makes exactly that test fail:
Focused and broader reasoning/tool-loop suites pass:
python -m pytest tests/test_think_prefill_reemit.py tests/test_safetensors_reasoning_stream.py \ tests/test_mlx_inference_backend.py tests/test_safetensors_tool_loop.py \ tests/test_safetensors_toolcall_wiring.py tests/test_tool_loop_controller.py \ tests/test_chat_template_continuation.py tests/test_responses_tool_passthrough.py \ tests/test_gemma4_chat_template_override.py tests/test_thinking_parameter.py \ tests/test_chat_only_reason.py -q # 682 passed