Repository navigation
Merge recurrent and composite cache rows without losing state - #90
ronaldmannak wants to merge 13 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: ddd0f806f8
ℹ️ 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".
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: c7566c8d2c
ℹ️ 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".
|
Re the two Codex findings, both fixed in the latest commit ("Keep an empty recurrent input's row count and mask nested lists from their batched child"), each with a test from the finding's scenario:
|
…their batched child ArraysCache.merge sized an empty input's zero state at one row whatever its padding said, so a two-row empty cache joined a populated one with three padding entries and two state rows. CacheList.makeMask looked only at immediate children for the batched attention cache; a nested list fell through to the default mask and attended padding (Codex review on #90). Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Rows without keys join a batch as all-padding rows, in either direction, and a batch with no rows changes nothing. This replaces the preconditions that refused the mix: a composite batch merged from empty lists and then extended with prefilled rows kept its attention child at a different row count from its recurrent child (Codex review on #88 and #90). Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: d06d255834
ℹ️ 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".
|
Re the Codex finding on extending an empty composite batch with prefilled rows: resolved by #88's latest commit, where BatchKVCache.extend takes mlx-lm's semantics (empty rows become all-padding rows), so the attention child and the recurrent child keep the same row count; covered here by the new test extendEmptyCompositeRows. |
|
Re the Codex finding on an all-empty recurrent merge losing its row count ( |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 04bee6c6b9
ℹ️ 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".
|
Correction to my reply on the all-empty recurrent merge: the full suite showed that combining padding and lengths in Whether |
|
@codex review |
|
Codex Review: Didn't find any major issues. Swish! Reviewed commit: ℹ️ 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". |
6ae2606 to
f714ea4
Compare
17a7d50 to
0a4975f
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: f714ea44a9
ℹ️ 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".
f714ea4 to
6aa4808
Compare
6aa4808 to
f407a6a
Compare
0a4975f to
aa59f4c
Compare
f407a6a to
8263a78
Compare
aa59f4c to
4392aff
Compare
3d23343 to
ba0526f
Compare
4392aff to
70d26a2
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: ba0526fcf0
ℹ️ 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".
| public static func merge(_ caches: [ArraysCache]) -> ArraysCache { | ||
| precondition(!caches.isEmpty, "merge needs a cache") | ||
| do { | ||
| try validateMerge(caches) |
There was a problem hiding this comment.
Reject unsupported subclasses in the typed recurrent merge
When callers pass RewindableConvolutionCache rows through the new typed ArraysCache.merge API, equal-shaped histories pass this validation even though mergeCaches explicitly rejects this subclass. The merged object retains its RewindableConvolutionCache type, but its inherited extract returns a plain MambaCache, losing the rewind behavior required by LFM2 convolution caches. Apply the supported exact-type restriction to the typed merge as well, so callers cannot bypass the refusal merely by choosing this overload.
Useful? React with 👍 / 👎.
70d26a2 to
fc7cb8a
Compare
ba0526f to
5dafbe0
Compare
…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>
5dafbe0 to
a35cbe2
Compare
fc7cb8a to
081b109
Compare
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>
…current-composite-merge Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
…current-composite-merge
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Stacked on #89.
What changed
ArraysCache,MambaCacheand nestedCacheListlayouts 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 aCacheListmasks with its positioned attention descendant.ArraysCacheno longer writes a fifthmetaStatefield (the row count). The format ismain's four fields again:[slotCount, presentSlots, leftPadding?, lengths?]. A merge of empty rows still keeps its row count in memory (emptyRowCount), where masking needs it while the batch runs.savePromptCacherefuses anArraysCache/MambaCache, alone or inside aCacheListat any depth, that has several rows and nothing recording them: no state arrays, no padding, no lengths. Such a file would restore one row.main's formats and refuses metadata with more than four fields, which no writer produces.mlx_vlm/models/cache.pyat Neywa-Labs/mlx-vlm@dcea787) for the empty-row handling: the all-empty merge (mlx-vlm records zero padding, this port a row count, because padding takes precedence over lengths inmake_maskin both), zero-filled empty rows in a merge, and zero-filled slots in an extension.BatchedVLMPositionTestsmoves intoRoPEApplicationTests.swift, andBatchedVLMPositionTests.swiftis deleted (f407a6a; see Test changes).Tests
In
Tests/MLXLMTests/BatchKVCacheTests.swift(BatchedHybridCacheTests,BatchedRecurrentParityTests) andRoPEApplicationTests.swift(BatchedVLMPositionTests, moved there in this update). New in this update:unrecordedRecurrentRowsAreRefused(plain andMambaCache):CacheList(KVCacheSimple(), …)and in a nestedCacheList.fourFieldRecurrentMetadataLoads: a populated, padded, length-prepared cache writes["2", "1", "1,0", "2,3"](main's format), and the file loads back with its type, rows, arrays, padding and lengths. It passes before and after, as a compatibility guard.Evidence
At this head (f407a6a), with
BatchedVLMPositionTestsnow inRoPEApplicationTests.swift, whose other suites run too:The moved suite, alone, before the move (
91f29a8) and after it (f407a6a); its one test has three cases:The same tests against this PR's previous
KVCache.swift(fd1d4b7, which wrote the fifth field):The whole
MLXLMTestsbundle at #91's head, which includes this change: 1559 Swift Testing tests and 869 XCTest cases, whose only failure isEmbeddingGemmaMaskTestsG7, which fails the same way on unmodifiedmainon this machine (output in #91).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).Recurrent offset follow-up (2026-11-06c)
ArraysCache.extend(other:)now keeps the longest row's offset, asmergealready did (3d23343). A side with no rows contributes no position.extendkept the running batch's offset. A row admitted with a longer prefix than the running rows therefore decoded at the running batch's shorter position. Add continuous batched token generation with checked admission #91 adds the matching iterator-level test.recurrentExtensionKeepsLongestOffsetinBatchedHybridCacheTests(BatchKVCacheTests.swift):extendand the one called throughany KVCache;With the fix disabled, at this head:
At this head (3d23343), the same ten suites as above:
The whole
MLXLMTestsbundle at #91's new head (1793cc5) runs 1570 Swift Testing tests and 869 XCTest cases. The only failure isEmbeddingGemmaMaskTestsG7, which also fails onmainon this machine; the two known issues are the expected ones inToolTests(MiniCPM5 CDATA). Output is in #91.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 the earlier commits unchanged.New commit
ba0526fadds two tests toBatchedRecurrentParityTestsinBatchKVCacheTests.swiftfor main's new and changed models:MambaCache) and full-attention rows merge, decode, filter and extract like separate sequences. It fails when LFM3 is made to apply its cache's scalar offset (5 issues) and passes with main'sropeOffset. Its sliding layers are left out: this file's row helpers do not cover rotating caches, whichBatchRotatingKVCacheTeststests.RewindableConvolutionCache, aMambaCachesubclass whose second slot is a rewind history of prompt-dependent length. This PR's exact-type checks refuse it inmergeCachesandvalidateExtension, including against a plainMambaCache, soBatchTokenIteratorrefuses these models at admission with aKVCacheErrorinstead of stacking histories of different lengths. The test pins that refusal; no library code changes.At this head (
ba0526f):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 commit5dafbe0:ArraysCache(so alsoMambaCache) andCacheListconform. They are their own batches, somergeCachesmerges them through their own class, as before; their row methods no longer overrideBaseKVCachestubs.CacheListreaches its children asBatchableKVCache.validateExtension(other:)throwsKVCacheErrorfor a child that is not one, as aCacheListbuilt from rows (CacheList(KVCacheSimple(), MambaCache())) holds.filter,extendandextractare non-throwing protocol methods, so on such an unmergedCacheListthey stop with a precondition naming the child; aCacheListfrommergeonly holds batches, and admission validates before it extends.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 (
5dafbe0, wasba0526f):Merge validation and padding-only extraction (2026-11-07c)
Rebased onto #89's
081b109. New commita35cbe2moves theBatchableKVCacherow operations out ofKVCache.swift. It changes no behavior:ArraysCache'sextend(other: any KVCache),validateExtension,extractandmerge(_: [any KVCache])now live inextension ArraysCache: BatchableKVCacheinBatching/BatchedCaches.swift. They reach the slots through the slot subscript, so the private storage keeps its access.CacheList'sbatchedChildren,filter,extend,validateExtension,extractandmerge(_: [any KVCache])now live inextension CacheList: BatchableKVCacheand usechildren.merge(_: [any KVCache])is astaticmethod in the extension, no longer aclass funcin the class body. Inside it,Selfis still the class it is called on, soMambaCacherows merge into aMambaCache(the existing Mamba tests pass), and no subclass overrides it.KVCache.swift:emptyRowCountand its bookkeeping, theextendoffset fix, theCacheList.makeMaskoverride withpositionedDescendant, and thesavePromptCacheguard (unsaveableRecurrentRows). This PR'sKVCache.swiftdiff goes from 193 insertions and 5 deletions to 81 insertions and 5 deletions.restoreFromMetaStatereader hardening. That covers thethrows, at most four metadata fields, a non-negative slot count, theslotIdx >= 0filter, and thetryat bothrestorecall sites.corruptRecurrentRowCountMetadataIsRejectedtests it. It is harmless:restorealready throws on main, and nothing else in the stack depends on the reader throwing.At this head (
a35cbe2, was5dafbe0):204 tests here, up from 201 at
5dafbe0: the three are #88's new tests inBatchKVCacheTests.Typed recurrent merge refuses subclasses and mixed classes (2026-11-07d)
New commit
e222aa2, pushed on top ofa35cbe2(no rebase). It answers the Codex finding on the typed recurrent merge:ArraysCache.validateMerge, which the typedArraysCache.merge(_: [ArraysCache])runs, now requires every row to be exactlyArraysCacheor exactlyMambaCache, and all rows the same class. ARewindableConvolutionCache(LFM2) used to get through this overload: the merged cache kept the subclass, but its inheritedextractreturns a plainMambaCache, so rewind support was lost silently. The erasedmerge(_: [any KVCache])andmergeCachesalready refused it throughbatchRows.validateMergefailure;validateMergeitself throwsKVCacheError.BatchedRecurrentParityTests:typedMergeValidationRefusesSubclassesAndMixedClasses(LFM2 convolution rows,MambaCache+ convolution, andArraysCache/MambaCachemixed both ways throw; plain same-class rows still pass),typedMergeStopsOnRewindableConvolutionRowsandtypedMergeStopsOnMixedRecurrentClasses(exit tests on the typed merge).The new tests at
a35cbe2's library code (tests frome222aa2), all three fail:At
e222aa2:207 tests here; 204 at
a35cbe2. The additions are #90's new tests.Not done on purpose
CacheList(one with a single-sequence child) still stops with a precondition infilter,extendandextract, which cannot throw; itsvalidateExtensionthrows. Making the row methods throwing would change every conformer and caller for a case admission never reaches.RewindableConvolutionCache(per-row rewind histories), which is new work rather than part of this rebase.main's behaviour, plus the four-field limit and the non-negative slot count.Test changes
typedMergeValidationRefusesSubclassesAndMixedClasses,typedMergeStopsOnRewindableConvolutionRows,typedMergeStopsOnMixedRecurrentClassesinBatchedRecurrentParityTests.a35cbe2moves code only, and every existing test runs unchanged.BatchedHybridCacheTests.batchableConformance:ArraysCache,MambaCacheandCacheListareBatchableKVCache, every child of a mergedCacheListis one, and an unmergedCacheListwith aKVCacheSimplechild throws fromvalidateExtension.any KVCacheto callextendthrough the protocol (recurrentExtensionKeepsLongestOffset, the metadata-merge test that buildsextended,emptyRecurrentFilterAndCompositeAdmissionKeepRows); they now hold it asany BatchableKVCache, the protocol that hasextend.BatchedHybridCacheTests.protocolSurfaceexpectedQuantizedKVCache.merge([QuantizedKVCache()])to throw (at this PR a quantized row has no batched form).QuantizedKVCachehas nomergemember until Add affine quantized KV caches for continuous batching #94, so the line now expectsQuantizedKVCachenot to be aBatchableKVCache;mergeCaches([QuantizedKVCache()])still throws. The test is renamed "through the BatchableKVCache type".BatchedRecurrentParityTests(ba0526f), with theirtinyLFM3()andtinyLFM2()fixtures.recurrentExtensionKeepsLongestOffset. No existing test changes in this follow-up.BatchedVLMPositionTests,BatchedVLMPositionFamilyandexpectVLMPositionParityfromBatchedVLMPositionTests.swiftto the end ofRoPEApplicationTests.swift, byte for byte; the old file is deleted (f407a6a). The suite runs the same number of tests before and after the move (counts under Evidence).Each of these tests asserted the fifth field, which this update removes:
emptyBatchRowsSurvivePromptCacheRoundTrip, renamedemptyBatchRowsSurviveJoinsButNotSaving:metaState == ["2", ""]and expects the save to throw, writing no file.nestedEmptyRecurrentRowsSurvivePromptCacheRoundTrip, renamednestedEmptyRecurrentRowsSurviveJoinsButNotSaving: the same change for the nestedCacheList. The save throws and writes no file, and the row checks and joins run on the batch in memory.recurrentRowCountMetadataCompatibility:finalize(), it now expectsmetaState == ["2", ""](it was["2", "", "", "", "2"]) plus a newbatchSize == 2check.corruptRecurrentRowCountMetadataIsRejectedis unchanged and passes: every case in it has five or more fields, which the reader now refuses outright. Its row-count layout checks no longer have a format to apply to.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 save format, its tests, mlx-vlm references) was made with Claude Code.
🤖 Generated with Claude Code