π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(core)!: keep TensorWrapper's own names out of __getattr__ and complete its operators (#5243)
Dmytro Mishkind97b63fb16ec
diff --git a/changelog.d/5243.breaking.md b/changelog.d/5243.breaking.mdnew file mode 100644index 000000000..5e0f5d2f4--- /dev/null+++ b/changelog.d/5243.breaking.md@@ -0,0 +1,11 @@+The in-place operators of `kornia.core.TensorWrapper`, and so of `Vector2`, `Vector3` and `Scalar` (`+=`, `-=`, `*=`,+`/=`, `//=`, `%=`, `**=`, `&=`, `|=`, `^=`, `<<=` and `>>=`), now update the wrapped tensor in place and return the same+wrapper, as they do on a tensor. They used to rebind the name to a new wrapper: `+=`, `-=`, `*=`, `/=` and `//=` with+any operand, and the others with a tensor operand (with a Python number or another wrapper they raised `TypeError`).+So an alias kept the old values, and the tensor the wrapper was built from was never modified. A wrapper does not copy+the tensor it is built from, so `v = Vector3(t); v += 1` now also modifies `t`. An in-place operator now raises+`RuntimeError` where the tensor's in-place operator raises, where it used to return a new wrapper: on a wrapper of a+leaf that requires grad, such as `Vector3(nn.Parameter(...))` ("a leaf Variable that requires grad is being used in an+in-place operation"), for an update that changes the dtype, such as `/=` on an integer wrapper ("result type Float+can't be cast to the desired output type Long"), and for an update that broadcasts to a larger shape. Write+`v = v + x` to keep the old behaviour. `@=` still rebinds, as it does on a tensor.diff --git a/changelog.d/5243.fixed.md b/changelog.d/5243.fixed.mdnew file mode 100644index 000000000..7807e924d--- /dev/null+++ b/changelog.d/5243.fixed.md@@ -0,0 +1,15 @@+`torch.compile` can trace a function that builds a `kornia.core.TensorWrapper`: on torch 2.14 and 2.5.1 it used to fail+inside Dynamo with `RecursionError`, with or without `fullgraph=True`, because `TensorWrapper.__getattr__` looked up the+wrapper's own unset slots through itself on the instance Dynamo had not initialised yet. The wrapper's own names (its+slots, `data`, `__dict__` and the copy and pickle hooks) are no longer forwarded to the wrapped tensor, so+`copy.deepcopy` of a `TensorWrapper`, `Vector2`, `Vector3` or `Scalar` keeps the class instead of returning a plain+`Tensor`, and a deep-copied `Hyperplane` keeps its `Vector3` normal. Pickling and `torch.save` of a wrapper no longer+fail after a torch function that pickle cannot store: after `tensor ** w` they raised `PicklingError`, and after+`torch.unique(w)` `AttributeError`. The copied and pickled state now keeps only the `used_calls` entries pickle can+store, and a `copy.copy` gets its own `used_attrs` and `used_calls` sets instead of sharing them with the original.+`TensorWrapper` also gains the operators it lacked: the reflected `2 / w` and `2 // w`; `%`, `**`, `@`, `&`, `|`, `^`,+`<<` and `>>` in their forward and reflected forms (`w % 2`, `2 % w`); unary `+`, `abs(w)` and `~w`; and `float(w)`,+`complex(w)` and `operator.index(w)`. The unary operators and the conversions used to raise `TypeError`, and so did the+binary operators with a Python number or another wrapper as the other operand; with a tensor operand the binary+operators already worked through `__torch_function__`. An operator returns what the wrapped tensor's operator returns,+wrapped in the class of the left operand when that is a wrapper and otherwise in the class of the right operand.diff --git a/kornia/core/tensor_wrapper.py b/kornia/core/tensor_wrapper.pyindex b21e0cb62..81d42e228 100644--- a/kornia/core/tensor_wrapper.py+++ b/kornia/core/tensor_wrapper.py@@ -18,7 +18,8 @@from __future__ import annotationsimport collections.abc-from typing import Any, Optional+import pickle+from typing import Any, Optional, Selfimport torchfrom torch import Tensor@@ -43,6 +44,15 @@ def _wrap(v: Any, cls: type[TensorWrapper]) -> Any:return cls(v) if isinstance(v, Tensor) else v+def _is_picklable(obj: Any) -> bool:+ """Return whether pickle can store ``obj``."""+ try:+ pickle.dumps(obj)+ except (pickle.PicklingError, AttributeError, TypeError):+ return False+ return True++def _unwrap(v: Any) -> Any:"""Unwrap nested type.@@ -65,6 +75,26 @@ class TensorWrapper:tracking which attributes and functions are accessed. Useful for debuggingand understanding tensor usage patterns.+ Convention:+ - An attribute the wrapper does not define is looked up on the wrapped tensor, and a tensor value is+ wrapped in the wrapper's class. The wrapper's own names are never forwarded: its slots, ``data``,+ ``__dict__`` and the copy and pickle hooks. So ``copy.copy``, ``copy.deepcopy`` and pickle return the+ wrapper's class, and ``torch.compile`` can trace a function that builds a wrapper. The array and DLPack+ hooks are forwarded, so ``numpy.asarray(w)`` and ``torch.from_dlpack(w)`` convert the wrapped tensor.+ - Every arithmetic, bitwise and comparison operator (``+ - * / // % ** @ & | ^ << >>``,+ ``== != < <= > >=``, unary ``-``, ``+``, ``abs`` and ``~``) computes the wrapped tensor's result and+ wraps it in the class of the left operand when that is a wrapper (``w + x``), and otherwise in the class+ of the right operand (``2 / w``, ``t + w``). A comparison whose right operand is an instance of a subclass+ of the left operand's wrapper class takes the subclass, because Python tries the subclass's reflected+ comparison first.+ - An in-place operator (``+=``, ``-=``, ``*=``, ``/=``, ``//=``, ``%=``, ``**=``, ``&=``, ``|=``, ``^=``,+ ``<<=``, ``>>=``) updates the wrapped tensor in place and returns the same wrapper, so an alias sees the+ change. The wrapper does not copy the tensor it is built from, so the update also changes that tensor,+ and it raises where the tensor's in-place operator raises: on a leaf that requires grad, or when the+ result would change the dtype or the shape. ``w @= x`` rebinds ``w`` to ``w @ x``, as ``@=`` does for+ a tensor.+ - ``bool``, ``int``, ``float``, ``complex``, ``operator.index`` and ``len`` return Python values.+Attributes:_data: The underlying PyTorch tensor.used_attrs: Set of attribute names that have been accessed.@@ -73,6 +103,25 @@ class TensorWrapper:__slots__ = ("_data", "used_attrs", "used_calls")+ # Names ``__getattr__`` never forwards to the wrapped tensor: forwarding a slot recurses on an instance whose+ # slots are not set yet (Dynamo builds one while it traces the constructor, and looks up ``__dict__`` on it),+ # and a forwarded copy or pickle hook copies the tensor instead of the wrapper.+ _OWNED_NAMES = frozenset(+ {+ *__slots__,+ "data",+ "__dict__",+ "__copy__",+ "__deepcopy__",+ "__getnewargs__",+ "__getnewargs_ex__",+ "__getstate__",+ "__reduce__",+ "__reduce_ex__",+ "__setstate__",+ }+ )+def __init__(self, data: Tensor) -> None:"""Initialize TensorWrapper with a PyTorch tensor.@@ -101,11 +150,17 @@ class TensorWrapper:return self._datadef __getstate__(self) -> dict[str, Any]:- """Support for pickle serialization."""+ """Support for pickle serialization.++ Both tracking sets are copied, so a ``copy.copy`` tracks its own usage. ``used_calls`` keeps only the+ functions pickle can store. A few torch functions cannot be pickled, such as ``torch.unique`` or the+ ``Tensor.__pow__`` that ``tensor ** wrapper`` dispatches, and they are left out of the state, so pickling,+ ``torch.save`` and ``copy.deepcopy`` still work after them.+ """return {"_data": self._data,- "used_attrs": self.used_attrs,- "used_calls": self.used_calls,+ "used_attrs": set(self.used_attrs),+ "used_calls": {func for func in self.used_calls if _is_picklable(func)},}def __setstate__(self, state: dict[str, Any]) -> None:@@ -120,9 +175,8 @@ class TensorWrapper:def __getattr__(self, name: str) -> Any:"""Get attribute from underlying tensor."""- # Handle special 'data' property- if name == "data":- return self._data+ if name in TensorWrapper._OWNED_NAMES:+ raise AttributeError(f"'{type(self).__name__}' object has no attribute '{name}'")# Track attribute usageself.used_attrs.add(name)@@ -209,10 +263,135 @@ class TensorWrapper:"""True division operation."""return self.__binary_op__(torch.true_divide, other)+ def __rtruediv__(self, other: Any) -> TensorWrapper:+ """Right-side true division operation."""+ return self.__binary_op__(Tensor.__rtruediv__, other)+def __floordiv__(self, other: Any) -> TensorWrapper:"""Floor division operation."""return self.__binary_op__(torch.floor_divide, other)+ def __rfloordiv__(self, other: Any) -> TensorWrapper:+ """Right-side floor division operation."""+ return self.__binary_op__(Tensor.__rfloordiv__, other)++ def __mod__(self, other: Any) -> TensorWrapper:+ """Remainder operation."""+ return self.__binary_op__(Tensor.__mod__, other)++ def __rmod__(self, other: Any) -> TensorWrapper:+ """Right-side remainder operation."""+ return self.__binary_op__(Tensor.__rmod__, other)++ def __pow__(self, other: Any) -> TensorWrapper:+ """Power operation."""+ # ``torch.pow`` rather than ``Tensor.__pow__``, which pickle cannot store in ``used_calls``. Like+ # ``Tensor.__pow__``, an operand ``torch.pow`` rejects returns NotImplemented, so Python tries its ``__rpow__``.+ try:+ return self.__binary_op__(torch.pow, other)+ except TypeError:+ return NotImplemented++ def __rpow__(self, other: Any) -> TensorWrapper:+ """Right-side power operation."""+ return self.__binary_op__(Tensor.__rpow__, other)++ def __matmul__(self, other: Any) -> TensorWrapper:+ """Matrix multiplication operation."""+ return self.__binary_op__(Tensor.__matmul__, other)++ def __rmatmul__(self, other: Any) -> TensorWrapper:+ """Right-side matrix multiplication operation."""+ return self.__binary_op__(Tensor.__rmatmul__, other)++ def __and__(self, other: Any) -> TensorWrapper:+ """Bitwise and operation."""+ return self.__binary_op__(Tensor.__and__, other)++ def __rand__(self, other: Any) -> TensorWrapper:+ """Right-side bitwise and operation."""+ return self.__binary_op__(Tensor.__rand__, other)++ def __or__(self, other: Any) -> TensorWrapper:+ """Bitwise or operation."""+ return self.__binary_op__(Tensor.__or__, other)++ def __ror__(self, other: Any) -> TensorWrapper:+ """Right-side bitwise or operation."""+ return self.__binary_op__(Tensor.__ror__, other)++ def __xor__(self, other: Any) -> TensorWrapper:+ """Bitwise exclusive or operation."""+ return self.__binary_op__(Tensor.__xor__, other)++ def __rxor__(self, other: Any) -> TensorWrapper:+ """Right-side bitwise exclusive or operation."""+ return self.__binary_op__(Tensor.__rxor__, other)++ def __lshift__(self, other: Any) -> TensorWrapper:+ """Left shift operation."""+ return self.__binary_op__(Tensor.__lshift__, other)++ def __rlshift__(self, other: Any) -> TensorWrapper:+ """Right-side left shift operation."""+ return self.__binary_op__(Tensor.__rlshift__, other)++ def __rshift__(self, other: Any) -> TensorWrapper:+ """Right shift operation."""+ return self.__binary_op__(Tensor.__rshift__, other)++ def __rrshift__(self, other: Any) -> TensorWrapper:+ """Right-side right shift operation."""+ return self.__binary_op__(Tensor.__rrshift__, other)++ def __iadd__(self, other: Any) -> Self:+ """In-place add operation."""+ return self.__inplace_op__(Tensor.__iadd__, other)++ def __isub__(self, other: Any) -> Self:+ """In-place subtract operation."""+ return self.__inplace_op__(Tensor.__isub__, other)++ def __imul__(self, other: Any) -> Self:+ """In-place multiply operation."""+ return self.__inplace_op__(Tensor.__imul__, other)++ def __itruediv__(self, other: Any) -> Self:+ """In-place true division operation."""+ return self.__inplace_op__(Tensor.__itruediv__, other)++ def __ifloordiv__(self, other: Any) -> Self:+ """In-place floor division operation."""+ return self.__inplace_op__(Tensor.__ifloordiv__, other)++ def __imod__(self, other: Any) -> Self:+ """In-place remainder operation."""+ return self.__inplace_op__(Tensor.__imod__, other)++ def __ipow__(self, other: Any) -> Self:+ """In-place power operation."""+ return self.__inplace_op__(Tensor.pow_, other)++ def __iand__(self, other: Any) -> Self:+ """In-place bitwise and operation."""+ return self.__inplace_op__(Tensor.__iand__, other)++ def __ior__(self, other: Any) -> Self:+ """In-place bitwise or operation."""+ return self.__inplace_op__(Tensor.__ior__, other)++ def __ixor__(self, other: Any) -> Self:+ """In-place bitwise exclusive or operation."""+ return self.__inplace_op__(Tensor.__ixor__, other)++ def __ilshift__(self, other: Any) -> Self:+ """In-place left shift operation."""+ return self.__inplace_op__(Tensor.__ilshift__, other)++ def __irshift__(self, other: Any) -> Self:+ """In-place right shift operation."""+ return self.__inplace_op__(Tensor.__irshift__, other)+def __ge__(self, other: Any) -> TensorWrapper:"""Greater than or equal comparison."""return self.__binary_op__(torch.ge, other)@@ -245,10 +424,34 @@ class TensorWrapper:"""Convert to integer (unwrapped)."""return int(self._data)+ def __float__(self) -> float:+ """Convert to float (unwrapped)."""+ return float(self._data)++ def __complex__(self) -> complex:+ """Convert to complex (unwrapped)."""+ return complex(self._data)++ def __index__(self) -> int:+ """Convert to an index (unwrapped)."""+ return self._data.__index__()+def __neg__(self) -> TensorWrapper:"""Negation operation."""return self.__unary_op__(torch.neg)+ def __pos__(self) -> TensorWrapper:+ """Unary plus operation."""+ return self.__unary_op__(Tensor.__pos__)++ def __abs__(self) -> TensorWrapper:+ """Absolute value operation."""+ return self.__unary_op__(Tensor.__abs__)++ def __invert__(self) -> TensorWrapper:+ """Bitwise not operation."""+ return self.__unary_op__(Tensor.__invert__)+def __len__(self) -> int:"""Return length of tensor."""return len(self._data)@@ -270,6 +473,20 @@ class TensorWrapper:args = (self, other)return self.__torch_function__(func, (type(self),), args)+ def __inplace_op__(self, func: Any, other: Any) -> Self:+ """Helper for in-place operations.++ Args:+ func: The in-place tensor operator to call, such as ``Tensor.__iadd__``.+ other: The other operand.++ Returns:+ This wrapper, whose tensor ``func`` updated in place. Whatever ``func`` raises propagates.+ """+ self.used_calls.add(func)+ func(self._data, _unwrap(other))+ return self+def __unary_op__(self, func: Any) -> TensorWrapper:"""Helper for unary operations.diff --git a/kornia/geometry/vector.py b/kornia/geometry/vector.pyindex fd0479ed2..6096317be 100644--- a/kornia/geometry/vector.py+++ b/kornia/geometry/vector.py@@ -48,10 +48,14 @@ class Vector3(TensorWrapper):return a :class:`Scalar` of that shape (for :meth:`dot`, the two operands' broadcast leading shape).- :meth:`random` draws vectors uniformly in the unit cube from torch's global generator, so every vectorlies in the first octant: it is not a random direction.- - Known defect: the returned type depends on the call path (``copy.deepcopy(v)`` and ``v.clone()`` are- plain tensors, while a torch function rewraps its result as a ``Vector3``, so ``torch.linalg.norm(v,- dim=-1)`` raises unless its result happens to end in 3), and a tuple index such as ``v[..., 0]`` raises- (`#5022 <https://github.com/kornia/kornia/issues/5022>`_).+ - ``copy.deepcopy``, ``copy.copy`` and pickle return a ``Vector3``. An in-place operator such as ``v += 1``+ updates the wrapped tensor, so an alias and the tensor the vector was built from see the change; the+ operator rules are those of :class:`~kornia.core.TensorWrapper`.+ - Known defect: the returned type depends on the call path (``v.clone()`` is a plain tensor, while a torch+ function rewraps its result as a ``Vector3``, so ``torch.linalg.norm(v, dim=-1)`` raises unless its+ result happens to end in 3), an operator with a :class:`Scalar` on the left returns a ``Scalar`` that+ holds the vectors (``s * v``, while ``v * s`` is a ``Vector3``), and a tuple index such as ``v[..., 0]``+ raises (`#5022 <https://github.com/kornia/kornia/issues/5022>`_)."""def __init__(self, vector: torch.Tensor) -> None:diff --git a/tests/core/test_tensor_wrapper.py b/tests/core/test_tensor_wrapper.pyindex f9e983ef4..12b1d21dc 100644--- a/tests/core/test_tensor_wrapper.py+++ b/tests/core/test_tensor_wrapper.py@@ -15,13 +15,18 @@# limitations under the License.#+import copy+import operator+import pickle++import numpy as npimport pytestimport torchfrom kornia.core.exceptions import TypeCheckErrorfrom kornia.core.tensor_wrapper import TensorWrapper, _unwrap, _wrap-from testing.base import BaseTester+from testing.base import BaseTester, dynamo_is_availableclass TestTensorWrapper(BaseTester):@@ -278,6 +283,395 @@ class TestTensorWrapper(BaseTester):def test_module(self, device, dtype):pass- @pytest.mark.skip(reason="not implemented yet")def test_gradcheck(self, device):- pass+ # No entry is an integer, where ``% 1.0`` jumps.+ x = torch.tensor([[0.5, 1.25, 2.5], [1.75, 3.5, 0.75]], device=device)++ def fn(t):+ w = TensorWrapper(t)+ return (2 / w + w**2 - abs(-w) % 1.0 + (w @ w.T).sum()).unwrap()++ self.gradcheck(fn, (x,))++ def inplace_fn(t):+ w = TensorWrapper(t * 1)+ w *= t+ w += 1+ w **= 2+ return (2 / w).unwrap()++ self.gradcheck(inplace_fn, (x,))++ def test_dynamo(self, device, dtype, torch_optimizer):+ x = torch.tensor([[0.5, 1.5, 2.0], [1.0, 3.0, 0.75]], device=device, dtype=dtype)+ compiled = torch_optimizer(_build_and_update)+ self.assert_close(compiled(x), _build_and_update(x))+++def _build_and_update(t):+ w = TensorWrapper(t.clone())+ w += 1+ w *= 2+ return (2 / w + w**2 - abs(w) % 1.5).unwrap()+++_PICKLE_FLOAT_CASES_WITH_IDS = [+ ("add", True, lambda w, x: w + x),+ ("radd", True, lambda w, x: 2 + w),+ ("sub", True, lambda w, x: w - x),+ ("rsub", True, lambda w, x: 2 - w),+ ("mul", True, lambda w, x: w * x),+ ("rmul", True, lambda w, x: 2 * w),+ ("truediv", True, lambda w, x: w / x),+ ("rtruediv", True, lambda w, x: 2 / w),+ ("floordiv", True, lambda w, x: w // x),+ ("rfloordiv", True, lambda w, x: 2 // w),+ ("mod", True, lambda w, x: w % x),+ ("rmod", True, lambda w, x: 2 % w),+ ("pow", True, lambda w, x: w**2),+ ("pow_tensor", True, lambda w, x: w**x),+ ("rpow", True, lambda w, x: 2**w),+ ("matmul", True, lambda w, x: w @ x.T),+ ("rmatmul", True, lambda w, x: w.__rmatmul__(x.T)),+ ("lt", True, lambda w, x: w < x),+ ("le", True, lambda w, x: w <= x),+ ("gt", True, lambda w, x: w > x),+ ("ge", True, lambda w, x: w >= x),+ ("eq", True, lambda w, x: w == x),+ ("ne", True, lambda w, x: w != x),+ ("neg", True, lambda w, x: -w),+ ("pos", True, lambda w, x: +w),+ ("abs", True, lambda w, x: abs(w)),+ ("iadd", True, operator.iadd),+ ("isub", True, operator.isub),+ ("imul", True, operator.imul),+ ("itruediv", True, operator.itruediv),+ ("ifloordiv", True, operator.ifloordiv),+ ("imod", True, operator.imod),+ ("ipow", True, operator.ipow),+ ("tensor_pow", False, lambda w, x: x**w),+ ("torch_unique", False, lambda w, x: torch.unique(w)),+]+_PICKLE_FLOAT_CASES = [(own, fn) for _, own, fn in _PICKLE_FLOAT_CASES_WITH_IDS]+_PICKLE_INT_CASES_WITH_IDS = [+ ("and", True, lambda w, x: w & x),+ ("rand", True, lambda w, x: 1 & w),+ ("or", True, lambda w, x: w | x),+ ("ror", True, lambda w, x: 1 | w),+ ("xor", True, lambda w, x: w ^ x),+ ("rxor", True, lambda w, x: 1 ^ w),+ ("lshift", True, lambda w, x: w << x),+ ("rlshift", True, lambda w, x: 1 << w),+ ("rshift", True, lambda w, x: w >> x),+ ("rrshift", True, lambda w, x: 64 >> w),+ ("invert", True, lambda w, x: ~w),+ ("iand", True, operator.iand),+ ("ior", True, operator.ior),+ ("ixor", True, operator.ixor),+ ("ilshift", True, operator.ilshift),+ ("irshift", True, operator.irshift),+]+_PICKLE_INT_CASES = [(own, fn) for _, own, fn in _PICKLE_INT_CASES_WITH_IDS]+++class TestTensorWrapperProtocol(BaseTester):+ """Attribute ownership, copying and the operator protocol (#5189, #5190)."""++ def test_uninitialized_instance_raises_attribute_error(self):+ # An instance made by ``__new__`` alone has no slots set, and Dynamo looks up ``__dict__`` on one while it+ # traces the constructor: every lookup must raise AttributeError instead of recursing through __getattr__.+ blank = TensorWrapper.__new__(TensorWrapper)+ for name in ("anything", "shape", "data", "_data", "used_attrs", "used_calls", "__dict__", "__deepcopy__"):+ with pytest.raises(AttributeError):+ getattr(blank, name)++ def test_owned_names_are_not_forwarded(self, device, dtype):+ wrapper = TensorWrapper(torch.zeros(2, device=device, dtype=dtype))+ for name in ("__dict__", "__copy__", "__deepcopy__", "__getnewargs__", "__getnewargs_ex__"):+ assert not hasattr(wrapper, name)+ assert wrapper.used_attrs == set()++ @pytest.mark.skipif(not dynamo_is_available(), reason="no Dynamo on this torch/python pair")+ @pytest.mark.parametrize(+ "fn, fullgraph",+ [+ (lambda t: TensorWrapper(t).data, True),+ (lambda t: TensorWrapper(t).unwrap(), True),+ (lambda t: (TensorWrapper(t) + 1).unwrap(), True),+ (_build_and_update, True),+ # torch 2.5.1's Dynamo breaks the graph here, cleanly: it does not send unary ``-`` or ``~``, a+ # comparison, ``@`` or a binary or in-place operator with a tensor operand to a user class, and it cannot+ # trace a torch function on a wrapper, ``__getitem__`` or a forwarded method.+ (lambda t: torch.add(TensorWrapper(t), 1).unwrap(), False),+ (lambda t: TensorWrapper(t)[0].unwrap(), False),+ (lambda t: TensorWrapper(t).sum(), False),+ (lambda t: (TensorWrapper(t) @ TensorWrapper(t.T)).unwrap(), False),+ ],+ ids=["data", "unwrap", "add", "inplace_and_reflected", "torch_add", "getitem", "method", "matmul"],+ )+ def test_eager_backend_traces_a_function_that_builds_a_wrapper(self, device, dtype, fn, fullgraph):+ # The eager backend keeps this in the ordinary jobs; test_dynamo covers the optimizer backends.+ torch._dynamo.reset()+ x = torch.tensor([[0.5, 1.5, 2.0], [1.0, 3.0, 0.75]], device=device, dtype=dtype)+ out = torch.compile(fn, backend="eager", fullgraph=fullgraph)(x)+ assert type(out) is torch.Tensor+ self.assert_close(out, fn(x))++ def test_deepcopy_copy_and_pickle_keep_the_class(self, device, dtype, tmp_path):+ data = torch.tensor([[0.3, -1.2, 2.5]], device=device, dtype=dtype, requires_grad=True)+ wrapper = TensorWrapper(data)+ _ = wrapper.shape+ _ = wrapper + 1++ deep = copy.deepcopy(wrapper)+ assert type(deep) is TensorWrapper+ self.assert_close(deep.data, data, rtol=0, atol=0)+ assert deep.data.data_ptr() != data.data_ptr()+ assert deep.used_attrs == {"shape"}+ assert deep.used_attrs is not wrapper.used_attrs++ shallow = copy.copy(wrapper)+ assert type(shallow) is TensorWrapper+ assert shallow.data is data+ # The copy tracks its own usage: both sets are copied, neither is shared with the original.+ assert shallow.used_attrs == wrapper.used_attrs+ assert shallow.used_attrs is not wrapper.used_attrs+ assert shallow.used_calls == wrapper.used_calls == {torch.add}+ assert shallow.used_calls is not wrapper.used_calls++ restored = pickle.loads(pickle.dumps(wrapper)) # noqa: S301+ torch.save(wrapper, tmp_path / "wrapper.pt")+ loaded = torch.load(tmp_path / "wrapper.pt", weights_only=False)+ for copied in (deep, restored, loaded):+ assert type(copied) is TensorWrapper+ self.assert_close(copied.data, data, rtol=0, atol=0)+ assert copied.data.requires_grad+ assert copied.data.is_leaf+ assert copied.data.device == data.device++ def test_array_protocols_still_reach_the_tensor(self):+ # Only the wrapper's own names stop at __getattr__: the DLPack and array-interface dunders are still+ # forwarded, so converting a wrapper keeps going through the wrapped tensor's buffer.+ data = torch.tensor([[0.3, -1.2, 2.5]])+ wrapper = TensorWrapper(data)+ self.assert_close(torch.from_dlpack(wrapper), data, rtol=0, atol=0)+ array = np.asarray(wrapper)+ assert array.dtype == np.float32+ assert array.tolist() == data.tolist()++ def test_pow_defers_to_the_other_operand_as_the_tensor_does(self, device, dtype):+ # For an operand torch.pow cannot take, Tensor.__pow__ returns NotImplemented, so Python tries the other+ # operand's __rpow__; ``w ** x`` does the same, like the other forward operators (``w % x``, ``w @ x``).+ class Exponent:+ def __rpow__(self, base):+ return "Exponent.__rpow__"++ data = torch.tensor([[1.0, 2.0, 3.0]], device=device, dtype=dtype)+ wrapper = TensorWrapper(data.clone())+ assert data ** Exponent() == "Exponent.__rpow__"+ assert wrapper ** Exponent() == "Exponent.__rpow__"+ with pytest.raises(TypeError, match="unsupported operand"):+ _ = wrapper ** "2"++ @pytest.mark.filterwarnings("ignore:__array_wrap__ must accept:DeprecationWarning")+ def test_pow_with_a_numpy_operand_matches_the_tensor(self):+ data = torch.tensor([[1.0, 2.0, 3.0]])+ for exponent in (np.array(2.0), np.array([[2.0, 0.5, 3.0]])):+ expected = data**exponent+ out = TensorWrapper(data.clone()) ** exponent+ assert type(out) is type(expected)+ self.assert_close(out, expected, rtol=0, atol=0)++ def test_result_class_with_a_wrapper_subclass_on_the_right(self, device, dtype):+ # Arithmetic takes the left wrapper's class; a comparison takes the right operand's subclass, because Python+ # tries a subclass's reflected comparison first.+ class Sub(TensorWrapper):+ pass++ a = torch.tensor([1.0, 2.0, 4.0], device=device, dtype=dtype)+ b = torch.tensor([2.0, 2.0, 3.0], device=device, dtype=dtype)+ for op in (operator.add, operator.mul):+ assert type(op(TensorWrapper(a), Sub(b))) is TensorWrapper+ for op in (operator.eq, operator.ne, operator.lt, operator.le, operator.gt, operator.ge):+ out = op(TensorWrapper(a), Sub(b))+ assert type(out) is Sub+ assert torch.equal(out.data, op(a, b))++ @pytest.mark.parametrize(+ "op",+ [operator.add, operator.sub, operator.mul, operator.truediv, operator.floordiv, operator.mod, operator.pow],+ )+ def test_arithmetic_operators_match_the_tensor(self, device, dtype, op):+ a = torch.tensor([[1.0, 2.0, 4.0], [0.5, 3.0, 5.0]], device=device, dtype=dtype)+ b = torch.tensor([[2.0, 0.5, 3.0], [1.5, 2.0, 0.25]], device=device, dtype=dtype)+ wa, wb = TensorWrapper(a), TensorWrapper(b)+ for lhs, rhs, expected in [+ (wa, wb, op(a, b)),+ (wa, b, op(a, b)),+ (a, wb, op(a, b)),+ (wa, 3, op(a, 3)),+ (3, wa, op(3, a)),+ ]:+ out = op(lhs, rhs)+ assert type(out) is TensorWrapper+ self.assert_close(out.data, expected, rtol=0, atol=0)++ def test_matmul_unary_and_conversions_match_the_tensor(self, device, dtype):+ a = torch.tensor([[1.0, -2.0, 4.0], [0.5, 3.0, -5.0]], device=device, dtype=dtype)+ wa = TensorWrapper(a)+ m = torch.tensor([[1.0, 2.0], [0.5, -1.0]], device=device, dtype=dtype)+ for out, expected in [+ (wa @ wa.T, a @ a.T),+ (wa @ TensorWrapper(a.T), a @ a.T),+ (a.T @ wa, a.T @ a),+ (wa.__rmatmul__(m), m @ a),+ (abs(wa), abs(a)),+ (+wa, +a),+ (-wa, -a),+ ]:+ assert type(out) is TensorWrapper+ self.assert_close(out.data, expected, rtol=0, atol=0)++ element = TensorWrapper(a[1, 1])+ assert float(element) == float(a[1, 1])+ assert complex(element) == complex(a[1, 1])+ assert int(element) == int(a[1, 1])+ index = TensorWrapper(torch.tensor(2, device=device))+ assert operator.index(index) == 2+ assert [10, 20, 30][index] == 30++ @pytest.mark.parametrize(+ "op",+ [operator.and_, operator.or_, operator.xor, operator.lshift, operator.rshift],+ )+ def test_bitwise_operators_match_the_tensor(self, device, op):+ a = torch.tensor([12, 5, 3], device=device)+ b = torch.tensor([10, 1, 2], device=device)+ wa, wb = TensorWrapper(a), TensorWrapper(b)+ for lhs, rhs, expected in [(wa, wb, op(a, b)), (wa, 1, op(a, 1)), (1, wa, op(1, a))]:+ out = op(lhs, rhs)+ assert type(out) is TensorWrapper+ self.assert_close(out.data, expected, rtol=0, atol=0)++ mask = TensorWrapper(a > 4)+ out = ~mask & (wa < 13)+ assert type(out) is TensorWrapper+ assert out.data.tolist() == (~(a > 4) & (a < 13)).tolist()++ @pytest.mark.parametrize(+ "op, iop",+ [+ (operator.add, operator.iadd),+ (operator.sub, operator.isub),+ (operator.mul, operator.imul),+ (operator.truediv, operator.itruediv),+ (operator.floordiv, operator.ifloordiv),+ (operator.mod, operator.imod),+ (operator.pow, operator.ipow),+ ],+ )+ def test_inplace_operators_update_the_wrapped_tensor(self, device, dtype, op, iop):+ a = torch.tensor([[1.0, 2.0, 4.0], [0.5, 3.0, 5.0]], device=device, dtype=dtype)+ for other in (3, torch.full_like(a, 2.0), TensorWrapper(torch.full_like(a, 2.0))):+ data = a.clone()+ wrapper = TensorWrapper(data)+ alias = wrapper+ out = iop(wrapper, other)+ assert out is alias+ assert out.data is data+ self.assert_close(alias.data, op(a, _unwrap(other)), rtol=0, atol=0)++ @pytest.mark.parametrize(+ "op, iop",+ [+ (operator.and_, operator.iand),+ (operator.or_, operator.ior),+ (operator.xor, operator.ixor),+ (operator.lshift, operator.ilshift),+ (operator.rshift, operator.irshift),+ ],+ )+ def test_inplace_bitwise_operators_update_the_wrapped_tensor(self, device, op, iop):+ a = torch.tensor([12, 5, 3], device=device)+ data = a.clone()+ wrapper = TensorWrapper(data)+ alias = wrapper+ out = iop(wrapper, 1)+ assert out is alias+ assert out.data is data+ assert alias.data.tolist() == op(a, 1).tolist()++ def test_inplace_matmul_rebinds_as_on_the_tensor(self, device, dtype):+ # A tensor has no ``__imatmul__``, so ``t @= m`` rebinds ``t`` to ``t @ m``; the wrapper does the same.+ a = torch.tensor([[1.0, 2.0], [0.5, 3.0]], device=device, dtype=dtype)+ m = torch.tensor([[0.0, 1.0], [1.0, 0.0]], device=device, dtype=dtype)+ tensor = a.clone()+ tensor_alias = tensor+ tensor @= m+ assert tensor is not tensor_alias+ wrapper = TensorWrapper(a.clone())+ alias = wrapper+ wrapper @= m+ assert wrapper is not alias+ assert type(wrapper) is TensorWrapper+ self.assert_close(wrapper.data, a @ m, rtol=0, atol=0)+ self.assert_close(alias.data, a, rtol=0, atol=0)++ def test_inplace_operators_raise_where_the_tensor_raises(self, device, dtype):+ # Wrapping does not copy, so an in-place operator writes into the caller's tensor, and it raises where the+ # tensor's in-place operator raises: on a leaf that requires grad, and for a dtype or shape change.+ leaf = torch.ones(2, 3, device=device, dtype=dtype, requires_grad=True)+ integer = torch.tensor([1, 2, 3], device=device)+ for target in (leaf, TensorWrapper(leaf)):+ with pytest.raises(RuntimeError, match="leaf Variable"):+ target += 1+ for target in (integer.clone(), TensorWrapper(integer.clone())):+ with pytest.raises(RuntimeError, match="can't be cast"):+ target /= 2+ for target in (leaf.detach().clone(), TensorWrapper(leaf.detach().clone())):+ with pytest.raises(RuntimeError):+ target += torch.ones(4, 2, 3, device=device, dtype=dtype)++ caller = leaf.detach().clone()+ wrapper = TensorWrapper(caller)+ wrapper += 1+ self.assert_close(caller, torch.full_like(caller, 2.0), rtol=0, atol=0)++ @pytest.mark.parametrize(+ "own, fn",+ _PICKLE_FLOAT_CASES,+ ids=[label for label, _, _ in _PICKLE_FLOAT_CASES_WITH_IDS],+ )+ def test_pickle_and_torch_save_after_each_operator(self, device, dtype, tmp_path, own, fn):+ w = TensorWrapper(torch.tensor([[1.0, 2.0, 4.0], [0.5, 3.0, 5.0]], device=device, dtype=dtype))+ x = torch.tensor([[2.0, 0.5, 3.0], [1.5, 2.0, 0.25]], device=device, dtype=dtype)+ fn(w, x)+ self._check_round_trips(w, own, tmp_path)++ @pytest.mark.parametrize(+ "own, fn",+ _PICKLE_INT_CASES,+ ids=[label for label, _, _ in _PICKLE_INT_CASES_WITH_IDS],+ )+ def test_pickle_and_torch_save_after_each_integer_operator(self, device, tmp_path, own, fn):+ w = TensorWrapper(torch.tensor([12, 5, 3], device=device))+ x = torch.tensor([10, 1, 2], device=device)+ fn(w, x)+ self._check_round_trips(w, own, tmp_path)++ def _check_round_trips(self, w, own, tmp_path):+ assert len(w.used_calls) > 0+ torch.save(w, tmp_path / "wrapper.pt")+ for restored in (+ pickle.loads(pickle.dumps(w)), # noqa: S301+ torch.load(tmp_path / "wrapper.pt", weights_only=False),+ ):+ assert type(restored) is TensorWrapper+ self.assert_close(restored.data, w.data, rtol=0, atol=0)+ assert restored.used_attrs == w.used_attrs+ # The wrapper's own operators record picklable functions; a torch function that pickle cannot store+ # (``torch.unique``, or the ``Tensor.__pow__`` that ``t ** w`` dispatches) is left out of the state.+ if own:+ assert restored.used_calls == w.used_calls+ else:+ assert restored.used_calls < w.used_callsdiff --git a/tests/geometry/test_vector.py b/tests/geometry/test_vector.pyindex b512b2bed..da9279c80 100644--- a/tests/geometry/test_vector.py+++ b/tests/geometry/test_vector.py@@ -16,6 +16,7 @@#import copy+import pickleimport pytestimport torch@@ -24,7 +25,7 @@ from kornia.core.check import BaseErrorfrom kornia.geometry.plane import Hyperplanefrom kornia.geometry.vector import Scalar, Vector2, Vector3-from testing.base import BaseTester+from testing.base import BaseTester, dynamo_is_availableclass TestVector3(BaseTester):@@ -293,9 +294,9 @@ class TestConventionsVector(BaseTester):expected_squared_norm = [5.0, 41.0] if dim == 2 else [14.0, 77.0]self.assert_close(squared_norm.data, torch.tensor(expected_squared_norm, device=device, dtype=dtype))- def test_wart_vector3_call_path_type_split_5022(self, device, dtype):- # Wart pin (#5022): deepcopy and tensor methods lose the wrapper, while torch functions rewrap their result.- # A shape-changing torch function then fails Vector3 validation. Each part flips when its path is fixed.+ def test_convention_vector_deepcopy_keeps_the_class_5022(self, device, dtype):+ # copy.deepcopy, copy.copy and pickle all return the wrapper's own class, so a deep-copied Hyperplane keeps+ # a Vector3 normal and a Scalar offset and measures the same distances.wrapped = (Vector3(torch.tensor([[0.3, -1.2, 2.5]], device=device, dtype=dtype)),Vector2(torch.tensor([[0.3, -1.2]], device=device, dtype=dtype)),@@ -304,8 +305,55 @@ class TestConventionsVector(BaseTester):for obj in wrapped:assert type(copy.copy(obj)) is type(obj)deep = copy.deepcopy(obj)- assert type(deep) is torch.Tensor- self.assert_close(deep, obj.data)+ assert type(deep) is type(obj)+ self.assert_close(deep.data, obj.data, rtol=0, atol=0)+ assert deep.data.data_ptr() != obj.data.data_ptr()+ assert type(pickle.loads(pickle.dumps(obj))) is type(obj) # noqa: S301++ normal = Vector3(torch.tensor([2.0, 1.0, -2.0], device=device, dtype=dtype) / 3.0)+ point = Vector3(torch.tensor([1.0, 2.0, 0.5], device=device, dtype=dtype))+ plane = Hyperplane.from_vector(normal, point)+ copied = copy.deepcopy(plane)+ assert type(copied.normal) is Vector3+ assert type(copied.offset) is Scalar+ self.assert_close(copied.normal.x, plane.normal.x, rtol=0, atol=0)+ query = Vector3(torch.tensor([[0.0, 0.0, 1.0], [2.0, -1.0, 0.5]], device=device, dtype=dtype))+ self.assert_close(copied.signed_distance(query).data, plane.signed_distance(query).data, rtol=0, atol=0)++ def test_convention_vector_operators_keep_the_class(self, device, dtype):+ # Reflected and in-place operators follow TensorWrapper's rule: the result is wrapped in the class of the+ # operand that handled it, and an in-place operator updates the wrapped tensor, so an alias sees it.+ data = torch.tensor([[0.5, 1.5, 2.0], [1.0, 3.0, 0.75]], device=device, dtype=dtype)+ v = Vector3(data.clone())+ reflected = 2 / v+ assert type(reflected) is Vector3+ self.assert_close(reflected.data, 2 / data, rtol=0, atol=0)+ alias = v+ v += 1+ assert v is alias+ assert type(v) is Vector3+ self.assert_close(alias.data, data + 1, rtol=0, atol=0)++ @pytest.mark.skipif(not dynamo_is_available(), reason="no Dynamo on this torch/python pair")+ def test_eager_backend_traces_vector_arithmetic(self, device, dtype):+ def fn(t):+ v = Vector3(t.clone())+ v += 1+ return (2 / v + v**2 + Vector3(t)).data++ torch._dynamo.reset()+ data = torch.tensor([[0.5, 1.5, 2.0], [1.0, 3.0, 0.75]], device=device, dtype=dtype)+ self.assert_close(torch.compile(fn, backend="eager", fullgraph=True)(data), fn(data))++ def test_wart_vector3_call_path_type_split_5022(self, device, dtype):+ # Wart pin (#5022): tensor methods lose the wrapper, while torch functions rewrap their result. A+ # shape-changing torch function then fails Vector3 validation. Each part flips when its path is fixed.+ wrapped = (+ Vector3(torch.tensor([[0.3, -1.2, 2.5]], device=device, dtype=dtype)),+ Vector2(torch.tensor([[0.3, -1.2]], device=device, dtype=dtype)),+ Scalar(torch.tensor([2.5], device=device, dtype=dtype)),+ )+ for obj in wrapped:assert type(obj.clone()) is torch.Tensorassert type(torch.clone(obj)) is type(obj)@@ -317,16 +365,18 @@ class TestConventionsVector(BaseTester):assert type(reduced) is Vector3assert reduced.data.shape == (3,)- normal = Vector3(torch.tensor([2.0, 1.0, -2.0], device=device, dtype=dtype) / 3.0)- point = Vector3(torch.tensor([1.0, 2.0, 0.5], device=device, dtype=dtype))- plane = Hyperplane.from_vector(normal, point)- assert isinstance(plane.normal, Vector3)- assert isinstance(plane.offset, Scalar)- copied = copy.deepcopy(plane)- assert type(copied.normal) is torch.Tensor- assert type(copied.offset) is torch.Tensor- with pytest.raises(AttributeError):- _ = copied.normal.x+ def test_wart_vector3_scalar_left_operand_wins_5022(self, device, dtype):+ # Wart pin (#5022): an operator wraps its result in the left operand's class, so a Scalar on the left+ # returns a Scalar that holds the (2, 3) vectors, while the same product with the Vector3 on the left is a+ # Vector3. A fix that returns a Vector3 whichever side the Scalar is on flips it.+ data = torch.tensor([[0.3, -1.2, 2.5], [1.0, 2.0, 3.0]], device=device, dtype=dtype)+ scale = torch.tensor([[2.0], [3.0]], device=device, dtype=dtype)+ v, s = Vector3(data), Scalar(scale)+ for out, expected in [(s * v, scale * data), (s / v, scale / data), (s + v, scale + data)]:+ assert type(out) is Scalar+ assert out.data.shape == (2, 3)+ self.assert_close(out.data, expected, rtol=0, atol=0)+ assert type(v * s) is Vector3def test_wart_vector3_normalized_scales_below_eps_3952(self, device, dtype):# Wart pin (#3952): normalized() divides by max(norm, 1e-12), so a vector shorter than 1e-12 is scaled by 1e12