Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(core)!: kornia check errors also derive from ValueError / TypeError; a dtype-only mismatch raises TypeCheckError (#5233)

Dmytro Mishkin2e932bab9644
diff --git a/changelog.d/5233.breaking.md b/changelog.d/5233.breaking.md
new file mode 100644
index 000000000..611f7d726
--- /dev/null
+++ b/changelog.d/5233.breaking.md
@@ -0,0 +1,17 @@
+kornia's validation errors now also derive from the matching built-in exception: `ShapeError`,
+`ValueCheckError`, `DeviceError` and `ImageError` are `ValueError`s, and `TypeCheckError` is a
+`TypeError`. Previously all five derived only from `BaseError` (an `Exception`), so an
+`except ValueError:` or `except TypeError:` around a kornia call caught the functions that raise the
+built-ins themselves but let a failed `KORNIA_CHECK_*` escape, for example `gaussian_blur2d` on a
+2-D tensor. Such clauses now catch these errors as well; `except BaseError` and the specific classes
+keep working. A failed plain `KORNIA_CHECK` still raises the bare `BaseError`, which is neither
+built-in. This does not restore v0.8.2, where the shape, device and color/gray image checks raised
+`TypeError`: they are `ValueError`s now, so an `except TypeError` written for v0.8.2 still misses
+them. Separately, a call whose tensors share a device but differ in dtype, such as
+`find_homography_dlt` with a `float32` and a `float64` point set, `get_motion_kernel2d`,
+`geometry.transform.Affine` or an augmentation's parameter generator given mixed dtypes, now raises
+`TypeCheckError` ("expected torch.float32, got torch.float64") instead of a `DeviceError` that
+listed the same device twice; `except DeviceError` no longer catches it. When the tensors span more
+than one device, the call raises `DeviceError` as before, whether or not their dtypes also differ
+and wherever the mismatches sit in the argument list; its message now names only the two devices
+("Passed tensors are not on the same device: expected cpu, got cuda:0.").
diff --git a/docs/source/core.rst b/docs/source/core.rst
index 4b73a2ff4..3febf5baa 100644
--- a/docs/source/core.rst
+++ b/docs/source/core.rst
@@ -41,10 +41,17 @@ Exceptions
The errors raised by kornia's ``KORNIA_CHECK*`` validation helpers in
``kornia.core.check`` (and by a few functions directly), such as a tensor with
-the wrong shape. All of them derive from :exc:`BaseError`, which derives from
-:exc:`Exception`, so ``except BaseError`` catches any of them. It does not catch
-every input error: many functions validate their inputs themselves and raise the
-built-in :exc:`ValueError` or :exc:`TypeError` instead.
+the wrong shape. All of them derive from :exc:`BaseError`, so ``except BaseError``
+catches any of them. Each subclass also derives from the built-in exception that
+matches its failure: :exc:`TypeCheckError` is also a :exc:`TypeError`, and
+:exc:`ShapeError`, :exc:`ValueCheckError`, :exc:`DeviceError` and
+:exc:`ImageError` are each also a :exc:`ValueError`. Many functions validate
+their inputs themselves and raise the built-in :exc:`ValueError` or
+:exc:`TypeError`, so ``except ValueError`` or ``except TypeError`` catches those
+and the matching kornia errors alike; ``except BaseError`` does not catch those
+built-ins. :exc:`BaseError` itself derives only from :exc:`Exception`: a failed
+``KORNIA_CHECK(condition)`` raises it, and neither of those two clauses catches
+it.
.. autoexception:: BaseError
:show-inheritance:
diff --git a/kornia/core/exceptions.py b/kornia/core/exceptions.py
index 486fe3f77..97bc87b49 100644
--- a/kornia/core/exceptions.py
+++ b/kornia/core/exceptions.py
@@ -21,6 +21,8 @@ from __future__ import annotations
from typing import Any, Optional
+import torch
+
__all__ = [
"BaseError",
"DeviceError",
@@ -32,11 +34,16 @@ __all__ = [
class BaseError(Exception):
- """Base class of the exceptions raised by kornia's ``KORNIA_CHECK*`` validation helpers and a few functions."""
+ """Base class of the exceptions raised by kornia's ``KORNIA_CHECK*`` validation helpers and a few functions.
+
+ A failed ``KORNIA_CHECK`` raises it directly; it is neither a :exc:`ValueError` nor a :exc:`TypeError`. Each
+ subclass also derives from the one of those two built-ins that matches its failure, so the matching ``except``
+ clause catches the subclass as well.
+ """
-class ShapeError(BaseError):
- """Raised when tensor shape validation fails.
+class ShapeError(BaseError, ValueError):
+ """Raised when tensor shape validation fails. Also a :exc:`ValueError`.
Attributes:
actual_shape: The actual shape of the tensor that failed validation.
@@ -55,28 +62,28 @@ class ShapeError(BaseError):
self.expected_shape = expected_shape
-class TypeCheckError(BaseError):
- """Raised when type validation fails.
+class TypeCheckError(BaseError, TypeError):
+ """Raised when type validation fails. Also a :exc:`TypeError`.
Attributes:
- actual_type: The actual type that failed validation.
- expected_type: The expected type.
+ actual_type: The actual type (or tensor dtype) that failed validation.
+ expected_type: The expected type (or tensor dtype).
"""
def __init__(
self,
message: str,
*,
- actual_type: Optional[type] = None,
- expected_type: Optional[type | tuple[type, ...]] = None,
+ actual_type: Optional[type | torch.dtype] = None,
+ expected_type: Optional[type | tuple[type, ...] | torch.dtype] = None,
):
super().__init__(message)
self.actual_type = actual_type
self.expected_type = expected_type
-class ValueCheckError(BaseError):
- """Raised when value/range validation fails.
+class ValueCheckError(BaseError, ValueError):
+ """Raised when value/range validation fails. Also a :exc:`ValueError`.
Attributes:
actual_value: The actual value that failed validation.
@@ -95,8 +102,8 @@ class ValueCheckError(BaseError):
self.expected_range = expected_range
-class DeviceError(BaseError):
- """Raised when device mismatch validation fails.
+class DeviceError(BaseError, ValueError):
+ """Raised when device mismatch validation fails. Also a :exc:`ValueError`.
Attributes:
actual_devices: The actual device(s) that failed validation.
@@ -115,5 +122,5 @@ class DeviceError(BaseError):
self.expected_device = expected_device
-class ImageError(BaseError):
- """Raised when image-specific validation fails."""
+class ImageError(BaseError, ValueError):
+ """Raised when image-specific validation fails. Also a :exc:`ValueError`."""
diff --git a/kornia/core/utils.py b/kornia/core/utils.py
index 6fd3965aa..a5e98658a 100644
--- a/kornia/core/utils.py
+++ b/kornia/core/utils.py
@@ -35,7 +35,7 @@ from kornia.core._small_linalg import (
_inverse_3x3_scalar,
)
from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_TYPE
-from kornia.core.exceptions import DeviceError
+from kornia.core.exceptions import DeviceError, TypeCheckError
def xla_is_available() -> bool:
@@ -93,40 +93,41 @@ def get_cuda_or_mps_device_if_available() -> torch.device:
def _extract_device_dtype(tensor_list: List[Optional[Any]]) -> Tuple[torch.device, torch.dtype]:
- """Check if all the input are in the same device (only if when they are torch.Tensor).
+ """Check that the tensors in the list share one device and one dtype, and return them.
- If so, it would return a tuple of (device, dtype).
- Default: (``torch.get_default_device()``, ``torch.get_default_dtype()``).
+ Entries that are not tensors (``None`` included) are skipped. Without any tensor, the result is
+ (``torch.get_default_device()``, ``torch.get_default_dtype()``).
Returns:
[torch.device, torch.dtype]
+ Raises:
+ DeviceError: if two tensors are on different devices. Every device is checked before any dtype, so this
+ error wins when the devices and the dtypes both differ, wherever the mismatches sit in the list.
+ TypeCheckError: if all the tensors share one device and two of them have different dtypes.
+
"""
- device, dtype = None, None
- for tensor in tensor_list:
- if tensor is not None:
- if not isinstance(tensor, torch.Tensor):
- continue
- _device = tensor.device
- _dtype = tensor.dtype
- if device is None and dtype is None:
- device = _device
- dtype = _dtype
- elif device != _device or dtype != _dtype:
- raise DeviceError(
- f"Passed values are not in the same device and dtype. "
- f"Got ({device}, {dtype}) and ({_device}, {_dtype}).",
- actual_devices=[device, _device],
- expected_device=device,
- )
- if device is None:
+ tensors = [tensor for tensor in tensor_list if isinstance(tensor, torch.Tensor)]
+ for tensor in tensors[1:]:
+ if tensor.device != tensors[0].device:
+ raise DeviceError(
+ f"Passed tensors are not on the same device: expected {tensors[0].device}, got {tensor.device}.",
+ actual_devices=[tensors[0].device, tensor.device],
+ expected_device=tensors[0].device,
+ )
+ for tensor in tensors[1:]:
+ if tensor.dtype != tensors[0].dtype:
+ raise TypeCheckError(
+ f"Passed tensors do not have the same dtype: expected {tensors[0].dtype}, got {tensor.dtype}.",
+ actual_type=tensor.dtype,
+ expected_type=tensors[0].dtype,
+ )
+ if not tensors:
# `torch.empty(0).device` reads the current default device and, unlike
# `torch.get_default_device()`, is traceable by dynamo β€” so this helper stays
# fullgraph-compilable even when a caller can't prove a tensor is in the list.
- device = torch.empty(0).device
- if dtype is None:
- dtype = torch.get_default_dtype()
- return (device, dtype)
+ return (torch.empty(0).device, torch.get_default_dtype())
+ return (tensors[0].device, tensors[0].dtype)
def _normalize_to_float32_or_float64(dtype: torch.dtype) -> torch.dtype:
diff --git a/tests/core/test_exceptions.py b/tests/core/test_exceptions.py
new file mode 100644
index 000000000..4c58c9229
--- /dev/null
+++ b/tests/core/test_exceptions.py
@@ -0,0 +1,155 @@
+# LICENSE HEADER MANAGED BY add-license-header
+#
+# Copyright 2018 Kornia Team
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+import copy
+import pickle
+
+import pytest
+import torch
+
+from kornia.core.check import (
+ KORNIA_CHECK,
+ KORNIA_CHECK_DM_DESC,
+ KORNIA_CHECK_IS_COLOR,
+ KORNIA_CHECK_IS_COLOR_OR_GRAY,
+ KORNIA_CHECK_IS_GRAY,
+ KORNIA_CHECK_IS_IMAGE,
+ KORNIA_CHECK_IS_LIST_OF_TENSOR,
+ KORNIA_CHECK_IS_TENSOR,
+ KORNIA_CHECK_SAME_DEVICE,
+ KORNIA_CHECK_SAME_DEVICES,
+ KORNIA_CHECK_SAME_SHAPE,
+ KORNIA_CHECK_SHAPE,
+ KORNIA_CHECK_TYPE,
+)
+from kornia.core.exceptions import (
+ BaseError,
+ DeviceError,
+ ImageError,
+ ShapeError,
+ TypeCheckError,
+ ValueCheckError,
+)
+
+from testing.base import BaseTester
+
+# One real check failure per helper, with the class it raises and the builtin that class also derives from (#5193).
+_CHECK_FAILURES = [
+ pytest.param(
+ lambda device: KORNIA_CHECK_SHAPE(torch.zeros(2, 3, device=device), ["1", "H", "W"]),
+ ShapeError,
+ ValueError,
+ id="KORNIA_CHECK_SHAPE",
+ ),
+ pytest.param(
+ lambda device: KORNIA_CHECK_SAME_SHAPE(torch.zeros(2, 3, device=device), torch.zeros(3, 2, device=device)),
+ ShapeError,
+ ValueError,
+ id="KORNIA_CHECK_SAME_SHAPE",
+ ),
+ pytest.param(
+ lambda device: KORNIA_CHECK_DM_DESC(
+ torch.zeros(4, device=device), torch.zeros(8, device=device), torch.zeros(4, 7, device=device)
+ ),
+ ShapeError,
+ ValueError,
+ id="KORNIA_CHECK_DM_DESC",
+ ),
+ pytest.param(lambda device: KORNIA_CHECK_TYPE(1, str), TypeCheckError, TypeError, id="KORNIA_CHECK_TYPE"),
+ pytest.param(lambda device: KORNIA_CHECK_IS_TENSOR([1.0]), TypeCheckError, TypeError, id="KORNIA_CHECK_IS_TENSOR"),
+ pytest.param(
+ lambda device: KORNIA_CHECK_IS_LIST_OF_TENSOR([torch.zeros(1, device=device), 1]),
+ TypeCheckError,
+ TypeError,
+ id="KORNIA_CHECK_IS_LIST_OF_TENSOR",
+ ),
+ pytest.param(
+ lambda device: KORNIA_CHECK_IS_IMAGE(torch.full((1, 2, 2), 2.0, device=device)),
+ ValueCheckError,
+ ValueError,
+ id="KORNIA_CHECK_IS_IMAGE",
+ ),
+ pytest.param(
+ lambda device: KORNIA_CHECK_SAME_DEVICE(torch.zeros(1, device=device), torch.zeros(1, device="meta")),
+ DeviceError,
+ ValueError,
+ id="KORNIA_CHECK_SAME_DEVICE",
+ ),
+ pytest.param(
+ lambda device: KORNIA_CHECK_SAME_DEVICES([torch.zeros(1, device=device), torch.zeros(1, device="meta")]),
+ DeviceError,
+ ValueError,
+ id="KORNIA_CHECK_SAME_DEVICES",
+ ),
+ pytest.param(
+ lambda device: KORNIA_CHECK_IS_COLOR(torch.zeros(1, 4, 4, device=device)),
+ ImageError,
+ ValueError,
+ id="KORNIA_CHECK_IS_COLOR",
+ ),
+ pytest.param(
+ lambda device: KORNIA_CHECK_IS_GRAY(torch.zeros(3, 4, 4, device=device)),
+ ImageError,
+ ValueError,
+ id="KORNIA_CHECK_IS_GRAY",
+ ),
+ pytest.param(
+ lambda device: KORNIA_CHECK_IS_COLOR_OR_GRAY(torch.zeros(2, 4, 4, device=device)),
+ ImageError,
+ ValueError,
+ id="KORNIA_CHECK_IS_COLOR_OR_GRAY",
+ ),
+]
+
+
+class TestExceptionBases(BaseTester):
+ """The builtin bases of the check exceptions (#5193)."""
+
+ @pytest.mark.parametrize("check, error, builtin", _CHECK_FAILURES)
+ def test_convention_kornia_errors_are_catchable_as_builtin(self, device, check, error, builtin):
+ # The ``except`` a caller writes around a kornia call catches the check's class through its builtin base.
+ with pytest.raises(builtin) as excinfo:
+ check(device)
+ assert type(excinfo.value) is error
+ # ``except BaseError`` keeps catching every check failure.
+ assert isinstance(excinfo.value, BaseError)
+ # Each class has one builtin base: a shape error is not a ``TypeError``, a type error not a ``ValueError``.
+ other = TypeError if builtin is ValueError else ValueError
+ assert not isinstance(excinfo.value, other)
+
+ def test_kornia_check_raises_the_bare_base_error(self):
+ # ``KORNIA_CHECK`` carries no semantic of its own, so its ``BaseError`` stays a plain ``Exception``.
+ with pytest.raises(BaseError) as excinfo:
+ KORNIA_CHECK(False, "a failed condition")
+ assert type(excinfo.value) is BaseError
+ assert not isinstance(excinfo.value, (ValueError, TypeError))
+ assert BaseError.__bases__ == (Exception,)
+
+ @pytest.mark.parametrize("check, error, builtin", _CHECK_FAILURES)
+ def test_pickle_and_copy_keep_class_message_and_attributes(self, device, check, error, builtin):
+ with pytest.raises(error) as excinfo:
+ check(device)
+ raised = excinfo.value
+ protocols = range(2, pickle.HIGHEST_PROTOCOL + 1)
+ clones = [pickle.loads(pickle.dumps(raised, protocol=p)) for p in protocols] # noqa: S301 - our own bytes
+ clones += [copy.copy(raised), copy.deepcopy(raised)]
+ for clone in clones:
+ assert type(clone) is error
+ assert isinstance(clone, builtin)
+ assert clone.args == raised.args
+ assert str(clone) == str(raised)
+ assert vars(clone) == vars(raised)
diff --git a/tests/core/test_helpers.py b/tests/core/test_helpers.py
index b7df02332..9cef21eb3 100644
--- a/tests/core/test_helpers.py
+++ b/tests/core/test_helpers.py
@@ -18,7 +18,7 @@
import pytest
import torch
-from kornia.core.exceptions import DeviceError
+from kornia.core.exceptions import DeviceError, TypeCheckError
from kornia.core.utils import (
_adjugate_closed_form,
_extract_device_dtype,
@@ -34,50 +34,114 @@ from kornia.core.utils import (
safe_solve_with_mask,
)
-from testing.base import assert_close
+from testing.base import BaseTester, assert_close
@pytest.mark.parametrize(
- "tensor_list,out_device,out_dtype,will_throw_error",
+ "tensor_list,out_device,out_dtype,error",
[
- ([], torch.device("cpu"), torch.get_default_dtype(), False),
- ([None, None], torch.device("cpu"), torch.get_default_dtype(), False),
- ([torch.tensor(0, device="cpu", dtype=torch.float16), None], torch.device("cpu"), torch.float16, False),
- ([torch.tensor(0, device="cpu", dtype=torch.float32), None], torch.device("cpu"), torch.float32, False),
- ([torch.tensor(0, device="cpu", dtype=torch.float64), None], torch.device("cpu"), torch.float64, False),
- ([torch.tensor(0, device="cpu", dtype=torch.float16)] * 2, torch.device("cpu"), torch.float16, False),
- ([torch.tensor(0, device="cpu", dtype=torch.float32)] * 2, torch.device("cpu"), torch.float32, False),
- ([torch.tensor(0, device="cpu", dtype=torch.float64)] * 2, torch.device("cpu"), torch.float64, False),
+ ([], torch.device("cpu"), torch.get_default_dtype(), None),
+ ([None, None], torch.device("cpu"), torch.get_default_dtype(), None),
+ ([torch.tensor(0, device="cpu", dtype=torch.float16), None], torch.device("cpu"), torch.float16, None),
+ ([torch.tensor(0, device="cpu", dtype=torch.float32), None], torch.device("cpu"), torch.float32, None),
+ ([torch.tensor(0, device="cpu", dtype=torch.float64), None], torch.device("cpu"), torch.float64, None),
+ ([torch.tensor(0, device="cpu", dtype=torch.float16)] * 2, torch.device("cpu"), torch.float16, None),
+ ([torch.tensor(0, device="cpu", dtype=torch.float32)] * 2, torch.device("cpu"), torch.float32, None),
+ ([torch.tensor(0, device="cpu", dtype=torch.float64)] * 2, torch.device("cpu"), torch.float64, None),
(
[torch.tensor(0, device="cpu", dtype=torch.float16), torch.tensor(0, device="cpu", dtype=torch.float64)],
None,
None,
- True,
+ TypeCheckError,
),
(
[torch.tensor(0, device="cpu", dtype=torch.float32), torch.tensor(0, device="cpu", dtype=torch.float64)],
None,
None,
- True,
+ TypeCheckError,
),
(
[torch.tensor(0, device="cpu", dtype=torch.float16), torch.tensor(0, device="cpu", dtype=torch.float32)],
None,
None,
- True,
+ TypeCheckError,
+ ),
+ (
+ [torch.tensor(0, device="cpu", dtype=torch.float32), torch.tensor(0, device="meta", dtype=torch.float32)],
+ None,
+ None,
+ DeviceError,
+ ),
+ (
+ [torch.tensor(0, device="cpu", dtype=torch.float32), torch.tensor(0, device="meta", dtype=torch.float64)],
+ None,
+ None,
+ DeviceError,
+ ),
+ # A device mismatch anywhere in the list wins over a dtype mismatch, whichever comes first.
+ (
+ [
+ torch.tensor(0, device="cpu", dtype=torch.float32),
+ torch.tensor(0, device="cpu", dtype=torch.float64),
+ torch.tensor(0, device="meta", dtype=torch.float32),
+ ],
+ None,
+ None,
+ DeviceError,
+ ),
+ (
+ [
+ torch.tensor(0, device="meta", dtype=torch.float32),
+ torch.tensor(0, device="cpu", dtype=torch.float64),
+ torch.tensor(0, device="cpu", dtype=torch.float32),
+ ],
+ None,
+ None,
+ DeviceError,
),
],
)
-def test_extract_device_dtype(tensor_list, out_device, out_dtype, will_throw_error):
- if will_throw_error:
- with pytest.raises(DeviceError):
+def test_extract_device_dtype(tensor_list, out_device, out_dtype, error):
+ if error is not None:
+ with pytest.raises(error) as excinfo:
_extract_device_dtype(tensor_list)
+ assert type(excinfo.value) is error
else:
device, dtype = _extract_device_dtype(tensor_list)
assert device == out_device
assert dtype == out_dtype
+class TestExtractDeviceDtype(BaseTester):
+ def test_dtype_only_mismatch_raises_type_check_error(self, device):
+ # Same device, two dtypes: a dtype problem, reported as one (#5199).
+ a = torch.zeros(1, device=device, dtype=torch.float32)
+ b = torch.zeros(1, device=device, dtype=torch.float16)
+ with pytest.raises(TypeError) as excinfo:
+ _extract_device_dtype([a, None, b])
+ err = excinfo.value
+ assert type(err) is TypeCheckError
+ assert err.expected_type == torch.float32
+ assert err.actual_type == torch.float16
+ assert "expected torch.float32, got torch.float16" in str(err)
+
+ def test_device_mismatch_raises_device_error(self, device):
+ # A device mismatch stays a DeviceError, also when the dtypes differ too, and also when a same-device pair
+ # with two dtypes comes before it in the list.
+ a = torch.zeros(1, device=device, dtype=torch.float32)
+ other_dtype = torch.zeros(1, device=device, dtype=torch.float16)
+ for tensors in (
+ [a, torch.zeros(1, device="meta", dtype=torch.float32)],
+ [a, torch.zeros(1, device="meta", dtype=torch.float16)],
+ [a, other_dtype, torch.zeros(1, device="meta", dtype=torch.float32)],
+ ):
+ with pytest.raises(DeviceError) as excinfo:
+ _extract_device_dtype(tensors)
+ assert excinfo.value.actual_devices == [a.device, torch.device("meta")]
+ assert excinfo.value.expected_device == a.device
+ assert str(excinfo.value) == f"Passed tensors are not on the same device: expected {a.device}, got meta."
+
+
class TestInverseCast:
@pytest.mark.parametrize("input_shape", [(4, 4), (1, 3, 4, 4), (2, 4, 5, 5)])
def test_smoke(self, device, dtype, input_shape):