Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

docs(conversions): trim convention blocks and pins to kornia scope (#4792)

Dmytro Mishkinb4fdbb262c80
diff --git a/changelog.d/4792.fixed.md b/changelog.d/4792.fixed.md
new file mode 100644
index 000000000..082e3e3e5
--- /dev/null
+++ b/changelog.d/4792.fixed.md
@@ -0,0 +1 @@
+`kornia.geometry.conversions` docstrings no longer claim that the deprecated aliases break `-W error::DeprecationWarning` (fixed in #3956), state the float64 axis-angle round-trip accuracy correctly (roundoff, about `2e-10` on the low-angle branch), and document two defects: `rotation_matrix_to_axis_angle` returns the identity for a reflection (#4773), and `Rt_to_matrix4x4` and `camtoworld_to_worldtocam_Rt` handle an `R`/`t` batch-size mismatch differently (#4774).
diff --git a/kornia/geometry/conversions.py b/kornia/geometry/conversions.py
index 60615037a..5f09ab435 100644
--- a/kornia/geometry/conversions.py
+++ b/kornia/geometry/conversions.py
@@ -231,10 +231,8 @@ def convert_points_from_homogeneous(points: torch.Tensor, eps: float = 1e-8) ->
``>``) the numerator is instead returned **unchanged**, following
OpenCV: ``[[2., 4., 0.]]`` gives ``[[2., 4.]]``
- ``eps`` only picks the branch, it never enters the division, so the
- result carries no bias from it. Note that ``eps`` is compared against
- ``w`` in the working dtype: in ``float16`` the default ``eps`` and
- ``w = 2e-8`` both underflow to ``0``, so ``[[2., 4., 2e-8]]`` takes
- the pass-through branch there and returns ``[[2., 4.]]``
+ result carries no bias from it. It is compared against ``w`` in the
+ working dtype
Args:
points: the points to be transformed of shape :math:`(*, N, D)`.
@@ -394,24 +392,13 @@ def axis_angle_to_rotation_matrix(axis_angle: torch.Tensor) -> torch.Tensor:
turns the same way
- ``angle_axis_to_rotation_matrix`` is the deprecated alias of this
function since 0.7.0; it emits a ``DeprecationWarning`` and forwards
- to this function, returning an equal result β€” see the alias warning
- below
+ to this function, returning an equal result
- differentiable at the identity rotation. The ``sqrt`` whose
derivative is unbounded there never sees its zero radicand, so the
gradient is the analytic limit of the surrounding map rather than
``nan``. The guard is elementwise, and away from the identity it
moves no forward bit
- .. warning::
- Calling any of this module's four deprecated aliases
- (``angle_axis_to_rotation_matrix``, ``rotation_matrix_to_angle_axis``,
- ``quaternion_to_angle_axis``, ``angle_axis_to_quaternion``) rewrites the
- process-global ``DeprecationWarning`` filters, so
- ``-W error::DeprecationWarning`` does not turn the warning into an error
- and every later ``DeprecationWarning`` raised in the process is affected
- too. Tracked in
- `#3956 <https://github.com/kornia/kornia/issues/3956>`_.
-
Args:
axis_angle: tensor of 3d vector of axis-angle rotations in radians with shape :math:`(*, 3)`.
@@ -530,19 +517,19 @@ def rotation_matrix_to_axis_angle(rotation_matrix: torch.Tensor) -> torch.Tensor
results above can be fed straight back
- the round trip through
:func:`~kornia.geometry.conversions.axis_angle_to_rotation_matrix`
- is accurate to about ``5e-09`` in ``float64`` β€” measured
- ``2.0e-12`` at ``theta = 1e-3`` and ``4.2e-09`` at ``theta = pi``
- about ``(1, 2, 3)/sqrt(14)`` β€” the latter is
- :func:`~kornia.geometry.conversions.rotation_matrix_to_axis_angle`'s
- own conditioning near the ``pi`` singularity
+ is accurate to roundoff, except that the low-angle Taylor branch
+ (``theta <= 1e-3``) leaves a truncation error of up to about
+ ``2e-10``
- the input is **not** checked for being a rotation matrix:
- ``zeros(3, 3)`` returns ``[0., 0., 3.1416]``, ``2 * eye(3)`` returns
- ``[0., 0., 0.]``, and the reflection ``diag(-1, 1, 1)``
- (``det = -1``) also returns ``[0., 0., 0.]``, i.e. is silently
- reported as no rotation at all
+ ``zeros(3, 3)`` returns ``[0., 0., 3.1416]`` and ``2 * eye(3)``
+ returns ``[0., 0., 0.]``
- ``rotation_matrix_to_angle_axis`` is the deprecated alias of this
- function since 0.7.0; see the alias warning on
- :func:`~kornia.geometry.conversions.axis_angle_to_rotation_matrix`
+ function since 0.7.0
+
+ .. warning::
+ A reflection (``det = -1``) is returned as a rotation:
+ ``diag(-1, 1, 1)`` gives ``[0., 0., 0.]``, the identity. Tracked in
+ `#4773 <https://github.com/kornia/kornia/issues/4773>`_.
Args:
rotation_matrix: rotation matrix of shape :math:`(*, 3, 3)`.
@@ -702,18 +689,12 @@ def normalize_quaternion(quaternion: torch.Tensor, eps: float = 1.0e-12) -> torc
.. warning::
When ``||q|| < eps`` the output is **not** a unit quaternion and no
- error is raised: in ``float64`` with the default ``eps = 1e-12``,
+ error is raised: with the default ``eps = 1e-12``,
``[1e-13, 0., 0., 0.]`` returns ``[0.1, 0., 0., 0.]`` and ``zeros(4)``
- returns ``zeros(4)``, and with ``eps=0.0`` the zero quaternion returns
- ``[nan, nan, nan, nan]`` instead. ``float32`` and ``bfloat16`` behave
- the same up to their rounding (``0.10000000149011612`` and
- ``0.099609375`` for the first input). For ``float16``, a positive
- ``eps`` is floored at the dtype's smallest positive subnormal value, so
- the default guard remains active and a zero quaternion also returns
- ``zeros(4)`` without clamping non-zero representable magnitudes. An
- explicit ``eps=0.0`` still disables that guard. The remaining
- sub-``eps`` behavior is tracked in
- `#3952 <https://github.com/kornia/kornia/issues/3952>`_.
+ returns ``zeros(4)``. Tracked in
+ `#3952 <https://github.com/kornia/kornia/issues/3952>`_. With
+ ``eps=0.0`` the zero quaternion returns ``nan``. In ``float16`` a
+ positive ``eps`` is floored at the smallest subnormal.
Args:
quaternion: a tensor containing a quaternion to be normalized.
@@ -772,47 +753,25 @@ def quaternion_to_rotation_matrix(quaternion: torch.Tensor) -> torch.Tensor:
rotation matrix and no error
- ``q`` and ``-q`` are the same rotation (double cover) and return
bit-identical matrices
- - the input is normalised internally:
+ - the input is normalised internally with
+ :func:`~kornia.geometry.conversions.normalize_quaternion`, so
``quaternion_to_rotation_matrix(2 * q)`` is bitwise
- ``quaternion_to_rotation_matrix(q)`` (400 000 random unit
- quaternions, at every dtype; every figure in this protocol was
- measured on torch 2.9.1, cpu, and passages citing the protocol
- inherit that tag). Rescaling by random factors between
- ``1e-6`` and ``1e6`` moves the matrix only by the working dtype's
- rounding in ``float64`` and ``float32`` (by ``1.3e-15`` and
- ``6.0e-07`` over 2000 random unit quaternions), but the
- reduced-precision dtypes do **not** hold to that: ``bfloat16`` moves
- by ``3.1e-02``, and ``float16`` loses the property altogether β€” near
- the top of that range the rescaled matrix bears no relation to the
- input at all (entries live in ``[-1, 1]``, and the deviation
- approaches the maximum possible ``2``), while the ``1e6`` end is
- ``nan`` outright because ``0.5 * 1e6`` overflows the dtype.
- Once ``||q||`` drops below
- :func:`~kornia.geometry.conversions.normalize_quaternion`'s effective
- floor (``eps = 1e-12``, raised to the smallest positive subnormal in
- ``float16``), the clamp takes over and rescaling changes the matrix
- outright: in ``float64``, ``q * 1e-13`` and ``q`` can give matrices
- that differ by order 1
+ ``quaternion_to_rotation_matrix(q)``; other rescalings move the
+ matrix by the working dtype's rounding, as long as the norm of the
+ rescaled quaternion neither overflows nor falls below the
+ normalisation floor ``eps = 1e-12`` (see that function's warning)
- :func:`~kornia.geometry.conversions.quaternion_to_axis_angle` is
- scale-safe over its own range, given in its Convention block; the two
- functions that are **not** are
+ scale-safe too;
:func:`~kornia.geometry.conversions.quaternion_exp_to_log` and
- :func:`~kornia.geometry.conversions.euler_from_quaternion`, whose
- warnings give the measured errors
+ :func:`~kornia.geometry.conversions.euler_from_quaternion` are
+ **not** (see their warnings)
- applied on the left to a column vector, ``+theta`` about ``+z`` maps
``x_hat`` to ``y_hat`` (right-hand rule)
- - the output dtype follows the input at every shape.
- :func:`~kornia.geometry.conversions.normalize_quaternion`,
- :func:`~kornia.geometry.conversions.quaternion_to_axis_angle` and
- :func:`~kornia.geometry.conversions.quaternion_exp_to_log` return the
- input dtype at every shape
+ - the output dtype follows the input at every shape
.. warning::
- The zero quaternion returns the identity matrix rather than raising:
- ``quaternion_to_rotation_matrix(torch.zeros(4))`` is ``eye(3)`` in
- ``float64``, ``float32``, ``bfloat16`` and ``float16``. This silently
- treats an input that is not a rotation as the identity rather than
- raising. Tracked in
+ The zero quaternion, which is not a rotation, returns the identity
+ matrix rather than raising. Tracked in
`#3952 <https://github.com/kornia/kornia/issues/3952>`_.
Args:
@@ -893,34 +852,18 @@ def quaternion_to_axis_angle(quaternion: torch.Tensor) -> torch.Tensor:
and the output is the rotation axis scaled by the angle in
**radians**
- for ``w != 0`` the double cover is collapsed: ``q`` and ``-q`` return
- the same vector, the representative with ``|theta| <= pi``, and in
- ``float64`` the two are bit-identical (400 000 random finite
- quaternions). At lower precision they agree to the working dtype's
- rounding
+ the same vector, the representative with ``|theta| <= pi``
- at exactly ``w = 0`` β€” a half turn, and ``0.`` is exactly
representable β€” the collapse does not happen and the two return exact
negations: ``[0., 1., 0., 0.]`` gives ``[pi, 0., 0.]`` while
``[-0., -1., 0., 0.]`` gives ``[-pi, 0., 0.]``, the same rotation
written the other way round
- - the input need not be unit. The measurement protocol is the one
- described on
- :func:`~kornia.geometry.conversions.quaternion_to_rotation_matrix` β€”
- bitwise equality under doubling over 400 000 random unit quaternions
- at every dtype, then rescaling by random factors between ``1e-6`` and
- ``1e6`` over 2000 such quaternions β€” and the figures it gives here
- are:
- ``float64`` and ``float32`` move only by their own rounding
- (``8.9e-16`` and ``4.8e-07``), while the reduced-precision dtypes do
- **not** hold to that β€” ``bfloat16`` moves by ``3.1e-02``, ``float16``
- by over ``3`` radians, and the ``1e6`` end is ``nan`` at ``float16``
- because ``0.5 * 1e6`` overflows the dtype.
- At extreme scales the squares of the vector part underflow and the
- result does change: in ``float32``,
- ``quaternion_to_axis_angle(q * 1e-25)`` returns exactly
- ``2 * (q * 1e-25)[..., 1:]``
+ - the input need not be unit: scaling ``q`` by a power of two returns a
+ bit-identical vector, and other scales move it by the working
+ dtype's rounding, as long as the squares of the components neither
+ overflow nor underflow
- ``quaternion_to_angle_axis`` is the deprecated alias of this function
- since 0.7.0; see the alias warning on
- :func:`~kornia.geometry.conversions.axis_angle_to_rotation_matrix`
+ since 0.7.0
- differentiable at the identity quaternion. The ``sqrt`` whose
derivative is unbounded there never sees its zero radicand, so the
gradient is the analytic limit of the surrounding map rather than
@@ -1030,10 +973,11 @@ def quaternion_log_to_exp(quaternion: torch.Tensor, eps: float = 1.0e-8) -> torc
in ``(w, x, y, z)`` order (see
:func:`~kornia.geometry.conversions.quaternion_to_rotation_matrix`)
- the map is ``w = cos(||v||)`` with vector part
- ``sin(||v||) * v / ||v||``, so whenever ``||v||`` is computed finitely
- the output is a unit quaternion up to the working dtype's rounding.
- Two inputs escape that: the ``float16`` zero vector, and any ``v``
- large enough that ``||v||`` overflows β€” see the two warnings below
+ ``sin(||v||) * v / ||v||``, and every finite ``v`` returns a unit
+ quaternion up to the working dtype's rounding: ``||v||`` is computed
+ as ``s * ||v / s||`` with ``s = max |v_i|``, so it cannot overflow,
+ and ``float16``/``bfloat16`` are computed in ``float32``, so the zero
+ vector returns ``[1., 0., 0., 0.]`` at every dtype
- ``pi/2 < ||v|| < 3 * pi/2`` lands in the ``w < 0`` half of the double
cover β€” at ``||v|| = 2`` the real part is ``-0.4161468365471424``.
``w`` is ``cos(||v||)``, so the sign turns over again beyond that
@@ -1048,23 +992,6 @@ def quaternion_log_to_exp(quaternion: torch.Tensor, eps: float = 1.0e-8) -> torc
``[-1., 0., 0., 0.]`` comes back as ``[1., 0., 0., 0.]`` β€” the other
half of the same rotation
- .. note::
- ``float16``/``bfloat16`` inputs are upcast to ``float32`` for the computation, so the
- default ``eps = 1e-8`` is representable there and the zero vector returns
- ``[1., 0., 0., 0.]`` at every dtype (the clamp that guards the division is not a no-op).
- This also removes the historical ``float16`` defect where the default ``eps`` rounded to
- ``0`` and the zero vector came back ``[1., nan, nan, nan]``. Tracked in
- `#3966 <https://github.com/kornia/kornia/issues/3966>`_.
-
- .. note::
- ``||v||`` is computed as ``scale * ||v / scale||`` with ``scale = max |v_i|`` (a scaling
- that keeps the squared terms bounded by the number of components), so the norm cannot
- overflow to ``inf`` from a sum of squares. The exponential map of a large finite vector
- therefore returns a finite unit quaternion across the whole finite range of every dtype,
- instead of all-``nan`` past the ``sqrt(finfo.max)`` turnover that ``torch.norm(p=2)``
- would hit. Tracked in
- `#3975 <https://github.com/kornia/kornia/issues/3975>`_.
-
Args:
quaternion: the log quaternion, a tensor of shape :math:`(*, 3)`.
eps: a small number for clamping.
@@ -1126,9 +1053,12 @@ def quaternion_exp_to_log(quaternion: torch.Tensor, eps: float = 1.0e-8) -> torc
- ``quaternion_exp_to_log(quaternion_log_to_exp(v))`` returns ``v`` for
``0 < ||v|| < pi`` and the wrapped ``||v|| - 2 * pi`` above ``pi``
(``pi + 0.5`` comes back as ``-2.6415926535897936``). At exactly
- ``||v|| = pi``, and only in ``float64``, it collapses to ``3.85e-08``
- β€” there ``cos(pi)`` rounds to ``-1`` and the vector part falls under
- the ``eps`` clamp. Both are properties of the map, not defects
+ ``||v|| = pi`` in ``float64`` it collapses to nearly ``0``: ``cos(pi)``
+ rounds to ``-1`` and the vector part falls under the ``eps`` clamp.
+ Both are properties of the map, not defects
+ - ``float16``/``bfloat16`` are computed in ``float32``, so the identity
+ returns ``[0., 0., 0.]`` at every dtype, and the gradient is finite
+ at ``w = +-1``, the identity included
.. warning::
The input is **not** normalised, so a non-unit quaternion is silently
@@ -1139,26 +1069,6 @@ def quaternion_exp_to_log(quaternion: torch.Tensor, eps: float = 1.0e-8) -> torc
``1``. Tracked in
`#3953 <https://github.com/kornia/kornia/issues/3953>`_.
- .. note::
- ``float16``/``bfloat16`` inputs are upcast to ``float32`` for the computation, so the
- default ``eps = 1e-8`` is representable there and the identity quaternion returns
- ``[0., 0., 0.]`` at every dtype (the clamp that guards the division is not a no-op).
- This also removes the historical ``float16`` defect where the default ``eps`` rounded to
- ``0`` and the identity came back ``[nan, nan, nan]``. Tracked in
- `#3966 <https://github.com/kornia/kornia/issues/3966>`_.
-
- .. note::
- The backward pass is finite at ``w = +-1`` (``w = 1`` is the identity quaternion, the
- standard initialisation for pose optimisation), where the forward already returns a
- correct value: ``acos``'s own derivative is unbounded there -- ``-inf`` on every
- supported torch version -- and is now guarded before it is differentiated. This used to
- return ``nan`` for the gradient at the identity, since it multiplied that unbounded
- derivative by the identity's exactly-zero vector part. On torch 2.14 the defect is masked
- rather than absent: ``clamp``'s backward returns ``0`` at the closed boundary there
- instead of passing the gradient through, so the ``-inf`` is killed before it reaches the
- multiply. That is ``clamp``'s behaviour changing, not ``acos``'s, and this guard does not
- depend on it. Delivered in `#4228 <https://github.com/kornia/kornia/pull/4228>`_.
-
Args:
quaternion: a tensor containing a quaternion to be converted.
The tensor can be of shape :math:`(*, 4)`.
@@ -1229,13 +1139,10 @@ def axis_angle_to_quaternion(axis_angle: torch.Tensor) -> torch.Tensor:
- nothing is canonicalised, so ``theta > pi`` returns the ``w < 0`` half
of the double cover: ``[2 * pi, 0., 0.]`` gives ``[-1., 0., 0., 0.]``
- the round trip with
- :func:`~kornia.geometry.conversions.quaternion_to_axis_angle` is exact
- in ``float64``: the measured error is ``0`` to ``2.2e-16`` at
- ``theta = 0``, ``1e-3``, ``0.7``, ``2`` and ``pi`` about
- ``(1, 2, 3)/sqrt(14)``
+ :func:`~kornia.geometry.conversions.quaternion_to_axis_angle` holds
+ to roundoff for ``0 <= theta <= pi``
- ``angle_axis_to_quaternion`` is the deprecated alias of this function
- since 0.7.0; see the alias warning on
- :func:`~kornia.geometry.conversions.axis_angle_to_rotation_matrix`
+ since 0.7.0
- an integral or boolean input is **promoted**, not rejected: the
``sqrt`` on the way in already produces a floating tensor, and the
output is allocated from that rather than from the input, so the
@@ -1316,8 +1223,7 @@ def euler_from_quaternion(
- the four quaternion coefficients are passed as **separate** tensors in
``(w, x, y, z)`` order, not as one :math:`(*, 4)` tensor, and their
shapes must be exactly equal: broadcastable shapes such as ``(2,)``
- and ``(1,)`` raise ``BaseError: Validation condition failed``, and
- Python floats raise ``AttributeError``
+ and ``(1,)`` raise ``BaseError``
- the return is a tuple of three tensors ``(roll, pitch, yaw)`` in
**radians**, with ``roll`` about ``x``, ``pitch`` about ``y`` and
``yaw`` about ``z``; the composition they stand for is documented on
@@ -1368,14 +1274,6 @@ def euler_from_quaternion(
.. note::
``pitch``'s gradient is finite at gimbal lock, including exactly at ``pitch = +-pi/2``.
- This is a separate concern from the two warnings above, which are about the *value*:
- ``asin``'s own derivative is unbounded at its domain boundary (``inf`` on every supported
- torch version), and used to return ``nan`` or ``inf`` there for every quaternion
- coefficient once anything downstream differentiated through ``pitch``, independent of
- whether the returned triple itself represented the input rotation. The ``clamp`` above
- bounds only the *value*; on torch < 2.14 it passes the gradient straight through, while
- 2.14 zeroes it at the boundary and masks the defect.
- Delivered in `#4228 <https://github.com/kornia/kornia/pull/4228>`_.
Args:
w: quaternion :math:`q_w` coefficient.
@@ -1431,8 +1329,7 @@ def quaternion_from_euler(
``Rx @ Ry @ Rz`` by ``0.64``, from ``Ry @ Rz @ Rx`` by ``0.55`` and
from ``Rx @ Rz @ Ry`` by ``0.25``
- the three arguments must have exactly equal shapes; broadcastable
- shapes such as ``(2,)`` and ``(1,)`` raise
- ``BaseError: Validation condition failed``
+ shapes such as ``(2,)`` and ``(1,)`` raise ``BaseError``
- the return is a tuple of **four separate tensors** ``(w, x, y, z)``,
not a :math:`(*, 4)` tensor: ``(0.3, 0.7, 1.1)`` gives
``[0.8186, -0.0575, 0.3624, 0.4418]``
@@ -1859,66 +1756,22 @@ def normalize_homography(
r"""Normalize a given homography in pixels to [-1, 1].
Convention:
- (every measured figure in this docstring β€” Convention block and
- warnings alike β€” is a sample of one build, torch 2.9.1 on cpu unless a
- sentence names another device; trailing digits may move with the
- backend's summation order)
-
- the input maps **source pixels to destination pixels** and the output
- maps **normalized source to normalized destination** β€” the same
- direction, re-expressed in the two images' :math:`[-1, 1]` frames. A
- ``+2`` pixel shift in ``x`` on a 5-wide image comes back as a ``+1.0``
- shift in normalized units, because the destination frame is scaled by
- ``2 / (width - 1) = 0.5``
- - the composition is exactly ``N_dst @ H @ inv(N_src)``, where ``N`` is
- :func:`~kornia.geometry.conversions.normal_transform_pixel`: so
- ``dsize_src`` drives the **right** (input-side) factor and
- ``dsize_dst`` the **left** (output-side) one. The reversed pairing
- ``inv(N_dst) @ H @ N_src`` is a different matrix β€” it is what
+ maps **normalized source to normalized destination**: exactly
+ ``N_dst @ H @ inv(N_src)`` with ``N`` from
+ :func:`~kornia.geometry.conversions.normal_transform_pixel`, so
+ ``dsize_src`` drives the right factor and ``dsize_dst`` the left one.
+ A ``+2`` pixel shift in ``x`` on a 5-wide image comes back as ``+1.0``.
:func:`~kornia.geometry.conversions.denormalize_homography` computes
- - both ``dsize`` arguments are ``(height, width)`` tuples, while the
- matrix itself acts on ``(x, y, 1)`` column vectors β€” ``x`` scaled by
- ``width``, ``y`` by ``height``
- - batching is per sample: element ``i`` of the output depends only on
- element ``i`` of the input
- - the :math:`[-1, 1]` frames are
- :func:`~kornia.geometry.conversions.normal_transform_pixel`'s, under
- the convention ``align_corners`` selects: **corner-aligned** by
- default (``True``), half-pixel for ``False`` β€” see the convention
- warning below
- - the shape guard accepts a :math:`(3, 3)` or a :math:`(B, 3, 3)`
- matrix and nothing else. An unbatched ``(3, 3)`` is promoted to
- ``(1, 3, 3)`` β€” the returned matrix is batched even though the input
- was not β€” while a rank-4 input such as ``(2, 4, 3, 3)`` and a
- wrong-sized one such as ``(B, 4, 4)`` both raise ``ValueError``
- naming the argument and the expected shape. Rank-4 inputs and
- ``(B, 4, 4)`` inputs used to pass this guard, the first returned
- unchanged in rank and the second dying later inside ``matmul``; fixed
- in `#3999 <https://github.com/kornia/kornia/pull/3999>`_
-
- .. warning::
- In **eager mode** the inverse this function takes is a closed-form 3x3
- adjugate built from ``torch.linalg.cross`` β€” chosen to keep ``cusolver``
- off the path β€” and a backend that has no ``cross`` kernel for the
- working dtype therefore makes this function **raise from inside the
- inverse** rather than return. That is kernel coverage, not a convention:
- nothing is wrong with the input, and the same call in another dtype on
- the same backend succeeds β€” measured on ``mps`` in ``bfloat16``
- (torch 2.5.1; fixed in 2.9.1) and on cpu in
- ``torch.bool``/``float8_e4m3fn`` (torch 2.9.1). Under
- ``torch.jit.trace`` and the legacy ONNX exporter that same closed form
- switches to a scalar cofactor expansion which calls no ``cross`` at all,
- so the gap is **eager-only**: with ``torch.linalg.cross`` replaced by a
- raising stub the eager call raises and the traced call returns (executed,
- torch 2.9.1, cpu).
- :func:`~kornia.geometry.conversions.normalize_homography3d` inverts
- through ``torch.linalg.inv`` in both modes β€” its matrices are 4x4 and
- the tracing fallback is 3x3-only β€” while
- :func:`~kornia.geometry.conversions.denormalize_homography` does so in
- eager mode only and takes the same cofactor expansion under tracing, so
- its traced graph holds no ``aten::linalg_inv`` either. Neither has this
- ``cross`` gap in either mode, and both carry the ``cusolver`` dependency
- wherever they do reach ``linalg.inv``.
+ the reverse ``inv(N_dst) @ H @ N_src``
+ - both ``dsize`` arguments are ``(height, width)``, while the matrix acts
+ on ``(x, y, 1)`` column vectors
+ - a :math:`(3, 3)` or :math:`(B, 3, 3)` matrix is accepted and batching is
+ per sample; an unbatched input is returned as ``(1, 3, 3)``, and any
+ other shape raises ``ValueError``
+ - in eager mode ``inv(N_src)`` is a closed-form adjugate built from
+ ``torch.linalg.cross``, so no ``cusolver`` is needed, but a backend
+ without a ``cross`` kernel for the dtype raises here
.. warning::
The two normalization matrices are built without a ``dtype=``
@@ -1947,28 +1800,10 @@ def normalize_homography(
`#3958 <https://github.com/kornia/kornia/issues/3958>`_.
.. warning::
- Integer inputs are handled inconsistently and the inconsistency is
- device-dependent: on cpu (torch 2.9.1) an ``int64`` call raises
- ``RuntimeError: expected scalar type Long but found Float`` here and a
- ``torch.linalg.LinAlgError`` about a zero diagonal in
- :func:`~kornia.geometry.conversions.denormalize_homography`, while on
- ``mps`` the same ``normalize_homography`` call returns an all-``nan``
- ``float32`` matrix instead of raising β€” ``denormalize_homography`` does
- raise there, with a bare internal assert out of
- ``BatchLinearAlgebra.cpp``. Only the cpu ``normalize_homography``
- message names dtypes at all β€” ``Long`` and ``Float``, without saying
- which argument β€” while cpu's ``denormalize_homography`` message is
- dtype-free and the ``mps`` assert carries no dtype, shape or argument
- name. What splits the ``normalize_homography`` behaviors is
- whether the backend rejects a **batched** ``int64``-by-``float32``
- matmul: the normalization matrices are truncated to ``int64``, the
- closed-form inverse silently promotes them back to an all-``nan``
- ``float32``, and the final chain matmul then sees a mixed pair β€” cpu
- rejects it, ``mps`` multiplies it. That mechanism, not the device
- names, is what decides: the behavior recorded here for cpu and ``mps``
- is the behavior of any backend that makes the same choice, and no CUDA
- behavior is claimed.
- Tracked in `#3959 <https://github.com/kornia/kornia/issues/3959>`_.
+ An integer matrix is not rejected: the normalization matrices are cast
+ to it and truncated, and the call then fails inside torch or returns
+ ``nan``, depending on the backend. Tracked in
+ `#3959 <https://github.com/kornia/kornia/issues/3959>`_.
.. warning::
The :math:`[-1, 1]` frames follow this function's own ``align_corners``,
@@ -1980,22 +1815,7 @@ def normalize_homography(
:func:`~kornia.geometry.transform.warp_perspective`,
:func:`~kornia.geometry.transform.warp_affine` and
:func:`~kornia.geometry.transform.homography_warp` forward their own
- flag, so they are consistent under both settings. Before that was the
- case, an identity ``warp_perspective`` at ``align_corners=False``
- deviated from its input by ``11.25`` on a 4x4 ``arange`` image, against
- ``1.4e-05`` at ``align_corners=True``; the cause was the corner-aligned
- grid being sampled under the half-pixel convention, not this function.
- For equal source and destination sizes an identity homography
- normalizes back to the identity to within a single ``float32`` rounding
- step under either convention β€” exactly ``0`` at most sizes and
- ``5.96e-08`` at the rest. *Which* sizes land where differs between the
- two conventions, because it is a property of the inverse-and-matmul
- chain rather than of the scale, so read the size you care about rather
- than a pattern off any list. At the default ``align_corners=True``,
- swept over equal sizes 2..32, the residual is ``5.96e-08`` at 4, 6, 7,
- 11, 13, 14, 21, 25 and 27 and exactly ``0`` everywhere else; ``4x4`` is
- in that first group, which is where the ``1.4e-05`` figure above comes
- from. Recorded in
+ flag, so they are consistent under both settings; see
`#3904 <https://github.com/kornia/kornia/issues/3904>`_.
:func:`~kornia.geometry.conversions.normalize_homography3d` still has
no ``align_corners`` parameter and is corner-aligned unconditionally, so
@@ -2070,48 +1890,12 @@ def normal_transform_pixel(
``[0.5, 0.0, -1.0]`` and ``[0.0, 0.6667, -1.0]``, and sends the pixels
``(0, 0)``, ``(4, 3)`` and ``(2, 1.5)`` to ``(-1, -1)``, ``(1, 1)``
and ``(0, 0)``
- - for sizes ``>= 2`` this is the same convention as
- :func:`~kornia.geometry.conversions.normalize_pixel_coordinates`, and
- for a caller that is usually the whole of it: in ``float32`` and
- ``float64`` the two routes agree to the working dtype's rounding β€”
- **exactly**, at every size measured, on cpu, and within one
- ``float32`` ulp on ``mps`` β€” while in ``float16``/``bfloat16`` they
- can and do diverge, and *whether* they diverge is a property of the
- build's matmul kernel rather than of the convention: swept over
- every size pair in ``range(2, 60)`` on cpu, ``float16`` disagrees at
- almost all of them under both torch builds measured, whereas
- ``bfloat16`` disagrees at almost all of them under one build and at
- none at all under the other. A reduced-precision pipeline should
- therefore not mix the two routes and expect a match β€” and should not
- read one build's exact agreement as a contract either. It is
- **not**
- :func:`torch.nn.functional.grid_sample`'s default half-pixel
- ``(2 * x + 1) / width - 1``, which would put column ``0`` of a 5-wide
- image at ``-0.8`` rather than ``-1.0``
- - *how far apart the two routes get, and why* β€” a measurement of the
- build's matmul kernel rather than a statement about the convention;
- skip it unless a reduced-precision difference is what brought you
- here. Both routes hold the same rounded ``2 / (size - 1)`` scale; what
- differs is where the rounding falls, since applying this matrix is a
- matmul (accumulated at higher precision, rounded once) while the
- helper multiplies and subtracts elementwise in the working dtype. The
- two agree in ``float32``/``float64``; whether they agree at
- ``float16``/``bfloat16`` is a property of the build, as above.
- The exact per-configuration gaps are a measurement of one build's
- kernel and are recorded, with the snippet that reproduces them, next
- to a pin that re-asserts each of them on the configuration it was
- measured on β€” and skips visibly elsewhere β€” rather than quoted here.
- What holds on any backend whose matmul rounds its inputs at the
- working dtype, and is a contract rather than a build-specific figure,
- is a dtype-scaled bound: the two routes stay within
- ``2 * finfo(dtype).eps`` of each other β€” *tolerated*, not derived,
- with roughly ``2x`` headroom over the measured cells. A backend or
- configuration that rounds a matmul's inputs below the working dtype
- (``TF32`` on ``cuda``, say) is outside that bound by construction and
- gets the same bound taken at the coarser format instead β€”
- ``2 * 2 ** -10`` rather than ``2 * 2 ** -23`` for ``TF32``
- ``float32`` β€” which is what the pin enforces there, so such a
- configuration widens the bound rather than exceeding it
+ - for sizes ``>= 2`` this is the same map as
+ :func:`~kornia.geometry.conversions.normalize_pixel_coordinates`. In
+ ``float32``/``float64`` the two routes agree to the working dtype's
+ rounding; in ``float16``/``bfloat16`` they can differ by about one
+ ``eps``, because the matrix is applied through a matmul while the
+ helper rounds elementwise
- the convention is selected by ``align_corners`` (``True`` by
default). ``False`` is the half-pixel mapping with scale ``2 / size``
and offset ``1 / size - 1``, so that :math:`\pm 1` fall on the outer
@@ -2121,33 +1905,14 @@ def normal_transform_pixel(
:func:`~kornia.geometry.conversions.normal_transform_pixel3d` is still
corner-aligned unconditionally; see the convention warning there
- a singleton axis maps its only pixel to the centre of the normalized
- range. Under ``align_corners=True`` that axis uses scale ``1`` and
- offset ``0`` β€” an invertible extension outside the lone valid
- coordinate, allowing homography composition to handle one-pixel
- source and destination sizes. Under ``align_corners=False`` the
- general formula already lands there (scale ``2``, offset ``0``) and no
- special case is needed. Zero and negative sizes raise ``ValueError``
- - with ``dtype=None`` the matrix is built from Python floats, so it
- takes ``torch.get_default_dtype()``: ``float32`` by default, and
- ``float64`` under ``torch.set_default_dtype(torch.float64)``. An
- explicit ``dtype=`` overrides that
-
- .. warning::
- An integer ``dtype`` is rejected:
- ``normal_transform_pixel(4, 5, dtype=torch.int64)`` raises
- ``ValueError``. The scale ``2 / (size - 1)`` is fractional for every
- dimension larger than 3 pixels, so an integer dtype would truncate it
- to ``0`` and return ``[[0, 0, -1], [0, 0, -1], [0, 0, 1]]``, mapping
- every pixel to the constant ``(-1, -1)``. The accepted dtypes are a
- property of the function rather than of ``height`` and ``width``: a
- dimension of 3 pixels or fewer makes the scale integral, and the
- rejection is uniform rather than depending on the image size. Any
- floating point dtype, including the ``float8`` formats, and any complex
- dtype are accepted. The rejection is unconditional β€” it is not a ``KORNIA_CHECK``, so
- ``disable_checks()``, ``python -O`` and ``KORNIA_CHECKS=0`` do not
- switch it off. One clause of
- `#3959 <https://github.com/kornia/kornia/issues/3959>`_, which stays
- open for the other functions it covers.
+ range: under ``align_corners=True`` with scale ``1`` and offset ``0``,
+ which keeps the matrix invertible for homography composition. Zero
+ and negative sizes raise ``ValueError``
+ - with ``dtype=None`` the matrix takes ``torch.get_default_dtype()``
+ (``float32`` unless the default was changed); an integer or bool
+ ``dtype`` raises ``ValueError``, since the fractional scales would
+ truncate to ``0``, for every size and even under ``disable_checks()``.
+ Every floating and complex dtype is accepted
.. note::
Legacy ``torch.jit.trace`` graphs assume positive runtime sizes because
@@ -2303,14 +2068,8 @@ def normal_transform_pixel3d(
point ``d=7, x=2, y=1`` gives ``[0.75, 1.0, -0.5]`` through the
coordinate helper and ``[1.0, -0.5, 0.75]`` through this matrix β€” so a
grid built for one silently permutes axes when fed to the other
-
- .. warning::
- As in :func:`~kornia.geometry.conversions.normal_transform_pixel`, an
- integer ``dtype`` is rejected: ``normal_transform_pixel3d(2, 4, 5,
- dtype=torch.int64)`` raises ``ValueError`` rather than returning a
- matrix with diagonal ``[0, 0, 2]``. Unconditional and uniform over
- sizes, for the reason given there. One clause of
- `#3959 <https://github.com/kornia/kornia/issues/3959>`_.
+ - an integer or bool ``dtype`` raises ``ValueError``, as in the 2-D
+ function
.. note::
Legacy ``torch.jit.trace`` graphs assume positive runtime sizes for the
@@ -2419,52 +2178,17 @@ def denormalize_homography(
:func:`~kornia.geometry.conversions.normalize_homography`: the
composition is ``inv(N_dst) @ H @ N_src``, so the input maps
normalized source to normalized destination and the output maps
- source pixels to destination pixels. Everything else β€” the
- ``(height, width)`` ``dsize`` tuples, ``dsize_src`` on the right and
- ``dsize_dst`` on the left, ``(x, y, 1)`` column vectors, per-sample
- batching, the ``align_corners``-selected frames β€” is as documented
- there, and so
- is the shape guard: this function carries the same one and rejects
- the same shapes. That function's dtype-pass-through
- (`#3958 <https://github.com/kornia/kornia/issues/3958>`_), int64-handling
- (`#3959 <https://github.com/kornia/kornia/issues/3959>`_ β€” this
- function's own clause there) and ``align_corners`` (`#3904
- <https://github.com/kornia/kornia/issues/3904>`_) warnings apply
- here too. The exception is the closed-form-inverse warning: in eager
- mode this function inverts through ``torch.linalg.inv`` rather than
- through the ``torch.linalg.cross`` adjugate, and under
- ``torch.jit.trace`` through a cofactor expansion that calls neither,
- so it does not have that gap in either mode β€” where it does reach
- ``linalg.inv`` it carries the ``cusolver`` dependency instead
- - both round trips hold, but neither is an exact identity in general.
- Each leg runs four matrix products and **two** inverses β€” one per
- function, and by different routines (see the bullet below) β€” so the
- deviation is a small multiple of the working dtype's eps times the
- largest entry, and the tolerance a caller should hold it to is that
- product rather than a fixed constant. The round trip is **bitwise**
- only when every intermediate product and sum of the chain is exactly
- representable in the working dtype β€” a property of the whole
- computation, not of ``H``'s entries or of the sizes alone, so dyadic
- sizes on their own are **neither necessary nor sufficient**: an ``H``
- with non-dyadic entries at ``2 ** k + 1`` sizes misses in both legs
- in ``float32``, while the ``float64`` identity comes back bitwise
- through both legs at the non-dyadic ``(4, 5) -> (8, 9)``. What does
- hold is the two halves together: in ``float32`` and ``float64`` a
- dyadic-entried ``H`` at ``2 ** k + 1`` sizes comes back bitwise
- through **both** legs, and that is what the pin relies on. In
- ``float16``/``bfloat16`` neither leg is safe once the entries
- grow, and the two legs miss at different rates β€” a precision artifact
- of where the rounding falls, not a structural asymmetry between the
- two directions
- - the two functions do **not** invert their normalization matrix the
- same way, so their errors are not mirror images either: on the
- identity homography with equal sizes ``(4, 7)``,
- :func:`~kornia.geometry.conversions.normalize_homography` deviates
- from the identity by ``5.960464477539063e-08`` while this function
- returns it exactly (torch 2.9.1, cpu β€” both figures come out of a
- matmul chain and an inverse, so which one lands on ``0.0`` is a
- property of the current linalg path, not a contract). Do not read one
- function's residual off the other's
+ source pixels to destination pixels. The ``dsize`` roles, the
+ ``(x, y, 1)`` column vectors, per-sample batching, the
+ ``align_corners``-selected frames and the shape guard are as
+ documented there, and so are its dtype
+ (`#3958 <https://github.com/kornia/kornia/issues/3958>`_) and integer
+ (`#3959 <https://github.com/kornia/kornia/issues/3959>`_) warnings
+ - ``inv(N_dst)`` goes through ``torch.linalg.inv`` in eager mode (so
+ ``cusolver`` on ``cuda``), not through the ``cross``-based adjugate
+ - the two functions invert each other to a small multiple of the
+ working dtype's ``eps`` times the largest entry, not bitwise in
+ general
Args:
dst_pix_trans_src_pix: homography/ies from source to destination to be
@@ -2521,41 +2245,19 @@ def normalize_homography3d(
**not** the 2-D function with wider matrices, though: the shapes, the
missing inverse and β€” least visibly β€” the inversion routine all
differ, as the bullets below record
- - **the two do not invert their normalization matrix by the same
- routine**, and the difference reaches callers. This function inverts
- with ``torch.linalg.inv``;
- :func:`~kornia.geometry.conversions.normalize_homography` inverts with
- a closed-form 3x3 adjugate. Three consequences, none of them
- cosmetic: it needs ``cusolver`` on ``cuda`` β€” which is the dependency
- the 2-D closed form exists to avoid, so a build where
- ``torch.linalg.inv`` fails to load still runs the 2-D function and not
- this one; at ``float16``/``bfloat16`` it upcasts to ``float32``,
- inverts and casts back, where the 2-D route inverts in the working
- dtype β€” so at those dtypes the two routes' inverses of the *same*
- normalization matrix differ, by more than a rounding step, and a
- reduced-precision pipeline should not expect the 2-D and 3-D paths to
- agree; and it does **not** inherit the 2-D route's dependence on a
- ``torch.linalg.cross`` kernel, described in that function's warning.
- :func:`~kornia.geometry.conversions.denormalize_homography` inverts
- the same way this one does in eager mode; under ``torch.jit.trace``
- the 3x3 route falls back to a cofactor expansion and this 4x4 one does
- not
+ - it inverts ``N_src`` with ``torch.linalg.inv`` (so ``cusolver`` on
+ ``cuda``, and a ``float32`` upcast for ``float16``/``bfloat16``),
+ where the 2-D function uses a closed-form adjugate in the working
+ dtype; the 2-D and 3-D routes therefore need not agree bitwise
- the matrices are :math:`(B, 4, 4)` and act on ``(x, y, z, 1)`` column
vectors, while both ``dsize`` arguments are
``(depth, height, width)`` triples
- - there is **no** ``denormalize_homography3d``: the 2-D pair is
- complete, this one is not, so an inverse has to be composed by hand
- from :func:`~kornia.geometry.conversions.normal_transform_pixel3d`.
+ - there is **no** ``denormalize_homography3d``; compose the inverse from
+ :func:`~kornia.geometry.conversions.normal_transform_pixel3d`.
Tracked in `#3962 <https://github.com/kornia/kornia/issues/3962>`_
- - the shape guard is the 2-D function's, with the size adapted: a
- :math:`(4, 4)` or :math:`(B, 4, 4)` matrix and nothing else, an
- unbatched ``(4, 4)`` promoted to ``(1, 4, 4)``, and anything else β€”
- a rank-4 tensor such as ``(2, 4, 4, 4)``, or a ``(B, 3, 3)`` β€”
- rejected with
- ``Input dst_pix_trans_src_pix must be a Bx4x4 tensor``. Both the
- guard's old ``or``-structure and its message, which used to name
- ``Bx3x3`` from a function that takes 4x4 matrices, were fixed in
- `#3999 <https://github.com/kornia/kornia/pull/3999>`_
+ - the shape guard is the 2-D function's for 4x4 matrices: :math:`(4, 4)`
+ (returned as ``(1, 4, 4)``) or :math:`(B, 4, 4)`, anything else raises
+ ``ValueError``
Args:
dst_pix_trans_src_pix: homography/ies from source to destination to be
@@ -2605,7 +2307,10 @@ def normalize_points_with_intrinsics(point_2d: torch.Tensor, camera_matrix: torc
``K = [[100., 0., 320.], [0., 200., 240.], [0., 0., 1.]]`` the pixel
``(420., 440.)`` maps to ``(1., 1.)``
- the skew entry ``K[0, 1]`` is **ignored**; only the two diagonal
- entries and the ``[:2, 2]`` column are read
+ entries and the ``[:2, 2]`` column are read. This is a design choice:
+ kornia's functional pinhole model is zero-skew, like OpenCV's, and
+ :func:`~kornia.geometry.camera.perspective.project_points` reads
+ ``K`` the same way. For a skewed ``K`` apply ``inv(K)`` directly
Args:
point_2d: tensor containing the 2d points in the image pixel coordinates. The shape of the tensor can be
@@ -2698,41 +2403,26 @@ def Rt_to_matrix4x4(R: torch.Tensor, t: torch.Tensor) -> torch.Tensor:
function's
- shapes are strict: exactly :math:`(B, 3, 3)` and :math:`(B, 3, 1)`.
An unbatched ``(3, 3)``, a ``(B, 3)`` translation, a ``(B, 1, 3)``
- translation and extra leading dimensions each raise ``ShapeError``,
- and the two batch sizes must match β€” but not through a kornia guard:
- ``KORNIA_CHECK_SHAPE`` validates each argument on its own, so ``R`` of
- batch 2 with ``t`` of batch 1 reaches ``torch.cat`` and raises
- ``RuntimeError: Sizes of tensors must match except in dimension 2``
- rather than broadcasting, where
- :func:`~kornia.geometry.conversions.camtoworld_to_worldtocam_Rt`
- silently broadcasts the same pair
- - :func:`~kornia.geometry.conversions.matrix4x4_to_Rt` is the inverse,
- and ``Rt -> 4x4 -> Rt`` is bitwise for any ``(R, t)``. The other
- direction is bitwise only for a **canonical** extrinsics matrix, one
- whose bottom row is already ``[0, 0, 0, 1]``: any other bottom row is
- discarded on the way out and rebuilt as ``[0, 0, 0, 1]``, so a matrix
- carrying ``[9, 9, 9, 9]`` β€” or a projective ``[0.1, 0.2, 0.3, 1]`` β€”
- does not survive the trip. That truncation is
- :func:`~kornia.geometry.conversions.matrix4x4_to_Rt`'s, and its block
- documents it
+ translation and extra leading dimensions each raise ``ShapeError``
+ - :func:`~kornia.geometry.conversions.matrix4x4_to_Rt` is the inverse:
+ ``Rt -> 4x4 -> Rt`` is bitwise, while ``4x4 -> Rt -> 4x4`` is bitwise
+ only when the bottom row is already ``[0, 0, 0, 1]``, because
+ :func:`~kornia.geometry.conversions.matrix4x4_to_Rt` drops it
.. warning::
- An ``int64`` ``(R, t)`` pair raises ``RuntimeError: result type Float
- can't be cast to the desired output type Long`` from the appended
- homogeneous row. The two ``camtoworld_*_to_*_Rt`` frame functions are
- built on it and so reject integer input, while their ``_4x4``
- counterparts accept it and return an ``int64`` matrix. The dichotomy is
- not ``_Rt`` versus ``_4x4`` in general:
- :func:`~kornia.geometry.conversions.camtoworld_to_worldtocam_Rt` and
- :func:`~kornia.geometry.conversions.worldtocam_to_camtoworld_Rt` do not
- go through this function β€” they only transpose, negate and multiply β€”
- and accept ``int64`` happily, returning an ``int64`` result. The
- accepting side is a **cpu/mps** statement (torch 2.9.1, executed) β€” no
- accept-and-return-``int64`` behavior is claimed on CUDA, for the
- source-derived reason carried by
- :func:`~kornia.geometry.conversions.camtoworld_graphics_to_vision_4x4`'s
- warning.
- Tracked in `#3959 <https://github.com/kornia/kornia/issues/3959>`_.
+ The batch sizes of ``R`` and ``t`` are not compared by a kornia guard:
+ a mismatch raises from inside ``torch.cat``, while
+ :func:`~kornia.geometry.conversions.camtoworld_to_worldtocam_Rt`
+ broadcasts the same pair. Tracked in
+ `#4774 <https://github.com/kornia/kornia/issues/4774>`_.
+
+ .. warning::
+ Integer input is not guarded: an ``int64`` ``(R, t)`` raises from inside
+ torch here and in the two ``camtoworld_*_Rt`` frame functions built on
+ it, while the ``_4x4`` frame functions and the
+ ``camtoworld_to_worldtocam_Rt`` pair return ``int64`` (on backends with
+ integer batched matmul). Tracked in
+ `#3959 <https://github.com/kornia/kornia/issues/3959>`_.
Args:
R: Rotation matrix, :math:`(B, 3, 3).`
@@ -2824,41 +2514,26 @@ def camtoworld_graphics_to_vision_4x4(extrinsics_graphics: torch.Tensor) -> torc
maps to world ``+y`` before the conversion and to world ``-y`` after
it, and likewise for ``+z``
- the flip **preserves the determinant** of the 3x3 block, and with it
- the handedness: ``diag(1, -1, -1)`` negates two axes and not one, so
- its own determinant is ``+1`` and the product's is whatever came in.
- A proper rotation therefore stays proper (``det = +1`` in, ``+1``
- out) β€” but this is preservation, not a guarantee: an input block with
- ``det = 2`` comes back with ``det = 2``, and an improper one with
- ``det = -1`` stays improper. Nothing here checks that the input is a
+ the handedness: ``diag(1, -1, -1)`` has determinant ``+1``, so a
+ proper rotation stays proper. Nothing here checks that the input is a
rotation
- the flip is an **involution**, and all four graphics/vision frame
functions compute the identical map:
:func:`~kornia.geometry.conversions.camtoworld_vision_to_graphics_4x4`
- returns bitwise the same matrix as this one on the same input, and
- applying either twice returns the input **value-exactly** β€” no
- rounding, every entry compares equal at ``atol = rtol = 0``. Not
- bitwise on a signed zero: the flip is a matmul, so any ``-0.0``
- entry β€” in the flipped columns or not β€” is summed with ``+0.0`` and
- comes back ``+0.0``, on the first application already (executed,
- ``float32`` cpu, torch 2.9.1). The two names
- document the caller's intent, not different arithmetic
+ returns the same matrix as this one on the same input, and applying
+ either twice returns the input. The two names document the caller's
+ intent, not different arithmetic
- the shape is strictly :math:`(B, 4, 4)`; the ``_Rt`` variants take and
return :math:`(B, 3, 3)` and :math:`(B, 3, 1)` and agree with this
path bitwise
.. warning::
- The ``_4x4`` and ``_Rt`` variants disagree on integer input: this
- function accepts an ``int64`` matrix and returns an ``int64`` matrix
- β€” on **cpu/mps** (torch 2.9.1, executed; its integer path runs
- through batched matmul, which PyTorch 2.9.1 implements for no integer
- dtype on CUDA β€” source-derived from that release's
- ``aten/src/ATen/native/cuda/Blas.cpp``, not executed here) β€”
- while
+ Integer input is not guarded: this function returns ``int64`` for an
+ ``int64`` matrix (on backends with integer batched matmul), while
:func:`~kornia.geometry.conversions.camtoworld_graphics_to_vision_Rt`
- raises ``RuntimeError: result type Float can't be cast to the desired
- output type Long`` from
- :func:`~kornia.geometry.conversions.Rt_to_matrix4x4`. Tracked in
- `#3959 <https://github.com/kornia/kornia/issues/3959>`_.
+ raises from inside torch. Tracked in
+ `#3959 <https://github.com/kornia/kornia/issues/3959>`_; see
+ :func:`~kornia.geometry.conversions.Rt_to_matrix4x4`.
Args:
extrinsics_graphics: pose matrix :math:`(B, 4, 4)`.
@@ -2902,12 +2577,10 @@ def camtoworld_graphics_to_vision_Rt(R: torch.Tensor, t: torch.Tensor) -> tuple[
function and splits the result again, so the two paths agree bitwise.
Only the lines below differ
- the shapes are strictly :math:`(B, 3, 3)` and :math:`(B, 3, 1)` in and
- out, with no broadcasting between the two batch sizes, as
- :func:`~kornia.geometry.conversions.Rt_to_matrix4x4` requires
+ out; the batch-size and integer-input warnings of
+ :func:`~kornia.geometry.conversions.Rt_to_matrix4x4` apply
- ``t`` is returned unchanged; only ``R`` has its second and third
columns negated
- - unlike the ``_4x4`` form, integer input raises β€” see that function's
- warning
Args:
R: Rotation matrix, :math:`(B, 3, 3).`
@@ -2995,8 +2668,7 @@ def camtoworld_vision_to_graphics_Rt(R: torch.Tensor, t: torch.Tensor) -> tuple[
:func:`~kornia.geometry.conversions.camtoworld_graphics_to_vision_Rt`.
The canonical block lives on
:func:`~kornia.geometry.conversions.camtoworld_graphics_to_vision_4x4`
- - the shapes are strictly :math:`(B, 3, 3)` and :math:`(B, 3, 1)` in and
- out, ``t`` is returned unchanged, and integer input raises β€” as in the
+ - the shapes, the unchanged ``t`` and the warnings are as in the
graphics-to-vision ``_Rt`` form
Args:
@@ -3034,57 +2706,33 @@ def camtoworld_to_worldtocam_Rt(R: torch.Tensor, t: torch.Tensor) -> tuple[torch
world-to-camera extrinsics and camera-centre semantics.
- the returned pair is exactly ``(R^T, -R^T @ t)`` β€” the **rigid**
- inverse, computed by transposition and never by a matrix inverse. For
- a proper rotation that is the true inverse as a map, and in floating
- point it recovers the identity to the working dtype's rounding rather
- than bitwise: packing both pairs with
- :func:`~kornia.geometry.conversions.Rt_to_matrix4x4` and multiplying
- gives ``max|M_inv @ M - I|`` at the ``1e-07`` scale in ``float32``
- and ``1e-15`` in ``float64``, over 64 unit-normalized random
- quaternions turned into rotations via
- :func:`~kornia.geometry.conversions.quaternion_to_rotation_matrix`
- β€” an orthogonality-preserving route, as is
- :func:`~kornia.geometry.conversions.axis_angle_to_rotation_matrix`
- β€” with matching random translations, both
- drawn from ``torch.Generator().manual_seed(seed)``, ``seed=0`` β€” a
- few ulps of the entries. Read the exponent, not the digits: the
- maximum moves with the draw (``4.77e-07`` to ``8.34e-07``, and
- ``6.66e-16`` to ``1.33e-15``, over ``seed`` ``0`` through ``5`` of
- the same sweep; torch 2.9.1, cpu). ``torch.equal`` against the
- identity is ``False``
+ inverse, computed by transposition and never by a matrix inverse, so
+ for a proper rotation it inverts the pose to the working dtype's
+ rounding
- what ``t`` means on each side: the input is a camera-to-world pose, so
its ``t`` is the **camera centre in world coordinates** (the 4x4 sends
the origin to ``t``); the returned ``-R^T t`` is the **world-to-camera
translation** of Colmap's ``images.txt`` (the returned 4x4 sends the
camera centre to the origin)
- :func:`~kornia.geometry.conversions.worldtocam_to_camtoworld_Rt` is
- the **same function**, not a separate formula: it returns bitwise
- identical outputs on the same input. Applying either one twice
- returns ``R`` **bitwise** β€” transposing twice moves no bits β€” but the
- translation only to rounding, since it costs two matrix products:
- over the same ``seed=0`` draw of 64 poses ``t`` comes back to
- ``9.54e-07`` in ``float32`` and ``1.78e-15`` in ``float64``. The two
- names record which direction the caller means
- - the shapes are :math:`(B, 3, 3)` and :math:`(B, 3, 1)`, but ``t`` is
- **broadcast** across the ``R`` batch: ``R`` of batch 2 with ``t`` of
- batch 1 returns ``(2, 3, 3)`` and ``(2, 3, 1)``, where
- :func:`~kornia.geometry.conversions.Rt_to_matrix4x4` raises on the
- same pair
+ the **same function** under the other name: applying either one twice
+ returns ``R`` exactly and ``t`` to rounding
+ - the shapes are :math:`(B, 3, 3)` and :math:`(B, 3, 1)`
.. warning::
``R`` is **assumed** to be a rotation and this is never checked, so for
- a non-orthogonal ``R`` the result is a transpose and not an inverse, and
- it is wrong silently. With
- ``R = [[1, 0.5, 0], [0, 1, 0], [0, 0, 2]]`` (``det = 2``) and
- ``t = (1, 2, 3)``, the composed 4x4 gives
- ``max|M_inv @ M - I| = 3.0`` β€” over six orders of magnitude above the
- ``float32`` figure quoted in the bullet above β€” and even the round trip
- through this function and back leaves ``t`` off by ``9.0``, while ``R``
- still returns bitwise because that leg is only a double transpose. The
- near-identity of the bullet above holds only because ``R`` was a
- rotation there. Tracked in
+ a non-orthogonal ``R`` the result is a transpose and not an inverse,
+ silently: ``R = [[1, 0.5, 0], [0, 1, 0], [0, 0, 2]]`` gives
+ ``max|M_inv @ M - I| = 3.0``. Tracked in
`#3961 <https://github.com/kornia/kornia/issues/3961>`_.
+ .. warning::
+ The batch sizes of ``R`` and ``t`` are not checked: ``t`` is broadcast
+ across ``R``, where :func:`~kornia.geometry.conversions.Rt_to_matrix4x4`
+ raises, and ``R`` of batch 1 with ``t`` of batch 2 returns outputs of
+ different batch sizes. Tracked in
+ `#4774 <https://github.com/kornia/kornia/issues/4774>`_.
+
Args:
R: Rotation matrix, :math:`(B, 3, 3).`
t: Translation matrix :math:`(B, 3, 1)`.
@@ -3119,18 +2767,15 @@ def worldtocam_to_camtoworld_Rt(R: torch.Tensor, t: torch.Tensor) -> tuple[torch
See :doc:`camera and world conventions </get-started/camera-conventions>` for camera-to-world versus
world-to-camera extrinsics and camera-centre semantics.
- - bitwise the **same function** as
+ - the **same function** as
:func:`~kornia.geometry.conversions.camtoworld_to_worldtocam_Rt`,
which carries the canonical block: for a proper rotation
- ``(R^T, -R^T @ t)`` is its own inverse as a map β€” to the working
- dtype's rounding in floating point, measured there β€” so one name
- serves both directions and the choice is documentation for the
- reader
+ ``(R^T, -R^T @ t)`` is its own inverse, so one name serves both
+ directions and the choice is documentation for the reader
- read the other way round here: the input ``t`` is the world-to-camera
translation and the returned ``-R^T t`` is the camera centre in world
coordinates
- - the broadcasting behaviour, the shapes and the unchecked-orthogonality
- warning are as documented there
+ - the shapes and both warnings are as documented there
Args:
R: Rotation matrix, :math:`(B, 3, 3).`
@@ -3168,115 +2813,44 @@ def ARKitQTVecs_to_ColmapQTVecs(qvec: torch.Tensor, tvec: torch.Tensor) -> tuple
See :doc:`camera and world conventions </get-started/camera-conventions>` for the camera frames and
extrinsics conventions composed by this conversion.
- (every measured figure in this block β€” the 16-digit "as computed"
- literals included β€” is a sample of one build, torch 2.9.1 on cpu, not
- a bound; trailing digits and turnover points may move with the
- backend's accumulation order)
-
- - **input**: ``qvec`` :math:`(B, 4)` is read as ``(w, x, y, z)``, real
- part first β€” ``[1., 0., 0., 0.]`` is the identity β€” and ``tvec`` is
- :math:`(B, 3, 1)`. The pair is interpreted as a **camera-to-world**
- pose in the **graphics** frame (``+y`` up, ``-z`` forward), so ``tvec``
- is the camera centre in world coordinates
- - **output**: ``(q, t)`` with ``q`` :math:`(B, 4)` again in
- ``(w, x, y, z)`` and ``t`` :math:`(B, 3, 1)`, forming a
- **world-to-camera** pose in the **vision** frame (``+y`` down, ``+z``
- forward) β€” Colmap's ``images.txt`` ``QW QX QY QZ TX TY TZ``. The
- composed pipeline is
+ - **input**: ``qvec`` :math:`(B, 4)` in ``(w, x, y, z)`` order β€”
+ ``[1., 0., 0., 0.]`` is the identity β€” and ``tvec`` :math:`(B, 3, 1)`,
+ read as a **camera-to-world** pose in the **graphics** frame (``+y``
+ up, ``-z`` forward), so ``tvec`` is the camera centre in world
+ coordinates
+ - **output**: ``(q, t)`` in the same layouts, a **world-to-camera** pose
+ in the **vision** frame (``+y`` down, ``+z`` forward) β€” Colmap's
+ ``images.txt`` ``QW QX QY QZ TX TY TZ``. The pipeline is
:func:`~kornia.geometry.conversions.quaternion_to_rotation_matrix`,
- then
:func:`~kornia.geometry.conversions.camtoworld_graphics_to_vision_Rt`,
- then :func:`~kornia.geometry.conversions.camtoworld_to_worldtocam_Rt`,
- then
- :func:`~kornia.geometry.conversions.rotation_matrix_to_quaternion` on
- the resulting matrix β€” that last step is what turns the ``(R, t)`` of
- the third function into the documented ``(q, t)``, and it is the
- source of the sign/branch behavior the bullets below describe
- - a caller reading ARKit directly must **reorder the quaternion first**:
- Apple's ``simd_quatf`` exposes ``.vector`` as ``(ix, iy, iz, r)``, i.e.
- ``xyzw``, which this function would read as ``wxyz`` and silently
- accept. (Apple's layout is cited from its API documentation, not
- executed here; the ``wxyz`` reading on kornia's side is executed)
- - the input quaternion need not be unit, **within a bounded range
- of** ``||q||``: rescaling it moves the resulting pose only by the working
- dtype's rounding as long as ``||q||`` stays **above**
- :func:`~kornia.geometry.conversions.normalize_quaternion`'s
- effective floor (``eps = 1e-12``, raised to the smallest positive
- subnormal in ``float16``) and **below** the point at which the norm's
- sum-of-squares accumulator overflows. Over 64 random unit
- quaternions rescaled by factors from ``1e-3`` to ``1e5``, the output
- rotation and translation moved at the ``1e-06`` scale in ``float32``
- β€” a few ulps of their entries, with the maximum moving from draw to
- draw, so this is an order of magnitude and not a bound. ``q`` and
- ``-q`` give bitwise the same output at every scale tried, since they
- are the same rotation
- - **past either end the pose changes outright, silently.** Below the
- floor the normalisation clamp takes over, as
- :func:`~kornia.geometry.conversions.quaternion_to_rotation_matrix`
- documents. One worked sub-floor input carries all the figures: in
- ``float64``, scaling ``[0.5, 0.5, 0.5, 0.5]`` by ``1e-13`` moves the
- output rotation by order ``1`` (``0.9999746262218625``) and, with
- ``t = (1, 2, 3)``, the translation by ``1.98`` (the worked example's
- ``t = (1, 1, 1)`` lies on this quaternion's rotation axis and its
- translation happens to move by exactly ``0``); the same input builds
- an internal matrix with ``det = 0.9703`` and orthogonality error
- ``0.0198`` (rounded; ``0.9702999999999999`` and
- ``0.01980000000000004`` as computed) and returns a quaternion of
- norm ``0.9962524249343686``, not ``1``. Above the
- ceiling the norm overflows to ``inf`` and the quaternion normalises to
- zero, which this function then reads as the identity: in ``float32``
- the perfectly finite ``[0., 1., 0., 1.] * 1.4e19`` returns
- ``q = [0., 1., 0., 0.]``, ``t = (-1., 1., 1.)`` β€” the zero-quaternion
- answer β€” instead of the ``[0.7071, 0., 0.7071, 0.]``,
- ``(-1., -1., 1.)`` of the same rotation at unit scale. The ceiling
- sits where ``||q||`` overflows the norm's sum-of-squares
- accumulator: the same ``sqrt(finfo.max)`` turnover, per-dtype
- figures and ``float16`` wider-accumulation exception that
- :func:`~kornia.geometry.conversions.quaternion_log_to_exp`'s block
- quantifies β€” the figures live there, once
- - for ``||q||`` above the normalisation floor of the previous bullet,
- the output rotation is **proper by construction** β€” it is built from
- an internally normalised quaternion and then right-multiplied by
- ``diag(1, -1, -1)``, which negates two axes and not one β€” so
- **handedness is preserved** and ``det`` is ``+1`` up to the working
- dtype's rounding: over 512 random quaternions the largest
- ``|det - 1|`` sits at the ``1e-06`` scale in ``float32`` and
- ``1e-15`` in ``float64`` (``7.15e-07`` to ``8.34e-07`` and
- ``1.78e-15`` to ``2e-15`` over four seeds β€” again the exponent, not
- the digits). It is the construction that guarantees
- properness; the digits are just arithmetic. Below the floor the
- construction's premise fails β€” the clamp leaves the internal
- quaternion non-unit β€” and the guarantee with it; the previous
- bullet's sub-floor input carries the measured ``det``, orthogonality
- and norm figures
- - the **sign of the output quaternion is not canonical**. It is whichever
+ :func:`~kornia.geometry.conversions.camtoworld_to_worldtocam_Rt`, then
+ :func:`~kornia.geometry.conversions.rotation_matrix_to_quaternion`
+ - ARKit's ``simd_quatf`` exposes ``.vector`` as ``(ix, iy, iz, r)``, i.e.
+ ``xyzw``: reorder it to ``wxyz`` first, since this function accepts
+ either order silently
+ - the input quaternion need not be unit and ``q`` and ``-q`` give the
+ same output, as long as ``||q||`` stays above the ``eps = 1e-12``
+ normalisation floor and its squared norm does not overflow (about
+ ``1.8e19`` in ``float32``); outside that range the result is the
+ zero-quaternion answer of the warning below or a wrong pose
+ - the **sign of the output quaternion is not canonical**: it is the
representative
:func:`~kornia.geometry.conversions.rotation_matrix_to_quaternion`'s
- branch produces: the
- unit input ``[0.5, 0.5, 0.5, 0.5]`` with ``t = (1, 2, 3)`` returns
- ``q = [-0.5, -0.5, -0.5, 0.5]`` (a zero-trace rotation, so the
- positive-trace branch does not apply) together with
- ``t = (-2, 3, 1)``. Compare rotations, never raw components
- - worked literal, hand-computed independently of kornia:
- ``q = [0., 1., 0., 1.]``, ``t = (1, 1, 1)`` gives
- ``q = [0.7071, 0., 0.7071, 0.]`` and ``t = (-1, -1, 1)``, which is the
- example below
- - there is **no** ``ColmapQTVecs_to_ARKitQTVecs``, so the conversion
- cannot be round-tripped through the public API; the inverse has to be
- composed from
- :func:`~kornia.geometry.conversions.worldtocam_to_camtoworld_Rt` and
- :func:`~kornia.geometry.conversions.camtoworld_vision_to_graphics_Rt`.
+ branch produces, so ``[0.5, 0.5, 0.5, 0.5]`` with ``t = (1, 2, 3)``
+ returns ``q = [-0.5, -0.5, -0.5, 0.5]`` and ``t = (-2, 3, 1)``.
+ Compare rotations, never raw components
+ - worked literal: ``q = [0., 1., 0., 1.]``, ``t = (1, 1, 1)`` gives
+ ``q = [0.7071, 0., 0.7071, 0.]`` and ``t = (-1, -1, 1)``, the example
+ below
+ - there is **no** ``ColmapQTVecs_to_ARKitQTVecs``; compose the inverse
+ from :func:`~kornia.geometry.conversions.worldtocam_to_camtoworld_Rt`
+ and :func:`~kornia.geometry.conversions.camtoworld_vision_to_graphics_Rt`.
Tracked in `#3962 <https://github.com/kornia/kornia/issues/3962>`_
.. warning::
- The all-zero quaternion is never rejected. At every floating dtype, the
- internal normalisation floor absorbs it: ``torch.zeros(1, 4)`` with
- ``t = (1, 1, 1)`` returns the plausible-looking
- ``q = [0., 1., 0., 0.]``, ``t = (-1, 1, 1)`` in ``float32`` β€” the same
- answer as the identity input β€” rather than raising. Validate the
- quaternion before calling if the input may be degenerate. This is the
- downstream reach of the sub-``eps`` clamp in
- :func:`~kornia.geometry.conversions.normalize_quaternion`. Tracked in
+ The zero quaternion is not rejected: ``torch.zeros(1, 4)`` with
+ ``t = (1, 1, 1)`` returns ``q = [0., 1., 0., 0.]``, ``t = (-1, 1, 1)``,
+ the same answer as the identity input. Tracked in
`#3952 <https://github.com/kornia/kornia/issues/3952>`_.
Args:
diff --git a/tests/geometry/test_conversions.py b/tests/geometry/test_conversions.py
index 17aeaf1ce..167bb5845 100644
--- a/tests/geometry/test_conversions.py
+++ b/tests/geometry/test_conversions.py
@@ -17,8 +17,6 @@
import dis
import inspect
-import platform
-import sys
import warnings
from collections.abc import Iterator
from contextlib import contextmanager
@@ -30,7 +28,6 @@ import pytest
import torch
import kornia
-from kornia.core._compat import torch_version, torch_version_lt
from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SHAPE, are_checks_enabled, disable_checks, enable_checks
from kornia.core.exceptions import BaseError, ShapeError
from kornia.core.ops import eye_like
@@ -133,48 +130,9 @@ def _skip_if_dtype_unavailable(device: torch.device, dtype: torch.dtype) -> None
pytest.skip(f"{dtype} is unavailable on device {device}: {allocation_error}")
-def _agreement_gap_at_2_28(device: torch.device, dtype: torch.dtype) -> float:
- # max|normalize_pixel_coordinates(grid) - matrix @ grid| over the full pixel grid of a
- # (2, 28) image -- the size pair behind normal_transform_pixel's agreement bullet, chosen
- # because 2/(28 - 1) is not exactly representable in reduced precision. Shared by the two pins
- # that read it (the dtype-scaled bound and the exact kernel measurement) so they cannot measure
- # subtly different things.
- # The grid is built from an int64 arange cast down afterwards, not a typed arange: `arange_mps`
- # has no bfloat16 kernel on torch 2.5.1 (executed; torch 2.9.1 has one) and would raise
- # instead of measuring.
- rows, columns = 2, 28
- y_grid, x_grid = torch.meshgrid(
- torch.arange(rows, device=device).to(dtype),
- torch.arange(columns, device=device).to(dtype),
- indexing="ij",
- )
- grid = torch.stack([x_grid.reshape(-1), y_grid.reshape(-1)], dim=-1)[None]
-
- via_helper = kornia.geometry.conversions.normalize_pixel_coordinates(grid, rows, columns)[0]
- matrix = kornia.geometry.conversions.normal_transform_pixel(rows, columns, device=device, dtype=dtype)
- homogeneous = torch.cat([grid[0], torch.ones_like(grid[0][:, :1])], dim=-1)
- via_matrix = (matrix[0] @ homogeneous.transpose(0, 1)).transpose(0, 1)[:, :2]
-
- # .float() because the difference of two bfloat16 values is not representable in bfloat16.
- return (via_helper.float() - via_matrix.float()).abs().max().item()
-
-
def _matmul_input_eps(device: torch.device, dtype: torch.dtype) -> float:
- # eps of the precision a matmul rounds its INPUTS to, which is not always the working dtype's:
- # on cuda a float32 matmul can be configured to round its inputs to TF32, 10 explicit mantissa
- # bits instead of 23. This suite can be run that way -- conftest.py's --tf32 / KORNIA_TEST_TF32
- # calls torch.set_float32_matmul_precision("high"), and executed here, both "high" and "medium"
- # leave torch.backends.cuda.matmul.allow_tf32 True (torch 2.9.1). The bound below is scaled by
- # this rather than by finfo(dtype).eps so that such a run widens it instead of reporting a red
- # test for a configuration change that touched no kornia code: the matrix route is a matmul
- # while the helper route stays in the working dtype, so it is exactly the leg a
- # reduced-precision mode rounds more coarsely.
- # Scoped to cuda because that is where the mode applies: executed on cpu, the (2, 28) gap is
- # identical under "highest", "high" and "medium" at all four dtypes, so widening the cpu bound
- # would only lose resolution. TF32's mantissa width is the documented format rather than a
- # measurement -- no CUDA device was available in this branch -- so this arm is a guard against
- # an unmeasured configuration, not a claim about one; a measured cuda figure belongs in the
- # wart pin's table below.
+ # eps of the precision a matmul rounds its INPUTS to: TF32 (10 mantissa bits) for a cuda
+ # float32 matmul under --tf32, otherwise the working dtype's.
if device.type == "cuda" and dtype == torch.float32 and torch.backends.cuda.matmul.allow_tf32:
return 2.0**-10
return torch.finfo(dtype).eps
@@ -329,12 +287,9 @@ def test_skip_probe_re_raises_everything_it_cannot_identify(monkeypatch):
assert_the_injected_failure_propagates("D, cross unavailable too")
-# The four deprecated aliases of this module, as (deprecated name, replacement name, call input).
-# One table serves all three pins that iterate them -- the alias-forwarding pin in
-# TestAngleAxisToQuaternion and the two module-level kornia#3956 pins at the end of this file -- so
-# that a fifth alias, or a retired one, is a one-line edit in one place. The third column is a call
-# INPUT, not a pinned expected value: each pin computes its own expectation from it, so sharing the
-# table shares no literal.
+# The four deprecated aliases of this module, as (deprecated name, replacement name, call input),
+# shared by the alias-forwarding pin in TestAngleAxisToQuaternion and the two module-level
+# kornia#3956 pins at the end of this file.
_DEPRECATED_ALIASES = [
("angle_axis_to_rotation_matrix", "axis_angle_to_rotation_matrix", [[0.1, 0.2, 0.3]]),
(
@@ -350,11 +305,6 @@ _DEPRECATED_ALIASES = [
("angle_axis_to_quaternion", "axis_angle_to_quaternion", [0.1, 0.2, 0.3]),
]
-# The projection the two module-level kornia#3956 pins parametrize over -- both read the alias name
-# and the call input and neither reads the replacement -- plus the ids both label their cells with.
-# Written once here rather than at each decorator: the table above being maintained in one place is
-# only true if what is derived from it is too, and an id suffix added to one copy of a duplicated
-# comprehension drifts silently from the other.
_DEPRECATED_ALIAS_NAMES_AND_ARGS = [(alias_name, arg) for alias_name, _, arg in _DEPRECATED_ALIASES]
_DEPRECATED_ALIAS_IDS = [row[0] for row in _DEPRECATED_ALIASES]
@@ -479,24 +429,13 @@ def test_guard_classifier_reads_the_raising_instruction():
)
-# The wrong-sized-matrix cells for the kornia#3960 convention pin: (op name, wrong square size).
-# Module-level rather than inline because a fourth op (a denormalize_homography3d per kornia#3962,
-# say) becomes a one-line edit that reaches the wrong-size pin and the rank pin together instead of
-# landing in one and not the other. The sizes helper lives here for the same reason.
-# These are call INPUTS, not pinned expected values: the pin computes its own verdict from them.
+# The kornia#3960 shape-guard cells: (op name, wrong square size).
_WRONG_SIZE_CASES = [
("normalize_homography", 4),
("denormalize_homography", 4),
("normalize_homography3d", 3),
]
-# Derived, not a second hand-maintained list: a length mismatch would fail at collection, but a
-# reorder of the table above would silently relabel the cells (a `[denormalize]` id reporting a
-# normalize_homography failure). Yields ["normalize", "denormalize", "normalize3d"] today.
_WRONG_SIZE_IDS = [op_name.replace("_homography", "") for op_name, _ in _WRONG_SIZE_CASES]
-# The same three ops as _WRONG_SIZE_CASES, without the per-op wrong size: the rank pin below
-# derives its own sizes from the op name and only needs the names. Derived from the table above
-# rather than written out again so a fourth op reaches both pins from one edit.
-_HOMOGRAPHY_OP_NAMES = [op_name for op_name, _ in _WRONG_SIZE_CASES]
def _homography_sizes(op_name: str) -> tuple[tuple[int, ...], tuple[int, ...]]:
@@ -702,32 +641,39 @@ class TestAngleAxisToQuaternion(BaseTester):
expected = torch.tensor((np.cos(0.5), np.sin(0.5), 0.0, 0.0), device=device, dtype=input_dtype)
self.assert_close(quaternion, expected, atol=1.0e-2, rtol=1.0e-2)
- def test_convention_the_guarded_sqrt_moves_no_forward_value_3949(self, device, dtype):
- # The #3949 fix is a BACKWARD-pass fix: away from theta == 0 the guarded sqrt must return
- # the very same BITS as the plain `sqrt(theta_squared)` formula it replaced, so no existing
- # forward value moves. torch.equal, not assert_close, for exactly that reason -- a
- # tolerance would hide the reassociation this pin exists to rule out.
- # The fourth row is the near-singular one, and it is derived from the dtype rather than
- # written as a literal: a fixed 1e-9 UNDERFLOWS to 0 at float16 (its smallest subnormal is
- # 5.96e-8), which puts the row on the guarded side of the branch, makes the reference
- # formula's own sin(0)/0 a NaN, and fails this pin under `pixi run test-half` while passing
- # everywhere else. finfo(dtype).eps squares to something representable in all four dtypes,
- # so the row stays near-singular AND stays on the unguarded side in each.
- # Companion: test_convention_gradients_at_the_identity_are_finite_3949 covers theta == 0
- # itself, where the two formulas deliberately DISAGREE.
- near_singular = torch.finfo(dtype).eps
- axis_angle = torch.tensor(
- ((0.1, 0.2, 0.3), (1.0, 0.0, 0.0), (3.0, -2.0, 0.5), (near_singular, 0.0, 0.0)),
- device=device,
- dtype=dtype,
- )
- a0, a1, a2 = axis_angle[..., 0:1], axis_angle[..., 1:2], axis_angle[..., 2:3]
- theta = torch.sqrt(a0 * a0 + a1 * a1 + a2 * a2)
- half_theta = theta * 0.5
- k = torch.sin(half_theta) / theta
- expected = torch.cat((torch.cos(half_theta), a0 * k, a1 * k, a2 * k), dim=-1)
- quaternion = kornia.geometry.conversions.axis_angle_to_quaternion(axis_angle)
- assert torch.equal(quaternion, expected)
+ @pytest.mark.parametrize("op_name", ["axis_angle_to_quaternion", "quaternion_to_axis_angle"])
+ def test_convention_the_guarded_sqrt_moves_no_forward_value_3949(self, device, dtype, op_name):
+ # The #3949 guard is backward-only: away from the zero rotation both directions return the
+ # same bits as the unguarded formula, so torch.equal rather than a tolerance. The last row
+ # is near-singular; finfo(dtype).eps keeps it on the unguarded side at every dtype, where a
+ # fixed 1e-9 would underflow to 0 in float16. The zero rotation itself is pinned by
+ # test_convention_gradients_at_the_identity_are_finite_3949.
+ eps = torch.finfo(dtype).eps
+ if op_name == "axis_angle_to_quaternion":
+ x = torch.tensor(
+ ((0.1, 0.2, 0.3), (1.0, 0.0, 0.0), (3.0, -2.0, 0.5), (eps, 0.0, 0.0)), device=device, dtype=dtype
+ )
+ a0, a1, a2 = x[..., 0:1], x[..., 1:2], x[..., 2:3]
+ theta = torch.sqrt(a0 * a0 + a1 * a1 + a2 * a2)
+ half_theta = theta * 0.5
+ k = torch.sin(half_theta) / theta
+ expected = torch.cat((torch.cos(half_theta), a0 * k, a1 * k, a2 * k), dim=-1)
+ else:
+ x = torch.tensor(
+ ((0.9, 0.1, 0.2, 0.3), (0.0, 1.0, 0.0, 0.0), (0.5, 3.0, -2.0, 0.5), (1.0, eps, 0.0, 0.0)),
+ device=device,
+ dtype=dtype,
+ )
+ cos_theta = x[..., 0]
+ q1, q2, q3 = x[..., 1], x[..., 2], x[..., 3]
+ sin_theta = torch.sqrt(q1 * q1 + q2 * q2 + q3 * q3)
+ two_theta = 2.0 * torch.where(
+ cos_theta < 0.0, torch.atan2(-sin_theta, -cos_theta), torch.atan2(sin_theta, cos_theta)
+ )
+ k = two_theta / sin_theta
+ expected = torch.stack((q1 * k, q2 * k, q3 * k), dim=-1)
+
+ assert torch.equal(getattr(kornia.geometry.conversions, op_name)(x), expected)
def test_gradcheck(self, device):
dtype = torch.float64
@@ -786,23 +732,12 @@ class TestAngleAxisToQuaternion(BaseTester):
)
def test_convention_axis_angle_quaternion_roundtrip_is_exact_in_float64(self, device):
- # Convention pin: axis_angle_to_quaternion and quaternion_to_axis_angle are exact inverses
- # in float64 over the whole [0, pi] range, including the two singular points theta = 0 and
- # theta = pi. This is what separates the quaternion leg from the matrix leg: the same
- # round-trip through axis_angle_to_rotation_matrix is only accurate to ~1e-6 even in
- # float64 (see TestRotationMatrixToAngleAxis.test_convention_axis_angle_roundtrip_
- # tolerance_is_1e_6_in_float64), so "the round-trip is exact" is a statement about this
- # pair only. float64 is hardcoded and the dtype fixture dropped because exactness is a
- # float64-only claim; MPS is skipped visibly because it has no float64 at all.
+ # axis_angle_to_quaternion and quaternion_to_axis_angle are inverses to roundoff in float64
+ # over [0, pi], including the singular points theta = 0 and theta = pi. Measured max error
+ # at these four rows: 2.2e-19 (torch, cpu float64); 1e-12 leaves margin for other backends.
# Snippet used to generate the inputs (stdlib only):
- # import math
# n = math.sqrt(14.0); axis = (1 / n, 2 / n, 3 / n)
# [[theta * a for a in axis] for theta in (0.0, 1e-3, 0.7, math.pi)]
- # Measured max |roundtrip - input| at those four thetas (torch 2.9.1, cpu float64):
- # 0.0, 2.168404344971009e-19, 0.0, 0.0 -- so atol 1e-12 is ~7 orders above the worst
- # observed error and ~6 orders below the 1e-6 the matrix leg would give. 1e-12 rather
- # than something tighter because this composes two atan2/sqrt chains and no CUDA job
- # exists to tell us what they cost there.
_skip_if_dtype_unavailable(device, torch.float64)
axis_angle = torch.tensor(
@@ -822,33 +757,10 @@ class TestAngleAxisToQuaternion(BaseTester):
self.assert_close(roundtrip, axis_angle, atol=1e-12, rtol=0.0)
- # Convention pin for the four deprecated aliases (they have no test class and no docstring of
- # their own; this class is named after one of them). Each still works and is a thin wrapper:
- # it emits a DeprecationWarning naming both the old and the new symbol, and returns output
- # that is bit-identical to the replacement's. The replacement, not the alias, is where the
- # Convention block lives.
- # The call is wrapped in warnings.catch_warnings() because invoking a kornia deprecated symbol
- # rewrites the process-global DeprecationWarning filters; pytest.warns alone does not restore
- # them, so without the wrapper this pin would leak filter state into every later test.
- # Snippet used to generate expected (torch only):
- # import warnings, kornia.geometry.conversions as C
- # with warnings.catch_warnings(record=True) as w:
- # warnings.simplefilter("always")
- # out = C.angle_axis_to_quaternion(torch.tensor([0.1, 0.2, 0.3]))
- # w[0].category, str(w[0].message) -> DeprecationWarning, 'Since kornia 0.7.0 the
- # `angle_axis_to_quaternion` is deprecated in favor of `axis_angle_to_quaternion`.'
- # torch.equal(out, C.axis_angle_to_quaternion(torch.tensor([0.1, 0.2, 0.3]))) -> True
- # The cases come from the module-level _DEPRECATED_ALIASES table, shared with the two #3956 pins
- # at the end of this file. The dtype fixture stays: alias == replacement is a contract about
- # whatever the two implementations are, not about today's one-line forward -- a future rewrite
- # that kept a frozen copy behind the alias could diverge at a single dtype, and only a leg at
- # that dtype would see it. The comparison is
- # torch.testing.assert_close at rtol=atol=0 (exact, and it checks shape/dtype/device itself)
- # rather than torch.equal, which reports no per-element diff on a mismatch. NaN is excluded
- # outright by the assertion above the comparison rather than tolerated through equal_nan=True:
- # all four rows are finite at every dtype today, so equal_nan could only ever matter for an
- # alias and a replacement that BOTH regressed to NaN, which is a pass this pin should not
- # hand out.
+ # Convention pin for the four deprecated aliases: each emits a DeprecationWarning naming the
+ # old and the new symbol and returns exactly the replacement's output, at every dtype.
+ # catch_warnings + simplefilter("always") makes the warning observable regardless of the
+ # suite's filters; NaN is rejected outright so two NaN outputs cannot count as a match.
@pytest.mark.parametrize(("deprecated_name", "replacement_name", "arg"), _DEPRECATED_ALIASES)
def test_convention_deprecated_alias_warns_and_matches_replacement(
self, device, dtype, deprecated_name, replacement_name, arg
@@ -903,7 +815,7 @@ class TestAngleAxisToQuaternion(BaseTester):
# input (quaternion_to_axis_angle at q = (1,0,0,0), axis_angle_to_quaternion at aa = (0,0,0)).
# The fix keeps the singular point away from the sqrt with a `where` on the radicand rather
# than clamping it, so the forward value at the identity is unchanged -- pinned separately
- # by test_convention_the_guarded_sqrt_moves_no_forward_value_3949 in each class.
+ # by test_convention_the_guarded_sqrt_moves_no_forward_value_3949.
# Three claims per cell, in order:
# (1) the gradient is finite -- the #3949 headline;
# (2) it equals the analytic value from _IDENTITY_GRADIENT_CASES, so a merely-finite
@@ -1053,33 +965,6 @@ class TestQuaternionToAngleAxis(BaseTester):
axis_angle = kornia.geometry.conversions.quaternion_to_axis_angle(quaternion)
self.assert_close(axis_angle, expected, atol=atol, rtol=rtol)
- def test_convention_the_guarded_sqrt_moves_no_forward_value_3949(self, device, dtype):
- # The quaternion_to_axis_angle half of the pin documented on
- # TestAngleAxisToQuaternion.test_convention_the_guarded_sqrt_moves_no_forward_value_3949 --
- # same claim, same reason the near-singular row is derived from finfo(dtype).eps rather
- # than written as a fixed 1e-9, which underflows to 0 at float16. Kept in this class rather
- # than as a third cell of that one because the reference formula is a different expression.
- quaternion = torch.tensor(
- (
- (0.9, 0.1, 0.2, 0.3),
- (0.0, 1.0, 0.0, 0.0),
- (0.5, 3.0, -2.0, 0.5),
- (1.0, torch.finfo(dtype).eps, 0.0, 0.0),
- ),
- device=device,
- dtype=dtype,
- )
- cos_theta = quaternion[..., 0]
- q1, q2, q3 = quaternion[..., 1], quaternion[..., 2], quaternion[..., 3]
- sin_theta = torch.sqrt(q1 * q1 + q2 * q2 + q3 * q3)
- two_theta = 2.0 * torch.where(
- cos_theta < 0.0, torch.atan2(-sin_theta, -cos_theta), torch.atan2(sin_theta, cos_theta)
- )
- k = two_theta / sin_theta
- expected = torch.stack((q1 * k, q2 * k, q3 * k), dim=-1)
- axis_angle = kornia.geometry.conversions.quaternion_to_axis_angle(quaternion)
- assert torch.equal(axis_angle, expected)
-
def test_gradcheck(self, device):
dtype = torch.float64
eps = torch.finfo(dtype).eps
@@ -1617,17 +1502,6 @@ class TestQuaternionToRotationMatrix(BaseTester):
)
self.assert_close(out_reversed, expected.flip(0))
- def test_convention_normalize_quaternion_zero_uses_the_default_guard_4021(self, device):
- _skip_if_dtype_unavailable(device, torch.float16)
- quaternion = torch.zeros(4, device=device, dtype=torch.float16)
-
- out = kornia.geometry.conversions.normalize_quaternion(quaternion)
-
- assert_close(out, quaternion, atol=0.0, rtol=0.0)
-
- without_guard = kornia.geometry.conversions.normalize_quaternion(quaternion, eps=0.0)
- assert torch.isnan(without_guard).all()
-
def test_convention_normalize_quaternion_preserves_float16_subnormal_4021(self, device):
_skip_if_dtype_unavailable(device, torch.float16)
quaternion = torch.tensor([5.960464477539063e-08, 0.0, 0.0, 0.0], device=device, dtype=torch.float16)
@@ -1638,22 +1512,12 @@ class TestQuaternionToRotationMatrix(BaseTester):
@pytest.mark.xfail(
raises=AssertionError,
- reason="normalize_quaternion divides by max(β€–qβ€–, eps), so below eps it returns a non-unit "
- "quaternion β€” kornia#3952",
+ reason="normalize_quaternion returns a non-unit quaternion below eps -- kornia#3952",
strict=True,
)
def test_convention_normalize_quaternion_is_unit_below_eps_3952(self, device, dtype):
- # Intended behavior: normalize_quaternion returns a unit quaternion, or refuses. It does
- # neither for a small input: it is F.normalize(q, p=2, dim=-1, eps=eps), which divides by
- # max(β€–qβ€–, eps), so any quaternion with β€–qβ€– < eps comes back scaled by β€–qβ€–/eps instead of
- # to unit length -- silently, with the docstring saying only "small value to avoid division
- # by zero". At β€–qβ€– = 1e-13 with the default eps = 1e-12 the output has norm exactly 0.1.
- # This pin is placed in this class because normalize_quaternion has no test class of its
- # own and quaternion_to_rotation_matrix is the function that calls it on every input (the
- # same placement as test_convention_normalize_quaternion_is_l2_over_the_last_axis above);
- # the consequence for that caller is pinned by
- # test_wart_zero_quaternion_becomes_the_identity_matrix_3952 below. Marked xfail(strict=True)
- # so fixing #3952 makes this XPASS and forces the mark out. Companion wart:
+ # Intended behavior: a unit quaternion, or an error. Below eps the output is scaled by
+ # ||q|| / eps instead (norm 0.1 at ||q|| = 1e-13, eps = 1e-12). Companion wart:
# test_wart_normalize_quaternion_scales_by_norm_over_eps_3952.
if dtype == torch.float16:
pytest.skip("float16 cannot represent the non-zero 1e-13 input used to pin the sub-eps behavior")
@@ -1666,64 +1530,50 @@ class TestQuaternionToRotationMatrix(BaseTester):
"kornia#3952: normalize_quaternion returned a non-unit quaternion below eps"
)
- def test_wart_normalize_quaternion_scales_by_norm_over_eps_3952(self, device, dtype):
- # Wart pin for kornia#3952, companion to the strict xfail above: assert the CURRENT
- # sub-eps outputs. Two cells here plus a third in the eps=0 control below, each
- # discriminating a different fix shape:
- # (1) β€–qβ€– = 1e-13 with eps = 1e-12 comes back as [0.1, 0, 0, 0] -- flips under every fix
- # (identity fallback, smaller eps, raise). float16 cannot represent this input, so
- # that cell applies only to the other dtypes;
- # (2) the exactly-zero quaternion comes back as zeros -- does NOT flip under a
- # "leave the input alone when β€–qβ€– < eps" fix, which is exactly the shape that would
- # leave cell (1) fixed and this one still broken.
- # If either fails, #3952 was (partly) fixed -- flip/remove the strict xfail above. NOT a
- # contract that sub-eps quaternions must keep these values. eps is passed explicitly at
- # every call site so the literals do not silently track a later change of the default.
- # Snippet used to generate expected (torch only, executed on cpu at float64):
+ @pytest.mark.parametrize("quaternion_dtype", [torch.float16, torch.bfloat16, torch.float32, torch.float64])
+ def test_wart_normalize_quaternion_scales_by_norm_over_eps_3952(self, device, quaternion_dtype):
+ # Wart pin for kornia#3952, companion to the strict xfail above. Two cells, each flipping
+ # under a different fix shape:
+ # (1) ||q|| = 1e-13 with eps = 1e-12 comes back as [0.1, 0, 0, 0] (not float16, which
+ # cannot represent the input);
+ # (2) the zero quaternion comes back as zeros -- a "leave sub-eps input alone" fix would
+ # fix (1) and not this one.
+ # The dtypes are hardcoded so the float16 cell runs in every test configuration.
+ # Snippet used to generate expected (torch, cpu, float64):
# normalize_quaternion(torch.tensor([1e-13, 0., 0., 0.], dtype=torch.float64), eps=1e-12)
- # -> [0.1, 0.0, 0.0, 0.0] (float32: [0.10000000149011612, 0, 0, 0];
- # bfloat16: [0.099609375, 0, 0, 0])
- # normalize_quaternion(torch.zeros(4, dtype=torch.float64), eps=1e-12) -> [0, 0, 0, 0]
- _skip_if_mps_clamp_caching(device)
-
+ # -> [0.1, 0.0, 0.0, 0.0]
+ _skip_if_dtype_unavailable(device, quaternion_dtype)
normalize_quaternion = kornia.geometry.conversions.normalize_quaternion
- zero = normalize_quaternion(torch.zeros(4, device=device, dtype=dtype), eps=1e-12)
-
- if dtype != torch.float16:
- sub_eps = normalize_quaternion(torch.tensor([1e-13, 0.0, 0.0, 0.0], device=device, dtype=dtype), eps=1e-12)
+ if quaternion_dtype != torch.float16:
+ sub_eps = normalize_quaternion(
+ torch.tensor([1e-13, 0.0, 0.0, 0.0], device=device, dtype=quaternion_dtype), eps=1e-12
+ )
assert_close(
sub_eps,
- torch.tensor([0.1, 0.0, 0.0, 0.0], device=device, dtype=dtype),
+ torch.tensor([0.1, 0.0, 0.0, 0.0], device=device, dtype=quaternion_dtype),
msg=_issue_msg("kornia#3952: a sub-eps quaternion is no longer scaled by ||q|| / eps"),
)
+ zero = torch.zeros(4, device=device, dtype=quaternion_dtype)
assert_close(
+ normalize_quaternion(zero),
zero,
- torch.zeros(4, device=device, dtype=dtype),
+ atol=0.0,
+ rtol=0.0,
msg=_issue_msg("kornia#3952: the zero quaternion no longer passes through unchanged"),
)
- def test_wart_normalize_quaternion_without_eps_divides_by_zero_3952(self, device, dtype):
- # Wart pin for kornia#3952, cell (3) and the control for the two cells above: with eps=0
- # the zero quaternion produces NaN, which pins the *mechanism* (normalize_quaternion is a
- # plain division by max(β€–qβ€–, eps), nothing more) rather than the symptom. It flips only if
- # that division is replaced by a clamp- or branch-shaped rewrite, which is how an eps-only
- # fix is told apart from a restructuring one. If it fails, #3952 was (partly) fixed --
- # flip/remove the strict xfail above. NOT a contract that eps=0 must keep producing NaN.
- # It lives in its own test rather than as a third cell of the wart above because on MPS the
- # two cannot share a process: this torch build caches clamp's scalar min per shape/dtype on
- # MPS, so an earlier normalize_quaternion(..., eps=1e-12) on a (4,) float32 tensor makes
- # the later eps=0.0 call reuse 1e-12 and return zeros instead of NaN (executed: cpu gives
- # [nan, nan, nan, nan], mps gives [0, 0, 0, 0] for the same three calls in sequence, while
- # the eps=0 call *alone* gives NaN on both). That is the torch defect already probed by
- # _skip_if_mps_clamp_caching further down this file, which is what guards this pin.
- # Snippet used to generate expected (torch only, executed on cpu at every floating dtype):
- # normalize_quaternion(torch.zeros(4, dtype=torch.float64), eps=0.0) -> [nan] * 4
- _skip_if_mps_clamp_caching(device)
+ @pytest.mark.parametrize("quaternion_dtype", [torch.float16, torch.bfloat16, torch.float32, torch.float64])
+ def test_convention_normalize_quaternion_eps_zero_gives_nan_at_zero(self, device, quaternion_dtype):
+ # eps=0.0 disables the guard: the zero quaternion is divided by its zero norm and returns
+ # NaN at every dtype, float16 included.
+ _skip_if_dtype_unavailable(device, quaternion_dtype)
- out = kornia.geometry.conversions.normalize_quaternion(torch.zeros(4, device=device, dtype=dtype), eps=0.0)
+ out = kornia.geometry.conversions.normalize_quaternion(
+ torch.zeros(4, device=device, dtype=quaternion_dtype), eps=0.0
+ )
- assert torch.isnan(out).all(), "kornia#3952: the eps=0 division by the zero norm is no longer NaN"
+ assert torch.isnan(out).all()
def test_float16_gradient_normalize_quaternion_zeros4_4623(self, device):
# Issue #4623: float16 gradient of normalize_quaternion at zeros(4) must be finite and zero.
@@ -1918,12 +1768,6 @@ class TestQuaternionLogToExp(BaseTester):
# Snippet used to generate expected (stdlib only):
# exp(log(q)) = q for every unit q except q = (-1, 0, 0, 0)
# 1 / math.sqrt(2.0) -> 0.7071067811865476
- # float16 is skipped: quaternion_exp_to_log((-1, 0, 0, 0)) returns NaN there, so the
- # exception case cannot be evaluated at all (float64/float32/bfloat16 all return the
- # origin as documented above).
- if dtype == torch.float16:
- pytest.skip("quaternion_exp_to_log((-1, 0, 0, 0)) is NaN at float16, so exp(log(.)) is undefined")
-
identity = torch.tensor([1.0, 0.0, 0.0, 0.0], device=device, dtype=dtype)
exp_to_log = kornia.geometry.conversions.quaternion_exp_to_log
log_to_exp = kornia.geometry.conversions.quaternion_log_to_exp
@@ -1935,18 +1779,10 @@ class TestQuaternionLogToExp(BaseTester):
self.assert_close(log_to_exp(exp_to_log(half_turn)), half_turn)
def test_convention_log_to_exp_of_the_origin_is_the_identity_in_float16_3966(self, device):
- # Intended behavior: the exponential map of the zero vector is the identity quaternion, at
- # every dtype -- float64, float32 and bfloat16 all return [1, 0, 0, 0]. float16 returns
- # [1, nan, nan, nan]: the default eps = 1e-8 is below float16's smallest subnormal
- # (5.960464477539063e-08), so torch.tensor(1e-8, dtype=float16) is exactly 0.0, the
- # .clamp(min=eps) on the norm is a no-op, and the vector part is sin(0) * 0 / 0. The real
- # part survives because it is cos(0). This is the same eps-underflow class as the one
- # kornia#3966 was filed for on quaternion_exp_to_log (pinned in TestQuaternionExpToLog);
- # bfloat16 escapes both because its exponent range is float32's. float16 is hardcoded and
- # the dtype fixture dropped so this pin runs in every configuration, with a visible skip
- # where the device lacks the dtype. Marked xfail(strict=True) so fixing #3966 makes this
- # XPASS and forces the mark out. Companion wart:
- # test_wart_float16_eps_underflow_makes_log_to_exp_nan_3966.
+ # The exponential map of the zero vector is the identity quaternion in float16 too: the
+ # computation runs in float32, where the default eps = 1e-8 is representable (in float16 it
+ # underflows to 0 and the vector part would be 0 / 0). float16 is hardcoded so the pin runs
+ # in every test configuration.
_skip_if_dtype_unavailable(device, torch.float16)
out = kornia.geometry.conversions.quaternion_log_to_exp(torch.zeros(3, device=device, dtype=torch.float16))
@@ -2130,13 +1966,10 @@ class TestQuaternionExpToLog(BaseTester):
# round-trip collapses to ~0 instead of returning pi -- the one interior point where the
# log/exp pair is not invertible. float64 is hardcoded and the dtype fixture dropped
# because the collapse needs cos(||v||) to round to exactly -1 and the vector part to fall
- # below the eps clamp, which only happens at float64: at float32 the same input returns
- # -3.1415927410125732 (no collapse), at float16/bfloat16 3.140625. MPS is skipped visibly
- # because it has no float64 at all.
+ # below the eps clamp, which only happens at float64.
# Snippet used to generate expected (stdlib only):
# math.cos(math.pi), math.sin(math.pi) -> (-1.0, 1.2246467991473532e-16)
- # Measured round-trip value at float64 (torch 2.9.1, cpu): 3.847341387443579e-08, i.e. an
- # error of 3.14 against the input, so atol 1e-7 pins the collapse without pinning the
+ # atol 1e-7 pins the collapse (an error of pi against the input) without pinning the
# residue itself.
_skip_if_dtype_unavailable(device, torch.float64)
@@ -2189,17 +2022,9 @@ class TestQuaternionExpToLog(BaseTester):
# literals do not silently track a later change of the default.
# Snippet used to generate expected (torch + stdlib, executed on cpu float64):
# quaternion_exp_to_log(torch.tensor([0.5, 0.5, 0., 0.], dtype=torch.float64), eps=1e-8)
- # -> [1.0471975511965976, 0.0, 0.0] (float32: 1.0471975803375244;
- # float16/bfloat16: 1.046875)
- # math.acos(0.5) -> 1.0471975511965979, and math.acos(1 / math.sqrt(2)) -> 0.7853981633974484
+ # -> [1.0471975511965976, 0.0, 0.0]; math.acos(1 / math.sqrt(2)) -> 0.7853981633974484
# quaternion_exp_to_log(torch.tensor([2., 0., 0., 0.], dtype=torch.float64), eps=1e-8)
# -> [0.0, 0.0, 0.0]
- if dtype == torch.float16:
- pytest.skip(
- "at float16 the second cell is NaN rather than the origin, because the default eps underflows and "
- "the zero vector part is divided by itself -- that is kornia#3966, pinned separately below"
- )
-
exp_to_log = kornia.geometry.conversions.quaternion_exp_to_log
scaled_down = exp_to_log(torch.tensor([0.5, 0.5, 0.0, 0.0], device=device, dtype=dtype), eps=1e-8)
@@ -2217,19 +2042,10 @@ class TestQuaternionExpToLog(BaseTester):
)
def test_convention_exp_to_log_of_the_identity_is_the_origin_in_float16_3966(self, device):
- # Intended behavior: the log of the identity quaternion is the origin, at every dtype --
- # float32, float64 and bfloat16 all return [0, 0, 0]. float16 returns [nan, nan, nan]:
- # the default eps = 1e-8 is below float16's smallest subnormal (5.960464477539063e-08), so
- # torch.tensor(1e-8, dtype=float16) is exactly 0.0, the .clamp(min=eps) on the vector-part
- # norm is a no-op, and the log is acos(1) * 0 / 0. bfloat16 escapes only because its
- # exponent range is float32's (1e-8 survives as 1.0011717677116394e-08). float16 is
- # hardcoded and the dtype fixture dropped so this pin runs in every configuration, with a
- # visible skip where the device lacks the dtype -- otherwise a RuntimeError would satisfy
- # the raises=AssertionError mark instead of the assertion. Marked xfail(strict=True) so
- # fixing #3966 makes this XPASS and forces the mark out. Companion wart:
- # test_wart_float16_eps_underflow_makes_exp_to_log_nan_3966. Note that 3a's merged
- # test_wart_float16_underflowed_default_eps_flips_branches pins the same failure class
- # (a float default eps that float16 cannot represent) at a different site.
+ # The log of the identity quaternion is the origin in float16 too: the computation runs in
+ # float32, where the default eps = 1e-8 is representable (in float16 it underflows to 0 and
+ # the log would be acos(1) * 0 / 0). float16 is hardcoded so the pin runs in every test
+ # configuration.
_skip_if_dtype_unavailable(device, torch.float16)
identity = torch.tensor([1.0, 0.0, 0.0, 0.0], device=device, dtype=torch.float16)
@@ -2653,28 +2469,37 @@ class TestRotationMatrixToAngleAxis(BaseTester):
assert multi_batched.shape == (2, 5, 3)
self.assert_close(multi_batched[1, 4], expected)
- def test_convention_axis_angle_roundtrip_tolerance_is_1e_6_in_float64(self, device):
- # Convention pin: rotation_matrix_to_axis_angle composed with
- # axis_angle_to_rotation_matrix recovers the vector only to ~1e-6, and that floor does not
- # move with the dtype -- it is still ~1e-6 in float64, six orders worse than the machine
- # epsilon a reader would expect from a "round-trip" and eleven orders worse than the
- # quaternion leg (see TestAngleAxisToQuaternion.test_convention_axis_angle_quaternion_
- # roundtrip_is_exact_in_float64, which is exact at the same angles). Anyone comparing
- # rotations through this pair must budget 1e-6. float64 is hardcoded and the dtype fixture
- # dropped because the claim is precisely that float64 does NOT help; MPS is skipped visibly
- # because it has no float64 at all. The tolerance is the observed one and must not be
- # tightened.
+ def test_wart_reflection_is_returned_as_the_identity_4773(self, device, dtype):
+ # Wart pin for kornia#4773: an improper matrix (det = -1) is not rejected, and the
+ # reflection diag(-1, 1, 1) comes back as the zero vector -- "no rotation". Flips when the
+ # function raises or returns anything else for it.
+ reflection = torch.diag(torch.tensor([-1.0, 1.0, 1.0], device=device, dtype=dtype))
+
+ out = kornia.geometry.conversions.rotation_matrix_to_axis_angle(reflection)
+
+ assert_close(
+ out,
+ torch.zeros(3, device=device, dtype=dtype),
+ atol=0.0,
+ rtol=0.0,
+ msg=_issue_msg("kornia#4773: a reflection is no longer returned as the identity rotation"),
+ )
+
+ def test_convention_axis_angle_matrix_roundtrip_is_accurate_in_float64(self, device):
+ # rotation_matrix_to_axis_angle(axis_angle_to_rotation_matrix(v)) returns v to roundoff,
+ # except on the low-angle Taylor branch (theta**2 <= 1e-6), whose second-order truncation
+ # leaves about theta**3 / 6 (1.2e-10 at the 9e-4 row). 1e-9 keeps ~8x headroom over that
+ # and would catch a first-order branch (theta**2 / 2 = 4e-7). Measured over 2e5 float64
+ # axis-angles drawn in float64 (uniform, log-spaced small and near-pi angles): 1.6e-10 max,
+ # at theta just under 1e-3; 1.3e-15 max for theta near pi.
# Snippet used to generate the inputs (stdlib only):
- # import math
# n = math.sqrt(14.0); axis = (1 / n, 2 / n, 3 / n)
- # [[theta * a for a in axis] for theta in (1e-3, 0.7, 2.0, math.pi)]
- # Measured max |roundtrip - input| at those four thetas (torch 2.9.1, cpu float64):
- # 8.009844122083441e-07, 6.410323137862051e-07, 5.134006499929455e-07,
- # 5.387205765927661e-07 -- so atol 1e-6 clears the worst of them by 20%.
+ # [[theta * a for a in axis] for theta in (9e-4, 1e-3, 0.7, 2.0, math.pi)]
_skip_if_dtype_unavailable(device, torch.float64)
axis_angle = torch.tensor(
[
+ [0.00024053511772118195, 0.0004810702354423639, 0.0007216053531635459],
[0.0002672612419124244, 0.0005345224838248488, 0.0008017837257372733],
[0.18708286933869706, 0.3741657386773941, 0.5612486080160912],
[0.5345224838248488, 1.0690449676496976, 1.6035674514745464],
@@ -2688,7 +2513,7 @@ class TestRotationMatrixToAngleAxis(BaseTester):
kornia.geometry.conversions.axis_angle_to_rotation_matrix(axis_angle)
)
- self.assert_close(roundtrip, axis_angle, atol=1e-6, rtol=0.0)
+ self.assert_close(roundtrip, axis_angle, atol=1e-9, rtol=0.0)
class TestRadDegConversions(BaseTester):
@@ -2882,9 +2707,6 @@ class TestPolCartConversions(BaseTester):
def test_convention_cart2pol_rho_is_the_exact_radius(self, device, dtype):
# The radius is the Euclidean distance. The gradient-safe implementation must not
# perturb the forward value at the origin or elsewhere (#3939).
- if dtype == torch.float16:
- pytest.skip("float16 cannot represent the default eps=1e-8")
-
zero = torch.tensor(0.0, device=device, dtype=dtype)
rho_origin = kornia.geometry.conversions.cart2pol(zero, zero)[0]
self.assert_close(rho_origin, zero, atol=0.0, rtol=0.0)
@@ -3217,21 +3039,6 @@ class TestConvertPointsFromHomogeneous(BaseTester):
)
-def _skip_if_mps_clamp_caching(device):
- # Runtime probe instead of a torch-version pin, so the skip retires itself on any torch
- # build where the two clamps below return different values.
- if device.type == "mps" and torch.equal(
- torch.zeros(2, device=device).clamp(1e-8), torch.zeros(2, device=device).clamp(1e-7)
- ):
- pytest.skip(
- "this torch build caches clamp's scalar min per shape/dtype on MPS -- first value wins "
- "(seen on torch 2.9.1): z = torch.zeros(2, device='mps'); z.clamp(1e-8) then z.clamp(1e-7) "
- "both return 9.99999993922529e-09, while the same pair on cpu returns 1e-08 then "
- "1.0000000116860974e-07. The clamped eps this pin measures is therefore set by whichever "
- "earlier test clamped first, which is a torch defect, not a kornia one"
- )
-
-
class TestNormalizePixelCoordinates(BaseTester):
def test_tensor_bhw2(self, device, dtype, atol, rtol):
height, width = 3, 4
@@ -3418,41 +3225,13 @@ class TestNormalizePixelCoordinates(BaseTester):
self.assert_close(actual[1], expected[1], atol=0.0, rtol=0.0)
-def test_wart_default_eps_1e_8_backs_the_remaining_quoted_warning_numbers():
- # These two APIs still use eps numerically and quote outputs based on its default.
+def test_convention_default_eps_is_1e_8():
+ # cart2pol and convert_points_from_homogeneous document outputs at their default eps.
for op_name in ("cart2pol", "convert_points_from_homogeneous"):
op = getattr(kornia.geometry.conversions, op_name)
assert inspect.signature(op).parameters["eps"].default == 1e-8, op_name
-def test_wart_float16_underflowed_default_eps_flips_branches(device):
- # Wart pin for the float16 sentence of the #3939 warning and for the float16 sentence of
- # the convert_points_from_homogeneous Convention block. float16 is hardcoded (no dtype
- # fixture) so the pins run in every test configuration: the float16 legs of the tests
- # above are skipped because the default eps=1e-8 underflows to 0 there, which is exactly
- # the behavior pinned here. eps is left at its default on purpose
- # -- the underflow of the *default* is the claim. atol=rtol=0.0 because both claims are
- # exactness claims: with the float16 default tolerance (1e-3) the eps-biased
- # rho = 1e-4 of the other branch would still compare equal to 0.
- # Snippet used to generate expected (torch only, executed on cpu float16):
- # cart2pol(torch.tensor(0., dtype=torch.float16), torch.tensor(0., dtype=torch.float16))[0]
- # -> 0.0 (not sqrt(eps) = 1e-4: eps underflows the sum inside the sqrt)
- # convert_points_from_homogeneous(torch.tensor([[2., 4., 2e-8]], dtype=torch.float16))
- # -> [[2., 4.]] (w underflows to 0 and takes the abs(w) <= eps passthrough branch)
- # The cart2pol half is narrowed rather than skipped whole: it reaches torch.atan2, whose CPU
- # float16 kernel ("atan2_cpu" not implemented for 'Half') only landed in PyTorch 2.2, while the
- # convert_points_from_homogeneous claim below has no such floor and stays pinned everywhere.
- if not (device.type == "cpu" and torch_version_lt(2, 2, 0)):
- zero = torch.tensor(0.0, device=device, dtype=torch.float16)
- rho = kornia.geometry.conversions.cart2pol(zero, zero)[0]
- assert_close(rho, zero, atol=0.0, rtol=0.0)
-
- out = kornia.geometry.conversions.convert_points_from_homogeneous(
- torch.tensor([[2.0, 4.0, 2e-8]], device=device, dtype=torch.float16)
- )
- assert_close(out, torch.tensor([[2.0, 4.0]], device=device, dtype=torch.float16), atol=0.0, rtol=0.0)
-
-
class TestDenormalizePixelCoordinates(BaseTester):
def test_tensor_bhw2(self, device, dtype):
height, width = 3, 4
@@ -3745,13 +3524,7 @@ class TestNormalTransformPixel(BaseTester):
# normal_transform_pixel and normal_transform_pixel3d have no test class of their own in this
# file -- their existing coverage lives in tests/geometry/transform/test_homography_warper.py.
# The convention pins live here, next to the pixel-coordinate family whose [-1, 1] convention
- # they share (an executed agreement, not a shared-code argument: see
- # test_convention_agrees_with_normalize_pixel_coordinates below).
- # NOTE: kornia#3904 landed and did NOT move any literal here. It gave normal_transform_pixel an
- # align_corners parameter, but left the default at True, so every literal in this class is still
- # the corner-aligned 2/(size - 1) one and every bare call still produces it. What would flip them
- # is a change to that default, not the existence of the parameter. They record current default
- # behavior; none of them is a ratified contract for that choice.
+ # they share. Every literal is the default align_corners=True mapping.
def test_convention_returns_one_unbatched_matrix_in_the_ambient_default_dtype(self, device):
# Convention pin: both helpers return exactly one matrix behind a leading axis of 1 --
@@ -3790,24 +3563,13 @@ class TestNormalTransformPixel(BaseTester):
)
def test_convention_corner_aligned_scale_is_two_over_size_minus_one(self, device):
- # Convention pin: the matrix is diag(2/(width - 1), 2/(height - 1), 1) with a -1 offset in
- # the last column, so pixel CENTRES 0 and size - 1 land exactly on -1 and +1. That is the
- # corner-aligned (align_corners=True) convention and it is applied unconditionally -- there
- # is no align_corners parameter, so the half-pixel convention cannot be selected:
- # grid_sample's default (align_corners=False) mapping (2*x + 1)/width - 1 would send the
- # same three columns to -0.8, 0.8, 0.0 instead of -1.0, 1.0, 0.0.
- # NOTE: covered by this class's kornia#3904 note above; recorded, not a ratified contract.
- # Sizes 3 and 5 are chosen because 2/(3 - 1) = 1.0 and 2/(5 - 1) = 0.5 are exact, so the
- # comparison runs at atol=rtol=0 and no nearby convention can satisfy it. float32 is
- # hardcoded and the dtype fixture dropped: the scales are pure Python floats computed
- # before any tensor exists (the wart matrix below documents the same mechanism), so a
- # non-float32 leg would only test torch's cast. Only the matrix is asserted: the pixel
- # maps in the snippet are pure arithmetic on the bitwise-pinned matrix and this test's own
- # constants, so a product assertion would add no failure surface against kornia.
+ # Convention pin: by default the matrix is diag(2/(width - 1), 2/(height - 1), 1) with a -1
+ # offset, so pixel CENTRES 0 and size - 1 land exactly on -1 and +1 (corner-aligned);
+ # grid_sample's half-pixel mapping (2*x + 1)/width - 1 would send columns 0, 4, 2 to
+ # -0.8, 0.8, 0.0 instead of -1.0, 1.0, 0.0. Sizes 3 and 5 keep both scales exact, so the
+ # comparison runs at atol=rtol=0.
# Snippet used to generate expected (stdlib only, height = 3, width = 5):
# 2 / (5 - 1), 2 / (3 - 1) -> 0.5, 1.0
- # [2 * x / (5 - 1) - 1 for x in (0, 4, 2)] -> [-1.0, 1.0, 0.0]
- # [(2 * x + 1) / 5 - 1 for x in (0, 4, 2)] -> [-0.8, 0.8, 0.0] (the half-pixel alternative)
matrix = kornia.geometry.conversions.normal_transform_pixel(3, 5, device=device, dtype=torch.float32)
expected = torch.tensor(
@@ -3816,161 +3578,41 @@ class TestNormalTransformPixel(BaseTester):
self.assert_close(matrix, expected, atol=0.0, rtol=0.0)
def test_convention_agrees_with_normalize_pixel_coordinates(self, device, dtype):
- # Convention pin: the matrix is the homogeneous form of normalize_pixel_coordinates -- the
- # same map, not merely a similar one -- and the agreement is EXACT only where the
- # arithmetic is. Two legs, and the dtype fixture is load-bearing across both.
- # Leg 1, sizes (3, 5): both scales (1.0 and 0.5) are exactly representable, so every route
- # and every dtype hits the same hardcoded literal at atol=rtol=0, on five points including
- # a half-pixel and an out-of-image one (neither route clamps).
- # Leg 2, sizes (2, 28): 2/(28 - 1) is not exactly representable in reduced precision, so
- # the two routes do diverge there and the dtype fixture is load-bearing -- each dtype gets
- # a different bound and a different measured gap, unlike the sizes in leg 1, where nothing
- # can diverge in any dtype. Note the two routes hold the SAME rounded scale; what differs
- # is where the rounding falls, so the divergence is not a property of the scale literal.
- # The helper multiplies and
- # subtracts elementwise in the working dtype, while applying the matrix is a matmul, whose
- # dot product is accumulated at higher precision and rounded once at the end.
- # What leg 2 asserts here is the dtype-scaled half of the docstring's claim -- the one that
- # runs everywhere rather than only where a kernel was measured: the disagreement stays
- # within 2 * the eps of the format the matmul rounds its INPUTS to -- finfo(dtype).eps on
- # every backend that evaluates the matmul at the working dtype, and the coarser format's eps
- # where it does not (TF32 on cuda; see _matmul_input_eps). The docstring's bound is scoped
- # the same way. That is a TOLERATED bound, not one derived from a portable
- # accuracy model (see the note at the assertion for what it does and does not promise),
- # computed from the dtype rather than hardcoded. The exact per-configuration
- # gaps are a kernel measurement and live in
- # test_wart_agreement_gap_at_2_28_is_a_kernel_measurement below, which is where the
- # docstring's figures are pinned and where an unmeasured configuration skips visibly.
- # What this pin does NOT decide: anything about non-corner-aligned callers such as
- # grid_sample(align_corners=False), which is pinned separately in
- # TestNormalizePixelCoordinates.
- # NOTE: covered by this class's kornia#3904 note above; recorded, not a ratified contract.
- # Snippet used to generate expected (leg 1, stdlib only, height = 3, width = 5):
+ # Convention pin: the matrix is the homogeneous form of normalize_pixel_coordinates.
+ # At sizes (3, 5) both scales are exact, so both routes hit the same literal at
+ # atol=rtol=0 on five points, including a half-pixel and an out-of-image one. At (2, 28),
+ # where 2/27 is inexact, the routes round in different places (the helper elementwise in
+ # the working dtype, the matrix through a matmul) and are held to 2 * eps of the format
+ # the matmul rounds its inputs to (see _matmul_input_eps).
+ # Snippet used to generate expected (stdlib only, height = 3, width = 5):
# x -> 2 * x / 4 - 1 for x in (0, 4, 2, 1, 6) -> -1.0, 1.0, 0.0, -0.5, 2.0
# y -> 2 * y / 2 - 1 for y in (0, 2, 1, 0.5, 0) -> -1.0, 1.0, 0.0, -0.5, -1.0
_skip_if_dtype_unavailable(device, dtype)
- pixels = torch.tensor(
- [[[0.0, 0.0], [4.0, 2.0], [2.0, 1.0], [1.0, 0.5], [6.0, 0.0]]], device=device, dtype=dtype
- )
+ conversions = kornia.geometry.conversions
+
+ def both_routes(pixels, height, width):
+ via_helper = conversions.normalize_pixel_coordinates(pixels, height, width)
+ matrix = conversions.normal_transform_pixel(height, width, device=device, dtype=dtype)[0]
+ homogeneous = torch.cat([pixels, torch.ones_like(pixels[:, :1])], dim=-1)
+ return via_helper, (matrix @ homogeneous.transpose(0, 1)).transpose(0, 1)[:, :2]
+
+ pixels = torch.tensor([[0.0, 0.0], [4.0, 2.0], [2.0, 1.0], [1.0, 0.5], [6.0, 0.0]], device=device, dtype=dtype)
expected = torch.tensor(
[[-1.0, -1.0], [1.0, 1.0], [0.0, 0.0], [-0.5, -0.5], [2.0, -1.0]], device=device, dtype=dtype
)
-
- via_helper = kornia.geometry.conversions.normalize_pixel_coordinates(pixels, 3, 5)[0]
- matrix = kornia.geometry.conversions.normal_transform_pixel(3, 5, device=device, dtype=dtype)
- homogeneous = torch.cat([pixels[0], torch.ones_like(pixels[0][:, :1])], dim=-1)
- via_matrix = (matrix[0] @ homogeneous.transpose(0, 1)).transpose(0, 1)[:, :2]
-
+ via_helper, via_matrix = both_routes(pixels, 3, 5)
self.assert_close(via_helper, expected, atol=0.0, rtol=0.0)
self.assert_close(via_matrix, expected, atol=0.0, rtol=0.0)
- largest_gap = _agreement_gap_at_2_28(device, dtype)
- # A tolerated bound, not a derived guarantee, and deliberately not called one rounding
- # step: eps IS the spacing at 1.0, so 2 * eps accepts two spacings there and four just
- # below it. What the constant is: roughly 2x headroom over the worst gap measured in any
- # configuration below, all of which are at most one eps (float16 is exactly eps on both
- # backends; every other nonzero cell is eps/2), scaled so no dtype inherits a bound sized
- # for another. Scaled by _matmul_input_eps rather than by finfo(dtype).eps directly,
- # because the matrix route is a matmul and a backend can be configured to round a matmul's
- # inputs below the working dtype (TF32 or bfloat16 for float32 on cuda) -- there the
- # coarser format IS the arithmetic, so the bound follows it instead of the pin going red on
- # a configuration change that touched no kornia code.
- # A failure is still not by itself a kornia regression: torch promises no common
- # accumulation precision across every backend, so it says re-derive the bound against the
- # configuration that produced it -- and record the measurement in the wart pin below,
- # keyed like the rest.
- tolerated_gap = 2 * _matmul_input_eps(device, dtype)
-
- assert largest_gap <= tolerated_gap, (
- f"the two routes now differ by {largest_gap!r} at (2, 28) in {dtype}, more than the "
- f"tolerated {tolerated_gap!r} (2 * the matmul's input eps) -- either they no longer differ only in where "
- "the rounding falls, or this configuration accumulates matmuls at a precision none of "
- "the measured ones used and needs a bound derived for it"
- )
-
- def test_wart_agreement_gap_at_2_28_is_a_kernel_measurement(self, device, dtype):
- # Wart pin for the exact figures normal_transform_pixel's agreement bullet quotes: at
- # (2, 28), where 2/(28 - 1) is not representable in reduced precision, how far apart the
- # two routes land is a property of the backend's and the build's matmul kernel, not of the
- # convention. Pinned exactly rather than as a bound -- the dtype-scaled bound is asserted by
- # test_convention_agrees_with_normalize_pixel_coordinates above -- because a bound would
- # let cpu float32/float64 regress from exact agreement to a small nonzero gap while the
- # docstring's "0.0" claim quietly became false.
- # Keyed by (torch version, backend, machine, dtype): every cell is a measurement of one
- # build, not a portable contract, so an unmeasured torch release must not silently inherit
- # an older release's kernel literal -- a future kernel reassociation could then fail this
- # pin on a release that was never measured, without any kornia regression.
- # - backend, because the mps matmul rounds once where cpu does not (float32: 2**-24 vs 0)
- # - machine, because arm64 and x86-64 use different CPU kernels; an unmeasured platform
- # must not inherit another machine's literal. The Linux CPU half-precision CI jobs now
- # exercise the measured torch 2.9.1 x86-64 rows below. Other x86-64 torch/dtype cells
- # still skip until measured. The portable half of the docstring's claim is asserted on
- # every CI leg by test_convention_agrees_with_normalize_pixel_coordinates above.
- # A cuda row, when one is measured, will need the float32 matmul precision mode in its
- # key as well: --tf32 rounds a matmul's inputs to 10 mantissa bits and the matrix route
- # is a matmul, while cpu is unaffected by that setting (executed, all four dtypes).
- # - version, because the cpu bfloat16 kernel changed between the two torch versions
- # executed (no divergence at all on 2.5.1, one bfloat16 step on 2.9.1) while every other
- # cell reproduced identically on both -- reproducing does not exempt a cell from being
- # keyed by version, since a later release could still change it
- # An unmeasured configuration skips visibly: the skip is a reminder to measure, not a
- # silent pass, and the dtype-scaled bound is still asserted by the pin above.
- # NOT a contract that these kernels must keep producing these numbers -- if a cell fails,
- # re-measure, update the cell here (this comment and the table below are where the figures
- # live; normal_transform_pixel's bullet states the contract and quotes none of them) and
- # check that the bullet's "agree in float32/float64; whether they agree at float16/bfloat16
- # is a property of the build" still holds -- the cpu bfloat16 row is the whole reason that
- # clause is build-scoped rather than absolute: 2.5.1 agrees at every size, 2.9.1 does not.
- # Snippet used to generate expected (torch + kornia; the arm64 values were executed on macOS
- # against torch 2.9.1 and 2.5.1, and the x86-64 values on Linux against torch 2.9.1;
- # max|helper - matrix| over the full (2, 28) pixel grid):
- # cpu 2.9.1: float64 -> 0.0 float32 -> 0.0 float16 -> 0.0009765625 bfloat16 -> 0.00390625
- # cpu 2.5.1: float64 -> 0.0 float32 -> 0.0 float16 -> 0.0009765625 bfloat16 -> 0.0
- # mps, both: float32 -> 5.960464477539063e-08 (2**-24) float16 -> 0.0009765625
- # bfloat16 -> 0.00390625 (float64 is unavailable on mps)
- # The full size sweep behind the docstring's "not at float16/bfloat16" clause is NOT
- # pinned -- 3364 size pairs per dtype is too slow for a unit test -- so its counts live in
- # this comment and nowhere else; the same snippet with the (2, 28) call in a double loop
- # over range(2, 60) reproduces them:
- # cpu 2.9.1: float16 3328/3364 (worst 9.77e-04) bfloat16 3315/3364 (worst 7.81e-03)
- # cpu 2.5.1: float16 3328/3364 (worst 9.77e-04) bfloat16 0/3364 (worst 0.0)
- _skip_if_dtype_unavailable(device, dtype)
- measured_gaps = {
- ("2.9.1", "cpu", "arm64", torch.float64): 0.0,
- ("2.5.1", "cpu", "arm64", torch.float64): 0.0,
- ("2.9.1", "cpu", "arm64", torch.float32): 0.0,
- ("2.5.1", "cpu", "arm64", torch.float32): 0.0,
- ("2.9.1", "cpu", "arm64", torch.float16): 0.0009765625,
- ("2.5.1", "cpu", "arm64", torch.float16): 0.0009765625,
- ("2.9.1", "cpu", "arm64", torch.bfloat16): 0.00390625,
- ("2.5.1", "cpu", "arm64", torch.bfloat16): 0.0,
- ("2.9.1", "cpu", "x86_64", torch.float64): 0.0,
- ("2.9.1", "cpu", "x86_64", torch.float32): 0.0,
- ("2.9.1", "cpu", "x86_64", torch.float16): 0.0009765625,
- ("2.9.1", "cpu", "x86_64", torch.bfloat16): 0.00390625,
- ("2.9.1", "mps", "arm64", torch.float32): 2.0**-24,
- ("2.5.1", "mps", "arm64", torch.float32): 2.0**-24,
- ("2.9.1", "mps", "arm64", torch.float16): 0.0009765625,
- ("2.5.1", "mps", "arm64", torch.float16): 0.0009765625,
- ("2.9.1", "mps", "arm64", torch.bfloat16): 0.00390625,
- ("2.5.1", "mps", "arm64", torch.bfloat16): 0.00390625,
- }
- machine = platform.machine()
- key = (torch_version(), device.type, machine, dtype)
-
- if key not in measured_gaps:
- pytest.skip(
- f"the (2, 28) agreement gap was not measured on {device.type} / {machine} / torch "
- f"{torch_version()} at {dtype}; no kernel literal to inherit"
- )
- expected_gap = measured_gaps[key]
-
- largest_gap = _agreement_gap_at_2_28(device, dtype)
-
- assert largest_gap == expected_gap, (
- f"the two routes now differ by {largest_gap!r} at (2, 28) on {device.type} / {machine} "
- f"in {dtype} under torch {torch_version()}, not {expected_gap!r} -- "
- "normal_transform_pixel's agreement bullet quotes this figure and must be re-measured"
+ # The grid is built from an int64 arange cast afterwards: some MPS builds have no bfloat16 arange.
+ y_grid, x_grid = torch.meshgrid(
+ torch.arange(2, device=device).to(dtype), torch.arange(28, device=device).to(dtype), indexing="ij"
+ )
+ via_helper, via_matrix = both_routes(torch.stack([x_grid.reshape(-1), y_grid.reshape(-1)], dim=-1), 2, 28)
+ # .float() because the difference of two bfloat16 values is not representable in bfloat16.
+ largest_gap = (via_helper.float() - via_matrix.float()).abs().max().item()
+ assert largest_gap <= 2 * _matmul_input_eps(device, dtype), (
+ f"the two routes differ by {largest_gap!r} at (2, 28) in {dtype}"
)
def test_convention_3d_matrix_acts_on_x_y_z_one(self, device):
@@ -3979,15 +3621,8 @@ class TestNormalTransformPixel(BaseTester):
# homogeneous (x, y, z, 1) with x scaled by WIDTH, y by HEIGHT and z by DEPTH, i.e. the
# reverse of its own argument order -- and is corner-aligned like the 2-D form, so
# (0, 0, 0) maps to (-1, -1, -1) and (width - 1, height - 1, depth - 1) to (1, 1, 1).
- # NOTE: covered by this class's kornia#3904 note above; recorded, not a ratified contract.
# (depth, height, width) = (3, 5, 9) keeps 2/8, 2/4 and 2/2 exact, so the comparison runs
- # at atol=rtol=0. float32 is hardcoded and the dtype fixture dropped -- NOT for the 2-D
- # pin's pure-Python-floats reason: normal_transform_pixel3d computes its scales as tensor
- # arithmetic in the requested dtype (tr_mat[i, i] * 2.0 / denominator). These dyadic
- # scales are exact in every dtype, and the 3-D helper's dtype-dependent arithmetic stays
- # exercised by the dtype-parameterized component-order pin below. Only the matrix is
- # asserted: the corner maps in the
- # snippet are pure arithmetic on the bitwise-pinned matrix and this test's own constants.
+ # at atol=rtol=0.
# Snippet used to generate expected (stdlib only):
# 2 / (9 - 1), 2 / (5 - 1), 2 / (3 - 1) -> 0.25, 0.5, 1.0
# matrix @ (0, 0, 0, 1) -> (-1, -1, -1, 1); matrix @ (8, 4, 2, 1) -> (1, 1, 1, 1)
@@ -4124,102 +3759,62 @@ class TestNormalTransformPixel(BaseTester):
finally:
torch.set_default_dtype(previous)
- @pytest.mark.parametrize("rejected_dtype", [torch.int64, torch.int32, torch.uint8, torch.bool])
- def test_convention_integer_dtype_is_rejected_3959(self, device, rejected_dtype):
- # Replaces the wart pin test_wart_integer_dtype_truncates_the_scale_to_zero_3959, which
- # recorded the truncation as undecided behavior. It is decided: the dtype is rejected.
- # The matrix scales by 2/(size - 1), fractional for every dimension larger than 3 pixels,
- # so an integer dtype truncated every scale below 1 to 0 and the function returned a
- # rank-deficient matrix -- [[0, 0, -1], [0, 0, -1], [0, 0, 1]] in 2-D, mapping EVERY pixel
- # to the constant (-1, -1), and diagonal [0, 0, 2] in 3-D, where depth = 2 keeps 2/1 = 2
- # alive through the truncation. No error, no warning.
- # kornia#3948 (axis_angle_to_quaternion) settled the sibling defect by PROMOTING, and the
- # wart named that as the precedent a fix here should follow. It is not followed, for a
- # reason specific to this function: promotion would silently change the dtype a caller
- # explicitly asked for, on a function whose whole contract is "give me this dtype", and the
- # matrix feeds torch.jit-scripted warp_affine where a surprise dtype propagates. Rejecting
- # is the narrower change; #3948's own float output is not a dtype the caller named.
- # Four cells because the guard asks a zero-element probe whether the dtype is floating or
- # complex (TorchScript cannot reach dtype attributes): a signed/unsigned, narrow/wide, or
- # bool difference would show up here. uint8 is the one cell that already raised on base,
- # with RuntimeError: value cannot be converted to type uint8 without overflow from the
- # -1.0 offset rather than a silent truncation; it is kept because it pins that the error
- # is now kornia's own and uniform with the other three.
- # The dtype fixture is dropped because the claim is about the dtype argument itself.
- with pytest.raises(ValueError, match="floating point or complex"):
- kornia.geometry.conversions.normal_transform_pixel(4, 5, device=device, dtype=rejected_dtype)
- with pytest.raises(ValueError, match="floating point or complex"):
- kornia.geometry.conversions.normal_transform_pixel3d(2, 4, 5, device=device, dtype=rejected_dtype)
- # A 3-pixel image is the case where the scale 2/(size - 1) is integral, so an integer
- # dtype would have returned the exactly correct matrix on base. The rejection is uniform
- # over sizes by decision, not by accident, and this cell is what makes that a decision.
- with pytest.raises(ValueError, match="floating point or complex"):
- kornia.geometry.conversions.normal_transform_pixel(3, 3, device=device, dtype=rejected_dtype)
-
@pytest.mark.parametrize(
- "accepted_dtype",
- [torch.float16, torch.bfloat16, torch.complex64, getattr(torch, "float8_e4m3fn", None)],
+ ("requested_dtype", "accepted"),
+ [
+ (torch.int64, False),
+ (torch.int32, False),
+ (torch.uint8, False),
+ (torch.bool, False),
+ (torch.float16, True),
+ (torch.bfloat16, True),
+ (torch.complex64, True),
+ (torch.float8_e4m3fn, True),
+ ],
)
- def test_convention_non_default_float_and_complex_dtypes_are_accepted_3959(self, device, accepted_dtype):
- # The guard must reject integers WITHOUT narrowing the accepted set to the common floats.
- # Complex is accepted because a complex scale is a well-defined answer, and float8 because
- # it is an ordinary floating point dtype whose scales round rather than truncate: on base
- # float8_e4m3fn returned [[0.5, 0, -1], [0, 0.6875, -1], [0, 0, 1]], where 0.6875 is 2/3 in
- # that format. An allowlist rejected both float8 formats by omission, which is the reason
- # the guard asks a probe instead. Fetched through getattr because kornia declares
- # torch>=2.0.0 and the float8 dtypes are newer, in the style of the linalg.cross probe.
- if accepted_dtype is None:
- pytest.skip("this torch build has no float8_e4m3fn")
- matrix = kornia.geometry.conversions.normal_transform_pixel(4, 5, device=device, dtype=accepted_dtype)
- assert matrix.dtype == accepted_dtype
- assert matrix.shape == (1, 3, 3)
- # Asserting the value, not only the dtype and shape: an all-zero matrix is the failure this
- # whole change is about, and it would satisfy both of those.
- # Widening the result rather than narrowing the expectation keeps the complex cell exact
- # (a cast the other way discards the imaginary part and warns), and the tolerance is set
- # for float8_e4m3fn, where 2/3 is 0.6875. The comparison runs on cpu because mps supports
- # neither float64 nor complex128, and the device is asserted separately.
- assert matrix.device.type == torch.device(device).type
- expected = torch.tensor([[[0.5, 0.0, -1.0], [0.0, 2.0 / 3.0, -1.0], [0.0, 0.0, 1.0]]])
- self.assert_close(matrix.cpu().to(torch.complex128), expected.to(torch.complex128), atol=0.05, rtol=0.05)
-
- # The 3-D function carries its own copy of the guard, so an allowlist planted in that one
- # alone would leave this test green if it only called the 2-D function.
- matrix_3d = kornia.geometry.conversions.normal_transform_pixel3d(2, 4, 5, device=device, dtype=accepted_dtype)
- assert matrix_3d.dtype == accepted_dtype
- assert matrix_3d.shape == (1, 4, 4)
- assert matrix_3d.device.type == torch.device(device).type
- expected_3d = torch.tensor(
- [
- [
- [0.5, 0.0, 0.0, -1.0],
- [0.0, 2.0 / 3.0, 0.0, -1.0],
- [0.0, 0.0, 2.0, -1.0],
- [0.0, 0.0, 0.0, 1.0],
- ]
- ]
- )
- self.assert_close(matrix_3d.cpu().to(torch.complex128), expected_3d.to(torch.complex128), atol=0.05, rtol=0.05)
-
- def test_convention_integer_dtype_rejection_is_unconditional_3959(self, device):
- # The guard is deliberately NOT a KORNIA_CHECK. KORNIA_CHECK is gated on
- # _KORNIA_CHECKS_ENABLED, which disable_checks(), python -O and KORNIA_CHECKS=0 all clear,
- # and the module documents that as the production path -- so a KORNIA_CHECK here would
- # leave the rank-deficient matrix reachable in exactly the configuration a deployment
- # runs. This pin is the difference between the two tiers; if it fails, the guard has been
- # demoted to an optional assertion and kornia#3959 is unfixed under -O.
- # python -O cannot be entered from inside a test (the flag is read at import), so this
- # covers the runtime switch; the -O and KORNIA_CHECKS=0 legs are covered by construction,
- # the guard being a plain if/raise that reads no flag at all.
- checks_were_enabled = are_checks_enabled()
- disable_checks()
- try:
- assert not are_checks_enabled()
- with pytest.raises(ValueError, match="floating point or complex"):
- kornia.geometry.conversions.normal_transform_pixel(4, 5, device=device, dtype=torch.int64)
- finally:
- if checks_were_enabled:
- enable_checks()
+ def test_convention_integer_dtype_is_rejected_3959(self, device, requested_dtype, accepted):
+ # Both helpers accept every floating and complex dtype and reject integer and bool dtypes
+ # with kornia's own ValueError, which would otherwise truncate the fractional scales to 0
+ # and map every pixel to (-1, -1). The rejection is uniform over sizes (a 3-pixel axis,
+ # whose scale 2/(3 - 1) is integral, is rejected too) and unconditional: it is not a
+ # KORNIA_CHECK, so disable_checks() leaves it on. The accepted cells assert the values
+ # too, since an all-zero matrix would satisfy a dtype/shape check; the comparison is widened
+ # to complex128 on cpu (mps has neither), with a tolerance sized for float8_e4m3fn.
+ conversions = kornia.geometry.conversions
+ calls = [
+ (lambda: conversions.normal_transform_pixel(4, 5, device=device, dtype=requested_dtype), (1, 3, 3)),
+ (lambda: conversions.normal_transform_pixel3d(2, 4, 5, device=device, dtype=requested_dtype), (1, 4, 4)),
+ ]
+ if not accepted:
+ calls.append((lambda: conversions.normal_transform_pixel(3, 3, device=device, dtype=requested_dtype), None))
+ checks_were_enabled = are_checks_enabled()
+ disable_checks()
+ try:
+ for call, _ in calls:
+ with pytest.raises(ValueError, match="floating point or complex"):
+ call()
+ finally:
+ if checks_were_enabled:
+ enable_checks()
+ return
+
+ expected = {
+ (1, 3, 3): [[[0.5, 0.0, -1.0], [0.0, 2.0 / 3.0, -1.0], [0.0, 0.0, 1.0]]],
+ (1, 4, 4): [
+ [[0.5, 0.0, 0.0, -1.0], [0.0, 2.0 / 3.0, 0.0, -1.0], [0.0, 0.0, 2.0, -1.0], [0.0, 0.0, 0.0, 1.0]]
+ ],
+ }
+ for call, shape in calls:
+ matrix = call()
+ assert matrix.dtype == requested_dtype
+ assert matrix.shape == shape
+ assert matrix.device.type == torch.device(device).type
+ self.assert_close(
+ matrix.cpu().to(torch.complex128),
+ torch.tensor(expected[shape], dtype=torch.complex128),
+ atol=0.05,
+ rtol=0.05,
+ )
class TestNormalizeHomography(BaseTester):
@@ -4309,41 +3904,18 @@ class TestNormalizeHomography(BaseTester):
expected = torch.tensor([[[1.0, 0.0, 1.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype)
self.assert_close(normalized, expected, atol=0.0, rtol=0.0)
- def test_wart_identity_at_equal_sizes_is_exact_at_some_sizes_and_not_others(self, device):
- # Wart pin for the figures normalize_homography's kornia#3904 warning quotes. That warning
- # exists to say this function is NOT the cause of warp_perspective's 11.25 deviation under
- # align_corners=False, and it backs that up with how little this function itself deviates on
- # the identity at equal sizes. Both halves of that figure are pinned here, because the
- # tempting reading of it -- "exact where the 2/(size - 1) scale is dyadic" -- is FALSE:
- # measured over equal sizes 2..32 in float32 the deviation is 0 at 2, 3, 5, 8, 9, 10, 12,
- # 15..20, 22, 23, 24, 26, 28..32 and 5.96e-08 at 4, 6, 7, 11, 13, 14, 21, 25, 27, and 8
- # (scale 2/7) is exact while 4 (scale 2/3) is not. Which size lands where is a property of
- # the inverse-and-matmul chain, which is what the warning now says instead of a rule.
- # Two sizes are enough to hold that: (4, 4), the size the warning quotes and the one the
- # warp_perspective comparison uses, and (3, 3), an exact one -- a change that made the chain
- # exact everywhere, or inexact everywhere, moves one of them.
- # float32 is hardcoded and the dtype fixture dropped: 5.96e-08 IS 2**-24, a float32 rounding
- # step, so the figure is only meaningful in float32 and every other dtype would need its own.
- # NOT a contract that these sizes must keep these residuals -- the class header's #3904 note
- # covers the whole surface. #3904 has since landed and moved neither cell, because it left
- # the default at align_corners=True; at align_corners=False the two sets differ (4 is exact
- # there and 3 is not), which is why the warning now quotes the default's figures only.
- # Snippet used to generate expected (torch only, executed on cpu, torch 2.9.1):
- # I = torch.eye(3)[None]
- # (normalize_homography(I, (n, n), (n, n)) - I).abs().max() for n = 4 -> 5.960464477539063e-08
- # for n = 3 -> 0.0
+ @pytest.mark.parametrize("size", [3, 4, 7, 16])
+ def test_convention_identity_at_equal_sizes_is_the_identity_to_one_float32_step(self, device, size):
+ # For equal source and destination sizes the identity homography normalizes back to the
+ # identity to within one float32 rounding step (2**-24); which sizes land on exactly 0 is a
+ # property of the inverse-and-matmul chain and is not pinned.
_skip_if_dtype_unavailable(device, torch.float32)
_skip_if_closed_form_inverse_unavailable(device, torch.float32)
identity = torch.eye(3, device=device, dtype=torch.float32)[None]
- inexact = kornia.geometry.conversions.normalize_homography(identity, (4, 4), (4, 4))
- exact = kornia.geometry.conversions.normalize_homography(identity, (3, 3), (3, 3))
+ normalized = kornia.geometry.conversions.normalize_homography(identity, (size, size), (size, size))
- assert (inexact - identity).abs().max().item() == 2.0**-24, (
- "normalize_homography's #3904 warning quotes 5.96e-08 for the identity at equal sizes "
- f"(4, 4); got {(inexact - identity).abs().max().item()!r}"
- )
- self.assert_close(exact, identity, atol=0.0, rtol=0.0)
+ assert (normalized - identity).abs().max().item() <= 2.0**-24
def test_convention_dsize_src_is_the_right_factor_and_dsize_dst_the_left(self, device, dtype):
# Convention pin: normalize_homography(H, dsize_src, dsize_dst) composes
@@ -4447,78 +4019,6 @@ class TestNormalizeHomography(BaseTester):
self.assert_close(non_dyadic, homography, atol=32.0 * eps, rtol=8.0 * eps)
self.assert_close(non_dyadic_reverse, homography, atol=32.0 * eps, rtol=8.0 * eps)
- # The two pins below are the negative half of the round-trip claim above, which the pin above
- # cannot express because it only ever runs the configuration that DOES come back bitwise:
- # denormalize_homography's bullet says dyadic sizes on their own are neither necessary nor
- # sufficient for a bitwise round trip, and each half of that needs a counterexample or it is an
- # unfalsifiable hedge. Both inputs are hardcoded rather than searched for, and both are
- # deterministic -- no rand, so neither pin can go quiet on a lucky seed. They are split into two
- # tests, and each hardcodes ONE dtype with the fixture dropped, because each half IS a statement
- # about one dtype: the same identity at (4, 5) -> (8, 9) in float32 misses through
- # denormalize(normalize(.)) and returns bitwise through the reverse, so a dtype-parameterized
- # form of either half would be false on the other dtype. Split rather than one test with two
- # dtypes so that on a backend without float64 (mps) the sufficiency half still reports as run.
- # NEITHER is a contract that these particular inputs must keep landing on these verdicts -- if a
- # cell flips, re-derive the bullet's "neither necessary nor sufficient" from whatever the new
- # counterexamples are.
-
- def test_convention_dyadic_sizes_are_not_sufficient_for_a_bitwise_round_trip(self, device):
- # The same dyadic sizes (3, 5) -> (5, 9) as the round-trip pin above, with entries that are
- # NOT dyadic, miss in float32 through BOTH legs. This is what makes that pin's "property of
- # the whole computation, not of the sizes" sentence load-bearing: nothing about the sizes
- # changed between this case and the bitwise one, only H.
- # Snippet used to generate expected (torch only, executed on cpu, torch 2.9.1):
- # H = [[1.1, 0.2, 3], [-0.3, 0.9, 1], [0.05, 0.1, 1]] (float32)
- # torch.equal(denormalize_homography(normalize_homography(H, (3,5), (5,9)), (3,5), (5,9)), H) -> False
- # torch.equal(normalize_homography(denormalize_homography(H, (3,5), (5,9)), (3,5), (5,9)), H) -> False
- _skip_if_dtype_unavailable(device, torch.float32)
- _skip_if_closed_form_inverse_unavailable(device, torch.float32)
- normalize_homography = kornia.geometry.conversions.normalize_homography
- denormalize_homography = kornia.geometry.conversions.denormalize_homography
- not_dyadic_entried = torch.tensor(
- [[[1.1, 0.2, 3.0], [-0.3, 0.9, 1.0], [0.05, 0.1, 1.0]]], device=device, dtype=torch.float32
- )
-
- forward = denormalize_homography(normalize_homography(not_dyadic_entried, (3, 5), (5, 9)), (3, 5), (5, 9))
- reverse = normalize_homography(denormalize_homography(not_dyadic_entried, (3, 5), (5, 9)), (3, 5), (5, 9))
-
- assert not torch.equal(forward, not_dyadic_entried), (
- "dyadic sizes now make denormalize(normalize(H)) bitwise for a non-dyadic-entried H in "
- "float32, so denormalize_homography's 'not sufficient' half has lost its counterexample"
- )
- assert not torch.equal(reverse, not_dyadic_entried), (
- "dyadic sizes now make normalize(denormalize(H)) bitwise for a non-dyadic-entried H in "
- "float32, so denormalize_homography's 'not sufficient' half has lost its counterexample"
- )
-
- def test_convention_dyadic_sizes_are_not_necessary_for_a_bitwise_round_trip(self, device):
- # The float64 identity comes back bitwise through BOTH legs at the non-dyadic
- # (4, 5) -> (8, 9) -- the exact size pair where the round-trip pin above has to fall back to
- # a 32 * eps tolerance for a general H.
- # Snippet used to generate expected (torch only, executed on cpu, torch 2.9.1):
- # I = torch.eye(3)[None] (float64), sizes (4, 5) -> (8, 9)
- # torch.equal(denormalize_homography(normalize_homography(I, (4,5), (8,9)), (4,5), (8,9)), I) -> True
- # torch.equal(normalize_homography(denormalize_homography(I, (4,5), (8,9)), (4,5), (8,9)), I) -> True
- _skip_if_dtype_unavailable(device, torch.float64)
- _skip_if_closed_form_inverse_unavailable(device, torch.float64)
- normalize_homography = kornia.geometry.conversions.normalize_homography
- denormalize_homography = kornia.geometry.conversions.denormalize_homography
- identity = torch.eye(3, device=device, dtype=torch.float64)[None]
-
- forward = denormalize_homography(normalize_homography(identity, (4, 5), (8, 9)), (4, 5), (8, 9))
- reverse = normalize_homography(denormalize_homography(identity, (4, 5), (8, 9)), (4, 5), (8, 9))
-
- assert torch.equal(forward, identity), (
- "the float64 identity no longer survives denormalize(normalize(.)) bitwise at the "
- "non-dyadic (4, 5) -> (8, 9), so denormalize_homography's 'not necessary' half has "
- "lost its counterexample"
- )
- assert torch.equal(reverse, identity), (
- "the float64 identity no longer survives normalize(denormalize(.)) bitwise at the "
- "non-dyadic (4, 5) -> (8, 9), so denormalize_homography's 'not necessary' half has "
- "lost its counterexample"
- )
-
def test_convention_batch_is_per_sample(self, device, dtype):
# Convention pin: both functions are per-sample -- the result for one batch element does not
# depend on the others, bit for bit -- and the leading batch dimension is preserved. Pinned
@@ -4704,158 +4204,33 @@ class TestNormalizeHomography(BaseTester):
msg=_issue_msg("kornia#3958: the ambient default dtype no longer decides the constants' precision"),
)
- def test_wart_integer_input_raises_or_nans_by_backend_3959(self, device):
- # Wart pin for kornia#3959's homography reach, companion to normalize_homography's
- # integer-input warning: the normalization matrices are cast to the input's int64 by
- # .to(input), truncating their scales to zero (the CALLER does the truncating here: both
- # functions call normal_transform_pixel WITHOUT a dtype and cast the float result with
- # .to(input), so normal_transform_pixel's own dtype guard never sees the int64 and this
- # leg of kornia#3959 is untouched by it), and the downstream
- # failure differs by backend. normalize_homography dies in the FINAL CHAIN MATMUL with a
- # RuntimeError -- the closed-form inverse does not raise, it silently promotes the
- # truncated int64 matrix to an all-nan float32 one, and the int64-vs-float32 matmul then
- # rejects the mix. denormalize_homography inverts the other matrix and by the other route
- # -- _torch_inverse_cast, i.e. torch.linalg.inv -- which dies on the zero diagonal of the
- # truncated matrix before any matmul runs.
- # Both legs are gated by capability PROBES rather than a device-name list: each probe IS
- # the mechanism its leg claims, so a future backend that behaves like cpu is covered instead
- # of skipped. Executed: cpu rejects the mixed batched matmul and reports a singular
- # inverse as torch.linalg.LinAlgError; mps accepts the matmul (hence the all-nan float32
- # result) and reports the singular inverse as a plain RuntimeError. The matmul probe must
- # be BATCHED -- the unbatched 2-D mixed form raises on both backends, so it would
- # discriminate nothing.
- # No message text is asserted -- torch may reword either message (the snippet quotes them
- # as samples). The exception TYPE plus the module-level _raised_by_a_kornia_guard is what
- # carries the claim instead: both raising legs assert that the failure came from downstream
- # arithmetic and NOT from a kornia guard, so a dtype guard added by a #3959 fix flips these
- # cells loudly in any style -- including a literal `raise RuntimeError(...)`, which the
- # type test alone could not tell apart from today's matmul failure. That second assert is
- # also what machine-checks the mechanism sentence above: it fails if the raise moves off
- # the chain matmul / linalg.inv statements into a guard.
- # If any cell fails, #3959 was (partly) fixed -- update or remove the warning. NOT a
- # contract that integer input must keep failing this way.
- # Snippet used to generate expected (torch only, executed on cpu and mps, torch 2.9.1):
- # normalize_homography(torch.eye(3, dtype=torch.int64)[None], (4, 5), (8, 9))
- # cpu -> RuntimeError: expected scalar type Long but found Float
- # raised at conversions.py's
- # dst_norm_trans_dst_pix @ (dst_pix_trans_src_pix @ src_pix_trans_src_norm)
- # mps -> all-nan float32 matrix, no error
- # _inverse_3x3_closed_form(normal_transform_pixel(4, 5).to(torch.int64))
- # cpu -> no exception; returns an all-nan float32 matrix
- # denormalize_homography(torch.eye(3, dtype=torch.int64)[None], (4, 5), (8, 9))
- # cpu -> torch.linalg.LinAlgError: linalg.inv: (Batch element 0): The diagonal
- # element 2 is zero, the inversion could not be completed
- # mps -> RuntimeError (linalg.inv on a singular matrix is an internal assert there)
+ @pytest.mark.parametrize("op_name", ["normalize_homography", "denormalize_homography"])
+ def test_wart_integer_input_raises_or_nans_by_backend_3959(self, device, op_name):
+ # Wart pin for kornia#3959: an int64 homography is not rejected by a kornia guard. The
+ # normalization matrices are cast to int64 with .to(input), truncating their scales to 0,
+ # and the call then fails inside torch arithmetic or returns an all-NaN matrix, depending
+ # on the backend. Flips when a guard lands (the failure is classified by
+ # _raised_by_a_kornia_guard, not by its type or message) or when integers are promoted
+ # (the result would be finite).
identity = torch.eye(3, device=device, dtype=torch.int64)[None]
-
- try:
- _ = (
- torch.eye(3, device=device, dtype=torch.int64)[None]
- @ torch.eye(3, device=device, dtype=torch.float32)[None]
- )
- except RuntimeError:
- mixed_matmul_rejected = True
- else:
- mixed_matmul_rejected = False
-
- if mixed_matmul_rejected:
- with pytest.raises(RuntimeError) as normalize_err:
- kornia.geometry.conversions.normalize_homography(identity, (4, 5), (8, 9))
- assert not _raised_by_a_kornia_guard(normalize_err.value), (
- "kornia#3959: normalize_homography now rejects integer input in a guard of its own "
- "-- update or remove the warning"
- )
- else:
- out = kornia.geometry.conversions.normalize_homography(identity, (4, 5), (8, 9))
- assert out.dtype == torch.float32, "kornia#3959: the accepting int64 result is no longer float32"
- assert out.isnan().all(), "kornia#3959: the accepting int64 result is no longer all-nan"
-
- try:
- torch.linalg.inv(torch.zeros(1, 3, 3, device=device, dtype=torch.float32))
- except RuntimeError as err:
- singular_inverse_error = type(err)
- else:
- singular_inverse_error = None
-
- if singular_inverse_error is None:
- pytest.skip("backend does not raise on a singular linalg.inv; #3959's denormalize leg has no failure here")
-
- with pytest.raises(singular_inverse_error) as denormalize_err:
- kornia.geometry.conversions.denormalize_homography(identity, (4, 5), (8, 9))
-
- assert not _raised_by_a_kornia_guard(denormalize_err.value), (
- "kornia#3959: denormalize_homography now rejects integer input in a guard of its own "
- "-- update or remove the warning"
- )
-
- @pytest.mark.parametrize(("op_name", "wrong_size"), _WRONG_SIZE_CASES, ids=_WRONG_SIZE_IDS)
- def test_convention_wrong_sized_matrices_are_rejected_by_the_shape_guard_3960(self, op_name, wrong_size, device):
- # Convention: a matrix of the wrong size is rejected by the function's own shape guard,
- # with a message naming the argument -- the same thing the guard already did for a rank-2
- # input of the wrong shape. Until kornia#3960 was fixed the guard read
- # `len(shape) == 3 or shape[-2:] == (3, 3)`, and the `or` meant any rank-3 tensor passed
- # whatever its trailing shape was, so a (1, 4, 4) input to the 3x3 functions (and a
- # (1, 3, 3) input to the 4x4 one) reached the matmul and died there with a message naming
- # neither the argument nor the expected shape. The guard now reads
- # `ndim in (2, 3) and shape[-2:] == (3, 3)`.
- # Three cells because the three functions carry three separate copies of the guard.
- # The body classifies the exception rather than asserting a type: the fix is a plain
- # `raise ValueError(...)` today, but a later rewrite to KORNIA_CHECK_SHAPE would raise a
- # ShapeError and a type test would fail on a change that keeps the convention. float32 is
- # hardcoded and the dtype fixture dropped because a shape guard runs before any arithmetic
- # and cannot depend on the dtype.
- # Classified by the module-level _raised_by_a_kornia_guard, so a guard in ANY style --
- # including a literal `raise RuntimeError(...)`, which no type test could tell apart from
- # the old matmul failure -- counts as guarded. An exception raised at an arithmetic
- # statement counts as unguarded, so a regression that reopens #3960 fails this pin instead
- # of passing on the raise alone. The cells come from the shared _WRONG_SIZE_CASES table.
op = getattr(kornia.geometry.conversions, op_name)
- wrong = torch.eye(wrong_size, device=device, dtype=torch.float32)[None]
try:
- op(wrong, *_homography_sizes(op_name))
+ out = op(identity, (4, 5), (8, 9))
except Exception as err:
- guarded = _raised_by_a_kornia_guard(err)
- else:
- guarded = False
-
- assert guarded, f"kornia#3960: {op_name} did not reject a ({wrong_size}, {wrong_size}) matrix in its guard"
-
- def test_convention_normalize_homography3d_shape_error_names_bx4x4_3960(self, device):
- # The message half of kornia#3960, and the reason it is pinned apart from the cells above:
- # normalize_homography3d is a 4x4 function whose guard used to report "must be a Bx3x3
- # tensor", so a fix that only tightened the guard's *condition* would have left the wrong
- # noun in place and the cells above would still have passed. This input is rejected by the
- # guard on either side of the fix -- only the noun changed -- which is why it asserts the
- # message text where the cells above deliberately assert none.
- # Snippet used to generate expected (torch only, executed on cpu float32):
- # normalize_homography3d(torch.zeros(4, 5), (2, 4, 5), (3, 8, 9))
- # -> ValueError: Input dst_pix_trans_src_pix must be a Bx4x4 tensor. Got torch.Size([4, 5])
- with pytest.raises(ValueError, match="must be a Bx4x4 tensor"):
- kornia.geometry.conversions.normalize_homography3d(
- torch.zeros(4, 5, device=device, dtype=torch.float32), (2, 4, 5), (3, 8, 9)
+ assert not _raised_by_a_kornia_guard(err), (
+ f"kornia#3959: {op_name} now rejects integer input in a guard of its own -- update the warning"
)
+ else:
+ assert out.isnan().all(), f"kornia#3959: {op_name} now returns a finite result for integer input"
- @pytest.mark.parametrize("op_name", _HOMOGRAPHY_OP_NAMES)
- def test_convention_the_guard_accepts_rank_2_and_3_and_rejects_higher_3960(self, op_name, device):
- # The rank half of the #3960 guard rewrite, and the two cases the wrong-size cells above
- # cannot see -- they only ever pass rank-3 inputs.
- # (1) An UNBATCHED matrix of the right size is accepted. The old `or` guard let it through
- # by its second clause, so this is behavior the fix had to PRESERVE, not behavior it
- # introduced: a narrower fix reading `ndim == 3 and shape[-2:] == (N, N)` would have
- # broken it, and nothing else in this file covers the unbatched path through these
- # three functions. The returned shape is (1, N, N), not (N, N) -- the composition
- # broadcasts against normal_transform_pixel's leading 1 and the input's missing batch
- # axis is not restored. Asserted as-is because it is what the old guard's callers
- # already got; kornia#3957's batch-axis policy is pinned elsewhere.
- # (2) A rank-4 input is now REJECTED, which the old `or` guard accepted through its second
- # clause: `normalize_homography(eye(3).expand(2, 1, 3, 3), (4, 5), (8, 9))` used to
- # broadcast all the way through and return a (2, 1, 3, 3) matrix. That is the
- # tightening #3960 asks for -- all three functions document a Bx3x3/Bx4x4 argument --
- # and it is pinned here so the break is deliberate rather than incidental.
- # The guard is what is under test, so the accepting leg asserts only the returned shape;
- # the values are pinned by the numerical tests above. float32 is hardcoded and the dtype
- # fixture dropped for the same reason as the cells above.
+ @pytest.mark.parametrize(("op_name", "wrong_size"), _WRONG_SIZE_CASES, ids=_WRONG_SIZE_IDS)
+ def test_convention_the_shape_guard_accepts_rank_2_and_3_only_3960(self, op_name, wrong_size, device):
+ # Each of the three functions carries its own copy of the shape guard. It accepts an
+ # unbatched (N, N) or a batched (B, N, N) matrix -- both come back as (1, N, N) here -- and
+ # rejects a wrong-sized matrix and a rank-4 one itself, with a ValueError naming the
+ # argument and the expected BxNxN shape. _raised_by_a_kornia_guard tells that apart from a
+ # failure inside the matmul, which is what a wrong-sized matrix reached before #3960.
op = getattr(kornia.geometry.conversions, op_name)
size = 4 if op_name.endswith("3d") else 3
sizes = _homography_sizes(op_name)
@@ -4864,8 +4239,14 @@ class TestNormalizeHomography(BaseTester):
assert op(eye, *sizes).shape == (1, size, size)
assert op(eye[None], *sizes).shape == (1, size, size)
- with pytest.raises(ValueError, match="dst_pix_trans_src_pix"):
- op(eye.expand(2, 1, size, size), *sizes)
+ wrong_sized = torch.eye(wrong_size, device=device, dtype=torch.float32)[None]
+ for rejected in (wrong_sized, eye.expand(2, 1, size, size)):
+ with pytest.raises(Exception) as excinfo:
+ op(rejected, *sizes)
+ assert _raised_by_a_kornia_guard(excinfo.value), (
+ f"kornia#3960: {op_name} did not reject a {tuple(rejected.shape)} matrix in its guard"
+ )
+ assert f"dst_pix_trans_src_pix must be a Bx{size}x{size} tensor" in str(excinfo.value)
def test_singleton_dsize_produces_finite_homographies(self, device):
identity = torch.eye(3, device=device, dtype=torch.float32)[None]
@@ -5274,67 +4655,45 @@ class TestRt2Extrinsics(BaseTester):
self.assert_close(extrinsics[0, :3, 3], torch.zeros(3, device=device, dtype=torch.float32), atol=0.0, rtol=0.0)
def test_wart_int64_Rt_raises_while_4x4_and_pose_forms_accept_3959(self, device):
- # Wart pin for the int64 dichotomy this family documents: Rt_to_matrix4x4 and the two
- # frame functions built on it raise RuntimeError on an int64 (R, t) -- the appended float
- # homogeneous row cannot be cast to Long -- while the _4x4 forms and the
- # transpose-negate-multiply pose pair accept int64 and return int64. Part of the
- # kornia#3959 integer-dtype family; without this pin, a torch promotion change in cat/pad
- # or a dtype guard added to one side would invalidate the docstring warnings with nothing
- # flipping red. RuntimeError is asserted by type only (the message is torch's and may be
- # reworded; a sample is quoted in the snippet), and each raising leg additionally asserts
- # through the module-level _raised_by_a_kornia_guard that the failure came from downstream
- # arithmetic rather than from a guard -- so a #3959 dtype guard flips these legs loudly in
- # any style, a bare `raise RuntimeError(...)` included.
- # Maintenance map, if any leg fails (#3959 was partly fixed, or torch promotion changed).
- # Five docstrings carry int64 text, two of them the carriers and three pointers into them:
- # carriers: Rt_to_matrix4x4, camtoworld_graphics_to_vision_4x4
- # pointers: camtoworld_graphics_to_vision_Rt, camtoworld_vision_to_graphics_4x4,
- # camtoworld_vision_to_graphics_Rt
- # Edit the two carriers, then re-check that the three pointers still describe what they
- # point at. camtoworld_to_worldtocam_Rt is deliberately NOT on this list: its int64
- # acceptance is exercised below but its docstring carries no integer text (only the #3961
- # non-orthogonal-R warning), so there is nothing there to update.
- # NOT a contract that the raising side must keep raising.
- # The accepting legs run only where the backend implements integer batched matmul (probed
- # visibly below): PyTorch 2.9.1 implements it for no integer dtype on CUDA -- source-
- # derived from that release's aten/src/ATen/native/cuda/Blas.cpp, not executed here, and
- # the probe rather than this comment is what decides -- so there the accepting side is a
- # torch limitation, not a kornia guard, and the warnings scope their accept-and-return-
- # int64 sentences to cpu/mps for the same reason. The raising legs run everywhere -- they
- # raise RuntimeError on every backend, whichever operation dies first.
+ # Wart pin for kornia#3959: no function in this family guards against an int64 pose.
+ # Rt_to_matrix4x4 and the two frame functions built on it fail inside torch (the appended
+ # float row cannot be cast to Long), while the _4x4 forms and the pose pair return int64
+ # wherever the backend has integer batched matmul, and fail inside torch elsewhere. Every
+ # failure is classified by _raised_by_a_kornia_guard rather than by its type or message, so
+ # the pin flips when a guard is added to either side or when integers are promoted.
# Snippet used to generate expected (torch only, executed on cpu):
- # Rt_to_matrix4x4(eye(3, int64)[None], ones(1, 3, 1, int64))
- # -> RuntimeError: result type Float can't be cast to the desired output type Long
- # camtoworld_graphics_to_vision_4x4(eye(4, int64)[None]).dtype -> torch.int64
- # camtoworld_to_worldtocam_Rt(eye(3, int64)[None], ones(1, 3, 1, int64))
- # -> (int64, int64)
+ # Rt_to_matrix4x4(eye(3, int64)[None], ones(1, 3, 1, int64)) -> RuntimeError
+ # camtoworld_graphics_to_vision_4x4(eye(4, int64)[None]).dtype -> torch.int64
+ # camtoworld_to_worldtocam_Rt(eye(3, int64)[None], ones(1, 3, 1, int64)) -> (int64, int64)
rotation = torch.eye(3, device=device, dtype=torch.int64)[None]
translation = torch.ones(1, 3, 1, device=device, dtype=torch.int64)
extrinsics = torch.eye(4, device=device, dtype=torch.int64)[None]
for op in (Rt_to_matrix4x4, camtoworld_graphics_to_vision_Rt, camtoworld_vision_to_graphics_Rt):
- with pytest.raises(RuntimeError) as excinfo:
+ with pytest.raises(Exception) as excinfo:
op(rotation, translation)
assert not _raised_by_a_kornia_guard(excinfo.value), (
- f"kornia#3959: {op.__name__} now rejects int64 (R, t) in a guard of its own -- "
- "update the docstring warnings named in the map above"
- )
-
- try:
- torch.eye(2, device=device, dtype=torch.int64)[None] @ torch.eye(2, device=device, dtype=torch.int64)[None]
- except RuntimeError:
- pytest.skip("backend implements no integer batched matmul; the accepting side of #3959 is cpu/mps-scoped")
-
- for op in (camtoworld_graphics_to_vision_4x4, camtoworld_vision_to_graphics_4x4):
- assert op(extrinsics).dtype == torch.int64, (
- "kornia#3959: the _4x4 side of the int64 dichotomy no longer accepts integer input"
+ f"kornia#3959: {op.__name__} now rejects int64 (R, t) in a guard of its own -- update the warning"
)
- for op in (camtoworld_to_worldtocam_Rt, worldtocam_to_camtoworld_Rt):
- pose_R, pose_t = op(rotation, translation)
- assert pose_R.dtype == torch.int64 and pose_t.dtype == torch.int64, (
- "kornia#3959: the pose pair no longer accepts integer input"
- )
+ accepting = [
+ (camtoworld_graphics_to_vision_4x4, (extrinsics,)),
+ (camtoworld_vision_to_graphics_4x4, (extrinsics,)),
+ (camtoworld_to_worldtocam_Rt, (rotation, translation)),
+ (worldtocam_to_camtoworld_Rt, (rotation, translation)),
+ ]
+ for op, args in accepting:
+ try:
+ out = op(*args)
+ except Exception as err:
+ assert not _raised_by_a_kornia_guard(err), (
+ f"kornia#3959: {op.__name__} now rejects int64 input in a guard of its own -- update the warning"
+ )
+ else:
+ outputs = out if isinstance(out, tuple) else (out,)
+ assert all(o.dtype == torch.int64 for o in outputs), (
+ f"kornia#3959: {op.__name__} no longer returns int64 for int64 input"
+ )
@pytest.mark.parametrize(
("op_name", "shapes"),
@@ -5364,27 +4723,32 @@ class TestRt2Extrinsics(BaseTester):
# (B, 3, 3) + (B, 3, 1) and (B, 4, 4) -- no unbatched form, no (B, 3) translation, no
# transposed (B, 1, 3) translation, no extra leading batch dimensions. This is the strict
# end of the family: camtoworld_to_worldtocam_Rt broadcasts a (1, 3, 1) translation across
- # a (2, 3, 3) rotation where Rt_to_matrix4x4 raises, which the Convention blocks record.
- # The batch-mismatch case is a torch.cat RuntimeError, pinned in
- # test_convention_batch_sizes_must_match below. Assertion policy and the float32 hardcoding
- # are documented once on the shared _assert_strictly_batched helper.
+ # a (2, 3, 3) rotation where Rt_to_matrix4x4 raises, which
+ # test_wart_batch_size_mismatch_is_not_guarded_4774 below pins. Assertion policy and the
+ # float32 hardcoding are documented once on the shared _assert_strictly_batched helper.
_assert_strictly_batched(op_name, shapes, device)
- def test_convention_batch_sizes_must_match(self, device):
- # Convention pin: Rt_to_matrix4x4 does NOT broadcast -- a batch of 2 rotations with a single
- # translation raises inside torch.cat instead of repeating the translation. RuntimeError is
- # asserted by type only: the message is entirely PyTorch's wording and may be reworded (a
- # sample is quoted in the snippet), same rule as the int64 pin above.
- # float32 is hardcoded for the same reason as the pin above.
- # Snippet used to generate expected (torch only, executed on cpu float32):
- # Rt_to_matrix4x4(torch.eye(3).expand(2, 3, 3), torch.ones(1, 3, 1))
- # -> RuntimeError: Sizes of tensors must match except in dimension 2. Expected size 2
- # but got size 1 for tensor number 1 in the list.
- rotation = torch.eye(3, device=device, dtype=torch.float32).expand(2, 3, 3)
- translation = torch.ones(1, 3, 1, device=device, dtype=torch.float32)
+ def test_wart_batch_size_mismatch_is_not_guarded_4774(self, device):
+ # Wart pin for kornia#4774: no kornia guard compares the batch sizes of R and t.
+ # Rt_to_matrix4x4 fails inside torch.cat, while camtoworld_to_worldtocam_Rt broadcasts the
+ # same pair -- and with R of batch 1 and t of batch 2 returns outputs of different batch
+ # sizes. Flips under either fix: a shared guard (the Rt_to_matrix4x4 failure becomes a
+ # guard's, and the pose pair raises) or consistent broadcasting.
+ rotation_batch_2 = torch.eye(3, device=device, dtype=torch.float32).expand(2, 3, 3)
+ translation_batch_1 = torch.ones(1, 3, 1, device=device, dtype=torch.float32)
- with pytest.raises(RuntimeError):
- Rt_to_matrix4x4(rotation, translation)
+ with pytest.raises(Exception) as excinfo:
+ Rt_to_matrix4x4(rotation_batch_2, translation_batch_1)
+ assert not _raised_by_a_kornia_guard(excinfo.value), (
+ "kornia#4774: Rt_to_matrix4x4 now rejects mismatched batch sizes in a guard of its own"
+ )
+
+ inverted_R, inverted_t = camtoworld_to_worldtocam_Rt(
+ torch.eye(3, device=device, dtype=torch.float32)[None], torch.ones(2, 3, 1, device=device)
+ )
+ assert (inverted_R.shape[0], inverted_t.shape[0]) == (1, 2), (
+ "kornia#4774: camtoworld_to_worldtocam_Rt no longer returns mismatched batch sizes"
+ )
class TestCamtoworldGraphicsToVision(BaseTester):
@@ -5520,89 +4884,37 @@ class TestCamtoworldGraphicsToVision(BaseTester):
rtol=0.0,
)
- def test_convention_all_four_functions_are_the_same_involution(self, device, dtype):
- # Convention pin: diag(1, -1, -1, 1) is its own inverse, so graphics_to_vision and
- # vision_to_graphics are the IDENTICAL map -- the direction in the name is documentation for
- # the reader, not behavior -- and applying either one twice returns the input value-exactly
- # (atol=rtol=0, no rounding). VALUE-exactly and not bitwise: assert_close at atol=rtol=0
- # treats -0.0 and +0.0 as equal, and the flip does not preserve the sign of a zero, which
- # test_convention_involution_normalises_signed_zero below pins on the raw words. Both
- # halves are executed here rather than argued from the shared implementation: the two 4x4
- # functions are compared on the same input, the Rt pair is compared against the 4x4 pair,
- # and each round trip is run.
- # Practical consequence recorded by this pin: nothing in the API can detect that a pose was
- # already converted, so a double conversion is silently a no-op.
- # Snippet used to generate expected (torch only, executed on cpu):
- # camtoworld_vision_to_graphics_4x4(M) == camtoworld_graphics_to_vision_4x4(M) (bitwise)
- # camtoworld_graphics_to_vision_4x4(camtoworld_graphics_to_vision_4x4(M)) == M (bitwise)
+ @pytest.mark.parametrize(
+ ("forward_name", "backward_name"),
+ [
+ ("camtoworld_graphics_to_vision_4x4", "camtoworld_vision_to_graphics_4x4"),
+ ("camtoworld_graphics_to_vision_Rt", "camtoworld_vision_to_graphics_Rt"),
+ ("camtoworld_to_worldtocam_Rt", "worldtocam_to_camtoworld_Rt"),
+ ],
+ ids=["graphics-vision-4x4", "graphics-vision-Rt", "camtoworld-worldtocam"],
+ )
+ def test_convention_both_directions_are_the_same_involution(self, device, dtype, forward_name, backward_name):
+ # Convention pin: each pair is one map under two names -- the direction in the name is
+ # documentation -- and applying it twice, or once in each direction, returns the input
+ # (value-exactly for this pose, whose entries keep every product exact). So nothing can
+ # detect that a pose was already converted. The pose pair holds because R is a rotation;
+ # test_wart_non_orthogonal_rotation_is_transposed_not_inverted_3961 pins the other case.
_skip_if_dtype_unavailable(device, dtype)
rotation, translation = _asymmetric_pose(device, dtype)
- extrinsics = Rt_to_matrix4x4(rotation, translation)
-
- to_vision = camtoworld_graphics_to_vision_4x4(extrinsics)
- to_graphics = camtoworld_vision_to_graphics_4x4(extrinsics)
-
- self.assert_close(to_graphics, to_vision, atol=0.0, rtol=0.0)
- self.assert_close(camtoworld_graphics_to_vision_4x4(to_vision), extrinsics, atol=0.0, rtol=0.0)
- self.assert_close(camtoworld_vision_to_graphics_4x4(to_vision), extrinsics, atol=0.0, rtol=0.0)
-
- vision_R, vision_t = camtoworld_graphics_to_vision_Rt(rotation, translation)
- graphics_R, graphics_t = camtoworld_vision_to_graphics_Rt(rotation, translation)
-
- self.assert_close(graphics_R, vision_R, atol=0.0, rtol=0.0)
- self.assert_close(graphics_t, vision_t, atol=0.0, rtol=0.0)
- self.assert_close(Rt_to_matrix4x4(vision_R, vision_t), to_vision, atol=0.0, rtol=0.0)
-
- def test_convention_involution_normalises_signed_zero(self, device):
- # Convention pin for the one place the involution above is exact in VALUE but not in BITS,
- # which the docstring states and no assert_close can check: assert_close at atol=rtol=0
- # compares -0.0 equal to +0.0, so the pin above would pass either way and the docstring's
- # "value-exact, not bitwise" clause would be unfalsifiable. Compared on the raw words
- # instead, through an int32 view of the float32 buffer.
- # The mechanism, and why it is not specific to the two flipped columns: the flip is
- # extrinsics @ diag(1, -1, -1, 1), a matmul, so every output entry is a sum of four
- # products. A -0.0 input entry contributes -0.0 to that sum and the other three terms
- # contribute +0.0, and IEEE-754 round-to-nearest gives -0.0 + 0.0 = +0.0. So EVERY signed
- # zero in the input is normalised to +0.0, in any column, on the FIRST application already,
- # and a second application cannot restore it.
- # float32 is hardcoded and the dtype fixture dropped: the subject is a sign bit, the
- # comparison needs a fixed-width integer view to read it, and the summation that loses the
- # sign is the same in every dtype.
- # NOT a contract that the flip must clear these sign bits -- if a future implementation
- # multiplies elementwise instead of through a matmul, -0.0 * -1.0 = +0.0 and -0.0 * 1.0
- # stays -0.0, so the flipped columns would flip signs and the rest would be preserved.
- # Then this pin fails and the docstring clause is what gets re-derived.
- # The input is built from a nested literal rather than by assigning -0.0 into a zeros
- # tensor: on mps (torch 2.9.1, executed) a Python-scalar assignment writes +0.0, so the
- # item-assignment form would silently build an input with no signed zeros in it and the pin
- # would assert nothing there. The guard below is what makes that failure loud, not silent.
- # Snippet used to generate expected (torch only, executed on cpu, torch 2.9.1):
- # M = torch.tensor([[[0., -0., 0., 0.], [0.] * 4, [0.] * 4, [0.] * 4]])
- # torch.signbit(camtoworld_graphics_to_vision_4x4(M))[0, 0, 1] -> False
- signed_zeros = torch.tensor(
- [
- [
- [0.0, -0.0, 0.0, 0.0],
- [-0.0, 0.0, -0.0, 0.0],
- [0.0, -0.0, 0.0, 0.0],
- [0.0, 0.0, 0.0, 0.0],
- ]
- ],
- device=device,
- dtype=torch.float32,
- )
- assert torch.signbit(signed_zeros).sum().item() == 4, "the input lost its signed zeros before the call"
+ pose = (Rt_to_matrix4x4(rotation, translation),) if forward_name.endswith("4x4") else (rotation, translation)
+ forward = getattr(kornia.geometry.conversions, forward_name)
+ backward = getattr(kornia.geometry.conversions, backward_name)
- once = camtoworld_graphics_to_vision_4x4(signed_zeros)
- twice = camtoworld_graphics_to_vision_4x4(once)
+ def call(op, args):
+ out = op(*args)
+ return out if isinstance(out, tuple) else (out,)
- self.assert_close(twice, signed_zeros, atol=0.0, rtol=0.0)
- assert not torch.equal(twice.view(torch.int32), signed_zeros.view(torch.int32)), (
- "the involution is now bitwise on signed zeros -- camtoworld_graphics_to_vision_4x4's "
- "involution bullet says value-exact but not bitwise and needs re-deriving"
- )
- assert torch.signbit(once).sum().item() == 0, "a signed zero survived the first application"
- assert torch.signbit(twice).sum().item() == 0, "a signed zero reappeared after the second application"
+ converted = call(forward, pose)
+ for actual, expected in zip(call(backward, pose), converted):
+ self.assert_close(actual, expected, atol=0.0, rtol=0.0)
+ for round_trip in (call(forward, converted), call(backward, converted)):
+ for actual, expected in zip(round_trip, pose):
+ self.assert_close(actual, expected, atol=0.0, rtol=0.0)
class TestCamtoworldRtToPoseRt(BaseTester):
@@ -5665,31 +4977,6 @@ class TestCamtoworldRtToPoseRt(BaseTester):
inverted_t, torch.tensor([[[-2.0], [-3.0], [-1.0]]], device=device, dtype=dtype), atol=0.0, rtol=0.0
)
- def test_convention_both_directions_are_the_same_function(self, device, dtype):
- # Convention pin: camtoworld_to_worldtocam_Rt and worldtocam_to_camtoworld_Rt are the same
- # formula under two names -- bitwise identical outputs on the same input -- so the direction
- # lives in the caller's head, not in the call. Consequences pinned here: applying either one
- # twice returns the input, and the two compose to the input in EITHER order. All three round
- # trips are executed separately rather than one being inferred from another.
- # This holds because R is a rotation; the same round trip fails for a non-orthogonal R,
- # which test_wart_non_orthogonal_rotation_is_transposed_not_inverted_3961 pins.
- _skip_if_dtype_unavailable(device, dtype)
- rotation, translation = _asymmetric_pose(device, dtype)
-
- forward_R, forward_t = camtoworld_to_worldtocam_Rt(rotation, translation)
- backward_R, backward_t = worldtocam_to_camtoworld_Rt(rotation, translation)
-
- self.assert_close(backward_R, forward_R, atol=0.0, rtol=0.0)
- self.assert_close(backward_t, forward_t, atol=0.0, rtol=0.0)
-
- twice_R, twice_t = camtoworld_to_worldtocam_Rt(forward_R, forward_t)
- round_R, round_t = worldtocam_to_camtoworld_Rt(forward_R, forward_t)
-
- self.assert_close(twice_R, rotation, atol=0.0, rtol=0.0)
- self.assert_close(twice_t, translation, atol=0.0, rtol=0.0)
- self.assert_close(round_R, rotation, atol=0.0, rtol=0.0)
- self.assert_close(round_t, translation, atol=0.0, rtol=0.0)
-
def test_convention_camtoworld_t_is_the_camera_centre(self, device, dtype):
# Convention pin: what t MEANS on each side, established by applying the packed 4x4 matrices
# to points. On the camtoworld side the camera origin maps to t, so t is the camera centre
@@ -5726,10 +5013,8 @@ class TestCamtoworldRtToPoseRt(BaseTester):
)
def test_convention_shapes_are_strictly_batched(self, op_name, shapes, device):
# Convention pin: both functions accept exactly (B, 3, 3) + (B, 3, 1) -- no unbatched form,
- # no (B, 3) translation, no extra leading batch dimensions. What they do NOT enforce is a
- # matching batch size: a (1, 3, 1) translation broadcasts across a (2, 3, 3) rotation here,
- # where Rt_to_matrix4x4 raises (pinned in TestRt2Extrinsics). That asymmetry is recorded in
- # the Convention blocks and is deliberately not pinned as a contract.
+ # no (B, 3) translation, no extra leading batch dimensions. A mismatched batch size is not
+ # checked (kornia#4774, pinned in TestRt2Extrinsics).
# Assertion policy and the float32 hardcoding are documented once on the shared
# _assert_strictly_batched helper.
_assert_strictly_batched(op_name, shapes, device)
@@ -6086,10 +5371,6 @@ class TestEulerFromQuaternion(BaseTester):
for name, t in (("w", w), ("x", x), ("y", y), ("z", z)):
assert bool(torch.isfinite(t.grad)), f"pitch grad wrt {name} is not finite: {t.grad}"
- @pytest.mark.skipif(
- torch_version() in {"2.0.1", "2.1.2", "2.2.2", "2.3.1"} and sys.version_info.minor == 8,
- reason="Not working on 2.0",
- )
def test_dynamo(self, device, dtype, torch_optimizer):
q = Quaternion.random(batch_size=1)
q = q.to(device, dtype)
@@ -6620,41 +5901,16 @@ class TestAxisAngleToRotationMatrix:
assert R.shape == (3, 3, 3)
-# Module-level pins for kornia#3956: the four deprecated aliases of this module
-# (angle_axis_to_rotation_matrix, rotation_matrix_to_angle_axis, quaternion_to_angle_axis,
-# angle_axis_to_quaternion) were never the site of the defect -- the root cause was
-# _emit_deprecation_warning in kornia/core/_compat.py, which wrapped its warnings.warn call in
-# warnings.simplefilter("always", DeprecationWarning) / simplefilter("default", DeprecationWarning)
-# and so rewrote the PROCESS-GLOBAL filter list on every call. Every deprecated symbol in kornia
-# was therefore affected, which is why these live at module level rather than in one symbol's
-# class, following the module-level wart precedent above; the emitter itself is pinned in
-# tests/utils/test_deprecated.py, and these four cells are what keeps the convention attached to
-# the aliases rather than to one caller of the decorator. Both pins run inside
-# warnings.catch_warnings() so that a regression's filter mutation cannot leak into the rest of the
-# suite: that bug was contagious across tests, and an unisolated pin would silently disarm every
-# other test's warning discipline.
-# Both pins parametrize over _DEPRECATED_ALIAS_NAMES_AND_ARGS, the projection of the module-level
-# _DEPRECATED_ALIASES table down to the two columns they use -- neither is about what the alias
-# forwards TO, only about the warning it emits on the way -- so both the list of aliases and the
-# projection of it are maintained in exactly one place, and neither signature carries a parameter
-# it never reads.
+# Module-level regression pins for kornia#3956: a kornia DeprecationWarning obeys the caller's
+# warning filters and leaves them unchanged. The emitter itself is pinned in
+# tests/utils/test_deprecated.py; these cells keep the property attached to this module's aliases.
+# Both run inside warnings.catch_warnings() so a regression cannot leak filter state into the suite.
@pytest.mark.parametrize(("alias_name", "arg"), _DEPRECATED_ALIAS_NAMES_AND_ARGS, ids=_DEPRECATED_ALIAS_IDS)
def test_convention_deprecated_alias_warning_can_be_escalated_to_an_error_3956(alias_name, arg):
- # Convention: a DeprecationWarning emitted by kornia obeys the caller's warning filters, so a
- # project running under -W error::DeprecationWarning (or pytest's filterwarnings = error) sees
- # the call fail and can find its deprecated usages. Until kornia#3956 was fixed it did not:
- # _emit_deprecation_warning installed simplefilter("always", DeprecationWarning) immediately
- # before warnings.warn, which overrode the caller's "error" entry, so the warning was printed
- # and execution continued.
- # The escalated DeprecationWarning is caught by type rather than by treating any exception as
- # the awaited raise: an unrelated TypeError from the alias would otherwise set escalated=True
- # and pass the body under a name that reads as "escalation works". Catching DeprecationWarning
- # specifically lets any other exception propagate and be reported as an error instead.
- # Four cells, one per alias, because all four are separate @deprecated call sites: the fix is
- # in _emit_deprecation_warning, but a future decorator that emits its own warning would have to
- # honor this too.
+ # Under -W error::DeprecationWarning the alias call must raise. DeprecationWarning is caught
+ # by type so an unrelated exception is reported as an error, not as a successful escalation.
alias = getattr(kornia.geometry.conversions, alias_name)
tensor = torch.tensor(arg)
@@ -6672,15 +5928,8 @@ def test_convention_deprecated_alias_warning_can_be_escalated_to_an_error_3956(a
@pytest.mark.parametrize(("alias_name", "arg"), _DEPRECATED_ALIAS_NAMES_AND_ARGS, ids=_DEPRECATED_ALIAS_IDS)
def test_convention_deprecated_alias_leaves_the_global_warning_filters_alone_3956(alias_name, arg):
- # The other half of kornia#3956, and the half the escalation pin above cannot see: a call must
- # leave warnings.filters exactly as it found it. Before the fix a single alias call pushed two
- # entries of its own -- 'always' before the warn and 'default' from the finally clause -- so
- # even a caller that never escalated had its process-global warning config rewritten, and the
- # 'default' entry outlived the call. Pinned separately because a half fix that dropped only the
- # "always" would restore escalation while still clobbering the caller's filters.
- # Starts from an EMPTY filter list rather than the ambient one so the assertion is exact rather
- # than a length comparison, and runs inside warnings.catch_warnings() so neither the reset nor
- # any mutation a regression reintroduces can leak into the rest of the suite.
+ # A call leaves warnings.filters exactly as it found it; starting from an empty list makes the
+ # comparison exact.
alias = getattr(kornia.geometry.conversions, alias_name)
tensor = torch.tensor(arg)