-
Notifications
You must be signed in to change notification settings - Fork 26.2k
Description
🐛 Describe the bug
Description:
Encountered TypeError while compiling a model with dynamic attribute access using torch.compile. The model uses the attribute access mode getattr (x, 'float', None) () with default values, which works properly in eager mode, but in compile mode, TorchDynamo incorrectly infers the return value as NoneType.
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:
TypeError: 'NoneType' object is not callable
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 @chenyang78 @kadeng @amjames @Lucaskabela