Repository navigation
feat(kvflash): exact attention-mass chunk scorers on CPU and GPU, user-question query helpers, mode 5 drafter scorer - #934
Conversation
There was a problem hiding this comment.
2 issues found across 19 files
Prompt for AI agents (unresolved issues)
Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="server/src/common/fnv.h">
<violation number="1" location="server/src/common/fnv.h:9">
P2: `kFnvBasis` is missing the final `7`, so this helper does not implement the documented standard FNV-1a seed. Use `14695981039346656037ULL` to keep question-id hashes compatible with the repository’s other FNV-1a implementations.</violation>
</file>
<file name="server/src/common/kvflash_pool_flag.h">
<violation number="1" location="server/src/common/kvflash_pool_flag.h:12">
P2: `std::atoi` accepts malformed positive prefixes, so `--kvflash 4096junk` or `LUCE_KVFLASH=4096junk` silently enables a 4096-token pool instead of rejecting invalid configuration. Parse the complete string and require full consumption, for example with `std::from_chars` and `parsed.ptr == end`.</violation>
</file>
Reply with feedback, questions, or to request a fix.
View guided diff | Re-trigger cubic
|
|
||
| namespace luce::common { | ||
|
|
||
| constexpr uint64_t kFnvBasis = 1469598103934665603ULL; |
There was a problem hiding this comment.
P2: kFnvBasis is missing the final 7, so this helper does not implement the documented standard FNV-1a seed. Use 14695981039346656037ULL to keep question-id hashes compatible with the repository’s other FNV-1a implementations.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At server/src/common/fnv.h, line 9:
<comment>`kFnvBasis` is missing the final `7`, so this helper does not implement the documented standard FNV-1a seed. Use `14695981039346656037ULL` to keep question-id hashes compatible with the repository’s other FNV-1a implementations.</comment>
<file context>
@@ -0,0 +1,19 @@
+
+namespace luce::common {
+
+constexpr uint64_t kFnvBasis = 1469598103934665603ULL;
+constexpr uint64_t kFnvPrime = 1099511628211ULL;
+
</file context>
| constexpr uint64_t kFnvBasis = 1469598103934665603ULL; | |
| constexpr uint64_t kFnvBasis = 14695981039346656037ULL; |
There was a problem hiding this comment.
Kept as is. 1469598103934665603ULL is the constant main already uses in six places, including the inline copy at kvflash_pager.h:596 that fnv.h replaces. In this PR it feeds only in-memory question-id keys (and, with #932, the pager's ledger hash in a log line). Neither is compared with the cluster fnv1a64 (cluster_protocol.h uses 0xcbf29ce484222325) or written anywhere another FNV-1a reads, so the hashes do not need to match. This file is byte-identical to the one in #932 and kept for parity with main. Correcting all six copies is a separate change.
| // "auto" is a real request even though its final size is not known until the backend measures VRAM. | ||
| inline bool kvflash_pool_requested(const char * value) { | ||
| return value != nullptr && | ||
| (std::strcmp(value, "auto") == 0 || std::atoi(value) > 0); |
There was a problem hiding this comment.
P2: std::atoi accepts malformed positive prefixes, so --kvflash 4096junk or LUCE_KVFLASH=4096junk silently enables a 4096-token pool instead of rejecting invalid configuration. Parse the complete string and require full consumption, for example with std::from_chars and parsed.ptr == end.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At server/src/common/kvflash_pool_flag.h, line 12:
<comment>`std::atoi` accepts malformed positive prefixes, so `--kvflash 4096junk` or `LUCE_KVFLASH=4096junk` silently enables a 4096-token pool instead of rejecting invalid configuration. Parse the complete string and require full consumption, for example with `std::from_chars` and `parsed.ptr == end`.</comment>
<file context>
@@ -0,0 +1,15 @@
+// "auto" is a real request even though its final size is not known until the backend measures VRAM.
+inline bool kvflash_pool_requested(const char * value) {
+ return value != nullptr &&
+ (std::strcmp(value, "auto") == 0 || std::atoi(value) > 0);
+}
+
</file context>
There was a problem hiding this comment.
Kept as is. kvflash_pool_requested moved out of kvflash_pager.h unchanged, so the atoi parsing is main's. Changing how --kvflash / LUCE_KVFLASH are parsed is out of scope for this PR.
davide221
left a comment
There was a problem hiding this comment.
Code review
No issues found. Checked for bugs and logic errors in the changed code.
Reviewed ca6b23ae · 1 candidate issue checked, kept at ≥70% confidence · add the code-review label to review again
…PU, with the user-question query helpers; the plain reference scorer is the test oracle
… chunk scores; off by default, no accuracy study yet
…pagate, mode 5 parses its session count - run_workers: n <= 0 runs nothing; a worker exception is captured, every thread is joined, the first is rethrown - gpu mass scorer: an empty host_seg with evicted chunks is refused with a reason - fast exact scorer: non-divisible GQA and non-positive layer/head dims are refused instead of dropping query heads - mode 5 query end is the last message's own span end (0 for an empty final message, which the drafter scorer refuses) - kvflash_uq_put honours max == 0 - mode 5 gate parses PFLASH_DRAFTER_SESSIONS whole (from_chars) and refuses malformed or overflowing values - ExactTiming comment says ns, the unit stored - tests: gpu parity now checks max_rel (2e-2, 1.3e-2 measured); the reference scorer refuses null queries and bad dims like the fast one; the exact-tie test also asserts the newest-first stable-sort tie-break on block scores (no ranking helper ships in this PR, so the contract is asserted directly)
5142331 to
9e4d9a4
Compare
…ite keys fail, spawn failure joins (#990) * fix(kvflash): graph scorer docs state the real tolerance; non-finite mass fails The header claimed the same outputs as the AVX2 scorer. ggml_mul_mat quantises queries to 8 bits for Q4_0/Q8_0 keys, so the select score deviates by up to 4e-2 at 400 sealed chunks and top-k sets can differ. Document that, add a 400-chunk bound test and an F32 exactness test, and make a NaN or Inf plane sum fail the call instead of reaching nth_element. * fix(kvflash): run_workers joins started threads when a spawn fails; CPU scorer rejects NaN A failed thread creation destroyed joinable threads and called std::terminate. The CPU scorer returned true with NaN scores for every chunk when one key value was NaN or Inf. Also drop the unused tol parameter and a stale section header in the exact-mass test. * fix(kvflash): pflash2 scorer guards on its real 128-token lookahead score_chunks guarded S against the legacy 8-token kLookahead while passing n_lookahead=128 to the drafter; a named constant now feeds both. Review: #963 thread T8
Why
A KVFlash recall step has to rank evicted chunks by how much attention a question would give them. Main has no scorer for that quantity: its selectors rank chunks by recency or by a pooled-key proxy or by the residency drafter, and none of them computes the softmax mass a chunk receives from the question's queries. A caller that wants recall before write (the PR that follows) has nothing to call.
This PR adds the scorers and the helpers around them. It has no caller: with KVFlash off, with KVFlash on, and with any recall setting, no code path in this PR runs, so there is nothing to reproduce on main. The tests below are red on main because the headers they include do not exist there.
What it does
All paths are under
server/src/unless a test is named.common/kvflash_exact_mass.h. The quantity and the types. For one query, the softmax mass each sealed chunk receives over all sealed chunks, averaged over the full-attention layers and query heads:score[c] = mean over (layer, head) of exp(lse_c - Z), withlse_cthe log-sum-exp of the chunk's scores andZthe log-sum-exp over chunks.KvFlashMassPlanesalso carries the mean of the 8 largest plane masses and the largest one. The plain reference scorer lives intest/unit/kvflash_mass_synth.hand is the oracle for the other two.common/kvflash_exact_fast.h. The AVX2 CPU scorer, one or many queries, on any K type ggml has ato_floatfor (f32, f16, q8_0, q4_0 and so on). It usescommon/parallel_for.h.common/kvflash_gpu_mass.h. The same outputs on the target backend, built from stock ggml ops only (noggml-cuda.h), so it runs on CUDA, HIP, Vulkan and, in the unit test, the ggml CPU backend. Resident chunks are read in place from the pool tensors; evicted chunks are gathered from their host copies into one pinned staging buffer and uploaded once per call. Queries are scored in balanced batches under a byte budget. Device memory is call-scoped. The call refuses (returns false) when the working set exceeds the device's free memory minus a margin, because WSL spills over-committed VRAM into system RAM without an error.common/kvflash_uq.h,common/kvflash_query_capture.h. Pure helpers for using the latest human question as extra selector queries: the human-turn span (the last user turn that is not a tool result), the capture plan, the per-session store with its key, and the gate that needs every chat token id.kQueryCaptureTokensis 64.common/kvflash_block_scores.h. Per-block sums of chunk scores.common/kvflash_pflash_map.h,pflash/kvflash_drafter_scorer.{h,cpp}. Mode 5:KvFlashPFlash2Scorerruns the PFlash request path as a recall scorer and maps the segment densities to chunk scores by the largest density of the segments that overlap a chunk. It is off unless selected and has no accuracy study.KvFlashDrafterScorer's id folding moves into a helper with the same behaviour.common/kvflash_pool_flag.h.kvflash_pool_requestedmoves out ofkvflash_pager.hso the query-capture header can use it without the pager's ggml include. The function is unchanged.common/fnv.hholds the FNV-1a helpers; it is byte-identical to the file in the pager-slices PR.Merge order: this branch is cut from main c5179e4 and does not need #932. Both touch the include block of
kvflash_pager.hand the merge has one conflict there (this PR's#include "kvflash_pool_flag.h"next to #932's#include "fnv.h"); keeping both lines resolves it.fnv.his added by both with the same content.Tests
test_server_unitgains 62 cases in four files:KvflashExactMassFixture20 (match against the reference on f32, f16, q4_0 and other types and GQA shapes, absent chunks, multi-query equals single, exact ties keep the newer chunk, plane aggregates),KvflashGpuMassFixture12 (mixed residency, all resident, all evicted, fewer than 64 queries, masked free and beyond-sealed blocks, reuse and growth, bad inputs, batch plan and batched equals one batch, parity with the CPU scorer),KvflashUqFixture14 andKvflashPflashMapFixture16. Eight of the 62 come from the review round (5142331):run_workerswith n <= 0 and with a throwing worker, GQA dimensions that would drop query heads, a null query on both scorers,max == 0in the question store, a malformedPFLASH_DRAFTER_SESSIONS, and an empty final message. The two bench cases inKvflashExactMassFixturereturn at once unlessLUCE_EXACT_BENCHis set, so they pass without measuring.Written red first: each of the four test files was compiled against main c5179e4 and stops at
fatal error: kvflash_pflash_map.h: No such file or directory(and the same forkvflash_exact_mass.handkvflash_exact_fast.h), because the headers are new. That is a compile error as the red, since there is no behaviour on main to fail.test_server_unit, passed / failed / skipped, main c5179e4 vs branch 5142331. There is no separate target; the four files are in thetest_server_unitsource list. Each of the three commits builds alone on CUDA.The GPU was idle before each CUDA run and one suite ran at a time. Each HIP log names its device (
gfx1201on hip:0,gfx1151on hip:1).Engine run
The engine does not call anything in this PR, so this run shows only that the serial
--kvflashpath is unchanged. Qwen3.8-27B (Qwen3.8-27B-UD-IQ4_XS.gguf, md5 54db94b16b77e3fe024faa893cc4b80d),luce_server <model> --max-ctx 65536 --kvflash 16384 --no-kv-cache --cache-type-k q8_0 --cache-type-v q8_0, two distinct prompts of 34583 and 37293 tokens, 128 max tokens, temperature 0, seed 1, HIP only. The pool pages out on every arm (pooled prefill: 34583 tokens through a 16384-token pool, and the same for 37293). One server at a time, caches dropped before each arm, arms in the order main, branch, main repeat on each GPU.luce_servermd5: main e01ec7db3b155947fc93c00f2acb4a07, branch 15876f7707214e852c43a1483df2a243. Every request showsprefix_len=0anddisk_hit=falseon all six arms. The prompts were answered in 61 and 61 tokens on gfx1201 and 61 and 63 on gfx1151 (finish=stop), the same on every arm of a GPU.With two requests, median equals mean, and best and min are the two requests (for wall, best is the fastest). Speeds are from the server's
chat DONElines; prefill time is printed in steps of 0.1 s.gfx1201 (hip:0):
gfx1151 (hip:1):
Branch against the first main run, medians: on gfx1201 prefill -0.72%, decode -0.34%, wall +0.69%; main against its own repeat is -1.78%, -0.68% and +1.76%. On gfx1151 prefill -0.53%, decode 0.0%, wall +0.52%; main against its own repeat is -0.32%, 0.0% and +0.31%. The branch sits inside the spread of main against itself on both GPUs. This PR makes no speed claim.
The tables above are for ca6b23a. The review fix 5142331 was run again with the same harness, main (same binary) then branch on each GPU, with no main repeat. Branch
luce_servermd5 1c904937801c744c586cdbac76c5e228. Text is identical to main on both requests on both GPUs.prefix_len=0anddisk_hit=falseon all four arms, and every arm logspooled prefillfor both prompts. Branch vs main, medians: gfx1201 prefill 865.67 vs 867.78 tok/s (-0.24%), decode 29.35 vs 29.35 (0.0%), wall 43.72 vs 43.66 s (+0.14%); gfx1151 prefill 290.89 vs 291.05 (-0.05%), decode 12.90 vs 12.90 (0.0%), wall 128.45 vs 128.41 s (+0.03%).The server has no logprobs, so near-tie margins between the two builds' token choices cannot be computed; text identity is the comparison.
Limits
--kvflash. There is no CUDA engine run. The unit tests run the GPU scorer on the ggml CPU backend only (ggml_backend_cpu_init), so the device path ofkvflash_gpu_mass.hon CUDA and HIP is built here but not run by any test or by the engine.KvFlashPFlash2Scorer) is off unless selected and has no accuracy study. Its tests cover the density-to-chunk mapping, the message map and the gate, not recall quality.kvflash_pager.h(see above).