π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(filters): return an empty batch from fft_conv instead of raising an MKL error (#6301)
Debanjan Sarkarbf9291cdd2fd
diff --git a/changelog.d/6301.fixed.md b/changelog.d/6301.fixed.mdnew file mode 100644index 000000000..ab36a995a--- /dev/null+++ b/changelog.d/6301.fixed.md@@ -0,0 +1 @@+`kornia.filters.fft_conv` now returns an empty batch for an empty input instead of raising an MKL FFT error.diff --git a/kornia/filters/filter.py b/kornia/filters/filter.pyindex 2c2651796..e226e067e 100644--- a/kornia/filters/filter.py+++ b/kornia/filters/filter.py@@ -532,6 +532,12 @@ def fft_conv(input_padded = input_padded.contiguous()tmp_kernel = tmp_kernel.contiguous()+ # The MKL FFT backend raises on an empty batch (pytorch/pytorch#174984), so there is nothing to transform: crop+ # the empty input to the output size. The zero-weighted kernel sum keeps the kernel in the autograd graph, as+ # filter2d does.+ if input_padded.shape[0] == 0:+ return input_padded[..., : padded_h - kh + 1, : padded_w - kw + 1] + tmp_kernel.sum() * 0+# CPU FFT kernels do not support float16 or bfloat16.is_cpu_half = input.device.type == "cpu" and input.dtype in (torch.float16, torch.bfloat16)if is_cpu_half:diff --git a/tests/filters/test_filters.py b/tests/filters/test_filters.pyindex 6f0dba3c8..334cc31a5 100644--- a/tests/filters/test_filters.py+++ b/tests/filters/test_filters.py@@ -2725,6 +2725,24 @@ class TestEmptyBatchPerSampleKernel(BaseTester):assert value.grad is not Noneassert value.grad.shape == value.shape+ @pytest.mark.parametrize("padding", ["same", "valid"])+ @pytest.mark.parametrize("kernel_batch", [0, 1])+ def test_fft_conv_empty_batch_6266(self, padding, kernel_batch, device, dtype):+ """fft_conv returns an empty batch like filter2d instead of raising an MKL FFT error (#6266)."""+ _fft_guard("fft_conv", device, dtype)+ image = torch.empty(0, 3, 9, 13, device=device, dtype=dtype, requires_grad=True)+ kernel = torch.ones(kernel_batch, 3, 5, device=device, dtype=dtype, requires_grad=True)+ output = fft_conv(image, kernel, "constant", True, padding)+ expected = filter2d(image, kernel, "constant", True, padding)+ assert output.shape == expected.shape+ assert output.dtype == dtype+ assert output.device == device+ output.sum().backward()+ for value in (image, kernel):+ assert value.grad is not None+ assert value.grad.shape == value.shape+ self.assert_close(value.grad, torch.zeros_like(value.grad))+@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):