Repository navigation
Add sliding-window batching with BatchRotatingKVCache - #89
ronaldmannak wants to merge 12 commits into
Conversation
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 2acd927b5d
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
…rt evictions A ragged prefill no longer trims the buffer to window - 1 old positions between chunks: a row that was complete lost a real token to every padding-only chunk of the rows still filling, and its extracted window then held padding. The buffer keeps every position until finalize, and the first decode step trims it to the window as before. trim is bounded by maxTrimCount, so it removes nothing once the window has filled instead of moving the ring cursor into negative territory. evictedTokenCount reports the positions the longest row no longer holds (Codex review on #89). Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
|
Re the three Codex findings, all fixed in the latest commit ("Keep completed rows' windows in a ragged prefill, clamp trim and report evictions"), each with a test built from the finding's own scenario:
|
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 2a0e49f5e7
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
💡 Codex Reviewmlx-swift-lm/Libraries/MLXLMCommon/Batching/BatchRotatingKVCache.swift Lines 240 to 241 in 54ec69d When merging a previously wrapped and trimmed source, ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
|
Re the three Codex findings, all fixed in the latest commit ("Keep the rotating batch's padding a count, and report rows' positions and evictions"):
Two more findings from the external review, fixed in the commit after ("Validate rows before a rotating merge, and bound a ragged prefill's buffer"):
Test changes: |
|
Re the Codex finding on the exact-rewind allowance ( |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: a36b53b150
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
634f402 to
93a4bc8
Compare
17a7d50 to
0a4975f
Compare
0a4975f to
aa59f4c
Compare
93a4bc8 to
0fea808
Compare
aa59f4c to
4392aff
Compare
b6cdd4f to
9c6ef21
Compare
70d26a2 to
fc7cb8a
Compare
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>
fc7cb8a to
081b109
Compare
…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>
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>
Stacked on #88.
What changed
BatchRotatingKVCachekeeps 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.extractchecks its row index with a precondition ("BatchRotatingKVCache row index out of range"). It read the row's padding and position throughMLXArraysubscripts, which do not trap past the batch, soextract(2)on a two-row batch returned a cache built from out-of-range metadata. mlx-vlm'sBatchKVCache.extractraises anIndexErrorfor the same case.mlx_vlm/models/cache.pyat Neywa-Labs/mlx-vlm@dcea787) sit next to the existing mlx-lm references where the Swift code follows mlx-vlm: lengths filtered with the rows, the merge's window check, the all-empty merge.BatchedSlidingWindowParityTestsmoves intoBatchRotatingKVCacheTests.swift, andBatchedSlidingWindowParityTests.swiftis deleted (aa59f4c; see Test changes).Tests
Tests/MLXLMTests/BatchRotatingKVCacheTests.swift:BatchRotatingKVCacheTests(cache lifecycle, wrap, ragged prefill, extension checks, status) and, moved there in this update,BatchedSlidingWindowParityTests(ragged and merged Gemma 3 rows decoding past the window); and additions toKVCacheConfigurationTests. New in this update:extractOutOfRange(exit test). Without the precondition the process exits successfully (expected exit status ".failure", but ".exitCode(EXIT_SUCCESS)" was reported instead).Round rollback follow-up
Positive-width staged rounds are refused while any row still has a negative logical position, or when the batch has no rows. Zero-width eligibility retains the existing window and eviction checks. The existing refusal of positive rounds that reach the window boundary or follow eviction is unchanged.
The refusal regressions fail with the guard removed without writing into the invalid round. Valid rounds after padding is consumed verify exact rollback and partial commit of retained K/V, row positions and the storage timeline; window-boundary and eviction refusals remain covered. Focused local validation passes 72 tests across 3 suites.
Codex prepared this follow-up, its regressions and validation at the maintainer's request for this origin fork.
Combined stack candidate
7510ad7also passes 222 Swift Testing tests across 13 suites and 35 XCTest cases. CI-pinned swift-format 603 checks and all 11 library DocC products pass with warnings treated as errors. These are local results; fork CI remains skipped.Evidence
Previous validation (aa59f4c), with
BatchedSlidingWindowParityTestsnow inBatchRotatingKVCacheTests.swift:The moved suite, alone, before the move (
6e092d4) and after it (aa59f4c):With the precondition removed:
swift-format format(604.0.0, repo.swift-format) leaves every file this update touches unchanged. Origin-fork GitHub Actions jobs are skipped by the workflow's repository-owner condition; the results above are local (M5 Max).Rebased onto main
4ab2679(2026-11-07)Rebased from
c8dabc6onto main4ab2679, which adds seven commits (22bdf2c..4ab2679): surrogate-pair escapes, weight-loading progress, LFM2.5, chat-session steering, VLM image prompts out of float32, LFM3, and Qwen 3.5 VLM YaRN. Git applied every commit of the stack without conflicts.git range-diffshows this PR's commits unchanged.At this head (
70d26a2):Batch row operations move to
BatchableKVCache(2026-11-07b)Rebased onto #88's
652c276, which moves the batch row operations fromKVCacheto the newBatchableKVCacheprotocol (see #88). New commitfc7cb8a:BatchRotatingKVCacheconforms, its row methods no longer overrideBaseKVCachestubs, and itsmerge(_:)takes exactlyRotatingKVCacherows.mergeCachesmaps aRotatingKVCacherow toBatchRotatingKVCache;RotatingKVCacheloses itsmergeoverride that returnedany KVCache, and the typedRotatingKVCache.merge(_:) -> BatchRotatingKVCachestays.Simplicity-rule justification for the new protocol: five conforming types across the stack (
BatchKVCachehere in #88,BatchRotatingKVCachein #89,ArraysCache(withMambaCache) andCacheListin #90,BatchQuantizedKVCachein #94), used byBatchTokenIterator, which holds its layers as[any BatchableKVCache], and byCacheList, which reaches its children through it. It replaces refusing defaults onKVCacheitself.At this head (
fc7cb8a, was70d26a2):Merge validation and padding-only extraction (2026-11-07c)
Rebased onto #88's
1c399b0. New commit081b109:BatchRotatingKVCache.extractclamps the slice start to the written range, so a row whose padding is past it comes back empty, with the batch's window, step (allocationStep) and capacity origin. Before, it trapped. A row whose padding exactly reaches the written range already came back as zero-width arrays, and still does (oneTokenRaggedPrefillchecks that). The extract reuses theleftPadding[index]andbatchOffset[index]values it already read, so it adds no sync. It requires a finalized batch (lengths == nil);BatchableKVCache.extract(_:)now documents that the batch must be finalized: during a ragged prefill, beforefinalize()moves the right padding, a row's tokens are not yet whereextractreads them.RotatingKVCache.mergechecks, before extending, that each input holds exactly one row and matches the first prefilled row in head count, head widths and dtype. A mismatch throwsKVCacheError; before, it stopped in MLX's concatenate. It uses Add full-attention batch KV caches and checked row operations #88'svalidateBatchKVRowson the one-row batches it builds, reading only array metadata.At this head (
081b109, wasfc7cb8a):Each new test, run alone with this head's tests on the code before the new commit:
Not done on purpose
filterkeeps every row's left padding as a count, as before. mlx-vlm's rotatingfilterdrops none either, so there is no shared-padding bound to port here (unlike Add full-attention batch KV caches and checked row operations #88).Test changes
081b109(output under Evidence):extractPaddingOnlyRow,extractBeforeFinalize(exit test) andmergeRefusesMismatchedRowsinBatchRotatingKVCacheTests. No existing test changes.BatchRotatingKVCacheTests.batchableConformance:RotatingKVCacheis not aBatchableKVCache,BatchRotatingKVCache.mergebuilds the batch from a rotating row, and merging no rows, aKVCacheSimplerow or the batch itself throws.BatchRotatingKVCacheTests.protocolSurfacesays "through the BatchableKVCache type"; its assertion is unchanged.BatchedSlidingWindowParityTests(two Gemma 3 parity tests) and its helpers (tinyGemma3,mergeRows,filterRows,extractRow,expectExtractedRowsMatch) fromBatchedSlidingWindowParityTests.swiftto the end ofBatchRotatingKVCacheTests.swift; the old file is deleted (aa59f4c). Two lines differ from a plain move:@testable import MLXLLM, as the old file had, for the tiny Gemma 3 text model;tinyGemma3()namesMLXLLM.Gemma3TextConfiguration, because the target'sMLXVLMimport declares aGemma3TextConfigurationof its own.AI assistance: the original implementation was developed with Claude Code. Codex implemented review fixes, reorganized the stack, and validated the rebuilt PRs at the maintainer's request for this origin fork. This update (the index check, its test, mlx-vlm references) was made with Claude Code.
🤖 Generated with Claude Code