Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Fixes singular matrix inverse/solve for RANSAC and ConvQuad3d (#1408)

Dmytro Mishkinb8629f8aa2ba
diff --git a/kornia/geometry/homography.py b/kornia/geometry/homography.py
index 9e28477de..b146a852e 100644
--- a/kornia/geometry/homography.py
+++ b/kornia/geometry/homography.py
@@ -5,7 +5,7 @@ import torch
import kornia
from kornia.geometry.epipolar import normalize_points
-from kornia.utils import _extract_device_dtype
+from kornia.utils import _extract_device_dtype, safe_inverse_with_mask
TupleTensor = Tuple[torch.Tensor, torch.Tensor]
@@ -78,12 +78,15 @@ def symmetric_transfer_error(
if pts2.size(-1) == 3:
pts2 = kornia.convert_points_from_homogeneous(pts2)
-
+ max_num = torch.finfo(pts1.dtype).max
# From Hartley and Zisserman, Symmetric transfer error (4.7)
# dist = \sum_{i} (d(x, H^-1 x')**2 + d(x', Hx)**2)
+ H_inv, good_H = safe_inverse_with_mask(H)
+
there: torch.Tensor = oneway_transfer_error(pts1, pts2, H, True, eps)
- back: torch.Tensor = oneway_transfer_error(pts2, pts1, torch.inverse(H), True, eps)
- out = there + back
+ back: torch.Tensor = oneway_transfer_error(pts2, pts1, H_inv, True, eps)
+ good_H_reshape: torch.Tensor = good_H.view(-1, 1).expand_as(there)
+ out = (there + back) * good_H_reshape.to(there.dtype) + max_num * (~good_H_reshape).to(there.dtype)
if squared:
return out
return (out + eps).sqrt()
diff --git a/kornia/geometry/subpix/spatial_soft_argmax.py b/kornia/geometry/subpix/spatial_soft_argmax.py
index 6887666b1..b2ce30ea9 100644
--- a/kornia/geometry/subpix/spatial_soft_argmax.py
+++ b/kornia/geometry/subpix/spatial_soft_argmax.py
@@ -8,7 +8,7 @@ import kornia
from kornia.geometry.conversions import normalize_pixel_coordinates, normalize_pixel_coordinates3d
from kornia.geometry.subpix import dsnt
from kornia.utils import create_meshgrid, create_meshgrid3d
-from kornia.utils.helpers import _torch_solve_cast
+from kornia.utils.helpers import _pytorch_version_geq, safe_solve_with_mask
def _get_window_grid_kernel2d(h: int, w: int, device: torch.device = torch.device('cpu')) -> torch.Tensor:
@@ -614,14 +614,18 @@ def conv_quad_interp3d(
dxs = 0.25 * A[..., 5] # normalization to match OpenCV implementation
Hes = torch.stack([dxx, dxy, dxs, dxy, dyy, dys, dxs, dys, dss], dim=-1).view(-1, 3, 3)
-
- # The following is needed to avoid singular cases
- Hes += torch.rand(Hes[0].size(), device=Hes.device).abs()[None] * eps
+ if not _pytorch_version_geq(1, 10):
+ # The following is needed to avoid singular cases
+ Hes += torch.rand(Hes[0].size(), device=Hes.device).abs()[None] * eps
nms_mask: torch.Tensor = kornia.feature.nms3d(input, (3, 3, 3), True)
x_solved: torch.Tensor = torch.zeros_like(b)
- x_solved_masked, _ = _torch_solve_cast(b[nms_mask.view(-1)], Hes[nms_mask.view(-1)])
- x_solved.masked_scatter_(nms_mask.view(-1, 1, 1), x_solved_masked)
+ x_solved_masked, _, solved_correctly = safe_solve_with_mask(b[nms_mask.view(-1)], Hes[nms_mask.view(-1)])
+
+ # Kill those points, where we cannot solve
+ new_nms_mask = nms_mask.masked_scatter(nms_mask, solved_correctly)
+
+ x_solved.masked_scatter_(new_nms_mask.view(-1, 1, 1), x_solved_masked[solved_correctly])
dx: torch.Tensor = -x_solved
# Ignore ones, which are far from window center
@@ -630,7 +634,7 @@ def conv_quad_interp3d(
dy: torch.Tensor = 0.5 * torch.bmm(b.permute(0, 2, 1), dx)
y_max = input + dy.view(B, CH, D, H, W)
if strict_maxima_bonus > 0:
- y_max += strict_maxima_bonus * nms_mask.to(input.dtype)
+ y_max += strict_maxima_bonus * new_nms_mask.to(input.dtype)
dx_res: torch.Tensor = dx.flip(1).reshape(B, CH, D, H, W, 3).permute(0, 1, 5, 2, 3, 4)
coords_max: torch.Tensor = grid_global.repeat(B, 1, 1, 1, 1).unsqueeze(1)
diff --git a/kornia/utils/__init__.py b/kornia/utils/__init__.py
index 59c7d89b7..60f620702 100644
--- a/kornia/utils/__init__.py
+++ b/kornia/utils/__init__.py
@@ -1,6 +1,6 @@
from .draw import draw_rectangle
from .grid import create_meshgrid, create_meshgrid3d
-from .helpers import _extract_device_dtype
+from .helpers import _extract_device_dtype, safe_inverse_with_mask, safe_solve_with_mask
from .image import image_list_to_tensor, image_to_tensor, ImageToTensor, tensor_to_image
from .memory import batched_forward
from .one_hot import one_hot
@@ -18,5 +18,7 @@ __all__ = [
"load_pointcloud_ply",
"draw_rectangle",
"_extract_device_dtype",
+ "safe_inverse_with_mask",
+ "safe_solve_with_mask",
"ImageToTensor",
]
diff --git a/kornia/utils/helpers.py b/kornia/utils/helpers.py
index 62c3f372e..3e3d5fef4 100644
--- a/kornia/utils/helpers.py
+++ b/kornia/utils/helpers.py
@@ -1,3 +1,4 @@
+import warnings
from typing import Any, List, Optional, Tuple
import torch
@@ -5,6 +6,11 @@ import torch
from kornia.utils._compat import solve
+def _pytorch_version_geq(major, minor):
+ version = torch.__version__.split('.')
+ return (int(version[0]) >= major) and (int(version[1]) >= minor)
+
+
def _extract_device_dtype(tensor_list: List[Optional[Any]]) -> Tuple[torch.device, torch.dtype]:
"""Check if all the input are in the same device (only if when they are torch.Tensor).
@@ -100,3 +106,45 @@ def _torch_solve_cast(input: torch.Tensor, A: torch.Tensor) -> Tuple[torch.Tenso
out = solve(A.to(dtype), input.to(dtype))
return (out.to(input.dtype), out)
+
+
+def safe_solve_with_mask(B: torch.Tensor, A: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
+ r"""Helper function, which avoids crashing because of singular matrix input and outputs the
+ mask of valid solution"""
+ if not (_pytorch_version_geq(1, 10)):
+ sol, lu = _torch_solve_cast(B, A)
+ warnings.warn('PyTorch version < 1.10, solve validness mask maybe not correct', RuntimeWarning)
+ return sol, lu, torch.ones(len(A), dtype=torch.bool, device=A.device)
+ # Based on https://github.com/pytorch/pytorch/issues/31546#issuecomment-694135622
+ if not isinstance(B, torch.Tensor):
+ raise AssertionError(f"B must be torch.Tensor. Got: {type(B)}.")
+ dtype: torch.dtype = B.dtype
+ if dtype not in (torch.float32, torch.float64):
+ dtype = torch.float32
+ A_LU, pivots, info = torch.lu(A.to(dtype), get_infos=True)
+ valid_mask: torch.Tensor = info == 0
+ A_LU_solvable = A_LU[valid_mask]
+ X = torch.lu_solve(B.to(dtype), A_LU, pivots)
+ A_LU_out = A_LU
+ return X.to(B.dtype), A_LU.to(A.dtype), valid_mask
+
+
+def safe_inverse_with_mask(A: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
+ r"""Helper function, which avoids crashing because of non-invertable matrix input and outputs the
+ mask of valid solution"""
+ # Based on https://github.com/pytorch/pytorch/issues/31546#issuecomment-694135622
+ if not (_pytorch_version_geq(1, 9)):
+ inv = _torch_inverse_cast(A)
+ warnings.warn('PyTorch version < 1.9, inverse validness mask maybe not correct', RuntimeWarning)
+ return inv, torch.ones(len(A), dtype=torch.bool, device=A.device)
+ if not isinstance(A, torch.Tensor):
+ raise AssertionError(f"A must be torch.Tensor. Got: {type(A)}.")
+ dtype_original: torch.dtype = A.dtype
+ if dtype_original not in (torch.float32, torch.float64):
+ dtype = torch.float32
+ else:
+ dtype = dtype_original
+ from torch.linalg import inv_ex
+ inverse, info = inv_ex(A.to(dtype))
+ mask = info == 0
+ return inverse.to(dtype_original), mask
diff --git a/test/geometry/subpix/test_spatial_softargmax.py b/test/geometry/subpix/test_spatial_softargmax.py
index 0d0236e71..3772d9ef2 100644
--- a/test/geometry/subpix/test_spatial_softargmax.py
+++ b/test/geometry/subpix/test_spatial_softargmax.py
@@ -450,8 +450,8 @@ class TestConvSoftArgmax3d:
class TestConvQuadInterp3d:
- # TODO(dmytro): verify this method
- @pytest.mark.skip("RuntimeError: solve_cpu: For batch 0: Argument 431682224 has illegal value")
+ @pytest.mark.skipif((int(torch.__version__.split('.')[0]) == 1) and (int(torch.__version__.split('.')[1]) < 9),
+ reason='<1.9.0 not supporting')
def test_smoke(self, device, dtype):
input = torch.randn(2, 3, 3, 4, 4, device=device, dtype=dtype)
nms = kornia.geometry.ConvQuadInterp3d(1)
@@ -459,6 +459,8 @@ class TestConvQuadInterp3d:
assert coord.shape == (2, 3, 3, 3, 4, 4)
assert val.shape == (2, 3, 3, 4, 4)
+ @pytest.mark.skipif((int(torch.__version__.split('.')[0]) == 1) and (int(torch.__version__.split('.')[1]) < 9),
+ reason='<1.9.0 not supporting')
def test_gradcheck(self, device, dtype):
input = torch.rand(1, 1, 3, 5, 5, device=device, dtype=dtype)
input[0, 0, 1, 2, 2] += 20.0
diff --git a/test/utils/test_helpers.py b/test/utils/test_helpers.py
index a6e131325..be158d168 100644
--- a/test/utils/test_helpers.py
+++ b/test/utils/test_helpers.py
@@ -3,7 +3,14 @@ import torch
from kornia.testing import assert_close
from kornia.utils import _extract_device_dtype
-from kornia.utils.helpers import _torch_histc_cast, _torch_inverse_cast, _torch_solve_cast, _torch_svd_cast
+from kornia.utils.helpers import (
+ _torch_histc_cast,
+ _torch_inverse_cast,
+ _torch_solve_cast,
+ _torch_svd_cast,
+ safe_inverse_with_mask,
+ safe_solve_with_mask,
+)
@pytest.mark.parametrize(
@@ -105,3 +112,45 @@ class TestSolveCast:
tol_val: float = 1e-1 if dtype == torch.float16 else 1e-4
assert_close(error, torch.zeros_like(error), atol=tol_val, rtol=tol_val)
+
+
+class TestSolveWithMask:
+ def test_smoke(self, device, dtype):
+ A = torch.randn(2, 3, 1, 4, 4, device=device, dtype=dtype)
+ B = torch.randn(2, 3, 1, 4, 6, device=device, dtype=dtype)
+
+ X, _, mask = safe_solve_with_mask(B, A)
+ X2, _ = _torch_solve_cast(B, A)
+ tol_val: float = 1e-1 if dtype == torch.float16 else 1e-4
+ if mask.sum() > 0:
+ assert_close(X[mask],
+ X2[mask],
+ atol=tol_val, rtol=tol_val)
+
+ @pytest.mark.skipif((int(torch.__version__.split('.')[0]) == 1) and (int(torch.__version__.split('.')[1]) < 10),
+ reason='<1.10.0 not supporting')
+ def test_all_bad(self, device, dtype):
+ A = torch.ones(10, 3, 3, device=device, dtype=dtype)
+ B = torch.ones(3, 10, device=device, dtype=dtype)
+
+ X, _, mask = safe_solve_with_mask(B, A)
+ assert torch.equal(mask, torch.zeros_like(mask))
+
+
+class TestInverseWithMask:
+ def test_smoke(self, device, dtype):
+ x = torch.tensor([[4.0, 7.0], [2.0, 6.0]], device=device, dtype=dtype)
+
+ y_expected = torch.tensor([[0.6, -0.7], [-0.2, 0.4]], device=device, dtype=dtype)
+
+ y, mask = safe_inverse_with_mask(x)
+
+ assert_close(y, y_expected)
+ assert torch.equal(mask, torch.ones_like(mask))
+
+ @pytest.mark.skipif((int(torch.__version__.split('.')[0]) == 1) and (int(torch.__version__.split('.')[1]) < 9),
+ reason='<1.9.0 not supporting')
+ def test_all_bad(self, device, dtype):
+ A = torch.ones(10, 3, 3, device=device, dtype=dtype)
+ X, mask = safe_inverse_with_mask(A)
+ assert torch.equal(mask, torch.zeros_like(mask))