From 0661d9b43938f463d8252fe941c3bfd8e117ac44 Mon Sep 17 00:00:00 2001 From: David Koski Date: Fri, 9 Oct 2026 11:20:04 -0700 Subject: [PATCH 1/5] Support for scripted models (tests) - add TranscriptKVCache (tests) - add ability to extend KVCache hierarchy --- Libraries/MLXLMCommon/KVCache.swift | 27 +++- Libraries/MLXLMCommon/KVCachePlan.swift | 20 +-- Libraries/MLXLMCommon/KVCacheTree.swift | 4 +- .../MLXLMCommon/PromptCacheTypeRegistry.swift | 62 ++++++++ .../Documentation.docc/Documentation.md | 5 + .../Model/TranscriptKVCache.swift | 93 ++++++++++++ Package.swift | 5 +- .../PromptCacheTypeRegistryTests.swift | 137 ++++++++++++++++++ .../ScriptedLM/TranscriptKVCacheTests.swift | 133 +++++++++++++++++ 9 files changed, 473 insertions(+), 13 deletions(-) create mode 100644 Libraries/MLXLMCommon/PromptCacheTypeRegistry.swift create mode 100644 Libraries/MLXScriptedLM/Model/TranscriptKVCache.swift create mode 100644 Tests/MLXLMTests/PromptCacheTypeRegistryTests.swift create mode 100644 Tests/MLXLMTests/ScriptedLM/TranscriptKVCacheTests.swift diff --git a/Libraries/MLXLMCommon/KVCache.swift b/Libraries/MLXLMCommon/KVCache.swift index ac0eacfbc9..815ab8aa2f 100644 --- a/Libraries/MLXLMCommon/KVCache.swift +++ b/Libraries/MLXLMCommon/KVCache.swift @@ -209,9 +209,22 @@ public protocol KVCacheAttentionProtocol: KVCache { ) -> MLXArray } +/// A cache entry that holds no attention state, such as a record of the tokens processed so far. +/// +/// Cache policy skips these entries: capacity and compression settings, offset alignment +/// checks, and ``KVCacheStatus`` layers ignore them. Generation still trims, copies, and saves +/// them with the other entries, so an auxiliary cache must be trimmable to keep pace. Make it +/// ``PromptCacheRestorable`` to restore it from a prompt cache file. +/// +/// Staged speculative rounds (MTP) write through an auxiliary entry and trim it back to the +/// accepted positions, so it must stay trimmable after the round's width. +public protocol AuxiliaryKVCache: KVCache {} + /// Base cache implementation providing default behaviors open class BaseKVCache: KVCache { public var offset: Int = 0 + + public init() {} public var maxSize: Int? { nil } open var evictedTokenCount: Int { 0 } @@ -1775,6 +1788,9 @@ public class CacheList: BaseKVCache { list.rewriteLeaves(path: childPath, using: transform) return list } + if child is any AuxiliaryKVCache { + return child + } let leaf = KVCacheLeaf(path: childPath, cache: child) return transform(leaf) } @@ -1891,6 +1907,9 @@ struct KVCacheError: Error, LocalizedError { /// Map a cache instance to its Python-compatible class name for serialization. private func cacheClassName(_ cache: KVCache) -> String { + if let custom = cache as? any PromptCacheRestorable { + return type(of: custom).promptCacheClassName + } switch cache { case is ChunkedKVCache: return "ChunkedKVCache" case is MambaCache: return "MambaCache" @@ -2380,7 +2399,13 @@ private func restoreCacheFromMetaState( return try CacheList.fromState(state: state, metaState: metaState) default: - throw KVCacheError(message: "Unknown cache class: \(className)") + if let type = PromptCacheTypeRegistry.shared.type(named: className) { + return try type.restore(state: state, metaState: metaState) + } + throw KVCacheError( + message: + "Unknown cache class: \(className). Custom cache types must be registered with registerPromptCacheType(_:)." + ) } } diff --git a/Libraries/MLXLMCommon/KVCachePlan.swift b/Libraries/MLXLMCommon/KVCachePlan.swift index d2e9c2e38c..6b935a2525 100644 --- a/Libraries/MLXLMCommon/KVCachePlan.swift +++ b/Libraries/MLXLMCommon/KVCachePlan.swift @@ -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 { + 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) } diff --git a/Libraries/MLXLMCommon/KVCacheTree.swift b/Libraries/MLXLMCommon/KVCacheTree.swift index 2212a2db40..87a4cb298c 100644 --- a/Libraries/MLXLMCommon/KVCacheTree.swift +++ b/Libraries/MLXLMCommon/KVCacheTree.swift @@ -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) } @@ -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)) } } diff --git a/Libraries/MLXLMCommon/PromptCacheTypeRegistry.swift b/Libraries/MLXLMCommon/PromptCacheTypeRegistry.swift new file mode 100644 index 0000000000..331cdb35d3 --- /dev/null +++ b/Libraries/MLXLMCommon/PromptCacheTypeRegistry.swift @@ -0,0 +1,62 @@ +// Copyright © 2026 Apple Inc. + +import Foundation +import MLX + +/// A cache type defined outside MLXLMCommon that prompt cache files can save and restore. +/// +/// ``savePromptCache(url:cache:metadata:state:)`` writes ``promptCacheClassName`` with the +/// cache's `state` and `metaState`. To load the file, register the type first with +/// ``registerPromptCacheType(_:)``. +public protocol PromptCacheRestorable: KVCache { + /// The class name written to prompt cache files. It must not be a built-in name such as + /// `KVCacheSimple`, and it should be unique, for example by including a module prefix. + static var promptCacheClassName: String { get } + + /// Rebuild a cache from the `state` and `metaState` it saved. + static func restore(state: [MLXArray], metaState: [String]) throws -> any KVCache +} + +/// Register a cache type so ``loadPromptCacheSnapshot(url:)`` can restore it. +/// +/// Registering the same type again has no effect. +/// +/// - Throws: if the name is a built-in cache name, or another type already uses it. +public func registerPromptCacheType(_ type: any PromptCacheRestorable.Type) throws { + try PromptCacheTypeRegistry.shared.register(type) +} + +final class PromptCacheTypeRegistry: @unchecked Sendable { + static let shared = PromptCacheTypeRegistry() + + /// Names that `restoreCacheFromMetaState` handles itself. + static let builtInNames: Set = [ + "KVCache", "KVCacheSimple", "RotatingKVCache", "QuantizedKVCache", + "VarianceNormalizedKVCache", "ChunkedKVCache", "MambaCache", "ArraysCache", + "TurboQuantKVCache", "CacheList", + ] + + private let lock = NSLock() + private var types: [String: any PromptCacheRestorable.Type] = [:] + + func register(_ type: any PromptCacheRestorable.Type) throws { + let name = type.promptCacheClassName + guard !Self.builtInNames.contains(name) else { + throw KVCacheError(message: "\(name) is a built-in prompt cache class name") + } + try lock.withLock { + if let existing = types[name] { + guard ObjectIdentifier(existing) == ObjectIdentifier(type) else { + throw KVCacheError( + message: "Prompt cache class name \(name) is already registered") + } + return + } + types[name] = type + } + } + + func type(named name: String) -> (any PromptCacheRestorable.Type)? { + lock.withLock { types[name] } + } +} diff --git a/Libraries/MLXScriptedLM/Documentation.docc/Documentation.md b/Libraries/MLXScriptedLM/Documentation.docc/Documentation.md index dbe7e04603..8ea3922d2b 100644 --- a/Libraries/MLXScriptedLM/Documentation.docc/Documentation.md +++ b/Libraries/MLXScriptedLM/Documentation.docc/Documentation.md @@ -44,6 +44,11 @@ let prompt = try tokenizer.applyChatTemplate( - ``ScriptedTemplateMessage`` - ``ScriptedTemplateError`` +### Model Support + +- ``TranscriptKVCache`` +- ``TranscriptKVCacheError`` + ### Vocabulary - ``VocabularyBuilder`` diff --git a/Libraries/MLXScriptedLM/Model/TranscriptKVCache.swift b/Libraries/MLXScriptedLM/Model/TranscriptKVCache.swift new file mode 100644 index 0000000000..a3bd95d945 --- /dev/null +++ b/Libraries/MLXScriptedLM/Model/TranscriptKVCache.swift @@ -0,0 +1,93 @@ +// 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. +public final class TranscriptKVCache: BaseKVCache, AuxiliaryKVCache, PromptCacheRestorable { + + public static var promptCacheClassName: String { "MLXScriptedLM.TranscriptKVCache" } + + /// Registers the type for prompt cache files once, on first use. + private static let registration: Void = { + try! registerPromptCacheType(TranscriptKVCache.self) + }() + + 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 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)" + } + } +} diff --git a/Package.swift b/Package.swift index 67f7941d99..7985a57294 100644 --- a/Package.swift +++ b/Package.swift @@ -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"] ), diff --git a/Tests/MLXLMTests/PromptCacheTypeRegistryTests.swift b/Tests/MLXLMTests/PromptCacheTypeRegistryTests.swift new file mode 100644 index 0000000000..b5659c6106 --- /dev/null +++ b/Tests/MLXLMTests/PromptCacheTypeRegistryTests.swift @@ -0,0 +1,137 @@ +// Copyright © 2026 Apple Inc. + +import Foundation +import MLX +import Testing + +@testable import MLXLMCommon + +/// Stores token ids, standing in for a cache type defined outside MLXLMCommon. +private final class TokenListCache: BaseKVCache, PromptCacheRestorable { + static var promptCacheClassName: String { "Tests.TokenListCache" } + + var tokens: [Int32] + + init(tokens: [Int32]) { + self.tokens = tokens + super.init() + offset = tokens.count + } + + override var state: [MLXArray] { + get { [MLXArray(tokens)] } + set { tokens = newValue.first?.asArray(Int32.self) ?? [] } + } + + override var metaState: [String] { + get { [String(offset)] } + set { offset = newValue.first.flatMap(Int.init) ?? tokens.count } + } + + override var isTrimmable: Bool { true } + + override func copy() -> any KVCache { TokenListCache(tokens: tokens) } + + static func restore(state: [MLXArray], metaState: [String]) throws -> any KVCache { + let cache = TokenListCache(tokens: state.first?.asArray(Int32.self) ?? []) + cache.metaState = metaState + return cache + } +} + +private final class OtherTokenListCache: BaseKVCache, PromptCacheRestorable { + static var promptCacheClassName: String { "Tests.TokenListCache" } + override func copy() -> any KVCache { OtherTokenListCache() } + static func restore(state: [MLXArray], metaState: [String]) throws -> any KVCache { + OtherTokenListCache() + } +} + +private final class BuiltInNameCache: BaseKVCache, PromptCacheRestorable { + static var promptCacheClassName: String { "KVCacheSimple" } + override func copy() -> any KVCache { BuiltInNameCache() } + static func restore(state: [MLXArray], metaState: [String]) throws -> any KVCache { + BuiltInNameCache() + } +} + +private final class UnregisteredCache: BaseKVCache, PromptCacheRestorable { + static var promptCacheClassName: String { "Tests.UnregisteredCache" } + override func copy() -> any KVCache { UnregisteredCache() } + static func restore(state: [MLXArray], metaState: [String]) throws -> any KVCache { + UnregisteredCache() + } +} + +struct PromptCacheTypeRegistryTests { + + static func temporaryURL() -> URL { + FileManager.default.temporaryDirectory + .appending(component: "prompt-cache-\(UUID().uuidString).safetensors") + } + + @Test func `a registered custom cache saves and restores with built-in caches`() throws { + try registerPromptCacheType(TokenListCache.self) + + let simple = KVCacheSimple() + _ = simple.update(keys: MLXArray.ones([1, 2, 3, 8]), values: MLXArray.ones([1, 2, 3, 8])) + let custom = TokenListCache(tokens: [7, 8, 9]) + + let url = Self.temporaryURL() + defer { try? FileManager.default.removeItem(at: url) } + try savePromptCache(url: url, cache: [simple, custom]) + + let restored = try loadPromptCacheSnapshot(url: url).cache + #expect(restored.count == 2) + #expect(restored[0] is KVCacheSimple) + #expect(restored[0].offset == 3) + let tokens = try #require(restored[1] as? TokenListCache) + #expect(tokens.tokens == [7, 8, 9]) + #expect(tokens.offset == 3) + } + + @Test func `a custom cache inside a CacheList round-trips`() throws { + try registerPromptCacheType(TokenListCache.self) + + let url = Self.temporaryURL() + defer { try? FileManager.default.removeItem(at: url) } + try savePromptCache( + url: url, cache: [CacheList(KVCacheSimple(), TokenListCache(tokens: [1, 2]))]) + + let list = try #require(try loadPromptCacheSnapshot(url: url).cache.first as? CacheList) + let tokens = try #require(list.children.last as? TokenListCache) + #expect(tokens.tokens == [1, 2]) + } + + @Test func `registering the same type twice is allowed`() throws { + try registerPromptCacheType(TokenListCache.self) + try registerPromptCacheType(TokenListCache.self) + } + + @Test func `another type cannot take a registered name`() throws { + try registerPromptCacheType(TokenListCache.self) + #expect(throws: (any Error).self) { + try registerPromptCacheType(OtherTokenListCache.self) + } + } + + @Test func `built-in names are reserved`() { + #expect(throws: (any Error).self) { + try registerPromptCacheType(BuiltInNameCache.self) + } + } + + @Test func `an unregistered custom cache saves under its name but does not load`() throws { + let url = Self.temporaryURL() + defer { try? FileManager.default.removeItem(at: url) } + try savePromptCache(url: url, cache: [UnregisteredCache()]) + + do { + _ = try loadPromptCacheSnapshot(url: url) + Issue.record("expected an unknown cache class error") + } catch { + #expect(error.localizedDescription.contains("Tests.UnregisteredCache")) + #expect(error.localizedDescription.contains("registerPromptCacheType")) + } + } +} diff --git a/Tests/MLXLMTests/ScriptedLM/TranscriptKVCacheTests.swift b/Tests/MLXLMTests/ScriptedLM/TranscriptKVCacheTests.swift new file mode 100644 index 0000000000..2e153ebfc3 --- /dev/null +++ b/Tests/MLXLMTests/ScriptedLM/TranscriptKVCacheTests.swift @@ -0,0 +1,133 @@ +// Copyright © 2026 Apple Inc. + +import Foundation +import MLX +import MLXLMCommon +import MLXScriptedLM +import Testing + +/// A custom cache without ``AuxiliaryKVCache``: cache policy treats it as an attention layer. +private final class PlainCustomCache: BaseKVCache { + override var isTrimmable: Bool { true } + override func copy() -> any KVCache { PlainCustomCache() } +} + +struct TranscriptKVCacheTests { + + static func attention(_ count: Int) -> KVCacheSimple { + let cache = KVCacheSimple() + let entry = MLXArray.zeros([1, 2, count, 64]) + _ = cache.update(keys: entry, values: entry) + return cache + } + + @Test func `tokens follow append, trim, and copy`() throws { + let transcript = TranscriptKVCache(tokens: [1, 2]) + transcript.append([3, 4, 5]) + #expect(transcript.tokens == [1, 2, 3, 4, 5]) + #expect(transcript.offset == 5) + + #expect(transcript.trim(2) == 2) + #expect(transcript.tokens == [1, 2, 3]) + #expect(transcript.trim(10) == 3) + #expect(transcript.offset == 0) + + transcript.append([9]) + let copy = try #require(transcript.copy() as? TranscriptKVCache) + transcript.append([10]) + #expect(copy.tokens == [9]) + } + + @Test func `capacity validation skips the transcript`() throws { + let parameters = GenerateParameters(maxKVSize: 16) + let plan = try parameters.kvCachePlan() + let attention = try makeAttentionKVCache(parameters: parameters) + + _ = try plan.validated([attention, TranscriptKVCache()]) + #expect(throws: (any Error).self) { + _ = try plan.validated([attention, PlainCustomCache()]) + } + } + + @Test func `compression leaves the transcript untouched`() { + let transcript = TranscriptKVCache(tokens: Array(0 ..< 8)) + var cache: [KVCache] = [Self.attention(8), transcript] + + maybeQuantizeKVCache(cache: &cache, kvBits: 4, quantizedKVStart: 0) + + #expect(cache[0] is QuantizedKVCache) + #expect((cache[1] as? TranscriptKVCache) === transcript) + #expect(transcript.tokens == Array(0 ..< 8)) + } + + @Test func `status reports and the shared timeline skip the transcript`() { + // Offsets disagree on purpose: the timeline must come from the attention entry. + let cache: [KVCache] = [Self.attention(5), TranscriptKVCache(tokens: [1, 2, 3])] + + let status = KVCacheStatus(cache: cache, plan: .disabled, phase: .planned) + #expect(status.layers.count == 1) + + let storage = KVCacheStorage(cache, plan: .disabled) + #expect(storage.processedTokenCount == 5) + #expect(storage.nativeAttentionOffsetsAreAligned) + } + + @Test func `trimming and copying include the transcript`() throws { + let transcript = TranscriptKVCache(tokens: [1, 2, 3, 4, 5]) + let storage = KVCacheStorage([Self.attention(5), transcript], plan: .disabled) + + #expect(storage.trim(2) == 2) + #expect(storage.cache[0].offset == 3) + #expect(transcript.tokens == [1, 2, 3]) + + let copy = try #require(storage.copy().cache[1] as? TranscriptKVCache) + #expect(copy !== transcript) + #expect(copy.tokens == [1, 2, 3]) + } + + @Test func `a staged speculative round writes through and trims the transcript back`() throws { + let attention = Self.attention(3) + let transcript = TranscriptKVCache(tokens: [1, 2, 3]) + let storage = KVCacheStorage([attention, transcript], plan: .disabled) + + let round = try #require(storage.beginRound(maximumPositions: 4)) + let presented = try #require(round.caches[1] as? TranscriptKVCache) + #expect(presented === transcript) + + // The verify pass writes 4 positions to every entry; 2 are accepted. + let entry = MLXArray.zeros([1, 2, 4, 64]) + _ = round.caches[0].update(keys: entry, values: entry) + presented.append([4, 5, 6, 7]) + let commit = storage.commit(round, retaining: 2) + + #expect(commit.committedPositions == 2) + #expect(attention.offset == 5) + #expect(transcript.tokens == [1, 2, 3, 4, 5]) + #expect(storage.processedTokenCount == 5) + } + + @Test func `a transcript round-trips through a prompt cache file`() throws { + let url = FileManager.default.temporaryDirectory + .appending(component: "transcript-\(UUID().uuidString).safetensors") + defer { try? FileManager.default.removeItem(at: url) } + + try savePromptCache( + url: url, cache: [Self.attention(3), TranscriptKVCache(tokens: [4, 5, 6])]) + let restored = try loadPromptCacheSnapshot(url: url).cache + + #expect(restored[0].offset == 3) + let transcript = try #require(restored[1] as? TranscriptKVCache) + #expect(transcript.tokens == [4, 5, 6]) + } + + @Test func `an empty transcript round-trips`() throws { + let url = FileManager.default.temporaryDirectory + .appending(component: "transcript-\(UUID().uuidString).safetensors") + defer { try? FileManager.default.removeItem(at: url) } + + try savePromptCache(url: url, cache: [KVCacheSimple(), TranscriptKVCache()]) + let transcript = try #require( + try loadPromptCacheSnapshot(url: url).cache.last as? TranscriptKVCache) + #expect(transcript.tokens.isEmpty) + } +} From 707f54c5e072d45b96f1cd38a638a5d4d039e640 Mon Sep 17 00:00:00 2001 From: David Koski Date: Wed, 14 Oct 2026 15:46:39 -0700 Subject: [PATCH 2/5] refactor type registry so everything goes through the same path --- Libraries/MLXLMCommon/KVCache.swift | 388 ++++++++---------- .../MLXLMCommon/KVCacheTypeRegistry.swift | 100 +++++ .../MLXLMCommon/PromptCacheTypeRegistry.swift | 62 --- Libraries/MLXLMCommon/TurboQuantKVCache.swift | 20 + .../VarianceNormalizedKVCache.swift | 80 ++++ .../Model/TranscriptKVCache.swift | 10 +- .../MLXLMTests/KVCacheTypeRegistryTests.swift | 164 ++++++++ .../PromptCacheTypeRegistryTests.swift | 137 ------- 8 files changed, 538 insertions(+), 423 deletions(-) create mode 100644 Libraries/MLXLMCommon/KVCacheTypeRegistry.swift delete mode 100644 Libraries/MLXLMCommon/PromptCacheTypeRegistry.swift create mode 100644 Tests/MLXLMTests/KVCacheTypeRegistryTests.swift delete mode 100644 Tests/MLXLMTests/PromptCacheTypeRegistryTests.swift diff --git a/Libraries/MLXLMCommon/KVCache.swift b/Libraries/MLXLMCommon/KVCache.swift index 815ab8aa2f..96630797d7 100644 --- a/Libraries/MLXLMCommon/KVCache.swift +++ b/Libraries/MLXLMCommon/KVCache.swift @@ -65,6 +65,15 @@ public protocol KVCache: Evaluatable { /// get/set metadata state as string array for serialization var metaState: [String] { get set } + /// The class name written to prompt cache files, or `nil` if this cache cannot be saved. + /// + /// Use a unique name, for example with a module prefix. A subclass that does not override + /// it saves under its parent's name and restores as the parent. + static var serializedClassName: String? { get } + + /// Rebuild a cache from the ``state`` and ``metaState`` it saved. + static func restore(state: [MLXArray], metaState: [String]) throws -> any KVCache + /// whether this cache can be trimmed var isTrimmable: Bool { get } @@ -112,6 +121,12 @@ public protocol KVCache: Evaluatable { } extension KVCache { + public static var serializedClassName: String? { nil } + + public static func restore(state: [MLXArray], metaState: [String]) throws -> any KVCache { + throw KVCacheError(message: "\(Self.self) cannot be restored from a prompt cache file") + } + public var ropeOffset: RoPEOffset { .scalar(offset) } @@ -213,8 +228,8 @@ public protocol KVCacheAttentionProtocol: KVCache { /// /// Cache policy skips these entries: capacity and compression settings, offset alignment /// checks, and ``KVCacheStatus`` layers ignore them. Generation still trims, copies, and saves -/// them with the other entries, so an auxiliary cache must be trimmable to keep pace. Make it -/// ``PromptCacheRestorable`` to restore it from a prompt cache file. +/// them with the other entries, so an auxiliary cache must be trimmable to keep pace, and it +/// needs a ``KVCache/serializedClassName`` to be saved to a prompt cache file. /// /// Staged speculative rounds (MTP) write through an auxiliary entry and trim it back to the /// accepted positions, so it must stay trimmable after the round's width. @@ -225,6 +240,13 @@ open class BaseKVCache: KVCache { public var offset: Int = 0 public init() {} + + open class var serializedClassName: String? { nil } + + open class func restore(state: [MLXArray], metaState: [String]) throws -> any KVCache { + throw KVCacheError(message: "\(Self.self) cannot be restored from a prompt cache file") + } + public var maxSize: Int? { nil } open var evictedTokenCount: Int { 0 } @@ -434,6 +456,27 @@ public func createSSMMask(h: MLXArray, cache: MambaCache?) -> MLXArray? { /// Standard KV cache implementation based on Python's KVCache /// See https://github.com/ml-explore/mlx-examples/blob/main/llms/mlx_lm/models/base.py#L11 public class KVCacheSimple: BaseKVCache, CustomDebugStringConvertible { + public override class var serializedClassName: String? { "KVCache" } + + public override class func restore( + state: [MLXArray], metaState: [String] + ) throws -> any KVCache { + try validatePromptCache( + className: "KVCacheSimple", state: state, stateCounts: [0, 2], + metadata: metaState, metadataCounts: [1]) + guard metaState == [""] else { + throw KVCacheError( + message: + "Corrupt prompt cache: KVCacheSimple metadata must contain its single empty placeholder." + ) + } + let cache = KVCacheSimple() + if !state.isEmpty { + cache.state = state + } + return cache + } + internal var keys: MLXArray? internal var values: MLXArray? public var step = 256 @@ -584,6 +627,46 @@ public class KVCacheSimple: BaseKVCache, CustomDebugStringConvertible { /// Rotating KV cache for sliding window attention public class RotatingKVCache: BaseKVCache, CustomDebugStringConvertible { + public override class var serializedClassName: String? { "RotatingKVCache" } + + public override class func restore( + state: [MLXArray], metaState: [String] + ) throws -> any KVCache { + try validatePromptCache( + className: "RotatingKVCache", state: state, stateCounts: [0, 2], + metadata: metaState, metadataCounts: [5, 6, 7, 8]) + let values = try promptCacheIntegers(metaState.prefix(5), className: "RotatingKVCache") + if metaState.count >= 6, + RotatingKVCache.CapacityOrigin(rawValue: metaState[5]) == nil + { + throw KVCacheError( + message: + "Corrupt prompt cache: invalid RotatingKVCache capacity origin '\(metaState[5])'." + ) + } + if metaState.count >= 7, Bool(metaState[6]) == nil { + throw KVCacheError( + message: + "Corrupt prompt cache: invalid RotatingKVCache wrapped flag '\(metaState[6])'." + ) + } + + if metaState.count == 8 { + guard let reserve = Int(metaState[7]), reserve >= 0, + values[1] <= Int.max - reserve + else { + throw KVCacheError(message: "Corrupt prompt cache: invalid rewind capacity.") + } + } + + let cache = RotatingKVCache(maxSize: values[1]) + if !state.isEmpty { + cache.state = state + } + cache.metaState = metaState + return cache + } + package enum CapacityOrigin: String { case modelNative case requested @@ -1080,6 +1163,23 @@ func resolvedKVQuantizationGroupSize( /// Quantized KV cache for memory efficiency using MLX quantization public class QuantizedKVCache: BaseKVCache, QuantizedKVCacheProtocol { + public override class var serializedClassName: String? { "QuantizedKVCache" } + + public override class func restore( + state: [MLXArray], metaState: [String] + ) throws -> any KVCache { + try validatePromptCache( + className: "QuantizedKVCache", state: state, stateCounts: [0, 4, 6], + metadata: metaState, metadataCounts: [4]) + let values = try promptCacheIntegers(metaState, className: "QuantizedKVCache") + let cache = QuantizedKVCache(groupSize: values[2], bits: values[3]) + if !state.isEmpty { + cache.state = state + } + cache.metaState = metaState + return cache + } + private var keys: (MLXArray, MLXArray, MLXArray?)? private var values: (MLXArray, MLXArray, MLXArray?)? private let step: Int @@ -1370,6 +1470,31 @@ public class QuantizedKVCache: BaseKVCache, QuantizedKVCacheProtocol { /// Chunked KV cache for processing large contexts in chunks public class ChunkedKVCache: KVCacheSimple { + public override class var serializedClassName: String? { "ChunkedKVCache" } + + public override class func restore( + state: [MLXArray], metaState: [String] + ) throws -> any KVCache { + try validatePromptCache( + className: "ChunkedKVCache", state: state, stateCounts: [0, 2], + metadata: metaState, metadataCounts: [2]) + + let chunkSize: Int? = + if metaState[0] == "None" { + nil + } else { + try promptCacheInteger(metaState[0], className: "ChunkedKVCache") + } + _ = try promptCacheInteger(metaState[1], className: "ChunkedKVCache") + + let cache = ChunkedKVCache(chunkSize: chunkSize) + if !state.isEmpty { + cache.state = state + } + cache.metaState = metaState + return cache + } + private var chunkSize: Int? private var startPosition: Int = 0 @@ -1464,6 +1589,16 @@ public class ChunkedKVCache: KVCacheSimple { /// Base cache for array-based state storage public class ArraysCache: BaseKVCache { + public override class var serializedClassName: String? { "ArraysCache" } + + public override class func restore( + state: [MLXArray], metaState: [String] + ) throws -> any KVCache { + let cache = ArraysCache(size: 0) + cache.restoreFromMetaState(state: state, savedMetaState: metaState) + return cache + } + fileprivate var cache: [MLXArray?] internal var leftPadding: MLXArray? internal var lengths: MLXArray? @@ -1658,6 +1793,16 @@ public class ArraysCache: BaseKVCache { /// Simple cache for Mamba-style state space models public class MambaCache: ArraysCache { + public override class var serializedClassName: String? { "MambaCache" } + + public override class func restore( + state: [MLXArray], metaState: [String] + ) throws -> any KVCache { + let cache = MambaCache() + cache.restoreFromMetaState(state: state, savedMetaState: metaState) + return cache + } + private struct SpeculativeCheckpoint { var state: [MLXArray?] var offset: Int @@ -1713,6 +1858,14 @@ public class MambaCache: ArraysCache { /// Composite cache that manages multiple sub-caches public class CacheList: BaseKVCache { + public override class var serializedClassName: String? { "CacheList" } + + public override class func restore( + state: [MLXArray], metaState: [String] + ) throws -> any KVCache { + return try CacheList.fromState(state: state, metaState: metaState) + } + private var caches: [KVCache] public init(_ caches: KVCache...) { @@ -1842,7 +1995,8 @@ public class CacheList: BaseKVCache { get { var result = ["\(caches.count)"] for cache in caches { - let className = cacheClassName(cache) + let className = + type(of: cache).serializedClassName ?? String(describing: type(of: cache)) let meta = cache.metaState result.append(className) result.append("\(cache.state.count)") @@ -1905,25 +2059,6 @@ struct KVCacheError: Error, LocalizedError { // MARK: - Utility Functions -/// Map a cache instance to its Python-compatible class name for serialization. -private func cacheClassName(_ cache: KVCache) -> String { - if let custom = cache as? any PromptCacheRestorable { - return type(of: custom).promptCacheClassName - } - switch cache { - case is ChunkedKVCache: return "ChunkedKVCache" - case is MambaCache: return "MambaCache" - case is ArraysCache: return "ArraysCache" - case is RotatingKVCache: return "RotatingKVCache" - case is VarianceNormalizedKVCache: return "VarianceNormalizedKVCache" - case is QuantizedKVCache: return "QuantizedKVCache" - case is TurboQuantKVCache: return "TurboQuantKVCache" - case is KVCacheSimple: return "KVCache" - case is CacheList: return "CacheList" - default: return "KVCache" - } -} - /// A prompt cache and the model state that belongs with it. /// /// Keeping the two together is the point: a KV cache restored without its model state positions @@ -1979,11 +2114,13 @@ public func savePromptCache( throw KVCacheError(message: "Model state requires at least one prompt cache") } + let cacheClasses = try cache.map { + promptCacheClassName( + try KVCacheTypeRegistry.shared.serializedClassName(for: $0), + hasState: !stateArrays.isEmpty) + } let cacheData = cache.map { $0.state } let cacheInfo = cache.map { $0.metaState } - let cacheClasses = cache.map { - promptCacheClassName(cacheClassName($0), hasState: !stateArrays.isEmpty) - } // Flatten cache data using tree_flatten compatible structure: "i.j" format var flattenedData: [String: MLXArray] = [:] @@ -2211,205 +2348,16 @@ private func restoreCacheFromMetaState( state: [MLXArray], metaState: [String] ) throws -> KVCache { - switch className { - case "KVCache", "KVCacheSimple": - try validatePromptCache( - className: "KVCacheSimple", state: state, stateCounts: [0, 2], - metadata: metaState, metadataCounts: [1]) - guard metaState == [""] else { - throw KVCacheError( - message: - "Corrupt prompt cache: KVCacheSimple metadata must contain its single empty placeholder." - ) - } - let cache = KVCacheSimple() - if !state.isEmpty { - cache.state = state - } - return cache - - case "RotatingKVCache": - try validatePromptCache( - className: className, state: state, stateCounts: [0, 2], - metadata: metaState, metadataCounts: [5, 6, 7, 8]) - let values = try promptCacheIntegers(metaState.prefix(5), className: className) - if metaState.count >= 6, - RotatingKVCache.CapacityOrigin(rawValue: metaState[5]) == nil - { - throw KVCacheError( - message: - "Corrupt prompt cache: invalid RotatingKVCache capacity origin '\(metaState[5])'." - ) - } - if metaState.count >= 7, Bool(metaState[6]) == nil { - throw KVCacheError( - message: - "Corrupt prompt cache: invalid RotatingKVCache wrapped flag '\(metaState[6])'." - ) - } - - if metaState.count == 8 { - guard let reserve = Int(metaState[7]), reserve >= 0, - values[1] <= Int.max - reserve - else { - throw KVCacheError(message: "Corrupt prompt cache: invalid rewind capacity.") - } - } - - let cache = RotatingKVCache(maxSize: values[1]) - if !state.isEmpty { - cache.state = state - } - cache.metaState = metaState - return cache - - case "QuantizedKVCache": - try validatePromptCache( - className: className, state: state, stateCounts: [0, 4, 6], - metadata: metaState, metadataCounts: [4]) - let values = try promptCacheIntegers(metaState, className: className) - let cache = QuantizedKVCache(groupSize: values[2], bits: values[3]) - if !state.isEmpty { - cache.state = state - } - cache.metaState = metaState - return cache - - case "VarianceNormalizedKVCache": - 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: className) - 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 - - case "ChunkedKVCache": - try validatePromptCache( - className: className, state: state, stateCounts: [0, 2], - metadata: metaState, metadataCounts: [2]) - - let chunkSize: Int? = - if metaState[0] == "None" { - nil - } else { - try promptCacheInteger(metaState[0], className: className) - } - _ = try promptCacheInteger(metaState[1], className: className) - - let cache = ChunkedKVCache(chunkSize: chunkSize) - if !state.isEmpty { - cache.state = state - } - cache.metaState = metaState - return cache - - case "MambaCache": - let cache = MambaCache() - cache.restoreFromMetaState(state: state, savedMetaState: metaState) - return cache - - case "ArraysCache": - let cache = ArraysCache(size: 0) - cache.restoreFromMetaState(state: state, savedMetaState: metaState) - return cache - - case "TurboQuantKVCache": - 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 - - case "CacheList": - return try CacheList.fromState(state: state, metaState: metaState) - - default: - if let type = PromptCacheTypeRegistry.shared.type(named: className) { - return try type.restore(state: state, metaState: metaState) - } + guard let type = KVCacheTypeRegistry.shared.type(named: className) else { throw KVCacheError( message: - "Unknown cache class: \(className). Custom cache types must be registered with registerPromptCacheType(_:)." + "Unknown cache class: \(className). Register custom cache types with registerKVCacheType(_:)." ) } + return try type.restore(state: state, metaState: metaState) } -private func validatePromptCache( +func validatePromptCache( className: String, state: [MLXArray], stateCounts: Set, @@ -2425,7 +2373,7 @@ private func validatePromptCache( } } -private func promptCacheInteger(_ value: String, className: String) throws -> Int { +func promptCacheInteger(_ value: String, className: String) throws -> Int { guard let value = Int(value) else { throw KVCacheError( message: "Corrupt prompt cache: \(className) metadata must contain integers." @@ -2434,7 +2382,7 @@ private func promptCacheInteger(_ value: String, className: String) throws -> In return value } -private func promptCacheIntegers( +func promptCacheIntegers( _ metadata: some Collection, className: String ) throws -> [Int] { try metadata.map { try promptCacheInteger($0, className: className) } diff --git a/Libraries/MLXLMCommon/KVCacheTypeRegistry.swift b/Libraries/MLXLMCommon/KVCacheTypeRegistry.swift new file mode 100644 index 0000000000..c6d5dd3f51 --- /dev/null +++ b/Libraries/MLXLMCommon/KVCacheTypeRegistry.swift @@ -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(_ type: T.Type) throws { + try KVCacheTypeRegistry.shared.register(type) +} + +private let logger = Logger(subsystem: "mlx-swift-lm", category: "kv-cache") + +/// 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(_ 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 + } +} diff --git a/Libraries/MLXLMCommon/PromptCacheTypeRegistry.swift b/Libraries/MLXLMCommon/PromptCacheTypeRegistry.swift deleted file mode 100644 index 331cdb35d3..0000000000 --- a/Libraries/MLXLMCommon/PromptCacheTypeRegistry.swift +++ /dev/null @@ -1,62 +0,0 @@ -// Copyright © 2026 Apple Inc. - -import Foundation -import MLX - -/// A cache type defined outside MLXLMCommon that prompt cache files can save and restore. -/// -/// ``savePromptCache(url:cache:metadata:state:)`` writes ``promptCacheClassName`` with the -/// cache's `state` and `metaState`. To load the file, register the type first with -/// ``registerPromptCacheType(_:)``. -public protocol PromptCacheRestorable: KVCache { - /// The class name written to prompt cache files. It must not be a built-in name such as - /// `KVCacheSimple`, and it should be unique, for example by including a module prefix. - static var promptCacheClassName: String { get } - - /// Rebuild a cache from the `state` and `metaState` it saved. - static func restore(state: [MLXArray], metaState: [String]) throws -> any KVCache -} - -/// Register a cache type so ``loadPromptCacheSnapshot(url:)`` can restore it. -/// -/// Registering the same type again has no effect. -/// -/// - Throws: if the name is a built-in cache name, or another type already uses it. -public func registerPromptCacheType(_ type: any PromptCacheRestorable.Type) throws { - try PromptCacheTypeRegistry.shared.register(type) -} - -final class PromptCacheTypeRegistry: @unchecked Sendable { - static let shared = PromptCacheTypeRegistry() - - /// Names that `restoreCacheFromMetaState` handles itself. - static let builtInNames: Set = [ - "KVCache", "KVCacheSimple", "RotatingKVCache", "QuantizedKVCache", - "VarianceNormalizedKVCache", "ChunkedKVCache", "MambaCache", "ArraysCache", - "TurboQuantKVCache", "CacheList", - ] - - private let lock = NSLock() - private var types: [String: any PromptCacheRestorable.Type] = [:] - - func register(_ type: any PromptCacheRestorable.Type) throws { - let name = type.promptCacheClassName - guard !Self.builtInNames.contains(name) else { - throw KVCacheError(message: "\(name) is a built-in prompt cache class name") - } - try lock.withLock { - if let existing = types[name] { - guard ObjectIdentifier(existing) == ObjectIdentifier(type) else { - throw KVCacheError( - message: "Prompt cache class name \(name) is already registered") - } - return - } - types[name] = type - } - } - - func type(named name: String) -> (any PromptCacheRestorable.Type)? { - lock.withLock { types[name] } - } -} diff --git a/Libraries/MLXLMCommon/TurboQuantKVCache.swift b/Libraries/MLXLMCommon/TurboQuantKVCache.swift index 30d348a40c..6dc009a464 100644 --- a/Libraries/MLXLMCommon/TurboQuantKVCache.swift +++ b/Libraries/MLXLMCommon/TurboQuantKVCache.swift @@ -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) diff --git a/Libraries/MLXLMCommon/VarianceNormalizedKVCache.swift b/Libraries/MLXLMCommon/VarianceNormalizedKVCache.swift index 8914d53002..5ff546ec13 100644 --- a/Libraries/MLXLMCommon/VarianceNormalizedKVCache.swift +++ b/Libraries/MLXLMCommon/VarianceNormalizedKVCache.swift @@ -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 diff --git a/Libraries/MLXScriptedLM/Model/TranscriptKVCache.swift b/Libraries/MLXScriptedLM/Model/TranscriptKVCache.swift index a3bd95d945..8e74aab51c 100644 --- a/Libraries/MLXScriptedLM/Model/TranscriptKVCache.swift +++ b/Libraries/MLXScriptedLM/Model/TranscriptKVCache.swift @@ -13,13 +13,13 @@ import MLXLMCommon /// /// It is an `AuxiliaryKVCache`, so capacity and compression settings ignore it, and it never /// stores keys or values. -public final class TranscriptKVCache: BaseKVCache, AuxiliaryKVCache, PromptCacheRestorable { +public final class TranscriptKVCache: BaseKVCache, AuxiliaryKVCache { - public static var promptCacheClassName: String { "MLXScriptedLM.TranscriptKVCache" } + 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! registerPromptCacheType(TranscriptKVCache.self) + try! registerKVCacheType(TranscriptKVCache.self) }() public private(set) var tokens: [Int] @@ -70,7 +70,9 @@ public final class TranscriptKVCache: BaseKVCache, AuxiliaryKVCache, PromptCache set {} } - public static func restore(state: [MLXArray], metaState: [String]) throws -> any KVCache { + 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 { diff --git a/Tests/MLXLMTests/KVCacheTypeRegistryTests.swift b/Tests/MLXLMTests/KVCacheTypeRegistryTests.swift new file mode 100644 index 0000000000..db886db54b --- /dev/null +++ b/Tests/MLXLMTests/KVCacheTypeRegistryTests.swift @@ -0,0 +1,164 @@ +// Copyright © 2026 Apple Inc. + +import Foundation +import MLX +import Testing + +@testable import MLXLMCommon + +/// Stores token ids, standing in for a cache type defined outside MLXLMCommon. +private final class TokenListCache: BaseKVCache { + override static var serializedClassName: String? { "Tests.TokenListCache" } + + var tokens: [Int32] + + init(tokens: [Int32]) { + self.tokens = tokens + super.init() + offset = tokens.count + } + + override var state: [MLXArray] { + get { [MLXArray(tokens)] } + set { tokens = newValue.first?.asArray(Int32.self) ?? [] } + } + + override var metaState: [String] { + get { [String(offset)] } + set { offset = newValue.first.flatMap(Int.init) ?? tokens.count } + } + + override var isTrimmable: Bool { true } + + override func copy() -> any KVCache { TokenListCache(tokens: tokens) } + + override static func restore(state: [MLXArray], metaState: [String]) throws -> any KVCache { + let cache = TokenListCache(tokens: state.first?.asArray(Int32.self) ?? []) + cache.metaState = metaState + return cache + } +} + +private final class OtherTokenListCache: BaseKVCache { + override static var serializedClassName: String? { "Tests.TokenListCache" } + override func copy() -> any KVCache { OtherTokenListCache() } + override static func restore(state: [MLXArray], metaState: [String]) throws -> any KVCache { + OtherTokenListCache() + } +} + +private final class BuiltInNameCache: BaseKVCache { + override static var serializedClassName: String? { "KVCacheSimple" } + override func copy() -> any KVCache { BuiltInNameCache() } +} + +/// Never registered explicitly, so only saving registers it. +private final class SavedOnlyCache: BaseKVCache { + override static var serializedClassName: String? { "Tests.SavedOnlyCache" } + override func copy() -> any KVCache { SavedOnlyCache() } + override static func restore(state: [MLXArray], metaState: [String]) throws -> any KVCache { + SavedOnlyCache() + } +} + +private final class UnnamedCache: BaseKVCache { + override func copy() -> any KVCache { UnnamedCache() } +} + +private final class InheritedNameCache: KVCacheSimple {} + +struct KVCacheTypeRegistryTests { + + static func temporaryURL() -> URL { + FileManager.default.temporaryDirectory + .appending(component: "prompt-cache-\(UUID().uuidString).safetensors") + } + + @Test func `a registered custom cache saves and restores with built-in caches`() throws { + try registerKVCacheType(TokenListCache.self) + + let simple = KVCacheSimple() + _ = simple.update(keys: MLXArray.ones([1, 2, 3, 8]), values: MLXArray.ones([1, 2, 3, 8])) + let custom = TokenListCache(tokens: [7, 8, 9]) + + let url = Self.temporaryURL() + defer { try? FileManager.default.removeItem(at: url) } + try savePromptCache(url: url, cache: [simple, custom]) + + let restored = try loadPromptCacheSnapshot(url: url).cache + #expect(restored.count == 2) + #expect(restored[0] is KVCacheSimple) + #expect(restored[0].offset == 3) + let tokens = try #require(restored[1] as? TokenListCache) + #expect(tokens.tokens == [7, 8, 9]) + #expect(tokens.offset == 3) + } + + @Test func `a custom cache inside a CacheList round-trips`() throws { + try registerKVCacheType(TokenListCache.self) + + let url = Self.temporaryURL() + defer { try? FileManager.default.removeItem(at: url) } + try savePromptCache( + url: url, cache: [CacheList(KVCacheSimple(), TokenListCache(tokens: [1, 2]))]) + + let list = try #require(try loadPromptCacheSnapshot(url: url).cache.first as? CacheList) + let tokens = try #require(list.children.last as? TokenListCache) + #expect(tokens.tokens == [1, 2]) + } + + @Test func `saving registers the type so the same process can load it`() throws { + let url = Self.temporaryURL() + defer { try? FileManager.default.removeItem(at: url) } + try savePromptCache(url: url, cache: [SavedOnlyCache()]) + + #expect(try loadPromptCacheSnapshot(url: url).cache.first is SavedOnlyCache) + } + + @Test func `registering the same type twice is allowed`() throws { + try registerKVCacheType(TokenListCache.self) + try registerKVCacheType(TokenListCache.self) + } + + @Test func `another type cannot take a registered name`() throws { + try registerKVCacheType(TokenListCache.self) + #expect(throws: (any Error).self) { + try registerKVCacheType(OtherTokenListCache.self) + } + + let url = Self.temporaryURL() + defer { try? FileManager.default.removeItem(at: url) } + #expect(throws: (any Error).self) { + try savePromptCache(url: url, cache: [OtherTokenListCache()]) + } + } + + @Test func `built-in names and aliases are taken`() { + #expect(throws: (any Error).self) { + try registerKVCacheType(BuiltInNameCache.self) + } + #expect(throws: (any Error).self) { + try registerKVCacheType(InheritedNameCache.self) + } + } + + @Test func `a cache without a serialized class name cannot be saved`() { + let url = Self.temporaryURL() + defer { try? FileManager.default.removeItem(at: url) } + #expect(throws: (any Error).self) { + try savePromptCache(url: url, cache: [UnnamedCache()]) + } + #expect(throws: (any Error).self) { + try savePromptCache(url: url, cache: [CacheList(KVCacheSimple(), UnnamedCache())]) + } + } + + @Test func `a subclass that keeps its parent's name restores as the parent`() throws { + let url = Self.temporaryURL() + defer { try? FileManager.default.removeItem(at: url) } + try savePromptCache(url: url, cache: [InheritedNameCache()]) + + let restored = try #require(try loadPromptCacheSnapshot(url: url).cache.first) + #expect(type(of: restored) == KVCacheSimple.self) + } +} diff --git a/Tests/MLXLMTests/PromptCacheTypeRegistryTests.swift b/Tests/MLXLMTests/PromptCacheTypeRegistryTests.swift deleted file mode 100644 index b5659c6106..0000000000 --- a/Tests/MLXLMTests/PromptCacheTypeRegistryTests.swift +++ /dev/null @@ -1,137 +0,0 @@ -// Copyright © 2026 Apple Inc. - -import Foundation -import MLX -import Testing - -@testable import MLXLMCommon - -/// Stores token ids, standing in for a cache type defined outside MLXLMCommon. -private final class TokenListCache: BaseKVCache, PromptCacheRestorable { - static var promptCacheClassName: String { "Tests.TokenListCache" } - - var tokens: [Int32] - - init(tokens: [Int32]) { - self.tokens = tokens - super.init() - offset = tokens.count - } - - override var state: [MLXArray] { - get { [MLXArray(tokens)] } - set { tokens = newValue.first?.asArray(Int32.self) ?? [] } - } - - override var metaState: [String] { - get { [String(offset)] } - set { offset = newValue.first.flatMap(Int.init) ?? tokens.count } - } - - override var isTrimmable: Bool { true } - - override func copy() -> any KVCache { TokenListCache(tokens: tokens) } - - static func restore(state: [MLXArray], metaState: [String]) throws -> any KVCache { - let cache = TokenListCache(tokens: state.first?.asArray(Int32.self) ?? []) - cache.metaState = metaState - return cache - } -} - -private final class OtherTokenListCache: BaseKVCache, PromptCacheRestorable { - static var promptCacheClassName: String { "Tests.TokenListCache" } - override func copy() -> any KVCache { OtherTokenListCache() } - static func restore(state: [MLXArray], metaState: [String]) throws -> any KVCache { - OtherTokenListCache() - } -} - -private final class BuiltInNameCache: BaseKVCache, PromptCacheRestorable { - static var promptCacheClassName: String { "KVCacheSimple" } - override func copy() -> any KVCache { BuiltInNameCache() } - static func restore(state: [MLXArray], metaState: [String]) throws -> any KVCache { - BuiltInNameCache() - } -} - -private final class UnregisteredCache: BaseKVCache, PromptCacheRestorable { - static var promptCacheClassName: String { "Tests.UnregisteredCache" } - override func copy() -> any KVCache { UnregisteredCache() } - static func restore(state: [MLXArray], metaState: [String]) throws -> any KVCache { - UnregisteredCache() - } -} - -struct PromptCacheTypeRegistryTests { - - static func temporaryURL() -> URL { - FileManager.default.temporaryDirectory - .appending(component: "prompt-cache-\(UUID().uuidString).safetensors") - } - - @Test func `a registered custom cache saves and restores with built-in caches`() throws { - try registerPromptCacheType(TokenListCache.self) - - let simple = KVCacheSimple() - _ = simple.update(keys: MLXArray.ones([1, 2, 3, 8]), values: MLXArray.ones([1, 2, 3, 8])) - let custom = TokenListCache(tokens: [7, 8, 9]) - - let url = Self.temporaryURL() - defer { try? FileManager.default.removeItem(at: url) } - try savePromptCache(url: url, cache: [simple, custom]) - - let restored = try loadPromptCacheSnapshot(url: url).cache - #expect(restored.count == 2) - #expect(restored[0] is KVCacheSimple) - #expect(restored[0].offset == 3) - let tokens = try #require(restored[1] as? TokenListCache) - #expect(tokens.tokens == [7, 8, 9]) - #expect(tokens.offset == 3) - } - - @Test func `a custom cache inside a CacheList round-trips`() throws { - try registerPromptCacheType(TokenListCache.self) - - let url = Self.temporaryURL() - defer { try? FileManager.default.removeItem(at: url) } - try savePromptCache( - url: url, cache: [CacheList(KVCacheSimple(), TokenListCache(tokens: [1, 2]))]) - - let list = try #require(try loadPromptCacheSnapshot(url: url).cache.first as? CacheList) - let tokens = try #require(list.children.last as? TokenListCache) - #expect(tokens.tokens == [1, 2]) - } - - @Test func `registering the same type twice is allowed`() throws { - try registerPromptCacheType(TokenListCache.self) - try registerPromptCacheType(TokenListCache.self) - } - - @Test func `another type cannot take a registered name`() throws { - try registerPromptCacheType(TokenListCache.self) - #expect(throws: (any Error).self) { - try registerPromptCacheType(OtherTokenListCache.self) - } - } - - @Test func `built-in names are reserved`() { - #expect(throws: (any Error).self) { - try registerPromptCacheType(BuiltInNameCache.self) - } - } - - @Test func `an unregistered custom cache saves under its name but does not load`() throws { - let url = Self.temporaryURL() - defer { try? FileManager.default.removeItem(at: url) } - try savePromptCache(url: url, cache: [UnregisteredCache()]) - - do { - _ = try loadPromptCacheSnapshot(url: url) - Issue.record("expected an unknown cache class error") - } catch { - #expect(error.localizedDescription.contains("Tests.UnregisteredCache")) - #expect(error.localizedDescription.contains("registerPromptCacheType")) - } - } -} From e26b8c42fe2a34a576f2049aaeb684067d66a557 Mon Sep 17 00:00:00 2001 From: David Koski Date: Wed, 14 Oct 2026 16:16:33 -0700 Subject: [PATCH 3/5] fix docs build, use MLXLogger in new code --- Libraries/MLXLMCommon/KVCache.swift | 2 +- Libraries/MLXLMCommon/KVCacheTypeRegistry.swift | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Libraries/MLXLMCommon/KVCache.swift b/Libraries/MLXLMCommon/KVCache.swift index 96630797d7..b5bab681ea 100644 --- a/Libraries/MLXLMCommon/KVCache.swift +++ b/Libraries/MLXLMCommon/KVCache.swift @@ -71,7 +71,7 @@ public protocol KVCache: Evaluatable { /// it saves under its parent's name and restores as the parent. static var serializedClassName: String? { get } - /// Rebuild a cache from the ``state`` and ``metaState`` it saved. + /// Rebuild a cache from the `state` and `metaState` it saved. static func restore(state: [MLXArray], metaState: [String]) throws -> any KVCache /// whether this cache can be trimmed diff --git a/Libraries/MLXLMCommon/KVCacheTypeRegistry.swift b/Libraries/MLXLMCommon/KVCacheTypeRegistry.swift index c6d5dd3f51..054eed8b09 100644 --- a/Libraries/MLXLMCommon/KVCacheTypeRegistry.swift +++ b/Libraries/MLXLMCommon/KVCacheTypeRegistry.swift @@ -14,7 +14,7 @@ public func registerKVCacheType(_ type: T.Type) throws { try KVCacheTypeRegistry.shared.register(type) } -private let logger = Logger(subsystem: "mlx-swift-lm", category: "kv-cache") +private let logger = MLXLogger(label: "KVCacheTypeRegistry") /// Maps ``KVCache/serializedClassName`` to cache types, starting with the built-in caches. final class KVCacheTypeRegistry: @unchecked Sendable { From 57b4e030bb1b0160276cd71afcbe6ea3c7c4ec54 Mon Sep 17 00:00:00 2001 From: David Koski Date: Wed, 14 Oct 2026 16:21:52 -0700 Subject: [PATCH 4/5] address some feedback --- Libraries/MLXScriptedLM/Model/TranscriptKVCache.swift | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/Libraries/MLXScriptedLM/Model/TranscriptKVCache.swift b/Libraries/MLXScriptedLM/Model/TranscriptKVCache.swift index 8e74aab51c..14975241b0 100644 --- a/Libraries/MLXScriptedLM/Model/TranscriptKVCache.swift +++ b/Libraries/MLXScriptedLM/Model/TranscriptKVCache.swift @@ -13,6 +13,10 @@ import MLXLMCommon /// /// 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 { public override static var serializedClassName: String? { "MLXScriptedLM.TranscriptKVCache" } @@ -22,6 +26,13 @@ public final class TranscriptKVCache: BaseKVCache, AuxiliaryKVCache { 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] = []) { From 8bfd27190036ac135b9552fd6ceb4f7a2e38fcde Mon Sep 17 00:00:00 2001 From: David Koski Date: Thu, 15 Oct 2026 09:24:20 -0700 Subject: [PATCH 5/5] make innerState open per PR feedback --- Libraries/MLXLMCommon/KVCache.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Libraries/MLXLMCommon/KVCache.swift b/Libraries/MLXLMCommon/KVCache.swift index b5bab681ea..d4b000d33b 100644 --- a/Libraries/MLXLMCommon/KVCache.swift +++ b/Libraries/MLXLMCommon/KVCache.swift @@ -254,7 +254,7 @@ open class BaseKVCache: KVCache { /// offset (e.g. a batched cache's per-row `.batch(...)`). open var ropeOffset: RoPEOffset { .scalar(offset) } - public func innerState() -> [MLXArray] { [] } + open func innerState() -> [MLXArray] { [] } open func update(keys: MLXArray, values: MLXArray) -> (MLXArray, MLXArray) { fatalError("update(keys:values:) must be implemented by subclass")