Repository navigation
ChatSession: reuse the KV cache for append-only media turns - #515
Conversation
19f5150 to
75d3e5e
Compare
|
Rebased onto main — though the It now fits the new shape: an One deliberate difference from |
75d3e5e to
59d0c71
Compare
aleroot
left a comment
There was a problem hiding this comment.
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.
59d0c71 to
3845c86
Compare
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.
|
Context for the reviewer, from running this branch head ( Two coverage observations, both by design of the current diff, recorded here so the review
Neither observation regresses anything ( |
3845c86 to
71e34b8
Compare
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.
71e34b8 to
431c2d0
Compare
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.
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.
431c2d0 to
5b78e44
Compare
|
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. 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. |
|
@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.
5b78e44 to
0481212
Compare
davidkoski
left a comment
There was a problem hiding this comment.
Changes look good, thank you!
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
|
Merged! 🐐 Thank you, @davidkoski. |
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.
…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

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.AppendOnlyMediaRuleinPromptCacheReusePolicy: fires when the turn carries new media, extends the cached prefix, and no speculative decoding is configured.ChatSessionasks the model to split, verifies the returned tokens against the boundary, and downgrades to.rebuildotherwise. The trim path is untouched, so the Fix structured ChatSession continuations #472 guard still holds.Qwen25VLconforms: its vision mask isolates each frame, so dropping a cached image leaves the remaining features unchanged --testQwen25VLAppendOnlyMediaSplitMatchesFullPrefillchecks warm split against cold prefill on a tiny random-weight model.Qwen2VLattends across images and does not conform;testQwen2VLAppendOnlyMediaSplitDivergesshows why.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
pre-commit run --all-filesto format my code / installed pre-commit prior to committing changesAI usage