Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(contrib): validate tensor patch parameters (#5969)

Karnajeet Gosaviba63196769dd
diff --git a/changelog.d/5969.breaking.md b/changelog.d/5969.breaking.md
new file mode 100644
index 000000000..ef6391a3b
--- /dev/null
+++ b/changelog.d/5969.breaking.md
@@ -0,0 +1 @@
+`extract_tensor_patches`, `combine_tensor_patches`, `compute_padding`, `ExtractTensorPatches` and `CombineTensorPatches` reject a `window_size` or `stride` component below 1 up front with `ValueCheckError` (a `BaseError` and a `ValueError`) naming the argument, also under `python -O`. A zero or negative `stride` used to fail later with `ZeroDivisionError` or a `RuntimeError` from `unfold`/`fold`, and the two module classes accepted it at construction; `combine_tensor_patches` failed the same way for a non-positive `window_size`, or raised `AssertionError` when the stride exceeded it; `compute_padding` raised `ZeroDivisionError` for a zero stride and returned `(0, 0, 0, 0)` for a negative stride or a non-positive `window_size`. `extract_tensor_patches` still raises a `ValueError` for a non-positive `window_size`.
diff --git a/kornia/contrib/extract_patches.py b/kornia/contrib/extract_patches.py
index 69d7a6801..66f30a396 100644
--- a/kornia/contrib/extract_patches.py
+++ b/kornia/contrib/extract_patches.py
@@ -26,12 +26,24 @@ from torch import nn
from torch.nn.modules.utils import _pair
from kornia.core._compat import torch_version_lt
+from kornia.core.exceptions import ValueCheckError
FullPadType = Tuple[int, int, int, int]
TuplePadType = Union[Tuple[int, int], FullPadType]
PadType = Union[int, TuplePadType]
+def _check_patch_params(window_size: Union[int, Tuple[int, int]], stride: Union[int, Tuple[int, int]]) -> None:
+ window_size = cast(Tuple[int, int], _pair(window_size))
+ stride = cast(Tuple[int, int], _pair(stride))
+ # Raised directly rather than through KORNIA_CHECK, which python -O and disable_checks() switch off: a zero
+ # window_size would then return empty patches instead of failing.
+ if any(size <= 0 for size in window_size):
+ raise ValueCheckError(f"window_size must contain positive values. Got {window_size}.")
+ if any(step <= 0 for step in stride):
+ raise ValueCheckError(f"stride must contain positive values. Got {stride}.")
+
+
def create_padding_tuple(padding: PadType, unpadding: bool = False) -> FullPadType:
"""Create argument for padding op."""
padding = cast(TuplePadType, _pair(padding))
@@ -87,6 +99,7 @@ def compute_padding(
if stride is None:
stride = window_size
stride = cast(Tuple[int, int], _pair(stride))
+ _check_patch_params(window_size, stride)
remainder_vertical = (original_size[0] - window_size[0]) % stride[0]
remainder_horizontal = (original_size[1] - window_size[1]) % stride[1]
@@ -189,6 +202,7 @@ class ExtractTensorPatches(nn.Module):
allow_auto_padding: bool = False,
) -> None:
super().__init__()
+ _check_patch_params(window_size, stride)
self.window_size: Union[int, Tuple[int, int]] = window_size
self.stride: Union[int, Tuple[int, int]] = stride
self.padding: PadType = padding
@@ -296,6 +310,7 @@ class CombineTensorPatches(nn.Module):
allow_auto_unpadding: bool = False,
) -> None:
super().__init__()
+ _check_patch_params(window_size, stride if stride is not None else window_size)
self.original_size: Tuple[int, int] = original_size
self.window_size: Union[int, Tuple[int, int]] = window_size
self.stride: Union[int, Tuple[int, int]] = stride if stride is not None else window_size
@@ -386,6 +401,7 @@ def combine_tensor_patches(
original_size = cast(Tuple[int, int], _pair(original_size))
window_size = cast(Tuple[int, int], _pair(window_size))
stride = cast(Tuple[int, int], _pair(stride))
+ _check_patch_params(window_size, stride)
if (stride[0] > window_size[0]) | (stride[1] > window_size[1]):
raise AssertionError(
@@ -577,10 +593,9 @@ def extract_tensor_patches(
# torch's unfold drops the final patches that don't fit
window_size = cast(Tuple[int, int], _pair(window_size))
stride = cast(Tuple[int, int], _pair(stride))
+ _check_patch_params(window_size, stride)
if input.shape[1] == 0:
raise ValueError("extract_tensor_patches requires a non-empty channel dimension.")
- if any(size <= 0 for size in window_size):
- raise ValueError(f"window_size must contain positive values. Got {window_size}.")
original_size = (input.shape[-2], input.shape[-1])
# if padding is specified, we leave it up to the user to ensure it fits
diff --git a/tests/contrib/test_combine_tensor_patch.py b/tests/contrib/test_combine_tensor_patch.py
index a8ef7ea9c..065feefe8 100644
--- a/tests/contrib/test_combine_tensor_patch.py
+++ b/tests/contrib/test_combine_tensor_patch.py
@@ -22,11 +22,28 @@ import torch
import kornia
from kornia.core._compat import torch_version_lt
+from kornia.core.exceptions import ValueCheckError
from testing.base import BaseTester
class TestCombineTensorPatches(BaseTester):
+ @pytest.mark.parametrize("argument", ["window_size", "stride"])
+ @pytest.mark.parametrize("value", [0, (1, 0), -1])
+ def test_function_rejects_non_positive_patch_params(self, argument, value):
+ params = {"window_size": 2, "stride": 1}
+ params[argument] = value
+ with pytest.raises(ValueCheckError, match=argument):
+ kornia.contrib.combine_tensor_patches(torch.ones(1, 1, 1, 2, 2), original_size=(2, 2), **params)
+
+ @pytest.mark.parametrize("argument", ["window_size", "stride"])
+ @pytest.mark.parametrize("value", [0, (1, 0), -1])
+ def test_module_rejects_non_positive_patch_params(self, argument, value):
+ params = {"window_size": 2, "stride": 1}
+ params[argument] = value
+ with pytest.raises(ValueCheckError, match=argument):
+ kornia.contrib.CombineTensorPatches(original_size=(2, 2), **params)
+
def test_smoke(self, device, dtype):
img = torch.arange(16, device=device, dtype=dtype).view(1, 1, 4, 4)
m = kornia.contrib.CombineTensorPatches((4, 4), (2, 2), (2, 2))
diff --git a/tests/contrib/test_extract_tensor_patch.py b/tests/contrib/test_extract_tensor_patch.py
index 0d3aa3705..efa11cfb7 100644
--- a/tests/contrib/test_extract_tensor_patch.py
+++ b/tests/contrib/test_extract_tensor_patch.py
@@ -21,11 +21,43 @@ import pytest
import torch
import kornia
+from kornia.core.check import are_checks_enabled, disable_checks, enable_checks
+from kornia.core.exceptions import ValueCheckError
from testing.base import BaseTester
class TestExtractTensorPatches(BaseTester):
+ @pytest.mark.parametrize("argument", ["window_size", "stride"])
+ @pytest.mark.parametrize("value", [0, (1, 0), -1])
+ def test_function_rejects_non_positive_patch_params(self, argument, value):
+ params = {"window_size": 2, "stride": 1}
+ params[argument] = value
+ with pytest.raises(ValueCheckError, match=argument):
+ kornia.contrib.extract_tensor_patches(torch.ones(1, 1, 4, 4), **params)
+
+ @pytest.mark.parametrize("argument", ["window_size", "stride"])
+ def test_rejects_non_positive_patch_params_with_checks_disabled(self, argument):
+ # A zero window_size returned empty patches without this guard, so it must not follow disable_checks().
+ params = {"window_size": 2, "stride": 1}
+ params[argument] = 0
+ was_enabled = are_checks_enabled()
+ disable_checks()
+ try:
+ with pytest.raises(ValueCheckError, match=argument):
+ kornia.contrib.extract_tensor_patches(torch.ones(1, 1, 4, 4), **params)
+ finally:
+ if was_enabled:
+ enable_checks()
+
+ @pytest.mark.parametrize("argument", ["window_size", "stride"])
+ @pytest.mark.parametrize("value", [0, (1, 0), -1])
+ def test_module_rejects_non_positive_patch_params(self, argument, value):
+ params = {"window_size": 2, "stride": 1}
+ params[argument] = value
+ with pytest.raises(ValueCheckError, match=argument):
+ kornia.contrib.ExtractTensorPatches(**params)
+
def test_smoke(self, device):
img = torch.arange(16.0, device=device).view(1, 1, 4, 4)
m = kornia.contrib.ExtractTensorPatches(3)
@@ -219,7 +251,7 @@ class TestExtractTensorPatches(BaseTester):
kornia.contrib.extract_tensor_patches(
torch.empty(batch_size, 3, 8, 12, device=device, dtype=dtype), (0, 4), (4, 4)
)
- with pytest.raises(RuntimeError, match=r"step.*> 0"):
+ with pytest.raises(ValueCheckError, match=r"stride.*positive"):
kornia.contrib.extract_tensor_patches(
torch.empty(batch_size, 3, 8, 12, device=device, dtype=dtype), 4, 0, padding=(1, 1, 1, 1)
)
@@ -240,3 +272,12 @@ class TestExtractTensorPatches(BaseTester):
out = kornia.contrib.extract_tensor_patches(img, 2, 2, padding=padding, allow_auto_padding=True)
assert out.shape == (1, 12, 1, 2, 2)
self.assert_close(out, expected)
+
+
[email protected]("argument", ["window_size", "stride"])
[email protected]("value", [0, (1, 0), -1])
+def test_compute_padding_rejects_non_positive_patch_params(argument, value):
+ params = {"window_size": 2, "stride": 1}
+ params[argument] = value
+ with pytest.raises(ValueCheckError, match=argument):
+ kornia.contrib.compute_padding((4, 4), **params)