pytorch - 💡(How to fix) Fix [TorchDynamo] Failed to trace builtin operator 'setattr' when registering forward hook inside forward method [1 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#178248Fetched 2026-04-08 01:21:03
View on GitHub
Comments
0
Participants
1
Timeline
94
Reactions
0
Participants
Timeline (top)
mentioned ×45subscribed ×45labeled ×4

Error Message

import os import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torchvision import datasets, transforms import matplotlib.pyplot as plt

class SparseAutoencoder(nn.Module):

def __init__(self, input_dim, encoding_dim, sparsity_target=0.05, sparsity_weight=0.2):
    super().__init__()
    self.encoder = nn.Sequential(nn.Linear(input_dim, 256), nn.ReLU(), nn.Linear(256, 128), nn.ReLU(), nn.Linear(128, encoding_dim), nn.Sigmoid())
    self.decoder = nn.Sequential(nn.Linear(encoding_dim, 128), nn.ReLU(), nn.Linear(128, 256), nn.ReLU(), nn.Linear(256, input_dim), nn.Sigmoid())
    self.sparsity_target = sparsity_target
    self.sparsity_weight = sparsity_weight

def forward(self, x):
    self.register_forward_hook(lambda module, inputs, output: output + 1)
    encoded = self.encoder(x)
    decoded = self.decoder(encoded)
    return (encoded, decoded)

def kl_divergence(self, encoded):
    batch_size = encoded.size(0)
    sparsity = torch.mean(encoded, dim=0)
    kl = self.sparsity_target * torch.log(self.sparsity_target / sparsity) + (1 - self.sparsity_target) * torch.log((1 - self.sparsity_target) / (1 - sparsity))
    return torch.sum(kl) * self.sparsity_weight / batch_size

def get_default_model(): input_dim = 784 encoding_dim = 64 sparsity_target = 0.05 sparsity_weight = 0.2 model = SparseAutoencoder(input_dim=input_dim, encoding_dim=encoding_dim, sparsity_target=sparsity_target, sparsity_weight=sparsity_weight) return model def get_sample_inputs(): batch_size = 4 input_dim = 784 x = torch.randn(batch_size, input_dim) return (x,) def main(): model = get_default_model() model.eval() inputs = get_sample_inputs() try: with torch.no_grad(): output_eager = model(*inputs) print(f'Eager: {output_eager}') except Exception as e: print(f'Eager: {e}') try: compiled_model = torch.compile(model, fullgraph=True) with torch.no_grad(): output_compile = compiled_model(*inputs) print(f'Compile: {output_compile}') except Exception as e: print(f'\nOriginal exception:\n {e}') if name == 'main': main()

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 os
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets, transforms
import matplotlib.pyplot as plt

class SparseAutoencoder(nn.Module):

    def __init__(self, input_dim, encoding_dim, sparsity_target=0.05, sparsity_weight=0.2):
        super().__init__()
        self.encoder = nn.Sequential(nn.Linear(input_dim, 256), nn.ReLU(), nn.Linear(256, 128), nn.ReLU(), nn.Linear(128, encoding_dim), nn.Sigmoid())
        self.decoder = nn.Sequential(nn.Linear(encoding_dim, 128), nn.ReLU(), nn.Linear(128, 256), nn.ReLU(), nn.Linear(256, input_dim), nn.Sigmoid())
        self.sparsity_target = sparsity_target
        self.sparsity_weight = sparsity_weight

    def forward(self, x):
        self.register_forward_hook(lambda module, inputs, output: output + 1)
        encoded = self.encoder(x)
        decoded = self.decoder(encoded)
        return (encoded, decoded)

    def kl_divergence(self, encoded):
        batch_size = encoded.size(0)
        sparsity = torch.mean(encoded, dim=0)
        kl = self.sparsity_target * torch.log(self.sparsity_target / sparsity) + (1 - self.sparsity_target) * torch.log((1 - self.sparsity_target) / (1 - sparsity))
        return torch.sum(kl) * self.sparsity_weight / batch_size
def get_default_model():
    input_dim = 784
    encoding_dim = 64
    sparsity_target = 0.05
    sparsity_weight = 0.2
    model = SparseAutoencoder(input_dim=input_dim, encoding_dim=encoding_dim, sparsity_target=sparsity_target, sparsity_weight=sparsity_weight)
    return model
def get_sample_inputs():
    batch_size = 4
    input_dim = 784
    x = torch.randn(batch_size, input_dim)
    return (x,)
def main():
    model = get_default_model()
    model.eval()
    inputs = get_sample_inputs()
    try:
        with torch.no_grad():
            output_eager = model(*inputs)
        print(f'Eager: {output_eager}')
    except Exception as e:
        print(f'Eager: {e}')
    try:
        compiled_model = torch.compile(model, fullgraph=True)
        with torch.no_grad():
            output_compile = compiled_model(*inputs)
        print(f'Compile: {output_compile}')
    except Exception as e:
        print(f'\nOriginal exception:\n {e}')
if __name__ == '__main__':
    main()

---

Eager: (tensor([[0.4980, 0.4772, 0.4928, 0.5248, 0.4728, 0.4748, 0.4807, 0.5189, 0.5188,
         0.5053, 0.5355, 0.4544, 0.4762, 0.5008, 0.5567, 0.4593, 0.4884, 0.5207,
         0.5287, 0.4646, 0.4630, 0.4927, 0.4501, 0.5756, 0.5020, 0.4781, 0.4223,
         0.5599, 0.4474, 0.5085, 0.4707, 0.5603, 0.5242, 0.4737, 0.4569, 0.5207,
         0.4648, 0.5448, 0.4591, 0.5110, 0.5515, 0.5431, 0.5471, 0.4772, 0.4770,
         0.5336, 0.5214, 0.5311, 0.5131, 0.4841, 0.5102, 0.5083, 0.5347, 0.5124,
         0.4950, 0.5303, 0.4624, 0.4805, 0.5298, 0.4767, 0.4948, 0.4854, 0.4578,
         0.5147],
        [0.4941, 0.4843, 0.4715, 0.5051, 0.5241, 0.4687, 0.4887, 0.5101, 0.5569,
         0.4617, 0.5028, 0.4705, 0.4931, 0.4943, 0.5050, 0.4851, 0.5230, 0.5168,
         0.4997, 0.4783, 0.4599, 0.4539, 0.4747, 0.5509, 0.5104, 0.4769, 0.4053,
         0.5110, 0.4991, 0.5151, 0.5275, 0.5307, 0.5119, 0.5007, 0.4559, 0.4389,
         0.4773, 0.4955, 0.4750, 0.4993, 0.4723, 0.5081, 0.4793, 0.5502, 0.5016,
         0.4841, 0.5207, 0.5157, 0.4994, 0.5006, 0.4613, 0.4838, 0.5079, 0.4801,
         0.5285, 0.5256, 0.4580, 0.5184, 0.4843, 0.4890, 0.5168, 0.4920, 0.4372,
         0.4921],
        [0.4849, 0.4582, 0.4386, 0.5377, 0.4726, 0.4576, 0.4769, 0.4819, 0.5358,
         0.5273, 0.5134, 0.4771, 0.5200, 0.4884, 0.4971, 0.4947, 0.4746, 0.5201,
         0.4828, 0.5078, 0.4696, 0.4379, 0.4855, 0.5784, 0.5112, 0.4696, 0.4498,
         0.5049, 0.4914, 0.5147, 0.5044, 0.5266, 0.4983, 0.5290, 0.4958, 0.4826,
         0.4451, 0.5127, 0.5175, 0.5183, 0.5410, 0.5129, 0.5054, 0.4961, 0.4770,
         0.5234, 0.5363, 0.5256, 0.4991, 0.5065, 0.5297, 0.4849, 0.5443, 0.4862,
         0.5003, 0.5045, 0.4395, 0.4909, 0.4939, 0.5121, 0.5032, 0.4944, 0.4746,
         0.4941],
        [0.4982, 0.5292, 0.5094, 0.4805, 0.4903, 0.4609, 0.4801, 0.4908, 0.5126,
         0.4988, 0.5015, 0.4532, 0.5026, 0.5227, 0.4815, 0.4838, 0.4775, 0.4926,
         0.5193, 0.4581, 0.4918, 0.4260, 0.4875, 0.5439, 0.4852, 0.4990, 0.4574,
         0.4894, 0.4954, 0.5139, 0.4945, 0.5367, 0.4898, 0.5236, 0.4480, 0.4801,
         0.4774, 0.5018, 0.4969, 0.5202, 0.5130, 0.4904, 0.5326, 0.5051, 0.4662,
         0.5340, 0.5216, 0.5082, 0.4697, 0.5268, 0.5130, 0.5073, 0.5076, 0.5242,
         0.5280, 0.4764, 0.4439, 0.4865, 0.5302, 0.5064, 0.5105, 0.4896, 0.4386,
         0.5118]]), tensor([[0.4901, 0.4757, 0.5341,  ..., 0.5186, 0.4870, 0.5159],
        [0.4900, 0.4761, 0.5328,  ..., 0.5176, 0.4855, 0.5160],
        [0.4910, 0.4752, 0.5339,  ..., 0.5172, 0.4870, 0.5152],
        [0.4904, 0.4763, 0.5328,  ..., 0.5178, 0.4849, 0.5155]]))

Original exception:
 Failed to trace builtin operator
  Explanation: Dynamo does not know how to trace builtin operator `setattr` with argument types ['type', 'str', 'int'] (has_kwargs False)
  Hint: Avoid calling builtin `setattr` with argument types ['type', 'str', 'int']. Consider using an equivalent alternative function/method to `setattr`.
  Hint: If you are attempting to call a logging function (e.g. `print`), you can try adding it to `torch._dynamo.config.reorderable_logging_functions`.
  Hint: Please report an issue to PyTorch.

  Developer debug context: builtin setattr [<class 'torch._dynamo.variables.user_defined.UserDefinedClassVariable'>, <class 'torch._dynamo.variables.constant.ConstantVariable'>, <class 'torch._dynamo.variables.constant.ConstantVariable'>] False


from user code:
...line 27, in __init__
    RemovableHandle.next_id += 1

Set TORCHDYNAMO_VERBOSE=1 for the internal stack trace (please do this especially if you're reporting a bug to PyTorch). For even more developer context, set TORCH_LOGS="+dynamo"
RAW_BUFFERClick to expand / collapse

🐛 Describe the bug

Description: When using torch.compile(model, fullgraph=True) with a model that registers a forward hook inside the forward method, compilation fails with an error about failing to trace the builtin setattr operator. code:

import os
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets, transforms
import matplotlib.pyplot as plt

class SparseAutoencoder(nn.Module):

    def __init__(self, input_dim, encoding_dim, sparsity_target=0.05, sparsity_weight=0.2):
        super().__init__()
        self.encoder = nn.Sequential(nn.Linear(input_dim, 256), nn.ReLU(), nn.Linear(256, 128), nn.ReLU(), nn.Linear(128, encoding_dim), nn.Sigmoid())
        self.decoder = nn.Sequential(nn.Linear(encoding_dim, 128), nn.ReLU(), nn.Linear(128, 256), nn.ReLU(), nn.Linear(256, input_dim), nn.Sigmoid())
        self.sparsity_target = sparsity_target
        self.sparsity_weight = sparsity_weight

    def forward(self, x):
        self.register_forward_hook(lambda module, inputs, output: output + 1)
        encoded = self.encoder(x)
        decoded = self.decoder(encoded)
        return (encoded, decoded)

    def kl_divergence(self, encoded):
        batch_size = encoded.size(0)
        sparsity = torch.mean(encoded, dim=0)
        kl = self.sparsity_target * torch.log(self.sparsity_target / sparsity) + (1 - self.sparsity_target) * torch.log((1 - self.sparsity_target) / (1 - sparsity))
        return torch.sum(kl) * self.sparsity_weight / batch_size
def get_default_model():
    input_dim = 784
    encoding_dim = 64
    sparsity_target = 0.05
    sparsity_weight = 0.2
    model = SparseAutoencoder(input_dim=input_dim, encoding_dim=encoding_dim, sparsity_target=sparsity_target, sparsity_weight=sparsity_weight)
    return model
def get_sample_inputs():
    batch_size = 4
    input_dim = 784
    x = torch.randn(batch_size, input_dim)
    return (x,)
def main():
    model = get_default_model()
    model.eval()
    inputs = get_sample_inputs()
    try:
        with torch.no_grad():
            output_eager = model(*inputs)
        print(f'Eager: {output_eager}')
    except Exception as e:
        print(f'Eager: {e}')
    try:
        compiled_model = torch.compile(model, fullgraph=True)
        with torch.no_grad():
            output_compile = compiled_model(*inputs)
        print(f'Compile: {output_compile}')
    except Exception as e:
        print(f'\nOriginal exception:\n {e}')
if __name__ == '__main__':
    main()

output:

Eager: (tensor([[0.4980, 0.4772, 0.4928, 0.5248, 0.4728, 0.4748, 0.4807, 0.5189, 0.5188,
         0.5053, 0.5355, 0.4544, 0.4762, 0.5008, 0.5567, 0.4593, 0.4884, 0.5207,
         0.5287, 0.4646, 0.4630, 0.4927, 0.4501, 0.5756, 0.5020, 0.4781, 0.4223,
         0.5599, 0.4474, 0.5085, 0.4707, 0.5603, 0.5242, 0.4737, 0.4569, 0.5207,
         0.4648, 0.5448, 0.4591, 0.5110, 0.5515, 0.5431, 0.5471, 0.4772, 0.4770,
         0.5336, 0.5214, 0.5311, 0.5131, 0.4841, 0.5102, 0.5083, 0.5347, 0.5124,
         0.4950, 0.5303, 0.4624, 0.4805, 0.5298, 0.4767, 0.4948, 0.4854, 0.4578,
         0.5147],
        [0.4941, 0.4843, 0.4715, 0.5051, 0.5241, 0.4687, 0.4887, 0.5101, 0.5569,
         0.4617, 0.5028, 0.4705, 0.4931, 0.4943, 0.5050, 0.4851, 0.5230, 0.5168,
         0.4997, 0.4783, 0.4599, 0.4539, 0.4747, 0.5509, 0.5104, 0.4769, 0.4053,
         0.5110, 0.4991, 0.5151, 0.5275, 0.5307, 0.5119, 0.5007, 0.4559, 0.4389,
         0.4773, 0.4955, 0.4750, 0.4993, 0.4723, 0.5081, 0.4793, 0.5502, 0.5016,
         0.4841, 0.5207, 0.5157, 0.4994, 0.5006, 0.4613, 0.4838, 0.5079, 0.4801,
         0.5285, 0.5256, 0.4580, 0.5184, 0.4843, 0.4890, 0.5168, 0.4920, 0.4372,
         0.4921],
        [0.4849, 0.4582, 0.4386, 0.5377, 0.4726, 0.4576, 0.4769, 0.4819, 0.5358,
         0.5273, 0.5134, 0.4771, 0.5200, 0.4884, 0.4971, 0.4947, 0.4746, 0.5201,
         0.4828, 0.5078, 0.4696, 0.4379, 0.4855, 0.5784, 0.5112, 0.4696, 0.4498,
         0.5049, 0.4914, 0.5147, 0.5044, 0.5266, 0.4983, 0.5290, 0.4958, 0.4826,
         0.4451, 0.5127, 0.5175, 0.5183, 0.5410, 0.5129, 0.5054, 0.4961, 0.4770,
         0.5234, 0.5363, 0.5256, 0.4991, 0.5065, 0.5297, 0.4849, 0.5443, 0.4862,
         0.5003, 0.5045, 0.4395, 0.4909, 0.4939, 0.5121, 0.5032, 0.4944, 0.4746,
         0.4941],
        [0.4982, 0.5292, 0.5094, 0.4805, 0.4903, 0.4609, 0.4801, 0.4908, 0.5126,
         0.4988, 0.5015, 0.4532, 0.5026, 0.5227, 0.4815, 0.4838, 0.4775, 0.4926,
         0.5193, 0.4581, 0.4918, 0.4260, 0.4875, 0.5439, 0.4852, 0.4990, 0.4574,
         0.4894, 0.4954, 0.5139, 0.4945, 0.5367, 0.4898, 0.5236, 0.4480, 0.4801,
         0.4774, 0.5018, 0.4969, 0.5202, 0.5130, 0.4904, 0.5326, 0.5051, 0.4662,
         0.5340, 0.5216, 0.5082, 0.4697, 0.5268, 0.5130, 0.5073, 0.5076, 0.5242,
         0.5280, 0.4764, 0.4439, 0.4865, 0.5302, 0.5064, 0.5105, 0.4896, 0.4386,
         0.5118]]), tensor([[0.4901, 0.4757, 0.5341,  ..., 0.5186, 0.4870, 0.5159],
        [0.4900, 0.4761, 0.5328,  ..., 0.5176, 0.4855, 0.5160],
        [0.4910, 0.4752, 0.5339,  ..., 0.5172, 0.4870, 0.5152],
        [0.4904, 0.4763, 0.5328,  ..., 0.5178, 0.4849, 0.5155]]))

Original exception:
 Failed to trace builtin operator
  Explanation: Dynamo does not know how to trace builtin operator `setattr` with argument types ['type', 'str', 'int'] (has_kwargs False)
  Hint: Avoid calling builtin `setattr` with argument types ['type', 'str', 'int']. Consider using an equivalent alternative function/method to `setattr`.
  Hint: If you are attempting to call a logging function (e.g. `print`), you can try adding it to `torch._dynamo.config.reorderable_logging_functions`.
  Hint: Please report an issue to PyTorch.

  Developer debug context: builtin setattr [<class 'torch._dynamo.variables.user_defined.UserDefinedClassVariable'>, <class 'torch._dynamo.variables.constant.ConstantVariable'>, <class 'torch._dynamo.variables.constant.ConstantVariable'>] False


from user code:
...line 27, in __init__
    RemovableHandle.next_id += 1

Set TORCHDYNAMO_VERBOSE=1 for the internal stack trace (please do this especially if you're reporting a bug to PyTorch). For even more developer context, set TORCH_LOGS="+dynamo"

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 @chauhang @penguinwu @voznesenskym @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @kadeng @amjames @Lucaskabela @jataylo

extent analysis

Fix Plan

The issue arises from the use of self.register_forward_hook inside the forward method of the model. This hook is not compatible with torch.compile when fullgraph=True.

To fix this issue, we need to refactor the model to avoid registering hooks inside the forward method. Here's a step-by-step solution:

  1. Remove the hook registration from the forward method:

def forward(self, x): # Remove this line # self.register_forward_hook(lambda module, inputs, output: output + 1) encoded = self.encoder(x) decoded = self.decoder(encoded) return (encoded, decoded)


2. **Apply the hook outside the `forward` method**, for example, in the `__init__` method or after the model is initialized:
   ```python
class SparseAutoencoder(nn.Module):
    # ...

    def __init__(self, input_dim, encoding_dim, sparsity_target=0.05, sparsity_weight=0.2):
        super().__init__()
        # ...
        # Register the hook here if necessary
        # self.register_forward_hook(lambda module, inputs, output: output + 1)

# Alternatively, register the hook after model initialization
model = SparseAutoencoder(input_dim=784, encoding_dim=64)
# model.register_forward_hook(lambda module, inputs, output: output + 1)

However, since the hook is modifying the output (output + 1), it might be more appropriate to integrate this modification directly into the forward method to ensure compatibility with torch.compile:

def forward(self, x):
    encoded = self.encoder(x)
    decoded = self.decoder(encoded)
    # Apply the modification directly
    encoded = encoded + 1
    return (encoded, decoded)

Verification

To verify that the fix worked, you should be able to compile the model without encountering the setattr error:

compiled_model = torch.compile(model, fullgraph=True)

Then, use the compiled model for inference:

with torch.no_grad():
    output_compile = compiled_model(*inputs)
print(f'Compile: {output_compile}')

This should print the output of the compiled model without any errors.

Extra Tips

  • When using torch.compile, it's essential to ensure that the model's forward method does not contain operations that are not traceable by PyTorch's dynamic compilation system.
  • Always test your model with and without compilation to ensure that the behavior remains consistent.
  • For more complex models or operations that are not compatible with torch.compile, consider using alternative optimization techniques or refactoring the model to be compatible with dynamic compilation.

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

pytorch - 💡(How to fix) Fix [TorchDynamo] Failed to trace builtin operator 'setattr' when registering forward hook inside forward method [1 participants]