Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(core): eye_like and vec_like reject a non-integer n with a TypeCheckError (#5251)

Dmytro Mishkindd7c3d376997
diff --git a/changelog.d/5251.fixed.md b/changelog.d/5251.fixed.md
new file mode 100644
index 000000000..c6da640b2
--- /dev/null
+++ b/changelog.d/5251.fixed.md
@@ -0,0 +1 @@
+`kornia.core.ops.eye_like` and `vec_like` now reject a non-integer `n` with a `TypeCheckError` that names `n` ("n must be an integer. Got: 2.0 (float)"), carrying the offending type as `actual_type` and `int` as `expected_type`. Before, a `float`, `True`, a NumPy float or bool scalar or a float tensor got past the `n > 0` check and failed inside torch with a builtin `TypeError` about the signature of `torch.eye` or `torch.zeros`; a string or `None` failed in that comparison with a `TypeError`; `torch.tensor(True)` and a multi-element tensor failed with a `RuntimeError`; and `False` and `torch.tensor(False)` raised "n must be positive. Got: False". With NumPy 1.x, whose bool scalars still implement `__index__`, `np.True_` was read as 1 and `np.False_` raised "n must be positive"; both are rejected too. `TypeCheckError` is a `BaseError`, and since #5233 also a `TypeError`, so both `except BaseError` and `except TypeError` around such a call catch it. An `int`, a NumPy integer and a 0-d integer tensor are accepted as before, and `n <= 0` raises the same error as before.
diff --git a/kornia/core/ops.py b/kornia/core/ops.py
index 82f3d59aa..1ee743cf4 100644
--- a/kornia/core/ops.py
+++ b/kornia/core/ops.py
@@ -15,16 +15,70 @@
# limitations under the License.
#
+import operator
+from typing import Any
+
import torch
-from kornia.core.check import KORNIA_CHECK
+from kornia.core.check import KORNIA_CHECK, are_checks_enabled
+from kornia.core.exceptions import TypeCheckError
+
+
+def _is_numpy_bool(n: Any) -> bool:
+ """Return whether ``n`` is a NumPy boolean scalar, read off its type so that this module does not import NumPy.
+
+ NumPy 1.x boolean scalars implement ``__index__`` (deprecated there, removed in NumPy 2.0), so ``operator.index``
+ reads ``np.True_`` as 1; the type is ``numpy.bool_`` on NumPy 1.x and ``numpy.bool`` on NumPy 2.
+ """
+ n_type = type(n)
+ return n_type.__module__ == "numpy" and n_type.__name__ in ("bool_", "bool")
+
+
+def _check_n_is_integer(n: Any) -> None:
+ """Raise `TypeCheckError` naming ``n`` unless it is an integer size.
+
+ Accepts an ``int``, a NumPy integer, an integer tensor with one element and a ``SymInt``: whatever
+ ``operator.index`` reads as an integer. ``bool`` is an ``int`` subclass and ``operator.index`` accepts it, as it
+ does a boolean tensor and, on NumPy 1.x, a NumPy boolean scalar, so all three are rejected by name; ``torch.eye``
+ and ``torch.zeros`` refuse the first two as sizes anyway. An integer tensor that cannot be read (a meta tensor)
+ raises torch's own ``RuntimeError``. Python-only: TorchScript cannot compile this body, and types ``n`` as ``int``
+ already. Like the ``KORNIA_CHECK*`` helpers, it does nothing once `disable_checks` has been called.
+ """
+ if not are_checks_enabled():
+ return
+ is_integer = True
+ if isinstance(n, bool) or (isinstance(n, torch.Tensor) and n.dtype == torch.bool):
+ is_integer = False
+ elif not isinstance(n, (int, torch.SymInt)):
+ # Ask `hasattr` first, so a `float`, `str` or `None` never reaches `operator.index`: on torch 2.5.1 dynamo
+ # aborts the trace with `InternalTorchDynamoError` when a builtin raises inside a `try`. The NumPy bool test
+ # sits in this branch so that a plain `int` never meets it: torch 2.5.1 dynamo cannot trace its comparison.
+ if not hasattr(n, "__index__") or _is_numpy_bool(n):
+ is_integer = False
+ else:
+ try:
+ operator.index(n)
+ except TypeError: # float tensor, multi-element tensor, ndarray; any other error (meta tensor) is torch's
+ is_integer = False
+ if not is_integer:
+ raise TypeCheckError(
+ f"n must be an integer. Got: {n!r} ({type(n).__name__})", actual_type=type(n), expected_type=int
+ )
+
+
+def _check_n(n: int) -> None:
+ """Validate the ``n`` of `eye_like` and `vec_like`: an integer, else `TypeCheckError`, and a positive one."""
+ if not torch.jit.is_scripting():
+ _check_n_is_integer(n)
+ KORNIA_CHECK(n > 0, f"n must be positive. Got: {n}")
def eye_like(n: int, input: torch.Tensor, shared_memory: bool = False) -> torch.Tensor:
r"""Return a 2-D tensor with ones on the diagonal and zeros elsewhere with the same batch size as the input.
Args:
- n: the number of rows :math:`(N)`.
+ n: the number of rows :math:`(N)`, a positive integer: an ``int``, a NumPy integer or a 0-d integer tensor.
+ A ``float`` or a ``bool`` is rejected.
input: image tensor that will determine the batch size of the output matrix.
The expected shape is :math:`(B, *)`.
shared_memory: when set, all samples in the batch will share the same memory.
@@ -32,13 +86,17 @@ def eye_like(n: int, input: torch.Tensor, shared_memory: bool = False) -> torch.
Returns:
The identity matrix with the same batch size as the input :math:`(B, N, N)`.
+ Raises:
+ TypeCheckError: if ``n`` is not an integer.
+ BaseError: if ``n`` is not positive, or if ``input`` has no dimension.
+
Notes:
When the dimension to expand is of size 1, using torch.expand(...) yields the same tensor as torch.repeat(...)
without using extra memory. Thus, when the tensor obtained by this method will be later assigned -
use this method with shared_memory=False, otherwise, prefer using it with shared_memory=True.
"""
- KORNIA_CHECK(n > 0, f"n must be positive. Got: {n}")
+ _check_n(n)
KORNIA_CHECK(len(input.shape) >= 1, f"input must have at least 1 dimension. Got shape: {input.shape}")
# Use torch.eye with dtype parameter directly (available since PyTorch 2.0+)
@@ -51,7 +109,8 @@ def vec_like(n: int, tensor: torch.Tensor, shared_memory: bool = False) -> torch
r"""Return a 2-D tensor with a vector containing zeros with the same batch size as the input.
Args:
- n: the number of rows :math:`(N)`.
+ n: the number of rows :math:`(N)`, a positive integer: an ``int``, a NumPy integer or a 0-d integer tensor.
+ A ``float`` or a ``bool`` is rejected.
tensor: image tensor that will determine the batch size of the output matrix.
The expected shape is :math:`(B, *)`.
shared_memory: when set, all samples in the batch will share the same memory.
@@ -59,13 +118,17 @@ def vec_like(n: int, tensor: torch.Tensor, shared_memory: bool = False) -> torch
Returns:
The vector with the same batch size as the input :math:`(B, N, 1)`.
+ Raises:
+ TypeCheckError: if ``n`` is not an integer.
+ BaseError: if ``n`` is not positive, or if ``tensor`` has no dimension.
+
Notes:
When the dimension to expand is of size 1, using torch.expand(...) yields the same tensor as torch.repeat(...)
without using extra memory. Thus, when the tensor obtained by this method will be later assigned -
use this method with shared_memory=False, otherwise, prefer using it with shared_memory=True.
"""
- KORNIA_CHECK(n > 0, f"n must be positive. Got: {n}")
+ _check_n(n)
KORNIA_CHECK(len(tensor.shape) >= 1, f"tensor must have at least 1 dimension. Got shape: {tensor.shape}")
vec = torch.zeros(n, 1, device=tensor.device, dtype=tensor.dtype)
diff --git a/tests/core/test_ops.py b/tests/core/test_ops.py
new file mode 100644
index 000000000..6faf7cd5a
--- /dev/null
+++ b/tests/core/test_ops.py
@@ -0,0 +1,259 @@
+# 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 numpy as np
+import pytest
+import torch
+
+from kornia.core.check import are_checks_enabled, disable_checks, enable_checks
+from kornia.core.exceptions import BaseError, TypeCheckError
+from kornia.core.ops import eye_like, vec_like
+
+from testing.base import BaseTester
+
+# Every `n` below is built by a factory, so no tensor is created at collection time.
+ACCEPTED_INTEGERS = {
+ "int": lambda: 3,
+ "numpy-int64": lambda: np.int64(3),
+ "numpy-int32": lambda: np.int32(3),
+ "tensor-0d-int64": lambda: torch.tensor(3),
+ "tensor-0d-int32": lambda: torch.tensor(3, dtype=torch.int32),
+ # Accepted before the integer check existed (torch reads them as a size) and kept: `operator.index` takes them.
+ "tensor-one-element-int": lambda: torch.tensor([3]),
+ "numpy-0d-array": lambda: np.array(3),
+}
+
+REJECTED_NON_INTEGERS = {
+ "float": lambda: 2.0,
+ "float-fractional": lambda: 3.5,
+ "bool-true": lambda: True,
+ "bool-false": lambda: False,
+ "numpy-float64": lambda: np.float64(2.0),
+ "numpy-bool": lambda: np.bool_(True),
+ "numpy-bool-false": lambda: np.bool_(False),
+ "tensor-0d-float": lambda: torch.tensor(2.0),
+ "tensor-0d-bool": lambda: torch.tensor(True),
+ "tensor-vector": lambda: torch.tensor([3, 3]),
+ "str": lambda: "3",
+ "none": lambda: None,
+}
+
+NON_POSITIVE_INTEGERS = {
+ "zero": lambda: 0,
+ "negative": lambda: -1,
+ "numpy-zero": lambda: np.int64(0),
+ "tensor-0d-zero": lambda: torch.tensor(0),
+}
+
+
+class _BatchLikeMixin(BaseTester):
+ """Checks shared by `eye_like` and `vec_like`: both take `(n, input, shared_memory)` and return `(B, n, *)`."""
+
+ op = None # the function under test, set by the subclass
+
+ def item_shape(self, n):
+ """Return the shape of one batch item for a given `n`."""
+ raise NotImplementedError
+
+ def expected(self, batch, n, device, dtype):
+ """Return the expected output for a batch of `batch` items."""
+ raise NotImplementedError
+
+ @pytest.mark.parametrize("n", [1, 2, 3, 4])
+ @pytest.mark.parametrize("input_shape", [(4,), (2, 3), (3, 1, 5, 5)])
+ def test_values(self, n, input_shape, device, dtype):
+ x = torch.zeros(*input_shape, device=device, dtype=dtype)
+ out = self.op(n, x)
+ assert out.shape == (input_shape[0], *self.item_shape(n))
+ assert out.device == x.device
+ assert out.dtype == x.dtype
+ assert torch.equal(out, self.expected(input_shape[0], n, device, dtype))
+
+ @pytest.mark.parametrize("shared_memory", [False, True])
+ def test_shared_memory_does_not_change_values(self, shared_memory, device, dtype):
+ x = torch.zeros(3, 2, device=device, dtype=dtype)
+ out = self.op(3, x, shared_memory=shared_memory)
+ assert out.shape == (3, *self.item_shape(3))
+ assert torch.equal(out, self.expected(3, 3, device, dtype))
+
+ def test_shared_memory_true_expands_one_copy(self, device, dtype):
+ x = torch.zeros(4, 2, device=device, dtype=dtype)
+ out = self.op(3, x, shared_memory=True)
+ assert out.stride(0) == 0
+ assert all(out[i].data_ptr() == out[0].data_ptr() for i in range(1, 4))
+
+ def test_shared_memory_false_owns_each_batch_item(self, device, dtype):
+ x = torch.zeros(4, 2, device=device, dtype=dtype)
+ out = self.op(3, x)
+ assert out.is_contiguous()
+ assert len({out[i].data_ptr() for i in range(4)}) == 4
+ # writing into one batch item must not leak into another
+ before = out[1].clone()
+ out[0].fill_(7)
+ assert torch.equal(out[1], before)
+
+ @pytest.mark.parametrize("make_n", ACCEPTED_INTEGERS.values(), ids=ACCEPTED_INTEGERS.keys())
+ def test_integer_n_of_any_integer_type(self, make_n, device, dtype):
+ x = torch.zeros(2, 2, device=device, dtype=dtype)
+ assert torch.equal(self.op(make_n(), x), self.op(3, x))
+
+ def test_integer_tensor_n_on_the_device(self, device, dtype):
+ # The other integer tensors above live on the CPU: this one is read as a size from the accelerator.
+ x = torch.zeros(2, 2, device=device, dtype=dtype)
+ n = torch.tensor(3, device=device)
+ assert torch.equal(self.op(n, x), self.op(3, x))
+
+ def test_meta_integer_tensor_n_raises_torchs_error(self, device, dtype):
+ # A meta tensor holds no value to read as a size. It is an integer, so it is not a `TypeCheckError`:
+ # torch raises its own `RuntimeError`, as it did before the integer check existed.
+ x = torch.zeros(2, 2, device=device, dtype=dtype)
+ with pytest.raises(RuntimeError, match="meta tensors"):
+ self.op(torch.tensor(3, device="meta"), x)
+
+ @pytest.mark.parametrize("make_n", REJECTED_NON_INTEGERS.values(), ids=REJECTED_NON_INTEGERS.keys())
+ def test_non_integer_n_raises_type_check_error_naming_n(self, make_n, device, dtype):
+ x = torch.zeros(2, 2, device=device, dtype=dtype)
+ n = make_n()
+ with pytest.raises(TypeCheckError, match=r"n must be an integer\. Got: ") as excinfo:
+ self.op(n, x)
+ assert isinstance(excinfo.value, BaseError)
+ assert excinfo.value.actual_type is type(n)
+ assert excinfo.value.expected_type is int
+
+ def test_non_integer_n_message_shows_the_value_and_type(self, device, dtype):
+ x = torch.zeros(2, 2, device=device, dtype=dtype)
+ with pytest.raises(TypeCheckError, match=r"n must be an integer\. Got: 2\.0 \(float\)"):
+ self.op(2.0, x)
+ with pytest.raises(TypeCheckError, match=r"n must be an integer\. Got: True \(bool\)"):
+ self.op(True, x)
+
+ def test_numpy_1_bool_scalar_is_rejected_by_type(self, device, dtype):
+ # NumPy 1.x `np.bool_` implements `__index__` (NumPy 2 removed it), so `operator.index` reads `np.True_` as 1
+ # there. This stand-in has NumPy 1.x's type name and an `__index__`, so the rejection is pinned on NumPy 2 too.
+ numpy_1_bool = type(
+ "bool_", (), {"__module__": "numpy", "__index__": lambda self: 1, "__gt__": lambda s, o: 1 > o}
+ )
+ x = torch.zeros(2, 2, device=device, dtype=dtype)
+ with pytest.raises(TypeCheckError, match=r"n must be an integer\. Got: .* \(bool_\)") as excinfo:
+ self.op(numpy_1_bool(), x)
+ assert excinfo.value.actual_type is numpy_1_bool
+
+ def test_non_integer_n_is_left_to_torch_when_checks_are_disabled(self, device, dtype):
+ x = torch.zeros(2, 2, device=device, dtype=dtype)
+ was_enabled = are_checks_enabled()
+ disable_checks()
+ try:
+ with pytest.raises(TypeError) as excinfo:
+ self.op(2.0, x)
+ finally:
+ if was_enabled:
+ enable_checks()
+ assert not isinstance(excinfo.value, BaseError)
+
+ @pytest.mark.parametrize("make_n", NON_POSITIVE_INTEGERS.values(), ids=NON_POSITIVE_INTEGERS.keys())
+ def test_non_positive_n_raises(self, make_n, device, dtype):
+ x = torch.zeros(2, 2, device=device, dtype=dtype)
+ with pytest.raises(BaseError, match=r"n must be positive\. Got: "):
+ self.op(make_n(), x)
+
+ def test_input_without_a_batch_dimension_raises(self, device, dtype):
+ x = torch.tensor(1.0, device=device, dtype=dtype)
+ with pytest.raises(BaseError, match="at least 1 dimension"):
+ self.op(3, x)
+
+ def test_dynamo(self, device, dtype, torch_optimizer):
+ x = torch.zeros(2, 4, device=device, dtype=dtype)
+ for shared_memory in (False, True):
+
+ def run(t, shared_memory=shared_memory):
+ return self.op(3, t, shared_memory=shared_memory)
+
+ self.assert_close(torch_optimizer(run, fullgraph=True)(x), run(x))
+
+ @pytest.mark.parametrize(
+ "make_n", [lambda: 2.0, lambda: True, lambda: "3", lambda: None], ids=["float", "bool", "str", "none"]
+ )
+ def test_dynamo_non_integer_n_raises_type_check_error(self, make_n, device, dtype, torch_optimizer):
+ # `n` is an argument of the compiled function, so the check runs while dynamo traces it. On torch 2.5.1 a
+ # builtin that raises inside a `try` aborts the trace with `InternalTorchDynamoError`, not a kornia error.
+ x = torch.zeros(2, 4, device=device, dtype=dtype)
+ compiled = torch_optimizer(self.op)
+ with pytest.raises(TypeCheckError, match=r"n must be an integer\. Got: "):
+ compiled(make_n(), x)
+
+ def test_dynamo_symbolic_n(self, device, dtype, torch_optimizer):
+ # `n` read off a tensor shape changes between calls. Dynamo specialises it (it never hands the check a
+ # `torch.SymInt`), so this pins only that a changing `n` compiles and gives the right result; see
+ # `test_symbolic_n_under_make_fx` for a real `SymInt`.
+ def run(t):
+ return self.op(t.shape[-1], t)
+
+ compiled = torch_optimizer(run, fullgraph=True)
+ for size in (3, 4, 5):
+ x = torch.zeros(2, size, device=device, dtype=dtype)
+ self.assert_close(compiled(x), run(x))
+
+ def test_symbolic_n_under_make_fx(self, device, dtype):
+ # `make_fx(tracing_mode="symbolic")` is what hands the check a real `torch.SymInt`
+ from torch.fx.experimental.proxy_tensor import make_fx
+
+ seen = []
+
+ def run(t):
+ seen.append(type(t.shape[-1]))
+ return self.op(t.shape[-1], t)
+
+ make_fx(run, tracing_mode="symbolic")(torch.zeros(2, 4, device=device, dtype=dtype))
+ assert seen == [torch.SymInt]
+
+ def test_scripts(self, device, dtype):
+ x = torch.zeros(2, 2, device=device, dtype=dtype)
+ scripted = torch.jit.script(self.op)
+ assert torch.equal(scripted(3, x), self.op(3, x))
+ assert torch.equal(scripted(3, x, True), self.op(3, x, shared_memory=True))
+ with pytest.raises(Exception, match=r"n must be positive\. Got: 0"):
+ scripted(0, x)
+
+
+class TestEyeLike(_BatchLikeMixin):
+ op = staticmethod(eye_like)
+
+ def item_shape(self, n):
+ return (n, n)
+
+ def expected(self, batch, n, device, dtype):
+ return torch.eye(n, device=device, dtype=dtype).expand(batch, n, n)
+
+ def test_shared_memory_stride(self, device, dtype):
+ x = torch.zeros(4, 2, device=device, dtype=dtype)
+ assert eye_like(3, x, shared_memory=True).stride() == (0, 3, 1)
+ assert eye_like(3, x, shared_memory=False).stride() == (9, 3, 1)
+
+
+class TestVecLike(_BatchLikeMixin):
+ op = staticmethod(vec_like)
+
+ def item_shape(self, n):
+ return (n, 1)
+
+ def expected(self, batch, n, device, dtype):
+ return torch.zeros(batch, n, 1, device=device, dtype=dtype)
+
+ def test_shared_memory_stride(self, device, dtype):
+ x = torch.zeros(4, 2, device=device, dtype=dtype)
+ assert vec_like(3, x, shared_memory=True).stride() == (0, 1, 1)
+ assert vec_like(3, x, shared_memory=False).stride() == (3, 1, 1)