Skip to content

feat(kvflash): mode 4's exact GPU scorer uses a fused chunk-mass kernel over a device archive of evicted K (stacked on #963) - #994

Merged
davide221 merged 48 commits into
Luce-Org:mainfrom
dusterbloom:kvflash/g2b-fused-scorer
Nov 19, 2026
Merged

davide221 merged 48 commits into
Luce-Org:mainfrom
dusterbloom:kvflash/g2b-fused-scorer

Conversation

@dusterbloom

@dusterbloom dusterbloom commented Nov 12, 2026 •

Copy link
Copy Markdown
Collaborator

Stacked on #963. Base: kvflash/prefill-recall at 2a01709b0 (#963's head: the lean #963 with main 1d949fd88 merged). Review range: 2a01709..643e03c, 15 commits, 14 files, +1639 / -42. Restacked 2026-11-19 from 934a9451a: its 9 commits plus 43fe79c39 (the fused scorer workspace is released before the GPU scorer refuses on free VRAM) replay onto the lean #963 with one conflict, in kvflash_pager.h: #963 no longer has the device victim tier, so the chunk versions stay and the victim fields go. The last five commits answer the review findings (0fa2db286, eb8df077b, 3503fa2e2, ed10245dc, 643e03c09). check_commit_messages.py --base 2a01709b0 --head 643e03c09: all 15 OK.

Gate on this head (2026-11-19, section "Restack gate" below): mode 4 against #963's head on 3 recorded sessions, 165 of 165 requests with identical output and picks, session prefill 677 vs 651 tok/s, wall 608 vs 628 s, decode 30.1 tok/s on both; HIP unit tests 380/380 on gfx1201 and gfx1151, the two new device tests run (not skipped) on both. The 14-session landing gate and the tests further below ran on an earlier form of this range.

The tests and the gate below ran on aec6a3e5c, the same 7 commits on 50020e4c5 (the head G2's gate ran on). 4be2caad4 is that tree plus #963's last three commits (2a6e64c53, 9fc7a36a4, d98512ff0): git diff aec6a3e5c 4be2caad4 is 3 files, +9 / -3 (ENVIRONMENT.md, a comment in kvflash_query_capture.h, one unit-test fixture). No compiled server code differs. Build and test_server_unit on 4be2caad4: pass, 0 failures (rebase record).

The landing gate passes: mode 4 with this PR against K1 on the 14 recorded sessions, one binary, session prefill 0.896x (bar 0.85x; G2's gate was 0.860x), P1 31/40 vs 0/40, P2 26/40 vs 24/40. Against the G2 scorer on the same binary (LUCE_KVFLASH_GPU_SCORE_FUSED=0, 3 sessions) the pick lists are identical on 137 of 137 requests.

Why

On G2's gate mode 4 costs 0.860x of K1's session prefill. After G2's reuse path, what is left of that cost is the exact scorer on the turns that still score: every call uploads the K of every evicted chunk from host again and runs a logits graph over it. On a 3-session screen (lucebox6 R9700, 151 requests, 36 scorer calls) that was 28.0 s of scorer time: "h2d 10.4 s graph 8.7 s total 28.0 s; uploaded 31701 of 31701 evicted chunks".

The evicted K does not change between calls unless the pager rewrites the chunk, and the score needs one number per chunk and query plane, not the logits.

What it does

  1. Device archive. The scorer keeps the evicted K it uploads in one device tensor per layer, [D, cap * chunk_tokens, heads]. Slots are keyed by KvFlashPager::chunk_version(c), so a chunk is uploaded again only after the pager rewrote it. kvflash_gpu_archive_plan (pure) decides hit, upload and evict per call. The archive grows with device-to-device carry-over and is taken only under the scorer's existing free-memory guard (about 1.06 MiB of VRAM per evicted chunk at q8_0).
  2. Fused chunk-mass kernel (kvflash_fused_mass.h, kvflash_fused_mass_cuda.cu). One kernel reads the pool K and the archive in place (q8_0 blocks), multiplies by the queries quantized exactly as MMQ quantizes them for a q8_0 operand, and reduces to per-chunk partials (local max and sum-exp), which a second pass rescales into the attention mass. No logits tensor exists. int8 WMMA on gfx12, dp4a on CUDA and other HIP targets. kvflash_fused_mass.h holds a CPU reference of the same numerics; the unit tests compare device, reference and the logits-graph scorer.
  3. Default and fallback. Mode 4's exact GPU scorer uses the kernel when KvFlashGpuMass::fused_available(k_type, head_dim, n_layers) holds: K is q8_0, head dim is a multiple of 32 and at most 256, at most 64 layers, and the build has the kernel. Otherwise, on a kernel error, or with LUCE_KVFLASH_GPU_SCORE_FUSED=0, the logits graph scores as on G2 and the archive stays off (the graph spans every slot held, so an archive under it costs more than it saves: graph 8.7 s to 13.3 s on the screen). A kernel error logs once: [kvflash] fused scorer unavailable: <why>; using the logits graph.

Nothing else changes: the selector, the picks budget, the reuse / prescore / two-pass paths and the rewind are G2's. With --kvflash off none of this code runs.

Which device gets the fused path with the default q8_0 K:

Device Path Evidence on this head
RTX 3090 (sm_86, CUDA) fused, dp4a unit: device vs reference worst 1.22e-06
R9700 (gfx1201, HIP) fused, int8 WMMA unit: 1.2e-06; engine: gate, 173 of 173 scorer calls fused=1, 0 fused scorer unavailable lines
Strix Halo (gfx1151, HIP) fused, dp4a unit: 1.13e-06

Any device with another K type (f16, q4_0, ...) or head dim takes the logits graph.

One new knob, in server/docs/ENVIRONMENT.md: LUCE_KVFLASH_GPU_SCORE_FUSED (default 1; 0 = logits graph, no archive).

Commits

Commit Subject
d1f6c8ce9 feat(kvflash): exact GPU scorer can keep the evicted K it uploads in a device archive, keyed by pager chunk versions
52701ab4f test(kvflash): CPU reference of the fused exact chunk-mass math (per-chunk local max and sum-exp, rescaled reduce) with the 217K roofline; matches the exact scorer to 3e-7 on mean and plane masses
8453eeb4c feat(kvflash): fused exact chunk-mass kernel (CUDA/HIP, q8_0 K x q8_1 q int8 dp4a, per-chunk partials, rescaled reduce, query tiles) with a CPU reference of the MMQ numerics; device matches it to 1.4e-6
0389b2444 perf(kvflash): fused kernel keeps the q block and loops in registers (compile-time D and chunk tokens, online max/sum-exp); 3090 kernel 140 ms per 217K call extrapolated, was local-memory bound
a47087d92 fix(kvflash): fused kernel quantizes q exactly as MMQ does for q8_0 K (d_inv = 127 / amax, float block scale, no fp16 rounding); device scores now match the logits graph to 4.4e-7
2e74c75a0 perf(kvflash): fused scorer uses int8 WMMA on gfx12 (16 planes x 16 tokens per wave, MMQ scale order kept); gfx1201 kernel 302 ms -> 82 ms at 3382 chunks, dp4a stays for CUDA and as impl=1
767dbc734 feat(kvflash): mode 4's exact GPU scorer defaults to the fused chunk-mass kernel over the pool K and the device archive
4736fa393 test(kvflash): fused-mass device tests skip without a GPU and the chunk-version test uses pageable staging, so check-cpu passes on the stub-driver runner
c20464905 fix(kvflash): fused scorer takes the WMMA path only on gfx1200/gfx1201, not any gfx12*
43fe79c39 fix(kvflash): release the fused scorer workspace before the GPU scorer refuses on free VRAM
0fa2db286 fix(kvflash): a failed fused run clears the CUDA sticky error, so the logits-graph fallback does not abort on it
eb8df077b fix(kvflash): the first failed fused run latches the kernel off for the scorer, so it is not retried on every call
3503fa2e2 fix(kvflash): a pager reset frees the GPU scorer's device archive instead of holding it until backend teardown
ed10245dc test(kvflash): the GPU CI jobs run the fused-mass and GPU-scorer fixtures, and a device case covers D=256 ct=64
643e03c09 fix(kvflash): a pooled snapshot restore drops the GPU scorer's device archive, since deserialize() resets the pager inside

Each of the 15 commits builds alone with every target (CUDA sm_86 build, luce_server, test_server_unit, test_model_smoke and the kernel object; 2026-11-19, rc=0 for all 15). The HIP builds are the two heads in the gate below.

Evidence

Restack gate (2026-11-19)

lucebox6 R9700 hip:0 (gfx1201, ROCm 7.2.4), HIP builds gfx1151;gfx1201 of #963's head 2a01709b0 (base, md5 dfd56422) and of 643e03c09 (md5 0500e482), Qwen3.8-27B UD-IQ4_XS, q8_0 K/V, --max-ctx 139264 --kvflash 16384 --prefix-cache-slots 8 --prefix-cache-max-mib 40960 --disk-prefix-cache off --no-kv-cache, mode 4 (recall profile: mode 4 (exact scorer) on every arm), 3 recorded sessions, 165 requests per arm, temperature 0, seed 1, page cache dropped before each arm, arms base / this PR / G3 on this PR / base.

Arm Output vs base Picks vs base Session prefill Decode med / mean / best / min (decode > 2 s, n 10) Wall
base (1st) - - 652 tok/s 30.10 / 30.08 / 30.30 / 29.90 627.4 s
this PR 165/165 identical identical (387 lines) 677 tok/s (1.04x) 30.10 / 30.12 / 30.30 / 30.00 608.2 s (0.97x)
base (2nd) 165/165 identical identical 650 tok/s 30.10 / 30.09 / 30.30 / 30.00 628.3 s

Prompt and cached tokens are equal on every request. The fused kernel scored all 48 scorer calls (fused=1), with no fused scorer unavailable line. The same replay on 43fe79c39 (this range without the five review commits) gave the same 165 outputs and picks, so the review commits do not change the numerics.

HIP unit tests (ctest -R '[Kk]vflash|[Ll]aunch|[Pp]rops|[Ff]eature.?[Gg]ate|[Ss]pec|[Dd]raft|[Rr]ollback'): 380 passed / 0 failed on gfx1201 and on gfx1151 (base: 357 / 0). KvflashFusedMassFixture.device_kernel_matches_the_cpu_reference_at_d256_ct64 and device_failed_run_leaves_no_cuda_error_behind run and pass on both GPUs (no no CUDA/HIP device skip).

Tests (earlier form)

Head aec6a3e5c. test_server_unit <group>.

Check RTX 3090 (sm_86, WSL) R9700 (gfx1201, lucebox6 hip:0) Strix (gfx1151, lucebox6 hip:1)
KvflashFusedMass 7 passed, 0 failed 7 passed, 0 failed 7 passed, 0 failed
device vs CPU reference, worst (1 tile / 5 tiles) 1.22e-06 / 1.22e-06 1.2e-06 / 1.2e-06 1.13e-06 / 1.13e-06
KvflashGpuMass (20 cases) 20 passed 20 passed (fused over archive vs graph worst 4.02e-07) 20 passed (fused over archive vs graph worst 4.72e-07)
KvflashPagerRecall 4 passed in the full suite in the full suite
full test_server_unit 1401 passed, 0 failed, 7 skipped 1382 passed, 0 failed, 5 skipped (private TMPDIR) 1382 passed, 0 failed, 5 skipped (private TMPDIR)

On lucebox6 the first full run with the shared /tmp failed one case on both cards, test_disk_cache_longest_prefix_and_prune_ancestors (test_server_unit.cpp:14732, cache.save); the log shows /tmp/luce_test_*.gguf files owned by another user that the suite could not open for writing. With TMPDIR set to a private directory the same binary passes all 1382 on both cards.

Selection and fallback cases in test_kvflash_gpu_mass.cpp: fused_kernel_is_selected_only_for_the_k_it_can_score, fused_request_on_other_k_types_scores_with_the_logits_graph, fused_kernel_over_the_archive_matches_the_logits_graph (5 residency steps, tolerance 1e-3).

Screen before the gate

lucebox6 R9700 hip:0 (gfx1201), 2026-11-11, luce_server md5 4346a634 built from 7cd7b260e on the screens branch (the same kernel, archive and selection code as this head, plus the experiment switches that are not in this PR), Qwen3.8-27B UD-IQ4_XS, 3 recorded sessions, 151 requests / 330,710 new tokens per arm, one binary and one session for all arms. Per-session values: median / mean / best / min.

Arm Session prefill (all) Per session Decode median Wall Scorer (36 calls) P1 P2
K1 (lru + pin) 800 tok/s (414 s) 805 / 803 / 840 / 764 28.0 tok/s 764 s - 0/9 5/9
Mode 4, G2 scorer (FUSED=0) 679 tok/s (487 s), 0.849x 687 / 681 / 698 / 657 27.1 tok/s 851 s (1.115x) 28.0 s, 31701 of 31701 chunks uploaded 9/9 4/9
Mode 4, this PR 747 tok/s (443 s), 0.934x 751 / 748 / 764 / 729 28.2 tok/s 753 s (0.986x) 4.0 s, 5985 of 31701 uploaded 9/9 4/9

Picks, this PR against the G2 scorer: 137 pick lists compared, 137 identical.

Gate on the earlier form (aec6a3e5c)

lucebox4 R9700 hip:0 (gfx1201, PCIe 3.0 x2, the card of G2's gate), 2026-11-11, one luce_server (md5 1daf5b10, built from aec6a3e5c; libggml-hip.so.0 md5 9dc3e9b8) for every arm, Qwen3.8-27B UD-IQ4_XS, the same 14 sessions as G2's gate (882 requests, 40 P1 and 40 P2 probes per arm). The arms ran with G2's arm script m4cost_arm.sh (md5 4b1e2b8b) and were judged by m4cost_eval.py gate, both unchanged, with the bars fixed before the run. There is no m4cost_gate.sh file; G2's gate is that pair, called from its chain script. Server flags on every arm: --max-ctx 139264 --prefix-cache-max-mib 40960 --prefix-cache-slots 8 --disk-prefix-cache off --no-kv-cache --cache-type-k q8_0 --cache-type-v q8_0 --kvflash 16384. Runner: thinking on, effort medium, T 1.0, top_p 0.95, top_k 20, probe max_tokens 16384. Arms differ only in LUCE_KVFLASH_POLICY=lru on K1; arm identity is read from the server logs (K1 policy=lru, M4 recall profile: mode 4 and policy=qk, 851 preamble-pin lines each). Caching state: prompt tokens 62,012,284 on both arms, cached prefix 60,542,275 (K1) vs 60,542,272 (M4), prefix_len > 0 on 881 of 882 requests in both. No power limit set or recorded.

Arm P1 P2 Session prefill (all) Per-session prefill med / mean / best / min Per-session decode med / mean / best / min Wall (per session med / mean / min / max)
K1 (lru + pin) 0/40 24/40 812 tok/s (1811 s) 822 / 814 / 882 / 717 29.2 / 29.2 / 29.2 / 29.1 3346 s (236 / 239 / 151 / 334)
Mode 4, this PR 31/40 26/40 728 tok/s (2020 s), 0.896x 750 / 733 / 818 / 619 29.0 / 29.0 / 29.1 / 28.8 3631 s, 1.085x (257 / 259 / 174 / 391)

Decode over all requests with out >= 64: median 29.2 tok/s (n 80) on K1, 29.0 (n 71) on mode 4, 0.993x.

Gate lines: PASS prefill >= 0.85 x K1 (0.896), PASS P1 >= K1+3 (31 vs 0), PASS P2 >= K1-2 (26 vs 24), GATES M4 vs K1: PASS. Mode-4 paths: reused 637, prescore 80, full 93, skip-fits 21, skip-pool 20, none 31 (the same counts as G2's gate); re-prefill 63,332 tokens; paging 27.8 s. Scorer: 173 calls, all fused=1, 16.1 s total (h2d 8.3 s, kernel 4.7 s in the log field graph), 26,344 of 148,018 evicted chunks uploaded.

Against G2's gate (same box, card and sessions, other binary and another day's run, so not a same-binary comparison): scorer 106.3 s to 16.1 s, session prefill 697 to 728 tok/s, 0.860x to 0.896x of K1 (K1 811 and 812 tok/s), wall 1.11x to 1.085x, P1 and P2 unchanged at 31/40 and 26/40.

Picks control, same binary. A third arm ran 3 of the sessions (151 requests) with LUCE_KVFLASH_GPU_SCORE_FUSED=0 (the G2 scorer; started with a copy of the arm script that adds this arm and limits its idle check to card 0). Compared with the same 3 sessions of the gate's mode-4 arm:

Arm (3 sessions) Session prefill Per session med / mean / best / min Decode median Wall Scorer P1 P2
FUSED=0 (logits graph) 736 tok/s (449 s) 742 / 738 / 752 / 719 29.1 tok/s 742 s 36 calls, 23.5 s, 31701 of 31701 chunks uploaded 9/9 4/9
This PR (from the gate arm) 770 tok/s (428 s) 775 / 771 / 785 / 754 29.1 tok/s 722 s 3.6 s 9/9 4/9

picks, M4 fused vs M4G graph: compared 137, identical 137, mean overlap 1.000. The two rows are not a clean speed pair: the control ran on a fresh server and the gate arm inside its 14-session run, and one request differs in cached prefix (new tokens 330,710 vs 329,645; prefix_len > 0 on 150 vs 151 of 151). The speed claim rests on the gate table; this arm is for the pick identity.

Limits

Not run:

  • E20, EXECODE, LongMemEval-S and K0 on this head.
  • The 14-session gate and its P1/P2 probes on this head; the restack gate above is 3 sessions without probes.
  • Any engine run on CUDA or on Strix; their evidence is unit tests. The engine numbers are R9700 (HIP).
  • The fallback path in an engine run on a non-q8_0 K (unit test only). The FUSED=0 control arm exercises the logits graph on q8_0.
  • Tensor parallelism (recall is off there, as on G2).
  • Full ctest; the suite run is test_server_unit.
  • A power limit is not recorded for any engine run.

View guided diff

@davide221

Copy link
Copy Markdown
Contributor

CI failed on 4be2caad

New kvflash tests fail on the GPU-less CI runner: device tests never skip, one pager test needs pinned memory

Four of the pull request's own new unit tests fail in the CPU test job. Three device-kernel tests try to initialize CUDA and hard-fail when the runner has no GPU (only a stub driver), instead of skipping like the neighboring GPU tests. A fourth pager test asks the driver for pinned host memory, which the stub driver refuses, while the identical tests around it explicitly fall back to pageable memory. The compiled code is fine; the tests just were not written for a GPU-less runner.

How to fix: Skip the fused-kernel device tests when no GPU is present, and use pageable host backing in the chunk-version pager test.

  1. In server/test/unit/test_kvflash_fused_mass.cpp, add if (ggml_backend_cuda_get_device_count() <= 0) SKIP("CUDA/HIP device unavailable"); as the first line of the three device TEST_CASEs (the file already includes ggml-cuda.h under LUCE_HAVE_KVFLASH_FUSED_MASS).
  2. In server/test/unit/test_kvflash_pager_recall.cpp, add p.set_pinned_host_backing(false); to chunk_version_changes_only_when_its_rows_are_written, matching the other three cases in the file.
  3. Rebuild and rerun ctest -R 'KvflashFusedMass|KvflashPagerRecall' on a GPU-less machine: the three device tests report Skipped, the pager test passes.

new unit tests require a gpu on a gpu-less runner · 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 (check-cpu): 4 of 1576 ctest cases fail, all added by this PR.

Tests 1256–1258 (KvflashFusedMassFixture.device_kernel_matches_the_cpu_reference, ..._tiles_the_queries_without_changing_scores, ...dp4a_impl_matches_and_wmma_impl_is_refused_off_gfx12): all three call fused_gpu_worst (server/test/unit/test_kvflash_fused_mass.cpp:161), whose first step is ggml_backend_cuda_init(0) with if (!be) return -1; (line 162-163). The runner has no GPU, so init fails — the log shows ggml_cuda_init: failed to initialize CUDA: CUDA driver is a stub library / ggml_backend_cuda_init: invalid device 0 — the helper returns -1 and CHECK(w >= 0) (lines 225, 236, 246) fails. These are device tests that must skip when no device exists; the established pattern in this repo is if (ggml_backend_cuda_get_device_count() <= 0) SKIP("CUDA/HIP device unavailable"); (server/test/unit/test_cuda_copy_batch.cpp:27-29), and the sibling GPU cases in this area were all Skipped in the same run (tests 1277, 1300-1305, 1403-1407, 1503-1511).

Test 1297 (KvflashPagerRecallFixture.chunk_version_changes_only_when_its_rows_are_written): the log shows [kvflash] cudaMallocHost failed: CUDA driver is a stub library, [kvflash] no pool slot at pos 512 (pool 512 exhausted), then Fail: pager recall helper precondition failed — the must(p.alloc_span(0, 14 * kChunk)) at server/test/unit/test_kvflash_pager_recall.cpp:133 threw. This is the only one of the four pager cases in this file missing p.set_pinned_host_backing(false) (compare lines 72, 79, 95, 110, all commented CPU tensors: pageable staging, no cudaMallocHost (stub-driver CI)); with pinned backing requested, the stub driver's cudaMallocHost failure breaks the pager's host backing and the pool cannot hand out blocks. The shared helper for exactly this exists in server/test/unit/kvflash_pager_test_host.h:24-26 (TestPager falls back to pageable memory).

The PR description's test_server_unit: pass was recorded on a GPU machine; this CI job builds with CUDA but runs on a GPU-less runner, which the new tests did not handle.

Other things to try

  • Reproduce locally by running the built test_server_unit ctest cases on any machine without a GPU (or with the CUDA stub driver): ctest -R 'KvflashFusedMassFixture|KvflashPagerRecallFixture'.
  • Alternative for the pager case: construct it with the shared TestPager helper from server/test/unit/kvflash_pager_test_host.h, which probes cudaMallocHost and falls back automatically, instead of hard-coding set_pinned_host_backing(false).
Patch (2 files)

Not applied anywhere. To try it, save the diff as fix.patch and run git apply fix.patch.

diff --git a/server/test/unit/test_kvflash_fused_mass.cpp b/server/test/unit/test_kvflash_fused_mass.cpp
index f6ad879a..2e164262 100644
--- a/server/test/unit/test_kvflash_fused_mass.cpp
+++ b/server/test/unit/test_kvflash_fused_mass.cpp
@@ -217,6 +217,7 @@ double fused_gpu_worst(const FSynth & s, size_t max_partial_bytes, double floor_
 }  // namespace
 
 TEST_CASE(KvflashFusedMassFixture, device_kernel_matches_the_cpu_reference) {
+    if (ggml_backend_cuda_get_device_count() <= 0) SKIP("CUDA/HIP device unavailable");
     FSynth s;
     s.build(GGML_TYPE_Q8_0, 3, 6, 2, 64, 41, 16, 5, 9);   // G = 3, 18 planes
     int tiles = 0;
@@ -227,6 +228,7 @@ TEST_CASE(KvflashFusedMassFixture, device_kernel_matches_the_cpu_reference) {
 }
 
 TEST_CASE(KvflashFusedMassFixture, device_kernel_tiles_the_queries_without_changing_scores) {
+    if (ggml_backend_cuda_get_device_count() <= 0) SKIP("CUDA/HIP device unavailable");
     FSynth s;
     s.build(GGML_TYPE_Q8_0, 2, 24, 4, 128, 67, 64, 19, 4);   // G = 6, 48 planes, ct 64, D 128
     int t1 = 0, t2 = 0;
@@ -240,6 +242,7 @@ TEST_CASE(KvflashFusedMassFixture, device_kernel_tiles_the_queries_without_chang
 }
 
 TEST_CASE(KvflashFusedMassFixture, dp4a_impl_matches_and_wmma_impl_is_refused_off_gfx12) {
+    if (ggml_backend_cuda_get_device_count() <= 0) SKIP("CUDA/HIP device unavailable");
     FSynth s;
     s.build(GGML_TYPE_Q8_0, 3, 6, 2, 64, 41, 16, 5, 9);
     const double w = fused_gpu_worst(s, (size_t)1 << 30, 1e-8, nullptr, 1);
diff --git a/server/test/unit/test_kvflash_pager_recall.cpp b/server/test/unit/test_kvflash_pager_recall.cpp
index ea10d8bf..8b3c945e 100644
--- a/server/test/unit/test_kvflash_pager_recall.cpp
+++ b/server/test/unit/test_kvflash_pager_recall.cpp
@@ -129,6 +129,7 @@ TEST_CASE(KvflashPagerRecallFixture, slot_mask_hides_rows_above_the_decode_posit
 TEST_CASE(KvflashPagerRecallFixture, chunk_version_changes_only_when_its_rows_are_written) {
     Harness h;
     KvFlashPager p;
+    p.set_pinned_host_backing(false);  // CPU tensors: pageable staging, no cudaMallocHost (stub-driver CI)
     REQUIRE(p.attach(cfg(), h.k, h.v));
     must(p.alloc_span(0, 14 * kChunk));
     const uint64_t v2 = p.chunk_version(2), v3 = p.chunk_version(3);
Prompt for a coding agent
A GitHub Actions run failed in Luce-Org/lucebox. Please fix it.

- Pull request #994 (branch `kvflash/g2b-fused-scorer`), commit 4be2caad4e9c5cc8cfdb2b797750835f68e0499f
- Workflow: CI (https://github.com/Luce-Org/lucebox/actions/runs/43138875076)
- 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` (check-cpu): 4 of 1576 ctest cases fail, all added by this PR.

**Tests 1256–1258** (`KvflashFusedMassFixture.device_kernel_matches_the_cpu_reference`, `..._tiles_the_queries_without_changing_scores`, `...dp4a_impl_matches_and_wmma_impl_is_refused_off_gfx12`): all three call `fused_gpu_worst` (server/test/unit/test_kvflash_fused_mass.cpp:161), whose first step is `ggml_backend_cuda_init(0)` with `if (!be) return -1;` (line 162-163). The runner has no GPU, so init fails — the log shows `ggml_cuda_init: failed to initialize CUDA: CUDA driver is a stub library` / `ggml_backend_cuda_init: invalid device 0` — the helper returns -1 and `CHECK(w >= 0)` (lines 225, 236, 246) fails. These are device tests that must skip when no device exists; the established pattern in this repo is `if (ggml_backend_cuda_get_device_count() <= 0) SKIP("CUDA/HIP device unavailable");` (server/test/unit/test_cuda_copy_batch.cpp:27-29), and the sibling GPU cases in this area were all `Skipped` in the same run (tests 1277, 1300-1305, 1403-1407, 1503-1511).

**Test 1297** (`KvflashPagerRecallFixture.chunk_version_changes_only_when_its_rows_are_written`): the log shows `[kvflash] cudaMallocHost failed: CUDA driver is a stub library`, `[kvflash] no pool slot at pos 512 (pool 512 exhausted)`, then `Fail: pager recall helper precondition failed` — the `must(p.alloc_span(0, 14 * kChunk))` at server/test/unit/test_kvflash_pager_recall.cpp:133 threw. This is the only one of the four pager cases in this file missing `p.set_pinned_host_backing(false)` (compare lines 72, 79, 95, 110, all commented `CPU tensors: pageable staging, no cudaMallocHost (stub-driver CI)`); with pinned backing requested, the stub driver's cudaMallocHost failure breaks the pager's host backing and the pool cannot hand out blocks. The shared helper for exactly this exists in server/test/unit/kvflash_pager_test_host.h:24-26 (`TestPager` falls back to pageable memory).

The PR description's `test_server_unit: pass` was recorded on a GPU machine; this CI job builds with CUDA but runs on a GPU-less runner, which the new tests did not handle.

Proposed fix: Skip the fused-kernel device tests when no GPU is present, and use pageable host backing in the chunk-version pager test.
1. In `server/test/unit/test_kvflash_fused_mass.cpp`, add `if (ggml_backend_cuda_get_device_count() <= 0) SKIP("CUDA/HIP device unavailable");` as the first line of the three device TEST_CASEs (the file already includes ggml-cuda.h under `LUCE_HAVE_KVFLASH_FUSED_MASS`).
2. In `server/test/unit/test_kvflash_pager_recall.cpp`, add `p.set_pinned_host_backing(false);` to `chunk_version_changes_only_when_its_rows_are_written`, matching the other three cases in the file.
3. Rebuild and rerun `ctest -R 'KvflashFusedMass|KvflashPagerRecall'` on a GPU-less machine: the three device tests report Skipped, the pager test passes.

Suggested patch (a starting point):
```diff
diff --git a/server/test/unit/test_kvflash_fused_mass.cpp b/server/test/unit/test_kvflash_fused_mass.cpp
index f6ad879a..2e164262 100644
--- a/server/test/unit/test_kvflash_fused_mass.cpp
+++ b/server/test/unit/test_kvflash_fused_mass.cpp
@@ -217,6 +217,7 @@ double fused_gpu_worst(const FSynth & s, size_t max_partial_bytes, double floor_
 }  // namespace
 
 TEST_CASE(KvflashFusedMassFixture, device_kernel_matches_the_cpu_reference) {
+    if (ggml_backend_cuda_get_device_count() <= 0) SKIP("CUDA/HIP device unavailable");
     FSynth s;
     s.build(GGML_TYPE_Q8_0, 3, 6, 2, 64, 41, 16, 5, 9);   // G = 3, 18 planes
     int tiles = 0;
@@ -227,6 +228,7 @@ TEST_CASE(KvflashFusedMassFixture, device_kernel_matches_the_cpu_reference) {
 }
 
 TEST_CASE(KvflashFusedMassFixture, device_kernel_tiles_the_queries_without_changing_scores) {
+    if (ggml_backend_cuda_get_device_count() <= 0) SKIP("CUDA/HIP device unavailable");
     FSynth s;
     s.build(GGML_TYPE_Q8_0, 2, 24, 4, 128, 67, 64, 19, 4);   // G = 6, 48 planes, ct 64, D 128
     int t1 = 0, t2 = 0;
@@ -240,6 +242,7 @@ TEST_CASE(KvflashFusedMassFixture, device_kernel_tiles_the_queries_without_chang
 }
 
 TEST_CASE(KvflashFusedMassFixture, dp4a_impl_matches_and_wmma_impl_is_refused_off_gfx12) {
+    if (ggml_backend_cuda_get_device_count() <= 0) SKIP("CUDA/HIP device unavailable");
     FSynth s;
     s.build(GGML_TYPE_Q8_0, 3, 6, 2, 64, 41, 16, 5, 9);
     const double w = fused_gpu_worst(s, (size_t)1 << 30, 1e-8, nullptr, 1);
diff --git a/server/test/unit/test_kvflash_pager_recall.cpp b/server/test/unit/test_kvflash_pager_recall.cpp
index ea10d8bf..8b3c945e 100644
--- a/server/test/unit/test_kvflash_pager_recall.cpp
+++ b/server/test/unit/test_kvflash_pager_recall.cpp
@@ -129,6 +129,7 @@ TEST_CASE(KvflashPagerRecallFixture, slot_mask_hides_rows_above_the_decode_posit
 TEST_CASE(KvflashPagerRecallFixture, chunk_version_changes_only_when_its_rows_are_written) {
     Harness h;
     KvFlashPager p;
+    p.set_pinned_host_backing(false);  // CPU tensors: pageable staging, no cudaMallocHost (stub-driver CI)
     REQUIRE(p.attach(cfg(), h.k, h.v));
     must(p.alloc_span(0, 14 * kChunk));
     const uint64_t v2 = p.chunk_version(2), v3 = p.chunk_version(3);
```

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.

@dusterbloom
dusterbloom marked this pull request as ready for review November 12, 2026 10:49

@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 2 issues.

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: b6e92ac3ee9733dfe4ed66d6219c7cd32db42588
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_fused_mass_cuda.cu">

<violation number="1" line="341" end_line="342">
WMMA runtime detection is broader than the compile-time kernel: on gfx12x targets outside the #if list the launched kern

`kvflash_fused_run` decides to launch the WMMA kernel from `device_has_wmma()` (lines 341-342), which returns true for any device whose `gcnArchName` starts with `"gfx12"` (lines 283-288). But `partials_wmma_kernel` only has a body when the TU's device pass defines `LUCE_FUSED_WMMA`, i.e. only for `__gfx1200__`/`__gfx1201__` (lines 117-121, 131-211); otherwise the kernel launches, writes nothing to `part`, and returns success. The two conditions can disagree in a supported build shape: HIP offloading to a gfx12 arch not in the list — e.g. ROCm's `gfx12-generic` generic target (supported since ROCm 6.4 and used by upstream llama.cpp builds) or a future gfx12xx part — defines none of `__gfx1200__`/`__gfx1201__`, while the runtime arch string still matches `"gfx12"`. In that configuration the fused scorer (the default for mode 4) silently produces scores from uninitialized partials instead of failing over to the logits graph; the error path at line 342 only covers `impl == 2` off gfx12, not the auto path with a missing kernel body. Fix: gate `device_has_wmma()` (or the `wmma` decision) on the same compile-time condition, e.g. return false unless `LUCE_FUSED_WMMA` is defined, so such builds take the dp4a kernel.

Fact I could not check: whether the repo's CI or documented HIP arch lists ever use `gfx12-generic`; the tested configurations (`gfx1201;gfx1151`) are consistent today.

<suggestion>
    const bool wmma = g.impl == 2 || (g.impl == 0 &amp;&amp; device_has_wmma());
    if (wmma &amp;&amp; !device_has_wmma()) return fail("fused kernel: int8 WMMA needs gfx12");
#ifdef LUCE_FUSED_WMMA
    // the device pass compiled the WMMA kernel body for this arch
#else
    if (wmma) return fail("fused kernel: int8 WMMA not compiled for this arch");   // auto/impl=2: dp4a below on auto
#endif
</suggestion>
</violation>

</file>

<file name="server/src/qwen35/qwen35_backend.cpp">

<violation number="1" line="2860" end_line="2860">
Mode-4 q_tail captured from the discarded first pass, never refreshed by the re-run

The tail-query capture is gated on `!rw_done`. During a two-pass mode-4 turn (`rw.run`), `rw_done` is false throughout the first pass, so the last `q_keep` prompt queries are captured from the pass over `[R, end)` that runs under the *old* pool — the pass whose result the rewind discards. After `kvflash_rewind_turn` sets `rw_done = true` and the loop re-runs `[R, end)` under the reselected pool, this condition is false, so the second pass never recaptures. The stale first-pass rows are then stored into `kvflash_m4_last_.q_tail` at line 2958 and used by the next request's Prescore path (`kvflash_m4_path` -&gt; `kvflash_prefill_score`) to score chunks, so the 'exact' scores are computed with queries that do not match the context the model actually generates from (tail tokens attend the reselected history, so their queries differ whenever the reselect changed residency). The code itself establishes that these rows are stale: lines 2906-2912 explicitly recapture the uq rows after a rewind for exactly this reason ("its rows from the old pool are stale ... the second pass replaces them"), but the q_tail capture was left with the inverted gate. The condition should skip the discarded first pass (`rw_pass1`), not the second pass; note the `capture_qk` build flag at lines 2753-2755 is already enabled for the second-pass batch, so only the read-back gate is wrong. I could not check `kvflash_m4_reuse.h` to see whether a downstream guard rejects stale tails, but nothing in this file refreshes them.

<suggestion>
        if (q_keep &gt; 0 &amp;&amp; !rw_pass1 &amp;&amp; committed + q_keep &gt; kv_offset + prompt_len) {
</suggestion>
</violation>

</file>
Issue overview
  1. WMMA runtime detection is broader than the compile-time kernel: on gfx12x targets outside the #if list the launched kern · likely (server/src/common/kvflash_fused_mass_cuda.cu:341-342)

  2. Mode-4 q_tail captured from the discarded first pass, never refreshed by the re-run · likely (server/src/qwen35/qwen35_backend.cpp:2860)

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

Comment on lines +341 to +342
const bool wmma = g.impl == 2 || (g.impl == 0 && device_has_wmma());
if (wmma && !device_has_wmma()) return fail("fused kernel: int8 WMMA needs gfx12");

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.

WMMA runtime detection is broader than the compile-time kernel: on gfx12x targets outside the #if list the launched kern · likely

kvflash_fused_run decides to launch the WMMA kernel from device_has_wmma() (lines 341-342), which returns true for any device whose gcnArchName starts with "gfx12" (lines 283-288). But partials_wmma_kernel only has a body when the TU's device pass defines LUCE_FUSED_WMMA, i.e. only for __gfx1200__/__gfx1201__ (lines 117-121, 131-211); otherwise the kernel launches, writes nothing to part, and returns success. The two conditions can disagree in a supported build shape: HIP offloading to a gfx12 arch not in the list — e.g. ROCm's gfx12-generic generic target (supported since ROCm 6.4 and used by upstream llama.cpp builds) or a future gfx12xx part — defines none of __gfx1200__/__gfx1201__, while the runtime arch string still matches "gfx12". In that configuration the fused scorer (the default for mode 4) silently produces scores from uninitialized partials instead of failing over to the logits graph; the error path at line 342 only covers impl == 2 off gfx12, not the auto path with a missing kernel body. Fix: gate device_has_wmma() (or the wmma decision) on the same compile-time condition, e.g. return false unless LUCE_FUSED_WMMA is defined, so such builds take the dp4a kernel.

Fact I could not check: whether the repo's CI or documented HIP arch lists ever use gfx12-generic; the tested configurations (gfx1201;gfx1151) are consistent today.

Checked (70%): The mismatch is confirmed in the code: device_has_wmma() (kvflash_fused_mass_cuda.cu:283-292) matches any gcnArchName starting with "gfx12", while the WMMA kernel body is compiled only when gfx1200/gfx1201 is defined (lines 117-121, 131); in any other gfx12 build (gfx12-generic, or a future gfx12xx part, both reachable via the user-settable LUCE_HIP_ARCHITECTURES documented in server/docs/MIXED_BACKEND.md:25) the kernel launches, writes nothing to part, and returns success, so the default fused scorer silently returns garbage instead of failing over. Confidence is not higher because no CI or documented build uses such a target today — the repo's arch lists are all gfx1200/gfx1201/gfx1151/gfx1100 — so it is a latent gap rather than a bug in a shipped configuration.

Suggested change
const bool wmma = g.impl == 2 || (g.impl == 0 && device_has_wmma());
if (wmma && !device_has_wmma()) return fail("fused kernel: int8 WMMA needs gfx12");
const bool wmma = g.impl == 2 || (g.impl == 0 && device_has_wmma());
if (wmma && !device_has_wmma()) return fail("fused kernel: int8 WMMA needs gfx12");
#ifdef LUCE_FUSED_WMMA
// the device pass compiled the WMMA kernel body for this arch
#else
if (wmma) return fail("fused kernel: int8 WMMA not compiled for this arch"); // auto/impl=2: dp4a below on auto
#endif

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.

Confirmed. device_has_wmma() matches any gcnArchName starting with "gfx12", while the WMMA kernel body is compiled only for __gfx1200__/__gfx1201__, so a gfx12-generic or other gfx12xx build would launch an empty kernel. The suggested #ifdef LUCE_FUSED_WMMA can't go in the host function because the host pass never defines the per-arch device macros. The fix makes the gate a pure predicate on the arch string that accepts exactly gfx1200 and gfx1201 (feature suffix ignored); everything else uses dp4a, and impl=2 off those archs fails with the existing error. A CPU unit test covers gfx1200, gfx1201, gfx12-generic, gfx1250, gfx1151 and empty input. It is on a local branch and goes into this PR with its rebase after #963 merges, so CI runs once on the rebased head.

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.

Pushed as 934a9451a on this branch, now rebased on #963's a21ae4883. CPU unit suite at that head: 1395 passed / 0 failed / 22 skipped, including wmma_arch_gate_matches_the_compiled_kernel_archs. The HIP path runs in this PR's R9700 job.

Comment thread server/src/qwen35/qwen35_backend.cpp Outdated

// Every batch holding any of the last q_keep prompt tokens is captured;
// append its queries and keep the last q_keep, oldest first.
if (q_keep > 0 && !rw_done && committed + q_keep > kv_offset + prompt_len) {

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.

Mode-4 q_tail captured from the discarded first pass, never refreshed by the re-run · likely

The tail-query capture is gated on !rw_done. During a two-pass mode-4 turn (rw.run), rw_done is false throughout the first pass, so the last q_keep prompt queries are captured from the pass over [R, end) that runs under the old pool — the pass whose result the rewind discards. After kvflash_rewind_turn sets rw_done = true and the loop re-runs [R, end) under the reselected pool, this condition is false, so the second pass never recaptures. The stale first-pass rows are then stored into kvflash_m4_last_.q_tail at line 2958 and used by the next request's Prescore path (kvflash_m4_path -> kvflash_prefill_score) to score chunks, so the 'exact' scores are computed with queries that do not match the context the model actually generates from (tail tokens attend the reselected history, so their queries differ whenever the reselect changed residency). The code itself establishes that these rows are stale: lines 2906-2912 explicitly recapture the uq rows after a rewind for exactly this reason ("its rows from the old pool are stale ... the second pass replaces them"), but the q_tail capture was left with the inverted gate. The condition should skip the discarded first pass (rw_pass1), not the second pass; note the capture_qk build flag at lines 2753-2755 is already enabled for the second-pass batch, so only the read-back gate is wrong. I could not check kvflash_m4_reuse.h to see whether a downstream guard rejects stale tails, but nothing in this file refreshes them.

Checked (80%): Verified mechanically: during the mode-4 first pass rw_done is false, so the final batch of [R, end) appends its (old-pool) queries into kvflash_q_tail at qwen35_backend.cpp:2860-2868; after the rewind (2898-2914) sets rw_done=true, the second pass over the same tail tokens never recaptures, so line 2958 stores first-pass rows, and kvflash_m4_path/kvflash_prefill_score (3241-3244, 3487-3495) use them to score the next request — while the code itself recaptures the uq rows after the rewind for exactly this staleness reason (2906-2912). Confidence is not higher only because the pass-1 tail is also what the rewind's own scoring consumes, so the gate could arguably be deliberate; the resulting mismatch (queries from the discarded pass proxying a context that was reselected) and the pass-2 capture_qk being enabled at 2753-2754 with no reader for the all-rows tensor both point to an oversight._

Suggested change
if (q_keep > 0 && !rw_done && committed + q_keep > kv_offset + prompt_len) {
if (q_keep > 0 && !rw_pass1 && committed + q_keep > kv_offset + prompt_len) {

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.

Confirmed, and it is the same defect davide221 raised as item 2 on #963. It is fixed there in d13a918: the tail is captured in both passes and, after a rewind, the pass 1 rows at positions >= R are trimmed so pass 2 refills them. Pass 1's tail has to stay because the rewind scoring consumes it, so gating on the first pass alone would not be enough. This branch still has the old !rw_done code and picks up the fix when it is rebased after #963 merges.

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.

This branch is now rebased on #963's a21ae4883 (head 934a9451a), which includes d13a91857.

@dusterbloom

Copy link
Copy Markdown
Collaborator Author

Both findings from the 11-12 code review are fixed:

  1. WMMA detection broader than the compiled kernel: 934a945 takes the WMMA path only on gfx1200/gfx1201, the archs the kernel body is compiled for. Other gfx12 archs use dp4a. The check is a pure predicate (kvflash_fused_arch_has_wmma) with a CPU unit test.
  2. Mode-4 tail queries kept from the discarded first pass: fixed in feat(qwen35): prefill recall with the exact scorer on the serial path, recall profile on by default #963 by d13a918, which this PR contains. Both passes capture, and a rewind trims the tail rows at positions >= R so pass 2 refills them.

CI is green on 934a945.

…all pick and recall budget

Pure functions for the serial recall path: kvflash_reselect_mode keeps modes 0, 4 and 5 and turns
1-3 off, kvflash_last_user_turn and kvflash_mode4_plan find the cut, kvflash_recall_pick ranks
blocks by summed score (ties to the newer block, 10-chunk sink floor), kvflash_recall_plan derives
tail, window and picks, and the preamble pin helpers keep the system+tools chunks out of the
candidates. Nothing calls them yet.
…ot mask

reselect_recent() resets the pool to the sink plus the newest chunks that fit and drops the hook,
so a pick left by the previous request does not stay resident into the next scoring pass.
fill_slot_mask(dst, valid_upto) hides rows at positions above a rewind; the default keeps every
caller unchanged.
…ayer in a KVFlash process

TargetCache::q_cap_all keeps the last kQueryCaptureTokens queries of each batch for selector v2 and
the user-question queries. Only a process with a LUCE_KVFLASH pool allocates it, so nothing changes
with KVFlash off. The loader also reads the user, system, im_end and tool_response token ids the
turn cuts and the preamble pin need. LUCE_KVFLASH_UQ_QUERIES is the one env count left.
…ition

kvflash_upload_mask(cur_pos) bounds the slot mask to cur_pos + 1 and rebuilds it
whenever the pager epoch or the decode position changes, i.e. every decode step.
Rows above the position hold rejected drafts or an earlier turn's tokens. Changes
AR numerics for KVFlash decode; without a KVFlash pool nothing changes.
…e_scorer

kvflash_load_drafter() loads the residency drafter once and remembers a failed load;
kvflash_ensure_scorer() calls it. Same messages, same order, no behavior change.
…estion queries in the selector

With LUCE_KVFLASH_PREFILL_RESELECT=4 the prefill is cut at the start of the last user turn, a
first pass over that turn captures its last query, the sealed chunks are scored with the exact
attention mass (selector v2), the state is restored to the cut, the pager is reselected by the
recall plan and the turn is written again under the new pool. Mode 5 takes the drafter's scores
for the same cut in one pass. Under tensor parallelism recall stays off (kvflash_recall_features).
Modes 1-3 stay off. Without a KVFlash pool nothing changes.
LUCE_KVFLASH_PREAMBLE_ROWS=R adds pool room (R rounded up to a chunk, clamped by max-ctx) for the
pinned system+tools chunks, so the preamble does not eat the history budget, and re-applies the pins
after a reset, restore or truncate. 0 turns the pin and the extra VRAM off.
Default-on under --kvflash: selector v2 with the GPU scorer (fixed in the backend, no variable),
mode 4, six recalled blocks in 2-chunk units on the recency scoring pool, the 6144-row preamble
pin (extra pool VRAM) and 64 user-question queries. The values are named constants in
KvflashRecallProfile and are installed as env defaults. A variable already set keeps its value.
Other architectures and launches without --kvflash install nothing.
…not 6144

The reserve grows the resident pool and every decode step attends the whole pool. 6144 rows took the pool from 16384 to 22528 and cost 4.7% decode; 1152 (18 chunks of 64) holds the measured 1064-token preamble pin and grows it by 7%.
…he pool no longer grows

The reserve took the pool from 16384 to 17664 rows and every decode step attends the whole pool, so the profile silently raised the decode cost the user chose with --kvflash. The reserve (1152 rows) is now held inside N, leaving N - 1152 history rows. A reserve that leaves no history row (>= N) turns the pin off with a log line, like a missing <|im_start|> id.
…evice KV (16 layers, 4 kv heads, hd256, q8_0)
…and not written since (dirty flag, d2h_skipped stat)
…unzeroed; a recall overwrites it, a fresh chunk zeroes it on handout, reselect flushes the rest
…ce at the end, not per hand-out, with residency unchanged (red: KvFlashStats has no fence_points yet)
reselect() recalls its page-ins as one batch on the page stream and waits
once at the end; on HIP every hand-out was a host wait (one per page-in,
~0.7 ms/event over 191k events in the K3 night). Residency and bytes
unchanged. The recent-pool and pick lines log the paging time on their own
line.
Review findings #2-#7, #11, #15 of the G2 landing review.

- Eviction hook: chunks at or past the committed position rank as pinned,
  so a drafter ledger that covers the whole prompt cannot evict the
  batch being allocated (RECALL_BLOCKS=0 lost 3 of 8 chunks).
- Recall gate (kvflash_recall_gate): mode 4 and 5 skip when no sealed
  chunk precedes the turn, when chunks(R) + the turn's reserve already
  fit the pool (the turn was counted twice), and when the pool cannot
  hold pins + recall + reserve; those requests run as a recency pool.
- GPU scorer: a request with nothing sealed or a free-VRAM refusal no
  longer latches kvflash_gpu_failed_ for the process.
- Victim tier defaults to 2x the pool in mode 5 only, and the auto pool
  budget accounts for its device bytes.
- Profile no longer exports PFLASH_SELECT_QUERY_PARSER (it changed PFlash
  compression's query), the retired PFLASH_SELECT_PARAGRAPH_JOIN or the
  unread LUCE_KVFLASH_SELECT_QUERIES; the mode-5 gate drops the parser.
- Docs: --prefill-drafter, RECALL_BLOCKS=0 wording, victim tier row.

Tests: test_kvflash_prefill_reselect (hook, gate, latch, victim),
test_launch_policy, test_kvflash_pflash_map.
Review findings #9 and #10 of the G2 landing review.

- victim_fifo_ gained an entry per page-out and was popped only when the
  free list ran empty; a freed slot is handed out again, so dead entries
  looked live. 2000 page-out/row-write cycles left 2000 entries; now the
  queue is swept (newest entry per chunk kept) past twice the tier.
- kvflash_pooled_ubatch clamps to the unpinned capacity: with 1152 rows
  pinned in a 2048 pool, LUCE_PREFILL_UBATCH=1024 no longer puts a
  16-chunk batch into 14 free blocks.

Tests: test_kvflash_pager_victim_tier (fifo growth), test_kvflash_ubatch.
Defect: q_cap_all is allocated in every KVFlash process, and the graph
copied into it whenever in.q_capture was set. The qk policy keeps capture_qk
on for decode and restore steps, so every decode step copied Q into a tensor
nothing reads there. Under tensor parallelism that tensor has no split
(qwen35_tensor_parallel.cpp classifies only q_cap) while the Q it copies from
is split by head; the view-of-view copy into q_cap_all is expected to trip
the split_dim_view_src assert in ggml-backend-meta.cpp on the first decode
(derived from reading, not run on hardware).

Fix: separate graph input QwenGraphInputs::q_capture_all, set from the pure
kvflash_capture_q_all(recall_on, uq_on, tp_degree, capture_qk). Only the
prefill windows that feed kvflash_read_captured_queries (recall mode 4 tail,
UQ window) pass it; decode and restore steps and every other caller keep the
default false. The rewind-only capture (rw_capture) reads q_cap, so it does
not set it. TP zeroes recall and UQ in the feature plan, so it never writes.

Tests: test_kvflash_exact_mass.cpp q_cap_all_is_written_only_for_recall_or_uq_prefill.
Red: helper missing (compile failure, red-item1-compile.log); green: 1378
passed, 0 failed.
…he startup line

Defect: --help still said --kvflash-policy defaults to drafter, but the
recall profile makes it qk on qwen35 with --kvflash. The startup line chose
"mode 4" from kvflash_mode5_requested() alone, while apply_env_defaults keeps
an already-set LUCE_KVFLASH_PREFILL_RESELECT, so the line could say mode 4
while 0, 4 or 5 (without its GGUFs) ran; on other architectures the profile
is not applied at all but the line still said mode 4.

Fix: kvflash_recall_banner(arch, mode5, get) prints the resolved mode (the
operator's env value when set, else the profile's), says when the
environment set it, and says the profile is not applied off qwen35. Help
text states the real default.

Tests: test_launch_policy.cpp test_kvflash_banner_prints_the_resolved_reselect_mode
(test_feature_gate target). Red: helper missing (compile failure,
red-item4b-compile.log); green: test_feature_gate 5 passed, 0 failed
(green-item4-gate.log).
Defect: kvflash_read_captured_queries copied the whole q_cap_all tensor
(64 rows x every plane, about 24 MiB on the 27B) with one
ggml_backend_tensor_get per captured batch, then used only n_q rows per
plane. The tensor is [hd, T, n_head, n_fa]: the n_q rows of one plane are
contiguous but planes are T*hd floats apart, so a plain prefix read is not
enough.

Fix: one ggml_backend_tensor_get_2d reading n_q*hd floats from each plane
(kvflash_q_cap_all_read gives the arguments), then kvflash_regroup_queries
turns [plane][n_q][hd] into the scorer's [t][plane][hd]. Output is identical
to the old loop; bytes read drop from planes*T*hd*4 to planes*n_q*hd*4.

Tests: test_kvflash_exact_mass.cpp
captured_queries_are_read_as_n_q_rows_per_plane_and_regrouped (n_q 1, 5, 64;
element-wise against the tensor, byte count asserted). Red: helpers missing
(compile failure, red-item4c-compile.log); green: 1379 passed, 0 failed.
The real tensor_get_2d path was not run on a GPU.
…ayed

Mode-4 recall rewinds to R, the start of the last user turn, and skipped the
recall when nothing was sealed before R (a cold single turn starts its user
turn in chunk 0) or when the turn was longer than the pool can replay
(PoolTooSmall). That turn then ran LRU only, and a fact the pool dropped was
gone at decode: one cold 81,430-token turn, pool 16384, answered key_123 wrong.

kvflash_max_turn_tokens is the longest turn the recall gate replays (its
PoolTooSmall bound). kvflash_mode4_plan takes it as an optional cap and
rewinds a longer turn to that tail, so the recall scores and pages in
everything before it. The serial call site (kvflash_recall_setup) passes the
cap; the gate is unchanged and a turn within the cap keeps its R.

A capped R that lands inside the question window (LUCE_KVFLASH_UQ_QUERIES) moves
to the window end (kvflash_uq_snap_rewind): a replay from inside it would leave
the stored question rows from the old pool.

Tests: test_kvflash_prefill_reselect, the cap equals the gate's bound and the
capped plan on the needle's shape rewinds to the tail; test_kvflash_uq, the snap.
Mode 5 (the PFlash drafter's scores as the recall scorer) is dropped; mode 4 is the only recall mode.
kvflash_reselect_mode returns 4 or 0, the mode-5 branches of the recall setup and the drafter scorer
glue in the Qwen35 backend are gone, and so is the device victim tier that only mode 5 used
(kvflash_victim_blocks_default, kvflash_pool_density_factor and their test). The ENVIRONMENT.md rows
and the pflash-map gate are back to the mode-4 text.
/props gains kvflash {enabled, pool_tokens, mode}. server_main fills it after the --kvflash, --kvflash-policy
and --kvflash-tau flags have set the environment the backend reads, so env-only KVFlash counts too.
pool_tokens is LUCE_KVFLASH (0 means auto, sized at load). mode is the backend's own kvflash_reselect_mode
over LUCE_KVFLASH_PREFILL_RESELECT, LUCE_KVFLASH_POLICY and LUCE_KVFLASH_RESELECT_SCORER:
"prefill-reselect=4" while recall runs, empty on another architecture, with --kvflash-policy lru or with a
scorer other than exact.
test_server_unit.cpp: main's Luce-Org#1031 pruned the model-card props tests next to the three /props.kvflash tests;
take main's version and keep the three tests.
…a device archive, keyed by pager chunk versions

Every exact-scorer call uploaded the K rows of every evicted sealed chunk
(1.06 MiB per chunk at q8_0, 1.39 GiB at 1342 evicted chunks) and freed them
on return. KvFlashPager::chunk_version(c) changes whenever chunk c's rows may
have changed and stays while the chunk only moves between the pool and its
host copy. KvFlashGpuMass::score(..., versions) keeps what it uploads in one
archive tensor per layer and uploads only chunks evicted since the last call;
a slot is scored only while its chunk has the version it was uploaded with.
Without versions the scorer is call-scoped as before; the backend does not
pass them yet.
…chunk local max and sum-exp, rescaled reduce) with the 217K roofline; matches the exact scorer to 3e-7 on mean and plane masses
… q int8 dp4a, per-chunk partials, rescaled reduce, query tiles) with a CPU reference of the MMQ numerics; device matches it to 1.4e-6
…(compile-time D and chunk tokens, online max/sum-exp); 3090 kernel 140 ms per 217K call extrapolated, was local-memory bound
… (d_inv = 127 / amax, float block scale, no fp16 rounding); device scores now match the logits graph to 4.4e-7
…okens per wave, MMQ scale order kept); gfx1201 kernel 302 ms -> 82 ms at 3382 chunks, dp4a stays for CUDA and as impl=1
…mass kernel over the pool K and the device archive

KvFlashGpuMass::score runs kvflash_fused_run on the pool tensors and the
archive where they are: each sealed chunk is read from its pool block or its
archive slot, so a call costs the chunks it scores, not the slots held. The
backend passes the pager's chunk versions (which keep the archive between
calls) only when the kernel can score the K: q8_0, head dim a multiple of 32
and at most 256. Any other K, a kernel failure, or
LUCE_KVFLASH_GPU_SCORE_FUSED=0 scores with the logits graph, call-scoped, as
before: the graph spans every archive slot, so it never gets the archive.
The scorer log line gains 'uploaded=U of E evicted (H held) fused=0|1'.
…nk-version test uses pageable staging, so check-cpu passes on the stub-driver runner
…1, not any gfx12*

The WMMA kernel body is compiled only for __gfx1200__/__gfx1201__; the runtime check matched any gfx12 prefix, so a gfx12-generic or other gfx12xx build launched an empty kernel and read uninitialized partials. The check is now a pure predicate (kvflash_fused_arch_has_wmma) with a CPU unit test; other gfx12 archs use dp4a.
… logits-graph fallback does not abort on it

ck() returned false on a CUDA error but left it set in the runtime. score() then falls back to the logits graph, and the first ggml-cuda launch check (cudaGetLastError) read the old error and aborted: a failed partials cudaMalloc under tight VRAM killed the process instead of costing one fused call. ck() now calls cudaGetLastError() on failure. Device test device_failed_run_leaves_no_cuda_error_behind: a run whose query buffer cannot be allocated fails, and the next run on the same thread passes its launch checks (skips without a GPU).

(cherry picked from commit 4f521dbded4c8f3dcf566670d7f702ac82030450)
…he scorer, so it is not retried on every call

score() only warned once, and qwen35_backend calls set_fused(true) before every call, so a kernel that could not run was tried (and its buffers allocated) on each reselect. The on/off state is now a pure KvFlashFusedLatch: fail() wins over any later set(true). The backend reads fused() back after set_fused(), so after a failure it stops passing chunk versions and the device archive, which only the kernel can use, is dropped on the next call. CPU test fused_latch_stays_off_after_the_first_failure.

(cherry picked from commit 1e5ddc75fca1919215c3f732da7e80f0450c60fb)
…tead of holding it until backend teardown

The archive (about 1 MiB per evicted 64-token chunk on the 27B, near 2 GiB after a 131K chat through a 16K pool) was freed only when the backend went away. After KvFlashPager::reset() every slot is stale, since chunk versions only grow, so the bytes were held for nothing until the next conversation evicted enough to trigger a rebuild. The three reset sites in qwen35_backend.cpp now go through kvflash_reset_pager(), which also calls KvFlashGpuMass::drop_archive(). CPU test drop_archive_frees_the_device_copy_and_the_next_call_starts_over.

(cherry picked from commit 08b1f077b39d621d8a1a75bc862d21e0031aafb3)
…ures, and a device case covers D=256 ct=64

No GPU job's ctest filter matched KvflashFusedMassFixture or KvflashGpuMassFixture, so their device tests ran only by hand: the CUDA job gets a step for both, the ROCm filter gets both names. The device cases used head dim 64 and 128; device_kernel_matches_the_cpu_reference_at_d256_ct64 adds the 27B shape (8 blocks per row, 64-token chunks, 24 q heads over 4 kv heads), one tile and several (skips without a GPU).

(cherry picked from commit 6ad8bdff9521a4ce60cdb95c4a445884a9062264)
… archive, since deserialize() resets the pager inside

kvflash_restore_pooled replaces every chunk through KvFlashPager::deserialize(), the one pager reset that did not go
through kvflash_reset_pager(). No score was wrong (restored chunks get new versions), but the old archive stayed on the
device until the next scoring call or cold prefill. Dropped right after the call, on success and on failure: a refused
header leaves the pager as it was, and dropping then only costs a re-upload.

(cherry picked from commit 777ea642b822865e6fc8a1587083ab0187008d0b)
@dusterbloom
dusterbloom force-pushed the kvflash/g2b-fused-scorer branch from 934a945 to 643e03c Compare November 19, 2026 15:16
@dusterbloom

Copy link
Copy Markdown
Collaborator Author

Thanks, all four are real. Each is fixed by its own commit on the branch:

  1. ck() leaves the error set. Fixed in 0fa2db2: when the call failed, ck() now calls cudaGetLastError(), so the logits-graph fallback starts clean. Test: KvflashFusedMassFixture.device_failed_run_leaves_no_cuda_error_behind. A run whose query buffer cannot be allocated fails, and then a normal run on the same thread must pass its launch checks.
  2. The fused path is retried on every call. Fixed in eb8df07: the first failed run latches the kernel off for the scorer (KvFlashFusedLatch), and set_fused(true) no longer turns it back on. The backend reads fused() back, so it also stops passing the chunk versions. The archive, which only the kernel uses, is dropped on the next call. Test (CPU): KvflashFusedMassFixture.fused_latch_stays_off_after_the_first_failure.
  3. The archive is held until teardown. Fixed in 3503fa2 and 643e03c. qwen35_backend.cpp resets the pager in four places:
    • The three explicit resets (two in do_prefill, one in kvflash_sync_prefill) go through kvflash_reset_pager(), which also frees the device archive with KvFlashGpuMass::drop_archive() (3503fa2).
    • The fourth is kvflash_restore_pooled: KvFlashPager::deserialize() resets the pager inside, so the restore now drops the archive right after that call, whether the call succeeds or fails (643e03c). Before this, that path gave no wrong score, because restored chunks get new versions, but the old archive stayed on the device until the next scoring call or cold prefill.
    • Test (CPU): KvflashGpuMassFixture.drop_archive_frees_the_device_copy_and_the_next_call_starts_over covers the drop itself. The restore call has no host test, since it needs a loaded model and a pooled snapshot.
  4. No GPU job ran the fixtures, and there was no D=256 device case. Fixed in ed10245:
    • the CUDA job has a new step, -R '^test_server_unit\.(KvflashFusedMassFixture|KvflashGpuMassFixture)\.';
    • the ROCm filter names both fixtures;
    • device_kernel_matches_the_cpu_reference_at_d256_ct64 covers the 27B shape (D=256, ct=64, 24 q heads over 4 kv heads), with one query tile and with several.

Run on an R9700 (gfx1201) + Strix Halo (gfx1151) box, with a HIP build of this head (643e03c):

  • Unit tests. All 380 tests matching [Kk]vflash|[Ll]aunch|[Pp]rops|[Ff]eature.?[Gg]ate|[Ss]pec|[Dd]raft|[Rr]ollback pass on gfx1201 and on gfx1151. The two new device tests pass on both GPUs, and neither skips:
    • device_kernel_matches_the_cpu_reference_at_d256_ct64: the worst error against the CPU reference is 9.5e-7 on gfx1201 and 1.0e-6 on gfx1151, with 1 and with 3 query tiles;
    • device_failed_run_leaves_no_cuda_error_behind passes.
  • Engine run. Mode-4 replay of 3 recorded agent sessions (165 requests), Qwen3.8-27B UD-IQ4_XS on the R9700, --kvflash 16384, temp 0:

The CUDA side of the device tests runs in the new CI step on this push. On my machine I only have the CPU stub driver: there, 269/269 [Kk]vflash tests pass and the device cases skip. The ROCm jobs are still waiting for their runner.

The branch is now restacked as linear commits on #963's head 2a01709b0 instead of merges. The five fixes are its last five commits, appended after the restacked PR commits, which are unchanged.

… the WMMA kernel from the loaded code

- With the QK policy a dense prefill (prompt fits the pool) called kvflash_qk_pool_to after every batch,
  before the pager has a mapping: one 'pool_chunk failed (block -1)' line per 64-token chunk on every
  request (130 lines for three chats of 6.4K, 95 and 2.3K tokens). kvflash_sync_prefill pools every chunk
  at the end, so only the pooled prefill pools per batch now. Answers are unchanged.
- device_has_wmma() also asks the loaded code object whether partials_wmma_kernel has its body. The arch
  name alone does not say: a gfx12-generic build on a gfx1201 card would launch an empty kernel without
  an error. Such a build now runs the dp4a kernel.
- Drop two members nothing uses (spec_early_stop_repairs_, kvflash_q_cap_from_stage).

lucebox8, R9700 + Strix Halo: unit suite 1239/1239 on both; same text as before on 4 prompts with and
without --kvflash; 89.6K-token chat with 8 hidden codes at --kvflash 16384: 8/8, scorer 16.8 ms, fused=1.

Co-Authored-By: Claude Fable 5.2 <[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