From 7ad51df775d1f2d909f4543b2650d44167d1a0e4 Mon Sep 17 00:00:00 2001 From: TheTom Date: Tue, 21 Apr 2026 11:09:55 -0500 Subject: [PATCH] fix Gemma 4 MoE router -- softmax order + fuse norm dispatches Softmax was applied to all 128 expert scores before top-k selection, so selected weights came from the full distribution rather than just the top-k. Moved softmax to after selection so it operates only on the chosen experts. Drops the renormalization step since softmax on top-k already produces a valid distribution. Also fuses norm + scale from 3 dispatches into one MLXFast.rmsNorm call. --- Libraries/MLXVLM/Models/Gemma4.swift | 20 +++++++++----------- 1 file changed, 9 insertions(+), 11 deletions(-) diff --git a/Libraries/MLXVLM/Models/Gemma4.swift b/Libraries/MLXVLM/Models/Gemma4.swift index cac757f98d..b2cc6c6a8a 100644 --- a/Libraries/MLXVLM/Models/Gemma4.swift +++ b/Libraries/MLXVLM/Models/Gemma4.swift @@ -499,9 +499,9 @@ private final class Gemma4TextMLP: Module, UnaryLayer { private final class Gemma4TextRouter: Module { let topKExperts: Int + let config: Gemma4TextConfiguration private let rootSize: Float - @ModuleInfo(key: "norm") var norm: Gemma4RMSNormNoScale @ModuleInfo(key: "proj") var proj: Linear @ParameterInfo(key: "scale") var scale: MLXArray @ParameterInfo(key: "per_expert_scale") var perExpertScale: MLXArray @@ -512,9 +512,9 @@ private final class Gemma4TextRouter: Module { } self.topKExperts = topKExperts + self.config = config self.rootSize = pow(Float(config.hiddenSize), -0.5) - self._norm.wrappedValue = Gemma4RMSNormNoScale(eps: config.rmsNormEps) self._proj.wrappedValue = Linear(config.hiddenSize, numExperts, bias: false) self._scale.wrappedValue = MLXArray.ones([config.hiddenSize]) self._perExpertScale.wrappedValue = MLXArray.ones([numExperts]) @@ -522,18 +522,16 @@ private final class Gemma4TextRouter: Module { } func callAsFunction(_ x: MLXArray) -> (MLXArray, MLXArray) { - var x = norm(x) - x = x * MLXArray(rootSize, dtype: x.dtype) - x = x * scale.asType(x.dtype) + let normed = MLXFast.rmsNorm( + x, weight: (scale * rootSize).asType(x.dtype), eps: config.rmsNormEps) - let expertScores = proj(x) - let routerProbabilities = MLX.softmax(expertScores, axis: -1, precise: true) + let scores = proj(normed) - let topKIndices = MLX.argPartition(-expertScores, kth: topKExperts - 1, axis: -1)[ - .ellipsis, ..