Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

perf(morphology): reduce flat unfold windows with amax/amin when nothing differentiates (#6034)

Dmytro Mishkina60a6c932a55
diff --git a/changelog.d/6034.fixed.md b/changelog.d/6034.fixed.md
new file mode 100644
index 000000000..46c478aa7
--- /dev/null
+++ b/changelog.d/6034.fixed.md
@@ -0,0 +1 @@
+The `kornia.morphology` operators run about 2x faster with less memory on CUDA, and with `engine="unfold"` on CPU, for a kernel without `structuring_element` when no gradient is recorded: the `unfold` engine masks the windows once and reduces them with `amax`/`amin`, without indices. Values are unchanged; as on every engine, an `erosion` window that ties `+0.0` with `-0.0` may return either zero. Calls that record gradients, forward-mode AD, `torch.func` transforms and traces keep the previous reduction.
diff --git a/kornia/morphology/morphology.py b/kornia/morphology/morphology.py
index 1236012a0..88c6bd026 100644
--- a/kornia/morphology/morphology.py
+++ b/kornia/morphology/morphology.py
@@ -73,6 +73,22 @@ def _can_reduce_in_place(padded: torch.Tensor, offsets: torch.Tensor) -> bool:
return all(torch.autograd.forward_ad.unpack_dual(t).tangent is None for t in (padded, offsets))
+def _unfold_reduces_values_only(
+ windows: torch.Tensor, neighborhood: torch.Tensor, flat: bool, recording_grad: bool
+) -> bool:
+ """Whether the ``unfold`` engine may reduce a flat window with ``amax``/``amin`` instead of ``max``/``min``.
+
+ Both return the same values but differ in derivatives: ``torch.max`` along a dimension routes the gradient or
+ tangent of a tied window to one cell, while ``amax`` splits it. So the swap needs a call that nothing
+ differentiates through: no backward graph, no forward-mode tangent, no ``torch.func`` transform and no trace,
+ which could later replay with gradients. Only CPU and CUDA take it, where ``amax`` propagates NaN like ``max``.
+ """
+ if not flat or recording_grad or windows.device.type not in ("cpu", "cuda"):
+ return False
+ return _can_reduce_in_place(windows, neighborhood)
+
+
def _shift_cell(
planes: torch.Tensor,
plane: torch.Tensor,
@@ -375,13 +391,21 @@ def dilation(
reduction_min: float = -float("inf")
if engine == "unfold":
output = output.unfold(2, se_h, 1).unfold(3, se_w, 1)
- output = output + neighborhood.flip((0, 1))
- output.masked_fill_(
- kernel.flip((0, 1)).view(1, 1, 1, 1, se_h, se_w) == 0,
- reduction_min,
- )
- output, _ = torch.max(output, 4)
- output, _ = torch.max(output, 4)
+ excluded = kernel.flip((0, 1)).view(1, 1, 1, 1, se_h, se_w) == 0
+ values_only = False
+ if not torch.jit.is_scripting():
+ values_only = _unfold_reduces_values_only(output, neighborhood, structuring_element is None, recording_grad)
+ if values_only:
+ # One masked copy of the windows and one reduction without indices, where the general path adds the
+ # offsets, fills the excluded cells in a second pass and reduces twice. The flat offsets are zero, and
+ # adding them only turns ``-0.0`` into ``+0.0``; adding ``0.0`` after the reduction does the same, and
+ # the exact upcast to the compute dtype commutes with the maximum, so the output is unchanged.
+ output = torch.where(excluded, reduction_min, output).amax((-2, -1)).to(compute_dtype) + 0.0
+ else:
+ output = output + neighborhood.flip((0, 1))
+ output.masked_fill_(excluded, reduction_min)
+ output, _ = torch.max(output, 4)
+ output, _ = torch.max(output, 4)
elif engine == "convolution":
B, C, H, W = tensor.size()
h_pad, w_pad = output.shape[-2:]
@@ -559,13 +583,18 @@ def erosion(
reduction_max: float = float("inf")
if engine == "unfold":
output = output.unfold(2, se_h, 1).unfold(3, se_w, 1)
- output = output - neighborhood
- output.masked_fill_(
- kernel.view(1, 1, 1, 1, se_h, se_w) == 0,
- reduction_max,
- )
- output, _ = torch.min(output, 4)
- output, _ = torch.min(output, 4)
+ excluded = kernel.view(1, 1, 1, 1, se_h, se_w) == 0
+ values_only = False
+ if not torch.jit.is_scripting():
+ values_only = _unfold_reduces_values_only(output, neighborhood, structuring_element is None, recording_grad)
+ if values_only:
+ # As in :func:`dilation`; subtracting the zero offsets changes no value, not even a ``-0.0``.
+ output = torch.where(excluded, reduction_max, output).amin((-2, -1)).to(compute_dtype)
+ else:
+ output = output - neighborhood
+ output.masked_fill_(excluded, reduction_max)
+ output, _ = torch.min(output, 4)
+ output, _ = torch.min(output, 4)
elif engine == "convolution":
B, C, H, W = tensor.size()
Hpad, Wpad = output.shape[-2:]
diff --git a/tests/morphology/test_dilation.py b/tests/morphology/test_dilation.py
index a3c983b16..feff8154f 100644
--- a/tests/morphology/test_dilation.py
+++ b/tests/morphology/test_dilation.py
@@ -567,6 +567,62 @@ class TestDilate(BaseTester):
assert torch.equal(op_script(tensor, kernel, engine="shift"), dilation(tensor, kernel, engine="shift"))
+ @pytest.mark.parametrize("kernel_shape", [(3, 3), (3, 4), (5, 5)])
+ @pytest.mark.parametrize("partial", [False, True])
+ @pytest.mark.parametrize("border_type", ["geodesic", "constant", "replicate"])
+ def test_unfold_engine_forward_only_matches_autograd_path(self, device, dtype, kernel_shape, partial, border_type):
+ if border_type == "replicate" and not supports_replicate_padding(device, dtype):
+ pytest.skip("replication_pad2d is unavailable for this device/dtype")
+ # Without a backward graph a flat ``unfold`` reduction takes ``amax``; it must match the ``torch.max``
+ # path, signed zeros included: the flat offsets turn every ``-0.0`` term into ``+0.0``. The sign and
+ # payload of a nan are the backend's choice (vectorised CPU bfloat16 arithmetic sets the sign bit).
+ nan, inf = float("nan"), float("inf")
+ tensor = torch.rand(2, 3, 9, 11, device=device, dtype=dtype)
+ tensor[0, 0, 2, 3] = nan
+ tensor[0, 1, 4, 5] = inf
+ tensor[1, 2, 0, 0] = -inf
+ tensor[1, 0, ::2] = -0.0
+ tensor[1, 0, 1::2] = 0.0
+ kernel = torch.ones(kernel_shape, device=device, dtype=dtype)
+ if partial:
+ kernel[0, 0] = 0.0
+ kernel[-1, 1] = 0.0
+
+ forward = dilation(tensor, kernel, border_type=border_type, engine="unfold")
+ recorded = dilation(tensor.clone().requires_grad_(True), kernel, border_type=border_type, engine="unfold")
+
+ recorded = recorded.detach()
+ torch.testing.assert_close(forward, recorded, rtol=0.0, atol=0.0, equal_nan=True)
+ numbers = ~forward.isnan()
+ assert torch.equal(torch.signbit(forward[numbers]), torch.signbit(recorded[numbers]))
+ assert forward.dtype == recorded.dtype
+
+ def test_unfold_engine_reduces_values_only_without_derivatives(self, device, dtype, monkeypatch):
+ calls = []
+ original = morphology_module._unfold_reduces_values_only
+
+ def wrapped(*args, **kwargs):
+ calls.append(original(*args, **kwargs))
+ return calls[-1]
+
+ monkeypatch.setattr(morphology_module, "_unfold_reduces_values_only", wrapped)
+
+ tensor = torch.rand(1, 1, 9, 11, device=device, dtype=dtype)
+ kernel = torch.ones(3, 3, device=device, dtype=dtype)
+
+ dilation(tensor, kernel, engine="unfold")
+ dilation(tensor, kernel, structuring_element=torch.zeros_like(kernel), engine="unfold")
+ with torch.enable_grad():
+ dilation(tensor.clone().requires_grad_(True), kernel, engine="unfold")
+ with torch.no_grad():
+ dilation(tensor.clone().requires_grad_(True), kernel, engine="unfold")
+ with torch.autograd.forward_ad.dual_level():
+ dilation(torch.autograd.forward_ad.make_dual(tensor, torch.rand_like(tensor)), kernel, engine="unfold")
+ torch.func.vmap(lambda x: dilation(x, kernel, engine="unfold"))(tensor[None])
+
+ plain = device.type in ("cpu", "cuda")
+ assert calls == [plain, False, False, plain, False, False]
+
def test_even_kernel_centre(self, device, dtype):
# `dilation` reflects the kernel contents but padded with the unreflected origin, so an
# even-sized kernel's default-origin window was anchored one pixel toward the top-left of
diff --git a/tests/morphology/test_erosion.py b/tests/morphology/test_erosion.py
index 7c558a90a..91688154a 100644
--- a/tests/morphology/test_erosion.py
+++ b/tests/morphology/test_erosion.py
@@ -551,6 +551,58 @@ class TestErode(BaseTester):
assert torch.equal(op_script(tensor, kernel, engine="shift"), erosion(tensor, kernel, engine="shift"))
+ @pytest.mark.parametrize("kernel_shape", [(3, 3), (3, 4), (5, 5)])
+ @pytest.mark.parametrize("partial", [False, True])
+ @pytest.mark.parametrize("border_type", ["geodesic", "constant", "replicate"])
+ def test_unfold_engine_forward_only_matches_autograd_path(self, device, dtype, kernel_shape, partial, border_type):
+ if border_type == "replicate" and not supports_replicate_padding(device, dtype):
+ pytest.skip("replication_pad2d is unavailable for this device/dtype")
+ # Without a backward graph a flat ``unfold`` reduction takes ``amin``; it must return the values of the
+ # ``torch.min`` path. A window tying ``+0.0`` with ``-0.0`` may return either zero, as on every engine.
+ nan, inf = float("nan"), float("inf")
+ tensor = torch.rand(2, 3, 9, 11, device=device, dtype=dtype)
+ tensor[0, 0, 2, 3] = nan
+ tensor[0, 1, 4, 5] = inf
+ tensor[1, 2, 0, 0] = -inf
+ tensor[1, 0, ::2] = -0.0
+ tensor[1, 0, 1::2] = 0.0
+ kernel = torch.ones(kernel_shape, device=device, dtype=dtype)
+ if partial:
+ kernel[0, 0] = 0.0
+ kernel[-1, 1] = 0.0
+
+ forward = erosion(tensor, kernel, border_type=border_type, engine="unfold")
+ recorded = erosion(tensor.clone().requires_grad_(True), kernel, border_type=border_type, engine="unfold")
+
+ torch.testing.assert_close(forward, recorded.detach(), rtol=0.0, atol=0.0, equal_nan=True)
+ assert forward.dtype == recorded.dtype
+
+ def test_unfold_engine_reduces_values_only_without_derivatives(self, device, dtype, monkeypatch):
+ calls = []
+ original = morphology_module._unfold_reduces_values_only
+
+ def wrapped(*args, **kwargs):
+ calls.append(original(*args, **kwargs))
+ return calls[-1]
+
+ monkeypatch.setattr(morphology_module, "_unfold_reduces_values_only", wrapped)
+
+ tensor = torch.rand(1, 1, 9, 11, device=device, dtype=dtype)
+ kernel = torch.ones(3, 3, device=device, dtype=dtype)
+
+ erosion(tensor, kernel, engine="unfold")
+ erosion(tensor, kernel, structuring_element=torch.zeros_like(kernel), engine="unfold")
+ with torch.enable_grad():
+ erosion(tensor.clone().requires_grad_(True), kernel, engine="unfold")
+ with torch.no_grad():
+ erosion(tensor.clone().requires_grad_(True), kernel, engine="unfold")
+ with torch.autograd.forward_ad.dual_level():
+ erosion(torch.autograd.forward_ad.make_dual(tensor, torch.rand_like(tensor)), kernel, engine="unfold")
+ torch.func.vmap(lambda x: erosion(x, kernel, engine="unfold"))(tensor[None])
+
+ plain = device.type in ("cpu", "cuda")
+ assert calls == [plain, False, False, plain, False, False]
+
def test_convention_erosion_does_not_reflect_kernel(self, device, dtype):
# `erosion` does not reflect the kernel: `out(p) = min_{q: kernel[q] != 0} x(p + (q - origin))`. The
# complement form `1 - erosion(1 - x, A)` separates the two conventions for the asymmetric `A`.