The last code works will.Just the first two code has problems.

loss=nn.CrossEntropyLoss()
input = torch.randn(3,21,50,50, requires_grad=True)
target = torch.empty(3,50,50, dtype=torch.long).random_(5)
output = loss(input, target)
output
tensor(3.5024, grad_fn=)

CrossEntropyLoss() don’t need the target to have the same channel with input,but the n,h and w need to be same.