The tensor y is a 2D tensor of sshape (batch_size, VOCAB_SIZE). So, when you pass yhat and y to loss_fucntion, you want to make sure that yhat has the same shape as y. So using yhat.view(-1, VOCAB_SIZE) will do the job.