Skip to content

Batching: Add sliding-window batching with BatchRotatingKVCache - #776

Open
ronaldmannak wants to merge 29 commits into
ml-explore:mainfrom
ronaldmannak:batching/a2-batch-rotating-kvcache
Open

ronaldmannak wants to merge 29 commits into
ml-explore:mainfrom
ronaldmannak:batching/a2-batch-rotating-kvcache

Conversation

@ronaldmannak

Copy link
Copy Markdown
Contributor

Proposed changes

This PR adds BatchRotatingKVCache which keeps each row's sliding attention window while preserving its logical position: window wrap, ragged prefill, filtering, compatible extension and extraction, with a single-token decode path.
Window, allocation-step and capacity-origin compatibility is validated before extension, and batched windows report through cache capacity and status. Pinned prefixes and rewind reserves are refused.

Merge #775 before this one. Part of decode batching #771

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:

ronaldmannak and others added 11 commits November 6, 2026 17:18
Gemma 2 scores grouped queries as [B, kv, repeats, L, S]. A cache whose mask carries one row per sequence, shape [B, 1, L, S], aligned its batch axis with the key-value heads, so row b masked head b of every sequence. Give such a mask the head-group axis before applying it.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Benchmarks/DecodeBench times greedy decode of TokenIterator on a local model as a median over rounds, so a change to the decode path can be compared with its base. MLX_SWIFT_LM_PATH points it at another checkout.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Move the per-row mask regression into Gemma2Tests and reuse its tiny model. Extract the standalone decode benchmark from the functional stack for separate review.

Co-authored-by: Codex <noreply@openai.com>
Every model this change edits now has a test in RoPEApplicationTests that
prefills two text rows of different lengths alone, joins their caches in the
stand-in RowOffsetCache and decodes three tokens, comparing each row with the
same sequence continued alone: Gemma 4 (with KV-shared layers), Idefics3,
LFM2-VL, Mistral 3 VLM (with Llama 4 scaling), MuseGlimmer, Pixtral, Qwen 2 VL
and Qwen 2.5 VL, and, in LLMRowPositionTests, Mistral 3 text and Nemotron Labs
Diffusion, whose Llama 4 scaling buckets differ between the rows' positions.
The helper steps through nextTokenLogits so the Qwen models, which have no
plain forward, take the same path.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Two six-token Llama rows, each behind two positions of left padding, fill a
BatchKVCache eight positions wide. The rows share position six, so the cache
takes the scalar RoPE path, which must use that logical position rather than
the buffer's offset of eight; three decoded tokens per row match the rows
continued alone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The row-position tests below this change now build the same tiny Qwen 2 and
2.5 VL text models, so QwenVLBatchedPositionTests uses their
QwenVLTextFamily and tinyQwenVLText(_:) instead of declaring identical copies.
The test itself is unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
filter drops the left padding every remaining row shares. A left-padded
prompt fed in chunks can be filtered before all of its padding is written,
and the drop then went past the buffer: offset turned negative. It is now
bounded by the offset, as mlx-vlm bounds min_left_pad by _idx; the new test
filters after two of three and four padding positions and fails without the
bound (offset -1 instead of 0).

extract checks its row index with a precondition, as mlx-vlm raises an
IndexError, and the places that follow mlx-vlm's port (right padding filtered
with the rows, the all-empty merge) cite mlx_vlm/models/cache.py pinned at
mlx-vlm dcea787 next to the existing mlx-lm references.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
QwenVLBatchedPositionTests moves unchanged to the end of
RoPEApplicationTests.swift, next to the QwenVLTextFamily and tinyQwenVLText
helpers it uses; QwenVLBatchedPositionTests.swift is deleted. No assertion
changes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Reject positive staged rounds while a row still has unconsumed left padding or the batch has no rows. Preserve zero-width no-op rounds and ordinary cache trimming. Cover safe refusal and exact rollback/partial commit with position-stamped cache state.

AI assistance: implemented and validated with Codex for this origin fork.
ronaldmannak and others added 8 commits November 6, 2026 21:20
KVCache and BaseKVCache no longer carry filter, extend, validateExtension,
extract and merge, so no cache inherits row methods that trap. The new
BatchableKVCache protocol declares them, BatchKVCache conforms, and
mergeCaches returns a BatchableKVCache: a KVCacheSimple row merges into a
BatchKVCache, a cache that is its own batch merges through its own class,
and any other cache throws KVCacheError.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- createCausalMask keeps main's public signature; the left-padding form is an
  internal overload that BatchKVCache.makeMask calls. The query range is a
  slice of the key range instead of a second array.
- BatchKVCache.merge throws KVCacheError before slicing or concatenating when a
  row is not paired 4-D keys and values with one row, or disagrees with the
  first populated row on heads, widths or dtype. KVCacheSimple.merge stops with
  the same message.
- BatchKVCache.extract returns an empty KVCacheSimple for a row whose padding
  covers every written position, and requires a finalized batch.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
extract read the row's padding and position through MLXArray subscripts,
which do not trap past the batch: extract(2) on a two-row batch returned a
cache built from out-of-range metadata. It now checks the index with a
precondition, as mlx-vlm's BatchKVCache.extract raises an IndexError; the new
exit test fails without it (the process exits successfully).

The places that follow mlx-vlm's port (lengths filtered with the rows, the
window check and the all-empty merge) cite mlx_vlm/models/cache.py pinned at
mlx-vlm dcea787 next to the existing mlx-lm references.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ests.swift

BatchedSlidingWindowParityTests and its helpers move to the end of
BatchRotatingKVCacheTests.swift; BatchedSlidingWindowParityTests.swift is
deleted. No assertion changes. Two lines differ from a plain move: the target
file now imports MLXLLM (@testable, as the old file did) for the tiny Gemma 3
text model, and tinyGemma3() names MLXLLM.Gemma3TextConfiguration, since the
target's MLXVLM import declares a Gemma3TextConfiguration of its own.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Keep sliding-window and eviction checks while refusing positive staged writes for negative row positions or zero rows. Preserve empty rounds and verify exact retained state and timeline alignment after supported rollback and partial commit.

AI assistance: implemented and validated with Codex for this origin fork.
The rotating batch's row methods implement BatchableKVCache instead of
overriding BaseKVCache stubs, and its merge takes exactly RotatingKVCache
rows. mergeCaches maps a RotatingKVCache row to BatchRotatingKVCache;
RotatingKVCache itself no longer has a merge that returns any KVCache.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- BatchRotatingKVCache.extract clamps the slice start to the written range, so
  a row whose padding is past it comes back empty with the batch's window, step
  and capacity origin instead of trapping. It requires a finalized batch.
- RotatingKVCache.merge throws KVCacheError before extending when an input
  holds more than one row or differs from the first prefilled row in heads,
  widths or dtype, instead of stopping in concatenation.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@ronaldmannak
ronaldmannak force-pushed the batching/a2-batch-rotating-kvcache branch from 4392aff to 081b109 Compare November 8, 2026 03:39
Cover both layer orders with a Release regression test. Codex assisted with the implementation and Release verification.
ronaldmannak and others added 2 commits November 11, 2026 22:50
BatchKVCache used the inherited offset as its write cursor, so it reported
the buffer width, padding included, while every other cache reports a
position. Cache storage worked around that by reading per-row positions
from the batch, which pulled MLX and a readback into KVCacheTree.

The write cursor is now a private idx, and offset is the longest row's
position, read from the host-side positions. KVCachePlan.swift and
KVCacheTree.swift go back to reading cache.offset, as on main.

A batch whose rows all carry padding is where the two differ: two rows of
six tokens behind two columns of padding report 6, in a buffer 8 wide.

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

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
ronaldmannak and others added 3 commits November 11, 2026 22:55
Cache storage no longer compares per-row positions, so the storage tests
stop asking it to: the reordered-rows and row-count rejections go, and
the ragged pair is kept as an adoption test at the longest row. The
padded pair now reports 6 and 7 from BatchKVCache.offset, as the rotating
cache already did.

What the removed checks stood for is tested on real operations instead:
the Gemma 3 merge test extends its live batch with two prefilled rows,
removes the longest row, and checks positions on every layer, the
extracted keys and values, and the next logits against solo caches.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
The offset counts tokens only once a prefill is finalized: during a ragged prefill every row advances by the chunk's width, right padding included, until finalize() turns that into left padding.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
ronaldmannak and others added 2 commits November 11, 2026 23:45
The status switch had moved the upstream rotating case to the end and told a sliding window apart by its layer kind. The rotating case is back where main has it, and a rotating batch joins it by type. The capacity check gets back the comment that explains why a requested prefix never matches a batch.

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

The switch had been wrapped in an if, which re-indented every upstream line. A rotating batch is now handled inside the default branch, so only that branch changes.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
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