Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(losses): let kl_div_loss_2d and js_div_loss_2d treat empty target cells as 0 instead of NaN (#5557)

εŒΊζ’“η1f97c27210bc
diff --git a/changelog.d/5557.fixed.md b/changelog.d/5557.fixed.md
new file mode 100644
index 000000000..e938368a6
--- /dev/null
+++ b/changelog.d/5557.fixed.md
@@ -0,0 +1,6 @@
+`kl_div_loss_2d` and `js_div_loss_2d` now apply the `0 Β· log 0 = 0` convention, so a distribution with empty cells
+compared with itself gives 0 with finite gradients instead of NaN (#5554). A zero cell also no longer makes a
+gradient NaN where the value was finite: the gradient of `kl_div_loss_2d` with respect to `target`, and of
+`js_div_loss_2d` with respect to either input, was NaN at every zero cell of that input. Every other cell keeps its
+value, including `+inf` where `pred` is zero and `target` is positive, and NaN for a NaN or negative entry and for an
+infinite `pred` where `target` is zero; strictly positive heatmaps are unchanged.
diff --git a/kornia/losses/divergence.py b/kornia/losses/divergence.py
index 20dd3bba2..791f51b2f 100644
--- a/kornia/losses/divergence.py
+++ b/kornia/losses/divergence.py
@@ -26,11 +26,17 @@ 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)
+ # D_KL(P || Q) with the convention 0 * log 0 = 0. Cells with p == 0 and a finite q >= 0 contribute nothing to the
+ # value or the gradient: both arguments are replaced by 1 there, so a q == 0 in such a cell cannot turn the term
+ # into NaN. Every other cell keeps the value of F.kl_div, so a NaN or a negative entry in either input, or an
+ # infinite q where p == 0, still gives NaN.
batch, chans, height, width = p.shape
- unsummed_kl = F.kl_div(
- q.reshape(batch * chans, height * width).log(), p.reshape(batch * chans, height * width), reduction="none"
- )
+ p = p.reshape(batch * chans, height * width)
+ q = q.reshape(batch * chans, height * width)
+ empty = (p == 0) & (q >= 0) & torch.isfinite(q)
+ p = p.masked_fill(empty, 1.0)
+ q = q.masked_fill(empty, 1.0)
+ unsummed_kl = F.kl_div(q.log(), p, reduction="none")
return unsummed_kl.sum(-1).view(batch, chans)
diff --git a/tests/losses/test_divergence.py b/tests/losses/test_divergence.py
index 865a1064d..735423bf2 100644
--- a/tests/losses/test_divergence.py
+++ b/tests/losses/test_divergence.py
@@ -161,3 +161,53 @@ class TestDivergenceLoss(BaseTester):
op = kornia.losses.js_div_loss_2d
op_optimized = torch_optimizer(op)
self.assert_close(op(*args), op_optimized(*args), rtol=0, atol=1e-5)
+
+ @pytest.mark.parametrize("loss", [kornia.losses.kl_div_loss_2d, kornia.losses.js_div_loss_2d])
+ def test_identical_distributions_with_zero_cells(self, device, dtype, loss):
+ # 0 * log 0 = 0: a distribution compared with itself has zero divergence and finite gradients even where it
+ # has empty cells (#5554).
+ p = torch.tensor([0.0, 0.25, 0.75, 0.0, 0.0, 0.0], device=device, dtype=dtype).view(1, 1, 2, 3)
+ pred, target = p.clone().requires_grad_(), p.clone().requires_grad_()
+ actual = loss(pred, target)
+ # xlogy(p, p) and p * log(p) can differ by an ulp on some CPUs, so the value is zero up to the default
+ # tolerance.
+ self.assert_close(actual, torch.zeros_like(actual))
+ actual.backward()
+ assert torch.isfinite(pred.grad).all() and torch.isfinite(target.grad).all()
+ assert torch.equal(pred.grad[p == 0], torch.zeros_like(pred.grad[p == 0]))
+ assert torch.equal(target.grad[p == 0], torch.zeros_like(target.grad[p == 0]))
+
+ def test_zero_cell_in_one_input(self, device, dtype):
+ # A zero cell in target alone contributes 0; a zero cell in pred where target > 0 is the true KL, +inf (#5554).
+ p = torch.tensor([0.0, 0.25, 0.75, 0.0, 0.0, 0.0], device=device, dtype=dtype).view(1, 1, 2, 3)
+ q = torch.tensor([0.1, 0.2, 0.3, 0.1, 0.2, 0.1], device=device, dtype=dtype).view(1, 1, 2, 3)
+ expected = (p[p > 0] * (p[p > 0].log() - q[p > 0].log())).sum()
+ self.assert_close(kornia.losses.kl_div_loss_2d(q, p), expected)
+ assert kornia.losses.kl_div_loss_2d(p, q).item() == math.inf
+
+ @pytest.mark.parametrize("loss", [kornia.losses.kl_div_loss_2d, kornia.losses.js_div_loss_2d])
+ def test_zero_cell_in_target_alone_has_finite_gradients(self, device, dtype, loss):
+ # A zero cell in target alone already contributed 0 to the value, but the gradient with respect to target was
+ # NaN there (#5554).
+ p = torch.tensor([0.0, 0.25, 0.75, 0.0, 0.0, 0.0], device=device, dtype=dtype).view(1, 1, 2, 3)
+ q = torch.tensor([0.1, 0.2, 0.3, 0.1, 0.2, 0.1], device=device, dtype=dtype).view(1, 1, 2, 3)
+ pred, target = q.clone().requires_grad_(), p.clone().requires_grad_()
+ loss(pred, target).backward()
+ assert torch.isfinite(pred.grad).all() and torch.isfinite(target.grad).all()
+
+ @pytest.mark.parametrize("loss", [kornia.losses.kl_div_loss_2d, kornia.losses.js_div_loss_2d])
+ def test_invalid_cells_stay_nan(self, device, dtype, loss):
+ # 0 * log 0 = 0 covers only target == 0 with a finite pred >= 0 (#5554): a NaN or a negative entry in either
+ # input, or an infinite pred where target is 0, keeps the NaN of its (b, n) slice, and the other slices of the
+ # batch are unaffected.
+ p = torch.tensor([0.0, 0.25, 0.75, 0.0, 0.0, 0.0], device=device, dtype=dtype).view(1, 1, 2, 3)
+ q = torch.tensor([0.1, 0.2, 0.3, 0.1, 0.2, 0.1], device=device, dtype=dtype).view(1, 1, 2, 3)
+ pred, target = q.repeat(6, 1, 1, 1), p.repeat(6, 1, 1, 1)
+ target[1, 0, 0, 0] = float("nan")
+ target[2, 0, 0, 0] = -0.25
+ pred[3, 0, 1, 0] = float("nan") # target is 0 in this cell
+ pred[4, 0, 1, 0] = -0.1 # target is 0 in this cell
+ pred[5, 0, 1, 0] = math.inf # target is 0 in this cell
+ actual = loss(pred, target, reduction="none")
+ self.assert_close(actual[0], loss(q, p, reduction="none")[0])
+ assert torch.isnan(actual[1:]).all()