Skip to content

CUDA: prefer whole-tile FlashAttention scheduling for efficient two-stage kernels - #29435

Merged
am17an merged 8 commits into
ggml-org:masterfrom
anujj:anujj/attention-scheduling-stream-k
Oct 5, 2026
Merged

am17an merged 8 commits into
ggml-org:masterfrom
anujj:anujj/attention-scheduling-stream-k

Conversation

@anujj

@anujj anujj commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

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:

  1. Exactly two effective loading stages in the selected MMA kernel.
  2. Tile efficiency of at least 75%, using the existing integer wave-efficiency calculation.

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:

  • ISL 64k
  • Batch and microbatch size: 4,096.
  • FlashAttention enabled; F16 K/V cache.
  • One excluded full-prompt warmup followed by three measured repetitions per build/model.

Representative command:

llama-bench -m <model.gguf> \
  -p 65536 -n 0 -d 0 \
  -b 4096 -ub 4096 -ngl 99 \
  -fa on -ctk f16 -ctv f16 \
  -t 20 -r 3 -o jsonl --progress

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.

Model / quantization Input tokens Baseline tokens/s Fixed tokens/s Throughput gain
Qwen 3.8 27B UD-Q4_K_M 65,536 550.64 734.98 +33.48%
Gemma 4 26B-A4B UD-Q4_K_M 65,536 2,122.24 2,351.81 +10.82%
Gemma 4 31B Q4_K_M 65,536 400.10 427.64 +6.88%
Qwen 3.6 35B-A3B UD-Q4_K_M 65,536 2,588.74 2,625.52 +1.42%
Nemotron 3.5 Lightning 30B-A3B UD-Q4_K_M 65,536 3,411.73 3,472.26 +1.77%
GPT-OSS 20B Q4_K_M 65,536 3,354.82 3,625.88 +8.08%
Meta-Llama-3-8B-Instruct Q4_K_M 8,192 2,961.27 3,135.26 +5.88%

RTX 5090

Native x64 Release build, CUDA 13.1, driver 616.92.

Model / quantization Input tokens Baseline tokens/s Fixed tokens/s Throughput gain
Qwen 3.8 27B UD-Q4_K_M 65,536 2,835.21 2,902.08 +2.36%
Gemma 4 26B-A4B UD-Q4_K_M 65,536 11,004.93¹ 11,202.08 +1.79%
Qwen 3.6 35B-A3B UD-Q4_K_M 65,536 10,608.03 10,648.41 +0.38%
Nemotron 3.5 Lightning 30B-A3B UD-Q4_K_M 65,536 15,317.31 15,439.89 +0.80%
GPT-OSS 20B Q4_K_M 65,536 14,355.81 15,038.88 +4.76%
Meta-Llama-3-8B-Instruct Q4_K_M 8,192 13,225.43 13,643.29 +3.16%

Correctness validation

  • RTX 5090: test-backend-ops -o FLASH_ATTN_EXT passed all 3,982/3,982 cases.
  • Perplexity comparisons, baseline → modified build:
    • Llama 3 8B, 8K context: 7.2840 → 7.2823.
    • Qwen 27B, 16K context: 5.5072 → 5.5033.
      • Qwen 27B, 64K context: 5.7976 → 5.7966.

Requirements

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.
@anujj
anujj requested a review from a team as a code owner September 25, 2026 16:21
@anujj
anujj marked this pull request as draft September 25, 2026 16:21
@github-actions github-actions Bot added ggml changes relating to the ggml tensor library for machine learning CUDA Related to the CUDA backend labels Sep 25, 2026
baykalokandemir added a commit to baykalokandemir/llama.cpp-bells-tortured that referenced this pull request Sep 28, 2026
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.
@anujj anujj changed the title Anujj/attention scheduling stream k cuda: guard whole-tile FlashAttention scheduling on Spark Sep 29, 2026

@JohannesGaessler JohannesGaessler left a 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.

If at all possible, please simplify the logic here. This seems very brittle to me.

@anujj

anujj commented Sep 29, 2026

Copy link
Copy Markdown
Contributor Author

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.
@anujj anujj changed the title cuda: guard whole-tile FlashAttention scheduling on Spark cuda: refine FlashAttention Stream-K scheduling using kernel properties Sep 30, 2026
@anujj
anujj marked this pull request as ready for review September 30, 2026 08:34
@anujj

anujj commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor Author

Moved the PR to the review stage and added the performance numbers to the PR description
@JohannesGaessler : could you please help to review, have simplified the logic and collected the numbers with the latest changes

Adding other reviews also @gaugarg-nv @ORippler

@anujj anujj changed the title cuda: refine FlashAttention Stream-K scheduling using kernel properties cuda: refine FlashAttention Stream-K scheduling Sep 30, 2026
@anujj anujj changed the title cuda: refine FlashAttention Stream-K scheduling CUDA: prefer whole-tile FlashAttention scheduling for efficient two-stage kernels Sep 30, 2026
@JohannesGaessler

Copy link
Copy Markdown
Contributor

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.

@JohannesGaessler

JohannesGaessler commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

In fattn-common.cuh there is this code:

    // 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 ncols1 * FATTN_KQ_STRIDE logical elements. Notably this is not considered when determining the start and stop indices for a stream-k decomposition. You are testing with a very large batch size of 4096 so presumably the workload per SM will be very unbalanced. And this should be even more pronounced in those kernel configs with only a single pipeline stage since those are also the ones with very low occupancy. Please check whether the execution of this code and/or max_blocks_per_sm == 1 is a better indicator for whether stream-k should be used.

@anujj

anujj commented Oct 1, 2026

Copy link
Copy Markdown
Contributor Author

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.

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.

@anujj

anujj commented Oct 1, 2026 •

Copy link
Copy Markdown
Contributor Author

In fattn-common.cuh there is this code:

    // 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 ncols1 * FATTN_KQ_STRIDE logical elements. Notably this is not considered when determining the start and stop indices for a stream-k decomposition. You are testing with a very large batch size of 4096 so presumably the workload per SM will be very unbalanced. And this should be even more pronounced in those kernel configs with only a single pipeline stage since those are also the ones with very low occupancy. Please check whether the execution of this code and/or max_blocks_per_sm == 1 is a better indicator for whether stream-k should be used.

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:

ubatch master this PR change
512 (no scan, Stream-K kept) 711.9 t/s 715.0 t/s +0.4%
4096 (scan, whole tiles) 511.1 t/s 677.0 t/s +32.5%

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.
test-backend-ops passes, OP numbers unchanged.

Comment thread ggml/src/ggml-cuda/fattn-common.cuh Outdated
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

@JohannesGaessler JohannesGaessler Oct 1, 2026 •

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.

Suggested change
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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done

@anujj

anujj commented Oct 1, 2026

Copy link
Copy Markdown
Contributor Author

Addressed the review comments

@JohannesGaessler

Copy link
Copy Markdown
Contributor
Performance

Table generated with scripts/compare-llama-bench.py

GPU Model Microbatch size Test t/s b11188 t/s 21470ad Speedup
RTX 4090 gemma 2B Q4_0 1024 pp65536 18704.07 18748.79 1.00
RTX 4090 gemma 2B Q4_0 2048 pp65536 18959.22 18995.87 1.00
RTX 4090 gemma 2B Q4_0 4096 pp65536 18930.39 18971.78 1.00
RTX 4090 gemma 2B Q4_0 8192 pp65536 18939.70 18952.82 1.00
RTX 4090 gpt-oss 20B MXFP4 MoE 1024 pp65536 9773.26 9890.77 1.01
RTX 4090 gpt-oss 20B MXFP4 MoE 2048 pp65536 9906.14 10136.92 1.02
RTX 4090 gpt-oss 20B MXFP4 MoE 4096 pp65536 9897.45 10128.44 1.02
RTX 4090 gpt-oss 20B MXFP4 MoE 8192 pp65536 9879.54 10117.26 1.02
RTX 4090 llama 1B Q4_0 1024 pp65536 24178.38 24474.99 1.01
RTX 4090 llama 1B Q4_0 2048 pp65536 23931.22 24029.67 1.00
RTX 4090 llama 1B Q4_0 4096 pp65536 23907.13 24003.36 1.00
RTX 4090 llama 1B Q4_0 8192 pp65536 23916.63 23997.88 1.00
RTX 4090 llama 8B Q4_0 1024 pp65536 5919.10 5937.93 1.00
RTX 4090 llama 8B Q4_0 2048 pp65536 5842.09 5872.61 1.01
RTX 4090 llama 8B Q4_0 4096 pp65536 5829.45 5863.61 1.01
RTX 4090 llama 8B Q4_0 8192 pp65536 5819.77 5854.89 1.01
RTX 5090 gemma 2B Q4_0 1024 pp65536 24404.45 24489.36 1.00
RTX 5090 gemma 2B Q4_0 2048 pp65536 24733.26 23139.98 0.94
RTX 5090 gemma 2B Q4_0 4096 pp65536 24617.76 23042.30 0.94
RTX 5090 gemma 2B Q4_0 8192 pp65536 24559.43 22992.65 0.94
RTX 5090 gpt-oss 20B MXFP4 MoE 1024 pp65536 15273.07 14912.33 0.98
RTX 5090 gpt-oss 20B MXFP4 MoE 2048 pp65536 15169.08 15483.22 1.02
RTX 5090 gpt-oss 20B MXFP4 MoE 4096 pp65536 15092.33 15416.21 1.02
RTX 5090 gpt-oss 20B MXFP4 MoE 8192 pp65536 15001.20 15336.61 1.02
RTX 5090 llama 1B Q4_0 1024 pp65536 31309.44 28813.89 0.92
RTX 5090 llama 1B Q4_0 2048 pp65536 32014.86 31181.25 0.97
RTX 5090 llama 1B Q4_0 4096 pp65536 31904.94 31101.26 0.97
RTX 5090 llama 1B Q4_0 8192 pp65536 31824.67 31040.83 0.98
RTX 5090 llama 8B Q4_0 1024 pp65536 7526.90 7239.41 0.96
RTX 5090 llama 8B Q4_0 2048 pp65536 7568.06 7588.89 1.00
RTX 5090 llama 8B Q4_0 4096 pp65536 7504.59 7546.81 1.01
RTX 5090 llama 8B Q4_0 8192 pp65536 7451.16 7515.91 1.01

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.

@anujj

anujj commented Oct 3, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for testing, I have added the spark check in the latest commit

@JohannesGaessler JohannesGaessler added the merge ready A maintainer can use this label to indicate that they consider the changes final and ready to merge. label Oct 4, 2026
@am17an
am17an merged commit d89651a into ggml-org:master Oct 5, 2026
2 checks passed
edwardyoon pushed a commit to edwardyoon/focus-llama that referenced this pull request Oct 8, 2026
edwardyoon added a commit to edwardyoon/focus-llama that referenced this pull request Oct 25, 2026
…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
)
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 merge ready A maintainer can use this label to indicate that they consider the changes final and ready to merge.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants