diff --git a/Libraries/IntegrationTestHelpers/IntegrationTestHelpers.swift b/Libraries/IntegrationTestHelpers/IntegrationTestHelpers.swift index ed4089134d..58b76907a4 100644 --- a/Libraries/IntegrationTestHelpers/IntegrationTestHelpers.swift +++ b/Libraries/IntegrationTestHelpers/IntegrationTestHelpers.swift @@ -227,7 +227,7 @@ public enum ChatSessionTests { to: "What is the weather in San Francisco?", images: [], videos: []) { switch generation { - case .chunk(let text): + case .chunk(let text, _): print(text, terminator: "") responseText += text case .toolCall(let toolCall): @@ -557,7 +557,7 @@ public enum ToolCallTests { var toolCalls: [ToolCall] = [] for try await generation in stream { switch generation { - case .chunk(let chunk): + case .chunk(let chunk, _): text += chunk case .toolCall(let toolCall): toolCalls.append(toolCall) diff --git a/Libraries/MLXLLM/LLMModel.swift b/Libraries/MLXLLM/LLMModel.swift index d686b7ef7d..c4ef99c7df 100644 --- a/Libraries/MLXLLM/LLMModel.swift +++ b/Libraries/MLXLLM/LLMModel.swift @@ -3,6 +3,19 @@ import MLX import MLXLMCommon +// MARK: - Prefill Progress Hook +// +// This global closure is set by Server.swift before each generate() call and +// cleared when the first decode token arrives. It mirrors llama-server's +// slot_update progress reporting: called after each 512-token prefill chunk +// with (n_past, n_total). +// +// Thread model: written by the server async task before generation starts +// (happens-before the generation Task reads it), and read only from the +// synchronous MLX evaluation thread inside prepare(). This is safe without +// a lock because writes precede all reads in time. +public nonisolated(unsafe) var activePrefillProgressHook: ((Int, Int) -> Void)? = nil + /// Marker protocol for LLMModels public protocol LLMModel: LanguageModel, LoRAModel { @@ -22,14 +35,20 @@ extension LLMModel { -> PrepareResult { let prefillStepSize = windowSize ?? 512 + let totalTokens = input.text.tokens.size var y = input.text + var processed = 0 - // Prepare the prompt in chunks if larger than the prefill size + // Prepare the prompt in chunks if larger than the prefill size. + // After each chunk, call the progress hook so the server can emit + // llama-server-style slot_update SSE events with real n_past. while y.tokens.size > prefillStepSize { let input = y[.newAxis, .. 0) @@ -476,7 +480,9 @@ public class GLM4MoELiteModelInner: Module { let mask = createAttentionMask(h: h, cache: cache?.first) for (i, layer) in layers.enumerated() { - h = layer(h, mask: mask, cache: cache?[i]) + h = partitionedLayerCall(index: i, gpuLayerCount: gpuLayerCount, stream: streamExperts) { + layer(h, mask: mask, cache: cache?[i]) + } } return norm(h) diff --git a/Libraries/MLXLLM/Models/GLMMoeDSA.swift b/Libraries/MLXLLM/Models/GLMMoeDSA.swift new file mode 100644 index 0000000000..9f63e66bc1 --- /dev/null +++ b/Libraries/MLXLLM/Models/GLMMoeDSA.swift @@ -0,0 +1,637 @@ +// +// GLM4MOELite.swift +// LLM +// +// Port of https://github.com/ml-explore/mlx-lm/blob/main/mlx_lm/models/glm_moe_dsa.py +// Created by Ronald Mannak on 2025/1/7. +// + +import Foundation +import MLX +import MLXLMCommon +import MLXNN + + +class GLMMoeDSAAttention: Module { + let config: GLMMoeDSAConfiguration + let hiddenSize: Int + let numHeads: Int + let maxPositionEmbeddings: Int + let ropeTheta: Float + let qLoraRank: Int? + let qkRopeHeadDim: Int + let kvLoraRank: Int + let vHeadDim: Int + let qkNopeHeadDim: Int + let qHeadDim: Int + var scale: Float + + let rope: RoPELayer + @ModuleInfo(key: "q_proj") var qProj: Linear? + @ModuleInfo(key: "q_a_proj") var qAProj: Linear? + @ModuleInfo(key: "q_a_layernorm") var qALayerNorm: RMSNorm? + @ModuleInfo(key: "q_b_proj") var qBProj: Linear? + @ModuleInfo(key: "o_proj") var oProj: Linear + @ModuleInfo(key: "kv_a_proj_with_mqa") var kvAProjWithMqa: Linear + @ModuleInfo(key: "kv_a_layernorm") var kvALayerNorm: RMSNorm + @ModuleInfo(key: "embed_q") var embedQ: Module // Can be MultiLinear or QuantizedMultiLinear + @ModuleInfo(key: "unembed_out") var unembedOut: Module // Can be MultiLinear or QuantizedMultiLinear + + init(_ config: GLMMoeDSAConfiguration) { + self.config = config + self.hiddenSize = config.hiddenSize + self.numHeads = config.attentionHeads + self.maxPositionEmbeddings = config.maxPositionEmbeddings + self.ropeTheta = config.ropeTheta + self.qLoraRank = config.qLoraRank + self.qkRopeHeadDim = config.qkRopeHeadDim + self.kvLoraRank = config.kvLoraRank + self.vHeadDim = config.vHeadDim + self.qkNopeHeadDim = config.qkNopeHeadDim + self.qHeadDim = config.qkNopeHeadDim + config.qkRopeHeadDim + self.scale = pow(Float(qHeadDim), -0.5) + + if let qLoraRank { + _qAProj.wrappedValue = Linear(hiddenSize, qLoraRank, bias: config.attentionBias) + _qALayerNorm.wrappedValue = RMSNorm(dimensions: qLoraRank, eps: config.rmsNormEps) + _qBProj.wrappedValue = Linear(qLoraRank, numHeads * qHeadDim, bias: false) + } else { + _qProj.wrappedValue = Linear(hiddenSize, numHeads * qHeadDim, bias: false) + } + + _kvAProjWithMqa.wrappedValue = Linear( + hiddenSize, + kvLoraRank + qkRopeHeadDim, + bias: config.attentionBias + ) + _kvALayerNorm.wrappedValue = RMSNorm(dimensions: kvLoraRank, eps: config.rmsNormEps) + _embedQ.wrappedValue = MultiLinear( + inputDims: qkNopeHeadDim, + outputDims: kvLoraRank, + numHeads: numHeads + ) + _unembedOut.wrappedValue = MultiLinear( + inputDims: kvLoraRank, + outputDims: vHeadDim, + numHeads: numHeads + ) + _oProj.wrappedValue = Linear( + numHeads * vHeadDim, hiddenSize, bias: config.attentionBias) + + if let ropeScaling = config.ropeScaling, + let mscaleAllDim = ropeScaling["mscale_all_dim"]?.asFloat(), + let scalingFactor = ropeScaling["factor"]?.asFloat(), + mscaleAllDim != 0, + scalingFactor > 1 + { + let s = 0.1 * mscaleAllDim * log(scalingFactor) + 1.0 + self.scale = self.scale * s * s + } + + var ropeScaling = config.ropeScaling + if let ropeType = ropeScaling?["type"] ?? ropeScaling?["rope_type"], + case .string(let value) = ropeType, + value == "deepseek_yarn" + { + var updated = ropeScaling ?? [:] + updated["type"] = .string("yarn") + ropeScaling = updated + } + + self.rope = initializeRope( + dims: qkRopeHeadDim, + base: ropeTheta, + traditional: config.ropeTraditional, + scalingConfig: ropeScaling, + maxPositionEmbeddings: maxPositionEmbeddings + ) + } + + /// Helper to call a MultiLinear or QuantizedMultiLinear module + private func callMultiLinear(_ module: Module, _ x: MLXArray) -> MLXArray { + if let multiLinear = module as? MultiLinear { + return multiLinear(x) + } else if let quantized = module as? QuantizedMultiLinear { + return quantized(x) + } else { + fatalError("Module must be MultiLinear or QuantizedMultiLinear") + } + } + + func callAsFunction( + _ x: MLXArray, mask: MLXFast.ScaledDotProductAttentionMaskMode, cache: KVCache? + ) -> MLXArray { + let (B, L, _) = (x.dim(0), x.dim(1), x.dim(2)) + + var q: MLXArray + if qLoraRank == nil { + q = qProj!(x) + } else { + q = qBProj!(qALayerNorm!(qAProj!(x))) + } + + q = q.reshaped(B, L, numHeads, qHeadDim).transposed(0, 2, 1, 3) + let splitQ = split(q, indices: [qkNopeHeadDim], axis: -1) + var qNope = splitQ[0] + var qPe = splitQ[1] + + var compressedKv = kvAProjWithMqa(x) + let splitCompressedKv = split(compressedKv, indices: [kvLoraRank], axis: -1) + compressedKv = splitCompressedKv[0] + var kPe = splitCompressedKv[1] + kPe = kPe.reshaped(B, L, 1, qkRopeHeadDim).transposed(0, 2, 1, 3) + var kvLatent = kvALayerNorm(compressedKv) + + qPe = applyRotaryPosition(rope, to: qPe, cache: cache) + kPe = applyRotaryPosition(rope, to: kPe, cache: cache) + + // Expand kvLatent for attention: [B, L, kvLoraRank] -> [B, 1, L, kvLoraRank] + kvLatent = expandedDimensions(kvLatent, axis: 1) + + // Transform q_nope through embed_q + qNope = callMultiLinear(embedQ, qNope) + + // Create keys for attention (and caching) + var keys = concatenated([kvLatent, kPe], axis: -1) + var values = kvLatent // Values are the compressed KV latent + + // Update cache with compressed representation + if let cache { + (keys, values) = cache.update(keys: keys, values: values) + } + + // Create queries + let queries = concatenated([qNope, qPe], axis: -1) + + // Compute attention + var output = MLXFast.scaledDotProductAttention( + queries: queries, + keys: keys, + values: values, + scale: scale, + mask: mask + ) + + // Transform output through unembed_out + output = callMultiLinear(unembedOut, output) + + output = output.transposed(0, 2, 1, 3).reshaped(B, L, -1) + return oProj(output) + } +} + +class GLMMoeDSAMLP: Module, UnaryLayer { + let hiddenSize: Int + let intermediateSize: Int + + @ModuleInfo(key: "gate_proj") var gateProj: Linear + @ModuleInfo(key: "up_proj") var upProj: Linear + @ModuleInfo(key: "down_proj") var downProj: Linear + + init(_ config: GLMMoeDSAConfiguration, hiddenSize: Int? = nil, intermediateSize: Int? = nil) { + self.hiddenSize = hiddenSize ?? config.hiddenSize + self.intermediateSize = intermediateSize ?? config.intermediateSize + + _gateProj.wrappedValue = Linear(self.hiddenSize, self.intermediateSize, bias: false) + _upProj.wrappedValue = Linear(self.hiddenSize, self.intermediateSize, bias: false) + _downProj.wrappedValue = Linear(self.intermediateSize, self.hiddenSize, bias: false) + } + + func callAsFunction(_ x: MLXArray) -> MLXArray { + downProj(silu(gateProj(x)) * upProj(x)) + } +} + +class GLMMoeDSAGate: Module { + let topK: Int + let normTopkProb: Bool + let nRoutedExperts: Int + let routedScalingFactor: Float + let nGroup: Int + let topkGroup: Int + + @ParameterInfo(key: "weight") var weight: MLXArray + @ParameterInfo(key: "e_score_correction_bias") var eScoreCorrectionBias: MLXArray + + init(_ config: GLMMoeDSAConfiguration) { + guard let nRoutedExperts = config.nRoutedExperts else { + fatalError("GLMMoeDSAGate requires nRoutedExperts") + } + + precondition(config.topkMethod == "noaux_tc", "Unsupported topk method.") + + self.topK = config.numExpertsPerTok + self.normTopkProb = config.normTopkProb + self.nRoutedExperts = nRoutedExperts + self.routedScalingFactor = config.routedScalingFactor + self.nGroup = config.nGroup + self.topkGroup = config.topkGroup + + _weight.wrappedValue = zeros([nRoutedExperts, config.hiddenSize]) + _eScoreCorrectionBias.wrappedValue = zeros([nRoutedExperts]) + + super.init() + } + + func callAsFunction(_ x: MLXArray) -> (MLXArray, MLXArray) { + let hiddenStates = x.matmul(weight.T) + let originalScores = sigmoid(hiddenStates.asType(.float32)) + var selectionScores = originalScores + eScoreCorrectionBias + + if nGroup > 1 { + selectionScores = unflatten(selectionScores, axis: -1, shape: [nGroup, -1]) + let groupScores = top(selectionScores, k: 2, axis: -1).sum(axis: -1, keepDims: true) + let k = nGroup - topkGroup + let groupIdx = argPartition(groupScores, kth: k - 1, axis: -2)[.ellipsis, .. 1, normTopkProb { + let denominator = selectedScores.sum(axis: -1, keepDims: true) + selectedScores = selectedScores / denominator + } + selectedScores = selectedScores * routedScalingFactor + + return (inds, selectedScores) + } +} + +class GLMMoeDSAMoE: Module, UnaryLayer { + let numExpertsPerTok: Int + let gate: GLMMoeDSAGate + + @ModuleInfo(key: "switch_mlp") var switchMLP: SwitchGLU + @ModuleInfo(key: "shared_experts") var sharedExperts: GLMMoeDSAMLP? + + init(_ config: GLMMoeDSAConfiguration) { + guard let nRoutedExperts = config.nRoutedExperts else { + fatalError("GLMMoeDSAMoE requires nRoutedExperts") + } + + self.numExpertsPerTok = config.numExpertsPerTok + self.gate = GLMMoeDSAGate(config) + + _switchMLP.wrappedValue = SwitchGLU( + inputDims: config.hiddenSize, + hiddenDims: config.moeIntermediateSize, + numExperts: nRoutedExperts + ) + + if let shared = config.nSharedExperts, shared > 0 { + let intermediateSize = config.moeIntermediateSize * shared + _sharedExperts.wrappedValue = GLMMoeDSAMLP( + config, intermediateSize: intermediateSize + ) + } + + super.init() + } + + func callAsFunction(_ x: MLXArray) -> MLXArray { + let (inds, scores) = gate(x) + var y = switchMLP(x, inds) + y = (y * scores[.ellipsis, .newAxis]).sum(axis: -2).asType(y.dtype) + if let sharedExperts { + y = y + sharedExperts(x) + } + return y + } +} + +class GLMMoeDSADecoderLayer: Module { + @ModuleInfo(key: "self_attn") var attention: GLMMoeDSAAttention + let mlp: UnaryLayer + + @ModuleInfo(key: "input_layernorm") var inputLayerNorm: RMSNorm + @ModuleInfo(key: "post_attention_layernorm") var postAttentionLayerNorm: RMSNorm + + init(_ config: GLMMoeDSAConfiguration, layerIdx: Int) { + _attention.wrappedValue = GLMMoeDSAAttention(config) + + if config.nRoutedExperts != nil, + layerIdx >= config.firstKDenseReplace, + layerIdx % config.moeLayerFreq == 0 + { + self.mlp = GLMMoeDSAMoE(config) + } else { + self.mlp = GLMMoeDSAMLP(config) + } + + _inputLayerNorm.wrappedValue = RMSNorm( + dimensions: config.hiddenSize, eps: config.rmsNormEps) + _postAttentionLayerNorm.wrappedValue = RMSNorm( + dimensions: config.hiddenSize, eps: config.rmsNormEps) + } + + func callAsFunction( + _ x: MLXArray, mask: MLXFast.ScaledDotProductAttentionMaskMode, cache: KVCache? + ) -> MLXArray { + let r = attention(inputLayerNorm(x), mask: mask, cache: cache) + let h = x + r + let r2 = mlp(postAttentionLayerNorm(h)) + return h + r2 + } +} + +public class GLMMoeDSAModelInner: Module, LayerPartitionable, StreamableMoE { + @ModuleInfo(key: "embed_tokens") var embedTokens: Embedding + + let layers: [GLMMoeDSADecoderLayer] + let norm: RMSNorm + + public var gpuLayerCount: Int? = nil + public var streamExperts: Bool = false + public var totalLayerCount: Int { layers.count } + + init(_ config: GLMMoeDSAConfiguration) { + precondition(config.vocabularySize > 0) + + _embedTokens.wrappedValue = Embedding( + embeddingCount: config.vocabularySize, dimensions: config.hiddenSize) + + self.layers = (0 ..< config.hiddenLayers) + .map { idx in + GLMMoeDSADecoderLayer(config, layerIdx: idx) + } + self.norm = RMSNorm(dimensions: config.hiddenSize, eps: config.rmsNormEps) + } + + func callAsFunction(_ inputs: MLXArray, cache: [KVCache]? = nil) -> MLXArray { + var h = embedTokens(inputs) + + let mask = createAttentionMask(h: h, cache: cache?.first) + + for (i, layer) in layers.enumerated() { + h = partitionedLayerCall(index: i, gpuLayerCount: gpuLayerCount, stream: streamExperts) { + layer(h, mask: mask, cache: cache?[i]) + } + } + + return norm(h) + } +} + +public class GLMMoeDSAModel: Module, LLMModel, KVCacheDimensionProvider { + public let vocabularySize: Int + public let kvHeads: [Int] + + public let model: GLMMoeDSAModelInner + let configuration: GLMMoeDSAConfiguration + + @ModuleInfo(key: "lm_head") var lmHead: Linear + + public init(_ args: GLMMoeDSAConfiguration) { + self.configuration = args + self.vocabularySize = args.vocabularySize + self.kvHeads = (0 ..< args.hiddenLayers).map { _ in args.kvHeads } + self.model = GLMMoeDSAModelInner(args) + + _lmHead.wrappedValue = Linear(args.hiddenSize, args.vocabularySize, bias: false) + } + + public func callAsFunction(_ inputs: MLXArray, cache: [KVCache]?) -> MLXArray { + let out = model(inputs, cache: cache) + return lmHead(out) + } + + public func sanitize(weights: [String: MLXArray]) -> [String: MLXArray] { + var sanitized = weights + + for l in 0 ..< configuration.hiddenLayers { + let prefix = "model.layers.\(l)" + + // Stack experts + for n in ["gate_proj", "down_proj", "up_proj"] { + for k in ["weight", "scales", "biases"] { + let key = "\(prefix).mlp.experts.0.\(n).\(k)" + if sanitized[key] != nil, let nRoutedExperts = configuration.nRoutedExperts { + let toJoin = (0 ..< nRoutedExperts).map { e in + sanitized.removeValue( + forKey: "\(prefix).mlp.experts.\(e).\(n).\(k)")! + } + sanitized["\(prefix).mlp.switch_mlp.\(n).\(k)"] = MLX.stacked(toJoin) + } + } + } + + // Convert kv_b_proj to embed_q and unembed_out + let attnPrefix = "\(prefix).self_attn" + if sanitized["\(attnPrefix).kv_b_proj.weight"] != nil { + let isQuantized = sanitized["\(attnPrefix).kv_b_proj.scales"] != nil + var v = sanitized.removeValue(forKey: "\(attnPrefix).kv_b_proj.weight")! + let headDim = configuration.qkNopeHeadDim + configuration.vHeadDim + + var inferredBits = 0 + var inferredGroupSize = 0 + + if isQuantized { + let dims = configuration.kvLoraRank + let scales = sanitized.removeValue(forKey: "\(attnPrefix).kv_b_proj.scales")! + let biases = sanitized.removeValue(forKey: "\(attnPrefix).kv_b_proj.biases")! + // Infer bits and group size + inferredBits = (v.dim(-1) * 32) / dims + inferredGroupSize = dims / scales.dim(-1) + v = dequantized( + v, scales: scales, biases: biases, groupSize: inferredGroupSize, + bits: inferredBits) + } + + let numHeads = configuration.attentionHeads + v = v.reshaped(numHeads, headDim, -1) + var wk = v[0..., .. 0 { + sanitized = sanitized.filter { key, _ in + for idx in 0 ..< numMptLayers { + if key.hasPrefix("model.layers.\(configuration.hiddenLayers + idx)") { + return false + } + } + return true + } + } + + return sanitized + } +} + +public struct GLMMoeDSAConfiguration: Codable, Sendable { + var modelType: String + var vocabularySize: Int + var hiddenSize: Int + var intermediateSize: Int + var moeIntermediateSize: Int + var hiddenLayers: Int + var attentionHeads: Int + var kvHeads: Int + var nSharedExperts: Int? + var nRoutedExperts: Int? + var routedScalingFactor: Float + var kvLoraRank: Int + var qLoraRank: Int? + var qkRopeHeadDim: Int + var qkNopeHeadDim: Int + var vHeadDim: Int + var indexerNHeads: Int? + var indexerHeadDim: Int? + var indexerTopk: Int? + var indexerRopeInterleave: Bool? + var topkMethod: String + var scoringFunc: String + var normTopkProb: Bool + var nGroup: Int + var topkGroup: Int + var numExpertsPerTok: Int + var moeLayerFreq: Int + var firstKDenseReplace: Int + var maxPositionEmbeddings: Int + var rmsNormEps: Float + var ropeTheta: Float + var ropeScaling: [String: StringOrNumber]? + var ropeTraditional: Bool + var attentionBias: Bool + var attentionDropout: Float + var partialRotaryFactor: Float + var tieWordEmbeddings: Bool + var numNextnPredictLayers: Int + + enum CodingKeys: String, CodingKey { + case modelType = "model_type" + case vocabularySize = "vocab_size" + case hiddenSize = "hidden_size" + case intermediateSize = "intermediate_size" + case moeIntermediateSize = "moe_intermediate_size" + case hiddenLayers = "num_hidden_layers" + case attentionHeads = "num_attention_heads" + case kvHeads = "num_key_value_heads" + case nSharedExperts = "n_shared_experts" + case nRoutedExperts = "n_routed_experts" + case routedScalingFactor = "routed_scaling_factor" + case kvLoraRank = "kv_lora_rank" + case qLoraRank = "q_lora_rank" + case qkRopeHeadDim = "qk_rope_head_dim" + case qkNopeHeadDim = "qk_nope_head_dim" + case vHeadDim = "v_head_dim" + case indexerNHeads = "index_n_heads" + case indexerHeadDim = "index_head_dim" + case indexerTopk = "index_topk" + case indexerRopeInterleave = "indexer_rope_interleave" + case topkMethod = "topk_method" + case scoringFunc = "scoring_func" + case normTopkProb = "norm_topk_prob" + case nGroup = "n_group" + case topkGroup = "topk_group" + case numExpertsPerTok = "num_experts_per_tok" + case moeLayerFreq = "moe_layer_freq" + case firstKDenseReplace = "first_k_dense_replace" + case maxPositionEmbeddings = "max_position_embeddings" + case rmsNormEps = "rms_norm_eps" + case ropeTheta = "rope_theta" + case ropeScaling = "rope_scaling" + case ropeTraditional = "rope_traditional" + case attentionBias = "attention_bias" + case attentionDropout = "attention_dropout" + case partialRotaryFactor = "partial_rotary_factor" + case tieWordEmbeddings = "tie_word_embeddings" + case numNextnPredictLayers = "num_nextn_predict_layers" + } + + public init(from decoder: Decoder) throws { + let container: KeyedDecodingContainer = + try decoder.container(keyedBy: GLMMoeDSAConfiguration.CodingKeys.self) + + self.modelType = try container.decode(String.self, forKey: .modelType) + self.vocabularySize = try container.decode(Int.self, forKey: .vocabularySize) + self.hiddenSize = try container.decode(Int.self, forKey: .hiddenSize) + self.intermediateSize = try container.decode(Int.self, forKey: .intermediateSize) + self.moeIntermediateSize = try container.decode(Int.self, forKey: .moeIntermediateSize) + self.hiddenLayers = try container.decode(Int.self, forKey: .hiddenLayers) + self.attentionHeads = try container.decode(Int.self, forKey: .attentionHeads) + self.kvHeads = try container.decode(Int.self, forKey: .kvHeads) + self.nSharedExperts = try container.decodeIfPresent(Int.self, forKey: .nSharedExperts) + self.nRoutedExperts = try container.decodeIfPresent(Int.self, forKey: .nRoutedExperts) + self.routedScalingFactor = try container.decode(Float.self, forKey: .routedScalingFactor) + self.kvLoraRank = try container.decode(Int.self, forKey: .kvLoraRank) + self.qLoraRank = try container.decodeIfPresent(Int.self, forKey: .qLoraRank) + self.qkRopeHeadDim = try container.decode(Int.self, forKey: .qkRopeHeadDim) + self.qkNopeHeadDim = try container.decode(Int.self, forKey: .qkNopeHeadDim) + self.vHeadDim = try container.decode(Int.self, forKey: .vHeadDim) + + // Optional indexer params + _ = try container.decodeIfPresent(Int.self, forKey: .indexerNHeads) + _ = try container.decodeIfPresent(Int.self, forKey: .indexerHeadDim) + _ = try container.decodeIfPresent(Int.self, forKey: .indexerTopk) + _ = try container.decodeIfPresent(Bool.self, forKey: .indexerRopeInterleave) + + self.topkMethod = + try container.decodeIfPresent(String.self, forKey: .topkMethod) ?? "noaux_tc" + self.scoringFunc = + try container.decodeIfPresent(String.self, forKey: .scoringFunc) ?? "sigmoid" + self.normTopkProb = try container.decodeIfPresent(Bool.self, forKey: .normTopkProb) ?? false + self.nGroup = try container.decodeIfPresent(Int.self, forKey: .nGroup) ?? 1 + self.topkGroup = try container.decodeIfPresent(Int.self, forKey: .topkGroup) ?? 1 + self.numExpertsPerTok = try container.decodeIfPresent(Int.self, forKey: .numExpertsPerTok) ?? 1 + self.moeLayerFreq = try container.decodeIfPresent(Int.self, forKey: .moeLayerFreq) ?? 1 + self.firstKDenseReplace = try container.decodeIfPresent(Int.self, forKey: .firstKDenseReplace) ?? 0 + self.maxPositionEmbeddings = try container.decodeIfPresent(Int.self, forKey: .maxPositionEmbeddings) ?? 131072 + self.rmsNormEps = try container.decodeIfPresent(Float.self, forKey: .rmsNormEps) ?? 1e-6 + self.ropeTheta = try container.decodeIfPresent(Float.self, forKey: .ropeTheta) ?? 10000.0 + self.ropeScaling = try container.decodeIfPresent( + [String: StringOrNumber].self, forKey: .ropeScaling) + self.ropeTraditional = + try container.decodeIfPresent(Bool.self, forKey: .ropeTraditional) ?? true + self.attentionBias = try container.decodeIfPresent(Bool.self, forKey: .attentionBias) ?? false + self.attentionDropout = + try container.decodeIfPresent(Float.self, forKey: .attentionDropout) ?? 0.0 + self.partialRotaryFactor = try container.decodeIfPresent(Float.self, forKey: .partialRotaryFactor) ?? 1.0 + self.tieWordEmbeddings = + try container.decodeIfPresent(Bool.self, forKey: .tieWordEmbeddings) + ?? false + self.numNextnPredictLayers = + try container.decodeIfPresent(Int.self, forKey: .numNextnPredictLayers) ?? 1 + } +} + +// MARK: - LoRA + +extension GLMMoeDSAModel: LoRAModel { + public var loraLayers: [Module] { + model.layers + } +} diff --git a/Libraries/MLXLLM/Models/GPTOSS.swift b/Libraries/MLXLLM/Models/GPTOSS.swift index f8ca2bcfca..1e8dedf499 100644 --- a/Libraries/MLXLLM/Models/GPTOSS.swift +++ b/Libraries/MLXLLM/Models/GPTOSS.swift @@ -332,7 +332,7 @@ class GPTOSSTransformerBlock: Module { } } -public class GPTOSSModelInner: Module { +public class GPTOSSModelInner: Module, LayerPartitionable, StreamableMoE { @ModuleInfo(key: "embed_tokens") var embedTokens: Embedding @ModuleInfo(key: "norm") var norm: RMSNorm let layerTypes: [String] @@ -341,6 +341,11 @@ public class GPTOSSModelInner: Module { let slidingAttentionIndex: Int let fullAttentionIndex: Int + // LayerPartitionable + public var gpuLayerCount: Int? + public var streamExperts: Bool = false + public var totalLayerCount: Int { layers.count } + public init(_ config: GPTOSSConfiguration) { _embedTokens.wrappedValue = Embedding( embeddingCount: config.vocabularySize, dimensions: config.hiddenSize) @@ -404,7 +409,9 @@ public class GPTOSSModelInner: Module { maskMode = slidingMask! } - x = layer(x, mask: maskMode, cache: cache[i]) + x = partitionedLayerCall(index: i, gpuLayerCount: gpuLayerCount, stream: streamExperts) { + layer(x, mask: maskMode, cache: cache[i]) + } } x = norm(x) diff --git a/Libraries/MLXLLM/Models/GatedDelta.swift b/Libraries/MLXLLM/Models/GatedDelta.swift index 7ddf39cba9..65c83cd401 100644 --- a/Libraries/MLXLLM/Models/GatedDelta.swift +++ b/Libraries/MLXLLM/Models/GatedDelta.swift @@ -289,7 +289,8 @@ func gatedDeltaUpdate( let state = state ?? MLXArray.zeros([B, Hv, Dv, Dk], dtype: q.dtype) - if GatedDeltaKernelManager.shared.kernel != nil { + let isCPU = Device.defaultDevice().deviceType == .cpu + if !isCPU, GatedDeltaKernelManager.shared.kernel != nil { return gatedDeltaKernel(q: q, k: k, v: v, g: g, beta: beta, state: state, mask: mask) } diff --git a/Libraries/MLXLLM/Models/Gemma.swift b/Libraries/MLXLLM/Models/Gemma.swift index 646460af20..a8c32bee53 100644 --- a/Libraries/MLXLLM/Models/Gemma.swift +++ b/Libraries/MLXLLM/Models/Gemma.swift @@ -128,7 +128,7 @@ class GemmaTransformerBlock: Module { } } -public class GemmaModelInner: Module { +public class GemmaModelInner: Module, LayerPartitionable { let args: GemmaConfiguration let vocabularySize: Int let numHiddenLayers: Int @@ -137,6 +137,10 @@ public class GemmaModelInner: Module { fileprivate let layers: [GemmaTransformerBlock] fileprivate let norm: Gemma.RMSNorm + // LayerPartitionable + public var gpuLayerCount: Int? + public var totalLayerCount: Int { layers.count } + public init(_ args: GemmaConfiguration) { precondition(args.vocabularySize > 0) @@ -161,7 +165,9 @@ public class GemmaModelInner: Module { let mask = createAttentionMask(h: h, cache: cache?.first) for (i, layer) in layers.enumerated() { - h = layer(h, mask: mask, cache: cache?[i]) + h = partitionedLayerCall(index: i, gpuLayerCount: gpuLayerCount) { + layer(h, mask: mask, cache: cache?[i]) + } } return norm(h) diff --git a/Libraries/MLXLLM/Models/Gemma2.swift b/Libraries/MLXLLM/Models/Gemma2.swift index cad04509d1..d202895a80 100644 --- a/Libraries/MLXLLM/Models/Gemma2.swift +++ b/Libraries/MLXLLM/Models/Gemma2.swift @@ -136,7 +136,12 @@ class Gemma2TransformerBlock: Module { } // Uses Gemma2TransformerBlock, otherwise same as GemmaModelInner -public class Gemma2ModelInner: Module { +public class Gemma2ModelInner: Module, LayerPartitionable { + + + // LayerPartitionable + public var gpuLayerCount: Int? + public var totalLayerCount: Int { layers.count } @ModuleInfo(key: "embed_tokens") var embedTokens: Embedding fileprivate let layers: [Gemma2TransformerBlock] @@ -167,7 +172,9 @@ public class Gemma2ModelInner: Module { let mask: MLXArray? = createAttentionMask(h: h, cache: cache) for (i, layer) in layers.enumerated() { - h = layer(h, mask: mask, cache: cache?[i]) + h = partitionedLayerCall(index: i, gpuLayerCount: gpuLayerCount) { + layer(h, mask: mask, cache: cache?[i]) + } } return norm(h) diff --git a/Libraries/MLXLLM/Models/Gemma4.swift b/Libraries/MLXLLM/Models/Gemma4.swift new file mode 100644 index 0000000000..25ac37510b --- /dev/null +++ b/Libraries/MLXLLM/Models/Gemma4.swift @@ -0,0 +1,943 @@ +// +// Gemma4.swift +// mlx-swift-lm +// +// Created for SwiftLM Gemma 4 Support +// + +import Foundation +import MLX +import MLXLMCommon +import MLXNN + +public struct Gemma4Configuration: Codable { + let modelType: String + let hiddenSize: Int + let hiddenLayers: Int + let intermediateSize: Int + let attentionHeads: Int + let headDim: Int + let rmsNormEps: Float + let vocabularySize: Int + let kvHeads: Int + let ropeTheta: Float + let ropeLocalBaseFreq: Float + let ropeTraditional: Bool + let queryPreAttnScalar: Float? + let slidingWindow: Int + let slidingWindowPattern: Int + let maxPositionEmbeddings: Int + let ropeScaling: [String: StringOrNumber]? + let globalHeadDim: Int + let numKvSharedLayers: Int + let useDoubleWideMlp: Bool + + // MoE / Global KV Configurations + public let numExperts: Int? + public let topKExperts: Int? + public let moeIntermediateSize: Int? + public let numGlobalKeyValueHeads: Int + public let tieWordEmbeddings: Bool + public let enableMoeBlock: Bool + + /// Fraction of global head_dim used for RoPE (default 0.25 for Gemma 4 global attn) + let globalRopePartialFactor: Float + /// Final logit softcapping value (0 = disabled). Gemma 4 uses 30.0. + let finalLogitSoftcapping: Float + /// Per-layer conditioning dimension (0 = disabled) + let hiddenSizePerLayerInput: Int + /// Vocabulary size for per-layer embedding table (0 = disabled) + let vocabSizePerLayerInput: Int + + public init( + modelType: String, hiddenSize: Int, hiddenLayers: Int, intermediateSize: Int, + attentionHeads: Int, headDim: Int, rmsNormEps: Float, vocabularySize: Int, kvHeads: Int, + ropeTheta: Float, ropeLocalBaseFreq: Float, ropeTraditional: Bool, + queryPreAttnScalar: Float?, slidingWindow: Int, slidingWindowPattern: Int, + maxPositionEmbeddings: Int, ropeScaling: [String: StringOrNumber]? = nil, + globalHeadDim: Int = 512, numKvSharedLayers: Int = 0, useDoubleWideMlp: Bool = false, + tieWordEmbeddings: Bool = true, + numExperts: Int? = nil, topKExperts: Int? = nil, moeIntermediateSize: Int? = nil, + numGlobalKeyValueHeads: Int? = nil, + hiddenSizePerLayerInput: Int = 0, vocabSizePerLayerInput: Int = 0, + globalRopePartialFactor: Float = 0.25, + finalLogitSoftcapping: Float = 0.0, + enableMoeBlock: Bool? = nil + ) { + self.modelType = modelType + self.hiddenSize = hiddenSize + self.hiddenLayers = hiddenLayers + self.intermediateSize = intermediateSize + self.attentionHeads = attentionHeads + self.headDim = headDim + self.rmsNormEps = rmsNormEps + self.vocabularySize = vocabularySize + self.kvHeads = kvHeads + self.ropeTheta = ropeTheta + self.ropeLocalBaseFreq = ropeLocalBaseFreq + self.ropeTraditional = ropeTraditional + self.queryPreAttnScalar = queryPreAttnScalar + self.slidingWindow = slidingWindow + self.slidingWindowPattern = slidingWindowPattern + self.maxPositionEmbeddings = maxPositionEmbeddings + self.ropeScaling = ropeScaling + self.globalHeadDim = globalHeadDim + self.numKvSharedLayers = numKvSharedLayers + self.useDoubleWideMlp = useDoubleWideMlp + self.tieWordEmbeddings = tieWordEmbeddings + self.numExperts = numExperts + self.topKExperts = topKExperts + self.moeIntermediateSize = moeIntermediateSize + self.numGlobalKeyValueHeads = numGlobalKeyValueHeads ?? kvHeads + self.hiddenSizePerLayerInput = hiddenSizePerLayerInput + self.vocabSizePerLayerInput = vocabSizePerLayerInput + self.globalRopePartialFactor = globalRopePartialFactor + self.finalLogitSoftcapping = finalLogitSoftcapping + self.enableMoeBlock = enableMoeBlock ?? (numExperts != nil && numExperts! > 0) + } + + enum CodingKeys: String, CodingKey { + case modelType = "model_type" + case hiddenSize = "hidden_size" + case hiddenLayers = "num_hidden_layers" + case intermediateSize = "intermediate_size" + case attentionHeads = "num_attention_heads" + case headDim = "head_dim" + case rmsNormEps = "rms_norm_eps" + case vocabularySize = "vocab_size" + case kvHeads = "num_key_value_heads" + case ropeTheta = "rope_theta" + case ropeLocalBaseFreq = "rope_local_base_freq" + case ropeTraditional = "rope_traditional" + case queryPreAttnScalar = "query_pre_attn_scalar" + case slidingWindow = "sliding_window" + case slidingWindowPattern = "sliding_window_pattern" + case maxPositionEmbeddings = "max_position_embeddings" + case ropeScaling = "rope_scaling" + case globalHeadDim = "global_head_dim" + case numKvSharedLayers = "num_kv_shared_layers" + case useDoubleWideMlp = "use_double_wide_mlp" + case tieWordEmbeddings = "tie_word_embeddings" + case numGlobalKeyValueHeads = "num_global_key_value_heads" + // MoE + case numExperts = "num_experts" + case topKExperts = "top_k_experts" + case moeIntermediateSize = "moe_intermediate_size" + case enableMoeBlock = "enable_moe_block" + // Per-layer conditioning + case hiddenSizePerLayerInput = "hidden_size_per_layer_input" + case vocabSizePerLayerInput = "vocab_size_per_layer_input" + // Logit softcapping + case finalLogitSoftcapping = "final_logit_softcapping" + } + + // Top-level keys (outside text_config) + enum TopLevelCodingKeys: String, CodingKey { + case textConfig = "text_config" + } + + enum VLMCodingKeys: String, CodingKey { + case textConfig = "text_config" + case enableMoeBlock = "enable_moe_block" + } + + public init(from decoder: Decoder) throws { + let nestedContainer = try decoder.container(keyedBy: VLMCodingKeys.self) + + let container = + if nestedContainer.contains(.textConfig) { + try nestedContainer.nestedContainer(keyedBy: CodingKeys.self, forKey: .textConfig) + } else { + try decoder.container(keyedBy: CodingKeys.self) + } + + modelType = try container.decode(String.self, forKey: .modelType) + + let tieWordOpt = try container.decodeIfPresent(Bool.self, forKey: .tieWordEmbeddings) + tieWordEmbeddings = tieWordOpt ?? true + numExperts = try container.decodeIfPresent(Int.self, forKey: .numExperts) + topKExperts = try container.decodeIfPresent(Int.self, forKey: .topKExperts) + moeIntermediateSize = try container.decodeIfPresent(Int.self, forKey: .moeIntermediateSize) + + let enableMoeOpt = try container.decodeIfPresent(Bool.self, forKey: .enableMoeBlock) + enableMoeBlock = enableMoeOpt ?? (self.numExperts != nil && self.numExperts! > 0) + + numGlobalKeyValueHeads = try container.decodeIfPresent(Int.self, forKey: .numGlobalKeyValueHeads) ?? (try container.decodeIfPresent(Int.self, forKey: .kvHeads) ?? 1) + hiddenSize = try container.decodeIfPresent(Int.self, forKey: .hiddenSize) ?? 1152 + hiddenLayers = try container.decodeIfPresent(Int.self, forKey: .hiddenLayers) ?? 26 + + intermediateSize = + try container.decodeIfPresent(Int.self, forKey: .intermediateSize) ?? 6912 + attentionHeads = try container.decodeIfPresent(Int.self, forKey: .attentionHeads) ?? 4 + headDim = try container.decodeIfPresent(Int.self, forKey: .headDim) ?? 256 + rmsNormEps = try container.decodeIfPresent(Float.self, forKey: .rmsNormEps) ?? 1.0e-6 + vocabularySize = try container.decodeIfPresent(Int.self, forKey: .vocabularySize) ?? 262144 + kvHeads = try container.decodeIfPresent(Int.self, forKey: .kvHeads) ?? 1 + ropeTheta = try container.decodeIfPresent(Float.self, forKey: .ropeTheta) ?? 1_000_000.0 + ropeLocalBaseFreq = try container.decodeIfPresent(Float.self, forKey: .ropeLocalBaseFreq) ?? 10_000.0 + ropeTraditional = try container.decodeIfPresent(Bool.self, forKey: .ropeTraditional) ?? true + queryPreAttnScalar = try container.decodeIfPresent(Float.self, forKey: .queryPreAttnScalar) + finalLogitSoftcapping = try container.decodeIfPresent(Float.self, forKey: .finalLogitSoftcapping) ?? 0.0 + slidingWindow = try container.decodeIfPresent(Int.self, forKey: .slidingWindow) ?? 512 + slidingWindowPattern = try container.decodeIfPresent(Int.self, forKey: .slidingWindowPattern) ?? (hiddenLayers == 35 ? 5 : 6) + maxPositionEmbeddings = try container.decodeIfPresent(Int.self, forKey: .maxPositionEmbeddings) ?? 32768 + ropeScaling = try container.decodeIfPresent([String: StringOrNumber].self, forKey: .ropeScaling) + globalHeadDim = try container.decodeIfPresent(Int.self, forKey: .globalHeadDim) ?? 512 + numKvSharedLayers = try container.decodeIfPresent(Int.self, forKey: .numKvSharedLayers) ?? 0 + useDoubleWideMlp = try container.decodeIfPresent(Bool.self, forKey: .useDoubleWideMlp) ?? false + // Per-layer conditioning + self.hiddenSizePerLayerInput = try container.decodeIfPresent(Int.self, forKey: .hiddenSizePerLayerInput) ?? 0 + self.vocabSizePerLayerInput = try container.decodeIfPresent(Int.self, forKey: .vocabSizePerLayerInput) ?? 0 + // Parse partial_rotary_factor for global attention from rope_parameters.full_attention + // Gemma 4 uses only 25% of global_head_dim (512) for positional encoding = 128 rotated dims. + struct AC: CodingKey { + var stringValue: String; init?(stringValue s: String) { stringValue = s } + var intValue: Int? { nil }; init?(intValue _: Int) { nil } + } + if let nestedContainer = try? decoder.container(keyedBy: AC.self), + let ropeParamsContainer = try? nestedContainer.nestedContainer(keyedBy: AC.self, forKey: AC(stringValue: "rope_parameters")!), + let fullAttnContainer = try? ropeParamsContainer.nestedContainer(keyedBy: AC.self, forKey: AC(stringValue: "full_attention")!), + let prf = try? fullAttnContainer.decode(Float.self, forKey: AC(stringValue: "partial_rotary_factor")!) { + self.globalRopePartialFactor = prf + } else { + self.globalRopePartialFactor = 0.25 // Gemma 4 default: 128/512 + } + } +} + +public class Gemma4RMSNormNoScale: Module { + let eps: Float + + public init(eps: Float = 1e-6) { + self.eps = eps + super.init() + } + + public func callAsFunction(_ x: MLXArray) -> MLXArray { + let xFloat32 = x.asType(.float32) + let meanSq = MLX.mean(MLX.square(xFloat32), axes: [-1], keepDims: true) + let inverseNorm = MLX.rsqrt(meanSq + eps) + return (xFloat32 * inverseNorm).asType(x.dtype) + } +} + +/// Proportional RoPE for Gemma 4 full-attention layers. +/// +/// Frequencies are computed relative to the full head dimension, and rotation is +/// applied to the first rotated_dims//2 elements of each half of the head, matching +/// the HF `rotate_half` convention used in the Python reference. +public class Gemma4ProportionalRoPE: Module, OffsetLayer { + let dims: Int + let traditional: Bool + let rotatedDims: Int + /// Stored as private; NOT a model parameter - computed at init from base/dims. + private var _computedFreqs: MLXArray? + + public init(dims: Int, traditional: Bool = false, base: Float = 10000.0, partialRotaryFactor: Float = 1.0) { + self.dims = dims + self.traditional = traditional + + let ropeAngles = Int(partialRotaryFactor * Float(dims) / 2.0) + self.rotatedDims = 2 * ropeAngles + + if rotatedDims > 0 { + let exponents = MLXArray(stride(from: Float(0), to: Float(rotatedDims), by: 2)) / Float(dims) + self._computedFreqs = MLXArray(base) ** exponents + } else { + self._computedFreqs = nil + } + + super.init() + // Freeze so the module system ignores this class entirely for weight loading + self.freeze() + } + + public func callAsFunction(_ x: MLXArray, offset: Int) -> MLXArray { + guard rotatedDims > 0, let freqs = _computedFreqs else { return x } + + let head = x[0..., 0..., 0..., 0.. 0 ? nKVHeads : 1) + self.headDim = self.isSliding ? config.headDim : config.globalHeadDim + + // Python reference: self.scale = 1.0 — Q/K RMS norms handle magnitude. + self.scale = 1.0 + self.attnLogitSoftcap = 0.0 + + self._queryProj.wrappedValue = Linear(dim, nHeads * self.headDim, bias: false) + self._keyProj.wrappedValue = Linear(dim, nKVHeads * self.headDim, bias: false) + self._valueProj.wrappedValue = Linear(dim, nKVHeads * self.headDim, bias: false) + self._outputProj.wrappedValue = Linear(nHeads * self.headDim, dim, bias: false) + + self._queryNorm.wrappedValue = RMSNorm( + dimensions: self.headDim, eps: config.rmsNormEps) + self._keyNorm.wrappedValue = RMSNorm(dimensions: self.headDim, eps: config.rmsNormEps) + self._valueNorm.wrappedValue = Gemma4RMSNormNoScale(eps: config.rmsNormEps) + + let ropeFactor = config.globalRopePartialFactor + self.globalRopePartialFactor = ropeFactor + + if isSliding { + // Sliding attention: standard RoPE on full head_dim + self.rope = RoPE( + dimensions: headDim, traditional: false, + base: config.ropeLocalBaseFreq, scale: 1.0) + } else { + // Global attention: ProportionalRoPE with partial rotation + self.rope = Gemma4ProportionalRoPE( + dims: self.headDim, + traditional: false, + base: 1000000.0, // rope_parameters.full_attention.rope_theta + partialRotaryFactor: ropeFactor + ) + } + + super.init() + } + + func callAsFunction( + _ x: MLXArray, + mask: MLXFast.ScaledDotProductAttentionMaskMode, + cache: KVCache? = nil + ) -> MLXArray { + let (B, L, _) = (x.dim(0), x.dim(1), x.dim(2)) + + var queries = queryProj(x) + var keys = keyProj(x) + var values = valueProj(x) + + queries = queries.reshaped(B, L, nHeads, -1).transposed(0, 2, 1, 3) + keys = keys.reshaped(B, L, nKVHeads, -1).transposed(0, 2, 1, 3) + values = values.reshaped(B, L, nKVHeads, -1).transposed(0, 2, 1, 3) + + queries = queryNorm(queries) + keys = keyNorm(keys) + values = valueNorm(values) + + // Python reference: rope applies to keys BEFORE cache update, queries AFTER. + // RoPE is applied to full head_dim; partial rotation is handled by rope init (dims param). + let LCache = cache?.offset ?? 0 + // Apply RoPE to keys first (before cache), then queries + keys = rope(keys, offset: LCache) + queries = rope(queries, offset: LCache) + + let output: MLXArray + if attnLogitSoftcap > 0 { + // Gemma 4 uses QK attention logit softcapping before softmax: + // scores = tanh(scores / cap) * cap (llama.cpp llm_build_gemma4_iswa) + // MLXFast.scaledDotProductAttention has no softcap parameter, so we do it manually. + let (cachedKeys, cachedValues) = cache?.update(keys: keys, values: values) ?? (keys, values) + var fullKeys = cachedKeys + var fullValues = cachedValues + // TurboKV decode if needed + if let kvCache = cache as? KVCacheSimple, + let pk = kvCache.polarKeys, let pv = kvCache.polarValues, + kvCache.compressedOffset > 0 { + var histK = MLXFast.turboDecodeK(packed: pk).asType(cachedKeys.dtype) + var histV = MLXFast.turboDecodeV(packed: pv).asType(cachedValues.dtype) + // Merge 2×256 virtual heads back to original count × 512 + if kvCache.turboSplitHeads { + let B = histK.dim(0), H2 = histK.dim(1), T = histK.dim(2) + histK = histK.reshaped(B, H2 / 2, T, 512) + histV = histV.reshaped(B, H2 / 2, T, 512) + } + fullKeys = concatenated([histK, cachedKeys], axis: 2) + fullValues = concatenated([histV, cachedValues], axis: 2) + } + // GQA expansion + var k = fullKeys + var v = fullValues + if nHeads > nKVHeads { + k = MLX.repeated(k, count: repeats, axis: 1) + v = MLX.repeated(v, count: repeats, axis: 1) + } + // scores: [B, nH, L, S] + var scores = (queries * scale).matmul(k.transposed(0, 1, 3, 2)) + // Apply attention mask + if let maskArray = mask.mask { + scores = scores + maskArray + } + // Apply QK softcap: tanh(scores / cap) * cap + // Critically, we MUST evaluate tanh in float32. In float16/bfloat16, tanh(x) saturates + // to exactly 1.0 for very small values above 3.0 (due to lack of mantissa bits!), + // destroying all confidence gradients and resulting in uniform distributions! + let originalType = scores.dtype + let scoresF32 = scores.asType(.float32) + let cap = MLXArray(attnLogitSoftcap).asType(.float32) + scores = (MLX.tanh(scoresF32 / cap) * cap).asType(originalType) + // Softmax + weighted sum + let attnWeights = MLX.softmax(scores.asType(.float32), axis: -1).asType(scores.dtype) + output = matmul(attnWeights, v) + } else { + output = attentionWithCacheUpdate( + queries: queries, keys: keys, values: values, + cache: cache, scale: scale, mask: mask) + } + return outputProj( + output.transposed(0, 2, 1, 3).reshaped(B, L, -1) + ) + } +} + +public class Gemma4MLP: Module { + @ModuleInfo(key: "gate_proj") var gateProj: Linear + @ModuleInfo(key: "down_proj") var downProj: Linear + @ModuleInfo(key: "up_proj") var upProj: Linear + + public init(dimensions: Int, hiddenDimensions: Int) { + self._gateProj.wrappedValue = Linear(dimensions, hiddenDimensions, bias: false) + self._downProj.wrappedValue = Linear(hiddenDimensions, dimensions, bias: false) + self._upProj.wrappedValue = Linear(dimensions, hiddenDimensions, bias: false) + } + + public func callAsFunction(_ x: MLXArray) -> MLXArray { + // Python reference: nn.gelu_approx(self.gate_proj(x)) * self.up_proj(x) + return downProj(geluApproximate(gateProj(x)) * upProj(x)) + } +} + +class Gemma4Router: Module { + @ModuleInfo(key: "proj") var proj: Linear + @ModuleInfo(key: "scale") var scale: MLXArray + @ModuleInfo(key: "per_expert_scale") var perExpertScale: MLXArray + + let eps: Float + let scalarRootSize: Float + + public init(dimensions: Int, numExperts: Int, eps: Float) { + self.eps = eps + self.scalarRootSize = 1.0 / sqrt(Float(dimensions)) + self._proj.wrappedValue = Linear(dimensions, numExperts, bias: false) + self._scale.wrappedValue = MLXArray.ones([dimensions]) + self._perExpertScale.wrappedValue = MLXArray.ones([numExperts]) + super.init() + } + + public func callAsFunction(_ x: MLXArray, topK: Int) -> (MLXArray, MLXArray) { + // Python reference: RMSNormNoScale → scale multiply → 1/sqrt(hidden) → proj → softmax → topK + // RMS norm without learnable weight (None weight) + let xF32 = x.asType(.float32) + let meanX2 = MLX.mean(MLX.square(xF32), axes: [-1], keepDims: true) + let xNormed = (x * MLX.rsqrt(meanX2 + MLXArray(eps))).asType(x.dtype) + + // Scale: x * root_size * scale (Python: x * self._root_size * self.scale) + let scaled = xNormed * MLXArray(scalarRootSize) * scale + + let expertScores = proj(scaled) + let routerProbs = MLX.softmax(expertScores, axis: -1) + + // Python: argpartition(-expert_scores, kth=topK-1)[..., :topK] + let negScores = MLX.negative(expertScores) + let allInds = MLX.argPartition(negScores, kth: topK - 1, axis: -1) + let topKInds = allInds[0..., 0..., 0.. MLXArray { + let (scores, inds) = router(routerInput, topK: topK) + let y = switchGLU(x, inds) + + let B = y.dim(0) + let T = y.dim(1) + + let yMasked = y * scores[0..., 0..., 0..., .newAxis] + let yMerged = yMasked.sum(axis: 2) + + return yMerged.reshaped([B, T, -1]) + } +} + +class Gemma4TransformerBlock: Module { + @ModuleInfo(key: "self_attn") var selfAttention: Gemma4Attention + @ModuleInfo var mlp: Gemma4MLP + @ModuleInfo(key: "experts") var expertsBlock: Gemma4SparseMoeBlock? + + @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 specific norms + @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? + + // Per-layer conditioning (Gemma 4 architectural novelty) + @ModuleInfo(key: "per_layer_input_gate") var perLayerInputGate: Linear? + @ModuleInfo(key: "per_layer_projection") var perLayerProjectionLayer: Linear? + @ModuleInfo(key: "post_per_layer_input_norm") var postPerLayerInputNorm: RMSNorm? + + @ModuleInfo(key: "layer_scalar") var layerScalar: MLXArray + + let numAttentionHeads: Int + let hiddenSize: Int + let layerIdx: Int + let isMoe: Bool + let hasPerLayerInput: Bool + + init(_ config: Gemma4Configuration, layerIdx: Int) { + self.numAttentionHeads = config.attentionHeads + self.hiddenSize = config.hiddenSize + self.layerIdx = layerIdx + self.hasPerLayerInput = config.hiddenSizePerLayerInput > 0 + + self._selfAttention.wrappedValue = Gemma4Attention(config, layerIdx: layerIdx) + + let mlpSize: Int + if config.useDoubleWideMlp && layerIdx >= (config.hiddenLayers - config.numKvSharedLayers) { + mlpSize = config.intermediateSize * 2 + } else { + mlpSize = config.intermediateSize + } + self.mlp = Gemma4MLP(dimensions: config.hiddenSize, hiddenDimensions: mlpSize) + + self.isMoe = config.enableMoeBlock + + if self.isMoe { + let numExperts = config.numExperts ?? 1 + self._expertsBlock.wrappedValue = Gemma4SparseMoeBlock( + dimensions: config.hiddenSize, + numExperts: numExperts, + topK: config.topKExperts ?? 1, + moeIntermediateSize: config.moeIntermediateSize ?? config.intermediateSize + ) + + self._postFeedforwardLayerNorm1.wrappedValue = RMSNorm(dimensions: config.hiddenSize, eps: config.rmsNormEps) + self._preFeedforwardLayerNorm2.wrappedValue = RMSNorm(dimensions: config.hiddenSize, eps: config.rmsNormEps) + self._postFeedforwardLayerNorm2.wrappedValue = RMSNorm(dimensions: config.hiddenSize, eps: config.rmsNormEps) + } + + if hasPerLayerInput { + self._perLayerInputGate.wrappedValue = Linear( + config.hiddenSize, config.hiddenSizePerLayerInput, bias: false) + self._perLayerProjectionLayer.wrappedValue = Linear( + config.hiddenSizePerLayerInput, config.hiddenSize, bias: false) + self._postPerLayerInputNorm.wrappedValue = RMSNorm( + dimensions: config.hiddenSize, eps: config.rmsNormEps) + } + + self._inputLayerNorm.wrappedValue = RMSNorm(dimensions: config.hiddenSize, eps: config.rmsNormEps) + self._postAttentionLayerNorm.wrappedValue = RMSNorm(dimensions: config.hiddenSize, eps: config.rmsNormEps) + self._preFeedforwardLayerNorm.wrappedValue = RMSNorm(dimensions: config.hiddenSize, eps: config.rmsNormEps) + self._postFeedforwardLayerNorm.wrappedValue = RMSNorm(dimensions: config.hiddenSize, eps: config.rmsNormEps) + self._layerScalar.wrappedValue = MLXArray.ones([1]) + + super.init() + } + + func callAsFunction( + _ x: MLXArray, + mask: MLXFast.ScaledDotProductAttentionMaskMode, + cache: KVCache? = nil, + perLayerInput: MLXArray? = nil + ) -> MLXArray { + let inputNorm = inputLayerNorm(x) + let r = selfAttention(inputNorm, mask: mask, cache: cache) + let attnNorm = postAttentionLayerNorm(r) + + var residualUpdates: MLXArray + + if isMoe, + let eb = expertsBlock, + let n1 = postFeedforwardLayerNorm1, + let preN2 = preFeedforwardLayerNorm2, + let postN2 = postFeedforwardLayerNorm2 { + let preMLPNorm = preFeedforwardLayerNorm(x + attnNorm) + let denseOut = mlp(preMLPNorm) + let densePostNorm1 = n1(denseOut) + + // Router evaluates on the un-normed `attn_out` stream + let routerInput = x + attnNorm + + // Experts evaluate on the DENSE-NORMED sparse stream (llama.cpp `ffn_pre_norm_2`) + let sparsePreNorm = preN2(routerInput) + let sparseOut = eb(sparsePreNorm, routerInput: routerInput) + let sparsePostNorm2 = postN2(sparseOut) + + let combined = densePostNorm1 + sparsePostNorm2 + let postMLPNorm = postFeedforwardLayerNorm(combined) + residualUpdates = attnNorm + postMLPNorm + } else { + let preMLPNorm = preFeedforwardLayerNorm(x + attnNorm) + let r2 = mlp(preMLPNorm) + let postMLPNorm = postFeedforwardLayerNorm(r2) + residualUpdates = attnNorm + postMLPNorm + } + + // Per-layer conditioning residual (Gemma 4 architectural novelty) + // Applied after attn+MLP, to the updates before they are added to the root state + if hasPerLayerInput, + let pli = perLayerInput, + let gate = perLayerInputGate, + let proj = perLayerProjectionLayer, + let norm = postPerLayerInputNorm + { + var gated = gate(x + residualUpdates) // Wait, Gemma 4 conditions on accumulated state? Let's assume yes. + gated = geluApproximate(gated) + gated = gated * pli + gated = proj(gated) + gated = norm(gated) + residualUpdates = residualUpdates + gated + } + + // Apply Gemma 4 residual scaling to the ENTIRE stream, avoiding exponential variance explosion + return (x + residualUpdates) * layerScalar + } +} + +// Restored LayerPartitionable & StreamableMoE conformance to re-enable +// SSD expert streaming, bridging the missing protocols from Damon Janis's initial draft. +// Reference: https://github.com/SharpAI/mlx-swift-lm/pull/1 +public class Gemma4ModelInternal: Module, LayerPartitionable, StreamableMoE { + @ModuleInfo(key: "embed_tokens") var embedTokens: Embedding + @ModuleInfo var layers: [Gemma4TransformerBlock] + @ModuleInfo var norm: RMSNorm + + // Per-layer conditioning weights (Gemma 4 architectural novelty) + @ModuleInfo(key: "embed_tokens_per_layer") var embedTokensPerLayer: Embedding? + @ModuleInfo(key: "per_layer_model_projection") var perLayerModelProjection: Linear? + @ModuleInfo(key: "per_layer_projection_norm") var perLayerProjectionNorm: RMSNorm? + + let config: Gemma4Configuration + + // LayerPartitionable + public var gpuLayerCount: Int? = nil + public var totalLayerCount: Int { layers.count } + + // StreamableMoE + public var streamExperts: Bool = false + + init(_ config: Gemma4Configuration) { + self.config = config + + self._embedTokens.wrappedValue = Embedding( + embeddingCount: config.vocabularySize, + dimensions: config.hiddenSize + ) + + self._layers.wrappedValue = (0 ..< config.hiddenLayers).map { layerIdx in + Gemma4TransformerBlock(config, layerIdx: layerIdx) + } + + self.norm = RMSNorm(dimensions: config.hiddenSize, eps: config.rmsNormEps) + + if config.hiddenSizePerLayerInput > 0 { + // embed_tokens_per_layer: [vocabSizePerLayerInput, numLayers × hiddenSizePerLayerInput] + self._embedTokensPerLayer.wrappedValue = Embedding( + embeddingCount: config.vocabSizePerLayerInput, + dimensions: config.hiddenLayers * config.hiddenSizePerLayerInput + ) + // per_layer_model_projection: [hiddenSize → numLayers × hiddenSizePerLayerInput] + self._perLayerModelProjection.wrappedValue = Linear( + config.hiddenSize, + config.hiddenLayers * config.hiddenSizePerLayerInput, + bias: false + ) + self._perLayerProjectionNorm.wrappedValue = RMSNorm( + dimensions: config.hiddenSizePerLayerInput, eps: config.rmsNormEps) + } + + super.init() + } + + func callAsFunction( + _ inputs: MLXArray, mask: MLXFast.ScaledDotProductAttentionMaskMode? = nil, + cache: [KVCache?]? = nil + ) -> MLXArray { + var h = embedTokens(inputs) + // Python reference: h = h * self.embed_scale where embed_scale = hidden_size**0.5 + h = h * MLXArray(Float(config.hiddenSize).squareRoot()) + var layerCache = cache + if layerCache == nil { + layerCache = Array(repeating: nil as KVCache?, count: layers.count) + } + + let globalMask = createAttentionMask(h: h, cache: cache?[config.slidingWindowPattern - 1]) + let slidingWindowMask: MLXFast.ScaledDotProductAttentionMaskMode = + config.slidingWindowPattern > 1 + ? createAttentionMask(h: h, cache: cache?[0], windowSize: config.slidingWindow) + : .none + + // Compute per-layer conditioning tensor: [B, L, numLayers, hiddenSizePerLayerInput] + // Combines a separate token-embedding table with a projection of the main embeddings. + var perLayerInputs: MLXArray? = nil + if config.hiddenSizePerLayerInput > 0, + let embedPerLayer = embedTokensPerLayer, + let modelProj = perLayerModelProjection, + let projNorm = perLayerProjectionNorm + { + let B = inputs.dim(0) + let L = inputs.dim(1) + let nL = config.hiddenLayers + let D = config.hiddenSizePerLayerInput + + // Token-based per-layer embeddings, scaled by sqrt(hiddenSizePerLayerInput) + let tokenScale = MLXArray(sqrt(Float(D))).asType(h.dtype) + let tokenEmbeds = (embedPerLayer(inputs) * tokenScale) + .reshaped(B, L, nL, D) // [B, L, numLayers, D] + + // Project main embeddings, scale by 1/sqrt(hiddenSize), reshape, then norm + let projScale = MLXArray(1.0 / sqrt(Float(config.hiddenSize))).asType(h.dtype) + let modelProjected = (modelProj(h) * projScale) + .reshaped(B, L, nL, D) // [B, L, numLayers, D] + let modelProjectedNormed = projNorm(modelProjected) + + // Combine: (tokenEmbeds + projection) * (1/sqrt(2)) + let combineScale = MLXArray(Float(1.0 / 2.0.squareRoot())).asType(h.dtype) + perLayerInputs = (tokenEmbeds + modelProjectedNormed) * combineScale + } + + for (i, layer) in layers.enumerated() { + let isGlobal = (i % config.slidingWindowPattern == config.slidingWindowPattern - 1) + let layerMask = isGlobal ? globalMask : slidingWindowMask + // Slice per-layer conditioning for this layer: [B, L, D] + let pli = perLayerInputs.map { $0[0..., 0..., i, 0...] } + + h = partitionedLayerCall(index: i, gpuLayerCount: gpuLayerCount, stream: streamExperts, cacheToEval: layerCache?[i]) { + layer(h, mask: layerMask, cache: layerCache?[i], perLayerInput: pli) + } + } + return norm(h) + } +} + +public class Gemma4Model: Module, LLMModel { + + @ModuleInfo public var model: Gemma4ModelInternal + @ModuleInfo(key: "lm_head") var lmHead: Linear? + + public let config: Gemma4Configuration + public var vocabularySize: Int { config.vocabularySize } + + public init(_ config: Gemma4Configuration) { + self.config = config + self.model = Gemma4ModelInternal(config) + if !config.tieWordEmbeddings { + self._lmHead.wrappedValue = Linear(config.hiddenSize, config.vocabularySize, bias: false) + } + super.init() + } + + public func callAsFunction(_ inputs: MLXArray, cache: [KVCache]? = nil) -> MLXArray { + var out = model(inputs, mask: nil, cache: cache) + if let lmHead { + out = lmHead(out) + } else { + out = model.embedTokens.asLinear(out) + } + // Apply final logit softcapping (Python reference line 579-580) + if config.finalLogitSoftcapping > 0 { + let cap = MLXArray(config.finalLogitSoftcapping) + out = MLX.tanh(out / cap) * cap + } + return out + } + + public func sanitize(weights: [String: MLXArray], metadata: [String: String]) -> [String: MLXArray] { + var processedWeights = weights + + let unflattened = ModuleParameters.unflattened(weights) + if let lm = unflattened["language_model"] { + processedWeights = Dictionary(uniqueKeysWithValues: lm.flattened()) + } + + let expectedVocab = config.vocabularySize + let keysToCheck = [ + "model.embed_tokens.weight", "model.embed_tokens.scales", "model.embed_tokens.biases", + "lm_head.weight", "lm_head.scales", "lm_head.biases", + ] + for key in keysToCheck { + if let tensor = processedWeights[key], tensor.dim(0) > expectedVocab { + processedWeights[key] = tensor[0 ..< expectedVocab] + } + } + + var finalWeights = [String: MLXArray]() + for (k, v) in processedWeights { + if k.contains("self_attn.rotary_emb") || k.contains("input_max") || k.contains("input_min") || k.contains("output_max") || k.contains("output_min") { + continue + } + if k.hasSuffix(".experts.gate_up_proj.weight") { + let base = k.replacingOccurrences(of: ".experts.gate_up_proj.weight", with: ".experts.switch_glu") + let parts = MLX.split(v, parts: 2, axis: -2) + finalWeights["\(base).gate_proj.weight"] = parts[0] + finalWeights["\(base).up_proj.weight"] = parts[1] + continue + } + if k.hasSuffix(".experts.down_proj.weight") { + let base = k.replacingOccurrences(of: ".experts.down_proj.weight", with: ".experts.switch_glu.down_proj.weight") + finalWeights[base] = v + continue + } + let newK = k.replacingOccurrences(of: ".router.", with: ".experts.router.") + finalWeights[newK] = v + } + + // Explicitly map per_layer_projection_norm to ensure it survives flattening + if let normWeight = weights["language_model.model.per_layer_projection_norm.weight"] { + finalWeights["model.per_layer_projection_norm.weight"] = normWeight + } else if let normWeight = weights["model.per_layer_projection_norm.weight"] { + finalWeights["model.per_layer_projection_norm.weight"] = normWeight + } + + // Handle mixed-quantization: MLP and MoE experts might be 8-bit while other layers are 4-bit. + for i in 0.. [KVCache] { + var caches = [KVCache]() + let slidingWindow = config.slidingWindow + let slidingWindowPattern = config.slidingWindowPattern + + for i in 0 ..< config.hiddenLayers { + let isGlobalLayer = (i % slidingWindowPattern == slidingWindowPattern - 1) + + if isGlobalLayer { + let cache = StandardKVCache() + cache.step = 1024 + caches.append(cache) + } else { + caches.append( + RotatingKVCache(maxSize: slidingWindow, keep: 0) + ) + } + } + + return caches + } + +} + +extension Gemma4Model: LoRAModel { + public var loraLayers: [Module] { + model.layers.map { $0 as Module } + } +} diff --git a/Libraries/MLXLLM/Models/Granite.swift b/Libraries/MLXLLM/Models/Granite.swift index a2ee21f191..3fd3e01257 100644 --- a/Libraries/MLXLLM/Models/Granite.swift +++ b/Libraries/MLXLLM/Models/Granite.swift @@ -131,7 +131,12 @@ class GraniteTransformerBlock: Module { } } -public class GraniteModelInner: Module { +public class GraniteModelInner: Module, LayerPartitionable { + + + // LayerPartitionable + public var gpuLayerCount: Int? + public var totalLayerCount: Int { layers.count } @ModuleInfo(key: "embed_tokens") var embedTokens: Embedding fileprivate let layers: [GraniteTransformerBlock] let norm: RMSNorm @@ -157,7 +162,9 @@ public class GraniteModelInner: Module { let mask = createAttentionMask(h: h, cache: cache?.first) for (i, layer) in layers.enumerated() { - h = layer(h, mask: mask, cache: cache?[i]) + h = partitionedLayerCall(index: i, gpuLayerCount: gpuLayerCount) { + layer(h, mask: mask, cache: cache?[i]) + } } return norm(h) diff --git a/Libraries/MLXLLM/Models/Internlm2.swift b/Libraries/MLXLLM/Models/Internlm2.swift index a2529384eb..4fd61bc1ff 100644 --- a/Libraries/MLXLLM/Models/Internlm2.swift +++ b/Libraries/MLXLLM/Models/Internlm2.swift @@ -180,7 +180,12 @@ class Internlm2TransformerBlock: Module { } } -public class InternLM2ModelInner: Module { +public class InternLM2ModelInner: Module, LayerPartitionable { + + + // LayerPartitionable + public var gpuLayerCount: Int? + public var totalLayerCount: Int { layers.count } @ModuleInfo(key: "tok_embeddings") var tokEmbeddings: Embedding let layers: [Internlm2TransformerBlock] @@ -202,7 +207,9 @@ public class InternLM2ModelInner: Module { let mask = createAttentionMask(h: h, cache: cache?.first) for (i, layer) in layers.enumerated() { - h = layer(h, mask: mask, cache: cache?[i]) + h = partitionedLayerCall(index: i, gpuLayerCount: gpuLayerCount) { + layer(h, mask: mask, cache: cache?[i]) + } } return norm(h) diff --git a/Libraries/MLXLLM/Models/Jamba.swift b/Libraries/MLXLLM/Models/Jamba.swift index a9054684ef..df074b3751 100644 --- a/Libraries/MLXLLM/Models/Jamba.swift +++ b/Libraries/MLXLLM/Models/Jamba.swift @@ -420,7 +420,7 @@ class JambaDecoderLayer: Module { } } -public class JambaModelInner: Module { +public class JambaModelInner: Module, LayerPartitionable, StreamableMoE { @ModuleInfo(key: "embed_tokens") var embedTokens: Embedding fileprivate let layers: [JambaDecoderLayer] @@ -429,6 +429,10 @@ public class JambaModelInner: Module { let attnIdx: Int let ssmIdx: Int + + public var gpuLayerCount: Int? = nil + public var streamExperts: Bool = false + public var totalLayerCount: Int { layers.count } public init(_ config: JambaConfiguration) { precondition(config.vocabSize > 0) @@ -457,9 +461,13 @@ public class JambaModelInner: Module { for (i, layer) in layers.enumerated() { if layer.isAttn { - h = layer(h, mask: attnMask, cache: cacheArray[i]) + h = partitionedLayerCall(index: i, gpuLayerCount: gpuLayerCount, stream: streamExperts) { + layer(h, mask: attnMask, cache: cacheArray[i]) + } } else { - h = layer(h, mask: .none, cache: cacheArray[i]) + h = partitionedLayerCall(index: i, gpuLayerCount: gpuLayerCount, stream: streamExperts) { + layer(h, mask: .none, cache: cacheArray[i]) + } } } diff --git a/Libraries/MLXLLM/Models/LFM2MoE.swift b/Libraries/MLXLLM/Models/LFM2MoE.swift index fcefb2e017..aa20e326e9 100644 --- a/Libraries/MLXLLM/Models/LFM2MoE.swift +++ b/Libraries/MLXLLM/Models/LFM2MoE.swift @@ -358,7 +358,7 @@ class LFM2MoEDecoderLayer: Module { } } -public class LFM2MoEModelInner: Module { +public class LFM2MoEModelInner: Module, LayerPartitionable, StreamableMoE { let args: LFM2MoEConfiguration let layers: [LFM2MoEDecoderLayer] let firstAttentionIndex: Int? @@ -366,6 +366,10 @@ public class LFM2MoEModelInner: Module { @ModuleInfo(key: "embed_tokens") var embedTokens: Embedding @ModuleInfo(key: "embedding_norm") var embeddingNorm: RMSNorm + + public var gpuLayerCount: Int? = nil + public var streamExperts: Bool = false + public var totalLayerCount: Int { layers.count } init(_ args: LFM2MoEConfiguration) { self.args = args @@ -407,7 +411,9 @@ public class LFM2MoEModelInner: Module { }() for (i, layer) in layers.enumerated() { - hidden = layer(hidden, attentionMask: attentionMask, ssmMask: ssmMask, cache: cache?[i]) + hidden = partitionedLayerCall(index: i, gpuLayerCount: gpuLayerCount, stream: streamExperts) { + layer(hidden, attentionMask: attentionMask, ssmMask: ssmMask, cache: cache?[i]) + } } return embeddingNorm(hidden) diff --git a/Libraries/MLXLLM/Models/Lille130m.swift b/Libraries/MLXLLM/Models/Lille130m.swift index 4fc3ff5354..16b09d6ec6 100644 --- a/Libraries/MLXLLM/Models/Lille130m.swift +++ b/Libraries/MLXLLM/Models/Lille130m.swift @@ -132,7 +132,12 @@ final class Lille130mBlock: Module { // MARK: - Model (inner) -public final class Lille130mModelInner: Module { +public final class Lille130mModelInner: Module, LayerPartitionable { + + + // LayerPartitionable + public var gpuLayerCount: Int? + public var totalLayerCount: Int { layers.count } @ModuleInfo(key: "tok_embeddings") var embedTokens: Embedding let layers: [Lille130mBlock] @@ -150,7 +155,9 @@ public final class Lille130mModelInner: Module { var h = embedTokens(inputs) let mask = createAttentionMask(h: h, cache: cache?.first) for (i, layer) in layers.enumerated() { - h = layer(h, mask: mask, cache: cache?[i]) + h = partitionedLayerCall(index: i, gpuLayerCount: gpuLayerCount) { + layer(h, mask: mask, cache: cache?[i]) + } } return norm(h) } diff --git a/Libraries/MLXLLM/Models/Llama.swift b/Libraries/MLXLLM/Models/Llama.swift index e4479b6bc7..1f71b66d02 100644 --- a/Libraries/MLXLLM/Models/Llama.swift +++ b/Libraries/MLXLLM/Models/Llama.swift @@ -118,13 +118,17 @@ class LlamaTransformerBlock: Module { } } -public class LlamaModelInner: Module { +public class LlamaModelInner: Module, LayerPartitionable { @ModuleInfo(key: "embed_tokens") var embedTokens: Embedding let layers: [LlamaTransformerBlock] let norm: RMSNorm + // LayerPartitionable + public var gpuLayerCount: Int? + public var totalLayerCount: Int { layers.count } + init(_ args: LlamaConfiguration) { precondition(args.vocabularySize > 0) @@ -141,7 +145,9 @@ public class LlamaModelInner: Module { let mask = createAttentionMask(h: h, cache: cache?.first) for (i, layer) in layers.enumerated() { - h = layer(h, mask: mask, cache: cache?[i]) + h = partitionedLayerCall(index: i, gpuLayerCount: gpuLayerCount) { + layer(h, mask: mask, cache: cache?[i]) + } } return norm(h) diff --git a/Libraries/MLXLLM/Models/MiMoV2Flash.swift b/Libraries/MLXLLM/Models/MiMoV2Flash.swift index f9545e8e1b..4abd23af74 100644 --- a/Libraries/MLXLLM/Models/MiMoV2Flash.swift +++ b/Libraries/MLXLLM/Models/MiMoV2Flash.swift @@ -335,7 +335,7 @@ class MiMoV2FlashDecoderLayer: Module { } } -public class MiMoV2FlashModelInner: Module { +public class MiMoV2FlashModelInner: Module, LayerPartitionable, StreamableMoE { @ModuleInfo(key: "embed_tokens") var embedTokens: Embedding let layers: [MiMoV2FlashDecoderLayer] @ModuleInfo(key: "norm") var norm: RMSNorm @@ -344,6 +344,10 @@ public class MiMoV2FlashModelInner: Module { let gaIdx: Int let slidingWindowSize: Int let hybridLayerPattern: [Int] + + public var gpuLayerCount: Int? = nil + public var streamExperts: Bool = false + public var totalLayerCount: Int { layers.count } init(_ config: MiMoV2FlashConfiguration) { _embedTokens.wrappedValue = Embedding( @@ -373,7 +377,9 @@ public class MiMoV2FlashModelInner: Module { for (i, layer) in layers.enumerated() { let mask = hybridLayerPattern[i] == 1 ? swaMask : fullMask - h = layer(h, mask: mask, cache: cache?[i]) + h = partitionedLayerCall(index: i, gpuLayerCount: gpuLayerCount, stream: streamExperts) { + layer(h, mask: mask, cache: cache?[i]) + } } return norm(h) diff --git a/Libraries/MLXLLM/Models/MiniCPM.swift b/Libraries/MLXLLM/Models/MiniCPM.swift index 852663b8da..1a84397968 100644 --- a/Libraries/MLXLLM/Models/MiniCPM.swift +++ b/Libraries/MLXLLM/Models/MiniCPM.swift @@ -120,7 +120,12 @@ final class MiniCPMDecoderLayer: Module { } } -public final class MiniCPMModelInner: Module { +public final class MiniCPMModelInner: Module, LayerPartitionable { + + + // LayerPartitionable + public var gpuLayerCount: Int? + public var totalLayerCount: Int { layers.count } @ModuleInfo(key: "embed_tokens") var embedTokens: Embedding let layers: [MiniCPMDecoderLayer] @@ -146,7 +151,9 @@ public final class MiniCPMModelInner: Module { let mask = createAttentionMask(h: h, cache: cache?.first) for (i, layer) in layers.enumerated() { - h = layer(h, mask: mask, cache: cache?[i]) + h = partitionedLayerCall(index: i, gpuLayerCount: gpuLayerCount) { + layer(h, mask: mask, cache: cache?[i]) + } } return norm(h) diff --git a/Libraries/MLXLLM/Models/MiniMax.swift b/Libraries/MLXLLM/Models/MiniMax.swift index 47bae6a599..86dd899731 100644 --- a/Libraries/MLXLLM/Models/MiniMax.swift +++ b/Libraries/MLXLLM/Models/MiniMax.swift @@ -158,7 +158,12 @@ class MiniMaxDecoderLayer: Module { } } -public class MiniMaxModelInner: Module { +public class MiniMaxModelInner: Module, LayerPartitionable { + + + // LayerPartitionable + public var gpuLayerCount: Int? + public var totalLayerCount: Int { layers.count } let args: MiniMaxConfiguration @ModuleInfo(key: "embed_tokens") var embedTokens: Embedding @@ -180,7 +185,9 @@ public class MiniMaxModelInner: Module { let mask = createAttentionMask(h: h, cache: cache?.first) for (i, layer) in layers.enumerated() { - h = layer(h, mask: mask, cache: cache?[i]) + h = partitionedLayerCall(index: i, gpuLayerCount: gpuLayerCount) { + layer(h, mask: mask, cache: cache?[i]) + } } return norm(h) diff --git a/Libraries/MLXLLM/Models/Mistral4.swift b/Libraries/MLXLLM/Models/Mistral4.swift new file mode 100644 index 0000000000..cbbd034dde --- /dev/null +++ b/Libraries/MLXLLM/Models/Mistral4.swift @@ -0,0 +1,478 @@ +// Mistral-Small-4 (119B) — MLA attention + MoE MLP +// Outer config: model_type="mistral3" (VLM wrapper) +// Inner text_config: model_type="mistral4" +// +// Architecture: +// Attention : Multi-head Latent Attention (MLA), same structural pattern as DeepSeek V3 +// MLP : 128 routed experts (SwitchGLU, pre-stacked) + 1 shared expert +// Gate : 8-bit quantized Linear; dequantized in sanitize() to plain float +// RoPE : Standard interleaved (rope_interleave=true → traditional:false) + +import Foundation +import MLX +import MLXLMCommon +import MLXNN + +// MARK: - Configuration + +/// Decoded from the outer VLM config.json; actual model params live under text_config. +public struct Mistral4Configuration: Codable, Sendable { + var hiddenSize: Int + var moeIntermediateSize: Int + var intermediateSize: Int + var numHiddenLayers: Int + var numAttentionHeads: Int + var numKeyValueHeads: Int + var nRoutedExperts: Int + var nSharedExperts: Int + var numExpertsPerTok: Int + var firstKDenseReplace: Int + var routedScalingFactor: Float + var normTopkProb: Bool + var kvLoraRank: Int + var qLoraRank: Int + var qkRopeHeadDim: Int + var qkNopeHeadDim: Int + var vHeadDim: Int + var rmsNormEps: Float + var ropeTheta: Float + var ropeParameters: [String: StringOrNumber]? + var vocabSize: Int + var tieWordEmbeddings: Bool + var maxPositionEmbeddings: Int + + var qHeadDim: Int { qkNopeHeadDim + qkRopeHeadDim } + + enum CodingKeys: String, CodingKey { + case hiddenSize = "hidden_size" + case moeIntermediateSize = "moe_intermediate_size" + case intermediateSize = "intermediate_size" + case numHiddenLayers = "num_hidden_layers" + case numAttentionHeads = "num_attention_heads" + case numKeyValueHeads = "num_key_value_heads" + case nRoutedExperts = "n_routed_experts" + case nSharedExperts = "n_shared_experts" + case numExpertsPerTok = "num_experts_per_tok" + case firstKDenseReplace = "first_k_dense_replace" + case routedScalingFactor = "routed_scaling_factor" + case normTopkProb = "norm_topk_prob" + case kvLoraRank = "kv_lora_rank" + case qLoraRank = "q_lora_rank" + case qkRopeHeadDim = "qk_rope_head_dim" + case qkNopeHeadDim = "qk_nope_head_dim" + case vHeadDim = "v_head_dim" + case rmsNormEps = "rms_norm_eps" + case ropeTheta = "rope_theta" + case ropeParameters = "rope_parameters" + case vocabSize = "vocab_size" + case tieWordEmbeddings = "tie_word_embeddings" + case maxPositionEmbeddings = "max_position_embeddings" + } + + // Decodes from either text_config-wrapped (VLM) or flat top-level layout. + enum OuterKeys: String, CodingKey { case textConfig = "text_config" } + enum TLKeys: String, CodingKey { case tieWordEmbeddings = "tie_word_embeddings" } + + public init(from decoder: Decoder) throws { + let outerContainer = try decoder.container(keyedBy: OuterKeys.self) + let tlContainer = try decoder.container(keyedBy: TLKeys.self) + let c: KeyedDecodingContainer + if outerContainer.contains(.textConfig) { + c = try outerContainer.nestedContainer(keyedBy: CodingKeys.self, forKey: .textConfig) + } else { + c = try decoder.container(keyedBy: CodingKeys.self) + } + + hiddenSize = try c.decode(Int.self, forKey: .hiddenSize) + moeIntermediateSize = try c.decode(Int.self, forKey: .moeIntermediateSize) + intermediateSize = try c.decodeIfPresent(Int.self, forKey: .intermediateSize) ?? moeIntermediateSize + numHiddenLayers = try c.decode(Int.self, forKey: .numHiddenLayers) + numAttentionHeads = try c.decode(Int.self, forKey: .numAttentionHeads) + numKeyValueHeads = try c.decodeIfPresent(Int.self, forKey: .numKeyValueHeads) ?? numAttentionHeads + nRoutedExperts = try c.decode(Int.self, forKey: .nRoutedExperts) + nSharedExperts = try c.decodeIfPresent(Int.self, forKey: .nSharedExperts) ?? 1 + numExpertsPerTok = try c.decode(Int.self, forKey: .numExpertsPerTok) + firstKDenseReplace = try c.decodeIfPresent(Int.self, forKey: .firstKDenseReplace) ?? 0 + routedScalingFactor = try c.decodeIfPresent(Float.self, forKey: .routedScalingFactor) ?? 1.0 + normTopkProb = try c.decodeIfPresent(Bool.self, forKey: .normTopkProb) ?? true + kvLoraRank = try c.decode(Int.self, forKey: .kvLoraRank) + qLoraRank = try c.decode(Int.self, forKey: .qLoraRank) + qkRopeHeadDim = try c.decode(Int.self, forKey: .qkRopeHeadDim) + qkNopeHeadDim = try c.decode(Int.self, forKey: .qkNopeHeadDim) + vHeadDim = try c.decode(Int.self, forKey: .vHeadDim) + rmsNormEps = try c.decode(Float.self, forKey: .rmsNormEps) + ropeTheta = try c.decodeIfPresent(Float.self, forKey: .ropeTheta) ?? 10_000.0 + ropeParameters = try c.decodeIfPresent([String: StringOrNumber].self, forKey: .ropeParameters) + vocabSize = try c.decode(Int.self, forKey: .vocabSize) + maxPositionEmbeddings = try c.decodeIfPresent(Int.self, forKey: .maxPositionEmbeddings) ?? 131_072 + tieWordEmbeddings = + (try? c.decodeIfPresent(Bool.self, forKey: .tieWordEmbeddings)) + ?? (try? tlContainer.decodeIfPresent(Bool.self, forKey: .tieWordEmbeddings)) + ?? false + } +} + +// MARK: - MLA Attention + +class Mistral4Attention: Module { + let numHeads: Int + let qkRopeHeadDim: Int + let kvLoraRank: Int + let vHeadDim: Int + let qkNopeHeadDim: Int + let qHeadDim: Int + let scale: Float + + let rope: RoPELayer + + @ModuleInfo(key: "q_a_proj") var qAProj: Linear + @ModuleInfo(key: "q_a_layernorm") var qALayerNorm: RMSNorm + @ModuleInfo(key: "q_b_proj") var qBProj: Linear + @ModuleInfo(key: "o_proj") var oProj: Linear + @ModuleInfo(key: "kv_a_proj_with_mqa") var kvAProjWithMqa: Linear + @ModuleInfo(key: "kv_a_layernorm") var kvALayerNorm: RMSNorm + @ModuleInfo(key: "kv_b_proj") var kvBProj: Linear + + init(_ config: Mistral4Configuration) { + let hiddenSize = config.hiddenSize + numHeads = config.numAttentionHeads + qkRopeHeadDim = config.qkRopeHeadDim + kvLoraRank = config.kvLoraRank + vHeadDim = config.vHeadDim + qkNopeHeadDim = config.qkNopeHeadDim + qHeadDim = config.qHeadDim + scale = pow(Float(qHeadDim), -0.5) + + _qAProj.wrappedValue = Linear(hiddenSize, config.qLoraRank, bias: false) + _qALayerNorm.wrappedValue = RMSNorm(dimensions: config.qLoraRank) + _qBProj.wrappedValue = Linear(config.qLoraRank, numHeads * qHeadDim, bias: false) + _kvAProjWithMqa.wrappedValue = Linear( + hiddenSize, kvLoraRank + qkRopeHeadDim, bias: false) + _kvALayerNorm.wrappedValue = RMSNorm(dimensions: kvLoraRank) + _kvBProj.wrappedValue = Linear( + kvLoraRank, numHeads * (qkNopeHeadDim + vHeadDim), bias: false) + _oProj.wrappedValue = Linear(numHeads * vHeadDim, hiddenSize, bias: false) + + // rope_interleave: true → traditional: false (standard interleaved, not YARN) + rope = initializeRope( + dims: qkRopeHeadDim, + base: config.ropeTheta, + traditional: false, + scalingConfig: config.ropeParameters, + maxPositionEmbeddings: config.maxPositionEmbeddings) + + super.init() + } + + func callAsFunction( + _ x: MLXArray, mask: MLXFast.ScaledDotProductAttentionMaskMode, cache: KVCache? + ) -> MLXArray { + let (B, L, _) = (x.dim(0), x.dim(1), x.dim(2)) + + // Low-rank Q decomposition + var q = qBProj(qALayerNorm(qAProj(x))) + q = q.reshaped(B, L, numHeads, qHeadDim).transposed(0, 2, 1, 3) + let splitQ = split(q, indices: [qkNopeHeadDim], axis: -1) + let (qNope, qPe) = (splitQ[0], splitQ[1]) + + // Latent KV compression (MLA) + let raw = kvAProjWithMqa(x) + let splitRaw = split(raw, indices: [kvLoraRank], axis: -1) + let compressedKv = splitRaw[0] + var kPe = splitRaw[1] + kPe = kPe.reshaped(B, L, 1, qkRopeHeadDim).transposed(0, 2, 1, 3) + + var kv = kvBProj(kvALayerNorm(compressedKv)) + kv = kv.reshaped(B, L, numHeads, -1).transposed(0, 2, 1, 3) + let splitKv = split(kv, indices: [qkNopeHeadDim], axis: -1) + let (kNope, values) = (splitKv[0], splitKv[1]) + + let offset = cache?.offset ?? 0 + let rotQPe = rope(qPe, offset: offset) + let rotKPe = rope(kPe, offset: offset) + let kPeExpanded = repeated(rotKPe, count: numHeads, axis: 1) + + let keys = concatenated([kNope, kPeExpanded], axis: -1) + let queries = concatenated([qNope, rotQPe], axis: -1) + + let output = attentionWithCacheUpdate( + queries: queries, keys: keys, values: values, + cache: cache, scale: scale, mask: mask + ) + .transposed(0, 2, 1, 3) + .reshaped(B, L, -1) + + return oProj(output) + } +} + +// MARK: - MoE MLP + +class Mistral4MLP: Module, UnaryLayer { + @ModuleInfo(key: "gate_proj") var gateProj: Linear + @ModuleInfo(key: "up_proj") var upProj: Linear + @ModuleInfo(key: "down_proj") var downProj: Linear + + init(hiddenDim: Int, intermediateDim: Int) { + _gateProj.wrappedValue = Linear(hiddenDim, intermediateDim, bias: false) + _upProj.wrappedValue = Linear(hiddenDim, intermediateDim, bias: false) + _downProj.wrappedValue = Linear(intermediateDim, hiddenDim, bias: false) + super.init() + } + + func callAsFunction(_ x: MLXArray) -> MLXArray { + downProj(silu(gateProj(x)) * upProj(x)) + } +} + +/// Expert router — kept as a raw Module (not Linear) so the 8-bit packed gate weight +/// bypasses the global 4-bit quantization system. The weight is dequantized to float +/// in Mistral4Model.sanitize() before being loaded into this module. +class Mistral4Gate: Module { + var weight: MLXArray // [nExperts, hiddenSize] — dequantized BF16 + + init(_ config: Mistral4Configuration) { + weight = zeros([config.nRoutedExperts, config.hiddenSize]) + super.init() + } + + func callAsFunction(_ x: MLXArray) -> MLXArray { + x.matmul(weight.T) // → [B, L, nExperts] + } +} + +class Mistral4MoE: Module, UnaryLayer { + // Gate weight stored as raw float (dequantized in sanitize); key path: mlp.gate.weight + var gate: Mistral4Gate + // Pre-stacked expert weights already in switch_mlp.{gate,up,down}_proj format + @ModuleInfo(key: "switch_mlp") var switchMLP: SwitchGLU + // Single shared expert: n_shared_experts × moeIntermediateSize + @ModuleInfo(key: "shared_experts") var sharedExperts: Mistral4MLP + + let topK: Int + let normTopkProb: Bool + let routedScalingFactor: Float + + init(_ config: Mistral4Configuration) { + topK = config.numExpertsPerTok + normTopkProb = config.normTopkProb + routedScalingFactor = config.routedScalingFactor + + gate = Mistral4Gate(config) + _switchMLP.wrappedValue = SwitchGLU( + inputDims: config.hiddenSize, + hiddenDims: config.moeIntermediateSize, + numExperts: config.nRoutedExperts, + activation: silu + ) + _sharedExperts.wrappedValue = Mistral4MLP( + hiddenDim: config.hiddenSize, + intermediateDim: config.moeIntermediateSize * config.nSharedExperts + ) + super.init() + } + + func callAsFunction(_ x: MLXArray) -> MLXArray { + // Softmax gate: n_group=1 / topk_group=1 → no group masking needed + let logits = gate(x) // [B, L, nExperts] + let scores = softmax(logits.asType(.float32), axis: -1) + + let inds = argPartition(-scores, kth: topK - 1, axis: -1)[.ellipsis, .. MLXArray { + // Note: partitionedLayerCall() in Mistral4ModelInner already performs + // eval + Stream.gpu.synchronize() after this function returns when + // ExpertStreamingConfig.shared.isEnabled == true (see LayerPartitioning.swift:130-139). + // QuantizedSwitchLinear.callAsFunction() performs its own eval+sync around + // each expert kernel (SwitchLayers.swift:270-271). + // No additional prefault or GPU syncs are needed here. + let r = selfAttn(inputLayerNorm(x), mask: mask, cache: cache) + let h = x + r + return h + mlp(postAttentionLayerNorm(h)) + } +} + +// MARK: - Inner Model + +public class Mistral4ModelInner: Module, LayerPartitionable, StreamableMoE { + let config: Mistral4Configuration + + @ModuleInfo(key: "embed_tokens") var embedTokens: Embedding + let layers: [Mistral4DecoderLayer] + @ModuleInfo(key: "norm") var norm: RMSNorm + + // LayerPartitionable (SSD streaming support) + public var startIdx: Int + public var endIdx: Int + public var numLayers: Int + public var pipelineRank: Int = 0 + public var pipelineSize: Int = 1 + + // StreamableMoE + public var gpuLayerCount: Int? = nil + public var streamExperts: Bool = false + public var totalLayerCount: Int { layers.count } + + init(_ config: Mistral4Configuration) { + self.config = config + _embedTokens.wrappedValue = Embedding( + embeddingCount: config.vocabSize, dimensions: config.hiddenSize) + layers = (0.. MLXArray { + var h = embedTokens(x) + let mask = createAttentionMask(h: h, cache: cache?.first) + for (i, layer) in layers.enumerated() { + h = partitionedLayerCall( + index: i, gpuLayerCount: gpuLayerCount, stream: streamExperts + ) { + layer(h, mask: mask, cache: cache?[i]) + } + } + return norm(h) + } +} + +// MARK: - Top-Level Model + +public class Mistral4Model: Module, LLMModel, KVCacheDimensionProvider, LoRAModel { + /// One entry per layer: each layer uses full MHA (numAttentionHeads heads). + /// Keys store qHeadDim per head; values store vHeadDim per head. + /// Must match numHiddenLayers or the server will create a wrong-sized cache array, + /// causing index-out-of-bounds on cache?[i] for any layer i. + public var kvHeads: [Int] + + let args: Mistral4Configuration + public let model: Mistral4ModelInner + @ModuleInfo(key: "lm_head") var lmHead: Linear? + + public init(_ args: Mistral4Configuration) { + self.args = args + kvHeads = Array(repeating: args.numAttentionHeads, count: args.numHiddenLayers) + model = Mistral4ModelInner(args) + if !args.tieWordEmbeddings { + _lmHead.wrappedValue = Linear(args.hiddenSize, args.vocabSize, bias: false) + } + super.init() + } + + public func callAsFunction(_ inputs: MLXArray, cache: [KVCache]?) -> MLXArray { + let out = model(inputs, cache: cache) + if let lmHead { return lmHead(out) } + return model.embedTokens.asLinear(out) + } + + // MARK: Weight Sanitization + // + // 1. Strip "language_model." VLM wrapper prefix + // 2. Drop vision_tower.*, multi_modal_projector.*, rotary_emb.inv_freq + // 3. Handle tied embeddings + // 4. fp8 weight_scale_inv dequantization (if present in FP8 conversions) + // 5. Dequantize gate router weights from 8-bit to float + // gate.weight [nExperts, hidden/4] U32 → [nExperts, hidden] BF16 + // gate.scales [nExperts, hidden/groupSize] + // gate.biases [nExperts, hidden/groupSize] + // Stored in Mistral4Gate.weight (plain MLXArray) — bypasses 4-bit quantization. + // + // NOTE: switch_mlp weights are pre-stacked → no expert aggregation needed. + // NOTE: kv_b_proj is used directly in Mistral4Attention; no reshape needed. + + public func sanitize(weights: [String: MLXArray]) -> [String: MLXArray] { + let langPrefix = "language_model." + var out: [String: MLXArray] = [:] + + // Step 1+2: strip prefix, skip vision keys + for (key, value) in weights { + guard key.hasPrefix(langPrefix) else { continue } + let stripped = String(key.dropFirst(langPrefix.count)) + guard !stripped.contains("rotary_emb.inv_freq") else { continue } + guard !stripped.hasPrefix("vision_tower") else { continue } + guard !stripped.hasPrefix("multi_modal_projector") else { continue } + out[stripped] = value + } + + // Step 3: tied embeddings + if args.tieWordEmbeddings { + out.removeValue(forKey: "lm_head.weight") + } + + // Step 4: fp8 weight_scale_inv dequantization + var processed: [String: MLXArray] = [:] + for (key, value) in out { + if key.contains("weight_scale_inv") { + let wk = key.replacingOccurrences(of: "_scale_inv", with: "") + if let w = out[wk], processed[wk] == nil { + processed[wk] = w * value + } + } else if processed[key] == nil { + processed[key] = value + } + } + if !processed.isEmpty { out = processed } + + // Step 5: dequantize 8-bit gate weights to float + // gate.weight shape [nExperts, packed], dtype U32 — 4 int8 values per uint32 + // gate.scales shape [nExperts, nGroups], dtype BF16 + // group_size = realNIn / nGroups = (packed * 4) / nGroups + for l in 0.. 0) @@ -169,15 +173,18 @@ public class OlmoEModelInner: Module { self.norm = RMSNorm(dimensions: args.hiddenSize, eps: args.rmsNormEps) } - func callAsFunction(_ inputs: MLXArray, cache: [KVCache]? = nil) -> MLXArray { + func callAsFunction( + _ inputs: MLXArray, + cache: [KVCache]? = nil + ) -> MLXArray { var h = embedTokens(inputs) - let mask = createAttentionMask(h: h, cache: cache?.first) for (i, layer) in layers.enumerated() { - h = layer(h, mask: mask, cache: cache?[i]) + h = partitionedLayerCall(index: i, gpuLayerCount: gpuLayerCount, stream: streamExperts) { + layer(h, mask: mask, cache: cache?[i]) + } } - return norm(h) } } diff --git a/Libraries/MLXLLM/Models/OpenELM.swift b/Libraries/MLXLLM/Models/OpenELM.swift index 1fa1c355be..98cfcaddde 100644 --- a/Libraries/MLXLLM/Models/OpenELM.swift +++ b/Libraries/MLXLLM/Models/OpenELM.swift @@ -145,7 +145,12 @@ class OpenELMTransformerDecoderLayer: Module { } } -public class OpenELMModelInner: Module { +public class OpenELMModelInner: Module, LayerPartitionable { + + + // LayerPartitionable + public var gpuLayerCount: Int? + public var totalLayerCount: Int { layers.count } @ModuleInfo(key: "token_embeddings") var embedTokens: Embedding fileprivate let layers: [OpenELMTransformerDecoderLayer] @@ -170,7 +175,9 @@ public class OpenELMModelInner: Module { let mask = createAttentionMask(h: h, cache: cache?.first) for (i, layer) in layers.enumerated() { - h = layer(h, mask: mask, cache: cache?[i]) + h = partitionedLayerCall(index: i, gpuLayerCount: gpuLayerCount) { + layer(h, mask: mask, cache: cache?[i]) + } } return norm(h) diff --git a/Libraries/MLXLLM/Models/Phi.swift b/Libraries/MLXLLM/Models/Phi.swift index b695dab392..fc362a72b0 100644 --- a/Libraries/MLXLLM/Models/Phi.swift +++ b/Libraries/MLXLLM/Models/Phi.swift @@ -118,7 +118,12 @@ class PhiDecoderLayer: Module { } } -public class PhiModelInner: Module { +public class PhiModelInner: Module, LayerPartitionable { + + + // LayerPartitionable + public var gpuLayerCount: Int? + public var totalLayerCount: Int { layers.count } @ModuleInfo(key: "embed_tokens") var embedTokens: Embedding @@ -143,7 +148,9 @@ public class PhiModelInner: Module { var x = embedTokens(x) for (i, layer) in layers.enumerated() { - x = layer(x, mask: mask, cache: cache?[i]) + x = partitionedLayerCall(index: i, gpuLayerCount: gpuLayerCount) { + layer(x, mask: mask, cache: cache?[i]) + } } return finalLayerNorm(x) diff --git a/Libraries/MLXLLM/Models/Phi3.swift b/Libraries/MLXLLM/Models/Phi3.swift index be8569ab2b..de9105bc69 100644 --- a/Libraries/MLXLLM/Models/Phi3.swift +++ b/Libraries/MLXLLM/Models/Phi3.swift @@ -144,7 +144,12 @@ class Phi3TransformerBlock: Module { } } -public class Phi3ModelInner: Module { +public class Phi3ModelInner: Module, LayerPartitionable { + + + // LayerPartitionable + public var gpuLayerCount: Int? + public var totalLayerCount: Int { layers.count } @ModuleInfo(key: "embed_tokens") var embedTokens: Embedding @@ -172,7 +177,9 @@ public class Phi3ModelInner: Module { let mask = createAttentionMask(h: h, cache: cache?.first) for (i, layer) in layers.enumerated() { - h = layer(h, mask: mask, cache: cache?[i]) + h = partitionedLayerCall(index: i, gpuLayerCount: gpuLayerCount) { + layer(h, mask: mask, cache: cache?[i]) + } } return norm(h) diff --git a/Libraries/MLXLLM/Models/Qwen2.swift b/Libraries/MLXLLM/Models/Qwen2.swift index b14636f855..3d6341a080 100644 --- a/Libraries/MLXLLM/Models/Qwen2.swift +++ b/Libraries/MLXLLM/Models/Qwen2.swift @@ -131,12 +131,16 @@ class Qwen2TransformerBlock: Module { } } -public class Qwen2ModelInner: Module { +public class Qwen2ModelInner: Module, LayerPartitionable { @ModuleInfo(key: "embed_tokens") var embedTokens: Embedding fileprivate let layers: [Qwen2TransformerBlock] let norm: RMSNorm + // LayerPartitionable + public var gpuLayerCount: Int? + public var totalLayerCount: Int { layers.count } + public init(_ args: Qwen2Configuration) { precondition(args.vocabularySize > 0) @@ -156,7 +160,9 @@ public class Qwen2ModelInner: Module { let mask = createAttentionMask(h: h, cache: cache?.first) for (i, layer) in layers.enumerated() { - h = layer(h, mask: mask, cache: cache?[i]) + h = partitionedLayerCall(index: i, gpuLayerCount: gpuLayerCount) { + layer(h, mask: mask, cache: cache?[i]) + } } return norm(h) diff --git a/Libraries/MLXLLM/Models/Qwen3.swift b/Libraries/MLXLLM/Models/Qwen3.swift index 73d9f9fd69..6777cb844f 100644 --- a/Libraries/MLXLLM/Models/Qwen3.swift +++ b/Libraries/MLXLLM/Models/Qwen3.swift @@ -139,7 +139,12 @@ class Qwen3TransformerBlock: Module { } } -public class Qwen3ModelInner: Module { +public class Qwen3ModelInner: Module, LayerPartitionable { + + + // LayerPartitionable + public var gpuLayerCount: Int? + public var totalLayerCount: Int { layers.count } @ModuleInfo(key: "embed_tokens") var embedTokens: Embedding fileprivate let layers: [Qwen3TransformerBlock] @@ -164,7 +169,9 @@ public class Qwen3ModelInner: Module { let mask = createAttentionMask(h: h, cache: cache?.first) for (i, layer) in layers.enumerated() { - h = layer(h, mask: mask, cache: cache?[i]) + h = partitionedLayerCall(index: i, gpuLayerCount: gpuLayerCount) { + layer(h, mask: mask, cache: cache?[i]) + } } return norm(h) diff --git a/Libraries/MLXLLM/Models/Qwen35.swift b/Libraries/MLXLLM/Models/Qwen35.swift index 15fcd6556c..846fc34921 100644 --- a/Libraries/MLXLLM/Models/Qwen35.swift +++ b/Libraries/MLXLLM/Models/Qwen35.swift @@ -294,6 +294,24 @@ final class Qwen35GatedDeltaNet: Module { } } +final class MathRMSNorm: Module, UnaryLayer { + @ParameterInfo(key: "weight") var weight: MLXArray + let eps: Float + init(dimensions: Int, eps: Float = 1e-6) { + self.eps = eps + _weight.wrappedValue = MLXArray.ones([dimensions]) + super.init() + } + func callAsFunction(_ hiddenStates: MLXArray) -> MLXArray { + let isCPU = Device.defaultDevice().deviceType == .cpu + if isCPU { + let variance = mean(square(hiddenStates), axis: -1, keepDims: true) + return (hiddenStates * rsqrt(variance + eps)) * weight + } + return MLXFast.rmsNorm(hiddenStates, weight: weight, eps: eps) + } +} + // MARK: - Attention final class Qwen35Attention: Module { @@ -306,8 +324,8 @@ final class Qwen35Attention: Module { @ModuleInfo(key: "v_proj") var vProj: Linear @ModuleInfo(key: "o_proj") var oProj: Linear - @ModuleInfo(key: "q_norm") var qNorm: RMSNorm - @ModuleInfo(key: "k_norm") var kNorm: RMSNorm + @ModuleInfo(key: "q_norm") var qNorm: MathRMSNorm + @ModuleInfo(key: "k_norm") var kNorm: MathRMSNorm let rope: RoPELayer @@ -326,8 +344,8 @@ final class Qwen35Attention: Module { _oProj.wrappedValue = Linear( args.attentionHeads * headDim, args.hiddenSize, bias: args.attentionBias) - _qNorm.wrappedValue = RMSNorm(dimensions: headDim, eps: args.rmsNormEps) - _kNorm.wrappedValue = RMSNorm(dimensions: headDim, eps: args.rmsNormEps) + _qNorm.wrappedValue = MathRMSNorm(dimensions: headDim, eps: args.rmsNormEps) + _kNorm.wrappedValue = MathRMSNorm(dimensions: headDim, eps: args.rmsNormEps) let ropeDims = Int(Float(headDim) * args.partialRotaryFactor) self.rope = initializeRope( @@ -393,7 +411,15 @@ final class Qwen35SparseMoeBlock: Module, UnaryLayer { init(_ args: Qwen35TextConfiguration) { self.normTopkProb = args.normTopkProb self.numExperts = args.numExperts - self.topK = args.numExpertsPerTok + self.topK = { + if let override = ProcessInfo.processInfo.environment["SWIFTLM_TOP_K"], + let k = Int(override), k > 0 { + let effective = min(k, args.numExpertsPerTok) + print("[SwiftLM] Top-K override: \(args.numExpertsPerTok) -> \(effective)") + return effective + } + return args.numExpertsPerTok + }() _gate.wrappedValue = Linear(args.hiddenSize, args.numExperts, bias: false) _switchMLP.wrappedValue = SwitchGLU( @@ -439,8 +465,8 @@ final class Qwen35DecoderLayer: Module { @ModuleInfo(key: "self_attn") var selfAttn: Qwen35Attention? @ModuleInfo(key: "linear_attn") var linearAttn: Qwen35GatedDeltaNet? - @ModuleInfo(key: "input_layernorm") var inputLayerNorm: RMSNorm - @ModuleInfo(key: "post_attention_layernorm") var postAttentionLayerNorm: RMSNorm + @ModuleInfo(key: "input_layernorm") var inputLayerNorm: MathRMSNorm + @ModuleInfo(key: "post_attention_layernorm") var postAttentionLayerNorm: MathRMSNorm @ModuleInfo(key: "mlp") var mlp: Module @@ -462,11 +488,11 @@ final class Qwen35DecoderLayer: Module { ) } - _inputLayerNorm.wrappedValue = RMSNorm( + _inputLayerNorm.wrappedValue = MathRMSNorm( dimensions: args.hiddenSize, eps: args.rmsNormEps ) - _postAttentionLayerNorm.wrappedValue = RMSNorm( + _postAttentionLayerNorm.wrappedValue = MathRMSNorm( dimensions: args.hiddenSize, eps: args.rmsNormEps ) @@ -474,12 +500,35 @@ final class Qwen35DecoderLayer: Module { super.init() } + private func prefaultEvaluatable(_ evalObj: Evaluatable?) { + guard let evalObj = evalObj else { return } + for array in evalObj.innerState() { + MLXFast.prefault(array) + } + } + func callAsFunction( _ x: MLXArray, attentionMask: MLXFast.ScaledDotProductAttentionMaskMode, ssmMask: MLXArray?, cache: KVCache? ) -> MLXArray { + + // OS VM SWAP WATCHDOG BYPASS: + // For massive models (e.g. 122B Qwen on 64GB Mac), Apple Unified Memory will swap + // weights and KV Cache to disk. If the GPU page-faults these during execution, it blocks the thread + // generating kIOGPUCommandBufferCallbackErrorTimeout after 5 seconds. + // By evaluating innerState() sequentially on the CPU thread here, we force the SSD load + // safely outside of the Apple Metal limits. KERNEL EXECUTION DROPS FROM 5s+ TO 100ms. + if ProcessInfo.processInfo.environment["EXPERIMENTAL_SSD_STREAM"] != nil { + prefaultEvaluatable(self.inputLayerNorm) + prefaultEvaluatable(self.postAttentionLayerNorm) + prefaultEvaluatable(self.selfAttn) + prefaultEvaluatable(self.linearAttn) + prefaultEvaluatable(cache) + // WE MUST NOT PREFAULT MOE EXPERTS TO AVOID MEMORY CRASH + } + let r: MLXArray if isLinear { r = linearAttn!(inputLayerNorm(x), mask: ssmMask, cache: cache as? MambaCache) @@ -488,21 +537,56 @@ final class Qwen35DecoderLayer: Module { } let h = x + r - return h + (mlp as! UnaryLayer)(postAttentionLayerNorm(h)) + + // ───────────────────────────────────────────────────────────────────── + // FLUSH-LOAD-EXECUTE ARCHITECTURE: Phase 1 (Flush & Split) + // ───────────────────────────────────────────────────────────────────── + // If we are processing a Mixture of Experts layer, we explicitly evaluate + // the attention subgraph (`h`) and synchronize the Metal GPU queue here. + // + // THIS IS VITAL FOR TWO REASONS: + // 1. FRESH COMMAND BUFFER (Streaming): When SSD Expert Streaming evaluates + // the `mlp` custom op, it performs a highly latency-sensitive `load_sync` + // (blocking the CPU). Ensuring the previous GPU work is committed and completed + // means the expert GEMM executes on an isolated, empty Metal Command Buffer. + // ───────────────────────────────────────────────────────────────────── + if let moeBlock = self.mlp as? Qwen35SparseMoeBlock { + if let cacheState = cache { + eval([h] + cacheState.innerState()) + } else { + eval(h) + } + Stream.gpu.synchronize() + } + + let mlpOutput = (self.mlp as! UnaryLayer)(postAttentionLayerNorm(h)) + let finalH = h + mlpOutput + if let moeBlock = self.mlp as? Qwen35SparseMoeBlock { + eval(finalH) + Stream.gpu.synchronize() + } + return finalH } } // MARK: - Text Model -public class Qwen35TextModelInner: Module { +public class Qwen35TextModelInner: Module, LayerPartitionable, StreamableMoE { @ModuleInfo(key: "embed_tokens") var embedTokens: Embedding fileprivate let layers: [Qwen35DecoderLayer] - let norm: RMSNorm + let norm: MathRMSNorm let ssmIdx: Int let faIdx: Int + // LayerPartitionable + public var gpuLayerCount: Int? + public var totalLayerCount: Int { layers.count } + + // StreamableMoE + public var streamExperts: Bool = false + init(_ args: Qwen35TextConfiguration) { precondition(args.vocabularySize > 0) @@ -515,7 +599,7 @@ public class Qwen35TextModelInner: Module { Qwen35DecoderLayer(args, layerIdx: layerIdx) } - self.norm = RMSNorm(dimensions: args.hiddenSize, eps: args.rmsNormEps) + self.norm = MathRMSNorm(dimensions: args.hiddenSize, eps: args.rmsNormEps) self.ssmIdx = 0 self.faIdx = args.fullAttentionInterval - 1 @@ -539,8 +623,10 @@ public class Qwen35TextModelInner: Module { let attnMask = layer.isLinear ? MLXFast.ScaledDotProductAttentionMaskMode.none : faMask - hiddenStates = layer( - hiddenStates, attentionMask: attnMask, ssmMask: mask, cache: cacheArray?[i]) + hiddenStates = partitionedLayerCall(index: i, gpuLayerCount: gpuLayerCount, stream: streamExperts, cacheToEval: cacheArray?[i]) { + layer( + hiddenStates, attentionMask: attnMask, ssmMask: mask, cache: cacheArray?[i]) + } } return norm(hiddenStates) diff --git a/Libraries/MLXLLM/Models/Qwen3MoE.swift b/Libraries/MLXLLM/Models/Qwen3MoE.swift index aa303ae21f..c5b53fcd99 100644 --- a/Libraries/MLXLLM/Models/Qwen3MoE.swift +++ b/Libraries/MLXLLM/Models/Qwen3MoE.swift @@ -186,7 +186,16 @@ class Qwen3MoeDecoderLayer: Module { } } -public class Qwen3MoEModelInner: Module { +public class Qwen3MoEModelInner: Module, LayerPartitionable, StreamableMoE { + + + // LayerPartitionable + public var gpuLayerCount: Int? + public var totalLayerCount: Int { layers.count } + + // StreamableMoE + public var streamExperts: Bool = false + @ModuleInfo(key: "embed_tokens") var embedTokens: Embedding fileprivate let layers: [Qwen3MoeDecoderLayer] @@ -213,7 +222,9 @@ public class Qwen3MoEModelInner: Module { let mask = createAttentionMask(h: h, cache: cache?.first) for (i, layer) in layers.enumerated() { - h = layer(h, mask: mask, cache: cache?[i]) + h = partitionedLayerCall(index: i, gpuLayerCount: gpuLayerCount, stream: streamExperts) { + layer(h, mask: mask, cache: cache?[i]) + } } return norm(h) diff --git a/Libraries/MLXLLM/Models/Qwen3Next.swift b/Libraries/MLXLLM/Models/Qwen3Next.swift index cfe0a985bd..355f25a30b 100644 --- a/Libraries/MLXLLM/Models/Qwen3Next.swift +++ b/Libraries/MLXLLM/Models/Qwen3Next.swift @@ -29,7 +29,14 @@ final class Qwen3NextRMSNormGated: Module { } func callAsFunction(_ hiddenStates: MLXArray, gate: MLXArray? = nil) -> MLXArray { - var x = MLXFast.rmsNorm(hiddenStates, weight: weight, eps: eps) + var x: MLXArray + let isCPU = Device.defaultDevice().deviceType == .cpu + if isCPU { + let variance = mean(square(hiddenStates), axis: -1, keepDims: true) + x = (hiddenStates * rsqrt(variance + eps)) * weight + } else { + x = MLXFast.rmsNorm(hiddenStates, weight: weight, eps: eps) + } if let gate { x = x * silu(gate) } diff --git a/Libraries/MLXLLM/Models/SmolLM3.swift b/Libraries/MLXLLM/Models/SmolLM3.swift index 64482f79a8..aebd734bce 100644 --- a/Libraries/MLXLLM/Models/SmolLM3.swift +++ b/Libraries/MLXLLM/Models/SmolLM3.swift @@ -137,7 +137,12 @@ class SmolLM3TransformerBlock: Module { // MARK: - Model -public class SmolLM3ModelInner: Module { +public class SmolLM3ModelInner: Module, LayerPartitionable { + + + // LayerPartitionable + public var gpuLayerCount: Int? + public var totalLayerCount: Int { layers.count } @ModuleInfo(key: "embed_tokens") var embedTokens: Embedding fileprivate let layers: [SmolLM3TransformerBlock] @@ -159,7 +164,9 @@ public class SmolLM3ModelInner: Module { let mask = createAttentionMask(h: h, cache: cache?.first) for (i, layer) in layers.enumerated() { - h = layer(h, mask: mask, cache: cache?[i]) + h = partitionedLayerCall(index: i, gpuLayerCount: gpuLayerCount) { + layer(h, mask: mask, cache: cache?[i]) + } } return norm(h) diff --git a/Libraries/MLXLLM/Models/Starcoder2.swift b/Libraries/MLXLLM/Models/Starcoder2.swift index c107a96cb0..def356ded0 100644 --- a/Libraries/MLXLLM/Models/Starcoder2.swift +++ b/Libraries/MLXLLM/Models/Starcoder2.swift @@ -115,7 +115,12 @@ class Starcoder2TransformerBlock: Module { } } -public class Starcoder2ModelInner: Module { +public class Starcoder2ModelInner: Module, LayerPartitionable { + + + // LayerPartitionable + public var gpuLayerCount: Int? + public var totalLayerCount: Int { layers.count } @ModuleInfo(key: "embed_tokens") var embedTokens: Embedding fileprivate let layers: [Starcoder2TransformerBlock] @@ -140,7 +145,9 @@ public class Starcoder2ModelInner: Module { let mask = createAttentionMask(h: h, cache: cache?.first) for (i, layer) in layers.enumerated() { - h = layer(h, mask: mask, cache: cache?[i]) + h = partitionedLayerCall(index: i, gpuLayerCount: gpuLayerCount) { + layer(h, mask: mask, cache: cache?[i]) + } } return norm(h) diff --git a/Libraries/MLXLMCommon/AttentionUtils.swift b/Libraries/MLXLMCommon/AttentionUtils.swift index 5b4e6c76bc..f3af074559 100644 --- a/Libraries/MLXLMCommon/AttentionUtils.swift +++ b/Libraries/MLXLMCommon/AttentionUtils.swift @@ -1,6 +1,40 @@ import Foundation import MLX +// ── TurboKV Telemetry ──────────────────────────────────────────────────────── +// Feeds C atomics in moe_stream_op.cpp; stats appear in the 10s SSD Stream log: +// [⚡️ SSD Stream] 7330 MB/s | ... | 🗜 TurboKV 4244t 4.3x +// No per-event prints — zero log spam. + +// Direct link to the C atomic recorder in moe_stream_op.cpp +@_silgen_name("mlx_turbo_kv_record") +func _mlxTurboKVRecord(_ tokens: UInt64, _ origBytes: UInt64, _ packedBytes: UInt64) + +enum TurboKVTelemetry { + /// Feed the 10s log aggregator from the cache compression path. + /// + /// `keys` and `values` are the packed uint8 arrays just produced by turboQuantEncode. + /// Shape: [B, nKVH, newTokens, packedDim] + /// origBytes = B × nKVH × newTokens × headDim × 2B (fp16) × 2 (K+V) + static func logOnce(compressedOffset: Int, keys: MLXArray, values: MLXArray, headDim: Int) { + let B = keys.dim(0) + let nKVH = keys.dim(1) + let newTokens = keys.dim(2) // only the tokens just encoded, not cumulative + let packedBytes = UInt64(keys.nbytes + values.nbytes) + let origBytes = UInt64(B * nKVH * newTokens * headDim * 2 * 2) // K+V fp16 + _mlxTurboKVRecord(UInt64(newTokens), origBytes, packedBytes) + } + + /// Feed the 10s log aggregator from the AttentionUtils decode path. + static func record(tokens: Int, origBytes: Int, packedBytes: Int) { + _mlxTurboKVRecord(UInt64(tokens), UInt64(origBytes), UInt64(packedBytes)) + } +} + +/// Alias used by KVCache.swift on the compression path. +typealias TurboKVCacheTelemetry = TurboKVTelemetry +// ───────────────────────────────────────────────────────────────────────────── + /// Attention utilities that match Python mlx-lm's interface /// /// This provides a single function that automatically routes to quantized or regular @@ -34,6 +68,29 @@ import MLX /// - scale: Attention scale factor /// - mask: Attention mask /// - Returns: Attention output [B, nHeads, L, D] +/// Fallback for scaledDotProductAttention when running on a CPU device +private func fallbackScaledDotProductAttention( + queries: MLXArray, keys: MLXArray, values: MLXArray, scale: Float, mask: MLXFast.ScaledDotProductAttentionMaskMode +) -> MLXArray { + // Handle Grouped Query Attention (GQA) / Multi-Query Attention (MQA) + var k = keys + var v = values + let qHeads = queries.dim(1) + let kHeads = keys.dim(1) + if qHeads > kHeads { + let repeats = qHeads / kHeads + k = MLX.repeated(k, count: repeats, axis: 1) + v = MLX.repeated(v, count: repeats, axis: 1) + } + + var scores = (queries * scale).matmul(k.transposed(0, 1, 3, 2)) + if let maskArray = mask.mask { + scores = scores + maskArray + } + let softMaxScores = MLX.softmax(scores.asType(.float32), axis: -1).asType(scores.dtype) + return matmul(softMaxScores, v) +} + public func attentionWithCacheUpdate( queries: MLXArray, keys: MLXArray, @@ -42,7 +99,14 @@ public func attentionWithCacheUpdate( scale: Float, mask: MLXFast.ScaledDotProductAttentionMaskMode = .none ) -> MLXArray { + let isCPU = Device.defaultDevice().deviceType == .cpu + + guard let cache else { + if isCPU { + return fallbackScaledDotProductAttention( + queries: queries, keys: keys, values: values, scale: scale, mask: mask) + } return MLXFast.scaledDotProductAttention( queries: queries, keys: keys, @@ -51,27 +115,95 @@ public func attentionWithCacheUpdate( mask: mask ) } + if let quantizedKVCache = cache as? QuantizedKVCacheProtocol { + if isCPU { + fatalError("[metal_kernel] Quantized KV Cache partitioning is only supported on GPU.") + } let (quantizedKeys, quantizedValues) = quantizedKVCache.updateQuantized( keys: keys, values: values) + + let targetS = quantizedKeys.0.dim(2) + var safeMask = mask + if case .array(let customMask) = mask { + if customMask.dim(-1) != targetS && customMask.dim(-1) > targetS { + let sliced: MLXArray + if customMask.ndim == 2 { + sliced = customMask[0..., .. 0 { + // Hot-window design: cachedKeys = fp16 hot window only (self.keys after eviction). + // polarKeys = compressed older history. They are disjoint — no duplication possible. + // SDPA sees: [decoded_prior_history | fp16_hot_window] + let historyK = MLXFast.turboDecodeK(packed: pk).asType(cachedKeys.dtype) + let historyV = MLXFast.turboDecodeV(packed: pv).asType(cachedValues.dtype) + // Merge 2×256 virtual heads back if 512-dim split was used + var mergedK = historyK + var mergedV = historyV + if kvCache.turboSplitHeads { + let B = historyK.dim(0), H2 = historyK.dim(1), T = historyK.dim(2) + mergedK = historyK.reshaped(B, H2 / 2, T, 512) + mergedV = historyV.reshaped(B, H2 / 2, T, 512) + } + fullKeys = concatenated([mergedK, cachedKeys], axis: 2) + fullValues = concatenated([mergedV, cachedValues], axis: 2) + // Telemetry fed from KVCache.update() on the compression path. + } + + let targetS = fullKeys.dim(2) + var safeMask = mask + if case .array(let customMask) = mask { + if customMask.dim(-1) != targetS && customMask.dim(-1) > targetS { + let sliced: MLXArray + if customMask.ndim == 2 { + sliced = customMask[0..., .. Self { - Self(role: .assistant, content: content, images: images, videos: videos) + Self(role: .assistant, content: content, images: images, videos: videos, toolCalls: toolCalls) } public static func user( @@ -42,8 +52,8 @@ public enum Chat { Self(role: .user, content: content, images: images, videos: videos) } - public static func tool(_ content: String) -> Self { - Self(role: .tool, content: content) + public static func tool(_ content: String, toolCallId: String? = nil) -> Self { + Self(role: .tool, content: content, toolCallId: toolCallId) } public enum Role: String, Sendable { @@ -81,10 +91,17 @@ public protocol MessageGenerator: Sendable { extension MessageGenerator { public func generate(message: Chat.Message) -> Message { - [ + var dict: [String: any Sendable] = [ "role": message.role.rawValue, "content": message.content, ] + if let toolCalls = message.toolCalls { + dict["tool_calls"] = toolCalls + } + if let toolCallId = message.toolCallId { + dict["tool_call_id"] = toolCallId + } + return dict } public func generate(messages: [Chat.Message]) -> [Message] { @@ -123,10 +140,17 @@ public struct DefaultMessageGenerator: MessageGenerator { public init() {} public func generate(message: Chat.Message) -> Message { - [ + var dict: [String: any Sendable] = [ "role": message.role.rawValue, "content": message.content, ] + if let toolCalls = message.toolCalls { + dict["tool_calls"] = toolCalls + } + if let toolCallId = message.toolCallId { + dict["tool_call_id"] = toolCallId + } + return dict } } diff --git a/Libraries/MLXLMCommon/Downloader.swift b/Libraries/MLXLMCommon/Downloader.swift index 939ebe278a..149e7901cd 100644 --- a/Libraries/MLXLMCommon/Downloader.swift +++ b/Libraries/MLXLMCommon/Downloader.swift @@ -74,6 +74,7 @@ public struct ResolvedModelConfiguration: Sendable { public var extraEOSTokens: Set public var eosTokenIds: Set public var toolCallFormat: ToolCallFormat? + public var lazyLoad: Bool public init( modelDirectory: URL, @@ -82,7 +83,8 @@ public struct ResolvedModelConfiguration: Sendable { defaultPrompt: String, extraEOSTokens: Set, eosTokenIds: Set, - toolCallFormat: ToolCallFormat? + toolCallFormat: ToolCallFormat?, + lazyLoad: Bool = false ) { self.modelDirectory = modelDirectory self.tokenizerDirectory = tokenizerDirectory @@ -91,6 +93,7 @@ public struct ResolvedModelConfiguration: Sendable { self.extraEOSTokens = extraEOSTokens self.eosTokenIds = eosTokenIds self.toolCallFormat = toolCallFormat + self.lazyLoad = lazyLoad } } diff --git a/Libraries/MLXLMCommon/Evaluate.swift b/Libraries/MLXLMCommon/Evaluate.swift index abcc01246a..5cb43971a5 100644 --- a/Libraries/MLXLMCommon/Evaluate.swift +++ b/Libraries/MLXLMCommon/Evaluate.swift @@ -26,7 +26,7 @@ public protocol LogitSampler { /// /// ```swift /// logits = processor?.process(logits: logits) ?? logits -/// let y = sampler.sample(logits: logits) +/// let y = sampler.sample(logits: logits); print("GENERATED TOKEN INNER: ", y.item(Int.self)) /// processor?.didSample(token: y) /// ``` /// @@ -845,6 +845,11 @@ public struct SpeculativeTokenIterator: TokenIteratorProtocol { return } + // Checkpoint Mamba caches before speculation (for rollback on rejection) + for layer in mainCache { + if let mamba = layer as? MambaCache { mamba.checkpoint() } + } + // Draft generation: autoregressive loop with draft model var draftProcessor = processor // Copy to discard later var draftTokens = [MLXArray]() @@ -1346,7 +1351,7 @@ public func generate( /// // Process the stream asynchronously to handle text chunks and completion info. /// for await generation in stream { /// switch generation { -/// case .chunk(let text): +/// case .chunk(let text, _): /// print("Generated text: \(text)") /// case .info(let info): /// print("Finished: \(info.tokensPerSecond) tokens/s.") @@ -1722,7 +1727,7 @@ private func generateLoopTask( if stopReason == nil { if Task.isCancelled { stopReason = .cancelled - } else if let maxTokens = iterator.maxTokens, iterator.tokenCount >= maxTokens { + } else if let maxTokens = iterator.maxTokens, tokenCount >= maxTokens { stopReason = .length } else { stopReason = .cancelled @@ -1844,12 +1849,14 @@ public struct GenerateCompletionInfo: Sendable { /// Represents the different stages or outputs of the token generation process. /// /// This enum distinguishes between the following: -/// - `.chunk`: A decoded string from one or more tokens generated by the language model. +/// - `.chunk`: A decoded string from one or more tokens generated by the language model, along with the token ID. /// - `.toolCall`: A tool call parsed from the generated output. /// - `.info`: Metadata and performance statistics about the generation process. public enum Generation: Sendable { - /// A generated text chunk as a String. - case chunk(String) + /// A generated text chunk as a String, paired with the raw token ID that produced it. + /// The token ID can be used to detect special tokens (e.g. gpt-oss channel markers) + /// without relying on text matching. + case chunk(String, tokenId: Int) /// Completion information summarizing token counts and performance metrics. case info(GenerateCompletionInfo) @@ -1860,7 +1867,7 @@ public enum Generation: Sendable { /// Generated text or nil public var chunk: String? { switch self { - case .chunk(let string): string + case .chunk(let string, _): string case .info: nil case .toolCall: nil } @@ -1869,7 +1876,7 @@ public enum Generation: Sendable { /// Completion info or nil public var info: GenerateCompletionInfo? { switch self { - case .chunk: nil + case .chunk(_, _): nil case .info(let info): info case .toolCall: nil } @@ -1970,7 +1977,7 @@ private struct TextToolTokenLoopHandler: TokenLoopHandler, @unchecked Sendable { if let chunk = detokenizer.next() { // Process chunk through the tool call processor. if let textToYield = toolCallProcessor.processChunk(chunk) { - if case .terminated = emit(.chunk(textToYield)) { + if case .terminated = emit(.chunk(textToYield, tokenId: token)) { return false } } diff --git a/Libraries/MLXLMCommon/ExpertStreamingConfig.swift b/Libraries/MLXLMCommon/ExpertStreamingConfig.swift new file mode 100644 index 0000000000..585a6c1718 --- /dev/null +++ b/Libraries/MLXLMCommon/ExpertStreamingConfig.swift @@ -0,0 +1,99 @@ +// ExpertStreamingConfig.swift — Swift API for expert streaming configuration +// +// Replaces the EXPERIMENTAL_SSD_STREAM environment variable gate so expert +// streaming can be enabled on iOS (via mmap fallback) without needing +// environment variables, which iOS apps cannot set. +// +// Usage (InferenceEngine.load): +// ExpertStreamingConfig.shared.activate(modelDirectory: dir, useDirectIO: false) +// +// Usage (SwitchLayers, Load, LayerPartitioning): +// if ExpertStreamingConfig.shared.isEnabled { ... } + +import Foundation + +// MARK: — Expert Streaming Mode + +public enum ExpertStreamingMode: Sendable { + /// Expert streaming disabled — all expert weights loaded into RAM at startup. + case disabled + + /// iOS path: expert weights mmap'd from APFS. The OS page cache serves + /// pages on first access and evicts them under memory pressure. + /// Bandwidth ~2–3 GB/s sequential; works entirely within iOS sandbox. + case mmapPageCache(modelDirectory: URL) + + /// macOS path: expert weights read via pread() directly from NVMe at + /// ~5 GB/s, bypassing the page cache entirely. Expert tensors never + /// appear as "resident" — fresh allocator::malloc per expert, freed immediately. + case directNVMe(modelDirectory: URL) +} + +// MARK: — ExpertStreamingConfig + +/// Shared configuration for MoE expert streaming. +/// Set `.mode` before calling `loadContainer` / `loadWeights`. +public final class ExpertStreamingConfig: @unchecked Sendable { + public static let shared = ExpertStreamingConfig() + private init() {} + + /// Current streaming mode. Thread-safe via MainActor coordination from InferenceEngine. + public var mode: ExpertStreamingMode = .disabled + + // MARK: — Convenience accessors + + public var isEnabled: Bool { + if case .disabled = mode { return false } + return true + } + + /// The model directory to use for resolving safetensors files. + public var modelDirectory: URL? { + switch mode { + case .disabled: return nil + case .mmapPageCache(let dir): return dir + case .directNVMe(let dir): return dir + } + } + + /// True only when directNVMe mode is active (macOS MLXFast.streamedGatherMM path). + public var useDirectNVMe: Bool { + if case .directNVMe = mode { return true } + return false + } + + // MARK: — Activation helpers + + /// Activate expert streaming for a model directory. + /// - Parameters: + /// - modelDirectory: The local directory containing model safetensors files. + /// - useDirectIO: If true and on macOS, uses direct NVMe pread() (5 GB/s). + /// If false or on iOS, uses mmap page-cache fallback (2–3 GB/s). + public func activate(modelDirectory: URL, useDirectIO: Bool = false) { + #if os(macOS) + if useDirectIO { + mode = .directNVMe(modelDirectory: modelDirectory) + } else { + mode = .mmapPageCache(modelDirectory: modelDirectory) + } + #else + // iOS: always use mmap page-cache — no direct NVMe pread() access + mode = .mmapPageCache(modelDirectory: modelDirectory) + #endif + } + + /// Disable expert streaming and free resources. + public func deactivate() { + mode = .disabled + } +} + +// MARK: — Backward Compatibility Shim + +extension ExpertStreamingConfig { + /// Returns the model directory path string if active, for use in C-level APIs. + /// This replaces `ProcessInfo.processInfo.environment["EXPERIMENTAL_SSD_STREAM"]`. + public var legacyEnvPath: String? { + modelDirectory?.path + } +} diff --git a/Libraries/MLXLMCommon/KVCache.swift b/Libraries/MLXLMCommon/KVCache.swift index b29434bff8..74cc4968cb 100644 --- a/Libraries/MLXLMCommon/KVCache.swift +++ b/Libraries/MLXLMCommon/KVCache.swift @@ -315,6 +315,26 @@ public func createSSMMask(h: MLXArray, cache: MambaCache?) -> MLXArray? { public class KVCacheSimple: BaseKVCache, CustomDebugStringConvertible { internal var keys: MLXArray? internal var values: MLXArray? + + // ── TurboQuant State ─────────────────────────────────────────────────────── + // When turboQuantEnabled=true (--turbo-kv flag), every incoming KV token is + // immediately compressed into 3-bit PolarQuant format. No fp16 buffer is kept. + // Design mirrors TurboQuantKVCacheV3.update_and_fetch() in the reference: + // all tokens → polarKeys/polarValues packed buffers from token 1. + // AttentionUtils decodes the full packed buffer before each SDPA call. + public var turboQuantEnabled: Bool = false + /// Tracks head_dim values that have already emitted a TurboKV fallback warning (log once per dim). + nonisolated(unsafe) private static var turboWarnedHeadDims: Set = [] + /// When true, 512-dim heads were split into 2×256 virtual heads for TurboKV encoding. + /// Decode must merge them back: [B, nKVH*2, T, 256] → [B, nKVH, T, 512] + public var turboSplitHeads: Bool = false + public var polarKeys: MLXArray? // packed uint8 [B, nKVH, T_total, 68 or 136] + public var polarValues: MLXArray? // packed uint8 [B, nKVH, T_total, 50 or 100] + public var residualKeys: MLXArray? + public var residualValues: MLXArray? + /// Total tokens stored in polarKeys/polarValues + public var compressedOffset: Int = 0 + public var step = 256 public override init() { @@ -328,6 +348,7 @@ public class KVCacheSimple: BaseKVCache, CustomDebugStringConvertible { public override func update(keys: MLXArray, values: MLXArray) -> (MLXArray, MLXArray) { let previous = self.offset + // ── Standard fp16 buffer (always runs — TurboKV evicts cold tokens after writing) ── let reset = if let currentKeys = self.keys, (previous + keys.dim(2)) > currentKeys.dim(2) { true @@ -348,30 +369,135 @@ public class KVCacheSimple: BaseKVCache, CustomDebugStringConvertible { if var currentKeys = self.keys, var currentValues = self.values { if previous % step != 0 { - currentKeys = currentKeys[.ellipsis, .. turboMinActivationTokens { + // Only compress once we have a genuinely long context. + // Below this threshold every token stays at full fp16 quality. + let coldEnd = self.offset - turboHotWindowSize + let newColdCount = coldEnd - self.compressedOffset // not-yet-compressed cold tokens + + if newColdCount >= step { // evict in step-sized chunks to avoid micro-operations + if let fullK = self.keys, let fullV = self.values { + var coldK = fullK[.ellipsis, self.compressedOffset..2048t) pay the 3-bit compression trade-off. + public var turboMinActivationTokens: Int = 2048 + + /// Number of fp16 tokens preserved as a high-quality hot window. + /// Only tokens older than this boundary are compressed into polarKeys. + /// Compression first triggers when offset > turboMinActivationTokens. + public var turboHotWindowSize: Int = 256 + + + + + public override var state: [MLXArray] { get { + // When TurboKV is active the fp16 buffer (self.keys) holds only the hot window. + // Returning just that would cause the prompt-cache to lose all compressed history, + // making every subsequent request that hits the cache see a truncated context. + // Fix: decode polarKeys and concatenate with the hot window to form the full fp16 state. + if turboQuantEnabled, + let pk = polarKeys, let pv = polarValues, + compressedOffset > 0, + let hotK = self.keys, let hotV = self.values { + var histK = MLXFast.turboDecodeK(packed: pk) + var histV = MLXFast.turboDecodeV(packed: pv) + // Merge 2×256 virtual heads back to original head count × 512 + if turboSplitHeads { + let B = histK.dim(0), H2 = histK.dim(1), T = histK.dim(2) + histK = histK.reshaped(B, H2 / 2, T, 512) + histV = histV.reshaped(B, H2 / 2, T, 512) + } + let hotKSlice = hotK[.ellipsis, .. Int { let trimmed = min(offset, n) offset -= trimmed + idx -= trimmed + // Wrap circular buffer correctly, skipping 'keep' region + while idx < keep && offset >= keep { + // idx underflowed into the keep region (or negative). + // The logical step back from 'keep' is the end of the buffer. + idx += (maxCacheSize - keep) + } + if offset < keep { + // If offset itself is within the keep region, idx and offset match. + idx = offset + } + return trimmed } @@ -658,14 +805,25 @@ public class RotatingKVCache: BaseKVCache, CustomDebugStringConvertible { n: Int, windowSize: Int?, returnArray: Bool ) -> MLXFast.ScaledDotProductAttentionMaskMode { if n > 1 { - // Multi-token case + // Multi-token case (prefill / prompt re-encode) + // + // updateConcat temporarily allows the physical key buffer to grow to + // (existingKeys + n) before trimming back toward maxCacheSize + n - 1. + // The buffer returned to the attention layer has exactly: + // physicalKeyCount = min(existingKeys + n, maxCacheSize + n - 1) + // columns, where existingKeys = min(offset, maxCacheSize). + // + // The mask must be [n, physicalKeyCount] wide, so we pass + // offset = physicalKeyCount - n to createCausalMask. let actualWindowSize = windowSize ?? maxCacheSize - let cappedOffset = min(maxCacheSize - 1, offset) + let existingKeys = min(offset, maxCacheSize) + // Physical key width the cache returns for this n-token batch + let physicalKeyCount = min(existingKeys + n, maxCacheSize + n - 1) + let maskOffset = physicalKeyCount - n - // Decide if we need an array mask - if cappedOffset + n > actualWindowSize || returnArray { + if maskOffset + n > actualWindowSize || returnArray { return .array( - createCausalMask(n: n, offset: cappedOffset, windowSize: actualWindowSize)) + createCausalMask(n: n, offset: maskOffset, windowSize: actualWindowSize)) } return .causal } else { @@ -1152,10 +1310,40 @@ public class ArraysCache: BaseKVCache { /// Simple cache for Mamba-style state space models public class MambaCache: ArraysCache { + /// Saved state for speculative decoding rollback. + /// Mamba state is recurrent and cannot be partially "trimmed" like attention KV caches. + /// Instead, we checkpoint before speculation and restore on rollback. + private var savedState: [MLXArray]? + public init(leftPadding: [Int]? = nil) { super.init(size: 2, leftPadding: leftPadding) } + /// Mark as trimmable to enable speculative decoding on hybrid Attention+Mamba models. + public override var isTrimmable: Bool { true } + + /// Save a checkpoint of the current Mamba state (call before speculative draft round). + public func checkpoint() { + let s = self.state + if !s.isEmpty { + savedState = s.map { $0[.ellipsis] } // deep copy + } + } + + /// Trim: for Mamba, restore from checkpoint if tokens are rejected. + /// When n > 0, rejected draft tokens have polluted the state — restore checkpoint. + /// When n == 0, all drafts accepted — keep current state and clear checkpoint. + @discardableResult + public override func trim(_ n: Int) -> Int { + if n > 0, let saved = savedState { + self.state = saved + savedState = nil + return n + } + savedState = nil // Clear checkpoint on full acceptance + return 0 + } + public override func copy() -> any KVCache { let new = MambaCache() let s = self.state diff --git a/Libraries/MLXLMCommon/LayerPartitioning.swift b/Libraries/MLXLMCommon/LayerPartitioning.swift new file mode 100644 index 0000000000..e0d26a80b4 --- /dev/null +++ b/Libraries/MLXLMCommon/LayerPartitioning.swift @@ -0,0 +1,159 @@ +// LayerPartitioning.swift — GPU/CPU layer partitioning support +// +// Provides a protocol for models that support running a subset of layers +// on GPU and the rest on CPU. On Apple Silicon with unified memory, +// there is zero data copy cost between CPU and GPU layers. +// +// Usage: +// 1. Model conforms to LayerPartitionable +// 2. After loading, call model.setGPULayers(N) to set the split +// 3. The model's forward pass uses partitionedLayerCall() to route each layer + +import Foundation +import MLX +import MLXNN + +// MARK: - Layer Partitioning Protocol + +/// Protocol for models that support per-layer GPU/CPU device placement. +/// +/// Models conforming to this protocol can run a configurable number of +/// transformer layers on GPU and the remainder on CPU, enabling inference +/// of models larger than available GPU memory on Apple Silicon. +/// +/// Because Apple Silicon uses unified memory architecture (UMA), there is +/// no data transfer cost between CPU and GPU layers — only the compute +/// engine differs. +public protocol LayerPartitionable: AnyObject { + + /// Number of layers to run on GPU. Layers beyond this index run on CPU. + /// When nil or >= total layer count, all layers run on GPU (default behavior). + var gpuLayerCount: Int? { get set } + + /// Total number of transformer layers in the model. + var totalLayerCount: Int { get } +} + +extension LayerPartitionable { + + /// Set the number of layers to run on GPU. + /// Pass nil to run all layers on GPU (default). + /// Values are clamped to [0, totalLayerCount]. + public func setGPULayers(_ count: Int?) { + if let count { + gpuLayerCount = min(max(0, count), totalLayerCount) + } else { + gpuLayerCount = nil + } + } + + /// Whether a given layer index should run on GPU. + public func isGPULayer(_ index: Int) -> Bool { + guard let gpuCount = gpuLayerCount else { return true } + return index < gpuCount + } + + /// The number of layers running on CPU. + public var cpuLayerCount: Int { + guard let gpuCount = gpuLayerCount else { return 0 } + return max(0, totalLayerCount - gpuCount) + } + + /// Summary string for logging. + public var partitionSummary: String { + guard let gpuCount = gpuLayerCount else { + return "\(totalLayerCount)/\(totalLayerCount) GPU (full)" + } + let cpuCount = totalLayerCount - gpuCount + return "\(gpuCount) GPU / \(cpuCount) CPU" + } +} + +// MARK: - Expert Streaming Protocol + +/// Protocol for Mixture-of-Experts (MoE) models that support SSD expert streaming. +/// +/// When `streamExperts` is enabled, the model evaluates intermediate states and +/// clears the MLX cache layer-by-layer. This pattern allows the OS Page Cache +/// to effortlessly load multi-gigabyte expert weights on the fly (`mmap`) and +/// discard them immediately to prevent Out-Of-Memory errors on memory-constrained +/// Apple Silicon devices (e.g., loading a 100B model on 16GB RAM). +public protocol StreamableMoE: AnyObject { + /// Whether this model should stream expert weights from SSD layer-by-layer + var streamExperts: Bool { get set } +} + +// MARK: - Partitioned Layer Execution + +/// Execute a single transformer layer on the appropriate device (GPU or CPU). +/// +/// This is the core routing function. When a layer is designated for CPU, +/// the entire forward pass of that layer runs on the CPU stream. +/// MLX's lazy evaluation ensures the computation graph is built correctly +/// across device boundaries with zero-copy UMA transfers. +/// +/// - Parameters: +/// - index: The layer index (0-based) +/// - gpuLayerCount: Number of layers assigned to GPU (nil = all GPU) +/// - stream: If true, synchronously evaluates the layer and clears MLX cache (Flash-MoE style) +/// - body: The layer forward pass closure +/// - Returns: The layer output +public func partitionedLayerCall( + index: Int, + gpuLayerCount: Int?, + stream: Bool = false, + cacheToEval: KVCache? = nil, + body: () -> T +) -> T { + let result: T + + let isSsdStream = ExpertStreamingConfig.shared.isEnabled + + if let gpuCount = gpuLayerCount, index >= gpuCount, !isSsdStream { + // CPU layer — scope the computation to the CPU device + result = Device.withDefaultDevice(.cpu, body) + } else { + // GPU layer (default path — no overhead) + result = body() + } + + // ─── EVAL SKIP (SSD STREAMING) ────────────────────────────────────────── + // When SSD streaming is active, we skip the per-layer eval here entirely. + // + // Why this is safe: + // 1. WATCHDOG: SwitchGLU's eval(idx + buffers) at the START of each MoE + // layer flushes the GPU command buffer, preventing the 5-second Apple + // GPU watchdog timeout on consecutive GatedDeltaNet linear-attention layers. + // + // 2. KV CACHE: The next layer's SwitchGLU eval(idx_next) transitively forces + // the current layer's FULL output (including KV cache) because: + // idx_next → router(h_N) → h_N = attn_out + MoE_out → + // attn_out → SDPA(Q, cached_K, cached_V) → cache.update(K, V) + // So the KV cache is materialized through the lazy dependency chain. + // + // 3. LAST LAYER: The generation loop's eval of logits forces layer 47's output. + // + // This eliminates 48 eval calls per token (~48-96ms of overhead). + // ───────────────────────────────────────────────────────────────────────── + if isSsdStream { + return result + } + + if stream, let array = result as? MLXArray { + // 1. Force evaluation of this single layer state. + if let cache = cacheToEval { + var itemsToEval = cache.state + itemsToEval.append(array) + eval(itemsToEval) + Stream.gpu.synchronize() + } else { + eval(array) + Stream.gpu.synchronize() + } + + // 2. Clear MLX's internal Metal buffer pool. + GPU.clearCache() + } + + return result +} diff --git a/Libraries/MLXLMCommon/Load.swift b/Libraries/MLXLMCommon/Load.swift index 1161620db2..a434fc49fc 100644 --- a/Libraries/MLXLMCommon/Load.swift +++ b/Libraries/MLXLMCommon/Load.swift @@ -14,7 +14,8 @@ import MLXNN public func loadWeights( modelDirectory: URL, model: LanguageModel, quantization: BaseConfiguration.Quantization? = nil, - perLayerQuantization: BaseConfiguration.PerLayerQuantization? = nil + perLayerQuantization: BaseConfiguration.PerLayerQuantization? = nil, + lazyLoad: Bool = false ) throws { // load the weights and collect metadata from the first safetensor file var weights = [String: MLXArray]() @@ -36,12 +37,26 @@ public func loadWeights( // per-model cleanup (models can inspect metadata to customize behavior) weights = model.sanitize(weights: weights, metadata: metadata) + // ExpertStreamingConfig: Initialize the ExpertStreamerManager when streaming is active. + // On macOS: pread() from NVMe at ~5 GB/s. + // On iOS: mmap page-cache from APFS at ~2-3 GB/s — same struct, different bandwidth. + if ExpertStreamingConfig.shared.isEnabled { + ExpertStreamerManager.shared = ExpertStreamerManager(modelDirectory: modelDirectory) + } + // quantize if needed if quantization != nil || perLayerQuantization != nil { quantize(model: model) { path, module in if weights["\(path).scales"] != nil { if let perLayerQuantization { - return perLayerQuantization.quantization(layer: path)?.asTuple + let dict = perLayerQuantization.perLayerQuantization + if let opt = dict[path] ?? dict["language_model.\(path)"] { + switch opt { + case .skip: return nil + case .quantize(let q): return q.asTuple + } + } + return perLayerQuantization.quantization?.asTuple } else { return quantization?.asTuple } @@ -55,5 +70,35 @@ public func loadWeights( let parameters = ModuleParameters.unflattened(weights) try model.update(parameters: parameters, verify: [.all]) - eval(model) + if ExpertStreamingConfig.shared.isEnabled { + // Assign tensorName to each QuantizedSwitchLinear. + // + // CRITICAL: tensorName must be the ORIGINAL key in the safetensors shard + // (before sanitize() strips VLM wrapper prefixes like "language_model."), + // because BOTH ExpertStreamerManager.getFile() and the C++ streamedGatherMM + // pread() use this key to locate the tensor bytes within the shard file. + // + // Example for Mistral4: + // post-sanitize path → "model.layers.0.mlp.switch_mlp.gate_proj" + // original shard key → "language_model.model.layers.0.mlp.switch_mlp.gate_proj.weight" + // + // We probe the ExpertStreamerManager weight map with common VLM prefixes + // and fall back to the bare path if none match. + let knownPrefixes = ["language_model.", "model.language_model.", ""] + for (path, module) in model.leafModules().flattened() { + if let qsl = module as? QuantizedSwitchLinear { + let bareName = "\(path).weight" + // Find the original key that exists in the shard index + let originalKey = knownPrefixes.lazy + .map { $0 + bareName } + .first { ExpertStreamerManager.shared?.getFile(for: $0) != nil } + ?? bareName // fallback: use bare name (works when model has no VLM wrapper) + qsl.tensorName = originalKey + } + } + } + + if !lazyLoad { + eval(model) + } } diff --git a/Libraries/MLXLMCommon/ModelConfiguration.swift b/Libraries/MLXLMCommon/ModelConfiguration.swift index d3d50e3ce2..c44d5c5dce 100644 --- a/Libraries/MLXLMCommon/ModelConfiguration.swift +++ b/Libraries/MLXLMCommon/ModelConfiguration.swift @@ -91,18 +91,24 @@ public struct ModelConfiguration: Sendable { /// Tool call format for this model (nil = default JSON format) public var toolCallFormat: ToolCallFormat? + /// If true, model weights are loaded lazily via mmap and not evaluated during loading. + public var lazyLoad: Bool = false + public init( id: String, revision: String = "main", tokenizerSource: TokenizerSource? = nil, defaultPrompt: String = "", extraEOSTokens: Set = [], - toolCallFormat: ToolCallFormat? = nil + toolCallFormat: ToolCallFormat? = nil, + preparePrompt: (@Sendable (String) -> String)? = nil, + lazyLoad: Bool = false ) { self.id = .id(id, revision: revision) self.tokenizerSource = tokenizerSource self.defaultPrompt = defaultPrompt self.extraEOSTokens = extraEOSTokens self.toolCallFormat = toolCallFormat + self.lazyLoad = lazyLoad } public init( @@ -111,7 +117,8 @@ public struct ModelConfiguration: Sendable { defaultPrompt: String = "", extraEOSTokens: Set = [], eosTokenIds: Set = [], - toolCallFormat: ToolCallFormat? = nil + toolCallFormat: ToolCallFormat? = nil, + lazyLoad: Bool = false ) { self.id = .directory(directory) self.tokenizerSource = tokenizerSource @@ -119,6 +126,7 @@ public struct ModelConfiguration: Sendable { self.extraEOSTokens = extraEOSTokens self.eosTokenIds = eosTokenIds self.toolCallFormat = toolCallFormat + self.lazyLoad = lazyLoad } /// Maps this configuration's behavioral properties into a @@ -136,7 +144,8 @@ public struct ModelConfiguration: Sendable { defaultPrompt: defaultPrompt, extraEOSTokens: extraEOSTokens, eosTokenIds: eosTokenIds, - toolCallFormat: toolCallFormat) + toolCallFormat: toolCallFormat, + lazyLoad: lazyLoad) } } diff --git a/Libraries/MLXLMCommon/ModelContainer.swift b/Libraries/MLXLMCommon/ModelContainer.swift index 9ecc309d76..5e571e5974 100644 --- a/Libraries/MLXLMCommon/ModelContainer.swift +++ b/Libraries/MLXLMCommon/ModelContainer.swift @@ -237,4 +237,109 @@ public final class ModelContainer: Sendable { let tokenizer = await self.tokenizer return try tokenizer.applyChatTemplate(messages: messages) } + + // MARK: - Layer Partitioning + + /// Configure GPU/CPU layer partitioning for the loaded model. + /// + /// When set, the first `gpuLayers` transformer layers run on GPU + /// and the rest run on CPU. This enables inference of models larger + /// than available GPU memory on Apple Silicon with UMA. + /// + /// - Parameter gpuLayers: Number of layers to run on GPU, or nil for all-GPU. + /// - Returns: The actual number of GPU layers set (after clamping), or nil. + @discardableResult + public func setGPULayers(_ gpuLayers: Int?) async -> Int? { + await context.read { ctx in + // Walk the module tree to find a LayerPartitionable child + if let partitionable = Self.findPartitionable(in: ctx.model) { + partitionable.setGPULayers(gpuLayers) + return partitionable.gpuLayerCount + } + return nil + } + } + + /// Enable or disable SSD Expert Streaming for MoE models. + /// + /// When enabled, the model evaluates intermediate states and clears the MLX cache + /// layer-by-layer. This allows the OS Page Cache to trivially load active experts + /// from SSD and discard them immediately, preventing OOM on memory-constrained devices. + /// + /// - Parameter stream: Whether expert streaming should be enabled. + /// - Returns: True if the model supports streaming and it was set, false otherwise. + @discardableResult + public func setStreamExperts(_ stream: Bool) async -> Bool { + await context.read { ctx in + if let streamable = Self.findStreamable(in: ctx.model) { + streamable.streamExperts = stream + return true + } + return false + } + } + + /// Recursively search for a `LayerPartitionable` in the module tree. + private static func findPartitionable(in module: Module) -> (any LayerPartitionable)? { + // Use MLX's native `modules()` traversal which correctly unwraps @ModuleInfo property wrappers + return module.modules().lazy.compactMap { $0 as? (any LayerPartitionable) }.first + } + + /// Recursively search for a `StreamableMoE` in the module tree. + private static func findStreamable(in module: Module) -> (any StreamableMoE)? { + // Use MLX's native `modules()` traversal which correctly unwraps @ModuleInfo property wrappers + return module.modules().lazy.compactMap { $0 as? (any StreamableMoE) }.first + } + + // MARK: - Speculative Decoding + + /// Extract the raw LanguageModel for use as a draft model in speculative decoding. + /// The model weights are immutable after loading, making this safe for cross-context use. + public func extractDraftModel() async -> DraftModelRef { + await context.read { DraftModelRef(model: $0.model) } + } + + /// Generate tokens using speculative decoding with a draft model. + /// + /// The draft model generates `numDraftTokens` tokens which are then verified in batch + /// by the main model. Accepted tokens are emitted; rejected tokens cause KV cache rollback. + /// Both models must share the same tokenizer. + /// + /// - Parameters: + /// - input: Prepared language model input + /// - parameters: Generation parameters + /// - draftModel: Draft model reference (extracted via `extractDraftModel()`) + /// - numDraftTokens: Number of tokens the draft model proposes per round + /// - wiredMemoryTicket: Optional wired memory ticket + /// - Returns: An AsyncStream of generation events (same format as non-speculative) + public func generate( + input: consuming sending LMInput, + parameters: GenerateParameters, + draftModel: DraftModelRef, + numDraftTokens: Int = 4, + wiredMemoryTicket: WiredMemoryTicket? = nil + ) async throws -> AsyncStream { + let input = SendableBox(input) + let draft = draftModel // Already Sendable via @unchecked + + return try await context.read { context in + try MLXLMCommon.generate( + input: input.consume(), + parameters: parameters, + context: context, + draftModel: draft.model, + numDraftTokens: numDraftTokens, + wiredMemoryTicket: wiredMemoryTicket + ) + } + } +} + +// MARK: - Speculative Decoding Types + +/// Thread-safe wrapper for passing a LanguageModel reference across concurrency boundaries. +/// Safe when model weights are immutable (post-loading, inference-only usage). +/// KV caches are created fresh per SpeculativeTokenIterator, so no shared mutable state. +public struct DraftModelRef: @unchecked Sendable { + public let model: any LanguageModel } diff --git a/Libraries/MLXLMCommon/SwitchLayers.swift b/Libraries/MLXLMCommon/SwitchLayers.swift index a4bfdbc447..468f5cde35 100644 --- a/Libraries/MLXLMCommon/SwitchLayers.swift +++ b/Libraries/MLXLMCommon/SwitchLayers.swift @@ -25,18 +25,35 @@ public func scatterUnsort(x: MLXArray, invOrder: MLXArray, shape: [Int]? = nil) return x } + +// Shared struct for expert range tracking across projections +public struct ExpertRange { + public let id: Int + public let start: Int + public let end: Int +} + // MARK: - SwitchGLU public class SwitchGLU: Module { - @ModuleInfo(key: "gate_proj") var gateProj: SwitchLinear - @ModuleInfo(key: "up_proj") var upProj: SwitchLinear - @ModuleInfo(key: "down_proj") var downProj: SwitchLinear + @ModuleInfo(key: "gate_proj") public var gateProj: SwitchLinear + @ModuleInfo(key: "up_proj") public var upProj: SwitchLinear + @ModuleInfo(key: "down_proj") public var downProj: SwitchLinear let inputDims: Int let hiddenDims: Int let numExperts: Int let activation: (MLXArray) -> MLXArray + // ── Async pipeline state (SSD streaming optimization) ── + // Persistent buffers: allocated once per layer, reused across tokens. + // Avoids per-token buffer allocation + eval overhead. + private var _persistentGate: [MLXArray]? + private var _persistentUp: [MLXArray]? + private var _persistentDown: [MLXArray]? + // Previous token's expert routing per layer for speculative prefetch. + private var _previousExpertIds: [Int]? + public init( inputDims: Int, hiddenDims: Int, @@ -55,14 +72,18 @@ public class SwitchGLU: Module { inputDims: inputDims, outputDims: hiddenDims, numExperts: numExperts, bias: bias) self._downProj.wrappedValue = SwitchLinear( inputDims: hiddenDims, outputDims: inputDims, numExperts: numExperts, bias: bias) - super.init() } public func callAsFunction(_ x: MLXArray, _ indices: MLXArray) -> MLXArray { var x = MLX.expandedDimensions(x, axes: [-2, -3]) - let doSort = indices.size >= 64 + // We must force sorting/flattening when SSD streaming is active to properly batch + // expert kernel dispatches dynamically over contiguous arrays. + let isSSDStreaming = ExpertStreamingConfig.shared.isEnabled + // NOTE: indices eval deferred to inside the cross-projection path below, + // where it's merged with buffer allocation into fewer eval calls. + let doSort = (indices.size >= 64) || isSSDStreaming var idx = indices var inverseOrder = MLXArray() @@ -71,6 +92,339 @@ public class SwitchGLU: Module { (x, idx, inverseOrder) = gatherSort(x: x, indices: indices) } + // ── Cross-projection batched SSD streaming path ────────────────── + // When all 3 projections are quantized and SSD-streaming is active, + // orchestrate buffer allocation, pread, and compute across all 3 + // projections to minimize MLX.eval() calls: + // - Single-token (fast path): 1 eval merges idx + buffer alloc + // - Prompt (large batch): 2 evals (idx, then buffers) + // - NO final eval — next layer's eval(idx) forces this layer + // This reduces from 4 evals/layer (original) to 1 eval/layer. + if isSSDStreaming, + let qGate = gateProj as? QuantizedSwitchLinear, + let qUp = upProj as? QuantizedSwitchLinear, + let qDown = downProj as? QuantizedSwitchLinear, + let gateSSD = qGate.resolveSSDInfo(), + let upSSD = qUp.resolveSSDInfo(), + let downSSD = qDown.resolveSSDInfo() { + + // ── EVAL REDUCTION STRATEGY ────────────────────────────────────── + // For single-token generation (idx.size ≤ 32), we merge the sorted- + // indices eval and buffer-allocation eval into ONE call, cutting from + // 3 evals/layer to 1. The final MLX.eval(x) is removed entirely: + // the NEXT layer's SwitchGLU eval(idx) transitively forces this + // layer's full output (including KV cache) through the lazy + // dependency chain. For the last layer, the generation loop's eval + // of logits handles it. + // ───────────────────────────────────────────────────────────────── + + if idx.size <= 32 { + // ── FAST PATH: single-token generation with async I/O-GPU pipeline ── + // + // STRATEGY: Overlap NVMe I/O with GPU compute using asyncEval. + // + // Cold path (first token): Allocate persistent buffers, merged eval, + // full pread — same as ssd-opt-v1 baseline. + // + // Warm path (subsequent tokens): asyncEval(idx) starts GPU work + // (prev layer expert compute + current attention/router) while + // CPU speculatively preads predicted experts (from previous token's + // routing) into persistent buffers. After GPU sync, only ~30% of + // experts need on-demand pread (misses). Saves ~60ms/token by + // hiding I/O behind GPU compute. + // + // Memory cost: ~5GB for persistent buffers across 48 layers + // (vs ~13GB for the failed in-memory cache approach). + + let maxBuffers = idx.size // typically 8 (top_k) + + if _persistentGate == nil { + // ── COLD PATH: first token, allocate persistent buffers ── + _persistentGate = qGate.allocateExpertBuffers(maxBuffers) + _persistentUp = qUp.allocateExpertBuffers(maxBuffers) + _persistentDown = qDown.allocateExpertBuffers(maxBuffers) + + // Merged eval: idx + buffer allocations (same as ssd-opt-v1) + var toEval: [MLXArray] = [idx] + toEval.append(contentsOf: _persistentGate!) + toEval.append(contentsOf: _persistentUp!) + toEval.append(contentsOf: _persistentDown!) + MLX.eval(toEval) + + // Handle empty indices + if idx.size == 0 { + var outShape = x.shape + outShape[outShape.count - 1] = qDown.outputDims + let result = MLXArray.zeros(outShape).asType(.float16) + if doSort { + return MLX.squeezed(scatterUnsort(x: result, invOrder: inverseOrder, shape: indices.shape), axis: -2) + } + return MLX.squeezed(result, axis: -2) + } + + // Parse routing + let cpuIndices = idx.asArray(UInt32.self) + var ranges = [ExpertRange]() + var startIdx = 0 + while startIdx < cpuIndices.count { + let eid = Int(cpuIndices[startIdx]) + var endIdx = startIdx + 1 + while endIdx < cpuIndices.count && Int(cpuIndices[endIdx]) == eid { endIdx += 1 } + ranges.append(ExpertRange(id: eid, start: startIdx, end: endIdx)) + startIdx = endIdx + } + + // Full concurrent pread (baseline path) + let totalReads = ranges.count * 3 + DispatchQueue.concurrentPerform(iterations: totalReads) { i in + let expertIdx = i / 3 + let projIdx = i % 3 + let r = ranges[expertIdx] + switch projIdx { + case 0: + MLXFast.preadInto(self._persistentGate![expertIdx], safetensorsPath: gateSSD.path, + tensorName: gateSSD.tensorName, expertIndex: UInt32(r.id)) + case 1: + MLXFast.preadInto(self._persistentUp![expertIdx], safetensorsPath: upSSD.path, + tensorName: upSSD.tensorName, expertIndex: UInt32(r.id)) + default: + MLXFast.preadInto(self._persistentDown![expertIdx], safetensorsPath: downSSD.path, + tensorName: downSSD.tensorName, expertIndex: UInt32(r.id)) + } + } + + // Store routing for next token's predictions + _previousExpertIds = ranges.map { $0.id } + + // Lazy compute + let usedGate = Array(_persistentGate![0.. buffer slot + for (slot, eid) in prevIds.enumerated() { + prevSlotMap[eid] = slot + } + + var usedSlots = Set() + var missInfo = [(rangeIdx: Int, expertId: Int, bufferSlot: Int)]() + + for (ri, r) in ranges.enumerated() { + if let slot = prevSlotMap[r.id], !usedSlots.contains(slot) { + // HIT: persistent buffer[slot] has correct expert data + usedGate.append(_persistentGate![slot]) + usedUp.append(_persistentUp![slot]) + usedDown.append(_persistentDown![slot]) + usedSlots.insert(slot) + } else { + // MISS: find a free slot + let freeSlot = (0.. MLXArray { + if ExpertStreamingConfig.shared.isEnabled { + MLX.eval(indices) + if indices.size == 0 { + var outShape = x.shape + outShape[outShape.count - 1] = self.outputDims + return MLXArray.zeros(outShape).asType(.float16) + } + + let cpuIndices = indices.asArray(UInt32.self) + var expertResults = [MLXArray]() + var startIdx = 0 + + // macOS directNVMe: resolve the safetensors shard + tensor offset once. + // iOS mmapPageCache: ssdInfo = nil → falls through to mmap prefault below. + let ssdInfo: (path: String, tensorName: String)? = { + #if os(macOS) + guard ExpertStreamingConfig.shared.useDirectNVMe, + let tName = self.tensorName, + let filename = ExpertStreamerManager.shared?.getFile(for: tName), + let dir = ExpertStreamingConfig.shared.modelDirectory else { return nil } + let path = dir.appendingPathComponent(filename).path + return (path, tName) + #else + return nil // iOS always uses mmap fallback + #endif + }() + + // ---- Parse expert ranges ---- + var ranges = [ExpertRange]() + while startIdx < cpuIndices.count { + let eid = Int(cpuIndices[startIdx]) + var endIdx = startIdx + 1 + while endIdx < cpuIndices.count && Int(cpuIndices[endIdx]) == eid { endIdx += 1 } + ranges.append(ExpertRange(id: eid, start: startIdx, end: endIdx)) + startIdx = endIdx + } + + if let info = ssdInfo { + // ---- Batch-allocate weight buffers (1 eval for all) ---- + var buffers = [MLXArray]() + for _ in ranges { + buffers.append(MLXArray.zeros([1, self.weight.dim(1), self.weight.dim(2)]).asType(self.weight.dtype)) + } + MLX.eval(buffers) + + // ---- Sequential pread into each fresh buffer ---- + for (i, r) in ranges.enumerated() { + MLXFast.preadInto( + buffers[i], + safetensorsPath: info.path, + tensorName: info.tensorName, + expertIndex: UInt32(r.id) + ) + } + + // ---- GPU compute for all experts ---- + for (i, r) in ranges.enumerated() { + let rangeX = x[r.start ..< r.end] + let expertIndices = MLXArray.zeros([rangeX.dim(0)], type: UInt32.self) + let expertScales = self.scales[r.id ..< r.id + 1] + var expertBiases: MLXArray? = nil + if let b = self.biases { expertBiases = b[r.id ..< r.id + 1] } + + var expertOutput = MLX.gatherQuantizedMM( + rangeX, buffers[i], + scales: expertScales, biases: expertBiases, + rhsIndices: expertIndices, transpose: true, + groupSize: self.groupSize, bits: self.bits, mode: mode, sortedIndices: true + ) + if let bias = self.bias { + let biasSlice = bias[r.id ..< r.id + 1] + expertOutput = expertOutput + MLX.expandedDimensions(biasSlice[expertIndices], axis: -2) + } + let leadingShape = Array(rangeX.shape.dropLast()) + let canonicalShape = leadingShape + [self.outputDims] + if expertOutput.shape != canonicalShape { + expertOutput = expertOutput.reshaped(canonicalShape) + } + expertResults.append(expertOutput) + } + } else { + // iOS mmap fallback — original sequential path with per-expert eval + for r in ranges { + let rangeX = x[r.start ..< r.end] + let expertIndices = MLXArray.zeros([rangeX.dim(0)], type: UInt32.self) + let w = self.weight[r.id ..< r.id + 1] + MLX.eval(w) + MLXFast.prefault(w) + let expertScales = self.scales[r.id ..< r.id + 1] + var expertBiases: MLXArray? = nil + if let b = self.biases { expertBiases = b[r.id ..< r.id + 1] } + var expertOutput = MLX.gatherQuantizedMM( + rangeX, w, + scales: expertScales, biases: expertBiases, + rhsIndices: expertIndices, transpose: true, + groupSize: self.groupSize, bits: self.bits, mode: mode, sortedIndices: true + ) + if let bias = self.bias { + let biasSlice = bias[r.id ..< r.id + 1] + expertOutput = expertOutput + MLX.expandedDimensions(biasSlice[expertIndices], axis: -2) + } + let leadingShape = Array(rangeX.shape.dropLast()) + let canonicalShape = leadingShape + [self.outputDims] + if expertOutput.shape != canonicalShape { + expertOutput = expertOutput.reshaped(canonicalShape) + } + MLX.eval(expertOutput) + expertResults.append(expertOutput) + } + } + + // Batch eval all expert outputs at once (directNVMe path) + if let _ = ssdInfo, !expertResults.isEmpty { + MLX.eval(expertResults) + } + + if expertResults.isEmpty { + var outShape = x.shape + outShape[outShape.count - 1] = self.outputDims + return MLXArray.zeros(outShape).asType(.float16) + } + + // PAPPS Heuristic: Prefetch exactly these experts so they are in cache for the N+1 token. + if let info = ssdInfo { + let uniqueIndices = Set(cpuIndices) + for _ in uniqueIndices { + // MLXFast.pappsPrefetch( + // safetensorsPath: info.path, + // tensorName: info.tensorName, + // expertIndex: idx + // ) + } + } + + return MLX.concatenated(expertResults, axis: 0) + } + var result = MLX.gatherQuantizedMM( x, self.weight, @@ -197,4 +689,136 @@ public class QuantizedSwitchLinear: SwitchLinear, Quantized { return result } + + + // MARK: - Cross-projection batching helpers (SSD streaming) + + /// Resolve the safetensors path and tensor name for SSD streaming. + public func resolveSSDInfo() -> (path: String, tensorName: String)? { + #if os(macOS) + guard ExpertStreamingConfig.shared.useDirectNVMe, + let tName = self.tensorName, + let filename = ExpertStreamerManager.shared?.getFile(for: tName), + let dir = ExpertStreamingConfig.shared.modelDirectory else { return nil } + let path = dir.appendingPathComponent(filename).path + return (path, tName) + #else + return nil + #endif + } + + /// Allocate zero-filled weight buffers for `count` experts (lazy, not yet eval'd). + public func allocateExpertBuffers(_ count: Int) -> [MLXArray] { + var buffers = [MLXArray]() + for _ in 0.. MLXArray { + var expertResults = [MLXArray]() + for (i, r) in ranges.enumerated() { + let rangeX = x[r.start ..< r.end] + let expertIndices = MLXArray.zeros([rangeX.dim(0)], type: UInt32.self) + let expertScales = self.scales[r.id ..< r.id + 1] + var expertBiases: MLXArray? = nil + if let b = self.biases { expertBiases = b[r.id ..< r.id + 1] } + + var expertOutput = MLX.gatherQuantizedMM( + rangeX, buffers[i], + scales: expertScales, biases: expertBiases, + rhsIndices: expertIndices, transpose: true, + groupSize: self.groupSize, bits: self.bits, mode: mode, sortedIndices: true + ) + if let bias = self.bias { + let biasSlice = bias[r.id ..< r.id + 1] + expertOutput = expertOutput + MLX.expandedDimensions(biasSlice[expertIndices], axis: -2) + } + let leadingShape = Array(rangeX.shape.dropLast()) + let canonicalShape = leadingShape + [self.outputDims] + if expertOutput.shape != canonicalShape { + expertOutput = expertOutput.reshaped(canonicalShape) + } + expertResults.append(expertOutput) + } + + if expertResults.isEmpty { + var outShape = x.shape + outShape[outShape.count - 1] = self.outputDims + return MLXArray.zeros(outShape).asType(.float16) + } + return MLX.concatenated(expertResults, axis: 0) + } } + +public class ExpertStreamerManager { + nonisolated(unsafe) public static var shared: ExpertStreamerManager? + + public let weightMap: [String: String] + + public init(modelDirectory: URL) { + var map = [String: String]() + let indexUrl = modelDirectory.appendingPathComponent("model.safetensors.index.json") + if let data = try? Data(contentsOf: indexUrl), + let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any], + let weightMapJson = json["weight_map"] as? [String: String] { + map = weightMapJson + } + self.weightMap = map + } + + public func getFile(for tensorName: String) -> String? { + return weightMap[tensorName] + } +} + +public final class SSDStreamMetrics: @unchecked Sendable { + public static let shared = SSDStreamMetrics() + private var totalBytes: Int = 0 + private var totalTimeNs: UInt64 = 0 + private var readCount: Int = 0 + private var lastLogTimeNs: UInt64 = DispatchTime.now().uptimeNanoseconds + private let lock = NSLock() + + public func record(bytes: Int, timeNs: UInt64) { + lock.lock() + defer { lock.unlock() } + totalBytes += bytes + totalTimeNs += timeNs + readCount += 1 + + let now = DispatchTime.now().uptimeNanoseconds + if now - lastLogTimeNs >= 1_000_000_000 { + let count = readCount + let bytes = totalBytes + let ns = totalTimeNs + + self.readCount = 0 + self.totalBytes = 0 + self.totalTimeNs = 0 + self.lastLogTimeNs = now + + if count > 0 { + // let mb = Double(bytes) / (1024.0 * 1024.0) + // let avgMs = (Double(ns) / 1_000_000.0) / Double(count) + // print(String(format: "[⚡️ SSD Stream] %.1f MB/s over %d chunks | Avg latency per chunk: %.6f ms", mb, count, avgMs)) + // fflush(stdout) + } + } + } +} + diff --git a/Libraries/MLXLMCommon/Tool/Parsers/Gemma4FunctionParser.swift b/Libraries/MLXLMCommon/Tool/Parsers/Gemma4FunctionParser.swift new file mode 100644 index 0000000000..a454d95615 --- /dev/null +++ b/Libraries/MLXLMCommon/Tool/Parsers/Gemma4FunctionParser.swift @@ -0,0 +1,77 @@ +// Copyright © 2025 Apple Inc. + +import Foundation + +/// Parser for Gemma 4 format: <|tool_call>call:name{key:<|"|>value<|"|>} +/// Reference: Gemma 4 native format +public struct Gemma4FunctionParser: ToolCallParser, Sendable { + public let startTag: String? = "<|tool_call>" + public let endTag: String? = "" + + private let escapeMarker = "<|\"|>" + + public init() {} + + public func parse(content: String, tools: [[String: any Sendable]]?) -> ToolCall? { + // Strip tags if present + var text = content + if let start = startTag { + text = text.replacingOccurrences(of: start, with: "") + } + if let end = endTag { + text = text.replacingOccurrences(of: end, with: "") + } + + // Pattern: call:(\w+)\{(.*?)\} + // Find "call:" followed by function name and arguments in braces + guard let callRange = text.range(of: "call:") else { return nil } + + let remaining = String(text[callRange.upperBound...]) + + // Extract function name (word characters until {) + guard let braceStart = remaining.firstIndex(of: "{") else { return nil } + let funcName = String(remaining[..str}` case gemma + /// Gemma 4 function call format. + /// Example: `<|tool_call>call:name{key:<|"|>value<|"|>}` + case gemma4 + /// Kimi K2 format with functions prefix. /// Example: `functions.name:0<|tool_call_argument_begin|>{"key": "value"}` case kimiK2 = "kimi_k2" @@ -111,6 +115,8 @@ public enum ToolCallFormat: String, Sendable, Codable, CaseIterable { return GLM4ToolCallParser() case .gemma: return GemmaFunctionParser() + case .gemma4: + return Gemma4FunctionParser() case .kimiK2: return KimiK2ToolCallParser() case .minimaxM2: @@ -140,8 +146,10 @@ public enum ToolCallFormat: String, Sendable, Codable, CaseIterable { return .glm4 } - // Gemma - if type == "gemma" { + // Gemma / Gemma 4 + if type.hasPrefix("gemma4") { + return .gemma4 + } else if type.hasPrefix("gemma") { return .gemma } diff --git a/Libraries/MLXLMCommon/Tool/ToolCallProcessor.swift b/Libraries/MLXLMCommon/Tool/ToolCallProcessor.swift index 6589952a6e..31487ba8dd 100644 --- a/Libraries/MLXLMCommon/Tool/ToolCallProcessor.swift +++ b/Libraries/MLXLMCommon/Tool/ToolCallProcessor.swift @@ -172,14 +172,20 @@ public class ToolCallProcessor { toolCallBuffer = "" // If the token contains the start character, there may be more tool calls to come + let nextOutput: String? if let trailingToken, let startChar = startTagFirstChar, trailingToken.contains(startChar) { - return processChunk(trailingToken) + nextOutput = processChunk(trailingToken) } else { // Otherwise, return the collected token, or nil if it's empty - return trailingToken?.isEmpty ?? true ? nil : trailingToken + nextOutput = trailingToken?.isEmpty ?? true ? nil : trailingToken } + + if let leading = leadingToken, !leading.isEmpty { + return leading + (nextOutput ?? "") + } + return nextOutput } else { return nil } diff --git a/Libraries/MLXVLM/MediaProcessing.swift b/Libraries/MLXVLM/MediaProcessing.swift index 0cd9a5b6db..0017ced8a7 100644 --- a/Libraries/MLXVLM/MediaProcessing.swift +++ b/Libraries/MLXVLM/MediaProcessing.swift @@ -13,7 +13,7 @@ public struct ProcessedFrames { public let totalDuration: CMTime } -private let context = CIContext() +nonisolated(unsafe) private let context = CIContext() /// Collection of methods for processing media (images, video, etc.). /// diff --git a/Libraries/MLXVLM/Models/Qwen35.swift b/Libraries/MLXVLM/Models/Qwen35.swift index 8a3c3984aa..29236f40dc 100644 --- a/Libraries/MLXVLM/Models/Qwen35.swift +++ b/Libraries/MLXVLM/Models/Qwen35.swift @@ -433,6 +433,24 @@ enum Qwen35Language { return (qOut, kOut) } + final class MathRMSNorm: Module, UnaryLayer { + @ParameterInfo(key: "weight") var weight: MLXArray + let eps: Float + init(dimensions: Int, eps: Float = 1e-6) { + self.eps = eps + _weight.wrappedValue = MLXArray.ones([dimensions]) + super.init() + } + func callAsFunction(_ hiddenStates: MLXArray) -> MLXArray { + let isCPU = Device.defaultDevice().deviceType == .cpu + if isCPU { + let variance = mean(square(hiddenStates), axis: -1, keepDims: true) + return (hiddenStates * rsqrt(variance + eps)) * weight + } + return MLXFast.rmsNorm(hiddenStates, weight: weight, eps: eps) + } + } + final class RMSNormGated: Module { @ParameterInfo(key: "weight") var weight: MLXArray let eps: Float @@ -444,7 +462,14 @@ enum Qwen35Language { } func callAsFunction(_ hiddenStates: MLXArray, gate: MLXArray? = nil) -> MLXArray { - var x = MLXFast.rmsNorm(hiddenStates, weight: weight, eps: eps) + var x: MLXArray + let isCPU = Device.defaultDevice().deviceType == .cpu + if isCPU { + let variance = mean(square(hiddenStates), axis: -1, keepDims: true) + x = (hiddenStates * rsqrt(variance + eps)) * weight + } else { + x = MLXFast.rmsNorm(hiddenStates, weight: weight, eps: eps) + } if let gate { x = x * silu(gate) } @@ -463,8 +488,8 @@ enum Qwen35Language { @ModuleInfo(key: "v_proj") var vProj: Linear @ModuleInfo(key: "o_proj") var oProj: Linear - @ModuleInfo(key: "q_norm") var qNorm: RMSNorm - @ModuleInfo(key: "k_norm") var kNorm: RMSNorm + @ModuleInfo(key: "q_norm") var qNorm: MathRMSNorm + @ModuleInfo(key: "k_norm") var kNorm: MathRMSNorm let rotaryEmbedding: RotaryEmbedding @@ -483,8 +508,8 @@ enum Qwen35Language { _oProj.wrappedValue = Linear( numAttentionHeads * headDim, args.hiddenSize, bias: args.attentionBias) - _qNorm.wrappedValue = RMSNorm(dimensions: headDim, eps: args.rmsNormEps) - _kNorm.wrappedValue = RMSNorm(dimensions: headDim, eps: args.rmsNormEps) + _qNorm.wrappedValue = MathRMSNorm(dimensions: headDim, eps: args.rmsNormEps) + _kNorm.wrappedValue = MathRMSNorm(dimensions: headDim, eps: args.rmsNormEps) let mrope = args.ropeParameters?["mrope_section"]?.asInts() ?? [11, 11, 10] let rotaryDim = Int(Float(headDim) * args.partialRotaryFactor) @@ -761,8 +786,8 @@ enum Qwen35Language { @ModuleInfo(key: "self_attn") var selfAttn: Attention? @ModuleInfo(key: "linear_attn") var linearAttn: GatedDeltaNet? - @ModuleInfo(key: "input_layernorm") var inputLayerNorm: RMSNorm - @ModuleInfo(key: "post_attention_layernorm") var postAttentionLayerNorm: RMSNorm + @ModuleInfo(key: "input_layernorm") var inputLayerNorm: MathRMSNorm + @ModuleInfo(key: "post_attention_layernorm") var postAttentionLayerNorm: MathRMSNorm @ModuleInfo(key: "mlp") var mlp: Module @@ -782,9 +807,9 @@ enum Qwen35Language { dimensions: args.hiddenSize, hiddenDimensions: args.intermediateSize) } - _inputLayerNorm.wrappedValue = RMSNorm( + _inputLayerNorm.wrappedValue = MathRMSNorm( dimensions: args.hiddenSize, eps: args.rmsNormEps) - _postAttentionLayerNorm.wrappedValue = RMSNorm( + _postAttentionLayerNorm.wrappedValue = MathRMSNorm( dimensions: args.hiddenSize, eps: args.rmsNormEps) super.init() @@ -810,14 +835,21 @@ enum Qwen35Language { } } - final class Model: Module { + final class Model: Module, LayerPartitionable, StreamableMoE { @ModuleInfo(key: "embed_tokens") var embedTokens: Embedding @ModuleInfo(key: "layers") fileprivate var layers: [DecoderLayer] - @ModuleInfo(key: "norm") var norm: RMSNorm + @ModuleInfo(key: "norm") var norm: MathRMSNorm let ssmIdx: Int let faIdx: Int + // LayerPartitionable + public var gpuLayerCount: Int? + public var totalLayerCount: Int { layers.count } + + // StreamableMoE + public var streamExperts: Bool = false + init(_ args: Qwen35Configuration.TextConfiguration) { precondition(args.vocabularySize > 0) _embedTokens.wrappedValue = Embedding( @@ -825,7 +857,7 @@ enum Qwen35Language { _layers.wrappedValue = (0 ..< args.hiddenLayers).map { DecoderLayer(args, layerIdx: $0) } - _norm.wrappedValue = RMSNorm(dimensions: args.hiddenSize, eps: args.rmsNormEps) + _norm.wrappedValue = MathRMSNorm(dimensions: args.hiddenSize, eps: args.rmsNormEps) self.ssmIdx = 0 self.faIdx = args.fullAttentionInterval - 1 @@ -862,13 +894,15 @@ enum Qwen35Language { for (index, layer) in layers.enumerated() { let layerSSMMask = layer.isLinear ? ssmMask : nil - hiddenStates = layer( - hiddenStates, - attentionMask: faMask, - ssmMask: layerSSMMask, - cache: cacheArray?[index], - positionIds: positionIds - ) + hiddenStates = partitionedLayerCall(index: index, gpuLayerCount: gpuLayerCount, stream: streamExperts) { + layer( + hiddenStates, + attentionMask: faMask, + ssmMask: layerSSMMask, + cache: cacheArray?[index], + positionIds: positionIds + ) + } } return norm(hiddenStates) diff --git a/Libraries/MLXVLM/VLMModelFactory.swift b/Libraries/MLXVLM/VLMModelFactory.swift index 64cee4494e..6e925d66b9 100644 --- a/Libraries/MLXVLM/VLMModelFactory.swift +++ b/Libraries/MLXVLM/VLMModelFactory.swift @@ -343,7 +343,8 @@ public final class VLMModelFactory: ModelFactory { try loadWeights( modelDirectory: modelDirectory, model: model, - perLayerQuantization: baseConfig.perLayerQuantization) + perLayerQuantization: baseConfig.perLayerQuantization, + lazyLoad: configuration.lazyLoad) let tokenizer = try await tokenizerTask let processorConfigData: Data diff --git a/Package.swift b/Package.swift index 8dcf54c517..a55ac05079 100644 --- a/Package.swift +++ b/Package.swift @@ -36,7 +36,11 @@ let package = Package( targets: ["IntegrationTestHelpers"]), ], dependencies: [ - .package(url: "https://github.com/ml-explore/mlx-swift", .upToNextMinor(from: "0.31.3")), + .package(url: "https://github.com/SharpAI/mlx-swift.git", branch: "main"), + .package( + url: "https://github.com/huggingface/swift-transformers", + .upToNextMinor(from: "1.2.0") + ), .package(url: "https://github.com/swiftlang/swift-syntax.git", from: "600.0.0-latest"), ], targets: [ diff --git a/scripts/debugging/Evaluate.swift.patch b/scripts/debugging/Evaluate.swift.patch new file mode 100644 index 0000000000..bcc6bbf6d4 --- /dev/null +++ b/scripts/debugging/Evaluate.swift.patch @@ -0,0 +1,17 @@ +--- mlx-swift-lm/Libraries/MLXLMCommon/Evaluate.swift ++++ mlx-swift-lm/Libraries/MLXLMCommon/Evaluate.swift +@@ -53,6 +53,15 @@ + + // generate the stream of results + let stream = try generate( + prompt: Array(tokens), model: model, temp: temp, + topP: topP, repetitionPenalty: repetitionPenalty, repetitionContextSize: repetitionContextSize + ) ++ ++ if let gemma4 = model.model as? MLXLLM.Gemma4Model { ++ let layer0 = gemma4.model.layers[0] ++ print("DEBUG WEIGHTS Layer 0:") ++ print("post1:", layer0.postFeedforwardLayerNorm1?.weight.max().item(Float.self) ?? "NIL") ++ print("pre2:", layer0.preFeedforwardLayerNorm2?.weight.max().item(Float.self) ?? "NIL") ++ print("post2:", layer0.postFeedforwardLayerNorm2?.weight.max().item(Float.self) ?? "NIL") ++ } diff --git a/scripts/debugging/patch.swift b/scripts/debugging/patch.swift new file mode 100644 index 0000000000..fecc4ab449 --- /dev/null +++ b/scripts/debugging/patch.swift @@ -0,0 +1 @@ +import Foundation diff --git a/scripts/debugging/test_moe.swift b/scripts/debugging/test_moe.swift new file mode 100644 index 0000000000..1b69ce3b33 --- /dev/null +++ b/scripts/debugging/test_moe.swift @@ -0,0 +1,29 @@ +import Foundation +import MLX +import MLXLLM +import MLXLMCommon + +@main +struct TestMoE { + static func main() async throws { + let config = ModelConfiguration(id: "mlx-community/gemma-4-26b-a4b-it-4bit") + let modelContainer = try await LLMModelFactory.shared.loadContainer(from: HubClient.default, using: TokenizersLoader(), configuration: config) + let context = try await modelContainer.context() + let prompt = "What is 2+2?" + let tokens = context.tokenizer.encode(text: prompt) + print("Prompt tokens:", tokens) + + let input = MLXArray(tokens).reshaped(1, -1) + MLX.eval(input) + + if let gemma4 = context.model as? Gemma4Model { + print("Successfully cast to Gemma4Model!") + let logits = gemma4(input, cache: nil) + MLX.eval(logits) + let logitsF32 = logits.asType(.float32) + print("Logits shape:", logitsF32.shape) + print("Max index:", MLX.argMax(logitsF32, axis: -1).item(Int.self)) + print("Max prob:", MLX.max(logitsF32).item(Float.self)) + } + } +}