Repository: pytorch
Issue: TransformerEncoderLayer behavior inconsistent between training and evaluation mode
Labels: module: nn,triaged

### 🐛 Describe the bug

Hi,

TransformerEncoderLayer is behaving differently in training and evaluation mode. In training mode, it expects the src_mask to be of shape (N⋅num_heads, S, S) and throws an error if the shape is (N, num_heads, S, S). This behavior is consistent with the documentation. However, in evaluation mode with gradients disabled and batch_first set to true, it takes the "sparsity fast path", which shows the opposite behavior: a src_mask of shape (N⋅num_heads, S, S) throws an error while (N, num_heads, S, S) works as expected.
See the code below for a minimum example.

```python
import torch
from torch.nn import TransformerEncoderLayer

heads = 8
bs = 64
input_dim = 16
seq_len = 4

layer = TransformerEncoderLayer(input_dim, heads, 32, batch_first=True)

# Works
res = layer(torch.zeros(bs, seq_len, input_dim), torch.zeros((bs * heads, seq_len, seq_len), dtype=torch.bool))

# Does not work
# res = layer(torch.zeros(bs, seq_len, input_dim), torch.zeros((bs, heads, seq_len, seq_len), dtype=torch.bool))

layer.eval()

with torch.no_grad():
    # Does not work
    # res = layer(torch.zeros(bs, seq_len, input_dim), torch.zeros((bs * heads, seq_len, seq_len), dtype=torch.bool))

    # Works
    res = layer(torch.zeros(bs, seq_len, input_dim), torch.zeros((bs, heads, seq_len, seq_len), dtype=torch.bool))

```
I personally think the second behavior is more intuitive, as I don't understand why the head and batch dimensions should be merged into one.
A workaround is to prevent TransformerEncoderLayer from being set to evaluation mode, which probably comes at a performance penalty.
Best,
Tim

### Versions

Collecting environment information...
PyTorch version: 2.0.0+cu117
Is debug build: False
CUDA used to build PyTorch: 11.7
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.1
Libc version: glibc-2.31

Python version: 3.8.10 (default, Mar 13 2023, 10:26:41)  [GCC 9.4.0] (64-bit runtime)
Python platform: Linux-5.15.0-69-generic-x86_64-with-glibc2.29
Is CUDA available: True
CUDA runtime version: Could not collect
CUDA_MODULE_LOADING set to: LAZY
GPU models and configuration: GPU 0: NVIDIA GeForce RTX 3080 Ti
Nvidia driver version: 525.105.17
cuDNN version: Could not collect
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:                   48 bits physical, 48 bits virtual
CPU(s):                          24
On-line CPU(s) list:             0-23
Thread(s) per core:              2
Core(s) per socket:              12
Socket(s):                       1
NUMA node(s):                    1
Vendor ID:                       AuthenticAMD
CPU family:                      25
Model:                           33
Model name:                      AMD Ryzen 9 5900X 12-Core Processor
Stepping:                        0
Frequency boost:                 enabled
CPU MHz:                         2200.000
CPU max MHz:                     3700,0000
CPU min MHz:                     2200,0000
BogoMIPS:                        7400.21
Virtualization:                  AMD-V
L1d cache:                       384 KiB
L1i cache:                       384 KiB
L2 cache:                        6 MiB
L3 cache:                        64 MiB
NUMA node0 CPU(s):               0-23
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 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; Retpolines, IBPB conditional, IBRS_FW, STIBP always-on, RSB filling, PBRSB-eIBRS Not affected
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 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 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 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 arat npt lbrv svm_lock nrip_save tsc_scale vmcb_clean flushbyasid decodeassists pausefilter pfthreshold avic v_vmsave_vmload vgif v_spec_ctrl umip pku ospke vaes vpclmulqdq rdpid overflow_recov succor smca fsrm

Versions of relevant libraries:
[pip3] numpy==1.24.2
[pip3] torch==2.0.0
[pip3] torchvision==0.15.1
[pip3] triton==2.0.0
[conda] Could not collect

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