From dd8435ce6e419f50d20238fe75e8701e1f55bbc6 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 6 Jun 2026 02:30:12 +0000 Subject: [PATCH 01/13] Add batched KV caches, factory, and cache plumbing (continuous batching PR1) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit First of a stacked series adding continuous/batched inference. This PR is the cache layer only — no engine or scheduler — and must not change single-stream behavior. New (Libraries/MLXLMCommon/Batching/): - BatchedCache: the continuous-batching cache protocol (filter/extend/prepare/ finalize/extract/advance), the BatchedCacheList composite, the SSM conformance for ArraysCache/MambaCache, and the makeBatchedCache factory. - BatchKVCache / BatchRotatingKVCache: full-attention and sliding-window batched caches with left-padding, ragged-prefill prepare/finalize, fromSingle, and (rotating) keep>0 rotation. Both conform to BatchedCache. KVCache.swift: - createCausalMask gains a per-sequence leftPadding argument. - ArraysCache gains the ragged-prefill lifecycle (lengths/prepare/finalize/ advance/extract) and the SSM mask-ordering fix; single-stream callers (which leave leftPadding/lengths nil) are unaffected. The factory routes rotating caches with keep>0 to the keep-capable BatchRotatingKVCache rather than rejecting them, and throws only for quantized and chunked topologies. Deferred (documented for later PRs in the series): - KVCache: Updatable — pending verification of the protocol's requirements on a Metal/macOS build; not needed by the cache layer. - SSM/composite fromSingle and Mamba-typed row extraction — implemented with PR4's auto-upgrade migration, where they can be validated end-to-end. Tests: Tests/MLXLMTests/BatchCacheTests.swift (cache lifecycle, keep>0 overflow, fromSingle, factory routing incl. keep>0, SSM/composite, left-padding masking). https://claude.ai/code/session_01YT4o4e6VgFikQKNzrHrrPp --- .../MLXLMCommon/Batching/BatchKVCache.swift | 532 ++++++++++ .../Batching/BatchRotatingKVCache.swift | 930 ++++++++++++++++++ .../MLXLMCommon/Batching/BatchedCache.swift | 239 +++++ Libraries/MLXLMCommon/KVCache.swift | 24 +- Tests/MLXLMTests/BatchCacheTests.swift | 288 ++++++ 5 files changed, 2012 insertions(+), 1 deletion(-) create mode 100644 Libraries/MLXLMCommon/Batching/BatchKVCache.swift create mode 100644 Libraries/MLXLMCommon/Batching/BatchRotatingKVCache.swift create mode 100644 Libraries/MLXLMCommon/Batching/BatchedCache.swift create mode 100644 Tests/MLXLMTests/BatchCacheTests.swift diff --git a/Libraries/MLXLMCommon/Batching/BatchKVCache.swift b/Libraries/MLXLMCommon/Batching/BatchKVCache.swift new file mode 100644 index 0000000000..f845a5d45d --- /dev/null +++ b/Libraries/MLXLMCommon/Batching/BatchKVCache.swift @@ -0,0 +1,532 @@ +// 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 + } + + // 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 + 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] + + // Shift left to reduce padding + let minLeftPad = leftPadding.min().item(Int32.self) + if minLeftPad > 0 { + 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. + public func extend(other: BatchKVCache) { + guard let selfKeys = self.keys, let otherKeys = other.keys else { + // If self is empty, take the other's state + if other.keys != nil { + 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 `KVCache` instances (typically `KVCacheSimple`). + /// - Returns: A new `BatchKVCache` containing all sequences. + public class func merge(_ caches: [KVCache]) -> BatchKVCache { + 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 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 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..7de7a4d44d --- /dev/null +++ b/Libraries/MLXLMCommon/Batching/BatchRotatingKVCache.swift @@ -0,0 +1,930 @@ +// 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) + let nArr = MLXArray(Int32(n)) + let raw = remainder(reshapedIndices - reshapedShifts, nArr) + let idx = remainder(raw + 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.. [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.max()! > 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 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 + } + + // 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) {} + + // 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 + return + } + + let indices = MLXArray(batchIndices.map { Int32($0) }) + + keys = keys?[indices] + values = values?[indices] + batchOffsets = batchOffsets[indices] + leftPadding = leftPadding[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. + public func extend(other: BatchRotatingKVCache) { + guard let selfKeys = self.keys, let otherKeys = other.keys else { + if other.keys != nil { + 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 + let k = rotCache.keep + 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" + ) + } + } + + 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 + 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 + let k = cache.keep + 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) + } + } +} + +// 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.") + } + + // `BatchRotatingKVCache` handles keep-prefix rotation, so (unlike a + // keep-only sliding window) any `keep` value can be batched. metaState + // layout is [keep, maxCacheSize, step, offset, idx]. + let keep = Int(rotating.metaState.first ?? "0") ?? 0 + + 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..29539b38d3 100644 --- a/Libraries/MLXLMCommon/KVCache.swift +++ b/Libraries/MLXLMCommon/KVCache.swift @@ -235,7 +235,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 +253,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 +1302,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.map { $0[idx ..< (idx + 1)] } + extracted.lengths = lengths.map { $0[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..22bf566657 --- /dev/null +++ b/Tests/MLXLMTests/BatchCacheTests.swift @@ -0,0 +1,288 @@ +// 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") + } + } +} + +// 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 supported (no throw)") + func rotatingWithKeepIsSupported() throws { + let factories = try makeBatchedCacheFactories(for: [RotatingKVCache(maxSize: 16, keep: 4)]) + let cache = factories[0]([0]) + let rotating = try #require(cache as? BatchRotatingKVCache) + #expect(rotating.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) +} From 289fc40db1ffd5afe5f9a3c0409a4f34cb9b8d80 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 6 Jun 2026 04:43:09 +0000 Subject: [PATCH 02/13] Address PR #8 review: fix batched ropeOffset dispatch and cache edge cases Codex / Gemini review fixes: - ropeOffset (Codex P1): BaseKVCache now declares ropeOffset as an overridable class member, and BatchKVCache/BatchRotatingKVCache override it to return the per-row .batch offset. Previously, accessing a batched cache as KVCache dispatched to the scalar extension default, corrupting batched RoPE. Adds a regression test. - extend on empty caches (Codex P2): concatenate row metadata when both caches are empty so admitted rows are not dropped before first prefill (both caches). - filter([]) (Codex P2): reset rotated/_lengths/_rightPadding so a reused rotating cache starts unrotated. - prepare (Gemini high): use rp.contains(where:) instead of rp.max()! to avoid a crash on an empty rightPadding array. - dynamicRoll (Gemini medium): use % instead of remainder to avoid overload ambiguity with Foundation/Darwin remainder. - ArraysCache filter/extract (Gemini medium): use optional-chaining subscripts. Deferred: - Rotating merge/extract tail for over-window prompts (Codex C4): noted in-code; validated in PR4 where merge is wired and testable. https://claude.ai/code/session_01YT4o4e6VgFikQKNzrHrrPp --- .../MLXLMCommon/Batching/BatchKVCache.swift | 13 +++++++-- .../Batching/BatchRotatingKVCache.swift | 29 +++++++++++++++---- Libraries/MLXLMCommon/KVCache.swift | 10 +++++-- Tests/MLXLMTests/BatchCacheTests.swift | 17 +++++++++++ 4 files changed, 60 insertions(+), 9 deletions(-) diff --git a/Libraries/MLXLMCommon/Batching/BatchKVCache.swift b/Libraries/MLXLMCommon/Batching/BatchKVCache.swift index f845a5d45d..8592986ad9 100644 --- a/Libraries/MLXLMCommon/Batching/BatchKVCache.swift +++ b/Libraries/MLXLMCommon/Batching/BatchKVCache.swift @@ -202,6 +202,10 @@ public class BatchKVCache: BaseKVCache, BatchPositionedKVCache, BatchedCache { 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. @@ -248,8 +252,13 @@ public class BatchKVCache: BaseKVCache, BatchPositionedKVCache, BatchedCache { /// - Parameter other: The other BatchKVCache to merge into this one. public func extend(other: BatchKVCache) { guard let selfKeys = self.keys, let otherKeys = other.keys else { - // If self is empty, take the other's state - if other.keys != nil { + 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 diff --git a/Libraries/MLXLMCommon/Batching/BatchRotatingKVCache.swift b/Libraries/MLXLMCommon/Batching/BatchRotatingKVCache.swift index 7de7a4d44d..3b923c37a9 100644 --- a/Libraries/MLXLMCommon/Batching/BatchRotatingKVCache.swift +++ b/Libraries/MLXLMCommon/Batching/BatchRotatingKVCache.swift @@ -44,9 +44,10 @@ internal func dynamicRoll(_ x: MLXArray, shifts: MLXArray, axis: Int) -> MLXArra // 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 raw = remainder(reshapedIndices - reshapedShifts, nArr) - let idx = remainder(raw + nArr, nArr) + let idx = ((reshapedIndices - reshapedShifts) % nArr + nArr) % nArr return takeAlong(x, idx.asType(.int32), axis: positiveAxis) } @@ -509,7 +510,7 @@ public class BatchRotatingKVCache: BaseKVCache, BatchPositionedKVCache, BatchedC self.batchOffsets = self.batchOffsets - lpArray } - if let rp = rightPadding, rp.max()! > 0, let lengths = lengths { + if let rp = rightPadding, rp.contains(where: { $0 > 0 }), let lengths = lengths { self._lengths = MLXArray(lengths.map { Int32($0) }) + self.batchOffsets } } @@ -550,6 +551,10 @@ public class BatchRotatingKVCache: BaseKVCache, BatchPositionedKVCache, BatchedC 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. @@ -595,6 +600,10 @@ public class BatchRotatingKVCache: BaseKVCache, BatchPositionedKVCache, BatchedC batchOffsets = MLXArray([Int32]()) _idx = 0 _scalarOffset = 0 + // Clear rotation/prefill state so a reused cache starts unrotated. + rotated = false + _lengths = nil + _rightPadding = nil return } @@ -613,7 +622,13 @@ public class BatchRotatingKVCache: BaseKVCache, BatchPositionedKVCache, BatchedC /// - Parameter other: The other BatchRotatingKVCache to merge into this one. public func extend(other: BatchRotatingKVCache) { guard let selfKeys = self.keys, let otherKeys = other.keys else { - if other.keys != nil { + 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 @@ -796,7 +811,11 @@ public class BatchRotatingKVCache: BaseKVCache, BatchPositionedKVCache, BatchedC 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 + // Get temporally ordered keys/values from the RotatingKVCache. + // NOTE (deferred to PR4): when a source prompt exceeds `maxSize`, the + // tail-vs-head retention of the temporal slice here needs validation + // against the single-stream rotating cache. `merge` is not wired until + // PR4, so this is exercised and tested there. (PR #8 review, Codex C4.) guard let rotCache = c as? RotatingKVCache else { continue } let temporalData = rotCache.temporalState if temporalData.count >= 2 { diff --git a/Libraries/MLXLMCommon/KVCache.swift b/Libraries/MLXLMCommon/KVCache.swift index 29539b38d3..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) { @@ -1311,8 +1317,8 @@ public class ArraysCache: BaseKVCache { let extracted = ArraysCache(size: cache.count) extracted.cache = cache.map { $0?[idx ..< (idx + 1)] } extracted.offset = offset - extracted.leftPadding = leftPadding.map { $0[idx ..< (idx + 1)] } - extracted.lengths = lengths.map { $0[idx ..< (idx + 1)] } + extracted.leftPadding = leftPadding?[idx ..< (idx + 1)] + extracted.lengths = lengths?[idx ..< (idx + 1)] return extracted } diff --git a/Tests/MLXLMTests/BatchCacheTests.swift b/Tests/MLXLMTests/BatchCacheTests.swift index 22bf566657..9f8729ce94 100644 --- a/Tests/MLXLMTests/BatchCacheTests.swift +++ b/Tests/MLXLMTests/BatchCacheTests.swift @@ -75,6 +75,23 @@ struct BatchKVCacheCoverageTests { 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) From e480c36fc7f97fa576b0d8b4507e476f70a93836 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 6 Jun 2026 04:54:42 +0000 Subject: [PATCH 03/13] Ignore Claude Code agent worktrees (.claude/worktrees/) https://claude.ai/code/session_01YT4o4e6VgFikQKNzrHrrPp --- .gitignore | 3 +++ 1 file changed, 3 insertions(+) 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/ + From 394e316c25fb31806656faac86c398e8d9e06334 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 6 Jun 2026 05:20:09 +0000 Subject: [PATCH 04/13] Fix compile error: read RotatingKVCache.keep via metaState RotatingKVCache.keep is private to KVCache.swift, so BatchRotatingKVCache's merge/fromSingle could not read cache.keep directly. Read it via the public metaState[0] (= keep), matching the makeBatchedCache factory. Flagged by the PR2 engine work as a stack-wide compile blocker. https://claude.ai/code/session_01YT4o4e6VgFikQKNzrHrrPp --- Libraries/MLXLMCommon/Batching/BatchRotatingKVCache.swift | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/Libraries/MLXLMCommon/Batching/BatchRotatingKVCache.swift b/Libraries/MLXLMCommon/Batching/BatchRotatingKVCache.swift index 3b923c37a9..1765e15ddd 100644 --- a/Libraries/MLXLMCommon/Batching/BatchRotatingKVCache.swift +++ b/Libraries/MLXLMCommon/Batching/BatchRotatingKVCache.swift @@ -759,7 +759,8 @@ public class BatchRotatingKVCache: BaseKVCache, BatchPositionedKVCache, BatchedC "BatchRotatingKVCache.merge requires RotatingKVCache instances") } let ms = rotCache.maxSize ?? 0 - let k = rotCache.keep + // 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 @@ -848,7 +849,8 @@ public class BatchRotatingKVCache: BaseKVCache, BatchPositionedKVCache, BatchedC /// - Returns: A new `BatchRotatingKVCache` with batch size 1. public class func fromSingle(_ cache: RotatingKVCache) -> BatchRotatingKVCache { let ms = cache.maxSize ?? 0 - let k = cache.keep + // 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 From 4b1c0945a5f84812de434f961419de6cd39fc872 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 6 Jun 2026 05:27:53 +0000 Subject: [PATCH 05/13] Address PR #8 re-review: fix filter([]) compile error, add copy() overrides MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Remove `_rightPadding = nil` from BatchRotatingKVCache.filter([]) — that field only exists on BatchKVCache, so assigning it on the rotating cache was a compile error introduced in the prior fix round (Codex P1). - Add copy() overrides to BatchKVCache and BatchRotatingKVCache so generic snapshot/copy paths (e.g. ChatSession's `cache.map { $0.copy() }`, and CacheList.copy() with batched children) deep-copy keys/values/offsets/padding/ transient state instead of hitting BaseKVCache.copy()'s fatalError (Codex P2). https://claude.ai/code/session_01YT4o4e6VgFikQKNzrHrrPp --- Libraries/MLXLMCommon/Batching/BatchKVCache.swift | 11 +++++++++++ .../Batching/BatchRotatingKVCache.swift | 15 ++++++++++++++- 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/Libraries/MLXLMCommon/Batching/BatchKVCache.swift b/Libraries/MLXLMCommon/Batching/BatchKVCache.swift index 8592986ad9..aebf11df29 100644 --- a/Libraries/MLXLMCommon/Batching/BatchKVCache.swift +++ b/Libraries/MLXLMCommon/Batching/BatchKVCache.swift @@ -535,6 +535,17 @@ public class BatchKVCache: BaseKVCache, BatchPositionedKVCache, BatchedCache { /// 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 index 1765e15ddd..0903402a5c 100644 --- a/Libraries/MLXLMCommon/Batching/BatchRotatingKVCache.swift +++ b/Libraries/MLXLMCommon/Batching/BatchRotatingKVCache.swift @@ -587,6 +587,20 @@ public class BatchRotatingKVCache: BaseKVCache, BatchPositionedKVCache, BatchedC /// 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. @@ -603,7 +617,6 @@ public class BatchRotatingKVCache: BaseKVCache, BatchPositionedKVCache, BatchedC // Clear rotation/prefill state so a reused cache starts unrotated. rotated = false _lengths = nil - _rightPadding = nil return } From 9bc4fa632387a7d13e9a7825756fb1eb68776e52 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 7 Jun 2026 14:53:24 +0000 Subject: [PATCH 06/13] Address PR #8 review: report logical offset from BatchRotatingKVCache, enforce prefill-before-extend - BatchRotatingKVCache.offset now reports the monotonic logical cache length (min(_scalarOffset, maxCacheSize)) instead of the ring write pointer _idx. _idx resets to `keep` on wrap, so generic callers that derive masks from cache.offset (e.g. the array-based createAttentionMask(h:cache:) used by Gemma2ModelInner) saw the position jump backward after the first rotation and built masks with too small an offset. This mirrors single-stream RotatingKVCache.offset, which reports a monotonic position rather than the ring index. - Both extend() methods now precondition that a non-empty `other` (batchSize > 0) has been prefilled (keys != nil), making the prefill-before-extend admission contract explicit in code and closing the "append empty admitted rows" hole. The PR2 engine prefills each admitted sub-batch before calling extend, so this path is unreachable in the engine flow. https://claude.ai/code/session_01YT4o4e6VgFikQKNzrHrrPp --- .../MLXLMCommon/Batching/BatchKVCache.swift | 13 +++++++++ .../Batching/BatchRotatingKVCache.swift | 29 +++++++++++++++++-- 2 files changed, 39 insertions(+), 3 deletions(-) diff --git a/Libraries/MLXLMCommon/Batching/BatchKVCache.swift b/Libraries/MLXLMCommon/Batching/BatchKVCache.swift index aebf11df29..5a22bb43c4 100644 --- a/Libraries/MLXLMCommon/Batching/BatchKVCache.swift +++ b/Libraries/MLXLMCommon/Batching/BatchKVCache.swift @@ -250,7 +250,20 @@ public class BatchKVCache: BaseKVCache, BatchPositionedKVCache, BatchedCache { /// 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 diff --git a/Libraries/MLXLMCommon/Batching/BatchRotatingKVCache.swift b/Libraries/MLXLMCommon/Batching/BatchRotatingKVCache.swift index 0903402a5c..8d4185da9b 100644 --- a/Libraries/MLXLMCommon/Batching/BatchRotatingKVCache.swift +++ b/Libraries/MLXLMCommon/Batching/BatchRotatingKVCache.swift @@ -171,10 +171,20 @@ public class BatchRotatingKVCache: BaseKVCache, BatchPositionedKVCache, BatchedC /// The maximum size of this cache (sliding window size). public override var maxSize: Int? { maxCacheSize } - /// The scalar offset (returns `_idx` for compatibility with KVCache protocol). + /// 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 { _idx } - set { _idx = newValue } + get { min(_scalarOffset, maxCacheSize) } + set { _scalarOffset = newValue } } /// Initialize a BatchRotatingKVCache with a maximum size and left-padding per sequence. @@ -633,7 +643,20 @@ public class BatchRotatingKVCache: BaseKVCache, BatchPositionedKVCache, BatchedC /// 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 From 189f43e0244a4d020ae464f7c2b6275f0bae0e53 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 7 Jun 2026 15:34:40 +0000 Subject: [PATCH 07/13] Address PR #8 re-review: guard empty-cache filter shift, fix rotating extract idx, preserve BatchedCacheList in copy - BatchKVCache.filter: skip the left-padding buffer/index shift while keys == nil so a fresh/cancelled-before-prefill cache does not drive _idx negative or leave batchOffsets inconsistent, which would corrupt the next prefill's prev range. - BatchRotatingKVCache.extract: restore the single RotatingKVCache idx from the row's logical write position (min(seqOffset, maxCacheSize) clamped to the extracted tensor length) instead of the padded tensor length, so a shorter/left-padded row in a globally-rotated batch does not lose its first post-extraction token. - BatchedCacheList.copy: override CacheList.copy to return a BatchedCacheList of copied BatchedCache children so generic cache snapshots keep the continuous-batching wrapper (filter/extend/ finalize/extract through the protocol). https://claude.ai/code/session_01YT4o4e6VgFikQKNzrHrrPp --- .../MLXLMCommon/Batching/BatchKVCache.swift | 8 ++++++-- .../Batching/BatchRotatingKVCache.swift | 13 ++++++++++-- .../MLXLMCommon/Batching/BatchedCache.swift | 20 +++++++++++++++++++ 3 files changed, 37 insertions(+), 4 deletions(-) diff --git a/Libraries/MLXLMCommon/Batching/BatchKVCache.swift b/Libraries/MLXLMCommon/Batching/BatchKVCache.swift index 5a22bb43c4..d37970d456 100644 --- a/Libraries/MLXLMCommon/Batching/BatchKVCache.swift +++ b/Libraries/MLXLMCommon/Batching/BatchKVCache.swift @@ -233,9 +233,13 @@ public class BatchKVCache: BaseKVCache, BatchPositionedKVCache, BatchedCache { batchOffsets = batchOffsets[indices] leftPadding = leftPadding[indices] - // Shift left to reduce padding + // 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`. let minLeftPad = leftPadding.min().item(Int32.self) - if minLeftPad > 0 { + if minLeftPad > 0, keys != nil { let padInt = Int(minLeftPad) keys = keys?[.ellipsis, padInt..., 0...] values = values?[.ellipsis, padInt..., 0...] diff --git a/Libraries/MLXLMCommon/Batching/BatchRotatingKVCache.swift b/Libraries/MLXLMCommon/Batching/BatchRotatingKVCache.swift index 8d4185da9b..edaffbb685 100644 --- a/Libraries/MLXLMCommon/Batching/BatchRotatingKVCache.swift +++ b/Libraries/MLXLMCommon/Batching/BatchRotatingKVCache.swift @@ -768,8 +768,17 @@ public class BatchRotatingKVCache: BaseKVCache, BatchPositionedKVCache, BatchedC cache.state = [extractedK, extractedV] cache.offset = seqOffset - // Set metaState to configure idx properly - let cacheIdx = extractedK.dim(2) + // Restore `idx` as the row's logical cache write position, not the + // padded tensor length. In the rotated path the slice keeps trailing + // padded slots beyond this row's `seqOffset` (a shorter/left-padded + // row in a globally-rotated batch), so `extractedK.dim(2)` would push + // the next write past those pad slots while `offset == seqOffset`, + // landing the next token outside the returned `..<(offset+1)` slice and + // losing the first post-extraction token. Clamp to the logical length + // (`min(seqOffset, maxCacheSize)`) and the physical tensor length so a + // full row still restores `idx == maxCacheSize` (wraps to `keep`) while + // a shorter row writes at its true logical position. + let cacheIdx = min(min(seqOffset, maxCacheSize), extractedK.dim(2)) cache.metaState = [ String(keep), String(maxCacheSize), "256", String(seqOffset), String(cacheIdx), ] diff --git a/Libraries/MLXLMCommon/Batching/BatchedCache.swift b/Libraries/MLXLMCommon/Batching/BatchedCache.swift index d9e0b1cf5b..9004a647db 100644 --- a/Libraries/MLXLMCommon/Batching/BatchedCache.swift +++ b/Libraries/MLXLMCommon/Batching/BatchedCache.swift @@ -95,6 +95,26 @@ public final class BatchedCacheList: CacheList, BatchedCache { 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 From 83fe975cfd675eadefea3230745e9f0ebb0cf493 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 12 Jun 2026 23:38:52 +0000 Subject: [PATCH 08/13] Review fixes: reject keep>0 topologies, guard merge silent-corruption paths MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Factory: RotatingKVCache probes with keep > 0 now throw BatchedCacheError. The keep-prefix wrap roll moves a padded row's pads to the END of the buffer, which the prefix-only leftPadding mask cannot express, so zero-K/V slots would be attended until overwritten. All in-repo models use keep == 0; keep == 4 arises only via maxKVSize, which now falls back to single-stream. - BatchKVCache.merge: precondition that all sources are KVCacheSimple (non-simple caches previously contributed silent all-zero rows). - BatchRotatingKVCache.merge: precondition that no source exceeds maxSize — temporalState is oldest-first, so the head slice would keep the oldest tokens and drop the newest (Codex C4); fail loudly instead. Removed the stale 'exercised and tested in PR4' note (PR4's upgrade path uses fromSingle, not merge). - BatchRotatingKVCache: class-doc warning documenting the keep>0 + left-padding limitation for direct users. https://claude.ai/code/session_01JWyjaK32no59hZqNf4kCty --- .../MLXLMCommon/Batching/BatchKVCache.swift | 9 ++++++- .../Batching/BatchRotatingKVCache.swift | 26 ++++++++++++++++--- .../MLXLMCommon/Batching/BatchedCache.swift | 19 +++++++++++--- Tests/MLXLMTests/BatchCacheTests.swift | 15 ++++++----- 4 files changed, 55 insertions(+), 14 deletions(-) diff --git a/Libraries/MLXLMCommon/Batching/BatchKVCache.swift b/Libraries/MLXLMCommon/Batching/BatchKVCache.swift index d37970d456..5414a64776 100644 --- a/Libraries/MLXLMCommon/Batching/BatchKVCache.swift +++ b/Libraries/MLXLMCommon/Batching/BatchKVCache.swift @@ -350,9 +350,16 @@ public class BatchKVCache: BaseKVCache, BatchPositionedKVCache, BatchedCache { /// Each cache is right-justified in the batch: shorter caches receive left-padding /// to match the longest sequence. /// - /// - Parameter caches: An array of `KVCache` instances (typically `KVCacheSimple`). + /// - 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 } diff --git a/Libraries/MLXLMCommon/Batching/BatchRotatingKVCache.swift b/Libraries/MLXLMCommon/Batching/BatchRotatingKVCache.swift index edaffbb685..15c4c2d8cb 100644 --- a/Libraries/MLXLMCommon/Batching/BatchRotatingKVCache.swift +++ b/Libraries/MLXLMCommon/Batching/BatchRotatingKVCache.swift @@ -130,6 +130,14 @@ extension RotatingKVCache { /// /// Like `BatchKVCache`, inputs are expected to be left-padded so that /// variable-length sequences align on the right. +/// +/// > 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]`. @@ -821,6 +829,17 @@ public class BatchRotatingKVCache: BaseKVCache, BatchPositionedKVCache, BatchedC } } + // 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 } @@ -858,10 +877,9 @@ public class BatchRotatingKVCache: BaseKVCache, BatchPositionedKVCache, BatchedC for (i, (p, c)) in zip(padding, caches).enumerated() { // Get temporally ordered keys/values from the RotatingKVCache. - // NOTE (deferred to PR4): when a source prompt exceeds `maxSize`, the - // tail-vs-head retention of the temporal slice here needs validation - // against the single-stream rotating cache. `merge` is not wired until - // PR4, so this is exercised and tested there. (PR #8 review, Codex C4.) + // 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 { diff --git a/Libraries/MLXLMCommon/Batching/BatchedCache.swift b/Libraries/MLXLMCommon/Batching/BatchedCache.swift index 9004a647db..dcf62348e5 100644 --- a/Libraries/MLXLMCommon/Batching/BatchedCache.swift +++ b/Libraries/MLXLMCommon/Batching/BatchedCache.swift @@ -241,11 +241,24 @@ private func makeBatchedCacheFactory( throw unsupported("RotatingKVCache must have a non-nil maxSize.") } - // `BatchRotatingKVCache` handles keep-prefix rotation, so (unlike a - // keep-only sliding window) any `keep` value can be batched. metaState - // layout is [keep, maxCacheSize, step, offset, idx]. + // 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) } diff --git a/Tests/MLXLMTests/BatchCacheTests.swift b/Tests/MLXLMTests/BatchCacheTests.swift index 9f8729ce94..4ecee0aa22 100644 --- a/Tests/MLXLMTests/BatchCacheTests.swift +++ b/Tests/MLXLMTests/BatchCacheTests.swift @@ -182,12 +182,15 @@ struct BatchedCacheFactoryTests { #expect(composite[0]([0, 0]) is BatchedCacheList) } - @Test("Rotating caches with keep > 0 are supported (no throw)") - func rotatingWithKeepIsSupported() throws { - let factories = try makeBatchedCacheFactories(for: [RotatingKVCache(maxSize: 16, keep: 4)]) - let cache = factories[0]([0]) - let rotating = try #require(cache as? BatchRotatingKVCache) - #expect(rotating.keep == 4) + @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") From 021ca56bbbb4a6ff2da6781de7c5ccce284b626b Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 24 Jun 2026 00:28:01 +0000 Subject: [PATCH 09/13] Add fork-only Swift build CI (build-for-testing on macOS) Adds a separate .github/workflows/swift.yml that builds the package (and compiles the tests, without running them) on every pushed commit, on a hosted Apple Silicon runner so the Metal toolchain is available. Gated with `if: github.repository == 'PicoMLX/mlx-swift-lm'` so it runs only on this fork and stays inert if it ever reaches upstream ml-explore, mirroring how pull_request.yml gates its jobs to ml-explore. Kept as a separate file from pull_request.yml so upstream syncs never conflict here. Co-Authored-By: Claude Opus 4.8 Claude-Session: https://claude.ai/code/session_01PdgqCjBLQ7ifUYhHYE381b --- .github/workflows/swift.yml | 45 +++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 .github/workflows/swift.yml diff --git a/.github/workflows/swift.yml b/.github/workflows/swift.yml new file mode 100644 index 0000000000..03aeb801ce --- /dev/null +++ b/.github/workflows/swift.yml @@ -0,0 +1,45 @@ +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' + # Apple Silicon hosted runner: provides Xcode + the Metal toolchain needed to + # produce the Metal library that `swift build` alone cannot. + runs-on: macos-14 + steps: + - uses: actions/checkout@v6 + with: + submodules: recursive + + - 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' From 1bec22f3541c7a4308a0aa24e08a84e371cbcd97 Mon Sep 17 00:00:00 2001 From: Ronald Mannak Date: Tue, 23 Jun 2026 17:35:29 -0700 Subject: [PATCH 10/13] Add override --- Libraries/MLXLMCommon/Batching/BatchKVCache.swift | 2 +- Libraries/MLXLMCommon/Batching/BatchRotatingKVCache.swift | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Libraries/MLXLMCommon/Batching/BatchKVCache.swift b/Libraries/MLXLMCommon/Batching/BatchKVCache.swift index 5414a64776..e4223a9fd2 100644 --- a/Libraries/MLXLMCommon/Batching/BatchKVCache.swift +++ b/Libraries/MLXLMCommon/Batching/BatchKVCache.swift @@ -505,7 +505,7 @@ public class BatchKVCache: BaseKVCache, BatchPositionedKVCache, BatchedCache { /// the causal mask correctly excludes it. /// /// Matches Python mlx-lm's `BatchKVCache.finalize()`. - public func finalize() { + public override func finalize() { guard let padding = _rightPadding else { return } if let k = keys, let v = values { diff --git a/Libraries/MLXLMCommon/Batching/BatchRotatingKVCache.swift b/Libraries/MLXLMCommon/Batching/BatchRotatingKVCache.swift index 15c4c2d8cb..24624c0b8c 100644 --- a/Libraries/MLXLMCommon/Batching/BatchRotatingKVCache.swift +++ b/Libraries/MLXLMCommon/Batching/BatchRotatingKVCache.swift @@ -540,7 +540,7 @@ public class BatchRotatingKVCache: BaseKVCache, BatchPositionedKVCache, BatchedC /// cache is in the correct state for subsequent decode steps. /// /// Matches Python mlx-lm's `BatchRotatingKVCache.finalize()`. - public func 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 { From cf1ec84777866f60b7c0b8c943bf642dbf71068a Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 24 Jun 2026 03:26:54 +0000 Subject: [PATCH 11/13] CI: use macos-15 + latest Xcode for Swift 6.1 toolchain The first runs failed at package resolution: the macos-14 image ships Xcode 15.4 / Swift 5.10, but Package.swift declares swift-tools-version 6.1 ("using Swift tools version 6.1.0 but the installed version is 5.10.0", exit 74). Switch to the macos-15 image and select the latest stable Xcode (Swift 6.1+) so package resolution and the build can proceed. Co-Authored-By: Claude Opus 4.8 Claude-Session: https://claude.ai/code/session_01PdgqCjBLQ7ifUYhHYE381b --- .github/workflows/swift.yml | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/.github/workflows/swift.yml b/.github/workflows/swift.yml index 03aeb801ce..7f70ddb35d 100644 --- a/.github/workflows/swift.yml +++ b/.github/workflows/swift.yml @@ -27,14 +27,24 @@ jobs: build: # Fork-only. Never runs on upstream ml-explore (kept inert if it lands there). if: github.repository == 'PicoMLX/mlx-swift-lm' - # Apple Silicon hosted runner: provides Xcode + the Metal toolchain needed to - # produce the Metal library that `swift build` alone cannot. - runs-on: macos-14 + # 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 From 3b558f161a2d3dbd62ac99be04349ea4c9e6545b Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 24 Jun 2026 04:41:12 +0000 Subject: [PATCH 12/13] Fix BatchKVCache.filter: guard left-shift on _idx >= minLeftPad Addresses a high-severity review finding (PR #16). filter(batchIndices:) left-shifts keys/values by minLeftPad to compact padding, but only guarded on `keys != nil`. During chunked prefill the KV buffer can exist before the write pointer (_idx) has advanced past the padding; shifting then drives _idx negative and slices past the written region, keeping uninitialized data. Require `_idx >= minLeftPad` so the shift is skipped until enough tokens are written (state stays consistent, just un-compacted that round). Co-Authored-By: Claude Opus 4.8 Claude-Session: https://claude.ai/code/session_01PdgqCjBLQ7ifUYhHYE381b --- Libraries/MLXLMCommon/Batching/BatchKVCache.swift | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/Libraries/MLXLMCommon/Batching/BatchKVCache.swift b/Libraries/MLXLMCommon/Batching/BatchKVCache.swift index e4223a9fd2..e1bccf773d 100644 --- a/Libraries/MLXLMCommon/Batching/BatchKVCache.swift +++ b/Libraries/MLXLMCommon/Batching/BatchKVCache.swift @@ -238,8 +238,13 @@ public class BatchKVCache: BaseKVCache, BatchPositionedKVCache, BatchedCache { // 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 { + if minLeftPad > 0, keys != nil, _idx >= Int(minLeftPad) { let padInt = Int(minLeftPad) keys = keys?[.ellipsis, padInt..., 0...] values = values?[.ellipsis, padInt..., 0...] From 3636be44e0171ac60cb1eccd2acd3cca10527702 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 24 Jun 2026 04:56:41 +0000 Subject: [PATCH 13/13] Filter transient prefill metadata with rows in batched caches Addresses two P2 review findings (PR #16). filter(batchIndices:) reindexed keys/values/batchOffsets/leftPadding but left the transient prepare->finalize metadata at the pre-filter batch shape: - BatchKVCache._rightPadding (set by prepareBatched, consumed by finalize) - BatchRotatingKVCache._lengths (prepared right-padded prefill) If a row is cancelled/filtered between prepareBatched(...) and finalize(), finalize() then rolls/subtracts using padding for rows that no longer exist, hitting a shape error or rolling surviving rows with the wrong per-row pad. Filter both with the same indices; also clear BatchKVCache._rightPadding in the empty-filter branch (BatchRotatingKVCache already clears _lengths there). Co-Authored-By: Claude Opus 4.8 Claude-Session: https://claude.ai/code/session_01PdgqCjBLQ7ifUYhHYE381b --- Libraries/MLXLMCommon/Batching/BatchKVCache.swift | 8 ++++++++ Libraries/MLXLMCommon/Batching/BatchRotatingKVCache.swift | 4 ++++ 2 files changed, 12 insertions(+) diff --git a/Libraries/MLXLMCommon/Batching/BatchKVCache.swift b/Libraries/MLXLMCommon/Batching/BatchKVCache.swift index e1bccf773d..81aed9933a 100644 --- a/Libraries/MLXLMCommon/Batching/BatchKVCache.swift +++ b/Libraries/MLXLMCommon/Batching/BatchKVCache.swift @@ -222,6 +222,9 @@ public class BatchKVCache: BaseKVCache, BatchPositionedKVCache, BatchedCache { 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 } @@ -232,6 +235,11 @@ public class BatchKVCache: BaseKVCache, BatchPositionedKVCache, BatchedCache { 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, diff --git a/Libraries/MLXLMCommon/Batching/BatchRotatingKVCache.swift b/Libraries/MLXLMCommon/Batching/BatchRotatingKVCache.swift index 24624c0b8c..02c02f660e 100644 --- a/Libraries/MLXLMCommon/Batching/BatchRotatingKVCache.swift +++ b/Libraries/MLXLMCommon/Batching/BatchRotatingKVCache.swift @@ -644,6 +644,10 @@ public class BatchRotatingKVCache: BaseKVCache, BatchPositionedKVCache, BatchedC 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.