π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(core)!: give TensorWrapper results one type rule and index vectors like tensors (#5688)
Leonardo Vanni3602884362dd
diff --git a/changelog.d/5688.breaking.md b/changelog.d/5688.breaking.mdnew file mode 100644index 000000000..bcb949303--- /dev/null+++ b/changelog.d/5688.breaking.md@@ -0,0 +1 @@+`TensorWrapper`, `Vector2`, `Vector3` and `Scalar` results now get one type rule, whether a torch function, a tensor method, a tensor attribute or an operator produced them. A result takes the class of a `Vector2`/`Vector3` operand, on either side, when it ends in that width and has at least as many axes as that operand. Otherwise it takes the class of the first operand without a width, and otherwise it is a plain tensor. Before, a tensor method such as `v.clone()` returned a plain tensor while `torch.clone(v)` returned a `Vector3`, `Scalar * Vector3` returned a `Scalar` holding the vectors, and `torch.linalg.norm(v, dim=-1)` and `v.T` raised unless the result happened to end in 3, in which case it was returned as a `Vector3`. Now `v.clone()` and `Scalar * Vector3` are a `Vector3`, `torch.linalg.norm(v, dim=-1)` returns a plain tensor, and `v.T` returns a plain tensor unless the batch holds exactly 3 vectors, whose `(3, 3)` transpose stays a `Vector3` because the rule reads shapes only. The same applies to any torch function that removes an axis: `torch.mean(v, dim=0)` of an `(N, 3)` `Vector3` was a `Vector3` and is now a plain `(3,)` tensor, as `v.mean(dim=0)` already was. `Vector2`/`Vector3` indexing now uses `data[key]`: `v[..., 0]` and `v[:, 0]`, which raised, and an unbatched `v[0]`, which raised `IndexError`, return the plain tensor the wrapped tensor gives, and keys that keep the coordinate axis return the vector class as before.diff --git a/kornia/core/tensor_wrapper.py b/kornia/core/tensor_wrapper.pyindex 0b4d61f37..d36d4000d 100644--- a/kornia/core/tensor_wrapper.py+++ b/kornia/core/tensor_wrapper.py@@ -19,7 +19,7 @@ from __future__ import annotationsimport collections.abcimport pickle-from typing import Any, Optional, Self+from typing import Any, ClassVar, Optional, Selfimport torchfrom torch import Tensor@@ -44,6 +44,74 @@ def _wrap(v: Any, cls: type[TensorWrapper]) -> Any:return cls(v) if isinstance(v, Tensor) else v+def _wrappers_in(args: Any, kwargs: Optional[dict[str, Any]] = None) -> list[TensorWrapper]:+ """Return the wrappers among ``args``, one level into a list or tuple, then among the values of ``kwargs``."""+ found: list[TensorWrapper] = []+ for a in (*args, *(kwargs or {}).values()):+ if isinstance(a, TensorWrapper):+ found.append(a)+ elif isinstance(a, collections.abc.Sequence) and not isinstance(a, (str, bytes)):+ found.extend(el for el in a if isinstance(el, TensorWrapper))+ return found+++def _result_type(result: Tensor, operands: list[TensorWrapper]) -> Optional[type[TensorWrapper]]:+ """Return the wrapper class a tensor result takes, or ``None`` when it stays a plain tensor.++ The class of an operand with a coordinate width (``Vector2``, ``Vector3``) comes before the class of one without+ (``Scalar``), whichever side of the call either is on. It is taken only when the result still holds such+ vectors: it ends in that width and has at least the operand's number of axes. An operation that removes an axis+ can leave a result that ends in the width by chance (the norms of three vectors), so it returns a plain tensor.+ A class without a width takes any result.+ """+ # ``__class__`` rather than ``type()``: torch 2.5.1's Dynamo cannot construct a class that ``type()`` returned.+ for op in operands:+ width = op.__class__._WIDTH+ if width is not None and op._data.ndim <= result.ndim and result.shape[-1] == width:+ return op.__class__+ for op in operands:+ if op.__class__._WIDTH is None:+ return op.__class__+ return None+++def _rewrap(v: Any, operands: list[TensorWrapper]) -> Any:+ """Wrap each tensor in ``v``, or in a list or tuple ``v``, in the class :func:`_result_type` picks."""+ if type(v) in {tuple, list}:+ return type(v)(_rewrap(vi, operands) for vi in v)+ if not isinstance(v, Tensor):+ return v+ cls = _result_type(v, operands)+ return v if cls is None else cls(v)+++def _keeps_last_axis(key: Any, ndim: int) -> bool:+ """Return whether indexing a tensor of ``ndim`` axes with ``key`` leaves its last axis last, at most sliced."""+ items = key if isinstance(key, tuple) else (key,)++ def consumed(item: Any) -> int:+ if item is None or item is Ellipsis or isinstance(item, bool):+ return 0+ if isinstance(item, Tensor) and item.dtype in (torch.bool, torch.uint8):+ return item.ndim+ return 1++ if sum(consumed(item) for item in items) < ndim:+ ellipsis = [i for i, item in enumerate(items) if item is Ellipsis]+ if not ellipsis:+ # The items index leading axes only, and new axes go before the untouched trailing ones.+ return True+ # The ellipsis spans at least one axis, so the items after it index the trailing axes.+ items = items[ellipsis[0] + 1 :]+ # Otherwise an ellipsis spans no axis, as in ``v[mask, ...]`` with a mask over every axis.+ # The last item that consumes an axis indexes the last axis. A new axis after it has size 1, which the caller's+ # width check rejects.+ for item in reversed(items):+ if consumed(item):+ return isinstance(item, slice)+ return True++def _is_picklable(obj: Any) -> bool:"""Return whether pickle can store ``obj``."""try:@@ -81,12 +149,24 @@ class TensorWrapper:``__dict__`` and the copy and pickle hooks. So ``copy.copy``, ``copy.deepcopy`` and pickle return thewrapper's class, and ``torch.compile`` can trace a function that builds a wrapper. The array and DLPackhooks 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.+ - A torch function called on a wrapper (``torch.clone(w)``), a tensor method reached through the wrapper+ (``w.clone()``), a tensor attribute (``w.T``) and every arithmetic, bitwise and comparison operator+ (``+ - * / // % ** @ & | ^ << >>``, ``== != < <= > >=``, unary ``-``, ``+``, ``abs`` and ``~``) compute+ the wrapped tensors' result and wrap each tensor in it, or in a list or tuple of them, by one rule. A+ ``torch.return_types`` result (``torch.sort``, ``torch.max`` with ``dim``) is returned as torch returns it,+ with plain tensors, since the rule would also wrap its ``indices``. The class of an operand with a+ coordinate width (``Vector2``, ``Vector3``) is taken, whichever side it is on, when the result ends in+ that width and keeps at least that operand's axes. Otherwise the class of the first operand without a+ width (``Scalar``, ``TensorWrapper``) is taken: the left operand's (``w + x``), or the right operand's+ when the left one is not a wrapper (``2 / w``, ``t + w``). A comparison whose right operand is an+ instance of a subclass of the left operand's class takes the subclass, because Python tries the+ subclass's reflected comparison first. When no operand qualifies, the result is a plain tensor. So+ ``Scalar * Vector3`` is a ``Vector3``, and ``torch.linalg.norm(v, dim=-1)`` is a plain tensor, also when+ it happens to end in 3. The rule reads shapes only: a result of the same shape stays in the class, as+ the transpose of a ``(3, 3)`` ``Vector3`` does.+ - Indexing returns the indexed tensor in the wrapper's class. For a subclass with a coordinate width, it+ does so only when the key leaves the coordinate axis last, at most sliced, and the result ends in the+ width (``v[0]``, ``v[mask]``); otherwise it returns a plain tensor (``v[..., 0]``, ``v[:, 0]``).- An in-place operator (``+=``, ``-=``, ``*=``, ``/=``, ``//=``, ``%=``, ``**=``, ``&=``, ``|=``, ``^=``,``<<=``, ``>>=``) updates the wrapped tensor in place and returns the same wrapper, so an alias sees thechange. The wrapper does not copy the tensor it is built from, so the update also changes that tensor,@@ -103,6 +183,9 @@ class TensorWrapper:__slots__ = ("_data", "used_attrs", "used_calls")+ # The size of the last axis a result needs to keep a subclass's class; ``None`` takes any result.+ _WIDTH: ClassVar[Optional[int]] = None+# 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.@@ -183,14 +266,18 @@ class TensorWrapper:# Get value from underlying tensorval = getattr(self._data, name)- # A tensor method is returned as is, so its result is not wrapped. Deciding this from the class keeps- # ``_wrap`` from asking for the bound method's type, which Dynamo does not know when the tensor is an- # intermediate, nor on torch 2.5.1 for any tensor.+ # A tensor method returns a function that wraps the method's result like a torch function's. Deciding+ # this from the class keeps the bound method's type out of it, which Dynamo does not know when the tensor+ # is an intermediate, nor on torch 2.5.1 for any tensor.if callable(getattr(Tensor, name, None)):- return val- # Wrap the result if it's a tensor- return _wrap(val, type(self))+ def method(*args: Any, **kwargs: Any) -> Any:+ out = val(*_unwrap(args), **{k: _unwrap(v) for k, v in kwargs.items()})+ return _rewrap(out, [self, *_wrappers_in(args, kwargs)])++ return method++ return _rewrap(val, [self])def __setattr__(self, name: str, value: Any) -> None:"""Set attribute on underlying tensor."""@@ -206,9 +293,13 @@ class TensorWrapper:"""Set item on underlying tensor."""self._data[key] = value- def __getitem__(self, key: Any) -> TensorWrapper:- """Get item from underlying tensor."""- return _wrap(self._data[key], type(self))+ def __getitem__(self, key: Any) -> Any:+ """Get item from underlying tensor, see the Convention block."""+ out = self._data[key]+ width = self.__class__._WIDTH+ if width is None or (_keeps_last_axis(key, self._data.ndim) and out.ndim >= 1 and out.shape[-1] == width):+ return self.__class__(out)+ return out@classmethoddef __torch_function__(@@ -222,23 +313,18 @@ class TensorWrapper:if kwargs is None:kwargs = {}- # Find instances of this class in the arguments- args_of_this_cls: list[TensorWrapper] = []- for a in args:- if isinstance(a, cls):- args_of_this_cls.append(a)- elif isinstance(a, collections.abc.Sequence) and not isinstance(a, (str, bytes)):- args_of_this_cls.extend(el for el in a if isinstance(el, cls))+ operands = _wrappers_in(args, kwargs)# Track function usage- for a in args_of_this_cls:- a.used_calls.add(func)+ for a in operands:+ if isinstance(a, cls):+ a.used_calls.add(func)# Unwrap arguments and call the functionunwrapped_args = _unwrap(args)unwrapped_kwargs = {k: _unwrap(v) for k, v in kwargs.items()}- return _wrap(func(*unwrapped_args, **unwrapped_kwargs), cls)+ return _rewrap(func(*unwrapped_args, **unwrapped_kwargs), operands)def __add__(self, other: Any) -> TensorWrapper:"""Add operation."""diff --git a/kornia/geometry/plane.py b/kornia/geometry/plane.pyindex 341bc987b..202b1de38 100644--- a/kornia/geometry/plane.py+++ b/kornia/geometry/plane.py@@ -305,7 +305,7 @@ def fit_plane(points: Vector3) -> Hyperplane:points_centered = points - mean# NOTE: not optimal for 2d points, but for now works for other dimensions- _, S, V = _torch_svd_cast(points_centered)+ _, S, V = _torch_svd_cast(_unwrap(points_centered))# The plane is determined when the centred points have rank 2: the second singular value# must be nonzero relative to the first, a scale-invariant test that keeps a small or thindiff --git a/kornia/geometry/vector.py b/kornia/geometry/vector.pyindex 073188f35..fd629f5b6 100644--- a/kornia/geometry/vector.py+++ b/kornia/geometry/vector.py@@ -31,8 +31,8 @@ __all__ = ["Scalar", "Vector2", "Vector3"]class Scalar(TensorWrapper):"""Wrap a tensor of scalars of any shape, such as the per-vector result of :meth:`Vector3.dot`.- The tensor is wrapped without a copy, and the call-path type defect of :class:`Vector3` applies to it- (`#5022 <https://github.com/kornia/kornia/issues/5022>`_).+ The tensor is wrapped without a copy. An operation between a ``Scalar`` and a :class:`Vector3` follows the+ rule of :class:`~kornia.core.TensorWrapper`, so ``s * v`` is a ``Vector3`` like ``v * s``."""def __init__(self, data: torch.Tensor) -> None:@@ -51,13 +51,18 @@ class Vector3(TensorWrapper):- ``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; theoperator 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>`_).+ - A result is a ``Vector3`` when it still holds 3D vectors, whether a torch function, a tensor method or an+ operator produced it, and whichever side a :class:`Scalar` is on: ``torch.clone(v)``, ``v.clone()``,+ ``s * v`` and ``v * s`` are ``Vector3``. A result that does not end in 3, or that lost an axis, is a+ plain tensor: ``torch.linalg.norm(v, dim=-1)`` and ``v.norm(dim=-1)``, also for three vectors. The full+ rule is in :class:`~kornia.core.TensorWrapper`.+ - Indexing the leading axes returns a ``Vector3`` (``v[0]``, ``v[1:]``, ``v[mask]``). An index into the+ coordinate axis returns a plain tensor, like the same index into the wrapped tensor: ``v[..., 0]`` and+ ``v[:, 0]`` have the leading shape, and an unbatched ``v[0]`` is 0-d."""+ _WIDTH = 3+def __init__(self, vector: torch.Tensor) -> None:super().__init__(vector)KORNIA_CHECK(vector.shape[-1] == 3)@@ -65,9 +70,6 @@ class Vector3(TensorWrapper):def __repr__(self) -> str:return f"x: {self.x}\ny: {self.y}\nz: {self.z}"- def __getitem__(self, idx: Union[slice, int, torch.Tensor]) -> "Vector3":- return Vector3(self.data[idx, ...])-@propertydef x(self) -> torch.Tensor:"""Return the x-coordinate stored in the last tensor dimension."""@@ -202,6 +204,8 @@ class Vector2(TensorWrapper):unit square."""+ _WIDTH = 2+def __init__(self, vector: torch.Tensor) -> None:super().__init__(vector)KORNIA_CHECK(vector.shape[-1] == 2)@@ -209,9 +213,6 @@ class Vector2(TensorWrapper):def __repr__(self) -> str:return f"x: {self.x}\ny: {self.y}"- def __getitem__(self, idx: Union[slice, int, torch.Tensor]) -> "Vector2":- return Vector2(self.data[idx, ...])-@propertydef x(self) -> torch.Tensor:"""Return the x-coordinate stored in the last tensor dimension."""diff --git a/tests/core/test_tensor_wrapper.py b/tests/core/test_tensor_wrapper.pyindex f33cf2282..f94ddf2c8 100644--- a/tests/core/test_tensor_wrapper.py+++ b/tests/core/test_tensor_wrapper.py@@ -399,11 +399,11 @@ class TestTensorWrapperProtocol(BaseTester):(lambda t: TensorWrapper(t).unwrap(), True),(lambda t: (TensorWrapper(t) + 1).unwrap(), True),(_build_and_update, True),- (lambda t: TensorWrapper(t).sum(), True),+ (lambda t: TensorWrapper(t).sum().unwrap(), True),# A forwarded method on a wrapper built from an intermediate tensor (#5241).- (lambda t: TensorWrapper(t.clone()).sum(), True),- (lambda t: TensorWrapper(t * 2).mean(dim=-1), True),- (lambda t: TensorWrapper(t + 1).reshape(-1), True),+ (lambda t: TensorWrapper(t.clone()).sum().unwrap(), True),+ (lambda t: TensorWrapper(t * 2).mean(dim=-1).unwrap(), True),+ (lambda t: TensorWrapper(t + 1).reshape(-1).unwrap(), 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 or ``__getitem__``.@@ -495,8 +495,10 @@ class TestTensorWrapperProtocol(BaseTester):for exponent in (np.array(2.0), np.array([[2.0, 0.5, 3.0]])):expected = data**exponentout = TensorWrapper(data.clone()) ** exponent- assert type(out) is type(expected)- self.assert_close(out, expected, rtol=0, atol=0)+ # NumPy hands the result back through the forwarded ``__array_wrap__``, so it is wrapped like the+ # result of any other operator.+ assert type(out) is TensorWrapper+ self.assert_close(out.data, 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 Pythondiff --git a/tests/geometry/test_vector.py b/tests/geometry/test_vector.pyindex da9279c80..79b032ddb 100644--- a/tests/geometry/test_vector.py+++ b/tests/geometry/test_vector.py@@ -21,7 +21,6 @@ import pickleimport pytestimport torch-from kornia.core.check import BaseErrorfrom kornia.geometry.plane import Hyperplanefrom kornia.geometry.vector import Scalar, Vector2, Vector3@@ -345,38 +344,78 @@ class TestConventionsVector(BaseTester):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.Tensor- assert type(torch.clone(obj)) is type(obj)-- with pytest.raises(BaseError):- torch.linalg.norm(wrapped[0], dim=-1)- # A reduced result with three elements instead passes shape validation and is miswrapped as a Vector3.- lucky_shape = Vector3(torch.ones(3, 3, device=device, dtype=dtype))- reduced = torch.linalg.norm(lucky_shape, dim=-1)- assert type(reduced) is Vector3- assert reduced.data.shape == (3,)-- 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.+ @pytest.mark.parametrize("vector_type, dim", [(Vector2, 2), (Vector3, 3)])+ def test_convention_vector_result_type_by_one_rule_5022(self, vector_type, dim, device, dtype):+ # A torch function, a tensor method, a tensor attribute and an operator give the same type: the vector class+ # while the result still holds vectors, else a plain tensor. Removing an axis returns a plain tensor even+ # when the result ends in dim by chance, as the norms of dim vectors do. The rule reads shapes only, so the+ # transpose of a square (dim, dim) batch would keep the class: four vectors keep v.T unambiguous here.+ data = torch.tensor(+ [[0.3, -1.2, 2.5], [1.0, 2.0, 3.0], [-0.5, 0.25, 1.5], [2.0, -1.0, 0.5]], device=device, dtype=dtype+ )[..., :dim]+ v = vector_type(data)+ kept = (v.clone(), torch.clone(v), torch.clone(input=v), v.mean(0, keepdim=True), torch.cat([v, v]))+ for out in (*kept, v + torch.ones_like(data)):+ assert type(out) is vector_type+ batched = v + torch.zeros(5, 1, dim, device=device, dtype=dtype)+ assert type(batched) is vector_type+ assert batched.data.shape == (5, 4, dim)++ norms = torch.linalg.norm(v, dim=-1)+ assert type(norms) is torch.Tensor+ self.assert_close(norms, torch.linalg.norm(data, dim=-1), rtol=0, atol=0)+ for out in (v.norm(dim=-1), v.T, v.sum(-1), v.reshape(-1), v.unbind(0)[0]):+ assert type(out) is torch.Tensor+ square = vector_type(torch.ones(dim, dim, device=device, dtype=dtype))+ for out in (torch.linalg.norm(square, dim=-1), square.sum(0), square.norm(dim=-1)):+ assert type(out) is torch.Tensor+ assert out.shape == (dim,)++ # A tensor attribute follows the same rule: the gradient of vectors is vectors.+ leaf = vector_type(data.clone().requires_grad_())+ (leaf.data**2).sum().backward()+ assert type(leaf.grad) is vector_type+ self.assert_close(leaf.grad.data, 2 * data)++ scalar = Scalar(torch.tensor([2.5], device=device, dtype=dtype))+ assert type(torch.clone(scalar)) is Scalar+ assert type(scalar.clone()) is Scalar++ @pytest.mark.skipif(not dynamo_is_available(), reason="no Dynamo on this torch/python pair")+ def test_eager_backend_traces_the_result_type_rule(self, device, dtype):+ # The rule runs inside a compiled function: a Scalar on the left gives a Vector3, a method keeps it, and a+ # norm drops it.+ def fn(t):+ v = Scalar(t[..., :1]) * Vector3(t)+ kept = v.clone()+ norms = kept.norm(dim=-1)+ return kept.data, norms, isinstance(kept, Vector3) and isinstance(norms, torch.Tensor)++ torch._dynamo.reset()+ data = torch.tensor([[0.5, 1.5, 2.0], [1.0, 3.0, 0.75], [2.0, -1.0, 0.25]], device=device, dtype=dtype)+ compiled = torch.compile(fn, backend="eager", fullgraph=True)(data)+ expected = fn(data)+ assert compiled[2] is expected[2] is True+ self.assert_close(compiled[0], expected[0])+ self.assert_close(compiled[1], expected[1])++ def test_convention_vector3_scalar_on_either_side_5022(self, device, dtype):+ # An operation between a Scalar and a Vector3 is a Vector3 whichever side the Scalar is on.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)+ for out, expected in [+ (s * v, scale * data),+ (v * s, data * scale),+ (s / v, scale / data),+ (s + v, scale + data),+ (torch.mul(s, v), scale * data),+ (s.mul(v), scale * data),+ ]:+ assert type(out) is Vector3self.assert_close(out.data, expected, rtol=0, atol=0)- assert type(v * s) is Vector3+ # A result that does not hold vectors falls back to the Scalar.+ assert type(torch.cat([v, s], -1)) is Scalardef 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@@ -391,21 +430,34 @@ class TestConventionsVector(BaseTester):)@pytest.mark.parametrize("vector_type, dim", [(Vector2, 2), (Vector3, 3)])- def test_wart_vector_tuple_index_raises_5022(self, vector_type, dim, device, dtype):- # Wart pin (#5022): Vector.__getitem__ indexes data[idx, ...], so a tuple key is turned into an index- # tensor and raises RuntimeError (v[..., 0], v[:, 0]), and an int index of an unbatched vector leaves a 0-d- # tensor that fails the last-dimension check (IndexError). A fix (index data[idx] and return a Tensor when- # the result is not (..., dim)) flips all three; indexing the batch, as in a[1], already works.+ def test_convention_vector_indexing_5022(self, vector_type, dim, device, dtype):+ # Indexing returns what the same key returns on the wrapped tensor: in the vector class while the key leaves+ # the coordinate axis last and whole, else as a plain tensor.data = torch.tensor([[0.3, -1.2, 2.5], [4.0, 0.5, -0.7]], device=device, dtype=dtype)[..., :dim]a = vector_type(data)- with pytest.raises(RuntimeError):- _ = a[..., 0]- with pytest.raises(RuntimeError):- _ = a[:, 0]- single = vector_type(data[0])- with pytest.raises(IndexError):- _ = single[0]+ mask = torch.tensor([True, False], device=device)+ index = torch.tensor([1, 0, 1], device=device)+ for key in (1, slice(1, None), mask, index, [1, 0], (Ellipsis,), (slice(None), None), None, (0, slice(None))):+ out = a[key]+ assert type(out) is vector_type, key+ self.assert_close(out.data, data[key], rtol=0, atol=0)+ for key in ((Ellipsis, 0), (slice(None), 0), (1, 1), (Ellipsis, None), (Ellipsis, slice(0, 1)), (0, index)):+ out = a[key]+ assert type(out) is torch.Tensor, key+ self.assert_close(out, data[key], rtol=0, atol=0)++ # A mask over both axes selects dim elements here, so only the key tells they are not one vector.+ full_mask = torch.zeros(2, dim, dtype=torch.bool, device=device)+ full_mask[0, :] = True+ for key in (full_mask, (full_mask, Ellipsis), (Ellipsis, full_mask)):+ assert type(a[key]) is torch.Tensor, key+ self.assert_close(a[key], data[key], rtol=0, atol=0)+ # An ellipsis spanning no axis does not hide the axes consumed before it.+ assert type(a[0, slice(None), Ellipsis]) is vector_type+ assert type(a[0, 1, Ellipsis]) is torch.Tensor- row = a[1]- assert isinstance(row, vector_type)- self.assert_close(row.data, data[1])+ single = vector_type(data[0])+ assert type(single[0]) is torch.Tensor+ assert single[0].shape == ()+ assert type(single[None]) is vector_type+ assert type(single[True]) is vector_type