Repository: pytorch
Issue: OptimizedModule __getattr__ may causes dead recursive call loop
Labels: module: nn,triaged,oncall: pt2,module: dynamo

### 🐛 Describe the bug

It is a common practice to compile a region of a large model to save compiling time like the following:
```python
class Model(torch.nn.Module):
    def __init__(self, apply_regional_compilation):
        super().__init__()
        self.linear = torch.nn.Linear(10, 10)
        # Apply compile only to the repeated layers.
        if apply_regional_compilation:
            self.layers = torch.nn.ModuleList(
                [torch.compile(Layer()) for _ in range(64)]
            )
        else:
            self.layers = torch.nn.ModuleList([Layer() for _ in range(64)])
```
While use this on LLAMA2 with DeepSpeed, OptimizedModule causes dead recursive call loop on its   __getattr__ method.

```python
  File "/home/haifchen/working/envs/env_test_nightly/lib/python3.10/site-packages/torch/_dynamo/eval_frame.py", line 220, in __getattr__
    return getattr(self._orig_mod, name)
  File "/home/haifchen/working/envs/env_test_nightly/lib/python3.10/site-packages/torch/_dynamo/eval_frame.py", line 219, in __getattr__
    return self._modules["_orig_mod"]
  File "/home/haifchen/working/envs/env_test_nightly/lib/python3.10/site-packages/torch/_dynamo/eval_frame.py", line 220, in __getattr__
    return getattr(self._orig_mod, name)
  File "/home/haifchen/working/envs/env_test_nightly/lib/python3.10/site-packages/torch/_dynamo/eval_frame.py", line 219, in __getattr__
    return self._modules["_orig_mod"]
  File "/home/haifchen/working/envs/env_test_nightly/lib/python3.10/site-packages/torch/_dynamo/eval_frame.py", line 220, in __getattr__
    return getattr(self._orig_mod, name)
  File "/home/haifchen/working/envs/env_test_nightly/lib/python3.10/site-packages/torch/_dynamo/eval_frame.py", line 218, in __getattr__
    if name == "_orig_mod":
RecursionError: maximum recursion depth exceeded in comparison
```
DeepSpeed uses some techniques to prepare the subclasses of torch.nn.Module before __init__ and calling hasattr and setattr before the object is initialized by its original __init__ method. In this case, the current implementation of OptimizedModule __getattr__ cannot handle such case and causes dead recursive loop.

Below is the simple producer which simulates what DeepSpeed is doing and reproduce the same problem:

```python
import torch
import functools

class MyModule(torch.nn.Module):
  def __init__(self):
      super().__init__()

  def forward(self, x):
      return x.mul(5.0)


def partition_after(f):
    @functools.wraps(f)
    def wrapper(module, *args, **kwargs):
        if not hasattr(module, "_ds_child_entered"):
            # child's __init__ was called, since parents all see the same object they can now skip post_init
            setattr(module, "_ds_child_entered", True)

        f(module, *args, **kwargs)

    return wrapper


def _enable_class(cls):
    if '__init__' in cls.__dict__:
        cls._old_init = cls.__init__
        cls.__init__ = partition_after(cls.__init__)


# https://stackoverflow.com/a/63851681/9201239
def get_all_subclasses(cls, include_root=True):
    subclass_list = []

    def recurse(cl):
        for subclass in cl.__subclasses__():
            subclass_list.append(subclass)
            recurse(subclass)

    recurse(cls)

    ret = set(subclass_list)
    if include_root:
        ret.add(cls)
    return ret


for subclass in get_all_subclasses(torch.nn.modules.module.Module):
  _enable_class(subclass)   

module = MyModule()
module = torch.compile(module)

```

### Versions

Collecting environment information...
PyTorch version: 2.6.0.dev20240914+cpu
Is debug build: False
CUDA used to build PyTorch: None
ROCM used to build PyTorch: N/A

OS: Ubuntu 22.04 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.22.1
Libc version: glibc-2.35

Python version: 3.10.12 (main, Sep 11 2024, 15:47:36) [GCC 11.4.0] (64-bit runtime)
Python platform: Linux-5.15.0-122-generic-x86_64-with-glibc2.35
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
Address sizes:                        43 bits physical, 48 bits virtual
Byte Order:                           Little Endian
CPU(s):                               12
On-line CPU(s) list:                  0-11
Vendor ID:                            GenuineIntel
Model name:                           Intel(R) Xeon(R) Gold 6230 CPU @ 2.10GHz
CPU family:                           6
Model:                                85
Thread(s) per core:                   1
Core(s) per socket:                   6
Socket(s):                            2
Stepping:                             0
BogoMIPS:                             4190.15
Flags:                                fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ss ht syscall nx pdpe1gb rdtscp lm constant_tsc arch_perfmon nopl xtopology tsc_reliable nonstop_tsc cpuid tsc_known_freq pni pclmulqdq vmx ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand hypervisor lahf_lm abm 3dnowprefetch invpcid_single pti ssbd ibrs ibpb stibp tpr_shadow vnmi ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 invpcid avx512f avx512dq rdseed adx smap clflushopt clwb avx512cd avx512bw avx512vl xsaveopt xsavec xsaves arat pku ospke md_clear flush_l1d arch_capabilities
Virtualization:                       VT-x
Hypervisor vendor:                    VMware
Virtualization type:                  full
L1d cache:                            384 KiB (12 instances)
L1i cache:                            384 KiB (12 instances)
L2 cache:                             12 MiB (12 instances)
L3 cache:                             55 MiB (2 instances)
NUMA node(s):                         1
NUMA node0 CPU(s):                    0-11
Vulnerability Gather data sampling:   Unknown: Dependent on hypervisor status
Vulnerability Itlb multihit:          KVM: Mitigation: VMX disabled
Vulnerability L1tf:                   Mitigation; PTE Inversion; VMX flush not necessary, SMT disabled
Vulnerability Mds:                    Mitigation; Clear CPU buffers; SMT Host state unknown
Vulnerability Meltdown:               Mitigation; PTI
Vulnerability Mmio stale data:        Mitigation; Clear CPU buffers; SMT Host state unknown
Vulnerability Reg file data sampling: Not affected
Vulnerability Retbleed:               Mitigation; IBRS
Vulnerability Spec rstack overflow:   Not affected
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; STIBP disabled; RSB filling; PBRSB-eIBRS Not affected; BHI SW loop, KVM SW loop
Vulnerability Srbds:                  Not affected
Vulnerability Tsx async abort:        Not affected

Versions of relevant libraries:
[pip3] numpy==2.1.1
[pip3] torch==2.6.0.dev20240914+cpu
[conda] Could not collect


cc @albanD @mruberry @jbschlosser @walterddr @mikaylagawarecki @ezyang @chauhang @penguinwu @voznesenskym @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @chenyang78 @kadeng @amjames @rec