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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 53 additions & 15 deletions Libraries/MLXLMCommon/KVCache.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down Expand Up @@ -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<Int>]? {
guard let keys else { return nil }

let available = wrapped ? keys.dim(2) : idx
let prefix = Swift.min(keep, available)
Expand All @@ -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) {
Expand Down Expand Up @@ -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 [] }
Expand Down
114 changes: 114 additions & 0 deletions Tests/MLXLMTests/RotatingKVCacheRewindTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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<Int>) -> 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<Int>) -> 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<Int>,
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<Int>,
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))
}
}
}
}
Loading