Repository: pytorch
Issue: A huge difference between the results of torch.round() on the GPU compared to its results on the CPU and other DL libraries
Labels: module: numerical-stability,module: cuda,triaged

### 🐛 Describe the bug
We found this problem by training the same model on different  hardware(i.e., CPU and GPU) and frameworks (i.e., MindSpore and PyTorch), using exactly the same input data.
Only the outputs of torch-gpu differs significantly from torch-cpu, mindspore-gpu, and mindspore-cpu.
Simple reproduction code：
```python
import numpy as np
import torch
import torch.nn.functional as F
"""
The commented out code is used to load our inputs and outputs, 
and a direct comparison shows that only torch-gpu differs significantly from torch-cpu, mindspore-gpu, and mindspor-cpu.
"""
# m_gpu_o = np.load("./mindspore_gpu_output.npz")
# t_gpu_o = np.load("./pytorch_gpu_output.npz")

# m_cpu_o = np.load("./mindspore_cpu_output.npz")
# t_cpu_o = np.load("./pytorch_cpu_output.npz")


# lst = [m_gpu_o, t_gpu_o, m_cpu_o, t_cpu_o]
# name = ['m_gpu', 't_gpu', 'm_cpu', 't_cpu']
# for i in range(0, 4):
#     for j in range(i+1, 4):
#         print(name[i].upper() + "-" + name[j].upper())
#         different_positions = np.where(lst[i]['relu3_output'] != lst[j]['relu3_output'])
#         print("position:", different_positions)
        
#         for pos in zip(*different_positions):
#             v1 = lst[i]['fc1_output'][pos]
#             v2 = lst[j]['fc1_output'][pos]
#             print(f"Specific values for locations {pos} where discrepancies exist in the input of round: {name[i].upper()}={v1}, {name[j].upper()}={v2}")

#             v3 = lst[i]['relu3_output'][pos]
#             v4 = lst[j]['relu3_output'][pos]
#             print(f"Specific values for locations {pos} where discrepancies exist in the output of round: {name[i].upper()}={v3}, {name[j].upper()}={v4}")

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

cpu_input = np.load("./pytorch_cpu_output.npz")['fc1_output']
gpu_input = np.load("./pytorch_gpu_output.npz")['fc1_output']

cpu_input_tensor = torch.from_numpy(cpu_input)
gpu_input_tensor = torch.from_numpy(gpu_input).to(device)

gpu_output = torch.round(gpu_input_tensor)
#np.savez("./gpu_output.npz",gpu_output.cpu().detach().numpy())
gpu_output = gpu_output.to('cpu')

cpu_output = torch.round(cpu_input_tensor)
#np.savez("./cpu_output.npz",cpu_output.cpu().detach().numpy())

output_chebyshev_distance = torch.max(torch.abs(cpu_output - gpu_output))
input_chebyshev_distance = torch.max(torch.abs(cpu_input_tensor - torch.from_numpy(gpu_input)))
print(f"Chebyshev distance between inputs: {input_chebyshev_distance.item()}")
print(f"Chebyshev distance between outputs: {output_chebyshev_distance.item()}")
```
Specific differences in the inputs and outputs of round operation:
```python
# M-GPU vs T-GPU
all different position in outputs: 
CPU [ 66, 141, 256, 316, 341, 379, 387, 400, 472, 476, 596, 705, 815,
       892, 924]
GPU [43, 81, 22, 72, 53, 36, 53, 22, 81, 53, 81, 36, 53, 36, 92]
For example: 
the different value of input of round in position (66, 43): m_gpu_o=0.4998815357685089, t_gpu_o=0.5000243186950684
the different value of output of round  in position (66, 43): m_gpu_o=0.0, t_gpu_o=1.0

# M-GPU vs M-CPU: No Diff
position: (array([], dtype=int64), array([], dtype=int64))
# M-CPU vs T-CPU: No Diff
position: (array([], dtype=int64), array([], dtype=int64))
```
This can eventually lead to significant differences in the output of the forward propagation when using the same input.
```python
MindSpore GPU Max: 1.4009582996368408 -- Min: -1.5092084407806396
Torch     GPU Max: 1.4009582996368408 -- Min: -1.5092084407806396
MindSpore CPU Max: 1.4009584188461304 -- Min: -1.509208083152771
Torch     CPU Max: 1.40095853805542 -- Min: -1.509208083152771
M-GPU-T-GPU Diff 0.2941844165325165
M-GPU-M-CPU Diff 7.152557373046875e-07
M-GPU-T-CPU Diff 5.960464477539062e-07
T-GPU-M-CPU Diff 0.29418444633483887
T-GPU-T-CPU Diff 0.29418444633483887
M-CPU-T-CPU Diff 2.384185791015625e-07
```
**As a result, we believe that there may be some issues with the numerical stability of the Torch-GPU and that ROUND amplifies the impact of the differences.**
Complete model training code on GPU：
```python
import torch
import torch.nn as nn
import numpy as np
from torch import optim
import os
import torch.nn.functional as F


class Model_gGjaaC_PbmJv5McK74QSRSo6yZEqY0Nb(nn.Module):
    def __init__(self):
        super(Model_gGjaaC_PbmJv5McK74QSRSo6yZEqY0Nb, self).__init__()
        self.conv1_mutated = torch.nn.ConvTranspose2d(in_channels=1, out_channels=6, kernel_size=[5, 5], stride=[1, 1], padding=[0, 0], output_padding=[0, 0], dilation=[1, 1], groups=1, bias=True)
        self.relu1 = torch.nn.ReLU()
        self.pool1_mutated = torch.nn.MaxPool2d(kernel_size=[2, 2], stride=[1, 2], padding=[0, 0], dilation=1, ceil_mode=False)
        self.conv2_mutated = torch.nn.Conv2d(in_channels=6, out_channels=16, kernel_size=[5, 5], stride=[8, 8], padding=[0, 0], dilation=[1, 1], groups=1, bias=True)
        self.relu2 = torch.nn.ReLU()
        self.pool2_mutated = torch.nn.MaxPool2d(kernel_size=[2, 2], stride=[8, 8], padding=[0, 0], dilation=1, ceil_mode=False)
        self.flatten = torch.nn.Flatten()
        self.linear1 = torch.nn.Linear(in_features=16, out_features=120)
        self.relu3_mutated = torch.round
        self.linear2_mutated = torch.nn.Linear(in_features=120, out_features=84)
        self.tail_flatten = torch.nn.Flatten()
        self.tail_fc = torch.nn.Linear(in_features=84, out_features=10)

    def forward(self, input):
        conv1_output = self.conv1_mutated(input)
        relu1_output = self.relu1(conv1_output)
        maxpool1_output = self.pool1_mutated(relu1_output)
        conv2_output = self.conv2_mutated(maxpool1_output)
        relu2_output = self.relu2(conv2_output)
        maxpool2_output = self.pool2_mutated(relu2_output)
        flatten_output = self.flatten(maxpool2_output)
        fc1_output = self.linear1(flatten_output)
        relu3_output = self.relu3_mutated(fc1_output)
        fc2_output = self.linear2_mutated(relu3_output)
        tail_flatten_output = self.tail_flatten(fc2_output)
        tail_fc_output = self.tail_fc(tail_flatten_output)

        tail_fc_output = tail_fc_output
        
        return tail_fc_output


def go():
    try:
        model = Model_gGjaaC_PbmJv5McK74QSRSo6yZEqY0Nb().to('cuda')
        x = torch.randn([1, 1, 28, 28]).to('cuda')
        y = model(x)
        flag = True
    except Exception:
        flag = False
    return flag


def initialize(model):
    module_dir = os.path.dirname(__file__)
    for name, param in model.named_parameters():
        layer_name, matrix_name = name.rsplit('.', 1)
        matrix_path = module_dir + '/../initializer/' + layer_name + '/' + matrix_name + '.npz'
        data = np.load(matrix_path)
        tensor = torch.from_numpy(data['matrix']).float()
        tensor = tensor.to(param.device)
        param.data = tensor


def train(inp, label):
    model = Model_gGjaaC_PbmJv5McK74QSRSo6yZEqY0Nb().to('cuda')
    initialize(model)
    my_input = torch.from_numpy(inp).to('cuda')
    output = model(my_input)
    target = torch.from_numpy(label).to('cuda')
    loss = nn.CrossEntropyLoss()(output, target)
    loss.backward()
    gradients = {name: param.grad.to('cpu').numpy() for name, param in model.named_parameters()}
    return gradients, loss.item(), output.detach().to('cpu').numpy()

```
Complete model training code on GPU：
```python
import torch
import torch.nn as nn
import numpy as np
from torch import optim
import os
import torch.nn.functional as F


class Model_gGjaaC_PbmJv5McK74QSRSo6yZEqY0Nb(nn.Module):
    def __init__(self):
        super(Model_gGjaaC_PbmJv5McK74QSRSo6yZEqY0Nb, self).__init__()
        self.conv1_mutated = torch.nn.ConvTranspose2d(in_channels=1, out_channels=6, kernel_size=[5, 5], stride=[1, 1], padding=[0, 0], output_padding=[0, 0], dilation=[1, 1], groups=1, bias=True)
        self.relu1 = torch.nn.ReLU()
        self.pool1_mutated = torch.nn.MaxPool2d(kernel_size=[2, 2], stride=[1, 2], padding=[0, 0], dilation=1, ceil_mode=False)
        self.conv2_mutated = torch.nn.Conv2d(in_channels=6, out_channels=16, kernel_size=[5, 5], stride=[8, 8], padding=[0, 0], dilation=[1, 1], groups=1, bias=True)
        self.relu2 = torch.nn.ReLU()
        self.pool2_mutated = torch.nn.MaxPool2d(kernel_size=[2, 2], stride=[8, 8], padding=[0, 0], dilation=1, ceil_mode=False)
        self.flatten = torch.nn.Flatten()
        self.linear1 = torch.nn.Linear(in_features=16, out_features=120)
        self.relu3_mutated = torch.round
        self.linear2_mutated = torch.nn.Linear(in_features=120, out_features=84)
        self.tail_flatten = torch.nn.Flatten()
        self.tail_fc = torch.nn.Linear(in_features=84, out_features=10)

    def forward(self, input):
        conv1_output = self.conv1_mutated(input)
        relu1_output = self.relu1(conv1_output)
        maxpool1_output = self.pool1_mutated(relu1_output)
        conv2_output = self.conv2_mutated(maxpool1_output)
        relu2_output = self.relu2(conv2_output)
        maxpool2_output = self.pool2_mutated(relu2_output)
        flatten_output = self.flatten(maxpool2_output)
        fc1_output = self.linear1(flatten_output)
        relu3_output = self.relu3_mutated(fc1_output)
        fc2_output = self.linear2_mutated(relu3_output)
        tail_flatten_output = self.tail_flatten(fc2_output)
        tail_fc_output = self.tail_fc(tail_flatten_output)

        tail_fc_output = tail_fc_output
        return tail_fc_output

def initialize(model):
    module_dir = os.path.dirname(__file__)
    for name, param in model.named_parameters():
        layer_name, matrix_name = name.rsplit('.', 1)
        matrix_path = module_dir + '/../initializer/' + layer_name + '/' + matrix_name + '.npz'
        data = np.load(matrix_path)
        tensor = torch.from_numpy(data['matrix']).float()
        tensor = tensor.to(param.device)
        param.data = tensor

def train(inp, label):
    model = Model_gGjaaC_PbmJv5McK74QSRSo6yZEqY0Nb()
    initialize(model)
    my_input = torch.from_numpy(inp)
    output = model(my_input)
    target = torch.from_numpy(label)
    loss = nn.CrossEntropyLoss()(output, target)
    loss.backward()
    gradients = {name: param.grad.to('cpu').numpy() for name, param in model.named_parameters()}
    return gradients, loss.item(), output.detach().to('cpu').numpy()

```
The data used for training, the weights, and the code that can be run are all in our repository.
https://github.com/PhyllisJi/MoCoDiff_Bug/tree/torch-issue%23126975
### Versions

PyTorch version: 2.2.0+cu121
Is debug build: False
CUDA used to build PyTorch: 12.1
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.16.3
Libc version: glibc-2.31

Python version: 3.10.13 (main, Sep 11 2023, 13:44:35) [GCC 11.2.0] (64-bit runtime)
Python platform: Linux-4.19.0-14-amd64-x86_64-with-glibc2.31
Is CUDA available: True
CUDA runtime version: 12.1.105
CUDA_MODULE_LOADING set to: LAZY
GPU models and configuration: GPU 0: NVIDIA GeForce RTX 3080 Ti
Nvidia driver version: 535.98
cuDNN version: Probably one of the following:
/usr/lib/x86_64-linux-gnu/libcudnn.so.8.9.0
/usr/lib/x86_64-linux-gnu/libcudnn_adv_infer.so.8.9.0
/usr/lib/x86_64-linux-gnu/libcudnn_adv_train.so.8.9.0
/usr/lib/x86_64-linux-gnu/libcudnn_cnn_infer.so.8.9.0
/usr/lib/x86_64-linux-gnu/libcudnn_ops_infer.so.8.9.0
/usr/lib/x86_64-linux-gnu/libcudnn_ops_train.so.8.9.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, 48 bits virtual
CPU(s): 72
On-line CPU(s) list: 0-71
Thread(s) per core: 2
Core(s) per socket: 18
Socket(s): 2
NUMA node(s): 2
Vendor ID: GenuineIntel
CPU family: 6
Model: 79
Model name: Intel(R) Xeon(R) CPU E5-2686 v4 @ 2.30GHz
Stepping: 1
CPU MHz: 1878.204
CPU max MHz: 3000.0000
CPU min MHz: 1200.0000
BogoMIPS: 4599.86
Virtualization: VT-x
L1d cache: 1.1 MiB
L1i cache: 1.1 MiB
L2 cache: 9 MiB
L3 cache: 90 MiB
NUMA node0 CPU(s): 0-17,36-53
NUMA node1 CPU(s): 18-35,54-71
Vulnerability Itlb multihit: KVM: Mitigation: Split huge pages
Vulnerability L1tf: Mitigation; PTE Inversion; VMX conditional cache flushes, SMT vulnerable
Vulnerability Mds: Mitigation; Clear CPU buffers; SMT vulnerable
Vulnerability Meltdown: Mitigation; PTI
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; Full generic retpoline, IBPB conditional, IBRS_FW, STIBP conditional, RSB filling
Vulnerability Srbds: Not affected
Vulnerability Tsx async abort: Mitigation; Clear CPU buffers; SMT vulnerable
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 arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc cpuid aperfmperf 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 cdp_l3 invpcid_single pti intel_ppin ssbd ibrs ibpb stibp tpr_shadow vnmi flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 erms invpcid rtm cqm rdt_a rdseed adx smap intel_pt xsaveopt cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local dtherm ida arat pln pts md_clear flush_l1d

Versions of relevant libraries:
[pip3] numpy==1.26.4
[pip3] onnx==1.16.0
[pip3] torch==2.2.0
[pip3] triton==2.2.0
[conda] numpy 1.26.4 pypi_0 pypi
[conda] torch 2.2.0 pypi_0 pypi
[conda] triton 2.2.0 pypi_0 pypi

cc @ptrblck @msaroufim