diff --git a/.gitignore b/.gitignore index dc0cc86d5a..6dc87ed8d4 100644 --- a/.gitignore +++ b/.gitignore @@ -93,6 +93,7 @@ iOSInjectionProject/ omlx/ mlx-swift-lm/ vllm-swift/ +refs/ # OS .DS_Store diff --git a/Libraries/MLXHuggingFaceMacros/HuggingFaceIntegrationMacros.swift b/Libraries/MLXHuggingFaceMacros/HuggingFaceIntegrationMacros.swift index c1086fa771..c60438a6b8 100644 --- a/Libraries/MLXHuggingFaceMacros/HuggingFaceIntegrationMacros.swift +++ b/Libraries/MLXHuggingFaceMacros/HuggingFaceIntegrationMacros.swift @@ -121,6 +121,18 @@ public struct TokenizerAdaptorMacro: ExpressionMacro { throw MLXLMCommon.TokenizerError.missingChatTemplate } } + + func applyChatTemplate( + messages: [[String: any Sendable]], + chatTemplate: String + ) throws -> [Int] { + do { + return try upstream.applyChatTemplate( + messages: messages, chatTemplate: chatTemplate) + } catch Tokenizers.TokenizerError.missingChatTemplate { + throw MLXLMCommon.TokenizerError.missingChatTemplate + } + } } return TokenizerBridge(huggingFaceTokenizer) diff --git a/Libraries/MLXLLM/LLMModelFactory.swift b/Libraries/MLXLLM/LLMModelFactory.swift index 969b9ca4d1..3ffc9588af 100644 --- a/Libraries/MLXLLM/LLMModelFactory.swift +++ b/Libraries/MLXLLM/LLMModelFactory.swift @@ -46,6 +46,7 @@ public enum LLMTypeRegistry { "openelm": create(OpenElmConfiguration.self, OpenELMModel.init), "internlm2": create(InternLM2Configuration.self, InternLM2Model.init), "deepseek_v3": create(DeepseekV3Configuration.self, DeepseekV3Model.init), + "deepseek_v4": create(DeepseekV4Configuration.self, DeepseekV4Model.init), "granite": create(GraniteConfiguration.self, GraniteModel.init), "granitemoehybrid": create( GraniteMoeHybridConfiguration.self, GraniteMoeHybridModel.init), diff --git a/Libraries/MLXLLM/Models/DeepseekV4.swift b/Libraries/MLXLLM/Models/DeepseekV4.swift new file mode 100644 index 0000000000..7a3ff55be8 --- /dev/null +++ b/Libraries/MLXLLM/Models/DeepseekV4.swift @@ -0,0 +1,1769 @@ +// DeepSeek-V4 model port. +// +// Faithful port of ml-explore/mlx-lm#1192 (base model by Blaizzy, 0xClandestine, +// angeloskath, pcuenca, eauchs) and Blaizzy/mlx-lm#15 (MTP). +// Reference: omlx/patches/deepseek_v4/deepseek_v4_model.py +// omlx/patches/deepseek_v4/hyper_connection.py +// omlx/patches/deepseek_v4/cache_extras.py (PoolingCache) + +import Foundation +import MLX +import MLXLMCommon +import MLXNN + +// MARK: - Configuration + +public struct DeepseekV4Configuration: Codable, Sendable { + var vocabSize: Int = 129280 + var hiddenSize: Int = 4096 + var moeIntermediateSize: Int = 2048 + var numHiddenLayers: Int = 43 + var numAttentionHeads: Int = 64 + var headDim: Int = 512 + var qLoraRank: Int = 1024 + var qkRopeHeadDim: Int = 64 + var rmsNormEps: Float = 1e-6 + var oGroups: Int = 8 + var oLoraRank: Int = 1024 + var slidingWindow: Int = 128 + var compressRatios: [Int] = [] + var compressRopeTheta: Float = 160000.0 + var nRoutedExperts: Int = 256 + var nSharedExperts: Int = 1 + var numExpertsPerTok: Int = 6 + var scoringFunc: String = "sqrtsoftplus" + var routedScalingFactor: Float = 1.5 + var swiguLimit: Float = 10.0 + var numHashLayers: Int = 3 + var numNextnPredictLayers: Int = 1 + var normTopkProb: Bool = true + var hcMult: Int = 4 + var hcSinkhornIters: Int = 20 + var hcEps: Float = 1e-6 + var ropeTheta: Float = 10000.0 + var ropeScaling: [String: StringOrNumber]? + var maxPositionEmbeddings: Int = 1_048_576 + var indexNHeads: Int = 64 + var indexHeadDim: Int = 128 + var indexTopk: Int = 512 + + var nopeHeadDim: Int { headDim - qkRopeHeadDim } + + enum CodingKeys: String, CodingKey { + case vocabSize = "vocab_size" + case hiddenSize = "hidden_size" + case moeIntermediateSize = "moe_intermediate_size" + case numHiddenLayers = "num_hidden_layers" + case numAttentionHeads = "num_attention_heads" + case headDim = "head_dim" + case qLoraRank = "q_lora_rank" + case qkRopeHeadDim = "qk_rope_head_dim" + case rmsNormEps = "rms_norm_eps" + case oGroups = "o_groups" + case oLoraRank = "o_lora_rank" + case slidingWindow = "sliding_window" + case compressRatios = "compress_ratios" + case compressRopeTheta = "compress_rope_theta" + case nRoutedExperts = "n_routed_experts" + case nSharedExperts = "n_shared_experts" + case numExpertsPerTok = "num_experts_per_tok" + case scoringFunc = "scoring_func" + case routedScalingFactor = "routed_scaling_factor" + case swiguLimit = "swiglu_limit" + case numHashLayers = "num_hash_layers" + case numNextnPredictLayers = "num_nextn_predict_layers" + case normTopkProb = "norm_topk_prob" + case hcMult = "hc_mult" + case hcSinkhornIters = "hc_sinkhorn_iters" + case hcEps = "hc_eps" + case ropeTheta = "rope_theta" + case ropeScaling = "rope_scaling" + case maxPositionEmbeddings = "max_position_embeddings" + case indexNHeads = "index_n_heads" + case indexHeadDim = "index_head_dim" + case indexTopk = "index_topk" + } + + /// Populate default compress_ratios if empty (mirrors Python __post_init__). + mutating func fillDefaultCompressRatios() { + guard compressRatios.isEmpty else { return } + let n = numHiddenLayers + compressRatios = + [0] + + (0..= 2 ? [0] : []) + compressRatios = Array(compressRatios.prefix(numHiddenLayers)) + } +} + +// MARK: - PoolingCache + +/// Accumulates tokens into windows of size `ratio`, compresses them, and stores pooled KVs. +/// Mirrors Python PoolingCache from mlx-lm#1192 cache.py. +final class PoolingCache { + let ratio: Int + var bufKV: MLXArray? // [B, remainder, out_dim] + var bufGate: MLXArray? // [B, remainder, out_dim] + var pooled: MLXArray? // [B, n_pooled, head_dim] + + var pooledCount: Int { pooled?.dim(1) ?? 0 } + + init(ratio: Int) { + self.ratio = ratio + } + + /// Split `kv`/`gate` into complete windows of `ratio` tokens. + /// Returns (readyKV, readyGate, poolBase) where readyKV has shape [B, n_windows*ratio, D]. + func accumulateWindows(kv: MLXArray, gate: MLXArray, offset: Int) + -> (MLXArray, MLXArray, Int) + { + let B = kv.dim(0), L = kv.dim(1), D1 = kv.dim(2), D2 = gate.dim(2) + + if L > 1 { + // Prompt mode + let remainder = bufKV?.dim(1) ?? 0 + let total = L + remainder + let usable = (total / ratio) * ratio + let newRemainder = total % ratio + + let readyKV: MLXArray + let readyGate: MLXArray + let poolBase: Int + + if usable > 0 { + let prevKV = bufKV ?? zeros([B, 0, D1], dtype: kv.dtype) + let prevGate = bufGate ?? zeros([B, 0, D2], dtype: gate.dtype) + let combinedKV = concatenated([prevKV, kv], axis: 1) + let combinedGate = concatenated([prevGate, gate], axis: 1) + readyKV = combinedKV[0..., .. 0 { + bufKV = kv[0..., (L - newRemainder)..., 0...] + bufGate = gate[0..., (L - newRemainder)..., 0...] + } else { + bufKV = nil + bufGate = nil + } + + return (readyKV, readyGate, poolBase) + } else { + // Decode mode: accumulate one token at a time + let newBufKV: MLXArray + let newBufGate: MLXArray + if let cur = bufKV, let curG = bufGate { + newBufKV = concatenated([cur, kv], axis: 1) + newBufGate = concatenated([curG, gate], axis: 1) + } else { + newBufKV = kv + newBufGate = gate + } + + if newBufKV.dim(1) == ratio { + // Full window ready + let readyKV = newBufKV + let readyGate = newBufGate + let poolBase = offset - ratio + 1 + bufKV = nil + bufGate = nil + return (readyKV, readyGate, poolBase) + } else { + bufKV = newBufKV + bufGate = newBufGate + return (zeros([B, 0, D1], dtype: kv.dtype), zeros([B, 0, D2], dtype: gate.dtype), 0) + } + } + } + + /// Append newly compressed tokens to the pool and return full pooled array. + func updateAndFetch(_ px: MLXArray) -> MLXArray { + if px.dim(1) == 0 { + return pooled ?? zeros([px.dim(0), 0, px.dim(2)], dtype: px.dtype) + } + if let p = pooled { + pooled = concatenated([p, px], axis: 1) + } else { + pooled = px + } + return pooled! + } + + /// Build a causal validity mask for pooled positions. + /// Returns `[L, P]` bool mask (nil for decode or empty pool). + func makeMask(L: Int, offset: Int) -> MLXArray? { + guard let p = pooled, L > 1 else { return nil } + let P = p.dim(1) + let poolIdx = MLXArray(Int32(0).. [MLXArray] { rotating.innerState() } + + var offset: Int { + get { rotating.offset } + set { rotating.offset = newValue } + } + + var maxSize: Int? { rotating.maxSize } + + func update(keys: MLXArray, values: MLXArray) -> (MLXArray, MLXArray) { + rotating.update(keys: keys, values: values) + } + + var state: [MLXArray] { + get { rotating.state } + set { rotating.state = newValue } + } + + var metaState: [String] { + get { rotating.metaState } + set { rotating.metaState = newValue } + } + + var isTrimmable: Bool { rotating.isTrimmable } + + @discardableResult + func trim(_ n: Int) -> Int { rotating.trim(n) } + + func copy() -> any KVCache { + DeepseekV4LayerCache(rotating: rotating.copy() as! RotatingKVCache, pooling: pooling) + } + + func makeMask( + n: Int, windowSize: Int?, returnArray: Bool + ) -> MLXFast.ScaledDotProductAttentionMaskMode { + rotating.makeMask(n: n, windowSize: windowSize, returnArray: returnArray) + } +} + +// MARK: - DeepseekV4RoPE + +/// Custom RoPE that prepends `nope_pairs` infinite-frequency pairs before the real RoPE dims. +/// Supports `inverse=true` for un-rotating attention outputs. +/// Mirrors Python DeepseekV4RoPE from mlx-lm#1192. +final class DeepseekV4RoPE { + let dims: Int + let freqScale: Int + private let baseFreqs: MLXArray // [dims/2] – base periods + private var cache: [String: MLXArray] = [:] + + init( + dims: Int, + base: Float, + scalingConfig: [String: StringOrNumber]?, + maxPositionEmbeddings: Int, + freqScale: Int = 1 + ) { + self.dims = dims + self.freqScale = freqScale + + // inv_freq[i] = base^(2i/dims) + let exponents = + MLXArray(stride(from: 0, to: dims, by: 2)).asType(.float32) / Float(dims) + var invFreq = MLX.pow(base, exponents) // [dims/2] + + // Yarn / DeepSeek-Yarn scaling + let ropeType: String? + if let cfg = scalingConfig { + if case .string(let s) = cfg["type"] { ropeType = s } + else if case .string(let s) = cfg["rope_type"] { ropeType = s } + else { ropeType = nil } + } else { + ropeType = nil + } + + if ropeType == "yarn" || ropeType == "deepseek_yarn" { + let factor = scalingConfig?["factor"]?.asFloat() ?? 1.0 + let origMaxPos = + (scalingConfig?["original_max_position_embeddings"]?.asInts()?.first) + ?? maxPositionEmbeddings + let betaFast = scalingConfig?["beta_fast"]?.asFloat() ?? 32.0 + let betaSlow = scalingConfig?["beta_slow"]?.asFloat() ?? 1.0 + + func correctionDim(_ numRot: Float) -> Float { + Float(dims) * log(Float(origMaxPos) / (numRot * 2 * .pi)) / (2 * log(base)) + } + + let low = max(Int(floor(correctionDim(betaFast))), 0) + var high = min(Int(ceil(correctionDim(betaSlow))), dims - 1) + if low == high { high += 1 } + + let ramp = + (MLXArray(stride(from: 0, to: dims / 2, by: 1)).asType(.float32) - Float(low)) + / Float(high - low) + let smooth = 1.0 - MLX.clip(ramp, min: MLXArray(Float(0)), max: MLXArray(Float(1))) + invFreq = invFreq / factor * (1.0 - smooth) + invFreq * smooth + } + + // baseFreqs = 1 / inv_freq = periods + self.baseFreqs = MLXArray(1.0) / invFreq + } + + private func freqs(headDim: Int, inverse: Bool) -> MLXArray { + let key = "\(headDim)_\(inverse)" + if let cached = cache[key] { return cached } + + var f = baseFreqs + if freqScale != 1 { + f = f / Float(freqScale) + } + if inverse { + f = -f + } + let nopePairs = (headDim - dims) / 2 + if nopePairs > 0 { + // Infinite frequency → angle = pos / inf = 0 → identity rotation (NOPE) + let infArr = MLXArray(Array(repeating: Float.infinity, count: nopePairs)) + f = concatenated([infArr, f]) + } + cache[key] = f + return f + } + + func callAsFunction(_ x: MLXArray, offset: Int = 0, inverse: Bool = false) -> MLXArray { + let headDim = x.dim(-1) + let f = freqs(headDim: headDim, inverse: inverse) + let actualOffset = freqScale != 1 ? offset / freqScale : offset + return MLXFast.RoPE( + x, + dimensions: headDim, + traditional: true, + base: nil, + scale: 1.0, + offset: actualOffset, + freqs: f) + } +} + +// MARK: - MultiLinear + +/// Grouped linear: o_groups independent projections applied in batch. +/// Weight shape: [groups, out_features, in_features]. +/// Used for wo_a (output gate projection before wo_b). +final class DeepseekV4MultiLinear: Module { + var weight: MLXArray // [groups, out_features, in_features] + + init(inFeatures: Int, outFeatures: Int, groups: Int) { + self.weight = zeros([groups, outFeatures, inFeatures]) + super.init() + } + + func callAsFunction(_ x: MLXArray) -> MLXArray { + // x: [B, groups, L, in_features] + // weight.T (axis 1,2): [groups, in_features, out_features] + return matmul(x, weight.transposed(0, 2, 1)) + } +} + +// MARK: - HCParams + +/// Holds the three learnable tensors for one HyperConnection block. +class HCParams: Module { + var fn: MLXArray + var base: MLXArray + var scale: MLXArray + + init(fn: MLXArray, base: MLXArray, scale: MLXArray) { + self.fn = fn + self.base = base + self.scale = scale + super.init() + } +} + +// MARK: - HC Sinkhorn Collapse Metal Kernel + +/// Fused Sinkhorn-normalisation + HC-collapse Metal kernel. +/// +/// Mirrors `_make_hc_sinkhorn_collapse_kernel` from +/// omlx/patches/deepseek_v4/hyper_connection.py. +/// +/// Layout: one threadgroup per token (B×S rows), 256 threads per group. +/// - SIMD-group 0 (lanes 0–3 active): compute pre / post / comb (Phase 1). +/// - All 256 threads: collapse [HC, D] → [D] with pre weights (Phase 2). +/// +/// Template parameters (all constexpr): +/// T input dtype, U output dtype (both x.dtype) +/// HC hc_mult (4 for DeepSeek-V4) +/// ITERS hc_sinkhorn_iters +/// D hidden_size +/// EPS_INT eps expressed as integer × 1e-9 (avoids float template args) +private let _hcSinkhornCollapseKernel: MLXFast.MLXFastKernel = MLXFast.metalKernel( + name: "hc_sinkhorn_collapse", + inputNames: ["x_in", "mixes", "scale", "base"], + outputNames: ["collapsed", "post", "comb"], + source: """ + uint tid = thread_position_in_threadgroup.x; + uint row = threadgroup_position_in_grid.x; + uint lane = tid % 32; + uint sg = tid / 32; + + constexpr int MIX = (2 + HC) * HC; + constexpr int BASE_OFF = 2 * HC; + constexpr float EPS = EPS_INT * 1e-9f; + + const device float* mix = (const device float*)mixes + row * MIX; + device float* post_out = (device float*)post + row * HC; + device float* comb_out = (device float*)comb + row * HC * HC; + + threadgroup float pre_shared[HC]; + + // ── Phase 1: branchless Sinkhorn on SIMD-group 0 ────────────────────── + // Lanes >= HC multiply by active=0 so they never corrupt sums — + // no divergent branches inside the Sinkhorn loop. + if (sg == 0) { + const float pre_scale = scale[0]; + const float post_scale = scale[1]; + const float comb_scale = scale[2]; + + const float active = (lane < (uint)HC) ? 1.0f : 0.0f; + const uint llane = metal::min(lane, (uint)(HC - 1)); + + float pre_z = mix[llane] * pre_scale + base[llane]; + float post_z = mix[HC + llane] * post_scale + base[HC + llane]; + float pre_v = 1.0f / (1.0f + metal::fast::exp(-pre_z)) + EPS; + float post_v = 2.0f / (1.0f + metal::fast::exp(-post_z)); + + if (lane < (uint)HC) { + pre_shared[lane] = pre_v; + post_out[lane] = post_v; + } + + // comb row: float4 load (HC=4), softmax, Sinkhorn normalisation + float4 v = (*(const device float4*)(mix + BASE_OFF + llane * HC) * comb_scale + + *(const device float4*)(base + BASE_OFF + llane * HC)) * active; + + float row_max = metal::max(metal::max(v.x, v.y), metal::max(v.z, v.w)); + float4 e = metal::fast::exp(v - row_max) * active; + float4 r = e * (1.0f / (e.x + e.y + e.z + e.w + EPS)) + EPS * active; + + // Initial column normalisation via simd_sum (free SIMD shuffle) + float4 col_inv = 1.0f / (float4( + simd_sum(r.x), simd_sum(r.y), simd_sum(r.z), simd_sum(r.w)) + EPS); + r *= col_inv; + + // Sinkhorn iterations: row-norm then col-norm, zero branches + for (int iter = 1; iter < ITERS; ++iter) { + r *= (1.0f / (r.x + r.y + r.z + r.w + EPS)) * active; + col_inv = 1.0f / (float4( + simd_sum(r.x), simd_sum(r.y), simd_sum(r.z), simd_sum(r.w)) + EPS); + r *= col_inv; + } + + if (lane < (uint)HC) { + *(device float4*)(comb_out + lane * HC) = r; + } + } + + threadgroup_barrier(mem_flags::mem_threadgroup); + + // ── Phase 2: vectorised weighted collapse [HC, D] → [D] ────────────── + const float p0 = pre_shared[0]; + const float p1 = pre_shared[1]; + const float p2 = pre_shared[2]; + const float p3 = pre_shared[3]; + + const device T* x_row = (const device T*)x_in + row * (HC * D); + device U* out_row = (device U*)collapsed + row * D; + + using T4 = vec; + using U4 = vec; + const device T4* x_row0 = (const device T4*)(x_row + 0 * D); + const device T4* x_row1 = (const device T4*)(x_row + 1 * D); + const device T4* x_row2 = (const device T4*)(x_row + 2 * D); + const device T4* x_row3 = (const device T4*)(x_row + 3 * D); + device U4* out4 = (device U4*)out_row; + + constexpr uint D4 = (uint)D / 4; + for (uint d4 = tid; d4 < D4; d4 += 256) { + float4 x0 = float4(x_row0[d4]); + float4 x1 = float4(x_row1[d4]); + float4 x2 = float4(x_row2[d4]); + float4 x3 = float4(x_row3[d4]); + out4[d4] = U4(fma(float4(p0), x0, + fma(float4(p1), x1, + fma(float4(p2), x2, float4(p3) * x3)))); + } + + // Scalar tail for D not divisible by 4 + #if (D % 4) != 0 + for (uint d = D4 * 4 + tid; d < (uint)D; d += 256) { + float val = p0 * (float)x_row[0*D + d] + p1 * (float)x_row[1*D + d] + + p2 * (float)x_row[2*D + d] + p3 * (float)x_row[3*D + d]; + out_row[d] = (U)val; + } + #endif + """, + ensureRowContiguous: true +) + +/// Dispatch the fused Sinkhorn-collapse kernel. +/// - Parameters: +/// - x: 4D hidden `[B, S, hc, D]` (model dtype) +/// - mixes: pre-computed projections `[B*S, (2+hc)*hc]` (float32) +/// - scale: `[3]` float32 — pre / post / comb scale factors +/// - base: `[(2+hc)*hc]` float32 — biases +/// - Returns: `(collapsed [B, S, D], post [B, S, HC], comb [B, S, HC, HC])` +private func hcKernel( + x: MLXArray, + mixes: MLXArray, + scale: MLXArray, + base: MLXArray, + hcMult: Int, + sinkhornIters: Int, + eps: Float +) -> (MLXArray, MLXArray, MLXArray) { + let B = x.dim(0), S = x.dim(1), hc = x.dim(2), D = x.dim(3) + let BL = B * S + let epsInt = max(1, Int((eps / 1e-9).rounded())) + let dtype = x.dtype + + let outputs = _hcSinkhornCollapseKernel( + [x, mixes, scale, base], + template: [ + ("T", dtype), + ("U", dtype), + ("HC", hcMult), + ("ITERS", sinkhornIters), + ("D", D), + ("EPS_INT", epsInt), + ], + grid: (BL * 256, 1, 1), + threadGroup: (256, 1, 1), + outputShapes: [[BL, D], [BL, hc], [BL, hc, hc]], + outputDTypes: [dtype, .float32, .float32] + ) + + return ( + outputs[0].reshaped([B, S, D]), + outputs[1].reshaped([B, S, hc]), + outputs[2].reshaped([B, S, hc, hc]) + ) +} + +// MARK: - HyperConnection helpers + +/// Compute the three gating matrices (pre, post, comb) from the 4D hidden state. +/// Corrected from Python hyper_connection.py: +/// post = 2 * sigmoid(...) (no eps, factor of 2) +/// comb = softmax(...) + eps (not sigmoid) +private func hcSplitSinkhorn( + _ mixes: MLXArray, + hcScale: MLXArray, + hcBase: MLXArray, + hcMult: Int, + sinkhornIters: Int, + eps: Float +) -> (MLXArray, MLXArray, MLXArray) { + let hc = hcMult + let B = mixes.dim(0), S = mixes.dim(1) + + let preMix = mixes[.ellipsis, .. (MLXArray, MLXArray, MLXArray) { + let dtype = x.dtype + let B = x.dim(0), S = x.dim(1), hc = x.dim(2), D = x.dim(3) + + let xFlat = x.reshaped([B, S, hc * D]).asType(.float32) + let normScale = rsqrt(xFlat.square().mean(axis: -1, keepDims: true) + eps) + let mixes = matmul(xFlat, hcFn.T) * normScale // [B, S, (2+hc)*hc] + + // Fused Metal kernel: Sinkhorn + collapse in one dispatch + if Device.defaultDevice().deviceType == .gpu { + return hcKernel( + x: x, + mixes: mixes.reshaped([B * S, mixes.dim(2)]), + scale: hcScale.asType(.float32), + base: hcBase.asType(.float32), + hcMult: hcMult, sinkhornIters: sinkhornIters, eps: eps) + } + + // Pure-ops fallback (CPU / non-Metal) + let (pre, post, comb) = hcSplitSinkhorn( + mixes, hcScale: hcScale, hcBase: hcBase, + hcMult: hcMult, sinkhornIters: sinkhornIters, eps: eps) + let y = (pre.expandedDimensions(axis: -1).asType(dtype) * x).sum(axis: -2) + return (y, post, comb) +} + +/// HC post-sublayer: expand [B, S, D] back to [B, S, hc, D]. +/// term1 = post[..., None] * x[:, :, None, :] +/// term2 = comb.swapaxes(-1,-2) @ residual (equiv to expand-multiply-sum trick) +func hcPost( + x: MLXArray, + residual: MLXArray, + post: MLXArray, + comb: MLXArray +) -> MLXArray { + let term1 = post.expandedDimensions(axis: -1) * x.expandedDimensions(axis: -2) + // term2: comb.swapaxes(-1,-2) @ residual + // comb: [B, S, hc, hc], residual: [B, S, hc, D] + // Using expand trick: combExp [B,S,hc,hc,1] * residualExp [B,S,hc,1,D] → sum axis 2 + let combExp = comb.expandedDimensions(axis: -1) + let residualExp = residual.expandedDimensions(axis: -2) + let term2 = (combExp * residualExp).sum(axis: 2) + return (term1.asType(.float32) + term2.asType(.float32)).asType(x.dtype) +} + +/// HC head: collapse 4D [B, S, hc, D] → [B, S, D] using HyperHead weights. +func hcHeadReduce( + x: MLXArray, + hcFn: MLXArray, + hcScale: MLXArray, + hcBase: MLXArray, + eps: Float +) -> MLXArray { + let dtype = x.dtype + let B = x.dim(0), S = x.dim(1), hc = x.dim(2), D = x.dim(3) + + let xFlat = x.reshaped([B, S, hc * D]).asType(.float32) + let normScale = rsqrt(xFlat.square().mean(axis: -1, keepDims: true) + eps) + let mixes = matmul(xFlat, hcFn.T) * normScale + let pre = sigmoid(mixes * hcScale + hcBase) + eps + + return (pre.expandedDimensions(axis: -1).asType(dtype) * x).sum(axis: -2).asType(dtype) +} + +// MARK: - Helpers + +private func sqrtSoftplus(_ x: MLXArray) -> MLXArray { + let sp = MLX.maximum(x, MLXArray(Float(0))) + MLX.log1p(MLX.exp(-MLX.abs(x))) + return MLX.sqrt(sp) +} + +private func headRmsNorm(_ x: MLXArray, eps: Float) -> MLXArray { + x * rsqrt(x.square().mean(axis: -1, keepDims: true) + eps) +} + +/// Extend an attention mask to cover pooled KV positions. +/// If mask is .none (decode mode), returns .none unchanged. +private func extendMask( + _ mask: MLXFast.ScaledDotProductAttentionMaskMode, + poolMask: MLXArray?, + L: Int, + P: Int +) -> MLXFast.ScaledDotProductAttentionMaskMode { + guard case .array(let localArr) = mask, P > 0 else { return mask } + let poolCols: MLXArray + if let pm = poolMask { + poolCols = pm.asType(.bool) // [L, P] + } else { + poolCols = MLXArray.ones([L, P], dtype: .bool) + } + return .array(concatenated([localArr, poolCols], axis: -1)) +} + +// MARK: - Compressor + +/// Compresses windows of `ratio` tokens into a single pooled KV. +/// Used by CompressedAttention (ratio=128) and SparseCompressedAttention/Indexer (ratio=4). +final class Compressor: Module { + let compressRatio: Int + let headDim: Int + let overlap: Bool // true when ratio=4 + let outDim: Int + + var wkv: Linear + var wgate: Linear + var ape: MLXArray // [ratio, out_dim] – positional encoding for windows + var norm: RMSNorm + let rope: DeepseekV4RoPE // non-Module: computed from hyperparams + + init(config: DeepseekV4Configuration, compressRatio: Int, headDim: Int) { + self.compressRatio = compressRatio + self.headDim = headDim + self.overlap = compressRatio == 4 + self.outDim = headDim * (overlap ? 2 : 1) + + self.wkv = Linear(config.hiddenSize, outDim, bias: false) + self.wgate = Linear(config.hiddenSize, outDim, bias: false) + self.ape = zeros([compressRatio, outDim]) + self.norm = RMSNorm(dimensions: headDim, eps: config.rmsNormEps) + self.rope = DeepseekV4RoPE( + dims: config.qkRopeHeadDim, + base: config.compressRopeTheta, + scalingConfig: config.ropeScaling, + maxPositionEmbeddings: config.maxPositionEmbeddings, + freqScale: compressRatio) + + super.init() + } + + func callAsFunction(_ x: MLXArray, poolCache: PoolingCache?, offset: Int) -> MLXArray { + let B = x.dim(0), D = x.dim(2) + let kv = wkv(x) // [B, S, out_dim] + let gate = wgate(x) // [B, S, out_dim] + + let readyKV: MLXArray + let readyGate: MLXArray + let poolBase: Int + + if let pc = poolCache { + (readyKV, readyGate, poolBase) = pc.accumulateWindows(kv: kv, gate: gate, offset: offset) + } else { + let usable = (kv.dim(1) / compressRatio) * compressRatio + readyKV = kv[0..., .. MLXArray { + // kv: [B, nWindows, ratio, out_dim=headDim] + // weights over ratio dim + let weights = softmax(gate.asType(.float32) + ape, axis: -2) + return (kv * weights.asType(kv.dtype)).sum(axis: -2) // [B, nWindows, headDim] + } + + private func overlapCompressKV(_ kv: MLXArray, _ gate: MLXArray) -> MLXArray { + // kv: [B, nWindows, ratio, out_dim=headDim*2] + let B = kv.dim(0), L = kv.dim(1), R = kv.dim(2) + let D = kv.dim(3) + let g = gate + ape.asType(gate.dtype) + + // Split along last dim: first half = prev-window tokens, second half = current + let kvParts = split(kv, indices: [D / 2], axis: -1) // [B,L,R,D/2], [B,L,R,D/2] + var kvA = kvParts[0] + let kvB = kvParts[1] + let gParts = split(g, indices: [D / 2], axis: -1) + var gA = gParts[0] + let gB = gParts[1] + + // Shift kvA by 1 window (prev window's first half) + let kv0 = zeros([B, 1, R, D / 2], dtype: kv.dtype) + kvA = concatenated([kv0, kvA[0..., ..<(L - 1), 0..., 0...]], axis: 1) + let g0 = full([B, 1, R, D / 2], values: MLXArray(-Float.infinity), dtype: gate.dtype) + gA = concatenated([g0, gA[0..., ..<(L - 1), 0..., 0...]], axis: 1) + + // Combine: [B, L, 2R, D/2] + let kvCombined = concatenated([kvA, kvB], axis: 2) + let gCombined = concatenated([gA, gB], axis: 2) + + let weights = softmax(gCombined.asType(.float32), axis: -2) + return (kvCombined * weights.asType(kv.dtype)).sum(axis: -2) // [B, L, D/2] = [B, L, headDim] + } +} + +// MARK: - Indexer + +/// Builds a sparse top-k index over pooled KV positions for SparseCompressedAttention. +final class Indexer: Module { + let nHeads: Int + let headDim: Int + let indexTopk: Int + let scale: Float + + var wq_b: Linear + var weights_proj: Linear + var compressor: Compressor + + init(config: DeepseekV4Configuration, compressRatio: Int) { + self.nHeads = config.indexNHeads + self.headDim = config.indexHeadDim + self.indexTopk = config.indexTopk + self.scale = pow(Float(config.indexHeadDim), -0.5) + + self.wq_b = Linear(config.qLoraRank, nHeads * headDim, bias: false) + self.weights_proj = Linear(config.hiddenSize, nHeads, bias: false) + self.compressor = Compressor(config: config, compressRatio: compressRatio, headDim: headDim) + + super.init() + } + + /// Returns top-k indices [B, L, k] into the pooled KV, or nil if pool is empty. + func callAsFunction( + _ x: MLXArray, + qResidual: MLXArray, + rope: DeepseekV4RoPE, + poolCache: PoolingCache?, + offset: Int + ) -> MLXArray? { + let B = x.dim(0), L = x.dim(1) + let pooled = compressor(x, poolCache: poolCache, offset: offset) + guard pooled.dim(1) > 0 else { return nil } + let P = pooled.dim(1) + + var q = wq_b(qResidual).reshaped([B, L, nHeads, headDim]) + q = q.transposed(0, 2, 1, 3) // [B, nHeads, L, headDim] + q = rope.callAsFunction(q, offset: offset) + + // scores: [B, nHeads, L, P] + let scores = q.asType(.float32) + .matmul(pooled[0..., .newAxis, 0..., 0...].transposed(0, 1, 3, 2).asType(.float32)) + let posScores = MLX.maximum(scores, MLXArray(Float(0))) * scale + + // Head weights: [B, L, nHeads] + let w = weights_proj(x).asType(.float32) * pow(Float(nHeads), -0.5) + // Combine heads: [B, L, P] + let combined = (posScores * w.transposed(0, 2, 1).expandedDimensions(axis: -1)) + .sum(axis: 1) + + // Apply causal pool mask if in prefill + var maskedScores = combined + if let pc = poolCache, let pm = pc.makeMask(L: L, offset: offset) { + maskedScores = MLX.where(pm[0..., 0...].expandedDimensions(axis: 0), combined, + MLXArray(Float(-Float.infinity))) + } + + let k = min(indexTopk, P) + return argPartition(-maskedScores, kth: k - 1, axis: -1)[0..., 0..., .. (MLXArray, MLXArray) { + let logits = x.matmul(weight.T).asType(.float32) + + let scores: MLXArray + switch scoringFunc { + case "softmax": scores = softmax(logits, axis: -1) + case "sigmoid": scores = sigmoid(logits) + default: scores = sqrtSoftplus(logits) + } + + let inds: MLXArray + let selectedScores: MLXArray + + if isHash, let ids = inputIds, let t2e = tid2eid { + // Hash routing: expert IDs determined by token ID + inds = t2e[ids] // [B, S, topK] + selectedScores = takeAlong(scores, inds, axis: -1) + } else { + let bias = e_score_correction_bias ?? zeros([weight.dim(0)]) + let scoresForChoice = scores + bias + inds = argPartition(-scoresForChoice, kth: topK - 1, axis: -1)[.ellipsis, .. MLXArray { + var g = gate_proj(x) + var u = up_proj(x) + if swiguLimit > 0 { + g = MLX.minimum(g, MLXArray(swiguLimit)) + u = clip(u, min: MLXArray(-swiguLimit), max: MLXArray(swiguLimit)) + } + return down_proj(silu(g) * u) + } +} + +// MARK: - DeepseekV4MoE + +class DeepseekV4MoE: Module { + let numExpertsPerTok: Int + let swiguLimit: Float + + var gate: DeepseekV4Gate + @ModuleInfo(key: "switch_mlp") var switchMLP: SwitchGLU + @ModuleInfo(key: "shared_experts") var sharedExperts: DeepseekV4MLP + + init(config: DeepseekV4Configuration, layerIdx: Int) { + self.numExpertsPerTok = config.numExpertsPerTok + self.swiguLimit = config.swiguLimit + self.gate = DeepseekV4Gate(config: config, layerIdx: layerIdx) + let limit = config.swiguLimit + self._switchMLP.wrappedValue = SwitchGLU( + inputDims: config.hiddenSize, + hiddenDims: config.moeIntermediateSize, + numExperts: config.nRoutedExperts, + activation: { x in limit > 0 ? silu(clip(x, min: -limit, max: limit)) : silu(x) }) + self._sharedExperts.wrappedValue = DeepseekV4MLP( + hiddenSize: config.hiddenSize, + intermediateSize: config.moeIntermediateSize * config.nSharedExperts, + swiguLimit: config.swiguLimit) + super.init() + } + + func callAsFunction(_ x: MLXArray, inputIds: MLXArray) -> MLXArray { + let (indices, scores) = gate(x, inputIds: inputIds) + var y = switchMLP(x, indices) + y = (y * scores[.ellipsis, .newAxis].asType(y.dtype)).sum(axis: -2) + return y + sharedExperts(x) + } +} + +// MARK: - Attention output projection helper + +private func applyOutputProjection( + _ out: MLXArray, + woA: DeepseekV4MultiLinear, + woB: Linear, + oGroups: Int, + oLoraRank: Int, + numHeads: Int, + headDim: Int +) -> MLXArray { + // out: [B, numHeads, L, headDim] + let B = out.dim(0), L = out.dim(2) + let nHeadsPerGroup = numHeads / oGroups + let groupFeat = nHeadsPerGroup * headDim + + let r = out + .reshaped([B, oGroups, nHeadsPerGroup, L, headDim]) // [B, oG, nHpG, L, hD] + .transposed(0, 1, 3, 2, 4) // [B, oG, L, nHpG, hD] + .reshaped([B, oGroups, L, groupFeat]) // [B, oG, L, groupFeat] + let lora = woA(r) // [B, oG, L, oLoraRank] + return woB( + lora + .transposed(0, 2, 1, 3) // [B, L, oG, oLoraRank] + .reshaped([B, L, oGroups * oLoraRank])) // [B, L, oG*oLoraRank] +} + +// MARK: - LocalAttention + +/// Attention with no KV compression (compress_ratio=0). +/// Uses ropeTheta=10000. +final class LocalAttention: Module { + let numHeads: Int + let headDim: Int + let oGroups: Int + let oLoraRank: Int + let scale: Float + let eps: Float + + let rope: DeepseekV4RoPE // non-Module + + var wq_a: Linear + @ModuleInfo(key: "q_norm") var qNorm: RMSNorm + var wq_b: Linear + var wkv: Linear + @ModuleInfo(key: "kv_norm") var kvNorm: RMSNorm + var wo_a: DeepseekV4MultiLinear + var wo_b: Linear + var attn_sink: MLXArray + + init(config: DeepseekV4Configuration, layerIdx: Int) { + self.numHeads = config.numAttentionHeads + self.headDim = config.headDim + self.oGroups = config.oGroups + self.oLoraRank = config.oLoraRank + self.scale = pow(Float(config.headDim), -0.5) + self.eps = config.rmsNormEps + + self.wq_a = Linear(config.hiddenSize, config.qLoraRank, bias: false) + self._qNorm.wrappedValue = RMSNorm(dimensions: config.qLoraRank, eps: config.rmsNormEps) + self.wq_b = Linear(config.qLoraRank, config.numAttentionHeads * config.headDim, bias: false) + self.wkv = Linear(config.hiddenSize, config.headDim, bias: false) + self._kvNorm.wrappedValue = RMSNorm(dimensions: config.headDim, eps: config.rmsNormEps) + self.wo_a = DeepseekV4MultiLinear( + inFeatures: config.numAttentionHeads * config.headDim / config.oGroups, + outFeatures: config.oLoraRank, + groups: config.oGroups) + self.wo_b = Linear(config.oGroups * config.oLoraRank, config.hiddenSize, bias: false) + self.attn_sink = zeros([config.numAttentionHeads]) + + // Local attention uses base rope_theta (not compress_rope_theta) + self.rope = DeepseekV4RoPE( + dims: config.qkRopeHeadDim, + base: config.ropeTheta, + scalingConfig: nil, + maxPositionEmbeddings: config.maxPositionEmbeddings) + + super.init() + } + + func callAsFunction( + _ x: MLXArray, + mask: MLXFast.ScaledDotProductAttentionMaskMode, + cache: (any KVCache)? + ) -> MLXArray { + let B = x.dim(0), L = x.dim(1) + let offset = cache?.offset ?? 0 + + var q = wq_b(qNorm(wq_a(x))) + q = q.reshaped([B, L, numHeads, headDim]) + q = headRmsNorm(q, eps: eps) + q = q.transposed(0, 2, 1, 3) // [B, numHeads, L, headDim] + q = rope.callAsFunction(q, offset: offset) + + var kv = kvNorm(wkv(x)).reshaped([B, 1, L, headDim]) + kv = rope.callAsFunction(kv, offset: offset) + if let c = cache { + let (cached, _) = c.update(keys: kv, values: kv) + kv = cached + } + + let sinks: MLXArray? = attn_sink.sum().item(Float.self) != 0 + ? attn_sink.asType(q.dtype) : nil + var out = MLXFast.scaledDotProductAttention( + queries: q, keys: kv, values: kv, + scale: scale, mask: mask, sinks: sinks) // [B, numHeads, L, headDim] + + out = rope.callAsFunction(out, offset: offset, inverse: true) + + return applyOutputProjection(out, woA: wo_a, woB: wo_b, + oGroups: oGroups, oLoraRank: oLoraRank, numHeads: numHeads, headDim: headDim) + } +} + +// MARK: - CompressedAttention + +/// Attention with pooled KV compression (compress_ratio=128). +/// Uses compressRopeTheta=160000 with Yarn scaling. +final class CompressedAttention: Module { + let numHeads: Int + let headDim: Int + let oGroups: Int + let oLoraRank: Int + let scale: Float + let eps: Float + + let rope: DeepseekV4RoPE + var compressor: Compressor + + var wq_a: Linear + @ModuleInfo(key: "q_norm") var qNorm: RMSNorm + var wq_b: Linear + var wkv: Linear + @ModuleInfo(key: "kv_norm") var kvNorm: RMSNorm + var wo_a: DeepseekV4MultiLinear + var wo_b: Linear + var attn_sink: MLXArray + + init(config: DeepseekV4Configuration, layerIdx: Int) { + self.numHeads = config.numAttentionHeads + self.headDim = config.headDim + self.oGroups = config.oGroups + self.oLoraRank = config.oLoraRank + self.scale = pow(Float(config.headDim), -0.5) + self.eps = config.rmsNormEps + + self.wq_a = Linear(config.hiddenSize, config.qLoraRank, bias: false) + self._qNorm.wrappedValue = RMSNorm(dimensions: config.qLoraRank, eps: config.rmsNormEps) + self.wq_b = Linear(config.qLoraRank, config.numAttentionHeads * config.headDim, bias: false) + self.wkv = Linear(config.hiddenSize, config.headDim, bias: false) + self._kvNorm.wrappedValue = RMSNorm(dimensions: config.headDim, eps: config.rmsNormEps) + self.wo_a = DeepseekV4MultiLinear( + inFeatures: config.numAttentionHeads * config.headDim / config.oGroups, + outFeatures: config.oLoraRank, + groups: config.oGroups) + self.wo_b = Linear(config.oGroups * config.oLoraRank, config.hiddenSize, bias: false) + self.attn_sink = zeros([config.numAttentionHeads]) + + self.rope = DeepseekV4RoPE( + dims: config.qkRopeHeadDim, + base: config.compressRopeTheta, + scalingConfig: config.ropeScaling, + maxPositionEmbeddings: config.maxPositionEmbeddings) + self.compressor = Compressor( + config: config, + compressRatio: config.compressRatios[layerIdx], + headDim: config.headDim) + + super.init() + } + + func callAsFunction( + _ x: MLXArray, + mask: MLXFast.ScaledDotProductAttentionMaskMode, + cache: (any KVCache)? + ) -> MLXArray { + let B = x.dim(0), L = x.dim(1) + let layerCache = cache as? DeepseekV4LayerCache + let localCache = layerCache?.rotating + let poolCache = layerCache?.pooling.first + let offset = localCache?.offset ?? 0 + + var q = wq_b(qNorm(wq_a(x))) + q = q.reshaped([B, L, numHeads, headDim]) + q = headRmsNorm(q, eps: eps) + q = q.transposed(0, 2, 1, 3) + q = rope.callAsFunction(q, offset: offset) + + var kv = kvNorm(wkv(x)).reshaped([B, 1, L, headDim]) + kv = rope.callAsFunction(kv, offset: offset) + if let lc = localCache { + let (cached, _) = lc.update(keys: kv, values: kv) + kv = cached + } + + // Pooled KV from Compressor + let pooled = compressor(x, poolCache: poolCache, offset: offset) // [B, P, headDim] + var effectiveMask = mask + let P = pooled.dim(1) + if P > 0 { + let poolMask = poolCache?.makeMask(L: L, offset: offset) + let fullKV = concatenated([kv, pooled.expandedDimensions(axis: 1)], axis: 2) + effectiveMask = extendMask(mask, poolMask: poolMask, L: L, P: P) + + let sinks: MLXArray? = attn_sink.sum().item(Float.self) != 0 + ? attn_sink.asType(q.dtype) : nil + var out = MLXFast.scaledDotProductAttention( + queries: q, keys: fullKV, values: fullKV, + scale: scale, mask: effectiveMask, sinks: sinks) + out = rope.callAsFunction(out, offset: offset, inverse: true) + return applyOutputProjection(out, woA: wo_a, woB: wo_b, + oGroups: oGroups, oLoraRank: oLoraRank, numHeads: numHeads, headDim: headDim) + } + + let sinks: MLXArray? = attn_sink.sum().item(Float.self) != 0 + ? attn_sink.asType(q.dtype) : nil + var out = MLXFast.scaledDotProductAttention( + queries: q, keys: kv, values: kv, + scale: scale, mask: mask, sinks: sinks) + out = rope.callAsFunction(out, offset: offset, inverse: true) + return applyOutputProjection(out, woA: wo_a, woB: wo_b, + oGroups: oGroups, oLoraRank: oLoraRank, numHeads: numHeads, headDim: headDim) + } +} + +// MARK: - SparseCompressedAttention + +/// Attention with sparse indexed pooled KV (compress_ratio=4). +final class SparseCompressedAttention: Module { + let numHeads: Int + let headDim: Int + let oGroups: Int + let oLoraRank: Int + let scale: Float + let eps: Float + + let rope: DeepseekV4RoPE + var compressor: Compressor + var indexer: Indexer + + var wq_a: Linear + @ModuleInfo(key: "q_norm") var qNorm: RMSNorm + var wq_b: Linear + var wkv: Linear + @ModuleInfo(key: "kv_norm") var kvNorm: RMSNorm + var wo_a: DeepseekV4MultiLinear + var wo_b: Linear + var attn_sink: MLXArray + + init(config: DeepseekV4Configuration, layerIdx: Int) { + self.numHeads = config.numAttentionHeads + self.headDim = config.headDim + self.oGroups = config.oGroups + self.oLoraRank = config.oLoraRank + self.scale = pow(Float(config.headDim), -0.5) + self.eps = config.rmsNormEps + + self.wq_a = Linear(config.hiddenSize, config.qLoraRank, bias: false) + self._qNorm.wrappedValue = RMSNorm(dimensions: config.qLoraRank, eps: config.rmsNormEps) + self.wq_b = Linear(config.qLoraRank, config.numAttentionHeads * config.headDim, bias: false) + self.wkv = Linear(config.hiddenSize, config.headDim, bias: false) + self._kvNorm.wrappedValue = RMSNorm(dimensions: config.headDim, eps: config.rmsNormEps) + self.wo_a = DeepseekV4MultiLinear( + inFeatures: config.numAttentionHeads * config.headDim / config.oGroups, + outFeatures: config.oLoraRank, + groups: config.oGroups) + self.wo_b = Linear(config.oGroups * config.oLoraRank, config.hiddenSize, bias: false) + self.attn_sink = zeros([config.numAttentionHeads]) + + self.rope = DeepseekV4RoPE( + dims: config.qkRopeHeadDim, + base: config.compressRopeTheta, + scalingConfig: config.ropeScaling, + maxPositionEmbeddings: config.maxPositionEmbeddings) + let compressRatio = config.compressRatios[layerIdx] + self.compressor = Compressor(config: config, compressRatio: compressRatio, headDim: config.headDim) + self.indexer = Indexer(config: config, compressRatio: compressRatio) + + super.init() + } + + func callAsFunction( + _ x: MLXArray, + mask: MLXFast.ScaledDotProductAttentionMaskMode, + cache: (any KVCache)? + ) -> MLXArray { + let B = x.dim(0), L = x.dim(1) + let layerCache = cache as? DeepseekV4LayerCache + let localCache = layerCache?.rotating + let compCache = layerCache?.pooling.first + let idxCache = layerCache?.pooling.count ?? 0 > 1 ? layerCache?.pooling[1] : nil + let offset = localCache?.offset ?? 0 + + let qResidual = qNorm(wq_a(x)) + var q = wq_b(qResidual).reshaped([B, L, numHeads, headDim]) + q = headRmsNorm(q, eps: eps) + q = q.transposed(0, 2, 1, 3) + q = rope.callAsFunction(q, offset: offset) + + var kv = kvNorm(wkv(x)).reshaped([B, 1, L, headDim]) + kv = rope.callAsFunction(kv, offset: offset) + if let lc = localCache { + let (cached, _) = lc.update(keys: kv, values: kv) + kv = cached + } + + let pooled = compressor(x, poolCache: compCache, offset: offset) + let pmask = compCache?.makeMask(L: L, offset: offset) + let topk = indexer(x, qResidual: qResidual, rope: rope, poolCache: idxCache, offset: offset) + let sinks: MLXArray? = attn_sink.sum().item(Float.self) != 0 + ? attn_sink.asType(q.dtype) : nil + let P = pooled.dim(1) + let indexTopk = indexer.indexTopk + + let out: MLXArray + if P == 0 { + // No pooled KV yet – pure local attention + out = MLXFast.scaledDotProductAttention( + queries: q, keys: kv, values: kv, + scale: scale, mask: mask, sinks: sinks) + } else if P <= indexTopk { + // Pool fits in topk – full attention with all pooled + let fullKV = concatenated([kv, pooled.expandedDimensions(axis: 1)], axis: 2) + let extMask = extendMask(mask, poolMask: pmask, L: L, P: P) + out = MLXFast.scaledDotProductAttention( + queries: q, keys: fullKV, values: fullKV, + scale: scale, mask: extMask, sinks: sinks) + } else if let tk = topk { + // Sparse: gather top-k pooled vectors and attend + out = sparsePooledAttention( + q: q, localKV: kv, pooled: pooled, topk: tk, + localMask: mask, pooledMask: pmask, sinks: sinks) + } else { + // Indexer returned nil (shouldn't happen if P > 0 and indexer returns) + out = MLXFast.scaledDotProductAttention( + queries: q, keys: kv, values: kv, + scale: scale, mask: mask, sinks: sinks) + } + + let result = rope.callAsFunction(out, offset: offset, inverse: true) + return applyOutputProjection(result, woA: wo_a, woB: wo_b, + oGroups: oGroups, oLoraRank: oLoraRank, numHeads: numHeads, headDim: headDim) + } + + /// Sparse pooled attention: gather top-k pooled KVs, combine with local in log-space. + private func sparsePooledAttention( + q: MLXArray, + localKV: MLXArray, + pooled: MLXArray, + topk: MLXArray, // [B, L, k] + localMask: MLXFast.ScaledDotProductAttentionMaskMode, + pooledMask: MLXArray?, + sinks: MLXArray? + ) -> MLXArray { + let B = q.dim(0), L = q.dim(2), D = q.dim(3) + let k = topk.dim(2) + + // Gather top-k pooled vectors: [B, L, k, D] + let flatTopk = topk.reshaped([B, L * k]) // [B, L*k] + let expandedIdx = flatTopk.expandedDimensions(axis: -1) // [B, L*k, 1] + let tiledIdx = expandedIdx + zeros([B, L * k, D], dtype: .int32) // [B, L*k, D] + let gathered = takeAlong(pooled, tiledIdx, axis: 1) // [B, L*k, D] + let pooledTopk = gathered.reshaped([B, L, k, D]) // [B, L, k, D] + + let qScaled = q * scale + + // Local scores: [B, H, L, localLen] + let localScores: MLXArray + switch localMask { + case .none, .causal: + localScores = qScaled.matmul(localKV.transposed(0, 1, 3, 2)) + case .array(let arr): + let raw = qScaled.matmul(localKV.transposed(0, 1, 3, 2)) + let arrExpanded = arr.expandedDimensions(axis: 0).expandedDimensions(axis: 1) + localScores = MLX.where(arrExpanded, raw, MLXArray(Float(-Float.infinity))) + @unknown default: + localScores = qScaled.matmul(localKV.transposed(0, 1, 3, 2)) + } + + let maxLocal = localScores.max(axis: -1, keepDims: true) + var logNorm = maxLocal + MLX.log( + MLX.exp(localScores - maxLocal).sum(axis: -1, keepDims: true) + 1e-20) + + // Pooled scores: [B, H, L, k] + let qBL = qScaled.transposed(0, 2, 1, 3) // [B, L, H, D] + var pooledScores = qBL.matmul(pooledTopk.transposed(0, 1, 3, 2)) // [B, L, H, k] + pooledScores = pooledScores.transposed(0, 2, 1, 3) // [B, H, L, k] + + // Apply sparse pool mask + if let pm = pooledMask { + // topk: [B, L, k], pm: [L, P] or [B, L, P] + let pmExpanded = pm.ndim == 2 ? pm.expandedDimensions(axis: 0) : pm + let sparsePM = takeAlong(pmExpanded, topk, axis: -1) // [B, L, k] + pooledScores = MLX.where( + sparsePM[0..., .newAxis, 0..., 0...], + pooledScores, + MLXArray(Float(-Float.infinity))) + } + + let maxPooled = pooledScores.max(axis: -1, keepDims: true) + let logNormPooled = maxPooled + MLX.log( + MLX.exp(pooledScores - maxPooled).sum(axis: -1, keepDims: true) + 1e-20) + logNorm = logNorm + MLX.log1p(MLX.exp(logNormPooled - logNorm)) + + if let s = sinks { + logNorm = logNorm + MLX.log1p(MLX.exp(s[.newAxis, 0..., .newAxis, .newAxis] - logNorm)) + } + + let localWeights = MLX.exp(localScores - logNorm) + let pooledWeights = MLX.exp(pooledScores - logNorm) + + let outLocal = localWeights.matmul(localKV) // [B, H, L, D] + let pwBL = pooledWeights.transposed(0, 2, 1, 3) // [B, L, H, k] + let outPooled = pwBL.matmul(pooledTopk).transposed(0, 2, 1, 3) // [B, H, L, D] + return (outLocal + outPooled).asType(q.dtype) + } +} + +// MARK: - Attention factory + +private func v4AttentionFactory(config: DeepseekV4Configuration, layerIdx: Int) -> Module { + let ratio = layerIdx < config.compressRatios.count ? config.compressRatios[layerIdx] : 0 + if ratio == 0 { return LocalAttention(config: config, layerIdx: layerIdx) } + if ratio == 128 { return CompressedAttention(config: config, layerIdx: layerIdx) } + return SparseCompressedAttention(config: config, layerIdx: layerIdx) +} + +// MARK: - Decoder Block + +class DeepseekV4Block: Module { + let config: DeepseekV4Configuration + + @ModuleInfo(key: "attn") var attn: Module + var ffn: DeepseekV4MoE + @ModuleInfo(key: "attn_norm") var attnNorm: RMSNorm + @ModuleInfo(key: "ffn_norm") var ffnNorm: RMSNorm + + var attn_hc: HCParams // key matches Python attn_hc.fn/base/scale + var ffn_hc: HCParams + + init(config: DeepseekV4Configuration, layerIdx: Int) { + self.config = config + self._attn.wrappedValue = v4AttentionFactory(config: config, layerIdx: layerIdx) + self.ffn = DeepseekV4MoE(config: config, layerIdx: layerIdx) + self._attnNorm.wrappedValue = RMSNorm(dimensions: config.hiddenSize, eps: config.rmsNormEps) + self._ffnNorm.wrappedValue = RMSNorm(dimensions: config.hiddenSize, eps: config.rmsNormEps) + + let hc = config.hcMult + let mixHc = (2 + hc) * hc + let hcDim = hc * config.hiddenSize + self.attn_hc = HCParams(fn: zeros([mixHc, hcDim]), base: zeros([mixHc]), scale: ones([3])) + self.ffn_hc = HCParams(fn: zeros([mixHc, hcDim]), base: zeros([mixHc]), scale: ones([3])) + + super.init() + } + + func callAsFunction( + _ x: MLXArray, + mask: MLXFast.ScaledDotProductAttentionMaskMode, + cache: (any KVCache)?, + inputIds: MLXArray + ) -> MLXArray { + // Attention sub-block + var residual = x + let (xAttn, postAttn, combAttn) = hcPre( + x: residual, hcFn: attn_hc.fn, hcScale: attn_hc.scale, hcBase: attn_hc.base, + hcMult: config.hcMult, sinkhornIters: config.hcSinkhornIters, eps: config.hcEps) + + let attnOut: MLXArray + let normedAttn = attnNorm(xAttn) + if let la = attn as? LocalAttention { + attnOut = la(normedAttn, mask: mask, cache: cache) + } else if let ca = attn as? CompressedAttention { + attnOut = ca(normedAttn, mask: mask, cache: cache) + } else if let sca = attn as? SparseCompressedAttention { + attnOut = sca(normedAttn, mask: mask, cache: cache) + } else { + fatalError("Unknown attention type in DeepseekV4Block") + } + + var h = hcPost(x: attnOut, residual: residual, post: postAttn, comb: combAttn) + + // FFN sub-block + residual = h + let (xFfn, postFfn, combFfn) = hcPre( + x: residual, hcFn: ffn_hc.fn, hcScale: ffn_hc.scale, hcBase: ffn_hc.base, + hcMult: config.hcMult, sinkhornIters: config.hcSinkhornIters, eps: config.hcEps) + let ffnOut = ffn(ffnNorm(xFfn), inputIds: inputIds) + return hcPost(x: ffnOut, residual: residual, post: postFfn, comb: combFfn) + } +} + +// MARK: - Inner Model + +public class DeepseekV4ModelInner: Module { + var config: DeepseekV4Configuration + + @ModuleInfo(key: "embed_tokens") var embedTokens: Embedding + var layers: [DeepseekV4Block] + @ModuleInfo(key: "norm") var norm: RMSNorm + var hc_head: HCParams + + init(config: DeepseekV4Configuration) { + self.config = config + self._embedTokens.wrappedValue = Embedding( + embeddingCount: config.vocabSize, dimensions: config.hiddenSize) + self.layers = (0 ..< config.numHiddenLayers).map { + DeepseekV4Block(config: config, layerIdx: $0) + } + self._norm.wrappedValue = RMSNorm(dimensions: config.hiddenSize, eps: config.rmsNormEps) + + let hc = config.hcMult + self.hc_head = HCParams( + fn: zeros([hc, hc * config.hiddenSize]), + base: zeros([hc]), + scale: ones([1])) + super.init() + } + + func callAsFunction(_ inputIds: MLXArray, cache: [any KVCache]?) -> MLXArray { + let (h, _) = forward(inputIds, cache: cache, returnRawHidden: false) + return h + } + + /// Forward with optional return of the raw 4D hidden state (for MTP). + func forward( + _ inputIds: MLXArray, + cache: [any KVCache]?, + returnRawHidden: Bool + ) -> (MLXArray, MLXArray?) { + let B = inputIds.dim(0), S = inputIds.dim(1) + let hc = config.hcMult + + let emb = embedTokens(inputIds) + var h = repeated(emb.expandedDimensions(axis: 2), count: hc, axis: 2) // [B, S, hc, D] + + // Compute attention mask from first rotating cache + let firstRotatingCache: (any KVCache)? = { + guard let c = cache?.first else { return nil } + return (c as? DeepseekV4LayerCache)?.rotating ?? c + }() + let hForMask = h.reshaped([B, S, hc * config.hiddenSize]) + let maskMode = createAttentionMask( + h: hForMask, + cache: firstRotatingCache, + windowSize: config.slidingWindow, + returnArray: true) + + for (i, layer) in layers.enumerated() { + h = layer(h, mask: maskMode, cache: cache?[i], inputIds: inputIds) + } + + let rawHidden = returnRawHidden ? h : nil + h = hcHeadReduce( + x: h, hcFn: hc_head.fn, hcScale: hc_head.scale, hcBase: hc_head.base, + eps: config.hcEps) + return (norm(h), rawHidden) + } +} + +// MARK: - Top-level Model + +public class DeepseekV4Model: Module, LLMModel, KVCacheDimensionProvider, LoRAModel { + public var kvHeads: [Int] + + var args: DeepseekV4Configuration + public var model: DeepseekV4ModelInner + @ModuleInfo(key: "lm_head") var lmHead: Linear + + /// MTP prediction blocks. Non-nil only when `_deepseekV4MTPEnabled == true` at init time. + var mtp: [DeepseekV4MTPBlock]? + + init(_ args: DeepseekV4Configuration) { + var config = args + config.fillDefaultCompressRatios() + self.args = config + self.kvHeads = Array(repeating: 1, count: config.numHiddenLayers) + self.model = DeepseekV4ModelInner(config: config) + self._lmHead.wrappedValue = Linear(config.hiddenSize, config.vocabSize, bias: false) + + if config.numNextnPredictLayers > 0 && _deepseekV4MTPEnabled { + let n = config.numHiddenLayers + self.mtp = (0 ..< config.numNextnPredictLayers).map { + DeepseekV4MTPBlock(config: config, layerIdx: n + $0) + } + } + super.init() + } + + public func callAsFunction(_ inputs: MLXArray, cache: [any KVCache]? = nil) -> MLXArray { + lmHead(model(inputs, cache: cache)) + } + + public func makeCache(parameters: GenerateParameters) -> [any KVCache] { + args.compressRatios.map { ratio in + if ratio == 0 { + return RotatingKVCache(maxSize: args.slidingWindow) as any KVCache + } else if ratio == 4 { + return DeepseekV4LayerCache( + rotating: RotatingKVCache(maxSize: args.slidingWindow), + pooling: [PoolingCache(ratio: ratio), PoolingCache(ratio: ratio)] + ) as any KVCache + } else { + // ratio == 128 + return DeepseekV4LayerCache( + rotating: RotatingKVCache(maxSize: args.slidingWindow), + pooling: [PoolingCache(ratio: ratio)] + ) as any KVCache + } + } + } + + public func sanitize(weights: [String: MLXArray]) -> [String: MLXArray] { + var w = weights + let hasMTP = mtp != nil + let hasMTPWeights = weights.keys.contains { $0.hasPrefix("mtp.") } + + if hasMTP && !hasMTPWeights { + self.mtp = nil + } + + // FP8 dequantization + func dequant(weight: MLXArray, scaleInv: MLXArray) -> MLXArray { + let bs = 128 + let (m, n) = (weight.dim(0), weight.dim(1)) + let padBottom = (bs - m % bs) % bs + let padSide = (bs - n % bs) % bs + var p = MLX.padded(weight, widths: [.init((0, padBottom)), .init((0, padSide))]) + p = p.reshaped([(m + padBottom) / bs, bs, (n + padSide) / bs, bs]) + let scaled = p * scaleInv[0..., .newAxis, 0..., .newAxis] + return scaled.reshaped([m + padBottom, n + padSide])[0 ..< m, 0 ..< n] + } + for (key, value) in weights { + if key.contains("weight_scale_inv") { + let weightKey = key.replacingOccurrences(of: "_scale_inv", with: "") + if let wt = weights[weightKey] { + w[weightKey] = dequant(weight: wt, scaleInv: value) + } + } else if w[key] == nil { + w[key] = value + } + } + + // Remap keys: hc_attn_fn → attn_hc.fn, w1 → gate_proj, etc. + // Also: ffn.gate.bias → ffn.gate.e_score_correction_bias + // Also: model.embed → model.embed_tokens, etc. + let topRemap: [String: String] = [ + "embed.weight": "model.embed_tokens.weight", + "norm.weight": "model.norm.weight", + "head.weight": "lm_head.weight", + "hc_head_fn": "model.hc_head.fn", + "hc_head_base": "model.hc_head.base", + "hc_head_scale": "model.hc_head.scale", + ] + let wRemap: [String: String] = ["w1": "gate_proj", "w2": "down_proj", "w3": "up_proj"] + + var remapped: [String: MLXArray] = [:] + for (key, value) in w { + var nk = key.hasPrefix("layers.") ? "model." + key : key + // Remap flat hc keys: .hc_attn_fn → .attn_hc.fn + for sub in ["attn", "ffn"] { + for param in ["fn", "base", "scale"] { + nk = nk.replacingOccurrences( + of: ".hc_\(sub)_\(param)", with: ".\(sub)_hc.\(param)") + } + } + // Gate bias rename + nk = nk.replacingOccurrences( + of: ".ffn.gate.bias", with: ".ffn.gate.e_score_correction_bias") + // Shared expert weight name remap + for (old, new) in wRemap { + nk = nk.replacingOccurrences( + of: ".shared_experts.\(old).", with: ".shared_experts.\(new).") + } + // Top-level remap + if let mapped = topRemap[nk] { remapped[mapped] = value } + else { remapped[nk] = value } + } + w = remapped + + // Stack per-expert routed weights → switch_mlp format + for l in 0 ..< args.numHiddenLayers { + let prefix = "model.layers.\(l)" + for (src, dst) in [("w1", "gate_proj"), ("w2", "down_proj"), ("w3", "up_proj")] { + for suffix in ["weight", "scales"] { + let key0 = "\(prefix).ffn.experts.0.\(src).\(suffix)" + if w[key0] != nil { + let stacked = (0 ..< args.nRoutedExperts).compactMap { + w.removeValue(forKey: "\(prefix).ffn.experts.\($0).\(src).\(suffix)") + } + if stacked.count == args.nRoutedExperts { + w["\(prefix).ffn.switch_mlp.\(dst).\(suffix)"] = MLX.stacked(stacked) + } + } + } + } + } + + // Stack MTP expert weights + if hasMTP && hasMTPWeights { + for i in 0 ..< args.numNextnPredictLayers { + let prefix = "mtp.\(i).block.ffn.experts" + for (src, dst) in [("w1", "gate_proj"), ("w2", "down_proj"), ("w3", "up_proj")] { + for suffix in ["weight", "scales"] { + let key0 = "\(prefix).0.\(src).\(suffix)" + if w[key0] != nil { + let stacked = (0 ..< args.nRoutedExperts).compactMap { + w.removeValue(forKey: "\(prefix).\($0).\(src).\(suffix)") + } + if stacked.count == args.nRoutedExperts { + w["mtp.\(i).block.ffn.switch_mlp.\(dst).\(suffix)"] = MLX.stacked(stacked) + } + } + } + } + } + } + + // Reshape wo_a weights from 2D → 3D [o_groups, o_lora_rank, -1] + for l in 0 ..< args.numHiddenLayers { + let prefix = "model.layers.\(l).attn.wo_a" + for key in ["\(prefix).weight", "\(prefix).scales", "\(prefix).biases"] { + if let v = w[key], v.ndim == 2 { + w[key] = v.reshaped([args.oGroups, args.oLoraRank, -1]) + } + } + } + + return w.filter { key, _ in + if key.hasPrefix("mtp.") && !hasMTP { return false } + if key.contains("rotary_emb.inv_freq") { return false } + return true + } + } + + public var loraLayers: [Module] { model.layers } +} diff --git a/Libraries/MLXLLM/Models/DeepseekV4MTP.swift b/Libraries/MLXLLM/Models/DeepseekV4MTP.swift new file mode 100644 index 0000000000..1ca25001d3 --- /dev/null +++ b/Libraries/MLXLLM/Models/DeepseekV4MTP.swift @@ -0,0 +1,177 @@ +// Multi-Token Prediction (MTP) head for DeepSeek-V4. +// +// Port of omlx commit 696d90a: +// patches/mlx_lm_mtp/deepseek_v4_model.py (MTPBlock, mtp_forward, make_mtp_cache) +// Reference: Blaizzy/mlx-lm#15 + +import Foundation +import MLX +import MLXLMCommon +import MLXNN + +// MARK: - Module-level MTP flag + +/// Controls whether DeepSeek-V4 model inits attach the MTP head. +/// Set to `true` before calling `MLXLLM.load(...)` when MTP should be active. +/// Mirrors omlx `is_mtp_active()` / `set_mtp_active()` from +/// patches/mlx_lm_mtp/__init__.py. +public nonisolated(unsafe) var _deepseekV4MTPEnabled: Bool = false + +// MARK: - DeepseekV4MTPBlock + +/// One MTP layer in DeepSeek-V4's prediction stack. +/// +/// Fuses the backbone's 4D pre-hcHead hidden state `h` `[B, S, hc, D]` with the +/// embedding of the next-position token, then runs a full `DeepseekV4Block` over +/// the result. The final block's `hc_head` collapses the HyperConnection dimension +/// before `norm` and the shared `lm_head` produce logits. +/// +/// omlx: patches/mlx_lm_mtp/deepseek_v4_model.py MTPBlock +final class DeepseekV4MTPBlock: Module { + let config: DeepseekV4Configuration + + var block: DeepseekV4Block + + var e_proj: Linear + var h_proj: Linear + var enorm: RMSNorm + var hnorm: RMSNorm + var norm: RMSNorm + + /// HyperHead parameters for collapsing the hc dimension after this block. + var hc_head: HCParams + + init(config: DeepseekV4Configuration, layerIdx: Int) { + self.config = config + self.block = DeepseekV4Block(config: config, layerIdx: layerIdx) + + let dim = config.hiddenSize + self.e_proj = Linear(dim, dim, bias: false) + self.h_proj = Linear(dim, dim, bias: false) + self.enorm = RMSNorm(dimensions: dim, eps: config.rmsNormEps) + self.hnorm = RMSNorm(dimensions: dim, eps: config.rmsNormEps) + self.norm = RMSNorm(dimensions: dim, eps: config.rmsNormEps) + + let hc = config.hcMult + self.hc_head = HCParams( + fn: zeros([hc, hc * dim]), + base: zeros([hc]), + scale: ones([1])) + } + + /// Forward one MTP block. + /// + /// - Parameters: + /// - h: 4D hidden `[B, S, hc, D]` from backbone or previous MTP block + /// - embedTokens: shared embedding table from the backbone model + /// - inputIds: next-token ids `[B, S]` + /// - mask: attention mask (pre-computed for the full MTP chain) + /// - cache: KV cache for this MTP block + /// - Returns: updated 4D hidden `[B, S, hc, D]` + /// + /// omlx: MTPBlock.__call__ + func callAsFunction( + _ h: MLXArray, + embedTokens: Embedding, + inputIds: MLXArray, + mask: MLXFast.ScaledDotProductAttentionMaskMode, + cache: KVCache? + ) -> MLXArray { + // 1. Norm and project the embedding of the next token. + let e = enorm(embedTokens(inputIds)) // [B, S, D] + + // 2. Norm the 4D hidden state (RMSNorm operates on last dim). + let hNorm = hnorm(h) // [B, S, hc, D] + + // 3. Fuse: broadcast projected embedding to [B, S, 1, D] then add. + // h_proj maps [B, S, hc, D] → [B, S, hc, D] (Linear on last dim). + let x = e_proj(e).expandedDimensions(axis: 2) + h_proj(hNorm) // [B, S, hc, D] + + // 4. Run full transformer block (returns 4D hidden). + return block(x, mask: mask, cache: cache, inputIds: inputIds) + } +} + +// MARK: - MTPCapable conformance + +extension DeepseekV4Model: MTPCapable { + public var hasMTPHead: Bool { mtp != nil } + + /// Backbone forward that also returns the raw 4D pre-hcHead hidden state. + /// + /// The raw hidden `[B, S, hc, D]` is passed to `mtpForward` to produce draft logits. + /// `nConfirmed` is unused in this model (no prefix caching in the V4 port). + /// + /// omlx: Model.__call__ with return_hidden=True + public func callWithHidden( + input: LMInput.Text, cache: [any KVCache], nConfirmed: Int + ) -> (MLXArray, MLXArray) { + let cacheArr: [KVCache] = cache.isEmpty ? [] : cache + let (normed, rawHidden) = model.forward( + input.tokens, + cache: cacheArr.isEmpty ? nil : cacheArr, + returnRawHidden: true) + let logits = lmHead(normed) + // rawHidden is non-nil because returnRawHidden=true. + return (logits, rawHidden!) + } + + /// Run the chained MTP blocks and produce draft logits. + /// + /// Each MTP block fuses `hidden` (4D, `[B, S, hc, D]`) with embedded + /// `nextTokenIds` through its `e_proj`/`h_proj` projections, then passes the + /// result through a `DeepseekV4Block`. The final block's `hc_head` collapses + /// the HyperConnection dimension before `norm` and the shared `lm_head`. + /// + /// omlx: Model.mtp_forward + public func mtpForward( + hidden: MLXArray, nextTokenIds: MLXArray, cache: [any KVCache] + ) -> MLXArray { + guard let mtpBlocks = mtp else { + fatalError( + "mtpForward called but MTP head is not attached. " + + "Set _deepseekV4MTPEnabled = true before loading the model.") + } + + var h = hidden // [B, S, hc, D] + + // Build attention mask from the collapsed [B, S, hc*D] representation. + let B = h.dim(0), S = h.dim(1), hc = h.dim(2), D = h.dim(3) + let maskInput = h.reshaped([B, S, hc * D]) + let firstCache: (any KVCache)? = cache.isEmpty ? nil : cache[0] + let mask = createAttentionMask( + h: maskInput, cache: firstCache, + windowSize: args.slidingWindow, returnArray: true) + + var lastBlock: DeepseekV4MTPBlock? + for (i, mtpBlock) in mtpBlocks.enumerated() { + let c: KVCache? = i < cache.count ? cache[i] : nil + h = mtpBlock( + h, + embedTokens: model.embedTokens, + inputIds: nextTokenIds, + mask: mask, + cache: c) + lastBlock = mtpBlock + } + + guard let lb = lastBlock else { fatalError("MTP block list is empty") } + + // Collapse hc dimension with the last block's hc_head, then norm + lm_head. + let out = hcHeadReduce( + x: h, hcFn: lb.hc_head.fn, hcScale: lb.hc_head.scale, + hcBase: lb.hc_head.base, eps: args.hcEps) + return lmHead(lb.norm(out)) + } + + /// Allocate fresh KV caches for the MTP head layers. + /// + /// MTP layers default to `compress_ratio=0` (no PoolingCache), so each block + /// gets a plain `KVCacheSimple`. + /// + /// omlx: Model.make_mtp_cache + public func makeMTPCache() -> [any KVCache] { + guard let mtpBlocks = mtp else { return [] } + return mtpBlocks.map { _ in KVCacheSimple() as any KVCache } + } +} diff --git a/Libraries/MLXLLM/Models/Gemma4.swift b/Libraries/MLXLLM/Models/Gemma4.swift index ea0c1c3db9..b6c43e12ad 100644 --- a/Libraries/MLXLLM/Models/Gemma4.swift +++ b/Libraries/MLXLLM/Models/Gemma4.swift @@ -25,8 +25,14 @@ public struct Gemma4Configuration: Codable, Sendable { case vocabSize = "vocab_size" } + enum QuantizationCodingKeys: String, CodingKey { + case quantization + case quantizationConfig = "quantization_config" + } + public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) + let quantizationContainer = try decoder.container(keyedBy: QuantizationCodingKeys.self) self.modelType = try container.decodeIfPresent(String.self, forKey: .modelType) ?? "gemma4" self.vocabSize = try container.decodeIfPresent(Int.self, forKey: .vocabSize) ?? 262144 @@ -40,6 +46,16 @@ public struct Gemma4Configuration: Codable, Sendable { } else { self.textConfig = try Gemma4TextConfiguration(from: decoder) } + + let quantization = + try quantizationContainer.decodeIfPresent( + Gemma4WeightQuantizationMetadata.self, forKey: .quantization) + ?? quantizationContainer.decodeIfPresent( + Gemma4WeightQuantizationMetadata.self, forKey: .quantizationConfig) + if let quantization { + self.textConfig.quantizationBits = quantization.bits + self.textConfig.quantizationGroupSize = quantization.groupSize + } } } @@ -51,6 +67,10 @@ public class Gemma4Model: Module, LLMModel, KVCacheDimensionProvider { @ModuleInfo(key: "language_model") fileprivate var languageModel: Gemma4TextModel + /// Public accessor for the inner text model (needed by MTP speculative + /// decoding which calls `Gemma4TextModel.forwardForMTP` directly). + public var textModel: Gemma4TextModel { languageModel } + public init(_ config: Gemma4Configuration) { self._languageModel.wrappedValue = Gemma4TextModel(config.textConfig) } diff --git a/Libraries/MLXLLM/Models/Gemma4MTP.swift b/Libraries/MLXLLM/Models/Gemma4MTP.swift new file mode 100644 index 0000000000..0ae931988e --- /dev/null +++ b/Libraries/MLXLLM/Models/Gemma4MTP.swift @@ -0,0 +1,2372 @@ +// Copyright 2026 Apple Inc. + +// Gemma 4 Multi-Token Prediction (MTP) speculative decoding. +// Single-file consolidation of drafter, sampling, round-loop, and token iterator support. + +import Foundation +import MLX +import MLXLMCommon +import MLXNN +import MLXRandom + +// MARK: - Errors + +/// Errors thrown by the Gemma 4 MTP drafter pipeline. +public enum Gemma4MTPError: LocalizedError, Sendable, Equatable { + /// The target passed to `generateGemma4MTP` wasn't a `Gemma4TextModel`. + /// Associated value is the actual type name. + case unsupportedTarget(String) + + /// `bind(target:)` was called a second time with a different target. + /// The drafter's weights encode assumptions about one specific target; + /// rebinding to a different target is not supported. + case rebindForbidden + + /// A drafter/target compatibility check failed at bind time. `field` + /// names the mismatched field; `drafter` and `target` are the observed + /// values (stringified). + case incompatibleDrafter(field: String, drafter: String, target: String) + + /// `generateGemma4MTP` was called with a `blockSize` outside the + /// supported range (typically 2-16). + case invalidBlockSize(Int) + + /// A drafter forward was attempted before `bind(target:)`. + case drafterNotBound + + public var errorDescription: String? { + switch self { + case .unsupportedTarget(let typeName): + return "Gemma4 MTP requires a Gemma4TextModel target; got \(typeName)." + case .rebindForbidden: + return + "Gemma4AssistantDraftModel cannot be rebound to a different target. " + + "Construct a new drafter instead." + case .incompatibleDrafter(let field, let drafter, let target): + return + "Drafter/target mismatch on \(field): drafter=\(drafter), target=\(target)." + case .invalidBlockSize(let n): + return "Invalid blockSize \(n): must be between 2 and 16 inclusive." + case .drafterNotBound: + return + "Gemma4AssistantDraftModel.bind(target:) must be called before " + + "any forward pass." + } + } +} + +// MARK: - Shared KV Types + +/// Public namespace for Gemma 4 types that need cross-module visibility. +public enum Gemma4 { + + /// Position offset for RoPE, either a single scalar (standard decode) + /// or a per-row `MLXArray` (continuous-batching / drafter paths). + /// + /// `@unchecked Sendable` because `MLXArray` is not `Sendable`; callers must + /// treat these values as immutable snapshots (they are only ever read, never + /// mutated in place). + public enum PositionOffset: @unchecked Sendable { + case scalar(Int) + case batch(MLXArray) + } +} + +/// Immutable snapshot of per-layer-type K/V captured from a target +/// `Gemma4TextModel` during `forwardForMTP`. Consumed by the Gemma 4 MTP +/// drafter; every drafter layer reads from one of these two slots rather +/// than projecting its own K/V. +public struct Gemma4SharedKV: @unchecked Sendable { + /// K/V from the target's last non-shared full-attention layer. + /// Shape: `[B, nGlobalKVHeads, T, globalHeadDim]`. + public let fullAttention: (MLXArray, MLXArray) + /// K/V from the target's last non-shared sliding-attention layer. + /// Shape: `[B, nKVHeads, T, headDim]`. + public let slidingAttention: (MLXArray, MLXArray) + + public init( + fullAttention: (MLXArray, MLXArray), + slidingAttention: (MLXArray, MLXArray) + ) { + self.fullAttention = fullAttention + self.slidingAttention = slidingAttention + } + + /// Trim the tail of both K/V tensors by `rejected` time positions. Used + /// by the MTP round-loop to match the post-rollback target cache length. + /// If `rejected >= T`, clamps to a 1-slot tail so the drafter always has + /// at least one K/V position to attend to. + public static func sliceTail( + from shared: Gemma4SharedKV, rejected: Int + ) -> Gemma4SharedKV { + func slice(_ kv: (MLXArray, MLXArray)) -> (MLXArray, MLXArray) { + let T = kv.0.dim(2) + let valid = max(1, T - max(0, rejected)) + if valid >= T { return kv } + let k = kv.0[.ellipsis, ..1 MTP round loop to match the per-row target cache + /// zeroing performed by `rollbackSpeculativeCache(.perRow:)`. Rows + /// that accepted less than max have their tail K/V zeroed so the + /// drafter doesn't attend to post-rollback "stale" positions. + /// + /// This differs from `sliceTail` which uniformly trims the T axis. + /// `zeroTailPerRow` preserves the T axis length (so all rows share + /// the same tensor shape) but zeros the invalid slots - the + /// SDPA/attention computation sees zeros, which contribute nothing + /// to the softmax when multiplied by queries. + /// + /// - Parameter keepLengths: int array of shape `[B]`. For row `b`, + /// slots `[0, keepLengths[b])` are preserved; slots + /// `[keepLengths[b], T)` are zeroed. + public static func zeroTailPerRow( + from shared: Gemma4SharedKV, keepLengths: MLXArray + ) -> Gemma4SharedKV { + func zero(_ kv: (MLXArray, MLXArray)) -> (MLXArray, MLXArray) { + let T = kv.0.dim(2) + let positions = MLXArray(Int32(0) ..< Int32(T)) + .reshaped([1, 1, T, 1]) // [1, 1, T, 1] + let keep = keepLengths.asType(.int32) + .reshaped([-1, 1, 1, 1]) // [B, 1, 1, 1] + let keepMask = positions .< keep // [B, 1, T, 1] + let maskK = keepMask.asType(kv.0.dtype) + let maskV = keepMask.asType(kv.1.dtype) + return (kv.0 * maskK, kv.1 * maskV) + } + return Gemma4SharedKV( + fullAttention: zero(shared.fullAttention), + slidingAttention: zero(shared.slidingAttention) + ) + } +} + +/// Mutable sink for the shared-KV capture hook in +/// `Gemma4TextModelInner.callAsFunction`. A reference type so the trunk can +/// write into it without a return-value contortion; cleared by the caller +/// between forwards. +public final class Gemma4SharedKVCapture: @unchecked Sendable { + public var fullAttention: (MLXArray, MLXArray)? = nil + public var slidingAttention: (MLXArray, MLXArray)? = nil + + public init() {} + + /// Snapshot into an immutable `Gemma4SharedKV`. Throws via + /// `fatalError` if either slot is missing - the capture hook is + /// expected to populate both. + public func snapshot() -> Gemma4SharedKV { + guard let full = fullAttention else { + fatalError("Gemma4SharedKVCapture: fullAttention was not populated") + } + guard let sliding = slidingAttention else { + fatalError("Gemma4SharedKVCapture: slidingAttention was not populated") + } + return Gemma4SharedKV(fullAttention: full, slidingAttention: sliding) + } +} + +/// Result of `Gemma4TextModel.forwardForMTP`. Carries both the LM head +/// output and the pre-head trunk hidden, plus the shared-KV snapshot the +/// drafter needs for its next round. +public struct Gemma4MTPForward: @unchecked Sendable { + /// `[B, L, vocab]` - softcap applied. + public let logits: MLXArray + /// `[B, L, hidden_size]` - last decoder-layer output BEFORE the final + /// `model.norm`. This matches HF's `hidden_states` capture point and is + /// what the MTP drafter's `pre_projection` was trained against. + public let lastHidden: MLXArray + /// Per-layer-type K/V from the last non-shared layers of the target. + public let capturedSharedKV: Gemma4SharedKV + + public init( + logits: MLXArray, lastHidden: MLXArray, capturedSharedKV: Gemma4SharedKV + ) { + self.logits = logits + self.lastHidden = lastHidden + self.capturedSharedKV = capturedSharedKV + } +} + +/// Count of accepted speculative tokens per round, either scalar (B=1) +/// or per-row (`[B]` int32 array, B>1). +public enum Gemma4AcceptCount: @unchecked Sendable { + case scalar(Int) + case perRow(MLXArray) + + /// Max accepted across all rows (== the scalar value in the scalar case). + func maxAccepted() -> Int { + switch self { + case .scalar(let n): return n + case .perRow(let arr): return Int(arr.max().item(Int32.self)) + } + } +} + +// MARK: - Automatic Policy + +/// Gemma 4 target family inferred from the loaded text-model config. +public enum Gemma4MTPModelFamily: Sendable, Equatable { + case e2b + case e4b + case moeA4B + case unknownDense + case unknownMoE +} + +/// Execution strategy for a requested MTP batch. +public enum Gemma4MTPBatchStrategy: Sendable, Equatable { + /// Run each request as a single stream (`B=1`) using this block size. + case singleStream(blockSize: Int) + /// Run the requests through the B>1 round loop using this block size. + case batched(blockSize: Int) + + public var blockSize: Int { + switch self { + case .singleStream(let blockSize), .batched(let blockSize): + return blockSize + } + } + + public var usesBatchedRoundLoop: Bool { + switch self { + case .batched: return true + case .singleStream: return false + } + } +} + +/// Single-stream runtime action selected by the automatic MTP policy. +public enum Gemma4MTPSingleStreamAction: Sendable, Equatable { + /// Run an MTP round with this block size. + case mtp(blockSize: Int) + /// Emit the next token from the target model only. + case targetOnly + + public var blockSize: Int? { + switch self { + case .mtp(let blockSize): blockSize + case .targetOnly: nil + } + } +} + +/// Model-aware defaults for Gemma 4 MTP on Apple Silicon. +/// +/// The policy is intentionally conservative: only model families with +/// measured B>1 wins opt into the batched round loop. Unknown dense and +/// MoE variants fall back to the B=1 path until benchmarked. +public struct Gemma4MTPAutomaticPolicy: Sendable, Equatable { + public let family: Gemma4MTPModelFamily + public let singleStreamBlockSize: Int + public let batchedBlockSize: Int? + + public var supportsBatchedMTP: Bool { + batchedBlockSize != nil + } + + /// Whether the public automatic generation entry point should use MTP + /// for this family when the caller does not force a block size. + public var enablesAutomaticMTP: Bool { + family != .e4b + } + + public func strategy(forBatchSize batchSize: Int) -> Gemma4MTPBatchStrategy { + precondition(batchSize >= 1, "batchSize must be at least 1") + if batchSize == 1 { + return .singleStream(blockSize: singleStreamBlockSize) + } + if let batchedBlockSize { + return .batched(blockSize: batchedBlockSize) + } + return .singleStream(blockSize: singleStreamBlockSize) + } + + public func singleStreamAction( + generatedTokens: Int, + maxTokens: Int? + ) -> Gemma4MTPSingleStreamAction { + precondition(generatedTokens >= 0, "generatedTokens must be non-negative") + + if !enablesAutomaticMTP { + return .targetOnly + } + + if family == .e2b && singleStreamBlockSize == 3 && batchedBlockSize == nil { + if let maxTokens, maxTokens <= 16 { + return .mtp(blockSize: 4) + } + if generatedTokens < 256 { + return .targetOnly + } + return .mtp(blockSize: 4) + } + + return .mtp(blockSize: singleStreamBlockSize) + } + + public static func automatic(for target: Gemma4TextModel) -> Self { + automatic(for: target.configuration) + } + + public static func automatic(for config: Gemma4TextConfiguration) -> Self { + if config.enableMoeBlock { + if config.hiddenSize == 2816 && config.numHiddenLayers == 30 { + return Self( + family: .moeA4B, + singleStreamBlockSize: 3, + batchedBlockSize: nil) + } + return Self( + family: .unknownMoE, + singleStreamBlockSize: 3, + batchedBlockSize: nil) + } + + if config.hiddenSize == 1536 && config.numHiddenLayers == 35 { + if config.quantizationBits == 4 { + return Self( + family: .e2b, + singleStreamBlockSize: 3, + batchedBlockSize: nil) + } + return Self( + family: .e2b, + singleStreamBlockSize: 5, + batchedBlockSize: 3) + } + + if config.hiddenSize == 2560 && config.numHiddenLayers == 42 { + return Self( + family: .e4b, + singleStreamBlockSize: 3, + batchedBlockSize: nil) + } + + return Self( + family: .unknownDense, + singleStreamBlockSize: 4, + batchedBlockSize: nil) + } +} + +// MARK: - Gemma4TextModel MTP Extensions + +extension Gemma4TextModel { + + /// Forward pass tailored for MTP speculative decoding. + /// + /// Returns both the LM head output (logits) and the pre-head trunk + /// hidden, plus a snapshot of the shared-KV tensors consumed by the + /// drafter on its next round. + public func forwardForMTP( + _ tokens: MLXArray, cache: [KVCache] + ) -> Gemma4MTPForward { + let capture = Gemma4SharedKVCapture() + let fullIdx = model.lastFullAttentionNonSharedIdx + let slidingIdx = model.lastSlidingAttentionNonSharedIdx + let (postNorm, preNorm) = model.callCapturingPreNorm( + tokens, cache: cache + ) { idx, kv in + if idx == fullIdx { + capture.fullAttention = kv + } else if idx == slidingIdx { + capture.slidingAttention = kv + } + } + let logits = applyLMHead(postNorm) + return Gemma4MTPForward( + logits: logits, + lastHidden: preNorm, + capturedSharedKV: capture.snapshot() + ) + } + + /// Rewind target KV caches after a speculative-decoding round. + /// + /// Uniformly trims rejected suffix positions. In the `.perRow` case, + /// batched caches are additionally zeroed per row so rows that accepted + /// fewer than the batch max cannot attend to stale post-rollback K/V. + public func rollbackSpeculativeCache( + _ caches: [KVCache], + accepted: Gemma4AcceptCount, + blockSize: Int + ) { + let maxAccepted = accepted.maxAccepted() + let trim = Swift.max(0, blockSize - maxAccepted - 1) + + for cache in caches { + guard cache.isTrimmable else { continue } + if trim > 0 { + _ = cache.trim(trim) + } + } + + if case .perRow(let perRowAccepted) = accepted, maxAccepted > 0 { + for cache in caches { + guard let batched = cache as? BatchKVCache else { continue } + let postTrimLen = batched.offset + let keepLengths = + perRowAccepted.asType(.int32) + + Int32(postTrimLen - maxAccepted) + batched.zeroTailPerRow(keepLengths: keepLengths) + } + } + } +} + +// MARK: - Drafter Masks + +public enum Gemma4DrafterMaskBuilder { + + /// Full-attention mask: always `.none`. SDPA handles bidirectional + /// attention without an explicit mask. + public static func bidirectionalFull( + queryLen: Int, kvLen: Int, dtype: DType + ) -> MLXFast.ScaledDotProductAttentionMaskMode { + _ = (queryLen, kvLen, dtype) + return .none + } + + /// Bidirectional sliding-window mask. + /// + /// For each query position `q in [queryOffset, queryOffset + queryLen)`, + /// allow attention to KV positions `k in (q - window, q + window)`. + /// Returns `.none` when the whole KV fits inside every query's window. + /// Otherwise returns a materialized `.array(...)` additive mask with + /// `-inf` outside the window and `0` inside. + public static func bidirectionalSWA( + queryLen: Int, queryOffset: Int, kvLen: Int, + window: Int, dtype: DType + ) -> MLXFast.ScaledDotProductAttentionMaskMode { + // No masking needed: the entire KV fits in the bidirectional window + // of every query. + if kvLen <= window && queryOffset + queryLen <= kvLen + window { + return .none + } + + let qIdx = MLXArray(Int32(queryOffset) ..< Int32(queryOffset + queryLen)) + .reshaped([queryLen, 1]) + let kIdx = MLXArray(Int32(0) ..< Int32(kvLen)) + .reshaped([1, kvLen]) + let dist = qIdx - kIdx + let inside = MLX.logicalAnd( + dist .> Int32(-window), + dist .< Int32(window)) + + let zero = MLXArray(0.0).asType(dtype) + let negInf = MLXArray(-Float.infinity).asType(dtype) + let bias = MLX.where(inside, zero, negInf) + // SDPA additive mask shape: broadcastable to (B, H, L, S). Add + // leading singleton axes for batch and head. + return .array(bias.reshaped([1, 1, queryLen, kvLen])) + } +} + +// MARK: - Masked Embedder + +public final class Gemma4MaskedEmbedder: Module, @unchecked Sendable { + @ModuleInfo(key: "centroids") public var centroids: Linear + @ParameterInfo(key: "token_ordering") public var tokenOrdering: MLXArray + + public let hiddenSize: Int + public let numCentroids: Int + public let topK: Int + public let vocabSize: Int + public let vocabSizePerCentroid: Int + + public init( + hiddenSize: Int, + numCentroids: Int, + topK: Int, + vocabSize: Int + ) { + precondition( + vocabSize % numCentroids == 0, + "vocabSize must be divisible by numCentroids") + self.hiddenSize = hiddenSize + self.numCentroids = numCentroids + self.topK = topK + self.vocabSize = vocabSize + self.vocabSizePerCentroid = vocabSize / numCentroids + + self._centroids.wrappedValue = Linear(hiddenSize, numCentroids, bias: false) + // token_ordering arrives as int64 in some checkpoints; the drafter + // sanitize step casts to int32. Default here is zeros. + self._tokenOrdering.wrappedValue = + MLXArray.zeros([vocabSize], type: Int32.self) + super.init() + } + + /// Compute sparse logits over the full vocab. + /// + /// - Parameters: + /// - hiddenStates: `[B, L, hidden]`. + /// - lmHeadWeight: `[vocabSize, hidden]` - typically tied to the + /// drafter's `embed_tokens.weight`. + /// - Returns: `[B, L, vocabSize]` with non-selected positions set to + /// `min(selected) - 1`. + public func callAsFunction( + hiddenStates: MLXArray, lmHeadWeight: MLXArray + ) -> MLXArray { + let B = hiddenStates.dim(0) + let L = hiddenStates.dim(1) + + // Cluster scores -> top-K cluster indices. + let centroidLogits = centroids(hiddenStates) // [B, L, numCentroids] + + // Negate-and-partition-from-front idiom: indices of the top-K + // scoring entries land at positions [0, topK). Matches the + // pattern in Libraries/MLXLMCommon/Evaluate.swift:288. + let topKIndices = argPartition(-centroidLogits, kth: topK - 1, axis: -1)[ + .ellipsis, .. [B, L, 1, topK * vsc] + let selectedLogits = matmul( + hiddenStates.expandedDimensions(axis: -2), + selectedEmb.swappedAxes(-1, -2) + ).squeezed(axis: -2) // [B, L, topK * vsc] + + // Scalar fill is faster than an explicit on-device broadcast on + // M3 for this shape; the only CPU sync in the sparse head is this + // scalar sentinel extraction. + let sentinelValue = selectedLogits.min().item(Float.self) - 1.0 + + // Full-vocab output tensor filled with the sentinel. + let out = MLX.full( + [B, L, vocabSize], + values: MLXArray(sentinelValue), + dtype: hiddenStates.dtype) + + // Scatter selected logits into their canonical positions. + let scatterIdx = selectedCanonical.reshaped([ + B, L, topK * vocabSizePerCentroid, + ]) + return putAlong(out, scatterIdx, values: selectedLogits, axis: -1) + } + + // MARK: - Test support + + /// Set centroids weight + tokenOrdering for unit tests. + /// Not part of the public surface. + internal func setTestWeights( + centroidsWeight: MLXArray, tokenOrdering: MLXArray + ) { + var params = ModuleParameters() + params["centroids"] = .dictionary([ + "weight": .value(centroidsWeight) + ]) + params["token_ordering"] = .value(tokenOrdering) + self.update(parameters: params) + } + + /// Set only the centroids weight. + internal func setTestCentroidWeight(_ w: MLXArray) { + var params = ModuleParameters() + params["centroids"] = .dictionary([ + "weight": .value(w) + ]) + self.update(parameters: params) + } +} + +// MARK: - Speculative Walk + +/// Accept/reject walker for speculative decoding. Pure Swift - no MLX +/// dependency so it can be exhaustively unit-tested. +public enum Gemma4SpeculativeWalk { + + /// Single-row greedy accept-prefix walker. + /// + /// The speculative-decoding contract: `main` contains `k + 1` tokens + /// (one verify per draft plus one "bonus" token that the target sampled + /// from the position after the last draft). `draft` contains the `k` + /// tokens the drafter proposed. Walk left-to-right, accept while + /// `draft[i] == main[i]`, and always emit one "correction" or "bonus" + /// token from `main` past the accepted prefix. + /// + /// - Returns: `(acceptedCount, emittedTokens)` where + /// `emittedTokens.count == acceptedCount + 1`. + public static func single(draft: [Int], main: [Int]) -> (Int, [Int]) { + // If draft is empty, just emit main[0] (the bonus). + guard !draft.isEmpty else { + precondition(!main.isEmpty, "main must contain at least the bonus") + return (0, [main[0]]) + } + precondition( + main.count >= draft.count + 1, + "main must have at least draft.count + 1 tokens (drafts + bonus)" + ) + var accepted = 0 + for i in 0 ..< draft.count { + if main[i] != draft[i] { break } + accepted += 1 + } + // Emit main[0...accepted] inclusive - that's accepted + 1 tokens. + return (accepted, Array(main[0 ... accepted])) + } + + /// Multi-row greedy accept-prefix walker with per-row emit budgets. + /// + /// - Parameters: + /// - draft: per-row draft tokens, length `[B][k]`. + /// - main: per-row verify tokens, length `[B][k+1]`. + /// - budgets: per-row max emit count. A row emits at most + /// `budgets[i]` tokens; the accept count is capped accordingly so + /// the `emitted.count == accepted + 1` invariant holds per row. + /// - Returns: `(acceptedPerRow, emittedPerRow)`. + public static func batched( + draft: [[Int]], main: [[Int]], budgets: [Int] + ) -> ([Int], [[Int]]) { + precondition( + draft.count == main.count && draft.count == budgets.count, + "batched: all inputs must have the same outer length B" + ) + var acceptedOut: [Int] = [] + var emittedOut: [[Int]] = [] + acceptedOut.reserveCapacity(draft.count) + emittedOut.reserveCapacity(draft.count) + for i in 0 ..< draft.count { + var (a, e) = single(draft: draft[i], main: main[i]) + let budget = Swift.max(0, budgets[i]) + if e.count > budget { + e = Array(e.prefix(budget)) + a = Swift.max(0, e.count - 1) + } + acceptedOut.append(a) + emittedOut.append(e) + } + return (acceptedOut, emittedOut) + } +} + +// MARK: - Speculative Sampling + +/// Result of one round of rejection-based speculative sampling. +public struct Gemma4SpeculativeSampleResult: Sendable { + /// Number of drafter tokens accepted (0...K). + public let accepted: Int + /// Tokens emitted by this round: first `accepted` drafter tokens, + /// followed by one corrective / bonus token. Always `accepted + 1` + /// entries. + public let emitted: [Int] + + public init(accepted: Int, emitted: [Int]) { + self.accepted = accepted + self.emitted = emitted + } +} + +/// Convert logits into the same sampling distribution used by +/// `GenerateParameters.sampler()`: compute log-probabilities, apply +/// topP/minP/topK filters, then apply temperature for the final categorical +/// distribution. The mask is applied in log-space before softmax so masked +/// positions land at 0 in `probs`. +/// +/// IMPORTANT: The SAME filter parameters must be used for both drafter +/// and target in `gemma4SpeculativeSampleRound`. Applying topP/topK to only +/// one side would make the accept ratio `p(c)/q(c)` ill-defined (e.g. +/// if `c` is in p's nucleus but not q's, `q(c) = 0`). +private func softmaxWithFilters( + _ logits: MLXArray, + temperature: Float, + topP: Float, + topK: Int, + minP: Float +) -> MLXArray { + precondition(temperature > 0, "temperature must be > 0 for stochastic sampling") + var logprobs = logSoftmax(logits.asType(.float32), axis: -1) + // Order matches mlx_lm's TopPSampler: topP -> minP -> topK. + if topP > 0 && topP < 1 { + logprobs = applyTopP(logprobs, p: topP) + } + if minP > 0 { + logprobs = applyMinP(logprobs, minP: minP) + } + if topK > 0 { + logprobs = applyTopK(logprobs, k: topK) + } + return softmax(logprobs / temperature, axis: -1) +} + +/// Public helper: sample one token from `logits` along the last axis +/// with temperature + optional topP / topK / minP filters. Returns the +/// sampled token index. Used by the MTP token iterator for the initial +/// bonus and for drafter draft steps so that the same filter masks are +/// applied everywhere along the generation path. +public func gemma4SampleLogitsWithFilters( + _ logits: MLXArray, + temperature: Float, + topP: Float, + topK: Int, + minP: Float, + rngKey: MLXArray +) -> MLXArray { + let probs = softmaxWithFilters( + logits, temperature: temperature, + topP: topP, topK: topK, minP: minP) + return sampleFromDistribution(probs, key: rngKey) +} + +/// Mask all but top-K log-probabilities to -inf along the last axis. +private func applyTopK(_ logprobs: MLXArray, k: Int) -> MLXArray { + let vocab = logprobs.shape.last ?? 0 + if k <= 0 || k >= vocab { return logprobs } + let sortedIdx = argSort(-logprobs, axis: -1) + let topIdx = sortedIdx[.ellipsis, 0 ..< k] + let topVals = takeAlong(logprobs, topIdx, axis: -1) + let threshold = topVals.min(axes: [-1], keepDims: true) + let negInf = MLXArray(-Float.infinity) + return MLX.where(logprobs .>= threshold, logprobs, negInf) +} + +/// Top-P (nucleus): mask tokens outside the smallest set whose +/// cumulative softmax mass is at least `p`. +private func applyTopP(_ logprobs: MLXArray, p: Float) -> MLXArray { + let sortedIdxAsc = argSort(logprobs, axis: -1) + let sortedLogprobs = takeAlong(logprobs, sortedIdxAsc, axis: -1) + let sortedProbs = exp(sortedLogprobs) + let cumProbs = sortedProbs.cumsum(axis: -1) + let keepMask = cumProbs .> MLXArray(1.0 - p) + let negInf = MLXArray(-Float.infinity) + let maskedSorted = MLX.where(keepMask, sortedLogprobs, negInf) + let inverseIdx = argSort(sortedIdxAsc, axis: -1) + return takeAlong(maskedSorted, inverseIdx, axis: -1) +} + +/// Min-P: mask tokens whose probability is below `minP * max_prob`. +/// Computed in log-space: `logp >= max_logp + log(minP)`. +private func applyMinP(_ logprobs: MLXArray, minP: Float) -> MLXArray { + let maxLogprob = logprobs.max(axis: -1, keepDims: true) + let threshold = maxLogprob + MLXArray(log(minP)) + let negInf = MLXArray(-Float.infinity) + return MLX.where(logprobs .>= threshold, logprobs, negInf) +} + +/// Sample one token from a distribution `[vocab]` (or `[..., vocab]`) +/// along the last axis. Returns an `[...]` int32 array. +private func sampleFromDistribution(_ probs: MLXArray, key: MLXArray) -> MLXArray { + // MLX has `MLXRandom.categorical(logits)` but we have probabilities. + // Use cumulative sum + uniform random number comparison. + let u = MLXRandom.uniform(low: Float(0), high: Float(1), key: key) + let cdf = probs.cumsum(axis: -1) + // count positions where cdf < u; that's the sampled index. + let lt = cdf .< u + return lt.sum(axis: -1).asType(.int32) +} + +/// Run rejection-based speculative sampling for one round. +/// +/// - Parameters: +/// - draftLogits: [K, vocab] - drafter logits at each of the K proposed +/// positions, *pre-temperature* (raw drafter output). +/// - draftTokens: [K] - tokens the drafter sampled. +/// - verifyLogits: [bs=K+1, vocab] - target logits at each verify +/// position, *pre-temperature* (raw target output). +/// - temperature: sampling temperature (> 0). +/// - topP: nucleus mass (1.0 = disabled). Applied identically to p and q. +/// - topK: top-K filter (0 = disabled). Applied identically to p and q. +/// - minP: min-P filter (0 = disabled). Applied identically to p and q. +/// - rngKey: MLX random key for the uniform draws. +/// - Returns: `(accepted, emitted)` - number of drafter tokens accepted +/// and the list of emitted tokens for this round. +public func gemma4SpeculativeSampleRound( + draftLogits: MLXArray, + draftTokens: [Int], + verifyLogits: MLXArray, + temperature: Float, + topP: Float = 1.0, + topK: Int = 0, + minP: Float = 0.0, + rngKey: MLXArray +) -> Gemma4SpeculativeSampleResult { + precondition(temperature > 0, "stochastic path requires temperature > 0") + let K = draftTokens.count + precondition(verifyLogits.dim(0) == K + 1, + "verifyLogits must have K+1 positions") + precondition(draftLogits.dim(0) == K, + "draftLogits must have K positions") + + // Apply temperature + identical filters on both p and q, once. + let q = softmaxWithFilters( + draftLogits, temperature: temperature, + topP: topP, topK: topK, minP: minP) // [K, vocab] + let p = softmaxWithFilters( + verifyLogits, temperature: temperature, + topP: topP, topK: topK, minP: minP) // [K+1, vocab] + + // Split the rng key into 2K subkeys (K for accept r_i, K for resample + // + final sample). + let keys = MLXRandom.split(key: rngKey, into: 2 * (K + 1)) + + var accepted = 0 + var emitted: [Int] = [] + for i in 0 ..< K { + let c = draftTokens[i] + let pi = p[i] // [vocab] + let qi = q[i] // [vocab] + let pc = pi[c].item(Float.self) + let qc = qi[c].item(Float.self) + let alpha = min(Float(1), qc > 0 ? pc / qc : 0) + let r = MLXRandom.uniform( + low: Float(0), high: Float(1), key: keys[i]).item(Float.self) + if r < alpha { + emitted.append(c) + accepted += 1 + } else { + // Reject. Resample from normalize(max(pi - qi, 0)). + let diff = MLX.maximum(pi - qi, MLXArray(Float(0))) + let s = diff.sum().item(Float.self) + let resampleDist: MLXArray + if s > 0 { + resampleDist = diff / s + } else { + // Numerical edge case: p == q exactly. Fall back to p + // which in theory should sum to 1 already. + resampleDist = pi + } + let nextTok = sampleFromDistribution( + resampleDist, key: keys[K + i]) + emitted.append(Int(nextTok.item(Int32.self))) + return Gemma4SpeculativeSampleResult(accepted: accepted, emitted: emitted) + } + } + // All K accepted - sample one bonus from p_K. + let bonus = sampleFromDistribution(p[K], key: keys[2 * K]) + emitted.append(Int(bonus.item(Int32.self))) + return Gemma4SpeculativeSampleResult(accepted: accepted, emitted: emitted) +} + +// MARK: - Assistant Configuration + +/// Configuration for the Gemma 4 Multi-Token Prediction "assistant" drafter. +/// +/// Mirrors the HF `Gemma4AssistantConfig` schema (flattened top-level + +/// nested `text_config`). Some fields are drafter-specific +/// (`backboneHiddenSize`, `useOrderedEmbeddings`, `numCentroids`, +/// `centroidIntermediateTopK`, `blockSize`); the nested `textConfig` +/// reuses the same `Gemma4TextConfiguration` that the target model uses, +/// with a post-init clamp that forces `numKvSharedLayers = +/// numHiddenLayers` when the checkpoint omits it (matching HF semantics +/// for drafter checkpoints). +public struct Gemma4AssistantConfiguration: Codable, Sendable { + public var modelType: String + public var backboneHiddenSize: Int + public var useOrderedEmbeddings: Bool + public var numCentroids: Int + public var centroidIntermediateTopK: Int + public var blockSize: Int + public var 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 blockSize = "block_size" + case textConfig = "text_config" + } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + self.modelType = + try container.decodeIfPresent(String.self, forKey: .modelType) + ?? "gemma4_assistant" + self.backboneHiddenSize = try container.decode(Int.self, forKey: .backboneHiddenSize) + self.useOrderedEmbeddings = + try container.decodeIfPresent(Bool.self, forKey: .useOrderedEmbeddings) ?? false + self.numCentroids = + try container.decodeIfPresent(Int.self, forKey: .numCentroids) ?? 2048 + self.centroidIntermediateTopK = + try container.decodeIfPresent(Int.self, forKey: .centroidIntermediateTopK) ?? 32 + // block_size isn't in the HF config file - it's a runtime hyperparam + // passed into the round loop. Default 4 matches Google's published + // recommendation. + self.blockSize = + try container.decodeIfPresent(Int.self, forKey: .blockSize) ?? 4 + + var textConfig = + try container.decode(Gemma4TextConfiguration.self, forKey: .textConfig) + + // HF post-init: drafter checkpoints require every layer to consume + // the target's shared K/V. If the checkpoint omits num_kv_shared_layers + // (decoder default 20, typically > num_hidden_layers=4 for drafters) + // or sets it to 0, clamp it to num_hidden_layers so every drafter + // layer is KV-shared. + if textConfig.numKvSharedLayers == 0 + || textConfig.numKvSharedLayers > textConfig.numHiddenLayers + { + textConfig.numKvSharedLayers = textConfig.numHiddenLayers + } + self.textConfig = textConfig + } +} + +// MARK: - Assistant Draft Model + +internal struct Gemma4DrafterMasks { + let full: MLXFast.ScaledDotProductAttentionMaskMode + let sliding: MLXFast.ScaledDotProductAttentionMaskMode +} + +public final class Gemma4AssistantDraftModel: Module, @unchecked Sendable { + public let config: Gemma4AssistantConfiguration + + @ModuleInfo public var model: Gemma4TextModelInner + @ModuleInfo(key: "pre_projection") public var preProjection: Linear + @ModuleInfo(key: "post_projection") public var postProjection: Linear + @ModuleInfo(key: "lm_head") public var lmHead: Linear? + @ModuleInfo(key: "masked_embedding") public var maskedEmbedder: Gemma4MaskedEmbedder? + + // Set by bind(target:); drafter is not usable before bind(). + internal var targetEmbed: ((MLXArray) -> MLXArray)? + internal var boundTargetID: ObjectIdentifier? + + public init(config: Gemma4AssistantConfiguration) { + self.config = config + + let textCfg = config.textConfig + self._model.wrappedValue = + Gemma4TextModelInner(textCfg, forceSharedKV: true) + + // pre: [2 * backbone -> drafter_hidden] + self._preProjection.wrappedValue = Linear( + 2 * config.backboneHiddenSize, textCfg.hiddenSize, bias: false) + // post: [drafter_hidden -> backbone] + self._postProjection.wrappedValue = Linear( + textCfg.hiddenSize, config.backboneHiddenSize, bias: false) + + if !textCfg.tieWordEmbeddings { + // Explicit LM head instantiated; Gemma4MaskedEmbedder stays nil. + self._lmHead.wrappedValue = Linear( + textCfg.hiddenSize, textCfg.vocabSize, bias: false) + } + + if config.useOrderedEmbeddings { + self._maskedEmbedder.wrappedValue = Gemma4MaskedEmbedder( + hiddenSize: textCfg.hiddenSize, + numCentroids: config.numCentroids, + topK: config.centroidIntermediateTopK, + vocabSize: textCfg.vocabSize + ) + } + + super.init() + } + + /// Bind the drafter to a Gemma 4 target. Captures a closure into the + /// target's scaled embedding lookup + runs compatibility validation. + /// Idempotent on the same target; throws `.rebindForbidden` if called + /// with a different target. + public func bind(target: Gemma4TextModel) throws { + let newID = ObjectIdentifier(target) + if let existing = boundTargetID { + if existing == newID { return } // idempotent same-target + throw Gemma4MTPError.rebindForbidden + } + try validateCompatibility(with: target) + self.targetEmbed = { [target] tokens in + target.embedTokensForDrafter(tokens) + } + self.boundTargetID = newID + } + + /// Clear the binding. Subsequent forward passes will throw + /// `.drafterNotBound`. + public func unbind() { + self.targetEmbed = nil + self.boundTargetID = nil + } + + // MARK: - Forward pass + + /// Drafter forward pass. + /// + /// - Parameters: + /// - inputsEmbeds: `[B, 1, 2 * backboneHiddenSize]` - the drafter-step + /// input, which the round-loop constructs as + /// `concat([target_embed(last_token), last_hidden], axis: -1)`. + /// - sharedKV: K/V snapshot from the target's last non-shared + /// full-attention and sliding-attention layers. Every drafter layer + /// reads from the appropriate slot by its `layerType`. + /// - positionOffset: absolute position of the bonus token; held + /// constant across all drafter steps within a block. + /// - Returns: `(lastHidden: [B, 1, backboneHiddenSize], logits: [B, 1, vocabSize])`. + /// + /// Softcap is **not** applied (drafter configs have + /// `final_logit_softcapping: null`). + public func callAsFunction( + inputsEmbeds: MLXArray, + sharedKV: Gemma4SharedKV, + positionOffset: Gemma4.PositionOffset + ) -> (lastHidden: MLXArray, logits: MLXArray) { + let h = preProjection(inputsEmbeds) + let masks = makeMasks( + queryLen: h.dim(1), + sharedKV: sharedKV, + positionOffset: positionOffset, + dtype: h.dtype) + return forwardProjected( + h, + sharedKV: sharedKV, + positionOffset: positionOffset, + masks: masks) + } + + internal func callAsFunction( + inputsEmbeds: MLXArray, + sharedKV: Gemma4SharedKV, + positionOffset: Gemma4.PositionOffset, + masks: Gemma4DrafterMasks + ) -> (lastHidden: MLXArray, logits: MLXArray) { + let h = preProjection(inputsEmbeds) + return forwardProjected( + h, + sharedKV: sharedKV, + positionOffset: positionOffset, + masks: masks) + } + + internal func makeMasks( + queryLen: Int, + sharedKV: Gemma4SharedKV, + positionOffset: Gemma4.PositionOffset, + dtype: DType + ) -> Gemma4DrafterMasks { + let textCfg = config.textConfig + let queryOffset: Int + switch positionOffset { + case .scalar(let v): queryOffset = v + case .batch(let arr): queryOffset = Int(arr[0].item(Int32.self)) + } + + let fullKVLen = sharedKV.fullAttention.0.dim(2) + let slidingKVLen = sharedKV.slidingAttention.0.dim(2) + + let fullMask = Gemma4DrafterMaskBuilder.bidirectionalFull( + queryLen: queryLen, kvLen: fullKVLen, dtype: dtype) + let slidingMask = Gemma4DrafterMaskBuilder.bidirectionalSWA( + queryLen: queryLen, queryOffset: queryOffset, + kvLen: slidingKVLen, window: textCfg.slidingWindow, dtype: dtype) + return Gemma4DrafterMasks(full: fullMask, sliding: slidingMask) + } + + private func forwardProjected( + _ projected: MLXArray, + sharedKV: Gemma4SharedKV, + positionOffset: Gemma4.PositionOffset, + masks: Gemma4DrafterMasks + ) -> (lastHidden: MLXArray, logits: MLXArray) { + let textCfg = config.textConfig + var h = projected + // Run each drafter layer with the appropriate shared-KV + mask. + for (i, layer) in model.layers.enumerated() { + let layerType = textCfg.layerTypes[i] + let kv: (MLXArray, MLXArray) + let mask: MLXFast.ScaledDotProductAttentionMaskMode + switch layerType { + case "full_attention": + kv = sharedKV.fullAttention + mask = masks.full + case "sliding_attention": + kv = sharedKV.slidingAttention + mask = masks.sliding + default: + preconditionFailure( + "Gemma4AssistantDraftModel: unexpected layerType '\(layerType)' at " + + "layer \(i). Compat validation should have rejected this." + ) + } + let (out, _, _) = layer( + h, + mask: mask, + cache: nil, + perLayerInput: nil, + sharedKV: kv, + positionOffset: positionOffset + ) + h = out + } + + h = model.norm(h) + let lastHidden = postProjection(h) + let logits = applyLMHead(h) + return (lastHidden, logits) + } + + /// Dispatch the LM head: masked-centroid if `useOrderedEmbeddings`, + /// tied otherwise (unless an explicit `lm_head` is present). + /// No softcap. + private func applyLMHead(_ hidden: MLXArray) -> MLXArray { + if let maskedEmbedder { + return maskedEmbedder( + hiddenStates: hidden, + lmHeadWeight: model.embedTokens.weight + ) + } + if let lmHead { + return lmHead(hidden) + } + // Tied: project hidden through the (transposed) token embedding. + return model.embedTokens.asLinear(hidden) + } + + // MARK: - Weight sanitization + + /// Sanitize a raw drafter checkpoint dictionary into the form the + /// drafter's modules expect. + /// + /// Rules: + /// - Cast `masked_embedding.token_ordering` to int32 (HF ships it as int64). + /// - Drop `lm_head.weight` when the drafter config has + /// `tieWordEmbeddings == true` (the LM head is tied to `embed_tokens`; + /// a present `lm_head.weight` in the checkpoint is redundant). + /// - Throw on unexpected `k_proj` / `v_proj` / `k_norm` / `v_norm` + /// weights: every drafter layer is kv-shared by construction, so + /// those modules aren't instantiated. A stray weight indicates a + /// checkpoint/config mismatch and should surface loudly rather than + /// be silently dropped. + /// + /// - Throws: `Gemma4MTPError.incompatibleDrafter(field:...)` with a + /// descriptive field name when an unexpected K/V weight is present. + public func sanitize(weights: [String: MLXArray]) throws -> [String: MLXArray] { + var out: [String: MLXArray] = [:] + out.reserveCapacity(weights.count) + + let forbiddenSubstrings = [ + ".self_attn.k_proj", + ".self_attn.v_proj", + ".self_attn.k_norm", + ".self_attn.v_norm", + ] + + for (key, value) in weights { + // Fail loud on forbidden K/V weights. + for substring in forbiddenSubstrings { + if key.contains(substring) { + throw Gemma4MTPError.incompatibleDrafter( + field: key, + drafter: "(unexpected - drafter layers are kv-shared)", + target: "(should not be present)" + ) + } + } + + // Drop lm_head.weight when tied. + if key == "lm_head.weight" && config.textConfig.tieWordEmbeddings { + continue + } + + // Cast masked_embedding.token_ordering to int32. + if key == "masked_embedding.token_ordering" { + out[key] = value.asType(.int32) + continue + } + + out[key] = value + } + + return out + } + + // MARK: - Compatibility validation + + /// Fail-fast on every drafter/target mismatch with the field name in + /// the error. Called once at bind time. + private func validateCompatibility(with target: Gemma4TextModel) throws { + let drafterT = config.textConfig + let targetCfg = target.configuration + + // 1. Backbone hidden size must match target hidden size (pre/post + // projection shapes depend on this). + guard config.backboneHiddenSize == targetCfg.hiddenSize else { + throw Gemma4MTPError.incompatibleDrafter( + field: "backboneHiddenSize", + drafter: "\(config.backboneHiddenSize)", + target: "\(targetCfg.hiddenSize)" + ) + } + + // 2. Vocab sizes must match (drafter's LM head produces logits over + // the target's vocab). + guard drafterT.vocabSize == targetCfg.vocabSize else { + throw Gemma4MTPError.incompatibleDrafter( + field: "vocabSize", + drafter: "\(drafterT.vocabSize)", + target: "\(targetCfg.vocabSize)" + ) + } + + // 3. Every drafter layer_type must be one of the two known types. + for (i, lt) in drafterT.layerTypes.enumerated() { + guard lt == "full_attention" || lt == "sliding_attention" else { + throw Gemma4MTPError.incompatibleDrafter( + field: "layerTypes[\(i)]", + drafter: lt, + target: "full_attention|sliding_attention" + ) + } + } + + // 4. K=V compatibility: applies only when the drafter has at least + // one full-attention layer AND attention_k_eq_v is true. + let drafterHasFullAttn = + drafterT.layerTypes.contains("full_attention") + if drafterHasFullAttn && drafterT.attentionKeqV { + guard targetCfg.attentionKeqV else { + throw Gemma4MTPError.incompatibleDrafter( + field: "attentionKeqV", + drafter: "true", + target: "false" + ) + } + guard drafterT.numGlobalKeyValueHeads == targetCfg.numGlobalKeyValueHeads + else { + throw Gemma4MTPError.incompatibleDrafter( + field: "numGlobalKeyValueHeads", + drafter: "\(drafterT.numGlobalKeyValueHeads.map(String.init) ?? "nil")", + target: "\(targetCfg.numGlobalKeyValueHeads.map(String.init) ?? "nil")" + ) + } + } + + // 5. Drafter must be fully KV-shared by construction. + guard drafterT.numKvSharedLayers == drafterT.numHiddenLayers else { + throw Gemma4MTPError.incompatibleDrafter( + field: "numKvSharedLayers", + drafter: "\(drafterT.numKvSharedLayers)", + target: "\(drafterT.numHiddenLayers)" + ) + } + } + + // MARK: - Loading + + /// Load a Gemma 4 MTP drafter from a local directory containing + /// `config.json` and one or more `*.safetensors` files. + /// + /// - Parameter directory: local directory containing the drafter + /// checkpoint (e.g. pre-downloaded via `huggingface-cli`). + /// - Returns: a ready-to-use drafter with weights loaded and evaluated. + /// - Throws: file I/O errors, JSON decoding errors, or + /// `Gemma4MTPError.incompatibleDrafter` from `sanitize`. + public static func load(from directory: URL) async throws -> Gemma4AssistantDraftModel { + // Decode the drafter config. + let configURL = directory.appending(component: "config.json") + let configData = try Data(contentsOf: configURL) + let config = try JSONDecoder.json5().decode( + Gemma4AssistantConfiguration.self, from: configData) + + // Construct the drafter (random init). + let drafter = Gemma4AssistantDraftModel(config: config) + + // Collect all safetensors files in the directory. + var weights = [String: MLXArray]() + guard let enumerator = FileManager.default.enumerator( + at: directory, includingPropertiesForKeys: nil) + else { + throw NSError( + domain: "Gemma4AssistantDraftModel", code: 1, + userInfo: [NSLocalizedDescriptionKey: + "Could not enumerate drafter directory: \(directory.path)"]) + } + let urls = enumerator.allObjects.compactMap { $0 as? URL } + for url in urls where url.pathExtension == "safetensors" { + let (shardWeights, _) = try loadArraysAndMetadata(url: url) + for (k, v) in shardWeights { + weights[k] = v + } + } + + // Run drafter sanitize (throws on unexpected K/V weights). + let sanitized = try drafter.sanitize(weights: weights) + + // Apply weights. + let params = ModuleParameters.unflattened(sanitized) + try drafter.update(parameters: params, verify: [.all]) + eval(drafter) + + return drafter + } + + /// Load a Gemma 4 MTP drafter from a remote model ID via a `Downloader`. + /// + /// Downloads `config.json` and `*.safetensors` files (tokenizer files are + /// skipped - drafters reuse the target's tokenizer at generation time). + /// + /// - Parameters: + /// - downloader: any `Downloader` (e.g. `HubClient`). + /// - id: the model identifier (e.g. `"mlx-community/gemma-4-E4B-it-assistant-bf16"`). + /// - revision: the revision to download (defaults to the downloader's + /// default, typically `"main"`). + /// - useLatest: whether to bypass the downloader's cache. + /// - progressHandler: optional progress callback. + /// - Returns: a ready-to-use drafter. + public static func load( + from downloader: any Downloader, + id: String, + revision: String? = nil, + useLatest: Bool = false, + progressHandler: @Sendable @escaping (Progress) -> Void = { _ in } + ) async throws -> Gemma4AssistantDraftModel { + let directory = try await downloader.download( + id: id, + revision: revision, + matching: ["*.safetensors", "config.json"], + useLatest: useLatest, + progressHandler: progressHandler + ) + return try await load(from: directory) + } +} + +// MARK: - Greedy Round + +internal struct Gemma4MTPGreedyRoundResult { + let accepted: Int + let tokens: [Int] + let bonus: Int + let hidden: MLXArray + let sharedKV: Gemma4SharedKV +} + +/// Run one single-batch greedy MTP round. +/// +/// The caller owns remaining-token truncation. `blockSize` is the actual +/// per-round size (`bonus + drafts`), not necessarily the user's maximum +/// configured block size. +internal func runGemma4MTPGreedyRound( + target: Gemma4TextModel, + drafter: Gemma4AssistantDraftModel, + cache: [KVCache], + bonus: Int, + hidden: MLXArray, + sharedKV: Gemma4SharedKV, + blockSize: Int +) -> Gemma4MTPGreedyRoundResult { + let k = blockSize - 1 + let driveOffset = cache[0].offset + let positionOffset = Gemma4.PositionOffset.scalar(driveOffset) + let masks = drafter.makeMasks( + queryLen: 1, + sharedKV: sharedKV, + positionOffset: positionOffset, + dtype: hidden.dtype) + + var tok = MLXArray([Int32(bonus)])[.newAxis, .ellipsis] + var h = hidden + var draftPerStep: [MLXArray] = [] + draftPerStep.reserveCapacity(k) + + for _ in 0 ..< k { + let tokEmbed = target.embedTokensForDrafter(tok) + let inputsEmbeds = concatenated([tokEmbed, h], axis: -1) + let (newH, logits) = drafter( + inputsEmbeds: inputsEmbeds, + sharedKV: sharedKV, + positionOffset: positionOffset, + masks: masks) + let sampled = logits.squeezed(axis: 1).argMax(axis: -1) + let sampled2d = sampled[.newAxis, .ellipsis] + draftPerStep.append(sampled2d) + tok = sampled2d + h = newH + } + + let bonusCol = MLXArray([Int32(bonus)])[.newAxis, .ellipsis] + let verifyInput: MLXArray = + draftPerStep.isEmpty + ? bonusCol + : concatenated([bonusCol] + draftPerStep, axis: 1) + let verifyOut = target.forwardForMTP(verifyInput, cache: cache) + let mainTokens = verifyOut.logits.asType(.float32).argMax(axis: -1) + let draftConcat: MLXArray = + draftPerStep.isEmpty + ? MLXArray.zeros([1, 0], dtype: .int32) + : concatenated(draftPerStep, axis: 1) + + eval(mainTokens, draftConcat) + let mainInts = mainTokens.squeezed(axis: 0).asArray(Int.self) + let draftTokens = draftConcat.squeezed(axis: 0).asArray(Int32.self) + .map { Int($0) } + let (accepted, newTokens) = Gemma4SpeculativeWalk.single( + draft: draftTokens, main: mainInts) + + if accepted < k { + target.rollbackSpeculativeCache( + cache, accepted: .scalar(accepted), blockSize: blockSize) + } + + let rejected = k - accepted + return Gemma4MTPGreedyRoundResult( + accepted: accepted, + tokens: newTokens, + bonus: newTokens.last!, + hidden: verifyOut.lastHidden[0..., accepted ..< accepted + 1, 0...], + sharedKV: Gemma4SharedKV.sliceTail( + from: verifyOut.capturedSharedKV, rejected: rejected) + ) +} + +// MARK: - Round Loops + +/// Run the Gemma 4 MTP round loop for a single request (B=1). +/// +/// - Parameters: +/// - target: the Gemma 4 target model. Must have been prefilled (i.e. +/// `forwardForMTP(promptTokens, cache:)` called once by the caller +/// before invoking this function) so `firstBonus`, `firstHidden`, and +/// `firstSharedKV` are available. +/// - drafter: the bound Gemma 4 MTP drafter. `bind(target:)` will be +/// called internally; if already bound to `target`, it's idempotent. +/// - targetCache: the KV caches from the prefill forward. Will be +/// advanced and rewound by this function. +/// - firstBonus: the token sampled from the last prefill position +/// (greedy argmax). This is the initial bonus - we yield it +/// immediately as the first stream element. +/// - firstHidden: the last-position hidden from the prefill forward, +/// shape `[B=1, L=1, hiddenSize]`. +/// - firstSharedKV: the shared-KV snapshot from the prefill forward. +/// - maxTokens: maximum total tokens to emit (including firstBonus). +/// - blockSize: speculative block size. Typical range 2-8. +/// - Returns: an `AsyncStream` emitting each generated token +/// as `.chunk("")`. The stream finishes when `maxTokens` is +/// reached or the loop terminates for any other reason. +/// - Throws: `Gemma4MTPError.invalidBlockSize` for blockSize < 2 or > 16. +/// +/// Tokens are yielded as `.chunk("")` strings; a real tokenizer +/// integration layer (see `generateGemma4MTP` in Task 22) wraps this with +/// `tokenizer.decode(tokenIds:)`. +public func runGemma4MTPRounds( + target: Gemma4TextModel, + drafter: Gemma4AssistantDraftModel, + targetCache: [KVCache], + firstBonus: Int, + firstHidden: MLXArray, + firstSharedKV: Gemma4SharedKV, + maxTokens: Int, + blockSize: Int +) throws -> AsyncStream { + guard blockSize >= 2 && blockSize <= 16 else { + throw Gemma4MTPError.invalidBlockSize(blockSize) + } + try drafter.bind(target: target) + + return AsyncStream { continuation in + // First yield: the prefill bonus. + continuation.yield(.chunk("\(firstBonus)")) + var emitted = 1 + + // Mutable state. + var bonus = firstBonus + var hidden = firstHidden + var sharedKV = firstSharedKV + + while emitted < maxTokens { + let remaining = maxTokens - emitted + let bs = min(blockSize, remaining + 1) + if bs <= 1 { break } + let round = runGemma4MTPGreedyRound( + target: target, + drafter: drafter, + cache: targetCache, + bonus: bonus, + hidden: hidden, + sharedKV: sharedKV, + blockSize: bs) + + // --- Emit --- + var stopEarly = false + for t in round.tokens { + continuation.yield(.chunk("\(t)")) + emitted += 1 + if emitted >= maxTokens { + stopEarly = true + break + } + } + if stopEarly { + continuation.finish() + return + } + + // --- Update state --- + hidden = round.hidden + bonus = round.bonus + sharedKV = round.sharedKV + + if emitted % 256 == 0 { + MLX.Memory.clearCache() + } + } + + continuation.finish() + } +} + +// MARK: - Batched (B > 1) output type + +/// Per-step output of the B>1 MTP round loop. Each `slots[i]` maps to +/// the original batch row `i`. +public struct BatchedGeneration: Sendable { + public let slots: [Slot] + + public struct Slot: Sendable { + /// Original index in the input batch. + public let row: Int + /// Token emitted this step; nil when the row is finished or the + /// step didn't produce output for this row. + public let token: Int? + /// Non-nil on the step where the row finishes. + public let finishReason: FinishReason? + + public init(row: Int, token: Int?, finishReason: FinishReason?) { + self.row = row + self.token = token + self.finishReason = finishReason + } + } + + public enum FinishReason: Sendable { + case stop + case eos + case length + } + + public init(slots: [Slot]) { + self.slots = slots + } +} + +// MARK: - B > 1 round loop + +/// Run the Gemma 4 MTP round loop for a batch of requests (B > 1). +/// +/// Mirrors `runGemma4MTPRounds` but tracks per-row acceptance counts and +/// per-row finishedness. Rows that finish (reach maxTokens or emit an +/// EOS token) stay in the batch but stop emitting - their +/// `BatchedGeneration.Slot.token` becomes nil. The round-loop terminates +/// when every row is finished. +/// +/// - Note: Continuous batching is implemented: when a row finishes (EOS +/// or maxTokens), `BatchedCache.filterBatched` shrinks every target +/// cache and `MLX.take(axis=0)` compacts `hidden` + `sharedKV` + the +/// per-row `bonus`/`activeIndices` arrays so the next round only pays +/// compute for still-active rows. Emitted `BatchedGeneration.Slot.row` +/// uses the ORIGINAL pre-compaction batch index so consumers can +/// demux regardless of active-batch size. +public func runGemma4MTPRoundsBatched( + target: Gemma4TextModel, + drafter: Gemma4AssistantDraftModel, + targetCache: [KVCache], + firstBonus: [Int], + firstHidden: MLXArray, + firstSharedKV: Gemma4SharedKV, + maxTokens: Int, + blockSize: Int, + eosTokenIds: Set?, + maxTokensPerRow: [Int]? = nil +) throws -> AsyncStream { + guard blockSize >= 2 && blockSize <= 16 else { + throw Gemma4MTPError.invalidBlockSize(blockSize) + } + try drafter.bind(target: target) + let originalB = firstBonus.count + // Per-row budget: if `maxTokensPerRow` is provided it overrides the + // global cap for each row; otherwise every row uses `maxTokens`. + let perRowBudget: [Int] = maxTokensPerRow ?? Array( + repeating: maxTokens, count: originalB) + precondition(perRowBudget.count == originalB, + "maxTokensPerRow.count must equal firstBonus.count") + + return AsyncStream { continuation in + // First yield: prefill bonus per original row. + var firstSlots: [BatchedGeneration.Slot] = [] + firstSlots.reserveCapacity(originalB) + // Per-original-row bookkeeping. `emitted`/`finished` stay + // indexed by original row for lifetime tracking; we compact the + // active batch separately. + var emitted = Array(repeating: 1, count: originalB) + var finished = Array(repeating: false, count: originalB) + for (i, b) in firstBonus.enumerated() { + if let eosTokenIds, eosTokenIds.contains(b) { + finished[i] = true + firstSlots.append(.init(row: i, token: b, finishReason: .eos)) + } else if emitted[i] >= perRowBudget[i] { + // Row's budget is 1 - the bonus is the only emitted token. + finished[i] = true + firstSlots.append(.init(row: i, token: b, finishReason: .length)) + } else { + firstSlots.append(.init(row: i, token: b, finishReason: nil)) + } + } + continuation.yield(BatchedGeneration(slots: firstSlots)) + if finished.allSatisfy({ $0 }) { + continuation.finish() + return + } + + // Active-batch state. `activeIndices[i]` is the original row index + // of active batch slot `i`. Shrinks as rows finish. + var activeIndices: [Int] = (0 ..< originalB).filter { !finished[$0] } + var bonus: [Int] = activeIndices.map { firstBonus[$0] } + var hidden: MLXArray = { + // firstHidden is [originalB, 1, H]. If any row already finished + // (EOS at prefill), compact to [activeB, 1, H] via takeAlong. + if activeIndices.count == originalB { + return firstHidden + } + let idx = MLXArray(activeIndices.map { Int32($0) }, [activeIndices.count]) + return MLX.take(firstHidden, idx, axis: 0) + }() + var sharedKV: Gemma4SharedKV = { + if activeIndices.count == originalB { + return firstSharedKV + } + let idx = MLXArray(activeIndices.map { Int32($0) }, [activeIndices.count]) + return Gemma4SharedKV( + fullAttention: ( + MLX.take(firstSharedKV.fullAttention.0, idx, axis: 0), + MLX.take(firstSharedKV.fullAttention.1, idx, axis: 0)), + slidingAttention: ( + MLX.take(firstSharedKV.slidingAttention.0, idx, axis: 0), + MLX.take(firstSharedKV.slidingAttention.1, idx, axis: 0))) + }() + // If we already lost some rows during prefill, compact the caches + // to match. + if activeIndices.count < originalB { + let idx = MLXArray(activeIndices.map { Int32($0) }, [activeIndices.count]) + for cache in targetCache { + if let bc = cache as? BatchedCache { + bc.filterBatched(batchIndices: idx) + } + } + } + + while !finished.allSatisfy({ $0 }) { + let B = activeIndices.count + // Determine this round's block size. Use the min `remaining` + // across ACTIVE rows only (finished rows are already excluded + // from activeIndices). + let activeRemaining = activeIndices.map { perRowBudget[$0] - emitted[$0] } + guard let minRemaining = activeRemaining.min(), minRemaining > 0 else { + break + } + let bs = min(blockSize, minRemaining + 1) + if bs <= 1 { break } + let k = bs - 1 + + // --- Draft (k autoregressive steps) --- + // + // Keep sampled draft tokens on the GPU instead of materialising + // each step as a Swift array. Each step's sampled [B] token + // tensor is collected; at the end we stack them [B, k] and + // prepend the bonus to form the verify input in one eval. + let driveOffset = targetCache[0].offset + let positionOffset = Gemma4.PositionOffset.scalar(driveOffset) + let masks = drafter.makeMasks( + queryLen: 1, + sharedKV: sharedKV, + positionOffset: positionOffset, + dtype: hidden.dtype) + // Seed token: per-row bonus as [B, 1] int32. + var tok = MLXArray(bonus.map { Int32($0) }, [B, 1]) + var h = hidden + var draftPerStep: [MLXArray] = [] // each is shape [B, 1] + draftPerStep.reserveCapacity(k) + for _ in 0 ..< k { + let tokEmbed = target.embedTokensForDrafter(tok) + let inputsEmbeds = concatenated([tokEmbed, h], axis: -1) + let (newH, logits) = drafter( + inputsEmbeds: inputsEmbeds, + sharedKV: sharedKV, + positionOffset: positionOffset, + masks: masks + ) + // Greedy sample per row: logits [B, 1, vocab] -> [B, 1] + let sampled = logits.squeezed(axis: 1).argMax(axis: -1) // [B] + let sampled2d = sampled.reshaped([B, 1]) // [B, 1] + draftPerStep.append(sampled2d) + tok = sampled2d + h = newH + } + + // --- Verify --- + // Concat drafts along axis=1 to get [B, k], prepend bonus to + // get [B, bs=k+1]. Single eval across the whole verify step. + let bonusCol = MLXArray(bonus.map { Int32($0) }, [B, 1]) + let verifyInput: MLXArray = + draftPerStep.isEmpty + ? bonusCol + : concatenated([bonusCol] + draftPerStep, axis: 1) + let verifyOut = target.forwardForMTP(verifyInput, cache: targetCache) + // fp32 argmax at verify: see comment in B=1 path above. + let mainTokens = verifyOut.logits.asType(.float32).argMax(axis: -1) // [B, bs] + // Materialise drafts + main tokens in a single sync. + let draftConcat: MLXArray = + draftPerStep.isEmpty + ? MLXArray.zeros([B, 0], dtype: .int32) + : concatenated(draftPerStep, axis: 1) // [B, k] + eval(mainTokens, draftConcat) + let mainFlat = mainTokens.asArray(Int32.self) + let draftFlat = draftConcat.asArray(Int32.self) + var mainPerRow: [[Int]] = [] + var draftTokensPerRow: [[Int]] = [] + mainPerRow.reserveCapacity(B) + draftTokensPerRow.reserveCapacity(B) + for bi in 0 ..< B { + let mStart = bi * bs + mainPerRow.append(mainFlat[mStart ..< mStart + bs].map { Int($0) }) + let dStart = bi * k + draftTokensPerRow.append(draftFlat[dStart ..< dStart + k].map { Int($0) }) + } + + // --- Walk (per-row, with remaining-budget truncation) --- + let budgets = activeIndices.map { perRowBudget[$0] - emitted[$0] } + let (accepted, newTokensPerRow) = Gemma4SpeculativeWalk.batched( + draft: draftTokensPerRow, + main: mainPerRow, + budgets: budgets + ) + let maxAcceptedInt = accepted.max() ?? 0 + + // --- Emit one BatchedGeneration per token-position within this round --- + // Slots use the ORIGINAL row index from activeIndices so consumers + // can continue to demux emissions even as the active batch shrinks. + // + // Track which active slots newly finished this round so we can + // compact the cache + state afterward. + var finishedThisRound = Array(repeating: false, count: B) + let maxNew = newTokensPerRow.map(\.count).max() ?? 0 + for pos in 0 ..< maxNew { + var slots: [BatchedGeneration.Slot] = [] + slots.reserveCapacity(B) + for bi in 0 ..< B { + let origRow = activeIndices[bi] + if finishedThisRound[bi] { + // Already finished earlier this round; no more + // emissions for this slot. + slots.append(.init(row: origRow, token: nil, finishReason: nil)) + continue + } + let row = newTokensPerRow[bi] + if pos < row.count { + let t = row[pos] + emitted[origRow] += 1 + var finishReason: BatchedGeneration.FinishReason? = nil + if let eosTokenIds, eosTokenIds.contains(t) { + finished[origRow] = true + finishedThisRound[bi] = true + finishReason = .eos + } else if emitted[origRow] >= perRowBudget[origRow] { + finished[origRow] = true + finishedThisRound[bi] = true + finishReason = .length + } + slots.append(.init(row: origRow, token: t, finishReason: finishReason)) + } else { + slots.append(.init(row: origRow, token: nil, finishReason: nil)) + } + } + continuation.yield(BatchedGeneration(slots: slots)) + } + + if finished.allSatisfy({ $0 }) { + continuation.finish() + return + } + + // --- Rewind target cache --- + // Fast path: if every row accepted the same count, use the + // scalar rewind (uniform cache trim, no per-row zero-tail). + // This is common when prompts are identical or strongly + // aligned - typical for synthetic benchmarks and real serving + // with prompt-prefix caching. + let uniformAccepted = accepted.allSatisfy { $0 == accepted[0] } + if maxAcceptedInt < k { + if uniformAccepted { + target.rollbackSpeculativeCache( + targetCache, + accepted: .scalar(accepted[0]), + blockSize: bs + ) + } else { + let acceptedArr = MLXArray(accepted.map { Int32($0) }) + target.rollbackSpeculativeCache( + targetCache, + accepted: .perRow(acceptedArr), + blockSize: bs + ) + } + } + + // --- Update state --- + // Per-row hidden: gather verifyOut.lastHidden[bi, accepted[bi], :] + // into a [B, 1, hidden] tensor via takeAlong on axis=1. + let hiddenDim = verifyOut.lastHidden.dim(2) + let acceptedIdx = MLX.broadcast( + MLXArray(accepted.map { Int32($0) }, [B, 1, 1]), + to: [B, 1, hiddenDim]) + hidden = MLX.takeAlong( + verifyOut.lastHidden, acceptedIdx, axis: 1) // [B, 1, hidden] + + // Update per-row bonus: last emitted token (or carry forward if + // the row finished without emitting). + for bi in 0 ..< B { + if let last = newTokensPerRow[bi].last { + bonus[bi] = last + } + } + + // Shared-KV update to match the target cache's rewind. + if uniformAccepted { + let rejected = k - accepted[0] + sharedKV = Gemma4SharedKV.sliceTail( + from: verifyOut.capturedSharedKV, rejected: rejected) + } else { + let capturedT = verifyOut.capturedSharedKV.fullAttention.0.dim(2) + let rejectedPerRow = accepted.map { Int32(k - $0) } + let keepLengths = MLXArray( + rejectedPerRow.map { Int32(capturedT) - $0 } + ) + sharedKV = Gemma4SharedKV.zeroTailPerRow( + from: verifyOut.capturedSharedKV, keepLengths: keepLengths) + } + + // --- Continuous batching: compact if any slot just finished --- + // + // When a subset of active slots hit EOS or maxTokens this round, + // filter the target cache + per-row state so the next round only + // pays compute for still-active rows. Rows that never finish are + // a no-op here. + if finishedThisRound.contains(true) { + let keepLocal: [Int] = finishedThisRound.enumerated() + .compactMap { $0.element ? nil : $0.offset } + if keepLocal.isEmpty { + // Shouldn't happen: finished.allSatisfy would have tripped + // above. Guard anyway. + break + } + // Compact the active-batch bookkeeping. + activeIndices = keepLocal.map { activeIndices[$0] } + bonus = keepLocal.map { bonus[$0] } + // Compact GPU-side state tensors + the shared KV + every cache. + let keepIdx = MLXArray( + keepLocal.map { Int32($0) }, [keepLocal.count]) + hidden = MLX.take(hidden, keepIdx, axis: 0) + sharedKV = Gemma4SharedKV( + fullAttention: ( + MLX.take(sharedKV.fullAttention.0, keepIdx, axis: 0), + MLX.take(sharedKV.fullAttention.1, keepIdx, axis: 0)), + slidingAttention: ( + MLX.take(sharedKV.slidingAttention.0, keepIdx, axis: 0), + MLX.take(sharedKV.slidingAttention.1, keepIdx, axis: 0))) + for cache in targetCache { + if let bc = cache as? BatchedCache { + bc.filterBatched(batchIndices: keepIdx) + } + } + } + + if (emitted.max() ?? 0) % 256 == 0 { + MLX.Memory.clearCache() + } + } + + continuation.finish() + } +} + +// MARK: - Token Iterator + +/// Single-batch (B=1) greedy MTP token iterator. Conforms to +/// ``TokenIteratorProtocol`` so callers can use the existing +/// ``generateTask(promptTokenCount:modelConfiguration:tokenizer:iterator:wiredMemoryTicket:)`` +/// entry point. +/// +/// Usage: +/// ```swift +/// let iter = try Gemma4MTPTokenIterator( +/// input: lmInput, +/// target: targetGemma4TextModel, +/// drafter: drafter, +/// parameters: GenerateParameters(maxTokens: 512, temperature: 0), +/// blockSize: 4) +/// let (stream, _) = generateTask( +/// promptTokenCount: lmInput.text.tokens.size, +/// modelConfiguration: modelContext.configuration, +/// tokenizer: modelContext.tokenizer, +/// iterator: iter) +/// for await gen in stream { ... } +/// ``` +/// +/// Supports greedy (`temperature=0`) and B=1 stochastic sampling via +/// rejection-based speculative sampling. +public struct Gemma4MTPTokenIterator: TokenIteratorProtocol { + + // Kept alive by the iterator so the GPU ops finish cleanly; not + // inspected from the outside. + private let target: Gemma4TextModel + private let drafter: Gemma4AssistantDraftModel + private var cache: [KVCache] + private let configuredBlockSize: Int + private let automaticPolicy: Gemma4MTPAutomaticPolicy? + private let temperature: Float + private let topP: Float + private let topK: Int + private let minP: Float + private var rngKey: MLXArray + + // MTP state - mutated each round. + private var bonus: Int + private var hidden: MLXArray + private var sharedKV: Gemma4SharedKV + + // Token stream state. + private var pendingTokens: [Int] = [] + private var pendingIndex: Int = 0 + + // TokenIteratorProtocol conformance. + public var tokenCount: Int = 0 + public let maxTokens: Int? + public var promptPrefillTime: TimeInterval = 0.0 + + /// Initialize - runs the prompt prefill and stages the first bonus. + /// The first token emitted by the iterator is the bonus sampled from + /// the last prefill position. + /// + /// - Parameters: + /// - input: prepared LM input. `input.text.tokens` is used for + /// prefill. + /// - target: the Gemma 4 target model. + /// - drafter: the MTP drafter. Will be bound to `target` on first + /// call (idempotent if already bound). + /// - cache: optional pre-allocated cache. If nil, allocated via + /// `target.newCache(parameters:)`. + /// - parameters: generation parameters. `maxTokens`, `temperature`, + /// `topP`, `topK`, `minP` are honored. At `temperature == 0` the + /// iterator uses the greedy walker (exact match with baseline). + /// At `temperature > 0` it uses rejection-based speculative + /// sampling with the same filter masks applied to both drafter + /// and target distributions. Emitted tokens match the distribution + /// that pure target sampling with the same filters would produce. + /// - blockSize: fixed speculative block size (2-16). Pass `nil` to use + /// the model-aware automatic policy, which may adapt the B=1 runtime + /// action as generation length grows. + /// - rngSeed: seed for rejection sampling (only used when + /// `temperature > 0`). Default 0 which seeds from the current MLX + /// random state. + /// - Throws: `Gemma4MTPError.invalidBlockSize` / bind errors. + public init( + input: LMInput, + target: Gemma4TextModel, + drafter: Gemma4AssistantDraftModel, + cache: [KVCache]? = nil, + parameters: GenerateParameters, + blockSize: Int? = nil, + rngSeed: UInt64 = 0 + ) throws { + let policy = Gemma4MTPAutomaticPolicy.automatic(for: target) + let resolvedBlockSize = blockSize + ?? policy.strategy(forBatchSize: 1).blockSize + guard resolvedBlockSize >= 2 && resolvedBlockSize <= 16 else { + throw Gemma4MTPError.invalidBlockSize(resolvedBlockSize) + } + try drafter.bind(target: target) + + self.target = target + self.drafter = drafter + self.cache = cache ?? target.newCache(parameters: parameters) + self.configuredBlockSize = resolvedBlockSize + self.automaticPolicy = blockSize == nil ? policy : nil + self.maxTokens = parameters.maxTokens + self.temperature = parameters.temperature + self.topP = parameters.topP + self.topK = parameters.topK + self.minP = parameters.minP + self.rngKey = rngSeed == 0 + ? MLXRandom.key(UInt64(Date().timeIntervalSince1970 * 1e6)) + : MLXRandom.key(rngSeed) + + // Prefill. + let prefillStart = Date() + var promptTokens = input.text.tokens + if promptTokens.ndim == 1 { + promptTokens = promptTokens[.newAxis, .ellipsis] + } + let prefillOut = target.forwardForMTP(promptTokens, cache: self.cache) + let lastLogits = prefillOut.logits[0..., -1, 0...] + let firstBonus: Int + if parameters.temperature == 0 { + let firstBonusArr = lastLogits.asType(.float32).argMax(axis: -1) + eval(firstBonusArr) + firstBonus = Int(firstBonusArr.item(Int32.self)) + } else { + // Sample the first bonus from the target's temperature-scaled + // softmax with the same filters the rest of the round loop + // will use. Split the rng key so the round loop gets fresh + // keys each call. + let keys = MLXRandom.split(key: self.rngKey, into: 2) + let idx = gemma4SampleLogitsWithFilters( + lastLogits, + temperature: parameters.temperature, + topP: parameters.topP, topK: parameters.topK, minP: parameters.minP, + rngKey: keys[0]) + eval(idx) + firstBonus = Int(idx.item(Int32.self)) + self.rngKey = keys[1] + } + self.bonus = firstBonus + self.hidden = prefillOut.lastHidden[ + 0..., -1 ..< prefillOut.lastHidden.dim(1), 0...] + self.sharedKV = prefillOut.capturedSharedKV + self.promptPrefillTime = -prefillStart.timeIntervalSinceNow + + // First emitted token is the prefill bonus. + self.pendingTokens.append(self.bonus) + } + + private mutating func nextTargetOnlyToken() -> Int? { + let input = MLXArray([Int32(bonus)])[.newAxis, .ellipsis] + let out = target.forwardForMTP(input, cache: cache) + let logits = out.logits[0..., -1, 0...] + let nextArr: MLXArray + if temperature == 0 { + nextArr = logits.asType(.float32).argMax(axis: -1) + } else { + let keys = MLXRandom.split(key: rngKey, into: 2) + nextArr = gemma4SampleLogitsWithFilters( + logits, + temperature: temperature, + topP: topP, topK: topK, minP: minP, + rngKey: keys[0]) + rngKey = keys[1] + } + + eval(nextArr) + let next = Int(nextArr.item(Int32.self)) + hidden = out.lastHidden[0..., -1 ..< out.lastHidden.dim(1), 0...] + sharedKV = out.capturedSharedKV + bonus = next + tokenCount += 1 + return next + } + + public mutating func next() -> Int? { + if let maxTokens, tokenCount >= maxTokens { + return nil + } + + // Drain pending tokens before the next round. + if pendingIndex < pendingTokens.count { + let t = pendingTokens[pendingIndex] + pendingIndex += 1 + tokenCount += 1 + return t + } + + // All drained - run one MTP round to refill. + pendingTokens.removeAll(keepingCapacity: true) + pendingIndex = 0 + let action = automaticPolicy?.singleStreamAction( + generatedTokens: tokenCount, maxTokens: maxTokens) + ?? .mtp(blockSize: configuredBlockSize) + if action == .targetOnly { + return nextTargetOnlyToken() + } + + guard case .mtp(let roundBlockSize) = action else { return nil } + let remaining = (maxTokens.map { $0 - tokenCount }) ?? roundBlockSize + guard remaining > 0 else { return nil } + let bs = Swift.min(roundBlockSize, remaining + 1) + if bs <= 1 { return nil } + let k = bs - 1 + + if temperature == 0 { + let round = runGemma4MTPGreedyRound( + target: target, + drafter: drafter, + cache: cache, + bonus: bonus, + hidden: hidden, + sharedKV: sharedKV, + blockSize: bs) + hidden = round.hidden + bonus = round.bonus + sharedKV = round.sharedKV + pendingTokens.append(contentsOf: round.tokens) + if pendingTokens.isEmpty { return nil } + let t = pendingTokens[pendingIndex] + pendingIndex += 1 + tokenCount += 1 + return t + } + + // Draft k tokens, GPU-resident. + // At temperature > 0 we also need to retain per-step drafter + // logits so the walker can compute q(c_i) for rejection sampling. + let driveOffset = cache[0].offset + let positionOffset = Gemma4.PositionOffset.scalar(driveOffset) + let masks = drafter.makeMasks( + queryLen: 1, + sharedKV: sharedKV, + positionOffset: positionOffset, + dtype: hidden.dtype) + var tok = MLXArray([Int32(bonus)])[.newAxis, .ellipsis] + var h = hidden + var draftPerStep: [MLXArray] = [] + var draftLogitsPerStep: [MLXArray] = [] // only populated when temperature > 0 + draftPerStep.reserveCapacity(k) + if temperature > 0 { + draftLogitsPerStep.reserveCapacity(k) + } + for _ in 0 ..< k { + let tokEmbed = target.embedTokensForDrafter(tok) + let inputsEmbeds = concatenated([tokEmbed, h], axis: -1) + let (newH, logits) = drafter( + inputsEmbeds: inputsEmbeds, + sharedKV: sharedKV, + positionOffset: positionOffset, + masks: masks) + let stepLogits = logits.squeezed(axis: 1) // [1, vocab] + let sampled: MLXArray + if temperature > 0 { + draftLogitsPerStep.append(stepLogits) + let keys = MLXRandom.split(key: rngKey, into: 2) + rngKey = keys[0] + sampled = gemma4SampleLogitsWithFilters( + stepLogits, + temperature: temperature, + topP: topP, topK: topK, minP: minP, + rngKey: keys[1]) + } else { + sampled = stepLogits.argMax(axis: -1) + } + let sampled2d = sampled[.newAxis, .ellipsis] + draftPerStep.append(sampled2d) + tok = sampled2d + h = newH + } + + // Verify. + let bonusCol = MLXArray([Int32(bonus)])[.newAxis, .ellipsis] + let verifyInput: MLXArray = + draftPerStep.isEmpty + ? bonusCol + : concatenated([bonusCol] + draftPerStep, axis: 1) + let verifyOut = target.forwardForMTP(verifyInput, cache: cache) + // fp32 argmax at verify to avoid bf16 near-uniform-tail argmax + // flips that would otherwise diverge from baseline. + let mainTokens = verifyOut.logits.asType(.float32).argMax(axis: -1) + let draftConcat: MLXArray = + draftPerStep.isEmpty + ? MLXArray.zeros([1, 0], dtype: .int32) + : concatenated(draftPerStep, axis: 1) + eval(mainTokens, draftConcat) + let mainInts = mainTokens.squeezed(axis: 0).asArray(Int.self) + let draftTokens = draftConcat.squeezed(axis: 0).asArray(Int32.self) + .map { Int($0) } + + // Walk: greedy or rejection-based depending on temperature. + let accepted: Int + let newTokens: [Int] + if temperature > 0 && k > 0 { + // Gather verify logits at positions 0..k (bs=k+1 positions). + let verifyLogits = verifyOut.logits.squeezed(axis: 0) // [bs, vocab] + // Stack drafter logits into [k, vocab]. + let draftLogits = concatenated(draftLogitsPerStep, axis: 0) + let keys = MLXRandom.split(key: rngKey, into: 2) + rngKey = keys[0] + let result = gemma4SpeculativeSampleRound( + draftLogits: draftLogits, + draftTokens: draftTokens, + verifyLogits: verifyLogits, + temperature: temperature, + topP: topP, topK: topK, minP: minP, + rngKey: keys[1]) + accepted = result.accepted + newTokens = result.emitted + } else { + var a = 0 + while a < k && draftTokens[a] == mainInts[a] { + a += 1 + } + accepted = a + newTokens = Array(mainInts[0 ..< a + 1]) + } + + // Rewind. + if accepted < k { + target.rollbackSpeculativeCache( + cache, accepted: .scalar(accepted), blockSize: bs) + } + + // Update state. + hidden = verifyOut.lastHidden[0..., accepted ..< accepted + 1, 0...] + bonus = newTokens.last! + let rejected = k - accepted + sharedKV = Gemma4SharedKV.sliceTail( + from: verifyOut.capturedSharedKV, rejected: rejected) + + pendingTokens.append(contentsOf: newTokens) + if pendingTokens.isEmpty { return nil } + let t = pendingTokens[pendingIndex] + pendingIndex += 1 + tokenCount += 1 + return t + } +} + +// MARK: - Generation API + +/// Generate text from a Gemma 4 target using a Gemma 4 MTP drafter. +/// +/// Internally wraps ``Gemma4MTPTokenIterator`` and a tokenizer-decoding +/// loop, producing an `AsyncStream` that yields decoded text +/// chunks and a terminal `.info(...)` with counts. +/// +/// - Parameters: +/// - input: prepared language-model input. `input.text.tokens` is used +/// for prefill; images/videos are ignored (MTP is text-only). +/// - parameters: generation parameters. `maxTokens` caps output length +/// (defaults to 1024 if nil). `temperature > 0` enables stochastic +/// rejection-based speculative sampling; `temperature == 0` is +/// greedy and produces byte-identical output to no-drafter baseline. +/// - target: `ModelContext` whose `model` is a `Gemma4TextModel` (or a +/// `Gemma4Model` VLM wrapper whose text portion is `Gemma4TextModel`). +/// Throws `unsupportedTarget` otherwise. +/// - drafter: the loaded Gemma 4 MTP drafter. +/// - blockSize: fixed speculative block size (2-16). Pass `nil` to use +/// the model-aware automatic policy, which may adapt the B=1 runtime +/// action as generation length grows. +/// - rngSeed: seed for stochastic sampling (only consulted when +/// `parameters.temperature > 0`). Default 0 -> seeds from the system +/// clock. +/// - Returns: an `AsyncStream` yielding `.chunk(String)` +/// (decoded token text) and one terminal `.info(...)`. +/// - Throws: `Gemma4MTPError.unsupportedTarget`, `.invalidBlockSize`, +/// or any error thrown by `drafter.bind(target:)`. +public func generateGemma4MTP( + input: LMInput, + parameters: GenerateParameters, + target: ModelContext, + drafter: Gemma4AssistantDraftModel, + blockSize: Int? = nil, + rngSeed: UInt64 = 0 +) throws -> AsyncStream { + let gemma4: Gemma4TextModel + if let t = target.model as? Gemma4TextModel { + gemma4 = t + } else if let wrapper = target.model as? Gemma4Model { + gemma4 = wrapper.textModel + } else { + throw Gemma4MTPError.unsupportedTarget( + String(describing: type(of: target.model))) + } + + let tokenizer = target.tokenizer + let eosIds = target.configuration.eosTokenIds + var params = parameters + if params.maxTokens == nil { + params.maxTokens = 1024 + } + let promptTokenCount = input.text.tokens.size + + let policy = Gemma4MTPAutomaticPolicy.automatic(for: gemma4) + if blockSize == nil && !policy.enablesAutomaticMTP { + return try generate(input: input, parameters: params, context: target) + } + + // Build the iterator outside the stream closure so init errors can + // throw synchronously. Prefill runs inside init. + let iter = try Gemma4MTPTokenIterator( + input: input, + target: gemma4, + drafter: drafter, + parameters: params, + blockSize: blockSize, + rngSeed: rngSeed + ) + let prefillElapsed = iter.promptPrefillTime + + // Wrap the iterator in a Sendable box so we can move it into the + // stream closure without tripping strict concurrency (the iterator + // holds MLXArray state which is `@unchecked Sendable`-compatible but + // isn't annotated yet). + let boxed = IteratorBox(iter: iter) + + return AsyncStream { continuation in + let task = Task { + let generateStart = Date() + var tokenCount = 0 + var stopReason: GenerateStopReason = .length + while let tok = boxed.next() { + tokenCount += 1 + continuation.yield(.chunk(tokenizer.decode(tokenIds: [tok]))) + if eosIds.contains(tok) { + stopReason = .stop + break + } + if Task.isCancelled { + stopReason = .cancelled + break + } + } + let elapsed = Date().timeIntervalSince(generateStart) + let info = GenerateCompletionInfo( + promptTokenCount: promptTokenCount, + generationTokenCount: tokenCount, + promptTime: prefillElapsed, + generationTime: elapsed, + stopReason: stopReason + ) + continuation.yield(.info(info)) + continuation.finish() + } + continuation.onTermination = { _ in + task.cancel() + } + } +} + +/// Box wrapping a `Gemma4MTPTokenIterator` so it can be captured by a +/// `Sendable` closure. The iterator itself holds `MLXArray` state which +/// is conceptually reference-counted GPU memory - safe to move across +/// tasks, but the Swift compiler needs an explicit `@unchecked`. +private final class IteratorBox: @unchecked Sendable { + private var iter: Gemma4MTPTokenIterator + init(iter: Gemma4MTPTokenIterator) { + self.iter = iter + } + func next() -> Int? { + iter.next() + } +} diff --git a/Libraries/MLXLLM/Models/Gemma4Text.swift b/Libraries/MLXLLM/Models/Gemma4Text.swift index c08b024b00..33b2ddd99f 100644 --- a/Libraries/MLXLLM/Models/Gemma4Text.swift +++ b/Libraries/MLXLLM/Models/Gemma4Text.swift @@ -11,44 +11,56 @@ import MLXNN // MARK: - Configuration +struct Gemma4WeightQuantizationMetadata: Codable, Sendable { + var bits: Int? + var groupSize: Int? + + enum CodingKeys: String, CodingKey { + case bits + case groupSize = "group_size" + } +} + public struct Gemma4TextConfiguration: Codable, Sendable { - var modelType: String = "gemma4_text" - var hiddenSize: Int = 1536 - var numHiddenLayers: Int = 35 - var intermediateSize: Int = 6144 - var numAttentionHeads: Int = 8 - var headDim: Int = 256 - var globalHeadDim: Int = 512 - var globalPartialRotaryFactor: Float = 0.25 - var rmsNormEps: Float = 1e-6 - var vocabSize: Int = 262144 - var vocabSizePerLayerInput: Int = 262144 - var numKeyValueHeads: Int = 1 - var numGlobalKeyValueHeads: Int? - var numKvSharedLayers: Int = 20 - var hiddenSizePerLayerInput: Int = 256 - var slidingWindow: Int = 512 - var slidingWindowPattern: Int = 5 - var maxPositionEmbeddings: Int = 131072 - var attentionKeqV: Bool = false - var finalLogitSoftcapping: Float = 30.0 - var useDoubleWideMlp: Bool = true - var layerTypes: [String] = [] - var tieWordEmbeddings: Bool = true + public internal(set) var modelType: String = "gemma4_text" + public internal(set) var hiddenSize: Int = 1536 + public internal(set) var numHiddenLayers: Int = 35 + public internal(set) var intermediateSize: Int = 6144 + public internal(set) var numAttentionHeads: Int = 8 + public internal(set) var headDim: Int = 256 + public internal(set) var globalHeadDim: Int = 512 + public internal(set) var globalPartialRotaryFactor: Float = 0.25 + public internal(set) var rmsNormEps: Float = 1e-6 + public internal(set) var vocabSize: Int = 262144 + public internal(set) var vocabSizePerLayerInput: Int = 262144 + public internal(set) var numKeyValueHeads: Int = 1 + public internal(set) var numGlobalKeyValueHeads: Int? + public var numKvSharedLayers: Int = 20 + public internal(set) var hiddenSizePerLayerInput: Int = 256 + public internal(set) var slidingWindow: Int = 512 + public internal(set) var slidingWindowPattern: Int = 5 + public internal(set) var maxPositionEmbeddings: Int = 131072 + public internal(set) var attentionKeqV: Bool = false + public internal(set) var finalLogitSoftcapping: Float = 30.0 + public internal(set) var useDoubleWideMlp: Bool = true + public internal(set) var layerTypes: [String] = [] + public internal(set) var tieWordEmbeddings: Bool = true + public internal(set) var quantizationBits: Int? + public internal(set) var quantizationGroupSize: Int? // MoE (only set on the 26B-A4B variant; 2B/4B/31B are dense) - var enableMoeBlock: Bool = false - var numExperts: Int? - var topKExperts: Int? - var moeIntermediateSize: Int? + public internal(set) var enableMoeBlock: Bool = false + public internal(set) var numExperts: Int? + public internal(set) var topKExperts: Int? + public internal(set) var moeIntermediateSize: Int? // RoPE parameters (nested dict with full_attention/sliding_attention sub-configs) - var ropeParameters: [String: [String: StringOrNumber]]? + public internal(set) var ropeParameters: [String: [String: StringOrNumber]]? // Derived properties - var slidingRopeTheta: Float = 10000.0 - var fullRopeTheta: Float = 1_000_000.0 - var fullPartialRotaryFactor: Float = 1.0 + public internal(set) var slidingRopeTheta: Float = 10000.0 + public internal(set) var fullRopeTheta: Float = 1_000_000.0 + public internal(set) var fullPartialRotaryFactor: Float = 1.0 enum CodingKeys: String, CodingKey { case modelType = "model_type" @@ -81,8 +93,14 @@ public struct Gemma4TextConfiguration: Codable, Sendable { case moeIntermediateSize = "moe_intermediate_size" } + enum QuantizationCodingKeys: String, CodingKey { + case quantization + case quantizationConfig = "quantization_config" + } + public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) + let quantizationContainer = try decoder.container(keyedBy: QuantizationCodingKeys.self) self.modelType = try container.decodeIfPresent(String.self, forKey: .modelType) ?? "gemma4_text" @@ -137,6 +155,13 @@ public struct Gemma4TextConfiguration: Codable, Sendable { } self.tieWordEmbeddings = try container.decodeIfPresent(Bool.self, forKey: .tieWordEmbeddings) ?? true + let quantization = + try quantizationContainer.decodeIfPresent( + Gemma4WeightQuantizationMetadata.self, forKey: .quantization) + ?? quantizationContainer.decodeIfPresent( + Gemma4WeightQuantizationMetadata.self, forKey: .quantizationConfig) + self.quantizationBits = quantization?.bits + self.quantizationGroupSize = quantization?.groupSize self.ropeParameters = try container.decodeIfPresent( [String: [String: StringOrNumber]].self, forKey: .ropeParameters) @@ -163,6 +188,24 @@ public struct Gemma4TextConfiguration: Codable, Sendable { } } +extension Gemma4TextConfiguration { + + /// Predicate for whether a layer uses shared K/V (consuming it from an + /// earlier layer rather than projecting its own). + /// + /// A layer is shared when either: + /// - `forceSharedKV` is true (drafter / assistant models where every layer + /// borrows K/V from the target), or + /// - the config declares `numKvSharedLayers > 0` AND this layer's index + /// falls within the trailing shared block. + public func layerUsesSharedKV(layerIdx: Int, forceSharedKV: Bool = false) -> Bool { + if forceSharedKV { return true } + guard numKvSharedLayers > 0 else { return false } + let firstShared = numHiddenLayers - numKvSharedLayers + return layerIdx >= firstShared + } +} + // MARK: - Helper Modules private class RMSNormNoScale: Module { @@ -193,12 +236,8 @@ private class ScaledLinear: Module { } } -private enum Gemma4PositionOffset { - case scalar(Int) - case batch(MLXArray) -} - -private func gemma4CapturePositionOffset(from cache: KVCache?) -> Gemma4PositionOffset { +@inline(__always) +internal func gemma4CapturePositionOffset(from cache: KVCache?) -> Gemma4.PositionOffset { if let batchCache = cache as? BatchPositionedKVCache { // Snapshot the per-sequence offsets before cache.update(...) advances them. .batch(batchCache.batchOffset + 0) @@ -207,10 +246,11 @@ private func gemma4CapturePositionOffset(from cache: KVCache?) -> Gemma4Position } } -private func gemma4ApplyRotaryPosition( +@inline(__always) +internal func gemma4ApplyRotaryPosition( _ rope: R, to x: MLXArray, - offset: Gemma4PositionOffset + offset: Gemma4.PositionOffset ) -> MLXArray { switch offset { case .scalar(let value): @@ -220,6 +260,71 @@ private func gemma4ApplyRotaryPosition( } } +private func gemma4AttentionFallback( + queries: MLXArray, + keys: MLXArray, + values: MLXArray, + scale: Float, + mask: MLXFast.ScaledDotProductAttentionMaskMode +) -> MLXArray { + let (B, nQHeads, L, D) = ( + queries.dim(0), queries.dim(1), queries.dim(2), queries.dim(3) + ) + let nKVHeads = keys.dim(1) + let repeats = nQHeads / nKVHeads + + var q = queries * scale + var k = keys + var v = values + if repeats > 1 { + q = q.reshaped([B, nKVHeads, repeats, L, D]) + k = expandedDimensions(k, axis: 2) + v = expandedDimensions(v, axis: 2) + } + + var scores = matmul(q, k.swappedAxes(-1, -2)) + + func applyMask(_ maskArray: MLXArray) { + var mask = maskArray + if scores.ndim == 5 && mask.ndim == 4 && mask.dim(0) == scores.dim(0) { + mask = expandedDimensions(mask, axis: 2) + } + if mask.dtype == .bool { + scores = MLX.where( + mask, scores, MLXArray(-Float.infinity, dtype: scores.dtype)) + } else { + scores = scores + mask + } + } + + switch mask { + case .none: + break + case .causal: + let qL = scores.dim(-2) + let kL = scores.dim(-1) + let qIndices = MLXArray(0 ..< qL) + MLXArray(kL - qL) + let kIndices = MLXArray(0 ..< kL) + let causalMask = greaterEqual( + expandedDimensions(qIndices, axis: -1), + expandedDimensions(kIndices, axis: -2)) + applyMask(causalMask) + case .array(let maskArray): + applyMask(maskArray) + case .arrays(let maskArrays): + if let maskArray = maskArrays.first { + applyMask(maskArray) + } + } + + scores = softmax(scores.asType(.float32), axis: -1, precise: true).asType(scores.dtype) + var output = matmul(scores, v) + if repeats > 1 { + output = output.reshaped([B, nQHeads, L, values.dim(3)]) + } + return output +} + // MARK: - Attention private class Gemma4Attention: Module { @@ -245,13 +350,13 @@ private class Gemma4Attention: Module { @ModuleInfo var rope: RoPELayer - init(_ config: Gemma4TextConfiguration, layerIdx: Int) { + init(_ config: Gemma4TextConfiguration, layerIdx: Int, forceSharedKV: Bool = false) { self.config = config self.layerIdx = layerIdx self.layerType = config.layerTypes[layerIdx] self.isSliding = layerType == "sliding_attention" - let firstKvSharedLayerIdx = config.numHiddenLayers - config.numKvSharedLayers - self.usesSharedKV = layerIdx >= firstKvSharedLayerIdx && firstKvSharedLayerIdx > 0 + self.usesSharedKV = config.layerUsesSharedKV( + layerIdx: layerIdx, forceSharedKV: forceSharedKV) // Full attention uses globalHeadDim, sliding uses headDim self.effectiveHeadDim = @@ -306,8 +411,8 @@ private class Gemma4Attention: Module { mask: MLXFast.ScaledDotProductAttentionMaskMode? = nil, cache: KVCache? = nil, sharedKV: (MLXArray, MLXArray)? = nil, - positionOffset: Gemma4PositionOffset? = nil - ) -> (MLXArray, (MLXArray, MLXArray), Gemma4PositionOffset) { + positionOffset: Gemma4.PositionOffset? = nil + ) -> (MLXArray, (MLXArray, MLXArray), Gemma4.PositionOffset) { let (B, L, _) = (x.dim(0), x.dim(1), x.dim(2)) var queries = qProj(x).reshaped(B, L, nHeads, effectiveHeadDim) @@ -366,13 +471,33 @@ private class Gemma4Attention: Module { } } - let output = MLXFast.scaledDotProductAttention( - queries: queries, - keys: keys, - values: values, - scale: scale, - mask: adjustedMask ?? .none - ) + let hasCachedPrefix: Bool + switch activePositionOffset { + case .scalar(let offset): + hasCachedPrefix = offset > 0 + case .batch: + hasCachedPrefix = true + } + + let attention: MLXArray + if L > 1 && hasCachedPrefix { + attention = gemma4AttentionFallback( + queries: queries, + keys: keys, + values: values, + scale: scale, + mask: adjustedMask ?? .none) + } else { + attention = MLXFast.scaledDotProductAttention( + queries: queries, + keys: keys, + values: values, + scale: scale, + mask: adjustedMask ?? .none + ) + } + + let output = attention .transposed(0, 2, 1, 3) .reshaped(B, L, -1) @@ -461,8 +586,7 @@ private class Gemma4MLP: Module { @ModuleInfo(key: "down_proj") var downProj: Linear init(_ config: Gemma4TextConfiguration, layerIdx: Int) { - let firstKvSharedLayerIdx = config.numHiddenLayers - config.numKvSharedLayers - let isKvSharedLayer = layerIdx >= firstKvSharedLayerIdx && firstKvSharedLayerIdx > 0 + let isKvSharedLayer = config.layerUsesSharedKV(layerIdx: layerIdx) let useDoubleWide = config.useDoubleWideMlp && isKvSharedLayer let intermediateSize = config.intermediateSize * (useDoubleWide ? 2 : 1) @@ -480,22 +604,27 @@ private class Gemma4MLP: Module { // MARK: - Decoder Layer -private class Gemma4DecoderLayer: Module { +/// Gemma 4 decoder layer. Combines `Gemma4Attention` with an MLP (or MoE) +/// block, the per-layer-input (PLE) path, and residual / layer-scalar +/// plumbing. Consumed by `Gemma4TextModelInner` and by the Gemma 4 MTP +/// drafter's trunk in `Gemma4MTP`; not intended as a user-facing +/// composable layer. +public class Gemma4DecoderLayer: Module { let config: Gemma4TextConfiguration let layerIdx: Int let layerType: String let hiddenSizePerLayerInput: Int - @ModuleInfo(key: "self_attn") var selfAttn: Gemma4Attention - @ModuleInfo var mlp: Gemma4MLP + @ModuleInfo(key: "self_attn") fileprivate var selfAttn: Gemma4Attention + @ModuleInfo fileprivate var mlp: Gemma4MLP @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 // MoE-only modules (26B-A4B); nil on dense variants. - @ModuleInfo(key: "router") var router: Gemma4Router? - @ModuleInfo(key: "experts") var experts: Gemma4Experts? + @ModuleInfo(key: "router") fileprivate var router: Gemma4Router? + @ModuleInfo(key: "experts") fileprivate var experts: Gemma4Experts? @ModuleInfo(key: "post_feedforward_layernorm_1") var postFeedforwardLayernorm1: RMSNorm? @ModuleInfo(key: "pre_feedforward_layernorm_2") var preFeedforwardLayernorm2: RMSNorm? @ModuleInfo(key: "post_feedforward_layernorm_2") var postFeedforwardLayernorm2: RMSNorm? @@ -510,14 +639,15 @@ private class Gemma4DecoderLayer: Module { let isMoE: Bool - init(_ config: Gemma4TextConfiguration, layerIdx: Int) { + public init(_ config: Gemma4TextConfiguration, layerIdx: Int, forceSharedKV: Bool = false) { self.config = config self.layerIdx = layerIdx self.layerType = config.layerTypes[layerIdx] self.hiddenSizePerLayerInput = config.hiddenSizePerLayerInput self.isMoE = config.enableMoeBlock - self._selfAttn.wrappedValue = Gemma4Attention(config, layerIdx: layerIdx) + self._selfAttn.wrappedValue = Gemma4Attention( + config, layerIdx: layerIdx, forceSharedKV: forceSharedKV) self._mlp.wrappedValue = Gemma4MLP(config, layerIdx: layerIdx) self._inputLayernorm.wrappedValue = RMSNorm( @@ -554,14 +684,14 @@ private class Gemma4DecoderLayer: Module { super.init() } - func callAsFunction( + public func callAsFunction( _ x: MLXArray, mask: MLXFast.ScaledDotProductAttentionMaskMode? = nil, cache: KVCache? = nil, perLayerInput: MLXArray? = nil, sharedKV: (MLXArray, MLXArray)? = nil, - positionOffset: Gemma4PositionOffset? = nil - ) -> (MLXArray, (MLXArray, MLXArray), Gemma4PositionOffset) { + positionOffset: Gemma4.PositionOffset? = nil + ) -> (MLXArray, (MLXArray, MLXArray), Gemma4.PositionOffset) { let residual = x let h = inputLayernorm(x) @@ -621,25 +751,35 @@ private class Gemma4DecoderLayer: Module { // MARK: - Text Model -private class Gemma4TextModelInner: Module { +/// Inner Gemma 4 trunk: embeddings + per-layer-input (PLE) + 35 decoder +/// layers + final norm. Public so the Gemma 4 MTP drafter in +/// `Gemma4MTP` can build its own 4-layer kv-shared trunk; not +/// intended as a user-facing model — use `Gemma4TextModel` for +/// standalone inference. +public class Gemma4TextModelInner: Module { let config: Gemma4TextConfiguration let embedScale: Float let hiddenSizePerLayerInput: Int - @ModuleInfo(key: "embed_tokens") var embedTokens: Embedding - @ModuleInfo(key: "layers") var layers: [Gemma4DecoderLayer] - @ModuleInfo var norm: RMSNorm + @ModuleInfo(key: "embed_tokens") public var embedTokens: Embedding + @ModuleInfo(key: "layers") public var layers: [Gemma4DecoderLayer] + @ModuleInfo public var norm: RMSNorm // Per-layer embeddings (PLE) @ModuleInfo(key: "embed_tokens_per_layer") var embedTokensPerLayer: Embedding? - @ModuleInfo(key: "per_layer_model_projection") var perLayerModelProjection: ScaledLinear? + @ModuleInfo(key: "per_layer_model_projection") fileprivate var perLayerModelProjection: ScaledLinear? @ModuleInfo(key: "per_layer_projection_norm") var perLayerProjectionNorm: RMSNorm? // KV sharing mapping: for each layer, which earlier layer provides KVs let previousKvs: [Int] let firstKvSharedLayerIdx: Int - init(_ config: Gemma4TextConfiguration) { + /// Index of the last non-shared full-attention layer (-1 if none). + /// Used by the shared-KV capture hook for the MTP drafter. + let lastFullAttentionNonSharedIdx: Int + let lastSlidingAttentionNonSharedIdx: Int + + public init(_ config: Gemma4TextConfiguration, forceSharedKV: Bool = false) { self.config = config self.embedScale = Float(config.hiddenSize).squareRoot() self.hiddenSizePerLayerInput = config.hiddenSizePerLayerInput @@ -647,7 +787,7 @@ private class Gemma4TextModelInner: Module { self._embedTokens.wrappedValue = Embedding( embeddingCount: config.vocabSize, dimensions: config.hiddenSize) self._layers.wrappedValue = (0 ..< config.numHiddenLayers).map { - Gemma4DecoderLayer(config, layerIdx: $0) + Gemma4DecoderLayer(config, layerIdx: $0, forceSharedKV: forceSharedKV) } self._norm.wrappedValue = RMSNorm(dimensions: config.hiddenSize, eps: config.rmsNormEps) @@ -682,13 +822,52 @@ private class Gemma4TextModelInner: Module { } self.previousKvs = kvMap + // Capture indices for MTP drafter: the last layer of each type that + // still has its own K/V (not shared from an earlier layer). + let firstShared = self.firstKvSharedLayerIdx + var lastFull = -1 + var lastSliding = -1 + for i in 0 ..< firstShared { + if config.layerTypes[i] == "full_attention" { lastFull = i } + if config.layerTypes[i] == "sliding_attention" { lastSliding = i } + } + self.lastFullAttentionNonSharedIdx = lastFull + self.lastSlidingAttentionNonSharedIdx = lastSliding + super.init() } - func callAsFunction( + public func callAsFunction( _ inputs: MLXArray, - cache: [KVCache]? = nil + cache: [KVCache]? = nil, + captureHook: ((Int, (MLXArray, MLXArray)) -> Void)? = nil ) -> MLXArray { + forwardTrunk( + inputs, cache: cache, captureHook: captureHook, capturePreNorm: false + ).postNorm + } + + /// Variant that ALSO returns the pre-norm last-layer hidden state. + /// The MTP drafter's `pre_projection` was trained against the pre-norm + /// hidden (HF captures `hidden_states` at the decoder-layer boundary, + /// BEFORE `model.norm`); the LM head consumes the post-norm hidden. + /// The non-MTP path goes through `callAsFunction`. + public func callCapturingPreNorm( + _ inputs: MLXArray, + cache: [KVCache]? = nil, + captureHook: ((Int, (MLXArray, MLXArray)) -> Void)? = nil + ) -> (postNorm: MLXArray, preNorm: MLXArray) { + let r = forwardTrunk( + inputs, cache: cache, captureHook: captureHook, capturePreNorm: true) + return (r.postNorm, r.preNorm!) + } + + private func forwardTrunk( + _ inputs: MLXArray, + cache: [KVCache]?, + captureHook: ((Int, (MLXArray, MLXArray)) -> Void)?, + capturePreNorm: Bool + ) -> (postNorm: MLXArray, preNorm: MLXArray?) { let inputEmbeddings = embedTokens(inputs) var h = inputEmbeddings * embedScale @@ -737,7 +916,7 @@ private class Gemma4TextModelInner: Module { fullCache = Array(repeating: nil, count: config.numHiddenLayers) } - // Build masks: one per attention type + // Build masks: one per attention type. var maskByType = [String: MLXFast.ScaledDotProductAttentionMaskMode]() for (i, layer) in layers.enumerated() { let lt = layer.layerType @@ -752,7 +931,7 @@ private class Gemma4TextModelInner: Module { } // Forward through layers, tracking intermediate KV pairs for sharing - var intermediates = [(kv: (MLXArray, MLXArray)?, positionOffset: Gemma4PositionOffset?)]( + var intermediates = [(kv: (MLXArray, MLXArray)?, positionOffset: Gemma4.PositionOffset?)]( repeating: (nil, nil), count: config.numHiddenLayers) for (idx, layer) in layers.enumerated() { @@ -771,9 +950,11 @@ private class Gemma4TextModelInner: Module { ) h = out intermediates[idx] = (kvPair, positionOffset) + captureHook?(idx, kvPair) } - return norm(h) + let postNorm = norm(h) + return (postNorm, capturePreNorm ? h : nil) } } @@ -784,7 +965,11 @@ public class Gemma4TextModel: Module, LLMModel, KVCacheDimensionProvider { public let kvHeads: [Int] fileprivate let config: Gemma4TextConfiguration - fileprivate let model: Gemma4TextModelInner + let model: Gemma4TextModelInner + + /// Read-only accessor for the underlying text configuration. Needed by + /// `Gemma4AssistantDraftModel` for its bind-time compatibility checks. + public var configuration: Gemma4TextConfiguration { config } @ModuleInfo(key: "lm_head") var lmHead: Linear? @@ -800,16 +985,50 @@ public class Gemma4TextModel: Module, LLMModel, KVCacheDimensionProvider { } public func callAsFunction(_ inputs: MLXArray, cache: [KVCache]?) -> MLXArray { - var out = model(inputs, cache: cache) + let hidden = model(inputs, cache: cache) + return applyLMHead(hidden) + } + + /// Apply the LM head (tied embedding or explicit `lm_head`) plus the + /// configured final-logit softcap. Pure function of the post-norm hidden. + func applyLMHead(_ hidden: MLXArray) -> MLXArray { + var out: MLXArray if let lmHead { - out = lmHead(out) + out = lmHead(hidden) } else { - out = model.embedTokens.asLinear(out) + out = model.embedTokens.asLinear(hidden) } out = tanh(out / config.finalLogitSoftcapping) * config.finalLogitSoftcapping return out } + /// Compute the scaled input embedding for `tokens`, matching what the + /// inner trunk does in its first step (`embedTokens(inputs) * embedScale`). + /// Used by `Gemma4AssistantDraftModel` as the "target embedding" input + /// when building its drafter-step input `[target_embed(last_token), last_hidden]`. + public func embedTokensForDrafter(_ tokens: MLXArray) -> MLXArray { + model.embedTokens(tokens) * Float(config.hiddenSize).squareRoot() + } + + /// Internal helper for Gemma4CaptureHookTests. Not part of the public API. + internal func _testCallInner( + _ inputs: MLXArray, + cache: [KVCache], + captureHook: ((Int, (MLXArray, MLXArray)) -> Void)? = nil + ) -> MLXArray { + model(inputs, cache: cache, captureHook: captureHook) + } + + /// Parse the layer index out of a weight key like + /// `"model.layers.15.self_attn.k_proj.weight"`. Returns nil if the key + /// doesn't match the expected `...layers....` pattern. + private func extractLayerIdx(from key: String) -> Int? { + guard let layersRange = key.range(of: "layers.") else { return nil } + let after = key[layersRange.upperBound...] + let end = after.firstIndex(of: ".") ?? after.endIndex + return Int(after[.. [String: MLXArray] { var sanitized = [String: MLXArray]() for (k, v) in weights { @@ -823,6 +1042,21 @@ public class Gemma4TextModel: Module, LLMModel, KVCacheDimensionProvider { continue } + // Skip k_proj/v_proj/k_norm/v_norm weights for layers that + // borrow K/V from an earlier non-shared layer (num_kv_shared_layers + // tail). Our `Gemma4Attention.init` doesn't allocate these modules + // for shared-KV layers, so the checkpoint's copies would fail the + // strict `update(parameters:verify:.all)` check. + if let layerIdx = extractLayerIdx(from: k), + config.layerUsesSharedKV(layerIdx: layerIdx), + k.contains(".self_attn.k_proj.") + || k.contains(".self_attn.v_proj.") + || k.contains(".self_attn.k_norm.") + || k.contains(".self_attn.v_norm.") + { + continue + } + // 26B-A4B checkpoints ship the experts as a fused // `gate_up_proj` (concatenated along axis -2) plus a separate // `down_proj`. SwitchGLU expects three separate diff --git a/Libraries/MLXLLM/Models/Qwen35.swift b/Libraries/MLXLLM/Models/Qwen35.swift index 15fcd6556c..c43546fbf2 100644 --- a/Libraries/MLXLLM/Models/Qwen35.swift +++ b/Libraries/MLXLLM/Models/Qwen35.swift @@ -49,6 +49,11 @@ public struct Qwen35TextConfiguration: Codable, Sendable { var moeIntermediateSize: Int = 0 var normTopkProb: Bool = true + // MTP — number of Multi-Token Prediction head layers. + // Port of omlx commit 696d90a: patches/mlx_lm_mtp/qwen35_model.py + // `_patch_text_model_args` attaches this from config.json at runtime. + var mtpNumHiddenLayers: Int = 0 + enum CodingKeys: String, CodingKey { case modelType = "model_type" case hiddenSize = "hidden_size" @@ -77,6 +82,7 @@ public struct Qwen35TextConfiguration: Codable, Sendable { case sharedExpertIntermediateSize = "shared_expert_intermediate_size" case moeIntermediateSize = "moe_intermediate_size" case normTopkProb = "norm_topk_prob" + case mtpNumHiddenLayers = "mtp_num_hidden_layers" } public init(from decoder: Decoder) throws { @@ -129,6 +135,8 @@ public struct Qwen35TextConfiguration: Codable, Sendable { self.moeIntermediateSize = try container.decodeIfPresent(Int.self, forKey: .moeIntermediateSize) ?? 0 self.normTopkProb = try container.decodeIfPresent(Bool.self, forKey: .normTopkProb) ?? true + self.mtpNumHiddenLayers = + try container.decodeIfPresent(Int.self, forKey: .mtpNumHiddenLayers) ?? 0 let ropeContainer = try decoder.container(keyedBy: RopeParametersCodingKey.self) let ropeParameters = try ropeContainer.decodeIfPresent( @@ -225,35 +233,38 @@ final class Qwen35GatedDeltaNet: Module { super.init() } - func callAsFunction( - _ inputs: MLXArray, - mask: MLXArray? = nil, - cache: MambaCache? = nil - ) -> MLXArray { - let B = inputs.dim(0) - let S = inputs.dim(1) - - var qkv = inProjQKV(inputs) - let z = inProjZ(inputs).reshaped(B, S, numVHeads, headVDim) - let b = inProjB(inputs) - let a = inProjA(inputs) - - let convState: MLXArray - if let cacheState = cache?[0] { - convState = cacheState - } else { - convState = MLXArray.zeros([B, convKernelSize - 1, convDim], dtype: inputs.dtype) - } - - if let mask { - qkv = MLX.where(mask[.ellipsis, .newAxis], qkv, 0) - } + // MARK: - _processChunk (MTP helper) + + /// Process one time-chunk of the linear-attention layer. + /// + /// Extracted from `callAsFunction` so the MTP verify cycle can run the prefix + /// (n_confirmed tokens) and draft suffix separately, snapshotting the SSM/conv + /// state in between for rollback on draft rejection. + /// + /// Port of omlx commit 696d90a: + /// patches/mlx_lm_mtp/qwen35_model.py `GatedDeltaNet._process_chunk` + /// + /// - Parameters: + /// - qkv: Already-masked QKV for this chunk [B, S_chunk, conv_dim] + /// - a, b: Input projections for this chunk [B, S_chunk, ...] + /// - convState: Initial conv state [B, conv_kernel_size-1, conv_dim] + /// - ssmState: Initial SSM state (nil on first token) + /// - mask: SSM mask for `gatedDeltaUpdate` (optional) + /// - Returns: `(out, newConvState, newSsmState)` + private func processChunk( + qkv: MLXArray, + a: MLXArray, + b: MLXArray, + convState: MLXArray, + ssmState: MLXArray?, + mask: MLXArray? + ) -> (out: MLXArray, newConvState: MLXArray, newSsmState: MLXArray) { + let B = qkv.dim(0) + let S = qkv.dim(1) let convInput = concatenated([convState, qkv], axis: 1) - if let cache { - cache[0] = convInput[0..., (-(convKernelSize - 1))...] - } - + let nKeep = convKernelSize - 1 + let newConvState = convInput[0..., (convInput.dim(1) - nKeep)...] let convOut = silu(conv1d(convInput)) let convSplit = MLX.split(convOut, indices: [keyDim, 2 * keyDim], axis: -1) @@ -261,7 +272,6 @@ final class Qwen35GatedDeltaNet: Module { let k = convSplit[1].reshaped(B, S, numKHeads, headKDim) let v = convSplit[2].reshaped(B, S, numVHeads, headVDim) - var state = cache?[1] let dtype = q.dtype let invScale = pow(Float(headKDim), -0.5) let qNormed = @@ -271,9 +281,7 @@ final class Qwen35GatedDeltaNet: Module { MLXArray(invScale).asType(dtype) * MLXFast.rmsNorm(k, weight: MLXArray.mlxNone, eps: 1e-6) - var out: MLXArray - - (out, state) = gatedDeltaUpdate( + let (out, newSsmState) = gatedDeltaUpdate( q: qNormed, k: kNormed, v: v, @@ -281,16 +289,97 @@ final class Qwen35GatedDeltaNet: Module { b: b, aLog: aLog, dtBias: dtBias, - state: state, + state: ssmState, mask: mask ) + return (out, newConvState, newSsmState) + } + + // MARK: - callAsFunction + + func callAsFunction( + _ inputs: MLXArray, + mask: MLXArray? = nil, + cache: MambaCache? = nil, + nConfirmed: Int = 0 + ) -> MLXArray { + // Port of omlx commit 696d90a: + // patches/mlx_lm_mtp/qwen35_model.py GatedDeltaNet.__call__ + let B = inputs.dim(0) + let S = inputs.dim(1) + + var qkv = inProjQKV(inputs) + let z = inProjZ(inputs).reshaped(B, S, numVHeads, headVDim) + let b = inProjB(inputs) + let a = inProjA(inputs) + + let convState: MLXArray + if let cacheState = cache?[0] { + convState = cacheState + } else { + convState = MLXArray.zeros([B, convKernelSize - 1, convDim], dtype: inputs.dtype) + } + + // Apply mask to full qkv before any chunking. + if let mask { + qkv = MLX.where(mask[.ellipsis, .newAxis], qkv, 0) + } + + let ssmState = cache?[1] + let out: MLXArray + let finalConvState: MLXArray + let finalSsmState: MLXArray + + if nConfirmed > 0 && nConfirmed < S { + // Split at nConfirmed boundary for the MTP 2-token verify forward. + // Run confirmed prefix first, snapshot rollback state, then run draft. + // omlx: GatedDeltaNet.__call__ nConfirmed > 0 branch + let maskC = mask.map { $0[0..., 0.. MLXArray { + // Port of omlx commit 696d90a: + // patches/mlx_lm_mtp/qwen35_model.py DecoderLayer.__call__ + // Passes nConfirmed through to the linear-attention sublayer. let r: MLXArray if isLinear { - r = linearAttn!(inputLayerNorm(x), mask: ssmMask, cache: cache as? MambaCache) + r = linearAttn!( + inputLayerNorm(x), mask: ssmMask, cache: cache as? MambaCache, + nConfirmed: nConfirmed) } else { r = selfAttn!(inputLayerNorm(x), mask: attentionMask, cache: cache) } @@ -523,7 +618,20 @@ public class Qwen35TextModelInner: Module { super.init() } - func callAsFunction(_ inputs: MLXArray, cache: [KVCache?]? = nil) -> MLXArray { + /// Returns the pre-norm hidden state from the final layer. + /// + /// The caller (`Qwen35TextModel`) applies `norm` and the LM head on top. + /// This split lets `callWithHidden` return both pre-norm hidden (for the MTP head) + /// and the normalised logits in one forward pass. + /// + /// Port of omlx commit 696d90a: + /// patches/mlx_lm_mtp/qwen35_model.py `_patch_qwen3_5_text_model` + /// (returns hidden_states before self.model.norm so TextModel can apply it) + func callAsFunction( + _ inputs: MLXArray, + cache: [KVCache?]? = nil, + nConfirmed: Int = 0 + ) -> MLXArray { var hiddenStates = embedTokens(inputs) var cacheArray = cache @@ -540,10 +648,12 @@ public class Qwen35TextModelInner: Module { layer.isLinear ? MLXFast.ScaledDotProductAttentionMaskMode.none : faMask hiddenStates = layer( - hiddenStates, attentionMask: attnMask, ssmMask: mask, cache: cacheArray?[i]) + hiddenStates, attentionMask: attnMask, ssmMask: mask, + cache: cacheArray?[i], nConfirmed: nConfirmed) } - return norm(hiddenStates) + // Return pre-norm hidden states. Norm is applied by Qwen35TextModel. + return hiddenStates } } @@ -556,6 +666,11 @@ public class Qwen35TextModel: Module, LLMModel, KVCacheDimensionProvider { @ModuleInfo(key: "lm_head") var lmHead: Linear? + /// MTP head. Non-nil only when `_qwen35MTPEnabled == true` at init time + /// AND `args.mtpNumHiddenLayers > 0`. + /// omlx: patches/mlx_lm_mtp/qwen35_model.py TextModel.__init__ (MTPModule attachment) + @ModuleInfo(key: "mtp") var mtp: Qwen35MTPModule? + public init(_ args: Qwen35TextConfiguration) { self.configuration = args self.vocabularySize = args.vocabularySize @@ -565,10 +680,19 @@ public class Qwen35TextModel: Module, LLMModel, KVCacheDimensionProvider { if !args.tieWordEmbeddings { _lmHead.wrappedValue = Linear(args.hiddenSize, args.vocabularySize, bias: false) } + + // Attach MTP head only when enabled and config declares MTP layers. + // omlx: `if n_mtp > 0 and is_mtp_active(): self.mtp = q35.MTPModule(args)` + if args.mtpNumHiddenLayers > 0 && _qwen35MTPEnabled { + _mtp.wrappedValue = Qwen35MTPModule(args) + } } public func callAsFunction(_ inputs: MLXArray, cache: [KVCache]?) -> MLXArray { - var out = model(inputs, cache: cache) + // Inner model now returns pre-norm hidden; apply norm + lm_head here. + // omlx: TextModel.__call__ (normed = self.model.norm(hidden); out = lm_head(normed)) + let hidden = model(inputs, cache: cache) + var out = model.norm(hidden) if let lmHead { out = lmHead(out) } else { @@ -587,24 +711,51 @@ public class Qwen35TextModel: Module, LLMModel, KVCacheDimensionProvider { } public func sanitize(weights: [String: MLXArray]) -> [String: MLXArray] { - let hasMTPWeights = weights.keys.contains { $0.contains("mtp.") } + // Port of omlx commit 696d90a: + // patches/mlx_lm_mtp/qwen35_model.py TextModel.sanitize + // + // Key differences from stock mlx-lm: + // 1. Gate norm shift on unsanitized conv1d shape ONLY (not on MTP key presence). + // Stock code uses `hasMTPWeights || hasUnsanitizedConv1d`, which double-shifts + // already-converted MLX checkpoints that have mtp.* keys. + // 2. Keep mtp.* keys when the MTP head is attached; strip them otherwise. + // 3. Extend norm-shift key set with MTP-specific norm names. + let hasUnsanitizedConv1d = weights.contains { key, value in key.contains("conv1d.weight") && value.dim(-1) != 1 } - let shouldShiftNormWeights = hasMTPWeights || hasUnsanitizedConv1d - - var weights = weights.filter { !$0.key.contains("mtp.") } + let shouldShiftNormWeights = hasUnsanitizedConv1d // NOT hasMTPWeights + + var weights = weights + + // Keep mtp.* keys if the head is attached; strip them otherwise. + // omlx: `if not hasattr(self, "mtp"): weights = {k:v if "mtp." not in k}` + if mtp == nil { + weights = weights.filter { !$0.key.contains("mtp.") } + } else if !weights.keys.contains(where: { $0.contains("mtp.") }) { + // MTP enabled but no mtp.* keys in checkpoint → needs re-conversion. + // omlx: raises ValueError with "weights are missing the mtp.* tensors" + print( + "[WARNING] Qwen35TextModel.sanitize: MTP head is enabled but no mtp.* " + + "weights found. Load will likely fail or produce garbage. " + + "Re-convert the checkpoint with a converter that preserves MTP weights.") + } if configuration.tieWordEmbeddings { weights["lm_head.weight"] = nil } + // Extended norm key set includes MTP-specific names. + // omlx: norm_keys tuple with ".pre_fc_norm_hidden.weight" etc. let normKeys = [ ".input_layernorm.weight", ".post_attention_layernorm.weight", "model.norm.weight", ".q_norm.weight", ".k_norm.weight", + ".pre_fc_norm_hidden.weight", + ".pre_fc_norm_embedding.weight", + "mtp.norm.weight", ] for k in Array(weights.keys) { @@ -625,6 +776,64 @@ public class Qwen35TextModel: Module, LLMModel, KVCacheDimensionProvider { } } +// MARK: - Qwen35TextModel + MTPCapable + +extension Qwen35TextModel: MTPCapable { + public var hasMTPHead: Bool { mtp != nil } + + /// Run a backbone forward that also returns pre-norm hidden states. + /// + /// Returns `(logits, preNormHidden)` where `preNormHidden` is the raw backbone output + /// BEFORE `model.norm`. The MTP head applies its own `pre_fc_norm_hidden` normalization, + /// so it expects un-normalized input. Passing post-norm would double-normalize. + /// + /// PR #990: `return out, hidden # pre-norm hidden for MTP head` + /// omlx: patches/mlx_lm_mtp/qwen35_model.py TextModel.__call__ with return_hidden=True + public func callWithHidden( + input: LMInput.Text, cache: [any KVCache], nConfirmed: Int + ) -> (MLXArray, MLXArray) { + let cacheOpt: [KVCache?] = cache.map { Optional($0) } + let hidden = model(input.tokens, cache: cacheOpt, nConfirmed: nConfirmed) + let normed = model.norm(hidden) + let logits: MLXArray + if let lmHead { + logits = lmHead(normed) + } else { + logits = model.embedTokens.asLinear(normed) + } + // Return pre-norm hidden, not post-norm. The MTP module's pre_fc_norm_hidden + // is the normalization step — it expects the raw backbone output as input. + return (logits, hidden) + } + + /// Run the MTP head forward. + /// omlx: patches/mlx_lm_mtp/qwen35_model.py TextModel.mtp_forward + public func mtpForward( + hidden: MLXArray, nextTokenIds: MLXArray, cache: [any KVCache] + ) -> MLXArray { + guard let mtp else { + fatalError("mtpForward called but MTP head is not attached. " + + "Set _qwen35MTPEnabled = true before loading the model.") + } + let mtpOut = mtp( + hidden: hidden, + nextTokenIds: nextTokenIds, + embedTokens: model.embedTokens, + cache: cache) + if configuration.tieWordEmbeddings { + return model.embedTokens.asLinear(mtpOut) + } + return lmHead!(mtpOut) + } + + /// Allocate a fresh KV cache for the MTP head layers. + /// omlx: patches/mlx_lm_mtp/qwen35_model.py TextModel.make_mtp_cache + public func makeMTPCache() -> [any KVCache] { + guard let mtp else { return [] } + return mtp.layers.map { _ in KVCacheSimple() as any KVCache } + } +} + extension Qwen35TextModel: LoRAModel { public var loraLayers: [Module] { model.layers @@ -680,3 +889,28 @@ extension Qwen35Model: LoRAModel { languageModel.model.layers } } + +// MARK: - Qwen35Model + MTPCapable + +/// VLM-outer-wrapper pass-through for MTPCapable. +/// Forwards all MTP calls to the inner `languageModel` (a Qwen35TextModel). +/// omlx: patches/mlx_lm_mtp/qwen35_model.py `_patch_outer_model` +extension Qwen35Model: MTPCapable { + public var hasMTPHead: Bool { languageModel.hasMTPHead } + + public func callWithHidden( + input: LMInput.Text, cache: [any KVCache], nConfirmed: Int + ) -> (MLXArray, MLXArray) { + languageModel.callWithHidden(input: input, cache: cache, nConfirmed: nConfirmed) + } + + public func mtpForward( + hidden: MLXArray, nextTokenIds: MLXArray, cache: [any KVCache] + ) -> MLXArray { + languageModel.mtpForward(hidden: hidden, nextTokenIds: nextTokenIds, cache: cache) + } + + public func makeMTPCache() -> [any KVCache] { + languageModel.makeMTPCache() + } +} diff --git a/Libraries/MLXLLM/Models/Qwen35MTP.swift b/Libraries/MLXLLM/Models/Qwen35MTP.swift new file mode 100644 index 0000000000..b685512baf --- /dev/null +++ b/Libraries/MLXLLM/Models/Qwen35MTP.swift @@ -0,0 +1,124 @@ +// Copyright © 2026 Eigen Labs. +// +// Port of omlx commit 696d90a: +// patches/mlx_lm_mtp/qwen35_model.py (MTPDecoderLayer, MTPModule) +// patches/mlx_lm_mtp/__init__.py (is_mtp_active / set_mtp_active) + +import Foundation +import MLX +import MLXLMCommon +import MLXNN + +// MARK: - Module-level MTP flag + +/// Controls whether Qwen3.5/3.6 model inits attach the MTP head. +/// Set to `true` before calling `MLXLLM.load(...)` when MTP should be active. +/// Mirrors omlx `is_mtp_active()` / `set_mtp_active()` from +/// patches/mlx_lm_mtp/__init__.py. +public nonisolated(unsafe) var _qwen35MTPEnabled: Bool = false + +// MARK: - MTPDecoderLayer + +/// Full-attention transformer layer used inside the Qwen3.5/3.6 MTP head. +/// Unlike `Qwen35DecoderLayer`, this always uses full attention (never SSM/linear). +/// MoE config is honoured when `num_experts > 0`. +/// omlx: patches/mlx_lm_mtp/qwen35_model.py MTPDecoderLayer +final class Qwen35MTPDecoderLayer: Module { + @ModuleInfo(key: "self_attn") var selfAttn: Qwen35Attention + @ModuleInfo(key: "input_layernorm") var inputLayerNorm: RMSNorm + @ModuleInfo(key: "post_attention_layernorm") var postAttentionLayerNorm: RMSNorm + @ModuleInfo(key: "mlp") var mlp: Module + + init(_ args: Qwen35TextConfiguration) { + _selfAttn.wrappedValue = Qwen35Attention(args) + if args.numExperts > 0 { + _mlp.wrappedValue = Qwen35SparseMoeBlock(args) + } else { + _mlp.wrappedValue = Qwen3NextMLP( + dimensions: args.hiddenSize, + hiddenDimensions: args.intermediateSize + ) + } + _inputLayerNorm.wrappedValue = RMSNorm( + dimensions: args.hiddenSize, eps: args.rmsNormEps) + _postAttentionLayerNorm.wrappedValue = RMSNorm( + dimensions: args.hiddenSize, eps: args.rmsNormEps) + super.init() + } + + func callAsFunction( + _ x: MLXArray, + mask: MLXFast.ScaledDotProductAttentionMaskMode, + cache: (any KVCache)? + ) -> MLXArray { + // omlx: MTPDecoderLayer.__call__ + let r = selfAttn(inputLayerNorm(x), mask: mask, cache: cache) + let h = x + r + return h + (mlp as! UnaryLayer)(postAttentionLayerNorm(h)) + } +} + +// MARK: - MTPModule + +/// Multi-Token Prediction head for Qwen3.5/3.6. +/// +/// Fuses the backbone's pre-norm hidden state at position t with the embedding of +/// the sampled main token (t+1) to predict the draft token at (t+2). +/// +/// Architecture (port of PR #990): +/// ``` +/// pre_fc_norm_hidden: RMSNorm(hidden_size) +/// pre_fc_norm_embedding: RMSNorm(hidden_size) +/// fc: Linear(hidden_size * 2 → hidden_size, bias: false) +/// layers: [MTPDecoderLayer] × mtp_num_hidden_layers +/// norm: RMSNorm(hidden_size) +/// ``` +/// omlx: patches/mlx_lm_mtp/qwen35_model.py MTPModule +final class Qwen35MTPModule: Module { + @ModuleInfo(key: "pre_fc_norm_hidden") var preFcNormHidden: RMSNorm + @ModuleInfo(key: "pre_fc_norm_embedding") var preFcNormEmbedding: RMSNorm + @ModuleInfo(key: "fc") var fc: Linear + // `layers` uses the default ModuleInfo key derived from the property name. + let layers: [Qwen35MTPDecoderLayer] + let norm: RMSNorm + + init(_ args: Qwen35TextConfiguration) { + _preFcNormHidden.wrappedValue = RMSNorm( + dimensions: args.hiddenSize, eps: args.rmsNormEps) + _preFcNormEmbedding.wrappedValue = RMSNorm( + dimensions: args.hiddenSize, eps: args.rmsNormEps) + _fc.wrappedValue = Linear(args.hiddenSize * 2, args.hiddenSize, bias: false) + self.layers = (0 ..< args.mtpNumHiddenLayers).map { _ in + Qwen35MTPDecoderLayer(args) + } + self.norm = RMSNorm(dimensions: args.hiddenSize, eps: args.rmsNormEps) + super.init() + } + + func callAsFunction( + hidden: MLXArray, + nextTokenIds: MLXArray, + embedTokens: Embedding, + cache: [any KVCache] + ) -> MLXArray { + // omlx: MTPModule.__call__ + // 1. Embed next-token ids and fuse with normed hidden state. + let embeds = embedTokens(nextTokenIds) + let e = preFcNormEmbedding(embeds) + let h = preFcNormHidden(hidden) + var fused = fc(concatenated([e, h], axis: -1)) + + // 2. Compute attention mask from the first cache entry (or nil if empty). + let firstCache: (any KVCache)? = cache.first + let mask = createAttentionMask(h: fused, cache: firstCache) + + // 3. Run each MTPDecoderLayer. + for (i, layer) in layers.enumerated() { + let c: (any KVCache)? = i < cache.count ? cache[i] : nil + fused = layer(fused, mask: mask, cache: c) + } + + // 4. Return pre-lm_head hidden (norm applied; lm_head is in TextModel). + return norm(fused) + } +} diff --git a/Libraries/MLXLLM/Models/Qwen3Next.swift b/Libraries/MLXLLM/Models/Qwen3Next.swift index cfe0a985bd..2c0e19fe09 100644 --- a/Libraries/MLXLLM/Models/Qwen3Next.swift +++ b/Libraries/MLXLLM/Models/Qwen3Next.swift @@ -29,9 +29,11 @@ final class Qwen3NextRMSNormGated: Module { } func callAsFunction(_ hiddenStates: MLXArray, gate: MLXArray? = nil) -> MLXArray { - var x = MLXFast.rmsNorm(hiddenStates, weight: weight, eps: eps) + let x = MLXFast.rmsNorm(hiddenStates, weight: weight, eps: eps) if let gate { - x = x * silu(gate) + // Upcast to float32 for numerical precision — mirrors Python _precise_swiglu. + let g = silu(gate.asType(.float32)) + return (g * x.asType(.float32)).asType(hiddenStates.dtype) } return x } @@ -129,7 +131,7 @@ final class Qwen3NextMLP: Module, UnaryLayer { } func callAsFunction(_ x: MLXArray) -> MLXArray { - downProj(silu(gateProj(x)) * upProj(x)) + return downProj(silu(gateProj(x)) * upProj(x)) } } diff --git a/Libraries/MLXLMCommon/BatchKVCache.swift b/Libraries/MLXLMCommon/BatchKVCache.swift index d120c6dd54..d94464e14d 100644 --- a/Libraries/MLXLMCommon/BatchKVCache.swift +++ b/Libraries/MLXLMCommon/BatchKVCache.swift @@ -555,6 +555,14 @@ public final class BatchRotatingKVCache: BaseKVCache, BatchPositionedKVCache, Ba self.values = values _idx = stepCount } else { + // Honor a prior trim before appending new K/V. Otherwise the + // stored tensors keep stale tail positions while `_idx` and masks + // describe the shorter logical cache. + if let storedK = self.keys, storedK.dim(2) > _idx { + self.keys = storedK[.ellipsis, ..<_idx, 0...] + self.values = self.values![.ellipsis, ..<_idx, 0...] + } + if stepCount > 1 { // Multi-token prefill must keep enough temporary context for // every query in this call. Match RotatingKVCache's concat @@ -852,3 +860,25 @@ public func dynamicRoll( let idx = (arange - reshapedShifts) % Int32(n) return takeAlong(x, idx, axis: axis) } + +// MARK: - Speculative-decoding primitives + +extension BatchKVCache { + + /// Zero per-row tail positions. For each row `b`, slots + /// `[keepLengths[b], _idx)` in both keys and values are set to 0. + /// + /// This is used by batched speculative decoding when rows accept different + /// numbers of tokens within the same verify block. + public func zeroTailPerRow(keepLengths: MLXArray) { + guard let storedK = keys, let storedV = values else { return } + let T = storedK.dim(2) + let positions = MLXArray(Int32(0) ..< Int32(T)) + .reshaped([1, 1, T, 1]) + let keep = keepLengths.asType(.int32) + .reshaped([-1, 1, 1, 1]) + let mask = (positions .< keep).asType(storedK.dtype) + keys = storedK * mask + values = storedV * mask + } +} diff --git a/Libraries/MLXLMCommon/ContinuousBatching/BatchedEngine.swift b/Libraries/MLXLMCommon/ContinuousBatching/BatchedEngine.swift index 525f986751..4ac5f06a3a 100644 --- a/Libraries/MLXLMCommon/ContinuousBatching/BatchedEngine.swift +++ b/Libraries/MLXLMCommon/ContinuousBatching/BatchedEngine.swift @@ -33,6 +33,9 @@ public final class BatchedEngine: @unchecked Sendable { private let tokenizer: any Tokenizer public let modelName: String + /// Chat template loaded from `chat_template.jinja` in the model directory, + /// used as fallback when the tokenizer config lacks a `chat_template` field. + private let externalChatTemplate: String? /// Create a batched engine from a loaded model context. public convenience init( @@ -49,11 +52,16 @@ public final class BatchedEngine: @unchecked Sendable { eosTokenIds: context.configuration.eosTokenIds, prefixCache: prefixCache ) + // Load chat_template.jinja if the tokenizer lacks an embedded chat template. + let externalTemplate: String? = (try? context.configuration.modelDirectory).flatMap { + try? String(contentsOf: $0.appendingPathComponent("chat_template.jinja"), encoding: .utf8) + } self.init( scheduler: scheduler, tokenizer: context.tokenizer, modelName: context.configuration.name, - config: config + config: config, + externalChatTemplate: externalTemplate ) } @@ -62,11 +70,13 @@ public final class BatchedEngine: @unchecked Sendable { scheduler: Scheduler, tokenizer: any Tokenizer, modelName: String = "", - config: ContinuousBatchingConfig = ContinuousBatchingConfig() + config: ContinuousBatchingConfig = ContinuousBatchingConfig(), + externalChatTemplate: String? = nil ) { self.core = EngineCore(scheduler: scheduler, config: config) self.tokenizer = tokenizer self.modelName = modelName + self.externalChatTemplate = externalChatTemplate } // MARK: - Lifecycle @@ -127,12 +137,20 @@ public final class BatchedEngine: @unchecked Sendable { // MARK: - Chat Completion /// Apply chat template to messages and return the prompt string. - /// Falls back to a simple "role: content" format if the template is unavailable. + /// If the tokenizer config lacks a chat_template, falls back to `chat_template.jinja` + /// loaded from the model directory. public func buildPrompt(messages: [[String: String]]) -> String { do { let tokenIds = try tokenizer.applyChatTemplate(messages: messages) return tokenizer.decode(tokenIds: tokenIds) } catch { + if let template = externalChatTemplate { + do { + let tokenIds = try tokenizer.applyChatTemplate( + messages: messages, chatTemplate: template) + return tokenizer.decode(tokenIds: tokenIds) + } catch {} + } return messages.map { "\($0["role"] ?? "user"): \($0["content"] ?? "")" } .joined(separator: "\n") + "\nassistant:" } diff --git a/Libraries/MLXLMCommon/ContinuousBatching/EngineCore.swift b/Libraries/MLXLMCommon/ContinuousBatching/EngineCore.swift index ca81ffdedb..2ab330766e 100644 --- a/Libraries/MLXLMCommon/ContinuousBatching/EngineCore.swift +++ b/Libraries/MLXLMCommon/ContinuousBatching/EngineCore.swift @@ -29,16 +29,23 @@ public struct ContinuousBatchingConfig: Sendable { /// Optional in-memory prefix cache configuration. /// Set to non-nil to enable block-level KV reuse across requests. public var prefixCacheConfig: PrefixCacheConfig? + /// Enable Multi-Token Prediction (MTP) speculative decoding for compatible models. + /// When true, the model loader should attach the MTP head (e.g. set `_qwen35MTPEnabled` + /// before calling `MLXLLM.load`). Only affects single-sequence batches. + /// Port of omlx commit 696d90a: patches/mlx_lm_mtp/qwen35_model.py is_mtp_active() + public var mtpEnabled: Bool public init( schedulerConfig: SchedulerConfig = SchedulerConfig(), stepInterval: TimeInterval = 0.001, yieldInterval: Int = 5, - prefixCacheConfig: PrefixCacheConfig? = nil + prefixCacheConfig: PrefixCacheConfig? = nil, + mtpEnabled: Bool = false ) { self.schedulerConfig = schedulerConfig self.stepInterval = stepInterval self.yieldInterval = yieldInterval self.prefixCacheConfig = prefixCacheConfig + self.mtpEnabled = mtpEnabled } } diff --git a/Libraries/MLXLMCommon/ContinuousBatching/MTPState.swift b/Libraries/MLXLMCommon/ContinuousBatching/MTPState.swift new file mode 100644 index 0000000000..022f9f9869 --- /dev/null +++ b/Libraries/MLXLMCommon/ContinuousBatching/MTPState.swift @@ -0,0 +1,81 @@ +// Copyright © 2026 Eigen Labs. +// +// Port of omlx commit 696d90a: +// patches/mlx_lm_mtp/batch_generator.py _MtpStats / _MtpState + +import Foundation +import MLX + +// MARK: - MTPStats + +/// Per-sequence MTP timing and accept/reject counters. +/// Logged at sequence finish so operators can evaluate draft+verify productivity. +/// omlx: batch_generator.py _MtpStats +struct MTPStats { + var cycles: Int = 0 // number of verify cycles run + var accepts: Int = 0 // cycles where the draft was accepted + var rejects: Int = 0 // cycles where the draft was rejected + var initEmits: Int = 0 // tokens emitted from the post-init queue (always 2) + var draftEmits: Int = 0 // tokens emitted as accepted drafts + var bonusEmits: Int = 0 // tokens emitted as bonus on accept path + var verifyEmits: Int = 0 // corrected tokens emitted on reject path + // Component timings + var backboneMs: Double = 0 // cumulative time inside 2-token verify forward + var mtpHeadMs: Double = 0 // cumulative time inside MTP-head forwards + var sampleMs: Double = 0 // cumulative time in sampling + acceptance check + var cacheOpsMs: Double = 0 // cumulative time in trim / rollback restore + + var acceptRate: Double { + cycles > 0 ? Double(accepts) / Double(cycles) : 0 + } + var totalEmits: Int { + initEmits + draftEmits + bonusEmits + verifyEmits + } +} + +// MARK: - MTPQueueItem + +/// One token buffered for emission from the MTP dispatch path. +/// omlx: batch_generator.py _MtpState.queue element +struct MTPQueueItem { + let tokenId: Int + let source: String // "init" | "draft" | "bonus" | "verify" +} + +// MARK: - MTPState + +/// Per-batch MTP state stashed on GenerationBatch when the MTP path is active. +/// omlx: batch_generator.py _MtpState +final class MTPState { + /// Pending tokens to emit in upcoming next() calls. + /// Max 2 items at any time (one draft + one bonus on accept). + var queue: [MTPQueueItem] = [] + + /// First input token for the next verify forward. Shape: (1,) uint32. + /// omlx: state.next_main + var nextMain: MLXArray? + + /// Current draft token. Shape: (1,) uint32. + /// omlx: state.draft_tok + var draftTok: MLXArray? + + /// Log-probabilities of the draft distribution. Shape: (vocab,). + /// Used for stochastic acceptance (Leviathan & Chen 2023). + /// omlx: state.draft_lp + var draftLp: MLXArray? + + /// Host-side int copy of draftTok, cached at draft creation time. + /// Avoids a GPU→CPU sync on every verify cycle's accept/reject check. + /// omlx: state.draft_id + var draftId: Int = -1 + + /// KV caches for the MTP transformer layer(s). Created once at init and + /// accumulated across cycles — the MTP head is auto-regressive and was + /// trained with a growing KV context, matching the backbone's behaviour. + /// PR #990: `mtp_cache = model.make_mtp_cache()` (created once, reused). + /// omlx uses fresh-per-cycle; we now match PR #990 for correctness. + var mtpCache: [any KVCache]? + + /// Stats to be logged on sequence finish. + var stats: MTPStats = MTPStats() +} diff --git a/Libraries/MLXLMCommon/Evaluate.swift b/Libraries/MLXLMCommon/Evaluate.swift index c59b03e716..48edaec20e 100644 --- a/Libraries/MLXLMCommon/Evaluate.swift +++ b/Libraries/MLXLMCommon/Evaluate.swift @@ -491,7 +491,10 @@ public struct PenaltyProcessor: LogitProcessor { } /// Common properties shared by token-generating iterators. -protocol TokenIteratorProtocol: Sequence, IteratorProtocol where Element == Int { +/// +/// Public so model-specific iterators outside `MLXLMCommon` can plug into +/// the shared generation loop. +public protocol TokenIteratorProtocol: Sequence, IteratorProtocol where Element == Int { var maxTokens: Int? { get } var tokenCount: Int { get } var promptPrefillTime: TimeInterval { get } @@ -529,8 +532,8 @@ public struct TokenIterator: TokenIteratorProtocol { var processor: LogitProcessor? let sampler: LogitSampler - var tokenCount = 0 - let maxTokens: Int? + public var tokenCount = 0 + public let maxTokens: Int? // Cache quantization parameters let kvBits: Int? @@ -538,7 +541,7 @@ public struct TokenIterator: TokenIteratorProtocol { let quantizedKVStart: Int // Internal metrics - var promptPrefillTime: TimeInterval = 0.0 + public var promptPrefillTime: TimeInterval = 0.0 /// Initialize a `TokenIterator` with the given tokens. Note: this has been /// replaced with ``init(input:model:cache:parameters:)``. @@ -746,8 +749,8 @@ public struct SpeculativeTokenIterator: TokenIteratorProtocol { var processor: LogitProcessor? let sampler: LogitSampler - var tokenCount = 0 - let maxTokens: Int? + public var tokenCount = 0 + public let maxTokens: Int? let numDraftTokens: Int // Buffer of accepted tokens from the current speculation round @@ -755,7 +758,7 @@ public struct SpeculativeTokenIterator: TokenIteratorProtocol { private var pendingIndex = 0 // Internal metrics - var promptPrefillTime: TimeInterval = 0.0 + public var promptPrefillTime: TimeInterval = 0.0 /// Initialize a `SpeculativeTokenIterator` with the given input. /// @@ -1500,6 +1503,31 @@ public func generateTask( ) } +/// Low-level token generation accepting any ``TokenIteratorProtocol`` +/// conformer. +/// +/// This mirrors the `TokenIterator` overload while allowing model-specific +/// iterators to share the standard `AsyncStream` output path. +public func generateTask( + promptTokenCount: Int, + modelConfiguration: ModelConfiguration, + tokenizer: Tokenizer, + iterator: consuming any TokenIteratorProtocol, + wiredMemoryTicket: WiredMemoryTicket? = nil +) -> (AsyncStream, Task) { + generateLoopTask( + promptTokenCount: promptTokenCount, + modelConfiguration: modelConfiguration, + tokenizer: tokenizer, + iterator: iterator, + wiredMemoryTicket: wiredMemoryTicket, + handler: TextToolTokenLoopHandler( + tokenizer: tokenizer, + format: modelConfiguration.toolCallFormat ?? .json + ) + ) +} + /// Generates raw token IDs asynchronously using the provided language model input, parameters, and context. /// /// This is similar to `generate(input:cache:parameters:context:)`, but yields raw token IDs instead of decoded text/tool calls. diff --git a/Libraries/MLXLMCommon/GenerationBatch.swift b/Libraries/MLXLMCommon/GenerationBatch.swift index 3a8e78c54a..d5f6b2d0c0 100644 --- a/Libraries/MLXLMCommon/GenerationBatch.swift +++ b/Libraries/MLXLMCommon/GenerationBatch.swift @@ -1,8 +1,14 @@ // Port of mlx_lm.generate.GenerationBatch. // https://github.com/ml-explore/mlx-lm/blob/main/mlx_lm/generate.py +// +// MTP (Multi-Token Prediction) dispatch is added at the bottom of this file +// as a private extension. It intercepts init/next/filter/extend when the +// model is MTPCapable and batchSize == 1. +// Port of omlx commit 696d90a: patches/mlx_lm_mtp/batch_generator.py import Foundation import MLX +import MLXRandom import MLXNN /// Picks one token per row from a `[B, vocab]` logits tensor. @@ -64,6 +70,11 @@ public final class GenerationBatch: @unchecked Sendable { private var numTokens: [Int] private var matcherStates: [SequenceStateMachineState] + /// MTP state. Non-nil when the batch is running the MTP draft+verify cycle. + /// Set by `postInitMTP` immediately after `init`; cleared on finish or fallback. + /// Port of omlx commit 696d90a: batch_generator.py _omlx_mtp_state + internal var _omlxMtpState: MTPState? + public init( model: any LanguageModel, uids: [Int], @@ -97,6 +108,11 @@ public final class GenerationBatch: @unchecked Sendable { // token extraction path. if !uids.isEmpty { _ = step() + // Attempt MTP post-init for eligible single-sequence batches. + // omlx: batch_generator.py patched_init → _post_init_mtp + if batchSize == 1, let mtpModel = model as? (any MTPCapable), mtpModel.hasMTPHead { + postInitMTP(model: mtpModel) + } } } @@ -106,6 +122,21 @@ public final class GenerationBatch: @unchecked Sendable { public func next() -> [GenerationBatchResponse] { if uids.isEmpty { return [] } + // MTP dispatch: for eligible single-sequence batches, emit from queue or + // run the 2-token verify cycle. + // omlx: batch_generator.py patched_next → _mtp_next + if batchSize == 1, + let state = _omlxMtpState, + let mtpModel = model as? (any MTPCapable) + { + do { + return try mtpNext(state: state, model: mtpModel) + } catch { + // Fall back to standard step; drop state to prevent half-built cycles. + _omlxMtpState = nil + } + } + let stepTokens = step() var keep: [Int] = [] @@ -184,6 +215,9 @@ public final class GenerationBatch: @unchecked Sendable { if !keep.isEmpty { nextTokens = take(nextTokens, keepArr, axis: 0) } + // MTP: drop state when batch is emptied externally (e.g. scheduler abort). + // omlx: batch_generator.py patched_filter + if keep.isEmpty { _omlxMtpState = nil } } /// In-place: append `other`'s rows to this batch. Per-layer caches are @@ -204,11 +238,88 @@ public final class GenerationBatch: @unchecked Sendable { matcherStates.append(contentsOf: other.matcherStates) numTokens.append(contentsOf: other.numTokens) nextTokens = concatenated([nextTokens, other.nextTokens], axis: 0) + // MTP: transfer state from donor batch when BatchGenerator merges a fresh + // single-sequence batch into self via extend(). The MTP post-init fires on + // the donor (whose __init__ ran with uids=[1]); without this transfer the + // state would be lost when the donor is released. + // omlx: batch_generator.py patched_extend + if let donorState = other._omlxMtpState, _omlxMtpState == nil { + _omlxMtpState = donorState + other._omlxMtpState = nil + } } public var isEmpty: Bool { uids.isEmpty } public var batchSize: Int { uids.count } + // MARK: - MTP post-init + + /// Called from `init` immediately after the standard `step()` for eligible + /// single-sequence batches. Sets up `_omlxMtpState` and seeds the emit queue + /// with two confirmed tokens so the first two `next()` calls bypass `step()`. + /// omlx: batch_generator.py patched_init → _post_init_mtp + internal func postInitMTP(model: any MTPCapable) { + let sampler = samplers[0] ?? fallbackSampler + + // nextTokens = main_tok: sampled from prompt[-1]'s logits in init's step(). + let mainTok = nextTokens // shape (1,) — asyncEval'd in step(); will force on use + + // 1. Backbone forward at main_tok → (logits [1,1,vocab], preNormHidden [1,1,H]). + // omlx: _post_init_mtp — "1-token backbone forward at main_tok with hidden state" + // Returns pre-norm hidden: the MTP head's pre_fc_norm_hidden applies its own norm. + let mainInput = mainTok.reshaped(1, 1) + let backboneCache = promptCache.map { $0 as any KVCache } + let (logits, hidden) = model.callWithHidden( + input: LMInput.Text(tokens: mainInput), + cache: backboneCache, + nConfirmed: 0 + ) + + // 2. Sample next_main_tok from logits[:, -1, :]. Upcast to float32 to avoid + // BF16 underflow on low-probability tokens (MTPLX: "fp32 p/q ratio" note). + let nextMainLogits = logits[0..., -1, 0...].asType(.float32) // [1, vocab] + let nextMainLp = nextMainLogits - logSumExp(nextMainLogits, axis: -1, keepDims: true) + let nextMainTok = sampler(nextMainLp) // (1,) + + // 3. Run MTP head: (hidden_at_main [1,1,H], next_main_tok [1,1]) → draft [1,1,vocab]. + // omlx: _post_init_mtp — "MTP head sees (hidden_at_main, next_main_tok)" + // Allocate the persistent MTP cache here so it's shared with all subsequent + // stepMTP calls. The MTP head is auto-regressive (trained with growing KV context). + // PR #990: `mtp_cache = model.make_mtp_cache()` — created once, reused every cycle. + let mtpCache = model.makeMTPCache() + let T = hidden.dim(1) + let hiddenAtMain = hidden[0..., (T - 1) ..< T, 0...] // [1, 1, H] + let nextIds = nextMainTok.reshaped(1, 1) // [1, 1] + let mtpLogits = model.mtpForward( + hidden: hiddenAtMain, nextTokenIds: nextIds, cache: mtpCache) + let draftLogits2d = mtpLogits[0..., -1, 0...].asType(.float32) // [1, vocab] + let draftLp2d = draftLogits2d - logSumExp(draftLogits2d, axis: -1, keepDims: true) + let draftTok = compactCategorical(draftLp2d, k: 512) // (1,) — sample draft for losslessness + + // 4. Single eval for all sampled tokens. Cache draft_id as Int to avoid a + // GPU→CPU sync in the first verify cycle's accept/reject check. + // omlx: _post_init_mtp — "mx.eval(main_tok, next_main_tok, draft_tok)" + eval(mainTok, nextMainTok, draftTok) + let mainId = Int(mainTok.asArray(UInt32.self)[0]) + let nextMainId = Int(nextMainTok.asArray(UInt32.self)[0]) + let draftId = Int(draftTok.asArray(UInt32.self)[0]) + + let state = MTPState() + state.mtpCache = mtpCache + state.nextMain = nextMainTok + state.draftTok = draftTok + state.draftLp = draftLp2d[0] // [vocab] + state.draftId = draftId + // Queue the two confirmed tokens. The first two next() calls emit from + // this queue without any model forward — "two confirmed tokens" from PR 990. + state.queue.append(MTPQueueItem(tokenId: mainId, source: "init")) + state.queue.append(MTPQueueItem(tokenId: nextMainId, source: "init")) + + _omlxMtpState = state + } + + // MARK: - Standard decode step (unchanged) + /// One forward pass + per-row sample, double-buffered like upstream /// `mlx_lm.generate.GenerationBatch._step`. /// @@ -261,3 +372,420 @@ public final class GenerationBatch: @unchecked Sendable { return stepTokens } } + +// MARK: - MTP fallback error + +/// Signals a clean fallback to the standard step() inside the MTP dispatch path. +/// omlx: batch_generator.py _MtpStepFallback +private enum MTPFallback: Error { + case missingVerifyInputs + case verifyProducedNoTokens + case cacheRollbackFailed +} + +// MARK: - MTP dispatch (private extension) +// +// Port of omlx commit 696d90a: +// patches/mlx_lm_mtp/batch_generator.py +// _mtp_next, _run_verify_cycle, _step_mtp, _residual_sample, _emit_response, +// _restore_or_trim_caches, _clear_rollback, _bump_emit_stat +// +// This extension intercepts next() for eligible single-sequence batches. +// The queue emitted by postInitMTP (two confirmed tokens) is drained first; +// subsequent calls run the 2-token verify cycle. + +private extension GenerationBatch { + + // MARK: next() dispatch + + /// Emit one token from the queue; run a verify cycle if the queue is empty. + /// omlx: batch_generator.py _mtp_next + func mtpNext(state: MTPState, model: any MTPCapable) throws -> [GenerationBatchResponse] { + if !state.queue.isEmpty { + let item = state.queue.removeFirst() + bumpEmitStat(&state.stats, source: item.source) + return emitMTPToken(item, state: state) + } + + try runVerifyCycle(state: state, model: model) + guard !state.queue.isEmpty else { + // Verify cycle must always produce at least the rejected-verify token. + // omlx: _mtp_next — "verify cycle produced no emit tokens" + throw MTPFallback.verifyProducedNoTokens + } + + let item = state.queue.removeFirst() + bumpEmitStat(&state.stats, source: item.source) + return emitMTPToken(item, state: state) + } + + // MARK: Verify cycle + + /// 2-token backbone forward [next_main, draft] with nConfirmed=1. + /// Populates state.queue with 1 (reject) or 2 (accept) tokens for the + /// upcoming emit calls. Updates state.nextMain / draftTok / draftLp for + /// the following cycle. + /// omlx: batch_generator.py _run_verify_cycle + func runVerifyCycle(state: MTPState, model: any MTPCapable) throws { + guard let nextMain = state.nextMain, let draftTok = state.draftTok else { + throw MTPFallback.missingVerifyInputs + } + + let sampler = samplers[0] ?? fallbackSampler + let isGreedy = samplers[0] == nil + + // Concatenate [next_main (1,), draft_tok (1,)] → (2,) → [1, 2] input. + let inputs = concatenated([nextMain, draftTok], axis: 0).reshaped(1, 2) + let backboneCache = promptCache.map { $0 as any KVCache } + + // --- backbone forward (2-token, nConfirmed=1) --- + // nConfirmed=1: GatedDeltaNet runs two sequential M=1 processChunk calls, saving + // a mid-point rollbackState snapshot for the reject path. Benchmarks show this costs + // only ~2ms more than nConfirmed=0 (single M=2 processChunk) since the DeltaNet + // layers are not the bottleneck — the 28 attention layers dominate KV cache bandwidth. + // omlx: _run_verify_cycle — "logits, hidden = gen_batch.model(..., n_confirmed=1)" + let t0 = CFAbsoluteTimeGetCurrent() + let (logits, hidden) = model.callWithHidden( + input: LMInput.Text(tokens: inputs), + cache: backboneCache, + nConfirmed: 1 + ) + state.stats.backboneMs += (CFAbsoluteTimeGetCurrent() - t0) * 1000 + + // verify position = [:, 0, :]; bonus position = [:, 1, :] + let verifyLogits = logits[0..., 0, 0...] // [1, vocab] + let bonusLogits = logits[0..., 1, 0...] // [1, vocab] + + // Batched logprob: one logsumexp over (2, vocab) vs two over (1, vocab). + // Upcast to float32 before log-softmax: BF16 underflows at low probabilities, + // causing -inf logprobs that break the acceptance ratio (MTPLX "fp32 p/q ratio" note). + // omlx: _run_verify_cycle — "combined_logits = mx.concatenate([verify_logits, bonus_logits])" + let tSample = CFAbsoluteTimeGetCurrent() + let combinedLogits = concatenated([verifyLogits, bonusLogits], axis: 0).asType(.float32) // [2, vocab] + let combinedLp = combinedLogits - logSumExp(combinedLogits, axis: -1, keepDims: true) + let verifyLp2d = combinedLp[0 ..< 1, 0...] // [1, vocab] + let bonusLp2d = combinedLp[1 ..< 2, 0...] // [1, vocab] + + let draftId = state.draftId + + // Accept check WITHOUT full categorical sampling. + // Greedy: argmax(verifyLp2d) == draft token (fast, O(vocab) max reduction). + // Stochastic: log P_target(draft) / log P_draft(draft) ratio check (single index read). + // Deferring sampling saves one categorical (~18ms at vocab=151K) per cycle: + // on accept we sample bonusTok; on reject we sample from residual distribution. + // Both paths perform exactly ONE categorical vs the previous unconditional TWO. + let accept: Bool + if isGreedy { + let verifyArgmax = argMax(verifyLp2d, axis: -1) + eval(verifyArgmax) + accept = Int(verifyArgmax.asArray(UInt32.self)[0]) == draftId + } else { + let logTargetAtDraft = Double(verifyLp2d[0, draftId].asArray(Float.self)[0]) + let logDraftAtDraft = Double(state.draftLp![draftId].asArray(Float.self)[0]) + let logAccept = logTargetAtDraft - logDraftAtDraft + accept = logAccept >= 0 || Double.random(in: 0 ..< 1) < exp(logAccept) + } + state.stats.sampleMs += (CFAbsoluteTimeGetCurrent() - tSample) * 1000 + + // Hidden at each verify-forward position. + let hiddenAtConfirmed = hidden[0..., 0 ..< 1, 0...] // [1, 1, H] + let hiddenAtDraft = hidden[0..., 1 ..< 2, 0...] // [1, 1, H] + + state.stats.cycles += 1 + + if accept { + state.stats.accepts += 1 + + // Accept path: clear rollback snapshots, sample bonus, run MTP head at draft position. + // ONE categorical (bonusTok) — verify token not needed on accept path. + // omlx: _run_verify_cycle accept branch + let tCache = CFAbsoluteTimeGetCurrent() + clearRollback() + state.stats.cacheOpsMs += (CFAbsoluteTimeGetCurrent() - tCache) * 1000 + + // Use compact sampling (argPartition top-K) to avoid categorical(151K) ≈ 18ms. + // Greedy: argmax is already O(N) optimal. Stochastic: pre-filter to top-512 + // and sample from that compact distribution — semantically identical to full + // vocab when topP nucleus fits within 512 tokens (true for topP≤0.9 on 151K vocab). + let bonusTok = isGreedy + ? argMax(bonusLp2d, axis: -1) + : compactSample(bonusLp2d, sampler: sampler) + eval(bonusTok) + let bonusId = Int(bonusTok.asArray(UInt32.self)[0]) + + let (newDraft, newDraftLp) = stepMTP( + state: state, model: model, + hiddenAtPosition: hiddenAtDraft, + nextMainTok: bonusTok + ) + // Queue: accepted draft uses MTP head's original draft distribution; + // bonus uses the verify forward's bonus distribution. + // omlx: _run_verify_cycle — "state.queue.append((draft_id, state.draft_lp, 'draft'))" + state.queue.append(MTPQueueItem(tokenId: draftId, source: "draft")) + state.queue.append(MTPQueueItem(tokenId: bonusId, source: "bonus")) + state.nextMain = bonusTok + state.draftTok = newDraft + state.draftLp = newDraftLp + return + } + + // Reject path: restore / trim caches, sample corrected token, run MTP at confirmed. + // ONE categorical (residualSample) or zero (greedy fallback) — bonus not needed. + // omlx: _run_verify_cycle reject branch + state.stats.rejects += 1 + let tCache = CFAbsoluteTimeGetCurrent() + guard restoreOrTrimCaches() else { + throw MTPFallback.cacheRollbackFailed + } + state.stats.cacheOpsMs += (CFAbsoluteTimeGetCurrent() - tCache) * 1000 + + let emitId: Int + if isGreedy { + // Greedy: emit argmax of verify distribution (already computed in accept check). + let verifyArgmax = argMax(verifyLp2d, axis: -1) + eval(verifyArgmax) + emitId = Int(verifyArgmax.asArray(UInt32.self)[0]) + } else { + // Stochastic: residual sample from max(P_target - P_draft, 0) / Z. + // Fall back to argmax if residual mass is negligible (z ≤ 1e-8). + let (rid, _) = residualSample( + verifyLp2d: verifyLp2d, draftLp1d: state.draftLp!) + if let rid { + emitId = rid + } else { + let verifyArgmax = argMax(verifyLp2d, axis: -1) + eval(verifyArgmax) + emitId = Int(verifyArgmax.asArray(UInt32.self)[0]) + } + } + + let emitTok = MLXArray([UInt32(emitId)]) // (1,) uint32 + let (newDraft, newDraftLp) = stepMTP( + state: state, model: model, + hiddenAtPosition: hiddenAtConfirmed, + nextMainTok: emitTok + ) + state.queue.append(MTPQueueItem(tokenId: emitId, source: "verify")) + state.nextMain = emitTok + state.draftTok = newDraft + state.draftLp = newDraftLp + } + + // MARK: MTP head forward + + /// One MTP-head forward + sample. Returns (draft_tok [1], draft_lp [vocab]). + /// Side effect: stores the host-side int in `state.draftId` to avoid a + /// GPU→CPU sync on the next verify cycle's accept/reject check. + /// omlx: batch_generator.py _step_mtp + func stepMTP( + state: MTPState, + model: any MTPCapable, + hiddenAtPosition: MLXArray, + nextMainTok: MLXArray + ) -> (MLXArray, MLXArray) { + let t0 = CFAbsoluteTimeGetCurrent() + + let nextIds = nextMainTok.reshaped(1, 1) // [1, 1] + // Use the persistent MTP cache from MTPState. The MTP head is auto-regressive + // (one full-attention transformer layer) and was trained with a growing KV context + // accumulated across the generation. PR #990 creates the cache once at init. + let mtpCache = state.mtpCache ?? model.makeMTPCache() + let mtpLogits = model.mtpForward( + hidden: hiddenAtPosition, nextTokenIds: nextIds, cache: mtpCache) + let mtpLogits2d = mtpLogits[0..., -1, 0...].asType(.float32) // [1, vocab] + let newLp2d = mtpLogits2d - logSumExp(mtpLogits2d, axis: -1, keepDims: true) + + // Sample the MTP draft from compactCategorical(top-512) so q matches the + // acceptance distribution exactly — fully lossless speculative decoding. + // compactCategorical is ~0.1ms/cycle (vs ~18ms for full 150K-vocab categorical). + // draft_lp (newLp2d[0]) is stored as the correct q distribution for accept check. + let newTok = compactCategorical(newLp2d, k: 512) // (1,) — compact-categorical draft + + // Force eval + cache int: avoids re-sync on next cycle's accept check. + // omlx: _step_mtp — "draft_id_int = int(new_tok.tolist()[0])" + eval(newTok) + state.draftId = Int(newTok.asArray(UInt32.self)[0]) + state.stats.mtpHeadMs += (CFAbsoluteTimeGetCurrent() - t0) * 1000 + + return (newTok, newLp2d[0]) // ([1], [vocab]) + } + + // MARK: Compact sampling helpers + + /// Sample from log-probability distribution lp [1, vocab] using a compact top-K subset. + /// + /// Uses `argPartition` (O(N)) to select the K highest-logprob tokens, then calls the + /// sampler closure on the compact [1, K] distribution, and maps the local index back + /// to the full vocabulary. This reduces the categorical kernel from vocab=151K to K, + /// eliminating the dominant ~18ms sampling bottleneck per MTP verify cycle. + /// + /// Correctness: the sampler's topP filter is applied to the K pre-filtered tokens. + /// This is equivalent to the full-vocab filter when K >= topP nucleus size (typically + /// 50–200 tokens for topP=0.9 on a 151K vocab), which K=512 satisfies conservatively. + private func compactSample(_ lp: MLXArray, sampler: RowSampler, k: Int = 512) -> MLXArray { + let vocab = lp.dim(-1) + if vocab <= k { return sampler(lp) } + + // argPartition(-lp, kth: k-1): indices at positions [0, k-1] are the K largest + // elements of lp (= K smallest of -lp), in arbitrary order. O(N) vs O(N log N) sort. + let partIdx = argPartition(-lp, kth: k - 1, axis: -1) // [1, vocab] + let topKIdx = partIdx[0..., 0 ..< k] // [1, K] + let topKLp = takeAlong(lp, topKIdx, axis: -1) // [1, K] compact log-probs + + // Sample from the compact distribution using the sampler (temp + topP + categorical). + let localTok = sampler(topKLp) // (1,) in [0, K-1] + + // Map local index back to the full vocabulary. + return takeAlong(topKIdx, localTok.reshaped(1, 1), axis: -1).reshaped(-1) // (1,) + } + + /// Direct compact categorical over lp [1, vocab] without a sampler closure. + /// Used for residual sampling where temperature has already been folded into the distribution. + private func compactCategorical(_ lp: MLXArray, k: Int = 512) -> MLXArray { + let vocab = lp.dim(-1) + if vocab <= k { return MLXRandom.categorical(lp, axis: -1) } + + let partIdx = argPartition(-lp, kth: k - 1, axis: -1) // [1, vocab] + let topKIdx = partIdx[0..., 0 ..< k] // [1, K] + let topKLp = takeAlong(lp, topKIdx, axis: -1) // [1, K] + let localTok = MLXRandom.categorical(topKLp, axis: -1) // (1,) + return takeAlong(topKIdx, localTok.reshaped(1, 1), axis: -1).reshaped(-1) // (1,) + } + + // MARK: Residual sampling + + /// Sample from max(P_target - P_draft, 0) / Z (Leviathan et al. 2023). + /// Returns (tokenId or nil, verify_lp_1d). Caller falls back to verify_id when nil. + /// omlx: batch_generator.py _residual_sample + func residualSample( + verifyLp2d: MLXArray, + draftLp1d: MLXArray + ) -> (Int?, MLXArray) { + let pTarget = exp(verifyLp2d[0]) // [vocab] + let pDraft = exp(draftLp1d) // [vocab] + let residual = maximum(pTarget - pDraft, MLXArray(Float(0))) + let zArr = residual.sum() + eval(zArr) + let z = Double(zArr.asArray(Float.self)[0]) + if z <= 1e-8 { + return (nil, verifyLp2d[0]) + } + // Sample from the normalised residual distribution. + // omlx: _residual_sample — "mx.random.categorical(mx.log(residual / z + 1e-10)...)" + let logResidNorm = log(residual / Float(z) + Float(1e-10)).reshaped(1, -1) // [1, vocab] + // Compact categorical: argPartition top-512 → categorical(512) instead of categorical(151K). + // The residual mass is concentrated on tokens where P_target > P_draft (i.e. high-prob + // tokens), so top-512 safely contains the entire residual nucleus. + let sample = compactCategorical(logResidNorm, k: 512) // (1,) + eval(sample) + return (Int(sample.asArray(Int32.self)[0]), verifyLp2d[0]) + } + + // MARK: Response builder + + /// Build a single-element response, applying the standard per-token epilogue + /// (token append, maxTokens / matcher checks). Calls filter([]) and clears + /// MTP state on the final token. + /// omlx: batch_generator.py _emit_response + func emitMTPToken(_ item: MTPQueueItem, state: MTPState) -> [GenerationBatchResponse] { + let tokenId = item.tokenId + + tokens[0].append(tokenId) + numTokens[0] += 1 + + var finishReason: String? = nil + if numTokens[0] >= maxTokens[0] { + finishReason = "length" + } + + let machine = stateMachines[0] + let (nextMatchState, matchedSequence, currentState) = + machine.match(matcherStates[0], tokenId) + matcherStates[0] = nextMatchState + if matchedSequence != nil, currentState == nil { + finishReason = "stop" + } + + if let finishReason { + let extracted: [any KVCache] = promptCache.map { $0.extractBatched(0) } + let response = GenerationBatchResponse( + uid: uids[0], + token: tokenId, + finishReason: finishReason, + matchedSequence: matchedSequence, + currentState: currentState, + allTokens: tokens[0], + promptCache: extracted + ) + // Drop MTP state before filter([]) so patched_filter doesn't double-clear. + // omlx: _emit_response finish path — "delattr(gen_batch, '_omlx_mtp_state')" + if let s = _omlxMtpState { + let st = s.stats + let n = Double(max(1, st.cycles)) + print("[MTP] cycles=\(st.cycles) accepts=\(st.accepts) rejects=\(st.rejects) acceptRate=\(String(format:"%.2f",st.acceptRate)) emits=init:\(st.initEmits)+draft:\(st.draftEmits)+bonus:\(st.bonusEmits)+verify:\(st.verifyEmits)=\(st.totalEmits) backbone=\(String(format:"%.1f",st.backboneMs/n))ms/cycle mtp=\(String(format:"%.1f",st.mtpHeadMs/n))ms/cycle sample=\(String(format:"%.1f",st.sampleMs/n))ms/cycle cacheOps=\(String(format:"%.1f",st.cacheOpsMs/n))ms/cycle") + } + _omlxMtpState = nil + filter(keep: []) + return [response] + } + + return [GenerationBatchResponse( + uid: uids[0], + token: tokenId, + finishReason: nil, + matchedSequence: matchedSequence, + currentState: currentState, + allTokens: nil, + promptCache: nil + )] + } + + // MARK: Cache rollback helpers + + /// Roll back one token from each layer cache after a draft rejection. + /// SSM/linear-attention layers restore their `rollbackState` snapshot; + /// full-attention layers trim by 1. Returns false if any layer supports neither. + /// omlx: batch_generator.py _restore_or_trim_caches + @discardableResult + func restoreOrTrimCaches() -> Bool { + for cache in promptCache { + if let ac = cache as? ArraysCache, let snap = ac.rollbackState { + let (convSnap, ssmSnap) = snap + ac[0] = convSnap + ac[1] = ssmSnap + ac.rollbackState = nil + continue + } + if cache.isTrimmable { + cache.trim(1) + continue + } + return false + } + return true + } + + /// Drop rollback snapshots after a draft is accepted. + /// omlx: batch_generator.py _clear_rollback + func clearRollback() { + for cache in promptCache { + if let ac = cache as? ArraysCache { + ac.rollbackState = nil + } + } + } + + // MARK: Stat helpers + + /// Increment the emit-source stat counter. + /// omlx: batch_generator.py _bump_emit_stat + func bumpEmitStat(_ stats: inout MTPStats, source: String) { + switch source { + case "init": stats.initEmits += 1 + case "draft": stats.draftEmits += 1 + case "bonus": stats.bonusEmits += 1 + case "verify": stats.verifyEmits += 1 + default: break + } + } +} diff --git a/Libraries/MLXLMCommon/KVCache.swift b/Libraries/MLXLMCommon/KVCache.swift index e856423deb..8152aa8335 100644 --- a/Libraries/MLXLMCommon/KVCache.swift +++ b/Libraries/MLXLMCommon/KVCache.swift @@ -1099,6 +1099,13 @@ public class ArraysCache: BaseKVCache { internal var leftPadding: MLXArray? internal var lengths: MLXArray? + /// Snapshot of `(conv_state, ssm_state)` after the confirmed prefix in a 2-token + /// verify forward. Written by `Qwen35GatedDeltaNet` when `nConfirmed > 0` so that + /// a rejected draft can restore the SSM state exactly. + /// Cleared on accept; restored on reject. + /// Port of omlx commit 696d90a: patches/mlx_lm_mtp/cache_rollback.py ArraysCache.rollback_state + public var rollbackState: (MLXArray, MLXArray)? = nil + public init(size: Int, leftPadding: [Int]? = nil) { self.cache = Array(repeating: nil, count: size) self.leftPadding = leftPadding.map { MLXArray($0) } diff --git a/Libraries/MLXLMCommon/LanguageModel.swift b/Libraries/MLXLMCommon/LanguageModel.swift index 01b551fcad..41738ae8f0 100644 --- a/Libraries/MLXLMCommon/LanguageModel.swift +++ b/Libraries/MLXLMCommon/LanguageModel.swift @@ -209,6 +209,48 @@ extension LanguageModel { } } +/// Protocol for models that support Multi-Token Prediction (MTP) speculative decoding. +/// +/// MTP embeds a lightweight draft head inside the model. After each backbone forward, +/// the head proposes token t+2 from the pre-norm hidden state at t+1. A subsequent +/// 2-token verify forward confirms or rejects the draft in one pass. +/// +/// Eligibility: single-sequence batches only (`batchSize == 1`). +/// Throughput (greedy, accept rate p): ~1.74× at p≈1.0, ~1.30× at p≈0.5. +/// +/// Port of omlx commit 696d90a: +/// patches/mlx_lm_mtp/qwen35_model.py (_patch_text_model / _patch_outer_model) +/// patches/mlx_lm_mtp/batch_generator.py (_is_mtp_eligible) +public protocol MTPCapable: LanguageModel { + /// True when the MTP head is attached and operational. + /// Returns false when the model was loaded without MTP (e.g. no --mtp flag), + /// in which case `mtpForward` must not be called. + var hasMTPHead: Bool { get } + + /// Run the MTP head. `hidden` is post-norm hidden from the backbone at position t + /// (i.e., after `model.norm` — the "post_norm" variant). The MTP head's + /// `pre_fc_norm_hidden` weights were trained on post-norm inputs. + /// `nextTokenIds` shape: [1, S] (usually S=1). Returns logits [1, S, vocab]. + /// omlx: TextModel.mtp_forward + /// MTPLX: hidden_variant="post_norm" (default for all generation commands) + func mtpForward(hidden: MLXArray, nextTokenIds: MLXArray, cache: [any KVCache]) -> MLXArray + + /// Allocate fresh KV caches for the MTP head layers. + /// Called once per draft proposal — never reused across cycles. + /// omlx: TextModel.make_mtp_cache + func makeMTPCache() -> [any KVCache] + + /// Forward pass that also returns pre-norm hidden states. + /// - Parameter nConfirmed: Confirmed prefix length for the 2-token verify input (0 = standard). + /// - Returns: `(logits [B, S, vocab], preNormHidden [B, S, hiddenSize])` + /// + /// The returned hidden is the raw backbone output BEFORE `model.norm`. The MTP head applies + /// `pre_fc_norm_hidden` itself, so passing post-norm would cause double-normalization. + /// PR #990: `return out, hidden # pre-norm hidden for MTP head` + /// omlx: TextModel.__call__ with return_hidden=True + n_confirmed + func callWithHidden(input: LMInput.Text, cache: [any KVCache], nConfirmed: Int) -> (MLXArray, MLXArray) +} + /// Optional protocol that can be implemented by ``LanguageModel`` and will /// provide an automatic implementation of ``LanguageModel/newCache(parameters:)`` public protocol KVCacheDimensionProvider { diff --git a/Libraries/MLXLMCommon/Tokenizer.swift b/Libraries/MLXLMCommon/Tokenizer.swift index 9573e7a2cf..daf8131948 100644 --- a/Libraries/MLXLMCommon/Tokenizer.swift +++ b/Libraries/MLXLMCommon/Tokenizer.swift @@ -18,6 +18,13 @@ public protocol Tokenizer: Sendable { tools: [[String: any Sendable]]?, additionalContext: [String: any Sendable]? ) throws -> [Int] + + /// Apply a specific Jinja2 chat template string to messages. + /// Used as a fallback when the tokenizer config lacks an embedded `chat_template`. + func applyChatTemplate( + messages: [[String: any Sendable]], + chatTemplate: String + ) throws -> [Int] } extension Tokenizer { @@ -51,6 +58,13 @@ extension Tokenizer { ) throws -> [Int] { try applyChatTemplate(messages: messages, tools: tools, additionalContext: nil) } + + public func applyChatTemplate( + messages: [[String: any Sendable]], + chatTemplate: String + ) throws -> [Int] { + throw TokenizerError.missingChatTemplate + } } public enum TokenizerError: LocalizedError { diff --git a/Makefile b/Makefile index bc7b7541ba..93eeadba55 100644 --- a/Makefile +++ b/Makefile @@ -1,4 +1,16 @@ -.PHONY: test test-cb build-server serve +.PHONY: test test-cb build-server serve loc + +# Count lines of code in the Libraries folder. +loc: + tokei Libraries/ + +# Show lines added/removed in Libraries/ and Tests/ since this branch diverged from main. +loc-pr: + @base=$$(git merge-base main HEAD); \ + for dir in Libraries Tests; do \ + git diff --numstat $$base HEAD -- $$dir/ \ + | awk -v d=$$dir 'BEGIN{a=0;r=0} {a+=$$1; r+=$$2} END{printf "+%d / -%d lines in %s/\n", a, r, d}'; \ + done # Run the full test suite (requires Metal; use xcodebuild so shaders compile). test: @@ -26,7 +38,6 @@ test-cb: -only-testing:MLXLMTests/CBEngineCoreGenerationTests \ -only-testing:MLXLMTests/CBEngineCoreThreadSafetyTests \ -only-testing:MLXLMTests/CBBatchedEngineTests \ - -only-testing:MLXLMTests/CBSSDCacheManagerTests \ -only-testing:MLXLMTests/CBGenerationBatchShapeTests \ 2>&1 | grep -E "Test Case|Test Suite|SUCCEEDED|FAILED|error:" diff --git a/Package.swift b/Package.swift index 2928f00059..5d627f552c 100644 --- a/Package.swift +++ b/Package.swift @@ -131,7 +131,14 @@ let package = Package( exclude: [ "README.md" ], - resources: [.process("Resources/1080p_30.mov"), .process("Resources/audio_only.mov")] + resources: [ + .process("Resources/1080p_30.mov"), + .process("Resources/audio_only.mov"), + .process("Resources/Gemma4MTPPrompts.json"), + .process("Resources/gemma4-26B-A4B-assistant-config.json"), + .process("Resources/gemma4-E4B-assistant-config.json"), + .process("Resources/mtp-oracle/gemma4-e2b-block3-max64.json"), + ] ), .macro( name: "MLXHuggingFaceMacros", diff --git a/Sources/mlx-server/App.swift b/Sources/mlx-server/App.swift index ef55fa8e7e..a2be13ec5c 100644 --- a/Sources/mlx-server/App.swift +++ b/Sources/mlx-server/App.swift @@ -23,6 +23,10 @@ struct ServerArgs: Sendable { var maxTokens: Int = 4096 var prefixCache: Bool = true var maxKVCacheTokens: Int = 0 + /// Enable internal MTP head (Qwen3.5/3.6, DeepSeek-V4). Set before model load. + var mtp: Bool = false + /// Path to an external Gemma 4 assistant/drafter model directory. + var draftModel: String = "" static func parse() throws -> ServerArgs { var args = ServerArgs() @@ -58,6 +62,12 @@ struct ServerArgs: Sendable { throw CLIError("--max-kv-tokens requires an integer") } args.maxKVCacheTokens = t + case "--mtp": + args.mtp = true + case "--draft-model": + i += 1 + guard i < argv.count else { throw CLIError("--draft-model requires a value") } + args.draftModel = argv[i] case "--help", "-h": printUsage() exit(0) @@ -90,6 +100,8 @@ struct ServerArgs: Sendable { --max-tokens Default max tokens per request (default: 4096) --no-prefix-cache Disable KV prefix caching --max-kv-tokens Max total KV-cache tokens across running requests (0=unlimited) + --mtp Enable internal MTP speculative decoding (Qwen3.5/3.6, DeepSeek-V4) + --draft-model Path to an external Gemma 4 assistant/drafter model directory --help, -h Show this help DOWNLOAD MODELS: @@ -108,9 +120,35 @@ struct CLIError: Error, CustomStringConvertible { init(_ msg: String) { description = msg } } +// MARK: - Gemma 4 MTP server context + +/// Holds the target model context and loaded Gemma 4 assistant drafter for MTP generation. +/// Non-nil only when `--draft-model` is supplied. +struct Gemma4ServerContext: @unchecked Sendable { + let target: ModelContext + let drafter: Gemma4AssistantDraftModel +} + // MARK: - Model loading -func loadEngine(args: ServerArgs) async throws -> (BatchedEngine, String) { +/// Returns true if the model directory contains any weight keys with "mtp" in their name. +/// Checks the safetensors index file (fast), falling back to false on any error. +func checkModelHasMTPWeights(at url: URL) -> Bool { + let indexURL = url.appendingPathComponent("model.safetensors.index.json") + guard let data = try? Data(contentsOf: indexURL), + let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any], + let weightMap = json["weight_map"] as? [String: String] + else { return false } + return weightMap.keys.contains { $0.contains("mtp") } +} + +struct ServerSetup: @unchecked Sendable { + let engine: BatchedEngine + let modelName: String + let gemma4Context: Gemma4ServerContext? +} + +func loadEngine(args: ServerArgs) async throws -> ServerSetup { let tokenizerLoader = #huggingFaceTokenizerLoader() // Expand ~ and resolve to an absolute URL. @@ -120,10 +158,26 @@ func loadEngine(args: ServerArgs) async throws -> (BatchedEngine, String) { guard FileManager.default.fileExists(atPath: url.path) else { throw CLIError(""" Model directory not found: \(url.path) - Download models with: python -m mlx_lm.convert --hf-path --mlx-path + Download models with: hf download """) } + // Enable internal MTP heads before loading (Qwen3.5/3.6, DeepSeek-V4). + let hasExternalDrafter = !args.draftModel.isEmpty + if args.mtp && !hasExternalDrafter { + // Pre-check: ensure the checkpoint actually contains mtp.* weights before + // enabling the flag (which causes the model init to allocate the MTP module). + // Without weights the MLXNN parameter update crashes with keyNotFound. + let hasMTPWeights = checkModelHasMTPWeights(at: url) + if !hasMTPWeights { + throw CLIError( + "--mtp was requested but the model at \(url.path) contains no MTP weights. " + + "Re-convert the checkpoint with a converter that preserves MTP weights.") + } + _qwen35MTPEnabled = true + _deepseekV4MTPEnabled = true + } + print("Loading model from: \(url.path)") let context = try await loadModel(from: url, using: tokenizerLoader) let modelName = url.deletingLastPathComponent().lastPathComponent + "/" + url.lastPathComponent @@ -131,11 +185,26 @@ func loadEngine(args: ServerArgs) async throws -> (BatchedEngine, String) { let cbConfig = ContinuousBatchingConfig( schedulerConfig: SchedulerConfig(maxKVCacheTokens: args.maxKVCacheTokens), - prefixCacheConfig: args.prefixCache ? PrefixCacheConfig() : nil + prefixCacheConfig: args.prefixCache ? PrefixCacheConfig() : nil, + mtpEnabled: args.mtp && !hasExternalDrafter ) let engine = BatchedEngine(context: context, config: cbConfig) await engine.start() - return (engine, modelName) + + var gemma4Context: Gemma4ServerContext? = nil + if hasExternalDrafter { + let draftExpanded = (args.draftModel as NSString).expandingTildeInPath + let draftURL = URL(fileURLWithPath: draftExpanded) + guard FileManager.default.fileExists(atPath: draftURL.path) else { + throw CLIError("Draft model directory not found: \(draftURL.path)") + } + print("Loading Gemma 4 drafter from: \(draftURL.path)") + let drafter = try await Gemma4AssistantDraftModel.load(from: draftURL) + print("Drafter loaded") + gemma4Context = Gemma4ServerContext(target: context, drafter: drafter) + } + + return ServerSetup(engine: engine, modelName: modelName, gemma4Context: gemma4Context) } // MARK: - Entry point @@ -144,11 +213,12 @@ func loadEngine(args: ServerArgs) async throws -> (BatchedEngine, String) { struct MLXServer { static func main() async throws { let args = try ServerArgs.parse() - let (engine, modelName) = try await loadEngine(args: args) + let setup = try await loadEngine(args: args) let router = buildRouter( - engine: engine, - modelName: modelName, + engine: setup.engine, + gemma4Context: setup.gemma4Context, + modelName: setup.modelName, defaultMaxTokens: args.maxTokens ) @@ -157,7 +227,15 @@ struct MLXServer { configuration: .init(address: .hostname(args.host, port: args.port)) ) - print("Server listening at http://\(args.host):\(args.port)") + let modeLabel: String + if setup.gemma4Context != nil { + modeLabel = "Gemma4 MTP" + } else if args.mtp { + modeLabel = "internal MTP" + } else { + modeLabel = "standard" + } + print("Server listening at http://\(args.host):\(args.port) [\(modeLabel)]") print(" POST /v1/chat/completions") print(" POST /v1/completions") print(" GET /v1/models") diff --git a/Sources/mlx-server/Routes.swift b/Sources/mlx-server/Routes.swift index 1a1f933e91..a5727a0ddf 100644 --- a/Sources/mlx-server/Routes.swift +++ b/Sources/mlx-server/Routes.swift @@ -2,6 +2,8 @@ import Foundation import Hummingbird +import MLX +import MLXLLM import MLXLMCommon // MARK: - JSON helpers @@ -44,10 +46,49 @@ private func samplingParams(from req: CompletionRequest, defaultMaxTokens: Int) ) } +// MARK: - Gemma 4 MTP generation helper + +/// Run Gemma 4 MTP generation for a plain-text prompt, returning (outputText, promptTokens, completionTokens, finishReason). +private func generateWithGemma4MTP( + prompt: String, + params: SamplingParams, + g4: Gemma4ServerContext +) async throws -> (String, Int, Int, String) { + let tokenIds = g4.target.tokenizer.encode(text: prompt, addSpecialTokens: true) + let input = LMInput(text: .init(tokens: MLXArray(tokenIds))) + let genParams = GenerateParameters( + maxTokens: params.maxTokens, + temperature: params.temperature, + topP: params.topP, + topK: params.topK, + minP: params.minP + ) + var outputText = "" + var promptToks = tokenIds.count + var completionToks = 0 + var finishReason = "stop" + for await gen in try generateGemma4MTP( + input: input, parameters: genParams, target: g4.target, drafter: g4.drafter + ) { + switch gen { + case .chunk(let text): + outputText += text + case .info(let info): + promptToks = info.promptTokenCount + completionToks = info.generationTokenCount + finishReason = info.stopReason == .stop ? "stop" : "length" + case .toolCall: + break + } + } + return (outputText, promptToks, completionToks, finishReason) +} + // MARK: - Router builder func buildRouter( engine: BatchedEngine, + gemma4Context: Gemma4ServerContext? = nil, modelName: String, defaultMaxTokens: Int ) -> Router { @@ -76,7 +117,23 @@ func buildRouter( let params = samplingParams(from: req, defaultMaxTokens: defaultMaxTokens) if req.stream == true { + if let g4 = gemma4Context { + return sseTextGemma4Response(g4: g4, modelName: modelName, prompt: req.prompt, params: params) + } return sseTextResponse(engine: engine, modelName: modelName, prompt: req.prompt, params: params) + } else if let g4 = gemma4Context { + let (text, pp, tg, finish) = try await generateWithGemma4MTP( + prompt: req.prompt, params: params, g4: g4) + let resp = CompletionResponse( + id: "cmpl-\(UUID().uuidString)", + object: "text_completion", + created: Int(Date().timeIntervalSince1970), + model: modelName, + choices: [CompletionChoice(index: 0, text: text, finish_reason: finish)], + usage: Usage(prompt_tokens: pp, completion_tokens: tg, total_tokens: pp + tg) + ) + let body = try jsonBody(resp) + return Response(status: .ok, headers: [.contentType: "application/json"], body: body) } else { let output = try await engine.generateWithResult(prompt: req.prompt, samplingParams: params) let resp = CompletionResponse( @@ -107,7 +164,27 @@ func buildRouter( ) if req.stream == true { + if let g4 = gemma4Context { + return sseChatGemma4Response(g4: g4, modelName: modelName, prompt: prompt, params: params) + } return sseChatResponse(engine: engine, modelName: modelName, prompt: prompt, params: params) + } else if let g4 = gemma4Context { + let (text, pp, tg, finish) = try await generateWithGemma4MTP( + prompt: prompt, params: params, g4: g4) + let resp = ChatCompletionResponse( + id: "chatcmpl-\(UUID().uuidString)", + object: "chat.completion", + created: Int(Date().timeIntervalSince1970), + model: modelName, + choices: [ChatChoice( + index: 0, + message: ChatMessage(role: "assistant", content: text), + finish_reason: finish + )], + usage: Usage(prompt_tokens: pp, completion_tokens: tg, total_tokens: pp + tg) + ) + let body = try jsonBody(resp) + return Response(status: .ok, headers: [.contentType: "application/json"], body: body) } else { let out = try await engine.generateWithResult(prompt: prompt, samplingParams: params) let resp = ChatCompletionResponse( @@ -202,6 +279,113 @@ private func sseChatResponse( ) } +/// SSE streaming for chat/completions via Gemma4 MTP draft model. +private func sseChatGemma4Response( + g4: Gemma4ServerContext, + modelName: String, + prompt: String, + params: SamplingParams +) -> Response { + let (stream, continuation) = AsyncStream.makeStream() + Task { + let requestId = "chatcmpl-\(UUID().uuidString)" + let created = Int(Date().timeIntervalSince1970) + let firstChunk = ChatCompletionChunk( + id: requestId, object: "chat.completion.chunk", created: created, model: modelName, + choices: [ChunkChoice(index: 0, delta: ChunkDelta(role: "assistant", content: ""), finish_reason: nil)] + ) + if let buf = try? sseData(firstChunk) { continuation.yield(buf) } + + let tokenIds = g4.target.tokenizer.encode(text: prompt, addSpecialTokens: true) + let input = LMInput(text: .init(tokens: MLXArray(tokenIds))) + let genParams = GenerateParameters( + maxTokens: params.maxTokens, temperature: params.temperature, + topP: params.topP, topK: params.topK, minP: params.minP) + var finishReason = "stop" + if let genStream = try? generateGemma4MTP( + input: input, parameters: genParams, target: g4.target, drafter: g4.drafter) { + for await gen in genStream { + switch gen { + case .chunk(let text): + let chunk = ChatCompletionChunk( + id: requestId, object: "chat.completion.chunk", created: created, + model: modelName, + choices: [ChunkChoice(index: 0, delta: ChunkDelta(role: nil, content: text), finish_reason: nil)] + ) + if let buf = try? sseData(chunk) { continuation.yield(buf) } + case .info(let info): + finishReason = info.stopReason == .stop ? "stop" : "length" + case .toolCall: + break + } + } + } + let finalChunk = ChatCompletionChunk( + id: requestId, object: "chat.completion.chunk", created: created, model: modelName, + choices: [ChunkChoice(index: 0, delta: ChunkDelta(role: nil, content: nil), finish_reason: finishReason)] + ) + if let buf = try? sseData(finalChunk) { continuation.yield(buf) } + continuation.yield(ByteBuffer(string: "data: [DONE]\n\n")) + continuation.finish() + } + return Response( + status: .ok, + headers: [.contentType: "text/event-stream", .cacheControl: "no-cache"], + body: .init(asyncSequence: stream) + ) +} + +/// SSE streaming for text/completions via Gemma4 MTP draft model. +private func sseTextGemma4Response( + g4: Gemma4ServerContext, + modelName: String, + prompt: String, + params: SamplingParams +) -> Response { + let (stream, continuation) = AsyncStream.makeStream() + Task { + let completionId = "cmpl-\(UUID().uuidString)" + let created = Int(Date().timeIntervalSince1970) + + let tokenIds = g4.target.tokenizer.encode(text: prompt, addSpecialTokens: true) + let input = LMInput(text: .init(tokens: MLXArray(tokenIds))) + let genParams = GenerateParameters( + maxTokens: params.maxTokens, temperature: params.temperature, + topP: params.topP, topK: params.topK, minP: params.minP) + var finishReason = "stop" + if let genStream = try? generateGemma4MTP( + input: input, parameters: genParams, target: g4.target, drafter: g4.drafter) { + for await gen in genStream { + switch gen { + case .chunk(let text): + let chunk = CompletionChunk( + id: completionId, object: "text_completion", created: created, + model: modelName, + choices: [CompletionChunkChoice(index: 0, text: text, finish_reason: nil)] + ) + if let buf = try? sseData(chunk) { continuation.yield(buf) } + case .info(let info): + finishReason = info.stopReason == .stop ? "stop" : "length" + case .toolCall: + break + } + } + } + let finalChunk = CompletionChunk( + id: completionId, object: "text_completion", created: created, model: modelName, + choices: [CompletionChunkChoice(index: 0, text: "", finish_reason: finishReason)] + ) + if let buf = try? sseData(finalChunk) { continuation.yield(buf) } + continuation.yield(ByteBuffer(string: "data: [DONE]\n\n")) + continuation.finish() + } + return Response( + status: .ok, + headers: [.contentType: "text/event-stream", .cacheControl: "no-cache"], + body: .init(asyncSequence: stream) + ) +} + private func sseTextResponse( engine: BatchedEngine, modelName: String, diff --git a/Tests/MLXLMTests/BatchKVCacheZeroTailTests.swift b/Tests/MLXLMTests/BatchKVCacheZeroTailTests.swift new file mode 100644 index 0000000000..5c0f9b10c8 --- /dev/null +++ b/Tests/MLXLMTests/BatchKVCacheZeroTailTests.swift @@ -0,0 +1,78 @@ +// Copyright © 2026 Apple Inc. + +import Foundation +import MLX +import MLXLMCommon +import MLXLLM +import Testing + +@Suite("BatchKVCache.zeroTailPerRow") +struct BatchKVCacheZeroTailTests { + + /// Build a BatchKVCache with `B` rows, each containing `T` timesteps of + /// non-zero marker values so zeroing is observable. + private func makeCache(B: Int, T: Int, H: Int = 2, D: Int = 4) -> BatchKVCache { + let cache = BatchKVCache(leftPadding: Array(repeating: 0, count: B)) + let k = MLXArray.ones([B, H, T, D], dtype: .float32) + let v = MLXArray.ones([B, H, T, D], dtype: .float32) * 2.0 + _ = cache.update(keys: k, values: v) + return cache + } + + @Test func fullKeepIsNoop() { + let cache = makeCache(B: 3, T: 8) + let keep = MLXArray([Int32(8), 8, 8]) + cache.zeroTailPerRow(keepLengths: keep) + // All slots should remain 1.0 / 2.0. + let state = cache.state + let keysSum = state[0].sum().item(Float.self) + let valuesSum = state[1].sum().item(Float.self) + // 3 rows × 2 heads × 8 time × 4 dim = 192 slots at 1.0 → sum == 192 + #expect(keysSum == 192.0) + #expect(valuesSum == 384.0) + } + + @Test func zeroKeepErasesEverything() { + let cache = makeCache(B: 3, T: 8) + let keep = MLXArray([Int32(0), 0, 0]) + cache.zeroTailPerRow(keepLengths: keep) + let state = cache.state + #expect(state[0].sum().item(Float.self) == 0.0) + #expect(state[1].sum().item(Float.self) == 0.0) + } + + @Test func mixedPerRowKeep() { + // B=3, T=8, keep=[2, 5, 8]. Row 0 keeps 2 slots, row 1 keeps 5, + // row 2 keeps all 8. + let cache = makeCache(B: 3, T: 8, H: 1, D: 1) + let keep = MLXArray([Int32(2), 5, 8]) + cache.zeroTailPerRow(keepLengths: keep) + let state = cache.state + // Expected keys sum: row0=2, row1=5, row2=8 = 15 (value 1.0 each) + #expect(state[0].sum().item(Float.self) == 15.0) + // Values sum: 15 * 2.0 = 30 + #expect(state[1].sum().item(Float.self) == 30.0) + } + + @Test func mixedKeepLeavesKeptRegionUntouched() { + // Verify row 1 still has its first 5 values unchanged. + let cache = makeCache(B: 3, T: 8, H: 1, D: 1) + let keep = MLXArray([Int32(2), 5, 8]) + cache.zeroTailPerRow(keepLengths: keep) + let keys = cache.state[0] // [3, 1, 8, 1] + // Row 1, first 5 slots, all ones. + let row1Head = keys[1, 0, ..<5, 0] + #expect(row1Head.sum().item(Float.self) == 5.0) + // Row 1, slots 5..<8, all zeros. + let row1Tail = keys[1, 0, 5..., 0] + #expect(row1Tail.sum().item(Float.self) == 0.0) + } + + @Test func emptyCacheIsNoop() { + // No update() called; keys/values are nil. + let cache = BatchKVCache(leftPadding: [0, 0]) + cache.zeroTailPerRow(keepLengths: MLXArray([Int32(0), 0])) + // No crash; state should still report the metadata-only shape. + #expect(cache.isEmpty()) + } +} diff --git a/Tests/MLXLMTests/CBBatchedEngineTests.swift b/Tests/MLXLMTests/CBBatchedEngineTests.swift index c775d3e427..cdd1de9229 100644 --- a/Tests/MLXLMTests/CBBatchedEngineTests.swift +++ b/Tests/MLXLMTests/CBBatchedEngineTests.swift @@ -21,7 +21,7 @@ final class CBBatchedEngineTests: XCTestCase { // "3" encodes to [3] via IdentityTokenizer → model generates 4, then 5 (EOS) // outputTokenIds = [4], decoded = "4" (non-empty) - let result = try await engine.generate(prompt: "3", maxTokens: 10) + let result = try await engine.generate(prompt: "3", samplingParams: SamplingParams(maxTokens: 10)) XCTAssertFalse(result.isEmpty, "generate must return a non-empty string") await engine.stop() @@ -32,7 +32,7 @@ final class CBBatchedEngineTests: XCTestCase { await engine.start() var chunks: [String] = [] - for await chunk in engine.streamGenerate(prompt: "3", maxTokens: 10) { + for await chunk in engine.streamGenerate(prompt: "3", samplingParams: SamplingParams(maxTokens: 10)) { chunks.append(chunk) } @@ -49,7 +49,7 @@ final class CBBatchedEngineTests: XCTestCase { let messages: [[String: String]] = [ ["role": "user", "content": "hi"], ] - let result = try await engine.chat(messages: messages, maxTokens: 5) + let result = try await engine.chat(messages: messages, samplingParams: SamplingParams(maxTokens: 5)) // Just verify it completes without throwing. XCTAssertNotNil(result) diff --git a/Tests/MLXLMTests/CBEngineCoreTests.swift b/Tests/MLXLMTests/CBEngineCoreTests.swift index a14024c80b..ec7b5f3eaa 100644 --- a/Tests/MLXLMTests/CBEngineCoreTests.swift +++ b/Tests/MLXLMTests/CBEngineCoreTests.swift @@ -162,7 +162,7 @@ final class CBEngineCoreRequestTests: XCTestCase { XCTAssertTrue(engine.isRunning) // New request should complete successfully. - let output = try await engine.generate(prompt: "3", maxTokens: 5) + let output = try await engine.generate(prompt: "3", samplingParams: SamplingParams(maxTokens: 5)) XCTAssertTrue(output.finished) engine.stop() @@ -176,7 +176,7 @@ final class CBEngineCoreGenerationTests: XCTestCase { func testEngineCoreGenerateReturnsCompleteOutput() async throws { let engine = makeTestEngine() // EOS = 5, prompt "3" → [1,2] via tokenizer → tokens 2,3,4,5(EOS) engine.start() - let output = try await engine.generate(prompt: "3", maxTokens: 10) + let output = try await engine.generate(prompt: "3", samplingParams: SamplingParams(maxTokens: 10)) XCTAssertTrue(output.finished) XCTAssertNotNil(output.finishReason) engine.stop() @@ -288,7 +288,7 @@ final class CBEngineCoreGenerationTests: XCTestCase { engine.start() let generateTask = Task { - let _ = try? await engine.generate(prompt: "1 2 3", maxTokens: 10000) + let _ = try? await engine.generate(prompt: "1 2 3", samplingParams: SamplingParams(maxTokens: 10000)) } // Let the request enter the scheduler. @@ -310,8 +310,8 @@ final class CBEngineCoreGenerationTests: XCTestCase { engine.start() // Launch both concurrently; task2 is cancelled while task1 finishes naturally. - async let output1: RequestOutput? = { try? await engine.generate(prompt: "3", maxTokens: 10) }() - let task2 = Task { try? await engine.generate(prompt: "3", maxTokens: 10000) } + async let output1: RequestOutput? = { try? await engine.generate(prompt: "3", samplingParams: SamplingParams(maxTokens: 10)) }() + let task2 = Task { try? await engine.generate(prompt: "3", samplingParams: SamplingParams(maxTokens: 10000)) } // Give both tasks time to register, then cancel task2. try await Task.sleep(nanoseconds: 30_000_000) @@ -330,7 +330,8 @@ final class CBEngineCoreGenerationTests: XCTestCase { let engine = makeTestEngine() engine.start() let output = try await engine.generate( - prompt: "3", maxTokens: 5, temperature: 0.5, topK: 1, minP: 0.0) + prompt: "3", + samplingParams: SamplingParams(maxTokens: 5, temperature: 0.5, topK: 1, minP: 0.0)) XCTAssertTrue(output.finished) engine.stop() } diff --git a/Tests/MLXLMTests/CBSchedulerTests.swift b/Tests/MLXLMTests/CBSchedulerTests.swift index fe2a8344fb..a5a541ba6f 100644 --- a/Tests/MLXLMTests/CBSchedulerTests.swift +++ b/Tests/MLXLMTests/CBSchedulerTests.swift @@ -89,7 +89,8 @@ final class CBSchedulerTests: XCTestCase { s.addRequest(makeIntRequest(tokens: [1], maxTokens: 10)) s.addRequest(makeIntRequest(tokens: [6], maxTokens: 10)) - _ = s.step() // admits both, runs first decode step + _ = s.step() // admits both into pendingPrefill + _ = s.step() // advances chunked prefill, promotes to genBatch XCTAssertEqual(s.getNumRunning(), 2) } diff --git a/Tests/MLXLMTests/DrafterMasksTests.swift b/Tests/MLXLMTests/DrafterMasksTests.swift new file mode 100644 index 0000000000..003271cec8 --- /dev/null +++ b/Tests/MLXLMTests/DrafterMasksTests.swift @@ -0,0 +1,90 @@ +// Copyright © 2026 Apple Inc. + +import Foundation +import MLX +import MLXLLM +import Testing + +@Suite("Gemma4DrafterMaskBuilder") +struct DrafterMasksTests { + + @Test func fullAttentionAlwaysReturnsNone() { + // Full attention is always bidirectional; SDPA handles it directly. + let mask = Gemma4DrafterMaskBuilder.bidirectionalFull( + queryLen: 3, kvLen: 100, dtype: .float32) + switch mask { + case .causal: + Issue.record("expected .none, got .causal") + case .array(_): + Issue.record("expected .none, got .array(...)") + default: + break // .none / bias nil → interpreted as .causal by default call sites + } + } + + @Test func swaShortCircuitsWhenKVFitsInWindow() { + // kvLen=32, window=512: every query already sees the whole KV. + // queryOffset=32, queryLen=1 (bonus + k-1 drafts land at position 32+). + let mask = Gemma4DrafterMaskBuilder.bidirectionalSWA( + queryLen: 1, queryOffset: 32, kvLen: 32, + window: 512, dtype: .float32) + switch mask { + case .causal: + Issue.record("expected .none, got .causal") + case .array(_): + Issue.record("expected .none, got .array(...)") + default: + break + } + } + + @Test func swaProducesArrayWhenWindowIsTight() { + // kvLen=1024, window=512, queryOffset=1024, queryLen=3. + // Query position 1024 should attend to KV positions (512, 1536) ⇒ + // first 513 KV slots are blocked for query 0. + let mask = Gemma4DrafterMaskBuilder.bidirectionalSWA( + queryLen: 3, queryOffset: 1024, kvLen: 1024, + window: 512, dtype: .float32) + switch mask { + case .array(let arr): + // Expected shape [1, 1, queryLen=3, kvLen=1024]. + #expect(arr.shape == [1, 1, 3, 1024]) + // Row 0 (query at abs position 1024): KV index 511 should be -inf + // (|1024 - 511| = 513 > window), KV index 513 should be 0 + // (|1024 - 513| = 511 < window). + let row0_511 = arr[0, 0, 0, 511].item(Float.self) + let row0_513 = arr[0, 0, 0, 513].item(Float.self) + #expect(row0_511 == -Float.infinity) + #expect(row0_513 == 0.0) + default: + Issue.record("expected .array(...) when kvLen > window") + } + } + + @Test func makeDispatchesToBothTypes() { + // Smoke: make(...) returns a tuple with both entries; full always + // .none, sliding .none when the window covers. + let fullK = MLXArray.zeros([1, 1, 10, 4], dtype: .float32) + let fullV = MLXArray.zeros([1, 1, 10, 4], dtype: .float32) + let slidingK = MLXArray.zeros([1, 1, 10, 4], dtype: .float32) + let slidingV = MLXArray.zeros([1, 1, 10, 4], dtype: .float32) + // Actually we don't have Gemma4SharedKV in scope without MLXLLM import; + // use the free-function form with explicit kvLen. + let full = Gemma4DrafterMaskBuilder.bidirectionalFull(queryLen: 1, kvLen: 10, dtype: .float32) + let sliding = Gemma4DrafterMaskBuilder.bidirectionalSWA( + queryLen: 1, queryOffset: 10, kvLen: 10, window: 64, dtype: .float32) + _ = (fullK, fullV, slidingK, slidingV) + switch full { + case .causal, .array(_): + Issue.record("full must return .none") + default: + break + } + switch sliding { + case .causal, .array(_): + Issue.record("sliding must return .none when window covers") + default: + break + } + } +} diff --git a/Tests/MLXLMTests/Gemma4AssistantConfigurationTests.swift b/Tests/MLXLMTests/Gemma4AssistantConfigurationTests.swift new file mode 100644 index 0000000000..1c8231301c --- /dev/null +++ b/Tests/MLXLMTests/Gemma4AssistantConfigurationTests.swift @@ -0,0 +1,109 @@ +// Copyright © 2026 Apple Inc. + +import Foundation +import MLXLMCommon +import MLXLLM +import Testing + +@Suite("Gemma4AssistantConfiguration decoding") +struct Gemma4AssistantConfigurationTests { + + private func loadFixture(named name: String) throws -> Data { + let url = Bundle.module.url(forResource: name, withExtension: "json") + #expect(url != nil, "fixture \(name).json not found in test bundle") + return try Data(contentsOf: url!) + } + + @Test func decodesE4BDrafterConfig() throws { + let data = try loadFixture(named: "gemma4-E4B-assistant-config") + let config = try JSONDecoder.json5().decode( + Gemma4AssistantConfiguration.self, from: data) + #expect(config.backboneHiddenSize == 2560) + #expect(config.useOrderedEmbeddings == true) + #expect(config.numCentroids == 2048) + #expect(config.centroidIntermediateTopK == 32) + #expect(config.textConfig.tieWordEmbeddings == true) + #expect(config.textConfig.numHiddenLayers == 4) + #expect(config.textConfig.numKvSharedLayers == 4) + #expect(config.textConfig.attentionKeqV == false) + } + + @Test func decodes26BA4BDrafterConfig() throws { + let data = try loadFixture(named: "gemma4-26B-A4B-assistant-config") + let config = try JSONDecoder.json5().decode( + Gemma4AssistantConfiguration.self, from: data) + #expect(config.backboneHiddenSize == 2816) + #expect(config.useOrderedEmbeddings == false) + #expect(config.numCentroids == 2048) + #expect(config.textConfig.tieWordEmbeddings == true) + #expect(config.textConfig.numHiddenLayers == 4) + #expect(config.textConfig.numKvSharedLayers == 4) + #expect(config.textConfig.attentionKeqV == true) + #expect(config.textConfig.numGlobalKeyValueHeads == 2) + } + + @Test func clampsNumKvSharedLayersWhenMissing() throws { + // Synthetic config: text_config omits num_kv_shared_layers; the + // post-init should set it to num_hidden_layers = 4. + let json = """ + { + "model_type": "gemma4_assistant", + "backbone_hidden_size": 256, + "use_ordered_embeddings": true, + "num_centroids": 16, + "centroid_intermediate_top_k": 4, + "text_config": { + "model_type": "gemma4_text", + "hidden_size": 256, + "num_hidden_layers": 4, + "intermediate_size": 512, + "num_attention_heads": 2, + "head_dim": 32, + "global_head_dim": 32, + "num_key_value_heads": 1, + "sliding_window": 64, + "tie_word_embeddings": true, + "vocab_size": 1024, + "vocab_size_per_layer_input": 1024, + "rms_norm_eps": 1e-6 + } + } + """ + let data = Data(json.utf8) + let config = try JSONDecoder.json5().decode( + Gemma4AssistantConfiguration.self, from: data) + #expect(config.textConfig.numKvSharedLayers == 4) + } + + @Test func clampsNumKvSharedLayersWhenZero() throws { + let json = """ + { + "model_type": "gemma4_assistant", + "backbone_hidden_size": 256, + "use_ordered_embeddings": false, + "num_centroids": 16, + "centroid_intermediate_top_k": 4, + "text_config": { + "model_type": "gemma4_text", + "hidden_size": 256, + "num_hidden_layers": 4, + "intermediate_size": 512, + "num_attention_heads": 2, + "head_dim": 32, + "global_head_dim": 32, + "num_key_value_heads": 1, + "num_kv_shared_layers": 0, + "sliding_window": 64, + "tie_word_embeddings": true, + "vocab_size": 1024, + "vocab_size_per_layer_input": 1024, + "rms_norm_eps": 1e-6 + } + } + """ + let data = Data(json.utf8) + let config = try JSONDecoder.json5().decode( + Gemma4AssistantConfiguration.self, from: data) + #expect(config.textConfig.numKvSharedLayers == 4) + } +} diff --git a/Tests/MLXLMTests/Gemma4AssistantDraftModelTests.swift b/Tests/MLXLMTests/Gemma4AssistantDraftModelTests.swift new file mode 100644 index 0000000000..433d60001a --- /dev/null +++ b/Tests/MLXLMTests/Gemma4AssistantDraftModelTests.swift @@ -0,0 +1,441 @@ +// Copyright © 2026 Apple Inc. + +import Foundation +import MLX +import MLXLMCommon +import MLXLLM +import Testing + +@Suite("Gemma4AssistantDraftModel skeleton") +struct Gemma4AssistantDraftModelTests { + + /// Build a minimal drafter config (4 layers, all kv-shared, tied embeds, + /// no centroid head). + private func drafterConfig( + backbone: Int = 64, + vocab: Int = 64, + useOrderedEmbeddings: Bool = false, + attentionKeqV: Bool = false, + numGlobalKVHeads: Int? = nil + ) throws -> Gemma4AssistantConfiguration { + let kvHeadsField = numGlobalKVHeads.map { "\"num_global_key_value_heads\": \($0)," } ?? "" + let json = """ + { + "model_type": "gemma4_assistant", + "backbone_hidden_size": \(backbone), + "use_ordered_embeddings": \(useOrderedEmbeddings), + "num_centroids": 8, + "centroid_intermediate_top_k": 2, + "text_config": { + "model_type": "gemma4_text", + "hidden_size": 64, + "num_hidden_layers": 4, + "intermediate_size": 128, + "num_attention_heads": 2, + "head_dim": 32, + "global_head_dim": 32, + "num_key_value_heads": 1, + "num_kv_shared_layers": 4, + \(kvHeadsField) + "sliding_window": 64, + "attention_k_eq_v": \(attentionKeqV), + "final_logit_softcapping": null, + "tie_word_embeddings": true, + "vocab_size": \(vocab), + "vocab_size_per_layer_input": \(vocab), + "rms_norm_eps": 1e-6, + "hidden_size_per_layer_input": 0, + "use_double_wide_mlp": false, + "layer_types": ["sliding_attention", "sliding_attention", + "sliding_attention", "full_attention"] + } + } + """ + let data = Data(json.utf8) + return try JSONDecoder.json5().decode( + Gemma4AssistantConfiguration.self, from: data) + } + + /// Build a matching small target config (same hidden_size = backbone, + /// same vocab). + private func targetConfig( + hiddenSize: Int = 64, + vocab: Int = 64, + attentionKeqV: Bool = false, + numGlobalKVHeads: Int? = nil + ) throws -> Gemma4TextConfiguration { + let kvHeadsField = numGlobalKVHeads.map { "\"num_global_key_value_heads\": \($0)," } ?? "" + let json = """ + { + "model_type": "gemma4_text", + "hidden_size": \(hiddenSize), + "num_hidden_layers": 10, + "intermediate_size": 128, + "num_attention_heads": 2, + "head_dim": 32, + "global_head_dim": 32, + "num_key_value_heads": 1, + \(kvHeadsField) + "num_kv_shared_layers": 5, + "sliding_window": 64, + "sliding_window_pattern": 5, + "attention_k_eq_v": \(attentionKeqV), + "final_logit_softcapping": 30.0, + "tie_word_embeddings": true, + "vocab_size": \(vocab), + "vocab_size_per_layer_input": \(vocab), + "rms_norm_eps": 1e-6, + "hidden_size_per_layer_input": 0 + } + """ + let data = Data(json.utf8) + return try JSONDecoder.json5().decode( + Gemma4TextConfiguration.self, from: data) + } + + @Test func drafterInitializes() throws { + let cfg = try drafterConfig() + let drafter = Gemma4AssistantDraftModel(config: cfg) + eval(drafter) + #expect(drafter.config.backboneHiddenSize == 64) + #expect(drafter.maskedEmbedder == nil) // useOrderedEmbeddings: false + } + + @Test func drafterWithCentroidHead() throws { + let cfg = try drafterConfig(useOrderedEmbeddings: true) + let drafter = Gemma4AssistantDraftModel(config: cfg) + eval(drafter) + #expect(drafter.maskedEmbedder != nil) + } + + @Test func bindSucceedsOnMatchedTarget() throws { + let cfg = try drafterConfig() + let drafter = Gemma4AssistantDraftModel(config: cfg) + let tCfg = try targetConfig() + let target = Gemma4TextModel(tCfg) + eval(drafter, target) + try drafter.bind(target: target) + } + + @Test func bindIsIdempotentOnSameTarget() throws { + let cfg = try drafterConfig() + let drafter = Gemma4AssistantDraftModel(config: cfg) + let target = Gemma4TextModel(try targetConfig()) + eval(drafter, target) + try drafter.bind(target: target) + try drafter.bind(target: target) // second call is a no-op + } + + @Test func rebindToDifferentTargetThrows() throws { + let cfg = try drafterConfig() + let drafter = Gemma4AssistantDraftModel(config: cfg) + let t1 = Gemma4TextModel(try targetConfig()) + let t2 = Gemma4TextModel(try targetConfig()) + eval(drafter, t1, t2) + try drafter.bind(target: t1) + #expect(throws: Gemma4MTPError.rebindForbidden) { + try drafter.bind(target: t2) + } + } + + @Test func hiddenSizeMismatchThrows() throws { + // Drafter backbone = 64, target hidden = 128 → mismatch. + let cfg = try drafterConfig(backbone: 64) + let drafter = Gemma4AssistantDraftModel(config: cfg) + let target = Gemma4TextModel(try targetConfig(hiddenSize: 128)) + eval(drafter, target) + #expect(throws: (any Error).self) { + try drafter.bind(target: target) + } + } + + @Test func vocabMismatchThrows() throws { + let cfg = try drafterConfig(vocab: 64) + let drafter = Gemma4AssistantDraftModel(config: cfg) + let target = Gemma4TextModel(try targetConfig(vocab: 128)) + eval(drafter, target) + #expect(throws: (any Error).self) { + try drafter.bind(target: target) + } + } + + @Test func kEqVCompatCheckPasses() throws { + // Both drafter and target have attention_k_eq_v = true + matching + // num_global_key_value_heads. + let cfg = try drafterConfig( + attentionKeqV: true, numGlobalKVHeads: 2) + let drafter = Gemma4AssistantDraftModel(config: cfg) + let target = Gemma4TextModel(try targetConfig( + attentionKeqV: true, numGlobalKVHeads: 2)) + eval(drafter, target) + try drafter.bind(target: target) + } + + @Test func kEqVMismatchThrows() throws { + // Drafter has k_eq_v=true, target has k_eq_v=false → throw. + let cfg = try drafterConfig( + attentionKeqV: true, numGlobalKVHeads: 2) + let drafter = Gemma4AssistantDraftModel(config: cfg) + let target = Gemma4TextModel(try targetConfig( + attentionKeqV: false)) + eval(drafter, target) + #expect(throws: (any Error).self) { + try drafter.bind(target: target) + } + } +} + +@Suite("Gemma4AssistantDraftModel forward") +struct Gemma4AssistantDraftModelForwardTests { + + private func drafterConfig( + useOrderedEmbeddings: Bool = false + ) throws -> Gemma4AssistantConfiguration { + let json = """ + { + "model_type": "gemma4_assistant", + "backbone_hidden_size": 64, + "use_ordered_embeddings": \(useOrderedEmbeddings), + "num_centroids": 8, + "centroid_intermediate_top_k": 2, + "text_config": { + "model_type": "gemma4_text", + "hidden_size": 64, + "num_hidden_layers": 4, + "intermediate_size": 128, + "num_attention_heads": 2, + "head_dim": 32, + "global_head_dim": 32, + "num_key_value_heads": 1, + "num_kv_shared_layers": 4, + "sliding_window": 64, + "final_logit_softcapping": null, + "tie_word_embeddings": true, + "vocab_size": 64, + "vocab_size_per_layer_input": 64, + "rms_norm_eps": 1e-6, + "hidden_size_per_layer_input": 0, + "use_double_wide_mlp": false, + "layer_types": ["sliding_attention", "sliding_attention", + "sliding_attention", "full_attention"] + } + } + """ + let data = Data(json.utf8) + return try JSONDecoder.json5().decode( + Gemma4AssistantConfiguration.self, from: data) + } + + /// Build dummy shared-KV (K/V for each layer-type). Shapes: + /// fullAttention: [B, num_key_value_heads, T, global_head_dim] + /// slidingAttention: [B, num_key_value_heads, T, head_dim] + /// Here: B=1, kvHeads=1, T=8, both head_dim = 32. + private func makeSharedKV(kvLen: Int = 8) -> Gemma4SharedKV { + let B = 1, H = 1, D = 32 + func kv() -> (MLXArray, MLXArray) { + let k = MLXArray.ones([B, H, kvLen, D], dtype: .float32) * 0.1 + let v = MLXArray.ones([B, H, kvLen, D], dtype: .float32) * 0.2 + return (k, v) + } + return Gemma4SharedKV(fullAttention: kv(), slidingAttention: kv()) + } + + @Test func forwardProducesExpectedShapes() throws { + let cfg = try drafterConfig() + let drafter = Gemma4AssistantDraftModel(config: cfg) + eval(drafter) + let inputsEmbeds = MLXArray.zeros([1, 1, 2 * 64], dtype: .float32) + let sharedKV = makeSharedKV() + let (lastHidden, logits) = drafter( + inputsEmbeds: inputsEmbeds, + sharedKV: sharedKV, + positionOffset: .scalar(8) + ) + #expect(lastHidden.shape == [1, 1, 64]) // [B, 1, backbone] + #expect(logits.shape == [1, 1, 64]) // [B, 1, vocab] + } + + @Test func forwardWithCentroidHeadHasCorrectShapes() throws { + let cfg = try drafterConfig(useOrderedEmbeddings: true) + let drafter = Gemma4AssistantDraftModel(config: cfg) + eval(drafter) + let inputsEmbeds = MLXArray.zeros([1, 1, 2 * 64], dtype: .float32) + let sharedKV = makeSharedKV() + let (lastHidden, logits) = drafter( + inputsEmbeds: inputsEmbeds, + sharedKV: sharedKV, + positionOffset: .scalar(8) + ) + #expect(lastHidden.shape == [1, 1, 64]) + #expect(logits.shape == [1, 1, 64]) + } + + @Test func forwardLogitsAreFinite() throws { + let cfg = try drafterConfig() + let drafter = Gemma4AssistantDraftModel(config: cfg) + eval(drafter) + let inputsEmbeds = MLXArray.zeros([1, 1, 2 * 64], dtype: .float32) + let sharedKV = makeSharedKV() + let (_, logits) = drafter( + inputsEmbeds: inputsEmbeds, + sharedKV: sharedKV, + positionOffset: .scalar(8) + ) + // Softcap NOT applied on drafter path, so logits can exceed ±30. + // This test just verifies they're not NaN / ±inf on zero input. + let absMax = MLX.abs(logits).max().item(Float.self) + #expect(absMax.isFinite) + } +} + +@Suite("Gemma4AssistantDraftModel sanitize") +struct Gemma4AssistantDraftModelSanitizeTests { + + private func drafterConfig( + tieWordEmbeddings: Bool = true + ) throws -> Gemma4AssistantConfiguration { + let json = """ + { + "model_type": "gemma4_assistant", + "backbone_hidden_size": 64, + "use_ordered_embeddings": true, + "num_centroids": 8, + "centroid_intermediate_top_k": 2, + "text_config": { + "model_type": "gemma4_text", + "hidden_size": 64, + "num_hidden_layers": 4, + "intermediate_size": 128, + "num_attention_heads": 2, + "head_dim": 32, + "global_head_dim": 32, + "num_key_value_heads": 1, + "num_kv_shared_layers": 4, + "sliding_window": 64, + "tie_word_embeddings": \(tieWordEmbeddings), + "vocab_size": 64, + "vocab_size_per_layer_input": 64, + "rms_norm_eps": 1e-6, + "hidden_size_per_layer_input": 0, + "use_double_wide_mlp": false, + "layer_types": ["sliding_attention", "sliding_attention", + "sliding_attention", "full_attention"] + } + } + """ + let data = Data(json.utf8) + return try JSONDecoder.json5().decode( + Gemma4AssistantConfiguration.self, from: data) + } + + @Test func castsTokenOrderingToInt32() throws { + let cfg = try drafterConfig() + let drafter = Gemma4AssistantDraftModel(config: cfg) + let int64Ordering = MLXArray([Int64(0), 1, 2, 3, 4, 5, 6, 7, + 8, 9, 10, 11, 12, 13, 14, 15, + 16, 17, 18, 19, 20, 21, 22, 23, + 24, 25, 26, 27, 28, 29, 30, 31, + 32, 33, 34, 35, 36, 37, 38, 39, + 40, 41, 42, 43, 44, 45, 46, 47, + 48, 49, 50, 51, 52, 53, 54, 55, + 56, 57, 58, 59, 60, 61, 62, 63]) + var weights: [String: MLXArray] = [ + "masked_embedding.token_ordering": int64Ordering, + ] + weights = try drafter.sanitize(weights: weights) + let cast = weights["masked_embedding.token_ordering"] + #expect(cast != nil) + #expect(cast!.dtype == .int32) + } + + @Test func dropsLmHeadWhenTied() throws { + let cfg = try drafterConfig(tieWordEmbeddings: true) + let drafter = Gemma4AssistantDraftModel(config: cfg) + let lmHead = MLXArray.zeros([64, 64], dtype: .float32) + let preProj = MLXArray.zeros([64, 128], dtype: .float32) + var weights: [String: MLXArray] = [ + "lm_head.weight": lmHead, + "pre_projection.weight": preProj, + ] + weights = try drafter.sanitize(weights: weights) + #expect(weights["lm_head.weight"] == nil) // dropped + #expect(weights["pre_projection.weight"] != nil) // kept + } + + @Test func keepsLmHeadWhenUntied() throws { + let cfg = try drafterConfig(tieWordEmbeddings: false) + let drafter = Gemma4AssistantDraftModel(config: cfg) + let lmHead = MLXArray.zeros([64, 64], dtype: .float32) + var weights: [String: MLXArray] = [ + "lm_head.weight": lmHead, + ] + weights = try drafter.sanitize(weights: weights) + #expect(weights["lm_head.weight"] != nil) + } + + @Test func failsLoudOnUnexpectedKProj() throws { + let cfg = try drafterConfig() + let drafter = Gemma4AssistantDraftModel(config: cfg) + let kProj = MLXArray.zeros([64, 64], dtype: .float32) + let weights: [String: MLXArray] = [ + "model.layers.0.self_attn.k_proj.weight": kProj, + ] + #expect(throws: (any Error).self) { + _ = try drafter.sanitize(weights: weights) + } + } + + @Test func failsLoudOnUnexpectedVProj() throws { + let cfg = try drafterConfig() + let drafter = Gemma4AssistantDraftModel(config: cfg) + let vProj = MLXArray.zeros([64, 64], dtype: .float32) + let weights: [String: MLXArray] = [ + "model.layers.2.self_attn.v_proj.weight": vProj, + ] + #expect(throws: (any Error).self) { + _ = try drafter.sanitize(weights: weights) + } + } + + @Test func preservesOtherWeights() throws { + let cfg = try drafterConfig() + let drafter = Gemma4AssistantDraftModel(config: cfg) + let qProj = MLXArray.zeros([64, 64], dtype: .float32) + let preProj = MLXArray.zeros([64, 128], dtype: .float32) + let postProj = MLXArray.zeros([64, 64], dtype: .float32) + let embed = MLXArray.zeros([64, 64], dtype: .float32) + let weights: [String: MLXArray] = [ + "model.layers.0.self_attn.q_proj.weight": qProj, + "pre_projection.weight": preProj, + "post_projection.weight": postProj, + "model.embed_tokens.weight": embed, + ] + let out = try drafter.sanitize(weights: weights) + #expect(out.count == 4) // all four kept + } +} + +@Suite("Gemma4AssistantDraftModel loading") +struct Gemma4AssistantDraftModelLoadingTests { + + /// Integration test gated on env var. Loads a pre-downloaded drafter + /// directory from disk using the local-path variant of `load`. + @Test(.enabled(if: ProcessInfo.processInfo.environment[ + "MLX_SWIFT_LM_INTEGRATION_DATA_DIR"] != nil)) + func loadsFromDirectory() async throws { + guard let dirPath = ProcessInfo.processInfo.environment[ + "MLX_SWIFT_LM_INTEGRATION_DATA_DIR"] else { return } + // Expect a sub-directory e.g. "gemma-4-E4B-it-assistant-bf16" under + // the integration data dir; caller is responsible for pre-downloading. + let drafterDir = URL(fileURLWithPath: dirPath) + .appending(path: "gemma-4-E4B-it-assistant-bf16") + let drafter = try await Gemma4AssistantDraftModel.load(from: drafterDir) + // A basic shape check: the first layer's q_proj weight should exist. + // We don't assert exact values here; the parity tests do that. + let params = drafter.parameters() + // Flatten to check a known key exists. + let flat = params.flattened() + let keys = Set(flat.map(\.0)) + #expect(keys.contains("model.layers.0.self_attn.q_proj.weight")) + } +} diff --git a/Tests/MLXLMTests/Gemma4CaptureHookTests.swift b/Tests/MLXLMTests/Gemma4CaptureHookTests.swift new file mode 100644 index 0000000000..e957e8f3c5 --- /dev/null +++ b/Tests/MLXLMTests/Gemma4CaptureHookTests.swift @@ -0,0 +1,75 @@ +// Copyright © 2026 Apple Inc. + +import Foundation +import MLX +@testable import MLXLLM +import MLXLMCommon +import Testing + +@Suite("Gemma4TextModelInner shared-KV capture hook") +struct Gemma4CaptureHookTests { + + private func smallTargetConfig() throws -> Gemma4TextConfiguration { + // 10-layer config with the last 5 kv-shared. First 5 are pattern + // [sliding, sliding, sliding, sliding, full] — matching the real + // model's slidingWindowPattern = 5. After derivation, layer_types + // should be [sliding, sliding, sliding, sliding, full, + // sliding, sliding, sliding, sliding, full]. + // Last non-shared full-attn = layer 4; last non-shared sliding = 3. + let json = """ + { + "model_type": "gemma4_text", + "hidden_size": 64, + "num_hidden_layers": 10, + "intermediate_size": 128, + "num_attention_heads": 2, + "head_dim": 32, + "global_head_dim": 32, + "num_key_value_heads": 1, + "num_kv_shared_layers": 5, + "sliding_window": 16, + "sliding_window_pattern": 5, + "final_logit_softcapping": 30.0, + "tie_word_embeddings": true, + "vocab_size": 32, + "vocab_size_per_layer_input": 32, + "rms_norm_eps": 1e-6, + "hidden_size_per_layer_input": 0 + } + """ + let data = Data(json.utf8) + return try JSONDecoder.json5().decode(Gemma4TextConfiguration.self, from: data) + } + + @Test func innerCaptureDirectlyPopulatesBothSlots() throws { + let config = try smallTargetConfig() + let model = Gemma4TextModel(config) + eval(model) + let tokens = MLXArray([Int32(1), 2, 3, 4])[.newAxis, .ellipsis] + let cache = model.newCache(parameters: nil) + let capture = Gemma4SharedKVCapture() + _ = model._testCallInner(tokens, cache: cache) { idx, kv in + if idx == 4 { + capture.fullAttention = kv + } else if idx == 3 { + capture.slidingAttention = kv + } + } + #expect(capture.fullAttention != nil) + #expect(capture.slidingAttention != nil) + // Expected shapes for this config: nKVHeads = 1, head_dim = 32, + // global_head_dim = 32, T = 4. + #expect(capture.fullAttention?.0.dim(2) == 4) + #expect(capture.slidingAttention?.0.dim(2) == 4) + } + + @Test func defaultCaptureIsNil() throws { + // Regression: confirm existing callers unaffected when no capture is passed. + let config = try smallTargetConfig() + let model = Gemma4TextModel(config) + eval(model) + let tokens = MLXArray([Int32(1), 2, 3])[.newAxis, .ellipsis] + let out = model(tokens, cache: model.newCache(parameters: nil)) + #expect(out.dim(-1) == model.vocabularySize) + } +} diff --git a/Tests/MLXLMTests/Gemma4ForceSharedKVTests.swift b/Tests/MLXLMTests/Gemma4ForceSharedKVTests.swift new file mode 100644 index 0000000000..a00c0e4fa1 --- /dev/null +++ b/Tests/MLXLMTests/Gemma4ForceSharedKVTests.swift @@ -0,0 +1,95 @@ +// Copyright © 2026 Apple Inc. + +import Foundation +import MLX +import MLXLLM +import MLXLMCommon +import Testing + +@Suite("Gemma4 shared-KV layer selection") +struct Gemma4ForceSharedKVTests { + + /// Build a 4-layer Gemma4TextConfiguration with every layer shared — + /// the drafter shape. + private func drafterLikeConfig() throws -> Gemma4TextConfiguration { + let json = """ + { + "model_type": "gemma4_text", + "hidden_size": 256, + "num_hidden_layers": 4, + "intermediate_size": 2048, + "num_attention_heads": 4, + "head_dim": 256, + "global_head_dim": 512, + "num_key_value_heads": 2, + "num_kv_shared_layers": 4, + "layer_types": ["sliding_attention", "sliding_attention", + "sliding_attention", "full_attention"], + "sliding_window": 512, + "final_logit_softcapping": null, + "hidden_size_per_layer_input": 0, + "use_double_wide_mlp": false, + "tie_word_embeddings": true, + "vocab_size": 1024, + "vocab_size_per_layer_input": 1024, + "rms_norm_eps": 1e-6 + } + """ + let data = Data(json.utf8) + return try JSONDecoder.json5().decode(Gemma4TextConfiguration.self, from: data) + } + + /// Build a 35-layer Gemma4TextConfiguration with the last 20 shared — + /// the 4B target shape. + private func targetLikeConfig() throws -> Gemma4TextConfiguration { + let json = """ + { + "model_type": "gemma4_text", + "hidden_size": 1536, + "num_hidden_layers": 35, + "intermediate_size": 6144, + "num_attention_heads": 8, + "head_dim": 256, + "global_head_dim": 512, + "num_key_value_heads": 1, + "num_kv_shared_layers": 20, + "sliding_window": 512, + "sliding_window_pattern": 5, + "final_logit_softcapping": 30.0, + "tie_word_embeddings": true, + "vocab_size": 1024, + "vocab_size_per_layer_input": 1024, + "rms_norm_eps": 1e-6 + } + """ + let data = Data(json.utf8) + return try JSONDecoder.json5().decode(Gemma4TextConfiguration.self, from: data) + } + + @Test func drafterConfigMarksAllLayersShared() throws { + let config = try drafterLikeConfig() + // For a drafter: numKvSharedLayers == numHiddenLayers, firstShared == 0. + // Every layer must be marked usesSharedKV == true. + for i in 0 ..< config.numHiddenLayers { + #expect(config.layerUsesSharedKV(layerIdx: i)) + } + } + + @Test func targetConfigKeepsExistingSplit() throws { + let config = try targetLikeConfig() + // First 15 layers: not shared. + for i in 0 ..< 15 { + #expect(!config.layerUsesSharedKV(layerIdx: i)) + } + // Last 20 layers: shared. + for i in 15 ..< 35 { + #expect(config.layerUsesSharedKV(layerIdx: i)) + } + } + + @Test func forceSharedKVOverridesIndex() throws { + let config = try targetLikeConfig() + // Even layer 0 should be treated as shared when forceSharedKV is true. + #expect(config.layerUsesSharedKV(layerIdx: 0, forceSharedKV: true)) + } +} diff --git a/Tests/MLXLMTests/Gemma4ForwardForMTPTests.swift b/Tests/MLXLMTests/Gemma4ForwardForMTPTests.swift new file mode 100644 index 0000000000..1e5b43fcf2 --- /dev/null +++ b/Tests/MLXLMTests/Gemma4ForwardForMTPTests.swift @@ -0,0 +1,79 @@ +// Copyright © 2026 Apple Inc. + +import Foundation +import MLX +import MLXLLM +import MLXLMCommon +import Testing + +@Suite("Gemma4TextModel.forwardForMTP") +struct Gemma4ForwardForMTPTests { + + private func smallConfig() throws -> Gemma4TextConfiguration { + let json = """ + { + "model_type": "gemma4_text", + "hidden_size": 64, + "num_hidden_layers": 10, + "intermediate_size": 128, + "num_attention_heads": 2, + "head_dim": 32, + "global_head_dim": 32, + "num_key_value_heads": 1, + "num_kv_shared_layers": 5, + "sliding_window": 16, + "sliding_window_pattern": 5, + "final_logit_softcapping": 30.0, + "tie_word_embeddings": true, + "vocab_size": 32, + "vocab_size_per_layer_input": 32, + "rms_norm_eps": 1e-6, + "hidden_size_per_layer_input": 0 + } + """ + let data = Data(json.utf8) + return try JSONDecoder.json5().decode(Gemma4TextConfiguration.self, from: data) + } + + @Test func shapesMatchExpectations() throws { + let config = try smallConfig() + let model = Gemma4TextModel(config) + eval(model) + let tokens = MLXArray([Int32(1), 2, 3, 4])[.newAxis, .ellipsis] // [1, 4] + let cache = model.newCache(parameters: nil) + let out = model.forwardForMTP(tokens, cache: cache) + #expect(out.logits.shape == [1, 4, 32]) // [B, L, vocab] + #expect(out.lastHidden.shape == [1, 4, 64]) // [B, L, hidden] + // Shared-KV shapes: [B, nKVHeads, T, headDim] + #expect(out.capturedSharedKV.fullAttention.0.dim(2) == 4) + #expect(out.capturedSharedKV.slidingAttention.0.dim(2) == 4) + } + + @Test func logitsRespectSoftcap() throws { + let config = try smallConfig() + let model = Gemma4TextModel(config) + eval(model) + let tokens = MLXArray([Int32(1), 2, 3, 4])[.newAxis, .ellipsis] + let cache = model.newCache(parameters: nil) + let out = model.forwardForMTP(tokens, cache: cache) + // Softcap 30.0 ⇒ abs(logits) < 30.0 everywhere. + let absMax = MLX.abs(out.logits).max().item(Float.self) + #expect(absMax <= 30.0) + } + + @Test func logitsMatchPlainForward() throws { + // forwardForMTP.logits must equal callAsFunction output on the + // same tokens + same fresh cache (byte-equality expected since + // the head is the factored-out applyLMHead helper in both paths). + let config = try smallConfig() + let model = Gemma4TextModel(config) + eval(model) + let tokens = MLXArray([Int32(1), 2, 3])[.newAxis, .ellipsis] + let cache = model.newCache(parameters: nil) + let out = model.forwardForMTP(tokens, cache: cache) + let cache2 = model.newCache(parameters: nil) + let reference = model(tokens, cache: cache2) + let close = allClose(out.logits, reference, rtol: 1e-5, atol: 1e-5) + #expect(close.item(Bool.self)) + } +} diff --git a/Tests/MLXLMTests/Gemma4MTPBenchmarkHelpers.swift b/Tests/MLXLMTests/Gemma4MTPBenchmarkHelpers.swift new file mode 100644 index 0000000000..fc849ea0ee --- /dev/null +++ b/Tests/MLXLMTests/Gemma4MTPBenchmarkHelpers.swift @@ -0,0 +1,397 @@ +// Copyright © 2026 Apple Inc. +// +// Benchmark primitives for Gemma 4 Multi-Token Prediction (MTP) +// speculative decoding. Provides four measurement helpers: +// +// - measureBaselineThroughput: B=1 no-drafter target-only greedy +// generation tokens/sec, from prefill-end through generation-end. +// - measureMTPThroughput: B=1 drafter-driven MTP generation tokens/sec +// + per-round accept histogram (rounds driven inline so round +// boundaries are visible). +// - measureBatchedBaselineThroughput: B>1 target-only greedy, using +// the same BatchKVCache / BatchRotatingKVCache used by MTP B>1. +// - measureBatchedMTPThroughput: B>1 MTP via runGemma4MTPRoundsBatched. +// +// These are intentionally minimal — no model loading, no CLI, no +// harness. Callers supply a loaded target + bound drafter + prompt(s) +// and receive back a `BenchmarkResult`. A full driver (model download, +// result table, speedup calculation) lives in the test target's +// `realModelThroughputBenchmark`. + +import Foundation +import MLX +@testable import MLXLLM +import MLXLMCommon + +/// Batched benchmark result: per-row token counts + shared timing. +public struct Gemma4MTPBatchedBenchmarkResult: Sendable { + public let batchSize: Int + /// Total tokens emitted across all rows (sum). + public let totalGenerated: Int + public let prefillSeconds: Double + public let generationSeconds: Double + /// Sum of per-row tokens / generationSeconds. This is the metric that + /// matters — it's the aggregate throughput of the system, which is + /// what MTP batching is supposed to improve vs single-stream baseline. + public var tokensPerSecond: Double { + guard generationSeconds > 0 else { return 0 } + return Double(totalGenerated) / generationSeconds + } + + public init( + batchSize: Int, totalGenerated: Int, + prefillSeconds: Double, generationSeconds: Double + ) { + self.batchSize = batchSize + self.totalGenerated = totalGenerated + self.prefillSeconds = prefillSeconds + self.generationSeconds = generationSeconds + } +} + +/// One benchmark measurement. Wall-clock times are post-prefill; prefill +/// is measured separately so MTP speedup is computed against the generation +/// phase only (MTP doesn't change prefill). +public struct Gemma4MTPBenchmarkResult: Sendable { + /// Number of tokens generated (excludes the prompt). + public let generatedTokens: Int + /// Seconds from prefill start to prefill end. + public let prefillSeconds: Double + /// Seconds from prefill end to last emitted token. + public let generationSeconds: Double + /// Generated tokens / generationSeconds. + public var tokensPerSecond: Double { + guard generationSeconds > 0 else { return 0 } + return Double(generatedTokens) / generationSeconds + } + /// Per-round count of accepted drafter tokens. `nil` for the no-drafter + /// baseline; populated with one entry per MTP round otherwise. + public let acceptLengths: [Int]? + + public init( + generatedTokens: Int, + prefillSeconds: Double, + generationSeconds: Double, + acceptLengths: [Int]? + ) { + self.generatedTokens = generatedTokens + self.prefillSeconds = prefillSeconds + self.generationSeconds = generationSeconds + self.acceptLengths = acceptLengths + } +} + +/// Run target-only greedy generation over `promptTokens` for `maxTokens` +/// steps. Returns timing + token count. This is the denominator for the +/// MTP speedup calculation — matches the semantics of the parity-test +/// `runBaselineGreedy` helper. +public func measureBaselineThroughput( + target: Gemma4TextModel, + promptTokens: MLXArray, + maxTokens: Int +) -> Gemma4MTPBenchmarkResult { + var prompt = promptTokens + if prompt.ndim == 1 { + prompt = prompt[.newAxis, .ellipsis] + } + let cache = target.newCache(parameters: nil) + + let prefillStart = Date() + var logits = target(prompt, cache: cache) + var tok = logits[0..., -1, 0...].asType(.float32).argMax(axis: -1) + eval(tok) + let prefillElapsed = Date().timeIntervalSince(prefillStart) + + let genStart = Date() + var generated = 1 + for _ in 1 ..< maxTokens { + let input = tok[.newAxis, .ellipsis] + logits = target(input, cache: cache) + tok = logits[0..., -1, 0...].asType(.float32).argMax(axis: -1) + eval(tok) + generated += 1 + } + let genElapsed = Date().timeIntervalSince(genStart) + + return Gemma4MTPBenchmarkResult( + generatedTokens: generated, + prefillSeconds: prefillElapsed, + generationSeconds: genElapsed, + acceptLengths: nil + ) +} + +/// Run MTP greedy generation over `promptTokens` for `maxTokens` steps +/// via `runGemma4MTPRounds`. Returns timing + token count + per-round +/// accept histogram. +/// +/// The drafter must already be bound to the target (or will be bound on +/// first call — `bind(target:)` is idempotent when the binding matches). +public func measureMTPThroughput( + target: Gemma4TextModel, + drafter: Gemma4AssistantDraftModel, + promptTokens: MLXArray, + maxTokens: Int, + blockSize: Int +) throws -> Gemma4MTPBenchmarkResult { + guard blockSize >= 2 && blockSize <= 16 else { + throw Gemma4MTPError.invalidBlockSize(blockSize) + } + try drafter.bind(target: target) + + var prompt = promptTokens + if prompt.ndim == 1 { + prompt = prompt[.newAxis, .ellipsis] + } + let cache = target.newCache(parameters: nil) + + let prefillStart = Date() + let prefillOut = target.forwardForMTP(prompt, cache: cache) + let firstBonusArr = prefillOut.logits[0..., -1, 0...].asType(.float32).argMax(axis: -1) + eval(firstBonusArr) + var bonus = Int(firstBonusArr.item(Int32.self)) + var hidden = prefillOut.lastHidden[ + 0..., -1 ..< prefillOut.lastHidden.dim(1), 0...] + var sharedKV = prefillOut.capturedSharedKV + let prefillElapsed = Date().timeIntervalSince(prefillStart) + + // Drive the round loop inline so we can track per-round accept counts + // (the AsyncStream public API doesn't delimit rounds). + let genStart = Date() + var emitted = 1 // the prefill bonus counts as the first emitted token + var accepts: [Int] = [] + + while emitted < maxTokens { + let remaining = maxTokens - emitted + let bs = min(blockSize, remaining + 1) + if bs <= 1 { break } + let round = runGemma4MTPGreedyRound( + target: target, + drafter: drafter, + cache: cache, + bonus: bonus, + hidden: hidden, + sharedKV: sharedKV, + blockSize: bs) + accepts.append(round.accepted) + + let emittedThisRound = min(round.tokens.count, remaining) + emitted += emittedThisRound + if emittedThisRound == 0 { break } + + // Update state for next round. + hidden = round.hidden + bonus = round.bonus + sharedKV = round.sharedKV + } + let genElapsed = Date().timeIntervalSince(genStart) + + return Gemma4MTPBenchmarkResult( + generatedTokens: emitted, + prefillSeconds: prefillElapsed, + generationSeconds: genElapsed, + acceptLengths: accepts + ) +} + +// MARK: - Batched (B>1) throughput + +/// Run target-only greedy generation over B padded prompts, each for +/// `maxTokens` steps. Uses `BatchKVCache` / `BatchRotatingKVCache` so the +/// cache semantics match the MTP batched path. +public func measureBatchedBaselineThroughput( + target: Gemma4TextModel, + promptTokens: [[Int32]], + maxTokens: Int +) -> Gemma4MTPBatchedBenchmarkResult { + let B = promptTokens.count + precondition(B >= 1, "Batch size must be >= 1") + let maxLen = promptTokens.map(\.count).max() ?? 0 + // Right-pad with 0s (token id 0). For a throughput bench this is fine; + // we're measuring compute, not semantic output. Real applications + // would left-pad and track leftPadding per row. + let padded = promptTokens.map { row -> [Int32] in + row + Array(repeating: Int32(0), count: maxLen - row.count) + } + let flat = padded.flatMap { $0 } + let prompt = MLXArray(flat, [B, maxLen]) + + let firstKvShared = target.configuration.numHiddenLayers + - target.configuration.numKvSharedLayers + let leftPadding = Array(repeating: 0, count: B) + var cache: [KVCache] = [] + for i in 0 ..< firstKvShared { + if target.configuration.layerTypes[i] == "full_attention" { + cache.append(BatchKVCache(leftPadding: leftPadding)) + } else { + cache.append(BatchRotatingKVCache( + maxSize: target.configuration.slidingWindow, + leftPadding: leftPadding)) + } + } + + let prefillStart = Date() + var logits = target(prompt, cache: cache) + var tok = logits[0..., -1, 0...].asType(.float32).argMax(axis: -1) // [B] + eval(tok) + let prefillElapsed = Date().timeIntervalSince(prefillStart) + + let genStart = Date() + var total = B + for _ in 1 ..< maxTokens { + let input = tok.reshaped([B, 1]) + logits = target(input, cache: cache) + tok = logits[0..., -1, 0...].asType(.float32).argMax(axis: -1) + eval(tok) + total += B + } + let genElapsed = Date().timeIntervalSince(genStart) + + return Gemma4MTPBatchedBenchmarkResult( + batchSize: B, totalGenerated: total, + prefillSeconds: prefillElapsed, generationSeconds: genElapsed) +} + +/// Run MTP over B padded prompts via `runGemma4MTPRoundsBatched` with +/// per-row `maxTokens` budgets. Returns aggregate timing — sum of +/// emitted tokens / wall seconds. This is the variant that exercises +/// continuous-batching compaction: rows with smaller budgets finish +/// early, get removed from the active batch, and the remaining rows +/// run at a smaller B until they finish. +public func measureBatchedMTPThroughputStaggered( + target: Gemma4TextModel, + drafter: Gemma4AssistantDraftModel, + promptTokens: [[Int32]], + maxTokensPerRow: [Int], + blockSize: Int +) async throws -> Gemma4MTPBatchedBenchmarkResult { + guard blockSize >= 2 && blockSize <= 16 else { + throw Gemma4MTPError.invalidBlockSize(blockSize) + } + try drafter.bind(target: target) + + let B = promptTokens.count + precondition(maxTokensPerRow.count == B, + "maxTokensPerRow must match the number of prompts") + let maxLen = promptTokens.map(\.count).max() ?? 0 + let padded = promptTokens.map { row -> [Int32] in + row + Array(repeating: Int32(0), count: maxLen - row.count) + } + let flat = padded.flatMap { $0 } + let prompt = MLXArray(flat, [B, maxLen]) + + let firstKvShared = target.configuration.numHiddenLayers + - target.configuration.numKvSharedLayers + let leftPadding = Array(repeating: 0, count: B) + var cache: [KVCache] = [] + for i in 0 ..< firstKvShared { + if target.configuration.layerTypes[i] == "full_attention" { + cache.append(BatchKVCache(leftPadding: leftPadding)) + } else { + cache.append(BatchRotatingKVCache( + maxSize: target.configuration.slidingWindow, + leftPadding: leftPadding)) + } + } + + let prefillStart = Date() + let prefillOut = target.forwardForMTP(prompt, cache: cache) + let firstBonusArr = prefillOut.logits[0..., -1, 0...].asType(.float32).argMax(axis: -1) + eval(firstBonusArr) + let bonusPerRow = firstBonusArr.asArray(Int32.self).map { Int($0) } + let firstHidden = prefillOut.lastHidden[ + 0..., -1 ..< prefillOut.lastHidden.dim(1), 0...] + let firstSharedKV = prefillOut.capturedSharedKV + let prefillElapsed = Date().timeIntervalSince(prefillStart) + + let genStart = Date() + let stream = try runGemma4MTPRoundsBatched( + target: target, drafter: drafter, + targetCache: cache, + firstBonus: bonusPerRow, firstHidden: firstHidden, + firstSharedKV: firstSharedKV, + maxTokens: maxTokensPerRow.max() ?? 0, + blockSize: blockSize, + eosTokenIds: nil, + maxTokensPerRow: maxTokensPerRow + ) + var total = 0 + for await step in stream { + for slot in step.slots where slot.token != nil { + total += 1 + } + } + let genElapsed = Date().timeIntervalSince(genStart) + + return Gemma4MTPBatchedBenchmarkResult( + batchSize: B, totalGenerated: total, + prefillSeconds: prefillElapsed, generationSeconds: genElapsed) +} + +/// Run MTP over B padded prompts via `runGemma4MTPRoundsBatched`. Returns +/// aggregate timing — sum of emitted tokens / wall seconds. +public func measureBatchedMTPThroughput( + target: Gemma4TextModel, + drafter: Gemma4AssistantDraftModel, + promptTokens: [[Int32]], + maxTokens: Int, + blockSize: Int +) async throws -> Gemma4MTPBatchedBenchmarkResult { + guard blockSize >= 2 && blockSize <= 16 else { + throw Gemma4MTPError.invalidBlockSize(blockSize) + } + try drafter.bind(target: target) + + let B = promptTokens.count + let maxLen = promptTokens.map(\.count).max() ?? 0 + let padded = promptTokens.map { row -> [Int32] in + row + Array(repeating: Int32(0), count: maxLen - row.count) + } + let flat = padded.flatMap { $0 } + let prompt = MLXArray(flat, [B, maxLen]) + + let firstKvShared = target.configuration.numHiddenLayers + - target.configuration.numKvSharedLayers + let leftPadding = Array(repeating: 0, count: B) + var cache: [KVCache] = [] + for i in 0 ..< firstKvShared { + if target.configuration.layerTypes[i] == "full_attention" { + cache.append(BatchKVCache(leftPadding: leftPadding)) + } else { + cache.append(BatchRotatingKVCache( + maxSize: target.configuration.slidingWindow, + leftPadding: leftPadding)) + } + } + + let prefillStart = Date() + let prefillOut = target.forwardForMTP(prompt, cache: cache) + let firstBonusArr = prefillOut.logits[0..., -1, 0...].asType(.float32).argMax(axis: -1) + eval(firstBonusArr) + let bonusPerRow = firstBonusArr.asArray(Int32.self).map { Int($0) } + let firstHidden = prefillOut.lastHidden[ + 0..., -1 ..< prefillOut.lastHidden.dim(1), 0...] + let firstSharedKV = prefillOut.capturedSharedKV + let prefillElapsed = Date().timeIntervalSince(prefillStart) + + let genStart = Date() + let stream = try runGemma4MTPRoundsBatched( + target: target, drafter: drafter, + targetCache: cache, + firstBonus: bonusPerRow, firstHidden: firstHidden, + firstSharedKV: firstSharedKV, + maxTokens: maxTokens, blockSize: blockSize, + eosTokenIds: nil + ) + var total = 0 + for await step in stream { + for slot in step.slots where slot.token != nil { + total += 1 + } + } + let genElapsed = Date().timeIntervalSince(genStart) + + return Gemma4MTPBatchedBenchmarkResult( + batchSize: B, totalGenerated: total, + prefillSeconds: prefillElapsed, generationSeconds: genElapsed) +} diff --git a/Tests/MLXLMTests/Gemma4MTPBenchmarkTests.swift b/Tests/MLXLMTests/Gemma4MTPBenchmarkTests.swift new file mode 100644 index 0000000000..dd55bbf915 --- /dev/null +++ b/Tests/MLXLMTests/Gemma4MTPBenchmarkTests.swift @@ -0,0 +1,416 @@ +// Copyright © 2026 Apple Inc. +// +// Smoke tests for the Gemma 4 MTP benchmark primitives. Verifies the +// measurement harness runs end-to-end, produces finite timings, and +// returns a token count matching `maxTokens`. Actual throughput numbers +// are hardware-dependent and are not asserted; a separate driver +// (outside the test target) collects them against real models. + +import Foundation +import MLX +import MLXLMCommon +import MLXRandom +import MLXLLM +import Testing + +@Suite("Gemma4MTPBenchmark", .serialized) +struct Gemma4MTPBenchmarkTests { + + /// Tiny target for smoke tests — matches the E2B-shaped config used + /// in the parity suite so we know the harness runs cleanly. + private func tinyTargetConfig() throws -> Gemma4TextConfiguration { + let json = """ + { + "model_type": "gemma4_text", + "hidden_size": 256, + "num_hidden_layers": 12, + "intermediate_size": 512, + "num_attention_heads": 4, + "head_dim": 32, + "global_head_dim": 32, + "num_key_value_heads": 1, + "num_kv_shared_layers": 6, + "sliding_window": 128, + "sliding_window_pattern": 5, + "final_logit_softcapping": 30.0, + "tie_word_embeddings": true, + "vocab_size": 1024, + "vocab_size_per_layer_input": 1024, + "rms_norm_eps": 1e-6, + "hidden_size_per_layer_input": 0 + } + """ + return try JSONDecoder.json5().decode( + Gemma4TextConfiguration.self, from: Data(json.utf8)) + } + + private func tinyDrafterConfig() throws -> Gemma4AssistantConfiguration { + let json = """ + { + "model_type": "gemma4_assistant", + "backbone_hidden_size": 256, + "use_ordered_embeddings": false, + "num_centroids": 32, + "centroid_intermediate_top_k": 4, + "tie_word_embeddings": true, + "text_config": { + "model_type": "gemma4_text", + "hidden_size": 64, + "num_hidden_layers": 4, + "intermediate_size": 128, + "num_attention_heads": 2, + "head_dim": 32, + "global_head_dim": 32, + "num_key_value_heads": 1, + "num_kv_shared_layers": 4, + "sliding_window": 64, + "final_logit_softcapping": null, + "tie_word_embeddings": true, + "vocab_size": 1024, + "vocab_size_per_layer_input": 1024, + "rms_norm_eps": 1e-6, + "hidden_size_per_layer_input": 0, + "use_double_wide_mlp": false, + "layer_types": ["sliding_attention", "sliding_attention", + "sliding_attention", "full_attention"] + } + } + """ + return try JSONDecoder.json5().decode( + Gemma4AssistantConfiguration.self, from: Data(json.utf8)) + } + + @Test func baselineHarnessRunsAndProducesFiniteTimings() async throws { + MLXRandom.seed(42) + let target = Gemma4TextModel(try tinyTargetConfig()) + eval(target) + let prompt = MLXArray([Int32](repeating: 7, count: 8)) + + let r = measureBaselineThroughput( + target: target, promptTokens: prompt, maxTokens: 8) + + #expect(r.generatedTokens == 8) + #expect(r.prefillSeconds.isFinite && r.prefillSeconds >= 0) + #expect(r.generationSeconds.isFinite && r.generationSeconds >= 0) + #expect(r.acceptLengths == nil, "baseline has no accept histogram") + } + + @Test func mtpHarnessRunsAndProducesAcceptLengths() async throws { + MLXRandom.seed(42) + let target = Gemma4TextModel(try tinyTargetConfig()) + let drafter = Gemma4AssistantDraftModel(config: try tinyDrafterConfig()) + eval(target, drafter) + let prompt = MLXArray([Int32](repeating: 7, count: 8)) + + let r = try await measureMTPThroughput( + target: target, drafter: drafter, + promptTokens: prompt, maxTokens: 12, blockSize: 3) + + #expect(r.generatedTokens == 12) + #expect(r.prefillSeconds.isFinite && r.prefillSeconds >= 0) + #expect(r.generationSeconds.isFinite && r.generationSeconds >= 0) + } + + // MARK: - Real-model benchmark (opt-in, gated on MTP_BENCH_DATA_DIR) + + /// Real-model benchmark. Measures tokens/sec for baseline vs MTP on + /// locally-resident models. Skipped unless `MTP_BENCH_DATA_DIR` env var + /// points to a directory containing: + /// - gemma-4-e2b-it-bf16/ + /// - gemma-4-E2B-it-assistant-bf16/ + /// (and optionally the e4b / 26b-a4b-4bit pairs). + /// + /// Produces a printed table. No assertions on throughput — numbers are + /// hardware-dependent. Used to populate the README performance section. + @Test func realModelThroughputBenchmark() async throws { + guard let dataDir = ProcessInfo.processInfo.environment["MTP_BENCH_DATA_DIR"] + else { + print("Skipping: MTP_BENCH_DATA_DIR env var not set") + return + } + + struct Pair { + let label: String + let targetDir: String + let drafterDir: String + } + let allPairs: [Pair] = [ + Pair(label: "E2B-4bit", + targetDir: "gemma-4-e2b-it-4bit", + drafterDir: "gemma-4-E2B-it-assistant-bf16"), + Pair(label: "E2B-bf16", + targetDir: "gemma-4-e2b-it-bf16", + drafterDir: "gemma-4-E2B-it-assistant-bf16"), + Pair(label: "E4B-bf16", + targetDir: "gemma-4-e4b-it-bf16", + drafterDir: "gemma-4-E4B-it-assistant-bf16"), + Pair(label: "26B-A4B-4bit", + targetDir: "gemma-4-26b-a4b-it-4bit", + drafterDir: "gemma-4-26B-A4B-it-assistant-bf16"), + ] + let env = ProcessInfo.processInfo.environment + let requestedPair = env["MTP_BENCH_PAIR"]?.lowercased() + let pairs = allPairs.filter { + let matchesRequest = + requestedPair == nil + || $0.label.lowercased() == requestedPair + || $0.targetDir.lowercased() == requestedPair + || $0.drafterDir.lowercased() == requestedPair + return matchesRequest + && FileManager.default.fileExists(atPath: "\(dataDir)/\($0.targetDir)") + && FileManager.default.fileExists(atPath: "\(dataDir)/\($0.drafterDir)") + } + #expect(!pairs.isEmpty, "No requested model pairs found in \(dataDir)") + + func envInt(_ name: String, default defaultValue: Int) -> Int { + guard let value = env[name], let parsed = Int(value), parsed > 0 else { + return defaultValue + } + return parsed + } + + func envIntList(_ name: String, default defaultValue: [Int]) -> [Int] { + guard let value = env[name] else { return defaultValue } + let parsed = value + .split(separator: ",") + .compactMap { Int($0.trimmingCharacters(in: .whitespaces)) } + .filter { $0 > 1 } + return parsed.isEmpty ? defaultValue : parsed + } + + // Load real chat-templated prompt tokens from a JSON fixture + // (produced via Python's transformers tokenizer — path pointed to + // by MTP_BENCH_PROMPTS env var). Using garbage token IDs produces + // misleading "slower than baseline" results because the drafter + // has no signal to predict from. Falls back to a single arbitrary + // prompt if the fixture isn't provided. + let promptsData: [[Int32]] + if let fixturePath = ProcessInfo.processInfo.environment["MTP_BENCH_PROMPTS"] { + let data = try Data(contentsOf: URL(fileURLWithPath: fixturePath)) + let decoded = try JSONDecoder().decode([[Int]].self, from: data) + promptsData = decoded.map { $0.map { Int32($0) } } + } else { + // Degenerate fallback. Use MTP_BENCH_PROMPTS for real numbers. + promptsData = [(0 ..< 16).map { Int32($0 * 211 + 7) }] + } + let maxTokens = envInt("MTP_BENCH_MAX_TOKENS", default: 64) + let warmupTokens = envInt( + "MTP_BENCH_WARMUP_TOKENS", + default: Swift.min(16, maxTokens)) + let blockSizes = envIntList("MTP_BENCH_BLOCK_SIZES", default: [2, 3, 4, 5]) + let b1Only = env["MTP_BENCH_B1_ONLY"] == "1" + + print("\n\n=== Gemma 4 MTP real-model benchmark ===") + print("prompts=\(promptsData.count), max_tokens=\(maxTokens), warmup=\(warmupTokens)") + print("model K base tok/s mtp tok/s speedup accept_avg") + + for pair in pairs { + let targetURL = URL(fileURLWithPath: "\(dataDir)/\(pair.targetDir)") + let drafterURL = URL(fileURLWithPath: "\(dataDir)/\(pair.drafterDir)") + print("--- loading \(pair.label) ---") + + let (target, _) = try loadRealTargetAsTextModel(from: targetURL) + let drafter = try await Gemma4AssistantDraftModel.load(from: drafterURL) + eval(target, drafter) + let policy = Gemma4MTPAutomaticPolicy.automatic(for: target) + print( + "\(pair.label) automatic policy: " + + "family=\(policy.family), " + + "B=1 \(policy.strategy(forBatchSize: 1)), " + + "B=4 \(policy.strategy(forBatchSize: 4))") + + // Warmup on first prompt with largest block size to exercise + // the full drafter path. + let warmupPrompt = MLXArray(promptsData[0]) + _ = measureBaselineThroughput( + target: target, promptTokens: warmupPrompt, maxTokens: warmupTokens) + _ = try measureMTPThroughput( + target: target, drafter: drafter, + promptTokens: warmupPrompt, maxTokens: warmupTokens, + blockSize: blockSizes.max()!) + MLX.Memory.clearCache() + + // Baseline once per prompt (block-size invariant). + var baseRates: [Double] = [] + for promptInts in promptsData { + let prompt = MLXArray(promptInts) + let base = measureBaselineThroughput( + target: target, promptTokens: prompt, maxTokens: maxTokens) + MLX.Memory.clearCache() + baseRates.append(base.tokensPerSecond) + } + let baseAvg = baseRates.reduce(0, +) / Double(baseRates.count) + + for K in blockSizes { + var mtpRates: [Double] = [] + var allAccepts: [Int] = [] + for promptInts in promptsData { + let prompt = MLXArray(promptInts) + let mtp = try measureMTPThroughput( + target: target, drafter: drafter, + promptTokens: prompt, maxTokens: maxTokens, + blockSize: K) + MLX.Memory.clearCache() + mtpRates.append(mtp.tokensPerSecond) + allAccepts.append(contentsOf: mtp.acceptLengths ?? []) + } + let mtpAvg = mtpRates.reduce(0, +) / Double(mtpRates.count) + let accAvg = allAccepts.isEmpty + ? 0.0 + : Double(allAccepts.reduce(0, +)) / Double(allAccepts.count) + let speedup = mtpAvg / max(baseAvg, 1e-9) + let baseStr = String(format: "%10.1f", baseAvg) + let mtpStr = String(format: "%10.1f", mtpAvg) + let spdStr = String(format: "%.2fx", speedup) + let accStr = String(format: "%.2f", accAvg) + let label = pair.label.padding(toLength: 18, withPad: " ", startingAt: 0) + print("\(label) \(K) \(baseStr) \(mtpStr) \(spdStr) \(accStr)/\(K-1)") + } + + if b1Only { + continue + } + + // Batched (B=4) — sweep block sizes because the B=1 optimum + // is not guaranteed to carry over to batched decode. + let B4 = Array(repeating: promptsData[0], count: 4) + _ = measureBatchedBaselineThroughput( + target: target, promptTokens: B4, maxTokens: warmupTokens) + _ = try await measureBatchedMTPThroughput( + target: target, drafter: drafter, + promptTokens: B4, maxTokens: warmupTokens, + blockSize: blockSizes.max()!) + MLX.Memory.clearCache() + + let batchBase = measureBatchedBaselineThroughput( + target: target, promptTokens: B4, maxTokens: maxTokens) + MLX.Memory.clearCache() + let labelB4 = pair.label.padding(toLength: 18, withPad: " ", startingAt: 0) + let automaticB4 = policy.strategy(forBatchSize: B4.count) + for K in blockSizes { + let batchMtp = try await measureBatchedMTPThroughput( + target: target, drafter: drafter, + promptTokens: B4, maxTokens: maxTokens, + blockSize: K) + MLX.Memory.clearCache() + let batchSpeedup = batchMtp.tokensPerSecond + / max(batchBase.tokensPerSecond, 1e-9) + let bbStr = String(format: "%10.1f", batchBase.tokensPerSecond) + let bmStr = String(format: "%10.1f", batchMtp.tokensPerSecond) + let bsStr = String(format: "%.2fx", batchSpeedup) + let automaticMarker = + automaticB4 == .batched(blockSize: K) ? " auto" : "" + print( + "\(labelB4) \(K)(B=4) \(bbStr) \(bmStr) " + + "\(bsStr)\(automaticMarker) " + + "-- (aggregate, uniform budget)") + } + + // Continuous-batching benchmark: staggered budgets at B ∈ + // {4, 8, 16}. Each row gets a different maxTokens cap, so + // rows finish at different times and compaction can fire. + // + // For each B: run WITH compaction (maxTokensPerRow set) vs + // WITHOUT compaction (uniform maxTokens = max of budgets, + // pad all rows). Compare wall time for the SAME total + // emitted tokens. + // + // B=16 only runs when MTP_BENCH_LARGE_B=1 is set (requires + // >64 GB to be safe on 26B-A4B). + let blockForBatch = 4 + let batchSizes: [Int] = { + if ProcessInfo.processInfo.environment["MTP_BENCH_LARGE_B"] != nil { + return [4, 8, 16] + } + return [4] + }() + print("\(labelB4) --- continuous-batching comparison ---") + print("\(labelB4) B budgets compact_s pad_s win") + for B in batchSizes { + // Build staggered budgets — half the rows at max, a + // quarter at max/2, a quarter at max/4 + max/8. + var budgets: [Int] = [] + for i in 0 ..< B { + switch i % 4 { + case 0: budgets.append(Swift.max(maxTokens / 8, 1)) + case 1: budgets.append(Swift.max(maxTokens / 4, 1)) + case 2: budgets.append(maxTokens / 2) + default: budgets.append(maxTokens) + } + } + let budgetMax = budgets.max() ?? maxTokens + let budgetTotal = budgets.reduce(0, +) + + let prompts = Array(repeating: promptsData[0], count: B) + + // Warmup (small budget) to clear kernel-compile noise. + _ = try await measureBatchedMTPThroughputStaggered( + target: target, drafter: drafter, + promptTokens: prompts, + maxTokensPerRow: Array(repeating: 4, count: B), + blockSize: blockForBatch) + MLX.Memory.clearCache() + + // Compacted run (true continuous batching). + let compactRun = try await measureBatchedMTPThroughputStaggered( + target: target, drafter: drafter, + promptTokens: prompts, maxTokensPerRow: budgets, + blockSize: blockForBatch) + MLX.Memory.clearCache() + + // Non-compacted run: all rows run to budgetMax (pad). + // Reports per-token time, so the win is compact_per_tok / + // pad_per_tok invariant (>1 means compact is faster per + // emitted token, regardless of total token count). + let padRun = try await measureBatchedMTPThroughput( + target: target, drafter: drafter, + promptTokens: prompts, + maxTokens: budgetMax, + blockSize: blockForBatch) + MLX.Memory.clearCache() + + let compactPerTok = + compactRun.generationSeconds + / Double(max(compactRun.totalGenerated, 1)) + let padPerTok = + padRun.generationSeconds + / Double(max(padRun.totalGenerated, 1)) + let win = padPerTok / compactPerTok + _ = budgetTotal // kept for clarity above + let budgetStr = budgets.map(String.init).joined(separator: ",") + let compStr = String( + format: "%.1f tok/s", 1.0 / compactPerTok) + let padStr = String( + format: "%.1f tok/s", 1.0 / padPerTok) + let winStr = String(format: "%.2fx", win) + print( + "\(labelB4) \(B) " + + "\(budgetStr.padding(toLength: 18, withPad: " ", startingAt: 0))" + + " compact=\(compStr) pad=\(padStr) win=\(winStr)") + } + } + } + + /// Load a HF Gemma 4 target (VLM-format checkpoint) into a bare + /// `Gemma4TextModel`. The VLM wrapper is instantiated briefly so its + /// sanitize() can strip vision/audio weights + remap key names; we + /// then reach in and return the inner text model for MTP use. + private func loadRealTargetAsTextModel( + from modelDir: URL + ) throws -> (Gemma4TextModel, Gemma4Configuration) { + let configData = try Data( + contentsOf: modelDir.appendingPathComponent("config.json")) + let decoder = JSONDecoder() + let fullConfig = try decoder.decode(Gemma4Configuration.self, from: configData) + let baseConfig = try? decoder.decode(BaseConfiguration.self, from: configData) + + let wrapper = Gemma4Model(fullConfig) + try loadWeights( + modelDirectory: modelDir, + model: wrapper, + quantization: nil, + perLayerQuantization: baseConfig?.perLayerQuantization + ) + return (wrapper.textModel, fullConfig) + } +} diff --git a/Tests/MLXLMTests/Gemma4MTPErrorTests.swift b/Tests/MLXLMTests/Gemma4MTPErrorTests.swift new file mode 100644 index 0000000000..d211e2fdb2 --- /dev/null +++ b/Tests/MLXLMTests/Gemma4MTPErrorTests.swift @@ -0,0 +1,41 @@ +// Copyright © 2026 Apple Inc. + +import Foundation +import MLXLLM +import Testing + +@Suite("Gemma4MTPError") +struct Gemma4MTPErrorTests { + + @Test func unsupportedTargetHasNonEmptyDescription() { + let err = Gemma4MTPError.unsupportedTarget("FooModel") + #expect(err.errorDescription != nil) + #expect(err.errorDescription!.contains("FooModel")) + } + + @Test func rebindForbiddenHasDescription() { + let err = Gemma4MTPError.rebindForbidden + #expect(err.errorDescription != nil) + #expect(!(err.errorDescription ?? "").isEmpty) + } + + @Test func incompatibleDrafterMentionsField() { + let err = Gemma4MTPError.incompatibleDrafter( + field: "backboneHiddenSize", drafter: "2560", target: "1536") + let desc = err.errorDescription ?? "" + #expect(desc.contains("backboneHiddenSize")) + #expect(desc.contains("2560")) + #expect(desc.contains("1536")) + } + + @Test func invalidBlockSizeMentionsValue() { + let err = Gemma4MTPError.invalidBlockSize(1) + #expect((err.errorDescription ?? "").contains("1")) + } + + @Test func drafterNotBoundHasDescription() { + let err = Gemma4MTPError.drafterNotBound + #expect(err.errorDescription != nil) + #expect(!(err.errorDescription ?? "").isEmpty) + } +} diff --git a/Tests/MLXLMTests/Gemma4MTPParityTests.swift b/Tests/MLXLMTests/Gemma4MTPParityTests.swift new file mode 100644 index 0000000000..a348ed0704 --- /dev/null +++ b/Tests/MLXLMTests/Gemma4MTPParityTests.swift @@ -0,0 +1,837 @@ +// Copyright © 2026 Apple Inc. + +import Foundation +import MLX +import MLXLMCommon +import MLXRandom +import MLXLLM +import Testing + +/// Swift-internal MTP parity. The invariant: +/// +/// target_greedy(prompt) == MTP_greedy(prompt, drafter) +/// +/// holds regardless of drafter weight quality — the MTP algorithm's +/// verify-and-correct path guarantees the drafter's presence doesn't +/// change the emitted token sequence. A divergence is an implementation +/// bug in the target forward, the drafter forward, the round loop, or +/// the cache rollback. +@Suite("Gemma4 MTP parity vs baseline (Swift-internal)", .serialized) +struct Gemma4MTPParityTests { + + // MARK: - Config fixtures + + /// E2B-shaped target (reduced for test speed): 12 layers, 6 kv-shared, + /// hidden=256, vocab=1024. Reduced vocab (2^10) keeps tests fast — the + /// algorithm is vocab-size-agnostic. + private func e2bStyleTargetConfig() throws -> Gemma4TextConfiguration { + let json = """ + { + "model_type": "gemma4_text", + "hidden_size": 256, + "num_hidden_layers": 12, + "intermediate_size": 512, + "num_attention_heads": 4, + "head_dim": 32, + "global_head_dim": 32, + "num_key_value_heads": 1, + "num_kv_shared_layers": 6, + "sliding_window": 128, + "sliding_window_pattern": 5, + "final_logit_softcapping": 30.0, + "tie_word_embeddings": true, + "vocab_size": 1024, + "vocab_size_per_layer_input": 1024, + "rms_norm_eps": 1e-6, + "hidden_size_per_layer_input": 0 + } + """ + let data = Data(json.utf8) + return try JSONDecoder.json5().decode(Gemma4TextConfiguration.self, from: data) + } + + /// E2B-shaped drafter. Matches target hidden_size + vocab_size for + /// compat validation; 4 layers all kv-shared; configurable centroid head. + private func e2bStyleDrafterConfig( + useOrderedEmbeddings: Bool = false + ) throws -> Gemma4AssistantConfiguration { + let json = """ + { + "model_type": "gemma4_assistant", + "backbone_hidden_size": 256, + "use_ordered_embeddings": \(useOrderedEmbeddings), + "num_centroids": 32, + "centroid_intermediate_top_k": 4, + "text_config": { + "model_type": "gemma4_text", + "hidden_size": 64, + "num_hidden_layers": 4, + "intermediate_size": 128, + "num_attention_heads": 2, + "head_dim": 32, + "global_head_dim": 32, + "num_key_value_heads": 1, + "num_kv_shared_layers": 4, + "sliding_window": 64, + "final_logit_softcapping": null, + "tie_word_embeddings": true, + "vocab_size": 1024, + "vocab_size_per_layer_input": 1024, + "rms_norm_eps": 1e-6, + "hidden_size_per_layer_input": 0, + "use_double_wide_mlp": false, + "layer_types": ["sliding_attention", "sliding_attention", + "sliding_attention", "full_attention"] + } + } + """ + let data = Data(json.utf8) + return try JSONDecoder.json5().decode(Gemma4AssistantConfiguration.self, from: data) + } + + // MARK: - Baseline (no-drafter greedy) + + /// Run target-only greedy generation: prefill with promptTokens, then + /// sample one token at a time for up to `maxTokens` steps. Returns the + /// generated token IDs (excluding the prompt). + private func runBaselineGreedy( + target: Gemma4TextModel, + promptTokens: [Int32], + maxTokens: Int + ) -> [Int] { + let cache = target.newCache(parameters: nil) + // Prefill. + let prompt = MLXArray(promptTokens)[.newAxis, .ellipsis] + var logits = target(prompt, cache: cache) // [1, L, vocab] + var tok = logits[0..., -1, 0...].asType(.float32).argMax(axis: -1) // [1] + eval(tok) + + var out: [Int] = [Int(tok.item(Int32.self))] + for _ in 1 ..< maxTokens { + // Feed last token back; cache advances. + let input = tok[.newAxis, .ellipsis] // [1, 1] + logits = target(input, cache: cache) + tok = logits[0..., -1, 0...].asType(.float32).argMax(axis: -1) + eval(tok) + out.append(Int(tok.item(Int32.self))) + } + return out + } + + // MARK: - MTP greedy (via runGemma4MTPRounds) + + private func runMTPGreedy( + target: Gemma4TextModel, + drafter: Gemma4AssistantDraftModel, + promptTokens: [Int32], + maxTokens: Int, + blockSize: Int + ) async throws -> [Int] { + // Prefill to produce firstBonus / firstHidden / firstSharedKV. + let prompt = MLXArray(promptTokens)[.newAxis, .ellipsis] + let cache = target.newCache(parameters: nil) + let prefillOut = target.forwardForMTP(prompt, cache: cache) + let lastLogits = prefillOut.logits[0..., -1, 0...] + let firstBonus = Int(lastLogits.asType(.float32).argMax(axis: -1).item(Int32.self)) + let firstHidden = prefillOut.lastHidden[ + 0..., -1 ..< prefillOut.lastHidden.dim(1), 0...] + let firstSharedKV = prefillOut.capturedSharedKV + + let stream = try runGemma4MTPRounds( + target: target, + drafter: drafter, + targetCache: cache, + firstBonus: firstBonus, + firstHidden: firstHidden, + firstSharedKV: firstSharedKV, + maxTokens: maxTokens, + blockSize: blockSize + ) + var tokens: [Int] = [] + for await gen in stream { + if case .chunk(let s) = gen, let tok = Int(s) { + tokens.append(tok) + } + } + return tokens + } + + // MARK: - Parity tests (parameterized) + + @Test(arguments: [ + (blockSize: 2, promptLen: 4, maxTokens: 12), + (blockSize: 3, promptLen: 4, maxTokens: 12), + (blockSize: 4, promptLen: 4, maxTokens: 12), + (blockSize: 2, promptLen: 16, maxTokens: 24), + (blockSize: 3, promptLen: 16, maxTokens: 24), + (blockSize: 4, promptLen: 16, maxTokens: 24), + (blockSize: 2, promptLen: 64, maxTokens: 32), + (blockSize: 3, promptLen: 64, maxTokens: 32), + (blockSize: 4, promptLen: 64, maxTokens: 32), + ]) + func dense_drafter_parity( + config: (blockSize: Int, promptLen: Int, maxTokens: Int) + ) async throws { + let targetCfg = try e2bStyleTargetConfig() + let target = Gemma4TextModel(targetCfg) + let drafterCfg = try e2bStyleDrafterConfig(useOrderedEmbeddings: false) + let drafter = Gemma4AssistantDraftModel(config: drafterCfg) + eval(target, drafter) + + // Deterministic random prompt — we only care about parity, not content. + var rng = SystemRandomNumberGenerator() + let promptTokens: [Int32] = (0 ..< config.promptLen).map { _ in + Int32.random(in: 0 ..< 1024, using: &rng) + } + + let baseline = runBaselineGreedy( + target: target, + promptTokens: promptTokens, + maxTokens: config.maxTokens + ) + let mtp = try await runMTPGreedy( + target: target, + drafter: drafter, + promptTokens: promptTokens, + maxTokens: config.maxTokens, + blockSize: config.blockSize + ) + + #expect( + baseline == mtp, + """ + Baseline vs MTP token divergence + blockSize=\(config.blockSize) + promptLen=\(config.promptLen) + maxTokens=\(config.maxTokens) + prompt=\(promptTokens) + baseline=\(baseline) + mtp=\(mtp) + """ + ) + } + + @Test(arguments: [ + (blockSize: 2, promptLen: 8, maxTokens: 12), + (blockSize: 3, promptLen: 8, maxTokens: 12), + (blockSize: 4, promptLen: 8, maxTokens: 12), + ]) + func centroid_drafter_parity( + config: (blockSize: Int, promptLen: Int, maxTokens: Int) + ) async throws { + // Same invariant, but exercising the Gemma4MaskedEmbedder path. + let targetCfg = try e2bStyleTargetConfig() + let target = Gemma4TextModel(targetCfg) + let drafterCfg = try e2bStyleDrafterConfig(useOrderedEmbeddings: true) + let drafter = Gemma4AssistantDraftModel(config: drafterCfg) + eval(target, drafter) + + var rng = SystemRandomNumberGenerator() + let promptTokens: [Int32] = (0 ..< config.promptLen).map { _ in + Int32.random(in: 0 ..< 1024, using: &rng) + } + + let baseline = runBaselineGreedy( + target: target, + promptTokens: promptTokens, + maxTokens: config.maxTokens + ) + let mtp = try await runMTPGreedy( + target: target, + drafter: drafter, + promptTokens: promptTokens, + maxTokens: config.maxTokens, + blockSize: config.blockSize + ) + + #expect( + baseline == mtp, + """ + Centroid-head baseline vs MTP divergence + blockSize=\(config.blockSize) + promptLen=\(config.promptLen) + maxTokens=\(config.maxTokens) + prompt=\(promptTokens) + baseline=\(baseline) + mtp=\(mtp) + """ + ) + } +} + +/// E4B-shaped parity, plus batched (B>1) coverage. +@Suite("Gemma4 MTP parity — E4B shapes", .serialized) +struct Gemma4E4BMTPParityTests { + + private struct SeededRNG: RandomNumberGenerator { + var state: UInt64 + init(seed: UInt64) { self.state = seed == 0 ? 0xDEADBEEF : seed } + mutating func next() -> UInt64 { + state &+= 0x9E3779B97F4A7C15 + var z = state + z = (z ^ (z >> 30)) &* 0xBF58476D1CE4E5B9 + z = (z ^ (z >> 27)) &* 0x94D049BB133111EB + return z ^ (z >> 31) + } + } + + // MARK: - Config fixtures + + /// E4B-shaped target: scaled down for test speed but preserves the + /// architectural shape (20 layers, 12 kv-shared, 8-head attention, + /// global_head_dim != head_dim). 1024 vocab keeps logit computation + /// cheap without changing the algorithm under test. + private func e4bStyleTargetConfig() throws -> Gemma4TextConfiguration { + let json = """ + { + "model_type": "gemma4_text", + "hidden_size": 512, + "num_hidden_layers": 20, + "intermediate_size": 1024, + "num_attention_heads": 4, + "head_dim": 64, + "global_head_dim": 128, + "num_key_value_heads": 1, + "num_kv_shared_layers": 12, + "sliding_window": 128, + "sliding_window_pattern": 5, + "final_logit_softcapping": 30.0, + "tie_word_embeddings": true, + "vocab_size": 1024, + "vocab_size_per_layer_input": 1024, + "rms_norm_eps": 1e-6, + "hidden_size_per_layer_input": 0 + } + """ + let data = Data(json.utf8) + return try JSONDecoder.json5().decode(Gemma4TextConfiguration.self, from: data) + } + + /// E4B-shaped drafter. backbone_hidden_size MUST equal target + /// hidden_size (512) for pre/post projection shapes to work. + /// Drafter's own hidden is smaller (128) — the tiny 4-layer trunk. + private func e4bStyleDrafterConfig( + useOrderedEmbeddings: Bool = false + ) throws -> Gemma4AssistantConfiguration { + let json = """ + { + "model_type": "gemma4_assistant", + "backbone_hidden_size": 512, + "use_ordered_embeddings": \(useOrderedEmbeddings), + "num_centroids": 32, + "centroid_intermediate_top_k": 4, + "text_config": { + "model_type": "gemma4_text", + "hidden_size": 128, + "num_hidden_layers": 4, + "intermediate_size": 256, + "num_attention_heads": 2, + "head_dim": 64, + "global_head_dim": 128, + "num_key_value_heads": 1, + "num_kv_shared_layers": 4, + "sliding_window": 64, + "final_logit_softcapping": null, + "tie_word_embeddings": true, + "vocab_size": 1024, + "vocab_size_per_layer_input": 1024, + "rms_norm_eps": 1e-6, + "hidden_size_per_layer_input": 0, + "use_double_wide_mlp": false, + "layer_types": ["sliding_attention", "sliding_attention", + "sliding_attention", "full_attention"] + } + } + """ + let data = Data(json.utf8) + return try JSONDecoder.json5().decode(Gemma4AssistantConfiguration.self, from: data) + } + + // MARK: - Baselines & MTP runners (B=1) + + /// Target-only greedy (same logic as Task 23 but inline so this suite is + /// self-contained). + private func runBaselineGreedy( + target: Gemma4TextModel, promptTokens: [Int32], maxTokens: Int + ) -> [Int] { + let cache = target.newCache(parameters: nil) + let prompt = MLXArray(promptTokens)[.newAxis, .ellipsis] + var logits = target(prompt, cache: cache) + var tok = logits[0..., -1, 0...].asType(.float32).argMax(axis: -1) + eval(tok) + var out: [Int] = [Int(tok.item(Int32.self))] + for _ in 1 ..< maxTokens { + let input = tok[.newAxis, .ellipsis] + logits = target(input, cache: cache) + tok = logits[0..., -1, 0...].asType(.float32).argMax(axis: -1) + eval(tok) + out.append(Int(tok.item(Int32.self))) + } + return out + } + + private func runMTPGreedy( + target: Gemma4TextModel, drafter: Gemma4AssistantDraftModel, + promptTokens: [Int32], maxTokens: Int, blockSize: Int + ) async throws -> [Int] { + let prompt = MLXArray(promptTokens)[.newAxis, .ellipsis] + let cache = target.newCache(parameters: nil) + let prefillOut = target.forwardForMTP(prompt, cache: cache) + let firstBonus = Int(prefillOut.logits[0..., -1, 0...] + .asType(.float32).argMax(axis: -1).item(Int32.self)) + let firstHidden = prefillOut.lastHidden[ + 0..., -1 ..< prefillOut.lastHidden.dim(1), 0...] + let stream = try runGemma4MTPRounds( + target: target, drafter: drafter, + targetCache: cache, + firstBonus: firstBonus, firstHidden: firstHidden, + firstSharedKV: prefillOut.capturedSharedKV, + maxTokens: maxTokens, blockSize: blockSize) + var out: [Int] = [] + for await gen in stream { + if case .chunk(let s) = gen, let tok = Int(s) { out.append(tok) } + } + return out + } + + // MARK: - Batched runner (B>1) + + /// Batched prefill helper. Assumes uniform prompt length across rows. + /// The target's non-shared layers get BatchKVCache / BatchRotatingKVCache + /// so the B>1 round loop has caches that support .filterBatched / per-row + /// tail-zero. + private func batchedPrefill( + target: Gemma4TextModel, promptIds: [[Int32]] + ) -> (firstBonus: [Int], firstHidden: MLXArray, + firstSharedKV: Gemma4SharedKV, cache: [KVCache]) { + let B = promptIds.count + let L = promptIds[0].count + let tokens = MLXArray(promptIds.flatMap { $0 }, [B, L]) + let firstKvShared = target.configuration.numHiddenLayers + - target.configuration.numKvSharedLayers + let leftPadding = Array(repeating: 0, count: B) + var cache: [KVCache] = [] + for i in 0 ..< firstKvShared { + let lt = target.configuration.layerTypes[i] + if lt == "full_attention" { + cache.append(BatchKVCache(leftPadding: leftPadding)) + } else { + cache.append(BatchRotatingKVCache( + maxSize: target.configuration.slidingWindow, + leftPadding: leftPadding)) + } + } + let out = target.forwardForMTP(tokens, cache: cache) + let lastLogits = out.logits[0..., -1, 0...] + let bonusArr = lastLogits.asType(.float32).argMax(axis: -1).asArray(Int32.self) + let bonus = bonusArr.map { Int($0) } + let lastHidden = out.lastHidden[0..., -1 ..< out.lastHidden.dim(1), 0...] + return (bonus, lastHidden, out.capturedSharedKV, cache) + } + + /// Collect per-row MTP output tokens from the batched round loop. + /// Returns [[Int]] where result[i] is row i's emitted token sequence. + private func runBatchedMTP( + target: Gemma4TextModel, drafter: Gemma4AssistantDraftModel, + promptIds: [[Int32]], maxTokens: Int, blockSize: Int + ) async throws -> [[Int]] { + let B = promptIds.count + let p = batchedPrefill(target: target, promptIds: promptIds) + let stream = try runGemma4MTPRoundsBatched( + target: target, drafter: drafter, + targetCache: p.cache, + firstBonus: p.firstBonus, firstHidden: p.firstHidden, + firstSharedKV: p.firstSharedKV, + maxTokens: maxTokens, blockSize: blockSize, + eosTokenIds: nil + ) + var perRow: [[Int]] = Array(repeating: [], count: B) + for await step in stream { + for slot in step.slots { + if let tok = slot.token { perRow[slot.row].append(tok) } + } + } + return perRow + } + + // MARK: - Tests + + @Test(arguments: [ + (blockSize: 2, promptLen: 8, maxTokens: 48), + (blockSize: 3, promptLen: 8, maxTokens: 48), + (blockSize: 4, promptLen: 8, maxTokens: 48), + (blockSize: 2, promptLen: 32, maxTokens: 64), + (blockSize: 3, promptLen: 32, maxTokens: 64), + (blockSize: 4, promptLen: 32, maxTokens: 64), + ]) + func dense_drafter_parity_E4B( + config: (blockSize: Int, promptLen: Int, maxTokens: Int) + ) async throws { + // Seed MLX's global random state so model weight init is + // reproducible across runs. + MLXRandom.seed( + UInt64(config.blockSize) * 1000 + UInt64(config.promptLen) * 100 + UInt64(config.maxTokens)) + let target = Gemma4TextModel(try e4bStyleTargetConfig()) + let drafter = Gemma4AssistantDraftModel(config: try e4bStyleDrafterConfig()) + eval(target, drafter) + + // Deterministic seed keyed on the test config so failures reproduce. + var rng = SeededRNG( + seed: UInt64(config.blockSize) * 1000 + UInt64(config.promptLen) * 100 + UInt64(config.maxTokens)) + let promptTokens: [Int32] = (0 ..< config.promptLen).map { _ in + Int32.random(in: 0 ..< 1024, using: &rng) + } + + let baseline = runBaselineGreedy( + target: target, promptTokens: promptTokens, maxTokens: config.maxTokens) + let mtp = try await runMTPGreedy( + target: target, drafter: drafter, + promptTokens: promptTokens, maxTokens: config.maxTokens, + blockSize: config.blockSize) + #expect( + baseline == mtp, + """ + E4B dense parity divergence + blockSize=\(config.blockSize) + promptLen=\(config.promptLen) + maxTokens=\(config.maxTokens) + prompt=\(promptTokens) + baseline=\(baseline) + mtp=\(mtp) + """ + ) + } + + @Test(arguments: [ + (blockSize: 2, promptLen: 8, maxTokens: 32), + (blockSize: 3, promptLen: 8, maxTokens: 32), + (blockSize: 4, promptLen: 8, maxTokens: 32), + ]) + func centroid_drafter_parity_E4B( + config: (blockSize: Int, promptLen: Int, maxTokens: Int) + ) async throws { + // Seed MLX's global random state so model weight init is + // reproducible across runs. + MLXRandom.seed( + UInt64(config.blockSize) * 1000 + UInt64(config.promptLen) * 100 + UInt64(config.maxTokens)) + let target = Gemma4TextModel(try e4bStyleTargetConfig()) + let drafter = Gemma4AssistantDraftModel( + config: try e4bStyleDrafterConfig(useOrderedEmbeddings: true)) + eval(target, drafter) + + // Deterministic seed keyed on the test config so failures reproduce. + var rng = SeededRNG( + seed: UInt64(config.blockSize) * 1000 + UInt64(config.promptLen) * 100 + UInt64(config.maxTokens)) + let promptTokens: [Int32] = (0 ..< config.promptLen).map { _ in + Int32.random(in: 0 ..< 1024, using: &rng) + } + + let baseline = runBaselineGreedy( + target: target, promptTokens: promptTokens, maxTokens: config.maxTokens) + let mtp = try await runMTPGreedy( + target: target, drafter: drafter, + promptTokens: promptTokens, maxTokens: config.maxTokens, + blockSize: config.blockSize) + #expect( + baseline == mtp, + """ + E4B centroid parity divergence + blockSize=\(config.blockSize) + promptLen=\(config.promptLen) + maxTokens=\(config.maxTokens) + prompt=\(promptTokens) + baseline=\(baseline) + mtp=\(mtp) + """ + ) + } + + /// Batched parity: per-row MTP must equal that row's standalone baseline. + /// + /// NOTE: `maxTokens` is chosen so no row enters a degenerate-logit + /// repetition tail. Random weights + tiny vocab (1024) quickly produce + /// near-uniform logits once the model starts repeating a token; in that + /// regime B=2 batched vs B=1 non-batched argmax can flip due to bf16 + /// precision differences in batched scaled-dot-product attention. This + /// is the same class of divergence the Python mlx-vlm MTP reference + /// exhibits at temp=0 (8/20 of our chat-templated prompts diverge) + /// and is not a correctness bug in the drafter itself — both sequences + /// are valid greedy continuations. + @Test(arguments: [ + (blockSize: 2, B: 2, maxTokens: 20), + (blockSize: 3, B: 2, maxTokens: 24), + (blockSize: 4, B: 2, maxTokens: 24), + (blockSize: 3, B: 4, maxTokens: 20), + ]) + func batched_parity_E4B( + config: (blockSize: Int, B: Int, maxTokens: Int) + ) async throws { + // Seed MLX's global random state so model weight init is + // reproducible across runs. + MLXRandom.seed( + UInt64(config.blockSize) * 1000 + UInt64(config.B) * 100 + UInt64(config.maxTokens)) + // Construct B prompts of uniform length 8. + // Deterministic seed keyed on the test config so failures reproduce. + var rng = SeededRNG( + seed: UInt64(config.blockSize) * 1000 + UInt64(config.B) * 100 + UInt64(config.maxTokens)) + let promptLen = 8 + let promptIds: [[Int32]] = (0 ..< config.B).map { _ in + (0 ..< promptLen).map { _ in + Int32.random(in: 0 ..< 1024, using: &rng) + } + } + + // Per-row baseline via the B=1 path — each row gets its own fresh + // target/drafter and cache. + var baselines: [[Int]] = [] + for row in promptIds { + let target = Gemma4TextModel(try e4bStyleTargetConfig()) + eval(target) + baselines.append(runBaselineGreedy( + target: target, promptTokens: row, maxTokens: config.maxTokens)) + } + + // Batched MTP run. NOTE: the target/drafter weights must be the + // same as the per-row baselines. To make this deterministic we + // seed every constructor with random init — but Swift MLX's + // random init uses a global RandomState. The simplest way to + // make baseline == mtp (weight-exactly) is to build ONE target, + // save its parameters, replay into each baseline-per-row target. + // That's brittle. Better: use a shared target/drafter for both + // baselines and the batched run. + // + // Rebuild: first construct shared target + drafter, run per-row + // baseline using the SAME target (re-using its weights, fresh + // cache per row), then run batched with the same target. + + let target = Gemma4TextModel(try e4bStyleTargetConfig()) + let drafter = Gemma4AssistantDraftModel(config: try e4bStyleDrafterConfig()) + eval(target, drafter) + + var sharedBaselines: [[Int]] = [] + for row in promptIds { + sharedBaselines.append(runBaselineGreedy( + target: target, promptTokens: row, maxTokens: config.maxTokens)) + } + let batched = try await runBatchedMTP( + target: target, drafter: drafter, + promptIds: promptIds, + maxTokens: config.maxTokens, + blockSize: config.blockSize) + + #expect(sharedBaselines.count == batched.count) + for i in 0 ..< sharedBaselines.count { + #expect( + sharedBaselines[i] == batched[i], + """ + E4B batched parity divergence at row \(i) + blockSize=\(config.blockSize) + B=\(config.B) + maxTokens=\(config.maxTokens) + baseline[\(i)]=\(sharedBaselines[i]) + batched[\(i)]=\(batched[i]) + """ + ) + } + } +} + +/// 26B-A4B-shaped parity. Exercises the MoE (`enable_moe_block: true`) +/// path in the TARGET. Drafter is always dense (4 layers, no MoE) — only +/// the target uses MoE routing. Validates that the shared-KV capture +/// hook, `forwardForMTP`, and round loop all handle MoE decoder layers +/// correctly. +/// +/// Shape is scaled down from the real 26B-A4B config (which has +/// hidden=2304, 32 layers, 24 kv-shared, 128 experts top-2) to keep tests +/// fast. Key architectural invariants preserved: `enable_moe_block=true`, +/// `num_experts > top_k_experts`, `moe_intermediate_size != intermediate_size`. +@Suite("Gemma4 MTP parity — 26B-A4B MoE target", .serialized) +struct Gemma4MoEMTPParityTests { + + private struct SeededRNG: RandomNumberGenerator { + var state: UInt64 + init(seed: UInt64) { self.state = seed == 0 ? 0xDEADBEEF : seed } + mutating func next() -> UInt64 { + state &+= 0x9E3779B97F4A7C15 + var z = state + z = (z ^ (z >> 30)) &* 0xBF58476D1CE4E5B9 + z = (z ^ (z >> 27)) &* 0x94D049BB133111EB + return z ^ (z >> 31) + } + } + + /// 26B-A4B-shaped target with MoE enabled. 12 layers (6 kv-shared), 8 + /// experts top-2 — matches the real 26B-A4B's architectural pattern + /// at a testable scale. + private func moeTargetConfig() throws -> Gemma4TextConfiguration { + let json = """ + { + "model_type": "gemma4_text", + "hidden_size": 256, + "num_hidden_layers": 12, + "intermediate_size": 512, + "num_attention_heads": 4, + "head_dim": 64, + "global_head_dim": 128, + "num_key_value_heads": 1, + "num_kv_shared_layers": 6, + "sliding_window": 128, + "sliding_window_pattern": 5, + "final_logit_softcapping": 30.0, + "tie_word_embeddings": true, + "vocab_size": 1024, + "vocab_size_per_layer_input": 1024, + "rms_norm_eps": 1e-6, + "hidden_size_per_layer_input": 0, + "enable_moe_block": true, + "num_experts": 8, + "top_k_experts": 2, + "moe_intermediate_size": 256 + } + """ + let data = Data(json.utf8) + return try JSONDecoder.json5().decode(Gemma4TextConfiguration.self, from: data) + } + + /// Drafter matching the 26B-A4B-shape target (backbone_hidden_size=256). + /// Drafter itself is dense (no MoE); the real 26B-A4B drafter uses a + /// tied LM head and no centroid routing. + /// + /// Attention head dims MUST match the target (head_dim=64, + /// global_head_dim=128) because the drafter reads target K/V directly — + /// `scaled_dot_product_attention` requires matching last-axis size + /// between query and keys. + private func moeDrafterConfig() throws -> Gemma4AssistantConfiguration { + let json = """ + { + "model_type": "gemma4_assistant", + "backbone_hidden_size": 256, + "use_ordered_embeddings": false, + "num_centroids": 32, + "centroid_intermediate_top_k": 4, + "tie_word_embeddings": true, + "text_config": { + "model_type": "gemma4_text", + "hidden_size": 128, + "num_hidden_layers": 4, + "intermediate_size": 256, + "num_attention_heads": 2, + "head_dim": 64, + "global_head_dim": 128, + "num_key_value_heads": 1, + "num_kv_shared_layers": 4, + "sliding_window": 64, + "final_logit_softcapping": null, + "tie_word_embeddings": true, + "vocab_size": 1024, + "vocab_size_per_layer_input": 1024, + "rms_norm_eps": 1e-6, + "hidden_size_per_layer_input": 0, + "use_double_wide_mlp": false, + "layer_types": ["sliding_attention", "sliding_attention", + "sliding_attention", "full_attention"] + } + } + """ + let data = Data(json.utf8) + return try JSONDecoder.json5().decode(Gemma4AssistantConfiguration.self, from: data) + } + + // MARK: - Baseline + MTP runners + + private func runBaselineGreedy( + target: Gemma4TextModel, promptTokens: [Int32], maxTokens: Int + ) -> [Int] { + let cache = target.newCache(parameters: nil) + let prompt = MLXArray(promptTokens)[.newAxis, .ellipsis] + var logits = target(prompt, cache: cache) + var tok = logits[0..., -1, 0...].asType(.float32).argMax(axis: -1) + eval(tok) + var out: [Int] = [Int(tok.item(Int32.self))] + for _ in 1 ..< maxTokens { + let input = tok[.newAxis, .ellipsis] + logits = target(input, cache: cache) + tok = logits[0..., -1, 0...].asType(.float32).argMax(axis: -1) + eval(tok) + out.append(Int(tok.item(Int32.self))) + } + return out + } + + private func runMTPGreedy( + target: Gemma4TextModel, drafter: Gemma4AssistantDraftModel, + promptTokens: [Int32], maxTokens: Int, blockSize: Int + ) async throws -> [Int] { + let prompt = MLXArray(promptTokens)[.newAxis, .ellipsis] + let cache = target.newCache(parameters: nil) + let prefillOut = target.forwardForMTP(prompt, cache: cache) + let firstBonus = Int(prefillOut.logits[0..., -1, 0...] + .asType(.float32).argMax(axis: -1).item(Int32.self)) + let firstHidden = prefillOut.lastHidden[ + 0..., -1 ..< prefillOut.lastHidden.dim(1), 0...] + let stream = try runGemma4MTPRounds( + target: target, drafter: drafter, + targetCache: cache, + firstBonus: firstBonus, firstHidden: firstHidden, + firstSharedKV: prefillOut.capturedSharedKV, + maxTokens: maxTokens, blockSize: blockSize) + var out: [Int] = [] + for await gen in stream { + if case .chunk(let s) = gen, let tok = Int(s) { out.append(tok) } + } + return out + } + + // MARK: - Tests + + /// MoE-target parity: MTP output must equal baseline across block sizes. + /// `maxTokens` kept modest to avoid the degenerate-logit tail (bf16 + /// near-uniform argmax flips, same class as Python oracle divergence). + @Test(arguments: [ + (blockSize: 2, promptLen: 8, maxTokens: 20), + (blockSize: 3, promptLen: 8, maxTokens: 20), + (blockSize: 4, promptLen: 8, maxTokens: 20), + (blockSize: 3, promptLen: 16, maxTokens: 16), + ]) + func moe_target_parity( + config: (blockSize: Int, promptLen: Int, maxTokens: Int) + ) async throws { + MLXRandom.seed( + UInt64(config.blockSize) * 1000 + + UInt64(config.promptLen) * 100 + + UInt64(config.maxTokens)) + + let target = Gemma4TextModel(try moeTargetConfig()) + let drafter = Gemma4AssistantDraftModel(config: try moeDrafterConfig()) + eval(target, drafter) + + var rng = SeededRNG( + seed: UInt64(config.blockSize) * 1000 + + UInt64(config.promptLen) * 100 + + UInt64(config.maxTokens)) + let promptTokens: [Int32] = (0 ..< config.promptLen).map { _ in + Int32.random(in: 0 ..< 1024, using: &rng) + } + + let baseline = runBaselineGreedy( + target: target, promptTokens: promptTokens, maxTokens: config.maxTokens) + let mtp = try await runMTPGreedy( + target: target, drafter: drafter, + promptTokens: promptTokens, maxTokens: config.maxTokens, + blockSize: config.blockSize) + + #expect( + baseline == mtp, + """ + MoE-target parity divergence + blockSize=\(config.blockSize) + promptLen=\(config.promptLen) + maxTokens=\(config.maxTokens) + prompt=\(promptTokens) + baseline=\(baseline) + mtp=\(mtp) + """ + ) + } +} diff --git a/Tests/MLXLMTests/Gemma4MTPPolicyTests.swift b/Tests/MLXLMTests/Gemma4MTPPolicyTests.swift new file mode 100644 index 0000000000..2a18ee9abe --- /dev/null +++ b/Tests/MLXLMTests/Gemma4MTPPolicyTests.swift @@ -0,0 +1,110 @@ +// Copyright © 2026 Apple Inc. + +import Foundation +import MLXLLM +import Testing + +@Suite("Gemma4 MTP automatic policy") +struct Gemma4MTPPolicyTests { + private func config( + hiddenSize: Int, + layers: Int, + enableMoe: Bool = false, + quantizationBits: Int? = nil + ) throws -> Gemma4TextConfiguration { + let quantizationJSON = + if let quantizationBits { + """ + , + "quantization": {"bits": \(quantizationBits), "group_size": 64} + """ + } else { + "" + } + let json = """ + { + "model_type": "gemma4_text", + "hidden_size": \(hiddenSize), + "num_hidden_layers": \(layers), + "enable_moe_block": \(enableMoe), + "num_experts": \(enableMoe ? 128 : 0), + "top_k_experts": \(enableMoe ? 8 : 0), + "moe_intermediate_size": \(enableMoe ? 704 : 0) + \(quantizationJSON) + } + """ + return try JSONDecoder().decode( + Gemma4TextConfiguration.self, from: Data(json.utf8)) + } + + @Test func e2bUsesBatchedMTPForBatchedRequests() throws { + let policy = Gemma4MTPAutomaticPolicy.automatic( + for: try config(hiddenSize: 1536, layers: 35)) + + #expect(policy.family == .e2b) + #expect(policy.supportsBatchedMTP) + #expect(policy.strategy(forBatchSize: 1) == .singleStream(blockSize: 5)) + #expect(policy.strategy(forBatchSize: 4) == .batched(blockSize: 3)) + #expect(policy.singleStreamAction( + generatedTokens: 32, maxTokens: nil) == .mtp(blockSize: 5)) + } + + @Test func quantizedE2BUsesTokenRangeAwareSingleStreamPolicy() throws { + let policy = Gemma4MTPAutomaticPolicy.automatic( + for: try config(hiddenSize: 1536, layers: 35, quantizationBits: 4)) + + #expect(policy.family == .e2b) + #expect(!policy.supportsBatchedMTP) + #expect(policy.strategy(forBatchSize: 1) == .singleStream(blockSize: 3)) + #expect(policy.strategy(forBatchSize: 4) == .singleStream(blockSize: 3)) + #expect(policy.singleStreamAction( + generatedTokens: 0, maxTokens: 12) == .mtp(blockSize: 4)) + #expect(policy.singleStreamAction( + generatedTokens: 15, maxTokens: 12) == .mtp(blockSize: 4)) + #expect(policy.singleStreamAction( + generatedTokens: 0, maxTokens: 64) == .targetOnly) + #expect(policy.singleStreamAction( + generatedTokens: 64, maxTokens: 1024) == .targetOnly) + #expect(policy.singleStreamAction( + generatedTokens: 255, maxTokens: 1024) == .targetOnly) + #expect(policy.singleStreamAction( + generatedTokens: 256, maxTokens: 1024) == .mtp(blockSize: 4)) + #expect(policy.singleStreamAction( + generatedTokens: 0, maxTokens: nil) == .targetOnly) + } + + @Test func e4bDisablesAutomaticMTPUntilCorrectPathBeatsBaseline() throws { + let policy = Gemma4MTPAutomaticPolicy.automatic( + for: try config(hiddenSize: 2560, layers: 42)) + + #expect(policy.family == .e4b) + #expect(!policy.enablesAutomaticMTP) + #expect(!policy.supportsBatchedMTP) + #expect(policy.strategy(forBatchSize: 1) == .singleStream(blockSize: 3)) + #expect(policy.strategy(forBatchSize: 4) == .singleStream(blockSize: 3)) + #expect(policy.singleStreamAction( + generatedTokens: 64, maxTokens: nil) == .targetOnly) + } + + @Test func moeA4BFallsBackToSingleStreamForBatchedRequests() throws { + let policy = Gemma4MTPAutomaticPolicy.automatic( + for: try config(hiddenSize: 2816, layers: 30, enableMoe: true)) + + #expect(policy.family == .moeA4B) + #expect(!policy.supportsBatchedMTP) + #expect(policy.strategy(forBatchSize: 1) == .singleStream(blockSize: 3)) + #expect(policy.strategy(forBatchSize: 4) == .singleStream(blockSize: 3)) + } + + @Test func unknownModelsStayConservative() throws { + let dense = Gemma4MTPAutomaticPolicy.automatic( + for: try config(hiddenSize: 4096, layers: 48)) + let moe = Gemma4MTPAutomaticPolicy.automatic( + for: try config(hiddenSize: 4096, layers: 48, enableMoe: true)) + + #expect(dense.family == .unknownDense) + #expect(dense.strategy(forBatchSize: 4) == .singleStream(blockSize: 4)) + #expect(moe.family == .unknownMoE) + #expect(moe.strategy(forBatchSize: 4) == .singleStream(blockSize: 3)) + } +} diff --git a/Tests/MLXLMTests/Gemma4MTPRoundLoopTests.swift b/Tests/MLXLMTests/Gemma4MTPRoundLoopTests.swift new file mode 100644 index 0000000000..3a92e60c51 --- /dev/null +++ b/Tests/MLXLMTests/Gemma4MTPRoundLoopTests.swift @@ -0,0 +1,583 @@ +// Copyright © 2026 Apple Inc. + +import Foundation +import MLX +import MLXLMCommon +import MLXLLM +import Testing + +@Suite("Gemma4MTPRoundLoop B=1") +struct Gemma4MTPRoundLoopTests { + + /// Minimal Gemma 4 target: 10 layers, 5 kv-shared, hidden=64, vocab=64. + /// Matches the shapes the drafter expects in its forward. + private func smallTarget() throws -> Gemma4TextModel { + let json = """ + { + "model_type": "gemma4_text", + "hidden_size": 64, + "num_hidden_layers": 10, + "intermediate_size": 128, + "num_attention_heads": 2, + "head_dim": 32, + "global_head_dim": 32, + "num_key_value_heads": 1, + "num_kv_shared_layers": 5, + "sliding_window": 64, + "sliding_window_pattern": 5, + "final_logit_softcapping": 30.0, + "tie_word_embeddings": true, + "vocab_size": 64, + "vocab_size_per_layer_input": 64, + "rms_norm_eps": 1e-6, + "hidden_size_per_layer_input": 0 + } + """ + let data = Data(json.utf8) + let config = try JSONDecoder.json5().decode( + Gemma4TextConfiguration.self, from: data) + return Gemma4TextModel(config) + } + + /// Minimal drafter config matching the target's hidden_size and vocab. + private func smallDrafter() throws -> Gemma4AssistantDraftModel { + let json = """ + { + "model_type": "gemma4_assistant", + "backbone_hidden_size": 64, + "use_ordered_embeddings": false, + "num_centroids": 8, + "centroid_intermediate_top_k": 2, + "text_config": { + "model_type": "gemma4_text", + "hidden_size": 64, + "num_hidden_layers": 4, + "intermediate_size": 128, + "num_attention_heads": 2, + "head_dim": 32, + "global_head_dim": 32, + "num_key_value_heads": 1, + "num_kv_shared_layers": 4, + "sliding_window": 64, + "final_logit_softcapping": null, + "tie_word_embeddings": true, + "vocab_size": 64, + "vocab_size_per_layer_input": 64, + "rms_norm_eps": 1e-6, + "hidden_size_per_layer_input": 0, + "use_double_wide_mlp": false, + "layer_types": ["sliding_attention", "sliding_attention", + "sliding_attention", "full_attention"] + } + } + """ + let data = Data(json.utf8) + let cfg = try JSONDecoder.json5().decode( + Gemma4AssistantConfiguration.self, from: data) + return Gemma4AssistantDraftModel(config: cfg) + } + + /// Run prefill on the target to produce firstBonus/firstHidden/firstSharedKV + /// for a given prompt. Drives the target's forwardForMTP over the prompt. + private func prefill( + target: Gemma4TextModel, promptTokens: [Int32] + ) -> (firstBonus: Int, firstHidden: MLXArray, firstSharedKV: Gemma4SharedKV, + cache: [KVCache]) { + let tokens = MLXArray(promptTokens)[.newAxis, .ellipsis] // [1, L] + let cache = target.newCache(parameters: nil) + let out = target.forwardForMTP(tokens, cache: cache) + // Greedy bonus from the last position. + let lastLogits = out.logits[0..., -1, 0...] + let bonus = Int(lastLogits.asType(.float32).argMax(axis: -1).item(Int32.self)) + // Last-position hidden (the drafter's next-step input). + let lastHidden = out.lastHidden[0..., -1 ..< out.lastHidden.dim(1), 0...] + return (bonus, lastHidden, out.capturedSharedKV, cache) + } + + @Test func mtpEmitsTokensAndTerminates() async throws { + let target = try smallTarget() + let drafter = try smallDrafter() + eval(target, drafter) + + let prompt: [Int32] = [1, 2, 3, 4, 5] + let prefillResult = prefill(target: target, promptTokens: prompt) + + // Collect generated tokens as ints for easy inspection. + var produced: [Int] = [] + let stream = try runGemma4MTPRounds( + target: target, + drafter: drafter, + targetCache: prefillResult.cache, + firstBonus: prefillResult.firstBonus, + firstHidden: prefillResult.firstHidden, + firstSharedKV: prefillResult.firstSharedKV, + maxTokens: 12, + blockSize: 3 + ) + for try await gen in stream { + if case .chunk(let s) = gen, let tok = Int(s) { produced.append(tok) } + } + // Should emit at least the first bonus + some more tokens, up to + // the maxTokens cap. Exact count depends on acceptance rate. + #expect(produced.count >= 1) + #expect(produced.count <= 12) + } + + @Test func mtpRespectsMaxTokens() async throws { + let target = try smallTarget() + let drafter = try smallDrafter() + eval(target, drafter) + + let prefillResult = prefill(target: target, promptTokens: [1, 2, 3]) + + var count = 0 + let stream = try runGemma4MTPRounds( + target: target, + drafter: drafter, + targetCache: prefillResult.cache, + firstBonus: prefillResult.firstBonus, + firstHidden: prefillResult.firstHidden, + firstSharedKV: prefillResult.firstSharedKV, + maxTokens: 5, + blockSize: 3 + ) + for try await gen in stream { + if case .chunk = gen { count += 1 } + } + #expect(count <= 5) + } +} + +@Suite("Gemma4MTPRoundLoop B>1") +struct Gemma4MTPRoundLoopBatchedTests { + + /// Build a target that can handle batched input. Uses `BatchKVCache` + /// for all non-shared attention layers. Shape is identical to the B=1 + /// tests but we pre-populate the cache via a batched prefill. + private func smallTarget() throws -> Gemma4TextModel { + let json = """ + { + "model_type": "gemma4_text", + "hidden_size": 64, + "num_hidden_layers": 10, + "intermediate_size": 128, + "num_attention_heads": 2, + "head_dim": 32, + "global_head_dim": 32, + "num_key_value_heads": 1, + "num_kv_shared_layers": 5, + "sliding_window": 64, + "sliding_window_pattern": 5, + "final_logit_softcapping": 30.0, + "tie_word_embeddings": true, + "vocab_size": 64, + "vocab_size_per_layer_input": 64, + "rms_norm_eps": 1e-6, + "hidden_size_per_layer_input": 0 + } + """ + let data = Data(json.utf8) + let config = try JSONDecoder.json5().decode( + Gemma4TextConfiguration.self, from: data) + return Gemma4TextModel(config) + } + + private func smallDrafter() throws -> Gemma4AssistantDraftModel { + let json = """ + { + "model_type": "gemma4_assistant", + "backbone_hidden_size": 64, + "use_ordered_embeddings": false, + "num_centroids": 8, + "centroid_intermediate_top_k": 2, + "text_config": { + "model_type": "gemma4_text", + "hidden_size": 64, + "num_hidden_layers": 4, + "intermediate_size": 128, + "num_attention_heads": 2, + "head_dim": 32, + "global_head_dim": 32, + "num_key_value_heads": 1, + "num_kv_shared_layers": 4, + "sliding_window": 64, + "final_logit_softcapping": null, + "tie_word_embeddings": true, + "vocab_size": 64, + "vocab_size_per_layer_input": 64, + "rms_norm_eps": 1e-6, + "hidden_size_per_layer_input": 0, + "use_double_wide_mlp": false, + "layer_types": ["sliding_attention", "sliding_attention", + "sliding_attention", "full_attention"] + } + } + """ + let data = Data(json.utf8) + let cfg = try JSONDecoder.json5().decode( + Gemma4AssistantConfiguration.self, from: data) + return Gemma4AssistantDraftModel(config: cfg) + } + + /// Batched prefill: B rows with identical length for simplicity. Returns + /// firstBonus (per row), firstHidden [B, 1, hidden], firstSharedKV. + private func batchedPrefill( + target: Gemma4TextModel, promptIds: [[Int32]] + ) -> (firstBonus: [Int], firstHidden: MLXArray, + firstSharedKV: Gemma4SharedKV, cache: [KVCache]) { + let B = promptIds.count + let L = promptIds[0].count + precondition(promptIds.allSatisfy { $0.count == L }, + "this test helper assumes uniform prompt lengths") + let tokens = MLXArray(promptIds.flatMap { $0 }, [B, L]) // [B, L] + + // Use BatchKVCache for every non-shared layer so the B>1 path works. + let firstKvShared = target.configuration.numHiddenLayers + - target.configuration.numKvSharedLayers + let leftPadding = Array(repeating: 0, count: B) + var cache: [KVCache] = [] + for i in 0 ..< firstKvShared { + let lt = target.configuration.layerTypes[i] + if lt == "full_attention" { + cache.append(BatchKVCache(leftPadding: leftPadding)) + } else { + cache.append(BatchRotatingKVCache( + maxSize: target.configuration.slidingWindow, + leftPadding: leftPadding)) + } + } + + let out = target.forwardForMTP(tokens, cache: cache) + // Per-row greedy bonus from the last position. + let lastLogits = out.logits[0..., -1, 0...] // [B, vocab] + let bonusArr = lastLogits.asType(.float32).argMax(axis: -1).asArray(Int32.self) + let bonus = bonusArr.map { Int($0) } + let lastHidden = out.lastHidden[0..., -1 ..< out.lastHidden.dim(1), 0...] + return (bonus, lastHidden, out.capturedSharedKV, cache) + } + + @Test func batchedMtpEmitsForAllRows() async throws { + let target = try smallTarget() + let drafter = try smallDrafter() + eval(target, drafter) + + let prompts: [[Int32]] = [ + [1, 2, 3, 4], + [5, 6, 7, 8], + ] + let p = batchedPrefill(target: target, promptIds: prompts) + + var emittedPerRow: [[Int]] = [[], []] + let stream = try runGemma4MTPRoundsBatched( + target: target, + drafter: drafter, + targetCache: p.cache, + firstBonus: p.firstBonus, + firstHidden: p.firstHidden, + firstSharedKV: p.firstSharedKV, + maxTokens: 8, + blockSize: 3, + eosTokenIds: nil + ) + for try await step in stream { + for slot in step.slots { + if let tok = slot.token { emittedPerRow[slot.row].append(tok) } + } + } + #expect(emittedPerRow[0].count >= 1) + #expect(emittedPerRow[0].count <= 8) + #expect(emittedPerRow[1].count >= 1) + #expect(emittedPerRow[1].count <= 8) + } + + @Test func batchedMtpRespectsEOS() async throws { + // Pick an EOS that's definitely in the vocab (anything <= 63). + // We can't force the model to emit a specific EOS on random weights, + // but we CAN choose a set large enough that at least one sampled + // token falls in it. Use the entire vocab as EOS -> every row + // finishes after its first sample. + let target = try smallTarget() + let drafter = try smallDrafter() + eval(target, drafter) + + let prompts: [[Int32]] = [[1, 2, 3], [4, 5, 6]] + let p = batchedPrefill(target: target, promptIds: prompts) + let allVocabEOS: Set = Set(0 ..< 64) + + var totalTokens = 0 + let stream = try runGemma4MTPRoundsBatched( + target: target, + drafter: drafter, + targetCache: p.cache, + firstBonus: p.firstBonus, + firstHidden: p.firstHidden, + firstSharedKV: p.firstSharedKV, + maxTokens: 16, + blockSize: 3, + eosTokenIds: allVocabEOS + ) + for try await step in stream { + for slot in step.slots where slot.token != nil { + totalTokens += 1 + } + } + // With every token in EOS, each row should finish almost immediately + // (the first bonus is always emitted before EOS can fire, plus any + // tokens emitted in the first round before the EOS check). + // Strict bound: each row emits <= blockSize tokens. + #expect(totalTokens <= 2 * 3) // B=2, blockSize=3 + } + + /// Continuous-batching compaction: when some rows finish early (EOS), + /// the remaining rows should keep emitting and the emission sequence + /// should still use the ORIGINAL row indices. Verifies that cache + /// filtering + state compaction don't corrupt the per-row output. + @Test func continuousBatchingCompactsFinishedRows() async throws { + let target = try smallTarget() + let drafter = try smallDrafter() + eval(target, drafter) + + let prompts: [[Int32]] = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]] + let p = batchedPrefill(target: target, promptIds: prompts) + + // Craft an EOS set that contains the first bonus for rows 0 and 2 + // but not rows 1 and 3 — rows 0/2 finish on their first emission, + // rows 1/3 must continue for the full maxTokens budget. + // + // We don't know the bonuses a priori, but we can find out: firstBonus + // is returned from batchedPrefill. Pick the EOS set accordingly. + let eos: Set = [p.firstBonus[0], p.firstBonus[2]] + + var emittedPerRow: [[Int]] = [[], [], [], []] + let stream = try runGemma4MTPRoundsBatched( + target: target, drafter: drafter, + targetCache: p.cache, + firstBonus: p.firstBonus, firstHidden: p.firstHidden, + firstSharedKV: p.firstSharedKV, + maxTokens: 8, blockSize: 3, + eosTokenIds: eos + ) + for try await step in stream { + for slot in step.slots { + if let tok = slot.token { + emittedPerRow[slot.row].append(tok) + } + } + } + // Rows 0 and 2: bonus is in EOS so they finish after their very + // first emission. They should have exactly 1 emitted token. + #expect(emittedPerRow[0].count == 1, + "row 0 should finish on bonus (EOS), got \(emittedPerRow[0].count)") + #expect(emittedPerRow[2].count == 1, + "row 2 should finish on bonus (EOS), got \(emittedPerRow[2].count)") + // Rows 1 and 3: bonus is NOT in EOS (unless by coincidence the + // random-weight bonuses happen to collide — rare at vocab=64 but + // possible); check that they continue past 1. + if p.firstBonus[1] != p.firstBonus[0] && p.firstBonus[1] != p.firstBonus[2] { + #expect(emittedPerRow[1].count > 1, + "row 1's bonus is not EOS; should continue past 1") + } + if p.firstBonus[3] != p.firstBonus[0] && p.firstBonus[3] != p.firstBonus[2] { + #expect(emittedPerRow[3].count > 1, + "row 3's bonus is not EOS; should continue past 1") + } + } +} + +@Suite("generateGemma4MTP") +struct GenerateGemma4MTPTests { + + /// Build a minimal Gemma4 target + drafter + TestTokenizer-based context. + /// Note: the tests use random weights, so output text is gibberish — we + /// only verify structure (stream starts/ends, string chunks emitted). + private func makeContext() throws -> (ModelContext, Gemma4AssistantDraftModel) { + let targetJSON = """ + { + "model_type": "gemma4_text", + "hidden_size": 64, + "num_hidden_layers": 10, + "intermediate_size": 128, + "num_attention_heads": 2, + "head_dim": 32, + "global_head_dim": 32, + "num_key_value_heads": 1, + "num_kv_shared_layers": 5, + "sliding_window": 64, + "sliding_window_pattern": 5, + "final_logit_softcapping": 30.0, + "tie_word_embeddings": true, + "vocab_size": 64, + "vocab_size_per_layer_input": 64, + "rms_norm_eps": 1e-6, + "hidden_size_per_layer_input": 0 + } + """ + let targetCfg = try JSONDecoder.json5().decode( + Gemma4TextConfiguration.self, from: Data(targetJSON.utf8)) + let target = Gemma4TextModel(targetCfg) + + let drafterJSON = """ + { + "model_type": "gemma4_assistant", + "backbone_hidden_size": 64, + "use_ordered_embeddings": false, + "num_centroids": 8, + "centroid_intermediate_top_k": 2, + "text_config": { + "model_type": "gemma4_text", + "hidden_size": 64, + "num_hidden_layers": 4, + "intermediate_size": 128, + "num_attention_heads": 2, + "head_dim": 32, + "global_head_dim": 32, + "num_key_value_heads": 1, + "num_kv_shared_layers": 4, + "sliding_window": 64, + "final_logit_softcapping": null, + "tie_word_embeddings": true, + "vocab_size": 64, + "vocab_size_per_layer_input": 64, + "rms_norm_eps": 1e-6, + "hidden_size_per_layer_input": 0, + "use_double_wide_mlp": false, + "layer_types": ["sliding_attention", "sliding_attention", + "sliding_attention", "full_attention"] + } + } + """ + let drafterCfg = try JSONDecoder.json5().decode( + Gemma4AssistantConfiguration.self, from: Data(drafterJSON.utf8)) + let drafter = Gemma4AssistantDraftModel(config: drafterCfg) + eval(target, drafter) + + let processor = TestInputProcessor() + let modelConfig = ModelConfiguration( + id: "gemma4-test", + defaultPrompt: "", + extraEOSTokens: [], + toolCallFormat: nil + ) + let context = ModelContext( + configuration: modelConfig, + model: target, + processor: processor, + tokenizer: processor.tokenizer + ) + return (context, drafter) + } + + @Test func generateEmitsChunksAndFinishesCleanly() async throws { + let (context, drafter) = try makeContext() + // Minimal LMInput. + let tokens = MLXArray([Int32(1), 2, 3, 4])[.newAxis, .ellipsis] + let input = LMInput(text: .init(tokens: tokens)) + var params = GenerateParameters() + params.maxTokens = 6 + + let stream = try generateGemma4MTP( + input: input, + parameters: params, + target: context, + drafter: drafter, + blockSize: 3 + ) + + var chunks: [String] = [] + var hasInfo = false + for try await gen in stream { + switch gen { + case .chunk(let s): chunks.append(s) + case .info: hasInfo = true + default: break + } + } + #expect(chunks.count >= 1) + #expect(chunks.count <= 6) + #expect(hasInfo) + } + + @Test func generateRejectsNonGemma4Target() async throws { + // Build a Gemma3TextModel context — it should throw unsupportedTarget. + let processor = TestInputProcessor() + let modelConfig = ModelConfiguration( + id: "gemma3-not-supported", defaultPrompt: "", + extraEOSTokens: [], toolCallFormat: nil) + let gemma3Config = Gemma3TextConfiguration( + modelType: "text", + hiddenSize: 64, hiddenLayers: 8, intermediateSize: 64, + attentionHeads: 4, headDim: 64, + rmsNormEps: 0.00001, vocabularySize: 100, kvHeads: 4, + ropeTheta: 1_000_000, ropeLocalBaseFreq: 10_000, + ropeTraditional: false, queryPreAttnScalar: 256, + slidingWindow: 512, slidingWindowPattern: 6, + maxPositionEmbeddings: 32768 + ) + let target = Gemma3TextModel(gemma3Config) + let context = ModelContext( + configuration: modelConfig, model: target, + processor: processor, tokenizer: processor.tokenizer) + + let drafterJSON = """ + { + "model_type": "gemma4_assistant", + "backbone_hidden_size": 64, + "use_ordered_embeddings": false, + "num_centroids": 8, + "centroid_intermediate_top_k": 2, + "text_config": { + "model_type": "gemma4_text", + "hidden_size": 64, + "num_hidden_layers": 4, + "intermediate_size": 128, + "num_attention_heads": 2, + "head_dim": 32, + "global_head_dim": 32, + "num_key_value_heads": 1, + "num_kv_shared_layers": 4, + "sliding_window": 64, + "final_logit_softcapping": null, + "tie_word_embeddings": true, + "vocab_size": 64, + "vocab_size_per_layer_input": 64, + "rms_norm_eps": 1e-6, + "hidden_size_per_layer_input": 0, + "use_double_wide_mlp": false, + "layer_types": ["sliding_attention", "sliding_attention", + "sliding_attention", "full_attention"] + } + } + """ + let drafterCfg = try JSONDecoder.json5().decode( + Gemma4AssistantConfiguration.self, from: Data(drafterJSON.utf8)) + let drafter = Gemma4AssistantDraftModel(config: drafterCfg) + eval(target, drafter) + + let tokens = MLXArray([Int32(1), 2, 3])[.newAxis, .ellipsis] + let input = LMInput(text: .init(tokens: tokens)) + var params = GenerateParameters() + params.maxTokens = 4 + + #expect(throws: Gemma4MTPError.self) { + _ = try generateGemma4MTP( + input: input, parameters: params, target: context, + drafter: drafter, blockSize: 3 + ) + } + } + + @Test func generateRejectsInvalidBlockSize() async throws { + let (context, drafter) = try makeContext() + let tokens = MLXArray([Int32(1), 2, 3])[.newAxis, .ellipsis] + let input = LMInput(text: .init(tokens: tokens)) + var params = GenerateParameters() + params.maxTokens = 4 + + #expect(throws: Gemma4MTPError.self) { + _ = try generateGemma4MTP( + input: input, parameters: params, target: context, + drafter: drafter, blockSize: 1 + ) + } + } +} diff --git a/Tests/MLXLMTests/Gemma4MTPStochasticTests.swift b/Tests/MLXLMTests/Gemma4MTPStochasticTests.swift new file mode 100644 index 0000000000..c90fb55855 --- /dev/null +++ b/Tests/MLXLMTests/Gemma4MTPStochasticTests.swift @@ -0,0 +1,266 @@ +// Copyright © 2026 Apple Inc. +// +// Tests for stochastic (temperature > 0) MTP sampling. Validates: +// 1. Iterator produces valid output at temperature > 0 (no crashes, +// tokens in vocab range). +// 2. Rejection-based sampling properties: at temperature=0.0001 the +// stochastic path degenerates to greedy (distributions are ~point +// masses; all accepts/resamples collapse to argmax). +// 3. Distribution match: repeated sampling of the first token from the +// iterator is consistent with sampling from the target's softmax +// directly (MTP shouldn't change the emission distribution). + +import Foundation +import MLX +import MLXLMCommon +import MLXRandom +import MLXLLM +import Testing + +@Suite("Gemma4 MTP stochastic sampling", .serialized) +struct Gemma4MTPStochasticTests { + + private func tinyTarget() throws -> Gemma4TextModel { + let json = """ + { + "model_type": "gemma4_text", + "hidden_size": 256, + "num_hidden_layers": 12, + "intermediate_size": 512, + "num_attention_heads": 4, + "head_dim": 32, + "global_head_dim": 32, + "num_key_value_heads": 1, + "num_kv_shared_layers": 6, + "sliding_window": 128, + "sliding_window_pattern": 5, + "final_logit_softcapping": 30.0, + "tie_word_embeddings": true, + "vocab_size": 1024, + "vocab_size_per_layer_input": 1024, + "rms_norm_eps": 1e-6, + "hidden_size_per_layer_input": 0 + } + """ + return Gemma4TextModel( + try JSONDecoder.json5().decode( + Gemma4TextConfiguration.self, from: Data(json.utf8))) + } + + private func tinyDrafter() throws -> Gemma4AssistantDraftModel { + let json = """ + { + "model_type": "gemma4_assistant", + "backbone_hidden_size": 256, + "use_ordered_embeddings": false, + "num_centroids": 32, + "centroid_intermediate_top_k": 4, + "tie_word_embeddings": true, + "text_config": { + "model_type": "gemma4_text", + "hidden_size": 64, + "num_hidden_layers": 4, + "intermediate_size": 128, + "num_attention_heads": 2, + "head_dim": 32, + "global_head_dim": 32, + "num_key_value_heads": 1, + "num_kv_shared_layers": 4, + "sliding_window": 64, + "final_logit_softcapping": null, + "tie_word_embeddings": true, + "vocab_size": 1024, + "vocab_size_per_layer_input": 1024, + "rms_norm_eps": 1e-6, + "hidden_size_per_layer_input": 0, + "use_double_wide_mlp": false, + "layer_types": ["sliding_attention", "sliding_attention", + "sliding_attention", "full_attention"] + } + } + """ + return Gemma4AssistantDraftModel( + config: try JSONDecoder.json5().decode( + Gemma4AssistantConfiguration.self, from: Data(json.utf8))) + } + + /// Temperature > 0 path runs end-to-end, emits the right count, and + /// every token is within the vocab range. + @Test func stochasticIteratorEmitsValidTokens() async throws { + MLXRandom.seed(42) + let target = try tinyTarget() + let drafter = try tinyDrafter() + eval(target, drafter) + + let promptTokens = MLXArray([Int32](repeating: 7, count: 8)) + let input = LMInput(text: .init(tokens: promptTokens)) + var iter = try Gemma4MTPTokenIterator( + input: input, target: target, drafter: drafter, + parameters: GenerateParameters(maxTokens: 16, temperature: 0.8), + blockSize: 3, + rngSeed: 12345) + + var count = 0 + var tokens: [Int] = [] + while let t = iter.next() { + count += 1 + tokens.append(t) + } + #expect(count == 16, "iterator must emit exactly maxTokens") + for t in tokens { + #expect(t >= 0 && t < 1024, "token \(t) out of vocab range [0, 1024)") + } + } + + /// Near-zero temperature should collapse stochastic to greedy. Tokens + /// emitted at temperature=1e-4 should match tokens at temperature=0 + /// for the same seed (drafter/target distributions become + /// degenerate point masses at the argmax). + @Test func lowTempCollapsesToGreedy() async throws { + MLXRandom.seed(42) + let target = try tinyTarget() + let drafter = try tinyDrafter() + eval(target, drafter) + + let promptTokens = MLXArray([Int32](repeating: 7, count: 8)) + let input = LMInput(text: .init(tokens: promptTokens)) + + var greedyIter = try Gemma4MTPTokenIterator( + input: input, target: target, drafter: drafter, + parameters: GenerateParameters(maxTokens: 8, temperature: 0), + blockSize: 3) + var greedyTokens: [Int] = [] + while let t = greedyIter.next() { greedyTokens.append(t) } + + var lowTempIter = try Gemma4MTPTokenIterator( + input: input, target: target, drafter: drafter, + parameters: GenerateParameters(maxTokens: 8, temperature: 1e-4), + blockSize: 3, + rngSeed: 777) + var lowTempTokens: [Int] = [] + while let t = lowTempIter.next() { lowTempTokens.append(t) } + + #expect( + greedyTokens == lowTempTokens, + """ + At temperature=1e-4 the stochastic path should produce the same + tokens as temperature=0. Divergence suggests a bug in the + rejection sampler. + greedy =\(greedyTokens) + lowTemp =\(lowTempTokens) + """) + } + + /// topK=1 at temperature > 0 should collapse to greedy — the filter + /// masks out everything except the argmax, so the rejection sampler + /// has no choice but to accept that token every time. + @Test func topKOneCollapsesToGreedy() async throws { + MLXRandom.seed(42) + let target = try tinyTarget() + let drafter = try tinyDrafter() + eval(target, drafter) + + let promptTokens = MLXArray([Int32](repeating: 7, count: 8)) + let input = LMInput(text: .init(tokens: promptTokens)) + + var greedyIter = try Gemma4MTPTokenIterator( + input: input, target: target, drafter: drafter, + parameters: GenerateParameters(maxTokens: 8, temperature: 0), + blockSize: 3) + var greedyTokens: [Int] = [] + while let t = greedyIter.next() { greedyTokens.append(t) } + + // topK=1 at temperature=1.0 — the filter collapses both p and q + // to point masses at their respective argmax. Since verify uses + // fp32 argmax on the SAME target logits baseline uses, emitted + // tokens must match greedy output exactly. + var params = GenerateParameters(maxTokens: 8, temperature: 1.0) + params.topK = 1 + var topKIter = try Gemma4MTPTokenIterator( + input: input, target: target, drafter: drafter, + parameters: params, + blockSize: 3, + rngSeed: 999) + var topKTokens: [Int] = [] + while let t = topKIter.next() { topKTokens.append(t) } + + #expect( + greedyTokens == topKTokens, + """ + topK=1 should produce the same output as greedy + greedy=\(greedyTokens) + topK=1=\(topKTokens) + """) + } + + /// topP with very small mass should narrow the output distribution + /// toward the argmax token — repeated samples under topP=0.01 should + /// be much less varied than topP=1.0 at the same temperature. + @Test func lowTopPNarrowsOutput() async throws { + MLXRandom.seed(42) + let target = try tinyTarget() + let drafter = try tinyDrafter() + eval(target, drafter) + + let promptTokens = MLXArray([Int32](repeating: 7, count: 8)) + let input = LMInput(text: .init(tokens: promptTokens)) + + func sampleAt(topP: Float, seed: UInt64) throws -> [Int] { + var params = GenerateParameters(maxTokens: 8, temperature: 1.0) + params.topP = topP + var iter = try Gemma4MTPTokenIterator( + input: input, target: target, drafter: drafter, + parameters: params, + blockSize: 3, + rngSeed: seed) + var toks: [Int] = [] + while let t = iter.next() { toks.append(t) } + return toks + } + + var narrow = Set<[Int]>() + var wide = Set<[Int]>() + for seed: UInt64 in 1 ... 8 { + narrow.insert(try sampleAt(topP: 0.01, seed: seed)) + wide.insert(try sampleAt(topP: 1.0, seed: seed)) + } + // Narrow topP should produce fewer distinct sequences than wide. + #expect( + narrow.count <= wide.count, + """ + topP=0.01 should produce at most as many distinct sequences + as topP=1.0 across the same 8 seeds + narrow (topP=0.01): \(narrow.count) distinct + wide (topP=1.0): \(wide.count) distinct + """) + } + + /// Different seeds at temperature > 0 should produce different output + /// (sanity: the sampler is actually stochastic). + @Test func differentSeedsProduceDifferentOutput() async throws { + MLXRandom.seed(42) + let target = try tinyTarget() + let drafter = try tinyDrafter() + eval(target, drafter) + + let promptTokens = MLXArray([Int32](repeating: 7, count: 8)) + let input = LMInput(text: .init(tokens: promptTokens)) + var seen = Set<[Int]>() + for seed: UInt64 in [1, 2, 3, 4, 5, 6, 7, 8] { + var iter = try Gemma4MTPTokenIterator( + input: input, target: target, drafter: drafter, + parameters: GenerateParameters(maxTokens: 12, temperature: 1.0), + blockSize: 3, + rngSeed: seed) + var toks: [Int] = [] + while let t = iter.next() { toks.append(t) } + seen.insert(toks) + } + #expect( + seen.count > 1, + """ + Different seeds at temperature=1.0 should produce different tokens; + got only \(seen.count) distinct sequences across 8 seeds + """) + } +} diff --git a/Tests/MLXLMTests/Gemma4MTPTokenIteratorTests.swift b/Tests/MLXLMTests/Gemma4MTPTokenIteratorTests.swift new file mode 100644 index 0000000000..b26039c5f3 --- /dev/null +++ b/Tests/MLXLMTests/Gemma4MTPTokenIteratorTests.swift @@ -0,0 +1,158 @@ +// Copyright © 2026 Apple Inc. +// +// Tests for `Gemma4MTPTokenIterator`. Validates: +// 1. Iterator conforms to `TokenIteratorProtocol` and emits the +// expected token count. +// 2. Output matches `runGemma4MTPRounds` (the AsyncStream entry point) +// for the same config — the iterator is a drop-in equivalent. + +import Foundation +import MLX +import MLXLMCommon +import MLXRandom +import MLXLLM +import Testing + +@Suite("Gemma4MTPTokenIterator", .serialized) +struct Gemma4MTPTokenIteratorTests { + + private func tinyTarget() throws -> Gemma4TextModel { + let json = """ + { + "model_type": "gemma4_text", + "hidden_size": 256, + "num_hidden_layers": 12, + "intermediate_size": 512, + "num_attention_heads": 4, + "head_dim": 32, + "global_head_dim": 32, + "num_key_value_heads": 1, + "num_kv_shared_layers": 6, + "sliding_window": 128, + "sliding_window_pattern": 5, + "final_logit_softcapping": 30.0, + "tie_word_embeddings": true, + "vocab_size": 1024, + "vocab_size_per_layer_input": 1024, + "rms_norm_eps": 1e-6, + "hidden_size_per_layer_input": 0 + } + """ + return Gemma4TextModel( + try JSONDecoder.json5().decode( + Gemma4TextConfiguration.self, from: Data(json.utf8))) + } + + private func tinyDrafter() throws -> Gemma4AssistantDraftModel { + let json = """ + { + "model_type": "gemma4_assistant", + "backbone_hidden_size": 256, + "use_ordered_embeddings": false, + "num_centroids": 32, + "centroid_intermediate_top_k": 4, + "tie_word_embeddings": true, + "text_config": { + "model_type": "gemma4_text", + "hidden_size": 64, + "num_hidden_layers": 4, + "intermediate_size": 128, + "num_attention_heads": 2, + "head_dim": 32, + "global_head_dim": 32, + "num_key_value_heads": 1, + "num_kv_shared_layers": 4, + "sliding_window": 64, + "final_logit_softcapping": null, + "tie_word_embeddings": true, + "vocab_size": 1024, + "vocab_size_per_layer_input": 1024, + "rms_norm_eps": 1e-6, + "hidden_size_per_layer_input": 0, + "use_double_wide_mlp": false, + "layer_types": ["sliding_attention", "sliding_attention", + "sliding_attention", "full_attention"] + } + } + """ + return Gemma4AssistantDraftModel( + config: try JSONDecoder.json5().decode( + Gemma4AssistantConfiguration.self, from: Data(json.utf8))) + } + + @Test func iteratorEmitsExpectedTokenCount() async throws { + MLXRandom.seed(42) + let target = try tinyTarget() + let drafter = try tinyDrafter() + eval(target, drafter) + + let promptTokens = MLXArray([Int32](repeating: 7, count: 8)) + let input = LMInput(text: .init(tokens: promptTokens)) + var iter = try Gemma4MTPTokenIterator( + input: input, target: target, drafter: drafter, + parameters: GenerateParameters(maxTokens: 16, temperature: 0), + blockSize: 3) + + var count = 0 + while let _ = iter.next() { count += 1 } + #expect(count == 16, "iterator must emit exactly maxTokens") + #expect(iter.tokenCount == 16) + #expect(iter.promptPrefillTime > 0) + } + + @Test func iteratorMatchesAsyncStreamPath() async throws { + MLXRandom.seed(42) + let target1 = try tinyTarget() + let drafter1 = try tinyDrafter() + eval(target1, drafter1) + + // Same seed → same weights, but we need to replay exactly: + // build a second pair from the same seeded init so iterator + // and stream see identical weights. + MLXRandom.seed(42) + let target2 = try tinyTarget() + let drafter2 = try tinyDrafter() + eval(target2, drafter2) + + let promptTokens = MLXArray([Int32](repeating: 7, count: 8)) + + // Iterator path. + let input = LMInput(text: .init(tokens: promptTokens)) + var iter = try Gemma4MTPTokenIterator( + input: input, target: target1, drafter: drafter1, + parameters: GenerateParameters(maxTokens: 12, temperature: 0), + blockSize: 3) + var iteratorTokens: [Int] = [] + while let t = iter.next() { iteratorTokens.append(t) } + + // AsyncStream path. + let cache = target2.newCache(parameters: nil) + let prefillOut = target2.forwardForMTP( + promptTokens[.newAxis, .ellipsis], cache: cache) + let firstBonus = Int(prefillOut.logits[0..., -1, 0...] + .asType(.float32).argMax(axis: -1).item(Int32.self)) + let firstHidden = prefillOut.lastHidden[ + 0..., -1 ..< prefillOut.lastHidden.dim(1), 0...] + let stream = try runGemma4MTPRounds( + target: target2, drafter: drafter2, + targetCache: cache, + firstBonus: firstBonus, firstHidden: firstHidden, + firstSharedKV: prefillOut.capturedSharedKV, + maxTokens: 12, blockSize: 3) + var streamTokens: [Int] = [] + for await gen in stream { + if case .chunk(let s) = gen, let t = Int(s) { + streamTokens.append(t) + } + } + + #expect( + iteratorTokens == streamTokens, + """ + TokenIterator output differs from AsyncStream output — they + must be identical for the same seed + config. + iterator=\(iteratorTokens) + stream =\(streamTokens) + """) + } +} diff --git a/Tests/MLXLMTests/Gemma4PositionOffsetTests.swift b/Tests/MLXLMTests/Gemma4PositionOffsetTests.swift new file mode 100644 index 0000000000..41fe9f5664 --- /dev/null +++ b/Tests/MLXLMTests/Gemma4PositionOffsetTests.swift @@ -0,0 +1,29 @@ +// Copyright © 2026 Apple Inc. + +import Foundation +import MLX +import MLXLLM +import Testing + +@Suite("Gemma4.PositionOffset is public and constructible") +struct Gemma4PositionOffsetTests { + + @Test func scalarCase() { + let offset = Gemma4.PositionOffset.scalar(42) + if case .scalar(let v) = offset { + #expect(v == 42) + } else { + Issue.record("expected .scalar case") + } + } + + @Test func batchCase() { + let arr = MLXArray([Int32(0), 1, 2, 3]) + let offset = Gemma4.PositionOffset.batch(arr) + if case .batch(let a) = offset { + #expect(a.dim(0) == 4) + } else { + Issue.record("expected .batch case") + } + } +} diff --git a/Tests/MLXLMTests/Gemma4RollbackTests.swift b/Tests/MLXLMTests/Gemma4RollbackTests.swift new file mode 100644 index 0000000000..17ed8d850d --- /dev/null +++ b/Tests/MLXLMTests/Gemma4RollbackTests.swift @@ -0,0 +1,92 @@ +// Copyright © 2026 Apple Inc. + +import Foundation +import MLX +import MLXLLM +import MLXLMCommon +import Testing + +@Suite("Gemma4TextModel.rollbackSpeculativeCache") +struct Gemma4RollbackTests { + + private func smallConfig() throws -> Gemma4TextConfiguration { + let json = """ + { + "model_type": "gemma4_text", + "hidden_size": 64, + "num_hidden_layers": 10, + "intermediate_size": 128, + "num_attention_heads": 2, + "head_dim": 32, + "global_head_dim": 32, + "num_key_value_heads": 1, + "num_kv_shared_layers": 5, + "sliding_window": 16, + "sliding_window_pattern": 5, + "final_logit_softcapping": 30.0, + "tie_word_embeddings": true, + "vocab_size": 32, + "vocab_size_per_layer_input": 32, + "rms_norm_eps": 1e-6, + "hidden_size_per_layer_input": 0 + } + """ + let data = Data(json.utf8) + return try JSONDecoder.json5().decode(Gemma4TextConfiguration.self, from: data) + } + + @Test func scalarTrimsUniformly() throws { + let config = try smallConfig() + let model = Gemma4TextModel(config) + eval(model) + let tokens = MLXArray([Int32(1), 2, 3, 4, 5])[.newAxis, .ellipsis] // [1, 5] + let cache = model.newCache(parameters: nil) + _ = model(tokens, cache: cache) + let offsetBefore = cache[0].offset // == 5 + model.rollbackSpeculativeCache(cache, accepted: .scalar(1), blockSize: 3) + // Trimmed = blockSize - accepted - 1 = 3 - 1 - 1 = 1 + #expect(cache[0].offset == offsetBefore - 1) + } + + @Test func scalarNoopWhenFullyAccepted() throws { + let config = try smallConfig() + let model = Gemma4TextModel(config) + eval(model) + let tokens = MLXArray([Int32(1), 2, 3, 4, 5])[.newAxis, .ellipsis] + let cache = model.newCache(parameters: nil) + _ = model(tokens, cache: cache) + let offsetBefore = cache[0].offset + // accepted == blockSize - 1 means all drafts were accepted; no trim. + model.rollbackSpeculativeCache(cache, accepted: .scalar(2), blockSize: 3) + #expect(cache[0].offset == offsetBefore) + } + + // perRow case tested indirectly through the B>1 round-loop tests; + // the isolated test here verifies the dispatch path calls both + // trim and zeroTailPerRow without crashing on a batched cache. + @Test func perRowDispatchesToBatchedPath() throws { + // This test requires a BatchKVCache, which Gemma4TextModel.newCache + // doesn't produce. We construct one manually and invoke the method + // on a caches array that includes it. + let b = BatchKVCache(leftPadding: [0, 0]) + let k = MLXArray.ones([2, 1, 6, 4], dtype: .float32) + let v = MLXArray.ones([2, 1, 6, 4], dtype: .float32) + _ = b.update(keys: k, values: v) + + let config = try smallConfig() + let model = Gemma4TextModel(config) + let accepted = MLXArray([Int32(0), 2]) // row 0 accepts 0, row 1 accepts 2 + model.rollbackSpeculativeCache( + [b], accepted: .perRow(accepted), blockSize: 3 + ) + // Uniform trim = 3 - max(accepted) - 1 = 3 - 2 - 1 = 0 → no trim. + #expect(b.offset == 6) + // zeroTailPerRow: row 0 keeps (6 - max + 0) = 4 slots, row 1 keeps + // (6 - max + 2) = 6 slots. Row 0's last 2 slots should be zero. + let state = b.state + let row0Tail = state[0][0, 0, 4..., 0] + #expect(row0Tail.sum().item(Float.self) == 0.0) + let row1All = state[0][1, 0, 0..<6, 0] + #expect(row1All.sum().item(Float.self) == 6.0) // untouched + } +} diff --git a/Tests/MLXLMTests/Gemma4SharedKVTests.swift b/Tests/MLXLMTests/Gemma4SharedKVTests.swift new file mode 100644 index 0000000000..29d886ae85 --- /dev/null +++ b/Tests/MLXLMTests/Gemma4SharedKVTests.swift @@ -0,0 +1,91 @@ +// Copyright © 2026 Apple Inc. + +import Foundation +import MLX +import MLXLLM +import Testing + +@Suite("Gemma4SharedKV types") +struct Gemma4SharedKVTests { + + @Test func sharedKVConstructs() { + let k = MLXArray.zeros([1, 2, 8, 4], dtype: .float32) + let v = MLXArray.zeros([1, 2, 8, 4], dtype: .float32) + let shared = Gemma4SharedKV( + fullAttention: (k, v), + slidingAttention: (k, v) + ) + #expect(shared.fullAttention.0.dim(2) == 8) + #expect(shared.slidingAttention.1.dim(2) == 8) + } + + @Test func sliceTailZeroRejectedIsIdentity() { + let k = MLXArray.ones([1, 2, 8, 4], dtype: .float32) + let v = MLXArray.ones([1, 2, 8, 4], dtype: .float32) * 2.0 + let shared = Gemma4SharedKV( + fullAttention: (k, v), + slidingAttention: (k, v) + ) + let sliced = Gemma4SharedKV.sliceTail(from: shared, rejected: 0) + #expect(sliced.fullAttention.0.dim(2) == 8) + #expect(sliced.slidingAttention.0.dim(2) == 8) + } + + @Test func sliceTailTrimsTimeAxis() { + let k = MLXArray.ones([1, 2, 8, 4], dtype: .float32) + let v = MLXArray.ones([1, 2, 8, 4], dtype: .float32) * 2.0 + let shared = Gemma4SharedKV( + fullAttention: (k, v), + slidingAttention: (k, v) + ) + let sliced = Gemma4SharedKV.sliceTail(from: shared, rejected: 3) + #expect(sliced.fullAttention.0.dim(2) == 5) + #expect(sliced.slidingAttention.0.dim(2) == 5) + #expect(sliced.fullAttention.1.dim(2) == 5) + } + + @Test func sliceTailClampsAtOne() { + // When rejected >= T, preserve at least one slot (preserving the + // minimum cache invariant used by the round-loop). + let k = MLXArray.ones([1, 2, 4, 4], dtype: .float32) + let v = MLXArray.ones([1, 2, 4, 4], dtype: .float32) + let shared = Gemma4SharedKV( + fullAttention: (k, v), + slidingAttention: (k, v) + ) + let sliced = Gemma4SharedKV.sliceTail(from: shared, rejected: 100) + #expect(sliced.fullAttention.0.dim(2) == 1) + } + + @Test func captureIsReferenceType() { + let capture = Gemma4SharedKVCapture() + #expect(capture.fullAttention == nil) + #expect(capture.slidingAttention == nil) + let k = MLXArray.zeros([1, 2, 4, 4], dtype: .float32) + let v = MLXArray.zeros([1, 2, 4, 4], dtype: .float32) + capture.fullAttention = (k, v) + // Aliasing semantics: a second reference observes the write. + let alias = capture + #expect(alias.fullAttention != nil) + } + + @Test func captureSnapshotReturnsImmutableSnapshot() { + let capture = Gemma4SharedKVCapture() + let kFull = MLXArray.ones([1, 2, 8, 4], dtype: .float32) + let vFull = MLXArray.ones([1, 2, 8, 4], dtype: .float32) * 2.0 + let kSliding = MLXArray.ones([1, 2, 6, 4], dtype: .float32) * 3.0 + let vSliding = MLXArray.ones([1, 2, 6, 4], dtype: .float32) * 4.0 + capture.fullAttention = (kFull, vFull) + capture.slidingAttention = (kSliding, vSliding) + + let snap = capture.snapshot() + // Shapes preserved. + #expect(snap.fullAttention.0.dim(2) == 8) + #expect(snap.slidingAttention.0.dim(2) == 6) + // Values round-trip (verifies the snapshot isn't zeroing anything). + #expect(snap.fullAttention.0.sum().item(Float.self) == 64.0) // 1*2*8*4 + #expect(snap.fullAttention.1.sum().item(Float.self) == 128.0) // 2*2*8*4 + #expect(snap.slidingAttention.0.sum().item(Float.self) == 144.0) // 3*2*6*4 + #expect(snap.slidingAttention.1.sum().item(Float.self) == 192.0) // 4*2*6*4 + } +} diff --git a/Tests/MLXLMTests/MaskedEmbedderTests.swift b/Tests/MLXLMTests/MaskedEmbedderTests.swift new file mode 100644 index 0000000000..7090950179 --- /dev/null +++ b/Tests/MLXLMTests/MaskedEmbedderTests.swift @@ -0,0 +1,97 @@ +// Copyright © 2026 Apple Inc. + +import Foundation +import MLX +@testable import MLXLLM +import Testing + +@Suite("Gemma4MaskedEmbedder") +struct MaskedEmbedderTests { + + /// Build a small Gemma4MaskedEmbedder with known weights. + /// hiddenSize=4, numCentroids=8, topK=2, vocabSize=16 → 2 tokens per centroid. + private func buildEmbedder() -> (Gemma4MaskedEmbedder, MLXArray) { + let hiddenSize = 4 + let numCentroids = 8 + let topK = 2 + let vocabSize = 16 + + let embedder = Gemma4MaskedEmbedder( + hiddenSize: hiddenSize, + numCentroids: numCentroids, + topK: topK, + vocabSize: vocabSize + ) + + // Deterministic centroid weights: identity-ish for clarity. + // token_ordering maps each centroid c to tokens [2c, 2c+1]. + // So centroid 3 → tokens [6, 7]; centroid 7 → tokens [14, 15]. + let tokenOrdering = MLXArray( + (0 ..< vocabSize).map { Int32($0) }) + let centroidWeight = MLXArray.zeros([numCentroids, hiddenSize]) + // lm_head_weight: row `t` is a 1-hot at position (t % hiddenSize). + let lmHead = MLXArray.zeros([vocabSize, hiddenSize]) + for t in 0 ..< vocabSize { + lmHead[t, t % hiddenSize] = MLXArray(Float(1)) + } + eval(centroidWeight, lmHead, tokenOrdering) + + embedder.setTestWeights( + centroidsWeight: centroidWeight, + tokenOrdering: tokenOrdering + ) + return (embedder, lmHead) + } + + @Test func outputShapeIsFullVocab() { + let (embedder, lmHead) = buildEmbedder() + let hidden = MLXArray.ones([1, 1, 4], dtype: .float32) + let logits = embedder(hiddenStates: hidden, lmHeadWeight: lmHead) + #expect(logits.shape == [1, 1, 16]) + } + + @Test func nonSelectedSlotsGetSentinel() { + // With all-zero centroids, argPartition picks the first topK indices. + // Those top-2 centroids → 4 of 16 vocab slots get "real" logits; + // the other 12 slots must all equal the same sentinel value. + let (embedder, lmHead) = buildEmbedder() + let hidden = MLXArray.ones([1, 1, 4], dtype: .float32) + let logits = embedder(hiddenStates: hidden, lmHeadWeight: lmHead) + + // Flatten to [16] and collect the distinct values. + let flat = logits.reshaped([-1]).asArray(Float.self) + var valueCounts = [Float: Int]() + for v in flat { valueCounts[v, default: 0] += 1 } + + // Exactly 4 "real" slots; 12 sentinel slots with the same value. + // (With one-hot lm_head and hidden=ones, each selected slot has a + // real logit of 1.0; the sentinel is min(selected) - 1 = 0.) + // At least one value should appear 12 times (the sentinel). + let sentinelCount = valueCounts.values.max() ?? 0 + #expect(sentinelCount >= 12) + } + + @Test func argmaxFallsInTopKCentroid() { + // With a hidden that points strongly at one dimension, the argmax + // token's canonical centroid must be among the top-K scoring + // centroids (tautological for small k, but a good shape check). + let (embedder, _) = buildEmbedder() + let hidden = MLXArray([Float(1), 2, 3, 4]).reshaped([1, 1, 4]) + // Use a centroid weight that biases centroid index 3 strongly. + let centroidWeight = MLXArray.zeros([8, 4]) + centroidWeight[3, 0] = MLXArray(Float(10)) + eval(centroidWeight) + embedder.setTestCentroidWeight(centroidWeight) + + let lmHead = MLXArray.zeros([16, 4]) + for t in 0 ..< 16 { lmHead[t, 0] = MLXArray(Float(1)) } + eval(lmHead) + let logits = embedder(hiddenStates: hidden, lmHeadWeight: lmHead) + + // The argmax token should fall within centroid 3's tokens + // (tokens 6 or 7 given our tokenOrdering setup). Loose smoke + // check: the path runs without crashing. + let argmax = logits.argMax(axis: -1).item(Int32.self) + _ = argmax + } +} diff --git a/Tests/MLXLMTests/Resources/Gemma4MTPPrompts.json b/Tests/MLXLMTests/Resources/Gemma4MTPPrompts.json new file mode 100644 index 0000000000..5798ec050a --- /dev/null +++ b/Tests/MLXLMTests/Resources/Gemma4MTPPrompts.json @@ -0,0 +1,30 @@ +{ + "version": 1, + "description": "Fixed prompt set for Gemma 4 MTP parity tests. Committed alongside the tests so Swift and Python reference runs use byte-identical inputs.", + "short": [ + "What is the capital of France?", + "Name three primary colors.", + "What is 7 times 8?", + "Who wrote Hamlet?", + "What planet do we live on?" + ], + "medium": [ + "Explain the difference between a list and a tuple in Python, giving one concrete example of when you would use each.", + "Write a short paragraph describing the water cycle, including evaporation, condensation, and precipitation.", + "Describe the main events of the Battle of Hastings in 1066 in three or four sentences.", + "Outline the key principles of object-oriented programming, naming each principle and giving a one-sentence description.", + "Explain photosynthesis at a level suitable for a high-school biology student, mentioning the reactants and products.", + "Describe the general structure of a DNA molecule, including the role of the four nucleotide bases.", + "Summarize the plot of Romeo and Juliet in five or six sentences, without spoilers for the final act.", + "Explain what causes seasons on Earth, referencing the axial tilt and orbit.", + "Describe the basic function of the human circulatory system and name its three major components.", + "Compare and contrast renewable and non-renewable energy sources, giving two examples of each." + ], + "long": [ + "Consider the following scenario: a software team is trying to decide between using a monolithic architecture and a microservices architecture for their new e-commerce platform. The team has ten engineers, expects to handle around ten thousand transactions per day initially, and anticipates scaling to one hundred thousand transactions per day within two years. Some team members argue that a monolith is simpler to deploy and debug, while others insist that microservices are the modern approach and will make scaling easier. Provide a thoughtful analysis of the trade-offs, discussing at least four specific technical or organizational factors that should influence this decision. Conclude with a concrete recommendation.", + "Imagine you are teaching an introductory class on machine learning. Your students have programming experience but no background in statistics. Write the first few paragraphs of your lecture, introducing the concept of supervised learning. Your explanation should motivate why supervised learning is useful, describe the general structure of a training dataset (features and labels), give an intuitive example of a simple prediction task, and briefly mention how the model's performance can be evaluated. Aim for a tone that is clear and engaging but technically correct.", + "You are writing documentation for a new distributed key-value store. The system provides strong consistency, is partition-tolerant, and trades availability during network partitions. Explain the CAP theorem to a reader who has heard the term but never really understood it. Then, using the specific design choices of this key-value store as a running example, walk the reader through what would happen during a network partition: which operations succeed, which fail, and why. Use concrete examples rather than abstract descriptions, and avoid mathematical formalism.", + "A senior engineer at your company has written a code review that you disagree with. The review criticizes your decision to extract a utility function into a shared module, arguing that premature abstraction is worse than duplication. You believe the abstraction is justified because the logic appears in three places and is likely to appear in more. Write a respectful, evidence-based response to the reviewer that acknowledges their general principle, explains the specific reasons your case differs, and proposes a concrete path forward. The tone should be collegial but firm.", + "Explain the concept of recursion in programming to a student who has written simple loops but never recursive functions. Begin with an intuitive example unrelated to programming, then introduce the idea of a function calling itself, then walk through a concrete code example (use a small one, like computing a factorial or reversing a string). Address the common confusion about base cases and why missing them causes infinite recursion. End with one practical piece of advice about when recursion is the right tool versus when a loop is simpler." + ] +} diff --git a/Tests/MLXLMTests/Resources/gemma4-26B-A4B-assistant-config.json b/Tests/MLXLMTests/Resources/gemma4-26B-A4B-assistant-config.json new file mode 100644 index 0000000000..55f70d8ffc --- /dev/null +++ b/Tests/MLXLMTests/Resources/gemma4-26B-A4B-assistant-config.json @@ -0,0 +1,88 @@ +{ + "architectures": [ + "Gemma4AssistantForCausalLM" + ], + "audio_token_id": 258881, + "backbone_hidden_size": 2816, + "boa_token_id": 256000, + "boi_token_id": 255999, + "centroid_intermediate_top_k": 32, + "dtype": "bfloat16", + "eoa_token_id": 258883, + "eoi_token_id": 258882, + "image_token_id": 258880, + "model_type": "gemma4_assistant", + "num_centroids": 2048, + "text_config": { + "_name_or_path": "", + "architectures": null, + "attention_bias": false, + "attention_dropout": 0.0, + "attention_k_eq_v": true, + "bos_token_id": 2, + "chunk_size_feed_forward": 0, + "dtype": "bfloat16", + "enable_moe_block": false, + "eos_token_id": 1, + "final_logit_softcapping": null, + "global_head_dim": 512, + "head_dim": 256, + "hidden_activation": "gelu_pytorch_tanh", + "hidden_size": 1024, + "hidden_size_per_layer_input": 0, + "id2label": { + "0": "LABEL_0", + "1": "LABEL_1" + }, + "initializer_range": 0.02, + "intermediate_size": 8192, + "is_encoder_decoder": false, + "label2id": { + "LABEL_0": 0, + "LABEL_1": 1 + }, + "layer_types": [ + "sliding_attention", + "sliding_attention", + "sliding_attention", + "full_attention" + ], + "max_position_embeddings": 262144, + "model_type": "gemma4_text", + "moe_intermediate_size": null, + "num_attention_heads": 16, + "num_experts": null, + "num_global_key_value_heads": 2, + "num_hidden_layers": 4, + "num_key_value_heads": 8, + "num_kv_shared_layers": 4, + "output_attentions": false, + "output_hidden_states": false, + "pad_token_id": 0, + "problem_type": null, + "return_dict": true, + "rms_norm_eps": 1e-06, + "rope_parameters": { + "full_attention": { + "partial_rotary_factor": 0.25, + "rope_theta": 1000000.0, + "rope_type": "proportional" + }, + "sliding_attention": { + "rope_theta": 10000.0, + "rope_type": "default" + } + }, + "sliding_window": 1024, + "tie_word_embeddings": true, + "top_k_experts": null, + "use_bidirectional_attention": null, + "use_cache": true, + "use_double_wide_mlp": false, + "vocab_size": 262144, + "vocab_size_per_layer_input": 0 + }, + "tie_word_embeddings": true, + "transformers_version": "5.7.0.dev0", + "use_ordered_embeddings": false +} diff --git a/Tests/MLXLMTests/Resources/gemma4-E4B-assistant-config.json b/Tests/MLXLMTests/Resources/gemma4-E4B-assistant-config.json new file mode 100644 index 0000000000..69e68e606c --- /dev/null +++ b/Tests/MLXLMTests/Resources/gemma4-E4B-assistant-config.json @@ -0,0 +1,88 @@ +{ + "architectures": [ + "Gemma4AssistantForCausalLM" + ], + "audio_token_id": 258881, + "backbone_hidden_size": 2560, + "boa_token_id": 256000, + "boi_token_id": 255999, + "centroid_intermediate_top_k": 32, + "dtype": "bfloat16", + "eoa_token_id": 258883, + "eoi_token_id": 258882, + "image_token_id": 258880, + "model_type": "gemma4_assistant", + "num_centroids": 2048, + "text_config": { + "_name_or_path": "", + "architectures": null, + "attention_bias": false, + "attention_dropout": 0.0, + "attention_k_eq_v": false, + "bos_token_id": 2, + "chunk_size_feed_forward": 0, + "dtype": "bfloat16", + "enable_moe_block": false, + "eos_token_id": 1, + "final_logit_softcapping": null, + "global_head_dim": 512, + "head_dim": 256, + "hidden_activation": "gelu_pytorch_tanh", + "hidden_size": 256, + "hidden_size_per_layer_input": 0, + "id2label": { + "0": "LABEL_0", + "1": "LABEL_1" + }, + "initializer_range": 0.02, + "intermediate_size": 2048, + "is_encoder_decoder": false, + "label2id": { + "LABEL_0": 0, + "LABEL_1": 1 + }, + "layer_types": [ + "sliding_attention", + "sliding_attention", + "sliding_attention", + "full_attention" + ], + "max_position_embeddings": 131072, + "model_type": "gemma4_text", + "moe_intermediate_size": null, + "num_attention_heads": 4, + "num_experts": null, + "num_global_key_value_heads": null, + "num_hidden_layers": 4, + "num_key_value_heads": 2, + "num_kv_shared_layers": 4, + "output_attentions": false, + "output_hidden_states": false, + "pad_token_id": 0, + "problem_type": null, + "return_dict": true, + "rms_norm_eps": 1e-06, + "rope_parameters": { + "full_attention": { + "partial_rotary_factor": 0.25, + "rope_theta": 1000000.0, + "rope_type": "proportional" + }, + "sliding_attention": { + "rope_theta": 10000.0, + "rope_type": "default" + } + }, + "sliding_window": 512, + "tie_word_embeddings": true, + "top_k_experts": null, + "use_bidirectional_attention": null, + "use_cache": true, + "use_double_wide_mlp": false, + "vocab_size": 262144, + "vocab_size_per_layer_input": 0 + }, + "tie_word_embeddings": true, + "transformers_version": "5.7.0.dev0", + "use_ordered_embeddings": true +} diff --git a/Tests/MLXLMTests/Resources/mtp-oracle/gemma4-e2b-block3-max64.json b/Tests/MLXLMTests/Resources/mtp-oracle/gemma4-e2b-block3-max64.json new file mode 100644 index 0000000000..52fbb47c6d --- /dev/null +++ b/Tests/MLXLMTests/Resources/mtp-oracle/gemma4-e2b-block3-max64.json @@ -0,0 +1,3714 @@ +{ + "config": { + "target": "gemma-4-e2b-it-bf16", + "drafter": "gemma-4-E2B-it-assistant-bf16", + "block_size": 3, + "max_tokens": 64, + "temperature": 0.0, + "mlx_vlm_commit": "244f4bb5a3339b180da3d2b276a4bdfcf7670f9f" + }, + "baseline": [ + { + "id": "short_0", + "prompt": "What is the capital of France?", + "tokens": [ + 818, + 5279, + 529, + 7001, + 563, + 5213, + 50429, + 84750, + 106, + 106, + 106, + 106, + 1, + 106, + 1, + 106, + 1, + 1, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106 + ], + "text": "The capital of France is **Paris**.", + "wall_seconds": 3.338364839553833 + }, + { + "id": "short_1", + "prompt": "Name three primary colors.", + "tokens": [ + 818, + 1806, + 5905, + 7913, + 659, + 5213, + 1192, + 236764, + 7070, + 236764, + 532, + 3730, + 84750, + 106, + 106, + 106, + 106, + 106, + 1, + 106, + 1, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106 + ], + "text": "The three primary colors are **red, yellow, and blue**.", + "wall_seconds": 2.6727731227874756 + }, + { + "id": "short_2", + "prompt": "What is 7 times 8?", + "tokens": [ + 236832, + 2782, + 236743, + 236828, + 563, + 5213, + 236810, + 236825, + 84750, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 1, + 106, + 1, + 106, + 1, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106 + ], + "text": "7 times 8 is **56**.", + "wall_seconds": 2.673388957977295 + }, + { + "id": "short_3", + "prompt": "Who wrote Hamlet?", + "tokens": [ + 1018, + 34848, + 36951, + 1018, + 7971, + 808, + 201313, + 22429, + 106, + 106, + 106, + 106, + 106, + 1, + 106, + 1, + 106, + 1, + 106, + 1, + 106, + 1, + 106, + 1, + 106, + 1, + 106, + 1, + 106, + 1, + 106, + 106, + 106, + 1, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106 + ], + "text": "**William Shakespeare** wrote *Hamlet*.", + "wall_seconds": 2.601807117462158 + }, + { + "id": "short_4", + "prompt": "What planet do we live on?", + "tokens": [ + 1882, + 3892, + 580, + 506, + 13401, + 5213, + 52858, + 84750, + 106, + 106, + 106, + 106, + 106, + 1, + 106, + 1, + 106, + 1, + 106, + 1, + 106, + 1, + 106, + 1, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106 + ], + "text": "We live on the planet **Earth**.", + "wall_seconds": 2.5710196495056152 + }, + { + "id": "medium_0", + "prompt": "Explain the difference between a list and a tuple in Python, giving one concrete example of when you would use each.", + "tokens": [ + 818, + 11001, + 4954, + 1534, + 496, + 5213, + 2234, + 1018, + 532, + 496, + 5213, + 40505, + 1018, + 528, + 17856, + 12828, + 528, + 910, + 5213, + 10181, + 2109, + 84750, + 108, + 8291, + 236789, + 236751, + 496, + 9813, + 25890, + 236787, + 108, + 7243, + 108, + 1408, + 236743, + 236770, + 236761, + 4361, + 77891, + 1005, + 236782, + 2234, + 90940, + 108, + 236776, + 1694, + 563, + 614, + 5213, + 42357, + 125546, + 5213, + 54887, + 1018, + 5249, + 529, + 4852, + 236761, + 108, + 236829, + 5213, + 92489, + 53121, + 669 + ], + "text": "The fundamental difference between a **list** and a **tuple** in Python lies in their **mutability**.\n\nHere's a detailed breakdown:\n\n---\n\n## 1. List ($\\text{list}$)\n\nA list is an **ordered**, **mutable** collection of items.\n\n* **Ordered:** The", + "wall_seconds": 2.5444586277008057 + }, + { + "id": "medium_1", + "prompt": "Write a short paragraph describing the water cycle, including evaporation, condensation, and precipitation.", + "tokens": [ + 818, + 1813, + 8881, + 563, + 496, + 8906, + 1657, + 600, + 15517, + 1217, + 1813, + 12489, + 580, + 236764, + 2787, + 236764, + 532, + 3426, + 506, + 3761, + 529, + 506, + 10824, + 236761, + 1030, + 12502, + 607, + 5213, + 2743, + 158743, + 125546, + 1298, + 506, + 3768, + 236789, + 236751, + 2778, + 62847, + 872, + 1813, + 528, + 59950, + 236764, + 32461, + 236764, + 532, + 25971, + 236764, + 13805, + 625, + 1131, + 21910, + 600, + 33358, + 1131, + 506, + 11661, + 236761, + 1773, + 672, + 1813, + 21910, + 227689, + 236764 + ], + "text": "The water cycle is a continuous process that describes how water moves on, above, and below the surface of the Earth. It begins with **evaporation**, where the sun's energy heats up water in oceans, lakes, and rivers, turning it into vapor that rises into the atmosphere. As this water vapor ascends,", + "wall_seconds": 2.573385000228882 + }, + { + "id": "medium_2", + "prompt": "Describe the main events of the Battle of Hastings in 1066 in three or four sentences.", + "tokens": [ + 2791, + 6198, + 236743, + 236770, + 236812, + 236764, + 236743, + 236770, + 236771, + 236825, + 236825, + 236764, + 506, + 37083, + 236772, + 991, + 14093, + 529, + 8966, + 529, + 114662, + 78752, + 7591, + 236764, + 5830, + 531, + 496, + 52297, + 10041, + 3541, + 89507, + 236761, + 669, + 5422, + 8290, + 236764, + 5378, + 684, + 6065, + 48249, + 3803, + 236765, + 14247, + 236764, + 25876, + 103966, + 840, + 964, + 15334, + 46002, + 684, + 506, + 37083, + 81686, + 532, + 4667, + 616, + 236761, + 6065, + 48249, + 691, + 10500, + 1913, + 506 + ], + "text": "On October 14, 1066, the Norman-led army of William of Normandy invaded England, leading to a decisive battle near Hastings. The English forces, led by King Harold Godwinson, fought fiercely but were ultimately overwhelmed by the Norman cavalry and archers. King Harold was killed during the", + "wall_seconds": 2.6178600788116455 + }, + { + "id": "medium_3", + "prompt": "Outline the key principles of object-oriented programming, naming each principle and giving a one-sentence description.", + "tokens": [ + 8291, + 659, + 506, + 2307, + 12466, + 529, + 8196, + 236772, + 38327, + 524, + 51062, + 568, + 198538, + 779, + 3008, + 607, + 496, + 886, + 236772, + 54554, + 6492, + 573, + 1546, + 236787, + 108, + 236770, + 236761, + 5213, + 14893, + 2786, + 2294, + 53121, + 1174, + 11441, + 49891, + 1262, + 568, + 30374, + 236768, + 532, + 506, + 4615, + 568, + 30693, + 236768, + 600, + 12833, + 580, + 600, + 1262, + 1131, + 496, + 3161, + 4360, + 568, + 508, + 2495, + 779, + 33495, + 506, + 6145, + 8688, + 4889, + 699 + ], + "text": "Here are the key principles of Object-Oriented Programming (OOP), along with a one-sentence description for each:\n\n1. **Encapsulation:** This principle bundles data (attributes) and the methods (functions) that operate on that data into a single unit (an object), hiding the internal implementation details from", + "wall_seconds": 2.5655500888824463 + }, + { + "id": "medium_4", + "prompt": "Explain photosynthesis at a level suitable for a high-school biology student, mentioning the reactants and products.", + "tokens": [ + 1408, + 37256, + 30445, + 236787, + 38039, + 522, + 8586, + 14935, + 146430, + 108, + 49660, + 30445, + 563, + 886, + 529, + 506, + 1346, + 11001, + 532, + 12763, + 6585, + 580, + 10824, + 236761, + 799, + 3606, + 3755, + 236764, + 625, + 563, + 506, + 5213, + 6449, + 684, + 837, + 3826, + 6485, + 236764, + 56758, + 236764, + 532, + 1070, + 15127, + 7352, + 2214, + 2778, + 236764, + 4781, + 699, + 506, + 3768, + 236764, + 1131, + 7395, + 2778, + 528, + 506, + 1183, + 529, + 22422, + 568, + 89325, + 769, + 1018 + ], + "text": "## Photosynthesis: Fueling Life Through Sunlight\n\nPhotosynthesis is one of the most fundamental and vital processes on Earth. In simple terms, it is the **process by which green plants, algae, and some bacteria convert light energy, usually from the sun, into chemical energy in the form of glucose (sugar).**", + "wall_seconds": 2.5605549812316895 + }, + { + "id": "medium_5", + "prompt": "Describe the general structure of a DNA molecule, including the role of the four nucleotide bases.", + "tokens": [ + 1408, + 669, + 5884, + 23718, + 529, + 496, + 10139, + 227230, + 108, + 3321, + 9700, + 1073, + 62128, + 525, + 4920, + 77891, + 1005, + 236782, + 29982, + 90940, + 563, + 506, + 11001, + 19544, + 529, + 222272, + 528, + 1346, + 4882, + 29025, + 236761, + 9567, + 3904, + 563, + 496, + 19374, + 2591, + 529, + 5213, + 7902, + 236772, + 156692, + 1018, + 18271, + 236764, + 837, + 5862, + 573, + 506, + 8143, + 6310, + 236764, + 35401, + 236764, + 532, + 5619, + 529, + 14707, + 1938, + 236761, + 108, + 8291, + 563, + 496 + ], + "text": "## The General Structure of a DNA Molecule\n\nDeoxyribonucleic acid ($\\text{DNA}$) is the fundamental molecule of heredity in most living organisms. Its structure is a remarkable example of **double-helix** geometry, which allows for the efficient storage, replication, and expression of genetic information.\n\nHere is a", + "wall_seconds": 2.5775160789489746 + }, + { + "id": "medium_6", + "prompt": "Summarize the plot of Romeo and Juliet in five or six sentences, without spoilers for the final act.", + "tokens": [ + 231194, + 532, + 93560, + 659, + 1156, + 3184, + 31881, + 699, + 1127, + 51251, + 7965, + 528, + 101689, + 236761, + 18565, + 506, + 18487, + 54584, + 1534, + 910, + 7965, + 236764, + 75699, + 532, + 93560, + 3798, + 19297, + 528, + 2765, + 532, + 63787, + 36542, + 236761, + 9963, + 25249, + 30875, + 563, + 6077, + 15381, + 684, + 126692, + 1013, + 532, + 506, + 13588, + 92278, + 600, + 79615, + 1091, + 236761, + 562, + 3605, + 529, + 44040, + 4749, + 122293, + 236764, + 5830, + 531, + 38412, + 8073, + 3523, + 684, + 506 + ], + "text": "Romeo and Juliet are two young lovers from feuding families in Verona. Despite the intense hatred between their families, Romeo and Juliet fall deeply in love and secretly marry. Their passionate romance is quickly complicated by misunderstandings and the dangerous feud that surrounds them. A series of tragic events unfolds, leading to desperate measures taken by the", + "wall_seconds": 2.601814031600952 + }, + { + "id": "medium_7", + "prompt": "Explain what causes seasons on Earth, referencing the axial tilt and orbit.", + "tokens": [ + 1869, + 5733, + 580, + 10824, + 659, + 13336, + 7321, + 684, + 506, + 5213, + 185500, + 529, + 506, + 10824, + 236789, + 236751, + 9485, + 1018, + 6658, + 531, + 1061, + 5213, + 50657, + 2101, + 506, + 7718, + 84750, + 108, + 8291, + 563, + 496, + 9813, + 25890, + 529, + 506, + 1657, + 236787, + 108, + 7243, + 108, + 10354, + 236743, + 236770, + 236761, + 669, + 10824, + 236789, + 236751, + 199161, + 165819, + 108, + 818, + 1346, + 13832, + 5415, + 563, + 600, + 506, + 10824, + 236789, + 236751, + 9485, + 529, + 13035 + ], + "text": "Seasons on Earth are primarily caused by the **tilt of the Earth's axis** relative to its **orbit around the Sun**.\n\nHere is a detailed breakdown of the process:\n\n---\n\n### 1. The Earth's Axial Tilt\n\nThe most crucial factor is that the Earth's axis of rotation", + "wall_seconds": 2.6513049602508545 + }, + { + "id": "medium_8", + "prompt": "Describe the basic function of the human circulatory system and name its three major components.", + "tokens": [ + 1408, + 18711, + 12939, + 529, + 506, + 11096, + 11366, + 24727, + 1804, + 108, + 818, + 6079, + 1292, + 529, + 506, + 3246, + 111967, + 1458, + 568, + 23681, + 3224, + 618, + 506, + 36432, + 1458, + 236768, + 563, + 531, + 5213, + 49494, + 5250, + 17924, + 5459, + 506, + 2742, + 532, + 6349, + 8321, + 3211, + 99382, + 108, + 2094, + 1458, + 12316, + 1133, + 496, + 3996, + 14227, + 3707, + 236764, + 17096, + 600, + 236787, + 108, + 236770, + 236761, + 5213, + 170701, + 532, + 16180, + 97523, + 659, + 191852, + 53121 + ], + "text": "## Basic Function of the Human Circulatory System\n\nThe basic function of the human circulatory system (also known as the cardiovascular system) is to **transport essential substances throughout the body and remove waste products.**\n\nThis system acts like a complex transportation network, ensuring that:\n\n1. **Oxygen and Nutrients are Delivered:**", + "wall_seconds": 2.55558705329895 + }, + { + "id": "medium_9", + "prompt": "Compare and contrast renewable and non-renewable energy sources, giving two examples of each.", + "tokens": [ + 1408, + 91468, + 532, + 97441, + 28728, + 100756, + 532, + 10645, + 236772, + 115489, + 742, + 9904, + 49174, + 108, + 115489, + 742, + 532, + 1908, + 236772, + 197054, + 2778, + 7021, + 2754, + 51935, + 1607, + 4861, + 692, + 3011, + 506, + 2778, + 4354, + 531, + 2066, + 1023, + 6176, + 236764, + 13390, + 236764, + 532, + 12308, + 236761, + 669, + 2307, + 8798, + 7089, + 528, + 910, + 5213, + 56905, + 236764, + 3136, + 529, + 155300, + 236764, + 8646, + 4100, + 236764, + 532, + 24488, + 99382, + 108, + 8291, + 563, + 496 + ], + "text": "## Comparing and Contrasting Renewable and Non-Renewable Energy Sources\n\nRenewable and non-renewable energy sources represent fundamentally different ways we obtain the energy needed to power our lives, industries, and infrastructure. The key differences lie in their **availability, rate of replenishment, environmental impact, and sustainability.**\n\nHere is a", + "wall_seconds": 2.5981099605560303 + }, + { + "id": "long_0", + "prompt": "Consider the following scenario: a software team is trying to decide between using a monolithic architecture and a microservices architecture for their new e-commerce platform. The team has ten engineers, expects to handle around ten thousand transactions per day initially, and anticipates scaling to one hundred thousand transactions per day within two years. Some team members argue that a monolith is simpler to deploy and debug, while others insist that microservices are the modern approach and will make scaling easier. Provide a thoughtful analysis of the trade-offs, discussing at least four specific technical or organizational factors that should influence this decision. Conclude with a concrete recommendation.", + "tokens": [ + 1408, + 13768, + 529, + 4325, + 76941, + 7728, + 236761, + 15103, + 15897, + 36468, + 573, + 614, + 645, + 236772, + 25351, + 25396, + 108, + 818, + 4893, + 1534, + 496, + 145218, + 532, + 496, + 4719, + 15897, + 13217, + 563, + 496, + 91798, + 886, + 600, + 795, + 8792, + 4100, + 506, + 2913, + 4249, + 236764, + 17934, + 16783, + 236764, + 532, + 1440, + 236772, + 6061, + 93711, + 529, + 506, + 861, + 545, + 236772, + 25351, + 5058, + 236761, + 17770, + 506, + 2434, + 2425, + 568, + 1571, + 22072, + 779, + 4068 + ], + "text": "## Analysis of Monolithic vs. Microservices Architecture for an E-commerce Platform\n\nThe decision between a monolithic and a microservices architecture is a foundational one that will significantly impact the development speed, operational complexity, and long-term scalability of the new e-commerce platform. Given the team size (ten engineers), initial", + "wall_seconds": 2.837601900100708 + }, + { + "id": "long_1", + "prompt": "Imagine you are teaching an introductory class on machine learning. Your students have programming experience but no background in statistics. Write the first few paragraphs of your lecture, introducing the concept of supervised learning. Your explanation should motivate why supervised learning is useful, describe the general structure of a training dataset (features and labels), give an intuitive example of a simple prediction task, and briefly mention how the model's performance can be evaluated. Aim for a tone that is clear and engaging but technically correct.", + "tokens": [ + 1408, + 23051, + 531, + 6562, + 32148, + 19180, + 108, + 236775, + 16651, + 4677, + 236888, + 564, + 236858, + 236757, + 2126, + 9775, + 531, + 1502, + 672, + 9338, + 1131, + 15313, + 19180, + 607, + 611, + 236761, + 5612, + 611, + 784, + 735, + 496, + 5139, + 14929, + 1695, + 236764, + 611, + 3016, + 735, + 506, + 6436, + 531, + 2016, + 4681, + 236761, + 10950, + 236764, + 692, + 236858, + 500, + 1771, + 531, + 2910, + 1003, + 808, + 7843, + 236829, + 692, + 3786, + 1724, + 4681, + 531, + 3449, + 699, + 1262 + ], + "text": "## Introduction to Supervised Learning\n\n\"Welcome everyone! I\u2019m really excited to start this journey into Machine Learning with you. Since you all have a solid programming background, you already have the tools to build models. Today, we\u2019re going to talk about *how* we teach those models to learn from data", + "wall_seconds": 2.614910840988159 + }, + { + "id": "long_2", + "prompt": "You are writing documentation for a new distributed key-value store. The system provides strong consistency, is partition-tolerant, and trades availability during network partitions. Explain the CAP theorem to a reader who has heard the term but never really understood it. Then, using the specific design choices of this key-value store as a running example, walk the reader through what would happen during a network partition: which operations succeed, which fail, and why. Use concrete examples rather than abstract descriptions, and avoid mathematical formalism.", + "tokens": [ + 1408, + 40411, + 506, + 31567, + 11318, + 528, + 5137, + 9533, + 236772, + 3135, + 13516, + 108, + 818, + 31567, + 14720, + 563, + 496, + 11001, + 3495, + 528, + 10861, + 3797, + 236761, + 1030, + 5022, + 600, + 496, + 10861, + 1262, + 4762, + 740, + 1186, + 15246, + 5213, + 13498, + 1018, + 529, + 506, + 2269, + 1806, + 5082, + 657, + 506, + 1638, + 990, + 236787, + 108, + 236770, + 236761, + 5213, + 223196, + 568, + 236780, + 1473, + 1018, + 7685, + 1676, + 21500, + 506, + 1346, + 4803, + 4903, + 653, + 614 + ], + "text": "## Understanding the CAP Theorem in Our Key-Value Store\n\nThe CAP theorem is a fundamental concept in distributed systems. It states that a distributed data store can only guarantee **two** of the following three properties at the same time:\n\n1. **Consistency (C):** Every read receives the most recent write or an", + "wall_seconds": 2.633779764175415 + }, + { + "id": "long_3", + "prompt": "A senior engineer at your company has written a code review that you disagree with. The review criticizes your decision to extract a utility function into a shared module, arguing that premature abstraction is worse than duplication. You believe the abstraction is justified because the logic appears in three places and is likely to appear in more. Write a respectful, evidence-based response to the reviewer that acknowledges their general principle, explains the specific reasons your case differs, and proposes a concrete path forward. The tone should be collegial but firm.", + "tokens": [ + 8291, + 659, + 496, + 2321, + 3835, + 236764, + 10167, + 580, + 506, + 4453, + 133378, + 611, + 1461, + 531, + 17308, + 236761, + 108, + 1408, + 19993, + 236743, + 236770, + 236787, + 140770, + 532, + 5774, + 236772, + 154902, + 568, + 75652, + 236768, + 108, + 2094, + 5086, + 563, + 6112, + 5707, + 236764, + 121019, + 506, + 65991, + 236789, + 236751, + 4561, + 236764, + 840, + 31077, + 15060, + 822, + 47107, + 2721, + 580, + 23782, + 3402, + 9626, + 236761, + 108, + 236813, + 18428, + 870, + 30852, + 497, + 236789, + 236751, + 7343 + ], + "text": "Here are a few options, depending on the exact nuance you want to convey.\n\n## Option 1: Balanced and Data-Driven (Recommended)\n\nThis option is highly professional, validates the reviewer's concern, but firmly presents your justification based on anticipated future maintenance.\n\n> Hi [Reviewer's Name", + "wall_seconds": 2.692835807800293 + }, + { + "id": "long_4", + "prompt": "Explain the concept of recursion in programming to a student who has written simple loops but never recursive functions. Begin with an intuitive example unrelated to programming, then introduce the idea of a function calling itself, then walk through a concrete code example (use a small one, like computing a factorial or reversing a string). Address the common confusion about base cases and why missing them causes infinite recursion. End with one practical piece of advice about when recursion is the right tool versus when a loop is simpler.", + "tokens": [ + 6372, + 236789, + 236751, + 496, + 1822, + 1977, + 531, + 577, + 236888, + 148362, + 659, + 11001, + 236764, + 532, + 6611, + 74175, + 563, + 506, + 2148, + 2563, + 2918, + 528, + 6972, + 1003, + 1217, + 531, + 8974, + 3996, + 4078, + 528, + 14929, + 236761, + 108, + 6481, + 236789, + 236751, + 2541, + 1679, + 74175, + 528, + 496, + 1595, + 600, + 3590, + 5113, + 236761, + 108, + 7243, + 108, + 1408, + 4040, + 236743, + 236770, + 236787, + 669, + 163850, + 2407, + 64679, + 568, + 818, + 9203, + 47436, + 522, + 153225 + ], + "text": "That's a great place to be! Loops are fundamental, and understanding recursion is the next big step in thinking about how to solve complex problems in programming.\n\nLet's break down recursion in a way that makes sense.\n\n---\n\n## Part 1: The Intuitive Idea (The Russian Nesting Dolls", + "wall_seconds": 2.6231069564819336 + } + ], + "mtp": [ + { + "id": "short_0", + "prompt": "What is the capital of France?", + "tokens": [ + 818, + 5279, + 529, + 7001, + 563, + 5213, + 50429, + 84750, + 106, + 106, + 106, + 106, + 1, + 106, + 1, + 106, + 1, + 1, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106 + ], + "text": "The capital of France is **Paris**.", + "wall_seconds": 1.622818946838379, + "accept_lens": [ + 2, + 2, + 2, + 2, + 1, + 0, + 0, + 0, + 0, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2 + ], + "matches_baseline": true + }, + { + "id": "short_1", + "prompt": "Name three primary colors.", + "tokens": [ + 818, + 1806, + 5905, + 7913, + 659, + 5213, + 1192, + 236764, + 7070, + 236764, + 532, + 3730, + 84750, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106 + ], + "text": "The three primary colors are **red, yellow, and blue**.", + "wall_seconds": 1.6055090427398682, + "accept_lens": [ + 2, + 1, + 0, + 0, + 0, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 1 + ], + "matches_baseline": false + }, + { + "id": "short_2", + "prompt": "What is 7 times 8?", + "tokens": [ + 236832, + 2782, + 236743, + 236828, + 563, + 5213, + 236810, + 236825, + 84750, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 1, + 106, + 1, + 106, + 1, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106 + ], + "text": "7 times 8 is **56**.", + "wall_seconds": 1.5348632335662842, + "accept_lens": [ + 2, + 2, + 0, + 2, + 2, + 2, + 2, + 1, + 1, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 1 + ], + "matches_baseline": true + }, + { + "id": "short_3", + "prompt": "Who wrote Hamlet?", + "tokens": [ + 1018, + 34848, + 36951, + 1018, + 7971, + 808, + 201313, + 22429, + 106, + 106, + 106, + 106, + 106, + 1, + 106, + 1, + 106, + 1, + 106, + 1, + 106, + 1, + 106, + 1, + 106, + 1, + 106, + 1, + 106, + 1, + 106, + 106, + 106, + 106, + 1, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106 + ], + "text": "**William Shakespeare** wrote *Hamlet*.", + "wall_seconds": 2.0188169479370117, + "accept_lens": [ + 0, + 2, + 0, + 1, + 2, + 2, + 0, + 0, + 0, + 0, + 1, + 1, + 1, + 1, + 1, + 1, + 2, + 1, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2 + ], + "matches_baseline": false + }, + { + "id": "short_4", + "prompt": "What planet do we live on?", + "tokens": [ + 1882, + 3892, + 580, + 506, + 13401, + 5213, + 52858, + 84750, + 106, + 106, + 106, + 106, + 106, + 1, + 106, + 1, + 106, + 1, + 106, + 1, + 106, + 1, + 106, + 1, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106, + 106 + ], + "text": "We live on the planet **Earth**.", + "wall_seconds": 2.1311917304992676, + "accept_lens": [ + 2, + 1, + 0, + 0, + 0, + 2, + 1, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 1 + ], + "matches_baseline": true + }, + { + "id": "medium_0", + "prompt": "Explain the difference between a list and a tuple in Python, giving one concrete example of when you would use each.", + "tokens": [ + 818, + 11001, + 4954, + 1534, + 496, + 5213, + 2234, + 1018, + 532, + 496, + 5213, + 40505, + 1018, + 528, + 17856, + 12828, + 528, + 910, + 5213, + 10181, + 2109, + 84750, + 108, + 8291, + 236789, + 236751, + 496, + 9813, + 25890, + 236787, + 108, + 7243, + 108, + 1408, + 236743, + 236770, + 236761, + 4361, + 77891, + 1005, + 236782, + 2234, + 90940, + 108, + 236776, + 1694, + 563, + 614, + 5213, + 42357, + 125546, + 5213, + 54887, + 1018, + 5249, + 529, + 4852, + 236761, + 108, + 236829, + 5213, + 92489, + 53121, + 669 + ], + "text": "The fundamental difference between a **list** and a **tuple** in Python lies in their **mutability**.\n\nHere's a detailed breakdown:\n\n---\n\n## 1. List ($\\text{list}$)\n\nA list is an **ordered**, **mutable** collection of items.\n\n* **Ordered:** The", + "wall_seconds": 2.500460147857666, + "accept_lens": [ + 0, + 2, + 0, + 0, + 2, + 2, + 0, + 1, + 2, + 0, + 0, + 0, + 2, + 1, + 0, + 0, + 2, + 0, + 0, + 0, + 2, + 0, + 2, + 2, + 0, + 1, + 1, + 0, + 2, + 0, + 0, + 0, + 2, + 0, + 0, + 1 + ], + "matches_baseline": true + }, + { + "id": "medium_1", + "prompt": "Write a short paragraph describing the water cycle, including evaporation, condensation, and precipitation.", + "tokens": [ + 818, + 1813, + 8881, + 563, + 496, + 8906, + 1657, + 600, + 15517, + 1217, + 1813, + 12489, + 580, + 236764, + 2787, + 236764, + 532, + 3426, + 506, + 3761, + 529, + 506, + 10824, + 236761, + 1030, + 12502, + 607, + 5213, + 2743, + 158743, + 125546, + 1298, + 506, + 3768, + 236789, + 236751, + 2778, + 62847, + 872, + 1813, + 528, + 59950, + 236764, + 32461, + 236764, + 532, + 25971, + 236764, + 13805, + 625, + 1131, + 21910, + 600, + 33358, + 1131, + 506, + 11661, + 236761, + 1773, + 672, + 1813, + 21910, + 227689, + 236764 + ], + "text": "The water cycle is a continuous process that describes how water moves on, above, and below the surface of the Earth. It begins with **evaporation**, where the sun's energy heats up water in oceans, lakes, and rivers, turning it into vapor that rises into the atmosphere. As this water vapor ascends,", + "wall_seconds": 3.378788709640503, + "accept_lens": [ + 2, + 1, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 1, + 0, + 0, + 1, + 0, + 0, + 0, + 1, + 2, + 0, + 0, + 0, + 0, + 1, + 0, + 1, + 0, + 0, + 1, + 1, + 0, + 1, + 0, + 0, + 0, + 0, + 0, + 0, + 1, + 1, + 0, + 1, + 0, + 1 + ], + "matches_baseline": true + }, + { + "id": "medium_2", + "prompt": "Describe the main events of the Battle of Hastings in 1066 in three or four sentences.", + "tokens": [ + 2791, + 6198, + 236743, + 236770, + 236812, + 236764, + 236743, + 236770, + 236771, + 236825, + 236825, + 236764, + 506, + 37083, + 236772, + 991, + 14093, + 529, + 8966, + 529, + 114662, + 78752, + 7591, + 236764, + 5830, + 531, + 496, + 52297, + 10041, + 3541, + 89507, + 236761, + 669, + 5422, + 8290, + 236764, + 5378, + 684, + 6065, + 48249, + 3803, + 236765, + 14247, + 236764, + 25876, + 103966, + 840, + 964, + 15334, + 46002, + 684, + 506, + 37083, + 81686, + 532, + 4667, + 616, + 236761, + 6065, + 48249, + 691, + 10500, + 1913, + 506 + ], + "text": "On October 14, 1066, the Norman-led army of William of Normandy invaded England, leading to a decisive battle near Hastings. The English forces, led by King Harold Godwinson, fought fiercely but were ultimately overwhelmed by the Norman cavalry and archers. King Harold was killed during the", + "wall_seconds": 3.173971176147461, + "accept_lens": [ + 0, + 2, + 0, + 0, + 2, + 2, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 1, + 1, + 0, + 0, + 0, + 0, + 2, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 0, + 0, + 2, + 0, + 1, + 0, + 1, + 0, + 0, + 0, + 0, + 1 + ], + "matches_baseline": true + }, + { + "id": "medium_3", + "prompt": "Outline the key principles of object-oriented programming, naming each principle and giving a one-sentence description.", + "tokens": [ + 8291, + 659, + 506, + 2307, + 12466, + 529, + 8196, + 236772, + 38327, + 524, + 51062, + 568, + 198538, + 779, + 3008, + 607, + 496, + 886, + 236772, + 54554, + 6492, + 573, + 1546, + 236787, + 108, + 236770, + 236761, + 5213, + 14893, + 2786, + 2294, + 53121, + 1174, + 11441, + 49891, + 1262, + 568, + 30374, + 236768, + 532, + 506, + 4615, + 568, + 30693, + 236768, + 600, + 12833, + 580, + 600, + 1262, + 1131, + 496, + 3161, + 4360, + 568, + 508, + 2495, + 779, + 33495, + 506, + 6145, + 8688, + 4889, + 699 + ], + "text": "Here are the key principles of Object-Oriented Programming (OOP), along with a one-sentence description for each:\n\n1. **Encapsulation:** This principle bundles data (attributes) and the methods (functions) that operate on that data into a single unit (an object), hiding the internal implementation details from", + "wall_seconds": 2.361295223236084, + "accept_lens": [ + 2, + 2, + 2, + 0, + 2, + 0, + 1, + 2, + 1, + 1, + 1, + 0, + 0, + 0, + 2, + 0, + 1, + 0, + 0, + 0, + 2, + 0, + 1, + 2, + 1, + 0, + 0, + 2, + 0, + 0, + 1, + 0, + 0, + 0, + 0, + 1 + ], + "matches_baseline": true + }, + { + "id": "medium_4", + "prompt": "Explain photosynthesis at a level suitable for a high-school biology student, mentioning the reactants and products.", + "tokens": [ + 1408, + 37256, + 30445, + 236787, + 38039, + 522, + 8586, + 14935, + 146430, + 108, + 49660, + 30445, + 563, + 886, + 529, + 506, + 1346, + 11001, + 532, + 12763, + 6585, + 580, + 10824, + 236761, + 799, + 3606, + 3755, + 236764, + 625, + 563, + 506, + 5213, + 6449, + 684, + 837, + 3826, + 6485, + 236764, + 56758, + 236764, + 532, + 1070, + 15127, + 7352, + 2214, + 2778, + 236764, + 4781, + 699, + 506, + 3768, + 236764, + 1131, + 7395, + 2778, + 528, + 506, + 1183, + 529, + 22422, + 568, + 89325, + 769, + 1018 + ], + "text": "## Photosynthesis: Fueling Life Through Sunlight\n\nPhotosynthesis is one of the most fundamental and vital processes on Earth. In simple terms, it is the **process by which green plants, algae, and some bacteria convert light energy, usually from the sun, into chemical energy in the form of glucose (sugar).**", + "wall_seconds": 3.312408685684204, + "accept_lens": [ + 0, + 2, + 0, + 0, + 0, + 0, + 0, + 0, + 2, + 0, + 1, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 2, + 1, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 2, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 2, + 0, + 0, + 1, + 1, + 0, + 0, + 0, + 0, + 0, + 0 + ], + "matches_baseline": true + }, + { + "id": "medium_5", + "prompt": "Describe the general structure of a DNA molecule, including the role of the four nucleotide bases.", + "tokens": [ + 1408, + 669, + 5884, + 23718, + 529, + 496, + 10139, + 227230, + 108, + 3321, + 9700, + 1073, + 62128, + 525, + 4920, + 77891, + 1005, + 236782, + 29982, + 90940, + 563, + 506, + 11001, + 19544, + 529, + 222272, + 528, + 1346, + 4882, + 29025, + 236761, + 9567, + 3904, + 563, + 85867, + 4970, + 618, + 496, + 5213, + 7902, + 77577, + 125546, + 496, + 43274, + 31840, + 6230, + 236761, + 1174, + 3904, + 563, + 13832, + 1547, + 625, + 5862, + 506, + 14707, + 1938, + 531, + 577, + 11628, + 136064, + 532, + 82835, + 23704 + ], + "text": "## The General Structure of a DNA Molecule\n\nDeoxyribonucleic acid ($\\text{DNA}$) is the fundamental molecule of heredity in most living organisms. Its structure is famously described as a **double helix**, a twisted ladder shape. This structure is crucial because it allows the genetic information to be stored stably and replicated accurately", + "wall_seconds": 2.5875139236450195, + "accept_lens": [ + 2, + 2, + 0, + 1, + 2, + 0, + 0, + 0, + 2, + 0, + 1, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 2, + 1, + 0, + 0, + 2, + 1, + 0, + 0, + 0, + 0, + 0, + 0, + 2, + 0, + 2, + 0, + 2, + 0, + 0, + 0, + 0, + 0 + ], + "matches_baseline": false + }, + { + "id": "medium_6", + "prompt": "Summarize the plot of Romeo and Juliet in five or six sentences, without spoilers for the final act.", + "tokens": [ + 231194, + 532, + 93560, + 659, + 1156, + 3184, + 31881, + 699, + 1127, + 51251, + 7965, + 528, + 101689, + 236761, + 18565, + 506, + 18487, + 54584, + 1534, + 910, + 7965, + 236764, + 75699, + 532, + 93560, + 3798, + 19297, + 528, + 2765, + 532, + 63787, + 36542, + 236761, + 9963, + 25249, + 30875, + 563, + 6077, + 15381, + 684, + 126692, + 1013, + 532, + 506, + 13588, + 92278, + 600, + 79615, + 1091, + 236761, + 562, + 3605, + 529, + 44040, + 4749, + 122293, + 236764, + 5830, + 531, + 38412, + 532, + 186674, + 9886, + 1603 + ], + "text": "Romeo and Juliet are two young lovers from feuding families in Verona. Despite the intense hatred between their families, Romeo and Juliet fall deeply in love and secretly marry. Their passionate romance is quickly complicated by misunderstandings and the dangerous feud that surrounds them. A series of tragic events unfolds, leading to desperate and fateful decisions made", + "wall_seconds": 3.0220391750335693, + "accept_lens": [ + 2, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 1, + 1, + 0, + 0, + 0, + 0, + 1, + 2, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 1, + 0, + 1, + 0, + 2, + 0, + 0, + 0, + 2, + 0, + 1, + 0, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 0 + ], + "matches_baseline": false + }, + { + "id": "medium_7", + "prompt": "Explain what causes seasons on Earth, referencing the axial tilt and orbit.", + "tokens": [ + 1869, + 5733, + 580, + 10824, + 659, + 13336, + 7321, + 684, + 506, + 5213, + 185500, + 529, + 506, + 10824, + 236789, + 236751, + 9485, + 1018, + 6658, + 531, + 1061, + 5213, + 50657, + 2101, + 506, + 7718, + 84750, + 108, + 8291, + 563, + 496, + 9813, + 25890, + 529, + 506, + 1657, + 236787, + 108, + 7243, + 108, + 10354, + 236743, + 236770, + 236761, + 669, + 10824, + 236789, + 236751, + 199161, + 165819, + 108, + 818, + 1346, + 13832, + 5415, + 563, + 600, + 506, + 10824, + 236789, + 236751, + 9485, + 529, + 13035 + ], + "text": "Seasons on Earth are primarily caused by the **tilt of the Earth's axis** relative to its **orbit around the Sun**.\n\nHere is a detailed breakdown of the process:\n\n---\n\n### 1. The Earth's Axial Tilt\n\nThe most crucial factor is that the Earth's axis of rotation", + "wall_seconds": 2.442885160446167, + "accept_lens": [ + 0, + 0, + 2, + 0, + 2, + 0, + 0, + 1, + 2, + 1, + 1, + 0, + 0, + 0, + 1, + 0, + 2, + 1, + 0, + 0, + 1, + 0, + 2, + 2, + 0, + 0, + 2, + 0, + 2, + 0, + 0, + 0, + 1, + 2, + 2, + 0 + ], + "matches_baseline": true + }, + { + "id": "medium_8", + "prompt": "Describe the basic function of the human circulatory system and name its three major components.", + "tokens": [ + 1408, + 18711, + 12939, + 529, + 506, + 11096, + 11366, + 24727, + 1804, + 108, + 818, + 6079, + 1292, + 529, + 506, + 3246, + 111967, + 1458, + 568, + 23681, + 3224, + 618, + 506, + 36432, + 1458, + 236768, + 563, + 531, + 5213, + 49494, + 5250, + 17924, + 5459, + 506, + 2742, + 532, + 6349, + 8321, + 3211, + 99382, + 108, + 2094, + 1458, + 12316, + 1133, + 496, + 3996, + 14227, + 3707, + 236764, + 17096, + 600, + 236787, + 108, + 236770, + 236761, + 5213, + 170701, + 532, + 16180, + 97523, + 659, + 191852, + 53121 + ], + "text": "## Basic Function of the Human Circulatory System\n\nThe basic function of the human circulatory system (also known as the cardiovascular system) is to **transport essential substances throughout the body and remove waste products.**\n\nThis system acts like a complex transportation network, ensuring that:\n\n1. **Oxygen and Nutrients are Delivered:**", + "wall_seconds": 2.882794141769409, + "accept_lens": [ + 0, + 2, + 0, + 2, + 0, + 1, + 2, + 0, + 2, + 0, + 0, + 2, + 2, + 0, + 0, + 0, + 0, + 0, + 0, + 2, + 0, + 0, + 0, + 2, + 1, + 0, + 1, + 0, + 0, + 1, + 1, + 0, + 2, + 0, + 0, + 0, + 0, + 0, + 0, + 1 + ], + "matches_baseline": true + }, + { + "id": "medium_9", + "prompt": "Compare and contrast renewable and non-renewable energy sources, giving two examples of each.", + "tokens": [ + 1408, + 91468, + 532, + 97441, + 28728, + 100756, + 532, + 10645, + 236772, + 115489, + 742, + 9904, + 49174, + 108, + 115489, + 742, + 532, + 1908, + 236772, + 197054, + 2778, + 7021, + 2754, + 51935, + 1607, + 4861, + 692, + 3011, + 506, + 2778, + 4354, + 531, + 2066, + 1023, + 6176, + 236764, + 13390, + 236764, + 532, + 12308, + 236761, + 669, + 2307, + 8798, + 7089, + 528, + 910, + 5213, + 56905, + 236764, + 3136, + 529, + 155300, + 236764, + 8646, + 4100, + 236764, + 532, + 24488, + 99382, + 108, + 8291, + 563, + 496 + ], + "text": "## Comparing and Contrasting Renewable and Non-Renewable Energy Sources\n\nRenewable and non-renewable energy sources represent fundamentally different ways we obtain the energy needed to power our lives, industries, and infrastructure. The key differences lie in their **availability, rate of replenishment, environmental impact, and sustainability.**\n\nHere is a", + "wall_seconds": 2.729619264602661, + "accept_lens": [ + 0, + 1, + 0, + 0, + 0, + 0, + 2, + 2, + 0, + 1, + 2, + 2, + 0, + 1, + 0, + 0, + 0, + 1, + 1, + 0, + 0, + 0, + 0, + 0, + 1, + 1, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 1, + 0, + 2, + 2, + 2 + ], + "matches_baseline": true + }, + { + "id": "long_0", + "prompt": "Consider the following scenario: a software team is trying to decide between using a monolithic architecture and a microservices architecture for their new e-commerce platform. The team has ten engineers, expects to handle around ten thousand transactions per day initially, and anticipates scaling to one hundred thousand transactions per day within two years. Some team members argue that a monolith is simpler to deploy and debug, while others insist that microservices are the modern approach and will make scaling easier. Provide a thoughtful analysis of the trade-offs, discussing at least four specific technical or organizational factors that should influence this decision. Conclude with a concrete recommendation.", + "tokens": [ + 1408, + 13768, + 529, + 4325, + 76941, + 7728, + 236761, + 15103, + 15897, + 36468, + 573, + 614, + 645, + 236772, + 25351, + 25396, + 108, + 818, + 4893, + 1534, + 496, + 145218, + 532, + 496, + 4719, + 15897, + 13217, + 563, + 496, + 91798, + 886, + 600, + 795, + 8792, + 4100, + 506, + 2913, + 9254, + 236764, + 17934, + 16783, + 236764, + 532, + 1440, + 236772, + 6061, + 93711, + 529, + 506, + 861, + 545, + 236772, + 25351, + 5058, + 236761, + 17770, + 506, + 2434, + 2425, + 568, + 1571, + 22072, + 779, + 4068 + ], + "text": "## Analysis of Monolithic vs. Microservices Architecture for an E-commerce Platform\n\nThe decision between a monolithic and a microservices architecture is a foundational one that will significantly impact the development velocity, operational complexity, and long-term scalability of the new e-commerce platform. Given the team size (ten engineers), initial", + "wall_seconds": 2.4689650535583496, + "accept_lens": [ + 2, + 0, + 0, + 2, + 0, + 2, + 2, + 2, + 0, + 2, + 0, + 0, + 2, + 1, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 1, + 0, + 2, + 2, + 0, + 1, + 0, + 2, + 2, + 1, + 0, + 0, + 2 + ], + "matches_baseline": false + }, + { + "id": "long_1", + "prompt": "Imagine you are teaching an introductory class on machine learning. Your students have programming experience but no background in statistics. Write the first few paragraphs of your lecture, introducing the concept of supervised learning. Your explanation should motivate why supervised learning is useful, describe the general structure of a training dataset (features and labels), give an intuitive example of a simple prediction task, and briefly mention how the model's performance can be evaluated. Aim for a tone that is clear and engaging but technically correct.", + "tokens": [ + 1408, + 23051, + 531, + 6562, + 32148, + 19180, + 108, + 236775, + 11947, + 5597, + 236764, + 4677, + 236764, + 532, + 8349, + 531, + 15313, + 19180, + 236888, + 564, + 236858, + 236757, + 2126, + 9775, + 531, + 735, + 611, + 784, + 1590, + 236761, + 5612, + 611, + 784, + 735, + 496, + 5139, + 14929, + 1695, + 236764, + 611, + 3016, + 735, + 506, + 6436, + 531, + 2016, + 4681, + 236761, + 10950, + 236764, + 692, + 236858, + 500, + 1771, + 531, + 2910, + 1003, + 808, + 7843, + 236829, + 692, + 3786, + 1724, + 4681 + ], + "text": "## Introduction to Supervised Learning\n\n\"Good morning, everyone, and welcome to Machine Learning! I\u2019m really excited to have you all here. Since you all have a solid programming background, you already have the tools to build models. Today, we\u2019re going to talk about *how* we teach those models", + "wall_seconds": 2.969041109085083, + "accept_lens": [ + 2, + 2, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 0, + 0, + 1, + 0, + 2, + 0, + 0, + 0, + 0, + 0, + 0, + 1, + 1, + 0, + 0, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 0, + 0, + 1, + 0, + 0, + 2, + 0, + 0, + 0, + 0, + 1, + 0, + 2, + 0, + 0 + ], + "matches_baseline": false + }, + { + "id": "long_2", + "prompt": "You are writing documentation for a new distributed key-value store. The system provides strong consistency, is partition-tolerant, and trades availability during network partitions. Explain the CAP theorem to a reader who has heard the term but never really understood it. Then, using the specific design choices of this key-value store as a running example, walk the reader through what would happen during a network partition: which operations succeed, which fail, and why. Use concrete examples rather than abstract descriptions, and avoid mathematical formalism.", + "tokens": [ + 1408, + 40411, + 506, + 31567, + 11318, + 528, + 5137, + 9533, + 236772, + 3135, + 13516, + 108, + 818, + 31567, + 14720, + 563, + 496, + 11001, + 3495, + 528, + 10861, + 3797, + 236761, + 1030, + 5022, + 600, + 496, + 10861, + 1262, + 4762, + 740, + 1186, + 15246, + 5213, + 13498, + 1018, + 529, + 506, + 2269, + 1806, + 5082, + 657, + 506, + 1638, + 990, + 236787, + 108, + 236770, + 236761, + 5213, + 223196, + 568, + 236780, + 1473, + 1018, + 7685, + 1676, + 21500, + 506, + 1346, + 4803, + 4903, + 653, + 614 + ], + "text": "## Understanding the CAP Theorem in Our Key-Value Store\n\nThe CAP theorem is a fundamental concept in distributed systems. It states that a distributed data store can only guarantee **two** of the following three properties at the same time:\n\n1. **Consistency (C):** Every read receives the most recent write or an", + "wall_seconds": 3.3143210411071777, + "accept_lens": [ + 0, + 2, + 0, + 0, + 2, + 2, + 1, + 0, + 2, + 0, + 0, + 0, + 2, + 1, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 2, + 0, + 0, + 0, + 0, + 1, + 0, + 2, + 1, + 0, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0 + ], + "matches_baseline": true + }, + { + "id": "long_3", + "prompt": "A senior engineer at your company has written a code review that you disagree with. The review criticizes your decision to extract a utility function into a shared module, arguing that premature abstraction is worse than duplication. You believe the abstraction is justified because the logic appears in three places and is likely to appear in more. Write a respectful, evidence-based response to the reviewer that acknowledges their general principle, explains the specific reasons your case differs, and proposes a concrete path forward. The tone should be collegial but firm.", + "tokens": [ + 8291, + 659, + 496, + 2321, + 3835, + 236764, + 10167, + 580, + 506, + 4453, + 133378, + 611, + 1461, + 531, + 17308, + 236761, + 108, + 1408, + 19993, + 236743, + 236770, + 236787, + 140770, + 532, + 5774, + 236772, + 154902, + 568, + 75652, + 236768, + 108, + 2094, + 5086, + 563, + 506, + 1346, + 5707, + 236764, + 5467, + 19246, + 506, + 52369, + 236764, + 532, + 174919, + 506, + 8699, + 8797, + 7659, + 1440, + 236772, + 6061, + 6417, + 236761, + 108, + 236813, + 18428, + 870, + 30852, + 497, + 236789, + 236751, + 7343, + 1604 + ], + "text": "Here are a few options, depending on the exact nuance you want to convey.\n\n## Option 1: Balanced and Data-Driven (Recommended)\n\nThis option is the most professional, directly addresses the critique, and pivots the discussion toward shared long-term benefits.\n\n> Hi [Reviewer's Name],", + "wall_seconds": 2.619187831878662, + "accept_lens": [ + 0, + 0, + 0, + 0, + 2, + 1, + 0, + 2, + 0, + 0, + 2, + 2, + 0, + 0, + 0, + 2, + 2, + 0, + 0, + 0, + 0, + 0, + 0, + 1, + 2, + 2, + 0, + 0, + 0, + 0, + 0, + 2, + 0, + 1, + 0, + 0, + 0, + 1, + 1, + 0 + ], + "matches_baseline": false + }, + { + "id": "long_4", + "prompt": "Explain the concept of recursion in programming to a student who has written simple loops but never recursive functions. Begin with an intuitive example unrelated to programming, then introduce the idea of a function calling itself, then walk through a concrete code example (use a small one, like computing a factorial or reversing a string). Address the common confusion about base cases and why missing them causes infinite recursion. End with one practical piece of advice about when recursion is the right tool versus when a loop is simpler.", + "tokens": [ + 6372, + 236789, + 236751, + 496, + 1822, + 1977, + 531, + 577, + 236888, + 148362, + 659, + 506, + 13916, + 529, + 27497, + 236764, + 532, + 901, + 659, + 20068, + 8632, + 236761, + 213726, + 526, + 563, + 1164, + 2264, + 1595, + 531, + 8974, + 4078, + 236764, + 840, + 625, + 6178, + 496, + 51935, + 1607, + 236764, + 3187, + 919, + 19185, + 236764, + 4313, + 236761, + 108, + 6481, + 236789, + 236751, + 2541, + 1679, + 74175, + 2918, + 236772, + 2003, + 236772, + 9340, + 236761, + 108, + 7243, + 108, + 1408, + 4040, + 236743 + ], + "text": "That's a great place to be! Loops are the foundation of iteration, and they are incredibly powerful. Recursion is just another way to solve problems, but it uses a fundamentally different, often more elegant, approach.\n\nLet's break down recursion step-by-step.\n\n---\n\n## Part ", + "wall_seconds": 2.9495770931243896, + "accept_lens": [ + 0, + 1, + 0, + 0, + 0, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 1, + 0, + 1, + 0, + 0, + 0, + 2, + 0, + 0, + 1, + 0, + 0, + 2, + 1, + 1, + 0, + 0, + 0, + 1, + 2, + 2, + 1, + 0, + 2, + 0, + 2, + 0, + 0, + 0, + 1 + ], + "matches_baseline": false + } + ] +} \ No newline at end of file diff --git a/Tests/MLXLMTests/SpeculativeWalkTests.swift b/Tests/MLXLMTests/SpeculativeWalkTests.swift new file mode 100644 index 0000000000..562497e6c6 --- /dev/null +++ b/Tests/MLXLMTests/SpeculativeWalkTests.swift @@ -0,0 +1,92 @@ +// Copyright © 2026 Apple Inc. + +import Foundation +import MLXLLM +import Testing + +@Suite("Gemma4SpeculativeWalk.single") +struct SpeculativeWalkSingleTests { + + @Test func emptyDraftReturnsJustMain() { + let (accepted, emitted) = Gemma4SpeculativeWalk.single( + draft: [], main: [7] + ) + #expect(accepted == 0) + #expect(emitted == [7]) + } + + @Test func allDraftsMatch() { + let (accepted, emitted) = Gemma4SpeculativeWalk.single( + draft: [1, 2, 3], main: [1, 2, 3, 4] + ) + #expect(accepted == 3) + #expect(emitted == [1, 2, 3, 4]) + } + + @Test func firstMismatchAtZero() { + let (accepted, emitted) = Gemma4SpeculativeWalk.single( + draft: [9, 2, 3], main: [1, 2, 3, 4] + ) + #expect(accepted == 0) + #expect(emitted == [1]) + } + + @Test func firstMismatchInMiddle() { + let (accepted, emitted) = Gemma4SpeculativeWalk.single( + draft: [1, 2, 99], main: [1, 2, 3, 4] + ) + #expect(accepted == 2) + #expect(emitted == [1, 2, 3]) + } + + @Test func emittedCountEqualsAcceptedPlusOne() { + // Invariant: emitted.count == accepted + 1 for any non-trivial input. + let draft = [1, 2, 3, 4, 5] + let main = [1, 2, 99, 4, 5, 6] + let (accepted, emitted) = Gemma4SpeculativeWalk.single(draft: draft, main: main) + #expect(emitted.count == accepted + 1) + } +} + +@Suite("Gemma4SpeculativeWalk.batched") +struct SpeculativeWalkBatchedTests { + + @Test func perRowEquivalenceToSingle() { + // B=2, k=3. Row 0 fully accepts; row 1 mismatches at position 1. + let draft: [[Int]] = [ + [1, 2, 3], + [4, 99, 6], + ] + let main: [[Int]] = [ + [1, 2, 3, 42], + [4, 5, 6, 7], + ] + let budgets = [Int.max, Int.max] + + let (batchedAccepted, batchedNew) = + Gemma4SpeculativeWalk.batched(draft: draft, main: main, budgets: budgets) + + // Expected per-row via single(...) + var expectedAccepted: [Int] = [] + var expectedNew: [[Int]] = [] + for i in 0 ..< draft.count { + let (a, n) = Gemma4SpeculativeWalk.single(draft: draft[i], main: main[i]) + expectedAccepted.append(a) + expectedNew.append(n) + } + #expect(batchedAccepted == expectedAccepted) + #expect(batchedNew == expectedNew) + } + + @Test func budgetTruncates() { + // Row accepts 3 and would emit 4 tokens, but budget = 2 truncates. + let draft: [[Int]] = [[1, 2, 3]] + let main: [[Int]] = [[1, 2, 3, 42]] + let (accepted, emitted) = + Gemma4SpeculativeWalk.batched(draft: draft, main: main, budgets: [2]) + // Emission is capped to 2 tokens; accepted is also capped so + // the invariant emitted.count == accepted + 1 still holds. + #expect(emitted[0].count == 2) + #expect(accepted[0] == 1) + } +} diff --git a/benchmarks/mtp-2026-05-09-130614.md b/benchmarks/mtp-2026-05-09-130614.md new file mode 100644 index 0000000000..aadfc3270f --- /dev/null +++ b/benchmarks/mtp-2026-05-09-130614.md @@ -0,0 +1,343 @@ +# MTP vs Baseline Benchmark + +## Environment + +| | | +|---|---| +| **Date** | 2026-05-09 17:06:17 UTC | +| **Commit** | `8eea326` (mtp-support-benchmark) | +| **Chip** | Apple M4 Max | +| **GPU cores** | 40 | +| **RAM** | 64 GB | +| **macOS** | 26.4 (25E246) | +| **Swift** | Apple Swift version 6.3 (swiftlang-6.3.0.123.5 clang-2100.0.123.102) | +| **pp sizes** | 512 2048 | +| **tg sizes** | 128 | +| **runs** | 3 | + +## Results + +## Gemma 4 26B +### gemma-4-26b-a4b [baseline] + +No model specified, attempting to auto-detect from endpoint... +Auto-detected HF model: snapshots/695690b33533b1f8b0395c1d6b4f00dc411353ef (served as: snapshots/695690b33533b1f8b0395c1d6b4f00dc411353ef) +llama-benchy (0.3.7) +Date: 2026-05-09 13:06:34 +Benchmarking model: snapshots/695690b33533b1f8b0395c1d6b4f00dc411353ef at http://localhost:18765/v1 +Concurrency levels: [1] +Loading text from cache: /Users/gg/.cache/llama-benchy/cc6a0b5782734ee3b9069aa3b64cc62c.txt +Total tokens available in text corpus: 144040 +Warming up... +Warmup (User only) complete. Delta: 12 tokens (Server: 33, Local: 21) +Warmup (System+Empty) complete. Delta: 17 tokens (Server: 38, Local: 21) + +Skipping coherence test (--skip-coherence specified) +Measuring latency using mode: generation... +Average latency (generation): 1.08 ms +Running test: pp=512, tg=128, depth=0, concurrency=1 + Run 1/3 (batch size 1)... + No token_ids in response, using local tokenization + Run 2/3 (batch size 1)... + Run 3/3 (batch size 1)... +Running test: pp=2048, tg=128, depth=0, concurrency=1 + Run 1/3 (batch size 1)... + Run 2/3 (batch size 1)... + Run 3/3 (batch size 1)... +Printing results in MD format: + + + +| model | test | t/s | peak t/s | ttfr (ms) | est_ppt (ms) | e2e_ttft (ms) | +|:---------------------------------------------------|-------:|-----------------:|-------------:|----------------:|----------------:|----------------:| +| snapshots/695690b33533b1f8b0395c1d6b4f00dc411353ef | pp512 | 4301.20 ± 608.18 | | 119.97 ± 18.65 | 118.88 ± 18.65 | 657.57 ± 35.86 | +| snapshots/695690b33533b1f8b0395c1d6b4f00dc411353ef | tg128 | 35.17 ± 0.13 | 36.33 ± 0.47 | | | | +| snapshots/695690b33533b1f8b0395c1d6b4f00dc411353ef | pp2048 | 1728.76 ± 58.07 | | 1180.12 ± 39.10 | 1179.04 ± 39.10 | 3949.78 ± 46.33 | +| snapshots/695690b33533b1f8b0395c1d6b4f00dc411353ef | tg128 | 33.98 ± 0.32 | 35.00 ± 0.00 | | | | + +llama-benchy (0.3.7) +date: 2026-05-09 13:06:34 | latency mode: generation + +### gemma-4-26b-a4b [MTP] + +No model specified, attempting to auto-detect from endpoint... +Auto-detected HF model: snapshots/695690b33533b1f8b0395c1d6b4f00dc411353ef (served as: snapshots/695690b33533b1f8b0395c1d6b4f00dc411353ef) +llama-benchy (0.3.7) +Date: 2026-05-09 13:07:18 +Benchmarking model: snapshots/695690b33533b1f8b0395c1d6b4f00dc411353ef at http://localhost:18765/v1 +Concurrency levels: [1] +Loading text from cache: /Users/gg/.cache/llama-benchy/cc6a0b5782734ee3b9069aa3b64cc62c.txt +Total tokens available in text corpus: 144040 +Warming up... +Warmup (User only) complete. Delta: 12 tokens (Server: 33, Local: 21) +Warmup (System+Empty) complete. Delta: 17 tokens (Server: 38, Local: 21) + +Skipping coherence test (--skip-coherence specified) +Measuring latency using mode: generation... +Average latency (generation): 1.30 ms +Running test: pp=512, tg=128, depth=0, concurrency=1 + Run 1/3 (batch size 1)... + No token_ids in response, using local tokenization + Run 2/3 (batch size 1)... + Run 3/3 (batch size 1)... +Running test: pp=2048, tg=128, depth=0, concurrency=1 + Run 1/3 (batch size 1)... + Run 2/3 (batch size 1)... + Run 3/3 (batch size 1)... +Printing results in MD format: + + + +| model | test | t/s | peak t/s | ttfr (ms) | est_ppt (ms) | e2e_ttft (ms) | +|:---------------------------------------------------|-------:|-----------------:|--------------:|----------------:|----------------:|-----------------:| +| snapshots/695690b33533b1f8b0395c1d6b4f00dc411353ef | pp512 | 3453.39 ± 158.63 | | 146.39 ± 6.74 | 145.09 ± 6.74 | 734.36 ± 16.77 | +| snapshots/695690b33533b1f8b0395c1d6b4f00dc411353ef | tg128 | 71.88 ± 6.06 | 80.00 ± 6.48 | | | | +| snapshots/695690b33533b1f8b0395c1d6b4f00dc411353ef | pp2048 | 1767.40 ± 96.68 | | 1156.60 ± 60.93 | 1155.31 ± 60.93 | 4125.06 ± 162.06 | +| snapshots/695690b33533b1f8b0395c1d6b4f00dc411353ef | tg128 | 38.65 ± 13.03 | 49.95 ± 26.92 | | | | + +llama-benchy (0.3.7) +date: 2026-05-09 13:07:18 | latency mode: generation + +## Gemma 4 31B +### gemma-4-31b [baseline] + +No model specified, attempting to auto-detect from endpoint... +Auto-detected HF model: snapshots/dcb78c3f5d6becacbfce71cd4851ad98c4f08a05 (served as: snapshots/dcb78c3f5d6becacbfce71cd4851ad98c4f08a05) +llama-benchy (0.3.7) +Date: 2026-05-09 13:07:49 +Benchmarking model: snapshots/dcb78c3f5d6becacbfce71cd4851ad98c4f08a05 at http://localhost:18765/v1 +Concurrency levels: [1] +Loading text from cache: /Users/gg/.cache/llama-benchy/cc6a0b5782734ee3b9069aa3b64cc62c.txt +Total tokens available in text corpus: 144040 +Warming up... +Warmup (User only) complete. Delta: 12 tokens (Server: 33, Local: 21) +Warmup (System+Empty) complete. Delta: 17 tokens (Server: 38, Local: 21) + +Skipping coherence test (--skip-coherence specified) +Measuring latency using mode: generation... +Average latency (generation): 1.24 ms +Running test: pp=512, tg=128, depth=0, concurrency=1 + Run 1/3 (batch size 1)... + No token_ids in response, using local tokenization + Run 2/3 (batch size 1)... + Run 3/3 (batch size 1)... +Running test: pp=2048, tg=128, depth=0, concurrency=1 + Run 1/3 (batch size 1)... + Run 2/3 (batch size 1)... + Run 3/3 (batch size 1)... +Printing results in MD format: + + + +| model | test | t/s | peak t/s | ttfr (ms) | est_ppt (ms) | e2e_ttft (ms) | +|:---------------------------------------------------|-------:|-----------------:|-------------:|-----------------:|-----------------:|-------------------:| +| snapshots/dcb78c3f5d6becacbfce71cd4851ad98c4f08a05 | pp512 | 1797.92 ± 836.03 | | 334.98 ± 121.01 | 333.75 ± 121.01 | 4928.44 ± 932.42 | +| snapshots/dcb78c3f5d6becacbfce71cd4851ad98c4f08a05 | tg128 | 12.52 ± 2.59 | 16.67 ± 0.47 | | | | +| snapshots/dcb78c3f5d6becacbfce71cd4851ad98c4f08a05 | pp2048 | 1236.88 ± 185.33 | | 1689.67 ± 282.67 | 1688.43 ± 282.67 | 21833.62 ± 5068.54 | +| snapshots/dcb78c3f5d6becacbfce71cd4851ad98c4f08a05 | tg128 | 9.85 ± 2.48 | 14.33 ± 0.94 | | | | + +llama-benchy (0.3.7) +date: 2026-05-09 13:07:49 | latency mode: generation + +### gemma-4-31b [MTP] + +No model specified, attempting to auto-detect from endpoint... +Auto-detected HF model: snapshots/dcb78c3f5d6becacbfce71cd4851ad98c4f08a05 (served as: snapshots/dcb78c3f5d6becacbfce71cd4851ad98c4f08a05) +llama-benchy (0.3.7) +Date: 2026-05-09 13:10:35 +Benchmarking model: snapshots/dcb78c3f5d6becacbfce71cd4851ad98c4f08a05 at http://localhost:18765/v1 +Concurrency levels: [1] +Loading text from cache: /Users/gg/.cache/llama-benchy/cc6a0b5782734ee3b9069aa3b64cc62c.txt +Total tokens available in text corpus: 144040 +Warming up... +Warmup (User only) complete. Delta: 12 tokens (Server: 33, Local: 21) +Warmup (System+Empty) complete. Delta: 17 tokens (Server: 38, Local: 21) + +Skipping coherence test (--skip-coherence specified) +Measuring latency using mode: generation... +Average latency (generation): 1.17 ms +Running test: pp=512, tg=128, depth=0, concurrency=1 + Run 1/3 (batch size 1)... + No token_ids in response, using local tokenization + Run 2/3 (batch size 1)... + Run 3/3 (batch size 1)... +Running test: pp=2048, tg=128, depth=0, concurrency=1 + Run 1/3 (batch size 1)... + Run 2/3 (batch size 1)... + Run 3/3 (batch size 1)... +Printing results in MD format: + + + +| model | test | t/s | peak t/s | ttfr (ms) | est_ppt (ms) | e2e_ttft (ms) | +|:---------------------------------------------------|-------:|-----------------:|-------------:|-----------------:|-----------------:|-------------------:| +| snapshots/dcb78c3f5d6becacbfce71cd4851ad98c4f08a05 | pp512 | 3874.46 ± 262.78 | | 130.80 ± 8.53 | 129.63 ± 8.53 | 6644.03 ± 605.22 | +| snapshots/dcb78c3f5d6becacbfce71cd4851ad98c4f08a05 | tg128 | 9.77 ± 1.06 | 17.33 ± 1.89 | | | | +| snapshots/dcb78c3f5d6becacbfce71cd4851ad98c4f08a05 | pp2048 | 1582.98 ± 130.24 | | 1296.66 ± 113.05 | 1295.48 ± 113.05 | 23390.14 ± 1430.60 | +| snapshots/dcb78c3f5d6becacbfce71cd4851ad98c4f08a05 | tg128 | 5.82 ± 0.51 | 10.00 ± 0.82 | | | | + +llama-benchy (0.3.7) +date: 2026-05-09 13:10:35 | latency mode: generation + +## Qwen3.6 27B +### Qwen3.6-27B [baseline] + +No model specified, attempting to auto-detect from endpoint... +Auto-detected HF model: snapshots/c000ac2c2057d94be3fa931000c31723aac53282 (served as: snapshots/c000ac2c2057d94be3fa931000c31723aac53282) +llama-benchy (0.3.7) +Date: 2026-05-09 13:14:01 +Benchmarking model: snapshots/c000ac2c2057d94be3fa931000c31723aac53282 at http://localhost:18765/v1 +Concurrency levels: [1] +Loading text from cache: /Users/gg/.cache/llama-benchy/cc6a0b5782734ee3b9069aa3b64cc62c.txt +Total tokens available in text corpus: 144480 +Warming up... +Warmup (User only) complete. Delta: 9 tokens (Server: 30, Local: 21) +Warmup (System+Empty) complete. Delta: 7 tokens (Server: 28, Local: 21) + +Skipping coherence test (--skip-coherence specified) +Measuring latency using mode: generation... +Average latency (generation): 1.22 ms +Running test: pp=512, tg=128, depth=0, concurrency=1 + Run 1/3 (batch size 1)... + No token_ids in response, using local tokenization + Run 2/3 (batch size 1)... + Run 3/3 (batch size 1)... +Running test: pp=2048, tg=128, depth=0, concurrency=1 + Run 1/3 (batch size 1)... + Run 2/3 (batch size 1)... + Run 3/3 (batch size 1)... +Printing results in MD format: + + + +| model | test | t/s | peak t/s | ttfr (ms) | est_ppt (ms) | e2e_ttft (ms) | +|:---------------------------------------------------|-------:|--------------------:|-------------:|-------------:|---------------:|------------------:| +| snapshots/c000ac2c2057d94be3fa931000c31723aac53282 | pp512 | 78384.81 ± 17685.05 | | 7.96 ± 1.44 | 6.74 ± 1.44 | 3582.97 ± 673.57 | +| snapshots/c000ac2c2057d94be3fa931000c31723aac53282 | tg128 | 15.12 ± 0.09 | 20.00 ± 0.00 | | | | +| snapshots/c000ac2c2057d94be3fa931000c31723aac53282 | pp2048 | 58478.25 ± 9106.92 | | 37.03 ± 6.10 | 35.81 ± 6.10 | 13887.84 ± 308.93 | +| snapshots/c000ac2c2057d94be3fa931000c31723aac53282 | tg128 | 15.55 ± 0.29 | 19.67 ± 0.47 | | | | + +llama-benchy (0.3.7) +date: 2026-05-09 13:14:01 | latency mode: generation + +### Qwen3.6-27B [MTP] + +No model specified, attempting to auto-detect from endpoint... +Auto-detected HF model: snapshots/c000ac2c2057d94be3fa931000c31723aac53282 (served as: snapshots/c000ac2c2057d94be3fa931000c31723aac53282) +llama-benchy (0.3.7) +Date: 2026-05-09 13:15:51 +Benchmarking model: snapshots/c000ac2c2057d94be3fa931000c31723aac53282 at http://localhost:18765/v1 +Concurrency levels: [1] +Loading text from cache: /Users/gg/.cache/llama-benchy/cc6a0b5782734ee3b9069aa3b64cc62c.txt +Total tokens available in text corpus: 144480 +Warming up... +Warmup (User only) complete. Delta: 9 tokens (Server: 30, Local: 21) +Warmup (System+Empty) complete. Delta: 7 tokens (Server: 28, Local: 21) + +Skipping coherence test (--skip-coherence specified) +Measuring latency using mode: generation... +Average latency (generation): 1.20 ms +Running test: pp=512, tg=128, depth=0, concurrency=1 + Run 1/3 (batch size 1)... + No token_ids in response, using local tokenization + Run 2/3 (batch size 1)... + Run 3/3 (batch size 1)... +Running test: pp=2048, tg=128, depth=0, concurrency=1 + Run 1/3 (batch size 1)... + Run 2/3 (batch size 1)... + Run 3/3 (batch size 1)... +Printing results in MD format: + + + +| model | test | t/s | peak t/s | ttfr (ms) | est_ppt (ms) | e2e_ttft (ms) | +|:---------------------------------------------------|-------:|--------------------:|-------------:|-------------:|---------------:|------------------:| +| snapshots/c000ac2c2057d94be3fa931000c31723aac53282 | pp512 | 88241.14 ± 14075.16 | | 7.06 ± 1.02 | 5.86 ± 1.02 | 3718.67 ± 759.93 | +| snapshots/c000ac2c2057d94be3fa931000c31723aac53282 | tg128 | 15.75 ± 0.34 | 21.67 ± 0.47 | | | | +| snapshots/c000ac2c2057d94be3fa931000c31723aac53282 | pp2048 | 73182.21 ± 10725.78 | | 29.61 ± 3.78 | 28.42 ± 3.78 | 14869.41 ± 389.56 | +| snapshots/c000ac2c2057d94be3fa931000c31723aac53282 | tg128 | 14.23 ± 0.80 | 20.00 ± 0.00 | | | | + +llama-benchy (0.3.7) +date: 2026-05-09 13:15:51 | latency mode: generation + +## Qwen3.6 35B +### Qwen3.6-35B [baseline] + +No model specified, attempting to auto-detect from endpoint... +Auto-detected HF model: snapshots/38740b847e4cb78f352aba30aa41c76e08e6eb46 (served as: snapshots/38740b847e4cb78f352aba30aa41c76e08e6eb46) +llama-benchy (0.3.7) +Date: 2026-05-09 13:17:45 +Benchmarking model: snapshots/38740b847e4cb78f352aba30aa41c76e08e6eb46 at http://localhost:18765/v1 +Concurrency levels: [1] +Loading text from cache: /Users/gg/.cache/llama-benchy/cc6a0b5782734ee3b9069aa3b64cc62c.txt +Total tokens available in text corpus: 144480 +Warming up... +Warmup (User only) complete. Delta: 9 tokens (Server: 30, Local: 21) +Warmup (System+Empty) complete. Delta: 7 tokens (Server: 28, Local: 21) + +Skipping coherence test (--skip-coherence specified) +Measuring latency using mode: generation... +Average latency (generation): 1.19 ms +Running test: pp=512, tg=128, depth=0, concurrency=1 + Run 1/3 (batch size 1)... + No token_ids in response, using local tokenization + Run 2/3 (batch size 1)... + Run 3/3 (batch size 1)... +Running test: pp=2048, tg=128, depth=0, concurrency=1 + Run 1/3 (batch size 1)... + Run 2/3 (batch size 1)... + Run 3/3 (batch size 1)... +Printing results in MD format: + + + +| model | test | t/s | peak t/s | ttfr (ms) | est_ppt (ms) | e2e_ttft (ms) | +|:---------------------------------------------------|-------:|--------------------:|-------------:|-------------:|---------------:|----------------:| +| snapshots/38740b847e4cb78f352aba30aa41c76e08e6eb46 | pp512 | 98664.38 ± 6854.20 | | 6.31 ± 0.35 | 5.12 ± 0.35 | 416.39 ± 7.03 | +| snapshots/38740b847e4cb78f352aba30aa41c76e08e6eb46 | tg128 | 35.68 ± 0.22 | 37.00 ± 0.00 | | | | +| snapshots/38740b847e4cb78f352aba30aa41c76e08e6eb46 | pp2048 | 104661.96 ± 3965.38 | | 20.70 ± 0.72 | 19.51 ± 0.72 | 2306.31 ± 52.51 | +| snapshots/38740b847e4cb78f352aba30aa41c76e08e6eb46 | tg128 | 35.09 ± 0.21 | 36.67 ± 0.47 | | | | + +llama-benchy (0.3.7) +date: 2026-05-09 13:17:45 | latency mode: generation + +### Qwen3.6-35B [MTP] + +No model specified, attempting to auto-detect from endpoint... +Auto-detected HF model: snapshots/38740b847e4cb78f352aba30aa41c76e08e6eb46 (served as: snapshots/38740b847e4cb78f352aba30aa41c76e08e6eb46) +llama-benchy (0.3.7) +Date: 2026-05-09 13:18:21 +Benchmarking model: snapshots/38740b847e4cb78f352aba30aa41c76e08e6eb46 at http://localhost:18765/v1 +Concurrency levels: [1] +Loading text from cache: /Users/gg/.cache/llama-benchy/cc6a0b5782734ee3b9069aa3b64cc62c.txt +Total tokens available in text corpus: 144480 +Warming up... +Warmup (User only) complete. Delta: 9 tokens (Server: 30, Local: 21) +Warmup (System+Empty) complete. Delta: 7 tokens (Server: 28, Local: 21) + +Skipping coherence test (--skip-coherence specified) +Measuring latency using mode: generation... +Average latency (generation): 1.19 ms +Running test: pp=512, tg=128, depth=0, concurrency=1 + Run 1/3 (batch size 1)... + No token_ids in response, using local tokenization + Run 2/3 (batch size 1)... + Run 3/3 (batch size 1)... +Running test: pp=2048, tg=128, depth=0, concurrency=1 + Run 1/3 (batch size 1)... + Run 2/3 (batch size 1)... + Run 3/3 (batch size 1)... +Printing results in MD format: + + + +| model | test | t/s | peak t/s | ttfr (ms) | est_ppt (ms) | e2e_ttft (ms) | +|:---------------------------------------------------|-------:|--------------------:|-------------:|-------------:|---------------:|-----------------:| +| snapshots/38740b847e4cb78f352aba30aa41c76e08e6eb46 | pp512 | 99887.69 ± 4900.64 | | 6.24 ± 0.26 | 5.05 ± 0.26 | 430.74 ± 5.98 | +| snapshots/38740b847e4cb78f352aba30aa41c76e08e6eb46 | tg128 | 25.57 ± 0.34 | 29.33 ± 0.47 | | | | +| snapshots/38740b847e4cb78f352aba30aa41c76e08e6eb46 | pp2048 | 105030.22 ± 1536.08 | | 20.61 ± 0.29 | 19.42 ± 0.29 | 1648.59 ± 147.55 | +| snapshots/38740b847e4cb78f352aba30aa41c76e08e6eb46 | tg128 | 24.97 ± 0.64 | 29.67 ± 0.47 | | | | + +llama-benchy (0.3.7) +date: 2026-05-09 13:18:21 | latency mode: generation + diff --git a/benchmarks/mtp-2026-05-09-142113.md b/benchmarks/mtp-2026-05-09-142113.md new file mode 100644 index 0000000000..8764e6f0de --- /dev/null +++ b/benchmarks/mtp-2026-05-09-142113.md @@ -0,0 +1,342 @@ +# MTP vs Baseline Benchmark + +## Environment + +| | | +|---|---| +| **Date** | 2026-05-09 18:21:16 UTC | +| **Commit** | `0459dd2` (mtp-support-perf) | +| **Chip** | Apple M4 Max | +| **GPU cores** | 40 | +| **RAM** | 64 GB | +| **macOS** | 26.4 (25E246) | +| **Swift** | Apple Swift version 6.3 (swiftlang-6.3.0.123.5 clang-2100.0.123.102) | +| **pp sizes** | 512 2048 | +| **tg sizes** | 128 | +| **runs** | 3 | + +## Results + +## Gemma 4 26B +### gemma-4-26b-a4b [baseline] + +No model specified, attempting to auto-detect from endpoint... +Auto-detected HF model: snapshots/695690b33533b1f8b0395c1d6b4f00dc411353ef (served as: snapshots/695690b33533b1f8b0395c1d6b4f00dc411353ef) +llama-benchy (0.3.7) +Date: 2026-05-09 14:21:26 +Benchmarking model: snapshots/695690b33533b1f8b0395c1d6b4f00dc411353ef at http://localhost:18765/v1 +Concurrency levels: [1] +Loading text from cache: /Users/gg/.cache/llama-benchy/cc6a0b5782734ee3b9069aa3b64cc62c.txt +Total tokens available in text corpus: 144040 +Warming up... +Warmup (User only) complete. Delta: 12 tokens (Server: 33, Local: 21) +Warmup (System+Empty) complete. Delta: 17 tokens (Server: 38, Local: 21) + +Skipping coherence test (--skip-coherence specified) +Measuring latency using mode: generation... +Average latency (generation): 1.16 ms +Running test: pp=512, tg=128, depth=0, concurrency=1 + Run 1/3 (batch size 1)... + No token_ids in response, using local tokenization + Run 2/3 (batch size 1)... + Run 3/3 (batch size 1)... +Running test: pp=2048, tg=128, depth=0, concurrency=1 + Run 1/3 (batch size 1)... + Run 2/3 (batch size 1)... + Run 3/3 (batch size 1)... +Printing results in MD format: + + + +| model | test | t/s | peak t/s | ttfr (ms) | est_ppt (ms) | e2e_ttft (ms) | +|:---------------------------------------------------|-------:|-----------------:|-------------:|----------------:|----------------:|-----------------:| +| snapshots/695690b33533b1f8b0395c1d6b4f00dc411353ef | pp512 | 3544.70 ± 238.37 | | 142.88 ± 9.93 | 141.72 ± 9.93 | 718.77 ± 20.28 | +| snapshots/695690b33533b1f8b0395c1d6b4f00dc411353ef | tg128 | 34.11 ± 0.39 | 35.67 ± 0.47 | | | | +| snapshots/695690b33533b1f8b0395c1d6b4f00dc411353ef | pp2048 | 1741.87 ± 137.59 | | 1177.07 ± 89.35 | 1175.91 ± 89.35 | 3991.04 ± 159.67 | +| snapshots/695690b33533b1f8b0395c1d6b4f00dc411353ef | tg128 | 33.69 ± 0.38 | 35.00 ± 0.00 | | | | + +llama-benchy (0.3.7) +date: 2026-05-09 14:21:26 | latency mode: generation + +### gemma-4-26b-a4b [MTP] + +No model specified, attempting to auto-detect from endpoint... +Auto-detected HF model: snapshots/695690b33533b1f8b0395c1d6b4f00dc411353ef (served as: snapshots/695690b33533b1f8b0395c1d6b4f00dc411353ef) +llama-benchy (0.3.7) +Date: 2026-05-09 14:22:10 +Benchmarking model: snapshots/695690b33533b1f8b0395c1d6b4f00dc411353ef at http://localhost:18765/v1 +Concurrency levels: [1] +Loading text from cache: /Users/gg/.cache/llama-benchy/cc6a0b5782734ee3b9069aa3b64cc62c.txt +Total tokens available in text corpus: 144040 +Warming up... +Warmup (User only) complete. Delta: 12 tokens (Server: 33, Local: 21) +Warmup (System+Empty) complete. Delta: 17 tokens (Server: 38, Local: 21) + +Skipping coherence test (--skip-coherence specified) +Measuring latency using mode: generation... +Average latency (generation): 1.31 ms +Running test: pp=512, tg=128, depth=0, concurrency=1 + Run 1/3 (batch size 1)... + No token_ids in response, using local tokenization + Run 2/3 (batch size 1)... + Run 3/3 (batch size 1)... +Running test: pp=2048, tg=128, depth=0, concurrency=1 + Run 1/3 (batch size 1)... + Run 2/3 (batch size 1)... + Run 3/3 (batch size 1)... +Printing results in MD format: + + + +| model | test | t/s | peak t/s | ttfr (ms) | est_ppt (ms) | e2e_ttft (ms) | +|:---------------------------------------------------|-------:|-----------------:|--------------:|----------------:|----------------:|-----------------:| +| snapshots/695690b33533b1f8b0395c1d6b4f00dc411353ef | pp512 | 4186.65 ± 73.57 | | 120.78 ± 2.13 | 119.46 ± 2.13 | 665.81 ± 7.18 | +| snapshots/695690b33533b1f8b0395c1d6b4f00dc411353ef | tg128 | 74.78 ± 3.02 | 81.67 ± 1.25 | | | | +| snapshots/695690b33533b1f8b0395c1d6b4f00dc411353ef | pp2048 | 1557.53 ± 104.82 | | 1314.55 ± 89.85 | 1313.24 ± 89.85 | 4455.03 ± 157.71 | +| snapshots/695690b33533b1f8b0395c1d6b4f00dc411353ef | tg128 | 51.24 ± 8.50 | 67.67 ± 15.58 | | | | + +llama-benchy (0.3.7) +date: 2026-05-09 14:22:10 | latency mode: generation + +## Gemma 4 31B +### gemma-4-31b [baseline] + +No model specified, attempting to auto-detect from endpoint... +Auto-detected HF model: snapshots/dcb78c3f5d6becacbfce71cd4851ad98c4f08a05 (served as: snapshots/dcb78c3f5d6becacbfce71cd4851ad98c4f08a05) +llama-benchy (0.3.7) +Date: 2026-05-09 14:22:46 +Benchmarking model: snapshots/dcb78c3f5d6becacbfce71cd4851ad98c4f08a05 at http://localhost:18765/v1 +Concurrency levels: [1] +Loading text from cache: /Users/gg/.cache/llama-benchy/cc6a0b5782734ee3b9069aa3b64cc62c.txt +Total tokens available in text corpus: 144040 +Warming up... +Warmup (User only) complete. Delta: 12 tokens (Server: 33, Local: 21) +Warmup (System+Empty) complete. Delta: 17 tokens (Server: 38, Local: 21) + +Skipping coherence test (--skip-coherence specified) +Measuring latency using mode: generation... +Average latency (generation): 1.37 ms +Running test: pp=512, tg=128, depth=0, concurrency=1 + Run 1/3 (batch size 1)... + No token_ids in response, using local tokenization + Run 2/3 (batch size 1)... + Run 3/3 (batch size 1)... +Running test: pp=2048, tg=128, depth=0, concurrency=1 + Run 1/3 (batch size 1)... + Run 2/3 (batch size 1)... + Run 3/3 (batch size 1)... +Printing results in MD format: + + + +| model | test | t/s | peak t/s | ttfr (ms) | est_ppt (ms) | e2e_ttft (ms) | +|:---------------------------------------------------|-------:|-----------------:|-------------:|-----------------:|-----------------:|-------------------:| +| snapshots/dcb78c3f5d6becacbfce71cd4851ad98c4f08a05 | pp512 | 2854.26 ± 444.97 | | 181.40 ± 31.19 | 180.03 ± 31.19 | 4714.72 ± 867.55 | +| snapshots/dcb78c3f5d6becacbfce71cd4851ad98c4f08a05 | tg128 | 12.90 ± 2.15 | 16.67 ± 0.47 | | | | +| snapshots/dcb78c3f5d6becacbfce71cd4851ad98c4f08a05 | pp2048 | 1398.32 ± 121.59 | | 1468.33 ± 125.90 | 1466.97 ± 125.90 | 24462.14 ± 9471.72 | +| snapshots/dcb78c3f5d6becacbfce71cd4851ad98c4f08a05 | tg128 | 9.61 ± 3.59 | 13.67 ± 3.30 | | | | + +llama-benchy (0.3.7) +date: 2026-05-09 14:22:46 | latency mode: generation + +### gemma-4-31b [MTP] + +No model specified, attempting to auto-detect from endpoint... +Auto-detected HF model: snapshots/dcb78c3f5d6becacbfce71cd4851ad98c4f08a05 (served as: snapshots/dcb78c3f5d6becacbfce71cd4851ad98c4f08a05) +llama-benchy (0.3.7) +Date: 2026-05-09 14:25:41 +Benchmarking model: snapshots/dcb78c3f5d6becacbfce71cd4851ad98c4f08a05 at http://localhost:18765/v1 +Concurrency levels: [1] +Loading text from cache: /Users/gg/.cache/llama-benchy/cc6a0b5782734ee3b9069aa3b64cc62c.txt +Total tokens available in text corpus: 144040 +Warming up... +Warmup (User only) complete. Delta: 12 tokens (Server: 33, Local: 21) +Warmup (System+Empty) complete. Delta: 17 tokens (Server: 38, Local: 21) + +Skipping coherence test (--skip-coherence specified) +Measuring latency using mode: generation... +Average latency (generation): 1.32 ms +Running test: pp=512, tg=128, depth=0, concurrency=1 + Run 1/3 (batch size 1)... + No token_ids in response, using local tokenization + Run 2/3 (batch size 1)... + Run 3/3 (batch size 1)... +Running test: pp=2048, tg=128, depth=0, concurrency=1 + Run 1/3 (batch size 1)... + Run 2/3 (batch size 1)... + Run 3/3 (batch size 1)... +Printing results in MD format: + + + +| model | test | t/s | peak t/s | ttfr (ms) | est_ppt (ms) | e2e_ttft (ms) | +|:---------------------------------------------------|-------:|-----------------:|-------------:|----------------:|----------------:|-------------------:| +| snapshots/dcb78c3f5d6becacbfce71cd4851ad98c4f08a05 | pp512 | 4008.58 ± 887.06 | | 131.61 ± 25.15 | 130.29 ± 25.15 | 5884.86 ± 142.28 | +| snapshots/dcb78c3f5d6becacbfce71cd4851ad98c4f08a05 | tg128 | 9.73 ± 1.25 | 17.00 ± 2.16 | | | | +| snapshots/dcb78c3f5d6becacbfce71cd4851ad98c4f08a05 | pp2048 | 1653.90 ± 111.26 | | 1237.69 ± 79.50 | 1236.38 ± 79.50 | 22213.39 ± 1161.20 | +| snapshots/dcb78c3f5d6becacbfce71cd4851ad98c4f08a05 | tg128 | 6.71 ± 1.05 | 12.67 ± 1.25 | | | | + +llama-benchy (0.3.7) +date: 2026-05-09 14:25:41 | latency mode: generation + +## Qwen3.6 27B +### Qwen3.6-27B [baseline] + +No model specified, attempting to auto-detect from endpoint... +Auto-detected HF model: snapshots/c000ac2c2057d94be3fa931000c31723aac53282 (served as: snapshots/c000ac2c2057d94be3fa931000c31723aac53282) +llama-benchy (0.3.7) +Date: 2026-05-09 14:28:53 +Benchmarking model: snapshots/c000ac2c2057d94be3fa931000c31723aac53282 at http://localhost:18765/v1 +Concurrency levels: [1] +Loading text from cache: /Users/gg/.cache/llama-benchy/cc6a0b5782734ee3b9069aa3b64cc62c.txt +Total tokens available in text corpus: 144480 +Warming up... +Warmup (User only) complete. Delta: 9 tokens (Server: 30, Local: 21) +Warmup (System+Empty) complete. Delta: 7 tokens (Server: 28, Local: 21) + +Skipping coherence test (--skip-coherence specified) +Measuring latency using mode: generation... +Average latency (generation): 1.26 ms +Running test: pp=512, tg=128, depth=0, concurrency=1 + Run 1/3 (batch size 1)... + No token_ids in response, using local tokenization + Run 2/3 (batch size 1)... + Run 3/3 (batch size 1)... +Running test: pp=2048, tg=128, depth=0, concurrency=1 + Run 1/3 (batch size 1)... + Run 2/3 (batch size 1)... + Run 3/3 (batch size 1)... +Printing results in MD format: + + + +| model | test | t/s | peak t/s | ttfr (ms) | est_ppt (ms) | e2e_ttft (ms) | +|:---------------------------------------------------|-------:|-------------------:|-------------:|-------------:|---------------:|------------------:| +| snapshots/c000ac2c2057d94be3fa931000c31723aac53282 | pp512 | 89739.86 ± 8649.72 | | 6.92 ± 0.52 | 5.66 ± 0.52 | 3661.64 ± 761.60 | +| snapshots/c000ac2c2057d94be3fa931000c31723aac53282 | tg128 | 9.97 ± 0.42 | 12.67 ± 0.47 | | | | +| snapshots/c000ac2c2057d94be3fa931000c31723aac53282 | pp2048 | 94611.98 ± 5592.48 | | 22.89 ± 1.26 | 21.63 ± 1.26 | 14438.59 ± 296.95 | +| snapshots/c000ac2c2057d94be3fa931000c31723aac53282 | tg128 | 10.00 ± 0.21 | 13.00 ± 0.00 | | | | + +llama-benchy (0.3.7) +date: 2026-05-09 14:28:53 | latency mode: generation + +### Qwen3.6-27B [MTP] + +No model specified, attempting to auto-detect from endpoint... +Auto-detected HF model: snapshots/c000ac2c2057d94be3fa931000c31723aac53282 (served as: snapshots/c000ac2c2057d94be3fa931000c31723aac53282) +llama-benchy (0.3.7) +Date: 2026-05-09 14:31:10 +Benchmarking model: snapshots/c000ac2c2057d94be3fa931000c31723aac53282 at http://localhost:18765/v1 +Concurrency levels: [1] +Loading text from cache: /Users/gg/.cache/llama-benchy/cc6a0b5782734ee3b9069aa3b64cc62c.txt +Total tokens available in text corpus: 144480 +Warming up... +Warmup (User only) complete. Delta: 9 tokens (Server: 30, Local: 21) +Warmup (System+Empty) complete. Delta: 7 tokens (Server: 28, Local: 21) + +Skipping coherence test (--skip-coherence specified) +Measuring latency using mode: generation... +Average latency (generation): 1.20 ms +Running test: pp=512, tg=128, depth=0, concurrency=1 + Run 1/3 (batch size 1)... + No token_ids in response, using local tokenization + Run 2/3 (batch size 1)... + Run 3/3 (batch size 1)... +Running test: pp=2048, tg=128, depth=0, concurrency=1 + Run 1/3 (batch size 1)... + Run 2/3 (batch size 1)... + Run 3/3 (batch size 1)... +Printing results in MD format: + + + +| model | test | t/s | peak t/s | ttfr (ms) | est_ppt (ms) | e2e_ttft (ms) | +|:---------------------------------------------------|-------:|--------------------:|-------------:|-------------:|---------------:|------------------:| +| snapshots/c000ac2c2057d94be3fa931000c31723aac53282 | pp512 | 100332.82 ± 5313.86 | | 6.23 ± 0.26 | 5.03 ± 0.26 | 3714.88 ± 503.98 | +| snapshots/c000ac2c2057d94be3fa931000c31723aac53282 | tg128 | 10.62 ± 0.40 | 15.67 ± 0.47 | | | | +| snapshots/c000ac2c2057d94be3fa931000c31723aac53282 | pp2048 | 85698.41 ± 8628.23 | | 25.23 ± 2.37 | 24.03 ± 2.37 | 14701.56 ± 179.35 | +| snapshots/c000ac2c2057d94be3fa931000c31723aac53282 | tg128 | 10.55 ± 0.33 | 15.00 ± 0.82 | | | | + +llama-benchy (0.3.7) +date: 2026-05-09 14:31:10 | latency mode: generation + +## Qwen3.6 35B +### Qwen3.6-35B [baseline] + +No model specified, attempting to auto-detect from endpoint... +Auto-detected HF model: snapshots/38740b847e4cb78f352aba30aa41c76e08e6eb46 (served as: snapshots/38740b847e4cb78f352aba30aa41c76e08e6eb46) +llama-benchy (0.3.7) +Date: 2026-05-09 14:33:27 +Benchmarking model: snapshots/38740b847e4cb78f352aba30aa41c76e08e6eb46 at http://localhost:18765/v1 +Concurrency levels: [1] +Loading text from cache: /Users/gg/.cache/llama-benchy/cc6a0b5782734ee3b9069aa3b64cc62c.txt +Total tokens available in text corpus: 144480 +Warming up... +Warmup (User only) complete. Delta: 9 tokens (Server: 30, Local: 21) +Warmup (System+Empty) complete. Delta: 7 tokens (Server: 28, Local: 21) + +Skipping coherence test (--skip-coherence specified) +Measuring latency using mode: generation... +Average latency (generation): 1.22 ms +Running test: pp=512, tg=128, depth=0, concurrency=1 + Run 1/3 (batch size 1)... + No token_ids in response, using local tokenization + Run 2/3 (batch size 1)... + Run 3/3 (batch size 1)... +Running test: pp=2048, tg=128, depth=0, concurrency=1 + Run 1/3 (batch size 1)... + Run 2/3 (batch size 1)... + Run 3/3 (batch size 1)... +Printing results in MD format: + + + +| model | test | t/s | peak t/s | ttfr (ms) | est_ppt (ms) | e2e_ttft (ms) | +|:---------------------------------------------------|-------:|--------------------:|-------------:|-------------:|---------------:|-----------------:| +| snapshots/38740b847e4cb78f352aba30aa41c76e08e6eb46 | pp512 | 111169.58 ± 4024.98 | | 5.75 ± 0.17 | 4.53 ± 0.17 | 416.81 ± 12.82 | +| snapshots/38740b847e4cb78f352aba30aa41c76e08e6eb46 | tg128 | 32.10 ± 0.44 | 33.33 ± 0.47 | | | | +| snapshots/38740b847e4cb78f352aba30aa41c76e08e6eb46 | pp2048 | 100701.62 ± 4191.80 | | 21.50 ± 0.82 | 20.28 ± 0.82 | 1917.87 ± 273.91 | +| snapshots/38740b847e4cb78f352aba30aa41c76e08e6eb46 | tg128 | 31.99 ± 0.18 | 33.00 ± 0.00 | | | | + +llama-benchy (0.3.7) +date: 2026-05-09 14:33:27 | latency mode: generation + +### Qwen3.6-35B [MTP] + +No model specified, attempting to auto-detect from endpoint... +Auto-detected HF model: snapshots/38740b847e4cb78f352aba30aa41c76e08e6eb46 (served as: snapshots/38740b847e4cb78f352aba30aa41c76e08e6eb46) +llama-benchy (0.3.7) +Date: 2026-05-09 14:34:03 +Benchmarking model: snapshots/38740b847e4cb78f352aba30aa41c76e08e6eb46 at http://localhost:18765/v1 +Concurrency levels: [1] +Loading text from cache: /Users/gg/.cache/llama-benchy/cc6a0b5782734ee3b9069aa3b64cc62c.txt +Total tokens available in text corpus: 144480 +Warming up... +Warmup (User only) complete. Delta: 9 tokens (Server: 30, Local: 21) +Warmup (System+Empty) complete. Delta: 7 tokens (Server: 28, Local: 21) + +Skipping coherence test (--skip-coherence specified) +Measuring latency using mode: generation... +Average latency (generation): 1.21 ms +Running test: pp=512, tg=128, depth=0, concurrency=1 + Run 1/3 (batch size 1)... + No token_ids in response, using local tokenization + Run 2/3 (batch size 1)... + Run 3/3 (batch size 1)... +Running test: pp=2048, tg=128, depth=0, concurrency=1 + Run 1/3 (batch size 1)... + Run 2/3 (batch size 1)... + Run 3/3 (batch size 1)... +Printing results in MD format: + + + +| model | test | t/s | peak t/s | ttfr (ms) | est_ppt (ms) | e2e_ttft (ms) | +|:---------------------------------------------------|-------:|--------------------:|-------------:|-------------:|---------------:|-----------------:| +| snapshots/38740b847e4cb78f352aba30aa41c76e08e6eb46 | pp512 | 99103.76 ± 6314.22 | | 6.31 ± 0.34 | 5.10 ± 0.34 | 440.21 ± 11.87 | +| snapshots/38740b847e4cb78f352aba30aa41c76e08e6eb46 | tg128 | 23.86 ± 1.07 | 27.33 ± 0.47 | | | | +| snapshots/38740b847e4cb78f352aba30aa41c76e08e6eb46 | pp2048 | 103984.37 ± 1021.88 | | 20.82 ± 0.19 | 19.61 ± 0.19 | 1791.70 ± 312.77 | +| snapshots/38740b847e4cb78f352aba30aa41c76e08e6eb46 | tg128 | 22.80 ± 0.54 | 27.67 ± 0.47 | | | | + +llama-benchy (0.3.7) +date: 2026-05-09 14:34:03 | latency mode: generation diff --git a/benchmarks/mtp-2026-05-09-183133.md b/benchmarks/mtp-2026-05-09-183133.md new file mode 100644 index 0000000000..ab4c3167d3 --- /dev/null +++ b/benchmarks/mtp-2026-05-09-183133.md @@ -0,0 +1,343 @@ +# MTP vs Baseline Benchmark + +## Environment + +| | | +|---|---| +| **Date** | 2026-05-09 22:31:36 UTC | +| **Commit** | `58e46dc` (mtp-support-perf) | +| **Chip** | Apple M4 Max | +| **GPU cores** | 40 | +| **RAM** | 64 GB | +| **macOS** | 26.4 (25E246) | +| **Swift** | Apple Swift version 6.3 (swiftlang-6.3.0.123.5 clang-2100.0.123.102) | +| **pp sizes** | 512 2048 | +| **tg sizes** | 128 | +| **runs** | 3 | + +## Results + +## Gemma 4 26B +### gemma-4-26b-a4b [baseline] + +No model specified, attempting to auto-detect from endpoint... +Auto-detected HF model: snapshots/695690b33533b1f8b0395c1d6b4f00dc411353ef (served as: snapshots/695690b33533b1f8b0395c1d6b4f00dc411353ef) +llama-benchy (0.3.7) +Date: 2026-05-09 18:31:46 +Benchmarking model: snapshots/695690b33533b1f8b0395c1d6b4f00dc411353ef at http://localhost:18765/v1 +Concurrency levels: [1] +Loading text from cache: /Users/gg/.cache/llama-benchy/cc6a0b5782734ee3b9069aa3b64cc62c.txt +Total tokens available in text corpus: 144040 +Warming up... +Warmup (User only) complete. Delta: 12 tokens (Server: 33, Local: 21) +Warmup (System+Empty) complete. Delta: 17 tokens (Server: 38, Local: 21) + +Skipping coherence test (--skip-coherence specified) +Measuring latency using mode: generation... +Average latency (generation): 1.20 ms +Running test: pp=512, tg=128, depth=0, concurrency=1 + Run 1/3 (batch size 1)... + No token_ids in response, using local tokenization + Run 2/3 (batch size 1)... + Run 3/3 (batch size 1)... +Running test: pp=2048, tg=128, depth=0, concurrency=1 + Run 1/3 (batch size 1)... + Run 2/3 (batch size 1)... + Run 3/3 (batch size 1)... +Printing results in MD format: + + + +| model | test | t/s | peak t/s | ttfr (ms) | est_ppt (ms) | e2e_ttft (ms) | +|:---------------------------------------------------|-------:|-----------------:|-------------:|-----------------:|-----------------:|-----------------:| +| snapshots/695690b33533b1f8b0395c1d6b4f00dc411353ef | pp512 | 3572.47 ± 355.39 | | 142.49 ± 13.42 | 141.29 ± 13.42 | 699.64 ± 24.75 | +| snapshots/695690b33533b1f8b0395c1d6b4f00dc411353ef | tg128 | 34.90 ± 0.08 | 36.00 ± 0.00 | | | | +| snapshots/695690b33533b1f8b0395c1d6b4f00dc411353ef | pp2048 | 1558.62 ± 128.82 | | 1317.02 ± 115.41 | 1315.82 ± 115.41 | 4281.15 ± 219.51 | +| snapshots/695690b33533b1f8b0395c1d6b4f00dc411353ef | tg128 | 33.86 ± 0.09 | 35.00 ± 0.00 | | | | + +llama-benchy (0.3.7) +date: 2026-05-09 18:31:46 | latency mode: generation + +### gemma-4-26b-a4b [MTP] + +No model specified, attempting to auto-detect from endpoint... +Auto-detected HF model: snapshots/695690b33533b1f8b0395c1d6b4f00dc411353ef (served as: snapshots/695690b33533b1f8b0395c1d6b4f00dc411353ef) +llama-benchy (0.3.7) +Date: 2026-05-09 18:32:30 +Benchmarking model: snapshots/695690b33533b1f8b0395c1d6b4f00dc411353ef at http://localhost:18765/v1 +Concurrency levels: [1] +Loading text from cache: /Users/gg/.cache/llama-benchy/cc6a0b5782734ee3b9069aa3b64cc62c.txt +Total tokens available in text corpus: 144040 +Warming up... +Warmup (User only) complete. Delta: 12 tokens (Server: 33, Local: 21) +Warmup (System+Empty) complete. Delta: 17 tokens (Server: 38, Local: 21) + +Skipping coherence test (--skip-coherence specified) +Measuring latency using mode: generation... +Average latency (generation): 1.34 ms +Running test: pp=512, tg=128, depth=0, concurrency=1 + Run 1/3 (batch size 1)... + No token_ids in response, using local tokenization + Run 2/3 (batch size 1)... + Run 3/3 (batch size 1)... +Running test: pp=2048, tg=128, depth=0, concurrency=1 + Run 1/3 (batch size 1)... + Run 2/3 (batch size 1)... + Run 3/3 (batch size 1)... +Printing results in MD format: + + + +| model | test | t/s | peak t/s | ttfr (ms) | est_ppt (ms) | e2e_ttft (ms) | +|:---------------------------------------------------|-------:|-----------------:|--------------:|-----------------:|-----------------:|-----------------:| +| snapshots/695690b33533b1f8b0395c1d6b4f00dc411353ef | pp512 | 3653.21 ± 346.16 | | 139.47 ± 13.34 | 138.13 ± 13.34 | 719.41 ± 27.56 | +| snapshots/695690b33533b1f8b0395c1d6b4f00dc411353ef | tg128 | 70.04 ± 6.86 | 78.00 ± 8.60 | | | | +| snapshots/695690b33533b1f8b0395c1d6b4f00dc411353ef | pp2048 | 1902.35 ± 197.99 | | 1082.57 ± 105.46 | 1081.23 ± 105.46 | 3933.20 ± 206.27 | +| snapshots/695690b33533b1f8b0395c1d6b4f00dc411353ef | tg128 | 49.72 ± 6.54 | 68.33 ± 13.10 | | | | + +llama-benchy (0.3.7) +date: 2026-05-09 18:32:30 | latency mode: generation + +## Gemma 4 31B +### gemma-4-31b [baseline] + +No model specified, attempting to auto-detect from endpoint... +Auto-detected HF model: snapshots/dcb78c3f5d6becacbfce71cd4851ad98c4f08a05 (served as: snapshots/dcb78c3f5d6becacbfce71cd4851ad98c4f08a05) +llama-benchy (0.3.7) +Date: 2026-05-09 18:33:05 +Benchmarking model: snapshots/dcb78c3f5d6becacbfce71cd4851ad98c4f08a05 at http://localhost:18765/v1 +Concurrency levels: [1] +Loading text from cache: /Users/gg/.cache/llama-benchy/cc6a0b5782734ee3b9069aa3b64cc62c.txt +Total tokens available in text corpus: 144040 +Warming up... +Warmup (User only) complete. Delta: 12 tokens (Server: 33, Local: 21) +Warmup (System+Empty) complete. Delta: 17 tokens (Server: 38, Local: 21) + +Skipping coherence test (--skip-coherence specified) +Measuring latency using mode: generation... +Average latency (generation): 1.25 ms +Running test: pp=512, tg=128, depth=0, concurrency=1 + Run 1/3 (batch size 1)... + No token_ids in response, using local tokenization + Run 2/3 (batch size 1)... + Run 3/3 (batch size 1)... +Running test: pp=2048, tg=128, depth=0, concurrency=1 + Run 1/3 (batch size 1)... + Run 2/3 (batch size 1)... + Run 3/3 (batch size 1)... +Printing results in MD format: + + + +| model | test | t/s | peak t/s | ttfr (ms) | est_ppt (ms) | e2e_ttft (ms) | +|:---------------------------------------------------|-------:|-----------------:|-------------:|-----------------:|-----------------:|-------------------:| +| snapshots/dcb78c3f5d6becacbfce71cd4851ad98c4f08a05 | pp512 | 3059.76 ± 606.55 | | 171.85 ± 36.53 | 170.60 ± 36.53 | 4345.46 ± 668.65 | +| snapshots/dcb78c3f5d6becacbfce71cd4851ad98c4f08a05 | tg128 | 10.73 ± 1.47 | 16.67 ± 0.47 | | | | +| snapshots/dcb78c3f5d6becacbfce71cd4851ad98c4f08a05 | pp2048 | 1364.91 ± 339.78 | | 1583.12 ± 366.70 | 1581.87 ± 366.70 | 22628.68 ± 7241.84 | +| snapshots/dcb78c3f5d6becacbfce71cd4851ad98c4f08a05 | tg128 | 9.58 ± 3.45 | 13.67 ± 3.30 | | | | + +llama-benchy (0.3.7) +date: 2026-05-09 18:33:05 | latency mode: generation + +### gemma-4-31b [MTP] + +No model specified, attempting to auto-detect from endpoint... +Auto-detected HF model: snapshots/dcb78c3f5d6becacbfce71cd4851ad98c4f08a05 (served as: snapshots/dcb78c3f5d6becacbfce71cd4851ad98c4f08a05) +llama-benchy (0.3.7) +Date: 2026-05-09 18:35:55 +Benchmarking model: snapshots/dcb78c3f5d6becacbfce71cd4851ad98c4f08a05 at http://localhost:18765/v1 +Concurrency levels: [1] +Loading text from cache: /Users/gg/.cache/llama-benchy/cc6a0b5782734ee3b9069aa3b64cc62c.txt +Total tokens available in text corpus: 144040 +Warming up... +Warmup (User only) complete. Delta: 12 tokens (Server: 33, Local: 21) +Warmup (System+Empty) complete. Delta: 17 tokens (Server: 38, Local: 21) + +Skipping coherence test (--skip-coherence specified) +Measuring latency using mode: generation... +Average latency (generation): 1.26 ms +Running test: pp=512, tg=128, depth=0, concurrency=1 + Run 1/3 (batch size 1)... + No token_ids in response, using local tokenization + Run 2/3 (batch size 1)... + Run 3/3 (batch size 1)... +Running test: pp=2048, tg=128, depth=0, concurrency=1 + Run 1/3 (batch size 1)... + Run 2/3 (batch size 1)... + Run 3/3 (batch size 1)... +Printing results in MD format: + + + +| model | test | t/s | peak t/s | ttfr (ms) | est_ppt (ms) | e2e_ttft (ms) | +|:---------------------------------------------------|-------:|-----------------:|-------------:|----------------:|----------------:|-------------------:| +| snapshots/dcb78c3f5d6becacbfce71cd4851ad98c4f08a05 | pp512 | 3447.11 ± 582.21 | | 150.11 ± 22.52 | 148.85 ± 22.52 | 6355.52 ± 86.22 | +| snapshots/dcb78c3f5d6becacbfce71cd4851ad98c4f08a05 | tg128 | 9.86 ± 1.12 | 17.67 ± 1.25 | | | | +| snapshots/dcb78c3f5d6becacbfce71cd4851ad98c4f08a05 | pp2048 | 1554.95 ± 82.66 | | 1314.49 ± 72.48 | 1313.22 ± 72.48 | 22967.63 ± 1455.44 | +| snapshots/dcb78c3f5d6becacbfce71cd4851ad98c4f08a05 | tg128 | 5.66 ± 0.51 | 9.67 ± 0.94 | | | | + +llama-benchy (0.3.7) +date: 2026-05-09 18:35:55 | latency mode: generation + +## Qwen3.6 27B +### Qwen3.6-27B [baseline] + +No model specified, attempting to auto-detect from endpoint... +Auto-detected HF model: snapshots/c000ac2c2057d94be3fa931000c31723aac53282 (served as: snapshots/c000ac2c2057d94be3fa931000c31723aac53282) +llama-benchy (0.3.7) +Date: 2026-05-09 18:39:17 +Benchmarking model: snapshots/c000ac2c2057d94be3fa931000c31723aac53282 at http://localhost:18765/v1 +Concurrency levels: [1] +Loading text from cache: /Users/gg/.cache/llama-benchy/cc6a0b5782734ee3b9069aa3b64cc62c.txt +Total tokens available in text corpus: 144480 +Warming up... +Warmup (User only) complete. Delta: 9 tokens (Server: 30, Local: 21) +Warmup (System+Empty) complete. Delta: 7 tokens (Server: 28, Local: 21) + +Skipping coherence test (--skip-coherence specified) +Measuring latency using mode: generation... +Average latency (generation): 1.21 ms +Running test: pp=512, tg=128, depth=0, concurrency=1 + Run 1/3 (batch size 1)... + No token_ids in response, using local tokenization + Run 2/3 (batch size 1)... + Run 3/3 (batch size 1)... +Running test: pp=2048, tg=128, depth=0, concurrency=1 + Run 1/3 (batch size 1)... + Run 2/3 (batch size 1)... + Run 3/3 (batch size 1)... +Printing results in MD format: + + + +| model | test | t/s | peak t/s | ttfr (ms) | est_ppt (ms) | e2e_ttft (ms) | +|:---------------------------------------------------|-------:|--------------------:|-------------:|-------------:|---------------:|-----------------:| +| snapshots/c000ac2c2057d94be3fa931000c31723aac53282 | pp512 | 76810.72 ± 16151.45 | | 8.07 ± 1.52 | 6.87 ± 1.52 | 3519.40 ± 649.03 | +| snapshots/c000ac2c2057d94be3fa931000c31723aac53282 | tg128 | 15.62 ± 0.39 | 20.00 ± 0.00 | | | | +| snapshots/c000ac2c2057d94be3fa931000c31723aac53282 | pp2048 | 61363.76 ± 8699.27 | | 35.14 ± 4.97 | 33.93 ± 4.97 | 13845.11 ± 45.05 | +| snapshots/c000ac2c2057d94be3fa931000c31723aac53282 | tg128 | 15.45 ± 0.26 | 20.00 ± 0.00 | | | | + +llama-benchy (0.3.7) +date: 2026-05-09 18:39:17 | latency mode: generation + +### Qwen3.6-27B [MTP] + +No model specified, attempting to auto-detect from endpoint... +Auto-detected HF model: snapshots/c000ac2c2057d94be3fa931000c31723aac53282 (served as: snapshots/c000ac2c2057d94be3fa931000c31723aac53282) +llama-benchy (0.3.7) +Date: 2026-05-09 18:41:06 +Benchmarking model: snapshots/c000ac2c2057d94be3fa931000c31723aac53282 at http://localhost:18765/v1 +Concurrency levels: [1] +Loading text from cache: /Users/gg/.cache/llama-benchy/cc6a0b5782734ee3b9069aa3b64cc62c.txt +Total tokens available in text corpus: 144480 +Warming up... +Warmup (User only) complete. Delta: 9 tokens (Server: 30, Local: 21) +Warmup (System+Empty) complete. Delta: 7 tokens (Server: 28, Local: 21) + +Skipping coherence test (--skip-coherence specified) +Measuring latency using mode: generation... +Average latency (generation): 1.13 ms +Running test: pp=512, tg=128, depth=0, concurrency=1 + Run 1/3 (batch size 1)... + No token_ids in response, using local tokenization + Run 2/3 (batch size 1)... + Run 3/3 (batch size 1)... +Running test: pp=2048, tg=128, depth=0, concurrency=1 + Run 1/3 (batch size 1)... + Run 2/3 (batch size 1)... + Run 3/3 (batch size 1)... +Printing results in MD format: + + + +| model | test | t/s | peak t/s | ttfr (ms) | est_ppt (ms) | e2e_ttft (ms) | +|:---------------------------------------------------|-------:|--------------------:|-------------:|-------------:|---------------:|-----------------:| +| snapshots/c000ac2c2057d94be3fa931000c31723aac53282 | pp512 | 97679.39 ± 4203.98 | | 6.29 ± 0.22 | 5.16 ± 0.22 | 3455.11 ± 606.21 | +| snapshots/c000ac2c2057d94be3fa931000c31723aac53282 | tg128 | 21.24 ± 0.85 | 36.00 ± 2.94 | | | | +| snapshots/c000ac2c2057d94be3fa931000c31723aac53282 | pp2048 | 104318.12 ± 3658.44 | | 20.70 ± 0.70 | 19.57 ± 0.70 | 14009.85 ± 58.22 | +| snapshots/c000ac2c2057d94be3fa931000c31723aac53282 | tg128 | 20.78 ± 1.28 | 32.67 ± 0.47 | | | | + +llama-benchy (0.3.7) +date: 2026-05-09 18:41:06 | latency mode: generation + +## Qwen3.6 35B +### Qwen3.6-35B [baseline] + +No model specified, attempting to auto-detect from endpoint... +Auto-detected HF model: snapshots/38740b847e4cb78f352aba30aa41c76e08e6eb46 (served as: snapshots/38740b847e4cb78f352aba30aa41c76e08e6eb46) +llama-benchy (0.3.7) +Date: 2026-05-09 18:42:43 +Benchmarking model: snapshots/38740b847e4cb78f352aba30aa41c76e08e6eb46 at http://localhost:18765/v1 +Concurrency levels: [1] +Loading text from cache: /Users/gg/.cache/llama-benchy/cc6a0b5782734ee3b9069aa3b64cc62c.txt +Total tokens available in text corpus: 144480 +Warming up... +Warmup (User only) complete. Delta: 9 tokens (Server: 30, Local: 21) +Warmup (System+Empty) complete. Delta: 7 tokens (Server: 28, Local: 21) + +Skipping coherence test (--skip-coherence specified) +Measuring latency using mode: generation... +Average latency (generation): 1.26 ms +Running test: pp=512, tg=128, depth=0, concurrency=1 + Run 1/3 (batch size 1)... + No token_ids in response, using local tokenization + Run 2/3 (batch size 1)... + Run 3/3 (batch size 1)... +Running test: pp=2048, tg=128, depth=0, concurrency=1 + Run 1/3 (batch size 1)... + Run 2/3 (batch size 1)... + Run 3/3 (batch size 1)... +Printing results in MD format: + + + +| model | test | t/s | peak t/s | ttfr (ms) | est_ppt (ms) | e2e_ttft (ms) | +|:---------------------------------------------------|-------:|---------------------:|-------------:|-------------:|---------------:|-----------------:| +| snapshots/38740b847e4cb78f352aba30aa41c76e08e6eb46 | pp512 | 109411.59 ± 12941.91 | | 5.92 ± 0.57 | 4.67 ± 0.57 | 400.82 ± 2.15 | +| snapshots/38740b847e4cb78f352aba30aa41c76e08e6eb46 | tg128 | 36.01 ± 0.14 | 37.00 ± 0.00 | | | | +| snapshots/38740b847e4cb78f352aba30aa41c76e08e6eb46 | pp2048 | 110534.21 ± 3112.65 | | 19.72 ± 0.51 | 18.46 ± 0.51 | 1893.90 ± 140.09 | +| snapshots/38740b847e4cb78f352aba30aa41c76e08e6eb46 | tg128 | 35.67 ± 0.15 | 37.00 ± 0.00 | | | | + +llama-benchy (0.3.7) +date: 2026-05-09 18:42:43 | latency mode: generation + +### Qwen3.6-35B [MTP] + +No model specified, attempting to auto-detect from endpoint... +Auto-detected HF model: snapshots/38740b847e4cb78f352aba30aa41c76e08e6eb46 (served as: snapshots/38740b847e4cb78f352aba30aa41c76e08e6eb46) +llama-benchy (0.3.7) +Date: 2026-05-09 18:43:17 +Benchmarking model: snapshots/38740b847e4cb78f352aba30aa41c76e08e6eb46 at http://localhost:18765/v1 +Concurrency levels: [1] +Loading text from cache: /Users/gg/.cache/llama-benchy/cc6a0b5782734ee3b9069aa3b64cc62c.txt +Total tokens available in text corpus: 144480 +Warming up... +Warmup (User only) complete. Delta: 9 tokens (Server: 30, Local: 21) +Warmup (System+Empty) complete. Delta: 7 tokens (Server: 28, Local: 21) + +Skipping coherence test (--skip-coherence specified) +Measuring latency using mode: generation... +Average latency (generation): 1.16 ms +Running test: pp=512, tg=128, depth=0, concurrency=1 + Run 1/3 (batch size 1)... + No token_ids in response, using local tokenization + Run 2/3 (batch size 1)... + Run 3/3 (batch size 1)... +Running test: pp=2048, tg=128, depth=0, concurrency=1 + Run 1/3 (batch size 1)... + Run 2/3 (batch size 1)... + Run 3/3 (batch size 1)... +Printing results in MD format: + + + +| model | test | t/s | peak t/s | ttfr (ms) | est_ppt (ms) | e2e_ttft (ms) | +|:---------------------------------------------------|-------:|---------------------:|--------------:|-------------:|---------------:|-----------------:| +| snapshots/38740b847e4cb78f352aba30aa41c76e08e6eb46 | pp512 | 114351.98 ± 6943.46 | | 5.57 ± 0.26 | 4.41 ± 0.26 | 437.65 ± 22.78 | +| snapshots/38740b847e4cb78f352aba30aa41c76e08e6eb46 | tg128 | 110.64 ± 7.93 | 111.67 ± 6.94 | | | | +| snapshots/38740b847e4cb78f352aba30aa41c76e08e6eb46 | pp2048 | 103896.86 ± 10209.87 | | 20.98 ± 1.99 | 19.82 ± 1.99 | 2567.51 ± 122.77 | +| snapshots/38740b847e4cb78f352aba30aa41c76e08e6eb46 | tg128 | 102.22 ± 2.00 | 105.33 ± 2.62 | | | | + +llama-benchy (0.3.7) +date: 2026-05-09 18:43:17 | latency mode: generation + diff --git a/benchmarks/mtp-2026-05-09-190948.md b/benchmarks/mtp-2026-05-09-190948.md new file mode 100644 index 0000000000..6528a45f12 --- /dev/null +++ b/benchmarks/mtp-2026-05-09-190948.md @@ -0,0 +1,375 @@ +# MTP vs Baseline Benchmark + +## Environment + +| | | +|---|---| +| **Date** | 2026-05-09 23:09:52 UTC | +| **Commit** | `c6e7df2` (mtp-support-perf) | +| **Chip** | Apple M4 Max | +| **GPU cores** | 40 | +| **RAM** | 64 GB | +| **macOS** | 26.4 (25E246) | +| **Swift** | Apple Swift version 6.3 (swiftlang-6.3.0.123.5 clang-2100.0.123.102) | +| **pp sizes** | 512 2048 | +| **tg sizes** | 128 | +| **runs** | 5 | + +## Results + +## Gemma 4 26B +### gemma-4-26b-a4b [baseline] + +No model specified, attempting to auto-detect from endpoint... +Auto-detected HF model: snapshots/695690b33533b1f8b0395c1d6b4f00dc411353ef (served as: snapshots/695690b33533b1f8b0395c1d6b4f00dc411353ef) +llama-benchy (0.3.7) +Date: 2026-05-09 19:09:58 +Benchmarking model: snapshots/695690b33533b1f8b0395c1d6b4f00dc411353ef at http://localhost:18765/v1 +Concurrency levels: [1] +Loading text from cache: /Users/gg/.cache/llama-benchy/cc6a0b5782734ee3b9069aa3b64cc62c.txt +Total tokens available in text corpus: 144040 +Warming up... +Warmup (User only) complete. Delta: 12 tokens (Server: 33, Local: 21) +Warmup (System+Empty) complete. Delta: 17 tokens (Server: 38, Local: 21) + +Skipping coherence test (--skip-coherence specified) +Measuring latency using mode: generation... +Average latency (generation): 1.18 ms +Running test: pp=512, tg=128, depth=0, concurrency=1 + Run 1/5 (batch size 1)... + No token_ids in response, using local tokenization + Run 2/5 (batch size 1)... + Run 3/5 (batch size 1)... + Run 4/5 (batch size 1)... + Run 5/5 (batch size 1)... +Running test: pp=2048, tg=128, depth=0, concurrency=1 + Run 1/5 (batch size 1)... + Run 2/5 (batch size 1)... + Run 3/5 (batch size 1)... + Run 4/5 (batch size 1)... + Run 5/5 (batch size 1)... +Printing results in MD format: + + + +| model | test | t/s | peak t/s | ttfr (ms) | est_ppt (ms) | e2e_ttft (ms) | +|:---------------------------------------------------|-------:|-----------------:|-------------:|-----------------:|-----------------:|-----------------:| +| snapshots/695690b33533b1f8b0395c1d6b4f00dc411353ef | pp512 | 4244.81 ± 484.95 | | 120.67 ± 14.92 | 119.49 ± 14.92 | 660.97 ± 28.83 | +| snapshots/695690b33533b1f8b0395c1d6b4f00dc411353ef | tg128 | 34.72 ± 0.50 | 35.80 ± 0.40 | | | | +| snapshots/695690b33533b1f8b0395c1d6b4f00dc411353ef | pp2048 | 1781.36 ± 268.02 | | 1170.26 ± 174.71 | 1169.08 ± 174.71 | 3906.07 ± 333.31 | +| snapshots/695690b33533b1f8b0395c1d6b4f00dc411353ef | tg128 | 34.17 ± 0.16 | 35.00 ± 0.00 | | | | + +llama-benchy (0.3.7) +date: 2026-05-09 19:09:58 | latency mode: generation + +### gemma-4-26b-a4b [MTP] + +No model specified, attempting to auto-detect from endpoint... +Auto-detected HF model: snapshots/695690b33533b1f8b0395c1d6b4f00dc411353ef (served as: snapshots/695690b33533b1f8b0395c1d6b4f00dc411353ef) +llama-benchy (0.3.7) +Date: 2026-05-09 19:11:06 +Benchmarking model: snapshots/695690b33533b1f8b0395c1d6b4f00dc411353ef at http://localhost:18765/v1 +Concurrency levels: [1] +Loading text from cache: /Users/gg/.cache/llama-benchy/cc6a0b5782734ee3b9069aa3b64cc62c.txt +Total tokens available in text corpus: 144040 +Warming up... +Warmup (User only) complete. Delta: 12 tokens (Server: 33, Local: 21) +Warmup (System+Empty) complete. Delta: 17 tokens (Server: 38, Local: 21) + +Skipping coherence test (--skip-coherence specified) +Measuring latency using mode: generation... +Average latency (generation): 1.14 ms +Running test: pp=512, tg=128, depth=0, concurrency=1 + Run 1/5 (batch size 1)... + No token_ids in response, using local tokenization + Run 2/5 (batch size 1)... + Run 3/5 (batch size 1)... + Run 4/5 (batch size 1)... + Run 5/5 (batch size 1)... +Running test: pp=2048, tg=128, depth=0, concurrency=1 + Run 1/5 (batch size 1)... + Run 2/5 (batch size 1)... + Run 3/5 (batch size 1)... + Run 4/5 (batch size 1)... + Run 5/5 (batch size 1)... +Printing results in MD format: + + + +| model | test | t/s | peak t/s | ttfr (ms) | est_ppt (ms) | e2e_ttft (ms) | +|:---------------------------------------------------|-------:|-----------------:|--------------:|-----------------:|-----------------:|-----------------:| +| snapshots/695690b33533b1f8b0395c1d6b4f00dc411353ef | pp512 | 3837.86 ± 407.81 | | 132.94 ± 14.25 | 131.79 ± 14.25 | 767.70 ± 115.71 | +| snapshots/695690b33533b1f8b0395c1d6b4f00dc411353ef | tg128 | 63.31 ± 6.45 | 70.60 ± 7.23 | | | | +| snapshots/695690b33533b1f8b0395c1d6b4f00dc411353ef | pp2048 | 1590.31 ± 160.44 | | 1293.48 ± 120.09 | 1292.34 ± 120.09 | 4556.32 ± 355.09 | +| snapshots/695690b33533b1f8b0395c1d6b4f00dc411353ef | tg128 | 47.59 ± 9.45 | 64.20 ± 16.73 | | | | + +llama-benchy (0.3.7) +date: 2026-05-09 19:11:06 | latency mode: generation + +## Gemma 4 31B +### gemma-4-31b [baseline] + +No model specified, attempting to auto-detect from endpoint... +Auto-detected HF model: snapshots/dcb78c3f5d6becacbfce71cd4851ad98c4f08a05 (served as: snapshots/dcb78c3f5d6becacbfce71cd4851ad98c4f08a05) +llama-benchy (0.3.7) +Date: 2026-05-09 19:12:05 +Benchmarking model: snapshots/dcb78c3f5d6becacbfce71cd4851ad98c4f08a05 at http://localhost:18765/v1 +Concurrency levels: [1] +Loading text from cache: /Users/gg/.cache/llama-benchy/cc6a0b5782734ee3b9069aa3b64cc62c.txt +Total tokens available in text corpus: 144040 +Warming up... +Warmup (User only) complete. Delta: 12 tokens (Server: 33, Local: 21) +Warmup (System+Empty) complete. Delta: 17 tokens (Server: 38, Local: 21) + +Skipping coherence test (--skip-coherence specified) +Measuring latency using mode: generation... +Average latency (generation): 1.19 ms +Running test: pp=512, tg=128, depth=0, concurrency=1 + Run 1/5 (batch size 1)... + No token_ids in response, using local tokenization + Run 2/5 (batch size 1)... + Run 3/5 (batch size 1)... + Run 4/5 (batch size 1)... + Run 5/5 (batch size 1)... +Running test: pp=2048, tg=128, depth=0, concurrency=1 + Run 1/5 (batch size 1)... + Run 2/5 (batch size 1)... + Run 3/5 (batch size 1)... + Run 4/5 (batch size 1)... + Run 5/5 (batch size 1)... +Printing results in MD format: + + + +| model | test | t/s | peak t/s | ttfr (ms) | est_ppt (ms) | e2e_ttft (ms) | +|:---------------------------------------------------|-------:|-----------------:|-------------:|-----------------:|-----------------:|-------------------:| +| snapshots/dcb78c3f5d6becacbfce71cd4851ad98c4f08a05 | pp512 | 1928.96 ± 883.00 | | 298.27 ± 83.84 | 297.08 ± 83.84 | 5586.09 ± 1019.57 | +| snapshots/dcb78c3f5d6becacbfce71cd4851ad98c4f08a05 | tg128 | 7.74 ± 1.50 | 16.40 ± 0.80 | | | | +| snapshots/dcb78c3f5d6becacbfce71cd4851ad98c4f08a05 | pp2048 | 992.87 ± 269.31 | | 2204.98 ± 590.88 | 2203.79 ± 590.88 | 23698.41 ± 2644.05 | +| snapshots/dcb78c3f5d6becacbfce71cd4851ad98c4f08a05 | tg128 | 10.00 ± 1.31 | 15.40 ± 0.80 | | | | + +llama-benchy (0.3.7) +date: 2026-05-09 19:12:05 | latency mode: generation + +### gemma-4-31b [MTP] + +No model specified, attempting to auto-detect from endpoint... +Auto-detected HF model: snapshots/dcb78c3f5d6becacbfce71cd4851ad98c4f08a05 (served as: snapshots/dcb78c3f5d6becacbfce71cd4851ad98c4f08a05) +llama-benchy (0.3.7) +Date: 2026-05-09 19:17:09 +Benchmarking model: snapshots/dcb78c3f5d6becacbfce71cd4851ad98c4f08a05 at http://localhost:18765/v1 +Concurrency levels: [1] +Loading text from cache: /Users/gg/.cache/llama-benchy/cc6a0b5782734ee3b9069aa3b64cc62c.txt +Total tokens available in text corpus: 144040 +Warming up... +Warmup (User only) complete. Delta: 12 tokens (Server: 33, Local: 21) +Warmup (System+Empty) complete. Delta: 17 tokens (Server: 38, Local: 21) + +Skipping coherence test (--skip-coherence specified) +Measuring latency using mode: generation... +Average latency (generation): 1.14 ms +Running test: pp=512, tg=128, depth=0, concurrency=1 + Run 1/5 (batch size 1)... + No token_ids in response, using local tokenization + Run 2/5 (batch size 1)... + Run 3/5 (batch size 1)... + Run 4/5 (batch size 1)... + Run 5/5 (batch size 1)... +Running test: pp=2048, tg=128, depth=0, concurrency=1 + Run 1/5 (batch size 1)... + Run 2/5 (batch size 1)... + Run 3/5 (batch size 1)... + Run 4/5 (batch size 1)... + Run 5/5 (batch size 1)... +Printing results in MD format: + + + +| model | test | t/s | peak t/s | ttfr (ms) | est_ppt (ms) | e2e_ttft (ms) | +|:---------------------------------------------------|-------:|-----------------:|-------------:|----------------:|----------------:|------------------:| +| snapshots/dcb78c3f5d6becacbfce71cd4851ad98c4f08a05 | pp512 | 4235.64 ± 817.33 | | 123.71 ± 23.72 | 122.57 ± 23.72 | 4596.77 ± 656.37 | +| snapshots/dcb78c3f5d6becacbfce71cd4851ad98c4f08a05 | tg128 | 13.72 ± 2.32 | 20.00 ± 2.61 | | | | +| snapshots/dcb78c3f5d6becacbfce71cd4851ad98c4f08a05 | pp2048 | 1814.75 ± 156.57 | | 1131.15 ± 93.82 | 1130.01 ± 93.82 | 20582.64 ± 624.05 | +| snapshots/dcb78c3f5d6becacbfce71cd4851ad98c4f08a05 | tg128 | 8.17 ± 2.03 | 15.80 ± 4.87 | | | | + +llama-benchy (0.3.7) +date: 2026-05-09 19:17:09 | latency mode: generation + +## Qwen3.6 27B +### Qwen3.6-27B [baseline] + +No model specified, attempting to auto-detect from endpoint... +Auto-detected HF model: snapshots/c000ac2c2057d94be3fa931000c31723aac53282 (served as: snapshots/c000ac2c2057d94be3fa931000c31723aac53282) +llama-benchy (0.3.7) +Date: 2026-05-09 19:21:33 +Benchmarking model: snapshots/c000ac2c2057d94be3fa931000c31723aac53282 at http://localhost:18765/v1 +Concurrency levels: [1] +Loading text from cache: /Users/gg/.cache/llama-benchy/cc6a0b5782734ee3b9069aa3b64cc62c.txt +Total tokens available in text corpus: 144480 +Warming up... +Warmup (User only) complete. Delta: 9 tokens (Server: 30, Local: 21) +Warmup (System+Empty) complete. Delta: 7 tokens (Server: 28, Local: 21) + +Skipping coherence test (--skip-coherence specified) +Measuring latency using mode: generation... +Average latency (generation): 1.12 ms +Running test: pp=512, tg=128, depth=0, concurrency=1 + Run 1/5 (batch size 1)... + No token_ids in response, using local tokenization + Run 2/5 (batch size 1)... + Run 3/5 (batch size 1)... + Run 4/5 (batch size 1)... + Run 5/5 (batch size 1)... +Running test: pp=2048, tg=128, depth=0, concurrency=1 + Run 1/5 (batch size 1)... + Run 2/5 (batch size 1)... + Run 3/5 (batch size 1)... + Run 4/5 (batch size 1)... + Run 5/5 (batch size 1)... +Printing results in MD format: + + + +| model | test | t/s | peak t/s | ttfr (ms) | est_ppt (ms) | e2e_ttft (ms) | +|:---------------------------------------------------|-------:|--------------------:|-------------:|-------------:|---------------:|------------------:| +| snapshots/c000ac2c2057d94be3fa931000c31723aac53282 | pp512 | 66528.77 ± 21492.59 | | 9.37 ± 2.19 | 8.25 ± 2.19 | 3747.96 ± 668.96 | +| snapshots/c000ac2c2057d94be3fa931000c31723aac53282 | tg128 | 15.04 ± 0.53 | 20.80 ± 0.40 | | | | +| snapshots/c000ac2c2057d94be3fa931000c31723aac53282 | pp2048 | 67356.06 ± 2693.03 | | 31.44 ± 1.23 | 30.32 ± 1.23 | 14105.24 ± 169.08 | +| snapshots/c000ac2c2057d94be3fa931000c31723aac53282 | tg128 | 15.05 ± 0.59 | 20.00 ± 0.00 | | | | + +llama-benchy (0.3.7) +date: 2026-05-09 19:21:33 | latency mode: generation + +### Qwen3.6-27B [MTP] + +No model specified, attempting to auto-detect from endpoint... +Auto-detected HF model: snapshots/c000ac2c2057d94be3fa931000c31723aac53282 (served as: snapshots/c000ac2c2057d94be3fa931000c31723aac53282) +llama-benchy (0.3.7) +Date: 2026-05-09 19:24:34 +Benchmarking model: snapshots/c000ac2c2057d94be3fa931000c31723aac53282 at http://localhost:18765/v1 +Concurrency levels: [1] +Loading text from cache: /Users/gg/.cache/llama-benchy/cc6a0b5782734ee3b9069aa3b64cc62c.txt +Total tokens available in text corpus: 144480 +Warming up... +Warmup (User only) complete. Delta: 9 tokens (Server: 30, Local: 21) +Warmup (System+Empty) complete. Delta: 7 tokens (Server: 28, Local: 21) + +Skipping coherence test (--skip-coherence specified) +Measuring latency using mode: generation... +Average latency (generation): 1.36 ms +Running test: pp=512, tg=128, depth=0, concurrency=1 + Run 1/5 (batch size 1)... + No token_ids in response, using local tokenization + Run 2/5 (batch size 1)... + Run 3/5 (batch size 1)... + Run 4/5 (batch size 1)... + Run 5/5 (batch size 1)... +Running test: pp=2048, tg=128, depth=0, concurrency=1 + Run 1/5 (batch size 1)... + Run 2/5 (batch size 1)... + Run 3/5 (batch size 1)... + Run 4/5 (batch size 1)... + Run 5/5 (batch size 1)... +Printing results in MD format: + + + +| model | test | t/s | peak t/s | ttfr (ms) | est_ppt (ms) | e2e_ttft (ms) | +|:---------------------------------------------------|-------:|--------------------:|-------------:|-------------:|---------------:|------------------:| +| snapshots/c000ac2c2057d94be3fa931000c31723aac53282 | pp512 | 105149.07 ± 8467.34 | | 6.18 ± 0.43 | 4.82 ± 0.43 | 3814.01 ± 157.35 | +| snapshots/c000ac2c2057d94be3fa931000c31723aac53282 | tg128 | 21.17 ± 1.17 | 34.20 ± 1.60 | | | | +| snapshots/c000ac2c2057d94be3fa931000c31723aac53282 | pp2048 | 105295.83 ± 7895.96 | | 20.85 ± 1.62 | 19.49 ± 1.62 | 13980.88 ± 279.26 | +| snapshots/c000ac2c2057d94be3fa931000c31723aac53282 | tg128 | 19.63 ± 1.16 | 32.80 ± 1.17 | | | | + +llama-benchy (0.3.7) +date: 2026-05-09 19:24:34 | latency mode: generation + +## Qwen3.6 35B +### Qwen3.6-35B [baseline] + +No model specified, attempting to auto-detect from endpoint... +Auto-detected HF model: snapshots/38740b847e4cb78f352aba30aa41c76e08e6eb46 (served as: snapshots/38740b847e4cb78f352aba30aa41c76e08e6eb46) +llama-benchy (0.3.7) +Date: 2026-05-09 19:27:13 +Benchmarking model: snapshots/38740b847e4cb78f352aba30aa41c76e08e6eb46 at http://localhost:18765/v1 +Concurrency levels: [1] +Loading text from cache: /Users/gg/.cache/llama-benchy/cc6a0b5782734ee3b9069aa3b64cc62c.txt +Total tokens available in text corpus: 144480 +Warming up... +Warmup (User only) complete. Delta: 9 tokens (Server: 30, Local: 21) +Warmup (System+Empty) complete. Delta: 7 tokens (Server: 28, Local: 21) + +Skipping coherence test (--skip-coherence specified) +Measuring latency using mode: generation... +Average latency (generation): 1.11 ms +Running test: pp=512, tg=128, depth=0, concurrency=1 + Run 1/5 (batch size 1)... + No token_ids in response, using local tokenization + Run 2/5 (batch size 1)... + Run 3/5 (batch size 1)... + Run 4/5 (batch size 1)... + Run 5/5 (batch size 1)... +Running test: pp=2048, tg=128, depth=0, concurrency=1 + Run 1/5 (batch size 1)... + Run 2/5 (batch size 1)... + Run 3/5 (batch size 1)... + Run 4/5 (batch size 1)... + Run 5/5 (batch size 1)... +Printing results in MD format: + + + +| model | test | t/s | peak t/s | ttfr (ms) | est_ppt (ms) | e2e_ttft (ms) | +|:---------------------------------------------------|-------:|--------------------:|-------------:|-------------:|---------------:|-----------------:| +| snapshots/38740b847e4cb78f352aba30aa41c76e08e6eb46 | pp512 | 102578.63 ± 4880.56 | | 6.03 ± 0.24 | 4.92 ± 0.24 | 415.78 ± 12.44 | +| snapshots/38740b847e4cb78f352aba30aa41c76e08e6eb46 | tg128 | 36.53 ± 0.21 | 37.80 ± 0.40 | | | | +| snapshots/38740b847e4cb78f352aba30aa41c76e08e6eb46 | pp2048 | 107169.47 ± 2596.67 | | 20.15 ± 0.46 | 19.04 ± 0.46 | 2069.34 ± 100.59 | +| snapshots/38740b847e4cb78f352aba30aa41c76e08e6eb46 | tg128 | 36.06 ± 0.16 | 37.20 ± 0.40 | | | | + +llama-benchy (0.3.7) +date: 2026-05-09 19:27:13 | latency mode: generation + +### Qwen3.6-35B [MTP] + +No model specified, attempting to auto-detect from endpoint... +Auto-detected HF model: snapshots/38740b847e4cb78f352aba30aa41c76e08e6eb46 (served as: snapshots/38740b847e4cb78f352aba30aa41c76e08e6eb46) +llama-benchy (0.3.7) +Date: 2026-05-09 19:28:07 +Benchmarking model: snapshots/38740b847e4cb78f352aba30aa41c76e08e6eb46 at http://localhost:18765/v1 +Concurrency levels: [1] +Loading text from cache: /Users/gg/.cache/llama-benchy/cc6a0b5782734ee3b9069aa3b64cc62c.txt +Total tokens available in text corpus: 144480 +Warming up... +Warmup (User only) complete. Delta: 9 tokens (Server: 30, Local: 21) +Warmup (System+Empty) complete. Delta: 7 tokens (Server: 28, Local: 21) + +Skipping coherence test (--skip-coherence specified) +Measuring latency using mode: generation... +Average latency (generation): 1.10 ms +Running test: pp=512, tg=128, depth=0, concurrency=1 + Run 1/5 (batch size 1)... + No token_ids in response, using local tokenization + Run 2/5 (batch size 1)... + Run 3/5 (batch size 1)... + Run 4/5 (batch size 1)... + Run 5/5 (batch size 1)... +Running test: pp=2048, tg=128, depth=0, concurrency=1 + Run 1/5 (batch size 1)... + Run 2/5 (batch size 1)... + Run 3/5 (batch size 1)... + Run 4/5 (batch size 1)... + Run 5/5 (batch size 1)... +Printing results in MD format: + + + +| model | test | t/s | peak t/s | ttfr (ms) | est_ppt (ms) | e2e_ttft (ms) | +|:---------------------------------------------------|-------:|--------------------:|---------------:|-------------:|---------------:|----------------:| +| snapshots/38740b847e4cb78f352aba30aa41c76e08e6eb46 | pp512 | 105175.60 ± 6399.30 | | 5.90 ± 0.30 | 4.80 ± 0.30 | 516.98 ± 119.12 | +| snapshots/38740b847e4cb78f352aba30aa41c76e08e6eb46 | tg128 | 102.63 ± 11.31 | 104.40 ± 11.48 | | | | +| snapshots/38740b847e4cb78f352aba30aa41c76e08e6eb46 | pp2048 | 108027.19 ± 1302.37 | | 19.98 ± 0.23 | 18.88 ± 0.23 | 2464.42 ± 78.24 | +| snapshots/38740b847e4cb78f352aba30aa41c76e08e6eb46 | tg128 | 103.05 ± 1.66 | 105.80 ± 1.47 | | | | + +llama-benchy (0.3.7) +date: 2026-05-09 19:28:07 | latency mode: generation + diff --git a/benchmarks/mtp-2026-05-09-203007.md b/benchmarks/mtp-2026-05-09-203007.md new file mode 100644 index 0000000000..660fbda93b --- /dev/null +++ b/benchmarks/mtp-2026-05-09-203007.md @@ -0,0 +1,375 @@ +# MTP vs Baseline Benchmark + +## Environment + +| | | +|---|---| +| **Date** | 2026-05-10 00:30:10 UTC | +| **Commit** | `7f4dba9` (mtp-support-perf) | +| **Chip** | Apple M4 Max | +| **GPU cores** | 40 | +| **RAM** | 64 GB | +| **macOS** | 26.4 (25E246) | +| **Swift** | Apple Swift version 6.3 (swiftlang-6.3.0.123.5 clang-2100.0.123.102) | +| **pp sizes** | 512 2048 | +| **tg sizes** | 128 | +| **runs** | 5 | + +## Results + +## Gemma 4 26B +### gemma-4-26b-a4b [baseline] + +No model specified, attempting to auto-detect from endpoint... +Auto-detected HF model: snapshots/695690b33533b1f8b0395c1d6b4f00dc411353ef (served as: snapshots/695690b33533b1f8b0395c1d6b4f00dc411353ef) +llama-benchy (0.3.7) +Date: 2026-05-09 20:30:20 +Benchmarking model: snapshots/695690b33533b1f8b0395c1d6b4f00dc411353ef at http://localhost:18765/v1 +Concurrency levels: [1] +Loading text from cache: /Users/gg/.cache/llama-benchy/cc6a0b5782734ee3b9069aa3b64cc62c.txt +Total tokens available in text corpus: 144040 +Warming up... +Warmup (User only) complete. Delta: 12 tokens (Server: 33, Local: 21) +Warmup (System+Empty) complete. Delta: 17 tokens (Server: 38, Local: 21) + +Skipping coherence test (--skip-coherence specified) +Measuring latency using mode: generation... +Average latency (generation): 1.12 ms +Running test: pp=512, tg=128, depth=0, concurrency=1 + Run 1/5 (batch size 1)... + No token_ids in response, using local tokenization + Run 2/5 (batch size 1)... + Run 3/5 (batch size 1)... + Run 4/5 (batch size 1)... + Run 5/5 (batch size 1)... +Running test: pp=2048, tg=128, depth=0, concurrency=1 + Run 1/5 (batch size 1)... + Run 2/5 (batch size 1)... + Run 3/5 (batch size 1)... + Run 4/5 (batch size 1)... + Run 5/5 (batch size 1)... +Printing results in MD format: + + + +| model | test | t/s | peak t/s | ttfr (ms) | est_ppt (ms) | e2e_ttft (ms) | +|:---------------------------------------------------|-------:|-----------------:|-------------:|----------------:|----------------:|-----------------:| +| snapshots/695690b33533b1f8b0395c1d6b4f00dc411353ef | pp512 | 3574.16 ± 397.56 | | 142.70 ± 15.15 | 141.57 ± 15.15 | 702.90 ± 31.45 | +| snapshots/695690b33533b1f8b0395c1d6b4f00dc411353ef | tg128 | 35.17 ± 0.19 | 36.20 ± 0.40 | | | | +| snapshots/695690b33533b1f8b0395c1d6b4f00dc411353ef | pp2048 | 1670.83 ± 143.65 | | 1227.99 ± 96.85 | 1226.87 ± 96.85 | 4086.81 ± 162.17 | +| snapshots/695690b33533b1f8b0395c1d6b4f00dc411353ef | tg128 | 34.12 ± 0.09 | 35.00 ± 0.00 | | | | + +llama-benchy (0.3.7) +date: 2026-05-09 20:30:20 | latency mode: generation + +### gemma-4-26b-a4b [MTP] + +No model specified, attempting to auto-detect from endpoint... +Auto-detected HF model: snapshots/695690b33533b1f8b0395c1d6b4f00dc411353ef (served as: snapshots/695690b33533b1f8b0395c1d6b4f00dc411353ef) +llama-benchy (0.3.7) +Date: 2026-05-09 20:31:29 +Benchmarking model: snapshots/695690b33533b1f8b0395c1d6b4f00dc411353ef at http://localhost:18765/v1 +Concurrency levels: [1] +Loading text from cache: /Users/gg/.cache/llama-benchy/cc6a0b5782734ee3b9069aa3b64cc62c.txt +Total tokens available in text corpus: 144040 +Warming up... +Warmup (User only) complete. Delta: 12 tokens (Server: 33, Local: 21) +Warmup (System+Empty) complete. Delta: 17 tokens (Server: 38, Local: 21) + +Skipping coherence test (--skip-coherence specified) +Measuring latency using mode: generation... +Average latency (generation): 1.30 ms +Running test: pp=512, tg=128, depth=0, concurrency=1 + Run 1/5 (batch size 1)... + No token_ids in response, using local tokenization + Run 2/5 (batch size 1)... + Run 3/5 (batch size 1)... + Run 4/5 (batch size 1)... + Run 5/5 (batch size 1)... +Running test: pp=2048, tg=128, depth=0, concurrency=1 + Run 1/5 (batch size 1)... + Run 2/5 (batch size 1)... + Run 3/5 (batch size 1)... + Run 4/5 (batch size 1)... + Run 5/5 (batch size 1)... +Printing results in MD format: + + + +| model | test | t/s | peak t/s | ttfr (ms) | est_ppt (ms) | e2e_ttft (ms) | +|:---------------------------------------------------|-------:|-----------------:|--------------:|-----------------:|-----------------:|-----------------:| +| snapshots/695690b33533b1f8b0395c1d6b4f00dc411353ef | pp512 | 3555.33 ± 209.96 | | 142.40 ± 7.88 | 141.10 ± 7.88 | 737.17 ± 17.49 | +| snapshots/695690b33533b1f8b0395c1d6b4f00dc411353ef | tg128 | 68.53 ± 2.52 | 74.20 ± 1.72 | | | | +| snapshots/695690b33533b1f8b0395c1d6b4f00dc411353ef | pp2048 | 1634.17 ± 140.73 | | 1256.36 ± 106.71 | 1255.06 ± 106.71 | 4449.44 ± 205.11 | +| snapshots/695690b33533b1f8b0395c1d6b4f00dc411353ef | tg128 | 49.45 ± 10.72 | 68.40 ± 18.36 | | | | + +llama-benchy (0.3.7) +date: 2026-05-09 20:31:29 | latency mode: generation + +## Gemma 4 31B +### gemma-4-31b [baseline] + +No model specified, attempting to auto-detect from endpoint... +Auto-detected HF model: snapshots/dcb78c3f5d6becacbfce71cd4851ad98c4f08a05 (served as: snapshots/dcb78c3f5d6becacbfce71cd4851ad98c4f08a05) +llama-benchy (0.3.7) +Date: 2026-05-09 20:32:27 +Benchmarking model: snapshots/dcb78c3f5d6becacbfce71cd4851ad98c4f08a05 at http://localhost:18765/v1 +Concurrency levels: [1] +Loading text from cache: /Users/gg/.cache/llama-benchy/cc6a0b5782734ee3b9069aa3b64cc62c.txt +Total tokens available in text corpus: 144040 +Warming up... +Warmup (User only) complete. Delta: 12 tokens (Server: 33, Local: 21) +Warmup (System+Empty) complete. Delta: 17 tokens (Server: 38, Local: 21) + +Skipping coherence test (--skip-coherence specified) +Measuring latency using mode: generation... +Average latency (generation): 1.20 ms +Running test: pp=512, tg=128, depth=0, concurrency=1 + Run 1/5 (batch size 1)... + No token_ids in response, using local tokenization + Run 2/5 (batch size 1)... + Run 3/5 (batch size 1)... + Run 4/5 (batch size 1)... + Run 5/5 (batch size 1)... +Running test: pp=2048, tg=128, depth=0, concurrency=1 + Run 1/5 (batch size 1)... + Run 2/5 (batch size 1)... + Run 3/5 (batch size 1)... + Run 4/5 (batch size 1)... + Run 5/5 (batch size 1)... +Printing results in MD format: + + + +| model | test | t/s | peak t/s | ttfr (ms) | est_ppt (ms) | e2e_ttft (ms) | +|:---------------------------------------------------|-------:|------------------:|-------------:|-----------------:|-----------------:|-------------------:| +| snapshots/dcb78c3f5d6becacbfce71cd4851ad98c4f08a05 | pp512 | 2592.84 ± 1249.72 | | 272.89 ± 166.42 | 271.69 ± 166.42 | 6958.10 ± 2895.44 | +| snapshots/dcb78c3f5d6becacbfce71cd4851ad98c4f08a05 | tg128 | 8.68 ± 3.24 | 15.80 ± 1.94 | | | | +| snapshots/dcb78c3f5d6becacbfce71cd4851ad98c4f08a05 | pp2048 | 1175.51 ± 368.90 | | 1880.83 ± 486.11 | 1879.63 ± 486.11 | 23243.17 ± 2462.61 | +| snapshots/dcb78c3f5d6becacbfce71cd4851ad98c4f08a05 | tg128 | 10.26 ± 0.90 | 15.60 ± 0.49 | | | | + +llama-benchy (0.3.7) +date: 2026-05-09 20:32:27 | latency mode: generation + +### gemma-4-31b [MTP] + +No model specified, attempting to auto-detect from endpoint... +Auto-detected HF model: snapshots/dcb78c3f5d6becacbfce71cd4851ad98c4f08a05 (served as: snapshots/dcb78c3f5d6becacbfce71cd4851ad98c4f08a05) +llama-benchy (0.3.7) +Date: 2026-05-09 20:37:36 +Benchmarking model: snapshots/dcb78c3f5d6becacbfce71cd4851ad98c4f08a05 at http://localhost:18765/v1 +Concurrency levels: [1] +Loading text from cache: /Users/gg/.cache/llama-benchy/cc6a0b5782734ee3b9069aa3b64cc62c.txt +Total tokens available in text corpus: 144040 +Warming up... +Warmup (User only) complete. Delta: 12 tokens (Server: 33, Local: 21) +Warmup (System+Empty) complete. Delta: 17 tokens (Server: 38, Local: 21) + +Skipping coherence test (--skip-coherence specified) +Measuring latency using mode: generation... +Average latency (generation): 1.14 ms +Running test: pp=512, tg=128, depth=0, concurrency=1 + Run 1/5 (batch size 1)... + No token_ids in response, using local tokenization + Run 2/5 (batch size 1)... + Run 3/5 (batch size 1)... + Run 4/5 (batch size 1)... + Run 5/5 (batch size 1)... +Running test: pp=2048, tg=128, depth=0, concurrency=1 + Run 1/5 (batch size 1)... + Run 2/5 (batch size 1)... + Run 3/5 (batch size 1)... + Run 4/5 (batch size 1)... + Run 5/5 (batch size 1)... +Printing results in MD format: + + + +| model | test | t/s | peak t/s | ttfr (ms) | est_ppt (ms) | e2e_ttft (ms) | +|:---------------------------------------------------|-------:|-----------------:|-------------:|-----------------:|-----------------:|-------------------:| +| snapshots/dcb78c3f5d6becacbfce71cd4851ad98c4f08a05 | pp512 | 3597.81 ± 354.43 | | 141.45 ± 13.53 | 140.30 ± 13.53 | 4439.83 ± 501.11 | +| snapshots/dcb78c3f5d6becacbfce71cd4851ad98c4f08a05 | tg128 | 12.87 ± 1.15 | 19.60 ± 2.94 | | | | +| snapshots/dcb78c3f5d6becacbfce71cd4851ad98c4f08a05 | pp2048 | 1600.07 ± 210.76 | | 1295.03 ± 163.11 | 1293.88 ± 163.11 | 21469.46 ± 1287.82 | +| snapshots/dcb78c3f5d6becacbfce71cd4851ad98c4f08a05 | tg128 | 9.65 ± 1.76 | 22.00 ± 4.00 | | | | + +llama-benchy (0.3.7) +date: 2026-05-09 20:37:36 | latency mode: generation + +## Qwen3.6 27B +### Qwen3.6-27B [baseline] + +No model specified, attempting to auto-detect from endpoint... +Auto-detected HF model: snapshots/c000ac2c2057d94be3fa931000c31723aac53282 (served as: snapshots/c000ac2c2057d94be3fa931000c31723aac53282) +llama-benchy (0.3.7) +Date: 2026-05-09 20:41:53 +Benchmarking model: snapshots/c000ac2c2057d94be3fa931000c31723aac53282 at http://localhost:18765/v1 +Concurrency levels: [1] +Loading text from cache: /Users/gg/.cache/llama-benchy/cc6a0b5782734ee3b9069aa3b64cc62c.txt +Total tokens available in text corpus: 144480 +Warming up... +Warmup (User only) complete. Delta: 9 tokens (Server: 30, Local: 21) +Warmup (System+Empty) complete. Delta: 7 tokens (Server: 28, Local: 21) + +Skipping coherence test (--skip-coherence specified) +Measuring latency using mode: generation... +Average latency (generation): 1.20 ms +Running test: pp=512, tg=128, depth=0, concurrency=1 + Run 1/5 (batch size 1)... + No token_ids in response, using local tokenization + Run 2/5 (batch size 1)... + Run 3/5 (batch size 1)... + Run 4/5 (batch size 1)... + Run 5/5 (batch size 1)... +Running test: pp=2048, tg=128, depth=0, concurrency=1 + Run 1/5 (batch size 1)... + Run 2/5 (batch size 1)... + Run 3/5 (batch size 1)... + Run 4/5 (batch size 1)... + Run 5/5 (batch size 1)... +Printing results in MD format: + + + +| model | test | t/s | peak t/s | ttfr (ms) | est_ppt (ms) | e2e_ttft (ms) | +|:---------------------------------------------------|-------:|--------------------:|-------------:|-------------:|---------------:|------------------:| +| snapshots/c000ac2c2057d94be3fa931000c31723aac53282 | pp512 | 74943.88 ± 16045.66 | | 8.17 ± 1.21 | 6.97 ± 1.21 | 3604.37 ± 625.90 | +| snapshots/c000ac2c2057d94be3fa931000c31723aac53282 | tg128 | 16.54 ± 0.54 | 21.00 ± 0.00 | | | | +| snapshots/c000ac2c2057d94be3fa931000c31723aac53282 | pp2048 | 75558.50 ± 4682.48 | | 28.29 ± 1.74 | 27.09 ± 1.74 | 13186.33 ± 181.37 | +| snapshots/c000ac2c2057d94be3fa931000c31723aac53282 | tg128 | 16.74 ± 0.09 | 20.20 ± 0.40 | | | | + +llama-benchy (0.3.7) +date: 2026-05-09 20:41:53 | latency mode: generation + +### Qwen3.6-27B [MTP] + +No model specified, attempting to auto-detect from endpoint... +Auto-detected HF model: snapshots/c000ac2c2057d94be3fa931000c31723aac53282 (served as: snapshots/c000ac2c2057d94be3fa931000c31723aac53282) +llama-benchy (0.3.7) +Date: 2026-05-09 20:44:39 +Benchmarking model: snapshots/c000ac2c2057d94be3fa931000c31723aac53282 at http://localhost:18765/v1 +Concurrency levels: [1] +Loading text from cache: /Users/gg/.cache/llama-benchy/cc6a0b5782734ee3b9069aa3b64cc62c.txt +Total tokens available in text corpus: 144480 +Warming up... +Warmup (User only) complete. Delta: 9 tokens (Server: 30, Local: 21) +Warmup (System+Empty) complete. Delta: 7 tokens (Server: 28, Local: 21) + +Skipping coherence test (--skip-coherence specified) +Measuring latency using mode: generation... +Average latency (generation): 1.17 ms +Running test: pp=512, tg=128, depth=0, concurrency=1 + Run 1/5 (batch size 1)... + No token_ids in response, using local tokenization + Run 2/5 (batch size 1)... + Run 3/5 (batch size 1)... + Run 4/5 (batch size 1)... + Run 5/5 (batch size 1)... +Running test: pp=2048, tg=128, depth=0, concurrency=1 + Run 1/5 (batch size 1)... + Run 2/5 (batch size 1)... + Run 3/5 (batch size 1)... + Run 4/5 (batch size 1)... + Run 5/5 (batch size 1)... +Printing results in MD format: + + + +| model | test | t/s | peak t/s | ttfr (ms) | est_ppt (ms) | e2e_ttft (ms) | +|:---------------------------------------------------|-------:|--------------------:|-------------:|-------------:|---------------:|------------------:| +| snapshots/c000ac2c2057d94be3fa931000c31723aac53282 | pp512 | 97972.90 ± 3335.24 | | 6.31 ± 0.18 | 5.14 ± 0.18 | 3492.68 ± 440.32 | +| snapshots/c000ac2c2057d94be3fa931000c31723aac53282 | tg128 | 21.64 ± 1.26 | 35.20 ± 2.79 | | | | +| snapshots/c000ac2c2057d94be3fa931000c31723aac53282 | pp2048 | 103397.11 ± 1876.97 | | 20.90 ± 0.37 | 19.73 ± 0.37 | 14117.86 ± 797.48 | +| snapshots/c000ac2c2057d94be3fa931000c31723aac53282 | tg128 | 21.59 ± 1.08 | 34.00 ± 1.67 | | | | + +llama-benchy (0.3.7) +date: 2026-05-09 20:44:39 | latency mode: generation + +## Qwen3.6 35B +### Qwen3.6-35B [baseline] + +No model specified, attempting to auto-detect from endpoint... +Auto-detected HF model: snapshots/38740b847e4cb78f352aba30aa41c76e08e6eb46 (served as: snapshots/38740b847e4cb78f352aba30aa41c76e08e6eb46) +llama-benchy (0.3.7) +Date: 2026-05-09 20:47:14 +Benchmarking model: snapshots/38740b847e4cb78f352aba30aa41c76e08e6eb46 at http://localhost:18765/v1 +Concurrency levels: [1] +Loading text from cache: /Users/gg/.cache/llama-benchy/cc6a0b5782734ee3b9069aa3b64cc62c.txt +Total tokens available in text corpus: 144480 +Warming up... +Warmup (User only) complete. Delta: 9 tokens (Server: 30, Local: 21) +Warmup (System+Empty) complete. Delta: 7 tokens (Server: 28, Local: 21) + +Skipping coherence test (--skip-coherence specified) +Measuring latency using mode: generation... +Average latency (generation): 1.19 ms +Running test: pp=512, tg=128, depth=0, concurrency=1 + Run 1/5 (batch size 1)... + No token_ids in response, using local tokenization + Run 2/5 (batch size 1)... + Run 3/5 (batch size 1)... + Run 4/5 (batch size 1)... + Run 5/5 (batch size 1)... +Running test: pp=2048, tg=128, depth=0, concurrency=1 + Run 1/5 (batch size 1)... + Run 2/5 (batch size 1)... + Run 3/5 (batch size 1)... + Run 4/5 (batch size 1)... + Run 5/5 (batch size 1)... +Printing results in MD format: + + + +| model | test | t/s | peak t/s | ttfr (ms) | est_ppt (ms) | e2e_ttft (ms) | +|:---------------------------------------------------|-------:|--------------------:|-------------:|-------------:|---------------:|-----------------:| +| snapshots/38740b847e4cb78f352aba30aa41c76e08e6eb46 | pp512 | 108587.49 ± 5681.62 | | 5.84 ± 0.25 | 4.65 ± 0.25 | 408.60 ± 9.70 | +| snapshots/38740b847e4cb78f352aba30aa41c76e08e6eb46 | tg128 | 35.54 ± 1.02 | 37.00 ± 0.89 | | | | +| snapshots/38740b847e4cb78f352aba30aa41c76e08e6eb46 | pp2048 | 108577.12 ± 3765.77 | | 20.00 ± 0.66 | 18.80 ± 0.66 | 1859.23 ± 164.66 | +| snapshots/38740b847e4cb78f352aba30aa41c76e08e6eb46 | tg128 | 36.04 ± 0.26 | 37.20 ± 0.40 | | | | + +llama-benchy (0.3.7) +date: 2026-05-09 20:47:14 | latency mode: generation + +### Qwen3.6-35B [MTP] + +No model specified, attempting to auto-detect from endpoint... +Auto-detected HF model: snapshots/38740b847e4cb78f352aba30aa41c76e08e6eb46 (served as: snapshots/38740b847e4cb78f352aba30aa41c76e08e6eb46) +llama-benchy (0.3.7) +Date: 2026-05-09 20:48:06 +Benchmarking model: snapshots/38740b847e4cb78f352aba30aa41c76e08e6eb46 at http://localhost:18765/v1 +Concurrency levels: [1] +Loading text from cache: /Users/gg/.cache/llama-benchy/cc6a0b5782734ee3b9069aa3b64cc62c.txt +Total tokens available in text corpus: 144480 +Warming up... +Warmup (User only) complete. Delta: 9 tokens (Server: 30, Local: 21) +Warmup (System+Empty) complete. Delta: 7 tokens (Server: 28, Local: 21) + +Skipping coherence test (--skip-coherence specified) +Measuring latency using mode: generation... +Average latency (generation): 1.13 ms +Running test: pp=512, tg=128, depth=0, concurrency=1 + Run 1/5 (batch size 1)... + No token_ids in response, using local tokenization + Run 2/5 (batch size 1)... + Run 3/5 (batch size 1)... + Run 4/5 (batch size 1)... + Run 5/5 (batch size 1)... +Running test: pp=2048, tg=128, depth=0, concurrency=1 + Run 1/5 (batch size 1)... + Run 2/5 (batch size 1)... + Run 3/5 (batch size 1)... + Run 4/5 (batch size 1)... + Run 5/5 (batch size 1)... +Printing results in MD format: + + + +| model | test | t/s | peak t/s | ttfr (ms) | est_ppt (ms) | e2e_ttft (ms) | +|:---------------------------------------------------|-------:|--------------------:|--------------:|-------------:|---------------:|----------------:| +| snapshots/38740b847e4cb78f352aba30aa41c76e08e6eb46 | pp512 | 106448.38 ± 7867.29 | | 5.88 ± 0.36 | 4.75 ± 0.36 | 408.02 ± 7.47 | +| snapshots/38740b847e4cb78f352aba30aa41c76e08e6eb46 | tg128 | 112.23 ± 4.18 | 114.80 ± 3.76 | | | | +| snapshots/38740b847e4cb78f352aba30aa41c76e08e6eb46 | pp2048 | 109363.56 ± 2705.68 | | 19.79 ± 0.47 | 18.66 ± 0.47 | 2216.65 ± 76.60 | +| snapshots/38740b847e4cb78f352aba30aa41c76e08e6eb46 | tg128 | 98.18 ± 2.62 | 99.60 ± 3.20 | | | | + +llama-benchy (0.3.7) +date: 2026-05-09 20:48:06 | latency mode: generation + diff --git a/scripts/benchmark-mtp.sh b/scripts/benchmark-mtp.sh new file mode 100755 index 0000000000..616acd9bee --- /dev/null +++ b/scripts/benchmark-mtp.sh @@ -0,0 +1,223 @@ +#!/usr/bin/env bash +# MTP vs baseline throughput benchmark using llama-benchy. +# +# Starts mlx-server for each model config (standard + MTP), runs llama-benchy +# against the OpenAI-compatible endpoint, then kills the server. +# +# Usage: +# ./scripts/benchmark-mtp.sh [--pp 512 2048] [--tg 128] [--runs 3] +# +# Requirements: +# - llama-benchy (pip install llama-benchy or brew install llama.cpp) +# - huggingface_hub Python package (pip install huggingface_hub) +# Models are downloaded automatically on first run via huggingface_hub. + +set -euo pipefail + +# ── defaults ───────────────────────────────────────────────────────────────── +BENCH_PORT=18765 +PP_SIZES="512 2048" +TG_SIZES="128" +RUNS=3 +CREATE_ISSUE=true +TIMESTAMP=$(date +"%Y-%m-%d-%H%M%S") +OUTDIR="benchmarks" +OUTFILE="${OUTDIR}/mtp-${TIMESTAMP}.md" + +# ── parse CLI overrides ─────────────────────────────────────────────────────── +while [[ $# -gt 0 ]]; do + case $1 in + --pp) shift; PP_SIZES="$*"; break ;; + --tg) shift; TG_SIZES="$1"; shift ;; + --runs) shift; RUNS="$1"; shift ;; + --no-issue) CREATE_ISSUE=false; shift ;; + *) echo "Unknown arg: $1"; exit 1 ;; + esac +done + +# ── helpers ─────────────────────────────────────────────────────────────────── +SERVER_PID="" + +hf_path() { + python3 - "$1" <<'EOF' +import sys +from huggingface_hub import snapshot_download +print(snapshot_download(sys.argv[1])) +EOF +} + +# ── download models ─────────────────────────────────────────────────────────── +echo "=== Downloading / verifying models ===" + +GEMMA4_26B=$(hf_path "mlx-community/gemma-4-26b-a4b-it-4bit") +GEMMA4_26B_DRAFTER=$(hf_path "google/gemma-4-26B-A4B-it-assistant") +GEMMA4_31B=$(hf_path "mlx-community/gemma-4-31b-it-4bit") +GEMMA4_31B_DRAFTER=$(hf_path "google/gemma-4-31B-it-assistant") +QWEN_27B=$(hf_path "mlx-community/Qwen3.6-27B-4bit") +QWEN_35B=$(hf_path "mlx-community/Qwen3.6-35B-A3B-4bit") + +echo " gemma-4-26b: $GEMMA4_26B" +echo " gemma-4-26b drafter: $GEMMA4_26B_DRAFTER" +echo " gemma-4-31b: $GEMMA4_31B" +echo " gemma-4-31b drafter: $GEMMA4_31B_DRAFTER" +echo " Qwen3.6-27B: $QWEN_27B" +echo " Qwen3.6-35B: $QWEN_35B" + +# ── output file setup ──────────────────────────────────────────────────────── +mkdir -p "$OUTDIR" +COMMIT=$(git rev-parse --short HEAD 2>/dev/null || echo "unknown") +BRANCH=$(git rev-parse --abbrev-ref HEAD 2>/dev/null || echo "unknown") +CHIP=$(sysctl -n machdep.cpu.brand_string 2>/dev/null || echo "unknown") +MACOS_VERSION=$(sw_vers -productVersion 2>/dev/null || echo "unknown") +MACOS_BUILD=$(sw_vers -buildVersion 2>/dev/null || echo "unknown") +SWIFT_VERSION=$(swift --version 2>/dev/null | head -1 || echo "unknown") +TOTAL_RAM_GB=$(( $(sysctl -n hw.memsize 2>/dev/null || echo 0) / 1024 / 1024 / 1024 )) +GPU_CORES=$(system_profiler SPDisplaysDataType 2>/dev/null | awk '/Total Number of Cores/{print $NF; exit}' || echo "unknown") +{ + echo "# MTP vs Baseline Benchmark" + echo "" + echo "## Environment" + echo "" + echo "| | |" + echo "|---|---|" + echo "| **Date** | $(date -u '+%Y-%m-%d %H:%M:%S UTC') |" + echo "| **Commit** | \`${COMMIT}\` (${BRANCH}) |" + echo "| **Chip** | ${CHIP} |" + echo "| **GPU cores** | ${GPU_CORES} |" + echo "| **RAM** | ${TOTAL_RAM_GB} GB |" + echo "| **macOS** | ${MACOS_VERSION} (${MACOS_BUILD}) |" + echo "| **Swift** | ${SWIFT_VERSION} |" + echo "| **pp sizes** | ${PP_SIZES} |" + echo "| **tg sizes** | ${TG_SIZES} |" + echo "| **runs** | ${RUNS} |" + echo "" + echo "## Results" + echo "" +} > "$OUTFILE" +echo "Results will be saved to: $OUTFILE" + +# ── build ───────────────────────────────────────────────────────────────────── +echo "" +echo "=== Building (release) ===" +swift build -c release 2>&1 | tail -5 +SERVER_BIN=".build/release/mlx-server" + +start_server() { + local model_path="$1"; shift + "$SERVER_BIN" --model "$model_path" --port "$BENCH_PORT" \ + --no-prefix-cache "$@" >/tmp/mlx-server-$$.log 2>&1 & + SERVER_PID=$! + local tries=0 + until curl -sf "http://localhost:${BENCH_PORT}/health" >/dev/null 2>&1; do + # Bail early if the server process has already exited. + if ! kill -0 "$SERVER_PID" 2>/dev/null; then + echo "ERROR: server process exited before becoming ready" >&2 + cat /tmp/mlx-server-$$.log >&2 || true + rm -f /tmp/mlx-server-$$.log + SERVER_PID="" + return 1 + fi + tries=$((tries + 1)) + if [[ $tries -ge 300 ]]; then + echo "ERROR: server did not start within 300 s" >&2 + kill "$SERVER_PID" 2>/dev/null || true + SERVER_PID="" + return 1 + fi + sleep 1 + done + rm -f /tmp/mlx-server-$$.log + echo " server ready (${tries}s)" +} + +stop_server() { + [[ -n "$SERVER_PID" ]] || return + kill "$SERVER_PID" 2>/dev/null || true + wait "$SERVER_PID" 2>/dev/null || true + SERVER_PID="" +} + +trap stop_server EXIT + +run_bench() { + local label="$1"; shift + local model_path="$1"; shift + # remaining args forwarded to mlx-server (e.g. --mtp, --draft-model ) + + echo "" + echo "━━━ ${label} ━━━" + if ! start_server "$model_path" "$@"; then + echo " SKIPPED: server failed to start for '${label}'" >&2 + printf "### %s\n\n⚠️ Server failed to start (no MTP weights or other startup error).\n\n" \ + "$label" >> "$OUTFILE" + return 0 + fi + + local result bench_exit + result=$(KMP_DUPLICATE_LIB_OK=TRUE llama-benchy \ + --base-url "http://localhost:${BENCH_PORT}/v1" \ + --tokenizer "$model_path" \ + --pp $PP_SIZES \ + --tg $TG_SIZES \ + --runs "$RUNS" \ + --no-cache \ + --no-warmup \ + --skip-coherence \ + --latency-mode generation \ + --format md 2>&1) && bench_exit=0 || bench_exit=$? + + echo "$result" + if [[ $bench_exit -ne 0 ]]; then + echo "WARNING: llama-benchy exited $bench_exit for '${label}'" >&2 + printf "### %s\n\n⚠️ llama-benchy failed (exit %s):\n\`\`\`\n%s\n\`\`\`\n\n" \ + "$label" "$bench_exit" "$result" >> "$OUTFILE" + else + printf "### %s\n\n%s\n\n" "$label" "$result" >> "$OUTFILE" + fi + + stop_server +} + +# ── benchmarks ──────────────────────────────────────────────────────────────── +echo "" +echo "=== Gemma 4 26B ===" +echo "## Gemma 4 26B" >> "$OUTFILE" +run_bench "gemma-4-26b-a4b [baseline]" "$GEMMA4_26B" +run_bench "gemma-4-26b-a4b [MTP]" "$GEMMA4_26B" --draft-model "$GEMMA4_26B_DRAFTER" + +echo "" +echo "=== Gemma 4 31B ===" +echo "## Gemma 4 31B" >> "$OUTFILE" +run_bench "gemma-4-31b [baseline]" "$GEMMA4_31B" +run_bench "gemma-4-31b [MTP]" "$GEMMA4_31B" --draft-model "$GEMMA4_31B_DRAFTER" + +echo "" +echo "=== Qwen3.6 27B ===" +echo "## Qwen3.6 27B" >> "$OUTFILE" +run_bench "Qwen3.6-27B [baseline]" "$QWEN_27B" +run_bench "Qwen3.6-27B [MTP]" "$QWEN_27B" --mtp + +echo "" +echo "=== Qwen3.6 35B ===" +echo "## Qwen3.6 35B" >> "$OUTFILE" +run_bench "Qwen3.6-35B [baseline]" "$QWEN_35B" +run_bench "Qwen3.6-35B [MTP]" "$QWEN_35B" --mtp + +# ── post results ────────────────────────────────────────────────────────────── +echo "" +echo "=== Results saved to: $OUTFILE ===" + +if [[ "$CREATE_ISSUE" == true ]]; then + echo "" + echo "=== Creating GitHub issue ===" + gh issue create \ + --title "MTP benchmark ${TIMESTAMP} (${COMMIT})" \ + --label "benchmark" \ + --body-file "$OUTFILE" +else + echo "" + echo "=== Skipping GitHub issue (--no-issue) ===" +fi + +echo "" +echo "=== Done ===" diff --git a/scripts/patch-qwen36-mtp.py b/scripts/patch-qwen36-mtp.py new file mode 100644 index 0000000000..b9eda596f9 --- /dev/null +++ b/scripts/patch-qwen36-mtp.py @@ -0,0 +1,208 @@ +#!/usr/bin/env python3 +""" +Patch an existing mlx-community Qwen3.6 4-bit checkpoint with MTP weights +extracted from the original HuggingFace model. + +The mlx-community conversions strip the `mtp.*` weight keys, but the original +HF checkpoint has them in specific shards. This script: + + 1. Downloads only the MTP-containing shards from the original HF repo + 2. Extracts the MTP weights (stored as bfloat16 — no requantisation needed, + since the Swift Linear layers load plain-float weights correctly) + 3. Saves a new `mtp-weights.safetensors` shard in the mlx checkpoint dir + using the key prefix `language_model.mtp.*` expected by Qwen35Model + 4. Updates `model.safetensors.index.json` to reference the new shard + +Usage: + python3 scripts/patch-qwen36-mtp.py [--model 27b|35b] + +Requirements: + pip install huggingface_hub safetensors torch +""" + +import argparse +import json +import sys +from pathlib import Path + +import torch +from huggingface_hub import hf_hub_download, snapshot_download +from safetensors.torch import load_file as st_load, save_file as st_save + + +# ── model registry ──────────────────────────────────────────────────────────── + +MODELS = { + "27b": { + "mlx_repo": "mlx-community/Qwen3.6-27B-4bit", + "hf_repo": "Qwen/Qwen3.6-27B", + }, + "35b": { + "mlx_repo": "mlx-community/Qwen3.6-35B-A3B-4bit", + "hf_repo": "Qwen/Qwen3.6-35B-A3B", + }, +} + +# In Qwen35Model.sanitize, the text-model's MTP weights live under the +# `language_model` sub-module of the outer VLM model, so keys must be +# `language_model.mtp.*` (not `language_model.model.mtp.*`). +KEY_PREFIX = "language_model." + +# Norm keys that need a +1 shift (HF stores them as deviation-from-1; MLXNN +# uses the weight directly, so we normalise to the MLX convention here). +# These must match the suffixes in Qwen35TextModel.sanitize's normKeys list. +NORM_SHIFT_SUFFIXES = ( + ".input_layernorm.weight", + ".post_attention_layernorm.weight", + ".q_norm.weight", + ".k_norm.weight", + ".pre_fc_norm_hidden.weight", + ".pre_fc_norm_embedding.weight", + "mtp.norm.weight", # full suffix so model.norm.weight doesn't match +) + + +# ── helpers ─────────────────────────────────────────────────────────────────── + +def find_mtp_shards(hf_repo: str, cache_dir: str | None) -> tuple[list[str], list[str]]: + """Return (shard_filenames, mtp_key_names) by inspecting the HF index.""" + index_path = hf_hub_download( + repo_id=hf_repo, filename="model.safetensors.index.json", cache_dir=cache_dir + ) + with open(index_path) as f: + index = json.load(f) + wmap: dict[str, str] = index["weight_map"] + shards = sorted({v for k, v in wmap.items() if k.startswith("mtp.")}) + keys = sorted(k for k in wmap if k.startswith("mtp.")) + return shards, keys + + +# ── main ───────────────────────────────────────────────────────────────────── + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--model", choices=["27b", "35b"], default="27b") + parser.add_argument("--mlx-dir", default=None, + help="Path to existing MLX checkpoint dir (default: auto-download)") + parser.add_argument("--cache-dir", default=None) + args = parser.parse_args() + + cfg = MODELS[args.model] + hf_repo = cfg["hf_repo"] + mlx_repo = cfg["mlx_repo"] + + print(f"=== Patching {mlx_repo} with MTP weights from {hf_repo} ===\n") + + # 1. Locate/download the MLX checkpoint + if args.mlx_dir: + mlx_dir = Path(args.mlx_dir) + print(f"Using MLX dir: {mlx_dir}") + else: + print(f"Downloading MLX checkpoint: {mlx_repo}") + mlx_dir = Path(snapshot_download(mlx_repo, cache_dir=args.cache_dir)) + print(f" -> {mlx_dir}") + + index_path = mlx_dir / "model.safetensors.index.json" + if not index_path.exists(): + sys.exit(f"ERROR: {index_path} not found — is this an MLX checkpoint?") + + with open(index_path) as f: + mlx_index = json.load(f) + mlx_wmap: dict[str, str] = mlx_index["weight_map"] + + existing = [k for k in mlx_wmap if "mtp" in k] + if existing: + print(f"\nCheckpoint already has {len(existing)} MTP key(s) — nothing to do.") + return + + # 2. Find which HF shards contain MTP weights + print(f"\nInspecting HF index: {hf_repo}") + mtp_shards, mtp_keys = find_mtp_shards(hf_repo, cache_dir=args.cache_dir) + if not mtp_shards: + sys.exit("ERROR: no mtp.* keys found in HF model index.") + print(f" {len(mtp_keys)} MTP keys in {len(mtp_shards)} shard(s): {mtp_shards}") + + # 3. Download only those shards + print(f"\nDownloading {len(mtp_shards)} shard(s) ...") + shard_paths = [ + hf_hub_download(repo_id=hf_repo, filename=s, cache_dir=args.cache_dir) + for s in mtp_shards + ] + for p in shard_paths: + print(f" -> {p}") + + # 4. Extract mtp.* tensors and rekey to language_model.mtp.* + print("\nExtracting MTP tensors ...") + output: dict[str, torch.Tensor] = {} + for shard_path in shard_paths: + for k, v in st_load(shard_path, device="cpu").items(): + if not k.startswith("mtp."): + continue + + # MoE fused expert conversion: + # HF stores fused gate+up proj as experts.gate_up_proj [num_experts, 2*intermediate, hidden]. + # Swift expects switch_mlp.gate_proj and switch_mlp.up_proj each [num_experts, intermediate, hidden]. + # Also rename experts.down_proj -> switch_mlp.down_proj. + if k.endswith(".mlp.experts.gate_up_proj"): + prefix = k[: -len(".mlp.experts.gate_up_proj")] + mid = v.shape[1] // 2 + gate = v[:, :mid, :] + up = v[:, mid:, :] + for suffix, tensor in [ + (".mlp.switch_mlp.gate_proj.weight", gate), + (".mlp.switch_mlp.up_proj.weight", up), + ]: + new_key = KEY_PREFIX + prefix + suffix + t = tensor.to(torch.float32) + print(f" {k} {tuple(v.shape)} split -> {new_key} {tuple(t.shape)}") + output[new_key] = t.to(torch.bfloat16) + continue + + if k.endswith(".mlp.experts.down_proj"): + prefix = k[: -len(".mlp.experts.down_proj")] + new_key = KEY_PREFIX + prefix + ".mlp.switch_mlp.down_proj.weight" + t = v.to(torch.float32) + print(f" {k} {tuple(v.shape)} rename -> {new_key}") + output[new_key] = t.to(torch.bfloat16) + continue + + new_key = KEY_PREFIX + k + t = v.to(torch.float32) + # Apply +1 shift to 1-D norm weights. + # HF stores RMSNorm gammas as deviation-from-1 (near 0 after training). + # MLXNN uses the weight directly, so we add 1 to match convention. + # The Swift sanitize won't shift these because hasUnsanitizedConv1d=False + # for the already-converted mlx-community checkpoint. + shifted = any(new_key.endswith(s) for s in NORM_SHIFT_SUFFIXES) + if shifted and t.dim() == 1: + t = t + 1.0 + print(f" {k} {tuple(v.shape)} +1 norm shift -> {new_key}") + else: + print(f" {k} {tuple(v.shape)} {v.dtype} -> {new_key}") + output[new_key] = t.to(torch.bfloat16) + + if not output: + sys.exit("ERROR: no mtp.* tensors found in downloaded shards.") + + # 5. Save new shard + out_shard = "mtp-weights.safetensors" + out_path = mlx_dir / out_shard + print(f"\nSaving {out_path} ...") + st_save(output, str(out_path)) + size_mb = out_path.stat().st_size / 1024 / 1024 + print(f" Saved {len(output)} tensors ({size_mb:.1f} MB)") + + # 6. Update index + print("\nUpdating model.safetensors.index.json ...") + for k in output: + mlx_wmap[k] = out_shard + with open(index_path, "w") as f: + json.dump(mlx_index, f, indent=2, sort_keys=True) + print(f" Added {len(output)} keys -> {out_shard}") + + print(f"\n=== Done! Patched: {mlx_dir} ===") + print(f'\nTest: .build/release/mlx-server --model "{mlx_dir}" --mtp --port 18765') + + +if __name__ == "__main__": + main()