diff --git a/.github/workflows/swift.yml b/.github/workflows/swift.yml new file mode 100644 index 0000000000..7f70ddb35d --- /dev/null +++ b/.github/workflows/swift.yml @@ -0,0 +1,55 @@ +name: Swift Build (fork) + +# Fork-only CI: builds the package (and compiles the tests, without running them) +# on every pushed commit. +# +# This is intentionally a SEPARATE file from pull_request.yml (the workflow shared +# with upstream ml-explore) for two reasons: +# 1. Syncing from upstream never produces a merge conflict on this file. +# 2. The job is gated to this fork via `if: github.repository == ...`, mirroring +# how upstream's jobs are gated to ml-explore. If this file ever reaches the +# upstream repo, the job is simply skipped there -- it can never run or +# interfere upstream. + +on: + push: + +permissions: + contents: read + +# Cancel an in-progress build for a branch when a newer commit is pushed to it, +# so rapid pushes don't pile up (macOS runner minutes are billed at 10x). +concurrency: + group: swift-build-${{ github.ref }} + cancel-in-progress: true + +jobs: + build: + # Fork-only. Never runs on upstream ml-explore (kept inert if it lands there). + if: github.repository == 'PicoMLX/mlx-swift-lm' + # macOS 15 (Sequoia) hosted runner: provides Xcode + the Metal toolchain + # needed to produce the Metal library that `swift build` alone cannot. Unlike + # the macos-14 image (which tops out at Xcode 15.4 / Swift 5.10), it can run + # Xcode 16.3+ for the Swift 6.1 toolchain that Package.swift requires. + runs-on: macos-15 + steps: + - uses: actions/checkout@v6 + with: + submodules: recursive + + # Package.swift declares swift-tools-version 6.1, so select the newest + # stable Xcode on the image (Swift 6.1+). Without this, package resolution + # fails: "using Swift tools version 6.1.0 but the installed version is 5.10.0". + - name: Select latest stable Xcode + uses: maxim-lobanov/setup-xcode@v1 + with: + xcode-version: latest-stable + + - name: Versions + run: | + xcodebuild -version + swift --version + + - name: Build for testing (Xcode, macOS) + run: | + xcodebuild build-for-testing -scheme mlx-swift-lm-Package -destination 'platform=macOS' diff --git a/.gitignore b/.gitignore index 4b8e5d1956..9a80c38667 100644 --- a/.gitignore +++ b/.gitignore @@ -102,3 +102,6 @@ pyproject.toml uv.lock main.py +# Claude Code agent worktrees (transient, isolated working copies) +.claude/worktrees/ + diff --git a/Libraries/MLXLMCommon/Batching/BatchKVCache.swift b/Libraries/MLXLMCommon/Batching/BatchKVCache.swift new file mode 100644 index 0000000000..81aed9933a --- /dev/null +++ b/Libraries/MLXLMCommon/Batching/BatchKVCache.swift @@ -0,0 +1,589 @@ +// Copyright © 2024 Apple Inc. + +import Foundation +import MLX +import MLXNN + +// MARK: - BatchKVCache + +/// Batch-aware KV cache with left-padding strategy for continuous batching. +/// +/// Ported from Python mlx-lm's `BatchKVCache`. The cache expects inputs to be +/// left-padded so that variable-length sequences align on the right. +/// +/// For example, prompts `[1, 3, 5]`, `[7]`, and `[2, 6, 8, 9]` are padded: +/// ``` +/// [0, 1, 3, 5] +/// [0, 0, 0, 7] +/// [2, 6, 8, 9] +/// ``` +/// With `leftPadding = [1, 3, 0]`. +public class BatchKVCache: BaseKVCache, BatchPositionedKVCache, BatchedCache { + + /// Per-sequence left-padding amounts as an MLXArray of shape `[B]`. + public internal(set) var leftPadding: MLXArray + + /// Per-sequence offset as an MLXArray of shape `[B]`. + /// Starts negative (equal to `-leftPadding`) and advances with each update. + public internal(set) var batchOffsets: MLXArray + + /// Internal buffer index tracking how far into the keys/values buffer we've written. + internal var _idx: Int = 0 + + /// Keys buffer: `[B, H, S_buf, D_k]` + internal var keys: MLXArray? + + /// Values buffer: `[B, H, S_buf, D_v]` + internal var values: MLXArray? + + /// Step size for buffer allocation (grow in chunks of this size). + public var step: Int = 256 + + /// The scalar offset (not meaningful for batch caches, returns `_idx`). + public override var offset: Int { + get { _idx } + set { _idx = newValue } + } + + /// Initialize a BatchKVCache with the given left-padding per sequence. + /// + /// - Parameter leftPadding: Array of integers specifying the left-padding for each sequence. + public init(leftPadding: [Int]) { + self.leftPadding = MLXArray(leftPadding.map { Int32($0) }) + self.batchOffsets = MLXArray(leftPadding.map { -Int32($0) }) + super.init() + } + + /// Internal initializer for creating empty batch caches with pre-built MLXArrays. + internal init(leftPaddingArray: MLXArray, batchOffsetsArray: MLXArray) { + self.leftPadding = leftPaddingArray + self.batchOffsets = batchOffsetsArray + super.init() + } + + // MARK: - KVCache Protocol + + public override func innerState() -> [MLXArray] { + [self.keys, self.values].compactMap { $0 } + } + + /// Update the cache with new keys and values. + /// + /// Keys/values have shape `[B, H, S, D]` where `S` is the number of new tokens. + /// The cache buffer grows in steps of `step` size. + public override func update(keys: MLXArray, values: MLXArray) -> (MLXArray, MLXArray) { + let prev = _idx + + let reset: Bool + if let currentKeys = self.keys, (prev + keys.dim(2)) <= currentKeys.dim(2) { + reset = false + } else { + reset = true + } + + if reset { + let B = keys.dim(0) + let kvHeads = keys.dim(1) + let kHeadDim = keys.dim(3) + let vHeadDim = values.dim(3) + + let nSteps = (step + keys.dim(2) - 1) / step + let kShape = [B, kvHeads, nSteps * step, kHeadDim] + let vShape = [B, kvHeads, nSteps * step, vHeadDim] + let newK = MLXArray.zeros(kShape, dtype: keys.dtype) + let newV = MLXArray.zeros(vShape, dtype: values.dtype) + + if var currentKeys = self.keys, var currentValues = self.values { + if prev % step != 0 { + currentKeys = currentKeys[.ellipsis, .. Int { + let trimmed = min(_idx, n) + _idx -= trimmed + batchOffsets = batchOffsets - Int32(trimmed) + return trimmed + } + + /// The batch size (number of sequences). + public var batchSize: Int { + leftPadding.dim(0) + } + + /// Whether the cache is empty (no keys/values stored). + public var isEmpty: Bool { + keys == nil + } + + // MARK: - BatchPositionedKVCache Conformance + + /// Per-sequence position offsets as an MLXArray of shape `[B]`. + /// + /// This is an alias for `batchOffsets`, providing the per-sequence position + /// offsets needed for batch-aware RoPE application via `applyRotaryPosition()`. + public var batchOffset: MLXArray { + batchOffsets + } + + /// Override `BaseKVCache`'s scalar `ropeOffset` so per-row offsets are used + /// even when this cache flows through attention layers typed as `KVCache`. + public override var ropeOffset: RoPEOffset { .batch(batchOffset + 0) } + + // MARK: - Batch Operations + + /// In-place filter to keep only the sequences at the given batch indices. + /// + /// After filtering, the minimum left-padding is subtracted from all sequences + /// and the buffer is trimmed accordingly (shift left to reduce padding). + /// + /// - Parameter batchIndices: Array of batch indices to keep. + public func filter(batchIndices: [Int]) { + // Handle empty filter -> produce valid empty state + guard !batchIndices.isEmpty else { + keys = nil + values = nil + leftPadding = MLXArray([Int32]()) + batchOffsets = MLXArray([Int32]()) + _idx = 0 + // Clear pending right-padding so a later finalize() can't roll/subtract + // with stale per-row metadata against the now-empty batch. + _rightPadding = nil + return + } + + let indices = MLXArray(batchIndices.map { Int32($0) }) + + // Filter along batch dimension (dim 0) + keys = keys?[indices] + values = values?[indices] + batchOffsets = batchOffsets[indices] + leftPadding = leftPadding[indices] + // Transient right-padding metadata (set by prepareBatched, consumed by + // finalize) is per-row too: filter it with the same indices so a cancel + // between prepare and finalize doesn't leave finalize rolling/subtracting + // against the pre-filter batch shape. + _rightPadding = _rightPadding?[indices] + + // Shift left to reduce padding. Only meaningful once a KV buffer exists: + // for a fresh/cancelled-before-prefill cache the tensor slices are no-ops, + // but decrementing `_idx` would drive it negative and leave `batchOffsets` + // inconsistent with the adjusted padding, corrupting the `prev` range used + // by the next prefill. Skip the shift entirely while `keys == nil`. + // + // Also require `_idx >= minLeftPad`: during chunked prefill the KV buffer + // can exist before the write pointer has advanced past the padding. Shifting + // then would drive `_idx` negative and slice past the written region (keeping + // uninitialized data), so skip until enough tokens have been written. + let minLeftPad = leftPadding.min().item(Int32.self) + if minLeftPad > 0, keys != nil, _idx >= Int(minLeftPad) { + let padInt = Int(minLeftPad) + keys = keys?[.ellipsis, padInt..., 0...] + values = values?[.ellipsis, padInt..., 0...] + _idx -= padInt + leftPadding = leftPadding - minLeftPad + } + } + + /// In-place extend this cache with another BatchKVCache. + /// + /// The caches are right-justified: the shorter cache gets additional left-padding + /// to align with the longer one along the sequence dimension. + /// + /// - Parameter other: The other BatchKVCache to merge into this one. + /// + /// Admission contract: the engine prefills every admitted sub-batch before + /// extending the active batch, so a non-empty `other` always arrives with a + /// populated KV buffer. This precondition makes that contract explicit and + /// closes the "append empty admitted rows" hole: an `other` that carries row + /// metadata (`batchSize > 0`) but no prefilled keys is rejected here instead + /// of silently dropping those rows from the enlarged batch. + public func extend(other: BatchKVCache) { + precondition( + other.keys != nil || other.batchSize == 0, + "BatchKVCache.extend requires a non-empty `other` to be prefilled " + + "(keys != nil) before extending; the engine prefills each " + + "admitted sub-batch before calling extend." + ) + guard let selfKeys = self.keys, let otherKeys = other.keys else { + if self.keys == nil && other.keys == nil { + // Both empty: concatenate row metadata so admitted rows survive + // until their first prefill instead of being dropped. + self.leftPadding = concatenated([self.leftPadding, other.leftPadding], axis: 0) + self.batchOffsets = concatenated([self.batchOffsets, other.batchOffsets], axis: 0) + } else if other.keys != nil { + // self empty, other populated: adopt other's state. + self.keys = other.keys + self.values = other.values + self.batchOffsets = other.batchOffsets + self.leftPadding = other.leftPadding + self._idx = other._idx + } + return + } + + let maxIdx = max(self._idx, other._idx) + let maxSize = max(selfKeys.dim(2), otherKeys.dim(2)) + + // Inner function to pad a cache's keys/values for right-justification. + func pad( + _ cache: BatchKVCache + ) -> (MLXArray, MLXArray, MLXArray, MLXArray) { + let left = maxIdx - cache._idx + var right = maxSize - cache.keys!.dim(2) - left + + var k = cache.keys! + var v = cache.values! + + if right < 0 { + k = k[.ellipsis, ..<(k.dim(2) + right), 0...] + v = v[.ellipsis, ..<(v.dim(2) + right), 0...] + right = 0 + } + + if left != 0 || right != 0 { + let padWidths: [IntOrPair] = [0, 0, .init((left, right)), 0] + k = MLX.padded(k, widths: padWidths) + v = MLX.padded(v, widths: padWidths) + } + + let adjustedLeftPadding = cache.leftPadding + Int32(left) + + return (k, v, cache.batchOffsets, adjustedLeftPadding) + } + + let (selfK, selfV, selfOff, selfLP) = pad(self) + let (otherK, otherV, otherOff, otherLP) = pad(other) + + self.keys = concatenated([selfK, otherK], axis: 0) + self.values = concatenated([selfV, otherV], axis: 0) + self.batchOffsets = concatenated([selfOff, otherOff], axis: 0) + self.leftPadding = concatenated([selfLP, otherLP], axis: 0) + self._idx = maxIdx + } + + /// Extract a single sequence from the batch as a `KVCacheSimple`. + /// + /// The returned cache has the left-padding stripped and contains only the + /// valid (non-padded) key/value data. + /// + /// - Parameter idx: The batch index of the sequence to extract. + /// - Returns: A `KVCacheSimple` with the extracted sequence data. + public func extract(idx: Int) -> KVCacheSimple { + let cache = KVCacheSimple() + let padding = Int(leftPadding[idx].item(Int32.self)) + + if let k = keys, let v = values { + cache.keys = MLX.contiguous(k[idx ..< (idx + 1), 0..., padding ..< _idx, 0...]) + cache.values = MLX.contiguous(v[idx ..< (idx + 1), 0..., padding ..< _idx, 0...]) + cache.offset = cache.keys!.dim(2) + } + + return cache + } + + /// Create a BatchKVCache by merging multiple individual KVCache instances. + /// + /// Each cache is right-justified in the batch: shorter caches receive left-padding + /// to match the longest sequence. + /// + /// - Parameter caches: An array of `KVCacheSimple` instances. + /// - Returns: A new `BatchKVCache` containing all sequences. + public class func merge(_ caches: [KVCache]) -> BatchKVCache { + // The copy loop below reads data only from `KVCacheSimple` instances; a + // non-simple cache would silently contribute an all-zero row that the + // mask still exposes. Fail loudly instead. + precondition( + caches.allSatisfy { $0 is KVCacheSimple }, + "BatchKVCache.merge requires KVCacheSimple instances" + ) + let lengths = caches.map { $0.offset } + let maxLength = lengths.max() ?? 0 + let padding = lengths.map { maxLength - $0 } + let B = caches.count + + // Find dimensions from first non-empty cache + var H = 0 + var Dk = 0 + var Dv = 0 + var dt: DType = .float16 + + for c in caches { + if let simple = c as? KVCacheSimple, let k = simple.keys { + H = k.dim(1) + Dk = k.dim(3) + Dv = simple.values!.dim(3) + dt = k.dtype + break + } + } + + guard H > 0 else { + // All caches are empty + return BatchKVCache(leftPadding: padding) + } + + let keysArr = MLXArray.zeros([B, H, maxLength, Dk], dtype: dt) + let valuesArr = MLXArray.zeros([B, H, maxLength, Dv], dtype: dt) + + for (i, (p, c)) in zip(padding, caches).enumerated() { + if let simple = c as? KVCacheSimple, let k = simple.keys, let v = simple.values { + let seqLen = c.offset + keysArr[i ..< (i + 1), 0..., p ..< (p + seqLen), 0...] = + k[.ellipsis, .. BatchKVCache { + let batchCache = BatchKVCache(leftPadding: [0]) + + if let k = cache.keys, let v = cache.values { + batchCache.keys = k + batchCache.values = v + batchCache._idx = cache.offset + batchCache.batchOffsets = MLXArray([Int32(cache.offset)]) + } + + return batchCache + } + + /// Convert a batch-1 BatchKVCache back to a KVCacheSimple. + /// + /// - Returns: A `KVCacheSimple` with the single sequence data. + public func toSingle() -> KVCacheSimple { + precondition(batchSize == 1, "toSingle() requires batch size of 1") + return extract(idx: 0) + } + + // MARK: - Mask Creation + + /// Create an attention mask for this batch cache. + /// + /// Unlike non-batch caches which return `.none` for `n=1`, batch caches + /// MUST always produce a mask that excludes left-padded positions. This + /// ensures that during single-token decode steps, padded positions are + /// still correctly masked out. + /// + /// - Parameters: + /// - n: The sequence length for the new tokens + /// - windowSize: Optional sliding window size + /// - returnArray: Force return of array mask instead of symbolic + /// - Returns: Attention mask mode for scaled dot product attention + public override func makeMask( + n: Int, windowSize: Int?, returnArray: Bool + ) -> MLXFast.ScaledDotProductAttentionMaskMode { + // Batch caches always need an explicit mask to handle left-padding, + // even for n=1 decode steps. + // + // makeMask() runs before attentionWithCacheUpdate(), but that helper + // appends the current step's keys/values before launching attention. + // The attention kernel therefore sees the post-update cache width, so + // the mask must span the existing cache plus the n incoming tokens. + return .array( + createCausalMask( + n: n, offset: _idx, windowSize: windowSize, leftPadding: leftPadding + ) + ) + } + + // MARK: - Prepare / Finalize (Cached-Prompt Prefill) + + /// Stored right-padding for the current prefill cycle. + /// Set by `prepare(rightPadding:)` and consumed by `finalize()`. + internal var _rightPadding: MLXArray? + + /// Prepare the cache for a cached-prompt batch prefill with right-padding. + /// + /// During mixed-depth cached-prompt prefill, suffix tokens are + /// RIGHT-padded (shorter suffixes padded on the right to match the + /// longest suffix). After prefill, the right-padding zeros sit at + /// positions that `createCausalMask` does NOT mask out, corrupting + /// attention. `finalize()` fixes this by rolling the right-padding + /// zeros to the LEFT side of the buffer. + /// + /// Matches Python mlx-lm's `BatchKVCache.prepare()`. + /// + /// - Parameter rightPadding: Per-sequence right-padding amounts as + /// an MLXArray of shape `[B]`. + public func prepare(rightPadding: MLXArray) { + // Only store if there's any non-zero padding + if rightPadding.max().item(Int32.self) > 0 { + _rightPadding = rightPadding + } + } + + /// Finalize the cache after a cached-prompt batch prefill. + /// + /// If `prepare(rightPadding:)` was called, this method uses + /// `dynamicRoll` to shift each sequence's KV data so that + /// right-padding zeros move to the LEFT side of the buffer, + /// then adjusts `leftPadding += rightPadding` and + /// `batchOffsets -= rightPadding`. + /// + /// After finalize, all padding is contiguous on the left and + /// the causal mask correctly excludes it. + /// + /// Matches Python mlx-lm's `BatchKVCache.finalize()`. + public override func finalize() { + guard let padding = _rightPadding else { return } + + if let k = keys, let v = values { + self.keys = dynamicRoll(k, shifts: padding[0..., .newAxis], axis: 2) + self.values = dynamicRoll(v, shifts: padding[0..., .newAxis], axis: 2) + } + batchOffsets = batchOffsets - padding + leftPadding = leftPadding + padding + _rightPadding = nil + } + + // MARK: - BatchedCache Conformance + + /// Bridges the `BatchedCache` protocol (MLXArray-indexed, used by the engine) + /// onto this cache's concrete operations. `batchIndices` is small (`[B]`), so + /// the host round-trip is negligible next to the per-token decode work. + public func filterBatched(batchIndices: MLXArray) { + filter(batchIndices: batchIndices.asArray(Int32.self).map(Int.init)) + } + + public func extendBatched(_ other: any BatchedCache) { + guard let other = other as? BatchKVCache else { + preconditionFailure("BatchKVCache.extendBatched requires another BatchKVCache") + } + extend(other: other) + } + + public func prepareBatched(leftPadding: [Int]?, lengths _: [Int]?, rightPadding: [Int]?) { + if let leftPadding { + precondition( + keys == nil, + "prepareBatched(leftPadding:) requires an empty BatchKVCache" + ) + let additional = MLXArray(leftPadding.map { Int32($0) }) + self.leftPadding = self.leftPadding + additional + self.batchOffsets = self.batchOffsets - additional + } + if let rightPadding, rightPadding.contains(where: { $0 > 0 }) { + prepare(rightPadding: MLXArray(rightPadding.map { Int32($0) })) + } + } + + public func finalizeBatched() { + finalize() + } + + public func extractBatched(_ idx: Int) -> any KVCache { + extract(idx: idx) + } + + /// Full-attention caches have no chunk-local prefill metadata to advance. + public func advanceBatched(_: Int) {} + + public override func copy() -> any KVCache { + let c = BatchKVCache( + leftPaddingArray: leftPadding[0...], batchOffsetsArray: batchOffsets[0...]) + c.keys = keys.map { $0[.ellipsis] } + c.values = values.map { $0[.ellipsis] } + c._idx = _idx + c.step = step + c._rightPadding = _rightPadding.map { $0[0...] } + return c + } + + public var debugDescription: String { + "BatchKVCache batchSize: \(batchSize), _idx: \(_idx), keys: \(keys?.shape.description ?? "-"), values: \(values?.shape.description ?? "-")" + } +} diff --git a/Libraries/MLXLMCommon/Batching/BatchRotatingKVCache.swift b/Libraries/MLXLMCommon/Batching/BatchRotatingKVCache.swift new file mode 100644 index 0000000000..02c02f660e --- /dev/null +++ b/Libraries/MLXLMCommon/Batching/BatchRotatingKVCache.swift @@ -0,0 +1,1018 @@ +// Copyright © 2024 Apple Inc. + +import Foundation +import MLX +import MLXNN + +// MARK: - Dynamic Roll Helper + +/// Per-element roll along a specified axis. +/// +/// Ported from Python mlx-lm's `dynamic_roll`. Each element along the batch +/// dimension is rolled by its own shift amount. +/// +/// - Parameters: +/// - x: The input array. +/// - shifts: Per-batch shift amounts. Shape must broadcast with `x` along axes +/// other than `axis`. +/// - axis: The axis along which to roll. +/// - Returns: The rolled array. +internal func dynamicRoll(_ x: MLXArray, shifts: MLXArray, axis: Int) -> MLXArray { + let n = x.dim(axis) + + // Build index shape for broadcasting. + let ndim = x.ndim + let positiveAxis = axis >= 0 ? axis : ndim + axis + + // arange indices along the roll axis + let indices = MLXArray(Int32(0) ..< Int32(n)) + + // Reshape indices so they broadcast: [1, ..., 1, n, 1, ..., 1] + var idxShape = [Int](repeating: 1, count: ndim) + idxShape[positiveAxis] = n + let reshapedIndices = indices.reshaped(idxShape) + + // Reshape shifts to broadcast: add trailing dims after the axis + // shifts shape: e.g. [B, 1] → needs to become [B, 1, 1, ..., 1] + var shiftShape = [Int](repeating: 1, count: ndim) + for d in 0 ..< shifts.ndim { + if d < ndim { + shiftShape[d] = shifts.dim(d) + } + } + let reshapedShifts = shifts.reshaped(shiftShape) + + // Compute rolled indices: (indices - shifts) mod n + // Use ((x % n) + n) % n to ensure non-negative result (Python-style modulo) + // ((x % n) + n) % n keeps the result non-negative (Python-style modulo). + // Using `%` avoids any overload ambiguity with Foundation/Darwin `remainder`. + let nArr = MLXArray(Int32(n)) + let idx = ((reshapedIndices - reshapedShifts) % nArr + nArr) % nArr + + return takeAlong(x, idx.asType(.int32), axis: positiveAxis) +} + +// MARK: - RotatingKVCache Internal Extension + +extension RotatingKVCache { + /// Returns temporally ordered keys/values suitable for merging into a batch cache. + /// + /// When the rotating cache has wrapped around (offset >= maxSize), the internal + /// buffer may not be in temporal order. This method returns the state in correct + /// temporal order, which is needed for `BatchRotatingKVCache.merge()`. + /// + /// The returned arrays have shape `[1, H, seqLen, D]` where `seqLen = min(offset, maxSize)`. + internal var temporalState: [MLXArray] { + // The `state` getter on RotatingKVCache already handles slicing: + // - When offset < keys.dim(2): returns keys[..= keys.dim(2): returns full buffer (may be rotated) + // + // For a rotated buffer, we need to reconstruct temporal order. + // We read metaState to get the idx and reconstruct. + let meta = self.metaState + guard meta.count >= 5, + let keep = Int(meta[0]), + let ms = Int(meta[1]), + let off = Int(meta[3]), + let ix = Int(meta[4]) + else { + return self.state + } + + let rawState = self.state + guard rawState.count == 2 else { return rawState } + + let k = rawState[0] + let v = rawState[1] + + // No rotation needed if offset < maxSize (buffer hasn't wrapped) + if off < ms { + return [k, v] + } + + // Buffer is full and may be rotated. Reconstruct temporal order. + // The idx tells us where the next write would go, so data before idx + // is newer and data from idx onwards is older. + if ix == k.dim(2) { + // No rotation happened or idx is at the end + return [k, v] + } else if ix < off { + // Rotated: [keep tokens][newer tokens from idx..][older tokens keep.. Warning: `keep > 0` is only sound while every row has zero left padding. +/// > At the rotation wrap, padded rows roll their pads to the END of the buffer +/// > to protect the keep prefix, but the prefix-only `leftPadding` mask cannot +/// > express trailing garbage, so those slots would be attended until +/// > overwritten. `makeBatchedCacheFactories` therefore rejects keep-prefix +/// > topologies; direct construction with `keep > 0` is for equal-length +/// > batches only. +public class BatchRotatingKVCache: BaseKVCache, BatchPositionedKVCache, BatchedCache { + + /// Per-sequence left-padding amounts as an MLXArray of shape `[B]`. + public internal(set) var leftPadding: MLXArray + + /// Per-sequence offset as an MLXArray of shape `[B]`. + /// Starts negative (equal to `-leftPadding`) and advances with each update. + public internal(set) var batchOffsets: MLXArray + + /// Internal buffer index tracking how far into the keys/values buffer we've written. + internal var _idx: Int = 0 + + /// Scalar offset tracking total tokens written (similar to RotatingKVCache._offset in Python). + internal var _scalarOffset: Int = 0 + + /// Whether the cache buffer has wrapped around (rotation has occurred). + internal var rotated: Bool = false + + /// Keys buffer: `[B, H, S_buf, D_k]` + internal var keys: MLXArray? + + /// Values buffer: `[B, H, S_buf, D_v]` + internal var values: MLXArray? + + /// Maximum cache size (sliding window size). + private var maxCacheSize: Int + + /// Number of tokens to always keep at the start of the cache during rotation. + /// Mirrors `RotatingKVCache.keep`. + public internal(set) var keep: Int = 0 + + /// Stored lengths for right-padded inputs during cached-prompt prefill. + /// Set by `prepare(rightPadding:lengths:)` and consumed by `finalize()`. + internal var _lengths: MLXArray? + + /// Step size for buffer allocation. + public var step: Int = 256 + + /// The maximum size of this cache (sliding window size). + public override var maxSize: Int? { maxCacheSize } + + /// The logical cache length, capped at `maxCacheSize`. + /// + /// `_idx` is the circular write pointer (reset to `keep` on wrap), so it is + /// not a valid position to expose to generic callers: after the first + /// rotation it jumps backward. Paths that derive masks from `cache.offset` + /// rather than `makeMask` — e.g. the array-based `createAttentionMask(h:cache:)` + /// used by `Gemma2ModelInner` during multi-token cached prefill — would then + /// build masks with too small an offset. Report the monotonic logical length + /// (`_scalarOffset`) capped at the window, mirroring how single-stream + /// `RotatingKVCache.offset` reports a monotonic position rather than the ring + /// index. The setter drives `_scalarOffset` for symmetry. + public override var offset: Int { + get { min(_scalarOffset, maxCacheSize) } + set { _scalarOffset = newValue } + } + + /// Initialize a BatchRotatingKVCache with a maximum size and left-padding per sequence. + /// + /// - Parameters: + /// - maxSize: The maximum cache size (sliding window size). + /// - leftPadding: Array of integers specifying the left-padding for each sequence. + /// - keep: Number of tokens to always keep at the start during rotation (default 0). + public init(maxSize: Int, leftPadding: [Int], keep: Int = 0) { + self.maxCacheSize = maxSize + self.keep = keep + self.leftPadding = MLXArray(leftPadding.map { Int32($0) }) + self.batchOffsets = MLXArray(leftPadding.map { -Int32($0) }) + super.init() + } + + /// Internal initializer with pre-built MLXArrays. + internal init( + maxSize: Int, keep: Int = 0, leftPaddingArray: MLXArray, batchOffsetsArray: MLXArray + ) { + self.maxCacheSize = maxSize + self.keep = keep + self.leftPadding = leftPaddingArray + self.batchOffsets = batchOffsetsArray + super.init() + } + + // MARK: - KVCache Protocol + + public override func innerState() -> [MLXArray] { + [self.keys, self.values].compactMap { $0 } + } + + // MARK: - Update + + /// Update the cache with new keys and values. + /// + /// Dispatches to the concat path for multi-token updates (prefill) or + /// the in-place rotation path for single-token updates (decode). + public override func update(keys: MLXArray, values: MLXArray) -> (MLXArray, MLXArray) { + if keys.dim(2) == 1 { + return updateInPlace(keys: keys, values: values) + } else { + return updateConcat(keys: keys, values: values) + } + } + + /// Multi-token concat path for prefill. + /// + /// Puts keys/values into temporal order, trims to maintain the sliding window, + /// and concatenates new data. + private func updateConcat(keys: MLXArray, values: MLXArray) -> (MLXArray, MLXArray) { + if self.keys == nil { + self.keys = keys + self.values = values + } else { + // Put keys/values in temporal order + temporalOrder() + + // Slice off unused end + if self.keys!.dim(2) > _idx { + self.keys = self.keys![.ellipsis, ..<_idx, 0...] + self.values = self.values![.ellipsis, ..<_idx, 0...] + } + + // Roll right sequences that are padded to make sure that we don't + // trim valid cache entries (cached-prompt prefill support) + if let lengths = _lengths { + let roll = MLX.maximum(MLXArray(Int32(0)), batchOffsets - lengths) + self.keys = dynamicRoll(self.keys!, shifts: roll[0..., .newAxis], axis: 2) + self.values = dynamicRoll(self.values!, shifts: roll[0..., .newAxis], axis: 2) + leftPadding = leftPadding + roll + batchOffsets = batchOffsets - roll + } + + // The largest size is maxCacheSize + S - 1 to ensure + // every token gets at least maxCacheSize context + let trimSize = _idx - maxCacheSize + 1 + if trimSize > 0 { + leftPadding = leftPadding - Int32(trimSize) + self.keys = trim(trimSize: trimSize, self.keys!, append: keys) + self.values = trim(trimSize: trimSize, self.values!, append: values) + } else { + self.keys = concatenated([self.keys!, keys], axis: 2) + self.values = concatenated([self.values!, values], axis: 2) + } + } + + batchOffsets = batchOffsets + Int32(keys.dim(2)) + _scalarOffset += keys.dim(2) + _idx = self.keys!.dim(2) + + return (self.keys!, self.values!) + } + + /// Single-token in-place rotation path for decode. + private func updateInPlace(keys: MLXArray, values: MLXArray) -> (MLXArray, MLXArray) { + precondition( + _lengths == nil, + "finalize() should be called before decoding with BatchRotatingKVCache" + ) + + let B = keys.dim(0) + let nKVHeads = keys.dim(1) + let S = keys.dim(2) + let kHeadDim = keys.dim(3) + let vHeadDim = values.dim(3) + let prev = _scalarOffset + + // May not have hit the max size yet, so potentially keep growing + if self.keys == nil + || (prev >= self.keys!.dim(2) && self.keys!.dim(2) < maxCacheSize) + { + let newSize = min(step, maxCacheSize - prev) + let kShape = [B, nKVHeads, newSize, kHeadDim] + let vShape = [B, nKVHeads, newSize, vHeadDim] + let newK = MLXArray.zeros(kShape, dtype: keys.dtype) + let newV = MLXArray.zeros(vShape, dtype: values.dtype) + + if let currentKeys = self.keys, let currentValues = self.values { + self.keys = concatenated([currentKeys, newK], axis: 2) + self.values = concatenated([currentValues, newV], axis: 2) + } else { + self.keys = newK + self.values = newV + } + _idx = prev + } + + // Trim if needed + let trimSize = self.keys!.dim(2) - maxCacheSize + if trimSize > 0 { + self.keys = trim(trimSize: trimSize, self.keys!) + self.values = trim(trimSize: trimSize, self.values!) + _idx = maxCacheSize + leftPadding = leftPadding - Int32(trimSize) + } + + // Rotate — wrap to keep (not 0) so the first `keep` positions are never overwritten + if _idx == maxCacheSize { + // When keep > 0 and some sequences have left-padding, the keep zone + // (positions 0.. 0 { + let effectivePadding = MLX.maximum(MLXArray(Int32(0)), leftPadding) + if effectivePadding.max().item(Int32.self) > 0 { + self.keys = dynamicRoll( + self.keys!, shifts: -effectivePadding[0..., .newAxis], axis: 2) + self.values = dynamicRoll( + self.values!, shifts: -effectivePadding[0..., .newAxis], axis: 2) + leftPadding = leftPadding - effectivePadding + } + } + rotated = true + _idx = keep + } + if rotated { + leftPadding = leftPadding - Int32(S) + } + + // Assign + self.keys![.ellipsis, _idx ..< (_idx + S), 0...] = keys + self.values![.ellipsis, _idx ..< (_idx + S), 0...] = values + _scalarOffset += S + batchOffsets = batchOffsets + Int32(S) + _idx += S + + // If the buffer is not full, slice off the end + if _scalarOffset < maxCacheSize { + return ( + self.keys![.ellipsis, ..<_scalarOffset, 0...], + self.values![.ellipsis, ..<_scalarOffset, 0...] + ) + } + return (self.keys!, self.values!) + } + + // MARK: - Temporal Order + + /// Rearrange the cache into temporal order by unrolling rotation. + /// + /// When `keep > 0`, the first `keep` positions are fixed and the circular + /// buffer operates on positions `keep.. 0 { + // Rotated with keep prefix: [keep tokens][newer(keep..<_idx)][older(_idx..)] + // Reorder to: [keep tokens][older(_idx..)][newer(keep..<_idx)] + self.keys = concatenated( + [ + k[.ellipsis, ..= scalarOffset: slice off the end + self.keys = k[.ellipsis, ..<_idx, 0...] + self.values = v[.ellipsis, ..<_idx, 0...] + } + + _idx = self.keys!.dim(2) + rotated = false + } + + // MARK: - Trim Helper + + /// Trim the oldest entries from a buffer (after keep tokens). + /// + /// Preserves the first `keep` positions and trims from the window portion, + /// matching `RotatingKVCache.trim` semantics. + private func trim(trimSize: Int, _ array: MLXArray, append: MLXArray? = nil) -> MLXArray { + var toCat: [MLXArray] = [] + if trimSize > 0 && keep > 0 { + toCat = [ + array[.ellipsis, .. 0 { + toCat = [array[.ellipsis, trimSize..., 0...]] + } else { + toCat = [array] + } + if let append = append { + toCat.append(append) + } + return concatenated(toCat, axis: 2) + } + + // MARK: - State Serialization + + public override var state: [MLXArray] { + get { + guard let keys = self.keys, let values = self.values else { return [] } + let k: MLXArray + let v: MLXArray + if _scalarOffset < keys.dim(2) { + k = keys[.ellipsis, ..<_scalarOffset, 0...] + v = values[.ellipsis, ..<_scalarOffset, 0...] + } else { + k = keys + v = values + } + return [k, v, batchOffsets, leftPadding] + } + set { + guard newValue.count == 4 else { + fatalError( + "BatchRotatingKVCache state must have exactly 4 arrays (keys, values, offset, leftPadding)" + ) + } + self.keys = newValue[0] + self.values = newValue[1] + self.batchOffsets = newValue[2] + self.leftPadding = newValue[3] + } + } + + public override var metaState: [String] { + get { + [ + String(maxCacheSize), String(_scalarOffset), String(_idx), + String(rotated), String(keep), + ] + } + set { + guard newValue.count == 5 else { + fatalError("BatchRotatingKVCache metaState must have exactly 5 values") + } + self.maxCacheSize = Int(newValue[0]) ?? 0 + self._scalarOffset = Int(newValue[1]) ?? 0 + self._idx = Int(newValue[2]) ?? 0 + self.rotated = newValue[3] == "true" + self.keep = Int(newValue[4]) ?? 0 + } + } + + public override var isTrimmable: Bool { + _scalarOffset < maxCacheSize + } + + @discardableResult + public override func trim(_ n: Int) -> Int { + let trimmed = min(_scalarOffset, n) + _scalarOffset -= trimmed + _idx -= trimmed + batchOffsets = batchOffsets - Int32(trimmed) + return trimmed + } + + // MARK: - Prepare / Finalize (Cached-Prompt Prefill) + + /// Prepare the cache for a cached-prompt batch prefill. + /// + /// During prefill with cached prompts of different lengths, some sequences + /// may need right-padding to align. This method stores the state needed to + /// roll back to left-padding on `finalize()`. + /// + /// Matches Python mlx-lm's `BatchRotatingKVCache.prepare()`. + /// + /// - Parameters: + /// - leftPadding: Optional additional left-padding to add (only valid on empty caches). + /// - lengths: Per-sequence token lengths (required when `rightPadding` is used). + /// - rightPadding: Per-sequence right-padding amounts. When provided, + /// stores `_lengths = lengths + offset` so that `finalize()` can roll + /// right-padded tokens back to left-padded order. + public func prepare( + leftPadding: [Int]? = nil, lengths: [Int]? = nil, rightPadding: [Int]? = nil + ) { + if let lp = leftPadding { + precondition( + keys == nil, "Left padding can only be added to an empty BatchRotatingKVCache") + let lpArray = MLXArray(lp.map { Int32($0) }) + self.leftPadding = self.leftPadding + lpArray + self.batchOffsets = self.batchOffsets - lpArray + } + + if let rp = rightPadding, rp.contains(where: { $0 > 0 }), let lengths = lengths { + self._lengths = MLXArray(lengths.map { Int32($0) }) + self.batchOffsets + } + } + + /// Finalize the cache after a cached-prompt batch prefill. + /// + /// If `prepare(rightPadding:lengths:)` was called, this method rolls + /// right-padded key/value data back to left-padded order so that the + /// cache is in the correct state for subsequent decode steps. + /// + /// Matches Python mlx-lm's `BatchRotatingKVCache.finalize()`. + public override func finalize() { + guard let lengths = _lengths else { return } + let roll = MLX.maximum(MLXArray(Int32(0)), batchOffsets - lengths) + if let k = keys, let v = values { + self.keys = dynamicRoll(k, shifts: roll[0..., .newAxis], axis: 2) + self.values = dynamicRoll(v, shifts: roll[0..., .newAxis], axis: 2) + } + self.leftPadding = self.leftPadding + roll + self.batchOffsets = self.batchOffsets - roll + self._lengths = nil + } + + /// The batch size (number of sequences). + public var batchSize: Int { + leftPadding.dim(0) + } + + /// Whether the cache is empty (no keys/values stored). + public var isEmpty: Bool { + keys == nil + } + + // MARK: - BatchPositionedKVCache Conformance + + /// Per-sequence position offsets as an MLXArray of shape `[B]`. + public var batchOffset: MLXArray { + batchOffsets + } + + /// Override `BaseKVCache`'s scalar `ropeOffset` so per-row offsets are used + /// even when this cache flows through attention layers typed as `KVCache`. + public override var ropeOffset: RoPEOffset { .batch(batchOffset + 0) } + + // MARK: - BatchedCache Conformance + + /// Bridges the `BatchedCache` protocol onto this cache's concrete operations. + /// `batchIndices` is small (`[B]`), so the host round-trip is negligible next + /// to the per-token decode work. + public func filterBatched(batchIndices: MLXArray) { + filter(batchIndices: batchIndices.asArray(Int32.self).map(Int.init)) + } + + public func extendBatched(_ other: any BatchedCache) { + guard let other = other as? BatchRotatingKVCache else { + preconditionFailure( + "BatchRotatingKVCache.extendBatched requires another BatchRotatingKVCache") + } + extend(other: other) + } + + public func prepareBatched(leftPadding: [Int]?, lengths: [Int]?, rightPadding: [Int]?) { + prepare(leftPadding: leftPadding, lengths: lengths, rightPadding: rightPadding) + } + + public func finalizeBatched() { + finalize() + } + + public func extractBatched(_ idx: Int) -> any KVCache { + extract(idx: idx) + } + + /// Sliding-window caches have no chunk-local prefill metadata to advance. + public func advanceBatched(_: Int) {} + + public override func copy() -> any KVCache { + let c = BatchRotatingKVCache( + maxSize: maxCacheSize, keep: keep, + leftPaddingArray: leftPadding[0...], batchOffsetsArray: batchOffsets[0...]) + c.keys = keys.map { $0[.ellipsis] } + c.values = values.map { $0[.ellipsis] } + c._idx = _idx + c._scalarOffset = _scalarOffset + c.rotated = rotated + c.step = step + c._lengths = _lengths.map { $0[0...] } + return c + } + + // MARK: - Batch Operations + + /// In-place filter to keep only the sequences at the given batch indices. + /// + /// - Parameter batchIndices: Array of batch indices to keep. + public func filter(batchIndices: [Int]) { + guard !batchIndices.isEmpty else { + keys = nil + values = nil + leftPadding = MLXArray([Int32]()) + batchOffsets = MLXArray([Int32]()) + _idx = 0 + _scalarOffset = 0 + // Clear rotation/prefill state so a reused cache starts unrotated. + rotated = false + _lengths = nil + return + } + + let indices = MLXArray(batchIndices.map { Int32($0) }) + + keys = keys?[indices] + values = values?[indices] + batchOffsets = batchOffsets[indices] + leftPadding = leftPadding[indices] + // Transient prepared-prefill lengths are per-row too: filter with the same + // indices so a cancel between prepare and finalize doesn't roll surviving + // rows with another row's padding (or hit a shape mismatch) in finalize. + _lengths = _lengths?[indices] + } + + /// In-place extend this cache with another BatchRotatingKVCache. + /// + /// If the rotation states differ, both caches are put into temporal order first. + /// + /// - Parameter other: The other BatchRotatingKVCache to merge into this one. + /// + /// Admission contract: the engine prefills every admitted sub-batch before + /// extending the active batch, so a non-empty `other` always arrives with a + /// populated KV buffer. This precondition makes that contract explicit and + /// closes the "append empty admitted rows" hole: an `other` that carries row + /// metadata (`batchSize > 0`) but no prefilled keys is rejected here instead + /// of silently dropping those rows from the enlarged batch. + public func extend(other: BatchRotatingKVCache) { + precondition( + other.keys != nil || other.batchSize == 0, + "BatchRotatingKVCache.extend requires a non-empty `other` to be " + + "prefilled (keys != nil) before extending; the engine prefills " + + "each admitted sub-batch before calling extend." + ) + guard let selfKeys = self.keys, let otherKeys = other.keys else { + if self.keys == nil && other.keys == nil { + // Both empty: concatenate row metadata so admitted rows survive + // until their first prefill instead of being dropped. + self.leftPadding = concatenated([self.leftPadding, other.leftPadding], axis: 0) + self.batchOffsets = concatenated([self.batchOffsets, other.batchOffsets], axis: 0) + } else if other.keys != nil { + // self empty, other populated: adopt other's state. + self.keys = other.keys + self.values = other.values + self.batchOffsets = other.batchOffsets + self.leftPadding = other.leftPadding + self._idx = other._idx + self._scalarOffset = other._scalarOffset + self.rotated = other.rotated + } + return + } + + // If rotation states differ, put both in temporal order + if self.rotated != other.rotated || self._idx != other._idx { + self.temporalOrder() + other.temporalOrder() + } + + let maxIdx = max(self._idx, other._idx) + let maxSize = max(selfKeys.dim(2), otherKeys.dim(2)) + + func pad(_ cache: BatchRotatingKVCache) -> (MLXArray, MLXArray, MLXArray, MLXArray) { + let left = maxIdx - cache._idx + var right = maxSize - cache.keys!.dim(2) - left + + var k = cache.keys! + var v = cache.values! + + if right < 0 { + k = k[.ellipsis, ..<(k.dim(2) + right), 0...] + v = v[.ellipsis, ..<(v.dim(2) + right), 0...] + right = 0 + } + + if left != 0 || right != 0 { + let padWidths: [IntOrPair] = [0, 0, .init((left, right)), 0] + k = MLX.padded(k, widths: padWidths) + v = MLX.padded(v, widths: padWidths) + } + + let adjustedLeftPadding = cache.leftPadding + Int32(left) + + return (k, v, cache.batchOffsets, adjustedLeftPadding) + } + + let (selfK, selfV, selfOff, selfLP) = pad(self) + let (otherK, otherV, otherOff, otherLP) = pad(other) + + self.keys = concatenated([selfK, otherK], axis: 0) + self.values = concatenated([selfV, otherV], axis: 0) + self.batchOffsets = concatenated([selfOff, otherOff], axis: 0) + self.leftPadding = concatenated([selfLP, otherLP], axis: 0) + self._idx = maxIdx + self._scalarOffset = max(self._scalarOffset, other._scalarOffset) + } + + /// Extract a single sequence from the batch as a `RotatingKVCache`. + /// + /// The returned cache has the left-padding stripped and contains only the + /// valid (non-padded) key/value data. The `maxSize` is preserved. + /// + /// - Parameter idx: The batch index of the sequence to extract. + /// - Returns: A `RotatingKVCache` with the extracted sequence data. + public func extract(idx: Int) -> RotatingKVCache { + let cache = RotatingKVCache(maxSize: maxCacheSize, keep: keep) + let rawPadding = Int(leftPadding[idx].item(Int32.self)) + let seqOffset = Int(batchOffsets[idx].item(Int32.self)) + + // After overflow (rotation), leftPadding can become negative because + // updateInPlace decrements it each step. Clamp to non-negative for slicing: + // the effective valid start is max(0, leftPadding). + let padding = max(0, rawPadding) + + if let k = keys, let v = values { + var extractedK = k[idx ..< (idx + 1)] + var extractedV = v[idx ..< (idx + 1)] + + // If rotated, apply temporal ordering before extraction + if rotated { + if keep > 0 { + // With keep: keep prefix is fixed, only roll the window portion + let keepK = extractedK[.ellipsis, .. BatchRotatingKVCache { + // Validate all caches have the same maxSize and keep + var targetMaxSize: Int = 0 + var targetKeep: Int = -1 + for cache in caches { + guard let rotCache = cache as? RotatingKVCache else { + preconditionFailure( + "BatchRotatingKVCache.merge requires RotatingKVCache instances") + } + let ms = rotCache.maxSize ?? 0 + // RotatingKVCache.keep is private; read it via metaState[0] (= keep). + let k = Int(rotCache.metaState.first ?? "0") ?? 0 + if targetMaxSize == 0 { + targetMaxSize = ms + targetKeep = k + } else { + precondition( + ms == targetMaxSize, + "BatchRotatingKVCache can only merge caches with the same maximum size" + ) + precondition( + k == targetKeep, + "BatchRotatingKVCache can only merge caches with the same keep value" + ) + } + } + + // Over-window sources are not yet supported: `temporalState` is + // oldest-first, so slicing its first `maxSize` entries below would keep + // the OLDEST tokens and drop the newest — the opposite of sliding-window + // semantics. Fail loudly instead of silently merging the wrong window. + // (PR #8 review, Codex C4.) + precondition( + caches.allSatisfy { $0.offset <= targetMaxSize }, + "BatchRotatingKVCache.merge does not yet support caches whose offset " + + "exceeds maxSize (wrapped/over-window sources)" + ) + + let lengths = caches.map { min($0.offset, targetMaxSize) } + let maxLength = lengths.max() ?? 0 + let padding = lengths.map { maxLength - $0 } + let offsets = caches.map { $0.offset } + let B = caches.count + + // Find dimensions from first non-empty cache + var H = 0 + var Dk = 0 + var Dv = 0 + var dt: DType = .float16 + + for c in caches { + if let rotCache = c as? RotatingKVCache { + let temporalData = rotCache.temporalState + if temporalData.count >= 2 { + let k = temporalData[0] + let v = temporalData[1] + H = k.dim(1) + Dk = k.dim(3) + Dv = v.dim(3) + dt = k.dtype + break + } + } + } + + guard H > 0 else { + return BatchRotatingKVCache( + maxSize: targetMaxSize, leftPadding: padding, keep: max(targetKeep, 0)) + } + + let keysArr = MLXArray.zeros([B, H, maxLength, Dk], dtype: dt) + let valuesArr = MLXArray.zeros([B, H, maxLength, Dv], dtype: dt) + + for (i, (p, c)) in zip(padding, caches).enumerated() { + // Get temporally ordered keys/values from the RotatingKVCache. + // Sources are guaranteed `offset <= maxSize` by the precondition + // above, so `temporalState` is the full linear history and the + // head slice below is exact. + guard let rotCache = c as? RotatingKVCache else { continue } + let temporalData = rotCache.temporalState + if temporalData.count >= 2 { + let k = temporalData[0] + let v = temporalData[1] + let seqLen = lengths[i] + if seqLen > 0 { + keysArr[i ..< (i + 1), 0..., p ..< (p + seqLen), 0...] = + k[.ellipsis, .. BatchRotatingKVCache { + let ms = cache.maxSize ?? 0 + // RotatingKVCache.keep is private; read it via metaState[0] (= keep). + let k = Int(cache.metaState.first ?? "0") ?? 0 + let batchCache = BatchRotatingKVCache(maxSize: ms, leftPadding: [0], keep: k) + + let temporalData = cache.temporalState + if temporalData.count >= 2 { + batchCache.keys = temporalData[0] + batchCache.values = temporalData[1] + let seqLen = min(cache.offset, ms) + batchCache._idx = seqLen + batchCache._scalarOffset = seqLen + batchCache.batchOffsets = MLXArray([Int32(cache.offset)]) + } + + return batchCache + } + + /// Convert a batch-1 BatchRotatingKVCache back to a RotatingKVCache. + /// + /// - Returns: A `RotatingKVCache` with the single sequence data. + public func toSingle() -> RotatingKVCache { + precondition(batchSize == 1, "toSingle() requires batch size of 1") + return extract(idx: 0) + } + + // MARK: - Mask Creation + + /// Create an attention mask for this batch rotating cache. + /// + /// Accounts for both the sliding window size and left-padding. During + /// rotation, the mask is rolled to match the rotated buffer layout. + /// + /// - Parameters: + /// - n: The sequence length for the new tokens + /// - windowSize: Optional sliding window size (defaults to maxSize) + /// - returnArray: Force return of array mask instead of symbolic + /// - Returns: Attention mask mode for scaled dot product attention + public override func makeMask( + n: Int, windowSize: Int?, returnArray: Bool + ) -> MLXFast.ScaledDotProductAttentionMaskMode { + var effectiveLeftPadding = self.leftPadding + let effectiveWindowSize = windowSize ?? maxCacheSize + let cappedOffset = min(maxCacheSize - 1, _scalarOffset) + + let rinds = MLXArray(Int32(0) ..< Int32(cappedOffset + n)) + var linds = + cappedOffset != 0 + ? MLXArray(Int32(cappedOffset) ..< Int32(cappedOffset + n)) + : rinds + linds = linds[0..., .newAxis] + let rindsRow = rinds[.newAxis] + + // Causal mask: query can attend to keys at or before its position + var mask = linds .>= rindsRow + + // Window mask: restrict attention to the window + mask = mask & (linds .< rindsRow + Int32(effectiveWindowSize)) + + // Adjust left_padding for trimming during multi-token concat + let trimSize = _idx - maxCacheSize + (n > 1 ? 1 : 0) + if trimSize > 0 { + effectiveLeftPadding = effectiveLeftPadding - Int32(trimSize) + } + + // Check if rotated during single-token decode + let isRotated = n == 1 && (rotated || _idx >= maxCacheSize) + if isRotated { + effectiveLeftPadding = effectiveLeftPadding - 1 + } + + // Apply left-padding mask + let lp = effectiveLeftPadding[0..., .newAxis, .newAxis, .newAxis] + mask = mask & (rindsRow .>= lp) + + // Roll mask for rotated buffer, accounting for keep prefix + if isRotated { + var currentIdx = _idx + if currentIdx >= maxCacheSize { + currentIdx = keep + } + if keep > 0 { + // With keep: only roll the window portion (positions keep.. any KVCache + + /// Advance chunk-local metadata after a chunked prefill step. + func advanceBatched(_ n: Int) +} + +// MARK: - BatchedCacheList + +/// Batched wrapper for composite per-layer caches. Some hybrid models keep +/// multiple cache objects per logical layer, so batching has to preserve that +/// nested topology instead of treating the composite as full attention. +public final class BatchedCacheList: CacheList, BatchedCache { + + private let batchedCaches: [any BatchedCache] + + internal init(caches: [any BatchedCache]) { + self.batchedCaches = caches + super.init(caches: caches.map { $0 as any KVCache }) + } + + public func filterBatched(batchIndices: MLXArray) { + for cache in batchedCaches { + cache.filterBatched(batchIndices: batchIndices) + } + } + + public func extendBatched(_ other: any BatchedCache) { + guard let other = other as? BatchedCacheList else { + preconditionFailure("BatchedCacheList.extendBatched requires another BatchedCacheList") + } + precondition( + batchedCaches.count == other.batchedCaches.count, + "Cannot extend BatchedCacheList with different child count" + ) + + for (a, b) in zip(batchedCaches, other.batchedCaches) { + a.extendBatched(b) + } + } + + public func prepareBatched(leftPadding: [Int]?, lengths: [Int]?, rightPadding: [Int]?) { + for cache in batchedCaches { + cache.prepareBatched( + leftPadding: leftPadding, + lengths: lengths, + rightPadding: rightPadding + ) + } + } + + public func finalizeBatched() { + for cache in batchedCaches { + cache.finalizeBatched() + } + } + + public func extractBatched(_ idx: Int) -> any KVCache { + CacheList(caches: batchedCaches.map { $0.extractBatched(idx) }) + } + + public func advanceBatched(_ n: Int) { + for cache in batchedCaches { + cache.advanceBatched(n) + } + } + + /// Deep-copy as a `BatchedCacheList`, preserving the `BatchedCache` wrapper. + /// + /// `CacheList.copy()` rebuilds a plain `CacheList` from copied children, which + /// would strip the continuous-batching protocol from a snapshot taken after the + /// factory builds a composite batched cache. Each batched child's `copy()` + /// returns the same concrete batched type, so it re-conforms to `BatchedCache`. + public override func copy() -> any KVCache { + BatchedCacheList( + caches: batchedCaches.map { child in + guard let copied = child.copy() as? any BatchedCache else { + preconditionFailure( + "BatchedCache.copy() must return a BatchedCache for " + + "BatchedCacheList snapshots" + ) + } + return copied + } + ) + } +} + +// MARK: - SSM cache conformance + +extension ArraysCache: BatchedCache { + public func filterBatched(batchIndices: MLXArray) { + filter(batchIndices: batchIndices) + } + + public func extendBatched(_ other: any BatchedCache) { + guard let other = other as? ArraysCache else { + preconditionFailure("ArraysCache.extendBatched requires another ArraysCache") + } + extend(other: other) + } + + public func prepareBatched(leftPadding _: [Int]?, lengths: [Int]?, rightPadding _: [Int]?) { + prepare(lengths: lengths) + } + + public func finalizeBatched() { + finalize() + } + + public func extractBatched(_ idx: Int) -> any KVCache { + extract(idx) + } + + public func advanceBatched(_ n: Int) { + advance(n) + } +} + +// MARK: - Factory + +/// A closure that allocates one batched cache for `leftPadding.count` rows. +public typealias BatchedCacheFactory = (_ leftPadding: [Int]) -> any BatchedCache + +/// Error thrown when a model's cache topology cannot be batched. +public enum BatchedCacheError: Error, CustomStringConvertible, Equatable { + case unsupportedCacheTopology(layer: Int, path: String, cacheType: String, reason: String) + + public var description: String { + switch self { + case .unsupportedCacheTopology(let layer, let path, let cacheType, let reason): + return "Unsupported cache topology at layer \(layer), \(path): " + + "\(cacheType). \(reason)" + } + } +} + +/// Build one ``BatchedCacheFactory`` per layer from a probe of single-stream +/// caches (typically `model.newCache(parameters:)`). +/// +/// Validating the topology once at engine-construction time means per-admission +/// allocation is a cheap closure call that cannot fail. +/// +/// - Throws: ``BatchedCacheError`` if any layer's cache type has no batched +/// implementation (e.g. quantized or chunked caches). +public func makeBatchedCacheFactories(for probe: [any KVCache]) throws -> [BatchedCacheFactory] { + try probe.enumerated().map { layer, cache in + try makeBatchedCacheFactory(for: cache, layer: layer, path: "layer") + } +} + +/// Convenience: build a fresh set of batched caches for `leftPadding.count` rows +/// directly from a probe of single-stream caches. +public func makeBatchedCache( + for probe: [any KVCache], leftPadding: [Int] +) throws -> [any BatchedCache] { + try makeBatchedCacheFactories(for: probe).map { $0(leftPadding) } +} + +private func makeBatchedCacheFactory( + for cache: any KVCache, + layer: Int, + path: String +) throws -> BatchedCacheFactory { + let cacheType = String(describing: Swift.type(of: cache)) + + func unsupported(_ reason: String) -> BatchedCacheError { + .unsupportedCacheTopology( + layer: layer, + path: path, + cacheType: cacheType, + reason: reason + ) + } + + if cache is QuantizedKVCache { + throw unsupported("Quantized KV caches are not supported by continuous batching.") + } + + if cache is ChunkedKVCache { + throw unsupported("Chunked KV caches are not supported by continuous batching.") + } + + if let cacheList = cache as? CacheList { + let childFactories = try cacheList.children.enumerated().map { childIndex, child in + try makeBatchedCacheFactory( + for: child, + layer: layer, + path: "\(path).children[\(childIndex)]" + ) + } + return { leftPadding in + BatchedCacheList(caches: childFactories.map { $0(leftPadding) }) + } + } + + // Exact-type matches avoid misclassifying subclasses such as + // MambaCache : ArraysCache and ChunkedKVCache : KVCacheSimple. + if Swift.type(of: cache) == MambaCache.self { + return { leftPadding in MambaCache(leftPadding: leftPadding) } + } + + if Swift.type(of: cache) == ArraysCache.self, let arrays = cache as? ArraysCache { + let slotCount = arrays.slotCount + return { leftPadding in ArraysCache(size: slotCount, leftPadding: leftPadding) } + } + + if let rotating = cache as? RotatingKVCache { + guard let maxSize = rotating.maxSize else { + throw unsupported("RotatingKVCache must have a non-nil maxSize.") + } + + // RotatingKVCache.keep is private; metaState layout is + // [keep, maxCacheSize, step, offset, idx]. + let keep = Int(rotating.metaState.first ?? "0") ?? 0 + + // keep > 0 cannot currently be combined with per-row left padding: at + // the rotation wrap, `BatchRotatingKVCache` rolls a padded row's pads + // to the END of the buffer to protect the keep prefix, but the + // prefix-only `leftPadding` mask cannot express trailing garbage, so + // those zero-K/V slots would be attended until overwritten. Until the + // mask model supports it, keep-prefix topologies fall back to + // single-stream (in-repo models all use keep == 0; keep == 4 arises + // only via `GenerateParameters.maxKVSize`). + guard keep == 0 else { + throw unsupported( + "RotatingKVCache with keep > 0 is not supported by continuous batching." + ) + } + + return { leftPadding in + BatchRotatingKVCache(maxSize: maxSize, leftPadding: leftPadding, keep: keep) + } + } + + if Swift.type(of: cache) == KVCacheSimple.self { + return { leftPadding in BatchKVCache(leftPadding: leftPadding) } + } + + throw unsupported("No batched cache implementation exists for this cache type.") +} diff --git a/Libraries/MLXLMCommon/KVCache.swift b/Libraries/MLXLMCommon/KVCache.swift index 4a21fd3d04..1a396ab991 100644 --- a/Libraries/MLXLMCommon/KVCache.swift +++ b/Libraries/MLXLMCommon/KVCache.swift @@ -174,6 +174,12 @@ open class BaseKVCache: KVCache { public var offset: Int = 0 public var maxSize: Int? { nil } + /// Declared as an overridable class member (not only via the `KVCache` + /// extension default) so batched subclasses can override it and have the + /// override dispatched through the `KVCache` witness table — otherwise a + /// batched cache used as `KVCache` would fall back to the scalar offset. + open var ropeOffset: RoPEOffset { .scalar(offset) } + public func innerState() -> [MLXArray] { [] } open func update(keys: MLXArray, values: MLXArray) -> (MLXArray, MLXArray) { @@ -235,7 +241,8 @@ public func createCausalMask( n: Int, offset: Int, windowSize: Int? = nil, - lengths: MLXArray? = nil + lengths: MLXArray? = nil, + leftPadding: MLXArray? = nil ) -> MLXArray { var rinds = MLXArray(Int32(0) ..< Int32(offset + n)) var linds = offset != 0 ? MLXArray(Int32(offset) ..< Int32(offset + n)) : rinds @@ -252,6 +259,13 @@ public func createCausalMask( mask = mask & (rinds .< lengths) } + // Mask out left-padded positions per sequence (continuous batching): + // row `b` may attend only to positions `>= leftPadding[b]`. + if let leftPadding { + let lp = leftPadding[0..., .newAxis, .newAxis, .newAxis] + mask = mask & (rinds .>= lp) + } + return mask } @@ -1294,6 +1308,20 @@ public class ArraysCache: BaseKVCache { leftPadding = nil } + /// Extract one row as its own single-row cache. + /// + /// Note: a ``MambaCache`` row is returned as a base ``ArraysCache`` (the + /// stored slots are identical); the Mamba auto-upgrade path can refine this + /// to preserve the concrete subtype if needed. + public func extract(_ idx: Int) -> ArraysCache { + let extracted = ArraysCache(size: cache.count) + extracted.cache = cache.map { $0?[idx ..< (idx + 1)] } + extracted.offset = offset + extracted.leftPadding = leftPadding?[idx ..< (idx + 1)] + extracted.lengths = lengths?[idx ..< (idx + 1)] + return extracted + } + public func advance(_ N: Int) { if let currentLengths = lengths { lengths = currentLengths - N diff --git a/Tests/MLXLMTests/BatchCacheTests.swift b/Tests/MLXLMTests/BatchCacheTests.swift new file mode 100644 index 0000000000..4ecee0aa22 --- /dev/null +++ b/Tests/MLXLMTests/BatchCacheTests.swift @@ -0,0 +1,308 @@ +// Copyright © 2024 Apple Inc. + +import Foundation +import MLX +import MLXNN +import Testing + +@testable import MLXLMCommon + +// MARK: - BatchKVCache + +@Suite(.serialized) +struct BatchKVCacheCoverageTests { + + @Test("Lifecycle covers update, filter, extend, and extract") + func lifecycleRoundTrip() { + // Zero-padding here so this test exercises lifecycle bookkeeping, not + // left-padding normalization (padding behavior is covered elsewhere). + 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: [0]) + #expect(cache.batchSize == 1) + #expect(cache.leftPadding.shape == [1]) + #expect(cache.leftPadding[0].item(Int32.self) == 0) + + let extensionCache = BatchKVCache(leftPadding: [0]) + let extensionKV = makeKV(batchSize: 1, heads: 2, seqLen: 2, headDim: 4, value: 4) + _ = extensionCache.update(keys: extensionKV.0, values: extensionKV.1) + cache.extend(other: extensionCache) + + #expect(cache.batchSize == 2) + #expect(cache.leftPadding[0].item(Int32.self) == 0) + #expect(cache.leftPadding[1].item(Int32.self) == 1) + #expect(cache.batchOffsets[0].item(Int32.self) == 3) + #expect(cache.batchOffsets[1].item(Int32.self) == 2) + + let extractedFirst = cache.extract(idx: 0) + let extractedSecond = cache.extract(idx: 1) + #expect(extractedFirst.offset == 3) + #expect(extractedSecond.offset == 2) + } + + @Test("fromSingle/toSingle preserve cache data") + func fromSingleRoundTripPreservesData() throws { + let single = KVCacheSimple() + let kv = makeKV(batchSize: 1, heads: 2, seqLen: 4, headDim: 4, value: 3) + _ = single.update(keys: kv.0, values: kv.1) + + let batch = BatchKVCache.fromSingle(single) + #expect(batch.batchSize == 1) + + let restored = batch.toSingle() + let restoredKeys = try #require(restored.state.first) + let originalKeys = try #require(single.state.first) + #expect(restored.offset == single.offset) + #expect(restoredKeys.shape == originalKeys.shape) + #expect(maxAbsDifference(restoredKeys, originalKeys) == 0) + } + + @Test("makeMask honours left padding during decode") + func makeMaskUsesLeftPaddingDuringDecode() { + let cache = BatchKVCache(leftPadding: [1, 3, 0]) + let mode = cache.makeMask(n: 2, windowSize: nil, returnArray: false) + + switch mode { + case .array(let mask): + #expect(mask.dim(0) == 3) + #expect(mask.dim(2) == 2) + // Row 0/1 left-padded slot 0 is masked out. + #expect(mask[0, 0, 0, 0].item(Bool.self) == false) + #expect(mask[1, 0, 0, 0].item(Bool.self) == false) + case .arrays, .causal, .none: + Issue.record("BatchKVCache should produce an explicit array mask for this path") + } + } + + @Test("ropeOffset dispatches to .batch through the KVCache type") + func ropeOffsetDispatchesThroughKVCache() { + // Models read `cache?.ropeOffset` with `cache` typed as `KVCache?`, so the + // batched override must win via witness-table dispatch (not the scalar + // KVCache extension default). + let full: any KVCache = BatchKVCache(leftPadding: [1, 0]) + guard case .batch = full.ropeOffset else { + Issue.record("BatchKVCache.ropeOffset via KVCache should be .batch") + return + } + let rotating: any KVCache = BatchRotatingKVCache(maxSize: 16, leftPadding: [1, 0], keep: 0) + guard case .batch = rotating.ropeOffset else { + Issue.record("BatchRotatingKVCache.ropeOffset via KVCache should be .batch") + return + } + } +} + +// MARK: - BatchRotatingKVCache (keep > 0) + +@Suite(.serialized) +struct BatchRotatingKVCacheCoverageTests { + + @Test("Lifecycle covers update, filter, extend, and extract with keep > 0") + func lifecycleRoundTrip() { + let cache = BatchRotatingKVCache(maxSize: 16, leftPadding: [0, 0], keep: 2) + let (keys, values) = makeDistinctKV(batchSize: 2, heads: 2, seqLen: 3, headDim: 4) + _ = cache.update(keys: keys, values: values) + + cache.filter(batchIndices: [0]) + #expect(cache.batchSize == 1) + + let extensionCache = BatchRotatingKVCache(maxSize: 16, leftPadding: [0], keep: 2) + let extensionKV = makeKV(batchSize: 1, heads: 2, seqLen: 2, headDim: 4, value: 5) + _ = extensionCache.update(keys: extensionKV.0, values: extensionKV.1) + cache.extend(other: extensionCache) + + #expect(cache.batchSize == 2) + #expect(cache.leftPadding[0].item(Int32.self) == 0) + #expect(cache.leftPadding[1].item(Int32.self) == 1) + + let extractedFirst = cache.extract(idx: 0) + let extractedSecond = cache.extract(idx: 1) + #expect(extractedFirst.offset == 3) + #expect(extractedSecond.offset == 2) + // `keep` is exposed on the batched cache (RotatingKVCache.keep is private). + #expect(cache.keep == 2) + } + + @Test("Overflow keeps the sliding window and preserves keep") + func overflowPreservesKeepAndWindow() throws { + let cache = BatchRotatingKVCache(maxSize: 4, leftPadding: [0], keep: 2) + let first = makeKV(batchSize: 1, heads: 2, seqLen: 4, headDim: 4, value: 1) + _ = cache.update(keys: first.0, values: first.1) + + let second = makeKV(batchSize: 1, heads: 2, seqLen: 1, headDim: 4, value: 9) + _ = cache.update(keys: second.0, values: second.1) + + let extracted = cache.extract(idx: 0) + let keys = try #require(extracted.state.first) + #expect(cache.keep == 2) + #expect(extracted.maxSize == 4) + #expect(keys.dim(2) <= 4) + } + + @Test("prepare/finalize preserve extractable state") + func prepareFinalizePreserveExtractableState() { + let cache = BatchRotatingKVCache(maxSize: 32, leftPadding: [2, 0], keep: 4) + cache.prepare(lengths: [3, 5], rightPadding: [2, 0]) + + let kv = makeKV(batchSize: 2, heads: 2, seqLen: 5, headDim: 4, value: 2) + _ = cache.update(keys: kv.0, values: kv.1) + #expect(cache._lengths != nil) + + cache.finalize() + #expect(cache._lengths == nil) + #expect(cache.keep == 4) + } +} + +// MARK: - Factory + BatchedCache protocol surface + +@Suite(.serialized) +struct BatchedCacheFactoryTests { + + @Test("Factory routes supported cache types") + func factoryRoutesSupportedTypes() throws { + let simple = try makeBatchedCacheFactories(for: [KVCacheSimple()]) + #expect(simple[0]([0, 0]) is BatchKVCache) + + let rotating = try makeBatchedCacheFactories(for: [RotatingKVCache(maxSize: 16)]) + #expect(rotating[0]([0]) is BatchRotatingKVCache) + + let arrays = try makeBatchedCacheFactories(for: [ArraysCache(size: 2)]) + let arraysCache = arrays[0]([0]) + #expect(arraysCache is ArraysCache) + #expect((arraysCache as? ArraysCache)?.slotCount == 2) + + let mamba = try makeBatchedCacheFactories(for: [MambaCache()]) + #expect(mamba[0]([0]) is MambaCache) + + let composite = try makeBatchedCacheFactories( + for: [CacheList(KVCacheSimple(), RotatingKVCache(maxSize: 16))]) + #expect(composite[0]([0, 0]) is BatchedCacheList) + } + + @Test("Rotating caches with keep > 0 are rejected (single-stream fallback)") + func rotatingWithKeepIsRejected() { + // keep-prefix rotation + per-row left padding cannot be represented by + // the prefix-only padding mask after the wrap roll; the factory routes + // these topologies back to single-stream until the mask model supports + // trailing-garbage exclusion. + #expect(throws: BatchedCacheError.self) { + _ = try makeBatchedCacheFactories(for: [RotatingKVCache(maxSize: 16, keep: 4)]) + } + } + + @Test("Factory rejects quantized and chunked caches") + func factoryRejectsUnsupportedTypes() { + #expect(throws: BatchedCacheError.self) { + _ = try makeBatchedCacheFactories(for: [QuantizedKVCache()]) + } + #expect(throws: BatchedCacheError.self) { + _ = try makeBatchedCacheFactories(for: [ChunkedKVCache(chunkSize: 16)]) + } + } + + @Test("BatchedCache protocol drives a full-attention cache") + func protocolSurfaceFullAttention() { + let cache: any BatchedCache = BatchKVCache(leftPadding: [0, 0]) + let (keys, values) = makeDistinctKV(batchSize: 2, heads: 2, seqLen: 3, headDim: 4) + _ = cache.update(keys: keys, values: values) + + cache.filterBatched(batchIndices: MLXArray([Int32(0), Int32(1)])) + let extracted = cache.extractBatched(0) + #expect(extracted is KVCacheSimple) + // advanceBatched is a no-op for full attention; just confirm it is callable. + cache.advanceBatched(1) + } +} + +// MARK: - SSM / composite batched lifecycle + +@Suite(.serialized) +struct BatchedSSMCacheTests { + + @Test("ArraysCache conforms to the BatchedCache lifecycle") + func arraysCacheBatchedLifecycle() { + let mamba = MambaCache(leftPadding: [0, 0]) + mamba[0] = MLXArray.ones([2, 4]) + mamba[1] = MLXArray.ones([2, 4]) + + let cache: any BatchedCache = mamba + cache.prepareBatched(leftPadding: nil, lengths: [3, 5], rightPadding: nil) + #expect(mamba.lengths != nil) + + cache.advanceBatched(1) + cache.finalizeBatched() + #expect(mamba.lengths == nil) + + cache.filterBatched(batchIndices: MLXArray([Int32(0)])) + #expect(mamba.batchSize == 1) + } + + @Test("BatchedCacheList preserves nested topology") + func batchedCacheListNested() throws { + let factories = try makeBatchedCacheFactories( + for: [CacheList(KVCacheSimple(), RotatingKVCache(maxSize: 16))]) + let composite = factories[0]([0, 0]) + let list = try #require(composite as? BatchedCacheList) + // Filtering routes through each child without flattening the topology. + list.filterBatched(batchIndices: MLXArray([Int32(0)])) + let extracted = list.extractBatched(0) + #expect(extracted is CacheList) + } +} + +// MARK: - Masking + +@Suite(.serialized) +struct BatchMaskingTests { + + @Test("createCausalMask masks left padding per sequence") + func causalMaskHonoursLeftPadding() { + let leftPadding = MLXArray([Int32(1), Int32(2)]) + let mask = createCausalMask(n: 4, offset: 0, leftPadding: leftPadding) + + #expect(mask.dim(0) == 2) + // Row 0: leftPadding 1 → position 0 masked, position 1 attendable on the diagonal. + #expect(mask[0, 0, 0, 0].item(Bool.self) == false) + #expect(mask[0, 0, 1, 1].item(Bool.self) == true) + // Row 1: leftPadding 2 → positions 0 and 1 masked, position 2 attendable. + #expect(mask[1, 0, 0, 0].item(Bool.self) == false) + #expect(mask[1, 0, 0, 1].item(Bool.self) == false) + #expect(mask[1, 0, 2, 2].item(Bool.self) == true) + } +} + +// MARK: - Helpers + +private func makeKV( + batchSize: Int, + heads: Int, + seqLen: Int, + headDim: Int, + value: Float = 1.0 +) -> (MLXArray, MLXArray) { + let keys = MLXArray.ones([batchSize, heads, seqLen, headDim]) * value + let values = MLXArray.ones([batchSize, heads, seqLen, headDim]) * (value + 1) + return (keys, values) +} + +private func makeDistinctKV( + batchSize: Int, + heads: Int, + seqLen: Int, + headDim: Int +) -> (MLXArray, MLXArray) { + var keysList = [MLXArray]() + var valuesList = [MLXArray]() + for index in 0 ..< batchSize { + keysList.append(MLXArray.ones([1, heads, seqLen, headDim]) * Float(index + 1)) + valuesList.append(MLXArray.ones([1, heads, seqLen, headDim]) * Float((index + 1) * 10)) + } + return (concatenated(keysList, axis: 0), concatenated(valuesList, axis: 0)) +} + +private func maxAbsDifference(_ lhs: MLXArray, _ rhs: MLXArray) -> Float { + abs(lhs.asType(.float32) - rhs.asType(.float32)).max().item(Float.self) +}