Export to onnx error: RuntimeError: ArrayRef: invalid index Index = 3; Length = 3
Labels: module: onnx, triaged

### 🐛 Describe the bug

When I try to export to onnx model, I got following error,
RuntimeError: ArrayRef: invalid index Index = 3; Length = 3

``` bash
  _C._jit_pass_onnx_graph_shape_type_inference(
Traceback (most recent call last):
  File "export.py", line 41, in <module>
    torch.onnx.export(model,               # model being run
  File "/home/leo/storage/sharedFolderVirtualbox/experiment/speaker_diarization-embeddings/embeddings/lib/python3.8/site-packages/torch/onnx/utils.py", line 516, in export
    _export(
  File "/home/leo/storage/sharedFolderVirtualbox/experiment/speaker_diarization-embeddings/embeddings/lib/python3.8/site-packages/torch/onnx/utils.py", line 1582, in _export
    graph, params_dict, torch_out = _model_to_graph(
  File "/home/leo/storage/sharedFolderVirtualbox/experiment/speaker_diarization-embeddings/embeddings/lib/python3.8/site-packages/torch/onnx/utils.py", line 1182, in _model_to_graph
    _C._jit_pass_onnx_assign_output_shape(
RuntimeError: ArrayRef: invalid index Index = 3; Length = 3
```
The code as below,
```python
import torchaudio
from speechbrain.pretrained import EncoderClassifier
import torch

model = EncoderClassifier.from_hparams(source="speechbrain/spkrec-ecapa-voxceleb")

signal, fs = torchaudio.load('shortTeaching2.wav')
print( signal )
print( signal.shape )
#exit( 0 ) 

# Print output shape
embeddings = model.encode_batch(signal)
#print( embeddings )
#print( embeddings.shape )
#exit( 0 ) 

# Create dummy input
symbolic_names = {0: "batch_size", 1: "max_seq_len"}
x = torch.randn( 1, 1920000 )
# Export the model
torch.onnx.export(model,               # model being run
                  x,                         # model input (or a tuple for multiple inputs)
                  "embeddings.onnx",   # where to save the model (can be a file or file-like object)
                  export_params=True,        # store the trained parameter weights inside the model file
                  opset_version=17,          # the ONNX version to export the model to
                  do_constant_folding=True,  # whether to execute constant folding for optimization
                  verbose=False,
                  input_names = ['signal'],   # the model's input names
                  output_names = ['embeddings'], # the model's output names
                  dynamic_axes={'signal' : symbolic_names,    # variable length axes
                                })

```

When  I pdb into python code, I found the error raised from this function,
_C._jit_pass_onnx_assign_output_shape
with local variables,
```bash
(Pdb) p output_wrapped
(tensor([[ 0.0677,  0.0583,  0.1144,  ..., -0.1774, -0.0198, -0.1925]]), tensor([0.2038]), tensor([3869]), ['id04606'])
(Pdb) p output_tensors
[tensor([[ 0.0677,  0.0583,  0.1144,  ..., -0.1774, -0.0198, -0.1925]]), tensor([0.2038]), tensor([3869])]
(Pdb) p out_desc
<torch.IODescriptor object at 0x7fecd75d08b0>
```
Then debug into pytorch c++ code( I used gdb ),
check desc ans tensors which passed into ONNXAssignOutputShape
```bash
(gdb) p desc
$24 = (const torch::jit::python::IODescriptor &) @0x74b81c0: {structure = "(vvv[s])",
  strings = std::vector of length 1, capacity 1 = {"id04606"},
  metadata = std::vector of length 3, capacity 3 = {{sizes = std::vector of length 2, capacity 2 = {
        1, 7205}, type = c10::ScalarType::Float, device = {type_ = c10::DeviceType::CPU,
        index_ = -1 '\377'}, requires_grad = false}, {
      sizes = std::vector of length 1, capacity 1 = {1}, type = c10::ScalarType::Float, device = {
        type_ = c10::DeviceType::CPU, index_ = -1 '\377'}, requires_grad = false}, {
      sizes = std::vector of length 1, capacity 1 = {1}, type = c10::ScalarType::Long, device = {
        type_ = c10::DeviceType::CPU, index_ = -1 '\377'}, requires_grad = false}},
  grad_enabled = true}
(gdb) p tensors
$23 = std::vector of length 3, capacity 3 = {{<at::TensorBase> = {impl_ = {
        target_ = 0x12ffadf0}}, <No data fields>}, {<at::TensorBase> = {impl_ = {
        target_ = 0x12ff5540}}, <No data fields>}, {<at::TensorBase> = {impl_ = {
        target_ = 0x12ffdac0}}, <No data fields>}}

```
after unflatten 
``` bash
PyObject* py_obj = unflatten(outputs, desc);

(gdb) p PyTuple_Size(py_obj)
$39 = 4
so later it references outputs of graph from 0 till 3( 0, 1, 2, 3 )
```
At line pytorch/torch/csrc/jit/passes/onnx/shape_type_inference.cpp:2295, 
graph->outputs() contains 3 elements only but it try access 4th elements by outputs_index=3 which leads to TORCH_CHECK failed.




### Versions

Collecting environment information...
PyTorch version: 2.1.0a0+git134d415
Is debug build: True
CUDA used to build PyTorch: Could not collect
ROCM used to build PyTorch: N/A

OS: Ubuntu 22.04.2 LTS (x86_64)
GCC version: (Ubuntu 11.4.0-1ubuntu1~22.04) 11.4.0
Clang version: 14.0.0-1ubuntu1.1
CMake version: version 3.27.2
Libc version: glibc-2.35

Python version: 3.8.17 (default, Jul  5 2023, 21:04:15)  [GCC 11.2.0] (64-bit runtime)
Python platform: Linux-6.2.0-26-generic-x86_64-with-glibc2.17
Is CUDA available: False
CUDA runtime version: 12.2.128
CUDA_MODULE_LOADING set to: N/A
GPU models and configuration: GPU 0: NVIDIA GeForce RTX 2070 SUPER
Nvidia driver version: 535.86.05
cuDNN version: Probably one of the following:
/usr/local/cuda-11.7/targets/x86_64-linux/lib/libcudnn.so.8
/usr/local/cuda-11.7/targets/x86_64-linux/lib/libcudnn_adv_infer.so.8
/usr/local/cuda-11.7/targets/x86_64-linux/lib/libcudnn_adv_train.so.8
/usr/local/cuda-11.7/targets/x86_64-linux/lib/libcudnn_cnn_infer.so.8
/usr/local/cuda-11.7/targets/x86_64-linux/lib/libcudnn_cnn_train.so.8
/usr/local/cuda-11.7/targets/x86_64-linux/lib/libcudnn_ops_infer.so.8
/usr/local/cuda-11.7/targets/x86_64-linux/lib/libcudnn_ops_train.so.8
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):                          16
On-line CPU(s) list:             0-15
Vendor ID:                       GenuineIntel
Model name:                      Intel(R) Core(TM) i9-9900KF CPU @ 3.60GHz
CPU family:                      6
Model:                           158
Thread(s) per core:              2
Core(s) per socket:              8
Socket(s):                       1
Stepping:                        13
CPU max MHz:                     5000.0000
CPU min MHz:                     800.0000
BogoMIPS:                        7200.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 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 invpcid_single ssbd ibrs ibpb stibp ibrs_enhanced tpr_shadow vnmi flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid mpx rdseed adx smap clflushopt intel_pt xsaveopt xsavec xgetbv1 xsaves dtherm ida arat pln pts hwp hwp_notify hwp_act_window hwp_epp md_clear flush_l1d arch_capabilities
Virtualization:                  VT-x
L1d cache:                       256 KiB (8 instances)
L1i cache:                       256 KiB (8 instances)
L2 cache:                        2 MiB (8 instances)
L3 cache:                        16 MiB (1 instance)
NUMA node(s):                    1
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
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:             Mitigation; Microcode
Vulnerability Tsx async abort:   Mitigation; TSX disabled

Versions of relevant libraries:
[pip3] numpy==1.24.4
[pip3] torch==2.1.0a0+git134d415
[pip3] torchaudio==2.1.0a0+47eaab4
[pip3] triton==2.0.0
[conda] cudatoolkit               11.3.1               h2bc3f7f_2    anaconda
[conda] magma-cuda117             2.6.1                         1    pytorch
[conda] mkl                       2023.1.0         h213fc3f_46343  
[conda] mkl-include               2023.1.0         h06a4308_46343  
[conda] numpy                     1.24.4                   pypi_0    pypi
[conda] torch                     2.1.0a0+git134d415           dev_0    <develop>
[conda] torchaudio                2.1.0a0+47eaab4          pypi_0    pypi
[conda] triton                    2.0.0                    pypi_0    pypi