Repository: pytorch
Issue: torch.set_float32_matmul_precision('medium') slower than regular BF16 matmul
Labels: module: performance,module: cuda,triaged

### 🐛 Describe the bug

According to the docs, setting the torch float32 matmul precision to 'medium' uses BF16 for the internal GEMM with a FP32 accumulator and returns the FP32 accumulator. My benchmark code (see below) says this is slower than rounding from FP32 to BF16 and then doing the matmul in BF16 and returning a BF16 accumulator. Why is this true? Shouldn't both be using the same BF16 tensorcores and the difference is in the accumulator precision? Is the overhead of using a higher precision accumulator *that much*?

Benchmark script:
```
import torch
import time

sizes = [512, 1024, 2048, 4096, 8192, 16384]
iters = 100

print('Regular FP32')

for sz in sizes:
    a = torch.randn(sz, sz, device=0)
    b = torch.randn(sz, sz, device=0)
    total = 0
    for i in range(iters):
        s = time.time()
        c = a @ b
        torch.cuda.synchronize()
        total += time.time() - s
    print(sz, total / iters)
print()

print('FP32 w/BF16 internal matmul')

torch.set_float32_matmul_precision('medium')
for sz in sizes:
    a = torch.randn(sz, sz, device=0)
    b = torch.randn(sz, sz, device=0)
    total = 0
    for i in range(iters):
        s = time.time()
        c = a @ b
        torch.cuda.synchronize()
        total += time.time() - s
    print(sz, total / iters)
print()

print('regular BF16')
for sz in sizes:
    a = torch.randn(sz, sz, device=0)
    b = torch.randn(sz, sz, device=0)
    total = 0
    for i in range(iters):
        s = time.time()
        c = a.to(torch.bfloat16) @ b.to(torch.bfloat16)
        torch.cuda.synchronize()
        total += time.time() - s
    print(sz, total / iters)
```

Output on a H100 SXM:
```
Regular FP32
512 0.0016167497634887696
1024 7.171869277954102e-05
2048 0.0005328941345214843
4096 0.0026724767684936524
8192 0.021244921684265138
16384 0.16401963710784911

FP32 w/BF16 internal matmul
512 0.00036259174346923827
1024 0.00013562202453613282
2048 0.0001180720329284668
4096 0.0004148006439208984
8192 0.0031256651878356933
16384 0.02780592679977417

regular BF16
512 0.0008567142486572266
1024 0.00077117919921875
2048 7.407903671264648e-05
4096 0.00030952930450439453
8192 0.001969149112701416
16384 0.014865560531616211
```



### Versions

```
Collecting environment information...
PyTorch version: 2.4.0+cu121
Is debug build: False
CUDA used to build PyTorch: 12.1
ROCM used to build PyTorch: N/A

OS: Ubuntu 22.04.3 LTS (x86_64)
GCC version: (Ubuntu 11.4.0-1ubuntu1~22.04) 11.4.0
Clang version: Could not collect
CMake version: version 3.22.1
Libc version: glibc-2.35

Python version: 3.12.4 | packaged by Anaconda, Inc. | (main, Jun 18 2024, 15:12:24) [GCC 11.2.0] (64-bit runtime)
Python platform: Linux-5.15.0-94-generic-x86_64-with-glibc2.35
Is CUDA available: True
CUDA runtime version: Could not collect
CUDA_MODULE_LOADING set to: LAZY
GPU models and configuration: 
GPU 0: NVIDIA H100 80GB HBM3
GPU 1: NVIDIA H100 80GB HBM3
GPU 2: NVIDIA H100 80GB HBM3
GPU 3: NVIDIA H100 80GB HBM3
GPU 4: NVIDIA H100 80GB HBM3
GPU 5: NVIDIA H100 80GB HBM3
GPU 6: NVIDIA H100 80GB HBM3
GPU 7: NVIDIA H100 80GB HBM3

Nvidia driver version: 535.154.05
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
Address sizes:                      48 bits physical, 57 bits virtual
Byte Order:                         Little Endian
CPU(s):                             176
On-line CPU(s) list:                0-175
Vendor ID:                          GenuineIntel
Model name:                         Intel(R) Xeon(R) Platinum 8468V
CPU family:                         6
Model:                              143
Thread(s) per core:                 2
Core(s) per socket:                 44
Socket(s):                          2
Stepping:                           8
BogoMIPS:                           4800.00
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 cpuid tsc_known_freq pni pclmulqdq vmx ssse3 fma cx16 pdcm pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand hypervisor lahf_lm abm 3dnowprefetch cpuid_fault invpcid_single ssbd ibrs ibpb stibp ibrs_enhanced tpr_shadow vnmi flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid avx512f avx512dq rdseed adx smap avx512ifma clflushopt clwb avx512cd sha_ni avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves avx_vnni avx512_bf16 wbnoinvd arat avx512vbmi umip pku ospke waitpkg avx512_vbmi2 gfni vaes vpclmulqdq avx512_vnni avx512_bitalg avx512_vpopcntdq la57 rdpid bus_lock_detect cldemote movdiri movdir64b fsrm md_clear serialize tsxldtrk amx_bf16 avx512_fp16 amx_tile amx_int8 arch_capabilities
Virtualization:                     VT-x
Hypervisor vendor:                  KVM
Virtualization type:                full
L1d cache:                          5.5 MiB (176 instances)
L1i cache:                          5.5 MiB (176 instances)
L2 cache:                           352 MiB (88 instances)
L3 cache:                           32 MiB (2 instances)
NUMA node(s):                       2
NUMA node0 CPU(s):                  0-87
NUMA node1 CPU(s):                  88-175
Vulnerability Gather data sampling: Not affected
Vulnerability Itlb multihit:        Not affected
Vulnerability L1tf:                 Not affected
Vulnerability Mds:                  Not affected
Vulnerability Meltdown:             Not affected
Vulnerability Mmio stale data:      Unknown: No mitigations
Vulnerability Retbleed:             Not affected
Vulnerability Spec rstack overflow: 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; Enhanced IBRS, IBPB conditional, RSB filling, PBRSB-eIBRS SW sequence
Vulnerability Srbds:                Not affected
Vulnerability Tsx async abort:      Mitigation; TSX disabled

Versions of relevant libraries:
[pip3] numpy==1.26.4
[pip3] torch==2.4.0
[pip3] triton==3.0.0
[conda] numpy                     1.26.4                   pypi_0    pypi
[conda] torch                     2.4.0                    pypi_0    pypi
[conda] triton                    3.0.0                    pypi_0    pypi
```

cc @msaroufim @ptrblck