Repository: pytorch
Issue: Get error: "tuple index with non-constant index" when exporting a model to ONNX format
Labels: module: onnx,triaged,onnx-needs-info

### 🐛 Describe the bug

I’m trying to convert a model to onnx format. A function is wrapped by torch.jit.script() in the model forward method. No other torch.jit.script() is uesd. The forward method is following:
```
   def forward(self, img):
        img = self.onnx_trans(img)
        x = self.backbone(img)
        x = self.neck(x)
        mask_feat_pred = self.mask_feat_head(x[self.mask_feat_head.start_level:self.mask_feat_head.end_level + 1])
        cate_preds, kernel_preds = self.bbox_head(x)
        get_seg = torch.jit.script(get_seg_scripted)
        seg_result = get_seg(cate_preds, kernel_preds, mask_feat_pred)
        print(seg_result)
        return seg_result
```
I use the following code to export the model:
```
    cfg = Custom_light_res50(mode='detect')
    cfg.print_cfg()
    model = SOLOv2(cfg).cuda()
    model.load_state_dict(torch.load(cfg.val_weight), strict=True)
    model.eval()

    input_size = (512, 512)
    input_img = cv2.imread('detect_imgs/test1.bmp', cv2.IMREAD_COLOR)
    input_img = cv2.resize(input_img, input_size)
    input_img = torch.from_numpy(input_img).cuda()

    torch.onnx.export(model,
                      input_img,
                      'seg.onnx',
                      input_names=['seg'],
                      output_names=['output'],
                      verbose=False,
                      opset_version=14)

```
I can get the correct value of variable `seg_result`. But still I get the error:
```
Traceback (most recent call last):
  File "/home/feiyu/SOLOv2_minimal/ttt.py", line 99, in <module>
    torch.onnx.export(model,
  File "/home/feiyu/.local/lib/python3.10/site-packages/torch/onnx/utils.py", line 504, in export
    _export(
  File "/home/feiyu/.local/lib/python3.10/site-packages/torch/onnx/utils.py", line 1529, in _export
    graph, params_dict, torch_out = _model_to_graph(
  File "/home/feiyu/.local/lib/python3.10/site-packages/torch/onnx/utils.py", line 1115, in _model_to_graph
    graph = _optimize_graph(
  File "/home/feiyu/.local/lib/python3.10/site-packages/torch/onnx/utils.py", line 582, in _optimize_graph
    _C._jit_pass_lower_all_tuples(graph)
RuntimeError: tuple index with non-constant index
```
Did I do anything wrong? Since I can already get the correct value, which means the forward computation is totally right. Why there’s still an error? Besides, the variable `seg_result` is the final result that I want to get. It's structure: `[[torch.Tensor, torch.Tensor, torch.Tensor]]`. No other procedure after `seg_result` returned.

### Versions

Collecting environment information...
PyTorch version: 1.13.1+cu116
Is debug build: False
CUDA used to build PyTorch: 11.6
ROCM used to build PyTorch: N/A

OS: Ubuntu 22.04.2 LTS (x86_64)
GCC version: (Ubuntu 11.3.0-1ubuntu1~22.04) 11.3.0
Clang version: Could not collect
CMake version: version 3.22.1
Libc version: glibc-2.35

Python version: 3.10.6 (main, Nov 14 2022, 16:10:14) [GCC 11.3.0] (64-bit runtime)
Python platform: Linux-5.19.0-35-generic-x86_64-with-glibc2.35
Is CUDA available: True
CUDA runtime version: 11.6.124
CUDA_MODULE_LOADING set to: LAZY
GPU models and configuration: GPU 0: NVIDIA GeForce RTX 3090
Nvidia driver version: 510.108.03
cuDNN version: Probably one of the following:
/usr/local/cuda-11.6/targets/x86_64-linux/lib/libcudnn.so.8
/usr/local/cuda-11.6/targets/x86_64-linux/lib/libcudnn_adv_infer.so.8
/usr/local/cuda-11.6/targets/x86_64-linux/lib/libcudnn_adv_train.so.8
/usr/local/cuda-11.6/targets/x86_64-linux/lib/libcudnn_cnn_infer.so.8
/usr/local/cuda-11.6/targets/x86_64-linux/lib/libcudnn_cnn_train.so.8
/usr/local/cuda-11.6/targets/x86_64-linux/lib/libcudnn_ops_infer.so.8
/usr/local/cuda-11.6/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):                          20
On-line CPU(s) list:             0-19
Vendor ID:                       GenuineIntel
Model name:                      Intel(R) Core(TM) i9-10900K CPU @ 3.70GHz
CPU family:                      6
Model:                           165
Thread(s) per core:              2
Core(s) per socket:              10
Socket(s):                       1
Stepping:                        5
CPU max MHz:                     5300.0000
CPU min MHz:                     800.0000
BogoMIPS:                        7399.70
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 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 pku ospke md_clear flush_l1d arch_capabilities
Virtualization:                  VT-x
L1d cache:                       320 KiB (10 instances)
L1i cache:                       320 KiB (10 instances)
L2 cache:                        2.5 MiB (10 instances)
L3 cache:                        20 MiB (1 instance)
NUMA node(s):                    1
NUMA node0 CPU(s):               0-19
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:   Not affected

Versions of relevant libraries:
[pip3] numpy==1.24.1
[pip3] torch==1.13.1+cu116
[pip3] torchvision==0.14.1+cu116
[conda] Could not collect