Skip to content

feat: transparent pool-backed KVCache + real-model paged parity test - #152

Merged
inureyes merged 1 commit into
mainfrom
feat/121-pool-backed-kvcache-verify
Jun 5, 2026
Merged

inureyes merged 1 commit into
mainfrom
feat/121-pool-backed-kvcache-verify

Conversation

@inureyes

@inureyes inureyes commented Jun 4, 2026 •

Copy link
Copy Markdown
Member

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 KVCache and a real-model parity test that proves those primitives actually work end-to-end through a real model's forward. 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 per KVCache, so model.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.rs

  • New optional KVCache::paged_backing: Option<PagedBacking>, defaulted to None in 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 the pool/state handles (cheap Rc clones); layer_idx selects this cache's slice of the per-sequence state. RefCell provides the &mut access update_and_fetch needs 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.
  • Single intercept at the top of update_and_fetch — the only cache method qwen3 calls for plain Fp16 prefill (l > 1) and decode (l == 1). When pool-backed it appends via write_prefill (works for bulk prefill and a single decode token), bumps self.offset += n_new exactly as the dense update_fp16 does, and returns gather_visible(...). The dense self.update(...) is skipped on this path so there is no double-write/allocate. K/V dtype is preserved (no astype).

tests/paged_real_model_parity.rs (new)

  • #[ignore] integration test that soft-skips when models/qwen3-0.6b-4bit is absent. Runs the identical prefill + 16-step greedy decode loop against (a) a dense model.make_caches() and (b) a Vec<KVCache> of new_paged(...) sharing one PagedBlockPool, 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 pointers

KVCache is not required to be Send/Sync anywhere in the tree: there is no unsafe impl Send for KVCache, no assert_send_sync::<KVCache>(), and the only place a Vec<KVCache> lives in an async context (the pipeline stage service's caches_by_request) is built and driven entirely inside one OS thread via block_on on a new_current_thread runtime — it never crosses a tokio::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,accelerate

  • cargo clippy --lib -p mlxcel-core --features metal,accelerate -- -D warnings (warm and cold via cargo clean -p mlxcel-core)

  • cargo check --tests -p mlxcel-core --features metal,accelerate

  • cargo clippy -p mlxcel-core --tests --features metal,accelerate -- -D warnings

  • cargo check --test paged_real_model_parity --features metal,accelerate

  • cargo clippy --test paged_real_model_parity --features metal,accelerate -- -D warnings

  • cargo fmt --check

  • Real-model parity (GPU; not run here — requires models/qwen3-0.6b-4bit):

    cargo test --test paged_real_model_parity --release --features metal,accelerate -- --ignored --nocapture
    

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
@inureyes inureyes added type:enhancement New features, capabilities, or significant additions area:architecture Architecture and code structure changes priority:medium Medium priority labels Jun 4, 2026
@inureyes
inureyes merged commit b6375dd into main Jun 5, 2026
4 checks passed
@inureyes
inureyes deleted the feat/121-pool-backed-kvcache-verify branch June 5, 2026 13:49
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.
@inureyes inureyes added this to the 0.2 milestone Jun 21, 2026
@inureyes inureyes self-assigned this Aug 31, 2026
@inureyes inureyes added the status:done Completed label Sep 6, 2026
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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:architecture Architecture and code structure changes priority:medium Medium priority status:done Completed type:enhancement New features, capabilities, or significant additions

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant