Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

perf(filters): keep bilateral_blur's window temporaries contiguous (#6280)

Dmytro Mishkin216afad23670
diff --git a/changelog.d/6280.fixed.md b/changelog.d/6280.fixed.md
new file mode 100644
index 000000000..2966c45d6
--- /dev/null
+++ b/changelog.d/6280.fixed.md
@@ -0,0 +1,6 @@
+`bilateral_blur` and `joint_bilateral_blur` are much faster on MPS: an 8 x 3 x 256 x 256 batch with a 5 x 5 kernel takes
+40 ms on an M1 Pro, against 556 ms before and 30 ms in 0.8.3; a grayscale batch takes 18 ms, against 378 ms before and
+208 ms in 0.8.3; and the RGB forward and backward pass takes 127 ms, against 1.1 s before. The filter's window tensors
+are now laid out in their memory order, which also makes CPU inputs that take the unfold path (small or differentiated
+ones) up to 30 % faster. Without a gradient the unfold path frees each window-sized temporary once used, so its
+peak memory is 27-42 % lower. Values change only by the rounding of a different summation order.
diff --git a/kornia/filters/bilateral.py b/kornia/filters/bilateral.py
index b20cc8eff..6dfa90377 100644
--- a/kornia/filters/bilateral.py
+++ b/kornia/filters/bilateral.py
@@ -155,7 +155,7 @@ def _bilateral_blur_cpu(
) -> torch.Tensor:
"""Bilateral filter as a loop over the kernel taps, without unfolding every window.
- The unfold path materialises several :math:`(B, C, H, W, k_y, k_x)` tensors, :math:`k_y k_x` times the image; on a
+ The unfold path materialises several :math:`(B, C, H, k_y, W, k_x)` tensors, :math:`k_y k_x` times the image; on a
large CPU batch they are fresh memory, faulted in on every call. Here every tap takes shifted slices of the padded
guidance and input, computes its weights with the unfold path's expression, so they are the same numbers, and adds
them to the weighted sum and to the normalizer; only the order of the :math:`k_y k_x` terms of those two sums
@@ -269,31 +269,50 @@ def _bilateral_blur(
sigma_color = sigma_color.view(-1, 1, 1, 1, 1, 1)
pad_y, pad_x = _compute_zero_padding(kernel_size)
- # Keep both patch axes: flattening them would copy every overlapping window.
+ # Keep both patch axes: flattening them would copy every overlapping window. The windows are viewed in the order of
+ # their elements in memory, (B, C, H, Ky, W, Kx), so that the arithmetic allocates every temporary contiguous, and
+ # every reduction, here and in the backward, runs over one axis. MPS reduces a permuted 6-D tensor about 150 times
+ # slower than a contiguous one (an M1: 238 ms against 1.4 ms for the colour distance of an 8 x 3 x 256 x 256 batch
+ # with a 5 x 5 kernel), and two axes that are not adjacent, such as Ky and Kx, about 140 times slower than one at a
+ # time, on torch 2.14 and on a 2.16 nightly alike.
padded_input = F.pad(input, (pad_x, pad_x, pad_y, pad_y), mode=border_type)
- unfolded_input = padded_input.unfold(2, ky, 1).unfold(3, kx, 1) # (B, C, H, W, Ky, Kx)
+ unfolded_input = padded_input.unfold(2, ky, 1).unfold(3, kx, 1).permute(0, 1, 2, 4, 3, 5) # (B, C, H, Ky, W, Kx)
if guidance is None:
guidance = input
unfolded_guidance = unfolded_input
else:
padded_guidance = F.pad(guidance, (pad_x, pad_x, pad_y, pad_y), mode=border_type)
- unfolded_guidance = padded_guidance.unfold(2, ky, 1).unfold(3, kx, 1) # (B, C, H, W, Ky, Kx)
+ unfolded_guidance = padded_guidance.unfold(2, ky, 1).unfold(3, kx, 1).permute(0, 1, 2, 4, 3, 5)
+ # After the padding, whose errors come first, as in the tap loop, and before any window arithmetic.
+ if color_distance_type not in ("l1", "l2"):
+ raise ValueError("color_distance_type only accepts l1 or l2")
- diff = unfolded_guidance - guidance[..., None, None]
- if color_distance_type == "l1":
+ # The centre pixel is broadcast over Kx by an expand and over Ky by the subtraction, so that the backward sums its
+ # gradient over one axis at a time.
+ centre = guidance.unsqueeze(-1).expand(-1, -1, -1, -1, kx).unsqueeze(3) # (B, C, H, 1, W, Kx)
+ diff = unfolded_guidance - centre
+ if diff.shape[1] == 1:
+ # One channel's sum is the value itself, so the sum is skipped: on torch 2.14, MPS reduces over an axis of
+ # size 1 about 270 times slower than it squares (222 ms against 0.8 ms). l1 keeps its abs(): |d|^2 is d^2
+ # only for a real difference, not for a complex one.
+ color_distance_sq = diff.abs().square() if color_distance_type == "l1" else diff.square()
+ elif color_distance_type == "l1":
color_distance_sq = diff.abs().sum(1, keepdim=True).square()
- elif color_distance_type == "l2":
- color_distance_sq = diff.square().sum(1, keepdim=True)
else:
- raise ValueError("color_distance_type only accepts l1 or l2")
- color_kernel = (-0.5 / sigma_color**2 * color_distance_sq).exp() # (B, 1, H, W, Ky, Kx)
+ color_distance_sq = diff.square().sum(1, keepdim=True)
+ del diff
space_kernel = get_gaussian_kernel2d(kernel_size, sigma_space, device=input.device, dtype=input.dtype)
- space_kernel = space_kernel.view(-1, 1, 1, 1, ky, kx)
-
- kernel = space_kernel * color_kernel
- return (unfolded_input * kernel).sum((-2, -1)) / kernel.sum((-2, -1))
+ space_kernel = space_kernel.view(-1, 1, 1, ky, 1, kx)
+
+ # Each window-sized temporary is freed once consumed. Without a gradient that lowers the peak memory by 27-42 % (an
+ # 8 x 3 or 8 x 1 x 256 x 256 batch, 5 x 5 kernel), and a fresh CPU process, whose glibc heap still returns a few MB
+ # to the system on every free, faults fewer pages back in per call.
+ kernel = space_kernel * (-0.5 / sigma_color**2 * color_distance_sq).exp() # (B, 1, H, Ky, W, Kx)
+ del color_distance_sq
+ # Over Kx, then over Ky.
+ return (unfolded_input * kernel).sum(-1).sum(-2) / kernel.sum(-1).sum(-2)
def bilateral_blur(
diff --git a/tests/filters/test_bilateral.py b/tests/filters/test_bilateral.py
index 12c0566a3..8033ac245 100644
--- a/tests/filters/test_bilateral.py
+++ b/tests/filters/test_bilateral.py
@@ -28,6 +28,7 @@ from kornia.filters import (
gaussian_blur2d,
joint_bilateral_blur,
)
+from kornia.filters.kernels import get_gaussian_kernel2d
from testing.base import BaseTester, supports_reflect_padding, supports_replicate_padding
@@ -221,6 +222,86 @@ class TestBilateralBlur(BaseTester):
self.gradcheck(bilateral_blur, (img, 3, 1, sigma_space), nondet_tol=1e-4)
self.gradcheck(bilateral_blur, (img, 3, sigma_color, sigma_space), nondet_tol=1e-4)
+ @pytest.mark.parametrize("kernel_size", [(3, 5), (5, 3)])
+ @pytest.mark.parametrize("color_distance_type", ["l1", "l2"])
+ @pytest.mark.parametrize(("channels", "guidance_channels"), [(1, None), (3, None), (3, 1), (1, 3)])
+ def test_matches_a_tap_sum(self, kernel_size, color_distance_type, channels, guidance_channels, device, dtype):
+ # The windows are viewed as (B, C, H, Ky, W, Kx); a rectangular kernel with an anisotropic, per-sample spatial
+ # sigma would expose a swapped window axis, in the values or in the gradients, on any device.
+ if not supports_reflect_padding(device, dtype):
+ pytest.skip("reflection padding is unsupported for this device/dtype")
+ torch.manual_seed(0)
+ image = torch.rand(2, channels, 7, 9, device=device, dtype=dtype)
+ guidance = (
+ None if guidance_channels is None else torch.rand(2, guidance_channels, 7, 9, device=device, dtype=dtype)
+ )
+ sigma_color = torch.tensor([0.1, 0.4], device=device, dtype=dtype)
+ sigma_space = torch.tensor([[1.0, 2.0], [2.5, 0.7]], device=device, dtype=dtype)
+ weight = torch.rand(2, channels, 7, 9, device=device, dtype=dtype)
+ sigma_color_ref = sigma_color.cpu().double().view(-1, 1, 1, 1)
+
+ def tap_sum(image, guidance):
+ # Float64 on the CPU, one shifted slice per tap, without any window view.
+ ky, kx = kernel_size
+ height, width = image.shape[-2:]
+ guide = image if guidance is None else guidance
+ padded_image = torch.nn.functional.pad(image, (kx // 2, kx // 2, ky // 2, ky // 2), mode="reflect")
+ padded_guide = torch.nn.functional.pad(guide, (kx // 2, kx // 2, ky // 2, ky // 2), mode="reflect")
+ space = get_gaussian_kernel2d(kernel_size, sigma_space.cpu().double())
+ numerator, denominator = 0.0, 0.0
+ for dy in range(ky):
+ for dx in range(kx):
+ diff = padded_guide[..., dy : dy + height, dx : dx + width] - guide
+ if color_distance_type == "l1":
+ distance_sq = diff.abs().sum(1, keepdim=True).square()
+ else:
+ distance_sq = diff.square().sum(1, keepdim=True)
+ tap = space[:, dy, dx].view(-1, 1, 1, 1) * (-0.5 * distance_sq / sigma_color_ref**2).exp()
+ numerator = numerator + tap * padded_image[..., dy : dy + height, dx : dx + width]
+ denominator = denominator + tap
+ return numerator / denominator
+
+ image_ref = image.cpu().double().clone().requires_grad_()
+ guidance_ref = None if guidance is None else guidance.cpu().double().clone().requires_grad_()
+ expected = tap_sum(image_ref, guidance_ref)
+ (expected * weight.cpu().double()).sum().backward()
+
+ image = image.clone().requires_grad_()
+ if guidance is None:
+ actual = bilateral_blur(
+ image, kernel_size, sigma_color, sigma_space, color_distance_type=color_distance_type
+ )
+ else:
+ guidance = guidance.clone().requires_grad_()
+ actual = joint_bilateral_blur(
+ image, guidance, kernel_size, sigma_color, sigma_space, color_distance_type=color_distance_type
+ )
+ self.assert_close(actual, expected.to(device, dtype))
+ if dtype in (torch.float16, torch.bfloat16):
+ return
+ (actual * weight).sum().backward()
+ self.assert_close(image.grad, image_ref.grad.to(device, dtype), rtol=1e-4, atol=1e-4)
+ if guidance is not None:
+ self.assert_close(guidance.grad, guidance_ref.grad.to(device, dtype), rtol=1e-4, atol=1e-4)
+
+ @pytest.mark.device_agnostic
+ @pytest.mark.parametrize("joint", [False, True])
+ def test_complex_single_channel_l1_weighs_the_squared_magnitude(self, joint):
+ # l1 weighs a difference d by |d|^2, which for a complex d is not d^2, also where one channel skips the sum.
+ image = torch.tensor([[[[0j, 1j, 0j]]]], dtype=torch.complex64)
+ sigma_space = torch.tensor([[1.0, 1.0]])
+ args = ((1, 3), 1.0, sigma_space)
+ kwargs = {"border_type": "constant", "color_distance_type": "l1"}
+ if joint:
+ actual = joint_bilateral_blur(image, image.clone(), *args, **kwargs)
+ else:
+ actual = bilateral_blur(image, *args, **kwargs)
+ # Space weights exp(-1/2) beside the centre, colour weights exp(-|d|^2 / 2) with |d|^2 = 1 next to 1j.
+ e = math.exp(-0.5)
+ edge = e**2 / (1 + e + e**2)
+ expected = torch.tensor([[[[edge * 1j, 1j / (1 + 2 * e**2), edge * 1j]]]], dtype=torch.complex64)
+ self.assert_close(actual, expected)
+
@pytest.mark.parametrize("shape", [(1, 1, 8, 15), (2, 3, 11, 7)])
@pytest.mark.parametrize("kernel_size", [5, (3, 5)])
@pytest.mark.parametrize("sigma_color", [1, 0.1])