Skip to content

Fix Qwen reasoning history reconstruction - #663

Merged
davidkoski merged 3 commits into
ml-explore:mainfrom
ngutech21:fix-qwen-reasoning-history
Oct 7, 2026
Merged

davidkoski merged 3 commits into
ml-explore:mainfrom
ngutech21:fix-qwen-reasoning-history

Conversation

@ngutech21

Copy link
Copy Markdown
Contributor

Proposed changes

Fix Qwen assistant-history reconstruction when the chat template expects reasoning in reasoning_content.

The tested Qwen 3.8 template lacks Qwen 3.6’s fallback for extracting reasoning from content. When ChatSession retains reasoning inline, the next rendered prompt inserts an empty reasoning block before that text. This changes the token prefix and prevents exact cache reuse.

This PR:

  • Records a package-only marker when the full prepared prompt supplies the reasoning-opening delimiter, before cache slicing.
  • Normalizes completed reasoning in Qwen3VLMessageGenerator into reasoning_content, retaining the visible answer in content and preserving whitespace and tool metadata.
  • Supports explicitly tagged imported history and reuses the existing QwenReasoningProtocol delimiters.
  • Leaves incomplete reasoning and ambiguous, unmarked closing-only history unchanged. Existing token-prefix checks remain authoritative.

Relationship to other work

This addresses one source of prompt divergence related to [#660](#660).

Validation

  • 78 focused Qwen reasoning and ChatSession tests passed.
  • Seven integration cases passed using pinned regular Qwen 3.8 and Qwen 3.6 tokenizer/templates. These verify complete tool-call prefixes, repeated suffix reuse, Qwen 3.6 equivalence, and safe fallback for independent mismatches.
  • Integration tests download tokenizer/template files only and use scripted generation. On macOS 26, they ran through a temporary project copy excluding unavailable FoundationModels tests.
  • pre-commit run --all-files passed with swift-format 603.0.0.
  • All nine DocC targets were verified; two required SwiftPM’s native backend to work around Xcode 27’s C++ header extraction failure.
  • The full package run reported one failure in the existing TokenIteratorClearCacheTests.testFirstTokenClearsBufferCache cache-seeding assertion. It passed in isolation; all other executed tests passed.

Checklist

  • I have read the CONTRIBUTING document
  • I have run pre-commit run --all-files to format my code / installed pre-commit prior to committing changes
  • I have added tests that prove my fix is effective or that my feature works
  • I have updated the necessary documentation (if needed)

No public documentation changes are required.

AI usage

  • I have read this PR description in full and approve it as my own, and it accurately describes the code changes.
  • AI usage disclosure: I used OpenAI Codex to investigate the issue, author the implementation and tests, run validation, and draft this PR description.

Preserve prompt-priming provenance and pass completed reasoning through
reasoning_content while retaining answer text and tool metadata.

Add pinned Qwen 3.8 regression and Qwen 3.6 compatibility tests covering
exact cache reuse and safe fallback.
Use the concrete class name for the static helper call inside Task.

AI assistance: OpenAI Codex applied the fix and ran focused verification.

@davidkoski davidkoski left a comment

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.

Change looks good. Would it make sense to move the MessageGenerator to MLXLMCommon so that Qwen3 and Qwen3Next could also use it (I think that they probably need the same thing)

@ngutech21

Copy link
Copy Markdown
Contributor Author

@davidkoski Moving shared Qwen reasoning normalization to MLXLMCommon makes sense. However, Qwen3 and Qwen3Next Thinking already support both reasoning_content and inline reasoning, so they don’t share Qwen3.8’s missing-field defect. Qwen3Next Instruct only uses content, so normalization should not be applied indiscriminately across all variants.

@davidkoski davidkoski left a comment

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.

Thank you!

@davidkoski
davidkoski merged commit e9c8500 into ml-explore:main Oct 7, 2026
5 checks passed
abra-code added a commit to abra-code/mlx-swift-lm that referenced this pull request Oct 13, 2026
… end

A <think> or <|channel> typed in a user turn or returned by a tool primed the reasoning scanner, because the prompt check searched for the last opener anywhere in the tail. Models that carry a reasoning config but do not think then delivered their whole answer as reasoning. The prompt now primes only when it ends with the opener, or for a labeled channel with the opener and a one-word label. A typed opener encodes to the same token id as the template's, so only position can tell them apart.

When both delimiters are single tokens, the stream decoder and ReasoningTokenCollector match them by id and report them to the emitter as boundaries. The same characters spelled out as text are content. Other tokenizers keep the text scan. The id lookup is shared with HarmonyFrameParser.

ChatSession keeps finished reasoning beside the assistant message, and Qwen3VLMessageGenerator replays it as reasoning_content, so the history fix from ml-explore#663 keeps working now that reasoning is no longer part of the message text. ChatSession reads priming from the whole prompt, not the part the cache left to prefill.

Added tests for markers in the middle of a prompt, a thought, and an answer, including the Harmony and Onyx decoders.

Co-Authored-By: Claude Opus 5.5
abra-code added a commit to abra-code/mlx-swift-lm that referenced this pull request Oct 16, 2026
… end

A <think> or <|channel> typed in a user turn or returned by a tool primed the reasoning scanner, because the prompt check searched for the last opener anywhere in the tail. Models that carry a reasoning config but do not think then delivered their whole answer as reasoning. The prompt now primes only when it ends with the opener, or for a labeled channel with the opener and a one-word label. A typed opener encodes to the same token id as the template's, so only position can tell them apart.

When both delimiters are single tokens, the stream decoder and ReasoningTokenCollector match them by id and report them to the emitter as boundaries. The same characters spelled out as text are content. Other tokenizers keep the text scan. The id lookup is shared with HarmonyFrameParser.

ChatSession keeps finished reasoning beside the assistant message, and Qwen3VLMessageGenerator replays it as reasoning_content, so the history fix from ml-explore#663 keeps working now that reasoning is no longer part of the message text. ChatSession reads priming from the whole prompt, not the part the cache left to prefill.

Added tests for markers in the middle of a prompt, a thought, and an answer, including the Harmony and Onyx decoders.

Co-Authored-By: Claude Opus 5.5
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.

3 participants