Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

refactor(core): extract closed-form small-matrix kernels into _small_linalg (#4193)

Dmytro Mishkin0ba2073b4542
diff --git a/kornia/core/_small_linalg.py b/kornia/core/_small_linalg.py
new file mode 100644
index 000000000..2e71f576e
--- /dev/null
+++ b/kornia/core/_small_linalg.py
@@ -0,0 +1,201 @@
+# LICENSE HEADER MANAGED BY add-license-header
+#
+# Copyright 2018 Kornia Team
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+"""Closed-form arithmetic for 2x2, 3x3 and 4x4 matrices.
+
+Private. These are **kernels**, not an API: every one of them is basic arithmetic on a
+fixed-size matrix, with no LAPACK, cuSOLVER or backend ``linalg`` call. That is what makes
+them usable where ``torch.linalg`` is not -- neither ONNX exporter lowers
+``aten::linalg_inv``, the Jetson wheel fails to ``dlopen`` its LAPACK backend, MPS has no
+kernel for several decompositions, and the ``linalg`` family has no half-precision kernel on
+any backend -- on CUDA ``linalg.inv`` gives ``Low precision dtypes not supported. Got Half``
+and ``linalg.det`` gives ``"lu_factor_cusolver" not implemented for 'Half'``.
+
+The contract is deliberately minimal, because the callers own the policy:
+
+- They compute in whatever dtype the caller supplies. **No promotion** -- that belongs to
+ :func:`kornia.core.utils._torch_inverse_cast`.
+- Exact shape and a real floating dtype are **caller preconditions, not runtime checks**.
+ Behavior on anything else is unspecified: ``_adjugate_3x3`` of a 4x4 silently uses the
+ leading 3x3 block, and of a 2x2 raises an incidental ``IndexError``. The contractual size
+ guard lives on the dispatcher :func:`kornia.core.utils._adjugate_closed_form`.
+- Output for a singular input is unspecified. There is no validity or conditioning
+ guarantee; a zero determinant is not a reliable singularity test in floating point.
+- No cross-mode bit-identity promise.
+
+Execution-mode policy (which kernel a caller takes under tracing or export), size dispatch,
+dtype promotion and validation all live in :mod:`kornia.core.utils`. Keeping them there is
+what lets this module import nothing from kornia and stay a leaf.
+"""
+
+from typing import Tuple
+
+import torch
+
+__all__ = [
+ "_adjugate_2x2",
+ "_adjugate_3x3",
+ "_adjugate_4x4",
+ "_inverse_3x3_cross",
+ "_inverse_3x3_scalar",
+]
+
+
+def _adjugate_2x2(input: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
+ """Return the adjugate and determinant of batched 2x2 matrices, in basic arithmetic only."""
+ a = input[..., 0, 0]
+ b = input[..., 0, 1]
+ c = input[..., 1, 0]
+ d = input[..., 1, 1]
+ det = a * d - b * c
+ adj = torch.stack([torch.stack([d, -b], dim=-1), torch.stack([-c, a], dim=-1)], dim=-2)
+ return adj, det
+
+
+def _adjugate_3x3(input: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
+ """Return the adjugate and determinant of batched 3x3 matrices, in basic arithmetic only."""
+ a = input[..., 0, 0]
+ b = input[..., 0, 1]
+ c = input[..., 0, 2]
+ d = input[..., 1, 0]
+ e = input[..., 1, 1]
+ f = input[..., 1, 2]
+ g = input[..., 2, 0]
+ h = input[..., 2, 1]
+ i = input[..., 2, 2]
+
+ # Cofactors (signed minors).
+ c00 = e * i - f * h
+ c01 = -(d * i - f * g)
+ c02 = d * h - e * g
+ c10 = -(b * i - c * h)
+ c11 = a * i - c * g
+ c12 = -(a * h - b * g)
+ c20 = b * f - c * e
+ c21 = -(a * f - c * d)
+ c22 = a * e - b * d
+
+ det = a * c00 + b * c01 + c * c02
+
+ # Adjugate is the transpose of the cofactor matrix.
+ row0 = torch.stack([c00, c10, c20], dim=-1)
+ row1 = torch.stack([c01, c11, c21], dim=-1)
+ row2 = torch.stack([c02, c12, c22], dim=-1)
+ adj = torch.stack([row0, row1, row2], dim=-2)
+
+ return adj, det
+
+
+def _adjugate_4x4(input: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
+ """Return the adjugate and determinant of batched 4x4 matrices, in basic arithmetic only.
+
+ Laplace expansion over the 2x2 minors of the top two rows (``s``) and bottom two rows (``c``),
+ the standard 4x4 cofactor scheme (e.g. MESA ``gluInvertMatrix``).
+ """
+ a = input[..., 0, 0]
+ b = input[..., 0, 1]
+ c = input[..., 0, 2]
+ d = input[..., 0, 3]
+ e = input[..., 1, 0]
+ f = input[..., 1, 1]
+ g = input[..., 1, 2]
+ h = input[..., 1, 3]
+ i = input[..., 2, 0]
+ j = input[..., 2, 1]
+ k = input[..., 2, 2]
+ l_ = input[..., 2, 3]
+ m = input[..., 3, 0]
+ n = input[..., 3, 1]
+ o = input[..., 3, 2]
+ p = input[..., 3, 3]
+
+ s0 = a * f - b * e
+ s1 = a * g - c * e
+ s2 = a * h - d * e
+ s3 = b * g - c * f
+ s4 = b * h - d * f
+ s5 = c * h - d * g
+
+ c5 = k * p - l_ * o
+ c4 = j * p - l_ * n
+ c3 = j * o - k * n
+ c2 = i * p - l_ * m
+ c1 = i * o - k * m
+ c0 = i * n - j * m
+
+ det = s0 * c5 - s1 * c4 + s2 * c3 + s3 * c2 - s4 * c1 + s5 * c0
+
+ row0 = torch.stack(
+ [f * c5 - g * c4 + h * c3, -b * c5 + c * c4 - d * c3, n * s5 - o * s4 + p * s3, -j * s5 + k * s4 - l_ * s3],
+ dim=-1,
+ )
+ row1 = torch.stack(
+ [-e * c5 + g * c2 - h * c1, a * c5 - c * c2 + d * c1, -m * s5 + o * s2 - p * s1, i * s5 - k * s2 + l_ * s1],
+ dim=-1,
+ )
+ row2 = torch.stack(
+ [e * c4 - f * c2 + h * c0, -a * c4 + b * c2 - d * c0, m * s4 - n * s2 + p * s0, -i * s4 + j * s2 - l_ * s0],
+ dim=-1,
+ )
+ row3 = torch.stack(
+ [-e * c3 + f * c1 - g * c0, a * c3 - b * c1 + c * c0, -m * s3 + n * s1 - o * s0, i * s3 - j * s1 + k * s0],
+ dim=-1,
+ )
+ adj = torch.stack([row0, row1, row2, row3], dim=-2)
+
+ return adj, det
+
+
+def _inverse_3x3_cross(input: torch.Tensor) -> torch.Tensor:
+ """Closed-form 3x3 inverse via three fused cross products. The eager path.
+
+ ``inv(M) = adj(M) / det``, and for a 3x3 the adjugate rows are cross products of the
+ columns: with columns ``(a, b, c)``, the inverse rows are ``(b x c, c x a, a x b) / det``,
+ ``det = a . (b x c)``. Three fused ``cross`` ops instead of nine scalar cofactor
+ expressions and four stacks -- far fewer kernel launches, which dominate on small matrices.
+
+ Prefer :func:`_inverse_3x3_scalar` wherever a graph is being captured. The reason is
+ **kernel coverage, not ONNX lowering**: a backend with no ``cross`` kernel for the working
+ dtype makes this raise rather than return -- torch 2.5.1 has no ``bfloat16`` ``cross`` on
+ MPS, while 2.9.1 does.
+
+ ONNX lowering is *not* a reason, measured: ``torch.linalg.cross`` lowers on both torch
+ versions kornia's CI runs -- 2.5.1 (legacy exporter) and 2.9.1 (legacy and dynamo) -- to
+ ``Slice``/``Mul``/``Sub``/``Concat``. What neither exporter lowers on either version is
+ ``aten::linalg_inv``, which is what :func:`kornia.core.utils._torch_inverse_cast` avoids by
+ reaching for a closed form in the first place. torch 2.0-2.4 is untested; CI does not run it
+ either.
+ """
+ col_a = input[..., :, 0]
+ col_b = input[..., :, 1]
+ col_c = input[..., :, 2]
+ row0 = torch.linalg.cross(col_b, col_c, dim=-1)
+ row1 = torch.linalg.cross(col_c, col_a, dim=-1)
+ row2 = torch.linalg.cross(col_a, col_b, dim=-1)
+ det = (col_a * row0).sum(-1)
+ return torch.stack([row0, row1, row2], dim=-2) / det[..., None, None]
+
+
+def _inverse_3x3_scalar(input: torch.Tensor) -> torch.Tensor:
+ """Closed-form 3x3 inverse via the plain scalar adjugate. The trace/export path.
+
+ Lowers to basic arithmetic that every standard ONNX opset supports, and calls no ``cross``.
+ Algebraically identical to :func:`_inverse_3x3_cross`; the two differ only in the order the
+ same products are accumulated, so they agree to rounding rather than bit-for-bit.
+ """
+ adj, det = _adjugate_3x3(input)
+ return adj / det[..., None, None]
diff --git a/kornia/core/utils.py b/kornia/core/utils.py
index 3191085ae..b751a27fe 100644
--- a/kornia/core/utils.py
+++ b/kornia/core/utils.py
@@ -27,6 +27,13 @@ import torch.nn.functional as F
from torch.linalg import inv_ex
from kornia.core._compat import torch_version_ge
+from kornia.core._small_linalg import (
+ _adjugate_2x2,
+ _adjugate_3x3,
+ _adjugate_4x4,
+ _inverse_3x3_cross,
+ _inverse_3x3_scalar,
+)
from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_TYPE
from kornia.core.exceptions import DeviceError
@@ -163,13 +170,16 @@ def _l2_normalize(input: torch.Tensor, dim: int = 1) -> torch.Tensor:
def _inverse_3x3_closed_form(input: torch.Tensor) -> torch.Tensor:
- """Closed-form inverse for batched 3x3 matrices.
+ """Closed-form inverse for batched 3x3 matrices, dispatching on the execution mode.
Used as an ONNX-traceable fallback to ``torch.linalg.inv``: the legacy ONNX
exporter does not lower ``aten::linalg_inv`` (as of opset 17). Computed via
the adjugate / determinant formula, which is composed entirely of basic
arithmetic ops that all standard ONNX opsets support.
+ The arithmetic lives in :mod:`kornia.core._small_linalg`; this function owns only the
+ choice between the two kernels, which is execution-mode policy and therefore stays here.
+
Args:
input: Tensor of shape ``(..., 3, 3)``.
@@ -180,23 +190,18 @@ def _inverse_3x3_closed_form(input: torch.Tensor) -> torch.Tensor:
(no explicit check, same as ``torch.linalg.inv`` itself).
"""
if not _is_tracing_or_exporting():
- # inv(M) = adj(M) / det, and for a 3x3 the adjugate rows are cross products of the
- # columns: with columns (a, b, c), the inverse rows are (b x c, c x a, a x b) / det,
- # det = a . (b x c). Three fused ``cross`` ops instead of nine scalar cofactor
- # expressions and four stacks β€” far fewer kernel launches (dominant on small matrices).
- col_a = input[..., :, 0]
- col_b = input[..., :, 1]
- col_c = input[..., :, 2]
- row0 = torch.linalg.cross(col_b, col_c, dim=-1)
- row1 = torch.linalg.cross(col_c, col_a, dim=-1)
- row2 = torch.linalg.cross(col_a, col_b, dim=-1)
- det = (col_a * row0).sum(-1)
- return torch.stack([row0, row1, row2], dim=-2) / det[..., None, None]
+ # Eager: three fused ``cross`` ops beat nine scalar cofactor expressions and four
+ # stacks, because kernel launches dominate on matrices this small.
+ return _inverse_3x3_cross(input)
# Under tracing/export (legacy ONNX / jit.trace / dynamo ONNX) stick to the plain scalar
- # adjugate: it lowers to basic arithmetic that every opset supports, whereas ``cross`` may not.
- adj, det = _adjugate_3x3(input)
- return adj / det[..., None, None]
+ # adjugate. NOTE the original rationale here -- "whereas ``cross`` may not [lower]" -- does not
+ # hold on the torch versions CI runs: measured, ``torch.linalg.cross`` lowers on 2.5.1 (legacy
+ # exporter) and on 2.9.1 (both exporters). The split is kept because it is still the safer
+ # capture path (scalar arithmetic needs no per-dtype kernel at all, and ``cross`` has real
+ # kernel gaps -- no bfloat16 on MPS in torch 2.5.1), not because ``cross`` fails to export.
+ # Collapsing the two branches is a behavior change and belongs in its own PR.
+ return _inverse_3x3_scalar(input)
def _is_tracing_or_exporting() -> bool:
@@ -210,111 +215,6 @@ def _is_tracing_or_exporting() -> bool:
return torch.jit.is_tracing() or is_exporting()
-def _adjugate_2x2(input: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
- """Return the adjugate and determinant of batched 2x2 matrices, in basic arithmetic only."""
- a = input[..., 0, 0]
- b = input[..., 0, 1]
- c = input[..., 1, 0]
- d = input[..., 1, 1]
- det = a * d - b * c
- adj = torch.stack([torch.stack([d, -b], dim=-1), torch.stack([-c, a], dim=-1)], dim=-2)
- return adj, det
-
-
-def _adjugate_3x3(input: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
- """Return the adjugate and determinant of batched 3x3 matrices, in basic arithmetic only."""
- a = input[..., 0, 0]
- b = input[..., 0, 1]
- c = input[..., 0, 2]
- d = input[..., 1, 0]
- e = input[..., 1, 1]
- f = input[..., 1, 2]
- g = input[..., 2, 0]
- h = input[..., 2, 1]
- i = input[..., 2, 2]
-
- # Cofactors (signed minors).
- c00 = e * i - f * h
- c01 = -(d * i - f * g)
- c02 = d * h - e * g
- c10 = -(b * i - c * h)
- c11 = a * i - c * g
- c12 = -(a * h - b * g)
- c20 = b * f - c * e
- c21 = -(a * f - c * d)
- c22 = a * e - b * d
-
- det = a * c00 + b * c01 + c * c02
-
- # Adjugate is the transpose of the cofactor matrix.
- row0 = torch.stack([c00, c10, c20], dim=-1)
- row1 = torch.stack([c01, c11, c21], dim=-1)
- row2 = torch.stack([c02, c12, c22], dim=-1)
- adj = torch.stack([row0, row1, row2], dim=-2)
-
- return adj, det
-
-
-def _adjugate_4x4(input: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
- """Return the adjugate and determinant of batched 4x4 matrices, in basic arithmetic only.
-
- Laplace expansion over the 2x2 minors of the top two rows (``s``) and bottom two rows (``c``),
- the standard 4x4 cofactor scheme (e.g. MESA ``gluInvertMatrix``).
- """
- a = input[..., 0, 0]
- b = input[..., 0, 1]
- c = input[..., 0, 2]
- d = input[..., 0, 3]
- e = input[..., 1, 0]
- f = input[..., 1, 1]
- g = input[..., 1, 2]
- h = input[..., 1, 3]
- i = input[..., 2, 0]
- j = input[..., 2, 1]
- k = input[..., 2, 2]
- l_ = input[..., 2, 3]
- m = input[..., 3, 0]
- n = input[..., 3, 1]
- o = input[..., 3, 2]
- p = input[..., 3, 3]
-
- s0 = a * f - b * e
- s1 = a * g - c * e
- s2 = a * h - d * e
- s3 = b * g - c * f
- s4 = b * h - d * f
- s5 = c * h - d * g
-
- c5 = k * p - l_ * o
- c4 = j * p - l_ * n
- c3 = j * o - k * n
- c2 = i * p - l_ * m
- c1 = i * o - k * m
- c0 = i * n - j * m
-
- det = s0 * c5 - s1 * c4 + s2 * c3 + s3 * c2 - s4 * c1 + s5 * c0
-
- row0 = torch.stack(
- [f * c5 - g * c4 + h * c3, -b * c5 + c * c4 - d * c3, n * s5 - o * s4 + p * s3, -j * s5 + k * s4 - l_ * s3],
- dim=-1,
- )
- row1 = torch.stack(
- [-e * c5 + g * c2 - h * c1, a * c5 - c * c2 + d * c1, -m * s5 + o * s2 - p * s1, i * s5 - k * s2 + l_ * s1],
- dim=-1,
- )
- row2 = torch.stack(
- [e * c4 - f * c2 + h * c0, -a * c4 + b * c2 - d * c0, m * s4 - n * s2 + p * s0, -i * s4 + j * s2 - l_ * s0],
- dim=-1,
- )
- row3 = torch.stack(
- [-e * c3 + f * c1 - g * c0, a * c3 - b * c1 + c * c0, -m * s3 + n * s1 - o * s0, i * s3 - j * s1 + k * s0],
- dim=-1,
- )
- adj = torch.stack([row0, row1, row2, row3], dim=-2)
-
- return adj, det
-
-
def _adjugate_closed_form(input: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
"""Adjugate and determinant of batched square matrices up to 4x4 in basic arithmetic only.
diff --git a/tests/core/test_small_linalg.py b/tests/core/test_small_linalg.py
new file mode 100644
index 000000000..3f74f0e64
--- /dev/null
+++ b/tests/core/test_small_linalg.py
@@ -0,0 +1,311 @@
+# LICENSE HEADER MANAGED BY add-license-header
+#
+# Copyright 2018 Kornia Team
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+"""Tests for the closed-form small-matrix kernels in ``kornia.core._small_linalg``.
+
+These are **raw kernels**: exact shape and a real floating dtype are caller preconditions,
+not runtime checks, and behavior on anything else is unspecified. So nothing here asserts
+that a kernel rejects an integer or complex tensor, and nothing pins what
+``_adjugate_3x3`` does when handed a 4x4 (it silently uses the leading 3x3 block) or a 2x2
+(it raises an incidental ``IndexError``). Those are recorded as known warts in the design
+note, deliberately not as behavior. The size guard that *is* contractual belongs to the
+dispatcher ``_adjugate_closed_form`` and is tested in ``test_helpers.py``.
+"""
+
+import io
+import re
+
+import pytest
+import torch
+
+from kornia.core._compat import torch_version_ge, torch_version_lt
+from kornia.core._small_linalg import (
+ _adjugate_2x2,
+ _adjugate_3x3,
+ _adjugate_4x4,
+ _inverse_3x3_cross,
+ _inverse_3x3_scalar,
+)
+
+from testing.base import BaseTester
+
+ADJUGATE = {2: _adjugate_2x2, 3: _adjugate_3x3, 4: _adjugate_4x4}
+
+# Op-type substrings that mean a linalg decomposition reached the graph. The point of these
+# kernels is that an exported graph is basic arithmetic and nothing else, so this is what a
+# regression would look like.
+#
+# Note what does the real work in the ONNX tests below: a MISSING lowering raises rather than
+# emitting a node -- measured on torch 2.9.1, ``torch.linalg.inv`` gives
+# ``UnsupportedOperatorError`` from the legacy exporter and ``ConversionError`` from the dynamo
+# one -- so the export call succeeding is itself the gate. This check covers the other case: a
+# future decomposition that exports *successfully* through something heavier than arithmetic.
+# Matched as a substring rather than a prefix, because the dynamo exporter names a fallback node
+# ``aten_linalg_inv``, which a ``startswith("linalg")`` test would miss.
+# Long markers are unambiguous as bare substrings. The short ones are anchored to a name
+# boundary, or they swallow basic arithmetic: "qr" matches ``Sqrt`` and "lu" matches the whole
+# ``Relu``/``Selu``/``Elu``/``Celu``/``PRelu``/``LeakyRelu``/``ThresholdedRelu`` family -- all of
+# them exactly the category this check exists to allow.
+_LINALG_OP_RE = re.compile(
+ r"(?:linalg|inverse|matmul|gemm|einsum)|(?:^|_)(?:det|lu|svd|qr|cholesky|eig)(?:$|_)", re.IGNORECASE
+)
+
+
+def _assert_basic_arithmetic_only(ops):
+ offenders = sorted(op for op in ops if _LINALG_OP_RE.search(op))
+ assert not offenders, f"linalg-shaped ops in the exported graph: {offenders} (full set: {sorted(ops)})"
+
+
+def _export_kwargs(use_dynamo_exporter: bool) -> dict:
+ """Export kwargs that are valid on every torch kornia declares support for.
+
+ ``dynamo=`` does not exist before torch 2.4 -- measured: ``TypeError: export() got an
+ unexpected keyword argument 'dynamo'`` on 2.0.1 and 2.2.2, present in 2.4.1. Passing it
+ unconditionally would be a ``TypeError`` on an older pin rather than a skip. Gated at 2.5
+ to match ``tests/filters/test_gaussian.py::test_onnx_export_legacy``, which is conservative
+ by one release and costs nothing.
+ """
+ kwargs = {"opset_version": 18}
+ if torch_version_ge(2, 5, 0):
+ kwargs["dynamo"] = use_dynamo_exporter
+ return kwargs
+
+
+def _require_exporter(use_dynamo_exporter: bool) -> None:
+ """Skip unless this build can actually run the requested ONNX exporter.
+
+ ``dynamo=`` first exists in torch 2.5, but there it still routes through the experimental
+ ``_compat.export_compat`` shim and needs ``onnxscript`` -- which the 2.5.1 CI legs do not
+ install, so an unguarded call is a hard failure rather than a skip there. Same reasoning and
+ same guard as ``tests/filters/test_gaussian.py::test_onnx_export_modern``.
+ """
+ pytest.importorskip("onnx")
+ if use_dynamo_exporter:
+ if torch_version_lt(2, 6, 0):
+ pytest.skip("the dynamo ONNX exporter is only non-experimental from PyTorch 2.6")
+ pytest.importorskip("onnxscript")
+
+
+def _well_conditioned(n, device, dtype, batch=()):
+ """A deterministic, well-conditioned matrix family.
+
+ Built without touching the global RNG: a seeded ``torch.rand`` would still mutate it, and
+ a fresh draw per run turns a tolerance assertion into a coin flip.
+
+ Each batch entry gets a distinct scale. A bare ``expand`` would make every slice identical,
+ and then a kernel that broadcast element 0 across the batch -- an indexing slip in the
+ trailing-dim arithmetic -- would pass the batched cases. Scaling leaves the condition number
+ untouched, so the tolerance argument above still holds.
+ """
+ ramp = torch.arange(1, n * n + 1, device=device, dtype=dtype).reshape(n, n) * 0.1
+ x = (torch.eye(n, device=device, dtype=dtype) + ramp).expand(*batch, n, n).clone()
+ if batch:
+ idx = torch.arange(x.numel() // (n * n), device=device, dtype=dtype).reshape(*batch, 1, 1)
+ x = x * (1 + idx * 0.05)
+ return x
+
+
+class TestAdjugateKernels(BaseTester):
+ @pytest.mark.parametrize("n", [2, 3, 4])
+ def test_smoke(self, device, dtype, n):
+ adj, det = ADJUGATE[n](_well_conditioned(n, device, dtype))
+ assert adj.shape == (n, n)
+ assert det.shape == ()
+
+ @pytest.mark.parametrize("n", [2, 3, 4])
+ @pytest.mark.parametrize("batch", [(), (2,), (2, 3)])
+ def test_cardinality(self, device, dtype, n, batch):
+ adj, det = ADJUGATE[n](_well_conditioned(n, device, dtype, batch))
+ assert adj.shape == (*batch, n, n)
+ assert det.shape == batch
+
+ @pytest.mark.parametrize("n", [2, 3, 4])
+ def test_matches_linalg_inv_on_well_conditioned_input(self, device, dtype, n):
+ # A smoke-test invariant on a controlled family, evaluated in a stated dtype -- not an
+ # accuracy oracle. linalg.inv has no half kernel, so the reference is computed in
+ # float32 and compared back.
+ x = _well_conditioned(n, device, dtype, (2,))
+ ref_dtype = torch.float32 if dtype in (torch.float16, torch.bfloat16) else dtype
+ adj, det = ADJUGATE[n](x)
+ tol = 1e-2 if dtype in (torch.float16, torch.bfloat16) else 1e-4
+ self.assert_close(
+ adj / det[..., None, None],
+ torch.linalg.inv(x.to(ref_dtype)).to(dtype),
+ atol=tol,
+ rtol=tol,
+ )
+ self.assert_close(det, torch.linalg.det(x.to(ref_dtype)).to(dtype), atol=tol, rtol=tol)
+
+ @pytest.mark.parametrize("n", [2, 3, 4])
+ def test_adjugate_identity_is_exact_on_integral_float64(self, device, n):
+ # A @ adj(A) == det(A) * I holds identically. Small integers held in float64 make every
+ # intermediate exactly representable, so this is an equality, not a tolerance -- and it
+ # is the only check here that exercises the float64 path against something other than a
+ # same-precision torch.linalg call, which would be no reference at all.
+ if device.type == "mps":
+ pytest.skip("MPS has no float64")
+ values = torch.arange(1, n * n + 1, device=device, dtype=torch.float64).reshape(n, n)
+ x = values + torch.eye(n, device=device, dtype=torch.float64) * (n * n)
+ adj, det = ADJUGATE[n](x)
+ expected = det * torch.eye(n, device=device, dtype=torch.float64)
+ assert torch.equal(x @ adj, expected)
+
+ @pytest.mark.parametrize("n", [2, 3, 4])
+ def test_gradcheck(self, device, n):
+ x = _well_conditioned(n, device, torch.float64)
+ self.gradcheck(lambda t: ADJUGATE[n](t)[0], (x,))
+ self.gradcheck(lambda t: ADJUGATE[n](t)[1], (x,))
+
+ @pytest.mark.parametrize("n", [2, 3, 4])
+ def test_dynamo(self, device, dtype, n, torch_optimizer):
+ x = _well_conditioned(n, device, dtype, (2,))
+ op = ADJUGATE[n]
+ op_optimized = torch_optimizer(op)
+ expected_adj, expected_det = op(x)
+ actual_adj, actual_det = op_optimized(x)
+ self.assert_close(actual_adj, expected_adj)
+ self.assert_close(actual_det, expected_det)
+
+ @pytest.mark.parametrize("n", [2, 3, 4])
+ def test_scripts(self, device, dtype, n):
+ x = _well_conditioned(n, device, dtype, (2,))
+ scripted = torch.jit.script(ADJUGATE[n])
+ expected_adj, expected_det = ADJUGATE[n](x)
+ actual_adj, actual_det = scripted(x)
+ self.assert_close(actual_adj, expected_adj)
+ self.assert_close(actual_det, expected_det)
+
+ @pytest.mark.device_agnostic
+ @pytest.mark.filterwarnings("ignore::DeprecationWarning")
+ @pytest.mark.parametrize("use_dynamo_exporter", [False, True], ids=["torchscript", "torchexport"])
+ @pytest.mark.parametrize("n", [2, 3, 4])
+ def test_onnx_export_uses_basic_arithmetic(self, device, n, use_dynamo_exporter):
+ # Capability matrix: the scalar kernels are the ONNX-safe path, and that is the whole
+ # reason they exist. Assert the graph carries no linalg decomposition, on both exporters.
+ _require_exporter(use_dynamo_exporter)
+ onnx = pytest.importorskip("onnx")
+ x = _well_conditioned(n, device, torch.float32, (2,))
+ buffer = io.BytesIO()
+ torch.onnx.export(_AdjugateModule(n), (x,), buffer, **_export_kwargs(use_dynamo_exporter))
+ ops = {node.op_type for node in onnx.load_from_string(buffer.getvalue()).graph.node}
+ _assert_basic_arithmetic_only(ops)
+
+
+class _AdjugateModule(torch.nn.Module):
+ """Wrapper so the kernels can be handed to ``torch.onnx.export``."""
+
+ def __init__(self, n: int) -> None:
+ super().__init__()
+ self.n = n
+
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
+ adj, det = ADJUGATE[self.n](x)
+ return adj / det[..., None, None]
+
+
+class TestInverse3x3Kernels(BaseTester):
+ def test_smoke(self, device, dtype):
+ x = _well_conditioned(3, device, dtype)
+ assert _inverse_3x3_cross(x).shape == (3, 3)
+ assert _inverse_3x3_scalar(x).shape == (3, 3)
+
+ @pytest.mark.parametrize("batch", [(), (2,), (2, 3)])
+ def test_cardinality(self, device, dtype, batch):
+ x = _well_conditioned(3, device, dtype, batch)
+ assert _inverse_3x3_cross(x).shape == (*batch, 3, 3)
+ assert _inverse_3x3_scalar(x).shape == (*batch, 3, 3)
+
+ def test_cross_and_scalar_kernels_agree(self, device, dtype):
+ # The mode split exists so that export avoids ``aten::linalg_inv``, not so that the two
+ # paths compute different answers. They are different orderings of the same algebra, so
+ # they agree to rounding rather than bit-for-bit.
+ x = _well_conditioned(3, device, dtype, (2,))
+ tol = 1e-2 if dtype in (torch.float16, torch.bfloat16) else 1e-4
+ self.assert_close(_inverse_3x3_cross(x), _inverse_3x3_scalar(x), atol=tol, rtol=tol)
+
+ @pytest.mark.parametrize("kernel", [_inverse_3x3_cross, _inverse_3x3_scalar])
+ def test_matches_linalg_inv_on_well_conditioned_input(self, device, dtype, kernel):
+ x = _well_conditioned(3, device, dtype, (2,))
+ ref_dtype = torch.float32 if dtype in (torch.float16, torch.bfloat16) else dtype
+ tol = 1e-2 if dtype in (torch.float16, torch.bfloat16) else 1e-4
+ self.assert_close(kernel(x), torch.linalg.inv(x.to(ref_dtype)).to(dtype), atol=tol, rtol=tol)
+
+ @pytest.mark.parametrize("kernel", [_inverse_3x3_cross, _inverse_3x3_scalar])
+ def test_gradcheck(self, device, kernel):
+ self.gradcheck(kernel, (_well_conditioned(3, device, torch.float64),))
+
+ @pytest.mark.parametrize("kernel", [_inverse_3x3_cross, _inverse_3x3_scalar])
+ def test_dynamo(self, device, dtype, kernel, torch_optimizer):
+ x = _well_conditioned(3, device, dtype, (2,))
+ self.assert_close(torch_optimizer(kernel)(x), kernel(x))
+
+ @pytest.mark.parametrize("kernel", [_inverse_3x3_cross, _inverse_3x3_scalar])
+ def test_scripts(self, device, dtype, kernel):
+ x = _well_conditioned(3, device, dtype, (2,))
+ self.assert_close(torch.jit.script(kernel)(x), kernel(x))
+
+ @pytest.mark.device_agnostic
+ @pytest.mark.filterwarnings("ignore::DeprecationWarning")
+ @pytest.mark.parametrize("use_dynamo_exporter", [False, True], ids=["torchscript", "torchexport"])
+ def test_scalar_kernel_exports_to_onnx(self, device, use_dynamo_exporter):
+ # Contractual: the scalar kernel is the path the dispatcher takes under export, so its
+ # graph must contain no linalg decomposition. Both exporters.
+ _require_exporter(use_dynamo_exporter)
+ onnx = pytest.importorskip("onnx")
+ x = _well_conditioned(3, device, torch.float32, (2,))
+ buffer = io.BytesIO()
+ torch.onnx.export(_ScalarInverseModule(), (x,), buffer, **_export_kwargs(use_dynamo_exporter))
+ ops = {node.op_type for node in onnx.load_from_string(buffer.getvalue()).graph.node}
+ _assert_basic_arithmetic_only(ops)
+
+ @pytest.mark.device_agnostic
+ @pytest.mark.filterwarnings("ignore::DeprecationWarning")
+ @pytest.mark.parametrize("use_dynamo_exporter", [False, True], ids=["torchscript", "torchexport"])
+ def test_cross_kernel_onnx_export_is_informational(self, device, use_dynamo_exporter):
+ # NOT a gate, deliberately -- but the measurement behind it is now stronger than it was.
+ # ``torch.linalg.cross`` lowers on BOTH torch versions CI runs: 2.9.1 on both exporters,
+ # and 2.5.1 on the legacy one (2.5.1's dynamo path needs onnxscript, which those CI legs
+ # do not install, so it is out of reach rather than broken). Untested: torch 2.0-2.4,
+ # which kornia declares support for and CI does not run.
+ # It stays a skip rather than a hard assertion for two reasons: the dispatcher never takes
+ # this kernel under export, so nothing in kornia depends on it lowering; and a future torch
+ # that stops lowering ``cross`` should surface as a visible skip here rather than as a red
+ # test for something kornia does not rely on.
+ _require_exporter(use_dynamo_exporter)
+ onnx = pytest.importorskip("onnx")
+ x = _well_conditioned(3, device, torch.float32, (2,))
+ buffer = io.BytesIO()
+ try:
+ torch.onnx.export(_CrossInverseModule(), (x,), buffer, **_export_kwargs(use_dynamo_exporter))
+ except TypeError:
+ # An API misuse is not a lowering failure. Re-raised rather than skipped, or a wrong
+ # kwarg would masquerade forever as "cross does not lower here".
+ raise
+ except Exception as err:
+ pytest.skip(f"torch.linalg.cross does not lower on torch {torch.__version__}: {err}")
+ ops = {node.op_type for node in onnx.load_from_string(buffer.getvalue()).graph.node}
+ _assert_basic_arithmetic_only(ops)
+
+
+class _ScalarInverseModule(torch.nn.Module):
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
+ return _inverse_3x3_scalar(x)
+
+
+class _CrossInverseModule(torch.nn.Module):
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
+ return _inverse_3x3_cross(x)
diff --git a/tests/geometry/test_conversions.py b/tests/geometry/test_conversions.py
index 9e7bf8cf9..db82a59f2 100644
--- a/tests/geometry/test_conversions.py
+++ b/tests/geometry/test_conversions.py
@@ -200,8 +200,8 @@ _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
+ # operation the route needs. kornia's cusolver-free 3x3 inverse dispatches to
+ # _inverse_3x3_cross (kornia/core/_small_linalg.py), which 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
@@ -219,10 +219,12 @@ def _skip_if_closed_form_inverse_unavailable(device: torch.device, dtype: torch.
# 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
+ # Residual, stated rather than hidden: this identifies the failing KERNEL, not the individual
+ # `cross` line inside it. _inverse_3x3_cross 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.
+ # It reads the cross KERNEL rather than the mode dispatcher that calls it: the dispatcher owns
+ # only the eager/export choice, so its frame is never where a missing `cross` surfaces.
# 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
@@ -232,7 +234,7 @@ def _skip_if_closed_form_inverse_unavailable(device: torch.device, dtype: torch.
# 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
+ from kornia.core._small_linalg import _inverse_3x3_cross
route = (device, dtype)
if route in _healthy_closed_form_inverse_routes:
@@ -242,7 +244,7 @@ def _skip_if_closed_form_inverse_unavailable(device: torch.device, dtype: torch.
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__
+ innermost is not None and innermost.tb_frame.f_code is _inverse_3x3_cross.__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}")
@@ -277,7 +279,7 @@ def test_skip_probe_re_raises_everything_it_cannot_identify(monkeypatch):
# 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
+ # inside _inverse_3x3_cross), 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.