From 7da5838e20f549a8f944b0de2ed5a7ddc6406219 Mon Sep 17 00:00:00 2001 From: Alessio Pollero Date: Sat, 24 Oct 2026 17:01:24 +0400 Subject: [PATCH] Attend a rotating cache with a rewind reserve in place A rewind reserve (#622) lets a rotating cache step back across its window edge, but it also taxed every generated token: update(keys:values:) returned retainedView(tail:), a fresh concatenation of the pinned prefix and the window tail, in every layer on every decode step. On granite-4.1-8b-4bit with an 8,192-token window and a 1,024-token reserve that copy is about 1.3 GB per token, and decode fell from 12.0 to 8.8 tok/s. RotatingKVCache now implements KVCacheAttentionProtocol. A one-token write with a reserve and no caller mask goes through updateAndAttend, which writes into the ring and attends it in place with a mask over the reserve rows. Multi-token writes, caller-supplied masks and caches without a reserve keep the existing update(keys:values:) path unchanged. retainedView and the new mask share one retainedRanges(tail:) helper, so they cannot disagree about which rows make up the window. Without a reserve the generated text is byte-identical. With one, the copy is gone: 11.5-11.6 tok/s against 11.9-12.0 without, instead of 8.8. --- Libraries/MLXLMCommon/KVCache.swift | 68 ++++++++--- .../RotatingKVCacheRewindTests.swift | 114 ++++++++++++++++++ 2 files changed, 167 insertions(+), 15 deletions(-) diff --git a/Libraries/MLXLMCommon/KVCache.swift b/Libraries/MLXLMCommon/KVCache.swift index d4b000d33b..05c7f123af 100644 --- a/Libraries/MLXLMCommon/KVCache.swift +++ b/Libraries/MLXLMCommon/KVCache.swift @@ -626,7 +626,7 @@ public class KVCacheSimple: BaseKVCache, CustomDebugStringConvertible { } /// Rotating KV cache for sliding window attention -public class RotatingKVCache: BaseKVCache, CustomDebugStringConvertible { +public class RotatingKVCache: BaseKVCache, KVCacheAttentionProtocol, CustomDebugStringConvertible { public override class var serializedClassName: String? { "RotatingKVCache" } public override class func restore( @@ -788,7 +788,17 @@ public class RotatingKVCache: BaseKVCache, CustomDebugStringConvertible { } private func retainedView(tail: Int) -> (MLXArray, MLXArray)? { - guard let keys = self.keys, let values = self.values else { return nil } + guard let keys, let values, let ranges = retainedRanges(tail: tail) else { return nil } + func view(_ array: MLXArray) -> MLXArray { + let parts = ranges.map { array[.ellipsis, $0, 0...] } + return parts.count == 1 ? parts[0] : concatenated(parts, axis: 2) + } + return (view(keys), view(values)) + } + + /// Storage rows holding the trailing `tail` entries, in chronological order. + private func retainedRanges(tail: Int) -> [Range]? { + guard let keys else { return nil } let available = wrapped ? keys.dim(2) : idx let prefix = Swift.min(keep, available) @@ -797,27 +807,29 @@ public class RotatingKVCache: BaseKVCache, CustomDebugStringConvertible { if !wrapped || idx == available { if prefix == 0 || bound == available { - return ( - keys[.ellipsis, (available - bound) ..< available, 0...], - values[.ellipsis, (available - bound) ..< available, 0...] - ) + return [(available - bound) ..< available] } } else if prefix == 0 && bound <= idx { - return ( - keys[.ellipsis, (idx - bound) ..< idx, 0...], - values[.ellipsis, (idx - bound) ..< idx, 0...] - ) + return [(idx - bound) ..< idx] } let recent = Swift.min(bound - prefix, idx - prefix) let older = bound - prefix - recent - let ranges = [0 ..< prefix, (available - older) ..< available, (idx - recent) ..< idx] + return [0 ..< prefix, (available - older) ..< available, (idx - recent) ..< idx] .filter { !$0.isEmpty } - func view(_ array: MLXArray) -> MLXArray { - let parts = ranges.map { array[.ellipsis, $0, 0...] } - return parts.count == 1 ? parts[0] : concatenated(parts, axis: 2) + } + + /// Marks the storage rows inside the attention window, so a decode step can attend the + /// ring in place and leave the rewind reserve out. + private func attentionWindowMask(rows: Int) -> MLXArray? { + guard rows > maxCacheSize, let ranges = retainedRanges(tail: maxCacheSize) else { + return nil } - return (view(keys), view(values)) + var inWindow = [Bool](repeating: false, count: rows) + for range in ranges { + inWindow.replaceSubrange(range, with: repeatElement(true, count: range.count)) + } + return MLXArray(inWindow) } private func updateConcat(keys: MLXArray, values: MLXArray) -> (MLXArray, MLXArray) { @@ -923,6 +935,32 @@ public class RotatingKVCache: BaseKVCache, CustomDebugStringConvertible { return result } + /// Attends a single decode token to the ring in place when a rewind reserve is configured. + /// + /// ``update(keys:values:)`` returns a copy of the window without the reserve rows. This + /// masks the reserve rows instead, so a reserve costs no copy per token. Other writes and + /// caller-supplied masks take the ``update(keys:values:)`` path unchanged. + public func updateAndAttend( + queries: MLXArray, + keys: MLXArray, + values: MLXArray, + scale: Float, + mask: MLXFast.ScaledDotProductAttentionMaskMode + ) -> MLXArray { + guard rewindCapacity > 0, keys.dim(2) == 1, case .none = mask else { + let (cachedKeys, cachedValues) = update(keys: keys, values: values) + return MLXFast.scaledDotProductAttention( + queries: queries, keys: cachedKeys, values: cachedValues, scale: scale, + mask: mask) + } + wrappedFlag = wrapped + let (ringKeys, ringValues) = updateInPlace(keys: keys, values: values) + let windowMask = attentionWindowMask(rows: ringKeys.dim(2)) + return MLXFast.scaledDotProductAttention( + queries: queries, keys: ringKeys, values: ringValues, scale: scale, + mask: windowMask.map { .array($0) } ?? .none) + } + public override var state: [MLXArray] { get { guard let keys = self.keys, let values = self.values else { return [] } diff --git a/Tests/MLXLMTests/RotatingKVCacheRewindTests.swift b/Tests/MLXLMTests/RotatingKVCacheRewindTests.swift index dcf8b839ec..f69105ce95 100644 --- a/Tests/MLXLMTests/RotatingKVCacheRewindTests.swift +++ b/Tests/MLXLMTests/RotatingKVCacheRewindTests.swift @@ -414,4 +414,118 @@ final class RotatingKVCacheRewindTests: XCTestCase { XCTAssertEqual(actual.1.asArray(Float.self), expected.1.asArray(Float.self)) } } + + // MARK: - In-place decode attention + + private func keyRows(_ positions: Range) -> MLXArray { + let base = MLXArray(positions.map(Float.init)).reshaped(1, 1, positions.count, 1) + return sin(base * MLXArray([0.37, 0.71, 1.3, 2.9] as [Float]).reshaped(1, 1, 1, 4)) + } + + private func valueRows(_ positions: Range) -> MLXArray { + let base = MLXArray(positions.map(Float.init)).reshaped(1, 1, positions.count, 1) + return cos(base * MLXArray([0.23, 0.53, 1.1, 1.9] as [Float]).reshaped(1, 1, 1, 4)) + } + + private func query(_ count: Int) -> MLXArray { + MLXArray.ones([1, 1, count, 4]) * 1.5 + } + + private func viewAttention( + _ cache: RotatingKVCache, positions: Range, + mask: MLXFast.ScaledDotProductAttentionMaskMode = .none + ) -> MLXArray { + let (keys, values) = cache.update(keys: keyRows(positions), values: valueRows(positions)) + return MLXFast.scaledDotProductAttention( + queries: query(positions.count), keys: keys, values: values, scale: 1, mask: mask) + } + + private func inPlaceAttention( + _ cache: RotatingKVCache, positions: Range, + mask: MLXFast.ScaledDotProductAttentionMaskMode = .none + ) -> MLXArray { + attentionWithCacheUpdate( + queries: query(positions.count), keys: keyRows(positions), + values: valueRows(positions), cache: cache, scale: 1, mask: mask) + } + + func testDecodeAttendsTheRingInPlaceLikeAReserveFreeCache() { + for keep in [0, 2] { + for step in [1, 4, 256] { + for reserve in [1, 5, 16] { + let cache = RotatingKVCache( + maxSize: 8, keep: keep, step: step, rewindCapacity: reserve) + let reference = RotatingKVCache(maxSize: 8, keep: keep, step: step) + var offset = 0 + let script = + [1, 1, 9, 1, 3, 1, 1, 16, 1, 2, 1, 1] + Array(repeating: 1, count: 30) + for count in script { + let positions = offset ..< (offset + count) + func prefillMask(_ cache: RotatingKVCache) + -> MLXFast.ScaledDotProductAttentionMaskMode + { + count > 1 + ? cache.makeMask(n: count, windowSize: nil, returnArray: true) + : .none + } + let actual = inPlaceAttention( + cache, positions: positions, mask: prefillMask(cache)) + let expected = viewAttention( + reference, positions: positions, mask: prefillMask(reference)) + XCTAssertTrue( + allClose(actual, expected, atol: 1e-5).item(Bool.self), + "keep=\(keep), step=\(step), reserve=\(reserve), offset=\(offset)") + XCTAssertEqual(cache.offset, reference.offset) + offset += count + } + XCTAssertEqual(cache.maxTrimCount, reserve) + } + } + } + } + + func testInPlaceDecodeLeavesTheSameCacheAsTheViewPath() throws { + for keep in [0, 2] { + let inPlace = RotatingKVCache(maxSize: 8, keep: keep, step: 4, rewindCapacity: 5) + let view = RotatingKVCache(maxSize: 8, keep: keep, step: 4, rewindCapacity: 5) + var offset = 0 + let script: [(write: Int, trim: Int)] = + [(9, 0), (1, 0), (1, 0)] + Array(repeating: (1, 0), count: 12) + + [(1, 3), (1, 0), (1, 5), (1, 0), (1, 0), (4, 2), (1, 0)] + + Array(repeating: (1, 0), count: 20) + [(1, 4)] + for (write, trim) in script { + let positions = offset ..< (offset + write) + let mask = + write > 1 + ? inPlace.makeMask(n: write, windowSize: nil, returnArray: true) : .none + let actual = inPlaceAttention(inPlace, positions: positions, mask: mask) + let expected = viewAttention(view, positions: positions, mask: mask) + XCTAssertTrue( + allClose(actual, expected, atol: 1e-5).item(Bool.self), + "keep=\(keep), offset=\(offset)") + offset += write + XCTAssertEqual(inPlace.trim(trim), view.trim(trim)) + offset -= trim + XCTAssertEqual(inPlace.metaState, view.metaState) + XCTAssertEqual( + inPlace.state.map { $0.asArray(Float.self) }, + view.state.map { $0.asArray(Float.self) }) + XCTAssertEqual(inPlace.maxTrimCount, view.maxTrimCount) + } + } + } + + func testCallerMasksAndCachesWithoutReserveKeepTheViewPath() { + for reserve in [0, 4] { + let routed = RotatingKVCache(maxSize: 8, keep: 2, rewindCapacity: reserve) + let direct = RotatingKVCache(maxSize: 8, keep: 2, rewindCapacity: reserve) + for position in 0 ..< 30 { + let positions = position ..< (position + 1) + let mask = routed.makeMask(n: 1, windowSize: 4, returnArray: false) + let actual = inPlaceAttention(routed, positions: positions, mask: mask) + let expected = viewAttention(direct, positions: positions, mask: mask) + XCTAssertEqual(actual.asArray(Float.self), expected.asArray(Float.self)) + } + } + } }