Repository: pytorch
Issue: Torch.onnx.dynamo_export Failure in Pytest for BatchNorm
Labels: module: onnx,triaged,onnx-needs-info

### 🐛 Describe the bug

Pytest does not work with torch.onnx.dynamo_export() if the model has a batchnorm in it.

As a minimal example with efficientnet_b0 consider running the following code snippet with pytest and then as a script. It fails with pytest, even though it succeeds when ran as a script.

 ```python
 import torch
 from torchvision.models import efficientnet_b0
 
 def test_onnx_export():
     test_data = torch.ones(1, 3, 360, 640).to(torch.float32).cuda()
     model = efficientnet_b0(pretrained=True).cuda()
     model.eval()
     torch.onnx.dynamo_export(model, test_data)
 
 if __name__ == "__main__":
     test_onnx_export()
   ```


The second example is a simple CNN. If the batch norm is included in the forward pass, the same error happens as in the first minimal example. If not, the pytest succeeds.

```
import torch

class SimpleCNN(torch.nn.Module):
    def __init__(self, num_classes):
        super(SimpleCNN, self).__init__()
        self.conv1 = torch.nn.Conv2d(3, 16, 3, padding=1)
        self.bn = torch.nn.BatchNorm2d(16)
        self.relu1 = torch.nn.ReLU()
        self.pool1 = torch.nn.MaxPool2d(2, 2)
        self.fc = torch.nn.Linear(16 * 180 * 320, num_classes)

    def forward(self, x):
        x = self.conv1(x)
        x = self.relu1(x)
        x = self.bn(x)
        x = self.pool1(x)
        x = torch.flatten(x, 1)
        x = self.fc(x)
        return x

def test_onnx_export():
    test_data = torch.ones(1, 3, 360, 640).to(torch.float32).cuda()
    model = SimpleCNN(10).cuda()
    model.eval()
    torch.onnx.dynamo_export(model, test_data)

if __name__ == "__main__":
    test_onnx_export()
 ```

This is the stacktrace I get when the pytests are failing:

```
I0829 08:05:29.460000 137854302897984 torch/onnx/_internal/fx/diagnostics.py:219] [__onnx_diagnostics] For detailed logging of graph modifications by this pass, either set `DiagnosticOptions.verbosity_level` to `logging.DEBUG` or use the environment variable `TORCH_LOGS='onnx_diagnostics'`.
I0829 08:05:29.464000 137854302897984 torch/onnx/_internal/fx/diagnostics.py:219] [__onnx_diagnostics] Renamed 'self._param_constant0' to 'self.conv1/weight', normalized from original parameter name 'conv1.weight'.
I0829 08:05:29.465000 137854302897984 torch/onnx/_internal/fx/diagnostics.py:219] [__onnx_diagnostics] Renamed 'self._param_constant1' to 'self.conv1/bias', normalized from original parameter name 'conv1.bias'.
I0829 08:05:29.465000 137854302897984 torch/onnx/_internal/fx/diagnostics.py:219] [__onnx_diagnostics] Renamed 'self._param_constant2' to 'self.bn/weight', normalized from original parameter name 'bn.weight'.
I0829 08:05:29.465000 137854302897984 torch/onnx/_internal/fx/diagnostics.py:219] [__onnx_diagnostics] Renamed 'self._param_constant3' to 'self.bn/bias', normalized from original parameter name 'bn.bias'.
E0829 08:05:29.466000 137854302897984 torch/onnx/_internal/fx/diagnostics.py:219] [__onnx_diagnostics] ## Exception log
E0829 08:05:29.466000 137854302897984 torch/onnx/_internal/fx/diagnostics.py:219] [__onnx_diagnostics] ```
E0829 08:05:29.466000 137854302897984 torch/onnx/_internal/fx/diagnostics.py:219] [__onnx_diagnostics] Traceback (most recent call last):
E0829 08:05:29.466000 137854302897984 torch/onnx/_internal/fx/diagnostics.py:219] [__onnx_diagnostics] 
E0829 08:05:29.466000 137854302897984 torch/onnx/_internal/fx/diagnostics.py:219] [__onnx_diagnostics]   File "/usr/local/lib/python3.10/dist-packages/torch/onnx/_internal/diagnostics/infra/decorator.py", line 135, in wrapper
E0829 08:05:29.466000 137854302897984 torch/onnx/_internal/fx/diagnostics.py:219] [__onnx_diagnostics]     return_values = fn(*args, **kwargs)
E0829 08:05:29.466000 137854302897984 torch/onnx/_internal/fx/diagnostics.py:219] [__onnx_diagnostics] 
E0829 08:05:29.466000 137854302897984 torch/onnx/_internal/fx/diagnostics.py:219] [__onnx_diagnostics]   File "/usr/local/lib/python3.10/dist-packages/torch/onnx/_internal/fx/_pass.py", line 275, in run
E0829 08:05:29.466000 137854302897984 torch/onnx/_internal/fx/diagnostics.py:219] [__onnx_diagnostics]     module = self._run(*args, **kwargs)
E0829 08:05:29.466000 137854302897984 torch/onnx/_internal/fx/diagnostics.py:219] [__onnx_diagnostics] 
E0829 08:05:29.466000 137854302897984 torch/onnx/_internal/fx/diagnostics.py:219] [__onnx_diagnostics]   File "/usr/local/lib/python3.10/dist-packages/torch/onnx/_internal/fx/passes/readability.py", line 129, in _run
E0829 08:05:29.466000 137854302897984 torch/onnx/_internal/fx/diagnostics.py:219] [__onnx_diagnostics]     self._rename_param_and_buffer(diagnostic, nodes, new_name)
E0829 08:05:29.466000 137854302897984 torch/onnx/_internal/fx/diagnostics.py:219] [__onnx_diagnostics] 
E0829 08:05:29.466000 137854302897984 torch/onnx/_internal/fx/diagnostics.py:219] [__onnx_diagnostics]   File "/usr/local/lib/python3.10/dist-packages/torch/onnx/_internal/fx/passes/readability.py", line 53, in _rename_param_and_buffer
E0829 08:05:29.466000 137854302897984 torch/onnx/_internal/fx/diagnostics.py:219] [__onnx_diagnostics]     new_node = self.module.graph.get_attr(normalized_name)
E0829 08:05:29.466000 137854302897984 torch/onnx/_internal/fx/diagnostics.py:219] [__onnx_diagnostics] 
E0829 08:05:29.466000 137854302897984 torch/onnx/_internal/fx/diagnostics.py:219] [__onnx_diagnostics]   File "/usr/local/lib/python3.10/dist-packages/torch/fx/graph.py", line 1102, in get_attr
E0829 08:05:29.466000 137854302897984 torch/onnx/_internal/fx/diagnostics.py:219] [__onnx_diagnostics]     warnings.warn("Attempted to insert a get_attr Node with no "
E0829 08:05:29.466000 137854302897984 torch/onnx/_internal/fx/diagnostics.py:219] [__onnx_diagnostics] 
E0829 08:05:29.466000 137854302897984 torch/onnx/_internal/fx/diagnostics.py:219] [__onnx_diagnostics] UserWarning: Attempted to insert a get_attr Node with no underlying reference in the owning GraphModule! Call GraphModule.add_submodule to add the necessary submodule, GraphModule.add_parameter to add the necessary Parameter, or nn.Module.register_buffer to add the necessary buffer
E0829 08:05:29.466000 137854302897984 torch/onnx/_internal/fx/diagnostics.py:219] [__onnx_diagnostics] 
E0829 08:05:29.466000 137854302897984 torch/onnx/_internal/fx/diagnostics.py:219] [__onnx_diagnostics] ```
```

### Versions

```
Collecting environment information...
PyTorch version: 2.3.1+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.30.2
Libc version: glibc-2.35

Python version: 3.10.12 (main, Jul 29 2024, 16:56:48) [GCC 11.4.0] (64-bit runtime)
Python platform: Linux-6.8.0-40-generic-x86_64-with-glibc2.35
Is CUDA available: True
CUDA runtime version: 12.1.105
CUDA_MODULE_LOADING set to: LAZY
GPU models and configuration: GPU 0: NVIDIA T500
Nvidia driver version: 535.183.01
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_cnn_train.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
Address sizes:                        39 bits physical, 48 bits virtual
Byte Order:                           Little Endian
CPU(s):                               8
On-line CPU(s) list:                  0-7
Vendor ID:                            GenuineIntel
Model name:                           11th Gen Intel(R) Core(TM) i7-1165G7 @ 2.80GHz
CPU family:                           6
Model:                                140
Thread(s) per core:                   2
Core(s) per socket:                   4
Socket(s):                            1
Stepping:                             1
CPU max MHz:                          4700.0000
CPU min MHz:                          400.0000
BogoMIPS:                             5606.40
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 est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault epb cat_l2 cdp_l2 ssbd ibrs ibpb stibp ibrs_enhanced tpr_shadow flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid rdt_a avx512f avx512dq rdseed adx smap avx512ifma clflushopt clwb intel_pt avx512cd sha_ni avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves split_lock_detect user_shstk dtherm ida arat pln pts hwp hwp_notify hwp_act_window hwp_epp hwp_pkg_req vnmi avx512vbmi umip pku ospke avx512_vbmi2 gfni vaes vpclmulqdq avx512_vnni avx512_bitalg avx512_vpopcntdq rdpid movdiri movdir64b fsrm avx512_vp2intersect md_clear ibt flush_l1d arch_capabilities
Virtualization:                       VT-x
L1d cache:                            192 KiB (4 instances)
L1i cache:                            128 KiB (4 instances)
L2 cache:                             5 MiB (4 instances)
L3 cache:                             12 MiB (1 instance)
NUMA node(s):                         1
NUMA node0 CPU(s):                    0-7
Vulnerability Gather data sampling:   Mitigation; Microcode
Vulnerability Itlb multihit:          Not affected
Vulnerability L1tf:                   Not affected
Vulnerability Mds:                    Not affected
Vulnerability Meltdown:               Not affected
Vulnerability Mmio stale data:        Not affected
Vulnerability Reg file data sampling: Not affected
Vulnerability Retbleed:               Not affected
Vulnerability Spec rstack overflow:   Not affected
Vulnerability Spec store bypass:      Mitigation; Speculative Store Bypass disabled via prctl
Vulnerability Spectre v1:             Mitigation; usercopy/swapgs barriers and __user pointer sanitization
Vulnerability Spectre v2:             Mitigation; Enhanced / Automatic IBRS; IBPB conditional; RSB filling; PBRSB-eIBRS SW sequence; BHI SW loop, KVM SW loop
Vulnerability Srbds:                  Not affected
Vulnerability Tsx async abort:        Not affected

Versions of relevant libraries:
[pip3] ament-flake8==0.12.11
[pip3] flake8==4.0.1
[pip3] mypy==1.9.0
[pip3] mypy-extensions==1.0.0
[pip3] numpy==1.26.4
[pip3] onnx==1.16.0
[pip3] onnx-graphsurgeon==0.5.2
[pip3] onnxruntime==1.17.3
[pip3] onnxruntime-gpu==1.17.1
[pip3] onnxscript==0.1.0.dev20240524
[pip3] torch==2.3.1+cu121
[pip3] torch-tb-profiler==0.4.3
[pip3] torchinfo==1.8.0
[pip3] torchtyping==0.1.4
[pip3] torchvision==0.18.1+cu121
[pip3] triton==2.3.1
[conda] Could not collect
```