Transformer performance drop due to slow PyTorch GEMMs
Labels: module: performance, module: cuda, triaged

### 🐛 Describe the bug

While trying to debug our transformer performance, we see the following problem. When looking at the performance of different matrix multiplications using `torch.nn.functional.linear()`, we see a huge drop in performance for GEMMs of size (2048, 4, 82432)x(82432, 20608) through (2048, 4,  89088)x(89088, 22272) as displayed in the below figures. 

![image](https://github.com/pytorch/pytorch/assets/74274091/0a59c531-2cf7-4da3-b93c-f7fa7eec2892)

![image](https://github.com/pytorch/pytorch/assets/74274091/1c64a607-d177-4a67-bf6c-e5231b41d0ac)

In the area of bad performance, there is a large drop in L2 cache hit rate, as well as a shifting in the tiling dimensions of the kernel call (128x256x64 to 256x128x64). When investigating this using Cutlass, we saw that it does not share the performance drop PyTorch does for these GEMM sizes. Why do we see this poor performance in GEMMs, and how can we avoid this poor performance?

full kernel names outside of dip: `ampere_fp16_s16816gemm_fp16_128x256_ldg8_f2f_stages_64x3_tn`
within dip: `ampere_fp16_s16816gemm_fp16_256x128_ldg8_f2f_stages_64x3_tn`

full script used to produce figures:

```
import time
import torch
def benchmark_mm_b(m, n, k, b=None, num_iterations=100):
    
    B = torch.randn(k, n).half().to("cuda:0")
    if b is None:
        A = torch.randn(m, n).half().to("cuda:0")
        b=1
        C = torch.empty(m, k).half().to("cuda:0")
    else:
        A = torch.randn(b,m,n).half().to("cuda:0")
        C = torch.empty(b,m, k).half().to("cuda:0")
    num_warmup_iterations = 50
    for i in range(num_warmup_iterations + num_iterations):
        if i == num_warmup_iterations:
            start_time = time.time()
        with torch.no_grad():
            torch.nn.functional.linear(A, B, out=C)
        torch.cuda.synchronize()
    elapsed_time = (time.time() - start_time) / num_iterations
    if b is None:
        print(f"Elapsed time for {m}x{n}x{k}: {elapsed_time:.3f}")
        print(f"Throughput (in TFLOP/s) for {m}x{n}x{k}: {(2 * m * n * k) / (elapsed_time * 10**12):.3f}")
    else:
        print(f"Elapsed time for {m}x{n}x{k}, b={b}: {elapsed_time:.4f}")
        print(f"Throughput (in TFLOP/s) for {m}x{n}x{k}, b={b}: "
          f"{(2 * b * m * n * k) / (elapsed_time * 10**12):.3f}") 
    print("-" * 80)


for h in range(20608-128, 22272+128+64, 64):
        benchmark_mm_b(4, 4*h, h, b=2048)
```

### Versions

```
Collecting environment information...
PyTorch version: 2.0.1+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.2) 9.4.0
Clang version: Could not collect
CMake version: version 3.26.4
Libc version: glibc-2.31

Python version: 3.8.16 (default, Mar  2 2023, 03:21:46)  [GCC 11.2.0] (64-bit runtime)
Python platform: Linux-5.15.0-1037-aws-x86_64-with-glibc2.17
Is CUDA available: True
CUDA runtime version: 11.7.64
CUDA_MODULE_LOADING set to: LAZY
GPU models and configuration: 
GPU 0: NVIDIA A100-SXM4-40GB
GPU 1: NVIDIA A100-SXM4-40GB
GPU 2: NVIDIA A100-SXM4-40GB
GPU 3: NVIDIA A100-SXM4-40GB
GPU 4: NVIDIA A100-SXM4-40GB
GPU 5: NVIDIA A100-SXM4-40GB
GPU 6: NVIDIA A100-SXM4-40GB
GPU 7: NVIDIA A100-SXM4-40GB

Nvidia driver version: 525.85.12
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:                   46 bits physical, 48 bits virtual
CPU(s):                          96
On-line CPU(s) list:             0-95
Thread(s) per core:              2
Core(s) per socket:              24
Socket(s):                       2
NUMA node(s):                    2
Vendor ID:                       GenuineIntel
CPU family:                      6
Model:                           85
Model name:                      Intel(R) Xeon(R) Platinum 8275CL CPU @ 3.00GHz
Stepping:                        7
CPU MHz:                         2999.998
BogoMIPS:                        5999.99
Hypervisor vendor:               KVM
Virtualization type:             full
L1d cache:                       1.5 MiB
L1i cache:                       1.5 MiB
L2 cache:                        48 MiB
L3 cache:                        71.5 MiB
NUMA node0 CPU(s):               0-23,48-71
NUMA node1 CPU(s):               24-47,72-95
Vulnerability Itlb multihit:     KVM: Mitigation: VMX unsupported
Vulnerability L1tf:              Mitigation; PTE Inversion
Vulnerability Mds:               Vulnerable: Clear CPU buffers attempted, no microcode; SMT Host state unknown
Vulnerability Meltdown:          Mitigation; PTI
Vulnerability Mmio stale data:   Vulnerable: Clear CPU buffers attempted, no microcode; SMT Host state unknown
Vulnerability Retbleed:          Vulnerable
Vulnerability Spec store bypass: Vulnerable
Vulnerability Spectre v1:        Mitigation; usercopy/swapgs barriers and __user pointer sanitization
Vulnerability Spectre v2:        Mitigation; Retpolines, STIBP disabled, 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 ss ht syscall nx pdpe1gb rdtscp lm constant_tsc arch_perfmon rep_good nopl xtopology nonstop_tsc cpuid aperfmperf tsc_known_freq pni pclmulqdq monitor ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand hypervisor lahf_lm abm 3dnowprefetch invpcid_single pti fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid mpx avx512f avx512dq rdseed adx smap clflushopt clwb avx512cd avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves ida arat pku ospke

Versions of relevant libraries:
[pip3] numpy==1.24.3
[pip3] torch==2.0.1
[pip3] torchaudio==2.0.2
[pip3] torchvision==0.15.2
[pip3] triton==2.0.0
[conda] cudatoolkit               11.7.0              hd8887f6_10    conda-forge
[conda] numpy                     1.24.3                   pypi_0    pypi
[conda] torch                     1.13.0+cu116             pypi_0    pypi
[conda] torchaudio                0.13.0+cu116             pypi_0    pypi
[conda] torchvision               0.14.0+cu116             pypi_0    pypi
[conda] triton                    2.0.0                    pypi_0    pypi
```

cc @ptrblck