🐍 Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(losses): reject mismatched Lovasz target batches (#6200)
A Aswanth Raj7faf2dbbc68a
diff --git a/changelog.d/6200.fixed.md b/changelog.d/6200.fixed.mdnew file mode 100644index 000000000..9e102091c--- /dev/null+++ b/changelog.d/6200.fixed.md@@ -0,0 +1 @@+`lovasz_hinge_loss`, `lovasz_softmax_loss` and their module wrappers raise `ValueError` when the prediction and target batch sizes differ, instead of an `IndexError` or `RuntimeError` from inside the loss. A `lovasz_softmax_loss` prediction batch of one is still scored against every target, as before.diff --git a/kornia/losses/lovasz_hinge.py b/kornia/losses/lovasz_hinge.pyindex 81ca0dabb..868f899e1 100644--- a/kornia/losses/lovasz_hinge.py+++ b/kornia/losses/lovasz_hinge.py@@ -59,8 +59,8 @@ def lovasz_hinge_loss(pred: Tensor, target: Tensor) -> Tensor:Convention:- ``pred`` holds one logit channel ``(B, 1, H, W)`` and ``target`` the labels ``(B, H, W)``, 1 for the- foreground and 0 for the background. The loss is computed per image and averaged over the batch into a- 0-d tensor; there is no ``reduction``.+ foreground and 0 for the background. The batch and spatial sizes must match. The loss is computed per image+ and averaged over the batch into a 0-d tensor; there is no ``reduction``.- The loss is the Lovász extension of the Jaccard loss at the hinge errors :math:`\max(0, 1 - z (2t - 1))`of logit :math:`z` and label :math:`t`, not :math:`1 - \text{IoU}`: logits of :math:`\pm 1` that arepositive on the predicted foreground give :math:`2 (1 - \text{IoU})` of that prediction, and correct@@ -90,7 +90,7 @@ def lovasz_hinge_loss(pred: Tensor, target: Tensor) -> Tensor:KORNIA_CHECK_SHAPE(target, ["B", "H", "W"])- if not pred.shape[-2:] == target.shape[-2:]:+ if not (pred.shape[0] == target.shape[0] and pred.shape[-2:] == target.shape[-2:]):raise ValueError(f"pred and target shapes must be the same. Got: {pred.shape} and {target.shape}")if not pred.device == target.device:diff --git a/kornia/losses/lovasz_softmax.py b/kornia/losses/lovasz_softmax.pyindex 24922ff36..f7db9635f 100644--- a/kornia/losses/lovasz_softmax.py+++ b/kornia/losses/lovasz_softmax.py@@ -60,8 +60,10 @@ def lovasz_softmax_loss(pred: Tensor, target: Tensor, weight: Optional[Tensor] =Convention:- ``pred`` holds logits ``(B, C, H, W)`` with ``C >= 2`` and the softmax over dim 1 is taken inside;- ``target`` holds class labels ``(B, H, W)`` in ``[0, C)``. There is no ``ignore_index`` and the labels are- not validated: a label of ``-100`` is not ignored, and the result for it is undefined.+ ``target`` holds class labels ``(B, H, W)`` in ``[0, C)`` with the spatial size of ``pred``. The batch+ sizes match, or ``pred`` holds one image, which is scored against every target. There is no+ ``ignore_index`` and the labels are not validated: a label of ``-100`` is not ignored, and the result+ for it is undefined.- Each image is scored on its own and the losses are averaged over the batch into a 0-d tensor; there is no``reduction``. An image's loss is the mean over all ``C`` classes: a class absent from the image enters itwith that image's largest probability for the class.@@ -94,7 +96,8 @@ def lovasz_softmax_loss(pred: Tensor, target: Tensor, weight: Optional[Tensor] =if not pred.shape[1] > 1:raise ValueError(f"Invalid pred shape, we expect BxNxHxW, with N > 1. Got: {pred.shape}")- if not pred.shape[-2:] == target.shape[-2:]:+ # A prediction batch of one is scored against every target, as the computation below broadcasts it.+ if not ((pred.shape[0] == target.shape[0] or pred.shape[0] == 1) and pred.shape[-2:] == target.shape[-2:]):raise ValueError(f"pred and target shapes must be the same. Got: {pred.shape} and {target.shape}")if not pred.device == target.device:diff --git a/tests/losses/test_lovaz_hinge.py b/tests/losses/test_lovaz_hinge.pyindex 174c4f5e3..b5f337491 100644--- a/tests/losses/test_lovaz_hinge.py+++ b/tests/losses/test_lovaz_hinge.py@@ -52,6 +52,15 @@ def _lovasz_hinge_reference(logits, labels):class TestLovaszHingeLoss(BaseTester):+ @pytest.mark.parametrize(("pred_batch", "target_batch"), [(1, 2), (2, 1), (2, 3), (3, 2)])+ @pytest.mark.parametrize("as_module", [False, True])+ def test_mismatched_batch(self, pred_batch, target_batch, as_module, device, dtype):+ logits = torch.zeros(pred_batch, 1, 2, 3, device=device, dtype=dtype)+ labels = torch.zeros(target_batch, 2, 3, device=device, dtype=torch.int64)+ criterion = kornia.losses.LovaszHingeLoss() if as_module else kornia.losses.lovasz_hinge_loss+ with pytest.raises(ValueError, match="pred and target shapes must be the same"):+ criterion(logits, labels)+def test_smoke(self, device, dtype):num_classes = 1logits = torch.rand(2, num_classes, 1, 1, device=device, dtype=dtype)diff --git a/tests/losses/test_lovaz_softmax.py b/tests/losses/test_lovaz_softmax.pyindex 41e5abfa4..f8c7ea1d0 100644--- a/tests/losses/test_lovaz_softmax.py+++ b/tests/losses/test_lovaz_softmax.py@@ -56,6 +56,25 @@ def _lovasz_softmax_reference(logits, labels, weight=None):class TestLovaszSoftmaxLoss(BaseTester):+ @pytest.mark.parametrize(("pred_batch", "target_batch"), [(2, 1), (2, 3), (3, 2)])+ @pytest.mark.parametrize("as_module", [False, True])+ def test_mismatched_batch(self, pred_batch, target_batch, as_module, device, dtype):+ logits = torch.zeros(pred_batch, 2, 2, 3, device=device, dtype=dtype)+ labels = torch.zeros(target_batch, 2, 3, device=device, dtype=torch.int64)+ criterion = kornia.losses.LovaszSoftmaxLoss() if as_module else kornia.losses.lovasz_softmax_loss+ with pytest.raises(ValueError, match="pred and target shapes must be the same"):+ criterion(logits, labels)++ @pytest.mark.parametrize("as_module", [False, True])+ def test_prediction_batch_of_one_is_scored_against_every_target(self, as_module, device, dtype):+ # The computation broadcasts a one-image prediction over the targets; it keeps working as the expanded call.+ logits = torch.tensor([[[[2.0, -1.0, 0.5]], [[-1.0, 1.5, 0.0]]]], device=device, dtype=dtype)+ labels = torch.tensor([[[0, 1, 1]], [[1, 0, 0]], [[0, 0, 1]]], device=device, dtype=torch.int64)+ criterion = kornia.losses.LovaszSoftmaxLoss() if as_module else kornia.losses.lovasz_softmax_loss+ expected = criterion(logits.expand(3, -1, -1, -1), labels)+ self.assert_close(criterion(logits, labels), expected, rtol=0, atol=0)+ assert expected > criterion(logits, labels[:1])+def test_smoke(self, device, dtype):num_classes = 3logits = torch.rand(2, num_classes, 1, 1, device=device, dtype=dtype)