You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I've made lot of work to significantly improve Kvarn KV Cache performance on my RTX 3090 for Qwen dense and MoE models, especially for concurrent requests without losing quality. Right now, the performance is on par with Q8 KV and Kvarn KV is faster on large context than Q8 KV. I hope, you will find my contribution useful. Since I've done it for myself, currently all docs and comments on my changes are in Russian.
Please look into this, I just tested and my results are even better than OP's.
Just confirm that his implementation does not affect KLD in any significant way.
I second this too, tested with rtx3090 and Qwen3.8-27B-UD-Q4_K_XL.gguf and I can confirm it's the fastest llama implementation so far.
And another discovering, latest v0.4.4 it's slower than v0.4.3 for my setup, don't know why but something it's loosing TPS...
Ported most of the changes, additionally adapting them to v0.4.4 changes that landed closer to release.
Performance is indeed better, especially with multiple slots.
Please test it thoroughly on the v0.4.5 branch, especially in terms of stability, correctness, and edge cases.
AI-written implementation details and benchmarks
Completed a port of the KVarN correctness and CUDA decode work from valujin/beellama-kvarn onto the current v0.4.5 architecture.
The main port landed in 72bace072 (Optimize KVarN CUDA decode paths). The final long-context compact-plan, windowing, and stage-slot follow-up described below is currently in the local candidate and has not yet been committed.
The implementation was adapted rather than cherry-picked because the optimization fork was based on an older v0.4.4 tree and its allocator, stage ownership, cache state, and CUDA routing differ materially from current v0.4.5.
What was implemented
1. Compact-plan lifecycle correctness
The cached indirect KVarN read plan is now invalidated whenever its source cache metadata can change:
llama_kv_cache_kvarn_context::next()
llama_kv_cache_kvarn_context::apply()
Previously, a plan could survive across ubatches even though the occupied and pending physical cells had changed. That could silently produce incorrect reads depending on slot count and scheduling.
2. Safe GQA-6 CUDA query loading
The CUDA MMA path logically supports six GQA rows, but ldmatrix physically reads an eight-row extent.
The query tile now:
reserves storage for all eight physical rows;
initializes the padded rows;
retains six logical GQA heads.
This prevents out-of-bounds or uninitialized shared-memory reads without changing logical attention dimensions.
3. Compact-plan duplicate bitmap
Compact plan construction now uses a capacity-sized bitmap instead of std::set for duplicate filtering.
It preserves:
occupied/pending deduplication;
first-occurrence semantics before physical layout;
capacity checks;
sentinel padding.
4. Physical record-group-safe compact plans
Unified-cache ownership can interleave logical sequences while their KVarN records remain physically disjoint. A logically ordered plan could therefore look contiguous to a CUDA cooperative record loader even though its adjacent rows came from different physical records.
The final plan implementation:
groups cells by their physical 128-cell KVarN record;
sorts selected records by physical group;
gives every selected record its own monotonic segment;
retains -1 holes within incomplete records;
never falls back to interleaved logical order for sparse groups.
This is the change responsible for recovering the large two-slot performance improvement.
5. Descriptor setup optimizations
The descriptor path now includes:
1024-thread descriptor reduction;
low-32-bit physical-cell extraction;
preservation of high-bit encoded stage-slot metadata;
division-free scanning for the common single-stream case.
The old fork treated indices more like plain physical cells. The port explicitly preserves the current v0.4.5 encoded stage-slot representation.
6. CUDA decode-kernel optimizations
The following mechanisms were ported and adapted:
packed fragment permutation;
paired low-bit unpack;
fully masked split skipping;
half-width shared quantization axes;
split-128 geometry;
launch bounds and occupancy-aware selection;
query-row tiling with Q_TILE=2/3;
reuse of decoded K/V data across query rows.
Unsupported shapes continue to use the descriptor-native MMA fallback rather than failing or silently changing cache interpretation.
7. Small verification-batch routing
Split decode is now eligible through n_q <= 8.
This covers common speculative verification shapes while preserving generic MMA fallback for larger batches. Multi-query split routing requires an attention mask.
A temporary n_q <= 3 experiment was rejected because it did not provide the same stability/performance balance.
8. Evidence-based split geometry selection
The final selector uses:
split-64 for ordinary single-query decode below 32K;
split-128 for single-query decode at 32K and above;
split-128 earlier when multi-query verification benefits from query tiling.
This replaced a broader initial split-128 policy that regressed ordinary-depth workloads.
9. Bounded large-window materialization
The default KVarN materialization window was reduced from 65,536 to 32,768 tokens.
This bounds transient K/V scratch when two long prompts share a 128K cache. The partial windows retain the online-softmax maximum, numerator, and denominator and are merged afterward.
Chunked-window CUDA parity coverage was added. The accepted RMSE is 3e-4, reflecting the changed floating-point reduction order.
10. Explicit replacement-stage slots in delayed sealers
The delayed high-shared, low-shared, head-wide, direct, and workspace sealing paths now use the incoming replacement group’s encoded host-assigned stage slot.
They no longer assume that a live group’s slot can always be reconstructed from its group number modulo the tail depth.
This did not explain every observed long-prefill failure because the production target uses eager record commitment, but it is a real correctness defect in the delayed paths and is retained with focused CPU/CUDA parity tests.
How this differs from the initial implementation
The first adaptation was deliberately conservative:
preserve first-seen logical group order;
align only small n_q=1..8 decode/verification plans;
cap alignment growth at 25%;
leave large prefill and sparse plans dense.
That version improved ordinary two-slot decode, but it did not fully enforce the CUDA record-loader invariant.
Initial approach
The initial policy assumed that dense fallback was safe when alignment expansion was large. This proved false: a sparse logical plan could still place rows from separate physical records next to each other and make them look like a contiguous physical tile.
It also retained logical group order to minimize observable ordering changes.
Final approach
After reproducing failures with larger two-slot contexts, the plan was changed to:
sort by physical record group;
reserve one complete monotonic segment per selected record;
preserve holes with -1;
remove the small-batch-only alignment helper;
remove the 25% sparse-growth fallback;
apply the physical record invariant to every compact unified-cache plan.
The API was simplified again after the growth policy was removed.
Other changes made during diagnosis
A startup crash caused by consulting base()->get_ubatch() while constructing synthetic reserve graphs was fixed by using valid current slot metadata. The policy that needed that query was later removed entirely.
The original 65,536-token materialization window was reduced to 32,768 after full-window tests showed excessive transient scratch at 128K.
Alignment, exact tail, CUDA graph use, low-shared-memory stores, ubatch size, and portable attention were tested independently to separate compact-plan failures from other long-run failures.
The final two-slot benchmark was redesigned so both slots were actually decoding simultaneously. The original cold-prompt harness measured one slot decoding while the other was still prefilling, which substantially understated two-slot decode throughput.
What was not implemented
1. The old fork allocator/group-claim implementation
The implementations from the old group-claim and allocator commits were not copied.
Current v0.4.5 already has newer:
allocator ownership;
planning reservations;
stage-slot assignment;
cache state and checkpoint handling.
Copying the old allocator would have replaced current ownership semantics and risked regressions in rollback, state restore, MTP verification, and slot reuse.
Only the physical read-plan mechanism was adapted.
2. The old fork stage-owner implementation
The old modulo/owner stage system was not ported.
Current v0.4.5 uses explicit host-assigned stage slots encoded in cache indices. The CUDA changes were adapted to consume those assignments rather than restoring the old ownership model.
3. Wholesale cherry-picking of 54bc3d29, c3ca5bcc, 432024c3b, or 1b2f628ca
These commits bundled mechanisms with obsolete allocator and state assumptions. They were used as architectural evidence, not treated as drop-in patches.
Additional changes not present in the optimization fork
The following work was added because it was required by current v0.4.5 or found during validation:
GQA-6 eight-row physical query padding.
Low-32-bit physical-cell decoding while preserving encoded stage slots.
32K bounded window materialization for 128K unified caches.
Explicit replacement-slot handling in every delayed CUDA sealer.
The measured 32K split-64/split-128 selector boundary.
Current-architecture stage-slot parity tests.
Chunked-window online-softmax parity tests.
Static source-safety tests for encoded indices, route limits, and removed experimental switches.
A synchronized hot-cache two-slot benchmark harness. It preloads both long prompts, then starts both measured requests with sub-0.2 ms launch skew and verifies that each request reuses the full cached prompt and reprocesses only one token.
Verification
The final candidate was checked with:
a complete Windows CUDA sm_86 build;
fresh serialized CTest: 82/82 passed;
earlier expanded/all-test coverage: all 104 tests passed across the full run plus one isolated retry of a transient unrelated CUDA test;
test-kvarn CPU/CUDA parity;
direct CUDA FlashAttention parity;
KVarN metadata, exact-tail, stage-slot, rollback, state, and route tests;
n_q=2..16 route coverage;
all 36 ordered KVarN CUDA bit pairs in the expanded build;
169 standard CUDA quantization pairs;
static safety tests;
git diff --check.
Benchmark environment
Unless noted otherwise:
GPU: RTX 3090, CUDA0, sm_86;
CUDA: 13.3;
driver: 616.56;
model: Qwen3.6-27B IQ3_XXS;
model SHA-256: a6cd1e829a8ba24a78edeb8f078b724ea7a9873856f1916e356eea5c537c0b40;
v0.4.4 package: commit f8cd4e6dd;
v0.4.5 package: commit 476aa6c4b;
final two-slot candidate: 476aa6c4b-dirty, including the follow-up physical-plan/window/stage work;
batch/ubatch for the standard decode and prefill matrix: 2048/512;
three samples unless noted.
The older published fork baseline was commit a749684, not the provided v0.4.4 package. The tables below use the provided f8cd4e6dd package.
v0.4.4 versus v0.4.5 results
16K single-slot decode
64 generated tokens:
Cache
v0.4.4
v0.4.5
Difference
BF16, tail 0
37.420
37.035
−1.03%
KVarN4, tail 0
33.042
34.451
+4.26%
KVarN4, tail 1024
32.042
33.470
+4.46%
Q4_0, tail 0
39.222
39.183
−0.10%
Q4_0, tail 1024
38.175
38.399
+0.59%
The controls show that the ordinary-depth gain is specific to KVarN rather than a general build-wide speedup.
16K prefill
Cache
v0.4.4
v0.4.5
Difference
BF16, tail 0
1244.96
1238.29 tok/s
−0.54%
KVarN4, tail 0
1176.11
1177.13 tok/s
+0.09%
KVarN4, tail 1024
1166.07
1166.44 tok/s
+0.03%
Q4_0, tail 0
1234.33
1234.69 tok/s
+0.03%
Q4_0, tail 1024
1205.29
1205.23 tok/s
−0.005%
There is no material prefill change at 16K.
64K single-slot decode
Tail 1024, 64 generated tokens:
Cache
v0.4.4
v0.4.5
Difference
KVarN4
18.347
20.036 tok/s
+9.21%
KVarN5
18.368
19.822 tok/s
+7.92%
The long-context gain is larger than the 16K gain, consistent with the descriptor and split-geometry changes.
Single-slot MTP
KVarN4, tail 1024, 16K context, three trials:
Build
Decode
v0.4.4
65.766 tok/s
v0.4.5
66.965 tok/s
Difference
+1.82%
Proper two-slot long-context comparison
The earlier cold-prompt server benchmark did not isolate simultaneous two-slot decode: one slot often decoded while the other was still prefilling.
The final benchmark therefore used:
--parallel 2;
--kv-unified;
131,072-token cache;
63,692 cached prompt tokens per slot;
F16 precision tail 1024;
256 measured tokens per slot;
both prompts preloaded before measurement;
one token reprocessed per measured request;
launch skew below 0.19 ms;
three valid measured trials for every build/cache combination.
Aggregate server-reported decode
Cache
v0.4.4
Final local v0.4.5
Difference
KVarN4
6.497 ± 0.114
29.346 ± 0.013 tok/s
4.52× / +351.7%
KVarN5
6.052 ± 0.035
29.298 ± 0.548 tok/s
4.84× / +384.1%
Average per slot
Cache
v0.4.4
Final local v0.4.5
KVarN4
3.249
14.673 tok/s
KVarN5
3.026
14.649 tok/s
Wall-clock aggregate throughput
This includes request and synchronization overhead:
Cache
v0.4.4
Final local v0.4.5
Difference
KVarN4
6.368
26.615 tok/s
4.18× / +317.9%
KVarN5
5.916
26.103 tok/s
4.41× / +341.2%
Long-prompt prefill in the same trials
Cache
v0.4.4
Final local v0.4.5
Difference
KVarN4
680.14
672.98 tok/s
−1.05%
KVarN5
673.42
672.40 tok/s
−0.15%
The large two-slot improvement is therefore a decode-path result, not a general prefill change.
The result does not exactly reproduce the fork’s published 5.9× Qwen3.8 result, but it confirms the same mechanism on a matched comparison against the provided v0.4.4 package: the final local build is approximately 4.5–4.8× faster with both long-context slots actively decoding.
I and my AI assistant have made farther mixed optimizations and fixes that improve QoL significantly for 24GB card users). Some of them are KVarN related (like MTP KV cache support and optimizations), some of them not (like VRAM free VISION with almost the same performance).
Update: what's new since the ported batch
All measured on RTX 3090 / Qwen3.8-27B-UD-Q4_K_M, ctx 212992, 4 slots, kvarn4 target cache.
Bug fixes — the first two are not KVarN-specific and likely affect the base as well
Speculation checkpoint rollback was quadratic.get_seq_rm_capability() declared a 1-token reserve that can_seq_rm() does not actually enforce for a structural cache. The server saw the capability as insufficient and re-serialized the entire draft cache on every speculation cycle, through a tail serializer that walks cells from zero per entry. perf showed state_tail_payload_slots at 17.95% of cycles with GPU at 63%. After the fix: 42.7 → 59.4 t/s at 20k depth, GPU 63% → 99%.
Draft rollback was computed on the wrong axis. The MTP draft numbers its tokens by count (n_past), while the server required rollback to ckpt.pos_max + 1 — the target's position axis. These are identical on text, so it never showed. On vision models they diverge: one image is thousands of tokens but only a few positions under M-RoPE. Result: GGML_ABORT on the first image whenever the draft cache is quantized. Fixed by using ckpt.n_tokens. Verified on 15 image requests across 5 configurations, byte-identical output, zero seq_rm refusals.
Shared-memory OOB in the KVarN decode kernel: p_sh is declared with 6 rows at MAX_GQA == 6, but load_ldmatrix reads 8. Harmless in practice, but real — fixed the same way q_sh already was, via a P_ROWS bound.
New capability
MTP draft cache on KVarN: 832 MiB f16 → 131 MiB kvarn2. This is safe by construction rather than by measurement — the draft only proposes tokens and the target verifies them with its own cache, so draft-cache error can lower acceptance but cannot corrupt output. Measured acceptance actually went up (0.875 vs 0.769). Total MTP cost 2522 → 1814 MiB.
Projector weights in pinned host memory, opt-in via --mmproj-host-weights: frees 886 MiB of VRAM, image encode +5–16%, output byte-identical, LLM speed untouched. Off by default.
One analysis that may interest ggml-org
The devices[].integrated = false gate (their PR ggml-org#16308) is masking a scheduler race, not a hardware limitation. llama.cpp deliberately places model input tensors in the CUDA host buffer; while CUDA reports it as unsupported, the scheduler copies those inputs to VRAM and calls ggml_backend_synchronize first — and that copy is the only barrier between the CPU writing inputs and kernels reading them. Naively enabling host buffers removes the barrier along with the copy. The fix is a separate weights-only buffer type. Isolated by enabling the gate without moving any weights: encode time unchanged, output corrupted with the identical hash. This appears to explain the open ggml-org#25992 (server returning other sessions' answers verbatim at -np 4).
On quality: none of these changes touch the target cache numerics. Verification was byte-exact output comparison at temperature 0, single slot — stricter than KLD for this purpose. Note that at --parallel > 1 response hashes are not reproducible run-to-run on this build (batching order), so multi-slot hash comparison is not a valid method.
Not resolved — please treat as known
One anomaly is reproducible but not root-caused: with a kvarn2 draft cache at --parallel 1, depth ≈2123 and one specific prompt, the first request after start differs from all subsequent ones (the draft itself diverges). Does not reproduce at --parallel 4 or at depth 20115. GGML_KVARN_SPLIT_MAX_Q=1 masks it. compute-sanitizer --tool initcheck is clean, though the pool uses VMM so that is not conclusive.
Unexplained: a coarser separate draft (Q4_K_S sidecar) reaches higher acceptance at 45k depth than the built-in layer — 0.804 vs 0.627. Measured stably over three runs, not understood.
Does the mmproj change result in weights being in RAM but the model still being processed on GPU?
Yeah, you got it right. mmproj is not that big and weights used once per request - PCIe link is sufficient for that. In my testing I got several percent speed reduction compared to full on GPU mmproj well known classic.
There's the --no-mmproj-offload option that offloads both weights and exectution to CPU, which is safe fallback, but GPU execution is indeed better if there won't be any issues.
Qwen mmproj require at least 1024 image tokens for reasonable output - this is 6.3s per image on my Ryzen 9950x. 2048 token images take 23s per image. That's insane.
If flash attention is on and --no-mmproj-offload is set - time per image just doubles (13s per 1024 token image). Using ZenDNN help, since it's used outside flash attention path.
My next thought was - why no use system RAM for on GPU CUDA computation. There are two ways:
GGML_CUDA_ENABLE_UNIFIED_MEMORY - it's already implemented in original llama.cpp, correct, but only frees 456 MiB, and 328 under load. Not worth it.
I flipped the gate and got the corruption too. Turns out it has nothing to do with weights or hardware. llama.cpp deliberately puts the model's input tensors in that same host buffer, and while CUDA reports the buft as unsupported, the scheduler is forced to copy them to VRAM with a ggml_backend_synchronize first — that sync is the only barrier before the kernels read them. Open the gate and the barrier disappears together with the copy, so the next ubatch's set_input() overwrites memory the previous one is still reading.
So instead of opening the general path I added a separate weights-only buffer type, reachable only via ggml_backend_reg_get_proc_address — model inputs can't land there, barrier stays.
Two gotchas: plain zero-copy is 2.9x slower because cuBLAS re-reads each weight tile over PCIe, so the weight gets staged into a device buffer with one cudaMemcpyAsync first (then it's a flat +56ms, one pass of 888 MiB). And clip.cpp sets threads only on backend_cpu, so a projector on any other backend silently runs on 4 threads.
886 MiB freed, encode +5-16%, output byte-identical, LLM speed untouched - this is a beast for me) Already running OCR tests for the past 6hrs with --spec-draft-type-k kvarn2 --spec-draft-type-v kvarn2 --mmproj-host-weights on my production dataset and everything is 100% correct.
Follow-up: I ported the remaining low-risk fixes, adapted to the current v0.4.5 cache and checkpoint architecture.
Changes:
Padded and initialized the CUDA probability tile for the physical eight-row ldmatrix read. This fixes the second D256/GQA6 out-of-bounds case.
Corrected compact-tail rollback capability reporting and clamped KVarN’s guaranteed exact rollback to one 128-token record.
Replaced per-tail-entry cache scans with one ordinal pass per stream.
Changed MTP draft rollback to use ckpt.n_tokens, with widened-removal and full-clear recovery instead of aborting.
Applied MTMD thread counts to every distinct scheduler backend that supports them.
Real Qwen3.6-27B MTP/KVarN4 tests on an RTX 3090 showed:
16K decode: 58.78 → 60.05 tok/s mean
64K decode: 45.90 → 46.39 tok/s
Hot checkpoint reprocessing: 178.21 → 200.18 tok/s median
Identical output across five repeated requests and all 64K comparisons
The pre-port build hit one illegal memory access and one illegal instruction in eight 16K attempts; the updated build completed 8/8 without CUDA or rollback errors. This is encouraging but not enough to claim every intermittent CUDA failure is resolved.
I deferred two parts:
KVarN MTP draft caches: needs a deeper architectural work to implement KVarN for speculative model, and the reported first-request divergence at a specific depth remains unexplained. The rollback and CUDA prerequisites are now fixed, but this still needs dedicated correctness testing before enabling it.
Pinned-host mmproj weights: the proposed implementation is tied to CUDA device 0 and stages a broader class of host weights than intended. It needs a per-device buffer type, exact buffer identity checks, and a concurrent-request reproducer, so it belongs in a separate backend/MTMD change.
Ran a fairly detailed characterization of the v0.4.5 KVarN decode path on hardware quite different from yours, and got a result that contradicts the "faster than Q8 on large context" claim, so it seems worth reporting.
Setup. 2x CMP 90HX (sm_86, 50 SM, 10 GiB each, GDDR6X 760 GB/s), GPU0 on PCIe Gen1 x16, GPU1 on Gen1 x1, host is an i5-650 with 7.6 GiB RAM. Model: Tiel-Coder-35B-A3B (qwen35moe, 40 blocks, MoE 256/8, full attention on every 4th layer only, GQA 8, D=256, 2 KV heads), UD-Q3_K_XL, -ngl 41 -ts 22/19 -fa on -b 2048 -ub 512. Built from source, sm_86 only.
+19% at 131k. Split-128 geometry is selected correctly at depth.
But plain types are ~2x faster at depth here:
depth
kvarn5/kvarn4
q6_0/q5_0
0
65.69
64.06
32768
36.22
52.99
131072
14.13
30.21
Identical at zero depth, 2.1x apart at 131k.
Bit width has no effect on speed at all (d=131072, -r 3): kvarn5/kvarn4 14.06 +- 0.33, kvarn4/kvarn4 14.22 +- 0.42, kvarn3/kvarn3 14.19 +- 0.39. kvarn3 moves 40% fewer bytes than kvarn5 and runs at the same speed, so neither unpack cost nor KV bandwidth appears to be the limiter.
Occupancy is not the limiter either. Overriding GGML_CUDA_FATTN_KVARN_DECODE_MIN_BLOCKS at d=131072: 4 -> 14.13 (4 blocks/SM, 11 waves), 5 -> 13.79 (5, 9), 6 -> 12.52 (5, 9). More resident blocks and fewer waves, consistently slower - register spills outweigh it. Your default of 4 is optimal here too.
Nothing is saturated during generation (d=32768, nvidia-smi dmon, generation phase): kvarn 36.5 t/s with sm 30%/72% and rx 72/99 MB/s; q6_0/q5_0 53.8 t/s with sm 25%/79% and rx 112/132 MB/s. Per token both push ~2.5 MB to GPU1. The faster configuration moves more data, so the x1 link is not the constraint. Looks latency/serialization bound rather than resource bound.
A coalesced-staging experiment, in case it is useful. Since the comment before the V loop names collective coalesced staging as the fix, I tried it: stage the K pass window and each V chunk into shared with aligned word/uint4 copies, unpack from shared, gated to D==256 && Q_TILE==1, with p_sh and q_sh reused as the staging buffers so shared stays under the 4-blocks/SM threshold. It builds, and output is bit-identical to unpatched (temp 0, fixed seed, 200 tokens). It gives no speedup here: 14.26 +- 0.39 -> 14.00 +- 0.36 at d=131072. Consistent with the bit-width result - if the kernel were memory-bound this should have moved something. Happy to post the diff if you want it as a starting point; on a 3090 where L1 may actually be the constraint it might behave differently.
Net: on this hardware the KVarN decode path seems bound by something that scales with n_kv but not with bytes moved or with occupancy. Everything I could test from the outside came back negative, so I am out of ideas that do not need ncu.
Full config below. Two unusual things about this box that are probably worth knowing up front: the compute unlock, and a local cherry-pick - so it is not a stock build.
Build (v0.4.5 preview at db621636, later updated to d19abea67), CUDA 12.4, g++-12:
One local commit on top: the half2 KQ accumulator for fattn-tile.cuh from Rhonstin/llama-cpp-cmp90hx, sm_86 only. The DP4A->IMAD half of that patch is deliberately not applied - see the unlock note below.
--override-tensor moves block 21's FFN to CUDA1 to even out the halves at this context size; llama-fit-params produced it. --cache-ram is pinned low because the host only has 7.6 GiB.
About the x1 link. GPU0 is Gen1 x16, GPU1 negotiated Gen1 x1 (downgraded, LnkCap says x16 on both). I suspected the same thing, so I measured it during the generation phase with nvidia-smi dmon -s ut at d=32768:
Per token both push about 2.5 MB to GPU1, and the faster configuration moves more data, so the link does not look like the binding constraint here - 132 MB/s against a practical x1 Gen1 ceiling near 250. That said, an earlier sample I took accidentally landed in the prefill phase and showed a sustained 207 MB/s on GPU1, so the link is definitely close to saturation during prefill, just not during decode.
About the unlock. The card runs the cmpunlocker rejoin15 profile on NVIDIA Open 610.43.03, which lifts the CMP compute throttles. Relevant because the well-known DP4A->IMAD workaround for these cards is a 32% generation regression once compute is unlocked: with that hunk as the only difference, tg128 on Qwen3.8-9B went 86.2 t/s without it versus 65.2 t/s with it. So if any of this looks unlike other CMP 90HX reports, that is likely why.
Appreciate that you are merging this change into v0.4.5, however I have tested it and it's not giving the same t/g speed boosts at high context as beellama-kvarn.
Something seems messed up. I can't even start using Q8_0 draft KV in latest version.
The same launch args that used to have a few GB memory unused now will OOM on launch.
VRAM consumption before error:
GPU1: 14.7
GPU2: 13.3
For your convenience, this is the pre-update VRAM consumption using Q8_0 from previous comment:
GPU-1 13.5GB
GPU-2 13.1GB
00:00.07 W DEPRECATED: --mmap and --no-mmap are deprecated. use --load-mode mmap instead
00:00.08 I cmn common_param: common_params_print_info: verbosity = 3 (adjust with the `-lv N` CLI arg)
00:00.15 I cmn common_specu: DFlash: omitted --spec-draft-n-max defaults to the drafter block depth (7); pass the flag to override
00:00.15 I srv load_model: loading model 'A:\models\Qwen3.8-27B-Cold-Fusion-GAIN-V1.1-NVFP4-MID-HIGH.gguf'
00:00.88 W model has unused tensor blk.64.attn_norm.weight (size = 20480 bytes) -- ignoring
00:00.88 W model has unused tensor blk.64.post_attention_norm.weight (size = 20480 bytes) -- ignoring
00:00.88 W model has unused tensor blk.64.attn_q.weight (size = 66846720 bytes) -- ignoring
00:00.88 W model has unused tensor blk.64.attn_k.weight (size = 5570560 bytes) -- ignoring
00:00.88 W model has unused tensor blk.64.attn_v.weight (size = 5570560 bytes) -- ignoring
00:00.88 W model has unused tensor blk.64.attn_output.weight (size = 33423360 bytes) -- ignoring
00:00.88 W model has unused tensor blk.64.attn_q_norm.weight (size = 1024 bytes) -- ignoring
00:00.88 W model has unused tensor blk.64.attn_k_norm.weight (size = 1024 bytes) -- ignoring
00:00.88 W model has unused tensor blk.64.ffn_gate.weight (size = 94699520 bytes) -- ignoring
00:00.88 W model has unused tensor blk.64.ffn_down.weight (size = 94699520 bytes) -- ignoring
00:00.88 W model has unused tensor blk.64.ffn_up.weight (size = 94699520 bytes) -- ignoring
00:00.88 W model has unused tensor blk.64.nextn.eh_proj.weight (size = 55705600 bytes) -- ignoring
00:00.88 W model has unused tensor blk.64.nextn.enorm.weight (size = 20480 bytes) -- ignoring
00:00.88 W model has unused tensor blk.64.nextn.hnorm.weight (size = 20480 bytes) -- ignoring
00:00.88 W model has unused tensor blk.64.nextn.shared_head_norm.weight (size = 20480 bytes) -- ignoring
00:07.21 W llama_init_from_model: KVarN requires Flash Attention; enabling it
00:07.42 I cmn init: llama threadpool init, n_threads = 6
00:07.60 I common_speculative_init_result: loading draft model 'A:\models\Qwen3.8-27B-DFlash2-Q4_K_M-rope-fixed.gguf'
00:08.56 W llama_kv_cache_iswa: using full-size SWA cache (ref: https://github.com/ggml-org/llama.cpp/pull/13194#issuecomment-2868343055)
S:\beellama.cpp-branch\ggml\src\ggml-backend.cpp:180: GGML_ASSERT(buffer) failed
00:08.73 E ggml_backend_cuda_buffer_type_alloc_buffer: allocating 887.99 MiB on device 0: cudaMalloc failed: out of memory
00:08.73 E alloc_tensor_range: failed to allocate CUDA0 buffer of size 931127936
[Process exited with code: -1073740791]
@Anbeeld In my last test, I saw that the decode speed drop to ~10 t/s (from normal ~60t/s) after reading an image. I remember this bug happens during the DFlash2 (before finally merged). Not sure if you can reproduced this.
KV cache accuracy: a small but reproducible gap between builds
I ran a KL-divergence sweep over ten cache configurations to sanity-check my own patch stack, and ended up with a difference on the KVarN cache types that I cannot attribute to anything in particular. Posting the numbers in case they are useful — the tail behaviour especially looks like it deserves a closer look than I can give it.
Setup
Model
Qwen3.8-27B UD-Q5_K_M (unsloth)
GPU
RTX 3090, 24 GiB
Corpus
wikitext-2 raw test, -c 65536, all 4 chunks
Reference
one shared f16/f16 logits file, computed once
Tail
--kv-tail-tokens 1024 on every kvarn row; q8_0 measured without a tail
preview-v0.4.4 (a749684) plus a local patch stack, ggml 0.20.2
Both builds were measured against the same reference logits. Measuring each build against its own f16 baseline would cancel out exactly the difference being looked for.
Control. Running the published image on an unquantised cache against that shared reference returns zeros:
run
median KLD
99.9% KLD
same top p
published image, f16 / f16
−0.000000
0.000052
99.998 %
So the two builds are numerically identical where no KVarN code executes, and everything below can be attributed to the cache path rather than to the build.
My fork
cache (K / V)
median KLD
99.9% KLD
same top p
q8_0 / q8_0 (no tail)
0.000519
0.043894
98.421 %
kvarn8 / kvarn8
0.000498
0.044939
98.447 %
kvarn6 / kvarn6
0.000505
0.039026
98.470 %
kvarn5 / kvarn5
0.000532
0.040410
98.462 %
kvarn4 / kvarn4
0.000622
0.049648
98.283 %
kvarn4 / kvarn3
0.000735
0.059107
98.154 %
kvarn3 / kvarn3
0.000995
0.095204
97.781 %
kvarn4 / kvarn2
0.001892
0.152836
97.124 %
kvarn2 / kvarn2
0.003792
0.420379
95.561 %
Published image
cache (K / V)
median KLD
99.9% KLD
same top p
q8_0 / q8_0 (no tail)
0.000519
0.043894
98.421 %
kvarn8 / kvarn8
0.000514
0.044353
98.432 %
kvarn6 / kvarn6
0.000524
0.042906
98.411 %
kvarn5 / kvarn5
0.000549
0.044596
98.378 %
kvarn4 / kvarn4
0.000636
0.053835
98.275 %
kvarn4 / kvarn3
0.000753
0.061927
98.109 %
kvarn3 / kvarn3
0.000995
0.087188
97.787 %
kvarn4 / kvarn2
0.001924
0.150618
97.067 %
kvarn2 / kvarn2
0.003792
0.420607
95.571 %
Difference
Negative means my build sits closer to the shared reference.
cache (K / V)
median KLD
99.9% KLD
same top p
q8_0 / q8_0 (no tail)
+0.0 %
+0.0 %
+0.000 pp
kvarn8 / kvarn8
-3.1 %
+1.3 %
+0.015 pp
kvarn6 / kvarn6
-3.6 %
-9.0 %
+0.059 pp
kvarn5 / kvarn5
-3.1 %
-9.4 %
+0.084 pp
kvarn4 / kvarn4
-2.2 %
-7.8 %
+0.008 pp
kvarn4 / kvarn3
-2.4 %
-4.6 %
+0.045 pp
kvarn3 / kvarn3
+0.0 %
+9.2 %
-0.006 pp
kvarn4 / kvarn2
-1.7 %
+1.5 %
+0.057 pp
kvarn2 / kvarn2
+0.0 %
-0.1 %
-0.010 pp
What I think is worth a look
On the median my build is equal or better on every row, by up to 3.6 %.
On the 99.9 % tail it goes both ways: my build is 8–9 % better on kvarn6, kvarn5 and kvarn4, and the published image is 9.2 % better on kvarn3/kvarn3. A difference that changes sign across bit widths looks more like a code path that is only taken at some widths than like a uniform accuracy difference.
The numbers are deterministic, not sampling noise: q8_0, kvarn3/kvarn3 and kvarn2/kvarn2 produced bit-identical medians on both builds.
@valujin Thanks for the detailed measurements. I reproduced and isolated the difference.
Root cause
The difference is caused by 286b31de5 in v0.4.5, which changed the default CUDA KVarN prefill materialization window from 65,536 to 32,768 tokens:
GGML_CUDA_FATTN_KVARN_WINDOW_CHUNK = 32768
Your v0.4.4-based build uses the 64K window, while the published v0.4.5 image uses 32K. Above 32K, v0.4.5 divides KVarN prefill attention into multiple windows and merges their online-softmax maximum, numerator, and denominator. This is mathematically equivalent, but changes floating-point reduction order. The result is deterministic, and its direction can vary by cache width, which explains why some of your p99.9 rows improve while others regress.
I confirmed this with v0.4.3, v0.4.4 and v0.4.5 using the same model and shared BF16 reference. Setting:
GGML_KVARN_WINDOW_CHUNK=65536
made v0.4.5 reproduce v0.4.3 exactly across homogeneous KVarN2 through KVarN8, including mean, median, p99.9 KLD, and same-top probability. For example:
KVarN4
Mean KLD
Median
p99.9
Same top
v0.4.3, 64K
0.002800
0.000866
0.064021
98.179%
v0.4.5, 32K
0.002974
0.000867
0.055475
98.198%
v0.4.5 forced to 64K
0.002800
0.000866
0.064021
98.179%
This rules out a width-specific KVarN quantization or storage change.
Why it was changed
I also checked the original development session. The 32K default was introduced defensively during a two-slot, 128K-cache stress test. A full 65,536-token FP16 K/V materialization window was suspected of putting too much pressure on transient CUDA scratch memory.
However, that diagnosis was not established:
There was no recorded CUDA out-of-memory error or measured scratch exhaustion.
Failures continued after switching to 32K.
The actual KVarN illegal-access defect was later traced to compact-plan physical record ordering.
The 32K path was validated with a 3e-4 RMSE tolerance and an identical deterministic output hash, but no KLD sweep was performed.
Resolution
I restored the 65,536-token default for v0.4.6 in b27c886f3. This avoids the additional partial-softmax merge through 64K contexts and restores the earlier numerical partitioning.
As a brief current-build check using Qwen3.8-27B UD-Q4_K_M at context 40,960, KVarN4 with the restored 64K window had lower mean, median, and p99.9 KLD than v0.4.4, with a slightly higher same-top rate. The change also passes the CUDA KVarN parity test and the updated source-policy regression.
The projector weights in pinned host memory (--mmproj-host-weights) it's a must, I didn't see any drop on performance but saving almost 1GB of VRAM it's just incredible.
The --mmproj-host-weights is highly anticipated! Unfortunate for it to require such complex implementation. It really is a silver bullet which recovers precious 1GB of VRAM for negligible performance loss.
As a point of reference, the vanilla CPU mmproj offload is so painful and exhibits extreme slowdowns with big images (even up to 200 seconds on the 7950x3D) - I wasted days to find optimizations, testing various CPU core masks, thread pinning, thread numbers etc.
Finally ended up with a Frankenstein build with CUDA for text and ROCm for the image processing on the AMD iGPU, got 200s -> 140s on my big test image. Further batching modification from hard-coded 64 to 32, made the severely limited iGPU (just 2 compute units) generate around 40 image tokens per second from the initial 12 on the CPU (still nowhere near the 1500 tps of the 4090... but than wastes ~1GB of memory that should go to better quality KV cache).
Currently I'm on exllama for the 2gb smaller models, but really miss KVarN, and this --mmproj-host-weights feature would tip the scales in favor of Beellama.
Activity
Anbeeld commentedon Aug 29, 2026
Looks interesting, I'll check it out. Thanks!
munchmunch77 commentedon Aug 31, 2026
Please look into this, I just tested and my results are even better than OP's.
Just confirm that his implementation does not affect KLD in any significant way.
Arien02 commentedon Sep 1, 2026
I second this too, tested with rtx3090 and Qwen3.8-27B-UD-Q4_K_XL.gguf and I can confirm it's the fastest llama implementation so far.
And another discovering, latest v0.4.4 it's slower than v0.4.3 for my setup, don't know why but something it's loosing TPS...
Anbeeld commentedon Sep 1, 2026
Ported most of the changes, additionally adapting them to v0.4.4 changes that landed closer to release.
Performance is indeed better, especially with multiple slots.
Please test it thoroughly on the v0.4.5 branch, especially in terms of stability, correctness, and edge cases.
AI-written implementation details and benchmarks
Completed a port of the KVarN correctness and CUDA decode work from
valujin/beellama-kvarnonto the current v0.4.5 architecture.The main port landed in
72bace072(Optimize KVarN CUDA decode paths). The final long-context compact-plan, windowing, and stage-slot follow-up described below is currently in the local candidate and has not yet been committed.The implementation was adapted rather than cherry-picked because the optimization fork was based on an older v0.4.4 tree and its allocator, stage ownership, cache state, and CUDA routing differ materially from current v0.4.5.
What was implemented
1. Compact-plan lifecycle correctness
The cached indirect KVarN read plan is now invalidated whenever its source cache metadata can change:
llama_kv_cache_kvarn_context::next()llama_kv_cache_kvarn_context::apply()Previously, a plan could survive across ubatches even though the occupied and pending physical cells had changed. That could silently produce incorrect reads depending on slot count and scheduling.
2. Safe GQA-6 CUDA query loading
The CUDA MMA path logically supports six GQA rows, but
ldmatrixphysically reads an eight-row extent.The query tile now:
This prevents out-of-bounds or uninitialized shared-memory reads without changing logical attention dimensions.
3. Compact-plan duplicate bitmap
Compact plan construction now uses a capacity-sized bitmap instead of
std::setfor duplicate filtering.It preserves:
4. Physical record-group-safe compact plans
Unified-cache ownership can interleave logical sequences while their KVarN records remain physically disjoint. A logically ordered plan could therefore look contiguous to a CUDA cooperative record loader even though its adjacent rows came from different physical records.
The final plan implementation:
-1holes within incomplete records;This is the change responsible for recovering the large two-slot performance improvement.
5. Descriptor setup optimizations
The descriptor path now includes:
The old fork treated indices more like plain physical cells. The port explicitly preserves the current v0.4.5 encoded stage-slot representation.
6. CUDA decode-kernel optimizations
The following mechanisms were ported and adapted:
Q_TILE=2/3;Unsupported shapes continue to use the descriptor-native MMA fallback rather than failing or silently changing cache interpretation.
7. Small verification-batch routing
Split decode is now eligible through
n_q <= 8.This covers common speculative verification shapes while preserving generic MMA fallback for larger batches. Multi-query split routing requires an attention mask.
A temporary
n_q <= 3experiment was rejected because it did not provide the same stability/performance balance.8. Evidence-based split geometry selection
The final selector uses:
This replaced a broader initial split-128 policy that regressed ordinary-depth workloads.
9. Bounded large-window materialization
The default KVarN materialization window was reduced from 65,536 to 32,768 tokens.
This bounds transient K/V scratch when two long prompts share a 128K cache. The partial windows retain the online-softmax maximum, numerator, and denominator and are merged afterward.
Chunked-window CUDA parity coverage was added. The accepted RMSE is
3e-4, reflecting the changed floating-point reduction order.10. Explicit replacement-stage slots in delayed sealers
The delayed high-shared, low-shared, head-wide, direct, and workspace sealing paths now use the incoming replacement group’s encoded host-assigned stage slot.
They no longer assume that a live group’s slot can always be reconstructed from its group number modulo the tail depth.
This did not explain every observed long-prefill failure because the production target uses eager record commitment, but it is a real correctness defect in the delayed paths and is retained with focused CPU/CUDA parity tests.
How this differs from the initial implementation
The first adaptation was deliberately conservative:
n_q=1..8decode/verification plans;That version improved ordinary two-slot decode, but it did not fully enforce the CUDA record-loader invariant.
Initial approach
The initial policy assumed that dense fallback was safe when alignment expansion was large. This proved false: a sparse logical plan could still place rows from separate physical records next to each other and make them look like a contiguous physical tile.
It also retained logical group order to minimize observable ordering changes.
Final approach
After reproducing failures with larger two-slot contexts, the plan was changed to:
-1;The API was simplified again after the growth policy was removed.
Other changes made during diagnosis
base()->get_ubatch()while constructing synthetic reserve graphs was fixed by using valid current slot metadata. The policy that needed that query was later removed entirely.What was not implemented
1. The old fork allocator/group-claim implementation
The implementations from the old group-claim and allocator commits were not copied.
Current v0.4.5 already has newer:
Copying the old allocator would have replaced current ownership semantics and risked regressions in rollback, state restore, MTP verification, and slot reuse.
Only the physical read-plan mechanism was adapted.
2. The old fork stage-owner implementation
The old modulo/owner stage system was not ported.
Current v0.4.5 uses explicit host-assigned stage slots encoded in cache indices. The CUDA changes were adapted to consume those assignments rather than restoring the old ownership model.
3. Wholesale cherry-picking of
54bc3d29,c3ca5bcc,432024c3b, or1b2f628caThese commits bundled mechanisms with obsolete allocator and state assumptions. They were used as architectural evidence, not treated as drop-in patches.
Additional changes not present in the optimization fork
The following work was added because it was required by current v0.4.5 or found during validation:
Verification
The final candidate was checked with:
test-kvarnCPU/CUDA parity;n_q=2..16route coverage;git diff --check.Benchmark environment
Unless noted otherwise:
a6cd1e829a8ba24a78edeb8f078b724ea7a9873856f1916e356eea5c537c0b40;f8cd4e6dd;476aa6c4b;476aa6c4b-dirty, including the follow-up physical-plan/window/stage work;The older published fork baseline was commit
a749684, not the provided v0.4.4 package. The tables below use the providedf8cd4e6ddpackage.v0.4.4 versus v0.4.5 results
16K single-slot decode
64 generated tokens:
The controls show that the ordinary-depth gain is specific to KVarN rather than a general build-wide speedup.
16K prefill
There is no material prefill change at 16K.
64K single-slot decode
Tail 1024, 64 generated tokens:
The long-context gain is larger than the 16K gain, consistent with the descriptor and split-geometry changes.
Single-slot MTP
KVarN4, tail 1024, 16K context, three trials:
Proper two-slot long-context comparison
The earlier cold-prompt server benchmark did not isolate simultaneous two-slot decode: one slot often decoded while the other was still prefilling.
The final benchmark therefore used:
--parallel 2;--kv-unified;Aggregate server-reported decode
Average per slot
Wall-clock aggregate throughput
This includes request and synchronization overhead:
Long-prompt prefill in the same trials
The large two-slot improvement is therefore a decode-path result, not a general prefill change.
The result does not exactly reproduce the fork’s published 5.9× Qwen3.8 result, but it confirms the same mechanism on a matched comparison against the provided v0.4.4 package: the final local build is approximately 4.5–4.8× faster with both long-context slots actively decoding.
valujin commentedon Sep 1, 2026
I and my AI assistant have made farther mixed optimizations and fixes that improve QoL significantly for 24GB card users). Some of them are KVarN related (like MTP KV cache support and optimizations), some of them not (like VRAM free VISION with almost the same performance).
Update: what's new since the ported batch
All measured on RTX 3090 / Qwen3.8-27B-UD-Q4_K_M, ctx 212992, 4 slots,
kvarn4target cache.Bug fixes — the first two are not KVarN-specific and likely affect the base as well
Speculation checkpoint rollback was quadratic.
get_seq_rm_capability()declared a 1-token reserve thatcan_seq_rm()does not actually enforce for a structural cache. The server saw the capability as insufficient and re-serialized the entire draft cache on every speculation cycle, through a tail serializer that walks cells from zero per entry.perfshowedstate_tail_payload_slotsat 17.95% of cycles with GPU at 63%. After the fix: 42.7 → 59.4 t/s at 20k depth, GPU 63% → 99%.Draft rollback was computed on the wrong axis. The MTP draft numbers its tokens by count (
n_past), while the server required rollback tockpt.pos_max + 1— the target's position axis. These are identical on text, so it never showed. On vision models they diverge: one image is thousands of tokens but only a few positions under M-RoPE. Result:GGML_ABORTon the first image whenever the draft cache is quantized. Fixed by usingckpt.n_tokens. Verified on 15 image requests across 5 configurations, byte-identical output, zeroseq_rmrefusals.Shared-memory OOB in the KVarN decode kernel:
p_shis declared with 6 rows atMAX_GQA == 6, butload_ldmatrixreads 8. Harmless in practice, but real — fixed the same wayq_shalready was, via aP_ROWSbound.New capability
MTP draft cache on KVarN: 832 MiB f16 → 131 MiB kvarn2. This is safe by construction rather than by measurement — the draft only proposes tokens and the target verifies them with its own cache, so draft-cache error can lower acceptance but cannot corrupt output. Measured acceptance actually went up (0.875 vs 0.769). Total MTP cost 2522 → 1814 MiB.
Projector weights in pinned host memory, opt-in via
--mmproj-host-weights: frees 886 MiB of VRAM, image encode +5–16%, output byte-identical, LLM speed untouched. Off by default.One analysis that may interest ggml-org
The
devices[].integrated = falsegate (their PR ggml-org#16308) is masking a scheduler race, not a hardware limitation. llama.cpp deliberately places model input tensors in the CUDA host buffer; while CUDA reports it as unsupported, the scheduler copies those inputs to VRAM and callsggml_backend_synchronizefirst — and that copy is the only barrier between the CPU writing inputs and kernels reading them. Naively enabling host buffers removes the barrier along with the copy. The fix is a separate weights-only buffer type. Isolated by enabling the gate without moving any weights: encode time unchanged, output corrupted with the identical hash. This appears to explain the open ggml-org#25992 (server returning other sessions' answers verbatim at-np 4).On quality: none of these changes touch the target cache numerics. Verification was byte-exact output comparison at
temperature 0, single slot — stricter than KLD for this purpose. Note that at--parallel > 1response hashes are not reproducible run-to-run on this build (batching order), so multi-slot hash comparison is not a valid method.Not resolved — please treat as known
--parallel 1, depth ≈2123 and one specific prompt, the first request after start differs from all subsequent ones (the draft itself diverges). Does not reproduce at--parallel 4or at depth 20115.GGML_KVARN_SPLIT_MAX_Q=1masks it.compute-sanitizer --tool initcheckis clean, though the pool uses VMM so that is not conclusive.Anbeeld commentedon Sep 1, 2026
I'll take a look.
Does the mmproj change result in weights being in RAM but the model still being processed on GPU?
valujin commentedon Sep 1, 2026
Yeah, you got it right. mmproj is not that big and weights used once per request - PCIe link is sufficient for that. In my testing I got several percent speed reduction compared to full on GPU mmproj well known classic.
Anbeeld commentedon Sep 1, 2026
There's the
--no-mmproj-offloadoption that offloads both weights and exectution to CPU, which is safe fallback, but GPU execution is indeed better if there won't be any issues.valujin commentedon Sep 1, 2026
I know and I hate it:)
My next thought was - why no use system RAM for on GPU CUDA computation. There are two ways:
GGML_CUDA_ENABLE_UNIFIED_MEMORY- it's already implemented in original llama.cpp, correct, but only frees 456 MiB, and 328 under load. Not worth it.ggml_backend_cuda_host_buffer_type— it's already in ggml, pinned host memory that CUDA kernels read over PCIe. But it's gated behinddevices[].integrated, which is hardcoded tofalsewith a comment blaming corrupted output (Eval bug: Broken/no Gemma 3n output on CUDA (Nvidia Jetson Orin Nano) ggml-org/llama.cpp#15034).I flipped the gate and got the corruption too. Turns out it has nothing to do with weights or hardware. llama.cpp deliberately puts the model's input tensors in that same host buffer, and while CUDA reports the buft as unsupported, the scheduler is forced to copy them to VRAM with a
ggml_backend_synchronizefirst — that sync is the only barrier before the kernels read them. Open the gate and the barrier disappears together with the copy, so the next ubatch'sset_input()overwrites memory the previous one is still reading.So instead of opening the general path I added a separate weights-only buffer type, reachable only via
ggml_backend_reg_get_proc_address— model inputs can't land there, barrier stays.Two gotchas: plain zero-copy is 2.9x slower because cuBLAS re-reads each weight tile over PCIe, so the weight gets staged into a device buffer with one
cudaMemcpyAsyncfirst (then it's a flat +56ms, one pass of 888 MiB). Andclip.cppsets threads only onbackend_cpu, so a projector on any other backend silently runs on 4 threads.886 MiB freed, encode +5-16%, output byte-identical, LLM speed untouched - this is a beast for me) Already running OCR tests for the past 6hrs with
--spec-draft-type-k kvarn2 --spec-draft-type-v kvarn2 --mmproj-host-weightson my production dataset and everything is 100% correct.Anbeeld commentedon Sep 2, 2026
Follow-up: I ported the remaining low-risk fixes, adapted to the current v0.4.5 cache and checkpoint architecture.
Changes:
ldmatrixread. This fixes the second D256/GQA6 out-of-bounds case.ckpt.n_tokens, with widened-removal and full-clear recovery instead of aborting.Real Qwen3.6-27B MTP/KVarN4 tests on an RTX 3090 showed:
I deferred two parts:
Commits:
ad66e5983,6763f90c6,ca89cab4d,02b36f2db,d19abea67.loss-and-quick commentedon Sep 2, 2026
Ran a fairly detailed characterization of the v0.4.5 KVarN decode path on hardware quite different from yours, and got a result that contradicts the "faster than Q8 on large context" claim, so it seems worth reporting.
Setup. 2x CMP 90HX (sm_86, 50 SM, 10 GiB each, GDDR6X 760 GB/s), GPU0 on PCIe Gen1 x16, GPU1 on Gen1 x1, host is an i5-650 with 7.6 GiB RAM. Model: Tiel-Coder-35B-A3B (
qwen35moe, 40 blocks, MoE 256/8, full attention on every 4th layer only, GQA 8, D=256, 2 KV heads), UD-Q3_K_XL,-ngl 41 -ts 22/19 -fa on -b 2048 -ub 512. Built from source,sm_86only.v0.4.5 helps, clearly.
llama-benchtg64, kvarn5/kvarn4 +--kv-tail-tokens 1024:+19% at 131k. Split-128 geometry is selected correctly at depth.
But plain types are ~2x faster at depth here:
Identical at zero depth, 2.1x apart at 131k.
Bit width has no effect on speed at all (d=131072,
-r 3): kvarn5/kvarn4 14.06 +- 0.33, kvarn4/kvarn4 14.22 +- 0.42, kvarn3/kvarn3 14.19 +- 0.39. kvarn3 moves 40% fewer bytes than kvarn5 and runs at the same speed, so neither unpack cost nor KV bandwidth appears to be the limiter.Occupancy is not the limiter either. Overriding
GGML_CUDA_FATTN_KVARN_DECODE_MIN_BLOCKSat d=131072: 4 -> 14.13 (4 blocks/SM, 11 waves), 5 -> 13.79 (5, 9), 6 -> 12.52 (5, 9). More resident blocks and fewer waves, consistently slower - register spills outweigh it. Your default of 4 is optimal here too.Nothing is saturated during generation (d=32768,
nvidia-smi dmon, generation phase): kvarn 36.5 t/s with sm 30%/72% and rx 72/99 MB/s; q6_0/q5_0 53.8 t/s with sm 25%/79% and rx 112/132 MB/s. Per token both push ~2.5 MB to GPU1. The faster configuration moves more data, so the x1 link is not the constraint. Looks latency/serialization bound rather than resource bound.Route debug at d=131072 for reference:
A coalesced-staging experiment, in case it is useful. Since the comment before the V loop names collective coalesced staging as the fix, I tried it: stage the K pass window and each V chunk into shared with aligned word/
uint4copies, unpack from shared, gated toD==256 && Q_TILE==1, withp_shandq_shreused as the staging buffers so shared stays under the 4-blocks/SM threshold. It builds, and output is bit-identical to unpatched (temp 0, fixed seed, 200 tokens). It gives no speedup here: 14.26 +- 0.39 -> 14.00 +- 0.36 at d=131072. Consistent with the bit-width result - if the kernel were memory-bound this should have moved something. Happy to post the diff if you want it as a starting point; on a 3090 where L1 may actually be the constraint it might behave differently.Net: on this hardware the KVarN decode path seems bound by something that scales with
n_kvbut not with bytes moved or with occupancy. Everything I could test from the outside came back negative, so I am out of ideas that do not needncu.Anbeeld commentedon Sep 2, 2026
@loss-and-quick Gen1 x1, holy llama... send your full launch config please.
loss-and-quick commentedon Sep 2, 2026
Full config below. Two unusual things about this box that are probably worth knowing up front: the compute unlock, and a local cherry-pick - so it is not a stock build.
Build (v0.4.5 preview at
db621636, later updated tod19abea67), CUDA 12.4,g++-12:One local commit on top: the half2 KQ accumulator for
fattn-tile.cuhfromRhonstin/llama-cpp-cmp90hx, sm_86 only. The DP4A->IMAD half of that patch is deliberately not applied - see the unlock note below.Numbers in my previous comment came from:
Serving config (llama-swap -> llama-server):
--override-tensormoves block 21's FFN to CUDA1 to even out the halves at this context size;llama-fit-paramsproduced it.--cache-ramis pinned low because the host only has 7.6 GiB.About the x1 link. GPU0 is Gen1 x16, GPU1 negotiated Gen1 x1 (downgraded,
LnkCapsays x16 on both). I suspected the same thing, so I measured it during the generation phase withnvidia-smi dmon -s utat d=32768:Per token both push about 2.5 MB to GPU1, and the faster configuration moves more data, so the link does not look like the binding constraint here - 132 MB/s against a practical x1 Gen1 ceiling near 250. That said, an earlier sample I took accidentally landed in the prefill phase and showed a sustained 207 MB/s on GPU1, so the link is definitely close to saturation during prefill, just not during decode.
About the unlock. The card runs the
cmpunlockerrejoin15 profile on NVIDIA Open 610.43.03, which lifts the CMP compute throttles. Relevant because the well-known DP4A->IMAD workaround for these cards is a 32% generation regression once compute is unlocked: with that hunk as the only difference, tg128 on Qwen3.8-9B went 86.2 t/s without it versus 65.2 t/s with it. So if any of this looks unlike other CMP 90HX reports, that is likely why.munchmunch77 commentedon Sep 2, 2026
Appreciate that you are merging this change into v0.4.5, however I have tested it and it's not giving the same t/g speed boosts at high context as beellama-kvarn.
@84448 context
beellama 0.4.5: 21.9 t/s
beellama-kvarn: 35.5 t/s
Please also merge the latest draft KV cache kvarn quants.
Anbeeld commentedon Sep 2, 2026
@kirstenjg provide full launch configs and logs, please.
20 remaining items
fantasyz commentedon Sep 6, 2026
@Anbeeld
Something seems messed up. I can't even start using Q8_0 draft KV in latest version.
The same launch args that used to have a few GB memory unused now will OOM on launch.
VRAM consumption before error:
For your convenience, this is the pre-update VRAM consumption using Q8_0 from previous comment:
Anbeeld commentedon Sep 6, 2026
@fantasyz pushed a fix, please try it.
fantasyz commentedon Sep 6, 2026
@Anbeeld Tested for a while with some tasks. It seems working correctly now.
Anbeeld commentedon Sep 6, 2026
@fantasyz Thanks a lot for testing.
I'm probably wrapping up v0.4.5 on that. Huge patch already, a lot of good work done. Big props to @valujin, really.
Will look into remaining stuff in v0.4.6
fantasyz commentedon Sep 6, 2026
@Anbeeld In my last test, I saw that the decode speed drop to ~10 t/s (from normal ~60t/s) after reading an image. I remember this bug happens during the DFlash2 (before finally merged). Not sure if you can reproduced this.
Anbeeld commentedon Sep 6, 2026
@fantasyz Pushed a fix, please check it out.
fantasyz commentedon Sep 6, 2026
@Anbeeld It works now. 👍
Anbeeld commentedon Sep 6, 2026
valujin commentedon Sep 7, 2026
KV cache accuracy: a small but reproducible gap between builds
I ran a KL-divergence sweep over ten cache configurations to sanity-check my own patch stack, and ended up with a difference on the KVarN cache types that I cannot attribute to anything in particular. Posting the numbers in case they are useful — the tail behaviour especially looks like it deserves a closer look than I can give it.
Setup
-c 65536, all 4 chunks--kv-tail-tokens 1024on every kvarn row;q8_0measured without a tailghcr.io/anbeeld/beellama.cpp:server-cuda13, digestsha256:1fc70cd5c63db690…, reports0.4.5 (build 0, commit unknown-dirty), ggml 0.22.0preview-v0.4.4(a749684) plus a local patch stack, ggml 0.20.2Both builds were measured against the same reference logits. Measuring each build against its own f16 baseline would cancel out exactly the difference being looked for.
Control. Running the published image on an unquantised cache against that shared reference returns zeros:
f16/f16So the two builds are numerically identical where no KVarN code executes, and everything below can be attributed to the cache path rather than to the build.
My fork
q8_0/q8_0(no tail)kvarn8/kvarn8kvarn6/kvarn6kvarn5/kvarn5kvarn4/kvarn4kvarn4/kvarn3kvarn3/kvarn3kvarn4/kvarn2kvarn2/kvarn2Published image
q8_0/q8_0(no tail)kvarn8/kvarn8kvarn6/kvarn6kvarn5/kvarn5kvarn4/kvarn4kvarn4/kvarn3kvarn3/kvarn3kvarn4/kvarn2kvarn2/kvarn2Difference
Negative means my build sits closer to the shared reference.
q8_0/q8_0(no tail)kvarn8/kvarn8kvarn6/kvarn6kvarn5/kvarn5kvarn4/kvarn4kvarn4/kvarn3kvarn3/kvarn3kvarn4/kvarn2kvarn2/kvarn2What I think is worth a look
kvarn6,kvarn5andkvarn4, and the published image is 9.2 % better onkvarn3/kvarn3. A difference that changes sign across bit widths looks more like a code path that is only taken at some widths than like a uniform accuracy difference.q8_0,kvarn3/kvarn3andkvarn2/kvarn2produced bit-identical medians on both builds.Anbeeld commentedon Sep 7, 2026
@valujin Thanks for the detailed measurements. I reproduced and isolated the difference.
Root cause
The difference is caused by
286b31de5in v0.4.5, which changed the default CUDA KVarN prefill materialization window from 65,536 to 32,768 tokens:Your v0.4.4-based build uses the 64K window, while the published v0.4.5 image uses 32K. Above 32K, v0.4.5 divides KVarN prefill attention into multiple windows and merges their online-softmax maximum, numerator, and denominator. This is mathematically equivalent, but changes floating-point reduction order. The result is deterministic, and its direction can vary by cache width, which explains why some of your p99.9 rows improve while others regress.
I confirmed this with v0.4.3, v0.4.4 and v0.4.5 using the same model and shared BF16 reference. Setting:
made v0.4.5 reproduce v0.4.3 exactly across homogeneous KVarN2 through KVarN8, including mean, median, p99.9 KLD, and same-top probability. For example:
This rules out a width-specific KVarN quantization or storage change.
Why it was changed
I also checked the original development session. The 32K default was introduced defensively during a two-slot, 128K-cache stress test. A full 65,536-token FP16 K/V materialization window was suspected of putting too much pressure on transient CUDA scratch memory.
However, that diagnosis was not established:
3e-4RMSE tolerance and an identical deterministic output hash, but no KLD sweep was performed.Resolution
I restored the 65,536-token default for v0.4.6 in
b27c886f3. This avoids the additional partial-softmax merge through 64K contexts and restores the earlier numerical partitioning.As a brief current-build check using Qwen3.8-27B UD-Q4_K_M at context 40,960, KVarN4 with the restored 64K window had lower mean, median, and p99.9 KLD than v0.4.4, with a slightly higher same-top rate. The change also passes the CUDA KVarN parity test and the updated source-policy regression.
thesantiagosp commentedon Sep 13, 2026
The projector weights in pinned host memory (--mmproj-host-weights) it's a must, I didn't see any drop on performance but saving almost 1GB of VRAM it's just incredible.
aand18 commentedon Sep 22, 2026
Amazing progress week after week, love to see it!
The --mmproj-host-weights is highly anticipated! Unfortunate for it to require such complex implementation. It really is a silver bullet which recovers precious 1GB of VRAM for negligible performance loss.
As a point of reference, the vanilla CPU mmproj offload is so painful and exhibits extreme slowdowns with big images (even up to 200 seconds on the 7950x3D) - I wasted days to find optimizations, testing various CPU core masks, thread pinning, thread numbers etc.
Finally ended up with a Frankenstein build with CUDA for text and ROCm for the image processing on the AMD iGPU, got 200s -> 140s on my big test image. Further batching modification from hard-coded 64 to 32, made the severely limited iGPU (just 2 compute units) generate around 40 image tokens per second from the initial 12 on the CPU (still nowhere near the 1500 tps of the 4090... but than wastes ~1GB of memory that should go to better quality KV cache).
Currently I'm on exllama for the 2gb smaller models, but really miss KVarN, and this
--mmproj-host-weightsfeature would tip the scales in favor of Beellama.Anbeeld commentedon Sep 27, 2026
--mmproj-host-weights is the only thing that's left, and it's moving to #179