Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(losses): check the target batch of dice_loss and tversky_loss (#5561)

εŒΊζ’“ηed58972788d7
diff --git a/changelog.d/5561.breaking.md b/changelog.d/5561.breaking.md
new file mode 100644
index 000000000..dd75a27ff
--- /dev/null
+++ b/changelog.d/5561.breaking.md
@@ -0,0 +1,7 @@
+`dice_loss`, `tversky_loss`, `DiceLoss` and `TverskyLoss` now require a `target` of shape `(B, H, W)` for a `pred` of
+shape `(B, C, H, W)` and raise `ValueError` otherwise (#5544). They used to compare only `H` and `W`, and some
+mismatched targets returned a value: with a `(1, H, W)` target for `B > 1`, `tversky_loss` returned the loss of sample
+0 alone and `dice_loss` broadcast the target over the batch; with `B = 1`, `dice_loss` averaged the prediction's loss
+over a larger target batch and returned a wrong loss for a `(1, 1, H, W)` target. Callers that relied on the broadcast
+must expand the target themselves. Most other mismatches ended in torch's `RuntimeError`; they now raise `ValueError`
+too, which `except RuntimeError` does not catch.
diff --git a/kornia/losses/dice.py b/kornia/losses/dice.py
index 76c7da46d..e035e37fd 100644
--- a/kornia/losses/dice.py
+++ b/kornia/losses/dice.py
@@ -101,6 +101,9 @@ def dice_loss(
if not pred.device == target.device:
raise ValueError(f"pred and target must be in the same device. Got: {pred.device} and {target.device}")
+
+ 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}")
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}")
diff --git a/kornia/losses/tversky.py b/kornia/losses/tversky.py
index dded3f1ce..7ea8914f8 100644
--- a/kornia/losses/tversky.py
+++ b/kornia/losses/tversky.py
@@ -94,6 +94,9 @@ def tversky_loss(
if not pred.device == target.device:
raise ValueError(f"pred and target must be in the same device. Got: {pred.device} and {target.device}")
+ 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}")
+
# compute softmax over the classes axis
pred_soft = F.softmax(pred, dim=1)
target, target_mask = mask_ignore_pixels(target, ignore_index)
diff --git a/tests/losses/test_dice.py b/tests/losses/test_dice.py
index f89e15027..5c1fea406 100644
--- a/tests/losses/test_dice.py
+++ b/tests/losses/test_dice.py
@@ -118,6 +118,17 @@ class TestDiceLoss(BaseTester):
kornia.losses.DiceLoss()(torch.rand(1, 1, 1, 1), torch.rand(1, 1, 1, 1, device="meta"))
assert "pred and target must be in the same device. Got:" in str(errinf)
+ # The target batch has to match the prediction batch, as for focal_loss (#5544).
+ with pytest.raises(ValueError, match=r"Expected target size torch.Size\(\[2, 4, 6\]\)"):
+ kornia.losses.DiceLoss()(torch.rand(2, 3, 4, 6), torch.randint(0, 3, (1, 4, 6)))
+
+ 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, (2, 4, 6)))
+
+ # A target with a channel axis, (B, 1, H, W), is not (B, H, W) either.
+ 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)))
+
def test_averaging_micro(self, device, dtype):
num_classes = 2
eps = 1e-8
@@ -128,7 +139,7 @@ class TestDiceLoss(BaseTester):
logits[:, 1, 0:3] = 1.0
logits[:, 1, 3:4] = 10.0
- labels = torch.zeros(2, 4, 1, device=device, dtype=torch.int64)
+ labels = torch.zeros(1, 4, 1, device=device, dtype=torch.int64)
exp_1_0 = torch.exp(torch.tensor([1.0], device=device, dtype=dtype))
exp_10_0 = torch.exp(torch.tensor([10.0], device=device, dtype=dtype))
@@ -252,7 +263,7 @@ class TestDiceLoss(BaseTester):
logits[:, 1, :, 0:3] = 1.0
logits[:, 1, :, 3:4] = 10.0
- labels = torch.zeros(2, 1, 4, device=device, dtype=torch.int64)
+ labels = torch.zeros(1, 1, 4, device=device, dtype=torch.int64)
exp_1_0 = torch.exp(torch.tensor([1.0], device=device, dtype=dtype))
exp_10_0 = torch.exp(torch.tensor([10.0], device=device, dtype=dtype))
diff --git a/tests/losses/test_tversky.py b/tests/losses/test_tversky.py
index 9d7f57484..5bc758e0b 100644
--- a/tests/losses/test_tversky.py
+++ b/tests/losses/test_tversky.py
@@ -107,6 +107,17 @@ class TestTverskyLoss(BaseTester):
criterion(torch.rand(1, 1, 1, 1), torch.rand(1, 1, 1, 1, device="meta"))
assert "pred and target must be in the same device. Got:" in str(errinfo)
+ # The target batch has to match the prediction batch, as for focal_loss (#5544).
+ with pytest.raises(ValueError, match=r"Expected target size torch.Size\(\[2, 4, 6\]\)"):
+ criterion(torch.rand(2, 3, 4, 6), torch.randint(0, 3, (1, 4, 6)))
+
+ with pytest.raises(ValueError, match=r"Expected target size torch.Size\(\[1, 4, 6\]\)"):
+ criterion(torch.rand(1, 3, 4, 6), torch.randint(0, 3, (2, 4, 6)))
+
+ # A target with a channel axis, (B, 1, H, W), is not (B, H, W) either.
+ with pytest.raises(ValueError, match=r"Expected target size torch.Size\(\[1, 4, 6\]\)"):
+ criterion(torch.rand(1, 3, 4, 6), torch.randint(0, 3, (1, 1, 4, 6)))
+
@pytest.mark.parametrize("ignore_index", [-100, None])
def test_all_zeros(self, device, dtype, ignore_index):
num_classes = 3