Repository: pytorch
Issue: Output Discrepancy between PyTorch Model and Converted ONNX Model
Labels: module: onnx,triaged

### 🐛 Describe the bug

### Description 
There's a significant discrepancy between the outputs of my PyTorch model and the same model converted to ONNX format. This inconsistency raises concerns about the accuracy and reliability of the conversion process.

I follow the same testing process as described in https://pytorch.org/tutorials/advanced/super_resolution_with_onnxruntime.html

### How to Reproduce
- poc.pt link: https://compsec.snu.ac.kr/git/SuhwanSong/poc/-/raw/main/torch/poc.pt
- poc.npy link: https://compsec.snu.ac.kr/git/SuhwanSong/poc/-/raw/main/torch/poc.npy


1. Download "poc.pt" (i.e., pytorch model) and "poc.npy" (i.e., input data).
2. Run the following script.

```python
import torch
import numpy as np
import onnxruntime

def to_numpy(tensor):
    return tensor.detach().cpu().numpy() if tensor.requires_grad else tensor.cpu().numpy()

if __name__ == "__main__" :

    pytorch_model = torch.load('poc.pt')
    onnx_model_path = 'converted.onnx'

    input_np = np.load('poc.npy')
    input_torch = torch.from_numpy(input_np)

    torch.onnx.export(pytorch_model,
            input_torch,
            onnx_model_path,
            export_params=True,
            do_constant_folding=False,
            input_names = ['x'],
            output_names = ['output'],
            dynamic_axes={'x' : {0 : 'batch_size'},
                        'output' : {0 : 'batch_size'}})

    ort_session = onnxruntime.InferenceSession(onnx_model_path)
    ort_inputs = {ort_session.get_inputs()[0].name: input_np}

    rtol = 1e-03
    atol = 1e-05

    pyout = pytorch_model(input_torch)
    ort_output = ort_session.run(None, ort_inputs)

    np.testing.assert_allclose(to_numpy(pyout), ort_output[0], rtol=rtol, atol=atol)
```

The output looks like:
```
Traceback (most recent call last):
  File "torch_report.py", line 41, in <module>
    np.testing.assert_allclose(to_numpy(pyout), ort_output[0], rtol=rtol, atol=atol)
  File "/home/suhwan/.local/lib/python3.8/site-packages/numpy/testing/_private/utils.py", line 1592, in assert_allclose
    assert_array_compare(compare, actual, desired, err_msg=str(err_msg),
  File "/usr/lib/python3.8/contextlib.py", line 75, in inner
    return func(*args, **kwds)
  File "/home/suhwan/.local/lib/python3.8/site-packages/numpy/testing/_private/utils.py", line 862, in assert_array_compare
    raise AssertionError(msg)
AssertionError: 
Not equal to tolerance rtol=0.001, atol=1e-05

Mismatched elements: 1000 / 1000 (100%)
Max absolute difference: 16991.25
Max relative difference: 0.10721099
 x: array([[134120.36 , 127842.09 , 124900.55 , 132048.45 , 135627.84 ,
        129770.71 , 128940.55 , 125610.234, 126661.89 , 128904.84 ,
        127167.67 , 132015.33 , 131392.16 , 128761.85 , 130220.94 ,...
 y: array([[150149.33, 143153.3 , 139858.36, 147857.44, 151888.75, 145287.84,
        144386.38, 140632.12, 141833.33, 144337.66, 142391.88, 147824.48,
        147122.9 , 144168.53, 145813.03, 144951.84, 144379.75, 148362.53,...

```


### Expected Behavior
We should see that the output of PyTorch and ONNX Runtime runs match numerically with the given precision (rtol=1e-03 and atol=1e-05).

### Actual Behavior
The script throws an AssertionError due to a discrepancy between the outputs of the PyTorch model and the ONNX model. The provided error message indicates a high number of mismatched elements and large differences between the maximum absolute and relative differences.


### Versions

```
Collecting environment information...
PyTorch version: 2.2.2+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: 12.0.0 (https://github.com/llvm/llvm-project.git d928dfc6f924f7e8436dcb5bcc51285fd03e869c)
CMake version: version 3.29.2
Libc version: glibc-2.31

Python version: 3.8.10 (default, Nov 22 2023, 10:22:35)  [GCC 9.4.0] (64-bit runtime)
Python platform: Linux-5.4.0-174-generic-x86_64-with-glibc2.29
Is CUDA available: False
CUDA runtime version: No CUDA
CUDA_MODULE_LOADING set to: N/A
GPU models and configuration: No CUDA
Nvidia driver version: No CUDA
cuDNN version: No CUDA
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):                             48
On-line CPU(s) list:                0-47
Thread(s) per core:                 2
Core(s) per socket:                 12
Socket(s):                          2
NUMA node(s):                       2
Vendor ID:                          GenuineIntel
CPU family:                         6
Model:                              85
Model name:                         Intel(R) Xeon(R) Silver 4214R CPU @ 2.40GHz
Stepping:                           7
CPU MHz:                            1000.134
CPU max MHz:                        3500.0000
CPU min MHz:                        1000.0000
BogoMIPS:                           4800.00
Virtualization:                     VT-x
L1d cache:                          768 KiB
L1i cache:                          768 KiB
L2 cache:                           24 MiB
L3 cache:                           33 MiB
NUMA node0 CPU(s):                  0-11,24-35
NUMA node1 CPU(s):                  12-23,36-47
Vulnerability Gather data sampling: Mitigation; Microcode
Vulnerability Itlb multihit:        KVM: Mitigation: Split huge pages
Vulnerability L1tf:                 Not affected
Vulnerability Mds:                  Not affected
Vulnerability Meltdown:             Not affected
Vulnerability Mmio stale data:      Mitigation; Clear CPU buffers; SMT vulnerable
Vulnerability Retbleed:             Mitigation; Enhanced IBRS
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
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 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 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 mpx rdt_a avx512f avx512dq rdseed adx smap clflushopt clwb intel_pt avx512cd avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local dtherm ida arat pln pts hwp hwp_act_window hwp_pkg_req pku ospke avx512_vnni md_clear flush_l1d arch_capabilities

Versions of relevant libraries:
[pip3] mypy-extensions==1.0.0
[pip3] numpy==1.24.4
[pip3] onnx==1.15.0
[pip3] onnx-tool==0.9.0
[pip3] onnx2torch==1.5.14
[pip3] onnxmltools==1.12.0
[pip3] onnxoptimizer==0.3.13
[pip3] onnxruntime==1.17.3
[pip3] torch==2.2.2
[pip3] torchvision==0.17.2
[pip3] triton==2.2.0
[conda] Could not collect

```