Shouldn’t this work?
loss_function = nn.NLLLoss(ignore_index=out_word2idx['<PAD>']).cuda()
loss = loss_function(output, y_data)

FWIW, I find it generally cleaner to use the “functional” version, but it’s up to you:
import torch.nn.functional as F
loss = F.nll_loss(output, y_data, ignore_index=out_word2idx['<PAD>'])