Skip to content

Drop trimmed entries in ConcatenateKVCache.trim - #2089

Open
andyrost wants to merge 1 commit into
ml-explore:mainfrom
andyrost:fix-concatenate-cache-trim
Open

andyrost wants to merge 1 commit into
ml-explore:mainfrom
andyrost:fix-concatenate-cache-trim

Conversation

@andyrost

@andyrost andyrost commented Nov 21, 2026 •

Copy link
Copy Markdown

I serve models using MLX-LM on my M5 Max Macbook Pro with 48GB of memory. I have them lean on cache rollback, and with speculative decoding I looked at using the trim function to drop rejected tokens. I also trim saved prompt cache back to the common prefix when a new request shares only part of an earlier prompt. I found that ConcatenateKVCache.trim(n) does only self.offset -= n , while leaving keys and values at full length. Other caches do not have this problem as they write at offset into a preallocated buffer and returns a slice up to offset.

ConcatenateKVCache works differently: update_and_fetch calls mx.concatenate([self.keys, keys], axis=-2) and sets self.offset = self.keys.shape[-2] . keys_and_values() returns the stored arrays unsliced. At the next update, trimmed entries are back in keys + values and the offset is reset to count them so the trim is undone.

This affects afm7 which puts this cache on the last layer.

This PR has trim(), after lowering the offset, slice keys and values to [..., :self.offset, :] when n > 0. It also adds a test.

  • ☑️ I understand it is strictly prohibited to use AI to write PR description
  • AI usage disclosure: Claude Fable 5.2 audited, reviewed, and after finding this issue, I had it apply the fix and the test.

trim() lowered the offset but kept the keys and values, so the next
update_and_fetch concatenated onto the untrimmed arrays and reset the
offset to their full length.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant