Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(losses): validate the reduction and the heatmap shapes of kl_div_loss_2d and js_div_loss_2d (#5555)

区梓灏dd6520fc2d83
diff --git a/changelog.d/5555.breaking.md b/changelog.d/5555.breaking.md
new file mode 100644
index 000000000..5af0ebab9
--- /dev/null
+++ b/changelog.d/5555.breaking.md
@@ -0,0 +1,7 @@
+`kl_div_loss_2d` and `js_div_loss_2d` now raise `NotImplementedError` for a `reduction` outside `'none'`, `'mean'`
+and `'sum'`, and check that `pred` and `target` are 4-D `(B, N, H, W)` tensors of the same shape (#5535). Before, any
+other reduction, torch's `'batchmean'` and `None` included, silently returned the `'sum'`, B · N times the `'mean'`
+value; kornia's `'mean'` is torch's `'batchmean'` on the `(B · N, H · W)` reshape. Before, `kl_div_loss_2d` also read
+a `pred` of another shape with the same number of elements, such as one with H and W swapped, in the layout of
+`target` and returned a value; it now raises `BaseError`. Shape mismatches that already failed now raise kornia's
+`BaseError`, or `ShapeError` for an input that is not 4-D, instead of torch's `RuntimeError` or a bare `ValueError`.
diff --git a/kornia/losses/divergence.py b/kornia/losses/divergence.py
index 9591b867d..20dd3bba2 100644
--- a/kornia/losses/divergence.py
+++ b/kornia/losses/divergence.py
@@ -22,6 +22,8 @@ from __future__ import annotations
import torch
import torch.nn.functional as F
+from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SHAPE
+
def _kl_div_2d(p: torch.Tensor, q: torch.Tensor) -> torch.Tensor:
# D_KL(P || Q)
@@ -43,7 +45,18 @@ def _js_div_2d(p: torch.Tensor, q: torch.Tensor) -> torch.Tensor:
def _reduce_loss(losses: torch.Tensor, reduction: str) -> torch.Tensor:
if reduction == "none":
return losses
- return torch.mean(losses) if reduction == "mean" else torch.sum(losses)
+ if reduction == "mean":
+ return torch.mean(losses)
+ if reduction == "sum":
+ return torch.sum(losses)
+ raise NotImplementedError(f"Invalid reduction mode: {reduction}")
+
+
+def _check_heatmaps(pred: torch.Tensor, target: torch.Tensor) -> None:
+ KORNIA_CHECK_SHAPE(pred, ["B", "N", "H", "W"])
+ KORNIA_CHECK(
+ pred.shape == target.shape, f"pred and target shapes must be the same. Got: {pred.shape} and {target.shape}"
+ )
def js_div_loss_2d(pred: torch.Tensor, target: torch.Tensor, reduction: str = "mean") -> torch.Tensor:
@@ -65,6 +78,7 @@ def js_div_loss_2d(pred: torch.Tensor, target: torch.Tensor, reduction: str = "m
0.0
"""
+ _check_heatmaps(pred, target)
return _reduce_loss(_js_div_2d(target, pred), reduction)
@@ -87,4 +101,5 @@ def kl_div_loss_2d(pred: torch.Tensor, target: torch.Tensor, reduction: str = "m
0.0
"""
+ _check_heatmaps(pred, target)
return _reduce_loss(_kl_div_2d(target, pred), reduction)
diff --git a/tests/losses/test_divergence.py b/tests/losses/test_divergence.py
index 6b8018d28..865a1064d 100644
--- a/tests/losses/test_divergence.py
+++ b/tests/losses/test_divergence.py
@@ -21,6 +21,7 @@ import pytest
import torch
import kornia
+from kornia.core.exceptions import BaseError, ShapeError
from testing.base import BaseTester
@@ -99,6 +100,36 @@ class TestDivergenceLoss(BaseTester):
expected = torch.tensor(expected).to(device, dtype)
self.assert_close(actual, expected)
+ @pytest.mark.parametrize("loss", [kornia.losses.kl_div_loss_2d, kornia.losses.js_div_loss_2d])
+ def test_reduction_sum(self, device, dtype, loss):
+ pred = torch.full((2, 3, 2, 4), 0.125, device=device, dtype=dtype)
+ target = torch.zeros((2, 3, 2, 4), device=device, dtype=dtype)
+ target[..., 0, 0] = 1.0
+ unreduced = loss(pred, target, reduction="none")
+ assert unreduced.shape == (2, 3)
+ self.assert_close(loss(pred, target, reduction="sum"), unreduced.sum())
+ self.assert_close(loss(pred, target, reduction="mean"), unreduced.mean())
+
+ @pytest.mark.parametrize("loss", [kornia.losses.kl_div_loss_2d, kornia.losses.js_div_loss_2d])
+ @pytest.mark.parametrize("reduction", ["batchmean", "MEAN", "avg", None])
+ def test_exception_invalid_reduction(self, device, dtype, loss, reduction):
+ # An unknown reduction raises as in the sibling losses instead of returning the sum (#5535).
+ pred = torch.full((1, 1, 2, 4), 0.125, device=device, dtype=dtype)
+ with pytest.raises(NotImplementedError, match="Invalid reduction mode"):
+ loss(pred, pred, reduction=reduction)
+
+ @pytest.mark.parametrize("loss", [kornia.losses.kl_div_loss_2d, kornia.losses.js_div_loss_2d])
+ def test_exception_shape(self, device, dtype, loss):
+ # pred and target must be 4-D (B, N, H, W) of the same shape; a transposed pred was reinterpreted in the
+ # layout of target (#5535).
+ target = torch.full((2, 3, 4, 6), 1 / 24, device=device, dtype=dtype)
+ with pytest.raises(BaseError, match="pred and target shapes must be the same"):
+ loss(target.transpose(-2, -1).contiguous(), target)
+ with pytest.raises(BaseError, match="pred and target shapes must be the same"):
+ loss(target[:, :2], target)
+ with pytest.raises(ShapeError):
+ loss(target[0], target[0])
+
def test_gradcheck_kl(self, device, dtype):
dtype = torch.float64
pred = torch.rand(1, 1, 10, 16, device=device, dtype=dtype)