close

[Solved] AttributeError: cannot assign module before Module.__init__() call

Hello Guys, How are you all? Hope You all Are Fine. Today I get the following error AttributeError: cannot assign module before Module.init() call in python. So Here I am Explain to you all the possible solutions here.

Without wasting your time, Let’s start This Article to Solve This Error.

How AttributeError: cannot assign module before Module.init() call Error Occurs?

Today I get the following error AttributeError: cannot assign module before Module.init() call in python.

How To Solve AttributeError: cannot assign module before Module.init() call Error ?

  1. How To Solve AttributeError: cannot assign module before Module.init() call Error ?

    To Solve AttributeError: cannot assign module before Module.init() call Error Pytorch keeps track of the submodules(conv1conv2) you will write in your custom Module. Under the hood, the graph corresponding to your Model is automatically built.

  2. AttributeError: cannot assign module before Module.init() call

    To Solve AttributeError: cannot assign module before Module.init() call Error Pytorch keeps track of the submodules(conv1conv2) you will write in your custom Module. Under the hood, the graph corresponding to your Model is automatically built.

Solution 1

Looking at the pytorch source code for Module, we see in the docstring an example of deriving from Module includes:

 class Model(nn.Module):
        def __init__(self):
            super(Model, self).__init__()
            self.conv1 = nn.Conv2d(1, 20, 5)
            self.conv2 = nn.Conv2d(20, 20, 5)

So you probably want to call Module‘s init the same way in your derived class:

super(QuestionClassifier, self).__init__()

Solution 2

Pytorch keeps track of the submodules(conv1conv2) you will write in your custom Module. Under the hood, the graph corresponding to your Model is automatically built.

The nested Modules will be added to an OrderedDict _modules (initialized in nn.Module.__init__) See source(L69)

If nn.Module.__init__ is not called (self._modules would equal to None), when trying to add a Module, it will raise an error (no key can be added to None). See source(L540-544)

Inspired from the doc:

 class CustomModule(nn.Module):
        def __init__(self):
            super(CustomModule, self).__init__() # Initialize self._modules as OrderedDict
            self.conv1 = nn.Conv2d(1, 20, 5)     # Add key conv1 to self._modules
            self.conv2 = nn.Conv2d(20, 20, 5)    # Add key conv2 to self._modules 

Summery

It’s all About this issue. Hope all solution helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which solution worked for you? Thank You.

Also, Read