It seems you are trying to calculate the dice loss for a multi-class prediction.
If that’s the case, you shouldn’t just flatten the prediction and target, as this will yield the size mismatch error (your prediction contains more values than the target).
You could try to pass your target as a one-hot encoded tensor and use @IssamLaradji’s approach 87.