Repository: pytorch
Issue: RuntimeError: `jit.freeze` fails to find externally assigned attributes
Labels: oncall: jit

### 🐛 Describe the bug

```python
import torch
from typing import Dict


class MyModule(torch.nn.Module):
    meta: Dict[str, int]

    def __init__(self, meta):
        super(MyModule, self).__init__()
        # This type cannot be inferred and must be specified
        self.meta = meta

    def forward(self, x):
        return x


m = torch.jit.script(MyModule({"foo": 0}))

assert m.meta == {"foo": 0}

m.extra_attr = torch.jit.Attribute(0, int)
assert m.extra_attr == 0

m = torch.jit.freeze(m.eval(), preserved_attrs=["meta", "extra_attr"])
```

I would expect this to run without error. Instead, `torch.jit.freeze` fails to find the externally assigned attribute `extra_attr`.

```
---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
Cell In[2], line 24
     21 m.extra_attr = torch.jit.Attribute(0, int)
     22 assert m.extra_attr == 0
---> 24 m = torch.jit.freeze(m.eval(), preserved_attrs=["meta", "extra_attr"])
     26 m.meta

File ~/Dev/torch_playground/vepytorch/lib/python3.12/site-packages/torch/jit/_freeze.py:116, in freeze(mod, preserved_attrs, optimize_numerics)
    109     raise RuntimeError(
    110         "Freezing is currently only implemented for modules in eval mode. "
    111         "Please call .eval() on your module before freezing."
    112     )
    114 preserved_attrs = preserved_attrs if preserved_attrs is not None else []
--> 116 out = RecursiveScriptModule(torch._C._freeze_module(mod._c, preserved_attrs))
    117 RecursiveScriptModule._finalize_scriptmodule(out)
    119 preserved_methods = [x for x in preserved_attrs if mod._c._has_method(x)]

RuntimeError: Unknown name: extra_attr~/Dev/torch_playground/vepytorch/lib/python3.12/site-packages/torch/jit/_freeze.py:119) preserved_methods = [x for x in preserved_attrs if mod._c._has_method(x)]

RuntimeError: Unknown name: extra_attr
```

EDIT: Moreover, `extra_attr` does not survive a `torch.jit.save`/`torch.jit.load`:

```python
from io import BytesIO

stream = BytesIO()

m = torch.jit.script(MyModule({"foo": 0}))
m.extra_attr = torch.jit.Attribute(0, int)
torch.jit.save(m, stream)

stream.seek(0)

m = torch.jit.load(stream)
assert m.meta == {"foo": 0}
assert m.extra_attr == 0
# AttributeError: 'RecursiveScriptModule' object has no attribute 'extra_attr'
```

EDIT: What I'm trying to achieve in the end is preserving certain attributes of a module while tracing.

I investigated a bit and it seems that this behavior is because both `torch.jit.freeze` and `torch.jit.save` act solely on `RecursiveScriptModule._c` which can not know about attributes added after instantiation.

### Versions

```
PyTorch version: 2.3.0
Is debug build: False
CUDA used to build PyTorch: Could not collect
ROCM used to build PyTorch: N/A

OS: Linux Mint 21.2 (x86_64)
GCC version: (Ubuntu 11.4.0-1ubuntu1~22.04) 11.4.0
Clang version: Could not collect
CMake version: Could not collect
Libc version: glibc-2.35

Python version: 3.12.3 | packaged by conda-forge | (main, Apr 15 2024, 18:38:13) [GCC 12.3.0] (64-bit runtime)
Python platform: Linux-5.15.0-91-generic-x86_64-with-glibc2.35
Is CUDA available: False
CUDA runtime version: 8.0.61
CUDA_MODULE_LOADING set to: N/A
GPU models and configuration: GPU 0: NVIDIA GeForce GTX TITAN X
Nvidia driver version: 470.223.02
cuDNN version: Could not collect
HIP runtime version: N/A
MIOpen runtime version: N/A
Is XNNPACK available: True

CPU:
Architektur:                        x86_64
CPU Operationsmodus:                32-bit, 64-bit
Adressgrößen:                       39 bits physical, 48 bits virtual
Byte-Reihenfolge:                   Little Endian
CPU(s):                             8
Liste der Online-CPU(s):            0-7
Anbieterkennung:                    GenuineIntel
Modellname:                         Intel(R) Core(TM) i7-6700K CPU @ 4.00GHz
Prozessorfamilie:                   6
Modell:                             94
Thread(s) pro Kern:                 2
Kern(e) pro Socket:                 4
Sockel:                             1
Stepping:                           3
Maximale Taktfrequenz der CPU:      4200.0000
Minimale Taktfrequenz der CPU:      800.0000
BogoMIPS:                           7999.96
Markierungen:                       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 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 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
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-Knoten:                        1
NUMA-Knoten0 CPU(s):                0-7
Schwachstelle Gather data sampling: Not affected
Schwachstelle Itlb multihit:        KVM: Mitigation: VMX unsupported
Schwachstelle L1tf:                 Mitigation; PTE Inversion
Schwachstelle Mds:                  Mitigation; Clear CPU buffers; SMT vulnerable
Schwachstelle Meltdown:             Mitigation; PTI
Schwachstelle Mmio stale data:      Mitigation; Clear CPU buffers; SMT vulnerable
Schwachstelle Retbleed:             Mitigation; IBRS
Schwachstelle Spec rstack overflow: Not affected
Schwachstelle Spec store bypass:    Mitigation; Speculative Store Bypass disabled via prctl and seccomp
Schwachstelle Spectre v1:           Mitigation; usercopy/swapgs barriers and __user pointer sanitization
Schwachstelle Spectre v2:           Mitigation; IBRS, IBPB conditional, STIBP conditional, RSB filling, PBRSB-eIBRS Not affected
Schwachstelle Srbds:                Mitigation; Microcode
Schwachstelle Tsx async abort:      Mitigation; TSX disabled

Versions of relevant libraries:
[pip3] numpy==1.26.4
[pip3] torch==2.3.0
[pip3] torchaudio==2.3.0
[pip3] torchvision==0.18.0
[conda] blas                      1.0                         mkl    conda-forge
[conda] cpuonly                   2.0                           0    pytorch
[conda] ffmpeg                    4.3                  hf484d3e_0    pytorch
[conda] libjpeg-turbo             2.0.0                h9bf148f_0    pytorch
[conda] mkl                       2023.1.0         h213fc3f_46344  
[conda] numpy                     1.26.4          py312heda63a1_0    conda-forge
[conda] pytorch                   2.3.0              py3.12_cpu_0    pytorch
[conda] pytorch-mutex             1.0                         cpu    pytorch
[conda] torchaudio                2.3.0                 py312_cpu    pytorch
[conda] torchvision               0.18.0                py312_cpu    pytorch
```

cc @EikanWang @jgong5 @wenzhe-nrv @sanchitintel