From 6059057b8fe75a98730687a0b17c906e4515b2e2 Mon Sep 17 00:00:00 2001 From: spokvulcan Date: Tue, 13 Oct 2026 16:42:09 +0000 Subject: [PATCH 1/5] DFlash2 block speculative decoding for Qwen3.5 and Qwen3.8 Adds DFlash2 speculative decoding: a drafter model (DFlash2DraftModel), the iterator that drives it (DFlash2SpeculativeTokenIterator), a factory and registry in the MTP drafter's shape, generate/generateTokens overloads, and the target side on Qwen35TextModel/Qwen35Model, which also serve the qwen3_8 model types. The drafter embeds [anchor, MASK x 7], attends over a sliding window of the target's captured hidden states and walks the top-16 candidates per position with its selector; the target verifies the block in one pass. The next round is built while that pass runs, from lazy accept-dependent arrays, and the host syncs once per round. Greedy rounds compare argmaxes; sampled rounds rejection-sample against the selector's candidate distribution. A verify pass sums in a different order than a one-token step, so greedy output can differ from TokenIterator where the top two logits nearly tie. The iterator follows the token-loop contracts the MTP iterator follows: - the logit processor comes from logitProcessor(parameters:model:), and the drafter masks the same suppressed ids before it picks candidates; - recordEmittedToken reaches the processor's didEmit, reasoningTokenCount is reported, and finalizeGeneration reaches the processor; - prefill runs through PrefillParameters.forEachChunk, after reporting the reused prefix through prefill.prefix; - a KV cache plan that compresses or bounds the cache is rejected before prefill, since the verify pass writes plain attention rows; - the MLX buffer cache is cleared on the first token and every 256, as TokenIterator does; - generate takes tool schemas and passes the tool-call policy. The drafter reads both published config layouts (layer_types with sliding_window, and mlx-community's dflash_config.use_swa with a top-level block_size) and is checked against the target's depth, hidden size and vocabulary before prefill. The factory passes excludedComponents. Qwen3.5: the verify pass reuses the compiled decode segments with S rows, writes attention rows at a lazy position without moving the cache offset, and returns gated-delta captures so the iterator can replay the recurrent state to the accepted prefix. Its traces declare the fused GDN projection as compile state, as the decode traces do, and live in a keyed cache that invalidateCompiledTraces() reaches. The plain decode path is unchanged. (cherry picked from commit 47ec29a7e602320281202bd6f7fbb899f079d46c) --- Libraries/MLXLLM/DFlash2Registration.swift | 29 + .../MLXLLM/Documentation.docc/using-model.md | 31 + Libraries/MLXLLM/Models/DFlash2.swift | 691 ++++++++++ Libraries/MLXLLM/Models/Qwen35.swift | 297 ++++- .../MLXLMCommon/DFlash2DrafterModel.swift | 418 ++++++ .../DFlash2DrafterModelFactory.swift | 129 ++ .../DFlash2SpeculativeTokenIterator.swift | 542 ++++++++ Libraries/MLXLMCommon/Evaluate.swift | 89 ++ Tests/MLXLMTests/DFlash2Tests.swift | 1162 +++++++++++++++++ 9 files changed, 3376 insertions(+), 12 deletions(-) create mode 100644 Libraries/MLXLLM/DFlash2Registration.swift create mode 100644 Libraries/MLXLLM/Models/DFlash2.swift create mode 100644 Libraries/MLXLMCommon/DFlash2DrafterModel.swift create mode 100644 Libraries/MLXLMCommon/DFlash2DrafterModelFactory.swift create mode 100644 Libraries/MLXLMCommon/DFlash2SpeculativeTokenIterator.swift create mode 100644 Tests/MLXLMTests/DFlash2Tests.swift diff --git a/Libraries/MLXLLM/DFlash2Registration.swift b/Libraries/MLXLLM/DFlash2Registration.swift new file mode 100644 index 0000000000..ae6c507614 --- /dev/null +++ b/Libraries/MLXLLM/DFlash2Registration.swift @@ -0,0 +1,29 @@ +// Copyright © 2026 Apple Inc. + +import Foundation +import MLXLMCommon + +/// Registers the DFlash2 drafter model type. +/// +/// Call once before loading a drafter through `DFlash2DrafterModelFactory`. +/// DFlash2 checkpoints report `model_type: qwen3`; the `dflash_config` +/// object tells them apart from a Qwen3 language model. +public enum DFlash2Registration { + public static func register() async { + await DFlash2DrafterTypeRegistry.shared.registerModelType( + "qwen3", + matches: isDFlash2Configuration, + creator: { data in + let config = try JSONDecoder.json5().decode(DFlash2Configuration.self, from: data) + return DFlash2DraftModel(config) + } + ) + } +} + +private func isDFlash2Configuration(_ data: Data) -> Bool { + guard let root = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else { + return false + } + return root["dflash_config"] is [String: Any] +} diff --git a/Libraries/MLXLLM/Documentation.docc/using-model.md b/Libraries/MLXLLM/Documentation.docc/using-model.md index 27925f9973..3f90d849e1 100644 --- a/Libraries/MLXLLM/Documentation.docc/using-model.md +++ b/Libraries/MLXLLM/Documentation.docc/using-model.md @@ -81,6 +81,37 @@ The returned `LoRAModelMetadata.defaultKeys` come from the registered model arch not from safetensors names. This accounts for models that rename or reshape checkpoint weights while loading. +### DFlash2 speculative decoding + +A DFlash2 drafter proposes a block of tokens from a Qwen 3.5 or Qwen 3.8 target's hidden +states, and the target checks the block in one pass. Register the drafter type, load the +target and a drafter trained for it, then use the DFlash2 generation overload: + +```swift +await DFlash2Registration.register() + +let target = try await LLMModelFactory.shared.load( + from: targetDirectory, + using: tokenizerLoader +) +let drafter = try await DFlash2DrafterModelFactory.shared.load( + from: drafterDirectory, + using: tokenizerLoader +) +let input = try await target.processor.prepare(input: UserInput(prompt: prompt)) + +let stream = try generate( + input: input, + parameters: GenerateParameters(maxTokens: 256, temperature: 0), + context: target, + dflash2Drafter: drafter.model +) +``` + +`DFlash2DrafterRegistry.qwen38_27B_dflash2` names the Qwen3.8-27B drafter. Greedy and +sampled decoding both work. Quantized or bounded KV caches are not supported, and a drafter +trained for a target of another shape fails before prefill. + ## Evaluation Flow - Load the Model diff --git a/Libraries/MLXLLM/Models/DFlash2.swift b/Libraries/MLXLLM/Models/DFlash2.swift new file mode 100644 index 0000000000..29d4285b4e --- /dev/null +++ b/Libraries/MLXLLM/Models/DFlash2.swift @@ -0,0 +1,691 @@ +// Copyright © 2026 Apple Inc. + +// DFlash2 block drafter (https://inco.ai/blog/dflash2/), a port of the reference +// `dflash/model_mlx.py` (https://github.com/z-lab/dflash). +// +// The drafter embeds an `[anchor, MASK, ...]` block, runs it through a few +// bidirectional layers that attend to a window of the target's hidden states, +// keeps the top-K candidates per position, and walks one path through them with +// a pairwise selector. Embedding and LM head are the target's. + +import Foundation +import MLX +import MLXLMCommon +import MLXNN + +// MARK: - Configuration + +/// The `dflash_config` object of a DFlash2 checkpoint. +public struct DFlash2SpecConfiguration: Codable, Sendable { + public var blockSize: Int = 16 + public var convGroupSize: Int = 16 + public var convKernelSize: Int = 2 + public var maskTokenId: Int = 0 + public var selectorRank: Int = 256 + public var selectorTopK: Int = 16 + public var targetLayerIds: [Int] = [] + public var inputEmbeddingScale: Float = 1.0 + public var outputMultiplier: Float = 1.0 + public var finalLogitSoftcapping: Float? + /// The mlx-community layout's sliding window: `use_swa` with `swa_window_size`. + public var useSlidingWindow: Bool? + public var slidingWindowSize: Int? + + enum CodingKeys: String, CodingKey { + case blockSize = "block_size" + case convGroupSize = "conv_group_size" + case convKernelSize = "conv_kernel_size" + case maskTokenId = "mask_token_id" + case selectorRank = "selector_rank" + case selectorTopK = "selector_top_k" + case targetLayerIds = "target_layer_ids" + case inputEmbeddingScale = "input_embedding_scale" + case outputMultiplier = "output_multiplier" + case finalLogitSoftcapping = "final_logit_softcapping" + case useSlidingWindow = "use_swa" + case slidingWindowSize = "swa_window_size" + } + + public init() {} + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + blockSize = try container.decodeIfPresent(Int.self, forKey: .blockSize) ?? 16 + convGroupSize = try container.decodeIfPresent(Int.self, forKey: .convGroupSize) ?? 16 + convKernelSize = try container.decodeIfPresent(Int.self, forKey: .convKernelSize) ?? 2 + maskTokenId = try container.decodeIfPresent(Int.self, forKey: .maskTokenId) ?? 0 + selectorRank = try container.decodeIfPresent(Int.self, forKey: .selectorRank) ?? 256 + selectorTopK = try container.decodeIfPresent(Int.self, forKey: .selectorTopK) ?? 16 + targetLayerIds = + try container.decodeIfPresent([Int].self, forKey: .targetLayerIds) ?? [] + inputEmbeddingScale = + try container.decodeIfPresent(Float.self, forKey: .inputEmbeddingScale) ?? 1.0 + outputMultiplier = + try container.decodeIfPresent(Float.self, forKey: .outputMultiplier) ?? 1.0 + finalLogitSoftcapping = + try container.decodeIfPresent(Float.self, forKey: .finalLogitSoftcapping) + useSlidingWindow = try container.decodeIfPresent(Bool.self, forKey: .useSlidingWindow) + slidingWindowSize = try container.decodeIfPresent(Int.self, forKey: .slidingWindowSize) + } +} + +/// Configuration of a DFlash2 draft checkpoint (`model_type: qwen3`, +/// `architectures: [DFlash2DraftModel]`). +/// +/// Reads both published layouts: `layer_types` with `sliding_window` (z-lab, +/// inco.ai), and `dflash_config.use_swa` with a top-level `block_size` +/// (mlx-community). Every layer must be non-causal sliding-window attention. +public struct DFlash2Configuration: Decodable, Sendable { + public var hiddenSize: Int = 5120 + public var hiddenLayers: Int = 5 + public var attentionHeads: Int = 32 + public var kvHeads: Int = 8 + public var headDim: Int = 128 + public var intermediateSize: Int = 17408 + public var vocabularySize: Int = 248320 + public var rmsNormEps: Float = 1e-6 + public var maxPositionEmbeddings: Int = 262144 + public var slidingWindow: Int = 2048 + public var ropeTheta: Float = 10_000_000 + public var ropeScaling: [String: StringOrNumber]? = nil + /// Depth of the target the drafter was distilled for; mlx-community omits it. + public var numTargetLayers: Int? + public var dflash: DFlash2SpecConfiguration = .init() + + enum CodingKeys: String, CodingKey { + case hiddenSize = "hidden_size" + case hiddenLayers = "num_hidden_layers" + case attentionHeads = "num_attention_heads" + case kvHeads = "num_key_value_heads" + case headDim = "head_dim" + case intermediateSize = "intermediate_size" + case vocabularySize = "vocab_size" + case rmsNormEps = "rms_norm_eps" + case maxPositionEmbeddings = "max_position_embeddings" + case slidingWindow = "sliding_window" + case layerTypes = "layer_types" + case isCausal = "is_causal" + case ropeTheta = "rope_theta" + case ropeParameters = "rope_parameters" + case ropeScaling = "rope_scaling" + case numTargetLayers = "num_target_layers" + case blockSize = "block_size" + case dflash = "dflash_config" + } + + public init() {} + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + hiddenSize = try container.decodeIfPresent(Int.self, forKey: .hiddenSize) ?? 5120 + hiddenLayers = try container.decodeIfPresent(Int.self, forKey: .hiddenLayers) ?? 5 + attentionHeads = try container.decodeIfPresent(Int.self, forKey: .attentionHeads) ?? 32 + kvHeads = try container.decodeIfPresent(Int.self, forKey: .kvHeads) ?? 8 + headDim = + try container.decodeIfPresent(Int.self, forKey: .headDim) + ?? (hiddenSize / attentionHeads) + intermediateSize = + try container.decodeIfPresent(Int.self, forKey: .intermediateSize) ?? 17408 + vocabularySize = + try container.decodeIfPresent(Int.self, forKey: .vocabularySize) ?? 248320 + rmsNormEps = try container.decodeIfPresent(Float.self, forKey: .rmsNormEps) ?? 1e-6 + maxPositionEmbeddings = + try container.decodeIfPresent(Int.self, forKey: .maxPositionEmbeddings) ?? 262144 + numTargetLayers = try container.decodeIfPresent(Int.self, forKey: .numTargetLayers) + dflash = + try container.decodeIfPresent(DFlash2SpecConfiguration.self, forKey: .dflash) + ?? .init() + let nested = try? container.nestedContainer( + keyedBy: DFlash2SpecConfiguration.CodingKeys.self, forKey: .dflash) + if try nested?.decodeIfPresent(Int.self, forKey: .blockSize) == nil, + let blockSize = try container.decodeIfPresent(Int.self, forKey: .blockSize) + { + dflash.blockSize = blockSize + } + + var ropeParameters = + try container.decodeIfPresent([String: StringOrNumber].self, forKey: .ropeParameters) + ?? container.decodeIfPresent([String: StringOrNumber].self, forKey: .ropeScaling) + if ropeParameters?["type"] == nil, let ropeType = ropeParameters?["rope_type"] { + ropeParameters?["type"] = ropeType + } + let topLevelTheta = try container.decodeIfPresent(Float.self, forKey: .ropeTheta) + ropeTheta = ropeParameters?["rope_theta"]?.asFloat() ?? topLevelTheta ?? 10_000_000 + ropeScaling = ropeParameters + + let window: Int? + if let layerTypes = try container.decodeIfPresent([String].self, forKey: .layerTypes) { + let allSliding = + layerTypes.count == hiddenLayers + && layerTypes.allSatisfy { $0 == "sliding_attention" } + window = + allSliding ? try container.decodeIfPresent(Int.self, forKey: .slidingWindow) : nil + } else { + window = dflash.useSlidingWindow == true ? dflash.slidingWindowSize : nil + } + guard let window, window > 1 else { + throw DecodingError.dataCorruptedError( + forKey: .layerTypes, in: container, + debugDescription: "DFlash2 needs sliding-window attention in every layer") + } + slidingWindow = window + // The reference treats a missing `is_causal` as causal for sliding layers. + guard try container.decodeIfPresent(Bool.self, forKey: .isCausal) == false else { + throw DecodingError.dataCorruptedError( + forKey: .isCausal, in: container, + debugDescription: "DFlash2 needs a non-causal (is_causal: false) drafter") + } + guard !dflash.targetLayerIds.isEmpty else { + throw DecodingError.dataCorruptedError( + forKey: .dflash, in: container, + debugDescription: "dflash_config.target_layer_ids is empty") + } + } + + /// Context rows a block can see: the window minus the block's own anchor. + public var contextWindow: Int { slidingWindow - 1 } +} + +// MARK: - Two-tap dynamic depthwise convolution + +/// `Conv(x)_t = k_{t,0} ⊙ x_t + k_{t,1} ⊙ x_{t-1}` on `groupSize`-channel groups: +/// a learned base kernel plus a per-group correction projected from the input. +/// `prepare` applies slot 0 and returns the dynamic kernel; `finish` applies slot 1. +final class DFlash2DynamicConv: Module { + let kernelSize: Int + let groupSize: Int + + @ParameterInfo(key: "base_kernel") var baseKernel: MLXArray + @ModuleInfo(key: "kernel_projection") var kernelProjection: Linear + + init(hiddenSize: Int, kernelSize: Int, groupSize: Int) { + precondition(hiddenSize % groupSize == 0, "conv groups must divide hidden size") + self.kernelSize = kernelSize + self.groupSize = groupSize + let groups = hiddenSize / groupSize + _baseKernel.wrappedValue = MLXArray.zeros([2, kernelSize, hiddenSize]) + _kernelProjection.wrappedValue = Linear(hiddenSize, 2 * kernelSize * groups, bias: false) + super.init() + } + + /// hidden `[B, L, H]`, dynamic `[B, L, K, groups]`, base `[K, H]`. The first + /// position reads zeros before it. + private static func convolve( + _ hidden: MLXArray, dynamic: MLXArray, base: MLXArray, groupSize: Int + ) -> MLXArray { + let (b, l, h) = (hidden.dim(0), hidden.dim(1), hidden.dim(2)) + let groups = h / groupSize + let blocks = hidden.reshaped(b, l, groups, groupSize) + var output = MLXArray.zeros(like: blocks) + for tap in 0 ..< base.dim(0) { + let values: MLXArray + if tap == 0 { + values = blocks + } else { + values = concatenated( + [MLXArray.zeros(like: blocks[0..., .. (convolved: MLXArray, kernel: MLXArray) { + let groups = hidden.dim(-1) / groupSize + let dynamic = kernelProjection(hidden).reshaped( + hidden.dim(0), hidden.dim(1), 2, kernelSize, groups) + return ( + Self.convolve( + hidden, dynamic: dynamic[0..., 0..., 0, 0..., 0...], + base: baseKernel[0], groupSize: groupSize), + dynamic[0..., 0..., 1, 0..., 0...] + ) + } + + func finish(_ hidden: MLXArray, kernel: MLXArray) -> MLXArray { + Self.convolve(hidden, dynamic: kernel, base: baseKernel[1], groupSize: groupSize) + } +} + +// MARK: - Attention + +/// Block queries attend to the cached context K/V plus the block's own K/V. +final class DFlash2Attention: Module { + let numHeads: Int + let numKVHeads: Int + let headDim: Int + let scale: Float + + @ModuleInfo(key: "q_proj") var qProj: Linear + @ModuleInfo(key: "k_proj") var kProj: Linear + @ModuleInfo(key: "v_proj") var vProj: Linear + @ModuleInfo(key: "o_proj") var oProj: Linear + @ModuleInfo(key: "q_norm") var qNorm: RMSNorm + @ModuleInfo(key: "k_norm") var kNorm: RMSNorm + + init(_ config: DFlash2Configuration) { + numHeads = config.attentionHeads + numKVHeads = config.kvHeads + headDim = config.headDim + scale = pow(Float(config.headDim), -0.5) + _qProj.wrappedValue = Linear(config.hiddenSize, numHeads * headDim, bias: false) + _kProj.wrappedValue = Linear(config.hiddenSize, numKVHeads * headDim, bias: false) + _vProj.wrappedValue = Linear(config.hiddenSize, numKVHeads * headDim, bias: false) + _oProj.wrappedValue = Linear(numHeads * headDim, config.hiddenSize, bias: false) + _qNorm.wrappedValue = RMSNorm(dimensions: headDim, eps: config.rmsNormEps) + _kNorm.wrappedValue = RMSNorm(dimensions: headDim, eps: config.rmsNormEps) + super.init() + } + + /// Rotated block queries and keys plus values, heads first. + func projectBlock( + _ x: MLXArray, rope: RoPELayer, position: MLXArray + ) -> (queries: MLXArray, keys: MLXArray, values: MLXArray) { + let (b, l) = (x.dim(0), x.dim(1)) + let queries = qNorm(qProj(x).reshaped(b, l, numHeads, headDim)).transposed(0, 2, 1, 3) + let keys = kNorm(kProj(x).reshaped(b, l, numKVHeads, headDim)).transposed(0, 2, 1, 3) + let values = vProj(x).reshaped(b, l, numKVHeads, headDim).transposed(0, 2, 1, 3) + return ( + applyRotaryPosition(rope, to: queries, offset: .batch(position)), + applyRotaryPosition(rope, to: keys, offset: .batch(position)), + values + ) + } + + /// Rotated context keys plus values for the cache, heads first. + func projectContext( + _ x: MLXArray, rope: RoPELayer, position: MLXArray + ) -> (keys: MLXArray, values: MLXArray) { + let (b, s) = (x.dim(0), x.dim(1)) + let keys = kNorm(kProj(x).reshaped(b, s, numKVHeads, headDim)).transposed(0, 2, 1, 3) + let values = vProj(x).reshaped(b, s, numKVHeads, headDim).transposed(0, 2, 1, 3) + return (applyRotaryPosition(rope, to: keys, offset: .batch(position)), values) + } + + func project(_ attention: MLXArray) -> MLXArray { + let (b, l) = (attention.dim(0), attention.dim(2)) + return oProj(attention.transposed(0, 2, 1, 3).reshaped(b, l, numHeads * headDim)) + } +} + +// MARK: - Decoder layer + +/// Pre-norm layer with a dynamic conv pair around each sublayer, split at the +/// attention so the SDPA over the growing context runs between two traces. +final class DFlash2DecoderLayer: Module { + @ModuleInfo(key: "self_attn") var selfAttn: DFlash2Attention + @ModuleInfo(key: "mlp") var mlp: DFlash2MLP + @ModuleInfo(key: "input_layernorm") var inputLayerNorm: RMSNorm + @ModuleInfo(key: "post_attention_layernorm") var postAttentionLayerNorm: RMSNorm + @ModuleInfo(key: "attention_conv") var attentionConv: DFlash2DynamicConv + @ModuleInfo(key: "mlp_conv") var mlpConv: DFlash2DynamicConv + + init(_ config: DFlash2Configuration) { + _selfAttn.wrappedValue = DFlash2Attention(config) + _mlp.wrappedValue = DFlash2MLP(config) + _inputLayerNorm.wrappedValue = RMSNorm( + dimensions: config.hiddenSize, eps: config.rmsNormEps) + _postAttentionLayerNorm.wrappedValue = RMSNorm( + dimensions: config.hiddenSize, eps: config.rmsNormEps) + _attentionConv.wrappedValue = DFlash2DynamicConv( + hiddenSize: config.hiddenSize, + kernelSize: config.dflash.convKernelSize, + groupSize: config.dflash.convGroupSize) + _mlpConv.wrappedValue = DFlash2DynamicConv( + hiddenSize: config.hiddenSize, + kernelSize: config.dflash.convKernelSize, + groupSize: config.dflash.convGroupSize) + super.init() + } + + /// Input norm, conv prepare and the block projections. + func preAttention( + x: MLXArray, rope: RoPELayer, position: MLXArray + ) -> (kernel: MLXArray, queries: MLXArray, keys: MLXArray, values: MLXArray) { + let (h, kernel) = attentionConv.prepare(inputLayerNorm(x)) + let (queries, keys, values) = selfAttn.projectBlock(h, rope: rope, position: position) + return (kernel, queries, keys, values) + } + + /// Output projection, conv finish, both residual adds and the MLP. + func postAttention(x: MLXArray, attention: MLXArray, kernel: MLXArray) -> MLXArray { + let h = x + attentionConv.finish(selfAttn.project(attention), kernel: kernel) + let (m, mlpKernel) = mlpConv.prepare(postAttentionLayerNorm(h)) + return h + mlpConv.finish(mlp(m), kernel: mlpKernel) + } +} + +final class DFlash2MLP: Module, UnaryLayer { + @ModuleInfo(key: "gate_proj") var gateProj: Linear + @ModuleInfo(key: "up_proj") var upProj: Linear + @ModuleInfo(key: "down_proj") var downProj: Linear + + init(_ config: DFlash2Configuration) { + _gateProj.wrappedValue = Linear(config.hiddenSize, config.intermediateSize, bias: false) + _upProj.wrappedValue = Linear(config.hiddenSize, config.intermediateSize, bias: false) + _downProj.wrappedValue = Linear(config.intermediateSize, config.hiddenSize, bias: false) + super.init() + } + + func callAsFunction(_ x: MLXArray) -> MLXArray { + downProj(silu(gateProj(x)) * upProj(x)) + } +} + +// MARK: - Candidate selector + +/// Scores adjacent pairs of top-K candidates with a low-rank bilinear match +/// gated by the successor's hidden state, +/// `S_t(a, b) = U_t(b) + `, then walks the best path. +final class DFlash2CandidateSelector: Module { + let topK: Int + + @ModuleInfo(key: "predecessor_codebook") var predecessorCodebook: Embedding + @ModuleInfo(key: "successor_codebook") var successorCodebook: Embedding + @ModuleInfo(key: "hidden_projection") var hiddenProjection: Linear + + /// The greedy walk is about 60 small ops; one trace per block width. + private let compiledGreedy = KeyedCompiledTraces() + + init(_ config: DFlash2Configuration) { + topK = config.dflash.selectorTopK + _predecessorCodebook.wrappedValue = Embedding( + embeddingCount: config.vocabularySize, dimensions: config.dflash.selectorRank) + _successorCodebook.wrappedValue = Embedding( + embeddingCount: config.vocabularySize, dimensions: config.dflash.selectorRank) + _hiddenProjection.wrappedValue = Linear( + config.hiddenSize, config.dflash.selectorRank, bias: false) + super.init() + } + + /// - Parameters: + /// - hidden: normed block hidden states past the anchor, `[B, L, H]`. + /// - logits: matching draft logits, `[B, L, V]`. + /// - anchor: the verified token before the block, `[B]`. + /// - temperature: 0 walks greedily; above 0 samples each step from + /// `softmax(scores / temperature)` and returns those distributions. + func select( + hidden: MLXArray, logits: MLXArray, anchor: MLXArray, temperature: Float + ) -> DFlash2Proposal { + guard temperature <= 0 else { + return walk(hidden: hidden, logits: logits, anchor: anchor, temperature: temperature) + } + let trace = compiledGreedy.trace(logits.dim(1)) { + CompiledTrace { selector, args in + let proposal = selector.walk( + hidden: args[0], logits: args[1], anchor: args[2], temperature: 0) + return [proposal.tokens, proposal.candidates] + } + } + let outputs = trace(self, [hidden, logits, anchor]) + return DFlash2Proposal(tokens: outputs[0], candidates: outputs[1]) + } + + private func walk( + hidden: MLXArray, logits: MLXArray, anchor: MLXArray, temperature: Float + ) -> DFlash2Proposal { + let length = logits.dim(1) + let kth = logits.dim(-1) - topK + let candidates = argPartition(logits, kth: kth, axis: -1)[.ellipsis, kth...] + let unary = takeAlong(logits, candidates, axis: -1) + let projected = hiddenProjection(hidden) + let successors = successorCodebook(candidates) + let predecessors = predecessorCodebook(candidates) + // Boundary 0 pairs the anchor with position 0; boundary t pairs the + // candidates of t - 1 with those of t, gated by position t's hidden. + let anchorEdges = + ((predecessorCodebook(anchor) * projected[0..., 0])[0..., .newAxis, 0...] + * successors[0..., 0, 0..., 0...]).sum(axis: -1) + let gated = + predecessors[0..., 0 ..< (length - 1), 0..., 0...] + * projected[0..., 1..., .newAxis, 0...] + let edges = matmul(gated, successors[0..., 1..., 0..., 0...].transposed(0, 1, 3, 2)) + + var path: [MLXArray] = [] + var distributions: [MLXArray] = [] + var previous: MLXArray? = nil + for position in 0 ..< length { + var scores = unary[0..., position] + if let previous { + scores = + scores + + takeAlong( + edges[0..., position - 1, 0..., 0...], + previous[0..., .newAxis, .newAxis], axis: 1 + )[0..., 0, 0...] + } else { + scores = scores + anchorEdges + } + let chosen: MLXArray + if temperature > 0 { + let distribution = softmax(scores.asType(.float32) / temperature, axis: -1) + distributions.append(distribution) + chosen = categorical(log(distribution)) + } else { + chosen = argMax(scores, axis: -1) + } + previous = chosen + path.append( + takeAlong(candidates[0..., position], chosen[.newAxis, 0...], axis: -1)[0..., 0]) + } + return DFlash2Proposal( + tokens: stacked(path, axis: 1), candidates: candidates, + probabilities: distributions.isEmpty ? nil : stacked(distributions, axis: 1)) + } +} + +// MARK: - Draft model + +/// The DFlash2 drafter. +/// +/// A proposal runs as compiled segments split at each layer's attention. The +/// block position and every accept-dependent value enter as arrays, so one +/// graph serves any accept outcome. +public final class DFlash2DraftModel: Module, DFlash2DrafterModel { + public let config: DFlash2Configuration + + @ModuleInfo(key: "fc") var fc: Linear + @ModuleInfo(key: "hidden_norm") var hiddenNorm: RMSNorm + @ModuleInfo(key: "layers") var layers: [DFlash2DecoderLayer] + @ModuleInfo(key: "norm") var norm: RMSNorm + @ModuleInfo(key: "candidate_selector") var candidateSelector: DFlash2CandidateSelector + + let rope: RoPELayer + + /// Test hook: run the segment bodies eagerly instead of through traces. + var compiledTracesEnabled = true + + public init(_ config: DFlash2Configuration) { + self.config = config + let concatDim = config.dflash.targetLayerIds.count * config.hiddenSize + _fc.wrappedValue = Linear(concatDim, config.hiddenSize, bias: false) + _hiddenNorm.wrappedValue = RMSNorm(dimensions: config.hiddenSize, eps: config.rmsNormEps) + _layers.wrappedValue = (0 ..< config.hiddenLayers).map { _ in + DFlash2DecoderLayer(config) + } + _norm.wrappedValue = RMSNorm(dimensions: config.hiddenSize, eps: config.rmsNormEps) + _candidateSelector.wrappedValue = DFlash2CandidateSelector(config) + rope = initializeRope( + dims: config.headDim, + base: config.ropeTheta, + traditional: false, + scalingConfig: config.ropeScaling, + maxPositionEmbeddings: config.maxPositionEmbeddings) + super.init() + } + + // MARK: DFlash2DrafterModel + + public var blockSize: Int { config.dflash.blockSize } + public var maskTokenId: Int { config.dflash.maskTokenId } + public var targetLayerIds: [Int] { config.dflash.targetLayerIds } + public var contextWindow: Int { config.contextWindow } + + public var targetGeometry: DFlash2Geometry { + DFlash2Geometry( + layerCount: config.numTargetLayers, hiddenSize: config.hiddenSize, + vocabularySize: config.vocabularySize) + } + + public func makeState() -> DFlash2DrafterState { + DFlash2DrafterState( + contextCaches: layers.map { _ in DFlash2ContextCache(window: contextWindow) }) + } + + public func propose( + _ request: DFlash2ProposalRequest, target: any DFlash2TargetModel, + state: inout DFlash2DrafterState + ) -> DFlash2Proposal { + let block = request.block + precondition(block.dim(0) == 1, "DFlash2 drafts one stream at a time") + precondition( + state.contextCaches.count == layers.count, "one context cache per drafter layer") + let rows = request.targetHidden.dim(1) + precondition(rows <= contextWindow, "targetHidden exceeds the drafter's context window") + let width = block.dim(1) + let contextPosition = MLXArray([Int32(request.contextPosition)]) + let blockPosition = contextPosition + request.validRows.asType(.int32).reshaped([1]) + + // Context K/V for the new rows, appended as placeholders. + let contextKV = projectContext(request.targetHidden, position: contextPosition) + let positions = (0 ..< rows).map { Int32(request.contextPosition + $0) } + var layerKV: [(MLXArray, MLXArray)] = [] + for (i, cache) in state.contextCaches.enumerated() { + layerKV.append( + cache.append( + keys: contextKV[2 * i], values: contextKV[2 * i + 1], positions: positions)) + } + // The caches move in lockstep, so one mask serves every layer. + let mask = Self.visibilityMask( + cache: state.contextCaches[0], appended: rows, validRows: request.validRows, + blockPosition: blockPosition, width: width, window: config.slidingWindow) + + // The target's embedding and head run outside the traces. + var x = target.dflash2Embedding(block) * config.dflash.inputEmbeddingScale + var attention: MLXArray? = nil + var kernel: MLXArray? = nil + for index in 0 ... layers.count { + let args = attention.map { [x, $0, kernel!, blockPosition] } ?? [x, blockPosition] + let outputs = + compiledTracesEnabled + ? segmentTrace(index: index, width: width)(self, args) + : segmentBody(at: index, args) + x = outputs[0] + guard index < layers.count else { break } + kernel = outputs[1] + let (contextKeys, contextValues) = layerKV[index] + attention = MLXFast.scaledDotProductAttention( + queries: outputs[2], + keys: concatenated([contextKeys, outputs[3]], axis: 2), + values: concatenated([contextValues, outputs[4]], axis: 2), + scale: layers[index].selfAttn.scale, mask: mask) + } + + let hidden = x[0..., 1..., 0...] + var logits = target.dflash2Head?(hidden) ?? target.dflash2Embedding.asLinear(hidden) + logits = logits * config.dflash.outputMultiplier + if let cap = config.dflash.finalLogitSoftcapping, cap > 0 { + logits = tanh(logits / cap) * cap + } + if let suppressor = request.suppressedTokens { + logits = suppressor.process(logits: logits[0]).expandedDimensions(axis: 0) + } + return candidateSelector.select( + hidden: hidden, logits: logits, anchor: block[0..., 0], + temperature: request.temperature) + } + + /// Bool mask `[width, cache.count + width]`. Committed context rows within the + /// window are visible, placeholders never, and the block sees itself in full. + static func visibilityMask( + cache: DFlash2ContextCache, appended: Int, validRows: MLXArray, + blockPosition: MLXArray, width: Int, window: Int + ) -> MLXArray { + let older = cache.count - appended + let keyPositions = MLXArray(cache.rowPositions) + let olderValid = MLXArray(Array(cache.rowValid[0 ..< older])) + let appendedValid = MLXArray(Int32(0) ..< Int32(appended)) .< validRows.asType(.int32) + let valid = concatenated([olderValid, appendedValid]) + let queryPositions = blockPosition.asType(.int32) + MLXArray(Int32(0) ..< Int32(width)) + let distance = + queryPositions.expandedDimensions(axis: 1) - keyPositions.expandedDimensions(axis: 0) + let contextVisible = valid.expandedDimensions(axis: 0) & (distance .< Int32(window)) + return concatenated( + [contextVisible, MLXArray.ones([width, width], dtype: .bool)], axis: 1) + } + + // MARK: Compiled segments + + private struct SegmentKey: Hashable { + var index: Int + var width: Int + } + + private let segmentTraces = KeyedCompiledTraces() + private let contextTraces = KeyedCompiledTraces() + + /// The prompt window projects eagerly; a trace per prompt length would only churn. + private static let maxTracedContextRows = 16 + + /// Live traces, so tests can check that the compiled route ran. + var compiledTraceCount: Int { segmentTraces.count + contextTraces.count } + + /// Segment `i` closes layer `i - 1` and opens layer `i`; the last segment + /// applies the final norm. In: `[x, position]` for segment 0, else + /// `[x, attention, kernel, position]`. Out: `[x, kernel, queries, keys, values]`, + /// or `[normed]` for the last. + private func segmentBody(at index: Int, _ args: [MLXArray]) -> [MLXArray] { + var x = args[0] + if index > 0 { + x = layers[index - 1].postAttention(x: x, attention: args[1], kernel: args[2]) + } + guard index < layers.count else { return [norm(x)] } + let position = args[index == 0 ? 1 : 3] + let (kernel, queries, keys, values) = layers[index].preAttention( + x: x, rope: rope, position: position) + return [x, kernel, queries, keys, values] + } + + private func segmentTrace(index: Int, width: Int) -> CompiledTrace { + segmentTraces.trace(SegmentKey(index: index, width: width)) { + CompiledTrace { model, args in model.segmentBody(at: index, args) } + } + } + + /// `[targetHidden, position]` to `[keys, values]` per layer. + private func contextBody(_ args: [MLXArray]) -> [MLXArray] { + let context = hiddenNorm(fc(args[0])) + return layers.flatMap { layer in + let (keys, values) = layer.selfAttn.projectContext( + context, rope: rope, position: args[1]) + return [keys, values] + } + } + + private func projectContext(_ targetHidden: MLXArray, position: MLXArray) -> [MLXArray] { + let rows = targetHidden.dim(1) + guard compiledTracesEnabled, rows <= Self.maxTracedContextRows else { + return contextBody([targetHidden, position]) + } + let trace = contextTraces.trace(rows) { + CompiledTrace { model, args in model.contextBody(args) } + } + return trace(self, [targetHidden, position]) + } + + /// The checkpoint stores the selector codebooks as bare tensors; `Embedding` + /// expects a `.weight` suffix. + public func sanitize(weights: [String: MLXArray]) -> [String: MLXArray] { + var weights = weights + for name in ["predecessor_codebook", "successor_codebook"] { + let bare = "candidate_selector.\(name)" + if let value = weights.removeValue(forKey: bare) { + weights["\(bare).weight"] = value + } + } + return weights + } +} diff --git a/Libraries/MLXLLM/Models/Qwen35.swift b/Libraries/MLXLLM/Models/Qwen35.swift index fd21df9195..67414c1ec1 100644 --- a/Libraries/MLXLLM/Models/Qwen35.swift +++ b/Libraries/MLXLLM/Models/Qwen35.swift @@ -415,17 +415,7 @@ final class Qwen35GatedDeltaNet: Module { let k = convSplit[1].reshaped(B, S, numKHeads, headKDim) let v = convSplit[2].reshaped(B, S, numVHeads, headVDim) - let dtype = q.dtype - let invScale = pow(Float(headKDim), -0.5) - // rmsNorm adds eps to mean(x^2). The reference l2norm adds 1e-6 to - // sum(x^2), so divide the eps by the head dim. - let qkEps = 1e-6 / Float(headKDim) - let qNormed = - MLXArray(pow(invScale, 2)).asType(dtype) - * MLXFast.rmsNorm(q, weight: MLXArray.mlxNone, eps: qkEps) - let kNormed = - MLXArray(invScale).asType(dtype) - * MLXFast.rmsNorm(k, weight: MLXArray.mlxNone, eps: qkEps) + let (qNormed, kNormed) = normalizedQK(q: q, k: k) let out: MLXArray let newRecState: MLXArray @@ -487,6 +477,49 @@ final class Qwen35GatedDeltaNet: Module { return (outProj(gated.reshaped(B, S, -1)), newConvState, newRecState, checkpoint) } + /// The weightless q/k RMS norms with the head scaling folded in. + private func normalizedQK(q: MLXArray, k: MLXArray) -> (MLXArray, MLXArray) { + let dtype = q.dtype + let invScale = pow(Float(headKDim), -0.5) + // rmsNorm adds eps to mean(x^2). The reference l2norm adds 1e-6 to + // sum(x^2), so divide the eps by the head dim. + let qkEps = 1e-6 / Float(headKDim) + return ( + MLXArray(pow(invScale, 2)).asType(dtype) + * MLXFast.rmsNorm(q, weight: MLXArray.mlxNone, eps: qkEps), + MLXArray(invScale).asType(dtype) + * MLXFast.rmsNorm(k, weight: MLXArray.mlxNone, eps: qkEps) + ) + } + + /// `forward` over an unmasked DFlash2 verify block, returning a capture + /// instead of the new recurrent state. Traceable: the capture is outputs. + func verifyForward( + _ x: MLXArray, convState: MLXArray, recState: MLXArray + ) -> (output: MLXArray, convState: MLXArray, capture: GatedDeltaCapture) { + let B = x.dim(0) + let S = x.dim(1) + let (qkv, z, b, a) = projectInputs(x, batch: B, sequence: S) + + // One concatenation serves the conv, the next conv state and the capture. + let convInput = concatenated([convState, qkv], axis: 1) + let newConvState = contiguous(convInput[0..., (-(convKernelSize - 1))..., 0...]) + let convOut = silu(conv1d(convInput)) + + let convSplit = MLX.split(convOut, indices: [keyDim, 2 * keyDim], axis: -1) + let (q, k) = normalizedQK( + q: convSplit[0].reshaped(B, S, numKHeads, headKDim), + k: convSplit[1].reshaped(B, S, numKHeads, headKDim)) + let v = convSplit[2].reshaped(B, S, numVHeads, headVDim) + + let (out, _) = gatedDeltaUpdate( + q: q, k: k, v: v, a: a, b: b, aLog: aLog, dtBias: dtBias, state: recState) + let capture = GatedDeltaCapture( + convInput: convInput, q: q, k: k, v: v, a: a, b: b, aLog: aLog, dtBias: dtBias, + initialState: recState) + return (outProj(norm(out, gate: z).reshaped(B, S, -1)), newConvState, capture) + } + /// The S == 1 depthwise conv as elementwise multiply-adds, so `compile` /// folds it into the surrounding segment. f32 accumulation with a single /// final round matches `generalConv`'s `Convolution` kernel bit-for-bit @@ -861,6 +894,32 @@ final class Qwen35DecoderLayer: Module { selfAttn!.projectPreRope(inputLayerNorm(x)) } + /// `linearLayerBody` for a DFlash2 verify pass: the recurrent state comes + /// back as a capture. + func linearLayerVerifyBody(x: MLXArray, convState: MLXArray, recState: MLXArray) -> ( + out: MLXArray, convState: MLXArray, capture: GatedDeltaCapture + ) { + let (r, newConvState, capture) = linearAttn!.verifyForward( + inputLayerNorm(x), convState: convState, recState: recState) + let h = x + r + return (h + mlpForward(postAttentionLayerNorm(h)), newConvState, capture) + } + + /// `attentionPreBody` with rope at `position`, a `[1]` array that may be lazy, + /// so a verify trace can take it as an input. + func verifyAttentionPreBody(x: MLXArray, position: MLXArray) -> ( + MLXArray, MLXArray, MLXArray, MLXArray + ) { + let rope = selfAttn!.rope + let (queries, gate, keys, values) = attentionPreBody(x: x) + return ( + applyRotaryPosition(rope, to: queries, offset: .batch(position)), + gate, + applyRotaryPosition(rope, to: keys, offset: .batch(position)), + values + ) + } + /// `x` is the layer input — the residual branch around the attention block. func attentionPostBody(x: MLXArray, attention: MLXArray, gate: MLXArray) -> MLXArray { let r = selfAttn!.mergeHeadsAndProject(attention: attention, gate: gate) @@ -951,7 +1010,22 @@ public class Qwen35TextModelInner: Module { return step } + let hiddenStates = forwardLayers( + inputs, cache: cache, checkpointAfter: checkpointAfter, captureLayers: [] + ).hidden + return applyFinalNorm ? norm(hiddenStates) : hiddenStates + } + + /// The general layer loop, without the final norm. Also returns the outputs + /// of `captureLayers`, in that order. + func forwardLayers( + _ inputs: MLXArray, + cache: [KVCache?]?, + checkpointAfter: Int? = nil, + captureLayers: [Int] + ) -> (hidden: MLXArray, captured: [MLXArray]) { var hiddenStates = embedTokens(inputs) + var captured: [Int: MLXArray] = [:] var cacheArray = cache if cacheArray == nil { @@ -974,9 +1048,12 @@ public class Qwen35TextModelInner: Module { hiddenStates = layer( hiddenStates, attentionMask: attnMask, ssmMask: mask, cache: cacheArray?[i], checkpointAfter: checkpointAfter) + if captureLayers.contains(i) { + captured[i] = hiddenStates + } } - return applyFinalNorm ? norm(hiddenStates) : hiddenStates + return (hiddenStates, captureLayers.map { captured[$0]! }) } // MARK: - Whole-step decode schedule @@ -1104,6 +1181,139 @@ public class Qwen35TextModelInner: Module { return carry } + + // MARK: - DFlash2 verify pass + + struct VerifySegmentKey: Hashable { + var index: Int + var length: Int + var captureLayers: [Int] + } + + let verifyTraces = KeyedCompiledTraces() + + /// `segmentBody` for a verify pass. A GDN layer emits its new conv state and + /// its capture's six arrays, and each layer in `captureLayers` emits its + /// output. Out: `[x]`, the GDN arrays, the captured outputs, then the + /// attention head. The final norm is left to the caller. + private func verifySegmentBody( + at index: Int, captureLayers: [Int], _ args: [MLXArray] + ) -> [MLXArray] { + let segment = decodeSegments[index] + var hiddenStates = index == 0 ? embedTokens(args[0]) : args[0] + var captured: [MLXArray] = [] + + if let post = segment.attentionPostLayer { + hiddenStates = layers[post].attentionPostBody( + x: hiddenStates, attention: args[1], gate: args[2]) + if captureLayers.contains(post) { captured.append(hiddenStates) } + } + + var states: [MLXArray] = [] + for (i, layerIndex) in segment.linearLayers.enumerated() { + let slot = segment.stateInputOffset + 2 * i + let (out, newConvState, capture) = layers[layerIndex].linearLayerVerifyBody( + x: hiddenStates, convState: args[slot], recState: args[slot + 1]) + hiddenStates = out + states.append(newConvState) + states.append(contentsOf: capture.arrays) + if captureLayers.contains(layerIndex) { captured.append(hiddenStates) } + } + + var outputs = [hiddenStates] + states + captured + if let pre = segment.attentionPreLayer { + let (queries, gate, keys, values) = layers[pre].verifyAttentionPreBody( + x: hiddenStates, position: args.last!) + outputs += [queries, gate, keys, values] + } + return outputs + } + + /// One verify pass through the compiled segments. Attention rows land at the + /// request's position without moving any offset, and recurrent state comes + /// back as captures: nothing is committed. + func verifyStep( + _ request: DFlash2VerifyRequest, cache: [KVCache] + ) -> (hidden: MLXArray, captured: [MLXArray], recurrentCaptures: [GatedDeltaCapture]) { + precondition(cache.count == layers.count, "one cache entry per layer") + let length = request.tokens.dim(1) + let visibleLength = request.positionUpperBound + length + let captureLayers = request.captureLayers + + // Row `i` sees columns up to its own position, `position + i`. + let columns = MLXArray(Int32(0) ..< Int32(visibleLength)).expandedDimensions(axis: 0) + let rows = (request.position.asType(.int32) + MLXArray(Int32(0) ..< Int32(length))) + .expandedDimensions(axis: 1) + let mask = columns .< (rows + 1) + + var carry = request.tokens + var pendingAttention: [MLXArray] = [] + var captured: [Int: MLXArray] = [:] + var recurrentCaptures: [Int: GatedDeltaCapture] = [:] + + for (segmentIndex, segment) in decodeSegments.enumerated() { + var args: [MLXArray] = [carry] + pendingAttention + for layerIndex in segment.linearLayers { + let mambaCache = cache[layerIndex] as! MambaCache + args.append(mambaCache[0]!) + args.append(mambaCache[1]!) + } + if segment.attentionPreLayer != nil { + args.append(request.position) + } + + let key = VerifySegmentKey( + index: segmentIndex, length: length, captureLayers: captureLayers) + let trace = verifyTraces.trace(key) { + CompiledTrace( + state: { model in + model.traceState(forLayers: segment.layerIndices) + + (segmentIndex == 0 ? [model.embedTokens] : []) + }, + body: { model, args in + model.verifySegmentBody( + at: segmentIndex, captureLayers: captureLayers, args) + }) + } + let outputs = trace(self, args) + + carry = outputs[0] + var next = 1 + var capturedHere: [Int] = [] + if let post = segment.attentionPostLayer, captureLayers.contains(post) { + capturedHere.append(post) + } + for layerIndex in segment.linearLayers { + let mambaCache = cache[layerIndex] as! MambaCache + let gdn = layers[layerIndex].linearAttn! + recurrentCaptures[layerIndex] = GatedDeltaCapture( + arrays: Array(outputs[(next + 1) ..< (next + 7)]), + aLog: gdn.aLog, dtBias: gdn.dtBias, initialState: mambaCache[1]!) + next += 7 + if captureLayers.contains(layerIndex) { capturedHere.append(layerIndex) } + } + for layerIndex in capturedHere { + captured[layerIndex] = outputs[next] + next += 1 + } + + pendingAttention = [] + if let pre = segment.attentionPreLayer { + let kvCache = cache[pre] as! KVCacheSimple + let (keys, values) = kvCache.writeRows( + keys: outputs[next + 2], values: outputs[next + 3], + position: request.position, visibleLength: visibleLength) + let attention = MLXFast.scaledDotProductAttention( + queries: outputs[next], keys: keys, values: values, + scale: layers[pre].selfAttn!.scale, mask: .array(mask)) + pendingAttention = [attention, outputs[next + 1]] + } + } + + let recurrentInOrder = layers.indices.filter { layers[$0].isLinear } + .map { recurrentCaptures[$0]! } + return (carry, captureLayers.map { captured[$0]! }, recurrentInOrder) + } } public class Qwen35TextModel: Module, LLMModel, KVCacheDimensionProvider { @@ -1283,6 +1493,47 @@ private func qwen35SharedKVOffsets( return ["full_attention": cache[fullAttentionIndex].offset] } +extension Qwen35TextModel: DFlash2TargetModel { + public var dflash2Geometry: DFlash2Geometry { + DFlash2Geometry( + layerCount: model.layers.count, hiddenSize: configuration.hiddenSize, + vocabularySize: vocabularySize) + } + public var dflash2Embedding: Embedding { model.embedTokens } + public var dflash2Head: Linear? { lmHead } + + /// Plain attention caches and gated-delta caches only; subclasses differ in how they write. + public func dflash2SupportsCache(_ cache: [KVCache]) -> Bool { + cache.count == model.layers.count + && zip(model.layers, cache).allSatisfy { layer, entry in + layer.isLinear + ? type(of: entry) == MambaCache.self + : type(of: entry) == KVCacheSimple.self && usesPlainAttentionCacheRoute(entry) + } + } + + public func dflash2Prefill( + _ tokens: MLXArray, cache: [KVCache], captureLayers: [Int] + ) -> (logits: MLXArray, hidden: [MLXArray]) { + let (hidden, captured) = model.forwardLayers( + tokens, cache: cache, captureLayers: captureLayers) + return (logits(model.norm(hidden)), captured) + } + + public func dflash2Verify( + _ request: DFlash2VerifyRequest, cache: [KVCache] + ) -> DFlash2VerifyResult { + let (hidden, captured, recurrentCaptures) = model.verifyStep(request, cache: cache) + return DFlash2VerifyResult( + logits: logits(model.norm(hidden)), hidden: captured, + recurrentCaptures: recurrentCaptures) + } + + private func logits(_ hidden: MLXArray) -> MLXArray { + lmHead?(hidden) ?? model.embedTokens.asLinear(hidden) + } +} + extension Qwen35TextModel: LoRAModel { public var loraLayers: [Module] { model.layers @@ -1349,6 +1600,28 @@ public class Qwen35Model: Module, LLMModel, KVCacheDimensionProvider { } } +extension Qwen35Model: DFlash2TargetModel { + public var dflash2Geometry: DFlash2Geometry { languageModel.dflash2Geometry } + public var dflash2Embedding: Embedding { languageModel.dflash2Embedding } + public var dflash2Head: Linear? { languageModel.dflash2Head } + + public func dflash2SupportsCache(_ cache: [KVCache]) -> Bool { + languageModel.dflash2SupportsCache(cache) + } + + public func dflash2Prefill( + _ tokens: MLXArray, cache: [KVCache], captureLayers: [Int] + ) -> (logits: MLXArray, hidden: [MLXArray]) { + languageModel.dflash2Prefill(tokens, cache: cache, captureLayers: captureLayers) + } + + public func dflash2Verify( + _ request: DFlash2VerifyRequest, cache: [KVCache] + ) -> DFlash2VerifyResult { + languageModel.dflash2Verify(request, cache: cache) + } +} + extension Qwen35Model: LoRAModel { public var loraLayers: [Module] { languageModel.model.layers diff --git a/Libraries/MLXLMCommon/DFlash2DrafterModel.swift b/Libraries/MLXLMCommon/DFlash2DrafterModel.swift new file mode 100644 index 0000000000..ab96e178a2 --- /dev/null +++ b/Libraries/MLXLMCommon/DFlash2DrafterModel.swift @@ -0,0 +1,418 @@ +// Copyright © 2026 Apple Inc. + +import Foundation +import MLX +import MLXNN + +// DFlash2 (https://inco.ai/blog/dflash2/, reference https://github.com/z-lab/dflash) +// drafts a block of tokens in one pass from the target's hidden states; the +// target verifies the block in one forward pass. The drafter and target models +// live in MLXLLM. + +// MARK: - Geometry + +/// The target shape a drafter was distilled for, or the shape a target has. +public struct DFlash2Geometry: Equatable, Sendable, CustomStringConvertible { + /// Decoder layers; `nil` when a drafter checkpoint does not record it. + public var layerCount: Int? + public var hiddenSize: Int + public var vocabularySize: Int + + public init(layerCount: Int?, hiddenSize: Int, vocabularySize: Int) { + self.layerCount = layerCount + self.hiddenSize = hiddenSize + self.vocabularySize = vocabularySize + } + + public var description: String { + "\(layerCount.map(String.init) ?? "?") layers, hidden \(hiddenSize), vocabulary \(vocabularySize)" + } + + /// Whether a drafter distilled for `self`, reading `layerIds`, can draft for `target`. + func accepts(_ target: DFlash2Geometry, layerIds: [Int]) -> Bool { + guard let targetLayers = target.layerCount else { return false } + return hiddenSize == target.hiddenSize && vocabularySize == target.vocabularySize + && (layerCount ?? targetLayers) == targetLayers + && layerIds.allSatisfy { (0 ..< targetLayers).contains($0) } + } +} + +// MARK: - Drafter + +/// One block to propose. Every accept-dependent input may be lazy, so the next +/// proposal can be built while the previous verify pass runs. +public struct DFlash2ProposalRequest { + /// `[1, width]` token ids: the anchor, then mask tokens. + public var block: MLXArray + /// `[1, S, targetLayerIds.count * hidden]` target outputs verified since the last proposal. + public var targetHidden: MLXArray + /// Absolute position of `targetHidden` row 0. + public var contextPosition: Int + /// `[]` int32 count of leading `targetHidden` rows that are committed context. + public var validRows: MLXArray + /// 0 selects greedily; above 0 samples and fills ``DFlash2Proposal/probabilities``. + public var temperature: Float + /// Token ids the target never emits; drafts skip them. + public var suppressedTokens: SuppressTokensProcessor? + + public init( + block: MLXArray, targetHidden: MLXArray, contextPosition: Int, validRows: MLXArray, + temperature: Float, suppressedTokens: SuppressTokensProcessor? = nil + ) { + self.block = block + self.targetHidden = targetHidden + self.contextPosition = contextPosition + self.validRows = validRows + self.temperature = temperature + self.suppressedTokens = suppressedTokens + } +} + +/// The drafted tokens and the per-position candidates they were chosen from. +public struct DFlash2Proposal { + /// `[1, width - 1]` drafted token ids. + public var tokens: MLXArray + /// `[1, width - 1, K]` candidate ids per drafted position. + public var candidates: MLXArray + /// Selection probabilities over `candidates`, present when sampled. + public var probabilities: MLXArray? + + public init(tokens: MLXArray, candidates: MLXArray, probabilities: MLXArray? = nil) { + self.tokens = tokens + self.candidates = candidates + self.probabilities = probabilities + } +} + +/// Per-stream drafter state, owned by the iterator so one drafter serves many streams. +public struct DFlash2DrafterState { + /// One context cache per drafter layer. + public var contextCaches: [DFlash2ContextCache] + + public init(contextCaches: [DFlash2ContextCache]) { + self.contextCaches = contextCaches + } +} + +/// A DFlash2 block drafter. +/// +/// It attends over projections of the target's hidden states and predicts every +/// position of an `[anchor, MASK, ...]` block at once. It borrows the target's +/// embedding and head per call and holds no per-stream state, like +/// ``MTPDrafterModel``. +public protocol DFlash2DrafterModel: BaseLanguageModel { + /// Tokens per verify pass the checkpoint was trained for, anchor included. + var blockSize: Int { get } + /// Token id that fills the block's non-anchor positions. + var maskTokenId: Int { get } + /// Target layers the drafter reads, in feature-concatenation order. + var targetLayerIds: [Int] { get } + /// The target shape the drafter was distilled for. + var targetGeometry: DFlash2Geometry { get } + /// Target hidden rows the drafter's context keeps. + var contextWindow: Int { get } + + func makeState() -> DFlash2DrafterState + + /// Propose one block. `request.targetHidden` rows enter `state` as + /// placeholders until the iterator resolves them. + func propose( + _ request: DFlash2ProposalRequest, target: any DFlash2TargetModel, + state: inout DFlash2DrafterState + ) -> DFlash2Proposal +} + +// MARK: - Target + +/// One verify pass over `[anchor, draft_1, ..., draft_{S-1}]`. +public struct DFlash2VerifyRequest { + /// `[1, S]` token ids. + public var tokens: MLXArray + /// `[1]` int32 absolute position of `tokens[0]`; may be lazy. + public var position: MLXArray + /// Largest value `position` can take. Bounds the attention span. + public var positionUpperBound: Int + /// Layers whose outputs the drafter reads, in ``DFlash2VerifyResult/hidden`` order. + public var captureLayers: [Int] + + public init( + tokens: MLXArray, position: MLXArray, positionUpperBound: Int, captureLayers: [Int] + ) { + self.tokens = tokens + self.position = position + self.positionUpperBound = positionUpperBound + self.captureLayers = captureLayers + } +} + +public struct DFlash2VerifyResult { + /// `[1, S, vocab]`; row `i` predicts input position `i + 1`. + public var logits: MLXArray + /// `[1, S, hidden]` per requested capture layer. + public var hidden: [MLXArray] + /// One capture per gated-delta layer, in cache order. + public var recurrentCaptures: [GatedDeltaCapture] + + public init(logits: MLXArray, hidden: [MLXArray], recurrentCaptures: [GatedDeltaCapture]) { + self.logits = logits + self.hidden = hidden + self.recurrentCaptures = recurrentCaptures + } +} + +/// A hybrid attention / gated-delta target that DFlash2 can speculate for. +/// +/// A verify pass never commits: it writes attention rows at the request's +/// position without moving any offset and returns recurrent state as captures. +/// The iterator commits once the accept count is known. +public protocol DFlash2TargetModel: LanguageModel { + var dflash2Geometry: DFlash2Geometry { get } + /// Embedding table the drafter borrows. + var dflash2Embedding: Embedding { get } + /// LM head the drafter borrows; `nil` when tied to the embedding. + var dflash2Head: Linear? { get } + + /// Whether the verify pass can drive `cache`. + func dflash2SupportsCache(_ cache: [KVCache]) -> Bool + + /// A prefill forward that also returns the outputs of `captureLayers`. + func dflash2Prefill( + _ tokens: MLXArray, cache: [KVCache], captureLayers: [Int] + ) -> (logits: MLXArray, hidden: [MLXArray]) + + func dflash2Verify(_ request: DFlash2VerifyRequest, cache: [KVCache]) -> DFlash2VerifyResult +} + +// MARK: - Recurrent capture + +/// What one gated-delta layer consumed in a verify pass: enough to recompute its +/// state as if only a prefix of the pass had run. +public struct GatedDeltaCapture { + /// `concat([convState, qkv])`, `[1, K - 1 + S, convDim]`. + public var convInput: MLXArray + /// Normalized, scaled `q`/`k` (`[1, S, Hk, Dk]`) and `v` (`[1, S, Hv, Dv]`). + public var q: MLXArray + public var k: MLXArray + public var v: MLXArray + /// Raw gate projections, `[1, S, Hv]`. + public var a: MLXArray + public var b: MLXArray + public var aLog: MLXArray + public var dtBias: MLXArray + /// Recurrent state before the pass. + public var initialState: MLXArray + + public init( + convInput: MLXArray, q: MLXArray, k: MLXArray, v: MLXArray, + a: MLXArray, b: MLXArray, aLog: MLXArray, dtBias: MLXArray, + initialState: MLXArray + ) { + self.convInput = convInput + self.q = q + self.k = k + self.v = v + self.a = a + self.b = b + self.aLog = aLog + self.dtBias = dtBias + self.initialState = initialState + } + + /// The per-pass arrays, so a compiled verify body can return them as outputs. + package var arrays: [MLXArray] { [convInput, q, k, v, a, b] } + + package init(arrays: [MLXArray], aLog: MLXArray, dtBias: MLXArray, initialState: MLXArray) { + precondition(arrays.count == 6, "convInput, q, k, v, a, b") + self.init( + convInput: arrays[0], q: arrays[1], k: arrays[2], v: arrays[3], a: arrays[4], + b: arrays[5], aLog: aLog, dtBias: dtBias, initialState: initialState) + } + + /// The layer's recurrent and conv state after the first `validCount` positions. + /// + /// Positions past `validCount` are masked out of the scan, so the result is + /// exact for any count and `validCount` may be a lazy `[]` int32 array. + public func replay(validCount: MLXArray) -> (recurrent: MLXArray, conv: MLXArray) { + let outputs = compiledGatedDeltaReplay([ + q, k, v, a, b, aLog, dtBias, initialState, convInput, validCount, + ]) + return (outputs[0], outputs[1]) + } +} + +/// One trace serves every layer: their shapes match. +private let compiledGatedDeltaReplay: @Sendable ([MLXArray]) -> [MLXArray] = compile { inputs in + let (q, k, v) = (inputs[0], inputs[1], inputs[2]) + let (a, b, aLog, dtBias) = (inputs[3], inputs[4], inputs[5], inputs[6]) + let (state, convInput, validCount) = (inputs[7], inputs[8], inputs[9]) + let s = q.dim(1) + let mask = (MLXArray(Int32(0) ..< Int32(s)) .< validCount.asType(.int32)) + .expandedDimensions(axis: 0) + let (_, newState) = gatedDeltaUpdate( + q: q, k: k, v: v, a: a, b: b, aLog: aLog, dtBias: dtBias, state: state, mask: mask) + // The conv state after `validCount` positions: rows [validCount, validCount + K - 1). + let kernelRows = convInput.dim(1) - s + let rows = (validCount.asType(.int32) + MLXArray(Int32(0) ..< Int32(kernelRows))) + .reshaped([1, kernelRows, 1]) + let conv = contiguous(takeAlong(convInput, rows, axis: 1)) + return [newState, conv] +} + +// MARK: - Keyed traces + +/// Compiled traces built on demand, one per key. `Module.invalidateCompiledTraces()` +/// finds it by reflection, so replacing modules drops every trace. +package final class KeyedCompiledTraces: CompiledTraceInvalidating { + private let lock = NSLock() + private var traces: [Key: CompiledTrace] = [:] + + package init() {} + + package var count: Int { lock.withLock { traces.count } } + + package func trace(_ key: Key, make: () -> CompiledTrace) -> CompiledTrace { + lock.withLock { + if let existing = traces[key] { return existing } + let trace = make() + traces[key] = trace + return trace + } + } + + package func invalidate() { + lock.withLock { traces.removeAll() } + } +} + +// MARK: - Attention cache rows + +extension KVCacheSimple { + /// Write `S` rows at `position` (`[1]` int32, possibly lazy) without moving + /// `offset`, and return the first `visibleLength` rows. Rows past the + /// committed offset are scratch for a later write to overwrite. + package func writeRows( + keys newKeys: MLXArray, values newValues: MLXArray, + position: MLXArray, visibleLength: Int + ) -> (MLXArray, MLXArray) { + if keys == nil || visibleLength > keys!.dim(2) { + let capacity = (visibleLength + step - 1) / step * step + let kShape = [newKeys.dim(0), newKeys.dim(1), capacity, newKeys.dim(3)] + let vShape = [newValues.dim(0), newValues.dim(1), capacity, newValues.dim(3)] + let grownKeys = MLXArray.zeros(kShape, dtype: newKeys.dtype) + let grownValues = MLXArray.zeros(vShape, dtype: newValues.dtype) + if let keys, let values { + // Keep the whole buffer: scratch rows may belong to a pass in flight. + self.keys = concatenated( + [keys, grownKeys[.ellipsis, keys.dim(2)..., 0...]], axis: 2) + self.values = concatenated( + [values, grownValues[.ellipsis, values.dim(2)..., 0...]], axis: 2) + } else { + keys = grownKeys + values = grownValues + } + } + let rows = (position.asType(.int32) + MLXArray(Int32(0) ..< Int32(newKeys.dim(2)))) + .reshaped([1, 1, -1, 1]) + keys = putAlong(keys!, rows, values: newKeys, axis: 2) + values = putAlong(values!, rows, values: newValues, axis: 2) + return ( + keys![.ellipsis, .. 0, "DFlash2ContextCache needs a positive window") + self.window = window + } + + /// Stored rows, placeholders included. + public var count: Int { storedCount } + + package var keys: MLXArray? { keyStore?[.ellipsis, .. (MLXArray, MLXArray) { + let n = newKeys.dim(2) + precondition(positions.count == n, "one position per appended row") + if keyStore == nil { + let capacity = Swift.max(n, window + compactionSlack) + keyStore = MLXArray.zeros( + [newKeys.dim(0), newKeys.dim(1), capacity, newKeys.dim(3)], dtype: newKeys.dtype) + valueStore = MLXArray.zeros( + [newValues.dim(0), newValues.dim(1), capacity, newValues.dim(3)], + dtype: newValues.dtype) + } + if storedCount + n > keyStore!.dim(2) || storedCount > window + compactionSlack { + compact(reserving: n) + } + keyStore![.ellipsis, storedCount ..< (storedCount + n), 0...] = newKeys + valueStore![.ellipsis, storedCount ..< (storedCount + n), 0...] = newValues + storedCount += n + rowPositions.append(contentsOf: positions) + rowValid.append(contentsOf: Array(repeating: false, count: n)) + return (keys!, values!) + } + + /// Commit the first `valid` of the newest `newest` rows. The rest stay + /// placeholders and drop at the next compaction. + package func resolve(newest: Int, valid: Int) { + precondition(newest <= storedCount, "resolving more rows than stored") + let base = storedCount - newest + for i in 0 ..< newest { + rowValid[base + i] = i < valid + } + } + + /// Keep the newest `window` valid rows in a fresh padded buffer. + private func compact(reserving n: Int) { + let kept = (0 ..< storedCount).filter { rowValid[$0] }.suffix(window) + let gather = MLXArray(kept.map { Int32($0) }) + let keptKeys = MLX.take(keyStore!, gather, axis: 2) + let keptValues = MLX.take(valueStore!, gather, axis: 2) + let capacity = Swift.max(window + compactionSlack, kept.count + n) + let padK = [keptKeys.dim(0), keptKeys.dim(1), capacity - kept.count, keptKeys.dim(3)] + let padV = [ + keptValues.dim(0), keptValues.dim(1), capacity - kept.count, keptValues.dim(3), + ] + keyStore = concatenated([keptKeys, MLXArray.zeros(padK, dtype: keptKeys.dtype)], axis: 2) + valueStore = concatenated( + [keptValues, MLXArray.zeros(padV, dtype: keptValues.dtype)], axis: 2) + rowPositions = kept.map { rowPositions[$0] } + rowValid = Array(repeating: true, count: kept.count) + storedCount = kept.count + } +} diff --git a/Libraries/MLXLMCommon/DFlash2DrafterModelFactory.swift b/Libraries/MLXLMCommon/DFlash2DrafterModelFactory.swift new file mode 100644 index 0000000000..266ba0069f --- /dev/null +++ b/Libraries/MLXLMCommon/DFlash2DrafterModelFactory.swift @@ -0,0 +1,129 @@ +// Copyright © 2026 Apple Inc. + +import Foundation +import MLX + +/// Registry of `model_type` strings to ``DFlash2DrafterModel`` creators. Empty until +/// `DFlash2Registration.register()` in MLXLLM adds the drafter. +public enum DFlash2DrafterTypeRegistry { + public static let shared: ModelTypeRegistry = .init() +} + +/// Registry of DFlash2 drafter ids to ``ModelConfiguration``. +public class DFlash2DrafterRegistry: AbstractModelRegistry, @unchecked Sendable { + public static let shared = DFlash2DrafterRegistry(modelConfigurations: all()) + + public static let qwen38_27B_dflash2 = ModelConfiguration(id: "incoai/Qwen3.8-27B-DFlash2") + + private static func all() -> [ModelConfiguration] { + [qwen38_27B_dflash2] + } +} + +/// A loaded DFlash2 drafter. It has no tokenizer or chat template of its own. +/// Not `Sendable`; share it through ``DFlash2DrafterContainer``. +public struct DFlash2DrafterContext { + public var configuration: ModelConfiguration + public var model: any DFlash2DrafterModel + + public init(configuration: ModelConfiguration, model: any DFlash2DrafterModel) { + self.configuration = configuration + self.model = model + } +} + +/// Sendable container for a ``DFlash2DrafterContext``, in the shape of +/// ``ModelContainer``. +public final class DFlash2DrafterContainer: Sendable { + private let context: SerialAccessContainer + + public var configuration: ModelConfiguration { + get async { + await context.read { $0.configuration } + } + } + + public init(context: consuming DFlash2DrafterContext) { + self.context = .init(context) + } + + /// Perform an action on the context. Evaluate any `MLXArray` before returning it. + public func perform( + _ action: @Sendable (DFlash2DrafterContext) async throws -> sending R + ) async rethrows -> sending R { + try await context.read { + try await action($0) + } + } +} + +/// Loader for DFlash2 drafter checkpoints, in the shape of `LLMModelFactory`. +public final class DFlash2DrafterModelFactory: GenericModelFactory { + public typealias ContextType = DFlash2DrafterContext + public typealias ContainerType = DFlash2DrafterContainer + + public static let shared = DFlash2DrafterModelFactory( + typeRegistry: DFlash2DrafterTypeRegistry.shared, + modelRegistry: DFlash2DrafterRegistry.shared + ) + + public let typeRegistry: ModelTypeRegistry + public let modelRegistry: AbstractModelRegistry + + public init( + typeRegistry: ModelTypeRegistry, + modelRegistry: AbstractModelRegistry + ) { + self.typeRegistry = typeRegistry + self.modelRegistry = modelRegistry + } + + public func _load( + configuration: ResolvedModelConfiguration, + tokenizerLoader: any TokenizerLoader + ) async throws -> DFlash2DrafterContext { + let modelDirectory = configuration.modelDirectory + let configurationURL = modelDirectory.appending(component: "config.json") + let configData: Data + do { + configData = try Data(contentsOf: configurationURL) + } catch { + throw ModelFactoryError.configurationFileError( + configurationURL.lastPathComponent, configuration.name, error) + } + let baseConfig: BaseConfiguration + do { + baseConfig = try JSONDecoder.json5().decode(BaseConfiguration.self, from: configData) + } catch let error as DecodingError { + throw ModelFactoryError.configurationDecodingError( + configurationURL.lastPathComponent, configuration.name, error) + } + + let model: any DFlash2DrafterModel + do { + model = try await typeRegistry.createModel( + configuration: configData, modelType: baseConfig.modelType) + } catch let error as DecodingError { + throw ModelFactoryError.configurationDecodingError( + configurationURL.lastPathComponent, configuration.name, error) + } + + try await loadWeights( + modelDirectory: modelDirectory, model: model, + perLayerQuantization: baseConfig.perLayerQuantization, + weightFileSelection: configuration.weightFileSelection, + excludedComponents: configuration.excludedComponents + ) + + let modelConfig = ModelConfiguration( + directory: modelDirectory, + tokenizerSource: nil, + defaultPrompt: "" + ) + return DFlash2DrafterContext(configuration: modelConfig, model: model) + } + + public func _wrap(_ context: DFlash2DrafterContext) -> DFlash2DrafterContainer { + .init(context: context) + } +} diff --git a/Libraries/MLXLMCommon/DFlash2SpeculativeTokenIterator.swift b/Libraries/MLXLMCommon/DFlash2SpeculativeTokenIterator.swift new file mode 100644 index 0000000000..7861474cd2 --- /dev/null +++ b/Libraries/MLXLMCommon/DFlash2SpeculativeTokenIterator.swift @@ -0,0 +1,542 @@ +// Copyright © 2026 Apple Inc. + +import Foundation +import MLX +import MLXNN + +/// Why a ``DFlash2SpeculativeTokenIterator`` could not be built. +public enum DFlash2SpeculationError: Error, Equatable { + /// The target model does not conform to ``DFlash2TargetModel``. + case unsupportedTarget + /// The cache or the requested KV cache configuration has entries the verify + /// pass cannot write, such as quantized or rotating attention caches. + case unsupportedCache + /// The drafter was distilled for a target of another shape. + case geometryMismatch(drafter: DFlash2Geometry, target: DFlash2Geometry) + /// DFlash2 speculation covers text-only prompts. + case textOnly + /// `prefilledPrefixTokens` must leave at least one prompt token. + case promptTooShort +} + +/// Token iterator for DFlash2 block speculative decoding. +/// +/// Each round verifies `[anchor, draft_1, ..., draft_{S-1}]` in one target pass. +/// The next round is built while that pass runs: the accept count, the bonus +/// token and the next position stay lazy, so the host syncs once per round. +/// +/// Greedy rounds accept the longest prefix that matches the target's argmax. +/// Sampled rounds use rejection sampling against the drafter's candidate +/// distribution, so emitted tokens follow the processed target distribution. +/// A verify pass sums in a different order than a one-token step, so greedy +/// output can differ from ``TokenIterator`` where the top two logits nearly tie. +public struct DFlash2SpeculativeTokenIterator: TokenIteratorProtocol { + let target: any DFlash2TargetModel + let drafter: any DFlash2DrafterModel + + var cache: [KVCache] + var drafterState: DFlash2DrafterState + + var processor: LogitProcessor? + let sampler: LogitSampler + /// Masks suppressed ids in the draft logits; the processor masks them in the target's. + let draftSuppressor: SuppressTokensProcessor? + let temperature: Float + let topP: Float + let topK: Int + let minP: Float + let randomState: MLXRandom.RandomState + + public let maxTokens: Int? + /// Tokens per verify pass: one anchor plus `blockSize - 1` drafts. + public let blockSize: Int + + public private(set) var promptPrefillTime: TimeInterval = 0 + + private var pendingTokens = [Int]() + private var pendingIndex = 0 + /// Drafts the last round accepted, for ``finalizeGeneration()``. + private var committedAcceptedCount = 0 + /// Tokens produced so far, drained or pending. + private var producedTokens = 0 + + /// A round whose verify pass is scheduled but whose accept is unknown. + private struct Round { + var drafts: MLXArray + var candidates: MLXArray + var probabilities: MLXArray? + var width: Int + var verify: DFlash2VerifyResult + } + + private var inFlight: Round? + /// Absolute position of the in-flight round's anchor. + private var anchorPosition = 0 + /// Recurrent captures of the last committed round, for ``finalizeGeneration()``. + private var committedCaptures: [GatedDeltaCapture] = [] + + private var telemetry = SpeculativeDecodingTelemetry() + public var speculativeDecodingTelemetry: SpeculativeDecodingTelemetry? { + telemetry.roundCount > 0 ? telemetry : nil + } + public private(set) var acceptedCount = 0 + public private(set) var proposedCount = 0 + + private var greedy: Bool { temperature <= 0 } + + /// - Parameters: + /// - input: the prompt, text only. + /// - mainModel: the target; must conform to ``DFlash2TargetModel``. + /// - drafter: a DFlash2 drafter distilled for `mainModel`'s shape. + /// - mainCache: a target cache to decode over. + /// - prefilledPrefixTokens: leading positions of `input` that `mainCache` + /// already holds; only the rest is prefilled. + /// - parameters: sampling and generation limits. + /// - blockSize: tokens per verify pass; `nil` uses the drafter's. + /// - components: generation hooks such as a custom logit processor. + public init( + input: LMInput, + mainModel: any LanguageModel, + drafter: any DFlash2DrafterModel, + mainCache: [KVCache]? = nil, + prefilledPrefixTokens: Int = 0, + parameters: GenerateParameters, + blockSize: Int? = nil, + components: GenerationComponents = .init() + ) throws { + guard let target = mainModel as? DFlash2TargetModel else { + throw DFlash2SpeculationError.unsupportedTarget + } + guard + drafter.targetGeometry.accepts(target.dflash2Geometry, layerIds: drafter.targetLayerIds) + else { + throw DFlash2SpeculationError.geometryMismatch( + drafter: drafter.targetGeometry, target: target.dflash2Geometry) + } + guard input.image == nil, input.video == nil, input.audio == nil else { + throw DFlash2SpeculationError.textOnly + } + let promptLength = input.text.tokens.dim(-1) + guard prefilledPrefixTokens >= 0, prefilledPrefixTokens < promptLength else { + throw DFlash2SpeculationError.promptTooShort + } + // The verify pass writes plain attention rows: no compression or capacity. + if let configuration = try parameters.kvCachePlan().configuration, + configuration.capacity != nil || configuration.strategy != .fullPrecision + { + throw DFlash2SpeculationError.unsupportedCache + } + let cache = try mainCache ?? target.newCache(parameters: parameters) + guard target.dflash2SupportsCache(cache) else { + throw DFlash2SpeculationError.unsupportedCache + } + try components.validate(parameters: parameters) + + self.target = target + self.drafter = drafter + self.cache = cache + self.drafterState = drafter.makeState() + self.processor = components.logitProcessor(parameters: parameters, model: mainModel) + self.draftSuppressor = makeSuppressTokensProcessor(model: mainModel) + self.sampler = parameters.sampler() + self.temperature = parameters.temperature + self.topP = parameters.topP + self.topK = parameters.topK + self.minP = parameters.minP + self.randomState = + parameters.seed.map { MLXRandom.RandomState(seed: $0) } ?? MLXRandom.RandomState() + self.maxTokens = parameters.maxTokens + self.blockSize = Swift.max(2, blockSize ?? drafter.blockSize) + + let prefillStart = Date.timeIntervalSinceReferenceDate + try prepare( + input: input, prefilledPrefixTokens: prefilledPrefixTokens, + prefill: parameters.prefill) + self.promptPrefillTime = Date.timeIntervalSinceReferenceDate - prefillStart + } + + // MARK: Prefill + + /// Chunked prefill that keeps the last `contextWindow` captured rows as the + /// drafter's first context, then samples the first token and builds round 0. + private mutating func prepare( + input: LMInput, prefilledPrefixTokens: Int, prefill: PrefillParameters + ) throws { + processor?.prompt(input.text.tokens) + prefill.prefix?(prefilledPrefixTokens) + let promptTokens = input.text.tokens + let promptLength = promptTokens.dim(0) + if prefilledPrefixTokens > 0, + let attention = cache.first(where: { type(of: $0) == KVCacheSimple.self }) + { + precondition( + attention.offset == prefilledPrefixTokens, + "cache holds \(attention.offset) positions, prefilledPrefixTokens is \(prefilledPrefixTokens)" + ) + } + + let window = drafter.contextWindow + let captureLayers = drafter.targetLayerIds + var hiddenWindow: MLXArray? = nil + var hiddenOffset = prefilledPrefixTokens + func forward(_ range: Range) -> MLXArray { + let chunk = promptTokens[range].expandedDimensions(axis: 0) + let result = target.dflash2Prefill(chunk, cache: cache, captureLayers: captureLayers) + var hidden = concatenatedHidden(result.hidden) + if let existing = hiddenWindow { + hidden = concatenated([existing, hidden], axis: 1) + } + let rows = hidden.dim(1) + if rows > window { + hiddenOffset += rows - window + hidden = hidden[0..., (rows - window)..., 0...] + } + hiddenWindow = hidden + return result.logits + } + + let total = promptLength - prefilledPrefixTokens + let processed = try prefill.forEachChunk(total: total) { range in + _ = forward(range.shifted(by: prefilledPrefixTokens)) + asyncEval(cache.flatMap { $0.innerState() } + [hiddenWindow!]) + } + let logits = forward((prefilledPrefixTokens + processed) ..< promptLength) + prefill.progress?(total, total) + + var last = logits[0..., -1, 0...] + last = processor?.process(logits: last) ?? last + let token = sampler.sample(logits: last) + processor?.didSample(token: token) + eval(token) + pendingTokens.append(token.item(Int.self)) + producedTokens = 1 + anchorPosition = promptLength + + // The prompt rows are committed context as soon as round 0 appends them. + let context = hiddenWindow! + let contextRows = buildRound( + anchor: token.reshaped([1]), + validRows: MLXArray(Int32(context.dim(1))), + targetHidden: context, + contextPosition: hiddenOffset, + position: MLXArray([Int32(promptLength)]), + positionUpperBound: promptLength, + producedAtLeast: 1) + for contextCache in drafterState.contextCaches { + contextCache.resolve(newest: contextRows, valid: contextRows) + } + } + + private func concatenatedHidden(_ layers: [MLXArray]) -> MLXArray { + layers.count == 1 ? layers[0] : concatenated(layers, axis: -1) + } + + // MARK: Rounds + + /// Drafts in the next round, fewer near `maxTokens`. `producedAtLeast` is + /// the fewest tokens produced before that round runs. + private func draftCount(producedAtLeast: Int) -> Int? { + guard let maxTokens else { return blockSize - 1 } + let remaining = maxTokens - producedAtLeast + return remaining > 0 ? Swift.min(blockSize - 1, remaining) : nil + } + + /// Schedule one round from possibly lazy inputs: the proposal, then the + /// verify pass over it. Returns the context rows appended to the drafter. + @discardableResult + private mutating func buildRound( + anchor: MLXArray, validRows: MLXArray, targetHidden: MLXArray, + contextPosition: Int, position: MLXArray, positionUpperBound: Int, + producedAtLeast: Int + ) -> Int { + guard let drafts = draftCount(producedAtLeast: producedAtLeast) else { + inFlight = nil + return 0 + } + let masks = MLXArray(Array(repeating: Int32(drafter.maskTokenId), count: drafts)) + let block = concatenated([anchor.asType(.int32), masks]).expandedDimensions(axis: 0) + let proposal = drafter.propose( + DFlash2ProposalRequest( + block: block, targetHidden: targetHidden, contextPosition: contextPosition, + validRows: validRows, temperature: temperature, suppressedTokens: draftSuppressor), + target: target, state: &drafterState) + let draftTokens = proposal.tokens.flattened().asType(.int32) + let request = DFlash2VerifyRequest( + tokens: concatenated([anchor.asType(.int32), draftTokens]).expandedDimensions(axis: 0), + position: position, + positionUpperBound: positionUpperBound, + captureLayers: drafter.targetLayerIds) + let verify = target.dflash2Verify(request, cache: cache) + asyncEval(verify.logits) + inFlight = Round( + drafts: draftTokens, candidates: proposal.candidates, + probabilities: proposal.probabilities, width: drafts + 1, verify: verify) + return targetHidden.dim(1) + } + + /// Accept the in-flight round, build the next one while its verify pass + /// still runs, then sync once and commit. + private mutating func speculateRound() { + guard let round = inFlight else { return } + let gamma = round.width - 1 + + // Accept, lazily. Drafts feed a copy of the processor row by row. + let logits = processedRows(round.verify.logits[0], drafts: round.drafts) + let acceptance: Acceptance + if greedy { + acceptance = Self.greedyAcceptance(drafts: round.drafts, logits: logits) + } else { + acceptance = sampledAcceptance(round: round, logits: logits) + } + asyncEval(acceptance.packed) + + let validCount = acceptance.accepted + 1 + commitRecurrentState(round.verify.recurrentCaptures, validCount: validCount) + + let appendedRows = buildRound( + anchor: acceptance.bonus, + validRows: validCount, + targetHidden: concatenatedHidden(round.verify.hidden), + contextPosition: anchorPosition, + position: MLXArray([Int32(anchorPosition)]) + validCount.asType(.int32), + positionUpperBound: anchorPosition + round.width, + producedAtLeast: producedTokens + 1) + + // The round's one host sync. + let packed = acceptance.packed.asArray(Int32.self) + let drafts = packed[0 ..< gamma].map(Int.init) + let accepted = Int(packed[gamma]) + let bonus = Int(packed[gamma + 1]) + + let committed = anchorPosition + accepted + 1 + for entry in cache { + if let recurrent = entry as? MambaCache { + recurrent.offset = committed + } else if let attention = entry as? KVCacheSimple { + attention.commitRows(count: committed) + } + } + for contextCache in drafterState.contextCaches { + contextCache.resolve(newest: appendedRows, valid: accepted + 1) + } + for token in drafts.prefix(accepted) { + processor?.didSample(token: MLXArray(token)) + } + processor?.didSample(token: MLXArray(bonus)) + + var newTokens = Array(drafts.prefix(accepted)) + newTokens.append(bonus) + if let maxTokens { + newTokens = Array(newTokens.prefix(Swift.max(0, maxTokens - tokenCount))) + } + pendingTokens.append(contentsOf: newTokens) + committedAcceptedCount = accepted + producedTokens += accepted + 1 + anchorPosition = committed + committedCaptures = round.verify.recurrentCaptures + + proposedCount += gamma + acceptedCount += accepted + telemetry.recordRound( + drafted: gamma, accepted: accepted, targetVerified: gamma + 1, draftModelCalls: 1) + } + + /// `[S, vocab]` verify logits through the processor, row by row on a copy + /// that has seen the drafts before each row. Row `i` matters only when + /// drafts `0 ..< i` were accepted, so that is the history it sees. + private func processedRows(_ logits: MLXArray, drafts: MLXArray) -> MLXArray { + guard let processor else { return logits } + var scratch = processor.copy() + var rows: [MLXArray] = [] + for i in 0 ..< logits.dim(0) { + rows.append(scratch.process(logits: logits[i ..< (i + 1)])) + if i < drafts.dim(0) { + scratch.didSample(token: drafts[i ..< (i + 1)]) + } + } + return concatenated(rows, axis: 0) + } + + /// Give every gated-delta layer the state it would hold after the first + /// `validCount` positions of the pass. Exact for any count, so it is built + /// before the count is known. + private func commitRecurrentState(_ captures: [GatedDeltaCapture], validCount: MLXArray) { + let recurrentCaches = cache.compactMap { $0 as? MambaCache } + precondition( + recurrentCaches.count == captures.count, + "\(captures.count) recurrent captures for \(recurrentCaches.count) recurrent caches") + for (recurrent, capture) in zip(recurrentCaches, captures) { + let replayed = capture.replay(validCount: validCount) + recurrent[0] = replayed.conv + recurrent[1] = replayed.recurrent + } + } + + // MARK: Acceptance + + /// The accept outcome as lazy arrays, plus `[drafts..., accepted, bonus]` + /// packed for the round's one sync. + struct Acceptance { + var accepted: MLXArray + var bonus: MLXArray + var packed: MLXArray + } + + /// Accept the longest prefix that matches the target's argmax; the bonus is + /// the argmax at the first mismatch. + private static func greedyAcceptance(drafts: MLXArray, logits: MLXArray) -> Acceptance { + let gamma = drafts.dim(0) + let targets = argMax(logits, axis: -1).asType(.int32) + let matches = (drafts .== targets[0 ..< gamma]).asType(.int32) + let accepted = cumprod(matches).sum() + let bonus = takeAlong(targets, accepted.reshaped([1]), axis: 0) + return Acceptance( + accepted: accepted, bonus: bonus, + packed: concatenated([drafts, accepted.reshaped([1]), bonus])) + } + + /// Rejection sampling against the drafter's candidate distribution, as the + /// reference `_rejection_sample` does. + private func sampledAcceptance(round: Round, logits: MLXArray) -> Acceptance { + guard let probabilities = round.probabilities else { + preconditionFailure("sampled proposal without selector probabilities") + } + let targetProbs = speculativeSamplingProbabilities( + logits, temperature: temperature, topP: topP, minP: minP, topK: topK) + return withRandomState(randomState) { + Self.rejectionSample( + drafts: round.drafts, targetProbs: targetProbs, + draftProbs: probabilities[0], candidates: round.candidates[0]) + } + } + + static func rejectionSample( + drafts: MLXArray, targetProbs: MLXArray, draftProbs: MLXArray, candidates: MLXArray + ) -> Acceptance { + let gamma = drafts.dim(0) + // p: the target's probability of each draft; q: the drafter's. + let p = takeAlong(targetProbs[0 ..< gamma], drafts[0..., .newAxis], axis: -1)[0..., 0] + let drafted = (candidates .== drafts[0..., .newAxis]).asType(.float32) + let q = (draftProbs * drafted).sum(axis: -1) + let accept = (uniform(0 ..< 1, [gamma]) * q) .< p + let accepted = cumprod(accept.asType(.int32)).sum() + + // Past a fully accepted block the bonus is the target's own sample. At a + // rejection it is drawn from `max(p - q, 0)`, or from `p` if that is empty. + let targetRow = takeAlong(targetProbs, accepted.reshaped([1, 1]), axis: 0)[0] + let rejectedRow = minimum(accepted, MLXArray(Int32(gamma - 1))).reshaped([1, 1]) + let candidateRow = takeAlong(candidates, rejectedRow, axis: 0)[0] + let draftRow = takeAlong(draftProbs, rejectedRow, axis: 0)[0] + var residual = putAlong( + targetRow, candidateRow, + values: takeAlong(targetRow, candidateRow, axis: -1) - draftRow, axis: -1) + residual = maximum(residual, MLXArray(Float(0))) + let total = residual.sum() + residual = MLX.where( + total .> 0, residual / maximum(total, MLXArray(Float(1e-30))), targetRow) + let bonusDistribution = MLX.where(accepted .== Int32(gamma), targetRow, residual) + let bonus = categorical(log(bonusDistribution)).asType(.int32).reshaped([1]) + return Acceptance( + accepted: accepted, bonus: bonus, + packed: concatenated([drafts, accepted.reshaped([1]), bonus])) + } + + // MARK: TokenIteratorProtocol + + public var tokenCount: Int { telemetry.emittedTokenCount } + + public var reasoningTokenCount: Int? { + (processor as? any GenerationReasoningTokenCounting)?.generationReasoningTokenCount + } + + public mutating func recordEmittedToken(_ token: Int) { + processor?.didEmit(token: token) + } + + public mutating func discardGeneratedToken() { + telemetry.discardGeneratedToken() + } + + public mutating func next() -> Int? { + if let maxTokens, tokenCount >= maxTokens { + return nil + } + if pendingIndex == pendingTokens.count { + pendingTokens.removeAll(keepingCapacity: true) + pendingIndex = 0 + committedAcceptedCount = 0 + autoreleasepool { speculateRound() } + if pendingTokens.isEmpty { + return nil + } + } + // Return freed buffers after prefill and every 256 tokens, as TokenIterator does. + if tokenCount % 256 == 0 { + Memory.clearCache() + } + let token = pendingTokens[pendingIndex] + pendingIndex += 1 + telemetry.recordGeneratedToken() + return token + } +} + +extension DFlash2SpeculativeTokenIterator: GenerationFinalizingTokenIterator { + /// Rewind the cache to the tokens the consumer drained. Pending draft `j` + /// sits at verify position `j + 1`; the bonus has no cache row yet. + public mutating func finalizeGeneration() { + defer { processor?.finalizeGeneration() } + let kept = Swift.min(pendingIndex, committedAcceptedCount) + let rewind = committedAcceptedCount - kept + guard rewind > 0 else { return } + for entry in cache { + if let recurrent = entry as? MambaCache { + recurrent.offset -= rewind + } else if entry.isTrimmable { + entry.trim(rewind) + } + } + commitRecurrentState(committedCaptures, validCount: MLXArray(Int32(kept + 1))) + anchorPosition -= rewind + committedAcceptedCount = kept + } +} + +extension DFlash2SpeculativeTokenIterator: MTPStatsCollecting { + public var proposedDraftTokens: Int { proposedCount } + public var acceptedDraftTokens: Int { acceptedCount } + public var passthroughReason: String? { nil } +} + +// MARK: - Sampling distribution + +/// The distribution a sampled round accepts against: ``TopPSampler``'s filters +/// in its order (top-p, min-p, top-k on log-probabilities, then temperature). +func speculativeSamplingProbabilities( + _ logits: MLXArray, temperature: Float, topP: Float, minP: Float, topK: Int +) -> MLXArray { + var logprobs = logSoftmax(logits.asType(.float32), axis: -1) + let negInf = MLXArray(-Float.infinity) + if topP > 0, topP < 1 { + let sortedIndices = argSort(logprobs, axis: -1) + let sortedLogprobs = takeAlong(logprobs, sortedIndices, axis: -1) + let cumulative = cumsum(exp(sortedLogprobs), axis: -1) + let filtered = MLX.where(cumulative .> (1 - topP), sortedLogprobs, negInf) + logprobs = putAlong(logprobs, sortedIndices, values: filtered, axis: -1) + } + if minP > 0 { + let threshold = logprobs.max(axis: -1, keepDims: true) + log(MLXArray(minP)) + logprobs = MLX.where(logprobs .>= threshold, logprobs, negInf) + } + if topK > 0, topK < logprobs.dim(-1) { + let masked = argPartition(-logprobs, kth: topK - 1, axis: -1)[0..., topK...] + logprobs = putAlong(logprobs, masked, values: negInf, axis: -1) + } + return softmax(logprobs * (1 / temperature), axis: -1) +} + +extension Range where Bound == Int { + fileprivate func shifted(by offset: Int) -> Range { + (lowerBound + offset) ..< (upperBound + offset) + } +} diff --git a/Libraries/MLXLMCommon/Evaluate.swift b/Libraries/MLXLMCommon/Evaluate.swift index f967f9bf12..d0b8f00e95 100644 --- a/Libraries/MLXLMCommon/Evaluate.swift +++ b/Libraries/MLXLMCommon/Evaluate.swift @@ -2556,6 +2556,95 @@ public func generateTokens( return stream } +/// Generates tokens asynchronously using DFlash2 speculative decoding. +/// +/// Parallel to ``generate(input:cache:parameters:context:mtpDrafter:blockSize:components:wiredMemoryTicket:tools:)`` +/// for a ``DFlash2DrafterModel``. The target must conform to ``DFlash2TargetModel``. +/// +/// - Parameters: +/// - input: text input for the target model. +/// - cache: optional ``KVCache`` for the target model. +/// - parameters: generation parameters. +/// - context: model context for the target model. +/// - dflash2Drafter: the drafter. It holds no per-stream state, so iterators can share it. +/// - blockSize: tokens per verify pass, anchor included; `nil` uses the drafter's. +/// - components: optional behavioral components, e.g. a custom ``LogitProcessor`` +/// - wiredMemoryTicket: optional wired memory ticket. +/// - tools: Optional tool schemas used to parse arguments and authorize function names. +/// - Returns: an `AsyncStream` yielding chunks and tool calls. +/// - Throws: ``DFlash2SpeculationError`` when the target, cache or input is unsupported. +public func generate( + input: LMInput, + cache: [KVCache]? = nil, + parameters: GenerateParameters, + context: ModelContext, + dflash2Drafter: any DFlash2DrafterModel, + blockSize: Int? = nil, + components: GenerationComponents = .init(), + wiredMemoryTicket: WiredMemoryTicket? = nil, + tools: [[String: any Sendable]]? = nil +) throws -> AsyncStream { + let iterator = try DFlash2SpeculativeTokenIterator( + input: input, + mainModel: context.model, + drafter: dflash2Drafter, + mainCache: cache, + parameters: parameters, + blockSize: blockSize, + components: components + ) + let (stream, _) = generateLoopTask( + promptTokenCount: input.text.tokens.size, + modelConfiguration: context.configuration, + tokenizer: context.tokenizer, + iterator: iterator, + wiredMemoryTicket: wiredMemoryTicket, + handler: TextToolTokenLoopHandler( + tokenizer: context.tokenizer, + stopStrings: context.configuration.effectiveStopStrings, + format: context.configuration.toolCallFormat ?? .json, + tools: tools, + toolCallPolicy: parameters.toolCallPolicy + ) + ) + return stream +} + +/// Generates raw token IDs asynchronously using DFlash2 speculative decoding. +/// +/// Parallels +/// ``generate(input:cache:parameters:context:dflash2Drafter:blockSize:components:wiredMemoryTicket:tools:)`` +/// but yields raw token IDs instead of decoded text or tool calls. +public func generateTokens( + input: LMInput, + cache: [KVCache]? = nil, + parameters: GenerateParameters, + context: ModelContext, + dflash2Drafter: any DFlash2DrafterModel, + blockSize: Int? = nil, + components: GenerationComponents = .init(), + wiredMemoryTicket: WiredMemoryTicket? = nil +) throws -> AsyncStream { + let iterator = try DFlash2SpeculativeTokenIterator( + input: input, + mainModel: context.model, + drafter: dflash2Drafter, + mainCache: cache, + parameters: parameters, + blockSize: blockSize, + components: components + ) + let (stream, _) = generateLoopTask( + promptTokenCount: input.text.tokens.size, + modelConfiguration: context.configuration, + tokenizer: context.tokenizer, + iterator: iterator, + wiredMemoryTicket: wiredMemoryTicket, + handler: RawTokenLoopHandler() + ) + return stream +} + /// Generates raw token IDs asynchronously and returns the stream plus a `Task`. /// /// Prefer this overload if you want to be able to observe when the underlying generation work is finished diff --git a/Tests/MLXLMTests/DFlash2Tests.swift b/Tests/MLXLMTests/DFlash2Tests.swift new file mode 100644 index 0000000000..2ff5b676c6 --- /dev/null +++ b/Tests/MLXLMTests/DFlash2Tests.swift @@ -0,0 +1,1162 @@ +// Copyright © 2026 Apple Inc. + +// Synthetic tests for the DFlash2 drafter and its speculative iterator. +// Real-weight parity with the Python reference needs the checkpoints and +// lives with the integration tests. + +import Foundation +import MLX +import MLXNN +import Testing +import XCTest + +@testable import MLXLLM +@testable import MLXLMCommon + +// MARK: - Configuration + +private func configJSON( + hiddenSize: Int = 64, layers: Int = 2, heads: Int = 4, kvHeads: Int = 2, + headDim: Int = 16, intermediate: Int = 96, vocab: Int = 64, window: Int = 8, + topK: Int = 4, rank: Int = 8, layerType: String = "sliding_attention", + isCausal: String = "false" +) -> String { + let layerTypes = Array(repeating: "\"\(layerType)\"", count: layers).joined(separator: ", ") + return """ + { + "architectures": ["DFlash2DraftModel"], + "is_causal": \(isCausal), + "dflash_config": { + "block_size": 5, + "conv_group_size": 16, + "conv_kernel_size": 2, + "mask_token_id": \(vocab - 2), + "selector_rank": \(rank), + "selector_top_k": \(topK), + "target_layer_ids": [1, 3] + }, + "head_dim": \(headDim), + "hidden_size": \(hiddenSize), + "intermediate_size": \(intermediate), + "layer_types": [\(layerTypes)], + "max_position_embeddings": 1024, + "model_type": "qwen3", + "num_attention_heads": \(heads), + "num_hidden_layers": \(layers), + "num_key_value_heads": \(kvHeads), + "num_target_layers": 4, + "rms_norm_eps": 1e-06, + "rope_parameters": { "rope_theta": 10000.0, "rope_type": "default" }, + "sliding_window": \(window), + "vocab_size": \(vocab) + } + """ +} + +private func tinyConfig(window: Int = 8, vocab: Int = 64) -> DFlash2Configuration { + try! JSONDecoder.json5().decode( + DFlash2Configuration.self, from: Data(configJSON(vocab: vocab, window: window).utf8)) +} + +@Test +func testDFlash2ConfigurationDecodesReleaseCheckpoint() throws { + // Mirrors incoai/Qwen3.8-27B-DFlash2's config.json. + let json = """ + { + "architectures": ["DFlash2DraftModel"], + "is_causal": false, + "dflash_config": { + "block_size": 8, + "conv_group_size": 16, + "conv_kernel_size": 2, + "mask_token_id": 248070, + "selector_rank": 256, + "selector_top_k": 16, + "target_layer_ids": [5, 19, 33, 47, 61] + }, + "head_dim": 128, + "hidden_size": 5120, + "intermediate_size": 17408, + "layer_types": ["sliding_attention", "sliding_attention", "sliding_attention", "sliding_attention", "sliding_attention"], + "max_position_embeddings": 262144, + "model_type": "qwen3", + "num_attention_heads": 32, + "num_hidden_layers": 5, + "num_key_value_heads": 8, + "num_target_layers": 64, + "rms_norm_eps": 1e-06, + "rope_parameters": { "rope_theta": 10000000, "rope_type": "default" }, + "sliding_window": 2048, + "tie_word_embeddings": false, + "vocab_size": 248320 + } + """ + let config = try JSONDecoder.json5().decode( + DFlash2Configuration.self, from: Data(json.utf8)) + #expect(config.hiddenSize == 5120) + #expect(config.hiddenLayers == 5) + #expect(config.kvHeads == 8) + #expect(config.headDim == 128) + #expect(config.ropeTheta == 10_000_000) + #expect(config.slidingWindow == 2048) + #expect(config.contextWindow == 2047) + #expect(config.numTargetLayers == 64) + #expect(config.dflash.blockSize == 8) + #expect(config.dflash.maskTokenId == 248070) + #expect(config.dflash.selectorTopK == 16) + #expect(config.dflash.targetLayerIds == [5, 19, 33, 47, 61]) +} + +@Test +func testDFlash2ConfigurationRejectsUnsupportedShapes() { + let causal = Data(configJSON(isCausal: "true").utf8) + #expect(throws: DecodingError.self) { + try JSONDecoder.json5().decode(DFlash2Configuration.self, from: causal) + } + let full = Data(configJSON(layerType: "full_attention").utf8) + #expect(throws: DecodingError.self) { + try JSONDecoder.json5().decode(DFlash2Configuration.self, from: full) + } +} + +@Test +func testDFlash2ConfigurationReadsTheMLXCommunityLayout() throws { + // Mirrors mlx-community/Qwen3.6-35B-A3B-DFlash2-4bit: the window lives in + // dflash_config, block_size is top level, and num_target_layers is absent. + let json = """ + { + "architectures": ["DFlash2DraftModel"], + "model_type": "qwen3", + "hidden_size": 2048, + "intermediate_size": 6144, + "num_hidden_layers": 6, + "vocab_size": 248320, + "num_attention_heads": 32, + "num_key_value_heads": 8, + "head_dim": 128, + "rms_norm_eps": 1e-06, + "max_position_embeddings": 262144, + "rope_parameters": { "rope_type": "default", "rope_theta": 10000000.0 }, + "block_size": 8, + "is_causal": false, + "quantization": { "mode": "affine", "bits": 4, "group_size": 64 }, + "dflash_config": { + "mask_token_id": 248077, + "target_layer_ids": [1, 6, 11, 16, 22, 27, 32, 37], + "conv_kernel_size": 2, + "conv_group_size": 16, + "selector_rank": 256, + "selector_top_k": 16, + "use_swa": true, + "swa_window_size": 2048 + } + } + """ + let config = try JSONDecoder.json5().decode( + DFlash2Configuration.self, from: Data(json.utf8)) + #expect(config.dflash.blockSize == 8) + #expect(config.slidingWindow == 2048) + #expect(config.numTargetLayers == nil) + #expect(config.dflash.maskTokenId == 248077) + + let noWindow = json.replacingOccurrences(of: "\"use_swa\": true", with: "\"use_swa\": false") + #expect(throws: DecodingError.self) { + try JSONDecoder.json5().decode(DFlash2Configuration.self, from: Data(noWindow.utf8)) + } +} + +@Test +func testDFlash2GeometryChecksWidthVocabularyAndDepth() { + let target = DFlash2Geometry(layerCount: 40, hiddenSize: 2048, vocabularySize: 248320) + let ids = [1, 6, 11, 16, 22, 27, 32, 37] + func drafter(_ layers: Int?, _ hidden: Int = 2048, _ vocab: Int = 248320) -> DFlash2Geometry { + DFlash2Geometry(layerCount: layers, hiddenSize: hidden, vocabularySize: vocab) + } + #expect(drafter(40).accepts(target, layerIds: ids)) + // A checkpoint without the depth still has to tap layers the target has. + #expect(drafter(nil).accepts(target, layerIds: ids)) + #expect(!drafter(nil).accepts(target, layerIds: ids + [40])) + #expect(!drafter(64).accepts(target, layerIds: ids)) + #expect(!drafter(40, 5120).accepts(target, layerIds: ids)) + #expect(!drafter(40, 2048, 202048).accepts(target, layerIds: ids)) +} + +// MARK: - Context cache + +@Test +func testDFlash2ContextCachePlaceholdersResolve() { + let cache = DFlash2ContextCache(window: 4) + let rows = MLXArray.ones([1, 1, 3, 2]) + cache.append(keys: rows, values: rows, positions: [0, 1, 2]) + #expect(cache.count == 3) + #expect(cache.rowValid == [false, false, false]) + + cache.resolve(newest: 3, valid: 2) + #expect(cache.rowValid == [true, true, false]) + + let more = MLXArray.ones([1, 1, 2, 2]) * 2 + cache.append(keys: more, values: more, positions: [2, 3]) + cache.resolve(newest: 2, valid: 2) + #expect(cache.count == 5) + #expect(cache.rowPositions == [0, 1, 2, 2, 3]) + #expect(cache.rowValid == [true, true, false, true, true]) +} + +@Test +func testDFlash2ContextCacheCompactionKeepsNewestValidRows() { + let cache = DFlash2ContextCache(window: 4) + var tag: Float = 0 + var position: Int32 = 0 + // 86 appends fill 258 of the 260-row buffer; the next one compacts. + for _ in 0 ..< 86 { + let rows = MLXArray.full([1, 1, 3, 2], values: MLXArray(tag)) + cache.append(keys: rows, values: rows, positions: [position, position + 1, position + 2]) + // The last row of every append stays a placeholder. + cache.resolve(newest: 3, valid: 2) + tag += 1 + position += 3 + } + // The newest 4 valid rows survive, in order, and the new rows follow. + let rows = MLXArray.full([1, 1, 3, 2], values: MLXArray(tag)) + cache.append(keys: rows, values: rows, positions: [position, position + 1, position + 2]) + #expect(cache.count == 7) + #expect(cache.rowValid == [true, true, true, true, false, false, false]) + let values = cache.values![0, 0, 0..., 0].asArray(Float.self) + #expect(values == [tag - 2, tag - 2, tag - 1, tag - 1, tag, tag, tag]) + #expect(cache.rowPositions.suffix(3) == [position, position + 1, position + 2]) +} + +// MARK: - Visibility mask + +@Test +func testDFlash2VisibilityMaskWindowsAndHidesPlaceholders() { + let cache = DFlash2ContextCache(window: 8) + let old = MLXArray.ones([1, 1, 4, 2]) + cache.append(keys: old, values: old, positions: [0, 1, 2, 3]) + cache.resolve(newest: 4, valid: 4) + let new = MLXArray.ones([1, 1, 2, 2]) + cache.append(keys: new, values: new, positions: [4, 5]) + + // One of the two appended rows is valid; the block starts at 5. + let mask = DFlash2DraftModel.visibilityMask( + cache: cache, appended: 2, validRows: MLXArray(Int32(1)), + blockPosition: MLXArray([Int32(5)]), width: 3, window: 3) + #expect(mask.shape == [3, 9]) + let expected: [[Bool]] = [ + [false, false, false, true, true, false, true, true, true], + [false, false, false, false, true, false, true, true, true], + [false, false, false, false, false, false, true, true, true], + ] + #expect(mask.asArray(Bool.self) == expected.flatMap { $0 }) +} + +// MARK: - Dynamic conv + +@Test +func testDFlash2DynamicConvMatchesNaive() throws { + let (hiddenSize, kernelSize, groupSize) = (16, 2, 4) + let conv = DFlash2DynamicConv( + hiddenSize: hiddenSize, kernelSize: kernelSize, groupSize: groupSize) + + MLXRandom.seed(7) + let base = MLXRandom.normal([2, kernelSize, hiddenSize]).asType(.bfloat16) + let proj = MLXRandom.normal([2 * kernelSize * (hiddenSize / groupSize), hiddenSize]) + .asType(.bfloat16) + try conv.update( + parameters: ModuleParameters.unflattened([ + ("base_kernel", base), ("kernel_projection.weight", proj), + ]), + verify: []) + + let hidden = MLXRandom.normal([1, 5, hiddenSize]).asType(.bfloat16) + let (prepared, kernel) = conv.prepare(hidden) + let finished = conv.finish(hidden, kernel: kernel) + eval(prepared, finished) + + let fullDyn = conv.kernelProjection(hidden).reshaped( + 1, 5, 2, kernelSize, hiddenSize / groupSize) + let kernel0 = fullDyn[0..., 0..., 0, 0..., 0...] + eval(kernel0) + + func naive(_ x: MLXArray, baseRow: Int, dynamic: MLXArray) -> [[Float]] { + let xF = x.asType(.float32) + let groups = hiddenSize / groupSize + let dynF = dynamic.asType(.float32) + let baseF = base.asType(.float32) + var out = [[Float]](repeating: [Float](repeating: 0, count: hiddenSize), count: 5) + for t in 0 ..< 5 { + for tap in 0 ..< kernelSize { + let src = t - tap + guard src >= 0 else { continue } + for g in 0 ..< groups { + let d = dynF[0, t, tap, g].item(Float.self) + for c in 0 ..< groupSize { + let ch = g * groupSize + c + let kVal = baseF[baseRow, tap, ch].item(Float.self) + d + out[t][ch] += kVal * xF[0, src, ch].item(Float.self) + } + } + } + } + return out + } + + // bf16 rounding in the module vs f32 accumulation in the loop. + let expectedPre = naive(hidden, baseRow: 0, dynamic: kernel0) + let preparedF = prepared.asType(.float32) + let expectedFin = naive(hidden, baseRow: 1, dynamic: kernel) + let finishedF = finished.asType(.float32) + for t in 0 ..< 5 { + for ch in 0 ..< hiddenSize { + #expect(abs(preparedF[0, t, ch].item(Float.self) - expectedPre[t][ch]) < 0.15) + #expect(abs(finishedF[0, t, ch].item(Float.self) - expectedFin[t][ch]) < 0.15) + } + } +} + +// MARK: - Selector + +@Test +func testDFlash2SelectorGreedyPrefersCoherentPath() throws { + // vocab 12, topK 3, rank 4, hidden 8. Position 0's top-1 candidate is a + // decoy; the selector must switch to the candidate the anchor points at. + let config = try JSONDecoder.json5().decode( + DFlash2Configuration.self, + from: Data( + configJSON( + hiddenSize: 8, layers: 1, heads: 1, kvHeads: 1, headDim: 8, intermediate: 8, + vocab: 12, window: 4, topK: 3, rank: 4 + ).utf8)) + let selector = DFlash2CandidateSelector(config) + + var proj = [Float](repeating: 0, count: 4 * 8) + for i in 0 ..< 4 { proj[i * 8 + i] = 1 } + try selector.hiddenProjection.update( + parameters: ModuleParameters.unflattened([("weight", MLXArray(proj, [4, 8]))]), + verify: []) + var pred = [Float](repeating: 0, count: 12 * 4) + pred[9 * 4 + 0] = 1 + var succ = [Float](repeating: 0, count: 12 * 4) + succ[5 * 4 + 0] = 50 + try selector.predecessorCodebook.update( + parameters: ModuleParameters.unflattened([("weight", MLXArray(pred, [12, 4]))]), + verify: []) + try selector.successorCodebook.update( + parameters: ModuleParameters.unflattened([("weight", MLXArray(succ, [12, 4]))]), + verify: []) + eval(selector.parameters()) + + // pos 0: raw top-1 is 7, but 5 wins through the anchor edge; pos 1: 2. + var logits = [Float](repeating: -30, count: 2 * 12) + logits[0 * 12 + 7] = 10 + logits[0 * 12 + 5] = 9 + logits[0 * 12 + 1] = 8 + logits[1 * 12 + 2] = 10 + logits[1 * 12 + 3] = 9 + logits[1 * 12 + 4] = 8 + let proposal = selector.select( + hidden: MLXArray.ones([1, 2, 8]), logits: MLXArray(logits, [1, 2, 12]), + anchor: MLXArray([Int32(9)]), temperature: 0) + eval(proposal.tokens, proposal.candidates) + #expect(proposal.probabilities == nil) + #expect(proposal.tokens.asArray(Int32.self) == [5, 2]) + #expect(proposal.candidates.shape == [1, 2, 3]) + + let sampled = selector.select( + hidden: MLXArray.ones([1, 2, 8]), logits: MLXArray(logits, [1, 2, 12]), + anchor: MLXArray([Int32(9)]), temperature: 1) + #expect(sampled.probabilities?.shape == [1, 2, 3]) +} + +// MARK: - Mock target and drafter + +/// Target with one attention cache and one recurrent cache. Its logits +/// depend only on the input token, `argmax = transition(token)`, so any +/// decoding of the same prompt is deterministic and comparable. +private final class MockTarget: Module, LanguageModel, KVCacheDimensionProvider, + DFlash2TargetModel, SuppressedTokensProviding +{ + static let vocab = 128 + static let hidden = 64 + static let Hk = 1 + static let Dk = 32 + static let Hv = 2 + static let Dv = 16 + static let K = 4 + static var convDim: Int { 2 * Hk * Dk + Hv * Dv } + + var kvHeads: [Int] { [1] } + let embedding = Embedding(embeddingCount: vocab, dimensions: hidden) + private(set) var verifyCalls = 0 + private(set) var verifyWidths: [Int] = [] + + var suppressedTokenIds: Set = [] + + /// Per-position token script for the verify rows; nil uses `transition`. + var script: [Int32]? + private var scriptIndex = 0 + + override init() { + super.init() + } + + static func transition(_ token: Int) -> Int { (token * 7 + 3) % vocab } + + private func logits(for tokens: MLXArray) -> MLXArray { + let ids = tokens.flattened().asArray(Int32.self).map(Int.init) + var data = [Float](repeating: 0, count: ids.count * Self.vocab) + for (i, token) in ids.enumerated() { + let best: Int + if let script { + best = scriptIndex < script.count ? Int(script[scriptIndex]) : 0 + scriptIndex += 1 + } else { + best = Self.transition(token) + } + data[i * Self.vocab + best] = 10 + data[i * Self.vocab + (best + 1) % Self.vocab] = 9 + data[i * Self.vocab + (best + 2) % Self.vocab] = 8 + } + return MLXArray(data, [1, ids.count, Self.vocab]) + } + + private func writeKV(_ cache: [KVCache], positions: Int) { + for entry in cache { + if let simple = entry as? KVCacheSimple { + let kv = MLXArray.zeros([1, 1, positions, 4]) + _ = simple.update(keys: kv, values: kv) + } else if let mamba = entry as? MambaCache { + mamba.advance(positions) + mamba.offset += positions + } + } + } + + // LanguageModel + + func callAsFunction(_ inputs: MLXArray, cache: [KVCache]?) -> MLXArray { + if let cache { writeKV(cache, positions: inputs.dim(-1)) } + return logits(for: inputs) + } + + func prepare( + _ input: LMInput, cache: [KVCache], state: LMOutput.State?, prefill: PrefillParameters + ) throws -> PrepareResult { + .tokens(input.text) + } + + func callAsFunction( + _ input: LMInput.Text, cache: [KVCache]?, state: LMOutput.State? + ) -> LMOutput { + LMOutput(logits: self(input.tokens, cache: cache)) + } + + func newCache(parameters: GenerateParameters?) -> [KVCache] { + let mamba = MambaCache() + mamba[0] = MLXArray.zeros([1, Self.K - 1, Self.convDim], dtype: .bfloat16) + mamba[1] = MLXArray.zeros([1, Self.Hv, Self.Dv, Self.Dk], dtype: .float32) + return [KVCacheSimple(), mamba] + } + + // DFlash2TargetModel + + var dflash2Geometry: DFlash2Geometry { + DFlash2Geometry(layerCount: 4, hiddenSize: Self.hidden, vocabularySize: Self.vocab) + } + var dflash2Embedding: Embedding { embedding } + var dflash2Head: Linear? { nil } + + func dflash2SupportsCache(_ cache: [KVCache]) -> Bool { + cache.count == 2 && cache[0] is KVCacheSimple && cache[1] is MambaCache + } + + func dflash2Prefill( + _ tokens: MLXArray, cache: [KVCache], captureLayers: [Int] + ) -> (logits: MLXArray, hidden: [MLXArray]) { + let positions = tokens.dim(-1) + writeKV(cache, positions: positions) + return ( + logits(for: tokens), + captureLayers.map { _ in MLXArray.zeros([1, positions, Self.hidden]) } + ) + } + + func dflash2Verify(_ request: DFlash2VerifyRequest, cache: [KVCache]) -> DFlash2VerifyResult { + verifyCalls += 1 + let positions = request.tokens.dim(-1) + verifyWidths.append(positions) + let attention = cache[0] as! KVCacheSimple + let kv = MLXArray.zeros([1, 1, positions, 4]) + _ = attention.writeRows( + keys: kv, values: kv, position: request.position, + visibleLength: request.positionUpperBound + positions) + let mamba = cache[1] as! MambaCache + MLXRandom.seed(UInt64(1000 + verifyCalls)) + let capture = GatedDeltaCapture( + convInput: MLXRandom.normal([1, Self.K - 1 + positions, Self.convDim]) + .asType(.bfloat16), + q: MLXRandom.normal([1, positions, Self.Hk, Self.Dk]).asType(.bfloat16), + k: MLXRandom.normal([1, positions, Self.Hk, Self.Dk]).asType(.bfloat16), + v: MLXRandom.normal([1, positions, Self.Hv, Self.Dv]).asType(.bfloat16), + a: MLXRandom.normal([1, positions, Self.Hv]).asType(.bfloat16), + b: MLXRandom.normal([1, positions, Self.Hv]).asType(.bfloat16), + aLog: MLXRandom.normal([Self.Hv]).asType(.float32), + dtBias: MLXRandom.normal([Self.Hv]).asType(.float32), + initialState: mamba[1]!) + return DFlash2VerifyResult( + logits: logits(for: request.tokens), + hidden: request.captureLayers.map { _ in + MLXArray.zeros([1, positions, Self.hidden]) + }, + recurrentCaptures: [capture]) + } +} + +/// Drafter that proposes from a script, or follows the target's transition +/// with a wrong token every `missEvery` positions. +private final class MockDrafter: Module, DFlash2DrafterModel { + var script: [[Int32]] = [] + var missEvery = 0 + private(set) var proposeCalls = 0 + private(set) var contextRows: [Int] = [] + private(set) var contextPositions: [Int] = [] + /// Committed context rows visible at each proposal, before its append. + private(set) var committedRows: [Int] = [] + private(set) var sawSuppressedTokens = false + var geometry = DFlash2Geometry( + layerCount: 4, hiddenSize: MockTarget.hidden, vocabularySize: MockTarget.vocab) + + init(script: [[Int32]] = [], missEvery: Int = 0) { + self.script = script + self.missEvery = missEvery + super.init() + } + + var blockSize: Int { 4 } + var maskTokenId: Int { MockTarget.vocab - 1 } + var targetLayerIds: [Int] { [1, 2] } + var targetGeometry: DFlash2Geometry { geometry } + var contextWindow: Int { 16 } + + func makeState() -> DFlash2DrafterState { + DFlash2DrafterState(contextCaches: [DFlash2ContextCache(window: contextWindow)]) + } + + func propose( + _ request: DFlash2ProposalRequest, target: any DFlash2TargetModel, + state: inout DFlash2DrafterState + ) -> DFlash2Proposal { + let (block, targetHidden, contextPosition) = ( + request.block, request.targetHidden, request.contextPosition + ) + sawSuppressedTokens = sawSuppressedTokens || request.suppressedTokens != nil + let round = proposeCalls + proposeCalls += 1 + contextRows.append(targetHidden.dim(1)) + contextPositions.append(contextPosition) + committedRows.append(state.contextCaches[0].rowValid.filter { $0 }.count) + let rows = targetHidden.dim(1) + let kv = MLXArray.zeros([1, 1, rows, 2]) + state.contextCaches[0].append( + keys: kv, values: kv, positions: (0 ..< rows).map { Int32(contextPosition + $0) }) + + let width = block.dim(1) - 1 + var tokens: [Int32] + if script.isEmpty { + // The anchor is lazy; sync it the way a real drafter never has to. + var token = Int(block[0, 0].item(Int32.self)) + tokens = [] + for i in 0 ..< width { + token = MockTarget.transition(token) + let miss = missEvery > 0 && (round * width + i) % missEvery == missEvery - 1 + tokens.append(Int32(miss ? (token + 5) % MockTarget.vocab : token)) + } + } else { + tokens = Array(script[min(round, script.count - 1)].prefix(width)) + } + let candidates: [Int32] = tokens.flatMap { [$0, 30, 31, 29] } + let probabilities: [Float] = tokens.flatMap { _ in [0.9, 0.05, 0.025, 0.025] } + return DFlash2Proposal( + tokens: MLXArray(tokens).expandedDimensions(axis: 0), + candidates: MLXArray(candidates, [1, width, 4]), + probabilities: MLXArray(probabilities, [1, width, 4])) + } +} + +// MARK: - Iterator + +@Test +func testDFlash2IteratorAcceptsPrefixAndTakesBonus() throws { + // Prefill runs in two chunks (2 + 1); the first token is script[2]. + let target = MockTarget() + target.script = [ + 1, 1, 10, + 20, 21, 55, 0, // round 1: accept 20, 21; 99 corrected to 55 + 30, 77, 0, 0, // round 2: accept 30; 31 corrected to 77 + 77, 77, 77, 77, // round 3: all accepted + ] + let drafter = MockDrafter(script: [[20, 21, 99], [30, 31, 32], [77, 77, 77]]) + var parameters = GenerateParameters(maxTokens: 20) + parameters.temperature = 0 + var iterator = try DFlash2SpeculativeTokenIterator( + input: LMInput(tokens: MLXArray([Int32(1), 2, 3])), mainModel: target, + drafter: drafter, parameters: parameters) + + var produced: [Int] = [] + while let token = iterator.next() { + produced.append(token) + } + #expect(produced.prefix(10) == [10, 20, 21, 55, 30, 77, 77, 77, 77, 77]) + #expect(produced.count == 20) + #expect(iterator.acceptedDraftTokens >= 6) + #expect(iterator.speculativeDecodingTelemetry?.emittedTokenCount == 20) + // Rounds narrow to what maxTokens leaves. + #expect(target.verifyWidths.allSatisfy { $0 <= 4 }) + #expect(drafter.contextRows.first == 3) + #expect(drafter.contextPositions.prefix(3) == [0, 3, 6]) + // The prompt rows are committed before round 1; each round then adds + // its anchor plus the accepted drafts. + #expect(drafter.committedRows.prefix(4) == [0, 3, 6, 8]) +} + +@Test +func testDFlash2IteratorMatchesTokenIteratorWithPenalties() throws { + // Greedy decoding with a repetition penalty: the target's argmax alone + // would cycle, so the processed history decides. Both iterators must emit + // the same stream, whatever the drafter proposes. + var parameters = GenerateParameters(maxTokens: 40, repetitionPenalty: 1.8) + parameters.temperature = 0 + parameters.repetitionContextSize = 6 + let prompt = LMInput(tokens: MLXArray([Int32(1), 2, 3, 4, 5])) + + var reference = try TokenIterator( + input: prompt, model: MockTarget(), parameters: parameters) + var expected: [Int] = [] + while let token = reference.next() { + expected.append(token) + } + #expect(expected.count == 40) + + for missEvery in [0, 2, 5] { + var iterator = try DFlash2SpeculativeTokenIterator( + input: prompt, mainModel: MockTarget(), drafter: MockDrafter(missEvery: missEvery), + parameters: parameters) + var produced: [Int] = [] + while let token = iterator.next() { + produced.append(token) + } + #expect(produced == expected, "missEvery \(missEvery)") + } +} + +@Test +func testDFlash2IteratorWarmStartMatchesColdStream() throws { + let target = MockTarget() + target.script = [1, 1, 10, 20, 21, 55, 0, 30, 77, 0, 0, 77, 77, 77, 77] + let drafter = MockDrafter(script: [[20, 21, 99], [30, 31, 32], [77, 77, 77]]) + let cache = target.newCache(parameters: nil) + _ = target(LMInput.Text(tokens: MLXArray([Int32(1), 2])), cache: cache, state: nil) + + var parameters = GenerateParameters(maxTokens: 8) + parameters.temperature = 0 + var iterator = try DFlash2SpeculativeTokenIterator( + input: LMInput(tokens: MLXArray([Int32(1), 2, 3])), mainModel: target, + drafter: drafter, mainCache: cache, prefilledPrefixTokens: 2, parameters: parameters) + + var produced: [Int] = [] + while let token = iterator.next() { + produced.append(token) + } + #expect(produced == [10, 20, 21, 55, 30, 77, 77, 77]) + // Only the suffix position is captured; the first context is one row. + #expect(drafter.contextRows.first == 1) + #expect(drafter.contextPositions.first == 2) +} + +@Test +func testDFlash2IteratorFinalizeRewindsUndrainedDrafts() throws { + let script: [Int32] = [1, 1, 10, 20, 21, 55, 0, 30, 77, 0, 0, 77, 77, 77, 77] + let drafts: [[Int32]] = [[20, 21, 99], [30, 31, 32], [77, 77, 77]] + var parameters = GenerateParameters(maxTokens: 20) + parameters.temperature = 0 + + func run(draining count: Int) throws -> (attention: Int, recurrent: Int) { + let target = MockTarget() + target.script = script + let cache = target.newCache(parameters: nil) + var iterator = try DFlash2SpeculativeTokenIterator( + input: LMInput(tokens: MLXArray([Int32(1), 2, 3])), mainModel: target, + drafter: MockDrafter(script: drafts), mainCache: cache, parameters: parameters) + for _ in 0 ..< count { _ = iterator.next() } + iterator.finalizeGeneration() + return (cache[0].offset, cache[1].offset) + } + + // 10 20 21 55 30 drained: 30 sits at position 7, nothing to rewind. + #expect(try run(draining: 5) == (8, 8)) + // 10 20 drained: 21 at position 5 was committed but never drained. + #expect(try run(draining: 2) == (5, 5)) + // 10 20 21 55 drained: the bonus has no cache entry yet. + #expect(try run(draining: 4) == (6, 6)) +} + +@Test +func testDFlash2IteratorRejectsUnsupportedInputs() throws { + let target = MockTarget() + let drafter = MockDrafter() + let parameters = GenerateParameters(maxTokens: 4) + #expect(throws: DFlash2SpeculationError.promptTooShort) { + _ = try DFlash2SpeculativeTokenIterator( + input: LMInput(tokens: MLXArray([Int32(1), 2])), mainModel: target, + drafter: drafter, prefilledPrefixTokens: 2, parameters: parameters) + } + let image = LMInput( + text: .init(tokens: MLXArray([Int32(1), 2])), + image: .init(pixels: MLXArray.zeros([1, 4, 4, 3]))) + #expect(throws: DFlash2SpeculationError.textOnly) { + _ = try DFlash2SpeculativeTokenIterator( + input: image, mainModel: target, drafter: drafter, parameters: parameters) + } + + let prompt = LMInput(tokens: MLXArray([Int32(1), 2])) + let narrow = MockDrafter() + narrow.geometry.hiddenSize = 32 + #expect( + throws: DFlash2SpeculationError.geometryMismatch( + drafter: narrow.geometry, target: target.dflash2Geometry) + ) { + _ = try DFlash2SpeculativeTokenIterator( + input: prompt, mainModel: target, drafter: narrow, parameters: parameters) + } + + var quantized = parameters + quantized.kvBits = 4 + var bounded = parameters + bounded.maxKVSize = 64 + for unsupported in [quantized, bounded] { + #expect(throws: DFlash2SpeculationError.unsupportedCache) { + _ = try DFlash2SpeculativeTokenIterator( + input: prompt, mainModel: target, drafter: drafter, parameters: unsupported) + } + } +} + +@Test +func testDFlash2IteratorNeverEmitsSuppressedTokens() throws { + // The prompt ends in 3, so the target's argmax runs 24, 43, 48, ... Suppressing + // 43 makes the processed argmax take the runner-up, as TokenIterator does. + let prompt = LMInput(tokens: MLXArray([Int32(1), 2, 3])) + var parameters = GenerateParameters(maxTokens: 12) + parameters.temperature = 0 + + let reference = MockTarget() + reference.suppressedTokenIds = [43] + var tokenIterator = try TokenIterator( + input: prompt, model: reference, parameters: parameters) + var expected: [Int] = [] + while let token = tokenIterator.next() { + expected.append(token) + } + + let target = MockTarget() + target.suppressedTokenIds = [43] + let drafter = MockDrafter() + var iterator = try DFlash2SpeculativeTokenIterator( + input: prompt, mainModel: target, drafter: drafter, parameters: parameters) + var produced: [Int] = [] + while let token = iterator.next() { + produced.append(token) + } + #expect(!produced.contains(43)) + #expect(produced.prefix(2) == [24, 44]) + #expect(produced == expected) + #expect(drafter.sawSuppressedTokens) +} + +private final class ProcessorLog: @unchecked Sendable { + var emitted: [Int] = [] + var finalized = 0 +} + +private struct RecordingProcessor: LogitProcessor { + let log: ProcessorLog + mutating func prompt(_ prompt: MLXArray) {} + func process(logits: MLXArray) -> MLXArray { logits } + mutating func didSample(token: MLXArray) {} + mutating func didEmit(token: Int) { log.emitted.append(token) } + mutating func finalizeGeneration() { log.finalized += 1 } +} + +@Test +func testDFlash2IteratorForwardsEmitAndFinalizeToTheProcessor() throws { + let log = ProcessorLog() + var parameters = GenerateParameters(maxTokens: 6) + parameters.temperature = 0 + var iterator = try DFlash2SpeculativeTokenIterator( + input: LMInput(tokens: MLXArray([Int32(1), 2, 3])), mainModel: MockTarget(), + drafter: MockDrafter(missEvery: 3), parameters: parameters, + components: GenerationComponents(logitProcessorFactory: { RecordingProcessor(log: log) })) + var produced: [Int] = [] + while let token = iterator.next() { + produced.append(token) + iterator.recordEmittedToken(token) + } + iterator.finalizeGeneration() + #expect(log.emitted == produced) + #expect(log.finalized == 1) +} + +private final class PrefillReports: @unchecked Sendable { + var prefix: [Int] = [] + var progress: [[Int]] = [] +} + +@Test +func testDFlash2IteratorReportsPrefixAndProgress() throws { + let reports = PrefillReports() + var parameters = GenerateParameters(maxTokens: 4) + parameters.temperature = 0 + parameters.prefill.stepSize = 2 + parameters.prefill.prefix = { reports.prefix.append($0) } + parameters.prefill.progress = { reports.progress.append([$0, $1]) } + + let target = MockTarget() + let cache = target.newCache(parameters: nil) + _ = target(LMInput.Text(tokens: MLXArray([Int32(1), 2])), cache: cache, state: nil) + _ = try DFlash2SpeculativeTokenIterator( + input: LMInput(tokens: MLXArray([Int32(1), 2, 3, 4, 5, 6, 7])), mainModel: target, + drafter: MockDrafter(), mainCache: cache, prefilledPrefixTokens: 2, + parameters: parameters) + #expect(reports.prefix == [2]) + // Five new positions: two balanced chunks of two, then the last one alone. + #expect(reports.progress == [[2, 5], [4, 5], [5, 5]]) +} + +final class DFlash2MemoryTests: XCTestCase { + + // As TokenIterator does since #620: a short generation must not leave its + // prefill buffers in the cache. + func testFirstTokenClearsBufferCache() throws { + var parameters = GenerateParameters(maxTokens: 4) + parameters.temperature = 0 + var iterator = try DFlash2SpeculativeTokenIterator( + input: LMInput(tokens: MLXArray([Int32(1), 2, 3])), mainModel: MockTarget(), + drafter: MockDrafter(), parameters: parameters) + + let seeded = 256 * 1024 * 1024 + do { + let buffer = MLXArray.zeros([seeded], dtype: .uint8) + 1 + eval(buffer) + Stream.defaultStream.synchronize() + } + Stream.defaultStream.synchronize() + XCTAssertGreaterThanOrEqual(Memory.cacheMemory, seeded) + + _ = iterator.next() + + XCTAssertLessThan(Memory.cacheMemory, seeded / 4) + } +} + +// MARK: - Recurrent replay + +@Test +func testGatedDeltaCaptureReplayMatchesPrefix() throws { + let (B, S, Hk, Dk, Hv, Dv, K) = (1, 6, 2, 32, 4, 16, 4) + let convDim = 2 * Hk * Dk + Hv * Dv + MLXRandom.seed(11) + let capture = GatedDeltaCapture( + convInput: MLXRandom.normal([B, K - 1 + S, convDim]).asType(.bfloat16), + q: MLXRandom.normal([B, S, Hk, Dk]).asType(.bfloat16), + k: MLXRandom.normal([B, S, Hk, Dk]).asType(.bfloat16), + v: MLXRandom.normal([B, S, Hv, Dv]).asType(.bfloat16), + a: MLXRandom.normal([B, S, Hv]).asType(.bfloat16), + b: MLXRandom.normal([B, S, Hv]).asType(.bfloat16), + aLog: MLXRandom.normal([Hv]).asType(.float32), + dtBias: MLXRandom.normal([Hv]).asType(.float32), + initialState: MLXRandom.normal([B, Hv, Dv, Dk]).asType(.float32)) + + for validCount in [1, 4, S] { + // Lazy count, as the iterator passes it. + let count = MLXArray(Int32(validCount - 1)) + Int32(1) + let (recurrent, conv) = capture.replay(validCount: count) + let (_, expected) = gatedDeltaUpdate( + q: capture.q[0..., ..= 2) + } +} + +// MARK: - Compiled drafter + +@Test +func testDFlash2CompiledProposalMatchesEager() throws { + let config = tinyConfig(window: 24, vocab: MockTarget.vocab) + MLXRandom.seed(11) + let compiled = DFlash2DraftModel(config) + let eager = DFlash2DraftModel(config) + eager.compiledTracesEnabled = false + try eager.update(parameters: compiled.parameters(), verify: []) + let target = MockTarget() + + var stateA = compiled.makeState() + var stateB = eager.makeState() + let concatDim = config.dflash.targetLayerIds.count * config.hiddenSize + // A 20-row first context takes the eager projection; later rounds trace. + let rounds: [(rows: Int, valid: Int, width: Int)] = [ + (20, 20, 5), (3, 2, 5), (1, 1, 3), (5, 4, 5), + ] + var position = 0 + var anchor: Int32 = 7 + for (round, spec) in rounds.enumerated() { + let targetHidden = MLXRandom.normal([1, spec.rows, concatDim]) + let block = MLXArray( + [anchor] + Array(repeating: Int32(config.dflash.maskTokenId), count: spec.width - 1) + ).expandedDimensions(axis: 0) + let validRows = MLXArray(Int32(spec.valid)) + let request = DFlash2ProposalRequest( + block: block, targetHidden: targetHidden, contextPosition: position, + validRows: validRows, temperature: 0) + let a = compiled.propose(request, target: target, state: &stateA) + let b = eager.propose(request, target: target, state: &stateB) + eval(a.tokens, b.tokens, a.candidates, b.candidates) + #expect(a.tokens.asArray(Int32.self) == b.tokens.asArray(Int32.self), "round \(round)") + #expect( + a.candidates.asArray(Int32.self) == b.candidates.asArray(Int32.self), + "round \(round)") + for state in [stateA, stateB] { + state.contextCaches[0].resolve(newest: spec.rows, valid: spec.valid) + } + position += spec.valid + anchor = a.tokens[0, 0].item(Int32.self) + } + #expect(compiled.compiledTraceCount >= 6) + #expect(eager.compiledTraceCount == 0) + + // Replacing modules (an adapter, a quantize after load) drops every trace. + compiled.invalidateCompiledTraces() + #expect(compiled.compiledTraceCount == 0) +} + +@Test +func testDFlash2DrafterSkipsSuppressedTokens() throws { + let config = tinyConfig(window: 24, vocab: MockTarget.vocab) + MLXRandom.seed(5) + let drafter = DFlash2DraftModel(config) + let allowed = Set(40 ..< 60) + let request = DFlash2ProposalRequest( + block: MLXArray( + [Int32(7)] + Array(repeating: Int32(config.dflash.maskTokenId), count: 4) + ).expandedDimensions(axis: 0), + targetHidden: MLXRandom.normal([1, 6, config.dflash.targetLayerIds.count * 64]), + contextPosition: 0, validRows: MLXArray(Int32(6)), temperature: 0, + suppressedTokens: SuppressTokensProcessor( + tokenIds: Set(0 ..< MockTarget.vocab).subtracting(allowed))) + var state = drafter.makeState() + let proposal = drafter.propose(request, target: MockTarget(), state: &state) + #expect(Set(proposal.candidates.asArray(Int32.self).map(Int.init)).isSubset(of: allowed)) + #expect(Set(proposal.tokens.asArray(Int32.self).map(Int.init)).isSubset(of: allowed)) +} + +// MARK: - Qwen 3.5 verify pass + +/// A tiny Qwen 3.8 text target with an explicit, non-periodic layer schedule, +/// quantized so the fused gated-delta input projection is in use. +private func tinyQwen38Target() throws -> Qwen35TextModel { + let json = """ + { + "model_type": "qwen3_8_text", + "hidden_size": 64, + "num_hidden_layers": 5, + "layer_types": ["linear_attention", "full_attention", "linear_attention", + "linear_attention", "full_attention"], + "intermediate_size": 64, + "num_attention_heads": 2, + "num_key_value_heads": 1, + "head_dim": 32, + "linear_num_value_heads": 4, + "linear_num_key_heads": 2, + "linear_key_head_dim": 32, + "linear_value_head_dim": 32, + "linear_conv_kernel_dim": 4, + "vocab_size": 64, + "num_experts": 0, + "num_experts_per_tok": 0 + } + """ + let configuration = try JSONDecoder().decode( + Qwen35TextConfiguration.self, from: Data(json.utf8)) + MLXRandom.seed(3) + let model = Qwen35TextModel(configuration) + quantize(model: model, groupSize: 32, bits: 4) + try model.prepare() + eval(model) + return model +} + +private func maxDifference(_ a: MLXArray, _ b: MLXArray) -> Float { + (a.asType(.float32) - b.asType(.float32)).abs().max().item(Float.self) +} + +@Test +func testQwen35VerifyMatchesOneForwardAndCommitsAnyPrefix() throws { + let model = try tinyQwen38Target() + #expect(model.model.layers.map(\.isLinear) == [true, false, true, true, false]) + #expect(model.model.layers[0].linearAttn!.hasFusedInputProjection) + let prompt: [Int32] = [3, 9, 14, 1, 27, 8] + let block: [Int32] = [5, 11, 2, 40, 17] + let captureLayers = [1, 3] + let tolerance = MatmulPrecision.splitTolerance + + // Reference: one forward over the prompt and the block. + let reference = model.dflash2Prefill( + MLXArray(prompt + block).expandedDimensions(axis: 0), + cache: try model.newCache(parameters: nil), captureLayers: captureLayers) + + for validCount in [1, 3, block.count] { + let cache = try model.newCache(parameters: nil) + _ = model.dflash2Prefill( + MLXArray(prompt).expandedDimensions(axis: 0), cache: cache, + captureLayers: captureLayers) + let result = model.dflash2Verify( + DFlash2VerifyRequest( + tokens: MLXArray(block).expandedDimensions(axis: 0), + position: MLXArray([Int32(prompt.count)]), positionUpperBound: prompt.count, + captureLayers: captureLayers), + cache: cache) + let blockRows = prompt.count... + #expect(maxDifference(result.logits, reference.logits[0..., blockRows]) < tolerance) + for (verified, expected) in zip(result.hidden, reference.hidden) { + #expect(maxDifference(verified, expected[0..., blockRows]) < tolerance) + } + + // Commit `validCount` positions as the iterator does, then decode the next + // block token: it must see exactly the prompt plus the accepted prefix. + let committed = prompt.count + validCount + let recurrent = cache.compactMap { $0 as? MambaCache } + for (entry, capture) in zip(recurrent, result.recurrentCaptures) { + let replayed = capture.replay(validCount: MLXArray(Int32(validCount))) + entry[0] = replayed.conv + entry[1] = replayed.recurrent + entry.offset = committed + } + for case let attention as KVCacheSimple in cache { + attention.commitRows(count: committed) + } + guard validCount < block.count else { continue } + let next = model( + LMInput.Text(tokens: MLXArray([block[validCount]]).expandedDimensions(axis: 0)), + cache: cache, state: nil + ).logits + #expect( + maxDifference(next[0, 0], reference.logits[0, committed]) < tolerance, + "validCount \(validCount)") + } + +} + +@Test +func testQwen35VerifySeesReplacedProjectionsAfterInvalidation() throws { + // Replacing modules, as an adapter fuse or a re-fusion does, needs + // `invalidateCompiledTraces()`; the verify traces must be among those it drops. + let model = try tinyQwen38Target() + let prompt: [Int32] = [3, 9, 14, 1] + let block: [Int32] = [5, 11, 2] + func verifyLogits() throws -> MLXArray { + let cache = try model.newCache(parameters: nil) + _ = model.dflash2Prefill( + MLXArray(prompt).expandedDimensions(axis: 0), cache: cache, captureLayers: [1]) + return model.dflash2Verify( + DFlash2VerifyRequest( + tokens: MLXArray(block).expandedDimensions(axis: 0), + position: MLXArray([Int32(prompt.count)]), positionUpperBound: prompt.count, + captureLayers: [1]), + cache: cache + ).logits + } + let before = try verifyLogits() + eval(before) + + // Change the input projections, as an adapter fuse would, then fuse again. + for layer in model.model.layers.compactMap(\.linearAttn) { + let projection = layer.inProjQKV as! QuantizedLinear + try layer.update( + parameters: ModuleParameters.unflattened([ + "in_proj_qkv.scales": projection.scales * 1.5 + ]), + verify: []) + } + try model.prepare() + model.invalidateCompiledTraces() + #expect(model.model.layers[0].linearAttn!.hasFusedInputProjection) + + let after = try verifyLogits() + let expected = model.dflash2Prefill( + MLXArray(prompt + block).expandedDimensions(axis: 0), + cache: try model.newCache(parameters: nil), captureLayers: [1] + ).logits[0..., prompt.count...] + #expect(maxDifference(after, before) > 0.01) + #expect(maxDifference(after, expected) < MatmulPrecision.splitTolerance) +} From b119cfe69a9d041d679fe9ab7b0f528b64fca98f Mon Sep 17 00:00:00 2001 From: Ronald Mannak Date: Sun, 25 Oct 2026 22:05:17 -0700 Subject: [PATCH 2/5] Continue DFlash2 generation after a cache the input does not repeat The generate(dflash2Drafter:) overloads pass a caller's cache with prefilledPrefixTokens left at zero, which is how a chat turn arrives: the cache holds the conversation so far and `input` is only the new tokens. Prefill appended the new tokens after the cached positions, but the first verify pass then started at `input`'s length instead of the cache's absolute position, so it wrote attention rows over cached ones, applied RoPE at the wrong positions, and told the drafter its context rows sat at position zero. Derive the absolute positions from the cache's offset before prefill: `origin` is where `input`'s first token sits, the anchor and the drafter's context position follow from it, and the reused prefix reported through `prefill.prefix` is the cache's position count, as TokenIterator reports it. A cold cache and the explicit `prefilledPrefixTokens` warm start are unchanged. Found by the Codex review of PicoMLX/mlx-swift-lm#70. Co-Authored-By: Claude Fable 5.1 --- .../DFlash2SpeculativeTokenIterator.swift | 28 +++++++++------ Tests/MLXLMTests/DFlash2Tests.swift | 35 +++++++++++++++++++ 2 files changed, 52 insertions(+), 11 deletions(-) diff --git a/Libraries/MLXLMCommon/DFlash2SpeculativeTokenIterator.swift b/Libraries/MLXLMCommon/DFlash2SpeculativeTokenIterator.swift index 7861474cd2..dab167dedb 100644 --- a/Libraries/MLXLMCommon/DFlash2SpeculativeTokenIterator.swift +++ b/Libraries/MLXLMCommon/DFlash2SpeculativeTokenIterator.swift @@ -88,7 +88,8 @@ public struct DFlash2SpeculativeTokenIterator: TokenIteratorProtocol { /// - input: the prompt, text only. /// - mainModel: the target; must conform to ``DFlash2TargetModel``. /// - drafter: a DFlash2 drafter distilled for `mainModel`'s shape. - /// - mainCache: a target cache to decode over. + /// - mainCache: a target cache to decode over. `input` continues after + /// the positions it already holds. /// - prefilledPrefixTokens: leading positions of `input` that `mainCache` /// already holds; only the rest is prefilled. /// - parameters: sampling and generation limits. @@ -163,22 +164,27 @@ public struct DFlash2SpeculativeTokenIterator: TokenIteratorProtocol { input: LMInput, prefilledPrefixTokens: Int, prefill: PrefillParameters ) throws { processor?.prompt(input.text.tokens) - prefill.prefix?(prefilledPrefixTokens) let promptTokens = input.text.tokens let promptLength = promptTokens.dim(0) - if prefilledPrefixTokens > 0, - let attention = cache.first(where: { type(of: $0) == KVCacheSimple.self }) - { + // The cache may hold positions `input` does not repeat, as when `input` + // is the uncached tail of a conversation. Positions below are absolute; + // `origin` is where `input`'s first token sits. + let cached = + (cache.first(where: { type(of: $0) == KVCacheSimple.self }) ?? cache.first)?.offset + ?? 0 + if prefilledPrefixTokens > 0 { precondition( - attention.offset == prefilledPrefixTokens, - "cache holds \(attention.offset) positions, prefilledPrefixTokens is \(prefilledPrefixTokens)" + cached == prefilledPrefixTokens, + "cache holds \(cached) positions, prefilledPrefixTokens is \(prefilledPrefixTokens)" ) } + let origin = cached - prefilledPrefixTokens + prefill.prefix?(cached) let window = drafter.contextWindow let captureLayers = drafter.targetLayerIds var hiddenWindow: MLXArray? = nil - var hiddenOffset = prefilledPrefixTokens + var hiddenOffset = cached func forward(_ range: Range) -> MLXArray { let chunk = promptTokens[range].expandedDimensions(axis: 0) let result = target.dflash2Prefill(chunk, cache: cache, captureLayers: captureLayers) @@ -210,7 +216,7 @@ public struct DFlash2SpeculativeTokenIterator: TokenIteratorProtocol { eval(token) pendingTokens.append(token.item(Int.self)) producedTokens = 1 - anchorPosition = promptLength + anchorPosition = origin + promptLength // The prompt rows are committed context as soon as round 0 appends them. let context = hiddenWindow! @@ -219,8 +225,8 @@ public struct DFlash2SpeculativeTokenIterator: TokenIteratorProtocol { validRows: MLXArray(Int32(context.dim(1))), targetHidden: context, contextPosition: hiddenOffset, - position: MLXArray([Int32(promptLength)]), - positionUpperBound: promptLength, + position: MLXArray([Int32(anchorPosition)]), + positionUpperBound: anchorPosition, producedAtLeast: 1) for contextCache in drafterState.contextCaches { contextCache.resolve(newest: contextRows, valid: contextRows) diff --git a/Tests/MLXLMTests/DFlash2Tests.swift b/Tests/MLXLMTests/DFlash2Tests.swift index 2ff5b676c6..da501837d4 100644 --- a/Tests/MLXLMTests/DFlash2Tests.swift +++ b/Tests/MLXLMTests/DFlash2Tests.swift @@ -673,6 +673,41 @@ func testDFlash2IteratorWarmStartMatchesColdStream() throws { #expect(drafter.contextPositions.first == 2) } +@Test +func testDFlash2IteratorContinuesAfterCachedPrefix() throws { + // The cache holds [1, 2] and `input` is the uncached tail [3], as a chat + // turn passes it. Every position is absolute: the context rows, the verify + // rows and the committed offsets all follow the cached positions. + let reports = PrefillReports() + let target = MockTarget() + target.script = [1, 1, 10, 20, 21, 55, 0, 30, 77, 0, 0, 77, 77, 77, 77] + let drafter = MockDrafter(script: [[20, 21, 99], [30, 31, 32], [77, 77, 77]]) + let cache = target.newCache(parameters: nil) + _ = target(LMInput.Text(tokens: MLXArray([Int32(1), 2])), cache: cache, state: nil) + + var parameters = GenerateParameters(maxTokens: 8) + parameters.temperature = 0 + parameters.prefill.prefix = { reports.prefix.append($0) } + var iterator = try DFlash2SpeculativeTokenIterator( + input: LMInput(tokens: MLXArray([Int32(3)])), mainModel: target, + drafter: drafter, mainCache: cache, parameters: parameters) + + var produced: [Int] = [] + for _ in 0 ..< 5 { + let token = iterator.next() + produced.append(try #require(token)) + } + iterator.finalizeGeneration() + #expect(produced == [10, 20, 21, 55, 30]) + #expect(reports.prefix == [2]) + #expect(drafter.contextRows.first == 1) + // The first context row is position 2; the anchors sit at 3 and 6. + #expect(drafter.contextPositions.prefix(3) == [2, 3, 6]) + // 30 sits at position 7, so the cache holds 8 positions and nothing rewinds. + #expect(cache[0].offset == 8) + #expect(cache[1].offset == 8) +} + @Test func testDFlash2IteratorFinalizeRewindsUndrainedDrafts() throws { let script: [Int32] = [1, 1, 10, 20, 21, 55, 0, 30, 77, 0, 0, 77, 77, 77, 77] From 3ae9aeeb77789d0f89553b5c4424fcd3232546d5 Mon Sep 17 00:00:00 2001 From: Ronald Mannak Date: Sun, 25 Oct 2026 22:05:18 -0700 Subject: [PATCH 3/5] Draw DFlash2 draft samples from the seeded random state With `temperature > 0` and `GenerateParameters.seed` set, the first token and the rejection sampling drew from the iterator's seeded state, but `drafter.propose` ran outside it, so the selector's `categorical` consumed the global random state. Different proposals change which drafts are accepted, so two runs with the same seed could emit different tokens. Run the proposal under `withRandomState(randomState)` as the acceptance already does. The mock target in the tests now builds its captures from a private random state instead of reseeding the global one. Found by the Codex review of PicoMLX/mlx-swift-lm#70. Co-Authored-By: Claude Fable 5.1 --- .../DFlash2SpeculativeTokenIterator.swift | 14 ++-- Tests/MLXLMTests/DFlash2Tests.swift | 71 +++++++++++++++---- 2 files changed, 67 insertions(+), 18 deletions(-) diff --git a/Libraries/MLXLMCommon/DFlash2SpeculativeTokenIterator.swift b/Libraries/MLXLMCommon/DFlash2SpeculativeTokenIterator.swift index dab167dedb..28f5445824 100644 --- a/Libraries/MLXLMCommon/DFlash2SpeculativeTokenIterator.swift +++ b/Libraries/MLXLMCommon/DFlash2SpeculativeTokenIterator.swift @@ -261,11 +261,15 @@ public struct DFlash2SpeculativeTokenIterator: TokenIteratorProtocol { } let masks = MLXArray(Array(repeating: Int32(drafter.maskTokenId), count: drafts)) let block = concatenated([anchor.asType(.int32), masks]).expandedDimensions(axis: 0) - let proposal = drafter.propose( - DFlash2ProposalRequest( - block: block, targetHidden: targetHidden, contextPosition: contextPosition, - validRows: validRows, temperature: temperature, suppressedTokens: draftSuppressor), - target: target, state: &drafterState) + // Sampled drafts draw from the seeded state too, so a seed reproduces the stream. + let proposal = withRandomState(randomState) { + drafter.propose( + DFlash2ProposalRequest( + block: block, targetHidden: targetHidden, contextPosition: contextPosition, + validRows: validRows, temperature: temperature, + suppressedTokens: draftSuppressor), + target: target, state: &drafterState) + } let draftTokens = proposal.tokens.flattened().asType(.int32) let request = DFlash2VerifyRequest( tokens: concatenated([anchor.asType(.int32), draftTokens]).expandedDimensions(axis: 0), diff --git a/Tests/MLXLMTests/DFlash2Tests.swift b/Tests/MLXLMTests/DFlash2Tests.swift index da501837d4..c1f55ffd07 100644 --- a/Tests/MLXLMTests/DFlash2Tests.swift +++ b/Tests/MLXLMTests/DFlash2Tests.swift @@ -491,18 +491,21 @@ private final class MockTarget: Module, LanguageModel, KVCacheDimensionProvider, keys: kv, values: kv, position: request.position, visibleLength: request.positionUpperBound + positions) let mamba = cache[1] as! MambaCache - MLXRandom.seed(UInt64(1000 + verifyCalls)) - let capture = GatedDeltaCapture( - convInput: MLXRandom.normal([1, Self.K - 1 + positions, Self.convDim]) - .asType(.bfloat16), - q: MLXRandom.normal([1, positions, Self.Hk, Self.Dk]).asType(.bfloat16), - k: MLXRandom.normal([1, positions, Self.Hk, Self.Dk]).asType(.bfloat16), - v: MLXRandom.normal([1, positions, Self.Hv, Self.Dv]).asType(.bfloat16), - a: MLXRandom.normal([1, positions, Self.Hv]).asType(.bfloat16), - b: MLXRandom.normal([1, positions, Self.Hv]).asType(.bfloat16), - aLog: MLXRandom.normal([Self.Hv]).asType(.float32), - dtBias: MLXRandom.normal([Self.Hv]).asType(.float32), - initialState: mamba[1]!) + // Deterministic captures from a private state, so the mock never + // touches the global random state a test may be watching. + let capture = withRandomState(MLXRandom.RandomState(seed: UInt64(1000 + verifyCalls))) { + GatedDeltaCapture( + convInput: MLXRandom.normal([1, Self.K - 1 + positions, Self.convDim]) + .asType(.bfloat16), + q: MLXRandom.normal([1, positions, Self.Hk, Self.Dk]).asType(.bfloat16), + k: MLXRandom.normal([1, positions, Self.Hk, Self.Dk]).asType(.bfloat16), + v: MLXRandom.normal([1, positions, Self.Hv, Self.Dv]).asType(.bfloat16), + a: MLXRandom.normal([1, positions, Self.Hv]).asType(.bfloat16), + b: MLXRandom.normal([1, positions, Self.Hv]).asType(.bfloat16), + aLog: MLXRandom.normal([Self.Hv]).asType(.float32), + dtBias: MLXRandom.normal([Self.Hv]).asType(.float32), + initialState: mamba[1]!) + } return DFlash2VerifyResult( logits: logits(for: request.tokens), hidden: request.captureLayers.map { _ in @@ -523,6 +526,10 @@ private final class MockDrafter: Module, DFlash2DrafterModel { /// Committed context rows visible at each proposal, before its append. private(set) var committedRows: [Int] = [] private(set) var sawSuppressedTokens = false + /// Above temperature 0, draw each draft from a flat candidate row with + /// `categorical`, as the real selector does, and record the draws. + var samplesDrafts = false + private(set) var sampledDrafts: [[Int32]] = [] var geometry = DFlash2Geometry( layerCount: 4, hiddenSize: MockTarget.hidden, vocabularySize: MockTarget.vocab) @@ -576,9 +583,18 @@ private final class MockDrafter: Module, DFlash2DrafterModel { } let candidates: [Int32] = tokens.flatMap { [$0, 30, 31, 29] } let probabilities: [Float] = tokens.flatMap { _ in [0.9, 0.05, 0.025, 0.025] } + let candidateRows = MLXArray(candidates, [1, width, 4]) + if samplesDrafts, request.temperature > 0 { + let flat = MLXArray([Float](repeating: 0.25, count: width * 4), [1, width, 4]) + let chosen = categorical(log(flat)) + let drafts = takeAlong(candidateRows, chosen[.ellipsis, .newAxis], axis: -1)[ + .ellipsis, 0] + sampledDrafts.append(drafts.flattened().asArray(Int32.self)) + return DFlash2Proposal(tokens: drafts, candidates: candidateRows, probabilities: flat) + } return DFlash2Proposal( tokens: MLXArray(tokens).expandedDimensions(axis: 0), - candidates: MLXArray(candidates, [1, width, 4]), + candidates: candidateRows, probabilities: MLXArray(probabilities, [1, width, 4])) } } @@ -708,6 +724,35 @@ func testDFlash2IteratorContinuesAfterCachedPrefix() throws { #expect(cache[1].offset == 8) } +@Test +func testDFlash2SeededSamplingIgnoresGlobalRandomState() throws { + // With a seed, the drafts are drawn from the iterator's random state as + // the bonus tokens are, so neither they nor the stream depend on the + // global one. + func run(globalSeed: UInt64) throws -> (tokens: [Int], drafts: [[Int32]]) { + MLXRandom.seed(globalSeed) + var parameters = GenerateParameters(maxTokens: 24) + parameters.temperature = 0.9 + parameters.seed = 5 + let drafter = MockDrafter() + drafter.samplesDrafts = true + var iterator = try DFlash2SpeculativeTokenIterator( + input: LMInput(tokens: MLXArray([Int32(1), 2, 3])), mainModel: MockTarget(), + drafter: drafter, parameters: parameters) + var produced: [Int] = [] + while let token = iterator.next() { + produced.append(token) + } + return (produced, drafter.sampledDrafts) + } + let first = try run(globalSeed: 1) + let second = try run(globalSeed: 2) + #expect(first.tokens.count == 24) + #expect(first.drafts.count >= 6) + #expect(second.drafts == first.drafts) + #expect(second.tokens == first.tokens) +} + @Test func testDFlash2IteratorFinalizeRewindsUndrainedDrafts() throws { let script: [Int32] = [1, 1, 10, 20, 21, 55, 0, 30, 77, 0, 0, 77, 77, 77, 77] From 2034ffce826b3c8b06130681c6a68cbddb49b4d1 Mon Sep 17 00:00:00 2001 From: Ronald Mannak Date: Sun, 25 Oct 2026 22:18:55 -0700 Subject: [PATCH 4/5] Sample the first DFlash2 token from the iterator's random state With `temperature > 0` and a seed, `parameters.sampler()` and the iterator each built a random state from the same seed, so both started on the same key: the sampler spent it on the first token and the iterator spent it again on the first drafts, which correlated the drafts with the anchor and broke the independence rejection sampling assumes. Upstream 607 had the same overlap between the first token and the first acceptance draw. Sampled rounds now draw the first token from the iterator's own state, through the same filtered distribution `speculativeSamplingProbabilities` builds for acceptance, so one advancing stream serves the first token, the drafts and the acceptance and no key is drawn twice. Greedy rounds still use the argmax sampler. The mock drafter's first sampled draft now has the shape of the target's first-token sample, and the mock target can emit flat logits, so the test can show that a shared key would repeat the first token as the first draft. Found by the Codex review of PicoMLX/mlx-swift-lm#70. Co-Authored-By: Claude Fable 5.1 --- .../DFlash2SpeculativeTokenIterator.swift | 13 ++++- Tests/MLXLMTests/DFlash2Tests.swift | 52 ++++++++++++++++--- 2 files changed, 58 insertions(+), 7 deletions(-) diff --git a/Libraries/MLXLMCommon/DFlash2SpeculativeTokenIterator.swift b/Libraries/MLXLMCommon/DFlash2SpeculativeTokenIterator.swift index 28f5445824..052d01a834 100644 --- a/Libraries/MLXLMCommon/DFlash2SpeculativeTokenIterator.swift +++ b/Libraries/MLXLMCommon/DFlash2SpeculativeTokenIterator.swift @@ -45,6 +45,7 @@ public struct DFlash2SpeculativeTokenIterator: TokenIteratorProtocol { let topP: Float let topK: Int let minP: Float + /// One stream for the first token, the drafts and the acceptance, so no key is drawn twice. let randomState: MLXRandom.RandomState public let maxTokens: Int? @@ -211,7 +212,7 @@ public struct DFlash2SpeculativeTokenIterator: TokenIteratorProtocol { var last = logits[0..., -1, 0...] last = processor?.process(logits: last) ?? last - let token = sampler.sample(logits: last) + let token = sampleFirstToken(last) processor?.didSample(token: token) eval(token) pendingTokens.append(token.item(Int.self)) @@ -233,6 +234,16 @@ public struct DFlash2SpeculativeTokenIterator: TokenIteratorProtocol { } } + /// The first token. Sampled rounds draw it from `randomState`, the stream + /// the drafts and the acceptance use: a sampler seeded alike would reuse + /// its first key for the drafts and correlate them with the anchor. + private func sampleFirstToken(_ logits: MLXArray) -> MLXArray { + guard !greedy else { return sampler.sample(logits: logits) } + let probabilities = speculativeSamplingProbabilities( + logits, temperature: temperature, topP: topP, minP: minP, topK: topK) + return withRandomState(randomState) { categorical(log(probabilities)) } + } + private func concatenatedHidden(_ layers: [MLXArray]) -> MLXArray { layers.count == 1 ? layers[0] : concatenated(layers, axis: -1) } diff --git a/Tests/MLXLMTests/DFlash2Tests.swift b/Tests/MLXLMTests/DFlash2Tests.swift index c1f55ffd07..e4d42a6edc 100644 --- a/Tests/MLXLMTests/DFlash2Tests.swift +++ b/Tests/MLXLMTests/DFlash2Tests.swift @@ -395,6 +395,8 @@ private final class MockTarget: Module, LanguageModel, KVCacheDimensionProvider, /// Per-position token script for the verify rows; nil uses `transition`. var script: [Int32]? private var scriptIndex = 0 + /// Flat logits at every position, for sampling tests. + var flatLogits = false override init() { super.init() @@ -404,6 +406,9 @@ private final class MockTarget: Module, LanguageModel, KVCacheDimensionProvider, private func logits(for tokens: MLXArray) -> MLXArray { let ids = tokens.flattened().asArray(Int32.self).map(Int.init) + if flatLogits { + return MLXArray.zeros([1, ids.count, Self.vocab]) + } var data = [Float](repeating: 0, count: ids.count * Self.vocab) for (i, token) in ids.enumerated() { let best: Int @@ -526,8 +531,9 @@ private final class MockDrafter: Module, DFlash2DrafterModel { /// Committed context rows visible at each proposal, before its append. private(set) var committedRows: [Int] = [] private(set) var sawSuppressedTokens = false - /// Above temperature 0, draw each draft from a flat candidate row with - /// `categorical`, as the real selector does, and record the draws. + /// Above temperature 0, draw the first draft over the whole vocabulary and + /// the rest from flat candidate rows with `categorical`, as the real + /// selector does, and record the draws. var samplesDrafts = false private(set) var sampledDrafts: [[Int32]] = [] var geometry = DFlash2Geometry( @@ -585,12 +591,21 @@ private final class MockDrafter: Module, DFlash2DrafterModel { let probabilities: [Float] = tokens.flatMap { _ in [0.9, 0.05, 0.025, 0.025] } let candidateRows = MLXArray(candidates, [1, width, 4]) if samplesDrafts, request.temperature > 0 { + // The first draw has the shape of the target's first-token sample. + let vocabulary = MLXArray.ones([1, MockTarget.vocab]) / Float(MockTarget.vocab) + let first = categorical(log(vocabulary)).asType(.int32) let flat = MLXArray([Float](repeating: 0.25, count: width * 4), [1, width, 4]) let chosen = categorical(log(flat)) - let drafts = takeAlong(candidateRows, chosen[.ellipsis, .newAxis], axis: -1)[ - .ellipsis, 0] - sampledDrafts.append(drafts.flattened().asArray(Int32.self)) - return DFlash2Proposal(tokens: drafts, candidates: candidateRows, probabilities: flat) + var drafts = takeAlong(candidateRows, chosen[.ellipsis, .newAxis], axis: -1)[ + .ellipsis, 0 + ].flattened().asArray(Int32.self) + drafts[0] = first.item(Int32.self) + var sampledCandidates = candidates + sampledCandidates[0] = drafts[0] + sampledDrafts.append(drafts) + return DFlash2Proposal( + tokens: MLXArray(drafts, [1, width]), + candidates: MLXArray(sampledCandidates, [1, width, 4]), probabilities: flat) } return DFlash2Proposal( tokens: MLXArray(tokens).expandedDimensions(axis: 0), @@ -753,6 +768,31 @@ func testDFlash2SeededSamplingIgnoresGlobalRandomState() throws { #expect(second.tokens == first.tokens) } +@Test +func testDFlash2FirstTokenAndDraftsDrawDifferentKeys() throws { + // One random state serves the first token and the drafts. Were both drawn + // from the same key, a flat target and a flat drafter would make the first + // draft repeat the first token for every seed. + var repeats = 0 + for seed in UInt64(1) ... 8 { + let target = MockTarget() + target.flatLogits = true + let drafter = MockDrafter() + drafter.samplesDrafts = true + var parameters = GenerateParameters(maxTokens: 4) + parameters.temperature = 1 + parameters.seed = seed + var iterator = try DFlash2SpeculativeTokenIterator( + input: LMInput(tokens: MLXArray([Int32(1), 2, 3])), mainModel: target, + drafter: drafter, parameters: parameters) + let first = iterator.next() + if drafter.sampledDrafts.first?.first == Int32(try #require(first)) { + repeats += 1 + } + } + #expect(repeats < 4) +} + @Test func testDFlash2IteratorFinalizeRewindsUndrainedDrafts() throws { let script: [Int32] = [1, 1, 10, 20, 21, 55, 0, 30, 77, 0, 0, 77, 77, 77, 77] From 6494db9b8d497f4fd9dcb79671dc8cfab8ba6993 Mon Sep 17 00:00:00 2001 From: Ronald Mannak Date: Fri, 6 Nov 2026 17:12:32 -0800 Subject: [PATCH 5/5] Route reasoning in the DFlash2 generate overload Main's reasoning streaming (#563) passes the model's reasoning configuration to the text handler in the plain and MTP generate overloads, so thinking text arrives as `.reasoning` events. The DFlash2 overload from PR 607 predates it and passed none, so a Qwen 3.5 or 3.8 target's thinking arrived as ordinary `.chunk` output, delimiters included. Read whether the prompt already opens a thought before the iterator queues its prefill, and pass the configuration and that seed to the handler, as the MTP overload does. The new test streams a prompt that ends in a prefilled `` and expects the thought as reasoning and the rest as the answer. Found by the Codex review of PicoMLX/mlx-swift-lm#70. Co-Authored-By: Claude Opus 5.5 --- Libraries/MLXLMCommon/Evaluate.swift | 8 ++++- Tests/MLXLMTests/DFlash2Tests.swift | 52 ++++++++++++++++++++++++++++ 2 files changed, 59 insertions(+), 1 deletion(-) diff --git a/Libraries/MLXLMCommon/Evaluate.swift b/Libraries/MLXLMCommon/Evaluate.swift index ce42389322..60d6abd3e5 100644 --- a/Libraries/MLXLMCommon/Evaluate.swift +++ b/Libraries/MLXLMCommon/Evaluate.swift @@ -2666,6 +2666,9 @@ public func generate( wiredMemoryTicket: WiredMemoryTicket? = nil, tools: [[String: any Sendable]]? = nil ) throws -> AsyncStream { + // Read the prompt before the iterator queues its prefill, which this would wait for. + let reasoningPrimedInside = promptPrimesReasoning( + input: input, modelConfiguration: context.configuration, tokenizer: context.tokenizer) let iterator = try DFlash2SpeculativeTokenIterator( input: input, mainModel: context.model, @@ -2686,7 +2689,10 @@ public func generate( stopStrings: context.configuration.effectiveStopStrings, format: context.configuration.toolCallFormat ?? .json, tools: tools, - toolCallPolicy: parameters.toolCallPolicy + toolCallPolicy: parameters.toolCallPolicy, + reasoning: context.configuration.reasoningConfig.map { + (config: $0, primedInside: reasoningPrimedInside) + } ) ) return stream diff --git a/Tests/MLXLMTests/DFlash2Tests.swift b/Tests/MLXLMTests/DFlash2Tests.swift index e4d42a6edc..8136fc641a 100644 --- a/Tests/MLXLMTests/DFlash2Tests.swift +++ b/Tests/MLXLMTests/DFlash2Tests.swift @@ -793,6 +793,58 @@ func testDFlash2FirstTokenAndDraftsDrawDifferentKeys() throws { #expect(repeats < 4) } +/// Decodes each token id to a fixed fragment; unknown ids decode to nothing. +private struct FragmentTokenizer: MLXLMCommon.Tokenizer { + let decoding: [Int: String] + func encode(text: String, addSpecialTokens: Bool) -> [Int] { [] } + func decode(tokenIds: [Int], skipSpecialTokens: Bool) -> String { + tokenIds.map { decoding[$0] ?? "" }.joined() + } + func convertTokenToId(_ token: String) -> Int? { nil } + func convertIdToToken(_ id: Int) -> String? { decoding[id] } + 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] { [] } +} + +private struct NoInputProcessor: UserInputProcessor { + func prepare(input: UserInput) throws -> LMInput { LMInput(tokens: MLXArray([Int32(1)])) } +} + +@Test +func testDFlash2GenerateRoutesReasoning() async throws { + // The prompt ends in a prefilled ``, so the stream opens inside a + // thought. MockTarget follows `transition`: 3 -> 24 -> 43 -> 48 -> 83 -> 72. + let tokenizer = FragmentTokenizer(decoding: [ + 1: "Q ", 3: "", 24: "weigh ", 43: "it", 48: "", 83: "Ans", 72: "wer", + ]) + let context = ModelContext( + configuration: ModelConfiguration( + id: "dflash2", eosTokenIds: [127], reasoningConfig: .alwaysOnThinking), + model: MockTarget(), processor: NoInputProcessor(), tokenizer: tokenizer) + var parameters = GenerateParameters(maxTokens: 5) + parameters.temperature = 0 + + let stream = try generate( + input: LMInput(tokens: MLXArray([Int32(1), 1, 3])), parameters: parameters, + context: context, dflash2Drafter: MockDrafter()) + var reasoning = "" + var response = "" + for await event in stream { + switch event { + case .reasoning(let text): reasoning += text + case .chunk(let text): response += text + default: break + } + } + #expect(reasoning == "weigh it") + #expect(response == "Answer") +} + @Test func testDFlash2IteratorFinalizeRewindsUndrainedDrafts() throws { let script: [Int32] = [1, 1, 10, 20, 21, 55, 0, 30, 77, 0, 0, 77, 77, 77, 77]