Skip to content

Add resumable Qwen MTP speculative decoding to ChatSession - #581

Merged
davidkoski merged 12 commits into
ml-explore:mainfrom
ngutech21:chat-session-qwen-mtp
Nov 3, 2026
Merged

davidkoski merged 12 commits into
ml-explore:mainfrom
ngutech21:chat-session-qwen-mtp

Conversation

@ngutech21

Copy link
Copy Markdown
Contributor

Proposed changes

This PR adds MTP drafters as a first-class speculative-decoding strategy for ChatSession and enables Qwen text and VLM drafters to resume safely across cached turns.

  • Add SpeculativeDecodingConfig(mtpDrafter:blockSize:) with typed block-size validation while preserving existing draft-model APIs.
  • Route eligible generations through MTPSpeculativeTokenIterator, with target-only fallback for unsupported sampling, media inputs, incompatible caches, or missing MTP state.
  • Persist target KV cache, model state, transcript, and MTP drafter continuation atomically across turns, tool restarts, EOS, and cancellation.
  • Resume Qwen text and VLM drafter caches over prompt suffixes, including M-RoPE state and hidden-state aggregation during warm VLM prefill.
  • Validate target family, hidden size, and vocabulary size before MTP prefill.
  • Model speculative-cache reuse as an exhaustive capability enum and share shifted Qwen drafter finalization between text and VLM implementations.
  • Preserve existing ordinary draft-model behavior and source compatibility.

Testing

Coverage includes:

  • Single-turn and warm multi-turn Qwen MTP generation
  • Automatic tool-call restarts
  • Early EOS and consumer cancellation
  • Stateless, resumable, and non-resumable drafter behavior
  • Raw prompt-cache, media, and sampling fallbacks
  • Prompt-cache append, rewind, and rebuild decisions
  • Qwen text/VLM target-family and dimension validation
  • Qwen VLM continuation and M-RoPE alignment
  • Existing eager and deferred draft-model configuration compatibility

Latest targeted verification:

  • 20 Qwen MTP compatibility, registration, and Metal-backed tests passed
  • git diff --check passed
  • Strict Swift formatting reports no branch-introduced diagnostics; the four Qwen35.swift naming diagnostics are also present at the merge base

Checklist

Put an x in the boxes that apply.

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

@ngutech21

Copy link
Copy Markdown
Contributor Author

@davidkoski could you take a look at this pr when you get a chance?

Comment thread Libraries/MLXLMCommon/ChatSession.swift Outdated
case .mtp(_, let blockSize) = speculativeDecoding.strategy,
let drafter = mtpDrafter
{
let iterator = try MTPSpeculativeTokenIterator(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The continuation ownership looks like the right boundary for applications using ChatSession. One remaining concern: ChatSession directly constructs MTPSpeculativeTokenIterator, while its initial beginRound probe can still throw when the cache cannot stage a speculative verification block. That appears to fail the chat request rather than select target-only generation.
Could unsupported speculative-cache capability be handled explicitly before prefill, preserving the authoritative target cache? Please keep this distinct from catching arbitrary initialization errors, since some errors may occur after cache mutation. A focused test with a cache that supports ordinary generation but refuses speculative staging would establish the fallback contract for both cold and warm sessions.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Thanks for the feedback. I have provided a fix:

The iterator now throws a dedicated MTPInitializationError.unsupportedSpeculativeCache when its initial staging probe fails. This happens before target prefill, while the target cache is still valid.

let prefillStart = Date.timeIntervalSinceReferenceDate
var mtpPrefill = parameters.prefill
if drafter.requiresPromptPrefill {
if drafter.requiresPromptPrefill || continuationToResume != nil {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Stateful MTP and warm continuation currently override the caller’s prefill configuration with Int.max and .unchunked. For long RAG prompts or large continuation suffixes, this could increase peak memory and first-token latency substantially.
Could we preserve bounded chunking while aggregating the required hidden states, or provide an explicit admission/fallback policy for cases that require unchunked prefill? It would help to include cold-prompt and warm-suffix measurements covering peak memory and first-token latency alongside decode throughput.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

We could preserve the configured chunk size for both target and drafter prefill, aggregating target hidden states across chunks while maintaining correct alignment for warm continuations. Since this primarily affects long prompts and large continuation suffixes, I’d suggest addressing it in a follow-up PR to keep this PR small and focused. What do you think?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Yes, I think it is reasonable.
Thanks, nice work overall.

}

if speculativeDecoding != nil, requiresMainOnlyContinuation {
if !speculationIsEligibleForParameters || requiresMainOnlyContinuation {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Could completion metadata expose the reason when ChatSession bypasses speculation before constructing the iterator? Currently the sampling fallback has nil speculative telemetry and nil passthroughReason, making it indistinguishable from acceleration being disabled.
A small typed fallback reason covering unsupported sampling, media, cache capability, and missing continuation would let applications accurately explain why a configured accelerator was inactive. Zero proposals alone is ambiguous, especially for very short generations. This would also make fallback tests more precise.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed the missing fallback diagnostics by adding typed reasons to ChatSession completion metadata, so applications can explain why configured speculative decoding was bypassed without changing generation behavior.

@aleroot

aleroot commented Sep 6, 2026 •

Copy link
Copy Markdown
Contributor

@ngutech21 this is something I need as well, so thanks for implementing this. See if my comments make sense.

@ngutech21

Copy link
Copy Markdown
Contributor Author

@davidkoski PR is ready for review

#expect(afterDrop.info.promptTokenCount == 1)
#expect(afterDrop.info.cachedPromptTokenCount > 0)
#expect(afterDrop.info.proposedDraftTokens == nil)
#expect(afterDrop.info.speculativeDecodingFallbackReason == .unavailableContinuation)

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.

Just want to make sure this is desired: after MTP speculation drops then it never gets turned back on (e.g. mtpSpeculativeStateIsReady stays false), even if the session has a full transcript and would otherwise be OK?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Yes, that was the behavior. Fixed in the latest commit: MTP now recovers from the full transcript when eligible again. Recovery costs one full prefill, with guards against repeated rebuilds and regression tests covering recovery, cache reuse, and fallback cases.

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

See question on mtpSpeculativeStateIsReady getting set to false and staying that way.

I think this is ready, it just needs a rebase to fix conflicts. Thank you!

Carry drafter state, target state, KV cache, and transcript atomically across
turns and tool restarts. Add generic resumable MTP support with fail-closed
target-only fallback, plus Qwen text and VLM adapters.
Move shifted-cache boundary finalization into MLXLMCommon and reuse it across the Qwen text and VLM adapters.
Replace correlated cache-state booleans with an exhaustive reuse capability and centralize ordinary draft and MTP state mapping.
Thread target state through chunked continuation prefill, aggregate hidden states for drafter resumption, and cover two-turn VLM cache reuse.
Reject text and VLM targets whose hidden or vocabulary sizes do not match the MTP drafter.
Rebuild target and drafter state from the retained transcript when
MTP becomes eligible again. Suppress further forced recovery after
staging or finalization failure.

@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, thank you!

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.

4 participants