nn.NLLLoss2d takes in a weights parameter in it’s constructor, which is the weights given to each class. For the labels to ignore, you can give 0 weight and the ones to count, you can give weight of 1.
For example:
import torch
import torch.nn as nn

nClasses = 10
ignore_classes = torch.LongTensor([4, 7]) # ignore class 5 and 8
weights = torch.ones(nClasses)
weights[ignore_classes] = 0.0
loss = nn.NLLLoss2d(weights)