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

I am getting the following error.

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

I have a class as follows.

class QuestionClassifier(nn.Module):

def __init__(self, dictionary, embeddings_index, max_seq_length, args):
    """"Constructor of the class"""
    self.embedding = EmbeddingLayer(len(dictionary), args.emsize, args.dropout)
    self.encoder = EncoderRNN(args.emsize, args.nhid, args.model, args.bidirection, 
                                                   args.nlayers, args.dropout)
    self.drop = nn.Dropout(args.dropout)

So, when I run the following line:

question_classifier = QuestionClassifier(corpus.dictionary, embeddings_index, corpus.max_sent_length, args)

I get the above mentioned error. Here, EmbeddingLayer and EncoderRNN is a class written by me which inherits nn.module like the QuestionClassifier class.

What I am doing wrong here?

3 Likes

The first thing you should always do when you create a module is call its super constructor…

So, your class should look like this:

class QuestionClassifier(nn.Module):

    def __init__(self, dictionary, embeddings_index, max_seq_length, args):
        """"Constructor of the class"""
        super(QuestionClassifier, self).__init__()

        self.embedding = EmbeddingLayer(len(dictionary), args.emsize, args.dropout)
        self.encoder = EncoderRNN(args.emsize, args.nhid, args.model, args.bidirection, args.nlayers, args.dropout)
        
        self.drop = nn.Dropout(args.dropout)
13 Likes

Add
super(QuestionClassifier, self).__init__()
after def __init__(self, dictionary, embeddings_index, max_seq_length, args): line

Pytorch keeps track of your custom class submodules like Embedding, nn.RNN using an ordered dictionary in addition to other things. And this dictionary is first initialized in nn.Module. If you inherit nn.Module as you did in in the first line class QuestionClassifier(nn.Module): , you still need to call the __init__() method of the nn.Module to initialize the ordered dictionary which will hold your submodules like nn.RNN. Use the super keyword to call the __init__() of the parent class.