Skip to content

Batching: Merge recurrent and composite cache rows without losing state - #777

Open
ronaldmannak wants to merge 42 commits into
ml-explore:mainfrom
ronaldmannak:batching/a3-recurrent-composite-merge
Open

ronaldmannak wants to merge 42 commits into
ml-explore:mainfrom
ronaldmannak:batching/a3-recurrent-composite-merge

Conversation

@ronaldmannak

Copy link
Copy Markdown
Contributor

Proposed changes

ArraysCache, MambaCache and nested CacheList layouts get batched row operations (merge, filter, extend, extract), keeping empty-row counts, sparse recurrent slots and late padding or length metadata. Extension is validated for recurrent and composite layouts, and a CacheList masks with its positioned attention descendant.

Merge after #776. Described in #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 ronaldmannak mentioned this pull request Nov 7, 2026
1 task done
ronaldmannak and others added 16 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>
…d rows

ArraysCache no longer writes a fifth metaState field for the row count. A
merged batch of empty rows keeps its count in memory (emptyRowCount), where
masking needs it while the batch runs, but nothing in a file records it, so
savePromptCache now refuses an ArraysCache or MambaCache, alone or inside a
CacheList, that has several rows and no state arrays, padding or lengths.
Every other save is unchanged: zero-row caches are still refused, a
single-sequence cache saves as before, and populated or padded batches save
their rows through their arrays or padding. The reader accepts main's
formats and refuses metadata longer than four fields, which no writer
produces.

Tests: the two save/load round trips of empty batches now expect the save to
throw and keep their later-join checks on the batch in memory; the metadata
compatibility test restores four-field metadata where it used five. New:
the refusal cases, the saves that still work, and a four-field file loading.

The all-empty merge, the zero-filled empty rows and the extension of arrays
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>
BatchedVLMPositionTests, BatchedVLMPositionFamily and expectVLMPositionParity
move unchanged to the end of RoPEApplicationTests.swift, with the other VLM
row-position tests; BatchedVLMPositionTests.swift is deleted. No assertion
changes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
ArraysCache.merge gives a recurrent batch the longest row's offset, but
extend(other:) kept the receiver's. Admission extends a running batch with
the newly admitted rows, so a row admitted with a longer prefix than the
running rows decoded at the running batch's offset. extend now takes the
larger offset; a side with no rows contributes none.

The new test extends offset 3 with 7 and 7 with 3, typed and through the
KVCache protocol, plus zero-row sides; it fails without the fix (3 instead
of 7).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Main added LFM3 and moved LFM2 and LFM2-MoE to RewindableConvolutionCache.
LFM3's convolution and full-attention rows now merge and decode like
separate sequences; LFM2's rewindable convolution rows are refused by the
exact-type checks instead of stacking histories of different lengths.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Recurrent and composite caches are their own batches: their row methods
implement BatchableKVCache instead of overriding BaseKVCache stubs, and
mergeCaches merges them through their own class. A CacheList reaches its
children as batched caches, and its extension check throws KVCacheError
for a child that is not one, as a CacheList built from rows holds.

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

ArraysCache's extend(other: any KVCache), validateExtension, extract and
merge(_: [any KVCache]), and CacheList's batchedChildren, filter, extend,
validateExtension, extract and merge(_: [any KVCache]), move from KVCache.swift
into the extensions in Batching/BatchedCaches.swift that declare the
conformance. They reach ArraysCache's slots through its subscript and a
CacheList's children through `children`, so no storage changes access.

merge(_: [any KVCache]) becomes a static method there. Inside it `Self` is the
class it is called on, so a MambaCache batch still merges as a MambaCache, and
no subclass overrides it.

No behavior changes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
ArraysCache.validateMerge, which the typed ArraysCache.merge(_: [ArraysCache])
runs, now requires every row to be exactly ArraysCache or exactly MambaCache,
and all rows the same class. Before, a RewindableConvolutionCache (LFM2) got
through the typed path: the merged cache kept the subclass, but its inherited
extract returns a plain MambaCache, so rewind support was lost silently. The
erased path already refused these through batchRows.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@ronaldmannak
ronaldmannak force-pushed the batching/a3-recurrent-composite-merge branch from 3d23343 to e222aa2 Compare November 8, 2026 03:39
@ronaldmannak ronaldmannak mentioned this pull request Nov 8, 2026
5 tasks done
ronaldmannak and others added 7 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>
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>
…current-composite-merge

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 4 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>
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>
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