Vector2 / Vector3 / Scalar change type with the call path (copy.deepcopy returns a plain Tensor, Scalar * Vector3 is a Scalar, torch.linalg.norm(Vector3) raises) and reject tensor indexing (v[..., 0], v[:, 0], unbatched v[0] raise)
Vector2, Vector3 and Scalar (kornia/geometry/vector.py) subclass TensorWrapper (kornia/core/tensor_wrapper.py). The type a caller gets back depends on how an operation is reached, and indexing does not accept tensor indices.
Type by call path
copy.deepcopyreturns a plainTensor.TensorWrapperdefines no__deepcopy__, so the lookup falls through__getattr__(:121) to the wrapped tensor's__deepcopy__.copy.copyand pickle keep the class. Anything that holds aVector3is affected:copy.deepcopy(Hyperplane(...)).normalis aTensor, and.normal.xraisesAttributeError.- A tensor method reached through
__getattr__returns a plainTensor(v.clone(),v.norm(dim=-1)). The function form goes through__torch_function__(:182), which rewraps every tensor result in the caller's class:torch.clone(v)is aVector3. - That rewrap also runs
Vector3's last-dimension check on results that are not(..., 3). Sotorch.linalg.norm(v, dim=-1)andv.TraiseBaseError: Validation condition failedinstead of returning a Tensor. - Binary operators wrap the result in the left operand's class.
v * sis aVector3, ands * vis aScalarthat holds a(2, 3)tensor.
Indexing
Vector3.__getitem__/Vector2.__getitem__(vector.py:48,:186) indexself.data[idx, ...], which nests a tuple key inside another tuple.v[..., 0]raisesRuntimeError: Could not infer dtype of ellipsis, andv[:, 0]raises the same error "of slice".- An integer index into an unbatched
(3,)vector yields a 0-d tensor, and re-wrapping it asVector3fails its check withIndexError. - An int, a slice, an index tensor and a mask work.
Relation to #4931. #4931 is about which type Se2.t / Se3.t has: Parameter, Tensor or Vector*, depending on the constructor. One of its symptoms is Se3.identity(1).t[..., 0] raising "Could not infer dtype of ellipsis". That symptom is the indexing defect above, reached through Se3. The remedy proposed in #4931 is to store tensors in Se2/Se3, which removes that route but does not touch the wrapper. The following findings are new relative to #4931 and survive its fix:
- the deepcopy type loss, and through it
Hyperplane; - the method-versus-function split;
- left-operand-wins operators;
- the validation failure on non-
(..., 3)results; - the indexing failures on any directly constructed
Vector2/Vector3.
Outside Se2/Se3, Hyperplane stores a Vector3 normal, and the sensors.camera projection models take and return Vector2/Vector3.
Reproduction
import copy
import torch
from kornia.geometry.plane import Hyperplane
from kornia.geometry.vector import Scalar, Vector2, Vector3
def attempt(label, fn):
try:
out = fn()
print(f"{label:40} -> {type(out).__name__} {tuple(out.shape)}")
except Exception as e:
print(f"{label:40} -> {type(e).__name__}: {str(e).splitlines()[0][:60]}")
v = Vector3(torch.tensor([[0.3, -1.2, 2.5], [1.0, 2.0, 3.0]]))
s = Scalar(torch.tensor([[2.0], [3.0]]))
print("-- type by call path")
attempt("copy.deepcopy(Vector3)", lambda: copy.deepcopy(v))
attempt("copy.deepcopy(Vector2)", lambda: copy.deepcopy(Vector2(torch.ones(2, 2))))
attempt("copy.deepcopy(Scalar)", lambda: copy.deepcopy(s))
attempt("copy.copy(Vector3)", lambda: copy.copy(v))
attempt("v.clone()", lambda: v.clone())
attempt("torch.clone(v)", lambda: torch.clone(v))
attempt("v * s", lambda: v * s)
attempt("s * v", lambda: s * v)
attempt("torch.linalg.norm(v, dim=-1)", lambda: torch.linalg.norm(v, dim=-1))
attempt("v.norm(dim=-1)", lambda: v.norm(dim=-1))
attempt("v.T", lambda: v.T)
plane = Hyperplane(Vector3(torch.tensor([[0.0, 0.0, 1.0]])), Scalar(torch.tensor([2.0])))
attempt("copy.deepcopy(Hyperplane).normal", lambda: copy.deepcopy(plane).normal)
attempt("copy.deepcopy(Hyperplane).normal.x", lambda: copy.deepcopy(plane).normal.x)
print("-- indexing")
attempt("v[0]", lambda: v[0])
attempt("v[0:1]", lambda: v[0:1])
attempt("v[..., 0]", lambda: v[..., 0])
attempt("v[:, 0]", lambda: v[:, 0])
attempt("Vector3(torch.ones(3))[0]", lambda: Vector3(torch.ones(3))[0])
attempt("Vector2(torch.ones(2, 2))[..., 0]", lambda: Vector2(torch.ones(2, 2))[..., 0])
attempt("torch.ones(2, 3)[..., 0] [Tensor control]", lambda: torch.ones(2, 3)[..., 0])-- type by call path
copy.deepcopy(Vector3) -> Tensor (2, 3)
copy.deepcopy(Vector2) -> Tensor (2, 2)
copy.deepcopy(Scalar) -> Tensor (2, 1)
copy.copy(Vector3) -> Vector3 (2, 3)
v.clone() -> Tensor (2, 3)
torch.clone(v) -> Vector3 (2, 3)
v * s -> Vector3 (2, 3)
s * v -> Scalar (2, 3)
torch.linalg.norm(v, dim=-1) -> BaseError: Validation condition failed
v.norm(dim=-1) -> Tensor (2,)
v.T -> BaseError: Validation condition failed
copy.deepcopy(Hyperplane).normal -> Tensor (1, 3)
copy.deepcopy(Hyperplane).normal.x -> AttributeError: 'Tensor' object has no attribute 'x'
-- indexing
v[0] -> Vector3 (3,)
v[0:1] -> Vector3 (1, 3)
v[..., 0] -> RuntimeError: Could not infer dtype of ellipsis
v[:, 0] -> RuntimeError: Could not infer dtype of slice
Vector3(torch.ones(3))[0] -> IndexError: tuple index out of range
Vector2(torch.ones(2, 2))[..., 0] -> RuntimeError: Could not infer dtype of ellipsis
torch.ones(2, 3)[..., 0] [Tensor control] -> Tensor (2,)kornia main 0fbed00b0, torch 2.14.0 (and 2.5.1: same output), CPU float32, macOS arm64.
Expected
- One rule for the result type, whichever path produced it. For example: operations whose result is still
(..., 3)return aVector3and everything else returns aTensor, with the same answer forv.clone()andtorch.clone(v). copy.deepcopykeeps the class, ascopy.copyand pickle already do.- Indexing behaves like the wrapped tensor's:
v[..., 0]andv[:, 0]return the(2,)tensor thattorch.ones(2, 3)[..., 0]returns (the Tensor control row), andVector3(torch.ones(3))[0]returns a 0-d tensor. - A product with a
Scalaris aVector3whichever side theScalaris on.
Classification
An API contract violation. It surfaces as exceptions (indexing, torch.linalg.norm, .T, .x after a deepcopy) and as silent type changes (deepcopy, .clone(), Scalar * Vector3). Generic code cannot rely on the type it gets back, and deep-copying a module that holds a Vector3 silently degrades it to Tensors.
No idiom of 1–9 applies. It is the same candidate as #4931, "return type depends on the path", here the call path rather than the constructor. Found in the conventions batch 10 audit.
Disposition
Documented as a Known defect in the batch-10 Convention block for Vector3; fix separately. Fix directions:
- a
__deepcopy__onTensorWrapperthat deep-copies_dataand keeps the class; __getitem__asself.data[idx], returning aTensorwhen the result is not(..., 3)/(..., 2);- in
__torch_function__, rewrapping only results that pass the subclass's shape check, and one rule for methods reached through__getattr__; - operators that return the vector class when one operand is a
Vector*and the other aScalar.
Each of these changes an observable return type, so each needs a changelog fragment.
Related
- #4931 (open):
Se2.t/Se3.ttype depends on the constructor. That issue carries theSe3route to the indexing symptom; this one is the wrapper itself. - #4923 (open): its
deepcopy(Se2.exp(v))failure has a different cause, non-leaf tensors registered as Parameters. - #2126 (closed): an earlier
Hyperplanetorch.save/torch.loadround-trip failure, fixed by__getstate__. It is a different path fromdeepcopy.
Posted on behalf of @ducha-aiki by Claude (Opus 5.5).
Source: kornia/kornia