🐍 Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(losses): weight the dice_loss micro intersection once (#5564)
Aditya17-bot130b95b8f135
diff --git a/changelog.d/5564.breaking.md b/changelog.d/5564.breaking.mdnew file mode 100644index 000000000..0150b2bf8--- /dev/null+++ b/changelog.d/5564.breaking.md@@ -0,0 +1 @@+`dice_loss(average="micro", weight=w)` and `DiceLoss(weight=w)` now weight the intersection once, computing the weighted Dice `2 Σ w p t / Σ w (p + t)`. They used to square the weight in the intersection, so a uniform weight scaled the Dice coefficient (a perfect prediction scored -1 with `weight=2`) and non-uniform weights could push the loss below -1. Weighted `"micro"` losses with weights other than 0 and 1 change value. Unweighted, 0/1-weighted and `"macro"` losses are unchanged.diff --git a/docs/source/get-started/precision.rst b/docs/source/get-started/precision.rstindex 6bf5f2ed4..d15a348ef 100644--- a/docs/source/get-started/precision.rst+++ b/docs/source/get-started/precision.rst@@ -127,10 +127,9 @@ precision, so the table says nothing about those backends.* - ``kornia.losses``- ⚠️ Partial- ⚠️ Partial- - 3 / 4+ - 3 / 3- Dice averaging overflows to inf/NaN in float16; the mutual-information range check fails in both- dtypes; bfloat16 Dice weighting and total variation miss accuracy. Hausdorff and the photometric losses- pass.+ dtypes; bfloat16 total variation misses accuracy. Hausdorff and the photometric losses pass.* - ``kornia.feature``- ✅ Yes- ✅ Yesdiff --git a/kornia/losses/dice.py b/kornia/losses/dice.pyindex e896bb041..73bec048d 100644--- a/kornia/losses/dice.py+++ b/kornia/losses/dice.py@@ -138,6 +138,9 @@ def dice_loss(# set dimensions for the appropriate averagingdims: tuple[int, ...] = (2, 3)+ # The weighted micro Dice is 2 sum(w p t) / sum(w (p + t)): the weight enters the intersection once, through the+ # weighted scores, so the intersection pairs them with the unweighted target.+ intersection_target = target_one_hotif average == "micro":dims = (1, *dims)@@ -147,7 +150,7 @@ def dice_loss(# Half-precision pixel counts can overflow before the Dice ratio is formed.reduction_dtype = torch.float32 if pred_soft.dtype in (torch.float16, torch.bfloat16) else pred_soft.dtype- intersection = torch.sum(pred_soft * target_one_hot, dims, dtype=reduction_dtype)+ intersection = torch.sum(pred_soft * intersection_target, dims, dtype=reduction_dtype)cardinality = torch.sum(pred_soft + target_one_hot, dims, dtype=reduction_dtype)dice_score = 2.0 * intersection / (cardinality + eps)diff --git a/testing/half_precision_xfails/cpu_bfloat16.txt b/testing/half_precision_xfails/cpu_bfloat16.txtindex 35f015ecf..1e6f72dee 100644--- a/testing/half_precision_xfails/cpu_bfloat16.txt+++ b/testing/half_precision_xfails/cpu_bfloat16.txt@@ -442,7 +442,6 @@ call builtins.AssertionError tests/integration/test_conversions.py::TestQuaternicall builtins.AssertionError tests/integration/test_conversions.py::TestQuaternionToRotationMatrixToAngleAxis::test_triplet_qma[cpu-bfloat16-0]call builtins.AssertionError tests/integration/test_conversions.py::TestQuaternionToRotationMatrixToAngleAxis::test_triplet_qma[cpu-bfloat16-1]call builtins.AssertionError tests/integration/test_conversions.py::TestQuaternionToRotationMatrixToAngleAxis::test_triplet_qma[cpu-bfloat16-2]-call builtins.AssertionError tests/losses/test_dice.py::TestDiceLoss::test_weight[cpu-bfloat16-micro]call builtins.AssertionError tests/losses/test_mutual_information.py::TestMutualInformationLoss::test_value_ranges[cpu-bfloat16]call builtins.AssertionError tests/losses/test_total_variation.py::TestTotalVariation::test_tv_on_3d[cpu-bfloat16-pred0-expected0]call builtins.AssertionError tests/losses/test_total_variation.py::TestTotalVariation::test_tv_on_4d[cpu-bfloat16-pred0-expected0]diff --git a/tests/losses/test_dice.py b/tests/losses/test_dice.pyindex 2a34c8843..05dd246c7 100644--- a/tests/losses/test_dice.py+++ b/tests/losses/test_dice.py@@ -172,7 +172,7 @@ class TestDiceLoss(BaseTester):(1- 2- * (w_cl_0 * tp_cl_0 + w_cl_1 * tp_cl_1) ** 2+ * (w_cl_0 * tp_cl_0 + w_cl_1 * tp_cl_1)/ (w_cl_0 * (2 * tp_cl_0 + fnfp_cl_0) + w_cl_1 * (2 * tp_cl_1 + fnfp_cl_1) + eps)).mean()@@ -184,6 +184,40 @@ class TestDiceLoss(BaseTester):loss = criterion(logits, labels)self.assert_close(loss, expected_loss, rtol=1e-3, atol=1e-3)+ @pytest.mark.parametrize("avg", ["micro", "macro"])+ @pytest.mark.parametrize("scale", [0.5, 2.0])+ def test_uniform_weight(self, device, dtype, avg, scale):+ num_classes = 3+ logits = torch.randn(2, num_classes, 4, 6, device=device, dtype=dtype)+ labels = torch.randint(num_classes, (2, 4, 6), device=device)+ weight = torch.full((num_classes,), scale, device=device, dtype=dtype)+ expected = kornia.losses.dice_loss(logits, labels, average=avg)+ self.assert_close(kornia.losses.dice_loss(logits, labels, average=avg, weight=weight), expected)++ # a perfect prediction has zero loss whatever the scale of the weights+ perfect = torch.full_like(logits, -30.0).scatter(1, labels[:, None], 30.0)+ loss = kornia.losses.dice_loss(perfect, labels, average=avg, weight=weight)+ self.assert_close(loss, torch.zeros_like(loss), rtol=1e-3, atol=1e-3)++ def test_weight_micro_formula(self, device, dtype):+ num_classes = 3+ eps = 1e-8+ logits = torch.randn(2, num_classes, 4, 6, device=device, dtype=dtype)+ labels = torch.randint(num_classes, (2, 4, 6), device=device)+ weight = torch.tensor([1.0, 2.0, 3.0], device=device, dtype=dtype)++ # weighted Dice per sample: 2 sum(w p t) / sum(w (p + t)), summed over classes and pixels+ probs = logits.softmax(1)+ targets = torch.nn.functional.one_hot(labels, num_classes).permute(0, 3, 1, 2).to(dtype)+ w = weight.view(1, -1, 1, 1)+ intersection = (w * probs * targets).sum((1, 2, 3))+ cardinality = (w * (probs + targets)).sum((1, 2, 3))+ expected = (1.0 - 2.0 * intersection / (cardinality + eps)).mean()++ loss = kornia.losses.dice_loss(logits, labels, average="micro", eps=eps, weight=weight)+ self.assert_close(loss, expected)+ assert 0.0 <= loss.item() <= 1.0+def test_averaging_macro(self, device, dtype):num_classes = 2eps = 1e-8