Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(losses): prevent half-precision overflow in Tversky loss (#5129)

El Mehdi TAFIKe3866b72e4f9
diff --git a/changelog.d/5129.fixed.md b/changelog.d/5129.fixed.md
new file mode 100644
index 000000000..5e32235c4
--- /dev/null
+++ b/changelog.d/5129.fixed.md
@@ -0,0 +1,4 @@
+`tversky_loss` and `TverskyLoss` sum float16 and bfloat16 inputs over the image in float32, form the ratio there and
+return the loss in the input dtype. In float16 a pixel count above 65504 used to overflow, so the loss came back as 1.0
+from 256 Γ— 256 pixels on, or NaN with `ignore_index` pixels; in bfloat16 a loss below about 4e-3 was rounded to a
+multiple of 2**-8.
diff --git a/kornia/losses/tversky.py b/kornia/losses/tversky.py
index 0e8a7f863..dded3f1ce 100644
--- a/kornia/losses/tversky.py
+++ b/kornia/losses/tversky.py
@@ -69,6 +69,11 @@ def tversky_loss(
Return:
the computed loss.
+ Note:
+ Spatial reductions and the ratio use float32 for float16 and bfloat16
+ inputs to avoid overflow on large images. The returned loss retains
+ the input dtype.
+
Example:
>>> N = 5 # num_classes
>>> pred = torch.randn(1, N, 3, 5, requires_grad=True)
@@ -95,15 +100,18 @@ def tversky_loss(
p_true = pred_soft.gather(1, target.unsqueeze(1)) # (B,1,H,W)
+ # Half-precision pixel counts can overflow before the ratio is formed.
+ reduction_dtype = torch.float32 if pred.dtype in (torch.float16, torch.bfloat16) else pred.dtype
+
if target_mask is not None:
m = target_mask.unsqueeze(1).to(dtype=pred.dtype)
p_true = p_true * m
- total = m.sum((1, 2, 3))
+ total = m.sum((1, 2, 3), dtype=reduction_dtype)
else:
B, _, H, W = pred.shape
- total = torch.full((B,), H * W, dtype=pred.dtype, device=pred.device)
+ total = torch.full((B,), H * W, dtype=reduction_dtype, device=pred.device)
- intersection = p_true.sum((1, 2, 3))
+ intersection = p_true.sum((1, 2, 3), dtype=reduction_dtype)
# denominator = intersection + (alpha + beta) * (total - intersection) + eps
# instead of multiple ops, do it in one fused step:
denominator = torch.addcmul(
@@ -114,7 +122,7 @@ def tversky_loss(
).add_(eps) # in-place add eps
score = intersection.div(denominator)
- return 1.0 - score.mean()
+ return (1.0 - score.mean()).to(pred.dtype)
class TverskyLoss(nn.Module):
diff --git a/tests/losses/test_tversky.py b/tests/losses/test_tversky.py
index 5a9880887..9d7f57484 100644
--- a/tests/losses/test_tversky.py
+++ b/tests/losses/test_tversky.py
@@ -24,6 +24,61 @@ from testing.base import BaseTester
class TestTverskyLoss(BaseTester):
+ @pytest.mark.parametrize(
+ "size,ignore_index,ignored_rows",
+ [(256, None, 0), (256, -100, 0), (512, -100, 8)],
+ )
+ def test_large_image_half_precision(self, device, dtype, size, ignore_index, ignored_rows):
+ logits = torch.full((1, 2, size, size), -2.0, device=device, dtype=dtype)
+ logits[:, 0] = 2.0
+ logits.requires_grad_()
+ labels = torch.zeros((1, size, size), device=device, dtype=torch.int64)
+ if ignored_rows:
+ labels[:, :ignored_rows] = ignore_index
+
+ # Use a reference dtype that can represent the spatial sums.
+ reference_dtype = torch.float64 if dtype == torch.float64 else torch.float32
+ expected = kornia.losses.tversky_loss(
+ logits.detach().to(reference_dtype),
+ labels,
+ alpha=0.5,
+ beta=0.5,
+ ignore_index=ignore_index,
+ )
+ actual = kornia.losses.tversky_loss(
+ logits,
+ labels,
+ alpha=0.5,
+ beta=0.5,
+ ignore_index=ignore_index,
+ )
+
+ assert actual.dtype == dtype
+ assert actual.device == logits.device
+ assert torch.isfinite(actual)
+ self.assert_close(actual, expected.to(dtype))
+
+ actual.backward()
+ assert logits.grad is not None
+ assert torch.isfinite(logits.grad).all()
+ if ignored_rows:
+ assert torch.count_nonzero(logits.grad[:, :, :ignored_rows]) == 0
+
+ def test_small_loss_ratio_in_float32(self, device, dtype):
+ # Half of the pixels have a logit gap of 20 and half a gap of 6, so the loss is about 1e-3 to 2e-3.
+ # A ratio formed in bfloat16 has a step of 2**-8 near 1 and returns 0 or 2**-8 instead.
+ logits = torch.zeros(1, 2, 128, 128, device=device, dtype=dtype)
+ logits[:, 0, :, ::2] = 20.0
+ logits[:, 0, :, 1::2] = 6.0
+ labels = torch.zeros(1, 128, 128, device=device, dtype=torch.int64)
+
+ p_true = logits.softmax(dim=1)[:, 0].cpu().double()
+ expected = 1.0 - p_true.sum() / (p_true.numel() + 1e-8)
+ actual = kornia.losses.tversky_loss(logits, labels, alpha=0.5, beta=0.5)
+
+ assert actual.dtype == dtype
+ self.assert_close(actual.cpu().double(), expected, rtol=1e-2, atol=1e-6)
+
def test_smoke(self, device, dtype):
num_classes = 3
logits = torch.rand(2, num_classes, 3, 2, device=device, dtype=dtype)