Skip to content

CUDA: read a gathered relative-position bias inside the vector flash attention - #413

Open
danielhanchen wants to merge 5 commits into
base/upstream-418fe97b5from
inkperf4-up-relfa-skip
Open

danielhanchen wants to merge 5 commits into
base/upstream-418fe97b5from
inkperf4-up-relfa-skip

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Pin for the prebuilt: upstream b12602 (418fe97) plus these two commits (same kernel). Base branch base/upstream-418fe97b5.

What it changes

  1. A relative bias gathered into the dense F16 mask of a flash attention ([SUB,] [CONT,] GET_ROWS, CPY to F16, ADD of the F16 mask, FLASH_ATTN_EXT, only views in between) is read by the vector kernel from the table and the row indices (fattn-rel.cu, a has_rel path in fattn-vec.cuh) instead of materializing the [n_kv, n_q, n_head, n_seq] bias. The value is computed as the chain does: the F32 table entry (minus the sink term), rounded to F16, added to the mask in F32, rounded to F16. The KV split comes from the kernel without the bias. Taken only when the vector kernel would run (F16 / BF16 K and V, head sizes 64/128/256, no ALiBi or softcap), when the intermediates have no other users and the output does not overlap the inputs. Independent nodes between the chain and the attention run first.
  2. A warp of the vector kernel skips the 32 KV columns of an iteration when the mask is -inf in all of them for every query column of the block. Their scores would be -inf, so the running maximum, the sum and the accumulated V are unchanged (exp(-inf) == 0, the rescale factor is exp(0)). The skipping variant uses the occupancy and KV split of the kernel without it, so the combine is unchanged. This pays where whole KV chunks are masked: other sequences' cells in a unified KV cache, cells outside a sliding window, the unused tail.

Kill switches: GGML_CUDA_DISABLE_REL_BIAS_FA_FUSION=1, GGML_CUDA_DISABLE_FA_VEC_MASK_SKIP=1. test-backend-ops gets FA_REL_BIAS_FUSE (83 cases) and FLASH_ATTN_EXT cases with masked runs (ring windows, unused tails, masked splits, per-head bands, sinks).

Evidence (B200, one exclusive card, load-gated runs)

  • Inkling-2-Mini decode: 5 kernels fewer per attention visit (240 per token).
  • Share of the decode set: tg128 -6.4% on UD-Q8_K_XL with the rel-bias read off.
  • Masked-KV skip: 4 sequences at 32K depth with a unified KV cache, 160.6 -> 188.8 tok/s (+17.6%); batch 1 unchanged.
  • KLD against the pin set (4 files; prefill, -ub 1/4/8, dense 4K, 4 and 2 sequences in a unified and a split KV cache up to 8K): PPL string equal, mean KLD 0, top-1 100%.

Other NVIDIA GPUs (Colab T4, L4, A100-40GB, RTX PRO 6000 Blackwell Server; one card each, built from b12628 plus #399 plus the decode pins)

GPU (cc) file pp512 with it off tg128 with it off
T4 (7.5) UD-IQ1_S -0.4% -1.7%
L4 (8.9) UD-IQ1_S -0.3% -1.9%
L4 (8.9) UD-Q4_K_XL +0.2% -1.7%
A100 (8.0) UD-IQ1_S +0.1% -4.1%
A100 (8.0) UD-Q4_K_XL +0.0% -3.9%
A100 (8.0) UD-Q8_K_XL +0.3% -3.4%
RTX PRO 6000 (12.0) UD-IQ1_S -0.5% -3.2%
RTX PRO 6000 (12.0) UD-Q4_K_XL +0.0% -2.4%
RTX PRO 6000 (12.0) UD-Q8_K_XL +0.0% -2.1%
  • The masked-KV skip is a tie at batch 1 on all four (0.992-1.001 with it off); it pays with several sequences in a unified KV cache at depth, measured on B200 above.

…attention

A relative bias that is gathered into the dense F16 mask of a flash attention
([SUB,] [CONT,] GET_ROWS, CPY to F16, ADD of the F16 mask, FLASH_ATTN_EXT, with
only views in between) is now read by the vector kernel from the table and the
row indices, instead of materializing the [n_kv, n_q, n_head, n_seq] bias.

The value is computed as the chain does: the F32 table entry (minus the sink
term), rounded to F16, added to the mask in F32 and rounded to F16. The split
over the KV cache comes from the kernel without the bias, and the mask scan
stays off as it is for a mask with a head dimension, so the result is
bit-identical. The fusion is only taken when the vector kernel would run
(F16 or BF16 K/V, head sizes 64/128/256, no ALiBi or softcap), when the
intermediate results have no other users and the output does not overlap the
inputs. GGML_CUDA_DISABLE_REL_BIAS_FA_FUSION=1 turns it off.

Adds FA_REL_BIAS_FUSE to test-backend-ops (1-8 rows, 1-2 streams, n_kv 256 to
4096, GQA 3, head sizes 64/128/256, with and without the sink subtraction).

- CUDA: run independent nodes between the relative bias chain and its flash attention first
- CUDA: say why the relative bias fusion declines when GGML_CUDA_REL_BIAS_FA_DEBUG is set
A warp of the vector kernel now skips the 32 KV columns of an iteration when
the mask is -inf in all of them for every query column. Their scores would be
-inf, so the running maximum, the sum and the accumulated V come out the same
(exp(-inf) == 0, the maximum keeps its value, the rescale factor is exp(0)).
This covers unused cells at the end of the KV view and cells outside a
sliding window, also with the relative bias read in the kernel (a finite bias
plus -inf is -inf).

The skipping variant is launched with the occupancy and KV split of the kernel
without it, so the split and the combine are unchanged. Set
GGML_CUDA_DISABLE_FA_VEC_MASK_SKIP=1 to turn it off;
GGML_CUDA_FA_VEC_MASK_SKIP_DEBUG=1 prints the skipped chunks of the
relative-bias launches.

tests: FLASH_ATTN_EXT with masked runs (ring windows, unused tails, masked
splits, per-head bands, sinks) and FA_REL_BIAS_FUSE with a ring mask.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 23, 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-11-23T03:59:24.384664Z 260b1ff 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: 730804060e

ℹ️ 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 +236 to +237
for (ggml_tensor * t : others) {
GGML_ASSERT(compute(ctx, t));

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Reject intervening writes that alias fused bias inputs

When an independent node between the bias chain and attention reuses a bias input's allocation, computing it here destroys data that the fused kernel still needs. The dependency checks establish tensor independence, but ggml_gallocr frees these inputs at their original last consumers, and the overlap check only examines fa, not others. A standalone allocator reproduction with head size 64, 24 heads and 129 relative-position rows places an intervening Q projection over both subtraction inputs while the attention output passes every overlap check. Fusion then reads projection results as bias values, silently corrupting attention. Check intervening writes against all retained bias inputs or preserve their allocations through the fused launch.

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.

Confirmed and fixed in 260b1ff. The independent nodes between the bias chain and the attention run before the fused kernel, and the allocator can place them over a table input it freed after the chain's first node. The matcher now declines when any of them overlaps the table, the subtracted term, the row indices or the mask (the same check that already covered the attention output). New test-backend-ops case: FA_REL_BIAS_FUSE with an in-place write of either table input in between; it failed before (ERR 0.087 / 0.0009) and passes now. On Inkling-2-Mini the fusion still engages on every attention (48 per token) and the output is bit-identical to before.

Comment thread ggml/src/ggml-cuda/fattn-vec.cuh Outdated
Comment on lines +302 to +304
if (__all_sync(0xFFFFFFFF, all_masked)) {
n_chunks_skipped++;
continue;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Include all physical lanes in the mask-skip vote

On HIP devices with 64-lane wavefronts, such as CDNA GPUs, 0xFFFFFFFF includes only the lower 32 physical lanes, although this kernel packs two logical 32-thread warps into each wavefront. If the lower logical warp's KV chunk is fully masked but the upper chunk contains visible columns, this vote can cause the upper warp to skip valid attention contributions. The HIP backend compiles this shared source and enables skipping by default, so this affects ordinary masked decode, not just relative-bias fusion. Use the portable ggml_cuda_all helper with the full physical thread mask, or implement a correctly masked vote for each logical warp.

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.

Confirmed and fixed in d94ca3d: the vote is now ggml_cuda_all(all_masked), which uses the full physical thread mask (64 bits on HIP). On wave64 both logical warps of a wavefront skip only when both of their chunks are fully masked, so no visible column is skipped and control flow stays uniform across the wavefront. On NVIDIA the mask is 32 bits, so it is the same vote as before. I have no CDNA hardware here, so this one is checked by reading the HIP mask type and helper rather than by a run.

Comment thread ggml/src/ggml-cuda/fattn-rel.cu Outdated
Comment on lines +117 to +118
if (ggml_cuda_rel_use_count(cgraph, cpy) != 1 || ggml_cuda_rel_use_count(cgraph, add) != 1 ||
(cpy->flags & GGML_TENSOR_FLAG_OUTPUT) || (add->flags & GGML_TENSOR_FLAG_OUTPUT)) {

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 observable writes to the CPY destination

When the CPY destination is marked as an output or read through another reference, skipping CPY leaves that tensor unchanged even though its write is observable outside the fused chain. ggml_cpy creates a separate view of its destination, so checking the returned cpy tensor's flags and use count does not establish that the destination is private. A graph with an output-marked destination still has cpy use count 1 and no output flag on cpy, passing these checks. Check the destination and its aliases before removing the write, or retain CPY whenever its destination is externally observable.

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.

Confirmed and fixed in 260b1ff. The fused path does not run the CPY, so its destination must now be private: not an output, not a view of another tensor, and read by nothing but the CPY (a view of it read elsewhere also counts as a use). New test case: the F16 bias destination read again after the attention; it failed before and passes now. The Inkling 2 graph copies into a fresh tensor, so it still fuses.

Comment on lines +165 to +169
const ggml_tensor * B = sub->src[1];
rel.sub = (const char *) B->data;
rel.sub_h = B->nb[1];
rel.sub_q = B->nb[2];
rel.sub_s = nr*B->nb[2];

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 Apply the table view's mapping to the subtraction operand

When the view before CONT slices the subtraction result, the matcher accepts it and applies its offset and strides to A, but B is still indexed from its original base using unsliced head/query coordinates. For example, selecting the last 24 heads of a 48-head subtraction makes the materialized chain subtract B[24..47], whereas the fused kernel subtracts B[0..23]. A CPU reproduction with A filled with 10 and B[h] = h gives -14 for the first selected table entry, while the fused indexing gives 10. Propagate the view's coordinate mapping to B as well, or restrict this fusion to the exact zero-offset permutation whose subtraction indexing is supported.

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.

Confirmed and fixed in 260b1ff. With a subtraction, the view before the CONT must now be exactly the [head, rel row, token] permutation of the whole difference (zero offset, the permuted shape and strides); anything else keeps the separate kernels. New test case: the table taken from the last 24 heads of a 48-head difference; it failed before (ERR 0.023) and passes now. The Inkling 2 graph uses the full permutation, so it still fuses.

…physical warp

The skip vote used __all_sync(0xFFFFFFFF, ...). On 64-lane wavefronts (HIP
GCN / CDNA) two 32-thread logical warps share a wavefront and that mask covers
only the lower one, so the upper warp could skip KV columns that are visible to
it. Use ggml_cuda_all, which votes over the full physical warp: on wave64 both
logical warps skip only when both chunks are fully masked. On NVIDIA it is the
same vote as before.
… not cover

- The independent nodes between the bias chain and the attention run before
  the fused kernel. The allocator can place them over a table input it freed
  after the chain's first node, so none of them may overlap the table, the
  subtracted term, the row indices or the mask.
- The CPY into the F16 bias is not run, so its destination must not be an
  output, a view of another tensor or read by anything else.
- With a subtraction, the view before the CONT must be exactly the
  [head, rel row, token] permutation of the whole difference: the subtracted
  term is indexed by head and token of that view, so a slice of it would read
  the wrong entries.

test-backend-ops: FA_REL_BIAS_FUSE with an in-place write of either table
input in between, the bias destination read again after the attention, and
the table sliced from a 48-head difference (all four failed before).
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Nice work!

Reviewed commit: 260b1ffa4d

ℹ️ 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".

…ast as well

ggml_cast makes the CPY its own destination, and the graph counts that self reference as a use,
so the single-use check declined every bias built with ggml_cast. llama-graph casts the dense
relative bias since #386 (e328b4d), so decode on Inkling 2 lost the fused read: about 3% of
tg128 on a B200 (UD-Q4_K_XL 112.8 -> 109.5 tok/s).
@danielhanchen

Copy link
Copy Markdown
Member Author

Repinned to 627b5434a, a fast-forward of 260b1ffa4 (no force push): "CUDA: rel bias in flash attention: fuse the F16 bias made with ggml_cast as well".

Since #386 (e328b4da0), llama-graph builds the dense relative bias with ggml_cast. ggml_cast makes the CPY its own destination, and the graph counts that self reference as a use. So the single-use check here declined every such bias, and Inkling 2 decode lost the fused bias read. The fix counts the ggml_cast self reference, and test-backend-ops gains cases for the cast-built bias. No upstream change was involved, and the base stays base/upstream-418fe97b5.

Evidence, B200:

arm tree PPL mean KLD vs A top-1
A current pr-set.json on b12667 (a658404ac) 8.4647 - -
A again same 8.464749 -0.000000 100%
B + #396 77941e048, #413 627b5434a, both mirrors, on b12667 (b15c4ae7e) 8.464749 -0.000000 100%
D new pin set on b12671 (4d5f65714) 8.464749 -0.000000 100%
C D + ggml-org master (afbc31e0f) 8.464749 -0.000000 100%

All arms give the same PPL, mean KLD 0 (printed as -0.000000) and top-1 100%, so the gate passes. (llama_pinset.py gate prints FAIL here only because its KLD regex does not accept the minus sign. The verdict was read from the logs.)

  • The pin set with this commit passes verify --cuda on b12670 and b12671, including cuda-rel-bias-fa-fusion: 101/101 cases match the CPU.

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