π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
Fix wildcard and scalar patterns in KORNIA_CHECK_SHAPE (#5442)
AhmetHakanBezir7455d9644621
diff --git a/changelog.d/5442.fixed.md b/changelog.d/5442.fixed.mdnew file mode 100644index 000000000..04e86fa1b--- /dev/null+++ b/changelog.d/5442.fixed.md@@ -0,0 +1 @@+`KORNIA_CHECK_SHAPE` now accepts every tensor shape for `["*"]`, treats an empty pattern as scalar-only, and reports the tensor dimension when a leading-wildcard check fails.diff --git a/kornia/core/check.py b/kornia/core/check.pyindex 063f96e5f..0e4274438 100644--- a/kornia/core/check.py+++ b/kornia/core/check.py@@ -136,7 +136,8 @@ def KORNIA_CHECK_SHAPE(x: torch.Tensor, shape: list[str], msg: Optional[str] = NArgs:x: the tensor to evaluate.- shape: a list with strings with the expected shape.+ shape: a list with strings with the expected shape. A leading or trailing ``"*"`` matches any number+ of dimensions; ``["*"]`` accepts any shape, and an empty list accepts only a scalar tensor.msg: optional custom message to append to error.raises: bool indicating whether an exception should be raised upon failure.@@ -163,10 +164,12 @@ def KORNIA_CHECK_SHAPE(x: torch.Tensor, shape: list[str], msg: Optional[str] = Nif not _KORNIA_CHECKS_ENABLED:return True- if "*" == shape[0]:+ dimension_offset = 0+ if len(shape) > 0 and "*" == shape[0]:shape_to_check = shape[1:]- x_shape_to_check = x.shape[-len(shape) + 1 :]- elif "*" == shape[-1]:+ dimension_offset = max(len(x.shape) - len(shape_to_check), 0)+ x_shape_to_check = x.shape[dimension_offset:]+ elif len(shape) > 0 and "*" == shape[-1]:shape_to_check = shape[:-1]x_shape_to_check = x.shape[: len(shape) - 1]else:@@ -199,7 +202,9 @@ def KORNIA_CHECK_SHAPE(x: torch.Tensor, shape: list[str], msg: Optional[str] = Ndim = int(dim_)if x_shape_to_check[i] != dim:if raises:- error_msg = f"Shape mismatch at dimension {i}: expected {dim}, got {x_shape_to_check[i]}.\n"+ error_msg = (+ f"Shape mismatch at dimension {i + dimension_offset}: expected {dim}, got {x_shape_to_check[i]}.\n"+ )error_msg += f" Expected shape: {shape}\n"x_shape_list = list(x.shape)error_msg += f" Actual shape: {x_shape_list}"diff --git a/tests/augmentation/test_conventions_intensity_ops.py b/tests/augmentation/test_conventions_intensity_ops.pyindex 69c89bf42..f027a32ea 100644--- a/tests/augmentation/test_conventions_intensity_ops.py+++ b/tests/augmentation/test_conventions_intensity_ops.py@@ -1144,8 +1144,8 @@ class TestNoiseAndWeatherConventions(BaseTester):("ColorJiggle", False, ValueError, r"Input size must have a shape of \(\*, 3, H, W\)"),("RandomHue", False, ValueError, r"Input size must have a shape of \(\*, 3, H, W\)"),("RandomSaturation", False, ValueError, r"Input size must have a shape of \(\*, 3, H, W\)"),- ("RandomJPEG", False, ShapeError, r"Shape mismatch at dimension 0: expected 3, got"),- ("RandomPlanckianJitter", False, ShapeError, r"Shape mismatch at dimension 0: expected 3, got"),+ ("RandomJPEG", False, ShapeError, r"Shape mismatch at dimension 1: expected 3, got"),+ ("RandomPlanckianJitter", False, ShapeError, r"Shape mismatch at dimension 1: expected 3, got"),("RandomRGBShift", False, ImageError, r"Not a color tensor"),("RandomSnow", False, BaseError, r"Number of color channels should be 3\."),("RandomRain", True, BaseError, r"Number of color channels should be 1 or 3\."),diff --git a/tests/core/test_check.py b/tests/core/test_check.pyindex 9bce862ec..a68fb0fcc 100644--- a/tests/core/test_check.py+++ b/tests/core/test_check.py@@ -100,6 +100,44 @@ class TestCheckShape:assert op_jit is not Noneassert op_jit(torch.rand(2, 3, 2, 3), ["2", "3", "H", "W"]) is True+ @pytest.mark.parametrize("size", [(), (7,), (0, 3), (2, 3, 4, 5)])+ def test_lone_wildcard_5187(self, device, dtype, size):+ x = torch.zeros(size, device=device, dtype=dtype)+ assert KORNIA_CHECK_SHAPE(x, ["*"]) is True+ assert KORNIA_CHECK_SHAPE(x, ["*"], raises=False) is True++ def test_empty_pattern_5187(self, device, dtype):+ assert KORNIA_CHECK_SHAPE(torch.zeros((), device=device, dtype=dtype), []) is True+ x = torch.zeros(2, 3, device=device, dtype=dtype)+ assert KORNIA_CHECK_SHAPE(x, [], raises=False) is False+ with pytest.raises(ShapeError, match="expected 0 dimensions, got 2") as exc:+ KORNIA_CHECK_SHAPE(x, [], msg="scalar required")+ assert exc.value.actual_shape == [2, 3]+ assert exc.value.expected_shape == []+ assert "scalar required" in str(exc.value)++ @pytest.mark.parametrize(+ "pattern,dimension",+ [(["*", "4", "5"], 3), (["*", "5", "6"], 2), (["2", "4", "*"], 1), (["B", "C", "4", "5"], 3)],+ )+ def test_mismatch_tensor_dimension_5187(self, device, dtype, pattern, dimension):+ x = torch.zeros(2, 3, 4, 6, device=device, dtype=dtype)+ with pytest.raises(ShapeError, match=f"at dimension {dimension}:") as exc:+ KORNIA_CHECK_SHAPE(x, pattern)+ assert exc.value.actual_shape == [2, 3, 4, 6]+ assert exc.value.expected_shape == pattern+ assert KORNIA_CHECK_SHAPE(x, pattern, raises=False) is False++ def test_jit_edge_patterns_5187(self, device, dtype):+ op = torch.jit.script(KORNIA_CHECK_SHAPE)+ scalar = torch.zeros((), device=device, dtype=dtype)+ matrix = torch.zeros(2, 3, device=device, dtype=dtype)+ assert op(scalar, []) is True+ assert op(matrix, [], raises=False) is False+ assert op(matrix, ["*"]) is True+ assert op(matrix, ["*", "3"]) is True+ assert op(matrix, ["*", "4"], raises=False) is False+class TestCheckSameShape:def test_valid(self):