Skip to content

Fix BatchRotatingKVCache mask for multi-token updates after the window wraps - #2076

Open
avifenesh wants to merge 1 commit into
ml-explore:mainfrom
avifenesh:fix/batch-rotating-wrapped-mask
Open

avifenesh wants to merge 1 commit into
ml-explore:mainfrom
avifenesh:fix/batch-rotating-wrapped-mask

Conversation

@avifenesh

@avifenesh avifenesh commented Nov 18, 2026 •

Copy link
Copy Markdown

BatchRotatingKVCache.make_mask drops the oldest valid key of a left-padded row on every multi-token update after its sliding window wraps.

For N > 1 the mask trims the left padding by _idx - max_size + 1. After a wrap, _idx is the ring cursor. But update_and_fetch first puts the ring back in temporal order, so the length becomes the buffer length, and then drops that many oldest columns. The mask still uses the cursor, so the padding it trims is off by the cursor position and the row's first real key gets masked.

The fix uses the buffer length for a multi-token update of a rotated cache. Single-token updates and caches that have not wrapped are unchanged.

Tests:

  • New test_batch_rotating_wrapped_multi_token_matches_single_row: a left-padded row of a batch window that wraps in place, then gets 3-token updates, has to attend exactly like the same row in its own RotatingKVCache. It fails on main and passes with the fix.
  • test_batch_rotating_kv_cache expected the buggy mask for the 2-token update after the wrap. That update drops one padding slot, so the first real key is column 2, not 3. I changed the expected mask; the new test checks the same case against a single-row cache.
  • python -m unittest tests.test_prompt_cache: 26 passed. Without the fix both tests above fail.

This came up in oMLX (jundot/omlx#5235), where batched speculative verify over sliding-window layers takes this path. mlx-vlm has the same code; the same fix there is Neywa-Labs/mlx-vlm#2757.

…al length

For N > 1, make_mask trims the left padding by _idx - max_size + 1. After the
window wraps, _idx is the ring cursor, but the update first puts the ring in
temporal order (the length becomes the buffer length) and then drops that many
oldest columns, so a left-padded row lost its oldest valid key.

Co-Authored-By: Claude Opus 5.5 <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