Skip to content

fix(KVCache): keep the ChunkedKVCache offset and the MambaCache slots - #268

Merged
Gajesh2007 merged 3 commits into
mainfrom
fix/prompt-cache-chunked-mamba
Oct 3, 2026
Merged

Gajesh2007 merged 3 commits into
mainfrom
fix/prompt-cache-chunked-mamba

Conversation

@davidtai

@davidtai davidtai commented Oct 1, 2026 •

Copy link
Copy Markdown

Implementation

Related issue: #239. Dependency stack: #214 -> #253 -> #268 (neutral references).

  • ChunkedKVCache.state saves exactly offset - startPosition valid rows. The state and metadata setters preserve absolute offset in either setter order.
  • ArraysCache.extractSlots(_:to:) preserves empty slot positions; Mamba extraction retains its dynamic type and all optional slots.
  • Fixed verified inherited serializer defects in this PR's loader scope: an all-empty file no longer creates 0...(-1); existing class metadata determines layer count, including empty middle/trailing layers. Empty fixed-arity caches skip their fatal nonthrowing state setter.
  • Added internal PromptCacheValidation.swift before nonthrowing restoration setters: reject malformed metadata arity, invalid numeric values, invalid array inventories and unsafe nested CacheList counts with a thrown error, not a fatal setter or silent numeric fallback.
  • Compatibility review correction: left padding is a signed token-relative value. ArraysCache.advance() legitimately makes it negative; the loader now accepts signed Int padding while retaining parse/range rejection and all other inventory/position guards. This fixes an introduced rejection on the earlier preparation head d4a75147.
  • CacheList counts are checked against remaining state/metadata before slicing, and trailing inventory is rejected. Parsed array/metadata indices are checked before indexing or growing reconstruction arrays.
  • Normally merged updated fix(KVCache): trim a chunked cache by its valid tokens #253 (05cf778635eb3d940d394c68ce8a09a62f95db32). Diff over that parent contains only persistence/extraction runtime work, its tests and its fork-map topic.

Runtime scope over updated parent: Libraries/MLXLMCommon/KVCache.swift and Libraries/MLXLMCommon/PromptCacheValidation.swift. No public signature changes or new file format.

Storage Contract

Retains existing array keys i.j, metadata keys 0.i.j, 1.key, 2.i, Chunked metadata [chunkSize, startPosition], slot-aware Arrays/Mamba metadata and documented legacy compact state ([""]). Existing unrelated named arrays remain ignored as the legacy recording requires. The old valid Chunked and Mamba fixtures remain readable. Missing layers are reconstructed only from existing class declarations, not guessed.

Left-padding entries accept signed integers, including legitimate negative values after advance(). This does not relax nonnegative slot indices/counts, chunk positions, metadata arity, nested inventory bounds or integer parsing. Nonnumeric, overflowed and malformed comma-separated padding still throws.

Historical Chunked files saved after trimming and a later update can contain padding indistinguishable from tokens. Their original valid token count cannot be recovered; this change does not invent a compatibility heuristic or claim to repair such data. Malformed declared state/metadata is now conservatively rejected. Direct in-memory nonthrowing setters retain their existing precondition behavior; validation is at the throwing file-loading boundary, not a claim of comprehensive hostile-file sandboxing.

Before

flowchart LR
  A[Trimmed cache] --> B[Inherited state getter and load setters]
  B --> C[Save padding or lose absolute offset]
  D[Sparse Mamba cache] --> E[extract through compacted state]
  E --> F[Slots shifted]
  G[Empty or malformed file] --> H[unflattenArrays and unchecked restoreCacheFromMetaState]
  H --> I[Range or setter fatal error]
  H --> J[Invalid numeric metadata silently defaults]
Loading

After

flowchart LR
  A[Trimmed cache] --> B[Chunked state valid rows and position-preserving setters]
  B --> C[Save load and next update preserve offset and context]
  D[Sparse Mamba cache] --> E[extractSlots maps every optional slot]
  E --> F[Same positions and batch row]
  G[File] --> H[loadPromptCache reads class declarations and bounded indices]
  H --> I[validatePromptCacheState and CacheList inventory guards]
  I -->|Valid empty legacy or signed-padding state| J[restoreCacheFromMetaState safely reconstructs]
  I -->|Malformed declaration| K[Throw recoverable error]
Loading

Fresh Validation (2026-10-03)

Head: 96d5f9761baa6055818af068a7f96bc5a9cdefbb, GitHub verification verified=true, reason valid. Only this PR was updated for the signed-padding correction; parent heads remain unchanged.

  • ruby cache-stack-validate.rb 268-padding-fixed; ./268-padding-fixed on CPU and REVIEW_GPU=1 ./268-padding-fixed under the shared mutex: 34 tests pass on each device. Actual authored copy, trim, Chunked/Mamba persistence suites; eleven durable validation tests; assertion-preserved cache recordings and prompt-file recordings through their serialization section.
  • Three permanent advanced-padding round-trip tests cover ArraysCache, MambaCache and a doubly nested CacheList, each with negative and positive controls. They check exact metadata, dynamic types, optional slots, payload, mask and subsequent advancement. Identical tests compiled with both cache and validation source from published d4a75147 all fail with invalid-cache errors (exit 1); parent 05cf7786 passes all three; corrected source passes. Additional malformed-padding cases still reject bad text, empty elements, mixed invalid signed text and integer overflow.
  • Read the independent verifier's paired proofs at readonly-cache-review-20261003-0924. Fresh differential and CPU/GPU logs are retained separately in cache-stack-evidence/268-padding-*.log and padding-results.json, collected by cache-stack-padding-evidence.rb. The older 31-test run did not cover advanced negative padding and was insufficient to establish that compatibility.
  • Includes real safetensors round trips for never-populated states of every supported cache type, an empty cache array, mixed empty/populated layers and a nested CacheList; retained old-format Chunked and legacy compact Mamba fixtures.
  • 36 boundary cells (chunk size 0/1/8, step 1/4/256, token count 0/1/8/10), both setter orders and idempotent metadata, copy/next-update equality, real save/load; 12 extraction cells (all four optional-slot masks across three batch rows), mutation isolation.
  • New regressions compiled against original e031bf20: unpopulated file test traps in 0...(-1) (signal 5); malformed arity traps in Chunked metadata setter (signal 5); mixed/nested empty-layer test fails with cache-count mismatch (exit 1); numeric-only test fails with two missing-error expectations (exit 1). All pass after the fix.
  • git diff --check and strict Swift format lint on both new files pass. Whole KVCache.swift strict lint still reports seven pre-existing naming/forEach findings; it was not renamed broadly to hide baseline lint debt.
  • Harness recompiles actual changed cache/loader source and relinks read-only reference dependencies: mlx-swift 0f4fe403, Cmlx core 3fa8f25e, mlx-c 02cf6f4d; owned immutable Metal SHA-256 2129f6132794d84243c02631bc7478417dba0e0dbd10467beab56c11bf20bdd2. Local harness/evidence: isolated held-pr-prep-20261003/cache-stack-* scratch. Not a fresh full SwiftPM suite or provider/checkpoint qualification.
  • Existing assertions survive; parent cleanup is inherited exactly once. No OS/activation/KV floor changes, provider pins, model downloads or production execution.

Serving Risk And Stack Gates

Generic ChatSession.saveCache calls this serializer; consumers can restore via loadPromptCache. Current library model constructors do not select ChunkedKVCache. Do not equate these SDK tests with canonical provider CBv2 qualification, which uses distinct cache paths.

Base remains fix/chunked-kvcache-trim. GitHub reports MERGEABLE against this parent, not independent main readiness. Exact new-head lint 37112426292 and fork-map 37112426301 pass; Fork Tests 37112426248 is in progress. Earlier-head checks are not substituted for these. Post-push refresh found no reviews, threads or comments; refresh again before merge. The independent negative-padding finding is addressed and differentially verified, not waived.

Only after #214 actually merges may #253 be retargeted to main. Only after #253 actually merges may this PR be retargeted to main, with own-only diff/checks revalidated before merge. No merge, deploy, retarget or shipment is performed by this preparation.

Combined Integration Validation

On 2026-10-03, the current prepared heads of the twelve held PRs were composed
on a local-only validation branch based on main 3799b115, including the
signed-padding compatibility correction 96d5f976. No PR was merged.

  • Fresh swift build --build-tests -j 4 completed successfully.
  • Affected suites: 261 Swift Testing cases and 33 executed XCTest cases passed;
    five optional fixture-dependent XCTest cases skipped. Advanced Arrays/Mamba
    and nested signed-padding round trips passed in this composed build.
  • Bounded serving integration: 107 Swift Testing cases and 105 XCTest cases
    passed, with no failures or skips, covering paged backend, scheduler,
    checkpoint engine, SSM bounds, Nemotron storage/priming, OpenAI service and
    tool parser paths.
  • Both executions used swift test --skip-build --filter ... --no-parallel
    under the shared GPU mutex. This is focused integration validation, not a
    full-package, real-weight or provider qualification. Exact compatible MLX
    dependency tuple and immutable Metal artifact were verified before staging.
  • Combined git diff --check and python3 scripts/check_forkdiff.py passed.
    Existing assertions remain intact; this evidence does not waive required
    latest-head CI, review, or parent-first retarget/revalidation gates.

davidtai and others added 2 commits October 1, 2026 15:42
The state of ChunkedKVCache came from KVCacheSimple. Its setter set the
offset to the buffer length, which is smaller than the offset after
maybeTrimFront(), so a loaded prompt cache had a wrong offset. The state
now holds only the valid tokens, and the state and metaState setters
keep offset - startPosition equal to the token count. The saved format
does not change.

MambaCache.extract(_:) went through state, which drops the empty slots.
It now copies every slot, as ArraysCache.extract does.

Fixes #239

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@Gajesh2007
Gajesh2007 changed the base branch from fix/chunked-kvcache-trim to main October 3, 2026 23:11
@Gajesh2007
Gajesh2007 merged commit 12cfc77 into main Oct 3, 2026
3 checks passed
@davidtai
davidtai deleted the fix/prompt-cache-chunked-mamba branch October 4, 2026 21:57
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