### 🐛 Describe the bug
Hi,
As discussed on slack and on https://github.com/hug…gingface/transformers/issues/30056#issuecomment-2657390613, SDPA with custom attn_mask using mem-efficient backend (aotriton 0.8.0) produces wrong outputs on torch 2.6.0 stable ROCm release. This is fixed on torch nightly that uses aotriton 0.8.2.
Reproduction:
```python
import torch
from torch.nn.attention import SDPBackend, sdpa_kernel
from transformers.modeling_attn_mask_utils import _prepare_4d_causal_attention_mask_for_sdpa
batch_size = 2
num_heads = 32
head_dim = 128
num_tokens_q = 7
num_tokens_kv = num_tokens_q
device= "cuda"
dtype = torch.float16
num_pad_tokens = 3
query = torch.rand(batch_size, num_heads, num_tokens_q, head_dim, dtype=dtype, device=device) - 0.5
key = torch.rand(batch_size, num_heads, num_tokens_q, head_dim, dtype=dtype, device=device) - 0.5
value = torch.rand(batch_size, num_heads, num_tokens_q, head_dim, dtype=dtype, device=device) - 0.5
attn_mask_2d = torch.ones(batch_size, num_tokens_q, dtype=torch.int32, device=device)
attn_mask_2d[1][:num_pad_tokens] = 0 # simulate padding
attn_mask_4d = _prepare_4d_causal_attention_mask_for_sdpa(
attn_mask_2d,
input_shape=(batch_size, num_tokens_q),
inputs_embeds=query, # this is only used to retrieve device, dtype.
past_key_values_length=0,
)
print("attn_mask_4d", attn_mask_4d)
with sdpa_kernel(SDPBackend.EFFICIENT_ATTENTION):
sdpa_out_efficient = torch.nn.functional.scaled_dot_product_attention(
query,
key,
value,
attn_mask=attn_mask_4d
)
with sdpa_kernel(SDPBackend.MATH):
sdpa_out_math = torch.nn.functional.scaled_dot_product_attention(
query,
key,
value,
attn_mask=attn_mask_4d
)
with sdpa_kernel(SDPBackend.MATH):
sdpa_out_math_cpu = torch.nn.functional.scaled_dot_product_attention(
query.cpu(),
key.cpu(),
value.cpu(),
attn_mask=attn_mask_4d.cpu()
)
print("[rocm math vs rocm mem-efficient] Median abs diff, non padded sequence:", (sdpa_out_efficient[0] - sdpa_out_math[0]).abs().median())
print("[rocm math vs rocm mem-efficient] Max abs diff, non padded sequence:", (sdpa_out_efficient[0] - sdpa_out_math[0]).abs().max())
print("[rocm math vs rocm mem-efficient] Median abs diff, padded sequence:", (sdpa_out_efficient[1, :, num_pad_tokens:] - sdpa_out_math[1, :, num_pad_tokens:]).abs().median())
print("[rocm math vs rocm mem-efficient] Max abs diff, padded sequence:", (sdpa_out_efficient[1, :, num_pad_tokens:] - sdpa_out_math[1, :, num_pad_tokens:]).abs().max())
sdpa_out_efficient = sdpa_out_efficient.cpu()
print("\n[cpu math vs rocm mem-efficient] Median abs diff, non padded sequence:", (sdpa_out_math_cpu[0] - sdpa_out_efficient[0]).abs().median())
print("[cpu math vs rocm mem-efficient] Max abs diff, non padded sequence:", (sdpa_out_math_cpu[0] - sdpa_out_efficient[0]).abs().max())
print("[cpu math vs rocm mem-efficient] Median abs diff, padded sequence:", (sdpa_out_math_cpu[1, :, num_pad_tokens:] - sdpa_out_efficient[1, :, num_pad_tokens:]).abs().median())
print("[cpu math vs rocm mem-efficient] Max abs diff, padded sequence:", (sdpa_out_math_cpu[1, :, num_pad_tokens:] - sdpa_out_efficient[1, :, num_pad_tokens:]).abs().max())
sdpa_out_math = sdpa_out_math.cpu()
print("\n[cpu math vs rocm math] Median abs diff, non padded sequence:", (sdpa_out_math_cpu[0] - sdpa_out_math[0]).abs().median())
print("[cpu math vs rocm math] Max abs diff, non padded sequence:", (sdpa_out_math_cpu[0] - sdpa_out_math[0]).abs().max())
print("[cpu math vs rocm math] Median abs diff, padded sequence:", (sdpa_out_math_cpu[1, :, num_pad_tokens:] - sdpa_out_math[1, :, num_pad_tokens:]).abs().median())
print("[cpu math vs rocm math] Max abs diff, padded sequence:", (sdpa_out_math_cpu[1, :, num_pad_tokens:] - sdpa_out_math[1, :, num_pad_tokens:]).abs().max())
```
which gives
```
attn_mask_4d tensor([[[[ 0., -65504., -65504., -65504., -65504., -65504., -65504.],
[ 0., 0., -65504., -65504., -65504., -65504., -65504.],
[ 0., 0., 0., -65504., -65504., -65504., -65504.],
[ 0., 0., 0., 0., -65504., -65504., -65504.],
[ 0., 0., 0., 0., 0., -65504., -65504.],
[ 0., 0., 0., 0., 0., 0., -65504.],
[ 0., 0., 0., 0., 0., 0., 0.]]],
[[[ -0., -0., -0., -0., -0., -0., -0.],
[ -0., -0., -0., -0., -0., -0., -0.],
[ -0., -0., -0., -0., -0., -0., -0.],
[-65504., -65504., -65504., 0., -65504., -65504., -65504.],
[-65504., -65504., -65504., 0., 0., -65504., -65504.],
[-65504., -65504., -65504., 0., 0., 0., -65504.],
[-65504., -65504., -65504., 0., 0., 0., 0.]]]],
device='cuda:0', dtype=torch.float16)
[rocm math vs rocm mem-efficient] Median abs diff, non padded sequence: tensor(0., device='cuda:0', dtype=torch.float16)
[rocm math vs rocm mem-efficient] Max abs diff, non padded sequence: tensor(0.0002, device='cuda:0', dtype=torch.float16)
[rocm math vs rocm mem-efficient] Median abs diff, padded sequence: tensor(0.0991, device='cuda:0', dtype=torch.float16)
[rocm math vs rocm mem-efficient] Max abs diff, padded sequence: tensor(0.6846, device='cuda:0', dtype=torch.float16)
[cpu math vs rocm mem-efficient] Median abs diff, non padded sequence: tensor(0., dtype=torch.float16)
[cpu math vs rocm mem-efficient] Max abs diff, non padded sequence: tensor(0.0002, dtype=torch.float16)
[cpu math vs rocm mem-efficient] Median abs diff, padded sequence: tensor(0.0991, dtype=torch.float16)
[cpu math vs rocm mem-efficient] Max abs diff, padded sequence: tensor(0.6846, dtype=torch.float16)
[cpu math vs rocm math] Median abs diff, non padded sequence: tensor(0., dtype=torch.float16)
[cpu math vs rocm math] Max abs diff, non padded sequence: tensor(6.1035e-05, dtype=torch.float16)
[cpu math vs rocm math] Median abs diff, padded sequence: tensor(0., dtype=torch.float16)
[cpu math vs rocm math] Max abs diff, padded sequence: tensor(6.1035e-05, dtype=torch.float16)
```
As we can see, SDPA on ROCm with mem-efficient attention gives wrong outputs. This causes issues in batched generation in Transformers: https://github.com/huggingface/transformers/issues/30056#issuecomment-2657390613
The root cause is a bug in aotriton 0.8.0 that is shipped with PyTorch 2.6.0+rocm6.2.4.
Using aotrition 0.8.2 (https://github.com/ROCm/aotriton/releases/tag/0.8.2b) fixes this issue, specifically grabbing the asset from https://github.com/ROCm/aotriton/releases/tag/0.8.2b and replacing `torch/lib/aotriton.images/` by the 0.8.2 release `aotriton.images/`.
Diff between math and mem-efficient is then much more reasonable:
```
[rocm math vs rocm mem-efficient] Median abs diff, non padded sequence: tensor(0., device='cuda:0', dtype=torch.float16)
[rocm math vs rocm mem-efficient] Max abs diff, non padded sequence: tensor(0.0002, device='cuda:0', dtype=torch.float16)
[rocm math vs rocm mem-efficient] Median abs diff, padded sequence: tensor(0., device='cuda:0', dtype=torch.float16)
[rocm math vs rocm mem-efficient] Max abs diff, padded sequence: tensor(0.0002, device='cuda:0', dtype=torch.float16)
[cpu math vs rocm mem-efficient] Median abs diff, non padded sequence: tensor(0., dtype=torch.float16)
[cpu math vs rocm mem-efficient] Max abs diff, non padded sequence: tensor(0.0002, dtype=torch.float16)
[cpu math vs rocm mem-efficient] Median abs diff, padded sequence: tensor(0., dtype=torch.float16)
[cpu math vs rocm mem-efficient] Max abs diff, padded sequence: tensor(0.0002, dtype=torch.float16)
[cpu math vs rocm math] Median abs diff, non padded sequence: tensor(0., dtype=torch.float16)
[cpu math vs rocm math] Max abs diff, non padded sequence: tensor(0.0001, dtype=torch.float16)
[cpu math vs rocm math] Median abs diff, padded sequence: tensor(0., dtype=torch.float16)
[cpu math vs rocm math] Max abs diff, padded sequence: tensor(4.7684e-07, dtype=torch.float16)
```
Using aotriton 0.8.2 in a torch patch release might be considered? cc @jeffdaily @sunway513 @jithunnair-amd @pruthvistony @ROCmSupport @dllehr-amd @jataylo @hongxiayang @naromero77amd @xinyazhang @atalman
Thank you!
### Versions
```
PyTorch version: 2.6.0+rocm6.2.4
Is debug build: False
CUDA used to build PyTorch: N/A
ROCM used to build PyTorch: 6.2.41134-65d174c3e
OS: Ubuntu 24.04 LTS (x86_64)
GCC version: (Ubuntu 13.3.0-6ubuntu2~24.04) 13.3.0
Clang version: Could not collect
CMake version: version 3.28.3
Libc version: glibc-2.39
Python version: 3.10.16 (main, Dec 11 2024, 16:24:50) [GCC 11.2.0] (64-bit runtime)
Python platform: Linux-6.8.0-51-generic-x86_64-with-glibc2.39
Is CUDA available: True
CUDA runtime version: Could not collect
CUDA_MODULE_LOADING set to: LAZY
GPU models and configuration: AMD Instinct MI250X/MI250 (gfx90a:sramecc+:xnack-)
Nvidia driver version: Could not collect
cuDNN version: Could not collect
HIP runtime version: 6.2.41134
MIOpen runtime version: 3.2.0
Is XNNPACK available: True
CPU:
Architecture: x86_64
CPU op-mode(s): 32-bit, 64-bit
Address sizes: 48 bits physical, 48 bits virtual
Byte Order: Little Endian
CPU(s): 32
On-line CPU(s) list: 0-31
Vendor ID: AuthenticAMD
Model name: AMD EPYC 73F3 16-Core Processor
CPU family: 25
Model: 1
Thread(s) per core: 1
Core(s) per socket: 16
Socket(s): 2
Stepping: 1
Frequency boost: enabled
CPU(s) scaling MHz: 61%
CPU max MHz: 4036.6211
CPU min MHz: 1500.0000
BogoMIPS: 6987.05
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 pcid 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 erms invpcid cqm rdt_a rdseed adx smap clflushopt clwb sha_ni xsaveopt xsavec xgetbv1 xsaves cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local user_shstk clzero irperf xsaveerptr rdpru wbnoinvd amd_ppin brs arat npt lbrv svm_lock nrip_save tsc_scale vmcb_clean flushbyasid decodeassists pausefilter pfthreshold v_vmsave_vmload vgif v_spec_ctrl umip pku ospke vaes vpclmulqdq rdpid overflow_recov succor smca fsrm debug_swap
Virtualization: AMD-V
L1d cache: 1 MiB (32 instances)
L1i cache: 1 MiB (32 instances)
L2 cache: 16 MiB (32 instances)
L3 cache: 512 MiB (16 instances)
NUMA node(s): 2
NUMA node0 CPU(s): 0-15
NUMA node1 CPU(s): 16-31
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 Reg file data sampling: Not affected
Vulnerability Retbleed: Not affected
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; IBRS_FW; STIBP disabled; RSB filling; PBRSB-eIBRS Not affected; BHI Not affected
Vulnerability Srbds: Not affected
Vulnerability Tsx async abort: Not affected
Versions of relevant libraries:
[pip3] numpy==2.2.2
[pip3] onnx==1.17.0
[pip3] onnxruntime==1.20.1
[pip3] onnxruntime_extensions==0.13.0
[pip3] onnxruntime-genai==0.5.2
[pip3] onnxsim==0.4.36
[pip3] pytorch-triton-rocm==3.2.0
[pip3] torch==2.6.0+rocm6.2.4
[pip3] torchaudio==2.6.0+rocm6.2.4
[pip3] torchvision==0.21.0+rocm6.2.4
[conda] Could not collect
```