Skip to content

feat: expose speculative decoding in ChatSession (#181) - #193

Merged
davidkoski merged 6 commits into
ml-explore:mainfrom
VDurocher:feat/chat-session-speculative-decoding
May 13, 2026
Merged

davidkoski merged 6 commits into
ml-explore:mainfrom
VDurocher:feat/chat-session-speculative-decoding

Conversation

@VDurocher

Copy link
Copy Markdown
Contributor

Closes #181

What

Exposes the existing speculative decoding implementation (added in #173) through ChatSession's public API.

Two files are modified:

Libraries/MLXLMCommon/Evaluate.swift — adds a public generateTask overload that accepts consuming SpeculativeTokenIterator. This mirrors the existing overload for TokenIterator and gives ChatSession a (AsyncStream<Generation>, Task<Void, Never>) pair it can use for clean early-termination.

Libraries/MLXLMCommon/ChatSession.swift — adds SpeculativeDecodingConfig and wires it in:

  • New public struct SpeculativeDecodingConfig: Sendable with draftModel: ModelContainer and numDraftTokens: Int
  • New public let speculativeDecoding: SpeculativeDecodingConfig? property
  • All six init overloads gain a speculativeDecoding: SpeculativeDecodingConfig? = nil parameter (fully backward-compatible — default is nil)
  • streamMap branches on speculativeDecoding: when set it extracts the draft LanguageModel from its ModelContainer (same pattern as the main model) and calls SpeculativeTokenIterator + the new generateTask overload; when nil the existing code path is taken unchanged

Why

Speculative decoding provides ~2–3× inference speedup with no quality degradation by using a small draft model to generate candidate token sequences that the main model verifies in a single forward pass. The internal machinery already exists — this PR surfaces it to ChatSession users.

API

// Load main and draft models
let main  = try await LLMModelFactory.shared.loadContainer(configuration: mainConfig)
let draft = try await LLMModelFactory.shared.loadContainer(configuration: draftConfig)

let session = ChatSession(
    main,
    speculativeDecoding: SpeculativeDecodingConfig(draftModel: draft, numDraftTokens: 5)
)

// Use exactly as before — speculative decoding is transparent
print(try await session.respond(to: "Hello!"))

Notes

  • numDraftTokens defaults to 5 (good balance speed/accuracy per the literature; the PR Add speculative decoding #173 benchmarks used 2 tokens — users can tune this)
  • Falls back gracefully to standard decoding when speculativeDecoding is nil
  • No public API change for existing ChatSession users (fully backward compatible)
  • The draft model's KVCache is freshly allocated per-turn (same lifecycle as the main model's cache), so there is no cross-turn state leak
  • SpeculativeDecodingConfig holds a ModelContainer (not a raw LanguageModel) to respect the same Sendable constraints already used by ChatSession

Add SpeculativeDecodingConfig struct and wire SpeculativeTokenIterator
into ChatSession.streamMap, enabling ~2-3x generation speedup with
no API break for existing callers.
Exposes a public generateTask(iterator: consuming SpeculativeTokenIterator)
overload so that ChatSession can obtain the (stream, task) pair needed
for clean early-termination handling — matching the pattern used by
the existing TokenIterator overload.
Comment thread Libraries/MLXLMCommon/ChatSession.swift Resolved
Comment thread Libraries/MLXLMCommon/ChatSession.swift Outdated
let draftModel = await speculativeDecoding.draftModel.perform { context in
SendableBox(context.model)
}.consume()
let draftCache = draftModel.newCache(parameters: generateParameters)

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.

I suspect we want the draftCache to be kept as state, just like the normal KVCache. Otherwise I think the draft model won't have the state for the conversation.

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.

True draftKVCache is now stored as an associated
value on Cache.kvcache alongside the main KV cache. It's allocated lazily
on the first turn and reused across subsequent turns, matching the lifecycle
of the main model's cache.

Comment thread Libraries/MLXLMCommon/Evaluate.swift Outdated
Comment on lines +1521 to +1527
public func generateTask(
promptTokenCount: Int,
modelConfiguration: ModelConfiguration,
tokenizer: Tokenizer,
iterator: consuming SpeculativeTokenIterator,
wiredMemoryTicket: WiredMemoryTicket? = nil
) -> (AsyncStream<Generation>, Task<Void, Never>) {

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.

Rather than make a new entry point, I wonder if the existing entry could take TokenIteratorProtocol? Either:

public func generateTask<TOKEN: TokenIteratorProtocol>(
    promptTokenCount: Int,
    modelConfiguration: ModelConfiguration,
    tokenizer: Tokenizer,
    iterator: consuming TOKEN,
    wiredMemoryTicket: WiredMemoryTicket? = nil
) -> (AsyncStream<Generation>, Task<Void, Never>) {

or

public func generateTask(
    promptTokenCount: Int,
    modelConfiguration: ModelConfiguration,
    tokenizer: Tokenizer,
    iterator: consuming any TokenIteratorProtocol,
    wiredMemoryTicket: WiredMemoryTicket? = nil
) -> (AsyncStream<Generation>, Task<Void, Never>) {

- Translate all French comments to English in ChatSession.swift
- Persist draftKVCache across turns by storing it in Cache.kvcache
  associated value instead of allocating fresh each turn
- Consolidate generateTask into a single generic overload over
  TokenIteratorProtocol, removing the duplicate SpeculativeTokenIterator
  overload as suggested by reviewer
JaeminKim-amoz

This comment was marked as spam.

@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 for your contribution!

@davidkoski
davidkoski merged commit 802e8a7 into ml-explore:main May 13, 2026
3 checks passed
@strikingleon

Copy link
Copy Markdown

Do you know when we might get a new tagged release that includes the ChatSession support for Speculative Decoding that was part of #181 @VDurocher @davidkoski

I think this will be a stellar help for something I am working on.

dkgv pushed a commit to dkgv/mlx-swift-lm that referenced this pull request Jul 30, 2026
…-explore#193)

* feat: expose speculative decoding in ChatSession (ml-explore#181)
* feat: add generateTask overload for SpeculativeTokenIterator

Add SpeculativeDecodingConfig struct and wire SpeculativeTokenIterator
into ChatSession.streamMap, enabling ~2-3x generation speedup with
no API break for existing callers.

Exposes a public generateTask(iterator: consuming SpeculativeTokenIterator)
overload so that ChatSession can obtain the (stream, task) pair needed
for clean early-termination handling — matching the pattern used by
the existing TokenIterator overload.

---------

Co-authored-by: David Koski <46639364+davidkoski@users.noreply.github.com>
davidtai added a commit to davidtai/mlx-swift-lm that referenced this pull request Oct 6, 2026
ChunkedKVCache.copy() went through the state of KVCacheSimple. After
maybeTrimFront() the buffer starts at startPosition, so the state setter
set the offset of the copy to the buffer length, which is smaller than the
offset of the original. The next update of the copy wrote over an older
token. Copy the valid part of the buffer, the offset and the start
position directly.

ArraysCache.copy() and MambaCache.copy() went through state, which drops
the empty slots, so a state in slot 1 of 3 moved to slot 0. Copy every
slot, also the empty ones, as mlx-lm cache.py keeps the None slots.

Add KVCacheCopyTests for the three copy() methods.

Fixes ml-explore#193

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

Enhancement: add speculative decoding to ChatSession

4 participants