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
148 changes: 102 additions & 46 deletions Libraries/MLXLMCommon/KVCache.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1156,6 +1156,28 @@ public class ChunkedKVCache: KVCacheSimple {
return new
}

/// The keys and values of the valid tokens: buffer rows
/// `0 ..< offset - startPosition`. The setter keeps `startPosition` and
/// sets `offset` to `startPosition` plus the token count, so the offset
/// is right in either order of `state` and `metaState`. mlx-lm cache.py
/// keeps `offset` and `start_position` in the state, so its load also
/// gives the saved offset.
public override var state: [MLXArray] {
get {
guard let keys = self.keys, let values = self.values else { return [] }
let end = offset - startPosition
return [keys[.ellipsis, ..<end, 0...], values[.ellipsis, ..<end, 0...]]
}
set {
guard newValue.count == 2 else {
fatalError("ChunkedKVCache state must have exactly 2 arrays (keys, values)")
}
self.keys = newValue[0]
self.values = newValue[1]
self.offset = startPosition + newValue[0].dim(2)
}
}

public override var metaState: [String] {
get {
let chunkSizeStr = chunkSize?.description ?? "None"
Expand All @@ -1170,7 +1192,10 @@ public class ChunkedKVCache: KVCacheSimple {
} else {
self.chunkSize = Int(newValue[0])
}
// Keep the count of valid tokens when the start position moves.
let valid = offset - startPosition
self.startPosition = Int(newValue[1]) ?? 0
self.offset = startPosition + valid
}
}
}
Expand Down Expand Up @@ -1321,10 +1346,17 @@ public class ArraysCache: BaseKVCache {

open func extract(_ idx: Int) -> ArraysCache {
let extracted = ArraysCache(size: cache.count)
extracted.cache = cache.map { $0?[idx ..< (idx + 1)] }
extractSlots(idx, to: extracted)
return extracted
}

/// Gives `other` batch row `idx` of every slot, also of the empty slots,
/// so that each state keeps its position. mlx-lm cache.py
/// `ArraysCache.extract` does the same.
internal func extractSlots(_ idx: Int, to other: ArraysCache) {
other.cache = cache.map { $0?[idx ..< (idx + 1)] }
}

public func prepare(lengths: [Int]? = nil) {
self.lengths = lengths.map { MLXArray($0.map { Int32($0) }) }
}
Expand Down Expand Up @@ -1441,8 +1473,9 @@ public class MambaCache: ArraysCache {
}

public override func extract(_ idx: Int) -> ArraysCache {
// Do not go through `state`: it drops the empty slots.
let extracted = MambaCache()
extracted.state = state.map { $0[idx ..< (idx + 1)] }
extractSlots(idx, to: extracted)
return extracted
}
}
Expand Down Expand Up @@ -1536,7 +1569,9 @@ public class CacheList: BaseKVCache {

/// Reconstruct a CacheList from flattened state + metaState, like Python's from_state()
internal static func fromState(state: [MLXArray], metaState: [String]) throws -> CacheList {
guard let childCount = metaState.first.flatMap({ Int($0) }) else {
guard let childCount = metaState.first.flatMap({ Int($0) }),
childCount >= 0, childCount <= (metaState.count - 1) / 3
else {
throw KVCacheError(message: "CacheList metaState missing child count")
}

Expand All @@ -1549,25 +1584,32 @@ public class CacheList: BaseKVCache {
throw KVCacheError(message: "CacheList metaState truncated")
}
let className = metaState[metaIdx]
guard let stateCount = Int(metaState[metaIdx + 1]) else {
guard let stateCount = Int(metaState[metaIdx + 1]),
stateCount >= 0, stateCount <= state.count - stateIdx
else {
throw KVCacheError(message: "CacheList: invalid stateCount for child")
}
guard let metaCount = Int(metaState[metaIdx + 2]) else {
guard let metaCount = Int(metaState[metaIdx + 2]),
metaCount >= 0, metaCount <= metaState.count - metaIdx - 3
else {
throw KVCacheError(message: "CacheList: invalid metaStateCount for child")
}
metaIdx += 3

let childMeta = Array(metaState[metaIdx ..< min(metaIdx + metaCount, metaState.count)])
let childMeta = Array(metaState[metaIdx ..< (metaIdx + metaCount)])
metaIdx += metaCount

let childState = Array(state[stateIdx ..< min(stateIdx + stateCount, state.count)])
let childState = Array(state[stateIdx ..< (stateIdx + stateCount)])
stateIdx += stateCount

let child = try restoreCacheFromMetaState(
className: className, state: childState, metaState: childMeta)
children.append(child)
}

guard metaIdx == metaState.count, stateIdx == state.count else {
throw KVCacheError(message: "CacheList has trailing state or metadata")
}
return CacheList(caches: children)
}
}
Expand Down Expand Up @@ -1650,11 +1692,8 @@ public func loadPromptCache(
) throws -> ([KVCache], [String: String]) {
let (arrays, metadata) = try loadArraysAndMetadata(url: url)

// Unflatten arrays using tree_unflatten compatible logic
let cacheData = unflattenArrays(arrays)

// Unflatten metadata using tree_unflatten compatible logic
let unflattenedMetadata = unflattenMetadata(metadata)
let unflattenedMetadata = try unflattenMetadata(metadata)

// Extract cache_info, user_metadata, and cache_classes from unflattened structure
// Structure: [cache_info, user_metadata, cache_classes]
Expand All @@ -1665,6 +1704,8 @@ public func loadPromptCache(
let cacheInfo = unflattenedMetadata[0] as? [[String]] ?? []
let userMetadata = unflattenedMetadata[1] as? [String: String] ?? [:]
let cacheClasses = unflattenedMetadata[2] as? [String] ?? []
// Class metadata records layers even when their state has no arrays.
let cacheData = try unflattenArrays(arrays, cacheCount: cacheClasses.count)

guard cacheData.count == cacheInfo.count && cacheData.count == cacheClasses.count else {
throw KVCacheError(message: "Mismatch in cache counts")
Expand Down Expand Up @@ -1693,10 +1734,11 @@ private func restoreCacheFromMetaState(
state: [MLXArray],
metaState: [String]
) throws -> KVCache {
try validatePromptCacheState(className: className, state: state, metaState: metaState)
switch className {
case "KVCache", "KVCacheSimple":
let cache = KVCacheSimple()
cache.state = state
if !state.isEmpty { cache.state = state }
cache.metaState = metaState
return cache

Expand All @@ -1715,19 +1757,19 @@ private func restoreCacheFromMetaState(
message: "Failed to parse RotatingKVCache maxSize from: \(metaState[1])")
}
let cache = RotatingKVCache(maxSize: maxSize)
cache.state = state
if !state.isEmpty { cache.state = state }
cache.metaState = metaState
return cache

case "QuantizedKVCache":
let cache = QuantizedKVCache()
cache.state = state
if !state.isEmpty { cache.state = state }
cache.metaState = metaState
return cache

case "ChunkedKVCache":
let cache = ChunkedKVCache()
cache.state = state
if !state.isEmpty { cache.state = state }
cache.metaState = metaState
return cache

Expand All @@ -1750,35 +1792,41 @@ private func restoreCacheFromMetaState(
}

/// Unflatten arrays from tree_flatten format (e.g., "0.1", "1.0") to nested structure
private func unflattenArrays(_ flatArrays: [String: MLXArray]) -> [[MLXArray]] {
private func unflattenArrays(_ flatArrays: [String: MLXArray], cacheCount: Int) throws
-> [[MLXArray]]
{
var arrayMap: [Int: [Int: MLXArray]] = [:]

// Parse all keys and organize by indices
for (key, array) in flatArrays {
let components = key.split(separator: ".")
if components.count >= 2,
// Legacy files may contain unrelated named arrays; retain that behavior.
guard components.count >= 2,
let i = Int(components[0]),
let j = Int(components[1])
{
if arrayMap[i] == nil {
arrayMap[i] = [:]
}
arrayMap[i]![j] = array
else { continue }
guard
i >= 0, i < cacheCount, j >= 0, j < flatArrays.count,
arrayMap[i]?[j] == nil
else {
throw KVCacheError(message: "Invalid cache array index: \(key)")
}
if arrayMap[i] == nil {
arrayMap[i] = [:]
}
arrayMap[i]![j] = array
}

// Convert to ordered array structure
var result: [[MLXArray]] = []
let maxI = arrayMap.keys.max() ?? -1

for i in 0 ... maxI {
for i in 0 ..< cacheCount {
if let innerMap = arrayMap[i] {
let maxJ = innerMap.keys.max() ?? -1
var innerArray: [MLXArray] = []
for j in 0 ... maxJ {
if let array = innerMap[j] {
innerArray.append(array)
for j in 0 ..< innerMap.count {
guard let array = innerMap[j] else {
throw KVCacheError(message: "Missing cache array index")
}
innerArray.append(array)
}
result.append(innerArray)
} else {
Expand All @@ -1790,7 +1838,7 @@ private func unflattenArrays(_ flatArrays: [String: MLXArray]) -> [[MLXArray]] {
}

/// Unflatten metadata from tree_flatten format to nested structure
private func unflattenMetadata(_ flatMetadata: [String: String]) -> [Any] {
private func unflattenMetadata(_ flatMetadata: [String: String]) throws -> [Any] {
var cacheInfo: [[String]] = []
var userMetadata: [String: String] = [:]
var cacheClasses: [String] = []
Expand All @@ -1800,33 +1848,41 @@ private func unflattenMetadata(_ flatMetadata: [String: String]) -> [Any] {

if components.count >= 3 && components[0] == "0" {
// Cache info: "0.i.j" format
if let i = Int(components[1]), let j = Int(components[2]) {
// Ensure cacheInfo is large enough
while cacheInfo.count <= i {
cacheInfo.append([])
}
// Ensure inner array is large enough
while cacheInfo[i].count <= j {
cacheInfo[i].append("")
}
cacheInfo[i][j] = value
guard components.count == 3,
let i = Int(components[1]), let j = Int(components[2]),
i >= 0, i < flatMetadata.count, j >= 0, j < flatMetadata.count
else {
throw KVCacheError(message: "Invalid cache metadata index: \(key)")
}
// Ensure cacheInfo is large enough
while cacheInfo.count <= i {
cacheInfo.append([])
}
// Ensure inner array is large enough
while cacheInfo[i].count <= j {
cacheInfo[i].append("")
}
cacheInfo[i][j] = value
} else if components.count >= 2 && components[0] == "1" {
// User metadata: "1.key" format
let metaKey = components.dropFirst().joined(separator: ".")
userMetadata[metaKey] = value
} else if components.count >= 2 && components[0] == "2" {
// Cache classes: "2.i" format
if let i = Int(components[1]) {
// Ensure cacheClasses is large enough
while cacheClasses.count <= i {
cacheClasses.append("")
}
cacheClasses[i] = value
guard components.count == 2, let i = Int(components[1]),
i >= 0, i < flatMetadata.count
else {
throw KVCacheError(message: "Invalid cache class index: \(key)")
}
// Ensure cacheClasses is large enough
while cacheClasses.count <= i {
cacheClasses.append("")
}
cacheClasses[i] = value
}
}

while cacheInfo.count < cacheClasses.count { cacheInfo.append([]) }
return [cacheInfo, userMetadata, cacheClasses]
}

Expand Down
93 changes: 93 additions & 0 deletions Libraries/MLXLMCommon/PromptCacheValidation.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
import MLX

/// Validate file input before calling nonthrowing cache setters. Empty state
/// means an unpopulated cache, not a missing keys/values pair.
internal func validatePromptCacheState(
className: String, state: [MLXArray], metaState: [String]
) throws {
func reject() throws {
throw KVCacheError(message: "Invalid \(className) state or metadata")
}
func integers(_ count: Int) -> [Int]? {
guard metaState.count == count else { return nil }
let values = metaState.compactMap(Int.init)
return values.count == count ? values : nil
}
switch className {
case "KVCache", "KVCacheSimple", "ChunkedKVCache", "RotatingKVCache":
guard state.isEmpty || (state.count == 2 && state.allSatisfy { $0.ndim == 4 }) else {
try reject()
return
}
if state.count == 2 {
guard state[0].shape.prefix(3) == state[1].shape.prefix(3) else {
try reject()
return
}
}
switch className {
case "ChunkedKVCache":
guard metaState.count == 2, let start = Int(metaState[1]), start >= 0,
metaState[0] == "None" || Int(metaState[0]).map({ $0 >= 0 }) == true,
start <= Int.max - (state.first?.dim(2) ?? 0)
else {
try reject()
return
}
case "RotatingKVCache":
guard let values = integers(5), values[0] >= 0, values[1] > values[0],
values[2] > 0, values[3] >= 0, values[4] >= 0,
values[4] <= (state.first?.dim(2) ?? 0),
!state.isEmpty || values[3] == 0
else {
try reject()
return
}
default:
guard metaState.isEmpty || metaState == [""] else {
try reject()
return
}
}
case "QuantizedKVCache":
guard let values = integers(4), values[0] > 0, values[1] >= 0,
values[2] > 0, values[3] > 0,
state.isEmpty
|| ((state.count == 4 || state.count == 6)
&& state.allSatisfy { $0.ndim == 4 && $0.dim(2) >= values[1] }),
!state.isEmpty || values[1] == 0
else {
try reject()
return
}
case "ArraysCache", "MambaCache":
// Preserve the documented legacy compact-state format.
if metaState.isEmpty || metaState == [""] { return }
guard (2 ... 3).contains(metaState.count), let slots = Int(metaState[0]), slots >= 0
else {
try reject()
return
}
let parts =
metaState[1].isEmpty
? [] : metaState[1].split(separator: ",", omittingEmptySubsequences: false)
let present = parts.compactMap { Int($0) }
guard present.count == parts.count, present.count == state.count,
Set(present).count == present.count, present.allSatisfy({ $0 >= 0 && $0 < slots })
else {
try reject()
return
}
if metaState.count == 3 && !metaState[2].isEmpty {
let padding = metaState[2].split(separator: ",", omittingEmptySubsequences: false)
// advance() subtracts consumed tokens, so valid padding can be negative.
guard padding.allSatisfy({ Int($0) != nil })
else {
try reject()
return
}
}
default:
break // CacheList validates its own flattened child inventory.
}
}
Loading
Loading