Repository navigation
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
Conversation
CI failed on
|
davide221
left a comment
There was a problem hiding this comment.
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 && 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
</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` -> `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 > 0 && !rw_pass1 && committed + q_keep > kv_offset + prompt_len) {
</suggestion>
</violation>
</file>
Issue overview
-
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) -
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
| 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"); |
There was a problem hiding this comment.
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.
| 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 |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
|
|
||
| // 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) { |
There was a problem hiding this comment.
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._
| 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) { |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
This branch is now rebased on #963's a21ae4883 (head 934a9451a), which includes d13a91857.
b6e92ac to
934a945
Compare
|
Both findings from the 11-12 code review are fixed:
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)
…per (layer, K/V) instead of one per kv head
…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.
…r refuses on free VRAM
… 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)
934a945 to
643e03c
Compare
|
Thanks, all four are real. Each is fixed by its own commit on the branch:
Run on an R9700 (gfx1201) + Strix Halo (gfx1151) box, with a HIP build of this head (643e03c):
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 The branch is now restacked as linear commits on #963's head |
… 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]>
Stacked on #963. Base:
kvflash/prefill-recallat2a01709b0(#963's head: the lean #963 with main1d949fd88merged). Review range: 2a01709..643e03c, 15 commits, 14 files, +1639 / -42. Restacked 2026-11-19 from934a9451a: its 9 commits plus43fe79c39(the fused scorer workspace is released before the GPU scorer refuses on free VRAM) replay onto the lean #963 with one conflict, inkvflash_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 on50020e4c5(the head G2's gate ran on).4be2caad4is that tree plus #963's last three commits (2a6e64c53,9fc7a36a4,d98512ff0):git diff aec6a3e5c 4be2caad4is 3 files, +9 / -3 (ENVIRONMENT.md, a comment inkvflash_query_capture.h, one unit-test fixture). No compiled server code differs. Build andtest_server_uniton4be2caad4: 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
[D, cap * chunk_tokens, heads]. Slots are keyed byKvFlashPager::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).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.hholds a CPU reference of the same numerics; the unit tests compare device, reference and the logits-graph scorer.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 withLUCE_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
--kvflashoff none of this code runs.Which device gets the fused path with the default q8_0 K:
fused=1, 0fused scorer unavailablelinesAny 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
d1f6c8ce952701ab4f8453eeb4c0389b2444a47087d922e74c75a0767dbc7344736fa393c2046490543fe79c390fa2db286eb8df077b3503fa2e2ed10245dc643e03c09Each of the 15 commits builds alone with every target (CUDA sm_86 build,
luce_server,test_server_unit,test_model_smokeand 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;gfx1201of #963's head2a01709b0(base, md5 dfd56422) and of643e03c09(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.Prompt and cached tokens are equal on every request. The fused kernel scored all 48 scorer calls (
fused=1), with nofused scorer unavailableline. The same replay on43fe79c39(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_ct64anddevice_failed_run_leaves_no_cuda_error_behindrun and pass on both GPUs (nono CUDA/HIP deviceskip).Tests (earlier form)
Head
aec6a3e5c.test_server_unit <group>.KvflashFusedMassKvflashGpuMass(20 cases)KvflashPagerRecalltest_server_unitTMPDIR)TMPDIR)On lucebox6 the first full run with the shared
/tmpfailed 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_*.gguffiles owned by another user that the suite could not open for writing. WithTMPDIRset 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_servermd5 4346a634 built from7cd7b260eon 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.FUSED=0)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 fromaec6a3e5c;libggml-hip.so.0md5 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 scriptm4cost_arm.sh(md5 4b1e2b8b) and were judged bym4cost_eval.py gate, both unchanged, with the bars fixed before the run. There is nom4cost_gate.shfile; 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 inLUCE_KVFLASH_POLICY=lruon K1; arm identity is read from the server logs (K1policy=lru, M4recall profile: mode 4andpolicy=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 > 0on 881 of 882 requests in both. No power limit set or recorded.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, allfused=1, 16.1 s total (h2d 8.3 s, kernel 4.7 s in the log fieldgraph), 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:FUSED=0(logits graph)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 > 0on 150 vs 151 of 151). The speed claim rests on the gate table; this arm is for the pick identity.Limits
Not run:
FUSED=0control arm exercises the logits graph on q8_0.ctest; the suite run istest_server_unit.