Problem with nn.ModuleDict ('method' object is not subscriptable)

I am tring to use nn.ModuleDict following this documentation: ModuleDict — PyTorch 1.7.0 documentation

I have this pytorch network:

class Net(nn.Module):
    def __init__(self, kernel_size):
        super(Net, self).__init__()
        modules = {}
        modules["layer1"] = nn.Conv2d(3, 16, kernel_size=kernel_size, stride=1, padding=2)
        self.modules = nn.ModuleDict(modules)

    def forward(self, x):
        x = self.modules["layer1"](x)

when i use the forward method, I get the following error:

'method' object is not subscriptable

when I change the forward method to:

  def forward(self, x):
        x = self.modules()["layer1"](x)

I get the following error:

TypeError: 'generator' object is not subscriptable

What am i doing wrong?


modules is a built-in method for nn.Module objects. Rename modules in your model definition to anything else and it should work.