Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(losses): return the exact one-hot in the requested dtype from one_hot, with eps 0 by default (#5571)

εŒΊζ’“η08502b04e99f
diff --git a/changelog.d/5571.breaking.md b/changelog.d/5571.breaking.md
new file mode 100644
index 000000000..6ffb9e4d3
--- /dev/null
+++ b/changelog.d/5571.breaking.md
@@ -0,0 +1,9 @@
+`kornia.losses.one_hot` now returns the exact one-hot tensor in the requested `dtype`: `eps` defaults to 0 and is
+applied only when it is non-zero, and a non-zero `eps` with an integer or bool `dtype` raises (#5538). Previously
+every zero was `eps = 1e-6`, each pixel summed to `1 + (C - 1) * eps`, and an integer or bool `dtype` came back as
+float32. `dice_loss` and `focal_loss` build their targets with it, so their values lose the eps terms: the macro
+Dice loss of a perfect prediction of a 256 Γ— 384 image with a one-pixel class is now 0 instead of 0.0234, and the
+non-target entries of `focal_loss(reduction='none')` are 0 instead of `1e-6` times the class term. Code that takes
+a log of the output of `one_hot` now needs its own floor, or can pass `eps` explicitly. `dice_loss` builds its
+target in float32 for float16 and bfloat16 input, so the float16 gradient of a class absent from a sample stays
+finite without the floor, including on the few-pixel images where it was NaN before.
diff --git a/kornia/losses/dice.py b/kornia/losses/dice.py
index 73bec048d..76c7da46d 100644
--- a/kornia/losses/dice.py
+++ b/kornia/losses/dice.py
@@ -110,8 +110,11 @@ def dice_loss(
target, target_mask = mask_ignore_pixels(target, ignore_index)
- # create the labels one hot torch.Tensor
- target_one_hot: torch.Tensor = one_hot(target, num_classes=pred.shape[1], device=pred.device, dtype=pred.dtype)
+ # create the labels one hot torch.Tensor. A half-precision target is built in float32, the dtype of the sums below:
+ # the intersection gradient of a class absent from the target is 2 / (cardinality + eps) up to the averaging, past
+ # the float16 range once that class's probabilities underflow, and float16 inf times the zero target is NaN.
+ target_dtype = torch.float32 if pred.dtype in (torch.float16, torch.bfloat16) else pred.dtype
+ target_one_hot: torch.Tensor = one_hot(target, num_classes=pred.shape[1], device=pred.device, dtype=target_dtype)
# mask ignore pixels
if target_mask is not None:
diff --git a/kornia/losses/one_hot.py b/kornia/losses/one_hot.py
index e260a1bd9..a184f12ab 100644
--- a/kornia/losses/one_hot.py
+++ b/kornia/losses/one_hot.py
@@ -22,7 +22,7 @@ from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR
def one_hot(
- labels: torch.Tensor, num_classes: int, device: torch.device, dtype: torch.dtype, eps: float = 1e-6
+ labels: torch.Tensor, num_classes: int, device: torch.device, dtype: torch.dtype, eps: float = 0.0
) -> torch.Tensor:
r"""Convert an integer label x-D torch.Tensor to a one-hot (x+1)-D torch.Tensor.
@@ -32,7 +32,8 @@ def one_hot(
num_classes: number of classes in labels.
device: the desired device of returned torch.Tensor.
dtype: the desired data type of returned torch.Tensor.
- eps: epsilon for numerical stability.
+ eps: optional smoothing floor. The default 0 returns the exact one-hot. A non-zero value replaces the
+ zeros with ``eps`` and keeps the ones, which needs a floating point ``dtype``.
Returns:
the labels in one hot torch.Tensor of shape :math:`(N, C, *)`,
@@ -40,19 +41,20 @@ def one_hot(
Examples:
>>> labels = torch.LongTensor([[[0, 1], [2, 0]]])
>>> one_hot(labels, num_classes=3, device=torch.device('cpu'), dtype=torch.float32)
- tensor([[[[1.0000e+00, 1.0000e-06],
- [1.0000e-06, 1.0000e+00]],
+ tensor([[[[1., 0.],
+ [0., 1.]],
<BLANKLINE>
- [[1.0000e-06, 1.0000e+00],
- [1.0000e-06, 1.0000e-06]],
+ [[0., 1.],
+ [0., 0.]],
<BLANKLINE>
- [[1.0000e-06, 1.0000e-06],
- [1.0000e+00, 1.0000e-06]]]])
+ [[0., 0.],
+ [1., 0.]]]])
"""
KORNIA_CHECK_IS_TENSOR(labels, "Input labels must be a torch.Tensor")
KORNIA_CHECK(labels.dtype == torch.int64, f"labels must be of dtype torch.int64. Got: {labels.dtype}")
KORNIA_CHECK(num_classes >= 1, f"The number of classes must be >= 1. Got: {num_classes}")
+ KORNIA_CHECK(eps == 0 or dtype.is_floating_point, f"A non-zero eps needs a floating point dtype. Got: {dtype}")
# Use PyTorch's built-in one_hot function
one_hot_tensor = F.one_hot(labels, num_classes=num_classes)
@@ -64,8 +66,9 @@ def one_hot(
permute_dims = [0] + [ndim] + list(range(1, ndim))
one_hot_tensor = one_hot_tensor.permute(*permute_dims)
- # Convert to desired dtype and device, then apply eps for numerical stability
one_hot_tensor = one_hot_tensor.to(dtype=dtype, device=device)
+ if eps == 0:
+ return one_hot_tensor
- # Apply eps: multiply by (1-eps) and add eps to all elements
+ # Optional smoothing floor: the zeros become eps and the ones stay 1
return one_hot_tensor * (1.0 - eps) + eps
diff --git a/tests/losses/test_dice.py b/tests/losses/test_dice.py
index 05dd246c7..f89e15027 100644
--- a/tests/losses/test_dice.py
+++ b/tests/losses/test_dice.py
@@ -81,6 +81,30 @@ class TestDiceLoss(BaseTester):
loss = criterion(logits, labels)
self.assert_close(loss, torch.zeros_like(loss), rtol=1e-3, atol=1e-3)
+ def test_perfect_prediction_of_a_rare_class(self, device, dtype):
+ # The target is an exact one-hot, so a perfect prediction scores 0 whatever the image size. The former
+ # eps floor of the target gave the one-pixel class a cardinality of 1 + eps * (pixels - 1), 0.006 here.
+ labels = torch.zeros(1, 128, 192, device=device, dtype=torch.int64)
+ labels[0, 10, 10] = 1
+ logits = torch.full((1, 2, 128, 192), -30.0, device=device, dtype=dtype).scatter(1, labels[:, None], 30.0)
+
+ loss = kornia.losses.dice_loss(logits, labels, average="macro")
+
+ self.assert_close(loss, torch.zeros_like(loss))
+
+ def test_gradient_of_an_absent_class_is_finite(self, device, dtype):
+ # Class 2 is absent from the target and its probabilities underflow, so its cardinality is eps alone and its
+ # intersection gradient is far past the float16 range. Times the exact zero target, that must not give NaN.
+ labels = torch.zeros(1, 16, 16, device=device, dtype=torch.int64)
+ labels[0, :, 8:] = 1
+ logits = torch.full((1, 3, 16, 16), -10.0, device=device, dtype=dtype).scatter(1, labels[:, None], 10.0)
+ logits.requires_grad_(True)
+
+ loss = kornia.losses.dice_loss(logits, labels, average="macro")
+ (grad,) = torch.autograd.grad(loss, logits)
+
+ assert grad.isfinite().all()
+
def test_exception(self):
with pytest.raises(ValueError) as errinf:
kornia.losses.DiceLoss()(torch.rand(1, 1, 1), torch.rand(1, 1, 1))
diff --git a/tests/losses/test_focal_loss.py b/tests/losses/test_focal_loss.py
index b3cce1af6..19d336d86 100644
--- a/tests/losses/test_focal_loss.py
+++ b/tests/losses/test_focal_loss.py
@@ -330,6 +330,18 @@ class TestFocalLoss(BaseTester):
self.assert_close(actual_values, expected_values)
+ def test_value_non_target_classes_are_zero(self, device, dtype):
+ # The target is an exact one-hot, so the per-class values of a pixel are 0 off its class.
+ num_classes = 3
+ logits = torch.rand(2, num_classes, 3, 2, device=device, dtype=dtype)
+ labels = torch.randint(num_classes, (2, 3, 2), device=device)
+
+ values = kornia.losses.focal_loss(logits, labels, alpha=0.5, gamma=2.0, reduction="none")
+
+ off_class = F.one_hot(labels, num_classes).movedim(-1, 1) == 0
+ self.assert_close(values[off_class], torch.zeros_like(values[off_class]), rtol=0, atol=0)
+ assert (values[~off_class] > 0).all()
+
def test_dynamo(self, device, dtype, torch_optimizer):
num_classes = 3
logits = torch.rand(2, num_classes, device=device, dtype=dtype)
diff --git a/tests/losses/test_one_hot.py b/tests/losses/test_one_hot.py
index d58fd3e20..b78cd267d 100644
--- a/tests/losses/test_one_hot.py
+++ b/tests/losses/test_one_hot.py
@@ -15,8 +15,11 @@
# limitations under the License.
#
+import pytest
import torch
+import torch.nn.functional as F
+from kornia.core.exceptions import BaseError
from kornia.losses.one_hot import one_hot
from testing.base import assert_close
@@ -38,3 +41,36 @@ class TestOneHot:
assert_close(one_hot_tensor[0, labels[0, 1, 0], 1, 0].item(), 1.0)
assert_close(one_hot_tensor[1, labels[1, 0, 0], 0, 0].item(), 1.0)
assert_close(one_hot_tensor[1, labels[1, 1, 0], 1, 0].item(), 1.0)
+
+ def test_exact_values(self, device, dtype):
+ labels = torch.tensor([[[0, 2, 1], [1, 0, 0]]], device=device)
+ expected = F.one_hot(labels, 3).movedim(-1, 1).to(dtype)
+
+ one_hot_tensor = one_hot(labels, 3, device, dtype)
+
+ assert one_hot_tensor.dtype == dtype
+ assert_close(one_hot_tensor, expected, rtol=0, atol=0)
+ assert_close(one_hot_tensor.sum(1), torch.ones_like(expected[:, 0]), rtol=0, atol=0)
+
+ @pytest.mark.parametrize("dtype", [torch.int64, torch.uint8, torch.bool])
+ def test_integer_dtypes(self, device, dtype):
+ labels = torch.tensor([[[0, 2, 1], [1, 0, 0]]], device=device)
+
+ one_hot_tensor = one_hot(labels, 3, device, dtype)
+
+ assert one_hot_tensor.dtype == dtype
+ assert torch.equal(one_hot_tensor, F.one_hot(labels, 3).movedim(-1, 1).to(dtype))
+
+ def test_eps_smoothing(self, device, dtype):
+ labels = torch.tensor([[[0, 2, 1], [1, 0, 0]]], device=device)
+ exact = F.one_hot(labels, 3).movedim(-1, 1).to(dtype)
+
+ one_hot_tensor = one_hot(labels, 3, device, dtype, eps=0.125)
+
+ assert_close(one_hot_tensor, torch.where(exact == 1, 1.0, 0.125).to(dtype))
+
+ def test_exception_eps_with_integer_dtype(self, device):
+ labels = torch.tensor([[0, 1]], device=device)
+
+ with pytest.raises(BaseError, match="floating point dtype"):
+ one_hot(labels, 2, device, torch.int64, eps=1e-6)