Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(filters): preserve guided-filter covariances in half precision (#6038)

Anton Soloviev2d8b49be0308
diff --git a/changelog.d/6038.fixed.md b/changelog.d/6038.fixed.md
new file mode 100644
index 000000000..080957f0a
--- /dev/null
+++ b/changelog.d/6038.fixed.md
@@ -0,0 +1 @@
+`guided_blur` and `GuidedBlur` now compute window statistics for float16 and bfloat16 images in float32. With scalar regularization, coefficients are also computed in float32 and only the result is cast back, so a half-precision call returns the float32 result for the same pixel values, rounded once. A float64 tensor `eps` widens coefficient arithmetic and the grayscale result to float64; multichannel guidance solves in float64 before casting its coefficients back. Before, the local variance `E[I^2] - E[I]^2` was formed in half precision, whose rounding at mid-gray (about 2e-4 in float16, 2e-3 in bfloat16) swamped a small `eps`: with `eps=1e-4` on two 512 x 512 test photographs, float16 results were off by up to 1.5 with grayscale guidance and 36 with RGB guidance, gradients came back non-finite, and with RGB guidance `torch.linalg.solve` could fail on a singular matrix. A float16 or bfloat16 multichannel guidance with an `input` of another dtype (float32, uint8 or the other half-precision type) raised a dtype mismatch; it now returns float32. Autocast is now disabled inside the filter: a float32 call in an autocast region used to be filtered in the autocast dtype, with the same errors, and returned that dtype with RGB guidance; it now returns the float32 result. float32 and float64 results outside autocast are unchanged.
diff --git a/kornia/filters/guided.py b/kornia/filters/guided.py
index 0dc0e7b8d..6c99ecbf6 100644
--- a/kornia/filters/guided.py
+++ b/kornia/filters/guided.py
@@ -200,7 +200,13 @@ def guided_blur(
:ref:`Filtering <filtering-conventions>` maps the arguments onto OpenCV's ``guidedFilter``.
- An integer or bool ``guidance`` or ``input`` is converted to float32 before the covariance products, on its
own scale, and the result has the promoted dtype of the two: a float16 ``input`` with a uint8 ``guidance``
- returns float32, where :func:`~kornia.filters.joint_bilateral_blur` keeps ``input``'s dtype.
+ returns float32, where :func:`~kornia.filters.joint_bilateral_blur` keeps ``input``'s dtype. With grayscale
+ guidance, a tensor-valued ``eps`` also participates in result dtype promotion; multichannel guidance
+ retains the promoted dtype of ``guidance`` and ``input``.
+ - A float16 or bfloat16 ``guidance`` or ``input`` is converted to float32 before the window statistics, and
+ the coefficients are solved in float32 as well (in float64 with a float64 tensor ``eps``). Autocast is
+ disabled inside the filter, so a float32 call in an autocast region returns float32. The result has the
+ dtype of the rule above.
Arguments:
guidance: the guidance torch.Tensor with shape :math:`(B,C_g,H,W)`.
@@ -253,9 +259,27 @@ def guided_blur(
input_is_guidance = input is guidance
guidance = _to_floating(guidance)
input = guidance if input_is_guidance else _to_floating(input)
+ output_dtype = torch.promote_types(guidance.dtype, input.dtype)
+ # E[g*g] - E[g]*E[g] loses the local variance in half precision, before
+ # even a promoted solve can help. Promote before all window statistics.
+ if guidance.dtype in (torch.float16, torch.bfloat16):
+ guidance = guidance.float()
+ if input_is_guidance:
+ input = guidance
+ elif input.dtype in (torch.float16, torch.bfloat16):
+ input = input.float()
if guidance.shape[1] == 1:
- return _guided_blur_grayscale_guidance(
+ blur = _guided_blur_grayscale_guidance
+ if isinstance(eps, torch.Tensor):
+ output_dtype = torch.promote_types(output_dtype, eps.dtype)
+ else:
+ blur = _guided_blur_multichannel_guidance
+ # Autocast would lower the box-filter convolutions back to half precision. A meta tensor carries only a shape and
+ # ``torch.autocast("meta")`` raises, so the CPU autocast stands in for it.
+ device_type = "cpu" if guidance.device.type == "meta" else guidance.device.type
+ with torch.autocast(device_type=device_type, enabled=False):
+ return blur(
guidance,
input,
kernel_size,
@@ -263,16 +287,7 @@ def guided_blur(
border_type,
subsample,
separable=separable,
- )
- return _guided_blur_multichannel_guidance(
- guidance,
- input,
- kernel_size,
- eps,
- border_type,
- subsample,
- separable=separable,
- )
+ ).to(output_dtype)
class GuidedBlur(nn.Module):
diff --git a/tests/filters/test_guided.py b/tests/filters/test_guided.py
index ad5dbb06f..e0c51ef9e 100644
--- a/tests/filters/test_guided.py
+++ b/tests/filters/test_guided.py
@@ -34,12 +34,8 @@ from kornia.filters.guided import _preprocess_fast_guided_blur, _subsample_indic
from testing.base import BaseTester, supports_reflect_padding, supports_replicate_padding
-# The guided filter is ill-conditioned in half precision: the window variance is E[g^2] - E[g]^2, a cancellation,
-# and the coefficient cov / (var + eps) amplifies its error by up to 1 / eps. Worst absolute error against float64
-# over 150 seeds: 0.008 (float16) and 0.092 (bfloat16) at eps=0.1, 0.0013 and 0.0102 at eps=1.0, 42 (bfloat16) at
-# eps=0.01; float32 2.4e-7 at eps=1.0. So the half dtypes use eps=1.0 and a tolerance a few times that error on
-# non-divisible sizes, float32 and float64 eps=0.1 and the harness's. bfloat16's 0.05 still catches only gross errors
-# (an align_corners=True mutant slips through most of them); float16's 0.01 catches it.
+# The fast-filter grid checks retain their broad half-precision tolerances.
+# Small-regularization regressions below separately check covariance accuracy.
_HALF_TOLERANCE = {torch.float16: 0.01, torch.bfloat16: 0.05}
@@ -114,6 +110,98 @@ def _scale_factor_interpolate(x, size=None, scale_factor=None, mode=None, **kwar
class TestGuidedBlur(BaseTester):
+ @pytest.mark.parametrize("guide_dim", [1, 3])
+ @pytest.mark.parametrize("eps", [1e-4, 1e-3])
+ def test_flat_guidance_small_regularization(self, guide_dim, eps, device, dtype):
+ """Constant guidance reduces to two input means even with small regularization."""
+ guide = torch.full((1, guide_dim, 9, 13), 0.5, device=device, dtype=dtype)
+ image = torch.linspace(0.1, 0.9, 117, device=device, dtype=dtype).reshape(1, 1, 9, 13)
+ # A constant guidance has zero covariance: the result is the mean of
+ # the local input means, independently of the regularization.
+ expected = image.double() if dtype == torch.float64 else image.float()
+ for _ in range(2):
+ expected = F.avg_pool2d(F.pad(expected, (2, 2, 2, 2), mode="reflect"), 5, stride=1)
+ actual = guided_blur(guide, image, 5, eps)
+ assert actual.dtype == dtype
+ self.assert_close(actual, expected.to(dtype))
+
+ @pytest.mark.parametrize("guide_dim", [1, 3])
+ def test_half_low_contrast_gradients(self, guide_dim, device, dtype):
+ """Half-precision low-contrast outputs and gradients match float32 calculations."""
+ if dtype not in (torch.float16, torch.bfloat16):
+ pytest.skip("half-precision covariance regression")
+ guide = torch.linspace(0.45, 0.55, 63, device=device, dtype=dtype).reshape(1, 1, 7, 9)
+ guide = guide.repeat(1, guide_dim, 1, 1).requires_grad_()
+ expected_input = guide.detach().clone().requires_grad_()
+ actual = guided_blur(guide, guide, 5, 1e-4)
+ expected_guide = expected_input.float()
+ expected = guided_blur(expected_guide, expected_guide, 5, 1e-4).to(dtype)
+ actual_grad = torch.autograd.grad(actual.float().square().mean(), guide)[0]
+ expected_grad = torch.autograd.grad(expected.float().square().mean(), expected_input)[0]
+ assert torch.isfinite(actual_grad).all()
+ self.assert_close(actual, expected)
+ # The gradients are at most 0.02, below bfloat16's 4 * eps of 0.031: scale the absolute tolerance to them.
+ tolerance = 4 * torch.finfo(dtype).eps
+ self.assert_close(actual_grad, expected_grad, atol=tolerance * expected_grad.abs().max().item(), rtol=tolerance)
+
+ @pytest.mark.parametrize("guide_dim", [1, 3])
+ @pytest.mark.parametrize("separate_input", [False, True])
+ def test_half_inputs_are_filtered_in_float32(self, guide_dim, separate_input, device, dtype):
+ """A half-precision call returns the float32 result for the same values, rounded once to its dtype.
+
+ A separate ``input`` enters the window statistics in float32 too: left in half precision, the rounding of
+ ``E[p]`` alone costs ``E[g p] - E[g] E[p]`` several units in the last place of the result here.
+ """
+ if dtype not in (torch.float16, torch.bfloat16):
+ pytest.skip("half-precision covariance regression")
+ guide = torch.linspace(0.45, 0.55, 63, device=device, dtype=dtype).reshape(1, 1, 7, 9)
+ guide = guide.repeat(1, guide_dim, 1, 1)
+ image = guide
+ if separate_input:
+ image = torch.linspace(0.8, 0.2, 63, device=device, dtype=dtype).reshape(1, 1, 7, 9)
+ guide32 = guide.float()
+ expected = guided_blur(guide32, image.float() if separate_input else guide32, 5, 1e-4).to(dtype)
+ self.assert_close(guided_blur(guide, image, 5, 1e-4), expected, rtol=0, atol=0)
+
+ @pytest.mark.parametrize("guide_dim", [1, 3])
+ def test_meta_tensors(self, guide_dim):
+ """A meta tensor has no autocast backend; the filter still infers its result shape and dtype."""
+ guide = torch.empty(2, guide_dim, 9, 13, device="meta", dtype=torch.float16)
+ image = torch.empty(2, 2, 9, 13, device="meta", dtype=torch.float16)
+ for out, dtype in (
+ (guided_blur(guide, image, 5, 0.01), torch.float16),
+ (guided_blur(guide.float(), image, 5, 0.01), torch.float32),
+ ):
+ assert out.device.type == "meta"
+ assert out.shape == image.shape
+ assert out.dtype == dtype
+
+ @pytest.mark.parametrize("guide_dim", [1, 3])
+ def test_autocast_preserves_covariance(self, guide_dim, device):
+ """Autocast preserves the covariance accuracy of float32 inputs."""
+ if device.type not in ("cpu", "cuda"):
+ pytest.skip("CPU/CUDA autocast regression")
+ guide = torch.linspace(0.45, 0.55, 63, device=device).reshape(1, 1, 7, 9).repeat(1, guide_dim, 1, 1)
+ expected = guided_blur(guide, guide, 5, 1e-4)
+ autocast_dtype = torch.bfloat16 if device.type == "cpu" else torch.float16
+ with torch.autocast(device_type=device.type, dtype=autocast_dtype):
+ actual = guided_blur(guide, guide, 5, 1e-4)
+ assert actual.dtype == expected.dtype
+ self.assert_close(actual, expected)
+
+ @pytest.mark.parametrize("guide_dim", [1, 3])
+ @pytest.mark.parametrize("eps_dtype", [torch.float32, torch.float64])
+ def test_tensor_regularization_output_dtype(self, guide_dim, eps_dtype, device, dtype):
+ """Tensor regularization widens grayscale output while retaining multichannel output dtype."""
+ if eps_dtype == torch.float64 and device.type == "mps":
+ pytest.skip("MPS has no float64")
+ guide = torch.full((1, guide_dim, 5, 7), 0.5, device=device, dtype=dtype)
+ eps = torch.tensor([1e-3], device=device, dtype=eps_dtype)
+ result = guided_blur(guide, guide, 3, eps)
+ expected_dtype = torch.promote_types(dtype, eps_dtype) if guide_dim == 1 else dtype
+ assert result.dtype == expected_dtype
+ self.assert_close(result, torch.full_like(result, 0.5))
+
@pytest.mark.parametrize("batch_size", [1, 2])
@pytest.mark.parametrize("guide_dim", [1, 3])
@pytest.mark.parametrize("input_dim", [1, 3])