diff --git a/Libraries/MLXLLM/Models/Gemma2.swift b/Libraries/MLXLLM/Models/Gemma2.swift index 08a28c2364..e614d03c80 100644 --- a/Libraries/MLXLLM/Models/Gemma2.swift +++ b/Libraries/MLXLLM/Models/Gemma2.swift @@ -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) diff --git a/Libraries/MLXLLM/Models/Llama4AttentionScaling.swift b/Libraries/MLXLLM/Models/Llama4AttentionScaling.swift new file mode 100644 index 0000000000..dc29f048fa --- /dev/null +++ b/Libraries/MLXLLM/Models/Llama4AttentionScaling.swift @@ -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] +} diff --git a/Libraries/MLXLLM/Models/Mistral3Text.swift b/Libraries/MLXLLM/Models/Mistral3Text.swift index 4d054c642f..08d8723c5b 100644 --- a/Libraries/MLXLLM/Models/Mistral3Text.swift +++ b/Libraries/MLXLLM/Models/Mistral3Text.swift @@ -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( @@ -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]) @@ -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) } diff --git a/Libraries/MLXLLM/Models/NemotronLabsDiffusion.swift b/Libraries/MLXLLM/Models/NemotronLabsDiffusion.swift index 4079a3c85c..3ba15e5c88 100644 --- a/Libraries/MLXLLM/Models/NemotronLabsDiffusion.swift +++ b/Libraries/MLXLLM/Models/NemotronLabsDiffusion.swift @@ -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( @@ -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. @@ -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) } diff --git a/Libraries/MLXLMCommon/Batching/BatchKVCache.swift b/Libraries/MLXLMCommon/Batching/BatchKVCache.swift new file mode 100644 index 0000000000..df75b72f27 --- /dev/null +++ b/Libraries/MLXLMCommon/Batching/BatchKVCache.swift @@ -0,0 +1,492 @@ +// Copyright © 2026 Apple Inc. + +import Foundation +import MLX + +/// A KV cache for a batch of left-padded sequences. +/// +/// Port of mlx-lm's `BatchKVCache`, with the fixes mlx-vlm's port of it carries +/// (`mlx_vlm/models/cache.py` at mlx-vlm dcea787, noted where they apply). Rows are +/// left-padded so that sequences of +/// different lengths end at the same position. Prompts `[1, 3, 5]`, `[7]` and +/// `[2, 6, 8, 9]` are stored as +/// ``` +/// [0, 1, 3, 5] +/// [0, 0, 0, 7] +/// [2, 6, 8, 9] +/// ``` +/// with ``leftPadding`` `[1, 3, 0]`. ``KVCache/offset`` is the longest row's position, 4 here: +/// after finalization it counts tokens, not padding. +/// +/// Row positions and padding live on the host. The arrays the model reads are +/// built from them on demand, so a decode step advances positions without a +/// kernel per layer, and a batch whose rows carry no padding decodes one token +/// with no mask at all. +public final class BatchKVCache: BaseKVCache, BatchPositionedKVCache, BatchableKVCache { + /// Each row's left padding, shape `[B]`. + public private(set) var leftPadding: MLXArray + + /// Each row's left padding on the host; `leftPadding` mirrors it. + private var leftPaddingValues: [Int32] + + /// Each row's position on the host. It starts at `-leftPadding`. + private var positions: [Int32] + + /// `positions` as an array, built on first use after every change. + private var positionsArray: MLXArray? + + /// Each row's position, shape `[B]`. It starts at `-leftPadding`. + public var batchOffset: MLXArray { + if let positionsArray { return positionsArray } + let array = MLXArray(positions) + positionsArray = array + return array + } + + var keys: MLXArray? + var values: MLXArray? + + /// The buffer position the next token is written to: the width in use, padding included. + private var idx = 0 + + /// The position of the longest row, as ``KVCache/offset`` counts it. After + /// finalization that is tokens, not padding, so it is 0 until a row has consumed its + /// left padding. During a ragged prefill it also counts right padding, until + /// `finalize()` turns that into left padding. Rows keep their own positions in + /// ``batchOffset``, so the batch as a whole cannot be moved. + public override var offset: Int { + get { Int(max(0, positions.max() ?? 0)) } + set { preconditionFailure("BatchKVCache positions are per row; see batchOffset") } + } + + /// The right padding of a ragged prefill, from `prepare` until `finalize`. + private var rightPadding: MLXArray? + private var rightPaddingValues: [Int32]? + + public var step = 256 + + /// - Parameter leftPadding: the left padding of each row + public init(leftPadding: [Int]) { + let padding = leftPadding.map { Int32($0) } + self.leftPaddingValues = padding + self.leftPadding = MLXArray(padding) + self.positions = padding.map { -$0 } + super.init() + } + + /// The number of rows. + public var batchSize: Int { positions.count } + + /// Whether any row carries left padding. + private var hasLeftPadding: Bool { leftPaddingValues.contains { $0 != 0 } } + + private func setPositions(_ new: [Int32]) { + positions = new + positionsArray = nil + } + + private func setLeftPadding(_ new: [Int32]) { + leftPaddingValues = new + leftPadding = MLXArray(new) + } + + private func setRightPadding(_ new: [Int32]?) { + rightPaddingValues = new + rightPadding = new.map { MLXArray($0) } + } + + /// Per-row positions, also when the cache is typed as `KVCache`. + /// + /// Rows at one shared position, such as a batch of one, get the scalar + /// form, so no array is built per layer per step. Otherwise no copy: + /// every change replaces the array rather than mutating it. + public override var ropeOffset: RoPEOffset { + if let first = positions.first, positions.allSatisfy({ $0 == first }) { + return .scalar(Int(first)) + } + return .batch(batchOffset) + } + + public override func innerState() -> [MLXArray] { + [keys, values].compactMap { $0 } + } + + public override func update(keys: MLXArray, values: MLXArray) -> (MLXArray, MLXArray) { + let previous = idx + if self.keys == nil || previous + keys.dim(2) > self.keys!.dim(2) { + let length = (step + keys.dim(2) - 1) / step * step + let newKeys = MLXArray.zeros( + [keys.dim(0), keys.dim(1), length, keys.dim(3)], dtype: keys.dtype) + let newValues = MLXArray.zeros( + [values.dim(0), values.dim(1), length, values.dim(3)], dtype: values.dtype) + if var currentKeys = self.keys, var currentValues = self.values { + if previous % step != 0 { + currentKeys = currentKeys[.ellipsis, .. Bool { + // A round can discard its whole write only after every row has consumed its padding. + positions >= 0 + && (positions == 0 + || (!self.positions.isEmpty && self.positions.allSatisfy { $0 >= 0 })) + } + + /// No row can lose more tokens than the shortest row holds. + public override var maxTrimCount: Int { + let shortest = Int(positions.min() ?? 0) + return min(idx, max(0, shortest)) + } + + @discardableResult + public override func trim(_ n: Int) -> Int { + let trimmed = min(maxTrimCount, n) + idx -= trimmed + setPositions(positions.map { $0 - Int32(trimmed) }) + return trimmed + } + + /// No mask for one token when no row is padded and the window, if any, + /// covers every retained key; otherwise an explicit mask, so left padding + /// and the window stay masked. This cache never evicts, so a window + /// smaller than the history still needs the mask. + public override func makeMask( + n: Int, windowSize: Int?, returnArray: Bool + ) -> MLXFast.ScaledDotProductAttentionMaskMode { + if n == 1, !hasLeftPadding, windowSize.map({ $0 >= idx + n }) ?? true { + return .none + } + return .array( + createCausalMask( + n: n, offset: idx, windowSize: windowSize, leftPadding: leftPadding)) + } + + /// Prepares a right-padded prefill of rows with the given lengths. + public override func prepare(lengths: [Int]?) { + guard let lengths, let longest = lengths.max(), lengths.contains(where: { $0 < longest }) + else { return } + setRightPadding(lengths.map { Int32(longest - $0) }) + } + + public override func prepare(lengths: MLXArray?) { + prepare(lengths: lengths?.asArray(Int.self)) + } + + /// Moves the right padding of a prefill to the left, where the mask excludes it. + public override func finalize() { + guard let rightPadding, let rightPaddingValues else { return } + // A circular roll of the whole buffer lands each row's tokens at + // `padding ..< idx`; what wraps around is masked or unused. + if let keys, let values { + self.keys = dynamicRoll(keys, shifts: rightPadding[0..., .newAxis], axis: 2) + self.values = dynamicRoll(values, shifts: rightPadding[0..., .newAxis], axis: 2) + } + setPositions(zip(positions, rightPaddingValues).map { $0 - $1 }) + setLeftPadding(zip(leftPaddingValues, rightPaddingValues).map { $0 + $1 }) + setRightPadding(nil) + } + + /// Keeps only the rows at `batchIndices`, in that order. + public func filter(batchIndices: MLXArray) { + let rows = batchIndices.asArray(Int32.self).map { Int($0) } + guard !rows.isEmpty else { + keys = nil + values = nil + setRightPadding(nil) + idx = 0 + setLeftPadding([]) + setPositions([]) + return + } + let indices = MLXArray(rows.map { Int32($0) }) + keys = keys?[indices] + values = values?[indices] + setPositions(rows.map { positions[$0] }) + var padding = rows.map { leftPaddingValues[$0] } + // A ragged prefill's right padding goes with its rows, as in mlx-vlm: + // https://github.com/Blaizzy/mlx-vlm/blob/dcea787/mlx_vlm/models/cache.py#L1673-L1674 + setRightPadding(rightPaddingValues.map { values in rows.map { values[$0] } }) + + // Drop the left padding that every remaining row has, but no more than the buffer + // holds: a chunked prefill can be filtered before all of its padding is written. + // mlx-vlm bounds `min_left_pad` by `_idx` the same way: + // https://github.com/Blaizzy/mlx-vlm/blob/dcea787/mlx_vlm/models/cache.py#L1677 + let shared = min(padding.min() ?? 0, Int32(idx)) + if shared > 0, keys != nil { + keys = keys?[.ellipsis, Int(shared)..., 0...] + values = values?[.ellipsis, Int(shared)..., 0...] + idx -= Int(shared) + padding = padding.map { $0 - shared } + } + setLeftPadding(padding) + } + + public func extend(other: any KVCache) { + guard let other = other as? BatchKVCache else { + preconditionFailure("BatchKVCache can only be extended with a BatchKVCache") + } + extend(other: other) + } + + public func validateExtension(other: any KVCache) throws { + guard let other = other as? BatchKVCache else { + throw KVCacheError(message: "BatchKVCache can only append a BatchKVCache") + } + guard rightPadding == nil, other.rightPadding == nil else { + throw KVCacheError(message: "BatchKVCache extension requires finalized rows") + } + for row in [self, other] { + guard row.leftPaddingValues.count == row.batchSize, + row.leftPadding.ndim == 1, row.leftPadding.size == row.batchSize, + zip(row.positions, row.leftPaddingValues).allSatisfy({ + Int($0) + Int($1) == row.idx + }) + else { + throw KVCacheError(message: "BatchKVCache metadata must agree on the row count") + } + } + try validateBatchKVExtension( + keys: keys, values: values, batchSize: batchSize, end: idx, + otherKeys: other.keys, otherValues: other.values, otherBatchSize: other.batchSize, + otherEnd: other.idx) + } + + /// Appends the rows of `other`. Port of mlx-lm's `BatchKVCache.extend`: rows without keys + /// yet join as all-padding rows, so empty and prefilled rows can share a batch, and a + /// batch with no rows changes nothing. Both batches must be finalized: a ragged prefill in + /// progress cannot take or give rows. + public func extend(other: BatchKVCache) { + guard other.batchSize > 0 else { return } + // Right padding of a prefill in progress is not combined: finalize first. + precondition( + rightPadding == nil && other.rightPadding == nil, + "BatchKVCache.extend takes finalized rows; finalize a ragged prefill first") + guard batchSize > 0 else { + // New array objects, so writes to either cache leave the other unchanged. + keys = other.keys?[.ellipsis] + values = other.values?[.ellipsis] + idx = other.idx + setLeftPadding(other.leftPaddingValues) + setPositions(other.positions) + setRightPadding(other.rightPaddingValues) + return + } + guard let templateKeys = keys ?? other.keys, let templateValues = values ?? other.values + else { + setLeftPadding(leftPaddingValues + other.leftPaddingValues) + setPositions(positions + other.positions) + return + } + // Rows without keys take zero-width arrays, which the padding below fills. + func arrays(_ cache: BatchKVCache) -> (MLXArray, MLXArray) { + if let keys = cache.keys, let values = cache.values { return (keys, values) } + return ( + MLXArray.zeros( + [cache.batchSize, templateKeys.dim(1), 0, templateKeys.dim(3)], + dtype: templateKeys.dtype), + MLXArray.zeros( + [cache.batchSize, templateValues.dim(1), 0, templateValues.dim(3)], + dtype: templateValues.dtype) + ) + } + let (ownKeys, ownValues) = arrays(self) + let (otherKeys, otherValues) = arrays(other) + + let end = max(idx, other.idx) + let width = max(ownKeys.dim(2), otherKeys.dim(2)) + let own = rightJustify(ownKeys, ownValues, end: idx, to: end, width: width) + let added = rightJustify(otherKeys, otherValues, end: other.idx, to: end, width: width) + keys = concatenated([own.keys, added.keys]) + values = concatenated([own.values, added.values]) + let ownShift = Int32(end - idx) + let addedShift = Int32(end - other.idx) + setLeftPadding( + leftPaddingValues.map { $0 + ownShift } + + other.leftPaddingValues.map { $0 + addedShift }) + setPositions(positions + other.positions) + idx = end + } + + /// The row at `index` without its left padding, as a ``KVCacheSimple``. A row whose + /// padding covers every written position comes back empty, as mlx-vlm's slice does. + public func extract(_ index: Int) -> any KVCache { + // mlx-vlm checks the row index first too: + // https://github.com/Blaizzy/mlx-vlm/blob/dcea787/mlx_vlm/models/cache.py#L1730-L1736 + precondition( + leftPaddingValues.indices.contains(index), "BatchKVCache row index out of range") + precondition( + rightPadding == nil, + "BatchKVCache.extract takes finalized rows; finalize a ragged prefill first") + let cache = KVCacheSimple() + let padding = Int(leftPaddingValues[index]) + if let keys, let values, padding < idx { + cache.keys = MLX.contiguous(keys[index ..< index + 1, 0..., padding ..< idx, 0...]) + cache.values = MLX.contiguous( + values[index ..< index + 1, 0..., padding ..< idx, 0...]) + cache.offset = idx - padding + } + return cache + } + + /// The rows of `caches`, exactly `KVCacheSimple` rows, as one batch. See + /// ``KVCacheSimple/merge(_:)``. + public static func merge(_ caches: [any KVCache]) throws -> any BatchableKVCache { + let rows = try batchRows(caches, of: KVCacheSimple.self) + try validateBatchKVRows(rows.map { ($0.keys, $0.values, $0.offset) }) + return BatchKVCache(merging: rows) + } + + /// The rows of `caches` as one batch, left-padded to the longest row. + fileprivate convenience init(merging caches: [KVCacheSimple]) { + let longest = caches.map(\.offset).max() ?? 0 + self.init(leftPadding: caches.map { longest - $0.offset }) + // An all-empty merge is an empty batch; the first update sizes it. mlx-vlm returns + // an empty batch for it too: + // https://github.com/Blaizzy/mlx-vlm/blob/dcea787/mlx_vlm/models/cache.py#L1750-L1751 + guard let template = caches.first(where: { $0.keys != nil }), + let templateKeys = template.keys, let templateValues = template.values + else { return } + var keys: [MLXArray] = [] + var values: [MLXArray] = [] + for cache in caches { + if let rowKeys = cache.keys, let rowValues = cache.values, cache.offset > 0 { + // Slice off allocation slack, then pad on the left to `longest`. + let row = rightJustify( + rowKeys[.ellipsis, .. any KVCache { + let copy = BatchKVCache(leftPadding: []) + copy.setLeftPadding(leftPaddingValues) + copy.setPositions(positions) + copy.keys = keys?[.ellipsis] + copy.values = values?[.ellipsis] + copy.setRightPadding(rightPaddingValues) + copy.idx = idx + copy.step = step + return copy + } +} + +extension KVCacheSimple { + /// The rows of `caches` as one batch, left-padded so every row ends at the + /// longest row's position. Port of mlx-lm's `KVCache.merge`. Every cache + /// must be exactly a `KVCacheSimple` holding one row of one layout; empty + /// caches become empty rows. ``BatchKVCache/merge(_:)`` throws where this stops. + public static func merge(_ caches: [KVCacheSimple]) -> BatchKVCache { + precondition(!caches.isEmpty, "merge needs a cache") + // Exact type: a ChunkedKVCache can report an offset beyond the arrays it holds. + precondition( + caches.allSatisfy { type(of: $0) == KVCacheSimple.self }, + "KVCacheSimple.merge takes exactly KVCacheSimple rows") + do { + try validateBatchKVRows(caches.map { ($0.keys, $0.values, $0.offset) }) + } catch { + preconditionFailure("KVCacheSimple.merge: \(error.localizedDescription)") + } + return BatchKVCache(merging: caches) + } +} + +/// `keys` and `values`, whose rows end at position `end`, padded to end at `newEnd` +/// in a buffer `width` wide. +func rightJustify( + _ keys: MLXArray, _ values: MLXArray, end: Int, to newEnd: Int, width: Int +) -> (keys: MLXArray, values: MLXArray) { + var keys = keys + var values = values + let left = newEnd - end + var right = width - keys.dim(2) - left + if right < 0 { + keys = keys[.ellipsis, ..<(keys.dim(2) + right), 0...] + values = values[.ellipsis, ..<(values.dim(2) + right), 0...] + right = 0 + } + if left != 0 || right != 0 { + let widths: [IntOrPair] = [0, 0, .init((left, right)), 0] + keys = MLX.padded(keys, widths: widths) + values = MLX.padded(values, widths: widths) + } + return (keys, values) +} + +/// Rolls each row of `x` along `axis` by its own shift. Port of mlx-lm's `dynamic_roll`. +func dynamicRoll(_ x: MLXArray, shifts: MLXArray, axis: Int) -> MLXArray { + let axis = axis >= 0 ? axis : x.ndim + axis + let n = x.dim(axis) + var positionShape = [Int](repeating: 1, count: x.ndim) + positionShape[axis] = n + var shiftShape = [Int](repeating: 1, count: x.ndim) + for dimension in 0 ..< min(shifts.ndim, x.ndim) { + shiftShape[dimension] = shifts.dim(dimension) + } + let positions = MLXArray(Int32(0) ..< Int32(n)).reshaped(positionShape) + let size = MLXArray(Int32(n)) + // Adding `n` keeps the index non-negative for negative shifts. + let indices = ((positions - shifts.reshaped(shiftShape)) % size + size) % size + return takeAlong(x, indices.asType(.int32), axis: axis) +} diff --git a/Libraries/MLXLMCommon/Batching/BatchedCaches.swift b/Libraries/MLXLMCommon/Batching/BatchedCaches.swift new file mode 100644 index 0000000000..57e344cb6f --- /dev/null +++ b/Libraries/MLXLMCommon/Batching/BatchedCaches.swift @@ -0,0 +1,120 @@ +// Copyright © 2026 Apple Inc. + +import Foundation +import MLX + +/// A cache that holds the rows of a batch, with the row operations continuous batching needs. +/// +/// Port of the row operations of mlx-lm's batch caches (`filter`, `extend`, `extract` and +/// `merge`). Single-sequence caches such as ``KVCacheSimple`` do not conform: +/// ``mergeCaches(_:)`` turns their rows into the batched cache of their kind, which does. +public protocol BatchableKVCache: KVCache { + /// Keep only the rows at `batchIndices`, in that order. + func filter(batchIndices: MLXArray) + + /// Append the rows of `other`, a batch of this type that ``validateExtension(other:)`` + /// accepted. + func extend(other: any KVCache) + + /// Check that ``extend(other:)`` can append `other` without changing either cache. + /// + /// Admission validates every layer before extending any layer or sampling tokens. + /// - Throws: An error when the types, settings, or storage layouts are incompatible. + func validateExtension(other: any KVCache) throws + + /// The row at `index` as a single-sequence cache. + /// + /// The batch must be finalized: extracting during a ragged prefill, before `finalize()` + /// moves its right padding, stops with a precondition failure. + func extract(_ index: Int) -> any KVCache + + /// The rows of `caches`, single-sequence caches of one layer, as a batch of this type. + /// + /// - Throws: `KVCacheError` when there are no rows, when a row is not exactly the class + /// this batch takes, or when a row cannot be batched. + static func merge(_ caches: [any KVCache]) throws -> any BatchableKVCache +} + +/// The rows of `caches`, single-sequence caches of one layer, as one batched cache. +/// +/// Port of mlx-lm's `_merge_caches` for one layer. A cache that is its own batch merges +/// through its own class; a ``KVCacheSimple`` row merges into a ``BatchKVCache``. Each batch +/// takes rows of exactly its class, so a `ChunkedKVCache` or an unsupported compressed cache +/// is refused rather than treated as the class it subclasses. Empty caches merge into an +/// empty batch with one row each. +/// +/// - Throws: `KVCacheError` when the type has no batched form, when the rows do not share +/// one type, or when a rotating cache keeps a prefix or a rewind reserve. +public func mergeCaches(_ caches: [any KVCache]) throws -> any BatchableKVCache { + guard let first = caches.first else { + throw KVCacheError(message: "merge needs a cache") + } + guard caches.allSatisfy({ type(of: $0) == type(of: first) }) else { + throw KVCacheError(message: "Rows of a batch must share one cache type") + } + let batch: any BatchableKVCache.Type + switch first { + case let own as any BatchableKVCache: batch = type(of: own) + case is KVCacheSimple: batch = BatchKVCache.self + default: throw KVCacheError(message: "\(type(of: first)) has no batched form") + } + return try batch.merge(caches) +} + +/// `caches` as rows of exactly `T`, for a `merge` that takes only its own class. +func batchRows(_ caches: [any KVCache], of _: T.Type) throws -> [T] { + guard !caches.isEmpty else { + throw KVCacheError(message: "merge needs a cache") + } + return try caches.map { cache in + guard type(of: cache) == T.self, let row = cache as? T else { + throw KVCacheError(message: "\(type(of: cache)) has no batched form") + } + return row + } +} + +/// Check that `rows`, single-sequence rows of one attention layer with `end` positions +/// written, can be stacked into one batch: each holds paired 4-D keys and values with one row, +/// and every row that holds keys matches the heads, widths and dtype of the first one that +/// does. Reads only array metadata. +func validateBatchKVRows(_ rows: [(keys: MLXArray?, values: MLXArray?, end: Int)]) throws { + let reference = rows.first { $0.keys != nil } ?? (nil, nil, 0) + for row in rows { + try validateBatchKVExtension( + keys: reference.keys, values: reference.values, batchSize: 1, end: reference.end, + otherKeys: row.keys, otherValues: row.values, otherBatchSize: 1, otherEnd: row.end) + } +} + +/// Check concatenation dimensions without evaluating either cache's arrays. +func validateBatchKVExtension( + keys: MLXArray?, values: MLXArray?, batchSize: Int, end: Int, + otherKeys: MLXArray?, otherValues: MLXArray?, otherBatchSize: Int, otherEnd: Int +) throws { + for (keys, values, count, end) in [ + (keys, values, batchSize, end), (otherKeys, otherValues, otherBatchSize, otherEnd), + ] { + guard (keys == nil) == (values == nil), end >= 0 else { + throw KVCacheError(message: "Batched attention needs paired key/value storage") + } + if let keys, let values { + guard keys.ndim == 4, values.ndim == 4, + keys.dim(0) == count, values.dim(0) == count, + keys.dim(1) == values.dim(1), keys.dim(2) == values.dim(2), end <= keys.dim(2) + else { + throw KVCacheError(message: "Batched attention has an invalid key/value layout") + } + } else if end != 0 { + throw KVCacheError(message: "An empty attention batch cannot hold written positions") + } + } + for (own, added) in [(keys, otherKeys), (values, otherValues)] { + if let own, let added, + own.dtype != added.dtype || own.dim(1) != added.dim(1) || own.dim(3) != added.dim(3) + { + throw KVCacheError( + message: "Attention batches must share key/value heads, widths and dtypes") + } + } +} diff --git a/Libraries/MLXLMCommon/KVCache.swift b/Libraries/MLXLMCommon/KVCache.swift index b44954481f..7f2efcf14a 100644 --- a/Libraries/MLXLMCommon/KVCache.swift +++ b/Libraries/MLXLMCommon/KVCache.swift @@ -322,9 +322,22 @@ public func createCausalMask( offset: Int, windowSize: Int? = nil, lengths: MLXArray? = nil +) -> MLXArray { + createCausalMask( + n: n, offset: offset, windowSize: windowSize, lengths: lengths, leftPadding: nil) +} + +/// ``createCausalMask(n:offset:windowSize:lengths:)`` for a left-padded batch: row `b` also +/// masks the keys before `leftPadding[b]`. +func createCausalMask( + n: Int, + offset: Int, + windowSize: Int? = nil, + lengths: MLXArray? = nil, + leftPadding: MLXArray? ) -> MLXArray { var rinds = MLXArray(Int32(0) ..< Int32(offset + n)) - var linds = offset != 0 ? MLXArray(Int32(offset) ..< Int32(offset + n)) : rinds + var linds = offset != 0 ? rinds[offset...] : rinds linds = linds[0..., .newAxis] rinds = rinds[.newAxis] var mask = linds .>= rinds @@ -338,6 +351,10 @@ public func createCausalMask( mask = mask & (rinds .< lengths) } + if let leftPadding { + mask = mask & (rinds .>= leftPadding[0..., .newAxis, .newAxis, .newAxis]) + } + return mask } diff --git a/Libraries/MLXLMCommon/KVCacheRuntime.swift b/Libraries/MLXLMCommon/KVCacheRuntime.swift index 5073f0a492..151860780b 100644 --- a/Libraries/MLXLMCommon/KVCacheRuntime.swift +++ b/Libraries/MLXLMCommon/KVCacheRuntime.swift @@ -267,6 +267,11 @@ extension KVCacheLeaf { state: requested == .fullPrecision ? .active : .skipped, resolvedStrategy: .fullPrecision, reason: requested == .fullPrecision ? nil : .slidingWindow) + case .unsupported where cache is BatchKVCache: + return status( + state: requested == .fullPrecision ? .active : .skipped, + resolvedStrategy: .fullPrecision, + reason: requested == .fullPrecision ? nil : .unsupportedShape) case .simple where requested == .fullPrecision: return status( state: .active, diff --git a/Libraries/MLXVLM/Models/FastVLM.swift b/Libraries/MLXVLM/Models/FastVLM.swift index e46871f60a..98744761e1 100644 --- a/Libraries/MLXVLM/Models/FastVLM.swift +++ b/Libraries/MLXVLM/Models/FastVLM.swift @@ -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, diff --git a/Libraries/MLXVLM/Models/Gemma3.swift b/Libraries/MLXVLM/Models/Gemma3.swift index 2b66203d62..2226237ab7 100644 --- a/Libraries/MLXVLM/Models/Gemma3.swift +++ b/Libraries/MLXVLM/Models/Gemma3.swift @@ -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 @@ -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, diff --git a/Libraries/MLXVLM/Models/Gemma4.swift b/Libraries/MLXVLM/Models/Gemma4.swift index 6f822d7125..5c61524a4a 100644 --- a/Libraries/MLXVLM/Models/Gemma4.swift +++ b/Libraries/MLXVLM/Models/Gemma4.swift @@ -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 @@ -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 @@ -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 { @@ -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) @@ -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") @@ -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( @@ -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] diff --git a/Libraries/MLXVLM/Models/Gemma4Assistant.swift b/Libraries/MLXVLM/Models/Gemma4Assistant.swift index 6391bcce56..23100ae80b 100644 --- a/Libraries/MLXVLM/Models/Gemma4Assistant.swift +++ b/Libraries/MLXVLM/Models/Gemma4Assistant.swift @@ -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 } diff --git a/Libraries/MLXVLM/Models/Idefics3.swift b/Libraries/MLXVLM/Models/Idefics3.swift index 456d7c0158..4c8a100b3e 100644 --- a/Libraries/MLXVLM/Models/Idefics3.swift +++ b/Libraries/MLXVLM/Models/Idefics3.swift @@ -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, diff --git a/Libraries/MLXVLM/Models/LFM2VL.swift b/Libraries/MLXVLM/Models/LFM2VL.swift index e3ba2feba9..c36a8016c2 100644 --- a/Libraries/MLXVLM/Models/LFM2VL.swift +++ b/Libraries/MLXVLM/Models/LFM2VL.swift @@ -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, diff --git a/Libraries/MLXVLM/Models/Mistral3.swift b/Libraries/MLXVLM/Models/Mistral3.swift index 9248e5541e..1eea7efa7b 100644 --- a/Libraries/MLXVLM/Models/Mistral3.swift +++ b/Libraries/MLXVLM/Models/Mistral3.swift @@ -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 @@ -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 @@ -473,7 +490,6 @@ private enum Language { } let cache = cache ?? [] - let offset = cache.first?.offset ?? 0 let faMask = createAttentionMask(h: h, cache: cache[faIndex]) @@ -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) diff --git a/Libraries/MLXVLM/Models/MuseGlimmer.swift b/Libraries/MLXVLM/Models/MuseGlimmer.swift index 4f9564287d..047c81f9fb 100644 --- a/Libraries/MLXVLM/Models/MuseGlimmer.swift +++ b/Libraries/MLXVLM/Models/MuseGlimmer.swift @@ -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( diff --git a/Libraries/MLXVLM/Models/Pixtral.swift b/Libraries/MLXVLM/Models/Pixtral.swift index 214889ca62..c4ae220430 100644 --- a/Libraries/MLXVLM/Models/Pixtral.swift +++ b/Libraries/MLXVLM/Models/Pixtral.swift @@ -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, diff --git a/Libraries/MLXVLM/Models/Qwen25VL.swift b/Libraries/MLXVLM/Models/Qwen25VL.swift index 5d26de8cc8..b2aa10e6f4 100644 --- a/Libraries/MLXVLM/Models/Qwen25VL.swift +++ b/Libraries/MLXVLM/Models/Qwen25VL.swift @@ -152,9 +152,9 @@ private enum Language { keys = kEmbed } else { // Simple sequential RoPE for autoregressive generation - 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( diff --git a/Libraries/MLXVLM/Models/Qwen2VL.swift b/Libraries/MLXVLM/Models/Qwen2VL.swift index 3b86cf5fad..9c1f3374bb 100644 --- a/Libraries/MLXVLM/Models/Qwen2VL.swift +++ b/Libraries/MLXVLM/Models/Qwen2VL.swift @@ -162,9 +162,9 @@ private enum Language { keys = (keys * cos) + (QwenVL.rotateHalf(keys) * sin) } else { // Simple sequential RoPE (no-image / text-only path) - 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( diff --git a/Tests/MLXLMTests/BatchKVCacheTests.swift b/Tests/MLXLMTests/BatchKVCacheTests.swift new file mode 100644 index 0000000000..86d4681559 --- /dev/null +++ b/Tests/MLXLMTests/BatchKVCacheTests.swift @@ -0,0 +1,1122 @@ +// Copyright © 2026 Apple Inc. + +import Foundation +import MLX +import MLXVLM +import Testing + +@testable import MLXLLM +@testable import MLXLMCommon + +@Suite(.serialized) +struct BatchKVCacheTests { + + @Test("Text-only Idefics3 uses each ragged row's rotary positions", arguments: [2, 3]) + func ideficsRaggedPositions(batchSize: Int) throws { + try Device.withDefaultDevice(.cpu) { + let model = try tinyIdefics3ForBatchPositions() + let prompts = Array( + [[1, 2, 3], Array(4 ..< 11), Array(11 ..< 20)].prefix(batchSize)) + var singles = try prompts.map { prompt in + let cache = try model.newCache(parameters: nil) + let logits = model(MLXArray(prompt.map { Int32($0) })[.newAxis], cache: cache) + eval(logits) + eval(cache) + return cache + } + let batch = try singles[0].indices.map { layer in + try mergeCaches(singles.map { $0[layer] }) + } + let first = try #require(batch.first as? BatchKVCache) + #expect(first.batchOffset.asArray(Int32.self) == prompts.map { Int32($0.count) }) + + var generated = 0 + for length in [1, 2] { + let tokens = MLXArray( + singles.indices.flatMap { row in + (0 ..< length).map { Int32(21 + row * 7 + generated + $0) } + } + ).reshaped([singles.count, length]) + try expectIdeficsChunk(model, tokens: tokens, batch: batch, singles: singles) + generated += length + } + + let keep = batchSize == 2 ? [1] : [2, 0] + let indices = MLXArray(keep.map { Int32($0) }) + for layer in batch { layer.filter(batchIndices: indices) } + singles = keep.map { singles[$0] } + if batchSize == 2 { + guard case .scalar(let position) = first.ropeOffset else { + Issue.record("the surviving single row must retain its scalar RoPE path") + return + } + #expect(position == singles[0][0].offset) + } + let afterFilter = MLXArray( + singles.indices.flatMap { row in [Int32(41 + row), Int32(44 + row)] } + ).reshaped([singles.count, 2]) + try expectIdeficsChunk(model, tokens: afterFilter, batch: batch, singles: singles) + + let admitted = try model.newCache(parameters: nil) + let prefix = MLXArray([Int32(30), 31, 32, 33, 34])[.newAxis] + eval(model(prefix, cache: admitted)) + eval(admitted) + for layer in batch.indices { + let added = try mergeCaches([admitted[layer]]) + try batch[layer].validateExtension(other: added) + batch[layer].extend(other: added) + } + singles.append(admitted) + let afterAdmission = MLXArray( + singles.indices.flatMap { row in [Int32(47 + row), Int32(50 + row)] } + ).reshaped([singles.count, 2]) + try expectIdeficsChunk(model, tokens: afterAdmission, batch: batch, singles: singles) + } + } + + @Test("The row methods and merge dispatch through the BatchableKVCache type") + func protocolSurface() throws { + let rows: [any KVCache] = [KVCacheSimple(), KVCacheSimple()] + let batch = try mergeCaches(rows) + #expect(batch is BatchKVCache) + let (keys, values) = makeDistinctKV(batchSize: 2, heads: 2, seqLen: 3, headDim: 4) + _ = batch.update(keys: keys, values: values) + batch.filter(batchIndices: batchRows(1)) + #expect((batch as? BatchKVCache)?.batchSize == 1) + let added = try mergeCaches([KVCacheSimple()]) + _ = added.update(keys: keys[0 ..< 1], values: values[0 ..< 1]) + batch.extend(other: added) + #expect((batch as? BatchKVCache)?.batchSize == 2) + let row = try #require(batch.extract(0) as? KVCacheSimple) + let rowKeys = try #require(row.state.first) + #expect(maxAbsDifference(rowKeys, MLXArray.ones(rowKeys.shape) * 2) == 0) + } + + @Test("Extension checks refuse incompatible full-precision storage") + func extensionValidation() throws { + try Device.withDefaultDevice(.cpu) { + let full = BatchKVCache(leftPadding: [0]) + let kv = makeKV(batchSize: 1, heads: 2, seqLen: 3, headDim: 4) + _ = full.update(keys: kv.0, values: kv.1) + let compatible = BatchKVCache(leftPadding: [0]) + _ = compatible.update(keys: kv.0, values: kv.1) + try full.validateExtension(other: compatible) + #expect(full.batchSize == 1) + full.extend(other: compatible) + #expect(full.batchSize == 2) + + let wrongWidth = BatchKVCache(leftPadding: [0]) + let wider = makeKV(batchSize: 1, heads: 2, seqLen: 3, headDim: 8) + _ = wrongWidth.update(keys: wider.0, values: wider.1) + #expect(throws: KVCacheError.self) { try full.validateExtension(other: wrongWidth) } + let prepared = BatchKVCache(leftPadding: [0, 0]) + prepared.prepare(lengths: [1, 2]) + #expect(throws: KVCacheError.self) { try full.validateExtension(other: prepared) } + + // A cache without a batched form has no extension check to call; admission + // refuses it when it merges the rows. + #expect(!(BaseKVCache() as any KVCache is any BatchableKVCache)) + #expect(throws: KVCacheError.self) { _ = try mergeCaches([BaseKVCache()]) } + } + } + + @Test("Only batched caches take row operations; merging any other cache throws") + func batchableConformance() throws { + let singles: [any KVCache] = [KVCacheSimple(), ChunkedKVCache(chunkSize: 4)] + for cache in singles { + #expect(!(cache is any BatchableKVCache), "\(type(of: cache))") + } + #expect(BatchKVCache(leftPadding: [0]) as any KVCache is any BatchableKVCache) + #expect(throws: KVCacheError.self) { _ = try mergeCaches([ChunkedKVCache(chunkSize: 4)]) } + #expect(throws: KVCacheError.self) { _ = try BatchKVCache.merge([any KVCache]()) } + // A batch is not a row: merging it again throws instead of nesting batches. + #expect(throws: KVCacheError.self) { + _ = try mergeCaches([BatchKVCache(leftPadding: [0])]) + } + } + + @Test("Update, filter, extend and extract keep each row's tokens") + func lifecycle() throws { + let cache = BatchKVCache(leftPadding: [0, 0]) + let (keys, values) = makeDistinctKV(batchSize: 2, heads: 2, seqLen: 3, headDim: 4) + _ = cache.update(keys: keys, values: values) + + cache.filter(batchIndices: batchRows(0)) + #expect(cache.batchSize == 1) + #expect(cache.leftPadding.asArray(Int32.self) == [0]) + + let added = BatchKVCache(leftPadding: [0]) + let addedKV = makePositionKV(positions: 0 ..< 2, heads: 2, headDim: 4) + _ = added.update(keys: addedKV.0, values: addedKV.1) + cache.extend(other: added) + + #expect(cache.batchSize == 2) + #expect(cache.leftPadding.asArray(Int32.self) == [0, 1]) + #expect(cache.batchOffset.asArray(Int32.self) == [3, 2]) + #expect(cache.extract(0).offset == 3) + + let second = cache.extract(1) + #expect(second.offset == 2) + #expect(maxAbsDifference(try #require(second.state.first), addedKV.0) == 0) + #expect(maxAbsDifference(try #require(second.state.last), addedKV.1) == 0) + } + + @Test("Filtering during a ragged prefill keeps the survivors' right padding") + func filterDuringRaggedPrefill() throws { + let cache = BatchKVCache(leftPadding: [0, 0]) + cache.prepare(lengths: [3, 5]) + let kv = makeDistinctKV(batchSize: 2, heads: 2, seqLen: 5, headDim: 4) + _ = cache.update(keys: kv.0, values: kv.1) + + cache.filter(batchIndices: batchRows(1)) + cache.finalize() + + let row = cache.extract(0) + #expect(row.offset == 5) + #expect(cache.leftPadding.asArray(Int32.self) == [0]) + let keys = try #require(row.state.first) + #expect(maxAbsDifference(keys, MLXArray.ones(keys.shape) * 2) == 0) + let values = try #require(row.state.last) + #expect(maxAbsDifference(values, MLXArray.ones(values.shape) * 20) == 0) + } + + @Test("Filtering drops no more shared left padding than the buffer holds") + func filterBeforePaddingIsWritten() throws { + // A left-padded prompt fed in chunks: the first two positions are padding in both rows. + let cache = BatchKVCache(leftPadding: [3, 4]) + let padding = makeKV(batchSize: 2, heads: 2, seqLen: 2, headDim: 4, value: 0) + _ = cache.update(keys: padding.0, values: padding.1) + + cache.filter(batchIndices: batchRows(0, 1)) + try #require(cache.offset == 0) + #expect(cache.leftPadding.asArray(Int32.self) == [1, 2]) + #expect(cache.batchOffset.asArray(Int32.self) == [-1, -2]) + + let rest = makeDistinctKV(batchSize: 2, heads: 2, seqLen: 3, headDim: 4) + _ = cache.update(keys: rest.0, values: rest.1) + #expect(cache.batchOffset.asArray(Int32.self) == [2, 1]) + let row = cache.extract(0) + #expect(row.offset == 2) + let keys = try #require(row.state.first) + #expect(maxAbsDifference(keys, rest.0[0 ..< 1, 0..., 1..., 0...]) == 0) + } + + @Test("extract refuses a row index past the batch") + func extractOutOfRange() async throws { + let result = try await #require( + processExitsWith: .failure, observing: [\.standardErrorContent] + ) { + Device.withDefaultDevice(.cpu) { + let cache = BatchKVCache(leftPadding: [0, 1]) + let kv = makeKV(batchSize: 2, heads: 1, seqLen: 3, headDim: 1) + _ = cache.update(keys: kv.0, values: kv.1) + _ = cache.extract(2) + } + } + #expect( + String(decoding: result.standardErrorContent, as: UTF8.self).contains( + "BatchKVCache row index out of range")) + } + + @Test("extract returns an empty row when its padding covers every written position") + func extractPaddingOnlyRow() throws { + let cache = BatchKVCache(leftPadding: [4, 0]) + let kv = makeDistinctKV(batchSize: 2, heads: 2, seqLen: 1, headDim: 4) + _ = cache.update(keys: kv.0, values: kv.1) + + let padded = try #require(cache.extract(0) as? KVCacheSimple) + #expect(padded.offset == 0) + #expect(padded.keys == nil) + #expect(padded.values == nil) + let written = cache.extract(1) + #expect(written.offset == 1) + #expect(maxAbsDifference(try #require(written.state.first), kv.0[1 ..< 2]) == 0) + } + + @Test("extract refuses a ragged prefill before finalize") + func extractBeforeFinalize() async throws { + let result = try await #require( + processExitsWith: .failure, observing: [\.standardErrorContent] + ) { + Device.withDefaultDevice(.cpu) { + let cache = BatchKVCache(leftPadding: [0, 0]) + cache.prepare(lengths: [1, 3]) + let kv = makeKV(batchSize: 2, heads: 1, seqLen: 3, headDim: 1) + _ = cache.update(keys: kv.0, values: kv.1) + _ = cache.extract(0) + } + } + #expect( + String(decoding: result.standardErrorContent, as: UTF8.self).contains( + "BatchKVCache.extract takes finalized rows")) + } + + @Test("merge throws for rows it cannot stack, also a single row") + func mergeRefusesMismatchedRows() throws { + func row( + heads: Int = 2, headDim: Int = 4, rows: Int = 1, dtype: DType = .float32 + ) -> KVCacheSimple { + let cache = KVCacheSimple() + let kv = makeKV(batchSize: rows, heads: heads, seqLen: 3, headDim: headDim) + _ = cache.update(keys: kv.0.asType(dtype), values: kv.1.asType(dtype)) + return cache + } + // Rows of one class that disagree on layout, also behind an empty first row. + let mismatched: [[any KVCache]] = [ + [row(), row(headDim: 8)], + [KVCacheSimple(), row(), row(headDim: 8)], + [row(), row(heads: 4)], + [row(), row(dtype: .float16)], + ] + for rows in mismatched { + #expect(throws: KVCacheError.self) { _ = try mergeCaches(rows) } + } + // A cache holding two rows is not a row, also alone: admission merges one at a time. + #expect(throws: KVCacheError.self) { _ = try mergeCaches([row(rows: 2)]) } + #expect(throws: KVCacheError.self) { _ = try mergeCaches([row(), row(rows: 2)]) } + + let merged = try mergeCaches([KVCacheSimple(), row(), row()]) + #expect((merged as? BatchKVCache)?.batchSize == 3) + } + + @Test("finalize keeps every row's tokens when the buffer has spare capacity") + func finalizeWithSpareCapacity() throws { + let cache = BatchKVCache(leftPadding: [0, 0]) + cache.prepare(lengths: [3, 5]) + // Row 0 holds 3 tokens and 2 right-padding slots, row 1 holds 5 tokens. + var stamps = [Float](repeating: 0, count: 10) + for row in 0 ..< 2 { + for position in 0 ..< (row == 0 ? 3 : 5) { + stamps[row * 5 + position] = Float(10 * (row + 1) + position) + } + } + let keys = MLXArray(stamps, [2, 1, 5, 1]) + _ = cache.update(keys: keys, values: keys * 2) + + cache.finalize() + + let first = try #require(cache.extract(0) as? KVCacheSimple) + #expect(first.offset == 3) + #expect(try #require(first.keys).asArray(Float.self) == [10, 11, 12]) + #expect(try #require(first.values).asArray(Float.self) == [20, 22, 24]) + let second = try #require(cache.extract(1) as? KVCacheSimple) + #expect(second.offset == 5) + #expect(try #require(second.keys).asArray(Float.self) == [20, 21, 22, 23, 24]) + #expect(try #require(second.values).asArray(Float.self) == [40, 42, 44, 46, 48]) + } + + @Test("merge of one cache and extract round-trip a sequence") + func mergeRoundTrip() throws { + let single = KVCacheSimple() + let kv = makePositionKV(positions: 0 ..< 4, heads: 2, headDim: 4) + _ = single.update(keys: kv.0, values: kv.1) + + let batch = KVCacheSimple.merge([single]) + #expect(batch.batchSize == 1) + + let restored = batch.extract(0) + #expect(restored.offset == single.offset) + #expect( + maxAbsDifference(try #require(restored.state.first), try #require(single.state.first)) + == 0) + #expect( + maxAbsDifference(try #require(restored.state.last), try #require(single.state.last)) + == 0) + + // Writing to the batch leaves the source unchanged. + let next = makePositionKV(positions: 4 ..< 5, heads: 2, headDim: 4) + _ = batch.update(keys: next.0, values: next.1) + #expect(single.offset == 4) + #expect(maxAbsDifference(try #require(single.state.first), kv.0) == 0) + } + + @Test("merge left-pads ragged rows and takes empty caches as empty rows") + func mergeRaggedRows() throws { + let longer = KVCacheSimple() + let kv = makePositionKV(positions: 0 ..< 2, heads: 2, headDim: 4) + _ = longer.update(keys: kv.0, values: kv.1) + let merged = KVCacheSimple.merge([longer, KVCacheSimple()]) + #expect(merged.leftPadding.asArray(Int32.self) == [0, 2]) + #expect(merged.batchOffset.asArray(Int32.self) == [2, 0]) + #expect(merged.offset == 2) + #expect(merged.extract(0).offset == 2) + #expect(merged.extract(1).offset == 0) + + // Two empty caches merge into an empty two-row batch. + let empty = KVCacheSimple.merge([KVCacheSimple(), KVCacheSimple()]) + #expect(empty.batchSize == 2) + #expect(empty.offset == 0) + } + + @Test("trim drops the newest tokens, no more than the shortest row holds") + func trimClampsToShortestRow() throws { + let cache = BatchKVCache(leftPadding: [2, 0]) + let kv = makePositionKV( + positions: 0 ..< 3, heads: 2, headDim: 4, batchSize: 2, rowStride: 10) + _ = cache.update(keys: kv.0, values: kv.1) + + #expect(cache.trim(2) == 1) + #expect(cache.batchOffset.asArray(Int32.self) == [0, 2]) + #expect(cache.extract(0).offset == 0) + let second = cache.extract(1) + #expect(second.offset == 2) + #expect(try #require(second.state.first)[0, 0, 0..., 0].asArray(Float.self) == [10, 11]) + #expect(try #require(second.state.last)[0, 0, 0..., 0].asArray(Float.self) == [110, 111]) + } + + @Test("maxTrimCount reports only what trim can remove") + func maxTrimCountMatchesTrim() { + let cache = BatchKVCache(leftPadding: [2, 0]) + let kv = makeKV(batchSize: 2, heads: 2, seqLen: 3, headDim: 4) + _ = cache.update(keys: kv.0, values: kv.1) + + #expect(cache.maxTrimCount == 1) + #expect(!canTrimPromptCache([cache], numTokens: 2)) + #expect(canTrimPromptCache([cache], numTokens: 1)) + #expect(cache.trim(1) == 1) + } + + @Test( + "Staged rounds refuse writes that cannot rewind every row's padding", + arguments: [0, 2], [1, 2, 5]) + func paddedRoundIsRefused(written: Int, width: Int) throws { + try Device.withDefaultDevice(.cpu) { + let cache = BatchKVCache(leftPadding: [3, 0]) + if written > 0 { + let kv = makePositionKV( + positions: 0 ..< written, heads: 1, headDim: 1, batchSize: 2, rowStride: 10) + _ = cache.update(keys: kv.0, values: kv.1) + } + let state = cache.state.map { $0.asArray(Int32.self) } + let storage = KVCacheStorage([cache], plan: .disabled) + #expect(cache.isTrimmable) + #expect(!cache.isTrimmable(after: width)) + let refused = storage.beginRound(maximumPositions: width) + #expect(refused == nil) + // Old code admits the round. Keep the negative regression safe by writing nothing. + if let refused { storage.rollback(refused) } + #expect(cache.offset == written) + #expect(cache.state.map { $0.asArray(Int32.self) } == state) + #expect(storage.processedTokenCount == written) + #expect(storage.nativeAttentionOffsetsAreAligned) + + #expect(cache.isTrimmable(after: 0)) + let empty = try #require(storage.beginRound(maximumPositions: 0)) + storage.rollback(empty) + #expect(cache.state.map { $0.asArray(Int32.self) } == state) + #expect(storage.nativeAttentionOffsetsAreAligned) + } + } + + @Test("A zero-row batch refuses positive staged rounds", arguments: [false, true]) + func zeroRowRoundIsRefused(filtered: Bool) throws { + try Device.withDefaultDevice(.cpu) { + let cache = BatchKVCache(leftPadding: filtered ? [0] : []) + if filtered { + let kv = makeKV(batchSize: 1, heads: 1, seqLen: 3, headDim: 1) + _ = cache.update(keys: kv.0, values: kv.1) + cache.filter(batchIndices: batchRows()) + } + let storage = KVCacheStorage([cache], plan: .disabled) + #expect(!cache.isTrimmable(after: 2)) + let refused = storage.beginRound(maximumPositions: 2) + #expect(refused == nil) + if let refused { storage.rollback(refused) } + #expect(cache.batchSize == 0) + #expect(cache.offset == 0) + #expect(storage.processedTokenCount == 0) + #expect(storage.nativeAttentionOffsetsAreAligned) + + #expect(cache.isTrimmable(after: 0)) + let empty = try #require(storage.beginRound(maximumPositions: 0)) + storage.rollback(empty) + #expect(cache.offset == 0) + #expect(storage.nativeAttentionOffsetsAreAligned) + } + } + + @Test( + "A staged round rewinds exactly after every row has consumed its padding", + arguments: [0, 1]) + func roundAfterPaddingCommitsExactly(retaining: Int) throws { + try Device.withDefaultDevice(.cpu) { + let cache = BatchKVCache(leftPadding: [3, 0]) + let prefix = makePositionKV( + positions: 0 ..< 3, heads: 1, headDim: 1, batchSize: 2, rowStride: 10) + _ = cache.update(keys: prefix.0, values: prefix.1) + let storage = KVCacheStorage([cache], plan: .disabled) + #expect(cache.isTrimmable(after: 2)) + #expect(!cache.isTrimmable(after: -1)) + let round = try #require(storage.beginRound(maximumPositions: 2)) + let proposed = makePositionKV( + positions: 3 ..< 5, heads: 1, headDim: 1, batchSize: 2, rowStride: 10) + _ = round.caches[0].update(keys: proposed.0, values: proposed.1) + let result = storage.commit(round, retaining: retaining) + + #expect(result.committedPositions == retaining) + #expect(result.discardedPositions == 2 - retaining) + #expect(cache.offset == 3 + retaining) + #expect( + cache.batchOffset.asArray(Int32.self) == [Int32(retaining), Int32(3 + retaining)]) + #expect(storage.processedTokenCount == 3 + retaining) + #expect(storage.nativeAttentionOffsetsAreAligned) + let expected = makePositionKV( + positions: 0 ..< 3 + retaining, heads: 1, headDim: 1, batchSize: 2, rowStride: 10) + let state = cache.state + #expect(maxAbsDifference(state[0], expected.0) == 0) + #expect(maxAbsDifference(state[1], expected.1) == 0) + } + } + + @Test("Empty rows join empty rows, and the batch fills on its first update") + func extendEmptyRows() throws { + let cache = BatchKVCache(leftPadding: [0]) + cache.extend(other: BatchKVCache(leftPadding: [1])) + #expect(cache.batchSize == 2) + #expect(cache.leftPadding.asArray(Int32.self) == [0, 1]) + #expect(cache.batchOffset.asArray(Int32.self) == [0, -1]) + + let kv = makeDistinctKV(batchSize: 2, heads: 2, seqLen: 3, headDim: 4) + _ = cache.update(keys: kv.0, values: kv.1) + #expect(cache.batchOffset.asArray(Int32.self) == [3, 2]) + #expect(cache.extract(1).offset == 2) + } + + @Test("Prefilled rows join empty rows as padding, and a zero-row batch changes nothing") + func extendMixedRows() throws { + let cache = BatchKVCache(leftPadding: [0]) + let added = BatchKVCache(leftPadding: [0]) + let kv = makePositionKV(positions: 0 ..< 3, heads: 2, headDim: 4) + _ = added.update(keys: kv.0, values: kv.1) + cache.extend(other: added) + #expect(cache.batchSize == 2) + #expect(cache.leftPadding.asArray(Int32.self) == [3, 0]) + #expect(cache.batchOffset.asArray(Int32.self) == [0, 3]) + #expect(cache.extract(0).offset == 0) + #expect(maxAbsDifference(try #require(cache.extract(1).state.first), kv.0) == 0) + + // The empty row's first token lands after its padding, the other row's after its history. + let next = makePositionKV(positions: 10 ..< 11, heads: 2, headDim: 4, batchSize: 2) + _ = cache.update(keys: next.0, values: next.1) + #expect(cache.batchOffset.asArray(Int32.self) == [1, 4]) + #expect( + try #require(cache.extract(0).state.first)[0, 0, 0..., 0].asArray(Float.self) == [10]) + #expect(cache.extract(1).offset == 4) + + // The other way round, and a batch with no rows. + let populated = BatchKVCache(leftPadding: [0]) + _ = populated.update(keys: kv.0, values: kv.1) + populated.extend(other: BatchKVCache(leftPadding: [0])) + populated.extend(other: BatchKVCache(leftPadding: [])) + #expect(populated.batchSize == 2) + #expect(populated.leftPadding.asArray(Int32.self) == [0, 3]) + #expect(populated.batchOffset.asArray(Int32.self) == [3, 0]) + } + + @Test("An empty cache extended from another does not share its arrays") + func extendEmptyCacheCopies() throws { + let source = BatchKVCache(leftPadding: [0]) + let prompt = makePositionKV(positions: 0 ..< 2, heads: 2, headDim: 4) + _ = source.update(keys: prompt.0, values: prompt.1) + let cache = BatchKVCache(leftPadding: []) + cache.extend(other: source) + + // Both writes land inside the buffer the source allocated. + let next = makePositionKV(positions: 50 ..< 51, heads: 2, headDim: 4) + _ = cache.update(keys: next.0, values: next.1) + let sourceNext = makePositionKV(positions: 70 ..< 71, heads: 2, headDim: 4) + _ = source.update(keys: sourceNext.0, values: sourceNext.1) + + let keys = try #require(cache.extract(0).state.first) + #expect(keys[0, 0, 0..., 0].asArray(Float.self) == [0, 1, 50]) + let sourceKeys = try #require(source.extract(0).state.first) + #expect(sourceKeys[0, 0, 0..., 0].asArray(Float.self) == [0, 1, 70]) + } + + @Test("One token with no left padding needs no mask; padding brings it back") + func oneTokenWithoutPaddingHasNoMask() throws { + let cache = BatchKVCache(leftPadding: [0, 0]) + let (keys, values) = makeDistinctKV(batchSize: 2, heads: 2, seqLen: 3, headDim: 4) + _ = cache.update(keys: keys, values: values) + guard case .none = cache.makeMask(n: 1, windowSize: nil, returnArray: false) else { + Issue.record("unpadded rows must decode one token without a mask") + return + } + guard case .array = cache.makeMask(n: 2, windowSize: nil, returnArray: false) else { + Issue.record("more than one token keeps the explicit mask") + return + } + + // Joining a shorter row pads it, so the one-token mask returns. + let added = BatchKVCache(leftPadding: [0]) + let addedKV = makePositionKV(positions: 0 ..< 2, heads: 2, headDim: 4) + _ = added.update(keys: addedKV.0, values: addedKV.1) + cache.extend(other: added) + guard case .array(let mask) = cache.makeMask(n: 1, windowSize: nil, returnArray: false) + else { + Issue.record("a padded batch must mask its padding") + return + } + #expect(mask[2, 0, 0, 0].item(Bool.self) == false) + + // Keeping only the padded row makes its padding shared, which filter drops. + cache.filter(batchIndices: batchRows(2)) + guard case .none = cache.makeMask(n: 1, windowSize: nil, returnArray: false) else { + Issue.record("padding dropped by filter must not keep the mask") + return + } + #expect(cache.batchOffset.asArray(Int32.self) == [2]) + #expect(cache.offset == 2) + } + + @Test("A window smaller than the history keeps the one-token mask") + func windowKeepsOneTokenMask() throws { + let cache = BatchKVCache(leftPadding: [0]) + let (keys, values) = makeDistinctKV(batchSize: 1, heads: 2, seqLen: 8, headDim: 4) + _ = cache.update(keys: keys, values: values) + guard case .none = cache.makeMask(n: 1, windowSize: 9, returnArray: false) else { + Issue.record("a window covering every key needs no mask") + return + } + guard case .array(let mask) = cache.makeMask(n: 1, windowSize: 4, returnArray: false) + else { + Issue.record("a window smaller than the history must keep the mask") + return + } + try #require(mask.shape.last == 9) + // The query at position 8 sees positions 5...8 only. + #expect(mask[0, 0, 0, 4].item(Bool.self) == false) + #expect(mask[0, 0, 0, 5].item(Bool.self) == true) + #expect(mask[0, 0, 0, 8].item(Bool.self) == true) + } + + @Test("The mask excludes each row's left padding, also for one token") + func maskExcludesLeftPadding() throws { + let cache = BatchKVCache(leftPadding: [1, 3, 0]) + for n in [1, 2] { + guard case .array(let mask) = cache.makeMask(n: n, windowSize: nil, returnArray: false) + else { + Issue.record("BatchKVCache must return an array mask") + return + } + try #require(mask.dim(0) == 3) + #expect(mask[0, 0, 0, 0].item(Bool.self) == false) + #expect(mask[1, 0, 0, 0].item(Bool.self) == false) + #expect(mask[2, 0, 0, 0].item(Bool.self) == true) + } + guard case .array(let mask) = cache.makeMask(n: 2, windowSize: nil, returnArray: false) + else { return } + // Row 0 (padding 1) attends position 1; row 1 (padding 3) does not. + #expect(mask[0, 0, 1, 1].item(Bool.self) == true) + #expect(mask[1, 0, 1, 1].item(Bool.self) == false) + } + + @Test("ropeOffset is per row through the KVCache type") + func ropeOffsetThroughKVCache() { + let kv = makeKV(batchSize: 2, heads: 2, seqLen: 3, headDim: 4) + let batch = BatchKVCache(leftPadding: [1, 0]) + _ = batch.update(keys: kv.0, values: kv.1) + let cache: any KVCache = batch + guard case .batch(let offsets) = cache.ropeOffset else { + Issue.record("BatchKVCache.ropeOffset must be .batch") + return + } + #expect(offsets.asArray(Int32.self) == [2, 3]) + } + + @Test("ropeOffset is scalar while every row shares one position") + func ropeOffsetScalarForSharedPosition() { + let kv = makeKV(batchSize: 2, heads: 2, seqLen: 3, headDim: 4) + let batch = BatchKVCache(leftPadding: [0, 0]) + _ = batch.update(keys: kv.0, values: kv.1) + guard case .scalar(let offset) = batch.ropeOffset else { + Issue.record("rows at one position must use the scalar offset") + return + } + #expect(offset == 3) + #expect(batch.batchOffset.asArray(Int32.self) == [3, 3]) + + // A shorter row joining the batch gives the rows different positions. + let added = BatchKVCache(leftPadding: [0]) + let addedKV = makePositionKV(positions: 0 ..< 2, heads: 2, headDim: 4) + _ = added.update(keys: addedKV.0, values: addedKV.1) + batch.extend(other: added) + guard case .batch(let offsets) = batch.ropeOffset else { + Issue.record("rows at different positions must use per-row offsets") + return + } + #expect(offsets.asArray(Int32.self) == [3, 3, 2]) + } + + @Test("createCausalMask masks each row's left padding") + func causalMaskWithLeftPadding() throws { + let mask = createCausalMask(n: 4, offset: 0, leftPadding: MLXArray([Int32(1), 2])) + try #require(mask.shape == [2, 1, 4, 4]) + #expect(mask[0, 0, 0, 0].item(Bool.self) == false) + #expect(mask[0, 0, 1, 1].item(Bool.self) == true) + #expect(mask[1, 0, 1, 1].item(Bool.self) == false) + #expect(mask[1, 0, 3, 1].item(Bool.self) == false) + #expect(mask[1, 0, 2, 2].item(Bool.self) == true) + } + + @Test("The cache status counts every row's bytes as one full-precision attention layer") + func statusCountsRows() throws { + let rows = (0 ..< 3).map { _ in KVCacheSimple() } + for row in rows { + let kv = makeKV(batchSize: 1, heads: 2, seqLen: 5, headDim: 8) + _ = row.update(keys: kv.0, values: kv.1) + } + let batch = KVCacheSimple.merge(rows) + + let status = KVCacheStatus(cache: [batch]) + try #require(status.layers.count == 1) + #expect(status.layers[0].kind == .attention(maxSize: nil)) + #expect(status.layers[0].state == .active) + #expect(status.layers[0].resolvedStrategy == .fullPrecision) + let rowBytes = (0 ..< 3).map { batch.extract($0) }.reduce(0) { bytes, row in + bytes + row.innerState().reduce(0) { $0 + $1.nbytes } + } + #expect(status.memoryBytes == rowBytes) + + // A batch holds full-precision rows only; compression skips it rather than rewriting it. + let affine = kvCacheLayerStatuses( + cache: [batch], configuration: KVCacheConfiguration(strategy: .affine(.fourBit))) + #expect(affine[0].state == .skipped) + #expect(affine[0].reason == .unsupportedShape) + } + + @Test("A batched cache cannot be saved as a prompt cache") + func savePromptCacheRefuses() { + let cache = BatchKVCache(leftPadding: [0, 1]) + let (keys, values) = makeKV(batchSize: 2, heads: 2, seqLen: 3, headDim: 4) + _ = cache.update(keys: keys, values: values) + + let url = FileManager.default.temporaryDirectory + .appendingPathComponent("batch-cache-\(UUID().uuidString).safetensors") + #expect(throws: (any Error).self) { + try savePromptCache(url: url, cache: [cache]) + } + #expect(!FileManager.default.fileExists(atPath: url.path)) + } +} + +/// Batched caches must give every row the logits and the keys and values it gets on its own. +@Suite(.serialized) +struct BatchedDecodeParityTests { + + @Test( + "Mistral 3 text preserves each row's scaling with and without llama4 scaling", + arguments: [Optional.none, .some(0), .some(1)]) + func mistral3Scaling(beta: Float?) throws { + try Device.withDefaultDevice(.cpu) { + let model = tinyMistral3Text(beta: beta) + try expectBatchedRowsMatchSingles(model) + try expectMergedRowsMatchSingles(model) + } + } + + @Test("Mistral 3 scaling follows ragged rows through chunks, admission and removal") + func mistral3ScalingLifecycle() throws { + try Device.withDefaultDevice(.cpu) { + try expectScalingLifecycle(tinyMistral3Text(beta: 1)) + } + } + + @Test("Nemotron Labs Diffusion AR scaling follows each ragged row") + func nemotronLabsScaling() throws { + try Device.withDefaultDevice(.cpu) { + let configuration = try JSONDecoder().decode( + NemotronLabsDiffusionConfiguration.self, + from: Data( + """ + { + "hidden_size": 32, "num_hidden_layers": 2, "intermediate_size": 64, + "num_attention_heads": 4, "num_key_value_heads": 2, "head_dim": 8, + "rms_norm_eps": 1e-5, "vocab_size": 64, "rope_theta": 10000.0, + "rope_parameters": { + "llama_4_scaling_beta": 1.0, "original_max_position_embeddings": 4 + } + } + """.utf8)) + let model = withRandomState(MLXRandom.RandomState(seed: 706)) { + let model = NemotronLabsDiffusionModel(configuration) + eval(model) + return model + } + try expectScalingLifecycle(model) + } + } + + @Test("Batched llama4 scaling keeps negative padding finite and scales the batch axis") + func negativePaddingScale() { + Device.withDefaultDevice(.cpu) { + let scale = batchedLlama4AttentionScale( + offsets: MLXArray([Int32(-3), 1]), length: 5, beta: 1, + maxPositionEmbeddings: 4) + #expect(scale.shape == [2, 1, 5, 1]) + let actual = scale.asArray(Float.self) + let allFinite = actual.allSatisfy(\.isFinite) + #expect(allFinite) + #expect(Array(actual.prefix(5)) == Array(repeating: Float(1), count: 5)) + #expect(abs(actual[8] - (1 + log(Float(2)))) < 1e-6) + let scaledQueries = MLXArray.ones([2, 4, 5, 8]) * scale + #expect(scaledQueries.shape == [2, 4, 5, 8]) + #expect(scaledQueries[0].max().item(Float.self) == 1) + #expect(abs(scaledQueries[1].max().item(Float.self) - (1 + log(Float(2)))) < 1e-6) + } + } + + @Test("A ragged batch of Llama prompts decodes like separate sequences") + func llama() throws { + try Device.withDefaultDevice(.cpu) { + let model = tinyLlama() + try expectBatchedRowsMatchSingles(model) + try expectMergedRowsMatchSingles(model) + } + } + + @Test("A ragged batch of Gemma 2 prompts decodes like separate sequences") + func gemma2() throws { + try Device.withDefaultDevice(.cpu) { + let model = try tinyGemma2() + try expectBatchedRowsMatchSingles(model) + try expectMergedRowsMatchSingles(model) + } + } + + @Test("Rows at one position behind a wider buffer decode at that position, not the buffer's") + func logicalPositionBehindPadding() throws { + try Device.withDefaultDevice(.cpu) { + let model = tinyLlama() + let prompts: [[Int32]] = [[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12]] + let singles = try prompts.map { prompt in + let cache = try model.newCache(parameters: nil) + eval(model(MLXArray(prompt).reshaped([1, prompt.count]), cache: cache)) + return cache + } + // Two positions of left padding in both rows: the buffer is eight wide, the rows six. + let widths: [IntOrPair] = [0, 0, .init((2, 0)), 0] + let batch = singles[0].indices.map { layer in + let cache = BatchKVCache(leftPadding: [2, 2]) + let rows = singles.map { $0[layer].state } + _ = cache.update( + keys: concatenated(rows.map { MLX.padded($0[0], widths: widths) }), + values: concatenated(rows.map { MLX.padded($0[1], widths: widths) })) + return cache + } + // `offset` counts the rows' six tokens, not the eight buffer positions, so cache + // storage adopts the batch at the position a single-row cache would report. + #expect(batch[0].offset == 6) + #expect(try #require(batch[0].state.first).dim(2) == 8) + #expect(batch[0].batchOffset.asArray(Int32.self) == [6, 6]) + let storage = KVCacheStorage(batch, plan: .disabled) + #expect(storage.processedTokenCount == 6) + #expect(storage.nativeAttentionOffsetsAreAligned) + guard case .scalar(let position) = batch[0].ropeOffset else { + Issue.record("rows at one position must use the scalar offset") + return + } + #expect(position == 6) + + for step in 0 ..< 3 { + let token = Int32(13 + step) + let output = model(MLXArray([token, token]).reshaped([2, 1]), cache: batch) + for row in prompts.indices { + let single = model(MLXArray([token]).reshaped([1, 1]), cache: singles[row]) + #expect( + maxAbsDifference(output[row ..< row + 1], single) < 1e-4, + "step \(step), row \(row)") + } + } + #expect(batch[0].batchOffset.asArray(Int32.self) == [9, 9]) + } + } +} + +private func tinyMistral3Text(beta: Float?) -> Mistral3TextModel { + let configuration = Mistral3TextConfiguration( + hiddenSize: 32, hiddenLayers: 2, intermediateSize: 64, attentionHeads: 4, + rmsNormEps: 1e-5, vocabularySize: 64, headDimensions: 8, kvHeads: 2, + ropeParameters: beta.map { + ["llama_4_scaling_beta": .float($0), "original_max_position_embeddings": .int(4)] + }) + return withRandomState(MLXRandom.RandomState(seed: 705)) { + let model = Mistral3TextModel(configuration) + eval(model) + return model + } +} + +/// Ragged positions cross scaling bands in batches both smaller than and equal to the head count. +private func expectScalingLifecycle(_ model: any LanguageModel) throws { + func prefill(_ prompt: [Int32]) throws -> [KVCache] { + let cache = try model.newCache(parameters: nil) + eval(model(MLXArray(prompt)[.newAxis], cache: cache)) + return cache + } + var singles = try [[Int32(1), 2, 3], [4, 5, 6, 7, 8, 9, 10]].map(prefill) + let batch = try singles[0].indices.map { layer in + try mergeCaches(singles.map { $0[layer].copy() }) + } + func decode(_ tokens: [[Int32]]) { + let length = tokens[0].count + let output = model( + MLXArray(tokens.flatMap { $0 }).reshaped([tokens.count, length]), cache: batch) + for row in tokens.indices { + let expected = model(MLXArray(tokens[row])[.newAxis], cache: singles[row]) + #expect( + maxAbsDifference(output[row ..< row + 1], expected) < 1e-4, + "row \(row), chunk length \(length)") + } + } + decode([[11, 12], [13, 14]]) + + let added = try [[Int32(15), 16], [17, 18, 19, 20, 21, 22]].map(prefill) + let incoming = try added[0].indices.map { layer in + try mergeCaches(added.map { $0[layer].copy() }) + } + for layer in batch.indices { + try batch[layer].validateExtension(other: incoming[layer]) + } + for layer in batch.indices { + batch[layer].extend(other: incoming[layer]) + } + singles += added + decode([[23, 24], [25, 26], [27, 28], [29, 30]]) + + batch.forEach { $0.filter(batchIndices: batchRows(3, 0)) } + singles = [singles[3], singles[0]] + decode([[31, 32, 33], [34, 35, 36]]) + batch.forEach { $0.filter(batchIndices: batchRows(1)) } + singles = [singles[1]] + decode([[37]]) +} + +func tinyLlama() -> LlamaModel { + withRandomState(MLXRandom.RandomState(seed: 7)) { + let model = LlamaModel( + LlamaConfiguration( + hiddenSize: 32, hiddenLayers: 2, intermediateSize: 64, + attentionHeads: 4, rmsNormEps: 1e-5, vocabularySize: 64, kvHeads: 2)) + eval(model) + return model + } +} + +/// The caches of `model`, as the single-sequence caches a batch is built from. +private func singleCaches(_ model: any LanguageModel) throws -> [KVCacheSimple] { + try model.newCache(parameters: nil).map { cache in + try #require(cache as? KVCacheSimple, "the parity models use plain caches") + } +} + +/// Merges fresh caches, prefills two prompts of different lengths as one right-padded batch, +/// decodes four tokens and drops a row, comparing every row's logits and extracted keys and +/// values with the same prompt run alone. +private func expectBatchedRowsMatchSingles(_ model: any LanguageModel) throws { + let prompts: [[Int32]] = [[1, 2, 3], [4, 5, 6, 7, 8]] + let longest = prompts.map(\.count).max()! + + var singles: [[any KVCache]] = [] + var expected: [MLXArray] = [] + for prompt in prompts { + let cache = try model.newCache(parameters: nil) + let logits = model(MLXArray(prompt).reshaped([1, prompt.count]), cache: cache) + singles.append(cache) + expected.append(logits[0..., (prompt.count - 1) ..< prompt.count, 0...]) + } + + // One fresh single cache per row, merged per layer into the empty batch. + let fresh = try prompts.map { _ in try singleCaches(model) } + let batched = fresh[0].indices.map { layer in KVCacheSimple.merge(fresh.map { $0[layer] }) } + let caches = batched.map { $0 as any KVCache } + batched.forEach { $0.prepare(lengths: prompts.map(\.count)) } + let padded = prompts.flatMap { $0 + Array(repeating: 0, count: longest - $0.count) } + let logits = model(MLXArray(padded).reshaped([prompts.count, longest]), cache: caches) + batched.forEach { $0.finalize() } + for (row, prompt) in prompts.enumerated() { + let actual = logits[row ..< row + 1, (prompt.count - 1) ..< prompt.count, 0...] + #expect(maxAbsDifference(actual, expected[row]) < 1e-4, "prefill, row \(row)") + } + try expectExtractedRowsMatch(batched, singles) + + for step in 0 ..< 4 { + let token = Int32(10 + step) + let output = model(MLXArray([token, token]).reshaped([2, 1]), cache: caches) + for row in prompts.indices { + let single = model(MLXArray([token]).reshaped([1, 1]), cache: singles[row]) + #expect( + maxAbsDifference(output[row ..< row + 1], single) < 1e-4, + "step \(step), row \(row)") + } + } + try expectExtractedRowsMatch(batched, singles) + + batched.forEach { $0.filter(batchIndices: batchRows(1)) } + let output = model(MLXArray([Int32(14)]).reshaped([1, 1]), cache: caches) + let single = model(MLXArray([Int32(14)]).reshaped([1, 1]), cache: singles[1]) + #expect(maxAbsDifference(output, single) < 1e-4, "after filtering") + try expectExtractedRowsMatch(batched, [singles[1]]) +} + +/// Prefills two prompts alone, merges their caches and decodes three tokens, comparing +/// every row with the same sequence continued alone. +private func expectMergedRowsMatchSingles(_ model: any LanguageModel) throws { + let prompts: [[Int32]] = [[1, 2, 3, 4, 5, 6], [7, 8]] + var singles: [[any KVCache]] = [] + var rows: [[KVCacheSimple]] = [] + for prompt in prompts { + let single = try model.newCache(parameters: nil) + eval(model(MLXArray(prompt).reshaped([1, prompt.count]), cache: single)) + singles.append(single) + let row = try singleCaches(model) + eval(model(MLXArray(prompt).reshaped([1, prompt.count]), cache: row)) + rows.append(row) + } + + let batched = rows[0].indices.map { layer in KVCacheSimple.merge(rows.map { $0[layer] }) } + #expect(batched[0].batchOffset.asArray(Int.self) == prompts.map(\.count)) + #expect(batched[0].leftPadding.asArray(Int.self) == [0, 4]) + let caches = batched.map { $0 as any KVCache } + try expectExtractedRowsMatch(batched, singles) + + for step in 0 ..< 3 { + let token = Int32(10 + step) + let output = model(MLXArray([token, token]).reshaped([2, 1]), cache: caches) + for row in prompts.indices { + let single = model(MLXArray([token]).reshaped([1, 1]), cache: singles[row]) + #expect( + maxAbsDifference(output[row ..< row + 1], single) < 1e-4, + "step \(step), row \(row)") + } + } + try expectExtractedRowsMatch(batched, singles) +} + +/// Every row extracted from `batch` holds the offset, keys and values of its single cache. +private func expectExtractedRowsMatch(_ batch: [BatchKVCache], _ singles: [[any KVCache]]) + throws +{ + for (row, caches) in singles.enumerated() { + try #require(caches.count == batch.count) + for layer in batch.indices { + let actual = batch[layer].extract(row) + #expect(actual.offset == caches[layer].offset, "row \(row), layer \(layer)") + let expected = caches[layer].state + try #require(actual.state.count == expected.count) + for (actualArray, expectedArray) in zip(actual.state, expected) { + try #require(actualArray.shape == expectedArray.shape) + #expect( + maxAbsDifference(actualArray, expectedArray) < 1e-4, + "row \(row), layer \(layer)") + } + } + } +} + +/// Keys and values with the same value at every position. Use this only for shape and +/// counter checks: it cannot show which positions an operation kept or their order. +func makeKV( + batchSize: Int, heads: Int, seqLen: Int, headDim: Int, value: Float = 1 +) -> (MLXArray, MLXArray) { + let keys = MLXArray.ones([batchSize, heads, seqLen, headDim]) * value + let values = MLXArray.ones([batchSize, heads, seqLen, headDim]) * (value + 1) + return (keys, values) +} + +/// Keys of `i + 1` and values of `(i + 1) * 10` in row `i`. +func makeDistinctKV(batchSize: Int, heads: Int, seqLen: Int, headDim: Int) -> (MLXArray, MLXArray) { + let rows = MLXArray((0 ..< batchSize).map { Float($0 + 1) }).reshaped([batchSize, 1, 1, 1]) + let ones = MLXArray.ones([batchSize, heads, seqLen, headDim]) + return (ones * rows, ones * rows * 10) +} + +/// Keys stamped with their position (plus `row * rowStride`), and values with the +/// key plus 100, so tests can check which positions survive and in what order. +func makePositionKV( + positions: Range, heads: Int, headDim: Int, batchSize: Int = 1, rowStride: Float = 0 +) -> (MLXArray, MLXArray) { + var stamps = [Float]() + for row in 0 ..< batchSize { + stamps.append(contentsOf: positions.map { Float($0) + Float(row) * rowStride }) + } + let stamp = MLXArray(stamps).reshaped([batchSize, 1, positions.count, 1]) + let ones = MLXArray.ones([batchSize, heads, positions.count, headDim]) + return (ones * stamp, ones * (stamp + 100)) +} + +func batchRows(_ indices: Int...) -> MLXArray { + MLXArray(indices.map { Int32($0) }) +} + +/// Two layers of grouped-query attention: four heads over two key-value heads. +func tinyGemma2Configuration() throws -> Gemma2Configuration { + try JSONDecoder().decode( + Gemma2Configuration.self, + from: Data( + """ + { + "hidden_size": 16, "num_hidden_layers": 2, "intermediate_size": 32, + "num_attention_heads": 4, "head_dim": 8, "rms_norm_eps": 1e-6, + "vocab_size": 32, "num_key_value_heads": 2, "attn_logit_softcapping": 50.0, + "final_logit_softcapping": 30.0, "query_pre_attn_scalar": 144.0 + } + """.utf8)) +} + +func tinyGemma2() throws -> Gemma2Model { + let configuration = try tinyGemma2Configuration() + return withRandomState(MLXRandom.RandomState(seed: 13)) { + let model = Gemma2Model(configuration) + eval(model) + return model + } +} + +/// A text-only fixture with 64-wide KV heads, shared with packed-cache parity tests. +func tinyIdefics3ForBatchPositions() throws -> Idefics3 { + let json = """ + { + "model_type": "idefics3", "vocab_size": 64, "scale_factor": 1, + "image_token_id": 63, "image_token_index": 63, + "text_config": { + "model_type": "llama", "hidden_size": 128, "num_hidden_layers": 2, + "intermediate_size": 256, "num_attention_heads": 2, "num_key_value_heads": 1, + "rms_norm_eps": 1e-5, "vocab_size": 64, "rope_theta": 10000.0, + "tie_word_embeddings": false + }, + "vision_config": { + "model_type": "siglip_vision_model", "hidden_size": 16, "num_hidden_layers": 1, + "num_attention_heads": 2, "intermediate_size": 32, "patch_size": 8, + "image_size": 16, "num_channels": 3 + } + } + """ + let configuration = try JSONDecoder().decode( + Idefics3Configuration.self, from: Data(json.utf8)) + return withRandomState(MLXRandom.RandomState(seed: 913)) { + let model = Idefics3(configuration) + model.train(false) + eval(model) + return model + } +} + +private func expectIdeficsChunk( + _ model: Idefics3, tokens: MLXArray, batch: [KVCache], singles: [[KVCache]], + sourceLocation: SourceLocation = #_sourceLocation +) throws { + let actual = model(tokens, cache: batch) + eval(actual) + eval(batch) + try #require( + actual.shape == [singles.count, tokens.dim(1), 64], sourceLocation: sourceLocation) + for row in singles.indices { + let expected = model(tokens[row ..< row + 1], cache: singles[row]) + eval(expected) + eval(singles[row]) + #expect( + maxAbsDifference(actual[row ..< row + 1], expected) < 1e-3, + "row \(row) must use its own rotary positions", sourceLocation: sourceLocation) + } +} diff --git a/Tests/MLXLMTests/Gemma2Tests.swift b/Tests/MLXLMTests/Gemma2Tests.swift index a24d60d7bb..0907c1ed70 100644 --- a/Tests/MLXLMTests/Gemma2Tests.swift +++ b/Tests/MLXLMTests/Gemma2Tests.swift @@ -9,13 +9,31 @@ import Foundation import MLX import MLXLLM -import MLXLMCommon import XCTest +@testable import MLXLMCommon + final class Gemma2Tests: XCTestCase { // MARK: - Tiny model + private final class RowLengthCache: KVCacheSimple { + let lengths: [Int32] + + init(lengths: [Int32]) { + self.lengths = lengths + super.init() + } + + override func makeMask( + n: Int, windowSize: Int?, returnArray: Bool + ) -> MLXFast.ScaledDotProductAttentionMaskMode { + .array( + createCausalMask( + n: n, offset: offset, windowSize: windowSize, lengths: MLXArray(lengths))) + } + } + private func makeTinyModel() throws -> Gemma2Model { let json = """ { @@ -73,6 +91,34 @@ final class Gemma2Tests: XCTestCase { XCTAssertLessThanOrEqual(maxAbsDiff(full, last), MatmulPrecision.splitTolerance) } + func testPerRowMaskMatchesIndependentSequences() throws { + try Device.withDefaultDevice(.cpu) { + let model = try makeTinyModel() + let prompts: [[Int32]] = [[3, 7, 1], [12, 5, 9, 2, 8]] + let longest = prompts.map(\.count).max()! + + var expected: [MLXArray] = [] + for prompt in prompts { + let logits = model( + MLXArray(prompt).reshaped([1, prompt.count]), + cache: try model.newCache(parameters: nil)) + expected.append(logits[0, prompt.count - 1]) + } + + let lengths = prompts.map { Int32($0.count) } + let cache = try model.newCache(parameters: nil).map { _ in + RowLengthCache(lengths: lengths) as KVCache + } + let padded = prompts.flatMap { $0 + Array(repeating: 0, count: longest - $0.count) } + let logits = model(MLXArray(padded).reshaped([prompts.count, longest]), cache: cache) + for (row, prompt) in prompts.enumerated() { + XCTAssertLessThan( + maxAbsDiff(logits[row, prompt.count - 1], expected[row]), 1e-4, + "row \(row)") + } + } + } + // MARK: - Warm continuation /// With a capacity-limited cache the mask must span the keys the cache diff --git a/Tests/MLXLMTests/Gemma4KVSharedLoadTests.swift b/Tests/MLXLMTests/Gemma4KVSharedLoadTests.swift index f1bdeb229e..ea47083393 100644 --- a/Tests/MLXLMTests/Gemma4KVSharedLoadTests.swift +++ b/Tests/MLXLMTests/Gemma4KVSharedLoadTests.swift @@ -27,6 +27,64 @@ import Testing struct Gemma4KVSharedLoadTests { + @Test( + "Gemma4 VLM text rows preserve rotary positions through KV-owning and shared layers", + arguments: [0, 2], [2, 3]) + func raggedTextPositions(numKVSharedLayers: Int, batchSize: Int) throws { + try Device.withDefaultDevice(.cpu) { + let model = tinyGemma4VLMTextForBatchPositions(numKVSharedLayers: numKVSharedLayers) + let prompts = Array( + [[1, 2, 3], Array(4 ..< 11), Array(11 ..< 20)].prefix(batchSize)) + var singles = try prompts.map { prompt in + let cache = try model.newCache(parameters: nil) + let output = model(MLXArray(prompt.map { Int32($0) })[.newAxis], cache: cache) + eval(output.logits) + eval(cache) + #expect(output.state == nil) + return cache + } + #expect(singles[0].count == 4 - numKVSharedLayers) + let batch = try singles[0].indices.map { layer in + try mergeCaches(singles.map { $0[layer] }) + } + + var generated = 0 + for length in [1, 2, 1] { + let tokens = MLXArray( + singles.indices.flatMap { row in + (0 ..< length).map { Int32(21 + row * 7 + generated + $0) } + } + ).reshaped([singles.count, length]) + try Self.expectTextChunk(model, tokens: tokens, batch: batch, singles: singles) + generated += length + } + + let keep = batchSize == 2 ? [1] : [2, 0] + let indices = MLXArray(keep.map { Int32($0) }) + for layer in batch { layer.filter(batchIndices: indices) } + singles = keep.map { singles[$0] } + let reorderedTokens = MLXArray( + singles.indices.flatMap { row in [Int32(41 + row), Int32(44 + row)] } + ).reshaped([singles.count, 2]) + try Self.expectTextChunk( + model, tokens: reorderedTokens, batch: batch, singles: singles) + + if singles.count > 1 { + for layer in batch { layer.filter(batchIndices: MLXArray([Int32(1)])) } + singles = [singles[1]] + } + let single = try #require(batch.first as? BatchKVCache) + guard case .scalar(let position) = single.ropeOffset else { + Issue.record("one remaining text row must keep the scalar rotary path") + return + } + #expect(position == singles[0][0].offset) + try Self.expectTextChunk( + model, tokens: MLXArray([Int32(51), 52])[.newAxis], batch: batch, + singles: singles) + } + } + /// The module tree of a model with KV sharing must not contain /// `k_proj` / `v_proj` / `k_norm` for the shared tail layers, while the /// non-shared head layers must still own them. @@ -90,22 +148,46 @@ struct Gemma4KVSharedLoadTests { return Int(key[range.upperBound...].prefix { $0.isNumber }) } + private static func expectTextChunk( + _ model: Gemma4TextLanguageModel, tokens: MLXArray, batch: [KVCache], + singles: [[KVCache]], sourceLocation: SourceLocation = #_sourceLocation + ) throws { + let output = model(tokens, cache: batch) + eval(output.logits) + eval(batch) + #expect(output.state == nil, sourceLocation: sourceLocation) + try #require( + output.logits.shape == [singles.count, tokens.dim(1), 64], + sourceLocation: sourceLocation) + for row in singles.indices { + let expected = model(tokens[row ..< row + 1], cache: singles[row]) + eval(expected.logits) + eval(singles[row]) + #expect( + maxAbsDifference(output.logits[row ..< row + 1], expected.logits) < 1e-3, + "row \(row) must retain its owner's rotary positions through the KV-shared tail", + sourceLocation: sourceLocation) + } + } + /// Tiny all-`full_attention` text config. `use_double_wide_mlp` is off so the /// dense and KV-sharing models differ *only* in the shared layers' K/V tensors, /// keeping every other weight shape-compatible across the two. - private static func textConfig(numKVSharedLayers: Int) -> Gemma4TextConfiguration { + static func textConfig( + numKVSharedLayers: Int, headDim: Int = 4, vocabularySize: Int = 12 + ) -> Gemma4TextConfiguration { let json = """ { "model_type": "gemma4_text", - "hidden_size": 8, + "hidden_size": \(headDim * 2), "num_hidden_layers": 4, - "intermediate_size": 16, + "intermediate_size": \(headDim * 4), "num_attention_heads": 2, "num_key_value_heads": 1, - "head_dim": 4, - "global_head_dim": 4, - "vocab_size": 12, - "vocab_size_per_layer_input": 12, + "head_dim": \(headDim), + "global_head_dim": \(headDim), + "vocab_size": \(vocabularySize), + "vocab_size_per_layer_input": \(vocabularySize), "num_kv_shared_layers": \(numKVSharedLayers), "hidden_size_per_layer_input": 0, "sliding_window": 8, @@ -127,3 +209,15 @@ struct Gemma4KVSharedLoadTests { Gemma4TextConfiguration.self, from: Data(json.utf8)) } } + +/// Text-only Gemma4 VLM backbone with 64-wide heads for float and packed-cache parity tests. +func tinyGemma4VLMTextForBatchPositions(numKVSharedLayers: Int) -> Gemma4TextLanguageModel { + withRandomState(MLXRandom.RandomState(seed: UInt64(923 + numKVSharedLayers))) { + let model = Gemma4TextLanguageModel( + Gemma4KVSharedLoadTests.textConfig( + numKVSharedLayers: numKVSharedLayers, headDim: 64, vocabularySize: 64)) + model.train(false) + eval(model) + return model + } +} diff --git a/Tests/MLXLMTests/KVCacheConfigurationTests.swift b/Tests/MLXLMTests/KVCacheConfigurationTests.swift index ff7bedc72d..54a41bd508 100644 --- a/Tests/MLXLMTests/KVCacheConfigurationTests.swift +++ b/Tests/MLXLMTests/KVCacheConfigurationTests.swift @@ -9,6 +9,18 @@ import Testing @Suite("KV-cache configuration") struct KVCacheConfigurationTests { + + @Test func modelCacheAdoptsSingleAndBatchedRowsAtOnePosition() { + Device.withDefaultDevice(.cpu) { + let single = KVCacheSimple() + let kv = makePositionKV(positions: 0 ..< 3, heads: 1, headDim: 4) + _ = single.update(keys: kv.0, values: kv.1) + let batch = KVCacheSimple.merge([single]) + let storage = KVCacheStorage([single, batch], plan: .disabled) + #expect(storage.processedTokenCount == 3) + #expect(storage.nativeAttentionOffsetsAreAligned) + } + } @Test func typedPresetsExposeStableAlgorithmIdentity() { let quality = KVCacheConfiguration( strategy: .turboQuant(.qualityFirst)) @@ -393,6 +405,18 @@ struct KVCacheConfigurationTests { #expect(storage.nativeAttentionOffsetsAreAligned) } + #if !DEBUG + @Test func modelCacheAdoptsMinimumOfDivergentAttentionOffsets() { + let ahead = KVCacheSimple() + ahead.offset = 8 + let behind = KVCacheSimple() + behind.offset = 6 + + #expect(KVCacheStorage([ahead, behind], plan: .disabled).processedTokenCount == 6) + #expect(KVCacheStorage([behind, ahead], plan: .disabled).processedTokenCount == 6) + } + #endif + @Test func modelCacheCopyAndTrimPreserveOneTimeline() throws { let attention = KVCacheSimple() _ = attention.update( diff --git a/Tests/MLXLMTests/RoPEApplicationTests.swift b/Tests/MLXLMTests/RoPEApplicationTests.swift index b4548b495b..f451fc82c7 100644 --- a/Tests/MLXLMTests/RoPEApplicationTests.swift +++ b/Tests/MLXLMTests/RoPEApplicationTests.swift @@ -1,6 +1,7 @@ import Foundation import MLX import MLXNN +import MLXVLM import Testing @testable import MLXLLM @@ -62,3 +63,511 @@ struct RoPEApplicationTests { } } } + +/// Rows at different positions, left-padded to one width, as a batched cache holds them. +private final class RowOffsetCache: KVCacheSimple, BatchPositionedKVCache { + private let leftPadding: [Int32] + + /// Joins prefilled single-sequence caches into one batch. + init(rows: [any KVCache]) { + let longest = rows.map(\.offset).max() ?? 0 + leftPadding = rows.map { Int32(longest - $0.offset) } + super.init() + var keys: [MLXArray] = [] + var values: [MLXArray] = [] + for row in rows { + let widths: [IntOrPair] = [0, 0, .init((longest - row.offset, 0)), 0] + keys.append(MLX.padded(row.state[0], widths: widths)) + values.append(MLX.padded(row.state[1], widths: widths)) + } + state = [concatenated(keys), concatenated(values)] + } + + var batchOffset: MLXArray { MLXArray(leftPadding.map { Int32(offset) - $0 }) } + + override var ropeOffset: RoPEOffset { .batch(batchOffset) } + + override func makeMask( + n: Int, windowSize: Int?, returnArray: Bool + ) -> MLXFast.ScaledDotProductAttentionMaskMode { + .array( + createCausalMask( + n: n, offset: offset, windowSize: windowSize, leftPadding: MLXArray(leftPadding))) + } +} + +/// An image row and a text row prefilled separately, then decoded as one batch, must each get +/// the logits they get on their own. +@Suite(.serialized) +struct VLMRowPositionTests { + + @Test("FastVLM positions each row of a batch at its own offset") + func fastVLM() throws { + try Device.withDefaultDevice(.cpu) { + let configuration = try JSONDecoder().decode( + FastVLMConfiguration.self, + from: Data( + """ + { + "model_type": "fastvlm", "hidden_size": 16, "num_hidden_layers": 1, + "intermediate_size": 32, "num_attention_heads": 2, "num_key_value_heads": 1, + "vocab_size": 16, "eos_token_id": 15, "mm_projector_type": "mlp2x_gelu", + "mm_hidden_size": 16, "tokenizer_model_max_length": 1024, + "tokenizer_padding_side": "right", + "vision_config": { + "cls_ratio": 1, "down_patch_size": 3, "down_stride": 2, + "downsamples": [false, false], "embed_dims": [16, 16], + "hidden_size": 16, "image_size": 128, "intermediate_size": 32, + "layers": [1, 1], "layer_scale_init_value": 0.00001, + "mlp_ratios": [2, 2], "num_classes": 16, "patch_size": 99, + "pos_embs_shapes": [null, null], "projection_dim": 16, + "repmixer_kernel_size": 3, "token_mixers": ["repmixer", "repmixer"] + } + } + """.utf8)) + let model = withRandomState(MLXRandom.RandomState(seed: 501)) { + let model = FastVLM(configuration) + eval(model) + return model + } + let inputs = [ + LMInput( + text: .init(tokens: MLXArray([1, -200, 2]).reshaped([1, 3])), + image: .init(pixels: MLXArray.ones([1, 3, 16, 16]), frames: [])), + LMInput(tokens: MLXArray([1, 2, 3]).reshaped([1, 3])), + ] + try expectRowsMatchSingles(model, inputs: inputs, positions: [18, 3]) + } + } + + @Test("Gemma 3 positions each row of a batch at its own offset") + func gemma3() throws { + try Device.withDefaultDevice(.cpu) { + let configuration = try JSONDecoder().decode( + Gemma3Configuration.self, + from: Data( + """ + { + "model_type": "gemma3", "mm_tokens_per_image": 4, + "text_config": { + "model_type": "gemma3_text", "hidden_size": 16, "num_hidden_layers": 6, + "intermediate_size": 32, "num_attention_heads": 2, "num_key_value_heads": 1, + "head_dim": 8, "query_pre_attn_scalar": 8, "sliding_window": 64 + }, + "vision_config": { + "model_type": "siglip_vision_model", "num_hidden_layers": 1, + "hidden_size": 16, "intermediate_size": 32, "num_attention_heads": 2, + "patch_size": 2, "image_size": 8 + } + } + """.utf8)) + let model = withRandomState(MLXRandom.RandomState(seed: 502)) { + let model = Gemma3(configuration) + eval(model) + return model + } + let inputs = [ + LMInput( + text: .init( + tokens: MLXArray([1, 262144, 262144, 262144, 262144, 2]) + .reshaped([1, 6])), + image: .init(pixels: MLXArray.ones([1, 3, 8, 8]), frames: [])), + LMInput(tokens: MLXArray([1, 2, 3]).reshaped([1, 3])), + ] + try expectRowsMatchSingles(model, inputs: inputs, positions: [6, 3]) + } + } + + @Test("Gemma 4 positions each row, also on its KV-shared layers") + func gemma4() throws { + try expectTextRows(seed: 503) { + Gemma4( + try JSONDecoder().decode( + Gemma4Configuration.self, + from: Data( + """ + { + "text_config": { + "hidden_size": 64, "num_hidden_layers": 4, "intermediate_size": 128, + "num_attention_heads": 2, "num_key_value_heads": 1, + "head_dim": 16, "global_head_dim": 32, + "vocab_size": 64, "vocab_size_per_layer_input": 64, + "num_kv_shared_layers": 2, "hidden_size_per_layer_input": 8, + "sliding_window": 64, "sliding_window_pattern": 2, + "max_position_embeddings": 512 + }, + "vision_config": { + "num_hidden_layers": 1, "hidden_size": 16, "intermediate_size": 32, + "num_attention_heads": 2, "head_dim": 8, "position_embedding_size": 64 + } + } + """.utf8))) + } + } + + @Test("Idefics3 positions each row of a batch at its own offset") + func idefics3() throws { + try expectTextRows(seed: 504) { + Idefics3( + try JSONDecoder().decode( + Idefics3Configuration.self, + from: Data( + """ + { + "model_type": "idefics3", "vocab_size": 64, "image_token_id": 63, + "scale_factor": 2, + "text_config": { + "model_type": "llama", "hidden_size": 32, "num_hidden_layers": 2, + "intermediate_size": 64, "num_attention_heads": 4, + "num_key_value_heads": 2, "rms_norm_eps": 1e-5, "vocab_size": 64, + "rope_theta": 10000.0 + }, + "vision_config": { + "model_type": "idefics3_vision", "hidden_size": 16, + "num_hidden_layers": 1, "intermediate_size": 32, + "num_attention_heads": 2, "patch_size": 4, "image_size": 16 + } + } + """.utf8))) + } + } + + @Test("LFM2-VL positions each row of a batch at its own offset") + func lfm2VL() throws { + try expectTextRows(seed: 505) { + LFM2VL( + try JSONDecoder().decode( + LFM2VLConfiguration.self, + from: Data( + """ + { + "model_type": "lfm2_vl", "image_token_id": 63, + "downsample_factor": 2, "projector_hidden_size": 16, + "projector_use_layernorm": false, + "text_config": { + "model_type": "lfm2", "vocab_size": 64, "hidden_size": 32, + "num_hidden_layers": 2, "num_attention_heads": 4, + "num_key_value_heads": 2, "intermediate_size": 64, "block_dim": 32, + "block_multiple_of": 8, "block_auto_adjust_ff_dim": false, + "layer_types": ["full_attention", "full_attention"] + }, + "vision_config": { + "model_type": "siglip2_vision_model", "hidden_size": 16, + "intermediate_size": 32, "num_hidden_layers": 1, + "num_attention_heads": 2, "num_channels": 3, + "num_patches": 16, "patch_size": 2, "layer_norm_eps": 1e-6 + } + } + """.utf8))) + } + } + + @Test("Mistral 3 positions and Llama 4-scales each row of a batch at its own offset") + func mistral3() throws { + try expectTextRows(seed: 506) { + Mistral3VLM( + try JSONDecoder().decode( + Mistral3VLMConfiguration.self, + from: Data( + """ + { + "model_type": "mistral3", "image_token_index": 63, + "spatial_merge_size": 1, "vision_feature_layer": -1, + "text_config": { + "model_type": "mistral", "hidden_size": 32, "num_hidden_layers": 2, + "intermediate_size": 64, "num_attention_heads": 2, + "num_key_value_heads": 1, "head_dim": 16, "rms_norm_eps": 1e-5, + "vocab_size": 64, "max_position_embeddings": 512, + "rope_parameters": { + "rope_theta": 10000.0, "llama_4_scaling_beta": 0.5, + "original_max_position_embeddings": 4 + } + }, + "vision_config": { + "model_type": "pixtral", "hidden_size": 32, "num_hidden_layers": 1, + "num_attention_heads": 2, "intermediate_size": 64, + "patch_size": 8, "image_size": 32 + } + } + """.utf8))) + } + } + + @Test("MuseGlimmer positions each row of a batch at its own offset") + func museGlimmer() throws { + // The tiny model's window is eight: these rows stay inside it while they decode. + try expectTextRows(seed: 507, prompts: [[1, 2], [1, 2, 3, 4, 5]]) { + try MuseGlimmerForwardTests.model() + } + } + + @Test("Pixtral positions each row of a batch at its own offset") + func pixtral() throws { + try expectTextRows(seed: 508) { + PixtralVLM( + try JSONDecoder().decode( + PixtralConfiguration.self, + from: Data( + """ + { + "model_type": "pixtral", "vocab_size": 64, "image_token_index": 63, + "text_config": { + "model_type": "mistral", "hidden_size": 32, "num_hidden_layers": 2, + "intermediate_size": 64, "num_attention_heads": 4, + "num_key_value_heads": 2, "head_dim": 8, "rms_norm_eps": 1e-5, + "vocab_size": 64, "rope_theta": 10000.0, "use_qk_norm": true + }, + "vision_config": { + "model_type": "pixtral", "hidden_size": 16, "num_hidden_layers": 1, + "num_attention_heads": 2, "intermediate_size": 32, + "patch_size": 4, "image_size": 8 + } + } + """.utf8))) + } + } + + @Test( + "Qwen 2 and 2.5 VL position each text row of a batch at its own offset", + arguments: QwenVLTextFamily.allCases) + func qwenVL(family: QwenVLTextFamily) throws { + try Device.withDefaultDevice(.cpu) { + try expectTextRowsMatchSingles(try tinyQwenVLText(family)) + } + } +} + +/// Text models whose Llama 4 query scaling follows each row's position. +@Suite(.serialized) +struct LLMRowPositionTests { + + /// Positions 3 and 9 fall in different Llama 4 scaling buckets of four positions. + private static let llama4Scaling = """ + "rope_parameters": { + "rope_theta": 10000.0, "llama_4_scaling_beta": 0.5, + "original_max_position_embeddings": 4 + } + """ + + @Test("Mistral 3 text Llama 4-scales each row of a batch at its own position") + func mistral3Text() throws { + try expectTextRows(seed: 509) { + Mistral3TextModel( + try JSONDecoder().decode( + Mistral3TextConfiguration.self, + from: Data( + """ + { + "model_type": "ministral3", "hidden_size": 16, "num_hidden_layers": 2, + "intermediate_size": 32, "num_attention_heads": 2, "rms_norm_eps": 1e-6, + "vocab_size": 32, "num_key_value_heads": 1, "head_dim": 8, + "tie_word_embeddings": true, + "layer_types": ["full_attention", "full_attention"], + \(Self.llama4Scaling) + } + """.utf8))) + } + } + + @Test("Nemotron Labs Diffusion Llama 4-scales each row of a batch at its own position") + func nemotronLabsDiffusion() throws { + try expectTextRows(seed: 510) { + NemotronLabsDiffusionModel( + try JSONDecoder().decode( + NemotronLabsDiffusionConfiguration.self, + from: Data( + """ + { + "hidden_size": 16, "num_hidden_layers": 2, "intermediate_size": 32, + "num_attention_heads": 2, "num_key_value_heads": 1, "head_dim": 8, + "rms_norm_eps": 1e-6, "vocab_size": 32, + \(Self.llama4Scaling) + } + """.utf8))) + } + } +} + +/// Builds a seeded tiny model on the CPU and checks its text rows decoded as one batch. +private func expectTextRows( + seed: UInt64, prompts: [[Int32]] = [[1, 2, 3], [1, 2, 3, 4, 5, 6, 7, 8, 9]], + _ makeModel: () throws -> any LanguageModel +) throws { + try Device.withDefaultDevice(.cpu) { + let model = try withRandomState(MLXRandom.RandomState(seed: seed)) { + let model = try makeModel() + eval(model) + return model + } + try expectTextRowsMatchSingles(model, prompts: prompts) + } +} + +enum QwenVLTextFamily: String, CaseIterable, Sendable { + case qwen2 = "qwen2_vl" + case qwen25 = "qwen2_5_vl" +} + +func tinyQwenVLText(_ family: QwenVLTextFamily) throws -> any LanguageModel { + var configuration: [String: Any] = [ + "model_type": family.rawValue, "hidden_size": 64, "num_hidden_layers": 2, + "intermediate_size": 128, "num_attention_heads": 4, "num_key_value_heads": 2, + "rms_norm_eps": 1e-6, "vocab_size": 64, "max_position_embeddings": 4096, + "rope_theta": 1000000.0, "rope_traditional": false, "tie_word_embeddings": false, + "image_token_id": 60, "video_token_id": 61, "vision_start_token_id": 62, + "vision_end_token_id": 63, "vision_token_id": 59, + "rope_scaling": ["type": "mrope", "mrope_section": [2, 3, 3]], + ] + if family == .qwen2 { + configuration["vision_config"] = [ + "depth": 1, "embed_dim": 32, "hidden_size": 64, "num_heads": 2, + "patch_size": 16, "mlp_ratio": 2.0, "spatial_patch_size": 16, + "spatial_merge_size": 2, "temporal_patch_size": 2, "in_channels": 3, + ] + } else { + configuration["sliding_window"] = 32768 + configuration["use_sliding_window"] = false + configuration["max_window_layers"] = 2 + configuration["vision_config"] = [ + "depth": 1, "hidden_size": 32, "intermediate_size": 64, "out_hidden_size": 64, + "num_heads": 2, "patch_size": 16, "spatial_patch_size": 16, + "spatial_merge_size": 2, "temporal_patch_size": 2, "window_size": 64, + "fullatt_block_indexes": [0], "tokens_per_second": 2, "in_chans": 3, + ] + } + let data = try JSONSerialization.data(withJSONObject: configuration) + let model: any LanguageModel + switch family { + case .qwen2: + let config = try JSONDecoder().decode(Qwen2VLConfiguration.self, from: data) + model = withRandomState(MLXRandom.RandomState(seed: 917)) { Qwen2VL(config) } + case .qwen25: + let config = try JSONDecoder().decode(Qwen25VLConfiguration.self, from: data) + model = withRandomState(MLXRandom.RandomState(seed: 918)) { Qwen25VL(config) } + } + model.train(false) + eval(model) + return model +} + +/// Prefills each input alone, joins the caches as one batch and decodes three tokens, +/// comparing every row's logits with the same sequence continued alone. +private func expectRowsMatchSingles( + _ model: any LanguageModel, inputs: [LMInput], positions: [Int] +) throws { + func prefill(_ input: LMInput) throws -> [any KVCache] { + let cache = try model.newCache(parameters: nil) + switch try model.prepare(input, cache: cache, state: nil, prefill: .init()) { + case .logits(let output): eval(output.logits) + case .tokens: Issue.record("The model must complete its own prefill") + } + eval(cache) + return cache + } + + try expectBatchDecodeMatchesSingles( + model, singles: try inputs.map(prefill), positions: positions) +} + +/// Prefills each prompt alone through the model's forward pass, then decodes the rows as one +/// batch as `expectRowsMatchSingles` does. +private func expectTextRowsMatchSingles( + _ model: any LanguageModel, + prompts: [[Int32]] = [[1, 2, 3], [1, 2, 3, 4, 5, 6, 7, 8, 9]] +) throws { + let singles = try prompts.map { prompt in + let cache = try model.newCache(parameters: nil) + eval(forward(model, MLXArray(prompt).reshaped([1, prompt.count]), cache: cache)) + eval(cache) + return cache + } + try expectBatchDecodeMatchesSingles(model, singles: singles, positions: prompts.map(\.count)) +} + +/// Joins prefilled single-row caches as one batch and decodes three tokens, comparing every +/// row's logits with the same sequence continued alone. +private func expectBatchDecodeMatchesSingles( + _ model: any LanguageModel, singles: [[any KVCache]], positions: [Int] +) throws { + #expect(singles.map { $0[0].offset } == positions) + let batch = singles[0].indices.map { layer in + RowOffsetCache(rows: singles.map { $0[layer] }) as KVCache + } + #expect((batch[0] as? RowOffsetCache)?.batchOffset.asArray(Int.self) == positions) + + for step in 0 ..< 3 { + let token = Int32(4 + step) + let output = forward(model, MLXArray([token, token]).reshaped([2, 1]), cache: batch) + for row in 0 ..< 2 { + let expected = forward(model, MLXArray([token]).reshaped([1, 1]), cache: singles[row]) + #expect( + maxAbsDifference(output[row ..< row + 1], expected) < 1e-4, + "row \(row), step \(step)") + } + } +} + +/// The logits of a stateless text step, through the entry point every model implements. +private func forward(_ model: any LanguageModel, _ tokens: MLXArray, cache: [any KVCache]) + -> MLXArray +{ + model.nextTokenLogits(.init(tokens: tokens), cache: cache, state: nil).logits +} + +func maxAbsDifference(_ lhs: MLXArray, _ rhs: MLXArray) -> Float { + abs(lhs.asType(.float32) - rhs.asType(.float32)).max().item(Float.self) +} + +@Suite(.serialized) +struct QwenVLBatchedPositionTests { + @Test( + "Stateless Qwen VL text rows use their own positions", arguments: QwenVLTextFamily.allCases) + func raggedTextLogits(family: QwenVLTextFamily) throws { + try Device.withDefaultDevice(.cpu) { + let model = try tinyQwenVLText(family) + let prompts = [[Int32(1), 2, 3], [4, 5, 6, 7, 8, 9, 10]] + var singles = try prompts.map { prompt in + let cache = try model.newCache(parameters: nil) + let output = model.nextTokenLogits( + .init(tokens: MLXArray(prompt)[.newAxis]), cache: cache, state: nil) + #expect(output.state?.isEmpty != false) + eval(output.logits, cache) + return cache + } + let batch = try singles[0].indices.map { layer in + try mergeCaches(singles.map { $0[layer].copy() }) + } + let first = try #require(batch.first as? BatchKVCache) + #expect(first.batchOffset.asArray(Int32.self) == [3, 7]) + + for length in [1, 2, 1] { + let tokens = MLXArray((0 ..< 2 * length).map { Int32(11 + $0) }) + .reshaped([2, length]) + let actual = model.nextTokenLogits(.init(tokens: tokens), cache: batch, state: nil) + #expect(actual.state?.isEmpty != false) + for row in singles.indices { + let expected = model.nextTokenLogits( + .init(tokens: tokens[row ..< row + 1]), cache: singles[row], state: nil) + #expect( + maxAbsDifference(actual.logits[row ..< row + 1], expected.logits) < 1e-4, + "\(family), row \(row), chunk length \(length)") + } + let expectedOffsets = singles.map { $0[0].offset } + #expect(first.batchOffset.asArray(Int.self) == expectedOffsets) + } + batch.forEach { $0.filter(batchIndices: batchRows(0)) } + singles = [singles[0]] + if case .scalar(let offset) = first.ropeOffset { + #expect(offset == singles[0][0].offset) + } else { + Issue.record("A remaining single row must use the scalar RoPE path") + } + let tokens = MLXArray([Int32(21), 22])[.newAxis] + let actual = model.nextTokenLogits(.init(tokens: tokens), cache: batch, state: nil) + let expected = model.nextTokenLogits( + .init(tokens: tokens), cache: singles[0], state: nil) + #expect(maxAbsDifference(actual.logits, expected.logits) < 1e-4) + } + } + +}