What about weighting the dice loss with zero values when you have to ignore it :

def dice_loss(output, target, weights=1, ignore_index=None):
    b, c, h, w = output.size()
    output = output.exp()
    encoded_target = output.data.new(b, c, h, w).zero_()
    encoded_target.scatter_(1, target.unsqueeze(0), 1)
    encoded_target = Variable(encoded_target)
    mask = None
    if ignore_index is not None:
        # mask of invalid label
        mask = (target == ignore_index).float()
        # expand the mask for the encoded target array
        mask = Variable(mask.unsqueeze(1))


    assert output.size() == encoded_target.size(), "Input sizes must be equal."
    assert output.dim() == 4, "Input must be a 4D Tensor."

    o = output
    t = encoded_target
    numerator = o * t
    denominator = o.pow(2) + t

    dice = 2 * (numerator / denominator) * weights  # dimensions are still [B, C, H, W] at this point
    if mask is not None:
        return (dice*mask).sum()  # array broadcasting is awesome !
    return dice.sum()