Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(filters): check the sigma_color and sigma_space batch in the bilateral blurs (#5432)

Muhammad Talha0d2532a6fb1b
diff --git a/changelog.d/5432.breaking.md b/changelog.d/5432.breaking.md
new file mode 100644
index 000000000..40d9b260b
--- /dev/null
+++ b/changelog.d/5432.breaking.md
@@ -0,0 +1,4 @@
+`bilateral_blur`, `joint_bilateral_blur`, `BilateralBlur` and `JointBilateralBlur` now raise a kornia error when an
+input of batch 1 is given a tensor `sigma_color` or `sigma_space` with a larger batch (#5430). Previously the
+broadcast succeeded silently and returned a batch as large as the sigma batch, for example 3 images from 1 input and 3
+`sigma_color` values. A sigma batch of 1, or equal to the input batch, is unchanged.
diff --git a/changelog.d/5432.fixed.md b/changelog.d/5432.fixed.md
new file mode 100644
index 000000000..971241f98
--- /dev/null
+++ b/changelog.d/5432.fixed.md
@@ -0,0 +1,4 @@
+`bilateral_blur`, `joint_bilateral_blur`, `BilateralBlur` and `JointBilateralBlur` now reject a tensor `sigma_color` or
+`sigma_space` whose batch is neither 1 nor the input batch at their entry with a kornia error that names the argument
+and both sizes, before any padding or kernel is built (#5430). Previously the mismatch surfaced as a torch broadcast
+error from inside the filter that named neither argument.
diff --git a/kornia/filters/bilateral.py b/kornia/filters/bilateral.py
index 527c1d911..d401dc684 100644
--- a/kornia/filters/bilateral.py
+++ b/kornia/filters/bilateral.py
@@ -30,6 +30,18 @@ from .kernels import _check_kernel_size, _unpack_2d_ks, get_gaussian_kernel2d
from .median import _compute_zero_padding
+def _check_sigma_batch(name: str, sigma: torch.Tensor, input: torch.Tensor) -> None:
+ """Check that a tensor sigma has a batch of 1, shared by the input, or the input batch."""
+ # Format the sizes only on failure: an f-string evaluated on every call makes Dynamo specialize the batch size,
+ # so a dynamic-shape torch.compile would recompile for each new batch.
+ if sigma.shape[0] not in (1, input.shape[0]):
+ KORNIA_CHECK(
+ False,
+ f"{name} must have a batch of 1 or the input batch. "
+ f"Got a {name} batch of {sigma.shape[0]} for an input batch of {input.shape[0]}",
+ )
+
+
def _bilateral_blur(
input: torch.Tensor,
guidance: Optional[torch.Tensor],
@@ -53,6 +65,7 @@ def _bilateral_blur(
if isinstance(sigma_color, torch.Tensor):
KORNIA_CHECK_SHAPE(sigma_color, ["B"])
+ _check_sigma_batch("sigma_color", sigma_color, input)
# `bool()` on a tensor is untraceable by dynamo; skip the data-dependent check under compile.
if not is_compiling() and not bool((sigma_color > 0).all()):
KORNIA_CHECK(False, f"sigma_color must be positive. Got {sigma_color}")
@@ -60,6 +73,10 @@ def _bilateral_blur(
elif not sigma_color > 0:
KORNIA_CHECK(False, f"sigma_color must be positive. Got {sigma_color}")
+ if isinstance(sigma_space, torch.Tensor):
+ KORNIA_CHECK_SHAPE(sigma_space, ["B", "2"])
+ _check_sigma_batch("sigma_space", sigma_space, input)
+
ky, kx = _unpack_2d_ks(kernel_size)
_check_kernel_size((ky, kx))
pad_y, pad_x = _compute_zero_padding(kernel_size)
@@ -111,9 +128,11 @@ def bilateral_blur(
input: the input torch.Tensor with shape :math:`(B,C,H,W)`.
kernel_size: the size of the kernel. Each entry must be a positive odd integer.
sigma_color: the standard deviation for intensity/color Gaussian kernel.
- Smaller values preserve more edges. It must be positive.
+ Smaller values preserve more edges. It must be positive. A float is shared by the batch; a
+ torch.Tensor has shape :math:`(1,)`, shared by the batch, or :math:`(B,)`, one value per sample.
sigma_space: the standard deviation for spatial Gaussian kernel.
- This is similar to ``sigma`` in :func:`gaussian_blur2d()`.
+ This is similar to ``sigma`` in :func:`gaussian_blur2d()`. A tuple of two floats is shared by the batch;
+ a torch.Tensor has shape :math:`(1, 2)`, shared by the batch, or :math:`(B, 2)`, one row per sample.
border_type: the padding mode to be applied before convolving.
The expected modes are: ``'constant'``, ``'reflect'``,
``'replicate'`` or ``'circular'``. Default: ``'reflect'``.
@@ -128,6 +147,7 @@ def bilateral_blur(
Raises:
BaseError: if an entry of ``kernel_size`` is even or not positive.
BaseError: if ``sigma_color`` is not positive.
+ BaseError: if the batch of a tensor ``sigma_color`` or ``sigma_space`` is neither 1 nor the input batch.
Examples:
>>> input = torch.rand(2, 4, 5, 5)
@@ -161,9 +181,11 @@ def joint_bilateral_blur(
guidance: the guidance torch.Tensor with shape :math:`(B,C,H,W)`.
kernel_size: the size of the kernel. Each entry must be a positive odd integer.
sigma_color: the standard deviation for intensity/color Gaussian kernel.
- Smaller values preserve more edges. It must be positive.
+ Smaller values preserve more edges. It must be positive. A float is shared by the batch; a
+ torch.Tensor has shape :math:`(1,)`, shared by the batch, or :math:`(B,)`, one value per sample.
sigma_space: the standard deviation for spatial Gaussian kernel.
- This is similar to ``sigma`` in :func:`gaussian_blur2d()`.
+ This is similar to ``sigma`` in :func:`gaussian_blur2d()`. A tuple of two floats is shared by the batch;
+ a torch.Tensor has shape :math:`(1, 2)`, shared by the batch, or :math:`(B, 2)`, one row per sample.
border_type: the padding mode to be applied before convolving.
The expected modes are: ``'constant'``, ``'reflect'``,
``'replicate'`` or ``'circular'``. Default: ``'reflect'``.
@@ -177,6 +199,7 @@ def joint_bilateral_blur(
Raises:
BaseError: if an entry of ``kernel_size`` is even or not positive.
BaseError: if ``sigma_color`` is not positive.
+ BaseError: if the batch of a tensor ``sigma_color`` or ``sigma_space`` is neither 1 nor the input batch.
Examples:
>>> input = torch.rand(2, 4, 5, 5)
@@ -228,9 +251,11 @@ class BilateralBlur(_BilateralBlur):
Arguments:
kernel_size: the size of the kernel. Each entry must be a positive odd integer.
sigma_color: the standard deviation for intensity/color Gaussian kernel.
- Smaller values preserve more edges. It must be positive.
+ Smaller values preserve more edges. It must be positive. A float is shared by the batch; a
+ torch.Tensor has shape :math:`(1,)`, shared by the batch, or :math:`(B,)`, one value per sample.
sigma_space: the standard deviation for spatial Gaussian kernel.
- This is similar to ``sigma`` in :func:`gaussian_blur2d()`.
+ This is similar to ``sigma`` in :func:`gaussian_blur2d()`. A tuple of two floats is shared by the batch;
+ a torch.Tensor has shape :math:`(1, 2)`, shared by the batch, or :math:`(B, 2)`, one row per sample.
border_type: the padding mode to be applied before convolving.
The expected modes are: ``'constant'``, ``'reflect'``,
``'replicate'`` or ``'circular'``. Default: ``'reflect'``.
@@ -249,6 +274,8 @@ class BilateralBlur(_BilateralBlur):
Raises:
BaseError: if an entry of ``kernel_size`` is even or not positive; raised from the constructor.
BaseError: if ``sigma_color`` is not positive; raised from ``forward``.
+ BaseError: if the batch of a tensor ``sigma_color`` or ``sigma_space`` is neither 1 nor the input batch;
+ raised from ``forward``.
Examples:
>>> input = torch.rand(2, 4, 5, 5)
@@ -296,9 +323,11 @@ class JointBilateralBlur(_BilateralBlur):
Arguments:
kernel_size: the size of the kernel. Each entry must be a positive odd integer.
sigma_color: the standard deviation for intensity/color Gaussian kernel.
- Smaller values preserve more edges. It must be positive.
+ Smaller values preserve more edges. It must be positive. A float is shared by the batch; a
+ torch.Tensor has shape :math:`(1,)`, shared by the batch, or :math:`(B,)`, one value per sample.
sigma_space: the standard deviation for spatial Gaussian kernel.
- This is similar to ``sigma`` in :func:`gaussian_blur2d()`.
+ This is similar to ``sigma`` in :func:`gaussian_blur2d()`. A tuple of two floats is shared by the batch;
+ a torch.Tensor has shape :math:`(1, 2)`, shared by the batch, or :math:`(B, 2)`, one row per sample.
border_type: the padding mode to be applied before convolving.
The expected modes are: ``'constant'``, ``'reflect'``,
``'replicate'`` or ``'circular'``. Default: ``'reflect'``.
@@ -316,6 +345,8 @@ class JointBilateralBlur(_BilateralBlur):
Raises:
BaseError: if an entry of ``kernel_size`` is even or not positive; raised from the constructor.
BaseError: if ``sigma_color`` is not positive; raised from ``forward``.
+ BaseError: if the batch of a tensor ``sigma_color`` or ``sigma_space`` is neither 1 nor the input batch;
+ raised from ``forward``.
Examples:
>>> input = torch.rand(2, 4, 5, 5)
diff --git a/tests/filters/test_bilateral.py b/tests/filters/test_bilateral.py
index b0b52a2cd..2e02a0a6f 100644
--- a/tests/filters/test_bilateral.py
+++ b/tests/filters/test_bilateral.py
@@ -105,6 +105,70 @@ class TestBilateralBlur(BaseTester):
with pytest.raises(BaseError, match="sigma_color must be positive"):
call()
+ @pytest.mark.parametrize("name", ["sigma_color", "sigma_space"])
+ @pytest.mark.parametrize(
+ "batch, rows",
+ [(2, 3), (4, 2), (4, 3), (1, 3)],
+ ids=["2_vs_3", "4_vs_2", "4_vs_3", "1_vs_3"],
+ )
+ def test_sigma_batch_mismatch_5430(self, name, batch, rows, device, dtype):
+ # A tensor sigma batch that is neither 1 nor the input batch raises at the entry with a message naming the
+ # argument and both sizes, not a torch broadcast error. Input batch 1 with 3 sigma rows used to succeed and
+ # silently return a batch of 3, so it is covered too. The check covers the joint filter and the modules.
+ from kornia.core.exceptions import BaseError
+
+ image = torch.rand(batch, 3, 8, 9, device=device, dtype=dtype)
+ sigma_color = 0.5
+ sigma_space = (1.0, 1.0)
+ if name == "sigma_color":
+ sigma_color = torch.linspace(0.5, 1.0, rows, device=device, dtype=dtype)
+ else:
+ sigma_space = torch.full((rows, 2), 1.5, device=device, dtype=dtype)
+
+ calls = (
+ lambda: bilateral_blur(image, 3, sigma_color, sigma_space),
+ lambda: joint_bilateral_blur(image, image, 3, sigma_color, sigma_space),
+ lambda: BilateralBlur(3, sigma_color, sigma_space)(image),
+ lambda: JointBilateralBlur(3, sigma_color, sigma_space)(image, image),
+ )
+ for call in calls:
+ with pytest.raises(BaseError, match=f"{name} batch of {rows} for an input batch of {batch}"):
+ call()
+
+ @pytest.mark.parametrize("name", ["sigma_color", "sigma_space"])
+ @pytest.mark.parametrize("per_sample", [False, True], ids=["shared", "per_sample"])
+ def test_sigma_batch_accepted_5430(self, name, per_sample, device, dtype):
+ # A sigma batch of 1 is shared by the input and a batch equal to the input gives each sample its own sigma:
+ # both keep working and match filtering every sample alone.
+ batch = 4
+ rows = batch if per_sample else 1
+ image = torch.rand(batch, 3, 8, 9, device=device, dtype=dtype)
+ if name == "sigma_color":
+ sigma_color = torch.linspace(0.3, 0.9, rows, device=device, dtype=dtype)
+ kwargs = {"sigma_color": sigma_color, "sigma_space": (1.2, 1.4)}
+ else:
+ sigma_space = torch.stack((torch.linspace(0.8, 1.6, rows), torch.linspace(1.0, 2.0, rows)), dim=-1)
+ kwargs = {"sigma_color": 0.5, "sigma_space": sigma_space.to(device=device, dtype=dtype)}
+
+ actual = bilateral_blur(image, 3, **kwargs)
+ assert actual.shape == image.shape
+
+ for i in range(batch):
+ row = i if per_sample else 0
+ single = {k: (v[row : row + 1] if isinstance(v, torch.Tensor) else v) for k, v in kwargs.items()}
+ self.assert_close(actual[i : i + 1], bilateral_blur(image[i : i + 1], 3, **single))
+
+ @pytest.mark.parametrize("shape", [(), (2,), (1, 1)], ids=["0d", "1d", "one_column"])
+ def test_sigma_space_shape_is_checked_before_its_batch_5430(self, shape, device, dtype):
+ # The (B, 2) shape check runs before the batch check: a 0-d sigma_space has no batch to read, and a 1-D pair
+ # on a batch-1 input would otherwise be reported as a sigma_space batch of 2.
+ from kornia.core.exceptions import ShapeError
+
+ image = torch.ones(1, 1, 8, 9, device=device, dtype=dtype)
+ sigma_space = torch.full(shape, 1.5, device=device, dtype=dtype)
+ with pytest.raises(ShapeError):
+ bilateral_blur(image, 3, 0.5, sigma_space)
+
def test_noncontiguous(self, device, dtype):
batch_size = 3
inp = torch.rand(3, 5, 5, device=device, dtype=dtype).expand(batch_size, -1, -1, -1)
@@ -158,6 +222,25 @@ class TestBilateralBlur(BaseTester):
op_optimized = torch_optimizer(op, fullgraph=True)
self.assert_close(op_optimized(data), op(data))
+ @pytest.mark.parametrize("per_sample", [False, True], ids=["shared_sigma", "per_sample_sigma"])
+ def test_dynamo_sigma_batch_check_is_dynamic_5430(self, per_sample, device, dtype, torch_optimizer):
+ """The sigma batch check does not specialize the batch: one dynamic graph serves every batch (#5430)."""
+ from torch._dynamo.testing import CompileCounter
+
+ def op(x, sigma_color, sigma_space):
+ return bilateral_blur(x, 3, sigma_color, sigma_space, "constant")
+
+ counter = CompileCounter()
+ compiled = torch_optimizer(op, backend=counter, fullgraph=True, dynamic=True)
+ # no batch equals another axis, including sigma_space's 2 columns, so duck sizing cannot tie the batch to it
+ for batch in (4, 5, 6):
+ rows = batch if per_sample else 1
+ image = torch.rand(batch, 3, 7, 9, device=device, dtype=dtype)
+ sigma_color = torch.rand(rows, device=device, dtype=dtype) + 0.5
+ sigma_space = torch.rand(rows, 2, device=device, dtype=dtype) + 0.5
+ self.assert_close(compiled(image, sigma_color, sigma_space), op(image, sigma_color, sigma_space))
+ assert counter.frame_count == 1
+
def test_opencv_grayscale(self, device, dtype):
img = [[95, 130, 108, 228], [98, 142, 187, 166], [114, 166, 190, 141], [150, 83, 174, 216]]
img = torch.tensor(img, device=device, dtype=dtype).view(1, 1, 4, 4) / 255