Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(filters): make guided_blur work at half precision with multi-channel guidance (#4087)

Dmytro Mishkin5f46e6daa189
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e31ded146..2bd49e968 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -25,6 +25,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Bug fixes
+* Make `guided_blur` / `GuidedBlur` work in `float16` and `bfloat16` when the guidance has more than one channel.
+ Multi-channel guidance solves a per-pixel `C x C` system, and `torch.linalg.solve` has no half-precision LU
+ kernel, so every such call failed: on CPU with `NotImplementedError: "lu_cpu" not implemented for 'Half'`, and on
+ MPS with a hard `Only MPSDataTypeFloat32 is supported` assertion that aborted the process rather than raising.
+ The system is now solved in `float32` and cast back. A tensor `eps` also takes part in dtype promotion, so
+ the common `eps=torch.tensor(0.1)` (float32) widened the matrix past the right-hand side and made `solve`
+ reject the pair; both operands are now solved in one dtype. Single-channel guidance never reached the solver
+ and is unaffected. `float32` and `float64` results are bit-identical to before, and the op still compiles with
+ `fullgraph=True` in one graph. This takes `tests/filters/test_guided.py` from 98 failed / 67 passed to
+ 169 passed under `--dtype=float16,bfloat16`.
+
* Raise `NotImplementedError` instead of `RuntimeError` for an integral `src` on the empty-`dsize` paths of
`warp_affine`, `warp_perspective`, `remap`, `warp_affine3d` and `warp_perspective3d`, matching what the non-empty path already raises from
`grid_sample` (#4031). The degenerate path had its own explicit guard that fired first with a different exception
diff --git a/kornia/filters/guided.py b/kornia/filters/guided.py
index 370589427..fc3a6dc02 100644
--- a/kornia/filters/guided.py
+++ b/kornia/filters/guided.py
@@ -113,7 +113,21 @@ def _guided_blur_multichannel_guidance(
_eps = torch.eye(C, device=guidance.device, dtype=guidance.dtype).view(1, 1, 1, C, C) * eps.view(-1, 1, 1, 1, 1)
else:
_eps = guidance.new_full((C,), eps).diag().view(1, 1, 1, C, C)
- a = torch.linalg.solve(var_I + _eps, cov_Ip) # B, H, W, C_guidance, C_input
+ # ``torch.linalg.solve`` needs both operands in one dtype, and it has no half-precision LU
+ # kernel: a float16/bfloat16 guidance dies here with ``NotImplementedError: "lu_cpu" not
+ # implemented for 'Half'``, and on MPS it aborts the process instead of raising. A tensor
+ # ``eps`` also takes part in promotion, so ``A`` can come out wider than ``cov_Ip`` -- the
+ # common ``eps=torch.tensor(0.1)`` is float32 -- and ``solve`` rejects the mismatched pair.
+ # So pick a single dtype for both operands, lifting half to float32, and cast the solution
+ # back. Deliberately not ``_torch_solve_cast``: that promotes float32 to float64, which would
+ # change the results of the default path and pay for a float64 solve at every pixel.
+ # ``Tensor.to`` is a no-op when the dtype already matches, so an all-float32 or all-float64
+ # call takes exactly the path it took before.
+ A = var_I + _eps
+ solve_dtype = torch.promote_types(A.dtype, cov_Ip.dtype)
+ if solve_dtype in (torch.float16, torch.bfloat16):
+ solve_dtype = torch.float32
+ a = torch.linalg.solve(A.to(solve_dtype), cov_Ip.to(solve_dtype)).to(cov_Ip.dtype)
b = mean_p - (mean_I.unsqueeze(-2) @ a).squeeze(-2) # B, H, W, C_input
mean_a = box_blur(a.flatten(-2).permute(0, 3, 1, 2), kernel_size, border_type, separable=separable)
diff --git a/tests/filters/test_guided.py b/tests/filters/test_guided.py
index b03cefee7..cd4e3a748 100644
--- a/tests/filters/test_guided.py
+++ b/tests/filters/test_guided.py
@@ -107,8 +107,10 @@ class TestGuidedBlur(BaseTester):
separable=True,
)
- if dtype in (torch.float16, torch.bfloat16):
- # The two convolution decompositions accumulate rounding errors in different orders at half precision.
+ if dtype == torch.float16:
+ # The two convolution decompositions accumulate rounding errors in different orders at
+ # half precision. Only float16 needs this: measured worst case is 1.953e-03 against the
+ # harness's 1e-03, while every bfloat16 case fits inside _DTYPE_PRECISIONS already.
tolerance = 3 * torch.finfo(dtype).eps
self.assert_close(actual, expected, rtol=tolerance, atol=tolerance)
else:
@@ -201,6 +203,42 @@ class TestGuidedBlur(BaseTester):
op(guide, img, kernel_size, eps, subsample=subsample, separable=separable),
)
+ @pytest.mark.parametrize("tensor_eps", [False, True], ids=["float_eps", "tensor_eps"])
+ def test_multichannel_guidance_in_half_precision(self, tensor_eps, device, dtype) -> None:
+ """Multi-channel guidance must run in float16/bfloat16 rather than dying in the solver.
+
+ ``_guided_blur_multichannel_guidance`` solves a C x C system per pixel, and
+ ``torch.linalg.solve`` has no half-precision LU kernel: before the fix this raised
+ ``NotImplementedError: "lu_cpu" not implemented for 'Half'`` on CPU, and on MPS it aborted
+ the process outright with ``Only MPSDataTypeFloat32 is supported``. Single-channel guidance
+ never reached the solver, so only ``guide_dim > 1`` was affected.
+
+ The ``tensor_eps`` case is the second half of the same bug: ``torch.tensor(0.1)`` is float32
+ even next to a half guidance and takes part in dtype promotion, so the matrix handed to
+ ``solve`` is wider than the right-hand side.
+ """
+ if dtype not in (torch.float16, torch.bfloat16):
+ pytest.skip("regression test for the half-precision solve path")
+
+ # ``constant`` keeps this test on the solver: the default ``reflect`` border needs a
+ # half-precision ``reflection_pad2d``, which CPU PyTorch 2.5.1 does not have for float16.
+ border_type = "constant"
+ eps = torch.tensor(0.1, device=device) if tensor_eps else 0.1
+
+ guide = torch.rand(1, 3, 12, 16, device=device, dtype=dtype)
+ inp = torch.rand(1, 2, 12, 16, device=device, dtype=dtype)
+
+ actual = guided_blur(guide, inp, 5, eps, border_type=border_type)
+
+ assert actual.dtype == dtype
+ assert torch.isfinite(actual).all()
+
+ # The solve runs in float32, so the result must track the exact answer to within the
+ # accumulated error of the surrounding half-precision arithmetic, not the solver's.
+ expected = guided_blur(guide.float(), inp.float(), 5, eps, border_type=border_type)
+ tolerance = 8 * torch.finfo(dtype).eps
+ self.assert_close(actual.float(), expected, rtol=tolerance, atol=tolerance)
+
@pytest.mark.skipif(
torch_version() in {"1.9.1", "2.1.0", "2.1.1", "2.1.2"},
reason=(
@@ -311,4 +349,13 @@ class TestGuidedBlur(BaseTester):
expected = torch.tensor(expected, device=device, dtype=dtype).view(1, 3, 4, 4)
out = guided_blur(guide, img, kernel_size, eps, border_type="replicate")
- self.assert_close(out, expected)
+ if dtype == torch.bfloat16:
+ # Multi-channel guidance chains three box blurs, a 3x3 solve and an einsum, so the error
+ # is a few eps rather than one. Measured against this op's own float64 result the error
+ # is 2.95 eps for bfloat16, 1.39 for float16 and 3.27 for float32 -- i.e. bfloat16 is not
+ # an outlier, the harness's 1-eps budget is simply too tight here. bfloat16 also cannot
+ # represent the inputs to better than 3.6e-3, over half that budget, before any
+ # arithmetic runs. float16 and float32 still use the harness tolerances.
+ self.assert_close(out, expected, rtol=4 * torch.finfo(dtype).eps, atol=4 * torch.finfo(dtype).eps)
+ else:
+ self.assert_close(out, expected)