Skip to content

cuDNN SDPA backward can return incorrect gradients for strided layouts #202035

Open

Description

@alexgarabt

🐛 Describe the bug

cuDNN SDPA backward can return incorrect gradients for strided layouts

We found an integer-width error in cuDNN's scaled dot-product attention backward path. In the analyzed SM90 kernel, an element offset is scaled to bytes with 32-bit arithmetic before it is combined with a 64-bit pointer. When the strided byte span crosses 4 GiB, high offset bits are lost. The kernel can then read the wrong values and return incorrect, finite gradients without a crash or NaN.

The instruction sequence

We captured the kernel launch arguments with CUPTI, extracted the cubin from the process, and inspected its SASS and Ghidra representation. The affected kernel is cudnn::fusion::compute_dot_do_o_specialized<true,128>, the prepass that computes the softmax correction D = sum(O ⊙ dO), in libcudnn_engines_runtime_compiled.so.9 for SM90.

The relevant instructions from cuobjdump show the byte scaling happening in a 32-bit register before the pointer addition:

0x0e80  IMAD.SHL.U32  R17, R12, 0x2, RZ      ; R17 = offset * 2 (32-bit)
0x0ee0  IADD3          R16, P1, R17, R8, RZ   ; add base low word
0x0ef0  IMAD.X         R17, RZ, RZ, R9, P1    ; add base high word + carry
0x0f10  LDG.E.128.CONSTANT R12, desc[UR8][R16.64] ; load using computed address

The later 64-bit pointer addition cannot restore high bits discarded by IMAD.SHL.U32. This is an address-calculation error, rather than ordinary BF16 rounding in the attention calculation. The SASS identifies the binary instructions; NVIDIA source lines for this proprietary kernel are not available to us.

Measured effect

On H200, a synthetic comparison against CPU FP64 measured relative-L2 errors of 0.1304754 for dQ and 0.1022068 for dK in the affected case. Equivalent compact-layout controls passed. Forward output and dV remained within the test tolerance.

In a fixed-input model diagnostic, without an optimizer step, the selected timestep-MLP weight-gradient norm was 88.17925 for the original batched cuDNN layout. It was 0.071049 for individual cuDNN examples, 0.070392 for batched FlashAttention, and 0.070973 for cuDNN with a packed upstream gradient. Packing the gradient left forward predictions bitwise unchanged and removed the measured amplification.

Controlled comparison of backward configurations

How we found it

The investigation began with severe quality degradation during a long training run. The job continued without crashing or producing NaNs, while gradient norms rose and loss remained elevated. Comparing fixed inputs and backward layouts isolated a layout-dependent gradient difference. We then captured the native launch with CUPTI, extracted the cubin, and traced the address calculation in SASS and Ghidra.

In an isolated research copy, changing the address calculation reduced the captured dot-product output's relative-L2 error from 0.5726383726 to 4.3537051104e-8, with bitwise agreement against the packed vendor control across 6,365,184 rows. This is agreement with that vendor control, not a claim of exact FP64 arithmetic: both vendor controls retained 15 failures under the original strict FP64 tolerance. The binary edit is causal evidence, not a shipping cuDNN fix.

The training comparison below shows the degraded branch and a separate rerun from checkpoint 1480. The rerun also restored the original batch layout and data sequence, so this comparison illustrates the incident and recovery; it does not isolate the kernel change by itself. Checkpoint 1775 is from the degraded branch. Checkpoint 1699 is from the separate rerun, not a later update of 1775.

With assistance from Astra-6, we traced the training regression to the backend behavior and developed the mitigation described below. This issue text was also prepared with AI assistance; the measurements and claims are based on our retained experimental records.

Training loss and gradient norm before degradation and after restarting with corrected backward handling

The image comparison uses the same prompt, seed, and inference settings. The left image is checkpoint 1480, before the affected continuation; the middle is checkpoint 1775; the right is checkpoint 1699 from the separate rerun.

Front view: same prompt and seed, before degradation, degraded checkpoint, and corrected rerun

Additional views of the same evaluation case:

Right view comparison

Back view comparison

Left view comparison

Upward view comparison

Downward view comparison

The following plots show global loss, loss for 2K targets, the gradient zoom around the onset, and the raw observations:

Global training loss

Training loss for 2K targets

Gradient norm around the onset

Raw loss and gradient observations around the onset

Why common checks can miss it

The trigger depends on physical layout, not only logical tensor size. A strided view can span more memory than a packed tensor holding the same values, while small or packed controls never cross the same address boundary. Backend selection matters too: a passing FlashAttention run does not exercise cuDNN.

The incorrect reads can stay within the tensor allocation and return finite values. In the retained affected run, Compute Sanitizer memcheck reported zero errors for this case. That result does not establish numerical correctness; the wrong values were read from addresses that remained inside the allocation. Forward parity, NaN checks, and crash-only monitoring therefore did not expose this backward error.

Proposed PyTorch mitigation

The candidate mitigation is in aten/src/ATen/native/cudnn/MHA.cpp, in the cuDNN SDPA backward path before descriptor and execution-plan cache-key construction. It checks the reachable byte spans of saved output O and incoming gradient dO, packs an oversized operand when its compact representation fits, and rejects the input explicitly if it still exceeds the supported range. Descriptors, cache keys, and pointers must all use the resulting layouts.

In simplified form, the proposed behavior is:

// Before building descriptors or the execution-plan cache key:
auto output_for_cudnn = pack_if_address_span_exceeds_limit(output);
auto grad_output_for_cudnn = pack_if_address_span_exceeds_limit(grad_output);

// Build descriptors, cache keys, and cuDNN arguments from these same tensors.

pack_if_address_span_exceeds_limit is explanatory pseudocode, not an existing PyTorch API. The actual change must compute the reachable span from the tensor's sizes and strides. Packing preserves logical values but costs memory and bandwidth; explicit rejection changes behavior for some inputs. Packing only the forward output is insufficient because the backward gradient can have its own strided layout.

This is a temporary PyTorch-side mitigation. We reported the underlying cuDNN defect to NVIDIA on October 25, 2026, and requested a vendor correction and confirmation of affected and fixed releases. We do not yet have confirmation of a fixed cuDNN release.

Versions and architecture scope

The CUDA-12 sweep used H200, PyTorch 2.14.1+cu126, Python 3.12.12, and Linux driver 595.91.07. Each listed cuDNN package has a retained result and loaded-runtime identity:

cuDNN package Loaded runtime identifier Explicit cuDNN backward result
9.10.2 91002 Incorrect dQ/dK
9.19.0.56 91900 Incorrect dQ/dK
9.20.0.48 92000 Incorrect dQ/dK
9.24.0.43 92400 Incorrect dQ/dK
9.26.1.1 92601 Incorrect dQ/dK
9.27.0.42 92700 Incorrect dQ/dK

Earlier H200 measurements also reproduced the issue with PyTorch 2.11.0+cu130 / cuDNN 9.19.0.56, 2.13.0+cu130 / 9.20.0.48, and 2.14.1+cu130 / 9.24.0.43.

The measured cuDNN releases span 9.10.2 through 9.27.0.42; we did not test every release in that interval or identify the first affected release. Default dispatch is build-dependent: the recorded 2.14.1+cu130 case selected cuDNN and failed, while 2.14.1+cu126 selected Flash for that geometry and passed; explicitly selecting cuDNN on the latter build failed. These results do not mean every workload using those versions is affected. Other PyTorch releases may be exposed when they dispatch to the same defective cuDNN path, but they have not all been tested.

Dynamic reproduction was performed on H200 only. Static inspection of cuDNN 9.20 found the same truncating instruction form in the corresponding SM80, SM86, SM90a, SM120, and SM121 cubins. This is static evidence, not dynamic validation on those architectures. SM100 uses a different scaling sequence in this path and is not included in the confirmed dynamic scope.

The compiled candidate patch was validated on PyTorch commit 23520dd5b595b832ace93bc5516a5c62488c6542: seven cases passed, along with a focused suite of 32 tests and 12 subtests. This is validation of that pinned build, not current PyTorch main or the full test suite.

Would the SDPA/cuDNN maintainers support this mitigation approach and advise on the affected version range and integration policy? We can update the patch to the agreed target and submit a focused PR.

Versions

Versions and architecture scope

The CUDA-12 sweep used H200, PyTorch 2.14.1+cu126, Python 3.12.12, and Linux driver 595.91.07. Each listed cuDNN package has a retained result and loaded-runtime identity:

cuDNN package Loaded runtime identifier Explicit cuDNN backward result
9.10.2 91002 Incorrect dQ/dK
9.19.0.56 91900 Incorrect dQ/dK
9.20.0.48 92000 Incorrect dQ/dK
9.24.0.43 92400 Incorrect dQ/dK
9.26.1.1 92601 Incorrect dQ/dK
9.27.0.42 92700 Incorrect dQ/dK

Earlier H200 measurements also reproduced the issue with PyTorch 2.11.0+cu130 / cuDNN 9.19.0.56, 2.13.0+cu130 / 9.20.0.48, and 2.14.1+cu130 / 9.24.0.43.

The measured cuDNN releases span 9.10.2 through 9.27.0.42; we did not test every release in that interval or identify the first affected release. Default dispatch is build-dependent: the recorded 2.14.1+cu130 case selected cuDNN and failed, while 2.14.1+cu126 selected Flash for that geometry and passed; explicitly selecting cuDNN on the latter build failed. These results do not mean every workload using those versions is affected. Other PyTorch releases may be exposed when they dispatch to the same defective cuDNN path, but they have not all been tested.

Dynamic reproduction was performed on H200 only. Static inspection of cuDNN 9.20 found the same truncating instruction form in the corresponding SM80, SM86, SM90a, SM120, and SM121 cubins. This is static evidence, not dynamic validation on those architectures. SM100 uses a different scaling sequence in this path and is not included in the confirmed dynamic scope.

cc @ezyang @gchanan @kadeng @msaroufim @csarofeen @ptrblck @eqy @nWEIdia

Activity

  1. github-actions commented on Oct 26, 2026

    @github-actions
    Contributor

    Thanks for the detailed report! This is a hardware-specific claim (H200, specific cuDNN builds) with extensive narrative and measurements, but no minimal, self-contained script that reproduces the incorrect dQ/dK on a strided SDPA backward call.

    To help us investigate and verify the address-truncation claim:

    • Could you share a minimal, runnable PyTorch script (random/synthetic tensors are fine, no checkpoints or training data needed) that constructs a strided O/dO pair spanning >4 GiB and calls torch.nn.functional.scaled_dot_product_attention with the cuDNN backend explicitly selected (torch.backends.cuda.sdp_kernel/sdpa_kernel context), showing the incorrect gradient compared to a reference (e.g. math/FlashAttention backend or CPU fp64)?
    • Output of python -m torch.utils.collect_env

    A self-contained reproducer lets maintainers independently confirm the issue and evaluate the proposed mitigation in aten/src/ATen/native/cudnn/MHA.cpp.

  2. added
    bot-triaged
    on Oct 26, 2026
  3. alexgarabt commented on Oct 26, 2026

    @alexgarabt
    Author

    Astra prepared the attached scripts and reran them on a fresh NVIDIA H200 instance. The runnable files are run_reproducer.py, b2_fixed.py, and synthetic_boundary.py. the README provides the execution instructions.

    The scripts force the cuDNN SDPA backend and compare packed and gapped upstream dO layouts with identical deterministic BF16 inputs. O is produced by the SDPA call; only the layout of dO changes. The gapped layout spans just over 4 GiB. The packed control is also checked against an independent CPU FP64 reference. No model weights or training data are required.

    The new run used PyTorch 2.14.1+cu126, CUDA build 12.6, and cuDNN runtime 9.10.2 from the nvidia-cudnn-cu12==9.10.2.21 wheel. The attached result.json records:

    • Batch 1: relative-L2 differences of 0.1284823 for dQ and 0.1011135 for dK.
    • Batch 0 and dV: packed and gapped results matched exactly.
    • Packed control: all gradient errors against the CPU FP64 reference were below 0.0025 relative-L2.

    The full environment report is attached as collect_env.txt. It lists system cuDNN 9.8 libraries from the container image and reports “Could not collect” for the CUDA runtime version. The reproducer itself reports cuDNN runtime 91002. The supplementary runtime-identity.txt confirms the 9.10.2.21 wheel and its loaded library paths in a separate Python process using the same isolated environment.

  4. alexgarabt commented on Oct 26, 2026

    @alexgarabt
    Author

    We also have a focused PyTorch-side mitigation prepared. Would a maintainer be willing to review the approach and mark this issue actionable, or support a PR for it?

  5. ptrblck commented on Oct 28, 2026

    @ptrblck
    Collaborator

    CC @eqy

  6. added
    module: cudnn
    module: correctness (silent)
    on Oct 28, 2026
  7. eqy commented on Oct 28, 2026

    @eqy
    Collaborator

    CC @drisspg curious how did this one slip through the triage review process?

  8. added
    module: 64-bit
    on Oct 28, 2026
  9. 1 remaining item

  10. alexgarabt commented on Oct 29, 2026

    @alexgarabt
    Author

    @gderossi @eqy , NVIDIA PSIRT has acknowledged the report and opened a case. I’ll keep you updated as I hear back.

    I also saw the comments on #202461 thanks for following up on this.

    We’ve published the investigation, reproduction scripts, results, and candidate PyTorch mitigation here.
    https://github.com/speridlabs/cudnn-sdpa-research

    The runnable scripts and fresh H200 results are already attached in my earlier comment. If attachments are inconvenient, I can put the relevant code inline.

    We’d be happy to contribute to the PyTorch to your preferred approach, or help with testing. Let us know what would be most useful.

  11. gderossi commented on Oct 29, 2026

    @gderossi
    Collaborator

    @alexgarabt thank you for that. I've reproduced the issue on H100 and forwarded info to the cuDNN team, I'm waiting to hear back from them to determine the best approach for a fix on the PyTorch side.

  12. alexgarabt commented on Oct 30, 2026

    @alexgarabt
    Author

    Thanks @gderossi.

    We also saw NVIDIA/cudnn-frontend#2060, which addresses related offset issues and mentions a separate fix in the cuDNN backend.

    Happy to help any way we can!

  13. added
    triaged
    and removed on Nov 2, 2026
  14. vedaanta commented on Nov 2, 2026

    @vedaanta
    Contributor

    Thanks @alexgarabt for reporting this.
    I added some fixes in cuDNN 9.28.1. Its available as a preview build here: pypi link

    Can you please help check this new build fixes the incorrect dQK?

  15. alexgarabt commented on Nov 3, 2026

    @alexgarabt
    Author

    @vedaanta thanks for the fix! I tested cuDNN 9.28.1.1.dev77966261 on an H200 with PyTorch 2.14.1+cu130, using cuDNN 9.24.0.43 as the affected control.

    With identical inputs, comparing packed versus strided dO across the 4 GiB boundary:

    • dQ relative-L2 difference: 0.12848 → 0
    • dK relative-L2 difference: 0.10111 → 0

    In our 80-step synthetic training test with the preview, the measured final parameter differences between the packed and strided runs were zero, and their final losses matched.

    This confirms the fix for our tested H200 cases.

    Thanks again for looking into it!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

bot-triagedhigh prioritymodule: 64-bitmodule: correctness (silent)module: cudnntriaged

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions