Skip to content

feat(kvflash): pooled prefix snapshots and suffix-only restore (opt-in) - #849

Merged
davide221 merged 16 commits into
Luce-Org:mainfrom
dusterbloom:kvflash/2.0a-B-pooled-snapshots
Oct 25, 2026
Merged

davide221 merged 16 commits into
Luce-Org:mainfrom
dusterbloom:kvflash/2.0a-B-pooled-snapshots

Conversation

@dusterbloom

@dusterbloom dusterbloom commented Oct 15, 2026 •

Copy link
Copy Markdown
Collaborator

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

  • Pooled snapshots. PrefixSnapshot carries 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.
  • Suffix-only restore, opt-in with LUCE_KVFLASH_RESTORE_CONSUME=1 (default off).
    • With it, the pager and the QK pool are rebuilt from the blob, and only the suffix is prefilled. The restored prefix keeps its real token ids.
    • Without it, or when the cut is not chunk aligned, the pooled snapshot is dropped and the whole prompt prefills from 0, exactly as before.
    • kvflash_restore_plan decides this. It is a pure function with unit tests.
  • Never written to the SSD tier. An OwnedSnapshot cannot carry the pager blob, so a file written from a pooled snapshot would restore with no KV.
    • disk_persistable() and SnapshotRef::pooled guard the save and the layout learning.
    • The default ModelBackend::snapshot_detach returns an empty snapshot for a pooled ref (5422246). The Qwen3.5 backend's override already freed it.
    • Writing compacted and pooled state to disk is planned work, not this PR.
  • No stale mapping. A dense prefill resets the pager, so a boundary snapshot never serializes the previous request's mapping.
  • Debug log. LUCE_KVFLASH_DEBUG_RESIDENT=1 logs the resident chunk ranges and a score-ledger hash after each prefill.
  • Docs. ENVIRONMENT.md rows, and a "KVFlash session restore" section in PREFIX_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:

  • Two runs per arm, in the order main, stack, main, stack. Answers byte-identical on 10/10 turns in both pairs.
  • prefix_len identical turn for turn on all four runs (0, then 11600 to 14199), and disk_hit=false on every request.
  • Medians over 10 turns, main vs stack: run 1 prefill 722 vs 685 tok/s, decode 43.70 vs 43.40 tok/s, wall 1.30 vs 1.30 s; run 2 prefill 722 vs 722 tok/s, decode 43.75 vs 43.75 tok/s, wall 1.30 vs 1.25 s. Pooled over both runs (20 turns): prefill 722 vs 720 tok/s, decode 43.75 vs 43.45 tok/s, wall 1.30 vs 1.30 s.
  • The server log times prefill to 0.1 s, so prefill tok/s on these short prefills is coarse. The gaps are within the spread between the two runs of the same arm, so this is no speed claim either way.

Tests

  • test_kvflash_restore_plan.cpp, test_pooled_snapshot_blob.cpp, and test_default_snapshot_detach_refuses_pooled_snapshots in test_server_unit.cpp.
  • test_server_unit (CUDA build): 1047 passed, 0 failed, 7 skipped.
  • optimizations/kvflash/tests/pooled_restore_identity.sh checks that restored and cold answers match at 20K, 35K and 64K tokens.
  • On the GPU, scenario 1 of the Gate A scripts (in D) restores a pooled snapshot past the pool. It passes on the 3090 at the top of the stack (09bde623).

Limits

  • With 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.

View guided diff

…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.

@davide221 davide221 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.
@dusterbloom
dusterbloom force-pushed the kvflash/2.0a-B-pooled-snapshots branch from 826bb49 to 17888b0 Compare October 23, 2026 16:41
davide221 and others added 4 commits October 24, 2026 02:07
…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]>
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]>
davide221 added a commit to dusterbloom/lucebox-hub that referenced this pull request Oct 24, 2026
…led grid branch

Via the Luce-Org#849 branch merge; no new conflicts.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
davide221 added a commit to dusterbloom/lucebox-hub that referenced this pull request Oct 24, 2026
…estore) into kvflash pooled grid branch

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@davide221

Copy link
Copy Markdown
Contributor

Pushed 04299a8 on top of your head (plus a merge of main for #886).

On the R9700 (lucebox2) pooled_restore_identity.sh failed at 35K and 64K: turn 3 differed between CONSUME=0 and CONSUME=1. Cause: deserialize() put the chunks back in blocks 0..n with a fresh LRU, while a cold prefill leaves them in rotated blocks. Attention then adds the rows in a different order and near-tie tokens flip.

Fix: the blob (now KVFLASH3) also stores each chunk's block, its LRU rank and the free-list order. A restore into a pool of the same size puts the exact layout back; a different pool size falls back to the old order. Two new serde tests cover both cases.

lucebox2, main + #848-#851 with the fix:

  • identity: PASS at 20K, 35K, 64K
  • gate (pool 8192, plain): 10/10 identical, turn wall 13.4 s -> 1.95 s
  • scenarios 1-3: PASS
  • unit: 1125 passed, 0 failed

@davide221
davide221 merged commit f4d09c3 into Luce-Org:main Oct 25, 2026
7 of 8 checks passed
davide221 added a commit to dusterbloom/lucebox-hub that referenced this pull request Oct 25, 2026
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]>
davide221 added a commit to dusterbloom/lucebox-hub that referenced this pull request Oct 25, 2026
…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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants