Skip to content

feat(kvflash): pager slices, step fences, deferred free and the KVFLASH2 blob - #932

Merged
davide221 merged 2 commits into
Luce-Org:mainfrom
dusterbloom:kvflash/pager-slices
Nov 6, 2026
Merged

davide221 merged 2 commits into
Luce-Org:mainfrom
dusterbloom:kvflash/pager-slices

Conversation

@dusterbloom

@dusterbloom dusterbloom commented Nov 3, 2026 •

Copy link
Copy Markdown
Collaborator

Why

KvFlashPager on main (server/src/common/kvflash_pager.h) is a pager for one pool that starts at row 0 of the KV allocation and frees a block the moment it is paged out. Work that needs more than that has nothing to build on:

  • A pool cannot be a slice of a larger KV allocation. block_of, slot_of, fill_slot_pos and fill_slot_mask all assume the pool begins at row 0, so two pools cannot share one allocation.
  • A page-out frees its block at once (page_out on main pushes to free_blocks_ directly). A caller that queues page-outs a step ahead and fences once per step has no way to hold the block until the copy has landed.
  • There is no pin that lasts one step, and no check that a page-out planned for a request is still valid when it runs.
  • page_out(c) on main does not check is_pinned(c); only eviction skips pinned chunks (main kvflash_pager.h:415-416).
  • reselect() sorts by score alone (main :566, a.s > b.s), so on an exact tie across the resident/host boundary the order is whatever std::sort leaves. A tie can cause a recall and an eviction for the same bytes.
  • The pooled blob is written only as KVFLASH3, as one flat buffer. A writer that keeps chunks apart cannot produce it without assembling a second full copy.

This PR adds the interface for those and nothing that only a later feature uses. With KVFlash off, no code path here runs. With KVFlash on and the serial path, the decisions are the same except for the three differences listed under Limits.

What it does

Line numbers are in server/src/common/kvflash_pager.h at 2599780 unless a file is named.

  • Slices. KvFlashConfig::row_base (:103) makes the pool a slice of a larger KV allocation. Rows and block ids the backend sees are arena space: block_of (:685), slot_of (:703), fill_slot_pos (:711), fill_slot_mask (:758), arena_tokens() (:695). The serial pagers stay at base 0, where these return what they returned before. attach checks the slice against the tensors (:132-146) before it touches any state.
  • Step pins and generation. pin_step_range / end_step (:459-461) sit beside the existing pin_range (:422). generation() (:558) with page_out_checked (:555) makes a page-out planned against a request that has since ended do nothing. abort_step (:563).
  • Deferred free (:635-638). set_deferred_free, last_record, pending_free_blocks and complete. With it on, a paged-out block goes to a pending list (:543) and becomes allocatable only after complete(record) for the record that freed it. It is off by default; the serial path keeps one fence per reused block.
  • Stream hooks. set_external_page_stream (:581), page_stream (:573), set_batch_submit (:572).
  • Selection. lru_victims(n) (:816). reselect(tail_override) (:775): a tail override of N protects only the last N chunks for that call, and a score tie keeps the resident chunk (:790). A truncate to a prefix that fits the pool calls relayout_identity_ (:284, :297) so the block map is the one a fresh pager would have; pool attention reduces over physical slots in order, so the layout is part of the result.
  • fill_slot_mask(dst, valid_upto) (:758): rows at logical positions at or above the bound are masked off. The default, INT64_MAX, keeps every resident row visible, so existing callers are unchanged. A decode step at position p would pass p + 1.
  • page_out refuses a pinned chunk (:530).
  • kvflash_require_base_zero (:1633) prints a message and calls std::abort() when a pager has a nonzero row_base. It guards the two serial-only consumers in server/src/qwen35/qwen35_backend.cpp (identity prefill sync :2884, single-mask upload :2965). server/src/common/layer_split_kvflash.h:31 makes the identity sync return false on a slice, and the shard daemon's identity-sync condition (server/src/qwen35/qwen35_target_shard_ipc_daemon.cpp:585) adds row_base() == 0. No path in this PR creates a slice, so none of these fire here. The slot-position buffer in server/src/qwen35/layer_split_forward.cpp:77 is now arena_tokens() long, which equals the pool size at base 0.
  • server/src/common/fnv.h holds the FNV-1a step used by the pager's ledger hash in its log line (:846), replacing the inline constant main has at :596.

KVFLASH2 and KVFLASH3

serialize() (:893) keeps writing KVFLASH3, the pooled snapshot with the pool layout, byte for byte. snapshot_save_pooled_at and kvflash_restore_pooled are not changed. KVFLASH2 is the same blob without the pool layout, produced in parts by serialize_to (:946), blob_header (:961), read_chunk (:972) and ledger_blob (:996), for a writer that keeps chunks apart. deserialize (:1025) reads both by magic: KVFLASH3 restores the exact layout, KVFLASH2 restores residency in identity block order. The expected chunk count, when given, is checked against the header before any state moves.

A test holds a KVFLASH3 blob captured from main's serializer (at 89fddc3, the geometry and seed are in the test). It loads, serializes back byte for byte, and equals what this pager writes for the same state (test_kvflash_pager_serde.cpp:1120, kvflash3_blob_written_by_main_loads_and_reserializes_byte_for_byte).

Left out of this PR

  • LUCE_KVFLASH_HOST_BACKING (kvflash_host_backing.h, its tests, set_host_backing). It has no caller until a later PR, so it ships with that caller. Here the pager keeps main's set_pinned_host_backing(bool) (:205) and the single cudaMallocHost path.
  • Strided copies (one cudaMemcpy2DAsync / cudaMemset2DAsync per layer and K|V instead of one call per head). This is a performance change with no test need and no benchmark yet, so it is not here: the per-head cudaMemcpyAsync / cudaMemsetAsync loops are main's, and gpu_runtime_compat.h is untouched.

Callers that arrive in follow-ups

Used by a follow-up: row_base and the arena-space accessors, step pins, deferred free and complete, set_external_page_stream, set_batch_submit, page_out_checked, lru_victims, the reselect tail override, fill_slot_mask's valid_upto, and the KVFLASH2 parts. Nothing in src calls set_external_page_stream or set_batch_submit after this PR, and the unit tests do not exercise them.

The slice, fence, deferred-free and blob pieces are in one commit because they share the pager header and its tests.

Tests

test_server_unit, filtered to the two fixtures this PR changes: KvflashPagerSerde goes from 19 to 47 cases, KvflashPagerCudaRace from 3 to 5 (CUDA only). The new cases cover: the KVFLASH3 blob from main, KVFLASH2 parts and the streamed blob, the expected-chunk-count check, pinned page_out, step pins, deferred free, stale generation, row_base rows, attach refusal and bytes at the offset rows, the reselect tail override and ties, reselect() parity with main for the gemma4/laguna call shape, the truncate layout contract and identity relayout (bytes move, a swap cycle resolves), the bounded slot mask, and a byte-exact page-out/page-in round trip with a partial-chunk truncate on the CUDA side.

Full test_server_unit, passed / failed / skipped, main c5179e4 vs this branch. The difference is 30 on CUDA: 28 new KvflashPagerSerde cases and 2 new KvflashPagerCudaRace cases. It is 28 on HIP, where the CUDA-only race cases do not run.

build main c5179e4 branch 2599780
CUDA, RTX 3090 (sm86, Release) 1224 / 0 / 6 1254 / 0 / 6
HIP gfx1201 (hip:0) 1207 / 0 / 4 1235 / 0 / 4
HIP gfx1151 (hip:1) 1207 / 0 / 4 1235 / 0 / 4

The GPU was idle before each run and one suite ran at a time. Each HIP log names its device (arch=gfx1201 on hip:0, arch=gfx1151 on hip:1).

Engine run

Qwen3.8-27B (Qwen3.8-27B-UD-IQ4_XS.gguf, md5 54db94b16b77e3fe024faa893cc4b80d), serial --kvflash 16384, two distinct prompts of 34583 and 37293 tokens, 128 max tokens, temperature 0, seed 1. The pool pages out on every arm, main and branch (pooled prefill: 34583 tokens through a 16384-token pool, and the same for 37293). Run on HIP only (gfx1201 and gfx1151); there is no CUDA engine run for this PR.

Setup: luce_server <model> --max-ctx 65536 --kvflash 16384 --no-kv-cache --cache-type-k q8_0 --cache-type-v q8_0, one server at a time, caches dropped before each arm, prompts sent one after the other. luce_server md5: main e01ec7db3b155947fc93c00f2acb4a07, branch 1b88cf5be5310ff36189e626291259fc. Arms run in the order main, branch, main repeat on each GPU. All requests show prefix_len=0 and disk_hit=false on all six arms, so no arm used a prefix or disk cache.

The prompts were answered in 61 and 61 tokens on gfx1201 and in 61 and 63 on gfx1151 (finish=stop), the same counts on every arm of a GPU. With two requests, median equals mean, and best and min are the two requests.

Speeds are from the server's chat DONE lines, tokens per second; wall in seconds (best = fastest). The log prints prefill time in steps of 0.1 s, so two runs with the same prefill time show the same prefill tok/s.

gfx1201 (hip:0):

arm prefill tok/s med / mean / best / min decode tok/s med / mean / best / min wall s med / mean / best / min text vs main
main 852.32 / 852.32 / 867.28 / 837.36 29.15 / 29.15 / 29.20 / 29.10 44.40 / 44.40 / 43.57 / 45.23 -
branch 852.32 / 852.32 / 867.28 / 837.36 29.15 / 29.15 / 29.20 / 29.10 44.41 / 44.41 / 43.58 / 45.24 identical, both requests
main repeat 851.31 / 851.31 / 867.28 / 835.34 29.15 / 29.15 / 29.20 / 29.10 44.42 / 44.42 / 43.61 / 45.23 identical, both requests

gfx1151 (hip:1):

arm prefill tok/s med / mean / best / min decode tok/s med / mean / best / min wall s med / mean / best / min text vs main
main 293.71 / 293.71 / 295.83 / 291.58 12.90 / 12.90 / 12.90 / 12.90 127.30 / 127.30 / 121.70 / 132.91 -
branch 290.66 / 290.66 / 291.10 / 290.22 12.90 / 12.90 / 12.90 / 12.90 128.56 / 128.56 / 123.63 / 133.50 identical, both requests
main repeat 291.13 / 291.13 / 291.59 / 290.67 12.90 / 12.90 / 12.90 / 12.90 128.34 / 128.34 / 123.41 / 133.27 identical, both requests

Branch vs the first main run, medians: on gfx1201 prefill 0.0%, decode 0.0%, wall +0.02%; main against its own repeat is -0.12%, 0.0% and +0.05%. On gfx1151 prefill -1.04%, decode 0.0%, wall +0.99%; main against its own repeat is -0.88%, 0.0% and +0.82%. On gfx1151 the first main run was the first after a server start and both later arms sit below it; against the main repeat the branch is -0.16% on prefill. This PR makes no speed claim and shows no speedup.

The tables above are for 1c0cbcd. The review fix 2599780 was run again with the same harness, main (same binary) then branch on each GPU, with no main repeat. Branch luce_server md5 562a325f83bbf8d310ae34d146af6546. Text is identical to main on both requests on both GPUs, and identical to the 1c0cbcd arms. prefix_len=0 and disk_hit=false on all four arms, and every arm logs pooled prefill for both prompts. Branch vs main, medians: gfx1201 prefill 858.44 vs 865.69 tok/s (-0.84%), decode 29.20 vs 29.30 (-0.34%), wall 44.07 vs 43.76 s (+0.71%); gfx1151 prefill 291.51 vs 292.72 (-0.41%), decode 12.90 vs 12.90 (0.0%), wall 128.24 vs 127.74 s (+0.39%). The same main binary gave 865.69 tok/s prefill on gfx1201 in this run and 852.32 in the run above.

The server has no logprobs, so near-tie margins between the two builds' token choices cannot be computed; text identity is the comparison.

Limits

  • Decode speed rests on 61 to 63 generated tokens, two requests per arm. It is a small sample; the decode numbers above are not a decode benchmark.
  • The engine run covers the serial --kvflash path on the two HIP devices. No CUDA engine run, and no run with a sliced pager (nothing in this PR creates one).
  • Three behaviour differences on the serial path when KVFlash is on:
    • page_out on a pinned chunk is refused.
    • A truncate to a prefix that fits the pool relays out to identity block order. The serial backends reset and rebuild on restore, so they did not see the old layout.
    • On an exact score tie across the resident/host boundary, reselect keeps the resident chunk, where main's comparator left the order unspecified. The test reselect_score_ties_keep_resident_chunks_where_main_recalled_by_chunk_id records main's result for its case, a recall by chunk id.
  • gemma4 and laguna call reselect() with no arguments and never pin a step. reselect_without_pins_matches_main_for_gemma4_and_laguna replays that call shape and compares events, residency and block order with what main's pager produced at 89fddc3. There is no gemma4 or laguna engine run.
  • kvflash_require_base_zero aborts the process on a sliced pager. It is unreachable in this PR.
  • set_external_page_stream and set_batch_submit have no caller and no test here.
  • The strided-copy change and LUCE_KVFLASH_HOST_BACKING are not in this PR (see above).

…SH2 blob

KvFlashPager gains the interface the arena, scorer and recall work builds
on, and nothing that only they use:

- KvFlashConfig::row_base: the pool can be a slice of a larger KV
  allocation. Rows and block ids the backend sees are arena space
  (block_of, slot_of, fill_slot_pos, fill_slot_mask, arena_tokens); the
  serial pagers stay at base 0, where nothing changes. attach validates
  the slice against the tensors before it touches any state.
- Step pins beside the hard pins (pin_step_range / end_step), generation()
  with page_out_checked so a page-out planned against a request that has
  since ended does nothing, and abort_step.
- Deferred free: set_deferred_free, last_record, pending_free_blocks,
  complete. A paged-out block becomes allocatable only after the record
  that freed it completes. Off by default; the serial path keeps one fence
  per reused block.
- set_external_page_stream / page_stream / set_batch_submit, lru_victims,
  reselect(tail_override) with ties keeping resident chunks, and an
  identity relayout when a truncate lands on a prefix that fits the pool.
- fill_slot_mask(dst, valid_upto): rows at logical positions at or above the
  bound are masked off; the default keeps every resident row visible.
- page_out refuses a pinned chunk, the way eviction already skipped it.

serialize() keeps writing KVFLASH3, the pooled snapshot with the pool
layout, byte for byte; snapshot_save_pooled_at and kvflash_restore_pooled
do not change. KVFLASH2 is the same blob without the pool layout, produced
in parts by serialize_to, blob_header, read_chunk and ledger_blob for a
writer that keeps chunks apart. deserialize reads both by magic: KVFLASH3
restores the exact layout, KVFLASH2 restores residency in identity order,
and the expected chunk count is checked before any state moves.

kvflash_require_base_zero guards the two serial-only consumers in
qwen35_backend.cpp (identity prefill sync, the single-mask upload), and the
identity sync in layer_split_kvflash.h and the shard daemon refuses a slice.
The mask and position buffers are arena-sized, which equals pool-sized at
base 0.

Tests: KvflashPagerSerde grows from 19 to 45 cases (a KVFLASH3 blob captured from main loads and reserializes byte for byte, KVFLASH2 parts, pins, deferred free, generation, row_base slices, and reselect() parity with main for the gemma4/laguna call shape, ties documented, the bounded slot mask), KvflashPagerCudaRace from 3 to 5.

@cubic-dev-ai cubic-dev-ai Bot 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.

1 issue found across 8 files

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="server/src/common/fnv.h">

<violation number="1" location="server/src/common/fnv.h:9">
P2: `kFnvBasis` is not the FNV-1a 64 offset basis: the literal is missing its last digit. Use `14695981039346656037ULL` (or `0xcbf29ce484222325ULL`). Otherwise kvflash ledger and blob hashes will not match FNV-1a values computed by the cluster `fnv1a64` or the HTTP fingerprints.</violation>
</file>

Reply with feedback, questions, or to request a fix.

View guided diff | Re-trigger cubic

Comment thread server/src/common/fnv.h

namespace luce::common {

constexpr uint64_t kFnvBasis = 1469598103934665603ULL;

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.

P2: kFnvBasis is not the FNV-1a 64 offset basis: the literal is missing its last digit. Use 14695981039346656037ULL (or 0xcbf29ce484222325ULL). Otherwise kvflash ledger and blob hashes will not match FNV-1a values computed by the cluster fnv1a64 or the HTTP fingerprints.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At server/src/common/fnv.h, line 9:

<comment>`kFnvBasis` is not the FNV-1a 64 offset basis: the literal is missing its last digit. Use `14695981039346656037ULL` (or `0xcbf29ce484222325ULL`). Otherwise kvflash ledger and blob hashes will not match FNV-1a values computed by the cluster `fnv1a64` or the HTTP fingerprints.</comment>

<file context>
@@ -0,0 +1,19 @@
+
+namespace luce::common {
+
+constexpr uint64_t kFnvBasis = 1469598103934665603ULL;
+constexpr uint64_t kFnvPrime = 1099511628211ULL;
+
</file context>
Suggested change
constexpr uint64_t kFnvBasis = 1469598103934665603ULL;
constexpr uint64_t kFnvBasis = 14695981039346656037ULL;

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Kept as is. 1469598103934665603ULL is the constant main already uses in six places, including the inline copy at kvflash_pager.h:596 that fnv.h replaces. Here it feeds only the pager's ledger hash in a log line. It is never compared with the cluster fnv1a64 (cluster_protocol.h uses 0xcbf29ce484222325) or with HTTP fingerprints. Changing it here would change the hash main logs, so this PR keeps it for parity. Correcting all six copies is a separate change.

Comment thread server/src/common/kvflash_pager.h Resolved
Comment thread server/src/common/kvflash_pager.h Resolved

@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

Found 1 issue.

Copy to agent

Use the copy button in the top-right corner of the block, then paste into your agent.

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.

Repository: Luce-Org/lucebox
Reviewed commit: 1c0cbcdee24f747fc468098eaef675cea6ece9c3
Verify the findings against the current code, run relevant checks for any fixes, and explain any findings you reject.

<file name="server/src/common/kvflash_pager.h">

<violation number="1" line="898" end_line="938">
serialize() omits deferred-free blocks from the pool layout, so the pager's own KVFLASH3 blob is rejected by deserialize

With `deferred_free_` on, a paged-out chunk's block is in `pending_free_`, i.e. neither `free_blocks_` nor any `chunks_[c].block`. `serialize()` builds `free_list` only from `free_blocks_` (line 898) plus dropped-tail blocks, so the blob's free-list count satisfies `n_resident + n_free = n_blocks_ - pending_free_.size()`. On load into a pool of the saved size, `deserialize()` takes the `exact` path and rejects the blob at `if (n_resident + n_free != (size_t)n_blocks_) return false;` (line 1068). So a pager with any pending deferred free cannot restore its own snapshot — the documented contract "the pager is exactly the one that was saved" silently fails (and `snapshot_save_pooled_at` consumers would lose the state instead of persisting it). `serialize_to()` inherits the same gap. Fix: include the `pending_free_` blocks in `free_list` (they are free, only not yet allocatable), e.g. append them after the live free list, matching what `complete()` would produce.
</violation>

</file>
Issue overview
  1. serialize() omits deferred-free blocks from the pool layout, so the pager's own KVFLASH3 blob is rejected by deserialize · likely (server/src/common/kvflash_pager.h:898-938)

    With deferred_free_ on, a paged-out chunk's block is in pending_free_, i.e. neither free_blocks_ nor any chunks_[c].block. serialize() builds free_list only from free_blocks_ (line 898) plus dropped-tail blocks, so the blob's free-list count satisfies n_resident + n_free = n_blocks_ - pending_free_.size(). On load into a pool of the saved size, deserialize() takes the exact path and rejects the blob at if (n_resident + n_free != (size_t)n_blocks_) return false; (line 1068). So a pager with any pending deferred free cannot restore its own snapshot — the documented contract "the pager is exactly the one that was saved" silently fails (and snapshot_save_pooled_at consumers would lose the state instead of persisting it). serialize_to() inherits the same gap. Fix: include the pending_free_ blocks in free_list (they are free, only not yet allocatable), e.g. append them after the live free list, matching what complete() would produce.

Reviewed 1c0cbcde · 3 candidate issues checked, kept at ≥70% confidence · add the code-review label to review again

…attach checks every layer's slice

serialize() left blocks waiting on their page-out record out of the free
list, so deserialize() rejected the pager's own blob on a same-size pool.
attach() validated the slice rows on the first K/V tensor only; it now
checks every layer before any state changes. The truncate race test now
asserts chunk 3 is dropped and its block returned.
@dusterbloom

Copy link
Copy Markdown
Collaborator Author

On the code-review-bot finding (serialize() leaving out deferred-free blocks, kvflash_pager.h 898-938 at 1c0cbcd), which is the same as cubic's deferred-free comment: fixed in 2599780. A block still waiting for its page-out record is now written as free in the KVFLASH3 layout, so the blob loads back. Test: kvflash3_blob_with_deferred_free_pending_loads_back, which fails on 1c0cbcd and passes on 2599780.

The same commit also makes attach() check every layer's tensors and adds the truncate assertions. test_server_unit on 2599780: CUDA 1254 / 0 / 6, HIP gfx1201 1235 / 0 / 4, HIP gfx1151 1235 / 0 / 4 (main c5179e4: 1224 / 0 / 6 and 1207 / 0 / 4). The engine run is in the description: text identical to main on both GPUs.

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