Issue with appending to torch.nn.ModuleList

I have a very confusing issue, I wrote the following code :

import torch 

class encoder(torch.nn.Module):

    def __init__(self, in_channels, **kwargs) -> None:

        super(encoder, self).__init__()

        self.modules = torch.nn.ModuleList([])
        hidden_dims = [32, 64, 128, 256, 512]

        for h_dim in hidden_dims:
            self.modules.append(torch.nn.Conv2d(in_channels, out_channels=h_dim, kernel_size= 3, stride= 2, padding  = 1))
            self.modules.append(torch.nn.BatchNorm2d(h_dim))
            self.modules.append(torch.nn.LeakyReLU)
            in_channels = h_dim

    def forward(self, x):
        for module in self.modules:
            x = module(x)
        x = torch.flatten(x)
        return x

test = encoder(1)

And I get the following error :

self.modules.append(torch.nn.Conv2d(in_channels, out_channels=h_dim, kernel_size= 3, stride= 2, padding  = 1))
AttributeError: 'function' object has no attribute 'append'

I’ve been going over it for the past hour, but I can’t find why it doesn’t work. I’ve found lots of examples that show that I can append a torch.nn.Module to a torch.nn.ModuleList (BMSG-GAN/GAN.py at master · akanimax/BMSG-GAN · GitHub see line 49), but it fails in this case, and I can’t figure out why.
It’s probably something realy dumb but I can’t figure it out. I would be grateful for any help :slight_smile: !

1 Like

.modules() is a function defined under class nn.Module.

You need to rename the variable self.modules as it is conflicting with this function.

1 Like

Thanks a lot ! that makes complete sense, I should be more careful about that