Skip to content

fix(kvflash): order a reused pool block after the page work queued on it - #854

Merged
davide221 merged 2 commits into
Luce-Org:mainfrom
dusterbloom:kvflash/fix-page-reuse-race
Oct 24, 2026
Merged

davide221 merged 2 commits into
Luce-Org:mainfrom
dusterbloom:kvflash/fix-page-reuse-race

Conversation

@dusterbloom

@dusterbloom dusterbloom commented Oct 17, 2026 •

Copy link
Copy Markdown
Collaborator

Why

When the KVFlash pool is full, the pager pages a cold chunk out to host memory and reuses its block for a new chunk. page_out queues two things on the pager's own CUDA stream: the copy of the block to host memory, and the zeroing of the block. It then frees the block at once. The next slot_for() hands that block to the backend's compute stream, which ggml-cuda creates as a non-blocking stream. Nothing orders the two streams. So the compute stream can write the new rows into the block before the queued work has run:

  • the write lands before the copy: the host archive of the evicted chunk receives the new bytes, and a later recall brings back wrong data;
  • the write lands before the zeroing: the new rows are wiped to zero.

Reproduction against main 6f2b179 (RTX 3090, CUDA build): the new unit test below, run as test_server_unit, reports corrupted chunks and fails. Whether a given run corrupts depends on scheduling, so this PR reports the measured rate (rounds corrupted out of rounds) rather than "always fails". Measured on the committed test file at e24f331: 33/40, 31/40 and 33/40 rounds corrupted in three runs (484, 537 and 525 corrupted chunks).

What was not observed: no server-level output difference. Qwen3.8-27B with --kvflash 16384 and a 38K-token prompt (pooled prefill, evicting) produced byte-identical answers on main and on this branch (4 server runs, see Tests). The race needs the compute write to overtake a copy that is queued ahead of it; on a real model each forward pass takes much longer than one chunk copy, so the window is small. The unit test removes the model and the passes between steps to make the window wide. This PR closes an ordering hole that the server run did not expose.

What it does

slot_for() now makes a new block safe before returning it. The pager remembers whether page work is queued on its stream, and when it hands out a block while work is queued it does one of two things:

  1. Default (host wait). It waits on the host until the pager stream has finished. This is correct for every pager user, with no change to them.
  2. Fast path (device wait). A backend can call the new set_compute_stream() with its compute stream, after attach() (which clears it). The pager then records an event on its own stream after the queued work and makes the compute stream wait for that event on the device. For this fence there is no host stall. Recall through alloc_span() and reselect() still waits on the host for the copy back, as before.

A failed stream or event call in the fence or in the explicit paging waits aborts the process with the call, the error string and the pool size, like CUDA_CHECK in ggml-cuda: ordering can no longer be guaranteed at that point, and continuing could hand out an unfenced block. With no tensor storage nothing was queued and no runtime call is made. Construction still falls back to the default stream if the page stream cannot be created, and the unchecked sync in cleanup_() predates this fix and is unchanged. attach() drops any registered compute stream, so a reattach cannot wait on a stream the caller has since destroyed.

HIP builds compile the event path out and stay on the host wait: re-recording an event while an earlier record is pending is documented as undefined on AMD, so set_compute_stream() does nothing there (cost: one host stall per reused block after a page-out). The upgrade path is an event per pending record, or a HIP-verified reuse. Compile-checked on gfx1151 (RDNA 3.5, ROCm 7.2.4): both luce_server and test_server_unit build for this tree and for main. test_server_unit on that GPU: main 1004 passed, 0 failed, 4 skipped; this branch 1004 passed, 0 failed, 4 skipped (the CUDA stress cases are built for CUDA only, so they are absent there). This checks that the HIP build still compiles and the existing tests are unchanged; it does not exercise the new fence, which is compiled out on HIP.

Which users use which:

  • Fast path: Qwen35Backend registers its compute stream right after the pager attaches (single GPU, non-tensor-parallel). Qwen35MoeBackend inherits this, because it calls Qwen35Backend::init() and shares the same pager and stream.
  • Default host wait: Gemma4, Laguna, the three layer-split adapters (qwen35, gemma4, laguna), and the qwen35 target shard daemon. Layer split must stay on the default: one pager spans several GPUs, each with its own compute stream, and the pager holds one stream and one event. Gemma4 and Laguna run on a single GPU and could register their stream in a follow-up; I did not, because I have no run of those two to check it with.
  • Consumers that use another owner's pager (the dflash targets, layer_split_forward.cpp, layer_split_kvflash.h) inherit the owner's behavior.

page_in into a block uses the same fence, since the recall copy is queued on the same stream.

The reverse order (a page-out copy reading a block while an earlier compute write to it is still running) is already ordered for Qwen35 and Qwen35Moe:

  • Qwen3.5 prefill chunks and decode steps run through ggml_backend_graph_compute, which is the async launch followed by ggml_backend_synchronize (ggml-backend.cpp:481-485). So the writes of one ubatch are complete before the next slot_for() queues a page-out (the ggml_backend_graph_compute(target_backend_, ...) calls in qwen35_backend.cpp).
  • The Qwen3.5 MoE pipelined decode launches graphs asynchronously, but pipelined_decode_one_token ends with ggml_backend_synchronize(backend) (qwen35moe_pipelined_decode.cpp) before the next token's slot_for() (qwen35moe_backend.cpp).
  • Not traced: Gemma4, Laguna, the layer-split paths and the shard daemon. I added no reverse-direction code and no test for it.

Tests

  • Two commits. The first adds the test and builds on main; the second is the fix and adds two test cases that need the new API. The first fails on main and the second passes; counts below.
  • New server/test/unit/test_kvflash_pager_cuda_race.cpp, on a real CUDA device with real tensors: 8 layers, 8 KV heads, pool of 8 blocks, 24 chunks appended through the full pool. Each new chunk is written on a separate non-blocking stream right after slot_for(). The interval from the page-out to the replacement write is not synchronized (that is the race); the previous chunk's write is explicitly waited for before each slot_for(), so the test does not depend on the implicit sync of a pinned allocation. At the end every chunk is read back: resident chunks from the pool, paged-out chunks by recalling them. Setup calls are checked and a failure fails the test with a message; with no device the tests are skipped. Three cases: the default one (first commit, runs against main), and in the fix commit one with a registered compute stream and one that reattaches after the registered stream is destroyed (a failed wait would abort the run; the case only detects what the runtime reports for a destroyed handle). 40 rounds for the stress cases; LUCE_KVFLASH_RACE_ROUNDS overrides it and must be a positive integer.
  • First commit alone, on main (red): the core case fails in 3 of 3 runs, [race] rounds=40 corrupted_rounds=33/31/33 corrupted_chunks=484/537/525.
  • With the fix commit (green): 3 of 3 runs of the race cases, corrupted_rounds=0 corrupted_chunks=0 of 40 rounds, both without and with a registered compute stream; the re-attach case passes 3 of 3.
  • test_server_unit (CUDA build, RTX 3090): main has 1016 passed, 0 failed, 7 skipped. This branch (b77e558): 1019 passed, 0 failed, 7 skipped (1016 plus the 3 new cases).
  • Before/after at b77e558 on Qwen3.8-27B UD-Q4_K_M, --kvflash 16384 --no-kv-cache --max-ctx 52224, temperature 0, seed 1, all KVFLASH_* and LUCE_KVFLASH_* variables cleared, client timed with time.monotonic. Five distinct prompts of 8037 to 8084 tokens (fits the pool) and five of 38054 to 38130 tokens (pages). 4 server runs in the order main, branch, branch, main, each under one GPU lock after an idle check: 2 per build, 5 requests per size per run, so 10 requests per build and size. Every request shows disk_hit=false, cache_hit=False, prefilled tokens equal to prompt tokens, and no prefix reuse, on both builds. Medians over the 10 requests per build and size:
prompt metric main branch
8K (no paging) prefill tok/s 1371.4 1350.6
8K (no paging) decode tok/s 48.80 48.15
8K (no paging) wall s 6.02 6.11
38K (pages) prefill tok/s 1233.8 1223.7
38K (pages) decode tok/s 45.20 45.35
38K (pages) wall s 31.04 31.28

Per-run medians (prefill tok/s, decode tok/s, wall s):

run build 8K 38K
1 main 1380.4, 48.60, 5.99 1219.4, 45.00, 31.38
2 branch 1347.6, 48.20, 6.14 1217.7, 45.00, 31.43
3 branch 1351.3, 48.10, 6.10 1235.8, 45.50, 30.96
4 main 1368.2, 49.00, 6.05 1249.2, 45.40, 30.65

Reading: at 38K the builds are inside run-to-run drift (main alone moved 2.4% in prefill between its two runs, 1219.4 to 1249.2). At 8K the branch is about 1.5% lower in prefill and 1.3% lower in decode, and both branch runs sit below both main runs, a gap about as large as main's own spread between its runs (0.9% prefill, 0.8% decode). Four runs cannot separate that from noise; I am reporting it as a possible small cost of the host wait, not as proven either way. This is not a speedup. Same-machine comparison; absolute tokens per second on this WSL2 box read high.

  • Answers: all 10 prompts gave the same answer text on all 4 server runs (main and branch, byte for byte), and the same text as the earlier runs at 0ebbcc12 (those earlier runs showed no gap: 8K prefill 1388.5 vs 1384.9, 38K 1246.5 vs 1257.2).
  • Binaries: main luce_server md5 85e94270 (the first commit's tree, which changes only the test), branch luce_server md5 31a60798. Shared libraries per build: libggml-cuda.so.0 95f2b4fb... (main) and 491a2261... (branch); libggml.so.0 0b944ecf... and 98ad88ab...; libggml-cpu.so.0 4235a4bc... and 80d8eec4....

Limits

  • No server-level corruption was observed (answers byte-identical), and the speed difference is within noise at 38K and about 1.5% lower at 8K over four runs. The evidence for the race is the unit test. The race may rarely or never show up on a real model run with the current graph sizes.
  • Default host wait: after a page-out, handing out the new block waits for that chunk's copy and zeroing to finish. This is one short stall per new chunk once the pool is full. Gemma4, Laguna, the layer-split paths and the shard daemon pay it. The timing above shows nothing measurable on the Qwen3.5 path, which uses the device wait instead; the host wait was not benchmarked on the backends that use it.
  • The fast path assumes the registered stream runs every graph that reads or writes the pool. A pool shared by several streams or devices must not register one.
  • Only the order "new write after queued page work" is fenced by the pager. The reverse order is covered, for Qwen35 and Qwen35Moe, by the synchronous graph calls cited above, not by new code in the pager.

View guided diff

…tream

page_out() queues the device-to-host copy and the block zeroing on the pager's
own stream and frees the block at once. The next slot_for() hands that block
to the compute stream, which ggml-cuda creates non-blocking, so nothing orders
the two. The test appends chunks through a full pool, writes each new chunk on
a separate non-blocking stream right after slot_for(), and then checks every
chunk by reading the pool (resident) or recalling it (paged out).

The interval from the page-out to the replacement write is not synchronized;
the previous chunk's write is waited for before each slot_for(), so the test
does not rely on the implicit sync of a pinned allocation. Setup calls are
checked, the test skips without a CUDA device, and the round count from
LUCE_KVFLASH_RACE_ROUNDS is validated.
page_out() queues the device-to-host copy and the zeroing of a block on the
pager's own stream and frees the block at once. slot_for() then hands the
block to the compute stream, which ggml-cuda creates non-blocking, so nothing
ordered the new write against the queued work: the write could land before
the copy (the host archive receives the new bytes) or before the zeroing (the
new row is wiped).

slot_for() now fences when it hands out a block while page work is queued. By
default that is a host wait on the pager stream. A backend that registers its
compute stream with set_compute_stream() gets a device-side wait instead (an
event recorded on the pager stream, waited on by the compute stream), with no
host stall for that fence. Qwen35Backend, and Qwen35MoeBackend through it,
registers its stream; the other pager users keep the safe default. HIP builds
compile the event path out and stay on the host wait, because re-recording an
event while an earlier record is pending is undefined there.

A failed stream or event call in the fence or the paging waits aborts, like
CUDA_CHECK in ggml-cuda: ordering can no longer be guaranteed. With no tensor
storage nothing was queued and no runtime call is made. attach() drops a
registered compute stream so a reattach cannot wait on a destroyed one.

The stress test now also runs with a registered compute stream, and a reattach
case is added.

@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 b77e558e · 0 candidate issues checked, kept at ≥70% confidence · add the code-review label to review again

@davide221
davide221 merged commit df7124d into Luce-Org:main Oct 24, 2026
11 checks passed
davide221 added a commit to dusterbloom/lucebox-hub that referenced this pull request Oct 24, 2026
…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]>
davide221 added a commit that referenced this pull request Oct 24, 2026
…tached (#886)

#854 made a failed cudaStreamSynchronize abort, and synced the default
stream whenever any KV tensor was attached. #848's pager serde and truncate
tests attach CPU-backend tensors with pageable host backing on hosted CI,
where the stub driver fails cudaStreamCreate and every sync. Host tensors
are paged with memcpy, so nothing is ever queued for them: only sync when a
page stream exists or a device tensor is attached.

Co-authored-by: Claude Opus 5.5 <[email protected]>
davide221 added a commit to dusterbloom/lucebox-hub that referenced this pull request Oct 24, 2026
…led 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]>
davide221 added a commit to dusterbloom/lucebox-hub that referenced this pull request Oct 24, 2026
…led grid branch

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

Co-Authored-By: Claude Opus 5.5 <[email protected]>
davide221 added a commit to dusterbloom/lucebox-hub that referenced this pull request Oct 24, 2026
…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]>
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