You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AttributeError排查:'int'对象无'_forward_pre_hooks'属性

Fixing AttributeError: 'int' object has no attribute '_forward_pre_hooks' in StackGAN PyTorch

Let's break down what's causing this error and how to fix it quickly.

Root Cause

The error occurs because you’re passing integer values (like ndf * 2, ndf * 4) to nn.utils.spectral_norm() instead of passing a PyTorch neural network module (such as nn.Conv2d).

The spectral_norm utility is meant to wrap around a module (e.g., a convolution layer) to apply spectral normalization to its weights. When you pass an integer, the function tries to treat that integer as a module and access attributes like _forward_pre_hooks—which integers don’t have, hence the AttributeError.

Fixed Code

Here’s the corrected define_module method, where we properly apply spectral_norm to each convolutional layer:

def define_module(self):
    ndf, nef = self.df_dim, self.ef_dim
    self.encode_img = nn.Sequential(
        nn.Conv2d(3, ndf, 4, 2, 1, bias=False),
        nn.LeakyReLU(0.2, inplace=True),
        # state size. (ndf) x 32 x 32
        nn.utils.spectral_norm(nn.Conv2d(ndf, ndf * 2, 4, 2, 1, bias=False)),
        nn.LeakyReLU(0.2, inplace=True),
        # state size (ndf*2) x 16 x 16
        nn.utils.spectral_norm(nn.Conv2d(ndf*2, ndf * 4, 4, 2, 1, bias=False)),
        nn.LeakyReLU(0.2, inplace=True),
        # state size (ndf*4) x 8 x 8
        nn.utils.spectral_norm(nn.Conv2d(ndf*4, ndf * 8, 4, 2, 1, bias=False)),
        nn.LeakyReLU(0.2, inplace=True)
        # state size (ndf * 8) x 4 x 4)
    )

Key Changes Explained

  • Instead of adding nn.utils.spectral_norm(ndf * 2) as a separate layer in the Sequential, we wrap the nn.Conv2d layer directly with nn.utils.spectral_norm(). This ensures the utility targets the correct module and applies normalization to its weights.
  • We removed the redundant standalone spectral_norm calls that took integer arguments—these were the direct source of the error.

内容的提问来源于stack exchange,提问作者xiaowang888

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 11:27:46