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?

1 Like

Don’t say batch first if you don’t mean it. :slight_smile:

Best regards

Thomas

P.S.: Pro tip: PyTorch supports not passing the initial state (implicitly initializing to 0). Calling like that will give you a final state where you can read off the required shape.

2 Likes