Skip to content

Support for scripted models (tests) - #701

Merged
davidkoski merged 5 commits into
mainfrom
scripted-2
Oct 15, 2026
Merged

davidkoski merged 5 commits into
mainfrom
scripted-2

Conversation

@davidkoski

Copy link
Copy Markdown
Member

Proposed changes

part 2 of scripted tokenizers & models. KVCache support

  • add TranscriptKVCache (tests)
  • add ability to extend KVCache hierarchy

Checklist

Put an x in the boxes that apply.

  • I have read the CONTRIBUTING document
  • I have run pre-commit run --all-files to format my code / installed pre-commit prior to committing changes
  • I have added tests that prove my fix is effective or that my feature works
  • I have updated the necessary documentation (if needed)

AI usage

  • I have read this PR description in full and approve it as my own, and it
    accurately describes the code changes.
  • AI usage disclosure: claude used to implement plan

- add TranscriptKVCache (tests)
- add ability to extend KVCache hierarchy
///
/// 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 {}

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.

Marker for special cache types. The plan is to compose a model like this:

  • ScripedModel(Gemma3())

the outer model will inject a KVCache for its own state and strip it off to pass to the interior model (which will be a random weight model).

In order for the KVCache to participate in normal KVCache activities we need to let the KVCache infrastructure (plans, save/restore) know what it is.

In general this will give third parties the ability to write KVCache types outside of mlx-swift-lm, or at least a first pass at it.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This looks like a nice addition! I like that a wrapper can keep its own state alongside the inner model’s caches and have it participate in trimming, copying, and save/restore.

Opening that up to cache types defined outside mlx-swift-lm also gives downstream projects more room to experiment. Thanks.

Comment on lines +244 to +246
open class var serializedClassName: String? { nil }

open class func restore(state: [MLXArray], metaState: [String]) throws -> any KVCache {

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.

Now all KVCache types declare their key and a way to restore state. Previously was two switch statements for the encode and decode.

Note: types can register aliases if there are two keys they can decode from.

Comment on lines +459 to +463
public override class var serializedClassName: String? { "KVCache" }

public override class func restore(
state: [MLXArray], metaState: [String]
) throws -> any KVCache {

@davidkoski davidkoski Oct 14, 2026 •

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.

Same pattern for all the cache types. serializedClassName comes from the switch in cacheClassName() (now gone), and restore is from the switch in restoreCacheFromMetaState() (remains but the body is now tiny).

// MARK: - Utility Functions

/// Map a cache instance to its Python-compatible class name for serialization.
private func cacheClassName(_ cache: KVCache) -> String {

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.

Replaced by static properties.

Comment on lines -2195 to -2196
switch className {
case "KVCache", "KVCacheSimple":

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.

All these moved to the restore() function on each type.

Comment on lines +225 to +226
// Auxiliary entries are not leaves, but they append and trim like one.
if entry is any 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.

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.

///
/// It is an `AuxiliaryKVCache`, so capacity and compression settings ignore it, and it never
/// stores keys or values.
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.

@davidkoski

Copy link
Copy Markdown
Member Author

@aleroot FYI, some proposed KVCache infrastructure changes

@aleroot

aleroot commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor

@aleroot FYI, some proposed KVCache infrastructure changes

Thanks for the heads-up, @davidkoski. This come with good timing!
I’m currently exploring this KV-Lingo cache translation paper for switching models within a conversation. These changes look compatible with the approach I have in mind: the translator would read the source cache and populate ordinary target KVCacheSimple instances, so the translated K/V would continue participating in normal cache policy and offset checks.

The distinction provided by AuxiliaryKVCache is something I appreciate and makes sense for bookkeeping alongside those attention caches.

One question about external cache implementations: BaseKVCache.innerState() remains public rather than open, so an external subclass holding MLX arrays cannot override it to expose its evaluation state. Would making that method open fit the extensibility goal here? This does not block my initial implementation using built-in caches, but seems useful for third-party cache types.

@davidkoski

Copy link
Copy Markdown
Member Author

Good point on innerState() being public -- I didn't need it to be open but most implementations would.

@davidkoski
davidkoski merged commit 6e338e5 into main Oct 15, 2026
5 checks passed
@davidkoski
davidkoski deleted the scripted-2 branch October 15, 2026 23:33
ximyro pushed a commit to ximyro/mlx-swift-lm that referenced this pull request Nov 4, 2026
Brings in ml-explore#622 (exact prefix rewinds in rotating KV caches), ml-explore#619 (streaming
detokenizers), ml-explore#698, ml-explore#699, ml-explore#700, ml-explore#701, ml-explore#705, ml-explore#697 and ml-explore#695.

Conflicts: AttentionUtils.swift keeps TurboKV telemetry next to upstream's
SharedAttentionKVCache; KVCache.swift takes upstream's serialization and
rotating-cache view/trim while keeping the fork's TurboQuant state, public
cache fields and temporallyOrdered.

Follow-ups for upstream behavior the fork had changed: the Qwen2VL audio
placeholder no longer indexes content.count - 1 when a tool-call message has no
text part, and Gemma4MessageGenerator uses content parts for every non-system
role.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants