Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

perf(losses): cut the HausdorffERLoss erosion loop's per-iteration kernels (#4594)

Dipak Chaudharid12948e8b222
diff --git a/kornia/losses/hausdorff.py b/kornia/losses/hausdorff.py
index d19ba3f55..720eb301f 100644
--- a/kornia/losses/hausdorff.py
+++ b/kornia/losses/hausdorff.py
@@ -64,16 +64,16 @@ class _HausdorffERLossBase(nn.Module):
kernel = torch.as_tensor(self.kernel, device=pred.device, dtype=pred.dtype)
eroded = torch.zeros_like(bound, device=pred.device, dtype=pred.dtype)
- mask = torch.ones_like(bound, device=pred.device, dtype=torch.bool)
# Same padding, assuming kernel is odd and square (cube) shaped.
padding = (kernel.size(-1) - 1) // 2
for k in range(self.k):
# compute convolution with kernel
dilation = self.conv(bound, weight=kernel, padding=padding, groups=1)
- # apply soft thresholding at 0.5 and F.normalize
- erosion = dilation - 0.5
- erosion[erosion < 0] = 0
+ # apply soft thresholding at 0.5 and F.normalize. masked_fill zeroes the negatives without
+ # a data-dependent index_put_, and keeps its gradient of 1 at dilation == 0.5 exactly;
+ # clamp_min's derivative at the bound is 0 on torch >= 2.14 and 1 before.
+ erosion = (dilation - 0.5).masked_fill(dilation < 0.5, 0)
# image-wise differences for 2D images
erosion_max = self.max_pool(erosion)
@@ -86,8 +86,8 @@ class _HausdorffERLossBase(nn.Module):
# erosion_max[to_norm] - erosion_min[to_norm])
_range = erosion_max - erosion_min
_to_norm = _range != 0
- _erosion_to_fill = (erosion - erosion_min) / torch.where(_to_norm, _range, torch.ones_like(_range))
- erosion = torch.where(mask * _to_norm, _erosion_to_fill, erosion)
+ _erosion_to_fill = (erosion - erosion_min) / torch.where(_to_norm, _range, 1.0)
+ erosion = torch.where(_to_norm, _erosion_to_fill, erosion)
# save erosion and add to loss
eroded = eroded + erosion * (k + 1) ** self.alpha
diff --git a/tests/losses/test_hd.py b/tests/losses/test_hd.py
index 5b500de8e..c4af28dbc 100644
--- a/tests/losses/test_hd.py
+++ b/tests/losses/test_hd.py
@@ -89,6 +89,52 @@ class TestHausdorffLoss(BaseTester):
actual = loss(logits, labels)
self.assert_close(actual, expected, rtol=1e-2, atol=1e-2)
+ @pytest.mark.parametrize(
+ "hd,shape", [[kornia.losses.HausdorffERLoss, (8, 8)], [kornia.losses.HausdorffERLoss3D, (6, 6, 6)]]
+ )
+ def test_gradient_at_the_threshold_tie(self, hd, shape, device, dtype):
+ # Quantized predictions land the dilation exactly on the 0.5 threshold, where the derivative of
+ # the soft threshold is version-dependent for clamp (#4229). Pin it against the reference: zero
+ # the negatives through a boolean index, whose gradient at the tie is 1.
+ if dtype != torch.float32:
+ pytest.skip("the 0.2 cross kernel sums to exactly 0.5 in float32 only, so no other dtype reaches the tie")
+ generator = torch.Generator().manual_seed(0)
+ pred = (torch.randint(0, 3, (1, 2, *shape), generator=generator) * 0.5).to(device, dtype)
+ target = torch.randint(0, 2, (1, 1, *shape), generator=generator).to(device)
+ loss = hd(k=3)
+
+ def reference_erosion(pred: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
+ bound = (pred - target) ** 2
+ kernel = torch.as_tensor(loss.kernel, device=pred.device, dtype=pred.dtype)
+ padding = (kernel.size(-1) - 1) // 2
+ eroded = torch.zeros_like(bound)
+ ties = 0
+ for k in range(loss.k):
+ dilation = loss.conv(bound, weight=kernel, padding=padding, groups=1)
+ ties += int((dilation == 0.5).sum())
+ erosion = dilation - 0.5
+ erosion[erosion < 0] = 0
+ erosion_max = loss.max_pool(erosion)
+ erosion_min = -loss.max_pool(-erosion)
+ _range = erosion_max - erosion_min
+ _to_norm = _range != 0
+ erosion = torch.where(_to_norm, (erosion - erosion_min) / torch.where(_to_norm, _range, 1.0), erosion)
+ eroded = eroded + erosion * (k + 1) ** loss.alpha
+ bound = erosion
+ assert ties > 0, "the fixture no longer reaches the threshold tie"
+ return eroded
+
+ pred_actual = pred.clone().requires_grad_()
+ loss(pred_actual, target).backward()
+
+ pred_expected = pred.clone().requires_grad_()
+ per_class = [
+ reference_erosion(pred_expected[:, i : i + 1], (target == i).to(dtype)) for i in range(pred.size(1))
+ ]
+ torch.stack(per_class).mean().backward()
+
+ self.assert_close(pred_actual.grad, pred_expected.grad, rtol=0.0, atol=0.0)
+
@pytest.mark.parametrize(
"hd,shape", [[kornia.losses.HausdorffERLoss, (5, 5)], [kornia.losses.HausdorffERLoss3D, (5, 5, 5)]]
)