Repository: pytorch
Issue: `einsum` is about 40x slower on CUDA than manually multiplying and summing
Labels: module: performance,triaged,module: linear algebra

### 🐛 Describe the bug

A similar issue was reported in #32591. Unfortunately, it doesn't look like it was actually fully fixed at the time.

Comparing
```python
(a * b).sum(dim=-1)
torch.einsum("Nc,Nc->N", a, b)
numpy.einsum("Nc,Nc->N", a, b) # a and b are equivalent numpy arrays
```
where `a` and `b` are tensors with a large `N` dimension and a relatively small `c` dimension

```
[-------------------------------------  -------------------------------------]
                                  |  mul/sum  |  torch.einsum  |  numpy.einsum
1 threads: -------------------------------------------------------------------
      Nc,Nc->N cpu (1048576, 2)   |    9900   |      9000      |      6660    
      Nc,Nc->N cuda (1048576, 2)  |     700   |     30880      |      6000    

Times are in microseconds (us).
```

So on the CPU both the "manual" and the `einsum` versions are about the same (though `numpy` is faster). But on the GPU, the `einsum` version is about 40 times slower (the exact slowdown can vary by machine, I also got a 10x slowdown on a slightly more modern workstation).

Here's the script that I used to get these results:

<details>
<summary><code>bench_einsum.py</code></summary>

```python
import numpy as np
import torch
import torch.utils.benchmark as benchmark
from torch.testing._internal.common_utils import make_tensor


def generate_test_cases(device, dtype):
    a = make_tensor((1024 * 1024, 2), device=device, dtype=dtype)
    b = make_tensor((1024 * 1024, 2), device=device, dtype=dtype)

    yield "Nc,Nc->N", a, b


results = []
for dev in ["cpu", "cuda"]:
    for equation, a, b in generate_test_cases(dev, torch.float):
        sub_label = f"{equation} {dev} {tuple(a.shape)}"

        results.append(
            benchmark.Timer(
                stmt="(a * b).sum(dim=-1)",
                globals={"equation": equation, "a": a, "b": b},
                sub_label=sub_label,
                description="mul/sum",
            ).blocked_autorange(min_run_time=1)
        )

        results.append(
            benchmark.Timer(
                stmt="torch.einsum(equation, a, b)",
                globals={"equation": equation, "a": a, "b": b},
                sub_label=sub_label,
                description="torch.einsum",
            ).blocked_autorange(min_run_time=1)
        )

        results.append(
            benchmark.Timer(
                stmt="numpy.einsum(equation, a, b)",
                setup="import numpy",
                globals={
                    "equation": equation,
                    "a": a.cpu().numpy(),
                    "b": b.cpu().numpy(),
                },
                sub_label=sub_label,
                description="numpy.einsum",
            ).blocked_autorange(min_run_time=1)
        )


compare = benchmark.Compare(results)
compare.trim_significant_figures()
compare.colorize(rowwise=True)
compare.print()
```
</details>

### Versions

<details>
<summary>Versions</summary>

```
Collecting environment information...
PyTorch version: 2.0.0
Is debug build: False
CUDA used to build PyTorch: 12.1
ROCM used to build PyTorch: N/A

OS: Manjaro Linux (x86_64)
GCC version: (GCC) 12.2.1 20230201
Clang version: 15.0.7
CMake version: version 3.26.3
Libc version: glibc-2.37

Python version: 3.10.10 (main, Mar  5 2023, 22:26:53) [GCC 12.2.1 20230201] (64-bit runtime)
Python platform: Linux-5.15.108-1-MANJARO-x86_64-with-glibc2.37
Is CUDA available: True
CUDA runtime version: 12.1.66
CUDA_MODULE_LOADING set to: LAZY
GPU models and configuration: GPU 0: NVIDIA GeForce GTX 1050
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:                   39 bits physical, 48 bits virtual
Byte Order:                      Little Endian
CPU(s):                          8
On-line CPU(s) list:             0-7
Vendor ID:                       GenuineIntel
Model name:                      Intel(R) Core(TM) i7-7700HQ CPU @ 2.80GHz
CPU family:                      6
Model:                           158
Thread(s) per core:              2
Core(s) per socket:              4
Socket(s):                       1
Stepping:                        9
CPU(s) scaling MHz:              84%
CPU max MHz:                     3800.0000
CPU min MHz:                     800.0000
BogoMIPS:                        5602.18
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 est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault epb invpcid_single pti ssbd ibrs ibpb stibp tpr_shadow vnmi flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid mpx rdseed adx smap clflushopt intel_pt xsaveopt xsavec xgetbv1 xsaves dtherm ida arat pln pts hwp hwp_notify hwp_act_window hwp_epp md_clear flush_l1d arch_capabilities
Virtualization:                  VT-x
L1d cache:                       128 KiB (4 instances)
L1i cache:                       128 KiB (4 instances)
L2 cache:                        1 MiB (4 instances)
L3 cache:                        6 MiB (1 instance)
NUMA node(s):                    1
NUMA node0 CPU(s):               0-7
Vulnerability Itlb multihit:     KVM: Mitigation: VMX disabled
Vulnerability L1tf:              Mitigation; PTE Inversion; VMX conditional cache flushes, SMT vulnerable
Vulnerability Mds:               Mitigation; Clear CPU buffers; SMT vulnerable
Vulnerability Meltdown:          Mitigation; PTI
Vulnerability Mmio stale data:   Mitigation; Clear CPU buffers; SMT vulnerable
Vulnerability Retbleed:          Mitigation; 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; IBRS, IBPB conditional, STIBP conditional, RSB filling, PBRSB-eIBRS Not affected
Vulnerability Srbds:             Mitigation; Microcode
Vulnerability Tsx async abort:   Not affected

Versions of relevant libraries:
[pip3] flake8==6.0.0
[pip3] mypy==1.1.1
[pip3] mypy-extensions==1.0.0
[pip3] numpy==1.24.2
[pip3] pytorch-lightning==2.0.1
[pip3] torch==2.0.0
[pip3] torchmetrics==0.11.3
[pip3] torchvision==0.15.1a0
[conda] Could not collect
```

</details>

cc @ngimel @jianyuh @nikitaved @pearu @mruberry @walterddr @IvanYashchuk @xwang233 @Lezcano