π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(filters)!: reject integer input in the blur pools (#6270)
Dmytro Mishkin394cdf67797d
diff --git a/changelog.d/6270.breaking.md b/changelog.d/6270.breaking.mdnew file mode 100644index 000000000..535da4582--- /dev/null+++ b/changelog.d/6270.breaking.md@@ -0,0 +1,8 @@+`blur_pool2d`, `max_blur_pool2d`, `edge_aware_blur_pool2d`, `BlurPool2D`, `MaxBlurPool2D` and `EdgeAwareBlurPool2D`+raise a `TypeCheckError` (a `TypeError`) for an integer or bool input, naming the dtype. The blur pools are network+layers and expect a floating feature map; unlike the image filters (#5669) they do not promote integer input. Before,+the binomial kernel was cast to the input's dtype, which truncated every tap to 0. On CPU, `BlurPool2D` and+`MaxBlurPool2D` returned an all-zero integer tensor without an error, and the functions raised a `RuntimeError` dtype+mismatch. On CUDA, every entry point raised a `RuntimeError` from cuDNN or the max pool. `except RuntimeError` no+longer catches the error. The check is skipped under `disable_checks()` in Python; scripted calls always validate,+as in Kornia's core checks. `BlurPool2D` and `MaxBlurPool2D` remain scriptable. Floating input is unchanged.diff --git a/docs/source/get-started/conventions.rst b/docs/source/get-started/conventions.rstindex efed94e88..c5f4d4d0f 100644--- a/docs/source/get-started/conventions.rst+++ b/docs/source/get-started/conventions.rst@@ -718,7 +718,8 @@ float32 on its own scale, neither rescaled to :math:`[0, 1]` nor rounded and cla``cv2.filter2D(img, -1, k)``, ``cv2.GaussianBlur`` and ``cv2.blur`` return a uint8 image rounded and saturated touint8; a floating image keeps its dtype. :func:`~kornia.filters.guided_blur` returns the promoted dtype of its``guidance`` and ``input``, an integer one counting as float32. The blur pools are network layers and expect a-floating input; an integer image is outside their contract.+floating input: they raise a :class:`~kornia.core.exceptions.TypeCheckError` (a ``TypeError``) for a non-floating+input instead of promoting it.- :func:`~kornia.filters.filter2d`, :func:`~kornia.filters.filter3d` and :func:`~kornia.filters.fft_conv`**correlate** by default, as ``cv2.filter2D`` and ``scipy.ndimage.correlate`` do; ``behaviour='conv'`` flips thediff --git a/kornia/filters/blur_pool.py b/kornia/filters/blur_pool.pyindex 70f1121eb..f484335cb 100644--- a/kornia/filters/blur_pool.py+++ b/kornia/filters/blur_pool.py@@ -24,7 +24,8 @@ import torchimport torch.nn.functional as Ffrom torch import nn-from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SHAPE+from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SHAPE, are_checks_enabled+from kornia.core.exceptions import TypeCheckErrorfrom .kernels import _check_kernel_size, get_pascal_kernel_2d@@ -94,6 +95,7 @@ class BlurPool2D(nn.Module):the sizes given in the Shape section of the class. They depend onlyon the input size and ``self.stride``."""+ _check_floating_feature_map(input, "BlurPool2D")kernel = self.kernel.to(device=input.device, dtype=input.dtype)# ONNX requires constant convolution groups and kernel shape, even with dynamic batch or spatial axes.channels = int(input.shape[1]) if torch.jit.is_tracing() else input.shape[1]@@ -178,6 +180,7 @@ class MaxBlurPool2D(nn.Module):class. They depend only on the input size, ``self.max_pool_size``and ``self.stride``."""+ _check_floating_feature_map(input, "MaxBlurPool2D")kernel = self.kernel.to(device=input.device, dtype=input.dtype)channels = int(input.shape[1]) if torch.jit.is_tracing() else input.shape[1]return _max_blur_pool_by_kernel2d(input, kernel.repeat((channels, 1, 1, 1)), self.stride, self.max_pool_size)@@ -231,6 +234,7 @@ class EdgeAwareBlurPool2D(nn.Module):Edge-aware blurred tensor with the shape of ``input``,:math:`(B, C, H, W)`."""+ _check_floating_feature_map(input, "EdgeAwareBlurPool2D")if epsilon is None:epsilon = 1e-6return edge_aware_blur_pool2d(@@ -255,6 +259,9 @@ def blur_pool2d(input: torch.Tensor, kernel_size: tuple[int, int] | int, stride:``kernel_size`` is thereby anchored at ``(k - 1) // 2``, as in :func:`~kornia.filters.filter2d`.:ref:`Filtering <filtering-conventions>` compares the padding with antialiased-cnns, and the sampling with:func:`~kornia.geometry.transform.pyrdown`.+ - The blur pools are network layers: an integer or bool input raises a+ :class:`~kornia.core.exceptions.TypeCheckError` instead of being promoted to float32 as the image filters+ promote it. A floating input keeps its dtype.Args:input: torch.Tensor to apply operation to.@@ -283,6 +290,7 @@ def blur_pool2d(input: torch.Tensor, kernel_size: tuple[int, int] | int, stride:[0.0000, 0.0625, 0.3125]]]])"""+ _check_floating_feature_map(input, "blur_pool2d")channels = int(input.shape[1]) if torch.jit.is_tracing() else input.shape[1]kernel = get_pascal_kernel_2d(kernel_size, norm=True, device=input.device, dtype=input.dtype).repeat((channels, 1, 1, 1)@@ -306,7 +314,7 @@ def max_blur_pool2d(Convention:- The result equals ``blur_pool2d(F.max_pool2d(input, max_pool_size, stride=1), kernel_size, stride)``: themax pool runs at stride 1 without padding and ``stride`` belongs to the blur. See the Convention block on- :func:`~kornia.filters.blur_pool2d` for the kernel and the border.+ :func:`~kornia.filters.blur_pool2d` for the kernel, the border and integer input, which raises.Args:input: torch.Tensor to apply operation to.@@ -329,6 +337,7 @@ def max_blur_pool2d("""_warn_ceil_mode_deprecated(ceil_mode)KORNIA_CHECK_SHAPE(input, ["B", "C", "H", "W"])+ _check_floating_feature_map(input, "max_blur_pool2d")channels = int(input.shape[1]) if torch.jit.is_tracing() else input.shape[1]kernel = get_pascal_kernel_2d(kernel_size, norm=True, device=input.device, dtype=input.dtype).repeat(@@ -337,6 +346,31 @@ def max_blur_pool2d(return _max_blur_pool_by_kernel2d(input, kernel, stride, max_pool_size)+def _check_floating_feature_map(input: torch.Tensor, op: str) -> None:+ """Reject non-floating inputs: the blur pools are network layers and expect a floating feature map.++ The binomial kernel is cast to the input's dtype, so an integer input truncated every tap to 0 and came back as+ zeros on CPU, and raised from cuDNN or the max pool on CUDA. Unlike the image filters (#5669), the blur pools do+ not promote integer input. The check reads only the dtype, so it stays ``torch.compile(fullgraph=True)``-safe, and+ ``disable_checks()`` skips it in Python. As in the core checks, scripted calls always validate and use a+ plain error message because TorchScript cannot compile the checks flag or exception metadata.+ """+ if input.is_floating_point():+ return+ if not torch.jit.is_scripting(): # noqa: SIM102 - TorchScript only skips a bare is_scripting() guard+ if not are_checks_enabled():+ return+ if torch.jit.is_scripting():+ raise TypeCheckError(+ op + " is a network layer and expects a floating-point feature map. Convert it first, e.g. input.float()."+ )+ raise TypeCheckError(+ f"{op} is a network layer and expects a floating-point feature map, got {input.dtype}. "+ "Convert it first, for example input.float().",+ actual_type=input.dtype,+ )++def _warn_ceil_mode_deprecated(ceil_mode: bool | None) -> None:"""Warn that ``ceil_mode`` was passed: at the stride-1 max pool it cannot change the result."""if ceil_mode is not None:@@ -408,7 +442,8 @@ def edge_aware_blur_pool2d(r"""Blur the input torch.Tensor while maintaining its edges.Convention:- - Nothing is downsampled: the output has the input's shape.+ - Nothing is downsampled: the output has the input's shape. An integer or bool input raises, as in+ :func:`~kornia.filters.blur_pool2d`.- A pixel is on an edge when, along ``x`` or ``y``, the channel mean of ``log2(input + epsilon)`` differsby more than ``log2(edge_threshold)`` between the pixels two before and two after it, so scaling the imagedoes not move the edges while the intensities stay well above ``epsilon``. Pixels on the edge map,@@ -434,6 +469,7 @@ def edge_aware_blur_pool2d("""KORNIA_CHECK_SHAPE(input, ["B", "C", "H", "W"])+ _check_floating_feature_map(input, "edge_aware_blur_pool2d")edge_dilation_kernel_size = operator.index(edge_dilation_kernel_size)_check_kernel_size(edge_dilation_kernel_size)KORNIA_CHECK(edge_threshold > 1.0, f"edge_threshold must be greater than 1. Got {edge_threshold}")diff --git a/tests/filters/test_blur_pool.py b/tests/filters/test_blur_pool.pyindex 22e0f0620..7dc01788f 100644--- a/tests/filters/test_blur_pool.py+++ b/tests/filters/test_blur_pool.py@@ -25,7 +25,7 @@ import pytestimport torchimport torch.nn.functional as F-from kornia.core.exceptions import BaseError+from kornia.core.exceptions import BaseError, TypeCheckErrorfrom kornia.filters import (BlurPool2D,EdgeAwareBlurPool2D,@@ -165,17 +165,10 @@ class TestBlurPoolKernelState(BaseTester):@staticmethoddef _integer_call(module, image):- # Integer output semantics remain a follow-up to #5669; even a failed call must preserve state.- if image.device.type == "mps":- with pytest.raises(RuntimeError, match="Convolution is supported only for Floating types"):- module(image)- else:- try:- module(image)- except RuntimeError as error:- # Other backends may lack Byte convolution/pooling kernels.- if "not implemented" not in str(error) or "Byte" not in str(error):- raise+ # The blur pools are network layers: an integer input raises on every device (they do not promote it as the+ # image filters do since #5669), and the failed call must leave the stored kernel untouched.+ with pytest.raises(TypeCheckError, match="network layer and expects a floating-point feature map"):+ module(image)def test_dtype_call_order_5699(self, module_cls, device, dtype):module = module_cls(3).to(device=device)@@ -708,3 +701,49 @@ class TestConventionsBlurPool(BaseTester):ones = torch.ones(1, 1, 15, 18, device=device, dtype=dtype)for kernel_size in (3, 5, 7, 9, 15):self.assert_close(edge_aware_blur_pool2d(ones, kernel_size), ones)++[email protected]("module_cls", [BlurPool2D, MaxBlurPool2D])+class TestBlurPoolScript(BaseTester):+ def test_script_roundtrip(self, module_cls, device, dtype):+ module = module_cls(3).to(device=device, dtype=dtype)+ image = torch.rand(1, 2, 8, 10, device=device, dtype=dtype)+ scripted = torch.jit.script(module)+ buffer = io.BytesIO()+ torch.jit.save(scripted, buffer)+ buffer.seek(0)+ restored = torch.jit.load(buffer, map_location=device)+ self.assert_close(restored(image), module(image))++ @pytest.mark.parametrize("input_dtype", [torch.uint8, torch.int32, torch.bool])+ def test_script_rejects_nonfloating_input(self, module_cls, device, input_dtype):+ scripted = torch.jit.script(module_cls(3).to(device=device))+ image = torch.ones(1, 1, 8, 8, device=device, dtype=input_dtype)+ with pytest.raises(torch.jit.Error, match=r"TypeCheckError: .*expects a floating-point feature map"):+ scripted(image)+++class TestBlurPoolIntegerInput:+ # The blur pools are network layers and expect a floating feature map. An integer kernel cast used to truncate+ # every binomial tap to 0: BlurPool2D and MaxBlurPool2D returned zeros on CPU, the functions raised a dtype+ # mismatch, and CUDA raised from cuDNN or the Byte max pool. Every entry point now raises the same TypeCheckError.+ @pytest.mark.parametrize(+ "call",+ [+ BlurPool2D(3),+ MaxBlurPool2D(3),+ EdgeAwareBlurPool2D(3),+ lambda x: blur_pool2d(x, 3),+ lambda x: max_blur_pool2d(x, 3),+ lambda x: edge_aware_blur_pool2d(x, 3),+ ],+ ids=["BlurPool2D", "MaxBlurPool2D", "EdgeAwareBlurPool2D", "blur_pool2d", "max_blur_pool2d", "edge_aware"],+ )+ @pytest.mark.parametrize("int_dtype", [torch.uint8, torch.int32, torch.bool])+ def test_integer_input_raises(self, call, int_dtype, device):+ image = (torch.arange(64, device=device).reshape(1, 1, 8, 8) % 7).to(int_dtype)+ with pytest.raises(TypeCheckError, match="network layer and expects a floating-point feature map") as error:+ call(image)+ assert str(int_dtype) in str(error.value)+ assert error.value.actual_type == int_dtype+ assert call(image.float()).dtype == torch.float32