pytorch - 💡(How to fix) Fix [torch.compile] Dynamo fails to trace assignment of custom tensor subclass to module attribute:self.custom_weights = CustomTensor(self.layer1.weight.data)`` [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#178388Fetched 2026-04-08 01:30:42
View on GitHub
Comments
0
Participants
1
Timeline
73
Reactions
0
Participants
Timeline (top)
mentioned ×34subscribed ×34labeled ×5

Error Message

import torch import torch.nn as nn class CustomTensor(torch.Tensor): def init(self, data): super().init() self.custom_metadata = "custom_tensor_data" @classmethod def torch_function(cls, func, types, args=(), kwargs=None): if kwargs is None: kwargs = {} return super().torch_function(func, types, args, kwargs) def custom_method(self): return f"Custom tensor with metadata: {self.custom_metadata}" class EnhancedCustomTensor(CustomTensor): def init(self, data): super().init(data) self.enhanced_flag = True def enhanced_operation(self): return self * 2.0 if self.enhanced_flag else self class NeuralNetWithCustomTensors(nn.Module): def init(self, input_size=784, hidden_size=128, num_classes=10): super().init() self.input_size = input_size self.layer1 = nn.Linear(input_size, hidden_size) self.layer2 = nn.Linear(hidden_size, hidden_size) self.output_layer = nn.Linear(hidden_size, num_classes) self.activation = nn.ReLU() self.dropout = nn.Dropout(0.2) self.custom_weights = None self.enhanced_features = None def forward(self, x): if not isinstance(x, CustomTensor): x = CustomTensor(x) self.custom_weights = CustomTensor(self.layer1.weight.data) x = self.layer1(x) x = self.activation(x) x = self.dropout(x) intermediate_result = CustomTensor(x) self.enhanced_features = EnhancedCustomTensor(intermediate_result) x = self.layer2(x) x = self.activation(x) if self.enhanced_features is not None: enhanced_result = self.enhanced_features.enhanced_operation() x = x + enhanced_result[:x.size(0), :x.size(1)] x = self.output_layer(x) return x def get_custom_metadata(self): if self.custom_weights is not None: return self.custom_weights.custom_method() return "No custom weights initialized" def get_default_model(): model = NeuralNetWithCustomTensors(input_size=784, hidden_size=128, num_classes=10) return model def get_sample_inputs(): batch_size = 4 input_size = 784 x = torch.randn(batch_size, input_size) return (x,) def main(): model = get_default_model() model.eval() inputs = get_sample_inputs() print("Model architecture:") print(model) print(f"\nCustom tensor subclass hierarchy: {model.get_custom_metadata()}") with torch.no_grad(): output = model(*inputs) print("\nModel executed successfully!") print(f"Input shape: {inputs[0].shape}") print(f"Output shape: {output.shape}") print(f"Output type: {type(output)}") print(f"Model parameters: {sum(p.numel() for p in model.parameters())}") if model.enhanced_features is not None: print(f"\nEnhanced features type: {type(model.enhanced_features)}") print(f"Enhanced features metadata: {model.enhanced_features.custom_metadata}") print(f"Enhanced operation result shape: {model.enhanced_features.enhanced_operation().shape}")

try:
    compiled_model = torch.compile(model)
    with torch.no_grad():
        output_compile = compiled_model(*inputs)
    print(f'Compile  shape: {output_compile.shape}')
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 torch
import torch.nn as nn
class CustomTensor(torch.Tensor):
    def __init__(self, data):
        super().__init__()
        self.custom_metadata = "custom_tensor_data"
    @classmethod
    def __torch_function__(cls, func, types, args=(), kwargs=None):
        if kwargs is None:
            kwargs = {}
        return super().__torch_function__(func, types, args, kwargs)
    def custom_method(self):
        return f"Custom tensor with metadata: {self.custom_metadata}"
class EnhancedCustomTensor(CustomTensor):
    def __init__(self, data):
        super().__init__(data)
        self.enhanced_flag = True
    def enhanced_operation(self):
        return self * 2.0 if self.enhanced_flag else self
class NeuralNetWithCustomTensors(nn.Module):
    def __init__(self, input_size=784, hidden_size=128, num_classes=10):
        super().__init__()
        self.input_size = input_size
        self.layer1 = nn.Linear(input_size, hidden_size)
        self.layer2 = nn.Linear(hidden_size, hidden_size)
        self.output_layer = nn.Linear(hidden_size, num_classes)
        self.activation = nn.ReLU()
        self.dropout = nn.Dropout(0.2)
        self.custom_weights = None
        self.enhanced_features = None
    def forward(self, x):
        if not isinstance(x, CustomTensor):
            x = CustomTensor(x)
        self.custom_weights = CustomTensor(self.layer1.weight.data)
        x = self.layer1(x)
        x = self.activation(x)
        x = self.dropout(x)
        intermediate_result = CustomTensor(x)
        self.enhanced_features = EnhancedCustomTensor(intermediate_result)
        x = self.layer2(x)
        x = self.activation(x)
        if self.enhanced_features is not None:
            enhanced_result = self.enhanced_features.enhanced_operation()
            x = x + enhanced_result[:x.size(0), :x.size(1)]
        x = self.output_layer(x)
        return x
    def get_custom_metadata(self):
        if self.custom_weights is not None:
            return self.custom_weights.custom_method()
        return "No custom weights initialized"
def get_default_model():
    model = NeuralNetWithCustomTensors(input_size=784, hidden_size=128, num_classes=10)
    return model
def get_sample_inputs():
    batch_size = 4
    input_size = 784
    x = torch.randn(batch_size, input_size)
    return (x,)
def main():
    model = get_default_model()
    model.eval()
    inputs = get_sample_inputs()
    print("Model architecture:")
    print(model)
    print(f"\nCustom tensor subclass hierarchy: {model.get_custom_metadata()}")
    with torch.no_grad():
        output = model(*inputs)
    print("\nModel executed successfully!")
    print(f"Input shape: {inputs[0].shape}")
    print(f"Output shape: {output.shape}")
    print(f"Output type: {type(output)}")
    print(f"Model parameters: {sum(p.numel() for p in model.parameters())}")
    if model.enhanced_features is not None:
        print(f"\nEnhanced features type: {type(model.enhanced_features)}")
        print(f"Enhanced features metadata: {model.enhanced_features.custom_metadata}")
        print(f"Enhanced operation result shape: {model.enhanced_features.enhanced_operation().shape}")

    try:
        compiled_model = torch.compile(model)
        with torch.no_grad():
            output_compile = compiled_model(*inputs)
        print(f'Compile  shape: {output_compile.shape}')
    except Exception as e:
        print(f'\nOriginal exception:\n {e}')
if __name__ == "__main__":
    main()

---

Model architecture:
NeuralNetWithCustomTensors(
  (layer1): Linear(in_features=784, out_features=128, bias=True)
  (layer2): Linear(in_features=128, out_features=128, bias=True)
  (output_layer): Linear(in_features=128, out_features=10, bias=True)
  (activation): ReLU()
  (dropout): Dropout(p=0.2, inplace=False)
)

Custom tensor subclass hierarchy: No custom weights initialized

Model executed successfully!
Input shape: torch.Size([4, 784])
Output shape: torch.Size([4, 10])
Output type: <class '__main__.EnhancedCustomTensor'>
Model parameters: 118282

Enhanced features type: <class '__main__.EnhancedCustomTensor'>
Enhanced features metadata: custom_tensor_data
Enhanced operation result shape: torch.Size([4, 128])

Original exception:
 

from user code:
  ...ine 34, in torch_dynamo_resume_in_forward_at_33
    self.custom_weights = CustomTensor(self.layer1.weight.data)

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

When using torch.compile with a model that creates a custom tensor subclass and assigns it to a module attribute (e.g., self.custom_weights = CustomTensor(...)), compilation fails with an empty exception traceback during the Dynamo resume step.

Pytorch 2.11.0 code:

import torch
import torch.nn as nn
class CustomTensor(torch.Tensor):
    def __init__(self, data):
        super().__init__()
        self.custom_metadata = "custom_tensor_data"
    @classmethod
    def __torch_function__(cls, func, types, args=(), kwargs=None):
        if kwargs is None:
            kwargs = {}
        return super().__torch_function__(func, types, args, kwargs)
    def custom_method(self):
        return f"Custom tensor with metadata: {self.custom_metadata}"
class EnhancedCustomTensor(CustomTensor):
    def __init__(self, data):
        super().__init__(data)
        self.enhanced_flag = True
    def enhanced_operation(self):
        return self * 2.0 if self.enhanced_flag else self
class NeuralNetWithCustomTensors(nn.Module):
    def __init__(self, input_size=784, hidden_size=128, num_classes=10):
        super().__init__()
        self.input_size = input_size
        self.layer1 = nn.Linear(input_size, hidden_size)
        self.layer2 = nn.Linear(hidden_size, hidden_size)
        self.output_layer = nn.Linear(hidden_size, num_classes)
        self.activation = nn.ReLU()
        self.dropout = nn.Dropout(0.2)
        self.custom_weights = None
        self.enhanced_features = None
    def forward(self, x):
        if not isinstance(x, CustomTensor):
            x = CustomTensor(x)
        self.custom_weights = CustomTensor(self.layer1.weight.data)
        x = self.layer1(x)
        x = self.activation(x)
        x = self.dropout(x)
        intermediate_result = CustomTensor(x)
        self.enhanced_features = EnhancedCustomTensor(intermediate_result)
        x = self.layer2(x)
        x = self.activation(x)
        if self.enhanced_features is not None:
            enhanced_result = self.enhanced_features.enhanced_operation()
            x = x + enhanced_result[:x.size(0), :x.size(1)]
        x = self.output_layer(x)
        return x
    def get_custom_metadata(self):
        if self.custom_weights is not None:
            return self.custom_weights.custom_method()
        return "No custom weights initialized"
def get_default_model():
    model = NeuralNetWithCustomTensors(input_size=784, hidden_size=128, num_classes=10)
    return model
def get_sample_inputs():
    batch_size = 4
    input_size = 784
    x = torch.randn(batch_size, input_size)
    return (x,)
def main():
    model = get_default_model()
    model.eval()
    inputs = get_sample_inputs()
    print("Model architecture:")
    print(model)
    print(f"\nCustom tensor subclass hierarchy: {model.get_custom_metadata()}")
    with torch.no_grad():
        output = model(*inputs)
    print("\nModel executed successfully!")
    print(f"Input shape: {inputs[0].shape}")
    print(f"Output shape: {output.shape}")
    print(f"Output type: {type(output)}")
    print(f"Model parameters: {sum(p.numel() for p in model.parameters())}")
    if model.enhanced_features is not None:
        print(f"\nEnhanced features type: {type(model.enhanced_features)}")
        print(f"Enhanced features metadata: {model.enhanced_features.custom_metadata}")
        print(f"Enhanced operation result shape: {model.enhanced_features.enhanced_operation().shape}")

    try:
        compiled_model = torch.compile(model)
        with torch.no_grad():
            output_compile = compiled_model(*inputs)
        print(f'Compile  shape: {output_compile.shape}')
    except Exception as e:
        print(f'\nOriginal exception:\n {e}')
if __name__ == "__main__":
    main()

output:

Model architecture:
NeuralNetWithCustomTensors(
  (layer1): Linear(in_features=784, out_features=128, bias=True)
  (layer2): Linear(in_features=128, out_features=128, bias=True)
  (output_layer): Linear(in_features=128, out_features=10, bias=True)
  (activation): ReLU()
  (dropout): Dropout(p=0.2, inplace=False)
)

Custom tensor subclass hierarchy: No custom weights initialized

Model executed successfully!
Input shape: torch.Size([4, 784])
Output shape: torch.Size([4, 10])
Output type: <class '__main__.EnhancedCustomTensor'>
Model parameters: 118282

Enhanced features type: <class '__main__.EnhancedCustomTensor'>
Enhanced features metadata: custom_tensor_data
Enhanced operation result shape: torch.Size([4, 128])

Original exception:
 

from user code:
  ...ine 34, in torch_dynamo_resume_in_forward_at_33
    self.custom_weights = CustomTensor(self.layer1.weight.data)

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

extent analysis

Fix Plan

To fix the compilation issue with torch.compile, we need to ensure that the custom tensor subclass is properly handled during the compilation process.

Here are the steps to fix the issue:

  • Modify the CustomTensor class to handle the __torch_function__ protocol correctly.
  • Update the NeuralNetWithCustomTensors class to avoid assigning custom tensors to module attributes.

Code Changes

class CustomTensor(torch.Tensor):
    # ... (rest of the class remains the same)

    @classmethod
    def __torch_function__(cls, func, types, args=(), kwargs=None):
        if kwargs is None:
            kwargs = {}
        # Handle the torch.function protocol correctly
        if func is torch.tensor:
            return torch.tensor(args[0], **kwargs)
        return super().__torch_function__(func, types, args, kwargs)

class NeuralNetWithCustomTensors(nn.Module):
    # ... (rest of the class remains the same)

    def forward(self, x):
        if not isinstance(x, CustomTensor):
            x = CustomTensor(x)
        # Avoid assigning custom tensors to module attributes
        custom_weights = CustomTensor(self.layer1.weight.data)
        x = self.layer1(x)
        x = self.activation(x)
        x = self.dropout(x)
        intermediate_result = CustomTensor(x)
        enhanced_features = EnhancedCustomTensor(intermediate_result)
        x = self.layer2(x)
        x = self.activation(x)
        if enhanced_features is not None:
            enhanced_result = enhanced_features.enhanced_operation()
            x = x + enhanced_result[:x.size(0), :x.size(1)]
        x = self.output_layer(x)
        return x

Verification

To verify that the fix worked, you can re-run the main function and check if the compilation with torch.compile succeeds. The output should no longer contain an empty exception traceback.

Extra Tips

  • When working with custom tensor subclasses, ensure that you handle the __torch_function__ protocol correctly to avoid issues during compilation.
  • Avoid assigning custom tensors to module attributes, as this can cause issues during the compilation process.
  • If you encounter any further issues, you can set TORCHDYNAMO_VERBOSE=1 to get more detailed error messages and stack traces.

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