Skip to content

CUDA: sparse flash attention lists from the TOP_K_MASK picks - #520

Open
danielhanchen wants to merge 2 commits into
base/upstream-9a811bab3from
pin-qsa-topk-sparse
Open

danielhanchen wants to merge 2 commits into
base/upstream-9a811bab3from
pin-qsa-topk-sparse

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Dec 6, 2026 •

Copy link
Copy Markdown
Member

CUDA: sparse flash attention lists from the TOP_K_MASK picks

Summary

The unslothai/llama.cpp prebuilt is an aged upstream b#### tag plus the pins listed in scripts/unsloth/pr-set.json, merged in order. This pin is one commit on top of upstream b12966 (9a811bab3c4), so it needs no other pin. Once upstream has an equivalent change, the pin is dropped.

The problem

Qwen4-35B-A3B (qwen4exp) has QSA sparse-attention layers. Each decode step builds a dense [n_kv, n_tokens] mask with GGML_OP_TOP_K_MASK: it fills the row with -inf, then copies the mask value of every cell of the picked pools plus the tail cells. The sparse flash attention kernel then scans that dense row again (flash_attn_mask_to_sparse_indices) to compact its finite cells back into the index list it gathers. Both passes walk the whole cache, so their cost grows with context while the attention itself does not.

On an RTX 5090, per decoded token (10 QSA layers, nsys):

depth top_k_mask_kernel flash_attn_mask_to_sparse_indices
16k 41 us 97 us
64k 57 us 256 us

The fix

  • qsa-topk-sparse.cu (new): when a TOP_K_MASK node is the whole mask of a FLASH_ATTN_EXT and its only reader, the batch is decode / verify sized (16 rows or fewer, one stream) and no node in between writes over the picks or the mask memory, the TOP_K_MASK node is not run at its position.
  • At the attention node, a one-query sparse gather (ncols1 == 1) gets its index lists from one launch that reads the picks directly: a bitmap over the cells collects the cells of the live picks and the extra cells whose mask value is finite, then each thread lists a contiguous run of words. The lists are ascending and duplicate free, the same lists the dense compaction gives, and only the listed mask cells are written, which are the only ones the gather reads.
  • Any other kernel (the dense paths, the 8-query sparse tile) gets the dense mask built at the attention node, so every route keeps the bytes of the base.
  • fusion.cu: the plan is made where the other fusions are tried, and the picks are kept allocated until the attention node with the existing add_alloc_dep mechanism.
  • top-k-mask.cu, fattn.cu, fattn-common.cuh: one hook each (skip, list build, dense fallback).
  • A mask (or a view of it) flagged as a graph output is never planned, and the cell bitmap stays within the default 48 KiB of shared memory together with the kernel's static 1040 bytes, so a cache past about 384k cells keeps the base path.
  • Kill switch: GGML_CUDA_QSA_TOPK_SPARSE=0 restores the base path. HIP and MUSA never plan it.
  • tests/test-backend-ops.cpp: QSA_TOPK_FA cases, a TOP_K_MASK feeding FLASH_ATTN_EXT (D 256, GQA 12, pools of 16 cells, 128 picks, 15 tail cells): 1 / 3 / 8 / 16 rows at 4k / 16k / 64k cells, plus tail-only rows, picks that include the pools under the tail, and masks with -inf cells. The 1 and 3 row cases at 16k and 64k take the gather route, the others the dense fallback.

Evidence

Test trees: the pin-set tree at b13024 (the scripts/unsloth/pr-set.json pins of the next release plus the open round-2 candidates #508, #510, #511, #512, #514, #515, #516 and #517), without (A) and with (SP) this pin, and SP with GGML_CUDA_QSA_TOPK_SPARSE=0 (SPK). Device: one RTX 5090 (sm_120a, CUDA 13.0, driver 610.57), Qwen4-35B-A3B UD-Q4_K_XL fully on the GPU, FA on.

Check Result
test-backend-ops -b CUDA0 -o QSA_TOPK_FA SP 30 / 30, SPK 30 / 30
test-backend-ops -b CUDA0 -o TOP_K_MASK A 38 / 38, SP 38 / 38, SPK 38 / 38
test-backend-ops -b CUDA0 -o FLASH_ATTN_EXT SP 4837 / 4837
Engagement, nsys, decode at 16k and 64k (per token) SP: qsa_topk_sparse_lists 10 launches, top_k_mask_kernel and flash_attn_mask_to_sparse_indices 0. SPK: the two base kernels, 10 launches each, as in A
Greedy text, llama-server at 0 / 16k / 64k, with and without MTP 2 identical across A, SP, SPK and A again at every depth
No-break greedy md5, 64 tokens identical A / SP / SPK on Qwen4-35B-A3B, Qwen3.8-27B, Qwen3.8-Flash-Next (short prompt and a 10k-token prompt), Inkling-2-Mini, Qwen3-0.6B, gemma-3-1b, gemma-4-E2B, granite-4.0-h-tiny and Qwen3-30B-A3B
Pin set at b13024 (llama_pinset.py sim), release pr-set + #508 #510 #511 #512 #514 #515 #516 #517 + pin-topk-oneblock + this pin all 77 pins merge, 0 refused, pin_contract all intact, merge_checks clean
HIP compile (gfx1201, ggml-hip + test-backend-ops) pending

Kernel time per decoded token (nsys):

depth base: top_k_mask_kernel + flash_attn_mask_to_sparse_indices pin: qsa_topk_sparse_lists
16k 43.7 + 97.1 = 140.8 us 78.5 us
64k 76.5 + 278.8 = 355.3 us 119.8 us

llama-bench tg128, tok/s, median of 3 rotated rounds (each round -r 3). The A/A spread is the range over the A and A2 runs; the first A run at 64k (184.3, a cold start) is left out:

depth A A2 SPK SP SP vs A A/A spread
0 216.75 216.58 216.66 216.71 0.0% 0.2%
16k 205.57 205.40 205.57 206.79 +0.6% 0.26%
64k 194.22 194.36 194.50 199.97 +2.9% 0.25%

Every SP run is above every A, A2 and SPK run at 16k and 64k. The kill switch matches the base.

llama-server decode tok/s, 256 tokens, raw completion:

  • Without MTP (1 round): 64k 195.6 vs 190.5 (A2) and 190.8 (SPK), +2.7%; 16k 201.9 vs 201.1 / 201.0, +0.4%; 0 equal.
  • MTP 2 (2 rounds, draft acceptance identical in every arm): 64k 296.2 / 295.3 vs 289.9 to 290.7 for A, A2 and SPK, +1.8%; 16k 305.1 / 304.5 vs 302.9 to 304.9, inside the spread; 0 equal.

Not proven

  • Speed was measured on one RTX 5090 only. Other NVIDIA cards were not timed; T4, A100, L4 and Blackwell datacenter parts were not run.
  • The gain at 16k (+0.6%) is small. The list build costs 78.5 us per token at 16k and 119.8 us at 64k, which leaves room to make it cheaper.
  • Batches above 4 rows (the 8-query sparse tile and the dense kernels) keep the dense mask, built at the attention node; only 1 to 4 rows (decode and the MTP 2 verify) take the new lists.
  • HIP: the file compiles to stubs there and is never planned; the gfx1201 compile check is pending. MUSA was not compiled.
  • The no-MTP server row is one round.

When a TOP_K_MASK is the whole mask of a FLASH_ATTN_EXT, decode and
verify sized (16 rows or fewer, one stream), the mask node is not run at
its position. A one-query sparse gather builds its index lists from the
picks, pool cells and extra cells in one launch (a bitmap keeps them
ascending and duplicate free, the same lists the dense mask compaction
gives) and writes only the listed mask cells. Any other kernel gets the
dense mask at the attention node. The picks are kept allocated until the
attention node. Output is bit-identical. CUDA only;
GGML_CUDA_QSA_TOPK_SPARSE=0 turns it off.

tests: QSA_TOPK_FA (gather and dense routes, 1 / 3 / 8 / 16 rows,
4k / 16k / 64k cells, tail only, pools under the tail, masked cells)
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Dec 6, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-12-06T14:38:15.949162Z ca67625 Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 2895a420ae

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +113 to +114
if (t->type != GGML_TYPE_F16 || mask->type != GGML_TYPE_F16 || t->ne[1] > QSA_TOPK_SPARSE_MAX_ROWS || t->ne[2] != 1 ||
t->ne[3] != 1 || !ggml_is_contiguous(t) || size_t((n_kv + 31)/32)*sizeof(uint32_t) > QSA_TOPK_SPARSE_MAX_BITS_SMEM) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Include static shared memory in the sparse-kernel limit

For a one-query sparse gather with n_kv = 393216, this guard accepts a 48 KiB bitmap, but qsa_topk_sparse_lists also declares 1,028 bytes of static shared memory for thread_offsets and row_count. The combined allocation exceeds CUDA's default 48 KiB per-block limit. Neither this launch nor ggml_cuda_kernel_launch opts the kernel into a larger shared-memory allowance, so an otherwise valid long-context attention operation fails at launch instead of using the previous dense-mask path. Subtract the static allocation from the limit, or explicitly opt in after checking the device's supported limit.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in ca67625: the bitmap limit now leaves room for the kernel's 1040 bytes of static shared memory (ptxas -v), so a near-cap n_kv falls back to the dense path.

Comment on lines +54 to +55
const ggml_tensor * t = cgraph->nodes[i];
int fa = -1;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Preserve mask tensors exposed as graph outputs

When the TOP_K_MASK tensor or one of its views is marked GGML_TENSOR_FLAG_OUTPUT, having attention as its only graph reader does not make it safe to leave the mask partially initialized. This scan ignores output flags and skips views unconditionally, so it permits the sparse-gather path, which writes only selected finite cells and leaves all other mask cells containing stale allocation contents rather than -INFINITY. Reading the exported mask after graph execution therefore returns incorrect results. Reject plans with an exported mask or exported view, as the existing fusion checks do for intermediate outputs.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in ca67625: a TOP_K_MASK node or any view of it flagged as a graph output is no longer planned.

@danielhanchen danielhanchen self-assigned this Dec 6, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Bravo.

Reviewed commit: ca67625950

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

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

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant