Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(filters): mark median_blur's non-finite windows without relying on the convolution (#5529)

Dmytro Mishkin9e188e088a84
diff --git a/changelog.d/5529.fixed.md b/changelog.d/5529.fixed.md
new file mode 100644
index 000000000..a921660fe
--- /dev/null
+++ b/changelog.d/5529.fixed.md
@@ -0,0 +1 @@
+`median_blur` now returns NaN for every window of more than one pixel that holds a NaN or an infinity on every backend, as documented. Windows of 7x7 and larger, and inputs that require grad, no longer depend on how the backend's convolution handles `0 * NaN` and `0 * Inf` (CPU bfloat16 on x86 returned finite values there).
diff --git a/kornia/filters/median.py b/kornia/filters/median.py
index c0165b734..1bffb571b 100644
--- a/kornia/filters/median.py
+++ b/kornia/filters/median.py
@@ -68,6 +68,27 @@ def _median_network(size: int) -> tuple[tuple[int, int, bool, bool], ...]:
_MEDIAN_NETWORKS = {3: _median_network(9), 5: _median_network(25)}
+def _non_finite_windows(input: torch.Tensor, kernel_size: tuple[int, int], border_type: str) -> torch.Tensor:
+ """Return where a ``(kH, kW)`` window of the padded input holds a NaN or an infinity.
+
+ Mark windows from a mask of the non-finite pixels rather than from the values: max-pooling NaNs directly, and
+ the products ``0 * NaN`` and ``0 * Inf`` inside a convolution, are version-, dtype- and backend-dependent on CPU.
+ """
+ ky, kx = kernel_size
+ height, width = input.shape[-2:]
+ pad = (kx // 2, kx // 2, ky // 2, ky // 2)
+ # The padding modes have no bool kernels; pad the mask in the input dtype.
+ padded = F.pad((~torch.isfinite(input)).to(input.dtype), pad, mode=border_type) != 0
+ # A window holds a marked pixel when one of its columns does: OR shifted slices, rows then columns.
+ columns = padded[..., :height, :]
+ for dy in range(1, ky):
+ columns = torch.logical_or(columns, padded[..., dy : dy + height, :])
+ windows = columns[..., :width]
+ for dx in range(1, kx):
+ windows = torch.logical_or(windows, columns[..., dx : dx + width])
+ return windows
+
+
def _median_blur_network(input: torch.Tensor, size: int, border_type: str = "reflect") -> torch.Tensor:
"""Select a small-window median without materializing patches or sorting them."""
radius = size // 2
@@ -80,11 +101,7 @@ def _median_blur_network(input: torch.Tensor, size: int, border_type: str = "ref
values[left] = torch.minimum(a, b)
if high:
values[right] = torch.maximum(a, b)
- # The original one-hot convolution propagates any NaN/Inf in a window to
- # every extracted feature (including 0 * Inf). Pool a finite-value mask:
- # max-pooling NaNs directly is version- and dtype-dependent on CPU.
- padded_mask = F.pad((~torch.isfinite(input)).to(input.dtype), (radius, radius, radius, radius), mode=border_type)
- invalid = F.max_pool2d(padded_mask, size, stride=1, padding=0).bool()
+ invalid = _non_finite_windows(input, (size, size), border_type)
selected = values[size * size // 2]
return torch.where(invalid, torch.full_like(selected, float("nan")), selected).contiguous()
@@ -160,6 +177,14 @@ def median_blur(input: torch.Tensor, kernel_size: tuple[int, int] | int, border_
padding = _compute_zero_padding(kernel_size)
+ # Convolve finite values only and mark the windows that held a NaN or an infinity afterwards, so the result
+ # does not depend on how the backend's convolution treats 0 * NaN and 0 * Inf. A 1x1 window has no zero
+ # weight and returns its pixel, infinity included. An empty input has nothing to mark.
+ invalid: torch.Tensor | None = None
+ if input.is_floating_point() and ky * kx > 1 and input.numel() > 0:
+ invalid = _non_finite_windows(input, (ky, kx), border_type)
+ input = input.nan_to_num(0.0, 0.0, 0.0)
+
# prepare kernel
kernel: torch.Tensor = get_binary_kernel2d(kernel_size, device=input.device, dtype=input.dtype)
b, c, h, w = input.shape
@@ -181,8 +206,12 @@ def median_blur(input: torch.Tensor, kernel_size: tuple[int, int] | int, border_
# compute the median along the feature axis
if is_exporting():
# ``median.dim`` has no ONNX lowering; a sort picks the same (lower-middle) element.
- return features.sort(dim=2)[0][:, :, (ky * kx - 1) // 2]
- return features.median(dim=2)[0]
+ median = features.sort(dim=2)[0][:, :, (ky * kx - 1) // 2]
+ else:
+ median = features.median(dim=2)[0]
+ if invalid is not None:
+ median = median.masked_fill(invalid, float("nan"))
+ return median
class MedianBlur(nn.Module):
diff --git a/tests/filters/test_median.py b/tests/filters/test_median.py
index 3f45d7361..563aa34d5 100644
--- a/tests/filters/test_median.py
+++ b/tests/filters/test_median.py
@@ -25,7 +25,7 @@ from kornia.core.exceptions import BaseError
from kornia.filters import MedianBlur, median_blur
from kornia.filters.kernels import get_binary_kernel2d
-from testing.base import BaseTester, supports_reflect_padding
+from testing.base import BaseTester, supports_reflect_padding, supports_replicate_padding
median_module = importlib.import_module("kornia.filters.median")
@@ -259,6 +259,36 @@ class TestMedianBlur(BaseTester):
self.assert_close(actual.isnan(), expected.isnan())
self.assert_close(actual.nan_to_num(), expected.nan_to_num())
+ @pytest.mark.parametrize("conv_nonfinite", ["drops", "spreads"])
+ @pytest.mark.parametrize("requires_grad", [False, True])
+ @pytest.mark.parametrize("kernel_size", [3, 7, (5, 7)])
+ @pytest.mark.parametrize("invalid", [float("nan"), float("inf")])
+ def test_nonfinite_window_does_not_depend_on_convolution(
+ self, monkeypatch, invalid, kernel_size, requires_grad, conv_nonfinite, device, dtype
+ ):
+ # CPU bf16 convolution on the x86 CI runners can drop a NaN from the one-hot features (7x7 windows) or
+ # spread it outside the window. Emulate both: only the windows that hold the non-finite pixel are NaN.
+ conv2d = torch.nn.functional.conv2d
+
+ def nonfinite_conv2d(x, *args, **kwargs):
+ if conv_nonfinite == "drops":
+ return conv2d(torch.where(torch.isfinite(x), x, torch.zeros_like(x)), *args, **kwargs)
+ out = conv2d(x, *args, **kwargs)
+ return torch.where(torch.isfinite(x).all(), out, torch.full_like(out, float("nan")))
+
+ if not supports_replicate_padding(device, dtype):
+ pytest.skip(f"this torch build has no replicate padding kernel for {dtype} on {device.type}")
+ monkeypatch.setattr(torch.nn.functional, "conv2d", nonfinite_conv2d)
+ image = torch.full((1, 1, 9, 11), 0.5, device=device, dtype=dtype)
+ image[0, 0, 4, 5] = invalid
+ image.requires_grad_(requires_grad)
+ ky, kx = (kernel_size, kernel_size) if isinstance(kernel_size, int) else kernel_size
+ expected = torch.zeros(1, 1, 9, 11, dtype=torch.bool, device=device)
+ expected[..., 4 - ky // 2 : 5 + ky // 2, 5 - kx // 2 : 6 + kx // 2] = True
+ actual = median_blur(image, kernel_size, "replicate").detach()
+ assert torch.equal(actual.isnan(), expected)
+ assert torch.equal(actual[~expected], torch.full_like(actual[~expected], 0.5))
+
@pytest.mark.parametrize("kernel_size", [3, 5])
@pytest.mark.parametrize("shape", [(1, 2, 7, 9), (1, 4, 512, 512)])
def test_selection_dispatch(self, monkeypatch, kernel_size, shape, device, dtype):