Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(contrib): keep distance_transform gradients finite (#4232)

Puttala Jeevan Kumar85833ad79ee4
diff --git a/CHANGELOG.md b/CHANGELOG.md
index c4abef46b..8cd8b25e2 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -351,6 +351,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Bug fixes
+
* `kornia.io.load_image` and `write_image` work on the kornia_rs that a plain `pip install kornia`
resolves. kornia_rs 0.1.11 moved its image readers and writers from the package root into
`kornia_rs.io`, and kornia kept calling the root, so on 0.1.11 and newer `load_image` raised
@@ -362,6 +363,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
so instead of mislabelling the tensor. The nightly PyPI job now imports the installed wheel from
outside the checkout (it used to import the source tree) and round-trips an image instead of only
importing. (#4326)
+
+* `distance_transform` no longer returns NaN gradients when the cascade's convolution is exactly zero, including
+ sparse masks and all-zero inputs; the existing forward output is unchanged. (#4232)
+
+
* `SemanticSegmentation.visualize` works for CUDA, MPS and half-precision models. It indexed the
CPU-drawn colormap with the mask's `argmax`, which raises for CUDA and MPS masks, and recognised a
softmax head with `torch.allclose(sum, 1)` at float32-sized default tolerances, which a float16 or
diff --git a/kornia/contrib/distance_transform.py b/kornia/contrib/distance_transform.py
index fd7149d2e..9201cbc5d 100644
--- a/kornia/contrib/distance_transform.py
+++ b/kornia/contrib/distance_transform.py
@@ -76,7 +76,9 @@ def _distance_transform_2d_impl(image: torch.Tensor, kernel_size: int, h: float)
for i in range(n_iters):
cdt = filter2d(boundary, kernel, border_type="replicate")
- cdt = -h * torch.log(cdt)
+ positive = cdt > 0
+ cdt = -h * torch.log(torch.where(positive, cdt, torch.ones_like(cdt)))
+ cdt = torch.where(positive, cdt, torch.zeros_like(cdt))
cdt = torch.nan_to_num(cdt, nan=0.0, posinf=0.0, neginf=0.0)
mask = cdt > 0
@@ -108,7 +110,9 @@ def _distance_transform_3d_impl(image: torch.Tensor, kernel_size: int, h: float)
for i in range(n_iters):
cdt = filter3d(boundary, kernel, border_type="replicate")
- cdt = -h * torch.log(cdt)
+ positive = cdt > 0
+ cdt = -h * torch.log(torch.where(positive, cdt, torch.ones_like(cdt)))
+ cdt = torch.where(positive, cdt, torch.zeros_like(cdt))
cdt = torch.nan_to_num(cdt, nan=0.0, posinf=0.0, neginf=0.0)
mask = cdt > 0
diff --git a/tests/contrib/test_conv_distance_transformer.py b/tests/contrib/test_conv_distance_transformer.py
index 3879fe0f2..d6b716de6 100755
--- a/tests/contrib/test_conv_distance_transformer.py
+++ b/tests/contrib/test_conv_distance_transformer.py
@@ -173,6 +173,24 @@ class TestConvDistanceTransform(BaseTester):
sample3d = torch.ones(B, C, D, H, W, device=device, dtype=torch.float64, requires_grad=True)
self.gradcheck(kornia.contrib.distance_transform, (sample3d,))
+ @pytest.mark.parametrize("shape", [(1, 1, 4, 4), (1, 1, 4, 4, 4)], ids=["2d", "3d"])
+ @pytest.mark.parametrize("has_signal", [False, True], ids=["all-zero", "one-hot"])
+ def test_zero_convolution_has_finite_gradients(self, shape, has_signal, device, dtype):
+ sample = torch.zeros(*shape, device=device, dtype=dtype)
+ if has_signal:
+ sample[(0, 0, *((1,) * (len(shape) - 2)))] = 1.0
+ sample.requires_grad_(True)
+
+ output = kornia.contrib.distance_transform(sample)
+ assert torch.isfinite(output).all()
+ if not has_signal:
+ assert torch.equal(output, torch.zeros_like(output))
+
+ output.sum().backward()
+ assert sample.grad is not None
+ assert sample.grad.shape == sample.shape
+ assert torch.isfinite(sample.grad).all()
+
def test_loss_grad(self, device, dtype):
B, C, H, W = 1, 1, 32, 32
sample1 = torch.rand(B, C, H, W, device=device, dtype=dtype, requires_grad=True)