There is an error with LSTM Hidden state dimension: RuntimeError: Expected hidden[0] size (4, 1, 256), got (1, 256)
I'm experimenting with seq2seq_tutorial in PyTorch. There appears to be a dimension error with the encoder's lstm hidden state size.

With bidirectional=True and num_layers = 2, the hidden state's shape is supposed to be (num_layers*2, batch_size, hidden_size). 

However, an error occurs with the following message:

RuntimeError: Expected hidden[0] size (4, 1, 256), got (1, 256)

I have tried reshaping the hidden state to initializing the hidden state with a different shape, to begin with, but nothing seems to work.

Here is the train method of my code:

def train(self, input, target, encoder, decoder, encoder_optim, decoder_optim, criterion):
    enc_optimizer = encoder_optim
    dec_optimizer = decoder_optim
    enc_optimizer.zero_grad()
    dec_optimizer.zero_grad()

    pair = (input, target)
    input_len = input.size(0)
    target_len = target.size(0)
    enc_output_tensor = torch.zeros(self.opt['max_seq_len'], encoder.hidden_size, device=device)
    enc_hidden = encoder.cuda().initHidden(device)

    for word_idx in range(input_len):
        print('Input:', input[word_idx], '\nHidden shape:', enc_hidden.size())
        enc_output, enc_hidden = encoder(input[word_idx], enc_hidden)
        enc_output_tensor[word_idx] = enc_output[0,0]


Here is the encoder method of my code:

class EncoderBRNN(nn.Module):
    # A bidirectional rnn based encoder
    def __init__(self, input_size, hidden_size, emb_size, batch_size=1, num_layers=2, bidir=True):
        super(EncoderBRNN, self).__init__()
        self.input_size = input_size
        self.hidden_size = hidden_size
        self.batch_size = batch_size
        self.embedding_dim = emb_size
        self.num_layers = num_layers
        self.bidir = bidir
        self.embedding_layer = nn.Embedding(self.input_size, self.embedding_dim)
        self.enc_layer = nn.LSTM(self.embedding_dim, self.hidden_size, num_layers=self.num_layers, bidirectional=self.bidir)

    def forward(self, input, hidden):
        embed = self.embedding_layer(input).view(1, 1, -1)
        output, hidden = self.enc_layer(embed, hidden)
        return output, hidden

    def initHidden(self, device):
        if self.bidir:
            num_stacks = self.num_layers * 2
        else:
            num_stacks = self.num_layers
        return torch.zeros(num_stacks, self.batch_size, self.hidden_size, device=device)


I know this was asked a while ago but I think I found the answer to this in this torch discussion. Relevant info:


  LSTM takes a tuple of hidden states: self.rnn(x, (h_0, c_0)) it looks like you haven’t sent in the second hidden state?


You can also see this in the documentation for LSTM
