Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(filters): keep blur_pool2d and max_blur_pool2d outputs at ceil(H / stride) for even kernel sizes (#5184)

εŒΊζ’“ηd34c91be58e4
diff --git a/changelog.d/5184.breaking.md b/changelog.d/5184.breaking.md
new file mode 100644
index 000000000..379c1ad20
--- /dev/null
+++ b/changelog.d/5184.breaking.md
@@ -0,0 +1,9 @@
+`blur_pool2d`, `BlurPool2D`, `max_blur_pool2d` and `MaxBlurPool2D` with an even kernel size now return
+`ceil(n / stride)` samples along each axis, as odd kernel sizes already did, where `n` is the input height or width,
+reduced by `max_pool_size - 1` for the max variants. The input is zero-padded by `(k - 1) // 2` pixels before and
+`k // 2` after, the amounts antialiased-cnns uses (antialiased-cnns pads by reflection by default; kornia pads with
+zeros). Previously both sides were padded by `(k - 1) // 2`, so an axis lost its last sample whenever `n - 1` was a
+multiple of the stride. At stride 1 that is every axis: a 7x10 map returned 6x9 and now returns 7x10. At stride 2 only
+an odd `n` is affected: `blur_pool2d` on a 7x10 map returned 3x5 and now returns 4x5 while 8x8 is unchanged, and
+`max_blur_pool2d` with the default `max_pool_size=2` on an 8x8 map returned 3x3 and now returns 4x4. The old output is
+always the leading block of the new one. Odd kernel sizes are unchanged, bit for bit (#5166).
diff --git a/changelog.d/5184.fixed.md b/changelog.d/5184.fixed.md
new file mode 100644
index 000000000..8e276b6e1
--- /dev/null
+++ b/changelog.d/5184.fixed.md
@@ -0,0 +1,2 @@
+`edge_aware_blur_pool2d` and `EdgeAwareBlurPool2D` accept an even `kernel_size` and keep the input shape, instead of
+raising a `RuntimeError` about mismatched tensor sizes.
diff --git a/kornia/filters/blur_pool.py b/kornia/filters/blur_pool.py
index 683e070e1..4768fb78e 100644
--- a/kornia/filters/blur_pool.py
+++ b/kornia/filters/blur_pool.py
@@ -24,7 +24,6 @@ from torch import nn
from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SHAPE
from .kernels import get_pascal_kernel_2d
-from .median import _compute_zero_padding # TODO: Move to proper place
__all__ = [
"BlurPool2D",
@@ -47,15 +46,11 @@ class BlurPool2D(nn.Module):
Shape:
- Input: :math:`(B, C, H, W)`
- - Output: :math:`(N, C, H_{out}, W_{out})`, where
+ - Output: :math:`(B, C, H_{out}, W_{out})`, where
.. math::
- H_{out} = \left\lfloor\frac{H_{in} + 2 \times \text{kernel\_size//2}[0] -
- \text{kernel\_size}[0]}{\text{stride}[0]} + 1\right\rfloor
-
- .. math::
- W_{out} = \left\lfloor\frac{W_{in} + 2 \times \text{kernel\_size//2}[1] -
- \text{kernel\_size}[1]}{\text{stride}[1]} + 1\right\rfloor
+ H_{out} = \left\lceil\frac{H}{\text{stride}}\right\rceil, \quad
+ W_{out} = \left\lceil\frac{W}{\text{stride}}\right\rceil
Examples:
>>> from kornia.filters.blur_pool import BlurPool2D
@@ -89,9 +84,9 @@ class BlurPool2D(nn.Module):
input width.
Returns:
- Downsampled tensor with shape :math:`(B, C, H_{out}, W_{out})`.
- :math:`H_{out}` and :math:`W_{out}` are determined by the kernel
- size, padding used inside the helper, and ``self.stride``.
+ Downsampled tensor of shape :math:`(B, C, H_{out}, W_{out})`, with
+ the sizes given in the Shape section of the class. They depend only
+ on the input size and ``self.stride``.
"""
self.kernel = torch.as_tensor(self.kernel, device=input.device, dtype=input.dtype)
return _blur_pool_by_kernel2d(input, self.kernel.repeat((input.shape[1], 1, 1, 1)), self.stride)
@@ -112,7 +107,11 @@ class MaxBlurPool2D(nn.Module):
Shape:
- Input: :math:`(B, C, H, W)`
- - Output: :math:`(B, C, H / stride, W / stride)`
+ - Output: :math:`(B, C, H_{out}, W_{out})`, where
+
+ .. math::
+ H_{out} = \left\lceil\frac{H - \text{max\_pool\_size} + 1}{\text{stride}}\right\rceil, \quad
+ W_{out} = \left\lceil\frac{W - \text{max\_pool\_size} + 1}{\text{stride}}\right\rceil
Returns:
torch.Tensor: the transformed torch.tensor.
@@ -156,9 +155,10 @@ class MaxBlurPool2D(nn.Module):
:math:`H` is the height, and :math:`W` is the width.
Returns:
- Tensor with shape :math:`(B, C, H_{out}, W_{out})` after max
- pooling and blur pooling. The spatial output sizes depend on the
- configured max-pool size, stride, blur kernel, and ``ceil_mode``.
+ Tensor of shape :math:`(B, C, H_{out}, W_{out})` after max pooling
+ and blur pooling, with the sizes given in the Shape section of the
+ class. They depend only on the input size, ``self.max_pool_size``
+ and ``self.stride``.
"""
self.kernel = torch.as_tensor(self.kernel, device=input.device, dtype=input.dtype)
return _max_blur_pool_by_kernel2d(
@@ -230,22 +230,15 @@ def blur_pool2d(input: torch.Tensor, kernel_size: tuple[int, int] | int, stride:
Shape:
- Input: :math:`(B, C, H, W)`
- - Output: :math:`(N, C, H_{out}, W_{out})`, where
+ - Output: :math:`(B, C, H_{out}, W_{out})`, where
.. math::
- H_{out} = \left\lfloor\frac{H_{in} + 2 \times \text{kernel\_size//2}[0] -
- \text{kernel\_size}[0]}{\text{stride}[0]} + 1\right\rfloor
-
- .. math::
- W_{out} = \left\lfloor\frac{W_{in} + 2 \times \text{kernel\_size//2}[1] -
- \text{kernel\_size}[1]}{\text{stride}[1]} + 1\right\rfloor
+ H_{out} = \left\lceil\frac{H}{\text{stride}}\right\rceil, \quad
+ W_{out} = \left\lceil\frac{W}{\text{stride}}\right\rceil
Returns:
the transformed torch.Tensor.
- .. note::
- This function is tested against https://github.com/adobe/antialiased-cnns.
-
.. note::
See a working example `here <https://www.kornia.org/tutorials/nbs/filtering_operators.html>`__.
@@ -283,9 +276,6 @@ def max_blur_pool2d(
max_pool_size: the kernel size for max pooling.
ceil_mode: should be true to match output size of conv2d with same kernel size.
- .. note::
- This function is tested against https://github.com/adobe/antialiased-cnns.
-
.. note::
See a working example `here <https://www.kornia.org/tutorials/nbs/filtering_operators.html>`__.
@@ -304,6 +294,20 @@ def max_blur_pool2d(
return _max_blur_pool_by_kernel2d(input, kernel, stride, max_pool_size, ceil_mode)
+def _blur_pool_conv2d(input: torch.Tensor, kernel: torch.Tensor, stride: int) -> torch.Tensor:
+ """Correlate every channel with its kernel at ``stride``, zero-padded so the output keeps ``ceil(H / stride)`` rows.
+
+ The padding is ``(k - 1) // 2`` pixels before and ``k // 2`` after along each spatial axis, the amounts
+ antialiased-cnns uses. For an odd ``k`` the two are equal and ``F.conv2d`` pads itself. An even ``k`` needs one
+ pixel more after than before, which ``F.pad`` adds.
+ """
+ ky, kx = kernel.shape[-2], kernel.shape[-1]
+ if ky % 2 == 1 and kx % 2 == 1:
+ return F.conv2d(input, kernel, padding=((ky - 1) // 2, (kx - 1) // 2), stride=stride, groups=input.shape[1])
+ input = F.pad(input, ((kx - 1) // 2, kx // 2, (ky - 1) // 2, ky // 2))
+ return F.conv2d(input, kernel, stride=stride, groups=input.shape[1])
+
+
def _blur_pool_by_kernel2d(input: torch.Tensor, kernel: torch.Tensor, stride: int) -> torch.Tensor:
"""Compute blur_pool by a given :math:`CxC_{out}xNxN` kernel."""
KORNIA_CHECK(
@@ -311,8 +315,7 @@ def _blur_pool_by_kernel2d(input: torch.Tensor, kernel: torch.Tensor, stride: in
f"Invalid kernel shape. Expect CxC_(out, None)xNxN, Got {kernel.shape}",
)
- padding = _compute_zero_padding((kernel.shape[-2], kernel.shape[-1]))
- return F.conv2d(input, kernel, padding=padding, stride=stride, groups=input.shape[1])
+ return _blur_pool_conv2d(input, kernel, stride)
def _max_blur_pool_by_kernel2d(
@@ -326,8 +329,7 @@ def _max_blur_pool_by_kernel2d(
# compute local maxima
input = F.max_pool2d(input, kernel_size=max_pool_size, padding=0, stride=1, ceil_mode=ceil_mode)
# blur and downsample
- padding = _compute_zero_padding((kernel.shape[-2], kernel.shape[-1]))
- return F.conv2d(input, kernel, padding=padding, stride=stride, groups=input.size(1))
+ return _blur_pool_conv2d(input, kernel, stride)
def edge_aware_blur_pool2d(
diff --git a/tests/filters/test_blur_pool.py b/tests/filters/test_blur_pool.py
index 2596e463d..9d1e5e054 100644
--- a/tests/filters/test_blur_pool.py
+++ b/tests/filters/test_blur_pool.py
@@ -15,6 +15,8 @@
# limitations under the License.
#
+import math
+
import pytest
import torch
@@ -30,6 +32,27 @@ from kornia.filters import (
from testing.base import BaseTester
+def _zero_padded_reference(x: torch.Tensor, k: int, s: int) -> torch.Tensor:
+ """Blur pool as adobe/antialiased-cnns BlurPool with pad_type='zero', in float64 on CPU.
+
+ Pads ``(k - 1) // 2`` zeros before and ``k // 2`` after along each spatial axis, then correlates with the normalised
+ Pascal kernel at stride ``s``, one output pixel at a time, without F.pad or F.conv2d.
+ """
+ x = x.cpu().double()
+ *lead, h, w = x.shape
+ taps = torch.tensor([math.comb(k - 1, i) for i in range(k)], dtype=torch.float64)
+ kernel = torch.outer(taps, taps) / (2.0 ** (2 * (k - 1)))
+ before = (k - 1) // 2
+ padded = torch.zeros(*lead, h + k - 1, w + k - 1, dtype=torch.float64)
+ padded[..., before : before + h, before : before + w] = x
+ h_out, w_out = math.ceil(h / s), math.ceil(w / s)
+ out = torch.zeros(*lead, h_out, w_out, dtype=torch.float64)
+ for i in range(h_out):
+ for j in range(w_out):
+ out[..., i, j] = (padded[..., i * s : i * s + k, j * s : j * s + k] * kernel).sum(dim=(-2, -1))
+ return out
+
+
class TestMaxBlurPool(BaseTester):
@pytest.mark.parametrize("kernel_size", [3, (5, 5)])
@pytest.mark.parametrize("ceil_mode", [True, False])
@@ -61,10 +84,11 @@ class TestMaxBlurPool(BaseTester):
assert actual.is_contiguous()
- def test_gradcheck(self, device):
+ @pytest.mark.parametrize("kernel_size", [3, 4])
+ def test_gradcheck(self, kernel_size, device):
batch_size, channels, height, width = 1, 2, 5, 4
img = torch.rand(batch_size, channels, height, width, device=device, dtype=torch.float64)
- self.gradcheck(max_blur_pool2d, (img, 3))
+ self.gradcheck(max_blur_pool2d, (img, kernel_size))
@pytest.mark.parametrize("kernel_size", [(3, 3), 5])
@pytest.mark.parametrize("batch_size", [1, 2])
@@ -77,7 +101,7 @@ class TestMaxBlurPool(BaseTester):
expected = op(img, kernel_size)
self.assert_close(actual, expected)
- @pytest.mark.parametrize("kernel_size", [3, (5, 5)])
+ @pytest.mark.parametrize("kernel_size", [3, 4, (5, 5)])
@pytest.mark.parametrize("batch_size", [1, 2])
@pytest.mark.parametrize("ceil_mode", [True, False])
def test_dynamo(self, batch_size, kernel_size, ceil_mode, device, dtype, torch_optimizer):
@@ -87,6 +111,28 @@ class TestMaxBlurPool(BaseTester):
self.assert_close(op(data), op_optimized(data))
+ @pytest.mark.parametrize("kernel_size", [2, 3, 4])
+ @pytest.mark.parametrize("stride", [1, 2])
+ @pytest.mark.parametrize("max_pool_size", [1, 2, 3])
+ def test_even_kernel_keeps_ceil_size_5166(self, kernel_size, stride, max_pool_size, device, dtype):
+ # An even kernel_size used to lose a row and a column: (7, 10) with kernel_size 2, stride 1, max_pool_size 1
+ # returned (6, 9). The size is ceil((H - max_pool_size + 1) / stride) for every kernel size.
+ data = torch.rand(1, 2, 7, 10, device=device, dtype=dtype)
+ actual = max_blur_pool2d(data, kernel_size, stride=stride, max_pool_size=max_pool_size)
+ expected = tuple(math.ceil((n - max_pool_size + 1) / stride) for n in (7, 10))
+ assert actual.shape == (1, 2, *expected)
+
+ @pytest.mark.parametrize("kernel_size", [2, 3, 4])
+ @pytest.mark.parametrize("stride", [1, 2])
+ @pytest.mark.parametrize("max_pool_size", [1, 2, 3])
+ def test_even_kernel_is_max_pool_then_blur_pool_5166(self, kernel_size, stride, max_pool_size, device, dtype):
+ # Max pooling at stride 1, then the float64 zero-padded reference blur pool instead of kornia's own helper.
+ data = torch.rand(1, 2, 7, 10, device=device, dtype=dtype)
+ pooled = torch.nn.functional.max_pool2d(data.cpu().double(), max_pool_size, stride=1)
+ expected = _zero_padded_reference(pooled, kernel_size, stride)
+ actual = max_blur_pool2d(data, kernel_size, stride=stride, max_pool_size=max_pool_size)
+ self.assert_close(actual, expected.to(device=device, dtype=dtype))
+
class TestBlurPool(BaseTester):
@pytest.mark.parametrize("kernel_size", [3, (5, 5)])
@@ -119,10 +165,11 @@ class TestBlurPool(BaseTester):
actual = blur_pool2d(inp, 3)
assert actual.is_contiguous()
- def test_gradcheck(self, device):
+ @pytest.mark.parametrize("kernel_size", [3, 4])
+ def test_gradcheck(self, kernel_size, device):
batch_size, channels, height, width = 1, 2, 5, 4
img = torch.rand(batch_size, channels, height, width, device=device, dtype=torch.float64)
- self.gradcheck(blur_pool2d, (img, 3))
+ self.gradcheck(blur_pool2d, (img, kernel_size))
@pytest.mark.parametrize("kernel_size", [3, (5, 5)])
@pytest.mark.parametrize("batch_size", [1, 2])
@@ -136,7 +183,7 @@ class TestBlurPool(BaseTester):
expected = op(img, kernel_size)
self.assert_close(actual, expected)
- @pytest.mark.parametrize("kernel_size", [3, (5, 5)])
+ @pytest.mark.parametrize("kernel_size", [3, 4, (5, 5)])
@pytest.mark.parametrize("batch_size", [1, 2])
@pytest.mark.parametrize("stride", [1, 2])
def test_dynamo(self, batch_size, kernel_size, stride, device, dtype, torch_optimizer):
@@ -146,6 +193,22 @@ class TestBlurPool(BaseTester):
self.assert_close(op(data), op_optimized(data))
+ @pytest.mark.parametrize("kernel_size", [1, 2, 3, 4, 5, 6])
+ @pytest.mark.parametrize("stride", [1, 2, 3])
+ def test_even_kernel_keeps_ceil_size_5166(self, kernel_size, stride, device, dtype):
+ # An even kernel_size used to lose a row and a column: (7, 10) returned (6, 9) at stride 1 and (3, 5) at
+ # stride 2. The size is ceil(H / stride) x ceil(W / stride) for every kernel size.
+ data = torch.rand(1, 2, 7, 10, device=device, dtype=dtype)
+ actual = blur_pool2d(data, kernel_size, stride=stride)
+ assert actual.shape == (1, 2, math.ceil(7 / stride), math.ceil(10 / stride))
+
+ @pytest.mark.parametrize("kernel_size", [2, 3, 4, 5])
+ @pytest.mark.parametrize("stride", [1, 2, 3])
+ def test_matches_zero_padded_reference_5166(self, kernel_size, stride, device, dtype):
+ data = torch.rand(2, 3, 7, 10, device=device, dtype=dtype)
+ expected = _zero_padded_reference(data, kernel_size, stride)
+ self.assert_close(blur_pool2d(data, kernel_size, stride=stride), expected.to(device=device, dtype=dtype))
+
class TestEdgeAwareBlurPool(BaseTester):
@pytest.mark.parametrize("kernel_size", [3, (5, 5)])
@@ -194,9 +257,10 @@ class TestEdgeAwareBlurPool(BaseTester):
expected = op(img, kernel_size)
self.assert_close(actual, expected)
- def test_gradcheck(self, device):
+ @pytest.mark.parametrize("kernel_size", [3, 4])
+ def test_gradcheck(self, kernel_size, device):
img = torch.rand((1, 2, 5, 4), device=device, dtype=torch.float64)
- self.gradcheck(edge_aware_blur_pool2d, (img, 3))
+ self.gradcheck(edge_aware_blur_pool2d, (img, kernel_size))
def test_smooth(self, device, dtype):
img = torch.ones(1, 1, 5, 5, device=device, dtype=dtype)
@@ -204,7 +268,7 @@ class TestEdgeAwareBlurPool(BaseTester):
blur = edge_aware_blur_pool2d(img, kernel_size=3, edge_threshold=32.0)
self.assert_close(img, blur)
- @pytest.mark.parametrize("kernel_size", [3, (5, 5)])
+ @pytest.mark.parametrize("kernel_size", [3, 4, (5, 5)])
@pytest.mark.parametrize("batch_size", [1, 2])
def test_dynamo(self, batch_size, kernel_size, device, dtype, torch_optimizer):
op = edge_aware_blur_pool2d
@@ -213,3 +277,21 @@ class TestEdgeAwareBlurPool(BaseTester):
op_optimized = torch_optimizer(op)
self.assert_close(op(data), op_optimized(data))
+
+ @pytest.mark.parametrize("kernel_size", [2, 4])
+ def test_even_kernel_keeps_shape_5166(self, kernel_size, device, dtype):
+ # blur_pool2d(stride=1) used to return one row and one column less for an even kernel_size, and the fusion
+ # with the input raised a shape error.
+ data = torch.rand(1, 3, 8, 8, device=device, dtype=dtype)
+ assert edge_aware_blur_pool2d(data, kernel_size).shape == data.shape
+
+ @pytest.mark.parametrize("kernel_size", [2, 4])
+ @pytest.mark.parametrize("shape", [(8, 8), (8, 9)])
+ def test_even_kernel_matches_blur_without_edges_5166(self, kernel_size, shape, device, dtype):
+ # With edge_threshold=1e6 no pixel is an edge, so the output is the stride-1 blur of the input reflect-padded by
+ # 2 pixels, cropped back to the input size.
+ data = torch.rand(1, 3, *shape, device=device, dtype=dtype) + 0.1
+ actual = edge_aware_blur_pool2d(data, kernel_size, edge_threshold=1e6)
+ padded = torch.nn.functional.pad(data.cpu().double(), (2, 2, 2, 2), mode="reflect")
+ expected = _zero_padded_reference(padded, kernel_size, 1)[..., 2:-2, 2:-2]
+ self.assert_close(actual, expected.to(device=device, dtype=dtype))