Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(losses): exclude absent target classes from macro Dice (#5590)

Puttala Jeevan Kumarb14cb8382e8e
diff --git a/changelog.d/5590.breaking.md b/changelog.d/5590.breaking.md
new file mode 100644
index 000000000..d57ab82a7
--- /dev/null
+++ b/changelog.d/5590.breaking.md
@@ -0,0 +1,7 @@
+`dice_loss` and `DiceLoss` with `average="macro"` now exclude classes with no
+non-ignored target pixel in each sample, and drop their weights from both the
+numerator and the denominator of the weighted mean. Previously, each absent
+class entered the mean as loss 1, so the loss grew when extra class channels
+were added. Micro averaging and samples containing every class are unchanged.
+Samples with all pixels ignored, or whose present classes all have weight 0,
+keep a loss of 1.
diff --git a/kornia/losses/dice.py b/kornia/losses/dice.py
index e035e37fd..bbca12938 100644
--- a/kornia/losses/dice.py
+++ b/kornia/losses/dice.py
@@ -70,7 +70,8 @@ def dice_loss(
average:
Reduction applied in multi-class scenario:
- ``'micro'`` [default]: Calculate the loss across all classes.
- - ``'macro'``: Calculate the loss for each class separately and average the metrics across classes.
+ - ``'macro'``: Average class losses over classes present in each sample's non-ignored target.
+ Samples with all pixels ignored, or whose present classes all have weight 0, have loss 1.
eps: Scalar to enforce numerical stabiliy.
weight: weights for classes with shape :math:`(num\_of\_classes,)`.
ignore_index: labels with this value are ignored in the loss computation.
@@ -164,7 +165,14 @@ def dice_loss(
# reduce the loss across samples (and classes in case of `macro` averaging)
if average == "macro":
- dice_loss = (dice_loss * weight).sum(-1) / weight.sum()
+ # A class is present in a sample when one of the sample's non-ignored target pixels has it.
+ present = (target_one_hot == 1).any(dim=-1).any(dim=-1)
+ weight = weight * present
+ normalizer = weight.sum(-1)
+ # No present class with a nonzero weight (all pixels ignored, or weight 0): loss 1, as before.
+ empty = normalizer == 0
+ dice_loss = (dice_loss * weight).sum(-1) / normalizer.masked_fill(empty, 1)
+ dice_loss = dice_loss.masked_fill(empty, 1)
return torch.mean(dice_loss).to(output_dtype)
@@ -177,7 +185,9 @@ class DiceLoss(nn.Module):
Args:
average: Reduction strategy for multi-class computation. Use "micro" to aggregate
- classes globally, or "macro" to average class-wise Dice scores.
+ classes globally, or "macro" to average over classes present in each sample's
+ non-ignored target. Samples with all pixels ignored, or whose present classes all have
+ weight 0, have loss 1.
eps: Small constant added to the denominator for numerical stability.
weight: Optional class-weight tensor of shape :math:`(C,)`.
ignore_index: Label value to exclude from loss computation.
diff --git a/tests/losses/test_dice.py b/tests/losses/test_dice.py
index 5c1fea406..ca0efc5e8 100644
--- a/tests/losses/test_dice.py
+++ b/tests/losses/test_dice.py
@@ -24,6 +24,132 @@ from testing.base import BaseTester
class TestDiceLoss(BaseTester):
+ def test_macro_absent_channels_5539(self, device, dtype):
+ labels = torch.zeros((1, 4, 6), device=device, dtype=torch.int64)
+ labels[0, :, 3:] = 1
+ labels[0, 0, 0] = 1
+ losses = []
+ for num_classes in (2, 3, 4):
+ logits = torch.full((1, num_classes, 4, 6), -20.0, device=device, dtype=dtype)
+ logits.scatter_(1, labels[:, None], 20.0)
+ loss = kornia.losses.dice_loss(logits, labels, average="macro")
+ assert loss.dtype == dtype
+ assert loss.device == device
+ losses.append(loss)
+ for loss in losses[1:]:
+ self.assert_close(loss, losses[0], rtol=0, atol=1e-6)
+
+ @pytest.mark.parametrize("weighted", [False, True])
+ def test_macro_target_presence_per_sample(self, device, dtype, weighted):
+ labels = torch.tensor([[[0, 1, 1, 0]], [[2, 2, 2, 2]]], device=device)
+ logits = torch.tensor(
+ [
+ [[[2.0, 0.0, 1.0, -1.0]], [[0.0, 2.0, 0.0, 1.0]], [[1.0, 1.0, 3.0, 2.0]]],
+ [[[1.0, 3.0, 2.0, 0.0]], [[2.0, 0.0, 1.0, 3.0]], [[0.0, 2.0, 0.0, 1.0]]],
+ ],
+ device=device,
+ dtype=dtype,
+ requires_grad=True,
+ )
+ weight = torch.tensor([0.25, 0.5, 8.0], device=device, dtype=dtype) if weighted else None
+ probabilities = logits.softmax(1)
+ # Evaluate only actual target labels, including when an absent class wins argmax.
+ sample_losses = []
+ for sample in range(2):
+ class_losses, class_weights = [], []
+ for label in labels[sample].unique():
+ # dice_loss builds an exact one-hot target, in float32 for half inputs.
+ reduction_dtype = torch.float64 if dtype == torch.float64 else torch.float32
+ target = (labels[sample] == label).to(reduction_dtype)
+ pred = probabilities[sample, label]
+ intersection = (pred * target).sum(dtype=reduction_dtype)
+ cardinality = (pred + target).sum(dtype=reduction_dtype)
+ class_losses.append(1 - 2 * intersection / (cardinality + 1e-8))
+ class_weights.append(weight[label] if weighted else logits.new_tensor(1.0))
+ weights = torch.stack(class_weights)
+ sample_losses.append((torch.stack(class_losses) * weights).sum() / weights.sum())
+ expected = torch.stack(sample_losses).mean().to(dtype)
+ actual = kornia.losses.dice_loss(logits, labels, average="macro", weight=weight)
+ self.assert_close(actual, expected)
+ actual_grad = torch.autograd.grad(actual, logits, retain_graph=True)[0]
+ expected_grad = torch.autograd.grad(expected, logits)[0]
+ assert actual_grad.dtype == dtype
+ assert actual_grad.device == device
+ assert torch.isfinite(actual_grad).all()
+ self.assert_close(actual_grad, expected_grad)
+
+ @pytest.mark.parametrize(
+ "average,all_classes,weighted",
+ [("micro", False, False), ("micro", True, False), ("macro", True, False), ("macro", True, True)],
+ )
+ def test_unchanged_aggregation(self, device, dtype, average, all_classes, weighted):
+ labels = torch.tensor([[[0, 1, 2 if all_classes else 1]]], device=device)
+ logits = torch.arange(9, device=device, dtype=dtype).reshape(1, 3, 1, 3) / 4
+ # dice_loss builds the one-hot target in float32 for half inputs.
+ reduction_dtype = torch.float64 if dtype == torch.float64 else torch.float32
+ target = kornia.losses.one_hot(labels, 3, device=device, dtype=reduction_dtype)
+ pred = logits.softmax(1)
+ dims = (1, 2, 3) if average == "micro" else (2, 3)
+ intersection = (pred * target).sum(dims, dtype=reduction_dtype)
+ cardinality = (pred + target).sum(dims, dtype=reduction_dtype)
+ expected = 1 - 2 * intersection / (cardinality + 1e-8)
+ weight = torch.tensor([0.25, 0.5, 8.0], device=device, dtype=dtype) if weighted else None
+ if weighted:
+ expected = (expected * weight).sum(-1) / weight.sum()
+ expected = expected.mean().to(dtype)
+ actual = kornia.losses.dice_loss(logits, labels, average=average, weight=weight)
+ self.assert_close(actual, expected, rtol=0, atol=0)
+
+ @pytest.mark.parametrize("ignore_index", [-100, 0, 255])
+ @pytest.mark.parametrize("weighted", [False, True])
+ def test_macro_ignored_samples(self, device, dtype, ignore_index, weighted):
+ labels = torch.tensor([[[1, ignore_index]], [[ignore_index, ignore_index]]], device=device)
+ logits = torch.zeros((2, 3, 1, 2), device=device, dtype=dtype, requires_grad=True)
+ weight = torch.tensor([8.0, 0.25, 4.0], device=device, dtype=dtype) if weighted else None
+ kwargs = {"average": "macro", "ignore_index": ignore_index, "weight": weight}
+ loss = kornia.losses.dice_loss(logits, labels, **kwargs)
+ # One valid class: Dice = 2 * (1/3) / (1 + 1/3) = 1/2; empty sample: loss 1.
+ self.assert_close(loss, logits.new_tensor(0.75))
+ empty_loss = kornia.losses.dice_loss(logits[1:], labels[1:], **kwargs)
+ self.assert_close(empty_loss, logits.new_tensor(1.0), rtol=0, atol=0)
+ loss.backward()
+ assert torch.isfinite(logits.grad).all()
+ self.assert_close(logits.grad[1], torch.zeros_like(logits.grad[1]), rtol=0, atol=0)
+ self.assert_close(logits.grad[0, :, :, 1], torch.zeros_like(logits.grad[0, :, :, 1]), rtol=0, atol=0)
+
+ def test_macro_sample_without_weighted_class(self, device, dtype):
+ # Sample 0 holds only class 0, whose weight is 0: no weighted class is left, as in a fully ignored sample, so
+ # it keeps loss 1 with a zero gradient instead of 0 / 0 spreading NaN over the batch.
+ labels = torch.tensor([[[0, 0, 0, 0]], [[0, 1, 1, 2]]], device=device)
+ logits = torch.tensor(
+ [
+ [[[2.0, 0.0, 1.0, -1.0]], [[0.0, 2.0, 0.0, 1.0]], [[1.0, 1.0, 3.0, 2.0]]],
+ [[[1.0, 3.0, 2.0, 0.0]], [[2.0, 0.0, 1.0, 3.0]], [[0.0, 2.0, 0.0, 1.0]]],
+ ],
+ device=device,
+ dtype=dtype,
+ requires_grad=True,
+ )
+ weight = torch.tensor([0.0, 1.0, 2.0], device=device, dtype=dtype)
+ kwargs = {"average": "macro", "weight": weight}
+ alone = kornia.losses.dice_loss(logits[:1], labels[:1], **kwargs)
+ self.assert_close(alone, logits.new_tensor(1.0), rtol=0, atol=0)
+ loss = kornia.losses.dice_loss(logits, labels, **kwargs)
+ self.assert_close(loss, (1 + kornia.losses.dice_loss(logits[1:], labels[1:], **kwargs)) / 2)
+ loss.backward()
+ assert torch.isfinite(logits.grad).all()
+ self.assert_close(logits.grad[0], torch.zeros_like(logits.grad[0]), rtol=0, atol=0)
+
+ def test_macro_absent_gradcheck(self, device):
+ logits = torch.arange(12, device=device, dtype=torch.float64).reshape(2, 3, 1, 2) / 4
+ labels = torch.tensor([[[1, -100]], [[-100, -100]]], device=device)
+ weight = torch.tensor([8.0, 0.25, 4.0], device=device, dtype=torch.float64)
+ self.gradcheck(
+ lambda pred, target: kornia.losses.dice_loss(pred, target, average="macro", weight=weight),
+ (logits, labels),
+ dtypes=[torch.float64, torch.int64],
+ )
+
@pytest.mark.parametrize("height", [256, 512])
@pytest.mark.parametrize("average", ["micro", "macro"])
@pytest.mark.parametrize("weighted", [False, True])
@@ -269,14 +395,14 @@ class TestDiceLoss(BaseTester):
exp_10_0 = torch.exp(torch.tensor([10.0], device=device, dtype=dtype))
expected_intersection_1 = (3.0 * exp_10_0 + exp_1_0) / (exp_1_0 + exp_10_0)
- expected_intersection_2 = 0.0 # all labels are 0 so the intersection for the second class is empty
expected_cardinality_1 = 4.0 + (3.0 * exp_10_0 + 1.0 * exp_1_0) / (exp_1_0 + exp_10_0)
- expected_cardinality_2 = 0.0 + (1.0 * exp_10_0 + 3.0 * exp_1_0) / (exp_1_0 + exp_10_0)
- expected_loss_1 = 1.0 - 2.0 * expected_intersection_1 / (expected_cardinality_1 + eps)
- expected_loss_2 = 1.0 - 2.0 * expected_intersection_2 / (expected_cardinality_2 + eps)
- expected_loss = (expected_loss_1 + expected_loss_2) / 2.0
- expected_loss = expected_loss.squeeze()
+ reduction_dtype = torch.float64 if dtype == torch.float64 else torch.float32
+ expected_loss_1 = 1.0 - 2.0 * expected_intersection_1.to(reduction_dtype) / (
+ expected_cardinality_1.to(reduction_dtype) + eps
+ )
+ # Class 1 is absent from the target, so only class 0 contributes to the macro mean.
+ expected_loss = expected_loss_1.squeeze().to(dtype)
criterion = kornia.losses.DiceLoss(average="macro", eps=eps)
loss = criterion(logits, labels)
@@ -306,7 +432,8 @@ class TestDiceLoss(BaseTester):
labels[ignore] = -100
self.gradcheck(kornia.losses.dice_loss, (logits, labels), dtypes=[torch.float64, torch.int64])
- def test_dynamo(self, device, dtype, torch_optimizer):
+ @pytest.mark.parametrize("average", ["micro", "macro"])
+ def test_dynamo(self, device, dtype, torch_optimizer, average):
num_classes = 3
logits = torch.rand(2, num_classes, 1, 2, device=device, dtype=dtype)
labels = torch.rand(2, 1, 2) * num_classes
@@ -315,7 +442,7 @@ class TestDiceLoss(BaseTester):
op = kornia.losses.dice_loss
op_optimized = torch_optimizer(op)
- self.assert_close(op(logits, labels), op_optimized(logits, labels))
+ self.assert_close(op(logits, labels, average=average), op_optimized(logits, labels, average=average))
def test_module(self, device, dtype):
num_classes = 3