Repository: pytorch
Issue: TransformerEncoderLayer fast path predicts NaN when provided attention bias
Labels: module: nn,triaged

### 🐛 Describe the bug

Similar to [this issue](https://github.com/pytorch/pytorch/issues/107084) (which is for `nn.MultiheadAttention`) and [this comment](https://github.com/pytorch/pytorch/issues/107084#issuecomment-1854786904) within the same thread, `nn.TransfromerEncoderLayer` predicts `NaN` in its fast path when provided with an attention mask. 

I have created a child class `MyTransformerEncoderLayer` , that is used to check the attention weights on the slow path (the fast path doesn't go through `_sa_block`).
```python
class MyTransformerEncoderLayer(nn.TransformerEncoderLayer):
    def _sa_block(self, x: Tensor,
                  attn_mask: Optional[Tensor], key_padding_mask: Optional[Tensor], is_causal: bool = False) -> Tensor:
        x, self.attn_weights = self.self_attn(x, x, x,
                           attn_mask=attn_mask,
                           key_padding_mask=key_padding_mask,
                           need_weights=True, is_causal=is_causal)
        return self.dropout1(x)
```
Here is how to reproduce the problem. Based on [another similar issue](https://github.com/pytorch/pytorch/issues/110505) that claims dropout was the cause, dropout has been set to zero here for simplification. 
```python
d_model = 8 ; n_head = 2    ; dim_feedforward = 16;
bsz = 3     ; seq_len = 5
x = torch.randn(bsz, seq_len, d_model)
padding_mask = torch.rand(bsz, seq_len) < 0.2
# padding_mask = None
mask = torch.randn(x.shape[0]*n_head, 5, 5)

enc_layer = nn.TransformerEncoderLayer(d_model, n_head, dim_feedforward, dropout=0.0, batch_first=True)
my_enc_layer = MyTransformerEncoderLayer(d_model, n_head, dim_feedforward, dropout=0.0, batch_first=True)

# slow path
y_enc = enc_layer(x, src_mask=mask, src_key_padding_mask=padding_mask)
y_my_enc = my_enc_layer(x, src_mask=mask, src_key_padding_mask=padding_mask)
attn_weights_my_enc = my_enc_layer.attn_weights

# fast path
with torch.no_grad():
    enc_layer.eval()
    my_enc_layer.eval()
    y_enc_fast = enc_layer(x, src_mask=mask, src_key_padding_mask=padding_mask)
    y_my_enc_fast = my_enc_layer(x, src_mask=mask, src_key_padding_mask=padding_mask)    # fast path doesn't go through _sa_block, so can't save the attention weights

print(f"y_enc                   : {y_enc.isnan().any(), y_enc.isnan().all()}")
print(f"y_enc_fast              : {y_enc_fast.isnan().any(), y_enc_fast.isnan().all()}")
print(f"y_my_enc                : {y_my_enc.isnan().any(), y_my_enc.isnan().all()}")
print(f"y_my_enc_fast           : {y_my_enc_fast.isnan().any(), y_my_enc_fast.isnan().all()}")
print(f"attn_weights_my_enc     : {attn_weights_my_enc.isnan().any(), attn_weights_my_enc.isnan().all()}")
```

Results:
```
y_enc                   : (tensor(False), tensor(False))
y_enc_fast              : (tensor(True), tensor(True))
y_my_enc                : (tensor(False), tensor(False))
y_my_enc_fast           : (tensor(True), tensor(True))
attn_weights_my_enc     : (tensor(False), tensor(False))
```

Only the fast path outputs `y_enc_fast` and `y_my_enc_fast` are all `NaN`. On the slow path, none of the attention weights in `attn_weights_my_enc` are `NaN` given the same set of inputs, which suggests that the problem is likely not due to erroneous inputs creating issues with the attention scores. Note that the same results are obtained even if `src_key_padding_mask` is `None`.


### 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 22.04.3 LTS (x86_64)
GCC version: (Ubuntu 11.4.0-1ubuntu1~22.04) 11.4.0
Clang version: 14.0.0-1ubuntu1.1
CMake version: version 3.27.9
Libc version: glibc-2.35

Python version: 3.10.12 (main, Nov 20 2023, 15:14:05) [GCC 11.4.0] (64-bit runtime)
Python platform: Linux-6.1.58+-x86_64-with-glibc2.35
Is CUDA available: True
CUDA runtime version: 12.2.140
CUDA_MODULE_LOADING set to: LAZY
GPU models and configuration: GPU 0: Tesla T4
Nvidia driver version: 535.104.05
cuDNN version: Probably one of the following:
/usr/lib/x86_64-linux-gnu/libcudnn.so.8.9.6
/usr/lib/x86_64-linux-gnu/libcudnn_adv_infer.so.8.9.6
/usr/lib/x86_64-linux-gnu/libcudnn_adv_train.so.8.9.6
/usr/lib/x86_64-linux-gnu/libcudnn_cnn_infer.so.8.9.6
/usr/lib/x86_64-linux-gnu/libcudnn_cnn_train.so.8.9.6
/usr/lib/x86_64-linux-gnu/libcudnn_ops_infer.so.8.9.6
/usr/lib/x86_64-linux-gnu/libcudnn_ops_train.so.8.9.6
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):                             2
On-line CPU(s) list:                0,1
Vendor ID:                          GenuineIntel
Model name:                         Intel(R) Xeon(R) CPU @ 2.30GHz
CPU family:                         6
Model:                              63
Thread(s) per core:                 2
Core(s) per socket:                 1
Socket(s):                          1
Stepping:                           0
BogoMIPS:                           4599.99
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 invpcid_single ssbd ibrs ibpb stibp fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid xsaveopt arat md_clear arch_capabilities
Hypervisor vendor:                  KVM
Virtualization type:                full
L1d cache:                          32 KiB (1 instance)
L1i cache:                          32 KiB (1 instance)
L2 cache:                           256 KiB (1 instance)
L3 cache:                           45 MiB (1 instance)
NUMA node(s):                       1
NUMA node0 CPU(s):                  0,1
Vulnerability Gather data sampling: Not affected
Vulnerability Itlb multihit:        Not affected
Vulnerability L1tf:                 Mitigation; PTE Inversion
Vulnerability Mds:                  Vulnerable; SMT Host state unknown
Vulnerability Meltdown:             Vulnerable
Vulnerability Mmio stale data:      Vulnerable
Vulnerability Retbleed:             Vulnerable
Vulnerability Spec rstack overflow: Not affected
Vulnerability Spec store bypass:    Vulnerable
Vulnerability Spectre v1:           Vulnerable: __user pointer sanitization and usercopy barriers only; no swapgs barriers
Vulnerability Spectre v2:           Vulnerable, IBPB: disabled, STIBP: disabled, PBRSB-eIBRS: Not affected
Vulnerability Srbds:                Not affected
Vulnerability Tsx async abort:      Not affected

Versions of relevant libraries:
[pip3] numpy==1.23.5
[pip3] torch==2.1.0+cu121
[pip3] torchaudio==2.1.0+cu121
[pip3] torchdata==0.7.0
[pip3] torchsummary==1.5.1
[pip3] torchtext==0.16.0
[pip3] torchvision==0.16.0+cu121
[pip3] triton==2.1.0
[conda] Could not collect

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