Repository navigation
feat(kvflash): DeltaNet state ladder and live restore of the running session - #851
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.
CI failed on
|
…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.
60d98ef to
b03fd7a
Compare
davide221
left a comment
There was a problem hiding this comment.
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: b03fd7acb71c51c9d523c04f5199e6854af8f0e3
Verify the findings against the current code, run relevant checks for any fixes, and explain any findings you reject.
<file name="optimizations/kvflash/tests/gate/scripts/gate4_live.py">
<violation number="1" line="43" end_line="46">
Mode C negative test is dead code: the documented message edit is guarded by `if False`
The module docstring (line 4) advertises mode `C` as a negative control: "B setup, turns 1-5 as A, turn 6 with a middle message edited". The code that performs that edit is inside `if False:` (line 43), so it never runs: mode C replays arm A's prompts verbatim, exactly like mode B, and will always report byte-identical answers. Anyone running `gate4_live.py C` as the documented negative control gets a run that cannot detect a restore that wrongly ignores a mid-history edit — it passes vacuously. The disabled block also contradicts the docstring on which message it edits (turn 3's user message vs the docstring's turn 6). Remove the `if False:` guard (and reconcile the edit target with the docstring) or drop mode C and its docstring line.
</violation>
</file>
Issue overview
- Mode C negative test is dead code: the documented message edit is guarded by
if False· likely (optimizations/kvflash/tests/gate/scripts/gate4_live.py:43-46)
Reviewed b03fd7ac · 4 candidate issues checked, kept at ≥70% confidence · add the code-review label to review again
| if False: # q38spec: C = live arm without drafter, replays A verbatim | ||
| # edit the user message of turn 3 (a middle message); keep everything else | ||
| idx = [i for i, m in enumerate(msgs) if m["role"] == "user"][2] | ||
| msgs[idx]["content"] = msgs[idx]["content"].replace("Update 3.0", "Update 3.0 (EDITED)", 1) |
There was a problem hiding this comment.
Mode C negative test is dead code: the documented message edit is guarded by if False · likely
The module docstring (line 4) advertises mode C as a negative control: "B setup, turns 1-5 as A, turn 6 with a middle message edited". The code that performs that edit is inside if False: (line 43), so it never runs: mode C replays arm A's prompts verbatim, exactly like mode B, and will always report byte-identical answers. Anyone running gate4_live.py C as the documented negative control gets a run that cannot detect a restore that wrongly ignores a mid-history edit — it passes vacuously. The disabled block also contradicts the docstring on which message it edits (turn 3's user message vs the docstring's turn 6). Remove the if False: guard (and reconcile the edit target with the docstring) or drop mode C and its docstring line.
Checked (85%): At gate4_live.py:43 the edit block is inside if False:, so mode C never edits any message and replays arm A verbatim, exactly like mode B; the docstring at line 4 still documents C as a negative control with a mid-history edit (and even disagrees with the dead block on which turn is edited). Only caveat: the inline comment suggests the author intentionally repurposed mode C, so this may be a stale docstring/dead code rather than a functional regression, but the documented negative control is indeed vacuous.
There was a problem hiding this comment.
Fixed in d5e4a35f. Mode C was a leftover: run_gate.sh only runs A and B and nothing checks a C result, so re-enabling the edit would only add an unchecked run. Mode C is gone from the docstring and the code, and any mode other than A or B now exits with the usage. The same commit is in #852 as 342f22d.
…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.
…session A KVFlash conversation keeps its KV rows in the resident pool, but the DeltaNet (recurrent) state cannot be rebuilt from them, so every new turn re-prefilled the whole prompt unless a server snapshot covered it. This resumes from the live session instead. - State ladder: while a pooled prefill runs, state-only checkpoints (SSM and conv state, no KV; the drafter feature ring only with a drafter) are captured on the 512 grid at the head cut, every 8192 tokens and at the prompt end. LRU eviction keeps them under LUCE_KVFLASH_STATE_LADDER_MIB (default 3072); the head and newest rung are never evicted. - Live restore: the longest common prefix of the prompt and the live token history picks the greatest rung at or below it. The pager is truncated to that rung, the state restored, and only prompt[C:] prefills on the grid. restore_and_generate compares the server snapshot cut with the live cut and takes the larger (kvflash_pick_resume); a dense snapshot that outgrows the pool is adopted by the pager as identity-mapped chunks instead of failing, and a live cut survives the pool boundary. - Spec decode appends accepted tokens to the live history. A consuming restore or a cold prefill (image or not) drops the previous session's ladder. - LUCE_KVFLASH_SESSION is the one switch (default on, 0 disables the ladder and live restore; it does not gate the 512 grid). Only active with KVFlash on. - ModelBackend::restorable_prefix reports the cut a restore would take; the server reports the backend's own cut as prefix_len. - Docs: ENVIRONMENT.md rows and PREFIX_CACHE.md paragraphs.
run_gate.sh runs the same 10-turn chat twice against a fresh server, with LUCE_KVFLASH_SESSION=0 (cold arm) and default (restore arm), and cmp_gate.py checks the answers are byte-identical turn by turn. run_scenarios.sh covers pooled restore past the pool, an unrelated session in between, and an edit mid-history. Paths and the model come from the environment, nothing is hardcoded.
HttpServer::ram_restorable_prefix_tokens counted only the tokens of the RAM snapshot the prefix cache would restore. It now remembers that snapshot's slot and returns backend.restorable_prefix(prompt, slot, slot_tokens), with slot -1 and 0 tokens when none matched, so a KVFlash live session counts as restorable and a snapshot the backend would drop counts for nothing. The default implementation returns slot_tokens, so other backends are unchanged.
A dense snapshot restored from the disk cache can hold more rows than the KVFlash pool tensor (written by a server with no pool or a larger one). The plan let it through as Dense on an exact hit and as AdoptDense with live restore on, and restore_target_cache wrote past the pool tensor and aborted. kv_offset > pool_tokens now plans FullReprefill (Reject without a prompt), whatever adopt_dense says; AdoptDense applies only when the rows fit.
The chat DONE line printed the server's snapshot or disk-hit position as prefix_len whenever a restore was attempted, so a snapshot the backend dropped for a full re-prefill still showed its length. The Qwen3.5 backend now marks the cut it made (restore_cut_reported) and reported_prefix_len() prefers it, including 0. Other backends keep their numbers. The chat CACHE line keeps printing the disk-hit position: pooled_restore_identity.sh parses it.
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.
…se and replayed arm A verbatim Nothing ran mode C (run_gate.sh runs A and B), and with the edit disabled it passed vacuously. Any mode other than A or B now exits with the usage.
d5e4a35 to
784e521
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]>
…led grid branch Via the Luce-Org#849 branch merge; no new conflicts. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…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]>
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]>
…estore) into kvflash session restore branch Co-Authored-By: Claude Opus 5.5 <[email protected]>
…t pool layout restore) into kvflash turn checkpoints branch Luce-Org#852 carried the pre-10-23 Luce-Org#848-Luce-Org#851 chain, which conflicted with the rebased Luce-Org#851 in 10 files. This tree is the new Luce-Org#851 branch plus this PR's own commits (046516e, d664068, 0e2ff1b, b3ebe9b) re-applied, all clean; 342f22d duplicates Luce-Org#851's 784e521 and is already there. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…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]>
…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]>
Main equals the tested Luce-Org#851 head, so the tree is the tested Luce-Org#852 tree. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Stacked on #850. This PR's own commits are 73bbff7, 99e7342, 6573a85, 2dcf1e1, e6116c6, 2afbd31 and 784e521.
Why
A KVFlash conversation keeps its KV rows in the resident pool, but the DeltaNet (recurrent) state cannot be rebuilt from them. So every new turn re-prefilled the whole prompt unless a server snapshot covered it. This PR resumes from the live session instead.
What it does
LUCE_KVFLASH_STATE_LADDER_MIB(default 3072). The head checkpoint and the newest one are never evicted.prompt[C:]prefills, on the grid.restore_and_generatecompares the server snapshot's cut with the live cut and takes the larger (kvflash_pick_resume).LUCE_KVFLASH_SESSIONis on by default;0disables the ladder and live restore. It does not gate the 512 grid from feat(kvflash): pooled prefill on an absolute 512-token grid #850, and it only acts with KVFlash on.ModelBackend::restorable_prefixreports the cut a restore would take. The server logs the backend's own cut asprefix_len.HttpServer::ram_restorable_prefix_tokenscounted only the RAM snapshot the prefix cache would restore. It now passes that snapshot's slot and length torestorable_prefix. So a KVFlash live session counts as restorable, and a snapshot the backend would drop counts for nothing. The default implementation returns the snapshot length, so other backends are unchanged.--kvflashor with a larger pool. Before this commit, the adopt path in this PR aborted on it by writing past the end of the pool tensor.prefix_lenafter a re-prefill (60d98ef2). Theprefix_lenon thechat DONElog line is now the backend's own cut, so it is 0 after a re-prefill. Before, it showed the length of the snapshot the server had offered, even when the backend dropped it. Thechat CACHEline still shows the disk-hit position.optimizations/kvflash/tests/gate/. Paths and the model come from the environment.run_gate.shruns a 10-turn chat twice, with the session off and on, and checks the answers are byte-identical turn by turn.run_scenarios.shcovers: a pooled restore past the pool; a restore at a 512-token boundary; an image prompt.ENVIRONMENT.mdrows andPREFIX_CACHE.mdparagraphs.Checks
Gate A, RTX 3090, at the top of the stack (09bde623).
--max-ctx 131072,--kvflash 8192, temperature 0, seed 1. Same binary on both arms. The first turn is about 12.5K tokens, followed by 9 short turns. Each arm had its own empty disk KV cache, and every request loggeddisk_hit=false.LUCE_KVFLASH_SESSION=0)Medians over 10 turns, server side.
prefix_lenis 0 on every turn. With it on, it is 0 on turn 1 and then goes from 11,602 to 14,201, and each turn resumes at the previous turn's last assistant header (the cuts come from feat(kvflash): turn checkpoints, generation-end rung and turn cuts #852; with D alone, a turn resumes at the 512-grid checkpoint below it).PFlash admission gap, R9700 (lucebox6). Measured before the last rebase, on fc5563d (the previous top of the stack, on main af64ae9). On that tree the PFlash admission commit was d11ba7a; it is 6573a85 now. This run was not repeated on the current stack.
--kvflash 16384,PFLASH_ADMISSION=cache, the PFlash heads, and ggml-org's Qwen3.5-0.8B BF16 drafter. Three arms built from the top of the stack.L=31063 C=31063 replay=8393KVFlash off, RTX 3090. Main 6f2b179 vs the top of the stack (09bde623), same 10-turn chat without
--kvflash,--no-kv-cacheon both (Qwen3.8-27B UD-Q4_K_M,--max-ctx 131072, temperature 0):prefix_lenidentical turn for turn on all four runs (0, then 11600 to 14199), anddisk_hit=falseon every request.Tests
test_kvflash_live_restore.cpp,test_kvflash_resume.cpp,test_kvflash_state_ladder.cpp, and new cases intest_kvflash_restore_plan.cpp.test_ram_restorable_prefix_defers_to_the_backendandtest_ram_restorable_prefix_default_is_the_snapshot_tokensintest_server_unit.cpp.test_server_unit(CUDA build): 1094 passed, 0 failed, 7 skipped.Limits
--max-concurrency 1.--kvflashand the entry holds more rows than the pool. fix(qwen35): refuse a dense snapshot longer than the KV cache rows #847, now merged, fixes main. With this stack, the entry is not used and the prompt prefills from token 0.--draft, every ladder rung also stores the drafter's target-feature ring (4096 rows × 25600 BF16, 200 MiB on the 27B models). Rungs grow from 149.6 MiB to 349.6 MiB, so the 20-rung ladder pins about 6.8 GiB of host memory instead of 2.9 GiB. This costs memory and copy time, not correctness.