AttributeError排查:'int'对象无'_forward_pre_hooks'属性
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 thenn.Conv2dlayer directly withnn.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

