Repository: pytorch
Issue: Discussion about the testing methods in test_transformers.py after math backend always uses fp32
Labels: triaged,module: sdpa

### 🐛 Describe the bug

The current method to estimate the numerical errors in test_transformers.py is based on the difference b/w results from current precision and higher precision tensors
https://github.com/pytorch/pytorch/blob/bc1b8f094d24de27432f4c29f0729e85a6b5ba63/test/test_transformers.py#L3107-L3108
https://github.com/pytorch/pytorch/blob/bc1b8f094d24de27432f4c29f0729e85a6b5ba63/test/test_transformers.py#L3118-L3122
https://github.com/pytorch/pytorch/blob/bc1b8f094d24de27432f4c29f0729e85a6b5ba63/test/test_transformers.py#L132-L133
https://github.com/pytorch/pytorch/blob/bc1b8f094d24de27432f4c29f0729e85a6b5ba63/test/test_transformers.py#L141-L145

However, with [PR 128922](https://github.com/pytorch/pytorch/pull/128922), the math backend always casts the input tensors to fp32 from 16-bit datatypes for better accuracy:
https://github.com/pytorch/pytorch/blob/bc1b8f094d24de27432f4c29f0729e85a6b5ba63/aten/src/ATen/native/transformers/attention.cpp#L787-L801

Although PR 128922 fixed the tests on NV GPUs by raising the fudge factors, the assumptions of current numerical error estimation method do not hold anymore because `ref` and `_lp` tensors are fundamentally doing the same computation, and the errors between the two tensors are probably not measuring something meaningful for the purpose of estimating the SDPA's numerical errors.

More concretely. I have inspected the output tensors of UT `TestSDPACudaOnlyCUDA.test_flash_attention_vs_math_ref_grads_batch_size_8_seq_len_q_2048_seq_len_k_2048_head_dim_8_is_causal_False_dropout_p_0_0_float16_scale_l1_enable_gqa_False_n_heads1_cuda_float16`
The difference b/w the gold and reference is `4.76837158203125e-07` for `grad_query`, and `3.0510127544403076e-05` for `grad_key`, which looks more like tolerances for float32 instead of float16.

## Potential Solution 1

Add a Python based SDPA function (something similar to https://pytorch.org/docs/stable/generated/torch.nn.functional.scaled_dot_product_attention.html) in `test_transformers.py`, without casting fp16/bf16 to fp32

## Potential Solution 2

Add a debug flag to Math backend function to disable the casting behavior

## Potential Solution 3

Other method to estimate the numerical error?

### Versions

```
PyTorch version: 2.5.0a0+git735162e             
Is debug build: False                           
CUDA used to build PyTorch: N/A                 
ROCM used to build PyTorch: 6.2.41133-dd7f95766 
                                                           
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.26.4                                                                                          
Libc version: glibc-2.31                                                                                                                                                                                                                      
                                                           
Python version: 3.9.19 (main, May  6 2024, 19:43:03)  [GCC 11.2.0] (64-bit runtime)
Python platform: Linux-6.5.0-35-generic-x86_64-with-glibc2.31                                                                                                                                                                                 Is CUDA available: True                                                                                                                                                                                                                       CUDA runtime version: Could not collect                                                                                                                                                                                                       CUDA_MODULE_LOADING set to: LAZY                                                                                                                                                                                                              GPU models and configuration: AMD Instinct MI210 (gfx90a:sramecc+:xnack-)
Nvidia driver version: Could not collect
cuDNN version: Could not collect
HIP runtime version: 6.2.41133
MIOpen runtime version: 3.2.0 
Is XNNPACK available: True          
                                                           
CPU:                               
Architecture:                       x86_64
CPU op-mode(s):                     32-bit, 64-bit
Byte Order:                         Little Endian
Address sizes:                      43 bits physical, 48 bits virtual
CPU(s):                             128
On-line CPU(s) list:                0-127
Thread(s) per core:                 2
Core(s) per socket:                 32
Socket(s):                          2
NUMA node(s):                       2
Vendor ID:                          AuthenticAMD
CPU family:                         23                                                                                 
Model:                              49                                                                                 
Model name:                         AMD EPYC 7542 32-Core Processor      
Stepping:                           0                                                                                  
Frequency boost:                    enabled                                                                            
CPU MHz:                            1500.000                                                                           
CPU max MHz:                        2900.0000                                                                          
CPU min MHz:                        1500.0000
BogoMIPS:                           5800.24
Virtualization:                     AMD-V
L1d cache:                          2 MiB
L1i cache:                          2 MiB
L2 cache:                           32 MiB
L3 cache:                           256 MiB
NUMA node0 CPU(s):                  0-31,64-95
NUMA node1 CPU(s):                  32-63,96-127
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:             Mitigation; untrained return thunk; SMT enabled with STIBP protection
Vulnerability Spec rstack overflow: Mitigation; Safe RET
Vulnerability Spec store bypass:    Mitigation; Speculative Store Bypass disabled via prctl
Vulnerability Spectre v1:           Mitigation; usercopy/swapgs barriers and __user pointer sanitization
Vulnerability Spectre v2:           Mitigation; Retpolines; IBPB conditional; STIBP always-on; RSB filling; PBRSB-eIBRS Not affected; BHI 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 rapl pni pclmulqdq monitor ssse3 fma cx16 sse4_1 sse4_2 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 hw_pstate ssbd mba ibrs ibpb stibp vmmcall fsgsbase bmi1 avx2 smep bmi2 cqm rdt_a rdseed adx smap clflushopt clwb sha_ni xsaveopt xsavec xgetbv1 cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_loc
al clzero irperf xsaveerptr rdpru wbnoinvd amd_ppin arat npt lbrv svm_lock nrip_save tsc_scale vmcb_clean flushbyasid decodeassists pausefilter pfthreshold avic v_vmsave_vmload vgif v_spec_ctrl umip rdpid overflow_recov succor smca sev se
v_es

Versions of relevant libraries:
[pip3] flake8==6.1.0
[pip3] flake8-bugbear==23.3.23
[pip3] flake8-comprehensions==3.15.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] mypy==1.10.0
[pip3] mypy-extensions==1.0.0
[pip3] numpy==1.26.0
[pip3] optree==0.12.1
[pip3] pytorch-triton-rocm==3.0.0
[pip3] torch==2.5.0a0+git2aca0ae
[pip3] torchaudio==2.4.0+rocm6.1
[pip3] torchvision==0.19.0a0
[pip3] triton==3.0.0
[conda] mkl                       2021.4.0           h06a4308_640  
[conda] mkl-include               2021.4.0           h06a4308_640  
[conda] numpy                     1.20.3                   pypi_0    pypi
[conda] optree                    0.11.0                   pypi_0    pypi
[conda] torch                     2.4.0a0+git6b37b45          pypi_0    pypi
[conda] torchvision               0.19.0a0+69e03db          pypi_0    pypi
[conda] triton                    3.0.0                    pypi_0    pypi
```

cc @jbschlosser @bhosmer @cpuhrsch @erichan1 @drisspg @mikaylagawarecki