Skip to content

Slow prefill on small KV quants fixed - #27140

Open
Cybertiron wants to merge 1 commit into
ggml-org:masterfrom
Cybertiron:fix-27109-quant-kv-fp16
Open

Cybertiron wants to merge 1 commit into
ggml-org:masterfrom
Cybertiron:fix-27109-quant-kv-fp16

Conversation

@Cybertiron

@Cybertiron Cybertiron commented Aug 15, 2026 •

Copy link
Copy Markdown

Overview

I found an issue with quants, that they become very slow on prefill. Later I googled the exact issue. Found out that q_8 is working perfectly fine, but it did not compress enough memory for single gpu to use newest qwen 3.8 model. Tested each quant individually to get results, which were unsatisfactory:

All "after" numbers measured at the same ~9000 token prompt for a fair comparison. Before the fix the small quants collapse and time out at long prompts, so those are at shorter prompts:

KV before after (~9000 tok prompt)
q4_0 74 t/s 1182 t/s
q4_1 ~157 1175
q5_0 slow / timeout 1167
q5_1 125 1164
q8_0 1159 (already fast) 1159

At equal prompt length all quant KV types now run within ~2% of each other, so the fix makes them all as fast as q8_0.

Than tried reverse engineer to find the problem with opus 4.8. Because it is working on q_8 i decided that the fix will be easy, as AI can find patterns and apply similar patterns for smaller quants. q4_0 was successfull from the start, later I ran into issues with q4_1, q5_0, q5_1. It took several hours to recompile them (they also need GGML_CUDA_FA_ALL_QUANTS=ON to be enabled), but the issue was fixed. After re-testing at the same prompt length all quants run at about the same speed. Still though I think there is room for improvement, but for maximum memory squeeze and performance q4_0 looks like the sweet spot for now. For a little bit better quality use q8_0, or q5_1 which sits between q4_0 and q8_0 in quality.

Additional information

Fixes #27109. Tested on 2x RTX 3090 with Qwen 3.8 27B, outputs are numerically correct.

llama.cpp prebuild for rtx 3090 lower Quants fast prefill fix (if you don't want to compile): https://github.com/Cybertiron/llama.cpp/releases/tag/b27109-quant-kv-fix

Requirements

  • I have read and agree with the contributing guidelines
  • AI usage disclosure: YES - the CUDA kernel code was written with AI (Opus 4.8). I found the problem, directed the debugging and tested/verified everything myself on my own 2x RTX 3090.

@Cybertiron
Cybertiron requested a review from a team as a code owner August 15, 2026 16:26
@github-actions github-actions Bot added ggml changes relating to the ggml tensor library for machine learning CUDA Related to the CUDA backend labels Aug 15, 2026
@ggml-gh-bot

ggml-gh-bot Bot commented Aug 15, 2026

Copy link
Copy Markdown

Hi @Cybertiron, thanks for your contribution!

Per our contribution guidelines, the automated PR checker found the following issue(s) that need your attention:

  • PR Template not respected: Please respect the template when creating a new pull request. Make sure to fill out all required sections.

  • AI-generated content: While code is allowed to be generated by AI, please write the PR description and commit messages on your own without the help of AI.


Please note that maintainers reserve the right to make final decisions on PRs. If you believe there is a mistake, please comment below.

@ggml-gh-bot ggml-gh-bot Bot added the draft PR will be changed to draft by github-actions bot label Aug 15, 2026
@github-actions
github-actions Bot marked this pull request as draft August 15, 2026 16:30
@github-actions github-actions Bot removed the draft PR will be changed to draft by github-actions bot label Aug 15, 2026
@Cybertiron
Cybertiron marked this pull request as ready for review August 15, 2026 16:52
@Cybertiron
Cybertiron force-pushed the fix-27109-quant-kv-fp16 branch from 428ae50 to 665dac0 Compare August 15, 2026 16:52
@Cybertiron Cybertiron changed the title CUDA: dedicated q4/q5 -> f16 dequant kernels for flash-attention (fixes #27109) Slow prefill on small KV quants fixed Aug 15, 2026
@2048khz-gachi-rmx

2048khz-gachi-rmx commented Aug 15, 2026 •

Copy link
Copy Markdown

seems to work on a 3090

# b10442, cuda 12
# note `-ctk q8_0 -ctv q4_0 -ctkd q8_0 -ctvd q8_0`
[DEBUG] <qwen3.8-27b-mtp-q5-m> Executing start command: C:/Software/llama_cpp/llama-server.exe --host 0.0.0.0 --port 5824 -m C:/Software/LM Studio Models/Qwen3.8-27B-Q5_K_M.gguf -c 56000 --swa-checkpoints 32 --checkpoint-min-step 1024 -np 1 --no-warmup --load-mode dio -ngl 999 -fa on --reasoning-preserve --kv-unified -ctk q8_0 -ctv q4_0 -ctkd q8_0 -ctvd q8_0 --spec-type draft-mtp,ngram-mod --spec-draft-n-max 3 --spec-ngram-mod-n-min 16 --spec-ngram-mod-n-max 64 --temp 0.6 --top-k 20 --top-p 0.95 --min-p 0 --presence-penalty 0.0

0.44.294.807 I slot print_timing: id  0 | task 0 | prompt eval time =   14020.22 ms /  2342 tokens (    5.99 ms per token,   167.04 tokens per second)
0.44.294.813 I slot print_timing: id  0 | task 0 |        eval time =   20039.11 ms /   657 tokens (   30.55 ms per token,    32.74 tokens per second)
0.44.294.814 I slot print_timing: id  0 | task 0 |       total time =   34059.33 ms /  2999 tokens
0.44.294.815 I slot print_timing: id  0 | task 0 |    graphs reused =        154
0.44.294.855 I slot print_timing: id  0 | task 0 | draft acceptance = 0.74962 (  497 accepted /   663 generated), mean len =  4.11
0.44.304.705 I slot      release: id  0 | task 0 | stop processing: n_tokens = 3000, truncated = 0
# from https://github.com/Cybertiron/llama.cpp/releases/tag/b27109-quant-kv-fix
# cuda 13, but otherwise same flags
[DEBUG] <qwen3.8-27b-mtp-q5-m> Executing start command: C:/Software/llama_cpp_q5/llama-server.exe --host 0.0.0.0 --port 5824 -m C:/Software/LM Studio Models/Qwen3.8-27B-Q5_K_M.gguf -c 56000 --swa-checkpoints 32 --checkpoint-min-step 1024 -np 1 --no-warmup --load-mode dio -ngl 999 -fa on --reasoning-preserve --kv-unified -ctk q8_0 -ctv q4_0 -ctkd q8_0 -ctvd q8_0 --spec-type draft-mtp,ngram-mod --spec-draft-n-max 3 --spec-ngram-mod-n-min 16 --spec-ngram-mod-n-max 64 --temp 0.6 --top-k 20 --top-p 0.95 --min-p 0 --presence-penalty 0.0

# also much faster TG???
0.28.095.941 I slot print_timing: id  0 | task 0 | prompt eval time =    2866.25 ms /  2342 tokens (    1.22 ms per token,   817.10 tokens per second)
0.28.095.946 I slot print_timing: id  0 | task 0 |        eval time =   15007.52 ms /   845 tokens (   17.78 ms per token,    56.24 tokens per second)
0.28.095.947 I slot print_timing: id  0 | task 0 |       total time =   17873.77 ms /  3187 tokens
0.28.095.947 I slot print_timing: id  0 | task 0 |    graphs reused =        212
0.28.095.974 I slot print_timing: id  0 | task 0 | draft acceptance = 0.74140 (  625 accepted /   843 generated), mean len =  3.84
0.28.096.096 I slot      release: id  0 | task 0 | stop processing: n_tokens = 3189, truncated = 0

cool stuff

@Cybertiron

Cybertiron commented Aug 15, 2026 •

Copy link
Copy Markdown
Author

I think you got a bit slow token generation. Maybe you did not get out of error?

@2048khz-gachi-rmx

2048khz-gachi-rmx commented Aug 15, 2026 •

Copy link
Copy Markdown

I think you got a bit slow token generation. Maybe you did not get out of error?

here's a bit of a cleaner experiment

# b10448, cuda 13
# this time, no speculative at all, smaller context, smaller quant to ensure we fit in VRAM. still -ctk q8_0 -ctv q4_0
[DEBUG] <qwen3.8-27b-q4-xl> Executing start command: C:/Software/llama_cpp_cuda13/llama-server.exe --host 0.0.0.0 --port 5825 -m C:/Software/LM Studio Models/Qwen3.8-27B-UD-Q4_K_XL.gguf -c 32000 --swa-checkpoints 32 --checkpoint-min-step 1024 -np 1 --no-warmup --load-mode dio -ngl 999 -fa on --reasoning-preserve --kv-unified -ctk q8_0 -ctv q4_0 --temp 0.6 --top-k 20 --top-p 0.95 --min-p 0 --presence-penalty 0.0

1.00.958.295 I slot print_timing: id  0 | task 0 | prompt eval time =   13556.62 ms /  2342 tokens (    5.79 ms per token,   172.76 tokens per second)
1.00.958.301 I slot print_timing: id  0 | task 0 |        eval time =   41133.71 ms /   861 tokens (   47.83 ms per token,    20.91 tokens per second)
1.00.958.302 I slot print_timing: id  0 | task 0 |       total time =   54690.33 ms /  3203 tokens
1.00.958.303 I slot print_timing: id  0 | task 0 |    graphs reused =        856
1.00.958.657 I slot      release: id  0 | task 0 | stop processing: n_tokens = 3202, truncated = 0

# also pegs my CPU to 100%
# same release: https://github.com/Cybertiron/llama.cpp/releases/tag/b27109-quant-kv-fix
[DEBUG] <qwen3.8-27b-q4-xl> Executing start command: C:/Software/llama_cpp_q5/llama-server.exe --host 0.0.0.0 --port 5825 -m C:/Software/LM Studio Models/Qwen3.8-27B-UD-Q4_K_XL.gguf -c 32000 --swa-checkpoints 32 --checkpoint-min-step 1024 -np 1 --no-warmup --load-mode dio -ngl 999 -fa on --reasoning-preserve --kv-unified -ctk q8_0 -ctv q4_0 --temp 0.6 --top-k 20 --top-p 0.95 --min-p 0 --presence-penalty 0.0

0.23.717.021 I slot print_timing: id  0 | task 0 | prompt eval time =    2374.01 ms /  2342 tokens (    1.01 ms per token,   986.52 tokens per second)
0.23.717.025 I slot print_timing: id  0 | task 0 |        eval time =   15163.29 ms /   552 tokens (   27.52 ms per token,    36.34 tokens per second)
0.23.717.026 I slot print_timing: id  0 | task 0 |       total time =   17537.30 ms /  2894 tokens
0.23.717.026 I slot print_timing: id  0 | task 0 |    graphs reused =        548
0.23.717.103 I slot      release: id  0 | task 0 | stop processing: n_tokens = 2893, truncated = 0

# uses around 15% of cpu, not sure what's up with that
# UPD: probably this https://github.com/ggml-org/llama.cpp/discussions/22238#discussioncomment-17379870

same exact model, same exact settings, just different executables; your branch is much faster.
as #27109 noted, this only happens if key quant != value quant or unsupported quants are used; if i use q8_0 for both, i get good speeds (similar-ish to your branch)
though why decode speed gets affected as well i dont know either

@Cybertiron

Copy link
Copy Markdown
Author

Thank you for sharing your settings! Here what I use - but not this is with my fix build from my repo https://github.com/Cybertiron/llama.cpp/releases/tag/b27109-quant-kv-fix not mainline llama.cpp build. On not yet fixed mainline llama.cpp you should use only -ctk q8_0 -ctv q8_0 (mixed/small quant KV falls back to CPU there and gets slow). My setup on a single RTX 3090:

  • Qwen3.8-27B-UD-Q4_K_XL, 1 GPU (Windows desktop is on the same card), ctx 192K
  • KV cache K q5_1 / V q4_0 (mixed = small, so everything fits in 24GB: Windows + model + 192K KV + compute buffer)
  • flash-attn on, MTP + ngram-mod

Right now it's generating a 3D chess game in Python at ~31 t/s (GPU 97%, 220W). Your ngram-mod tip actually helped — about +27% t/s on code/math generation for me (single GPU only; on 2-GPU split it didn't help). Thanks again!

@Cybertiron

Copy link
Copy Markdown
Author

Lowered KV cache to q3_K quants

github.com/Cybertiron/llama.cpp-rtx3090-prefill-fix/releases/tag/ampere-kv-v0.1

@2048khz-gachi-rmx

2048khz-gachi-rmx commented Aug 17, 2026 •

Copy link
Copy Markdown

the commit with the new q3_k quant and updated README from your repo bled into this PR; i don't think that's what you intended to do

@Cybertiron

Copy link
Copy Markdown
Author

I will fix that

@pwilkin
pwilkin marked this pull request as draft August 17, 2026 10:25
@pwilkin

pwilkin commented Aug 17, 2026

Copy link
Copy Markdown
Member

Please remove the extra quant code and mark it as ready when you're done.

@Cybertiron
Cybertiron force-pushed the fix-27109-quant-kv-fp16 branch from 6239571 to 665dac0 Compare August 17, 2026 10:41
Cybertiron added a commit to Cybertiron/llama-prism-ampere-kv that referenced this pull request Aug 17, 2026
@Cybertiron
Cybertiron marked this pull request as ready for review August 17, 2026 11:02
@Cybertiron

Copy link
Copy Markdown
Author

I removed the extra quant code, it is original code.

@pwilkin

pwilkin commented Aug 17, 2026

Copy link
Copy Markdown
Member

/bot review

@ggml-gh-bot

ggml-gh-bot Bot commented Aug 17, 2026 •

Copy link
Copy Markdown
Automated code review

I have enough context. Let me write the review.

Code Review: PR #27140 - Slow prefill on small KV quants fixed

Reviewed the diff in ggml/src/ggml-cuda/convert.cu. The change adds four dedicated q4_0/q4_1/q5_0/q5_1 -> f16 dequantize kernels with half2-vectorized writes, dispatched from ggml_get_to_fp16_cuda when fp16_available(cc) is true, falling back to the existing path otherwise.

I verified the dequant math and output layout of all four kernels against the reference helpers in dequantize.cuh (dequantize_q4_0/q4_1/q5_0/q5_1) and the existing dequantize_block_q4_0/dequantize_block_q4_1 template kernels. The element mapping (il = tid/8, ir = tid%8, yb = y + 256*i + 32*ir + 4*il, lo at +0..3, hi at +16..19) matches the reference exactly, the q5 high-bit extraction (((qh >> p) << 4) & 0x10 / (qh >> (p+12)) & 0x10 with p = 4*il+l) is identical, and the q5_0 vs q5_1 -16/dm.y distinction is correct. Rounding (__floats2half2_rn) matches the implicit float->half cast the old templated path used, so output is bit-identical. half2 store alignment is fine (all 4-byte aligned). Scope is single-purpose, CUDA-only, additive/gated, with a linked issue (#27109) and AI disclosure present.

Blocking

(point 1) HIP/ROCm build portability of __floats2half2_rn. The new kernels use __floats2half2_rn(a, b), which is not used anywhere else in ggml-cuda. The existing f16 dequant kernel (dequantize_block_q8_0_f16) deliberately uses make_half2(...) + __hmul2, and the rest of the codebase uses __float22half2_rn(make_float2(...)). Since fp16_available(cc) returns true on AMD (highest compiled arch >= PASCAL), these new kernels will be dispatched on HIP builds, so a missing intrinsic is a real CI break, not a theoretical one. Please confirm the HIP build compiles, or - preferred - switch to the established, portable pattern, e.g. __float22half2_rn(make_float2(a, b)) (or make_half2(__float2half_rn(a), __float2half_rn(b))), matching the rest of the file.

Will slow the review

(point 2) Comments reference the issue/PR. Every new block is prefixed // #27109 fix:. Per the project's comment guidance, comments should be generic and not reference the current task/PR. Drop the #27109 fix: tags; the explanatory remainder ("half2-vectorized writes bypass the slow element-wise f16 path") can stay, ideally trimmed.

(point 3) Comment verbosity / restating code. The // assume 32 threads line is fine (copied from the sibling kernel), but the added // 0..3 and // 0..7 on il/ir in dequantize_block_q4_0_f16 just restate tid/8 and tid%8, and the other three kernels don't have them. Remove for consistency.

(point 4) Duplicated near-identical kernels. q4_0/q4_1 differ only in scale/min (d/-8*d vs dm.x/dm.y), and q5_0/q5_1 differ only in scale (d/-16 vs dm.x/dm.y). This mirrors the existing separate template kernels, so it's acceptable, but if the HIP intrinsic fix pushes a rewrite, consider a single small template over the scale/min expression to cut the four bodies down - not required, just a cleaner option.

Nits

(point 5) The kernel parameters are const int64_t nb32 but the launchers compute const int nb32 = k / 32; and rely on implicit widening. The sibling dequantize_row_q4_0_cuda uses int consistently. Make the types match (either both int or both int64_t) to avoid the implicit conversion.

(point 6) Style: the new kernels use if (ib >= nb32) return; on one line, while the surrounding dequantize_block_q4_0/q4_1 use braces (if (ib >= nb32) { return; }). Match the surrounding style.

Notes for the contributor

  • Test coverage of the f16 dequant path for these quants is exercised indirectly by test_flash_attn_ext with quantized KV (the TILE/MMA_F16 kernels set need_f16_K = true and dequant K to f16 even at GGML_PREC_F32). A direct test_cpy(quant -> F16) case in tests/test-backend-ops.cpp would make this coverage explicit and would have caught any future layout regression in this exact code path - consider adding one.
  • No docs/ops.md update is needed since no op was added/changed; the perf claim (the ~16x numbers) is reasonable to keep in the PR description but isn't required in-tree.

This review was generated automatically by pi coding agent using zai-org/GLM-5.2. It may contain mistakes. Maintainers make the final call.

@CISC
CISC removed request for a team, CISC and ggerganov August 19, 2026 08:58
@47Hunter47

This comment was marked as spam.

@47Hunter47

This comment was marked as spam.

@EJainDev

Copy link
Copy Markdown

+1

I hope maintainers get to review this sometime soon

@ggml-org ggml-org temporarily blocked 47Hunter47 Sep 26, 2026
@JohannesGaessler

Copy link
Copy Markdown
Contributor

According to the llama.cpp AI usage policy:

It is strictly prohibited to use AI to write your posts for you (bug reports, feature requests, pull request descriptions, Github discussions, responding to humans, ...).

@JohannesGaessler JohannesGaessler left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  1. There is a lot of code duplication between the kernels. If at all possible, please consolidate them into a single template.
  2. The existing dequantization kernels should be removed and the new ones should be used unconditionally. The check on fp16_available is only needed for cases where FP16 arithmetic is used (which these kernels don't). Type conversions are always fine.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CUDA Related to the CUDA backend documentation Improvements or additions to documentation examples ggml changes relating to the ggml tensor library for machine learning

Projects

None yet

Development

Successfully merging this pull request may close these issues.

CUDA: 4-bit KV cache (q4_1/q4_0) collapses prefill to ~34 t/s on qwen35 hybrid (RTX 3090, MMQ guard passes)

6 participants