Search code examples
python-3.xlstmpytorchbatchsize

LSTM's expected hidden state dimensions doesn't take batch size into account


I have this decoder model, which is supposed to take batches of sentence embeddings (batchsize = 50, hidden size=300) as input and output a batch of one hot representation of predicted sentences:

class DecoderLSTMwithBatchSupport(nn.Module):
        # Your code goes here
        def __init__(self, embedding_size,batch_size, hidden_size, output_size):
            super(DecoderLSTMwithBatchSupport, self).__init__()
            self.hidden_size = hidden_size
            self.batch_size = batch_size
            self.lstm = nn.LSTM(input_size=embedding_size,num_layers=1, hidden_size=hidden_size, batch_first=True)
            self.out = nn.Linear(hidden_size, output_size)
            self.softmax = nn.LogSoftmax(dim=1)

        def forward(self, my_input, hidden):
            print(type(my_input), type(hidden))
            output, hidden = self.lstm(my_input, hidden)
            output = self.softmax(self.out(output[0]))
            return output, hidden

        def initHidden(self):
            return Variable(torch.zeros(1, self.batch_size, self.hidden_size)).cuda()

However, when I run it using:

decoder=DecoderLSTMwithBatchSupport(vocabularySize,batch_size, 300, vocabularySize)
decoder.cuda()
decoder_input=np.zeros([batch_size,vocabularySize])
    for i in range(batch_size):
        decoder_input[i] = embeddings[SOS_token]
    decoder_input=Variable(torch.from_numpy(decoder_input)).cuda()
    decoder_hidden = (decoder.initHidden(),decoder.initHidden())
        for di in range(target_length):
            decoder_output, decoder_hidden = decoder(decoder_input.view(1,batch_size,-1), decoder_hidden)

I get he following error:

Expected hidden[0] size (1, 1, 300), got (1, 50, 300)

What am I missing in order to make the model expect batched hidden states?


Solution

  • When you create the LSTM, the flag batch_first is not necessary, because it assumes a different shape of your input. From the docs:

    If True, then the input and output tensors are provided as (batch, seq, feature). Default: False

    change the LSTM creation to:

    self.lstm = nn.LSTM(input_size=embedding_size, num_layers=1, hidden_size=hidden_size)
    

    Also, there is a type error. When you create the decoder_input using torch.from_numpy() it has a dtype=torch.float64, while decoder_input has as default dtype=torch.float32. Change the line where you create the decoder_input to something like

    decoder_input = Variable(torch.from_numpy(decoder_input)).cuda().float()
    

    With both changes, it is supposed to work fine :)