Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(losses): keep the Lovasz Jaccard weights in the prediction dtype and return it (#5303)

εŒΊζ’“ηe16f36e63908
diff --git a/changelog.d/5303.breaking.md b/changelog.d/5303.breaking.md
new file mode 100644
index 000000000..448fba423
--- /dev/null
+++ b/changelog.d/5303.breaking.md
@@ -0,0 +1,8 @@
+`lovasz_softmax_loss`, `LovaszSoftmaxLoss`, `lovasz_hinge_loss` and `LovaszHingeLoss` now compute the Jaccard
+weights and the sum over pixels in the dtype of the prediction, or in float32 for a float16 or bfloat16 prediction,
+and return the loss in the dtype of the prediction, promoted with the dtype of `weight` for the softmax variant
+(#5289). Previously the Jaccard weights took `torch.get_default_dtype()`: a float16 or bfloat16 prediction returned a
+float32 loss, a float32 prediction under a float64 default returned float64, and a float64 prediction had float32
+rounding in its weights and gradient. A `weight` wider than the loss was cast down to it, so a float32 prediction
+with a float64 `weight` returned float32; it now returns float64, as `dice_loss` does. Float32 predictions with no
+`weight` or a float32 `weight` under the default float32 are unchanged.
diff --git a/kornia/losses/lovasz_hinge.py b/kornia/losses/lovasz_hinge.py
index 6b88c80e4..5fc87f427 100644
--- a/kornia/losses/lovasz_hinge.py
+++ b/kornia/losses/lovasz_hinge.py
@@ -60,7 +60,9 @@ def lovasz_hinge_loss(pred: Tensor, target: Tensor) -> Tensor:
target: labels tensor with shape :math:`(N, H, W)` with binary values.
Return:
- a scalar with the computed loss.
+ a scalar with the computed loss, in the dtype of a floating-point ``pred`` and in float32 for an
+ integer or bool ``pred``. The Jaccard weights and the sum over pixels are computed in float32 for a
+ float16 or bfloat16 ``pred``.
Example:
>>> N = 1 # num_classes
@@ -81,8 +83,11 @@ def lovasz_hinge_loss(pred: Tensor, target: Tensor) -> Tensor:
raise ValueError(f"pred and target must be in the same device. Got: {pred.device} and {target.device}")
# flatten pred and target [B, -1] and to float
+ # The labels, the Jaccard weights and the sum over pixels are accumulated in the prediction dtype, or in float32
+ # for a half-precision prediction, where pixel counts stay exact up to 2**24 pixels.
+ accumulation_dtype = torch.promote_types(pred.dtype, torch.float32)
pred_flatten: Tensor = pred.reshape(pred.shape[0], -1)
- target_flatten: Tensor = target.reshape(target.shape[0], -1)
+ target_flatten: Tensor = target.reshape(target.shape[0], -1).to(accumulation_dtype)
# get shapes
B, N = pred_flatten.shape
@@ -101,7 +106,8 @@ def lovasz_hinge_loss(pred: Tensor, target: Tensor) -> Tensor:
if N > 1:
gradient[..., 1:] = gradient[..., 1:] - gradient[..., :-1]
loss: Tensor = (errors_sorted.relu() * gradient).sum(1).mean()
- return loss
+ # an integer or bool pred keeps the float32 loss instead of truncating it
+ return loss.to(pred.dtype if pred.is_floating_point() else accumulation_dtype)
class LovaszHingeLoss(nn.Module):
@@ -138,7 +144,9 @@ class LovaszHingeLoss(nn.Module):
labels: labels tensor with shape :math:`(N, H, W)` with binary values.
Return:
- a scalar with the computed loss.
+ a scalar with the computed loss, in the dtype of a floating-point ``pred`` and in float32 for an
+ integer or bool ``pred``. The Jaccard weights and the sum over pixels are computed in float32 for a
+ float16 or bfloat16 ``pred``.
Example:
>>> N = 1 # num_classes
diff --git a/kornia/losses/lovasz_softmax.py b/kornia/losses/lovasz_softmax.py
index a126a3301..a5b3c1ae2 100644
--- a/kornia/losses/lovasz_softmax.py
+++ b/kornia/losses/lovasz_softmax.py
@@ -63,7 +63,8 @@ def lovasz_softmax_loss(pred: Tensor, target: Tensor, weight: Optional[Tensor] =
weight: weights for classes with shape :math:`(num\_of\_classes,)`.
Return:
- a scalar with the computed loss.
+ a scalar with the computed loss, in the dtype of ``pred`` promoted with the dtype of ``weight``.
+ The Jaccard weights and the sum over pixels are computed in float32 for a float16 or bfloat16 ``pred``.
Example:
>>> N = 5 # num_classes
@@ -116,8 +117,10 @@ def lovasz_softmax_loss(pred: Tensor, target: Tensor, weight: Optional[Tensor] =
errors: Tensor = (pred_soft - foreground).abs()
errors_sorted, permutations = torch.sort(errors, dim=2, descending=True)
# The Jaccard gradient uses the foreground indicator for each class, not the class labels.
- # Keep pixel counts integral, including for large half-precision images.
- target_sorted = foreground.gather(2, permutations).to(torch.int64)
+ # Pixel counts, the Jaccard weights and the sum over pixels are accumulated in the prediction dtype, or in
+ # float32 for a half-precision prediction, where counts stay exact up to 2**24 pixels.
+ accumulation_dtype = torch.promote_types(pred.dtype, torch.float32)
+ target_sorted = foreground.gather(2, permutations).to(accumulation_dtype)
target_sorted_sum = target_sorted.sum(2, keepdim=True)
intersection = target_sorted_sum - target_sorted.cumsum(2)
union = target_sorted_sum + (1.0 - target_sorted).cumsum(2)
@@ -126,10 +129,12 @@ def lovasz_softmax_loss(pred: Tensor, target: Tensor, weight: Optional[Tensor] =
gradient[..., 1:] = gradient[..., 1:] - gradient[..., :-1]
weighted_errors = errors_sorted * gradient
loss_per_class = weighted_errors.sum(2).mean(0)
+ output_dtype = pred.dtype
if weight is not None:
- loss_per_class *= weight
+ loss_per_class = loss_per_class * weight
+ output_dtype = torch.promote_types(output_dtype, weight.dtype)
final_loss: Tensor = loss_per_class.mean()
- return final_loss
+ return final_loss.to(output_dtype)
class LovaszSoftmaxLoss(nn.Module):
@@ -167,7 +172,8 @@ class LovaszSoftmaxLoss(nn.Module):
weight: weights for classes with shape :math:`(num\_of\_classes,)`.
Return:
- a scalar with the computed loss.
+ a scalar with the computed loss, in the dtype of ``pred`` promoted with the dtype of ``weight``.
+ The Jaccard weights and the sum over pixels are computed in float32 for a float16 or bfloat16 ``pred``.
Example:
>>> N = 5 # num_classes
diff --git a/tests/losses/test_lovaz_hinge.py b/tests/losses/test_lovaz_hinge.py
index 6a98c83dd..6cc9df39b 100644
--- a/tests/losses/test_lovaz_hinge.py
+++ b/tests/losses/test_lovaz_hinge.py
@@ -23,6 +23,34 @@ import kornia
from testing.base import BaseTester
+def _lovasz_grad_reference(foreground_sorted):
+ """Berman's lovasz_grad in float64, with the counts kept as Python integers (foreground_sorted holds 0. and 1.)."""
+ total = int(foreground_sorted.sum().item())
+ seen_foreground = seen_background = 0
+ jaccard = []
+ for value in foreground_sorted.tolist():
+ if value:
+ seen_foreground += 1
+ else:
+ seen_background += 1
+ jaccard.append(1.0 - (total - seen_foreground) / (total + seen_background))
+ out = torch.tensor(jaccard, dtype=torch.float64)
+ out[1:] = out[1:] - out[:-1]
+ return out
+
+
+def _lovasz_hinge_reference(logits, labels):
+ """kornia's reduction of Berman's per-image Lovasz hinge, evaluated in float64 one sample at a time."""
+ logits = logits.double()
+ loss = torch.zeros((), dtype=torch.float64)
+ for b in range(logits.shape[0]):
+ target = labels[b].double().flatten()
+ errors = (1.0 - logits[b].flatten() * (2.0 * target - 1.0)).relu()
+ errors_sorted, permutation = errors.sort(descending=True)
+ loss = loss + errors_sorted.dot(_lovasz_grad_reference(target[permutation])) / logits.shape[0]
+ return loss
+
+
class TestLovaszHingeLoss(BaseTester):
def test_smoke(self, device, dtype):
num_classes = 1
@@ -63,6 +91,65 @@ class TestLovaszHingeLoss(BaseTester):
loss = criterion(prediction, labels)
self.assert_close(loss, torch.zeros_like(loss), rtol=1e-3, atol=1e-3)
+ def test_output_dtype_follows_the_prediction(self, device, dtype):
+ logits = torch.randn(2, 1, 4, 5, device=device, dtype=dtype)
+ labels = torch.randint(0, 2, (2, 4, 5), device=device)
+ assert kornia.losses.lovasz_hinge_loss(logits, labels).dtype == dtype
+ assert kornia.losses.LovaszHingeLoss()(logits, labels).dtype == dtype
+
+ def test_default_dtype_does_not_change_the_loss(self, device, dtype):
+ logits = torch.randn(2, 1, 4, 5, device=device, dtype=dtype)
+ labels = torch.randint(0, 2, (2, 4, 5), device=device)
+ expected = kornia.losses.lovasz_hinge_loss(logits, labels)
+ original = torch.get_default_dtype()
+ try:
+ torch.set_default_dtype(torch.float32 if original == torch.float64 else torch.float64)
+ loss = kornia.losses.lovasz_hinge_loss(logits, labels)
+ finally:
+ torch.set_default_dtype(original)
+ assert loss.dtype == dtype
+ self.assert_close(loss, expected)
+
+ def test_float64_matches_a_float64_reference(self, device):
+ if device.type == "mps":
+ pytest.skip("MPS does not support float64")
+ torch.manual_seed(0)
+ logits = torch.randn(2, 1, 16, 24, device=device, dtype=torch.float64, requires_grad=True)
+ labels = torch.randint(0, 2, (2, 16, 24), device=device)
+ reference_logits = logits.detach().cpu().clone().requires_grad_()
+ expected = _lovasz_hinge_reference(reference_logits, labels.cpu())
+ expected_grad = torch.autograd.grad(expected, reference_logits)[0]
+ loss = kornia.losses.lovasz_hinge_loss(logits, labels)
+ # the Jaccard weights are exact in float64: only the summation order differs from the reference
+ self.assert_close(loss, expected.to(device), rtol=1e-12, atol=1e-12)
+ self.assert_close(torch.autograd.grad(loss, logits)[0], expected_grad.to(device), rtol=1e-12, atol=1e-15)
+
+ def test_large_foreground_counts(self, device, dtype):
+ # More than 65504 foreground pixels exceed float16's finite range, and cumulative counts above 256 (bfloat16)
+ # or 2048 (float16) are not exact in half precision.
+ logits = torch.zeros((1, 1, 257, 257), device=device, dtype=dtype, requires_grad=True)
+ labels = torch.ones((1, 257, 257), device=device, dtype=torch.int64)
+ loss = kornia.losses.lovasz_hinge_loss(logits, labels)
+ # every error is 1 and the Jaccard weights sum to the last Jaccard index, 1
+ self.assert_close(loss, torch.tensor(1.0, device=device, dtype=dtype))
+ assert torch.isfinite(torch.autograd.grad(loss, logits)[0]).all()
+
+ @pytest.mark.parametrize(
+ "logits, expected",
+ [
+ # errors 1 - logit * sign: [-1, 0, 1, -2]; sorted labels [0, 0, 1, 1] weigh them by [1/3, 1/6, 1/4, 1/4]
+ ([[2, -1], [0, 3]], 1 / 3),
+ # errors [0, 1, 1, 0]: the two errors of 1 take the weights 1/3 and 1/6
+ ([[True, False], [False, True]], 1 / 2),
+ ],
+ )
+ def test_integer_logits_return_a_float_loss(self, device, logits, expected):
+ logits = torch.tensor([[logits]], device=device)
+ labels = torch.tensor([[[1, 0], [0, 1]]], device=device)
+ loss = kornia.losses.lovasz_hinge_loss(logits, labels)
+ assert loss.dtype == torch.float32
+ self.assert_close(loss, torch.tensor(expected, device=device))
+
def test_gradcheck(self, device, dtype):
dtype = torch.float64
num_classes = 1
diff --git a/tests/losses/test_lovaz_softmax.py b/tests/losses/test_lovaz_softmax.py
index d947c4d79..9895f660b 100644
--- a/tests/losses/test_lovaz_softmax.py
+++ b/tests/losses/test_lovaz_softmax.py
@@ -23,6 +23,38 @@ import kornia
from testing.base import BaseTester
+def _lovasz_grad_reference(foreground_sorted):
+ """Berman's lovasz_grad in float64, with the counts kept as Python integers (foreground_sorted holds 0. and 1.)."""
+ total = int(foreground_sorted.sum().item())
+ seen_foreground = seen_background = 0
+ jaccard = []
+ for value in foreground_sorted.tolist():
+ if value:
+ seen_foreground += 1
+ else:
+ seen_background += 1
+ jaccard.append(1.0 - (total - seen_foreground) / (total + seen_background))
+ out = torch.tensor(jaccard, dtype=torch.float64)
+ out[1:] = out[1:] - out[:-1]
+ return out
+
+
+def _lovasz_softmax_reference(logits, labels, weight=None):
+ """kornia's reduction of Berman's per-image Lovasz-Softmax, evaluated in float64 one sample and class at a time."""
+ probabilities = logits.double().softmax(1)
+ B, C = probabilities.shape[:2]
+ per_class = torch.zeros(C, dtype=torch.float64)
+ for b in range(B):
+ for c in range(C):
+ foreground = (labels[b] == c).double().flatten()
+ errors = (foreground - probabilities[b, c].flatten()).abs()
+ errors_sorted, permutation = errors.sort(descending=True)
+ per_class[c] = per_class[c] + errors_sorted.dot(_lovasz_grad_reference(foreground[permutation])) / B
+ if weight is not None:
+ per_class = per_class * weight.double()
+ return per_class.mean()
+
+
class TestLovaszSoftmaxLoss(BaseTester):
def test_smoke(self, device, dtype):
num_classes = 3
@@ -180,6 +212,46 @@ class TestLovaszSoftmaxLoss(BaseTester):
self.assert_close(loss.to(dtype), torch.tensor(4 / 9, device=device, dtype=dtype))
assert torch.isfinite(torch.autograd.grad(loss, logits)[0]).all()
+ def test_output_dtype_follows_the_prediction(self, device, dtype):
+ logits = torch.randn(2, 3, 4, 5, device=device, dtype=dtype)
+ labels = torch.randint(0, 3, (2, 4, 5), device=device)
+ weight = torch.tensor([1.0, 2.0, 3.0], device=device, dtype=dtype)
+ assert kornia.losses.lovasz_softmax_loss(logits, labels).dtype == dtype
+ assert kornia.losses.lovasz_softmax_loss(logits, labels, weight).dtype == dtype
+ assert kornia.losses.LovaszSoftmaxLoss(weight)(logits, labels).dtype == dtype
+ # the weight dtype is promoted into the output, as in dice_loss
+ promoted = torch.promote_types(dtype, torch.float32)
+ assert kornia.losses.lovasz_softmax_loss(logits, labels, weight.float()).dtype == promoted
+
+ def test_default_dtype_does_not_change_the_loss(self, device, dtype):
+ logits = torch.randn(2, 3, 4, 5, device=device, dtype=dtype)
+ labels = torch.randint(0, 3, (2, 4, 5), device=device)
+ expected = kornia.losses.lovasz_softmax_loss(logits, labels)
+ original = torch.get_default_dtype()
+ try:
+ torch.set_default_dtype(torch.float32 if original == torch.float64 else torch.float64)
+ loss = kornia.losses.lovasz_softmax_loss(logits, labels)
+ finally:
+ torch.set_default_dtype(original)
+ assert loss.dtype == dtype
+ self.assert_close(loss, expected)
+
+ @pytest.mark.parametrize("weighted", [False, True])
+ def test_float64_matches_a_float64_reference(self, device, weighted):
+ if device.type == "mps":
+ pytest.skip("MPS does not support float64")
+ torch.manual_seed(0)
+ logits = torch.randn(2, 3, 16, 24, device=device, dtype=torch.float64, requires_grad=True)
+ labels = torch.randint(0, 3, (2, 16, 24), device=device)
+ weight = torch.tensor([1.0, 2.0, 3.0], device=device, dtype=torch.float64) if weighted else None
+ reference_logits = logits.detach().cpu().clone().requires_grad_()
+ expected = _lovasz_softmax_reference(reference_logits, labels.cpu(), None if weight is None else weight.cpu())
+ expected_grad = torch.autograd.grad(expected, reference_logits)[0]
+ loss = kornia.losses.lovasz_softmax_loss(logits, labels, weight)
+ # the Jaccard weights are exact in float64: only the summation order differs from the reference
+ self.assert_close(loss, expected.to(device), rtol=1e-12, atol=1e-12)
+ self.assert_close(torch.autograd.grad(loss, logits)[0], expected_grad.to(device), rtol=1e-12, atol=1e-15)
+
def test_gradcheck(self, device, dtype):
num_classes = 4
logits = torch.rand(2, num_classes, 3, 2, device=device, dtype=torch.float64)