pytorch - 💡(How to fix) Fix [TorchDynamo] NotImplementedError when registering forward hook with lambda expression 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#178250Fetched 2026-04-08 01:21:02
View on GitHub
Comments
0
Participants
1
Timeline
125
Reactions
0
Participants
Timeline (top)
mentioned ×60subscribed ×60labeled ×5

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) 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)
        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.4719, 0.5285, 0.5228, 0.5114, 0.5176, 0.5273, 0.4578, 0.4710, 0.5027,
         0.5016, 0.5485, 0.4698, 0.4932, 0.4811, 0.5236, 0.5477, 0.5188, 0.4853,
         0.4448, 0.5429, 0.5012, 0.4568, 0.5002, 0.5189, 0.5269, 0.5045, 0.4527,
         0.4585, 0.5060, 0.5005, 0.4861, 0.4679, 0.5618, 0.5312, 0.4816, 0.5300,
         0.5179, 0.4879, 0.4863, 0.4953, 0.5116, 0.4844, 0.4582, 0.5155, 0.5182,
         0.4630, 0.4902, 0.5111, 0.5103, 0.4957, 0.4864, 0.5177, 0.5676, 0.4905,
         0.4648, 0.5495, 0.5001, 0.5015, 0.5135, 0.4713, 0.5132, 0.4957, 0.5100,
         0.4352],
        [0.5093, 0.5298, 0.4927, 0.5025, 0.4880, 0.5268, 0.5092, 0.4344, 0.4734,
         0.5028, 0.5505, 0.4586, 0.4952, 0.4901, 0.4871, 0.5256, 0.5097, 0.5069,
         0.4872, 0.4744, 0.4672, 0.4885, 0.4882, 0.5080, 0.5069, 0.4956, 0.4629,
         0.4605, 0.4874, 0.5022, 0.4606, 0.4855, 0.5289, 0.5464, 0.4948, 0.5175,
         0.4920, 0.5399, 0.5055, 0.4832, 0.5321, 0.4962, 0.5072, 0.5339, 0.5009,
         0.5111, 0.5100, 0.5178, 0.4965, 0.4950, 0.5074, 0.5142, 0.5422, 0.4998,
         0.5058, 0.5213, 0.4891, 0.5062, 0.5001, 0.4655, 0.5229, 0.5057, 0.5157,
         0.4779],
        [0.4626, 0.5180, 0.4843, 0.4935, 0.5012, 0.5168, 0.4952, 0.4398, 0.5070,
         0.4678, 0.5590, 0.4713, 0.5052, 0.4868, 0.5093, 0.5055, 0.5083, 0.5347,
         0.4722, 0.4981, 0.5213, 0.4856, 0.4995, 0.4879, 0.5190, 0.4944, 0.4616,
         0.4763, 0.5312, 0.4726, 0.4885, 0.4973, 0.5504, 0.5349, 0.4765, 0.5276,
         0.4935, 0.4948, 0.4864, 0.4858, 0.5216, 0.4606, 0.4796, 0.4914, 0.4819,
         0.5192, 0.5139, 0.4886, 0.4651, 0.4766, 0.5152, 0.5263, 0.5318, 0.4823,
         0.4901, 0.5250, 0.5026, 0.4647, 0.4965, 0.4873, 0.5128, 0.4899, 0.5158,
         0.4945],
        [0.5046, 0.5239, 0.5029, 0.5328, 0.5066, 0.5091, 0.4793, 0.4401, 0.4740,
         0.4853, 0.5126, 0.4941, 0.4651, 0.4343, 0.4812, 0.5404, 0.4920, 0.4937,
         0.4642, 0.4841, 0.4478, 0.5150, 0.5237, 0.4659, 0.4753, 0.4872, 0.4613,
         0.4788, 0.5402, 0.4833, 0.5072, 0.4865, 0.5542, 0.5540, 0.4926, 0.5429,
         0.4814, 0.5019, 0.4747, 0.4917, 0.5133, 0.4603, 0.4662, 0.5236, 0.4938,
         0.4935, 0.5164, 0.5102, 0.4971, 0.4626, 0.4524, 0.5279, 0.5609, 0.5154,
         0.4685, 0.5249, 0.4954, 0.4785, 0.4708, 0.4835, 0.5481, 0.4811, 0.5776,
         0.4454]]), tensor([[0.4981, 0.4845, 0.4908,  ..., 0.5035, 0.4728, 0.5007],
        [0.4978, 0.4844, 0.4913,  ..., 0.5047, 0.4725, 0.5001],
        [0.4982, 0.4846, 0.4919,  ..., 0.5036, 0.4723, 0.5001],
        [0.4990, 0.4841, 0.4920,  ..., 0.5047, 0.4723, 0.5007]]))

Original exception:
 NotImplementedError: 

from user code:
...line 19, in <lambda>
    self.register_forward_hook(lambda module, inputs, output: output + 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) (without fullgraph=True) with a model that registers a forward hook containing a lambda expression inside the forward method, a NotImplementedError occurs. The eager mode works correctly. 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)
        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.4719, 0.5285, 0.5228, 0.5114, 0.5176, 0.5273, 0.4578, 0.4710, 0.5027,
         0.5016, 0.5485, 0.4698, 0.4932, 0.4811, 0.5236, 0.5477, 0.5188, 0.4853,
         0.4448, 0.5429, 0.5012, 0.4568, 0.5002, 0.5189, 0.5269, 0.5045, 0.4527,
         0.4585, 0.5060, 0.5005, 0.4861, 0.4679, 0.5618, 0.5312, 0.4816, 0.5300,
         0.5179, 0.4879, 0.4863, 0.4953, 0.5116, 0.4844, 0.4582, 0.5155, 0.5182,
         0.4630, 0.4902, 0.5111, 0.5103, 0.4957, 0.4864, 0.5177, 0.5676, 0.4905,
         0.4648, 0.5495, 0.5001, 0.5015, 0.5135, 0.4713, 0.5132, 0.4957, 0.5100,
         0.4352],
        [0.5093, 0.5298, 0.4927, 0.5025, 0.4880, 0.5268, 0.5092, 0.4344, 0.4734,
         0.5028, 0.5505, 0.4586, 0.4952, 0.4901, 0.4871, 0.5256, 0.5097, 0.5069,
         0.4872, 0.4744, 0.4672, 0.4885, 0.4882, 0.5080, 0.5069, 0.4956, 0.4629,
         0.4605, 0.4874, 0.5022, 0.4606, 0.4855, 0.5289, 0.5464, 0.4948, 0.5175,
         0.4920, 0.5399, 0.5055, 0.4832, 0.5321, 0.4962, 0.5072, 0.5339, 0.5009,
         0.5111, 0.5100, 0.5178, 0.4965, 0.4950, 0.5074, 0.5142, 0.5422, 0.4998,
         0.5058, 0.5213, 0.4891, 0.5062, 0.5001, 0.4655, 0.5229, 0.5057, 0.5157,
         0.4779],
        [0.4626, 0.5180, 0.4843, 0.4935, 0.5012, 0.5168, 0.4952, 0.4398, 0.5070,
         0.4678, 0.5590, 0.4713, 0.5052, 0.4868, 0.5093, 0.5055, 0.5083, 0.5347,
         0.4722, 0.4981, 0.5213, 0.4856, 0.4995, 0.4879, 0.5190, 0.4944, 0.4616,
         0.4763, 0.5312, 0.4726, 0.4885, 0.4973, 0.5504, 0.5349, 0.4765, 0.5276,
         0.4935, 0.4948, 0.4864, 0.4858, 0.5216, 0.4606, 0.4796, 0.4914, 0.4819,
         0.5192, 0.5139, 0.4886, 0.4651, 0.4766, 0.5152, 0.5263, 0.5318, 0.4823,
         0.4901, 0.5250, 0.5026, 0.4647, 0.4965, 0.4873, 0.5128, 0.4899, 0.5158,
         0.4945],
        [0.5046, 0.5239, 0.5029, 0.5328, 0.5066, 0.5091, 0.4793, 0.4401, 0.4740,
         0.4853, 0.5126, 0.4941, 0.4651, 0.4343, 0.4812, 0.5404, 0.4920, 0.4937,
         0.4642, 0.4841, 0.4478, 0.5150, 0.5237, 0.4659, 0.4753, 0.4872, 0.4613,
         0.4788, 0.5402, 0.4833, 0.5072, 0.4865, 0.5542, 0.5540, 0.4926, 0.5429,
         0.4814, 0.5019, 0.4747, 0.4917, 0.5133, 0.4603, 0.4662, 0.5236, 0.4938,
         0.4935, 0.5164, 0.5102, 0.4971, 0.4626, 0.4524, 0.5279, 0.5609, 0.5154,
         0.4685, 0.5249, 0.4954, 0.4785, 0.4708, 0.4835, 0.5481, 0.4811, 0.5776,
         0.4454]]), tensor([[0.4981, 0.4845, 0.4908,  ..., 0.5035, 0.4728, 0.5007],
        [0.4978, 0.4844, 0.4913,  ..., 0.5047, 0.4725, 0.5001],
        [0.4982, 0.4846, 0.4919,  ..., 0.5036, 0.4723, 0.5001],
        [0.4990, 0.4841, 0.4920,  ..., 0.5047, 0.4723, 0.5007]]))

Original exception:
 NotImplementedError: 

from user code:
...line 19, in <lambda>
    self.register_forward_hook(lambda module, inputs, output: output + 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 @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

The issue arises from using torch.compile(model) without fullgraph=True on a model that registers a forward hook containing a lambda expression. To fix this, we can modify the model to avoid using lambda expressions in the forward hook.

Here are the steps:

  • Remove the lambda expression from the forward method.
  • Define a separate function for the hook logic.
  • Register this function as the forward hook.

Code Changes

class SparseAutoencoder(nn.Module):
    # ...

    def forward_hook(self, module, inputs, output):
        return output + 1

    def forward(self, x):
        self.register_forward_hook(self.forward_hook)
        encoded = self.encoder(x)
        decoded = self.decoder(encoded)
        return (encoded, decoded)

Alternatively, you can also use torch.compile(model, fullgraph=True) to compile the model, but this may have performance implications.

Verification

To verify that the fix worked, run the main function again and check that the compiled model produces the expected output without raising a NotImplementedError.

Extra Tips

  • Avoid using lambda expressions in forward hooks when compiling models with Torch.
  • Use torch.compile(model, fullgraph=True) as a temporary workaround if you cannot modify the model.
  • Be cautious when using fullgraph=True as it may impact performance.

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