Repository: pytorch
Issue: scaled_dot_product returns NaN arrays with eval()
Labels: triaged,module: NaNs and Infs,module: sdpa

### 🐛 Describe the bug

Hello, I'm trying to use the built-in transformer encoder for my work.

The model works well in the training phase (with train()). 
But, when I try to evaluate my model (with eval() and no_grad()), my model always returns all of NaNs. 
(I checked that the no_grad doesn't cause the problem; only eval() causes the problem.)

I traced the source code and found that the `drouput_p` in  `nn.functional.multi_head_attention_forward` causes the problem. 

The `dropout_p` is set to 0.1 with train(), and 0.0 with eval().
And the `scaled_dot_product` (nn.functional.py line 5287) function returns all NaNs with 0.0 of `dropout_p`.
So I manually changed the `dropout_p` to 1.0 in eval(), then the `scaled_dot_product` function returns some float values (but I can't be sure they are correct values). 

Is there any bug in the `scaled_dot_product` code for the `dropout_p`?
Or did I make some mistake to use the model?
I don't use any attn_mask or padding mask in this work.

my model is as follows:
```python
class RankNet(nn.Module):
    def __init__(self, config):
        super(RankNet, self).__init__()

        f_dim = config['train']['f_dim']
        d_model = config['train']['d_model']
        self.autoencoder = AutoEncoder()
        self.extractor = nn.Linear(f_dim, d_model)
        self.pos_encoder = PositionalEncoding(d_model)
        encoder_layers = TransformerEncoderLayer(d_model=d_model, nhead=8)
        self.transformer_encoder = TransformerEncoder(encoder_layers, num_layers=2)
        self.fc = nn.Linear(d_model, 1)

    def forward(self, img1, input1, img2, input2):
        reshaped_img1 = img1.view(-1, *img1.shape[2:])  # batch, 4, c, h, w => batch * 4, c, h, w
        reshaped_img2 = img2.view(-1, *img2.shape[2:])
        e1, d1 = self.autoencoder(reshaped_img1)
        e2, d2 = self.autoencoder(reshaped_img2)
        e1 = e1.view(int(e1.shape[0]/4), 4, -1)
        e2 = e2.view(int(e2.shape[0]/4), 4, -1)

        input1 = torch.cat((input1, e1), dim=2)
        input1 = self.extractor(input1.view(-1, input1.shape[-1]))
        input1 = input1.view(int(input1.shape[0]/4), 4, -1)
        input2 = torch.cat((input2, e2), dim=2)
        input2 = self.extractor(input2.view(-1, input2.shape[-1]))
        input2 = input2.view(int(input2.shape[0]/4), 4, -1)

        # batch first to seqence first
        input1 = input1.transpose(0, 1)
        input2 = input2.transpose(0, 1)

        input1 = self.pos_encoder(input1)
        input2 = self.pos_encoder(input2)

        x1 = self.transformer_encoder(input1)
        x2 = self.transformer_encoder(input2)
        avg_pooled1 = torch.mean(x1, dim=0)
        avg_pooled2 = torch.mean(x2, dim=0)
        x1 = self.fc(avg_pooled1)
        x2 = self.fc(avg_pooled2)
        return torch.sigmoid(x1 - x2), d1, d2
```

And the evaluation process is as follows:
``` python
            model.eval()
            with torch.no_grad():
                accs = 0
                d1, d2 = None, None
                for i, (img1, feature1, img2, feature2, label) in tqdm(enumerate(val_loader), desc=f'Evaluation'):
                    img1 = img1.to(self.device)
                    feature1 = feature1.to(self.device)
                    img2 = img2.to(self.device)
                    feature2 = feature2.to(self.device)
                    label = label.unsqueeze(1).to(self.device)

                    o, d1, d2 = model(img1, feature1, img2, feature2)
```

### Versions

PyTorch version: 2.0.0+cu118
Is debug build: False
CUDA used to build PyTorch: 11.8
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.26.4
Libc version: glibc-2.31

Python version: 3.10.12 (main, Jun  7 2023, 12:45:35) [GCC 9.4.0] (64-bit runtime)
Python platform: Linux-5.4.0-135-generic-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: 525.125.06
cuDNN version: Probably one of the following:
/usr/lib/x86_64-linux-gnu/libcudnn.so.8.9.0
/usr/lib/x86_64-linux-gnu/libcudnn_adv_infer.so.8.9.0
/usr/lib/x86_64-linux-gnu/libcudnn_adv_train.so.8.9.0
/usr/lib/x86_64-linux-gnu/libcudnn_cnn_infer.so.8.9.0
/usr/lib/x86_64-linux-gnu/libcudnn_cnn_train.so.8.9.0
/usr/lib/x86_64-linux-gnu/libcudnn_ops_infer.so.8.9.0
/usr/lib/x86_64-linux-gnu/libcudnn_ops_train.so.8.9.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:                   46 bits physical, 57 bits virtual
CPU(s):                          112
On-line CPU(s) list:             0-111
Thread(s) per core:              2
Core(s) per socket:              28
Socket(s):                       2
NUMA node(s):                    4
Vendor ID:                       GenuineIntel
CPU family:                      6
Model:                           106
Model name:                      Intel(R) Xeon(R) Gold 6330 CPU @ 2.00GHz
Stepping:                        6
CPU MHz:                         800.000
CPU max MHz:                     3100.0000
CPU min MHz:                     800.0000
BogoMIPS:                        4000.00
Virtualization:                  VT-x
L1d cache:                       2.6 MiB
L1i cache:                       1.8 MiB
L2 cache:                        70 MiB
L3 cache:                        84 MiB
NUMA node0 CPU(s):               0-13,56-69
NUMA node1 CPU(s):               14-27,70-83
NUMA node2 CPU(s):               28-41,84-97
NUMA node3 CPU(s):               42-55,98-111
Vulnerability Itlb multihit:     Not affected
Vulnerability L1tf:              Not affected
Vulnerability Mds:               Not affected
Vulnerability Meltdown:          Not affected
Vulnerability Mmio stale data:   Mitigation; Clear CPU buffers; SMT vulnerable
Vulnerability Retbleed:          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
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 invpcid_single 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 rdt_a avx512f avx512dq rdseed adx smap avx512ifma clflushopt clwb intel_pt avx512cd sha_ni avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local wbnoinvd dtherm ida arat pln pts hwp hwp_act_window hwp_epp hwp_pkg_req avx512vbmi umip pku ospke avx512_vbmi2 gfni vaes vpclmulqdq avx512_vnni avx512_bitalg tme avx512_vpopcntdq rdpid md_clear pconfig flush_l1d arch_capabilities

Versions of relevant libraries:
[pip3] flake8==3.8.4
[pip3] numpy==1.24.3
[pip3] torch==2.0.0+cu118
[pip3] torchaudio==2.0.0+cu118
[pip3] torchvision==0.15.1+cu118
[pip3] triton==2.0.0
[pip3] tritonclient==2.35.0
[conda] Could not collect

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