diff --git a/Libraries/MLXLLM/LLMModelFactory.swift b/Libraries/MLXLLM/LLMModelFactory.swift index 7228be0d78..0891573722 100644 --- a/Libraries/MLXLLM/LLMModelFactory.swift +++ b/Libraries/MLXLLM/LLMModelFactory.swift @@ -33,6 +33,8 @@ public enum LLMTypeRegistry { "gemma3n": create(Gemma3nTextConfiguration.self, Gemma3nTextModel.init), "gemma4": create(Gemma4TextConfiguration.self, Gemma4TextModel.init), "gemma4_text": create(Gemma4TextConfiguration.self, Gemma4TextModel.init), + "gemma4_assistant": create( + Gemma4AssistantConfiguration.self, Gemma4AssistantModel.init), "qwen2": create(Qwen2Configuration.self, Qwen2Model.init), "qwen3": create(Qwen3Configuration.self, Qwen3Model.init), "qwen3_moe": create(Qwen3MoEConfiguration.self, Qwen3MoEModel.init), diff --git a/Libraries/MLXLLM/Models/Gemma4.swift b/Libraries/MLXLLM/Models/Gemma4.swift index 50be110c5a..4362c8ece5 100644 --- a/Libraries/MLXLLM/Models/Gemma4.swift +++ b/Libraries/MLXLLM/Models/Gemma4.swift @@ -1012,7 +1012,7 @@ public class Gemma4TextModel: Module, LLMModel, KVCacheDimensionProvider { public let kvHeads: [Int] @ModuleInfo public var model: Gemma4ModelInner - @ModuleInfo(key: "lm_head") var lmHead: Linear? + @ModuleInfo(key: "lm_head") public var lmHead: Linear? let config: Gemma4TextConfiguration diff --git a/Libraries/MLXLLM/Models/Gemma4Assistant.swift b/Libraries/MLXLLM/Models/Gemma4Assistant.swift new file mode 100644 index 0000000000..5753c4eb04 --- /dev/null +++ b/Libraries/MLXLLM/Models/Gemma4Assistant.swift @@ -0,0 +1,536 @@ +// Copyright © 2026 Tom Turney. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 +// +// Gemma 4 Multi-Token Prediction (MTP) drafter — Swift port of +// Blaizzy/mlx-vlm:mlx_vlm/speculative/drafters/gemma4_assistant/. +// +// Architecture notes: +// - 4-layer "assistant" model trained to draft K candidate tokens per +// round; full Gemma 4 target verifies in one parallel forward pass. +// - Tightly coupled to target: no own KV cache, reads K/V directly +// from target's last full-attention + last sliding-attention layers. +// - Each draft step input = concat([target_embed(last_token), +// last_hidden_state]) → pre_projection → drafter hidden_size. +// - Position is held constant across all draft steps within a block +// (RoPE rotates queries at the bonus token's absolute position). +// +// Implementation scope: 26B-A4B variant (no masked embedder, tied dense +// LM head, use_ordered_embeddings=false). MaskedEmbedder for E2B/E4B +// can be added later — same interface, different LM head. + +import Foundation +import MLX +import MLXLMCommon +import MLXNN + +// MARK: - Configuration + +public struct Gemma4AssistantConfiguration: Codable, Sendable { + public let modelType: String + public let backboneHiddenSize: Int + public let useOrderedEmbeddings: Bool + public let numCentroids: Int + public let centroidIntermediateTopK: Int + public let tieWordEmbeddings: Bool + public let textConfig: Gemma4TextConfiguration + + enum CodingKeys: String, CodingKey { + case modelType = "model_type" + case backboneHiddenSize = "backbone_hidden_size" + case useOrderedEmbeddings = "use_ordered_embeddings" + case numCentroids = "num_centroids" + case centroidIntermediateTopK = "centroid_intermediate_top_k" + case tieWordEmbeddings = "tie_word_embeddings" + case textConfig = "text_config" + } + + public init(from decoder: Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + self.modelType = try c.decode(String.self, forKey: .modelType) + self.backboneHiddenSize = try c.decode(Int.self, forKey: .backboneHiddenSize) + self.useOrderedEmbeddings = + try c.decodeIfPresent(Bool.self, forKey: .useOrderedEmbeddings) ?? false + self.numCentroids = + try c.decodeIfPresent(Int.self, forKey: .numCentroids) ?? 2048 + self.centroidIntermediateTopK = + try c.decodeIfPresent(Int.self, forKey: .centroidIntermediateTopK) ?? 32 + self.tieWordEmbeddings = + try c.decodeIfPresent(Bool.self, forKey: .tieWordEmbeddings) ?? true + self.textConfig = try c.decode( + Gemma4TextConfiguration.self, forKey: .textConfig) + } + + public func encode(to encoder: Encoder) throws { + var c = encoder.container(keyedBy: CodingKeys.self) + try c.encode(modelType, forKey: .modelType) + try c.encode(backboneHiddenSize, forKey: .backboneHiddenSize) + try c.encode(useOrderedEmbeddings, forKey: .useOrderedEmbeddings) + try c.encode(numCentroids, forKey: .numCentroids) + try c.encode(centroidIntermediateTopK, forKey: .centroidIntermediateTopK) + try c.encode(tieWordEmbeddings, forKey: .tieWordEmbeddings) + try c.encode(textConfig, forKey: .textConfig) + } +} + +// MARK: - Parent KV Extraction + +/// Pull the parent's last full-attention and last sliding-attention +/// K/V from its cache list, accounting for KV-sharing donors. The +/// drafter's 4 layers all run kv_shared_only against these two +/// donor tensors. +public func extractDrafterSharedKV( + layerTypes: [String], + previousKVs: [Int], + caches: [KVCache] +) -> (full: (MLXArray, MLXArray), sliding: (MLXArray, MLXArray))? { + var lastFull: Int? = nil + var lastSliding: Int? = nil + for (i, t) in layerTypes.enumerated() { + if t == "full_attention" { lastFull = i } + else if t == "sliding_attention" { lastSliding = i } + } + guard let lf = lastFull, let ls = lastSliding else { return nil } + let fullDonor = previousKVs[lf] + let slidingDonor = previousKVs[ls] + guard fullDonor < caches.count, slidingDonor < caches.count else { + return nil + } + guard let fullKV = caches[fullDonor].peek(), + let slidingKV = caches[slidingDonor].peek() + else { return nil } + return (full: fullKV, sliding: slidingKV) +} + +// MARK: - Bidirectional Drafter Masks + +/// Build a bidirectional sliding-window mask for the drafter's queries +/// against the target's cached K/V. For each query at absolute position +/// `q ∈ [queryOffset, queryOffset+queryLen)`, allow attention to keys in +/// `(q - window, q + window)`. Returns nil when no masking is needed. +private func bidirectionalSWAMask( + queryLen: Int, queryOffset: Int, kvLen: Int, + window: Int, dtype: DType +) -> MLXArray? { + if kvLen <= window && queryOffset + queryLen <= kvLen + window { + return nil + } + let qIdx = MLXArray( + Array(stride(from: Int32(queryOffset), + to: Int32(queryOffset + queryLen), + by: 1))) + .reshaped([queryLen, 1]) + let kIdx = MLXArray( + Array(stride(from: Int32(0), to: Int32(kvLen), by: 1))) + .reshaped([1, kvLen]) + let dist = qIdx - kIdx + let lo = MLX.greater(dist, MLXArray(-Int32(window))) + let hi = MLX.less(dist, MLXArray(Int32(window))) + let inside = MLX.logicalAnd(lo, hi) + let bias = MLX.where( + inside, + MLXArray(0.0).asType(dtype), + MLXArray(-Float.infinity).asType(dtype)) + return bias.reshaped([1, 1, queryLen, kvLen]) +} + +// MARK: - Drafter Attention (Q-only — K/V come from parent's shared KV) + +private class Gemma4DrafterAttention: Module { + let isSliding: Bool + let nHeads: Int + let nKVHeads: Int + let headDim: Int + let scale: Float + + @ModuleInfo(key: "q_proj") var qProj: Linear + @ModuleInfo(key: "o_proj") var oProj: Linear + @ModuleInfo(key: "q_norm") var qNorm: RMSNorm + + let rmsNormEps: Float + let rope: any OffsetLayer + let _fusedInvFreqs: MLXArray? + + init(_ config: Gemma4TextConfiguration, layerIdx: Int) { + self.isSliding = config.layerTypes[layerIdx] == "sliding_attention" + self.nHeads = config.attentionHeads + if isSliding { + self.headDim = config.headDim + self.nKVHeads = config.kvHeads + } else { + self.headDim = config.globalHeadDim + self.nKVHeads = config.globalKvHeads + } + self.scale = 1.0 + let dim = config.hiddenSize + self._qProj.wrappedValue = Linear(dim, nHeads * headDim, bias: false) + self._oProj.wrappedValue = Linear(nHeads * headDim, dim, bias: false) + self._qNorm.wrappedValue = RMSNorm( + dimensions: headDim, eps: config.rmsNormEps) + self.rmsNormEps = config.rmsNormEps + + if isSliding { + self.rope = RoPE( + dimensions: headDim, traditional: false, + base: config.ropeTheta) + let exponents = MLXArray( + stride(from: Float(0), to: Float(headDim), by: 2) + ) / Float(headDim) + let freqs = pow(MLXArray(config.ropeTheta), exponents) + self._fusedInvFreqs = 1.0 / freqs + } else { + let ropeDim = Int(Float(headDim) * config.partialRotaryFactor) + self.rope = ProportionalRoPE( + dims: headDim, rotatedDims: ropeDim, + traditional: false, base: config.globalRopeTheta) + let propExponents = MLXArray( + stride(from: Float(0), to: Float(ropeDim), by: 2) + ) / Float(headDim) + let realFreqs = pow(MLXArray(config.globalRopeTheta), propExponents) + let paddingCount = (headDim - ropeDim) / 2 + let infPadding = MLXArray( + Array(repeating: Float.infinity, count: paddingCount)) + let allFreqs = concatenated([realFreqs, infPadding], axis: 0) + self._fusedInvFreqs = 1.0 / allFreqs + } + super.init() + } + + func callAsFunction( + _ x: MLXArray, + mask: MLXFast.ScaledDotProductAttentionMaskMode, + sharedKV: (MLXArray, MLXArray), + donorOffset: Int + ) -> MLXArray { + let (B, L, _) = (x.dim(0), x.dim(1), x.dim(2)) + var queries = qProj(x).reshaped(B, L, nHeads, -1) + + if let invFreqs = _fusedInvFreqs { + queries = MLXFast.rmsNormRoPE( + queries, weight: qNorm.weight, invFreqs: invFreqs, + eps: rmsNormEps, offset: donorOffset, + nHeads: nHeads, seqLen: L) + queries = queries.transposed(0, 2, 1, 3) + } else { + queries = qNorm(queries) + queries = queries.transposed(0, 2, 1, 3) + queries = rope(queries, offset: donorOffset) + } + + let (cachedK, cachedV) = sharedKV + let output = MLXFast.scaledDotProductAttention( + queries: queries, keys: cachedK, values: cachedV, + scale: scale, mask: mask + ).transposed(0, 2, 1, 3).reshaped(B, L, -1) + return oProj(output) + } +} + +// MARK: - Drafter Decoder Layer + +private class Gemma4DrafterDecoderLayer: Module { + @ModuleInfo(key: "self_attn") var attention: Gemma4DrafterAttention + @ModuleInfo(key: "input_layernorm") var inputLayerNorm: RMSNorm + @ModuleInfo(key: "post_attention_layernorm") var postAttentionLayerNorm: RMSNorm + @ModuleInfo(key: "pre_feedforward_layernorm") var preFeedforwardLayerNorm: RMSNorm + @ModuleInfo(key: "post_feedforward_layernorm") var postFeedforwardLayerNorm: RMSNorm + + @ModuleInfo(key: "mlp") var mlp: DrafterMLP + + @ParameterInfo(key: "layer_scalar") var layerScalar: MLXArray + + init(_ config: Gemma4TextConfiguration, layerIdx: Int) { + self._attention.wrappedValue = Gemma4DrafterAttention( + config, layerIdx: layerIdx) + self._inputLayerNorm.wrappedValue = RMSNorm( + dimensions: config.hiddenSize, eps: config.rmsNormEps) + self._postAttentionLayerNorm.wrappedValue = RMSNorm( + dimensions: config.hiddenSize, eps: config.rmsNormEps) + self._preFeedforwardLayerNorm.wrappedValue = RMSNorm( + dimensions: config.hiddenSize, eps: config.rmsNormEps) + self._postFeedforwardLayerNorm.wrappedValue = RMSNorm( + dimensions: config.hiddenSize, eps: config.rmsNormEps) + self._mlp.wrappedValue = DrafterMLP(config) + // layer_scalar is loaded from checkpoint + self._layerScalar.wrappedValue = MLXArray.ones([1]) + super.init() + } + + func callAsFunction( + _ x: MLXArray, + mask: MLXFast.ScaledDotProductAttentionMaskMode, + sharedKV: (MLXArray, MLXArray), + donorOffset: Int + ) -> MLXArray { + let inputNorm = inputLayerNorm(x) + let attnOut = attention( + inputNorm, mask: mask, sharedKV: sharedKV, + donorOffset: donorOffset) + var h = MLXFast.rmsNormResidual( + attnOut, residual: x, + weight: postAttentionLayerNorm.weight, + eps: postAttentionLayerNorm.eps) + let preFFNNorm = preFeedforwardLayerNorm(h) + let ffnOut = mlp(preFFNNorm) + h = MLXFast.rmsNormResidual( + ffnOut, residual: h, + weight: postFeedforwardLayerNorm.weight, + eps: postFeedforwardLayerNorm.eps) + h = h * layerScalar + return h + } +} + +private class DrafterMLP: 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: Gemma4TextConfiguration) { + let hidden = config.hiddenSize + let inter = config.intermediateSize + self._gateProj.wrappedValue = Linear(hidden, inter, bias: false) + self._upProj.wrappedValue = Linear(hidden, inter, bias: false) + self._downProj.wrappedValue = Linear(inter, hidden, bias: false) + super.init() + } + + func callAsFunction(_ x: MLXArray) -> MLXArray { + downProj(geluApproximate(gateProj(x)) * upProj(x)) + } +} + +// MARK: - Drafter Inner Model + +private class Gemma4AssistantInner: Module { + @ModuleInfo(key: "embed_tokens") var embedTokens: Embedding + @ModuleInfo var layers: [Gemma4DrafterDecoderLayer] + @ModuleInfo var norm: RMSNorm + + let config: Gemma4TextConfiguration + + init(_ config: Gemma4TextConfiguration) { + self.config = config + self._embedTokens.wrappedValue = Embedding( + embeddingCount: config.vocabularySize, + dimensions: config.hiddenSize) + self._layers.wrappedValue = (0 ..< config.hiddenLayers).map { + Gemma4DrafterDecoderLayer(config, layerIdx: $0) + } + self._norm.wrappedValue = RMSNorm( + dimensions: config.hiddenSize, eps: config.rmsNormEps) + super.init() + } +} + +// MARK: - Drafter Model + +public class Gemma4AssistantModel: Module, LanguageModel { + public var vocabularySize: Int { config.textConfig.vocabularySize } + public let kvHeads: [Int] = [] // No own cache + @ModuleInfo private var model: Gemma4AssistantInner + @ModuleInfo(key: "pre_projection") var preProjection: Linear + @ModuleInfo(key: "post_projection") var postProjection: Linear + @ModuleInfo(key: "lm_head") var lmHead: Linear? + + public let config: Gemma4AssistantConfiguration + + /// Bound parent embedding (set via `bind(parent:)`). + private var parentEmbed: Embedding? + private var parentEmbedScale: Float = 1.0 + + /// Shared K/V from parent (set via `setSharedKV(...)` per draft block). + /// Keys are layer types: "full_attention" and "sliding_attention". + private var sharedKV: [String: (MLXArray, MLXArray)] = [:] + private var sharedKVOffset: Int = 0 + private var draftPosition: Int = 0 + + public init(_ config: Gemma4AssistantConfiguration) { + self.config = config + let textCfg = config.textConfig + self._model.wrappedValue = Gemma4AssistantInner(textCfg) + self._preProjection.wrappedValue = Linear( + 2 * config.backboneHiddenSize, textCfg.hiddenSize, bias: false) + self._postProjection.wrappedValue = Linear( + textCfg.hiddenSize, config.backboneHiddenSize, bias: false) + if !config.tieWordEmbeddings { + self._lmHead.wrappedValue = Linear( + textCfg.hiddenSize, textCfg.vocabularySize, bias: false) + } + super.init() + } + + /// Bind to the parent target model's input embedding. Required before + /// `draftBlock` can run (drafter uses parent's embedding to embed + /// the last accepted token). + public func bind(parentEmbedding: Embedding, embedScale: Float) { + self.parentEmbed = parentEmbedding + self.parentEmbedScale = embedScale + } + + /// Provide shared K/V from parent's caches. Call this BEFORE every + /// `draftBlock` so the drafter sees the up-to-date target activations. + /// - Parameters: + /// - fullAttn: parent's last full-attention layer's (K, V) + /// - slidingAttn: parent's last sliding-attention layer's (K, V) + /// - kvOffset: parent cache.offset (number of cells filled) + /// - position: absolute position of bonus query (typically kvOffset) + public func setSharedKV( + fullAttn: (MLXArray, MLXArray), + slidingAttn: (MLXArray, MLXArray), + kvOffset: Int, + position: Int? = nil + ) { + self.sharedKV = [ + "full_attention": fullAttn, + "sliding_attention": slidingAttn, + ] + self.sharedKVOffset = kvOffset + self.draftPosition = position ?? kvOffset + } + + /// Pre-computed masks for one draft block (constant across all + /// blockSize-1 steps within a block — position is fixed and KV is + /// not appended to during drafting). + private var cachedMasks: [String: MLXFast.ScaledDotProductAttentionMaskMode] = [:] + + /// One forward step of the drafter. + /// - Parameter inputsEmbeds: shape `[B, L, 2*backboneHiddenSize]` + /// - Returns: (last_hidden in backbone size, logits) + public func forwardStep( + _ inputsEmbeds: MLXArray + ) -> (lastHidden: MLXArray, logits: MLXArray) { + let textCfg = config.textConfig + var h = preProjection(inputsEmbeds) + let queryOffset = draftPosition + + for (layerIdx, layer) in model.layers.enumerated() { + let layerType = textCfg.layerTypes[layerIdx] + guard let kv = sharedKV[layerType] else { + fatalError("setSharedKV not called for \(layerType)") + } + let mask = cachedMasks[layerType] ?? .none + h = layer( + h, mask: mask, sharedKV: kv, + donorOffset: queryOffset) + } + + h = model.norm(h) + let lastHidden = postProjection(h) + + let logits: MLXArray + if let lm = lmHead { + logits = lm(h) + } else { + logits = model.embedTokens.asLinear(h) + } + return (lastHidden, logits) + } + + /// Build per-layer-type masks once at the start of each draft block. + private func buildBlockMasks(queryLen: Int, dtype: DType) { + let textCfg = config.textConfig + cachedMasks.removeAll(keepingCapacity: true) + for (layerType, kv) in sharedKV { + if layerType == "sliding_attention" { + if let m = bidirectionalSWAMask( + queryLen: queryLen, queryOffset: draftPosition, + kvLen: kv.0.dim(2), window: textCfg.slidingWindow, + dtype: dtype) + { + cachedMasks[layerType] = .array(m) + } else { + cachedMasks[layerType] = .none + } + } else { + cachedMasks[layerType] = .none + } + } + } + + /// Autoregressive K-step drafting (lazy). Returns an `MLXArray` of + /// shape `[1, blockSize-1]` (Int32) — the drafted candidate tokens + /// — WITHOUT forcing GPU↔CPU sync. The caller is expected to thread + /// this directly into the parent's verify forward and sync once at + /// the end of the round, so the full drafter chain fuses into one + /// lazy MLX graph evaluation. + /// + /// `lastBonus` is the most recently accepted token (B=1: scalar Int); + /// `hidden` is the parent's last hidden state at that position. + public func draftBlock( + lastBonus: Int, hidden: MLXArray, blockSize: Int + ) -> MLXArray { + precondition(parentEmbed != nil, + "bind(parentEmbedding:) must be called before draftBlock") + precondition(!sharedKV.isEmpty, + "setSharedKV must be called before draftBlock") + precondition(blockSize > 1, "blockSize must be >= 2") + + // Build masks once per draft block (queryLen=1 fixed across steps, + // queryOffset and KV layout are also constant per block). + buildBlockMasks(queryLen: 1, dtype: hidden.dtype) + + // Token state stays as MLXArray throughout — never pulls to CPU + // until the caller decides to sync. + var tokArr = MLXArray([Int32(lastBonus)]).reshaped([1, 1]) + var hPrev = hidden + var draftedArrs: [MLXArray] = [] + for _ in 0 ..< (blockSize - 1) { + let tokEmbed = parentEmbed!(tokArr) * parentEmbedScale + let inputsEmbeds = concatenated([tokEmbed, hPrev], axis: -1) + let (newHidden, logits) = forwardStep(inputsEmbeds) + // Greedy argmax → next token (shape [1, 1] int32). Stays + // lazy; no .item() call. + let nextTokArr = argMax(logits[0, 0], axis: -1) + .asType(.int32).reshaped([1, 1]) + draftedArrs.append(nextTokArr) + hPrev = newHidden + tokArr = nextTokArr + } + // shape [1, blockSize-1] + return concatenated(draftedArrs, axis: 1) + } + + /// Stub for LanguageModel protocol conformance — Gemma4Assistant is + /// driven via `runMTPSpeculative`, not the standard generate path. + /// Calling `prepare` or `callAsFunction` on this model directly is a + /// programming error. + public func prepare( + _ input: LMInput, cache: [KVCache], windowSize: Int? + ) throws -> PrepareResult { + fatalError( + "Gemma4AssistantModel must be driven via runMTPSpeculative, " + + "not the standard generate() path") + } + + /// Drafter has no own KV cache — reads K/V from the parent's caches + /// via setSharedKV during draft_block. + public func newCache(parameters: GenerateParameters?) -> [KVCache] { + [] + } + + /// Strip checkpoint keys that aren't loaded (e.g. tied LM head, ordering + /// indices not used in 26B-A4B path). Mirror of mlx-vlm sanitize(). + public func sanitize(weights: [String: MLXArray]) -> [String: MLXArray] { + var out = weights + + // Strip language_model. prefix if present (some checkpoints wrap it). + let unflattened = ModuleParameters.unflattened(weights) + if let lm = unflattened["language_model"] { + out = Dictionary(uniqueKeysWithValues: lm.flattened()) + } + + // Drop tied lm_head.weight (we use embed_tokens.asLinear). + if config.tieWordEmbeddings { + out.keys.filter { $0.hasPrefix("lm_head.") } + .forEach { out.removeValue(forKey: $0) } + } + + // Drop masked embedder weights (E2B/E4B-only — not used in 26B-A4B). + if !config.useOrderedEmbeddings { + out.keys.filter { $0.hasPrefix("masked_embedding.") } + .forEach { out.removeValue(forKey: $0) } + } + + return out + } +} diff --git a/Libraries/MLXLLM/Models/MTPSpec.swift b/Libraries/MLXLLM/Models/MTPSpec.swift new file mode 100644 index 0000000000..38ece64954 --- /dev/null +++ b/Libraries/MLXLLM/Models/MTPSpec.swift @@ -0,0 +1,324 @@ +// Copyright © 2026 Tom Turney. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 +// +// MTPSpec — Multi-Token Prediction speculative decoding driver for +// Gemma 4 + Gemma4Assistant pairs. Distinct from +// SpeculativeTokenIterator (which assumes the drafter is autoregressive +// on token IDs); this iterator threads parent's last hidden state + +// shared K/V into the drafter every round. +// +// Loop: +// 1. Prefill parent on prompt → cache populated, last token + last +// hidden state captured. +// 2. While more tokens needed: +// a. Extract parent's last full-attn + last sliding-attn K/V. +// b. drafter.setSharedKV(...) with current parent cache offset. +// c. drafter.draftBlock(lastBonus, lastHidden, blockSize) → +// (blockSize-1) candidate tokens. +// d. Verify input = [lastBonus, c1, c2, ..., c_{K-1}] of length K. +// e. parent forward → K logits + K hidden states. +// f. Greedy verify: argmax(logits[i]) must match c_{i+1} for +// accept. Stop at first mismatch. +// g. If all matched, accept argmax(logits[K-1]) as bonus. +// h. Trim parent cache by (K - acceptedCount) cells. +// i. Yield accepted tokens. lastBonus = last accepted, lastHidden +// = hidden at that position. + +import Foundation +import MLX +import MLXLMCommon +import MLXNN + +public struct MTPGeneration: Sendable { + public enum Kind: Sendable { + case token(Int) + case info(MTPInfo) + } + public let kind: Kind +} + +public struct MTPInfo: Sendable { + public let promptTokens: Int + public let generatedTokens: Int + public let prefillSec: Double + public let decodeSec: Double + public let proposedTotal: Int + public let acceptedTotal: Int + public var acceptanceRate: Double { + proposedTotal > 0 + ? Double(acceptedTotal) / Double(proposedTotal) : 0 + } +} + +/// Run MTP speculative generation synchronously. Caller is responsible +/// for tokenizing the prompt (use mainContext.processor.prepare on a +/// UserInput). Token IDs are reported via the `onToken` callback as +/// they're accepted; the function returns once generation is complete. +public func runMTPSpeculative( + input: LMInput, + mainModel: Gemma4TextModel, + drafter: Gemma4AssistantModel, + parameters: GenerateParameters, + blockSize: Int = 4, + onToken: (Int) -> Void +) throws -> MTPInfo { + return try runMTPSpeculativeBody( + input: input, + mainModel: mainModel, + drafter: drafter, + parameters: parameters, + blockSize: blockSize, + onToken: onToken + ) +} + +private func runMTPSpeculativeBody( + input: LMInput, + mainModel: Gemma4TextModel, + drafter: Gemma4AssistantModel, + parameters: GenerateParameters, + blockSize: Int, + onToken: (Int) -> Void +) throws -> MTPInfo { + precondition(blockSize >= 2, + "MTP requires blockSize >= 2 (drafter generates blockSize-1)") + + // Bind drafter to parent's input embedding. + let embedScale = sqrt(Float(mainModel.config.hiddenSize)) + drafter.bind( + parentEmbedding: mainModel.model.embedTokens, + embedScale: embedScale) + + // Build parent cache. + let cache = mainModel.newCache(parameters: parameters) + + // Prefill via parent.prepare — chunks through all but last token. + let promptTokens = input.text.tokens.size + let tStart = Date() + let prepareResult = try mainModel.prepare( + input, cache: cache, windowSize: nil) + var remaining: LMInput.Text + switch prepareResult { + case .tokens(let y): + remaining = y + default: + // logits-output prepare not handled here + throw NSError( + domain: "MTPSpec", code: 1, + userInfo: [NSLocalizedDescriptionKey: + "prepare() returned non-token result"]) + } + + // Process the remaining (typically 1) token to get initial + // last_hidden + bootstrap the first generated token. + let lastChunk = remaining.tokens[.newAxis, 0...] + let initHidden = mainModel.model(lastChunk, cache: cache) + let initLogits: MLXArray + if mainModel.config.tieWordEmbeddings { + initLogits = mainModel.model.embedTokens.asLinear(initHidden) + } else { + initLogits = mainModel.lmHead!(initHidden) + } + // Greedy first token from the last position's logits. The argMax + // .item() call forces eval of the dependency graph here — no need + // for an explicit eval() barrier. + let lastT = initLogits.dim(1) - 1 + var lastBonus = argMax(initLogits[0, lastT], axis: -1).item(Int.self) + // Hidden at the last position: shape [1, 1, hidden]. Eval forces + // it onto a fresh root so subsequent rounds don't keep the entire + // initial graph alive. + var lastHidden = initHidden[0..<1, lastT.. 0 + }?.offset ?? cache[0].offset + drafter.setSharedKV( + fullAttn: shared.full, + slidingAttn: shared.sliding, + kvOffset: parentOffset, + position: parentOffset) + + // 3. Draft K-1 candidates — stays as MLXArray, no sync yet. + let tDraftStart = profileEnabled ? Date() : Date.distantPast + let candidatesArr = drafter.draftBlock( + lastBonus: lastBonus, + hidden: lastHidden, + blockSize: blockSize) + if profileEnabled { + eval(candidatesArr) // force eval to measure drafter alone + tDraft += Date().timeIntervalSince(tDraftStart) + } + let numCandidates = blockSize - 1 + proposedTotal += numCandidates + + // 4. Build verification input = [[bonus, c1, c2, ..., c_{K-1}]]. + // Concat lazily so the entire drafter chain + parent verify + // forward fuses into one MLX graph evaluation. + let bonusArr = MLXArray([Int32(lastBonus)]).reshaped([1, 1]) + let verifyInput = concatenated([bonusArr, candidatesArr], axis: 1) + let K = blockSize // verifyInput length + + // 5. Parent forward. + let tVerifyStart = profileEnabled ? Date() : Date.distantPast + let vHidden = mainModel.model(verifyInput, cache: cache) + let vLogits: MLXArray + if mainModel.config.tieWordEmbeddings { + vLogits = mainModel.model.embedTokens.asLinear(vHidden) + } else { + vLogits = mainModel.lmHead!(vHidden) + } + if profileEnabled { + eval(vLogits) + tVerify += Date().timeIntervalSince(tVerifyStart) + } + + // 6. Single sync per round: pull both candidates (drafter + // outputs) and target predictions in one shot. Concatenate + // [candidates_flat, preds] into one tensor and read it back + // with a single asArray call — collapses 3 sync points + // (K-1 in drafter + 1 here) into 1. + let tSyncStart = profileEnabled ? Date() : Date.distantPast + let predsTensor = argMax(vLogits[0], axis: -1).asType(.int32) + let combined = concatenated( + [candidatesArr.flattened(), predsTensor], axis: 0) + let combinedCPU: [Int32] = combined.asArray(Int32.self) + if profileEnabled { + tSync += Date().timeIntervalSince(tSyncStart) + } + let candidatesCPU = Array(combinedCPU[0.. 0 { + for c in cache { + if c.isTrimmable { + _ = c.trim(toTrim) + } + } + } + if profileEnabled { + tCache += Date().timeIntervalSince(tCacheStart) + roundsCounted += 1 + } + + // 9. Yield accepted tokens (capped to maxTokens). + for tok in accepted { + if generatedCount >= maxTokens { break } + onToken(tok) + generatedCount += 1 + } + + // 10. Update lastBonus + lastHidden for next round. + lastBonus = accepted.last! + // Hidden index in vHidden: position lastAcceptedIdx (if matched + // all, use K-1; if partial match at i, use i). + let hIdx = allMatched ? (K - 1) : lastAcceptedIdx + lastHidden = vHidden[0..<1, hIdx.. 0 { + let n = Double(roundsCounted) + print(String(format: + "[mtp-profile] rounds=%d draft=%.2fms verify=%.2fms " + + "sync=%.2fms cache_trim=%.2fms per_round_total=%.2fms", + roundsCounted, + tDraft / n * 1000.0, + tVerify / n * 1000.0, + tSync / n * 1000.0, + tCache / n * 1000.0, + decodeSec / n * 1000.0)) + } + return MTPInfo( + promptTokens: promptTokens, + generatedTokens: generatedCount, + prefillSec: prefillSec, + decodeSec: decodeSec, + proposedTotal: proposedTotal, + acceptedTotal: acceptedTotal) +} diff --git a/Tests/Benchmarks/MTPSpecDecode.swift b/Tests/Benchmarks/MTPSpecDecode.swift new file mode 100644 index 0000000000..ac95effa29 --- /dev/null +++ b/Tests/Benchmarks/MTPSpecDecode.swift @@ -0,0 +1,281 @@ +// Copyright © 2026 Tom Turney. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 +// +// Google Gemma 4 MTP drafter benchmark on M5 Max. +// +// Google released MTP drafters (small "assistant" models) for the Gemma 4 +// family on 2026-05-05, claimed up to 3× decode speedup via speculative +// decoding with no quality loss. Drafters share the target's tokenizer +// and (per Google's blog) "seamlessly utilize the target model's +// activations and share its KV cache." +// +// This benchmark uses the standard mlx-swift-lm SpeculativeTokenIterator +// path (port of mlx-lm's speculative_generate_step) — separate KV caches +// for main and draft. So this measures the floor of what MTP gives us +// before any KV-share plumbing. +// +// Pairs: +// target: mlx-community/gemma-4-e4b-it-4bit +// draft: mlx-community/gemma-4-E4B-it-assistant-bf16 +// +// Captures per cell: prefill_s, decode_s, decode_tps, accepted_total, +// proposed_total, acceptance_rate. +// +// Gated: +// RUN_MTP_SPEC=1 swift test --filter "MTPSpecDecode" + +import Foundation +import Testing +import MLX +import MLXNN +import MLXLMCommon +import MLXLLM +import HuggingFace +import MLXHuggingFace +import Tokenizers + +private let mtpDownloader: any Downloader = #hubDownloader() +private let mtpTokenizerLoader: any TokenizerLoader = #huggingFaceTokenizerLoader() + +@Suite("Gemma 4 MTP drafter speedup on M5", .serialized) +struct MTPSpecDecode { + + private static var enabled: Bool { + ProcessInfo.processInfo.environment["RUN_MTP_SPEC"] == "1" + } + + // 31B dense — matches the community Python MLX benchmark Tom shared + // (1.99× speedup at ~20 tps baseline on bf16). Going with 4bit target + // to keep download manageable (~17GB vs 62GB bf16). 31B drafter is + // also `use_ordered_embeddings=false` per its config — no masked + // embedder needed. + private static let targetId = "mlx-community/gemma-4-31b-it-4bit" + private static let draftId = "mlx-community/gemma-4-31B-it-assistant-bf16" + + // numDraftTokens values to sweep. Includes k=1 and k=3 to find the + // real sweet spot after drafter quantization shifted the optimum. + // Defaults to short-ctx full sweep; at long ctx (MTP_PROMPT_TOK set) + // we trim to k=2 (proven optimum) to keep the run fast. + private static var draftBudgets: [Int] { + let isLong = ProcessInfo.processInfo.environment["MTP_PROMPT_TOK"] + .flatMap(Int.init).map { $0 >= 16_000 } ?? false + return isLong ? [2] : [1, 2, 3, 4, 6, 8] + } + + private static let shortPrompt = """ + Write a detailed explanation of how speculative decoding works in + modern language model inference. Cover the role of the draft \ + model, why acceptance rate matters, the relationship between draft \ + length and end-to-end speedup, and the typical failure modes when \ + the draft and target diverge in distribution. + """ + + /// Generate a long filler prompt targeting roughly `tokenTarget` tokens. + /// Filler tokenizes at ~1 token / 7 chars on Gemma's tokenizer. + private static func longPrompt(tokenTarget: Int) -> String { + let charTarget = max(64, tokenTarget * 7) + let filler = "the routine quarterly procedure required " + + "careful review of the documented operational records " + + "during the assessment cycle. " + var s = "" + while s.count < charTarget { s += filler } + return s + "\n\nSummarize the above in one paragraph." + } + + /// Resolve the prompt: if MTP_PROMPT_TOK env is set, build a long + /// filler prompt to that token target. Otherwise use the short one. + private static var prompt: String { + if let s = ProcessInfo.processInfo.environment["MTP_PROMPT_TOK"], + let n = Int(s), n > 0 + { + return longPrompt(tokenTarget: n) + } + return shortPrompt + } + + private static let maxTokens = 256 + + @Test("Gemma 4 E4B + E4B-assistant MTP speedup") + func mtpRamp() async throws { + guard Self.enabled else { + print("[mtp] skipped: set RUN_MTP_SPEC=1") + return + } + + unsetenv("VLLM_TRIATT_ENABLED") + unsetenv("LONGCTX_ENDPOINT") + + print("[mtp] loading target \(Self.targetId)...") + let tStart = Date() + let mainContext = try await loadModel( + from: mtpDownloader, using: mtpTokenizerLoader, + id: Self.targetId, progressHandler: { _ in } + ) + print("[mtp] target loaded in " + + "\(String(format: "%.1f", Date().timeIntervalSince(tStart)))s") + + print("[mtp] loading drafter \(Self.draftId)...") + let dStart = Date() + let draftContext = try await loadModel( + from: mtpDownloader, using: mtpTokenizerLoader, + id: Self.draftId, progressHandler: { _ in } + ) + print("[mtp] drafter loaded in " + + "\(String(format: "%.1f", Date().timeIntervalSince(dStart)))s") + + // Optional: quantize drafter to 4-bit at load. Saves ~75% of + // drafter weight bandwidth on every forward step. Profile shows + // drafter ≈ 2.5ms/step at bf16; expected ~0.7ms at 4-bit. + if ProcessInfo.processInfo.environment["MTP_DRAFTER_4BIT"] == "1", + let drafter = draftContext.model as? Gemma4AssistantModel + { + let qStart = Date() + MLXNN.quantize( + model: drafter, + filter: { _, module in + // Quantize Linear and Embedding layers, group=64 bits=4. + if module is Linear || module is Embedding { + return (groupSize: 64, bits: 4, mode: .affine) + } + return nil + } + ) + eval(drafter) + print("[mtp] drafter quantized to 4-bit in " + + "\(String(format: "%.1f", Date().timeIntervalSince(qStart)))s") + } + + let resolvedPrompt = Self.prompt + let messages: [[String: String]] = [ + ["role": "user", "content": resolvedPrompt], + ] + let userInput = UserInput(prompt: .messages(messages)) + let input = try await mainContext.processor.prepare(input: userInput) + let promptTok = input.text.tokens.size + print("[mtp] prompt tokens: \(promptTok)") + + let params = GenerateParameters( + maxTokens: Self.maxTokens, temperature: 0.0 + ) + + print("\n==== GEMMA 4 MTP DRAFTER BENCH (M5 Max) ====") + print("target: \(Self.targetId)") + print("draft: \(Self.draftId)") + print("prompt_tok=\(promptTok), max_new=\(Self.maxTokens), temp=0.0\n") + print("config prefill decode tps tokens speedup") + + // Baseline (no draft model) + var baselineTps: Double = 0 + do { + let r = try await Self.runOne( + input: input, params: params, + mainContext: mainContext, draftModel: nil, numDraftTokens: 0 + ) + baselineTps = r.decodeTps + Self.printRow( + tag: "baseline ", + r: r, speedup: 1.0 + ) + } + + // Spec-decode sweep + for k in Self.draftBudgets { + do { + let r = try await Self.runOne( + input: input, params: params, + mainContext: mainContext, + draftModel: draftContext.model, numDraftTokens: k + ) + let speedup = baselineTps > 0 + ? r.decodeTps / baselineTps : 0.0 + Self.printRow( + tag: "spec k=\(k) ", + r: r, speedup: speedup + ) + } catch { + print("spec k=\(k) ERROR: \(error)") + } + } + } + + private static func printRow(tag: String, r: CellResult, speedup: Double) { + let prefillStr = String(format: "%.2f", r.prefillSec) + let decodeStr = String(format: "%.2f", r.decodeSec) + let tpsStr = String(format: "%.1f", r.decodeTps) + let speedupStr = String(format: "%.2f", speedup) + print("\(tag)\(prefillStr)s \(decodeStr)s \(tpsStr) " + + "\(r.tokensGen) \(speedupStr)×") + } + + private struct CellResult { + let prefillSec: Double + let decodeSec: Double + let decodeTps: Double + let tokensGen: Int + } + + private static func runOne( + input: LMInput, + params: GenerateParameters, + mainContext: ModelContext, + draftModel: (any LanguageModel)?, + numDraftTokens: Int + ) async throws -> CellResult { + // MTP path: drafter is a Gemma4AssistantModel, target a + // Gemma4TextModel — use the dedicated MTP iterator. + if let drafter = draftModel as? Gemma4AssistantModel, + let mainGemma = mainContext.model as? Gemma4TextModel + { + let blockSize = max(2, numDraftTokens + 1) + var tokensGen = 0 + let info = try runMTPSpeculative( + input: input, mainModel: mainGemma, drafter: drafter, + parameters: params, blockSize: blockSize, + onToken: { _ in tokensGen += 1 }) + let prefillSec = info.prefillSec + let decodeSec = info.decodeSec + let tps = decodeSec > 0 + ? Double(max(1, tokensGen - 1)) / decodeSec : 0.0 + print(String(format: + " [mtp k=%d] proposed=%d accepted=%d (rate=%.2f%%)", + numDraftTokens, info.proposedTotal, info.acceptedTotal, + info.proposedTotal > 0 + ? 100.0 * Double(info.acceptedTotal) / + Double(info.proposedTotal) + : 0.0)) + return CellResult( + prefillSec: prefillSec, decodeSec: decodeSec, + decodeTps: tps, tokensGen: tokensGen) + } + + // Baseline (no drafter) — standard generate. + let stream = try MLXLMCommon.generate( + input: input, parameters: params, context: mainContext + ) + + let tStart = Date() + var firstTokenTime: TimeInterval? = nil + var tokensGen = 0 + for await gen in stream { + switch gen { + case .chunk: + if firstTokenTime == nil { + firstTokenTime = Date().timeIntervalSince(tStart) + } + tokensGen += 1 + case .info, .toolCall: + break + } + } + let totalSec = Date().timeIntervalSince(tStart) + let prefillSec = firstTokenTime ?? totalSec + let decodeSec = max(0.001, totalSec - prefillSec) + let decodeTps = Double(max(1, tokensGen - 1)) / decodeSec + return CellResult( + prefillSec: prefillSec, + decodeSec: decodeSec, + decodeTps: decodeTps, + tokensGen: tokensGen + ) + } +}