pytorch - 💡(How to fix) Fix [Dynamo] Unable to trace RemovableHandle when register_forward_hook is called conditionally in forward method [1 comments, 2 participants]

Official PRs (…)
ON THIS PAGE

Recommended Tools

×6

Utilities matched from this issue’s tags and category — try them while you read without losing context.

GitHub issue graph ai analysis

Paste a GitHub issue URL. We fetch that issue, discover linked issues from bodies/comments/timeline, collect linked pull requests, and produce a structured English report.

The report is written in English Markdown for sharing and archival.

Helpful · Quick feedback

Loading…
GitHub stats
pytorch/pytorch#178265Fetched 2026-04-08 01:20:49
View on GitHub
Comments
1
Participants
2
Timeline
48
Reactions
0
Timeline (top)
mentioned ×20subscribed ×20labeled ×5commented ×1

Root Cause

output:

Attempted to represent unregistered RemovableHandle Explanation: Dynamo attempted to build a representation of a torch.utils.hooks.RemovableHandle, which is not supported. This happens because the RemovableHandle was created in another frame.

Fix Action

Fix / Workaround

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): 32 On-line CPU(s) list: 0-31 Vendor ID: GenuineIntel Model name: Intel(R) Core(TM) i9-14900HX CPU family: 6 Model: 183 Thread(s) per core: 2 Core(s) per socket: 24 Socket(s): 1 Stepping: 1 CPU(s) scaling MHz: 31% CPU max MHz: 5800.0000 CPU min MHz: 800.0000 BogoMIPS: 4838.40 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 tsc_known_freq pni pclmulqdq dtes64 monitor ds_cpl vmx 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 ssbd ibrs ibpb stibp ibrs_enhanced tpr_shadow flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid rdseed adx smap clflushopt clwb intel_pt sha_ni xsaveopt xsavec xgetbv1 xsaves split_lock_detect user_shstk avx_vnni dtherm ida arat pln pts hwp hwp_notify hwp_act_window hwp_epp hwp_pkg_req hfi vnmi umip pku ospke waitpkg gfni vaes vpclmulqdq rdpid movdiri movdir64b fsrm md_clear serialize arch_lbr ibt flush_l1d arch_capabilities Virtualization: VT-x L1d cache: 896 KiB (24 instances) L1i cache: 1.3 MiB (24 instances) L2 cache: 32 MiB (12 instances) L3 cache: 36 MiB (1 instance) NUMA node(s): 1 NUMA node0 CPU(s): 0-31 Vulnerability Gather data sampling: Not affected Vulnerability Ghostwrite: Not affected Vulnerability Indirect target selection: 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 Reg file data sampling: Mitigation; Clear Register File Vulnerability Retbleed: Not affected Vulnerability Spec rstack overflow: Not affected 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 / Automatic IBRS; IBPB conditional; PBRSB-eIBRS SW sequence; BHI BHI_DIS_S Vulnerability Srbds: Not affected Vulnerability Tsx async abort: Not affected

Code Example

import torch
import torch.nn as nn
class SparseAutoencoder(nn.Module):
    def __init__(self, input_dim, encoding_dim):
        super().__init__()
        self.encoder = nn.Linear(input_dim, encoding_dim)
        self.decoder = nn.Linear(encoding_dim, input_dim)
    def forward(self, x):
        if not hasattr(self, '_forward_hook'):
            self._forward_hook = self.register_forward_hook(
                lambda module, inputs, output: output + 1)
        encoded = self.encoder(x)
        decoded = self.decoder(encoded)
        return decoded
def main():
    model = SparseAutoencoder(784, 64)
    model.eval()
    inputs = torch.randn(4, 784)
    with torch.no_grad():
        output_eager = model(inputs)
    print(f'Eager output shape: {output_eager.shape}')
    compiled_model = torch.compile(model, fullgraph=True)
    with torch.no_grad():
        output_compile = compiled_model(inputs)
    print(f'Compile output shape: {output_compile.shape}')
if __name__ == '__main__':
    main()

---

Attempted to represent unregistered RemovableHandle
Explanation: Dynamo attempted to build a representation of a 
torch.utils.hooks.RemovableHandle, which is not supported. 
This happens because the RemovableHandle was created in another frame.

Developer debug context:
from user code:
  File "example.py", line 13, in forward
    if not hasattr(self, '_forward_hook'): self._forward_hook = self.register_forward_hook(
RAW_BUFFERClick to expand / collapse

🐛 Describe the bug

Description: When compiling a model with conditional registration forward hooks using torch.compile, Dynamo was unable to track the torch.utils.hooks.MoveableHandle object, resulting in compilation failure. code:

import torch
import torch.nn as nn
class SparseAutoencoder(nn.Module):
    def __init__(self, input_dim, encoding_dim):
        super().__init__()
        self.encoder = nn.Linear(input_dim, encoding_dim)
        self.decoder = nn.Linear(encoding_dim, input_dim)
    def forward(self, x):
        if not hasattr(self, '_forward_hook'):
            self._forward_hook = self.register_forward_hook(
                lambda module, inputs, output: output + 1)
        encoded = self.encoder(x)
        decoded = self.decoder(encoded)
        return decoded
def main():
    model = SparseAutoencoder(784, 64)
    model.eval()
    inputs = torch.randn(4, 784)
    with torch.no_grad():
        output_eager = model(inputs)
    print(f'Eager output shape: {output_eager.shape}')
    compiled_model = torch.compile(model, fullgraph=True)
    with torch.no_grad():
        output_compile = compiled_model(inputs)
    print(f'Compile output shape: {output_compile.shape}')
if __name__ == '__main__':
    main()

output:

Attempted to represent unregistered RemovableHandle
Explanation: Dynamo attempted to build a representation of a 
torch.utils.hooks.RemovableHandle, which is not supported. 
This happens because the RemovableHandle was created in another frame.

Developer debug context:
from user code:
  File "example.py", line 13, in forward
    if not hasattr(self, '_forward_hook'): self._forward_hook = self.register_forward_hook(

Versions

PyTorch version: 2.8.0+cu126 Is debug build: False CUDA used to build PyTorch: 12.6 ROCM used to build PyTorch: N/A

OS: Ubuntu 24.04.1 LTS (x86_64) GCC version: (Ubuntu 9.5.0-6ubuntu2) 9.5.0 Clang version: Could not collect CMake version: version 4.0.3 Libc version: glibc-2.39

Python version: 3.9.7 (default, Jul 16 2025, 16:34:47) [GCC 13.3.0] (64-bit runtime) Python platform: Linux-6.14.0-29-generic-x86_64-with-glibc2.39 Is CUDA available: False CUDA runtime version: Could not collect CUDA_MODULE_LOADING set to: N/A GPU models and configuration: GPU 0: NVIDIA GeForce RTX 4060 Laptop GPU Nvidia driver version: 580.65.06 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 Address sizes: 39 bits physical, 48 bits virtual Byte Order: Little Endian CPU(s): 32 On-line CPU(s) list: 0-31 Vendor ID: GenuineIntel Model name: Intel(R) Core(TM) i9-14900HX CPU family: 6 Model: 183 Thread(s) per core: 2 Core(s) per socket: 24 Socket(s): 1 Stepping: 1 CPU(s) scaling MHz: 31% CPU max MHz: 5800.0000 CPU min MHz: 800.0000 BogoMIPS: 4838.40 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 tsc_known_freq pni pclmulqdq dtes64 monitor ds_cpl vmx 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 ssbd ibrs ibpb stibp ibrs_enhanced tpr_shadow flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid rdseed adx smap clflushopt clwb intel_pt sha_ni xsaveopt xsavec xgetbv1 xsaves split_lock_detect user_shstk avx_vnni dtherm ida arat pln pts hwp hwp_notify hwp_act_window hwp_epp hwp_pkg_req hfi vnmi umip pku ospke waitpkg gfni vaes vpclmulqdq rdpid movdiri movdir64b fsrm md_clear serialize arch_lbr ibt flush_l1d arch_capabilities Virtualization: VT-x L1d cache: 896 KiB (24 instances) L1i cache: 1.3 MiB (24 instances) L2 cache: 32 MiB (12 instances) L3 cache: 36 MiB (1 instance) NUMA node(s): 1 NUMA node0 CPU(s): 0-31 Vulnerability Gather data sampling: Not affected Vulnerability Ghostwrite: Not affected Vulnerability Indirect target selection: 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 Reg file data sampling: Mitigation; Clear Register File Vulnerability Retbleed: Not affected Vulnerability Spec rstack overflow: Not affected 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 / Automatic IBRS; IBPB conditional; PBRSB-eIBRS SW sequence; BHI BHI_DIS_S Vulnerability Srbds: Not affected Vulnerability Tsx async abort: Not affected

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

extent analysis

Fix Plan

To resolve the issue with torch.compile failing due to the inability to track torch.utils.hooks.MoveableHandle objects, we need to ensure that the forward hook is registered outside of the forward method. This is because the hook registration should be done at the module initialization level, not within the forward pass.

Here are the steps to fix the issue:

  1. Register the forward hook in the __init__ method: Move the registration of the forward hook to the __init__ method of the SparseAutoencoder class. This ensures that the hook is registered when the module is initialized, rather than during the forward pass.
class SparseAutoencoder(nn.Module):
    def __init__(self, input_dim, encoding_dim):
        super().__init__()
        self.encoder = nn.Linear(input_dim, encoding_dim)
        self.decoder = nn.Linear(encoding_dim, input_dim)
        self._forward_hook = self.register_forward_hook(
            lambda module, inputs, output: output + 1)
  1. Remove the conditional hook registration: Since the hook is now registered in the __init__ method, you can remove the conditional check and registration from the forward method.
def forward(self, x):
    encoded = self.encoder(x)
    decoded = self.decoder(encoded)
    return decoded

Verification

After applying these changes, you should be able to compile the model using torch.compile without encountering the error related to torch.utils.hooks.MoveableHandle.

compiled_model = torch.compile(model, fullgraph=True)
with torch.no_grad():
    output_compile = compiled_model(inputs)
print(f'Compile output shape: {output_compile.shape}')

Extra Tips

  • Always register hooks at the module initialization level (__init__) rather than within the forward pass to avoid issues with torch.compile.
  • Ensure that any modifications to the module's behavior are done in a way that is compatible with torch.compile's requirements.

Vote matrix · Quick signals

Works
Did the solution work? Tap to confirm.
Easy Fix
Was it a quick fix?
Time Saver
Did it save you time?
Blocking
Was it severely blocking?
Common Issue
Are others likely hitting this too?
Flaky / Intermittent
Is it intermittent?
Verified / Reproducible
Can you reproduce it reliably?
Loading…

Still need to ship something?

×6

Another batch ranked right after the header list — different links, same matching logic.

Back to top recommendations

TRENDING