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
399 changes: 186 additions & 213 deletions Libraries/MLXLMCommon/KVCache.swift

Large diffs are not rendered by default.

20 changes: 11 additions & 9 deletions Libraries/MLXLMCommon/KVCachePlan.swift
Original file line number Diff line number Diff line change
Expand Up @@ -219,17 +219,19 @@ package final class KVCacheStorage {
package func beginRound(maximumPositions: Int) -> KVCacheRound? {
precondition(!roundIsOpen, "a staged round is already open on this storage")

let leaves = KVCacheTree.leaves(in: cache)
guard leaves.count == cache.count, leaves.allSatisfy({ $0.path.count == 1 }) else {
return nil
}

var strategies = [any KVCacheRoundStrategy]()
strategies.reserveCapacity(leaves.count)
for leaf in leaves {
guard
strategies.reserveCapacity(cache.count)
for (slot, entry) in cache.enumerated() {
// Auxiliary entries are not leaves, but they append and trim like one.
if entry is any AuxiliaryKVCache {
Comment on lines +225 to +226

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

My thought is that this would be the least intrusive for the fake KVCaches that would appear but still be able to participate like a normal KVCache.

guard entry.isTrimmable(after: maximumPositions) else { return nil }
strategies.append(AppendOnlyRoundStrategy(slot: slot, live: entry))
continue
}
guard !(entry is CacheList),
let strategy = KVCacheRoundStrategyFactory.make(
for: leaf, slot: leaf.path[0], maximumPositions: maximumPositions)
for: KVCacheLeaf(path: [slot], cache: entry), slot: slot,
maximumPositions: maximumPositions)
else { return nil }
strategies.append(strategy)
}
Expand Down
4 changes: 2 additions & 2 deletions Libraries/MLXLMCommon/KVCacheTree.swift
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ enum KVCacheTree {
for index in cache.indices {
if let list = cache[index] as? CacheList {
list.rewriteLeaves(path: [index], using: transform)
} else {
} else if !(cache[index] is any AuxiliaryKVCache) {
let leaf = KVCacheLeaf(path: [index], cache: cache[index])
cache[index] = transform(leaf)
}
Expand Down Expand Up @@ -153,7 +153,7 @@ enum KVCacheTree {
for (index, child) in list.children.enumerated() {
appendLeaves(from: child, path: path + [index], to: &leaves)
}
} else {
} else if !(cache is any AuxiliaryKVCache) {
leaves.append(KVCacheLeaf(path: path, cache: cache))
}
}
Expand Down
100 changes: 100 additions & 0 deletions Libraries/MLXLMCommon/KVCacheTypeRegistry.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
// Copyright © 2026 Apple Inc.

import Foundation
import MLX

/// Register a cache type so ``loadPromptCacheSnapshot(url:)`` can restore it.
///
/// ``savePromptCache(url:cache:metadata:state:)`` registers the types it writes, so a file saved
/// and loaded in one process works without this call. Call it before loading in a new process.
/// Registering the same type again has no effect.
///
/// - Throws: if the type has no ``KVCache/serializedClassName``, or another type already uses it.
public func registerKVCacheType<T: KVCache>(_ type: T.Type) throws {
try KVCacheTypeRegistry.shared.register(type)
}

private let logger = MLXLogger(label: "KVCacheTypeRegistry")

/// Maps ``KVCache/serializedClassName`` to cache types, starting with the built-in caches.
final class KVCacheTypeRegistry: @unchecked Sendable {
private struct Entry {
let type: any KVCache.Type
/// True for an instance of `type`, or of a subclass that inherits its name.
let matches: (any KVCache) -> Bool
}

static let shared = KVCacheTypeRegistry()

private let lock = NSLock()
private var entries: [String: Entry] = [:]

private init() {
try! register(KVCacheSimple.self, aliases: ["KVCacheSimple"])
try! register(RotatingKVCache.self)
try! register(QuantizedKVCache.self)
try! register(VarianceNormalizedKVCache.self)
try! register(ChunkedKVCache.self)
try! register(ArraysCache.self)
try! register(MambaCache.self)
try! register(TurboQuantKVCache.self)
try! register(CacheList.self)
}

func register<T: KVCache>(_ type: T.Type, aliases: [String] = []) throws {
guard let name = type.serializedClassName else {
throw KVCacheError(message: "\(type) has no serializedClassName")
}
let entry = Entry(type: type, matches: { $0 is T })
try lock.withLock {
for name in [name] + aliases {
if let existing = entries[name] {
guard ObjectIdentifier(existing.type) == ObjectIdentifier(type) else {
throw KVCacheError(
message:
"Cache class name \(name) is already registered to \(existing.type)"
)
}
} else {
entries[name] = entry
}
}
}
}

func type(named name: String) -> (any KVCache.Type)? {
lock.withLock { entries[name]?.type }
}

/// The name to save `cache` under, registering its type if needed.
///
/// - Throws: if the cache, or a `CacheList` child, has no name or uses another type's name.
func serializedClassName(for cache: any KVCache) throws -> String {
let cacheType = Swift.type(of: cache)
guard let name = cacheType.serializedClassName else {
throw KVCacheError(
message: "\(cacheType) has no serializedClassName, so it cannot be saved")
}

if let entry = lock.withLock({ entries[name] }) {
guard entry.matches(cache) else {
throw KVCacheError(
message:
"\(cacheType) uses cache class name \(name), which belongs to \(entry.type)"
)
}
} else {
try register(cacheType)
logger.warning(
"Registered \(String(describing: cacheType)) while saving a prompt cache. Call registerKVCacheType(_:) before loading it in a new process."
)
}

if let list = cache as? CacheList {
for child in list.children {
_ = try serializedClassName(for: child)
}
}
return name
}
}
20 changes: 20 additions & 0 deletions Libraries/MLXLMCommon/TurboQuantKVCache.swift
Original file line number Diff line number Diff line change
Expand Up @@ -631,6 +631,26 @@ class MSECodec {
///
/// Both keys and values: Algorithm 1 (MSE at b bits, no QJL)
public class TurboQuantKVCache: BaseKVCache, SharedAttentionKVCache {
public override class var serializedClassName: String? { "TurboQuantKVCache" }

public override class func restore(
state: [MLXArray], metaState: [String]
) throws -> any KVCache {
guard metaState.count >= 5,
let bits = Int(metaState[1]),
let keyBits = Int(metaState[2]),
let valueBits = Int(metaState[3]),
let seed = UInt64(metaState[4])
else {
throw KVCacheError(
message: "Invalid TurboQuantKVCache metaState")
}
let cache = TurboQuantKVCache(
bits: bits, keyBits: keyBits, valueBits: valueBits, seed: seed)
cache.state = state
cache.metaState = metaState
return cache
}

public let bits: Int // Legacy: used when keyBits == valueBits
public let keyBits: Int // Bit-width for key compression (0 = raw FP16, no compression)
Expand Down
80 changes: 80 additions & 0 deletions Libraries/MLXLMCommon/VarianceNormalizedKVCache.swift
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,86 @@ extension KVCacheSimple {
public class VarianceNormalizedKVCache: BaseKVCache, KVCacheAttentionProtocol,
CustomDebugStringConvertible
{
public override class var serializedClassName: String? { "VarianceNormalizedKVCache" }

public override class func restore(
state: [MLXArray], metaState: [String]
) throws -> any KVCache {
guard metaState.count == 7 || metaState.count == 10 else {
throw KVCacheError(
message:
"Corrupt prompt cache: VarianceNormalizedKVCache metadata must contain 7 legacy or 10 versioned values."
)
}
let values = try promptCacheIntegers(
Array(metaState.prefix(7)), className: "VarianceNormalizedKVCache")
let tileSize = values[0]
let offset = values[1]
let keyBits = values[2]
let valueBits = values[3]
let sinkhornIterations = values[4]
let tileCount = values[5]
let tailLength = values[6]
guard
(try? VarianceNormalizedKVCacheConfiguration(
keyBits: keyBits,
valueBits: valueBits,
tileSize: tileSize,
sinkhornIterations: sinkhornIterations)) != nil,
offset >= 0,
tileCount >= 0,
(0 ..< tileSize).contains(tailLength),
metaState.count == 7
|| (Int(metaState[7]) == VarianceNormalizedKVCache.metadataVersion
&& (metaState[8] == "none"
|| varianceNormalizedDType(named: metaState[8])
.map(isSupportedVarianceNormalizedDType) == true)
&& (metaState[9] == "none"
|| varianceNormalizedDType(named: metaState[9])
.map(isSupportedVarianceNormalizedDType) == true))
else {
throw KVCacheError(
message: "Corrupt prompt cache: invalid VarianceNormalizedKVCache metadata."
)
}
let (tiledLength, tileLengthOverflow) = tileCount.multipliedReportingOverflow(
by: tileSize)
let (representedLength, offsetOverflow) = tiledLength.addingReportingOverflow(tailLength)
let tailStateCount =
tailLength > 0 ? VarianceNormalizedKVCache.tailStateCount : 0
let tileStateCount = state.count - min(state.count, tailStateCount)
let hasValidTileStateCount =
if tileCount == 0 {
tileStateCount == 0
} else {
tileStateCount.isMultiple(of: tileCount)
&& [
VarianceNormalizedKVCache.compactTileStateCount,
VarianceNormalizedKVCache.legacyTileStateCount,
].contains(tileStateCount / tileCount)
}
guard
!tileLengthOverflow,
!offsetOverflow,
offset == representedLength,
state.count >= tailStateCount,
hasValidTileStateCount,
state.allSatisfy({ $0.ndim == 4 })
else {
throw KVCacheError(
message: "Corrupt prompt cache: invalid VarianceNormalizedKVCache state."
)
}
let cache = VarianceNormalizedKVCache(
tileSize: tileSize,
keyBits: keyBits,
valueBits: valueBits,
sinkhornIterations: sinkhornIterations)
cache.metaState = metaState
cache.state = state
return cache
}

static let compactTileStateCount = 8
static let legacyTileStateCount = 10
static let tailStateCount = 2
Expand Down
5 changes: 5 additions & 0 deletions Libraries/MLXScriptedLM/Documentation.docc/Documentation.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,11 @@ let prompt = try tokenizer.applyChatTemplate(
- ``ScriptedTemplateMessage``
- ``ScriptedTemplateError``

### Model Support

- ``TranscriptKVCache``
- ``TranscriptKVCacheError``

### Vocabulary

- ``VocabularyBuilder``
Expand Down
106 changes: 106 additions & 0 deletions Libraries/MLXScriptedLM/Model/TranscriptKVCache.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
// Copyright © 2026 Apple Inc.

import Foundation
import MLX
import MLXLMCommon

/// The tokens a model has processed, kept as an entry in its KV cache.
///
/// A scripted model appends this entry to its inner model's caches and keeps it in step with
/// them. Generation trims, rewinds, copies, and saves the whole cache together, so `tokens`
/// always matches what the inner caches hold, across speculative rejections, prompt-cache
/// reuse, and `ChatSession` rebuilds.
///
/// It is an `AuxiliaryKVCache`, so capacity and compression settings ignore it, and it never
/// stores keys or values.
///
/// Note: this KVCache should not be used for any production use.
/// Its performance is O(n^2) or worse and is strictly meant as
/// a mechanism that a `ScriptedModel` could use.
public final class TranscriptKVCache: BaseKVCache, AuxiliaryKVCache {

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is the new KVCache to be used by ScriptedModels in the next PR.


public override static var serializedClassName: String? { "MLXScriptedLM.TranscriptKVCache" }

/// Registers the type for prompt cache files once, on first use.
private static let registration: Void = {
try! registerKVCacheType(TranscriptKVCache.self)
}()

/// Register the type for KVCache save and restore.
/// This will happen automatically if a cache instance is
/// created.
public static func register() {
_ = Self.registration
}

public private(set) var tokens: [Int]

public init(tokens: [Int] = []) {
_ = Self.registration
self.tokens = tokens
super.init()
offset = tokens.count
}

/// Records tokens the inner model has just processed.
public func append(_ newTokens: [Int]) {
tokens += newTokens
offset = tokens.count
}

public override func update(keys: MLXArray, values: MLXArray) -> (MLXArray, MLXArray) {
preconditionFailure("TranscriptKVCache records tokens; it does not store keys and values")
}

public override var isTrimmable: Bool { true }

@discardableResult
public override func trim(_ n: Int) -> Int {
let trimmed = Swift.min(Swift.max(n, 0), tokens.count)
tokens.removeLast(trimmed)
offset = tokens.count
return trimmed
}

public override func copy() -> any KVCache {
TranscriptKVCache(tokens: tokens)
}

// MARK: - Prompt cache files

public override var state: [MLXArray] {
get { tokens.isEmpty ? [] : [MLXArray(tokens.map(Int32.init))] }
set {
tokens = newValue.first?.asArray(Int32.self).map(Int.init) ?? []
offset = tokens.count
}
}

public override var metaState: [String] {
get { [String(tokens.count)] }
set {}
}

public override static func restore(
state: [MLXArray], metaState: [String]
) throws -> any KVCache {
let cache = TranscriptKVCache()
cache.state = state
guard metaState == [String(cache.tokens.count)] else {
throw TranscriptKVCacheError.countMismatch(
stored: metaState.first ?? "", restored: cache.tokens.count)
}
return cache
}
}

public enum TranscriptKVCacheError: LocalizedError, Equatable {
case countMismatch(stored: String, restored: Int)

public var errorDescription: String? {
switch self {
case .countMismatch(let stored, let restored):
"TranscriptKVCache file says \(stored) tokens but holds \(restored)"
}
}
}
5 changes: 4 additions & 1 deletion Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,10 @@ let package = Package(
// Scripted tokenizers and models
.target(
name: "MLXScriptedLM",
dependencies: ["MLXLMCommon"],
dependencies: [
"MLXLMCommon",
.product(name: "MLX", package: "mlx-swift"),
],
path: "Libraries/MLXScriptedLM",
exclude: ["README.md"]
),
Expand Down
Loading
Loading