Backward pass for Nested Tensors using flash attention in sdpa fails
Labels: triaged, module: nestedtensor, oncall: transformer/mha, module: multi-headed-attention

### 🐛 Describe the bug

I am trying to use Flash Attention in PyTorch using torch.backends.cuda.sdp_kernel and nested tensors. Here a minimal example:

```python
import random
import torch
import math

class TransformerModel(torch.nn.Module):
    def __init__(self, num_layers, model_dim, ff_dim, num_heads):
        super().__init__()
        self.layers = torch.nn.ModuleList([FastTransformerLayer(model_dim, ff_dim, num_heads) for i in range(num_layers)])

    def forward(self, x):
        for l in self.layers:
            x = l(x)
        x = x.to_padded_tensor(padding=0)
        lens = (x!=0).sum(axis=1)[:,0]
        mean_x = x.sum(axis=1)/lens[:,None]

        return mean_x

class FastMHA(torch.nn.Module):
    def __init__(self, model_dim, num_heads):
        super().__init__()
        self.Q = torch.nn.Linear(model_dim, model_dim)
        self.K = torch.nn.Linear(model_dim, model_dim)
        self.V = torch.nn.Linear(model_dim, model_dim)
        self.O = torch.nn.Linear(model_dim, model_dim)
        self.num_heads = num_heads
        self.head_dim = model_dim // num_heads

    def forward(self, q, k, v):
        bsz, dim = q.size(0), q.size(2)
        q,k,v = self.Q(q), self.K(k), self.V(v)
        q = q.view(bsz,-1,self.num_heads,self.head_dim).transpose(1,2)
        k = k.view(bsz,-1,self.num_heads,self.head_dim).transpose(1,2)
        v = v.view(bsz,-1,self.num_heads,self.head_dim).transpose(1,2)

        with torch.backends.cuda.sdp_kernel(enable_flash=True, enable_math=False, enable_mem_efficient=False):
            attn_output=torch.nn.functional.scaled_dot_product_attention(q,k,v)
        attn_output = attn_output.transpose(1,2).view(bsz,-1,dim)
        attn_output = self.O(attn_output)

        return attn_output

class FastTransformerLayer(torch.nn.Module):
    def __init__(self, model_dim, ff_dim, num_heads):
        super().__init__()
        self.mha = FastMHA(model_dim, num_heads)
        self.ff = torch.nn.Sequential(torch.nn.Linear(model_dim, ff_dim), torch.nn.ReLU(), torch.nn.Linear(ff_dim, model_dim))
        self.ln1 = torch.nn.LayerNorm(model_dim)
        self.ln2 = torch.nn.LayerNorm(model_dim)

    def forward(self, x):
        x_att = self.mha(x, x, x)
        x = self.ln1(x + x_att)
        x_ff = self.ff(x)
        x = self.ln2(x + x_ff)

        return x

D=768
BS=16
MIN_SEQLEN=50
MAX_SEQLEN=300
FFDIM=2048
N_STEPS=1000

model = TransformerModel(num_layers=4, model_dim=D, ff_dim=FFDIM, num_heads=12)
model.to(device='cuda:0', dtype=torch.float16)
criterion = torch.nn.MSELoss(reduction='sum')
optimizer = torch.optim.AdamW(model.parameters(),
                                lr=0.0001,
                                betas=(0.9,0.95),
                                weight_decay=0.05)
for t in range(N_STEPS):
    xlens = torch.randint(low=MIN_SEQLEN,high=MAX_SEQLEN,size=(BS,),device='cuda:0')
    x = torch.nested.nested_tensor([torch.randn((xl,D)) for xl in xlens]).to(device='cuda:0',dtype=torch.float16)
    y = torch.randn((BS,D), device=x.device, dtype=x.dtype)
    y_pred = model(x)

    loss = criterion(y_pred, y)
    print(t, loss.item())

    optimizer.zero_grad()
    loss.backward()
    optimizer.step()
```

This is the error I get:

```
Traceback (most recent call last):                                                                                        
  File "minimal_train.py", line 84, in <module>                                                                           
    loss.backward()                                                                                                       
  File "/usr/local/lib/python3.8/dist-packages/torch/_tensor.py", line 492, in backward                                
    torch.autograd.backward(                                                                                              
  File "/usr/local/lib/python3.8/dist-packages/torch/autograd/__init__.py", line 251, in backward                
    Variable._execution_engine.run_backward(  # Calls into the C++ engine to run the backward pass      
NotImplementedError: Could not run 'aten::_scaled_dot_product_flash_attention_backward' with arguments from the 'NestedTen
sorCUDA' backend. This could be because the operator doesn't exist for this backend, or was omitted during the selective/c
ustom build process (if using custom build). If you are a Facebook employee using PyTorch on mobile, please visit https://
fburl.com/ptmfixes for possible resolutions. 'aten::_scaled_dot_product_flash_attention_backward' is only available for th
ese backends: [CPU, CUDA, Meta, BackendSelect, Python, FuncTorchDynamicLayerBackMode, Functionalize, Named, Conjugate, Neg
ative, ZeroTensor, ADInplaceOrView, AutogradOther, AutogradCPU, AutogradCUDA, AutogradHIP, AutogradXLA, AutogradMPS, Autog
radIPU, AutogradXPU, AutogradHPU, AutogradVE, AutogradLazy, AutogradMTIA, AutogradPrivateUse1, AutogradPrivateUse2, Autogr
adPrivateUse3, AutogradMeta, AutogradNestedTensor, Tracer, AutocastCPU, AutocastCUDA, FuncTorchBatched, FuncTorchVmapMode,
 Batched, VmapMode, FuncTorchGradWrapper, PythonTLSSnapshot, FuncTorchDynamicLayerFrontMode, PreDispatch, PythonDispatcher
].

CPU: registered at aten/src/ATen/RegisterCPU.cpp:31188 [kernel]
CUDA: registered at aten/src/ATen/RegisterCUDA.cpp:44143 [kernel]
Meta: registered at /dev/null:219 [kernel]
BackendSelect: fallthrough registered at ../aten/src/ATen/core/BackendSelectFallbackKernel.cpp:3 [backend fallback]
Python: registered at ../aten/src/ATen/core/PythonFallbackKernel.cpp:153 [backend fallback]
FuncTorchDynamicLayerBackMode: registered at ../aten/src/ATen/functorch/DynamicLayer.cpp:498 [backend fallback]
Functionalize: registered at ../aten/src/ATen/FunctionalizeFallbackKernel.cpp:290 [backend fallback]                      
Named: registered at ../aten/src/ATen/core/NamedRegistrations.cpp:7 [backend fallback]                                    
Conjugate: registered at ../aten/src/ATen/ConjugateFallback.cpp:17 [backend fallback]
Negative: registered at ../aten/src/ATen/native/NegateFallback.cpp:19 [backend fallback]
ZeroTensor: registered at ../aten/src/ATen/ZeroTensorFallback.cpp:86 [backend fallback]
ADInplaceOrView: fallthrough registered at ../aten/src/ATen/core/VariableFallbackKernel.cpp:86 [backend fallback]
AutogradOther: registered at ../torch/csrc/autograd/generated/VariableType_4.cpp:16976 [autograd kernel]
AutogradCPU: registered at ../torch/csrc/autograd/generated/VariableType_4.cpp:16976 [autograd kernel]
AutogradCUDA: registered at ../torch/csrc/autograd/generated/VariableType_4.cpp:16976 [autograd kernel]
AutogradHIP: registered at ../torch/csrc/autograd/generated/VariableType_4.cpp:16976 [autograd kernel]
AutogradXLA: registered at ../torch/csrc/autograd/generated/VariableType_4.cpp:16976 [autograd kernel]
AutogradMPS: registered at ../torch/csrc/autograd/generated/VariableType_4.cpp:16976 [autograd kernel]
AutogradIPU: registered at ../torch/csrc/autograd/generated/VariableType_4.cpp:16976 [autograd kernel]
AutogradXPU: registered at ../torch/csrc/autograd/generated/VariableType_4.cpp:16976 [autograd kernel]
AutogradHPU: registered at ../torch/csrc/autograd/generated/VariableType_4.cpp:16976 [autograd kernel]
AutogradVE: registered at ../torch/csrc/autograd/generated/VariableType_4.cpp:16976 [autograd kernel]
AutogradLazy: registered at ../torch/csrc/autograd/generated/VariableType_4.cpp:16976 [autograd kernel]
AutogradMTIA: registered at ../torch/csrc/autograd/generated/VariableType_4.cpp:16976 [autograd kernel]
AutogradPrivateUse1: registered at ../torch/csrc/autograd/generated/VariableType_4.cpp:16976 [autograd kernel]
AutogradPrivateUse2: registered at ../torch/csrc/autograd/generated/VariableType_4.cpp:16976 [autograd kernel]
AutogradPrivateUse3: registered at ../torch/csrc/autograd/generated/VariableType_4.cpp:16976 [autograd kernel]
AutogradMeta: registered at ../torch/csrc/autograd/generated/VariableType_4.cpp:16976 [autograd kernel]
AutogradNestedTensor: registered at ../torch/csrc/autograd/generated/VariableType_4.cpp:16976 [autograd kernel]
Tracer: registered at ../torch/csrc/autograd/generated/TraceType_4.cpp:13056 [kernel]
AutocastCPU: fallthrough registered at ../aten/src/ATen/autocast_mode.cpp:382 [backend fallback]
AutocastCUDA: fallthrough registered at ../aten/src/ATen/autocast_mode.cpp:249 [backend fallback]
FuncTorchBatched: registered at ../aten/src/ATen/functorch/LegacyBatchingRegistrations.cpp:710 [backend fallback]
FuncTorchVmapMode: fallthrough registered at ../aten/src/ATen/functorch/VmapModeRegistrations.cpp:28 [backend fallback]
Batched: registered at ../aten/src/ATen/LegacyBatchingRegistrations.cpp:1075 [backend fallback]
VmapMode: fallthrough registered at ../aten/src/ATen/VmapModeRegistrations.cpp:33 [backend fallback]
FuncTorchGradWrapper: registered at ../aten/src/ATen/functorch/TensorWrapper.cpp:203 [backend fallback]
PythonTLSSnapshot: registered at ../aten/src/ATen/core/PythonFallbackKernel.cpp:161 [backend fallback]
FuncTorchDynamicLayerFrontMode: registered at ../aten/src/ATen/functorch/DynamicLayer.cpp:494 [backend fallback]
PreDispatch: registered at ../aten/src/ATen/core/PythonFallbackKernel.cpp:165 [backend fallback]
PythonDispatcher: registered at ../aten/src/ATen/core/PythonFallbackKernel.cpp:157 [backend fallback]
```


### Versions

Collecting environment information...                                                                                     
PyTorch version: 2.1.0+cu121                                                                                              
Is debug build: False                                                                                                     CUDA used to build PyTorch: 12.1                                                                                          ROCM used to build PyTorch: N/A                                                                                                                                                                                                                     OS: Ubuntu 20.04.6 LTS (x86_64)                                                                                           GCC version: (Ubuntu 9.4.0-1ubuntu1~20.04.1) 9.4.0                                                                        Clang version: Could not collect                                                                                          CMake version: version 3.27.5                                                                                             
Libc version: glibc-2.31                                                                                                  
                                                                                                                          
Python version: 3.8.10 (default, May 26 2023, 14:05:08)  [GCC 9.4.0] (64-bit runtime)          
Python platform: Linux-5.15.0-84-generic-x86_64-with-glibc2.29                                      
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 3090                                                                                            
GPU 1: NVIDIA GeForce RTX 3090                                                                                            
                                                                                                                          
Nvidia driver version: 525.125.06                                                                                         
cuDNN version: Probably one of the following:                                                                    [46/1972]
/usr/lib/x86_64-linux-gnu/libcudnn.so.8.5.0
/usr/lib/x86_64-linux-gnu/libcudnn_adv_infer.so.8.5.0
/usr/lib/x86_64-linux-gnu/libcudnn_adv_train.so.8.5.0
/usr/lib/x86_64-linux-gnu/libcudnn_cnn_infer.so.8.5.0
/usr/lib/x86_64-linux-gnu/libcudnn_cnn_train.so.8.5.0
/usr/lib/x86_64-linux-gnu/libcudnn_ops_infer.so.8.5.0
/usr/lib/x86_64-linux-gnu/libcudnn_ops_train.so.8.5.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
Byte Order:                         Little Endian
Address sizes:                      43 bits physical, 48 bits virtual
CPU(s):                             48
On-line CPU(s) list:                0-47
Thread(s) per core:                 2
Core(s) per socket:                 24
Socket(s):                          1
NUMA node(s):                       1
Vendor ID:                          AuthenticAMD
CPU family:                         23
Model:                              49
Model name:                         AMD Ryzen Threadripper 3960X 24-Core Processor                               [20/1972]
Stepping:                           0
Frequency boost:                    enabled
CPU MHz:                            2200.000
CPU max MHz:                        3800.0000
CPU min MHz:                        2200.0000
BogoMIPS:                           7586.00
Virtualization:                     AMD-V
L1d cache:                          768 KiB
L1i cache:                          768 KiB
L2 cache:                           12 MiB
L3 cache:                           128 MiB
NUMA node0 CPU(s):                  0-47
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 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; Retpolines, IBPB conditional, STIBP always-on, RSB filling, PBRSB-eIBRS No
t 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 fx
sr sse sse2 ht syscall nx mmxext fxsr_opt pdpe1gb rdtscp lm constant_tsc rep_good nopl nonstop_tsc cpuid extd_apicid aperf
mperf rapl pni pclmulqdq monitor ssse3 fma cx16 sse4_1 sse4_2 movbe popcnt aes xsave avx f16c rdrand lahf_lm cmp_legacy sv
m extapic cr8_legacy abm sse4a misalignsse 3dnowprefetch osvw ibs skinit wdt tce topoext perfctr_core perfctr_nb bpext per
fctr_llc mwaitx cpb cat_l3 cdp_l3 hw_pstate ssbd mba 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_local clzero irperf xsavee
rptr rdpru wbnoinvd arat npt lbrv svm_lock nrip_save tsc_scale vmcb_clean flushbyasid decodeassists pausefilter pfthreshol
d avic v_vmsave_vmload vgif v_spec_ctrl umip rdpid overflow_recov succor smca sme sev sev_es

Versions of relevant libraries:
[pip3] numpy==1.23.5
[pip3] pytorch-lightning==2.0.9.post0
[pip3] torch==2.1.0
[pip3] torchaudio==2.1.0
[pip3] torchinfo==1.8.0
[pip3] torchmetrics==1.1.2
[pip3] torchvision==0.15.2
[pip3] triton==2.1.0
[conda] Could not collect

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