π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(core): reject empty or non-tensor input in KORNIA_CHECK_SAME_DEVICES (#5401)
hoobnn3c263310332a
diff --git a/changelog.d/5401.fixed.md b/changelog.d/5401.fixed.mdnew file mode 100644index 000000000..e6b90a7bf--- /dev/null+++ b/changelog.d/5401.fixed.md@@ -0,0 +1 @@+`KORNIA_CHECK_SAME_DEVICES` now returns `False` with `raises=False` and raises `TypeCheckError` with `raises=True` for an empty list, a non-list container or a list holding a non-tensor. Previously `[]` and tuples returned `True` with `raises=False`, and a non-tensor element raised `AttributeError`, or was compared by its `device` attribute if it had one (a `Vector3`, for example).diff --git a/kornia/core/check.py b/kornia/core/check.pyindex f2c380a38..b61417dc8 100644--- a/kornia/core/check.py+++ b/kornia/core/check.py@@ -454,14 +454,15 @@ def KORNIA_CHECK_SAME_DEVICE(x: torch.Tensor, y: torch.Tensor, raises: bool = Trdef KORNIA_CHECK_SAME_DEVICES(tensors: list[torch.Tensor], msg: Optional[str] = None, raises: bool = True) -> bool:- """Check whether a list provided tensors live in the same device.+ """Check whether a non-empty list of tensors live on the same device.Args:- tensors: a list of tensors.+ tensors: a non-empty list of tensors.msg: message to show in the exception.raises: bool indicating whether an exception should be raised upon failure.Raises:+ TypeCheckError: if tensors is not a non-empty list of tensors and raises is True.DeviceError: if all the tensors are not in the same device and raises is True.Note:@@ -481,7 +482,24 @@ def KORNIA_CHECK_SAME_DEVICES(tensors: list[torch.Tensor], msg: Optional[str] =if not _KORNIA_CHECKS_ENABLED:return True- KORNIA_CHECK(isinstance(tensors, list) and len(tensors) >= 1, "Expected a list with at least one element", raises)+ if not (isinstance(tensors, list) and len(tensors) > 0 and all(isinstance(x, torch.Tensor) for x in tensors)):+ if raises:+ prefix = "Expected a non-empty list of tensors, got"+ suffix = "" if msg is None else f"\n {msg}"+ if not isinstance(tensors, list):+ raise TypeCheckError(+ f"{prefix} {type(tensors).__name__}.{suffix}", actual_type=type(tensors), expected_type=list+ )+ if len(tensors) == 0:+ raise TypeCheckError(f"{prefix} an empty list.{suffix}")+ for x in tensors:+ if not isinstance(x, torch.Tensor):+ raise TypeCheckError(+ f"{prefix} a list containing {type(x).__name__}.{suffix}",+ actual_type=type(x),+ expected_type=torch.Tensor,+ )+ return Falseif not all(tensors[0].device == x.device for x in tensors):if raises:devices = [x.device for x in tensors]diff --git a/tests/core/test_check.py b/tests/core/test_check.pyindex 1f62b90dc..df61aeef1 100644--- a/tests/core/test_check.py+++ b/tests/core/test_check.py@@ -186,20 +186,43 @@ class TestCheckSameDevice:class TestCheckSameDevices:- def test_valid(self, device):- assert KORNIA_CHECK_SAME_DEVICES([torch.rand(1, device=device), torch.rand(1, device=device)]) is True+ @pytest.mark.parametrize("count", [1, 2, 3])+ def test_valid(self, device, count):+ assert KORNIA_CHECK_SAME_DEVICES([torch.rand(1, device=device) for _ in range(count)]) is True++ @pytest.mark.parametrize(+ "tensors, got, actual_type, expected_type",+ [+ ([], "an empty list", None, None),+ ((), "tuple", tuple, list),+ ((torch.zeros(1),), "tuple", tuple, list),+ (None, "NoneType", type(None), list),+ ("tensor", "str", str, list),+ ([1], "a list containing int", int, torch.Tensor),+ ([torch.zeros(1), 1], "a list containing int", int, torch.Tensor),+ ],+ )+ def test_invalid_input(self, tensors, got, actual_type, expected_type):+ assert KORNIA_CHECK_SAME_DEVICES(tensors, raises=False) is False+ with pytest.raises(TypeCheckError, match=f"Expected a non-empty list of tensors, got {got}\\.") as exc_info:+ KORNIA_CHECK_SAME_DEVICES(tensors, raises=True)+ assert exc_info.value.actual_type is actual_type+ assert exc_info.value.expected_type is expected_type++ @pytest.mark.parametrize("tensors", [[], (torch.zeros(1),), [torch.zeros(1), 1]])+ def test_invalid_input_message(self, tensors):+ with pytest.raises(TypeCheckError, match="custom message"):+ KORNIA_CHECK_SAME_DEVICES(tensors, msg="custom message")- @pytest.mark.skipif(not torch.cuda.is_available(), reason="Skip if no GPU.")def test_invalid(self):- with pytest.raises(DeviceError):- KORNIA_CHECK_SAME_DEVICES([torch.rand(1, device="cpu"), torch.rand(1, device="cuda")])+ with pytest.raises(DeviceError) as exc_info:+ KORNIA_CHECK_SAME_DEVICES([torch.rand(1), torch.empty(1, device="meta")], msg="custom message")+ assert exc_info.value.expected_device == torch.device("cpu")+ assert exc_info.value.actual_devices == [torch.device("cpu"), torch.device("meta")]+ assert "custom message" in str(exc_info.value)- @pytest.mark.skipif(not torch.cuda.is_available(), reason="Skip if no GPU.")def test_invalid_raises_false(self):- assert (- KORNIA_CHECK_SAME_DEVICES([torch.rand(1, device="cpu"), torch.rand(1, device="cuda")], raises=False)- is False- )+ assert KORNIA_CHECK_SAME_DEVICES([torch.rand(1), torch.empty(1, device="meta")], raises=False) is Falseclass TestCheckIsColor: