π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(losses): avoid NaN focal loss for non-target overflow (#5642)
Puttala Jeevan Kumaraba5f7dac073
diff --git a/changelog.d/5642.fixed.md b/changelog.d/5642.fixed.mdnew file mode 100644index 000000000..1bec9ac11--- /dev/null+++ b/changelog.d/5642.fixed.md@@ -0,0 +1 @@+`focal_loss` no longer produces NaN losses or gradients from overflowing non-target log probabilities.diff --git a/kornia/losses/focal.py b/kornia/losses/focal.pyindex 3c9fecab5..495f227c9 100644--- a/kornia/losses/focal.py+++ b/kornia/losses/focal.py@@ -60,9 +60,9 @@ def focal_loss(logit difference ``pred[:, 1:] - pred[:, :1]`` and the target ``target[:, None]``, with the same ``alpha``and ``gamma``: class 1 is the positive class.- The default ``reduction='none'`` returns a ``(B, C, *)`` map whose target slice holds the focal term above- and whose other slices are 0 where their log-probability is finite. ``'mean'`` divides its sum by every- element of that map, ``C`` times the pixel count, so with ``gamma=0`` and ``alpha=None`` it is the mean- cross entropy divided by ``C``.+ and whose other slices are 0, also where their log-probability overflows to ``-inf``. ``'mean'`` divides+ its sum by every element of that map, ``C`` times the pixel count, so with ``gamma=0`` and ``alpha=None``+ it is the mean cross entropy divided by ``C``.- ``weight`` multiplies the slice of class ``c`` by ``weight[c]``; ``'mean'`` is not normalised by theweights.- A pixel labelled ``ignore_index`` (default ``-100``) is 0 in every slice and still counts in the ``'mean'``@@ -70,9 +70,6 @@ def focal_loss(:ref:`Losses and metrics <losses-metrics-conventions>` ports:func:`~torch.nn.functional.cross_entropy` to this loss.- ``alpha`` outside ``[0, 1]`` and a negative ``gamma`` are not validated.- - Known defect: a non-target class whose log-probability overflows to ``-inf``, at a logit gap beyond the- range of the dtype (about 65504 in float16), turns its slice, the reduced loss and the gradient of that- pixel's logits into NaN (`#5628 <https://github.com/kornia/kornia/issues/5628>`_).Args:pred: logits torch.Tensor with shape :math:`(N, C, *)` where C = number of classes.@@ -134,6 +131,8 @@ def focal_loss(base = 1.0 - log_pred_soft.exp()saturated = base == 0focal_weight = torch.where(saturated, base.detach().pow(gamma), base.masked_fill(saturated, 1.0).pow(gamma))+ # Mask before multiplying: a non-target log probability of -inf otherwise gives NaN values and gradients.+ log_pred_soft = log_pred_soft.masked_fill(target_one_hot == 0, 0.0)loss_tmp: torch.Tensor = -focal_weight * log_pred_soft * target_one_hotnum_of_classes = pred.shape[1]diff --git a/tests/losses/test_focal_loss.py b/tests/losses/test_focal_loss.pyindex 6e29f37f2..ea49df07f 100644--- a/tests/losses/test_focal_loss.py+++ b/tests/losses/test_focal_loss.py@@ -170,6 +170,65 @@ class TestBinaryFocalLossWithLogits(BaseTester):class TestFocalLoss(BaseTester):+ @pytest.mark.parametrize("reduction", ["none", "mean", "sum"])+ @pytest.mark.parametrize("gamma", [0.0, 0.5, 2.0])+ @pytest.mark.parametrize("alpha", [None, 0.25])+ @pytest.mark.parametrize("weighted", [False, True])+ def test_overflowing_non_target_log_probability_5628(self, device, dtype, reduction, gamma, alpha, weighted):+ # Exact float16/float32 reproducers from #5628; exercise the same overflow in the other dtypes too.+ big = {torch.float16: 40000.0, torch.float32: 3e38}.get(dtype, 0.75 * torch.finfo(dtype).max)+ logits = torch.tensor([[big, -big, 0.0], [1.0, 2.0, 3.0]], device=device, dtype=dtype, requires_grad=True)+ labels = torch.tensor([0, 2], device=device)+ assert logits.isfinite().all()+ assert logits.log_softmax(1)[0, 1].isneginf()+ weight = torch.tensor([0.5, 1.5, 2.0], device=device, dtype=dtype) if weighted else None+ # A finite logit gap gives the same saturated probabilities, without overflowing log-softmax.+ control = torch.tensor(+ [[10000.0, -10000.0, 0.0], [1.0, 2.0, 3.0]], device=device, dtype=dtype, requires_grad=True+ )+ expected = kornia.losses.focal_loss(control, labels, alpha, gamma, reduction, weight)+ expected_grad = torch.autograd.grad(expected.sum(), control)[0]+ actual = kornia.losses.focal_loss(logits, labels, alpha, gamma, reduction, weight)+ assert actual.isfinite().all()+ self.assert_close(actual, expected, rtol=0, atol=0)+ grad = torch.autograd.grad(actual.sum(), logits)[0]+ assert grad.isfinite().all()+ self.assert_close(grad[0], torch.zeros_like(grad[0]), rtol=0, atol=0)+ self.assert_close(grad[1], expected_grad[1])+ if reduction == "none":+ self.assert_close(actual[0], torch.zeros_like(actual[0]), rtol=0, atol=0)++ @pytest.mark.parametrize("reduction", ["none", "mean", "sum"])+ @pytest.mark.parametrize("gamma", [0.0, 0.5, 2.0])+ @pytest.mark.parametrize("alpha", [None, 0.25])+ @pytest.mark.parametrize("weighted", [False, True])+ def test_finite_loss_and_gradient(self, device, dtype, reduction, gamma, alpha, weighted):+ logits = torch.tensor(+ [[[1.0, -0.5], [2.0, 0.3], [3.0, 1.5]], [[-1.0, 0.2], [0.5, -0.7], [0.0, 1.0]]],+ device=device,+ dtype=dtype,+ requires_grad=True,+ )+ labels = torch.tensor([[2, 0], [1, 2]], device=device)+ weight = torch.tensor([0.5, 1.5, 2.0], device=device, dtype=dtype) if weighted else None+ # Original finite-input formula, before masking non-target log probabilities.+ reference = logits.detach().clone().requires_grad_()+ logp = reference.log_softmax(1)+ expected = -(1.0 - logp.exp()).pow(gamma) * logp * F.one_hot(labels, 3).movedim(-1, 1).to(dtype)+ if alpha is not None:+ expected = torch.tensor([1.0 - alpha, alpha, alpha], device=device, dtype=dtype).view(3, 1) * expected+ if weight is not None:+ expected = weight.view(3, 1) * expected+ if reduction == "mean":+ expected = expected.mean()+ elif reduction == "sum":+ expected = expected.sum()+ actual = kornia.losses.focal_loss(logits, labels, alpha, gamma, reduction, weight)+ self.assert_close(actual, expected, rtol=0, atol=0)+ self.assert_close(+ torch.autograd.grad(actual.sum(), logits)[0], torch.autograd.grad(expected.sum(), reference)[0]+ )+@pytest.mark.parametrize("reduction", ["none", "mean", "sum"])@pytest.mark.parametrize("gamma", [0.0, 2.0])@pytest.mark.parametrize("weighted", [False, True])@@ -538,20 +597,22 @@ class TestConventionsFocalLoss(BaseTester):)self.assert_close(actual, expected.to(device=device, dtype=dtype))- def test_wart_focal_loss_overflowing_non_target_log_probability_5628(self, device, dtype):- # A logit gap beyond the range of the dtype overflows a non-target log-probability to -inf, and its term times- # the exact zero of the one-hot target is 0 * -inf = NaN (#5628): that slice, the reduced loss and the gradient- # of that pixel's logits are NaN, while the target slice is 0 and the other pixel stays finite+ def test_convention_focal_loss_overflowing_non_target_log_probability_5628(self, device, dtype):+ # A logit gap beyond the range of the dtype overflows a non-target log-probability to -inf; its slice is still+ # 0 (#5628). The pixel is classified with probability 1, so its loss and its logits' gradient are 0, as for+ # F.cross_entropy, and the other pixel keeps the value it has on its own.big = 0.75 * torch.finfo(dtype).maxlogits = torch.tensor([[[[big, 1.0]], [[-big, -0.5]], [[0.0, 0.3]]]], device=device, dtype=dtype)logits.requires_grad_()labels = torch.zeros(1, 1, 2, device=device, dtype=torch.long)+ assert logits.log_softmax(1)[0, 1, 0, 0].isneginf()out = kornia.losses.focal_loss(logits, labels, None)- assert out[0, 1, 0, 0].isnan()- assert out[0, 0, 0, 0] == 0- assert out[0, :, 0, 1].isfinite().all()+ self.assert_close(out[..., 0], torch.zeros_like(out[..., 0]), rtol=0, atol=0)+ rest = logits[..., 1:].detach().clone().requires_grad_()+ rest_total = kornia.losses.focal_loss(rest, labels[..., 1:], None, reduction="sum")+ self.assert_close(out[..., 1:], kornia.losses.focal_loss(rest, labels[..., 1:], None))total = kornia.losses.focal_loss(logits, labels, None, reduction="sum")- assert total.isnan()+ self.assert_close(total, rest_total)(grad,) = torch.autograd.grad(total, logits)- assert grad[..., 0].isnan().all()- assert grad[..., 1].isfinite().all()+ self.assert_close(grad[..., 0], torch.zeros_like(grad[..., 0]), rtol=0, atol=0)+ self.assert_close(grad[..., 1:], torch.autograd.grad(rest_total, rest)[0])