Repository: pytorch
Issue: [Regression PyTorch 2.1 & 2.2] `torch._transformer_encoder_layer_fwd` outputs on CUDA/NestedTensorCUDA backends significantly diverge from truth for torch>=2.1 (SDP math))
Labels: high priority,module: nn,triaged,module: nestedtensor

### 🐛 Describe the bug

Hi,

As reported in https://github.com/huggingface/optimum/issues/1769, I noticed that the outputs of `torch._transformer_encoder_layer_fwd` significantly diverge from the correct outputs for torch>=2.1. User reports degradated predictive performance due to this.

In my case, I see a mean relative difference of **more than 2%** overall. Besides, **more than 2% of values have a mean relative difference of more than 5%**. Besides, out of a 16384 values output tensor, 78 values differ by more than 20%, which is huge and seem to impact the global outputs. Note that I checked only one layer, this may accumulate on several layers.

Note: Given the user report of degradated performance, I am confident that PyTorch 2.0.2 is "truth", but I need to confirm that

This occurs only on CUDA device, not CPU.

Reproduction:
* `wget https://huggingface.co/fxmarty/debug-_transformer_encoder_layer_fwd/raw/main/debug_bt.zip` (see https://huggingface.co/fxmarty/debug-_transformer_encoder_layer_fwd/tree/main, could not upload on github directly as too large)
* unzip it
* Create two conda envs with torch `2.2.1+cu118` and `2.0.1+cu118`

Run on each conda environment
```python
import torch

device = "cuda"

embed_dim = 1024
num_heads = 16
use_gelu = True
norm_first = False
norm1_eps = 1e-05
attention_mask = None

in_proj_weight = torch.load("in_proj_weight.pt").to(device)
in_proj_bias = torch.load("in_proj_bias.pt").to(device)
out_proj_weight = torch.load("out_proj_weight.pt").to(device)
out_proj_bias = torch.load("out_proj_bias.pt").to(device)
norm1_weight = torch.load("norm1_weight.pt").to(device)
norm1_bias = torch.load("norm1_bias.pt").to(device)
norm2_weight = torch.load("norm2_weight.pt").to(device)
norm2_bias = torch.load("norm2_bias.pt").to(device)
linear1_weight = torch.load("linear1_weight.pt").to(device)
linear1_bias = torch.load("linear1_bias.pt").to(device)
linear2_weight = torch.load("linear2_weight.pt").to(device)
linear2_bias = torch.load("linear2_bias.pt").to(device)

hidden_states = torch.load("hidden_states.pt").to(device)
hidden_states = hidden_states.unsqueeze(0)
#hidden_states = torch.nested.nested_tensor([hidden_states])

with torch.no_grad():
    with torch.backends.cuda.sdp_kernel(enable_flash=False, enable_math=True, enable_mem_efficient=False):
        res = torch._transformer_encoder_layer_fwd(
            hidden_states,
            embed_dim,
            num_heads,
            in_proj_weight,
            in_proj_bias,
            out_proj_weight,
            out_proj_bias,
            use_gelu,
            norm_first,
            norm1_eps,
            norm1_weight,
            norm1_bias,
            norm2_weight,
            norm2_bias,
            linear1_weight,
            linear1_bias,
            linear2_weight,
            linear2_bias,
            attention_mask,
        )

torch.save(res, f"result_{torch.__version__}.pt")
```

And then run
```python
import torch

tensor_221 = torch.load("/home/fxmarty/debug_bt/result_2.2.1+cu118.pt")
tensor_201 = torch.load("/home/fxmarty/debug_bt/result_2.0.1+cu118.pt")

reldiff = (tensor_221 - tensor_201).abs() / (tensor_221.abs() + 1e-12)
print("max reldiff=", reldiff.max())
print("mean reldiff=", reldiff.mean())

print("reldiff>0.2 count:", torch.count_nonzero(reldiff > 0.2), "out of", reldiff.numel())
print("reldiff>0.05 count:", torch.count_nonzero(reldiff > 0.05), "out of", reldiff.numel())

torch.set_printoptions(threshold=1000000000)

print((tensor_221 - tensor_201).abs() / (tensor_221.abs() + 1e-12))
```

giving
```
max reldiff= tensor(209.0369, device='cuda:0')
mean reldiff= tensor(0.0214, device='cuda:0')
reldiff>0.2 count: tensor(78, device='cuda:0') out of 16384
reldiff>0.05 count: tensor(323, device='cuda:0') out of 16384
...
```

### Versions

PyTorch 2.2.1 env:
```
PyTorch version: 2.2.1+cu118
Is debug build: False
CUDA used to build PyTorch: 11.8
ROCM used to build PyTorch: N/A

OS: Ubuntu 22.04.1 LTS (x86_64)
GCC version: (Ubuntu 11.4.0-1ubuntu1~22.04) 11.4.0
Clang version: 14.0.0-1ubuntu1.1
CMake version: version 3.27.4
Libc version: glibc-2.35

Python version: 3.9.12 (main, Apr  5 2022, 06:56:58)  [GCC 7.5.0] (64-bit runtime)
Python platform: Linux-5.15.0-101-generic-x86_64-with-glibc2.35
Is CUDA available: True
CUDA runtime version: 11.7.99
CUDA_MODULE_LOADING set to: LAZY
GPU models and configuration: GPU 0: NVIDIA GeForce RTX 3060 Laptop GPU
Nvidia driver version: 515.86.01
cuDNN version: Probably one of the following:
/usr/local/cuda-11.7/targets/x86_64-linux/lib/libcudnn.so.8.6.0
/usr/local/cuda-11.7/targets/x86_64-linux/lib/libcudnn_adv_infer.so.8.6.0
/usr/local/cuda-11.7/targets/x86_64-linux/lib/libcudnn_adv_train.so.8.6.0
/usr/local/cuda-11.7/targets/x86_64-linux/lib/libcudnn_cnn_infer.so.8.6.0
/usr/local/cuda-11.7/targets/x86_64-linux/lib/libcudnn_cnn_train.so.8.6.0
/usr/local/cuda-11.7/targets/x86_64-linux/lib/libcudnn_ops_infer.so.8.6.0
/usr/local/cuda-11.7/targets/x86_64-linux/lib/libcudnn_ops_train.so.8.6.0
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
Address sizes:                      46 bits physical, 48 bits virtual
Byte Order:                         Little Endian
CPU(s):                             20
On-line CPU(s) list:                0-19
Vendor ID:                          GenuineIntel
Model name:                         12th Gen Intel(R) Core(TM) i7-1280P
CPU family:                         6
Model:                              154
Thread(s) per core:                 2
Core(s) per socket:                 14
Socket(s):                          1
Stepping:                           3
CPU max MHz:                        4800,0000
CPU min MHz:                        400,0000
BogoMIPS:                           3993.60
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 tsc_known_freq pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 sdbg fma cx16 xtpr pdcm sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault epb cat_l2 cdp_l2 ssbd ibrs ibpb stibp ibrs_enhanced tpr_shadow vnmi flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid rdt_a rdseed adx smap clflushopt clwb intel_pt sha_ni xsaveopt xsavec xgetbv1 xsaves split_lock_detect avx_vnni dtherm ida arat pln pts hwp hwp_notify hwp_act_window hwp_epp hwp_pkg_req umip pku ospke waitpkg gfni vaes vpclmulqdq tme rdpid movdiri movdir64b fsrm md_clear serialize pconfig arch_lbr flush_l1d arch_capabilities
Virtualization:                     VT-x
L1d cache:                          544 KiB (14 instances)
L1i cache:                          704 KiB (14 instances)
L2 cache:                           11,5 MiB (8 instances)
L3 cache:                           24 MiB (1 instance)
NUMA node(s):                       1
NUMA node0 CPU(s):                  0-19
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 rstack overflow: 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 IBRS, IBPB conditional, RSB filling, PBRSB-eIBRS SW sequence
Vulnerability Srbds:                Not affected
Vulnerability Tsx async abort:      Not affected

Versions of relevant libraries:
[pip3] flake8==6.1.0
[pip3] flake8-bugbear==23.3.23
[pip3] flake8-comprehensions==3.12.0
[pip3] flake8-executable==2.1.3
[pip3] flake8-logging-format==0.9.0
[pip3] flake8-pyi==23.3.1
[pip3] flake8-simplify==0.19.3
[pip3] lovely-numpy==0.2.11
[pip3] mypy==1.8.0
[pip3] mypy-extensions==1.0.0
[pip3] numpy==1.26.0
[pip3] onnx==1.15.0
[pip3] onnx-graphsurgeon==0.3.12
[pip3] onnx-simplifier==0.4.35
[pip3] onnx-tool==0.9.0
[pip3] onnxoptimizer==0.3.13
[pip3] onnxruntime-extensions==0.9.0
[pip3] onnxruntime-gpu==1.17.1
[pip3] onnxscript==0.1.0.dev20231010
[pip3] open-clip-torch==2.23.0
[pip3] optree==0.10.0
[pip3] torch==2.2.1+cu118
[pip3] torch-model-archiver==0.6.1
[pip3] torch-tb-profiler==0.4.1
[pip3] torch-workflow-archiver==0.2.5
[pip3] torchaudio==2.2.1+cu118
[pip3] torchinfo==1.7.0
[pip3] torchserve==0.6.1
[pip3] torchvision==0.17.1+cu118
[pip3] torchviz==0.0.2
[pip3] triton==2.2.0
[conda] cudatoolkit               11.3.1               h2bc3f7f_2    anaconda
[conda] lovely-numpy              0.2.11                   pypi_0    pypi
[conda] numpy                     1.26.0                   pypi_0    pypi
[conda] open-clip-torch           2.23.0                   pypi_0    pypi
[conda] optree                    0.10.0                   pypi_0    pypi
[conda] torch                     2.2.1+cu118              pypi_0    pypi
[conda] torch-model-archiver      0.6.1                    pypi_0    pypi
[conda] torch-tb-profiler         0.4.1                    pypi_0    pypi
[conda] torch-workflow-archiver   0.2.5                    pypi_0    pypi
[conda] torchaudio                2.2.1+cu118              pypi_0    pypi
[conda] torchfix                  0.4.0                    pypi_0    pypi
[conda] torchinfo                 1.7.0                    pypi_0    pypi
[conda] torchserve                0.6.1                    pypi_0    pypi
[conda] torchvision               0.17.1+cu118             pypi_0    pypi
[conda] torchviz                  0.0.2                    pypi_0    pypi
[conda] triton                    2.2.0                    pypi_0    pypi
```

PyTorch 2.0.1 env:
```
PyTorch version: 2.0.1+cu118
Is debug build: False
CUDA used to build PyTorch: 11.8
ROCM used to build PyTorch: N/A

OS: Ubuntu 22.04.1 LTS (x86_64)
GCC version: (Ubuntu 11.4.0-1ubuntu1~22.04) 11.4.0
Clang version: 14.0.0-1ubuntu1.1
CMake version: version 3.25.0
Libc version: glibc-2.35

Python version: 3.9.16 (main, Mar  8 2023, 14:00:05)  [GCC 11.2.0] (64-bit runtime)
Python platform: Linux-5.15.0-101-generic-x86_64-with-glibc2.35
Is CUDA available: True
CUDA runtime version: 11.7.99
CUDA_MODULE_LOADING set to: LAZY
GPU models and configuration: GPU 0: NVIDIA GeForce RTX 3060 Laptop GPU
Nvidia driver version: 515.86.01
cuDNN version: Probably one of the following:
/usr/local/cuda-11.7/targets/x86_64-linux/lib/libcudnn.so.8.6.0
/usr/local/cuda-11.7/targets/x86_64-linux/lib/libcudnn_adv_infer.so.8.6.0
/usr/local/cuda-11.7/targets/x86_64-linux/lib/libcudnn_adv_train.so.8.6.0
/usr/local/cuda-11.7/targets/x86_64-linux/lib/libcudnn_cnn_infer.so.8.6.0
/usr/local/cuda-11.7/targets/x86_64-linux/lib/libcudnn_cnn_train.so.8.6.0
/usr/local/cuda-11.7/targets/x86_64-linux/lib/libcudnn_ops_infer.so.8.6.0
/usr/local/cuda-11.7/targets/x86_64-linux/lib/libcudnn_ops_train.so.8.6.0
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
Address sizes:                      46 bits physical, 48 bits virtual
Byte Order:                         Little Endian
CPU(s):                             20
On-line CPU(s) list:                0-19
Vendor ID:                          GenuineIntel
Model name:                         12th Gen Intel(R) Core(TM) i7-1280P
CPU family:                         6
Model:                              154
Thread(s) per core:                 2
Core(s) per socket:                 14
Socket(s):                          1
Stepping:                           3
CPU max MHz:                        4800,0000
CPU min MHz:                        400,0000
BogoMIPS:                           3993.60
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 tsc_known_freq pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 sdbg fma cx16 xtpr pdcm sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault epb cat_l2 cdp_l2 ssbd ibrs ibpb stibp ibrs_enhanced tpr_shadow vnmi flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid rdt_a rdseed adx smap clflushopt clwb intel_pt sha_ni xsaveopt xsavec xgetbv1 xsaves split_lock_detect avx_vnni dtherm ida arat pln pts hwp hwp_notify hwp_act_window hwp_epp hwp_pkg_req umip pku ospke waitpkg gfni vaes vpclmulqdq tme rdpid movdiri movdir64b fsrm md_clear serialize pconfig arch_lbr flush_l1d arch_capabilities
Virtualization:                     VT-x
L1d cache:                          544 KiB (14 instances)
L1i cache:                          704 KiB (14 instances)
L2 cache:                           11,5 MiB (8 instances)
L3 cache:                           24 MiB (1 instance)
NUMA node(s):                       1
NUMA node0 CPU(s):                  0-19
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 rstack overflow: 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 IBRS, IBPB conditional, RSB filling, PBRSB-eIBRS SW sequence
Vulnerability Srbds:                Not affected
Vulnerability Tsx async abort:      Not affected

Versions of relevant libraries:
[pip3] lovely-numpy==0.2.11
[pip3] mypy-extensions==1.0.0
[pip3] numpy==1.24.1
[pip3] torch==2.0.1+cu118
[pip3] torchaudio==2.0.2+cu118
[pip3] torchvision==0.15.2+cu118
[pip3] triton==2.0.0
[conda] lovely-numpy              0.2.11                   pypi_0    pypi
[conda] numpy                     1.24.1                   pypi_0    pypi
[conda] torch                     2.0.1+cu118              pypi_0    pypi
[conda] torchaudio                2.0.2+cu118              pypi_0    pypi
[conda] torchvision               0.15.2+cu118             pypi_0    pypi
[conda] triton                    2.0.0                    pypi_0    pypi
```

cc @ezyang @gchanan @zou3519 @kadeng @msaroufim @albanD @mruberry @jbschlosser @walterddr @mikaylagawarecki @cpuhrsch @bhosmer @drisspg @soulitzer @davidberard98 @YuqingJ @erichan1