π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(filters): reject a kernel batch that is neither 1 nor the input batch (#5359)
εΊζ’η13fa1347dc23
diff --git a/changelog.d/5359.breaking.md b/changelog.d/5359.breaking.mdnew file mode 100644index 000000000..24b979053--- /dev/null+++ b/changelog.d/5359.breaking.md@@ -0,0 +1,8 @@+`filter2d`, `filter3d`, `filter2d_separable` and `fft_conv` now raise a `BaseError` naming both sizes when the kernel+batch is neither 1 nor the input batch (#5154). Inputs that used to return a value now raise: `filter2d`,+`filter2d_separable` and `filter3d` applied a kernel batch that divides the input batch cyclically, sample `i`+filtered with kernel `i % Bk`, and `fft_conv` broadcast one input sample over a batch of kernels, one output per+kernel. The same holds for the blurs that build one kernel per sample: `gaussian_blur2d` with a tensor `sigma`, and+`motion_blur` and `motion_blur3d` with tensor `angle` and `direction`, whose batch divides the input batch. The other+kernel batches used to raise torch's `RuntimeError` and now raise the `BaseError`, which is not a `RuntimeError`. The+documented `(1, kH, kW)` and `(B, kH, kW)` kernels are unchanged.diff --git a/kornia/filters/filter.py b/kornia/filters/filter.pyindex 0ab1353a0..17a27ced3 100644--- a/kornia/filters/filter.py+++ b/kornia/filters/filter.py@@ -51,6 +51,18 @@ def _compute_padding(kernel_size: list[int]) -> list[int]:return out_padding+def _check_kernel_batch(input: torch.Tensor, kernel: torch.Tensor) -> None:+ """Check that the kernel batch is 1 or the input batch."""+ # Format the sizes only on failure: an f-string evaluated on every call makes Dynamo specialize the batch size,+ # so a dynamic-shape torch.compile would recompile for each new batch.+ if kernel.shape[0] not in (1, input.shape[0]):+ KORNIA_CHECK(+ False,+ "The kernel batch must be 1 or the input batch. "+ f"Got a kernel batch of {kernel.shape[0]} for an input batch of {input.shape[0]}",+ )++def filter2d(input: torch.Tensor,kernel: torch.Tensor,@@ -77,16 +89,14 @@ def filter2d(``k // 2`` for a kernel ``k`` taps long along it, and ``'circular'`` at least that long; a shorter axisraises.- 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.+ sample its own, shared by the sample's channels; there are no per-channel kernels. Any other kernel batch+ raises.- ``normalized=True`` divides each kernel by the sum of its absolute values, so a zero-sum derivative kernelkeeps its sign.- The kernel is cast to the input's dtype and device and stays differentiable; the output has the input'sdtype.- Known defects:- - a kernel batch that divides the input batch without matching it is not rejected: with 2 kernels for 4- samples, sample ``i`` is filtered with kernel ``i % 2``- (`#5154 <https://github.com/kornia/kornia/issues/5154>`_).- an integer input casts the kernel to its dtype, so a fractional kernel truncates to 0: a uint8 imagefiltered with a box kernel comes back as zeros, or the call raises where torch has no integerconvolution (`#5155 <https://github.com/kornia/kornia/issues/5155>`_).@@ -133,6 +143,7 @@ def filter2d(KORNIA_CHECK_SHAPE(input, ["B", "C", "H", "W"])KORNIA_CHECK_IS_TENSOR(kernel)KORNIA_CHECK_SHAPE(kernel, ["B", "H", "W"])+ _check_kernel_batch(input, kernel)KORNIA_CHECK(str(border_type).lower() in _VALID_BORDERS,@@ -319,6 +330,7 @@ def filter3d(KORNIA_CHECK_SHAPE(input, ["B", "C", "D", "H", "W"])KORNIA_CHECK_IS_TENSOR(kernel)KORNIA_CHECK_SHAPE(kernel, ["B", "D", "H", "W"])+ _check_kernel_batch(input, kernel)KORNIA_CHECK(str(border_type).lower() in _VALID_BORDERS,@@ -389,8 +401,6 @@ def fft_conv(window reaches it.- Known defects:- - one input sample with a batch of kernels is broadcast, one output per kernel, where- :func:`~kornia.filters.filter2d` raises (`#5154 <https://github.com/kornia/kornia/issues/5154>`_).- an integer input truncates a fractional kernel to 0, as in :func:`~kornia.filters.filter2d`, and theresult is in torch's default floating dtype (float32) instead of the input's(`#5155 <https://github.com/kornia/kornia/issues/5155>`_).@@ -449,6 +459,7 @@ def fft_conv(KORNIA_CHECK_IS_TENSOR(kernel)KORNIA_CHECK_SHAPE(kernel, ["B", "H", "W"])+ _check_kernel_batch(input, kernel)KORNIA_CHECK(str(border_type).lower() in _VALID_BORDERS,diff --git a/tests/filters/test_filters.py b/tests/filters/test_filters.pyindex 9a0706fba..29525de09 100644--- a/tests/filters/test_filters.py+++ b/tests/filters/test_filters.py@@ -19,6 +19,7 @@import pytestimport torchimport torch.nn.functional as F+from torch._dynamo.testing import CompileCounterfrom kornia.core._compat import torch_version_lefrom kornia.core.exceptions import BaseError@@ -1606,39 +1607,76 @@ class TestConventionsFilter2d(BaseTester):# constant padding runs on any sizeassert filter2d(_rand(1, 1, 3, 1, device=device, dtype=dtype), kernel, "constant").shape == (1, 1, 3, 1)- @pytest.mark.parametrize("name", ["filter2d", "filter2d_separable", "filter3d"])- def test_wart_kernel_batch_dividing_the_input_batch_is_applied_cyclically_5154(self, name, device, dtype):- """Two kernels for four samples are not rejected: sample i is filtered with kernel i % 2 (#5154)."""+ @pytest.mark.parametrize("name", ["filter2d", "filter2d_separable", "filter3d", "fft_conv"])+ def test_convention_kernel_batch_is_one_or_the_input_batch_5154(self, name, device, dtype):+ """A kernel batch that is neither 1 nor the input batch raises a kornia error naming both (#5154)."""+ _fft_guard(name, device, dtype)if name == "filter2d_separable":image = _rand(4, 1, 5, 7, device=device, dtype=dtype)- kernel_x = _rand(2, 3, device=device, dtype=dtype, seed=1)- kernel_y = _rand(2, 3, device=device, dtype=dtype, seed=2)+ kernel_x = _rand(4, 3, device=device, dtype=dtype, seed=1)+ kernel_y = _rand(4, 3, device=device, dtype=dtype, seed=2)def run(x, lo, hi):return filter2d_separable(x, kernel_x[lo:hi], kernel_y[lo:hi], "constant")else:- fn = filter3d if name == "filter3d" else filter2d+ fn = {"filter2d": filter2d, "filter3d": filter3d, "fft_conv": fft_conv}[name]image = _rand(4, 1, *((3,) if name == "filter3d" else ()), 5, 7, device=device, dtype=dtype)- kernels = _rand(2, *((3,) if name == "filter3d" else ()), 3, 3, device=device, dtype=dtype, seed=1)+ kernels = _rand(4, *((3,) if name == "filter3d" else ()), 3, 3, device=device, dtype=dtype, seed=1)def run(x, lo, hi):return fn(x, kernels[lo:hi], "constant")- out = run(image, 0, 2)- assert out.shape == image.shape+ # one kernel for the whole batch and one kernel per sample are the two accepted shapes+ shared = run(image, 0, 1)+ own = run(image, 0, 4)+ assert shared.shape == own.shape == image.shapefor i in range(4):- self.assert_close(out[i : i + 1], run(image[i : i + 1], i % 2, i % 2 + 1))-- def test_wart_fft_conv_broadcasts_one_sample_over_the_kernel_batch_5154(self, device, dtype):- """fft_conv returns a batch of 4 for one sample and 4 kernels, where filter2d raises (#5154)."""+ self.assert_close(shared[i : i + 1], run(image[i : i + 1], 0, 1))+ self.assert_close(own[i : i + 1], run(image[i : i + 1], i, i + 1))+ # 2 kernels divide the 4 samples and 3 do not: both raise the kornia error, not a torch view error+ for count in (2, 3):+ with pytest.raises(BaseError, match=f"kernel batch of {count} for an input batch of 4"):+ run(image, 0, count)++ def test_convention_fft_conv_rejects_a_kernel_batch_for_one_sample_5154(self, device, dtype):+ """One sample with four kernels raises in fft_conv as in filter2d instead of broadcasting (#5154)."""_fft_guard("fft_conv", device, dtype)image = _rand(1, 1, 5, 7, device=device, dtype=dtype)kernels = _rand(4, 3, 3, device=device, dtype=dtype, seed=1)- out = fft_conv(image, kernels, border_type="constant")- assert out.shape == (4, 1, 5, 7)- for j in range(4):- self.assert_close(out[j : j + 1], fft_conv(image, kernels[j : j + 1], border_type="constant"))+ for fn in (fft_conv, filter2d):+ with pytest.raises(BaseError, match="kernel batch of 4 for an input batch of 1"):+ fn(image, kernels, border_type="constant")++ @pytest.mark.parametrize("per_sample", [False, True])+ @pytest.mark.parametrize("name", ["filter2d", "filter2d_separable", "filter3d", "fft_conv"])+ def test_compile_kernel_batch_check_keeps_the_batch_dynamic_5154(+ self, name, per_sample, device, dtype, torch_optimizer+ ):+ """The kernel batch check does not specialize the batch: one dynamic graph serves every batch (#5154)."""+ _fft_guard(name, device, dtype)+ if name == "fft_conv" and torch_version_le(2, 5, 1):+ pytest.skip("torch 2.5.1 cannot trace torch.fft.rfftn with dynamic shapes")+ if name == "filter2d_separable":++ def op(x, k):+ return filter2d_separable(x, k[:, 0], k[:, 1], "constant")++ else:+ fn = {"filter2d": filter2d, "filter3d": filter3d, "fft_conv": fft_conv}[name]++ def op(x, k):+ return fn(x, k, "constant")++ counter = CompileCounter()+ compiled = torch_optimizer(op, backend=counter, fullgraph=True, dynamic=True)+ depth = (5,) if name == "filter3d" else ()+ # no batch equals another axis, so duck sizing cannot tie the batch to it+ for batch in (2, 4, 6):+ image = _rand(batch, 3, *depth, 7, 9, device=device, dtype=dtype)+ kernel = _rand(batch if per_sample else 1, *((3,) if depth else ()), 3, 3, device=device, dtype=dtype)+ self.assert_close(compiled(image, kernel), op(image, kernel))+ assert counter.frame_count == 1@pytest.mark.parametrize("name", ["filter2d", "filter2d_separable", "filter3d", "fft_conv"])def test_wart_integer_input_truncates_a_fractional_kernel_to_zero_5155(self, name, device, dtype):diff --git a/tests/filters/test_gaussian.py b/tests/filters/test_gaussian.pyindex 850be8dcd..f1c796625 100644--- a/tests/filters/test_gaussian.py+++ b/tests/filters/test_gaussian.py@@ -25,6 +25,7 @@ import pytestimport torchfrom kornia.core._compat import torch_version_ge, torch_version_lt+from kornia.core.exceptions import BaseErrorfrom kornia.filters import (GaussianBlur2d,gaussian,@@ -558,14 +559,20 @@ class TestGaussianBlur2d(BaseTester):assert output.shape == sample.shapedef test_batched_sigma_mismatched_batch_size(self, device, dtype):- """Test that batched sigma uses first batch element when shapes don't match."""- # Note: The function broadcasts sigma, so mismatched batch size is allowed- # but only the first sigma in the batch is used for all input samples+ """A sigma batch that is neither 1 nor the input batch raises through the kernel batch check (#5154).++ A check of the sigma shape at the entry of gaussian_blur2d is #5169.+ """sample = torch.rand(4, 3, 8, 8, device=device, dtype=dtype)- sigma = torch.tensor([[1.5, 1.5], [2.0, 2.0]], device=device, dtype=dtype)- # Should not raise - will use broadcasting behavior- output = gaussian_blur2d(sample, (3, 3), sigma)- assert output.shape == sample.shape+ # 2 rows divide the 4 samples and 3 do not: both raise the kornia error, not a torch reshape error+ for rows in (2, 3):+ sigma = torch.full((rows, 2), 1.5, device=device, dtype=dtype)+ with pytest.raises(BaseError, match=f"kernel batch of {rows} for an input batch of 4"):+ gaussian_blur2d(sample, (3, 3), sigma)+ # one row for the whole batch and one row per sample run+ for rows in (1, 4):+ sigma = torch.full((rows, 2), 1.5, device=device, dtype=dtype)+ assert gaussian_blur2d(sample, (3, 3), sigma).shape == sample.shapedef test_all_border_types(self, device, dtype):"""Test that all supported border types work."""