Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(contrib): guard distance_transform against exp(-dist/h) kernel underflow (#4158)

Mohansree Vijayakumar1ba6c03a6258
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 5c624199f..cfd33906f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -188,10 +188,26 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Bug fixes
+* `distance_transform` no longer silently returns a wrong or all-zero result when its `exp(-dist/h)` kernel
+ underflows (#4152). The kernel's axis-aligned tap, at distance `kernel_size // 2` along a single axis,
+ underflowing to exactly zero -- reachable from the documented default `h=0.35` at `kernel_size >= 15` in
+ `float16` -- used to make the convolution silently drop it, returning a plausible-looking but wrong distance
+ field or, with a smaller `h`, an all-zero one. Two changes: `float16`/`bfloat16` inputs now run the cascade in
+ `float32` and cast the result back (the default `h=0.35` case is fixed by this alone, matching `float32`'s own
+ working range); and an `h`/`kernel_size`/dtype combination whose axis-aligned tap still underflows
+ `torch.finfo(dtype).tiny` now raises instead of guessing. This also catches a case that is not itself
+ numerically wrong on CPU (`h=0.01` at `kernel_size=3` in `float32` tracks the analytic reference to ~2e-4,
+ carried through the subnormal range) but where MPS flushes subnormals to zero while CPU does not, so the same
+ call used to silently disagree across backends; raising there rules out that disagreement rather than trusting
+ which backend a caller happens to run on. Concretely, at the documented default `h=0.35` in `float32`,
+ `kernel_size >= 63` now raises: CPU used to return a usable-looking answer there while MPS silently returned
+ something else for the same call.
+
* `RandomTransplantation` and `RandomTransplantation3D` transplanted nothing on MPS when no `excluded_labels`
were given: PyTorch's MPS backend evaluates `all()` over the empty excluded-label axis to an undefined value,
usually `False`, so every donor label was filtered out and the output equalled the input. The filter is now skipped when there is
nothing to exclude. (#4160)
+
* `VisualPrompter.predict()` called without any prompt (the "run the prediction without prompts" example on the
Segment Anything page) raised `TypeError: object of type 'NoneType' has no len()` from the prompt augmentation
container; it now predicts from the image embedding alone, as documented. (#4178)
diff --git a/kornia/contrib/distance_transform.py b/kornia/contrib/distance_transform.py
index d190ae989..fd7149d2e 100644
--- a/kornia/contrib/distance_transform.py
+++ b/kornia/contrib/distance_transform.py
@@ -27,21 +27,51 @@ from kornia.filters import filter2d, filter3d
from kornia.geometry.grid import create_meshgrid, create_meshgrid3d
+def _compute_dtype(dtype: torch.dtype) -> torch.dtype:
+ # The exp(-dist/h) kernel and its -h*log(...) inverse have a working range that float16 and
+ # bfloat16 cannot cover (see _check_h_range): run the cascade in float32 and cast the result
+ # back, the same way half-precision inputs are upcast elsewhere in kornia (e.g.
+ # PatchAffineShapeEstimator, extract_patches_from_pyramid).
+ if dtype in (torch.float16, torch.bfloat16):
+ return torch.float32
+ return dtype
+
+
+def _check_h_range(kernel_size: int, h: float, dtype: torch.dtype) -> None:
+ # The kernel's corner tap (distance sqrt(dims)*k_half) decays fast enough that losing it is
+ # harmless -- its contribution to the soft-min is negligible by construction. It is the
+ # axis-aligned tap, at distance k_half along a single axis, that has to survive: losing it is
+ # what actually corrupts the result, so it -- not the corner -- is the discriminating case.
+ # Checked against `finfo.tiny` -- the smallest positive *normal* value -- rather than the true
+ # (device-dependent) smallest subnormal: MPS flushes subnormals to zero while CPU does not, so
+ # a subnormal-aware threshold would silently disagree across devices for the same dtype and h,
+ # which is the inconsistency this guard exists to rule out.
+ k_half = kernel_size // 2
+ smallest_tap = math.exp(-k_half / h)
+ KORNIA_CHECK(
+ smallest_tap >= torch.finfo(dtype).tiny,
+ f"h={h} is too small for kernel_size={kernel_size} at working precision {dtype}: the axis-aligned "
+ f"kernel tap exp(-{k_half}/h) underflows to zero, so the convolution silently drops it and "
+ "distance_transform returns a wrong or all-zero result. Increase h or decrease kernel_size.",
+ )
+
+
def _distance_transform_2d_impl(image: torch.Tensor, kernel_size: int, h: float) -> torch.Tensor:
device = image.device
dtype = image.dtype
+ compute_dtype = _compute_dtype(dtype)
k_half = kernel_size // 2
n_iters = math.ceil(max(image.shape[2], image.shape[3]) / k_half)
- grid = create_meshgrid(kernel_size, kernel_size, False, device, dtype)
+ grid = create_meshgrid(kernel_size, kernel_size, False, device, compute_dtype)
grid = grid - k_half
# `torch.hypot` has no ONNX lowering; the grid offsets are small integers, so the plain form is exact enough.
dist = torch.sqrt(grid[0, ..., 0] ** 2 + grid[0, ..., 1] ** 2)
kernel = torch.exp(-dist / h).unsqueeze(0)
- out = torch.zeros_like(image)
- boundary = image.clone()
+ out = torch.zeros_like(image, dtype=compute_dtype)
+ boundary = image.to(compute_dtype)
signal_ones = torch.ones_like(boundary)
for i in range(n_iters):
@@ -57,22 +87,23 @@ def _distance_transform_2d_impl(image: torch.Tensor, kernel_size: int, h: float)
out = out + (offset + cdt) * mask.to(dtype=out.dtype)
boundary = torch.where(mask, signal_ones, boundary)
- return out
+ return out.to(dtype)
def _distance_transform_3d_impl(image: torch.Tensor, kernel_size: int, h: float) -> torch.Tensor:
device = image.device
dtype = image.dtype
+ compute_dtype = _compute_dtype(dtype)
k_half = kernel_size // 2
n_iters = math.ceil(max(image.shape[2:]) / k_half)
- grid = create_meshgrid3d(kernel_size, kernel_size, kernel_size, False, device, dtype)
+ grid = create_meshgrid3d(kernel_size, kernel_size, kernel_size, False, device, compute_dtype)
grid = grid - k_half
dist = torch.norm(grid[0], p=2, dim=-1)
kernel = torch.exp(-dist / h).unsqueeze(0)
- out = torch.zeros_like(image)
- boundary = image.clone()
+ out = torch.zeros_like(image, dtype=compute_dtype)
+ boundary = image.to(compute_dtype)
signal_ones = torch.ones_like(boundary)
for i in range(n_iters):
@@ -88,7 +119,7 @@ def _distance_transform_3d_impl(image: torch.Tensor, kernel_size: int, h: float)
out = out + (offset + cdt) * mask.to(dtype=out.dtype)
boundary = torch.where(mask, signal_ones, boundary)
- return out
+ return out.to(dtype)
def distance_transform(image: torch.Tensor, kernel_size: int = 3, h: float = 0.35) -> torch.Tensor:
@@ -101,7 +132,12 @@ def distance_transform(image: torch.Tensor, kernel_size: int = 3, h: float = 0.3
Args:
image: Image or volume with shape :math:`(B,C,H,W)` or :math:`(B,C,D,H,W)`.
kernel_size: size of the convolution kernel. Must be an odd number.
- h: value that influence the approximation of the min function.
+ h: value that influences the approximation of the min function. The cascade's kernel taps are
+ ``exp(-dist/h)``; too small an ``h`` for the given ``kernel_size`` underflows the
+ axis-aligned tap (distance ``kernel_size // 2``) to exactly zero, which used to return a
+ silently wrong or all-zero result. That combination now raises instead. ``float16`` and
+ ``bfloat16`` inputs run the cascade in ``float32`` and cast the result back, which widens
+ the safe ``h`` range for those dtypes to match ``float32``.
Returns:
tensor with the same shape as input.
@@ -133,6 +169,8 @@ def distance_transform(image: torch.Tensor, kernel_size: int = 3, h: float = 0.3
KORNIA_CHECK(kernel_size % 2 != 0 and kernel_size >= 3, "kernel_size must be an odd integer >= 3")
KORNIA_CHECK(h > 0, f"h must be a positive float, got {h}")
+ compute_dtype = _compute_dtype(image.dtype)
+ _check_h_range(kernel_size, h, compute_dtype)
if image.ndim == 4:
return _distance_transform_2d_impl(image, kernel_size, h)
@@ -144,7 +182,8 @@ class DistanceTransform(nn.Module):
Args:
kernel_size: size of the convolution kernel.
- h: value that influence the approximation of the min function.
+ h: value that influences the approximation of the min function. See :func:`distance_transform`
+ for the safe range of ``h`` relative to ``kernel_size`` and working precision.
"""
diff --git a/tests/contrib/test_conv_distance_transformer.py b/tests/contrib/test_conv_distance_transformer.py
index 3fb778827..3879fe0f2 100755
--- a/tests/contrib/test_conv_distance_transformer.py
+++ b/tests/contrib/test_conv_distance_transformer.py
@@ -192,6 +192,15 @@ class TestConvDistanceTransform(BaseTester):
loss_3d.backward()
def test_offset_parenthesis_fix(self, device, dtype):
+ # h=0.01 at kernel_size=3 was not itself numerically wrong on CPU/float32 (it tracked the
+ # analytic reference to ~2e-4, carried through the subnormal range), but #4152's fix now
+ # explicitly rejects that combination -- the same call silently disagreed on MPS, which
+ # flushes subnormals to zero -- so this test can no longer use it regardless. h=0.1 keeps
+ # the offset accumulation this test exists to pin (n - 0.00313 per row, strictly increasing
+ # by 1, so a mis-parenthesized `offset + cdt * mask` would fail this) while staying well
+ # clear of the underflow guard; reference values generated at float64 via:
+ # img = torch.zeros(1, 1, 8, 4, dtype=torch.float64); img[0, 0, 1, :] = 1.0
+ # kornia.contrib.distance_transform(img, kernel_size=3, h=0.1)[0, 0, :, 0]
if not supports_replicate_padding(device, dtype):
pytest.skip("This device does not support replicate padding for the regression dtype")
if not supports_conv2d(device, dtype):
@@ -199,19 +208,17 @@ class TestConvDistanceTransform(BaseTester):
img = torch.zeros(1, 1, 8, 4, device=device, dtype=dtype)
img[0, 0, 1, :] = 1.0
- # exp(-1 / 0.01) is a float32 subnormal that MPS flushes to zero. h=0.1 keeps
- # the regression's expected offset away from backend-specific underflow behavior (#4152).
out = kornia.contrib.distance_transform(img, kernel_size=3, h=0.1)
expected = torch.tensor(
[
- [0.9969, 0.9969, 0.9969, 0.9969],
- [0.0000, 0.0000, 0.0000, 0.0000],
- [0.9969, 0.9969, 0.9969, 0.9969],
- [1.9969, 1.9969, 1.9969, 1.9969],
- [2.9969, 2.9969, 2.9969, 2.9969],
- [3.9969, 3.9969, 3.9969, 3.9969],
- [4.9969, 4.9969, 4.9969, 4.9969],
- [5.9969, 5.9969, 5.9969, 5.9969],
+ [0.996872, 0.996872, 0.996872, 0.996872],
+ [0.000000, 0.000000, 0.000000, 0.000000],
+ [0.996872, 0.996872, 0.996872, 0.996872],
+ [1.996872, 1.996872, 1.996872, 1.996872],
+ [2.996872, 2.996872, 2.996872, 2.996872],
+ [3.996872, 3.996872, 3.996872, 3.996872],
+ [4.996872, 4.996872, 4.996872, 4.996872],
+ [5.996872, 5.996872, 5.996872, 5.996872],
],
device=device,
dtype=dtype,
@@ -220,27 +227,57 @@ class TestConvDistanceTransform(BaseTester):
tolerance = 5e-3 if dtype == torch.bfloat16 else 1e-3
self.assert_close(out[0, 0], expected, rtol=tolerance, atol=tolerance)
- @pytest.mark.xfail(
- raises=AssertionError,
- reason="distance_transform silently collapses to zero when its kernel underflows β€” kornia#4152",
- strict=True,
- )
- def test_convention_small_h_keeps_nonzero_distances_4152(self, device, dtype):
- if not (dtype in (torch.float16, torch.bfloat16) or (device.type == "mps" and dtype == torch.float32)):
- pytest.skip("This device and dtype do not reproduce the small-h underflow in kornia#4152")
+ # test_convention_small_h_keeps_nonzero_distances_4152, a strict xfail pinning the pre-fix silent
+ # wrong-output behavior for h=0.01 at kernel_size=3 in float16/bfloat16/mps-float32, is removed
+ # here: this PR fixes #4152, so that combination now raises BaseError (a different exception than
+ # the pinned `raises=AssertionError`) instead of returning a wrong value, which would make the
+ # xfail fail outright rather than pass. test_h_too_small_raises and
+ # test_h_too_small_raises_float32_regression below pin the new, fixed behavior instead.
+
+ def test_half_precision_matches_float64_reference(self, device, dtype):
+ # #4152: the exp(-dist/h) kernel's far taps underflow to exactly zero in float16/bfloat16
+ # at the documented default h=0.35 once kernel_size >= 15, and the convolution silently
+ # drops them -- the peak distance below came back as ~15.7 instead of ~13.5 before the fix.
+ # distance_transform now runs the cascade in float32 for half-precision inputs, so the
+ # result should track the float64 reference to about float32 precision regardless of the
+ # input dtype. The reference is built on its own CPU float64 tensor -- MPS has no float64,
+ # so a `.double()` of the fixture's own `img` would fail there.
if not supports_replicate_padding(device, dtype):
pytest.skip("This device does not support replicate padding for the regression dtype")
if not supports_conv2d(device, dtype):
pytest.skip("This device does not support convolution for the regression dtype")
+ img = torch.zeros(1, 1, 16, 4, device=device, dtype=dtype)
+ img[0, 0, 1, :] = 1.0
+ ref_img = torch.zeros(1, 1, 16, 4, dtype=torch.float64)
+ ref_img[0, 0, 1, :] = 1.0
+ reference = kornia.contrib.distance_transform(ref_img, kernel_size=15).max()
+ out = kornia.contrib.distance_transform(img, kernel_size=15).max()
+ self.assert_close(out.cpu(), reference.to(dtype).cpu(), rtol=1e-2, atol=1e-2)
+
+ def test_h_too_small_raises(self, device, dtype):
+ # #4152: an h too small for kernel_size at the working precision used to underflow the
+ # farthest kernel tap to zero and silently return a wrong or all-zero field. It now raises
+ # instead of guessing. h=1e-30 underflows at any working precision, including float64.
img = torch.zeros(1, 1, 8, 4, device=device, dtype=dtype)
img[0, 0, 1, :] = 1.0
- out = kornia.contrib.distance_transform(img, kernel_size=3, h=0.01)
- expected_column = torch.tensor(
- [0.9998, 0.0, 0.9998, 1.9998, 2.9998, 3.9998, 4.9998, 5.9998], device=device, dtype=dtype
- )
-
- self.assert_close(out[0, 0, :, 0], expected_column)
+ with pytest.raises(BaseError, match="too small for kernel_size"):
+ kornia.contrib.distance_transform(img, kernel_size=3, h=1e-30)
+
+ def test_h_too_small_raises_float32_regression(self, device):
+ # #4152: h=0.01 at kernel_size=3 in float32 (or float16/bfloat16, upcast to float32) is not
+ # itself numerically wrong on CPU -- it tracks the analytic Euclidean distance to ~2e-4,
+ # carried through the subnormal range -- so the reason to reject it is not accuracy. It is
+ # that MPS flushes subnormals to zero while CPU does not, so the same call would silently
+ # disagree across backends; raising here makes that disagreement impossible rather than
+ # trusting the accident of which backend a caller happens to run on. Checked at float32
+ # explicitly, independent of the dtype fixture: float64's much smaller `finfo.tiny` does not
+ # underflow at this h, so this combination legitimately only raises at float32-or-coarser
+ # working precision.
+ img = torch.zeros(1, 1, 8, 4, device=device, dtype=torch.float32)
+ img[0, 0, 1, :] = 1.0
+ with pytest.raises(BaseError, match="too small for kernel_size"):
+ kornia.contrib.distance_transform(img, kernel_size=3, h=0.01)
def test_dynamo(self, device, dtype, torch_optimizer):
input2d = torch.rand(1, 1, 16, 16, device=device, dtype=dtype)