Repository navigation
feat: transparent pool-backed KVCache + real-model paged parity test - #152
Merged
Merged
Conversation
Add an optional, transparent paged-pool backing to `KVCache` so a real model can run prefill + decode where each layer's cache writes new K/V into a shared `PagedBlockPool` (`write_prefill`) and reads the visible window back (`gather_visible`) — without changing the model `forward` at all. This is the single-stream (B==1) verification slice that proves the paged KV primitives (#118 layout / #119 write / #120 read) actually work end-to-end through a real model, and the groundwork for the scheduler-driven wiring (#121). Design (additive; the dense path is byte-for-byte unchanged): - New `KVCache::paged_backing: Option<PagedBacking>`, defaulted to `None` in both struct-literal constructors (`new`, `new_with_mode_and_seed`). Every other construction path (`new_with_mode`, `adopt`, detach round-trip) goes through those, so all existing call sites are untouched. - `PagedBacking` holds `Rc<RefCell<PagedBlockPool>>` + `Rc<RefCell<PagedSequenceState>>` + `layer_idx`. `Rc<RefCell<…>>` (not raw pointers) is sound here: `KVCache` is never required to be `Send`/`Sync` (no `unsafe impl`, no `assert_send_sync::<KVCache>()`; the only async-context `Vec<KVCache>` — the pipeline stage service — is built and driven entirely on one OS thread via `block_on` on a current-thread runtime, never crossing a `tokio::spawn` boundary). - `KVCache::new_paged(pool, state, layer_idx)` builds a pool-backed Fp16 cache. - Single intercept point at the top of `update_and_fetch` (the only cache method qwen3 calls for plain Fp16 prefill and decode): when pool-backed, append via `write_prefill`, bump `self.offset += n_new` exactly as dense `update_fp16` does (RoPE reads `cache.offset` before the next call), and return `gather_visible(...)` — the dense `self.update(...)` is skipped so there is no double-write. K/V dtype is preserved (no astype). Test `tests/paged_real_model_parity.rs` (`#[ignore]`, soft-skips when `models/qwen3-0.6b-4bit` is absent): runs the identical prefill + 16-step greedy decode loop against a dense `make_caches()` and against a `Vec<KVCache>` of `new_paged(...)` sharing one pool, and asserts the two greedy token sequences are identical (plus prints both). Run it with: cargo test --test paged_real_model_parity --release --features metal,accelerate -- --ignored --nocapture
7 tasks done
inureyes
added a commit
that referenced
this pull request
Jun 6, 2026
) * feat: back paged scheduler sequences with the shared KV block pool Sub-step (a) of #121: make the live batch scheduler's paged decode backend actually use the PagedBlockPool that #118-120 built and #152 proved through a real model. Path A — the pool rides inside the KVCache, so the LanguageModel trait and forward signature stay unchanged. CachePool refactor (behaviour-preserving): `paged_pool` and `SequenceCacheSet.paged` become `Rc<RefCell<…>>` so a pool-backed sequence shares one authoritative block table across its per-layer caches. Every access site (allocate, detach/adopt/park, sync, stats, restore, accessors) now scopes its borrows tightly; the request-boundary pool/state borrows never nest with the forward's `update_and_fetch` borrows. Live wiring: `CachePool::allocate` builds pool-backed caches (`KVCache::new_paged`) for paged sequences whose model uses the dense external KVCache slice (qwen3/llama3) under an Fp16 layout; model-owned families (gemma3/llama4/qwen3_5) and Turbo4 layouts keep their existing dense placeholders. The qwen3/llama3 batched-decode dispatch skips the native dense-pointer kernel when any cache `is_paged_backed()` and falls through to the per-sequence `update_and_fetch` loop, whose pool intercept writes the new K/V (`write_prefill`) and gathers the visible window (`gather_visible`). `update` gained the same intercept so the single-sequence fused causal prefill path (llama3) also writes to the pool. `sync_paged_state_with_dense` skips pool-backed sequences (the pool is authoritative), and `trim`/`trim_front` are dense-side no-ops for them. Hybrid-SSM carve-out: confirmed `effective_decode_storage_backend` already excludes recurrent models — they keep `supports_batching() == false` and the `supports_paged_decode_backend()` default `false`, either of which forces the dense backend. Added a test pinning the combined SSM profile across batch sizes. Verification: new `tests/paged_scheduler_parity.rs` (`#[ignore]`, qwen3-0.6b-4bit) drives the scheduler's paged allocation path (single-sequence and batched B=2) and asserts identical greedy tokens to the dense backend. Drive-by: fixed a pre-existing `clippy::identity_op` in `utils.rs` (`0 + 2`). * fix: per-row RoPE in fast_rope_batched to avoid MLX stride aliasing on T=1 batched decode The uniform-batch fast path collapsed fast_rope_batched to a single fast_rope over the whole [B, n_heads, T, D] tensor when all offsets matched. In batched decode (T==1) the Q/K/V arrive transposed from [B, T, n_heads, D], where swapping the size-1 sequence dim leaves stride[batch] == stride[sequence]; MLX's fast::rope Metal kernel then confuses the batch index for an intra-sequence position and rotates batch element b to position offset+b instead of offset. This silently corrupted RoPE for every batch row past the first even when sequences shared the same offset -- a latent bug affecting dense batched decode (the function's existing callers), surfaced by the paged B=2 same-prompt parity test. Drop the uniform fast path; always slice to [1, n_heads, T, D] (B==1 cannot alias) and concatenate. Adds test_fast_rope_batched_non_contiguous_t1_symmetric. * fix: keep Int8/Turbo3 paged sequences on the dense KV path (pool-backing is Fp16-only) The pool-backing gate keys on paged_layout.cache_mode == Fp16, but the scheduler built Int8 (and Turbo3Asym) paged layouts via PagedKvLayout::uniform, which stamps cache_mode = Fp16, so those sequences were pool-backed and stored as raw Fp16 -- correct output but silently losing the Int8 memory saving. Build the non-Turbo4 paged layout with uniform_with_mode(effective_mode, 0) so the layout carries the real cache mode; the gate then pool-backs only genuine Fp16 and Int8/Turbo3 keep their existing dense path. Pool-native quantized storage is a later phase.
8 tasks
be-free-snowboy
pushed a commit
to freestylejs/snowbrain-mlxcel
that referenced
this pull request
Oct 27, 2026
…ablup#152) Add an optional, transparent paged-pool backing to `KVCache` so a real model can run prefill + decode where each layer's cache writes new K/V into a shared `PagedBlockPool` (`write_prefill`) and reads the visible window back (`gather_visible`) — without changing the model `forward` at all. This is the single-stream (B==1) verification slice that proves the paged KV primitives (lablup#118 layout / lablup#119 write / lablup#120 read) actually work end-to-end through a real model, and the groundwork for the scheduler-driven wiring (lablup#121). Design (additive; the dense path is byte-for-byte unchanged): - New `KVCache::paged_backing: Option<PagedBacking>`, defaulted to `None` in both struct-literal constructors (`new`, `new_with_mode_and_seed`). Every other construction path (`new_with_mode`, `adopt`, detach round-trip) goes through those, so all existing call sites are untouched. - `PagedBacking` holds `Rc<RefCell<PagedBlockPool>>` + `Rc<RefCell<PagedSequenceState>>` + `layer_idx`. `Rc<RefCell<…>>` (not raw pointers) is sound here: `KVCache` is never required to be `Send`/`Sync` (no `unsafe impl`, no `assert_send_sync::<KVCache>()`; the only async-context `Vec<KVCache>` — the pipeline stage service — is built and driven entirely on one OS thread via `block_on` on a current-thread runtime, never crossing a `tokio::spawn` boundary). - `KVCache::new_paged(pool, state, layer_idx)` builds a pool-backed Fp16 cache. - Single intercept point at the top of `update_and_fetch` (the only cache method qwen3 calls for plain Fp16 prefill and decode): when pool-backed, append via `write_prefill`, bump `self.offset += n_new` exactly as dense `update_fp16` does (RoPE reads `cache.offset` before the next call), and return `gather_visible(...)` — the dense `self.update(...)` is skipped so there is no double-write. K/V dtype is preserved (no astype). Test `tests/paged_real_model_parity.rs` (`#[ignore]`, soft-skips when `models/qwen3-0.6b-4bit` is absent): runs the identical prefill + 16-step greedy decode loop against a dense `make_caches()` and against a `Vec<KVCache>` of `new_paged(...)` sharing one pool, and asserts the two greedy token sequences are identical (plus prints both). Run it with: cargo test --test paged_real_model_parity --release --features metal,accelerate -- --ignored --nocapture
be-free-snowboy
pushed a commit
to freestylejs/snowbrain-mlxcel
that referenced
this pull request
Oct 27, 2026
…ablup#167) * feat: back paged scheduler sequences with the shared KV block pool Sub-step (a) of lablup#121: make the live batch scheduler's paged decode backend actually use the PagedBlockPool that lablup#118-120 built and lablup#152 proved through a real model. Path A — the pool rides inside the KVCache, so the LanguageModel trait and forward signature stay unchanged. CachePool refactor (behaviour-preserving): `paged_pool` and `SequenceCacheSet.paged` become `Rc<RefCell<…>>` so a pool-backed sequence shares one authoritative block table across its per-layer caches. Every access site (allocate, detach/adopt/park, sync, stats, restore, accessors) now scopes its borrows tightly; the request-boundary pool/state borrows never nest with the forward's `update_and_fetch` borrows. Live wiring: `CachePool::allocate` builds pool-backed caches (`KVCache::new_paged`) for paged sequences whose model uses the dense external KVCache slice (qwen3/llama3) under an Fp16 layout; model-owned families (gemma3/llama4/qwen3_5) and Turbo4 layouts keep their existing dense placeholders. The qwen3/llama3 batched-decode dispatch skips the native dense-pointer kernel when any cache `is_paged_backed()` and falls through to the per-sequence `update_and_fetch` loop, whose pool intercept writes the new K/V (`write_prefill`) and gathers the visible window (`gather_visible`). `update` gained the same intercept so the single-sequence fused causal prefill path (llama3) also writes to the pool. `sync_paged_state_with_dense` skips pool-backed sequences (the pool is authoritative), and `trim`/`trim_front` are dense-side no-ops for them. Hybrid-SSM carve-out: confirmed `effective_decode_storage_backend` already excludes recurrent models — they keep `supports_batching() == false` and the `supports_paged_decode_backend()` default `false`, either of which forces the dense backend. Added a test pinning the combined SSM profile across batch sizes. Verification: new `tests/paged_scheduler_parity.rs` (`#[ignore]`, qwen3-0.6b-4bit) drives the scheduler's paged allocation path (single-sequence and batched B=2) and asserts identical greedy tokens to the dense backend. Drive-by: fixed a pre-existing `clippy::identity_op` in `utils.rs` (`0 + 2`). * fix: per-row RoPE in fast_rope_batched to avoid MLX stride aliasing on T=1 batched decode The uniform-batch fast path collapsed fast_rope_batched to a single fast_rope over the whole [B, n_heads, T, D] tensor when all offsets matched. In batched decode (T==1) the Q/K/V arrive transposed from [B, T, n_heads, D], where swapping the size-1 sequence dim leaves stride[batch] == stride[sequence]; MLX's fast::rope Metal kernel then confuses the batch index for an intra-sequence position and rotates batch element b to position offset+b instead of offset. This silently corrupted RoPE for every batch row past the first even when sequences shared the same offset -- a latent bug affecting dense batched decode (the function's existing callers), surfaced by the paged B=2 same-prompt parity test. Drop the uniform fast path; always slice to [1, n_heads, T, D] (B==1 cannot alias) and concatenate. Adds test_fast_rope_batched_non_contiguous_t1_symmetric. * fix: keep Int8/Turbo3 paged sequences on the dense KV path (pool-backing is Fp16-only) The pool-backing gate keys on paged_layout.cache_mode == Fp16, but the scheduler built Int8 (and Turbo3Asym) paged layouts via PagedKvLayout::uniform, which stamps cache_mode = Fp16, so those sequences were pool-backed and stored as raw Fp16 -- correct output but silently losing the Int8 memory saving. Build the non-Turbo4 paged layout with uniform_with_mode(effective_mode, 0) so the layout carries the real cache mode; the gate then pool-backs only genuine Fp16 and Int8/Turbo3 keep their existing dense path. Pool-native quantized storage is a later phase.
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
Single-stream verification slice for the merged paged KV cache (epic #116, phases #118 layout / #119 write / #120 read): add a transparent pool-backed path to
KVCacheand a real-model parity test that proves those primitives actually work end-to-end through a real model'sforward. This is the foundational, single-stream (B == 1) groundwork for the scheduler wiring tracked in #121. It is a verification slice only and intentionally carries no closing keyword, so merging it must not auto-close any issue.It deliberately leaves the model
forward,generate.rs, and all C++ untouched: a pool-backed cache is opt-in perKVCache, somodel.forward(&input, &mut caches, mask)is unchanged and the existing dense path is byte-for-byte identical.What changed
src/lib/mlxcel-core/src/cache.rsKVCache::paged_backing: Option<PagedBacking>, defaulted toNonein both struct-literal constructors (KVCache::new,KVCache::new_with_mode_and_seed). Every other construction path (new_with_mode,CachePool::adopt, the detach/adopt round-trip) routes through those two, so all existing call sites are unchanged and the dense path is unaffected.PagedBacking { pool: Rc<RefCell<PagedBlockPool>>, state: Rc<RefCell<PagedSequenceState>>, layer_idx }. All layers of one sequence share thepool/statehandles (cheapRcclones);layer_idxselects this cache's slice of the per-sequence state.RefCellprovides the&mutaccessupdate_and_fetchneeds while the model only hands caches out behind&mut [KVCache]one layer at a time.KVCache::new_paged(pool, state, layer_idx)builds a pool-backed Fp16 cache.update_and_fetch— the only cache method qwen3 calls for plain Fp16 prefill (l > 1) and decode (l == 1). When pool-backed it appends viawrite_prefill(works for bulk prefill and a single decode token), bumpsself.offset += n_newexactly as the denseupdate_fp16does, and returnsgather_visible(...). The denseself.update(...)is skipped on this path so there is no double-write/allocate. K/V dtype is preserved (noastype).tests/paged_real_model_parity.rs(new)#[ignore]integration test that soft-skips whenmodels/qwen3-0.6b-4bitis absent. Runs the identical prefill + 16-step greedy decode loop against (a) a densemodel.make_caches()and (b) aVec<KVCache>ofnew_paged(...)sharing onePagedBlockPool, then asserts the two greedy token sequences are identical (and prints both). Identical generation is the decisive "it actually works through a real model" signal.Why
Rc<RefCell<…>>and not raw pointersKVCacheis not required to beSend/Syncanywhere in the tree: there is nounsafe impl Send for KVCache, noassert_send_sync::<KVCache>(), and the only place aVec<KVCache>lives in an async context (the pipeline stage service'scaches_by_request) is built and driven entirely inside one OS thread viablock_onon anew_current_threadruntime — it never crosses atokio::spawn(multi-thread,Send-requiring) boundary. The safe shared-ownership form is therefore correct and preferred.Test plan
cargo check --lib -p mlxcel-core --features metal,acceleratecargo clippy --lib -p mlxcel-core --features metal,accelerate -- -D warnings(warm and cold viacargo clean -p mlxcel-core)cargo check --tests -p mlxcel-core --features metal,acceleratecargo clippy -p mlxcel-core --tests --features metal,accelerate -- -D warningscargo check --test paged_real_model_parity --features metal,acceleratecargo clippy --test paged_real_model_parity --features metal,accelerate -- -D warningscargo fmt --checkReal-model parity (GPU; not run here — requires
models/qwen3-0.6b-4bit):