Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(filters): support empty batches with per-sample kernels (#5857)

renta0426f200aaa12bbd
diff --git a/changelog.d/5857.fixed.md b/changelog.d/5857.fixed.md
new file mode 100644
index 000000000..dba76c44d
--- /dev/null
+++ b/changelog.d/5857.fixed.md
@@ -0,0 +1 @@
+`filter2d`, `filter2d_separable` and `filter3d` accept an empty batch with an empty per-sample kernel, so `gaussian_blur2d` with a `(0, 2)` sigma, `motion_blur`, `motion_blur3d`, `RandomGaussianBlur` and fixed-size `RandomMotionBlur` and `RandomMotionBlur3D` return an empty batch instead of raising `RuntimeError: cannot reshape tensor of 0 elements`. Ranged motion-kernel sampling remains outside this fix. Part of #4429.
diff --git a/kornia/filters/filter.py b/kornia/filters/filter.py
index 9d6c62504..4cb7cdf89 100644
--- a/kornia/filters/filter.py
+++ b/kornia/filters/filter.py
@@ -102,6 +102,8 @@ def filter2d(
- A :math:`(1, kH, kW)` kernel is shared by the whole batch, and a :math:`(B, kH, kW)` kernel gives each
sample its own, shared by the sample's channels; there are no per-channel kernels. Any other kernel batch
raises.
+ An empty batch accepts either a shared kernel or an empty per-sample kernel and retains the usual output
+ spatial size, dtype promotion and gradient connections to both input and kernel.
- ``normalized=True`` divides each kernel by the sum of its absolute values, so a zero-sum derivative kernel
keeps its sign.
- ``border_type``, ``padding`` and ``behaviour`` are case-insensitive: ``'REFLECT'``, ``'SAME'`` and
@@ -192,6 +194,11 @@ def filter2d(
padding_shape: list[int] = _compute_padding([height, width])
input = F.pad(input, padding_shape, mode=border_type)
+ # An empty per-sample kernel needs one structural row for nonzero convolution groups. Reduce after
+ # normalization to avoid normalizing a zero kernel, while keeping the original kernel in the autograd graph.
+ if tmp_kernel.shape[0] == 0:
+ tmp_kernel = tmp_kernel.sum(dim=0, keepdim=True)
+
# kernel and input tensor reshape to align element-wise or batch-wise params
tmp_kernel = tmp_kernel.reshape(-1, 1, height, width)
input = input.reshape(-1, tmp_kernel.size(0), input.size(-2), input.size(-1))
@@ -375,6 +382,10 @@ def filter3d(
padding_shape: list[int] = _compute_padding([depth, height, width])
input_pad = F.pad(input, padding_shape, mode=border_type)
+ # As in filter2d, preserve the empty kernel's gradient connection without using zero convolution groups.
+ if tmp_kernel.shape[0] == 0:
+ tmp_kernel = tmp_kernel.sum(dim=0, keepdim=True)
+
# kernel and input tensor reshape to align element-wise or batch-wise params
tmp_kernel = tmp_kernel.reshape(-1, 1, depth, height, width)
input_pad = input_pad.reshape(-1, tmp_kernel.size(0), input_pad.size(-3), input_pad.size(-2), input_pad.size(-1))
diff --git a/kornia/filters/kernels_geometry.py b/kornia/filters/kernels_geometry.py
index b21457e6f..894453a4b 100644
--- a/kornia/filters/kernels_geometry.py
+++ b/kornia/filters/kernels_geometry.py
@@ -114,7 +114,8 @@ def get_motion_kernel2d(
step = (1 - 2 * direction) / (kernel_size - 1)
positions = torch.arange(kernel_size, device=direction.device, dtype=direction.dtype)
k = direction[:, None] + step[:, None] * positions
- kernel = F.pad(k[:, None], [0, 0, kernel_size // 2, kernel_size // 2, 0, 0])
+ # Pad only the kernel axes: torch 2.5.1 and 2.9.1 reject any pad of an empty batch axis, even a zero one.
+ kernel = F.pad(k[:, None], [0, 0, kernel_size // 2, kernel_size // 2])
expected_shape = torch.Size([direction.size(0), *kernel_tuple])
KORNIA_CHECK(kernel.shape == expected_shape, f"Kernel shape should be {expected_shape}. Got {kernel.shape}")
@@ -259,9 +260,8 @@ def get_motion_kernel3d(
# kernel[:, kernel_size // 2, kernel_size // 2, :] = torch.stack(
# [(direction + ((1 - 2 * direction) / (kernel_size - 1)) * i) for i in range(kernel_size)], dim=-1)
k = torch.stack([(direction + ((1 - 2 * direction) / (kernel_size - 1)) * i) for i in range(kernel_size)], -1)
- kernel = F.pad(
- k[:, None, None], [0, 0, kernel_size // 2, kernel_size // 2, kernel_size // 2, kernel_size // 2, 0, 0]
- )
+ # Pad only the kernel axes, as in get_motion_kernel2d.
+ kernel = F.pad(k[:, None, None], [0, 0, kernel_size // 2, kernel_size // 2, kernel_size // 2, kernel_size // 2])
expected_shape = torch.Size([direction.size(0), *kernel_tuple])
KORNIA_CHECK(kernel.shape == expected_shape, f"Kernel shape should be {expected_shape}. Got {kernel.shape}")
diff --git a/tests/augmentation/test_base.py b/tests/augmentation/test_base.py
index d3f75af2b..d6136ff1b 100644
--- a/tests/augmentation/test_base.py
+++ b/tests/augmentation/test_base.py
@@ -1238,6 +1238,12 @@ class TestConventionAugmentationBase2D(BaseTester):
pytest.param(lambda: K.RandomEqualize(p=1.0), (0, 3, 6, 8), id="RandomEqualize"),
pytest.param(lambda: K.RandomPosterize(p=1.0), (0, 3, 6, 8), id="RandomPosterize"),
pytest.param(lambda: K.RandomSharpness(p=1.0), (0, 3, 6, 8), id="RandomSharpness"),
+ pytest.param(
+ lambda: K.RandomGaussianBlur((3, 5), (0.5, 1.5), "constant", p=1.0),
+ (0, 3, 6, 8),
+ id="RandomGaussianBlur",
+ ),
+ pytest.param(lambda: K.RandomMotionBlur(3, 35.0, 0.5, p=1.0), (0, 3, 6, 8), id="RandomMotionBlur"),
],
)
def test_convention_zero_batch_is_empty_in_empty_out(self, augmentation, shape, device, dtype):
diff --git a/tests/filters/test_filters.py b/tests/filters/test_filters.py
index 5d8019dd0..84bca4b57 100644
--- a/tests/filters/test_filters.py
+++ b/tests/filters/test_filters.py
@@ -56,6 +56,8 @@ from kornia.filters import (
get_spatial_gradient_kernel3d,
laplacian,
laplacian_1d,
+ motion_blur,
+ motion_blur3d,
spatial_gradient,
spatial_gradient3d,
)
@@ -2650,3 +2652,90 @@ class TestConventionsKernels(BaseTester):
expected[..., -1] = 0.0
self.assert_close(kernel, expected)
assert int((kernel == 0).sum()) == (2 if ndim == 1 else 4)
+
+
+class TestEmptyBatchPerSampleKernel(BaseTester):
+ """An empty batch with an empty per-sample kernel, sigma or angle returns an empty output (#4429)."""
+
+ # The first parameter after the image reaches the convolution weight, so its gradient must be connected.
+ @pytest.mark.parametrize(
+ ("op", "image_shape", "param_shapes", "expected_shape"),
+ [
+ pytest.param(lambda x, k: filter2d(x, k, "constant"), (0, 3, 9, 13), [(0, 3, 5)], (0, 3, 9, 13), id="2d"),
+ pytest.param(
+ lambda x, k: filter2d(x, k, "constant", True, "valid", "conv"),
+ (0, 3, 9, 13),
+ [(0, 3, 5)],
+ (0, 3, 7, 9),
+ id="2d-valid",
+ ),
+ pytest.param(
+ lambda x, kx, ky: filter2d_separable(x, kx, ky, "constant", padding="valid"),
+ (0, 3, 9, 13),
+ [(0, 5), (0, 3)],
+ (0, 3, 7, 9),
+ id="separable",
+ ),
+ pytest.param(
+ lambda x, k: filter3d(x, k, "constant", True),
+ (0, 2, 5, 9, 13),
+ [(0, 3, 3, 5)],
+ (0, 2, 5, 9, 13),
+ id="3d",
+ ),
+ pytest.param(
+ lambda x, s: gaussian_blur2d(x, (3, 5), s, "constant"),
+ (0, 3, 9, 13),
+ [(0, 2)],
+ (0, 3, 9, 13),
+ id="gaussian",
+ ),
+ pytest.param(
+ lambda x, d, a: motion_blur(x, 3, a, d, "constant"),
+ (0, 3, 9, 13),
+ [(0,), (0,)],
+ (0, 3, 9, 13),
+ id="motion",
+ ),
+ pytest.param(
+ lambda x, d, a: motion_blur3d(x, 3, a, d, "constant"),
+ (0, 2, 5, 9, 13),
+ [(0,), (0, 3)],
+ (0, 2, 5, 9, 13),
+ id="motion3d",
+ ),
+ pytest.param(
+ lambda x, d, a: motion_blur3d(x, 3, a, d, "constant", mode="bilinear"),
+ (0, 2, 5, 9, 13),
+ [(0,), (0, 3)],
+ (0, 2, 5, 9, 13),
+ id="motion3d-bilinear",
+ ),
+ ],
+ )
+ def test_empty_batch_4429(self, op, image_shape, param_shapes, expected_shape, device, dtype):
+ image = torch.empty(image_shape, device=device, dtype=dtype, requires_grad=True)
+ params = [torch.empty(shape, device=device, dtype=dtype, requires_grad=True) for shape in param_shapes]
+ output = op(image, *params)
+ assert output.shape == expected_shape
+ assert output.dtype == dtype
+ assert output.device == device
+ output.sum().backward()
+ for value in (image, params[0]):
+ assert value.grad is not None
+ assert value.grad.shape == value.shape
+
+ @pytest.mark.parametrize(("op", "spatial"), [(filter2d, (9, 13)), (filter3d, (5, 9, 13))])
+ @pytest.mark.parametrize(("batch", "kernel_batch"), [(0, 2), (2, 0)])
+ def test_empty_kernel_batch_must_match_4429(self, op, spatial, batch, kernel_batch, device, dtype):
+ image = torch.empty(batch, 3, *spatial, device=device, dtype=dtype)
+ kernel = torch.empty(kernel_batch, *([3] * len(spatial)), device=device, dtype=dtype)
+ with pytest.raises(BaseError, match="kernel batch must be 1 or the input batch"):
+ op(image, kernel, "constant")
+
+ @pytest.mark.parametrize("batch", [0, 2])
+ def test_dynamo_4429(self, batch, device, dtype, torch_optimizer):
+ image = torch.rand(batch, 3, 9, 13, device=device, dtype=dtype)
+ kernel = torch.rand(batch, 3, 5, device=device, dtype=dtype) + 0.1
+ op = torch_optimizer(filter2d)
+ self.assert_close(op(image, kernel, "constant", True), filter2d(image, kernel, "constant", True))