Defake:

loss = criterion_test(dec_outs.view(-1, vocab_size, batch_size), targets.view(-1, batch_size))


I think you need to do criterion_test(dec_outs.view(-1, vocab_size),targets.view(-1))
In your case, ( C )-> vocab_size and (N)-> (batch_size*seq_length). I am assuming all the batches have the same sequence length. If not, you’ll have to use pack_padded_sequence and also mask the loss for the pad token.