Repository: pytorch
Issue: C++ API `torch::nn::MultiheadAttention` Crashes by division by zero
Labels: module: crash,module: cpp,module: nn,triaged

### 🐛 Describe the bug

`num_heads = 0` leads to crash by division by zero.

Test code:
```c++
#include <stdint.h>
#include <stddef.h>
#include <c10/util/irange.h>
#include <cassert>
#include <torch/torch.h>

namespace F = torch::nn::functional;
using namespace torch::nn;

int main() {
  try {
    torch::TensorOptions toptions = torch::TensorOptions();

    auto moptions = torch::nn::MultiheadAttentionOptions(0,0);
    auto m = torch::nn::MultiheadAttention(moptions);

    auto result = m->forward(
      torch::randn({}, toptions),
      torch::randn({}, toptions),
      torch::randn({}, toptions));
  } catch (std::exception& e) {
    return -2;
  }

  return 0;
}
```
Error Log:
```
AddressSanitizer:DEADLYSIGNAL
=================================================================
==700223==ERROR: AddressSanitizer: FPE on unknown address 0x7f0cd209f172 (pc 0x7f0cd209f172 bp 0x7ffdf04ab770 sp 0x7ffdf04aa360 T0)
    #0 0x7f0cd209f172 in torch::nn::MultiheadAttentionImpl::reset() /home/sehoon/pytorch/torch/csrc/api/src/nn/modules/activation.cpp:500:34
    #1 0x7f0cd209d092 in torch::nn::MultiheadAttentionImpl::MultiheadAttentionImpl(torch::nn::MultiheadAttentionOptions const&) /home/sehoon/pytorch/torch/csrc/api/src/nn/modules/activation.cpp:437:3
    #2 0x407115 in torch::nn::ModuleHolder<torch::nn::MultiheadAttentionImpl>::ModuleHolder<torch::nn::MultiheadAttentionOptions&, void>(torch::nn::MultiheadAttentionOptions&) /home/sehoon/pytorch/torch/csrc/api/include/torch/nn/pimpl.h:65:19
    #3 0x4057ac in torch::nn::MultiheadAttention::MultiheadAttention<torch::nn::MultiheadAttentionOptions&, void>(torch::nn::MultiheadAttentionOptions&) /home/sehoon/pytorch/torch/csrc/api/include/torch/nn/modules/activation.h:872:1
    #4 0x4047ff in main /home/sehoon/pytorch/test/cpp/reproduce/MultiheadAttention.cpp:15:14
    #5 0x7f0cb084dd8f in __libc_start_call_main csu/../sysdeps/nptl/libc_start_call_main.h:58:16
    #6 0x7f0cb084de3f in __libc_start_main csu/../csu/libc-start.c:392:3
    #7 0x404484 in _start (/home/sehoon/pytorch/build/bin/reproduce_MultiheadAttention+0x404484)

AddressSanitizer can not provide additional info.
SUMMARY: AddressSanitizer: FPE /home/sehoon/pytorch/torch/csrc/api/src/nn/modules/activation.cpp:500:34 in torch::nn::MultiheadAttentionImpl::reset()
==700223==ABORTING
```
[Error location](https://github.com/pytorch/pytorch/blob/1cc002621d23749c6742193ef3c1eda1015480c2/torch/csrc/api/src/nn/modules/activation.cpp#L500):
```c++
  head_dim = options.embed_dim() / options.num_heads();
```
Because there is no guard which bans `num_heads=0`, it ends up with crash.

### Versions

PyTorch version: 2.1.0a0+git416bf4e
Is debug build: True
CUDA used to build PyTorch: Could not collect
ROCM used to build PyTorch: N/A

OS: Ubuntu 22.04.2 LTS (x86_64)
GCC version: (Ubuntu 11.4.0-1ubuntu1~22.04) 11.4.0
Clang version: 12.0.1 (git@github.com:starlab-unist/llvm-project.git 82ccd79bfce79353c2bb4c1ab258ebfeb536a67d)
CMake version: version 3.26.4
Libc version: glibc-2.35

Python version: 3.9.17 (main, Jul  5 2023, 20:41:20)  [GCC 11.2.0] (64-bit runtime)
Python platform: Linux-5.15.0-78-generic-x86_64-with-glibc2.35
Is CUDA available: False
CUDA runtime version: 11.7.99
CUDA_MODULE_LOADING set to: N/A
GPU models and configuration: 
GPU 0: NVIDIA GeForce RTX 3090
GPU 1: NVIDIA GeForce RTX 3090
GPU 2: NVIDIA GeForce RTX 3090
GPU 3: NVIDIA GeForce RTX 3090

Nvidia driver version: 535.86.10
cuDNN version: Probably one of the following:
/usr/local/cuda-11.7/targets/x86_64-linux/lib/libcudnn.so.8.9.2
/usr/local/cuda-11.7/targets/x86_64-linux/lib/libcudnn_adv_infer.so.8.9.2
/usr/local/cuda-11.7/targets/x86_64-linux/lib/libcudnn_adv_train.so.8.9.2
/usr/local/cuda-11.7/targets/x86_64-linux/lib/libcudnn_cnn_infer.so.8.9.2
/usr/local/cuda-11.7/targets/x86_64-linux/lib/libcudnn_cnn_train.so.8.9.2
/usr/local/cuda-11.7/targets/x86_64-linux/lib/libcudnn_ops_infer.so.8.9.2
/usr/local/cuda-11.7/targets/x86_64-linux/lib/libcudnn_ops_train.so.8.9.2
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):                          96
On-line CPU(s) list:             0-95
Vendor ID:                       GenuineIntel
Model name:                      Intel(R) Xeon(R) Gold 6248R CPU @ 3.00GHz
CPU family:                      6
Model:                           85
Thread(s) per core:              2
Core(s) per socket:              24
Socket(s):                       2
Stepping:                        7
CPU max MHz:                     4000.0000
CPU min MHz:                     1200.0000
BogoMIPS:                        6000.00
Flags:                           fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc art arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc cpuid aperfmperf pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid dca sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault epb cat_l3 cdp_l3 invpcid_single intel_ppin ssbd mba ibrs ibpb stibp ibrs_enhanced tpr_shadow vnmi flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid cqm mpx rdt_a avx512f avx512dq rdseed adx smap clflushopt clwb intel_pt avx512cd avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local dtherm ida arat pln pts pku ospke avx512_vnni md_clear flush_l1d arch_capabilities
Virtualization:                  VT-x
L1d cache:                       1.5 MiB (48 instances)
L1i cache:                       1.5 MiB (48 instances)
L2 cache:                        48 MiB (48 instances)
L3 cache:                        71.5 MiB (2 instances)
NUMA node(s):                    2
NUMA node0 CPU(s):               0-23,48-71
NUMA node1 CPU(s):               24-47,72-95
Vulnerability Itlb multihit:     KVM: Mitigation: VMX disabled
Vulnerability L1tf:              Not affected
Vulnerability Mds:               Not affected
Vulnerability Meltdown:          Not affected
Vulnerability Mmio stale data:   Mitigation; Clear CPU buffers; SMT vulnerable
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; TSX disabled

Versions of relevant libraries:
[pip3] numpy==1.25.2
[pip3] torch==2.1.0a0+git416bf4e
[conda] mkl                       2023.1.0         h6d00ec8_46342  
[conda] mkl-include               2023.1.0         h06a4308_46342  
[conda] numpy                     1.25.2                   pypi_0    pypi
[conda] torch                     2.1.0a0+git416bf4e           dev_0    <develop>

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