Repository navigation
Support for scripted models (tests) #701
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
0661d9b
Support for scripted models (tests)
davidkoski 707f54c
refactor type registry so everything goes through the same path
davidkoski e26b8c4
fix docs build, use MLXLogger in new code
davidkoski 57b4e03
address some feedback
davidkoski 8bfd271
make innerState open per PR feedback
davidkoski File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 { | ||
|
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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)" | ||
| } | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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.