diff --git a/Libraries/MLXLLM/Models/AfMoE.swift b/Libraries/MLXLLM/Models/AfMoE.swift index 30b64c096a..0c0c340645 100644 --- a/Libraries/MLXLLM/Models/AfMoE.swift +++ b/Libraries/MLXLLM/Models/AfMoE.swift @@ -197,13 +197,8 @@ class AfMoEAttention: Module { // Apply RoPE only for local (sliding window) attention if isLocalAttention, let rope = rope { - if let cache = cache { - queries = rope(queries, offset: cache.offset) - keys = rope(keys, offset: cache.offset) - } else { - queries = rope(queries, offset: 0) - keys = rope(keys, offset: 0) - } + queries = applyRotaryPosition(rope, to: queries, cache: cache) + keys = applyRotaryPosition(rope, to: keys, cache: cache) } var output = attentionWithCacheUpdate( diff --git a/Libraries/MLXLLM/Models/Apertus.swift b/Libraries/MLXLLM/Models/Apertus.swift index 0f7f27bc6b..ed107b772a 100644 --- a/Libraries/MLXLLM/Models/Apertus.swift +++ b/Libraries/MLXLLM/Models/Apertus.swift @@ -223,17 +223,14 @@ private class ApertusAttention: Module { values = values.transposed(0, 2, 1, 3) // 4. RoPE - if let cache = cache { - queries = rope(queries, offset: cache.offset) - keys = rope(keys, offset: cache.offset) + queries = applyRotaryPosition(rope, to: queries, cache: cache) + keys = applyRotaryPosition(rope, to: keys, cache: cache) + if let cache = cache { // Update cache (expects [B, H, L, D]) let (k, v) = cache.update(keys: keys, values: values) keys = k values = v - } else { - queries = rope(queries, offset: 0) - keys = rope(keys, offset: 0) } // 5. Attention (SDPA expects [B, H, L, D]) diff --git a/Libraries/MLXLLM/Models/BaichuanM1.swift b/Libraries/MLXLLM/Models/BaichuanM1.swift index 20a7d330d7..c480c9c9e9 100644 --- a/Libraries/MLXLLM/Models/BaichuanM1.swift +++ b/Libraries/MLXLLM/Models/BaichuanM1.swift @@ -113,12 +113,11 @@ class BaichuanM1Attention: Module { var keys = qkv[1].reshaped(B, L, numKVHeads, headDim).transposed(0, 2, 1, 3) var values = qkv[2].reshaped(B, L, numKVHeads, headDim).transposed(0, 2, 1, 3) - var offset = 0 var lastK: MLXArray? = nil var lastV: MLXArray? = nil + let kvSubCache: KVCache? = (cache as? CacheList)?[1] if let cacheList = cache as? CacheList { - offset = cacheList[1].offset if let mambaCache = cacheList[0] as? MambaCache { lastK = mambaCache[0] lastV = mambaCache[1] @@ -131,8 +130,8 @@ class BaichuanM1Attention: Module { keys = customConvolution(keys, convK, state: lastK) values = customConvolution(values, convV, state: lastV) - queries = rope(queries, offset: offset) - keys = rope(keys, offset: offset) + queries = applyRotaryPosition(rope, to: queries, cache: kvSubCache) + keys = applyRotaryPosition(rope, to: keys, cache: kvSubCache) if let cache = cache as? CacheList { let kvCache = cache[1] diff --git a/Libraries/MLXLLM/Models/BailingMoe.swift b/Libraries/MLXLLM/Models/BailingMoe.swift index 2e7ee0ca18..ebd0627476 100644 --- a/Libraries/MLXLLM/Models/BailingMoe.swift +++ b/Libraries/MLXLLM/Models/BailingMoe.swift @@ -145,13 +145,8 @@ class BailingMoeAttention: Module { keys = keys.transposed(0, 2, 1, 3) values = values.reshaped(B, L, kvHeads, -1).transposed(0, 2, 1, 3) - if let cache { - queries = rope(queries, offset: cache.offset) - keys = rope(keys, offset: cache.offset) - } else { - queries = rope(queries, offset: 0) - keys = rope(keys, offset: 0) - } + queries = applyRotaryPosition(rope, to: queries, cache: cache) + keys = applyRotaryPosition(rope, to: keys, cache: cache) let output = attentionWithCacheUpdate( queries: queries, diff --git a/Libraries/MLXLLM/Models/Bitnet.swift b/Libraries/MLXLLM/Models/Bitnet.swift index e28aedca23..067aa5ed20 100644 --- a/Libraries/MLXLLM/Models/Bitnet.swift +++ b/Libraries/MLXLLM/Models/Bitnet.swift @@ -315,13 +315,11 @@ class BitnetAttention: Module { keys = keys.reshaped(B, L, args.resolvedKvHeads, -1).transposed(0, 2, 1, 3) values = values.reshaped(B, L, args.resolvedKvHeads, -1).transposed(0, 2, 1, 3) + queries = applyRotaryPosition(rope, to: queries, cache: cache) + keys = applyRotaryPosition(rope, to: keys, cache: cache) + if let cache { - queries = rope(queries, offset: cache.offset) - keys = rope(keys, offset: cache.offset) (keys, values) = cache.update(keys: keys, values: values) - } else { - queries = rope(queries, offset: 0) - keys = rope(keys, offset: 0) } let output = MLXFast.scaledDotProductAttention( diff --git a/Libraries/MLXLLM/Models/Cohere.swift b/Libraries/MLXLLM/Models/Cohere.swift index 03b6cf435c..eb2e109e6a 100644 --- a/Libraries/MLXLLM/Models/Cohere.swift +++ b/Libraries/MLXLLM/Models/Cohere.swift @@ -50,13 +50,8 @@ class CohereAttention: Module { keys = keys.reshaped(B, L, args.kvHeads, -1).transposed(0, 2, 1, 3) values = values.reshaped(B, L, args.kvHeads, -1).transposed(0, 2, 1, 3) - if let cache { - queries = rope(queries, offset: cache.offset) - keys = rope(keys, offset: cache.offset) - } else { - queries = rope(queries) - keys = rope(keys) - } + queries = applyRotaryPosition(rope, to: queries, cache: cache) + keys = applyRotaryPosition(rope, to: keys, cache: cache) let output = attentionWithCacheUpdate( queries: queries, diff --git a/Libraries/MLXLLM/Models/DeepseekV3.swift b/Libraries/MLXLLM/Models/DeepseekV3.swift index 0f0cd50287..e20fdbe649 100644 --- a/Libraries/MLXLLM/Models/DeepseekV3.swift +++ b/Libraries/MLXLLM/Models/DeepseekV3.swift @@ -197,17 +197,15 @@ class DeepseekV3Attention: Module { var (kNope, values) = (splitKv[0], splitKv[1]) + qPe = applyRotaryPosition(rope, to: qPe, cache: cache) + kPe = applyRotaryPosition(rope, to: kPe, cache: cache) + kPe = repeated(kPe, count: numHeads, axis: 1) + var keys: MLXArray if let cache = cache { - qPe = self.rope(qPe, offset: cache.offset) - kPe = self.rope(kPe, offset: cache.offset) - kPe = repeated(kPe, count: numHeads, axis: 1) (keys, values) = cache.update( keys: concatenated([kNope, kPe], axis: -1), values: values) } else { - qPe = self.rope(qPe, offset: 0) - kPe = self.rope(kPe, offset: 0) - kPe = repeated(kPe, count: numHeads, axis: 1) keys = concatenated([kNope, kPe], axis: -1) } diff --git a/Libraries/MLXLLM/Models/Ernie4_5.swift b/Libraries/MLXLLM/Models/Ernie4_5.swift index be14cb08fd..23f753a52f 100644 --- a/Libraries/MLXLLM/Models/Ernie4_5.swift +++ b/Libraries/MLXLLM/Models/Ernie4_5.swift @@ -104,13 +104,8 @@ class Ernie45Attention: Module { keys = keys.reshaped(B, L, nKVHeads, -1).transposed(0, 2, 1, 3) values = values.reshaped(B, L, nKVHeads, -1).transposed(0, 2, 1, 3) - if let cache { - queries = rope(queries, offset: cache.offset) - keys = rope(keys, offset: cache.offset) - } else { - queries = rope(queries, offset: 0) - keys = rope(keys, offset: 0) - } + queries = applyRotaryPosition(rope, to: queries, cache: cache) + keys = applyRotaryPosition(rope, to: keys, cache: cache) let output = attentionWithCacheUpdate( queries: queries, diff --git a/Libraries/MLXLLM/Models/Exaone4.swift b/Libraries/MLXLLM/Models/Exaone4.swift index 6918605c2e..d99fc58554 100644 --- a/Libraries/MLXLLM/Models/Exaone4.swift +++ b/Libraries/MLXLLM/Models/Exaone4.swift @@ -71,12 +71,9 @@ class Exaone4Attention: Module { keys = kNorm(keys.reshaped(B, L, args.kvHeads, -1)).transposed(0, 2, 1, 3) values = values.reshaped(B, L, args.kvHeads, -1).transposed(0, 2, 1, 3) - if let cache, useRope, let rope { - queries = rope(queries, offset: cache.offset) - keys = rope(keys, offset: cache.offset) - } else if useRope, let rope { - queries = rope(queries, offset: 0) - keys = rope(keys, offset: 0) + if useRope, let rope { + queries = applyRotaryPosition(rope, to: queries, cache: cache) + keys = applyRotaryPosition(rope, to: keys, cache: cache) } let output = attentionWithCacheUpdate( diff --git a/Libraries/MLXLLM/Models/FalconH1.swift b/Libraries/MLXLLM/Models/FalconH1.swift index 48af10f338..efbce762d8 100644 --- a/Libraries/MLXLLM/Models/FalconH1.swift +++ b/Libraries/MLXLLM/Models/FalconH1.swift @@ -302,13 +302,11 @@ class FalconH1Attention: Module { keys = keys.reshaped(B, L, numKVHeads, -1).transposed(0, 2, 1, 3) values = values.reshaped(B, L, numKVHeads, -1).transposed(0, 2, 1, 3) + queries = applyRotaryPosition(rope, to: queries, cache: cache) + keys = applyRotaryPosition(rope, to: keys, cache: cache) + if let cache { - queries = rope(queries, offset: cache.offset) - keys = rope(keys, offset: cache.offset) (keys, values) = cache.update(keys: keys, values: values) - } else { - queries = rope(queries, offset: 0) - keys = rope(keys, offset: 0) } var output = MLXFast.scaledDotProductAttention( diff --git a/Libraries/MLXLLM/Models/GLM4.swift b/Libraries/MLXLLM/Models/GLM4.swift index bc185a862d..22c4a90316 100644 --- a/Libraries/MLXLLM/Models/GLM4.swift +++ b/Libraries/MLXLLM/Models/GLM4.swift @@ -55,13 +55,8 @@ class GLM4Attention: Module { keys = keys.reshaped(B, L, args.kvHeads, -1).transposed(0, 2, 1, 3) values = values.reshaped(B, L, args.kvHeads, -1).transposed(0, 2, 1, 3) - if let cache { - queries = rope(queries, offset: cache.offset) - keys = rope(keys, offset: cache.offset) - } else { - queries = rope(queries, offset: 0) - keys = rope(keys, offset: 0) - } + queries = applyRotaryPosition(rope, to: queries, cache: cache) + keys = applyRotaryPosition(rope, to: keys, cache: cache) let output = attentionWithCacheUpdate( queries: queries, diff --git a/Libraries/MLXLLM/Models/GLM4MOE.swift b/Libraries/MLXLLM/Models/GLM4MOE.swift index 3487a4d233..02ac0682c2 100644 --- a/Libraries/MLXLLM/Models/GLM4MOE.swift +++ b/Libraries/MLXLLM/Models/GLM4MOE.swift @@ -70,13 +70,8 @@ class GLM4MoEAttention: Module { keys = keys.transposed(0, 2, 1, 3) values = values.reshaped(B, L, args.kvHeads, -1).transposed(0, 2, 1, 3) - if let cache { - queries = rope(queries, offset: cache.offset) - keys = rope(keys, offset: cache.offset) - } else { - queries = rope(queries, offset: 0) - keys = rope(keys, offset: 0) - } + queries = applyRotaryPosition(rope, to: queries, cache: cache) + keys = applyRotaryPosition(rope, to: keys, cache: cache) let output = attentionWithCacheUpdate( queries: queries, diff --git a/Libraries/MLXLLM/Models/GLM4MOELite.swift b/Libraries/MLXLLM/Models/GLM4MOELite.swift index a686fddca8..e48df0d0f6 100644 --- a/Libraries/MLXLLM/Models/GLM4MOELite.swift +++ b/Libraries/MLXLLM/Models/GLM4MOELite.swift @@ -254,9 +254,8 @@ class GLM4MoELiteAttention: Module { kPe = kPe.reshaped(B, L, 1, qkRopeHeadDim).transposed(0, 2, 1, 3) var kvLatent = kvALayerNorm(compressedKv) - let offset = cache?.offset ?? 0 - qPe = rope(qPe, offset: offset) - kPe = rope(kPe, offset: offset) + 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) diff --git a/Libraries/MLXLLM/Models/GPTOSS.swift b/Libraries/MLXLLM/Models/GPTOSS.swift index 1a317015d2..f8ca2bcfca 100644 --- a/Libraries/MLXLLM/Models/GPTOSS.swift +++ b/Libraries/MLXLLM/Models/GPTOSS.swift @@ -229,13 +229,8 @@ class AttentionBlock: Module { if sinksActive { fatalError("Quantized attention does not support non-zero sinks.") } - if qcache.offset == 0 { - q = rope(q) - k = rope(k) - } else { - q = rope(q, offset: qcache.offset) - k = rope(k, offset: qcache.offset) - } + q = applyRotaryPosition(rope, to: q, cache: cache) + k = applyRotaryPosition(rope, to: k, cache: cache) let (qKeys, qValues) = qcache.updateQuantized(keys: k, values: v) let vHat = quantizedScaledDotProductAttention( @@ -252,13 +247,11 @@ class AttentionBlock: Module { return oProj(vHat.swappedAxes(1, 2).reshaped(B, L, -1)) } + q = applyRotaryPosition(rope, to: q, cache: cache) + k = applyRotaryPosition(rope, to: k, cache: cache) + if let cache { - q = rope(q, offset: cache.offset) - k = rope(k, offset: cache.offset) (k, v) = cache.update(keys: k, values: v) - } else { - q = rope(q) - k = rope(k) } let vHat = MLXFast.scaledDotProductAttention( diff --git a/Libraries/MLXLLM/Models/Gemma.swift b/Libraries/MLXLLM/Models/Gemma.swift index 2c9dee8eb6..646460af20 100644 --- a/Libraries/MLXLLM/Models/Gemma.swift +++ b/Libraries/MLXLLM/Models/Gemma.swift @@ -68,13 +68,8 @@ class GemmaAttention: Module { keys = keys.reshaped(B, L, nKVHeads, -1).transposed(0, 2, 1, 3) values = values.reshaped(B, L, nKVHeads, -1).transposed(0, 2, 1, 3) - if let cache { - queries = rope(queries, offset: cache.offset) - keys = rope(keys, offset: cache.offset) - } else { - queries = rope(queries) - keys = rope(keys) - } + queries = applyRotaryPosition(rope, to: queries, cache: cache) + keys = applyRotaryPosition(rope, to: keys, cache: cache) let output = attentionWithCacheUpdate( queries: queries, diff --git a/Libraries/MLXLLM/Models/Gemma2.swift b/Libraries/MLXLLM/Models/Gemma2.swift index eaf30b23e6..cad04509d1 100644 --- a/Libraries/MLXLLM/Models/Gemma2.swift +++ b/Libraries/MLXLLM/Models/Gemma2.swift @@ -54,13 +54,11 @@ class Gemma2Attention: Module { keys = keys.reshaped(B, L, nKVHeads, -1).transposed(0, 2, 1, 3) values = values.reshaped(B, L, nKVHeads, -1).transposed(0, 2, 1, 3) + queries = applyRotaryPosition(rope, to: queries, cache: cache) + keys = applyRotaryPosition(rope, to: keys, cache: cache) + if let cache { - queries = rope(queries, offset: cache.offset) - keys = rope(keys, offset: cache.offset) (keys, values) = cache.update(keys: keys, values: values) - } else { - queries = rope(queries) - keys = rope(keys) } queries = queries * self.scale diff --git a/Libraries/MLXLLM/Models/Gemma3Text.swift b/Libraries/MLXLLM/Models/Gemma3Text.swift index cef72fc889..df1eab41f0 100644 --- a/Libraries/MLXLLM/Models/Gemma3Text.swift +++ b/Libraries/MLXLLM/Models/Gemma3Text.swift @@ -140,7 +140,7 @@ class Gemma3Attention: Module { @ModuleInfo(key: "q_norm") var queryNorm: Gemma.RMSNorm @ModuleInfo(key: "k_norm") var keyNorm: Gemma.RMSNorm - @ModuleInfo var rope: OffsetLayer + @ModuleInfo var rope: RoPELayer init(_ config: Gemma3TextConfiguration, layerIdx: Int) { let dim = config.hiddenSize @@ -197,13 +197,8 @@ class Gemma3Attention: Module { queries = queryNorm(queries) keys = keyNorm(keys) - if let cache { - queries = rope(queries, offset: cache.offset) - keys = rope(keys, offset: cache.offset) - } else { - queries = rope(queries, offset: 0) - keys = rope(keys, offset: 0) - } + queries = applyRotaryPosition(rope, to: queries, cache: cache) + keys = applyRotaryPosition(rope, to: keys, cache: cache) let output = attentionWithCacheUpdate( queries: queries, diff --git a/Libraries/MLXLLM/Models/Gemma3nText.swift b/Libraries/MLXLLM/Models/Gemma3nText.swift index 19f244effd..727aeb1227 100644 --- a/Libraries/MLXLLM/Models/Gemma3nText.swift +++ b/Libraries/MLXLLM/Models/Gemma3nText.swift @@ -212,7 +212,7 @@ class Gemma3nAttention: Module { @ModuleInfo(key: "q_norm") var qNorm: RMSNorm @ModuleInfo(key: "k_norm") var kNorm: RMSNorm @ModuleInfo(key: "v_norm") var vNorm: RMSNoScale - @ModuleInfo var rope: OffsetLayer + @ModuleInfo var rope: RoPELayer init(_ config: Gemma3nTextConfiguration, layerIdx: Int) { let layerTypes = @@ -263,13 +263,6 @@ class Gemma3nAttention: Module { queries = queries.reshaped(B, L, -1, headDim) queries = qNorm(queries) - let offset = - if isKvSharedLayer && cache != nil { - cache!.offset - } else { - cache?.offset ?? 0 - } - var keys: MLXArray var values: MLXArray @@ -282,7 +275,7 @@ class Gemma3nAttention: Module { keys = kProj(x).reshaped(B, L, -1, headDim) keys = kNorm(keys) keys = keys.transposed(0, 2, 1, 3) - keys = rope(keys, offset: offset) + keys = applyRotaryPosition(rope, to: keys, cache: cache) values = vProj(x).reshaped(B, L, -1, headDim) values = vNorm(values) @@ -296,7 +289,7 @@ class Gemma3nAttention: Module { keys = kProj(x).reshaped(B, L, -1, headDim) keys = kNorm(keys) keys = keys.transposed(0, 2, 1, 3) - keys = rope(keys, offset: offset) + keys = applyRotaryPosition(rope, to: keys, cache: cache) values = vProj(x).reshaped(B, L, -1, headDim) values = vNorm(values) @@ -308,7 +301,7 @@ class Gemma3nAttention: Module { } queries = queries.transposed(0, 2, 1, 3) - queries = rope(queries, offset: offset) + queries = applyRotaryPosition(rope, to: queries, cache: cache) var adjustedMask = mask if case .array(let maskArray) = mask { diff --git a/Libraries/MLXLLM/Models/Granite.swift b/Libraries/MLXLLM/Models/Granite.swift index 5fa685be59..a2ee21f191 100644 --- a/Libraries/MLXLLM/Models/Granite.swift +++ b/Libraries/MLXLLM/Models/Granite.swift @@ -59,13 +59,8 @@ class GraniteAttention: Module { keys = keys.reshaped(B, L, args.kvHeads, -1).transposed(0, 2, 1, 3) values = values.reshaped(B, L, args.kvHeads, -1).transposed(0, 2, 1, 3) - if let cache { - queries = rope(queries, offset: cache.offset) - keys = rope(keys, offset: cache.offset) - } else { - queries = rope(queries, offset: 0) - keys = rope(keys, offset: 0) - } + queries = applyRotaryPosition(rope, to: queries, cache: cache) + keys = applyRotaryPosition(rope, to: keys, cache: cache) let output = attentionWithCacheUpdate( queries: queries, diff --git a/Libraries/MLXLLM/Models/GraniteMoeHybrid.swift b/Libraries/MLXLLM/Models/GraniteMoeHybrid.swift index a8931a0a80..54aa9922b6 100644 --- a/Libraries/MLXLLM/Models/GraniteMoeHybrid.swift +++ b/Libraries/MLXLLM/Models/GraniteMoeHybrid.swift @@ -245,13 +245,8 @@ class GraniteMoeHybridAttention: Module { values = values.reshaped(B, L, args.kvHeads, headDim).transposed(0, 2, 1, 3) if let rope { - if let cache { - queries = rope(queries, offset: cache.offset) - keys = rope(keys, offset: cache.offset) - } else { - queries = rope(queries, offset: 0) - keys = rope(keys, offset: 0) - } + queries = applyRotaryPosition(rope, to: queries, cache: cache) + keys = applyRotaryPosition(rope, to: keys, cache: cache) } let output = attentionWithCacheUpdate( diff --git a/Libraries/MLXLLM/Models/Internlm2.swift b/Libraries/MLXLLM/Models/Internlm2.swift index 6620d3f99b..a2529384eb 100644 --- a/Libraries/MLXLLM/Models/Internlm2.swift +++ b/Libraries/MLXLLM/Models/Internlm2.swift @@ -9,7 +9,7 @@ import MLXNN // Port of https://github.com/maiqingqiang/mlx-examples/blob/main/llms/mlx_lm/models/internlm2.py -class Internlm2DynamicNTKScalingRoPE: Module { +class Internlm2DynamicNTKScalingRoPE: Module, OffsetLayer, ArrayOffsetLayer { let dims: Int let maxPositionEmbeddings: Int let traditional: Bool @@ -27,14 +27,25 @@ class Internlm2DynamicNTKScalingRoPE: Module { self.scale = scale } - func callAsFunction(_ x: MLXArray, offset: Int = 0) -> MLXArray { - let seqLen = x.dim(1) + offset + private func computeBase(seqLen: Int) -> Float { var base = originalBase if seqLen > maxPositionEmbeddings { base *= pow( (scale * Float(seqLen) / Float(maxPositionEmbeddings)) - (scale - 1), Float(dims) / Float(dims - 2)) } + return base + } + + public func callAsFunction(_ x: MLXArray, offset: Int = 0) -> MLXArray { + let base = computeBase(seqLen: x.dim(1) + offset) + return MLXFast.RoPE( + x, dimensions: dims, traditional: traditional, base: base, scale: scale, offset: offset) + } + + public func callAsFunction(_ x: MLXArray, offset: MLXArray) -> MLXArray { + let maxOffset = offset.max().item(Int.self) + let base = computeBase(seqLen: x.dim(1) + maxOffset) return MLXFast.RoPE( x, dimensions: dims, traditional: traditional, base: base, scale: scale, offset: offset) } @@ -108,13 +119,8 @@ class Internlm2Attention: Module { keys = keys.reshaped(B, L, args.kvHeads, -1).transposed(0, 2, 1, 3) values = values.reshaped(B, L, args.kvHeads, -1).transposed(0, 2, 1, 3) - if let cache { - queries = rope(queries, offset: cache.offset) - keys = rope(keys, offset: cache.offset) - } else { - queries = rope(queries) - keys = rope(keys) - } + queries = applyRotaryPosition(rope, to: queries, cache: cache) + keys = applyRotaryPosition(rope, to: keys, cache: cache) let output = attentionWithCacheUpdate( queries: queries, diff --git a/Libraries/MLXLLM/Models/LFM2.swift b/Libraries/MLXLLM/Models/LFM2.swift index d25ea82dbe..8d7fc1b45e 100644 --- a/Libraries/MLXLLM/Models/LFM2.swift +++ b/Libraries/MLXLLM/Models/LFM2.swift @@ -157,13 +157,8 @@ class LFM2Attention: Module { keys = kLayerNorm(keys.reshaped(B, L, args.kvHeads, -1)).transposed(0, 2, 1, 3) values = values.reshaped(B, L, args.kvHeads, -1).transposed(0, 2, 1, 3) - if let cache { - queries = rope(queries, offset: cache.offset) - keys = rope(keys, offset: cache.offset) - } else { - queries = rope(queries) - keys = rope(keys) - } + queries = applyRotaryPosition(rope, to: queries, cache: cache) + keys = applyRotaryPosition(rope, to: keys, cache: cache) let output = attentionWithCacheUpdate( queries: queries, diff --git a/Libraries/MLXLLM/Models/LFM2MoE.swift b/Libraries/MLXLLM/Models/LFM2MoE.swift index 7e505f6da8..fcefb2e017 100644 --- a/Libraries/MLXLLM/Models/LFM2MoE.swift +++ b/Libraries/MLXLLM/Models/LFM2MoE.swift @@ -154,13 +154,8 @@ class LFM2MoEAttention: Module { keys = kLayerNorm(keys.reshaped(B, L, args.kvHeads, -1)).transposed(0, 2, 1, 3) values = values.reshaped(B, L, args.kvHeads, -1).transposed(0, 2, 1, 3) - if let cache { - queries = rope(queries, offset: cache.offset) - keys = rope(keys, offset: cache.offset) - } else { - queries = rope(queries) - keys = rope(keys) - } + queries = applyRotaryPosition(rope, to: queries, cache: cache) + keys = applyRotaryPosition(rope, to: keys, cache: cache) let output = attentionWithCacheUpdate( queries: queries, diff --git a/Libraries/MLXLLM/Models/Lille130m.swift b/Libraries/MLXLLM/Models/Lille130m.swift index 2014bb42bc..4fc3ff5354 100644 --- a/Libraries/MLXLLM/Models/Lille130m.swift +++ b/Libraries/MLXLLM/Models/Lille130m.swift @@ -66,13 +66,8 @@ final class Lille130mAttention: Module { values = values.reshaped(B, L, args.kvHeads, -1).transposed(0, 2, 1, 3) // Apply RoPE with cache-aware offset if available - if let cache { - queries = rope(queries, offset: cache.offset) - keys = rope(keys, offset: cache.offset) - } else { - queries = rope(queries) - keys = rope(keys) - } + queries = applyRotaryPosition(rope, to: queries, cache: cache) + keys = applyRotaryPosition(rope, to: keys, cache: cache) let output = attentionWithCacheUpdate( queries: queries, diff --git a/Libraries/MLXLLM/Models/Llama.swift b/Libraries/MLXLLM/Models/Llama.swift index b81ab75450..e4479b6bc7 100644 --- a/Libraries/MLXLLM/Models/Llama.swift +++ b/Libraries/MLXLLM/Models/Llama.swift @@ -55,13 +55,8 @@ class LlamaAttention: Module { keys = keys.reshaped(B, L, args.kvHeads, -1).transposed(0, 2, 1, 3) values = values.reshaped(B, L, args.kvHeads, -1).transposed(0, 2, 1, 3) - if let cache { - queries = rope(queries, offset: cache.offset) - keys = rope(keys, offset: cache.offset) - } else { - queries = rope(queries, offset: 0) - keys = rope(keys, offset: 0) - } + queries = applyRotaryPosition(rope, to: queries, cache: cache) + keys = applyRotaryPosition(rope, to: keys, cache: cache) let output = attentionWithCacheUpdate( queries: queries, diff --git a/Libraries/MLXLLM/Models/MiMo.swift b/Libraries/MLXLLM/Models/MiMo.swift index da81309edc..93173f4df7 100644 --- a/Libraries/MLXLLM/Models/MiMo.swift +++ b/Libraries/MLXLLM/Models/MiMo.swift @@ -59,13 +59,8 @@ class MiMoAttention: Module { keys = keys.reshaped(B, L, args.kvHeads, -1).transposed(0, 2, 1, 3) values = values.reshaped(B, L, args.kvHeads, -1).transposed(0, 2, 1, 3) - if let cache { - queries = rope(queries, offset: cache.offset) - keys = rope(keys, offset: cache.offset) - } else { - queries = rope(queries, offset: 0) - keys = rope(keys, offset: 0) - } + queries = applyRotaryPosition(rope, to: queries, cache: cache) + keys = applyRotaryPosition(rope, to: keys, cache: cache) let output = attentionWithCacheUpdate( queries: queries, diff --git a/Libraries/MLXLLM/Models/MiMoV2Flash.swift b/Libraries/MLXLLM/Models/MiMoV2Flash.swift index 4867279577..f9545e8e1b 100644 --- a/Libraries/MLXLLM/Models/MiMoV2Flash.swift +++ b/Libraries/MLXLLM/Models/MiMoV2Flash.swift @@ -169,13 +169,8 @@ class MiMoV2FlashAttention: Module { var k = keys.reshaped(B, L, numKeyValueHeads, -1).transposed(0, 2, 1, 3) let v = values.reshaped(B, L, numKeyValueHeads, -1).transposed(0, 2, 1, 3) - if let cache { - q = rope(q, offset: cache.offset) - k = rope(k, offset: cache.offset) - } else { - q = rope(q) - k = rope(k) - } + q = applyRotaryPosition(rope, to: q, cache: cache) + k = applyRotaryPosition(rope, to: k, cache: cache) let output = attentionWithCacheUpdateAndSinks( queries: q, diff --git a/Libraries/MLXLLM/Models/MiniCPM.swift b/Libraries/MLXLLM/Models/MiniCPM.swift index eaee3fc22e..852663b8da 100644 --- a/Libraries/MLXLLM/Models/MiniCPM.swift +++ b/Libraries/MLXLLM/Models/MiniCPM.swift @@ -54,9 +54,8 @@ final class MiniCPMAttention: Module { keys = keys.reshaped(B, L, args.kvHeads, -1).transposed(0, 2, 1, 3) values = values.reshaped(B, L, args.kvHeads, -1).transposed(0, 2, 1, 3) - let offset = cache?.offset ?? 0 - queries = rope(queries, offset: offset) - keys = rope(keys, offset: offset) + queries = applyRotaryPosition(rope, to: queries, cache: cache) + keys = applyRotaryPosition(rope, to: keys, cache: cache) let output = attentionWithCacheUpdate( queries: queries, diff --git a/Libraries/MLXLLM/Models/MiniMax.swift b/Libraries/MLXLLM/Models/MiniMax.swift index 73ea604c50..47bae6a599 100644 --- a/Libraries/MLXLLM/Models/MiniMax.swift +++ b/Libraries/MLXLLM/Models/MiniMax.swift @@ -77,13 +77,8 @@ class MiniMaxAttention: Module { var k = keys.reshaped(B, L, numKeyValueHeads, -1).transposed(0, 2, 1, 3) let v = values.reshaped(B, L, numKeyValueHeads, -1).transposed(0, 2, 1, 3) - if let cache { - q = rope(q, offset: cache.offset) - k = rope(k, offset: cache.offset) - } else { - q = rope(q) - k = rope(k) - } + q = applyRotaryPosition(rope, to: q, cache: cache) + k = applyRotaryPosition(rope, to: k, cache: cache) let output = attentionWithCacheUpdate( queries: q, diff --git a/Libraries/MLXLLM/Models/Mistral3Text.swift b/Libraries/MLXLLM/Models/Mistral3Text.swift index 34d9af7bb2..7bf516e550 100644 --- a/Libraries/MLXLLM/Models/Mistral3Text.swift +++ b/Libraries/MLXLLM/Models/Mistral3Text.swift @@ -87,9 +87,8 @@ class Mistral3Attention: Module { values = values.reshaped(B, L, nKVHeads, -1).transposed(0, 2, 1, 3) // Apply RoPE - let offset = cache?.offset ?? 0 - queries = rope(queries, offset: offset) - keys = rope(keys, offset: offset) + queries = applyRotaryPosition(rope, to: queries, cache: cache) + keys = applyRotaryPosition(rope, to: keys, cache: cache) // Apply attention scaling queries = queries * attnScale diff --git a/Libraries/MLXLLM/Models/NanoChat.swift b/Libraries/MLXLLM/Models/NanoChat.swift index cd44289c44..c9a28fb1da 100644 --- a/Libraries/MLXLLM/Models/NanoChat.swift +++ b/Libraries/MLXLLM/Models/NanoChat.swift @@ -25,6 +25,41 @@ private func applySoftcap(_ logits: MLXArray, cap: Float) -> MLXArray { return scale * tanh(logits / scale) } +private final class NanoChatRoPE: Module, OffsetLayer, ArrayOffsetLayer { + let dimensions: Int + private let freqs: MLXArray + + init(dimensions: Int, freqs: MLXArray) { + self.dimensions = dimensions + self.freqs = freqs + super.init() + } + + func callAsFunction(_ x: MLXArray, offset: Int) -> MLXArray { + MLXFast.RoPE( + x, + dimensions: dimensions, + traditional: false, + base: nil, + scale: 1.0, + offset: offset, + freqs: freqs + ) + } + + func callAsFunction(_ x: MLXArray, offset: MLXArray) -> MLXArray { + MLXFast.RoPE( + x, + dimensions: dimensions, + traditional: false, + base: nil, + scale: 1.0, + offset: offset, + freqs: freqs + ) + } +} + // MARK: - Attention final class NanoChatAttention: Module { @@ -39,7 +74,7 @@ final class NanoChatAttention: Module { @ModuleInfo(key: "c_v") var wv: Linear @ModuleInfo(key: "c_proj") var wo: Linear - private let _ropeFreqs: MLXArray + let rope: RoPELayer init(_ config: NanoChatConfiguration) { self.config = config @@ -58,7 +93,8 @@ final class NanoChatAttention: Module { let halfDim = headDim / 2 let freqIndices = MLXArray(Array(0 ..< halfDim)).asType(.float32) let freqScale = Float(log(Double(config.ropeTheta)) / Double(halfDim)) - self._ropeFreqs = -MLX.exp(freqIndices * freqScale) + let ropeFreqs = -MLX.exp(freqIndices * freqScale) + self.rope = NanoChatRoPE(dimensions: headDim, freqs: ropeFreqs) } func callAsFunction( @@ -76,26 +112,8 @@ final class NanoChatAttention: Module { keys = keys.reshaped(batchSize, sequenceLength, numKVHeads, -1).transposed(0, 2, 1, 3) values = values.reshaped(batchSize, sequenceLength, numKVHeads, -1).transposed(0, 2, 1, 3) - let offset = cache?.offset ?? 0 - let freqs = _ropeFreqs - queries = MLXFast.RoPE( - queries, - dimensions: headDim, - traditional: false, - base: nil, - scale: 1.0, - offset: offset, - freqs: freqs - ) - keys = MLXFast.RoPE( - keys, - dimensions: headDim, - traditional: false, - base: nil, - scale: 1.0, - offset: offset, - freqs: freqs - ) + queries = applyRotaryPosition(rope, to: queries, cache: cache) + keys = applyRotaryPosition(rope, to: keys, cache: cache) queries = functionalRMSNorm(queries, eps: config.rmsNormEps) keys = functionalRMSNorm(keys, eps: config.rmsNormEps) diff --git a/Libraries/MLXLLM/Models/Olmo2.swift b/Libraries/MLXLLM/Models/Olmo2.swift index b9f7780930..2dd1f3ba1e 100644 --- a/Libraries/MLXLLM/Models/Olmo2.swift +++ b/Libraries/MLXLLM/Models/Olmo2.swift @@ -68,13 +68,8 @@ class Olmo2Attention: Module { keys = keys.reshaped(B, L, nKVHeads, -1).transposed(0, 2, 1, 3) values = values.reshaped(B, L, nKVHeads, -1).transposed(0, 2, 1, 3) - if let cache { - queries = rope(queries, offset: cache.offset) - keys = rope(keys, offset: cache.offset) - } else { - queries = rope(queries, offset: 0) - keys = rope(keys, offset: 0) - } + queries = applyRotaryPosition(rope, to: queries, cache: cache) + keys = applyRotaryPosition(rope, to: keys, cache: cache) let output = attentionWithCacheUpdate( queries: queries, diff --git a/Libraries/MLXLLM/Models/Olmo3.swift b/Libraries/MLXLLM/Models/Olmo3.swift index bd76b7c5f4..9574db5561 100644 --- a/Libraries/MLXLLM/Models/Olmo3.swift +++ b/Libraries/MLXLLM/Models/Olmo3.swift @@ -78,13 +78,8 @@ class Olmo3Attention: Module { keys = keys.reshaped(B, L, nKVHeads, -1).transposed(0, 2, 1, 3) values = values.reshaped(B, L, nKVHeads, -1).transposed(0, 2, 1, 3) - if let cache { - queries = rope(queries, offset: cache.offset) - keys = rope(keys, offset: cache.offset) - } else { - queries = rope(queries, offset: 0) - keys = rope(keys, offset: 0) - } + queries = applyRotaryPosition(rope, to: queries, cache: cache) + keys = applyRotaryPosition(rope, to: keys, cache: cache) let output = attentionWithCacheUpdate( queries: queries, diff --git a/Libraries/MLXLLM/Models/OlmoE.swift b/Libraries/MLXLLM/Models/OlmoE.swift index 7f213f049e..6318cd110e 100644 --- a/Libraries/MLXLLM/Models/OlmoE.swift +++ b/Libraries/MLXLLM/Models/OlmoE.swift @@ -67,13 +67,8 @@ class OlmoEAttention: Module { keys = keys.reshaped(B, L, nKVHeads, -1).transposed(0, 2, 1, 3) values = values.reshaped(B, L, nKVHeads, -1).transposed(0, 2, 1, 3) - if let cache { - queries = rope(queries, offset: cache.offset) - keys = rope(keys, offset: cache.offset) - } else { - queries = rope(queries, offset: 0) - keys = rope(keys, offset: 0) - } + queries = applyRotaryPosition(rope, to: queries, cache: cache) + keys = applyRotaryPosition(rope, to: keys, cache: cache) let output = attentionWithCacheUpdate( queries: queries, diff --git a/Libraries/MLXLLM/Models/OpenELM.swift b/Libraries/MLXLLM/Models/OpenELM.swift index ccd1d12a36..1fa1c355be 100644 --- a/Libraries/MLXLLM/Models/OpenELM.swift +++ b/Libraries/MLXLLM/Models/OpenELM.swift @@ -78,13 +78,8 @@ class MultiHeadCausalAttention: Module { keys = kNorm(keys) } - if let cache { - queries = rope(queries, offset: cache.offset) - keys = rope(keys, offset: cache.offset) - } else { - queries = rope(queries) - keys = rope(keys) - } + queries = applyRotaryPosition(rope, to: queries, cache: cache) + keys = applyRotaryPosition(rope, to: keys, cache: cache) let output = attentionWithCacheUpdate( queries: queries, diff --git a/Libraries/MLXLLM/Models/Phi.swift b/Libraries/MLXLLM/Models/Phi.swift index 2cb4e3641b..b695dab392 100644 --- a/Libraries/MLXLLM/Models/Phi.swift +++ b/Libraries/MLXLLM/Models/Phi.swift @@ -57,13 +57,8 @@ class PhiAttention: Module { values = values.reshaped(B, L, args.kvHeads, headDim).transposed(0, 2, 1, 3) // Add RoPE to the queries and keys and combine them with the cache - if let cache { - queries = rope(queries, offset: cache.offset) - keys = rope(keys, offset: cache.offset) - } else { - queries = rope(queries) - keys = rope(keys) - } + queries = applyRotaryPosition(rope, to: queries, cache: cache) + keys = applyRotaryPosition(rope, to: keys, cache: cache) // Finally perform the attention computation let scale = sqrt(1 / Float(queries.dim(-1))) diff --git a/Libraries/MLXLLM/Models/Phi3.swift b/Libraries/MLXLLM/Models/Phi3.swift index 4fb79b9b6d..be8569ab2b 100644 --- a/Libraries/MLXLLM/Models/Phi3.swift +++ b/Libraries/MLXLLM/Models/Phi3.swift @@ -20,21 +20,7 @@ class Phi3Attention: Module { @ModuleInfo(key: "qkv_proj") var wqkv: Linear @ModuleInfo(key: "o_proj") var wo: Linear - enum PositionalEncoding { - case rope(RoPE) - case suScaledRoPE(SuScaledRoPE) - - func applyEncoding(_ x: MLXArray, offset: Int = 0) -> MLXArray { - switch self { - case .rope(let rope): - return rope.callAsFunction(x, offset: offset) - case .suScaledRoPE(let suScaledRoPE): - return suScaledRoPE(x, offset: offset) - } - } - } - - let rope: PositionalEncoding + let rope: RoPELayer public init(_ args: Phi3Configuration) { self.args = args @@ -64,19 +50,19 @@ class Phi3Attention: Module { ropeScaling.type == "su" || ropeScaling.type == "longrope", let shortFactor = ropeScaling.shortFactor, let longFactor = ropeScaling.longFactor { - self.rope = .suScaledRoPE( + self.rope = SuScaledRoPE( dimensions: ropeDim, base: args.ropeTheta, maxPositionEmbeddings: args.maxPositionEmbeddings, originalMaxPositionEmbeddings: args.originalMaxPositionEmbeddings, shortFactor: shortFactor, - longFactor: longFactor)) + longFactor: longFactor) } else { - self.rope = .rope( + self.rope = RoPE( dimensions: ropeDim, traditional: args.ropeTraditional, base: args.ropeTheta, - scale: ropeScale)) + scale: ropeScale) } } @@ -96,13 +82,8 @@ class Phi3Attention: Module { keys = keys.reshaped(B, L, args.kvHeads, -1).transposed(0, 2, 1, 3) values = values.reshaped(B, L, args.kvHeads, -1).transposed(0, 2, 1, 3) - if let cache { - queries = rope.applyEncoding(queries, offset: cache.offset) - keys = rope.applyEncoding(keys, offset: cache.offset) - } else { - queries = rope.applyEncoding(queries) - keys = rope.applyEncoding(keys) - } + queries = applyRotaryPosition(rope, to: queries, cache: cache) + keys = applyRotaryPosition(rope, to: keys, cache: cache) let output = attentionWithCacheUpdate( queries: queries, diff --git a/Libraries/MLXLLM/Models/PhiMoE.swift b/Libraries/MLXLLM/Models/PhiMoE.swift index 74055b51ec..f8f7fe5762 100644 --- a/Libraries/MLXLLM/Models/PhiMoE.swift +++ b/Libraries/MLXLLM/Models/PhiMoE.swift @@ -91,13 +91,8 @@ class PhiMoEAttention: Module { var k = keys.reshaped(B, L, args.kvHeads, -1).transposed(0, 2, 1, 3) let v = values.reshaped(B, L, args.kvHeads, -1).transposed(0, 2, 1, 3) - if let cache { - q = rope(q, offset: cache.offset) - k = rope(k, offset: cache.offset) - } else { - q = rope(q) - k = rope(k) - } + q = applyRotaryPosition(rope, to: q, cache: cache) + k = applyRotaryPosition(rope, to: k, cache: cache) let output = attentionWithCacheUpdate( queries: q, diff --git a/Libraries/MLXLLM/Models/Qwen2.swift b/Libraries/MLXLLM/Models/Qwen2.swift index 2b336b826c..b14636f855 100644 --- a/Libraries/MLXLLM/Models/Qwen2.swift +++ b/Libraries/MLXLLM/Models/Qwen2.swift @@ -70,13 +70,8 @@ class Qwen2Attention: Module { keys = keys.reshaped(B, L, args.kvHeads, -1).transposed(0, 2, 1, 3) values = values.reshaped(B, L, args.kvHeads, -1).transposed(0, 2, 1, 3) - if let cache { - queries = rope(queries, offset: cache.offset) - keys = rope(keys, offset: cache.offset) - } else { - queries = rope(queries) - keys = rope(keys) - } + queries = applyRotaryPosition(rope, to: queries, cache: cache) + keys = applyRotaryPosition(rope, to: keys, cache: cache) let output = attentionWithCacheUpdate( queries: queries, diff --git a/Libraries/MLXLLM/Models/Qwen3.swift b/Libraries/MLXLLM/Models/Qwen3.swift index 86555c464a..73d9f9fd69 100644 --- a/Libraries/MLXLLM/Models/Qwen3.swift +++ b/Libraries/MLXLLM/Models/Qwen3.swift @@ -77,13 +77,8 @@ class Qwen3Attention: Module { values = values.reshaped(B, L, args.kvHeads, -1).transposed(0, 2, 1, 3) // Apply RoPE positioning - if let cache { - queries = rope(queries, offset: cache.offset) - keys = rope(keys, offset: cache.offset) - } else { - queries = rope(queries) - keys = rope(keys) - } + queries = applyRotaryPosition(rope, to: queries, cache: cache) + keys = applyRotaryPosition(rope, to: keys, cache: cache) // Use the automatic attention router that handles both quantized and regular caches let output = attentionWithCacheUpdate( diff --git a/Libraries/MLXLLM/Models/Qwen35.swift b/Libraries/MLXLLM/Models/Qwen35.swift index 410d52b38e..15fcd6556c 100644 --- a/Libraries/MLXLLM/Models/Qwen35.swift +++ b/Libraries/MLXLLM/Models/Qwen35.swift @@ -359,13 +359,8 @@ final class Qwen35Attention: Module { keys = kNorm(keys.reshaped(B, L, kvHeads, -1)).transposed(0, 2, 1, 3) values = values.reshaped(B, L, kvHeads, -1).transposed(0, 2, 1, 3) - if let cache { - queries = rope(queries, offset: cache.offset) - keys = rope(keys, offset: cache.offset) - } else { - queries = rope(queries, offset: 0) - keys = rope(keys, offset: 0) - } + queries = applyRotaryPosition(rope, to: queries, cache: cache) + keys = applyRotaryPosition(rope, to: keys, cache: cache) let output = attentionWithCacheUpdate( queries: queries, diff --git a/Libraries/MLXLLM/Models/Qwen3MoE.swift b/Libraries/MLXLLM/Models/Qwen3MoE.swift index 79a3d7c8ad..aa303ae21f 100644 --- a/Libraries/MLXLLM/Models/Qwen3MoE.swift +++ b/Libraries/MLXLLM/Models/Qwen3MoE.swift @@ -76,13 +76,8 @@ class Qwen3MoEAttention: Module { keys = kNorm(keys.reshaped(B, L, args.kvHeads, -1)).transposed(0, 2, 1, 3) values = values.reshaped(B, L, args.kvHeads, -1).transposed(0, 2, 1, 3) - if let cache { - queries = rope(queries, offset: cache.offset) - keys = rope(keys, offset: cache.offset) - } else { - queries = rope(queries) - keys = rope(keys) - } + queries = applyRotaryPosition(rope, to: queries, cache: cache) + keys = applyRotaryPosition(rope, to: keys, cache: cache) let output = attentionWithCacheUpdate( queries: queries, diff --git a/Libraries/MLXLLM/Models/Qwen3Next.swift b/Libraries/MLXLLM/Models/Qwen3Next.swift index 46a2cd9da2..cfe0a985bd 100644 --- a/Libraries/MLXLLM/Models/Qwen3Next.swift +++ b/Libraries/MLXLLM/Models/Qwen3Next.swift @@ -99,13 +99,8 @@ public final class Qwen3NextAttention: Module { keys = kNorm(keys.reshaped(B, L, args.kvHeads, -1)).transposed(0, 2, 1, 3) values = values.reshaped(B, L, args.kvHeads, -1).transposed(0, 2, 1, 3) - if let cache { - queries = rope(queries, offset: cache.offset) - keys = rope(keys, offset: cache.offset) - } else { - queries = rope(queries, offset: 0) - keys = rope(keys, offset: 0) - } + queries = applyRotaryPosition(rope, to: queries, cache: cache) + keys = applyRotaryPosition(rope, to: keys, cache: cache) let output = attentionWithCacheUpdate( queries: queries, diff --git a/Libraries/MLXLLM/Models/SmolLM3.swift b/Libraries/MLXLLM/Models/SmolLM3.swift index 4da0631ad5..64482f79a8 100644 --- a/Libraries/MLXLLM/Models/SmolLM3.swift +++ b/Libraries/MLXLLM/Models/SmolLM3.swift @@ -10,22 +10,15 @@ import MLX import MLXLMCommon import MLXNN -protocol SmolLM3PositionEmbedding { - func callAsFunction(_ x: MLXArray, offset: Int) -> MLXArray - func callAsFunction(_ x: MLXArray) -> MLXArray -} - -extension RoPE: SmolLM3PositionEmbedding {} - // MARK: - NoPE -final class NoPE: Module, SmolLM3PositionEmbedding { - func callAsFunction(_ x: MLXArray, offset: Int) -> MLXArray { +final class NoPE: Module, OffsetLayer, ArrayOffsetLayer { + public func callAsFunction(_ x: MLXArray, offset: Int) -> MLXArray { return x } - func callAsFunction(_ x: MLXArray) -> MLXArray { - callAsFunction(x, offset: 0) + public func callAsFunction(_ x: MLXArray, offset: MLXArray) -> MLXArray { + return x } } @@ -40,7 +33,7 @@ class SmolLM3Attention: Module { @ModuleInfo(key: "v_proj") var wv: Linear @ModuleInfo(key: "o_proj") var wo: Linear - var rope: SmolLM3PositionEmbedding + var rope: RoPELayer init(_ args: SmolLM3Configuration) { self.args = args @@ -78,13 +71,8 @@ class SmolLM3Attention: Module { keys = keys.reshaped(B, L, args.kvHeads, -1).transposed(0, 2, 1, 3) values = values.reshaped(B, L, args.kvHeads, -1).transposed(0, 2, 1, 3) - if let cache { - queries = rope(queries, offset: cache.offset) - keys = rope(keys, offset: cache.offset) - } else { - queries = rope(queries) - keys = rope(keys) - } + queries = applyRotaryPosition(rope, to: queries, cache: cache) + keys = applyRotaryPosition(rope, to: keys, cache: cache) let output = attentionWithCacheUpdate( queries: queries, diff --git a/Libraries/MLXLLM/Models/Starcoder2.swift b/Libraries/MLXLLM/Models/Starcoder2.swift index 036b4c114e..c107a96cb0 100644 --- a/Libraries/MLXLLM/Models/Starcoder2.swift +++ b/Libraries/MLXLLM/Models/Starcoder2.swift @@ -55,13 +55,8 @@ class Starcoder2Attention: Module { keys = keys.reshaped(B, L, args.kvHeads, -1).transposed(0, 2, 1, 3) values = values.reshaped(B, L, args.kvHeads, -1).transposed(0, 2, 1, 3) - if let cache { - queries = rope(queries, offset: cache.offset) - keys = rope(keys, offset: cache.offset) - } else { - queries = rope(queries) - keys = rope(keys) - } + queries = applyRotaryPosition(rope, to: queries, cache: cache) + keys = applyRotaryPosition(rope, to: keys, cache: cache) let output = attentionWithCacheUpdate( queries: queries, diff --git a/Libraries/MLXLMCommon/RoPEApplication.swift b/Libraries/MLXLMCommon/RoPEApplication.swift new file mode 100644 index 0000000000..d909dcbc31 --- /dev/null +++ b/Libraries/MLXLMCommon/RoPEApplication.swift @@ -0,0 +1,27 @@ +// Copyright © 2024 Apple Inc. + +import Foundation +import MLX +import MLXNN + +// MARK: - applyRotaryPosition Helper + +/// Apply rotary position embeddings, using the cache offset when available. +/// +/// This function enables models to use a single call site instead of +/// repeating conditional offset handling: +/// ```swift +/// queries = applyRotaryPosition(rope, to: queries, cache: cache) +/// keys = applyRotaryPosition(rope, to: keys, cache: cache) +/// ``` +/// +/// - Parameters: +/// - rope: A RoPE layer conforming to both `OffsetLayer` and `ArrayOffsetLayer`. +/// - x: The input tensor to apply RoPE to. +/// - cache: The KV cache (determines offset), or `nil` for offset 0. +/// - Returns: The input with rotary positional encoding applied. +public func applyRotaryPosition(_ rope: R, to x: MLXArray, cache: KVCache?) + -> MLXArray +{ + return rope(x, offset: cache?.offset ?? 0) +}