From 0875d215d907eaaf7ef0650048be50eede9974db Mon Sep 17 00:00:00 2001 From: Hamed Shams Date: Fri, 6 Nov 2026 03:30:54 +0300 Subject: [PATCH 1/2] fix: roll the recurrent layers back after a partially accepted DFlash block MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit On Qwen3.5 the gated delta net layers keep their state in a plain MambaCache. The DFlash verify pass ran the whole drafted block through them, and when only part of the block was accepted the state kept the rejected drafts: every conformance says dflashIsHybridGDN = false, and restoreTargetCacheAfterAcceptance only moved the offset. The next cycle verified against a prefix the model never produced and the text degenerated after the first block ("Paris,\n,\n,\n,…") at 70-90 % reported acceptance. Block size 1 was exact, since it drafts nothing. Do what mlx-swift-lm's draft-model loop does on a rejection with recurrent layers: checkpoint the plain MambaCaches when the verify is armed, and on a partial acceptance restore them, trim the attention layers to the pre-verify prefix and run the committed tokens through the target once more. Full acceptance and the no-draft case are unchanged apart from dropping the checkpoint. The next draft still conditions on the verify pass's hidden states, which are exact at the accepted positions. Eight greedy prompts now match the plain server to the last character (DFlash emits the trailing newline before <|im_end|>, the plain path stops at the end token). It costs one extra target forward of the committed tokens per partially accepted cycle. --- Sources/DFlash/DFlashRuntime.swift | 86 ++++++++++++++--- .../DFlashRecurrentRollbackTests.swift | 93 +++++++++++++++++++ tests/test-dflash.sh | 23 ++++- 3 files changed, 190 insertions(+), 12 deletions(-) create mode 100644 tests/SwiftLMTests/DFlashRecurrentRollbackTests.swift diff --git a/Sources/DFlash/DFlashRuntime.swift b/Sources/DFlash/DFlashRuntime.swift index 08fd94f7..caddbb9d 100644 --- a/Sources/DFlash/DFlashRuntime.swift +++ b/Sources/DFlash/DFlashRuntime.swift @@ -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). @@ -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 @@ -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 diff --git a/tests/SwiftLMTests/DFlashRecurrentRollbackTests.swift b/tests/SwiftLMTests/DFlashRecurrentRollbackTests.swift new file mode 100644 index 00000000..8e435778 --- /dev/null +++ b/tests/SwiftLMTests/DFlashRecurrentRollbackTests.swift @@ -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]) + } +} diff --git a/tests/test-dflash.sh b/tests/test-dflash.sh index 7d674e51..39b20ef5 100755 --- a/tests/test-dflash.sh +++ b/tests/test-dflash.sh @@ -27,6 +27,7 @@ NUM_DRAFT_TOKENS=16 URL="http://${HOST}:${PORT}" PASS=0 FAIL=0 +SKIP=0 TOTAL=0 LOG_FILE="/tmp/SwiftLM-test-dflash.log" @@ -40,6 +41,8 @@ NC='\033[0m' log() { echo -e "${YELLOW}[dflash-test]${NC} $*"; } pass() { PASS=$((PASS + 1)); TOTAL=$((TOTAL + 1)); echo -e " ${GREEN}✅ PASS${NC}: $*"; } fail() { FAIL=$((FAIL + 1)); TOTAL=$((TOTAL + 1)); echo -e " ${RED}❌ FAIL${NC}: $*"; } +# A capability the model may lack is not a contract failure: it reports SKIP, as in test-contract.sh. +skip() { SKIP=$((SKIP + 1)); TOTAL=$((TOTAL + 1)); echo -e " ⏭️ SKIP: $*"; } cleanup() { if [ -n "${SERVER_PID:-}" ]; then @@ -209,6 +212,24 @@ else fail "request after an early-ended stream failed (server alive: $(curl -sf "$URL/health" >/dev/null 2>&1 && echo yes || echo no))" fi +# ── Test 4c: a drafted block that is only partly accepted keeps the state right ── +# Qwen3.5's recurrent layers could not be rolled back after a partial acceptance, so the +# rejected drafts stayed in their state and every answer degenerated after the first block +# ("Paris,\n,\n,\n,…"). The earlier tests only check that something came back; this one +# checks that a list-shaped answer is still a list. Greedy, so the reply is deterministic. +log "Test 4c: generation stays coherent past the first drafted block" +COHERENT=$(curl -sf --max-time 180 -X POST "$URL/v1/chat/completions" \ + -H "Content-Type: application/json" \ + -d "{\"model\":\"$MAIN_MODEL\",\"max_tokens\":120,\"temperature\":0,\"messages\":[{\"role\":\"user\",\"content\":\"List five European capitals with their countries, one per line.\"}]}" 2>/dev/null || echo "") +COHERENT_CONTENT=$(echo "$COHERENT" | jq -r '.choices[0].message.content // empty' 2>/dev/null || echo "") +CAPITALS=$(echo "$COHERENT_CONTENT" | grep -c -i -E "paris|berlin|madrid|rome|london|vienna|lisbon|athens|warsaw|prague|amsterdam|brussels|dublin|stockholm|oslo|copenhagen|helsinki|budapest|bern" || true) +REPEATED_LINES=$(echo "$COHERENT_CONTENT" | grep -v '^\s*$' | sort | uniq -d | wc -l | tr -d ' ') +if [ "$CAPITALS" -ge 4 ] && [ "$REPEATED_LINES" -eq 0 ]; then + pass "coherent past the first block: $CAPITALS capitals named, no repeated line" +else + fail "degenerate output ($CAPITALS capitals, $REPEATED_LINES repeated lines): $(echo "$COHERENT_CONTENT" | head -c 160 | tr '\n' ' ')" +fi + # ── Test 5: Multiple sequential requests (stability) ──────────────── log "Test 5: Sequential request stability (3 requests)" @@ -258,7 +279,7 @@ log "Speculative Decoding Test Results" log " Draft: $DRAFT_MODEL" log " Main: $MAIN_MODEL" log " Tokens/round: $NUM_DRAFT_TOKENS" -log " Results: ${PASS} passed, ${FAIL} failed, ${TOTAL} total" +log " Results: ${PASS} passed, ${FAIL} failed, ${SKIP} skipped, ${TOTAL} total" log "═══════════════════════════════════════" if [ "$FAIL" -gt 0 ]; then From 1106ce11fe3ee9b26e9893b7998d703ab57cef97 Mon Sep 17 00:00:00 2001 From: Hamed Shams Date: Fri, 6 Nov 2026 03:30:54 +0300 Subject: [PATCH 2/2] fix: run DFlash tokens through the standard path's token handler MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The DFlash bridge turned tokens into text with a bare detokenizer, so a tool call reached the client as content ("…"), with no tool_calls and finish_reason "stop", and the model's own stop strings were never applied. Every token now goes through the TextToolTokenLoopHandler the standard path builds, with the model's tool-call format, the request's tools, the tool-call policy and the configured stop strings; the handler is flushed before .info, and a stop it reports ends the stream and cancels the DFlash producer (#224). Reasoning stays with the server's own tracker, as on the standard path. --- Sources/SwiftLM/Server.swift | 96 +++++++--- .../DFlashStreamBridgeTests.swift | 176 +++++++++++++++++- tests/test-dflash.sh | 21 +++ 3 files changed, 261 insertions(+), 32 deletions(-) diff --git a/Sources/SwiftLM/Server.swift b/Sources/SwiftLM/Server.swift index a4f818ff..a21afc94 100644 --- a/Sources/SwiftLM/Server.swift +++ b/Sources/SwiftLM/Server.swift @@ -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 @@ -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( _ events: AsyncStream, tokenLimit: Int, - nextText: @escaping @Sendable (Int) -> String? -) -> AsyncStream { + stopTokenIDs: Set, + handler: Handler +) -> AsyncStream where Handler.Output == Generation { AsyncStream { 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, @@ -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 `` 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) } diff --git a/tests/SwiftLMTests/DFlashStreamBridgeTests.swift b/tests/SwiftLMTests/DFlashStreamBridgeTests.swift index 55a3279f..0f944070 100644 --- a/tests/SwiftLMTests/DFlashStreamBridgeTests.swift +++ b/tests/SwiftLMTests/DFlashStreamBridgeTests.swift @@ -66,7 +66,8 @@ final class DFlashStreamBridgeTests: XCTestCase { // Scoped like the handler's `for await` over the generation stream: once the // consumer breaks out and the stream value goes away, the bridge must be // torn down and the DFlash stream with it. - let generation = dflashGenerationStream(events.stream, tokenLimit: 1_000) { "t\($0) " } + let generation = dflashGenerationStream( + events.stream, tokenLimit: 1_000, stopTokenIDs: [], handler: SpellingHandler()) for await item in generation { if case .chunk(let text, _) = item { received.append(text) } if received.count == 3 { break } @@ -90,17 +91,184 @@ final class DFlashStreamBridgeTests: XCTestCase { var chunks: [String] = [] var info: GenerateCompletionInfo? - // The detokenizer seam may hold text back (nil) and release it on a later token. - for await item in dflashGenerationStream(events, tokenLimit: 3, nextText: { $0 == 1 ? nil : "one two" }) { + // A handler may hold text back and release it later, or at the end of the generation. + let handler = SpellingHandler(holdBack: [1], flushAtEnd: "end ") + for await item in dflashGenerationStream(events, tokenLimit: 3, stopTokenIDs: [], handler: handler) { switch item { case .chunk(let text, _): chunks.append(text) case .info(let i): info = i default: break } } - XCTAssertEqual(chunks, ["one two"]) + XCTAssertEqual(chunks, ["t2 ", "end "], "held-back text is released by onGenerationEnd before .info") XCTAssertEqual(info?.generationTokenCount, 3) XCTAssertEqual(info?.promptTokenCount, 7) XCTAssertEqual(info?.stopReason, .length, "3 generated against a limit of 3 is a length stop") } + + // MARK: the handler sees tokens the way the standard loop shows them to it + + /// DFlash yields the stop token it ends on. The standard loop hands such a token to + /// `onStopToken`, which a handler ignores unless it asked for stop tokens, so the end + /// marker never reaches the client as text. + func testStopTokenGoesToOnStopTokenNotOnToken() async throws { + let (events, continuation) = AsyncStream.makeStream() + continuation.yield(.token(tokenID: 5, generatedTokens: 1, acceptanceRatio: 0, cyclesCompleted: 1)) + continuation.yield(.token(tokenID: 99, generatedTokens: 2, acceptanceRatio: 0, cyclesCompleted: 1)) + continuation.yield(.summary(DFlashSummary( + elapsedUs: 1_000, promptTokenCount: 1, generatedTokenIDs: [5, 99], acceptedFromDraft: 0, + acceptanceRatio: 0, blockTokens: 16, cyclesCompleted: 1, + phaseTimingsUs: .init(prefill: 0, draft: 0, verify: 0, replay: 0)))) + continuation.finish() + + let seen = SpellingHandler.Seen() + var chunks: [String] = [] + for await item in dflashGenerationStream( + events, tokenLimit: 10, stopTokenIDs: [99], handler: SpellingHandler(seen: seen)) + { + if case .chunk(let text, _) = item { chunks.append(text) } + } + XCTAssertEqual(chunks, ["t5 "]) + XCTAssertEqual(seen.tokens, [5]) + XCTAssertEqual(seen.stopTokens, [99]) + } + + /// A handler that ends the generation (one of the model's stop strings) ends the + /// stream: the bridge flushes it, reports the counts so far, and tears the DFlash + /// stream down instead of draining it to max_tokens. + func testHandlerStopEndsTheStreamAndTearsDownTheProducer() async throws { + let events = EndlessEvents() + var chunks: [String] = [] + var info: GenerateCompletionInfo? + do { + let generation = dflashGenerationStream( + events.stream, tokenLimit: 1_000, stopTokenIDs: [], + handler: SpellingHandler(stopAt: 3, flushAtEnd: "end ")) + for await item in generation { + switch item { + case .chunk(let text, _): chunks.append(text) + case .info(let i): info = i + default: break + } + } + } + XCTAssertEqual(chunks, ["t1 ", "t2 ", "end "], "token 3 stops: flushed, not spelled") + XCTAssertEqual(info?.generationTokenCount, 3) + XCTAssertEqual(info?.stopReason, .stop) + await fulfillment(of: [events.terminated], timeout: 2) + } + + // MARK: the real handler: a tool call comes out as a tool call, not as text + + /// With the bare detokenizer the DFlash path used before, a model's `` block + /// was streamed to the client as content. Through the standard path's handler it is a + /// `.toolCall` event, as it is without `--dflash`. + func testRealHandlerTurnsAToolCallIntoAToolCallEvent() async throws { + let text = #"Checking.{"name": "get_weather", "arguments": {"city": "Paris"}}"# + let tokenizer = ByteTokenizer() + let (events, continuation) = AsyncStream.makeStream() + var count = 0 + for id in tokenizer.encode(text: text, addSpecialTokens: false) { + count += 1 + continuation.yield(.token(tokenID: id, generatedTokens: count, acceptanceRatio: 0, cyclesCompleted: 1)) + } + continuation.yield(.summary(DFlashSummary( + elapsedUs: 1_000, promptTokenCount: 1, generatedTokenIDs: Array(repeating: 0, count: count), + acceptedFromDraft: 0, acceptanceRatio: 0, blockTokens: 16, cyclesCompleted: 1, + phaseTimingsUs: .init(prefill: 0, draft: 0, verify: 0, replay: 0)))) + continuation.finish() + + let handler = TextToolTokenLoopHandler( + tokenizer: tokenizer, format: .json, + tools: [["type": "function", "function": ["name": "get_weather"] as [String: any Sendable]]]) + var content = "" + var calls: [ToolCall] = [] + var info: GenerateCompletionInfo? + for await item in dflashGenerationStream(events, tokenLimit: 1_000, stopTokenIDs: [], handler: handler) { + switch item { + case .chunk(let text, _): content += text + case .toolCall(let call): calls.append(call) + case .info(let i): info = i + default: break + } + } + XCTAssertEqual(calls.map(\.function.name), ["get_weather"]) + XCTAssertEqual(calls.first?.function.arguments["city"]?.anyValue as? String, "Paris") + XCTAssertFalse(content.contains(""), "the tool call was handed over as text: \(content)") + XCTAssertEqual(content, "Checking.") + XCTAssertEqual(info?.stopReason, .stop) + } +} + +// MARK: - Test doubles + +/// A `TokenLoopHandler` that spells tokens as `t `, like the closure the bridge used +/// to take, and records which hook each token reached. +private struct SpellingHandler: TokenLoopHandler { + typealias Output = Generation + + final class Seen: @unchecked Sendable { + var tokens: [Int] = [] + var stopTokens: [Int] = [] + } + + var seen = Seen() + var holdBack: Set = [] + var stopAt: Int? = nil + var flushAtEnd: String? = nil + + init(seen: Seen = Seen(), holdBack: Set = [], stopAt: Int? = nil, flushAtEnd: String? = nil) { + self.seen = seen + self.holdBack = holdBack + self.stopAt = stopAt + self.flushAtEnd = flushAtEnd + } + + mutating func onToken( + _ token: Int, logProbabilities: DeferredTokenLogProbabilities?, + emit: (sending Generation) -> Bool + ) -> TokenLoopDisposition { + seen.tokens.append(token) + if token == stopAt { return .stop } + if holdBack.contains(token) { return .more } + return emit(.chunk("t\(token) ", tokenId: token)) ? .more : .cancelled + } + + mutating func onStopToken( + _ token: Int, logProbabilities: DeferredTokenLogProbabilities?, + emit: (sending Generation) -> Bool + ) -> TokenLoopDisposition { + seen.stopTokens.append(token) + return .more + } + + mutating func onGenerationEnd(emit: (sending Generation) -> Bool) -> TokenLoopDisposition { + if let flushAtEnd { _ = emit(.chunk(flushAtEnd, tokenId: -1)) } + return .more + } + + func infoEvent(_ info: GenerateCompletionInfo) -> Generation { .info(info) } +} + +/// One token per UTF-8 byte, enough to run the real text-and-tool handler without a model. +private struct ByteTokenizer: MLXLMCommon.Tokenizer { + func encode(text: String, addSpecialTokens: Bool) -> [Int] { text.utf8.map(Int.init) } + func decode(tokenIds: [Int], skipSpecialTokens: Bool) -> String { + String(decoding: tokenIds.map(UInt8.init), as: UTF8.self) + } + func convertTokenToId(_ token: String) -> Int? { + guard token.utf8.count == 1 else { return nil } + return token.utf8.first.map(Int.init) + } + func convertIdToToken(_ id: Int) -> String? { + guard (0 ... 255).contains(id) else { return nil } + return String(decoding: [UInt8(id)], as: UTF8.self) + } + var bosToken: String? { nil } + var eosToken: String? { nil } + var unknownToken: String? { nil } + func applyChatTemplate( + messages: [[String: any Sendable]], tools: [[String: any Sendable]]?, + additionalContext: [String: any Sendable]? + ) throws -> [Int] { [] } } diff --git a/tests/test-dflash.sh b/tests/test-dflash.sh index 39b20ef5..a110c581 100755 --- a/tests/test-dflash.sh +++ b/tests/test-dflash.sh @@ -212,6 +212,27 @@ else fail "request after an early-ended stream failed (server alive: $(curl -sf "$URL/health" >/dev/null 2>&1 && echo yes || echo no))" fi +# ── Test 4b: a tool call is a tool call under DFlash too ────────────────── +# The DFlash bridge used a bare detokenizer, so the model's `` block reached +# the client as content, with no `tool_calls` and `finish_reason: "stop"`. The tokens now +# go through the same handler the standard path uses. Whether the model calls the tool is +# a capability, not a contract, so a reply without any tool-call shape reports SKIP. +log "Test 4b: a tool call under DFlash arrives as tool_calls, not as text" +TOOLS='[{"type":"function","function":{"name":"get_weather","description":"Get the current weather for a city","parameters":{"type":"object","properties":{"city":{"type":"string"}},"required":["city"]}}}]' +TOOL_RESP=$(curl -sf --max-time 180 -X POST "$URL/v1/chat/completions" \ + -H "Content-Type: application/json" \ + -d "{\"model\":\"$MAIN_MODEL\",\"max_tokens\":120,\"temperature\":0,\"tools\":$TOOLS,\"messages\":[{\"role\":\"system\",\"content\":\"You are a weather kiosk. Call get_weather for any weather question and say nothing else.\"},{\"role\":\"user\",\"content\":\"What is the weather in Paris right now?\"}]}" 2>/dev/null || echo "") +TOOL_NAME=$(echo "$TOOL_RESP" | jq -r '.choices[0].message.tool_calls[0].function.name // empty' 2>/dev/null || echo "") +TOOL_CONTENT=$(echo "$TOOL_RESP" | jq -r '.choices[0].message.content // empty' 2>/dev/null || echo "") +TOOL_FINISH=$(echo "$TOOL_RESP" | jq -r '.choices[0].finish_reason // empty' 2>/dev/null || echo "") +if [ "$TOOL_NAME" = "get_weather" ] && [ "$TOOL_FINISH" = "tool_calls" ]; then + pass "DFlash tool call parsed: tool_calls[0]=get_weather, finish_reason=tool_calls" +elif echo "$TOOL_CONTENT" | grep -q "tool_call\|get_weather"; then + fail "DFlash handed the tool call over as text: $(echo "$TOOL_CONTENT" | head -c 120)" +else + skip "model did not emit a tool call (capability, not contract): $(echo "$TOOL_CONTENT" | head -c 80)" +fi + # ── Test 4c: a drafted block that is only partly accepted keeps the state right ── # Qwen3.5's recurrent layers could not be rolled back after a partial acceptance, so the # rejected drafts stayed in their state and every answer degenerated after the first block