Skip to content

feat(kvflash): pooled prefill on an absolute 512-token grid - #850

Merged
davide221 merged 20 commits into
Luce-Org:mainfrom
dusterbloom:kvflash/2.0a-C-prefill-grid
Oct 25, 2026
Merged

davide221 merged 20 commits into
Luce-Org:mainfrom
dusterbloom:kvflash/2.0a-C-prefill-grid

Conversation

@dusterbloom

@dusterbloom dusterbloom commented Oct 15, 2026 •

Copy link
Copy Markdown
Collaborator

Stacked on #849 (which is on #848). This PR's own commit is the last one (ccbe206).

Why

Pooled prefill used min(ubatch, remaining) batches, counted from wherever the request started. So where a batch ended depended on the session's earlier history. A restored run could cut its batches differently from a cold run of the same prompt, and the two could then disagree on the output.

What it does

  • With KVFlash on, pooled prefill batches now end on multiples of 512, which is a multiple of the 64-token pager chunk. Only two batches are short: the first one after an off-grid resume, and the remainder at the end of the prompt.
  • kvflash_prefill_batch_end and kvflash_prefill_batches in qwen35/prefill_helpers.h are pure functions with unit tests. The remainder never produces NaN.
  • The non-pooled prefill path is unchanged. With KVFlash off, nothing changes.
  • The grid is always on for pooled prefill. It is not behind the session switch that D adds (LUCE_KVFLASH_SESSION). It is documented in server/docs/PREFIX_CACHE.md.

Tests

  • New cases in test_kvflash_restore_plan.cpp.
  • test_server_unit (CUDA build): 1052 passed, 0 failed, 7 skipped.
  • On the GPU, scenario 2 of the Gate A scripts (in D) checks a restore at a 512-token boundary. It passes on the 3090 at the top of the stack (09bde623).

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 0fe12d90 · 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.
Pooled prefill used min(ubatch, remaining) batches counted from wherever the
request started, so where a batch ended depended on the earlier history of the
session and a restored run could cut differently from a cold one.

Batches now end on multiples of 512 (a multiple of the 64-token pager chunk):
only the first batch after an off-grid resume and the end-of-prompt remainder
are short. kvflash_prefill_batch_end / kvflash_prefill_batches are pure and unit
tested; the non-pooled prefill path is unchanged. Documented in PREFIX_CACHE.md.
@dusterbloom
dusterbloom force-pushed the kvflash/2.0a-C-prefill-grid branch from 0fe12d9 to ccbe206 Compare October 23, 2026 16:41
davide221 and others added 6 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]>
…led grid branch

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

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]>
…estore) into kvflash pooled grid branch

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
…sion restore branch

Via the Luce-Org#850 branch merge. server/CMakeLists.txt keeps this branch's live
restore and resume tests plus main's test_dflash_window.cpp.

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 session restore branch

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

Copy link
Copy Markdown
Contributor

Merged the updated base (main #886 + the #849 restore-layout fix, see #849) into this branch; your commits are unchanged. The stack (main + #848-#851) passes on lucebox2: restore identity at 20K/35K/64K, gate 10/10 identical, scenarios 1-3, unit 1125/0.

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
davide221 merged commit 4a18fb0 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
…lash DeltaNet ladder branch

Clean 3-way merge against the tested Luce-Org#850 head: Luce-Org#851 changes and the
main-side changes (Luce-Org#876 sampler seeding, Luce-Org#863 PFlash cleanup) are both
kept exactly.

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