Skip to content

feat(kvflash): turn checkpoints, generation-end rung and turn cuts - #852

Merged
davide221 merged 49 commits into
Luce-Org:mainfrom
dusterbloom:kvflash/2.0a-E-turn-checkpoints
Oct 26, 2026
Merged

davide221 merged 49 commits into
Luce-Org:mainfrom
dusterbloom:kvflash/2.0a-E-turn-checkpoints

Conversation

@dusterbloom

@dusterbloom dusterbloom commented Oct 15, 2026 •

Copy link
Copy Markdown
Collaborator

Stacked on #851. This PR's own commits are 046516e (the feature), d664068 (test) and 0e2ff1b (fix).

Why

Live restore (#851) only resumed at 512-grid checkpoints. So a chat turn replayed up to a whole 512-token grid cell plus the previous answer. Two more checkpoints make the next turn resume where the last one ended. Both are under LUCE_KVFLASH_SESSION.

What it does

  • Generation-end checkpoint.
    • After decode, the backend captures one state-only checkpoint at cur_pos, off the grid, in the same LRU ladder. There, the KV and the DeltaNet state hold history[0:cur_pos].
    • Early stop inside a verified block (0e2ff1b). When a speculative step stops at EOS or a cancel before commit_n, the target has already run the rest of the block. The recurrent state and the feature ring were therefore ahead of cur_pos, and the checkpoint labelled that state cur_pos: it carried the token after EOS. The normal emit path now restores the pre-step snapshot and replays only the emitted tokens, as the floor path already does. On a 12-turn drafter chain this stop happened on every turn. The same repair covers main's --agent-turn-cache save after a drafter turn, by code reading; that path did not fire in these runs.
    • Live restore no longer requires the cut to be chunk aligned: pager.truncate zeroes the rows past it, and the replay rewrites them.
    • Each turn logs whether the re-rendered history still covers the checkpoint.
    • The checkpoint is used only when the next prompt carries the previous answer verbatim (thinking preserved, replayed tool calls). With the default template the think block is dropped, the history diverges before the checkpoint (L<G), and the turn cut below is used instead.
  • Turn cuts.
    • The chat template re-renders the previous assistant turn without its think block. So the next prompt diverges from the history right after the last assistant header.
    • kvflash_turn_cuts finds every assistant header, with the token ids read from the vocabulary. The last header becomes an exact checkpoint, and all of them become extra batch boundaries off the grid.
    • The cut set is a pure function of the prompt and is applied to every prefill. So a restore at a cut replays exactly the batches a cold prefill runs from there on.

Checks

Gate A, RTX 3090, on the feature commit (09bde623 before the last rebase, now 046516e). Same setup as #851.

  • Answers byte-identical on 10/10 turns.
  • Medians over 10 turns, server side: prefill 9.85 s with the session off against 0.55 s with it on; wall 10.45 s against 1.40 s. Decode is 44.5 tok/s on both.
  • Each arm ran on its own empty disk KV cache, and every request logged disk_hit=false.
  • On each turn the live-restore length equals prefix_len, and the replay starts at the last assistant header. Turn 2, for example, logs L=11602 C=11602 replay=356: only the re-rendered previous answer and the new message are prefilled.

R9700 (gfx1201), Qwen3.8-27B UD-IQ4_XS, --kvflash 16384 --max-ctx 52224, temperature 0, 12 turns, restored (session on) against cold (session off). run_gate.sh now runs the cold arm with --no-kv-cache --prefix-cache-slots 0; before, the cold arm could restore from the RAM prefix cache.

  • Template chain (gate4_live.py), AR: answers byte-identical on 12/12 turns. Medians: prefill 12.45 s cold against 0.65 s restored, wall 13.75 s against 2.20 s, decode 26.3 against 26.4 tok/s.
  • Verbatim chain (gate5_verbatim.py, new: each prompt is the previous prompt plus the generated tokens, so restores land on the generation-end checkpoint), DFlash2 drafter: 13 checkpoints captured and 10 used. Medians: prefill 13.15 s against 0.80 s, wall 13.85 s against 1.90 s, decode 58.4 against 58.8 tok/s.

Limits

  • A restore at the generation-end checkpoint continues from the KV rows and DeltaNet state that decode wrote, as the session would without any restore. A cold prefill of the same tokens writes them in batches and rounds differently, so the next answer can differ from a cold run where two tokens are nearly tied. On the verbatim chain under AR, 10/12 answers are byte-identical to cold. The other two flip the argmax at token 14 between the same two candidates; cold's top-2 margin there is 0.074 and 0.011 nats. Grid checkpoints and turn cuts are written by prefill and stay byte-identical (12/12 on the template chain).
  • With the drafter, restored answers are 11/12 identical to cold on both chains, before and after the fix. Under AR the same restore points give 12/12, so the difference comes from the drafter path, most likely its proposals after a restore changing verify widths and therefore rounding.

Tests

  • New cases in test_kvflash_live_restore.cpp, test_kvflash_restore_plan.cpp and test_kvflash_state_ladder.cpp, including early_stop_inside_a_verified_block_needs_a_state_repair.
  • test_server_unit: CUDA build on the feature commit, 1114 passed, 0 failed, 7 skipped. HIP build on 0e2ff1b, 1103 passed, 0 failed, 4 skipped.

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.
@davide221

Copy link
Copy Markdown
Contributor

CI failed on 09bde623

New KVFlash pager tests fail: cudaMallocHost fails on the GPU-less CI runner

Twelve new pager unit tests fail in the C++ CPU test step. The pager's new serialize/truncate code allocates its host backing with cudaMallocHost, which cannot work on the CI runner because it has no GPU (the CUDA driver is a stub), so page-out, eviction and deserialize all fail and the tests abort. The change under test is at fault: it added CPU-tensor fallbacks for the copy and zeroing paths but forgot the allocation path.

How to fix: Allocate the pager's host backing with plain malloc when the KV tensors are host-resident, keeping cudaMallocHost for device tensors.

  1. In server/src/common/kvflash_pager.h add a host_data_pinned flag to ChunkState and two helpers: alloc_host_ (malloc when is_host_tensor_(attn_k_[0]), else cudaMallocHost) and free_host_ (free/cudaFreeHost to match).
  2. Use alloc_host_ in page_out and deserialize, and free_host_ in reset, release_host_ and cleanup_.
  3. Rebuild and run ctest -R 'KvflashPager(Serde|Truncate)' (or make check-cpu) to confirm the 12 tests pass.

failing unit tests on cuda stub driver · high confidence · run

Details and evidence

Failed: Build (cmake + uv sync --extra megakernel) › Build and run C++ CPU unit tests

Job 'Build (cmake + uv sync --extra megakernel)', step 'Build and run C++ CPU unit tests': 12 tests fail, all in KvflashPagerSerdeFixture (9) and KvflashPagerTruncateFixture (3). The decisive log lines, in order: [kvflash] cudaStreamCreate failed; paging falls back to the (blocking) default stream, then [kvflash] cudaMallocHost failed: CUDA driver is a stub library, then [kvflash] no pool slot at pos 512 (pool 512 exhausted), and each test ends with Fail: kvflash serde helper precondition failed / kvflash truncate helper precondition failed.

Root cause: in CUDA builds (KVFLASH_HAS_ASYNC_DMA), KvFlashPager::page_out (server/src/common/kvflash_pager.h:378) and deserialize (server/src/common/kvflash_pager.h:657) allocate the per-chunk host backing with cudaMallocHost and return false when it fails. The CI runner has no GPU, so the stub CUDA driver makes every cudaMallocHost fail. The tests use CPU ggml tensors (server/test/unit/test_kvflash_pager_serde.cpp:38-47), and the PR already added a host-tensor fallback (is_host_tensor_, server/src/common/kvflash_pager.h:727-731) for the memcpy/memset paths in copy_chunk/zero_block/zero_chunk_rows_ — but not for the allocation path. So page_out(2) in build_source (test_kvflash_pager_serde.cpp:120) fails and must() throws (test_kvflash_pager_serde.cpp:69); in the truncate tests, eviction inside append fails the same way, so slot_for returns -1 and alloc_span reports the pool as exhausted (test_kvflash_pager_truncate.cpp:95). Everything else (1197 other tests) passes.

Other things to try

  • Reproduce locally: build with CUDA on a machine without a GPU (or with the stub driver) and run ctest -R 'KvflashPager(Serde|Truncate)' — the same 12 tests fail before the fix.
  • An alternative is to skip these fixtures when cudaMallocHost is unavailable, but the tests are meant to exercise the CPU-tensor path in CUDA builds (that is what is_host_tensor_ was added for), so fixing the allocation path is preferable.

The proposed patch was dropped: edits[1] (server/src/common/kvflash_pager.h): "find" must match exactly once, it matches 0 times; copy the text exactly from the file and include more context

Prompt for a coding agent
A GitHub Actions run failed in Luce-Org/lucebox. Please fix it.

- Pull request #852 (branch `kvflash/2.0a-E-turn-checkpoints`), commit 09bde6230a842cf858fd2a1c8889f371113d495b
- Workflow: CI (https://github.com/Luce-Org/lucebox/actions/runs/38761922374)
- Failed: Build (cmake + uv sync --extra megakernel) › Build and run C++ CPU unit tests

Diagnosis:
Job 'Build (cmake + uv sync --extra megakernel)', step 'Build and run C++ CPU unit tests': 12 tests fail, all in `KvflashPagerSerdeFixture` (9) and `KvflashPagerTruncateFixture` (3). The decisive log lines, in order: `[kvflash] cudaStreamCreate failed; paging falls back to the (blocking) default stream`, then `[kvflash] cudaMallocHost failed: CUDA driver is a stub library`, then `[kvflash] no pool slot at pos 512 (pool 512 exhausted)`, and each test ends with `Fail: kvflash serde helper precondition failed` / `kvflash truncate helper precondition failed`.

Root cause: in CUDA builds (`KVFLASH_HAS_ASYNC_DMA`), `KvFlashPager::page_out` (server/src/common/kvflash_pager.h:378) and `deserialize` (server/src/common/kvflash_pager.h:657) allocate the per-chunk host backing with `cudaMallocHost` and return false when it fails. The CI runner has no GPU, so the stub CUDA driver makes every `cudaMallocHost` fail. The tests use CPU ggml tensors (server/test/unit/test_kvflash_pager_serde.cpp:38-47), and the PR already added a host-tensor fallback (`is_host_tensor_`, server/src/common/kvflash_pager.h:727-731) for the memcpy/memset paths in `copy_chunk`/`zero_block`/`zero_chunk_rows_` — but not for the allocation path. So `page_out(2)` in `build_source` (test_kvflash_pager_serde.cpp:120) fails and `must()` throws (test_kvflash_pager_serde.cpp:69); in the truncate tests, eviction inside `append` fails the same way, so `slot_for` returns -1 and `alloc_span` reports the pool as exhausted (test_kvflash_pager_truncate.cpp:95). Everything else (1197 other tests) passes.

Proposed fix: Allocate the pager's host backing with plain malloc when the KV tensors are host-resident, keeping cudaMallocHost for device tensors.
1. In `server/src/common/kvflash_pager.h` add a `host_data_pinned` flag to `ChunkState` and two helpers: `alloc_host_` (malloc when `is_host_tensor_(attn_k_[0])`, else `cudaMallocHost`) and `free_host_` (free/cudaFreeHost to match).
2. Use `alloc_host_` in `page_out` and `deserialize`, and `free_host_` in `reset`, `release_host_` and `cleanup_`.
3. Rebuild and run `ctest -R 'KvflashPager(Serde|Truncate)'` (or `make check-cpu`) to confirm the 12 tests pass.

Check out that commit, confirm the diagnosis, make the fix (adjust it if the diagnosis is wrong), and re-run the failing step locally before pushing.

Reply with /ci-fix and what to change to get a revised diagnosis.

…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.
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.
…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.
Live restore only resumed at 512-grid rungs, so a chat turn replayed up to a
whole grid cell plus the previous answer. Two more rungs make the next turn
resume where the last one ended; both sit under LUCE_KVFLASH_SESSION.

- Generation end: after decode the backend captures one state-only rung at
  cur_pos (off the grid, in the same LRU ladder), where KV and DeltaNet state
  hold exactly history[0:cur_pos]. Live restore no longer requires the cut to be
  chunk aligned: pager.truncate zeroes the rows past it and the replay rewrites
  them. Each turn logs whether the re-rendered history still covers the rung.
- Turn cuts: the chat template re-renders the previous assistant turn without
  its think block, so the next prompt diverges from the history right after the
  last assistant header. kvflash_turn_cuts finds every header (token ids read
  from the vocabulary); the last one becomes an exact ladder rung, and all of
  them are extra batch boundaries off the grid. The cut set is a pure function
  of the prompt and applied to every prefill, so a restore at a cut replays
  exactly the batches a cold prefill runs from there on.
…arm without prefix cache, early-stop repair predicate

gate5_verbatim.py replays each prompt as the previous prompt plus the generated
tokens so a live restore reaches the gen ckpt; run_gate.sh selects it with
KV_SCRIPT and runs both arms with --no-kv-cache --prefix-cache-slots 0. The
predicate spec_early_stop_needs_repair is declared but returns false, so its
unit test fails.
…er an early stop in a verified block

When the emit loop stops before commit_n on EOS or cancel, the target has
already run all commit_n tokens, so its DeltaNet state and feature ring sit
past the committed position. The floor and budget-close paths repair this;
the normal path did not, and the generation-end checkpoint (and the agent turn
cache) captured the advanced state as history[0:cur_pos]. Restore the pre-step
snapshot and replay the emitted tokens, as the floor path does.
@dusterbloom
dusterbloom marked this pull request as ready for review October 21, 2026 12:16

@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: 0e2ff1be677ac3e857030fc317b5442e11cc35c9
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/gate5_verbatim.py">

<violation number="1" line="59" end_line="60">
Verbatim chain splices an empty think block instead of the generated reasoning, so prompts never reach the generation-en

The script's contract (docstring, line 1-4, and the comment on line 58) is that each turn's prompt is the previous prompt plus the tokens the model actually generated — thinking included — so that a live restore can resume exactly at the generation-end checkpoint captured at `cur_pos`. Line 59 builds that segment in `gen` from `o["reasoning"]`, but `gen` is never used; line 60 instead appends a hardcoded empty think block `"&lt;think&gt;\n\n&lt;/think&gt;\n\n"`. Whenever the model produces non-empty reasoning (the server streams `reasoning_content` deltas, collected on lines 40-41, and this gate targets thinking models), the next prompt diverges from the real token history right at the assistant turn — precisely the divergence the template re-render causes in gate4 and which this script was written to avoid. The failure is silent: both arms replay the same (non-verbatim) prompts, so `cmp_gate.py` still reports IDENTICAL, and the `gen` log lines collected on line 55 are never asserted, so the run passes without a single restore ever landing on the generation-end rung the test exists to exercise. Use the actual generated segment (the `gen` value from line 59) when extending `content`, and fail or warn when no `gen ckpt` usage is observed.

<suggestion>
        gen = ("&lt;think&gt;" + o["reasoning"] + "&lt;/think&gt;\n\n" if o["reasoning"] else "") + o["text"]
        content = content + "&lt;|im_end|&gt;\n&lt;|im_start|&gt;assistant\n" + gen + "&lt;|im_end|&gt;\n&lt;|im_start|&gt;user\n" + upd(t + 1)
</suggestion>
</violation>

</file>
Issue overview
  1. Verbatim chain splices an empty think block instead of the generated reasoning, so prompts never reach the generation-en · confirmed (optimizations/kvflash/tests/gate/scripts/gate5_verbatim.py:59-60)

Reviewed 0e2ff1be · 4 candidate issues checked, kept at ≥70% confidence · add the code-review label to review again

Comment on lines +59 to +60
gen = ("<think>" + o["reasoning"] + "</think>\n\n" if o["reasoning"] is not None else "") + o["text"]
content = content + "<|im_end|>\n<|im_start|>assistant\n" + "<think>\n\n</think>\n\n" + o["text"] + "<|im_end|>\n<|im_start|>user\n" + upd(t + 1)

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.

Verbatim chain splices an empty think block instead of the generated reasoning, so prompts never reach the generation-en · confirmed

The script's contract (docstring, line 1-4, and the comment on line 58) is that each turn's prompt is the previous prompt plus the tokens the model actually generated — thinking included — so that a live restore can resume exactly at the generation-end checkpoint captured at cur_pos. Line 59 builds that segment in gen from o["reasoning"], but gen is never used; line 60 instead appends a hardcoded empty think block "<think>\n\n</think>\n\n". Whenever the model produces non-empty reasoning (the server streams reasoning_content deltas, collected on lines 40-41, and this gate targets thinking models), the next prompt diverges from the real token history right at the assistant turn — precisely the divergence the template re-render causes in gate4 and which this script was written to avoid. The failure is silent: both arms replay the same (non-verbatim) prompts, so cmp_gate.py still reports IDENTICAL, and the gen log lines collected on line 55 are never asserted, so the run passes without a single restore ever landing on the generation-end rung the test exists to exercise. Use the actual generated segment (the gen value from line 59) when extending content, and fail or warn when no gen ckpt usage is observed.

Checked (90%): In gate5_verbatim.py:59 the variable gen is built from o["reasoning"] but never used; line 60 instead splices the hardcoded empty think block "\n\n" into the next prompt. So whenever the model streams non-empty reasoning (lines 40-41 collect reasoning_content), the next prompt diverges from the generated history and never lands on the generation-end rung the script exists to exercise; nothing asserts gen ckpt usage either.

Suggested change
gen = ("<think>" + o["reasoning"] + "</think>\n\n" if o["reasoning"] is not None else "") + o["text"]
content = content + "<|im_end|>\n<|im_start|>assistant\n" + "<think>\n\n</think>\n\n" + o["text"] + "<|im_end|>\n<|im_start|>user\n" + upd(t + 1)
gen = ("<think>" + o["reasoning"] + "</think>\n\n" if o["reasoning"] else "") + o["text"]
content = content + "<|im_end|>\n<|im_start|>assistant\n" + gen + "<|im_end|>\n<|im_start|>user\n" + upd(t + 1)

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.

Partly agree; fixed in b3ebe9b.

  • gen was dead, and nothing asserted that a restore landed on the generation-end checkpoint. Both fixed: each turn now records consumed (the live restore's C equals the gen ckpt G, with no state-restore or draft-sync fallback after it), and arm B exits nonzero when live restore ran and no turn consumed the checkpoint.
  • The hardcoded empty think block is the verbatim history, not a divergence. The gate runs with thinking off, where the template pre-fills <think>\n\n</think>\n\n after <|im_start|>assistant\n, so the generated tokens are the answer and EOS after that block. On the recorded R9700 runs reasoning was empty on every turn and the checkpoint was consumed on 10/12 turns with the drafter and 9/12 without; the template-chain run gives 0/12 and now fails. The suggested patch drops the block when reasoning is empty, which would break the match on every turn.
  • The script supports thinking off only, and now exits if a turn streams reasoning instead of rebuilding the think block from reasoning_content.

…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.
…s at the generation-end checkpoint, and exits on streamed reasoning

The chain copies the empty think block the template pre-fills with thinking
off, which is what the generated history holds; a thinking turn cannot be
rebuilt verbatim from reasoning_content, so it exits. Each turn records
consumed (live restore C == gen ckpt G, with no state-restore or draft-sync
fallback to a cold prefill); arm B exits nonzero when live restore ran and no
turn consumed the checkpoint. Removes the unused gen variable.

On the recorded lucebox6 runs: verbatim chain with drafter 10/12 consumed,
AR 9/12, AR template chain 0/12 (now a failure).
…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.
dusterbloom and others added 24 commits October 23, 2026 16:46
…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.
…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]>
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]>
The cold reference arm (LUCE_KVFLASH_SESSION=0) ran its pooled prefill on the
512 grid only, while the session arm also cut after every assistant header. So
a restore at a turn cut replayed the session arm's batches, not the reference's,
and on the R9700 the plain gate came out 9/10 (turn 2 differs, restored at the
cut 11602). The cuts are a pure function of the prompt, like the grid, so apply
them whatever the session switch says. The switch still turns off the ladder,
live restore and the turn checkpoints.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
With Luce-Org#852 the live restore at the turn cut (C=33722 at N=35K) beats the pooled
snapshot (33280), in the CONSUME=0 reference too, so the test saw no
'pooled restore: consume' line and failed although the text matched.
LUCE_KVFLASH_SESSION=0 keeps it on the path it tests; the session is covered by
tests/gate.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A pooled snapshot is only consumable at a multiple of the 64-token chunk, and
the boundary snapshot was taken at the start of the batch holding snap_pos. With
turn cuts that start can be a cut: at N=20K turn 2 saved at 18815, and turn 3
fell back to a full re-prefill of 18893 tokens. Take it at the last
chunk-aligned batch start at or below snap_pos (kvflash_pooled_snapshot_pos),
or skip it when there is none.

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

Copy link
Copy Markdown
Contributor

Rebased this onto the new #851 (it conflicted in 10 files) as a merge commit, your own diff unchanged, then pushed three fixes on top. All found on the R9700 (lucebox2), pool 8192:

  1. 3cdec28 turn cuts on every pooled prefill. The plain gate was 9/10: turn 2 restored at the cut 11602 and differed from A. Arm A runs with LUCE_KVFLASH_SESSION=0, which also turned the cuts off, so A batched 11264 -> 11776 while B's restored rows came from 11264 -> 11602. The cuts are a pure function of the prompt, like the 512 grid, so they now apply whatever the session switch says (the switch still gates the ladder, live restore and turn checkpoints). Cold prefill cost: 12.2 -> 12.5 s median at ~12K.
  2. 2ac040f identity test with the session off. With this PR the live restore at the turn cut beats the pooled snapshot (C=33722 vs 33280 at N=35K), in the CONSUME=0 reference too, so pooled_restore_identity.sh found no pooled restore: consume line. It now runs with LUCE_KVFLASH_SESSION=0; the session is covered by tests/gate.
  3. 14aead4 pooled boundary snapshot on a chunk multiple. With cuts, the boundary snapshot could be taken at a cut (turn 2 saved at 18815), which a pooled restore can never consume, so turn 3 re-prefilled all 18893 tokens. It now goes to the last chunk-aligned batch start at or below snap_pos (kvflash_pooled_snapshot_pos, unit-tested).

lucebox2 with all three:

  • plain gate (gate4): 10/10 identical, wall 13.45 s -> 1.65 s
  • verbatim gate (gate5): 9/10; turn 2 restores at the generation-end rung and flips "a status of ok" / "an ok status", the decode-written-KV case your description already lists
  • pooled_restore_identity.sh: PASS at 20K, 35K, 64K, turns 2 and 3 suffix-only
  • scenarios 1-3: PASS
  • unit: 1126/0 (GPU), 1124/0 (no GPU)
  • DGX GB10 job steps run by hand on gx10-01bc (the CI runner is offline): all pass, plus the Kvflash unit tests on CUDA

davide221 and others added 3 commits October 25, 2026 15:08
…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]>
@davide221
davide221 merged commit 9a2c0b6 into Luce-Org:main Oct 26, 2026
14 of 20 checks passed
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