Skip to content

feat: serialize paged KV block contents for node handoff - #185

Merged
inureyes merged 5 commits into
mainfrom
feature/issue-125-paged-kv-serde
Jun 8, 2026
Merged

inureyes merged 5 commits into
mainfrom
feature/issue-125-paged-kv-serde

Conversation

@inureyes

@inureyes inureyes commented Jun 8, 2026

Copy link
Copy Markdown
Member

Summary

Implements distributed paged KV block-content transfer ("Approach A") for issue #125 (part of epic #116, the unified paged KV cache). A prefill node can now serialize a POOL-BACKED (Fp16 paged) sequence's KV, including the referenced PagedBlockPool block CONTENTS, ship it through the existing kv_cache_serde wire format, and a decode node reconstructs identical KV on fresh pool blocks so decode continues bit-identically, with block accounting (refcounts) after restore matching the origin.

Why

Before this change the serde path transferred dense per-layer KV plus paged block-table METADATA only. For pool-backed sequences (the Fp16 paged path from #121, built via KVCache::new_paged) the dense keys/values buffers are None (the data lives in the shared PagedBlockPool), and the serialized block_ids are origin-node PHYSICAL ids that are meaningless on the decode pool. So the handoff transferred no usable KV for pool-backed sequences. This PR closes that gap by transferring the block contents and remapping to fresh decode-side block ids on restore.

What changed

mlxcel-core primitives

  • PagedBlockPool::read_block_contents (src/lib/mlxcel-core/src/cache/paged.rs): reads one block's full [block_size, n_kv_heads, head_dim] K/V slabs out of the pool tensors, reusing the exact slab-read logic from copy_on_write_block.
  • PagedBlockPool::acquire_and_write_block (paged.rs): acquires a fresh block and writes a bare layout-A slab at slot 0 (refcount 1).
  • PagedBlockContents (src/lib/mlxcel-core/src/cache.rs): a plain runtime carrier holding live UniquePtr<MlxArray> K/V, because mlxcel-core (the lower crate) cannot reference the upper-crate serde types.
  • CachePool::extract_paged_blocks (cache.rs): one PagedBlockContents per distinct pool block in the sequence's table (sequence-wide dedup). Returns empty for dense / model-owned / non-pool-backed sequences ("nothing pool-paged to transfer").
  • CachePool::restore_paged_state_with_contents (cache.rs): acquires + writes a fresh block per transferred block, remaps the block table over the fresh ids, replaces the shared paged-state cell contents IN PLACE (so the pool-backed caches keep observing it, unlike the metadata-only restore_paged_state which swaps the Rc), and advances each cache's RoPE offset to the restored prefix length (mirrors adopt_paged_preserving).
  • CachePool::get (cache.rs): immutable accessor mirroring get_mut.

kv_cache_serde (upper mlxcel crate)

  • SerializablePagedBlock and a paged_blocks field on SerializableCacheState (types.rs). serde(default) + skip_serializing_if = "Vec::is_empty" keep the wire format backward compatible; tensor bytes ride inside the JSON metadata as RawTensorData, same as the dense entries (a compact binary framing is deferred to End-to-end validation, parity, benchmarks, and docs #126).
  • serialize_cache_pool_sequence (serialize.rs): pool-aware superset of serialize_sequence_cache_set that attaches block contents via extract_paged_blocks.
  • restore_into_cache_pool_sequence (deserialize.rs): takes the content path when paged_blocks is non-empty (skips the dense restore, which is empty for pool-backed sequences, and calls restore_paged_state_with_contents). The empty case keeps the existing dense / metadata-only behavior unchanged.
  • Re-exports updated in kv_cache_serde/mod.rs and distributed/mod.rs.

Scope boundary

This wires the kv_cache_serde module's own public flow plus the mlxcel-core primitives it needs. The live disaggregated scheduler (prefill_scheduler.rs / decode_scheduler.rs), a real transport, and a concrete HandoffProtocol impl are still greenfield and are the epic capstone #126; they are intentionally untouched here. tests/disaggregated_e2e.rs remains a mock.

This path is Fp16 pool-backed only (SSM / model-owned families keep their KV model-internal and are excluded from donate/detach per #124). Turbo sidecar transfer is out of scope for the Fp16 path.

Test plan

  • cargo check -p mlxcel-core --lib --features metal,accelerate
  • cargo check -p mlxcel --lib --features metal,accelerate
  • cargo clippy -p mlxcel-core --lib --tests --features metal,accelerate -- -D warnings
  • cargo clippy -p mlxcel --tests --features metal,accelerate -- -D warnings
  • New CPU unit tests compile (mlxcel-core --tests): pool-level round-trip (extract_then_restore_with_contents_round_trips) and CachePool-level round-trip (cache_pool_extract_and_restore_with_contents_round_trips), asserting byte-identical content, per-block refcount == 1, and live_block_count / paged_stats parity.
  • Real-model parity (tests/paged_kv_serialize_parity.rs, qwen3 + llama3, #[ignore]): single-node decode vs serialize/wire/restore handoff decode. Left for the orchestrator to run on Metal (no reliable GPU here).

Run the parity test on Metal with:

cargo test --test paged_kv_serialize_parity --release --features metal,accelerate -- --ignored --nocapture --test-threads=1

Closes #125

The distributed kv_cache_serde path transfers dense per-layer KV plus paged block-table METADATA, but for POOL-BACKED (Fp16 paged) sequences the dense buffers are empty (the data lives in the shared PagedBlockPool) and the serialized block ids are origin-node physical ids that are meaningless on the decode pool, so no usable KV crosses the boundary. This implements true pool-block CONTENT transfer ("Approach A"): the prefill node ships each referenced pool block's K/V, and the decode node re-materializes it on fresh blocks.

mlxcel-core primitives: PagedBlockPool gains read_block_contents (reads a block's full [block_size, n_kv_heads, head_dim] K/V slabs, reusing the copy-on-write slab logic) and acquire_and_write_block (acquire a fresh block then write a slab at slot 0, refcount 1). A new plain carrier struct PagedBlockContents ferries live K/V across the crate boundary, since mlxcel-core cannot reference the upper-crate serde types. CachePool gains extract_paged_blocks (one PagedBlockContents per distinct pool block, deduped, empty for dense or model-owned sequences) and restore_paged_state_with_contents (acquire and write fresh blocks, remap the block table over the fresh ids, replace the shared paged-state cell contents IN PLACE so the pool-backed caches keep observing it, and advance each cache's RoPE offset to the restored prefix length), plus a get accessor mirroring get_mut.

kv_cache_serde: a new SerializablePagedBlock type and a paged_blocks field on SerializableCacheState (serde default plus skip_serializing_if keeps the wire format backward compatible). serialize_cache_pool_sequence is the pool-aware superset of serialize_sequence_cache_set that attaches the block contents via CachePool::extract_paged_blocks. restore_into_cache_pool_sequence takes the content path when paged_blocks is non-empty (skipping the dense restore, which is empty for pool-backed sequences, and calling restore_paged_state_with_contents); the empty case keeps the existing dense / metadata-only behavior unchanged.

Scope boundary: this wires the kv_cache_serde module's own public flow plus the mlxcel-core primitives it needs. The live disaggregated scheduler, a real transport, and a concrete HandoffProtocol are still greenfield and are the epic capstone #126; they are intentionally untouched here.

Tests: a pool-level round-trip (read_block_contents plus acquire_and_write_block, byte-identical gather, fresh disjoint ids, per-block refcount and live-count parity), a CachePool-level extract/restore round-trip (paged_stats plus content-byte parity between origin and decode pools), and a gated (#[ignore]) real-model parity test for qwen3 and llama3 that compares a single-node prefill+decode against a serialize, wire round-trip, and restore handoff (run on Metal).
@inureyes inureyes added status:review Under review type:enhancement New features, capabilities, or significant additions area:core mlxcel-core: MLX FFI, primitives, KV cache, layers labels Jun 8, 2026
inureyes added 3 commits June 9, 2026 01:01
The distributed paged KV handoff (#125) ships pool block contents through array_to_raw_bytes, the wire format, and from_bytes. Two latent bugs corrupted every 16-bit transfer. from_bytes routed FLOAT16 (9) and BFLOAT16 (12) through its default case, which reinterprets the byte pointer as uint8 and casts one value per byte, reading only half the data and mangling the rest; it now reinterprets 2-byte pairs via make_array_typed<float16_t>/<bfloat16_t>, matching the existing FLOAT32 case. Separately, mlx_dtype_element_size reported BFLOAT16 as 4 bytes, so validate_raw_tensor rejected valid bf16 payloads before reconstruction; it is now 2 bytes.

Both bugs also affected the dense KV serde path (reconstruct_mlx_array), which had never been exercised with real fp16/bf16 model tensors. Lock the regression with fp16 and bf16 byte-round-trip pool tests, and add per-layer gather-window and RoPE-offset parity assertions to the real-model handoff test so any future content or position drift fails loudly.
restore_paged_state_with_contents acquires a fresh pool block per transferred block in a loop; a mid-loop failure (a malformed or oversized transferred slab rejected by write_block, an out-of-range layer_idx, a block-budget rejection, or a block-table entry with no matching contents) previously left every already-acquired block stranded at refcount 1, a permanent leak that accumulates across handoffs and can exhaust the decode node's block pool. acquire_and_write_block also leaked the block it had just minted when write_block failed, since acquire precedes the fallible write.

Track the freshly acquired ids and release them on any acquire/write error or missing-contents remap miss before returning, and release the minted block inside acquire_and_write_block when the write fails. release_block on a fresh, single-owner block is a clean refcount drop to zero with no double-free, and the success path is byte-identical so the handoff parity holds. Found by the PR security review; locked with a pool-level rejected-write test and a CachePool-level missing-remap restore test that both assert live_block_count returns to baseline.
Whitespace-only normalization of the paged KV block-content serde additions, no semantic change.
@inureyes inureyes added status:done Completed and removed status:review Under review labels Jun 8, 2026
@inureyes

inureyes commented Jun 8, 2026

Copy link
Copy Markdown
Member Author

Orchestrator verification (Metal gate) + review summary

Verified end-to-end on Apple Silicon (Metal). The sub-agent's implementation compiled and its unit tests passed, but the real-model handoff exposed two latent bugs that the single-layer FP32 unit tests could not catch; both are now fixed and locked with regressions.

Real-model parity (authoritative DoD)

tests/paged_kv_serialize_parity.rs passes for both pool-backed families: prefill -> serialize_cache_pool_sequence -> binary wire round-trip -> fresh decode CachePool -> content-path restore -> decode is BYTE-IDENTICAL to the single-node run.

  • qwen3-0.6b-4bit: 56 pool blocks reconstructed across the wire, 16 decode steps identical.
  • llama-3.2-1b-4bit: 32 pool blocks reconstructed, 16 decode steps identical.
  • Per-layer gathered-window parity, RoPE-offset parity, and block accounting (live_block_count + paged_stats) parity all asserted.

Bugs found and fixed during verification

  1. from_bytes (cpp) routed FLOAT16 (9) and BFLOAT16 (12) through its default uint8 case, reading one value per byte instead of reinterpreting 2-byte pairs, corrupting every 16-bit transfer. Added explicit float16_t/bfloat16_t cases. mlx_dtype_element_size also reported BFLOAT16 as 4 bytes, so validate_raw_tensor rejected valid bf16 payloads; now 2 bytes. Both also repaired the dense KV serde path, which had never been exercised with real fp16/bf16 model tensors.
  2. Restore partial-failure block leak (found by the security review): a mid-loop failure in restore_paged_state_with_contents (malformed slab, bad layer, budget rejection, missing-contents remap) stranded already-acquired pool blocks at refcount 1, an accumulating leak. Fresh blocks are now released on every error path, and acquire_and_write_block releases its block when the write fails.

Review outcomes

  • pr-reviewer: APPROVE, no CRITICAL/HIGH/MEDIUM. It independently confirmed the in-place state-cell replacement keeps the pool-backed caches' shared Rc valid, the refcount/COW/remap logic, and wire backward-compat.
  • pr-security-checker: core memory safety verified (validate_raw_tensor runs before from_bytes, so no OOB); fixed the HIGH leak above.

Deferred to #126 (epic capstone: live disaggregated scheduler + transport + E2E)

These relate to the untrusted-network surface, which this PR does not wire (no live socket yet):

  • Empty pool-backed sequence (zero prefill tokens) would route to the metadata-only restore_paged_state; unreachable in a genuine handoff (a prefilled sequence always has a non-empty block table).
  • Anchor each transferred slab's n_kv_heads x head_dim x dtype to the decode model's real KV geometry, and cap total transferred blocks/bytes per handoff.
  • Validate that each (block_id, layer_idx) the table needs has matching contents on the same layer.
  • Cap the accepted frame size in the End-to-end validation, parity, benchmarks, and docs #126 frame reader.

Checks: cold clippy (metal,accelerate, -D warnings) clean on both crates; cache:: suite 386 passed / 0 failed; rustfmt applied.

The #125 handoff caught a from_bytes bug that corrupted every 16-bit float tensor (it read the bytes per-byte as uint8 instead of reinterpreting 2-byte pairs), latent because all prior round-trip tests used FP32, which has an explicit from_bytes case. Add a low-level FFI guard (from_bytes_round_trips_16bit_floats_bit_exactly) asserting byte-exact round-trip for FLOAT16/BFLOAT16/FLOAT32 directly through array_to_raw_bytes/from_bytes, and a serde-layer guard (reconstruct_mlx_array_round_trips_16bit_floats) covering the distributed restore path. Both are plain unit tests, so they run in the local make verify gate alongside the pool-level byte-roundtrip and the real-model handoff regressions.
@inureyes
inureyes merged commit 92273c6 into main Jun 8, 2026
5 checks passed
@inureyes
inureyes deleted the feature/issue-125-paged-kv-serde branch June 8, 2026 17:24
@inureyes inureyes self-assigned this Jun 10, 2026
@inureyes inureyes added this to the 0.2 milestone Jun 21, 2026
be-free-snowboy pushed a commit to freestylejs/snowbrain-mlxcel that referenced this pull request Oct 27, 2026
Implements distributed paged KV block-content transfer (Approach A) for a prefill-to-decode handoff of pool-backed (Fp16/BFloat16) sequences: serialize the referenced pool blocks plus the block table, then reconstruct identical KV on fresh decode-side blocks with matching refcount accounting. Part of epic lablup#116.

Includes two correctness fixes the real-model handoff gate surfaced, both also latent in the dense KV serde path: from_bytes silently corrupted 16-bit float round-trips (it read the bytes per-byte as uint8 instead of reinterpreting 2-byte pairs), and restore_paged_state_with_contents leaked pool blocks on a partial-failure path. Verified with real-model handoff parity (qwen3 + llama3, byte-identical decode) plus layered fp16/bf16 byte-round-trip and block-leak regression tests.

Closes lablup#125
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:core mlxcel-core: MLX FFI, primitives, KV cache, layers status:done Completed type:enhancement New features, capabilities, or significant additions

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Distributed block-table serialization (kv_cache_serde)

1 participant