Skip to content

CUDA/HIP: optimize the masking kernel for sparse tile fattn and tune for RDNA3/4 and CDNA1 - #32741

Open
IMbackK wants to merge 10 commits into
ggml-org:masterfrom
IMbackK:pr-30370-cdna
Open

IMbackK wants to merge 10 commits into
ggml-org:masterfrom
IMbackK:pr-30370-cdna

Conversation

@IMbackK

@IMbackK IMbackK commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

Overview

optimizes the masking kernel and enables and tunes the sparse path in the tile kernel for RDNA2, RDNA3, RDNA4
masking kernel now dose 16 byte loads, keeps more loads in flight, row_count is kept in registers and the data for compaction is first staged trough lds.

This pr is based on and must be merged after #30370

Additional information

perf cdna mi100.log

perf rdna3 rx7900xtx.log

perf rdna4 r9700.log

test-backend-ops perf patch used to generate the attached perf logs fattn-sparse-baseline mentioned in the logs is master with this patch applied
commit da17a4e3199810c84f4c86ab6a8f1ba4f8ec32cc
Author: Carl Philipp Klemm <[email protected]>
Date:   Sat Nov 21 11:40:57 2026 +0100

    tests: add sparse flash attention perf cases

diff --git a/tests/test-backend-ops.cpp b/tests/test-backend-ops.cpp
index 66aaa98ee2..65a84c6e3c 100644
--- a/tests/test-backend-ops.cpp
+++ b/tests/test-backend-ops.cpp
@@ -13981,6 +13981,56 @@ static std::vector<std::unique_ptr<test_case>> make_test_cases_perf() {
         }
     }
 
+    // Sparse flash attention comparison set: n_kv_max = 0 is the dense reference.
+    // 256/256 gqa 12 (Qwen QSA) over depth and batch size.
+    for (int64_t kv : {4096, 8192, 16384, 32768, 65536, 131072}) {
+        for (int64_t nb : {1, 2, 4, 8, 16, 32, 64}) {
+            if (kv == 131072 && nb > 8) {
+                continue;
+            }
+            for (int64_t n_kv_max : {0, 2048}) {
+                test_cases.emplace_back(new test_flash_attn_ext(256, 256, 2, {12, 1}, kv, nb, true, false, 0, 0, GGML_PREC_F32, GGML_TYPE_F16, GGML_TYPE_F16, {0, 1, 2, 3}, true, false, n_kv_max));
+            }
+        }
+    }
+    // Fraction of selected positions at a fixed depth.
+    for (int64_t n_kv_max : {256, 512, 1024, 4096, 8192}) {
+        for (int64_t nb : {1, 8}) {
+            test_cases.emplace_back(new test_flash_attn_ext(256, 256, 2, {12, 1}, 32768, nb, true, false, 0, 0, GGML_PREC_F32, GGML_TYPE_F16, GGML_TYPE_F16, {0, 1, 2, 3}, true, false, n_kv_max));
+        }
+    }
+    // Quantized and bf16 K/V over GQA ratios.
+    for (ggml_type type_KV : {GGML_TYPE_Q8_0, GGML_TYPE_Q4_0, GGML_TYPE_BF16}) {
+        for (int64_t kv : {16384, 65536}) {
+            for (int64_t nb : {1, 2, 8}) {
+                for (int64_t n_kv_max : {0, 1024}) {
+                    test_cases.emplace_back(new test_flash_attn_ext(256, 256, 2, {12, 1}, kv, nb, true, false, 0, 0, GGML_PREC_F32, type_KV, type_KV, {0, 1, 2, 3}, true, false, n_kv_max));
+                    test_cases.emplace_back(new test_flash_attn_ext(128, 128, 8, { 4, 1}, kv, nb, true, false, 0, 0, GGML_PREC_F32, type_KV, type_KV, {0, 1, 2, 3}, true, false, n_kv_max));
+                    test_cases.emplace_back(new test_flash_attn_ext(128, 128, 4, { 8, 1}, kv, nb, true, false, 0, 0, GGML_PREC_F32, type_KV, type_KV, {0, 1, 2, 3}, true, false, n_kv_max));
+                    test_cases.emplace_back(new test_flash_attn_ext(128, 128, 2, {16, 1}, kv, nb, true, false, 0, 0, GGML_PREC_F32, type_KV, type_KV, {0, 1, 2, 3}, true, false, n_kv_max));
+                }
+            }
+        }
+    }
+    // Other head sizes and GQA ratios.
+    for (int64_t kv : {8192, 32768}) {
+        for (int64_t nb : {1, 8}) {
+            for (int64_t n_kv_max : {0, 1024}) {
+                for (int64_t hs : {72, 80, 96, 112, 128}) {
+                    test_cases.emplace_back(new test_flash_attn_ext(hs, hs, 2, {12, 1}, kv, nb, true, false, 0, 0, GGML_PREC_F32, GGML_TYPE_F16, GGML_TYPE_F16, {0, 1, 2, 3}, true, false, n_kv_max));
+                }
+                test_cases.emplace_back(new test_flash_attn_ext(192, 128, 2, {32, 1}, kv, nb, true, false, 0, 0, GGML_PREC_F32, GGML_TYPE_F16, GGML_TYPE_F16, {0, 1, 2, 3}, true, false, n_kv_max));
+                test_cases.emplace_back(new test_flash_attn_ext(256, 256, 2, { 2, 1}, kv, nb, true, false, 0, 0, GGML_PREC_F32, GGML_TYPE_F16, GGML_TYPE_F16, {0, 1, 2, 3}, true, false, n_kv_max));
+                test_cases.emplace_back(new test_flash_attn_ext(256, 256, 2, { 4, 1}, kv, nb, true, false, 0, 0, GGML_PREC_F32, GGML_TYPE_F16, GGML_TYPE_F16, {0, 1, 2, 3}, true, false, n_kv_max));
+                test_cases.emplace_back(new test_flash_attn_ext(320, 256, 1, {32, 1}, kv, nb, true, false, 0, 0, GGML_PREC_F32, GGML_TYPE_F16, GGML_TYPE_F16, {0, 1, 2, 3}, true, false, n_kv_max));
+                test_cases.emplace_back(new test_flash_attn_ext(512, 512, 1, { 8, 1}, kv, nb, true, false, 0, 0, GGML_PREC_F32, GGML_TYPE_F16, GGML_TYPE_F16, {0, 1, 2, 3}, true, false, n_kv_max));
+                test_cases.emplace_back(new test_flash_attn_ext(512, 512, 1, {16, 1}, kv, nb, true, false, 0, 0, GGML_PREC_F32, GGML_TYPE_F16, GGML_TYPE_F16, {0, 1, 2, 3}, true, false, n_kv_max));
+                test_cases.emplace_back(new test_flash_attn_ext(576, 512, 1, {16, 1}, kv, nb, true, false, 0, 0, GGML_PREC_F32, GGML_TYPE_F16, GGML_TYPE_F16, {0, 1, 2, 3}, true, true,  n_kv_max));
+                test_cases.emplace_back(new test_flash_attn_ext(576, 512, 1, {32, 1}, kv, nb, true, false, 0, 0, GGML_PREC_F32, GGML_TYPE_F16, GGML_TYPE_F16, {0, 1, 2, 3}, true, true,  n_kv_max));
+            }
+        }
+    }
+
     // Sparse flash attention (n_kv_max hint) decode across KV depths.
     // Shapes: 576/512 DeepSeek MLA, 512/512 DeepSeek-V4/GLM-5.2, 256/256 gqa12 Qwen QSA.
     for (int64_t kv : {4096, 16384, 32768}) {

Requirements

  • I have read and agree with the contributing guidelines
  • AI usage disclosure: YES codex 5.5 wrote the new masking kernel as the _vec varient for the cdna port, which i merged back into the main kernel.

@IMbackK
IMbackK requested review from a team and ggerganov as code owners November 21, 2026 15:34
@IMbackK IMbackK changed the title Pr 30370 cdna CUDA/HIP: optimize the masking kernel for sparse tile fattn and tune for RDNA3/4 and CDNA1 Nov 21, 2026
@IMbackK

IMbackK commented Nov 21, 2026

Copy link
Copy Markdown
Contributor Author

@am17an could you check perf on cuda, the changes to flash_attn_mask_to_sparse_indices should be positive there too but i cant test.

@IMbackK

IMbackK commented Nov 21, 2026

Copy link
Copy Markdown
Contributor Author

Force push was for: rebase on latest master.

@github-actions github-actions Bot added testing Everything test related ggml changes relating to the ggml tensor library for machine learning CUDA Related to the CUDA backend labels Nov 21, 2026
}

#ifdef GGML_USE_HIP
bool ggml_cuda_flash_attn_ext_tile_shall_use_sparse(const int cc, const ggml_tensor * dst, const int DKQ, const int DV) {

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.

The function ggml_cuda_flash_attn_ext_tile_shall_use_sparse() decides whether sparse Flash Attention should be used, but it does not check logit_softcap but ggml_cuda_flash_attn_ext_tile_may_use_sparse() explicitly disables sparse execution when logit_softcap is enabled.

This creates an inconsistency:

  1. The kernel selector chooses BEST_FATTN_KERNEL_TILE, expecting to use sparse attention.
  2. The tile launcher rejects the sparse variant because logit_softcap != 0.
  3. The dense tile kernel runs instead, potentially bypassing a faster MFMA/WMMA implementation.
    Which lead to possible performance regression for models using both logit_softcap and n_kv_max > 0.

Maybe we should add something like this:

     float max_bias = 0.0f;
+    float logit_softcap = 0.0f;
     memcpy(&max_bias, (const float *) dst->op_params + 1, sizeof(float));
+    memcpy(&logit_softcap, (const float *) dst->op_params + 2, sizeof(float));

     if (!mask || mask->ne[0] != n_kv || mask->ne[1] < Q->ne[1] ||
-        mask->ne[2] != 1 || dst->src[5] || n_kv_max <= 0 || max_bias != 0.0f) {
+        mask->ne[2] != 1 || dst->src[5] || n_kv_max <= 0 || max_bias != 0.0f || logit_softcap != 0.0f) {
         return false;
     }

Also we do not have test-backend-ops test with logit_softcap != 0 (they are all logit_softcap = 0), we should add one maybe

}
warp_item_offset += ggml_cuda_popc(selected_warp[item]);
const int i_t = i0 + tid*cpt;
uint64_t sel = ((const sel_t *) sel_lds)[tid];

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.

sel_lds is defined as a uint8_t array but later used as uint64_t or uint16_t

should do something like

-        uint64_t sel = ((const sel_t *) sel_lds)[tid];
+        sel_t sel_bits;
+        memcpy(&sel_bits, sel_lds + tid*nload, sizeof(sel_bits));
+        uint64_t sel = sel_bits;

@sorasoras

Copy link
Copy Markdown

Measured this PR's sparse tile kernel on NVIDIA Pascal (Tesla P40, sm_61) by ungating the sparse path for pre-Volta CUDA. Patch (~150 lines on top of this branch): pascal-sparse.patch

What the patch changes:

  • ggml_cuda_flash_attn_ext_tile_may_use_sparse: compiled for CUDA too; on NVIDIA requires the fp16 and fp32 tile config tables to have an entry for (DKQ, DV, ncols2), so the sparse instantiation compiles for every arch.
  • flash_attn_tile: the sparse variant is only NO_DEVICE_CODE-elided for __CUDA_ARCH__ >= 700 (tensor-core GPUs use the mma sparse kernel); pre-Volta CUDA and the host pass compile the real body.
  • launch_fattn_tile_switch_ncols1 + the best-kernel dispatch: ungated, shall_use_sparse now has an NVIDIA branch (cc < Volta only).
  • shall_use_sparse NVIDIA thresholds, tuned on the P40: same shape table as GCN, same 25% selection cap, but no gqa gates for 512/512 and 576/512 (see DSA results below).

Correctness: all sparse FLASH_ATTN_EXT eval cases pass on sm_61 (fp32 tile path), including the dense-fallback shapes, the multi-sequence variants, and DSA-shape cases (512/512 gqa 8 @ kv 32768, 576/512 gqa 16 @ kv 32768).

Perf on Tesla P40, fp32 tile kernel, 256/256 gqa 12 f16 KV, n_kv_max=2048 — speedup vs dense at the same shape:

kv selection nb=1 nb=2 nb=4 nb=8 nb=16 nb=32 nb=64
8192 25% 2.39x 1.92x 1.55x 1.13x 1.12x 1.15x 1.19x
16384 12.5% 5.25x 3.72x 2.98x 2.11x 2.16x 2.21x 2.27x
32768 6.2% 9.05x 7.34x 5.71x 3.96x 4.13x 4.25x 4.28x
65536 3.1% 20.7x 14.2x 10.9x 7.4x 7.7x 8.0x 8.1x

No crossover below the 25% selection cap even at nb=64. Fraction sweep at kv=32768 confirms the low end: 58x at 0.8% selection, 27x at 3.1%, 10.9x at 12.5%, 6.1x at 25% for nb=1; at nb=8 still 18.7x / 6.8x / 2.2x / 1.14x — a win even at n_gather = 2*n_kv, so no gather-count rule is needed beyond the 25% cap.

Quantized K/V (q8_0, n_kv_max=1024): the existing (!quantized_kv || Q->ne[1] > 2 || gqa_ratio >= 12) guard holds on Pascal. 256/256 gqa 12 wins at nb=1 (1.36x @ kv 16384, 1.36x @ kv 65536); at nb=8 quantized sparse wins everywhere: 2.13x (256/256), 1.63x / 1.45x (128/128 gqa 4 / 8) @ kv 16384. The 128/128 nb=1 cases stay dense per the guard — correct, since the per-launch K/V f16 conversion dominates there (break-even measured, not a loss).

DSA/MLA shapes with the gqa gates dropped (f16 KV, nb=1, kv=49152):

shape dense sparse gain
512/512 gqa 8 (DeepSeek-V4/GLM-5.2) 541 us 78 us 6.97x
512/512 gqa 8, nh 2 (gemma-4 global attn) 1043 us 106 us 9.81x
576/512 gqa 16 (Kimi K3.1 MLA) 1107 us 116 us 9.56x

The GCN gqa>=16/32 gates for 512/512 and 576/512 were tuned for GCN's LDS-heavy gather; on Pascal the gathered rows stream at full memory bandwidth and low-gqa sparse wins big, so the patch drops those gates for NVIDIA.

The kernels are arch-neutral (index gather + ballot compaction only), so this is a straight ungate + thresholds. Happy to fold it into this PR or send it as a follow-up — whichever you prefer.

@sorasoras

Copy link
Copy Markdown

Two additions to the Pascal enablement posted above:

1. Interaction with #30792 (native q8_0 KV tile FA): both PRs rewrite fattn-tile.cuh and they conflict. I resolved the 3-way merge — the q8_0 loader branches need && !use_sparse (the sparse path always runs on the f16-converted scratch, the raw q8_0 readers have no index indirection), template signatures union, and the kernel instantiation sites gain the extra template args. Merge reference: https://gist.github.com/sorasoras/5744379227b229b71a1a68deaf864d21 — with it applied, both PRs build and pass the full FLASH_ATTN_EXT eval on sm_61. Note #30792 also needs a pre-Volta fix to compile for sm_61 (details posted there).

2. Reusable break-even test cases: my Pascal tuning was driven by a set of dense/sparse paired perf cases added to test-backend-ops.cpp — 256/256 gqa 12 over kv {4096…65536} × nb {1…64} with n_kv_max {0, 2048} (dense reference pairs), a selection-fraction sweep at fixed depth (0.8%→25%), quantized-KV (q8_0) dense/sparse pairs, and DSA/MLA shapes (512/512 gqa 8, 576/512 gqa 16). They auto-serve as correctness eval cases too. Happy to send them as a follow-up commit on this PR if useful for tuning the other architectures.

@dark-penguin

dark-penguin commented Nov 23, 2026 •

Copy link
Copy Markdown

I'm trying this (#32741 with #30792 merged with the "merge reference" gist) on 2x RX6800 on Qwen 3.8 Flash-Next (Linux, ROCm v7.2.3, layer split mode, no pipeline parallelism, no MTP - I can provide more details if something in particular is important).

It does not look related to running out of memory because I've made sure to have more than enough headroom, and each one works on its own but not both of them.

I don't think I could have messed up the merge since the patch applied properly, but just to make sure - and for anyone else who wants to try this but has trouble figuring out how to apply the "merge reference" - here is what I got: https://github.com/dark-penguin/llama.cpp/tree/cherrypick/q8_0_x_sparse_fattn

Qwen 3.8-27B seems to be unaffected.

Logs
[38775] 0.25.278.964 I srv          init: init: chat template, thinking = 0
[38775] 0.25.278.986 I srv          init: preserve_reasoning kwarg: true
[38775] 0.25.278.989 W srv          init: chat template supports preserving reasoning, it is enabled by default (may use more tokens, disable via --no-reasoning-preserve)
[38775] 0.25.279.047 I srv  server_run_i: model loaded
[38775] 0.25.279.054 I srv  server_on_li: listening on http://127.0.0.1:38775
[38775] 0.25.279.155 I srv    operator(): child server monitoring thread started, waiting for EOF on stdin...
[38775] 0.25.279.309 I srv  update_slots: all slots are idle
0.28.526.354 I srv  proxy_reques: proxying request to model Qwen3.8-Flash-Next on port 38775
[38775] 0.25.281.186 I srv  server_strea: conv_id= (empty=1)
[38775] 0.25.303.418 I slot       select: id  0 | task -1 |  - skipping, slot is empty
[38775] 0.25.303.425 I slot       select: id  0 | task -1 | selected slot by LRU, n_tokens = 0, t_last = -1
[38775] 0.25.303.429 I srv  update_promp: updating prompt cache
[38775] 0.25.303.435 I srv          load:  - looking for better prompt, base f_keep = -1.000, f_sim = 0.000
[38775] 0.25.303.441 I srv        update:  - cache state: 0 prompts, 0.000 MiB (limits: 32768.000 MiB, 131072 tokens, 34359738368 est)
[38775] 0.25.303.444 I srv  update_promp: prompt cache update took 0.01 ms
[38775] 0.25.303.519 I slot launch_slot_: id  0 | task -1 | sampler chain: logits -> penalties -> ?dry -> ?top-n-sigma -> top-k -> ?typical -> top-p -> ?min-p -> ?xtc -> temp-ext -> dist 
[38775] 0.25.303.661 I slot launch_slot_: id  0 | task -1 | sampler params: 
[38775] 	repeat_last_n = 64, repeat_penalty = 1.000, frequency_penalty = 0.000, presence_penalty = 1.500
[38775] 	dry_multiplier = 0.000, dry_base = 1.750, dry_allowed_length = 2, dry_penalty_last_n = 64
[38775] 	top_k = 20, top_p = 0.800, min_p = 0.000, xtc_probability = 0.000, xtc_threshold = 0.100, typical_p = 1.000, top_n_sigma = -1.000, temp = 0.700
[38775] 	mirostat = 0, mirostat_lr = 0.100, mirostat_ent = 5.000, adaptive_target = -1.000, adaptive_decay = 0.900
[38775] 0.25.303.666 I slot launch_slot_: id  0 | task 0 | processing task, is_child = 0
[38775] 0.25.303.683 I slot   operator(): id  0 | task 0 | new prompt, n_ctx_slot = 131072, n_keep = 0, task.n_tokens = 8835
[38775] 0.25.303.691 I slot   operator(): id  0 | task 0 | cached n_tokens = 0, memory_seq_rm [0, end)
0.31.981.482 I srv  proxy_reques: proxying request to model Qwen3.8-Flash-Next on port 38775
0.41.982.282 I srv  proxy_reques: proxying request to model Qwen3.8-Flash-Next on port 38775
[38775] 0.40.666.387 I slot print_timing: id  0 | task 0 | prompt processing, n_tokens =   4096, progress = 0.46, t =  15.36 s / 266.62 tokens per second
[38775] 0.40.666.391 I slot   operator(): id  0 | task 0 | cached n_tokens = 4096, memory_seq_rm [4096, end)
[38775] 0.40.671.811 I sched_graph_realloc: graph reallocation: nodes = 7263 (changed = 0), splits = 163, n_same = 1, n_diff = 0
[38775] 0.47.281.758 I slot print_timing: id  0 | task 0 | prompt processing, n_tokens =   4739, progress = 0.54, t =  21.98 s / 215.62 tokens per second
[38775] 0.47.281.762 I slot   operator(): id  0 | task 0 | cached n_tokens = 4739, memory_seq_rm [4739, end)
[38775] 0.47.331.981 I slot create_check: id  0 | task 0 | created context checkpoint 1 of 32 (pos_min = 4738, pos_max = 4738, n_tokens = 4739, size = 112.571 MiB)
[38775] 0.47.342.046 I sched_graph_realloc: graph reallocation: nodes = 7263 (changed = 0), splits = 163, n_same = 2, n_diff = 0
0.51.982.085 I srv  proxy_reques: proxying request to model Qwen3.8-Flash-Next on port 38775
1.01.981.814 I srv  proxy_reques: proxying request to model Qwen3.8-Flash-Next on port 38775
[38775] 1.03.040.524 I slot print_timing: id  0 | task 0 | prompt processing, n_tokens =   8831, progress = 1.00, t =  37.74 s / 234.02 tokens per second
[38775] 1.03.040.528 I slot   operator(): id  0 | task 0 | cached n_tokens = 8831, memory_seq_rm [8831, end)
[38775] 1.03.074.852 I slot init_sampler: id  0 | task 0 | init sampler, took 34.29 ms, tokens: text = 8835, total = 8835
[38775] 1.03.125.322 I slot create_check: id  0 | task 0 | created context checkpoint 2 of 32 (pos_min = 8830, pos_max = 8830, n_tokens = 8831, size = 112.571 MiB)

< ... freezes ... >

1.11.981.341 I srv  proxy_reques: proxying request to model Qwen3.8-Flash-Next on port 38775
1.21.982.214 I srv  proxy_reques: proxying request to model Qwen3.8-Flash-Next on port 38775
1.31.981.649 I srv  proxy_reques: proxying request to model Qwen3.8-Flash-Next on port 38775
1.41.982.104 I srv  proxy_reques: proxying request to model Qwen3.8-Flash-Next on port 38775

< ... I hit Ctrl+C, and terminate the benchmark too ... >

^C1.44.537.700 E srv    operator(): http client error: Failed to read connection
1.44.537.886 I srv    operator(): operator(): cleaning up before exit...
1.44.537.958 I srv    unload_all: stopping model instance name=Qwen3.8-Flash-Next
[38775] 1.41.291.131 I srv    operator(): exit command received, exiting...
[38775] 1.41.308.808 W srv          stop: cancel task, id_task = 0
1.54.547.973 W srv           run: force-killing child process for name=Qwen3.8-Flash-Next after timeout
1.55.307.057 I srv           run: instance name=Qwen3.8-Flash-Next exited with status 1

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 ggml changes relating to the ggml tensor library for machine learning testing Everything test related

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants