Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(filters): run unsharp_mask under autocast (#6183)

Saksham Sharma93f1376e4d16
diff --git a/changelog.d/6183.fixed.md b/changelog.d/6183.fixed.md
new file mode 100644
index 000000000..e42222a06
--- /dev/null
+++ b/changelog.d/6183.fixed.md
@@ -0,0 +1 @@
+`unsharp_mask` and `UnsharpMask` run under `torch.autocast`. Under autocast the blur, a convolution, came back in the autocast dtype, and `torch.lerp`, which does not promote, raised `RuntimeError: expected dtype ... for 'end' but got dtype float` on the mismatch with a float32 image. The blur is now cast to the image's dtype before the `lerp`, so the result keeps the image's dtype, as `2 * image - blur` would and as `kornia.enhance.sharpness` does; outside autocast the cast is a no-op and every result is unchanged.
diff --git a/kornia/filters/unsharp.py b/kornia/filters/unsharp.py
index 621b3a1fe..40aa35204 100644
--- a/kornia/filters/unsharp.py
+++ b/kornia/filters/unsharp.py
@@ -42,6 +42,9 @@ def unsharp_mask(
below 0 and above 1. :ref:`Filtering <filtering-conventions>` maps the call onto scikit-image.
- An integer or bool image is filtered in float32 and the result is float32 on its own scale, like
:func:`~kornia.filters.gaussian_blur2d`; a floating image keeps its dtype.
+ - Under ``torch.autocast`` the blur runs in the autocast dtype, as in :func:`~kornia.filters.gaussian_blur2d`
+ (autocast leaves a float64 image alone), and the result keeps the image's dtype, as for
+ :func:`~kornia.enhance.sharpness`.
Args:
input: the input torch.Tensor with shape :math:`(B,C,H,W)`.
@@ -63,7 +66,10 @@ def unsharp_mask(
"""
input = _to_floating(input)
data_blur: torch.Tensor = gaussian_blur2d(input, kernel_size, sigma, border_type)
- return torch.lerp(data_blur, input, weight=2.0)
+ # Under autocast the blur, a convolution, comes back in the autocast dtype, and torch.lerp, which is not an autocast
+ # op and does not promote, raised on the dtype mismatch with the image. Casting the blur back gives the image's
+ # dtype, as 2 * image - blur would; the cast is a no-op outside autocast.
+ return torch.lerp(data_blur.to(input.dtype), input, weight=2.0)
class UnsharpMask(nn.Module):
diff --git a/tests/filters/test_unsharp_mask.py b/tests/filters/test_unsharp_mask.py
index 166783931..e83932cff 100644
--- a/tests/filters/test_unsharp_mask.py
+++ b/tests/filters/test_unsharp_mask.py
@@ -134,3 +134,58 @@ class TestConventionsUnsharpMask(BaseTester):
self.assert_close(out[0, 0, 3], torch.tensor(expected, device=device, dtype=dtype))
assert out.min() < -0.3
assert out.max() > 1.3
+
+
+def _mixed_precision_region_6182(device):
+ # MPS autocasts to float16, and so does a CUDA device without bfloat16, where bfloat16 autocast raises.
+ if device.type not in ("cpu", "cuda", "mps"):
+ pytest.skip("CPU, CUDA and MPS autocast")
+ bfloat16_ok = device.type == "cpu" or (device.type == "cuda" and torch.cuda.is_bf16_supported())
+ return torch.bfloat16 if bfloat16_ok else torch.float16
+
+
+class TestUnsharpMaskMixedPrecision(BaseTester):
+ """``unsharp_mask`` and ``UnsharpMask`` run inside a mixed-precision region (#6182).
+
+ No "autocast" in the test names: the repository conftest skips those on MPS.
+ """
+
+ @pytest.mark.parametrize("as_module", [False, True])
+ def test_a_mixed_precision_region_keeps_the_image_dtype_6182(self, device, as_module):
+ # The blur, a convolution, came back in the autocast dtype and met the float32 image in torch.lerp, which raised
+ # "expected dtype ... for `end` but got dtype float". The blur is now cast back, as 2 * image - blur would be.
+ region_dtype = _mixed_precision_region_6182(device)
+ generator = torch.Generator().manual_seed(6182)
+ image = torch.rand(2, 3, 16, 20, generator=generator).to(device)
+ op = UnsharpMask((5, 5), (1.5, 1.5)) if as_module else lambda x: unsharp_mask(x, (5, 5), (1.5, 1.5))
+ with torch.autocast(device.type, dtype=region_dtype):
+ actual = op(image)
+ blur = gaussian_blur2d(image, (5, 5), (1.5, 1.5))
+ assert blur.dtype == region_dtype
+ assert actual.dtype == torch.float32
+ self.assert_close(actual, torch.lerp(blur.float(), image, weight=2.0), atol=0, rtol=0)
+ self.assert_close(actual, unsharp_mask(image, (5, 5), (1.5, 1.5)), atol=5e-2, rtol=0)
+
+ def test_half_precision_image_in_the_other_half_precision_region_6182(self, device):
+ # A float16 image inside a bfloat16 region also raised; it now keeps float16.
+ if device.type != "cpu":
+ pytest.skip("measured on the CPU")
+ image = torch.rand(1, 3, 12, 12, generator=torch.Generator().manual_seed(6182)).to(device, torch.float16)
+ with torch.autocast(device.type, dtype=torch.bfloat16):
+ out = unsharp_mask(image, (3, 3), (1.0, 1.0))
+ assert out.dtype == torch.float16
+ self.assert_close(out.float(), unsharp_mask(image.float(), (3, 3), (1.0, 1.0)), atol=5e-2, rtol=0)
+
+ def test_gradient_in_a_mixed_precision_region_6182(self, device):
+ region_dtype = _mixed_precision_region_6182(device)
+ image = torch.rand(1, 3, 12, 12, device=device, requires_grad=True)
+ with torch.autocast(device.type, dtype=region_dtype):
+ out = unsharp_mask(image, (3, 3), (1.0, 1.0))
+ out.sum().backward()
+ assert out.dtype == torch.float32
+ assert image.grad is not None
+ assert image.grad.dtype == torch.float32
+ assert torch.isfinite(image.grad).all()
+ # The gradient also flows back through the blur: it matches that of 2 * image - blur outside the region.
+ (expected,) = torch.autograd.grad((2 * image - gaussian_blur2d(image, (3, 3), (1.0, 1.0))).sum(), image)
+ self.assert_close(image.grad, expected, atol=5e-2, rtol=0)