From 6aa0023f83408837b06108695bd9ea2a75b05935 Mon Sep 17 00:00:00 2001 From: Aegis AI Assistant Date: Tue, 7 Apr 2026 23:51:28 -0700 Subject: [PATCH 1/6] Add GLMMoeDSA.swift stub --- Libraries/MLXLLM/Models/GLMMoeDSA.swift | 143 ++++++++++++++++++++++++ 1 file changed, 143 insertions(+) create mode 100644 Libraries/MLXLLM/Models/GLMMoeDSA.swift diff --git a/Libraries/MLXLLM/Models/GLMMoeDSA.swift b/Libraries/MLXLLM/Models/GLMMoeDSA.swift new file mode 100644 index 0000000000..afd37af349 --- /dev/null +++ b/Libraries/MLXLLM/Models/GLMMoeDSA.swift @@ -0,0 +1,143 @@ +// +// GLMMoeDSA.swift +// LLM +// +// Created for GLM-5.1 (glm_moe_dsa) support. +// + +import Foundation +import MLX +import MLXLMCommon +import MLXNN + +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 = "indexer_n_heads" + case indexerHeadDim = "indexer_head_dim" + case indexerTopk = "indexer_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 = try decoder.container(keyedBy: CodingKeys.self) + + // Defaults + Extraction + 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.decodeIfPresent(Int.self, forKey: .intermediateSize) ?? 0 + self.moeIntermediateSize = try container.decodeIfPresent(Int.self, forKey: .moeIntermediateSize) ?? 0 + self.hiddenLayers = try container.decode(Int.self, forKey: .hiddenLayers) + self.attentionHeads = try container.decode(Int.self, forKey: .attentionHeads) + self.kvHeads = try container.decodeIfPresent(Int.self, forKey: .kvHeads) ?? 1 + + self.nSharedExperts = try container.decodeIfPresent(Int.self, forKey: .nSharedExperts) + self.nRoutedExperts = try container.decodeIfPresent(Int.self, forKey: .nRoutedExperts) + self.routedScalingFactor = try container.decodeIfPresent(Float.self, forKey: .routedScalingFactor) ?? 1.0 + self.kvLoraRank = try container.decodeIfPresent(Int.self, forKey: .kvLoraRank) ?? 512 + self.qLoraRank = try container.decodeIfPresent(Int.self, forKey: .qLoraRank) + self.qkRopeHeadDim = try container.decodeIfPresent(Int.self, forKey: .qkRopeHeadDim) ?? 64 + self.qkNopeHeadDim = try container.decodeIfPresent(Int.self, forKey: .qkNopeHeadDim) ?? 128 + self.vHeadDim = try container.decodeIfPresent(Int.self, forKey: .vHeadDim) ?? 128 + + self.indexerNHeads = try container.decodeIfPresent(Int.self, forKey: .indexerNHeads) + self.indexerHeadDim = try container.decodeIfPresent(Int.self, forKey: .indexerHeadDim) + self.indexerTopk = try container.decodeIfPresent(Int.self, forKey: .indexerTopk) + self.indexerRopeInterleave = try container.decodeIfPresent(Bool.self, forKey: .indexerRopeInterleave) + + self.topkMethod = try container.decodeIfPresent(String.self, forKey: .topkMethod) + self.scoringFunc = try container.decodeIfPresent(String.self, forKey: .scoringFunc) + self.normTopkProb = try container.decodeIfPresent(Bool.self, forKey: .normTopkProb) + self.nGroup = try container.decodeIfPresent(Int.self, forKey: .nGroup) + self.topkGroup = try container.decodeIfPresent(Int.self, forKey: .topkGroup) + self.numExpertsPerTok = try container.decodeIfPresent(Int.self, forKey: .numExpertsPerTok) + self.moeLayerFreq = try container.decodeIfPresent(Int.self, forKey: .moeLayerFreq) + self.firstKDenseReplace = try container.decodeIfPresent(Int.self, forKey: .firstKDenseReplace) + 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) + + self.attentionBias = try container.decodeIfPresent(Bool.self, forKey: .attentionBias) + self.attentionDropout = try container.decodeIfPresent(Float.self, forKey: .attentionDropout) + self.partialRotaryFactor = try container.decodeIfPresent(Float.self, forKey: .partialRotaryFactor) + self.tieWordEmbeddings = try container.decodeIfPresent(Bool.self, forKey: .tieWordEmbeddings) + self.numNextnPredictLayers = try container.decodeIfPresent(Int.self, forKey: .numNextnPredictLayers) + } +} From 321993b2c88e47f2ed17465851bb178c1efd9840 Mon Sep 17 00:00:00 2001 From: Aegis AI Assistant Date: Tue, 7 Apr 2026 23:52:17 -0700 Subject: [PATCH 2/6] Register GLMMoeDSA stub into factory on glm5.1 branch --- Libraries/MLXLLM/LLMModelFactory.swift | 1 + Libraries/MLXLLM/Models/GLMMoeDSA.swift | 38 +++++++++++++++++++++++++ 2 files changed, 39 insertions(+) diff --git a/Libraries/MLXLLM/LLMModelFactory.swift b/Libraries/MLXLLM/LLMModelFactory.swift index 2f57c9b45e..c2b8d321b8 100644 --- a/Libraries/MLXLLM/LLMModelFactory.swift +++ b/Libraries/MLXLLM/LLMModelFactory.swift @@ -54,6 +54,7 @@ public enum LLMTypeRegistry { "glm4": create(GLM4Configuration.self, GLM4Model.init), "glm4_moe": create(GLM4MoEConfiguration.self, GLM4MoEModel.init), "glm4_moe_lite": create(GLM4MoELiteConfiguration.self, GLM4MoELiteModel.init), + "glm_moe_dsa": create(GLMMoeDSAConfiguration.self, GLMMoeDSAModel.init), "acereason": create(Qwen2Configuration.self, Qwen2Model.init), "falcon_h1": create(FalconH1Configuration.self, FalconH1Model.init), "bitnet": create(BitnetConfiguration.self, BitnetModel.init), diff --git a/Libraries/MLXLLM/Models/GLMMoeDSA.swift b/Libraries/MLXLLM/Models/GLMMoeDSA.swift index afd37af349..03ebb8dc25 100644 --- a/Libraries/MLXLLM/Models/GLMMoeDSA.swift +++ b/Libraries/MLXLLM/Models/GLMMoeDSA.swift @@ -141,3 +141,41 @@ public struct GLMMoeDSAConfiguration: Codable, Sendable { self.numNextnPredictLayers = try container.decodeIfPresent(Int.self, forKey: .numNextnPredictLayers) } } + +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 class GLMMoeDSAModelInner: Module { + @ModuleInfo(key: "embed_tokens") var embedTokens: Embedding + let norm: RMSNorm + + init(_ config: GLMMoeDSAConfiguration) { + _embedTokens.wrappedValue = Embedding(embeddingCount: config.vocabularySize, dimensions: config.hiddenSize) + self.norm = RMSNorm(dimensions: config.hiddenSize, eps: config.rmsNormEps) + } + + func callAsFunction(_ inputs: MLXArray, cache: [KVCache]? = nil) -> MLXArray { + var h = embedTokens(inputs) + return norm(h) + } +} From c141cecedb82f2e129682bfd504d22b782b53fed Mon Sep 17 00:00:00 2001 From: Aegis AI Assistant Date: Tue, 7 Apr 2026 23:59:24 -0700 Subject: [PATCH 3/6] Implement GLMMoeDSA architecture via Dense MLA and drop indexer in sanitize --- Libraries/MLXLLM/Models/GLMMoeDSA.swift | 751 +++++++++++++++++++++--- 1 file changed, 658 insertions(+), 93 deletions(-) diff --git a/Libraries/MLXLLM/Models/GLMMoeDSA.swift b/Libraries/MLXLLM/Models/GLMMoeDSA.swift index 03ebb8dc25..5384648e8b 100644 --- a/Libraries/MLXLLM/Models/GLMMoeDSA.swift +++ b/Libraries/MLXLLM/Models/GLMMoeDSA.swift @@ -1,8 +1,9 @@ // -// GLMMoeDSA.swift +// GLM4MOELite.swift // LLM // -// Created for GLM-5.1 (glm_moe_dsa) support. +// 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 @@ -10,6 +11,599 @@ import MLX import MLXLMCommon import MLXNN +// MARK: - MultiLinear + +class MultiLinear: Module, Quantizable { + let inputDims: Int + let outputDims: Int + let numHeads: Int + + @ParameterInfo(key: "weight") var weight: MLXArray + + init(inputDims: Int, outputDims: Int, numHeads: Int) { + self.inputDims = inputDims + self.outputDims = outputDims + self.numHeads = numHeads + + let scale = sqrt(1.0 / Float(inputDims)) + _weight.wrappedValue = MLXRandom.uniform( + low: -scale, + high: scale, + [numHeads, outputDims, inputDims] + ) + super.init() + } + + func callAsFunction(_ x: MLXArray) -> MLXArray { + return x.matmul(weight.swappedAxes(-1, -2)) + } + + // MARK: - Quantizable conformance + + public func toQuantized(groupSize: Int, bits: Int, mode: QuantizationMode) -> Module { + return QuantizedMultiLinear( + weight: weight, + groupSize: groupSize, + bits: bits, + mode: mode + ) + } +} + +// MARK: - QuantizedMultiLinear + +/// Quantized version of MultiLinear that handles packed 4-bit weights. +/// This is the Swift equivalent of Python's QuantizedMultiLinear class (lines 89-129 in glm_moe_dsa.py). +class QuantizedMultiLinear: Module, Quantized { + public let groupSize: Int + public let bits: Int + public let mode: QuantizationMode + + @ParameterInfo(key: "weight") var weight: MLXArray + @ParameterInfo(key: "scales") var scales: MLXArray + @ParameterInfo(key: "biases") var biases: MLXArray? + + /// Initialize from non-quantized weights (for conversion from MultiLinear) + init( + weight: MLXArray, + groupSize: Int, + bits: Int, + mode: QuantizationMode = .affine + ) { + self.groupSize = groupSize + self.bits = bits + self.mode = mode + + let (quantizedWeight, scales, biases) = MLX.quantized( + weight, groupSize: groupSize, bits: bits, mode: mode + ) + _weight.wrappedValue = quantizedWeight + _scales.wrappedValue = scales + _biases.wrappedValue = biases + + super.init() + self.freeze() + } + + /// Initialize with pre-quantized weights and scales (for loading from file) + init( + weight: MLXArray, + scales: MLXArray, + biases: MLXArray?, + groupSize: Int, + bits: Int, + mode: QuantizationMode = .affine + ) { + self.groupSize = groupSize + self.bits = bits + self.mode = mode + + _weight.wrappedValue = weight + _scales.wrappedValue = scales + _biases.wrappedValue = biases + + super.init() + self.freeze() + } + + func callAsFunction(_ x: MLXArray) -> MLXArray { + // Use quantizedMM for efficient quantized matrix multiplication + // The weight is in shape [numHeads, outputDims, inputDims(packed)] + return quantizedMM( + x, + weight, + scales: scales, + biases: biases, + transpose: true, + groupSize: groupSize, + bits: bits, + mode: mode + ) + } +} + +// MARK: - Attention + +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 @@ -27,30 +621,24 @@ public struct GLMMoeDSAConfiguration: Codable, Sendable { 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 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 ropeTheta: Float var ropeScaling: [String: StringOrNumber]? - var ropeTraditional: Bool? - var attentionBias: Bool? - var attentionDropout: Float? - var partialRotaryFactor: Float? - var tieWordEmbeddings: Bool? - var numNextnPredictLayers: Int? + 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" @@ -69,12 +657,10 @@ public struct GLMMoeDSAConfiguration: Codable, Sendable { case qkRopeHeadDim = "qk_rope_head_dim" case qkNopeHeadDim = "qk_nope_head_dim" case vHeadDim = "v_head_dim" - - case indexerNHeads = "indexer_n_heads" - case indexerHeadDim = "indexer_head_dim" - case indexerTopk = "indexer_topk" + case indexNHeads = "index_n_heads" + case indexHeadDim = "index_head_dim" + case indexTopk = "index_topk" case indexerRopeInterleave = "indexer_rope_interleave" - case topkMethod = "topk_method" case scoringFunc = "scoring_func" case normTopkProb = "norm_topk_prob" @@ -96,86 +682,65 @@ public struct GLMMoeDSAConfiguration: Codable, Sendable { } public init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - - // Defaults + Extraction + 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.decodeIfPresent(Int.self, forKey: .intermediateSize) ?? 0 - self.moeIntermediateSize = try container.decodeIfPresent(Int.self, forKey: .moeIntermediateSize) ?? 0 + 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.decodeIfPresent(Int.self, forKey: .kvHeads) ?? 1 - + 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.decodeIfPresent(Float.self, forKey: .routedScalingFactor) ?? 1.0 - self.kvLoraRank = try container.decodeIfPresent(Int.self, forKey: .kvLoraRank) ?? 512 + 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.decodeIfPresent(Int.self, forKey: .qkRopeHeadDim) ?? 64 - self.qkNopeHeadDim = try container.decodeIfPresent(Int.self, forKey: .qkNopeHeadDim) ?? 128 - self.vHeadDim = try container.decodeIfPresent(Int.self, forKey: .vHeadDim) ?? 128 + 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) - self.indexerNHeads = try container.decodeIfPresent(Int.self, forKey: .indexerNHeads) - self.indexerHeadDim = try container.decodeIfPresent(Int.self, forKey: .indexerHeadDim) - self.indexerTopk = try container.decodeIfPresent(Int.self, forKey: .indexerTopk) - self.indexerRopeInterleave = try container.decodeIfPresent(Bool.self, forKey: .indexerRopeInterleave) + // Optional indexer params + _ = try container.decodeIfPresent(Int.self, forKey: .indexNHeads) + _ = try container.decodeIfPresent(Int.self, forKey: .indexHeadDim) + _ = try container.decodeIfPresent(Int.self, forKey: .indexTopk) + _ = try container.decodeIfPresent(Bool.self, forKey: .indexerRopeInterleave) - self.topkMethod = try container.decodeIfPresent(String.self, forKey: .topkMethod) - self.scoringFunc = try container.decodeIfPresent(String.self, forKey: .scoringFunc) - self.normTopkProb = try container.decodeIfPresent(Bool.self, forKey: .normTopkProb) - self.nGroup = try container.decodeIfPresent(Int.self, forKey: .nGroup) - self.topkGroup = try container.decodeIfPresent(Int.self, forKey: .topkGroup) - self.numExpertsPerTok = try container.decodeIfPresent(Int.self, forKey: .numExpertsPerTok) - self.moeLayerFreq = try container.decodeIfPresent(Int.self, forKey: .moeLayerFreq) - self.firstKDenseReplace = try container.decodeIfPresent(Int.self, forKey: .firstKDenseReplace) + 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) - - self.attentionBias = try container.decodeIfPresent(Bool.self, forKey: .attentionBias) - self.attentionDropout = try container.decodeIfPresent(Float.self, forKey: .attentionDropout) - self.partialRotaryFactor = try container.decodeIfPresent(Float.self, forKey: .partialRotaryFactor) - self.tieWordEmbeddings = try container.decodeIfPresent(Bool.self, forKey: .tieWordEmbeddings) - self.numNextnPredictLayers = try container.decodeIfPresent(Int.self, forKey: .numNextnPredictLayers) + 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 } } -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 +// MARK: - LoRA - 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 class GLMMoeDSAModelInner: Module { - @ModuleInfo(key: "embed_tokens") var embedTokens: Embedding - let norm: RMSNorm - - init(_ config: GLMMoeDSAConfiguration) { - _embedTokens.wrappedValue = Embedding(embeddingCount: config.vocabularySize, dimensions: config.hiddenSize) - self.norm = RMSNorm(dimensions: config.hiddenSize, eps: config.rmsNormEps) - } - - func callAsFunction(_ inputs: MLXArray, cache: [KVCache]? = nil) -> MLXArray { - var h = embedTokens(inputs) - return norm(h) +extension GLMMoeDSAModel: LoRAModel { + public var loraLayers: [Module] { + model.layers } } From c40ed46ac771d632d6994062c5da078a950992c5 Mon Sep 17 00:00:00 2001 From: Aegis AI Assistant Date: Wed, 8 Apr 2026 00:00:41 -0700 Subject: [PATCH 4/6] Fix syntax and repoint dependency inside Package.swift --- Package.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Package.swift b/Package.swift index a55ac05079..6dfce07819 100644 --- a/Package.swift +++ b/Package.swift @@ -36,7 +36,7 @@ let package = Package( targets: ["IntegrationTestHelpers"]), ], dependencies: [ - .package(url: "https://github.com/SharpAI/mlx-swift.git", branch: "main"), + .package(path: "../mlx-swift"), .package( url: "https://github.com/huggingface/swift-transformers", .upToNextMinor(from: "1.2.0") From d9d4c82644c49209e69f7ee023ac7a22d48bd4f9 Mon Sep 17 00:00:00 2001 From: Aegis AI Assistant Date: Wed, 8 Apr 2026 00:09:55 -0700 Subject: [PATCH 5/6] Finalize GLM-5.1 MoE port with robust parameter filtering and integration test fix --- .../IntegrationTestHelpers.swift | 4 +- Libraries/MLXLLM/Models/GLMMoeDSA.swift | 135 ++---------------- 2 files changed, 15 insertions(+), 124 deletions(-) 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/Models/GLMMoeDSA.swift b/Libraries/MLXLLM/Models/GLMMoeDSA.swift index 5384648e8b..9f63e66bc1 100644 --- a/Libraries/MLXLLM/Models/GLMMoeDSA.swift +++ b/Libraries/MLXLLM/Models/GLMMoeDSA.swift @@ -11,118 +11,6 @@ import MLX import MLXLMCommon import MLXNN -// MARK: - MultiLinear - -class MultiLinear: Module, Quantizable { - let inputDims: Int - let outputDims: Int - let numHeads: Int - - @ParameterInfo(key: "weight") var weight: MLXArray - - init(inputDims: Int, outputDims: Int, numHeads: Int) { - self.inputDims = inputDims - self.outputDims = outputDims - self.numHeads = numHeads - - let scale = sqrt(1.0 / Float(inputDims)) - _weight.wrappedValue = MLXRandom.uniform( - low: -scale, - high: scale, - [numHeads, outputDims, inputDims] - ) - super.init() - } - - func callAsFunction(_ x: MLXArray) -> MLXArray { - return x.matmul(weight.swappedAxes(-1, -2)) - } - - // MARK: - Quantizable conformance - - public func toQuantized(groupSize: Int, bits: Int, mode: QuantizationMode) -> Module { - return QuantizedMultiLinear( - weight: weight, - groupSize: groupSize, - bits: bits, - mode: mode - ) - } -} - -// MARK: - QuantizedMultiLinear - -/// Quantized version of MultiLinear that handles packed 4-bit weights. -/// This is the Swift equivalent of Python's QuantizedMultiLinear class (lines 89-129 in glm_moe_dsa.py). -class QuantizedMultiLinear: Module, Quantized { - public let groupSize: Int - public let bits: Int - public let mode: QuantizationMode - - @ParameterInfo(key: "weight") var weight: MLXArray - @ParameterInfo(key: "scales") var scales: MLXArray - @ParameterInfo(key: "biases") var biases: MLXArray? - - /// Initialize from non-quantized weights (for conversion from MultiLinear) - init( - weight: MLXArray, - groupSize: Int, - bits: Int, - mode: QuantizationMode = .affine - ) { - self.groupSize = groupSize - self.bits = bits - self.mode = mode - - let (quantizedWeight, scales, biases) = MLX.quantized( - weight, groupSize: groupSize, bits: bits, mode: mode - ) - _weight.wrappedValue = quantizedWeight - _scales.wrappedValue = scales - _biases.wrappedValue = biases - - super.init() - self.freeze() - } - - /// Initialize with pre-quantized weights and scales (for loading from file) - init( - weight: MLXArray, - scales: MLXArray, - biases: MLXArray?, - groupSize: Int, - bits: Int, - mode: QuantizationMode = .affine - ) { - self.groupSize = groupSize - self.bits = bits - self.mode = mode - - _weight.wrappedValue = weight - _scales.wrappedValue = scales - _biases.wrappedValue = biases - - super.init() - self.freeze() - } - - func callAsFunction(_ x: MLXArray) -> MLXArray { - // Use quantizedMM for efficient quantized matrix multiplication - // The weight is in shape [numHeads, outputDims, inputDims(packed)] - return quantizedMM( - x, - weight, - scales: scales, - biases: biases, - transpose: true, - groupSize: groupSize, - bits: bits, - mode: mode - ) - } -} - -// MARK: - Attention class GLMMoeDSAAttention: Module { let config: GLMMoeDSAConfiguration @@ -582,10 +470,9 @@ public class GLMMoeDSAModel: Module, LLMModel, KVCacheDimensionProvider { } // Drop DSA indexer parameters since SwiftLM currently evaluates via dense MLA for streaming compatibility - sanitized.removeValue(forKey: "\(attnPrefix).indexer.wk.weight") - sanitized.removeValue(forKey: "\(attnPrefix).indexer.wq_b.weight") - sanitized.removeValue(forKey: "\(attnPrefix).indexer.weights_proj.weight") - sanitized.removeValue(forKey: "\(attnPrefix).indexer.k_norm.weight") + sanitized = sanitized.filter { key, _ in + !key.hasPrefix("\(attnPrefix).indexer.") + } } let numMptLayers = configuration.numNextnPredictLayers @@ -621,6 +508,10 @@ public struct GLMMoeDSAConfiguration: Codable, Sendable { 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 @@ -657,9 +548,9 @@ public struct GLMMoeDSAConfiguration: Codable, Sendable { case qkRopeHeadDim = "qk_rope_head_dim" case qkNopeHeadDim = "qk_nope_head_dim" case vHeadDim = "v_head_dim" - case indexNHeads = "index_n_heads" - case indexHeadDim = "index_head_dim" - case indexTopk = "index_topk" + 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" @@ -703,9 +594,9 @@ public struct GLMMoeDSAConfiguration: Codable, Sendable { self.vHeadDim = try container.decode(Int.self, forKey: .vHeadDim) // Optional indexer params - _ = try container.decodeIfPresent(Int.self, forKey: .indexNHeads) - _ = try container.decodeIfPresent(Int.self, forKey: .indexHeadDim) - _ = try container.decodeIfPresent(Int.self, forKey: .indexTopk) + _ = 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 = From 2b1c653db075848c8c5dd9b3c724e6712b2e5ca3 Mon Sep 17 00:00:00 2001 From: Aegis AI Assistant Date: Wed, 8 Apr 2026 17:06:35 -0700 Subject: [PATCH 6/6] feat: permanently disable PAPPS N+1 heuristic to restore native Apple TPS --- Libraries/MLXLMCommon/SwitchLayers.swift | 28 +++++++++++++++++------- 1 file changed, 20 insertions(+), 8 deletions(-) diff --git a/Libraries/MLXLMCommon/SwitchLayers.swift b/Libraries/MLXLMCommon/SwitchLayers.swift index 11a1f824d7..e4d7dccbcb 100644 --- a/Libraries/MLXLMCommon/SwitchLayers.swift +++ b/Libraries/MLXLMCommon/SwitchLayers.swift @@ -222,16 +222,16 @@ public class QuantizedSwitchLinear: SwitchLinear, Quantized { let readStart = DispatchTime.now().uptimeNanoseconds let expertWeight: MLXArray if let info = ssdInfo { - // macOS directNVMe: pread() at ~5 GB/s, loads the quantized weight from SSD. - // The result is the raw weight tensor — same role as self.weight[expert..