Repository: pytorch
Issue: There is a big precision error between A100 and 3090 when using torch.matmul with fp16 precision
Labels: module: cuda,triaged,module: half

### 🐛 Describe the bug

There are two intputs:
attention_scores_clamp_softmax.npy and andattention_values.npy

Test data:
The copy them with different names and there md5 value are the same:
2c93eb5671266aeb561724e0d487e2e5  38_attention_scores_clamp_softmax.npy
6316a816fdecde5084160cb9ccd10889  38_attention_values.npy
2c93eb5671266aeb561724e0d487e2e5  41_attention_scores_clamp_softmax.npy
6316a816fdecde5084160cb9ccd10889  41_attention_values.npy
2c93eb5671266aeb561724e0d487e2e5  42_attention_scores_clamp_softmax.npy
6316a816fdecde5084160cb9ccd10889  42_attention_values.npy

Hardware & Software information:
38 Server is a Server with 3090 NVIDIA Card
Driver: 530.30.02
CUDA: 12.1
torch                   2.0.1
torchaudio              2.0.2
torchvision             0.15.2


41 Server is a Server with A100 NVIDIA Card torch
Driver: 530.30.02
CUDA: 12.1
torch                   2.0.1
torchaudio              2.0.2
torchvision             0.15.2


42 Server is a Server with A100 NVIDIA Card torch
Driver: 525.125.06
CUDA: 12.0
torch                   2.0.1
torchaudio              2.0.2
torchvision             0.15.2


1st, run generate_output_38.py on 3090 Server
2nd, run generate_output_41.py on A100 Server
3rd, run generate_output_42.py on A100 Server
4th, copy all files to 38 Server and 41 Server
5th, run cmp_output_fp16.py on 3090 Server
6th, run cmp_output_fp16.py on A100 Server
7th, run cmp_output_fp16.py on A100 Server

Then get results below:

On 41 Server(A100):
$ python cmp_output_fp16.py
matmul_out_38 == matmul_out_42 False
matmul_out_41 == matmul_out_42 True
allclose torch output between 38 and 42  False
allclose torch output between 38 and 41  False
allclose torch output between 41 and 42  True

On 38 Server(3090):
$ python cmp_output_fp16.py
matmul_out_38 == matmul_out_42 False
matmul_out_41 == matmul_out_42 True
allclose torch output between 38 and 42  False
allclose torch output between 38 and 41  False
allclose torch output between 41 and 42  True

On 42 Server(A100):
$ python cmp_output_fp16.py
matmul_out_38 == matmul_out_42 False
matmul_out_41 == matmul_out_42 True
allclose torch output between 38 and 42  False
allclose torch output between 38 and 41  False
allclose torch output between 41 and 42  True

It seems there is a big gap between the value generated on 3090 and A100.

Then, check the md5 value of each outputs and found the tensor from 41 and 42 (A100) are the same:
5d77b2f48b27e099b10e5bdee5f1a38b  38_output.npy
4654e5fe4740dc4480953585379ea638  41_output.npy
4654e5fe4740dc4480953585379ea638  42_output.npy

Change the atol and rtol and found the following results:
test_cmp_output_fp16_threshold.py
When np.allclose(matmul_out_38, matmul_out_42, rtol=1e-05, atol=1e-03)} the 3090 and A100 could np.allclose return True

Attachment 1 generate_output_38.py

```
import torch
import numpy as np

x = torch.from_numpy(np.load('38_attention_scores_clamp_softmax.npy')).cuda().half()
y = torch.from_numpy(np.load('38_attention_values.npy')).cuda().half()

class MatMulNetwork(torch.nn.Module):
    def __init__(self):
        super(MatMulNetwork, self).__init__()

    def forward(self, x, y):
        return torch.matmul(x, y)

net = MatMulNetwork()
net.cuda()
net.half()
net.eval()
output = net(x, y)

np.save("38_output.npy", output.cpu().numpy())
print(output)

```
Attachment 2 cmp_output_fp16.py

```
import numpy as np
import torch


torch_matmul_38 = "38_output.npy"
torch_matmul_42 = "42_output.npy"
torch_matmul_41 = "41_output.npy"

device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
matmul_out_38 = np.load(torch_matmul_38)
matmul_out_42 = np.load(torch_matmul_42)
matmul_out_41 = np.load(torch_matmul_41)

print(f"matmul_out_38 == matmul_out_42 {np.array_equal(matmul_out_38, matmul_out_42)}")
print(f"matmul_out_41 == matmul_out_42 {np.array_equal(matmul_out_41, matmul_out_42)}")
print(f"allclose torch output between 38 and 42  {np.allclose(matmul_out_38, matmul_out_42, rtol=1e-05, atol=1e-08)}")
print(f"allclose torch output between 38 and 41  {np.allclose(matmul_out_38, matmul_out_41, rtol=1e-05, atol=1e-08)}")
print(f"allclose torch output between 41 and 42  {np.allclose(matmul_out_41, matmul_out_42, rtol=1e-05, atol=1e-08)}")
```




### Versions

Collecting environment information...
PyTorch version: 2.0.1
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.1) 9.4.0
Clang version: Could not collect
CMake version: version 3.26.3
Libc version: glibc-2.31

Python version: 3.10.8 (main, Nov 24 2022, 14:13:03) [GCC 11.2.0] (64-bit runtime)
Python platform: Linux-5.15.0-43-generic-x86_64-with-glibc2.31
Is CUDA available: True
CUDA runtime version: 11.7.99
CUDA_MODULE_LOADING set to: LAZY
GPU models and configuration:
GPU 0: NVIDIA GeForce RTX 3090
GPU 1: NVIDIA GeForce RTX 3090
GPU 2: NVIDIA GeForce RTX 3090
GPU 3: NVIDIA GeForce RTX 3090
GPU 4: NVIDIA GeForce RTX 3090
GPU 5: NVIDIA GeForce RTX 3090
GPU 6: NVIDIA GeForce RTX 3090
GPU 7: NVIDIA GeForce RTX 3090

Nvidia driver version: 530.30.02
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, 57 bits virtual
CPU(s):                          128
On-line CPU(s) list:             0-127
Thread(s) per core:              2
Core(s) per socket:              32
Socket(s):                       2
NUMA node(s):                    2
Vendor ID:                       GenuineIntel
CPU family:                      6
Model:                           106
Model name:                      Intel(R) Xeon(R) Platinum 8358 CPU @ 2.60GHz
Stepping:                        6
CPU MHz:                         800.000
CPU max MHz:                     3400.0000
CPU min MHz:                     800.0000
BogoMIPS:                        5200.00
Virtualization:                  VT-x
L1d cache:                       3 MiB
L1i cache:                       2 MiB
L2 cache:                        80 MiB
L3 cache:                        96 MiB
NUMA node0 CPU(s):               0-31,64-95
NUMA node1 CPU(s):               32-63,96-127
Vulnerability Itlb multihit:     Not affected
Vulnerability L1tf:              Not affected
Vulnerability Mds:               Not affected
Vulnerability Meltdown:          Not affected
Vulnerability Mmio stale data:   Mitigation; Clear CPU buffers; SMT vulnerable
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
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 pni pclmulqdq dtes64 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 invpcid_single intel_ppin 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 wbnoinvd dtherm ida arat pln pts avx512vbmi umip pku ospke avx512_vbmi2 gfni vaes vpclmulqdq avx512_vnni avx512_bitalg tme avx512_vpopcntdq la57 rdpid fsrm md_clear pconfig flush_l1d arch_capabilities

Versions of relevant libraries:
[pip3] mypy-extensions==1.0.0
[pip3] numpy==1.25.0
[pip3] torch==2.0.1
[pip3] torchaudio==2.0.2
[pip3] torchvision==0.15.2
[pip3] triton==2.0.0
[conda] blas                      1.0                         mkl    defaults
[conda] ffmpeg                    4.3                  hf484d3e_0    pytorch
[conda] mkl                       2023.1.0         h6d00ec8_46342    defaults
[conda] mkl-service               2.4.0           py310h5eee18b_1    defaults
[conda] mkl_fft                   1.3.6           py310h1128e8f_1    defaults
[conda] mkl_random                1.2.2           py310h1128e8f_1    defaults
[conda] numpy                     1.25.0          py310h5f9d8c6_0    defaults
[conda] numpy-base                1.25.0          py310hb5e798b_0    defaults
[conda] pytorch                   2.0.1           py3.10_cuda11.7_cudnn8.5.0_0    pytorch
[conda] pytorch-cuda              11.7                 h778d358_5    pytorch
[conda] pytorch-mutex             1.0                        cuda    pytorch
[conda] torchaudio                2.0.2               py310_cu117    pytorch
[conda] torchtriton               2.0.0                     py310    pytorch
[conda] torchvision               0.15.2              py310_cu117    pytorch

cc @ptrblck