Repository navigation
feat: expose speculative decoding in ChatSession (#181) - #193
davidkoski merged 6 commits into
Conversation
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.
| let draftModel = await speculativeDecoding.draftModel.perform { context in | ||
| SendableBox(context.model) | ||
| }.consume() | ||
| let draftCache = draftModel.newCache(parameters: generateParameters) |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
| public func generateTask( | ||
| promptTokenCount: Int, | ||
| modelConfiguration: ModelConfiguration, | ||
| tokenizer: Tokenizer, | ||
| iterator: consuming SpeculativeTokenIterator, | ||
| wiredMemoryTicket: WiredMemoryTicket? = nil | ||
| ) -> (AsyncStream<Generation>, Task<Void, Never>) { |
There was a problem hiding this comment.
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
davidkoski
left a comment
There was a problem hiding this comment.
Thank you for your contribution!
|
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. |
…-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>
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>
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 publicgenerateTaskoverload that acceptsconsuming SpeculativeTokenIterator. This mirrors the existing overload forTokenIteratorand givesChatSessiona(AsyncStream<Generation>, Task<Void, Never>)pair it can use for clean early-termination.Libraries/MLXLMCommon/ChatSession.swift— addsSpeculativeDecodingConfigand wires it in:public struct SpeculativeDecodingConfig: SendablewithdraftModel: ModelContainerandnumDraftTokens: Intpublic let speculativeDecoding: SpeculativeDecodingConfig?propertyinitoverloads gain aspeculativeDecoding: SpeculativeDecodingConfig? = nilparameter (fully backward-compatible — default isnil)streamMapbranches onspeculativeDecoding: when set it extracts the draftLanguageModelfrom itsModelContainer(same pattern as the main model) and callsSpeculativeTokenIterator+ the newgenerateTaskoverload; whennilthe existing code path is taken unchangedWhy
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
ChatSessionusers.API
Notes
numDraftTokensdefaults to 5 (good balance speed/accuracy per the literature; the PR Add speculative decoding #173 benchmarks used 2 tokens — users can tune this)speculativeDecodingisnilChatSessionusers (fully backward compatible)SpeculativeDecodingConfigholds aModelContainer(not a rawLanguageModel) to respect the sameSendableconstraints already used byChatSession