Repository: pytorch
Issue: Matrix multiplication performance regression in case of an additional dimension of size 1
Labels: module: dependency bug,triaged,module: cublas

### 🐛 Describe the bug

`A.unsqueeze(0) @ B.unsqueeze(0)` can be about 70 times slower than `A @ B` depending on the dimensions of matrices `A` and `B`.

Code for reproducing:
```python
from time import time
import torch

A = torch.randn([20, 4000000], dtype=torch.float64, device='cuda')
B = torch.randn([4000000, 20], dtype=torch.float64, device='cuda')
torch.cuda.synchronize()

for i in range(3):
    start = time()
    a = A @ B
    torch.cuda.synchronize()
    print(time() - start)  # 0.064

    start = time()
    b = (A.unsqueeze(0) @ B.unsqueeze(0)).squeeze(0)
    torch.cuda.synchronize()
    print(time() - start)  # 4.375

    start = time()
    c = torch.einsum("in,nj->ij", A, B)
    torch.cuda.synchronize()
    print(time() - start)  # 4.375

print(torch.isclose(a, b).all().item())  # True
print((a == b).all().item())  # False
print((b == c).all().item())  # True
```

This happens on a machine with NVIDIA GeForce RTX 2080 Ti and
```
PyTorch version: 2.0.1
CUDA used to build PyTorch: 12.1
OS: Arch Linux (x86_64)
CUDA runtime version: 12.1.105
```

There is no difference in execution times (always 0.064 s) and `(a == b).all().item()` evaluates to `True` on a similar machine with
```
PyTorch version: 1.13.1
CUDA used to build PyTorch: 11.8
OS: Arch Linux (x86_64)
CUDA runtime version: 11.8.89
```


### Versions

```
Collecting environment information...
PyTorch version: 2.0.1
Is debug build: False
CUDA used to build PyTorch: 12.1
ROCM used to build PyTorch: N/A

OS: Arch Linux (x86_64)
GCC version: (GCC) 13.1.1 20230429
Clang version: Could not collect
CMake version: Could not collect
Libc version: glibc-2.37

Python version: 3.11.3 (main, Apr  5 2023, 15:52:25) [GCC 12.2.1 20230201] (64-bit runtime)
Python platform: Linux-6.3.2-arch1-1-x86_64-with-glibc2.37
Is CUDA available: True
CUDA runtime version: 12.1.105
CUDA_MODULE_LOADING set to: LAZY
GPU models and configuration:
GPU 0: NVIDIA GeForce RTX 2080 Ti
GPU 1: NVIDIA GeForce RTX 2080 Ti
GPU 2: NVIDIA GeForce RTX 2080 Ti
GPU 3: NVIDIA GeForce RTX 2080 Ti

Nvidia driver version: 530.41.03
cuDNN version: Probably one of the following:
/usr/lib/libcudnn.so.8.8.0
/usr/lib/libcudnn_adv_infer.so.8.8.0
/usr/lib/libcudnn_adv_train.so.8.8.0
/usr/lib/libcudnn_cnn_infer.so.8.8.0
/usr/lib/libcudnn_cnn_train.so.8.8.0
/usr/lib/libcudnn_ops_infer.so.8.8.0
/usr/lib/libcudnn_ops_train.so.8.8.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
Address sizes:                   43 bits physical, 48 bits virtual
Byte Order:                      Little Endian
CPU(s):                          24
On-line CPU(s) list:             0-23
Vendor ID:                       AuthenticAMD
Model name:                      AMD Ryzen Threadripper 2920X 12-Core Processor
CPU family:                      23
Model:                           8
Thread(s) per core:              2
Core(s) per socket:              12
Socket(s):                       1
Stepping:                        2
Frequency boost:                 enabled
CPU(s) scaling MHz:              59%
CPU max MHz:                     3500.0000
CPU min MHz:                     2200.0000
BogoMIPS:                        6988.87
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 amd_dcm 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 skinit wdt tce topoext perfctr_core perfctr_nb bpext perfctr_llc mwaitx cpb hw_pstate ssbd ibpb vmmcall fsgsbase bmi1 avx2 smep bmi2 rdseed adx smap clflushopt sha_ni xsaveopt xsavec xgetbv1 clzero irperf xsaveerptr arat npt lbrv svm_lock nrip_save tsc_scale vmcb_clean flushbyasid decodeassists pausefilter pfthreshold avic v_vmsave_vmload vgif overflow_recov succor smca sev sev_es
Virtualization:                  AMD-V
L1d cache:                       384 KiB (12 instances)
L1i cache:                       768 KiB (12 instances)
L2 cache:                        6 MiB (12 instances)
L3 cache:                        32 MiB (4 instances)
NUMA node(s):                    1
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:          Mitigation; untrained return thunk; SMT vulnerable
Vulnerability Spec store bypass: Mitigation; Speculative Store Bypass disabled via prctl
Vulnerability Spectre v1:        Mitigation; usercopy/swapgs barriers and __user pointer sanitization
Vulnerability Spectre v2:        Mitigation; Retpolines, IBPB conditional, STIBP disabled, RSB filling, PBRSB-eIBRS Not affected
Vulnerability Srbds:             Not affected
Vulnerability Tsx async abort:   Not affected

Versions of relevant libraries:
[pip3] numpy==1.24.3
[pip3] pytorch-lightning==2.0.2
[pip3] torch==2.0.1
[pip3] torchmetrics==0.11.4
[pip3] torchvision==0.15.1a0
[conda] Could not collect
```

cc @csarofeen @ptrblck @xwang233