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

Merged
DA
1mo ago
+602-78

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.

checkresult
test_paged_attn_lanes, both GPUsPASS
test_model_smoke PagedAttention, both GPUs8 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 promptsidentical 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.

promptTTFT, main / this PRdecode, main / this PRaccepted per step
1,0351.2 / 1.2 s64.0 / 64.2 tok/s3.30
4,1763.8 / 3.8 s57.2 / 58.0 tok/s3.32
18,35518.1 / 17.2 s (-5%)41.2 / 46.0 tok/s (+12%)3.40
53,03066.0 / 59.3 s (-10%)27.8 / 31.8 tok/s (+14%)3.18
102,766166.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)mainthis PR
tree verify, 16 rows7,383 us5,588 us (-24%)
tree verify, 1 row882 us720 us (-18%)
decode (WMMA rows), 1 row557 us485 us (-13%)
decode (WMMA rows), 16 rows2,111 us1,445 us (-32%)
prefill chunk, 4,096 rows after a 98K prefix381.0 ms272.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.

promptbase, run 1 / run 2 (tok/s)this change (tok/s)
18,35552.1 / 52.054.4
53,03031.0 / 34.133.7
102,76620.4 / 21.826.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