Skip to content

ggml/CUDA+HIP: Flash Attention with indexed bias - #33063

Merged
pwilkin merged 7 commits into
masterfrom
pwilkin/inkling-fattn-bias-cuda
Nov 26, 2026
Merged

pwilkin merged 7 commits into
masterfrom
pwilkin/inkling-fattn-bias-cuda

Conversation

@pwilkin

@pwilkin pwilkin commented Nov 25, 2026

Copy link
Copy Markdown
Member

Overview

Implements Flash Attention with indexed bias in CUDA + HIP.

Additional information

CUDA/HIP implementation of the contract in #32740

Requirements

pwilkin and others added 4 commits November 25, 2026 19:05
Replays the #32740 bias support on the shared typed tile loader, adds bias
in F32 to match the CPU reference and routes rows via KV_indirection.

Assisted-by: SimpleCoder
(cherry picked from commit de58aab)
An all -inf mask row has a zero softmax sum, which divided gave NaN. Guard
the tile, vec and results-combine divisions so it gives zeros, as ggml-cpu.

Assisted-by: SimpleCoder
(cherry picked from commit 50bbc59)
(cherry picked from commit bbf6c55)
@pwilkin
pwilkin requested review from a team and ggerganov as code owners November 25, 2026 18:57
@pwilkin

pwilkin commented Nov 25, 2026

Copy link
Copy Markdown
Member Author

The CI regressions are from the Hy4_flash commit, they're unrelated (unless it's some new one).

Comment thread ggml/src/ggml-cuda/fattn-common.cuh Resolved
Comment thread ggml/src/ggml-cuda/fattn-common.cuh Outdated
Comment on lines +1459 to +1460
const bool scan_mask = !use_sparse && mask && mask->ne[2] == 1 && mask->ne[1]/ncols1 >= ntiles_x &&
n_kv_cols % FATTN_KQ_STRIDE == 0 && (Q->ne[1] >= 1024 || Q->ne[3] > 1 || kv_rows);

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.

Why is this being changed?

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.

Added comment.

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.

Should scan_mask ever be set to true for a bias mask? It only provides a speedup if there is padding at the end that can be skipped.

Comment thread ggml/src/ggml-cuda/fattn-tile.cuh Resolved
Comment thread ggml/src/ggml-cuda/fattn-tile.cuh Resolved
Comment thread ggml/src/ggml-cuda/fattn-vec.cuh Resolved
Comment thread ggml/src/ggml-cuda/fattn-vec.cuh Resolved
@ShapeShifter499

ShapeShifter499 commented Nov 25, 2026 •

Copy link
Copy Markdown

I worked on a port of the CUDA implementation of this feature onto the current master (my own branch, now closed as a duplicate of this PR) and verified it on an RTX 3060 Ti (cc 8.6). Some findings that may be useful while reviewing this PR — they are about the original implementation and the current kernels, not about this diff, which I have not built:

The contract to implement is the CPU reference in ggml/src/ggml-cpu/ops.cpp (ggml_compute_forward_flash_attn_ext_f16_one_chunk):

n_bins  = bias_table->ne[0]                        // the table is [n_bins, n_head, n_query]
query   = iq3*neq1 + iq1                            // the queries of all streams are flattened
head    = iq2
bin     = bias_indices[query*row_stride + key]
value   = bias_table[(query*n_head + head)*n_bins + bin]

The original CUDA code in the first commit of #32740 (1fa93f902) read the number of bins from dim 1 and indexed the table as if the queries came first — that is the layout before #33053 changed the table the Inkling 2 graph builds.

The head of a column in the tile kernel is head0 + col % ncols2, because the query index is col_Q_0 + col / ncols2 (so the head is the remainder). If the head is taken as head0 alone, the GQA head grouping silently reads another head's bias. Related: forcing ncols2 == 1 breaks the kernel's grid decomposition — the launch grid is blocks_num.z = ntiles_z_gqa * K->ne[2] * Q->ne[3], but the kernel splits it as blockIdx.z / (ne02 / ncols2), so a smaller ncols2 makes the kernel expect a larger grid than the launch produces. That showed up as all 12 kv_rows=1 op-test cases failing at NMSE ~1.8 while the other 12 passed.

The tile kernel and K/V row lists: it passes nullptr for the row indices to the KV loader, so it reads the K/V cache directly and does not go through a row list; the loader itself does support them. The CPU reference broadcasts the K/V over the streams in that case (ik3 = iq3 / rk3), which the CUDA kernels do not do, so for a row list with more than one stream the K/V stream offset needs the same broadcast.

Measurements (RTX 3060 Ti, cc 8.6, Inkling 2 Mini UD-Q4_K_M, the tile kernel):

  • the 12 FLASH_ATTN_EXT indexed-bias op-test cases that the tile kernel supports pass against the CPU reference (test-backend-ops test -o FLASH_ATTN_EXT -b CUDA0);
  • on the real model the answer is byte-identical to the dense path (sha256 cbd095a0f65be35a42ffdbbcb15b65f6e2600b546b2224af522c2048514df6b4);
  • the memory breakdown with the compact bias is 7861 = 658 free + (6901 = 5640 model + 1227 KV + 33 compute) + 300 MiB, against 7861 = 622 free + (7034 = 5640 model + 1227 KV + 166 compute) + 204 for the dense path — i.e. the attention mask is 166 MiB here, and the KV cache is the term that grows with the context.

Happy to test a branch of this PR with test-backend-ops if that would help.

EDIT: AI assisted

Assisted-by: Hermes-Agent:minimax/MiniMax-M3

@pwilkin

pwilkin commented Nov 25, 2026

Copy link
Copy Markdown
Member Author

@JohannesGaessler aight, should be addressed now.

@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 25, 2026
Comment thread ggml/src/ggml-cuda/fattn-tile.cuh Resolved
Comment thread ggml/src/ggml-cuda/fattn-tile.cuh Resolved
Comment thread ggml/src/ggml-cuda/fattn-vec.cuh Resolved
@Davidyz

Davidyz commented Nov 26, 2026 •

Copy link
Copy Markdown

Is this supposed to be the only remaining PR required to fix the compute buffer problem? I tried building this locally and ran the Q8_0 quant from ggml-org, and I'm still seeing 12GB+ computing buffer on a tiny context window (4096):

$ ./build/bin/llama-server -m ./Inkling-2-Mini-Q8_0.gguf -fitt 256 -np 1 -c 4096 -ub 128 -ctk q8_0 -ctv q8_0 -lv 4
...
0.14.135.269 I common_params_fit_impl: memory for test allocation by device:
0.14.135.274 I common_params_fit_impl: id=0, n_layer= 2, n_part= 1, overflow_type=4, mem= 13390 MiB
0.14.135.276 I common_params_fit_impl: set ngl_per_device_high[0].n_layer=2
0.14.306.606 I common_memory_breakdown_print: | memory breakdown [MiB]  | total   free     self   model   context   compute    unaccounted |
0.14.306.610 I common_memory_breakdown_print: |   - CUDA0 (RTX 3060 Ti) |  7861 =  553 + (13381 =   469 +       0 +   12912) +       -6073 |
0.14.306.610 I common_memory_breakdown_print: |   - Host                |                 26239 = 26050 +     181 +       7                |
...

Edit: It'll be convenient for users if there were a checklist that tracks the follow-ups needed to fix the compute buffer problem (eg., backend support for FA with indexed bias). I imagine #32910 would be a good place for this.

azjhf-dev added a commit to azjhf-dev/Avalon that referenced this pull request Nov 26, 2026
…R #33063

Ports pwilkin's indexed-bias FA kernels (ggml-org/llama.cpp#33063, tip
a5e173111, OPEN/unmerged) into the fork, adapted for fork divergence:

- no kv_rows/KV_rows anywhere: all rows plumbing dropped, mask width is
  K->ne[1] directly
- llama-graph build_attn_mha: replaces the offload_kqv CPU-pin fallback
  with unconditional ggml_flash_attn_ext_add_indexed_bias; dispatch now
  follows the backends' supports_op
- fattn.cu: removes the indexed-bias reject; selection block added (tile
  for hs 128, tile/vec for hs 64 without softcap; vec only when
  softcap==0 && Q->ne[1]==1 && K->ne[1]%FATTN_KQ_STRIDE==0)
- tile/vec kernels: indexed_bias template param + bias.add at the mask
  site; fixup/combine/gate divisions route through fattn_normalize so a
  fully masked query returns 0 like the CPU backend
- mma kernel: signature param only, biased ops never dispatch to it
- HIP: narrower tile widths for indexed bias; F8_E4M3 register tuning
  dropped (fork has no F8 type); vgpr-check mangled names updated
- ggml: exported ggml_validate_flash_attn_ext_indexed_bias, used by
  add_indexed_bias and the RPC server
- tests: test_flash_attn_ext_indexed_bias adapted without kv_rows
  (18 cases, all pass on CPU)

Verification: CPU build + 18/18 FLASH_ATTN_EXT indexed-bias backend
tests pass. CUDA/HIP graft is REVIEW-ONLY - not compile-checked (no
GPU toolchain in this environment).
Comment thread ggml/src/ggml-rpc/ggml-rpc.cpp Resolved
Comment thread ggml/src/ggml.c Resolved
@pwilkin

pwilkin commented Nov 26, 2026

Copy link
Copy Markdown
Member Author

Is this supposed to be the only remaining PR required to fix the compute buffer problem? I tried building this locally and ran the Q8_0 quant from ggml-org, and I'm still seeing 12GB+ computing buffer on a tiny context window (4096):

$ ./build/bin/llama-server -m ./Inkling-2-Mini-Q8_0.gguf -fitt 256 -np 1 -c 4096 -ub 128 -ctk q8_0 -ctv q8_0 -lv 4
...
0.14.135.269 I common_params_fit_impl: memory for test allocation by device:
0.14.135.274 I common_params_fit_impl: id=0, n_layer= 2, n_part= 1, overflow_type=4, mem= 13390 MiB
0.14.135.276 I common_params_fit_impl: set ngl_per_device_high[0].n_layer=2
0.14.306.606 I common_memory_breakdown_print: | memory breakdown [MiB]  | total   free     self   model   context   compute    unaccounted |
0.14.306.610 I common_memory_breakdown_print: |   - CUDA0 (RTX 3060 Ti) |  7861 =  553 + (13381 =   469 +       0 +   12912) +       -6073 |
0.14.306.610 I common_memory_breakdown_print: |   - Host                |                 26239 = 26050 +     181 +       7                |

This doesn't look like it's the KV cache. This looks like the OP offload to GPU with the model fully on CPU (see the host usage).

@Davidyz

Davidyz commented Nov 26, 2026

Copy link
Copy Markdown

This doesn't look like it's the KV cache. This looks like the OP offload to GPU with the model fully on CPU (see the host usage).

I'm mostly concerned about the compute column here, because from @ShapeShifter499's comment, the sizes of compute are 33 and 166. I tried the same llama-server command on a master build, and it didn't make much difference:

0.13.030.704 I common_memory_breakdown_print: | memory breakdown [MiB]  | total   free     self   model   context   compute    unaccounted |
0.13.030.707 I common_memory_breakdown_print: |   - CUDA0 (RTX 3060 Ti) |  7861 = 7722 + (13353 =   469 +       0 +   12883) +      -13214 |
0.13.030.707 I common_memory_breakdown_print: |   - Host                |                 26253 = 26050 +     181 +      21                |

I'm not actually sure whether this is related to the indexed bias, but the compute buffer problem has been there since the beginning, and #32740 claimed to solve the enormous VRAM usage issue, so I expected the overall VRAM usage to drop. When I run Qwen3.6-35b-a3b on the same rig with the same flags, the compute buffer is under 300MB combined, and I intuitively thought the compute buffer of inkling2-mini should be similar. Or is it just expected to have a huge compute buffer for this model?

@pwilkin

pwilkin commented Nov 26, 2026

Copy link
Copy Markdown
Member Author

@Davidyz please paste the results of the KV cache dumps from the logs, not the final breakdown.

@Davidyz

Davidyz commented Nov 26, 2026

Copy link
Copy Markdown

@pwilkin sorry about not including the info. The kv cache is actually reasonably sized (although squeezed to CPU). The -lv 4 log doesn't show much about the compute buffer. I'm happy to help but I'm not familiar with debugging llama.cpp, so if I'm missing anything again, please just let me know.

Details
0.14.431.276 I llama_context: n_ctx_seq (4096) < n_ctx_train (1048576) -- the full capacity of the model will not be utilized
0.14.431.437 I llama_context:        CPU  output buffer size =     0.76 MiB
0.14.431.440 I llama_kv_cache_iswa: creating non-SWA KV cache, size = 4096 cells
0.14.452.128 I llama_kv_cache:        CPU KV buffer size =    68.00 MiB
0.14.452.132 I llama_kv_cache: size =   68.00 MiB (  4096 cells,   8 layers,  1/1 seqs), K (q8_0):   34.00 MiB, V (q8_0):   34.00 MiB
0.14.452.133 I llama_kv_cache: n_rot_k = 128, n_embd_head_k_all = 128
0.14.452.133 I llama_kv_cache: n_rot_v = 64, n_embd_head_k_all = 128
0.14.452.174 I init_rotation:        CPU rotation buffer size =     0.62 MiB
0.14.452.190 I llama_kv_cache_iswa: creating     SWA KV cache, size = 1280 cells
0.14.499.962 I llama_kv_cache:        CPU KV buffer size =   106.25 MiB
0.14.499.965 I llama_kv_cache: size =  106.25 MiB (  1280 cells,  40 layers,  1/1 seqs), K (q8_0):   53.12 MiB, V (q8_0):   53.12 MiB
0.14.499.966 I llama_kv_cache: n_rot_k = 128, n_embd_head_k_all = 128
0.14.499.966 I llama_kv_cache: n_rot_v = 64, n_embd_head_k_all = 128
0.14.500.154 I init_rotation:        CPU rotation buffer size =     3.12 MiB
0.14.500.435 I llama_memory_recurrent:        CPU RS buffer size =     3.66 MiB
0.14.500.439 I llama_memory_recurrent: size =    3.66 MiB (     1 cells,  48 layers,  1 seqs  0 rs_seq), R (f32):    3.66 MiB, S (f32):    0.00 MiB, P (f32):    0.00 MiB
0.14.500.443 I sched_reserve: reserving ...
0.14.500.848 I resolve_fused_ops: resolving fused DeepSeek V4 HC support:
0.14.503.150 I resolve_fused_ops: fused DeepSeek V4 HC pre enabled
0.14.505.045 I resolve_fused_ops: fused DeepSeek V4 HC comb enabled
0.14.506.930 I resolve_fused_ops: fused DeepSeek V4 HC post enabled
0.14.513.571 E ggml_backend_cuda_buffer_type_alloc_buffer: allocating 12889.13 MiB on device 0: cudaMalloc failed: out of memory
0.14.513.575 E ggml_gallocr_reserve_n_impl: failed to allocate CUDA0 buffer of size 13515227648
0.14.513.576 E graph_reserve: failed to allocate compute buffers
0.14.522.453 E llama_init_from_model: failed to initialize the context: failed to allocate compute pp buffers

@Davidyz

Davidyz commented Nov 26, 2026

Copy link
Copy Markdown

After applying this patch from @erdincyasar, the compute buffer size dropped from 12,904 MB to 1,237 MB at -ub 128. Nice work! Maybe @pwilkin can help take a look and see if it can be merged?

@pwilkin

pwilkin commented Nov 26, 2026

Copy link
Copy Markdown
Member Author

@rgerganov @JohannesGaessler the fixes are up.

@pwilkin

pwilkin commented Nov 26, 2026

Copy link
Copy Markdown
Member Author

@Davidyz sure, but it's a separate PR since that's a scheduler issue.

@pwilkin

pwilkin commented Nov 26, 2026

Copy link
Copy Markdown
Member Author

All right, this no longer has any RPC code so I guess I can merge once checks are green.

…-bias-cuda-master

Assisted-by: Codex

# Conflicts:
#	scripts/hip/gcn-cdna-vgpr-check.py
@pwilkin

pwilkin commented Nov 26, 2026

Copy link
Copy Markdown
Member Author

Need a reapproval, the CI changes are not related.

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.

6 participants