Skip to content

Attend a rotating cache with a rewind reserve in place - #727

Merged
davidkoski merged 1 commit into
ml-explore:mainfrom
aleroot:alessio/rotating-rewind-reserve-in-place
Nov 26, 2026
Merged

davidkoski merged 1 commit into
ml-explore:mainfrom
aleroot:alessio/rotating-rewind-reserve-in-place

Conversation

@aleroot

@aleroot aleroot commented Oct 24, 2026 •

Copy link
Copy Markdown
Contributor

Proposed changes

When a chat gets long, the app can only remember the last few thousand tokens at a time, and normally that means it can never undo a step so after a tool call the model has to re-read the whole conversation from scratch, which on granite model for example costs over a minute of "thinking" before it answers. In the past we gave the cache a small rewind reserve, so it can step back and skip that re-read. The catch was that carrying those footprints slowed down every single generated word by about a quarter. This change keeps the footprints in a separate spare area the model doesn't look at, so generation runs at full speed again while the rewind ability stays.

#622 made rotating caches rewindable by giving them a reserve of rows past the window: the exact fix a tool-call follow-up needs once the ring has wrapped. But the reserve taxed every generated token.

This stacks cleanly with #716, whose checkpoints make a rewind unnecessary for the templates that drop reasoning; with both, a small reserve covers the remaining tool-call re-renders.

Measurements

Apple M2, 16 GB. granite-4.1-8b-4bit, an 8,192-token rotating cache
(pinned prefix 4), 8,344-token prompt then 256 greedy tokens, warm runs:

Cache Before (main) After (this PR)
No reserve 11.88–12.03 tok/s 11.95–11.97 tok/s
Reserve 1,024 8.80–8.85 tok/s 11.54–11.64 tok/s

A reserve now costs ~3% instead of ~26%.

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:

A rewind reserve (ml-explore#622) lets a rotating cache step back across its window
edge, but it also taxed every generated token: update(keys:values:)
returned retainedView(tail:), a fresh concatenation of the pinned prefix
and the window tail, in every layer on every decode step. On
granite-4.1-8b-4bit with an 8,192-token window and a 1,024-token reserve
that copy is about 1.3 GB per token, and decode fell from 12.0 to 8.8
tok/s.

RotatingKVCache now implements KVCacheAttentionProtocol. A one-token
write with a reserve and no caller mask goes through updateAndAttend,
which writes into the ring and attends it in place with a mask over the
reserve rows. Multi-token writes, caller-supplied masks and caches
without a reserve keep the existing update(keys:values:) path unchanged.
retainedView and the new mask share one retainedRanges(tail:) helper, so
they cannot disagree about which rows make up the window.

Without a reserve the generated text is byte-identical. With one, the
copy is gone: 11.5-11.6 tok/s against 11.9-12.0 without, instead of 8.8.

@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.

This looks great, thank you!

@davidkoski
davidkoski merged commit fa4c14a into ml-explore:main Nov 26, 2026
4 checks passed
wballard added a commit to swissarmyhammer/mlx-swift-lm that referenced this pull request Nov 30, 2026
Apply the upstream commits a2b47a7..026d599 (the 6 after 6759555) as
cherry-picks. CLAUDE.md is untouched. Where a conflict was only a fork
refactor, upstream's code is taken; the fork's MTP speed and prompt-cache
behavior is kept.

- a2b47a7 Batching: Use per-row rotary positions and attention scaling in LLM and VLM models (ml-explore#773)
- b4cc88a Select LFM2-MoE experts in mlx-lm's argpartition order (ml-explore#830)
- 9e0f27d Expand the segsum batch mask once, as mlx-lm does (ml-explore#829)
- 4d2d8a3 Report the full-vocabulary entropy with token log probabilities (ml-explore#822)
- fa4c14a Attend a rotating cache with a rewind reserve in place (ml-explore#727)
- 026d599 Bonsai 2.5: Rotate Hadamard-quantized activations in one Metal pass (ml-explore#835)

Conflict resolutions:
- ml-explore#773: the Qwen 3.5 VLM decode positions take upstream's
  QwenVL.decodePositionIds; the fork's version differed only by the
  MRopeAxis.count name.
- ml-explore#830: LFM2MoeRoutingTests keeps the fork's removal of the unused
  TokenizerLoaderStub and takes upstream's makeConfig(numExpertsPerToken:).
- ml-explore#822: the Evaluate.swift hunks go into the fork's GenerateParameters.swift
  (GenerateTokenLogProbabilities.entropy) and TokenIterators.swift
  (DeferredTokenLogProbabilities). The speculative log-probability test is
  not taken: the fork's SpeculativeTokenIterator reports no log
  probabilities, and the doc keeps saying so.
- ml-explore#727: the KVCache.swift hunks go into the fork's RotatingKVCache.swift
  (retainedRanges over the fork's rowRanges, so the window mask also leaves
  out vacant rows after a rewind). RotatingKVCache does NOT conform to
  KVCacheAttentionProtocol: the fork's prefill kernel, DeepSeek-V4 and
  Inkling 2 read a conforming cache as one that owns its attention (Inkling 2
  stops with a precondition). attentionWithCacheUpdate calls
  RotatingKVCache.updateAndAttend directly, and passes the fork's sinks
  through. The Qwen MTP drafter attends through PrefillAttentionKernel and
  keeps update(keys:values:). Two tests cover the sinks and the
  non-conformance.

After-merge steps: no merged model adds advance( with a manual offset +=,
no new MambaCache/ArraysCache model type, no environment-gated test.

Tests: all five bundles pass under xctest (MLXLMTests 1272 XCTest + 2865
Swift Testing, MLXGuidedGenerationTests 96, MLXFoundationModelsTests 770,
CXGrammarTests 7, MLXHuggingFaceMacrosTests 11).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
aleroot added a commit to aleroot/mlx-swift-lm that referenced this pull request Nov 30, 2026
RotatingKVCache conforms to KVCacheAttentionProtocol since ml-explore#727, so the
precondition that rejects self-attending caches trapped on Inkling 2's own
rotating caches. Inkling 2 reads the ring through update(keys:values:),
which ml-explore#727 left unchanged, so treat rotating caches as plain caches.
@aleroot aleroot mentioned this pull request Nov 30, 2026
5 tasks done
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