Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(morphology): preserve NaNs in old MPS shift engine (#5457)

Arc0000074a4ddd1fd4ff
diff --git a/changelog.d/5457.fixed.md b/changelog.d/5457.fixed.md
new file mode 100644
index 000000000..446778285
--- /dev/null
+++ b/changelog.d/5457.fixed.md
@@ -0,0 +1 @@
+On MPS with PyTorch before 2.7, `dilation`, `erosion` and the operators built on them (`opening`, `closing`, `gradient`, `top_hat`, `bottom_hat`) now propagate a NaN inside the window when they use the `shift` engine, which `engine="auto"` (the default) selects on MPS. They used to return a finite value there, because `torch.maximum` and `torch.minimum` ignore NaN on those versions.
diff --git a/kornia/morphology/morphology.py b/kornia/morphology/morphology.py
index e7c4da772..b4dc29de5 100644
--- a/kornia/morphology/morphology.py
+++ b/kornia/morphology/morphology.py
@@ -15,16 +15,29 @@
# limitations under the License.
#
-from typing import List, Optional
+from typing import Final, List, Optional
import torch
import torch.nn.functional as F
+from kornia.core._compat import torch_version_lt
from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SAME_SHAPE, KORNIA_CHECK_SHAPE
from kornia.core.exceptions import ValueCheckError
__all__ = ["bottom_hat", "closing", "dilation", "erosion", "gradient", "opening", "reconstruction", "top_hat"]
+_MPS_MAXIMUM_IGNORES_NAN: Final[bool] = torch_version_lt(2, 7, 0)
+
+
+def _maximum_ignores_nan(device: torch.device, mps_ignores_nan: bool = _MPS_MAXIMUM_IGNORES_NAN) -> bool:
+ """Whether ``torch.maximum``/``torch.minimum`` return the non-NaN operand of a pair on ``device``.
+
+ MPS does so before PyTorch 2.7 (pytorch/pytorch#143976, fixed by pytorch/pytorch#144086), so the ``shift``
+ engine tracks NaN itself there. The version flag is a default argument because TorchScript cannot read a
+ module-level ``bool``.
+ """
+ return device.type == "mps" and mps_ignores_nan
+
def _validate_morphology_inputs(
tensor: torch.Tensor, kernel: torch.Tensor, structuring_element: Optional[torch.Tensor], border_type: str
@@ -118,12 +131,15 @@ def _shift_reduce(
# than masking (CPU float32, 3 x 3 and 7 x 7). While a backward graph is being recorded, or for a
# a call without a reduction value, the masked form is kept.
recording = torch.is_grad_enabled() and (padded.requires_grad or offsets.requires_grad)
+ # Where the pairwise reduction drops NaN (see ``_maximum_ignores_nan``), a running ``isnan`` mask restores it.
+ propagate_nan = _maximum_ignores_nan(padded.device)
if reduction_value is None or recording:
# Keep each offset two-dimensional so PyTorch applies tensor-tensor dtype promotion. Indexing
# down to a scalar would instead apply wrapped-scalar rules and silently keep ``padded.dtype``.
output = padded[..., 0:height, 0:width] + offsets[0:1, 0:1]
if reduction_value is not None:
output = torch.where(kernel[0, 0] != 0, output, torch.full_like(output, reduction_value))
+ nan_mask = torch.isnan(output) if propagate_nan else None
# ``unfold`` reduces the kernel-height dimension first and then kernel width; keep that traversal so
# tied values are met in the same order. Which of two tied operands a backend's ``max``/``min``
# returns is its own choice (CPU keeps the first, MPS the second), so the sign of a zero result is
@@ -135,10 +151,14 @@ def _shift_reduce(
shifted = padded[..., i : i + height, j : j + width] + offsets[i : i + 1, j : j + 1]
if reduction_value is not None:
shifted.masked_fill_(kernel[i, j] == 0, reduction_value)
+ if nan_mask is not None:
+ nan_mask = nan_mask | torch.isnan(shifted)
if inplace:
torch.maximum(output, shifted, out=output) if dilate else torch.minimum(output, shifted, out=output)
else:
output = torch.maximum(output, shifted) if dilate else torch.minimum(output, shifted)
+ if nan_mask is not None:
+ output = output.masked_fill(nan_mask, float("nan"))
return output
# Out-of-place on purpose: ``vmap`` and forward-mode AD batch or dualise ``padded``, which an in-place
@@ -153,16 +173,21 @@ def _shift_reduce(
offsets = torch.where(included, offsets, torch.zeros_like(offsets))
output = _shift_cell(planes, plane, offsets, 0, 0, height, width, flat)
+ nan_mask = torch.isnan(output) if propagate_nan else None
# Same traversal order as the masked loop above and as ``unfold``.
for j in range(kw):
for i in range(kh):
if i == 0 and j == 0:
continue
shifted = _shift_cell(planes, plane, offsets, i, j, height, width, flat)
+ if nan_mask is not None:
+ nan_mask = nan_mask | torch.isnan(shifted)
if inplace:
torch.maximum(output, shifted, out=output) if dilate else torch.minimum(output, shifted, out=output)
else:
output = torch.maximum(output, shifted) if dilate else torch.minimum(output, shifted)
+ if nan_mask is not None:
+ output = output.masked_fill(nan_mask, float("nan"))
return output
diff --git a/tests/morphology/test_dilation.py b/tests/morphology/test_dilation.py
index 106cb8c98..285749b37 100644
--- a/tests/morphology/test_dilation.py
+++ b/tests/morphology/test_dilation.py
@@ -840,11 +840,12 @@ class TestDilate(BaseTester):
)
assert torch.equal(dilate(half_image, half_cross, max_val=65504.0), dilate(half_image, half_cross))
- @pytest.mark.parametrize("engine", ["unfold", "shift", "convolution"])
+ @pytest.mark.parametrize("engine", ["unfold", "shift", "convolution", "auto"])
def test_convention_non_finite_inputs_agree_across_engines_4734(self, device, dtype, engine):
# A NaN or an infinity inside the window reaches the output; one in a cell the kernel excludes does
# not. `convolution` multiplies every window cell by a one-hot weight, so it has to keep `inf * 0` and
- # `nan * 0` out of the excluded cells without dropping the values of the included ones.
+ # `nan * 0` out of the excluded cells without dropping the values of the included ones. On MPS with PyTorch
+ # <2.7, this also covers #4997: `auto` selects `shift`, whose pairwise maximum/minimum otherwise ignore NaN.
nan, inf = float("nan"), float("inf")
tensor = torch.tensor([[[[0.25, nan, 0.75, inf, 0.5, -inf, 0.75]]]], device=device, dtype=dtype)
side_kernel = torch.tensor([[1.0, 0.0, 0.0]], device=device, dtype=dtype)
@@ -859,6 +860,63 @@ class TestDilate(BaseTester):
expected_tensor = torch.tensor(expected, device=device, dtype=actual.dtype)
torch.testing.assert_close(actual, expected_tensor, rtol=0.0, atol=0.0, equal_nan=True)
+ @pytest.mark.parametrize("op", [dilation, erosion, opening, closing, gradient, top_hat, bottom_hat])
+ @pytest.mark.parametrize("requires_grad", [False, True])
+ def test_convention_shift_tracks_nan_when_maximum_ignores_it_4997(
+ self, device, dtype, op, requires_grad, monkeypatch
+ ):
+ # MPS before PyTorch 2.7 returns the non-NaN operand of `torch.maximum`/`torch.minimum`, and the only MPS CI
+ # leg runs a newer PyTorch. Patching in a pairwise reduction with that behaviour runs the NaN tracking of the
+ # `shift` engine wherever this suite runs (`torch.fmax`/`torch.fmin` would do, but lack MPS bfloat16 kernels
+ # on old PyTorch). Row 0 holds a NaN and an `inf` that meets the `-inf` structuring element entry
+ # (`inf + -inf` is NaN); row 1 is finite.
+ nan, inf = float("nan"), float("inf")
+ tensor = torch.tensor(
+ [[[[0.25, nan, 0.75, inf, 0.5, -inf, 0.75]]], [[[0.5, 0.25, 0.75, 0.0, 1.0, 0.5, 0.25]]]],
+ device=device,
+ dtype=dtype,
+ )
+ ones = torch.ones(1, 3, device=device, dtype=dtype)
+ cases = [
+ (ones, None),
+ (torch.tensor([[1.0, 0.0, 0.0]], device=device, dtype=dtype), None),
+ (ones, torch.tensor([[0.0, -inf, 0.5]], device=device, dtype=dtype)),
+ ]
+ expected = [op(tensor, kernel, structuring_element=se, engine="shift") for kernel, se in cases]
+
+ def ignoring_nan(reduce):
+ def pairwise(a, b, out=None):
+ result = torch.where(torch.isnan(a), b, torch.where(torch.isnan(b), a, reduce(a, b)))
+ return result if out is None else out.copy_(result)
+
+ return pairwise
+
+ def run_with_nan_ignoring_maximum(track_nan):
+ with monkeypatch.context() as patch:
+ patch.setattr(morphology_module, "_maximum_ignores_nan", lambda _: track_nan)
+ patch.setattr(torch, "maximum", ignoring_nan(torch.maximum))
+ patch.setattr(torch, "minimum", ignoring_nan(torch.minimum))
+ image = tensor.clone().requires_grad_(requires_grad)
+ return [op(image, kernel, structuring_element=se, engine="shift").detach() for kernel, se in cases]
+
+ for actual, reference in zip(run_with_nan_ignoring_maximum(True), expected):
+ torch.testing.assert_close(actual, reference, rtol=0.0, atol=0.0, equal_nan=True)
+ # The finite row is untouched by the NaN of the other row.
+ assert not torch.isnan(actual[1]).any()
+ # Control: without the tracking, the patched reduction does drop NaN, so the assertion above is not vacuous.
+ dropped = run_with_nan_ignoring_maximum(False)
+ assert sum(int(out.isnan().sum()) for out in dropped) < sum(int(out.isnan().sum()) for out in expected)
+
+ def test_nan_tracking_gate_matches_the_backend_4997(self, device, dtype):
+ # The `shift` engine tracks NaN exactly where the backend's pairwise maximum/minimum drop it.
+ nan_first = torch.tensor([float("nan"), 1.0], device=device, dtype=dtype)
+ nan_second = nan_first.flip(0)
+ propagates = (
+ torch.isnan(torch.maximum(nan_first, nan_second)).all()
+ and torch.isnan(torch.minimum(nan_first, nan_second)).all()
+ )
+ assert morphology_module._maximum_ignores_nan(nan_first.device) == (not bool(propagates))
+
@pytest.mark.parametrize("image_dtype", [torch.bool, torch.uint8, torch.int32, torch.int64])
def test_convention_non_float_images_are_rejected_4735(self, device, image_dtype):
kernel = torch.ones(1, 3, device=device)