Repository navigation
feat: unify radix prompt cache with paged block pool (sub-step b of #121) - #168
Merged
Merged
Conversation
Lets two requests sharing a prompt prefix store its KV once in the paged pool and reuse it via paged adopt/donate instead of re-prefilling, removing the `try_adopt_cached_prefix` Paged guard (part of #121 sub-step b). Replace the prompt-cache store's dense-only `DetachedHolder` with a `DetachedKvSet { Dense(DetachedCacheSet), Paged(DetachedPagedCacheSet) }` union (plus a `DetachedKvSetHolder` Send/Sync newtype). `CacheEntry::new`/`take_detached` now carry either variant and `size_bytes` snapshots `DetachedKvSet::nbytes()` so byte-budget eviction accounting is backend-agnostic. The variant-aware `DetachedKvSet::is_empty()` gates a paged set on its block table / visible length (its dense handles are empty by design) rather than the dense caches. Wire the scheduler for both backends: `try_adopt_cached_prefix` drops the Paged backend guard and dispatches adoption on the union (`Dense => cache_pool.adopt`, `Paged => cache_pool.adopt_paged`), skipping on a backend/variant mismatch and releasing any paged block pins it declines to use; `donate_finished_sequence_cache` drops its dense-only rejection and detaches dense via `detach`, paged via `detach_paged`, still skipping `ModelOwned`. Short paged prefixes are length-screened before detaching so the store never takes block pins it would only have to release. Fix `adopt_paged_preserving` to reconstruct POOL-BACKED caches: for a dense-natural Fp16 sequence (the same gate `allocate_with_layout` uses) the adopted per-layer caches are rebuilt with `KVCache::new_paged` sharing the adopted block-table state and the active pool — the prefix is read straight from the pinned, refcounted pool pages with no copy — and each cache's monotonic offset is restored from its detached handle so post-adopt RoPE positions continue from the cached prefix length. The previous dense-from-handles rebuild handed pool-backed sequences empty buffers. Non-Fp16 / model-owned paged sets keep the dense-from-handles path. Concurrent prefix-share copy-on-write is already provided by the pool (#118/#120): once an adopted sequence shares blocks (refcount>1) the first write past the shared prefix forks the block. Add a `min_prefix_tokens()` accessor to `PromptCacheStore` for the donate-side length screen. Tests: CachePool-level `adopt_paged_reconstructs_pool_backed_caches_and_shares_prefix` (pool-backed adopt, shared block ids, restored offset, no double allocation, gather equality) and `pool_backed_sharers_cow_keeps_other_prefix_intact` (two live sharers, divergent-suffix COW fork, other prefix intact); a root-crate `DetachedKvSet::Paged` round-trip through `CacheEntry`; and an ignored real-model `paged_prefix_share_parity` proving B reuses A's stored prefix blocks and decodes identically to a cold run. Deferred: APC block-hash matching for paged entries; releasing store-declined/evicted paged pins under pool block-budget pressure (#122); distributed serde of `DetachedPagedCacheSet` (#125).
This was referenced Jun 7, 2026
be-free-snowboy
pushed a commit
to freestylejs/snowbrain-mlxcel
that referenced
this pull request
Oct 27, 2026
…ng (lablup#168) Lets two requests sharing a prompt prefix store its KV once in the paged pool and reuse it via paged adopt/donate instead of re-prefilling, removing the `try_adopt_cached_prefix` Paged guard (part of lablup#121 sub-step b). Replace the prompt-cache store's dense-only `DetachedHolder` with a `DetachedKvSet { Dense(DetachedCacheSet), Paged(DetachedPagedCacheSet) }` union (plus a `DetachedKvSetHolder` Send/Sync newtype). `CacheEntry::new`/`take_detached` now carry either variant and `size_bytes` snapshots `DetachedKvSet::nbytes()` so byte-budget eviction accounting is backend-agnostic. The variant-aware `DetachedKvSet::is_empty()` gates a paged set on its block table / visible length (its dense handles are empty by design) rather than the dense caches. Wire the scheduler for both backends: `try_adopt_cached_prefix` drops the Paged backend guard and dispatches adoption on the union (`Dense => cache_pool.adopt`, `Paged => cache_pool.adopt_paged`), skipping on a backend/variant mismatch and releasing any paged block pins it declines to use; `donate_finished_sequence_cache` drops its dense-only rejection and detaches dense via `detach`, paged via `detach_paged`, still skipping `ModelOwned`. Short paged prefixes are length-screened before detaching so the store never takes block pins it would only have to release. Fix `adopt_paged_preserving` to reconstruct POOL-BACKED caches: for a dense-natural Fp16 sequence (the same gate `allocate_with_layout` uses) the adopted per-layer caches are rebuilt with `KVCache::new_paged` sharing the adopted block-table state and the active pool — the prefix is read straight from the pinned, refcounted pool pages with no copy — and each cache's monotonic offset is restored from its detached handle so post-adopt RoPE positions continue from the cached prefix length. The previous dense-from-handles rebuild handed pool-backed sequences empty buffers. Non-Fp16 / model-owned paged sets keep the dense-from-handles path. Concurrent prefix-share copy-on-write is already provided by the pool (lablup#118/lablup#120): once an adopted sequence shares blocks (refcount>1) the first write past the shared prefix forks the block. Add a `min_prefix_tokens()` accessor to `PromptCacheStore` for the donate-side length screen. Tests: CachePool-level `adopt_paged_reconstructs_pool_backed_caches_and_shares_prefix` (pool-backed adopt, shared block ids, restored offset, no double allocation, gather equality) and `pool_backed_sharers_cow_keeps_other_prefix_intact` (two live sharers, divergent-suffix COW fork, other prefix intact); a root-crate `DetachedKvSet::Paged` round-trip through `CacheEntry`; and an ignored real-model `paged_prefix_share_parity` proving B reuses A's stored prefix blocks and decodes identically to a cold run. Deferred: APC block-hash matching for paged entries; releasing store-declined/evicted paged pins under pool block-budget pressure (lablup#122); distributed serde of `DetachedPagedCacheSet` (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
Part of #121 — sub-step (b) of three. Sub-step (a) (pool-backed
KVCachefor paged Fp16 sequences) is already merged.Unifies the cross-request radix prompt-prefix cache with the paged block pool so two requests sharing a prompt prefix store that prefix's KV once in the pool and the second request reuses it via paged adopt/donate instead of re-prefilling. The
try_adopt_cached_prefixPaged guard is removed.Changes
Store entry union (
src/server/prompt_cache/entry.rs)Replaces the dense-only
DetachedHolderwith an enumDetachedKvSet { Dense(DetachedCacheSet), Paged(DetachedPagedCacheSet) }plus aDetachedKvSetHolderSend/Sync newtype.CacheEntry::new/take_detachednow carry either variant;size_bytessnapshotsDetachedKvSet::nbytes()so byte-budget eviction accounting is backend-agnostic. The variant-awareDetachedKvSet::is_empty()gates a paged set on its block table / visible length (its dense per-layer handles are empty by design) rather than on the dense caches.store.rs/lookup.rsare unchanged (they work offsize_bytes/has_detached). AddedPromptCacheStore::min_prefix_tokens()for the donate-side screen below.Scheduler wiring (
src/server/batch/scheduler.rs)try_adopt_cached_prefix: drops theDecodeStorageBackend::Pagedearly return and dispatches adoption on the union —Dense => cache_pool.adopt,Paged => cache_pool.adopt_paged. Skips (cold prefill) on a backend/variant mismatch, and on any skip path that took paged block pins it releases them viarelease_detached_paged(a paged set dropped on the floor would leak its pins). The empty check is variant-aware.donate_finished_sequence_cache: drops the dense-only rejection and detachesDense => detach,Paged => detach_paged, still skippingModelOwned. Short paged prefixes are length-screened againstmin_prefix_tokens()before detaching so the store never takes block pins it would only have to release.adopt_pagedpool-backed reconstruction (src/lib/mlxcel-core/src/cache/paged_detach.rs) — key correctness changeadopt_paged_preservingpreviously rebuilt dense caches from the detached handles. For a pool-backed sequence those handles are empty (K/V lives in the pool), so the adopted sequence read garbage. It now decides pool-backing with the same gateCachePool::allocate_with_layoutuses (model.sequence_state_layout().backend == DenseKvCache && paged_layout.cache_mode == Fp16); when pool-backed it rebuilds the per-layer caches withKVCache::new_pagedsharing the adopted block-tablestate_rc+ the active pool (the block table already points at the pinned, refcounted pool pages, so the prefix is read with no copy), and restores each cache's monotonicoffsetfrom its detached handle so post-adopt RoPE positions continue from the cached prefix length. Non-Fp16/ model-owned paged sets keep the dense-from-handles path.Copy-on-write
Concurrent prefix-share COW is already provided by the pool (from #118/#120): once an adopted sequence shares blocks (refcount>1), the first write past the shared prefix forks the block. No new COW code — the adopt path just shares the blocks correctly.
Tests
cache::paged_detach::tests::adopt_paged_reconstructs_pool_backed_caches_and_shares_prefix— detach→park→adopt of a pool-backed sequence: adopted caches are pool-backed, restored offset == prefix length, shared block ids,live_blocksnot doubled,gather_visibleequals the original, and a suffix allocates only its own blocks.cache::paged_detach::tests::pool_backed_sharers_cow_keeps_other_prefix_intact— two live pool-backed sequences sharing a partial-tail prefix; a divergent suffix on one forks the shared tail (COW) while the other's prefix stays bit-identical.server::batch::scheduler_prompt_cache_tests::paged_detached_set_round_trips_through_cache_entry/empty_paged_detached_set_reports_empty— a realDetachedKvSet::Pagedround-trips throughCacheEntry::new/take_detached(one-shot) andnbytes()/is_empty()dispatch to the paged arm.tests/paged_prefix_share_parity.rs(#[ignore], qwen3-0.6b-4bit, soft-skip) — sequence A stores its prefix in a realPromptCacheStore; sequence B looks it up,adopt_pageds it (reusing A's prefix blocks, refcount asserted across the handoff), prefills only its suffix and decodes identically to a cold no-cache run.Deferred (not in this sub-step)
apc_block_hashespath stays dense-only) — a later Phase 4: Radix-trie and block-pool unification (scheduler wiring) #121 sub-step.Dropwarns. The donate-side length pre-screen avoids the common prefix-too-short case.)DetachedPagedCacheSet— tracked by Distributed block-table serialization (kv_cache_serde) #125.Validation
cargo check(both crates,--tests), coldcargo clean -p mlxcel-core && cargo clippy -p mlxcel-core --tests --features metal,accelerate -- -D warnings, and rootcargo clippy --tests --features metal,accelerate -- -D warningsare clean;cargo fmt --checkpasses.cargo test --lib -p mlxcel-core --features metal,accelerate cache::paged_detach::testscargo test -p mlxcel --lib --features metal,accelerate server::batch::scheduler_prompt_cache_testscargo test --test paged_prefix_share_parity --release --features metal,accelerate -- --ignored --nocaptureOrchestrator verification (all green, M1 Ultra, metal+accelerate): cold clippy clean (both crates);
cache::paged_detach21 passed (incl.adopt_paged_reconstructs_pool_backed_caches_and_shares_prefix+ COW + offset);scheduler_prompt_cache15 passed; full core regression 834 passed; and the real-model DoDpaged_prefix_share_matches_cold_runPASSED — sequence B reused sequence A's 2-block prefix from the radix store and decoded 16 tokens identically to a cold no-cache run.