Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(morphology): compute engine=convolution in the promoted dtype (#4882)

Aryan Kumar943253a7344b
diff --git a/changelog.d/4882.breaking.md b/changelog.d/4882.breaking.md
new file mode 100644
index 000000000..2a458824d
--- /dev/null
+++ b/changelog.d/4882.breaking.md
@@ -0,0 +1 @@
+`kornia.morphology.dilation`, `erosion`, and the functions built on them (`opening`, `closing`, `gradient`, `top_hat`, `bottom_hat`) now compute `engine="convolution"` in the same promoted dtype as `engine="unfold"` and `engine="shift"`. Previously, `engine="convolution"` returned the image's own dtype for a mismatched-dtype kernel or `structuring_element` (for example, a float16 image with a float32 kernel returned float16), while the other two engines promoted to the wider dtype (float32) β€” so switching `engine` silently changed the result dtype. All three engines now agree.
diff --git a/kornia/morphology/morphology.py b/kornia/morphology/morphology.py
index 05d0104b3..e1d0263d7 100644
--- a/kornia/morphology/morphology.py
+++ b/kornia/morphology/morphology.py
@@ -182,11 +182,8 @@ def dilation(
names. :doc:`Conventions & Pitfalls </get-started/conventions>` maps both, and the kernel
conventions, onto scipy, scikit-image and OpenCV.
- Known defects: the finite ``max_val`` sentinel reaches the output in an empty window and once the
- data range approaches it (`#4734 <https://github.com/kornia/kornia/issues/4734>`_); a non-float
- image is not rejected (`#4735 <https://github.com/kornia/kornia/issues/4735>`_); and
- ``engine="convolution"`` returns the image dtype where ``unfold`` and ``shift`` return the dtype
- promoted with ``structuring_element``, or with ``kernel`` when none is given
- (`#4762 <https://github.com/kornia/kornia/issues/4762>`_).
+ data range approaches it (`#4734 <https://github.com/kornia/kornia/issues/4734>`_), and a non-float
+ image is not rejected (`#4735 <https://github.com/kornia/kornia/issues/4735>`_).
Args:
tensor: Image with shape :math:`(B, C, H, W)`.
@@ -284,12 +281,13 @@ def dilation(
elif engine == "convolution":
B, C, H, W = tensor.size()
h_pad, w_pad = output.shape[-2:]
- reshape_kernel = _neight2channels_like_kernel(kernel).to(dtype=output.dtype)
+ conv_input = output.to(dtype=compute_dtype)
+ reshape_kernel = _neight2channels_like_kernel(kernel).to(dtype=compute_dtype)
output, _ = F.conv2d(
- output.view(B * C, 1, h_pad, w_pad),
+ conv_input.view(B * C, 1, h_pad, w_pad),
reshape_kernel,
padding=0,
- bias=neighborhood.view(-1).flip(0).to(dtype=output.dtype),
+ bias=neighborhood.view(-1).flip(0).to(dtype=compute_dtype),
).max(dim=1)
output = output.view(B, C, H, W)
elif engine == "shift":
@@ -427,12 +425,13 @@ def erosion(
elif engine == "convolution":
B, C, H, W = tensor.size()
Hpad, Wpad = output.shape[-2:]
- reshape_kernel = _neight2channels_like_kernel(kernel).to(dtype=output.dtype)
+ conv_input = output.to(dtype=compute_dtype)
+ reshape_kernel = _neight2channels_like_kernel(kernel).to(dtype=compute_dtype)
output, _ = F.conv2d(
- output.view(B * C, 1, Hpad, Wpad),
+ conv_input.view(B * C, 1, Hpad, Wpad),
reshape_kernel,
padding=0,
- bias=-neighborhood.view(-1).to(dtype=output.dtype),
+ bias=-neighborhood.view(-1).to(dtype=compute_dtype),
).min(dim=1)
output = output.view(B, C, H, W)
elif engine == "shift":
diff --git a/tests/morphology/test_dilation.py b/tests/morphology/test_dilation.py
index e6dbd6d05..7b657ac8f 100644
--- a/tests/morphology/test_dilation.py
+++ b/tests/morphology/test_dilation.py
@@ -209,17 +209,19 @@ class TestDilate(BaseTester):
def test_convolution_engine_dtype_mismatch(self, device, dtype):
# engine="convolution" used to crash when tensor.dtype != kernel.dtype, because the
# conv weight/bias were built from kernel.dtype instead of the input's dtype. See #4541.
- # Passing a mismatched kernel must match casting the kernel to the input dtype up front;
- # that is the same computation, so the results are bitwise equal (no tolerance needed).
+ # It now computes in torch.promote_types(tensor.dtype, kernel.dtype), matching unfold and
+ # shift (#4762). Passing a mismatched kernel must match casting both operands to that
+ # promoted dtype up front; that is the same computation, so the results are bitwise equal.
other_dtype = torch.float16 if dtype == torch.float32 else torch.float32
+ compute_dtype = torch.promote_types(dtype, other_dtype)
tensor = torch.rand(1, 2, 5, 5, device=device, dtype=dtype)
kernel = torch.ones(3, 3, device=device, dtype=other_dtype)
result = dilation(tensor, kernel, engine="convolution")
- assert result.dtype == dtype
- self.assert_close(result, dilation(tensor, kernel.to(dtype), engine="convolution"))
+ assert result.dtype == compute_dtype
+ self.assert_close(result, dilation(tensor.to(compute_dtype), kernel.to(compute_dtype), engine="convolution"))
def test_auto_engine(self, device, dtype):
# engine="auto", the default, runs "unfold" on CUDA and the exact "shift" engine everywhere
@@ -847,13 +849,15 @@ class TestDilate(BaseTester):
op(frame, float_kernel, structuring_element=flat_se),
), (mask_dtype, op.__name__)
- def test_wart_convolution_engine_keeps_image_dtype_4762(self, device):
- # `unfold` and `shift` return the promoted dtype of the image and the kernel (or the structuring
- # element); `engine="convolution"` casts the kernel to the image's dtype instead, so the result dtype
- # depends on the engine. Tracked in #4762. Dtypes are explicit, so this pin takes `device` only.
+ @pytest.mark.parametrize("engine", ["unfold", "shift", "convolution"])
+ def test_convention_engines_return_promoted_dtype_4762(self, device, engine):
+ # Every engine computes in the dtype promoted from the image and the kernel, or the structuring
+ # element when one is given, so the result dtype does not depend on `engine` (#4762). Dtypes are
+ # explicit, so this pin takes `device` only.
tensor = torch.rand(1, 1, 4, 5, generator=torch.Generator().manual_seed(0)).to(device, torch.float16)
- kernel = torch.ones(3, 3, device=device)
+ half_kernel = torch.ones(3, 3, device=device, dtype=torch.float16)
+ structuring_element = torch.zeros(3, 3, device=device)
for op in (dilation, erosion):
- assert op(tensor, kernel, engine="unfold").dtype == torch.float32, op.__name__
- assert op(tensor, kernel, engine="shift").dtype == torch.float32, op.__name__
- assert op(tensor, kernel, engine="convolution").dtype == torch.float16, op.__name__
+ assert op(tensor, half_kernel.float(), engine=engine).dtype == torch.float32, op.__name__
+ actual = op(tensor, half_kernel, structuring_element=structuring_element, engine=engine)
+ assert actual.dtype == torch.float32, op.__name__
diff --git a/tests/morphology/test_erosion.py b/tests/morphology/test_erosion.py
index 5348e9d20..fc8a5c7af 100644
--- a/tests/morphology/test_erosion.py
+++ b/tests/morphology/test_erosion.py
@@ -195,17 +195,19 @@ class TestErode(BaseTester):
def test_convolution_engine_dtype_mismatch(self, device, dtype):
# engine="convolution" used to crash when tensor.dtype != kernel.dtype, because the
# conv weight/bias were built from kernel.dtype instead of the input's dtype. See #4541.
- # Passing a mismatched kernel must match casting the kernel to the input dtype up front;
- # that is the same computation, so the results are bitwise equal (no tolerance needed).
+ # It now computes in torch.promote_types(tensor.dtype, kernel.dtype), matching unfold and
+ # shift (#4762). Passing a mismatched kernel must match casting both operands to that
+ # promoted dtype up front; that is the same computation, so the results are bitwise equal.
other_dtype = torch.float16 if dtype == torch.float32 else torch.float32
+ compute_dtype = torch.promote_types(dtype, other_dtype)
tensor = torch.rand(1, 2, 5, 5, device=device, dtype=dtype)
kernel = torch.ones(3, 3, device=device, dtype=other_dtype)
result = erosion(tensor, kernel, engine="convolution")
- assert result.dtype == dtype
- self.assert_close(result, erosion(tensor, kernel.to(dtype), engine="convolution"))
+ assert result.dtype == compute_dtype
+ self.assert_close(result, erosion(tensor.to(compute_dtype), kernel.to(compute_dtype), engine="convolution"))
def test_auto_engine(self, device, dtype):
# engine="auto", the default, runs "unfold" on CUDA and the exact "shift" engine everywhere