Repository: pytorch
Issue: Issue Exporting PyTorch Model with pytorch3d.ops.ball_query to ONNX: Bug or Compatibility Problem?
Labels: needs reproduction,module: onnx,onnx-needs-info,oncall: export

### 🐛 Describe the bug

Hi,
I am trying to export a PyTorch model to ONNX, which utilizes pytorch3d.ops.ball_query. However, I have not been able to successfully export the model due to an exception.

I'm posting here because the exception suggests reporting a bug, though I'm not sure if it’s a bug or a compatibility issue.

It's worth noting that the export works when using fixed batch sizes.

---
**Exception:** 

```bash
outerNode->outputs().size() == node->inputs().size() INTERNAL ASSERT FAILED at "../torch/csrc/jit/passes/dead_code_elimination.cpp":139, please report a bug to PyTorch. 
  File "debug_model.py", line 24, in export_model_to_onnx
    torch.onnx.export(
  File "debug_model.py", line 66, in <module>
    export_model_to_onnx(model)
RuntimeError: outerNode->outputs().size() == node->inputs().size() INTERNAL ASSERT FAILED at "../torch/csrc/jit/passes/dead_code_elimination.cpp":139, please report a bug to PyTorch.  
```

--- 
**minimal code to reproduce:** 

```python
import torch
import torch.nn as nn
import pytorch3d.ops
import onnxruntime as ort

class SimpleModel(nn.Module):
    def __init__(self):
        super(SimpleModel, self).__init__()

    def forward(self, query_points, all_points):
            #------------------------------------------------------------------------------------------------------------------------------------ 
            # Here is the problematic line: if we remove the call to pytorch3d function the export works as expected 
            #------------------------------------------------------------------------------------------------------------------------------------ 
        dist, idx, nns = pytorch3d.ops.ball_query(  # <<<<<<
            query_points, all_points, K=10, radius=0.1 # <<<<<<
        ) 
        #------------------------------------------------------------------------------------------------------------------------------------ 
        print(dist)
        return query_points, all_points


def export_model_to_onnx(model, file_path="model.onnx"):
    model.eval()
    sample1 = torch.zeros([1, 10, 3], dtype=torch.float)  # batch, nb points , R³
    sample2 = torch.zeros([1, 20, 3], dtype=torch.float)  # batch, nb points , R³

    torch.onnx.export(
        model,
        (sample1, sample2),
        file_path,
        verbose=True,
        input_names=["query_points", "all_points"],
        output_names=["output1", "output2"],
        dynamic_axes={
            "query_points": {0: "batch_size", 1: "nb_points"},
            "all_points": {0: "batch_size", 1: "nb_points"},
            "output1": {0: "batch_size", 1: "nb_points"},
            "output2": {0: "batch_size", 1: "nb_points"},
        },
        opset_version=13,
    )

def load_and_run_onnx_model(file_path, query_points, all_points):
    ort_session = ort.InferenceSession(file_path)
    ort_inputs = {
        "query_points": query_points.numpy(),
        "all_points": all_points.numpy(),
    }
    ort_outputs = ort_session.run(None, ort_inputs)

    return ort_outputs

# Define initial batch sizes
batch_size_2 = 2
batch_size_1 = 1
num_query_points = 10
num_all_points = 100
point_dim = 3

# Create random tensors for batch size 1
query_points_1 = torch.rand(
    batch_size_1, num_query_points, point_dim, dtype=torch.float32
)
all_points_1 = torch.rand(batch_size_1, num_all_points, point_dim, dtype=torch.float32)

# Export model
model = SimpleModel()

export_model_to_onnx(model)
dist_onnx_1 = load_and_run_onnx_model("model.onnx", query_points_1, all_points_1)
print("Results for batch size 1:")
print("Distances:", dist_onnx_1)
```

### Versions


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.4 LTS (x86_64)
GCC version: (Ubuntu 11.4.0-1ubuntu1~22.04) 11.4.0
Clang version: Could not collect
CMake version: version 3.29.2
Libc version: glibc-2.35

Python version: 3.10.14 (main, May  6 2024, 19:42:50) [GCC 11.2.0] (64-bit runtime)
Python platform: Linux-6.5.0-44-generic-x86_64-with-glibc2.35
Is CUDA available: True
CUDA runtime version: Could not collect
CUDA_MODULE_LOADING set to: LAZY
GPU models and configuration: GPU 0: NVIDIA RTX A2000 8GB Laptop GPU
Nvidia driver version: 545.23.08
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
Address sizes:                      46 bits physical, 48 bits virtual
Byte Order:                         Little Endian
CPU(s):                             20
On-line CPU(s) list:                0-19
Vendor ID:                          GenuineIntel
Model name:                         12th Gen Intel(R) Core(TM) i7-12800H
CPU family:                         6
Model:                              154
Thread(s) per core:                 2
Core(s) per socket:                 14
Socket(s):                          1
Stepping:                           3
CPU max MHz:                        4800,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 smx est tm2 ssse3 sdbg fma cx16 xtpr pdcm sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault epb ssbd ibrs ibpb stibp ibrs_enhanced tpr_shadow flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid rdseed adx smap clflushopt clwb intel_pt sha_ni xsaveopt xsavec xgetbv1 xsaves split_lock_detect avx_vnni dtherm ida arat pln pts hwp hwp_notify hwp_act_window hwp_epp hwp_pkg_req hfi vnmi umip pku ospke waitpkg gfni vaes vpclmulqdq tme rdpid movdiri movdir64b fsrm md_clear serialize pconfig arch_lbr ibt flush_l1d arch_capabilities
Virtualization:                     VT-x
L1d cache:                          544 KiB (14 instances)
L1i cache:                          704 KiB (14 instances)
L2 cache:                           11,5 MiB (8 instances)
L3 cache:                           24 MiB (1 instance)
NUMA node(s):                       1
NUMA node0 CPU(s):                  0-19
Vulnerability Gather data sampling: Not affected
Vulnerability Itlb multihit:        Not affected
Vulnerability L1tf:                 Not affected
Vulnerability Mds:                  Not affected
Vulnerability Meltdown:             Not affected
Vulnerability Mmio stale data:      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 BHI_DIS_S
Vulnerability Srbds:                Not affected
Vulnerability Tsx async abort:      Not affected

Versions of relevant libraries:
[pip3] numpy==1.26.3
[pip3] onnx==1.16.1
[pip3] onnxconverter-common==1.14.0
[pip3] onnxruntime==1.16.3
[pip3] onnxruntime-tools==1.7.0
[pip3] onnxscript==0.1.0.dev20240701
[pip3] outsight_onnx_metadata==1.30.2.post19+git.ddf097c3.dirty
[pip3] pytorch3d==0.7.6
[pip3] skl2onnx==1.17.0
[pip3] torch==2.3.1
[pip3] torchvision==0.18.1
[pip3] triton==2.3.1
[conda] pytorch3d                 0.7.6                    pypi_0    pypi
[conda] torch                     2.3.1                    pypi_0    pypi
[conda] torchvision               0.18.1                   pypi_0    pypi
[conda] triton                    2.3.1                    pypi_0    pypi


cc @avikchaudhuri @gmagogsfm @zhxchen17 @tugsbayasgalan @angelayi @suo @ydwu4 @penguinwu