Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(losses): keep focal_loss gradients finite for fractional gamma (#5563)

Aditya17-bota45b61c7ff32
diff --git a/changelog.d/5563.fixed.md b/changelog.d/5563.fixed.md
new file mode 100644
index 000000000..084c7dfc9
--- /dev/null
+++ b/changelog.d/5563.fixed.md
@@ -0,0 +1 @@
+`focal_loss` no longer returns NaN gradients with a fractional focusing parameter (`0 < gamma < 1`) when the softmax probability of any class rounds to 1, for a correct and a wrong prediction alike.
diff --git a/kornia/losses/focal.py b/kornia/losses/focal.py
index c4b848999..e4770e779 100644
--- a/kornia/losses/focal.py
+++ b/kornia/losses/focal.py
@@ -103,7 +103,13 @@ def focal_loss(
log_pred_soft: torch.Tensor = pred.log_softmax(1)
# compute the actual focal loss
- loss_tmp: torch.Tensor = -torch.pow(1.0 - log_pred_soft.exp(), gamma) * log_pred_soft * target_one_hot
+ # For 0 < gamma < 1, x ** gamma has an infinite derivative at x = 0, so a probability that rounds to 1 gives a
+ # NaN gradient. The loss term (1 - p) ** gamma * log(p) has a zero derivative at p = 1, so saturated entries take
+ # the factor's value from a detached copy and pass no gradient through it.
+ base = 1.0 - log_pred_soft.exp()
+ saturated = base == 0
+ focal_weight = torch.where(saturated, base.detach().pow(gamma), base.masked_fill(saturated, 1.0).pow(gamma))
+ loss_tmp: torch.Tensor = -focal_weight * log_pred_soft * target_one_hot
num_of_classes = pred.shape[1]
broadcast_dims = [-1] + [1] * len(pred.shape[2:])
diff --git a/tests/losses/test_focal_loss.py b/tests/losses/test_focal_loss.py
index 00b7f9eb3..b3cce1af6 100644
--- a/tests/losses/test_focal_loss.py
+++ b/tests/losses/test_focal_loss.py
@@ -215,6 +215,40 @@ class TestFocalLoss(BaseTester):
assert (grad[0] == 0).all()
self.assert_close(grad, torch.autograd.grad(expected, safe_logits)[0])
+ @pytest.mark.parametrize("gamma", [0.0, 0.25, 0.5, 0.75, 1.0, 2.0])
+ @pytest.mark.parametrize("alpha", [None, 0.25])
+ @pytest.mark.parametrize("reduction", ["none", "mean", "sum"])
+ def test_saturated_logits_backward(self, device, dtype, gamma, alpha, reduction):
+ # Row 0 is saturated on its target class, row 1 on a wrong class.
+ logits = torch.tensor([[1000.0, 0.0, 0.0], [0.0, 1000.0, 0.0]], device=device, dtype=dtype, requires_grad=True)
+ labels = torch.tensor([0, 0], device=device)
+ # Every probability rounds to 0 or 1: (1 - p) ** gamma is 1 where p = 0 and multiplies log(p) = 0 where p = 1,
+ # so the loss and its gradient reduce to the gamma = 0 ones, which have no singularity.
+ cross_entropy_logits = logits.detach().clone().requires_grad_()
+ expected = kornia.losses.focal_loss(cross_entropy_logits, labels, alpha, 0.0, reduction)
+ expected_grad = torch.autograd.grad(expected.sum(), cross_entropy_logits)[0]
+ if reduction == "sum":
+ # A correct saturated prediction costs nothing and a wrong one its logit gap.
+ self.assert_close(
+ expected, torch.tensor(1000.0 * (1.0 - alpha if alpha else 1.0), device=device, dtype=dtype)
+ )
+
+ actual = kornia.losses.focal_loss(logits, labels, alpha, gamma, reduction)
+ self.assert_close(actual, expected)
+ # detect_anomaly also rejects a NaN inside the backward that torch.where would discard, so this pins the safe
+ # base of the unselected branch and not only the final gradient.
+ with torch.autograd.detect_anomaly():
+ grad = torch.autograd.grad(actual.sum(), logits)[0]
+ self.assert_close(grad, expected_grad)
+
+ @pytest.mark.parametrize("gamma", [0.5, 2.0])
+ def test_dynamo_saturated_logits(self, device, dtype, torch_optimizer, gamma):
+ logits = torch.tensor([[1000.0, 0.0, 0.0], [0.0, 1000.0, 0.0]], device=device, dtype=dtype)
+ labels = torch.tensor([0, 0], device=device)
+ op = kornia.losses.focal_loss
+ op_optimized = torch_optimizer(op)
+ self.assert_close(op_optimized(logits, labels, 0.25, gamma), op(logits, labels, 0.25, gamma))
+
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)