Skip to content

feat(server): /props.kvflash advertises the recall capability (stacked on #963) - #999

Closed
dusterbloom wants to merge 48 commits into
Luce-Org:mainfrom
dusterbloom:kvflash/g2c-props
Closed

dusterbloom wants to merge 48 commits into
Luce-Org:mainfrom
dusterbloom:kvflash/g2c-props

Conversation

@dusterbloom

@dusterbloom dusterbloom commented Nov 12, 2026 •

Copy link
Copy Markdown
Collaborator

Draft. Sibling of #963 (G2, KVFlash 2.0 prefill recall), opened after #963 gates; not a stack member. Review only d98512ff0..e0c3d06fb: 2 commits, 5 files, +79 -2, against kvflash/prefill-recall at d98512ff0 (#963 is now at a21ae4883, five commits later; this branch is not rebased onto them).

Why

A launcher or client cannot tell whether a running server has KVFlash recall, or which mode, without reading its log. This adds one line to --help and one object to /props.

What it does

Paths under server/.

  • src/server/launch_profiles.h: kKvflashRecallProtocol = 1, kvflash_recall_help_line() = kvflash-recall: protocol=1, and the pure kvflash_recall_mode(arch, reselect): prefill-reselect=<4|5> on qwen35, empty on another architecture or when LUCE_KVFLASH_PREFILL_RESELECT is 0 or unset.
  • src/server/server_main.cpp: --help ends with the protocol line; with --kvflash, after the recall profile (kvflash_recall_env(arch, mode5)) is installed, the server config takes kvflash_enabled, kvflash_pool_tokens (0 for auto) and the mode.
  • src/server/http_server.cpp/.h: /props gains kvflash {enabled, pool_tokens, recall {protocol, active, mode}}; active = enabled and a non-empty mode. Without --kvflash: enabled:false, active:false.
  • Hand port of 79a6f18fb, adapted to the mode-4 / mode-5 profile of feat(qwen35): prefill recall with the exact scorer on the serial path, recall profile on by default #963. feat/kvflash-ecap and -v3 are duplicates of it.

Commits

  • 2e5475509 test(server): 4 cases (help line, mode string, /props without the flag, /props with pool and recall). Red alone: the helpers and the config fields are missing.
  • e0c3d06fb feat(server): the helpers, the config fields, the /props object, the --help line.

Evidence

RTX 3090 (CUDA 12.6, sm_86), pre-rebase head 071a87f2b (maps to e0c3d06fb): build ok; test_server_unit 1389 pass / 0 fail / 6 skip; ctest 1705 of 1711 at the 120 s timeout; of the 6, 3 are timeouts that pass alone at 900 s and 3 fail on the base too (test_ds41_mmid_width_invariance, qwen4exp_prefix_cache, server_unit_entrypoint). Per commit: the test commit does not compile alone (red-first, kvflash_recall_help_line arrives with the feature commit); the feature commit builds.

Radeon AI PRO R9700 (gfx1201, ROCm 7.2.4, lucebox6), e0c3d06fb itself: HIP build ok; test_server_unit 1370 pass / 0 fail / 4 skip. A server started with --no-kv-cache --kvflash 16384 (Qwen3.8-27B IQ4_XS, no draft model) serves over HTTP /props.kvflash = {"enabled": true, "pool_tokens": 16384, "recall": {"active": true, "mode": "prefill-reselect=4", "protocol": 1}}; without --kvflash it serves {"enabled": false, "pool_tokens": 0, "recall": {"active": false, "mode": "", "protocol": 1}}; the same before and after a request.

Not run

  • /props over HTTP in mode 5, with --kvflash auto or on the slot engine (--max-concurrency): the HTTP read covers mode 4 on the serial path only.
  • The consumer: the luce_box W4 probe that reads this object has not landed.
  • HIP ctest beyond test_server_unit; gfx1151.

View guided diff

…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.
…that must grow (red: pflash_pick_resume not defined yet)
…ows in place and resumes at its checkpoint, it no longer re-scores from token 0

acquire_scoring_session skipped any stored session with capacity < S_padded, then freed the chosen one and cleared its state, so a conversation past S + S/2 + 4096 tokens was scored fresh. pflash_pick_resume keeps an undersized session as a candidate (needs_grow); grow_scoring_session copies its token-indexed tensors below the checkpoint and the rest whole into a bigger allocation and moves the bookkeeping over.
…92 projection chunk holding the resume point is re-projected whole from kept exact block-14 rows
…r scoring while the latest user question and the conversation prefix are unchanged
…new chunks padded with the lowest (red: kvflash_m5_reuse_scores not defined yet)
…m the last drafter scores instead of falling back to a recency-only pool
…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
…ent turn runs; the prefix hash already rejects a diverged conversation
…st scored prompt, with a tail slack for the re-rendered generation prompt (red: KvFlashM5Last has no ids yet)
…s a re-rendered tail of up to 64 tokens; the prefix hash over the old end never matched the next agent turn
…nged question by default (LUCE_KVFLASH_M5_RESCORE_TOKENS=0 scores every turn)
…probe's tap-count smoothing as a pure function that must match the scorer's inline loop bit for bit (red: not declared yet)
…tants once (boundary scores, split scores, line flags) instead of once per pin set, and logs the score half's phases (proj, segments, windows, tiles) on the [qwen35-scorer] line

The mode-5 drafter (pflash2 scorer) segments the prompt up to three times per call (query-step units, the pin fit, the served selection); each re-ran the Conv1d smoothing over all S probe logits, the sub-unit smoothing and S token_text + line flags. These depend only on the session's raw logits and the ids, so they are computed on first use and shared; the segments are unchanged (same inputs, same function). The smoothing moved into pflash_probe_boundary_scores (pure, unit-tested against the old loop bit for bit).

The scorer line now adds 'phases: proj N ms, segments C/N ms, windows C/N ms, tiles C/N ms' so the next GPU run splits the context-proportional score cost (0.55-0.94 s at 90-120K on the R9700) between the full-probability window readback and the device-reduced tiles.
…over (query, head) on device and reads back S floats instead of [S,nq,H]; PFLASH_TW_HOST_REDUCE=1 keeps the host path for A/B
…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.
Red tests for a pager victim tier: paged-out chunks keep their bytes beside
the pool and a recall copies from there with identical bytes and residency;
FIFO by page-out, a row write after a recall invalidates the copy, truncate
drops the dropped.
Red: KvFlashConfig has no victim_blocks yet.
Victim tier on the device for paged-out chunks (LUCE_KVFLASH_VICTIM_BLOCKS,
default twice the pool); a recall of a chunk still in it is a D2D copy
instead of an H2D over the host link. lucebox4's R9700 sits on a Gen3 x2
root port (00:03.2, 8 GT/s x2): recalls ran at 1.32 GB/s, 1.6 ms per
2.1 MiB chunk, 22.5 s on the K2 screen. Same bytes, same residency; the
paging lines log the tier hits.
The tier is device memory and does not engage for memcpy-paged CPU tensors,
which the gate's CPU-tensor fixture hit: 3 FAIL on hip0/hip1, stat counters
only. A fifth case pins that host tensors on a GPU build get no device tier.
…en the drafter and its three PFlash GGUFs are set, the measured K3 settings, and mode 4 exact without them (red: kvflash_recall_env takes no drafter flag, no kvflash_drafter_ready)
--kvflash on qwen35 installs KVFlash 2.0 (mode 5, PFlash 2.0 drafter
scorer, the K3-measured selection settings) when the drafter and its three
PFlash GGUFs are set, and mode 4 exact otherwise; the server logs which
profile it installed; ENVIRONMENT.md rows for the victim tier and the
window host reduce.
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.
… tensors

The attach path pins host staging with cudaMallocHost by default. On the
stub-driver CI runner that call fails, so 3 tests in these two fixtures
failed in the Linux build of Luce-Org#963. Set set_pinned_host_backing(false)
before each attach, as test_kvflash_pager_serde.cpp already does.

Local 3090, CUDA_VISIBLE_DEVICES="": 9/12 before, 12/12 after; 12/12 with the GPU.
…nd mode 5 only when LUCE_KVFLASH_PREFILL_RESELECT=5 asks for it with the drafter and its three PFlash GGUFs (red: no kvflash_mode5_requested)
… is opt-in

kvflash_mode5_requested replaces kvflash_drafter_ready: the mode-5 profile
installs only when LUCE_KVFLASH_PREFILL_RESELECT=5 and the drafter and its
three PFlash GGUFs are set. Otherwise --kvflash installs mode 4, the exact
scorer with the latest question's 64 queries. On ten replayed agent sessions
mode 4 kept the needle resident from the first write turn in 10/10 sessions
and mode 5 in 0/10; on 20 live agent tasks mode 4 passed 19 and mode 5 17.
The startup line says which profile was installed.
…ageable staging on CPU tensors

Same cause as the pager recall and pin tests: attach pins host staging with
cudaMallocHost, which fails without a CUDA device (the stub-driver CI runner).
CUDA_VISIBLE_DEVICES="" on the 3090: 3 of these tests failed before, all pass
after; with the GPU they pass both ways.
…changed

A turn that continues the last request under the same question picks from the
last exact scores when they cover every recall candidate, and scores before the
pass (stored question queries + the previous request's tail queries) when a
candidate has none. Neither rewinds or resets the pool to recency. A new
question, another conversation or a rewritten scored chunk takes the unchanged
two-pass path. LUCE_KVFLASH_M4_SINGLE=0 forces the two-pass path on every turn.

Old M4 on 14 LIVECODE sessions (2026-11-10, lucebox4): 810 reselects, scorer
512 s, 750779 tokens prefilled twice, prefill 0.504x of 1.0 recency.
…t N blocks of SELECT_UNIT chunks

The recall budget is 10 x RECALL_BLOCKS chunks (qwen35_backend.cpp in.recall_chunks), picked in
SELECT_UNIT-sized units (kvflash_prefill_reselect.h k_units = recall_chunks / unit). The row said
N blocks of SELECT_UNIT chunks, i.e. 12 chunks at the defaults instead of 60.

Review: Luce-Org#963 thread T5 (cubic)
…inside the pool

Production takes the preamble reserve out of --kvflash N (pool stays N). The fixture added it on top
(256 + 96) and asserted the feature-off tail, so it encoded the old design. It now uses a 256-block
pool and asserts the reduced tail (95 = off - 96); it fails if the tail formula ignores the reserve.

Review: Luce-Org#963 thread T7 (cubic)
…or parallelism

kvflash_q_cap_all_rows() keys off LUCE_KVFLASH only, so a tp_degree > 1 process reserves the
64-row capture although recall is off there. Threading the resolved plan through
create_target_cache_partial (6 callers across layer-split, shard daemon, drafter) and the VRAM estimate
exceeds the small-fix cap, so the comment now states the deliberate reservation and its size.

Review: Luce-Org#963 thread T10 (cubic)
…help names the recall protocol (red: kvflash_recall_help_line, kvflash_recall_mode and the ServerConfig fields are missing)
…props.kvflash {enabled, pool_tokens, recall {protocol, active, mode}}
@dusterbloom

Copy link
Copy Markdown
Collaborator Author

Folded into #963 as its last commit, 4f2de18da (feat(server): /props.kvflash reports whether recall is on), so this PR is closed.

What changed on the way in:

  • /props.kvflash is flat: {enabled, pool_tokens, mode}. The nested recall {protocol, active, mode} object and the --help marker are not carried, since no client reads them.
  • mode is the backend's own kvflash_reselect_mode over LUCE_KVFLASH_PREFILL_RESELECT, LUCE_KVFLASH_POLICY and LUCE_KVFLASH_RESELECT_SCORER, read after the --kvflash* flags have set them. So --kvflash-policy lru reports recall off. Here an explicit --kvflash-policy lru could still report recall active, because the fields were read before the flag override.
  • KVFlash enabled through LUCE_KVFLASH alone now shows enabled: true. pool_tokens is 0 for --kvflash auto (sized at load).

Checked on lucebox6 (R9700):

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.

1 participant