Skip to content

Studio: derive native reasoning-channel state from the rendered prompt - #8410

Merged
danielhanchen merged 1 commit into
unslothai:mainfrom
Lyxot:fix/studio-reasoning-prompt-channel-state
Aug 11, 2026
Merged

danielhanchen merged 1 commit into
unslothai:mainfrom
Lyxot:fix/studio-reasoning-prompt-channel-state

Conversation

@Lyxot

@Lyxot Lyxot commented Aug 11, 2026 •

Copy link
Copy Markdown
Collaborator

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 triggers web_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:

{%- if add_generation_prompt -%}
    {%- if ns.prev_message_type != 'tool_response' and ns.prev_message_type != 'tool_call' -%}
        {{- '<|turn>model\n' -}}
    {%- elif ns.prev_message_type == 'tool_response' and enable_thinking -%}
        {{- '<|channel>thought\n' -}}
    {%- endif -%}
{%- endif -%}

So generation starts inside the reasoning channel and emits only the closing <channel|>. ReasoningChannelNormalizer always 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 Prompt tail Channel open?
Ordinary turn <|turn>model\n no
Post-tool, thinking on <|channel>thought\n yes
Post-tool, thinking off <tool_response|> no

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

ReasoningChannelNormalizer now accepts its initial channel state, and both the MLX and safetensors streaming paths derive that state from the rendered prompt via a new prompt_opens_reasoning_channel helper. 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: ReasoningTextIteratorStreamer takes the initial state, and _make_text_streamer receives the rendered prompt from both the text and vision call sites.

before:

84f4275380dc183c4c18f210d98848df

after:

322ccba2cb39e770c019cf8f5c04ea60

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_prefill already 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:

detector forced to always-closed (pre-fix)     -> 5 tests fail, reproducing the reported symptom verbatim
detector reverted to last-opener-anywhere      -> history-forgery test fails
MLX VLM prompt wire removed                    -> VLM test fails
safetensors vision prompt wire removed         -> vision test fails
protocol-newline rule inverted                 -> newline-equivalence test fails
drain() discarding its buffer                  -> cancellation test fails

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

@Lyxot
Lyxot requested a review from danielhanchen as a code owner August 11, 2026 09:54
@Lyxot

Lyxot commented Aug 11, 2026

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

@Lyxot
Lyxot force-pushed the fix/studio-reasoning-prompt-channel-state branch from 72f8d45 to 2abe93e Compare August 11, 2026 10:04
@Lyxot

Lyxot commented Aug 11, 2026

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

@Lyxot
Lyxot force-pushed the fix/studio-reasoning-prompt-channel-state branch from 2abe93e to 0a18481 Compare August 11, 2026 10:13
@Lyxot

Lyxot commented Aug 11, 2026

Copy link
Copy Markdown
Collaborator Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. What shall we delve into next?

Reviewed commit: 0a18481029

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

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.
@Lyxot
Lyxot force-pushed the fix/studio-reasoning-prompt-channel-state branch from 0a18481 to 940d5ba Compare August 11, 2026 10:18
@Lyxot

Lyxot commented Aug 11, 2026

Copy link
Copy Markdown
Collaborator Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Chef's kiss.

Reviewed commit: 940d5ba633

ℹ️ 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

Copy link
Copy Markdown
Member

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 unsloth/gemma-4-E2B-it (bf16, one B200, 2048 ctx, peak 9.9 GB). One Studio install, one home, one port, same loaded weights; the only thing toggled between the two runs is whether the three inference modules are at the merge base or at this head. Driving the real safetensors tool loop over /api/inference/chat/completions with enable_tools: true and the sandboxed python tool:

merge base 9856d99 head 940d5ba
visible content The user asked me to compute ... crucial.<channel|>The result of 34518 multiplied by 7291 is 251,670,738. The result of 34518 multiplied by 7291 is 251,670,738.
reasoning_content first turn only both turns

before and after

Same thing straight through InferenceBackend on a post-tool conversation, 3 seeded runs per side: 3/3 leaked on the base, 0/3 here, snapshots prefix-monotonic on both.

The prompt-tail claims hold against the live template. Rendering unsloth/gemma-4-E2B-it (rev d36bdd38) and unsloth/gemma-4-E4B-it-UD-MLX-4bit (rev 549bd405, byte-identical chat_template.jinja) through the production helpers, all ten shapes agree with the detector: ordinary turn <|turn>model\n closed, post-tool with thinking <|channel>thought\n open, post-tool without thinking <tool_response|> closed, plus two tool rounds, parallel calls, replayed history, and the forged unclosed opener. Both bundled templates in assets/chat_templates/ never leave the channel open across the four thinking/tool combinations, which matches the compatibility section.

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 mlx). I also mutation-checked the production change: nine of ten mutations are killed by a named test, including always-closed, last-opener-anywhere, dropping the continued guard, the protocol-newline rule, the orphan </think>, and both VLM prompt wires.

One gap worth closing. The tenth mutation survives. Replacing inference.py:1217 with the raw request flag:

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 0a18481 was about, only on the safetensors side:

post-tool (ordinary request)      -> <think>reasoned</think>answer
post-tool after a CONTINUED turn  -> reasoned<channel|>answer

MLX has test_tool_loop_pass_of_a_continued_turn_still_reads_the_prompt pinning this; safetensors has no sibling. A fake model replaying reasoned / <channel|> / answer through _generate_chat_response_inner with the real Gemma template covers it in a few lines.

Minor. mlx_inference.generate_audio_input_response still builds ReasoningChannelNormalizer(*markers) with no initial state. It renders its own system plus user prompt and takes no tools, so the post-tool shape is unreachable there today; routing it through the same helper would keep the seams from drifting.

CI red on this PR is not from these changes. tests/studio/test_remote_connection_models_contract.py fails identically on plain main locally, the three Core failures are unsloth_zoo's own tests, and the rest (Chat UI Playwright timeout, the research-runs timing assertions, web rank) do not touch this code and pass locally at this head.

danielhanchen added a commit to Datta0/unsloth-staging-3 that referenced this pull request Aug 11, 2026
@danielhanchen
danielhanchen merged commit bf6799c into unslothai:main Aug 11, 2026
37 of 47 checks passed
Lyxot added a commit to Lyxot/unsloth that referenced this pull request Aug 11, 2026
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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants