Repository: pytorch
Issue: `scaled_dot_product_attention` produces NaNs for math backend, but not memory efficient backend when used in mixed precision.
Labels: module: numerical-stability,module: cuda,triaged,module: sdpa

### 🐛 Describe the bug

I have found the problem with dot attention when using mixed precision, in my project i had disabled memory efficient cross attention and sometimes math backend behave incorrectly and produces NaNs. This is a reproduction. 

NOTE: Flash Attention 2 is disabled automatically due usage of a custom mask.

```python
import torch
device = "cuda"

# Load checkpoint
data = torch.load("debug_attention.pt", map_location=device)
q = data['q']
k = data['k']
v = data['v']
mask = data['mask']

with torch.autocast(device_type="cuda", dtype=torch.float16):
    with torch.backends.cuda.sdp_kernel(enable_mem_efficient=True):
        y = torch.nn.functional.scaled_dot_product_attention(q, k, v, attn_mask = mask.to(device))
        if torch.isnan(y).any() or torch.isinf(y).any():
            print("Invalid tensor for memory efficient!")
        else:
            print("Valid tensor for memory efficient!")

with torch.autocast(device_type="cuda", dtype=torch.float16):
    with torch.backends.cuda.sdp_kernel(enable_mem_efficient=False):
        y = torch.nn.functional.scaled_dot_product_attention(q, k, v, attn_mask = mask.to(device))
        if torch.isnan(y).any() or torch.isinf(y).any():
            print("Invalid tensor for math!")
        else:
            print("Valid tensor for math!")
```

[debug_attention.pt.zip](https://github.com/pytorch/pytorch/files/14154262/debug_attention.pt.zip)


### Versions

```
PyTorch version: 2.1.2+cu121
Is debug build: False
CUDA used to build PyTorch: 12.1
ROCM used to build PyTorch: N/A

OS: Ubuntu 20.04.6 LTS (x86_64)
GCC version: (Ubuntu 9.4.0-1ubuntu1~20.04.2) 9.4.0
Clang version: Could not collect
CMake version: version 3.28.1
Libc version: glibc-2.31

Python version: 3.10.13 | packaged by conda-forge | (main, Dec 23 2023, 15:36:39) [GCC 12.3.0] (64-bit runtime)
Python platform: Linux-5.4.0-170-generic-x86_64-with-glibc2.31
Is CUDA available: True
CUDA runtime version: 12.3.107
CUDA_MODULE_LOADING set to: LAZY
GPU models and configuration: 
GPU 0: NVIDIA GeForce RTX 4090
GPU 1: NVIDIA GeForce RTX 4090

Nvidia driver version: 545.23.08
cuDNN version: Probably one of the following:
/usr/lib/x86_64-linux-gnu/libcudnn.so.8.9.7
/usr/lib/x86_64-linux-gnu/libcudnn_adv_infer.so.8.9.7
/usr/lib/x86_64-linux-gnu/libcudnn_adv_train.so.8.9.7
/usr/lib/x86_64-linux-gnu/libcudnn_cnn_infer.so.8.9.7
/usr/lib/x86_64-linux-gnu/libcudnn_cnn_train.so.8.9.7
/usr/lib/x86_64-linux-gnu/libcudnn_ops_infer.so.8.9.7
/usr/lib/x86_64-linux-gnu/libcudnn_ops_train.so.8.9.7
HIP runtime version: N/A
MIOpen runtime version: N/A
Is XNNPACK available: True

CPU:
Architecture:                       x86_64
CPU op-mode(s):                     32-bit, 64-bit
Byte Order:                         Little Endian
Address sizes:                      52 bits physical, 57 bits virtual
CPU(s):                             48
On-line CPU(s) list:                0-47
Thread(s) per core:                 2
Core(s) per socket:                 24
Socket(s):                          1
NUMA node(s):                       1
Vendor ID:                          AuthenticAMD
CPU family:                         25
Model:                              24
Model name:                         AMD Ryzen Threadripper 7960X 24-Cores
Stepping:                           1
Frequency boost:                    enabled
CPU MHz:                            1702.542
CPU max MHz:                        4200.0000
CPU min MHz:                        1500.0000
BogoMIPS:                           8387.15
Virtualization:                     AMD-V
L1d cache:                          768 KiB
L1i cache:                          768 KiB
L2 cache:                           24 MiB
L3 cache:                           128 MiB
NUMA node0 CPU(s):                  0-47
Vulnerability Gather data sampling: Not affected
Vulnerability Itlb multihit:        Not affected
Vulnerability L1tf:                 Not affected
Vulnerability Mds:                  Not affected
Vulnerability Meltdown:             Not affected
Vulnerability Mmio stale data:      Not affected
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; Retpolines, IBPB conditional, IBRS_FW, STIBP always-on, RSB filling, PBRSB-eIBRS Not affected
Vulnerability Srbds:                Not affected
Vulnerability Tsx async abort:      Not affected
Flags:                              fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ht syscall nx mmxext fxsr_opt pdpe1gb rdtscp lm constant_tsc rep_good nopl nonstop_tsc cpuid extd_apicid aperfmperf pni pclmulqdq monitor ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt aes xsave avx f16c rdrand lahf_lm cmp_legacy svm extapic cr8_legacy abm sse4a misalignsse 3dnowprefetch osvw ibs skinit wdt tce topoext perfctr_core perfctr_nb bpext perfctr_llc mwaitx cpb cat_l3 cdp_l3 invpcid_single hw_pstate ssbd mba ibrs ibpb stibp vmmcall fsgsbase bmi1 avx2 smep bmi2 erms invpcid cqm rdt_a avx512f avx512dq rdseed adx smap avx512ifma clflushopt clwb avx512cd sha_ni avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local avx512_bf16 clzero irperf xsaveerptr wbnoinvd arat npt lbrv svm_lock nrip_save tsc_scale vmcb_clean flushbyasid decodeassists pausefilter pfthreshold avic v_vmsave_vmload vgif avx512vbmi umip pku ospke avx512_vbmi2 gfni vaes vpclmulqdq avx512_vnni avx512_bitalg avx512_vpopcntdq rdpid overflow_recov succor smca flush_l1d

Versions of relevant libraries:
[pip3] audiolm-pytorch==2.0.6
[pip3] ema-pytorch==0.3.2
[pip3] mypy-extensions==1.0.0
[pip3] naturalspeech2-pytorch==0.1.8
[pip3] numpy==1.26.3
[pip3] onnx==1.15.0
[pip3] onnxruntime-gpu==1.16.3
[pip3] pytorch-triton==2.2.0+e28a256d71
[pip3] pytorch-warmup==0.1.1
[pip3] rotary-embedding-torch==0.5.3
[pip3] spear-tts-pytorch==0.4.8
[pip3] torch==2.1.2
[pip3] torchaudio==2.1.2
[pip3] torchdiffeq==0.2.3
[pip3] torchode==0.2.0
[pip3] torchtyping==0.1.4
[pip3] torchvision==0.16.2
[pip3] triton==2.1.0
[pip3] vector_quantize_pytorch==1.12.16
[pip3] voicebox-pytorch==0.4.12
[conda] audiolm-pytorch           2.0.6                    pypi_0    pypi
[conda] cudatoolkit               11.8.0              h4ba93d1_12    conda-forge
[conda] ema-pytorch               0.3.2                    pypi_0    pypi
[conda] libmagma                  2.7.1                hc72dce7_6    conda-forge
[conda] libmagma_sparse           2.7.1                h8354cda_6    conda-forge
[conda] libopenvino-pytorch-frontend 2023.2.0             h59595ed_5    conda-forge
[conda] magma                     2.7.1                ha770c72_6    conda-forge
[conda] naturalspeech2-pytorch    0.1.8                    pypi_0    pypi
[conda] numpy                     1.26.3          py310hb13e2d6_0    conda-forge
[conda] pytorch-triton            2.2.0+e28a256d71          pypi_0    pypi
[conda] pytorch-warmup            0.1.1                    pypi_0    pypi
[conda] rotary-embedding-torch    0.5.3                    pypi_0    pypi
[conda] spear-tts-pytorch         0.4.8                    pypi_0    pypi
[conda] torch                     2.1.2                    pypi_0    pypi
[conda] torchaudio                2.1.2                    pypi_0    pypi
[conda] torchdiffeq               0.2.3                    pypi_0    pypi
[conda] torchode                  0.2.0                    pypi_0    pypi
[conda] torchtyping               0.1.4                    pypi_0    pypi
[conda] torchvision               0.16.2                   pypi_0    pypi
[conda] triton                    2.1.0                    pypi_0    pypi
[conda] vector-quantize-pytorch   1.12.16                  pypi_0    pypi
[conda] voicebox-pytorch          0.4.12                   pypi_0    pypi
```

cc @ptrblck @msaroufim @eqy