Skip to content

ChatSession: reuse the KV cache for append-only media turns - #515

Merged
davidkoski merged 1 commit into
ml-explore:mainfrom
NivDvir:feat/append-only-media-cache-reuse
Sep 14, 2026
Merged

davidkoski merged 1 commit into
ml-explore:mainfrom
NivDvir:feat/append-only-media-cache-reuse

Conversation

@NivDvir

@NivDvir NivDvir commented Aug 6, 2026 •

Copy link
Copy Markdown
Contributor

Proposed changes

A turn that adds a new image to an unchanged transcript extends the cached prefix exactly as a text turn does, but #472 excludes every media turn from reuse, so it re-prefills the whole transcript and re-runs the vision tower over every cached image. (The figure in the comments below shows it.)

  • PreparedInputSplitting: an opt-in protocol for models that can split their prepared input at a token boundary, keeping only the suffix's media.
  • AppendOnlyMediaRule in PromptCacheReusePolicy: fires when the turn carries new media, extends the cached prefix, and no speculative decoding is configured. ChatSession asks the model to split, verifies the returned tokens against the boundary, and downgrades to .rebuild otherwise. The trim path is untouched, so the Fix structured ChatSession continuations #472 guard still holds.
  • Qwen25VL conforms: its vision mask isolates each frame, so dropping a cached image leaves the remaining features unchanged -- testQwen25VLAppendOnlyMediaSplitMatchesFullPrefill checks warm split against cold prefill on a tiny random-weight model. Qwen2VL attends across images and does not conform; testQwen2VLAppendOnlyMediaSplitDiverges shows why.
  • Refused, and rebuild as before: video, temporal grids, audio, precomputed position ids, non-uniform masks, a boundary inside a media block. No other model changes.

Overlaps #581 in the reuse switch; happy to rebase across it if that lands first. No speedup is claimed; cost is stated in prompt tokens and encoder passes only.

Checklist

  • 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: Yes, I used Claude Code for parts of this. I reviewed and understand all of it.

@NivDvir
NivDvir force-pushed the feat/append-only-media-cache-reuse branch from 19f5150 to 75d3e5e Compare August 9, 2026 06:24
@NivDvir

NivDvir commented Aug 9, 2026

Copy link
Copy Markdown
Contributor Author

Rebased onto main — though the PromptCacheReusePolicy refactor replaced the inline block this patched, so it is a redesign rather than a rebase.

It now fits the new shape: an appendMediaSuffix decision case, an AppendOnlyMediaRule, and a canSplitPreparedMedia fact on PromptCacheTurn that keeps the policy free of MLX and model types. The split can be declined per input, so it is verified and downgraded to .rebuild before prefilling — the same treatment trimToCommonPrefix gets.

One deliberate difference from ExtendCachedPrefixRule: the media path does not require the absence of an attention mask. A VL processor pairs media with an all-ones mask, so that guard would disable the path for the inputs it exists to serve; the splitter rejects anything that is not all-ones.

@NivDvir
NivDvir force-pushed the feat/append-only-media-cache-reuse branch from 75d3e5e to 59d0c71 Compare August 10, 2026 19:04
Comment thread Libraries/MLXVLM/Models/QwenVL.swift Resolved
Comment thread Libraries/MLXLMCommon/ChatSession.swift Resolved

@aleroot aleroot left a comment

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.

The core approach looks sound, I would suggest to rebase against main again as there have been a few changes last few days and look at the comments, for the rest it seems ok.

@NivDvir
NivDvir force-pushed the feat/append-only-media-cache-reuse branch from 59d0c71 to 3845c86 Compare August 15, 2026 23:40
NivDvir added a commit to NivDvir/mlx-swift-lm that referenced this pull request Aug 15, 2026
Both from review on ml-explore#515.

`splitVisionPayload` accepted a `t > 1` grid carried in the image payload,
although the refusal `splitPreparedInput` documents for video rests on the
same fact — the vision full-attention mask mis-accumulates `cuSeqlens`
across temporal slices, so those rows are not independently reusable.
The video guard only caught the usual carrier. Require `t == 1` per frame.

`ChatSession` checked only that the splitter returned a value. The ledger
advances to `representedTokens` on the strength of the requested boundary,
so a conformer returning any other suffix would have it prefilled verbatim
and leave the record describing a cache that was never built. Compare the
returned tokens against `promptTokenIds[suffixStart...]` and downgrade to
`.rebuild` on any mismatch, the same treatment a declined split gets.

Also updates the two wrapper mocks that forward to `base.newCache`, which
is now throwing on main.
@NivDvir

NivDvir commented Aug 16, 2026

Copy link
Copy Markdown
Contributor Author

Context for the reviewer, from running this branch head (3845c86) on real weights
(Qwen3-VL-4B-4bit, 10-row grounding protocol, decision instrumented per turn):

Two coverage observations, both by design of the current diff, recorded here so the review
can weigh them deliberately rather than discover them later:

  1. Qwen3-VL is outside the conformance set (only Qwen25VL conforms; Qwen2VL is
    deliberately excluded — its unmasked vision attention makes a split unsound, as the
    in-code comment explains). For Qwen3-VL the exclusion is only conservatism: its vision
    attention is block-diagonal over cuSeqlens with correct per-frame accumulation, so
    items are feature-isolated, and deepstack needs no split handling at all — it never
    appears in a prepared input; the model recomputes it from the pixels each forward. I
    have the conformance ready on a branch
    (feat/qwen3vl-prepared-input-splitting:
    extension + position-equivalence tests against Qwen3-VL's own getRopeIndex + an
    end-to-end split-continuation test for both conformers), validated on real weights:
    10/10 warm turns take appendMediaSuffix, grounding parseable on every row, cold
    outputs byte-identical.

  2. Text-only turns after a media turn still rebuild, for every VL model including the
    conforming one.
    Observed turn facts: newMedia=false preparedMedia=true mask=true extendsPrefix=true → rebuild. The transcript's earlier image is re-prepared each turn
    with its all-ones mask; ExtendCachedPrefixRule refuses on the mask, and
    AppendOnlyMediaRule requires carriesNewMedia=true, so neither serves the shape —
    although a conforming model's splitter would carve a media-less suffix trivially.
    Fixable by letting AppendOnlyMediaRule (or a sibling rule) also accept
    carriesNewMedia=false when the model can split; not done in this diff.

Neither observation regresses anything (rebuild is today's behavior); they bound what the
diff speeds up. Happy to open the Qwen3-VL follow-up once this lands.

@NivDvir
NivDvir force-pushed the feat/append-only-media-cache-reuse branch from 3845c86 to 71e34b8 Compare August 20, 2026 03:29
NivDvir added a commit to NivDvir/mlx-swift-lm that referenced this pull request Aug 20, 2026
Both from review on ml-explore#515.

`splitVisionPayload` accepted a `t > 1` grid carried in the image payload,
although the refusal `splitPreparedInput` documents for video rests on the
same fact — the vision full-attention mask mis-accumulates `cuSeqlens`
across temporal slices, so those rows are not independently reusable.
The video guard only caught the usual carrier. Require `t == 1` per frame.

`ChatSession` checked only that the splitter returned a value. The ledger
advances to `representedTokens` on the strength of the requested boundary,
so a conformer returning any other suffix would have it prefilled verbatim
and leave the record describing a cache that was never built. Compare the
returned tokens against `promptTokenIds[suffixStart...]` and downgrade to
`.rebuild` on any mismatch, the same treatment a declined split gets.

Also updates the two wrapper mocks that forward to `base.newCache`, which
is now throwing on main.
@NivDvir
NivDvir force-pushed the feat/append-only-media-cache-reuse branch from 71e34b8 to 431c2d0 Compare August 27, 2026 23:43
NivDvir added a commit to NivDvir/mlx-swift-lm that referenced this pull request Aug 27, 2026
Both from review on ml-explore#515.

`splitVisionPayload` accepted a `t > 1` grid carried in the image payload,
although the refusal `splitPreparedInput` documents for video rests on the
same fact — the vision full-attention mask mis-accumulates `cuSeqlens`
across temporal slices, so those rows are not independently reusable.
The video guard only caught the usual carrier. Require `t == 1` per frame.

`ChatSession` checked only that the splitter returned a value. The ledger
advances to `representedTokens` on the strength of the requested boundary,
so a conformer returning any other suffix would have it prefilled verbatim
and leave the record describing a cache that was never built. Compare the
returned tokens against `promptTokenIds[suffixStart...]` and downgrade to
`.rebuild` on any mismatch, the same treatment a declined split gets.

Also updates the two wrapper mocks that forward to `base.newCache`, which
is now throwing on main.
NivDvir added a commit to NivDvir/mlx-swift-lm that referenced this pull request Aug 29, 2026
Both from review on ml-explore#515.

`splitVisionPayload` accepted a `t > 1` grid carried in the image payload,
although the refusal `splitPreparedInput` documents for video rests on the
same fact — the vision full-attention mask mis-accumulates `cuSeqlens`
across temporal slices, so those rows are not independently reusable.
The video guard only caught the usual carrier. Require `t == 1` per frame.

`ChatSession` checked only that the splitter returned a value. The ledger
advances to `representedTokens` on the strength of the requested boundary,
so a conformer returning any other suffix would have it prefilled verbatim
and leave the record describing a cache that was never built. Compare the
returned tokens against `promptTokenIds[suffixStart...]` and downgrade to
`.rebuild` on any mismatch, the same treatment a declined split gets.

Also updates the two wrapper mocks that forward to `base.newCache`, which
is now throwing on main.
@NivDvir
NivDvir force-pushed the feat/append-only-media-cache-reuse branch from 431c2d0 to 5b78e44 Compare August 29, 2026 12:55
@NivDvir

NivDvir commented Sep 6, 2026

Copy link
Copy Markdown
Contributor Author

A picture of the change, for anyone reading the description cold. Nothing in the PR moved; this is the same before/after the text above describes, drawn.

What a media turn costs — before and after #515

Green is the prefix kept in the KV cache, orange is what the turn prefills. Before: a new screenshot re-prefills every earlier one and re-runs the vision tower over it. After: the cached prefix stays and only the suffix is prefilled — one encoder pass per turn at any conversation length, Qwen2.5-VL only, with every unsafe shape still rebuilding as listed above. The figures at the bottom are the ones already in the description.

@aleroot

aleroot commented Sep 6, 2026

Copy link
Copy Markdown
Contributor

@NivDvir nice picture 😉

A turn that adds a new image to an unchanged transcript extends the cached
prefix exactly as a text turn does, but ml-explore#472 excludes every media turn from
reuse, so it re-prefills the whole transcript and re-runs the vision tower
over every cached image.

Add PreparedInputSplitting, an opt-in protocol for models that can split
their prepared input at a token boundary and keep only the suffix's media.
AppendOnlyMediaRule fires when the turn carries new media, extends the
cached prefix, and no speculative decoding is configured; ChatSession asks
the model to split, verifies the returned tokens against the boundary, and
downgrades to .rebuild otherwise.

Qwen2.5-VL conforms: its vision mask isolates each frame, so dropping a
cached image leaves the remaining features unchanged (tested on a tiny
random-weight model). Qwen2-VL attends across images and does not conform;
the same test shows the divergence. Video, temporal grids, audio,
precomputed position ids, non-uniform masks, and boundaries inside a media
block are refused and rebuild as before. No other model changes.
@NivDvir
NivDvir force-pushed the feat/append-only-media-cache-reuse branch from 5b78e44 to 0481212 Compare September 6, 2026 18:36
@NivDvir

NivDvir commented Sep 6, 2026

Copy link
Copy Markdown
Contributor Author

@aleroot rebased on main and squashed to one commit; added the vision-tower test you'd have wanted (testQwen25VLAppendOnlyMediaSplitMatchesFullPrefill, and the Qwen2-VL counterexample). Aware this overlaps #581 in the reuse switch -- happy to rebase across it if that lands first.

@aleroot

aleroot commented Sep 7, 2026

Copy link
Copy Markdown
Contributor

@NivDvir you have done a nice work here. If I was to decide I would probably merge this before #581 and then rebase #581 on top the new main ... Thanks for this, I think it is a quality pull request from my point of view.

@aleroot aleroot mentioned this pull request Sep 11, 2026
1 task done

@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 3e6ea1e into ml-explore:main Sep 14, 2026
5 checks passed
wballard added a commit to swissarmyhammer/mlx-swift-lm-old that referenced this pull request Sep 14, 2026
Apply the upstream commits e3d4a20..3e6ea1e as a 3-way patch. CLAUDE.md is
excluded.

- db05290 Let training differentiate the gated-delta recurrence (ml-explore#616)
- 4c3d793 Emit only the new scalars when a token extends the previous character (ml-explore#613)
- 1012230 Gemma 4 VLM: fuse float32 logit softcapping (ml-explore#615)
- 9ce5b4f Fix generation loop blocking Swift cooperative workers (ml-explore#611)
- 238ad74 Add configuration-based LoRA metadata discovery (ml-explore#597)
- 604fae7 RotatingKVCache: make trim wrap-aware instead of corrupting the ring (ml-explore#584)
- a56aee3 Add bounded cross-dialect tool-call recovery (ml-explore#548)
- 3e6ea1e Reuse the KV cache for append-only media turns (ml-explore#515)

Conflict resolutions:

- Evaluate.swift: keep the shared generateSpeculativeStream helper. It now
  receives parameters and tools, and passes tools and toolCallPolicy to
  TextToolTokenLoopHandler for the draft-model and MTP paths.
- PromptCacheReusePolicy.swift: keep the package access of the turn fields,
  and make canSplitPreparedMedia package also. reconcilePromptCache has no
  prepared input to split, thus it answers .appendMediaSuffix with nil.
- ToolCallFormat.swift: keep buffersEntireResponse and add supportsBareJSON.
- ToolCallProcessor.swift: the buffersEntireResponse check stays first in
  processChunk. The recovery scanner path comes after it.

Follow-up changes:

- AllowedToolOutputRouter: join adjacent response outputs into one event.
  The recovery scanner can divide response text at a "<" that does not
  start a call.
- Gemma4FusionTests: delete testFusionLatency. It runs only when an
  environment variable is set, and stable runs no skipped tests.

Tests: all five bundles pass with no skipped test (MLXLMTests 1170 Swift
Testing + 693 XCTest, MLXGuidedGenerationTests 70, MLXFoundationModelsTests
213, CXGrammarTests 7, MLXHuggingFaceMacrosTests 5).

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01TEgdBA8Ap14pU1EfmHkazD
@NivDvir

NivDvir commented Sep 15, 2026

Copy link
Copy Markdown
Contributor Author

Merged! 🐐 Thank you, @davidkoski.

@NivDvir NivDvir mentioned this pull request Sep 17, 2026
4 of 5 tasks
djandrewgibbons pushed a commit to djandrewgibbons/mlx-swift-lm that referenced this pull request Sep 26, 2026
A turn that adds a new image to an unchanged transcript extends the cached
prefix exactly as a text turn does, but ml-explore#472 excludes every media turn from
reuse, so it re-prefills the whole transcript and re-runs the vision tower
over every cached image.

Add PreparedInputSplitting, an opt-in protocol for models that can split
their prepared input at a token boundary and keep only the suffix's media.
AppendOnlyMediaRule fires when the turn carries new media, extends the
cached prefix, and no speculative decoding is configured; ChatSession asks
the model to split, verifies the returned tokens against the boundary, and
downgrades to .rebuild otherwise.

Qwen2.5-VL conforms: its vision mask isolates each frame, so dropping a
cached image leaves the remaining features unchanged (tested on a tiny
random-weight model). Qwen2-VL attends across images and does not conform;
the same test shows the divergence. Video, temporal grids, audio,
precomputed position ids, non-uniform masks, and boundaries inside a media
block are refused and rebuild as before. No other model changes.
div0-space pushed a commit to LibraxisAI/mlx-swift-lm that referenced this pull request Nov 29, 2026
…kling-sampler

Land Inkling 2 Mini (ml-explore#488–ml-explore#503) and the CBv2 sampling fix (ml-explore#505) for provider 0.10.18
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.

4 participants