Repository: pytorch
Issue: Torchscript: Name Mangling prevents Type Refinement
Labels: oncall: jit

### 🐛 Describe the bug

Name mangling in Torchscript prevents type refinement. See the following script for an example:

```python
from typing import Tuple

import torch
from torch import nn
from torch import Tensor

class A(nn.Module):

    def __init__(self, s: int):
        super().__init__()
        self.linear = nn.Linear(int(s**2), int(s**2))

    def forward(self, x: Tensor):
        return x


class Sequence(nn.Module):

    def __init__(self, n_modules: int):
        super().__init__()
        self.mods = nn.ModuleList([])
        for i in range(n_modules):
            self.mods.append(A(i + 1))

    def forward(self, x):
        tmp : Tuple[A] = (self.mods[0], self.mods[1])
        for mod in self.mods:
            assert isinstance(mod, A)
            x = mod(x)
        return x

if __name__ == "__main__":
    seq = Sequence(3)
    seqs = torch.jit.script(seq)

```
The script fails with the following error:
```
Traceback (most recent call last):
  File "problem.py", line 34, in <module>
    seqs = torch.jit.script(seq)
  File "/home/schuetze/.local/lib/python3.8/site-packages/torch/jit/_script.py", line 1284, in script
    return torch.jit._recursive.create_script_module(
  File "/home/schuetze/.local/lib/python3.8/site-packages/torch/jit/_recursive.py", line 480, in create_script_module
    return create_script_module_impl(nn_module, concrete_type, stubs_fn)
  File "/home/schuetze/.local/lib/python3.8/site-packages/torch/jit/_recursive.py", line 546, in create_script_module_impl
    create_methods_and_properties_from_stubs(concrete_type, method_stubs, property_stubs)
  File "/home/schuetze/.local/lib/python3.8/site-packages/torch/jit/_recursive.py", line 397, in create_meth

ods_and_properties_from_stubs
    concrete_type._create_methods_and_properties(property_defs, property_rcbs, method_defs, method_rcbs, method_defaults)
RuntimeError: 
Variable 'tmp' is annotated with type Tuple[__torch__.A] but is being assigned to a value of type Tuple[__torch__.A, __torch__.___torch_mangle_1.A]:
  File "problem.py", line 26
    def forward(self, x):
        tmp : Tuple[A] = (self.mods[0], self.mods[1])
        ~~~ <--- HERE
        for mod in self.mods:
            assert isinstance(mod, A)
```
The types of the different elements are mangled names, and therefore I cannot do type refinment. Is there a way for me around this problem? 

_For context (in case it matters):_
I need to use type refinement because I need to help the compiler with some overload resolution. In the real example, there's not just class A, but also class B and I need to tell the compiler that some element of a nn.ModuleList have the same type and what that type is.  

### 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.18.2
Libc version: glibc-2.31

Python version: 3.8.10 (default, Mar 13 2023, 10:26:41)  [GCC 9.4.0] (64-bit runtime)
Python platform: Linux-5.15.0-67-generic-x86_64-with-glibc2.29
Is CUDA available: False
CUDA runtime version: No CUDA
CUDA_MODULE_LOADING set to: N/A
GPU models and configuration: No CUDA
Nvidia driver version: No CUDA
cuDNN version: No CUDA
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:                   39 bits physical, 48 bits virtual
CPU(s):                          4
On-line CPU(s) list:             0-3
Thread(s) per core:              2
Core(s) per socket:              2
Socket(s):                       1
NUMA node(s):                    1
Vendor ID:                       GenuineIntel
CPU family:                      6
Model:                           78
Model name:                      Intel(R) Core(TM) i7-6600U CPU @ 2.60GHz
Stepping:                        3
CPU MHz:                         2800.000
CPU max MHz:                     3400,0000
CPU min MHz:                     400,0000
BogoMIPS:                        5599.85
Virtualization:                  VT-x
L1d cache:                       64 KiB
L1i cache:                       64 KiB
L2 cache:                        512 KiB
L3 cache:                        4 MiB
NUMA node0 CPU(s):               0-3
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 and seccomp
Vulnerability Spectre v1:        Mitigation; usercopy/swapgs barriers and __user pointer sanitization
Vulnerability Spectre v2:        Mitigation; IBRS, IBPB conditional, RSB filling, PBRSB-eIBRS Not affected
Vulnerability Srbds:             Mitigation; Microcode
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 sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault epb 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

Versions of relevant libraries:
[pip3] flake8==5.0.4
[pip3] functorch==1.13.1
[pip3] mypy==0.982
[pip3] mypy-extensions==0.4.3
[pip3] numpy==1.24.2
[pip3] numpy-financial==1.0.0
[pip3] onnx2torch==1.5.6
[pip3] pytorch-lightning==1.5.4
[pip3] pytorch3d==0.7.3
[pip3] torch==2.0.0
[pip3] torch-tb-profiler==0.4.0
[pip3] torchdata==0.6.0
[pip3] torchmetrics==0.9.3
[pip3] torchtext==0.15.1
[pip3] torchvision==0.15.1
[pip3] triton==2.0.0
[pip3] tritonclient==2.27.0
[conda] Could not collect


cc @EikanWang @jgong5 @wenzhe-nrv @sanchitintel