Repository navigation
feat: serialize paged KV block contents for node handoff - #185
Merged
Merged
Conversation
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).
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.
Member
Author
Orchestrator verification (Metal gate) + review summaryVerified 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)
Bugs found and fixed during verification
Review outcomes
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):
Checks: cold clippy ( |
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.
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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
PagedBlockPoolblock CONTENTS, ship it through the existingkv_cache_serdewire 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 densekeys/valuesbuffers areNone(the data lives in the sharedPagedBlockPool), and the serializedblock_idsare 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-coreprimitivesPagedBlockPool::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 fromcopy_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 liveUniquePtr<MlxArray>K/V, becausemlxcel-core(the lower crate) cannot reference the upper-crate serde types.CachePool::extract_paged_blocks(cache.rs): onePagedBlockContentsper 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-onlyrestore_paged_statewhich swaps theRc), and advances each cache's RoPEoffsetto the restored prefix length (mirrorsadopt_paged_preserving).CachePool::get(cache.rs): immutable accessor mirroringget_mut.kv_cache_serde(uppermlxcelcrate)SerializablePagedBlockand apaged_blocksfield onSerializableCacheState(types.rs).serde(default)+skip_serializing_if = "Vec::is_empty"keep the wire format backward compatible; tensor bytes ride inside the JSON metadata asRawTensorData, same as the denseentries(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 ofserialize_sequence_cache_setthat attaches block contents viaextract_paged_blocks.restore_into_cache_pool_sequence(deserialize.rs): takes the content path whenpaged_blocksis non-empty (skips the dense restore, which is empty for pool-backed sequences, and callsrestore_paged_state_with_contents). The empty case keeps the existing dense / metadata-only behavior unchanged.kv_cache_serde/mod.rsanddistributed/mod.rs.Scope boundary
This wires the
kv_cache_serdemodule's own public flow plus themlxcel-coreprimitives it needs. The live disaggregated scheduler (prefill_scheduler.rs/decode_scheduler.rs), a real transport, and a concreteHandoffProtocolimpl are still greenfield and are the epic capstone #126; they are intentionally untouched here.tests/disaggregated_e2e.rsremains 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,acceleratecargo check -p mlxcel --lib --features metal,acceleratecargo clippy -p mlxcel-core --lib --tests --features metal,accelerate -- -D warningscargo clippy -p mlxcel --tests --features metal,accelerate -- -D warnings--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, andlive_block_count/paged_statsparity.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:
Closes #125