Repository: pytorch
Issue: Forwardpropagation of high-dimensional tensors through the nn.Linear module becomes multiple times slower since pytorch 2.1.0
Labels: module: cuda,triaged

### 🐛 Describe the bug

Since the pytorch 2.1.0, the forward propagation speed of ``nn.Linear`` against high-dimensional tensors, i.e. tensors with four, five, or even more dimensions, is noticeably slower than pytorch 2.0.0 and 2.0.1. I learn that ```torch.backends.cuda.matmul.allow_tf32``` can affect the speed of ```nn.Linear``` from the issue 118349 and 119000, but in this case setting it ```True``` or ```False``` has little effect on the running time.

Here is the benchmark script we used to evaluate the speed. 
GPU: NVIDIA V100 16GB
CUDA: 11.8
Python: 3.10.14

```python
import torch
import time
import torch.nn as nn

device = 'cuda'
dim = (8, 32, 64, 5, 32)
tf_32_enablement = True
retry_times = 200000

torch.backends.cuda.matmul.allow_tf32 = tf_32_enablement

module = nn.Linear(dim[-1], dim[-1], bias = True, device = device)

input_data = torch.randn(*dim, device = device)

start_time = time.time()
for _ in range(retry_times):
    output = module(input_data)
end_time = time.time()

print(f'PyTorch Version: {torch.__version__}.')
print(f'We use PyTorch compiled against CUDA {torch.version.cuda}.')
print(f'Compute time: {end_time - start_time}s.')
```

Following is the compute time:

```
2.0.0: 13.82092022895813s.
2.0.1: 13.836414337158203s.
2.1.0: 53.548094034194946s.  <------ slow
2.1.1: 53.52842974662781s.
2.1.2: 53.52682709693909s.
2.2.0: 53.527302503585815s.
2.2.1: 53.52418661117554s.
2.2.2: 53.52575945854187s.
2.3.0: 53.58273243904114s.
```

It shows when the input tensor has shape ```(8, 32, 64, 5, 32)```, the forward propagation speed of ```nn.Linear``` sees an noticeable drop from 2.0.1 to 2.1.0. The benchmark results on an RTX 3090(TDP limit: 310W) agree with this finding:

```
2.0.1 + cu117: 14.966339826583862s
2.1.2 + cu121: 39.45850372314453s   
```

Results from another benchmark script further show how the propagation time of ```nn.Linear``` from different pytorch releases increases as the input dimension increases.

```python
import torch
import time
import torch.nn as nn
import sys

random_seed = 12345
device = 'cuda'
data_dims = range(10)
dim_number = 8
tf_32_enablement = True
number_of_loops = 1000

torch.manual_seed(random_seed)
torch.backends.cuda.matmul.allow_tf32 = tf_32_enablement

recorded_times = []
module = nn.Linear(dim_number, dim_number, bias = True, device = device)

for additional_dim in data_dims:
    input_data = torch.randn((dim_number,) * (additional_dim + 1), device = device)

    start_time = time.time()
    for _ in range(number_of_loops):
        output = module(input_data)
    end_time = time.time()
    recorded_times.append(end_time - start_time)

print(f'PyTorch Version: {torch.__version__}.')
print(f'Python Version: {sys.version_info}.')
print(f'We use PyTorch compiled against CUDA {torch.version.cuda}.')
for dim, t in zip(data_dims, recorded_times):
    print(f'Dim: {(dim_number,) * (dim + 1)} \t -----> computation time: {t}s.')
```

Results:
```
2.0.0
PyTorch Version: 2.0.0.
Python Version: sys.version_info(major=3, minor=10, micro=14, releaselevel='final', serial=0).
We use PyTorch compiled against CUDA 11.8.
Dim: (8,)        -----> computation time: 0.05569744110107422s.
Dim: (8, 8)      -----> computation time: 0.0230557918548584s.
Dim: (8, 8, 8)   -----> computation time: 0.02665257453918457s.
Dim: (8, 8, 8, 8)        -----> computation time: 0.030395030975341797s.
Dim: (8, 8, 8, 8, 8)     -----> computation time: 0.03008127212524414s.
Dim: (8, 8, 8, 8, 8, 8)          -----> computation time: 0.03304100036621094s.
Dim: (8, 8, 8, 8, 8, 8, 8)       -----> computation time: 0.03186631202697754s.
Dim: (8, 8, 8, 8, 8, 8, 8, 8)    -----> computation time: 0.369830846786499s.
Dim: (8, 8, 8, 8, 8, 8, 8, 8, 8)         -----> computation time: 3.3960494995117188s.
Dim: (8, 8, 8, 8, 8, 8, 8, 8, 8, 8)      -----> computation time: 27.773303508758545s.

2.0.1
PyTorch Version: 2.0.1.
Python Version: sys.version_info(major=3, minor=10, micro=14, releaselevel='final', serial=0).
We use PyTorch compiled against CUDA 11.8.
Dim: (8,)        -----> computation time: 0.05523109436035156s.
Dim: (8, 8)      -----> computation time: 0.023726463317871094s.
Dim: (8, 8, 8)   -----> computation time: 0.02841949462890625s.
Dim: (8, 8, 8, 8)        -----> computation time: 0.030512094497680664s.
Dim: (8, 8, 8, 8, 8)     -----> computation time: 0.03201746940612793s.
Dim: (8, 8, 8, 8, 8, 8)          -----> computation time: 0.03427457809448242s.
Dim: (8, 8, 8, 8, 8, 8, 8)       -----> computation time: 0.032979726791381836s.
Dim: (8, 8, 8, 8, 8, 8, 8, 8)    -----> computation time: 0.3679842948913574s.
Dim: (8, 8, 8, 8, 8, 8, 8, 8, 8)         -----> computation time: 3.3936691284179688s.
Dim: (8, 8, 8, 8, 8, 8, 8, 8, 8, 8)      -----> computation time: 27.76928973197937s.

2.1.0
PyTorch Version: 2.1.0.
Python Version: sys.version_info(major=3, minor=10, micro=14, releaselevel='final', serial=0).
We use PyTorch compiled against CUDA 11.8.
Dim: (8,)        -----> computation time: 0.04741096496582031s.
Dim: (8, 8)      -----> computation time: 0.024776935577392578s.
Dim: (8, 8, 8)   -----> computation time: 0.029422760009765625s.
Dim: (8, 8, 8, 8)        -----> computation time: 0.02626514434814453s.
Dim: (8, 8, 8, 8, 8)     -----> computation time: 0.02653956413269043s.
Dim: (8, 8, 8, 8, 8, 8)          -----> computation time: 0.03148913383483887s.
Dim: (8, 8, 8, 8, 8, 8, 8)       -----> computation time: 0.03050541877746582s.
Dim: (8, 8, 8, 8, 8, 8, 8, 8)    -----> computation time: 0.6981430053710938s.
Dim: (8, 8, 8, 8, 8, 8, 8, 8, 8)         -----> computation time: 5.044178247451782s.
Dim: (8, 8, 8, 8, 8, 8, 8, 8, 8, 8)      -----> computation time: 41.3300883769989s.

2.2.0
PyTorch Version: 2.2.0.
Python Version: sys.version_info(major=3, minor=10, micro=14, releaselevel='final', serial=0).
We use PyTorch compiled against CUDA 11.8.
Dim: (8,)        -----> computation time: 0.04648089408874512s.
Dim: (8, 8)      -----> computation time: 0.024461746215820312s.
Dim: (8, 8, 8)   -----> computation time: 0.029138565063476562s.
Dim: (8, 8, 8, 8)        -----> computation time: 0.02600836753845215s.
Dim: (8, 8, 8, 8, 8)     -----> computation time: 0.02669215202331543s.
Dim: (8, 8, 8, 8, 8, 8)          -----> computation time: 0.03170037269592285s.
Dim: (8, 8, 8, 8, 8, 8, 8)       -----> computation time: 0.030368804931640625s.
Dim: (8, 8, 8, 8, 8, 8, 8, 8)    -----> computation time: 0.6984641551971436s.
Dim: (8, 8, 8, 8, 8, 8, 8, 8, 8)         -----> computation time: 5.043280363082886s.
Dim: (8, 8, 8, 8, 8, 8, 8, 8, 8, 8)      -----> computation time: 41.32612371444702s.
```


### Versions

All results come from fresh conda environments with only ```pytorch``` and dependencies installed. All tested pytorch releases are built against CUDA 11.8. I only provide the version information of one used conda environment.

```
PyTorch version: 2.3.0
Is debug build: False
CUDA used to build PyTorch: 11.8
ROCM used to build PyTorch: N/A

OS: Red Hat Enterprise Linux Server release 7.9 (Maipo) (x86_64)
GCC version: (GCC) 4.8.5 20150623 (Red Hat 4.8.5-44)
Clang version: 3.4.2 (tags/RELEASE_34/dot2-final)
CMake version: version 2.8.12.2
Libc version: glibc-2.17

Python version: 3.10.14 | packaged by conda-forge | (main, Mar 20 2024, 12:45:18) [GCC 12.3.0] (64-bit runtime)
Python platform: Linux-3.10.0-1160.114.2.el7.x86_64-x86_64-with-glibc2.17
Is CUDA available: True
CUDA runtime version: Could not collect
CUDA_MODULE_LOADING set to: LAZY
GPU models and configuration: GPU 0: Tesla V100-PCIE-16GB
Nvidia driver version: 550.54.15
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
CPU(s):                28
On-line CPU(s) list:   0-27
Thread(s) per core:    2
Core(s) per socket:    14
Socket(s):             1
NUMA node(s):          1
Vendor ID:             GenuineIntel
CPU family:            6
Model:                 85
Model name:            Intel(R) Xeon(R) Gold 6132 CPU @ 2.60GHz
Stepping:              4
CPU MHz:               1315.075
CPU max MHz:           3700.0000
CPU min MHz:           1000.0000
BogoMIPS:              5200.00
Virtualization:        VT-x
L1d cache:             32K
L1i cache:             32K
L2 cache:              1024K
L3 cache:              19712K
NUMA node0 CPU(s):     0-27
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 aperfmperf eagerfpu 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 epb cat_l3 cdp_l3 invpcid_single intel_ppin ssbd mba rsb_ctxsw ibrs ibpb stibp tpr_shadow vnmi flexpriority ept vpid fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 erms invpcid rtm cqm mpx rdt_a avx512f avx512dq rdseed adx smap clflushopt clwb intel_pt avx512cd avx512bw avx512vl xsaveopt xsavec xgetbv1 cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local dtherm ida arat pln pts hwp hwp_act_window hwp_pkg_req pku ospke md_clear spec_ctrl intel_stibp flush_l1d arch_capabilities

Versions of relevant libraries:
[pip3] numpy==1.26.4
[pip3] torch==2.3.0
[pip3] torchaudio==2.3.0
[pip3] torchvision==0.18.0
[pip3] triton==2.3.0
[conda] blas                      2.116                       mkl    conda-forge
[conda] blas-devel                3.9.0            16_linux64_mkl    conda-forge
[conda] ffmpeg                    4.3                  hf484d3e_0    pytorch
[conda] libblas                   3.9.0            16_linux64_mkl    conda-forge
[conda] libcblas                  3.9.0            16_linux64_mkl    conda-forge
[conda] libjpeg-turbo             2.0.0                h9bf148f_0    pytorch
[conda] liblapack                 3.9.0            16_linux64_mkl    conda-forge
[conda] liblapacke                3.9.0            16_linux64_mkl    conda-forge
[conda] mkl                       2022.1.0           h84fe81f_915    conda-forge
[conda] mkl-devel                 2022.1.0           ha770c72_916    conda-forge
[conda] mkl-include               2022.1.0           h84fe81f_915    conda-forge
[conda] numpy                     1.26.4          py310hb13e2d6_0    conda-forge
[conda] pytorch                   2.3.0           py3.10_cuda11.8_cudnn8.7.0_0    pytorch
[conda] pytorch-cuda              11.8                 h7e8668a_5    pytorch
[conda] pytorch-mutex             1.0                        cuda    pytorch
[conda] torchaudio                2.3.0               py310_cu118    pytorch
[conda] torchtriton               2.3.0                     py310    pytorch
[conda] torchvision               0.18.0              py310_cu118    pytorch
```

cc @ptrblck