Repository: pytorch
Issue: ONNX Exporter Fails with Handling Complex Tensors
Labels: module: onnx,triaged,OSS contribution wanted

### 🐛 Describe the bug

## Bug description

I encountered an issue when trying to export a model using the `torch.onnx.dynamo_export` function. The model involves operations with complex tensors, specifically using `torch.fft.rfft` and complex matrix multiplications. The exporter throws an error related to `aten::unsqueeze.default` not supporting complex dtypes. This behavior is also found in the nightly versions (like `2.4.0.dev20240522`).

## Environment

- PyTorch version: `2.3.0+cu121`
- Python version: `3.11`
- OS: `Ubuntu 22.04`

## Steps to Reproduce

1. Define a PyTorch model that involves complex tensor operations with `torch.unsqueeze`.
2. Attempt to export the model to ONNX using `torch.onnx.dynamo_export`.

Here is a minimal code snippet to reproduce the issue:

```python
import torch

class BSSModel(torch.nn.Module):
    def __init__(self, n_fft: int = 2048):
        super().__init__()
        self.win_a = torch.hamming_window(n_fft, dtype=torch.float)[:, None]
        self.win_s = self.win_a / (self.win_a**2 + torch.roll(self.win_a, n_fft // 2)**2)

    def forward(self, frame: torch.Tensor, prev_in: torch.Tensor, prev_out: torch.Tensor, W: torch.Tensor):
        buffer = torch.cat((prev_in, frame))
        x = torch.fft.rfft(buffer * self.win_a, axis=0)
        y = (W @ x.unsqueeze(-1)).squeeze(-1)
        curr_out, next_out = torch.chunk(torch.fft.irfft(y, axis=0) * self.win_s, 2)
        return curr_out + prev_out, frame, next_out
    
frame_size = 1024
channels = 4

model = BSSModel()
frame = torch.zeros((frame_size, channels), dtype=torch.float)
W = torch.empty((frame_size + 1, channels, channels), dtype=torch.cfloat)

export_output = torch.onnx.dynamo_export(model, frame, frame, frame, W)
```

**Expected Behavior:**

The model should be successfully exported to ONNX format.

**Actual Behavior:**

The export fails with an error indicating that `aten::unsqueeze.default` cannot find a symbolic function for complex dtypes.

**Full traceback of the exception**:

```
/home/vladimir/miniconda3/envs/pt-2-3/lib/python3.11/site-packages/torch/onnx/_internal/exporter.py:136: UserWarning: torch.onnx.dynamo_export only implements opset version 18 for now. If you need to use a different opset version, please register them with register_custom_op.
  warnings.warn(
Traceback (most recent call last):
  File "/home/vladimir/miniconda3/envs/pt-2-3/lib/python3.11/site-packages/torch/onnx/_internal/exporter.py", line 1428, in dynamo_export
    ).export()
      ^^^^^^^^
  File "/home/vladimir/miniconda3/envs/pt-2-3/lib/python3.11/site-packages/torch/onnx/_internal/exporter.py", line 1181, in export
    onnxscript_graph = fx_interpreter.run(
                       ^^^^^^^^^^^^^^^^^^^
  File "/home/vladimir/miniconda3/envs/pt-2-3/lib/python3.11/site-packages/torch/onnx/_internal/diagnostics/infra/decorator.py", line 151, in wrapper
    ctx.log_and_raise_if_error(diag)
  File "/home/vladimir/miniconda3/envs/pt-2-3/lib/python3.11/site-packages/torch/onnx/_internal/diagnostics/infra/context.py", line 366, in log_and_raise_if_error
    raise diagnostic.source_exception
  File "/home/vladimir/miniconda3/envs/pt-2-3/lib/python3.11/site-packages/torch/onnx/_internal/diagnostics/infra/decorator.py", line 135, in wrapper
    return_values = fn(*args, **kwargs)
                    ^^^^^^^^^^^^^^^^^^^
  File "/home/vladimir/miniconda3/envs/pt-2-3/lib/python3.11/site-packages/torch/onnx/_internal/fx/fx_onnx_interpreter.py", line 576, in run
    self.run_node(
  File "/home/vladimir/miniconda3/envs/pt-2-3/lib/python3.11/site-packages/torch/onnx/_internal/diagnostics/infra/decorator.py", line 151, in wrapper
    ctx.log_and_raise_if_error(diag)
  File "/home/vladimir/miniconda3/envs/pt-2-3/lib/python3.11/site-packages/torch/onnx/_internal/diagnostics/infra/context.py", line 366, in log_and_raise_if_error
    raise diagnostic.source_exception
  File "/home/vladimir/miniconda3/envs/pt-2-3/lib/python3.11/site-packages/torch/onnx/_internal/diagnostics/infra/decorator.py", line 135, in wrapper
    return_values = fn(*args, **kwargs)
                    ^^^^^^^^^^^^^^^^^^^
  File "/home/vladimir/miniconda3/envs/pt-2-3/lib/python3.11/site-packages/torch/onnx/_internal/fx/fx_onnx_interpreter.py", line 470, in run_node
    self.call_function(
  File "/home/vladimir/miniconda3/envs/pt-2-3/lib/python3.11/site-packages/torch/onnx/_internal/fx/fx_onnx_interpreter.py", line 692, in call_function
    symbolic_fn = onnxfunction_dispatcher.dispatch(
                  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/vladimir/miniconda3/envs/pt-2-3/lib/python3.11/site-packages/torch/onnx/_internal/fx/onnxfunction_dispatcher.py", line 136, in dispatch
    default_and_custom_functions = self.get_function_overloads(
                                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/vladimir/miniconda3/envs/pt-2-3/lib/python3.11/site-packages/torch/onnx/_internal/diagnostics/infra/decorator.py", line 151, in wrapper
    ctx.log_and_raise_if_error(diag)
  File "/home/vladimir/miniconda3/envs/pt-2-3/lib/python3.11/site-packages/torch/onnx/_internal/diagnostics/infra/context.py", line 366, in log_and_raise_if_error
    raise diagnostic.source_exception
  File "/home/vladimir/miniconda3/envs/pt-2-3/lib/python3.11/site-packages/torch/onnx/_internal/diagnostics/infra/decorator.py", line 135, in wrapper
    return_values = fn(*args, **kwargs)
                    ^^^^^^^^^^^^^^^^^^^
  File "/home/vladimir/miniconda3/envs/pt-2-3/lib/python3.11/site-packages/torch/onnx/_internal/fx/onnxfunction_dispatcher.py", line 406, in get_function_overloads
    function_group = self._filter_or_keep_complex(
                     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/vladimir/miniconda3/envs/pt-2-3/lib/python3.11/site-packages/torch/onnx/_internal/fx/onnxfunction_dispatcher.py", line 177, in _filter_or_keep_complex
    raise diagnostics.RuntimeErrorWithDiagnostic(diagnostic)
torch.onnx._internal.diagnostics.infra.context.RuntimeErrorWithDiagnostic: Cannot find any COMPLEX symbolic function for aten::unsqueeze.default, which should be registered under aten.unsqueeze.default.

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/home/vladimir/playground/pt-bug/bug.py", line 24, in <module>
    export_output = torch.onnx.dynamo_export(model, frame, frame, frame, W)
                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/vladimir/miniconda3/envs/pt-2-3/lib/python3.11/site-packages/torch/onnx/_internal/exporter.py", line 1439, in dynamo_export
    raise OnnxExporterError(
torch.onnx.OnnxExporterError: Failed to export the model to ONNX. Generating SARIF report at 'report_dynamo_export.sarif'. SARIF is a standard format for the output of static analysis tools. SARIF logs can be loaded in VS Code SARIF viewer extension, or SARIF web viewer (https://microsoft.github.io/sarif-web-component/). Please report a bug on PyTorch Github: https://github.com/pytorch/pytorch/issues
```

### Versions

```
PyTorch version: 2.3.0+cu121
Is debug build: False
CUDA used to build PyTorch: 12.1
ROCM used to build PyTorch: N/A

OS: Ubuntu 22.04.1 LTS (x86_64)
GCC version: (Ubuntu 11.3.0-1ubuntu1~22.04.1) 11.3.0
Clang version: Could not collect
CMake version: version 3.22.1
Libc version: glibc-2.35

Python version: 3.11.9 | packaged by conda-forge | (main, Apr 19 2024, 18:36:13) [GCC 12.3.0] (64-bit runtime)
Python platform: Linux-5.19.0-45-generic-x86_64-with-glibc2.35
Is CUDA available: True
CUDA runtime version: 11.7.99
CUDA_MODULE_LOADING set to: LAZY
GPU models and configuration: GPU 0: NVIDIA GeForce RTX 3090 Ti
Nvidia driver version: 530.30.02
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-12700
CPU family:                      6
Model:                           151
Thread(s) per core:              2
Core(s) per socket:              12
Socket(s):                       1
Stepping:                        2
CPU max MHz:                     4900,0000
CPU min MHz:                     800,0000
BogoMIPS:                        4224.00
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 pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault 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 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 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:                       512 KiB (12 instances)
L1i cache:                       512 KiB (12 instances)
L2 cache:                        12 MiB (9 instances)
L3 cache:                        25 MiB (1 instance)
NUMA node(s):                    1
NUMA node0 CPU(s):               0-19
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 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 IBRS, IBPB conditional, RSB filling, PBRSB-eIBRS SW sequence
Vulnerability Srbds:             Not affected
Vulnerability Tsx async abort:   Not affected

Versions of relevant libraries:
[pip3] numpy==1.26.4
[pip3] onnx==1.16.0
[pip3] onnxscript==0.1.0.dev20240523
[pip3] torch==2.3.0
[pip3] torchaudio==2.3.0
[pip3] torchvision==0.18.0
[pip3] triton==2.3.0
[conda] numpy                     1.26.4                   pypi_0    pypi
[conda] torch                     2.3.0                    pypi_0    pypi
[conda] torchaudio                2.3.0                    pypi_0    pypi
[conda] torchvision               0.18.0                   pypi_0    pypi
[conda] triton                    2.3.0                    pypi_0    pypi
```