Repository: pytorch
Issue: FlexAttention result deviates with torch.compile() and torch.set_float32_matmul_precision('high')
Labels: triaged,oncall: pt2,module: higher order operators,module: pt2-dispatcher,module: flex attention

### 🐛 Describe the bug

Hi, I was testing FlexAttention by comparing its output with that of `nn.MultiheadAttention` and `torch.nn.functional.scaled_dot_product_attention`. In the end, I tracked down the discrepancy to the minimum test below:

```python
import argparse
import itertools

import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.attention import flex_attention


parser = argparse.ArgumentParser(description='Minimum MHA / SDPA / Flex Attention mask test')
parser.add_argument('--test-flex-attention', action='store_true',
                    help='assert_close for the flex attention output to the rest.')
parser.add_argument('--mask', action='store_true',
                    help='Test with a simple attention mask.')
parser.add_argument('--compile', action='store_true',
                    help='Compile the model.')
parser.add_argument('--high-precision', action='store_true',
                    help='Set float32 matmul precision to "high" (instead of "highest").')


def apply_attn_in(input, in_w, in_b, num_heads, head_dim):
    b, s, d = input.shape
    qkv = F.linear(input, in_w, in_b)
    qkv = qkv.reshape((b, s, 3, num_heads, head_dim))
    # (b, s, 3, nh, hd) -> (3, b, nh, s, hd)
    return qkv.permute(2, 0, 3, 1, 4)


def apply_attn_out(out, out_w, out_b):
    # (b, nh, s, hd) -> (b, s, nh, hd)
    out = out.transpose(1, 2)
    b, s, nh, hd = out.shape
    out = out.reshape((b, s, nh * hd))
    return F.linear(out, out_w, out_b)


def apply_attention(input, in_w, in_b, out_w, out_b, num_heads, head_dim, attn_mask, block_mask):
    q, k, v = apply_attn_in(input, in_w, in_b, num_heads, head_dim)
    out = F.scaled_dot_product_attention(q, k, v, attn_mask=attn_mask)
    sdpa_out = apply_attn_out(out, out_w, out_b)
    out = flex_attention.flex_attention(q, k, v, block_mask=block_mask)
    flex_out = apply_attn_out(out, out_w, out_b)
    return sdpa_out, flex_out


class ThreeAttention(nn.Module):

    def __init__(
        self,
        hidden_dim: int,
        num_heads: int,
        attn_mask,
        block_mask,
        test_flex_attention,
    ):
        super().__init__()
        self.hidden_dim = hidden_dim
        self.num_heads = num_heads
        self.mha = nn.MultiheadAttention(hidden_dim, num_heads, batch_first=True)
        self.attn_mask = attn_mask
        self.block_mask = block_mask
        self.test_flex_attention = test_flex_attention

    def forward(self, x):
        sdpa_out, flex_out = apply_attention(
            x, self.mha.in_proj_weight,
            self.mha.in_proj_bias,
            self.mha.out_proj.weight,
            self.mha.out_proj.bias,
            self.num_heads,
            self.hidden_dim // self.num_heads,
            self.attn_mask, self.block_mask)
        if self.test_flex_attention:
            torch.testing.assert_close(sdpa_out, flex_out)
        mha_out, _ = self.mha(x, x, x, need_weights=False, attn_mask=None if self.attn_mask is None else ~self.attn_mask)
        torch.testing.assert_close(sdpa_out, mha_out)
        return mha_out


def main():
    args = parser.parse_args()
    for args.test_flex_attention, args.mask, args.compile, args.high_precision in itertools.product((False, True), repeat=4):
        try:
            if args.high_precision:
                torch.set_float32_matmul_precision('high')
            else:
                torch.set_float32_matmul_precision('highest')
            hidden_dim = 16
            num_heads = 1
            seq_length = 2
            attn_mask = block_mask = None
            if args.mask:
                attn_mask = torch.eye(seq_length, dtype=torch.bool).cuda()
                def mask_mod(b, h, q_idx, kv_idx):
                    return attn_mask[q_idx][kv_idx]
                block_mask = flex_attention.create_block_mask(
                    mask_mod, B=None, H=None, Q_LEN=seq_length, KV_LEN=seq_length, BLOCK_SIZE=seq_length)
            attn = ThreeAttention(hidden_dim, num_heads, attn_mask, block_mask, args.test_flex_attention).cuda()
            if args.compile:
                attn = torch.compile(attn)
            batch_size = 1
            x = torch.randn(batch_size, seq_length, hidden_dim).cuda()
            attn(x)
        except Exception as ex:
            print(f"{args.test_flex_attention=}, {args.mask=}, {args.compile=}, {args.high_precision=} FAILED!")
            print(ex)


if __name__ == "__main__":
    main()
```
Here is one of the raw test output (username redacted):
```bash
$ python minimum_test.py
/home/████/.local/lib/python3.12/site-packages/torch/_inductor/compile_fx.py:167: UserWarning: TensorFloat32 tensor cores for float32 matrix multiplication available but not enabled. Consider setting `torch.set_float32_matmul_precision('high')` for better performance.
  warnings.warn(
args.test_flex_attention=True, args.mask=False, args.compile=True, args.high_precision=True FAILED!
Tensor-likes are not close!

Mismatched elements: 29 / 32 (90.6%)
Greatest absolute difference: 0.0002556145191192627 at index (0, 0, 2) (up to 1e-05 allowed)
Greatest relative difference: 0.024009626358747482 at index (0, 0, 12) (up to 1.3e-06 allowed)
args.test_flex_attention=True, args.mask=True, args.compile=True, args.high_precision=True FAILED!
Tensor-likes are not close!

Mismatched elements: 28 / 32 (87.5%)
Greatest absolute difference: 0.00046330690383911133 at index (0, 0, 5) (up to 1e-05 allowed)
Greatest relative difference: 0.11991884559392929 at index (0, 0, 6) (up to 1.3e-06 allowed)
```
The absolute and relative difference...well, differs in each run, but AFAICT these two cases always fail.
It seems that FlexAttention gives a significantly different result from that of MHA / SDPA when compiled and `torch.set_float32_matmul_precision('high')` whether a mask is applied or not, while everything else is robust. I am not particularly versed in numerical methods or CUDA kernels, but >0.1 of relative difference seems unusual even if 19-bit "TF32" is used here.

I have also tried running `minimum_test.py` above with the current nightly `torch==2.6.0.dev20241021+cu121`. `args.test_flex_attention=True, args.mask=False, args.compile=True, args.high_precision=True` still fails while `args.test_flex_attention=True, args.mask=True, args.compile=True, args.high_precision=False / True` hits a separate error:
```bash
$ python minimum_test.py
args.test_flex_attention=True, args.mask=False, args.compile=True, args.high_precision=True FAILED!
Tensor-likes are not close!

Mismatched elements: 32 / 32 (100.0%)
Greatest absolute difference: 0.00021606683731079102 at index (0, 0, 0) (up to 1e-05 allowed)
Greatest relative difference: 0.004445451311767101 at index (0, 0, 8) (up to 1.3e-06 allowed)
/home/████/.local/lib/python3.12/site-packages/torch/_inductor/compile_fx.py:183: UserWarning: TensorFloat32 tensor cores for float32 matrix multiplication available but not enabled. Consider setting `torch.set_float32_matmul_precision('high')` for better performance.
  warnings.warn(
args.test_flex_attention=True, args.mask=True, args.compile=True, args.high_precision=False FAILED!
backend='inductor' raised:
LoweringException: NoValidChoicesError: No choices to select, please consider adding ATEN into max_autotune_gemm_backends config (defined in torch/_inductor/config.py) to allow at least one choice. 
# (...)
args.test_flex_attention=True, args.mask=True, args.compile=True, args.high_precision=True FAILED!
backend='inductor' raised:
LoweringException: NoValidChoicesError: No choices to select, please consider adding ATEN into max_autotune_gemm_backends config (defined in torch/_inductor/config.py) to allow at least one choice. 
# (...)
```
(https://github.com/pytorch/pytorch/issues/135161 *might* be related...? But that one is about the gradient, not the forward pass...)

### Versions

```bash
$ python collect_env.py
Collecting environment information...
PyTorch version: 2.5.0+cu121
Is debug build: False
CUDA used to build PyTorch: 12.1
ROCM used to build PyTorch: N/A

OS: Ubuntu 24.04.1 LTS (x86_64)
GCC version: (Ubuntu 13.2.0-23ubuntu4) 13.2.0
Clang version: Could not collect
CMake version: Could not collect
Libc version: glibc-2.39

Python version: 3.12.3 (main, Sep 11 2024, 14:17:37) [GCC 13.2.0] (64-bit runtime)
Python platform: Linux-6.8.0-47-generic-x86_64-with-glibc2.39
Is CUDA available: True
CUDA runtime version: 12.0.140
CUDA_MODULE_LOADING set to: LAZY
GPU models and configuration: GPU 0: NVIDIA GeForce RTX 3080 Laptop GPU
Nvidia driver version: 535.183.01
cuDNN version: Probably one of the following:
/usr/lib/x86_64-linux-gnu/libcudnn.so.8.6.0
/usr/lib/x86_64-linux-gnu/libcudnn_adv_infer.so.8.6.0
/usr/lib/x86_64-linux-gnu/libcudnn_adv_train.so.8.6.0
/usr/lib/x86_64-linux-gnu/libcudnn_cnn_infer.so.8.6.0
/usr/lib/x86_64-linux-gnu/libcudnn_cnn_train.so.8.6.0
/usr/lib/x86_64-linux-gnu/libcudnn_ops_infer.so.8.6.0
/usr/lib/x86_64-linux-gnu/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:                        39 bits physical, 48 bits virtual
Byte Order:                           Little Endian
CPU(s):                               16
On-line CPU(s) list:                  0-15
Vendor ID:                            GenuineIntel
Model name:                           11th Gen Intel(R) Core(TM) i7-11800H @ 2.30GHz
CPU family:                           6
Model:                                141
Thread(s) per core:                   2
Core(s) per socket:                   8
Socket(s):                            1
Stepping:                             1
CPU(s) scaling MHz:                   21%
CPU max MHz:                          4600.0000
CPU min MHz:                          800.0000
BogoMIPS:                             4608.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 tsc_known_freq pni pclmulqdq dtes64 monitor ds_cpl vmx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid 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 flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid rdt_a avx512f avx512dq rdseed adx smap avx512ifma clflushopt clwb intel_pt avx512cd sha_ni avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves split_lock_detect user_shstk dtherm ida arat pln pts hwp hwp_notify hwp_act_window hwp_epp hwp_pkg_req vnmi avx512vbmi umip pku ospke avx512_vbmi2 gfni vaes vpclmulqdq avx512_vnni avx512_bitalg avx512_vpopcntdq rdpid movdiri movdir64b fsrm avx512_vp2intersect md_clear ibt flush_l1d arch_capabilities
Virtualization:                       VT-x
L1d cache:                            384 KiB (8 instances)
L1i cache:                            256 KiB (8 instances)
L2 cache:                             10 MiB (8 instances)
L3 cache:                             24 MiB (1 instance)
NUMA node(s):                         1
NUMA node0 CPU(s):                    0-15
Vulnerability Gather data sampling:   Mitigation; Microcode
Vulnerability Itlb multihit:          Not affected
Vulnerability L1tf:                   Not affected
Vulnerability Mds:                    Not affected
Vulnerability Meltdown:               Not affected
Vulnerability Mmio stale data:        Not affected
Vulnerability Reg file data sampling: Not affected
Vulnerability Retbleed:               Not affected
Vulnerability Spec rstack overflow:   Not affected
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; Enhanced / Automatic IBRS; IBPB conditional; RSB filling; PBRSB-eIBRS SW sequence; BHI SW loop, KVM SW loop
Vulnerability Srbds:                  Not affected
Vulnerability Tsx async abort:        Not affected

Versions of relevant libraries:
[pip3] flake8==7.0.0
[pip3] numpy==1.26.3
[pip3] nvidia-cublas-cu12==12.1.3.1
[pip3] nvidia-cuda-cupti-cu12==12.1.105
[pip3] nvidia-cuda-nvrtc-cu12==12.1.105
[pip3] nvidia-cuda-runtime-cu12==12.1.105
[pip3] nvidia-cudnn-cu12==9.1.0.70
[pip3] nvidia-cufft-cu12==11.0.2.54
[pip3] nvidia-curand-cu12==10.3.2.106
[pip3] nvidia-cusolver-cu12==11.4.5.107
[pip3] nvidia-cusparse-cu12==12.1.0.106
[pip3] nvidia-nccl-cu12==2.21.5
[pip3] nvidia-nvjitlink-cu12==12.1.105
[pip3] nvidia-nvtx-cu12==12.1.105
[pip3] pytorch-triton==3.1.0+cf34004b8a
[pip3] torch==2.5.0+cu121
[pip3] torchaudio==2.5.0+cu121
[pip3] torchvision==0.20.0+cu121
[pip3] triton==3.1.0
[pip3] types-flake8-2020==1.8
[pip3] types-flake8-bugbear==23.9.16
[pip3] types-flake8-builtins==2.2
[pip3] types-flake8-docstrings==1.7
[pip3] types-flake8-plugin-utils==1.3
[pip3] types-flake8-rst-docstrings==0.3
[pip3] types-flake8-simplify==0.21
[pip3] types-flake8-typing-imports==1.15
[pip3] types-mypy-extensions==1.0
[conda] Could not collect
```

cc @ezyang @chauhang @penguinwu @zou3519 @ydwu4 @bdhirsh @yf225 @Chillee @drisspg @yanboliang @BoyuanFeng