diff --git a/Libraries/MLXLLM/Models/Gemma4Text.swift b/Libraries/MLXLLM/Models/Gemma4Text.swift index bdc5dfd55e..c0d2f3faf5 100644 --- a/Libraries/MLXLLM/Models/Gemma4Text.swift +++ b/Libraries/MLXLLM/Models/Gemma4Text.swift @@ -9,6 +9,45 @@ import MLX import MLXLMCommon import MLXNN +// MARK: - vMLX decode hot-path helpers (ported from osaurus/main Gemma4Text) +// +// File-private, self-contained compiled fusions. They do NOT depend on the +// SwitchLayers / HardwareInfo lane so this file builds stand-alone; when that +// lane lands public `safeGeluApproximate` / `MLXHardwareInfo` these can collapse +// to the shared symbols (identical math + same env knob) with no behavior change. +// `compile(shapeless: true)` is gated by `MLX_COMPILED_DECODE` (default on), +// mirroring `MLXHardwareInfo.isCompiledDecodeSupported`, so M1/M2 + macOS Tahoe +// (MLX #3329) can opt out without a code change. Matches the ungated +// `compiledSiluProduct` / `weightedExpertSum` convention already in this tree. +private let gemma4CompiledDecodeSupported: Bool = { + if let raw = ProcessInfo.processInfo.environment["MLX_COMPILED_DECODE"] { + return ["1", "true", "yes", "on"].contains(raw.lowercased()) + } + return true +}() + +/// Approximate (tanh) GELU written with `x * x * x` instead of the Power +/// primitive (`x ** 3`) so it is safe under `compile(shapeless: true)` — the +/// Power primitive returns zero results on the Tahoe Metal JIT (MLX #3329). +/// Numerically identical to `MLXNN.geluApproximate` (vMLX `safeGeluApproximate`). +private let gemma4SafeGeluApproximate: @Sendable (MLXArray) -> MLXArray = { + let body: @Sendable (MLXArray) -> MLXArray = { (x: MLXArray) -> MLXArray in + 0.5 * x * (1 + tanh(sqrt(2 / Float.pi) * (x + 0.044715 * x * x * x))) + } + return gemma4CompiledDecodeSupported ? compile(shapeless: true, body) : body +}() + +/// Final-logit softcap (`tanh(x / cap) * cap`) fused into one Metal dispatch +/// (vMLX `compiledLogitSoftcap`). The untyped (float32) cap keeps the softcap +/// math — and the logits handed to the sampler — full precision. +private let gemma4CompiledLogitSoftcap: @Sendable (MLXArray, MLXArray) -> MLXArray = { + let body: @Sendable (MLXArray, MLXArray) -> MLXArray = { + (x: MLXArray, cap: MLXArray) -> MLXArray in + tanh(x / cap) * cap + } + return gemma4CompiledDecodeSupported ? compile(shapeless: true, body) : body +}() + // MARK: - Configuration struct Gemma4WeightQuantizationMetadata: Codable, Sendable { @@ -573,7 +612,7 @@ private class Gemma4Experts: Module { inputDims: config.hiddenSize, hiddenDims: moeIntermediate, numExperts: numExperts, - activation: { geluApproximate($0) }, + activation: { gemma4SafeGeluApproximate($0) }, bias: false ) super.init() @@ -582,9 +621,15 @@ private class Gemma4Experts: Module { func callAsFunction( _ x: MLXArray, topKIndices: MLXArray, topKWeights: MLXArray ) -> MLXArray { - let w = MLX.expandedDimensions(topKWeights, axis: -1) - let y = switchGLU(x, topKIndices) - return (w * y).sum(axis: -2) + // Flatten [B, S, H] -> [B*S, H] (and indices/weights to [B*S, K]) so + // SwitchGLU runs its optimized 2D gather/sort path, then fuse the + // per-expert scale + reduce via the shared compiled `weightedExpertSum` + // and reshape back. Numerically identical to the prior + // `(expandDims(weights, -1) * switchGLU(x, idx)).sum(-2)`; matches vMLX. + let (B, S, H) = (x.dim(0), x.dim(1), x.dim(2)) + let K = topKIndices.dim(-1) + let y = switchGLU(x.reshaped(B * S, H), topKIndices.reshaped(B * S, K)) + return weightedExpertSum(y, topKWeights.reshaped(B * S, K)).reshaped(B, S, H) } } @@ -608,7 +653,7 @@ private class Gemma4MLP: Module { } func callAsFunction(_ x: MLXArray) -> MLXArray { - downProj(geluApproximate(gateProj(x)) * upProj(x)) + downProj(gemma4SafeGeluApproximate(gateProj(x)) * upProj(x)) } } @@ -746,7 +791,7 @@ public class Gemma4DecoderLayer: Module { { let residual3 = out var g = gate(out) - g = geluApproximate(g) + g = gemma4SafeGeluApproximate(g) g = g * perLayerInput g = proj(g) g = norm(g) @@ -1008,7 +1053,10 @@ public class Gemma4TextModel: Module, LLMModel, KVCacheDimensionProvider { } else { out = model.embedTokens.asLinear(hidden) } - out = tanh(out / config.finalLogitSoftcapping) * config.finalLogitSoftcapping + // Fused tanh-softcap (vMLX `compiledLogitSoftcap`). Untyped (float32) cap + // keeps the softcap math + sampler logits full precision; when the compile + // gate is off this is equivalent to `tanh(out / cap) * cap`. + out = gemma4CompiledLogitSoftcap(out, MLXArray(config.finalLogitSoftcapping)) return out } diff --git a/Libraries/MLXLMCommon/CompilableKVCache.swift b/Libraries/MLXLMCommon/CompilableKVCache.swift new file mode 100644 index 0000000000..2bcd7562b8 --- /dev/null +++ b/Libraries/MLXLMCommon/CompilableKVCache.swift @@ -0,0 +1,255 @@ +// CompilableKVCache: Fixed-size KV cache using the Overflow Bin pattern. +// +// Ported from osaurus-ai/vmlx-swift-lm (Libraries/MLXLMCommon/CompilableKVCache.swift). +// This is the foundation type for whole-step compiled decode: it is the only +// full-attention cache whose `update()` is graph-traceable, so a decode step +// (model forward + cache write) can be captured by `compile(inputs:outputs:)`. +// +// Standard KVCacheSimple returns keys[..= 2 { + let existingKeys = existingState[0] // [B, H, seqLen, D] + let existingValues = existingState[1] + + let seqLen = existingKeys.dim(2) + let B = existingKeys.dim(0) + let H = existingKeys.dim(1) + let kD = existingKeys.dim(3) + let vD = existingValues.dim(3) + + // Pre-allocate to maxLength + self.keys = MLXArray.zeros([B, H, maxLength, kD], dtype: existingKeys.dtype) + self.values = MLXArray.zeros([B, H, maxLength, vD], dtype: existingValues.dtype) + + // Copy existing data at position 0 + self.keys![.ellipsis, .. [MLXArray] { + if let keys, let values { + return [keys, values, offsetArray] + } + return [offsetArray] + } + + public override func update(keys newKeys: MLXArray, values newValues: MLXArray) + -> (MLXArray, MLXArray) + { + let nTokens = newKeys.dim(2) + + // Lazy initialization on first call + if self.keys == nil { + let B = newKeys.dim(0) + let H = newKeys.dim(1) + let kD = newKeys.dim(3) + let vD = newValues.dim(3) + self.keys = MLXArray.zeros([B, H, maxLength, kD], dtype: newKeys.dtype) + self.values = MLXArray.zeros([B, H, maxLength, vD], dtype: newValues.dtype) + } + + let prev = offsetArray + let newOffset = prev + MLXArray([Int32(nTokens)]) + + // Must use _updateInternal to preserve object identity — compile() captures + // stateInputs at innerCall start and expects the same objects to be mutated. + self.keys!._updateInternal( + dynamicSliceUpdate(self.keys!, update: newKeys, start: prev, axes: [2])) + self.values!._updateInternal( + dynamicSliceUpdate(self.values!, update: newValues, start: prev, axes: [2])) + + self.offsetArray._updateInternal(newOffset) + + // OVERFLOW BIN: return the full static-size buffer. + // The attention mask from makeMask() handles which positions are valid. + // This keeps tensor shapes constant across all decode steps, + // enabling compile() to trace the entire forward pass. + return (self.keys!, self.values!) + } + + // MARK: - Mask (Overflow Bin) + + /// Generate attention mask for the full-buffer return. + /// + /// Since update() returns the entire maxLength buffer, we ALWAYS need an array + /// mask to prevent attention to unwritten positions. The mask is boolean: + /// True = attend, False = don't attend (gets -inf in attention scores). + /// + /// For decode (n=1): mask[0, j] = (j <= offset) + /// For prefill (n>1): mask[i, j] = (j <= offset + i) (causal) + /// + /// Note: `offset` here is the PRE-update value. After update, positions + /// 0.. MLXFast.ScaledDotProductAttentionMaskMode { + // Use offsetArray directly — compile-traceable, no .item() needed + let currentOffsetArr = offsetArray // MLXArray [1] int32 + + // Query positions: [offset, offset+1, ..., offset+n-1] + let linds: MLXArray + if n == 1 { + linds = currentOffsetArr.reshaped(1, 1) + } else { + linds = (MLXArray(Int32(0) ..< Int32(n)) + currentOffsetArr).reshaped(n, 1) + } + + // Key positions: [0, 1, ..., maxLength-1] + let rinds = maskRinds.reshaped(1, maxLength) + + // Causal + validity: attend to positions j where j <= query_position + var mask = linds .>= rinds + + // Apply sliding window if specified + if let windowSize { + let windowStart = linds - Int32(windowSize - 1) + mask = mask & (rinds .>= windowStart) + } + + return .array(mask) + } + + // MARK: - State + + public override var state: [MLXArray] { + get { + guard let keys, let values else { return [] } + let off: Int = offsetArray[0].item(Int.self) + if off == keys.dim(2) { + return [keys, values] + } else { + // Return only valid portion for serialization + return [ + keys[.ellipsis, .. Int { + let current: Int = offsetArray[0].item(Int.self) + let trimmed = min(current, n) + offsetArray = MLXArray([Int32(current - trimmed)]) + super.offset = current - trimmed + return trimmed + } + + public override func copy() -> any KVCache { + let c = CompilableKVCache(maxLength: maxLength, step: step) + c.keys = keys + c.values = values + c.offsetArray = offsetArray + return c + } + + // MARK: - Debug + + public var debugDescription: String { + "CompilableKVCache(offset=\(offset), maxLength=\(maxLength), " + + "shape=\(keys?.shape.description ?? "nil"))" + } +} diff --git a/Libraries/MLXLMCommon/CompiledDecode.swift b/Libraries/MLXLMCommon/CompiledDecode.swift new file mode 100644 index 0000000000..0242599bb3 --- /dev/null +++ b/Libraries/MLXLMCommon/CompiledDecode.swift @@ -0,0 +1,76 @@ +// CompiledDecode: whole-step compiled decode helper. +// +// Ported (trimmed) from osaurus-ai/vmlx-swift-lm +// (Libraries/MLXLMCommon/BatchEngine/BatchCompile.swift `compileForward`). +// +// This wraps MLX `compile(inputs:outputs:)` so a single decode step — the model +// forward plus the per-layer KV-cache write — is captured as one compiled graph, +// collapsing hundreds of FFI crossings into a single compiled call. The tracer +// captures each cache layer's `innerState()`; subsequent invocations mutate the +// captured cache objects in place via `_updateInternal`. +// +// REQUIREMENTS / CONSTRAINTS (why this is currently UNWIRED): +// - Every layer must be a ``CompilableKVCache`` (fixed-shape, MLXArray offset). +// Standard `KVCacheSimple` / `RotatingKVCache` change state shape per step and +// cannot be compile-traced (that is the whole reason ``CompilableKVCache`` +// exists). Sliding-window (SWA) models therefore additionally need a +// `CompilableRotatingKVCache` — see the port plan — before they can use this. +// - The trace specialises on the token-batch shape it first sees (typically +// `[B, 1]`). A changing batch size forces a recompile, so the batched decode +// path needs fixed-size buckets (see the port plan for `GenerationBatch`). +// +// This helper is dependency-free w.r.t. the continuous-batching engine: it can +// be exercised in isolation (see CompilableKVCacheTests) and reused by either a +// single-stream or a batched decode loop once the cache-promotion + bucketing +// plumbing lands. + +import Foundation +import MLX + +public enum CompiledDecode { + + /// True iff every layer is a ``CompilableKVCache`` and thus compile-traceable + /// by ``compileForward(model:cacheRef:)``. + public static func eligible(_ cache: [KVCache]) -> Bool { + !cache.isEmpty && cache.allSatisfy { $0 is CompilableKVCache } + } + + /// Build a compiled forward closure for a decode step. + /// + /// The returned closure accepts `[tokens]` (a single `[B, L]` int token + /// array wrapped in a one-element array) and returns `[logits]` (a single + /// `[B, L, V]` array). The captured cache layers are mutated in place. + /// + /// - Precondition: `cacheRef` is non-empty and every element is a + /// ``CompilableKVCache`` (see ``eligible(_:)``). Call `eval(cacheRef)` + /// before this so no pending tracer ops corrupt state identity. + /// + /// - Parameters: + /// - model: The language model to trace through. + /// - cacheRef: Per-layer ``CompilableKVCache`` instances. Captured by the + /// returned closure; must not be empty. + /// - Returns: A `@Sendable` closure mapping `[tokens]` → `[logits]`. + public static func compileForward( + model: any LanguageModel, + cacheRef: [KVCache] + ) -> @Sendable ([MLXArray]) -> [MLXArray] { + precondition( + eligible(cacheRef), + "CompiledDecode.compileForward requires a non-empty cache where every " + + "layer is a CompilableKVCache.") + + let capturedModel = model + let captured = cacheRef + + return compile( + inputs: captured, outputs: captured + ) { (args: [MLXArray]) -> [MLXArray] in + let result = capturedModel( + LMInput.Text(tokens: args[0]), + cache: captured.isEmpty ? nil : captured, + state: nil + ) + return [result.logits] + } + } +} diff --git a/Libraries/MLXLMCommon/DynamicSlice.swift b/Libraries/MLXLMCommon/DynamicSlice.swift new file mode 100644 index 0000000000..a35cba3d84 --- /dev/null +++ b/Libraries/MLXLMCommon/DynamicSlice.swift @@ -0,0 +1,83 @@ +// Dynamic slice operations with MLXArray start positions. +// +// These wrap the MLX C `slice_dynamic` / `slice_update_dynamic` primitives. +// Unlike the Swift subscript (`src[from.. MLXArray { + // Use the C-level slice(array, array_start, axes, slice_size) overload. + // This creates a DynamicSlice primitive which has output_shapes support. + var result = mlx_array_new() + var axesInt = axes.map { Int32($0) } + var sizes = sliceSize.map { Int32($0) } + let rc = mlx_slice_dynamic( + &result, + src.ctx, + start.ctx, + &axesInt, + axesInt.count, + &sizes, + sizes.count, + stream.ctx) + if rc != 0 { + fatalError("[dynamicSlice] mlx_slice_dynamic failed with rc=\(rc)") + } + return MLXArray(result) +} + +/// Update a slice of `src` at dynamic `start` positions on given `axes`. +/// +/// Returns a new array equal to `src` with `update` written in at `start`. +/// Used by ``CompilableKVCache`` to write new KV tokens into a fixed-size +/// buffer inside a compiled graph. +public func dynamicSliceUpdate( + _ src: MLXArray, + update: MLXArray, + start: MLXArray, + axes: [Int32], + stream: StreamOrDevice = .default +) -> MLXArray { + var result = mlx_array_new() + var axesInt = axes.map { Int32($0) } + let rc = mlx_slice_update_dynamic( + &result, + src.ctx, + update.ctx, + start.ctx, + &axesInt, + axesInt.count, + stream.ctx) + if rc != 0 { + fatalError("[dynamicSliceUpdate] mlx_slice_update_dynamic failed with rc=\(rc)") + } + return MLXArray(result) +} diff --git a/Libraries/MLXLMCommon/MLXHardwareInfo.swift b/Libraries/MLXLMCommon/MLXHardwareInfo.swift new file mode 100644 index 0000000000..363f5fcd95 --- /dev/null +++ b/Libraries/MLXLMCommon/MLXHardwareInfo.swift @@ -0,0 +1,39 @@ +import Foundation + +/// Runtime gate for `compile(shapeless: true)` activation micro-fusions +/// (SwiGLU / GeGLU / GELU / softcap). +/// +/// Ported from osaurus/main (`Libraries/MLXLMCommon/HardwareInfo.swift`) and +/// renamed to `MLXHardwareInfo` to avoid colliding with ProviderCore's existing +/// `HardwareInfo` type in the provider build. +/// +/// ## Background +/// +/// `compile(shapeless: true)` wraps a closure in a `CompiledFunction` whose +/// `Compiled::eval_gpu` path can return zero results on some macOS Tahoe Metal +/// JIT drivers (notably M1/M2 A14/A15 GPUs, but also observed on M4). Swift then +/// crashes reading `call(...)[0]` on the empty result. See MLX issues #3329, +/// #3201, #3256. +/// +/// The crash was empirically tied to the *whole-model* compile path +/// (`setupCompiledDecode` + `CompilableKVCache`), not to these small fixed-shape +/// activation fusions, so the default is ON. The per-op overhead of the fusions +/// is negligible vs. the model forward pass, so a machine that does hit the JIT +/// bug can opt out via the `MLX_COMPILED_DECODE` env var with no code change. +/// +/// This intentionally mirrors the `MLX_COMPILED_DECODE` knob used by the Gemma 4 +/// decode helpers (`MLXVLM/Models/Gemma4.swift`) so those file-private fusions can +/// later be collapsed onto this single shared symbol with no behavior change. +public enum MLXHardwareInfo { + /// `true` when `compile(shapeless: true)` activation fusions are enabled. + /// + /// Defaults to `true`. Set `MLX_COMPILED_DECODE` to `0`/`false`/`no`/`off` + /// to disable compiled fusions on a machine that hits the Tahoe Metal JIT + /// bug; any other (or absent) value keeps them on. + public static let isCompiledDecodeSupported: Bool = { + if let raw = ProcessInfo.processInfo.environment["MLX_COMPILED_DECODE"] { + return ["1", "true", "yes", "on"].contains(raw.lowercased()) + } + return true + }() +} diff --git a/Libraries/MLXLMCommon/RoPEUtils.swift b/Libraries/MLXLMCommon/RoPEUtils.swift index 6f49333f7f..060cc6f1e6 100644 --- a/Libraries/MLXLMCommon/RoPEUtils.swift +++ b/Libraries/MLXLMCommon/RoPEUtils.swift @@ -110,7 +110,24 @@ public class ProportionalRoPE: Module, OffsetLayer, ArrayOffsetLayer { if rotatedDims > 0 { let exponents = MLXArray(stride(from: 0, to: rotatedDims, by: 2)).asType(.float32) / Float(dims) - self._freqs = factor * MLX.pow(base, exponents) + let realFreqs = factor * MLX.pow(base, exponents) + // Pad the pass-through pairs with +inf "frequencies" so a single + // MLXFast.RoPE over the FULL `dims` leaves them unrotated + // (angle = offset / inf = 0). This reproduces the previous explicit + // split/concat/reconstruct partial rotary EXACTLY (verified + // bit-identical) in one fused dispatch, mirroring the mlx_lm Python + // `ProportionalRoPE` reference. NOTE: this is deliberately NOT a + // default RoPE over `rotatedDims` dims — that rotates different pairs + // (x[i],x[rotatedDims/2+i]) with /rotatedDims frequencies and is + // numerically wrong for Gemma4 (the weights expect /dims, partner at + // dims/2). + let padCount = (dims - rotatedDims) / 2 + if padCount > 0 { + let pad = MLXArray(Array(repeating: Float.infinity, count: padCount)) + self._freqs = concatenated([realFreqs, pad], axis: -1) + } else { + self._freqs = realFreqs + } } else { self._freqs = nil } @@ -122,96 +139,37 @@ public class ProportionalRoPE: Module, OffsetLayer, ArrayOffsetLayer { guard rotatedDims > 0, let _freqs else { return x } - - let half = dims / 2 - let rotatedHalf = rotatedDims / 2 - - let head: MLXArray - let tail: MLXArray? - if x.shape[x.ndim - 1] > dims { - let parts = split(x, indices: [dims], axis: -1) - head = parts[0] - tail = parts[1] - } else { - head = x - tail = nil - } - - let headParts = split(head, indices: [half], axis: -1) - var left = headParts[0] - var right = headParts[1] - - let leftParts = split(left, indices: [rotatedHalf], axis: -1) - let rightParts = split(right, indices: [rotatedHalf], axis: -1) - var rotated = concatenated([leftParts[0], rightParts[0]], axis: -1) - rotated = MLXFast.RoPE( - rotated, - dimensions: rotatedDims, + // Single fused partial RoPE over the full head dim. `_freqs` carries +inf + // entries for the pass-through pairs (built in init), so MLXFast.RoPE + // rotates only the first `rotatedDims` pairs and leaves the rest + // unchanged — bit-identical to the previous split/concat/reconstruct path + // but in one dispatch. Trailing dims beyond `dims` pass through natively. + return MLXFast.RoPE( + x, + dimensions: dims, traditional: traditional, base: nil, scale: 1.0, offset: offset, freqs: _freqs ) - - let rotatedParts = split(rotated, indices: [rotatedHalf], axis: -1) - left = concatenated([rotatedParts[0], leftParts[1]], axis: -1) - right = concatenated([rotatedParts[1], rightParts[1]], axis: -1) - let updatedHead = concatenated([left, right], axis: -1) - - if let tail { - return concatenated([updatedHead, tail], axis: -1) - } else { - return updatedHead - } } public func callAsFunction(_ x: MLXArray, offset: MLXArray) -> MLXArray { guard rotatedDims > 0, let _freqs else { return x } - - let half = dims / 2 - let rotatedHalf = rotatedDims / 2 - - let head: MLXArray - let tail: MLXArray? - if x.shape[x.ndim - 1] > dims { - let parts = split(x, indices: [dims], axis: -1) - head = parts[0] - tail = parts[1] - } else { - head = x - tail = nil - } - - let headParts = split(head, indices: [half], axis: -1) - var left = headParts[0] - var right = headParts[1] - - let leftParts = split(left, indices: [rotatedHalf], axis: -1) - let rightParts = split(right, indices: [rotatedHalf], axis: -1) - var rotated = concatenated([leftParts[0], rightParts[0]], axis: -1) - rotated = MLXFast.RoPE( - rotated, - dimensions: rotatedDims, + // Batched-offset twin of the scalar path above: one fused MLXFast.RoPE + // over the full head dim with the inf-padded `_freqs`. + return MLXFast.RoPE( + x, + dimensions: dims, traditional: traditional, base: nil, scale: 1.0, offset: offset, freqs: _freqs ) - - let rotatedParts = split(rotated, indices: [rotatedHalf], axis: -1) - left = concatenated([rotatedParts[0], leftParts[1]], axis: -1) - right = concatenated([rotatedParts[1], rightParts[1]], axis: -1) - let updatedHead = concatenated([left, right], axis: -1) - - if let tail { - return concatenated([updatedHead, tail], axis: -1) - } else { - return updatedHead - } } } diff --git a/Libraries/MLXLMCommon/SwitchLayers.swift b/Libraries/MLXLMCommon/SwitchLayers.swift index f440ae421e..9fa9fdeee7 100644 --- a/Libraries/MLXLMCommon/SwitchLayers.swift +++ b/Libraries/MLXLMCommon/SwitchLayers.swift @@ -21,6 +21,64 @@ public let weightedExpertSum: @Sendable (MLXArray, MLXArray) -> MLXArray = compi (outputs * MLX.expandedDimensions(weights, axis: -1)).sum(axis: -2) } +// MARK: - Compiled activation fusions (vMLX / osaurus-main port) + +/// Approximate (tanh) GELU written with `x * x * x` instead of the Power +/// primitive (`x ** 3`). The Power primitive returns zero results under the +/// macOS Tahoe Metal JIT (MLX #3329), so the explicit multiplies keep it safe +/// under `compile(shapeless: true)`. Numerically identical to +/// `MLXNN.geluApproximate`. +/// +/// Gated by `MLXHardwareInfo.isCompiledDecodeSupported` (env `MLX_COMPILED_DECODE`, +/// default on); falls back to the plain closure when compiled fusions are off. +public let safeGeluApproximate: @Sendable (MLXArray) -> MLXArray = { + let body: @Sendable (MLXArray) -> MLXArray = { (x: MLXArray) -> MLXArray in + 0.5 * x * (1 + tanh(sqrt(2 / Float.pi) * (x + 0.044715 * x * x * x))) + } + if MLXHardwareInfo.isCompiledDecodeSupported { + return compile(shapeless: true, body) + } + return body +}() + +/// Drop-in replacement for `MLXNN.GELU(approximation: .tanh)` that avoids the +/// Power primitive crash. Use anywhere a tanh-approx GELU unary layer is needed. +public class SafeGELU: Module, UnaryLayer { + public override init() { super.init() } + public func callAsFunction(_ x: MLXArray) -> MLXArray { + safeGeluApproximate(x) + } +} + +/// Compiled SiLU-gated GLU product (`silu(gate) * up`). Same math as +/// `compiledSiluProduct` above, but gated by `MLXHardwareInfo` so M1/M2 + macOS +/// Tahoe can opt out. Used by `SwitchGLU` when a SiLU activation is supplied via +/// the custom-activation initializer (where `activationProduct` is nil). +private let compiledSwiGLU: @Sendable (MLXArray, MLXArray) -> MLXArray = { + let body: @Sendable (MLXArray, MLXArray) -> MLXArray = { + (gate: MLXArray, up: MLXArray) -> MLXArray in + MLXNN.silu(gate) * up + } + if MLXHardwareInfo.isCompiledDecodeSupported { + return compile(shapeless: true, body) + } + return body +}() + +/// Compiled GELU-gated GLU product (`geluApprox(gate) * up`), fusing the tanh +/// GELU and the element-wise multiply into one shapeless kernel. Uses the +/// Power-free `x * x * x` GELU so it is safe under `compile(shapeless: true)`. +private let compiledGeGLU: @Sendable (MLXArray, MLXArray) -> MLXArray = { + let body: @Sendable (MLXArray, MLXArray) -> MLXArray = { + (gate: MLXArray, up: MLXArray) -> MLXArray in + (0.5 * gate * (1 + tanh(sqrt(2 / Float.pi) * (gate + 0.044715 * gate * gate * gate)))) * up + } + if MLXHardwareInfo.isCompiledDecodeSupported { + return compile(shapeless: true, body) + } + return body +}() + public func gatherSort(x: MLXArray, indices: MLXArray) -> (MLXArray, MLXArray, MLXArray) { let m = indices.dim(-1) let indices = indices.flattened() @@ -59,6 +117,16 @@ public class SwitchGLU: Module { /// supplied (we then fall back to `activation(gate) * up`). Upstream ef85ed0. let activationProduct: (@Sendable (MLXArray, MLXArray) -> MLXArray)? + /// Activation-type flags detected once at init from a tiny test input (vMLX + /// approach — no per-token check). Only consulted when `activationProduct` is + /// nil (the custom-activation path): they let SiLU/GELU custom activations use + /// the compiled `compiledSwiGLU` / `compiledGeGLU` fusions instead of the + /// uncompiled `activation(gate) * up`. On any mismatch we fall back to that + /// exact uncompiled path, so detection only ever enables a numerically + /// equivalent fast path — it can never change results. + let isSiluActivation: Bool + let isGeluActivation: Bool + /// Default SiLU GLU path -- uses the compiled fused (silu * up) kernel. public init( inputDims: Int, @@ -72,6 +140,11 @@ public class SwitchGLU: Module { self.numExperts = numExperts self.activation = MLXNN.silu self.activationProduct = compiledSiluProduct + // Default path is SiLU and `activationProduct` is non-nil, so these are + // not consulted on the hot path; set them accurately for completeness + // (and to avoid a needless probe eval at load for every MoE layer). + self.isSiluActivation = true + self.isGeluActivation = false if fuseGateUp { self._gateUpProj.wrappedValue = SwitchLinear( @@ -102,6 +175,17 @@ public class SwitchGLU: Module { self.numExperts = numExperts self.activation = activation self.activationProduct = nil + // Detect SiLU/GELU once via a tiny test input (vMLX approach) so the hot + // path can select the compiled fusion without a per-token check. Exact + // equality is intentional: a match means the supplied closure computes + // that exact function; any non-match falls back to `activation(gate) * up` + // in callAsFunction, so this can only ever enable an equivalent fast path. + let probe = MLXArray([Float(1.0)]) + let probeOut = activation(probe) + let detectedSilu = (probeOut .== MLXNN.silu(probe)).all().item(Bool.self) + self.isSiluActivation = detectedSilu + self.isGeluActivation = + !detectedSilu && (probeOut .== safeGeluApproximate(probe)).all().item(Bool.self) if fuseGateUp { self._gateUpProj.wrappedValue = SwitchLinear( @@ -148,12 +232,21 @@ public class SwitchGLU: Module { xUp = upProj(x, idx, sortedIndices: doSort) xGate = gateProj(x, idx, sortedIndices: doSort) } - let activated = - if let activationProduct { - activationProduct(xGate, xUp) - } else { - activation(xGate) * xUp - } + let activated: MLXArray + if let activationProduct { + // Highest precedence: the compiled fused (silu * up) kernel wired up + // for the default SiLU path. Preserved exactly. + activated = activationProduct(xGate, xUp) + } else if isSiluActivation { + // Custom activation that is exactly SiLU -> compiled SwiGLU fusion. + activated = compiledSwiGLU(xGate, xUp) + } else if isGeluActivation { + // Custom activation that is exactly tanh-approx GELU -> compiled GeGLU. + activated = compiledGeGLU(xGate, xUp) + } else { + // Exact, uncompiled fallback for any other custom activation. + activated = activation(xGate) * xUp + } x = downProj( activated, idx, diff --git a/Libraries/MLXVLM/Models/Gemma4.swift b/Libraries/MLXVLM/Models/Gemma4.swift index a710adcdc2..006a96992a 100644 --- a/Libraries/MLXVLM/Models/Gemma4.swift +++ b/Libraries/MLXVLM/Models/Gemma4.swift @@ -1,2616 +1,1109 @@ +// Copyright © 2024-2026 Jinho Jang (eric@jangq.ai) +// +// Gemma 4 VLM — vision-language model with: +// - Linear patch embedding with 2D position embeddings +// - 2D multidimensional RoPE for vision encoder +// - VisionPooler for downsampling patches +// - MultimodalEmbedder projecting vision features into text space +// - Full Gemma4 text decoder (MoE 26B or Dense 31B) +// +// Python reference: mlx_vlm/models/gemma4/ + import CoreImage -import CoreMedia import Foundation import MLX -import MLXLLM import MLXLMCommon import MLXNN -// Based on https://github.com/Blaizzy/mlx-vlm/tree/main/mlx_vlm/models/gemma4 - -private enum Gemma4Error: LocalizedError { - case imageTokenCountMismatch(expectedVisionTokens: Int, actualPromptTokens: Int) - - var errorDescription: String? { - switch self { - case .imageTokenCountMismatch(let expectedVisionTokens, let actualPromptTokens): - return - "Gemma4 image token count mismatch: vision encoder produced \(expectedVisionTokens) soft tokens, but the prompt contains \(actualPromptTokens) image tokens." - } - } -} - -private func gemma4BuildLayerTypes(hiddenLayers: Int, slidingWindowPattern: Int) -> [String] { - let pattern = - Array(repeating: "sliding_attention", count: max(slidingWindowPattern - 1, 0)) - + ["full_attention"] - guard !pattern.isEmpty else { return Array(repeating: "full_attention", count: hiddenLayers) } - var result: [String] = [] - result.reserveCapacity(hiddenLayers) - while result.count < hiddenLayers { - result.append(contentsOf: pattern) - } - return Array(result.prefix(hiddenLayers)) -} - -private func gemma4DefaultTextRopeParameters() -> [String: [String: StringOrNumber]] { - [ - "full_attention": [ - "partial_rotary_factor": .float(1.0), - "rope_theta": .float(1_000_000.0), - "rope_type": .string("proportional"), - ], - "sliding_attention": [ - "partial_rotary_factor": .float(1.0), - "rope_theta": .float(10_000.0), - "rope_type": .string("default"), - ], - ] -} - -private func gemma4DefaultVisionRopeParameters() -> [String: StringOrNumber] { - [ - "rope_theta": .float(100.0), - "rope_type": .string("default"), - ] -} - -private func gemma4MaskedScatter( - inputTensor: MLXArray, mask: MLXArray, source: MLXArray -) -> MLXArray { - let flattenedInput = inputTensor.flattened() - let flattenedMask = mask.flattened().asArray(Bool.self) - let flattenedSource = source.flattened() - - let targetIndices = flattenedMask.enumerated().compactMap { idx, value in - value ? Int32(idx) : nil - } - guard !targetIndices.isEmpty else { - return inputTensor - } - - guard flattenedSource.dim(0) == targetIndices.count else { - fatalError( - "Masked scatter shape mismatch. source=\(flattenedSource.dim(0)) mask=\(targetIndices.count)" - ) - } - - let result = flattenedInput - result[MLXArray(targetIndices, [targetIndices.count])] = flattenedSource - return result.reshaped(inputTensor.shape) -} - -private func gemma4OneHot(_ indices: MLXArray, numClasses: Int) -> MLXArray { - expandedDimensions(indices, axis: -1) .== MLXArray(0 ..< numClasses) -} - -/// Per-token block id for vision spans: each contiguous run of vision tokens shares an id, -/// non-vision tokens get -1. Mirrors Python `_block_sequence_ids_for_mask`. -private func gemma4VisionBlockIds(_ isVision: MLXArray) -> MLXArray { - let length = isVision.dim(1) - let leading = MLXArray.zeros([isVision.dim(0), 1], dtype: .bool) - let prev = concatenated([leading, isVision[0..., ..<(length - 1)]], axis: 1) - let starts = logicalAnd(isVision, logicalNot(prev)) - let groupIds = cumsum(starts.asType(.int32), axis: 1) - 1 - return MLX.where(isVision, groupIds, MLXArray(Int32(-1))) -} - -/// Overlay blockwise bidirectional attention for vision-token spans onto a boolean causal -/// mask (True = attend). Tokens in the same image block attend to each other in both -/// directions. Mirrors Python `_apply_blockwise_bidirectional_overlay`. -private func gemma4BidirectionalVisionMask(_ baseMask: MLXArray, isVision: MLXArray) -> MLXArray { - let blockIds = gemma4VisionBlockIds(isVision) - let qBlocks = expandedDimensions(blockIds, axis: -1) // [B, L, 1] - let kBlocks = expandedDimensions(blockIds, axis: -2) // [B, 1, L] - let sameBlock = logicalAnd(qBlocks .!= MLXArray(Int32(-1)), qBlocks .== kBlocks) // [B, L, L] - return logicalOr(baseMask, expandedDimensions(sameBlock, axis: 1)) // -> [B, 1, L, L] -} - -/// If `mode` carries a boolean mask array, overlay the vision bidirectional attention; pass -/// other modes (e.g. `.causal`, `.none`) through unchanged. -private func gemma4OverlayBidirectionalVision( - _ mode: MLXFast.ScaledDotProductAttentionMaskMode, isVision: MLXArray -) -> MLXFast.ScaledDotProductAttentionMaskMode { - switch mode { - case .array(let maskArray): - return .array(gemma4BidirectionalVisionMask(maskArray, isVision: isVision)) - default: - return mode - } -} - -private func gemma4RotateHalf(_ x: MLXArray) -> MLXArray { - let half = x.shape[x.shape.count - 1] / 2 - let x1 = x[.ellipsis, .. MLXArray { - let headDim = inputs.shape[inputs.ndim - 1] - if positions.ndim == 2 { - let half = headDim / 2 - let freqExponents = - (2.0 / Float(headDim)) * MLXArray(0 ..< half).asType(.float32) - let timescale = MLX.pow(MLXArray(baseFrequency), freqExponents) - let sinusoid = positions.asType(.float32).expandedDimensions(axis: -1) / timescale - var cosValue = cos(sinusoid) - var sinValue = sin(sinusoid) - cosValue = concatenated([cosValue, cosValue], axis: -1).asType(inputs.dtype) - sinValue = concatenated([sinValue, sinValue], axis: -1).asType(inputs.dtype) - cosValue = expandedDimensions(cosValue, axis: 2) - sinValue = expandedDimensions(sinValue, axis: 2) - return inputs * cosValue + gemma4RotateHalf(inputs) * sinValue - } - - let numDimensions = positions.shape[positions.ndim - 1] - let channelsPerDimension = 2 * (headDim / (2 * numDimensions)) - let halfPerDimension = channelsPerDimension / 2 - - var parts: [MLXArray] = [] - parts.reserveCapacity(numDimensions) - - for d in 0 ..< numDimensions { - let start = d * channelsPerDimension - let end = start + channelsPerDimension - let part = inputs[.ellipsis, start ..< end] - - let freqExponents = - (2.0 / Float(channelsPerDimension)) * MLXArray(0 ..< halfPerDimension).asType(.float32) - let timescale = MLX.pow(MLXArray(baseFrequency), freqExponents) - let dimPositions = positions[.ellipsis, d ..< d + 1].asType(.float32) - let sinusoid = dimPositions / timescale - - var cosValue = cos(sinusoid) - var sinValue = sin(sinusoid) - cosValue = concatenated([cosValue, cosValue], axis: -1).asType(inputs.dtype) - sinValue = concatenated([sinValue, sinValue], axis: -1).asType(inputs.dtype) - cosValue = expandedDimensions(cosValue, axis: 2) - sinValue = expandedDimensions(sinValue, axis: 2) - - parts.append(part * cosValue + gemma4RotateHalf(part) * sinValue) - } - - return concatenated(parts, axis: -1) -} - -private func gemma4EnsureFusedSDPA( - queries: MLXArray, - keys: MLXArray, - values: MLXArray, - scale: Float, - mask: MLXFast.ScaledDotProductAttentionMaskMode -) -> MLXArray { - let fusedDims = [64, 80, 128] - let d = queries.dim(queries.ndim - 1) - let target = fusedDims.first(where: { d <= $0 }) ?? d - - if target == d { - return MLXFast.scaledDotProductAttention( - queries: queries, keys: keys, values: values, scale: scale, mask: mask) - } - - let paddedQueries = MLX.padded( - queries, widths: [0, 0, 0, .init((0, target - d))]) - let paddedKeys = MLX.padded( - keys, widths: [0, 0, 0, .init((0, target - d))]) - let paddedValues = MLX.padded( - values, widths: [0, 0, 0, .init((0, target - d))]) - - return MLXFast.scaledDotProductAttention( - queries: paddedQueries, keys: paddedKeys, values: paddedValues, scale: scale, mask: mask - )[.ellipsis, .. MLXFast.ScaledDotProductAttentionMaskMode { - switch mask { - case .array(let maskArray): - let maskLength = maskArray.dim(-1) - guard maskLength > keyLength else { - return mask - } - let start = maskLength - keyLength - return .array(maskArray[.ellipsis, start...]) - case .arrays, .causal, .none: - return mask - } -} - -/// Manual batched attention used on the decode path when an explicit array mask -/// is present. MLX issue #3384: `MLXFast.scaledDotProductAttention` takes a -/// numerically divergent kernel branch when handed an explicit mask array on -/// 4-bit-quantized Gemma 4 — flipping top-1 logits and trapping continuous- -/// batched generation in repetition loops (the symptom users hit). This -/// explicit matmul + precise float32 softmax path is immune to that divergence -/// and matches the fused kernel's math. The NaN guard maps fully-masked -/// (left-padding) query rows to zero so `0 * NaN` can't corrupt other rows. -private func gemma4MaskedAttentionFallback( - queries: MLXArray, - keys: MLXArray, - values: MLXArray, - scale: Float, - mask: MLXFast.ScaledDotProductAttentionMaskMode -) -> MLXArray { - let (B, nQHeads, L, D) = ( - queries.dim(0), queries.dim(1), queries.dim(2), queries.dim(3) - ) - let nKVHeads = keys.dim(1) - let repeats = nQHeads / nKVHeads - - var q = queries * scale - var k = keys - var v = values - if repeats > 1 { - q = q.reshaped([B, nKVHeads, repeats, L, D]) - k = expandedDimensions(k, axis: 2) - v = expandedDimensions(v, axis: 2) - } - - var scores = matmul(q, k.swappedAxes(-1, -2)) - - func applyMask(_ maskArray: MLXArray) { - var m = maskArray - if scores.ndim == 5 && m.ndim == 4 && m.dim(0) == scores.dim(0) { - m = expandedDimensions(m, axis: 2) - } - if m.dtype == .bool { - scores = MLX.where(m, scores, MLXArray(-Float.infinity, dtype: scores.dtype)) - } else { - scores = scores + m - } - } - - switch mask { - case .none: - break - case .causal: - let qL = scores.dim(-2) - let kL = scores.dim(-1) - let qIndices = MLXArray(0 ..< qL) + MLXArray(kL - qL) - let kIndices = MLXArray(0 ..< kL) - let causalMask = greaterEqual( - expandedDimensions(qIndices, axis: -1), - expandedDimensions(kIndices, axis: -2)) - applyMask(causalMask) - case .array(let maskArray): - applyMask(maskArray) - case .arrays(let maskArrays): - if let maskArray = maskArrays.first { applyMask(maskArray) } - } - - var probs = softmax(scores.asType(.float32), axis: -1, precise: true) - probs = MLX.where(probs .!= probs, MLXArray(Float(0)), probs) - scores = probs.asType(scores.dtype) - var output = matmul(scores, v) - if repeats > 1 { - output = output.reshaped([B, nQHeads, L, values.dim(3)]) - } - return output -} - -/// Whether a mask mode carries an explicit materialized array (the kernel path -/// that triggers MLX #3384 on quantized Gemma 4). -private func gemma4MaskIsExplicitArray( - _ mask: MLXFast.ScaledDotProductAttentionMaskMode -) -> Bool { - switch mask { - case .array, .arrays: return true - case .none, .causal: return false - } -} - -// MARK: - Configuration - -public struct Gemma4TextConfiguration: Codable, Sendable { - public let modelType: String - public let hiddenSize: Int - public let hiddenLayers: Int - public let intermediateSize: Int - public let attentionHeads: Int - public let kvHeads: Int - public let globalKVHeads: Int? - public let headDim: Int - public let globalHeadDim: Int - public let vocabularySize: Int - public let vocabularySizePerLayerInput: Int - public let numKVSharedLayers: Int - public let hiddenSizePerLayerInput: Int - public let slidingWindow: Int - public let slidingWindowPattern: Int - public let maxPositionEmbeddings: Int - public let rmsNormEps: Float - public let ropeTraditional: Bool - public let finalLogitSoftcapping: Float? - public let useDoubleWideMLP: Bool - public let enableMoEBlock: Bool - public let numExperts: Int? - public let topKExperts: Int? - public let moeIntermediateSize: Int? - public let attentionKEqV: Bool - public let layerTypes: [String] - public let ropeParameters: [String: [String: StringOrNumber]] - public let tieWordEmbeddings: Bool - /// "vision" enables blockwise bidirectional attention within image-token spans - /// (Gemma 4 vision). nil/absent keeps attention fully causal. - public let useBidirectionalAttention: String? - - 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 kvHeads = "num_key_value_heads" - case globalKVHeads = "num_global_key_value_heads" - case headDim = "head_dim" - case globalHeadDim = "global_head_dim" - case vocabularySize = "vocab_size" - case vocabularySizePerLayerInput = "vocab_size_per_layer_input" - case numKVSharedLayers = "num_kv_shared_layers" - case hiddenSizePerLayerInput = "hidden_size_per_layer_input" - case slidingWindow = "sliding_window" - case slidingWindowPattern = "sliding_window_pattern" - case maxPositionEmbeddings = "max_position_embeddings" - case rmsNormEps = "rms_norm_eps" - case ropeTraditional = "rope_traditional" - case finalLogitSoftcapping = "final_logit_softcapping" - case useDoubleWideMLP = "use_double_wide_mlp" - case enableMoEBlock = "enable_moe_block" - case numExperts = "num_experts" - case topKExperts = "top_k_experts" - case moeIntermediateSize = "moe_intermediate_size" - case attentionKEqV = "attention_k_eq_v" - case layerTypes = "layer_types" - case ropeParameters = "rope_parameters" - case tieWordEmbeddings = "tie_word_embeddings" - case useBidirectionalAttention = "use_bidirectional_attention" - } - - public init(from decoder: any Swift.Decoder) throws { - let c = try decoder.container(keyedBy: CodingKeys.self) - modelType = - try c.decodeIfPresent(String.self, forKey: CodingKeys.modelType) ?? "gemma4_text" - hiddenSize = try c.decodeIfPresent(Int.self, forKey: CodingKeys.hiddenSize) ?? 1536 - hiddenLayers = try c.decodeIfPresent(Int.self, forKey: CodingKeys.hiddenLayers) ?? 35 - intermediateSize = - try c.decodeIfPresent(Int.self, forKey: CodingKeys.intermediateSize) ?? 6144 - attentionHeads = try c.decodeIfPresent(Int.self, forKey: CodingKeys.attentionHeads) ?? 8 - kvHeads = try c.decodeIfPresent(Int.self, forKey: CodingKeys.kvHeads) ?? 1 - globalKVHeads = try c.decodeIfPresent(Int.self, forKey: CodingKeys.globalKVHeads) - headDim = try c.decodeIfPresent(Int.self, forKey: CodingKeys.headDim) ?? 256 - globalHeadDim = try c.decodeIfPresent(Int.self, forKey: CodingKeys.globalHeadDim) ?? 512 - vocabularySize = - try c.decodeIfPresent(Int.self, forKey: CodingKeys.vocabularySize) ?? 262_144 - vocabularySizePerLayerInput = - try c.decodeIfPresent(Int.self, forKey: CodingKeys.vocabularySizePerLayerInput) - ?? vocabularySize - numKVSharedLayers = - try c.decodeIfPresent(Int.self, forKey: CodingKeys.numKVSharedLayers) ?? 20 - hiddenSizePerLayerInput = - try c.decodeIfPresent(Int.self, forKey: CodingKeys.hiddenSizePerLayerInput) ?? 256 - slidingWindow = try c.decodeIfPresent(Int.self, forKey: CodingKeys.slidingWindow) ?? 512 - slidingWindowPattern = - try c.decodeIfPresent(Int.self, forKey: CodingKeys.slidingWindowPattern) ?? 5 - maxPositionEmbeddings = - try c.decodeIfPresent(Int.self, forKey: CodingKeys.maxPositionEmbeddings) ?? 131_072 - rmsNormEps = try c.decodeIfPresent(Float.self, forKey: CodingKeys.rmsNormEps) ?? 1e-6 - ropeTraditional = - try c.decodeIfPresent(Bool.self, forKey: CodingKeys.ropeTraditional) ?? false - finalLogitSoftcapping = - try c.decodeIfPresent(Float.self, forKey: CodingKeys.finalLogitSoftcapping) ?? 30.0 - useDoubleWideMLP = - try c.decodeIfPresent(Bool.self, forKey: CodingKeys.useDoubleWideMLP) ?? true - enableMoEBlock = - try c.decodeIfPresent(Bool.self, forKey: CodingKeys.enableMoEBlock) ?? false - numExperts = try c.decodeIfPresent(Int.self, forKey: CodingKeys.numExperts) - topKExperts = try c.decodeIfPresent(Int.self, forKey: CodingKeys.topKExperts) - moeIntermediateSize = try c.decodeIfPresent( - Int.self, forKey: CodingKeys.moeIntermediateSize) - attentionKEqV = try c.decodeIfPresent(Bool.self, forKey: CodingKeys.attentionKEqV) ?? false - ropeParameters = - try c.decodeIfPresent( - [String: [String: StringOrNumber]].self, forKey: CodingKeys.ropeParameters) - ?? gemma4DefaultTextRopeParameters() - layerTypes = - try c.decodeIfPresent([String].self, forKey: CodingKeys.layerTypes) - ?? gemma4BuildLayerTypes( - hiddenLayers: hiddenLayers, slidingWindowPattern: slidingWindowPattern) - tieWordEmbeddings = - try c.decodeIfPresent(Bool.self, forKey: CodingKeys.tieWordEmbeddings) ?? true - useBidirectionalAttention = - try c.decodeIfPresent(String.self, forKey: CodingKeys.useBidirectionalAttention) - } +// Darkbloom note: wholesale port of vMLX Libraries/MLXVLM/Models/Gemma4.swift +// (the proven 79.6 TPS Gemma4-26B-A4B decode path). Adapted to our integration +// base: HardwareInfo -> MLXHardwareInfo, RuntimeMoETopKOverride dropped (plain +// decode), graphOffsetArray stubbed (host-int offset fallback), audio guard and +// cacheScopeSalt removed (not in our LMInput), QwenVL.intExtent replaced by a +// local helper. MTP/capture hooks intentionally dropped (provider only references +// Gemma4 in comments; the decode benchmark uses only the LanguageModel API). + +// Compiled logit softcap — fuses divide + tanh + multiply into one Metal dispatch. +private let compiledLogitSoftcap: @Sendable (MLXArray, MLXArray) -> MLXArray = { + let body: @Sendable (MLXArray, MLXArray) -> MLXArray = { (x: MLXArray, cap: MLXArray) -> MLXArray in + tanh(x / cap) * cap + } + return MLXHardwareInfo.isCompiledDecodeSupported ? compile(shapeless: true, body) : body +}() + +// Graph-traceable offset for KV-sharing layers. The vMLX reference reads a +// Compilable*/Batch* cache `offsetArray` here to keep the shared-KV offset inside +// the compiled graph. Our integration base does not expose that accessor in the +// MLXVLM scope, so we fall back to the host-int offset (`sharedOffset`), which is +// correct for B=1 / non-compiled decode — the path the provider and the decode +// benchmark exercise. Returns nil to select that fallback. +private func gemma4VLMGraphOffsetArray(for cache: KVCache?) -> MLXArray? { nil } + +// Local replacement for vMLX's `QwenVL.intExtent` (absent in our tree). Rejects +// zero-area / non-finite extents so the scale-factor math below cannot divide by +// zero or trap inside `Int(floor(.nan))` / `Int(.infinity)`. +private func gemma4IntExtent(_ size: CGSize) throws -> (Int, Int) { + let w = size.width + let h = size.height + guard w.isFinite, h.isFinite, w > 0, h > 0 else { + throw VLMError.imageProcessingFailure( + "Gemma4: image has a zero-area or non-finite extent (w=\(w), h=\(h)).") + } + return (Int(h), Int(w)) } -public struct Gemma4VisionConfiguration: Codable, Sendable { - public let modelType: String - public let hiddenLayers: Int - public let hiddenSize: Int - public let intermediateSize: Int - public let attentionHeads: Int - public let keyValueHeads: Int - public let headDim: Int - public let patchSize: Int - public let rmsNormEps: Float - public let defaultOutputLength: Int - public let positionEmbeddingSize: Int - public let poolingKernelSize: Int - public let useClippedLinears: Bool - public let standardize: Bool - public let ropeParameters: [String: StringOrNumber] - enum CodingKeys: String, CodingKey { - case modelType = "model_type" - case hiddenLayers = "num_hidden_layers" - case hiddenSize = "hidden_size" - case intermediateSize = "intermediate_size" - case attentionHeads = "num_attention_heads" - case keyValueHeads = "num_key_value_heads" - case headDim = "head_dim" - case patchSize = "patch_size" - case rmsNormEps = "rms_norm_eps" - case defaultOutputLength = "default_output_length" - case positionEmbeddingSize = "position_embedding_size" - case poolingKernelSize = "pooling_kernel_size" - case useClippedLinears = "use_clipped_linears" - case standardize - case ropeParameters = "rope_parameters" - } - - public init(from decoder: any Swift.Decoder) throws { - let c = try decoder.container(keyedBy: CodingKeys.self) - modelType = - try c.decodeIfPresent(String.self, forKey: CodingKeys.modelType) ?? "gemma4_vision" - hiddenLayers = try c.decodeIfPresent(Int.self, forKey: CodingKeys.hiddenLayers) ?? 16 - hiddenSize = try c.decodeIfPresent(Int.self, forKey: CodingKeys.hiddenSize) ?? 768 - intermediateSize = - try c.decodeIfPresent(Int.self, forKey: CodingKeys.intermediateSize) ?? 3072 - attentionHeads = try c.decodeIfPresent(Int.self, forKey: CodingKeys.attentionHeads) ?? 12 - keyValueHeads = - try c.decodeIfPresent(Int.self, forKey: CodingKeys.keyValueHeads) ?? attentionHeads - headDim = try c.decodeIfPresent(Int.self, forKey: CodingKeys.headDim) ?? 64 - patchSize = try c.decodeIfPresent(Int.self, forKey: CodingKeys.patchSize) ?? 16 - rmsNormEps = try c.decodeIfPresent(Float.self, forKey: CodingKeys.rmsNormEps) ?? 1e-6 - defaultOutputLength = - try c.decodeIfPresent(Int.self, forKey: CodingKeys.defaultOutputLength) ?? 280 - positionEmbeddingSize = - try c.decodeIfPresent(Int.self, forKey: CodingKeys.positionEmbeddingSize) ?? 10_240 - poolingKernelSize = - try c.decodeIfPresent(Int.self, forKey: CodingKeys.poolingKernelSize) ?? 3 - useClippedLinears = - try c.decodeIfPresent(Bool.self, forKey: CodingKeys.useClippedLinears) ?? false - standardize = try c.decodeIfPresent(Bool.self, forKey: CodingKeys.standardize) ?? false - ropeParameters = - try c.decodeIfPresent([String: StringOrNumber].self, forKey: CodingKeys.ropeParameters) - ?? gemma4DefaultVisionRopeParameters() - } -} - -public struct Gemma4Configuration: Codable, Sendable { - public let textConfiguration: Gemma4TextConfiguration - public let visionConfiguration: Gemma4VisionConfiguration - public let modelType: String - public let quantization: BaseConfiguration.Quantization? - public let imageTokenId: Int - public let videoTokenId: Int? - public let audioTokenId: Int? - public let boiTokenId: Int - public let eoiTokenId: Int? - public let visionSoftTokensPerImage: Int - public let tieWordEmbeddings: Bool - - private let _vocabularySize: Int? - private let _hiddenSize: Int? - private let _padTokenId: Int? - - public var vocabularySize: Int { _vocabularySize ?? textConfiguration.vocabularySize } - public var hiddenSize: Int { _hiddenSize ?? textConfiguration.hiddenSize } - public var padTokenId: Int { _padTokenId ?? 0 } +// MARK: - Shared Norm Utilities - enum CodingKeys: String, CodingKey { - case textConfiguration = "text_config" - case visionConfiguration = "vision_config" - case modelType = "model_type" - case quantization - case imageTokenId = "image_token_id" - case videoTokenId = "video_token_id" - case audioTokenId = "audio_token_id" - case boiTokenId = "boi_token_id" - case eoiTokenId = "eoi_token_id" - case visionSoftTokensPerImage = "vision_soft_tokens_per_image" - case tieWordEmbeddings = "tie_word_embeddings" - case _vocabularySize = "vocab_size" - case _hiddenSize = "hidden_size" - case _padTokenId = "pad_token_id" - } - - public init(from decoder: any Swift.Decoder) throws { - let c = try decoder.container(keyedBy: CodingKeys.self) - textConfiguration = try c.decode( - Gemma4TextConfiguration.self, forKey: CodingKeys.textConfiguration) - visionConfiguration = try c.decode( - Gemma4VisionConfiguration.self, forKey: CodingKeys.visionConfiguration) - modelType = try c.decodeIfPresent(String.self, forKey: CodingKeys.modelType) ?? "gemma4" - quantization = try c.decodeIfPresent( - BaseConfiguration.Quantization.self, forKey: CodingKeys.quantization) - imageTokenId = try c.decodeIfPresent(Int.self, forKey: CodingKeys.imageTokenId) ?? 258_880 - // Default to the Gemma 4 video token id so the model stays in sync with the processor - // (which always emits video placeholders) even when config.json omits the key. - videoTokenId = try c.decodeIfPresent(Int.self, forKey: CodingKeys.videoTokenId) ?? 258_884 - audioTokenId = try c.decodeIfPresent(Int.self, forKey: CodingKeys.audioTokenId) - boiTokenId = try c.decodeIfPresent(Int.self, forKey: CodingKeys.boiTokenId) ?? 255_999 - eoiTokenId = try c.decodeIfPresent(Int.self, forKey: CodingKeys.eoiTokenId) - visionSoftTokensPerImage = - try c.decodeIfPresent(Int.self, forKey: CodingKeys.visionSoftTokensPerImage) - ?? visionConfiguration.defaultOutputLength - tieWordEmbeddings = - try c.decodeIfPresent(Bool.self, forKey: CodingKeys.tieWordEmbeddings) - ?? textConfiguration.tieWordEmbeddings - _vocabularySize = try c.decodeIfPresent(Int.self, forKey: CodingKeys._vocabularySize) - _hiddenSize = try c.decodeIfPresent(Int.self, forKey: CodingKeys._hiddenSize) - _padTokenId = try c.decodeIfPresent(Int.self, forKey: CodingKeys._padTokenId) - } -} - -// MARK: - Text - -private final class Gemma4RMSNormNoScale: Module, UnaryLayer { +/// Standard Gemma4 RMSNorm — weight used directly, NO +1 offset +private class G4RMSNorm: Module, UnaryLayer { + let weight: MLXArray let eps: Float - - init(eps: Float = 1e-6) { + init(dimensions: Int, eps: Float = 1e-6) { + self.weight = MLXArray.ones([dimensions]) self.eps = eps super.init() } - func callAsFunction(_ x: MLXArray) -> MLXArray { - MLXFast.rmsNorm(x, weight: MLXArray.mlxNone, eps: eps) + MLXFast.rmsNorm(x, weight: weight, eps: eps) } } -private final class Gemma4RMSNormZeroShift: Module, UnaryLayer { +/// Vision RMSNorm — full float32 computation for precision +private class VisionRMSNorm: Module, UnaryLayer { + let weight: MLXArray let eps: Float - @ModuleInfo var weight: MLXArray - init(dimensions: Int, eps: Float = 1e-6) { + self.weight = MLXArray.ones([dimensions]) self.eps = eps - self._weight.wrappedValue = MLXArray.ones([dimensions]) - super.init() - } - - func callAsFunction(_ x: MLXArray) -> MLXArray { - MLXFast.rmsNorm(x, weight: weight, eps: eps) - } -} - -private final class Gemma4TextMLP: Module, UnaryLayer { - @ModuleInfo(key: "gate_proj") var gateProj: Linear - @ModuleInfo(key: "down_proj") var downProj: Linear - @ModuleInfo(key: "up_proj") var upProj: Linear - - init(config: Gemma4TextConfiguration, layerIdx: Int) { - let firstKVSharedLayer = config.hiddenLayers - config.numKVSharedLayers - let isKVSharedLayer = layerIdx >= firstKVSharedLayer && firstKVSharedLayer > 0 - let useDoubleWide = config.useDoubleWideMLP && isKVSharedLayer - let hiddenDimensions = config.intermediateSize * (useDoubleWide ? 2 : 1) - - self._gateProj.wrappedValue = Linear(config.hiddenSize, hiddenDimensions, bias: false) - self._downProj.wrappedValue = Linear(hiddenDimensions, config.hiddenSize, bias: false) - self._upProj.wrappedValue = Linear(config.hiddenSize, hiddenDimensions, bias: false) super.init() } - func callAsFunction(_ x: MLXArray) -> MLXArray { - downProj(geluApproximate(gateProj(x)) * upProj(x)) + let xf = x.asType(.float32) + let v = (xf * xf).mean(axis: -1, keepDims: true) + return ((xf * rsqrt(v + eps)) * weight.asType(.float32)).asType(x.dtype) } } -private final class Gemma4TextRouter: Module { - let topKExperts: Int - 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 - - init(config: Gemma4TextConfiguration) { - guard let numExperts = config.numExperts, let topKExperts = config.topKExperts else { - fatalError("Gemma4 MoE router requires numExperts and topKExperts") - } - - self.topKExperts = topKExperts - 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]) - super.init() - } - - func callAsFunction(_ x: MLXArray) -> (MLXArray, MLXArray) { - var x = norm(x) - x = x * MLXArray(rootSize, dtype: x.dtype) - x = x * scale.asType(x.dtype) - - let expertScores = proj(x) - - let topKIndices = MLX.argPartition(-expertScores, kth: topKExperts - 1, axis: -1)[ - .ellipsis, .. MLXArray { + MLXFast.rmsNorm(x, weight: MLXArray.mlxNone, eps: eps) } -private final class Gemma4TextExperts: Module { - @ModuleInfo(key: "switch_glu") var switchGLU: SwitchGLU - - init(config: Gemma4TextConfiguration) { - guard let numExperts = config.numExperts, - let moeIntermediateSize = config.moeIntermediateSize - else { - fatalError("Gemma4 MoE experts require numExperts and moeIntermediateSize") - } - - // The mlx-community checkpoints ship the experts as separate, independently quantized - // gate_proj/up_proj tensors. Fusing them (concatenating the 4-bit-packed weights + - // per-group scales/biases) corrupts the experts, so keep them unfused — matching the - // Python mlx-vlm reference, which also consumes gate_proj/up_proj directly. - self._switchGLU.wrappedValue = SwitchGLU( - inputDims: config.hiddenSize, - hiddenDims: moeIntermediateSize, - numExperts: numExperts, - activation: geluApproximate, - bias: false, - fuseGateUp: false - ) - super.init() - } - - func callAsFunction( - _ x: MLXArray, topKIndices: MLXArray, topKWeights: MLXArray - ) -> MLXArray { - let batch = x.dim(0) - let length = x.dim(1) - let hidden = x.dim(2) - let topK = topKIndices.dim(-1) - - let expertOutput = switchGLU( - x.reshaped(batch * length, hidden), - topKIndices.reshaped(batch * length, topK) - ) - let weights = topKWeights.reshaped(batch * length, topK, 1).asType(expertOutput.dtype) - return (expertOutput * weights).sum(axis: -2).reshaped(batch, length, hidden) - } +private func visionRmsNormNoScale(_ x: MLXArray, eps: Float = 1e-6) -> MLXArray { + let xf = x.asType(.float32) + let v = (xf * xf).mean(axis: -1, keepDims: true) + return (xf * rsqrt(v + eps)).asType(x.dtype) } -private final class Gemma4ScaledLinear: Module, UnaryLayer { - @ModuleInfo(key: "weight") var weight: MLXArray - let scalar: Float - - init(inFeatures: Int, outFeatures: Int, scalar: Float) { - self.scalar = scalar - self._weight.wrappedValue = MLXArray.zeros([outFeatures, inFeatures]) - super.init() - } - - func callAsFunction(_ x: MLXArray) -> MLXArray { - (x.matmul(weight.transposed())) * scalar - } -} +// MARK: - Configurations -private final class Gemma4TextAttention: Module { - let config: Gemma4TextConfiguration - let layerIdx: Int - let layerType: String - let isSliding: Bool +public struct Gemma4VisionConfig: Codable, Sendable { + let hiddenSize: Int + let intermediateSize: Int + let numHiddenLayers: Int + let numAttentionHeads: Int + let numKeyValueHeads: Int let headDim: Int - let numHeads: Int - let numKVHeads: Int - let scale: Float - let isKVSharedLayer: Bool - let useKEqV: Bool - - @ModuleInfo(key: "q_proj") var qProj: Linear - @ModuleInfo(key: "k_proj") var kProj: Linear - @ModuleInfo(key: "v_proj") var vProj: Linear? - @ModuleInfo(key: "o_proj") var oProj: Linear - @ModuleInfo(key: "q_norm") var qNorm: Gemma4RMSNormZeroShift - @ModuleInfo(key: "k_norm") var kNorm: Gemma4RMSNormZeroShift - @ModuleInfo(key: "v_norm") var vNorm: Gemma4RMSNormNoScale - @ModuleInfo var rope: OffsetLayer - - init(config: Gemma4TextConfiguration, layerIdx: Int) { - self.config = config - self.layerIdx = layerIdx - self.layerType = config.layerTypes[layerIdx] - self.isSliding = layerType == "sliding_attention" - self.headDim = - layerType == "full_attention" && config.globalHeadDim > 0 - ? config.globalHeadDim : config.headDim - self.numHeads = config.attentionHeads - self.useKEqV = config.attentionKEqV && !isSliding - self.numKVHeads = - useKEqV ? (config.globalKVHeads ?? config.kvHeads) : config.kvHeads - self.scale = 1.0 - - let firstKVSharedLayer = config.hiddenLayers - config.numKVSharedLayers - self.isKVSharedLayer = layerIdx >= firstKVSharedLayer && firstKVSharedLayer > 0 - - self._qProj.wrappedValue = Linear(config.hiddenSize, numHeads * headDim, bias: false) - self._kProj.wrappedValue = Linear(config.hiddenSize, numKVHeads * headDim, bias: false) - if !useKEqV { - self._vProj.wrappedValue = Linear( - config.hiddenSize, numKVHeads * headDim, bias: false) - } - self._oProj.wrappedValue = Linear(numHeads * headDim, config.hiddenSize, bias: false) - self._qNorm.wrappedValue = Gemma4RMSNormZeroShift( - dimensions: headDim, eps: config.rmsNormEps) - self._kNorm.wrappedValue = Gemma4RMSNormZeroShift( - dimensions: headDim, eps: config.rmsNormEps) - self._vNorm.wrappedValue = Gemma4RMSNormNoScale(eps: config.rmsNormEps) - - let ropeKey = isSliding ? "sliding_attention" : "full_attention" - let ropeConfig = config.ropeParameters[ropeKey] - let ropeTheta = ropeConfig?["rope_theta"]?.asFloat() ?? (isSliding ? 10_000 : 1_000_000) - self._rope.wrappedValue = initializeRope( - dims: headDim, - base: ropeTheta, - traditional: config.ropeTraditional, - scalingConfig: ropeConfig, - maxPositionEmbeddings: config.maxPositionEmbeddings - ) - - super.init() - } - - func callAsFunction( - _ x: MLXArray, mask: MLXFast.ScaledDotProductAttentionMaskMode = .none, - cache: KVCache? = nil, - sharedKV: Gemma4SharedKVState? = nil, - offset: Int? = nil, - perRowOffset: MLXArray? = nil - ) -> (MLXArray, Gemma4SharedKVState?, Int) { - let (batch, length, _) = (x.dim(0), x.dim(1), x.dim(2)) - - var queries = qProj(x).reshaped(batch, length, numHeads, headDim) - queries = qNorm(queries) - - let currentOffset: Int - let kvState: Gemma4SharedKVState? - - // Per-row RoPE: in a continuous batch, rows have different lengths, so a - // single scalar `cache.offset` (the max across rows) would give shorter - // rows the wrong positions and corrupt their output. When the cache is a - // BatchPositionedKVCache the caller threads its per-row `batchOffset` - // (captured pre-update) and we apply RoPE per row; otherwise (B=1 / - // vision / non-batched) we fall back to the scalar offset unchanged. - func applyRoPE(_ t: MLXArray, scalar: Int) -> MLXArray { - if let perRowOffset, let arrayRope = rope as? ArrayOffsetLayer { - return arrayRope.callAsFunction(t, offset: perRowOffset) - } - return rope(t, offset: scalar) - } - - if let sharedKV { - currentOffset = offset ?? 0 - kvState = sharedKV - } else { - currentOffset = cache?.offset ?? 0 - var keys = kProj(x).reshaped(batch, length, numKVHeads, headDim) - var values = - if useKEqV { - keys - } else { - vProj!(x).reshaped(batch, length, numKVHeads, headDim) - } - keys = kNorm(keys).transposed(0, 2, 1, 3) - values = vNorm(values).transposed(0, 2, 1, 3) - keys = applyRoPE(keys, scalar: currentOffset) - if let quantizedCache = cache as? QuantizedKVCacheProtocol { - let (quantizedKeys, quantizedValues) = quantizedCache.updateQuantized( - keys: keys, values: values) - kvState = .quantized( - keys: quantizedKeys, - values: quantizedValues, - groupSize: quantizedCache.groupSize, - bits: quantizedCache.bits, - mode: quantizedCache.mode - ) - } else { - if let cache { - (keys, values) = cache.update(keys: keys, values: values) - } - kvState = .regular(keys: keys, values: values) - } - } - - queries = queries.transposed(0, 2, 1, 3) - queries = applyRoPE(queries, scalar: currentOffset) - - guard let kvState else { - fatalError("Gemma4 attention expected a KV state") - } - let localMask = gemma4AdjustAttentionMask(mask, keyLength: kvState.sequenceLength) - - // Decode steps that carry an explicit array mask (left-padded batches) - // would otherwise hit the MLX #3384 fused-kernel divergence on 4-bit - // Gemma 4. Route just those through the immune manual fallback; prefill - // (length > 1) and unmasked decode (.none/.causal) keep the fast fused - // kernel. - let useManualMaskedAttention = length == 1 && gemma4MaskIsExplicitArray(localMask) - - let output: MLXArray - switch kvState { - case .regular(let keys, let values): - if useManualMaskedAttention { - output = gemma4MaskedAttentionFallback( - queries: queries, - keys: keys, - values: values, - scale: scale, - mask: localMask - ) - } else { - output = MLXFast.scaledDotProductAttention( - queries: queries, - keys: keys, - values: values, - scale: scale, - mask: localMask - ) - } - case .quantized(let keys, let values, let groupSize, let bits, let mode): - output = quantizedScaledDotProductAttention( - queries: queries, - quantizedKeys: keys, - quantizedValues: values, - scale: scale, - mask: localMask, - groupSize: groupSize, - bits: bits, - mode: mode - ) - } - - return ( - oProj(output.transposed(0, 2, 1, 3).reshaped(batch, length, -1)), - kvState, - currentOffset - ) - } -} - -private final class Gemma4TextDecoderLayer: Module { - let layerType: String - let enableMoE: Bool - - @ModuleInfo(key: "self_attn") var selfAttention: Gemma4TextAttention - @ModuleInfo var mlp: Gemma4TextMLP - @ModuleInfo(key: "input_layernorm") var inputLayerNorm: Gemma4RMSNormZeroShift - @ModuleInfo(key: "post_attention_layernorm") var postAttentionLayerNorm: Gemma4RMSNormZeroShift - @ModuleInfo(key: "pre_feedforward_layernorm") var preFeedforwardLayerNorm: - Gemma4RMSNormZeroShift - @ModuleInfo(key: "post_feedforward_layernorm") var postFeedforwardLayerNorm: - Gemma4RMSNormZeroShift - @ModuleInfo(key: "router") var router: Gemma4TextRouter? - @ModuleInfo(key: "experts") var experts: Gemma4TextExperts? - @ModuleInfo(key: "post_feedforward_layernorm_1") var postFeedforwardLayerNorm1: - Gemma4RMSNormZeroShift? - @ModuleInfo(key: "post_feedforward_layernorm_2") var postFeedforwardLayerNorm2: - Gemma4RMSNormZeroShift? - @ModuleInfo(key: "pre_feedforward_layernorm_2") var preFeedforwardLayerNorm2: - Gemma4RMSNormZeroShift? - @ModuleInfo(key: "per_layer_input_gate") var perLayerInputGate: Linear? - @ModuleInfo(key: "per_layer_projection") var perLayerProjection: Linear? - @ModuleInfo(key: "post_per_layer_input_norm") var postPerLayerInputNorm: Gemma4RMSNormZeroShift? - @ModuleInfo(key: "layer_scalar") var layerScalar: MLXArray - - init(config: Gemma4TextConfiguration, layerIdx: Int) { - self.layerType = config.layerTypes[layerIdx] - self.enableMoE = config.enableMoEBlock - self._selfAttention.wrappedValue = Gemma4TextAttention(config: config, layerIdx: layerIdx) - self._mlp.wrappedValue = Gemma4TextMLP(config: config, layerIdx: layerIdx) - self._inputLayerNorm.wrappedValue = Gemma4RMSNormZeroShift( - dimensions: config.hiddenSize, eps: config.rmsNormEps) - self._postAttentionLayerNorm.wrappedValue = Gemma4RMSNormZeroShift( - dimensions: config.hiddenSize, eps: config.rmsNormEps) - self._preFeedforwardLayerNorm.wrappedValue = Gemma4RMSNormZeroShift( - dimensions: config.hiddenSize, eps: config.rmsNormEps) - self._postFeedforwardLayerNorm.wrappedValue = Gemma4RMSNormZeroShift( - dimensions: config.hiddenSize, eps: config.rmsNormEps) - if config.enableMoEBlock { - self._router.wrappedValue = Gemma4TextRouter(config: config) - self._experts.wrappedValue = Gemma4TextExperts(config: config) - self._postFeedforwardLayerNorm1.wrappedValue = Gemma4RMSNormZeroShift( - dimensions: config.hiddenSize, eps: config.rmsNormEps) - self._postFeedforwardLayerNorm2.wrappedValue = Gemma4RMSNormZeroShift( - dimensions: config.hiddenSize, eps: config.rmsNormEps) - self._preFeedforwardLayerNorm2.wrappedValue = Gemma4RMSNormZeroShift( - dimensions: config.hiddenSize, eps: config.rmsNormEps) - } - if config.hiddenSizePerLayerInput > 0 { - self._perLayerInputGate.wrappedValue = Linear( - config.hiddenSize, config.hiddenSizePerLayerInput, bias: false) - self._perLayerProjection.wrappedValue = Linear( - config.hiddenSizePerLayerInput, config.hiddenSize, bias: false) - self._postPerLayerInputNorm.wrappedValue = Gemma4RMSNormZeroShift( - dimensions: config.hiddenSize, eps: config.rmsNormEps) - } - self._layerScalar.wrappedValue = MLXArray.ones([1]) - super.init() - } - - func callAsFunction( - _ x: MLXArray, - mask: MLXFast.ScaledDotProductAttentionMaskMode = .none, - cache: KVCache? = nil, - perLayerInput: MLXArray? = nil, - sharedKV: Gemma4SharedKVState? = nil, - offset: Int? = nil, - perRowOffset: MLXArray? = nil - ) -> (MLXArray, Gemma4SharedKVState?, Int) { - var residual = x - var h = inputLayerNorm(x) - let (attentionOutput, kvState, attentionOffset) = selfAttention( - h, mask: mask, cache: cache, sharedKV: sharedKV, offset: offset, - perRowOffset: perRowOffset) - h = attentionOutput - h = postAttentionLayerNorm(h) - h = residual + h - - residual = h - if enableMoE, - let router, - let experts, - let postFeedforwardLayerNorm1, - let postFeedforwardLayerNorm2, - let preFeedforwardLayerNorm2 - { - var dense = preFeedforwardLayerNorm(h) - dense = mlp(dense) - dense = postFeedforwardLayerNorm1(dense) - - let (topKIndices, topKWeights) = router(h) - var sparse = preFeedforwardLayerNorm2(h) - sparse = experts(sparse, topKIndices: topKIndices, topKWeights: topKWeights) - sparse = postFeedforwardLayerNorm2(sparse) - - h = dense + sparse - } else { - h = preFeedforwardLayerNorm(h) - h = mlp(h) - } - h = postFeedforwardLayerNorm(h) - h = residual + h - - if let perLayerInputGate, let perLayerProjection, let postPerLayerInputNorm, - let perLayerInput - { - residual = h - var gated = perLayerInputGate(h) - gated = geluApproximate(gated) - gated = gated * perLayerInput - gated = perLayerProjection(gated) - gated = postPerLayerInputNorm(gated) - h = residual + gated - } - - return (h * layerScalar, kvState, attentionOffset) - } -} - -private final class Gemma4TextBackbone: Module { - let config: Gemma4TextConfiguration - let firstKVSharedLayerIdx: Int - let layerIdxToCacheIdx: [Int] - let firstFullCacheIdx: Int - let firstSlidingCacheIdx: Int - /// Last non-shared full/sliding-attention layer indices — the layers whose - /// own K/V the MTP drafter reads (mirrors MLXLLM's capture indices). - let lastFullNonSharedIdx: Int - let lastSlidingNonSharedIdx: Int - let embedScale: Float - let embedTokensPerLayerScale: Float - private let _perLayerInputScale: MLXArray - - @ModuleInfo(key: "embed_tokens") var embedTokens: Embedding - @ModuleInfo(key: "layers") var layers: [Gemma4TextDecoderLayer] - @ModuleInfo(key: "norm") var norm: Gemma4RMSNormZeroShift - @ModuleInfo(key: "embed_tokens_per_layer") var embedTokensPerLayer: Embedding? - @ModuleInfo(key: "per_layer_model_projection") var perLayerModelProjection: Gemma4ScaledLinear? - @ModuleInfo(key: "per_layer_projection_norm") var perLayerProjectionNorm: - Gemma4RMSNormZeroShift? - - init(_ config: Gemma4TextConfiguration) { - self.config = config - self.firstKVSharedLayerIdx = config.hiddenLayers - config.numKVSharedLayers - self.embedScale = pow(Float(config.hiddenSize), 0.5) - self.embedTokensPerLayerScale = pow(Float(max(config.hiddenSizePerLayerInput, 1)), 0.5) - self._perLayerInputScale = rsqrt(MLXArray(2.0)) - - let concreteLayers = Array(config.layerTypes.prefix(firstKVSharedLayerIdx)) - let sharedFullIdx = concreteLayers.lastIndex(of: "full_attention") ?? 0 - let sharedSlidingIdx = concreteLayers.lastIndex(of: "sliding_attention") ?? 0 - - var cacheMap: [Int] = [] - cacheMap.reserveCapacity(config.hiddenLayers) - for (idx, layerType) in config.layerTypes.enumerated() { - if idx < firstKVSharedLayerIdx { - cacheMap.append(idx) - } else { - cacheMap.append(layerType == "full_attention" ? sharedFullIdx : sharedSlidingIdx) - } - } - layerIdxToCacheIdx = cacheMap - firstFullCacheIdx = concreteLayers.firstIndex(of: "full_attention") ?? 0 - firstSlidingCacheIdx = concreteLayers.firstIndex(of: "sliding_attention") ?? 0 - lastFullNonSharedIdx = sharedFullIdx - lastSlidingNonSharedIdx = sharedSlidingIdx - - self._embedTokens.wrappedValue = Embedding( - embeddingCount: config.vocabularySize, dimensions: config.hiddenSize) - self._layers.wrappedValue = (0 ..< config.hiddenLayers).map { - Gemma4TextDecoderLayer(config: config, layerIdx: $0) - } - self._norm.wrappedValue = Gemma4RMSNormZeroShift( - dimensions: config.hiddenSize, eps: config.rmsNormEps) - if config.hiddenSizePerLayerInput > 0 { - self._embedTokensPerLayer.wrappedValue = Embedding( - embeddingCount: config.vocabularySizePerLayerInput, - dimensions: config.hiddenLayers * config.hiddenSizePerLayerInput - ) - self._perLayerModelProjection.wrappedValue = Gemma4ScaledLinear( - inFeatures: config.hiddenSize, - outFeatures: config.hiddenLayers * config.hiddenSizePerLayerInput, - scalar: pow(Float(config.hiddenSize), -0.5) - ) - self._perLayerProjectionNorm.wrappedValue = Gemma4RMSNormZeroShift( - dimensions: config.hiddenSizePerLayerInput, eps: config.rmsNormEps) - } - - super.init() - } - - func getPerLayerInputs(_ inputIds: MLXArray) -> MLXArray { - guard let embedTokensPerLayer else { - fatalError("Per-layer inputs requested for a model without embed_tokens_per_layer") - } - let validMask = - logicalAnd( - inputIds .>= 0, inputIds .< config.vocabularySizePerLayerInput) - let tokens = MLX.where(validMask, inputIds, MLXArray.zeros(like: inputIds)) - var result = embedTokensPerLayer(tokens) - result = (result * MLXArray(embedTokensPerLayerScale, dtype: .float32)).asType(result.dtype) - return result.reshaped( - Array(inputIds.shape) + [config.hiddenLayers, config.hiddenSizePerLayerInput] - ) - } - - func projectPerLayerInputs( - _ inputsEmbeds: MLXArray, perLayerInputs: MLXArray? - ) -> MLXArray? { - guard let perLayerModelProjection, let perLayerProjectionNorm else { - return nil - } - - var perLayerProjection = perLayerModelProjection(inputsEmbeds) - perLayerProjection = perLayerProjection.reshaped( - Array(inputsEmbeds.shape.dropLast()) + [ - config.hiddenLayers, config.hiddenSizePerLayerInput, - ] - ) - perLayerProjection = perLayerProjectionNorm(perLayerProjection) - - guard let perLayerInputs else { - return perLayerProjection - } - - return (perLayerProjection + perLayerInputs) - * _perLayerInputScale.asType(inputsEmbeds.dtype) - } - - func callAsFunction( - _ inputs: MLXArray? = nil, - inputsEmbeds: MLXArray? = nil, - mask: MLXFast.ScaledDotProductAttentionMaskMode? = nil, - cache: [KVCache?]? = nil, - perLayerInputs: MLXArray? = nil, - imageTokenMask: MLXArray? = nil - ) -> MLXArray { - forwardTrunk( - inputs, inputsEmbeds: inputsEmbeds, mask: mask, cache: cache, - perLayerInputs: perLayerInputs, imageTokenMask: imageTokenMask, - captureMTP: false - ).postNorm - } - - /// MTP forward over the shared trunk: returns the post-norm hidden (for the - /// LM head), the pre-norm last hidden (the drafter's `pre_projection` input, - /// matching HF's `hidden_states` capture point), and the last non-shared - /// full/sliding-attention K/V snapshots the drafter attends to next round. - func callForMTP( - _ inputs: MLXArray? = nil, - inputsEmbeds: MLXArray? = nil, - cache: [KVCache?]? = nil, - perLayerInputs: MLXArray? = nil, - imageTokenMask: MLXArray? = nil - ) -> ( - postNorm: MLXArray, preNorm: MLXArray, - full: (MLXArray, MLXArray), sliding: (MLXArray, MLXArray) - ) { - let r = forwardTrunk( - inputs, inputsEmbeds: inputsEmbeds, mask: nil, cache: cache, - perLayerInputs: perLayerInputs, imageTokenMask: imageTokenMask, - captureMTP: true) - return (r.postNorm, r.preNorm!, r.full!, r.sliding!) - } - - private func forwardTrunk( - _ inputs: MLXArray? = nil, - inputsEmbeds: MLXArray? = nil, - mask: MLXFast.ScaledDotProductAttentionMaskMode? = nil, - cache: [KVCache?]? = nil, - perLayerInputs: MLXArray? = nil, - imageTokenMask: MLXArray? = nil, - captureMTP: Bool = false - ) -> ( - postNorm: MLXArray, preNorm: MLXArray?, - full: (MLXArray, MLXArray)?, sliding: (MLXArray, MLXArray)? - ) { - // Tolerate 1D (L,) token inputs / 2D (L, D) embeds by adding the leading - // batch dim. The perLayerInputs indexing path needs 4D shapes and would - // otherwise crash on continuation prefills that build LMInput directly. - // Zero-copy and a no-op for canonical 2D/3D shapes. Upstream 84697ac. - let inputs = inputs.map { $0.ndim == 1 ? $0.expandedDimensions(axis: 0) : $0 } - let inputsEmbeds = inputsEmbeds.map { - $0.ndim == 2 ? $0.expandedDimensions(axis: 0) : $0 - } - - let h0: MLXArray - if let inputsEmbeds { - h0 = inputsEmbeds - } else if let inputs { - let embeddings = embedTokens(inputs) - h0 = (embeddings * MLXArray(embedScale, dtype: .float32)).asType(embeddings.dtype) - } else { - fatalError("Either inputs or inputsEmbeds must be provided") - } - - let processedPerLayerInputs: MLXArray? - if config.hiddenSizePerLayerInput > 0 { - if let perLayerInputs { - processedPerLayerInputs = perLayerInputs - } else if let inputs { - processedPerLayerInputs = getPerLayerInputs(inputs) - } else { - processedPerLayerInputs = nil - } - } else { - processedPerLayerInputs = nil - } - let finalPerLayerInputs = projectPerLayerInputs(h0, perLayerInputs: processedPerLayerInputs) - - let hasExplicitCache = cache != nil - let localCache = - cache ?? Array(repeating: nil as KVCache?, count: max(firstKVSharedLayerIdx, 1)) - let fullMask: MLXFast.ScaledDotProductAttentionMaskMode - let slidingMask: MLXFast.ScaledDotProductAttentionMaskMode - if let mask { - fullMask = mask - slidingMask = mask - } else { - let fullCache = firstFullCacheIdx < localCache.count ? localCache[firstFullCacheIdx] : nil - let slidingCache = firstSlidingCacheIdx < localCache.count - ? localCache[firstSlidingCacheIdx] : nil - - // Gemma 4 applies blockwise bidirectional attention within image-token spans - // during prefill. The overlay needs a materialized boolean mask, so force - // returnArray when it is active. - let useBidirectionalVision = - imageTokenMask != nil - && config.useBidirectionalAttention == "vision" - && h0.dim(1) > 1 - - // Otherwise let `createAttentionMask` choose (symbolic `.causal`, or - // a windowed array on overflow) — identical to the text-only MLXLLM - // tower. Forcing an offset-indexed array mask for every cached - // multi-token chunk silently miscounts after a speculative - // rollback shrinks the cache (the MTP verify pattern), which the - // symbolic causal path handles correctly. Only the vision overlay - // genuinely needs a materialized mask. - var builtFullMask = createAttentionMask( - h: h0, cache: fullCache, returnArray: useBidirectionalVision) - var builtSlidingMask = createAttentionMask( - h: h0, cache: slidingCache, windowSize: config.slidingWindow, - returnArray: useBidirectionalVision) - if useBidirectionalVision, let imageTokenMask { - builtFullMask = gemma4OverlayBidirectionalVision( - builtFullMask, isVision: imageTokenMask) - builtSlidingMask = gemma4OverlayBidirectionalVision( - builtSlidingMask, isVision: imageTokenMask) - } - fullMask = builtFullMask - slidingMask = builtSlidingMask - } - - // Per-row RoPE offsets for continuous batching. Every non-shared layer - // cache holds the same pre-step offset, so capture it once here — before - // any layer's `cache.update` advances it — and thread it into every - // layer (including KV-shared layers, whose queries sit at the same - // positions). nil for non-batched caches (B=1 / vision), which keeps the - // existing scalar-offset path. Fixes mixed-length batch corruption where - // the scalar `cache.offset` (max across rows) mis-positions shorter rows. - let perRowOffset: MLXArray? = localCache.lazy - .compactMap { ($0 as? BatchPositionedKVCache)?.batchOffset } - .first - - var h = h0 - var intermediates = [(kv: Gemma4SharedKVState?, offset: Int?)]( - repeating: (nil, nil), count: config.hiddenLayers) - for (idx, layer) in layers.enumerated() { - let sourceIdx = layerIdxToCacheIdx[idx] - let layerCache: KVCache? = - if idx < firstKVSharedLayerIdx, sourceIdx < localCache.count { - localCache[sourceIdx] - } else { - nil - } - let layerMask = - if layer.layerType == "full_attention" { - fullMask - } else { - slidingMask - } - let layerInput: MLXArray? = - if let finalPerLayerInputs { - finalPerLayerInputs[0..., 0..., idx, 0...] - } else { - nil - } - let (output, kvState, attentionOffset) = layer( - h, - mask: layerMask, - cache: layerCache, - perLayerInput: layerInput, - // Shared-KV layers gate on layer index only, NOT on the presence - // of an explicit cache: no-cache forwards (embedding extraction, - // retrieval, batched eval) must still reuse the source layer's - // K/V or they silently re-project and violate Gemma 4's - // cross-layer KV-sharing invariant. Cached generation is - // unaffected (hasExplicitCache was always true there). Upstream - // d675185. (Our per-row batched offset is preserved below.) - sharedKV: idx >= firstKVSharedLayerIdx - ? intermediates[sourceIdx].kv : nil, - offset: idx >= firstKVSharedLayerIdx - ? intermediates[sourceIdx].offset : nil, - perRowOffset: perRowOffset - ) - h = output - intermediates[idx] = (kvState, attentionOffset) - } - if captureMTP { - func regular(_ state: Gemma4SharedKVState?) -> (MLXArray, MLXArray) { - guard case let .regular(keys, values)? = state else { - fatalError( - "MTP capture requires non-quantized KV caches (got " - + "\(String(describing: state)))") - } - return (keys, values) - } - return ( - norm(h), h, - regular(intermediates[lastFullNonSharedIdx].kv), - regular(intermediates[lastSlidingNonSharedIdx].kv) - ) - } - return (norm(h), nil, nil, nil) - } -} - -private final class Gemma4TextLanguageModel: Module, KVCacheDimensionProvider { - let config: Gemma4TextConfiguration - let finalLogitSoftcapping: Float? - - @ModuleInfo(key: "model") var model: Gemma4TextBackbone - @ModuleInfo(key: "lm_head") var lmHead: Linear? - - var kvHeads: [Int] { - (0 ..< config.hiddenLayers).map { idx in - let layerType = config.layerTypes[idx] - if config.attentionKEqV && layerType == "full_attention" { - return config.globalKVHeads ?? config.kvHeads - } else { - return config.kvHeads - } - } - } - - init(_ config: Gemma4TextConfiguration) { - self.config = config - self.finalLogitSoftcapping = config.finalLogitSoftcapping - self._model.wrappedValue = Gemma4TextBackbone(config) - if !config.tieWordEmbeddings { - self._lmHead.wrappedValue = Linear( - config.hiddenSize, config.vocabularySize, bias: false) - } - super.init() - } + let rmsNormEps: Float + let patchSize: Int + let positionEmbeddingSize: Int + let defaultOutputLength: Int + let poolingKernelSize: Int + let standardize: Bool + let useClippedLinears: Bool + let ropeTheta: Float - func newCache(parameters: GenerateParameters?) -> [any KVCache] { - let slidingWindow = config.slidingWindow > 0 ? config.slidingWindow : 4096 - return config.layerTypes.prefix(config.hiddenLayers - config.numKVSharedLayers).map { - layerType in - if layerType == "full_attention" { - StandardKVCache() - } else { - RotatingKVCache(maxSize: slidingWindow, keep: 0) - } - } + enum CodingKeys: String, CodingKey { + case hiddenSize = "hidden_size" + case intermediateSize = "intermediate_size" + case numHiddenLayers = "num_hidden_layers" + case numAttentionHeads = "num_attention_heads" + case numKeyValueHeads = "num_key_value_heads" + case headDim = "head_dim" + case rmsNormEps = "rms_norm_eps" + case patchSize = "patch_size" + case positionEmbeddingSize = "position_embedding_size" + case defaultOutputLength = "default_output_length" + case poolingKernelSize = "pooling_kernel_size" + case standardize + case useClippedLinears = "use_clipped_linears" } - func prefillBackbone( - _ inputs: MLXArray? = nil, - cache: [KVCache]? = nil, - inputsEmbeds: MLXArray? = nil, - perLayerInputs: MLXArray? = nil, - mask: MLXFast.ScaledDotProductAttentionMaskMode? = nil, - imageTokenMask: MLXArray? = nil - ) -> MLXArray { - model( - inputs, inputsEmbeds: inputsEmbeds, mask: mask, cache: cache?.map { $0 as KVCache? }, - perLayerInputs: perLayerInputs, imageTokenMask: imageTokenMask - ) + enum TopKeys: String, CodingKey { + case ropeParameters = "rope_parameters" } - private func projectToLogits(_ output: MLXArray) -> MLXArray { - let logits: MLXArray - if let lmHead { - logits = lmHead(output) + public init(from decoder: Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + hiddenSize = try c.decodeIfPresent(Int.self, forKey: .hiddenSize) ?? 768 + intermediateSize = try c.decodeIfPresent(Int.self, forKey: .intermediateSize) ?? 3072 + numHiddenLayers = try c.decodeIfPresent(Int.self, forKey: .numHiddenLayers) ?? 16 + numAttentionHeads = try c.decodeIfPresent(Int.self, forKey: .numAttentionHeads) ?? 12 + numKeyValueHeads = try c.decodeIfPresent(Int.self, forKey: .numKeyValueHeads) ?? 12 + headDim = try c.decodeIfPresent(Int.self, forKey: .headDim) ?? 64 + rmsNormEps = try c.decodeIfPresent(Float.self, forKey: .rmsNormEps) ?? 1e-6 + patchSize = try c.decodeIfPresent(Int.self, forKey: .patchSize) ?? 16 + positionEmbeddingSize = try c.decodeIfPresent(Int.self, forKey: .positionEmbeddingSize) ?? 10240 + defaultOutputLength = try c.decodeIfPresent(Int.self, forKey: .defaultOutputLength) ?? 280 + poolingKernelSize = try c.decodeIfPresent(Int.self, forKey: .poolingKernelSize) ?? 3 + standardize = try c.decodeIfPresent(Bool.self, forKey: .standardize) ?? false + useClippedLinears = try c.decodeIfPresent(Bool.self, forKey: .useClippedLinears) ?? false + + if let rc = try? decoder.container(keyedBy: TopKeys.self), + let rp = try? rc.decodeIfPresent([String: StringOrNumber].self, forKey: .ropeParameters), + let t = rp["rope_theta"]?.asFloat() + { + ropeTheta = t } else { - logits = model.embedTokens.asLinear(output) - } - if let finalLogitSoftcapping, finalLogitSoftcapping > 0 { - let scale = MLXArray(finalLogitSoftcapping) - return tanh(logits / scale) * scale + ropeTheta = 100.0 } - return logits } +} - func callAsFunction( - _ inputs: MLXArray? = nil, - cache: [KVCache]? = nil, - inputsEmbeds: MLXArray? = nil, - perLayerInputs: MLXArray? = nil, - mask: MLXFast.ScaledDotProductAttentionMaskMode? = nil, - imageTokenMask: MLXArray? = nil - ) -> LMOutput { - LMOutput(logits: projectToLogits( - prefillBackbone( - inputs, cache: cache, inputsEmbeds: inputsEmbeds, - perLayerInputs: perLayerInputs, mask: mask, imageTokenMask: imageTokenMask))) - } +/// Inline text config for VLM — mirrors MLXLLM's Gemma4TextConfiguration +struct G4TextConfig: Codable, Sendable { + let hiddenSize: Int + let numHiddenLayers: Int + let numAttentionHeads: Int + let numKeyValueHeads: Int + let numGlobalKeyValueHeads: Int? + let headDim: Int + let globalHeadDim: Int + let intermediateSize: Int + let vocabSize: Int + let rmsNormEps: Float + let slidingWindow: Int + let layerTypes: [String] + let finalLogitSoftcapping: Float? + let tieWordEmbeddings: Bool + let attentionBias: Bool + let attentionKEqV: Bool + let hiddenSizePerLayerInput: Int + let vocabSizePerLayerInput: Int + let numKvSharedLayers: Int + let useDoubleWideMlp: Bool + let enableMoeBlock: Bool + let moeIntermediateSize: Int + let numExperts: Int + let topKExperts: Int + let ropeTraditional: Bool + let ropeParameters: [String: [String: StringOrNumber]] - /// MTP forward producing logits, the pre-norm last hidden, and the last - /// non-shared full/sliding K/V snapshots. Handles both text-token decode - /// (`inputs`) and the multimodal prefill (`inputsEmbeds` + `perLayerInputs` - /// + `imageTokenMask`). - func forwardForMTP( - _ inputs: MLXArray? = nil, - cache: [KVCache], - inputsEmbeds: MLXArray? = nil, - perLayerInputs: MLXArray? = nil, - imageTokenMask: MLXArray? = nil - ) -> ( - logits: MLXArray, lastHidden: MLXArray, - full: (MLXArray, MLXArray), sliding: (MLXArray, MLXArray) - ) { - let r = model.callForMTP( - inputs, inputsEmbeds: inputsEmbeds, cache: cache.map { $0 as KVCache? }, - perLayerInputs: perLayerInputs, imageTokenMask: imageTokenMask) - return (projectToLogits(r.postNorm), r.preNorm, r.full, r.sliding) + enum CodingKeys: String, CodingKey { + case hiddenSize = "hidden_size" + case numHiddenLayers = "num_hidden_layers" + case numAttentionHeads = "num_attention_heads" + case numKeyValueHeads = "num_key_value_heads" + case numGlobalKeyValueHeads = "num_global_key_value_heads" + case headDim = "head_dim" + case globalHeadDim = "global_head_dim" + case intermediateSize = "intermediate_size" + case vocabSize = "vocab_size" + case rmsNormEps = "rms_norm_eps" + case slidingWindow = "sliding_window" + case layerTypes = "layer_types" + case finalLogitSoftcapping = "final_logit_softcapping" + case tieWordEmbeddings = "tie_word_embeddings" + case attentionBias = "attention_bias" + case attentionKEqV = "attention_k_eq_v" + case hiddenSizePerLayerInput = "hidden_size_per_layer_input" + case vocabSizePerLayerInput = "vocab_size_per_layer_input" + case numKvSharedLayers = "num_kv_shared_layers" + case useDoubleWideMlp = "use_double_wide_mlp" + case enableMoeBlock = "enable_moe_block" + case moeIntermediateSize = "moe_intermediate_size" + case numExperts = "num_experts" + case topKExperts = "top_k_experts" + case ropeTraditional = "rope_traditional" + case ropeParameters = "rope_parameters" } - func sanitize(weights: [String: MLXArray]) -> [String: MLXArray] { - var sanitized: [String: MLXArray] = [:] - sanitized.reserveCapacity(weights.count + 1) - - for (key, value) in weights { - if key.contains("rotary_emb") { - continue - } - - var newKey = key - if newKey.hasPrefix("model.") { - newKey.removeFirst("model.".count) - } - if newKey.hasPrefix("language_model."), - !newKey.hasPrefix("language_model.model."), - !newKey.hasPrefix("language_model.lm_head.") - { - let rest = String(newKey.dropFirst("language_model.".count)) - newKey = "language_model.model.\(rest)" - } - - if newKey.hasSuffix(".experts.down_proj") { - newKey = newKey.replacingOccurrences( - of: ".experts.down_proj", - with: ".experts.switch_glu.down_proj.weight" - ) - } - - if newKey.hasSuffix(".experts.gate_up_proj") { - let mid = value.dim(-2) / 2 - sanitized[ - newKey.replacingOccurrences( - of: ".experts.gate_up_proj", - with: ".experts.switch_glu.gate_proj.weight" - ) - ] = value[.ellipsis, ..