Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions Libraries/MLXLLM/Models/Gemma2.swift
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,11 @@ class Gemma2Attention: Module {
var scores = matmul(queries, keys.swappedAxes(-1, -2))
scores = tanh(scores / logitSoftCap) * logitSoftCap

// A per-row `[B, 1, L, S]` mask needs the head-group axis of grouped-query scores.
var mask = mask
if repeats > 1, case .array(let array) = mask, array.ndim == 4 {
mask = .array(expandedDimensions(array, axis: -3))
}
scores = applyAttentionMask(scores: scores, mask: mask)
scores = softmax(scores, axis: -1, precise: true)
var output = matmul(scores, values)
Expand Down
16 changes: 16 additions & 0 deletions Libraries/MLXLLM/Models/Llama4AttentionScaling.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
// Copyright © 2026 Apple Inc.

import MLX

/// Per-row query scales for attention shaped `[B, H, L, D]`.
func batchedLlama4AttentionScale(
offsets: MLXArray, length: Int, beta: Float, maxPositionEmbeddings: Int
) -> MLXArray {
let positions = offsets[0..., .newAxis] + MLXArray.arange(length)[.newAxis]
// Negative positions belong to left padding and must not produce log(0).
let nonnegative = MLX.maximum(positions, MLXArray(Int32(0))).asType(.float32)
let scaling =
1 + beta
* MLX.log(1 + MLX.floor(nonnegative / Float(maxPositionEmbeddings)))
return scaling[0..., .newAxis, 0..., .newAxis]
}
32 changes: 18 additions & 14 deletions Libraries/MLXLLM/Models/Mistral3Text.swift
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,10 @@ import MLXNN
private func getLlama4AttentionScale(
start: Int, stop: Int, beta: Float, maxPositionEmbeddings: Int
) -> MLXArray {
let positions = MLXArray(Int32(start) ..< Int32(stop))
var positions = MLXArray(Int32(start) ..< Int32(stop))
if start < 0 {
positions = MLX.maximum(positions, MLXArray(Int32(0)))
}
let scaling =
1 + beta
* MLX.log(
Expand Down Expand Up @@ -224,13 +227,6 @@ public class Mistral3TextModelInner: Module {
h = embedTokens(inputs)
}

let offset: Int
if let cache {
offset = cache[0].offset
} else {
offset = 0
}

// Create full attention mask
let faMask = createAttentionMask(h: h, cache: cache?[faIdx])

Expand All @@ -249,12 +245,20 @@ public class Mistral3TextModelInner: Module {
let llama4ScalingBeta = ropeParams["llama_4_scaling_beta"]?.asFloat(),
let originalMaxPosEmbed = ropeParams["original_max_position_embeddings"]?.asInt()
{
attnScale = getLlama4AttentionScale(
start: offset,
stop: offset + inputs.dim(1),
beta: llama4ScalingBeta,
maxPositionEmbeddings: originalMaxPosEmbed
).asType(h.dtype)
switch cache?.first?.ropeOffset ?? .scalar(0) {
case .scalar(let offset):
attnScale = getLlama4AttentionScale(
start: offset,
stop: offset + inputs.dim(1),
beta: llama4ScalingBeta,
maxPositionEmbeddings: originalMaxPosEmbed
).asType(h.dtype)
case .batch(let offsets):
attnScale = batchedLlama4AttentionScale(
offsets: offsets, length: inputs.dim(1), beta: llama4ScalingBeta,
maxPositionEmbeddings: originalMaxPosEmbed
).asType(h.dtype)
}
} else {
attnScale = MLXArray.ones([inputs.dim(1), 1]).asType(h.dtype)
}
Expand Down
31 changes: 18 additions & 13 deletions Libraries/MLXLLM/Models/NemotronLabsDiffusion.swift
Original file line number Diff line number Diff line change
Expand Up @@ -22,15 +22,14 @@ import MLXLMCommon
import MLXNN

// MARK: - Llama-4 Attention Scaling
//
// Identical to Mistral3Text.swift's helper but kept private here to keep the
// file self-contained — the existing helper there is `private` so it cannot be
// reused.

private func nlsLlama4AttentionScale(
start: Int, stop: Int, beta: Float, maxPositionEmbeddings: Int
) -> MLXArray {
let positions = arange(start, stop)
var positions = arange(start, stop)
if start < 0 {
positions = MLX.maximum(positions, MLXArray(Int32(0)))
}
let scaling =
1 + beta
* MLX.log(
Expand Down Expand Up @@ -207,8 +206,6 @@ public class NemotronLabsDiffusionEncoder: Module {
) -> MLXArray {
var h = embedTokens(inputs)

let offset = cache?[0].offset ?? 0

let mask: MLXFast.ScaledDotProductAttentionMaskMode
if bidirectional {
// Diffusion mode: full attention.
Expand All @@ -223,12 +220,20 @@ public class NemotronLabsDiffusionEncoder: Module {
let beta = ropeParams["llama_4_scaling_beta"]?.asFloat(),
let origMax = ropeParams["original_max_position_embeddings"]?.asInt()
{
attnScale = nlsLlama4AttentionScale(
start: offset,
stop: offset + inputs.dim(1),
beta: beta,
maxPositionEmbeddings: origMax
).asType(h.dtype)
switch cache?.first?.ropeOffset ?? .scalar(0) {
case .scalar(let offset):
attnScale = nlsLlama4AttentionScale(
start: offset,
stop: offset + inputs.dim(1),
beta: beta,
maxPositionEmbeddings: origMax
).asType(h.dtype)
case .batch(let offsets):
attnScale = batchedLlama4AttentionScale(
offsets: offsets, length: inputs.dim(1), beta: beta,
maxPositionEmbeddings: origMax
).asType(h.dtype)
}
} else {
attnScale = MLXArray.ones([inputs.dim(1), 1]).asType(h.dtype)
}
Expand Down
6 changes: 3 additions & 3 deletions Libraries/MLXVLM/Models/FastVLM.swift
Original file line number Diff line number Diff line change
Expand Up @@ -152,9 +152,9 @@ private enum Language {
keys = keys.reshaped(B, L, kvHeads, headDim).transposed(0, 2, 1, 3)
values = values.reshaped(B, L, kvHeads, headDim).transposed(0, 2, 1, 3)

let offset = cache?.offset ?? 0
queries = rotaryEmbedding(queries, offset: offset)
keys = rotaryEmbedding(keys, offset: offset)
let offset = cache?.ropeOffset
queries = applyRotaryPosition(rotaryEmbedding, to: queries, offset: offset)
keys = applyRotaryPosition(rotaryEmbedding, to: keys, offset: offset)

let output = attentionWithCacheUpdate(
queries: queries,
Expand Down
12 changes: 4 additions & 8 deletions Libraries/MLXVLM/Models/Gemma3.swift
Original file line number Diff line number Diff line change
Expand Up @@ -190,7 +190,7 @@ private class Attention: 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
Expand Down Expand Up @@ -247,13 +247,9 @@ private class Attention: Module {
keys = keyNorm(keys)

// Apply rotary position embedding
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)
}
let offset = cache?.ropeOffset
queries = applyRotaryPosition(rope, to: queries, offset: offset)
keys = applyRotaryPosition(rope, to: keys, offset: offset)

let output = attentionWithCacheUpdate(
queries: queries,
Expand Down
22 changes: 11 additions & 11 deletions Libraries/MLXVLM/Models/Gemma4.swift
Original file line number Diff line number Diff line change
Expand Up @@ -605,7 +605,7 @@ final class Gemma4TextAttention: Module {
@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
@ModuleInfo var rope: RoPELayer

init(config: Gemma4TextConfiguration, layerIdx: Int, kvSharedOnly: Bool = false) {
self.config = config
Expand Down Expand Up @@ -664,18 +664,18 @@ final class Gemma4TextAttention: Module {
_ x: MLXArray, mask: MLXFast.ScaledDotProductAttentionMaskMode = .none,
cache: KVCache? = nil,
sharedKV: Gemma4SharedKVState? = nil,
offset: Int? = nil
) -> (MLXArray, Gemma4SharedKVState?, Int) {
offset: RoPEOffset? = nil
) -> (MLXArray, Gemma4SharedKVState?, RoPEOffset) {
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 currentOffset: RoPEOffset
let kvState: Gemma4SharedKVState?

if let sharedKV {
currentOffset = offset ?? 0
currentOffset = offset ?? .scalar(0)
kvState = sharedKV
} else {
// KV-owning path: K/V projections must be present. If they are nil
Expand All @@ -686,7 +686,7 @@ final class Gemma4TextAttention: Module {
fatalError(
"Gemma4 attention called without sharedKV on a KV-shared layer")
}
currentOffset = cache?.offset ?? 0
currentOffset = cache?.ropeOffset ?? .scalar(0)
var keys = kProj(x).reshaped(batch, length, numKVHeads, headDim)
var values =
if useKEqV {
Expand All @@ -696,7 +696,7 @@ final class Gemma4TextAttention: Module {
}
keys = kNorm(keys).transposed(0, 2, 1, 3)
values = vNorm(values).transposed(0, 2, 1, 3)
keys = rope(keys, offset: currentOffset)
keys = applyRotaryPosition(rope, to: keys, offset: currentOffset)
if let quantizedCache = cache as? QuantizedKVCacheProtocol {
let (quantizedKeys, quantizedValues) = quantizedCache.updateQuantized(
keys: keys, values: values)
Expand All @@ -716,7 +716,7 @@ final class Gemma4TextAttention: Module {
}

queries = queries.transposed(0, 2, 1, 3)
queries = rope(queries, offset: currentOffset)
queries = applyRotaryPosition(rope, to: queries, offset: currentOffset)

guard let kvState else {
fatalError("Gemma4 attention expected a KV state")
Expand Down Expand Up @@ -822,8 +822,8 @@ final class Gemma4TextDecoderLayer: Module {
cache: KVCache? = nil,
perLayerInput: MLXArray? = nil,
sharedKV: Gemma4SharedKVState? = nil,
offset: Int? = nil
) -> (MLXArray, Gemma4SharedKVState?, Int) {
offset: RoPEOffset? = nil
) -> (MLXArray, Gemma4SharedKVState?, RoPEOffset) {
var residual = x
var h = inputLayerNorm(x)
let (attentionOutput, kvState, attentionOffset) = selfAttention(
Expand Down Expand Up @@ -1101,7 +1101,7 @@ final class Gemma4TextBackbone: Module {
}

var h = h0
var intermediates = [(kv: Gemma4SharedKVState?, offset: Int?)](
var intermediates = [(kv: Gemma4SharedKVState?, offset: RoPEOffset?)](
repeating: (nil, nil), count: config.hiddenLayers)
for (idx, layer) in layers.enumerated() {
let sourceIdx = layerIdxToCacheIdx[idx]
Expand Down
2 changes: 1 addition & 1 deletion Libraries/MLXVLM/Models/Gemma4Assistant.swift
Original file line number Diff line number Diff line change
Expand Up @@ -406,7 +406,7 @@ public final class Gemma4AssistantDraftModel: Module, MTPDrafterModel {
: .array(slidingMask)
let (out, _, _) = layer(
h, mask: layerMask, cache: nil, perLayerInput: nil,
sharedKV: kvState, offset: queryOffset)
sharedKV: kvState, offset: .scalar(queryOffset))
h = out
}

Expand Down
6 changes: 3 additions & 3 deletions Libraries/MLXVLM/Models/Idefics3.swift
Original file line number Diff line number Diff line change
Expand Up @@ -232,9 +232,9 @@ private enum Language {
k = k.reshaped(B, L, nKVHeads, -1).transposed(0, 2, 1, 3)
v = v.reshaped(B, L, nKVHeads, -1).transposed(0, 2, 1, 3)

let offset = cache?.offset ?? 0
q = ropeEmbed(q, offset: offset)
k = ropeEmbed(k, offset: offset)
let offset = cache?.ropeOffset
q = applyRotaryPosition(ropeEmbed, to: q, offset: offset)
k = applyRotaryPosition(ropeEmbed, to: k, offset: offset)

let output = attentionWithCacheUpdate(
queries: q,
Expand Down
10 changes: 3 additions & 7 deletions Libraries/MLXVLM/Models/LFM2VL.swift
Original file line number Diff line number Diff line change
Expand Up @@ -342,13 +342,9 @@ private enum Language {
keys = kLayerNorm(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)
keys = rope(keys)
}
let offset = cache?.ropeOffset
queries = applyRotaryPosition(rope, to: queries, offset: offset)
keys = applyRotaryPosition(rope, to: keys, offset: offset)

let output = attentionWithCacheUpdate(
queries: queries,
Expand Down
34 changes: 25 additions & 9 deletions Libraries/MLXVLM/Models/Mistral3.swift
Original file line number Diff line number Diff line change
Expand Up @@ -283,11 +283,28 @@ private enum Language {
// MARK: Llama 4 Attention Scaling

static func getLlama4AttentionScale(
start: Int, stop: Int, beta: Float, maxPositionEmbeddings: Int
offset: RoPEOffset?, length: Int, beta: Float, maxPositionEmbeddings: Int
) -> MLXArray {
let positions = MLXArray(start ..< stop).asType(.float32)
guard beta != 0 else { return MLXArray.ones([length, 1]) }
let positions: MLXArray
let batched: Bool
switch offset {
case .batch(let offsets):
positions = MLX.maximum(
(offsets[0..., .newAxis] + MLXArray(0 ..< length)[.newAxis]).asType(.float32), 0)
batched = true
case .scalar(let start):
let range = MLXArray(start ..< start + length).asType(.float32)
positions = start < 0 ? MLX.maximum(range, 0) : range
batched = false
case nil:
positions = MLXArray(0 ..< length).asType(.float32)
batched = false
}
let scaling = 1 + beta * MLX.log(1 + MLX.floor(positions / Float(maxPositionEmbeddings)))
return expandedDimensions(scaling, axis: -1)
return batched
? scaling[0..., .newAxis, 0..., .newAxis]
: expandedDimensions(scaling, axis: -1)
}

// MARK: Language Attention
Expand Down Expand Up @@ -352,9 +369,9 @@ private enum Language {
keys = keys.reshaped(B, L, nKVHeads, -1).transposed(0, 2, 1, 3)
values = values.reshaped(B, L, nKVHeads, -1).transposed(0, 2, 1, 3)

let offset = cache?.offset ?? 0
queries = rope(queries, offset: offset)
keys = rope(keys, offset: offset)
let offset = cache?.ropeOffset
queries = applyRotaryPosition(rope, to: queries, offset: offset)
keys = applyRotaryPosition(rope, to: keys, offset: offset)

queries = queries * attentionScale

Expand Down Expand Up @@ -473,7 +490,6 @@ private enum Language {
}

let cache = cache ?? []
let offset = cache.first?.offset ?? 0

let faMask = createAttentionMask(h: h, cache: cache[faIndex])

Expand All @@ -488,8 +504,8 @@ private enum Language {
config.ropeParameters?["original_max_position_embeddings"]?.asInt()
?? config.maxPositionEmbeddings ?? 4096
let attentionScale = getLlama4AttentionScale(
start: offset,
stop: offset + h.dim(1), // Use h's length (embeddings), not inputs (token IDs)
offset: cache.first?.ropeOffset,
length: h.dim(1),
beta: beta,
maxPositionEmbeddings: originalMaxPos
).asType(h.dtype)
Expand Down
6 changes: 3 additions & 3 deletions Libraries/MLXVLM/Models/MuseGlimmer.swift
Original file line number Diff line number Diff line change
Expand Up @@ -457,9 +457,9 @@ private class MuseGlimmerTextAttention: Module {
values = values.transposed(0, 2, 1, 3)

if useRope {
let offset = cache?.offset ?? 0
queries = rope(queries, offset: offset)
keys = rope(keys, offset: offset)
let offset = cache?.ropeOffset
queries = applyRotaryPosition(rope, to: queries, offset: offset)
keys = applyRotaryPosition(rope, to: keys, offset: offset)
}

var output = attentionWithCacheUpdate(
Expand Down
6 changes: 3 additions & 3 deletions Libraries/MLXVLM/Models/Pixtral.swift
Original file line number Diff line number Diff line change
Expand Up @@ -566,9 +566,9 @@ private enum PixtralLanguage {
keys = kNorm(keys)
}

let offset = cache?.offset ?? 0
queries = rope(queries, offset: offset)
keys = rope(keys, offset: offset)
let offset = cache?.ropeOffset
queries = applyRotaryPosition(rope, to: queries, offset: offset)
keys = applyRotaryPosition(rope, to: keys, offset: offset)

let output = attentionWithCacheUpdate(
queries: queries, keys: keys, values: values,
Expand Down
Loading
Loading