Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Fix numerical stability for binary focal loss (#2125)

Boris Zimkafdb5d39bfd03
diff --git a/kornia/losses/focal.py b/kornia/losses/focal.py
index e37b39c5f..cc6209588 100644
--- a/kornia/losses/focal.py
+++ b/kornia/losses/focal.py
@@ -212,9 +212,12 @@ def binary_focal_loss_with_logits(
probs_pos = input.sigmoid()
probs_neg = (-input).sigmoid()
+ log_probs_pos = nn.functional.logsigmoid(input)
+ log_probs_neg = nn.functional.logsigmoid(-input)
+
loss_tmp = (
- -alpha * pos_weight * probs_neg.pow(gamma) * target * probs_pos.log()
- - (1 - alpha) * probs_pos.pow(gamma) * (1.0 - target) * probs_neg.log()
+ -alpha * pos_weight * probs_neg.pow(gamma) * target * log_probs_pos
+ - (1 - alpha) * probs_pos.pow(gamma) * (1.0 - target) * log_probs_neg
)
if reduction == 'none':
diff --git a/test/losses/test_losses.py b/test/losses/test_losses.py
index dee30646f..42346c2e1 100644
--- a/test/losses/test_losses.py
+++ b/test/losses/test_losses.py
@@ -99,6 +99,15 @@ class TestBinaryFocalLossWithLogits:
logits, labels, **kwargs
) == kornia.losses.BinaryFocalLossWithLogits(**kwargs)(logits, labels)
+ def test_numeric_stability(self, device, dtype):
+ logits = torch.tensor([[100.0, -100]], dtype=dtype, device=device)
+ labels = torch.tensor([[1.0, 0.0]], dtype=dtype, device=device)
+ expected = torch.tensor([[0.0, 0.0]], dtype=dtype, device=device)
+
+ kwargs = {"alpha": 0.25, "gamma": 2.0, "reduction": 'none'}
+ actual = kornia.losses.binary_focal_loss_with_logits(logits, labels, **kwargs)
+ assert_close(actual, expected, atol=1e-3, rtol=1e-3)
+
class TestFocalLoss:
def test_smoke_none(self, device, dtype):