pytorch - 💡(How to fix) Fix [torch.compile] Graph break and assertion error when using getattr with None default followed by call [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#178391Fetched 2026-04-08 01:30:40
View on GitHub
Comments
1
Participants
2
Timeline
116
Reactions
0
Timeline (top)
mentioned ×55subscribed ×55labeled ×4closed ×1

Error Message

AssertionError: expected size 3==3, stride 1==49 at dim=1

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

AssertionError: expected size 3==3, stride 1==49 at dim=1

---

import os
import torch
import torch.nn as nn
import torch.nn.functional as F

class MaskedConv2d(nn.Conv2d):

    def __init__(self, mask_type, *args, **kwargs):
        super(MaskedConv2d, self).__init__(*args, **kwargs)
        assert mask_type in ['A', 'B'], "mask_type must be either 'A' or 'B'"
        self.register_buffer('mask', self.weight.data.clone())
        (_, _, height, width) = self.weight.size()
        self.mask.fill_(1)
        self.mask[:, :, height // 2, width // 2 + (mask_type == 'B'):] = 0
        self.mask[:, :, height // 2 + 1:] = 0

    def forward(self, x):
        self.weight.data *= self.mask
        return super(MaskedConv2d, self).forward(x)

class ResidualBlock(nn.Module):

    def __init__(self, in_channels):
        super(ResidualBlock, self).__init__()
        self.conv = nn.Sequential(nn.ReLU(), MaskedConv2d('B', in_channels, in_channels // 2, 1, 1, 0, bias=False), nn.BatchNorm2d(in_channels // 2), nn.ReLU(), MaskedConv2d('B', in_channels // 2, in_channels // 2, 3, 1, 1, bias=False), nn.BatchNorm2d(in_channels // 2), nn.ReLU(), MaskedConv2d('B', in_channels // 2, in_channels, 1, 1, 0, bias=False), nn.BatchNorm2d(in_channels))
        self.skip = nn.Identity()

    def forward(self, x):
        return self.conv(x) + self.skip(x)

class PixelCNN(nn.Module):

    def __init__(self, in_channels=3, hidden_dim=128, out_channels=256, num_layers=12):
        super(PixelCNN, self).__init__()
        self.input_conv = MaskedConv2d('A', in_channels, hidden_dim, 7, 1, 3)
        self.res_blocks = nn.ModuleList()
        for _ in range(num_layers):
            self.res_blocks.append(ResidualBlock(hidden_dim))
        self.output_layers = nn.Sequential(nn.ReLU(), MaskedConv2d('B', hidden_dim, hidden_dim, 1), nn.ReLU(), MaskedConv2d('B', hidden_dim, out_channels * in_channels, 1))
        self.out_channels = out_channels
        self.in_channels = in_channels

    def forward(self, x):
        x = getattr(x, 'float', None)() / 255.0
        h = self.input_conv(x)
        for res_block in self.res_blocks:
            h = res_block(h)
        out = self.output_layers(h)
        (batch_size, _, height, width) = out.shape
        out = out.view(batch_size, self.out_channels, self.in_channels, height, width)
        return out

    def sample(self, shape, device='cpu', temperature=1.0):
        with torch.no_grad():
            samples = torch.zeros(shape, device=device)
            for i in range(shape[2]):
                for j in range(shape[3]):
                    for c in range(shape[1]):
                        logits = self.forward(samples * 255.0)[:, :, c, i, j] / temperature
                        probs = F.softmax(logits, dim=1)
                        sampled = torch.multinomial(probs, 1).squeeze(-1)
                        samples[:, c, i, j] = sampled.float() / 255.0
            return samples * 255.0

def get_default_model():
    in_channels = 3
    hidden_dim = 128
    out_channels = 256
    num_layers = 12
    model = PixelCNN(in_channels=in_channels, hidden_dim=hidden_dim, out_channels=out_channels, num_layers=num_layers)
    return model

def get_sample_inputs():
    batch_size = 2
    channels = 3
    height = 32
    width = 32
    x = torch.randint(0, 256, (batch_size, channels, height, width), dtype=torch.float32)
    return (x,)

def main():
    model = get_default_model()
    model.eval()
    inputs = get_sample_inputs()
    with torch.no_grad():
        output = model(*inputs)
    print('Model executed successfully!')
    print(f'Input shape: {inputs[0].shape}')
    print(f'Output shape: {output.shape}')
    print(f'Model parameters: {sum((p.numel() for p in model.parameters()))}')
    compiled_model = torch.compile(model)
    with torch.no_grad():
        output_compile = compiled_model(*inputs)
    print(f'Compile  shape: {output_compile.shape}')
if __name__ == '__main__':
    main()

---

AssertionError: expected size 3==3, stride 1==49 at dim=1
RAW_BUFFERClick to expand / collapse

🐛 Describe the bug

When using torch.compile with a PixelCNN model that uses custom MaskedConv2d layers with in-place weight masking (self.weight.data *= self.mask), an AssertionError occurs during the Inductor-generated code execution:

AssertionError: expected size 3==3, stride 1==49 at dim=1

pytorch version :2.4.0 code:

import os
import torch
import torch.nn as nn
import torch.nn.functional as F

class MaskedConv2d(nn.Conv2d):

    def __init__(self, mask_type, *args, **kwargs):
        super(MaskedConv2d, self).__init__(*args, **kwargs)
        assert mask_type in ['A', 'B'], "mask_type must be either 'A' or 'B'"
        self.register_buffer('mask', self.weight.data.clone())
        (_, _, height, width) = self.weight.size()
        self.mask.fill_(1)
        self.mask[:, :, height // 2, width // 2 + (mask_type == 'B'):] = 0
        self.mask[:, :, height // 2 + 1:] = 0

    def forward(self, x):
        self.weight.data *= self.mask
        return super(MaskedConv2d, self).forward(x)

class ResidualBlock(nn.Module):

    def __init__(self, in_channels):
        super(ResidualBlock, self).__init__()
        self.conv = nn.Sequential(nn.ReLU(), MaskedConv2d('B', in_channels, in_channels // 2, 1, 1, 0, bias=False), nn.BatchNorm2d(in_channels // 2), nn.ReLU(), MaskedConv2d('B', in_channels // 2, in_channels // 2, 3, 1, 1, bias=False), nn.BatchNorm2d(in_channels // 2), nn.ReLU(), MaskedConv2d('B', in_channels // 2, in_channels, 1, 1, 0, bias=False), nn.BatchNorm2d(in_channels))
        self.skip = nn.Identity()

    def forward(self, x):
        return self.conv(x) + self.skip(x)

class PixelCNN(nn.Module):

    def __init__(self, in_channels=3, hidden_dim=128, out_channels=256, num_layers=12):
        super(PixelCNN, self).__init__()
        self.input_conv = MaskedConv2d('A', in_channels, hidden_dim, 7, 1, 3)
        self.res_blocks = nn.ModuleList()
        for _ in range(num_layers):
            self.res_blocks.append(ResidualBlock(hidden_dim))
        self.output_layers = nn.Sequential(nn.ReLU(), MaskedConv2d('B', hidden_dim, hidden_dim, 1), nn.ReLU(), MaskedConv2d('B', hidden_dim, out_channels * in_channels, 1))
        self.out_channels = out_channels
        self.in_channels = in_channels

    def forward(self, x):
        x = getattr(x, 'float', None)() / 255.0
        h = self.input_conv(x)
        for res_block in self.res_blocks:
            h = res_block(h)
        out = self.output_layers(h)
        (batch_size, _, height, width) = out.shape
        out = out.view(batch_size, self.out_channels, self.in_channels, height, width)
        return out

    def sample(self, shape, device='cpu', temperature=1.0):
        with torch.no_grad():
            samples = torch.zeros(shape, device=device)
            for i in range(shape[2]):
                for j in range(shape[3]):
                    for c in range(shape[1]):
                        logits = self.forward(samples * 255.0)[:, :, c, i, j] / temperature
                        probs = F.softmax(logits, dim=1)
                        sampled = torch.multinomial(probs, 1).squeeze(-1)
                        samples[:, c, i, j] = sampled.float() / 255.0
            return samples * 255.0

def get_default_model():
    in_channels = 3
    hidden_dim = 128
    out_channels = 256
    num_layers = 12
    model = PixelCNN(in_channels=in_channels, hidden_dim=hidden_dim, out_channels=out_channels, num_layers=num_layers)
    return model

def get_sample_inputs():
    batch_size = 2
    channels = 3
    height = 32
    width = 32
    x = torch.randint(0, 256, (batch_size, channels, height, width), dtype=torch.float32)
    return (x,)

def main():
    model = get_default_model()
    model.eval()
    inputs = get_sample_inputs()
    with torch.no_grad():
        output = model(*inputs)
    print('Model executed successfully!')
    print(f'Input shape: {inputs[0].shape}')
    print(f'Output shape: {output.shape}')
    print(f'Model parameters: {sum((p.numel() for p in model.parameters()))}')
    compiled_model = torch.compile(model)
    with torch.no_grad():
        output_compile = compiled_model(*inputs)
    print(f'Compile  shape: {output_compile.shape}')
if __name__ == '__main__':
    main()

output:

AssertionError: expected size 3==3, stride 1==49 at dim=1

Versions

PyTorch version: 2.4.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 @chauhang @penguinwu @voznesenskym @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @ipiszy @kadeng @muchulee8 @amjames @aakhundov @coconutruben @jataylo

extent analysis

Fix Plan

The issue arises from the in-place modification of the weight attribute in the MaskedConv2d layer. To fix this, we need to avoid modifying the weight attribute directly. Instead, we can create a new tensor that represents the masked weight and use it in the forward pass.

Step-by-Step Solution

  1. Modify the MaskedConv2d layer:
    • Remove the line self.weight.data *= self.mask from the forward method.
    • Create a new tensor masked_weight by multiplying self.weight with self.mask.
    • Use masked_weight in the forward method instead of self.weight.
  2. Update the forward method:

def forward(self, x): masked_weight = self.weight * self.mask return F.conv2d(x, masked_weight, self.bias, self.stride, self.padding, self.dilation, self.groups)

3. **Remove the `in-place` modification**:
    * Remove the line `self.weight.data *= self.mask` from the `__init__` method.

### Verification
To verify that the fix worked, you can run the `main` function again and check if the `AssertionError` is resolved. You can also add additional tests to ensure that the model is working as expected.

### Extra Tips
* Avoid modifying the `weight` attribute directly in the `forward` method, as it can cause issues with the compilation of the model.
* Use the `F.conv2d` function to perform the convolution operation, as it allows for more flexibility and avoids modifying the `weight` attribute directly.

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