Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(losses): accept empty batches in Hausdorff losses (#6291)

Keshav Chhabrace23eebc98db
diff --git a/changelog.d/6291.fixed.md b/changelog.d/6291.fixed.md
new file mode 100644
index 000000000..13477650c
--- /dev/null
+++ b/changelog.d/6291.fixed.md
@@ -0,0 +1 @@
+`HausdorffERLoss` and `HausdorffERLoss3D` now support empty batches.
diff --git a/kornia/losses/hausdorff.py b/kornia/losses/hausdorff.py
index 521a5f55f..b7096e7eb 100644
--- a/kornia/losses/hausdorff.py
+++ b/kornia/losses/hausdorff.py
@@ -117,7 +117,7 @@ class _HausdorffERLossBase(nn.Module):
raise ValueError(f"Expect long type target value in range [0, {pred.size(1)}). Got {target.dtype}.")
# The range check reads the data, which graph capture cannot do; skip it under any capture.
# Neither Hausdorff loss scripts on main (its ``super().forward``), so no TorchScript guard is needed.
- if not is_compiling() and not (target.max() < pred.size(1) and target.min() >= 0):
+ if not is_compiling() and target.numel() > 0 and not (target.max() < pred.size(1) and target.min() >= 0):
raise ValueError(
f"Expect long type target value in range [0, {pred.size(1)}). ({target.min()}, {target.max()})"
)
diff --git a/tests/losses/test_hd.py b/tests/losses/test_hd.py
index 28742f5fa..ca4ecfe36 100644
--- a/tests/losses/test_hd.py
+++ b/tests/losses/test_hd.py
@@ -45,6 +45,35 @@ class TestHausdorffLoss(BaseTester):
loss(logits, labels)
+ @pytest.mark.parametrize("reduction", ["mean", "none", "sum"])
+ @pytest.mark.parametrize(
+ "hd,shape", [(kornia.losses.HausdorffERLoss, (4, 4)), (kornia.losses.HausdorffERLoss3D, (3, 4, 4))]
+ )
+ def test_empty_batch(self, hd, shape, reduction, device, dtype):
+ pred = torch.empty(0, 2, *shape, device=device, dtype=dtype)
+ target = torch.empty(0, 1, *shape, device=device, dtype=torch.long)
+
+ actual = hd(reduction=reduction)(pred, target)
+
+ if reduction == "none":
+ assert actual.shape == (2, 0, 1, *shape)
+ elif reduction == "sum":
+ self.assert_close(actual, torch.tensor(0.0, device=device, dtype=dtype))
+ else:
+ assert actual.ndim == 0
+ assert torch.isnan(actual)
+
+ @pytest.mark.parametrize(
+ "hd,shape", [(kornia.losses.HausdorffERLoss, (4, 4)), (kornia.losses.HausdorffERLoss3D, (3, 4, 4))]
+ )
+ @pytest.mark.parametrize("label", [-1, 2])
+ def test_nonempty_target_out_of_range(self, hd, shape, label, device, dtype):
+ pred = torch.rand(1, 2, *shape, device=device, dtype=dtype)
+ target = torch.full((1, 1, *shape), label, device=device, dtype=torch.long)
+
+ with pytest.raises(ValueError, match="Expect long type target value in range"):
+ hd()(pred, target)
+
def test_exception_2d(self):
with pytest.raises(ValueError) as errinf:
kornia.losses.HausdorffERLoss()((torch.rand(1, 2, 1) > 0.5) * 1, (torch.rand(1, 1, 1, 2) > 0.5) * 1)