Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

test(losses): keep half-precision Dice averaging references finite (#5844)

peng xiang2476f20b8cfe
diff --git a/README.md b/README.md
index 4184f793c..eef8715e0 100644
--- a/README.md
+++ b/README.md
@@ -109,7 +109,7 @@ covers CUDA or MPS half precision.
| `kornia.geometry.ransac` | ⚠️ | ⚠️ | 4 / 4 | The essential and fundamental models raise through the epipolar solvers |
| `kornia.geometry` (other) | ⚠️ | ⚠️ | 8 / 17 | Accuracy in boxes, depth and line utilities; bfloat16 `NamedPose` construction raises |
| `kornia.image` | ⚠️ | ⚠️ | 4 / 4 | `draw_convex_polygon` fill accuracy |
-| `kornia.losses` | ⚠️ | ⚠️ | 2 / 2 | Dice averaging overflows to inf/NaN in float16; bfloat16 total variation; mutual information passes |
+| `kornia.losses` | ✅ | ⚠️ | 0 / 2 | Mutual information and Dice averaging pass; bfloat16 total variation accuracy |
| `kornia.feature` | ✅ | ✅ | 0 / 0 | Matching uses a manual `cdist` fallback for half dtypes; LightGlue's float16 tests are skipped, so that path is unmeasured |
| `kornia.metrics` | ✅ | ⚠️ | 0 / 1 | bfloat16: `ssim3d` accuracy |
| `kornia.models` | ✅ | ⚠️ | 0 / 1 | bfloat16 RT-DETR RepVGG fusion accuracy |
diff --git a/changelog.d/5844.fixed.md b/changelog.d/5844.fixed.md
new file mode 100644
index 000000000..84dd97c2f
--- /dev/null
+++ b/changelog.d/5844.fixed.md
@@ -0,0 +1 @@
+The README and precision-guide half-precision tables no longer say that `dice_loss` averaging overflows in float16: the overflow was in the float16 reference value of its tests, not in the library.
diff --git a/docs/source/get-started/precision.rst b/docs/source/get-started/precision.rst
index 05a9050fb..1f12b6b08 100644
--- a/docs/source/get-started/precision.rst
+++ b/docs/source/get-started/precision.rst
@@ -127,11 +127,11 @@ precision, so the table says nothing about those backends.
own; the vertices are used as given, already rounded to half precision. The circle and ellipse tests still
miss because they compute their vertices and their reference mask in half precision.
* - ``kornia.losses``
+ - ✅ Yes
- ⚠️ Partial
- - ⚠️ Partial
- - 2 / 2
- - Dice averaging overflows to inf/NaN in float16; bfloat16 total variation misses accuracy.
- Mutual information, Hausdorff and the photometric losses pass.
+ - 0 / 2
+ - Mutual information, Dice averaging, Hausdorff and the photometric losses pass.
+ bfloat16 total variation misses accuracy.
* - ``kornia.feature``
- ✅ Yes
- ✅ Yes
diff --git a/testing/half_precision_xfails/cpu_float16.txt b/testing/half_precision_xfails/cpu_float16.txt
index 984c969fe..c0351b942 100644
--- a/testing/half_precision_xfails/cpu_float16.txt
+++ b/testing/half_precision_xfails/cpu_float16.txt
@@ -271,5 +271,3 @@ call builtins.AssertionError tests/integration/test_conversions.py::TestQuaterni
call builtins.AssertionError tests/integration/test_conversions.py::TestQuaternionToRotationMatrixToAngleAxis::test_triplet_qma[cpu-float16-0]
call builtins.AssertionError tests/integration/test_conversions.py::TestQuaternionToRotationMatrixToAngleAxis::test_triplet_qma[cpu-float16-1]
call builtins.AssertionError tests/integration/test_conversions.py::TestQuaternionToRotationMatrixToAngleAxis::test_triplet_qma[cpu-float16-2]
-call builtins.AssertionError tests/losses/test_dice.py::TestDiceLoss::test_averaging_macro[cpu-float16]
-call builtins.AssertionError tests/losses/test_dice.py::TestDiceLoss::test_averaging_micro[cpu-float16]
diff --git a/tests/losses/test_dice.py b/tests/losses/test_dice.py
index 7946ed509..6db7f2452 100644
--- a/tests/losses/test_dice.py
+++ b/tests/losses/test_dice.py
@@ -294,6 +294,7 @@ class TestDiceLoss(BaseTester):
kornia.losses.DiceLoss()(torch.rand(1, 3, 4, 6), torch.randint(0, 3, (1, 1, 4, 6)))
def test_averaging_micro(self, device, dtype):
+ """Keep the analytical micro-averaging reference finite in half precision."""
num_classes = 2
eps = 1e-8
@@ -305,16 +306,20 @@ class TestDiceLoss(BaseTester):
labels = torch.zeros(1, 4, 1, device=device, dtype=torch.int64)
- exp_1_0 = torch.exp(torch.tensor([1.0], device=device, dtype=dtype))
- exp_10_0 = torch.exp(torch.tensor([10.0], device=device, dtype=dtype))
+ # In float16, 3 * exp(10) overflows before the ratio is formed (#4153).
+ reference_dtype = torch.float64 if dtype == torch.float64 else torch.float32
+ exp_1_0 = torch.exp(torch.tensor([1.0], device=device, dtype=reference_dtype))
+ exp_10_0 = torch.exp(torch.tensor([10.0], device=device, dtype=reference_dtype))
expected_intersection = (3.0 * exp_10_0 + 1.0 * exp_1_0) / (exp_1_0 + exp_10_0)
expected_cardinality = 8.0 # for micro averaging cardinality is equal 2 * H * W
expected_loss = 1.0 - 2.0 * expected_intersection / (expected_cardinality + eps)
- expected_loss = expected_loss.squeeze()
+ expected_loss = expected_loss.squeeze().to(dtype)
criterion = kornia.losses.DiceLoss(average="micro", eps=eps)
loss = criterion(logits, labels)
+ assert torch.isfinite(expected_loss)
+ assert torch.isfinite(loss)
self.assert_close(loss, expected_loss, rtol=1e-3, atol=1e-3)
@pytest.mark.parametrize("avg", ["micro", "macro"])
@@ -418,6 +423,7 @@ class TestDiceLoss(BaseTester):
assert 0.0 <= loss.item() <= 1.0
def test_averaging_macro(self, device, dtype):
+ """Keep the analytical macro-averaging reference finite in half precision."""
num_classes = 2
eps = 1e-8
@@ -429,21 +435,22 @@ class TestDiceLoss(BaseTester):
labels = torch.zeros(1, 1, 4, device=device, dtype=torch.int64)
- exp_1_0 = torch.exp(torch.tensor([1.0], device=device, dtype=dtype))
- exp_10_0 = torch.exp(torch.tensor([10.0], device=device, dtype=dtype))
+ # Promote before forming the intersection/cardinality; casting an overflow later cannot repair it.
+ reference_dtype = torch.float64 if dtype == torch.float64 else torch.float32
+ exp_1_0 = torch.exp(torch.tensor([1.0], device=device, dtype=reference_dtype))
+ exp_10_0 = torch.exp(torch.tensor([10.0], device=device, dtype=reference_dtype))
expected_intersection_1 = (3.0 * exp_10_0 + exp_1_0) / (exp_1_0 + exp_10_0)
expected_cardinality_1 = 4.0 + (3.0 * exp_10_0 + 1.0 * exp_1_0) / (exp_1_0 + exp_10_0)
- reduction_dtype = torch.float64 if dtype == torch.float64 else torch.float32
- expected_loss_1 = 1.0 - 2.0 * expected_intersection_1.to(reduction_dtype) / (
- expected_cardinality_1.to(reduction_dtype) + eps
- )
+ expected_loss_1 = 1.0 - 2.0 * expected_intersection_1 / (expected_cardinality_1 + eps)
# Class 1 is absent from the target, so only class 0 contributes to the macro mean.
expected_loss = expected_loss_1.squeeze().to(dtype)
criterion = kornia.losses.DiceLoss(average="macro", eps=eps)
loss = criterion(logits, labels)
+ assert torch.isfinite(expected_loss)
+ assert torch.isfinite(loss)
self.assert_close(loss, expected_loss, rtol=1e-3, atol=1e-3)
@pytest.mark.parametrize("ignore_index", [-100, 255])