Repository: pytorch
Issue: [BUG] Poor torch.bmm performance on H100
Labels: module: performance,module: cuda,triaged,module: cublas,matrix multiplication

### 🐛 Describe the bug

I was recently testing bmm performance on H100. When batch size is 1, the number is normal and expected. However, when I increase batch size to 2 and 4, the TFLOPS number drops significantly. I think the bug stems from cublas because I can obtain similar bad numbers by implementing a CUDA micro-benchmakring script directly using `cublasGemmStridedBatchedEx`.

- batch size 1: 742.7 TFLOPS
- batch size 2: 549.5 TFLOPS
- batch size 4: 542.9 TFLOPS

The pytorch results can be reproduced using the script below with command: `python3 benchmark.py --batch-size 1` with `nvcr.io/ea-bignlp/bignlp-training` container.
```
import argparse
import torch


pt_dtype_mappings = {
    "float": torch.float,
    "half": torch.half,
    "float16": torch.float16,
    "bfloat16": torch.bfloat16,
}


def parse_args():
    """Define command-line arguments"""
    parser = argparse.ArgumentParser()

    parser.add_argument("--batch-size", type=int, default=1, help="Batch size")
    parser.add_argument("--sequence-length", type=int, default=2048, help="Sequence length")
    parser.add_argument("--hidden-size", type=int, default=8192, help="Hidden size")

    parser.add_argument("--warmup", type=int, default=10, help="Warmp-up iterations")
    parser.add_argument(
        "--iterations",
        type=int,
        default=100,
        help="The number of repeat matmul iterations",
    )
    parser.add_argument("--dtype", type=str, default="bfloat16", help="Precision of the tensor")
    parser.add_argument("--gpu-idx", type=int, default=0, help="GPU index")

    return parser.parse_args()


def run(
    batch_size, sequence_size, hidden_size, warmup=10, iterations=100, dtype="float", gpu_idx=0
):
    ngpu = torch.cuda.device_count()
    assert gpu_idx < ngpu, f"GPU index {gpu_idx} is out of range ({ngpu} GPUs available)"

    torch.cuda.set_device(gpu_idx)
    a = torch.randn(batch_size, sequence_size, hidden_size, dtype=dtype, device=f"cuda:{gpu_idx}")
    b = torch.randn(batch_size, hidden_size, sequence_size, dtype=dtype, device=f"cuda:{gpu_idx}")
    c = torch.randn(batch_size, sequence_size, sequence_size, dtype=dtype, device=f"cuda:{gpu_idx}")

    for _ in range(warmup):
        torch.bmm(a, b, out=c)

    torch.cuda.synchronize()
    start = torch.cuda.Event(enable_timing=True)
    end = torch.cuda.Event(enable_timing=True)

    start.record()
    for _ in range(iterations):
        torch.bmm(a, b, out=c)
    end.record()

    torch.cuda.synchronize()

    tflops = (
        2
        * batch_size
        * sequence_size**2
        * hidden_size
        * iterations
        / start.elapsed_time(end)
        / 10**9
    )
    print(
        f"The TFLOPS for computing batched matmul between {dtype} tensor "
        f"({batch_size}, {sequence_size}, {hidden_size}) and "
        f"({batch_size}, {hidden_size}, {sequence_size}) on GPU {gpu_idx} is {tflops}"
    )


if __name__ == "__main__":
    args = parse_args()
    batch_size = args.batch_size
    sequence_size = args.sequence_length
    hidden_size = args.hidden_size
    warmup = args.warmup
    iterations = args.iterations
    if args.dtype not in pt_dtype_mappings:
        raise ValueError(f"Unsupported dtype: {args.dtype}")
    dtype = pt_dtype_mappings[args.dtype]
    gpu_idx = args.gpu_idx

    run(batch_size, sequence_size, hidden_size, warmup, iterations, dtype, gpu_idx)
```

### Versions

```
PyTorch version: 1.14.0a0+44dac51
Is debug build: False
CUDA used to build PyTorch: 12.0
ROCM used to build PyTorch: N/A

OS: Ubuntu 20.04.5 LTS (x86_64)
GCC version: (Ubuntu 9.4.0-1ubuntu1~20.04.1) 9.4.0
Clang version: Could not collect
CMake version: version 3.24.1
Libc version: glibc-2.31

Python version: 3.8.10 (default, Nov 14 2022, 12:59:47)  [GCC 9.4.0] (64-bit runtime)
Python platform: Linux-5.15.0-71-generic-x86_64-with-glibc2.29
Is CUDA available: True
CUDA runtime version: 12.0.140
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: 525.105.17
cuDNN version: Probably one of the following:
/usr/lib/x86_64-linux-gnu/libcudnn.so.8.7.0
/usr/lib/x86_64-linux-gnu/libcudnn_adv_infer.so.8.7.0
/usr/lib/x86_64-linux-gnu/libcudnn_adv_train.so.8.7.0
/usr/lib/x86_64-linux-gnu/libcudnn_cnn_infer.so.8.7.0
/usr/lib/x86_64-linux-gnu/libcudnn_cnn_train.so.8.7.0
/usr/lib/x86_64-linux-gnu/libcudnn_ops_infer.so.8.7.0
/usr/lib/x86_64-linux-gnu/libcudnn_ops_train.so.8.7.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
Byte Order:                      Little Endian
Address sizes:                   46 bits physical, 57 bits virtual
CPU(s):                          224
On-line CPU(s) list:             0-223
Thread(s) per core:              2
Core(s) per socket:              56
Socket(s):                       2
NUMA node(s):                    2
Vendor ID:                       GenuineIntel
CPU family:                      6
Model:                           143
Model name:                      Intel(R) Xeon(R) Platinum 8480+
Stepping:                        8
Frequency boost:                 enabled
CPU MHz:                         1895.558
CPU max MHz:                     2001.0000
CPU min MHz:                     800.0000
BogoMIPS:                        4000.00
Virtualization:                  VT-x
L1d cache:                       5.3 MiB
L1i cache:                       3.5 MiB
L2 cache:                        224 MiB
L3 cache:                        210 MiB
NUMA node0 CPU(s):               0-55,112-167
NUMA node1 CPU(s):               56-111,168-223
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:          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:   Not affected
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 tsc_known_freq 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 cpuid_fault epb cat_l3 cat_l2 cdp_l3 invpcid_single cdp_l2 ssbd mba ibrs ibpb stibp ibrs_enhanced tpr_shadow vnmi flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid cqm rdt_a avx512f avx512dq rdseed adx smap avx512ifma clflushopt clwb intel_pt avx512cd sha_ni avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local split_lock_detect avx_vnni avx512_bf16 wbnoinvd dtherm ida arat pln pts avx512vbmi umip pku ospke waitpkg avx512_vbmi2 gfni vaes vpclmulqdq avx512_vnni avx512_bitalg tme avx512_vpopcntdq la57 rdpid bus_lock_detect cldemote movdiri movdir64b enqcmd fsrm md_clear serialize tsxldtrk pconfig arch_lbr amx_bf16 avx512_fp16 amx_tile amx_int8 flush_l1d arch_capabilities

Versions of relevant libraries:
[pip3] mypy-extensions==1.0.0
[pip3] numpy==1.22.2
[pip3] pytorch-lightning==1.9.4
[pip3] pytorch-quantization==2.1.2
[pip3] torch==1.14.0a0+44dac51
[pip3] torch-tensorrt==1.4.0.dev0
[pip3] torchmetrics==0.9.1
[pip3] torchtext==0.13.0a0+fae8e8c
[pip3] torchvision==0.15.0a0
[pip3] triton==2.0.0
[pip3] tritonclient==2.22.4
[conda] Could not collect
```


cc @ngimel @csarofeen @ptrblck @xwang233