pytorch - 💡(How to fix) Fix [torch.compile] as_subclass() fails with custom tensor subclass: NotImplementedError for argument of type '_TensorMeta' [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#178386Fetched 2026-04-08 01:30:46
View on GitHub
Comments
1
Participants
2
Timeline
75
Reactions
0
Timeline (top)
mentioned ×34subscribed ×34labeled ×5closed ×1

Error Message

import torch import torch.nn as nn import torch.nn.functional as F class MyTensor(torch.Tensor): def sum(self, dim=None, keepdim=False): return super().sum(dim=dim, keepdim=keepdim).as_subclass(MyTensor) def mean(self, dim=None, keepdim=False): return super().mean(dim=dim, keepdim=keepdim).as_subclass(MyTensor) def prod(self, dim=None, keepdim=False): return super().prod(dim=dim, keepdim=keepdim).as_subclass(MyTensor) class TestModel(nn.Module): def init(self): super().init() self.fc = nn.Linear(10, 5) def forward(self, x): out = self.fc(x) out_subclass = out.as_subclass(MyTensor) reduced = out_subclass.sum(dim=1) return reduced def get_default_model(): return TestModel() def get_sample_inputs(): x = torch.randn(4, 10, requires_grad=True) return (x,) def main(): model = get_default_model() inputs = get_sample_inputs() x = inputs[0] output = model(x) target = torch.zeros_like(output) loss = F.mse_loss(output, target) loss.backward() print('TestModel executed successfully!') print('Input shape:', x.shape) print('Output shape:', output.shape) print('Model parameters count:', sum(p.numel() for p in model.parameters())) print('Input gradients shape:', x.grad.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
import torch.nn.functional as F
class MyTensor(torch.Tensor):
    def sum(self, dim=None, keepdim=False):
        return super().sum(dim=dim, keepdim=keepdim).as_subclass(MyTensor)
    def mean(self, dim=None, keepdim=False):
        return super().mean(dim=dim, keepdim=keepdim).as_subclass(MyTensor)
    def prod(self, dim=None, keepdim=False):
        return super().prod(dim=dim, keepdim=keepdim).as_subclass(MyTensor)
class TestModel(nn.Module):
    def __init__(self):
        super().__init__()
        self.fc = nn.Linear(10, 5)
    def forward(self, x):
        out = self.fc(x)
        out_subclass = out.as_subclass(MyTensor)
        reduced = out_subclass.sum(dim=1)
        return reduced
def get_default_model():
    return TestModel()
def get_sample_inputs():
    x = torch.randn(4, 10, requires_grad=True)
    return (x,)
def main():
    model = get_default_model()
    inputs = get_sample_inputs()
    x = inputs[0]
    output = model(x)
    target = torch.zeros_like(output)
    loss = F.mse_loss(output, target)
    loss.backward()
    print('TestModel executed successfully!')
    print('Input shape:', x.shape)
    print('Output shape:', output.shape)
    print('Model parameters count:', sum(p.numel() for p in model.parameters()))
    print('Input gradients shape:', x.grad.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()

---

NotImplementedError: argument of type: <class 'torch._C._TensorMeta'>

from user code:
   File "test.py", line 24, in forward
    out_subclass = out.as_subclass(MyTensor)
RAW_BUFFERClick to expand / collapse

🐛 Describe the bug

When using torch.compile with a model that converts a tensor to a custom subclass using .as_subclass(MyTensor), the compilation fails with NotImplementedError: argument of type: <class 'torch._C._TensorMeta'>.

This error occurs specifically when calling .as_subclass() on a tensor within a compiled function. Torch Version: 2.7.0 code:

import torch
import torch.nn as nn
import torch.nn.functional as F
class MyTensor(torch.Tensor):
    def sum(self, dim=None, keepdim=False):
        return super().sum(dim=dim, keepdim=keepdim).as_subclass(MyTensor)
    def mean(self, dim=None, keepdim=False):
        return super().mean(dim=dim, keepdim=keepdim).as_subclass(MyTensor)
    def prod(self, dim=None, keepdim=False):
        return super().prod(dim=dim, keepdim=keepdim).as_subclass(MyTensor)
class TestModel(nn.Module):
    def __init__(self):
        super().__init__()
        self.fc = nn.Linear(10, 5)
    def forward(self, x):
        out = self.fc(x)
        out_subclass = out.as_subclass(MyTensor)
        reduced = out_subclass.sum(dim=1)
        return reduced
def get_default_model():
    return TestModel()
def get_sample_inputs():
    x = torch.randn(4, 10, requires_grad=True)
    return (x,)
def main():
    model = get_default_model()
    inputs = get_sample_inputs()
    x = inputs[0]
    output = model(x)
    target = torch.zeros_like(output)
    loss = F.mse_loss(output, target)
    loss.backward()
    print('TestModel executed successfully!')
    print('Input shape:', x.shape)
    print('Output shape:', output.shape)
    print('Model parameters count:', sum(p.numel() for p in model.parameters()))
    print('Input gradients shape:', x.grad.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:

NotImplementedError: argument of type: <class 'torch._C._TensorMeta'>

from user code:
   File "test.py", line 24, in forward
    out_subclass = out.as_subclass(MyTensor)

Versions

PyTorch version: 2.7.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 issue with torch.compile and custom tensor subclasses, we need to modify the forward method in the TestModel class. The error occurs because torch.compile does not support the as_subclass method.

Here are the steps to fix the issue:

  • Remove the as_subclass method calls from the forward method.
  • Apply the necessary operations directly to the tensor without converting it to a custom subclass.

Code Changes

class TestModel(nn.Module):
    def __init__(self):
        super().__init__()
        self.fc = nn.Linear(10, 5)

    def forward(self, x):
        out = self.fc(x)
        reduced = out.sum(dim=1)
        return reduced

Alternatively, if you need to use a custom tensor subclass, you can create a separate function that applies the necessary operations and call it outside of the compiled model:

class MyTensor(torch.Tensor):
    def sum(self, dim=None, keepdim=False):
        return super().sum(dim=dim, keepdim=keepdim)

class TestModel(nn.Module):
    def __init__(self):
        super().__init__()
        self.fc = nn.Linear(10, 5)

    def forward(self, x):
        out = self.fc(x)
        return out

def process_output(out):
    out_subclass = out.as_subclass(MyTensor)
    reduced = out_subclass.sum(dim=1)
    return reduced

def main():
    model = get_default_model()
    inputs = get_sample_inputs()
    x = inputs[0]
    output = model(x)
    processed_output = process_output(output)
    # ...
    try:
        compiled_model = torch.compile(model)
        with torch.no_grad():
            output_compile = compiled_model(*inputs)
        processed_output_compile = process_output(output_compile)
        print(f'Compile  shape: {processed_output_compile.shape}')
    except Exception as e:
        print(f'\nOriginal exception:\n {e}')

Verification

To verify that the fix worked, you can check the output shape of the compiled model and the processed output. The shapes should match the expected output shapes.

Extra Tips

  • When using torch.compile, make sure to test your model with and without compilation to ensure that the results match.
  • If you need to use custom tensor subclasses, consider creating separate functions that apply the necessary operations outside of the compiled model.

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