Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(losses): compute Tversky scores per target-present class (#5594)

Puttala Jeevan Kumarfaaa02ec882b
diff --git a/changelog.d/5594.breaking.md b/changelog.d/5594.breaking.md
new file mode 100644
index 000000000..6f84da792
--- /dev/null
+++ b/changelog.d/5594.breaking.md
@@ -0,0 +1,9 @@
+`tversky_loss` and `TverskyLoss` now compute true positives, false positives and
+false negatives per class and average over classes present in each sample's
+non-ignored target. Previously, pooling across classes made false-positive and
+false-negative mass equal, so `alpha` and `beta` acted only through their sum.
+Coefficient splits with the same sum now give different losses; `alpha=beta=0.5`
+corresponds to macro Dice with exact targets and twice the denominator epsilon,
+rather than micro Dice. Fully ignored samples retain loss 1 and zero gradients.
+Half-precision inputs use float32 through softmax and the ratio to keep gradients
+finite for saturated predictions, while the returned loss keeps the input dtype.
diff --git a/kornia/losses/tversky.py b/kornia/losses/tversky.py
index 7ea8914f8..099828019 100644
--- a/kornia/losses/tversky.py
+++ b/kornia/losses/tversky.py
@@ -24,6 +24,7 @@ import torch.nn.functional as F
from torch import nn
from kornia.losses._utils import mask_ignore_pixels
+from kornia.losses.one_hot import one_hot
# based on:
# https://github.com/kevinzakka/pytorch-goodies/blob/master/losses.py
@@ -47,15 +48,19 @@ def tversky_loss(
\frac{|PG|}{|PG| + \alpha |P \setminus G| + \beta |G \setminus P|}
Where:
- - :math:`P` and :math:`G` are the predicted and ground truth binary
- labels.
+ - :math:`P` and :math:`G` are the softmax probabilities and exact one-hot
+ targets for each class, restricted to non-ignored pixels.
- :math:`\alpha` and :math:`\beta` control the magnitude of the
penalties for FPs and FNs, respectively.
Note:
- - :math:`\alpha = \beta = 0.5` => dice coeff
- - :math:`\alpha = \beta = 1` => tanimoto coeff
- - :math:`\alpha + \beta = 1` => F beta coeff
+ - Scores are computed per class and averaged over classes present in each
+ sample's non-ignored target, then over samples. Fully ignored samples have loss 1.
+ - :math:`\alpha = \beta = 0.5` corresponds to macro Dice with exact targets
+ and a denominator epsilon of :math:`2\,\text{eps}` in the Dice formula.
+ - :math:`\alpha = \beta = 1` corresponds to the per-class Tanimoto coefficient.
+ - For :math:`\alpha + \beta = 1` and :math:`\alpha > 0`, the unsmoothed
+ per-class score is :math:`F_{\sqrt{\beta / \alpha}}`.
Args:
pred: logits tensor with shape :math:`(N, C, H, W)` where C = number of classes.
@@ -70,9 +75,9 @@ def tversky_loss(
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.
+ Softmax, spatial reductions and the ratio use float32 for float16 and
+ bfloat16 inputs to avoid overflow in large-image sums and ratio gradients.
+ The returned loss retains the input dtype.
Example:
>>> N = 5 # num_classes
@@ -97,33 +102,27 @@ def tversky_loss(
if not (pred.shape[0] == target.shape[0] and pred.shape[2:] == target.shape[1:]):
raise ValueError(f"Expected target size {torch.Size((pred.shape[0], *pred.shape[2:]))}, got {target.shape}")
- # compute softmax over the classes axis
- pred_soft = F.softmax(pred, dim=1)
+ # Keep the ratio's backward pass in float32 through softmax for half inputs.
+ reduction_dtype = torch.float32 if pred.dtype in (torch.float16, torch.bfloat16) else pred.dtype
+ pred_soft = F.softmax(pred, dim=1, dtype=reduction_dtype)
target, target_mask = mask_ignore_pixels(target, ignore_index)
- 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
+ target_one_hot = one_hot(target, pred.shape[1], device=pred.device, dtype=reduction_dtype, eps=0.0)
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), dtype=reduction_dtype)
- else:
- B, _, H, W = pred.shape
- total = torch.full((B,), H * W, dtype=reduction_dtype, device=pred.device)
-
- 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(
- intersection, # base
- total - intersection, # tensor1
- torch.full_like(total, alpha + beta), # tensor2 (scalar as tensor)
- value=1.0, # (intersection) + 1 * (tensor1*tensor2)
- ).add_(eps) # in-place add eps
- score = intersection.div(denominator)
+ mask = target_mask.unsqueeze(1)
+ pred_soft = pred_soft * mask
+ target_one_hot = target_one_hot * mask
+
+ dims = (2, 3)
+ tp = (pred_soft * target_one_hot).sum(dims)
+ fp = (pred_soft * (1.0 - target_one_hot)).sum(dims)
+ fn = ((1.0 - pred_soft) * target_one_hot).sum(dims)
+ present = target_one_hot.sum(dims) > 0
+ denominator = tp + alpha * fp + beta * fn + eps
+ # Absent classes do not enter the mean; avoid undefined ratios even when eps is zero.
+ score = (tp / denominator.masked_fill(~present, 1.0)).masked_fill(~present, 0.0)
+ score = score.sum(-1) / present.sum(-1).clamp_min(1)
return (1.0 - score.mean()).to(pred.dtype)
@@ -139,15 +138,19 @@ class TverskyLoss(nn.Module):
\frac{|PG|}{|PG| + \alpha |P \setminus G| + \beta |G \setminus P|}
Where:
- - :math:`P` and :math:`G` are the predicted and ground truth binary
- labels.
+ - :math:`P` and :math:`G` are the softmax probabilities and exact one-hot
+ targets for each class, restricted to non-ignored pixels.
- :math:`\alpha` and :math:`\beta` control the magnitude of the
penalties for FPs and FNs, respectively.
Note:
- - :math:`\alpha = \beta = 0.5` => dice coeff
- - :math:`\alpha = \beta = 1` => tanimoto coeff
- - :math:`\alpha + \beta = 1` => F beta coeff
+ - Scores are computed per class and averaged over classes present in each
+ sample's non-ignored target, then over samples. Fully ignored samples have loss 1.
+ - :math:`\alpha = \beta = 0.5` corresponds to macro Dice with exact targets
+ and a denominator epsilon of :math:`2\,\text{eps}` in the Dice formula.
+ - :math:`\alpha = \beta = 1` corresponds to the per-class Tanimoto coefficient.
+ - For :math:`\alpha + \beta = 1` and :math:`\alpha > 0`, the unsmoothed
+ per-class score is :math:`F_{\sqrt{\beta / \alpha}}`.
Args:
alpha: the first coefficient in the denominator.
diff --git a/tests/losses/test_tversky.py b/tests/losses/test_tversky.py
index 5bc758e0b..119e7a819 100644
--- a/tests/losses/test_tversky.py
+++ b/tests/losses/test_tversky.py
@@ -24,6 +24,123 @@ from testing.base import BaseTester
class TestTverskyLoss(BaseTester):
+ def test_per_class_issue_5543(self, device):
+ # The issue's CPU-seeded fixture; all classes are present in each sample.
+ generator = torch.Generator().manual_seed(1206)
+ logits = torch.randn(2, 3, 4, 6, dtype=torch.float64, generator=generator) * 2
+ labels = torch.randint(0, 3, (2, 4, 6), generator=generator)
+ labels[1, :, :2] = 2
+ logits, labels = logits.to(device=device, dtype=torch.float32), labels.to(device)
+ # Exact one-hot, spatial-only TP / (TP + alpha FP + beta FN + 1e-8).
+ expected = (0.6015094950, 0.5990951811, 0.6037325821)
+ for (alpha, beta), value in zip(((0.3, 0.7), (0.7, 0.3), (0.5, 0.5)), expected):
+ loss = kornia.losses.tversky_loss(logits, labels, alpha, beta)
+ self.assert_close(loss, logits.new_tensor(value), rtol=0, atol=1e-7)
+
+ @pytest.mark.parametrize("alpha,beta", [(0.3, 0.7), (0.7, 0.3), (0.5, 0.5), (1.0, 1.0)])
+ @pytest.mark.parametrize("eps", [0.0, 0.25])
+ def test_target_presence_per_sample(self, device, dtype, alpha, beta, eps):
+ probabilities = torch.tensor(
+ [
+ [[[0.5, 0.25, 0.125, 0.5]], [[0.25, 0.5, 0.125, 0.25]], [[0.25, 0.25, 0.75, 0.25]]],
+ [[[0.5, 0.25, 0.5, 0.25]], [[0.25, 0.5, 0.25, 0.5]], [[0.25, 0.25, 0.25, 0.25]]],
+ ],
+ device=device,
+ dtype=dtype,
+ )
+ labels = torch.tensor([[[0, 1, 1, 0]], [[2, 2, 2, 2]]], device=device)
+ # Sample 0: (TP, FP, FN) = (1, 3/8, 1), (5/8, 1/2, 11/8).
+ # Sample 1: (1, 0, 3). Absent classes can win argmax but are not averaged in.
+ score_0 = 1 / (1 + alpha * 0.375 + beta + eps)
+ score_1 = 0.625 / (0.625 + alpha * 0.5 + beta * 1.375 + eps)
+ score_2 = 1 / (1 + beta * 3 + eps)
+ expected = 1 - ((score_0 + score_1) / 2 + score_2) / 2
+ loss = kornia.losses.tversky_loss(probabilities.log(), labels, alpha, beta, eps=eps)
+ assert loss.dtype == dtype
+ assert loss.device == device
+ self.assert_close(loss, probabilities.new_tensor(expected))
+
+ def test_absent_channels(self, device, dtype):
+ labels = torch.tensor([[[0, 1, 1, 0]]], device=device)
+ losses = []
+ for num_classes in (2, 3, 4):
+ logits = torch.full((1, num_classes, 1, 4), -40.0, device=device, dtype=dtype)
+ # Imperfect predictions, unchanged when negligible unused channels are added.
+ logits[:, :2] = torch.tensor([[[[2.0, 0.0, 1.0, 2.0]], [[0.0, 2.0, 2.0, 0.0]]]], device=device)
+ losses.append(kornia.losses.tversky_loss(logits, labels, 0.3, 0.7))
+ for loss in losses[1:]:
+ self.assert_close(loss, losses[0], rtol=0, atol=1e-7)
+
+ @pytest.mark.parametrize("alpha,beta", [(0.3, 0.7), (1.0, 0.0), (0.0, 1.0)])
+ def test_present_class_without_correct_predictions(self, device, dtype, alpha, beta):
+ logits = torch.tensor([[[[100.0, 100.0]], [[-100.0, -100.0]], [[-100.0, -100.0]]]], device=device)
+ logits = logits.to(dtype).requires_grad_()
+ labels = torch.tensor([[[0, 1]]], device=device)
+ loss = kornia.losses.tversky_loss(logits, labels, alpha, beta)
+ # Class 0: TP=1, FP=1, FN=0. Class 1: TP=0, FP=0, FN=1; its loss stays 1.
+ self.assert_close(loss, logits.new_tensor(1 - (1 / (1 + alpha)) / 2))
+ loss.backward()
+ assert torch.isfinite(logits.grad).all()
+
+ def test_exact_target_rare_class(self, device, dtype):
+ labels = torch.zeros((1, 128, 192), device=device, dtype=torch.int64)
+ labels[0, 0, 0] = 1
+ logits = torch.full((1, 3, 128, 192), -40.0, device=device, dtype=dtype)
+ logits.scatter_(1, labels[:, None], 40.0).requires_grad_()
+ loss = kornia.losses.tversky_loss(logits, labels, 0.3, 0.7)
+ # An epsilon floor in off-class target entries gives the rare class spurious FN mass.
+ self.assert_close(loss, torch.zeros_like(loss), rtol=0, atol=1e-7)
+ loss.backward()
+ assert torch.isfinite(logits.grad).all()
+
+ @pytest.mark.parametrize("eps", [0.0, 0.25])
+ def test_macro_dice_correspondence(self, device, dtype, eps):
+ logits = (torch.arange(18, device=device, dtype=dtype).reshape(2, 3, 1, 3) / 4).requires_grad_()
+ labels = torch.tensor([[[0, 1, 1]], [[2, 2, -100]]], device=device)
+ probabilities = logits.to(torch.float64 if dtype == torch.float64 else torch.float32).softmax(1)
+ # Independent macro Dice over each sample's actual labels, as required by #5539.
+ # Tversky's eps becomes 2*eps when the Dice numerator/denominator are doubled.
+ sample_losses = []
+ for sample, classes in enumerate(((0, 1), (2,))):
+ class_losses = []
+ valid = labels[sample] != -100
+ for label in classes:
+ pred = probabilities[sample, label] * valid
+ target = (labels[sample] == label).to(pred.dtype)
+ class_losses.append(1 - 2 * (pred * target).sum() / ((pred + target).sum() + 2 * eps))
+ sample_losses.append(torch.stack(class_losses).mean())
+ expected = torch.stack(sample_losses).mean().to(dtype)
+ actual = kornia.losses.tversky_loss(logits, labels, 0.5, 0.5, eps=eps)
+ self.assert_close(actual, expected)
+ actual_grad = torch.autograd.grad(actual, logits, retain_graph=True)[0]
+ expected_grad = torch.autograd.grad(expected, logits)[0]
+ assert torch.isfinite(actual_grad).all()
+ self.assert_close(actual_grad, expected_grad)
+
+ @pytest.mark.parametrize("ignore_index", [-100, 0, 255])
+ @pytest.mark.parametrize("eps", [0.0, 1e-8])
+ def test_ignored_samples(self, device, dtype, ignore_index, eps):
+ logits = torch.zeros((2, 3, 1, 2), device=device, dtype=dtype, requires_grad=True)
+ labels = torch.tensor([[[1, ignore_index]], [[ignore_index, ignore_index]]], device=device)
+ kwargs = {"alpha": 0.3, "beta": 0.7, "eps": eps, "ignore_index": ignore_index}
+ loss = kornia.losses.tversky_loss(logits, labels, **kwargs)
+ # Valid sample: TP=1/3, FP=0, FN=2/3. Fully ignored sample: score=0, loss=1.
+ self.assert_close(loss, logits.new_tensor(1 - (1 / 2.4) / 2))
+ empty_loss = kornia.losses.tversky_loss(logits[1:], labels[1:], **kwargs)
+ self.assert_close(empty_loss, logits.new_tensor(1.0), rtol=0, atol=0)
+ loss.backward()
+ assert torch.isfinite(logits.grad).all()
+ self.assert_close(logits.grad[1], torch.zeros_like(logits.grad[1]), rtol=0, atol=0)
+ self.assert_close(logits.grad[0, :, :, 1], torch.zeros_like(logits.grad[0, :, :, 1]), rtol=0, atol=0)
+ assert torch.count_nonzero(logits.grad[0, :, :, 0]) > 0
+
+ def test_absent_and_ignored_gradcheck(self, device):
+ logits = torch.arange(12, device=device, dtype=torch.float64).reshape(2, 3, 1, 2) / 4
+ labels = torch.tensor([[[1, -100]], [[-100, -100]]], device=device)
+ self.gradcheck(
+ kornia.losses.tversky_loss, (logits, labels, 0.3, 0.7), dtypes=[torch.float64, torch.int64, None, None]
+ )
+
@pytest.mark.parametrize(
"size,ignore_index,ignored_rows",
[(256, None, 0), (256, -100, 0), (512, -100, 8)],
@@ -65,15 +182,17 @@ class TestTverskyLoss(BaseTester):
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.
+ # Half of the pixels have a logit gap of 20 and half a gap of 6, so the loss is about 6e-4 to 1e-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)
+ reduction_dtype = torch.float64 if dtype == torch.float64 else torch.float32
+ p_true = logits.to(reduction_dtype).softmax(dim=1)[:, 0].cpu().double()
+ # Only class 0 is present: TP=sum(p_true), FP=0, FN=N-TP.
+ expected = 1.0 - p_true.sum() / (p_true.sum() + 0.5 * (p_true.numel() - p_true.sum()) + 1e-8)
actual = kornia.losses.tversky_loss(logits, labels, alpha=0.5, beta=0.5)
assert actual.dtype == dtype
@@ -141,7 +260,8 @@ class TestTverskyLoss(BaseTester):
labels = torch.zeros(2, 1, 4, device=device, dtype=torch.int64)
labels[..., 2:] = ignore_index
- expected_loss = torch.tensor([1.0 / 2.0], device=device, dtype=dtype).squeeze()
+ # Only class 0 is present, with TP=1, FP=0, FN=1 after masking.
+ expected_loss = torch.tensor([1.0 / 3.0], device=device, dtype=dtype).squeeze()
criterion = kornia.losses.TverskyLoss(alpha=0.5, beta=0.5, ignore_index=ignore_index)
loss = criterion(logits, labels)
self.assert_close(loss, expected_loss, rtol=1e-3, atol=1e-3)
@@ -158,13 +278,18 @@ class TestTverskyLoss(BaseTester):
kornia.losses.tversky_loss, (logits, labels, alpha, beta), dtypes=[torch.float64, torch.int64, None, None]
)
- def test_dynamo(self, device, dtype, torch_optimizer):
+ @pytest.mark.parametrize("ignored_sample", [False, True])
+ def test_dynamo(self, device, dtype, torch_optimizer, ignored_sample):
num_classes = 3
params = (0.5, 0.05)
logits = torch.rand(2, num_classes, 3, 2, device=device, dtype=dtype)
labels = torch.rand(2, 3, 2) * num_classes
labels = labels.to(device).long()
+ if ignored_sample:
+ labels[0, :, 0] = -100
+ labels[1] = -100
+
op = kornia.losses.tversky_loss
op_optimized = torch_optimizer(op)
@@ -174,10 +299,12 @@ class TestTverskyLoss(BaseTester):
def test_module(self, device, dtype):
num_classes = 3
- params = (0.5, 0.5)
+ params = (0.3, 0.7, 0.25, -100)
logits = torch.rand(2, num_classes, 3, 2, device=device, dtype=dtype)
labels = torch.rand(2, 3, 2) * num_classes
labels = labels.to(device).long()
+ labels[0, :, 0] = -100
+ labels[1] = -100
op = kornia.losses.tversky_loss
op_module = kornia.losses.TverskyLoss(*params)