Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(losses): exclude ignored logits before focal log-softmax (#5153)

AhmetHakanBezira445318eb622
diff --git a/changelog.d/5153.fixed.md b/changelog.d/5153.fixed.md
new file mode 100644
index 000000000..b6884c9c4
--- /dev/null
+++ b/changelog.d/5153.fixed.md
@@ -0,0 +1,3 @@
+`focal_loss` and `FocalLoss` now exclude ignored logits before log-softmax, so extreme finite logits (whose
+log-probability overflows) and infinite or NaN logits at ignored positions no longer turn the loss and its gradients
+into NaN.
diff --git a/kornia/losses/focal.py b/kornia/losses/focal.py
index d4e0a422f..719041ccb 100644
--- a/kornia/losses/focal.py
+++ b/kornia/losses/focal.py
@@ -96,6 +96,8 @@ def focal_loss(
if target_mask is not None:
target_mask.unsqueeze_(1)
target_one_hot = target_one_hot * target_mask
+ # Exclude ignored logits before log-softmax: an overflowing log probability times zero is NaN.
+ pred = pred.masked_fill(~target_mask, 0.0)
# compute F.softmax over the classes axis
log_pred_soft: torch.Tensor = pred.log_softmax(1)
diff --git a/tests/losses/test_focal_loss.py b/tests/losses/test_focal_loss.py
index ecb4d0ea3..f4643ef23 100644
--- a/tests/losses/test_focal_loss.py
+++ b/tests/losses/test_focal_loss.py
@@ -145,6 +145,60 @@ class TestBinaryFocalLossWithLogits(BaseTester):
class TestFocalLoss(BaseTester):
+ @pytest.mark.parametrize("reduction", ["none", "mean", "sum"])
+ @pytest.mark.parametrize("gamma", [0.0, 2.0])
+ @pytest.mark.parametrize("weighted", [False, True])
+ @pytest.mark.parametrize("spatial", [False, True])
+ def test_ignored_extreme_logits(self, device, dtype, reduction, gamma, weighted, spatial):
+ extreme = torch.finfo(dtype).max
+ logits = torch.tensor([[extreme, -extreme], [0.0, 0.0]], device=device, dtype=dtype)
+ labels = torch.tensor([-100, 0], device=device)
+ if spatial:
+ logits = logits.T.reshape(1, 2, 1, 2)
+ labels = labels.reshape(1, 1, 2)
+ logits = logits.requires_grad_()
+ weight = torch.tensor([0.5, 1.5], device=device, dtype=dtype) if weighted else None
+ alpha = 0.25 if weighted else None
+ safe_logits = torch.zeros_like(logits, requires_grad=True)
+ op = kornia.losses.focal_loss
+ expected = op(safe_logits, labels, alpha, gamma, reduction, weight)
+ actual = op(logits, labels, alpha, gamma, reduction, weight)
+ self.assert_close(actual, expected)
+ self.assert_close(
+ torch.autograd.grad(actual.sum(), logits)[0], torch.autograd.grad(expected.sum(), safe_logits)[0]
+ )
+ self.assert_close(kornia.losses.FocalLoss(alpha, gamma, reduction, weight)(logits, labels), expected)
+
+ @pytest.mark.parametrize("ignore_index", [-100, 255])
+ def test_all_ignored_extreme_logits(self, device, dtype, ignore_index):
+ extreme = torch.finfo(dtype).max
+ logits = torch.tensor([[extreme, -extreme]], device=device, dtype=dtype, requires_grad=True)
+ labels = torch.full((1,), ignore_index, device=device, dtype=torch.int64)
+ loss = kornia.losses.focal_loss(logits, labels, alpha=None, reduction="sum", ignore_index=ignore_index)
+ self.assert_close(loss, torch.zeros_like(loss))
+ self.assert_close(torch.autograd.grad(loss, logits)[0], torch.zeros_like(logits))
+
+ @pytest.mark.parametrize("value", [float("inf"), float("-inf"), float("nan")])
+ def test_ignored_non_finite_logits(self, device, dtype, value):
+ logits = torch.tensor([[value, 0.0], [0.3, -0.2]], device=device, dtype=dtype, requires_grad=True)
+ safe_logits = torch.tensor([[0.0, 0.0], [0.3, -0.2]], device=device, dtype=dtype, requires_grad=True)
+ labels = torch.tensor([-100, 1], device=device)
+ actual = kornia.losses.focal_loss(logits, labels, alpha=0.25, reduction="sum")
+ expected = kornia.losses.focal_loss(safe_logits, labels, alpha=0.25, reduction="sum")
+ self.assert_close(actual, expected)
+ grad = torch.autograd.grad(actual, logits)[0]
+ assert (grad[0] == 0).all()
+ self.assert_close(grad, torch.autograd.grad(expected, safe_logits)[0])
+
+ def test_dynamo_ignored_extreme_logits(self, device, dtype, torch_optimizer):
+ extreme = torch.finfo(dtype).max
+ logits = torch.tensor([[extreme, -extreme]], device=device, dtype=dtype, requires_grad=True)
+ labels = torch.full((1,), -100, device=device, dtype=torch.int64)
+ op = torch_optimizer(kornia.losses.focal_loss)
+ loss = op(logits, labels, None, reduction="sum")
+ self.assert_close(loss, torch.zeros_like(loss))
+ self.assert_close(torch.autograd.grad(loss, logits)[0], torch.zeros_like(logits))
+
@pytest.mark.parametrize("reduction,expected_shape", [("none", (2, 3, 3, 2)), ("mean", ()), ("sum", ())])
@pytest.mark.parametrize("alpha", [None, 0.2, 0.5])
@pytest.mark.parametrize("gamma", [0.0, 1.0, 2.0])