Skip to content

Prefer the cuDNN SDPA backend on Hopper - #48163

Closed
qgallouedec wants to merge 7 commits into
mainfrom
prefer-cudnn-sdpa
Closed

qgallouedec wants to merge 7 commits into
mainfrom
prefer-cudnn-sdpa

Conversation

@qgallouedec

@qgallouedec qgallouedec commented Aug 20, 2026 •

Copy link
Copy Markdown
Member

CPU CI GPU run-slow

Edit: originally gated to capability >= 9 ("Hopper and newer") based on H100 numbers alone.
After benchmarking six GPUs across five architectures, cuDNN turns out to win on Hopper and nowhere
else: it is slower on Ampere (0.82x on A100, 0.93x on A10G) and on Blackwell (0.88x on RTX PRO 6000),
and a wash on Ada (1.00x on L40S). The gate is now == 9, Hopper only. Full table in
this comment;
the text below has been updated to match.

torch.nn.functional.scaled_dot_product_attention picks its backend by a fixed priority that puts FlashAttention first. On Hopper the cuDNN attention kernels are consistently 1.7–2.3× faster for training shapes, at the same numerical accuracy. This adds a backend preference (not a restriction) on Hopper, so shapes cuDNN cannot serve fall back exactly as before.

Confirmed that the default really is FlashAttention — profiling Qwen3-0.6B at 16K on main shows
pytorch_flash::flash_bwd_... / flash_fwd_kernel taking 335 ms of a 677 ms step.

Measured

One GPU, pure torch, no transformers involved: forward+backward through
scaled_dot_product_attention once per backend (script at the end of this section).

NVIDIA H100 80GB HBM3, torch 2.13.0+cu130

speed, bf16 causal forward+backward, 32 heads x 128
     seq               flash               cudnn  speedup
    8192       8.6 ms   192 TF/s       3.8 ms   438 TF/s  2.29x
   32768      93.6 ms   282 TF/s      51.8 ms   509 TF/s  1.81x
   65536     373.3 ms   283 TF/s     203.2 ms   519 TF/s  1.84x
  131072    1504.2 ms   281 TF/s     874.3 ms   483 TF/s  1.72x

speed, same thing at the head configurations of current models, seq 32768
             model       shape         flash         cudnn  speedup
       gpt-oss-20b   64x64         249 TF/s     408 TF/s  1.64x
       Gemma 4 31B   32x256        232 TF/s     396 TF/s  1.71x
        Qwen3.5-9B   16x256        223 TF/s     395 TF/s  1.77x
  Muse-Glimmer-30B   32x128        281 TF/s     498 TF/s  1.77x
           GLM-5.2   64x192        247 TF/s     331 TF/s  1.34x

accuracy, gradient relative L2 against an fp64 reference (seq 4096, causal)
                  dq          dk          dv
   flash    4.18e-03    3.09e-03    1.70e-03
   cudnn    4.19e-03    3.09e-03    1.70e-03

cuDNN is ahead at every sequence length and at every head shape shipped by the models people are training
today, from 1.34x (GLM-5.2, 64 heads x 192) to 1.83x. The gradients land at the same distance from an fp64
reference, so this is a free change numerically.

cudnn-speedup

Confirmed that the default really is FlashAttention: profiling Qwen3-0.6B at 16K on main shows pytorch_flash::flash_bwd_... / flash_fwd_kernel taking 335 ms of a 677 ms step.

repro_cudnn_sdpa.py
import time

import torch
import torch.nn.functional as F
from torch.nn.attention import SDPBackend, sdpa_kernel

BACKENDS = {"flash": SDPBackend.FLASH_ATTENTION, "cudnn": SDPBackend.CUDNN_ATTENTION}


# (heads, head_dim) as shipped, from each model's config.json
MODELS = {
    "gpt-oss-20b": (64, 64),
    "Gemma 4 31B": (32, 256),
    "Qwen3.5-9B": (16, 256),
    "Muse-Glimmer-30B": (32, 128),
    "GLM-5.2": (64, 192),
}


def timed(backend, seq, heads, dim, iters=3):
    q, k, v = (torch.randn(1, heads, seq, dim, device="cuda", dtype=torch.bfloat16, requires_grad=True)
               for _ in range(3))

    def run():
        with sdpa_kernel([BACKENDS[backend]]):
            out = F.scaled_dot_product_attention(q, k, v, is_causal=True)
        out.sum().backward()

    run()
    torch.cuda.synchronize()
    start = time.perf_counter()
    for _ in range(iters):
        run()
    torch.cuda.synchronize()
    seconds = (time.perf_counter() - start) / iters
    # causal attention: 4 matmul FLOPs per (query, key) pair, half the pairs, ~3x for fwd+bwd
    flops = 4 * seq * seq * heads * dim * 0.5 * 3
    return seconds * 1e3, flops / seconds / 1e12

def accuracy(backend, seq=4096, heads=8, dim=64):
    torch.manual_seed(0)
    ref_inputs = [torch.randn(1, heads, seq, dim, device="cuda", dtype=torch.float64, requires_grad=True)
                  for _ in range(3)]
    F.scaled_dot_product_attention(*ref_inputs, is_causal=True).sum().backward()

    inputs = [t.detach().bfloat16().requires_grad_(True) for t in ref_inputs]
    with sdpa_kernel([BACKENDS[backend]]):
        F.scaled_dot_product_attention(*inputs, is_causal=True).sum().backward()
    return [((got.grad.double() - want.grad).norm() / want.grad.norm()).item()
            for got, want in zip(inputs, ref_inputs)]


def main():
    print(f"{torch.cuda.get_device_name()}, torch {torch.__version__}\n")

    print("speed, bf16 causal forward+backward, 32 heads x 128")
    print(f"{'seq':>8}  {'flash':>18}  {'cudnn':>18}  speedup")
    for seq in (8192, 32768, 65536, 131072):
        (fms, ftf), (cms, ctf) = (timed(b, seq, 32, 128) for b in ("flash", "cudnn"))
        print(f"{seq:>8}  {fms:8.1f} ms {ftf:5.0f} TF/s  {cms:8.1f} ms {ctf:5.0f} TF/s  {ctf / ftf:.2f}x")

    print("\nspeed, same thing at the head configurations of current models, seq 32768")
    print(f"{'model':>18}  {'shape':>10}  {'flash':>12}  {'cudnn':>12}  speedup")
    for name, (heads, dim) in MODELS.items():
        try:
            (_, ftf), (_, ctf) = (timed(b, 32768, heads, dim) for b in ("flash", "cudnn"))
        except RuntimeError as exc:  # a backend can refuse a shape; that is the point of a preference
            print(f"{name:>18}  {heads}x{dim:<7}  {type(exc).__name__}: {str(exc)[:40]}")
            continue
        print(f"{name:>18}  {heads:>3}x{dim:<6}  {ftf:6.0f} TF/s  {ctf:6.0f} TF/s  {ctf / ftf:.2f}x")

    print("\naccuracy, gradient relative L2 against an fp64 reference (seq 4096, causal)")
    print(f"{'':>8}  {'dq':>10}  {'dk':>10}  {'dv':>10}")
    for backend in BACKENDS:
        dq, dk, dv = accuracy(backend)
        print(f"{backend:>8}  {dq:10.2e}  {dk:10.2e}  {dv:10.2e}")


if __name__ == "__main__":
    main()

Implementation

wrapping the single scaled_dot_product_attention call in sdpa_attention_forward.

Design notes, each of which I measured the hard way:

  • The q_length == 1 gate is load-bearing. Expressing a preference costs ~18 us because it saves and restores global backend flags. That is nothing next to a training attention call, but a decode-shaped call is only ~32 us, so wrapping it ungated made 64-token generation 13% slower (2872 ms vs 2542 ms). With the gate, generation is back to baseline.
  • Wrapping the SDPA call itself, rather than the training step, is what makes activation checkpointing work. Recompute re-enters sdpa_attention_forward and therefore re-selects the same backend. Wrapping at a coarser granularity that does not cover the backward gives CheckpointError: Recomputed values ... have different metadata.
  • set_priority=True expresses an order, so shapes cuDNN cannot serve fall through to flash/efficient/math (verified with head_dim=72, which cuDNN refuses).
  • Gated to CUDA SM90+, because that is where I have measurements.

End-to-end effect (steady-state median step time, gradient checkpointing, Qwen3-0.6B unless noted)

cudnn-end-to-end
config main this PR
generation, 64 tokens 2542 ms 2511 ms unchanged (gated out)
training, seq 512 x batch 16 377 ms 375 ms no change — attention is a small share of the step
training, seq 16384 x batch 1 1129 ms 924 ms 1.22x
training, Qwen3-8B, seq 1,048,576, 8xH100 + context parallelism 612 s 364 s 1.68x

Losses match to 5 decimal places in every case (e.g. 11.42171 vs 11.42174). The gain grows with how much of the step is attention, and there is no configuration in which this is slower.

Caveats / questions for maintainers

  • Benchmarks are H100 only. If you want this on Ampere or Blackwell, that needs numbers I do not have; the gate is one line to widen.
  • There is an open torch issue about cuDNN SDPA + context parallelism strides [distributed] CUDNN SDPA backend + CP stride failure pytorch/pytorch#176915; I did not hit it in extensive CP runs (Qwen3-8B / 30B-A3B at 1M–4M tokens, torch 2.13), but it is worth knowing about.
  • If a global preference feels too broad, the same change scoped to is_causal and attention_mask is None would still capture nearly all of the training win.

If you would rather not take this

I'd understand if you decide not to move forward: it changes a default for everyone

Nothing is blocked either way, users can select the backend themselves, but it's not super clean:

class FastSFTTrainer(SFTTrainer):
    def training_step(self, *args, **kwargs):
        with sdpa_kernel([SDPBackend.CUDNN_ATTENTION], set_priority=True):
            return super().training_step(*args, **kwargs)

It has to wrap forward and backward, since checkpoint recompute must pick the same backend. This is what I
used for every long-context run here.

So the question is really whether the default should do this for people who will never read a benchmark. I
think yes, but happy to close it and document the workaround instead.

@HuggingFaceDocBuilderDev

Copy link
Copy Markdown

The docs for this PR live here. All of your documentation changes will be reflected on that endpoint. The docs are available until 30 days after the last update.

@qgallouedec

qgallouedec commented Aug 20, 2026 •

Copy link
Copy Markdown
Member Author

Update: I ran the same benchmark on other GPUs, and it changed the gate.

cuDNN wins on Hopper (H100 and H200 alike). It is slower on Ampere and on Blackwell, and a wash on Ada. My original gate was capability[0] >= 9, which includes Blackwell, so as written this PR would have made Blackwell about 12% slower. Now gated to Hopper only (== 9), with the measurements in the docstring.

GPU arch 8K 32K 64K 128K
A100 Ampere, sm80 0.85x 0.83x 0.82x 0.82x
A10G Ampere, sm86 0.91x 0.93x 0.93x 0.93x
L40S Ada, sm89 0.96x 1.00x 1.00x 1.00x
H100 Hopper, sm90 2.29x 1.81x 1.84x 1.72x
H200 Hopper, sm90 2.13x 1.78x 1.79x 1.73x
RTX PRO 6000 Blackwell, sm120 1.10x 0.87x 0.88x 0.88x

Same torch build (2.13.0+cu130) and the gradients match an fp64 reference to the same relative error everywhere.

H100 ran on our cluster and the rest on HF Jobs, so the two Hopper points are not infrastructure matched, but they agree within 7%.

sm100 (B200) I had no access to, so it is excluded.

The benchmark script lives in this PR under Measured: pure torch, one GPU, no transformers needed, so any card I did not cover is a couple of minutes to check.

image

@qgallouedec qgallouedec changed the title Prefer the cuDNN SDPA backend on Hopper and newer Prefer the cuDNN SDPA backend on Hopper Aug 20, 2026

@vasqu vasqu left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

I'm not too opposed to this because in a sense it's a free perf gain. I have some initial questions first tho

Still a bit surprised about the blackwell results ngl but hopper shouldnt be changing anymore so these should be consistent improvements

Comment on lines +29 to +32
Hopper only, because that is where cuDNN wins: measured forward+backward at 8K-128K sequence
lengths, cuDNN is 1.7-2.3x faster on H100 and H200, but 0.82x on A100 and 0.88x on Blackwell
(RTX PRO 6000, sm120). sm100 was not measured. Benchmark and numbers:
https://github.com/huggingface/transformers/pull/48163

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

I'm a bit surprised that blackwell is losing quite a bit as well, potentially a big reason why this is still seen as quite experimental.

Another thing I'm concerned about is the shipped cuda version you tested these on: Cudnn implementations may vary would be my initial intuition

# Expressing a preference costs ~18us per call (it saves and restores global backend flags), so it is
# only worth it when the attention call itself is substantial. During decoding `q_length == 1` and that
# overhead would dominate, so keep the default backend there.
if q_length == 1 or not torch.cuda.is_available() or not _prefer_cudnn_sdpa(torch.cuda.current_device()):

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Could we not cache the cuda availability (torch.cuda.is_available()) into _prefer_cudnn_sdpa?



@lru_cache
def _prefer_cudnn_sdpa(device: int) -> bool:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Honestly we could keep them public as well

@github-actions

Copy link
Copy Markdown
Contributor

CI recap

Dashboard: View test results in Grafana
Latest run: 33435974920:1
Result: success | Jobs: 16 | Tests: 145,326 | Failures: 0 | Duration: 14h 39m

@qgallouedec

Copy link
Copy Markdown
Member Author

Thanks for the review. Answering the CUDA version question turned up something that says this PR should not land 🫠

image PyTorch already does exactly this.

check_prefer_cudnn_attention() in sdp_utils.cpp sets the same backend order this PR sets, gated on cudnn_version > 91500 and sm90/sm100, and that code is already in 2.10. What changes at 2.11 is the bundled cuDNN crossing the threshold. So on recent torch the default is already cuDNN, and asking again only adds the context manager's overhead.

The builds where this PR does change something are the ones PyTorch excludes on purpose. That threshold comes from pytorch/pytorch#138522 making cuDNN opt-in after the 2.5 bugs (pytorch/pytorch#139298 among them), and the comment above it points at pytorch/pytorch#169849, a seq_len not divisible by 128 fix that only landed in cuDNN 9.15.1. Forcing it there overrides a deliberate guard rather than winning anything. Closing.

For context: I only saw a win because our cluster puts the system CUDA on LD_LIBRARY_PATH, which shadows the cuDNN inside the torch wheel. Torch falls back to flash, so on my machine the default really was flash and forcing cuDNN really was 1.8x. Same node with unset LD_LIBRARY_PATH and the default is already cuDNN. The benchmark was right, the conclusion was not: it compared two forced backends and never the default. see https://huggingface.slack.com/archives/C0BF837HWLX/p1788212991953029

@vasqu

vasqu commented Aug 31, 2026

Copy link
Copy Markdown
Collaborator

Woah I did expect something re cuda but that's super interesting and TIL as well.

A bit sad but it's something very good having it documented somewhere and on how to setup on our clusters, appreciate it.

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.

3 participants