Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Writing fft_conv (#3592)

codeguitarmaster776e37685ac1
diff --git a/kornia/filters/__init__.py b/kornia/filters/__init__.py
index 3e7c5d898..4095dafe6 100644
--- a/kornia/filters/__init__.py
+++ b/kornia/filters/__init__.py
@@ -34,7 +34,7 @@ from .blur_pool import (
)
from .canny import Canny, canny
from .dissolving import StableDiffusionDissolving
-from .filter import filter2d, filter2d_separable, filter3d
+from .filter import fft_conv, filter2d, filter2d_separable, filter3d
from .gaussian import GaussianBlur2d, gaussian_blur2d, gaussian_blur2d_t
from .guided import GuidedBlur, guided_blur
from .in_range import InRange, in_range
@@ -95,6 +95,7 @@ __all__ = [
"box_blur",
"canny",
"edge_aware_blur_pool2d",
+ "fft_conv",
"filter2d",
"filter2d_separable",
"filter3d",
diff --git a/kornia/filters/filter.py b/kornia/filters/filter.py
index 3ede75183..62e61afad 100644
--- a/kornia/filters/filter.py
+++ b/kornia/filters/filter.py
@@ -21,8 +21,7 @@ import torch
import torch.nn.functional as F
from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE
-
-from .kernels import normalize_kernel2d
+from kornia.filters.kernels import normalize_kernel2d
_VALID_BORDERS = {"constant", "reflect", "replicate", "circular"}
_VALID_PADDING = {"valid", "same"}
@@ -109,15 +108,15 @@ def filter2d(
KORNIA_CHECK(
str(border_type).lower() in _VALID_BORDERS,
- f"Invalid border, gotcha {border_type}. Expected one of {_VALID_BORDERS}",
+ f"Invalid border, {border_type}. Expected one of {_VALID_BORDERS}",
)
KORNIA_CHECK(
str(padding).lower() in _VALID_PADDING,
- f"Invalid padding mode, gotcha {padding}. Expected one of {_VALID_PADDING}",
+ f"Invalid padding mode, {padding}. Expected one of {_VALID_PADDING}",
)
KORNIA_CHECK(
str(behaviour).lower() in _VALID_BEHAVIOUR,
- f"Invalid padding mode, gotcha {behaviour}. Expected one of {_VALID_BEHAVIOUR}",
+ f"Invalid padding mode, {behaviour}. Expected one of {_VALID_BEHAVIOUR}",
)
# prepare kernel
b, c, h, w = input.shape
@@ -125,7 +124,6 @@ def filter2d(
tmp_kernel = kernel.flip((-2, -1))[:, None, ...].to(device=input.device, dtype=input.dtype)
else:
tmp_kernel = kernel[:, None, ...].to(device=input.device, dtype=input.dtype)
- # str(behaviour).lower() == 'conv':
if normalized:
tmp_kernel = normalize_kernel2d(tmp_kernel)
@@ -305,3 +303,141 @@ def filter3d(
output = F.conv3d(input_pad, tmp_kernel, groups=tmp_kernel.size(0), padding=0, stride=1)
return output.view(b, c, d, h, w)
+
+
+def fft_conv(
+ input: torch.Tensor,
+ kernel: torch.Tensor,
+ border_type: str = "reflect",
+ normalized: bool = False,
+ padding: str = "same",
+ behaviour: str = "corr",
+) -> torch.Tensor:
+ r"""Apply a 2D convolution (or correlation) using an FFT-based backend.
+
+ This function applies a spatial kernel to a batched tensor using the
+ convolution theorem, i.e., convolution in the spatial domain is performed
+ as element-wise multiplication in the frequency domain.
+
+ The kernel is applied independently to each channel of the input tensor.
+ Depending on the selected padding mode, the output can either preserve
+ the input spatial resolution (`'same'`) or return only the valid region
+ (`'valid'`). Boundary handling is performed in the spatial domain prior
+ to the FFT.
+
+ This function is recommended when the kernel size is larger than
+ approximately (20 x 20). For large kernels, FFT-based convolution is
+ computationally more efficient than direct spatial convolution,
+ reducing complexity from O(H * W * kH * kW) to approximately
+ O(H * W log(H * W)). For small kernels, however, direct convolution
+ is usually faster due to lower constant overhead.
+
+ Args:
+ input: Input tensor of shape :math:`(B, C, H, W)`.
+ kernel: Convolution kernel of shape :math:`(B, kH, kW)`. Each batch
+ element provides one kernel, which is shared across all channels
+ of the corresponding input batch.
+ border_type: Padding mode applied to the input before convolution.
+ Supported values are ``'constant'``, ``'reflect'``,
+ ``'replicate'``, and ``'circular'``.
+ normalized: If ``True``, the kernel is L1-normalized before applying
+ the convolution.
+ padding: Padding strategy to use. Supported values are:
+ ``'same'`` (output has the same spatial size as the input) or
+ ``'valid'`` (no implicit padding).
+ behaviour: Convolution mode. If ``'corr'`` (default), performs
+ cross-correlation. If ``'conv'``, performs true convolution
+ by flipping the kernel spatially.
+
+ Returns:
+ Tensor: The filtered tensor. If ``padding='same'``, the output shape
+ is :math:`(B, C, H, W)`. If ``padding='valid'``, the output shape is
+ :math:`(B, C, H - kH + 1, W - kW + 1)`.
+
+ Note:
+ - Internally, the function performs zero-padding of the kernel to
+ match the input size and uses real-valued FFTs (`rfftn` / `irfftn`).
+ - This implementation computes linear convolution via FFT by
+ appropriate spatial padding and cropping, avoiding circular
+ convolution artifacts.
+ - No stride or dilation is supported.
+
+ Example:
+ >>> input = torch.tensor([[[[
+ ... 0., 0., 0., 0., 0.],
+ ... [0., 0., 0., 0., 0.],
+ ... [0., 0., 5., 0., 0.],
+ ... [0., 0., 0., 0., 0.],
+ ... [0., 0., 0., 0., 0.],
+ ... ]]])
+ >>> kernel = torch.ones(1, 3, 3)
+ >>> fft_conv(input, kernel, padding="same")
+ tensor([[[[0., 0., 0., 0., 0.],
+ [0., 5., 5., 5., 0.],
+ [0., 5., 5., 5., 0.],
+ [0., 5., 5., 5., 0.],
+ [0., 0., 0., 0., 0.]]]])
+ """
+ KORNIA_CHECK_IS_TENSOR(input)
+ KORNIA_CHECK_SHAPE(input, ["B", "C", "H", "W"])
+
+ KORNIA_CHECK_IS_TENSOR(kernel)
+ KORNIA_CHECK_SHAPE(kernel, ["B", "H", "W"])
+
+ KORNIA_CHECK(
+ str(border_type).lower() in _VALID_BORDERS,
+ f"Invalid border, {border_type}. Expected one of {_VALID_BORDERS}",
+ )
+
+ KORNIA_CHECK(
+ str(padding).lower() in _VALID_PADDING,
+ f"Invalid padding mode, {padding}. Expected one of {_VALID_PADDING}",
+ )
+
+ KORNIA_CHECK(
+ str(behaviour).lower() in _VALID_BEHAVIOUR,
+ f"Invalid behaviour mode, {behaviour}. Expected one of {_VALID_BEHAVIOUR}",
+ )
+
+ _, c, _, _ = input.shape
+ kh, kw = kernel.shape[-2:]
+
+ if str(behaviour).lower() == "conv":
+ tmp_kernel = kernel.flip((-2, -1))[:, None, ...].to(device=input.device, dtype=input.dtype)
+ else:
+ tmp_kernel = kernel[:, None, ...].to(device=input.device, dtype=input.dtype)
+
+ if normalized:
+ tmp_kernel = normalize_kernel2d(tmp_kernel)
+
+ # Expand kernel across channels
+ tmp_kernel = tmp_kernel.expand(-1, c, -1, -1)
+
+ # Padding (spatial domain)
+ if padding == "same":
+ padding_shape = _compute_padding([kh, kw])
+ input_padded = F.pad(input, padding_shape, mode=border_type)
+ else:
+ input_padded = input
+
+ padded_h, padded_w = input_padded.shape[-2:]
+
+ input_padded = input_padded.contiguous()
+ tmp_kernel = tmp_kernel.contiguous()
+
+ # FFT
+ input_fr = torch.fft.rfftn(input_padded, dim=(-2, -1))
+ kernel_fr = torch.fft.rfftn(tmp_kernel, s=(padded_h, padded_w), dim=(-2, -1))
+
+ # Correlation via conjugation
+ output_fr = input_fr * torch.conj(kernel_fr)
+
+ # Inverse FFT
+ output = torch.fft.irfftn(output_fr, s=(padded_h, padded_w), dim=(-2, -1))
+
+ # Crop to valid region
+ crop_h = padded_h - kh + 1
+ crop_w = padded_w - kw + 1
+ output = output[..., :crop_h, :crop_w].contiguous()
+
+ return output
diff --git a/tests/filters/test_filters.py b/tests/filters/test_filters.py
index 12c8be7b0..f58cea041 100644
--- a/tests/filters/test_filters.py
+++ b/tests/filters/test_filters.py
@@ -15,11 +15,12 @@
# limitations under the License.
#
+
import pytest
import torch
from kornia.core._compat import torch_version_le
-from kornia.filters import filter2d, filter2d_separable, filter3d
+from kornia.filters import fft_conv, filter2d, filter2d_separable, filter3d
from testing.base import BaseTester
@@ -116,11 +117,11 @@ class TestFilter2D(BaseTester):
with pytest.raises(Exception) as errinfo:
filter2d(data, k, border_type="a")
- assert "Invalid border, gotcha a. Ex" in str(errinfo)
+ assert "Invalid border, a. Ex" in str(errinfo)
with pytest.raises(Exception) as errinfo:
filter2d(data, k, padding="a")
- assert "Invalid padding mode, gotcha a. Ex" in str(errinfo)
+ assert "Invalid padding mode, a. Ex" in str(errinfo)
@pytest.mark.parametrize("padding", ["same", "valid"])
def test_mean_filter(self, padding, device, dtype):
@@ -746,3 +747,358 @@ class TestFilter3D(BaseTester):
actual = op_optimized(data, kernel, normalized=normalized)
self.assert_close(actual, expected)
+
+
+class TestFilter2D_fftconv(BaseTester):
+ @pytest.mark.parametrize("border_type", ["constant", "reflect", "replicate", "circular"])
+ @pytest.mark.parametrize("normalized", [True, False])
+ @pytest.mark.parametrize("padding", ["same", "valid"])
+ def test_smoke(self, border_type, normalized, padding, device, dtype):
+ kernel = torch.rand(1, 3, 3, device=device, dtype=dtype)
+ _, height, width = kernel.shape
+ sample = torch.ones(1, 1, 7, 8, device=device, dtype=dtype)
+ b, c, h, w = sample.shape
+
+ actual = fft_conv(sample, kernel, border_type, normalized, padding)
+ assert isinstance(actual, torch.Tensor)
+ assert actual.shape in {(b, c, h, w), (b, c, h - height + 1, w - width + 1)}
+
+ @pytest.mark.parametrize("batch_size", [2, 3, 6, 8])
+ @pytest.mark.parametrize("padding", ["same", "valid"])
+ def test_cardinality(self, batch_size, padding, device, dtype):
+ B: int = batch_size
+ kernel = torch.rand(1, 3, 3, device=device, dtype=dtype)
+ _, height, width = kernel.shape
+ sample = torch.ones(B, 3, 7, 8, device=device, dtype=dtype)
+ b, c, h, w = sample.shape
+ out = fft_conv(sample, kernel, padding=padding)
+ if padding == "same":
+ assert out.shape == (b, c, h, w)
+ else:
+ assert out.shape == (b, c, h - height + 1, w - width + 1)
+
+ def test_conv(self, device, dtype):
+ inp = torch.zeros(1, 1, 5, 5, device=device, dtype=dtype)
+ inp[..., 2, 2] = 1.0
+ kernel = torch.arange(1, 10).reshape(3, 3).to(device, dtype)[None]
+ corr_expected = torch.tensor(
+ [
+ [
+ [
+ [0.0, 0.0, 0.0, 0.0, 0.0],
+ [0.0, 9.0, 8.0, 7.0, 0.0],
+ [0.0, 6.0, 5.0, 4.0, 0.0],
+ [0.0, 3.0, 2.0, 1.0, 0.0],
+ [0.0, 0.0, 0.0, 0.0, 0.0],
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype,
+ )
+ conv_expected = torch.tensor(
+ [
+ [
+ [
+ [0.0, 0.0, 0.0, 0.0, 0.0],
+ [0.0, 1.0, 2.0, 3.0, 0.0],
+ [0.0, 4.0, 5.0, 6.0, 0.0],
+ [0.0, 7.0, 8.0, 9.0, 0.0],
+ [0.0, 0.0, 0.0, 0.0, 0.0],
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype,
+ )
+ out_corr = fft_conv(inp, kernel, behaviour="corr")
+ self.assert_close(out_corr, corr_expected, atol=1e-6, rtol=1e-6)
+ out_conv = fft_conv(inp, kernel, behaviour="conv")
+ self.assert_close(out_conv, conv_expected, atol=1e-6, rtol=1e-6)
+
+ def test_exception(self):
+ from kornia.core.exceptions import ShapeError, TypeCheckError
+
+ k = torch.ones(1, 1, 1)
+ data = torch.ones(1, 1, 1, 1)
+ with pytest.raises(TypeCheckError) as errinfo:
+ fft_conv(1, k)
+ assert "Type mismatch: expected Tensor" in str(errinfo.value)
+
+ with pytest.raises(TypeCheckError) as errinfo:
+ fft_conv(data, 1)
+ assert "Type mismatch: expected Tensor" in str(errinfo.value)
+
+ with pytest.raises(ShapeError) as errinfo:
+ fft_conv(torch.ones(1), k)
+ assert "Shape dimension mismatch" in str(errinfo.value)
+ assert "['B', 'C', 'H', 'W']" in str(errinfo.value)
+
+ with pytest.raises(ShapeError) as errinfo:
+ fft_conv(data, torch.ones(1))
+ assert "Shape dimension mismatch" in str(errinfo.value)
+ assert "['B', 'H', 'W']" in str(errinfo.value)
+
+ with pytest.raises(Exception) as errinfo:
+ fft_conv(data, k, border_type="a")
+ assert "Invalid border, a. Ex" in str(errinfo)
+
+ with pytest.raises(Exception) as errinfo:
+ fft_conv(data, k, padding="a")
+ assert "Invalid padding mode, a. Ex" in str(errinfo)
+
+ @pytest.mark.parametrize("padding", ["same", "valid"])
+ def test_mean_filter(self, padding, device, dtype):
+ kernel = torch.ones(1, 3, 3, device=device, dtype=dtype)
+ sample = torch.tensor(
+ [
+ [
+ [
+ [0.0, 0.0, 0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0, 0.0, 0.0],
+ [0.0, 0.0, 5.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0, 0.0, 0.0],
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype,
+ )
+
+ actual = fft_conv(sample, kernel, padding=padding)
+
+ if padding == "same":
+ expected_same = torch.tensor(
+ [
+ [
+ [
+ [0.0, 0.0, 0.0, 0.0, 0.0],
+ [0.0, 5.0, 5.0, 5.0, 0.0],
+ [0.0, 5.0, 5.0, 5.0, 0.0],
+ [0.0, 5.0, 5.0, 5.0, 0.0],
+ [0.0, 0.0, 0.0, 0.0, 0.0],
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype,
+ )
+
+ self.assert_close(actual, expected_same)
+ else:
+ expected_valid = torch.tensor(
+ [[[[5.0, 5.0, 5.0], [5.0, 5.0, 5.0], [5.0, 5.0, 5.0]]]], device=device, dtype=dtype
+ )
+
+ self.assert_close(actual, expected_valid)
+
+ @pytest.mark.parametrize("padding", ["same", "valid"])
+ def test_mean_filter_2batch_2ch(self, padding, device, dtype):
+ kernel = torch.ones(1, 3, 3, device=device, dtype=dtype)
+ sample = torch.tensor(
+ [
+ [
+ [
+ [0.0, 0.0, 0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0, 0.0, 0.0],
+ [0.0, 0.0, 5.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0, 0.0, 0.0],
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype,
+ ).expand(2, 2, -1, -1)
+
+ actual = fft_conv(sample, kernel, padding=padding)
+
+ if padding == "same":
+ expected_same = torch.tensor(
+ [
+ [
+ [
+ [0.0, 0.0, 0.0, 0.0, 0.0],
+ [0.0, 5.0, 5.0, 5.0, 0.0],
+ [0.0, 5.0, 5.0, 5.0, 0.0],
+ [0.0, 5.0, 5.0, 5.0, 0.0],
+ [0.0, 0.0, 0.0, 0.0, 0.0],
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype,
+ ).expand(2, 2, -1, -1)
+
+ self.assert_close(actual, expected_same)
+ else:
+ expected_valid = torch.tensor(
+ [[[[5.0, 5.0, 5.0], [5.0, 5.0, 5.0], [5.0, 5.0, 5.0]]]], device=device, dtype=dtype
+ ).expand(2, 2, -1, -1)
+ self.assert_close(actual, expected_valid)
+
+ @pytest.mark.parametrize("padding", ["same", "valid"])
+ def test_normalized_mean_filter(self, padding, device, dtype):
+ kernel = torch.ones(1, 3, 3, device=device, dtype=dtype)
+ sample = torch.tensor(
+ [
+ [
+ [
+ [0.0, 0.0, 0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0, 0.0, 0.0],
+ [0.0, 0.0, 5.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0, 0.0, 0.0],
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype,
+ ).expand(2, 2, -1, -1)
+
+ nv: float = 5.0 / 9 # normalization value
+ actual = fft_conv(sample, kernel, normalized=True, padding=padding)
+
+ if padding == "same":
+ expected_same = torch.tensor(
+ [
+ [
+ [
+ [0.0, 0.0, 0.0, 0.0, 0.0],
+ [0.0, nv, nv, nv, 0.0],
+ [0.0, nv, nv, nv, 0.0],
+ [0.0, nv, nv, nv, 0.0],
+ [0.0, 0.0, 0.0, 0.0, 0.0],
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype,
+ ).expand(2, 2, -1, -1)
+
+ self.assert_close(actual, expected_same)
+ else:
+ expected_valid = torch.tensor(
+ [[[[nv, nv, nv], [nv, nv, nv], [nv, nv, nv]]]], device=device, dtype=dtype
+ ).expand(2, 2, -1, -1)
+
+ self.assert_close(actual, expected_valid)
+
+ @pytest.mark.parametrize("padding", ["same", "valid"])
+ def test_even_sized_filter(self, padding, device, dtype):
+ kernel = torch.ones(1, 2, 2, device=device, dtype=dtype)
+ sample = torch.tensor(
+ [
+ [
+ [
+ [0.0, 0.0, 0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0, 0.0, 0.0],
+ [0.0, 0.0, 5.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0, 0.0, 0.0],
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype,
+ )
+
+ actual = fft_conv(sample, kernel, padding=padding)
+
+ if padding == "same":
+ expected_same = torch.tensor(
+ [
+ [
+ [
+ [0.0, 0.0, 0.0, 0.0, 0.0],
+ [0.0, 5.0, 5.0, 0.0, 0.0],
+ [0.0, 5.0, 5.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0, 0.0, 0.0],
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype,
+ )
+
+ self.assert_close(actual, expected_same)
+ else:
+ expected_valid = torch.tensor(
+ [[[[0.0, 0.0, 0.0, 0.0], [0.0, 5.0, 5.0, 0.0], [0.0, 5.0, 5.0, 0.0], [0.0, 0.0, 0.0, 0.0]]]],
+ device=device,
+ dtype=dtype,
+ )
+
+ self.assert_close(actual, expected_valid)
+
+ @pytest.mark.parametrize("padding", ["same", "valid"])
+ def test_mix_sized_filter_padding_same(self, padding, device, dtype):
+ kernel = torch.ones(1, 5, 6, device=device, dtype=dtype)
+ sample_ = torch.tensor(
+ [
+ [
+ [
+ [0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
+ [0.0, 0.0, 1.0, 0.0, 0.0, 0.0],
+ [0.0, 0.0, 1.0, 0.0, 0.0, 0.0],
+ [0.0, 0.0, 1.0, 0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype,
+ )
+
+ expected_same = torch.tensor(
+ [
+ [
+ [
+ [2.0, 2.0, 2.0, 2.0, 2.0, 0.0],
+ [3.0, 3.0, 3.0, 3.0, 3.0, 0.0],
+ [3.0, 3.0, 3.0, 3.0, 3.0, 0.0],
+ [3.0, 3.0, 3.0, 3.0, 3.0, 0.0],
+ [2.0, 2.0, 2.0, 2.0, 2.0, 0.0],
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype,
+ )
+
+ actual = fft_conv(sample_, kernel, padding="same", border_type="constant")
+ self.assert_close(actual, expected_same)
+
+ @pytest.mark.parametrize("padding", ["same", "valid"])
+ def test_noncontiguous(self, padding, device, dtype):
+ batch_size = 3
+ inp = torch.rand(3, 5, 5, device=device, dtype=dtype).expand(batch_size, -1, -1, -1)
+ kernel = torch.ones(1, 2, 2, device=device, dtype=dtype)
+
+ actual = fft_conv(inp, kernel, padding=padding)
+ assert actual.is_contiguous()
+
+ def test_gradcheck(self, device):
+ kernel = torch.rand(1, 3, 3, device=device, dtype=torch.float64)
+ sample = torch.ones(1, 1, 7, 8, device=device, dtype=torch.float64)
+
+ # evaluate function gradient
+ self.gradcheck(fft_conv, (sample, kernel), nondet_tol=1e-8)
+
+ @pytest.mark.skip(reason="filter2d do not have a module")
+ def test_module(self): ...
+
+ @pytest.mark.parametrize("normalized", [True, False])
+ @pytest.mark.parametrize("padding", ["same", "valid"])
+ def test_dynamo(self, normalized, padding, device, dtype, torch_optimizer):
+ kernel = torch.rand(1, 3, 3, device=device, dtype=dtype)
+ data = torch.ones(2, 3, 10, 10, device=device, dtype=dtype)
+ op = fft_conv
+ op_optimized = torch_optimizer(op)
+
+ expected = op(data, kernel, padding=padding, normalized=normalized)
+ actual = op_optimized(data, kernel, padding=padding, normalized=normalized)
+
+ self.assert_close(actual, expected)