The code and shapes of your output and target are generally alright.
However, since you are trying to calculate a loss using spatial inputs, you would have to use torch::nll_loss2d as the loss function.