Skip to content

fix(server): close mkstemp fd in _tokenize_prompt to prevent fd leak - #15

Merged
davide221 merged 1 commit into
Luce-Org:mainfrom
sanastasiou:fix/tokenize-fd-leak
Apr 23, 2026
Merged

davide221 merged 1 commit into
Luce-Org:mainfrom
sanastasiou:fix/tokenize-fd-leak

Conversation

@sanastasiou

Copy link
Copy Markdown
Contributor

The bug

In dflash/scripts/server.py, _tokenize_prompt() calls:

tmp = Path(tempfile.mkstemp(suffix=".bin")[1])

tempfile.mkstemp() returns (fd, path). This code keeps only the path (index [1]) and discards fd. Python's GC does not close integer file descriptors, so the fd stays open in the OS until the process dies. Every chat request leaks exactly one fd.

Under sustained load the process hits RLIMIT_NOFILE (default 1024 on a systemd service without explicit LimitNOFILE=). Once the wall is reached, socket.accept() starts throwing OSError: [Errno 24] Too many open files and the API stops accepting new HTTP connections — even though the model process itself is still healthy.

Reproduction

In our deployment we have Lucebox sitting behind ~6 concurrent client services (4 Hermes agents + a Hindsight memory server + a Honcho peer-model service + a Firecrawl extractor, all OpenAI-compatible). Within roughly an hour of normal aux traffic, FD count reached 1023/1024 and new requests were rejected.

/proc/<lucebox-pid>/fd showed the composition: only ~5 actual sockets and pipes, and ~1000 orphan /tmp/tmp*.bin file descriptors — exactly the pattern of a leaked mkstemp fd.

Journal log excerpt:

OSError: [Errno 24] Too many open files
socket.accept() out of system resource
socket: <asyncio.TransportSocket fd=8, family=2, type=1, proto=6, laddr=('0.0.0.0', 8001)>

The fix

Use os.fdopen(fd, "wb") which takes ownership of fd and closes it when the with block exits:

fd, path = tempfile.mkstemp(suffix=".bin")
tmp = Path(path)
with os.fdopen(fd, "wb") as f:
    for t in ids:
        f.write(struct.pack("<i", int(t)))

The on-disk temp file is still cleaned up by the existing prompt_bin.unlink() in chat_completions (both streaming and non-streaming paths), so there is no change to disk behaviour — only the fd lifecycle changes.

Verification

  • Before fix: FD count delta across 3 probe chat requests = +3 (one fd leaked per request)
  • After fix: FD count delta across 3 probe chat requests = 0 ✓

Also raised LimitNOFILE from the default 1024 to 65536 on our systemd unit as a defence-in-depth measure (unrelated to this PR). The code change alone is the correct fix; the limit bump is independent and up to the operator.

`tempfile.mkstemp()` returns `(fd, path)`. The previous code kept only
the path (index [1]) and discarded `fd`. Python's GC does not close
integer file descriptors, so the fd stays open in the OS until the
process dies. Every chat request leaks exactly one fd.

Under sustained load, the process hits `RLIMIT_NOFILE` (default 1024
on a systemd service without explicit `LimitNOFILE=`). Once that wall
is hit, `socket.accept()` starts throwing `OSError: [Errno 24] Too
many open files` and the API stops accepting new HTTP connections.

Reproduction in our deployment: Lucebox behind ~6 concurrent client
services (4 Hermes agents + a Hindsight memory server + a Honcho
peer-model service + a Firecrawl extractor). Within roughly an hour
of normal aux traffic, FD count reached 1023/1024 and new requests
were rejected even though the model itself was healthy.

Fix: use `os.fdopen(fd, "wb")` which takes ownership of `fd` and
closes it when the `with` block exits. The on-disk temp file is
still cleaned up by the existing `prompt_bin.unlink()` in
`chat_completions` (both streaming and non-streaming paths), so
there is no change to disk behavior.

Verified empirically: FD count delta across three probe chat
requests went from +3 (one leak per request) to 0 after the patch.
@davide221
davide221 merged commit e5ef959 into Luce-Org:main Apr 23, 2026
oliveagle pushed a commit to oliveagle/lucebox-hub that referenced this pull request May 22, 2026
fix(server): close mkstemp fd in _tokenize_prompt to prevent fd leak
easel added a commit to easel/lucebox-hub that referenced this pull request May 29, 2026
- lucebox/README.md: fix the relative link to `cli.py`; resolves to
  `src/lucebox/cli.py` (the actual location), not the nonexistent
  `lucebox/cli.py` (Luce-Org#15).
- luce-bench/NOTICE: the bundled forge_eval LICENSE says
  "Copyright (c) 2025-2026 Antoine Zambelli", not 2024 — sync NOTICE
  with the actual upstream LICENSE (Luce-Org#16).
- luce-bench/src/lucebench/areas/__init__.py: `__all__` was missing
  agent / agent_recorded / forge / longctx / smoke. Add the imports +
  list entries so `from lucebench.areas import *` matches the actual
  area surface (Luce-Org#17).

Addresses cubic Luce-Org#15–Luce-Org#17 (P3) on PR Luce-Org#285.
davide221 added a commit that referenced this pull request Jun 7, 2026
The origin/main merge resolved the server/deps/llama.cpp gitlink to the PR's
older b896cf69 (llama #12 hip-shim), rewinding it from main's 570d9785 and
dropping llama #13 (crash), #14 (pflash-sparse stream-sync / BSA fix) and
#15 (fattn-sparse hip cudaStreamDefault). Point the gitlink back to 570d9785
(a strict superset — b896cf69 is its ancestor) so the PR no longer downgrades
llama.cpp / drops the BSA fix.

Rebuilt + smoke-tested against 570d9785: sg_b100 96/96 bit-exact vs all-GPU,
offload 60% 99.3 tok/s, all-GPU 119.5.

Co-Authored-By: WOZCODE <[email protected]>
davide221 added a commit that referenced this pull request Nov 19, 2026
…el over a device archive of evicted K (stacked on #963) (#994)

* feat(kvflash): prefill reselect helpers, the mode gate, turn cut, recall 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.

* feat(kvflash): pager reselect_recent and a valid_upto bound on the slot 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.

* feat(qwen35): capture the last 64 prompt queries per full-attention layer 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.

* feat(qwen35): the KVFlash decode mask hides rows above the decode position

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.

* refactor(qwen35): split the KVFlash drafter load out of kvflash_ensure_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.

* feat(qwen35): recall before write at the last user turn, with user-question 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.

* feat(qwen35): pin the system+tools preamble in the KVFlash pool

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.

* feat(server): --kvflash on a qwen35 target installs the recall profile

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.

* fix(server): the KVFlash recall profile reserves 1152 preamble rows, 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%.

* fix(qwen35): the KVFlash preamble reserve comes out of --kvflash N, the 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.

* test(kvflash): bench_kvflash_page, ms per page event over real-size device KV (16 layers, 4 kv heads, hd256, q8_0)

* perf(kvflash): page copies and block zeroing are one strided 2D call per (layer, K/V) instead of one per kv head

* perf(kvflash): page_out skips the D2H for a chunk recalled from host and not written since (dirty flag, d2h_skipped stat)

* perf(kvflash): eviction and reselect page-outs leave the freed block unzeroed; a recall overwrites it, a fresh chunk zeroes it on handout, reselect flushes the rest

* test(kvflash): red test for the pager reselect fencing its recalls once at the end, not per hand-out, with residency unchanged (red: KvFlashStats has no fence_points yet)

* perf(kvflash): reselect recalls page-ins as one batch, one wait

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.

* fix(kvflash): recall gate, eviction hook clamp and profile cleanups

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.

* fix(kvflash): victim FIFO compaction and pinned-aware pooled ubatch

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.

* test(kvflash): pager recall and pin tests use pageable staging on CPU 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 #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.

* test(kvflash): reselect fence and host-tensor victim tier tests use pageable 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.

* feat(kvflash): mode 4 runs a turn once while the human question is unchanged

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.

* docs(server): LUCE_KVFLASH_RECALL_BLOCKS is a 10 x N chunk budget, not 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: #963 thread T5 (cubic)

* test(kvflash): the pinned-preamble recall fixture carves the reserve 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: #963 thread T7 (cubic)

* docs(kvflash): state the per-process q_cap_all reservation under tensor 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: #963 thread T10 (cubic)

* fix(kvflash): recapture the turn's tail queries after a rewind

Defect: the m4 tail capture was gated on !rw_done, so on a rewound turn
kvflash_q_tail_ kept pass 1's queries (old pool) and pass 2, which
recomputes [R, end) under the new pool, captured nothing. The stale tail was
stored in kvflash_m4_last_.q_tail and scored by the next turn's Prescore.

Fix: capture in both passes (pass 1's tail is still what the rewind scores
with), and when kvflash_rewind_turn returns rc > 0 drop the tail rows at
positions >= R (kvflash_q_tail_trim) so pass 2 refills them. The append and
trim logic are pure helpers in kvflash_query_capture.h.

Tests: test_kvflash_uq.cpp q_tail_* cases (trim at R, ragged tail, pass 1
below R followed by pass 2 rows). Red: the helpers did not exist
(compile failure, red-item2-compile.log); green: 1377 passed, 0 failed.
Not run on hardware.

* fix(kvflash): write q_cap_all only when recall or UQ is on

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.

* fix(server): kvflash help default and the resolved reselect mode in the 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).

* fix(kvflash): read only the captured rows of q_cap_all

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.

* fix(kvflash): recall a turn's tail when the whole turn cannot be replayed

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.

* refactor(kvflash): remove mode 5

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.

* feat(server): /props.kvflash reports whether recall is on

/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.

* feat(kvflash): exact GPU scorer can keep the evicted K it uploads in 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.

* 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

* 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

* 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

* 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

* 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

* feat(kvflash): mode 4's exact GPU scorer defaults to the fused chunk-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'.

* 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

* fix(kvflash): fused scorer takes the WMMA path only on gfx1200/gfx1201, 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.

* fix(kvflash): release the fused scorer workspace before the GPU scorer refuses on free VRAM

* fix(kvflash): a failed fused run clears the CUDA sticky error, so the 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)

* fix(kvflash): the first failed fused run latches the kernel off for the 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)

* fix(kvflash): a pager reset frees the GPU scorer's device archive instead 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)

* test(kvflash): the GPU CI jobs run the fused-mass and GPU-scorer fixtures, 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)

* fix(kvflash): a pooled snapshot restore drops the GPU scorer's device 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)

* fix(kvflash): no scorer warnings on a prompt that fits the pool; pick 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]>

---------

Co-authored-by: mrciffa <[email protected]>
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