Repository navigation
feat(kvflash): pooled prefix snapshots and suffix-only restore (opt-in) - #849
Conversation
…score ledger Library additions to KvFlashPager, header and unit tests only; nothing in the backends calls them yet. - serialize(max_chunks) / deserialize(): a position-addressed blob of the first N chunks (resident rows, host copies, per-chunk score ledger), so a pager can be rebuilt later. A failed pinned-host allocation in deserialize frees the buffers already allocated. - truncate(P): drop every logical position >= P, as if the pager had only seen P tokens. The chunk containing P keeps its block with rows >= P zeroed; the pool is refilled from host copies like a fresh pager (recency, or score with a scorer) and the LRU clock is renumbered in logical order. - pin_range / unpin_all (reset clears pins), per-chunk score ledger accessors, floor_to_chunk, and memset of host-resident blocks.
…is unavailable The CPU-backend serde and truncate cases that page chunks out allocate their host backing with cudaMallocHost on GPU builds. On the CPU-only check-cpu runner the driver is a stub and that allocation fails, so 12 cases failed. Skip them there; the GPU runners still run them.
5422246 to
826bb49
Compare
davide221
left a comment
There was a problem hiding this comment.
Code review
No issues found. Checked for bugs and logic errors in the changed code.
Reviewed 826bb497 · 0 candidate issues checked, kept at ≥70% confidence · add the code-review label to review again
…ing the rest refill_after_truncate_ ranked host chunks by score alone, so with a scorer older high-score chunks could take every free block and leave the sink, tail window and pinned chunks non-resident, unlike a pager that only saw P tokens. Recall the protected chunks first, then rank the discretionary ones.
…VFLASH2 The header recorded only the K dtype, so a V cache switched from F16 to BF16 passed the byte-geometry checks and its values were reinterpreted. Record the V dtype as a ninth header field, validate it, and bump the magic to KVFLASH2 so blobs written by the previous layout are refused.
attach() reset the mappings but kept the pin vector, so pins set against a larger pool survived re-attaching to a smaller one and protected every chunk, starving allocation. Clear them with the other per-attach state.
A position at chunk index 2^31 narrowed to a negative int, skipped the resize and wrote pinned_ out of bounds (segfault in the unit test). Check the range in 64 bits first: refuse spans longer than the pool and chunk indices past 4M, which also bounds the range scan and the pin-flag allocation.
… as recallable zero KV deserialize marked every entry on_host, so a chunk that was never written (a hole left by a failed allocation or a position jump) became recallable zero KV that reselect could pick. Write a materialized byte in the ledger (same KVFLASH2 layout bump as the V dtype), restore holes as holes without a host copy, and refuse a blob that marks a never-materialized chunk resident.
…ents are caught The pattern repeated every 256 bytes but a segment is 512, so whole K/V/head/layer segments were interchangeable and swapping them went undetected (28 of 28 pair swaps passed the old check). Hash the byte offset within the chunk instead, in both the serde and truncate tests, and add a case that swaps every segment pair.
…geable host backing Fifteen CPU-backend cases skipped on the check-cpu runner because the pager's pinned host backing (cudaMallocHost) fails under the stub driver, so CI never ran them. Add KvFlashPager::set_pinned_host_backing(false) (pageable memory, each chunk remembers how its buffer was allocated) and a TestPager that picks it when pinned allocation is unavailable. None of these cases exercise DMA ordering (their tensors are host memory), so none stay GPU-gated.
The wire format was documented as little-endian but integers and floats are written in host byte order. Add a static_assert for little-endian hosts, fix the comment, and pin the byte layout with a test. No encoder is added.
With KVFlash on, a prefix snapshot used to be refused as soon as the live cache outgrew the resident pool, because dense snapshots copy KV rows assuming the identity layout that pooled prefill breaks. This saves such a snapshot as a pager blob and restores it without re-prefilling the prefix. - PrefixSnapshot carries the pager blob (is_pooled, kvflash_blob); the state snapshot skips the dense KV tensors (skip_kv). Pooled snapshots are taken at a chunk boundary of a pooled prefill and at the end of a prompt. - Restore, behind LUCE_KVFLASH_RESTORE_CONSUME=1 (default off, behavior then unchanged): the pager and QK pool are rebuilt from the blob and only the suffix prefills, with real token ids for the restored prefix. Without it, or when the cut is not chunk aligned, a pooled snapshot is dropped and the whole prompt prefills from 0 (kvflash_restore_plan, pure and unit tested). - A pooled snapshot is never handed to the SSD tier: an OwnedSnapshot cannot carry the pager blob, so a file written from it would restore with no KV (Luce-Org#839 hazard). disk_persistable() and SnapshotRef::pooled guard the save and the layout learning. - A dense prefill resets the pager, so a boundary snapshot never serializes the previous request's mapping. - LUCE_KVFLASH_DEBUG_RESIDENT logs the resident chunk ranges and a score-ledger hash after each prefill. - optimizations/kvflash/tests/pooled_restore_identity.sh checks restored and cold answers match at 20K/35K/64K. - Docs: ENVIRONMENT.md rows and a KVFlash session restore section in PREFIX_CACHE.md.
…ot to the disk writer The Qwen3.5 backend overrides snapshot_detach and already frees a pooled snapshot. The default implementation copies snapshot_ref() to host, which for a pooled snapshot would carry tensors without the KV held in the pager blob. Return an empty snapshot instead, and cover it with a unit test.
826bb49 to
17888b0
Compare
…er branch kvflash_pager.h reset(): keep Luce-Org#854's sync_page_stream_() (checked wait that clears page_work_queued_) and this branch's free_host_buffer_() helper. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…led snapshot branch Via the Luce-Org#848 branch merge. server/CMakeLists.txt keeps both new unit tests (test_kvflash_restore_plan.cpp and main's test_dflash_window.cpp). Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
deserialize() put resident chunks back in identity block order with a fresh LRU order. A cold prefill has the same chunks resident but in rotated blocks, so attention summed the same rows in a different order: rounding-level logit differences that flipped near-tie tokens. On the R9700 pooled_restore_identity.sh failed at 35K and 64K (turn 3 differs between CONSUME=0 and =1). KVFLASH3 adds a pool layout section: block and LRU rank per chunk, the use clock and the free-list order. Into a pool of the saved size every chunk gets its own block back and evictions pick the same victims; another pool size keeps the KVFLASH2 behavior (residency only, identity order). LRU stamps are saved as dense ranks, which evict exactly like the raw clock, so pagers that behave alike serialize alike. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…led grid branch Via the Luce-Org#849 branch merge; no new conflicts. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…estore) into kvflash pooled grid branch Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Pushed 04299a8 on top of your head (plus a merge of main for #886). On the R9700 (lucebox2) Fix: the blob (now lucebox2, main + #848-#851 with the fix:
|
Main now equals the tested Luce-Org#849 tree, so this keeps the tested Luce-Org#850 tree unchanged (a plain 3-way merge would duplicate the Luce-Org#849 hunks). Co-Authored-By: Claude Opus 5.5 <[email protected]>
…rg#850, Luce-Org#876, Luce-Org#863) into kvflash turn checkpoints branch Clean 3-way merge against the tested Luce-Org#851 head: Luce-Org#852 changes and the main-side changes are both kept exactly. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Stacked on #848. This PR's own commits are 5520478 and 17888b0.
Why
With KVFlash on, a prefix snapshot was refused as soon as the live cache outgrew the resident pool. Dense snapshots copy KV rows assuming an identity layout, and pooled prefill breaks that layout. So a long KVFlash session could not be snapshotted at all.
What it does
PrefixSnapshotcarries the pager blob from feat(kvflash): pager serialize/deserialize, truncate, chunk pins and score ledger #848 (is_pooled,kvflash_blob). The state snapshot skips the dense KV tensors (skip_kv). Pooled snapshots are taken at a chunk boundary during a pooled prefill and at the end of a prompt.LUCE_KVFLASH_RESTORE_CONSUME=1(default off).kvflash_restore_plandecides this. It is a pure function with unit tests.OwnedSnapshotcannot carry the pager blob, so a file written from a pooled snapshot would restore with no KV.disk_persistable()andSnapshotRef::pooledguard the save and the layout learning.ModelBackend::snapshot_detachreturns an empty snapshot for a pooled ref (5422246). The Qwen3.5 backend's override already freed it.LUCE_KVFLASH_DEBUG_RESIDENT=1logs the resident chunk ranges and a score-ledger hash after each prefill.ENVIRONMENT.mdrows, and a "KVFlash session restore" section inPREFIX_CACHE.md.With KVFlash off, nothing changes. On the 3090 (Qwen3.8-27B UD-Q4_K_M,
--max-ctx 131072, temperature 0,--no-kv-cache), main 6f2b179 and the top of this stack (09bde623) ran the same 10-turn chat without--kvflash:prefix_lenidentical turn for turn on all four runs (0, then 11600 to 14199), anddisk_hit=falseon every request.Tests
test_kvflash_restore_plan.cpp,test_pooled_snapshot_blob.cpp, andtest_default_snapshot_detach_refuses_pooled_snapshotsintest_server_unit.cpp.test_server_unit(CUDA build): 1047 passed, 0 failed, 7 skipped.optimizations/kvflash/tests/pooled_restore_identity.shchecks that restored and cold answers match at 20K, 35K and 64K tokens.Limits
LUCE_KVFLASH_POLICY=qk, a pooled restore rebuilds the pooled-key store only for chunks that are resident in the snapshot, then moves the pooling watermark past every sealed chunk. Chunks that were evicted get no pooled key: they score −2, below the cosine range, and are not pooled later, so the qk reselect cannot pick them in that session. The default policies (drafter, LRU) do not read the pooled-key store. The fix pools those chunks from the pager's host copy at restore. It comes as its own PR, because it changes which chunks qk recalls after a restore.Rebased on 2026-10-23 onto #848 at e35391f (its review fixes). The diff against the previous head is exactly those fixes; this PR's own changes are unchanged. The test counts above were measured before the rebase.