Repository navigation
CUDA: read a gathered relative-position bias inside the vector flash attention - #413
danielhanchen wants to merge 5 commits into
Conversation
…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.
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 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".
| for (ggml_tensor * t : others) { | ||
| GGML_ASSERT(compute(ctx, t)); |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
| if (__all_sync(0xFFFFFFFF, all_masked)) { | ||
| n_chunks_skipped++; | ||
| continue; |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
| 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)) { |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
| 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]; |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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).
|
@codex review |
|
Codex Review: Didn't find any major issues. Nice work! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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).
|
Repinned to Since #386 ( Evidence, B200:
All arms give the same PPL, mean KLD 0 (printed as -0.000000) and top-1 100%, so the gate passes. (
|
Pin for the prebuilt: upstream b12602 (418fe97) plus these two commits (same kernel). Base branch base/upstream-418fe97b5.
What it changes
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)
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)