Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(filters): transform float16 and bfloat16 inputs of fft_conv in float32 on every device (#6564)

Dmytro Mishkin5ef09250e8e2
diff --git a/README.md b/README.md
index 47ce0f17e..e0ee460ab 100644
--- a/README.md
+++ b/README.md
@@ -139,7 +139,7 @@ No CI job covers CUDA or MPS half precision; CPU results do not establish suppor
| Module | float16 | bfloat16 | Known failures (fp16 / bf16) | Notes |
|--------|:-------:|:--------:|:----------------------------:|-------|
| `kornia.color` | βœ… | βœ… | 0 / 0 | Lab/Luv conversions and `rgb255_to_normals` compute half inputs in float32 and return the input dtype |
-| `kornia.filters` | βœ… | βœ… | 0 / 0 | Canny, Gaussian kernels/blur and CPU FFT convolution compute half inputs in float32 and return the input dtype |
+| `kornia.filters` | βœ… | βœ… | 0 / 0 | Canny, Gaussian kernels/blur and FFT convolution compute half inputs in float32 and return the input dtype |
| `kornia.enhance` | βœ… | βœ… | 0 / 0 | ZCA keeps half-input fitted state in float32; whitening and JPEG return the input dtype after float32 computation |
| `kornia.morphology` | βœ… | βœ… | 0 / 0 | |
| `kornia.augmentation` | ⚠️ | ⚠️ | 59 / 48 | float16: container autocast/runtime errors and accuracy; both dtypes: 3D backward and random-generator accuracy |
diff --git a/changelog.d/6564.fixed.md b/changelog.d/6564.fixed.md
new file mode 100644
index 000000000..baa3062a6
--- /dev/null
+++ b/changelog.d/6564.fixed.md
@@ -0,0 +1,3 @@
+`fft_conv` now transforms float16 and bfloat16 inputs in float32 on every device, not only on CPU, and returns the
+input dtype. On CUDA a float16 input used to raise unless every padded size was a power of two, and a bfloat16 input
+raised (torch before 2.14) or returned float32 (torch 2.14 and later). On MPS both dtypes raised for every size.
diff --git a/docs/source/get-started/precision.rst b/docs/source/get-started/precision.rst
index c66f3e99b..8953fd1ae 100644
--- a/docs/source/get-started/precision.rst
+++ b/docs/source/get-started/precision.rst
@@ -29,7 +29,7 @@ No CI job covers CUDA or MPS half precision; CPU results do not establish suppor
- βœ…
- βœ…
- 0 / 0
- - Canny, Gaussian kernels/blur and CPU FFT convolution compute half inputs in float32 and return the input dtype
+ - Canny, Gaussian kernels/blur and FFT convolution compute half inputs in float32 and return the input dtype
* - ``kornia.enhance``
- βœ…
- βœ…
diff --git a/kornia/filters/filter.py b/kornia/filters/filter.py
index 1d28e7f44..40dcd60ba 100644
--- a/kornia/filters/filter.py
+++ b/kornia/filters/filter.py
@@ -448,8 +448,11 @@ def fft_conv(
Note:
- Internally, the function performs zero-padding of the kernel to
match the input size and uses real-valued FFTs (`rfftn` / `irfftn`).
- - CPU float16 and bfloat16 inputs use float32 FFTs, with the result
- cast back to the input dtype.
+ - float16 and bfloat16 inputs use float32 FFTs on every device, with
+ the result cast back to the input dtype: torch's CPU and MPS FFTs
+ have no half-precision kernels, and cuFFT computes float16 only for
+ power-of-two sizes, while a CUDA bfloat16 FFT raises before torch
+ 2.14 and returns float32 from 2.14 on.
- This implementation computes linear convolution via FFT by
appropriate spatial padding and cropping, avoiding circular
convolution artifacts.
@@ -538,9 +541,12 @@ def fft_conv(
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:
+ # torch has no half-precision FFT that covers every input: the CPU and MPS kernels support neither float16 nor
+ # bfloat16, cuFFT computes float16 only for power-of-two sizes, and a CUDA bfloat16 FFT raises before torch 2.14
+ # and returns float32 from 2.14 on. Half inputs are therefore transformed in float32 on every device and cast
+ # back once.
+ is_half = input.dtype in (torch.float16, torch.bfloat16)
+ if is_half:
input_padded = input_padded.float()
tmp_kernel = tmp_kernel.float()
@@ -559,7 +565,7 @@ def fft_conv(
crop_w = padded_w - kw + 1
output = output[..., :crop_h, :crop_w].contiguous()
- return output.to(input.dtype) if is_cpu_half else output
+ return output.to(input.dtype) if is_half else output
def correlate2d(
diff --git a/tests/filters/test_filters.py b/tests/filters/test_filters.py
index 334cc31a5..0c0323348 100644
--- a/tests/filters/test_filters.py
+++ b/tests/filters/test_filters.py
@@ -877,6 +877,24 @@ class TestFilter3D(BaseTester):
class TestFilter2D_fftconv(BaseTester):
+ @pytest.mark.parametrize("size", [(50, 50), (40, 45)])
+ def test_half_input_is_transformed_in_float32(self, size, device, dtype):
+ """A half input returns the float32 result for the same values, cast back to the input dtype.
+
+ With a 15 x 15 kernel the padded sizes are 64 x 64, a power of two, and 54 x 59, which is not.
+ """
+ if dtype not in (torch.float16, torch.bfloat16):
+ pytest.skip("checks the float16 and bfloat16 path")
+ generator = torch.Generator().manual_seed(0)
+ sample = torch.rand(2, 3, *size, generator=generator).to(device, dtype)
+ kernel = torch.rand(1, 15, 15, generator=generator).to(device, dtype)
+
+ actual = fft_conv(sample, kernel, border_type="constant")
+ expected = fft_conv(sample.float(), kernel.float(), border_type="constant").to(dtype)
+
+ assert actual.dtype == dtype
+ self.assert_close(actual, expected, rtol=0, atol=0)
+
@pytest.mark.parametrize("padding", ["same", "valid"])
@pytest.mark.parametrize("behaviour", ["corr", "conv"])
@pytest.mark.parametrize("normalized", [True, False])
@@ -1399,11 +1417,12 @@ _FILTER2D_FNS = {"filter2d": filter2d, "fft_conv": fft_conv}
def _fft_guard(name: str, device: torch.device, dtype: torch.dtype) -> None:
- """Skip fft_conv where the device has no FFT for the dtype (fft_conv computes a CPU half input in float32)."""
+ """Skip fft_conv where the device has no FFT for the dtype it transforms (float32 for half inputs)."""
if name != "fft_conv" or device.type == "cpu":
return
+ fft_dtype = torch.float32 if dtype in (torch.float16, torch.bfloat16) else dtype
try:
- torch.fft.rfftn(torch.zeros(3, 5, device=device, dtype=dtype))
+ torch.fft.rfftn(torch.zeros(3, 5, device=device, dtype=fft_dtype))
except (RuntimeError, NotImplementedError):
pytest.skip("this device has no FFT for this dtype, which fft_conv needs")