Skip to content

Reuse the KV cache on text turns after an image turn - #827

Merged
davidkoski merged 2 commits into
ml-explore:mainfrom
aleroot:reuse-cache-after-image-turns
Dec 3, 2026
Merged

davidkoski merged 2 commits into
ml-explore:mainfrom
aleroot:reuse-cache-after-image-turns

Conversation

@aleroot

@aleroot aleroot commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Proposed changes

See the superseded #688, plus the below addition.

A VL processor pairs media with an all-ones attention mask and renders the whole transcript, so every turn after an image turn carries the mask, text turns too. ExtendCachedPrefixRule refuses any mask, so each such turn rebuilt the cache: a full prefill with every earlier image through the vision tower again. Only turns adding new media reused the cache (#515).

Only the model can tell the benign mask from padding, so the split now takes these turns. AppendOnlyMediaRule fires for new media or a mask. Models that cannot split rebuild as before.

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:

@aleroot

aleroot commented Nov 23, 2026

Copy link
Copy Markdown
Contributor Author

Integrated my previous #688 work as well for completeness.

Comment thread Libraries/MLXLMCommon/ChatSession.swift Outdated
mediaSuffixInput
?? LMInput(
tokens: MLXArray(
Array(promptTokenIds.dropFirst(commonPrefixLength))))

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I don't think the root cause is in this PR, but the PR exposes it: these lines, along with 1705 and 1710 (ChatSession.swift), produce rank-1 suffixes, and with this PR they now reach models that don't handle rank-1 on a warm cache:

  • Qwen2VL
  • Qwen25VL
  • Qwen3VLMoE

In Qwen2VL/Qwen25VL, prepare only takes the continuation path when inputIds.ndim == 2. A rank-1 suffix falls through to the cold path, which drops the carried rope delta, so later turns get the wrong M-RoPE positions with no error. Removing the all-ones mask means a text turn after an image turn now takes .appendSuffix and lands here.

Qwen3VLMoE never reshapes rank-1 input, so a warm rank-1 suffix traps in the language model (dim(1) on a 1-D array, then an index trap in broadcast). With ModelStateRewinding, the trim path now goes ahead for these models and gets there too.

Qwen3VL does handle this:

    public func prepare(
...
        // Text-only follow-up processors may return rank-1 tokens. The language
        // model and continuation slicers require [batch, sequence], so normalize
        // before choosing a warm path rather than falling through and trapping.
        let inputIds2D = inputIds.ndim == 1 ? inputIds[.newAxis, 0...] : inputIds

As we move to batched evaluation, we probably always want [B, L] going into prepare. Some options:

  • These three models could normalize like Qwen3VL does, before the warm/cold routing check. This is the minimal fix and seems right for this PR.
  • Longer term, normalize once at the boundary, for example in LMInput or where prepare is called, and document [B, L] as the shape. That needs the LLM path to move at the same time: the default prepare in LLMModel.swift and prefill currently assume rank-1 (y[.newAxis, range], remaining[text: .newAxis]), so I'd do it as a follow-up.
  • Promoting to [1, L] in ChatSession alone would break those same LLM paths, so I don't think that's an option on its own.

Either way, a test that feeds a rank-1 suffix on a warm cache would cover the path production
uses. The new continuation tests all use [1, L].

@ronaldmannak FYI as this touches on the batch work you are doing

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I guess the problem is that this now changes the dimensions of the input -- if ChatSession preserved the dimensions that would be another approach. I still think that we need to sort out the input dimensions, but this might be a more focused fix.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Thanks, the repro tests helped. Going one level down: ChatSession built every reuse suffix as [L] from a Swift [Int], so a warm turn could get a different shape than a cold turn. Qwen2/2.5-VL picked their warm path by checking for 2-D input and dropped the rope delta otherwise. Qwen3-VL-MoE never made its input 2-D. The Qwen3-VL-MoE crash is already on main for a plain second text-only turn (your ChatSession repro passes on main only because that template triggers a rewind, which main rebuilds). This PR added the trim path and the text-after-image path.

I did both fixes in ad1ae5c: ChatSession now slices preparedInput.text.tokens[.ellipsis, start...], so suffixes keep the processor's shape, and the three models make the input 2-D before choosing a path, like Qwen3VL. A warm turn now sends the model the same shape as a cold turn, which every model must already accept, so LLMs keep getting [L].

I would leave settling on [B, L] everywhere for a follow-up, maybe with @ronaldmannak's batching work. It means changing the LLM prepare/prefill paths at the same time. Warm prefill of more than one row on Qwen2/2.5-VL still drops the rope delta, so that belongs there too.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

About the tests for the rank-1 path: ChatSessionSuffixRankTests runs real two-turn sessions against a cold one (Qwen2.5-VL text after an image; Qwen3-VL-MoE on both the append and trim paths). ContinuationAssertions now runs the warm text and image checks with both [1, L] and [L] for every Qwen-VL model and GLM-OCR. Without the model change the continuation checks fail; without either change the session tests crash.

@davidkoski davidkoski left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Change looks good, but see my comment in ChatSession -- I had claude generate some tests to explore that (if it is useful):

ReproTests.swift.zip

I think this is an issue here, but see what you think. Thanks!

@aleroot
aleroot force-pushed the reuse-cache-after-image-turns branch from 833eae6 to ad1ae5c Compare December 3, 2026 05:49
@aleroot

aleroot commented Dec 3, 2026

Copy link
Copy Markdown
Contributor Author

By the way... force-push hit "Reset CI state", which now fails because GitHub blocks pull_request_target on public repos by default since Dec 2 (https://gh.io/securely-using-pull_request_target#default-policy-for-pull_request_target). The labels weren't reset, so this PR needs needs-ci re-added by hand. Allowing the event in an Actions policy, or moving the reset to workflow_run like ci-state.yml, would fix it for every PR. Maybe @thechriswebb can help?

@davidkoski

Copy link
Copy Markdown
Member

The org recently changed some of its auth, so maybe fallout from that. In the meantime I will try and keep an eye on these CI runs (or lack of).

@davidkoski davidkoski left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Changes look good, thank you!

@davidkoski
davidkoski merged commit f718469 into ml-explore:main Dec 3, 2026
5 of 6 checks passed
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