torch.onnx.export does not respect nn.Module.forward API when using export_modules_as_functions=True
Labels: module: onnx, triaged

### 🐛 Describe the bug

Hi everyone. I'm currently trying to debug an issue with ONNX exporting and I'm currently trying to get ideas on how to further debug the problem.
I'm currently on PyTorch 2.0.

I've included an minimum runnable example below in case you're interested in testing it on your own setup.

**Context:** I'm trying to export a network with two `nn.Module`s, that will both be replaced by [ONNX functions](https://onnx.ai/onnx/intro/concepts.html#functions).
These functions are used to abstract out data-dependent computational graphs, so that it can later be replaced by
a custom op, on the target hardware.  This ensures that each `nn.Module` receives and outputs fixed sized tensors.

**Problem:** When I connect the output of `FixedShapeUnique` to the input of `CreateVoxelGrid` is where problems start.
`FixedShapeUnique` reports having **four** output tensors instead of two and `CreateVoxelGrid` reports six input tensors
instead of four.

If I don't pass `CreateVoxelGrid` as an argument into `export_modules_as_functions`, `FixedShapeUnique` still reports
having **four** output tensors instead of two.

If I don't use `export_modules_as_functions`, I also don't see these bogus nodes appearing.

Any ideas on where should I start looking into

**Code:**

```python
from typing import Optional

import torch
from torch import nn


class CreateVoxelGrid(nn.Module):
    def __init__(self, shape: tuple[int, int, int, int]) -> None:
        super().__init__()
        self.grid_shape = shape

    def forward(
        self,
        voxel_features: torch.Tensor,
        indices: torch.Tensor,
        voxel_features_mask: Optional[torch.Tensor] = None,
        indices_mask: Optional[torch.Tensor] = None,
    ) -> torch.Tensor:
        grid = voxel_features.new_zeros(self.grid_shape)

        if voxel_features_mask is not None:
            voxel_features = voxel_features[voxel_features_mask]
        if indices_mask is not None:
            indices = indices[indices_mask]
        grid[indices[:, 0], indices[:, 1], indices[:, 2]] = voxel_features
        return grid


class FixedShapeUnique(nn.Module):
    def forward(
        self,
        tensor: torch.Tensor,
        mask: Optional[torch.Tensor] = None,
    ) -> tuple[torch.Tensor, torch.Tensor]:
        if mask is None:
            mask = torch.ones(tensor.shape[0], dtype=torch.bool, device=tensor.device)

        output = torch.zeros_like(tensor)
        valid = torch.zeros_like(mask)

        unique_tensor = torch.unique(tensor[mask], dim=0)

        output[: unique_tensor.shape[0]] = unique_tensor
        valid[: unique_tensor.shape[0]] = True

        return output, valid


class Network(nn.Module):
    def __init__(self, grid_shape: tuple[int, int, int, int]) -> None:
        super().__init__()

        self.unique = FixedShapeUnique()
        self.voxel_grid = CreateVoxelGrid(grid_shape)

    def forward(
        self,
        voxel_features: torch.Tensor,
        indices: torch.Tensor,
        voxel_features_mask: Optional[torch.Tensor] = None,
        indices_mask: Optional[torch.Tensor] = None,
    ) -> torch.Tensor:
        indices, indices_mask = self.unique(indices, mask=indices_mask)  # <- the million dollar question
        return self.voxel_grid(
            voxel_features, indices, voxel_features_mask=voxel_features_mask, indices_mask=indices_mask
        )


def main():
    torch.manual_seed(24)

    channels = 8
    n_occupied_voxels = 20
    voxel_features = torch.randn(n_occupied_voxels, channels)

    batch_size = 1
    grid_shape = (batch_size, 256, 256, channels)
    indices = torch.stack([torch.randint(size, size=(n_occupied_voxels,)) for size in grid_shape], dim=1)

    voxel_features_mask = torch.rand(voxel_features.shape[0]) > 0.5
    # just creating a new mask with the same number of True elements
    indices_mask = torch.flipud(voxel_features_mask)

    model = Network(grid_shape)
    model(voxel_features, indices, voxel_features_mask=voxel_features_mask, indices_mask=indices_mask)

    path = "/tmp/playground.onnx"

    torch.onnx.export(
        model=model.eval(),
        args=(voxel_features, indices, {"voxel_features_mask": voxel_features_mask, "indices_mask": indices_mask}),
        f=path,
        opset_version=15,
        input_names=["voxel_features", "indices", "voxel_features_mask", "indices_mask"],
        export_modules_as_functions={FixedShapeUnique, CreateVoxelGrid},
    )


if __name__ == "__main__":
    main()
```

**ONNX Graph:**
![Screenshot 2023-07-10 at 18 00 59](https://github.com/pytorch/pytorch/assets/124908487/1c6e28ee-5baa-4160-8a96-dbeacdf135cb)
![Screenshot 2023-07-10 at 18 02 02](https://github.com/pytorch/pytorch/assets/124908487/b9a7ebf5-064f-4b5c-bce2-fc9a07ba7991)



### 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: Could not collect
CMake version: version 3.26.3
Libc version: glibc-2.31

Python version: 3.9.16 (main, Mar  8 2023, 14:00:05)  [GCC 11.2.0] (64-bit runtime)
Python platform: Linux-5.15.0-73-generic-x86_64-with-glibc2.31
Is CUDA available: True
CUDA runtime version: 10.1.243
CUDA_MODULE_LOADING set to: LAZY
GPU models and configuration: GPU 0: Quadro RTX 5000
Nvidia driver version: 470.161.03
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
Byte Order:                      Little Endian
Address sizes:                   46 bits physical, 48 bits virtual
CPU(s):                          16
On-line CPU(s) list:             0-15
Thread(s) per core:              2
Core(s) per socket:              8
Socket(s):                       1
NUMA node(s):                    1
Vendor ID:                       GenuineIntel
CPU family:                      6
Model:                           85
Model name:                      Intel(R) Xeon(R) W-2245 CPU @ 3.90GHz
Stepping:                        7
CPU MHz:                         3900.000
CPU max MHz:                     4700.0000
CPU min MHz:                     1200.0000
BogoMIPS:                        7799.87
Virtualization:                  VT-x
L1d cache:                       256 KiB
L1i cache:                       256 KiB
L2 cache:                        8 MiB
L3 cache:                        16.5 MiB
NUMA node0 CPU(s):               0-15
Vulnerability Itlb multihit:     KVM: Mitigation: VMX disabled
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_epp hwp_pkg_req avx512_vnni md_clear flush_l1d arch_capabilities

Versions of relevant libraries:
[pip3] efficientnet-pytorch==0.7.1
[pip3] mypy==1.0.1
[pip3] mypy-extensions==1.0.0
[pip3] numpy==1.23.5
[pip3] numpy-quaternion==2022.4.3
[pip3] torch==2.0.0+cu117
[pip3] torch-scatter==2.1.1+pt20cu117
[pip3] torchmetrics==0.12.0.dev0
[pip3] torchvision==0.15.0+cu117
[pip3] triton==2.0.0
[conda] efficientnet-pytorch      0.7.1                    pypi_0    pypi
[conda] mkl                       2023.0.0                 pypi_0    pypi
[conda] mkl-service               2.4.0                    pypi_0    pypi
[conda] numpy                     1.23.5                   pypi_0    pypi
[conda] numpy-quaternion          2022.4.3                 pypi_0    pypi
[conda] torch                     2.0.0+cu117              pypi_0    pypi
[conda] torch-scatter             2.1.1+pt20cu117          pypi_0    pypi
[conda] torchmetrics              0.12.0.dev0              pypi_0    pypi
[conda] torchvision               0.15.0+cu117             pypi_0    pypi
[conda] triton                    2.0.0                    pypi_0    pypi
```