Runtime Error outerNode->outputs().size() == node->inputs().size() INTERNAL ASSERT FAILED when exporting custom operator
Labels: module: onnx, triaged

### 🐛 Describe the bug

Dear community, 

I need to export to ONNX a method that is highly state-sensitive and difficult to make stateless, I've found a trick to that with giving the custom_op function the results to return directly, when doing so, it works very well as long as the method to deploy is doing branching only, but when computation is added, this fails with the error.
`RuntimeError: outerNode->outputs().size() == node->inputs().size() INTERNAL ASSERT FAILED at "../torch/csrc/jit/passes/dead_code_elimination.cpp":140, please report a bug to PyTorch.`

I'm having a hard time debugging that and any help would be greatly appreciated ! Here is a minimal working example that allows to reproduce the issue:

In this example if you uncomment `#    compute_to_use = fake_compute # This work` the export works fine.

```python
from typing import Tuple, Union
import torch


class CustomClassOp_Func(torch.autograd.Function):
    @staticmethod
    @torch.no_grad()
    def forward(
        g: torch.onnx._internal.jit_utils.GraphContext,
        result: Union[torch.Value, Tuple[torch.Value]],
        *args: torch.Value,
    ) -> torch.Value:
        return result

    @staticmethod
    def symbolic(
        g: torch.onnx._internal.jit_utils.GraphContext,
        result: Union[torch.Value, Tuple[torch.Value]],
        *args: torch.Value,
    ) -> torch.Value:
        return g.op(
            f"CustomDomain::custom_op",
            *args,
            outputs=len(result),
        )


class Custom(torch.nn.Module):
    def real_compute(self, input1, input2):
        a = input1 + input2
        b = 2 * input1
        c = 2 * input2
        return a,b,c
    
    def fake_compute(self, input1, input2):
        a = input1
        b = input1
        c = input2
        return a,b,c
    
    # Change me
    compute_to_use = real_compute # This doesn't work
#    compute_to_use = fake_compute # This work
    
    @torch.no_grad()
    def custom_op_inference(self, *args):
        return CustomClassOp_Func.apply(
                    self.compute_to_use(*args),
                    *args
                )
    
    def forward(self, input1, input2):
        if torch.onnx.is_in_onnx_export():
            args = input1, input2
            return self.custom_op_inference(*args)
        return self.compute_to_use(input1, input2)

model = Custom()
batch = (torch.FloatTensor(1, 3), torch.FloatTensor(1, 3))
torch.onnx.export(model, batch, "/tmp/model.onnx", opset_version=16, custom_opsets={"CustomDomain": 1})
```

and the logtrace obtained


```
============= Diagnostic Run torch.onnx.export version 2.0.0+cu117 =============
verbose: False, log level: Level.ERROR
======================= 0 NONE 0 NOTE 0 WARNING 0 ERROR ========================

Traceback (most recent call last):
  File "/work/PSEE/metavision-computational-imaging/.vscode/.scratch/.model/colorizer_preprocessing.py", line 60, in <module>
    torch.onnx.export(model, batch, "/tmp/model.onnx", opset_version=16, custom_opsets={"CustomDomain": 1})
  File "/home/edupuis/.cache/pypoetry/virtualenvs/cimaging-ml-qzr9xo67-py3.8/lib/python3.8/site-packages/torch/onnx/utils.py", line 506, in export
    _export(
  File "/home/edupuis/.cache/pypoetry/virtualenvs/cimaging-ml-qzr9xo67-py3.8/lib/python3.8/site-packages/torch/onnx/utils.py", line 1548, in _export
    graph, params_dict, torch_out = _model_to_graph(
  File "/home/edupuis/.cache/pypoetry/virtualenvs/cimaging-ml-qzr9xo67-py3.8/lib/python3.8/site-packages/torch/onnx/utils.py", line 1117, in _model_to_graph
    graph = _optimize_graph(
  File "/home/edupuis/.cache/pypoetry/virtualenvs/cimaging-ml-qzr9xo67-py3.8/lib/python3.8/site-packages/torch/onnx/utils.py", line 584, in _optimize_graph
    _C._jit_pass_lower_all_tuples(graph)
RuntimeError: outerNode->outputs().size() == node->inputs().size() INTERNAL ASSERT FAILED at "../torch/csrc/jit/passes/dead_code_elimination.cpp":140, please report a bug to PyTorch. 
```

### Versions

Collecting environment information...
PyTorch version: 2.0.0+cu117
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: 10.0.0-4ubuntu1 
CMake version: version 3.26.3
Libc version: glibc-2.31

Python version: 3.8.10 (default, May 26 2023, 14:05:08)  [GCC 9.4.0] (64-bit runtime)
Python platform: Linux-5.14.0-1058-oem-x86_64-with-glibc2.29
Is CUDA available: True
CUDA runtime version: Could not collect
CUDA_MODULE_LOADING set to: LAZY
GPU models and configuration: GPU 0: NVIDIA T500
Nvidia driver version: 530.30.02
cuDNN version: Probably one of the following:
/usr/lib/x86_64-linux-gnu/libcudnn.so.8.9.2
/usr/lib/x86_64-linux-gnu/libcudnn_adv_infer.so.8.9.2
/usr/lib/x86_64-linux-gnu/libcudnn_adv_train.so.8.9.2
/usr/lib/x86_64-linux-gnu/libcudnn_cnn_infer.so.8.9.2
/usr/lib/x86_64-linux-gnu/libcudnn_cnn_train.so.8.9.2
/usr/lib/x86_64-linux-gnu/libcudnn_ops_infer.so.8.9.2
/usr/lib/x86_64-linux-gnu/libcudnn_ops_train.so.8.9.2
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:                   39 bits physical, 48 bits virtual
CPU(s):                          8
On-line CPU(s) list:             0-7
Thread(s) per core:              2
Core(s) per socket:              4
Socket(s):                       1
NUMA node(s):                    1
Vendor ID:                       GenuineIntel
CPU family:                      6
Model:                           140
Model name:                      11th Gen Intel(R) Core(TM) i7-1165G7 @ 2.80GHz
Stepping:                        1
CPU MHz:                         4083.291
CPU max MHz:                     4700.0000
CPU min MHz:                     400.0000
BogoMIPS:                        5606.40
Virtualization:                  VT-x
L1d cache:                       192 KiB
L1i cache:                       128 KiB
L2 cache:                        5 MiB
L3 cache:                        12 MiB
NUMA node0 CPU(s):               0-7
Vulnerability Itlb multihit:     Not affected
Vulnerability L1tf:              Not affected
Vulnerability Mds:               Not affected
Vulnerability Meltdown:          Not affected
Vulnerability Mmio stale data:   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
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 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 invpcid_single cdp_l2 ssbd ibrs ibpb stibp ibrs_enhanced tpr_shadow vnmi 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 dtherm ida arat pln pts hwp hwp_notify hwp_act_window hwp_epp hwp_pkg_req avx512vbmi umip pku ospke avx512_vbmi2 gfni vaes vpclmulqdq avx512_vnni avx512_bitalg avx512_vpopcntdq rdpid movdiri movdir64b fsrm avx512_vp2intersect md_clear flush_l1d arch_capabilities

Versions of relevant libraries:
[pip3] mypy==1.3.0
[pip3] mypy-extensions==1.0.0
[pip3] numpy==1.23.5
[pip3] pytorch-lightning==2.0.2
[pip3] torch==2.0.0
[pip3] torch-tb-profiler==0.4.1
[pip3] torchmetrics==0.11.4
[pip3] torchvision==0.15.1
[pip3] triton==2.0.0
[conda] mkl                       2022.1.0           hc2b9512_224  
[conda] numpy                     1.23.5           py38hf838250_0  
[conda] numpy-base                1.23.5           py38h1e6e340_0  
[conda] pytorch                   1.12.1          cpu_py38h9dbd814_1  
[conda] pytorch-mutex             1.0                         cpu    pytorch