Repository: pytorch
Issue: Torch jit load model with enums
Labels: oncall: jit

### 🐛 Describe the bug

Below I have some code. First I create a model which contains `something` as an int. This value is preserved when the model is saved to file and loaded back in. It is also preserved when the model is loaded from a separate process.

In the second example, an enum is stored in the model. This works when the model is saved and loaded, but not when it is loaded from a separate process. 

How can I navigate this?

The code:

```python
import torch
import subprocess
import sys
from enum import Enum


class Model(torch.nn.Module):
    def __init__(self, something: int):
        super().__init__()
        self.something = something

    def forward(self, x):
        return x


class SomethingElse(Enum):
    Thing1 = 1
    Thing2 = 2


class ModelEnum(torch.nn.Module):
    def __init__(self, something: SomethingElse):
        super().__init__()
        self.something = something

    def forward(self, x):
        return x


def load_model_subprocess(model_path):
    out = subprocess.check_output([sys.executable, "-c", f"import torch; m=torch.jit.load('{model_path}'); print(m.something)"])
    return out.decode().rstrip()


def check_with_val():
    something = 5
    model_path = "model.pt"
    model = Model(something)
    torch.jit.script(model).save(model_path)
    model_reloaded = torch.jit.load(model_path)
    assert model_reloaded.something == something  # <-- this works

    out = load_model_subprocess(model_path)  # <-- this works
    assert out == str(something)


def check_with_enum():
    something = SomethingElse.Thing2
    model_path = "model2.pt"
    model = ModelEnum(something)
    torch.jit.script(model).save(model_path)
    model_reloaded = torch.jit.load(model_path)
    assert model_reloaded.something == something  # <-- this works

    out = load_model_subprocess(model_path)  # <-- this doesn't work
    assert out.decode().rstrip() == str(something)


if __name__ == "__main__":
    check_with_val()
    check_with_enum()
```

The error:

```
Exception has occurred: RuntimeError       (note: full exception trace is shown but execution is paused at: <module>)
Unknown reference to ScriptClass __torch__.SomethingElse. (Did you forget to import it?)
  File "/home/richardbrown/mambaforge/envs/recolour/lib/python3.10/site-packages/torch/jit/_script.py", line 803, in __getattr__
    return self._c.getattr(attr)
  File "<string>", line 1, in <module> (Current frame)
RuntimeError: Unknown reference to ScriptClass __torch__.SomethingElse. (Did you forget to import it?)
```

### Versions

PyTorch version: 2.1.0+cu121
Is debug build: False
CUDA used to build PyTorch: 12.1
ROCM used to build PyTorch: N/A

OS: Ubuntu 20.04.6 LTS (x86_64)
GCC version: (Ubuntu 9.4.0-1ubuntu1~20.04.2) 9.4.0
Clang version: Could not collect
CMake version: version 3.16.3
Libc version: glibc-2.31

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-5.15.0-1043-aws-x86_64-with-glibc2.31
Is CUDA available: True
CUDA runtime version: Could not collect
CUDA_MODULE_LOADING set to: LAZY
GPU models and configuration: GPU 0: NVIDIA A10G
Nvidia driver version: 535.54.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:                      48 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:                          AuthenticAMD
CPU family:                         23
Model:                              49
Model name:                         AMD EPYC 7R32
Stepping:                           0
CPU MHz:                            3268.870
BogoMIPS:                           5599.99
Hypervisor vendor:                  KVM
Virtualization type:                full
L1d cache:                          256 KiB
L1i cache:                          256 KiB
L2 cache:                           4 MiB
L3 cache:                           32 MiB
NUMA node0 CPU(s):                  0-15
Vulnerability Gather data sampling: Not affected
Vulnerability Itlb multihit:        Not affected
Vulnerability L1tf:                 Not affected
Vulnerability Mds:                  Not affected
Vulnerability Meltdown:             Not affected
Vulnerability Mmio stale data:      Not affected
Vulnerability Retbleed:             Mitigation; untrained return thunk; SMT enabled with STIBP protection
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; Retpolines, IBPB conditional, STIBP always-on, RSB filling, PBRSB-eIBRS Not affected
Vulnerability Srbds:                Not affected
Vulnerability Tsx async abort:      Not affected
Flags:                              fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ht syscall nx mmxext fxsr_opt pdpe1gb rdtscp lm constant_tsc rep_good nopl nonstop_tsc cpuid extd_apicid aperfmperf tsc_known_freq pni pclmulqdq ssse3 fma cx16 sse4_1 sse4_2 movbe popcnt aes xsave avx f16c rdrand hypervisor lahf_lm cmp_legacy cr8_legacy abm sse4a misalignsse 3dnowprefetch topoext ssbd ibrs ibpb stibp vmmcall fsgsbase bmi1 avx2 smep bmi2 rdseed adx smap clflushopt clwb sha_ni xsaveopt xsavec xgetbv1 clzero xsaveerptr rdpru wbnoinvd arat npt nrip_save rdpid

Versions of relevant libraries:
[pip3] numpy==1.23.5
[pip3] torch==2.1.0
[pip3] torchvision==0.16.0
[pip3] triton==2.1.0
[conda] numpy                     1.23.5                   pypi_0    pypi
[conda] torch                     2.1.0                    pypi_0    pypi
[conda] torchvision               0.16.0                   pypi_0    pypi
[conda] triton                    2.1.0                    pypi_0    pypi

cc @EikanWang @jgong5 @wenzhe-nrv @sanchitintel