Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(core): report the rejected value in the check helper failure paths (#5445)

Animesh Kumarc30d444adb87
diff --git a/changelog.d/5445.fixed.md b/changelog.d/5445.fixed.md
new file mode 100644
index 000000000..3bbc3e6e5
--- /dev/null
+++ b/changelog.d/5445.fixed.md
@@ -0,0 +1 @@
+The `kornia.core.check` failure paths now report the rejected value: `KORNIA_CHECK_TYPE` handles a `int | str` union instead of crashing while building its message, `KORNIA_CHECK_IS_LIST_OF_TENSOR` names the first non-tensor element, the colour and gray checks print the failing shape and raise their `ImageError` under TorchScript, and `KORNIA_CHECK_DM_DESC` returns `False` (or raises `ShapeError`) for a distance matrix or descriptor of the wrong rank instead of an `IndexError`.
diff --git a/kornia/core/check.py b/kornia/core/check.py
index b61417dc8..063f96e5f 100644
--- a/kornia/core/check.py
+++ b/kornia/core/check.py
@@ -268,7 +268,7 @@ _T = TypeVar("_T", bound=type)
def KORNIA_CHECK_TYPE(x: Any, typ: _T | tuple[_T, ...], msg: Optional[str] = None, raises: bool = True) -> bool:
- """Check the type of an aribratry variable.
+ """Check the type of an arbitrary variable.
Args:
x: any input variable.
@@ -303,7 +303,12 @@ def KORNIA_CHECK_TYPE(x: Any, typ: _T | tuple[_T, ...], msg: Optional[str] = Non
error_msg += f"\n {msg}"
raise TypeCheckError(error_msg)
# In Python mode, we can safely use type introspection
- expected_type_str = typ.__name__ if not isinstance(typ, tuple) else " | ".join(t.__name__ for t in typ)
+ # A PEP 604 union (``int | str``) has no ``__name__``; its repr is already readable.
+ expected_type_str = (
+ " | ".join(getattr(t, "__name__", repr(t)) for t in typ)
+ if isinstance(typ, tuple)
+ else getattr(typ, "__name__", repr(typ))
+ )
type_name = str(type(x))
error_msg = f"Type mismatch: expected {expected_type_str}, got {type_name}."
if msg is not None:
@@ -401,7 +406,11 @@ def KORNIA_CHECK_IS_LIST_OF_TENSOR(x: Optional[Sequence[Any]], raises: bool = Tr
are_tensors = isinstance(x, list) and all(isinstance(d, torch.Tensor) for d in x)
if not are_tensors:
if raises:
- error_msg = f"Type mismatch: expected list[Tensor], got {type(x).__name__}."
+ got = type(x).__name__
+ if isinstance(x, list):
+ index = next(i for i, d in enumerate(x) if not isinstance(d, torch.Tensor))
+ got += f"; element {index} is {type(x[index]).__name__}"
+ error_msg = f"Type mismatch: expected list[Tensor], got {got}."
raise TypeCheckError(
error_msg,
actual_type=type(x),
@@ -590,7 +599,7 @@ def KORNIA_CHECK_IS_COLOR(x: torch.Tensor, msg: Optional[str] = None, raises: bo
if len(x.shape) < 3 or x.shape[-3] != 3:
if raises:
- error_msg = f"Not a color tensor. Got: {type(x)}."
+ error_msg = f"Not a color tensor. Got shape {list(x.shape)}."
if msg is not None:
error_msg += f"\n{msg}"
raise ImageError(error_msg)
@@ -627,7 +636,7 @@ def KORNIA_CHECK_IS_GRAY(x: torch.Tensor, msg: Optional[str] = None, raises: boo
if len(x.shape) < 2 or (len(x.shape) >= 3 and x.shape[-3] != 1):
if raises:
- error_msg = f"Not a gray tensor. Got: {type(x)}."
+ error_msg = f"Not a gray tensor. Got shape {list(x.shape)}."
if msg is not None:
error_msg += f"\n{msg}"
raise ImageError(error_msg)
@@ -664,7 +673,7 @@ def KORNIA_CHECK_IS_COLOR_OR_GRAY(x: torch.Tensor, msg: Optional[str] = None, ra
if len(x.shape) < 3 or x.shape[-3] not in [1, 3]:
if raises:
- error_msg = f"Not a color or gray tensor. Got: {type(x)}."
+ error_msg = f"Not a color or gray tensor. Got shape {list(x.shape)}."
if msg is not None:
error_msg += f"\n{msg}"
raise ImageError(error_msg)
@@ -767,6 +776,15 @@ def KORNIA_CHECK_DM_DESC(desc1: torch.Tensor, desc2: torch.Tensor, dm: torch.Ten
if not _KORNIA_CHECKS_ENABLED:
return True
+ if dm.dim() < 2 or desc1.dim() < 1 or desc2.dim() < 1:
+ if raises:
+ raise ShapeError(
+ "Distance matrix shape mismatch.\n"
+ " Expected a distance matrix with at least 2 dimensions and descriptors with at least 1.\n"
+ f" dm shape: {list(dm.shape)}, desc1 shape: {list(desc1.shape)}, desc2 shape: {list(desc2.shape)}",
+ actual_shape=list(dm.shape),
+ )
+ return False
if not ((dm.size(0) == desc1.size(0)) and (dm.size(1) == desc2.size(0))):
if raises:
expected_shape = (desc1.size(0), desc2.size(0))
diff --git a/tests/core/test_check.py b/tests/core/test_check.py
index df61aeef1..9bce862ec 100644
--- a/tests/core/test_check.py
+++ b/tests/core/test_check.py
@@ -142,6 +142,12 @@ class TestCheckType:
def test_invalid_raises_false(self):
assert KORNIA_CHECK_TYPE("world", int, raises=False) is False
+ @pytest.mark.parametrize("typ", [int | str, (int | str, bytes)])
+ def test_invalid_union(self, typ):
+ assert KORNIA_CHECK_TYPE(1.0, typ, raises=False) is False
+ with pytest.raises(TypeCheckError, match=r"expected int \| str"):
+ KORNIA_CHECK_TYPE(1.0, typ)
+
class TestCheckIsTensor:
def test_valid(self):
@@ -168,6 +174,18 @@ class TestCheckIsListOfTensor:
def test_invalid_raises_false(self):
assert KORNIA_CHECK_IS_LIST_OF_TENSOR([torch.rand(1), [2, 3], torch.rand(1)], raises=False) is False
+ @pytest.mark.parametrize(
+ "x, detail",
+ [
+ ([torch.zeros(1), 1], "got list; element 1 is int"),
+ ([torch.zeros(1), torch.zeros(1), [2, 3]], "got list; element 2 is list"),
+ ((torch.zeros(1),), "got tuple"),
+ ],
+ )
+ def test_invalid_message_names_the_offending_value(self, x, detail):
+ with pytest.raises(TypeCheckError, match=f"expected list\\[Tensor\\], {detail}\\."):
+ KORNIA_CHECK_IS_LIST_OF_TENSOR(x)
+
class TestCheckSameDevice:
def test_valid(self, device):
@@ -244,6 +262,15 @@ class TestCheckIsColor:
def test_invalid_raises_false(self):
assert KORNIA_CHECK_IS_COLOR(torch.rand(1, 4, 4), raises=False) is False
+ def test_invalid_message_reports_the_shape(self):
+ with pytest.raises(ImageError, match=r"Not a color tensor\. Got shape \[2, 4, 5\]\."):
+ KORNIA_CHECK_IS_COLOR(torch.zeros(2, 4, 5))
+
+ def test_jit_raises_image_error(self):
+ op_jit = torch.jit.script(KORNIA_CHECK_IS_COLOR)
+ with pytest.raises(torch.jit.Error, match=r"ImageError: Not a color tensor\. Got shape \[2, 4, 5\]\."):
+ op_jit(torch.zeros(2, 4, 5))
+
class TestCheckIsGray:
def test_valid(self):
@@ -264,6 +291,15 @@ class TestCheckIsGray:
def test_invalid_raises_false(self):
assert KORNIA_CHECK_IS_GRAY(torch.rand(1, 3, 4, 4, 4), raises=False) is False
+ def test_invalid_message_reports_the_shape(self):
+ with pytest.raises(ImageError, match=r"Not a gray tensor\. Got shape \[2, 4, 5\]\."):
+ KORNIA_CHECK_IS_GRAY(torch.zeros(2, 4, 5))
+
+ def test_jit_raises_image_error(self):
+ op_jit = torch.jit.script(KORNIA_CHECK_IS_GRAY)
+ with pytest.raises(torch.jit.Error, match=r"ImageError: Not a gray tensor\. Got shape \[2, 4, 5\]\."):
+ op_jit(torch.zeros(2, 4, 5))
+
class TestCheckIsColorOrGray:
def test_valid(self):
@@ -283,6 +319,15 @@ class TestCheckIsColorOrGray:
def test_invalid_raises_false(self):
assert KORNIA_CHECK_IS_COLOR_OR_GRAY(torch.rand(1, 4, 4, 4), raises=False) is False
+ def test_invalid_message_reports_the_shape(self):
+ with pytest.raises(ImageError, match=r"Not a color or gray tensor\. Got shape \[2, 4, 5\]\."):
+ KORNIA_CHECK_IS_COLOR_OR_GRAY(torch.zeros(2, 4, 5))
+
+ def test_jit_raises_image_error(self):
+ op_jit = torch.jit.script(KORNIA_CHECK_IS_COLOR_OR_GRAY)
+ with pytest.raises(torch.jit.Error, match=r"ImageError: Not a color or gray tensor\. Got shape \[2, 4, 5\]\."):
+ op_jit(torch.zeros(2, 4, 5))
+
class TestCheckDmDesc:
def test_valid(self):
@@ -301,6 +346,19 @@ class TestCheckDmDesc:
def test_invalid_raises_false(self):
assert KORNIA_CHECK_DM_DESC(torch.rand(4), torch.rand(8), torch.rand(4, 7), raises=False) is False
+ @pytest.mark.parametrize(
+ "desc1, desc2, dm",
+ [
+ (torch.zeros(4, 128), torch.zeros(8, 128), torch.zeros(4)),
+ (torch.zeros(()), torch.zeros(8, 128), torch.zeros(4, 8)),
+ (torch.zeros(4, 128), torch.zeros(()), torch.zeros(4, 8)),
+ ],
+ )
+ def test_invalid_rank(self, desc1, desc2, dm):
+ assert KORNIA_CHECK_DM_DESC(desc1, desc2, dm, raises=False) is False
+ with pytest.raises(ShapeError):
+ KORNIA_CHECK_DM_DESC(desc1, desc2, dm)
+
class TestCheckLaf:
def test_valid(self):