Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(core)!: decide singularity in safe_inverse_with_mask and safe_solve_with_mask by one scale-free rule (#5488)

εŒΊζ’“η24907d03eae5
diff --git a/changelog.d/5488.breaking.md b/changelog.d/5488.breaking.md
new file mode 100644
index 000000000..e174fbade
--- /dev/null
+++ b/changelog.d/5488.breaking.md
@@ -0,0 +1,6 @@
+`safe_inverse_with_mask` and `safe_solve_with_mask` now decide the singularity of 2x2, 3x3 and 4x4 matrices by one
+rule in eager mode and under capture alike, the closed-form determinant against the permanent of the absolute values,
+`|det A| <= 8 n eps perm |A|` (#5476). Previously the mask came from LAPACK's `info` in eager mode and from `det != 0`
+under capture, so a 3x3 with two equal rows was valid on torch 2.5.1 eager and under `torch.jit.trace` and invalid on
+torch 2.14 eager. A matrix whose determinant is rounding noise is now invalid everywhere, whatever its scale, and
+`_torch_inverse_cast` documents that it does not check singular input.
diff --git a/kornia/core/_small_linalg.py b/kornia/core/_small_linalg.py
index 1f4cb1212..6995954ad 100644
--- a/kornia/core/_small_linalg.py
+++ b/kornia/core/_small_linalg.py
@@ -51,6 +51,9 @@ __all__ = [
"_adjugate_2x2",
"_adjugate_3x3",
"_adjugate_4x4",
+ "_det_perm_2x2",
+ "_det_perm_3x3",
+ "_det_perm_4x4",
"_inverse_3x3_cross",
"_inverse_3x3_scalar",
]
@@ -161,6 +164,117 @@ def _adjugate_4x4(input: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
return adj, det
+def _det_perm_2x2(input: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
+ """Return the determinant of batched 2x2 matrices and the permanent of their absolute values.
+
+ The permanent of ``|A|`` is the sum of the absolute values of the terms of the determinant expansion,
+ so it is the scale of the rounding error of the determinant computed here, and the scale against which
+ a determinant counts as zero.
+ """
+ a = input[..., 0, 0]
+ b = input[..., 0, 1]
+ c = input[..., 1, 0]
+ d = input[..., 1, 1]
+ ad = a * d
+ bc = b * c
+ return ad - bc, ad.abs() + bc.abs()
+
+
+def _det_perm_3x3(input: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
+ """Return the determinant of batched 3x3 matrices and the permanent of their absolute values.
+
+ Both expand along the first row: the determinant with signed 2x2 minors, the permanent of ``|A|`` with
+ the absolute values of the same products added.
+ """
+ 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]
+ ei = e * i
+ fh = f * h
+ di = d * i
+ fg = f * g
+ dh = d * h
+ eg = e * g
+ det = a * (ei - fh) - b * (di - fg) + c * (dh - eg)
+ perm = a.abs() * (ei.abs() + fh.abs()) + b.abs() * (di.abs() + fg.abs()) + c.abs() * (dh.abs() + eg.abs())
+ return det, perm
+
+
+def _det_perm_4x4(input: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
+ """Return the determinant of batched 4x4 matrices and the permanent of their absolute values.
+
+ Laplace expansion over the 2x2 minors of the top two rows against the complementary minors of the
+ bottom two rows, as :func:`_adjugate_4x4`; the permanent of ``|A|`` pairs the 2x2 permanents of
+ ``|A|`` the same way.
+ """
+ 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]
+
+ af = a * f
+ be = b * e
+ ag = a * g
+ ce = c * e
+ ah = a * h
+ de = d * e
+ bg = b * g
+ cf = c * f
+ bh = b * h
+ df = d * f
+ ch = c * h
+ dg = d * g
+
+ kp = k * p
+ lo = l_ * o
+ jp = j * p
+ ln = l_ * n
+ jo = j * o
+ kn = k * n
+ ip = i * p
+ lm = l_ * m
+ io = i * o
+ km = k * m
+ in_ = i * n
+ jm = j * m
+
+ det = (
+ (af - be) * (kp - lo)
+ - (ag - ce) * (jp - ln)
+ + (ah - de) * (jo - kn)
+ + (bg - cf) * (ip - lm)
+ - (bh - df) * (io - km)
+ + (ch - dg) * (in_ - jm)
+ )
+ perm = (
+ (af.abs() + be.abs()) * (kp.abs() + lo.abs())
+ + (ag.abs() + ce.abs()) * (jp.abs() + ln.abs())
+ + (ah.abs() + de.abs()) * (jo.abs() + kn.abs())
+ + (bg.abs() + cf.abs()) * (ip.abs() + lm.abs())
+ + (bh.abs() + df.abs()) * (io.abs() + km.abs())
+ + (ch.abs() + dg.abs()) * (in_.abs() + jm.abs())
+ )
+ return det, perm
+
+
def _inverse_3x3_cross(input: torch.Tensor) -> torch.Tensor:
"""Closed-form 3x3 inverse via three fused cross products. The eager path.
diff --git a/kornia/core/utils.py b/kornia/core/utils.py
index e2d45d843..85df5bd83 100644
--- a/kornia/core/utils.py
+++ b/kornia/core/utils.py
@@ -30,6 +30,9 @@ from kornia.core._small_linalg import (
_adjugate_2x2,
_adjugate_3x3,
_adjugate_4x4,
+ _det_perm_2x2,
+ _det_perm_3x3,
+ _det_perm_4x4,
_inverse_3x3_cross,
_inverse_3x3_scalar,
)
@@ -243,6 +246,22 @@ def _adjugate_closed_form(input: torch.Tensor) -> Tuple[torch.Tensor, torch.Tens
raise NotImplementedError(f"Closed-form inverse only supports 2x2, 3x3 and 4x4 matrices, got {list(input.shape)}")
+def _det_perm_closed_form(input: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
+ """Determinant of batched square matrices up to 4x4 and the permanent of their absolute values.
+
+ Raises:
+ NotImplementedError: for shapes other than ``(..., n, n)`` with ``n`` in 2, 3, 4.
+ """
+ n = input.shape[-1]
+ if input.shape[-2] == n and n == 2:
+ return _det_perm_2x2(input)
+ if input.shape[-2] == n and n == 3:
+ return _det_perm_3x3(input)
+ if input.shape[-2] == n and n == 4:
+ return _det_perm_4x4(input)
+ raise NotImplementedError(f"Closed-form determinant supports 2x2, 3x3 and 4x4 matrices, got {list(input.shape)}")
+
+
def _has_closed_form_inverse(input: torch.Tensor) -> bool:
n = input.shape[-1]
return input.shape[-2] == n and n in (2, 3, 4)
@@ -260,6 +279,12 @@ def _torch_inverse_cast(input: torch.Tensor) -> torch.Tensor:
include ``aten::linalg_inv``, which neither ONNX exporter lowers. ``torch.jit.is_tracing()``
is JIT-script-safe (unlike ``torch.onnx.is_in_onnx_export``, which contains an ``import``
statement).
+
+ Singular input is not checked here. In eager mode ``torch.linalg.inv`` decides, and raises, from the
+ pivots of its own factorization; under capture the adjugate is divided by the determinant, which gives
+ non-finite or large values. Which near-singular matrices raise, and which return large values, depends
+ on the torch version, the device and the capture mode. Callers that need a verdict use
+ :func:`safe_inverse_with_mask`, whose mask follows one rule everywhere.
"""
KORNIA_CHECK_IS_TENSOR(input, "Input must be torch.Tensor")
dtype = _normalize_to_float32_or_float64(input.dtype)
@@ -383,13 +408,53 @@ def _rows_finite(x: torch.Tensor) -> torch.Tensor:
return x.isfinite().all(-1).all(-1)
+def _is_singular(A: torch.Tensor) -> torch.Tensor:
+ """Whether each 2x2, 3x3 or 4x4 matrix of ``A`` counts as singular, as a mask over its batch.
+
+ One rule decides, the same in eager mode and under graph capture, on every torch version and device,
+ and unchanged by scaling the matrix: a matrix is singular when its closed-form determinant is within
+ the rounding error of that determinant,
+
+ ``|det A| <= 8 * n * eps * perm |A|``,
+
+ where ``perm |A|``, the permanent of the absolute values, is the sum of the absolute values of the terms
+ of the determinant expansion, ``eps`` the machine epsilon of the dtype of ``A`` and ``n`` its order. The
+ permanent, unlike ``||A||^n``, does not grow with a translation: a homography that moves by 5000 pixels
+ has ``det 1`` and ``perm 1``. A matrix with a non-finite entry is not flagged; its inverse is not finite
+ and the callers reject it on that account.
+
+ Both sides are linear in every row and every column, so the rule is read on the matrix with each row,
+ then each column, divided by its largest magnitude. That leaves the ratio unchanged and keeps the
+ products of ``n`` entries from overflowing or underflowing: unscaled, ``1e10 * I`` of order 4 in float32
+ reads ``inf <= inf`` and ``1e-13 * I`` reads ``0 <= 0``, and both would count as singular.
+
+ Raises:
+ NotImplementedError: for shapes other than ``(..., n, n)`` with ``n`` in 2, 3, 4.
+ """
+ if torch.jit.is_scripting():
+ # ``torch.finfo`` does not script; the callers hand this float32 or float64 only.
+ double = A.dtype == torch.float64
+ eps = 2.220446049250313e-16 if double else 1.1920928955078125e-07
+ tiny = 2.2250738585072014e-308 if double else 1.1754943508222875e-38
+ else:
+ eps = torch.finfo(A.dtype).eps
+ tiny = torch.finfo(A.dtype).tiny
+ A = A / A.abs().amax(-1, keepdim=True).clamp_min(tiny)
+ A = A / A.abs().amax(-2, keepdim=True).clamp_min(tiny)
+ det, perm = _det_perm_closed_form(A)
+ return det.abs() <= (8 * A.shape[-1] * eps) * perm
+
+
def safe_solve_with_mask(B: torch.Tensor, A: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
r"""Solves the system of equations.
Avoids crashing because of singular matrix input and outputs the mask of valid solution.
- A system is valid when the LU factorization of ``A`` has no zero pivot and the solution is finite in
- the dtype of ``B``. An invalid system is solved with the identity in place of ``A``, so its row of
+ A system is valid when ``A`` is not singular and the solution is finite in the dtype of ``B``. A 2x2,
+ 3x3 or 4x4 ``A`` is singular when ``|det A| <= 8 * n * eps * perm |A|``, the closed-form determinant
+ against the permanent of the absolute values (:func:`_is_singular`), which is the same on every torch
+ version, or when its LU factorization has a zero pivot; a larger ``A`` by the zero pivot alone. An
+ invalid system is solved with the identity in place of ``A``, so its row of
``X`` holds ``B`` and its row of the returned LU factor is the identity's. The differentiated solve
therefore never sees a singular matrix, and the gradient with respect to the valid systems (and to
any parameter they share with an invalid one) stays finite.
@@ -421,9 +486,12 @@ def safe_solve_with_mask(B: torch.Tensor, A: torch.Tensor) -> Tuple[torch.Tensor
# identity. Masking the output instead is not enough: the backward of ``lu_factor`` / ``lu_solve`` at
# a singular matrix is non-finite, and ``0 * nan`` leaks it into every shared parameter.
# Since kornia requires torch>=2.5.1, we can always use torch.linalg.lu_factor_ex and torch.linalg.lu_solve
- LU_detached, pivots_detached, info = torch.linalg.lu_factor_ex(A_cast.detach())
+ A_detached = A_cast.detach()
+ LU_detached, pivots_detached, info = torch.linalg.lu_factor_ex(A_detached)
X_detached = torch.linalg.lu_solve(LU_detached, pivots_detached, B_cast.detach())
valid_mask: torch.Tensor = (info == 0) & _rows_finite(X_detached.to(B.dtype))
+ if _has_closed_form_inverse(A):
+ valid_mask = valid_mask & ~_is_singular(A_detached)
eye = torch.eye(A_cast.shape[-1], device=A_cast.device, dtype=dtype)
A_safe = torch.where(valid_mask[..., None, None], A_cast, eye)
@@ -438,8 +506,11 @@ def safe_inverse_with_mask(A: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]
Avoids crashing because of non-invertable matrix input and outputs the mask of valid solution.
- A matrix is valid when it is invertible (no zero pivot in eager mode, a non-zero determinant under
- graph capture) and its inverse is finite in the dtype of ``A``. An invalid matrix is inverted as the
+ A matrix is valid when it is not singular and its inverse is finite in the dtype of ``A``. A 2x2, 3x3
+ or 4x4 matrix is singular when ``|det A| <= 8 * n * eps * perm |A|``, the closed-form determinant
+ against the permanent of the absolute values (:func:`_is_singular`), which is the same in eager mode and
+ under graph capture and on every torch version, or, in eager mode, when ``inv_ex`` reports a zero
+ pivot; a larger matrix by the zero pivot alone. An invalid matrix is inverted as the
identity, so its row of the output is the identity. The differentiated inverse therefore never sees a
singular matrix, and the gradient with respect to the valid matrices (and to any parameter they
share with an invalid one) stays finite.
@@ -460,18 +531,20 @@ def safe_inverse_with_mask(A: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]
# Decide validity on a detached pass, then invert a batch whose invalid matrices are replaced by the
# identity. Masking the output instead is not enough: the backward of ``inv`` reuses its non-finite
# output, and ``0 * nan`` leaks it into every shared parameter.
+ A_detached = A_cast.detach()
if _is_tracing_or_exporting() and _has_closed_form_inverse(A):
- # ``linalg_inv_ex`` has no ONNX lowering; the adjugate form is basic arithmetic, and a
- # zero determinant is exactly the singularity ``inv_ex`` flags through ``info``.
- adj_detached, det_detached = _adjugate_closed_form(A_cast.detach())
- mask = det_detached != 0
+ # ``linalg_inv_ex`` has no ONNX lowering; the adjugate form is basic arithmetic.
+ adj_detached, det_detached = _adjugate_closed_form(A_detached)
+ mask = ~_is_singular(A_detached)
safe_det = torch.where(mask, det_detached, torch.ones_like(det_detached))
mask = mask & _rows_finite((adj_detached / safe_det[..., None, None]).to(dtype_original))
adj, det = _adjugate_closed_form(torch.where(mask[..., None, None], A_cast, eye))
return (adj / det[..., None, None]).to(dtype_original), mask
- inverse_detached, info = inv_ex(A_cast.detach())
+ inverse_detached, info = inv_ex(A_detached)
mask = (info == 0) & _rows_finite(inverse_detached.to(dtype_original))
+ if _has_closed_form_inverse(A):
+ mask = mask & ~_is_singular(A_detached)
inverse, _ = inv_ex(torch.where(mask[..., None, None], A_cast, eye))
return inverse.to(dtype_original), mask
diff --git a/tests/core/test_helpers.py b/tests/core/test_helpers.py
index fb99b064f..fdc3b1320 100644
--- a/tests/core/test_helpers.py
+++ b/tests/core/test_helpers.py
@@ -21,8 +21,10 @@ import torch
from kornia.core.exceptions import BaseError, DeviceError, TypeCheckError
from kornia.core.utils import (
_adjugate_closed_form,
+ _det_perm_closed_form,
_extract_device_dtype,
_inverse_3x3_closed_form,
+ _is_singular,
_torch_histc_cast,
_torch_inverse_cast,
_torch_linalg_svdvals,
@@ -40,6 +42,30 @@ from kornia.core.utils import (
from testing.base import BaseTester, assert_close
+def _issue_5476_batch(device, dtype):
+ """Identity, a 3x3 with equal first and last rows, one with a doubled row, zeros and a translation homography."""
+ repeated = torch.tensor([[-956.0, -761.0, -67.0], [760.0, -37.0, -621.0], [-956.0, -761.0, -67.0]])
+ doubled = torch.tensor([[1.0, 2.0, 3.0], [2.0, 4.0, 6.0], [0.0, 1.0, 1.0]])
+ translation = torch.tensor([[1.0, 0.0, 4096.0], [0.0, 1.0, -2048.0], [0.0, 0.0, 1.0]])
+ return torch.stack([torch.eye(3), repeated, doubled, torch.zeros(3, 3), translation]).to(device, dtype)
+
+
+def _scales(dtype):
+ """Powers of two keep the scaling exact, the decimal ones, kept out of half precision, perturb it by a rounding."""
+ if dtype in (torch.float16, torch.bfloat16):
+ return [2.0**-10, 1.0, 2.0**10]
+ return [1e-3, 1.0, 1e3, 2.0**-20, 2.0**20]
+
+
+# One row is the sum of two others, or a multiple of the other, in small integers: exactly singular, and every
+# product of the closed-form determinant is exact.
+_DEPENDENT_ROWS = {
+ 2: [[3.0, -7.0], [-6.0, 14.0]],
+ 3: [[2.0, -3.0, 5.0], [7.0, 1.0, -4.0], [9.0, -2.0, 1.0]],
+ 4: [[1.0, -2.0, 3.0, 4.0], [5.0, 6.0, -7.0, 8.0], [-9.0, 1.0, 2.0, -3.0], [-3.0, 5.0, -2.0, 9.0]],
+}
+
+
@pytest.mark.parametrize(
"tensor_list,out_device,out_dtype,error",
[
@@ -509,6 +535,26 @@ class TestSolveWithMask:
assert mask.tolist() == [False]
assert torch.equal(X, B)
+ def test_singular_verdict_is_the_one_of_safe_inverse_with_mask_5476(self, device, dtype):
+ # The 3x3 with two equal rows has a float32 LU pivot that is zero on some torch versions and tiny on
+ # others; the verdict is kornia's rule, the same as the inverse's, on every one of them.
+ A = _issue_5476_batch(device, dtype)
+ B = torch.ones(5, 3, device=device, dtype=dtype)
+ X, _, mask = safe_solve_with_mask(B, A)
+ assert mask.tolist() == [True, False, False, False, True]
+ assert torch.equal(mask, safe_inverse_with_mask(A)[1])
+ assert_close(X[0, :, 0], B[0])
+ assert_close(X[4, :, 0], torch.tensor([1.0 - 4096.0, 1.0 + 2048.0, 1.0], device=device, dtype=dtype))
+
+ @pytest.mark.parametrize("n", [2, 3, 4])
+ def test_dependent_rows_are_singular_at_every_scale(self, device, dtype, n):
+ A = torch.tensor(_DEPENDENT_ROWS[n], device=device, dtype=dtype)
+ scales = _scales(dtype)
+ A = A * torch.tensor(scales, device=device, dtype=dtype)[:, None, None]
+ B = torch.ones(len(scales), n, device=device, dtype=dtype)
+ _, _, mask = safe_solve_with_mask(B, A)
+ assert not mask.any()
+
class TestBatchedForwardBatchSize:
def test_rejects_zero_batch_size(self):
@@ -589,6 +635,117 @@ class TestInverseWithMask:
assert not mask.item()
assert torch.equal(inverse, torch.eye(2, device=device, dtype=torch.float16))
+ def test_singular_verdict_is_the_same_in_eager_and_trace_5476(self, device, dtype):
+ # The 3x3 with two equal rows has a closed-form float32 determinant of -20 against a permanent of
+ # 1e9, and a float32 LU pivot that is zero on some torch versions and tiny on others. The verdict
+ # is kornia's rule in both modes, so it is the same one everywhere.
+ A = _issue_5476_batch(device, dtype)
+ expected = [True, False, False, False, True]
+ for fn in (safe_inverse_with_mask, torch.jit.trace(safe_inverse_with_mask, (A,), check_trace=False)):
+ inverse, mask = fn(A)
+ assert mask.tolist() == expected
+ assert_close(inverse[0], A[0])
+ assert torch.equal(inverse[1:4], A[0].expand(3, 3, 3))
+
+ @pytest.mark.parametrize("n", [2, 3, 4])
+ def test_dependent_rows_are_singular_at_every_scale(self, device, dtype, n):
+ # Scaling a matrix scales its determinant and the permanent of its absolute values alike, so the
+ # verdict does not depend on the units; the inexact decimal scales also perturb the exact
+ # dependence by a rounding error, which the rule has to absorb.
+ A = torch.tensor(_DEPENDENT_ROWS[n], device=device, dtype=dtype)
+ scales = _scales(dtype)
+ A = A * torch.tensor(scales, device=device, dtype=dtype)[:, None, None]
+ for fn in (safe_inverse_with_mask, torch.jit.trace(safe_inverse_with_mask, (A,), check_trace=False)):
+ inverse, mask = fn(A)
+ assert not mask.any()
+ assert torch.equal(inverse, torch.eye(n, device=device, dtype=dtype).expand_as(A))
+
+ def test_translation_homography_is_valid_and_inverted_exactly(self, device, dtype):
+ # ``det 1`` against ``perm 1``: a rule scaled by the norm of the matrix, ``4096 ** 3`` here, would call
+ # the most common matrix kornia inverts singular in float32.
+ A = _issue_5476_batch(device, dtype)[4]
+ expected = torch.tensor([[1.0, 0.0, -4096.0], [0.0, 1.0, 2048.0], [0.0, 0.0, 1.0]], device=device, dtype=dtype)
+ for fn in (safe_inverse_with_mask, torch.jit.trace(safe_inverse_with_mask, (A,), check_trace=False)):
+ inverse, mask = fn(A)
+ assert mask.item()
+ assert torch.equal(inverse, expected)
+
+ def test_tiny_but_regular_matrix_is_valid(self, device, dtype):
+ # diag(1, s) has determinant and permanent s, so it is regular however small s is; only an inverse
+ # that does not fit the dtype makes it invalid.
+ small = 2.0**-14 if dtype in (torch.float16, torch.bfloat16) else 1e-30
+ A = torch.diag(torch.tensor([1.0, small], device=device, dtype=dtype))
+ inverse, mask = safe_inverse_with_mask(A)
+ assert mask.item()
+ assert torch.equal(inverse, torch.diag(torch.tensor([1.0, 1.0 / small], device=device, dtype=dtype)))
+
+ def test_scripts_with_the_eager_verdict_5476(self, device, dtype):
+ # The rule has to compile under TorchScript, as the functions did before it.
+ A = _issue_5476_batch(device, dtype)
+ B = torch.ones(5, 3, device=device, dtype=dtype)
+ inverse, mask = torch.jit.script(safe_inverse_with_mask)(A)
+ X, _, valid = torch.jit.script(safe_solve_with_mask)(B, A)
+ assert mask.tolist() == valid.tolist() == [True, False, False, False, True]
+ assert_close(inverse, safe_inverse_with_mask(A)[0])
+ assert_close(X, safe_solve_with_mask(B, A)[0])
+ if dtype in (torch.float32, torch.float64):
+ # the scripted threshold reads the eps and the floor of the dtype, as the eager one does
+ eps = torch.finfo(dtype).eps
+ edges = torch.tensor([[[1.0, 1.0], [1.0, 1.0 + k * eps]] for k in (24, 64)], device=device, dtype=dtype)
+ zero_row = torch.tensor([[1.0, 2.0], [0.0, 0.0]], device=device, dtype=dtype)
+ edges = torch.cat([edges, zero_row[None]])
+ assert torch.jit.script(_is_singular)(edges).tolist() == _is_singular(edges).tolist() == [True, False, True]
+
+ def test_regular_matrix_is_regular_at_a_scale_whose_products_overflow(self, device, dtype):
+ # The terms of a 4x4 determinant are products of four entries, which overflow (or underflow) the dtype
+ # long before the inverse does: unscaled, the rule would read ``inf <= inf`` (or ``0 <= 0``) and call a
+ # well-conditioned matrix singular. Scaling two rows or two columns alone underflows the products too.
+ # Powers of two keep the scaling exact. Half input is decided in float32, where these scales are harmless.
+ if dtype not in (torch.float32, torch.float64):
+ pytest.skip("half input is decided in float32")
+ big = 2.0**40 if dtype == torch.float32 else 2.0**300
+ small = 2.0**-80 if dtype == torch.float32 else 2.0**-600
+ A = torch.tensor(
+ [[4.0, 1.0, 2.0, 1.0], [1.0, 5.0, 1.0, 2.0], [2.0, 1.0, 6.0, 1.0], [1.0, 2.0, 1.0, 7.0]],
+ device=device,
+ dtype=dtype,
+ )
+ D = torch.diag(torch.tensor([1.0, 1.0, small, small], device=device, dtype=dtype))
+ A = torch.stack([A * big, A / big, A @ D, D @ A])
+ assert not _is_singular(A).any()
+ assert safe_inverse_with_mask(A)[1].all()
+ assert safe_solve_with_mask(torch.ones(4, 4, device=device, dtype=dtype), A)[2].all()
+
+ def test_rule_calls_a_zero_row_or_column_singular(self, device, dtype):
+ # The rule divides each row and column by its largest magnitude; a zero row or column has to stay
+ # zero (determinant and permanent 0, so singular) rather than turn into 0 / 0.
+ A = torch.tensor([[4.0, 1.0, 2.0], [1.0, 5.0, 1.0], [2.0, 1.0, 6.0]], device=device, dtype=dtype)
+ zero_row, zero_col = A.clone(), A.clone()
+ zero_row[1] = 0.0
+ zero_col[:, 2] = 0.0
+ assert _is_singular(torch.stack([zero_row, zero_col, torch.zeros_like(A)])).all()
+ assert not _is_singular(A).item()
+
+ @pytest.mark.parametrize("n", [2, 3, 4])
+ def test_rule_reads_the_determinant_against_the_permanent(self, device, dtype, n):
+ A = torch.tensor(_DEPENDENT_ROWS[n], device=device, dtype=dtype)
+ det, perm = _det_perm_closed_form(A)
+ assert torch.equal(det, torch.zeros_like(det)) and perm.item() > 0
+ assert _is_singular(A).item()
+ # [[1, 1], [1, 1 + d]] has determinant d, exact for a power of two d, against a permanent of 2 + d:
+ # the threshold ``8 * n * eps * perm`` sits at about 32 eps, so 64 eps is regular and 24 eps singular
+ # (a threshold without the order ``n``, about 16 eps, would call 24 eps regular)
+ eps = torch.finfo(dtype).eps
+ edge = torch.tensor([[1.0, 1.0], [1.0, 1.0 + 64 * eps]], device=device, dtype=dtype)
+ assert torch.equal(_det_perm_closed_form(edge)[0], torch.tensor(64 * eps, device=device, dtype=dtype))
+ assert not _is_singular(edge).item()
+ edge[1, 1] = 1.0 + 24 * eps
+ assert _is_singular(edge).item()
+
+ def test_rule_rejects_other_shapes(self, device, dtype):
+ with pytest.raises(NotImplementedError):
+ _is_singular(torch.eye(5, device=device, dtype=dtype))
+
def test_is_autocast_enabled_cpu():
assert not is_autocast_enabled()
diff --git a/tests/core/test_small_linalg.py b/tests/core/test_small_linalg.py
index 390a6027c..6b82a397b 100644
--- a/tests/core/test_small_linalg.py
+++ b/tests/core/test_small_linalg.py
@@ -27,6 +27,7 @@ dispatcher ``_adjugate_closed_form`` and is tested in ``test_helpers.py``.
"""
import io
+import itertools
import re
import pytest
@@ -37,6 +38,9 @@ from kornia.core._small_linalg import (
_adjugate_2x2,
_adjugate_3x3,
_adjugate_4x4,
+ _det_perm_2x2,
+ _det_perm_3x3,
+ _det_perm_4x4,
_inverse_3x3_cross,
_inverse_3x3_scalar,
)
@@ -44,6 +48,7 @@ from kornia.core._small_linalg import (
from testing.base import BaseTester
ADJUGATE = {2: _adjugate_2x2, 3: _adjugate_3x3, 4: _adjugate_4x4}
+DET_PERM = {2: _det_perm_2x2, 3: _det_perm_3x3, 4: _det_perm_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
@@ -233,6 +238,127 @@ class _AdjugateModule(torch.nn.Module):
return adj / det[..., None, None]
+def _signed(n, device, dtype):
+ """A batch of two: ``_well_conditioned``, all positive, so terms of the determinant cancel and the permanent
+ of the absolute values is strictly larger than ``|det|``, and the same with mixed signs."""
+ x = _well_conditioned(n, device, dtype)
+ signs = torch.tensor([[(-1.0) ** (r * c) for c in range(n)] for r in range(n)], device=device, dtype=dtype)
+ return torch.stack([x, x * signs])
+
+
+def _permanent_of_abs(x):
+ """The permanent of ``|x|`` summed over the permutations, in float64 on the CPU (MPS has no float64)."""
+ n = x.shape[-1]
+ x = x.abs().cpu().to(torch.float64)
+ terms = [x[..., range(n), perm].prod(-1) for perm in itertools.permutations(range(n))]
+ return torch.stack(terms, -1).sum(-1)
+
+
+class TestDetPermKernels(BaseTester):
+ @pytest.mark.parametrize("n", [2, 3, 4])
+ def test_smoke(self, device, dtype, n):
+ det, perm = DET_PERM[n](_well_conditioned(n, device, dtype))
+ assert det.shape == ()
+ assert perm.shape == ()
+ assert det.dtype == dtype and perm.dtype == dtype
+
+ @pytest.mark.parametrize("n", [2, 3, 4])
+ @pytest.mark.parametrize("batch", [(), (2,), (2, 3)])
+ def test_cardinality(self, device, dtype, n, batch):
+ det, perm = DET_PERM[n](_well_conditioned(n, device, dtype, batch))
+ assert det.shape == batch
+ assert perm.shape == batch
+
+ @pytest.mark.parametrize("n", [2, 3, 4])
+ def test_matches_linalg_det_and_the_permanent_of_the_absolute_values(self, device, dtype, n):
+ # The determinant is checked against torch within the rounding scale the permanent names, and the
+ # permanent against its definition, the sum over the permutations of the products of ``|x|``.
+ x = _signed(n, device, dtype)
+ det, perm = DET_PERM[n](x)
+ ref_dtype = torch.float32 if dtype in (torch.float16, torch.bfloat16) else dtype
+ eps = torch.finfo(dtype).eps
+ det_ref = torch.linalg.det(x.to(ref_dtype)).to(dtype)
+ assert ((det - det_ref).abs() <= 8 * n * eps * perm).all()
+ self.assert_close(perm.cpu().to(torch.float64), _permanent_of_abs(x), rtol=8 * n * eps, atol=0.0)
+ assert (perm >= det.abs()).all()
+ assert (perm > det.abs()).any()
+ if n == 4:
+ # the same Laplace pairing of the minors, in the same order, as the adjugate kernel's determinant
+ assert torch.equal(det, ADJUGATE[n](x)[1])
+
+ @pytest.mark.parametrize("n", [2, 3, 4])
+ def test_scaling_a_row_scales_both_and_keeps_their_ratio(self, device, dtype, n):
+ # Both are homogeneous of degree one in every row and column, so their ratio, which is what
+ # ``safe_inverse_with_mask`` reads, does not depend on the units of the matrix. Powers of two keep
+ # the scaling exact in every dtype.
+ x = _signed(n, device, dtype)
+ det, perm = DET_PERM[n](x)
+ scale = torch.ones(n, 1, device=device, dtype=dtype)
+ scale[0] = 2.0**6
+ scale[-1] = 2.0**-9
+ det_s, perm_s = DET_PERM[n](x * scale)
+ factor = 2.0 ** (6 - 9)
+ assert torch.equal(det_s, det * factor)
+ assert torch.equal(perm_s, perm * factor)
+
+ @pytest.mark.parametrize("n", [2, 3, 4])
+ def test_dependent_rows_give_a_zero_determinant_and_a_positive_permanent(self, device, dtype, n):
+ # Small integers keep every product and sum exact, so the determinant of a matrix with a row equal
+ # to the sum of two others is exactly zero while the permanent of the absolute values is not.
+ x = torch.arange(1, n * n + 1, device=device, dtype=dtype).reshape(n, n)
+ x = x * torch.tensor([[(-1.0) ** (r * n + c) for c in range(n)] for r in range(n)], device=device, dtype=dtype)
+ x[-1] = x[0] + x[1] if n > 2 else -2 * x[0]
+ det, perm = DET_PERM[n](x)
+ assert torch.equal(det, torch.zeros_like(det))
+ assert perm.item() > 0
+
+ @pytest.mark.parametrize("n", [2, 3, 4])
+ def test_dynamo(self, device, dtype, n, torch_optimizer):
+ x = _signed(n, device, dtype)
+ op = DET_PERM[n]
+ op_optimized = torch_optimizer(op)
+ expected_det, expected_perm = op(x)
+ actual_det, actual_perm = op_optimized(x)
+ self.assert_close(actual_det, expected_det)
+ self.assert_close(actual_perm, expected_perm)
+
+ @pytest.mark.parametrize("n", [2, 3, 4])
+ def test_scripts(self, device, dtype, n):
+ x = _signed(n, device, dtype)
+ scripted = torch.jit.script(DET_PERM[n])
+ expected_det, expected_perm = DET_PERM[n](x)
+ actual_det, actual_perm = scripted(x)
+ self.assert_close(actual_det, expected_det)
+ self.assert_close(actual_perm, expected_perm)
+
+ @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):
+ # The singular verdict of ``safe_inverse_with_mask`` under capture is built from these kernels, so
+ # the exported graph has to stay basic arithmetic as the adjugate's does.
+ _require_exporter(use_dynamo_exporter)
+ onnx = pytest.importorskip("onnx")
+ x = _signed(n, device, torch.float32)
+ buffer = io.BytesIO()
+ torch.onnx.export(_DetPermModule(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 _DetPermModule(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:
+ det, perm = DET_PERM[self.n](x)
+ return det.abs() <= 1e-6 * perm
+
+
class TestInverse3x3Kernels(BaseTester):
def test_smoke(self, device, dtype):
x = _well_conditioned(3, device, dtype)