Skip to content

Merge recurrent and composite cache rows without losing state - #90

Open
ronaldmannak wants to merge 13 commits into
claude/a2-batch-rotating-kvcachefrom
claude/a3-recurrent-composite-merge
Open

ronaldmannak wants to merge 13 commits into
claude/a2-batch-rotating-kvcachefrom
claude/a3-recurrent-composite-merge

Conversation

@ronaldmannak

@ronaldmannak ronaldmannak commented Nov 5, 2026 •

Copy link
Copy Markdown
Owner

Stacked on #89.

What changed

  • 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.
  • Before merging recurrent rows, slot counts, row cardinality and each populated slot's dtype and shape are checked before anything is copied or indexed. The erased merge throws for incompatible layouts; the typed merge keeps its non-throwing signature and checks the same contract.
  • New in this update, saved files:
    • ArraysCache no longer writes a fifth metaState field (the row count). The format is main'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.
    • savePromptCache refuses an ArraysCache/MambaCache, alone or inside a CacheList at any depth, that has several rows and nothing recording them: no state arrays, no padding, no lengths. Such a file would restore one row.
    • Unchanged: the zero-row refusal, ordinary single-sequence saves, and saves of populated or padded multi-row recurrent caches, whose arrays or padding carry the row count.
    • The reader accepts main's formats and refuses metadata with more than four fields, which no writer produces.
  • New in this update: pinned mlx-vlm references (mlx_vlm/models/cache.py at 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 in make_mask in both), zero-filled empty rows in a merge, and zero-filled slots in an extension.
  • New in this update: BatchedVLMPositionTests moves into RoPEApplicationTests.swift, and BatchedVLMPositionTests.swift is deleted (f407a6a; see Test changes).

Tests

In Tests/MLXLMTests/BatchKVCacheTests.swift (BatchedHybridCacheTests, BatchedRecurrentParityTests) and RoPEApplicationTests.swift (BatchedVLMPositionTests, moved there in this update). New in this update:

  • unrecordedRecurrentRowsAreRefused (plain and MambaCache):
    • Refused: two merged empty rows, alone, in CacheList(KVCacheSimple(), …) and in a nested CacheList.
    • Still saved and restored: a padded empty batch keeps both rows, and a populated two-row batch keeps both rows and its arrays.
    • Fails on this PR's previous save code (6 issues: the three refusals, for both cache types).
  • 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 BatchedVLMPositionTests now in RoPEApplicationTests.swift, whose other suites run too:

DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer xcodebuild test -skipPackagePluginValidation \
  -scheme mlx-swift-lm-Package -destination 'platform=macOS' \
  -only-testing:MLXLMTests/BatchKVCacheTests -only-testing:MLXLMTests/BatchedDecodeParityTests \
  -only-testing:MLXLMTests/BatchedHybridCacheTests -only-testing:MLXLMTests/BatchedRecurrentParityTests \
  -only-testing:MLXLMTests/BatchedVLMPositionTests -only-testing:MLXLMTests/KVCacheTests \
  -only-testing:MLXLMTests/RoPEApplicationTests -only-testing:MLXLMTests/VLMRowPositionTests \
  -only-testing:MLXLMTests/LLMRowPositionTests -only-testing:MLXLMTests/QwenVLBatchedPositionTests

Suite RoPEApplicationTests passed after 0.120 seconds.
Suite LLMRowPositionTests passed after 1.192 seconds.
Suite QwenVLBatchedPositionTests passed after 1.232 seconds.
Suite BatchedHybridCacheTests passed after 1.516 seconds.
Suite BatchKVCacheTests passed after 1.908 seconds.
Suite BatchedRecurrentParityTests passed after 1.919 seconds.
Suite BatchedVLMPositionTests passed after 2.317 seconds.
Suite VLMRowPositionTests passed after 2.505 seconds.
Suite BatchedDecodeParityTests passed after 2.745 seconds.
Suite KVCacheTests passed after 3.516 seconds.
Test run with 193 tests in 10 suites passed after 3.517 seconds.
** TEST SUCCEEDED **

The moved suite, alone, before the move (91f29a8) and after it (f407a6a); its one test has three cases:

-only-testing:MLXLMTests/BatchedVLMPositionTests
before: Test run with 1 test in 1 suite passed after 0.342 seconds.
after:  Test run with 1 test in 1 suite passed after 0.308 seconds.

The same tests against this PR's previous KVCache.swift (fd1d4b7, which wrote the fifth field):

Test "Saving refuses only a recurrent batch whose rows nothing records, also in a list" with 2 test cases failed after 0.004 seconds with 6 issues.
Test "A file with four-field recurrent metadata loads" with 2 test cases passed after 0.001 seconds.
Test "Empty recurrent batches keep every row through later joins, and refuse to save" with 4 test cases failed after 0.004 seconds with 24 issues.
Test "Nested lists keep empty recurrent rows through joins, and refuse to save" with 2 test cases failed after 0.001 seconds with 4 issues.
Test "Recurrent restore keeps legacy metadata and signed masks" with 2 test cases failed after 0.001 seconds with 2 issues.
Test run with 29 tests in 1 suite failed after 0.071 seconds with 36 issues.

The whole MLXLMTests bundle at #91's head, which includes this change: 1559 Swift Testing tests and 869 XCTest cases, whose only failure is EmbeddingGemmaMaskTests G7, which fails the same way on unmodified main on 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, as merge already did (3d23343). A side with no rows contributes no position.
  • The bug: admission extends a running recurrent batch with the newly admitted rows, and extend kept 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.
  • New test, recurrentExtensionKeepsLongestOffset in BatchedHybridCacheTests (BatchKVCacheTests.swift):
    • offsets 3 and 7, in both orders;
    • the typed extend and the one called through any KVCache;
    • zero-row sides.

With the fix disabled, at this head:

-only-testing:MLXLMTests/BatchedHybridCacheTests
Test "Extending a recurrent batch keeps the longest row's offset, as merge does" recorded an issue with 1 argument offsets → (3, 7) at BatchKVCacheTests.swift:1559:13: Expectation failed: active.offset == 7
Test "Extending a recurrent batch keeps the longest row's offset, as merge does" recorded an issue with 1 argument offsets → (3, 7) at BatchKVCacheTests.swift:1565:13: Expectation failed: erased.offset == 7
Test "Extending a recurrent batch keeps the longest row's offset, as merge does" recorded an issue with 1 argument offsets → (3, 7) at BatchKVCacheTests.swift:1576:13: Expectation failed: fromEmpty.offset == offsets.1
Test "Extending a recurrent batch keeps the longest row's offset, as merge does" recorded an issue with 1 argument offsets → (7, 3) at BatchKVCacheTests.swift:1576:13: Expectation failed: fromEmpty.offset == offsets.1
Test run with 30 tests in 1 suite failed after 0.070 seconds with 4 issues.

At this head (3d23343), the same ten suites as above:

-only-testing:MLXLMTests/BatchKVCacheTests -only-testing:MLXLMTests/BatchedDecodeParityTests
-only-testing:MLXLMTests/BatchedHybridCacheTests -only-testing:MLXLMTests/BatchedRecurrentParityTests
-only-testing:MLXLMTests/BatchedVLMPositionTests -only-testing:MLXLMTests/KVCacheTests
-only-testing:MLXLMTests/RoPEApplicationTests -only-testing:MLXLMTests/VLMRowPositionTests
-only-testing:MLXLMTests/LLMRowPositionTests -only-testing:MLXLMTests/QwenVLBatchedPositionTests
Test run with 197 tests in 10 suites passed after 5.306 seconds.
** TEST SUCCEEDED **

The whole MLXLMTests bundle at #91's new head (1793cc5) runs 1570 Swift Testing tests and 869 XCTest cases. The only failure is EmbeddingGemmaMaskTests G7, which also fails on main on this machine; the two known issues are the expected ones in ToolTests (MiniCPM5 CDATA). Output is in #91.

Rebased onto main 4ab2679 (2026-11-07)

Rebased from c8dabc6 onto main 4ab2679, 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-diff shows the earlier commits unchanged.

New commit ba0526f adds two tests to BatchedRecurrentParityTests in BatchKVCacheTests.swift for main's new and changed models:

  • LFM3 ("Merged LFM3 prompts decode like separate sequences"): its convolution (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's ropeOffset. Its sliding layers are left out: this file's row helpers do not cover rotating caches, which BatchRotatingKVCacheTests tests.
  • LFM2 and LFM2-MoE ("LFM2's rewindable convolution rows are refused, not merged as plain recurrent state"): main moved their convolution layers to RewindableConvolutionCache, a MambaCache subclass whose second slot is a rewind history of prompt-dependent length. This PR's exact-type checks refuse it in mergeCaches and validateExtension, including against a plain MambaCache, so BatchTokenIterator refuses these models at admission with a KVCacheError instead of stacking histories of different lengths. The test pins that refusal; no library code changes.

At this head (ba0526f):

DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer xcodebuild test -skipPackagePluginValidation \
  -scheme mlx-swift-lm-Package -destination 'platform=macOS' \
  -only-testing:MLXLMTests/BatchKVCacheTests -only-testing:MLXLMTests/BatchedDecodeParityTests -only-testing:MLXLMTests/BatchedHybridCacheTests -only-testing:MLXLMTests/BatchedRecurrentParityTests -only-testing:MLXLMTests/BatchedVLMPositionTests -only-testing:MLXLMTests/KVCacheTests -only-testing:MLXLMTests/RoPEApplicationTests -only-testing:MLXLMTests/VLMRowPositionTests -only-testing:MLXLMTests/LLMRowPositionTests -only-testing:MLXLMTests/QwenVLBatchedPositionTests

Suite RoPEApplicationTests passed after 0.116 seconds.
Suite LLMRowPositionTests passed after 1.188 seconds.
Suite QwenVLBatchedPositionTests passed after 1.233 seconds.
Suite BatchedHybridCacheTests passed after 1.557 seconds.
Suite BatchKVCacheTests passed after 1.973 seconds.
Suite BatchedRecurrentParityTests passed after 2.079 seconds.
Suite BatchedVLMPositionTests passed after 2.349 seconds.
Suite VLMRowPositionTests passed after 2.536 seconds.
Suite BatchedDecodeParityTests passed after 2.732 seconds.
Suite KVCacheTests passed after 3.516 seconds.
Test run with 199 tests in 10 suites passed after 3.517 seconds.
** TEST SUCCEEDED **

Batch row operations move to BatchableKVCache (2026-11-07b)

Rebased onto #88's 652c276, which moves the batch row operations from KVCache to the new BatchableKVCache protocol (see #88). New commit 5dafbe0:

  • ArraysCache (so also MambaCache) and CacheList conform. They are their own batches, so mergeCaches merges them through their own class, as before; their row methods no longer override BaseKVCache stubs.
  • CacheList reaches its children as BatchableKVCache. validateExtension(other:) throws KVCacheError for a child that is not one, as a CacheList built from rows (CacheList(KVCacheSimple(), MambaCache())) holds. filter, extend and extract are non-throwing protocol methods, so on such an unmerged CacheList they stop with a precondition naming the child; a CacheList from merge only holds batches, and admission validates before it extends.

Simplicity-rule justification for the new protocol: five conforming types across the stack (BatchKVCache here in #88, BatchRotatingKVCache in #89, ArraysCache (with MambaCache) and CacheList in #90, BatchQuantizedKVCache in #94), used by BatchTokenIterator, which holds its layers as [any BatchableKVCache], and by CacheList, which reaches its children through it. It replaces refusing defaults on KVCache itself.

At this head (5dafbe0, was ba0526f):

DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer xcodebuild test -skipPackagePluginValidation \
  -scheme mlx-swift-lm-Package -destination 'platform=macOS' \
  -only-testing:MLXLMTests/BatchKVCacheTests -only-testing:MLXLMTests/BatchedDecodeParityTests -only-testing:MLXLMTests/BatchedHybridCacheTests -only-testing:MLXLMTests/BatchedRecurrentParityTests -only-testing:MLXLMTests/BatchedVLMPositionTests -only-testing:MLXLMTests/KVCacheTests -only-testing:MLXLMTests/RoPEApplicationTests -only-testing:MLXLMTests/VLMRowPositionTests -only-testing:MLXLMTests/LLMRowPositionTests -only-testing:MLXLMTests/QwenVLBatchedPositionTests

Suite RoPEApplicationTests passed after 0.122 seconds.
Suite LLMRowPositionTests passed after 1.144 seconds.
Suite QwenVLBatchedPositionTests passed after 1.223 seconds.
Suite BatchedHybridCacheTests passed after 1.555 seconds.
Suite BatchKVCacheTests passed after 1.994 seconds.
Suite BatchedRecurrentParityTests passed after 2.112 seconds.
Suite BatchedVLMPositionTests passed after 2.409 seconds.
Suite VLMRowPositionTests passed after 2.565 seconds.
Suite BatchedDecodeParityTests passed after 2.758 seconds.
Suite KVCacheTests passed after 3.566 seconds.
Test run with 201 tests in 10 suites passed after 3.567 seconds.
** TEST SUCCEEDED **

Merge validation and padding-only extraction (2026-11-07c)

Rebased onto #89's 081b109. New commit a35cbe2 moves the BatchableKVCache row operations out of KVCache.swift. It changes no behavior:

  • ArraysCache's extend(other: any KVCache), validateExtension, extract and merge(_: [any KVCache]) now live in extension ArraysCache: BatchableKVCache in Batching/BatchedCaches.swift. They reach the slots through the slot subscript, so the private storage keeps its access.
  • CacheList's batchedChildren, filter, extend, validateExtension, extract and merge(_: [any KVCache]) now live in extension CacheList: BatchableKVCache and use children.
  • merge(_: [any KVCache]) is a static method in the extension, no longer a class func in the class body. Inside it, Self is still the class it is called on, so MambaCache rows merge into a MambaCache (the existing Mamba tests pass), and no subclass overrides it.
  • These stay in KVCache.swift: emptyRowCount and its bookkeeping, the extend offset fix, the CacheList.makeMask override with positionedDescendant, and the savePromptCache guard (unsaveableRecurrentRows). This PR's KVCache.swift diff goes from 193 insertions and 5 deletions to 81 insertions and 5 deletions.
  • In scope, and staying in this PR: the restoreFromMetaState reader hardening. That covers the throws, at most four metadata fields, a non-negative slot count, the slotIdx >= 0 filter, and the try at both restore call sites. corruptRecurrentRowCountMetadataIsRejected tests it. It is harmless: restore already throws on main, and nothing else in the stack depends on the reader throwing.

At this head (a35cbe2, was 5dafbe0):

DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer xcodebuild test -skipPackagePluginValidation \
  -scheme mlx-swift-lm-Package -destination 'platform=macOS' \
  -only-testing:MLXLMTests/BatchKVCacheTests -only-testing:MLXLMTests/BatchedDecodeParityTests -only-testing:MLXLMTests/BatchedHybridCacheTests -only-testing:MLXLMTests/BatchedRecurrentParityTests -only-testing:MLXLMTests/BatchedVLMPositionTests -only-testing:MLXLMTests/KVCacheTests -only-testing:MLXLMTests/RoPEApplicationTests -only-testing:MLXLMTests/VLMRowPositionTests -only-testing:MLXLMTests/LLMRowPositionTests -only-testing:MLXLMTests/QwenVLBatchedPositionTests

Suite RoPEApplicationTests passed after 0.115 seconds.
Suite LLMRowPositionTests passed after 1.169 seconds.
Suite QwenVLBatchedPositionTests passed after 1.221 seconds.
Suite BatchedHybridCacheTests passed after 1.512 seconds.
Suite BatchKVCacheTests passed after 1.983 seconds.
Suite BatchedRecurrentParityTests passed after 2.094 seconds.
Suite BatchedVLMPositionTests passed after 2.323 seconds.
Suite VLMRowPositionTests passed after 2.464 seconds.
Suite BatchedDecodeParityTests passed after 2.634 seconds.
Suite KVCacheTests passed after 3.445 seconds.
Test run with 204 tests in 10 suites passed after 3.445 seconds.
** TEST SUCCEEDED **

204 tests here, up from 201 at 5dafbe0: the three are #88's new tests in BatchKVCacheTests.

Typed recurrent merge refuses subclasses and mixed classes (2026-11-07d)

New commit e222aa2, pushed on top of a35cbe2 (no rebase). It answers the Codex finding on the typed recurrent merge:

  • 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. A RewindableConvolutionCache (LFM2) used to get through this overload: the merged cache kept the subclass, but its inherited extract returns a plain MambaCache, so rewind support was lost silently. The erased merge(_: [any KVCache]) and mergeCaches already refused it through batchRows.
  • The typed merge stops with a precondition on these rows, as it already does for every other validateMerge failure; validateMerge itself throws KVCacheError.
  • Three new tests in BatchedRecurrentParityTests: typedMergeValidationRefusesSubclassesAndMixedClasses (LFM2 convolution rows, MambaCache + convolution, and ArraysCache/MambaCache mixed both ways throw; plain same-class rows still pass), typedMergeStopsOnRewindableConvolutionRows and typedMergeStopsOnMixedRecurrentClasses (exit tests on the typed merge).

The new tests at a35cbe2's library code (tests from e222aa2), all three fail:

Expectation failed: expected exit status ".failure", but ".exitCode(EXIT_SUCCESS)" was reported instead   (typedMergeStopsOnMixedRecurrentClasses)
Expectation failed: expected exit status ".failure", but ".exitCode(EXIT_SUCCESS)" was reported instead   (typedMergeStopsOnRewindableConvolutionRows)
Expectation failed: an error was expected but none was thrown   (typedMergeValidationRefusesSubclassesAndMixedClasses, lines 2101, 2104, 2107)
Test run with 3 tests in 1 suite failed after 1.970 seconds with 5 issues.

At e222aa2:

DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer xcodebuild test -skipPackagePluginValidation \
  -scheme mlx-swift-lm-Package -destination 'platform=macOS' \
  -only-testing:MLXLMTests/BatchKVCacheTests -only-testing:MLXLMTests/BatchedDecodeParityTests -only-testing:MLXLMTests/BatchedHybridCacheTests -only-testing:MLXLMTests/BatchedRecurrentParityTests -only-testing:MLXLMTests/BatchedVLMPositionTests -only-testing:MLXLMTests/KVCacheTests -only-testing:MLXLMTests/LLMRowPositionTests -only-testing:MLXLMTests/QwenVLBatchedPositionTests -only-testing:MLXLMTests/RoPEApplicationTests -only-testing:MLXLMTests/VLMRowPositionTests

Suite RoPEApplicationTests passed after 0.345 seconds.
Suite LLMRowPositionTests passed after 1.432 seconds.
Suite QwenVLBatchedPositionTests passed after 1.467 seconds.
Suite BatchedHybridCacheTests passed after 1.794 seconds.
Suite BatchKVCacheTests passed after 2.322 seconds.
Suite BatchedRecurrentParityTests passed after 2.636 seconds.
Suite BatchedVLMPositionTests passed after 2.683 seconds.
Suite VLMRowPositionTests passed after 2.866 seconds.
Suite BatchedDecodeParityTests passed after 3.021 seconds.
Suite KVCacheTests passed after 3.837 seconds.
Test run with 207 tests in 10 suites passed after 3.837 seconds.
** TEST SUCCEEDED **

207 tests here; 204 at a35cbe2. The additions are #90's new tests.

Not done on purpose

  • An unmerged CacheList (one with a single-sequence child) still stops with a precondition in filter, extend and extract, which cannot throw; its validateExtension throws. Making the row methods throwing would change every conformer and caller for a case admission never reaches.
  • LFM2 and LFM2-MoE stay refused: batching them needs a batched form of main's RewindableConvolutionCache (per-row rewind histories), which is new work rather than part of this rebase.
  • A multi-row recurrent batch with no state is refused rather than saved with its count: a file format change for one transient case was the cost the fifth field carried.
  • Restored metadata is not cross-checked against the arrays' row count any more (that check came with the fifth field). It is back to main's behaviour, plus the four-field limit and the non-negative slot count.

Test changes

  • Added, no existing test changed (2026-11-07d): typedMergeValidationRefusesSubclassesAndMixedClasses, typedMergeStopsOnRewindableConvolutionRows, typedMergeStopsOnMixedRecurrentClasses in BatchedRecurrentParityTests.
  • None in 2026-11-07c: a35cbe2 moves code only, and every existing test runs unchanged.
  • Added: BatchedHybridCacheTests.batchableConformance: ArraysCache, MambaCache and CacheList are BatchableKVCache, every child of a merged CacheList is one, and an unmerged CacheList with a KVCacheSimple child throws from validateExtension.
  • Changed declarations, no assertion changes: three tests held a recurrent cache as any KVCache to call extend through the protocol (recurrentExtensionKeepsLongestOffset, the metadata-merge test that builds extended, emptyRecurrentFilterAndCompositeAdmissionKeepRows); they now hold it as any BatchableKVCache, the protocol that has extend.
  • Changed: BatchedHybridCacheTests.protocolSurface expected QuantizedKVCache.merge([QuantizedKVCache()]) to throw (at this PR a quantized row has no batched form). QuantizedKVCache has no merge member until Add affine quantized KV caches for continuous batching #94, so the line now expects QuantizedKVCache not to be a BatchableKVCache; mergeCaches([QuantizedKVCache()]) still throws. The test is renamed "through the BatchableKVCache type".
  • Added, no existing test changed: the LFM3 and LFM2 tests in BatchedRecurrentParityTests (ba0526f), with their tinyLFM3() and tinyLFM2() fixtures.
  • Added (2026-11-06c): recurrentExtensionKeepsLongestOffset. No existing test changes in this follow-up.
  • Moved, no assertion changes: BatchedVLMPositionTests, BatchedVLMPositionFamily and expectVLMPositionParity from BatchedVLMPositionTests.swift to the end of RoPEApplicationTests.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, renamed emptyBatchRowsSurviveJoinsButNotSaving:
    • It now expects metaState == ["2", ""] and expects the save to throw, writing no file.
    • Its row, slot, padding and length checks and every later-join check now run on the batch in memory instead of the reloaded copy.
  • nestedEmptyRecurrentRowsSurvivePromptCacheRoundTrip, renamed nestedEmptyRecurrentRowsSurviveJoinsButNotSaving: the same change for the nested CacheList. The save throws and writes no file, and the row checks and joins run on the batch in memory.
  • recurrentRowCountMetadataCompatibility:
    • The two restores that used five fields now use the same four. The masks they assert are unchanged.
    • After finalize(), it now expects metaState == ["2", ""] (it was ["2", "", "", "", "2"]) plus a new batchSize == 2 check.
  • corruptRecurrentRowCountMetadataIsRejected is 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

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 5, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-12T08:03:17.614447Z c7a591b New commits
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 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".

Comment thread Libraries/MLXLMCommon/KVCache.swift Resolved

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 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".

@ronaldmannak

Copy link
Copy Markdown
Owner Author

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:

  • ArraysCache.merge sizes an empty input's zero state by its batchSize (what its padding says) instead of one row; a zero-row empty cache contributes no row (test: mergeKeepsEmptyInputRows).
  • CacheList.makeMask looks for the batched attention cache through nested lists, not only immediate children (test: nestedCompositeMask).

ronaldmannak added a commit that referenced this pull request Nov 5, 2026
…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>
ronaldmannak added a commit that referenced this pull request Nov 5, 2026
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>
ronaldmannak added a commit that referenced this pull request Nov 5, 2026
…dren aligned

With extend joining empty and prefilled rows as padding (#88), the attention child and the recurrent child of a merged empty list keep the same row count when prefilled rows join (Codex review on #90).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 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".

@ronaldmannak

Copy link
Copy Markdown
Owner Author

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.

@ronaldmannak

Copy link
Copy Markdown
Owner Author

Re the Codex finding on an all-empty recurrent merge losing its row count (BatchedCaches.swift:76): fixed in the latest commit ("Give an all-empty recurrent merge its rows' padding"). As in mlx-lm (cache.left_padding = mx.array([0] * B)), a merge of only empty recurrent caches now gives every row zero padding, so batchSize survives later merges and extends; ArraysCache.makeMask combines padding and lengths when both exist, as mlx-lm's does, instead of letting padding hide the lengths. New test allEmptyMergeKeepsRows covers merging two fresh caches, then merging the result with a populated one (3 rows), and extending an all-empty composite batch with prefilled rows with its children aligned; mergedRecurrentMasksByLengths now expects the zero padding.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 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".

@ronaldmannak

Copy link
Copy Markdown
Owner Author

Correction to my reply on the all-empty recurrent merge: the full suite showed that combining padding and lengths in ArraysCache.makeMask breaks the existing KVCacheTests.testArraysCacheAdvanceUpdatesLengthsAndLeftPaddingMasks, which asserts the rule on main (padding takes precedence over lengths). mlx-lm combines them, so the Swift port and mlx-lm differ here; that existing test is not mine to change, so the latest commit ("Count an all-empty recurrent batch's rows without padding, and keep main's mask") puts the mask back to main's and keeps the row count another way: an empty cache records the rows it stands for in emptyRowCount, which batchSize reads after the arrays, padding and lengths, and which filter and extend carry. allEmptyMergeKeepsRows still passes (two fresh caches, then a populated one, give three rows; an all-empty composite extends with aligned children), and mergedRecurrentMasksByLengths again expects no padding and the lengths mask.

Whether makeMask should follow mlx-lm and combine padding with lengths is a behaviour change to main with an existing test against it, so I left it for a human decision rather than editing that test.

@ronaldmannak

Copy link
Copy Markdown
Owner Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Swish!

Reviewed commit: 734541eeec

ℹ️ 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".

@ronaldmannak
ronaldmannak force-pushed the claude/a3-recurrent-composite-merge branch from 6ae2606 to f714ea4 Compare November 6, 2026 03:54
@ronaldmannak
ronaldmannak force-pushed the claude/a2-batch-rotating-kvcache branch from 17a7d50 to 0a4975f Compare November 6, 2026 03:54
@ronaldmannak ronaldmannak changed the title Merge recurrent and composite caches into batches Merge recurrent and composite cache rows without losing state Nov 6, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 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".

Comment thread Libraries/MLXLMCommon/KVCache.swift Resolved
Comment thread Libraries/MLXLMCommon/KVCache.swift Resolved
@ronaldmannak
ronaldmannak deleted the claude/a3-recurrent-composite-merge branch November 7, 2026 01:02
@ronaldmannak
ronaldmannak restored the claude/a3-recurrent-composite-merge branch November 7, 2026 01:02
@ronaldmannak ronaldmannak reopened this Nov 7, 2026
@ronaldmannak
ronaldmannak changed the base branch from batching/a2-batch-rotating-kvcache to claude/a2-batch-rotating-kvcache November 7, 2026 01:03
@ronaldmannak
ronaldmannak force-pushed the claude/a3-recurrent-composite-merge branch from 3d23343 to ba0526f Compare November 7, 2026 05:11
@ronaldmannak
ronaldmannak force-pushed the claude/a2-batch-rotating-kvcache branch from 4392aff to 70d26a2 Compare November 7, 2026 05:11

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 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".

Comment on lines +115 to +118
public static func merge(_ caches: [ArraysCache]) -> ArraysCache {
precondition(!caches.isEmpty, "merge needs a cache")
do {
try validateMerge(caches)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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 👍 / 👎.

@ronaldmannak
ronaldmannak force-pushed the claude/a2-batch-rotating-kvcache branch from 70d26a2 to fc7cb8a Compare November 7, 2026 06:25
@ronaldmannak
ronaldmannak force-pushed the claude/a3-recurrent-composite-merge branch from ba0526f to 5dafbe0 Compare November 7, 2026 06:25
ronaldmannak and others added 7 commits November 6, 2026 23:47
…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>
@ronaldmannak
ronaldmannak force-pushed the claude/a3-recurrent-composite-merge branch from 5dafbe0 to a35cbe2 Compare November 7, 2026 08:11
@ronaldmannak
ronaldmannak force-pushed the claude/a2-batch-rotating-kvcache branch from fc7cb8a to 081b109 Compare November 7, 2026 08:11
ronaldmannak and others added 6 commits November 7, 2026 06:17
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>
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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants