pytorch - ✅(Solved) Fix SDPA returns 0 output and 0 gradient with corner case input since 2.12 [1 pull requests, 1 participants]

Official PRs (…)
ON THIS PAGE

Recommended Tools

×6

Utilities matched from this issue’s tags and category — try them while you read without losing context.

GitHub issue graph ai analysis

Paste a GitHub issue URL. We fetch that issue, discover linked issues from bodies/comments/timeline, collect linked pull requests, and produce a structured English report.

The report is written in English Markdown for sharing and archival.

Helpful · Quick feedback

Loading…
GitHub stats
pytorch/pytorch#184330Fetched 2026-05-20 03:39:14
View on GitHub
Comments
0
Participants
1
Timeline
8
Reactions
0
Participants
Timeline (top)
mentioned ×3subscribed ×3cross-referenced ×1labeled ×1

Fix Action

Fix / Workaround

CPU: Architecture: x86_64 CPU op-mode(s): 32-bit, 64-bit Address sizes: 46 bits physical, 57 bits virtual Byte Order: Little Endian CPU(s): 128 On-line CPU(s) list: 0-127 Vendor ID: GenuineIntel BIOS Vendor ID: Intel(R) Corporation Model name: Intel(R) Xeon(R) Platinum 8358 CPU @ 2.60GHz BIOS Model name: Intel(R) Xeon(R) Platinum 8358 CPU @ 2.60GHz CPU @ 2.6GHz BIOS CPU family: 179 CPU family: 6 Model: 106 Thread(s) per core: 2 Core(s) per socket: 32 Socket(s): 2 Stepping: 6 Frequency boost: enabled CPU(s) scaling MHz: 97% CPU max MHz: 3400.0000 CPU min MHz: 800.0000 BogoMIPS: 5200.00 Flags: fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc art arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc cpuid aperfmperf pni pclmulqdq dtes64 ds_cpl vmx smx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid dca sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault epb cat_l3 invpcid_single ssbd mba ibrs ibpb stibp ibrs_enhanced tpr_shadow vnmi flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid cqm rdt_a avx512f avx512dq rdseed adx smap avx512ifma clflushopt clwb intel_pt avx512cd sha_ni avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local wbnoinvd dtherm ida arat pln pts avx512vbmi umip pku ospke avx512_vbmi2 gfni vaes vpclmulqdq avx512_vnni avx512_bitalg tme avx512_vpopcntdq la57 rdpid md_clear pconfig flush_l1d arch_capabilities Virtualization: VT-x L1d cache: 3 MiB (64 instances) L1i cache: 2 MiB (64 instances) L2 cache: 80 MiB (64 instances) L3 cache: 96 MiB (2 instances) NUMA node(s): 2 NUMA node0 CPU(s): 0-31,64-95 NUMA node1 CPU(s): 32-63,96-127 Vulnerability Gather data sampling: Vulnerable: No microcode Vulnerability Itlb multihit: Not affected Vulnerability L1tf: Not affected Vulnerability Mds: Not affected Vulnerability Meltdown: Not affected Vulnerability Mmio stale data: Vulnerable: Clear CPU buffers attempted, no microcode; SMT vulnerable Vulnerability Retbleed: Not affected Vulnerability Spec store bypass: Mitigation; Speculative Store Bypass disabled via prctl and seccomp Vulnerability Spectre v1: Mitigation; usercopy/swapgs barriers and __user pointer sanitization Vulnerability Spectre v2: Mitigation; Enhanced / Automatic IBRS, IBPB conditional, RSB filling, PBRSB-eIBRS SW sequence Vulnerability Srbds: Not affected Vulnerability Tsx async abort: Not affected

PR fix notes

PR #5774: use eager attn for test_train_vlm_multi_image as a WA

Description (problem / solution / changelog)

We need to skip vision part of the model in multi-image test case, just like what we did in test_train_vlm, pls help review, @qgallouedec @kashif

<!-- CURSOR_SUMMARY -->

[!NOTE] Low Risk Low risk: this is a test-only workaround that changes attention backend selection for one test case, with no impact on library runtime behavior.

Overview Adjusts test_train_vlm_multi_image to initialize the model with attn_implementation="eager" via GRPOConfig.model_init_kwargs, working around a Torch SDPA bug (noted as affecting torch 2.12) that was causing the multi-image VLM training test to fail.

<sup>Reviewed by Cursor Bugbot for commit 8a5f28465aed0b30b9b09af8d1cdf4991b678b65. Bugbot is set up for automated code reviews on this repo. Configure here.</sup>

<!-- /CURSOR_SUMMARY -->

Changed files

  • tests/test_grpo_trainer.py (modified, +1/-0)

Code Example

import torch
import torch.nn.functional as F


def eager_attention(query, key, value, scale):
    scores = torch.matmul(query, key.transpose(-2, -1)) * scale
    probs = torch.softmax(scores, dim=-1, dtype=torch.float32).to(query.dtype)
    return torch.matmul(probs, value)


def run(use_sdpa, device):
    torch.manual_seed(0)
    query = torch.empty((1, 16, 16, 0), device=device, requires_grad=True)
    key = torch.empty((1, 16, 16, 0), device=device, requires_grad=True)
    value = torch.randn((1, 16, 16, 1), device=device, requires_grad=True)
    grad_output = torch.randn((1, 16, 16, 1), device=device)

    if use_sdpa:
        output = F.scaled_dot_product_attention(
            query,
            key,
            value,
            dropout_p=0.0,
            is_causal=False,
            scale=1.0,
        )
    else:
        output = eager_attention(query, key, value, scale=1.0)

    output.backward(grad_output)
    return output.detach().abs().sum().item(), value.grad.detach().abs().sum().item()


def compare(device):
    sdpa_output_sum, sdpa_value_grad_sum = run(use_sdpa=True, device=device)
    eager_output_sum, eager_value_grad_sum = run(use_sdpa=False, device=device)

    print(f"\n{device}")
    print(f"sdpa : output_abs_sum={sdpa_output_sum:.9e}, value_grad_abs_sum={sdpa_value_grad_sum:.9e}")
    print(f"eager: output_abs_sum={eager_output_sum:.9e}, value_grad_abs_sum={eager_value_grad_sum:.9e}")

    if sdpa_value_grad_sum == 0.0 and eager_value_grad_sum > 0.0:
        print("BUG: SDPA returns zero value gradient while eager attention returns a non-zero gradient.")


def main():
    print(f"torch: {torch.__version__}")
    compare("cuda")
    compare("cpu")


if __name__ == "__main__":
    main()

---

PyTorch version: 2.12.0+cu126
Is debug build: False
CUDA used to build PyTorch: 12.6
ROCM used to build PyTorch: N/A

OS: Ubuntu 24.04.1 LTS (x86_64)
GCC version: (Ubuntu 13.3.0-6ubuntu2~24.04.1) 13.3.0
Clang version: Could not collect
CMake version: version 3.28.3
Libc version: glibc-2.39

Python version: 3.12.3 (main, Mar  3 2026, 12:15:18) [GCC 13.3.0] (64-bit runtime)
Python platform: Linux-5.4.292-1.el8.elrepo.x86_64-x86_64-with-glibc2.39
Is CUDA available: True
CUDA runtime version: 12.8.93
CUDA_MODULE_LOADING set to:
GPU models and configuration:
GPU 0: NVIDIA A100 80GB PCIe
GPU 1: NVIDIA A100 80GB PCIe
GPU 2: NVIDIA A100 80GB PCIe
GPU 3: NVIDIA A100 80GB PCIe
GPU 4: NVIDIA A100 80GB PCIe
GPU 5: NVIDIA A100 80GB PCIe
GPU 6: NVIDIA A100 80GB PCIe

Nvidia driver version: 570.133.20
cuDNN version: Probably one of the following:
/usr/lib/x86_64-linux-gnu/libcudnn.so.9.20.0
/usr/lib/x86_64-linux-gnu/libcudnn_adv.so.9.20.0
/usr/lib/x86_64-linux-gnu/libcudnn_cnn.so.9.20.0
/usr/lib/x86_64-linux-gnu/libcudnn_engines_precompiled.so.9.20.0
/usr/lib/x86_64-linux-gnu/libcudnn_engines_runtime_compiled.so.9.20.0
/usr/lib/x86_64-linux-gnu/libcudnn_graph.so.9.20.0
/usr/lib/x86_64-linux-gnu/libcudnn_heuristic.so.9.20.0
/usr/lib/x86_64-linux-gnu/libcudnn_ops.so.9.20.0
Is XPU available: False
HIP runtime version: N/A
MIOpen runtime version: N/A
Is XNNPACK available: True
Caching allocator config: N/A

CPU:
Architecture:                       x86_64
CPU op-mode(s):                     32-bit, 64-bit
Address sizes:                      46 bits physical, 57 bits virtual
Byte Order:                         Little Endian
CPU(s):                             128
On-line CPU(s) list:                0-127
Vendor ID:                          GenuineIntel
BIOS Vendor ID:                     Intel(R) Corporation
Model name:                         Intel(R) Xeon(R) Platinum 8358 CPU @ 2.60GHz
BIOS Model name:                    Intel(R) Xeon(R) Platinum 8358 CPU @ 2.60GHz  CPU @ 2.6GHz
BIOS CPU family:                    179
CPU family:                         6
Model:                              106
Thread(s) per core:                 2
Core(s) per socket:                 32
Socket(s):                          2
Stepping:                           6
Frequency boost:                    enabled
CPU(s) scaling MHz:                 97%
CPU max MHz:                        3400.0000
CPU min MHz:                        800.0000
BogoMIPS:                           5200.00
Flags:                              fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc art arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc cpuid aperfmperf pni pclmulqdq dtes64 ds_cpl vmx smx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid dca sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault epb cat_l3 invpcid_single ssbd mba ibrs ibpb stibp ibrs_enhanced tpr_shadow vnmi flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid cqm rdt_a avx512f avx512dq rdseed adx smap avx512ifma clflushopt clwb intel_pt avx512cd sha_ni avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local wbnoinvd dtherm ida arat pln pts avx512vbmi umip pku ospke avx512_vbmi2 gfni vaes vpclmulqdq avx512_vnni avx512_bitalg tme avx512_vpopcntdq la57 rdpid md_clear pconfig flush_l1d arch_capabilities
Virtualization:                     VT-x
L1d cache:                          3 MiB (64 instances)
L1i cache:                          2 MiB (64 instances)
L2 cache:                           80 MiB (64 instances)
L3 cache:                           96 MiB (2 instances)
NUMA node(s):                       2
NUMA node0 CPU(s):                  0-31,64-95
NUMA node1 CPU(s):                  32-63,96-127
Vulnerability Gather data sampling: Vulnerable: No microcode
Vulnerability Itlb multihit:        Not affected
Vulnerability L1tf:                 Not affected
Vulnerability Mds:                  Not affected
Vulnerability Meltdown:             Not affected
Vulnerability Mmio stale data:      Vulnerable: Clear CPU buffers attempted, no microcode; SMT vulnerable
Vulnerability Retbleed:             Not affected
Vulnerability Spec store bypass:    Mitigation; Speculative Store Bypass disabled via prctl and seccomp
Vulnerability Spectre v1:           Mitigation; usercopy/swapgs barriers and __user pointer sanitization
Vulnerability Spectre v2:           Mitigation; Enhanced / Automatic IBRS, IBPB conditional, RSB filling, PBRSB-eIBRS SW sequence
Vulnerability Srbds:                Not affected
Vulnerability Tsx async abort:      Not affected

Versions of relevant libraries:
[pip3] apollo-torch==1.0.3
[pip3] galore-torch==1.0
[pip3] mypy_extensions==1.1.0
[pip3] numpy==2.2.6
[pip3] nvidia-cublas-cu12==12.6.4.1
[pip3] nvidia-cuda-cupti-cu12==12.6.80
[pip3] nvidia-cuda-nvrtc-cu12==12.6.85
[pip3] nvidia-cuda-runtime-cu12==12.6.77
[pip3] nvidia-cudnn-cu12==9.10.2.21
[pip3] nvidia-cufft-cu12==11.3.0.4
[pip3] nvidia-curand-cu12==10.3.7.77
[pip3] nvidia-cusolver-cu12==11.7.1.2
[pip3] nvidia-cusparse-cu12==12.5.4.2
[pip3] nvidia-cusparselt-cu12==0.7.1
[pip3] nvidia-nccl-cu12==2.29.3
[pip3] nvidia-nvjitlink-cu12==12.6.85
[pip3] nvidia-nvtx-cu12==12.6.77
[pip3] onnx==1.20.1
[pip3] onnx-ir==0.2.0
[pip3] onnxscript==0.6.2
[pip3] torch==2.12.0+cu126
[pip3] torchdata==0.11.0
[pip3] torchvision==0.27.0+cu126
[pip3] transformer_engine_torch==2.13.0
[pip3] triton==3.7.0
RAW_BUFFERClick to expand / collapse

🐛 Describe the bug

We meet a corner case bug for SDPA produced by the tiny Qwen2.5-VL vision model: In our config, attention after RoPE: hidden_size=16, num_heads=16 -> head_dim=1, while RoPE cos/sin have last dimension 0. As a result q/k become (..., 0), but v remains (..., 1). With this input SDPA will return 0 output and 0 gradient, while with eager mode it is OK. w/ PT 2.11, both sdpa and eager attn_implementation are OK. So is it a bug introduced by torch 2.12, or it is an expected behavior?

import torch
import torch.nn.functional as F


def eager_attention(query, key, value, scale):
    scores = torch.matmul(query, key.transpose(-2, -1)) * scale
    probs = torch.softmax(scores, dim=-1, dtype=torch.float32).to(query.dtype)
    return torch.matmul(probs, value)


def run(use_sdpa, device):
    torch.manual_seed(0)
    query = torch.empty((1, 16, 16, 0), device=device, requires_grad=True)
    key = torch.empty((1, 16, 16, 0), device=device, requires_grad=True)
    value = torch.randn((1, 16, 16, 1), device=device, requires_grad=True)
    grad_output = torch.randn((1, 16, 16, 1), device=device)

    if use_sdpa:
        output = F.scaled_dot_product_attention(
            query,
            key,
            value,
            dropout_p=0.0,
            is_causal=False,
            scale=1.0,
        )
    else:
        output = eager_attention(query, key, value, scale=1.0)

    output.backward(grad_output)
    return output.detach().abs().sum().item(), value.grad.detach().abs().sum().item()


def compare(device):
    sdpa_output_sum, sdpa_value_grad_sum = run(use_sdpa=True, device=device)
    eager_output_sum, eager_value_grad_sum = run(use_sdpa=False, device=device)

    print(f"\n{device}")
    print(f"sdpa : output_abs_sum={sdpa_output_sum:.9e}, value_grad_abs_sum={sdpa_value_grad_sum:.9e}")
    print(f"eager: output_abs_sum={eager_output_sum:.9e}, value_grad_abs_sum={eager_value_grad_sum:.9e}")

    if sdpa_value_grad_sum == 0.0 and eager_value_grad_sum > 0.0:
        print("BUG: SDPA returns zero value gradient while eager attention returns a non-zero gradient.")


def main():
    print(f"torch: {torch.__version__}")
    compare("cuda")
    compare("cpu")


if __name__ == "__main__":
    main()

Versions

PyTorch version: 2.12.0+cu126
Is debug build: False
CUDA used to build PyTorch: 12.6
ROCM used to build PyTorch: N/A

OS: Ubuntu 24.04.1 LTS (x86_64)
GCC version: (Ubuntu 13.3.0-6ubuntu2~24.04.1) 13.3.0
Clang version: Could not collect
CMake version: version 3.28.3
Libc version: glibc-2.39

Python version: 3.12.3 (main, Mar  3 2026, 12:15:18) [GCC 13.3.0] (64-bit runtime)
Python platform: Linux-5.4.292-1.el8.elrepo.x86_64-x86_64-with-glibc2.39
Is CUDA available: True
CUDA runtime version: 12.8.93
CUDA_MODULE_LOADING set to:
GPU models and configuration:
GPU 0: NVIDIA A100 80GB PCIe
GPU 1: NVIDIA A100 80GB PCIe
GPU 2: NVIDIA A100 80GB PCIe
GPU 3: NVIDIA A100 80GB PCIe
GPU 4: NVIDIA A100 80GB PCIe
GPU 5: NVIDIA A100 80GB PCIe
GPU 6: NVIDIA A100 80GB PCIe

Nvidia driver version: 570.133.20
cuDNN version: Probably one of the following:
/usr/lib/x86_64-linux-gnu/libcudnn.so.9.20.0
/usr/lib/x86_64-linux-gnu/libcudnn_adv.so.9.20.0
/usr/lib/x86_64-linux-gnu/libcudnn_cnn.so.9.20.0
/usr/lib/x86_64-linux-gnu/libcudnn_engines_precompiled.so.9.20.0
/usr/lib/x86_64-linux-gnu/libcudnn_engines_runtime_compiled.so.9.20.0
/usr/lib/x86_64-linux-gnu/libcudnn_graph.so.9.20.0
/usr/lib/x86_64-linux-gnu/libcudnn_heuristic.so.9.20.0
/usr/lib/x86_64-linux-gnu/libcudnn_ops.so.9.20.0
Is XPU available: False
HIP runtime version: N/A
MIOpen runtime version: N/A
Is XNNPACK available: True
Caching allocator config: N/A

CPU:
Architecture:                       x86_64
CPU op-mode(s):                     32-bit, 64-bit
Address sizes:                      46 bits physical, 57 bits virtual
Byte Order:                         Little Endian
CPU(s):                             128
On-line CPU(s) list:                0-127
Vendor ID:                          GenuineIntel
BIOS Vendor ID:                     Intel(R) Corporation
Model name:                         Intel(R) Xeon(R) Platinum 8358 CPU @ 2.60GHz
BIOS Model name:                    Intel(R) Xeon(R) Platinum 8358 CPU @ 2.60GHz  CPU @ 2.6GHz
BIOS CPU family:                    179
CPU family:                         6
Model:                              106
Thread(s) per core:                 2
Core(s) per socket:                 32
Socket(s):                          2
Stepping:                           6
Frequency boost:                    enabled
CPU(s) scaling MHz:                 97%
CPU max MHz:                        3400.0000
CPU min MHz:                        800.0000
BogoMIPS:                           5200.00
Flags:                              fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc art arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc cpuid aperfmperf pni pclmulqdq dtes64 ds_cpl vmx smx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid dca sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault epb cat_l3 invpcid_single ssbd mba ibrs ibpb stibp ibrs_enhanced tpr_shadow vnmi flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid cqm rdt_a avx512f avx512dq rdseed adx smap avx512ifma clflushopt clwb intel_pt avx512cd sha_ni avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local wbnoinvd dtherm ida arat pln pts avx512vbmi umip pku ospke avx512_vbmi2 gfni vaes vpclmulqdq avx512_vnni avx512_bitalg tme avx512_vpopcntdq la57 rdpid md_clear pconfig flush_l1d arch_capabilities
Virtualization:                     VT-x
L1d cache:                          3 MiB (64 instances)
L1i cache:                          2 MiB (64 instances)
L2 cache:                           80 MiB (64 instances)
L3 cache:                           96 MiB (2 instances)
NUMA node(s):                       2
NUMA node0 CPU(s):                  0-31,64-95
NUMA node1 CPU(s):                  32-63,96-127
Vulnerability Gather data sampling: Vulnerable: No microcode
Vulnerability Itlb multihit:        Not affected
Vulnerability L1tf:                 Not affected
Vulnerability Mds:                  Not affected
Vulnerability Meltdown:             Not affected
Vulnerability Mmio stale data:      Vulnerable: Clear CPU buffers attempted, no microcode; SMT vulnerable
Vulnerability Retbleed:             Not affected
Vulnerability Spec store bypass:    Mitigation; Speculative Store Bypass disabled via prctl and seccomp
Vulnerability Spectre v1:           Mitigation; usercopy/swapgs barriers and __user pointer sanitization
Vulnerability Spectre v2:           Mitigation; Enhanced / Automatic IBRS, IBPB conditional, RSB filling, PBRSB-eIBRS SW sequence
Vulnerability Srbds:                Not affected
Vulnerability Tsx async abort:      Not affected

Versions of relevant libraries:
[pip3] apollo-torch==1.0.3
[pip3] galore-torch==1.0
[pip3] mypy_extensions==1.1.0
[pip3] numpy==2.2.6
[pip3] nvidia-cublas-cu12==12.6.4.1
[pip3] nvidia-cuda-cupti-cu12==12.6.80
[pip3] nvidia-cuda-nvrtc-cu12==12.6.85
[pip3] nvidia-cuda-runtime-cu12==12.6.77
[pip3] nvidia-cudnn-cu12==9.10.2.21
[pip3] nvidia-cufft-cu12==11.3.0.4
[pip3] nvidia-curand-cu12==10.3.7.77
[pip3] nvidia-cusolver-cu12==11.7.1.2
[pip3] nvidia-cusparse-cu12==12.5.4.2
[pip3] nvidia-cusparselt-cu12==0.7.1
[pip3] nvidia-nccl-cu12==2.29.3
[pip3] nvidia-nvjitlink-cu12==12.6.85
[pip3] nvidia-nvtx-cu12==12.6.77
[pip3] onnx==1.20.1
[pip3] onnx-ir==0.2.0
[pip3] onnxscript==0.6.2
[pip3] torch==2.12.0+cu126
[pip3] torchdata==0.11.0
[pip3] torchvision==0.27.0+cu126
[pip3] transformer_engine_torch==2.13.0
[pip3] triton==3.7.0

cc @drisspg @liangel-02 @howardzhang-cv

Vote matrix · Quick signals

Works
Did the solution work? Tap to confirm.
Easy Fix
Was it a quick fix?
Time Saver
Did it save you time?
Blocking
Was it severely blocking?
Common Issue
Are others likely hitting this too?
Flaky / Intermittent
Is it intermittent?
Verified / Reproducible
Can you reproduce it reliably?
Loading…

Still need to ship something?

×6

Another batch ranked right after the header list — different links, same matching logic.

Back to top recommendations

TRENDING