Repository navigation
CUDA: prefer whole-tile FlashAttention scheduling for efficient two-stage kernels - #29435
Conversation
Exclude DGX Spark from the unconditional Ada-and-newer Stream-K preference so it uses the existing tile-efficiency heuristic. Select Stream-K when estimated tile efficiency is below 75%, and whole-tile scheduling at 75% or above. Efficiency measures how fully output tiles fill waves of resident CUDA blocks; it is not GPU utilization. This addresses the observed long-context prefill slowdown on Spark without query-length, KV-length or model-shape thresholds. Other GPU architectures and the separate MMQ Stream-K policy remain unchanged.
Remove the unconditional Ada-and-newer Stream-K preference so all NVIDIA GPUs reaching this FlashAttention selector use the existing tile-efficiency heuristic, extending the preceding Spark-only change. Select Stream-K below 75% estimated tile efficiency and whole-tile scheduling at 75% or above. Preserve the AMD WMMA exception and leave the separate MMQ Stream-K policy unchanged.
… neutral; not adopted Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_018co7fcJoEQXMxLezg7HpMU
Restrict the 75% tile-efficiency override to validated Spark D256 prefill shapes with two loading stages, Q in registers, and at least two resident blocks per SM. Check the tile shape, query chunk, sequence count, KV length, F16 KV types, and non-sparse attention before changing the schedule. Preserve the upstream policy for other configurations, including the D512 Gemma full-attention kernel that regressed under the unrestricted rule.
JohannesGaessler
left a comment
There was a problem hiding this comment.
If at all possible, please simplify the logic here. This seems very brittle to me.
|
Sure, I'm currently collecting numbers for the different GPUs for different models. I will be correcting/simplifying the logic soon. |
Remove the Spark-specific device and workload allowlists from the whole-tile override. Select eligible NVIDIA kernels using two effective loading stages, Q in registers, at least two resident blocks per SM, and the existing 75% tile-efficiency threshold. Preserve the upstream selector when these conditions are not met, including for the single-stage, shared-Q kernel that regressed under the unrestricted tile-efficiency policy.
|
Moved the PR to the review stage and added the performance numbers to the PR description Adding other reviews also @gaugarg-nv @ORippler |
|
What parts of the OP did you write vs. Claude? I don't think the explanation is correct. Also, please make your posts more concise. |
|
In // Optional optimization where the mask is scanned to determine whether part of the calculation can be skipped.
// Only worth the overhead if there is at lease one FATTN_KQ_STRIDE x FATTN_KQ_STRIDE square to be skipped or
// multiple sequences of possibly different lengths.
if (!use_sparse && mask && K->ne[1] % FATTN_KQ_STRIDE == 0 && (Q->ne[1] >= 1024 || Q->ne[3] > 1)) {
const int64_t s31 = mask->nb[1] / sizeof(half2);
const int64_t s33 = mask->nb[3] / sizeof(half2);
const dim3 blocks_num_KV_max(ntiles_x, Q->ne[3], 1);
const dim3 block_dim_KV_max(FATTN_KQ_STRIDE/2, 1, 1);
const int ne_KV_max = blocks_num_KV_max.x*blocks_num_KV_max.y;
const int iter_k = K->ne[1] / FATTN_KQ_STRIDE;
KV_max.alloc(ne_KV_max);
ggml_cuda_kernel_launch_params launch_params = ggml_cuda_kernel_launch_params(blocks_num_KV_max, block_dim_KV_max, 0, main_stream);
ggml_cuda_kernel_launch(flash_attn_mask_to_KV_max<ncols1>, launch_params,
(const half2 *) mask->data, KV_max.ptr, iter_k, s31, s33);
CUDA_CHECK(cudaGetLastError());
}For large batch sizes it is worthwhile to do a scan over the mask to skip fully masked out tiles of |
Thanks for the review, and sorry for the long posts. The OP drafted by Claude and ediited by me. My first version enabled the 75% tile-efficiency rule for all NVIDIA GPUs. Qwen3.8 27B gained a lot on Spark, but Gemma 4 regressed, its D512 kernel has a single-stage pipeline and was stalling on K/V loads, so I limited whole tiles to two-stage kernels. |
Thanks for the lead. In latest commit whole tiles are only used if the mask scan runs and the kernel has the two-stage pipeline (plus the existing 75% check). Qwen3.8 27B, dgx spark, 64K prompt:
max_blocks_per_sm >= 2 instead of the stage check enabled whole tiles for non-GQA kernels (no cp.async, 2 blocks/SM), which made -18.8% for Phi-3.5-mini in prefill, so I kept the stage check. |
| ggml_backend_cuda_context & ctx, ggml_tensor * dst, fattn_kernel_t fattn_kernel, const int nwarps, const size_t nbytes_shared, | ||
| const int nbatch_fa, const bool need_f16_K, const bool need_f16_V, const bool stream_k, const bool use_sparse, | ||
| const int warp_size = WARP_SIZE | ||
| const int warp_size = WARP_SIZE, const bool allow_whole_tiles = false |
There was a problem hiding this comment.
| const int warp_size = WARP_SIZE, const bool allow_whole_tiles = false | |
| const int warp_size = WARP_SIZE, const bool async_kv_preload = false |
So far we are not observing that anything other than the asynchronous KV preload is relevant so I think this is a more descriptive name.
|
Addressed the review comments |
PerformanceTable generated with
On my RTX 4090/5090 I'm only seeing small changes and those changes are quite inconsistent. I would say to enable the changes in this PR only for DGX spark. |
|
Thanks for testing, I have added the spark check in the latest commit |
…pstream ggml-org#29435: prefer whole tiles over stream-K on DGX Spark when async KV preload + mask scan with >=75% tile efficiency. ggml-org#30517: Q2_K/Q3_K/Q6_K VDR 1->2, two rows per block (low-bit, GB10 IQ2_S/IQ3_S, per-type GCN nwarps, Q3_K/Q6_K prefetch distance 1. Cherry-pick conflicts resolved manually: local master already has later upstream commits on these files (HIP calc_max_nwarps rename, need_f16_KV), so hunks were adapted to the local state. EOF )
Overview
Improve CUDA FlashAttention prefill performance by selecting whole-tile scheduling when the selected kernel can use it efficiently.
The existing Ada-and-newer NVIDIA policy always selects Stream-K in this scheduling path. Our investigation found that whole-tile scheduling substantially improves some long-context workloads on DGX Spark, with smaller improvements on RTX 5090.
This change uses kernel properties to distinguish eligible configurations while preserving the original scheduling policy elsewhere.
Implementation
The new whole-tile override requires the following:
If any condition fails, the original selector remains in control. Failing a new guard does not universally force Stream-K; the existing architecture-specific fallback is preserved.
Root cause and rationale:
For the profiled long-context workload, Stream-K partitions the work into contiguous ranges, starting blocks for the same KV head at different K offsets. Causal truncation further separates their progress through K/V, reducing opportunities for reuse in L2. Whole-tile scheduling improves that reuse: on dgx spark, the measured L2 hit rate increased from 41.79% to 96.09%; the baseline was consuming approximately 91% of peak DRAM bandwidth.
Whole-tile scheduling is not beneficial for every kernel specialization. In a controlled experiment with the same inputs, fixed grid, comparable clocks, and equal occupancy, the single-stage D512 kernel took approximately 59% more time with whole tiles. Profiling showed increased waits on K/V load dependencies. Unlike the two-stage pipeline, this specialization cannot overlap prefetching the next K/V tile with computation on the current tile. This was the kernel responsible for the Gemma regression observed with the earlier unrestricted policy and motivates retaining the effective-stage condition.
Performance testing
Both builds used the same model files and benchmark configuration:
Representative command:
The following numbers are prefill throughput, excluding startup, model loading, and warmup. Throughput is input tokens divided by mean measured prefill time.
DGX Spark
Native ARM64 Release build, CUDA 13.4.1.
RTX 5090
Native x64 Release build, CUDA 13.1, driver 616.92.
Correctness validation
test-backend-ops -o FLASH_ATTN_EXTpassed all 3,982/3,982 cases.Requirements