Repository navigation
cuDNN SDPA backward: give grad_output the output's layout on torch 2.6 - 2.13 - #15445
Conversation
…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.
|
@codex review |
Codex Review SummaryThis 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. |
…(context_parallel) [skip ci]
|
Follow-up: under torch New GPU test @codex review |
There was a problem hiding this comment.
💡 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") |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
|
@codex review |
|
Codex Review: Didn't find any major issues. Keep them coming! 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". |
|
@codex review |
|
Codex Review: Didn't find any major issues. Keep them coming! 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". |
[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]
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. Delightful! 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". |
`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.
…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.
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 secondgrad_outputhas 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):is_causal=TrueThis is a torch bug, not a cuDNN one:
aten/src/ATen/native/cudnn/MHA.cppin 2.13 buildsMHAParamsfrom the q / k / v / bias dims and strides only. With cuDNN >= 9.5.1 it handsgrad_outputto 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 theo,dOand 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_sdpafails when it runs inside the fulltests/test_hf_packed_attention.pyfile 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_layoutwrapstorch.nn.functional.scaled_dot_product_attention. When the output requires grad, it passes through a small identityautograd.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_outputpinned 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=1opts out. On torch >= 2.14 nothing is installed.Alternatives considered:
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.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_cudnn_sdpa_backward_is_right_across_grad_layouts_after_import(eager mask / causal / no mask, both orders, compiled)TestAffectedRange,TestGradInOutputLayout(CPU)test_block_varlen_runs_inside_the_graph_and_matches_dense_sdpa[None, 4]in the full filetest_cudnn_sdpa_d256_masked_backward.pySpeed: 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.
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
torch.ops.aten._scaled_dot_product_cudnn_attentiondirectly, or that boundscaled_dot_product_attentionbefore Unsloth is imported, bypasses the wrapper.MHA.cppsource at each tag.