Skip to content

perf(paged-attn): faster long-context prefill and decode, same bits for Q8_0 K/V - #980

Merged
davide221 merged 1 commit into
mainfrom
perf/paged-attn-long-context
Nov 10, 2026
Merged

davide221 merged 1 commit into
mainfrom
perf/paged-attn-long-context

Conversation

@davide221

@davide221 davide221 commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

What

Long-context speedups in ggml-cuda/paged-attn.cu. All of them keep the outputs bit-identical for q8_0 K/V caches.

Prefill (WMMA kernel, paged_attn_wmma, RDNA4)

  • V is staged transposed in shared memory. The tile is laid out dims x tokens, which is the layout of the VKQ mma's V operand. Each V fragment now loads as one 16-byte read per lane. The identity mma that transposed every fragment is gone; it was about a third of the kernel's WMMA instructions.
    • The two lanes of a token pair trade halves with one DPP move.
    • The 16-byte chunks are XOR-swizzled by dim group, so the transposed stores do not hit the same banks.
  • Q8_0 is dequantized in packed f16. The kernel builds the f16 1024 + (q + 128) with a byte permute and subtracts 1152. That gives q exactly, and one f16 multiply by d follows. mmb-q8f16.cuh already uses the same idea.
  • The shared memory size is one constant for the launcher and the kernel, with a static_assert for every phase that aliases it (Q, K, V, combine).

Decode and tree verify (paged_attn_decode)

  • K·Q scores are reduced two tokens at a time with paged_attn_reduce_group<2>. The first butterfly level trades half of the pair instead of a whole sum, so every exchange carries a value the partner still needs.
    • Q4_0 K keeps one token at a time, because pairing it costs registers and occupancy.
  • On RDNA (wave32), lane exchanges use the VALU.
    • DPP row_xmask and v_permlanex16 replace ds_bpermute in every butterfly: scores, tile max and tile sum.
    • readlane replaces the broadcast shuffles of the token index and the softmax weights.
    • Wave64 targets and CUDA keep __shfl_*_sync.

Helpers and test

  • The helpers move to paged-attn-common.cuh: lane exchanges, group reduction, packed Q8_0 dequant and transposed store.
  • New GPU unit test test_paged_attn_lanes (HIP and CUDA) checks them bit for bit:
    • reduce_group<2> and <1>, warp sum, warp max, xor exchange and lane broadcast against warp_reduce_sum, warp_reduce_max and the plain shuffles. Inputs are random values with signed zeros, subnormals and cancelling pairs, in blocks of several warps.
    • Packed Q8_0 dequant against __float2half(__half2float(d) * q), exhaustively over all 65,536 f16 scales (NaN excluded) x 256 quants.
    • The transposed V staging against the row-major staging, for every (token, dim), with the padding left untouched.
    • Each check was shown to fail on purpose: wrong permlanex16 selector, wrong DPP control, swapped group halves, wrong pair distance, wrong readlane source, and swapped quant bytes.

Side effect. On main, paged-attn.cu does not compile for gfx90a or gfx942: A_identity is undeclared on the MFMA path. It now compiles for gfx90a, gfx942, gfx1100, gfx1151 and gfx1201. The non-RDNA, non-ldmatrix branch of the V load is NO_DEVICE_CODE; the launcher already limits this kernel to RDNA4.

Why it is exact

  • Reductions. Every token's sum takes the same additions as warp_reduce_sum, in the same order. DPP and permlanex16 move the same values a shuffle would. The unit test checks this bitwise.
  • Q8_0 dequant. 1024 + (q + 128) and the subtraction are exact in f16, so the only rounding is the f16 product d * q. The old path rounds the exact float product d * q to f16 once. The results are equal for every finite input.
    • The one difference is the sign of a zero product. The packed path keeps the IEEE sign, while ROCm's __float2half(-0.0f) returns +0.
    • No output can see it: every mma accumulator starts at +0, and +0 plus -0 is +0.
  • Transposed V. This is a layout change only. Each value lands where the fragment load reads it, which the unit test checks.
  • Partition count. It derives from occupancy (cudaOccupancyMaxActiveBlocksPerMultiprocessor), so a register change can shift bits.
    • For q8_0 K/V, register use stays in the same occupancy step on gfx1201 and gfx1151.
    • Forcing a partition count with the existing debug override gave identical outputs for every K/V type tested.

Verification

Hardware: Radeon AI PRO R9700 (gfx1201) and Radeon 8060S (gfx1151), ROCm 7.2, GGML_HIP_GRAPHS=OFF. Base is main, built the same way.

check result
test_paged_attn_lanes, both GPUs PASS
test_model_smoke PagedAttention, both GPUs 8 of 8 cases pass
Kernel output hashes vs main, q8_0 K/V, gfx1201: tree, hot, seqs and rows modes (20 shapes each), chunk mode (5 prefixes) 85 of 85 identical
Kernel output hashes vs main, q8_0 K/V, gfx1151: tree mode (20 shapes) 20 of 20 identical
Greedy model text vs main, fixed verify width 16, 1K to 103K prompts identical at all 5 sizes, same acceptance
Greedy model text, no drafter, 1K to 103K prompts (development build with the same kernel diff) identical at all 5 sizes

Measured

Model: Qwen3.8-27B, q8_0 K/V cache, on gfx1201. Prompts are 1K to 103K tokens, 300 output tokens, temperature 0.

Fixed verify width 16 (LUCE_ADAPTIVE_SPEC_WIDTH=0). The text is run-stable here, and identical between main and this branch.

prompt TTFT, main / this PR decode, main / this PR accepted per step
1,035 1.2 / 1.2 s 64.0 / 64.2 tok/s 3.30
4,176 3.8 / 3.8 s 57.2 / 58.0 tok/s 3.32
18,355 18.1 / 17.2 s (-5%) 41.2 / 46.0 tok/s (+12%) 3.40
53,030 66.0 / 59.3 s (-10%) 27.8 / 31.8 tok/s (+14%) 3.18
102,766 166.1 / 142.1 s (-14%) 18.5 / 22.4 tok/s (+21%) 3.20

Kernel time per full-attention layer at 102,400 tokens of context:

kernel (gfx1201) main this PR
tree verify, 16 rows 7,383 us 5,588 us (-24%)
tree verify, 1 row 882 us 720 us (-18%)
decode (WMMA rows), 1 row 557 us 485 us (-13%)
decode (WMMA rows), 16 rows 2,111 us 1,445 us (-32%)
prefill chunk, 4,096 rows after a 98K prefix 381.0 ms 272.9 ms (-28%)

On gfx1151, the 16-row tree verify goes from 12,812 to 9,897 us per layer (-23%).

Default adaptive verify width (development build with the same kernel diff). These numbers are noisy, and the greedy text is not run-stable even without this change: the width controller picks widths from wall-clock step time. Two base runs give a sense of the noise.

prompt base, run 1 / run 2 (tok/s) this change (tok/s)
18,355 52.1 / 52.0 54.4
53,030 31.0 / 34.1 33.7
102,766 20.4 / 21.8 26.0

Known limits

  • f16 K caches can shift bits at some shapes. The decode kernel drops from 131 to 126 VGPRs with f16 K. On gfx1201 that raises occupancy one step, and with it the occupancy-derived partition count.
    • Outputs change at a few short-context, wide-verify shapes: 2 of 20 tree f16 cells, and 26 of 288 per-case test hashes, all with K=f16.
    • At a fixed partition count the outputs are identical.
    • q8_0 K/V does not move.
  • Partitions depend on occupancy. Any register change, including a compiler update, can move a shape across an occupancy step and change its low bits. This is true on main as well. Pinning a per-arch occupancy constant would fix it, but that would change bits once, so it is left out.
  • Exactness is for finite inputs. A NaN product (inf scale times 0) is NaN on both paths, but the payload bits may differ. A zero product keeps its sign, as described above.
  • CUDA is compile-only.
    • The CUDA branches of the helpers (__shfl_*_sync, __byte_perm) and the ldmatrix path were not built here; there was no CUDA compiler. CI covers them.
    • The unit test's CUDA build is wired in CMake, but it has not been run on an NVIDIA GPU.

🤖 Generated with Claude Code

View guided diff

…or Q8_0 K/V

Prefill (WMMA kernel): V is staged transposed in shared memory, so each V
fragment is one 16-byte load and the identity MMA that transposed it is
gone; Q8_0 is dequantized in packed f16 with the same single rounding.
Decode and tree verify: K.Q scores reduce two tokens at a time, and on
wave32 RDNA the lane exchanges use DPP, permlanex16 and readlane instead
of shuffles through shared memory. Same additions in the same order.

The helpers move to paged-attn-common.cuh and test_paged_attn_lanes checks
them bit for bit (reductions on random inputs with signed zeros and
subnormals, the Q8_0 dequant over every f16 scale and quant, the
transposed staging against the row-major one).

Qwen3.8-27B on gfx1201, Q8_0 K/V, fixed verify width 16, main -> this:
decode 41.2 -> 46.0 tok/s at 18K, 27.8 -> 31.8 at 53K, 18.5 -> 22.4 at
103K; time to first token 166.1 -> 142.1 s at 103K. Greedy text identical
at 1K to 103K; kernel output hashes identical on gfx1201 and gfx1151.

F16 K caches can change low bits at a few shapes: the kernel uses fewer
registers, which moves the occupancy-derived partition count.

Co-Authored-By: Claude <[email protected]>
davide221 added a commit that referenced this pull request Nov 10, 2026
…path

The fast path reads src1 with contiguous channels and any token and
sequence stride that is a multiple of 4 bytes, so a token row may be a
column slice of a stacked projection and sequences may be padded. Two
comments still described the strict dense layout of the original
specialization.

With the fast path, the concat kernels at 102,766 prompt tokens on
Qwen3.8-27B take 0.77 s of GPU time instead of 6.41 s (profiled on the
branch of #980, whose concat is the same as main's).

Co-Authored-By: Claude <[email protected]>
@davide221
davide221 marked this pull request as ready for review November 10, 2026 22:43
@davide221
davide221 merged commit 245801f into main Nov 10, 2026
18 of 19 checks passed
davide221 added a commit that referenced this pull request Nov 10, 2026
* perf(ggml-cuda): strided source rows on the transposed concat fast path

The Qwen 3.5/3.6 DeltaNet conv input is concat(conv_history, transpose(qkv))
along tokens. Where a layer's gate and qkv projections are stacked, qkv is a
column slice of 16,384-float rows, so the dense-only fast path rejected it
and the generic concat_non_cont kernel ran instead, reading one channel per
lane `row` floats apart (about 64 GB/s on gfx1201).

The 32x32 shared-memory transpose now takes the source's token-row and
sequence strides; channels must still be contiguous. It is a copy, so the
output bits are unchanged.

Measured on an R9700 (Qwen3.8-27B IQ4_XS, paged prefill, 2,048-row chunks):
CONCAT 6.41 s -> fast path at a 102,766-token prompt; time to first token
1K / 4K / 18K / 53K / 103K 1.2 / 3.8 / 17.3 / 59.4 / 142.3 s ->
1.2 / 3.6 / 16.5 / 57.1 / 138.0 s; greedy text without the drafter
identical at all five sizes. test_concat_transpose: three strided cases
(including 3 + 2048 tokens x 10,240 channels from 16,384-float rows),
bit-exact against the host reference, all on the fast path.

Co-Authored-By: Claude <[email protected]>

* perf(qwen35): embed prompt chunks straight into pinned rows

Each 2,048-row prefill step used to dequantize its token embeddings into a
fresh, zero-filled 42 MB vector, copy them into a second host buffer, and
upload that pageable buffer synchronously. Prompt chunks and decode rows are
now embedded once into one pinned host buffer (the device's host buffer
type), grown on demand and uploaded asynchronously.

Lifetime: the buffer is only rewritten by the next step. Every step
synchronizes after its compute, nothing returns between the upload and the
compute, and the compute-failure path now synchronizes before it returns.

Measured on an R9700 (Qwen3.8-27B IQ4_XS, paged prefill): host time per
2,048-row chunk staging 15.9 -> 7.9 ms, upload 14.1 -> 0.03 ms. With the
checkpoint change that follows, time to first token at 1K / 4K / 18K / 53K
/ 103K tokens 1.2 / 3.6 / 16.5 / 57.1 / 138.0 s -> 1.1 / 3.5 / 16.3 / 56.7 /
137.0 s; greedy text without the drafter identical to the base at all five.

Co-Authored-By: Claude <[email protected]>

* perf(qwen35): huge pages for prefix checkpoint snapshots

A checkpoint copies the paged KV and recurrent state into a fresh host
buffer (3.7 GB at a 103K-token prompt), whose pages are first touched by
that copy. On Linux, madvise(MADV_HUGEPAGE) on the buffer's 2 MiB-aligned
interior lets the copy fault once per 2 MiB instead of once per 4 KiB.
Advice only: contents and layout are unchanged, and it compiles out where
MADV_HUGEPAGE does not exist.

Measured on an R9700 box (THP in madvise mode): checkpoint time at
18K / 53K / 103K tokens 322 / 768 / 1,392 ms -> 282 / 690 / 1,271 ms.

Co-Authored-By: Claude <[email protected]>

* docs(ggml-cuda): describe the strided src1 layout of the concat fast path

The fast path reads src1 with contiguous channels and any token and
sequence stride that is a multiple of 4 bytes, so a token row may be a
column slice of a stacked projection and sequences may be padded. Two
comments still described the strict dense layout of the original
specialization.

With the fast path, the concat kernels at 102,766 prompt tokens on
Qwen3.8-27B take 0.77 s of GPU time instead of 6.41 s (profiled on the
branch of #980, whose concat is the same as main's).

Co-Authored-By: Claude <[email protected]>

* test(ggml-cuda): concat transpose with padded sequences

Adds a case whose source sequences are not tokens x row width apart
(5 unused token rows between them), so the sequence stride is checked
on its own and not only through the token stride.

Co-Authored-By: Claude <[email protected]>

* revert(qwen35): drop huge pages for prefix checkpoint snapshots

This reverts commit b2ca568.

The test box runs transparent huge pages with enabled=madvise and
defrag=madvise. Under defrag=madvise, a page fault in a MADV_HUGEPAGE
region enters direct reclaim and compaction, so on a box whose free
memory is fragmented the checkpoint copy can stall instead of getting
faster. The measured gain was 120 to 135 ms per checkpoint at 53K to
103K tokens (0.1% of the time to first token), on a box with plenty of
free 2 and 4 MiB blocks; that is too small to carry a platform setting
dependent risk.

Main (f5993e0) against this branch after the revert, Qwen3.8-27B,
greedy without the drafter, time to first token: 1.18 to 1.16 s at
1,035 tokens, 3.79 to 3.62 s at 4,176, 18.06 to 17.25 s at 18,355,
66.02 to 63.47 s at 53,030 and 166.29 to 161.04 s at 102,766 tokens
(-1.7 to -4.5%). The generated text is identical at all five sizes.

Co-Authored-By: Claude <[email protected]>

* refactor(qwen35): reserve the input embedding rows once, in a PinnedStage

The pinned input-embedding rows grew during requests through a raw
host buffer, freed by hand. They now use the shared PinnedStage helper
and are reserved once when the engine is built, for the largest step
step_plan_limits() allows: min(max prefills x 2048, the largest of the
idle, mixed and long mixed token caps) prompt rows plus the decode
bucket of every slot. step() already rejects plans above those limits,
and checks the sum once more before staging. Without pinned memory the
rows fall back to pageable memory, with one log line.

Also drops a token offset that was initialized twice.

Co-Authored-By: Claude <[email protected]>

---------

Co-authored-by: Claude <[email protected]>

@davide221 davide221 left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Code review

No issues found. Checked for bugs and logic errors in the changed code.

Reviewed 297ab233 · 0 candidate issues checked, kept at ≥70% confidence · add the code-review label to review again

davide221 added a commit that referenced this pull request Nov 10, 2026
The lane-isolation fix this branch was stacked on is on main as #981, so
the branch now carries only the overlap step on top of main.

Co-Authored-By: Claude <[email protected]>
@davide221
davide221 deleted the perf/paged-attn-long-context branch November 12, 2026 14:57
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant