Repository: pytorch
Issue: 2.4.0: sdpa disallows batch-of-0 in Flash (default backend) and cuDNN.
Labels: module: cudnn,triaged,module: sdpa

### 🐛 Describe the bug

I'm trying to do attention on a batch-of-zero, because my program uses a static graph and I rely on zero-batching (index_select zero-batch of inputs, index_add zero-batch of outputs) to toggle functionality without adding branches to the logic.

But attention is failing on a batch-of-zero:

```python
import torch
from torch.nn.functional import scaled_dot_product_attention

device = torch.device('cuda')
dtype = torch.float16

batch = 0
q_heads = kv_heads = 10
q_tokens = 3952
kv_tokens = 16
head_dim = 64
q = torch.zeros(batch, q_heads, q_tokens, head_dim, device=device, dtype=dtype)
k = torch.zeros(batch, kv_heads, kv_tokens, head_dim, device=device, dtype=dtype)
v = torch.zeros(batch, kv_heads, kv_tokens, head_dim, device=device, dtype=dtype)

scaled_dot_product_attention(q, k, v)
```

This is a _backend-specific_ problem.  
Math backend is fine. Memory-efficient backend is fine.  

But the default backend in torch 2.4.0 is Flash. Flash refuses to run:  
```
RuntimeError: batch size must be positive
```

That assertion probably comes from here:  
https://github.com/pytorch/pytorch/blob/d6368985af9f670db43b9a644f878d4e57e67b6b/aten/src/ATen/native/transformers/cuda/flash_attn/flash_api.cpp#L394

If I enable cuDNN backend via `TORCH_CUDNN_SDPA_ENABLED=1` env var and context manager:

```python
from torch.nn.attention import SDPBackend, sdpa_kernel
with sdpa_kernel(SDPBackend.CUDNN_ATTENTION):
    scaled_dot_product_attention(q, k, v)
```

cuDNN fails too, because it dislikes cross-attention. But it'd be better if it recognised batch-of-zero could be treated as a special case.

```
UserWarning: Query tensor was not in cuDNN-supported packed QKV layout[2529280, 252928, 64, 1] (Triggered internally at /build/pytorch/aten/src/ATen/native/transformers/cuda/sdp_utils.cpp:410.)
  scaled_dot_product_attention(q, k, v)
UserWarning: Key tensor was not in cuDNN-supported packed QKV layout[10240, 1024, 64, 1] (Triggered internally at /build/pytorch/aten/src/ATen/native/transformers/cuda/sdp_utils.cpp:413.)
  scaled_dot_product_attention(q, k, v)
UserWarning: Value tensor was not in cuDNN-supported packed QKV layout[10240, 1024, 64, 1] (Triggered internally at /build/pytorch/aten/src/ATen/native/transformers/cuda/sdp_utils.cpp:416.)
  scaled_dot_product_attention(q, k, v)
UserWarning: Query tensor was not in cuDNN-supported unpacked QKV layout[2529280, 252928, 64, 1] (Triggered internally at /build/pytorch/aten/src/ATen/native/transformers/cuda/sdp_utils.cpp:421.)
  scaled_dot_product_attention(q, k, v)
UserWarning: Key tensor was not in cuDNN-supported unpacked QKV layout[10240, 1024, 64, 1] (Triggered internally at /build/pytorch/aten/src/ATen/native/transformers/cuda/sdp_utils.cpp:424.)
  scaled_dot_product_attention(q, k, v)
UserWarning: Value tensor was not in cuDNN-supported unpacked QKV layout[10240, 1024, 64, 1] (Triggered internally at /build/pytorch/aten/src/ATen/native/transformers/cuda/sdp_utils.cpp:427.)
  scaled_dot_product_attention(q, k, v)
```

It's tempting to say that in this situation we should just select the MATH kernel.

But I have one worry: I use torch jit to trace the model into a static graph (see [stable-fast](https://github.com/chengzeyi/stable-fast)). If we fallback to MATH kernel for batch-of-zero: does this mean that the graph will always pick MATH kernel, even when generalizing to larger batch sizes? If that's the case: it'd be better to find a solution that fixes the Flash backend (i.e. add support for zero-batching).

### Versions

```
Collecting environment information...
PyTorch version: 2.4.0
Is debug build: False
CUDA used to build PyTorch: 12.4
ROCM used to build PyTorch: N/A

OS: Ubuntu 22.04.4 LTS (x86_64)
GCC version: (Ubuntu 11.4.0-1ubuntu1~22.04) 11.4.0
Clang version: Could not collect
CMake version: version 3.30.1
Libc version: glibc-2.35

Python version: 3.10.12 (main, Mar 22 2024, 16:50:05) [GCC 11.4.0] (64-bit runtime)
Python platform: Linux-6.5.13-650-3434-22042-coreweave-1-x86_64-with-glibc2.35
Is CUDA available: True
CUDA runtime version: 12.4.131
CUDA_MODULE_LOADING set to: LAZY
GPU models and configuration: GPU 0: NVIDIA A40
Nvidia driver version: 535.177
cuDNN version: Probably one of the following:
/usr/lib/x86_64-linux-gnu/libcudnn.so.9.1.0
/usr/lib/x86_64-linux-gnu/libcudnn_adv.so.9.1.0
/usr/lib/x86_64-linux-gnu/libcudnn_cnn.so.9.1.0
/usr/lib/x86_64-linux-gnu/libcudnn_engines_precompiled.so.9.1.0
/usr/lib/x86_64-linux-gnu/libcudnn_engines_runtime_compiled.so.9.1.0
/usr/lib/x86_64-linux-gnu/libcudnn_graph.so.9.1.0
/usr/lib/x86_64-linux-gnu/libcudnn_heuristic.so.9.1.0
/usr/lib/x86_64-linux-gnu/libcudnn_ops.so.9.1.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:                      48 bits physical, 48 bits virtual
Byte Order:                         Little Endian
CPU(s):                             96
On-line CPU(s) list:                0-95
Vendor ID:                          AuthenticAMD
Model name:                         AMD EPYC 7413 24-Core Processor
CPU family:                         25
Model:                              1
Thread(s) per core:                 2
Core(s) per socket:                 24
Socket(s):                          2
Stepping:                           1
Frequency boost:                    enabled
CPU max MHz:                        3630.8101
CPU min MHz:                        1500.0000
BogoMIPS:                           5299.87
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 invpcid_single 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 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
Virtualization:                     AMD-V
L1d cache:                          1.5 MiB (48 instances)
L1i cache:                          1.5 MiB (48 instances)
L2 cache:                           24 MiB (48 instances)
L3 cache:                           256 MiB (8 instances)
NUMA node(s):                       8
NUMA node0 CPU(s):                  0-5,48-53
NUMA node1 CPU(s):                  6-11,54-59
NUMA node2 CPU(s):                  12-17,60-65
NUMA node3 CPU(s):                  18-23,66-71
NUMA node4 CPU(s):                  24-29,72-77
NUMA node5 CPU(s):                  30-35,78-83
NUMA node6 CPU(s):                  36-41,84-89
NUMA node7 CPU(s):                  42-47,90-95
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:             Not affected
Vulnerability Spec rstack overflow: Vulnerable: Safe RET, no microcode
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 always-on; RSB filling; PBRSB-eIBRS Not affected; BHI Not affected
Vulnerability Srbds:                Not affected
Vulnerability Tsx async abort:      Not affected

Versions of relevant libraries:
[pip3] clip-anytorch==2.6.0
[pip3] dctorch==0.1.2
[pip3] numpy==1.26.4
[pip3] open_clip_torch==2.26.1
[pip3] pytorch-lightning==2.3.3
[pip3] torch==2.4.0
[pip3] torchaudio==2.4.0
[pip3] torchdiffeq==0.2.4
[pip3] torchmetrics==1.4.0.post0
[pip3] torchsde==0.2.6
[pip3] torchvision==0.19.0
[pip3] triton==3.0.0
[pip3] welford-torch==0.2.4
[conda] Could not collect
```

cc @csarofeen @ptrblck @xwang233 @eqy @drisspg @mikaylagawarecki