Skip to content

Batching: Add full-attention batch KV caches and checked row operations - #775

Open
ronaldmannak wants to merge 17 commits into
ml-explore:mainfrom
ronaldmannak:batching/a1-batch-kvcache
Open

ronaldmannak wants to merge 17 commits into
ml-explore:mainfrom
ronaldmannak:batching/a1-batch-kvcache

Conversation

@ronaldmannak

@ronaldmannak ronaldmannak commented Nov 7, 2026 •

Copy link
Copy Markdown
Contributor

Proposed changes

This PR adds BatchKVCache for full-attention batching. It merges compatible KVCacheSimple rows of unequal lengths, tracks each row’s logical position and padding, and extracts individual rows back into KVCacheSimple once the batch is finalized.

The new BatchableKVCache protocol defines the batch row operations. The existing KVCache requirements are unchanged.

Support for sliding-window, recurrent, and composite caches follows in subsequent PRs.

Note: Merge #773 first, part of batched generation issue #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: Opus and Astra extracted code from a fork

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

Copy link
Copy Markdown
Contributor Author

Changed PR to draft. The preconditionFailures added to KVCache's default implementation isn't great. Instead I think I prefer a separate protocol

ronaldmannak and others added 2 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>
@ronaldmannak
ronaldmannak force-pushed the batching/a1-batch-kvcache branch from b6cdd4f to 1c399b0 Compare November 8, 2026 03:39
@ronaldmannak
ronaldmannak marked this pull request as ready for review November 8, 2026 16:21
@ronaldmannak

Copy link
Copy Markdown
Contributor Author

I've reopened the PR after moving the batch row operations into BatchableKVCache, a new protocol that builds on KVCache. The existing KVCache requirements are unchanged.

mergeCaches still accepts compatible single-sequence caches and combines them into a BatchKVCache. Apps can restore per-request prompt caches from SSD and use them to seed a new batch.

return
}
let indices = MLXArray(rows.map { Int32($0) })
keys = keys?[indices]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Every exit is a gather and every join is a pad plus a concatenation of the whole batch. On 4 rows x 4096 tokens x 40 layers (8 KV heads, head dim 128, fp16), filter took 37 ms and extend 76 ms, about 1.4
decode steps of the 14B model. Writing a 512-token newcomer into the slot a finished row left took 1.6 ms, flat in the width. The buffer is owned by one cache object, so MLX updates it in place. Keeping finished rows as free slots and compacting only when many are free would remove most of these copies. Happy to try it as a follow-up once the stack lands.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@aleroot This part of the code is basically a port of mlx-lm. Whenever a stream is finished, the row is removed from the batched cache and when a new stream is inserted, a new row is added to the cache. Both are expensive operations.

Your suggestion is to keep stale rows around and reuse them when a compatible (a shorter or same length new request) comes in (longer newcomers would require to reformat the tensor anyway). I've rerun the benchmarks on an M5 Max and the gains are real:

Cache operation Unpatched PR #775 Slot-reuse prototype Prototype behavior
Remove a row, 4 → 3 live rows 7.66 ms 0.099 ms Mark the slot vacant and keep it allocated
Remove a row and compact immediately 7.66 ms 7.66 ms Use the original filter
Admit a 512-token row, 3 → 4 live rows 11.91 ms 0.87 ms Fill a previously vacated slot
Admit a 512-token row to a full batch, 4 → 5 14.27 ms 14.26 ms Use the original extend
Replace a finished row immediately, 4 → 3 → 4 19.34 ms 0.85 ms Overwrite the slot and update its metadata

There is a tradeoff though: a stale slot still adds work to each decode forward. After a number of forward passes you've basically lost the time previously won. Maybe the compaction algo should be based on both number of empty slots and forward passes (and really also model and hardware, this gets complicated fast).

FYI: another potential improvement that may make your suggestion even more attractive combining the prefill chunks and decode in the same forward pass. It would definitely be interesting to look at the combination.

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

Copy link
Copy Markdown
Member

This needs a rebase and it looks like there is a doc build failure. Thank you!

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.

5 participants