Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(losses): validate target tensor and eps in dice_loss (#6230)

Ali Tharwat5d7082e87768
diff --git a/changelog.d/6230.fixed.md b/changelog.d/6230.fixed.md
new file mode 100644
index 000000000..4e2700277
--- /dev/null
+++ b/changelog.d/6230.fixed.md
@@ -0,0 +1 @@
+`dice_loss` and `DiceLoss` raise `TypeCheckError`, a `TypeError`, when `target` is not a tensor; it used to be an `AttributeError`, or a misleading device-mismatch `ValueError` for a NumPy array. They raise `ValueError` when `eps` is a negative Python `int` or `float` (`DiceLoss` at construction); such an `eps` used to be accepted: `eps=-1e-8` gave the `eps=0` loss, and `eps=-inf` gave 1. A tensor `eps`, including one per class, is not checked and works as before. `DiceLoss` also rejects an unknown `average` when it is created instead of at its first call.
diff --git a/kornia/losses/dice.py b/kornia/losses/dice.py
index 07611d22d..6cc4e8855 100644
--- a/kornia/losses/dice.py
+++ b/kornia/losses/dice.py
@@ -253,6 +253,7 @@ def dice_loss(
"""
KORNIA_CHECK_IS_TENSOR(pred)
+ KORNIA_CHECK_IS_TENSOR(target)
if not len(pred.shape) == 4:
raise ValueError(f"Invalid pred shape, we expect BxNxHxW. Got: {pred.shape}")
@@ -265,6 +266,12 @@ def dice_loss(
if not (pred.shape[0] == target.shape[0] and pred.shape[2:] == target.shape[1:]):
raise ValueError(f"Expected target size {torch.Size((pred.shape[0], *pred.shape[2:]))}, got {target.shape}")
+
+ # Only a Python number is checked: a tensor eps worked before, and reading its value here would cost a host sync
+ # on every call and break a fullgraph compile.
+ if isinstance(eps, (int, float)) and eps < 0.0:
+ raise ValueError(f"eps must be non-negative. Got: {eps}")
+
num_of_classes = pred.shape[1]
possible_average = {"micro", "macro"}
KORNIA_CHECK(average in possible_average, f"The `average` has to be one of {possible_average}. Got: {average}")
@@ -378,6 +385,11 @@ class DiceLoss(nn.Module):
weight: Optional class-weight tensor of shape :math:`(C,)`.
ignore_index: Label value to exclude from loss computation.
"""
+ if isinstance(eps, (int, float)) and eps < 0.0:
+ raise ValueError(f"eps must be non-negative. Got: {eps}")
+ possible_average = {"micro", "macro"}
+ KORNIA_CHECK(average in possible_average, f"The `average` has to be one of {possible_average}. Got: {average}")
+
super().__init__()
self.average = average
self.eps = eps
diff --git a/tests/losses/test_dice.py b/tests/losses/test_dice.py
index 6db7f2452..64e8c404f 100644
--- a/tests/losses/test_dice.py
+++ b/tests/losses/test_dice.py
@@ -20,6 +20,7 @@ import torch
import torch.nn.functional as F
import kornia
+from kornia.core.exceptions import BaseError, TypeCheckError
from testing.base import BaseTester
@@ -270,6 +271,14 @@ class TestDiceLoss(BaseTester):
assert grad.isfinite().all()
def test_exception(self):
+ with pytest.raises(TypeCheckError) as errinf:
+ kornia.losses.DiceLoss()(None, torch.rand(1, 1, 1))
+ assert "Type mismatch: expected Tensor" in str(errinf.value)
+
+ with pytest.raises(TypeCheckError) as errinf:
+ kornia.losses.DiceLoss()(torch.rand(1, 1, 1, 1), [1, 2, 3])
+ assert "Type mismatch: expected Tensor" in str(errinf.value)
+
with pytest.raises(ValueError) as errinf:
kornia.losses.DiceLoss()(torch.rand(1, 1, 1), torch.rand(1, 1, 1))
assert "Invalid pred shape, we expect BxNxHxW. Got:" in str(errinf)
@@ -293,6 +302,34 @@ class TestDiceLoss(BaseTester):
with pytest.raises(ValueError, match=r"Expected target size torch.Size\(\[1, 4, 6\]\)"):
kornia.losses.DiceLoss()(torch.rand(1, 3, 4, 6), torch.randint(0, 3, (1, 1, 4, 6)))
+ with pytest.raises(ValueError, match="eps must be non-negative"):
+ kornia.losses.dice_loss(torch.rand(1, 1, 1, 1), torch.randint(0, 1, (1, 1, 1)), eps=-1e-8)
+
+ with pytest.raises(ValueError, match="eps must be non-negative"):
+ kornia.losses.DiceLoss(eps=-1e-8)
+
+ with pytest.raises(BaseError, match="The `average` has to be one of"):
+ kornia.losses.DiceLoss(average="invalid")
+
+ def test_tensor_eps(self, device, dtype):
+ pred = torch.rand(2, 3, 4, 4, device=device, dtype=dtype)
+ target = torch.randint(0, 3, (2, 4, 4), device=device)
+ expected = kornia.losses.dice_loss(pred, target, average="macro", eps=1e-6)
+ self.assert_close(
+ kornia.losses.dice_loss(pred, target, average="macro", eps=torch.tensor(1e-6, device=device, dtype=dtype)),
+ expected,
+ rtol=0,
+ atol=0,
+ )
+ self.assert_close(
+ kornia.losses.dice_loss(
+ pred, target, average="macro", eps=torch.full((3,), 1e-6, device=device, dtype=dtype)
+ ),
+ expected,
+ rtol=0,
+ atol=0,
+ )
+
def test_averaging_micro(self, device, dtype):
"""Keep the analytical micro-averaging reference finite in half precision."""
num_classes = 2