Repository: pytorch
Issue: Flex Attention not support score_mod with gradients
Labels: triaged,oncall: pt2,module: higher order operators,module: pt2-dispatcher,module: flex attention

### 🐛 Describe the bug

`Flex Attention` does not support `score_mod with gradients`, making it impossible to define a learnable score_mod for the dynamic mask attention variants.
```python
import torch
from torch.nn.attention.flex_attention import flex_attention

A = torch.nn.Parameter(torch.zeros(1))

query = torch.randn(1, 1, 1, 32)
key = torch.randn(1, 1, 1, 32)
value = torch.randn(1, 1, 1, 32)
dt = torch.randn(1, 1, 1)

dynamic_mask = torch.exp(A * dt).transpose(-1, -2)
attn_mask = dynamic_mask[:, :, None, :]

def dynamic_mod(score, batch, head, q_idx, kv_idx):
    score = score + attn_mask[batch][head][0][kv_idx]
    return score

attn_output = flex_attention(
    query=query,
    key=key,
    value=value,
    score_mod=dynamic_mod,
)
print(attn_output)
```

```
Traceback (most recent call last):
  File "e:\Doge\bug.py", line 22, in <module>
    attn_output = flex_attention(
  File "E:\conda\envs\doge\lib\site-packages\torch\nn\attention\flex_attention.py", line 1038, in flex_attention
    out, lse = torch.compile(
  File "E:\conda\envs\doge\lib\site-packages\torch\_dynamo\eval_frame.py", line 465, in _fn
    return fn(*args, **kwargs)
  File "E:\conda\envs\doge\lib\site-packages\torch\nn\attention\flex_attention.py", line 1032, in _flex_attention_hop_wrapper
    def _flex_attention_hop_wrapper(*args, **kwargs):
  File "E:\conda\envs\doge\lib\site-packages\torch\_dynamo\eval_frame.py", line 632, in _fn
    return fn(*args, **kwargs)
  File "<eval_with_key>.3", line 24, in forward
  File "E:\conda\envs\doge\lib\site-packages\torch\_higher_order_ops\flex_attention.py", line 109, in __call__
    return super().__call__(
  File "E:\conda\envs\doge\lib\site-packages\torch\_ops.py", line 433, in __call__
    return wrapper()
  File "E:\conda\envs\doge\lib\site-packages\torch\_dynamo\eval_frame.py", line 632, in _fn
    return fn(*args, **kwargs)
  File "E:\conda\envs\doge\lib\site-packages\torch\_ops.py", line 429, in wrapper
    return self.dispatch(
  File "E:\conda\envs\doge\lib\site-packages\torch\_ops.py", line 412, in dispatch
    return kernel(*args, **kwargs)
  File "E:\conda\envs\doge\lib\site-packages\torch\_higher_order_ops\flex_attention.py", line 703, in flex_attention_autograd
    out, logsumexp = FlexAttentionAutogradOp.apply(
  File "E:\conda\envs\doge\lib\site-packages\torch\autograd\function.py", line 575, in apply
    return super().apply(*args, **kwargs)  # type: ignore[misc]
  File "E:\conda\envs\doge\lib\site-packages\torch\_higher_order_ops\flex_attention.py", line 578, in forward
    assert (
AssertionError: Captured buffers that require grad are not yet supported.
```

### Versions

Collecting environment information...
PyTorch version: 2.6.0a0+df5bbc09d1.nv24.12
Is debug build: False
CUDA used to build PyTorch: 12.6
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: version 3.31.1
Libc version: glibc-2.39

Python version: 3.12.3 (main, Nov  6 2024, 18:32:19) [GCC 13.2.0] (64-bit runtime)
Python platform: Linux-5.15.153.1-microsoft-standard-WSL2-x86_64-with-glibc2.39
Is CUDA available: True
CUDA runtime version: 12.6.85
CUDA_MODULE_LOADING set to: LAZY
GPU models and configuration: GPU 0: NVIDIA GeForce RTX 4090
Nvidia driver version: 566.36
cuDNN version: Probably one of the following:
/usr/lib/x86_64-linux-gnu/libcudnn.so.9.6.0
/usr/lib/x86_64-linux-gnu/libcudnn_adv.so.9.6.0
/usr/lib/x86_64-linux-gnu/libcudnn_cnn.so.9.6.0
/usr/lib/x86_64-linux-gnu/libcudnn_engines_precompiled.so.9.6.0
/usr/lib/x86_64-linux-gnu/libcudnn_engines_runtime_compiled.so.9.6.0
/usr/lib/x86_64-linux-gnu/libcudnn_graph.so.9.6.0
/usr/lib/x86_64-linux-gnu/libcudnn_heuristic.so.9.6.0
/usr/lib/x86_64-linux-gnu/libcudnn_ops.so.9.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):                             32
On-line CPU(s) list:                0-31
Vendor ID:                          GenuineIntel
Model name:                         13th Gen Intel(R) Core(TM) i9-13900KS
CPU family:                         6
Model:                              183
Thread(s) per core:                 2
Core(s) per socket:                 16
Socket(s):                          1
Stepping:                           1
BogoMIPS:                           6374.42
Flags:                              fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ss ht syscall nx pdpe1gb rdtscp lm constant_tsc rep_good nopl xtopology tsc_reliable nonstop_tsc cpuid pni pclmulqdq vmx ssse3 fma cx16 sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand hypervisor lahf_lm abm 3dnowprefetch ssbd ibrs ibpb stibp ibrs_enhanced tpr_shadow vnmi ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid rdseed adx smap clflushopt clwb sha_ni xsaveopt xsavec xgetbv1 xsaves avx_vnni umip waitpkg gfni vaes vpclmulqdq rdpid movdiri movdir64b fsrm md_clear serialize flush_l1d arch_capabilities
Virtualization:                     VT-x
Hypervisor vendor:                  Microsoft
Virtualization type:                full
L1d cache:                          768 KiB (16 instances)
L1i cache:                          512 KiB (16 instances)
L2 cache:                           32 MiB (16 instances)
L3 cache:                           36 MiB (1 instance)
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; Enhanced IBRS
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] mypy-extensions==1.0.0
[pip3] numpy==1.26.4
[pip3] nvidia-cudnn-frontend==1.8.0
[pip3] nvtx==0.2.5
[pip3] onnx==1.17.0
[pip3] optree==0.13.1
[pip3] pynvjitlink==0.3.0
[pip3] pytorch-triton==3.0.0+72734f086
[pip3] torch==2.6.0a0+df5bbc09d1.nv24.12
[pip3] torch_tensorrt==2.6.0a0
[pip3] torchprofile==0.0.4
[pip3] torchvision==0.20.0a0
[conda] Could not collect

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