Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
86 changes: 75 additions & 11 deletions Sources/DFlash/DFlashRuntime.swift
Original file line number Diff line number Diff line change
Expand Up @@ -169,15 +169,59 @@ public enum DFlashRuntime {
/// Arm all rollback-capable caches in the target model.
/// RecurrentRollbackCache arms for innovation-tape recording.
/// MambaSnapshotCache takes a lazy state snapshot (O(1), no GPU copy).
/// Plain MambaCache instances are not checkpointed.
/// A plain MambaCache (the recurrent layers of a model the runtime does not treat as
/// hybrid, e.g. Qwen3.5's gated delta net layers) checkpoints its state, so a partial
/// acceptance can restore it and replay the committed tokens; see
/// `replayCommittedTokens`.
public static func armTargetRollback(targetCache: [KVCache], prefixLen: Int) {
for cache in targetCache {
if let rollbackCache = cache as? DFlashRollbackCache {
rollbackCache.armRollback(prefixLen: prefixLen)
} else if let mambaCache = cache as? MambaCache {
mambaCache.checkpoint()
}
}
}

/// True when a partial acceptance cannot be rolled back in place: a plain MambaCache
/// restores its pre-verify checkpoint whole, so the accepted tokens have to be run
/// through the target again. Rollback-capable caches and attention caches do not need it.
public static func needsReplayAfterPartialAcceptance(_ cacheEntries: [KVCache]) -> Bool {
cacheEntries.contains { $0 is MambaCache && !($0 is DFlashRollbackCache) }
}

/// Rolls every layer back to the prefix the verify pass started from and runs the
/// committed tokens (the staged first token and the accepted drafts) through the target
/// again, so the recurrent state holds exactly the accepted prefix. Attention layers are
/// trimmed to the prefix first, so the replay appends them once. This is what
/// mlx-swift-lm's draft-model speculative loop does on a rejection with recurrent layers.
///
/// `forward` runs the target on `[1, n]` token ids against the cache; its output is not
/// needed, the verify pass already captured the hidden states of the committed tokens.
///
/// - Returns: Time spent on the replay in nanoseconds.
@discardableResult
public static func replayCommittedTokens(
_ cacheEntries: [KVCache],
prefixLen: Int,
committed: MLXArray,
forward: (MLXArray) -> MLXArray
) -> Int {
let startNs = Int(DispatchTime.now().uptimeNanoseconds)
for cache in cacheEntries {
if cache is DFlashRollbackCache {
continue
} else if let mambaCache = cache as? MambaCache {
// Any n > 0 restores the checkpoint `armTargetRollback` took.
mambaCache.trim(1)
} else if cache.isTrimmable, cache.offset > prefixLen {
cache.trim(cache.offset - prefixLen)
}
}
eval(forward(committed.reshaped(1, -1)))
return Int(DispatchTime.now().uptimeNanoseconds) - startNs
}

/// Restore the target cache after partial acceptance of draft tokens.
///
/// RecurrentRollbackCache: replays innovation tape for accepted steps (exact).
Expand Down Expand Up @@ -207,10 +251,11 @@ public enum DFlashRuntime {
rollbackCache.rollback(nAccepted: acceptanceLength)
replayNs += Int(DispatchTime.now().uptimeNanoseconds) - startNs
} else if let mambaCache = cache as? MambaCache {
// Plain MambaCache (non-rollback): no checkpoint-based rollback available.
// Python doesn't call checkpoint/trim on these. The state contains
// contributions from all verify tokens but we can't undo them.
// Only update the offset to reflect the accepted prefix.
// Plain MambaCache: this path runs when nothing was rejected (every draft
// accepted, or no draft at all), so the state is right as it is. Drop the
// checkpoint `armTargetRollback` took; a partial acceptance is handled by
// `replayCommittedTokens` instead.
mambaCache.trim(0)
mambaCache.offset = targetLen
} else if cache.isTrimmable {
let offset = cache.offset
Expand Down Expand Up @@ -587,14 +632,33 @@ public enum DFlashRuntime {
}

// ── Rollback ───────────────────────────────────────
let prefixLen = start
start += commitCount
targetHidden = committedHidden
let replayNs = engine.rollback(
targetCache: targetCache,
targetLen: start,
acceptanceLength: acceptanceLen,
draftedTokens: blockLen - 1
)
let draftedTokens = blockLen - 1
let replayNs: Int
if draftedTokens > 0, acceptanceLen < draftedTokens,
needsReplayAfterPartialAcceptance(targetCache)
{
// Recurrent layers the runtime cannot roll back in place: they are
// restored to the pre-verify checkpoint and the committed tokens run
// through the target again. Before this, their state kept the rejected
// drafts and the generation degenerated after the first block.
replayNs = replayCommittedTokens(
targetCache, prefixLen: prefixLen, committed: committedSegment
) { ids in
targetModel.dflashForwardWithCapture(
inputIDs: ids, cache: targetCache, captureLayerIDs: []
).0
}
} else {
replayNs = engine.rollback(
targetCache: targetCache,
targetLen: start,
acceptanceLength: acceptanceLen,
draftedTokens: draftedTokens
)
}
replayNsTotal += replayNs
cyclesCompleted += 1
acceptedFromDraft += acceptanceLen
Expand Down
96 changes: 68 additions & 28 deletions Sources/SwiftLM/Server.swift
Original file line number Diff line number Diff line change
Expand Up @@ -2411,12 +2411,6 @@ func stopTokenIDs(
return ids.sorted()
}

/// Mutable detokenizer shared with the bridge task in `dflashGenerationStream`.
private final class DetokenizerBox: @unchecked Sendable {
var detokenizer: NaiveStreamingDetokenizer
init(_ d: NaiveStreamingDetokenizer) { self.detokenizer = d }
}

/// Bridges a DFlash event stream to the `Generation` stream the handlers consume.
///
/// When the consumer stops early — a text-level stop sequence, a client disconnect — the
Expand All @@ -2425,30 +2419,64 @@ private final class DetokenizerBox: @unchecked Sendable {
/// the bridge was a bare `Task` nobody cancelled, so the DFlash loop ran on to
/// `max_tokens` after the response had ended and the next request's generation
/// overlapped it (#224).
func dflashGenerationStream(
///
/// Every token goes through `handler`, the same `TokenLoopHandler` the standard path
/// runs its tokens through, so a tool call, a rejected tool call and the model's own
/// stop strings come out the same under `--dflash`. With a bare detokenizer here, a
/// tool call reached the client as plain text. `stopTokenIDs` are the ids DFlash itself
/// stops on; the handler sees them through `onStopToken`, as in the standard loop.
func dflashGenerationStream<Handler: TokenLoopHandler>(
_ events: AsyncStream<DFlashEvent>,
tokenLimit: Int,
nextText: @escaping @Sendable (Int) -> String?
) -> AsyncStream<Generation> {
stopTokenIDs: Set<Int>,
handler: Handler
) -> AsyncStream<Generation> where Handler.Output == Generation {
AsyncStream<Generation> { continuation in
let bridge = Task {
let bridge = Task { [handler] in
var handler = handler
let emit: (sending Generation) -> Bool = { continuation.yield($0); return true }
let started = Date()
var promptTokenCount = 0
var prefillSeconds = 0.0
var generated = 0
for await event in events {
if Task.isCancelled { break }
switch event {
case .token(let tokenID, _, _, _):
if let chunk = nextText(tokenID) {
continuation.yield(.chunk(chunk, tokenId: tokenID))
}
case .prefill, .prefillProgress:
case .prefill(let count, let prefillUs):
promptTokenCount = count
prefillSeconds = prefillUs / 1_000_000.0
case .prefillProgress:
break
case .token(let tokenID, let generatedTokens, _, _):
generated = generatedTokens
let disposition = stopTokenIDs.contains(tokenID)
? handler.onStopToken(tokenID, logProbabilities: nil, emit: emit)
: handler.onToken(tokenID, logProbabilities: nil, emit: emit)
if case .more = disposition { continue }
// The handler ended the generation (one of the model's stop strings):
// flush it and close with the counts so far, then cancel this task so
// the next wait on `events` cancels the DFlash stream and its producer
// stops computing (#224), instead of running on to max_tokens.
_ = handler.onGenerationEnd(emit: emit)
continuation.yield(handler.infoEvent(GenerateCompletionInfo(
promptTokenCount: promptTokenCount,
generationTokenCount: generated,
promptTime: prefillSeconds,
generationTime: max(0, Date().timeIntervalSince(started) - prefillSeconds),
stopReason: .stop
)))
withUnsafeCurrentTask { $0?.cancel() }
case .summary(let summary):
print("[SwiftLM] DFlash summary: \(summary.generationTokens) tokens, \(String(format: "%.1f", summary.tokensPerSecond)) tok/s, acceptance=\(String(format: "%.1f%%", summary.acceptanceRatio * 100)), \(summary.cyclesCompleted) cycles")
// Text the handler is still holding (a tag it was watching) goes out
// before the end of the generation is announced.
_ = handler.onGenerationEnd(emit: emit)
// The SSE/non-streaming handlers emit finish_reason, usage and
// `[DONE]` from `.info`. Without it, a DFlash run that ends on EOS
// or max_tokens (rather than a textual stop sequence) closes the
// stream with no `[DONE]` sentinel.
let prefillSec = summary.phaseTimingsUs.prefill / 1_000_000.0
continuation.yield(.info(GenerateCompletionInfo(
continuation.yield(handler.infoEvent(GenerateCompletionInfo(
promptTokenCount: summary.promptTokenCount,
generationTokenCount: summary.generationTokens,
promptTime: prefillSec,
Expand Down Expand Up @@ -2691,25 +2719,37 @@ func handleChatCompletion(
// Convert DFlashEvent stream to Generation stream with proper streaming detokenizer
let dflashTokenizer = await container.tokenizer
let dflashConfiguration = await container.configuration
// The token handler the standard path uses (`generate` in mlx-swift-lm builds the
// same one): it turns the model's tool-call protocol into `.toolCall` events and
// honours the model's stop strings. Reasoning stays nil here as on the standard
// path, since this server splits `<think>` out of the text itself.
let dflashHandler = TextToolTokenLoopHandler(
tokenizer: dflashTokenizer,
stopStrings: dflashConfiguration.effectiveStopStrings,
format: dflashConfiguration.toolCallFormat ?? .json,
tools: toolSpecs,
toolCallPolicy: params.toolCallPolicy,
reasoning: nil)
// The end-of-sequence set the standard path stops on. Without it DFlash ran
// to max_tokens past `<|im_end|>` (#224). The handler may add ids of its own,
// as it does in the standard loop.
let dflashStopTokenIDs = Set(stopTokenIDs(
eosTokenIDs: dflashConfiguration.eosTokenIds,
tokenizerEOS: dflashTokenizer.eosTokenId,
extraEOSTokens: dflashConfiguration.extraEOSTokens,
tokenID: dflashTokenizer.convertTokenToId)
).union(dflashHandler.additionalStopTokenIDs)
let dflashStream = DFlashRuntime.generate(
targetModel: targetModel,
draftModel: dflashDraft,
promptTokens: promptTokens,
maxNewTokens: tokenLimit,
blockTokens: dflashBlockSize,
// The end-of-sequence set the standard path stops on. Without it DFlash ran
// to max_tokens past `<|im_end|>` (#224).
stopTokenIDs: stopTokenIDs(
eosTokenIDs: dflashConfiguration.eosTokenIds,
tokenizerEOS: dflashTokenizer.eosTokenId,
extraEOSTokens: dflashConfiguration.extraEOSTokens,
tokenID: dflashTokenizer.convertTokenToId)
stopTokenIDs: Array(dflashStopTokenIDs)
)
let box = DetokenizerBox(NaiveStreamingDetokenizer(tokenizer: dflashTokenizer))
let genStream = dflashGenerationStream(dflashStream, tokenLimit: tokenLimit) { tokenID in
box.detokenizer.append(token: tokenID)
return box.detokenizer.next()
}
let genStream = dflashGenerationStream(
dflashStream, tokenLimit: tokenLimit, stopTokenIDs: dflashStopTokenIDs,
handler: dflashHandler)

return (genStream, nil)
}
Expand Down
93 changes: 93 additions & 0 deletions tests/SwiftLMTests/DFlashRecurrentRollbackTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
import XCTest
import Foundation
import MLX
@testable import DFlash
import MLXLMCommon

// MARK: - Rolling a hybrid target back after a partially accepted DFlash block
//
// Qwen3.5's gated delta net layers keep a recurrent state in a plain `MambaCache`. The
// verify pass runs the whole drafted block through it, and when only part of the block is
// accepted that state cannot be trimmed like attention KV. The runtime used to leave it as
// it was (contributions of the rejected drafts included), and generation degenerated
// after the first block. Now `armTargetRollback` checkpoints such caches, and a partial
// acceptance restores them and replays the committed tokens through the target, as
// mlx-swift-lm's draft-model loop does on a rejection with recurrent layers.
final class DFlashRecurrentRollbackTests: XCTestCase {

private func recurrent(_ value: Float) -> MambaCache {
let cache = MambaCache()
cache[0] = MLXArray([value, value])
cache[1] = MLXArray([value])
cache.offset = 10
return cache
}

private func attention(tokens: Int) -> KVCacheSimple {
let cache = KVCacheSimple()
let keys = MLXArray.zeros([1, 1, tokens, 2])
_ = cache.update(keys: keys, values: keys)
return cache
}

func testNeedsReplayOnlyForPlainRecurrentCaches() {
XCTAssertFalse(DFlashRuntime.needsReplayAfterPartialAcceptance([attention(tokens: 4)]))
XCTAssertTrue(DFlashRuntime.needsReplayAfterPartialAcceptance([attention(tokens: 4), recurrent(1)]))
XCTAssertFalse(
DFlashRuntime.needsReplayAfterPartialAcceptance([RecurrentRollbackCache(), MambaSnapshotCache()]),
"rollback-capable caches roll back in place")
}

func testArmCheckpointsPlainRecurrentCaches() {
let cache = recurrent(1)
DFlashRuntime.armTargetRollback(targetCache: [cache], prefixLen: 10)
// The verify pass moves the state on; a trim restores the checkpoint.
cache[1] = MLXArray([99] as [Float])
cache.offset = 26
XCTAssertEqual(cache.trim(1), 1)
XCTAssertEqual(cache[1]!.asArray(Float.self), [1])
XCTAssertEqual(cache.offset, 10)
}

/// A partial acceptance: the recurrent state goes back to the checkpoint, attention is
/// trimmed to the prefix, and the committed tokens are fed once more.
func testPartialAcceptanceRestoresCheckpointTrimsAttentionAndReplays() {
let mamba = recurrent(1)
let attn = attention(tokens: 10)
let caches: [KVCache] = [attn, mamba]
DFlashRuntime.armTargetRollback(targetCache: caches, prefixLen: 10)
// The verify pass of a 16-token block: 16 more attention positions, a moved state.
_ = attn.update(keys: MLXArray.zeros([1, 1, 16, 2]), values: MLXArray.zeros([1, 1, 16, 2]))
mamba[1] = MLXArray([99] as [Float])
mamba.offset = 26

var replayed: [Int] = []
let committed = MLXArray([7, 8, 9].map { UInt32($0) }) // staged first + 2 accepted
DFlashRuntime.replayCommittedTokens(caches, prefixLen: 10, committed: committed) { ids in
XCTAssertEqual(ids.shape, [1, 3])
replayed = ids.asArray(Int.self)
// The forward ran against caches already at the prefix.
XCTAssertEqual(attn.offset, 10)
XCTAssertEqual(mamba.offset, 10)
return MLXArray.zeros([1, 3, 4])
}
XCTAssertEqual(replayed, [7, 8, 9])
XCTAssertEqual(mamba[1]!.asArray(Float.self), [1], "the rejected drafts' contributions are gone")
XCTAssertEqual(attn.offset, 10, "the forward in this test appends nothing; the real target appends the committed tokens")
}

/// Nothing rejected: the state is right as it is, and the checkpoint is dropped so a
/// later trim cannot restore stale state.
func testFullAcceptanceKeepsStateAndDropsCheckpoint() {
let mamba = recurrent(1)
DFlashRuntime.armTargetRollback(targetCache: [mamba], prefixLen: 10)
mamba[1] = MLXArray([5] as [Float])
mamba.offset = 26
DFlashRuntime.restoreTargetCacheAfterAcceptance(
[mamba], targetLen: 26, acceptanceLength: 15, draftedTokens: 15)
XCTAssertEqual(mamba[1]!.asArray(Float.self), [5])
XCTAssertEqual(mamba.offset, 26)
XCTAssertEqual(mamba.trim(1), 0, "no checkpoint is held any more")
XCTAssertEqual(mamba[1]!.asArray(Float.self), [5])
}
}
Loading
Loading