Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

docs(geometry): per-op Convention blocks for conversions (batch 3c: homography normalization & camera frames) (#3984)

Dmytro Mishkind73bf9c0e503
diff --git a/docs/source/geometry.conversions.rst b/docs/source/geometry.conversions.rst
index 0f8f233c3..251f6cddc 100644
--- a/docs/source/geometry.conversions.rst
+++ b/docs/source/geometry.conversions.rst
@@ -37,6 +37,8 @@ Homography
.. autofunction:: normalize_homography
.. autofunction:: denormalize_homography
.. autofunction:: normalize_homography3d
+.. autofunction:: normal_transform_pixel
+.. autofunction:: normal_transform_pixel3d
Quaternion
----------
diff --git a/kornia/geometry/conversions.py b/kornia/geometry/conversions.py
index 087ba084f..e36ff1c9e 100644
--- a/kornia/geometry/conversions.py
+++ b/kornia/geometry/conversions.py
@@ -439,9 +439,10 @@ def axis_angle_to_rotation_matrix(axis_angle: torch.Tensor) -> torch.Tensor:
the angle when the axis is normalised, which shrinks the axis. In
``float64`` at ``theta = pi/2`` about ``+z``, ``det(R)`` is
``0.9999974535249636`` and ``max|R R^T - I|`` is
- ``2.5464750363912714e-06``; the determinant is axis-independent to the
- last digit or two, while the orthogonality residual is not (a generic
- axis gives
+ ``2.5464750363912714e-06`` (torch 2.9.1, cpu β€” the trailing digits are
+ backend-dependent; the magnitude is the point); the determinant is
+ axis-independent to the last digit or two, while the orthogonality
+ residual is not (a generic axis gives
``2.091747640764474e-06``). ``float32`` is no better
(``2.5033950805664062e-06`` on the same input), and
the second example below hides it β€” the printed ``1.0000e+00`` at
@@ -806,7 +807,9 @@ def quaternion_to_rotation_matrix(quaternion: torch.Tensor) -> torch.Tensor:
- the input is normalised internally:
``quaternion_to_rotation_matrix(2 * q)`` is bitwise
``quaternion_to_rotation_matrix(q)`` (400 000 random unit
- quaternions, at every dtype). Rescaling by random factors between
+ 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
@@ -829,10 +832,8 @@ def quaternion_to_rotation_matrix(quaternion: torch.Tensor) -> torch.Tensor:
warnings give the measured errors
- 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 but one: an
- **unbatched** ``float16`` or ``bfloat16`` quaternion of shape
- ``(4,)`` returns a ``float32`` matrix, so the same call on ``q`` and
- on ``q[None]`` returns two different dtypes β€” see the warning below.
+ - the output dtype follows the input at every shape but one β€” see the
+ dtype warning below.
: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
@@ -948,16 +949,18 @@ def quaternion_to_axis_angle(quaternion: torch.Tensor) -> torch.Tensor:
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: ``quaternion_to_axis_angle(2 * q)`` is
- bitwise ``quaternion_to_axis_angle(q)`` (400 000 random unit
- quaternions, at every dtype). Rescaling by random factors between
- ``1e-6`` and ``1e6`` moves the result only by the working dtype's
- rounding in ``float64`` and ``float32`` (by ``8.9e-16`` and
- ``4.8e-07`` over 2000 random unit quaternions), but the
- reduced-precision dtypes do **not** hold to that: ``bfloat16`` moves
- by ``3.1e-02`` and ``float16`` by over ``3`` radians, and the ``1e6``
- end is ``nan`` at ``float16`` because ``0.5 * 1e6`` overflows the
- dtype.
+ - 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
@@ -1076,8 +1079,10 @@ def quaternion_log_to_exp(quaternion: torch.Tensor, eps: float = 1.0e-8) -> torc
in wider precision, so its squares never overflow and it turns over
only once the true ``||v||`` exceeds what ``float16`` itself can hold,
near ``65520``. That still happens, but it takes **two or more**
- non-zero components, since a single one cannot exceed ``65504``:
- ``[37824., 37824., 37824.]`` is finite while
+ non-zero components, since a single one cannot exceed ``65504``. Where
+ exactly the turnover falls tracks ``torch.norm``'s accumulation
+ strategy, so treat it as a bound and not as a threshold: on this build
+ (torch 2.9.1, cpu) ``[37824., 37824., 37824.]`` is still finite while
``[37856., 37856., 37856.]`` is all ``nan``. Tracked in
`#3975 <https://github.com/kornia/kornia/issues/3975>`_.
@@ -1693,6 +1698,160 @@ def normalize_homography(
) -> torch.Tensor:
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
+ :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
+ **corner-aligned** ones, inherited unconditionally β€” see the
+ convention warning below
+
+ .. warning::
+ The documented :math:`(B, 3, 3)` is not what the guard enforces. An
+ unbatched ``(3, 3)`` is accepted and promoted to ``(1, 3, 3)``, and any
+ number of leading batch dimensions is accepted and preserved
+ (``(2, 4, 3, 3)`` returns ``(2, 4, 3, 3)``). Worse, a ``(B, 4, 4)``
+ input passes the guard entirely and fails later inside ``matmul`` with
+ a message naming neither the argument nor the expected shape. Which of
+ those ranks the contract will ratify is undecided. Tracked in
+ `#3960 <https://github.com/kornia/kornia/issues/3960>`_.
+
+ .. 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``.
+
+ .. warning::
+ The two normalization matrices are built without a ``dtype=``
+ pass-through and cast to the input afterwards, so their precision is
+ decided by the **ambient default dtype** and not by the argument's. At
+ the ``float32`` default β€” the usual case β€” a ``float64`` caller gets
+ ``float32``-rounded constants: ``normalize_homography`` of the
+ ``float64`` identity from ``(4, 4)`` to ``(6, 6)`` returns
+ ``0.5999999910593036`` where the ``float64``-native composition gives
+ ``0.6000000000000001`` β€” a deviation of ``8.94069651646845e-09``, about
+ eight significant digits instead of sixteen. Under
+ ``torch.set_default_dtype(torch.float64)`` that same ``float64`` call
+ returns the native ``0.6000000000000001`` instead, which is what
+ identifies the missing pass-through as the cause rather than an epsilon
+ or a rounding choice: it is
+ :func:`~kornia.geometry.conversions.normal_transform_pixel`'s
+ documented ``dtype=None`` behaviour reaching through, so setting the
+ ambient default is also the workaround. Same mechanism in
+ :func:`~kornia.geometry.conversions.denormalize_homography`
+ (``2.483526828633842e-08`` on the same input, at the ``float32``
+ default) and in
+ :func:`~kornia.geometry.conversions.normalize_homography3d`. These
+ deviations run through ``matmul`` and an inverse, so their trailing
+ digits are backend-dependent; the magnitude β€” half the mantissa gone β€”
+ is the point, not the digits. Tracked in
+ `#3958 <https://github.com/kornia/kornia/issues/3958>`_.
+
+ .. warning::
+ Scope: the degenerate-denominator branch only, as delimited in
+ :func:`~kornia.geometry.conversions.normal_transform_pixel`'s
+ degenerate-size warning. Neither ``dsize`` is validated, so
+ :func:`~kornia.geometry.conversions.normal_transform_pixel`'s
+ degenerate sizes propagate straight into the homography. On the
+ identity, holding the other size at ``(4, 5)``: a **source** ``dsize``
+ of ``(4, 1)`` collapses the ``x`` scale to ``2.500000167887412e-15``,
+ the same ``(4, 1)`` as the **destination** blows it up to the reciprocal
+ ``400000001507328.0``, and a size of ``0`` silently mirrors that axis
+ (source ``(4, 0)``, destination ``(4, 5)``, first row
+ ``[-0.25, 0.0, -1.25]``). Those three figures pass through ``matmul``
+ and an inverse, so their trailing digits are backend-dependent; the
+ orders of magnitude are the point. This is the
+ executed root of 1-pixel warp outputs coming back all-``nan`` on cpu
+ and mps β€” the devices executed; no CUDA behavior is claimed. Tracked
+ in
+ `#3957 <https://github.com/kornia/kornia/issues/3957>`_ and, for the
+ symptom, `#3929 <https://github.com/kornia/kornia/issues/3929>`_.
+
+ .. 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>`_.
+
+ .. warning::
+ The :math:`[-1, 1]` frames are corner-aligned
+ (``align_corners=True``) and there is no way to select the half-pixel
+ convention: :func:`~kornia.geometry.conversions.denormalize_homography`,
+ :func:`~kornia.geometry.conversions.normalize_homography3d` and
+ :func:`~kornia.geometry.transform.warp_perspective` all inherit it. That
+ is a separate fact from why an identity ``warp_perspective`` called with
+ ``align_corners=False`` does not reproduce its input β€” on a 4x4
+ ``arange`` image the maximum deviation is ``11.25``, against ``1.4e-05``
+ at ``align_corners=True``. This function is not that cause: for equal
+ source and destination sizes, an identity homography normalizes back to
+ the identity to within a single ``float32`` rounding step β€” the
+ deviation is exactly ``0`` at most equal sizes and ``5.96e-08`` at the
+ rest, with the ``4x4`` case above among the latter; which size lands
+ where is a property of the inverse-and-matmul chain and not a rule
+ about the scale, so read the size you care about rather than a pattern
+ off these β€” and ``warp_perspective``'s
+ ``11.25`` comes from its own ``create_meshgrid``-built, corner-aligned
+ grid being sampled by ``grid_sample`` under the ``align_corners=False``
+ half-pixel convention. Recorded in
+ `#3904 <https://github.com/kornia/kornia/issues/3904>`_.
+
Args:
dst_pix_trans_src_pix: homography/ies from source to destination to be
normalized. :math:`(B, 3, 3)`
@@ -1735,16 +1894,118 @@ def normal_transform_pixel(
) -> torch.Tensor:
r"""Compute the normalization matrix from image size in pixels to [-1, 1].
+ Convention:
+ - the result is a **single** matrix of shape :math:`(1, 3, 3)` β€” never
+ batched β€” acting on homogeneous ``(x, y, 1)`` column vectors, with
+ ``x`` indexing columns and scaled by ``width`` and ``y`` indexing rows
+ and scaled by ``height``. The positional argument order is the other
+ way round, ``(height, width)``
+ - the mapping is **corner-aligned**: scale ``2 / (size - 1)``, offset
+ ``-1``, so the pixel *centres* ``0`` and ``size - 1`` map to exactly
+ ``-1`` and ``+1``. ``normal_transform_pixel(4, 5)`` has rows
+ ``[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``. At the degenerate sizes the
+ two diverge outright β€” they clamp through different ``eps``
+ mechanisms, ``2e14``-scale here against ``2e8``-scale there at
+ ``size == 1``, and with opposite signs at ``size == 0`` (executed; see
+ the warning below)
+ - *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
+ - the convention is applied **unconditionally** β€” there is no
+ ``align_corners`` parameter β€” and
+ :func:`~kornia.geometry.conversions.normalize_homography` and its
+ siblings inherit it; see the convention warning there
+ - 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::
+ This paragraph is about the degenerate-denominator branch only, not
+ about the ``2 / (size - 1)`` scaling or the corner-aligned convention,
+ which are `#3904 <https://github.com/kornia/kornia/issues/3904>`_'s
+ territory. ``height`` and ``width`` are not validated. A size of ``1``
+ takes the ``eps`` branch,
+ so with the default ``eps = 1e-14`` the scale becomes ``2 / eps``:
+ ``normal_transform_pixel(4, 1)`` has ``sx = 200000000753664.0``, finite
+ and silent. A size of ``0`` divides by ``-1`` instead and gives
+ ``sx = -2.0``, a mirroring transform, and negative sizes are accepted
+ too (``width = -3`` gives ``-0.5``). ``eps`` is consulted **only** in
+ the ``size == 1`` branch, so it does not guard the ``size == 0`` case;
+ raising it to ``eps=1.0`` changes the ``size == 1`` scale to ``2.0`` and
+ leaves the ``size == 0`` scale at ``-2.0``. The blow-up reaches users:
+ an identity :func:`~kornia.geometry.transform.warp_perspective` onto a
+ 1-pixel-high output is all-``nan`` at ``align_corners=True``, where the
+ 2-pixel-high control is finite (executed on cpu and mps; no CUDA
+ behavior is claimed). Tracked in
+ `#3957 <https://github.com/kornia/kornia/issues/3957>`_ and, for the
+ symptom, `#3929 <https://github.com/kornia/kornia/issues/3929>`_.
+
+ .. warning::
+ An integer ``dtype`` truncates the scale instead of raising:
+ ``normal_transform_pixel(4, 5, dtype=torch.int64)`` returns
+ ``[[0, 0, -1], [0, 0, -1], [0, 0, 1]]``, which maps every pixel to the
+ constant ``(-1, -1)``. Tracked in
+ `#3959 <https://github.com/kornia/kornia/issues/3959>`_.
+
Args:
height: image height.
width: image width.
- eps: epsilon to prevent divide-by-zero errors
+ eps: denominator substituted for ``size - 1`` when a size equals ``1``;
+ it is not consulted on any other path.
device: device to place the result on.
- dtype: dtype of the result.
+ dtype: dtype of the result. ``None`` means ``torch.get_default_dtype()``.
Returns:
normalized transform with shape :math:`(1, 3, 3)`.
+ Example:
+ >>> normal_transform_pixel(4, 5)
+ tensor([[[ 0.5000, 0.0000, -1.0000],
+ [ 0.0000, 0.6667, -1.0000],
+ [ 0.0000, 0.0000, 1.0000]]])
+
"""
# prevent divide by zero bugs
width_denom: float = eps if width == 1 else width - 1.0
@@ -1773,17 +2034,60 @@ def normal_transform_pixel3d(
) -> torch.Tensor:
r"""Compute the normalization matrix from image size in pixels to [-1, 1].
+ Convention:
+ - the 3-D counterpart of
+ :func:`~kornia.geometry.conversions.normal_transform_pixel`: same
+ corner-aligned ``2 / (size - 1)`` scaling with offset ``-1``, same
+ unconditional application, same ``dtype=None`` /
+ ``torch.get_default_dtype()`` rule, and likewise **never batched**.
+ Only the lines below differ
+ - the result has shape :math:`(1, 4, 4)` and acts on homogeneous
+ ``(x, y, z, 1)`` column vectors with ``x`` scaled by ``width``, ``y``
+ by ``height`` and ``z`` by ``depth``, while the positional argument
+ order is ``(depth, height, width)``: ``normal_transform_pixel3d(9, 5, 3)``
+ has diagonal ``[1.0, 0.5, 0.25]`` and sends ``(0, 0, 0)`` to
+ ``(-1, -1, -1)`` and the far corner ``(2, 4, 8)`` to ``(1, 1, 1)``
+ - that ``(x, y, z)`` slot order is a **permutation** of
+ :func:`~kornia.geometry.conversions.normalize_pixel_coordinates3d`,
+ which reads its input as ``(d, x, y)``. The two produce the same three
+ numbers in different slots β€” with ``depth=9, height=5, width=3`` the
+ 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::
+ Scope: the degenerate-denominator branch only, as delimited in
+ :func:`~kornia.geometry.conversions.normal_transform_pixel`'s
+ degenerate-size warning. The degenerate-size
+ and integer-``dtype`` behaviours of
+ :func:`~kornia.geometry.conversions.normal_transform_pixel` apply here
+ per axis: ``depth=1`` gives a ``z``
+ scale of ``2e14`` under the default ``eps``, ``depth=0`` gives ``-2.0``,
+ negative sizes are accepted, and
+ ``normal_transform_pixel3d(2, 4, 5, dtype=torch.int64)`` returns a
+ matrix with diagonal ``[0, 0, 2]``. Tracked in
+ `#3957 <https://github.com/kornia/kornia/issues/3957>`_ and
+ `#3959 <https://github.com/kornia/kornia/issues/3959>`_.
+
Args:
depth: image depth.
height: image height.
width: image width.
- eps: epsilon to prevent divide-by-zero errors
+ eps: denominator substituted for ``size - 1`` when a size equals ``1``;
+ it is not consulted on any other path.
device: device to place the result on.
- dtype: dtype of the result.
+ dtype: dtype of the result. ``None`` means ``torch.get_default_dtype()``.
Returns:
normalized transform with shape :math:`(1, 4, 4)`.
+ Example:
+ >>> normal_transform_pixel3d(2, 4, 5)
+ tensor([[[ 0.5000, 0.0000, 0.0000, -1.0000],
+ [ 0.0000, 0.6667, 0.0000, -1.0000],
+ [ 0.0000, 0.0000, 2.0000, -1.0000],
+ [ 0.0000, 0.0000, 0.0000, 1.0000]]])
+
"""
tr_mat = torch.tensor(
[[1.0, 0.0, 0.0, -1.0], [0.0, 1.0, 0.0, -1.0], [0.0, 0.0, 1.0, -1.0], [0.0, 0.0, 0.0, 1.0]],
@@ -1808,6 +2112,59 @@ def denormalize_homography(
) -> torch.Tensor:
r"""De-normalize a given homography in pixels from [-1, 1] to actual height and width.
+ Convention:
+ - the mirror of
+ :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 corner-aligned frames β€” is as documented there, and so
+ are that function's shape-guard (`#3960
+ <https://github.com/kornia/kornia/issues/3960>`_), dtype-pass-through
+ (`#3958 <https://github.com/kornia/kornia/issues/3958>`_),
+ degenerate-size (`#3957
+ <https://github.com/kornia/kornia/issues/3957>`_), int64-handling
+ (`#3959 <https://github.com/kornia/kornia/issues/3959>`_ β€” this
+ function's own clause there) and corner-alignment (`#3904
+ <https://github.com/kornia/kornia/issues/3904>`_) warnings. 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
+
Args:
dst_pix_trans_src_pix: homography/ies from source to destination to be
denormalized. :math:`(B, 3, 3)`
@@ -1843,6 +2200,76 @@ def normalize_homography3d(
) -> torch.Tensor:
r"""Normalize a given homography in pixels to [-1, 1].
+ Convention:
+ - the 3-D counterpart of
+ :func:`~kornia.geometry.conversions.normalize_homography`: same
+ composition ``N_dst @ H @ inv(N_src)``, same source-to-destination
+ direction re-expressed in normalized frames, same ``dsize_src`` on the
+ right and ``dsize_dst`` on the left, and the same corner-aligned
+ frames β€” with
+ :func:`~kornia.geometry.conversions.normal_transform_pixel3d` in place
+ of the 2-D helper. It is **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
+ - 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`.
+ Tracked in `#3962 <https://github.com/kornia/kornia/issues/3962>`_
+
+ .. warning::
+ The shape guard has the 2-D function's ``or``-structure and the 2-D
+ function's message, with only the size adapted: it accepts an unbatched
+ ``(4, 4)`` (promoted to ``(1, 4, 4)``) and any number of leading batch
+ dimensions, it lets a ``(B, 3, 3)`` through to die inside ``matmul``,
+ and when it does fire its message names the wrong shape β€”
+ ``Input dst_pix_trans_src_pix must be a Bx3x3 tensor`` from a function
+ that takes 4x4 matrices. Tracked in
+ `#3960 <https://github.com/kornia/kornia/issues/3960>`_.
+
+ .. warning::
+ Scope: the degenerate-denominator branch only, as delimited in
+ :func:`~kornia.geometry.conversions.normal_transform_pixel`'s
+ degenerate-size warning. A source
+ ``depth`` of ``1`` collapses the ``z`` scale through
+ :func:`~kornia.geometry.conversions.normal_transform_pixel3d`'s ``2e14``
+ blow-up, leaving a value that is **not** an exact zero and merely prints
+ as ``0.`` at the default precision. Both it and the determinant scale
+ with the destination depth, so neither means anything without both
+ sizes: from ``dsize_src = (1, 4, 5)`` to ``dsize_dst = (3, 8, 9)`` the
+ ``z`` scale is ``4.99999991225835e-15`` and ``det`` is
+ ``1.0714285980035544e-15``, while the same source against
+ ``(2, 8, 9)`` gives ``9.9999998245167e-15`` and
+ ``2.1428571960071087e-15`` (torch 2.9.1, cpu β€” these run through an
+ inverse, a ``matmul`` and ``linalg.det``, so read the exponents, not
+ the trailing digits). ``torch.linalg.inv`` still succeeds on such
+ a matrix, so it is unusable in practice rather than formally singular,
+ and it annihilates every ``z`` coordinate. Returned without any
+ warning. The ``float32`` constants of
+ `#3958 <https://github.com/kornia/kornia/issues/3958>`_ apply here too.
+ Tracked in `#3957 <https://github.com/kornia/kornia/issues/3957>`_.
+
Args:
dst_pix_trans_src_pix: homography/ies from source to destination to be
normalized. :math:`(B, 4, 4)`
@@ -1960,7 +2387,59 @@ def denormalize_points_with_intrinsics(point_2d_norm: torch.Tensor, camera_matri
def Rt_to_matrix4x4(R: torch.Tensor, t: torch.Tensor) -> torch.Tensor:
- r"""Combine 3x3 rotation matrix R and 1x3 translation vector t into 4x4 extrinsics.
+ r"""Combine 3x3 rotation matrix R and 3x1 translation vector t into 4x4 extrinsics.
+
+ Convention:
+ - ``t`` goes in the **last column** and the appended bottom row is
+ ``[0, 0, 0, 1]``, so the result acts on homogeneous column vectors as
+ ``x_out = R @ x_in + t``: with ``t = (1, 2, 3)``,
+ ``M @ (0, 0, 0, 1)`` returns ``t`` itself and ``M @ (1, 0, 0, 1)``
+ returns ``R[:, 0] + t``
+ - the function is **frame-agnostic** β€” it packs whatever ``(R, t)`` it
+ is handed and does not check that ``R`` is a rotation. Under the
+ camera-to-world reading the rest of this family uses (see
+ :func:`~kornia.geometry.conversions.camtoworld_to_worldtocam_Rt`),
+ ``t`` is the **camera centre in world coordinates**, whereas the
+ world-to-camera form's ``-R^T t`` is a translation and not a centre.
+ Which of the two you are packing is your bookkeeping, not this
+ 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
+
+ .. 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>`_.
Args:
R: Rotation matrix, :math:`(B, 3, 3).`
@@ -1985,7 +2464,24 @@ def Rt_to_matrix4x4(R: torch.Tensor, t: torch.Tensor) -> torch.Tensor:
def matrix4x4_to_Rt(extrinsics: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
- r"""Convert 4x4 extrinsics into 3x3 rotation matrix R and 1x3 translation vector ts.
+ r"""Convert 4x4 extrinsics into 3x3 rotation matrix R and 3x1 translation vector t.
+
+ Convention:
+ - the inverse of
+ :func:`~kornia.geometry.conversions.Rt_to_matrix4x4`, with the same
+ layout β€” ``R`` is the top-left 3x3 block and ``t`` the first three
+ rows of the last column β€” and the same frame-agnosticism. Only the
+ lines below differ
+ - the input shape is strictly :math:`(B, 4, 4)`; an unbatched ``(4, 4)``,
+ a ``(B, 3, 3)`` and extra leading dimensions each raise ``ShapeError``
+ - the **bottom row is ignored**: a projective 4x4 is silently truncated
+ to its rigid part, so replacing the bottom row with ``[9, 9, 9, 9]``
+ leaves ``R`` and ``t`` bit-identical, and re-packing through
+ :func:`~kornia.geometry.conversions.Rt_to_matrix4x4` restores the
+ canonical ``[0, 0, 0, 1]`` rather than what was passed in
+ - the returned ``R`` and ``t`` are **views** of ``extrinsics``, not
+ copies: ``R.mul_(0.)`` zeroes the caller's rotation block in place.
+ Clone before mutating either output
Args:
extrinsics: pose matrix :math:`(B, 4, 4)`.
@@ -2010,11 +2506,64 @@ def matrix4x4_to_Rt(extrinsics: torch.Tensor) -> tuple[torch.Tensor, torch.Tenso
def camtoworld_graphics_to_vision_4x4(extrinsics_graphics: torch.Tensor) -> torch.Tensor:
- r"""Convert graphics coordinate frame (e.g. OpenGL) to vision coordinate frame (e.g. OpenCV.).
+ r"""Convert a camera-to-world pose from the graphics frame (e.g. OpenGL) to the vision frame (e.g. OpenCV).
I.e. flips y and z axis. Graphics convention: [+x, +y, +z] == [right, up, backwards].
Vision convention: [+x, +y, +z] == [right, down, forwards].
+ Convention:
+ - the input is a **camera-to-world** pose :math:`(B, 4, 4)`: its 3x3
+ block maps camera axes into the world and its last column is the
+ camera centre in world coordinates
+ - the operation is exactly ``extrinsics @ diag(1, -1, -1, 1)`` β€” a
+ **right** multiplication, i.e. a change of the **camera-side** basis.
+ The translation column is untouched. Left-multiplying by the same
+ matrix would negate two of its components instead, and feeding a
+ *world-to-camera* matrix in flips the wrong side and leaves the
+ translation in the old frame: a silent error, not an exception
+ - graphics (OpenGL) camera frame: ``+x`` right, ``+y`` up, ``+z``
+ backwards β€” the camera looks down ``-z``. Vision (OpenCV) camera
+ frame: ``+x`` right, ``+y`` down, ``+z`` forwards β€” the camera looks
+ down ``+z``. On the identity camera-to-world pose, camera ``+y``
+ 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
+ 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
+ - 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
+ :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>`_.
+
Args:
extrinsics_graphics: pose matrix :math:`(B, 4, 4)`.
@@ -2040,11 +2589,27 @@ def camtoworld_graphics_to_vision_4x4(extrinsics_graphics: torch.Tensor) -> torc
def camtoworld_graphics_to_vision_Rt(R: torch.Tensor, t: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
- r"""Convert graphics coordinate frame (e.g. OpenGL) to vision coordinate frame (e.g. OpenCV.).
+ r"""Convert a camera-to-world pose from the graphics frame (e.g. OpenGL) to the vision frame (e.g. OpenCV).
I.e. flips y and z axis. Graphics convention: [+x, +y, +z] == [right, up, backwards].
Vision convention: [+x, +y, +z] == [right, down, forwards].
+ Convention:
+ - the split-argument form of
+ :func:`~kornia.geometry.conversions.camtoworld_graphics_to_vision_4x4`,
+ which documents the flip, the two camera frames, the involution and
+ the preserved handedness. It packs ``(R, t)`` with
+ :func:`~kornia.geometry.conversions.Rt_to_matrix4x4`, applies that
+ 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
+ - ``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).`
t: Translation matrix :math:`(B, 3, 1)`.
@@ -2070,11 +2635,23 @@ def camtoworld_graphics_to_vision_Rt(R: torch.Tensor, t: torch.Tensor) -> tuple[
def camtoworld_vision_to_graphics_4x4(extrinsics_vision: torch.Tensor) -> torch.Tensor:
- r"""Convert vision coordinate frame (e.g. OpenCV) to graphics coordinate frame (e.g. OpenGK.).
+ r"""Convert a camera-to-world pose from the vision frame (e.g. OpenCV) to the graphics frame (e.g. OpenGL).
- I.e. flips y and z axis Graphics convention: [+x, +y, +z] == [right, up, backwards].
+ I.e. flips y and z axis. Graphics convention: [+x, +y, +z] == [right, up, backwards].
Vision convention: [+x, +y, +z] == [right, down, forwards].
+ Convention:
+ - the same map as
+ :func:`~kornia.geometry.conversions.camtoworld_graphics_to_vision_4x4`,
+ which carries the canonical block: ``diag(1, -1, -1, 1)`` is its own
+ inverse, so vision-to-graphics and graphics-to-vision are the identical
+ function and return bitwise equal matrices on the same input. The name
+ records which direction the caller means
+ - everything else β€” the right multiplication, the untouched translation
+ column, the two frame definitions, the preserved determinant, the
+ strict :math:`(B, 4, 4)` shape and the integer-dtype warning β€” is as
+ documented there
+
Args:
extrinsics_vision: pose matrix :math:`(B, 4, 4)`.
@@ -2100,10 +2677,22 @@ def camtoworld_vision_to_graphics_4x4(extrinsics_vision: torch.Tensor) -> torch.
def camtoworld_vision_to_graphics_Rt(R: torch.Tensor, t: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
- r"""Convert graphics coordinate frame (e.g. OpenGL) to vision coordinate frame (e.g. OpenCV.).
+ r"""Convert a camera-to-world pose from the vision frame (e.g. OpenCV) to the graphics frame (e.g. OpenGL).
I.e. flips y and z axis. Graphics convention: [+x, +y, +z] == [right, up, backwards].
- Vision convention: [+x, +y, +z] == [right, down, forwards]
+ Vision convention: [+x, +y, +z] == [right, down, forwards].
+
+ Convention:
+ - the split-argument form of
+ :func:`~kornia.geometry.conversions.camtoworld_vision_to_graphics_4x4`
+ and, because ``diag(1, -1, -1, 1)`` is its own inverse, bitwise the
+ same function as
+ :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
+ graphics-to-vision ``_Rt`` form
Args:
R: Rotation matrix, :math:`(B, 3, 3).`
@@ -2135,6 +2724,61 @@ def camtoworld_to_worldtocam_Rt(R: torch.Tensor, t: torch.Tensor) -> tuple[torch
See
long-url: https://colmap.github.io/format.html#output-format
+ Convention:
+ - 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; contrast
+ :func:`~kornia.geometry.conversions.axis_angle_to_rotation_matrix`,
+ whose own non-orthogonality (`#3947
+ <https://github.com/kornia/kornia/issues/3947>`_) inflates this
+ figure to ``3.16e-06`` β€” 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``
+ - 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
+
+ .. 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
+ `#3961 <https://github.com/kornia/kornia/issues/3961>`_.
+
Args:
R: Rotation matrix, :math:`(B, 3, 3).`
t: Translation matrix :math:`(B, 3, 1)`.
@@ -2165,6 +2809,20 @@ def camtoworld_to_worldtocam_Rt(R: torch.Tensor, t: torch.Tensor) -> tuple[torch
def worldtocam_to_camtoworld_Rt(R: torch.Tensor, t: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
r"""Convert worldtocam frame used in Colmap to camtoworld.
+ Convention:
+ - bitwise 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
+ - 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
+
Args:
R: Rotation matrix, :math:`(B, 3, 3).`
t: Translation matrix :math:`(B, 3, 1)`.
@@ -2193,10 +2851,141 @@ def worldtocam_to_camtoworld_Rt(R: torch.Tensor, t: torch.Tensor) -> tuple[torch
def ARKitQTVecs_to_ColmapQTVecs(qvec: torch.Tensor, tvec: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
- r"""Convert output of Apple ARKit screen pose to the camera-to-world transformation, expected by Colmap.
+ r"""Convert an Apple ARKit camera-to-world screen pose to the world-to-camera pose expected by Colmap.
Both poses in quaternion representation.
+ Convention:
+ (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
+ :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
+ ``eps = 1e-12`` 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
+ 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`.
+ Tracked in `#3962 <https://github.com/kornia/kornia/issues/3962>`_
+
+ .. warning::
+ The output quaternion is not exactly unit in ``float64``: the identity
+ input ``[1., 0., 0., 0.]`` with ``t = (1, 1, 1)`` returns
+ ``[0., 1.0000000012499999, 0., 0.]``, so ``|q| - 1`` is
+ ``1.2499998813808588e-09`` (torch 2.9.1, cpu), where ``float32`` returns
+ an exactly unit ``[0., 1., 0., 0.]``. The ``[0, 1, 0, 0]`` shape is
+ correct and not a component shift β€” for an identity input the composed
+ rotation is ``diag(1, -1, -1)``, a half turn about ``x``. Only the
+ magnitude is wrong; it is inherited from
+ :func:`~kornia.geometry.conversions.rotation_matrix_to_quaternion`.
+ Colmap consumers that validate ``QW QX QY QZ`` as a unit quaternion will
+ see it. Tracked in
+ `#3951 <https://github.com/kornia/kornia/issues/3951>`_.
+
+ .. warning::
+ The all-zero quaternion is never rejected, and what it gives back
+ instead **splits by dtype**. In ``float64``, ``float32`` and
+ ``bfloat16`` 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, at every one of
+ those three dtypes β€” rather than raising. In ``float16`` the default
+ ``eps = 1e-12`` underflows to ``0`` (``bfloat16``'s wider exponent
+ keeps it), so the clamp is a no-op, the normalisation divides ``0`` by
+ ``0``, and **both returned tensors are entirely** ``nan``. Neither
+ branch is an error: 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`,
+ whose own warning carries the same ``float16`` underflow. Tracked in
+ `#3952 <https://github.com/kornia/kornia/issues/3952>`_.
+
Args:
qvec: ARKit rotation quaternion :math:`(B, 4)`, [w, x, y, z] format.
tvec: translation vector :math:`(B, 3, 1)`, [x, y, z]
diff --git a/tests/geometry/test_conversions.py b/tests/geometry/test_conversions.py
index bf113e158..37162f96c 100644
--- a/tests/geometry/test_conversions.py
+++ b/tests/geometry/test_conversions.py
@@ -15,10 +15,15 @@
# limitations under the License.
#
+import dis
import inspect
+import platform
import sys
import warnings
-from functools import partial
+from collections.abc import Iterator
+from contextlib import contextmanager
+from functools import cache, partial
+from types import TracebackType
import numpy as np
import pytest
@@ -26,6 +31,8 @@ import torch
import kornia
from kornia.core._compat import torch_version
+from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SHAPE
+from kornia.core.exceptions import BaseError, ShapeError
from kornia.core.ops import eye_like
from kornia.geometry.conversions import (
ARKitQTVecs_to_ColmapQTVecs,
@@ -86,17 +93,239 @@ def _issue_msg(text: str):
return lambda default_message: f"{text}\n{default_message}"
-def _skip_if_dtype_unavailable(device, dtype) -> None:
- # Visible skip (never a silent guard) for the dtype-hardcoded pins below. Those pins drop the
- # dtype fixture on purpose so they run in every test configuration, which means they would
- # otherwise also run on a device that cannot represent the dtype at all -- MPS has no float64
- # -- and the resulting TypeError would satisfy a raises=AssertionError xfail mark instead of
- # the assertion the pin documents. Probed at runtime rather than hardcoded per backend so the
- # skip retires itself once a backend gains the dtype.
+def _innermost_frame(err: BaseException) -> TracebackType | None:
+ # The frame an exception actually died in: the last link of its traceback chain. Two helpers
+ # below read that frame for different questions -- which routine failed, and which bytecode
+ # instruction raised -- so the walk itself is written once and cannot drift between them.
+ frame = err.__traceback__
+ while frame is not None and frame.tb_next is not None:
+ frame = frame.tb_next
+ return frame
+
+
+@cache
+def _dtype_allocation_error(device: torch.device, dtype: torch.dtype) -> str | None:
+ # "Can this backend hold this dtype at all?", as ONE probe with ONE exception set, shared by
+ # _skip_if_dtype_unavailable and _cross_is_unavailable below. Two copies of it with different
+ # exception tuples would mean a backend that starts rejecting an allocation with a new
+ # exception type makes one of them skip while the other errors, for the same fact. Cached
+ # because the answer is a property of the build, not of the caller, and the pins below ask it
+ # once per test; the message is returned rather than the exception so no traceback is kept
+ # alive between tests.
try:
torch.zeros(1, device=device, dtype=dtype)
- except (TypeError, RuntimeError) as err:
- pytest.skip(f"{dtype} is unavailable on device {device}: {err}")
+ except (TypeError, RuntimeError, NotImplementedError) as err:
+ return str(err)
+ return None
+
+
+def _skip_if_dtype_unavailable(device: torch.device, dtype: torch.dtype) -> None:
+ # Visible skip (never a silent guard) for the pins below, in both directions. The
+ # dtype-hardcoded pins drop the dtype fixture on purpose so they run in every test
+ # configuration, which means they would otherwise also run on a device that cannot represent
+ # the dtype at all -- MPS has no float64 -- and the resulting TypeError would satisfy a
+ # raises=AssertionError xfail mark instead of the assertion the pin documents. The
+ # fixture-parametrized pins call it for the same reason read the other way round: a
+ # --device=mps --dtype=all run would otherwise report them as failures indistinguishable from
+ # a real one, when the only fact being reported is that MPS has no float64. Probed at runtime
+ # rather than hardcoded per backend so the skip retires itself once a backend gains the
+ # dtype.
+ allocation_error = _dtype_allocation_error(device, dtype)
+ if allocation_error is not 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.
+ if device.type == "cuda" and dtype == torch.float32 and torch.backends.cuda.matmul.allow_tf32:
+ return 2.0**-10
+ return torch.finfo(dtype).eps
+
+
+_healthy_closed_form_inverse_routes: set[tuple[torch.device, torch.dtype]] = set()
+
+
+def _skip_if_closed_form_inverse_unavailable(device: torch.device, dtype: torch.dtype) -> None:
+ # Visible skip for the pins that route through normalize_homography, one layer deeper than
+ # _skip_if_dtype_unavailable: a backend can REPRESENT a dtype and still have no kernel for an
+ # operation the route needs. kornia's cusolver-free 3x3 inverse
+ # (_inverse_3x3_closed_form in kornia/core/utils.py) is three torch.linalg.cross calls, and
+ # MPS lacks a bfloat16 `cross` kernel in SOME builds -- executed: torch 2.5.1 raises
+ # `RuntimeError: Failed to create function state object for: cross_bfloat` there while torch
+ # 2.9.1 runs it, and torch.zeros in that dtype succeeds on both, so the allocation probe alone
+ # lets the pin fail with a message about torch's kernel coverage rather than about kornia's
+ # convention. Probed rather than version-gated: two builds are two data points, not a history.
+ # What is attempted is the PUBLIC operation, on a throwaway input, and a failure becomes a skip
+ # only when BOTH halves of the identification hold: the call died INSIDE the closed-form
+ # inverse (innermost frame, matched by code object rather than by name or message, so a rename
+ # is a re-raise and not a silent skip) AND the primitive that routine is built from raises on
+ # the same device and dtype. Every other failure is re-raised, so a kornia-side regression
+ # still fails the pin here rather than being skipped over. The frame half is what keeps an
+ # UNRELATED RuntimeError from riding the skip: on a backend that genuinely lacks the kernel the
+ # primitive probe always fails, so on its own it would turn any new failure raised before the
+ # inverse -- in the guard, in normal_transform_pixel, in the chain matmul -- into a skip, and
+ # the regression would be invisible exactly where the skip is live. The primitive half is what
+ # keeps the skip from outliving the limitation: the day kornia's inverse stops needing `cross`,
+ # these pins must run again on backends that lack it instead of skipping forever.
+ # Residual, stated rather than hidden: this identifies the failing ROUTINE, not the individual
+ # `cross` line inside it. _inverse_3x3_closed_form is three `cross` calls, a multiply-sum and a
+ # divide, so a failure at one of the latter two on a backend whose `cross` is also missing
+ # would still skip. Narrowing further would mean pinning line numbers in another module.
+ # Only the HEALTHY verdict is memoized, keyed by (device, dtype): a route that works is a
+ # property of the build, and four pins ask this question in every test configuration, each
+ # paying a matmul and a 3x3 inverse for the answer. A failing route is deliberately never
+ # memoized -- it has to be re-raised with its own traceback every time, and it is the branch
+ # this helper exists for.
+ # Imported here rather than at module scope on purpose: this is a PRIVATE kornia helper, and a
+ # module-level import of it would make the WHOLE file uncollectable if it is ever renamed --
+ # every test in it erroring over a rename that concerns the four pins routed through here.
+ # Inside the probe, the same rename is an ImportError on those four and nothing else.
+ from kornia.core.utils import _inverse_3x3_closed_form
+
+ route = (device, dtype)
+ if route in _healthy_closed_form_inverse_routes:
+ return
+ try:
+ kornia.geometry.conversions.normalize_homography(torch.eye(3, device=device, dtype=dtype)[None], (2, 2), (2, 2))
+ except (RuntimeError, NotImplementedError) as err:
+ innermost = _innermost_frame(err)
+ died_in_the_closed_form_inverse = (
+ innermost is not None and innermost.tb_frame.f_code is _inverse_3x3_closed_form.__code__
+ )
+ if died_in_the_closed_form_inverse and _cross_is_unavailable(device, dtype):
+ pytest.skip(f"torch.linalg.cross has no {dtype} kernel on device {device}: {err}")
+ raise
+ _healthy_closed_form_inverse_routes.add(route)
+
+
+@cache
+def _cross_is_unavailable(device: torch.device, dtype: torch.dtype) -> bool:
+ # "Can this build run torch.linalg.cross here?", for the helper above and the pin below.
+ # A dtype the backend cannot even allocate (mps rejects float8 outright) counts as unavailable
+ # rather than propagating as an error, and that half of the question is answered by the shared
+ # probe rather than by a second copy of it, so both helpers classify such a backend the same
+ # way. Cached for the same reason the probe is: it is a property of the build.
+ if _dtype_allocation_error(device, dtype) is not None:
+ return True
+ try:
+ probe = torch.ones(1, 3, device=device, dtype=dtype)
+ torch.linalg.cross(probe, probe, dim=-1)
+ except (RuntimeError, NotImplementedError, TypeError):
+ return True
+ return False
+
+
+def test_skip_probe_re_raises_everything_it_cannot_identify(monkeypatch):
+ # Direct pin for _skip_if_closed_form_inverse_unavailable above, for the same reason
+ # test_guard_classifier_reads_the_raising_instruction pins the guard classifier: four pins
+ # route their "does normalize_homography work here at all" question through that helper, and if
+ # it starts skipping too readily they go quiet instead of failing, which is the mode a skip
+ # helper fails in. Nothing else in this file would notice.
+ # Case B needs a REAL kernel gap rather than a patched `cross`: patching it with a Python
+ # function puts that function in the innermost frame, which is precisely what the helper reads,
+ # so a patch cannot reproduce the branch it is meant to exercise. torch has no `cross` kernel
+ # for bool or float8 on cpu (executed, torch 2.9.1: NotImplementedError, and the route dies
+ # inside _inverse_3x3_closed_form), which is the same shape as the mps bfloat16 gap on torch
+ # 2.5.1 that the helper exists for, reachable on the default device without that build. The
+ # candidate list is searched rather than asserted: mps DOES have a bool `cross`, so a build
+ # that grows the missing kernels must make this case skip visibly, not fail.
+ # Cases C and D patch normal_transform_pixel, which normalize_homography calls BEFORE the
+ # inverse, so the route dies without ever reaching `cross` and the patch stays out of the
+ # frame the helper reads. D is the one that matters: it is exactly C on a backend that also
+ # lacks the kernel, which a probe of the primitive alone cannot tell apart from a real gap --
+ # it would skip there, and a kornia-side regression would be invisible on exactly the backends
+ # where the skip is live.
+ # The helper's memo and the two cached probes are cleared first: they are performance
+ # shortcuts, and a pin whose whole subject is which branch the helper takes has to run the
+ # branches rather than a remembered verdict from an earlier test.
+ # The two globals that cases C and D patch go through monkeypatch rather than by hand: this is
+ # the one pin in the file that writes to torch and to the kornia module itself, and a leak from
+ # here would follow every later test in the process, so restoration belongs to pytest rather
+ # than to a nest of try/finally blocks that has to be read to be trusted.
+ cpu = torch.device("cpu")
+ conversions = kornia.geometry.conversions
+ _healthy_closed_form_inverse_routes.clear()
+ _cross_is_unavailable.cache_clear()
+ _dtype_allocation_error.cache_clear()
+
+ _skip_if_closed_form_inverse_unavailable(cpu, torch.float32) # A: healthy route, must not skip
+
+ # torch.float8_e4m3fn was added in torch 2.1; kornia declares torch>=2.0.0, so it is probed
+ # through getattr rather than referenced unconditionally.
+ candidate_dtypes = (torch.bool, getattr(torch, "float8_e4m3fn", None))
+ unsupported = next(
+ (dtype for dtype in candidate_dtypes if dtype is not None and _cross_is_unavailable(cpu, dtype)),
+ None,
+ )
+ if unsupported is None:
+ pytest.skip("no dtype without a torch.linalg.cross cpu kernel on this build")
+ with pytest.raises(pytest.skip.Exception): # B: the gap the helper exists for
+ _skip_if_closed_form_inverse_unavailable(cpu, unsupported)
+
+ def regression(*args, **kwargs):
+ raise RuntimeError("kornia-side regression")
+
+ def assert_the_injected_failure_propagates(case: str) -> None:
+ # NOT pytest.raises: a skip is a BaseException that pytest.raises(RuntimeError) lets
+ # through, so the regression this pin exists to catch would turn the pin itself yellow
+ # instead of red -- the same going-quiet the helper's own over-eager skip causes, one level
+ # up.
+ try:
+ _skip_if_closed_form_inverse_unavailable(cpu, torch.float32)
+ except pytest.skip.Exception as skipped:
+ raise AssertionError(f"{case}: an unrelated failure was skipped over: {skipped}") from skipped
+ except RuntimeError as err:
+ assert "kornia-side regression" in str(err), f"{case}: wrong error re-raised: {err}"
+ else:
+ raise AssertionError(f"{case}: the injected failure did not propagate at all")
+
+ # Cleared again: case A memoized (cpu, float32) as healthy, and C/D have to reach the body.
+ _healthy_closed_form_inverse_routes.clear()
+ monkeypatch.setattr(conversions, "normal_transform_pixel", regression)
+ assert_the_injected_failure_propagates("C, cross available")
+
+ monkeypatch.setattr(torch.linalg, "cross", regression)
+ assert_the_injected_failure_propagates("D, cross unavailable too")
def _undo_3954_upcast(matrix: torch.Tensor, dtype: torch.dtype) -> torch.Tensor:
@@ -108,6 +337,270 @@ def _undo_3954_upcast(matrix: torch.Tensor, dtype: torch.dtype) -> torch.Tensor:
return matrix.to(dtype)
+# 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.
+_DEPRECATED_ALIASES = [
+ ("angle_axis_to_rotation_matrix", "axis_angle_to_rotation_matrix", [[0.1, 0.2, 0.3]]),
+ (
+ "rotation_matrix_to_angle_axis",
+ "rotation_matrix_to_axis_angle",
+ [
+ [0.5357142857142858, -0.6229365034008422, 0.5700529070291328],
+ [0.765793646257985, 0.6428571428571429, -0.01716931065742361],
+ [-0.3557671927434186, 0.4457407392288521, 0.8214285714285714],
+ ],
+ ),
+ ("quaternion_to_angle_axis", "quaternion_to_axis_angle", [1.0, 2.0, 3.0, 4.0]),
+ ("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]
+
+
+# Exception types that mean "kornia's OWN guard rejected the input", for the kornia#3959 and
+# kornia#3960 pins below: kornia's guards raise BaseError subclasses (KORNIA_CHECK_SHAPE's ShapeError, plain
+# KORNIA_CHECK's bare BaseError, TypeCheckError -- BaseError is not a ValueError subclass, so both
+# entries are needed) or the hand-rolled ValueError the three homography functions raise today,
+# while every torch shape failure in these call chains (matmul, linalg.inv) raises RuntimeError.
+# Deliberately type-only -- no message text, which may be reworded on either side. This tuple is
+# one input to _raised_by_a_kornia_guard below, which every #3959/#3960 pin classifies through, so
+# the strict xfail and its companion warts cannot drift apart.
+_KORNIA_GUARD_EXCEPTIONS = (BaseError, ValueError)
+
+
+def _raised_by_a_kornia_guard(err: BaseException) -> bool:
+ # "Did kornia reject this input itself, or did it reach downstream arithmetic and die there?"
+ # -- the question every wart pin below has to answer, and the reason a type test alone is not
+ # enough: a guard written as a literal `raise RuntimeError(...)` is indistinguishable BY TYPE
+ # from the torch matmul/linalg failures these warts pin, so such a fix would land with the
+ # strict xfail still XFAIL and the companion warts still green.
+ # The discriminator is the BYTECODE INSTRUCTION the innermost traceback frame died on, read
+ # through tb_lasti. A Python `raise` statement compiles to RAISE_VARARGS (RERAISE when an
+ # exception is re-raised) whatever its source formatting -- `raise X`, `raise(X)`, a raise
+ # split across lines, or a KORNIA_CHECK* helper raising inside kornia/core/check.py -- while
+ # an exception surfacing out of a C call lands on the call site itself: BINARY_OP for
+ # `... @ ...` and `H[..., -1, -1] += 1.0`, CALL for `torch.linalg.inv(...)`. Matching the
+ # source line for "raise " instead of the bytecode would be formatting-sensitive rather than
+ # semantic -- it would miss `raise(RuntimeError(...))`, whose missing space before the
+ # parenthesis is not a semantic difference.
+ # Both directions are exercised: test_guard_classifier_reads_the_raising_instruction below
+ # covers the classifier itself, the #3960 strict xfail asserts this is True (XPASSing the day
+ # a guard lands, in any style), and the four warts assert it is False.
+ # The instruction DECIDES; the type tuple is only the fallback for a frame whose instruction
+ # cannot be read. ORing the two instead of falling back would make the instruction check
+ # unreachable for exactly the types kornia's guards raise, so it would score any downstream
+ # ValueError as a guard -- `normalize_homography(eye(3)[None], (4, 5, 6), (8, 9))` dies at the
+ # UNPACK_SEQUENCE of `src_h, src_w = dsize_src` with `too many values to unpack`, which is
+ # torch-free but is not a guard either. ANDing them instead would be worse, not better: it
+ # would reject the literal `raise RuntimeError(...)` guard that is the whole reason this
+ # function exists (executed -- three of the six positives below are RuntimeError raised
+ # through `raise`).
+ innermost = _innermost_frame(err)
+ if innermost is None:
+ return isinstance(err, _KORNIA_GUARD_EXCEPTIONS)
+ raising_opname = next(
+ (
+ instruction.opname
+ for instruction in dis.get_instructions(innermost.tb_frame.f_code)
+ if instruction.offset == innermost.tb_lasti
+ ),
+ None,
+ )
+ if raising_opname is None:
+ return isinstance(err, _KORNIA_GUARD_EXCEPTIONS)
+ return raising_opname in ("RAISE_VARARGS", "RERAISE")
+
+
+def test_guard_classifier_reads_the_raising_instruction():
+ # Direct pin for _raised_by_a_kornia_guard above. Every #3959/#3960 pin's "a guard fix cannot
+ # land unnoticed" guarantee rests on that one function, and nothing else in this file would
+ # notice it regressing -- the pins would simply go quiet, which is the failure mode the
+ # guarantee exists to prevent. `raise (X)` is in the positive set because it is semantically
+ # identical to `raise X` -- only the formatting differs, and a classifier keyed on source text
+ # rather than bytecode would not see that.
+ # The negative set is the two shapes of downstream failure the warts actually pin, a mixed
+ # matmul and a singular inverse, plus a ValueError raised at a non-`raise` instruction: those
+ # two are RuntimeError and so can never reach the type tuple, which would leave the ONE
+ # combination that breaks -- a guard TYPE at a downstream instruction -- uncovered. It is not
+ # hypothetical for these functions: normalize_homography opens with `src_h, src_w = dsize_src`,
+ # so a 3-tuple dsize raises ValueError from UNPACK_SEQUENCE inside kornia and must still
+ # classify as NOT a guard. Device-independent by construction: default-device tensors, no
+ # fixture, and only the raising instruction is read.
+ def spaced_raise():
+ raise RuntimeError("guard")
+
+ def parenthesised_raise():
+ raise (RuntimeError("guard"))
+
+ def raise_a_bound_name():
+ error = RuntimeError("guard")
+ raise error
+
+ def kornia_shape_check():
+ KORNIA_CHECK_SHAPE(torch.eye(4)[None], ["B", "3", "3"])
+
+ def kornia_value_check():
+ KORNIA_CHECK(False, "guard")
+
+ def hand_rolled_value_error():
+ raise ValueError("Input dst_pix_trans_src_pix must be a Bx3x3 tensor")
+
+ def mixed_matmul_failure():
+ return torch.eye(3, dtype=torch.int64)[None] @ torch.eye(3, dtype=torch.float32)[None]
+
+ def singular_inverse_failure():
+ return torch.linalg.inv(torch.zeros(1, 3, 3))
+
+ def downstream_value_error():
+ # ValueError, but raised by UNPACK_SEQUENCE rather than by a `raise`.
+ first, second, third = [1, 2] # noqa: F841
+
+ for guard in (
+ spaced_raise,
+ parenthesised_raise,
+ raise_a_bound_name,
+ kornia_shape_check,
+ kornia_value_check,
+ hand_rolled_value_error,
+ ):
+ with pytest.raises(Exception) as excinfo:
+ guard()
+ assert _raised_by_a_kornia_guard(excinfo.value), (
+ f"{guard.__name__} rejects the input on kornia's side and must classify as a guard"
+ )
+
+ for downstream in (mixed_matmul_failure, singular_inverse_failure, downstream_value_error):
+ with pytest.raises((RuntimeError, ValueError)) as excinfo:
+ downstream()
+ assert not _raised_by_a_kornia_guard(excinfo.value), (
+ f"{downstream.__name__} does not reject the input at a kornia guard and must not classify as one"
+ )
+
+
+# The wrong-sized-matrix cells for the kornia#3960 pair: (op name, wrong square size). One table
+# feeds BOTH the strict xfail and its companion wart -- their comments say the cells must flip
+# together, and sharing the table is what enforces it rather than asking a future editor to
+# remember. A fourth op (a denormalize_homography3d per kornia#3962, say) becomes a one-line edit
+# that cannot land in one list and not the other. The sizes helper lives here for the same reason.
+# These are call INPUTS, not pinned expected values: each pin computes its own verdict from them.
+_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]
+
+
+def _homography_sizes(op_name: str) -> tuple[tuple[int, ...], tuple[int, ...]]:
+ # (dsize_src, dsize_dst) for the kornia#3960 cells: 3-D ops take (depth, height, width).
+ return ((2, 4, 5), (3, 8, 9)) if op_name.endswith("3d") else ((4, 5), (8, 9))
+
+
+# The asymmetric camera pose shared by the camera-frame pins: a proper rotation (det = +1) that is
+# the 120-degree turn about (1, 1, 1), so it is NOT equal to its own transpose and NOT symmetric --
+# an identity or symmetric pose is invariant under the very flips and transposes these pins exist to
+# catch. Every entry is 0 or 1 and the translation is small integers, so every product below is
+# exact at float16, bfloat16, float32 and float64 alike, which is what lets those pins compare at
+# atol=rtol=0 under the dtype fixture. Materialised per test through _asymmetric_pose below, which
+# builds FRESH tensors on every call so no tensor is shared between tests; the values are kept as
+# plain nested lists for the same reason. Used by TestRt2Extrinsics, TestCamtoworldGraphicsToVision
+# and TestCamtoworldRtToPoseRt -- one definition and one materialisation site instead of nine
+# copies that would have to be edited in lockstep, and it is what makes those classes'
+# "same asymmetric pose as TestRt2Extrinsics" cross-references true by construction.
+# The kornia#3961 wart deliberately uses a DIFFERENT, non-orthogonal rotation and stays out of this.
+_ASYMMETRIC_R = [[[0.0, 0.0, 1.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]]]
+_ASYMMETRIC_T = [[[1.0], [2.0], [3.0]]]
+
+
+def _asymmetric_pose(device: torch.device, dtype: torch.dtype) -> tuple[torch.Tensor, torch.Tensor]:
+ # (rotation, translation) of the asymmetric pose above, as fresh tensors on every call.
+ return (
+ torch.tensor(_ASYMMETRIC_R, device=device, dtype=dtype),
+ torch.tensor(_ASYMMETRIC_T, device=device, dtype=dtype),
+ )
+
+
+# Shared inputs for the same reason as _ASYMMETRIC_R above: pins cross-reference each other as
+# using "the same input", and a shared definition makes that true by construction instead of by
+# inspection of copied literals. Plain nested lists, materialised per test, no tensor shared.
+# _DIRECTION_H feeds TestNormalizeHomography's composition/direction/per-sample pins (affine, zero
+# projective row, asymmetric); _ROUND_TRIP_H feeds its round-trip and per-sample pins (projective,
+# chosen so that at dyadic sizes every intermediate of the round trip is exactly representable);
+# _ARKIT_WORKED_QVEC and _ARKIT_WORKED_TVEC are the ARKit worked-example (q, t) pair that three
+# TestCARKitToColmap pins anchor to one another -- both halves are shared so that a change to the
+# worked example cannot leave one pin silently testing a different pose.
+_DIRECTION_H = [[[2.0, 0.5, 2.0], [-0.25, 1.0, 1.0], [0.0, 0.0, 1.0]]]
+_ROUND_TRIP_H = [[[1.25, 0.25, 4.0], [-0.5, 0.75, 2.0], [0.0625, 0.125, 1.0]]]
+_ARKIT_WORKED_QVEC = [[0.0, 1.0, 0.0, 1.0]]
+_ARKIT_WORKED_TVEC = [[[1.0], [1.0], [1.0]]]
+
+
+@contextmanager
+def _ambient_default_dtype(dtype: torch.dtype) -> Iterator[None]:
+ # Swap the PROCESS-WIDE torch default dtype for the duration of a with-block, restoring it even
+ # if the body raises. The finally-restore is the safety-critical part -- a leaked float64
+ # default would silently change every later test's tolerances across the whole suite -- so it
+ # lives in one place instead of being hand-rolled at each ambient-default pin (the two #3958
+ # pins today; any future one should use this too).
+ previous = torch.get_default_dtype()
+ torch.set_default_dtype(dtype)
+ try:
+ yield
+ finally:
+ torch.set_default_dtype(previous)
+
+
+def _assert_proper_rotation(rotation: torch.Tensor) -> None:
+ # det(R) == +1 backs the handedness-is-preserved Convention bullets, so it is asserted even
+ # where an earlier bitwise pin on a 0/+-1 literal already implies it -- the det claim is
+ # documented on its own and deserves its own loud flip. Computed after upcasting to float32:
+ # torch.linalg.det is not implemented for float16/bfloat16 on all backends, and the upcast of
+ # an exactly-representable matrix is lossless. atol=1e-5 covers float32 det round-off on
+ # near-0/+-1 entries while a reflection (det = -1) misses by 2.
+ assert_close(
+ torch.linalg.det(rotation.to(torch.float32)),
+ torch.ones(rotation.shape[0], device=rotation.device, dtype=torch.float32),
+ atol=1e-5,
+ rtol=0.0,
+ )
+
+
+def _assert_strictly_batched(op_name: str, shapes: tuple[tuple[int, ...], ...], device: torch.device) -> None:
+ # Shared body for the three test_convention_shapes_are_strictly_batched pins (TestRt2Extrinsics,
+ # TestCamtoworldGraphicsToVision, TestCamtoworldRtToPoseRt), whose executable bodies were
+ # line-for-line identical -- only their parametrize tables differ. One definition means a change
+ # to the assertion policy is one edit, not three synchronized ones; each class keeps its own
+ # parametrized test, so collect IDs and per-class failure reporting are unchanged.
+ # ShapeError (kornia's own) is asserted rather than the message text: within the call chains
+ # these three pins exercise, KORNIA_CHECK_SHAPE is the only thing that raises it (kornia
+ # raises ShapeError elsewhere too, e.g. directly in kornia/color/yuv.py, so this is a scoped
+ # claim, not a global one -- re-scope it before copying this helper to a new surface), so the
+ # type is the evidence that kornia's guard fired and not some downstream arithmetic, and the
+ # wording stays free to change.
+ # float32 is hardcoded and the dtype fixture dropped: a shape guard runs before any arithmetic,
+ # so which shapes are rejected cannot depend on the dtype and the fixture only multiplied cells.
+ # TestCARKitToColmap's variant is deliberately NOT routed through here: it is unparametrized and
+ # classifies a ValueError branch as well, so it is a different assertion, not a copy of this one.
+ op = getattr(kornia.geometry.conversions, op_name)
+ args = [torch.zeros(shape, device=device, dtype=torch.float32) for shape in shapes]
+
+ with pytest.raises(ShapeError):
+ op(*args)
+
+
class TestAngleAxisToQuaternion(BaseTester):
# based on:
# https://github.com/ceres-solver/ceres-solver/blob/master/internal/ceres/rotation_test.cc#L271
@@ -280,23 +773,18 @@ class TestAngleAxisToQuaternion(BaseTester):
# 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
- @pytest.mark.parametrize(
- ("deprecated_name", "replacement_name", "arg"),
- [
- ("angle_axis_to_rotation_matrix", "axis_angle_to_rotation_matrix", [[0.1, 0.2, 0.3]]),
- (
- "rotation_matrix_to_angle_axis",
- "rotation_matrix_to_axis_angle",
- [
- [0.5357142857142858, -0.6229365034008422, 0.5700529070291328],
- [0.765793646257985, 0.6428571428571429, -0.01716931065742361],
- [-0.3557671927434186, 0.4457407392288521, 0.8214285714285714],
- ],
- ),
- ("quaternion_to_angle_axis", "quaternion_to_axis_angle", [1.0, 2.0, 3.0, 4.0]),
- ("angle_axis_to_quaternion", "axis_angle_to_quaternion", [0.1, 0.2, 0.3]),
- ],
- )
+ # 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.
+ @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
):
@@ -313,7 +801,10 @@ class TestAngleAxisToQuaternion(BaseTester):
):
actual = deprecated(tensor)
- assert torch.equal(actual, expected)
+ assert not actual.isnan().any(), (
+ f"`{deprecated_name}` returned NaN; an exact comparison of two NaNs is not a match this pin should accept"
+ )
+ torch.testing.assert_close(actual, expected, rtol=0, atol=0)
def test_wart_integer_input_returns_the_zero_quaternion_3948(self, device):
# Wart pin for kornia#3948: axis_angle_to_quaternion allocates its output buffer with
@@ -1885,16 +2376,15 @@ class TestAngleAxisToRotationMatrix(BaseTester):
# Intended behavior: axis_angle_to_rotation_matrix returns a rotation matrix, i.e.
# R @ R.T == I and det(R) == 1 to the precision of the input dtype. It does not: the axis
# is normalised by (theta + eps) with eps = 1e-6 hardcoded inside the function, so the axis
- # is shrunk by eps/theta and what comes back is a slightly scaled rotation. Measured at
- # theta = pi/2 about +z in float64 (torch 2.9.1, cpu):
- # det(R) = 0.9999974535249636 (should be 1.0)
- # max|R @ R.T - I| = 2.5464750363912714e-06 (should be ~1e-16)
- # and the error does not shrink with dtype -- float32 gives 2.5033950805664062e-06.
+ # is shrunk by eps/theta and what comes back is a slightly scaled rotation. The measured
+ # determinant and orthogonality error at theta = pi/2 about +z are asserted executably by
+ # the companion wart named at the end of this comment, and are not restated here so that
+ # they cannot drift apart from it.
# kornia's own quaternion route is the independent reference for the intended value:
# quaternion_to_rotation_matrix(axis_angle_to_quaternion(v)) has det exactly 1.0 and
# max|R @ R.T - I| exactly 0.0 on this input, and differs from axis_angle_to_rotation_matrix
# by 1.273238328769466e-06 -- so the defect is in this function, not in the angle.
- # float64 is hardcoded and the dtype fixture dropped so the literals mean one thing; the
+ # float64 is hardcoded and the dtype fixture dropped so that figure means one thing; the
# skip is visible so that on MPS, which has no float64, a raw TypeError cannot satisfy the
# raises=AssertionError mark instead of the assertion this pin documents. Marked
# xfail(strict=True) so fixing #3947 makes this XPASS and forces the mark out. Companion
@@ -1933,6 +2423,15 @@ class TestAngleAxisToRotationMatrix(BaseTester):
# float64 is hardcoded and the dtype fixture dropped because both literals are float64
# facts: at float32 the same theta = 1e-3 input has theta**2 = 1.0000001111620804e-06 and
# falls into the *other* branch, so cell (2) would be pinning a different code path.
+ # A third, float32 cell backs the docstring's "float32 is no better" figure
+ # (2.5033950805664062e-06 on the same general-branch input), which was otherwise asserted
+ # nowhere: an eps scaled to the input dtype's machine epsilon could fix float32 while
+ # leaving float64, flipping no test but falsifying the docstring. Its atol is 1e-6, sized
+ # to backend variance rather than to cpu jitter: float32 trig/matmul kernels differ by a
+ # few ulp per entry across backends, and a 2-ulp move of one entry of R already shifts
+ # max|R R^T - I| by 2.4e-07, so a dot-product-jitter budget would flip on a kernel change
+ # with no kornia change. 1e-6 still discriminates: a #3947 fix drives the error to a few
+ # eps_float32 (~2.4e-07), well outside [2.5e-06 - 1e-6, 2.5e-06 + 1e-6].
# Snippet used to generate expected (torch only, executed on cpu float64):
# v = torch.tensor([[0., 0., math.pi / 2]], dtype=torch.float64)
# R = axis_angle_to_rotation_matrix(v)[0]
@@ -1942,9 +2441,24 @@ class TestAngleAxisToRotationMatrix(BaseTester):
# axis_angle_to_rotation_matrix(t)[0].tolist()
# -> [[1.0, -0.001, 0.0], [0.001, 1.0, 0.0], [0.0, 0.0, 1.0]]
# torch.linalg.det(that).item() -> 1.000001
+ axis_angle_to_rotation_matrix = kornia.geometry.conversions.axis_angle_to_rotation_matrix
+
+ # The float32 cell runs BEFORE the float64 gate so a float64-less device (MPS) still
+ # asserts the docstring's "float32 is no better" figure instead of skipping it away --
+ # skipping it would re-open the dtype-scoped half-fix this cell exists to catch.
+ general_f32 = axis_angle_to_rotation_matrix(
+ torch.tensor([[0.0, 0.0, torch.pi / 2]], device=device, dtype=torch.float32)
+ )[0]
+ assert_close(
+ (general_f32 @ general_f32.T - torch.eye(3, device=device, dtype=torch.float32)).abs().max(),
+ torch.tensor(2.5033950805664062e-06, device=device, dtype=torch.float32),
+ atol=1e-6,
+ rtol=0.0,
+ msg=_issue_msg("kornia#3947: the float32 general-branch orthogonality error changed"),
+ )
+
_skip_if_dtype_unavailable(device, torch.float64)
- axis_angle_to_rotation_matrix = kornia.geometry.conversions.axis_angle_to_rotation_matrix
identity = torch.eye(3, device=device, dtype=torch.float64)
general = axis_angle_to_rotation_matrix(
@@ -1980,7 +2494,7 @@ class TestAngleAxisToRotationMatrix(BaseTester):
"guard message saying (*, 3) β€” kornia#3955",
strict=True,
)
- def test_convention_accepts_any_leading_batch_dimensions_3955(self, device, dtype):
+ def test_convention_accepts_any_leading_batch_dimensions_3955(self, device):
# Intended behavior: axis_angle_to_rotation_matrix accepts (*, 3) -- which is what its own
# shape guard says in the message it raises ("Input size must be a (*, 3) tensor") and what
# every sibling in this module does, including rotation_matrix_to_axis_angle (pinned by
@@ -1994,10 +2508,16 @@ class TestAngleAxisToRotationMatrix(BaseTester):
# match, so the failure would be reported as an error rather than an XFAIL. Marked
# xfail(strict=True) so fixing #3955 makes this XPASS and forces the mark out. Companion
# wart: test_wart_only_rank_2_input_is_accepted_3955.
+ # float32 is hardcoded and the dtype fixture dropped: all three rank errors come out of the
+ # same shape-driven `wxyz.unbind(dim=1)` inside _compute_rotation_matrix, which no dtype can
+ # change. NOT "before any arithmetic runs" -- theta2 = (aa * aa).sum(-1), the sqrt and the
+ # axis division all execute first and succeed at every float dtype; it is that the
+ # arithmetic ahead of the unbind is dtype-safe, so which ranks are accepted still cannot
+ # depend on the dtype and the fixture only multiplied the cell count.
axis_angle_to_rotation_matrix = kornia.geometry.conversions.axis_angle_to_rotation_matrix
rotation_matrix_to_axis_angle = kornia.geometry.conversions.rotation_matrix_to_axis_angle
- unbatched = torch.tensor([0.0, 0.0, 0.6], device=device, dtype=dtype)
+ unbatched = torch.tensor([0.0, 0.0, 0.6], device=device, dtype=torch.float32)
rot = axis_angle_to_rotation_matrix(unbatched.reshape(1, 3))[0]
assert _runs_without_raising(axis_angle_to_rotation_matrix, unbatched), (
@@ -2022,7 +2542,7 @@ class TestAngleAxisToRotationMatrix(BaseTester):
],
ids=["unbatched", "extra_batch_dim", "singleton_extra_batch_dim"],
)
- def test_wart_only_rank_2_input_is_accepted_3955(self, device, dtype, shape, error, message):
+ def test_wart_only_rank_2_input_is_accepted_3955(self, device, shape, error, message):
# Wart pin for kornia#3955, companion to the strict xfail above: assert the CURRENT failure
# modes, matching on the message and not merely on the type, because the message is the
# evidence that these are raw Python unpacking errors leaking out of the implementation
@@ -2031,14 +2551,19 @@ class TestAngleAxisToRotationMatrix(BaseTester):
# is PyTorch's and CPython's wording, so a reword upstream would flip these cells and be
# misread as "#3955 was partly fixed". The phrase alone still separates the three failure
# modes from each other and from kornia's own guard, which is all the evidence needs.
- # Three cells: the unbatched case fails in a different place from the two over-batched ones
- # (an indexing error inside the theta reduction, not the unbind), so a fix that only
- # flattens the leading dimensions flips the last two and leaves the first. The (1, 1, 3)
- # and (2, 5, 3) cells do flip together under every fix shape I could construct, but they
- # are kept apart because they report *different* messages today, and pinning only one of
- # them would let the other change unnoticed.
+ # Three cells: all three raise at the SAME line -- wxyz.unbind(dim=1) in
+ # _compute_rotation_matrix -- but with different error kinds, because
+ # the rank differs: the unbatched (3,) case has no dim=1 to unbind and gets an IndexError,
+ # while the two over-batched cases unbind successfully and fail on the 3-way assignment
+ # with a ValueError. So a fix that only flattens the leading dimensions flips the last two
+ # and leaves the first. The (1, 1, 3) and (2, 5, 3) cells do flip together under every fix
+ # shape I could construct, but they are kept apart because they report *different* messages
+ # today, and pinning only one of them would let the other change unnoticed.
# If any cell fails, #3955 was (partly) fixed -- flip/remove the strict xfail above. NOT a
# contract that these ranks must keep raising.
+ # float32 is hardcoded and the dtype fixture dropped for the same reason as the xfail above:
+ # every one of these errors comes from the same shape-driven unbind, and the arithmetic that
+ # precedes it succeeds at every float dtype, so the dtype cannot change which ranks raise.
# Snippet used to generate expected (torch only, executed on cpu float64):
# axis_angle_to_rotation_matrix(torch.zeros(3, dtype=torch.float64))
# -> IndexError: Dimension out of range (expected to be in range of [-1, 0], but got 1)
@@ -2048,7 +2573,9 @@ class TestAngleAxisToRotationMatrix(BaseTester):
# -> ValueError: not enough values to unpack (expected 3, got 1)
# (the accepted ranks (1, 3) and (2, 3) return (1, 3, 3) and (2, 3, 3))
with pytest.raises(error, match=message):
- kornia.geometry.conversions.axis_angle_to_rotation_matrix(torch.zeros(shape, device=device, dtype=dtype))
+ kornia.geometry.conversions.axis_angle_to_rotation_matrix(
+ torch.zeros(shape, device=device, dtype=torch.float32)
+ )
class TestRotationMatrixToAngleAxis(BaseTester):
@@ -3174,6 +3701,1205 @@ class TestDenormalizePixelCoordinates(BaseTester):
)
+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 (reserved) may extend this surface. EVERY literal in this class -- not only
+ # the pins that repeat this line -- is built from the unconditional corner-aligned 2/(size - 1)
+ # constants, so all of them would flip if #3904 made the normalization respect align_corners.
+ # They record current default behavior; none of them is a ratified contract for that choice.
+
+ 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 --
+ # (1, 3, 3) and (1, 4, 4) -- for every size; there is no batched form, and the sizes are
+ # Python ints rather than tensors. With dtype=None the matrix is built by torch.tensor()
+ # from Python floats, so its dtype is torch's AMBIENT default rather than float32
+ # unconditionally: changing the process default changes the result. That is the mechanism
+ # behind the float32 constants that leak into float64 homography pipelines (kornia#3958,
+ # pinned in TestNormalizeHomography): normalize_homography calls these helpers without
+ # passing dtype= through, so they materialise at the ambient default and are cast after.
+ # The dtype fixture is dropped because the claim is about the *absence* of a dtype
+ # argument, and the default is read back through torch.get_default_dtype() rather than
+ # hardcoded, so the pin says "follows the ambient default" and not "is always float32".
+ # The ambient-default leg runs on cpu whatever the device fixture says: the claim is about
+ # which dtype is selected, not about placement, and MPS cannot represent float64 at all.
+ # Snippet used to generate expected (torch only, executed on cpu):
+ # normal_transform_pixel(4, 5).shape, .dtype -> (1, 3, 3), torch.float32
+ # normal_transform_pixel3d(3, 5, 9).shape, .dtype -> (1, 4, 4), torch.float32
+ # torch.set_default_dtype(torch.float64)
+ # normal_transform_pixel(4, 5).dtype -> torch.float64
+ normal_transform_pixel = kornia.geometry.conversions.normal_transform_pixel
+ normal_transform_pixel3d = kornia.geometry.conversions.normal_transform_pixel3d
+
+ assert normal_transform_pixel(4, 5, device=device).shape == (1, 3, 3)
+ assert normal_transform_pixel3d(3, 5, 9, device=device).shape == (1, 4, 4)
+ assert normal_transform_pixel(4, 5, device=device).dtype == torch.get_default_dtype()
+ assert normal_transform_pixel3d(3, 5, 9, device=device).dtype == torch.get_default_dtype()
+ assert normal_transform_pixel(4, 5, device=device, dtype=torch.float16).dtype == torch.float16
+
+ with _ambient_default_dtype(torch.float64):
+ ambient_dtype = normal_transform_pixel(4, 5).dtype
+
+ assert ambient_dtype == torch.float64, (
+ "normal_transform_pixel no longer follows the ambient default dtype, so the kornia#3958 "
+ "mechanism pinned in TestNormalizeHomography has changed"
+ )
+
+ 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.
+ # 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(
+ [[[0.5, 0.0, -1.0], [0.0, 1.0, -1.0], [0.0, 0.0, 1.0]]], device=device, dtype=torch.float32
+ )
+ 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):
+ # 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
+ )
+ 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]
+
+ 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 every figure below was taken on macOS arm64 and nothing here has
+ # run on x86-64/MKL; an unmeasured platform must not inherit a kernel literal.
+ # What that costs, stated rather than left to be discovered: of the runners
+ # pr_test_cpu.yml uses, only macos-latest is arm64, so the ubuntu and windows legs
+ # skip every cell here, and no CI job sets KORNIA_TEST_DTYPE to float16/bfloat16, so
+ # the reduced-precision cells -- the only ones with a nonzero literal on cpu -- run
+ # on none of them. The x86-64 rows need one measurement on such a runner to become
+ # live; deriving them from the arm64 figures instead is exactly what this key exists
+ # to prevent. 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, executed on macOS arm64 against both
+ # torch 2.9.1 and torch 2.5.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", "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"
+ )
+
+ def test_convention_3d_matrix_acts_on_x_y_z_one(self, device):
+ # Convention pin: normal_transform_pixel3d(depth, height, width) returns a 4x4 whose
+ # diagonal is (2/(width - 1), 2/(height - 1), 2/(depth - 1), 1) -- the matrix acts on
+ # 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.
+ # 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)
+ matrix = kornia.geometry.conversions.normal_transform_pixel3d(3, 5, 9, device=device, dtype=torch.float32)
+
+ expected = torch.tensor(
+ [[[0.25, 0.0, 0.0, -1.0], [0.0, 0.5, 0.0, -1.0], [0.0, 0.0, 1.0, -1.0], [0.0, 0.0, 0.0, 1.0]]],
+ device=device,
+ dtype=torch.float32,
+ )
+ self.assert_close(matrix, expected, atol=0.0, rtol=0.0)
+
+ def test_convention_3d_component_order_permutes_normalize_pixel_coordinates3d(self, device, dtype):
+ # Convention pin: normal_transform_pixel3d and normalize_pixel_coordinates3d order their
+ # components differently, so a 3-D grid built for one is silently permuted by the other.
+ # The matrix consumes (x, y, z); the helper consumes (d, x, y) (pinned in
+ # TestNormalizePixelCoordinates.test_convention_3d_component_order_is_depth_x_y). The same
+ # voxel therefore produces the same three numbers in two different slot orders --
+ # helper[(1, 2, 0)] == matrix route -- which is what this pin asserts, at atol=rtol=0.
+ # (depth, height, width) = (9, 5, 3) keeps every scale exact in every dtype.
+ # Snippet used to generate expected (stdlib only, depth = 9, height = 5, width = 3):
+ # helper (d, x, y) = (7, 2, 1) -> 2*7/8 - 1, 2*2/2 - 1, 2*1/4 - 1 -> [0.75, 1.0, -0.5]
+ # matrix (x, y, z) = (2, 1, 7) -> 2*2/2 - 1, 2*1/4 - 1, 2*7/8 - 1 -> [1.0, -0.5, 0.75]
+ _skip_if_dtype_unavailable(device, dtype)
+ voxel_for_helper = torch.tensor([[[7.0, 2.0, 1.0]]], device=device, dtype=dtype)
+ voxel_for_matrix = torch.tensor([[2.0], [1.0], [7.0], [1.0]], device=device, dtype=dtype)
+
+ via_helper = kornia.geometry.conversions.normalize_pixel_coordinates3d(voxel_for_helper, 9, 5, 3)[0, 0]
+ matrix = kornia.geometry.conversions.normal_transform_pixel3d(9, 5, 3, device=device, dtype=dtype)
+ via_matrix = (matrix[0] @ voxel_for_matrix)[:3, 0]
+
+ self.assert_close(via_helper, torch.tensor([0.75, 1.0, -0.5], device=device, dtype=dtype), atol=0.0, rtol=0.0)
+ self.assert_close(via_matrix, torch.tensor([1.0, -0.5, 0.75], device=device, dtype=dtype), atol=0.0, rtol=0.0)
+ self.assert_close(via_helper[[1, 2, 0]], via_matrix, atol=0.0, rtol=0.0)
+
+ # Wart-pin matrix for kornia#3957: one cell per (size argument x degenerate class) of
+ # normal_transform_pixel and normal_transform_pixel3d, asserting the CURRENT scale factor that
+ # a degenerate size produces. If any cell fails, #3957 was (partly) fixed -- update or remove
+ # the degenerate-size warnings on normal_transform_pixel, normal_transform_pixel3d,
+ # normalize_homography and normalize_homography3d (denormalize_homography inherits these
+ # warnings by reference), and also the
+ # expected_2d_1 / expected_3d_1 rows of TestHomographyNormalTransform in
+ # tests/geometry/transform/test_homography_warper.py, which hardcode the same
+ # size == 1 -> 2e14 literal and would otherwise fail two directories away with nothing
+ # connecting them to the fix. The cells are NOT a
+ # contract that a degenerate size must keep returning these numbers.
+ # They are regular tests rather than strict xfails for the same reason as the #3940 matrix in
+ # TestNormalizePixelCoordinates: the intended behavior (raise, clamp, or keep the current
+ # silent pass-through) is a maintainer decision, and a strict xfail asserting one of those
+ # answers would stay silently XFAIL forever if a different one were chosen. A wart pin flips
+ # loudly under every polarity, and covering the full matrix means any partial fix -- one
+ # function, one argument, or one degenerate class -- flips at least one cell.
+ # Exactly one size argument is degenerate per cell (the others stay at 3/5 in 2-D and 3/5/9 in
+ # 3-D, whose scales are exact in every dtype), so the finite components pin which argument was
+ # degenerated. The three classes give three different answers because only size == 1 is routed
+ # to eps: size == 1 divides by eps = 1e-14 and gives 2e14, size == 0 divides by -1 and gives a
+ # sign-flipped -2.0 (a mirroring transform), size == -3 divides by -4 and gives -0.5.
+ # float32 is hardcoded and the dtype fixture dropped: any kornia-side change to a scale flips
+ # the float32 cell. The 2-D scales are pure Python floats (2.0 / width_denom and friends)
+ # computed before any tensor exists, so other legs would only test torch's cast; the 3-D
+ # helper computes its scales as tensor arithmetic in the requested dtype
+ # (tr_mat[i, i] * 2.0 / denominator), so its other legs would re-run that division under a
+ # different rounding -- a claim about torch's arithmetic, not about which scale kornia
+ # chooses, which the float32 cell already pins.
+ # Snippet used to generate expected (torch only, executed on cpu float32/float64):
+ # normal_transform_pixel(3, 1)[0, 0, 0] -> 200000000753664.0 (2 / 1e-14)
+ # normal_transform_pixel(3, 0)[0, 0, 0] -> -2.0
+ # normal_transform_pixel(3, -3)[0, 0, 0] -> -0.5
+ # normal_transform_pixel3d(1, 5, 9)[0, 2, 2] -> 200000000753664.0
+ @pytest.mark.parametrize(
+ ("degenerate_size", "degenerate_scale"), [(1, 2e14), (0, -2.0), (-3, -0.5)], ids=["one", "zero", "negative"]
+ )
+ @pytest.mark.parametrize(
+ ("ndim", "arg_name", "diagonal"),
+ [
+ ("2d", "height", [0.5, None]),
+ ("2d", "width", [None, 1.0]),
+ ("3d", "depth", [0.25, 0.5, None]),
+ ("3d", "height", [0.25, None, 1.0]),
+ ("3d", "width", [None, 0.5, 1.0]),
+ ],
+ ids=["2d-height", "2d-width", "3d-depth", "3d-height", "3d-width"],
+ )
+ def test_wart_degenerate_size_scale_matrix_3957(
+ self, ndim, arg_name, diagonal, degenerate_size, degenerate_scale, device
+ ):
+ expected = list(diagonal)
+ expected[diagonal.index(None)] = degenerate_scale
+
+ if ndim == "2d":
+ sizes = {"height": 3, "width": 5}
+ sizes[arg_name] = degenerate_size
+ matrix = kornia.geometry.conversions.normal_transform_pixel(
+ sizes["height"], sizes["width"], device=device, dtype=torch.float32
+ )
+ else:
+ sizes = {"depth": 3, "height": 5, "width": 9}
+ sizes[arg_name] = degenerate_size
+ matrix = kornia.geometry.conversions.normal_transform_pixel3d(
+ sizes["depth"], sizes["height"], sizes["width"], device=device, dtype=torch.float32
+ )
+
+ scales = torch.stack([matrix[0, i, i] for i in range(len(expected))])
+
+ self.assert_close(scales, torch.tensor(expected, device=device, dtype=torch.float32), atol=0.0, rtol=0.0)
+
+ def test_wart_eps_guards_only_the_size_one_branch_3957(self, device):
+ # Wart pin for kornia#3957, companion to the matrix above: eps is consulted ONLY in the
+ # size == 1 branch -- the docstring now says exactly that ("denominator substituted for
+ # size - 1 when a size equals 1; it is not consulted on any other path"), and this pin is
+ # what keeps that sentence honest -- so the eps argument does not reach the case that is
+ # literally a zero-sized image. float32 is
+ # hardcoded and the dtype fixture dropped: which branch consults eps is a Python-level
+ # size comparison decided before any tensor arithmetic, and the pinned answers 2.0 and
+ # -2.0 are exact in every dtype, so no other-dtype leg can fail where float32 passes and
+ # the fixture only multiplied cells. Three cells:
+ # (0) the eps default is still 1e-14 -- a re-tuned default already flips the size == 1
+ # cells of the matrix above loudly (they call with the default and pin 2/1e-14), so
+ # this cell adds attribution, not detection: it fails naming the default itself
+ # instead of leaving a reader to reverse-engineer a 2e14 mismatch;
+ # (1) eps=1.0 changes the size == 1 answer to 2.0, proving that branch reads eps;
+ # (2) the same eps=1.0 leaves the size == 0 answer at -2.0, proving that branch does not.
+ # If any cell fails, #3957 was (partly) fixed -- flip/remove the matrix above. NOT a
+ # contract that eps must keep being ignored on the size == 0 path.
+ # Snippet used to generate expected (torch only, executed on cpu):
+ # normal_transform_pixel(3, 1, eps=1.0)[0, 0, 0] -> 2.0
+ # normal_transform_pixel(3, 0, eps=1.0)[0, 0, 0] -> -2.0
+ normal_transform_pixel = kornia.geometry.conversions.normal_transform_pixel
+ assert inspect.signature(normal_transform_pixel).parameters["eps"].default == 1e-14, (
+ "kornia#3957: the eps default moved, so the 2e14 literals pinned above no longer describe a default call"
+ )
+
+ size_one = normal_transform_pixel(3, 1, eps=1.0, device=device, dtype=torch.float32)[0, 0, 0]
+ size_zero = normal_transform_pixel(3, 0, eps=1.0, device=device, dtype=torch.float32)[0, 0, 0]
+
+ self.assert_close(size_one, torch.tensor(2.0, device=device, dtype=torch.float32), atol=0.0, rtol=0.0)
+ self.assert_close(size_zero, torch.tensor(-2.0, device=device, dtype=torch.float32), atol=0.0, rtol=0.0)
+
+ def test_wart_integer_dtype_truncates_the_scale_to_zero_3959(self, device):
+ # Wart pin for kornia#3959: the matrix is built by torch.tensor([...], dtype=dtype) from
+ # Python floats, so an integer dtype truncates every scale below 1 to 0 and the function
+ # returns a rank-deficient matrix -- no error, no warning. The 2-D result maps EVERY pixel
+ # to the constant (-1, -1) -- recorded in the snippet as pure arithmetic on the
+ # bitwise-pinned integer matrix, so it is not asserted separately (and no integer matmul
+ # runs, which CUDA would not implement). The 3-D cell keeps depth = 2 so that its z scale, 2/1 = 2,
+ # survives the truncation: a partial fix that only promotes float scales would still have
+ # to flip the two zeroed axes.
+ # There is deliberately NO companion strict xfail, for the same reason as
+ # test_wart_integer_input_returns_the_zero_quaternion_3948: the intended behavior is
+ # undecided (promote to float, or raise), and an assertion-shaped xfail can express only
+ # the first. If either cell fails, #3959 was (partly) fixed -- remove this pin. NOT a
+ # contract that an integer dtype must keep returning a degenerate matrix.
+ # The dtype fixture is dropped because the claim is about the dtype argument itself.
+ # Snippet used to generate expected (torch only, executed on cpu):
+ # normal_transform_pixel(4, 5, dtype=torch.int64)
+ # -> [[0, 0, -1], [0, 0, -1], [0, 0, 1]]
+ # normal_transform_pixel3d(2, 4, 5, dtype=torch.int64)
+ # -> diag [0, 0, 2] (2/(5-1) and 2/(4-1) truncate, 2/(2-1) does not)
+ # matrix @ (x, y, 1) -> (-1, -1, 1) for every pixel -- e.g. (0, 0), (4, 3), (2, 1)
+ matrix = kornia.geometry.conversions.normal_transform_pixel(4, 5, device=device, dtype=torch.int64)
+ matrix3d = kornia.geometry.conversions.normal_transform_pixel3d(2, 4, 5, device=device, dtype=torch.int64)
+
+ assert matrix[0].tolist() == [[0, 0, -1], [0, 0, -1], [0, 0, 1]], (
+ "kornia#3959: an integer dtype no longer truncates the 2-D normalization scales to 0"
+ )
+ assert [matrix3d[0, i, i].item() for i in range(3)] == [0, 0, 2], (
+ "kornia#3959: an integer dtype no longer truncates the 3-D normalization scales to 0"
+ )
+
+
+class TestNormalizeHomography(BaseTester):
+ # normalize_homography, denormalize_homography and normalize_homography3d 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
+ # normal_transform_pixel, whose corner-aligned convention all three inherit.
+ # The CONVENTION pins below (composition, direction, round-trip, batching, 3-D) use sizes of
+ # the form 2**k + 1 (3, 5, 9, 17) so that every 2/(size - 1) is exact in every dtype and those
+ # pins compare at atol=rtol=0. That also keeps them independent of kornia#3958 (the float32
+ # constants leak, pinned separately below with non-dyadic sizes): a fix for #3958 must not flip
+ # an ordering or direction pin. The exactness invariant is theirs alone -- the bug pins below
+ # deliberately step outside it (the round-trip pin's non-dyadic (4, 5)/(8, 9) legs at
+ # atol=32*eps, the #3960 cells, the #3957 propagation warts), so a new atol=0 pin belongs here
+ # only at these sizes AND with a literal whose intermediates are exact. The invariant also
+ # leans on the SHAPE of the normalization matrices -- upper-triangular with power-of-two
+ # pivots -- surviving BOTH inverse routes actually in play (the functions do NOT share one):
+ # normalize_homography inverts through _inverse_3x3_closed_form (cofactor arithmetic --
+ # products and sums of dyadic values, then division by a power-of-two determinant, all
+ # exact), while denormalize_homography and normalize_homography3d go through
+ # _torch_inverse_cast (torch.linalg.inv in eager mode, rounding-free on such triangular
+ # matrices, with a float32 upcast for half dtypes and a closed-form 3x3 fallback under
+ # tracing -- each exactness-preserving on these values). A future non-triangular
+ # normalization (a #3904 align_corners variant, say) voids the atol=0 claim on EVERY route
+ # and needs a tolerance instead.
+ # No pin asserts anything about kornia#3962 (no denormalize_homography3d, no
+ # ColmapQTVecs_to_ARKitQTVecs) -- a missing symbol is a scope question, not a defect.
+ # NOTE: kornia#3904 (reserved) may extend this surface. EVERY literal in this class -- the
+ # composition, direction, round-trip, batching and 3-D pins as much as the #3957 and #3958 bug
+ # pins, and whether or not the pin repeats this line -- is built from the corner-aligned
+ # 2/(size - 1) constants these three functions inherit from normal_transform_pixel, so a #3904
+ # fix that made the normalization respect align_corners would flip all of them. They record
+ # current default behavior; none of them ratifies that choice as contract. (The #3958 pins would
+ # also flip on a #3958 fix, which is their point; the #3904 exposure is separate and additional.)
+
+ def test_gradcheck(self, device):
+ # The three functions are on the warp_perspective path and are differentiable in their
+ # homography argument, and nothing in the suite checked that: neither this file nor
+ # test_homography_warper.py had a gradcheck for any of them before this pin
+ # (`grep -rn "normalize_homography" tests/ | grep gradcheck` was empty). Each is linear in
+ # the homography -- a fixed matrix on each side -- so the gradient is the composition of
+ # the two normalization matrices and any evaluation point checks the same thing; a
+ # non-identity one is used anyway so that a route which silently ignored its input would
+ # not still agree numerically. The dsize arguments are Python ints, so they are bound
+ # through partial rather than passed as gradcheck inputs.
+ # normal_transform_pixel and normal_transform_pixel3d get no gradcheck on purpose: they
+ # take ints and return a constant matrix, so there is no input to differentiate.
+ dtype = torch.float64
+ homography = torch.tensor([[[1.0, 0.2, 3.0], [0.1, 1.0, -2.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype)
+ homography3d = torch.eye(4, device=device, dtype=dtype)[None] + 0.1
+
+ self.gradcheck(
+ partial(kornia.geometry.conversions.normalize_homography, dsize_src=(4, 5), dsize_dst=(8, 9)),
+ (homography,),
+ )
+ self.gradcheck(
+ partial(kornia.geometry.conversions.denormalize_homography, dsize_src=(4, 5), dsize_dst=(8, 9)),
+ (homography,),
+ )
+ self.gradcheck(
+ partial(kornia.geometry.conversions.normalize_homography3d, dsize_src=(2, 4, 5), dsize_dst=(3, 8, 9)),
+ (homography3d,),
+ )
+
+ def test_convention_maps_normalized_src_to_normalized_dst(self, device, dtype):
+ # Convention pin: the returned matrix has the SAME src -> dst direction as its input,
+ # re-expressed in the two [-1, 1] frames -- it maps normalized src coordinates to
+ # normalized dst coordinates, and it is size-aware: a +2 px shift in a 5-wide image becomes
+ # a +1.0 shift in normalized units (2 px * 2/(5 - 1)).
+ # Only the matrix is asserted: the pixel-level reading in the snippet -- src (1, 1)
+ # normalized, pushed through the result, landing on the normalization of the dst pixel
+ # (3, 1) -- is pure arithmetic on the bitwise-pinned matrix and this test's constants.
+ # NOTE: covered by this class's kornia#3904 note above; recorded, not a ratified contract.
+ # Snippet used to generate expected (stdlib only, height = 3, width = 5 on both sides):
+ # 2 / (5 - 1) = 0.5, so the +2 px translation becomes 2 * 0.5 = 1.0
+ # src (1, 1) -> (2*1/4 - 1, 2*1/2 - 1) = (-0.5, 0.0)
+ # dst (3, 1) -> (2*3/4 - 1, 2*1/2 - 1) = ( 0.5, 0.0)
+ _skip_if_dtype_unavailable(device, dtype)
+ _skip_if_closed_form_inverse_unavailable(device, dtype)
+ translate_two_px = torch.tensor(
+ [[[1.0, 0.0, 2.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype
+ )
+
+ normalized = kornia.geometry.conversions.normalize_homography(translate_two_px, (3, 5), (3, 5))
+
+ 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, and a #3904 fix is expected to move both cells.
+ # 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
+ _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))
+
+ 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)
+
+ 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
+ # N(dsize_dst) @ H @ N(dsize_src)^-1 -- the source size drives the RIGHT (input) factor and
+ # the destination size the LEFT (output) factor. Both sizes are asymmetric here ((3, 5) and
+ # (5, 9)) and the same call with the two size arguments exchanged is pinned to its own,
+ # different literal: that second literal is what makes this a direction pin rather than a
+ # value pin, since the reversed composition is exactly the mistake a caller makes.
+ # Snippet used to generate expected (torch only, executed on cpu float64 and float32):
+ # H = [[2, 0.5, 2], [-0.25, 1, 1], [0, 0, 1]]
+ # normalize_homography(H, (3, 5), (5, 9))
+ # -> [[1.0, 0.125, 0.625], [-0.25, 0.5, -0.25], [0.0, 0.0, 1.0]]
+ # normalize_homography(H, (5, 9), (3, 5))
+ # -> [[4.0, 0.5, 4.5], [-1.0, 2.0, 1.0], [0.0, 0.0, 1.0]]
+ _skip_if_dtype_unavailable(device, dtype)
+ _skip_if_closed_form_inverse_unavailable(device, dtype)
+ homography = torch.tensor(_DIRECTION_H, device=device, dtype=dtype)
+
+ normalized = kornia.geometry.conversions.normalize_homography(homography, (3, 5), (5, 9))
+ swapped = kornia.geometry.conversions.normalize_homography(homography, (5, 9), (3, 5))
+
+ self.assert_close(
+ normalized,
+ torch.tensor([[[1.0, 0.125, 0.625], [-0.25, 0.5, -0.25], [0.0, 0.0, 1.0]]], device=device, dtype=dtype),
+ atol=0.0,
+ rtol=0.0,
+ )
+ self.assert_close(
+ swapped,
+ torch.tensor([[[4.0, 0.5, 4.5], [-1.0, 2.0, 1.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype),
+ atol=0.0,
+ rtol=0.0,
+ )
+
+ def test_convention_denormalize_is_the_mirror_composition(self, device, dtype):
+ # Convention pin: denormalize_homography(H, dsize_src, dsize_dst) composes
+ # N(dsize_dst)^-1 @ H @ N(dsize_src) -- the exact mirror of normalize_homography, with the
+ # same argument roles (source size on the right, destination size on the left) and the two
+ # normalization matrices exchanged. Pinned on the same asymmetric input and sizes as the
+ # normalize pin above, so the two literals can be read side by side; they differ, which is
+ # what rules out the two functions being the same map.
+ # Snippet used to generate expected (torch only, executed on cpu float64 and float32):
+ # H = [[2, 0.5, 2], [-0.25, 1, 1], [0, 0, 1]]
+ # denormalize_homography(H, (3, 5), (5, 9))
+ # -> [[4.0, 2.0, 2.0], [-0.25, 2.0, 2.5], [0.0, 0.0, 1.0]]
+ _skip_if_dtype_unavailable(device, dtype)
+ homography = torch.tensor(_DIRECTION_H, device=device, dtype=dtype)
+
+ denormalized = kornia.geometry.conversions.denormalize_homography(homography, (3, 5), (5, 9))
+
+ self.assert_close(
+ denormalized,
+ torch.tensor([[[4.0, 2.0, 2.0], [-0.25, 2.0, 2.5], [0.0, 0.0, 1.0]]], device=device, dtype=dtype),
+ atol=0.0,
+ rtol=0.0,
+ )
+
+ def test_convention_normalize_and_denormalize_round_trip(self, device, dtype):
+ # Convention pin: the two functions are mutual inverses, in BOTH compositions -- each is
+ # executed on its own here rather than one being inferred from the other -- on a general
+ # projective homography whose bottom row is non-zero.
+ # Two legs. With dyadic sizes ((3, 5) and (5, 9)) every normalization constant is exact,
+ # and THIS literal is chosen so that every intermediate product and sum is exactly
+ # representable too (exact constants alone do not make the round trip bitwise -- that is a
+ # property of the whole computation, not of the sizes or of the entries; the
+ # triangular-inverse mechanism in the class header is part of it), so the round trip
+ # returns the input bit for bit and that leg runs at atol=rtol=0. Cross-file:
+ # TestHomographyWarper::test_consistency in
+ # tests/geometry/transform/test_homography_warper.py (back-pointer there) exercises the
+ # same high-level mutual-inverse invariant, on its own literal, sizes and tolerances. With
+ # non-dyadic sizes ((4, 5) and (8, 9)) the constants are rounded and the round trip is only
+ # approximate; its tolerance is sized from the mechanism rather than from a measurement --
+ # each entry passes through four matrix products and TWO 3x3 inverses, one per function and
+ # by different routines (normalize_homography inverts N_src with _inverse_3x3_closed_form,
+ # denormalize_homography inverts N_dst with _torch_inverse_cast), so the error is a small
+ # multiple of eps times the largest entry (max |H| = 4) -- giving atol = 32 * eps and
+ # rtol = 8 * eps. Both compositions are asserted at those sizes, not just one: they do not
+ # land on the same figure, and quoting one of them for the other is the mistake a
+ # single-leg pin invites. Measured float32 deviations, sample points against a bound of
+ # 3.8e-06: 1.19e-07 for denormalize(normalize(H)) and 2.38e-07 for the reverse.
+ # Snippet used to generate expected (torch only, executed on cpu at every dtype):
+ # H = [[1.25, 0.25, 4], [-0.5, 0.75, 2], [0.0625, 0.125, 1]]
+ # denormalize_homography(normalize_homography(H, (3, 5), (5, 9)), (3, 5), (5, 9)) == H (bitwise)
+ # normalize_homography(denormalize_homography(H, (3, 5), (5, 9)), (3, 5), (5, 9)) == H (bitwise)
+ _skip_if_dtype_unavailable(device, dtype)
+ _skip_if_closed_form_inverse_unavailable(device, dtype)
+ normalize_homography = kornia.geometry.conversions.normalize_homography
+ denormalize_homography = kornia.geometry.conversions.denormalize_homography
+ homography = torch.tensor(_ROUND_TRIP_H, device=device, dtype=dtype)
+
+ denorm_of_norm = denormalize_homography(normalize_homography(homography, (3, 5), (5, 9)), (3, 5), (5, 9))
+ norm_of_denorm = normalize_homography(denormalize_homography(homography, (3, 5), (5, 9)), (3, 5), (5, 9))
+
+ self.assert_close(denorm_of_norm, homography, atol=0.0, rtol=0.0)
+ self.assert_close(norm_of_denorm, homography, atol=0.0, rtol=0.0)
+
+ eps = torch.finfo(dtype).eps
+ non_dyadic = denormalize_homography(normalize_homography(homography, (4, 5), (8, 9)), (4, 5), (8, 9))
+ non_dyadic_reverse = normalize_homography(denormalize_homography(homography, (4, 5), (8, 9)), (4, 5), (8, 9))
+
+ 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
+ # on a batch of two different homographies, comparing element 1 of the batched call against
+ # the single-element call.
+ _skip_if_dtype_unavailable(device, dtype)
+ _skip_if_closed_form_inverse_unavailable(device, dtype)
+ normalize_homography = kornia.geometry.conversions.normalize_homography
+ denormalize_homography = kornia.geometry.conversions.denormalize_homography
+ batch = torch.tensor([_DIRECTION_H[0], _ROUND_TRIP_H[0]], device=device, dtype=dtype)
+
+ normalized = normalize_homography(batch, (3, 5), (5, 9))
+ denormalized = denormalize_homography(batch, (3, 5), (5, 9))
+
+ assert normalized.shape == (2, 3, 3)
+ self.assert_close(normalized[1], normalize_homography(batch[1:], (3, 5), (5, 9))[0], atol=0.0, rtol=0.0)
+ self.assert_close(denormalized[1], denormalize_homography(batch[1:], (3, 5), (5, 9))[0], atol=0.0, rtol=0.0)
+
+ def test_convention_3d_dsize_is_depth_height_width(self, device, dtype):
+ # Convention pin: normalize_homography3d takes (depth, height, width) size tuples, composes
+ # them the same way as the 2-D function (source size on the right, destination size on the
+ # left) and returns a 4x4 acting on homogeneous (x, y, z, 1). Both the call and the call
+ # with the two size arguments exchanged are pinned, so the pin is about direction and not
+ # only about values; the sizes are asymmetric in all three axes ((3, 5, 9) and (5, 9, 17)),
+ # so a (width, height, depth) reading of either tuple would give a different matrix.
+ # Snippet used to generate expected (torch only, executed on cpu float64 and float32):
+ # H = [[2, 0.5, 0.25, 2], [-0.25, 1, 0.5, 1], [0.125, -0.5, 2, 3], [0, 0, 0, 1]]
+ # normalize_homography3d(H, (3, 5, 9), (5, 9, 17))
+ # -> [[1.0, 0.125, 0.03125, 0.40625], [-0.25, 0.5, 0.125, -0.375],
+ # [0.25, -0.5, 1.0, 1.25], [0.0, 0.0, 0.0, 1.0]]
+ # normalize_homography3d(H, (5, 9, 17), (3, 5, 9))
+ # -> [[4.0, 0.5, 0.125, 4.125], [-1.0, 2.0, 0.5, 1.0],
+ # [1.0, -2.0, 4.0, 5.0], [0.0, 0.0, 0.0, 1.0]]
+ _skip_if_dtype_unavailable(device, dtype)
+ homography = torch.tensor(
+ [
+ [
+ [2.0, 0.5, 0.25, 2.0],
+ [-0.25, 1.0, 0.5, 1.0],
+ [0.125, -0.5, 2.0, 3.0],
+ [0.0, 0.0, 0.0, 1.0],
+ ]
+ ],
+ device=device,
+ dtype=dtype,
+ )
+
+ normalized = kornia.geometry.conversions.normalize_homography3d(homography, (3, 5, 9), (5, 9, 17))
+ swapped = kornia.geometry.conversions.normalize_homography3d(homography, (5, 9, 17), (3, 5, 9))
+
+ self.assert_close(
+ normalized,
+ torch.tensor(
+ [
+ [
+ [1.0, 0.125, 0.03125, 0.40625],
+ [-0.25, 0.5, 0.125, -0.375],
+ [0.25, -0.5, 1.0, 1.25],
+ [0.0, 0.0, 0.0, 1.0],
+ ]
+ ],
+ device=device,
+ dtype=dtype,
+ ),
+ atol=0.0,
+ rtol=0.0,
+ )
+ self.assert_close(
+ swapped,
+ torch.tensor(
+ [
+ [
+ [4.0, 0.5, 0.125, 4.125],
+ [-1.0, 2.0, 0.5, 1.0],
+ [1.0, -2.0, 4.0, 5.0],
+ [0.0, 0.0, 0.0, 1.0],
+ ]
+ ],
+ device=device,
+ dtype=dtype,
+ ),
+ atol=0.0,
+ rtol=0.0,
+ )
+
+ @pytest.mark.xfail(
+ raises=AssertionError,
+ reason="the normalization matrices are built at the ambient default dtype and cast to the "
+ "input afterwards, so a float64 caller gets float32-rounded constants β€” kornia#3958",
+ strict=True,
+ )
+ def test_convention_float64_input_gets_float64_normalization_constants_3958(self, device):
+ # Intended behavior: a float64 homography is normalized with float64 constants, so the
+ # entries carry float64 accuracy. They do not: normalize_homography calls
+ # normal_transform_pixel() without passing dtype= through, so the constants materialise at
+ # the ambient default (float32) and are cast to float64 afterwards, leaving about eight
+ # significant digits. For sizes (4, 4) -> (6, 6) the (0, 0) entry is mathematically
+ # 2/(6 - 1) * (4 - 1)/2 = 0.6 exactly, and any float64-native evaluation lands within an ulp
+ # of it; the tolerance 1e-12 sits four orders above float64 noise and three below the
+ # deviation the current implementation produces.
+ # Non-dyadic sizes are required here: with 2**k + 1 sizes the float32 constants are exact
+ # and there is nothing to leak, which is why the ordering pins above use them and this pin
+ # does not. float64 is hardcoded and the dtype fixture dropped because the claim is a
+ # float64 claim, and the skip is visible so that on MPS, which has no float64, a raw
+ # TypeError cannot satisfy the raises=AssertionError mark instead of the assertion.
+ # Marked xfail(strict=True) so fixing #3958 makes this XPASS and forces the mark out.
+ # Companion wart: test_wart_float32_constants_leak_into_float64_results_3958.
+ _skip_if_dtype_unavailable(device, torch.float64)
+
+ identity = torch.eye(3, device=device, dtype=torch.float64)[None]
+
+ normalized = kornia.geometry.conversions.normalize_homography(identity, (4, 4), (6, 6))
+
+ assert abs(normalized[0, 0, 0].item() - 0.6) < 1e-12, (
+ "kornia#3958: normalize_homography did not use float64 normalization constants"
+ )
+
+ def test_wart_float32_constants_leak_into_float64_results_3958(self, device):
+ # Wart pin for kornia#3958, companion to the strict xfail above: assert the CURRENT
+ # float32-rounded entries in a float64 result. Four cells:
+ # (1) normalize_homography, whose src factor is inverted by the closed-form 3x3 inverse;
+ # (2) denormalize_homography, whose dst factor is inverted by _torch_inverse_cast instead
+ # -- a separate code path that could be fixed on its own;
+ # (3) normalize_homography3d, which calls the 3-D helper and is a third call site;
+ # (4) the control that proves the cause is the missing dtype= pass-through and not an
+ # epsilon or a rounding choice: with the ambient default dtype set to float64 the
+ # same call returns the float64-native value 0.6000000000000001, because the helper
+ # now materialises in float64 before the cast. Cell (4) also fails if the helpers stop
+ # reading the ambient default, which is the other half of the same mechanism.
+ # If any cell fails, #3958 was (partly) fixed -- flip/remove the strict xfail above. NOT a
+ # contract that float64 callers must keep receiving float32-rounded constants.
+ # atol 1e-10 pins the MAGNITUDE of the deviation, which is what the docstring warning
+ # promises ("the magnitude -- half the mantissa gone -- is the point ... rather than the
+ # digits"): it sits an order below the ~8.9e-09 deviation being discriminated (so a fix
+ # still flips these cells red) and six above the ~1.1e-16 ulp of the entries, so no
+ # backend's reassociation of the matmul-and-inverse chain can flip them. float64 is
+ # hardcoded for the same reason as the xfail above.
+ # Snippet used to generate expected (torch only, executed on cpu float64):
+ # normalize_homography(eye(3, float64), (4, 4), (6, 6))[0, 0] -> 0.5999999910593036
+ # denormalize_homography(eye(3, float64), (4, 4), (6, 6))[0, 0] -> 1.6666666915019348
+ # normalize_homography3d(eye(4, float64), (4, 4, 4), (6, 6, 6))[0, 0] -> 0.5999999910593036
+ # with torch.set_default_dtype(torch.float64):
+ # normalize_homography(eye(3, float64), (4, 4), (6, 6))[0, 0] -> 0.6000000000000001
+ _skip_if_dtype_unavailable(device, torch.float64)
+
+ normalize_homography = kornia.geometry.conversions.normalize_homography
+ identity = torch.eye(3, device=device, dtype=torch.float64)[None]
+ identity3d = torch.eye(4, device=device, dtype=torch.float64)[None]
+
+ normalized = normalize_homography(identity, (4, 4), (6, 6))[0, 0, 0]
+ denormalized = kornia.geometry.conversions.denormalize_homography(identity, (4, 4), (6, 6))[0, 0, 0]
+ normalized3d = kornia.geometry.conversions.normalize_homography3d(identity3d, (4, 4, 4), (6, 6, 6))[0, 0, 0]
+
+ with _ambient_default_dtype(torch.float64):
+ with_float64_default = normalize_homography(identity, (4, 4), (6, 6))[0, 0, 0]
+
+ assert_close(
+ normalized,
+ torch.tensor(0.5999999910593036, device=device, dtype=torch.float64),
+ atol=1e-10,
+ rtol=0.0,
+ msg=_issue_msg("kornia#3958: normalize_homography no longer rounds its constants to float32"),
+ )
+ assert_close(
+ denormalized,
+ torch.tensor(1.6666666915019348, device=device, dtype=torch.float64),
+ atol=1e-10,
+ rtol=0.0,
+ msg=_issue_msg("kornia#3958: denormalize_homography no longer rounds its constants to float32"),
+ )
+ assert_close(
+ normalized3d,
+ torch.tensor(0.5999999910593036, device=device, dtype=torch.float64),
+ atol=1e-10,
+ rtol=0.0,
+ msg=_issue_msg("kornia#3958: normalize_homography3d no longer rounds its constants to float32"),
+ )
+ assert_close(
+ with_float64_default,
+ torch.tensor(0.6000000000000001, device=device, dtype=torch.float64),
+ atol=1e-10,
+ rtol=0.0,
+ 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 truncation itself is pinned in
+ # test_wart_integer_dtype_truncates_the_scale_to_zero_3959 above), 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, matching
+ # test_wart_one_pixel_output_makes_warp_perspective_all_nan_3957 below: 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)
+ 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.xfail(
+ raises=AssertionError,
+ reason="the or-guard accepts any (B, N, N) tensor, so a wrong-sized matrix reaches matmul "
+ "instead of the shape check β€” kornia#3960",
+ strict=True,
+ )
+ @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):
+ # Intended behavior: a matrix of the wrong size is rejected by the function's own shape
+ # guard, with a message naming the argument -- which is what the guard already does for a
+ # rank-2 input of the wrong shape. It is not: the guard reads
+ # `len(shape) == 3 or shape[-2:] == (3, 3)`, and the `or` means any rank-3 tensor passes
+ # whatever its trailing shape is, so a (1, 4, 4) input to the 3x3 functions (and a (1, 3, 3)
+ # input to the 4x4 one) reaches the matmul and dies there with a message that names neither
+ # the argument nor the expected shape.
+ # Three cells because the three functions carry three separate copies of the guard.
+ # The current behavior is a raise, so the body classifies the exception instead of letting
+ # it escape: under raises=AssertionError an escaping RuntimeError would be reported as an
+ # error rather than an XFAIL. 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
+ # today's matmul failure -- counts as guarded and XPASSes this pin. Today's matmul
+ # RuntimeError, raised at the arithmetic statement itself, counts as unguarded, which
+ # keeps the pin XFAIL until #3960 is actually fixed. The cells come from the shared
+ # _WRONG_SIZE_CASES table for the same reason: the pair must cover identical cells.
+ # Marked xfail(strict=True) so fixing #3960 makes all three cases XPASS and forces the mark
+ # out. Companion wart: test_wart_wrong_sized_matrices_die_inside_matmul_3960.
+ 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))
+ 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"
+
+ @pytest.mark.parametrize(("op_name", "wrong_size"), _WRONG_SIZE_CASES, ids=_WRONG_SIZE_IDS)
+ def test_wart_wrong_sized_matrices_die_inside_matmul_3960(self, op_name, wrong_size, device):
+ # Wart pin for kornia#3960, companion to the strict xfail above: assert that the wrong-sized
+ # matrix CURRENTLY escapes kornia's guard and dies in downstream arithmetic. Two layers, on
+ # purpose. pytest.raises(RuntimeError) requires the exception TYPE that torch's own
+ # arithmetic raises -- the name says the input dies inside matmul, and catching a broader
+ # Exception would let an unrelated TypeError or IndexError regression pass under that name;
+ # a guard fix in any of kornia's own check styles is not a RuntimeError at all and escapes
+ # the raises() outright. The assertion then holds the complement of the xfail's
+ # classification through the same module-level _raised_by_a_kornia_guard, which is what
+ # closes the remaining case: a guard raising a bare RuntimeError passes the raises() but
+ # fails this assert, so it cannot land unnoticed either. Neither layer depends on message
+ # text (the message below is quoted as a sample, asserted nowhere).
+ # If any cell fails, #3960 was (partly) fixed -- flip/remove the strict xfail above. NOT a
+ # contract that these shapes must keep dying outside the guard.
+ # Snippet used to generate expected (torch only, executed on cpu float32, torch 2.9.1):
+ # normalize_homography(torch.eye(4)[None], (4, 5), (8, 9))
+ # -> RuntimeError: Expected size for first two dimensions of batch2 tensor to be:
+ # [1, 4] but got: [1, 3].
+ # normalize_homography3d(torch.eye(3)[None], (2, 4, 5), (3, 8, 9))
+ # -> RuntimeError: ... to be: [1, 3] but got: [1, 4].
+ op = getattr(kornia.geometry.conversions, op_name)
+ wrong = torch.eye(wrong_size, device=device, dtype=torch.float32)[None]
+
+ with pytest.raises(RuntimeError) as excinfo:
+ op(wrong, *_homography_sizes(op_name))
+
+ assert not _raised_by_a_kornia_guard(excinfo.value), (
+ f"kornia#3960: {op_name} now rejects a ({wrong_size}, {wrong_size}) matrix in its own "
+ "shape guard -- the companion strict xfail should be XPASSing"
+ )
+
+ def test_wart_normalize_homography3d_shape_error_says_bx3x3_3960(self, device):
+ # Wart pin for the message half of kornia#3960: normalize_homography3d is a 4x4 function
+ # whose own shape guard reports "must be a Bx3x3 tensor". Pinned separately from the cells
+ # above because it is a different failure path -- this input is caught by the guard, those
+ # are not -- and because a fix that only tightens the guard's *condition* would leave the
+ # wrong noun in place. If this fails, the message was corrected -- remove this pin. NOT a
+ # contract that the message must keep naming the wrong shape.
+ # 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 Bx3x3 tensor. Got torch.Size([4, 5])
+ with pytest.raises(ValueError, match="must be a Bx3x3 tensor"):
+ kornia.geometry.conversions.normalize_homography3d(
+ torch.zeros(4, 5, device=device, dtype=torch.float32), (2, 4, 5), (3, 8, 9)
+ )
+
+ def test_wart_degenerate_dsize_propagates_into_the_homography_3957(self, device):
+ # Wart pin for kornia#3957 in the homography functions: the degenerate scales pinned in
+ # TestNormalTransformPixel are not contained by the composition -- they arrive in the
+ # returned matrix, silently and finite. Four cells, each a different way the same root
+ # shows up:
+ # (1) normalize_homography with a 1-pixel-wide source collapses the x scale to 2.5e-15;
+ # (2) denormalize_homography with the same sizes explodes it to 4.0e+14 instead -- the
+ # reciprocal, because the two functions invert opposite factors;
+ # (3) normalize_homography with a ZERO-wide source silently mirrors (a negative x scale
+ # and a shifted offset), a different degenerate class that no fix for (1) need touch;
+ # (4) normalize_homography3d with depth == 1 returns a matrix whose z scale is 5.0e-15 --
+ # near-singular in practice, not formally singular, so nothing downstream raises.
+ # If any cell fails, #3957 was (partly) fixed -- flip/remove the matrix in
+ # TestNormalTransformPixel too. NOT a contract that a degenerate dsize must keep producing
+ # these numbers.
+ # float32 is hardcoded and the dtype fixture dropped: at float16 the 2e14 scale overflows to
+ # inf and the chain degenerates by a different mechanism (this pin does not decide that
+ # case), while at float64 the constants are still built in float32 (kornia#3958) so the
+ # literals would be the same numbers pinned twice.
+ # rtol 1e-6 rather than an exact comparison: the entries are float32 values printed at
+ # float64 precision, and one ulp of 2.5e-15 is 5e-22 -- far tighter than any claim made here.
+ # Snippet used to generate expected (torch only, executed on cpu float32):
+ # normalize_homography(eye(3)[None], (4, 1), (4, 5))[0, 0] -> 2.500000167887412e-15
+ # denormalize_homography(eye(3)[None], (4, 1), (4, 5))[0, 0] -> 400000001507328.0
+ # normalize_homography(eye(3)[None], (4, 0), (4, 5))[0] -> [-0.25, 0.0, -1.25]
+ # normalize_homography3d(eye(4)[None], (1, 4, 5), (3, 8, 9))[2, 2] -> 4.99999991225835e-15
+ identity = torch.eye(3, device=device, dtype=torch.float32)[None]
+ identity3d = torch.eye(4, device=device, dtype=torch.float32)[None]
+
+ collapsed = kornia.geometry.conversions.normalize_homography(identity, (4, 1), (4, 5))[0, 0, 0]
+ exploded = kornia.geometry.conversions.denormalize_homography(identity, (4, 1), (4, 5))[0, 0, 0]
+ mirrored = kornia.geometry.conversions.normalize_homography(identity, (4, 0), (4, 5))[0, 0]
+ near_singular = kornia.geometry.conversions.normalize_homography3d(identity3d, (1, 4, 5), (3, 8, 9))[0, 2, 2]
+
+ assert_close(
+ collapsed,
+ torch.tensor(2.500000167887412e-15, device=device, dtype=torch.float32),
+ rtol=1e-6,
+ atol=0.0,
+ msg=_issue_msg("kornia#3957: a 1-pixel-wide source no longer collapses the normalized x scale"),
+ )
+ assert_close(
+ exploded,
+ torch.tensor(400000001507328.0, device=device, dtype=torch.float32),
+ rtol=1e-6,
+ atol=0.0,
+ msg=_issue_msg("kornia#3957: a 1-pixel-wide source no longer explodes the denormalized x scale"),
+ )
+ assert_close(
+ mirrored,
+ torch.tensor([-0.25, 0.0, -1.25], device=device, dtype=torch.float32),
+ rtol=1e-6,
+ atol=0.0,
+ msg=_issue_msg("kornia#3957: a zero-wide source no longer produces a mirrored normalization"),
+ )
+ assert_close(
+ near_singular,
+ torch.tensor(4.99999991225835e-15, device=device, dtype=torch.float32),
+ rtol=1e-6,
+ atol=0.0,
+ msg=_issue_msg("kornia#3957: depth == 1 no longer collapses the normalized z scale"),
+ )
+
+ def test_wart_one_pixel_output_makes_warp_perspective_all_nan_3957(self, device):
+ # Wart pin for the user-visible end of kornia#3957, executed rather than argued: a
+ # 1-pixel-high output size sends normalize_homography's 2e14 scale into
+ # warp_perspective's grid and every sampled value comes back NaN -- with align_corners=True,
+ # i.e. in the branch kornia#3904's reserved fix does not touch. crop_by_transform_mat is
+ # pinned in the same test because it is the caller kornia#3929 reports the symptom from.
+ # The finite control at a 2-pixel-high output is what makes the two NaN cells evidence of
+ # the degenerate denominator rather than of warp_perspective being broken in general.
+ # NaN is checked with torch.isnan, never with an equality against a NaN literal.
+ # If any cell fails, #3957 was (partly) fixed -- flip/remove the wart pins above. NOT a
+ # contract that a 1-pixel output must keep returning NaN.
+ # float32 is hardcoded and the dtype fixture dropped: this pin is about a size, not a dtype.
+ # TWO LAYERS, on purpose. The load-bearing claim -- the 1-pixel output is BROKEN while the
+ # 2-pixel control is not -- is asserted device-portably: the 1-row output does not reproduce
+ # the row the same identity warp produces at 2 rows. The stronger "and the breakage is
+ # specifically all-NaN" form is asserted only on the devices it was generated and verified
+ # on backends whose grid_sample propagates an all-NaN grid (probed below; cpu and mps,
+ # executed), because the NaN depends on backend NaN handling inside grid_sample: the
+ # sampling grid entering it is entirely NaN, and with padding_mode='zeros' a kernel that
+ # turns floor(NaN) into a failed within-bounds check would emit 0.0 instead of NaN. That
+ # would still be a broken output -- and the portable assertion would still catch it -- but
+ # it is not a fact this branch has executed, and no CUDA fact is claimed anywhere in this
+ # work. Asserting all-NaN unconditionally would let an untested backend fail here and be
+ # misread as "#3957 was partly fixed", which is the one misreading this pin must not invite.
+ # Snippet used to generate expected (torch only, executed on cpu float32, torch 2.9.1; the
+ # same three lines re-executed on mps give the same verdicts):
+ # img = torch.arange(25.).view(1, 1, 5, 5)
+ # warp_perspective(img, torch.eye(3)[None], (1, 4), align_corners=True) -> all nan
+ # crop_by_transform_mat(img, torch.eye(3)[None], (1, 4), align_corners=True) -> all nan
+ # warp_perspective(img, torch.eye(3)[None], (2, 4), align_corners=True)
+ # -> [[0., 1., 2., 3.], [5., 6., 7., 8.]] (finite control)
+ image = torch.arange(25.0, device=device, dtype=torch.float32).view(1, 1, 5, 5)
+ identity = torch.eye(3, device=device, dtype=torch.float32)[None]
+
+ warped = kornia.geometry.transform.warp_perspective(image, identity, (1, 4), align_corners=True)
+ cropped = kornia.geometry.transform.crop_by_transform_mat(image, identity, (1, 4), align_corners=True)
+ control = kornia.geometry.transform.warp_perspective(image, identity, (2, 4), align_corners=True)
+
+ assert torch.isfinite(control).all(), (
+ "kornia#3957: the 2-pixel-high control is no longer finite, so the cells above stopped being evidence"
+ )
+ assert not torch.equal(warped[0, 0, 0], control[0, 0, 0]), (
+ "kornia#3957: a 1-pixel-high warp_perspective output now reproduces the 2-row control's first row, "
+ "i.e. the degenerate size no longer corrupts the sampling grid"
+ )
+ assert not torch.equal(cropped[0, 0, 0], control[0, 0, 0]), (
+ "kornia#3957: a 1-pixel-high crop_by_transform_mat output now reproduces the 2-row control's first row"
+ )
+
+ # Capability probe instead of a device-name list, so the all-NaN leg self-extends to any
+ # backend whose grid_sample propagates an all-NaN grid and shows up as a SKIP (not a
+ # silent pass) anywhere else. The portable corruption assertions above have already run
+ # by this point on every device.
+ nan_grid = torch.full((1, 1, 1, 2), float("nan"), device=device, dtype=torch.float32)
+ probe = torch.nn.functional.grid_sample(
+ torch.zeros(1, 1, 2, 2, device=device, dtype=torch.float32), nan_grid, align_corners=True
+ )
+ if not torch.isnan(probe).all():
+ pytest.skip(
+ "this backend's grid_sample does not propagate an all-NaN sampling grid; the "
+ "all-NaN symptom leg is scoped to backends where it does (executed: cpu, mps)"
+ )
+
+ assert torch.isnan(warped).all(), (
+ "kornia#3957: a 1-pixel-high warp_perspective output is no longer all-NaN on this device"
+ )
+ assert torch.isnan(cropped).all(), (
+ "kornia#3957: a 1-pixel-high crop_by_transform_mat output is no longer all-NaN on this device"
+ )
+
+
class TestProjectPoints(BaseTester):
def test_smoke(self, device, dtype):
point_3d = torch.zeros(1, 3, device=device, dtype=dtype)
@@ -3401,6 +5127,258 @@ class TestRt2Extrinsics(BaseTester):
t = torch.rand(batch_size, 3, 1, dtype=torch.float64, device=device)
self.gradcheck(kornia.geometry.conversions.Rt_to_matrix4x4, (R, t))
+ # Every literal in the convention pins below uses the same asymmetric rotation
+ # R = [[0, 0, 1], [1, 0, 0], [0, 1, 0]] -- the 120-degree turn about (1, 1, 1), a proper
+ # rotation (det = +1) that differs from its own transpose -- with t = (1, 2, 3). Its entries are
+ # 0 and 1, so every product below is exact in every dtype and the pins compare at atol=rtol=0;
+ # an identity or a symmetric rotation would make the direction and transpose claims unfalsifiable.
+
+ def test_convention_translation_is_the_last_column_under_a_0_0_0_1_row(self, device):
+ # Convention pin: Rt_to_matrix4x4 places R in the top-left 3x3 block, t in the LAST COLUMN
+ # (not the bottom row, which is the other packing convention in use), and appends
+ # [0, 0, 0, 1]. Pinned as one hardcoded 4x4 so that a transposed or bottom-row packing
+ # cannot satisfy it. float32 is hardcoded and the dtype fixture dropped for the same reason
+ # as the split-back pin below: packing is pure concatenation of exactly representable
+ # values -- no arithmetic touches any element -- so no other-dtype leg can fail where
+ # float32 passes.
+ # Snippet used to generate expected (torch only, executed on cpu):
+ # Rt_to_matrix4x4([[0,0,1],[1,0,0],[0,1,0]], [1,2,3])
+ # -> [[0, 0, 1, 1], [1, 0, 0, 2], [0, 1, 0, 3], [0, 0, 0, 1]]
+ rotation, translation = _asymmetric_pose(device, torch.float32)
+
+ extrinsics = Rt_to_matrix4x4(rotation, translation)
+
+ expected = torch.tensor(
+ [[[0.0, 0.0, 1.0, 1.0], [1.0, 0.0, 0.0, 2.0], [0.0, 1.0, 0.0, 3.0], [0.0, 0.0, 0.0, 1.0]]],
+ device=device,
+ dtype=torch.float32,
+ )
+ self.assert_close(extrinsics, expected, atol=0.0, rtol=0.0)
+
+ def test_convention_matrix_maps_x_to_r_x_plus_t(self, device):
+ # Convention pin: the packed matrix computes x_out = R @ x_in + t, established by applying
+ # it to points rather than by reading the argument names. The origin maps to t itself, so
+ # under the camtoworld reading the rest of this family uses (pinned in
+ # TestCamtoworldRtToPoseRt.test_convention_camtoworld_t_is_the_camera_centre) t is the
+ # camera centre in world coordinates -- Rt_to_matrix4x4 itself is frame-agnostic and packs
+ # whatever (R, t) it is given; what it is NOT is a world-to-camera packing, which would
+ # send the origin to -R.T @ t.
+ # Snippet used to generate expected (torch only, executed on cpu):
+ # M @ (0, 0, 0, 1) -> [1, 2, 3, 1] == t
+ # M @ (1, 0, 0, 1) -> [1, 3, 3, 1] == R[:, 0] + t = (0, 1, 0) + (1, 2, 3)
+ # float32 is hardcoded and the dtype fixture dropped: Rt_to_matrix4x4 is pure
+ # concatenation, so only the test-side matmul would run per-dtype -- torch's arithmetic,
+ # not kornia's.
+ rotation, translation = _asymmetric_pose(device, torch.float32)
+
+ extrinsics = Rt_to_matrix4x4(rotation, translation)[0]
+
+ origin = torch.tensor([0.0, 0.0, 0.0, 1.0], device=device, dtype=torch.float32)
+ unit_x = torch.tensor([1.0, 0.0, 0.0, 1.0], device=device, dtype=torch.float32)
+
+ self.assert_close(
+ extrinsics @ origin,
+ torch.tensor([1.0, 2.0, 3.0, 1.0], device=device, dtype=torch.float32),
+ atol=0.0,
+ rtol=0.0,
+ )
+ self.assert_close(
+ extrinsics @ unit_x,
+ torch.tensor([1.0, 3.0, 3.0, 1.0], device=device, dtype=torch.float32),
+ atol=0.0,
+ rtol=0.0,
+ )
+
+ def test_convention_matrix4x4_to_Rt_splits_back_and_ignores_the_bottom_row(self, device):
+ # Convention pin: matrix4x4_to_Rt returns (R (B, 3, 3), t (B, 3, 1)) sliced out of the same
+ # positions Rt_to_matrix4x4 wrote them to. Rt -> 4x4 -> Rt is therefore 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]. It reads only the top three rows: a projective
+ # (non-affine) bottom row is silently dropped, and packing the pieces back re-imposes the
+ # canonical [0, 0, 0, 1], so a matrix carrying [9, 9, 9, 9] does not survive the trip
+ # (executed below). That makes the pair lossy for anything but a rigid transform, which is
+ # the claim this pin fixes. float32 is hardcoded and the dtype fixture dropped: the round
+ # trip is pure slicing and concatenation of exactly representable values -- no arithmetic
+ # touches any element -- so no other-dtype leg can fail where float32 passes and the
+ # fixture only multiplied cells.
+ # Not asserted, per this file's rule that a comparison which could only flip together with
+ # one already made is left out: the two recovered shapes (assert_close checks shape itself,
+ # and the two calls below run against the (1, 3, 3)/(1, 3, 1) tensors _asymmetric_pose
+ # returns) and the canonical re-pack
+ # Rt_to_matrix4x4(recovered_R, recovered_t) == extrinsics (pure cat/pad over tensors the
+ # two lines above already pin bitwise to what extrinsics was built from). The PROJECTIVE
+ # re-pack at the end IS asserted -- the rebuilt [0, 0, 0, 1] bottom row is what nothing
+ # else here constrains.
+ # Snippet used to generate expected (torch only, executed on cpu):
+ # matrix4x4_to_Rt(M) -> (R, t) equal to the inputs of Rt_to_matrix4x4, bitwise
+ # matrix4x4_to_Rt(M with bottom row [9, 9, 9, 9]) -> the same (R, t)
+ # Rt_to_matrix4x4(that R, t)[0, 3] -> [0, 0, 0, 1]
+ rotation, translation = _asymmetric_pose(device, torch.float32)
+ extrinsics = Rt_to_matrix4x4(rotation, translation)
+
+ recovered_R, recovered_t = matrix4x4_to_Rt(extrinsics)
+
+ self.assert_close(recovered_R, rotation, atol=0.0, rtol=0.0)
+ self.assert_close(recovered_t, translation, atol=0.0, rtol=0.0)
+
+ projective = extrinsics.clone()
+ projective[0, 3] = torch.tensor([9.0, 9.0, 9.0, 9.0], device=device, dtype=torch.float32)
+ projective_R, projective_t = matrix4x4_to_Rt(projective)
+
+ self.assert_close(projective_R, rotation, atol=0.0, rtol=0.0)
+ self.assert_close(projective_t, translation, atol=0.0, rtol=0.0)
+ self.assert_close(
+ Rt_to_matrix4x4(projective_R, projective_t)[0, 3],
+ torch.tensor([0.0, 0.0, 0.0, 1.0], device=device, dtype=torch.float32),
+ atol=0.0,
+ rtol=0.0,
+ )
+
+ def test_convention_matrix4x4_to_Rt_returns_views_of_its_input(self, device):
+ # Convention pin: the two returned tensors are VIEWS of the input extrinsics, not copies --
+ # writing into the returned R in place rewrites the caller's matrix. Pinned by observing the
+ # mutation rather than by comparing data_ptr(), so the pin stays true to what a caller can
+ # actually notice. float32 is hardcoded and the dtype fixture dropped: whether the returned
+ # tensors alias the input is a property of the slicing, not of the element type, so no
+ # other-dtype leg can fail where float32 passes and the fixture only multiplied cells.
+ # What this pin does NOT decide: whether the views are contiguous (they are not, today),
+ # whether any particular later kornia version must keep aliasing, or what a copy-returning
+ # implementation should do; it records the aliasing so the Convention block that documents
+ # it stays honest. The t leg is asserted separately because R and t are two independent
+ # slices and a fix could copy one and not the other.
+ # Snippet used to generate expected (torch only, executed on cpu):
+ # R, t = matrix4x4_to_Rt(M); R.mul_(0.) -> M[:, :3, :3] becomes all zeros
+ # t.mul_(0.) -> M[:, :3, 3] becomes all zeros
+ rotation, translation = _asymmetric_pose(device, torch.float32)
+ extrinsics = Rt_to_matrix4x4(rotation, translation)
+
+ aliased_R, aliased_t = matrix4x4_to_Rt(extrinsics)
+ aliased_R.mul_(0.0)
+
+ self.assert_close(
+ extrinsics[0, :3, :3], torch.zeros(3, 3, device=device, dtype=torch.float32), atol=0.0, rtol=0.0
+ )
+ self.assert_close(
+ extrinsics[0, :3, 3], torch.tensor([1.0, 2.0, 3.0], device=device, dtype=torch.float32), atol=0.0, rtol=0.0
+ )
+
+ aliased_t.mul_(0.0)
+
+ 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.
+ # 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)
+ 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:
+ 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"
+ )
+
+ 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"
+ )
+
+ @pytest.mark.parametrize(
+ ("op_name", "shapes"),
+ [
+ ("Rt_to_matrix4x4", ((3, 3), (1, 3, 1))),
+ ("Rt_to_matrix4x4", ((1, 3, 3), (1, 3))),
+ ("Rt_to_matrix4x4", ((1, 3, 3), (1, 1, 3))),
+ ("Rt_to_matrix4x4", ((1, 4, 4), (1, 3, 1))),
+ ("Rt_to_matrix4x4", ((2, 1, 3, 3), (1, 3, 1))),
+ ("matrix4x4_to_Rt", ((4, 4),)),
+ ("matrix4x4_to_Rt", ((2, 1, 4, 4),)),
+ ("matrix4x4_to_Rt", ((1, 3, 3),)),
+ ],
+ ids=[
+ "pack-unbatched-R",
+ "pack-flat-t",
+ "pack-transposed-t",
+ "pack-4x4-R",
+ "pack-extra-batch-dim",
+ "split-unbatched",
+ "split-extra-batch-dim",
+ "split-3x3",
+ ],
+ )
+ def test_convention_shapes_are_strictly_batched(self, op_name, shapes, device):
+ # Convention pin: both functions go through KORNIA_CHECK_SHAPE and accept exactly
+ # (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.
+ _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 and the #3960 wart.
+ # 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)
+
+ with pytest.raises(RuntimeError):
+ Rt_to_matrix4x4(rotation, translation)
+
class TestCamtoworldGraphicsToVision(BaseTester):
@pytest.mark.parametrize("batch_size", [1, 2, 3])
@@ -3442,6 +5420,183 @@ class TestCamtoworldGraphicsToVision(BaseTester):
self.gradcheck(camtoworld_graphics_to_vision_4x4, (K_vis,))
self.gradcheck(camtoworld_vision_to_graphics_4x4, (K_vis,))
+ # The convention pins below use the same asymmetric pose as TestRt2Extrinsics --
+ # R = [[0, 0, 1], [1, 0, 0], [0, 1, 0]] (a proper rotation that is not its own transpose) with
+ # t = (1, 2, 3) -- because an identity or a symmetric pose is invariant under the very flip
+ # being pinned. All entries are 0, 1 or small integers, so every literal is exact in every dtype.
+
+ def test_convention_flip_right_multiplies_by_diag_1_minus1_minus1_1(self, device, dtype):
+ # Convention pin: the conversion is extrinsics @ diag(1, -1, -1, 1) -- a RIGHT
+ # multiplication, i.e. a change of the CAMERA-side basis. Two consequences are pinned
+ # because both are what a caller gets wrong: columns 1 and 2 of the rotation flip sign while
+ # column 0 is untouched, and the translation column is left ALONE. The left-multiplied
+ # alternative, diag(1, -1, -1, 1) @ extrinsics, negates the translation instead -- exactly
+ # what happens when a *worldtocam* matrix is passed to these functions, a silent error
+ # since the shapes match. That contrast is recorded in the snippet below rather than
+ # asserted: it is test-side arithmetic on an already-pinned matrix with no kornia call on
+ # its path, so per this file's rule it could only flip on a torch matmul regression.
+ # The determinant of the rotation block stays +1: two axes flip, not one, so handedness is
+ # preserved and this is a rotation rather than a reflection.
+ # Snippet used to generate expected (torch only, executed on cpu):
+ # M = [[0, 0, 1, 1], [1, 0, 0, 2], [0, 1, 0, 3], [0, 0, 0, 1]]
+ # camtoworld_graphics_to_vision_4x4(M)
+ # -> [[0, 0, -1, 1], [1, 0, 0, 2], [0, -1, 0, 3], [0, 0, 0, 1]]
+ # diag(1, -1, -1, 1) @ M
+ # -> [[0, 0, 1, 1], [-1, 0, 0, -2], [0, -1, 0, -3], [0, 0, 0, 1]]
+ _skip_if_dtype_unavailable(device, dtype)
+ rotation, translation = _asymmetric_pose(device, dtype)
+ extrinsics = Rt_to_matrix4x4(rotation, translation)
+
+ flipped = camtoworld_graphics_to_vision_4x4(extrinsics)
+
+ expected = torch.tensor(
+ [[[0.0, 0.0, -1.0, 1.0], [1.0, 0.0, 0.0, 2.0], [0.0, -1.0, 0.0, 3.0], [0.0, 0.0, 0.0, 1.0]]],
+ device=device,
+ dtype=dtype,
+ )
+ self.assert_close(flipped, expected, atol=0.0, rtol=0.0)
+
+ flipped_R, flipped_t = camtoworld_graphics_to_vision_Rt(rotation, translation)
+
+ self.assert_close(flipped_t, translation, atol=0.0, rtol=0.0)
+ self.assert_close(flipped_R, flipped[:, :3, :3], atol=0.0, rtol=0.0)
+ _assert_proper_rotation(flipped_R)
+
+ @pytest.mark.parametrize(
+ ("op_name", "shapes"),
+ [
+ ("camtoworld_graphics_to_vision_4x4", ((4, 4),)),
+ ("camtoworld_graphics_to_vision_4x4", ((2, 1, 4, 4),)),
+ ("camtoworld_graphics_to_vision_4x4", ((1, 3, 3),)),
+ ("camtoworld_vision_to_graphics_4x4", ((4, 4),)),
+ ("camtoworld_graphics_to_vision_Rt", ((3, 3), (1, 3, 1))),
+ ("camtoworld_graphics_to_vision_Rt", ((1, 3, 3), (1, 3))),
+ ("camtoworld_vision_to_graphics_Rt", ((1, 4, 4), (1, 3, 1))),
+ ],
+ ids=[
+ "g2v-4x4-unbatched",
+ "g2v-4x4-extra-batch-dim",
+ "g2v-4x4-3x3",
+ "v2g-4x4-unbatched",
+ "g2v-Rt-unbatched-R",
+ "g2v-Rt-flat-t",
+ "v2g-Rt-4x4-R",
+ ],
+ )
+ def test_convention_shapes_are_strictly_batched(self, op_name, shapes, device):
+ # Convention pin: the four conversions accept exactly (B, 4, 4) and (B, 3, 3) + (B, 3, 1) --
+ # no unbatched form and no extra leading batch dimensions, the same strictness as
+ # Rt_to_matrix4x4, which the Rt variants call. 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_graphics_is_y_up_and_vision_is_y_down(self, device, dtype):
+ # Convention pin: the two frames the docstrings name, read off the columns of the converted
+ # identity pose. For a camtoworld matrix, column i is the world direction of camera axis i,
+ # so converting the identity graphics pose gives the vision axes in graphics coordinates:
+ # +x is shared, +y is negated (up -> down) and +z is negated (backwards -> forwards).
+ # Graphics (OpenGL): [+x, +y, +z] == [right, up, backwards], the camera looks down -z.
+ # Vision (OpenCV): [+x, +y, +z] == [right, down, forwards], the camera looks down +z.
+ # Asserted as the full diag(1, -1, -1, 1) matrix rather than per-column reads -- strictly
+ # stronger: the translation column and the bottom row are covered too.
+ # Snippet used to generate expected (torch only, executed on cpu):
+ # camtoworld_graphics_to_vision_4x4(torch.eye(4)[None]) -> diag(1, -1, -1, 1)
+ _skip_if_dtype_unavailable(device, dtype)
+ identity = torch.eye(4, device=device, dtype=dtype)[None]
+
+ vision_axes = camtoworld_graphics_to_vision_4x4(identity)[0]
+
+ self.assert_close(
+ vision_axes,
+ torch.diag(torch.tensor([1.0, -1.0, -1.0, 1.0], device=device, dtype=dtype)),
+ atol=0.0,
+ 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)
+ _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"
+
+ once = camtoworld_graphics_to_vision_4x4(signed_zeros)
+ twice = camtoworld_graphics_to_vision_4x4(once)
+
+ 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"
+
class TestCamtoworldRtToPoseRt(BaseTester):
@pytest.mark.parametrize("batch_size", [1, 2, 3])
@@ -3472,6 +5627,148 @@ class TestCamtoworldRtToPoseRt(BaseTester):
self.gradcheck(camtoworld_to_worldtocam_Rt, (R, t))
self.gradcheck(worldtocam_to_camtoworld_Rt, (R, t))
+ # The convention pins below reuse the asymmetric pose of TestRt2Extrinsics --
+ # R = [[0, 0, 1], [1, 0, 0], [0, 1, 0]], t = (1, 2, 3) -- so that R.T differs from R and the
+ # transpose claim is falsifiable; every literal is exact in every dtype.
+
+ def test_convention_is_the_rigid_inverse_r_transposed_and_minus_r_transposed_t(self, device, dtype):
+ # Convention pin: both functions compute exactly (R.T, -R.T @ t) -- the RIGID inverse, built
+ # from a transpose, with no matrix inverse anywhere. Checked against a literal computed by
+ # hand rather than against torch.inverse, so the pin does not assume the very property it
+ # is asserting: for this R, R.T @ t permutes (1, 2, 3) to (2, 3, 1) and the result is its
+ # negation. One assert per output: the hand literal IS R.T of _ASYMMETRIC_R, so a second
+ # comparison against rotation.transpose(1, 2) could only ever flip together with it and is
+ # not made. Same for t's shape -- the assert_close against a (1, 3, 1) literal checks it.
+ # Snippet used to generate expected (stdlib only):
+ # R.T = [[0, 1, 0], [0, 0, 1], [1, 0, 0]]
+ # R.T @ t = (2, 3, 1)
+ # -R.T @ t = (-2, -3, -1)
+ _skip_if_dtype_unavailable(device, dtype)
+ rotation, translation = _asymmetric_pose(device, dtype)
+
+ inverted_R, inverted_t = camtoworld_to_worldtocam_Rt(rotation, translation)
+
+ self.assert_close(
+ inverted_R,
+ torch.tensor([[[0.0, 1.0, 0.0], [0.0, 0.0, 1.0], [1.0, 0.0, 0.0]]], device=device, dtype=dtype),
+ atol=0.0,
+ rtol=0.0,
+ )
+ self.assert_close(
+ 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
+ # in world coordinates; on the worldtocam (Colmap) side the same centre maps to the origin,
+ # so the returned t' = -R.T @ t is the world-to-camera translation and not a second camera
+ # centre. The composition of the two matrices is the identity.
+ # Snippet used to generate expected (torch only, executed on cpu):
+ # M @ (0, 0, 0, 1) -> [1, 2, 3, 1] (the camera centre)
+ # Mi @ (1, 2, 3, 1) -> [0, 0, 0, 1]
+ # Mi @ M -> the identity
+ _skip_if_dtype_unavailable(device, dtype)
+ rotation, translation = _asymmetric_pose(device, dtype)
+
+ camtoworld = Rt_to_matrix4x4(rotation, translation)[0]
+ worldtocam = Rt_to_matrix4x4(*camtoworld_to_worldtocam_Rt(rotation, translation))[0]
+
+ origin = torch.tensor([0.0, 0.0, 0.0, 1.0], device=device, dtype=dtype)
+ centre = torch.tensor([1.0, 2.0, 3.0, 1.0], device=device, dtype=dtype)
+
+ self.assert_close(camtoworld @ origin, centre, atol=0.0, rtol=0.0)
+ self.assert_close(worldtocam @ centre, origin, atol=0.0, rtol=0.0)
+ self.assert_close(worldtocam @ camtoworld, torch.eye(4, device=device, dtype=dtype), atol=0.0, rtol=0.0)
+
+ @pytest.mark.parametrize(
+ ("op_name", "shapes"),
+ [
+ ("camtoworld_to_worldtocam_Rt", ((3, 3), (1, 3, 1))),
+ ("camtoworld_to_worldtocam_Rt", ((1, 3, 3), (1, 3))),
+ ("camtoworld_to_worldtocam_Rt", ((2, 1, 3, 3), (1, 3, 1))),
+ ("worldtocam_to_camtoworld_Rt", ((3, 3), (1, 3, 1))),
+ ("worldtocam_to_camtoworld_Rt", ((1, 3, 3), (1, 3))),
+ ],
+ ids=["c2w-unbatched-R", "c2w-flat-t", "c2w-extra-batch-dim", "w2c-unbatched-R", "w2c-flat-t"],
+ )
+ 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.
+ # 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_wart_non_orthogonal_rotation_is_transposed_not_inverted_3961(self, device, dtype):
+ # Wart pin for kornia#3961: R is ASSUMED orthogonal and the assumption is never checked, so
+ # for any other matrix the result is a transpose that is not an inverse -- silently, with no
+ # error and no warning. Three cells, each a different observable of the same root:
+ # (1) the returned rotation is exactly R.T even though R.T is not R^-1 here;
+ # (2) composing the two 4x4 matrices misses the identity by 3.0, i.e. not by a rounding
+ # amount -- this is what a caller notices as "my poses drifted";
+ # (3) even the round trip breaks, the translation coming back 9.0 away from the input;
+ # cell (3) is kept separate from (2) because a fix that validated only the rotation
+ # would leave the translation error in place for a caller who ignores the raise.
+ # There is deliberately NO companion strict xfail: the intended behavior is undecided -- a
+ # fix could raise on a non-orthogonal R, or fall back to a true inverse -- and an
+ # assertion-shaped xfail could express only one of those and would stay silently XFAIL if
+ # the other were chosen. Same shape as the #3948 and #3957 wart pins in this file.
+ # If any cell fails, #3961 was (partly) fixed -- remove this pin. NOT a contract that a
+ # non-orthogonal R must keep producing these numbers.
+ # R = [[1, 0.5, 0], [0, 1, 0], [0, 0, 2]] has det = 2 and dyadic entries, so every literal
+ # below is exact in every dtype.
+ # Snippet used to generate expected (torch only, executed on cpu):
+ # camtoworld_to_worldtocam_Rt(R, (1, 2, 3))
+ # -> R' = [[1, 0, 0], [0.5, 1, 0], [0, 0, 2]] (= R.T), t' = (-1, -2.5, -6)
+ # max|Rt_to_matrix4x4(R', t') @ Rt_to_matrix4x4(R, t) - I| -> 3.0
+ # worldtocam_to_camtoworld_Rt(R', t')[1] -> (2.25, 2.5, 12.0), i.e. 9.0 from (1, 2, 3)
+ _skip_if_dtype_unavailable(device, dtype)
+ rotation = torch.tensor([[[1.0, 0.5, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 2.0]]], device=device, dtype=dtype)
+ translation = torch.tensor([[[1.0], [2.0], [3.0]]], device=device, dtype=dtype)
+
+ inverted_R, inverted_t = camtoworld_to_worldtocam_Rt(rotation, translation)
+ composed = Rt_to_matrix4x4(inverted_R, inverted_t)[0] @ Rt_to_matrix4x4(rotation, translation)[0]
+ _, round_trip_t = worldtocam_to_camtoworld_Rt(inverted_R, inverted_t)
+
+ self.assert_close(inverted_R, rotation.transpose(1, 2), atol=0.0, rtol=0.0)
+ self.assert_close(
+ inverted_t, torch.tensor([[[-1.0], [-2.5], [-6.0]]], device=device, dtype=dtype), atol=0.0, rtol=0.0
+ )
+ assert (composed - torch.eye(4, device=device, dtype=dtype)).abs().max().item() == 3.0, (
+ "kornia#3961: a non-orthogonal rotation no longer misses the identity by 3.0"
+ )
+ self.assert_close(
+ round_trip_t, torch.tensor([[[2.25], [2.5], [12.0]]], device=device, dtype=dtype), atol=0.0, rtol=0.0
+ )
+
class TestCARKitToColmap(BaseTester):
def test_everything(self, device, dtype):
@@ -3491,6 +5788,301 @@ class TestCARKitToColmap(BaseTester):
self.assert_close(angles_colmap, expected_angles, rtol=1e-4, atol=1e-5)
self.assert_close(t_colmap, expected_t, rtol=1e-4, atol=1e-5)
+ def test_convention_quaternion_order_is_w_x_y_z_on_both_sides(self, device, dtype):
+ # Convention pin: the real part comes FIRST on both sides of this function -- the input
+ # qvec is read as (w, x, y, z), and the returned q_colmap is (w, x, y, z) too, which is
+ # Colmap's images.txt order (QW QX QY QZ).
+ # Two legs, one per side, because the two are independent claims:
+ # (in) [1, 0, 0, 0] is the identity rotation, so the result is the pure frame flip. The
+ # (x, y, z, w) impostor of the same rotation, [0, 0, 0, 1], is passed as the
+ # contrast: kornia reads it as a 180-degree turn about z and returns a different
+ # quaternion AND a different translation, so a caller who forgets to reorder is not
+ # merely off by a sign.
+ # (out) the returned quaternion is fed back through quaternion_to_rotation_matrix and
+ # compared against the hand-computed R_colmap = (I @ diag(1, -1, -1)).T =
+ # diag(1, -1, -1); reading the output as (x, y, z, w) would make it the identity
+ # instead.
+ # Caller obligation this pin CANNOT check, because Apple's types are not importable here:
+ # ARKit's simd_quatf.vector is (ix, iy, iz, r) = xyzw, so a pose read straight from ARKit
+ # must be reordered to wxyz before it is passed in.
+ # Snippet used to generate expected (torch only, executed on cpu):
+ # ARKitQTVecs_to_ColmapQTVecs([1, 0, 0, 0], [1, 2, 3]) -> [0, 1, 0, 0], [-1, 2, 3]
+ # ARKitQTVecs_to_ColmapQTVecs([0, 0, 0, 1], [1, 2, 3]) -> [0, 0, 1, 0], [1, -2, 3]
+ # quaternion_to_rotation_matrix([0, 1, 0, 0]) -> diag(1, -1, -1)
+ _skip_if_dtype_unavailable(device, dtype)
+ identity_wxyz = torch.tensor([[1.0, 0.0, 0.0, 0.0]], device=device, dtype=dtype)
+ identity_xyzw_impostor = torch.tensor([[0.0, 0.0, 0.0, 1.0]], device=device, dtype=dtype)
+ translation = torch.tensor([[[1.0], [2.0], [3.0]]], device=device, dtype=dtype)
+
+ q_colmap, t_colmap = ARKitQTVecs_to_ColmapQTVecs(identity_wxyz, translation)
+ q_impostor, t_impostor = ARKitQTVecs_to_ColmapQTVecs(identity_xyzw_impostor, translation)
+
+ self.assert_close(q_colmap, torch.tensor([[0.0, 1.0, 0.0, 0.0]], device=device, dtype=dtype))
+ self.assert_close(t_colmap, torch.tensor([[[-1.0], [2.0], [3.0]]], device=device, dtype=dtype))
+ self.assert_close(q_impostor, torch.tensor([[0.0, 0.0, 1.0, 0.0]], device=device, dtype=dtype))
+ self.assert_close(t_impostor, torch.tensor([[[1.0], [-2.0], [3.0]]], device=device, dtype=dtype))
+
+ rotation_from_output = kornia.geometry.conversions.quaternion_to_rotation_matrix(q_colmap)
+
+ self.assert_close(
+ rotation_from_output,
+ torch.tensor([[[1.0, 0.0, 0.0], [0.0, -1.0, 0.0], [0.0, 0.0, -1.0]]], device=device, dtype=dtype),
+ )
+
+ def test_convention_worked_literal_matches_the_hand_computation(self, device, dtype):
+ # Convention pin: the docstring's own example, reproduced against a hand computation done
+ # outside kornia (wxyz -> R by the standard formula, right-multiply by diag(1, -1, -1),
+ # transpose, then negate-and-rotate the translation). The rotation is pinned as a matrix
+ # rather than only as a quaternion because the quaternion sign is not part of the contract
+ # (see the trace-zero pin below), and det(R_colmap) = +1 is asserted: the flip negates two
+ # axes, not one, so handedness is PRESERVED despite the graphics/vision framing.
+ # Snippet used to generate expected (stdlib only, q = [0, 1, 0, 1] wxyz, t = (1, 1, 1)):
+ # R_cg = [[0, 0, 1], [0, -1, 0], [1, 0, 0]]
+ # R_colmap = (R_cg @ diag(1, -1, -1)).T = [[0, 0, 1], [0, 1, 0], [-1, 0, 0]]
+ # t_colmap = -R_colmap @ (1, 1, 1) = (-1, -1, 1)
+ # q_colmap = [0.7071067811865476, 0.0, 0.7071067811865475, 0.0]
+ # det(R_colmap) = 1.0
+ _skip_if_dtype_unavailable(device, dtype)
+ qvec = torch.tensor(_ARKIT_WORKED_QVEC, device=device, dtype=dtype)
+ tvec = torch.tensor(_ARKIT_WORKED_TVEC, device=device, dtype=dtype)
+
+ q_colmap, t_colmap = ARKitQTVecs_to_ColmapQTVecs(qvec, tvec)
+ rotation = kornia.geometry.conversions.quaternion_to_rotation_matrix(q_colmap)
+
+ self.assert_close(q_colmap, torch.tensor([[0.70710678, 0.0, 0.70710678, 0.0]], device=device, dtype=dtype))
+ self.assert_close(t_colmap, torch.tensor([[[-1.0], [-1.0], [1.0]]], device=device, dtype=dtype))
+ self.assert_close(
+ rotation,
+ torch.tensor([[[0.0, 0.0, 1.0], [0.0, 1.0, 0.0], [-1.0, 0.0, 0.0]]], device=device, dtype=dtype),
+ )
+ _assert_proper_rotation(rotation)
+
+ def test_convention_output_quaternion_sign_is_not_canonical(self, device, dtype):
+ # Convention pin: compare ROTATIONS, never raw quaternion components. At trace = 0 the
+ # final rotation_matrix_to_quaternion step takes a branch that returns the negative-w half
+ # of the double cover, so a perfectly ordinary input comes back with w < 0. Both halves
+ # encode the same rotation; the sign is an implementation artefact, not information.
+ # Same claim, one function further down the pipeline, as
+ # TestRotationMatrixToQuaternion.test_convention_w_is_not_canonicalised_to_non_negative.
+ # The second, fully asymmetric hand-computed literal of this function lives here: the input
+ # q = [0.5, 0.5, 0.5, 0.5] with t = (1, 2, 3) is exact in every dtype and its R_colmap has
+ # trace 0, so it exercises the branch the docstring example does not.
+ # Snippet used to generate expected (stdlib only, q = [0.5]*4 wxyz, t = (1, 2, 3)):
+ # R_colmap = [[0, 1, 0], [0, 0, -1], [-1, 0, 0]] (trace 0)
+ # t_colmap = -R_colmap @ (1, 2, 3) = (-2, 3, 1)
+ # kornia returns q = [-0.5, -0.5, -0.5, 0.5], i.e. the negative-w representative
+ _skip_if_dtype_unavailable(device, dtype)
+ qvec = torch.tensor([[0.5, 0.5, 0.5, 0.5]], device=device, dtype=dtype)
+ tvec = torch.tensor([[[1.0], [2.0], [3.0]]], device=device, dtype=dtype)
+
+ q_colmap, t_colmap = ARKitQTVecs_to_ColmapQTVecs(qvec, tvec)
+ rotation = kornia.geometry.conversions.quaternion_to_rotation_matrix(q_colmap)
+
+ self.assert_close(
+ rotation,
+ torch.tensor([[[0.0, 1.0, 0.0], [0.0, 0.0, -1.0], [-1.0, 0.0, 0.0]]], device=device, dtype=dtype),
+ )
+ self.assert_close(t_colmap, torch.tensor([[[-2.0], [3.0], [1.0]]], device=device, dtype=dtype))
+ # The [-0.5, ...] literal itself carries the sign claim -- w within tolerance of -0.5 is
+ # necessarily negative, so a separate sign assert could never fail on its own. The point
+ # stands: the sign is an artefact either way; compare rotations, never raw components.
+ self.assert_close(q_colmap, torch.tensor([[-0.5, -0.5, -0.5, 0.5]], device=device, dtype=dtype))
+
+ def test_convention_input_quaternion_is_normalized_and_double_covered(self, device, dtype):
+ # Convention pin: the input quaternion does not have to be unit -- the pipeline normalizes
+ # it -- and q and -q describe the same rotation, so both give the same pose. Two legs
+ # because they are independent: scaling exercises the normalizer, negating exercises the
+ # double cover. What this pin does NOT decide is the zero quaternion, which is absorbed by
+ # the normalizer's eps guard and silently produces a plausible pose (documented, not pinned:
+ # the intended answer there is a maintainer decision, tracked in kornia#3952 -- this is the
+ # downstream reach of that issue's sub-eps clamp).
+ # Snippet used to generate expected (torch only, executed on cpu float32):
+ # ARKitQTVecs_to_ColmapQTVecs(q * 1000, t) == ARKitQTVecs_to_ColmapQTVecs(q, t) (0.0 diff)
+ # ARKitQTVecs_to_ColmapQTVecs(-q, t) == ARKitQTVecs_to_ColmapQTVecs(q, t) (0.0 diff)
+ _skip_if_dtype_unavailable(device, dtype)
+ qvec = torch.tensor(_ARKIT_WORKED_QVEC, device=device, dtype=dtype)
+ tvec = torch.tensor(_ARKIT_WORKED_TVEC, device=device, dtype=dtype)
+
+ q_reference, t_reference = ARKitQTVecs_to_ColmapQTVecs(qvec, tvec)
+ q_scaled, t_scaled = ARKitQTVecs_to_ColmapQTVecs(qvec * 1000.0, tvec)
+ q_negated, t_negated = ARKitQTVecs_to_ColmapQTVecs(-qvec, tvec)
+
+ self.assert_close(q_scaled, q_reference)
+ self.assert_close(t_scaled, t_reference)
+ self.assert_close(q_negated, q_reference)
+ self.assert_close(t_negated, t_reference)
+
+ def test_wart_zero_quaternion_is_absorbed_or_nans_by_dtype_3952(self, device, dtype):
+ # Wart pin for the downstream reach of kornia#3952 into this function, companion to its
+ # zero-quaternion warning: the all-zero input is not rejected, and what it produces instead
+ # SPLITS BY DTYPE, which is the half the warning got wrong before this pin existed.
+ # float64/float32/bfloat16: normalize_quaternion's β€–qβ€– < eps clamp absorbs the zero, the
+ # internal rotation comes back as the identity, and the call returns exactly what the
+ # IDENTITY quaternion returns -- a plausible pose, silently, for an input that is not a
+ # rotation at all.
+ # float16: the default eps = 1e-12 underflows to 0 there (bfloat16's wider exponent keeps
+ # it: 1.0018652574217413e-12), so the clamp is a no-op, the normalisation divides 0 by 0
+ # and the whole pose is NaN. Same underflow class as kornia#3966.
+ # The first two legs assert against the IDENTITY input's own output rather than against a
+ # literal, so the claim the docstring makes -- "the same answer as the identity input" --
+ # is what runs, at every dtype and on every backend, with no constant to re-measure per
+ # build. The third leg pins the one value the warning quotes outright, t = (-1, 1, 1),
+ # which is exact in every dtype here; without it the first two would still pass if BOTH
+ # routes moved together.
+ # If the non-float16 leg fails, #3952 was (partly) fixed, or this function grew a guard --
+ # check which. If the float16 leg fails, the eps reaching normalize_quaternion is no longer
+ # underflowing, which is the #3966 half. NOT a contract that either is correct.
+ # Snippet used to generate expected (torch only, executed on cpu):
+ # ARKitQTVecs_to_ColmapQTVecs(torch.zeros(1, 4), torch.ones(1, 3, 1))
+ # -> q [0., 1., 0., 0.], t [-1., 1., 1.] (float64 q_x: 1.0000000012499999)
+ # the same call at float16 -> q [nan] * 4, t [nan] * 3
+ _skip_if_dtype_unavailable(device, dtype)
+ zeros = torch.zeros(1, 4, device=device, dtype=dtype)
+ identity = torch.tensor([[1.0, 0.0, 0.0, 0.0]], device=device, dtype=dtype)
+ tvec = torch.tensor(_ARKIT_WORKED_TVEC, device=device, dtype=dtype)
+
+ q_zero, t_zero = ARKitQTVecs_to_ColmapQTVecs(zeros, tvec)
+
+ if dtype == torch.float16:
+ assert torch.isnan(q_zero).all() and torch.isnan(t_zero).all(), _issue_msg(
+ "kornia#3952/#3966: the float16 zero quaternion no longer underflows to an all-NaN pose"
+ )
+ return
+
+ q_identity, t_identity = ARKitQTVecs_to_ColmapQTVecs(identity, tvec)
+
+ assert_close(
+ q_zero,
+ q_identity,
+ atol=0.0,
+ rtol=0.0,
+ msg=_issue_msg("kornia#3952: the zero quaternion no longer gives the identity input's rotation"),
+ )
+ assert_close(
+ t_zero,
+ t_identity,
+ atol=0.0,
+ rtol=0.0,
+ msg=_issue_msg("kornia#3952: the zero quaternion no longer gives the identity input's translation"),
+ )
+ assert_close(
+ t_zero,
+ torch.tensor([[[-1.0], [1.0], [1.0]]], device=device, dtype=dtype),
+ atol=0.0,
+ rtol=0.0,
+ msg=_issue_msg("kornia#3952: the absorbed zero quaternion no longer produces the documented pose"),
+ )
+
+ def test_convention_input_is_camtoworld_graphics_and_output_is_worldtocam_vision(self, device, dtype):
+ # Convention pin: the frames, which the docstring never states -- it calls the output "the
+ # camera-to-world transformation, expected by Colmap", and the output is world-to-camera.
+ # Executed as an equality against the composition of the two conversions this function is
+ # built from, each of them pinned separately in this file: the input is a CAMTOWORLD pose in
+ # the GRAPHICS frame (y up, -z forward), and the output is a WORLDTOCAM pose in the VISION
+ # frame (y down, +z forward), i.e. Colmap's images.txt convention.
+ # The two-step reference is written out here rather than compared against a single literal
+ # so that the pin names the frames it is asserting; the literals themselves are pinned by
+ # test_convention_worked_literal_matches_the_hand_computation.
+ _skip_if_dtype_unavailable(device, dtype)
+ qvec = torch.tensor(_ARKIT_WORKED_QVEC, device=device, dtype=dtype)
+ tvec = torch.tensor(_ARKIT_WORKED_TVEC, device=device, dtype=dtype)
+
+ q_colmap, t_colmap = ARKitQTVecs_to_ColmapQTVecs(qvec, tvec)
+
+ camtoworld_graphics_R = kornia.geometry.conversions.quaternion_to_rotation_matrix(qvec)
+ camtoworld_vision_R, camtoworld_vision_t = camtoworld_graphics_to_vision_Rt(camtoworld_graphics_R, tvec)
+ worldtocam_vision_R, worldtocam_vision_t = camtoworld_to_worldtocam_Rt(camtoworld_vision_R, camtoworld_vision_t)
+
+ self.assert_close(
+ kornia.geometry.conversions.quaternion_to_rotation_matrix(q_colmap),
+ worldtocam_vision_R,
+ atol=1e-5,
+ rtol=0.0,
+ )
+ self.assert_close(t_colmap, worldtocam_vision_t, atol=0.0, rtol=0.0)
+
+ def test_convention_output_shapes_and_per_sample_batching(self, device, dtype):
+ # Convention pin: the outputs are q (B, 4) and t (B, 3, 1) -- the translation keeps its
+ # trailing singleton axis, guaranteed by an explicit reshape -- and the conversion is
+ # per-sample: element 1 of a batched call equals the single-element call, bitwise. The
+ # two shape asserts are dtype-invariant, but the bitwise per-sample comparison runs the
+ # whole quaternion pipeline on a batched and an unbatched path, so the dtype fixture
+ # stays: each dtype's arithmetic could break the equality on its own.
+ _skip_if_dtype_unavailable(device, dtype)
+ batch_q = torch.tensor([[0.0, 1.0, 0.0, 1.0], [0.5, 0.5, 0.5, 0.5]], device=device, dtype=dtype)
+ batch_t = torch.tensor([[[1.0], [1.0], [1.0]], [[1.0], [2.0], [3.0]]], device=device, dtype=dtype)
+
+ q_colmap, t_colmap = ARKitQTVecs_to_ColmapQTVecs(batch_q, batch_t)
+ single_q, single_t = ARKitQTVecs_to_ColmapQTVecs(batch_q[1:], batch_t[1:])
+
+ assert q_colmap.shape == (2, 4)
+ assert t_colmap.shape == (2, 3, 1)
+ self.assert_close(q_colmap[1:], single_q, atol=0.0, rtol=0.0)
+ self.assert_close(t_colmap[1:], single_t, atol=0.0, rtol=0.0)
+
+ def test_convention_shapes_are_strictly_batched(self, device):
+ # Convention pin: the inputs are strictly qvec (B, 4) and tvec (B, 3, 1) -- an unbatched
+ # (4,) quaternion is rejected, and so is a flat (B, 3) translation. The two rejections come
+ # from different guards, which the pin keeps visible: both ShapeErrors are raised by
+ # camtoworld_graphics_to_vision_Rt's OWN KORNIA_CHECK_SHAPE guards (traceback-verified:
+ # ARKitQTVecs_to_ColmapQTVecs -> camtoworld_graphics_to_vision_Rt -> KORNIA_CHECK_SHAPE;
+ # Rt_to_matrix4x4 is never reached -- its guards do not back these rejections and cannot be
+ # deduplicated on the strength of this pin), while a (B, 3) quaternion is caught even
+ # earlier by quaternion_to_rotation_matrix's own "(*, 4)" ValueError.
+ # float32 is hardcoded and the dtype fixture dropped because these guards run before any
+ # arithmetic and cannot depend on the dtype.
+ # Snippet used to generate expected (torch only, executed on cpu float32):
+ # ARKitQTVecs_to_ColmapQTVecs(torch.zeros(4), torch.ones(1, 3, 1)) -> ShapeError
+ # ARKitQTVecs_to_ColmapQTVecs(torch.zeros(1, 4), torch.ones(1, 3)) -> ShapeError
+ # ARKitQTVecs_to_ColmapQTVecs(torch.zeros(1, 3), torch.ones(1, 3, 1))
+ # -> ValueError: Input must be a tensor of shape (*, 4). Got torch.Size([1, 3])
+ quaternion = torch.tensor([[1.0, 0.0, 0.0, 0.0]], device=device, dtype=torch.float32)
+ translation = torch.ones(1, 3, 1, device=device, dtype=torch.float32)
+
+ with pytest.raises(ShapeError):
+ ARKitQTVecs_to_ColmapQTVecs(quaternion[0], translation)
+ with pytest.raises(ShapeError):
+ ARKitQTVecs_to_ColmapQTVecs(quaternion, translation[..., 0])
+ with pytest.raises(ValueError, match=r"shape \(\*, 4\)"):
+ ARKitQTVecs_to_ColmapQTVecs(quaternion[:, :3], translation)
+
+ def test_wart_float64_output_quaternion_is_not_unit_3951(self, device):
+ # Wart pin for the downstream reach of kornia#3951: this function ends its pipeline with
+ # rotation_matrix_to_quaternion, whose eps is added INSIDE the sqrt, so a float64 ARKit call
+ # returns a quaternion that is not unit -- a Colmap consumer that validates QW QX QY QZ sees
+ # it. The root cause is pinned in TestRotationMatrixToQuaternion
+ # (test_convention_returns_a_unit_quaternion_3951 and its companion wart); this cell pins
+ # only that the defect reaches the public ARKit entry point, so it flips together with them.
+ # The [0, 1, 0, 0] shape of the output is CORRECT, not a component shift: for an identity
+ # input the composed map is (I @ diag(1, -1, -1)).T = diag(1, -1, -1), a 180-degree turn
+ # about x. The defect is the magnitude alone.
+ # If this fails, #3951 was fixed -- remove this pin together with the two in
+ # TestRotationMatrixToQuaternion. NOT a contract that the output must stay non-unit.
+ # float64 is hardcoded and the dtype fixture dropped because a 1.25e-09 inflation is
+ # invisible at float32 and below (the same reason the root-cause pins hardcode it), and the
+ # skip is visible so MPS, which has no float64, reports a skip rather than a TypeError.
+ # atol 1e-11 sits two orders below the inflation and five above the float64 ulp of 1.0.
+ # Snippet used to generate expected (torch only, executed on cpu float64):
+ # ARKitQTVecs_to_ColmapQTVecs(tensor([[1., 0., 0., 0.]], float64), ones(1, 3, 1, float64))
+ # -> q = [0.0, 1.0000000012499999, 0.0, 0.0], ||q|| - 1 = 1.2499998813808588e-09
+ _skip_if_dtype_unavailable(device, torch.float64)
+
+ qvec = torch.tensor([[1.0, 0.0, 0.0, 0.0]], device=device, dtype=torch.float64)
+ tvec = torch.ones(1, 3, 1, device=device, dtype=torch.float64)
+
+ q_colmap, _ = ARKitQTVecs_to_ColmapQTVecs(qvec, tvec)
+
+ assert_close(
+ q_colmap,
+ torch.tensor([[0.0, 1.0000000012499999, 0.0, 0.0]], device=device, dtype=torch.float64),
+ atol=1e-11,
+ rtol=0.0,
+ msg=_issue_msg("kornia#3951: the float64 ARKit output quaternion is no longer inflated"),
+ )
+ # No separate ||q|| != 1 assert: the literal above pins ||q|| - 1 = 1.25e-09 at atol=1e-11,
+ # which already implies non-unit by two orders -- a second, weaker assert could never fail
+ # while the pin holds.
+
class TestEulerFromQuaternion(BaseTester):
def test_smoke(self, device, dtype):
@@ -4066,12 +6658,11 @@ class TestAxisAngleToRotationMatrix:
# so that the filter mutation they provoke cannot leak into the rest of the suite: this bug is
# contagious across tests, and an unisolated pin would silently disarm every other test's warning
# discipline.
-_DEPRECATED_ALIASES = [
- ("angle_axis_to_rotation_matrix", [[0.0, 0.0, 0.6]]),
- ("rotation_matrix_to_angle_axis", [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]),
- ("quaternion_to_angle_axis", [1.0, 0.0, 0.0, 0.0]),
- ("angle_axis_to_quaternion", [0.1, 0.2, 0.3]),
-]
+# 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.
@pytest.mark.xfail(
@@ -4080,7 +6671,7 @@ _DEPRECATED_ALIASES = [
"-W error::DeprecationWarning cannot escalate it β€” kornia#3956",
strict=True,
)
[email protected](("alias_name", "arg"), _DEPRECATED_ALIASES, ids=[name for name, _ in _DEPRECATED_ALIASES])
[email protected](("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):
# Intended behavior: a DeprecationWarning emitted by kornia obeys the caller's warning filters,
# so a project that runs under -W error::DeprecationWarning (or pytest's filterwarnings =
@@ -4112,7 +6703,7 @@ def test_convention_deprecated_alias_warning_can_be_escalated_to_an_error_3956(a
assert escalated, f"kornia#3956: {alias_name} did not raise under simplefilter('error', DeprecationWarning)"
[email protected](("alias_name", "arg"), _DEPRECATED_ALIASES, ids=[name for name, _ in _DEPRECATED_ALIASES])
[email protected](("alias_name", "arg"), _DEPRECATED_ALIAS_NAMES_AND_ARGS, ids=_DEPRECATED_ALIAS_IDS)
def test_wart_deprecated_alias_rewrites_the_global_warning_filters_3956(alias_name, arg):
# Wart pin for kornia#3956, companion to the strict xfail above: assert that a single alias
# call CURRENTLY leaves two entries of its own at the head of the process-global filter list,
@@ -4126,7 +6717,7 @@ def test_wart_deprecated_alias_rewrites_the_global_warning_filters_3956(alias_na
# Snippet used to generate expected (stdlib + torch, executed on cpu):
# with warnings.catch_warnings():
# warnings.resetwarnings()
- # kornia.geometry.conversions.angle_axis_to_quaternion(torch.tensor([0., 0., 0.6]))
+ # kornia.geometry.conversions.angle_axis_to_quaternion(torch.tensor([0.1, 0.2, 0.3]))
# warnings.filters[:2]
# -> [('default', None, <class 'DeprecationWarning'>, None, 0),
# ('always', None, <class 'DeprecationWarning'>, None, 0)]
diff --git a/tests/geometry/transform/test_homography_warper.py b/tests/geometry/transform/test_homography_warper.py
index fe9670f59..042edca68 100644
--- a/tests/geometry/transform/test_homography_warper.py
+++ b/tests/geometry/transform/test_homography_warper.py
@@ -126,6 +126,9 @@ class TestHomographyWarper(BaseTester):
@pytest.mark.parametrize("batch_size", [1, 3])
def test_consistency(self, batch_size, device, dtype):
+ # The same high-level normalize/denormalize mutual-inverse invariant is pinned bitwise at
+ # dyadic sizes by TestNormalizeHomography::test_convention_normalize_and_denormalize_round_trip
+ # in tests/geometry/test_conversions.py, on its own literal, sizes and tolerances.
# create input data
height, width = 2, 5
dst_homo_src = torch.eye(3, device=device, dtype=dtype)
@@ -364,12 +367,16 @@ class TestHomographyWarper(BaseTester):
class TestHomographyNormalTransform(BaseTester):
expected_2d_0 = torch.tensor([[[0.5, 0.0, -1.0], [0.0, 2.0, -1.0], [0.0, 0.0, 1.0]]])
+ # kornia#3957: the 2e14 rows below hardcode the size == 1 -> 2 / eps degenerate scale, the same
+ # literal pinned by TestNormalTransformPixel's wart matrix in tests/geometry/test_conversions.py
+ # -- a #3957 fix flips both files together.
expected_2d_1 = torch.tensor([[[0.5, 0.0, -1.0], [0.0, 2e14, -1.0], [0.0, 0.0, 1.0]]])
expected_3d_0 = expected = torch.tensor(
[[[0.4, 0.0, 0.0, -1.0], [0.0, 2.0, 0.0, -1.0], [0.0, 0.0, 0.6667, -1.0], [0.0, 0.0, 0.0, 1.0]]]
)
+ # kornia#3957: same degenerate-scale literal as expected_2d_1 above, 3-D variant.
expected_3d_1 = torch.tensor(
[[[0.4, 0.0, 0.0, -1.0], [0.0, 2e14, 0.0, -1.0], [0.0, 0.0, 0.6667, -1.0], [0.0, 0.0, 0.0, 1.0]]]
)