Skip to content

cuDNN SDPA backward: give grad_output the output's layout on torch 2.6 - 2.13 - #15445

Merged
danielhanchen merged 8 commits into
mainfrom
dh/s7-cudnn-sdpa-bwd-cache
Oct 27, 2026
Merged

danielhanchen merged 8 commits into
mainfrom
dh/s7-cudnn-sdpa-bwd-cache

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Problem

On torch 2.6 through 2.13, the cuDNN SDPA backward caches its execution plan under a key that leaves out the strides of grad_output. Suppose one process runs two same-shape cuDNN SDPA backwards, and the second grad_output has a different layout from the first. The second backward then reuses the first plan and returns wrong dQ / dK / dV. There is no error and there are no NaNs.

A common way to hit it is a HF style call, which reads the output through transpose(1, 2) and so hands back a (B, T, H, D) gradient, followed by a call that reads the output directly and hands back a contiguous (B, H, T, D) gradient. Errors against an fp32 math reference (bf16, B=1, H=8, T=374, D=64, B200):

Case torch 2.13.0 / cuDNN 9.20 torch 2.14.1 / cuDNN 9.24
second backward, block-causal mask 6.31 0.016
second backward, is_causal=True 6.31 0.016
second backward, no mask 0.68 0.002
second backward, B=4 H=16 T=1024 D=128 causal 10.69 0.031
same layout both times 0.016 0.016

This is a torch bug, not a cuDNN one:

  • torch 2.13.0 still fails with the cuDNN 9.24 library swapped in.
  • torch 2.10.0 / cuDNN 9.10 fails the same way.

aten/src/ATen/native/cudnn/MHA.cpp in 2.13 builds MHAParams from the q / k / v / bias dims and strides only. With cuDNN >= 9.5.1 it hands grad_output to cuDNN with its own strides; older cuDNN builds copied it to the output layout first. pytorch/pytorch#191576 (commit eaf9ee9780, first released in 2.14.0) adds the o, dO and softmax-stats dims and strides to the key. pytorch/pytorch#144913 and #202035 are related cuDNN SDPA backward layout reports, but neither is this bug.

On torch 2.13 with CUDA 13 wheels and cuDNN > 9.15, SDPA picks cuDNN first by default on SM90 and SM100. Unsloth's own training SDPA avoids cuDNN on SM100, but HF modeling code (attn_implementation="sdpa") and the H100 path still run the cuDNN backward. In this repo, test_block_varlen_runs_inside_the_graph_and_matches_dense_sdpa fails when it runs inside the full tests/test_hf_packed_attention.py file on torch 2.13 / B200. Its cuDNN dense reference reuses a plan that an earlier test left behind, and gets max abs error 3.3 to 4.9.

Fix

On torch 2.6 - 2.13 with CUDA and cuDNN >= 9.5.1 (not ROCm), fix_cudnn_sdpa_backward_grad_layout wraps torch.nn.functional.scaled_dot_product_attention. When the output requires grad, it passes through a small identity autograd.Function, and the backward of that function gives the incoming gradient the output's own strides. If the gradient already has them, nothing is copied.

The output layout follows the query layout, and the query layout is part of the key. With grad_output pinned to the output layout, the key fully describes the plan. This is the same condition torch 2.14 enforces. cuDNN attention stays enabled, so its speed is kept. Every other backend just sees a gradient in its own output's layout.

UNSLOTH_SKIP_CUDNN_SDPA_GRAD_LAYOUT_FIX=1 opts out. On torch >= 2.14 nothing is installed.

Alternatives considered:

  • Forcing grad_output.contiguous() is also correct, as long as every call goes through it. But it copies on every HF call, because HF gradients come in (B, T, H, D) layout.
  • Disabling cuDNN SDPA for training is correct but slow. Flash attention cannot take a mask, so masked training falls back to the efficient kernel (numbers below).

The block varlen test now takes a math-backend reference, as #15414's test does, so its result no longer depends on test order.

Before / after

Tests on B200 (base = main 8abe47a):

Test 2.13.0 base 2.13.0 head 2.14.1 base 2.14.1 head
test_cudnn_sdpa_backward_is_right_across_grad_layouts_after_import (eager mask / causal / no mask, both orders, compiled) FAIL (6.31) PASS skip skip
same test with the opt-out env (kill switch) n/a bug reproduces (> 0.5) n/a n/a
TestAffectedRange, TestGradInOutputLayout (CPU) FAIL (no symbol) PASS FAIL (no symbol) PASS
test_block_varlen_runs_inside_the_graph_and_matches_dense_sdpa[None, 4] in the full file FAIL PASS not run not run
test_cudnn_sdpa_d256_masked_backward.py PASS PASS PASS PASS

Speed: attention forward + backward, Qwen3-0.6B shape (B=4, 16 heads, head_dim 128, bf16, HF layout), torch 2.13.0, B200. Each value is the median ms over 3 repeats of 20 steps.

T, kind cuDNN cuDNN + this fix cuDNN + fix, contiguous grad (copy) flash efficient
1024 causal 0.178 0.208 0.227 0.363 0.675
2048 causal 0.420 0.406 0.407 1.101 2.130
4096 causal 0.988 1.100 1.187 3.383 7.467
1024 masked 0.355 0.303 0.495 no kernel 1.129
2048 masked 0.880 0.884 0.934 no kernel 3.866
4096 masked 3.146 3.144 3.236 no kernel 15.070

With HF layout gradients, a profiler run of the fix arm shows the same 7 CUDA kernels and the same device time as plain cuDNN (T=4096 causal). The remaining differences are eager host overhead from one extra autograd node, and they sit within the run-to-run spread seen on 2.14.1. A copy runs only when a caller hands a gradient in another layout, and it costs about 3% at T=4096. Turning cuDNN off instead would cost 2.6x to 3.4x on causal calls (flash) and 4.4x to 4.8x on masked calls (efficient).

Not covered

  • Code that calls torch.ops.aten._scaled_dot_product_cudnn_attention directly, or that bound scaled_dot_product_attention before Unsloth is imported, bypasses the wrapper.
  • torch 2.14.0 nightlies from before 2026-08-05 still carry the bug but report version 2.14.0, so they are left alone.
  • Only torch 2.10.0 and 2.13.0 were run on the affected side. 2.6 - 2.9, 2.11 and 2.12 are covered from the MHA.cpp source at each tag.
  • SM90 (H100) was not run: Colab had no H100 for this account. The fault is in the arch-neutral torch cache key, and SM90 is a default cuDNN arch on 2.13, so H100 is expected to be affected, but that has not been measured.

…6 - 2.13

torch 2.6 - 2.13 key the cuDNN SDPA backward plan cache without grad_output
strides, so two same-shape backwards whose grad_output layouts differ share a
plan and the second returns wrong dQ / dK / dV (pytorch/pytorch#191576 fixes it
in 2.14.0). Wrap SDPA on those versions so its backward always sees a gradient
laid out like the output; the output layout follows the query layout, which is
in the key. HF modeling code already hands that layout, so no copy runs there.

The block varlen test now uses a math-backend reference.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 26, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-27T10:45:27.113787Z 8e00174 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.

@danielhanchen

Copy link
Copy Markdown
Member Author

Follow-up: under torch context_parallel (and DTensor tensor parallel) the SDPA output is a DTensor, and the wrapper's backward copied the DTensor gradient into a plain empty_strided buffer, raising aten.copy_.default got mixed torch.Tensor and DTensor (6 of 12 layout cells on a 1-rank NCCL mesh). The wrapper now applies only when type(out) is torch.Tensor; DTensor outputs take the unwrapped path exactly as before this PR.

New GPU test tests/test_cudnn_sdpa_grad_layout_dtensor.py::test_context_parallel_sdpa_backward_with_the_grad_layout_wrapper fails on the previous head and passes here; together with tests/test_cudnn_sdpa_backward_grad_layout.py 17 of 17 pass on B200 (torch 2.13).

@codex review

@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: 5f0ebb49ee

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



@pytest.mark.gpu
@pytest.mark.skipif(not torch.cuda.is_available(), reason = "needs CUDA + NCCL")

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 Gate the DTensor regression test on CP and NCCL availability

On supported CUDA installations without context-parallel support (including torch 2.6), this test runs but its subprocess fails at the unconditional context_parallel import instead of testing the wrapper. Likewise, CUDA-enabled Windows installations without NCCL fail at init_process_group("nccl"). The CUDA-only skip condition does not cover either prerequisite. Check context-parallel availability and torch.distributed.is_nccl_available() before launching the probe, consistent with the capability gating in unsloth/context_parallel.py.

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.

Fixed: the test now also skips when torch.distributed.is_nccl_available() is false (CUDA on Windows) and when torch.distributed.tensor.experimental.context_parallel cannot be imported (older torch), before launching the probe. On B200 (torch 2.13) it still runs and passes (17 of 17 with the grad-layout tests); on the torch 2.6 venv it reports SKIPPED instead of failing in the subprocess.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep them coming!

Reviewed commit: 7fabfa956e

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

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep them coming!

Reviewed commit: 02f949bfa7

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

[skip ci]
Eager cuDNN outputs now get a tensor hook instead of a custom autograd.Function, so
the output stays a plain tensor: in-place ops on SDPA outputs and torch.func transforms
work as before, and flash / efficient / math outputs are returned untouched. Compiled
regions keep the Function (a hook on an intermediate graph-breaks), now new-style with
setup_context and generate_vmap_rule, and without grad.stride() in the traced backward
on torch 2.6, where Dynamo bans it. The flex gate test unwraps the whole SDPA wrapper
chain.

[skip ci]
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 8e0017470a

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

@danielhanchen danielhanchen self-assigned this Oct 27, 2026
@danielhanchen
danielhanchen merged commit 2df2860 into main Oct 27, 2026
@danielhanchen
danielhanchen deleted the dh/s7-cudnn-sdpa-bwd-cache branch October 27, 2026 13:54
danielhanchen added a commit that referenced this pull request Oct 27, 2026
`tests/python/test_accelerator_skip_guards.py::test_no_skip_guard_reads_a_spoofable_accelerator_probe`
fails on main again (`Repo tests (CPU, studio)`, e.g. job 122253474793
on #15556):

```
these skip guards read a probe tests/_zoo_aggressive_cuda_spoof.py patches to True process-wide ...
    test_cudnn_sdpa_grad_layout_dtensor.py:73: torch.cuda.is_available()
```

#15445 added
`test_context_parallel_sdpa_backward_with_the_grad_layout_wrapper` with
`@pytest.mark.skipif(not torch.cuda.is_available(), ...)`. That is the
probe the CUDA spoof patches to True, so on a CPU-only runner sharing a
session with `tests/version_compat` or `tests/vllm_compat` the test can
un-skip. The guard test is right; the new test's skip condition should
read `has_real_cuda()` like the rest of the suite (same fix as #15516).
The cuDNN change itself is unaffected.

Verification (local):
- `tests/python/test_accelerator_skip_guards.py`: main 1 failed, 23
passed; this branch 24 passed.
- `has_real_cuda()` is True on a real GPU host, so the test still runs
where it is meant to.
danielhanchen added a commit that referenced this pull request Oct 28, 2026
…in place (#15721)

## Problem

#15445 works around the torch 2.6 - 2.13 cuDNN SDPA backward plan cache.
Under `torch.compile`, its `scaled_dot_product_attention` wrapper passes
every qualifying SDPA output through `_GradInOutputLayout`, whose
forward returned `out.view_as(out)`. PyTorch forbids in-place ops on a
view returned by a custom autograd Function ("Output 0 of ... is a view
and is being modified inplace ... You can fix this by cloning the output
of the custom Function"). So compiled code that modifies an SDPA output
in place, for example `out = F.scaled_dot_product_attention(q, k, v);
out.mul_(2)`, now fails at trace time under `fullgraph=True` and
`False`, with the `aot_eager` and `inductor` backends alike. The same
code compiles and trains without the wrapper.

The eager path is not affected: it uses a gradient hook, not the
Function. On torch 2.14 and later nothing is installed.

## Fix

The Function's forward returns `out.clone()`. Only the compiled path
uses this Function, and Inductor's post-grad `remove_noop_ops` drops a
same-layout `aten.clone` (`true_noop`). The generated forward and
backward code is the same as before: 5 kernels and 29 buffer allocations
with and without the change (CPU Inductor, torch 2.13, counted with
`torch._inductor.utils.run_and_get_code`). The backward that gives the
gradient the output's layout is unchanged.

## Tests

`tests/test_cudnn_sdpa_backward_grad_layout.py`:

| test | main | this branch |
|---|---|---|
| `TestCompiledPathFunction::test_compiled_inplace_consumer[aot_eager]`
(fullgraph, in-place `mul_`, loss and grads vs no wrapper) | FAIL (view
modified inplace) | PASS |
| `TestCompiledPathFunction::test_compiled_inplace_consumer[inductor]` |
FAIL (same) | PASS |
| `TestGradInOutputLayout::test_forward_is_identity` (now also checks
the output is not a view and takes an in-place op) | FAIL | PASS |

The whole file passes on torch 2.6, 2.10, 2.13 and 2.14 on CPU (27
passed, 1 skipped GPU test).

## Not covered

- No GPU run. The cuDNN numerics test
(`test_cudnn_sdpa_backward_is_right_across_grad_layouts_after_import`)
needs CUDA with torch 2.13. The change does not touch the backward or
the eager hook path.
- No stock transformers or Unsloth model was found that modifies an SDPA
output in place, so this affects user code and custom modeling code
only.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant