Repository: pytorch
Issue: MultiHeadAttention, fast path broken with `bias=False` or uneven number of heads
Labels: module: nn,triaged

### 🐛 Describe the bug

Certain configurations of `MultiHeadAttention` fail during inference, because of issues in the fast execution path. These need to be added to the fast path, or else handled gracefully (i.e. revert to slow path). 

The following configurations break:
1. `batch_first=True`, `bias=False`
2. `batch_first=True`, `num_heads` is odd, and `key_padding_mask` provided

### Example 1
```python
import torch
import torch.nn as nn
import contextlib

B, L, F = 8, 100, 128
nb_heads = 8
batch_first = True
bias = False
fast_path = True
use_pad_mask = False

mha = nn.MultiheadAttention(
    embed_dim=F,
    num_heads=nb_heads,
    batch_first=batch_first,
    bias=bias
).cuda()
mha.eval()

ctx = torch.no_grad if fast_path else contextlib.nullcontext
with ctx():
    x = torch.randn(B, L, F).cuda()
    if not batch_first:
        x = x.transpose(0, 1)
        
    pad_mask = None
    if use_pad_mask:
        pad_mask = torch.zeros((B, L), dtype=torch.bool).cuda()

    mha(query=x, key=x, value=x, key_padding_mask=pad_mask)
```

Yields,
```
File ~/miniconda3/envs/py39/lib/python3.9/site-packages/torch/nn/modules/activation.py:1144, in MultiheadAttention.forward(self, query, key, value, key_padding_mask, need_weights, attn_mask, average_attn_weights, is_causal)
   1141     if not why_not_fast_path:
   1142         merged_mask, mask_type = self.merge_masks(attn_mask, key_padding_mask, query)
-> 1144         return torch._native_multi_head_attention(
   1145             query,
   1146             key,
   1147             value,
   1148             self.embed_dim,
   1149             self.num_heads,
   1150             self.in_proj_weight,
   1151             self.in_proj_bias,
   1152             self.out_proj.weight,
   1153             self.out_proj.bias,
   1154             merged_mask,
   1155             need_weights,
   1156             average_attn_weights,
   1157             mask_type)
   1159 any_nested = query.is_nested or key.is_nested or value.is_nested
   1160 assert not any_nested, ("MultiheadAttention does not support NestedTensor outside of its fast path. " +
   1161                         f"The fast path was not hit because {why_not_fast_path}")

TypeError: _native_multi_head_attention(): argument 'qkv_bias' (position 7) must be Tensor, not NoneType
```

### Example 2
```python
B, L, F = 8, 100, 128
nb_heads = 1
batch_first = True
bias = True
fast_path = True
use_pad_mask = True
...
```

Yields,
```
...
RuntimeError: Only support when num_heads is even in transformer
```

### Versions

PyTorch version: 2.0.0
Is debug build: False
CUDA used to build PyTorch: 11.8
ROCM used to build PyTorch: N/A

OS: Ubuntu 20.04.5 LTS (x86_64)
GCC version: (Ubuntu 9.4.0-1ubuntu1~20.04.1) 9.4.0
Clang version: Could not collect
CMake version: Could not collect
Libc version: glibc-2.31

Python version: 3.9.16 (main, Mar  8 2023, 14:00:05)  [GCC 11.2.0] (64-bit runtime)
Python platform: Linux-5.15.0-1029-gcp-x86_64-with-glibc2.31
Is CUDA available: True
CUDA runtime version: Could not collect
CUDA_MODULE_LOADING set to: LAZY
GPU models and configuration: 
GPU 0: NVIDIA A100-SXM4-40GB
GPU 1: NVIDIA A100-SXM4-40GB
GPU 2: NVIDIA A100-SXM4-40GB
GPU 3: NVIDIA A100-SXM4-40GB

Nvidia driver version: 495.29.05
cuDNN version: Probably one of the following:
/usr/local/cuda-11.5/targets/x86_64-linux/lib/libcudnn.so.8.3.1
/usr/local/cuda-11.5/targets/x86_64-linux/lib/libcudnn_adv_infer.so.8.3.1
/usr/local/cuda-11.5/targets/x86_64-linux/lib/libcudnn_adv_train.so.8.3.1
/usr/local/cuda-11.5/targets/x86_64-linux/lib/libcudnn_cnn_infer.so.8.3.1
/usr/local/cuda-11.5/targets/x86_64-linux/lib/libcudnn_cnn_train.so.8.3.1
/usr/local/cuda-11.5/targets/x86_64-linux/lib/libcudnn_ops_infer.so.8.3.1
/usr/local/cuda-11.5/targets/x86_64-linux/lib/libcudnn_ops_train.so.8.3.1
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:                   46 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:                       GenuineIntel
CPU family:                      6
Model:                           85
Model name:                      Intel(R) Xeon(R) CPU @ 2.20GHz
Stepping:                        7
CPU MHz:                         2200.220
BogoMIPS:                        4400.44
Hypervisor vendor:               KVM
Virtualization type:             full
L1d cache:                       768 KiB
L1i cache:                       768 KiB
L2 cache:                        24 MiB
L3 cache:                        38.5 MiB
NUMA node0 CPU(s):               0-47
Vulnerability Itlb multihit:     Not affected
Vulnerability L1tf:              Not affected
Vulnerability Mds:               Mitigation; Clear CPU buffers; SMT Host state unknown
Vulnerability Meltdown:          Not affected
Vulnerability Mmio stale data:   Vulnerable: Clear CPU buffers attempted, no microcode; SMT Host state unknown
Vulnerability Retbleed:          Mitigation; Enhanced IBRS
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:   Mitigation; Clear CPU buffers; SMT Host state unknown
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 nonstop_tsc cpuid tsc_known_freq pni pclmulqdq ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt aes xsave avx f16c rdrand hypervisor lahf_lm abm 3dnowprefetch invpcid_single ssbd ibrs ibpb stibp ibrs_enhanced fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 erms invpcid rtm mpx avx512f avx512dq rdseed adx smap clflushopt clwb avx512cd avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves arat avx512_vnni md_clear arch_capabilities

Versions of relevant libraries:
[pip3] mypy==0.991
[pip3] mypy-extensions==1.0.0
[pip3] numpy==1.21.6
[pip3] poptorch==3.11.0
[pip3] torch==2.0.0
[pip3] torchaudio==2.0.0
[pip3] torchfile==0.1.0
[pip3] torchvision==0.15.0
[pip3] triton==2.0.0
[conda] blas                      1.0                         mkl  
[conda] ffmpeg                    4.3                  hf484d3e_0    pytorch
[conda] mkl                       2021.4.0           h06a4308_640  
[conda] mkl-service               2.4.0            py39h7f8727e_0  
[conda] mkl_fft                   1.3.1            py39hd3c417c_0  
[conda] mkl_random                1.2.2            py39h51133e4_0  
[conda] numpy                     1.21.6                   pypi_0    pypi
[conda] poptorch                  3.11.0                   pypi_0    pypi
[conda] pytorch                   2.0.0           py3.9_cuda11.8_cudnn8.7.0_0    pytorch
[conda] pytorch-cuda              11.8                 h7e8668a_3    pytorch
[conda] pytorch-mutex             1.0                        cuda    pytorch
[conda] torchaudio                2.0.0                py39_cu118    pytorch
[conda] torchfile                 0.1.0                    pypi_0    pypi
[conda] torchtriton               2.0.0                      py39    pytorch
[conda] torchvision               0.15.0               py39_cu118    pytorch

cc @albanD @mruberry @jbschlosser @walterddr @mikaylagawarecki @bhosmer @cpuhrsch @erichan1 @drisspg