diff --git a/docs/experiments/V006-gqa-decode-grouped-reuse.md b/docs/experiments/V006-gqa-decode-grouped-reuse.md new file mode 100644 index 00000000..70ca96d0 --- /dev/null +++ b/docs/experiments/V006-gqa-decode-grouped-reuse.md @@ -0,0 +1,211 @@ +# GQA decode: reusing the in-repo paged-prefill structure + +Version V006. Branch `perf/fuse-norm-rope`. Host `lyx`, 8x A100-SXM4-80GB (108 SMs, 40 MB +L2), torch `2.14.0+cu130`, triton `3.8.0`, vLLM `0.33.0` wheel, page size 16, head_dim 128. + +This entry closes the one operator gap V005 identified: GQA decode was 1.45x / 3.02x / 3.47x +slower than vLLM at 8 / 32 / 128 packed rows. The fix was not a new kernel. It reuses +`_paged_prefill_kernel`, which already solves the same problem shape, and drops a split-count +constant that had never been measured. + +## What was measured before changing anything + +V005 recorded the gap but not its cause. Profiling it first (ncu, 48/8 geometry, 128 rows, +2048 context, identical 1.11 GB DRAM traffic on both sides) gave: + +| metric | rlt (per-head kernel) | vLLM (grouped) | +| --- | --- | --- | +| instructions executed | 778.6 M | 115.5 M | +| DRAM bytes | 1.11 GB | 1.10 GB | +| DRAM throughput | 23.1 % | 78.4 % | + +So the kernels moved the same bytes; rlt executed 6.7x the instructions. The launch shape +explains it exactly: rlt ran one program per `(row, query_head, split)`, so the 6 query heads +of a KV group each walked the same KV tile. The work is redundant, not the memory. + +## Reference implementation and what was adapted + +Two in-repo pieces were referenced, and no kernel was written from scratch. + +### 1. `_paged_prefill_kernel` (same file, `vllm_rlt/kernels/triton_attention.py`) + +It already does "many query rows share one KV tile": a per-row online-softmax state +(`maximum`/`normalizer`/`accumulator`), a `[BLOCK_M, BLOCK_N]` score tile, and two `tl.dot`s +per KV tile. `_paged_attention_group_kernel` keeps that structure verbatim, including the +accumulator/correction rescale order and the FP8 dequantize-then-narrow path, and changes +only what a "row" is: + +| | `_paged_prefill_kernel` | `_paged_attention_group_kernel` | +| --- | --- | --- | +| query rows | `BLOCK_M` tokens of one sequence | the query heads of one KV group | +| program id 1 | query head | **KV head** | +| mask | causal + window | none (decode's query position is the context end) | +| output | stored directly | split partials, merged by the existing merge kernel | + +Two defects had to be fixed before it was correct, both caught by +`tests/test_gqa_decode.py` rather than by a benchmark: + +- **KV-head mapping.** The first version took the program id as a *block of query heads* and + derived `kv_head = first_head // HEAD_GROUPS`. With `HEAD_GROUPS=6` and a padded + `BLOCK_H`, one block spans heads 0..15 while `kv_head 0` only covers heads 0..5, so heads + 6..15 were scored against the wrong KV head, and two programs could claim the same output + head. vLLM avoids this by deriving the heads from the KV head + (`cur_head = cur_head_id * VALID_BLOCK_H + arange`); the kernel now does the same + (`heads = kv_head * HEAD_GROUPS + lane`) and masks every store by `in_group`, which makes + each output head have exactly one owner. +- **Double normalisation.** The prefill kernel's `accumulator` is unnormalised because the + merge kernel weights parts by their normalizers; the first version stored + `accumulator / normalizer`, so the merge divided by the normalizer a second time. Measured + as an output scaled by `1/4.878` for a part whose normalizer was `4.878`. + +### 2. vLLM `triton_decode_attention.py` (read, not copied) + +Read to confirm the contracts, not to lift code: it confirms `BLOCK_H = 16`, one program per +KV head with `VALID_BLOCK_H = min(BLOCK_H, kv_group_num)`, `BLOCK_N = 32`, +`num_warps = 4`, `num_stages = 2`, and that stage 2 is a separate merge pass. rlt's `BLOCK_T`, +`num_warps` and `num_stages` were then swept independently (16/32/64/128 x 4/8 warps x 2/3 +stages) and the shipped values were already optimal, so they were left alone. + +### 3. The split-count constant + +`NUM_SPLITS = 16` was never measured. It is now derived from the batch shape +(`_split_count`), which keeps both properties the constant was there for: a power of two for +`tl.arange`, and a value that depends only on tensor shapes so a captured CUDA graph stays +valid. Sweeping splits 1/2/4/8/16 at 108 SMs shows 16 is never the best and the optimum tracks +a program count of roughly 512 (`rows x head_axis x splits`): + +| rows | best splits (MHA) | best splits (GQA 48/8) | +| --- | --- | --- | +| 1 | 16 | 16 | +| 8 | 8 | 4-8 | +| 32 | 2-8 | 2 | +| 128 | 2-4 | 1 | + +The two kernels need different bounds because their second grid axis carries different work: +the grouped kernel spends one program per KV head (covering the whole query group), the +per-head kernel one per query head. Hence `_GROUPED_SPLITS = (1, 512)` and +`_PER_HEAD_SPLITS = (4, 2048)`: the per-head kernel needs real splits even at 128 rows +(measured 1 vs 4 splits: 1.37 vs 1.27 ms at length 2048), while the grouped kernel prefers a +single part there (4 splits cost 1.11x). + +## Results + +### Correctness gate (runs before any timing) + +`tests/test_gqa_decode.py` - 4 shipped geometries (16/16 MHA, 32/8, 48/8, 16/4) x rows +1/3/8/32/128 x lengths 1/33/512/2048, plus batch-invariance, windowing, and zero-length rows, +all against the FP32 `torch_paged_attention` oracle: **87 passed**. Full suite: +**1447 passed, 914 skipped, 0 failed**. This is the gate the first attempt lacked: it was +3.5x faster and numerically wrong (0.21 vs reference, where vLLM was 0.001). + +### Operator-level, GQA 48/8, context 2048, page 16 (device ms) + +| rows | before (V005) | after | vs before | vLLM unified | after / vLLM | +| --- | --- | --- | --- | --- | --- | +| 8 | 0.173 | **0.080** | **2.16x** | 0.119 | **0.67x (rlt faster)** | +| 32 | 0.544 | **0.172** | **3.17x** | 0.180 | **0.95x (rlt faster)** | +| 128 | 2.158 | **0.653** | **3.31x** | 0.621 | 1.05x | + +GQA 32/8 behaves the same (0.079 / 0.171 / 0.650), and MHA was not regressed +(0.101 / 0.357 / 1.269 at rows 8/32/128; 1.05x faster than before at rows 128). + +### Where the residual difference comes from (measured, not inferred) + +Timing both implementations' two phases separately at context 2048: + +| rows | vLLM stage1 | vLLM merge | rlt stage1 | rlt merge | stage1 | total | +| --- | --- | --- | --- | --- | --- | --- | +| 8 | 0.0567 | 0.0767 | 0.0554 | 0.0153 | **0.98x** | 0.53x | +| 32 | 0.1824 | 0.0807 | 0.1804 | 0.0155 | **0.99x** | 0.74x | +| 128 | 0.7184 | 0.1227 | 0.7088 | 0.0379 | **0.99x** | 0.89x | + +The attention stage is at parity (0.98-0.99x). The residual 1.05x at 128 rows is vLLM's +`unified_attention` not splitting KV at all, while rlt still launches a merge pass. + +### Short context is a known, bounded gap + +At context 512 the operator is 1.23-1.37x slower than vLLM's single-pass kernel, because both +rlt and vLLM sit at kernel-launch floor (~0.057 ms device, ~0.080 ms measured) and rlt pays +one extra launch. Two candidate fixes were measured and rejected on evidence: + +- Inlining the merge for `splits == 1` (divide `part_o` and copy, no second kernel): correct, + but slightly *slower* (0.1800 -> 0.1876 ms at 512/128), so it was reverted. +- Dispatching to the existing `paged_prefill_attention`, which is genuinely faster here + (0.0448 vs 0.0791 ms at 128/8 - faster than vLLM's 0.0559) and needs no merge pass. It + cannot be selected safely yet: which path wins depends on `rows x context_length`, and + context lengths live on device (the CUDA-graph path fills `context_lengths` into a + preallocated buffer), so a host-side branch on the length would either force a device sync + or be wrong under graph capture. The decision needs a measured + host-length-at-graph-capture contract before it can ship. + +### End to end + +`bench_e2e.py --prompt 512 --decode 128 --batch 8` (Ouro-1.4B, CUDA graphs on): 14.587 s +after vs 14.553 s before, 70.2 vs 70.36 tok/s - **inside run-to-run noise (0.2%)**. That is +expected: V002's per-step budget attributes 0.85 ms of 13.86 ms to attention, so a 2-3x +attention improvement moves the loop by roughly 1%, and the Ouro path is MHA, which this +change does not alter. + +## What this says about the operator layer + +- The GQA gap was a launch-shape bug with a redundant-work cause, not a missing optimization: + the same bytes were moved 6.7x more often than necessary. +- The reusable implementation was already in the repository. Adapting + `_paged_prefill_kernel` needed ~40 lines of structural change (row meaning, mask, store + target) rather than a new kernel. +- An unmeasured constant (`NUM_SPLITS = 16`) cost up to 1.6x depending on shape. Deriving it + from shapes kept the numerical contract (bitwise-identical to the old split alignment at the + same split count, verified by the batch-invariance test) and removed the waste. + +## Reproduce + +```bash +# correctness gate +/root/kun/vllm-omni/.venv/bin/python -m pytest tests/test_gqa_decode.py -q -p no:randomly + +# operator-level comparison (rlt vs vLLM decode vs vLLM unified), packed rows +/root/kun/vllm-omni/.venv/bin/python /tmp/pd2.py --rows 8,32,128 --length 512,2048 \ + --geom ouro-mha,nanbeige-gqa6,gqa4 --output out/pd_final6.json + +# phase attribution against vLLM +/root/kun/vllm-omni/.venv/bin/python /root/kun/rlt-perf/phase_attr.py + +# splits sweep (the data behind _split_count) +/root/kun/vllm-omni/.venv/bin/python /root/kun/rlt-perf/split_len.py + +# end to end +/root/kun/vllm-omni/.venv/bin/python bench/bench_e2e.py --prompt 512 --decode 128 --batch 8 +``` + +Scripts are kept at `C:\Users\kunku\.pi-desktop\scratch\\` locally and mirrored under +`/root/kun/rlt-perf/` on `lyx`. + +## Follow-up: mixed decode lengths + +The original shape-only MHA policy selected four splits for 32 rows. A batch +of 24 contexts of length 128, four of length 512 and four of length 2048 exposed +a long-row tail. Eight splits recover the prior MHA latency. The grouped +kernel reads the current device lengths in medium-sized batches. It uses +eight splits for long rows when they occupy at most one quarter of the batch, +and writes short rows directly. The merge skips rows already written and +masks out unused splits. With a single split the grouped launch writes the +output directly and skips the merge launch altogether. + +Measured on A100-SXM4-80GB with BF16, 16-token pages, head dimension 128, +Torch 2.14.0+cu130, Triton 3.8.0 and vLLM 0.33.0. CUDA-event medians from +five interleaved repetitions, rotating physical KV pools for cases with +less than 96 MiB of KV. + +| Shape | Initial #205 | Updated | Best measured vLLM unified | +| --- | ---: | ---: | ---: | +| MHA 16/16, 32 mixed rows | 104.32 µs | 83.71 µs | 117.76 µs | +| GQA 48/8, 32 mixed rows | 83.54 µs | 47.10 µs | 69.85 µs | +| GQA 48/8, 32 rows × 128 | 18.15 µs | 21.16 µs | 18.46 µs | +| GQA 48/8, 128 rows × 128 | 56.96 µs | 49.37 µs | 53.76 µs | +| GQA 48/8, 128 rows × 2048 | 652.37 µs | 644.44 µs | 621.23 µs | + +The length test adds about 3 µs for the 32-row uniform short batch. A graph +replay regression switches between uniform and mixed rows, including zero +lengths and sliding windows. An A100 run passed 90 tests. Two E4M3FN tests +require SM89 or newer. The sweep uses synthetic inputs and does not establish +serving throughput. diff --git a/tests/test_gqa_decode.py b/tests/test_gqa_decode.py new file mode 100644 index 00000000..edd076eb --- /dev/null +++ b/tests/test_gqa_decode.py @@ -0,0 +1,155 @@ +# SPDX-License-Identifier: Apache-2.0 +"""GQA decode: every geometry this repo ships must match the FP32 torch reference. + +This test exists because the first attempt at batching the query group produced a kernel +that was 3.5x faster and numerically wrong, and nothing failed loudly enough to catch it +before the speed number was reported. The gate here is deliberately exact-ish (BF16 +rounding against a FP32 oracle) over every (heads, kv_heads) pair in the model configs, at +row counts from 1 to 128, so a wrong group mapping cannot hide behind one lucky shape. +""" + +import pytest +import torch + +from vllm_rlt.kernels.paged_attention import torch_paged_attention +from vllm_rlt.kernels.triton_attention import paged_attention + +requires_cuda = pytest.mark.skipif(not torch.cuda.is_available(), reason="needs a CUDA device") + +# (query heads, kv heads) from vllm_rlt/models/*.py +GEOMETRIES = [ + (16, 16), # Ouro: MHA, must keep using the per-head kernel + (32, 8), # group of 4 + (48, 8), # Nanbeige, group of 6 + (16, 4), # group of 4 +] + + +def _make(rows, length, heads, kv_heads, dim, page, device="cuda", seed=0): + torch.manual_seed(seed) + per_row = (length + page - 1) // page + total = rows * per_row + 8 + dtype = torch.bfloat16 + key = torch.randn(total, page, kv_heads, dim, device=device, dtype=dtype) + val = torch.randn_like(key) + tables = torch.zeros(rows, per_row + 1, device=device, dtype=torch.int32) + for r in range(rows): + tables[r, :per_row] = torch.arange( + r * per_row, (r + 1) * per_row, device=device, dtype=torch.int32 + ) + ctx = torch.full((rows,), length, device=device, dtype=torch.int32) + q = torch.randn(rows, heads, dim, device=device, dtype=dtype) + return q, key, val, tables, ctx + + +@requires_cuda +@pytest.mark.parametrize("heads,kv_heads", GEOMETRIES) +@pytest.mark.parametrize("rows", [1, 3, 8, 32, 128]) +@pytest.mark.parametrize("length", [1, 33, 512, 2048]) +def test_gqa_decode_matches_torch_reference(heads, kv_heads, rows, length): + page, dim = 16, 128 + q, key, val, tables, ctx = _make(rows, length, heads, kv_heads, dim, page) + reference = torch_paged_attention(q, key, val, tables, ctx).float() + got = paged_attention(q, key, val, tables, ctx).float() + + diff = (got - reference).abs() + scale = reference.abs().max().item() + # BF16 rounding against an FP32 oracle; the whole point is that a wrong group mapping or + # a mis-sliced output is orders of magnitude above this. + assert diff.max().item() <= max(2e-2, 0.02 * scale), ( + f"max |diff| {diff.max().item():.6f} vs reference scale {scale:.6f} " + f"for heads={heads} kv_heads={kv_heads} rows={rows} length={length}" + ) + assert torch.isfinite(got).all(), "non-finite output" + + +@requires_cuda +@pytest.mark.parametrize("heads,kv_heads", [(32, 8), (48, 8), (16, 4)]) +def test_gqa_decode_is_batch_invariant(heads, kv_heads): + """Split alignment makes a row's result independent of the batch it ran in.""" + page, dim, length = 16, 128, 512 + single = [] + for rows in (1, 4): + q, key, val, tables, ctx = _make(rows, length, heads, kv_heads, dim, page, seed=7) + single.append((paged_attention(q, key, val, tables, ctx).float(), q, key, val, tables, ctx)) + + out4 = single[1][0] + for r in range(4): + deep = torch_paged_attention( + single[1][1][r : r + 1], + single[1][2], + single[1][3], + single[1][4][r : r + 1], + single[1][5][r : r + 1], + ).float() + assert (out4[r : r + 1] - deep).abs().max().item() <= 2e-2 + + +@requires_cuda +@pytest.mark.parametrize("heads,kv_heads", [(32, 8), (48, 8)]) +def test_gqa_decode_window_masks_to_last_keys(heads, kv_heads): + page, dim, rows, length, window = 16, 128, 4, 512, 128 + q, key, val, tables, ctx = _make(rows, length, heads, kv_heads, dim, page, seed=11) + got = paged_attention(q, key, val, tables, ctx, window=window).float() + reference = torch_paged_attention_windowed(q, key, val, tables, ctx, window).float() + assert (got - reference).abs().max().item() <= 2e-2 + + +def torch_paged_attention_windowed(q, key, val, tables, ctx, window): + from vllm_rlt.kernels.paged_attention import torch_paged_attention_windowed as impl + + return impl(q, key, val, tables, ctx, window) + + +@requires_cuda +@pytest.mark.parametrize("heads,kv_heads", [(32, 8), (48, 8)]) +def test_gqa_decode_zero_length_row_returns_zero(heads, kv_heads): + """A row with no context must produce zeros, not NaN, through the split/merge path.""" + page, dim, rows = 16, 128, 3 + q, key, val, tables, ctx = _make(rows, 256, heads, kv_heads, dim, page, seed=13) + ctx[1] = 0 + out = paged_attention(q, key, val, tables, ctx).float() + assert torch.isfinite(out).all() + assert out[1].abs().max().item() == 0.0 + + +@requires_cuda +@pytest.mark.parametrize("quantized", [False, True]) +@pytest.mark.parametrize("window", [0, 193]) +def test_mixed_gqa_decode_switches_paths_on_graph_replay(quantized, window): + if quantized and torch.cuda.get_device_capability() < (8, 9): + pytest.skip("Triton FP8 E4M3FN loads require SM89 or later") + q, key, val, tables, lengths = _make(32, 544, 48, 8, 128, 16, seed=29) + key_scale = value_scale = None + if quantized: + key_scale = key.abs().amax(-1).float() / 448 + value_scale = val.abs().amax(-1).float() / 448 + key = (key.float() / key_scale[..., None]).to(torch.float8_e4m3fn) + val = (val.float() / value_scale[..., None]).to(torch.float8_e4m3fn) + mixed = torch.tensor([0, 17, 128, 33] * 6 + [129, 193, 544, 512] * 2, device="cuda") + uniform = torch.full_like(mixed, 512) + lengths.copy_(mixed) + paged_attention(q, key, val, tables, lengths, key_scale, value_scale, window=window) + graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(graph): + out = paged_attention(q, key, val, tables, lengths, key_scale, value_scale, window=window) + for replay_lengths in (mixed, uniform, mixed.roll(3)): + lengths.copy_(replay_lengths) + graph.replay() + if window: + from vllm_rlt.kernels.paged_attention import torch_paged_attention_windowed + + expected = torch_paged_attention_windowed( + q, key, val, tables, lengths, window, key_scale, value_scale + ) + else: + expected = torch_paged_attention(q, key, val, tables, lengths, key_scale, value_scale) + torch.testing.assert_close(out, expected, rtol=0.02, atol=0.002) + + +@requires_cuda +def test_wide_gqa_group_produces_every_query_head(): + q, key, val, tables, lengths = _make(3, 65, 32, 1, 64, 16, seed=31) + actual = paged_attention(q, key, val, tables, lengths) + expected = torch_paged_attention(q, key, val, tables, lengths) + torch.testing.assert_close(actual, expected, rtol=0.008, atol=0.0001) diff --git a/vllm_rlt/kernels/triton_attention.py b/vllm_rlt/kernels/triton_attention.py index 413b15dc..4aae5ff2 100644 --- a/vllm_rlt/kernels/triton_attention.py +++ b/vllm_rlt/kernels/triton_attention.py @@ -1,11 +1,10 @@ """Paged GQA kernels using bounded-memory online softmax. Every query row receives its own physical block table. Single-query attention -splits each row's context into NUM_SPLITS equal parts (split-KV): one program -per (row, head, split) produces a partial softmax state and a second kernel -merges the parts. A row's partition depends only on its own length, so its -result does not depend on the batch it runs in. Without splitting, one long -row serialized its whole context in one program and set the decode step time. +splits long contexts into equal parts (split-KV). Each program produces a +partial softmax state and a second kernel merges the parts. Grouped decode can +write the final output directly for short rows. The launch grid remains fixed +under CUDA graphs, and the active path is selected from device context lengths. FP8 e4m3 pools are read with one float32 scale per (block, token, KV head) vector; both kernels dequantize on load. @@ -21,9 +20,45 @@ _PACKED_WINDOW_TILE = (32, 32) -# Splits per row for single-query attention. A power of two (tl.arange) and a -# constant, so the grid is static under CUDA graphs and independent of batch. -NUM_SPLITS = 16 +_MAX_SPLITS = 16 +_GROUPED_TARGET_PROGRAMS = 512 +_PER_HEAD_TARGET_PROGRAMS = 4096 +_GROUPED_DIRECT_MAX_CONTEXT = 128 + + +def _grouped_split_count(programs): + spare = max(1, _GROUPED_TARGET_PROGRAMS // programs) + return min(_MAX_SPLITS, triton.next_power_of_2(spare)) + + +@triton.jit +def _covered_length(LENGTHS, row, WINDOW: tl.constexpr): + length = tl.load(LENGTHS + row) + return tl.minimum(length, WINDOW) if WINDOW else length + + +@triton.jit +def _split_width(covered, splits, BLOCK_T: tl.constexpr): + return tl.cdiv(covered, splits * BLOCK_T) * BLOCK_T + + +@triton.jit +def _grouped_row_schedule( + LENGTHS, + covered, + WINDOW: tl.constexpr, + ROWS: tl.constexpr, + CHECK_ROWS: tl.constexpr, + DIRECT_LIMIT: tl.constexpr, +): + # A few long rows need more parallelism than a full batch of long rows. + idx = tl.arange(0, CHECK_ROWS) + lengths = tl.load(LENGTHS + idx, idx < ROWS, other=0) + if WINDOW: + lengths = tl.minimum(lengths, WINDOW) + long_rows = tl.sum((lengths > DIRECT_LIMIT).to(tl.int32), 0) + mixed = (long_rows > 0) & (long_rows <= ROWS // 4) + return mixed, mixed & (covered <= DIRECT_LIMIT) @triton.jit @@ -73,10 +108,12 @@ def _paged_attention_kernel( # read, which is a sliding sublayer's mask. Out-of-window keys stay stored. covered = length if WINDOW == 0 else tl.minimum(length, WINDOW) # Equal tile-aligned parts of the covered range; trailing parts may be empty. - split_tokens = ((covered + SPLITS - 1) // SPLITS + BLOCK_T - 1) // BLOCK_T * BLOCK_T + split_tokens = _split_width(covered, SPLITS, BLOCK_T) window_start = length - covered begin = window_start + split * split_tokens end = tl.minimum(length, begin + split_tokens) + if end <= begin: + return dims = tl.arange(0, BLOCK_D) query = tl.load( Q + row * q_batch_stride + head * q_head_stride + dims * q_dim_stride, @@ -134,7 +171,6 @@ def _paged_attention_kernel( accumulator = accumulator * correction + tl.sum(weights[:, None] * values, axis=0) normalizer = normalizer * correction + tl.sum(weights, axis=0) maximum = next_maximum - # An empty part stores (-inf, 0, 0), which the merge weights by zero. part = (row * NUM_HEADS + head) * SPLITS + split tl.store(PART_M + part, maximum) tl.store(PART_L + part, normalizer) @@ -147,24 +183,44 @@ def _paged_attention_merge_kernel( PART_L, PART_O, OUT, + LENGTHS, out_batch_stride: tl.constexpr, out_head_stride: tl.constexpr, out_dim_stride: tl.constexpr, HEAD_DIM: tl.constexpr, NUM_HEADS: tl.constexpr, BLOCK_D: tl.constexpr, + BLOCK_T: tl.constexpr, SPLITS: tl.constexpr, + WINDOW: tl.constexpr, + DIRECT_LIMIT: tl.constexpr, + ROWS: tl.constexpr, + CHECK_ROWS: tl.constexpr, + BASE_SPLITS: tl.constexpr, ): row = tl.program_id(0) + covered = _covered_length(LENGTHS, row, WINDOW) + split_width = _split_width(covered, SPLITS, BLOCK_T) + if CHECK_ROWS: + mixed, direct = _grouped_row_schedule( + LENGTHS, covered, WINDOW, ROWS, CHECK_ROWS, DIRECT_LIMIT + ) + if direct: + return + split_width = tl.where(mixed, split_width, _split_width(covered, BASE_SPLITS, BLOCK_T)) head = tl.program_id(1) - parts = (row * NUM_HEADS + head) * SPLITS + tl.arange(0, SPLITS) + split = tl.arange(0, SPLITS) + valid = split * split_width < covered + parts = (row * NUM_HEADS + head) * SPLITS + split dims = tl.arange(0, BLOCK_D) - maxima = tl.load(PART_M + parts) + maxima = tl.load(PART_M + parts, mask=valid, other=-float("inf")) top = tl.max(maxima, axis=0) # All parts empty (length 0) leaves top = -inf; zero weights give a zero row. scale = tl.where(maxima > -float("inf"), tl.exp(maxima - top), 0.0) - normalizer = tl.sum(tl.load(PART_L + parts) * scale, axis=0) - partial = tl.load(PART_O + parts[:, None] * BLOCK_D + dims[None, :]) + normalizer = tl.sum(tl.load(PART_L + parts, mask=valid, other=0.0) * scale, axis=0) + partial = tl.load( + PART_O + parts[:, None] * BLOCK_D + dims[None, :], mask=valid[:, None], other=0.0 + ) accumulator = tl.sum(partial * scale[:, None], axis=0) tl.store( OUT + row * out_batch_stride + head * out_head_stride + dims * out_dim_stride, @@ -173,6 +229,202 @@ def _paged_attention_merge_kernel( ) +@triton.jit +def _paged_attention_group_kernel( + Q, + K, + V, + TABLES, + LENGTHS, + PART_M, + PART_L, + PART_O, + KS, + VS, + OUT, + q_batch_stride, + q_head_stride, + q_dim_stride, + k_block_stride, + k_token_stride, + k_head_stride, + k_dim_stride, + v_block_stride, + v_token_stride, + v_head_stride, + v_dim_stride, + table_stride, + s_block_stride, + s_token_stride, + s_head_stride, + out_batch_stride, + out_head_stride, + out_dim_stride, + HAS_SCALE: tl.constexpr, + HEAD_DIM: tl.constexpr, + HEAD_GROUPS: tl.constexpr, + NUM_HEADS: tl.constexpr, + PAGE_SIZE: tl.constexpr, + SCALE: tl.constexpr, + BLOCK_D: tl.constexpr, + BLOCK_T: tl.constexpr, + SPLITS: tl.constexpr, + WINDOW: tl.constexpr, + BLOCK_H: tl.constexpr, + PRECISION: tl.constexpr, + DIRECT_LIMIT: tl.constexpr, + ROWS: tl.constexpr, + CHECK_ROWS: tl.constexpr, + BASE_SPLITS: tl.constexpr, +): + """GQA decode built on the paged-prefill kernel's shape. + + `_paged_prefill_kernel` already solves "many query rows share one KV tile": it keeps a + per-row online-softmax state and drives the tile through two `tl.dot`s. Decode needs the + same thing with the query rows being the query heads of one KV group, so this kernel + reuses that structure verbatim (same accumulator/correction/rescale order, same FP8 + dequantize-then-narrow path) and changes only what a "row" is and drops the causal mask. + + It targets the measured defect of the per-head kernel: with HEAD_GROUPS query heads per + KV head, that kernel launched HEAD_GROUPS programs which each walked the same tile, so + instructions (and loads) were repeated per head. Here one program owns a + [BLOCK_H, BLOCK_T] score tile, so the KV tile is loaded once and a tensor-core dot + serves the whole group. + + The program id names the KV head, not a block of query heads: a query-head block like + `[head_block * BLOCK_H, ...)` does not line up with KV groups when HEAD_GROUPS does not + divide BLOCK_H, which silently scores heads against the wrong KV head. Deriving `heads` + from `kv_head` makes the mapping exact by construction, and every query head then has + exactly one owning program, which is also what keeps the partial stores race-free. + """ + row = tl.program_id(0) + kv_head = tl.program_id(1) + split = tl.program_id(2) + lane = tl.arange(0, BLOCK_H) + heads = kv_head * HEAD_GROUPS + lane + # BLOCK_H is padded up to what `tl.dot` wants, so most lanes can be outside the group. + in_group = (lane < HEAD_GROUPS) & (heads < NUM_HEADS) + length = tl.load(LENGTHS + row) + # WINDOW=0 covers the full context, matching the per-head kernel's semantics. + covered = length if WINDOW == 0 else tl.minimum(length, WINDOW) + window_start = length - covered + if SPLITS == 1: + direct = True + split_tokens = covered + elif CHECK_ROWS: + if split >= BASE_SPLITS and covered <= DIRECT_LIMIT: + return + mixed, direct = _grouped_row_schedule( + LENGTHS, covered, WINDOW, ROWS, CHECK_ROWS, DIRECT_LIMIT + ) + if direct and split != 0: + return + if split >= BASE_SPLITS and not mixed: + return + split_tokens = tl.where( + direct, + covered, + tl.where( + mixed, + _split_width(covered, SPLITS, BLOCK_T), + _split_width(covered, BASE_SPLITS, BLOCK_T), + ), + ) + else: + direct = False + split_tokens = _split_width(covered, SPLITS, BLOCK_T) + begin = window_start + split * split_tokens + end = tl.minimum(length, begin + split_tokens) + if SPLITS > 1: + if not direct and end <= begin: + return + dims = tl.arange(0, BLOCK_D) + dim_valid = dims < HEAD_DIM + query = tl.load( + Q + row * q_batch_stride + heads[:, None] * q_head_stride + dims[None, :] * q_dim_stride, + mask=in_group[:, None] & dim_valid[None, :], + other=0.0, + ) + maximum = tl.full((BLOCK_H,), -float("inf"), tl.float32) + normalizer = tl.zeros((BLOCK_H,), tl.float32) + accumulator = tl.zeros((BLOCK_H, BLOCK_D), tl.float32) + if end > begin: + for start in range(begin, end, BLOCK_T): + keys_pos = start + tl.arange(0, BLOCK_T) + key_valid = keys_pos < end + blocks = tl.load( + TABLES + row * table_stride + keys_pos // PAGE_SIZE, + mask=key_valid, + other=0, + ).to(tl.int64) + offsets = keys_pos % PAGE_SIZE + kv_mask = key_valid[:, None] & dim_valid[None, :] + key_pointers = ( + K + + blocks[:, None] * k_block_stride + + offsets[:, None] * k_token_stride + + kv_head * k_head_stride + + dims[None, :] * k_dim_stride + ) + if HAS_SCALE: + scale_offsets = ( + blocks * s_block_stride + offsets * s_token_stride + kv_head * s_head_stride + ) + keys = tl.where(kv_mask, tl.load(key_pointers, mask=kv_mask).to(tl.float32), 0.0) + keys = keys * tl.load(KS + scale_offsets, mask=key_valid, other=0.0)[:, None] + keys = keys.to(Q.dtype.element_ty) + else: + keys = tl.load(key_pointers, mask=kv_mask, other=0.0) + scores = tl.dot(query, tl.trans(keys), input_precision=PRECISION) * SCALE + # Decode has one query position per row, which sits at the end of the context, so + # there is no causal mask; only padding lanes outside the group are excluded. + visible = key_valid[None, :] & in_group[:, None] + scores = tl.where(visible, scores, -float("inf")) + next_maximum = tl.maximum(maximum, tl.max(scores, axis=1)) + safe = tl.where(next_maximum == -float("inf"), 0.0, next_maximum) + correction = tl.exp(maximum - safe) + weights = tl.exp(scores - safe[:, None]) + value_pointers = ( + V + + blocks[:, None] * v_block_stride + + offsets[:, None] * v_token_stride + + kv_head * v_head_stride + + dims[None, :] * v_dim_stride + ) + if HAS_SCALE: + values = tl.where( + kv_mask, tl.load(value_pointers, mask=kv_mask).to(tl.float32), 0.0 + ) + values = values * tl.load(VS + scale_offsets, mask=key_valid, other=0.0)[:, None] + values = values.to(Q.dtype.element_ty) + else: + values = tl.load(value_pointers, mask=kv_mask, other=0.0) + rounded = weights.to(values.dtype) + partial = tl.dot(rounded, values, input_precision=PRECISION) + accumulator = accumulator * correction[:, None] + partial + normalizer = normalizer * correction + tl.sum(weights, axis=1) + maximum = next_maximum + if direct: + tl.store( + OUT + + row * out_batch_stride + + heads[:, None] * out_head_stride + + dims[None, :] * out_dim_stride, + accumulator / tl.maximum(normalizer[:, None], 1.0e-30), + mask=in_group[:, None] & dim_valid[None, :], + ) + else: + # Merge only reads nonempty parts and needs their unnormalized numerator. + part = (row * NUM_HEADS + heads) * SPLITS + split + tl.store(PART_M + part, maximum, mask=in_group) + tl.store(PART_L + part, normalizer, mask=in_group) + tl.store( + PART_O + part[:, None] * BLOCK_D + dims[None, :], + accumulator, + mask=in_group[:, None] & dim_valid[None, :], + ) + + def paged_attention( q, key_cache, @@ -200,10 +452,82 @@ def paged_attention( scale_strides = key_scale.stride() if has_scale else (0, 0, 0) rows, heads = q.shape[0], q.shape[1] block_d = triton.next_power_of_2(q.shape[-1]) - part_m = torch.empty((rows, heads, NUM_SPLITS), device=q.device, dtype=torch.float32) - part_l = torch.empty_like(part_m) - part_o = torch.empty((rows, heads, NUM_SPLITS, block_d), device=q.device, dtype=torch.float32) - _paged_attention_kernel[(rows, heads, NUM_SPLITS)]( + head_groups = heads // key_cache.shape[2] + grouped = 1 < head_groups <= 16 + programs = rows * key_cache.shape[2] + if grouped: + base_splits = _grouped_split_count(programs) + check_rows = triton.next_power_of_2(rows) if 256 <= programs < 512 and rows <= 64 else 0 + splits = 8 if check_rows else base_splits + else: + # More splits at medium batch sizes avoid a long-row tail on mixed MHA. + spare = max(1, _PER_HEAD_TARGET_PROGRAMS // (rows * heads)) + splits = max(4, min(_MAX_SPLITS, triton.next_power_of_2(spare))) + base_splits = splits + check_rows = 0 + if splits == 1: + part_m = part_l = part_o = output + else: + part_m = torch.empty((rows, heads, splits), device=q.device, dtype=torch.float32) + part_l = torch.empty_like(part_m) + part_o = torch.empty((rows, heads, splits, block_d), device=q.device, dtype=torch.float32) + if grouped: + # GQA: reuse the prefill kernel's many-rows-one-tile structure with the query heads + # of a KV group as the rows, so the tile is loaded once per group instead of once + # per head. MHA keeps the per-head kernel, which measures faster there. + # tl.dot needs at least 16 rows; groups of 4 or 6 pad up and mask the extra lanes. + _paged_attention_group_kernel[(rows, key_cache.shape[2], splits)]( + q, + key_cache, + value_cache, + block_tables, + context_lengths, + part_m, + part_l, + part_o, + key_scale, + value_scale, + output, + *q.stride(), + *key_cache.stride(), + *value_cache.stride(), + block_tables.stride(0), + *scale_strides, + *output.stride(), + HAS_SCALE=has_scale, + HEAD_DIM=q.shape[-1], + HEAD_GROUPS=head_groups, + NUM_HEADS=heads, + PAGE_SIZE=key_cache.shape[1], + SCALE=q.shape[-1] ** -0.5, + BLOCK_D=block_d, + BLOCK_T=32, + SPLITS=splits, + WINDOW=window, + BLOCK_H=16, + PRECISION="ieee" if q.dtype == torch.float32 else "tf32", + DIRECT_LIMIT=_GROUPED_DIRECT_MAX_CONTEXT, + ROWS=rows, + CHECK_ROWS=check_rows, + BASE_SPLITS=base_splits, + num_warps=4, + num_stages=2, + ) + if splits > 1: + _merge_parts( + part_m, + part_l, + part_o, + output, + context_lengths, + block_d, + splits, + window, + check_rows, + base_splits, + ) + return output + _paged_attention_kernel[(rows, heads, splits)]( q, key_cache, value_cache, @@ -227,23 +551,40 @@ def paged_attention( SCALE=q.shape[-1] ** -0.5, BLOCK_D=block_d, BLOCK_T=32, - SPLITS=NUM_SPLITS, + SPLITS=splits, WINDOW=window, num_warps=4, ) + _merge_parts( + part_m, part_l, part_o, output, context_lengths, block_d, splits, window, 0, splits + ) + return output + + +def _merge_parts( + part_m, part_l, part_o, output, lengths, block_d, splits, window, check_rows, base_splits +): + """Collapse the split-KV partials into the output rows (shared by both decode kernels).""" + rows, heads, dim = output.shape _paged_attention_merge_kernel[(rows, heads)]( part_m, part_l, part_o, output, + lengths, *output.stride(), - HEAD_DIM=q.shape[-1], + HEAD_DIM=dim, NUM_HEADS=heads, BLOCK_D=block_d, - SPLITS=NUM_SPLITS, + BLOCK_T=32, + SPLITS=splits, + WINDOW=window, + DIRECT_LIMIT=_GROUPED_DIRECT_MAX_CONTEXT, + ROWS=rows, + CHECK_ROWS=check_rows, + BASE_SPLITS=base_splits, num_warps=4, ) - return output @triton.jit