onnx export jit.script ShapeInferenceError Unexpected axis value: 1. Expected range [-1, 1)
Labels: module: onnx, triaged

### 🐛 Describe the bug

I cannot seem to export a simple model, that has some dynamic shapes using jit.script.

Small repro:
```python
import torch
from typing import List

@torch.jit.script
def spatial_shapes_helper(embeds: List[torch.FloatTensor]) -> torch.LongTensor:
    return torch.tensor([
        [embeds[0].shape[2], embeds[0].shape[3]],
        [embeds[1].shape[2], embeds[1].shape[3]],
        [embeds[2].shape[2], embeds[2].shape[3]],
    ], device=embeds[0].device)

class MyShaphesModule(torch.nn.Module):
    def __init__(self):
        super().__init__()

    def forward(
        self,
        input_embeds0,
        input_embeds1,
        input_embeds2,
    ):
        input_embeds = [input_embeds0, input_embeds1, input_embeds2]
        spatial_shapes: torch.LongTensor = spatial_shapes_helper(input_embeds)
        offset_normalizer: torch.LongTensor = torch.flip(spatial_shapes, [1])
        
        return spatial_shapes, offset_normalizer

def test_myshapes():
    model = MyShaphesModule()

    embeds = tuple([
        torch.rand([1, 256, 37, 58]),
        torch.rand([1, 256, 74, 116]),
        torch.rand([1, 256, 147, 232])
    ])

    output = model(*embeds)

    input_names = ["embeds0", "embeds1", "embeds2"]
    output_names = [
        "spatial_shapes",
        "offset_normalizer"
    ]
    torch.onnx.export(
        model,
        embeds,
        "myshapes.onnx",
        verbose=False,
        input_names=input_names,
        output_names=output_names,
        opset_version=17,
        dynamic_axes={
            "embeds0": [2,3],
            "embeds1": [2,3],
            "embeds2": [2,3],
        },
    )

if __name__ == "__main__":
    test_myshapes()
    print("done")
```

Output:
```
/home/ad.adasworks.com/balint.varga/mambaforge/envs/tc_nightly/lib/python3.10/site-packages/torch/jit/annotations.py:387: UserWarning: TorchScript will treat type annotations of Tensor dtype-specific subtypes as if they are normal Tensors. dtype constraints are not enforced in compilation either.
  warnings.warn(
/home/ad.adasworks.com/balint.varga/mambaforge/envs/tc_nightly/lib/python3.10/site-packages/torch/onnx/utils.py:2099: UserWarning: No names were found for specified dynamic axes of provided input.Automatically generated names will be applied to each dynamic axes of input embeds0
  warnings.warn(
/home/ad.adasworks.com/balint.varga/mambaforge/envs/tc_nightly/lib/python3.10/site-packages/torch/onnx/utils.py:2099: UserWarning: No names were found for specified dynamic axes of provided input.Automatically generated names will be applied to each dynamic axes of input embeds1
  warnings.warn(
/home/ad.adasworks.com/balint.varga/mambaforge/envs/tc_nightly/lib/python3.10/site-packages/torch/onnx/utils.py:2099: UserWarning: No names were found for specified dynamic axes of provided input.Automatically generated names will be applied to each dynamic axes of input embeds2
  warnings.warn(
/home/ad.adasworks.com/balint.varga/mambaforge/envs/tc_nightly/lib/python3.10/site-packages/torch/onnx/utils.py:1703: UserWarning: The exported ONNX model failed ONNX shape inference. The model will not be executable by the ONNX Runtime. If this is unintended and you believe there is a bug, please report an issue at https://github.com/pytorch/pytorch/issues. Error reported by strict ONNX shape inference: [ShapeInferenceError] Shape inference error(s): (op_type:Slice, node name: /Slice): [ShapeInferenceError] Unexpected axis value: 1. Expected range [-1, 1)
 (Triggered internally at ../torch/csrc/jit/serialization/export.cpp:1445.)
  _C._check_onnx_proto(proto)
done
```

The important part of the output log is:
`Shape inference error(s): (op_type:Slice, node name: /Slice): [ShapeInferenceError] Unexpected axis value: 1. Expected range [-1, 1)`
When running in verbose mode, it's clear that the slice is coming from torch.flip.

Also, infering on the pytorch model without onnx works fine, the outputs are:
```
spatial_shapes
tensor([[ 37,  58],
        [ 74, 116],
        [147, 232]])
offset_normalizer
tensor([[ 58,  37],
        [116,  74],
        [232, 147]])
```

Despite the error, the onnx file is exported, and can be visualized with netron:
(but I don't think it's a usable onnx file because of the error)
![Screenshot from 2023-10-06 11-58-06](https://github.com/pytorch/pytorch/assets/3685997/6c1618cf-b597-438e-a02b-2243c0c6395f)

It looks like the spatial_shapes has lost a dimension, instead of being a [3,2] shaped tensor, it's only a [3] shaped tensor.
That would explain why the flip/slice can't index into it with axis=[1].

I checked this with the nightly cpu torch version, same problem. (the log copied here is from the nightly)

Unfortunately removing @torch.jit.script from spatial_shapes_helper is not really something I want to do, because I want to be able to infer on dynamic shaped inputs.

A side question:
If I had the forward function as a single list input_embeds, instead of
input_embeds0, input_embeds1, input_embeds2,
then how do I specify the dynamic_axes for torch.onnx.export?
Could I do it with:
input_names = ["embeds"]
dynamic_axes={"embeds": [2,3]} ?
embeds in this case is a list or a sequence of tensors, and while in my case all 3 members of it needs to have [2,3] axes to be dynamic, it could also happen that they have different dynamic axes each, so how do I refer to them then?

Thanks

### Versions

```
Collecting environment information...
PyTorch version: 2.2.0.dev20231005+cpu
Is debug build: False
CUDA used to build PyTorch: Could not collect
ROCM used to build PyTorch: N/A

OS: Ubuntu 22.04.3 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.25.3
Libc version: glibc-2.35

Python version: 3.10.12 | packaged by conda-forge | (main, Jun 23 2023, 22:40:32) [GCC 12.3.0] (64-bit runtime)
Python platform: Linux-6.2.0-26-generic-x86_64-with-glibc2.35
Is CUDA available: False
CUDA runtime version: 12.1.66
CUDA_MODULE_LOADING set to: N/A
GPU models and configuration: 
GPU 0: NVIDIA GeForce GTX 1080
GPU 1: NVIDIA GeForce GTX 1080

Nvidia driver version: 535.113.01
cuDNN version: Probably one of the following:
/usr/lib/x86_64-linux-gnu/libcudnn.so.8.8.1
/usr/lib/x86_64-linux-gnu/libcudnn_adv_infer.so.8.8.1
/usr/lib/x86_64-linux-gnu/libcudnn_adv_train.so.8.8.1
/usr/lib/x86_64-linux-gnu/libcudnn_cnn_infer.so.8.8.1
/usr/lib/x86_64-linux-gnu/libcudnn_cnn_train.so.8.8.1
/usr/lib/x86_64-linux-gnu/libcudnn_ops_infer.so.8.8.1
/usr/lib/x86_64-linux-gnu/libcudnn_ops_train.so.8.8.1
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):                          8
On-line CPU(s) list:             0-7
Vendor ID:                       GenuineIntel
Model name:                      Intel(R) Core(TM) i7-6700T CPU @ 2.80GHz
CPU family:                      6
Model:                           94
Thread(s) per core:              2
Core(s) per socket:              4
Socket(s):                       1
Stepping:                        3
CPU max MHz:                     3600.0000
CPU min MHz:                     800.0000
BogoMIPS:                        5599.85
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 sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault invpcid_single pti ssbd ibrs ibpb stibp 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:                       128 KiB (4 instances)
L1i cache:                       128 KiB (4 instances)
L2 cache:                        1 MiB (4 instances)
L3 cache:                        8 MiB (1 instance)
NUMA node(s):                    1
NUMA node0 CPU(s):               0-7
Vulnerability Itlb multihit:     KVM: Mitigation: VMX disabled
Vulnerability L1tf:              Mitigation; PTE Inversion; VMX conditional cache flushes, SMT vulnerable
Vulnerability Mds:               Mitigation; Clear CPU buffers; SMT vulnerable
Vulnerability Meltdown:          Mitigation; PTI
Vulnerability Mmio stale data:   Mitigation; Clear CPU buffers; SMT vulnerable
Vulnerability Retbleed:          Mitigation; 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; IBRS, IBPB conditional, STIBP conditional, RSB filling, PBRSB-eIBRS Not affected
Vulnerability Srbds:             Mitigation; Microcode
Vulnerability Tsx async abort:   Mitigation; TSX disabled

Versions of relevant libraries:
[pip3] numpy==1.24.1
[pip3] onnx==1.14.1
[pip3] torch==2.2.0.dev20231005+cpu
[pip3] torchaudio==2.2.0.dev20231005+cpu
[pip3] torchvision==0.17.0.dev20231005+cpu
[conda] numpy                     1.24.1                   pypi_0    pypi
[conda] torch                     2.2.0.dev20231005+cpu          pypi_0    pypi
[conda] torchaudio                2.2.0.dev20231005+cpu          pypi_0    pypi
[conda] torchvision               0.17.0.dev20231005+cpu          pypi_0    pypi
```