π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
RANSAC: Levenberg-Marquardt local optimization and 7-point samples by default for homographies and fundamental matrices (#5031)
Dmytro Mishkinc27b2dac663e
diff --git a/benchmarks/geometry/ransac.py b/benchmarks/geometry/ransac.pyindex 611b654a7..8754a0371 100644--- a/benchmarks/geometry/ransac.py+++ b/benchmarks/geometry/ransac.py@@ -501,10 +501,9 @@ def sweep(args: argparse.Namespace) -> None:Every configuration runs once per pair, all configurations of one pair back to back, so slowdrift affects every method alike. Each call is timed on its own with device synchronization,as in the IMC time-mAA protocol; the curve averages the times over pairs (see the module- docstring for why this is not ``time_us``). Kornia's budget is- ``batch_size * max_iter`` minimal sets (a budget below ``--batch`` runs as one batch of that- size); OpenCV's is ``maxIters``. Predictions are stored with bit-packed inlier masks and scored- by ``evaluate``.+ docstring for why this is not ``time_us``). Kornia's budget is ``max_samples`` minimal sets,+ drawn in the estimator's own ``"auto"`` batches unless ``--batch`` fixes them; OpenCV's is+ ``maxIters``. Predictions are stored with bit-packed inlier masks and scored by ``evaluate``."""kornia_methods = [m for m in args.kornia.split(",") if m]device, _, _ = setup_run(args, opencv=any(args.opencv.split(",")))@@ -556,12 +555,13 @@ def sweep(args: argparse.Namespace) -> None:for name, budget, threshold in itertools.product(methods, budgets, thresholds):if SWEEP_KORNIA[name].get("prosac_sampling") and not ranked:continue- batch = min(args.batch, budget)+ # "auto" leaves the batches to the estimator, as a caller would; the budget is max_samples.+ batch = args.batch if args.batch == "auto" else min(int(args.batch), budget)estimator = ransac_class(model_type="fundamental",inl_th=threshold,batch_size=batch,- max_iter=budget // batch,+ max_samples=budget,confidence=args.confidence,max_lo_iters=args.lo_iters,seed=args.seed,@@ -933,7 +933,7 @@ def main() -> None:sw.add_argument("--poselib", default=",".join(SWEEP_POSELIB), help=f"subset of {','.join(SWEEP_POSELIB)}")sw.add_argument("--base-source", type=Path, help="also sweep another revision's ransac.py as 'kornia-base'")sw.add_argument("--budgets", default="256,512,1024,2048,4096,8192,16384", help="kornia minimal-sample budgets")- sw.add_argument("--batch", type=int, default=256, help="kornia batch size (smaller budgets use one batch)")+ sw.add_argument("--batch", default="auto", help='kornia batch size, or "auto" (the default) for the estimator\'s')sw.add_argument("--opencv-iters", default="10,25,100,400,1600,6400,25600")sw.add_argument("--poselib-iters", default="10,25,100,400,1600,6400,25600", help="PoseLib max_iterations")sw.add_argument("--thresholds", default="0.25,0.5,0.75,1,1.5,2")@@ -1007,8 +1007,8 @@ def main() -> None:unknown |= set(args.poselib.split(",")) - set(SWEEP_POSELIB)if unknown - {""}:parser.error(f"unknown --kornia, --opencv or --poselib method: {sorted(unknown - {''})}")- if args.batch <= 0 or any(b % min(b, args.batch) for b in (int(x) for x in args.budgets.split(","))):- parser.error("every --budgets entry must be a multiple of --batch or smaller than it")+ if args.batch != "auto" and (not args.batch.isdigit() or int(args.batch) <= 0):+ parser.error('--batch must be a positive integer or "auto"')commands_by_name = {"prepare": prepare, "run": run, "sweep": sweep, "plot": plot}commands_by_name.update(compare=compare, evaluate=evaluate)commands_by_name[args.command](args)diff --git a/changelog.d/5031.added.md b/changelog.d/5031.added.mdnew file mode 100644index 000000000..ef80cae69--- /dev/null+++ b/changelog.d/5031.added.md@@ -0,0 +1 @@+`RANSAC` gains `local_optimization` (`"lm"` or `"dlt"`), `refine_iters` for the final Levenberg-Marquardt refinement, the `"fundamental_8pt"` model type, and an `offset` argument to `RANSAC.sample` that continues the PROSAC schedule across batches of different sizes. The new pipeline normalizes the correspondences once per call, solves minimal samples through a batched LU null space and scores them with one matrix product per batch; on PhotoTourism fundamental matrices and HEB homographies it is more accurate than the previous defaults and several times faster on CUDA. `sample_is_valid_for_homography` no longer copies index tensors to the device on every call. The minimal solvers share their LU null space with the public estimators: `find_fundamental(method="7POINT")`, the eight-correspondence unweighted case of `find_fundamental`, and the four-correspondence `find_homography_dlt(solver="lu")` replace `eigh`, QR or SVD with one batched LU factorization, which is several times faster on CPU and now runs in float16 and bfloat16; the seven-point cubic is expanded without inverting the null-space basis. `sampson_epipolar_distance` and `oneway_transfer_error` (and so `symmetric_transfer_error`) score several matrices on one set of correspondences with one or two matrix products, faster on CPU and CUDA for RANSAC-sized batches, and `find_fundamental`'s eight-point solver removes the smallest singular value in closed form instead of with an SVD for batches of 128 or more on CPU and 512 or more on other devices, about twice as fast for 2048 samples.diff --git a/changelog.d/5031.breaking.md b/changelog.d/5031.breaking.mdnew file mode 100644index 000000000..e0e57f0b6--- /dev/null+++ b/changelog.d/5031.breaking.md@@ -0,0 +1 @@+`RANSAC` for homographies and fundamental matrices now defaults to `local_optimization="lm"`: it keeps the eight best minimal models of the run, refines them with Levenberg-Marquardt on the truncated Sampson or transfer error after sampling, and refines the winner on its inliers with a Cauchy loss. Previously each new best model was refitted with DLT solutions on 32-inlier subsets and then on all its inliers (`lo_sample_size=32`). `model_type="fundamental"` now draws seven-point samples like `"fundamental_7pt"`; it used to draw eight-point ones, which the new `"fundamental_8pt"` keeps. With the new default, auto batches grow from 256 samples on CPU instead of a fixed size, early stopping follows the support of the best minimal model instead of the refitted one, and the returned mask holds the inliers of the returned, refined model. Estimates for a given seed change accordingly; pass `local_optimization="dlt"` (with `"fundamental_8pt"` for fundamental matrices) to keep the previous behavior. Essential matrices and line-segment homographies are unchanged.diff --git a/changelog.d/5031.fixed.md b/changelog.d/5031.fixed.mdnew file mode 100644index 000000000..c2c464a5d--- /dev/null+++ b/changelog.d/5031.fixed.md@@ -0,0 +1 @@+The seven-point fundamental solver keeps rank-two candidates when both null-space basis matrices have nearly vanishing determinants, and its cubic polishing no longer displaces repeated roots through a nearly zero derivative. RANSAC's Levenberg-Marquardt pipeline filters unsupported hypotheses before selecting its best candidates and recomputes the returned inlier mask after converting the model to the input dtype, returning failure if rounding removes sufficient support.diff --git a/docs/source/geometry.ransac.rst b/docs/source/geometry.ransac.rstindex 641703861..df8e68d12 100644--- a/docs/source/geometry.ransac.rst+++ b/docs/source/geometry.ransac.rst@@ -18,7 +18,20 @@ last batch is truncated to it. Seven-point fundamental and five-point essentialsolvers may produce several candidate matrices from each set. Early stopping ischecked between batches, and ``confidence=1`` runs the whole budget.-The default ``batch_size="auto"`` picks the batch per call. On CUDA and MPS a+``model_type="fundamental"`` draws seven-point samples and completes each with+up to three rank-2 matrices, the roots of the cubic det F = 0, like+``"fundamental_7pt"``; ``"fundamental_8pt"`` draws eight-point samples. Seven+correspondences make an all-inlier sample more likely than eight, so fewer+samples reach the same confidence.++The default ``batch_size="auto"`` picks the batches per call. With the default+``local_optimization="lm"`` (see below), a CPU call starts with 256 samples, 512+for homographies, and doubles the batch after each one up to 2048, 4096 for+homographies: inputs with many inliers stop after a small first batch, and the+others pay the per-batch overhead only a few times. On CUDA and MPS the batch+is the whole budget up to 8192 samples. Both shrink for many correspondences, so+that a batch scores at most ``2**22`` (CPU) or ``2**25`` residuals. The rest of+this paragraph describes ``local_optimization="dlt"``: on CUDA and MPS ahomography batch costs about the same from a few hundred up to 8192 hypotheses,so the budget is drawn in batches of 8192; the epipolar solvers arecompute-bound past 2048 hypotheses, so their batches stop there. Verification@@ -84,7 +97,40 @@ model PROSAC certifies first may fit them well and the pose poorly. Preferuniform sampling there, or run PROSAC with ``confidence=1`` when the extradraws are affordable.-Local optimization refits the incumbent on its inliers. For the+Local optimization+------------------++Homographies and fundamental matrices default to ``local_optimization="lm"``.+The sampling loop keeps the eight best-scoring minimal models of the whole run,+normalized once per call. After sampling, all eight are refined together with+``max_lo_iters`` Levenberg-Marquardt iterations that minimize the squared+Sampson distance or one-way transfer error of every correspondence, truncated+at ``inl_th``. The best-scoring model among the refits and the minimal models+is then refined on its own inliers with ``refine_iters`` iterations of a Cauchy+loss of scale ``inl_th / 3``, the noise level of a threshold at three standard+deviations, and the returned mask holds the inliers of the returned model after+conversion to the input dtype. If rounding removes sufficient support, the call+returns the all-zero model and empty inlier mask used for estimation failure.+Fundamental matrices keep rank two through the parametrization of+`Bartoli and Sturm (TPAMI 2004) <https://doi.org/10.1109/TPAMI.2004.1265873>`_;+the refinement follows PoseLib's ``refine_fundamental`` and+``refine_homography``. Refining several models once sampling ends, rather than+each new incumbent, is the batched form of PoseLib's rule of refining every+minimal model that improves on the best one so far. The minimal solvers take+their null spaces from a partial-pivoted LU factorization and scores come from+one matrix product per batch, which keeps the per-hypothesis cost low on every+device. The refinements are a few dozen small operations per iteration and run+on the CPU in float64 for every device, where launch latency would dominate.+Early stopping follows the support of the best minimal model.++On PhotoTourism pairs this raises the pose mAA of fundamental matrices by 0.04+to 0.1 over the subset refits below at the same sample budget. SIFT matches take+a third of the time on CPU and half on CUDA; ALIKED matches with LightGlue, on+which both stop early, take about 0.5 ms longer on CPU. On the HEB homographies+it adds about 0.04 mAA at a quarter to a half of the time.++``local_optimization="dlt"``, the only choice for essential matrices and+line-segment homographies, refits the incumbent on its inliers. For thehomography models the refit is the iteratively re-weighted least squares of:func:`~kornia.geometry.homography.find_homography_dlt_iterated`, whose Gaussianweights use ``inl_th`` as their standard deviation, so a correspondence at thediff --git a/kornia/geometry/epipolar/_metrics.py b/kornia/geometry/epipolar/_metrics.pyindex fca26f9ae..ba0017e3b 100644--- a/kornia/geometry/epipolar/_metrics.py+++ b/kornia/geometry/epipolar/_metrics.py@@ -17,10 +17,14 @@"""Module including useful metrics for Structure from Motion."""+import math++import torchfrom torch import Tensor, ones_likefrom kornia.core.check import KORNIA_CHECK_IS_TENSORfrom kornia.geometry.conversions import convert_points_to_homogeneous+from kornia.geometry.epipolar.fundamental import _epipolar_design_rowsfrom kornia.geometry.linalg import point_line_distance@@ -134,6 +138,97 @@ def _sampson_epipolar_distance_matmul_impl_(return (out + eps).sqrt()+# Shared-point Sampson distances take the GEMM path on CPU from two models on. On CUDA both paths are launch-bound+# below about 2**16 model-point pairs, where the GEMM path's extra kernels cost ~40 us, and it wins above+# (2048 models x 1000 points: 718 -> 261 us; RTX 4090, torch 2.14).+_SAMPSON_SHARED_MIN_PAIRS_ACCELERATOR = 2**16+++def _shares_points(pts1: Tensor, pts2: Tensor) -> bool:+ """Whether ``pts1`` and ``pts2`` are one set of correspondences: leading dimensions of size 1, equal counts."""+ return math.prod(pts1.shape[:-2]) == 1 and math.prod(pts2.shape[:-2]) == 1 and pts1.shape[-2] == pts2.shape[-2]+++def _sampson_errors(F: Tensor, x1: Tensor, x2: Tensor, eps: float) -> Tensor:+ """Squared Sampson distances ``(M, N)`` of fundamental matrices ``(M, 3, 3)`` on homogeneous points ``(N, 3)``.++ The line ``F x1`` and the first two components of ``F^T x2`` of every model come from ``(3M, 3) @ (3, N)`` and+ ``(2M, 3) @ (3, N)`` products; the residual ``x2 . (F x1)`` and the squared gradient norm are then formed in the+ order of the manual implementation, and ``eps`` is added to the denominator. Expanding either into monomials of+ the coordinates, as :func:`_sampson_quadratic_basis` does, cancels near the epipoles: on pixel-scale float32 points+ 0.01-1000 px from both epipoles an expanded denominator returned negative and infinite distances, and for+ ``F = [[1, 0, -1000], [0, 1, -1000], [-1000, -1000, 2e6]]``, ``x1 = (1000.1, 1000.2)``, ``x2 = (1000.3, 1000.4)``+ an expanded residual gives 0.0521 where this gives the manual path's 0.0319 (float64: 0.0403).+ """+ m, n = F.shape[0], x1.shape[0]+ lines = (F.reshape(3 * m, 3) @ x1.T).view(m, 3, n)+ lines_t = (F.mT[:, :2].reshape(2 * m, 3) @ x2.T).view(m, 2, n)+ residual = x2[:, 0] * lines[:, 0] + x2[:, 1] * lines[:, 1] + x2[:, 2] * lines[:, 2]+ denominator = lines[:, 0].square() + lines[:, 1].square() + lines_t[:, 0].square() + lines_t[:, 1].square() + eps+ return residual.square() / denominator+++def _sampson_epipolar_distance_shared_impl_(+ pts1: Tensor, pts2: Tensor, Fm: Tensor, squared: bool, eps: float, denominator_eps: float+) -> Tensor:+ """Sampson distances of many fundamental matrices on one set of correspondences, by :func:`_sampson_errors`.++ ``pts1`` and ``pts2`` have leading dimensions of size 1; the result has the broadcast shape ``(*, N)``. Half+ precision is computed in float32 and returned in the input dtype. ``denominator_eps`` is ``eps``, or 0 where the+ CUDA matmul implementation would have run (#4881).+ """+ num_points = pts1.shape[-2]+ dtype = torch.promote_types(torch.promote_types(pts1.dtype, pts2.dtype), Fm.dtype)+ work = torch.promote_types(dtype, torch.float32)+ x1 = pts1.reshape(num_points, pts1.shape[-1]).to(work)+ x2 = pts2.reshape(num_points, pts2.shape[-1]).to(work)+ if x1.shape[-1] == 2:+ x1 = convert_points_to_homogeneous(x1)+ if x2.shape[-1] == 2:+ x2 = convert_points_to_homogeneous(x2)+ out = _sampson_errors(Fm.reshape(-1, 3, 3).to(work), x1, x2, denominator_eps)+ if not squared:+ out = (out + eps).sqrt()+ shape = torch.broadcast_shapes(pts1.shape[:-2], pts2.shape[:-2], Fm.shape[:-2])+ return out.reshape(*shape, num_points).to(dtype)+++def _sampson_quadratic_basis(x1: Tensor, x2: Tensor) -> Tensor:+ """Per-correspondence monomials ``(27, 2N)`` of the Sampson distance, for RANSAC's sampling loop only.++ ``[vec F, vec Q1, vec Q2] @ basis`` gives the epipolar residuals and the squared gradient norms of every model in+ one product, with ``Q1 = F[:2]^T F[:2]`` and ``Q2 = F[:, :2] F[:, :2]^T``: ``x2^T F x1`` is linear in+ ``vec(x2 x1^T)``, and ``|F[:2] x1|^2 + |F[:, :2]^T x2|^2 = x1^T Q1 x1 + x2^T Q2 x2`` in ``vec(x1 x1^T)`` and+ ``vec(x2 x2^T)``. It writes 2N values per model where :func:`_sampson_errors` writes 5N, which is RANSAC's reason+ to keep it (ALIKED matches, N ~ 700: 5.6 against 7.0 ms per pair on CPU, 10.0 against 11.4 ms on CUDA). The+ expansion cancels near the epipoles, which is harmless only on Hartley-normalized homogeneous points ``(N, 3)``+ and unit-norm models: on 58.3M float32 inlier decisions at 0.5-4 px from 90 PhotoTourism pairs it disagreed with+ float64 24 times and the line form 30 times.+ """+ n = x1.shape[0]+ basis = x1.new_zeros(27, 2 * n)+ basis[:9, :n] = _epipolar_design_rows(x1, x2).T+ basis[9:18, n:] = _epipolar_design_rows(x1, x1).T+ basis[18:, n:] = _epipolar_design_rows(x2, x2).T+ return basis+++def _sampson_from_quadratic_basis(F: Tensor, basis: Tensor) -> Tensor:+ """Squared Sampson distances ``(M, N)`` of fundamental matrices ``(M, 3, 3)`` from :func:`_sampson_quadratic_basis`.++ A cancelled denominator can come out negative. ``clamp_min(0)`` lifts such a distance to 0, which keeps the inlier+ decisions of the unguarded ratio (a negative value is below every threshold) without the MSAC contribution above+ 1, and passes NaN through, so a non-finite correspondence stays an outlier. A floor on the denominator instead+ turned 1849 of 2.56M near-epipole decisions into false inliers. A value guard for a no-grad loop, not a gradient+ guard (#4229).+ """+ n = basis.shape[1] // 2+ q1 = F[:, :2, :].mT @ F[:, :2, :]+ q2 = F[:, :, :2] @ F[:, :, :2].mT+ out = torch.cat([F.flatten(1), q1.flatten(1), q2.flatten(1)], 1) @ basis+ return (out[:, :n].square() / out[:, n:]).clamp_min(0)++def sampson_epipolar_distance(pts1: Tensor,pts2: Tensor,@@ -150,6 +245,9 @@ def sampson_epipolar_distance((see :ref:`two-view geometry <two-view-conventions>`).- Returns squared pixel distances by default; a 3-vector point is used as given, so it must have:math:`w = 1`.+ - One set of correspondences scored against several matrices (points with leading dimensions of size 1)+ is computed from two matrix products for all of them, in at least float32; the result matches the+ per-matrix computation to roundoff.- Known defects: ``eps`` is added to the denominator, so the value depends on the scale of ``Fm``;``squared=False`` returns :math:`\sqrt{d^2 + \epsilon}`, which is not zero for an exact match; and onCUDA the matmul path omits ``eps`` from the denominator, so CUDA and CPU results differ@@ -168,10 +266,19 @@ def sampson_epipolar_distance(the computed Sampson distance with shape :math:`(*, N)`."""- if Fm.device.type == "cuda":- num_points = pts1.shape[-2]- if num_points < use_matmul_at_less_than_points:- return _sampson_epipolar_distance_matmul_impl_(pts1, pts2, Fm, squared, eps)+ # Shapes are validated by the implementations, as before; a single (3, 3) Fm never counts as several models.+ num_points = pts1.shape[-2]+ matmul = Fm.device.type == "cuda" and num_points < use_matmul_at_less_than_points+ num_models = math.prod(Fm.shape[:-2])+ if (+ num_models >= 2+ and _shares_points(pts1, pts2)+ and (Fm.device.type == "cpu" or num_models * num_points >= _SAMPSON_SHARED_MIN_PAIRS_ACCELERATOR)+ ):+ # The CUDA matmul implementation leaves eps out of the denominator (#4881); the shared path follows it there.+ return _sampson_epipolar_distance_shared_impl_(pts1, pts2, Fm, squared, eps, 0.0 if matmul else eps)+ if matmul:+ return _sampson_epipolar_distance_matmul_impl_(pts1, pts2, Fm, squared, eps)return _sampson_epipolar_distance_manual_impl_(pts1, pts2, Fm, squared, eps)diff --git a/kornia/geometry/epipolar/fundamental.py b/kornia/geometry/epipolar/fundamental.pyindex 52864b9e0..f91c147e9 100644--- a/kornia/geometry/epipolar/fundamental.py+++ b/kornia/geometry/epipolar/fundamental.py@@ -25,7 +25,8 @@ import torchfrom kornia.core.check import KORNIA_CHECK_SAME_SHAPE, KORNIA_CHECK_SHAPEfrom kornia.core.utils import _torch_svd_cast, safe_inverse_with_maskfrom kornia.geometry.conversions import convert_points_from_homogeneous, convert_points_to_homogeneous-from kornia.geometry.solvers.polynomial_solver import _solve_cubic_with_count+from kornia.geometry.solvers.homogeneous import _det3, _null_space_lu+from kornia.geometry.solvers.polynomial_solver import _solve_cubic_realdef normalize_points(@@ -128,62 +129,289 @@ def normalize_transformation(M: torch.Tensor, eps: float = 1e-8) -> torch.Tensorreturn torch.where(mask, M / divisor, M)-def _nullspace_via_eigh(A: torch.Tensor) -> torch.Tensor:- """Compute the nullspace of a matrix A using the eigh method.+def _epipolar_design_rows(x1: torch.Tensor, x2: torch.Tensor) -> torch.Tensor:+ """Rows ``vec(x2 x1^T)`` of the epipolar constraint, so that ``row . vec(F) = x2^T F x1`` with ``F`` row-major.++ Each entry is one product ``x2_i x1_j``, so the constructions below give the same bits; the cheapest depends on+ the device. On CPU the broadcast outer product costs 2.5x the column-wise form (256 samples x 100 points: 402 vs+ 157 us); on CUDA it is one kernel instead of a dozen (12 vs 51 us).Args:- A: (..., 7, 9)+ x1: points of the first image, homogeneous ``(..., N, 3)`` or inhomogeneous ``(..., N, 2)`` with ``w = 1``.+ x2: points of the second image, in the same form as ``x1``.Returns:- N: (..., 9, 2) where columns span the right nullspace of A+ the design matrix ``(..., N, 9)``: ``[x2 x1, x2 y1, x2, y2 x1, y2 y1, y2, x1, y1, 1]`` for inhomogeneous+ points."""- AT = A.transpose(-2, -1) # (..., 9, 7)- G = AT @ A # (..., 9, 9) SPD- _evals, evecs = torch.linalg.eigh(G) # ascending eigenvalues- return evecs[..., :, :2] # eigenvectors for 2 smallest evals+ if x1.shape[-1] == 2:+ u1, v1 = torch.chunk(x1, dim=-1, chunks=2)+ u2, v2 = torch.chunk(x2, dim=-1, chunks=2)+ return torch.cat([u2 * u1, u2 * v1, u2, v2 * u1, v2 * v1, v2, u1, v1, torch.ones_like(u1)], dim=-1)+ if x1.device.type == "cpu":+ return torch.cat([x2[..., 0:1] * x1, x2[..., 1:2] * x1, x2[..., 2:3] * x1], dim=-1)+ return (x2[..., :, None] * x1[..., None, :]).flatten(-2)-def _F1F2_from_nullspace(N: torch.Tensor):- """Compute the F1 and F2 matrices from the nullspace of a matrix A.+def _seven_point_basis(A: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:+ """The two-dimensional null space of seven epipolar constraints ``(B, 7, 9)`` as two ``(B, 3, 3)`` matrices.- Args:- N: (..., 9, 2) where columns span the right nullspace of A- Returns:- F1: (..., 3, 3)- F2: (..., 3, 3)+ The null space comes from :func:`~kornia.geometry.solvers.homogeneous._null_space_lu`, in at least float32 since+ no backend factorizes half precision."""- F1 = N[..., 0].view(-1, 3, 3)- F2 = N[..., 1].view(-1, 3, 3)- return F1, F2+ solve_dtype = torch.promote_types(A.dtype, torch.float32)+ basis = _null_space_lu(A.to(solve_dtype)).mT.reshape(-1, 2, 3, 3).to(A.dtype)+ return basis[:, 0], basis[:, 1]-def _normalize_F(F: torch.Tensor, eps: float = 1e-12) -> torch.Tensor:- """Frobenius-normalize each 3x3 (keeps cubic coefficients well-scaled).+def _det_pencil_coefficients(f1: torch.Tensor, f2: torch.Tensor) -> torch.Tensor:+ r"""Coefficients ``(B, 4)`` of the cubic :math:`\det(x f_1 + f_2)`, highest degree first.- Args:- F: (..., 3, 3)- eps: small value to avoid unstabilities.+ Expanded by multilinearity in the rows, so neither matrix needs to be invertible: the leading coefficient is+ :math:`\det f_1` and the constant one :math:`\det f_2`.+ """+ a1, a2, a3 = f1[:, 0], f1[:, 1], f1[:, 2]+ b1, b2, b3 = f2[:, 0], f2[:, 1], f2[:, 2]+ crosses = torch.linalg.cross(torch.stack([a2, b2, a2, b2], 1), torch.stack([a3, b3, b3, a3], 1))+ x_aa, x_bb, x_ab = crosses[:, 0], crosses[:, 1], crosses[:, 2] + crosses[:, 3]+ dots = (torch.stack([a1, b1, a1, a1, b1, b1], 1) * torch.stack([x_aa, x_aa, x_ab, x_bb, x_ab, x_bb], 1)).sum(-1)+ return torch.stack([dots[:, 0], dots[:, 1] + dots[:, 2], dots[:, 3] + dots[:, 4], dots[:, 5]], 1)- Returns:- F: (..., 3, 3)++def _solve_dtype(device: torch.device) -> torch.dtype:+ """The dtype of the small closed-form steps: float64, except on MPS, which has none."""+ return torch.float32 if device.type == "mps" else torch.float64+++def _rank2_projection(F: torch.Tensor) -> torch.Tensor:+ r"""The nearest rank-2 matrices ``(B, 3, 3)`` in Frobenius norm, ``F (I - v v^T)`` for a smallest singular vector.++ ``v`` is an eigenvector of ``F^T F`` for its smallest eigenvalue :math:`\lambda_3`, found without an SVD: the+ eigenvalue from the trigonometric solution of the characteristic polynomial, the vector from the best cross+ product of two rows of ``F^T F - \lambda_3 I``. When :math:`\lambda_3` is repeated those rows span one direction or+ none and every cross product vanishes; any unit vector orthogonal to the rows is then a smallest singular vector:+ the cross product of the largest row with the coordinate axis least aligned to it, or ``e_3`` when every row+ vanishes. The nearest rank-2 matrix is not unique there, and this returns one of them.++ Runs in :func:`_solve_dtype` and returns ``F``'s dtype. ``sqrt``, ``acos`` and the normalizations take safe+ substitutes where their derivative is unbounded (#4229), so gradients stay finite.+ """+ dtype = F.dtype+ F = F.to(_solve_dtype(F.device))+ eye = torch.eye(3, dtype=F.dtype, device=F.device)+ M = F.mT @ F+ trace = M.diagonal(dim1=-2, dim2=-1).sum(-1)+ q = trace / 3+ shifted = M - q[:, None, None] * eye+ p2 = shifted.square().sum((-2, -1)) / 6+ spread = p2 > 0+ p = torch.where(spread, p2, torch.ones_like(p2)).sqrt()+ r = _det3(*(shifted / p[:, None, None]).flatten(-2).unbind(-1)) / 2+ inside = r.abs() < 1+ boundary = torch.where(r > 0, torch.zeros_like(r), torch.full_like(r, math.pi))+ angle = torch.where(inside, torch.acos(torch.where(inside, r, torch.zeros_like(r))), boundary) / 3+ smallest = q + torch.where(spread, 2 * p * torch.cos(angle + 2 * math.pi / 3), torch.zeros_like(p))+ rows = M - smallest[:, None, None] * eye+ crosses = torch.linalg.cross(rows[:, [0, 0, 1]], rows[:, [1, 2, 2]])+ cross_norms = crosses.square().sum(-1)+ best = cross_norms.argmax(1, keepdim=True)+ cross = crosses.gather(1, best[..., None].expand(-1, 1, 3))[:, 0]+ cross_norm = cross_norms.gather(1, best)[:, 0]+ row_norms = rows.square().sum(-1)+ top = row_norms.argmax(1, keepdim=True)+ row = rows.gather(1, top[..., None].expand(-1, 1, 3))[:, 0]+ row_norm = row_norms.gather(1, top)[:, 0]+ perpendicular = torch.linalg.cross(row, eye[row.abs().argmin(1)])+ # Rows are rounded at about eps * trace(F^T F); cross products and rows below that carry no direction.+ noise = (8 * torch.finfo(F.dtype).eps * trace).square()+ two_rows = cross_norm > noise * row_norm+ one_row = row_norm > noise+ v = torch.where(two_rows[:, None], cross, torch.where(one_row[:, None], perpendicular, eye[2].expand_as(cross)))+ norm = v.square().sum(-1)+ v = v * torch.where(norm > 0, norm, torch.ones_like(norm)).rsqrt()[:, None]+ return (F - (F @ v[:, :, None]) @ v[:, None, :]).to(dtype)+++# The closed-form rank-2 step costs about 45 small kernels whatever the batch: it is faster than a batched 3x3 SVD+# from 128 matrices on CPU (2048: 3.2 -> 0.8 ms) and from 512 on CUDA (2048: 3.2 -> 1.2 ms), slower below+# (i7-14700K / RTX 4090, torch 2.14).+_RANK2_CLOSED_FORM_MIN_BATCH_CPU = 128+_RANK2_CLOSED_FORM_MIN_BATCH_ACCELERATOR = 512+++def _enforce_rank2(F: torch.Tensor) -> torch.Tensor:+ """Remove the smallest singular value of ``(B, 3, 3)`` matrices.++ :func:`_rank2_projection` for large batches, an SVD for small ones, where it is cheaper. Without float64 (MPS) the+ closed form would run in float32, where its error grows like ``eps * (sigma_1 / sigma_2)^2`` through ``F^T F``, so+ the SVD is kept for every batch there.+ """+ threshold = _RANK2_CLOSED_FORM_MIN_BATCH_CPU if F.device.type == "cpu" else _RANK2_CLOSED_FORM_MIN_BATCH_ACCELERATOR+ if F.shape[0] >= threshold and _solve_dtype(F.device) == torch.float64:+ return _rank2_projection(F)+ U, S, V = _torch_svd_cast(F)+ S_new = torch.zeros_like(S)+ S_new[..., :-1] = S[..., :-1]+ return U @ torch.diag_embed(S_new) @ V.mH+++def _eight_point_null_vector(A: torch.Tensor) -> torch.Tensor:+ """The unit null vectors ``(B, 9)`` of eight epipolar constraints ``A`` ``(B, 8, 9)``, in ``A``'s dtype.++ One batched LU factorization (:func:`~kornia.geometry.solvers.homogeneous._null_space_lu`) finds them much faster+ than ``eigh`` of ``A^T A``, which loops over the batch on CPU and squares the condition number; the factorization+ runs in at least float32 since no backend factorizes half precision.+ """+ h = _null_space_lu(A.to(torch.promote_types(A.dtype, torch.float32)))[..., 0]+ return (h / h.norm(dim=-1, keepdim=True)).to(A.dtype)+++def _eight_point_fundamental(A: torch.Tensor) -> torch.Tensor:+ """Rank-2 fundamental matrices ``(B, 3, 3)`` from eight epipolar constraints ``A`` ``(B, 8, 9)``, in ``A``'s dtype.++ :func:`_eight_point_null_vector` followed by :func:`_rank2_projection`: RANSAC's eight-point sampler, which passes+ rows of points it normalized once per call, in batches large enough for the closed form."""- nrm = F.norm(dim=(-2, -1), p=1, keepdim=True).clamp_min(eps)- return F / nrm+ return _rank2_projection(_eight_point_null_vector(A).reshape(-1, 3, 3))++def _seven_point_candidates(A: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:+ """Fundamental matrices through seven correspondences, one per real root of ``det(x f_1 + f_2) = 0``.-# Reference: Adapted from the 'run_7point' function in opencv-# https://github.com/opencv/opencv/blob/4.x/modules/calib3d/src/fundam.cpp-def _isclose0(x: torch.Tensor, eps: float = 1e-12) -> torch.Tensor:- # torch.isclose(x, 0) but TorchScript/GPU-friendly (no scalar tensor creation)- return x.abs() <= eps+ The two-dimensional null space ``x f_1 + f_2`` of the constraints ``A`` ``(B, 7, 9)`` (:func:`_epipolar_design_rows`+ of normalized points) is completed by the real roots of its determinant (Hartley and Zisserman, section 11.1.2), so+ every candidate has rank two. The cubic is solved in :func:`_solve_dtype`, choosing its leading matrix from+ ``f_1``, ``f_2``, ``f_1 + f_2`` and ``f_1 - f_2`` to maximize the leading determinant. These four evaluations+ determine the homogeneous cubic, so both singular basis matrices still give a well-conditioned parametrization.++ Returns:+ Candidates ``(B, 3, 3, 3)`` of unit Frobenius norm in ``A``'s dtype, and a mask ``(B, 3)`` of the real roots+ with finite candidates. A cubic with one real root repeats its candidate in the two masked slots rather than+ producing NaN, so that masking them afterwards leaves finite gradients.+ """+ solve_dtype = _solve_dtype(A.device)+ f1, f2 = (f.to(solve_dtype) for f in _seven_point_basis(A))+ coefficients = _det_pencil_coefficients(f1, f2)+ a, b, c, d = coefficients.unbind(1)+ # For lead = f1 +/- f2 and rest = f2, substitute (x, +/-x + 1) into the homogeneous cubic.+ plus = torch.stack([a + b + c + d, b + 2 * c + 3 * d, c + 3 * d, d], 1)+ minus = torch.stack([a - b + c - d, b - 2 * c + 3 * d, c - 3 * d, d], 1)+ choices = torch.stack([coefficients, coefficients.flip(1), plus, minus], 1)+ best = choices[:, :, 0].abs().argmax(1)+ coefficients = choices.gather(1, best[:, None, None].expand(-1, 1, 4))[:, 0]+ directions = torch.stack([f1, f2, f1 + f2, f1 - f2], 1)+ lead = directions.gather(1, best[:, None, None, None].expand(-1, 1, 3, 3))[:, 0]+ rest = torch.where((best == 1)[:, None, None], f1, f2)+ # An identically zero determinant has no isolated roots. Substitute a finite cubic before masking the row.+ isolated = coefficients[:, 0] != 0+ fallback = coefficients.new_tensor([1.0, 0.0, 0.0, 0.0])+ roots, valid = _solve_cubic_real(torch.where(isolated[:, None], coefficients, fallback))+ valid = valid & isolated[:, None]+ F = roots[:, :, None, None] * lead[:, None] + rest[:, None]+ F = F * F.square().sum((-2, -1), keepdim=True).rsqrt()+ return F.to(A.dtype), valid & torch.isfinite(F).flatten(-2).all(-1)+++def _robust_loss(r2: torch.Tensor, loss: str, scale2: float) -> Tuple[torch.Tensor, torch.Tensor]:+ """IRLS weights and costs of a squared residual: Cauchy, or truncated at ``scale2``."""+ if loss == "cauchy":+ return 1.0 / (1.0 + r2 / scale2), torch.log1p(r2 / scale2)+ return (r2 < scale2).to(r2.dtype), torch.fmin(r2, torch.full_like(r2[:1, :1], scale2))+++def _hat_basis(dtype: torch.dtype, device: torch.device) -> torch.Tensor:+ """``E[a] = [e_a]_x``, the generators of rotations, as ``(3, 3, 3)``."""+ E = torch.zeros(3, 3, 3, dtype=dtype, device=device)+ E[0, 1, 2], E[0, 2, 1] = -1.0, 1.0+ E[1, 0, 2], E[1, 2, 0] = 1.0, -1.0+ E[2, 0, 1], E[2, 1, 0] = -1.0, 1.0+ return E+++def _refine_fundamental_lm(+ F: torch.Tensor,+ x1: torch.Tensor,+ x2: torch.Tensor,+ mask: Optional[torch.Tensor],+ loss: str,+ scale2: float,+ iters: int,+) -> torch.Tensor:+ """Levenberg-Marquardt on the Sampson distance, batched over fundamental matrices ``(K, 3, 3)``.++ In the spirit of PoseLib's ``refine_fundamental`` (Larsson and contributors, https://github.com/PoseLib/PoseLib):+ ``F = U diag(1, s, 0) V^T`` with rotations ``U``, ``V`` updated by Cayley steps, the seven-parameter factorization+ of Bartoli and Sturm, "Nonlinear estimation of the fundamental matrix with minimal parameters", TPAMI 2004. Each+ iteration takes the residuals and their Jacobian from two matrix products with per-correspondence monomials.+ ``x1`` and ``x2`` are homogeneous ``(N, 3)`` points, normalized by the caller. ``loss`` is ``"truncated"`` or+ ``"cauchy"`` with squared scale ``scale2``; ``mask`` (``(K, N)``) restricts each model to its correspondences. A+ step is kept only if it lowers the cost. For RANSAC, under ``torch.no_grad``.+ """+ K = F.shape[0]+ dtype, device = F.dtype, F.device+ E = _hat_basis(dtype, device)+ eye3 = torch.eye(3, dtype=dtype, device=device)+ eye7 = torch.eye(7, dtype=dtype, device=device)+ algebraic = _epipolar_design_rows(x1, x2).T # (9, N)+ quadratic = torch.cat([_epipolar_design_rows(x1, x1), _epipolar_design_rows(x2, x2)], 1).T # (18, N)+ U, S, Vh = torch.linalg.svd(F)+ V = Vh.mT+ # Proper rotations: the third singular vectors do not enter F, so their signs are free.+ U = torch.cat([U[..., :2], U[..., 2:] * torch.linalg.det(U).sign()[:, None, None]], -1)+ V = torch.cat([V[..., :2], V[..., 2:] * torch.linalg.det(V).sign()[:, None, None]], -1)+ UV = torch.stack([U, V], 1)+ sigma = S[:, 1] / S[:, 0].clamp(min=torch.finfo(dtype).tiny)+ damping = torch.full((K, 1, 1), 1e-3, dtype=dtype, device=device)++ def compose(UV: torch.Tensor, sigma: torch.Tensor) -> torch.Tensor:+ scale = torch.stack([torch.ones_like(sigma), sigma], 1)[:, None, :]+ return (UV[:, 0, :, :2] * scale) @ UV[:, 1, :, :2].mT++ def normal_equations(F: torch.Tensor, UV: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:+ # Directions dF/dp: E_a F (left rotation), -F E_a (right rotation), u_2 v_2^T (singular value ratio).+ tangent = torch.cat(+ [E @ F[:, None], (F[:, None] @ E).neg(), (UV[:, 0, :, 1:2] @ UV[:, 1, :, 1:2].mT)[:, None]], 1+ )+ stacked = torch.cat([F[:, None], tangent], 1) # (K, 8, 3, 3): F, then the seven directions+ # x1^T (F[:2]^T X[:2]) x1 + x2^T (F[:, :2] X[:, :2]^T) x2 is half the derivative of the squared gradient norm.+ quad1 = F[:, None, :2, :].mT @ stacked[:, :, :2, :]+ quad2 = F[:, None, :, :2] @ stacked[:, :, :, :2].mT+ out_c = stacked.reshape(K, 8, 9) @ algebraic+ out_g = torch.cat([quad1, quad2], 2).reshape(K, 8, 18) @ quadratic+ inv = out_g[:, 0].rsqrt()+ r = out_c[:, 0] * inv+ J = (out_c[:, 1:] - (r * inv)[:, None] * out_g[:, 1:]) * inv[:, None] # (K, 7, N)+ w, rho = _robust_loss(r * r, loss, scale2)+ if mask is not None:+ w, rho = w * mask, rho * mask+ Jw = J * w[:, None]+ return torch.cat([Jw @ J.mT, Jw @ r[..., None]], 2), rho.sum(1)++ F = compose(UV, sigma)+ system, cost = normal_equations(F, UV)+ for _ in range(iters):+ delta = -torch.linalg.solve_ex(system[..., :7] + damping * eye7, system[..., 7:])[0][..., 0]+ half = delta[:, :6].reshape(K * 2, 3) * 0.5+ skew = (half @ E.reshape(3, 9)).reshape(K, 2, 3, 3)+ factor = (2.0 / (1.0 + half.square().sum(1))).reshape(K, 2, 1, 1)+ UV_new = (eye3 + factor * (skew + skew @ skew)) @ UV # Cayley transform of the half-angle skew matrix+ sigma_new = sigma + delta[:, 6]+ F_new = compose(UV_new, sigma_new)+ system_new, cost_new = normal_equations(F_new, UV_new)+ accept = (cost_new < cost)[:, None, None]+ UV = torch.where(accept[..., None], UV_new, UV)+ F, system = torch.where(accept, F_new, F), torch.where(accept, system_new, system)+ sigma, cost = torch.where(accept[:, 0, 0], sigma_new, sigma), torch.where(accept[:, 0, 0], cost_new, cost)+ damping = damping * torch.where(accept, 0.1, 10.0)+ return Fdef run_7point(points1: torch.Tensor, points2: torch.Tensor) -> torch.Tensor:r"""Compute the fundamental matrix using the 7-point algorithm.The 7-point algorithm computes the fundamental matrix from exactly 7 point correspondences.- Unlike the 8-point algorithm, this method returns 3 candidate fundamental matrices, one per root of the- cubic that formulates the rank-2 constraint, padded to three.+ Unlike the 8-point algorithm, this method returns 3 candidate fundamental matrices, one per real root of the+ cubic that formulates the rank-2 constraint, padded to three with zero matrices.Reference: Hartley/Zisserman 11.1.2 pag.281@@ -199,82 +427,15 @@ def run_7point(points1: torch.Tensor, points2: torch.Tensor) -> torch.Tensor:KORNIA_CHECK_SHAPE(points1, ["B", "7", "2"])KORNIA_CHECK_SHAPE(points2, ["B", "7", "2"])- B = points1.shape[0]- device = points1.device- dtype = points1.dtype-+ # Reference: Hartley and Zisserman, section 11.1.2; the cubic follows OpenCV's run7Point+ # (https://github.com/opencv/opencv/blob/4.x/modules/calib3d/src/fundam.cpp).points1_norm, transform1 = normalize_points(points1)points2_norm, transform2 = normalize_points(points2)-- x1, y1 = torch.chunk(points1_norm, dim=-1, chunks=2) # (B,7,1)- x2, y2 = torch.chunk(points2_norm, dim=-1, chunks=2) # (B,7,1)- ones = torch.ones_like(x1)-- # (B,7,9)- X = torch.cat([x2 * x1, x2 * y1, x2, y2 * x1, y2 * y1, y2, x1, y1, ones], dim=-1)-- # nullspace basis -> (B,3,3)- f1, f2 = _F1F2_from_nullspace(_nullspace_via_eigh(X))- f1 = _normalize_F(f1)- f2 = _normalize_F(f2)-- # --- cubic coeffs (keep your known-good inverse-based formula) ---- coeffs = torch.zeros((B, 4), device=device, dtype=dtype)- f1_det = torch.linalg.det(f1)- f2_det = torch.linalg.det(f2)-- inv_f1, _ = safe_inverse_with_mask(f1)- inv_f2, _ = safe_inverse_with_mask(f2)-- coeffs[:, 0] = f1_det- coeffs[:, 1] = torch.einsum("bii->b", f2 @ inv_f1) * f1_det- coeffs[:, 2] = torch.einsum("bii->b", f1 @ inv_f2) * f2_det- coeffs[:, 3] = f2_det-- roots, num_real = _solve_cubic_with_count(coeffs) # (B,3), (B,)-- # The real roots fill the first num_real slots; the rest are solve_cubic's 0.0 padding, not roots.- valid_root_mask = torch.arange(3, device=device) < num_real.unsqueeze(1) # (B,3) bool-- # --- compute lambda/mu for ALL batches (no compaction) ---- _lambda = roots.clone()- _mu = torch.ones_like(_lambda)-- # _s = f1[2,2] * root + f2[2,2] for each of 3 roots- f1_22 = f1[:, 2, 2].unsqueeze(1) # (B,1)- f2_22 = f2[:, 2, 2].unsqueeze(1) # (B,1)- _s = f1_22 * roots + f2_22 # (B,3)-- # avoid torch.isclose with scalar tensor creation- _s_non_zero_mask = ~_isclose0(_s, 1e-12) # (B,3) bool-- # mu = 1/s where s != 0, else mu stays 1- mu_new = torch.where(_s_non_zero_mask, 1.0 / _s, _mu)- lam_new = torch.where(_s_non_zero_mask, _lambda * mu_new, _lambda)-- _mu = mu_new- _lambda = lam_new-- # --- form candidates for ALL batches: F = f1*lambda + f2*mu ---- f1_expanded = f1.unsqueeze(1).expand(B, 3, 3, 3)- f2_expanded = f2.unsqueeze(1).expand(B, 3, 3, 3)-- fmatrix = f1_expanded * _lambda[:, :, None, None] + f2_expanded * _mu[:, :, None, None] # (B,3,3,3)-- # --- enforce last element handling like your original ---- # If s != 0 set F[2,2]=1 else set to 0 (per-candidate)- # This is exactly what your boolean-indexing version did, but without advanced indexing.- f22 = torch.where(_s_non_zero_mask, torch.ones_like(_s, dtype=dtype), torch.zeros_like(_s, dtype=dtype))- fmatrix[:, :, 2, 2] = f22 # (B,3)-- # --- zero the candidates of padded roots (no compaction) ---- fmatrix = torch.where(valid_root_mask.view(B, 3, 1, 1), fmatrix, torch.zeros_like(fmatrix))-- # --- denormalize for ALL batches ---- # F = T2^T * F * T1- fmatrix = (transform2.unsqueeze(1).transpose(-2, -1) @ fmatrix) @ transform1.unsqueeze(1)-- return normalize_transformation(fmatrix)+ A = _epipolar_design_rows(points1_norm, points2_norm)+ candidates, valid = _seven_point_candidates(A)+ # F = T2^T F T1+ fmatrix = normalize_transformation(transform2[:, None].mT @ candidates @ transform1[:, None])+ return torch.where(valid[..., None, None], fmatrix, torch.zeros_like(fmatrix))def run_8point(@@ -308,48 +469,43 @@ def run_8point(pts1n, T1 = normalize_points(points1, weights=weights)pts2n, T2 = normalize_points(points2, weights=weights)- x1, y1 = torch.chunk(pts1n, dim=-1, chunks=2) # (B,N,1)- x2, y2 = torch.chunk(pts2n, dim=-1, chunks=2) # (B,N,1)- ones = torch.ones_like(x1)-# Design matrix rows A_i = [x2*x1, x2*y1, x2, y2*x1, y2*y1, y2, x1, y1, 1]# Shape: A β (B, N, 9)- A = torch.cat([x2 * x1, x2 * y1, x2, y2 * x1, y2 * y1, y2, x1, y1, ones], dim=-1).squeeze(-2)+ A = _epipolar_design_rows(pts1n, pts2n)B, N, _ = A.shape- # Build normal matrix M = A^T W A (B,9,9) without forming NxN diagonals.- if weights is None:- if N < use_einsum_at_more_than_points:- # Use GEMM on tall A: (B,9,N) @ (B,N,9)- M = A.transpose(-2, -1).contiguous() @ A- else:- # Accumulate via einsum (saves bandwidth for huge N)- M = torch.einsum("bni,bnj->bij", A, A)+ if weights is None and N == 8:+ # A minimal sample has an exact null vector.+ h = _eight_point_null_vector(A)else:- # Negative weights count as zero. A weight of exactly 0 is the documented way to drop a correspondence, and- # its gradient should be the one-sided derivative from above. ``clamp_min(0)`` passes the gradient through- # at the bound on torch 2.5.1 and 2.9.1 but returns 0 on 2.14 (#4229); ``where`` passes it on every version.- w = torch.where(weights < 0, 0.0, weights)- if N < use_einsum_at_more_than_points:- # Scale one factor by w instead of both by sqrt(w). Both build the same A^T W A, but the derivative- # of sqrt is unbounded at 0, so a zero weight got a NaN gradient. This form is linear in w, like the- # einsum branch below.- Aw = A * w.unsqueeze(-1)- M = Aw.transpose(-2, -1).contiguous() @ A+ # Build normal matrix M = A^T W A (B,9,9) without forming NxN diagonals.+ if weights is None:+ if N < use_einsum_at_more_than_points:+ # Use GEMM on tall A: (B,9,N) @ (B,N,9)+ M = A.transpose(-2, -1).contiguous() @ A+ else:+ # Accumulate via einsum (saves bandwidth for huge N)+ M = torch.einsum("bni,bnj->bij", A, A)else:- # Weighted einsum- M = torch.einsum("bni,bnj,bn->bij", A, A, w)-- _evals, evecs = torch.linalg.eigh(M) # ascending order- h = evecs[..., 0] # (B,9), eigenvector for smallest Ξ»- F_hat = h.view(B, 3, 3)-- # Enforce rank-2 with a 3x3 SVD- U, S, V = _torch_svd_cast(F_hat)- S_new = torch.zeros_like(S)- S_new[..., :-1] = S[..., :-1]- F_rank2 = U @ torch.diag_embed(S_new) @ V.mH+ # Negative weights count as zero. A weight of exactly 0 is the documented way to drop a correspondence,+ # and its gradient should be the one-sided derivative from above. ``clamp_min(0)`` passes the gradient+ # through at the bound on torch 2.5.1 and 2.9.1 but returns 0 on 2.14 (#4229); ``where`` passes it on+ # every version.+ w = torch.where(weights < 0, 0.0, weights)+ if N < use_einsum_at_more_than_points:+ # Scale one factor by w instead of both by sqrt(w). Both build the same A^T W A, but the+ # derivative of sqrt is unbounded at 0, so a zero weight got a NaN gradient. This form is linear in+ # w, like the einsum branch below.+ Aw = A * w.unsqueeze(-1)+ M = Aw.transpose(-2, -1).contiguous() @ A+ else:+ # Weighted einsum+ M = torch.einsum("bni,bnj,bn->bij", A, A, w)++ _evals, evecs = torch.linalg.eigh(M) # ascending order+ h = evecs[..., 0] # (B,9), eigenvector for smallest Ξ»+ F_rank2 = _enforce_rank2(h.reshape(B, 3, 3))F = T2.transpose(-2, -1) @ (F_rank2 @ T1)return normalize_transformation(F)diff --git a/kornia/geometry/homography.py b/kornia/geometry/homography.pyindex fa7fdc29f..8d8b8ccc2 100644--- a/kornia/geometry/homography.py+++ b/kornia/geometry/homography.py@@ -24,7 +24,10 @@ from kornia.core.check import KORNIA_CHECK_SHAPEfrom kornia.core.utils import _extract_device_dtype, _torch_svd_cast, safe_inverse_with_mask, safe_solve_with_maskfrom kornia.geometry.conversions import convert_points_from_homogeneous, convert_points_to_homogeneousfrom kornia.geometry.epipolar import normalize_points, normalize_transformation+from kornia.geometry.epipolar._metrics import _shares_points+from kornia.geometry.epipolar.fundamental import _robust_lossfrom kornia.geometry.linalg import transform_points+from kornia.geometry.solvers.homogeneous import _null_space_lu__all__ = ["find_homography_dlt",@@ -48,6 +51,9 @@ def oneway_transfer_error(Convention:- ``oneway_transfer_error(pts1, pts2, H)`` measures in image 2, between ``H`` applied to ``pts1`` and``pts2``.+ - One set of correspondences scored against several homographies (points with leading dimensions of+ size 1) is computed from one matrix product for all of them, in at least float32; the result matches the+ per-homography computation to roundoff.- ``squared=True``, the default here and in :func:`symmetric_transfer_error`, returns the squareddistance; :func:`line_segment_transfer_error_one_way` defaults to ``squared=False``.- Known defects: ``eps`` is added to the projective denominator and inside the square root, so the error@@ -68,6 +74,8 @@ def oneway_transfer_error("""KORNIA_CHECK_SHAPE(H, ["B", "3", "3"])+ if H.shape[0] >= 2 and _shares_points(pts1, pts2):+ return _oneway_transfer_error_shared_impl_(pts1, pts2, H, squared, eps)if pts1.shape[-1] == 3:x1y1 = convert_points_from_homogeneous(pts1)@@ -226,6 +234,159 @@ def _line_segment_squared_distance_one_way(ls1: torch.Tensor, ls2: torch.Tensor,return torch.where(length > 0, distance.square(), torch.full_like(distance, float("inf")))+def _homography_rows(p1: torch.Tensor, points2: torch.Tensor) -> torch.Tensor:+ """DLT rows ``(..., 2N, 9)`` of homogeneous ``p1`` ``(..., N, 3)`` with unit last coordinate and ``points2``.++ Two rows per correspondence, ``[0, -p1, y2 p1]`` and ``[p1, 0, -x2 p1]``, so that ``row . vec(H) = 0`` for+ ``points2 ~ H p1`` with ``H`` row-major; only the first two coordinates of ``points2`` are read.+ """+ # DIAPO 11: https://www.uio.no/studier/emner/matnat/its/nedlagte-emner/UNIK4690/v16/forelesninger/lecture_4_3-estimating-homographies-from-feature-correspondences.pdf # noqa: E501+ zeros = torch.zeros_like(p1)+ ax = torch.cat([zeros, -p1, points2[..., 1:2] * p1], dim=-1)+ ay = torch.cat([p1, zeros, -points2[..., 0:1] * p1], dim=-1)+ return torch.stack([ax, ay], dim=-2).flatten(-3, -2)+++def _homography_design_rows(points1: torch.Tensor, points2: torch.Tensor) -> torch.Tensor:+ """DLT rows ``(..., 2N, 9)`` of correspondences ``(..., N, 2)``, as :func:`_homography_rows`.++ Each entry is the product the rows used to be written out with coordinate by coordinate, in fewer kernels.+ """+ return _homography_rows(torch.cat([points1, torch.ones_like(points1[..., :1])], dim=-1), points2)+++def _four_point_homography(x1: torch.Tensor, x2: torch.Tensor) -> torch.Tensor:+ """Homographies ``(B, 3, 3)`` of unit Frobenius norm through four normalized correspondences.++ ``x1`` is homogeneous ``(B, 4, 3)`` with unit last coordinate and ``x2`` ``(B, 4, 2)`` or homogeneous. The null+ vector of :func:`_homography_rows` comes from :func:`~kornia.geometry.solvers.homogeneous._null_space_lu`, in at+ least float32. Unlike :func:`find_homography_dlt` there is no per-sample normalization, gauge solve or+ ``H[2, 2] = 1`` scaling: RANSAC's sampler normalizes once per call and scores unit-norm models.+ """+ A = _homography_rows(x1, x2)+ h = _null_space_lu(A.to(torch.promote_types(A.dtype, torch.float32)))[..., 0]+ return (h * h.square().sum(-1, keepdim=True).rsqrt()).reshape(-1, 3, 3).to(x1.dtype)+++def _transfer_errors(H: torch.Tensor, x1: torch.Tensor, x2: torch.Tensor, eps: float) -> torch.Tensor:+ """Squared one-way transfer errors ``(M, N)`` of homographies ``(M, 3, 3)`` on one set of correspondences.++ ``x1`` is homogeneous ``(N, 3)`` with unit last coordinate and ``x2`` ``(N, 2)``. ``H x1`` of every model is one+ ``(3M, 3) @ (3, N)`` product; the rest is :func:`oneway_transfer_error`'s formula, ``eps`` in the projective+ denominator included.+ """+ m, n = H.shape[0], x1.shape[0]+ projected = (H.reshape(3 * m, 3) @ x1.T).view(m, 3, n)+ w = projected[:, 2] + eps+ return (projected[:, 0] / w - x2[:, 0]).square() + (projected[:, 1] / w - x2[:, 1]).square()+++def _oneway_transfer_error_shared_impl_(+ pts1: torch.Tensor, pts2: torch.Tensor, H: torch.Tensor, squared: bool, eps: float+) -> torch.Tensor:+ """One-way transfer errors of many homographies on one set of correspondences, by :func:`_transfer_errors`.++ ``pts1`` and ``pts2`` have leading dimensions of size 1; homogeneous points are dehomogenized. Half precision is+ computed in float32 and returned in the input dtype.+ """+ num_points = pts1.shape[-2]+ dtype = torch.promote_types(torch.promote_types(pts1.dtype, pts2.dtype), H.dtype)+ work = torch.promote_types(dtype, torch.float32)+ x1 = pts1.reshape(num_points, pts1.shape[-1]).to(work)+ x2 = pts2.reshape(num_points, pts2.shape[-1]).to(work)+ if x1.shape[-1] == 3:+ x1 = convert_points_from_homogeneous(x1)+ if x2.shape[-1] == 3:+ x2 = convert_points_from_homogeneous(x2)+ err2 = _transfer_errors(H.to(work), convert_points_to_homogeneous(x1), x2, eps)+ out = err2 if squared else (err2 + eps).sqrt()+ shape = torch.broadcast_shapes(pts1.shape[:-2], pts2.shape[:-2], H.shape[:-2])+ return out.reshape(*shape, num_points).to(dtype)+++def _transfer_basis(x1: torch.Tensor, x2: torch.Tensor) -> torch.Tensor:+ """Per-correspondence monomials ``(9, 3N)`` of the one-way transfer error, for RANSAC's sampling loop only.++ ``vec(H) @ basis`` is ``[P_0 - u P_2 | P_1 - v P_2 | P_2]`` for ``P = H x1`` and ``x2 = (u, v)``, with ``x1``+ homogeneous ``(N, 3)``. Folding the subtraction into the product is about 10% faster than+ :func:`_transfer_errors` in RANSAC's loop on CPU (2048 models x 500 points: 6.6 against 7.2 ms) and 20-35 us per+ CUDA batch of 512-8192 models; it is accurate on normalized points, but in pixel units its float32 error was 2.5x+ that of :func:`oneway_transfer_error`.+ """+ n = x1.shape[0]+ basis = x1.new_zeros(9, 3 * n)+ basis[0:3, :n] = x1.T+ basis[6:9, :n] = -(x2[:, 0:1] * x1).T+ basis[3:6, n : 2 * n] = x1.T+ basis[6:9, n : 2 * n] = -(x2[:, 1:2] * x1).T+ basis[6:9, 2 * n :] = x1.T+ return basis+++def _transfer_from_basis(H: torch.Tensor, basis: torch.Tensor) -> torch.Tensor:+ """Squared one-way transfer errors ``(M, N)`` of homographies ``(M, 3, 3)`` from :func:`_transfer_basis`."""+ n = basis.shape[1] // 3+ out = H.flatten(1) @ basis+ return (out[:, :n].square() + out[:, n : 2 * n].square()) / out[:, 2 * n :].square()+++def _refine_homography_lm(+ H: torch.Tensor,+ x1: torch.Tensor,+ x2: torch.Tensor,+ mask: Optional[torch.Tensor],+ loss: str,+ scale2: float,+ iters: int,+) -> torch.Tensor:+ """Levenberg-Marquardt on the one-way transfer error, batched over homographies ``(K, 3, 3)``.++ In the spirit of PoseLib's ``refine_homography``: steps are taken in the eight-dimensional orthogonal complement of+ the unit-norm ``vec(H)`` and renormalized. ``x1`` is homogeneous ``(N, 3)`` and ``x2`` ``(N, 2)``, normalized by+ the caller; the loss, ``mask`` and step acceptance are those of+ :func:`~kornia.geometry.epipolar.fundamental._refine_fundamental_lm`. For RANSAC, under ``torch.no_grad``.+ """+ K = H.shape[0]+ dtype, device = H.dtype, H.device+ eye8 = torch.eye(8, dtype=dtype, device=device)+ eye9 = torch.eye(9, dtype=dtype, device=device)+ last = eye9[8]+ target = torch.cat([x2[:, 0], x2[:, 1]])+ h = H.flatten(1)+ h = h * h.square().sum(1, keepdim=True).rsqrt()+ damping = torch.full((K, 1, 1), 1e-3, dtype=dtype, device=device)++ def normal_equations(h: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:+ # Householder reflection of h onto the last axis: its other eight columns span the tangent space.+ v = h + torch.where(h[:, 8:9] >= 0, 1.0, -1.0) * last+ v = v * v.square().sum(1, keepdim=True).rsqrt()+ tangent = (eye9 - 2 * v[:, :, None] * v[:, None, :])[:, :, :8] # (K, 9, 8)+ stacked = torch.cat([h[:, :, None], tangent], 2).mT.reshape(K, 27, 3) # rows of H, then of each direction+ P = (stacked @ x1.T).reshape(K, 9, 3, -1) # (K, 9, 3, N): P = H x1, then its directional derivatives+ iz = 1.0 / P[:, 0, 2]+ uv = P[:, 0, :2] * iz[:, None] # (K, 2, N)+ r = uv.flatten(1) - target # (K, 2N): u residuals, then v residuals+ J = ((P[:, 1:, :2] - uv[:, None] * P[:, 1:, 2:3]) * iz[:, None, None]).flatten(2) # (K, 8, 2N)+ r2 = r[:, : x1.shape[0]].square() + r[:, x1.shape[0] :].square()+ w, rho = _robust_loss(r2, loss, scale2)+ if mask is not None:+ w, rho = w * mask, rho * mask+ Jw = J * torch.cat([w, w], 1)[:, None]+ return torch.cat([Jw @ J.mT, Jw @ r[..., None]], 2), rho.sum(1), tangent++ system, cost, tangent = normal_equations(h)+ for _ in range(iters):+ delta = -torch.linalg.solve_ex(system[..., :8] + damping * eye8, system[..., 8:])[0]+ h_new = h + (tangent @ delta)[..., 0]+ h_new = h_new * h_new.square().sum(1, keepdim=True).rsqrt()+ system_new, cost_new, tangent_new = normal_equations(h_new)+ accept = (cost_new < cost)[:, None, None]+ h, cost = torch.where(accept[:, :, 0], h_new, h), torch.where(accept[:, 0, 0], cost_new, cost)+ system, tangent = torch.where(accept, system_new, system), torch.where(accept, tangent_new, tangent)+ damping = damping * torch.where(accept, 0.1, 10.0)+ return h.reshape(K, 3, 3)++def find_homography_dlt(points1: torch.Tensor, points2: torch.Tensor, weights: Optional[torch.Tensor] = None, solver: str = "lu") -> torch.Tensor:@@ -278,14 +439,7 @@ def _homography_dlt_system(points1_norm, transform1 = normalize_points(points1, weights=weights)points2_norm, transform2 = normalize_points(points2, weights=weights)- x1, y1 = torch.chunk(points1_norm, dim=-1, chunks=2) # BxNx1- x2, y2 = torch.chunk(points2_norm, dim=-1, chunks=2) # BxNx1- ones, zeros = torch.ones_like(x1), torch.zeros_like(x1)-- # DIAPO 11: https://www.uio.no/studier/emner/matnat/its/nedlagte-emner/UNIK4690/v16/forelesninger/lecture_4_3-estimating-homographies-from-feature-correspondences.pdf # noqa: E501- ax = torch.cat([zeros, zeros, zeros, -x1, -y1, -ones, y2 * x1, y2 * y1, y2], dim=-1)- ay = torch.cat([x1, y1, ones, zeros, zeros, zeros, -x2 * x1, -x2 * y1, -x2], dim=-1)- A = torch.cat((ax, ay), dim=-1).reshape(ax.shape[0], -1, ax.shape[-1])+ A = _homography_design_rows(points1_norm, points2_norm)return A, transform1, transform2@@ -334,10 +488,11 @@ def _homography_from_dlt_system(else:# A four-point sample gives eight equations for nine unknowns, so the normal matrix# is singular and LU-factoring it is what produced all-NaN homographies. Work from- # the design matrix instead: its null vector comes from a complete QR, the largest- # component of that vector fixes the homogeneous gauge, and the retained 8x8 system- # is solved for the rest. A fixed h33=1 gauge is invalid whenever the bottom-right- # entry is zero. Five or more points keep the normal-equation formulation above.+ # the design matrix instead: its null vector comes from a pivoted LU factorization of+ # it, the largest component of that vector fixes the homogeneous gauge, and the+ # retained 8x8 system is solved for the rest. A fixed h33=1 gauge is invalid whenever+ # the bottom-right entry is zero. Five or more points keep the normal-equation+ # formulation above.Aw = A if w_full is None else A * w_full.transpose(-2, -1)# torch.linalg.qr on CUDA can spin forever on a design matrix that mixes NaN with the# structured zeros of the DLT rows (#4770). Hand QR and the solve finite entries only,@@ -347,14 +502,12 @@ def _homography_from_dlt_system(Aw = torch.where(finite_entries, Aw, torch.zeros_like(Aw))gauge_dtype = torch.float64 if dtype == torch.float64 else torch.float32design = Aw.detach().to(gauge_dtype)- if device.type == "cuda":- # torch.linalg.qr has no batched CUDA kernel: it factors the B matrices one cusolver call at a- # time (~0.1 ms each), so a 2048-sample RANSAC batch spent ~250 ms here. The batched Jacobi- # SVD is one kernel (~1 ms for 2048) and its null vector agrees with the QR one to roundoff.- null = torch.linalg.svd(design)[2][..., -1, :]- else:- Q, _ = torch.linalg.qr(design.transpose(-2, -1), mode="complete")- null = Q[..., -1]+ # One batched LU factorization on every backend: torch.linalg.qr has no batched CUDA kernel+ # (one cusolver call per matrix, ~250 ms for a 2048-sample RANSAC batch), and a batched SVD or+ # QR costs about three times the LU on CPU. A zero-weight correspondence leaves the null vector+ # finite, since the unit triangular factor the basis is solved from is never singular.+ null = _null_space_lu(design)[..., 0]+ null = null / null.norm(dim=-1, keepdim=True)gauge = null.abs().argmax(dim=-1)retained = torch.arange(8, device=device).expand(A.shape[0], -1)retained = retained + (retained >= gauge[:, None]).to(retained.dtype)@@ -440,14 +593,15 @@ def sample_is_valid_for_homography(points1: torch.Tensor, points2: torch.Tensor)"""if points1.shape != points2.shape:raise AssertionError(points1.shape)- # Triples to test: (0,1,2), (0,1,3), (0,2,3), (1,2,3)- idx_i = torch.tensor([0, 0, 0, 1], device=points1.device)- J = torch.tensor([1, 1, 2, 2], device=points1.device)- K = torch.tensor([2, 3, 3, 3], device=points1.device)-- # Gather the triples for both sets: shape (B, 4, 2)- p1_i, p1_j, p1_k = points1[:, idx_i], points1[:, J], points1[:, K]- p2_i, p2_j, p2_k = points2[:, idx_i], points2[:, J], points2[:, K]++ # Triples to test: (0,1,2), (0,1,3), (0,2,3), (1,2,3), gathered by slicing, shape (B, 4, 2). Index tensors+ # would be copied to the device on every call.+ def _triples(points: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:+ p0, p1, p2, p3 = points[:, 0], points[:, 1], points[:, 2], points[:, 3]+ return torch.stack([p0, p0, p0, p1], 1), torch.stack([p1, p1, p2, p2], 1), torch.stack([p2, p3, p3, p3], 1)++ p1_i, p1_j, p1_k = _triples(points1)+ p2_i, p2_j, p2_k = _triples(points2)# 2D orientation (signed area) for each triple:# orient(a,b,c) = cross2d(b-a, c-a) = (bx-ax)*(cy-ay) - (by-ay)*(cx-ax)diff --git a/kornia/geometry/ransac.py b/kornia/geometry/ransac.pyindex 3ac78f713..92e48b50d 100644--- a/kornia/geometry/ransac.py+++ b/kornia/geometry/ransac.py@@ -28,9 +28,23 @@ import torchfrom torch import nnfrom kornia.core.check import KORNIA_CHECK_SHAPE+from kornia.geometry.conversions import convert_points_to_homogeneousfrom kornia.geometry.epipolar import find_essential, find_fundamental, project_to_essential, sampson_epipolar_distance+from kornia.geometry.epipolar._metrics import _sampson_from_quadratic_basis, _sampson_quadratic_basis+from kornia.geometry.epipolar.fundamental import (+ _eight_point_fundamental,+ _epipolar_design_rows,+ _refine_fundamental_lm,+ _seven_point_candidates,+ normalize_points,+ normalize_transformation,+)from kornia.geometry.homography import (+ _four_point_homography,_line_segment_squared_distance_one_way,+ _refine_homography_lm,+ _transfer_basis,+ _transfer_from_basis,find_homography_dlt,find_homography_dlt_iterated,find_homography_lines_dlt,@@ -44,6 +58,10 @@ __all__ = ["RANSAC"]# The batch size that the ``max_iter`` budget counts in when ``batch_size="auto"``._DEFAULT_BATCH = 2048+# Model types that local_optimization="lm" supports, and how many minimal models it refines.+_LM_MODELS = ("homography", "fundamental", "fundamental_7pt", "fundamental_8pt")+_LM_CANDIDATES = 8+@lru_cache(maxsize=32)def _prosac_growth(sample_size: int, pop_size: int, budget: int) -> Tuple[int, ...]:@@ -59,6 +77,36 @@ def _prosac_growth(sample_size: int, pop_size: int, budget: int) -> Tuple[int, .return tuple(ends)+def _normalize_correspondences(+ kp1: torch.Tensor, kp2: torch.Tensor, shared_scale: bool+) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, float, float]:+ r"""Hartley-normalize both images' correspondences with :func:`normalize_points`, once per RANSAC call.++ Statistics use the correspondences finite in both images: the others enter :func:`normalize_points` as zero-weight+ placeholders, since a weight of 0 does not remove a NaN from its weighted sums, and come out as NaN in both images,+ so they are never counted as inliers. ``shared_scale`` gives both images the scale of the mean of their two mean+ radii, which keeps the Sampson distance a multiple of the pixel one: :func:`normalize_points` scales by+ :math:`\sqrt{2} / (r + \epsilon)`, so that scale is the harmonic mean of the two.++ Returns:+ Homogeneous normalized points ``(N, 3)`` of each image, the ``(3, 3)`` transforms that map pixels to them, and+ the two scales in pixels per normalized unit.+ """+ finite = torch.isfinite(kp1).all(1) & torch.isfinite(kp2).all(1)+ stacked = torch.stack([kp1, kp2])+ placeholders = torch.where(finite[None, :, None], stacked, torch.zeros_like(stacked))+ points, transforms = normalize_points(placeholders, weights=finite.to(kp1.dtype).expand(2, -1))+ if shared_scale:+ scale = transforms[:, 0, 0]+ ratio = (2.0 / (1.0 / scale).sum()) / scale+ points = points * ratio[:, None, None]+ transforms = torch.cat([transforms[:, :2] * ratio[:, None, None], transforms[:, 2:]], 1)+ points = torch.where(finite[None, :, None], points, torch.full_like(points, float("nan")))+ points = convert_points_to_homogeneous(points)+ s1, s2 = (1.0 / transforms[:, 0, 0]).tolist()+ return points[0], points[1], transforms[0], transforms[1], s1, s2++class RANSAC(nn.Module):"""Module for robust geometry estimation with RANSAC. https://en.wikipedia.org/wiki/Random_sample_consensus.@@ -66,33 +114,47 @@ class RANSAC(nn.Module):- ``kp1`` and ``kp2`` are passed as the first- and second-image arguments of the estimator selected by``model_type``, so a homography maps ``kp1`` to ``kp2``. ``forward`` returns a ``(3, 3)`` model and an``(N,)`` bool inlier mask, or an all-zero model and no inliers when no candidate has more inliers than- its minimal sample (four correspondences for homographies, five for ``"essential"``, seven or eight- for the fundamental models).+ its minimal sample (four correspondences for homographies, five for ``"essential"``, seven for+ ``"fundamental"`` and ``"fundamental_7pt"``, eight for ``"fundamental_8pt"``).+ - ``"fundamental"`` draws seven-point samples, like ``"fundamental_7pt"``; ``"fundamental_8pt"`` draws+ eight-point ones.- ``inl_th`` is in the keypoints' own units (pixels, or calibrated units for ``"essential"``): acorrespondence is an inlier when its one-way transfer error for ``"homography"``, its Sampson distance- for ``"fundamental"``, ``"fundamental_7pt"`` and ``"essential"``, or the mean distance of its transferred- endpoints from the image-2 segment's line for ``"homography_from_linesegments"`` is at most ``inl_th``.+ for the fundamental models and ``"essential"``, or the mean distance of its transferred endpoints from+ the image-2 segment's line for ``"homography_from_linesegments"`` is at most ``inl_th``.:ref:`two-view-conventions` compares this with OpenCV.- ``score_type="msac"`` (the default) ranks candidates by ``sum(1 - min(e / inl_th**2, 1))`` over thesquared errors ``e``; acceptance and early stopping count inliers for either score.- - Local optimization defaults to ``lo_sample_size=32``: ``max_lo_iters`` randomized refits on 32-inlier- subsets followed by one full-inlier refit; ``lo_sample_size=None`` refits all inliers iteratively.+ - ``local_optimization="lm"``, the default for homographies and fundamental matrices, keeps the eight+ best-scoring minimal models of the whole run. After sampling, it refines them together with+ ``max_lo_iters`` Levenberg-Marquardt iterations on all correspondences with the squared error truncated+ at ``inl_th``, keeps the best-scoring refit or minimal model, and refines that one on its inliers with+ ``refine_iters`` iterations of a Cauchy loss of scale ``inl_th / 3``. The returned mask holds the inliers+ of the returned model after conversion to the input dtype; if that conversion loses sufficient support,+ the call returns the all-zero failure result. Early stopping follows the support of the best minimal model.+ The refinements run on the CPU in float64 whatever the device of the correspondences: they are a few dozen+ small operations per iteration, which launch latency makes slower on an accelerator.+ - ``local_optimization="dlt"``, the only choice for ``"essential"`` and+ ``"homography_from_linesegments"``, refits each new best model from its inliers: with the default+ ``lo_sample_size=32``, ``max_lo_iters`` randomized refits on 32-inlier subsets followed by one+ full-inlier refit; ``lo_sample_size=None`` refits all inliers iteratively.- ``prosac_sampling=True`` expects correspondences sorted best-first and stops with PROSAC'stermination-length test; ``confidence=1`` runs the whole ``batch_size * max_iter`` budget.- A seeded call uses a private generator and leaves torch's global RNG state unchanged; ``seed=None``draws from the global generator.Args:- model_type: "homography", "fundamental", "fundamental_7pt", "essential", or+ model_type: "homography", "fundamental", "fundamental_7pt", "fundamental_8pt", "essential", or"homography_from_linesegments".inl_th: positive inlier threshold, in the units given above.- batch_size: hypotheses generated and verified at once, or ``"auto"`` to pick the batch per call from+ batch_size: hypotheses generated and verified at once, or ``"auto"`` to pick the batches per call fromthe device and the number of correspondences (see :meth:`resolve_batch_size`).max_iter: with an integer ``batch_size``, the maximum number of batches, for a budget of``batch_size * max_iter`` minimal samples; with ``"auto"``, the budget is ``2048 * max_iter``. Theseven- and five-point solvers can return multiple models per sample.confidence: stopping confidence in ``(0, 1]``; 1 disables early stopping.- max_lo_iters: maximum local refitting iterations; zero disables polishing.+ max_lo_iters: local optimization iterations: Levenberg-Marquardt iterations with+ ``local_optimization="lm"``, refits with ``"dlt"``; zero disables local optimization.score_type: "msac" (default) for truncated squared residuals, or "ransac" for support count.prosac_sampling: use PROSAC sampling on best-first ordered correspondences. The growth scheduleadvances per sampled set within each batch; stopping tests the incumbent's support within ranked@@ -101,10 +163,15 @@ class RANSAC(nn.Module):85% or more inliers it can certify a model fitted to a spatially clustered top-ranked prefix afterone batch and score below uniform sampling; use uniform sampling or ``confidence=1`` there.seed: optional seed, reset on each call for reproducible estimation on the same device.- lo_sample_size: inlier-subset size for a batch of ``max_lo_iters`` randomized local refits followed- by a full-inlier refit (default 32). None uses iterative full-inlier refitting.+ lo_sample_size: with ``local_optimization="dlt"``, the inlier-subset size for a batch of ``max_lo_iters``+ randomized local refits followed by a full-inlier refit (default 32). None uses iterative full-inlier+ refitting. Unused with ``"lm"``.max_samples: optional budget of minimal samples that overrides the one implied by ``batch_size`` and``max_iter``; the last batch is truncated to it.+ local_optimization: ``"lm"`` or ``"dlt"``, as described above; None picks ``"lm"`` for homographies and+ fundamental matrices and ``"dlt"`` for the other models.+ refine_iters: Levenberg-Marquardt iterations of the final refinement with ``local_optimization="lm"``;+ zero disables it."""@@ -121,31 +188,35 @@ class RANSAC(nn.Module):seed: Optional[int] = None,lo_sample_size: Optional[int] = 32,max_samples: Optional[int] = None,+ local_optimization: Optional[str] = None,+ refine_iters: int = 3,) -> None:"""Initialize the RANSAC estimator.Args:- model_type: type of model to estimate: "homography", "fundamental", "fundamental_7pt", "essential",- "homography_from_linesegments".+ model_type: type of model to estimate: "homography", "fundamental", "fundamental_7pt",+ "fundamental_8pt", "essential", "homography_from_linesegments".inl_th: inlier threshold; the class docstring gives its unit per ``model_type``.- batch_size: number of generated samples at once, or ``"auto"``: batches of up to 8192 homography or- 2048 epipolar hypotheses on CUDA and MPS, fewer for very many correspondences, and on CPU a batch- sized for the model and the number of correspondences so that early stopping is checked every- millisecond or so. Other devices retain the historical 2048-sample batch.+ batch_size: number of generated samples at once, or ``"auto"`` (see :meth:`resolve_batch_size`).max_iter: maximum batches to generate. At most ``batch_size * max_iter`` minimal samples are drawn(``2048 * max_iter`` with ``batch_size="auto"``) unless ``max_samples`` is given.confidence: desired confidence of the result, used for the early stopping. 1 runs the full budget.- max_lo_iters: number of local optimization (polishing) iterations.+ max_lo_iters: number of local optimization iterations.score_type: scoring method to use: "msac" (default) or "ransac".prosac_sampling: use PROSAC's progressive sampling schedule. Inputs must be sorted best-firstby match quality. The schedule advances for every sampled set, including within batches.Stops when a ranked prefix, or the whole set, certifies the incumbent with ``confidence``.seed: optional random seed for reproducible results. If None, uses global random state.- lo_sample_size: cap on the number of inliers used by each randomized local refit (default 32).- Fits ``max_lo_iters`` independent subsets in one batch, followed by one full-inlier refit.- None uses iterative full-inlier refitting. Subset refits must raise the score; a full-inlier- refit may also tie it, since it is more precise than the minimal-sample model.+ lo_sample_size: with ``local_optimization="dlt"``, the cap on the number of inliers used by each+ randomized local refit (default 32). Fits ``max_lo_iters`` independent subsets in one batch,+ followed by one full-inlier refit. None uses iterative full-inlier refitting. Subset refits must+ raise the score; a full-inlier refit may also tie it, since it is more precise than the+ minimal-sample model.max_samples: optional budget of minimal samples, overriding ``batch_size * max_iter``.+ local_optimization: ``"lm"`` (batched Levenberg-Marquardt refinement of the best minimal models and a+ final robust refinement) or ``"dlt"`` (refits of each new best model); None picks ``"lm"`` where it+ is supported, for homographies and fundamental matrices.+ refine_iters: Levenberg-Marquardt iterations of the final refinement on the inliers with ``"lm"``."""super().__init__()@@ -153,6 +224,7 @@ class RANSAC(nn.Module):"homography","fundamental","fundamental_7pt",+ "fundamental_8pt","homography_from_linesegments","essential",]@@ -174,6 +246,14 @@ class RANSAC(nn.Module):raise ValueError("max_samples must be a positive integer")if not 0 < confidence <= 1:raise ValueError("confidence must lie in (0, 1]")+ if isinstance(refine_iters, bool) or not isinstance(refine_iters, int) or refine_iters < 0:+ raise ValueError("refine_iters must be a nonnegative integer")+ if local_optimization is None:+ local_optimization = "lm" if model_type in _LM_MODELS else "dlt"+ if local_optimization not in ("lm", "dlt"):+ raise ValueError(f'local_optimization must be "lm" or "dlt", got {local_optimization!r}')+ if local_optimization == "lm" and model_type not in _LM_MODELS:+ raise ValueError(f'local_optimization="lm" supports {", ".join(_LM_MODELS)}, not {model_type!r}')self.score_type = score_typeself.inl_th = inl_thself.max_iter = max_iter@@ -186,6 +266,8 @@ class RANSAC(nn.Module):self.prosac_sampling = prosac_samplingself.seed = seedself.lo_sample_size = lo_sample_size+ self.local_optimization = local_optimization+ self.refine_iters = refine_iters# The PROSAC growth schedule as a device tensor, reused across the batches of a call.self._prosac_ends: Optional[Tuple[Tuple[int, int, int, torch.device], torch.Tensor]] = None@@ -207,13 +289,13 @@ class RANSAC(nn.Module):self.polisher_solver = partial(find_homography_lines_dlt_iterated, soft_inl_th=inl_th)self.minimal_sample_size = 4self.polisher_sample_size = 4- elif model_type == "fundamental":+ elif model_type == "fundamental_8pt":self.error_fn = sampson_epipolar_distanceself.minimal_solver = find_fundamentalself.minimal_sample_size = 8self.polisher_solver = find_fundamentalself.polisher_sample_size = 8- elif model_type == "fundamental_7pt":+ elif model_type in ("fundamental", "fundamental_7pt"):self.error_fn = sampson_epipolar_distanceself.minimal_solver = partial(find_fundamental, method="7POINT")self.minimal_sample_size = 7@@ -237,6 +319,7 @@ class RANSAC(nn.Module):batch_size: int,iteration: int,device: Optional[Union[torch.device, str]] = None,+ offset: Optional[int] = None,) -> torch.Tensor:"""Minimal sampler, but unlike traditional RANSAC we sample in batches.@@ -246,8 +329,11 @@ class RANSAC(nn.Module):sample_size: number of samples to draw from the population.pop_size: size of the population to sample from.batch_size: number of sample sets to generate.- iteration: zero-based batch index (used for PROSAC scheduling and the random seed).+ iteration: zero-based batch index (used for the random seed and, without ``offset``, for PROSAC+ scheduling).device: device to place the samples on.+ offset: number of sets drawn by the previous batches, for PROSAC scheduling when batches differ in+ size; None assumes ``iteration`` batches of ``batch_size``.Returns:Tensor of sampled indices with shape :math:`(batch_size, sample_size)`.@@ -272,7 +358,8 @@ class RANSAC(nn.Module):force_newest = torch.zeros(batch_size, device=device, dtype=torch.bool)if self.prosac_sampling:ends = self._prosac_schedule(sample_size, pop_size, device)- draws = torch.arange(batch_size, device=device) + iteration * batch_size + 1+ start = iteration * batch_size if offset is None else offset+ draws = torch.arange(batch_size, device=device) + start + 1population = (torch.searchsorted(ends, draws) + sample_size).clamp(max=pop_size)force_newest = draws <= ends[-1]@@ -316,7 +403,7 @@ class RANSAC(nn.Module):return _DEFAULT_BATCH * self.max_iterdef resolve_batch_size(self, num_tc: int, device: torch.device) -> int:- """Return the batch size of a call: the configured one, or the ``"auto"`` choice for the device.+ """Return the batch size of a ``local_optimization="dlt"`` call: the configured one, or the ``"auto"`` choice.On CUDA and MPS a homography batch costs about the same from a few hundred up to 8192 hypotheses(the four-point solve is launch-bound), so the whole :attr:`sample_budget` is drawn in batches of@@ -327,6 +414,14 @@ class RANSAC(nn.Module):``batch * N`` residuals, and the eight-point solver is about ten times a DLT, so the batch aims at amillisecond or so of work, 256 to 2048 hypotheses for homographies and 128 to 512 for the epipolarmodels. Other devices retain the historical 2048-sample batch.++ With ``local_optimization="lm"`` an ``"auto"`` batch instead starts at 256 samples on CPU (512 for+ homographies) and doubles after every batch, up to 2048 (4096 for homographies), so that inputs with+ many inliers stop after a small first batch while the rest pay the per-batch overhead a few times only.+ On CUDA and MPS it is the whole budget up to 8192 samples. Both shrink when a batch would score more+ than ``2**22`` (CPU) or ``2**25`` (accelerators) residuals, counting the three models of a seven-point+ sample; scoring holds two or three times that many entries at its peak, about 0.5 GiB in float32 on an+ accelerator. An integer ``batch_size`` is kept for every batch."""if isinstance(self.batch_size, int):return self.batch_size@@ -340,6 +435,22 @@ class RANSAC(nn.Module):batch = min(max(work // max(num_tc, 1), lower), upper)return min(batch, self.sample_budget)+ def _lm_batch_range(self, num_tc: int, device: torch.device) -> Tuple[int, int]:+ """First and largest batch of a ``local_optimization="lm"`` call; see :meth:`resolve_batch_size`."""+ budget = self.sample_budget+ if isinstance(self.batch_size, int):+ return min(self.batch_size, budget), min(self.batch_size, budget)+ models = 3 if self.minimal_sample_size == 7 else 1+ planar = self.model_type == "homography"+ if device.type == "cpu":+ first, upper, work = (512, 4096, 1 << 22) if planar else (256, 2048, 1 << 22)+ elif device.type in ("cuda", "mps"):+ first, upper, work = 8192, 8192, 1 << 25+ else:+ first, upper, work = _DEFAULT_BATCH, _DEFAULT_BATCH, 1 << 25+ largest = max(min(upper, work // (models * max(num_tc, 1))), 64)+ return min(first, largest, budget), min(largest, budget)+def _is_supported(self, num_inliers: float) -> bool:"""Whether a model has support beyond the minimal sample it may have been fitted to.@@ -694,6 +805,9 @@ class RANSAC(nn.Module):"""self.validate_inputs(kp1, kp2, weights)+ if self.local_optimization == "lm":+ with torch.no_grad():+ return self._forward_lm(kp1, kp2)best_score_total = -float("inf")num_tc: int = len(kp1)budget = self.sample_budget@@ -717,7 +831,7 @@ class RANSAC(nn.Module):continue# Estimate modelsmodels = self.estimate_model_from_minsample(kp1_sampled, kp2_sampled)- if self.model_type in ["essential", "fundamental_7pt"]:+ if self.model_type in ["essential", "fundamental", "fundamental_7pt"]:models = models.reshape(-1, 3, 3)models = self.remove_bad_models(models)if (models is None) or (len(models) == 0):@@ -760,3 +874,156 @@ class RANSAC(nn.Module):best_model_total = torch.zeros_like(best_model_total)inliers_best_total = torch.zeros_like(inliers_best_total)return best_model_total, inliers_best_total++ def _lm_minimal_models(self, x1: torch.Tensor, x2: torch.Tensor) -> torch.Tensor:+ """Minimal models ``(M, 3, 3)`` of normalized homogeneous samples ``(B, m, 3)``.++ Samples that :func:`~kornia.geometry.homography.sample_is_valid_for_homography` rejects and absent roots of+ the seven-point cubic are dropped on CPU; on other devices, where dropping would need a synchronization, they+ are NaN models, which score no inliers. The orientation test is unaffected by the normalization, a+ translation and a positive scale.+ """+ compact = x1.device.type == "cpu"+ if self.model_type == "homography":+ oriented = sample_is_valid_for_homography(x1[..., :2], x2[..., :2])+ if compact:+ x1, x2 = x1[oriented], x2[oriented]+ if len(x1) == 0:+ return x1.new_zeros(0, 3, 3)+ return _four_point_homography(x1, x2)+ models = _four_point_homography(x1, x2)+ return models.masked_fill(~oriented[:, None, None], float("nan"))+ design = _epipolar_design_rows(x1, x2)+ if self.minimal_sample_size == 7:+ candidates, valid = _seven_point_candidates(design)+ models = candidates.masked_fill(~valid[..., None, None], float("nan")).flatten(0, 1)+ else:+ models = _eight_point_fundamental(design)+ return models[torch.isfinite(models).flatten(1).all(1)] if compact else models++ def _lm_errors(self, models: torch.Tensor, x1: torch.Tensor, x2: torch.Tensor) -> torch.Tensor:+ """Squared residuals ``(M, N)``, in normalized units, of normalized models on normalized correspondences."""+ if self.model_type == "homography":+ return _transfer_from_basis(models, _transfer_basis(x1, x2[:, :2]))+ return _sampson_from_quadratic_basis(models, _sampson_quadratic_basis(x1, x2))++ def _lm_score(self, errors: torch.Tensor, threshold: float) -> torch.Tensor:+ """MSAC scores ``sum(1 - min(e / threshold, 1))`` or RANSAC support counts ``(M,)`` of squared residuals."""+ if self.score_type == "msac":+ # fmin, unlike clamp, takes the threshold for NaN residuals: a NaN residual is an outlier.+ return (1.0 - torch.fmin(errors, torch.full_like(errors[:1, :1], threshold)) / threshold).sum(1)+ return (errors <= threshold).sum(1).to(errors.dtype)++ def _lm_refine(+ self,+ models: torch.Tensor,+ x1: torch.Tensor,+ x2: torch.Tensor,+ mask: Optional[torch.Tensor],+ loss: str,+ scale2: float,+ iters: int,+ ) -> torch.Tensor:+ """Refine normalized models with Levenberg-Marquardt; all inputs are float64 host tensors."""+ if self.model_type == "homography":+ return _refine_homography_lm(models, x1, x2[:, :2], mask, loss, scale2, iters)+ return _refine_fundamental_lm(models, x1, x2, mask, loss, scale2, iters)++ def _forward_lm(self, kp1: torch.Tensor, kp2: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:+ """RANSAC with batched minimal solvers and Levenberg-Marquardt local optimization and refinement.++ Sampling, minimal solving and scoring run on the device of the correspondences; the normalization, the+ refinements and the final selection run on the host in float64, which needs a handful of synchronizations+ per call instead of one per small operation. What differs from the public solvers is what a sampling loop+ needs: correspondences are normalized once per call rather than per sample, models stay in that normalized+ frame at unit Frobenius norm instead of ``F[2, 2] = 1``, absent candidates are NaN on accelerators rather than+ dropped, and scoring uses the quadratic Sampson and folded transfer bases, which are fast and accurate in that+ frame only.+ """+ device, dtype = kp1.device, kp1.dtype+ work = torch.float64 if dtype == torch.float64 else torch.float32+ num_tc, m = len(kp1), self.minimal_sample_size+ planar = self.model_type == "homography"+ failure = (torch.zeros(3, 3, dtype=dtype, device=device), torch.zeros(num_tc, dtype=torch.bool, device=device))+ host = torch.device("cpu")+ # The Sampson distance scales with a similarity shared by both images; the transfer error with image 2's.+ kp1_host, kp2_host = kp1.detach().to(host, torch.float64), kp2.detach().to(host, torch.float64)+ finite = torch.isfinite(kp1_host).all(1) & torch.isfinite(kp2_host).all(1)+ if not bool(finite.any()):+ return failure+ x1_host, x2_host, t1, t2, s1, s2 = _normalize_correspondences(kp1_host, kp2_host, not planar)+ threshold = (self.inl_th / (s2 if planar else s1)) ** 2+ x1, x2 = x1_host.to(device, work), x2_host.to(device, work)+ basis = _transfer_basis(x1, x2[:, :2]) if planar else _sampson_quadratic_basis(x1, x2)+ budget = self.sample_budget+ batch, largest = self._lm_batch_range(num_tc, device)+ grow = not isinstance(self.batch_size, int)+ candidates, candidate_scores = x1.new_zeros(0, 3, 3), x1.new_zeros(0)+ best_score = -1.0+ max_samples, drawn, iteration = budget, 0, 0+ while drawn < max_samples:+ current = min(batch, max_samples - drawn)+ indices = self.sample(m, num_tc, current, iteration, device, offset=drawn)+ drawn, iteration = drawn + current, iteration + 1+ if grow:+ batch = min(2 * batch, largest)+ models = self._lm_minimal_models(x1[indices], x2[indices])+ if len(models) == 0:+ continue+ errors = _transfer_from_basis(models, basis) if planar else _sampson_from_quadratic_basis(models, basis)+ # Reject insufficient support before ranking: high MSAC scores from minimal samples alone must not+ # crowd supported models out of the candidate pool.+ counts_all = (errors <= threshold).sum(1)+ scores_all = self._lm_score(errors, threshold).masked_fill(counts_all <= m, -1.0)+ top_scores, top = scores_all.topk(min(_LM_CANDIDATES, len(models)))+ top_inliers = errors[top] <= threshold+ top_counts = counts_all[top]+ # The run's best minimal models so far, refined after sampling.+ candidate_scores, order = torch.cat([top_scores, candidate_scores]).topk(+ min(_LM_CANDIDATES, len(top_scores) + len(candidate_scores))+ )+ candidates = torch.cat([models[top], candidates])[order]+ scores, counts = torch.stack([top_scores, top_counts.to(top_scores.dtype)]).tolist()+ best = max(range(len(scores)), key=scores.__getitem__)+ if scores[best] > best_score:+ # The bound follows the new incumbent's own support, as with local_optimization="dlt".+ best_score = scores[best]+ if self.prosac_sampling:+ max_samples = self._prosac_max_samples(top_inliers[best], int(counts[best]))+ else:+ support = int(counts[best])+ max_samples = min(budget, self.max_samples_by_conf(support, num_tc, m, self.confidence))+ x1_host, x2_host = x1_host[finite], x2_host[finite]+ candidates = candidates.to(host, torch.float64)[candidate_scores.to(host) >= 0]+ if len(candidates) == 0:+ return failure+ if self.max_lo_iters > 0:+ refits = self._lm_refine(candidates, x1_host, x2_host, None, "truncated", threshold, self.max_lo_iters)+ # Refits first: a tie goes to the refit, which is fitted to more than a minimal sample.+ candidates = torch.cat([refits, candidates])+ errors = self._lm_errors(candidates, x1_host, x2_host)+ inliers = errors <= threshold+ scores = self._lm_score(errors, threshold).masked_fill(inliers.sum(1) <= m, -1.0)+ best = int(scores.argmax())+ if scores[best] < 0:+ return failure+ model, inliers = candidates[best], inliers[best]+ if self.refine_iters > 0:+ # A Cauchy scale of a third of the threshold: the threshold as three standard deviations of the noise.+ mask = inliers.to(torch.float64)[None]+ refined = self._lm_refine(model[None], x1_host, x2_host, mask, "cauchy", threshold / 9, self.refine_iters)+ refined_inliers = self._lm_errors(refined, x1_host, x2_host)[0] <= threshold+ if self._is_supported(int(refined_inliers.sum())):+ model, inliers = refined[0], refined_inliers+ model = (torch.linalg.inv(t2) @ model @ t1) if planar else (t2.mT @ model @ t1)+ model = normalize_transformation(model).to(dtype)+ if not bool(torch.isfinite(model).all()):+ return failure+ # Casting (especially to half precision) changes the model. Classify that exact returned matrix in pixel+ # coordinates, in float64 so metric arithmetic does not add another round of low-precision error. The public+ # line/transfer forms also avoid cancellation in the normalized quadratic sampling basis near epipoles.+ errors = self.error_fn(kp1_host[None], kp2_host[None], model[None].to(torch.float64), eps=0.0)[0]+ mask = finite & (errors <= self.inl_th**2)+ if not self._is_supported(int(mask.sum())):+ return failure+ return model.to(device), mask.to(device)diff --git a/kornia/geometry/solvers/homogeneous.py b/kornia/geometry/solvers/homogeneous.pyindex 602ee9687..5a3ba3afb 100644--- a/kornia/geometry/solvers/homogeneous.py+++ b/kornia/geometry/solvers/homogeneous.py@@ -168,3 +168,24 @@ def null_vector_3x4(A: torch.Tensor) -> torch.Tensor:)return torch.stack([v0, v1, v2, v3], dim=-1)+++def _null_space_lu(A: torch.Tensor) -> torch.Tensor:+ r"""Right null spaces of a batch of ``(B, m, n)`` matrices, ``m < n``, as ``(B, n, n - m)``.++ With ``A^T = P L U`` from a partial-pivoted LU factorization, ``f^T A^T = 0`` exactly when ``y = P^T f`` solves+ ``y^T L = 0``. Splitting the unit lower trapezoidal ``L`` into its square top ``L_1`` and bottom ``L_2`` rows+ gives the basis ``y = [-(L_2 L_1^{-1})^T; I]``. The pivoting chooses the gauge, so no coordinate of the null+ vector is assumed non-zero, and the basis is not orthonormal.++ Unlike an SVD, a QR or an ``eigh`` of ``A^T A``, a batched LU factorization is one batched kernel on every+ backend, and working on ``A`` rather than ``A^T A`` does not square its condition number. ``L_1`` is unit+ triangular, so a rank-deficient ``A`` still gives a basis of null vectors, of dimension ``n - m`` only, as long+ as the factorization stays finite; callers treat non-finite vectors as degenerate.+ """+ batch, m, n = A.shape+ lu, pivots, _ = torch.linalg.lu_factor_ex(A.mT)+ lower = torch.linalg.solve_triangular(lu[:, :m, :m], lu[:, m:, :m], upper=False, left=False, unitriangular=True)+ eye = torch.eye(n - m, dtype=A.dtype, device=A.device).expand(batch, -1, -1)+ permutation, _, _ = torch.lu_unpack(lu, pivots, unpack_data=False)+ return permutation @ torch.cat([-lower.mT, eye], 1)diff --git a/kornia/geometry/solvers/polynomial_solver.py b/kornia/geometry/solvers/polynomial_solver.pyindex 15338f816..75891b20d 100644--- a/kornia/geometry/solvers/polynomial_solver.py+++ b/kornia/geometry/solvers/polynomial_solver.py@@ -18,6 +18,7 @@"""nn.Module containing the functionalities for computing the real roots of polynomial equation."""import math+from typing import Tupleimport torch@@ -303,6 +304,52 @@ def _solve_cubic_with_count(coeffs: torch.Tensor) -> tuple[torch.Tensor, torch.Treturn solutions, num_real+def _solve_cubic_real(coeffs: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:+ """Real roots ``(B, 3)`` of the cubics ``coeffs (B, 4)``, highest degree first, and a mask of the genuine ones.++ Cardano's formula for one real root, the trigonometric one for three, followed by a Newton step. A cubic with one+ real root repeats it in the two masked slots, so a caller builds every candidate from finite roots and masks+ afterwards. The caller chooses a well-conditioned pencil parametrization with a nonzero leading coefficient.++ A private kernel for the seven-point solvers rather than :func:`solve_cubic`, whose public contract differs where a+ hot loop cares: it pads missing roots with 0.0, indistinguishable from a genuine root at 0; it lowers the degree of+ a vanishing leading coefficient behind ``torch.any`` tests, a device synchronization per call; and it defines a+ surrogate backward at repeated roots. Here the closed form runs without gradient and the Newton step carries it:+ at a simple root that is the implicit-function derivative ``-(dp/dc) / p'(x)``, and the ``clamp``-guarded+ ``sqrt``, ``acos`` and cube roots of the closed form, whose derivatives are unbounded at their bounds (#4229),+ never enter the backward pass. At a repeated root ``p'(x) = 0``; the division is guarded and the gradient finite.+ """+ c3, c2, c1, c0 = coeffs.unbind(1)+ a, b, c = c2 / c3, c1 / c3, c0 / c3+ with torch.no_grad():+ a3 = a / 3+ p = b - a * a3+ q = (2 * a3 * a3 - b) * a3 + c+ discriminant = 0.25 * q * q + p * p * p / 27+ # Cancellation at a repeated root can round the discriminant slightly positive.+ discriminant_scale = 0.25 * q.square() + p.abs().pow(3) / 27+ three = discriminant <= 32 * torch.finfo(coeffs.dtype).eps * discriminant_scale+ root = discriminant.clamp(min=0).sqrt()+ u, w = root - 0.5 * q, -root - 0.5 * q+ single = torch.copysign(u.abs().pow(1 / 3), u) + torch.copysign(w.abs().pow(1 / 3), w)+ radius = (-p / 3).clamp(min=0).sqrt()+ safe_radius = torch.where(radius > 0, radius, torch.ones_like(radius))+ angle = torch.acos((-0.5 * q / safe_radius.pow(3)).clamp(-1, 1)) / 3+ offsets = torch.tensor([0.0, 2 * math.pi / 3, 4 * math.pi / 3], dtype=c3.dtype, device=c3.device)+ triple = 2 * radius[:, None] * torch.cos(angle[:, None] - offsets)+ x = torch.where(three[:, None], triple, single[:, None].expand(-1, 3)) - a3[:, None]+ value = ((x + a[:, None]) * x + b[:, None]) * x + c[:, None]+ slope = (3 * x + 2 * a[:, None]) * x + b[:, None]+ # At repeated roots rounding can leave a tiny nonzero slope: dividing two rounding errors then moves an+ # already accurate root far away. Bound the derivative relative to its terms, including their cancellation.+ slope_scale = 3 * x.square() + 2 * a[:, None].abs() * x.abs() + b[:, None].abs()+ simple = slope.abs() > 8 * torch.finfo(coeffs.dtype).eps * slope_scale+ correction = value / torch.where(simple, slope, torch.ones_like(slope))+ x = x - torch.where(simple, correction, torch.zeros_like(correction))+ valid = torch.stack([torch.ones_like(three), three, three], 1)+ return x, valid++def _quartic_root_residual_tol(dtype: torch.dtype) -> float:"""Largest scaled Horner residual a polished quartic candidate may leave and still count as a root.diff --git a/testing/half_precision_xfails/cpu_bfloat16.txt b/testing/half_precision_xfails/cpu_bfloat16.txtindex cd0bf6095..5df4dd1c2 100644--- a/testing/half_precision_xfails/cpu_bfloat16.txt+++ b/testing/half_precision_xfails/cpu_bfloat16.txt@@ -157,11 +157,6 @@ call builtins.NotImplementedError tests/geometry/epipolar/test_fundamental.py::Tcall builtins.NotImplementedError tests/geometry/epipolar/test_fundamental.py::TestFindFundamental::test_shape[cpu-bfloat16-1-8]call builtins.NotImplementedError tests/geometry/epipolar/test_fundamental.py::TestFindFundamental::test_shape[cpu-bfloat16-2-9]call builtins.NotImplementedError tests/geometry/epipolar/test_fundamental.py::TestFindFundamental::test_shape[cpu-bfloat16-3-10]-call builtins.NotImplementedError tests/geometry/epipolar/test_fundamental.py::TestFindFundamental::test_shape_7point[cpu-bfloat16-1]-call builtins.NotImplementedError tests/geometry/epipolar/test_fundamental.py::TestFindFundamental::test_shape_7point[cpu-bfloat16-2]-call builtins.NotImplementedError tests/geometry/epipolar/test_fundamental.py::TestFindFundamental::test_shape_7point[cpu-bfloat16-3]-call builtins.NotImplementedError tests/geometry/epipolar/test_fundamental.py::TestFindFundamental::test_shape_noweights[cpu-bfloat16-1-8]-call builtins.NotImplementedError tests/geometry/epipolar/test_fundamental.py::TestFindFundamental::test_shape_noweights[cpu-bfloat16-2-8]call builtins.NotImplementedError tests/geometry/epipolar/test_fundamental.py::TestFindFundamental::test_shape_noweights[cpu-bfloat16-3-10]call builtins.NotImplementedError tests/geometry/epipolar/test_fundamental.py::TestFindFundamental::test_smoke[cpu-bfloat16]call builtins.NotImplementedError tests/geometry/epipolar/test_fundamental.py::TestFindFundamental::test_synthetic_sampson[cpu-bfloat16]@@ -378,7 +373,6 @@ call builtins.AssertionError tests/geometry/test_quaternion.py::TestQuaternionAvcall builtins.NotImplementedError tests/geometry/test_ransac.py::TestRANSACEssential::test_forward_enforces_essential_constraint[cpu-bfloat16]call builtins.NotImplementedError tests/geometry/test_ransac.py::TestRANSACEssential::test_polish_enforces_essential_constraint[cpu-bfloat16]call builtins.NotImplementedError tests/geometry/test_ransac.py::TestRANSACEssential::test_smoke[cpu-bfloat16]-call builtins.NotImplementedError tests/geometry/test_ransac.py::TestRANSACFundamental::test_smoke[cpu-bfloat16]call builtins.AssertionError tests/geometry/transform/test_affine.py::TestAffine2d::test_affine_rotate_translate[cpu-bfloat16]call builtins.AssertionError tests/geometry/transform/test_affine.py::TestRescale::test_downscale_values[cpu-bfloat16]call builtins.AssertionError tests/geometry/transform/test_affine.py::TestRescale::test_downscale_values_AA[cpu-bfloat16]diff --git a/testing/half_precision_xfails/cpu_float16.txt b/testing/half_precision_xfails/cpu_float16.txtindex 9ae0a075d..97979ee7d 100644--- a/testing/half_precision_xfails/cpu_float16.txt+++ b/testing/half_precision_xfails/cpu_float16.txt@@ -261,11 +261,6 @@ call builtins.NotImplementedError tests/geometry/epipolar/test_fundamental.py::Tcall builtins.NotImplementedError tests/geometry/epipolar/test_fundamental.py::TestFindFundamental::test_shape[cpu-float16-1-8]call builtins.NotImplementedError tests/geometry/epipolar/test_fundamental.py::TestFindFundamental::test_shape[cpu-float16-2-9]call builtins.NotImplementedError tests/geometry/epipolar/test_fundamental.py::TestFindFundamental::test_shape[cpu-float16-3-10]-call builtins.NotImplementedError tests/geometry/epipolar/test_fundamental.py::TestFindFundamental::test_shape_7point[cpu-float16-1]-call builtins.NotImplementedError tests/geometry/epipolar/test_fundamental.py::TestFindFundamental::test_shape_7point[cpu-float16-2]-call builtins.NotImplementedError tests/geometry/epipolar/test_fundamental.py::TestFindFundamental::test_shape_7point[cpu-float16-3]-call builtins.NotImplementedError tests/geometry/epipolar/test_fundamental.py::TestFindFundamental::test_shape_noweights[cpu-float16-1-8]-call builtins.NotImplementedError tests/geometry/epipolar/test_fundamental.py::TestFindFundamental::test_shape_noweights[cpu-float16-2-8]call builtins.NotImplementedError tests/geometry/epipolar/test_fundamental.py::TestFindFundamental::test_shape_noweights[cpu-float16-3-10]call builtins.NotImplementedError tests/geometry/epipolar/test_fundamental.py::TestFindFundamental::test_smoke[cpu-float16]call builtins.NotImplementedError tests/geometry/epipolar/test_fundamental.py::TestFindFundamental::test_synthetic_sampson[cpu-float16]@@ -383,7 +378,6 @@ call builtins.AssertionError tests/geometry/test_quaternion.py::TestQuaternion::call builtins.NotImplementedError tests/geometry/test_ransac.py::TestRANSACEssential::test_forward_enforces_essential_constraint[cpu-float16]call builtins.NotImplementedError tests/geometry/test_ransac.py::TestRANSACEssential::test_polish_enforces_essential_constraint[cpu-float16]call builtins.NotImplementedError tests/geometry/test_ransac.py::TestRANSACEssential::test_smoke[cpu-float16]-call builtins.NotImplementedError tests/geometry/test_ransac.py::TestRANSACFundamental::test_smoke[cpu-float16]call builtins.AssertionError tests/geometry/transform/test_affine.py::TestAffine2d::test_affine_rotate_translate[cpu-float16]call builtins.AssertionError tests/geometry/transform/test_affine.py::TestRotate::test_angle90[cpu-float16]call builtins.AssertionError tests/geometry/transform/test_affine.py::TestRotate::test_angle90_batch2[cpu-float16]diff --git a/tests/geometry/epipolar/test_epipolar_metrics.py b/tests/geometry/epipolar/test_epipolar_metrics.pyindex e93c66610..b5ddf59e6 100644--- a/tests/geometry/epipolar/test_epipolar_metrics.py+++ b/tests/geometry/epipolar/test_epipolar_metrics.py@@ -21,6 +21,15 @@ import pytestimport torchimport kornia.geometry.epipolar as epi+from kornia.geometry.epipolar._metrics import (+ _sampson_epipolar_distance_manual_impl_,+ _sampson_epipolar_distance_matmul_impl_,+ _sampson_epipolar_distance_shared_impl_,+ _sampson_errors,+ _sampson_from_quadratic_basis,+ _sampson_quadratic_basis,+)+from kornia.geometry.epipolar.fundamental import _rank2_projectionfrom testing.base import BaseTesterfrom testing.geometry.create import create_random_fundamental_matrix@@ -334,3 +343,184 @@ class TestConventionEpipolarMetrics(BaseTester):for fn in (epi.left_to_right_epipolar_distance, epi.right_to_left_epipolar_distance):unit, tiny = fn(x1, x2, F), fn(x1, x2, 1e-6 * F)assert ((unit - tiny).abs() / unit).min() > 1e-2+++def _near_epipole_scene(n: int, seed: int):+ """Pixel correspondences 0.01-1000 px from both epipoles, which lie inside a 1920x1080 image, and their F."""+ generator = torch.Generator().manual_seed(seed)+ f64 = torch.float64+ size = torch.tensor([1920.0, 1080.0], dtype=f64)+ e1 = torch.cat([torch.rand(2, generator=generator, dtype=f64) * size, torch.ones(1, dtype=f64)])+ e2 = torch.cat([torch.rand(2, generator=generator, dtype=f64) * size, torch.ones(1, dtype=f64)])+ eye = torch.eye(3, dtype=f64)+ A = torch.randn(3, 3, generator=generator, dtype=f64)+ F = (eye - e2[:, None] * e2[None] / (e2 @ e2)) @ A @ (eye - e1[:, None] * e1[None] / (e1 @ e1))+ offsets = torch.logspace(-2, 3, n, dtype=f64)[:, None]+ x1 = e1[:2] + torch.randn(n, 2, generator=generator, dtype=f64) * offsets+ x2 = e2[:2] + torch.randn(n, 2, generator=generator, dtype=f64) * offsets+ return x1, x2, F / F[2, 2]+++class TestSampsonSharedPoints(BaseTester):+ """One point set scored against many fundamental matrices: two matrix products instead of per-model broadcasting."""++ @pytest.mark.parametrize("squared", [True, False])+ def test_public_dispatch_and_eps_4881(self, device, dtype, squared):+ if dtype in (torch.float16, torch.bfloat16):+ pytest.skip("eps = 1e-8 is below half precision's resolution")+ # 256 matrices x 300 points reach the shared path on every device. At 1e-4 of unit scale, eps moves the+ # distances by tens of percent, so the comparison tells the CPU rule (eps in the denominator) from the CUDA+ # matmul one (no eps in the denominator, #4881).+ generator = torch.Generator().manual_seed(5)+ pts1 = torch.rand(1, 300, 2, generator=generator).to(device, dtype)+ pts2 = torch.rand(1, 300, 2, generator=generator).to(device, dtype)+ Fm = 1e-4 * create_random_fundamental_matrix(256, dtype=dtype, device=device)+ out = epi.sampson_epipolar_distance(pts1, pts2, Fm, squared=squared)+ matmul = device.type == "cuda"+ shared = _sampson_epipolar_distance_shared_impl_(pts1, pts2, Fm, squared, 1e-8, 0.0 if matmul else 1e-8)+ assert torch.equal(out, shared)+ reference = _sampson_epipolar_distance_matmul_impl_ if matmul else _sampson_epipolar_distance_manual_impl_+ expected = reference(pts1, pts2, Fm, squared, 1e-8)+ # Roundoff on the near-zero distances aside, eps in or out of the denominator is a 20-60% difference.+ self.assert_close(out, expected, rtol=1e-3, atol=1e-3 * float(expected.abs().median()))++ def test_single_matrix_without_batch_dimension(self, device, dtype):+ if device.type != "cuda":+ pytest.skip("the manual implementation, used on CPU, has always required a batch dimension on Fm")+ # The CUDA matmul implementation broadcasts a single (3, 3) matrix; the shared-point dispatch must not reject+ # it.+ pts1 = torch.rand(1, 9, 2, device=device, dtype=dtype)+ pts2 = torch.rand(1, 9, 2, device=device, dtype=dtype)+ Fm = create_random_fundamental_matrix(1, dtype=dtype, device=device)+ out = epi.sampson_epipolar_distance(pts1, pts2, Fm[0])+ assert out.shape == (1, 9)+ self.assert_close(out, epi.sampson_epipolar_distance(pts1, pts2, Fm))++ @pytest.mark.parametrize("squared", [True, False])+ def test_matches_the_other_paths(self, device, dtype, squared):+ pts1 = torch.rand(1, 20, 2, device=device, dtype=dtype)+ pts2 = torch.rand(1, 20, 2, device=device, dtype=dtype)+ # 4000 models x 20 points: the GEMM path on every device.+ Fm = create_random_fundamental_matrix(4000, dtype=dtype, device=device)+ out = epi.sampson_epipolar_distance(pts1, pts2, Fm, squared=squared)+ other = (+ _sampson_epipolar_distance_matmul_impl_+ if device.type == "cuda"+ else _sampson_epipolar_distance_manual_impl_+ )+ work = torch.promote_types(dtype, torch.float32)+ expected = other(pts1.to(work), pts2.to(work), Fm.to(work), squared, 1e-8).to(dtype)+ assert out.dtype == dtype+ self.assert_close(out, expected)++ def test_shapes(self, device, dtype):+ pts1 = torch.rand(1, 1, 7, 2, device=device, dtype=dtype)+ pts2 = torch.cat(+ [torch.rand(1, 7, 2, device=device, dtype=dtype), torch.ones(1, 7, 1, device=device, dtype=dtype)], -1+ )+ Fm = create_random_fundamental_matrix(6, dtype=dtype, device=device).reshape(2, 3, 3, 3)+ assert _sampson_epipolar_distance_shared_impl_(pts1, pts2, Fm, True, 1e-8, 1e-8).shape == (2, 3, 7)+ assert _sampson_epipolar_distance_shared_impl_(pts1[0, 0], pts2[0], Fm[0], True, 1e-8, 1e-8).shape == (3, 7)+ empty = torch.zeros(1, 0, 2, device=device, dtype=dtype)+ assert _sampson_epipolar_distance_shared_impl_(empty, empty, Fm[0], True, 1e-8, 1e-8).shape == (3, 0)++ def test_homogeneous_points_are_used_as_given(self, device, dtype):+ pts1 = torch.rand(1, 9, 2, device=device, dtype=dtype)+ pts2 = torch.rand(1, 9, 2, device=device, dtype=dtype)+ Fm = create_random_fundamental_matrix(3, dtype=dtype, device=device)+ scaled = 2.0 * _hom(pts1)+ out = _sampson_epipolar_distance_shared_impl_(scaled, pts2, Fm, True, 1e-8, 1e-8)+ work = torch.promote_types(dtype, torch.float32)+ expected = _sampson_epipolar_distance_manual_impl_(scaled.to(work), pts2.to(work), Fm.to(work), True, 1e-8)+ self.assert_close(out, expected.to(dtype))++ def test_non_contiguous_and_mixed_dtype_models(self, device, dtype):+ pts1 = torch.rand(1, 11, 2, device=device, dtype=torch.float64)+ pts2 = torch.rand(1, 11, 2, device=device, dtype=torch.float64)+ Fm = create_random_fundamental_matrix(4, dtype=dtype, device=device)+ out = _sampson_epipolar_distance_shared_impl_(pts1, pts2, Fm.mT, True, 1e-8, 1e-8)+ assert out.dtype == torch.promote_types(torch.float64, dtype)+ self.assert_close(+ out, _sampson_epipolar_distance_shared_impl_(pts1, pts2, Fm.mT.contiguous(), True, 1e-8, 1e-8)+ )+ one = Fm[:1].expand(5, 3, 3)+ expanded = _sampson_epipolar_distance_shared_impl_(pts1, pts2, one, True, 1e-8, 1e-8)+ self.assert_close(expanded, expanded[:1].expand_as(expanded))++ def test_residual_order_regression(self, device, dtype):+ if dtype != torch.float32:+ pytest.skip("a float32 cancellation case (half cannot hold 1000.1 or 2e6; float64 is the reference)")+ # PR #5031 review: a numerator expanded into monomials of the coordinates cancels here (0.0521 against a+ # float64 value of 0.0403); forming x2 . (F x1) keeps the manual path's 0.0319.+ F = torch.tensor(+ [[1.0, 0.0, -1000.0], [0.0, 1.0, -1000.0], [-1000.0, -1000.0, 2e6]], device=device, dtype=dtype+ )+ x1 = torch.tensor([[[1000.1, 1000.2]]], device=device, dtype=dtype)+ x2 = torch.tensor([[[1000.3, 1000.4]]], device=device, dtype=dtype)+ models = F.expand(64, 3, 3)+ shared = _sampson_epipolar_distance_shared_impl_(x1, x2, models, True, 0.0, 0.0)[:, 0].double().cpu()+ manual = _sampson_epipolar_distance_manual_impl_(x1, x2, F[None], True, 0.0)[0, 0].double().cpu()+ reference = _sampson_epipolar_distance_manual_impl_(x1.double(), x2.double(), F[None].double(), True, 0.0)+ reference = reference[0, 0].cpu()+ self.assert_close(shared, manual.expand_as(shared), rtol=1e-4, atol=0.0)+ assert (shared - reference).abs().max() <= 2 * (manual - reference).abs()++ @pytest.mark.parametrize("seed", [0, 1, 2, 3])+ def test_near_epipoles_in_pixels(self, device, dtype, seed):+ if dtype != torch.float32:+ pytest.skip("the float32 cancellation case")+ x1, x2, F = _near_epipole_scene(2000, seed=seed)+ perturb = 1 + 1e-4 * torch.randn(7, 3, 3, generator=torch.Generator().manual_seed(1), dtype=torch.float64)+ models = torch.cat([F[None], F[None] * perturb])+ reference = _sampson_epipolar_distance_manual_impl_(x1[None], x2[None], models, True, 0.0)+ cast = lambda t: t.to(device, dtype) # noqa: E731+ shared = _sampson_epipolar_distance_shared_impl_(cast(x1[None]), cast(x2[None]), cast(models), True, 0.0, 0.0)+ manual = _sampson_epipolar_distance_manual_impl_(cast(x1[None]), cast(x2[None]), cast(models), True, 0.0)+ shared, manual = shared.double().cpu(), manual.double().cpu()+ assert torch.isfinite(shared).all()+ assert (shared >= 0).all()+ # Within 0.1 px of an epipole both float32 computations are rounding noise (the maximum error of either is+ # an accident of summation order), so compare the error distributions: the tail and the number of+ # distances off by more than 1 px^2. An expanded monomial residual fails this on seeds 1 and 3.+ small = reference < 100+ error_shared = (shared - reference).abs()[small]+ error_manual = (manual - reference).abs()[small]+ assert error_shared.quantile(0.99) <= 1.25 * error_manual.quantile(0.99)+ assert (error_shared > 1).sum() <= 1.25 * (error_manual > 1).sum() + 2++ def test_ransac_quadratic_form_near_epipoles(self, device, dtype):+ if dtype != torch.float32:+ pytest.skip("RANSAC scores in float32 on the device")+ x1, x2, F = _near_epipole_scene(2000, seed=0)+ n1, t1 = epi.normalize_points(x1[None])+ n2, t2 = epi.normalize_points(x2[None])+ h1, h2 = _hom(n1[0]), _hom(n2[0])+ Fn = torch.linalg.inv(t2[0]).mT @ F @ torch.linalg.inv(t1[0])+ Fn = Fn / Fn.norm()+ generator = torch.Generator().manual_seed(2)+ perturbed = Fn + 1e-3 * torch.randn(7, 3, 3, generator=generator, dtype=torch.float64)+ models = torch.cat([Fn[None], _rank2_projection(perturbed)])+ models = models / models.flatten(1).norm(dim=1)[:, None, None]+ reference = _sampson_errors(models, h1, h2, 0.0)+ cast = lambda t: t.to(device, torch.float32) # noqa: E731+ errors = _sampson_from_quadratic_basis(cast(models), _sampson_quadratic_basis(cast(h1), cast(h2)))+ errors = errors.double().cpu()+ assert not errors.isnan().any()+ assert (errors >= 0).all()+ scale = float(t2[0, 0, 0])+ decisions = 0+ flips = 0+ for px in (0.5, 1.0, 2.0, 4.0):+ threshold = (px * scale) ** 2+ flips += int(((errors <= threshold) != (reference <= threshold)).sum())+ decisions += errors.numel()+ # Measured 1.2e-5 of the decisions over 40 such scenes (PR #5031 review).+ assert flips <= 1e-4 * decisions++ def test_gradcheck(self, device):+ pts1 = torch.rand(1, 5, 2, device=device, dtype=torch.float64)+ pts2 = torch.rand(1, 5, 2, device=device, dtype=torch.float64)+ Fm = create_random_fundamental_matrix(3, dtype=torch.float64, device=device)+ self.gradcheck(+ lambda a, b, F: _sampson_epipolar_distance_shared_impl_(a, b, F, True, 1e-8, 1e-8), (pts1, pts2, Fm)+ )diff --git a/tests/geometry/epipolar/test_fundamental.py b/tests/geometry/epipolar/test_fundamental.pyindex 55df7f9cc..e77b1459f 100644--- a/tests/geometry/epipolar/test_fundamental.py+++ b/tests/geometry/epipolar/test_fundamental.py@@ -21,6 +21,17 @@ import pytestimport torchimport kornia.geometry.epipolar as epi+import kornia.geometry.epipolar.fundamental as fundamental_module+from kornia.core.utils import _torch_svd_cast+from kornia.geometry.conversions import axis_angle_to_rotation_matrix+from kornia.geometry.epipolar.fundamental import (+ _eight_point_fundamental,+ _enforce_rank2,+ _epipolar_design_rows,+ _rank2_projection,+ _seven_point_candidates,+)+from kornia.geometry.solvers.homogeneous import _null_space_lufrom testing.base import BaseTesterfrom testing.geometry.create import create_random_fundamental_matrix, generate_two_view_random_scene@@ -796,8 +807,8 @@ class TestConventionFundamental(BaseTester):def test_run_7point_zeroes_padded_roots_4862(self, device, dtype):two_view = two_view_scene(device, dtype)_skip_half(dtype, _NO_HALF_EIGH)- # #4862: a 7-point sample whose cubic has one real root. The solver pads the two missing roots with 0.0; their- # candidates used to be one rank-3 matrix repeated, and are now zeroed as the padding they are.+ # #4862: a 7-point sample whose cubic has one real root. The candidates of its two missing roots used to be one+ # rank-3 matrix repeated, and are now zero matrices.idx = [0, 1, 2, 3, 4, 6, 10]F = epi.find_fundamental(two_view["x1"][:, idx], two_view["x2"][:, idx], method="7POINT")assert F.shape == (1, 3, 3, 3)@@ -858,3 +869,216 @@ class TestConventionFundamental(BaseTester):F = epi.fundamental_from_projections(two_view["P1"], two_view["P2"])assert F.dtype == torch.float16assert torch.isinf(F).any()+++def _rotation(axis_angle):+ return axis_angle_to_rotation_matrix(torch.tensor([axis_angle], dtype=torch.float64))[0]+++def _with_singular_values(values, rotate: bool) -> torch.Tensor:+ S = torch.diag(torch.tensor(values, dtype=torch.float64))+ if not rotate:+ return S+ return _rotation([0.3, -0.2, 0.5]) @ S @ _rotation([-0.4, 0.1, 0.2]).T+++class TestEpipolarDesignRows(BaseTester):+ def test_inhomogeneous_and_homogeneous_rows_agree(self, device, dtype):+ # Each entry is one product x2_i * x1_j, so every construction (chosen per device for speed) gives the same+ # bits, and inhomogeneous points imply w = 1.+ generator = torch.Generator().manual_seed(7)+ p1 = torch.rand(5, 11, 2, generator=generator).to(device, dtype)+ p2 = torch.rand(5, 11, 2, generator=generator).to(device, dtype)+ rows = _epipolar_design_rows(p1, p2)+ assert rows.shape == (5, 11, 9)+ assert torch.equal(rows, _epipolar_design_rows(_hom(p1), _hom(p2)))+ x1, y1 = p1.unbind(-1)+ x2, y2 = p2.unbind(-1)+ one = torch.ones_like(x1)+ expected = torch.stack([x2 * x1, x2 * y1, x2, y2 * x1, y2 * y1, y2, x1, y1, one], -1)+ assert torch.equal(rows, expected)+++class TestRankTwoProjection(BaseTester):+ def test_matches_svd(self, device):+ F = torch.randn(128, 3, 3, generator=torch.Generator().manual_seed(0), dtype=torch.float64).to(device)+ U, S, Vh = torch.linalg.svd(F)+ expected = U @ torch.diag_embed(S * torch.tensor([1.0, 1.0, 0.0], device=device, dtype=torch.float64)) @ Vh+ self.assert_close(_rank2_projection(F), expected, atol=1e-9, rtol=0)++ @pytest.mark.parametrize(+ "values, rotate",+ [+ ([1.0, 1.0, 1.0], False),+ ([2.0, 2.0, 2.0], True),+ ([3.0, 1.0, 1.0], False),+ ([3.0, 1.0, 1.0], True),+ ([3.0, 1.0, 1.0 - 1e-12], True),+ ([3.0, 1.0, 1.0 - 1e-8], True),+ ([3.0, 1.0, 1.0 - 1e-4], True),+ ([1.0, 0.0, 0.0], True),+ ([0.0, 0.0, 0.0], False),+ ],+ )+ def test_repeated_singular_values(self, device, values, rotate):+ # At a repeated smallest singular value the nearest rank-2 matrix is not unique, so compare what every one of+ # them shares with the SVD's: the two largest singular values, a zero third one, and the distance sigma_3.+ F = _with_singular_values(values, rotate).to(device)[None]+ P = _rank2_projection(F)+ s = torch.linalg.svdvals(F)[0]+ sp = torch.linalg.svdvals(P)[0]+ tol = 1e-9 * max(float(s[0]), 1.0)+ self.assert_close(sp[:2], s[:2], atol=tol, rtol=0)+ assert float(sp[2]) <= tol+ self.assert_close((F - P).norm(), s[2], atol=tol, rtol=0)++ def test_enforce_rank2_keeps_the_svd_without_float64(self, device, monkeypatch):+ # Without float64 (MPS) the closed form runs in float32, where its error grows like eps (sigma_1 / sigma_2)^2+ # through F^T F; batches of any size then keep the SVD. Simulated here by patching the solve dtype.+ monkeypatch.setattr(fundamental_module, "_solve_dtype", lambda device: torch.float32)+ generator = torch.Generator().manual_seed(4)+ U = torch.linalg.qr(torch.randn(600, 3, 3, generator=generator, dtype=torch.float64))[0]+ V = torch.linalg.qr(torch.randn(600, 3, 3, generator=generator, dtype=torch.float64))[0]+ F = U @ torch.diag(torch.tensor([1.0, 1e-2, 1e-3], dtype=torch.float64)) @ V.mT+ expected = U[..., :2] @ torch.diag(torch.tensor([1.0, 1e-2], dtype=torch.float64)) @ V[..., :2].mT+ P = _enforce_rank2(F.to(device, torch.float32)).cpu().double()+ assert (P - expected).abs().max() < 1e-5++ def test_backward_is_finite_at_a_repeated_spectrum(self, device):+ F = torch.eye(3, device=device, dtype=torch.float64)[None].requires_grad_()+ _rank2_projection(F).sum().backward()+ assert torch.isfinite(F.grad).all()++ def test_gradcheck(self, device):+ F = torch.randn(4, 3, 3, generator=torch.Generator().manual_seed(1), dtype=torch.float64).to(device)+ self.gradcheck(_rank2_projection, (F,))++ def test_keeps_dtype(self, device, dtype):+ F = torch.randn(2, 3, 3, generator=torch.Generator().manual_seed(2)).to(device, dtype)+ assert _rank2_projection(F).dtype == dtype++ def test_eight_point_fundamental_is_exact(self, device, dtype):+ _skip_half(dtype, "the eight-point kernel is compared at float32 and float64 accuracy")+ two_view = two_view_scene(torch.device("cpu"), torch.float64)+ x1, x2 = two_view["x1"][:, :8], two_view["x2"][:, :8]+ n1, t1 = epi.normalize_points(x1)+ n2, t2 = epi.normalize_points(x2)+ A = _epipolar_design_rows(_hom(n1), _hom(n2)).to(device, dtype)+ F = t2.mT @ _eight_point_fundamental(A).cpu().double() @ t1+ F = F / F.norm()+ truth = _pixel_F(two_view)+ truth = truth / truth.norm()+ tolerance = 1e-6 if dtype == torch.float64 else 1e-2+ assert torch.linalg.det(F).abs().max() < tolerance+ assert min((F - truth).norm(), (F + truth).norm()) < tolerance++ @pytest.mark.parametrize("num_points", [8, 12])+ def test_run_8point_small_batches_keep_the_svd(self, device, dtype, num_points):+ _skip_half(dtype, _NO_HALF_EIGH)+ # Below a few hundred matrices a batched 3x3 SVD is cheaper than the closed form's fixed cost, so small+ # batches keep the SVD rank-2 step, and their results, to the bit.+ generator = torch.Generator().manual_seed(num_points)+ points1 = torch.rand(4, num_points, 2, generator=generator).to(device, dtype)+ points2 = torch.rand(4, num_points, 2, generator=generator).to(device, dtype)+ n1, t1 = epi.normalize_points(points1)+ n2, t2 = epi.normalize_points(points2)+ A = _epipolar_design_rows(_hom(n1), _hom(n2))+ if num_points == 8:+ h = _null_space_lu(A.to(torch.promote_types(A.dtype, torch.float32)))[..., 0]+ h = (h / h.norm(dim=-1, keepdim=True)).to(A.dtype)+ else:+ h = torch.linalg.eigh(A.transpose(-2, -1).contiguous() @ A)[1][..., 0]+ U, S, V = _torch_svd_cast(h.reshape(4, 3, 3))+ S_new = torch.zeros_like(S)+ S_new[..., :-1] = S[..., :-1]+ expected = epi.normalize_transformation(t2.transpose(-2, -1) @ ((U @ torch.diag_embed(S_new) @ V.mH) @ t1))+ assert torch.equal(epi.find_fundamental(points1, points2), expected)++ def test_run_8point_large_batches_match_small_ones(self, device, dtype):+ _skip_half(dtype, _NO_HALF_EIGH)+ generator = torch.Generator().manual_seed(3)+ points1 = torch.rand(600, 12, 2, generator=generator).to(device, dtype)+ points2 = torch.rand(600, 12, 2, generator=generator).to(device, dtype)+ batched = epi.find_fundamental(points1, points2)+ one_by_one = torch.cat(+ [epi.find_fundamental(points1[i : i + 1], points2[i : i + 1]) for i in range(0, 600, 60)]+ )+ scale = one_by_one.flatten(1).norm(dim=1)[:, None, None]+ self.assert_close(batched[::60] / scale, one_by_one / scale, rtol=1e-3, atol=1e-3)++ @pytest.mark.parametrize("num_points", [8, 12])+ def test_gradcheck_run_8point_unweighted(self, device, num_points):+ generator = torch.Generator().manual_seed(num_points)+ points1 = torch.rand(1, num_points, 2, generator=generator, dtype=torch.float64).to(device)+ points2 = torch.rand(1, num_points, 2, generator=generator, dtype=torch.float64).to(device)+ self.gradcheck(lambda p1: epi.find_fundamental(p1, points2), (points1,))+++class TestSevenPoint(BaseTester):+ def test_identically_singular_pencil_is_finite(self, device, dtype):+ _skip_half(dtype, "the seven-point kernel is compared at float32 and float64 accuracy")+ # Only the first two entries of F are free: every matrix in this null space is rank deficient.+ design = torch.eye(9, device=device, dtype=dtype)[None, 2:]+ candidates, valid = _seven_point_candidates(design)+ assert torch.isfinite(candidates).all()+ assert not valid.any()++ def test_singular_pencil_endpoints(self, device, dtype):+ _skip_half(dtype, "the seven-point kernel is compared at float32 and float64 accuracy")+ points1 = torch.tensor(+ [[[0, -2], [-2, 1], [0, 1], [0, 0], [-1, 2], [-1, 1], [2, -1]]], device=device, dtype=dtype+ )+ points2 = torch.tensor(+ [[[1, 2], [2, 2], [0, -2], [-1, 2], [0, -1], [-1, -2], [2, 2]]], device=device, dtype=dtype+ )+ # The constraints have full row rank, but both LU null-space basis matrices have zero determinant.+ design = _epipolar_design_rows(points1, points2)+ assert torch.linalg.matrix_rank(design).item() == 7+ candidates = fundamental_module.run_7point(points1, points2)+ norms = candidates.flatten(-2).norm(dim=-1)+ valid = norms > 0+ assert valid.any()+ if dtype == torch.float64:+ assert valid.all() # Keep the double projective root as well as the simple root.+ # Float32 perturbations of the constraints can split the double root into a complex pair.+ candidates = candidates / torch.where(valid, norms, torch.ones_like(norms))[..., None, None]+ tolerance = 1e-10 if dtype == torch.float64 else 1e-5+ self.assert_close(torch.linalg.det(candidates), torch.zeros_like(norms), atol=tolerance, rtol=0)+ residuals = design @ candidates.flatten(-2).mT+ self.assert_close(residuals, torch.zeros_like(residuals), atol=tolerance, rtol=0)+ if dtype == torch.float64:+ distances = torch.cdist(candidates.flatten(-2), candidates.flatten(-2))+ assert distances.max() > 0.1 # Keep both distinct matrices, including the root at infinity.++ def test_candidates_are_exact(self, device, dtype):+ _skip_half(dtype, "the seven-point kernel is compared at float32 and float64 accuracy")+ two_view = two_view_scene(torch.device("cpu"), torch.float64)+ x1, x2 = two_view["x1"][:, :7], two_view["x2"][:, :7]+ n1, t1 = epi.normalize_points(x1)+ n2, t2 = epi.normalize_points(x2)+ candidates, valid = _seven_point_candidates(_epipolar_design_rows(_hom(n1), _hom(n2)).to(device, dtype))+ assert valid.any()+ F = t2[:, None].mT @ candidates.cpu().double() @ t1[:, None]+ F = (F / F.flatten(-2).norm(dim=-1)[..., None, None])[valid.cpu()]+ truth = _pixel_F(two_view)[0]+ truth = truth / truth.norm()+ tolerance = 1e-6 if dtype == torch.float64 else 1e-2+ assert torch.linalg.det(F).abs().max() < tolerance+ distance = torch.minimum((F - truth).flatten(1).norm(dim=1), (F + truth).flatten(1).norm(dim=1))+ assert distance.min() < tolerance++ @pytest.mark.parametrize("idx", [[0, 1, 2, 3, 4, 5, 6], [0, 1, 2, 3, 4, 6, 10]])+ def test_backward_is_finite(self, device, idx):+ # The second sample has one real root (#4862): masking candidates built from NaN roots used to leave NaN in+ # the backward pass although the output was finite.+ two_view = two_view_scene(device, torch.float64)+ x1 = two_view["x1"][:, idx].clone().requires_grad_()+ F = epi.find_fundamental(x1, two_view["x2"][:, idx], method="7POINT")+ F.sum().backward()+ assert torch.isfinite(x1.grad).all()++ @pytest.mark.parametrize("idx", [[0, 1, 2, 3, 4, 5, 6], [0, 1, 2, 3, 4, 6, 10]])+ def test_gradcheck(self, device, idx):+ two_view = two_view_scene(device, torch.float64)+ x2 = two_view["x2"][:, idx]+ self.gradcheck(lambda p1: epi.find_fundamental(p1, x2, method="7POINT"), (two_view["x1"][:, idx],))diff --git a/tests/geometry/solvers/test_homogeneous.py b/tests/geometry/solvers/test_homogeneous.pyindex f47e3f360..bf5242595 100644--- a/tests/geometry/solvers/test_homogeneous.py+++ b/tests/geometry/solvers/test_homogeneous.py@@ -19,6 +19,7 @@ import pytestimport torchfrom kornia.geometry import solvers+from kornia.geometry.solvers.homogeneous import _null_space_lufrom testing.base import BaseTester@@ -270,3 +271,33 @@ class TestConventionNullVector3x4(BaseTester):self.assert_close(null([A[1], A[0], A[2]]), expect([-40.0, 16.0, 4.0, 32.0]))rank2 = [A[0], A[1], [a + 2.0 * b for a, b in zip(A[0], A[1])]]self.assert_close(null(rank2), expect([0.0, 0.0, 0.0, 0.0]))+++class TestNullSpaceLU(BaseTester):+ """``_null_space_lu``, the batched null space behind the seven-, eight- and four-point minimal solvers."""++ @pytest.mark.parametrize("rows", [7, 8])+ def test_matches_svd_subspace(self, device, dtype, rows):+ if dtype in (torch.float16, torch.bfloat16):+ pytest.skip("no backend factorizes half precision; callers promote to float32")+ A = torch.randn(64, rows, 9, device=device, dtype=dtype)+ basis = _null_space_lu(A)+ assert basis.shape == (64, 9, 9 - rows)+ basis = basis / basis.norm(dim=1, keepdim=True)+ self.assert_close((A @ basis).abs().amax(), torch.zeros((), device=device, dtype=dtype), atol=1e-5, rtol=0)+ # The same subspace as the SVD's null space: projecting onto it keeps the basis.+ null = torch.linalg.svd(A.cpu().double(), full_matrices=True)[2][:, rows:].mT+ projected = null @ (null.mT @ basis.cpu().double())+ self.assert_close(projected, basis.cpu().double(), atol=1e-5, rtol=0)++ def test_rank_deficient_stays_in_null_space(self, device):+ # Zero rows, as a zero-weight correspondence gives the DLT design matrix: the unit triangular factor the+ # basis is solved from stays regular, so the vectors are finite and still annihilated by A.+ A = torch.randn(3, 8, 9, device=device, dtype=torch.float32)+ A[0, 6:] = 0+ A[1, 4:] = 0+ A[2] = 0+ basis = _null_space_lu(A)+ assert torch.isfinite(basis).all()+ basis = basis / basis.norm(dim=1, keepdim=True)+ assert (A @ basis).abs().amax() < 1e-5diff --git a/tests/geometry/solvers/test_polynomial_solver.py b/tests/geometry/solvers/test_polynomial_solver.pyindex 64bfa2780..0a3b76462 100644--- a/tests/geometry/solvers/test_polynomial_solver.py+++ b/tests/geometry/solvers/test_polynomial_solver.py@@ -21,7 +21,7 @@ import torchimport kornia.geometry.solvers as solverfrom kornia.core.exceptions import ShapeError-from kornia.geometry.solvers.polynomial_solver import _solve_cubic_with_count+from kornia.geometry.solvers.polynomial_solver import _solve_cubic_real, _solve_cubic_with_countfrom testing.base import BaseTester@@ -1316,3 +1316,65 @@ class TestConventionPolynomialSolvers(BaseTester):# gradient is nan.(grad,) = torch.autograd.grad(roots.sum(), coeffs)assert grad.isfinite().all()+++class TestSolveCubicReal(BaseTester):+ """The private seven-point cubic kernel: real roots, a validity mask, and gradients from the Newton step."""++ def _skip_half(self, dtype):+ if dtype in (torch.float16, torch.bfloat16):+ pytest.skip("the kernel runs in the seven-point solvers' float32/float64 solve dtype")++ def test_repeated_root_newton_step(self, device, dtype):+ self._skip_half(dtype)+ coeffs = torch.tensor([[1.0, 0.0, -0.75, 0.25]], device=device, dtype=dtype, requires_grad=True)+ roots, valid = _solve_cubic_real(coeffs)+ assert valid.all()+ expected = torch.tensor([[-1.0, 0.5, 0.5]], device=device, dtype=dtype)+ self.assert_close(roots.sort(dim=1).values, expected)+ roots.sum().backward()+ assert torch.isfinite(coeffs.grad).all()++ def test_three_real_roots(self, device, dtype):+ self._skip_half(dtype)+ # (x - 1)(x - 2)(x - 3)+ coeffs = torch.tensor([[1.0, -6.0, 11.0, -6.0]], device=device, dtype=dtype)+ roots, valid = _solve_cubic_real(coeffs)+ assert valid.all()+ self.assert_close(roots.sort(dim=1).values, torch.tensor([[1.0, 2.0, 3.0]], device=device, dtype=dtype))++ def test_one_real_root_is_repeated_in_the_masked_slots(self, device, dtype):+ self._skip_half(dtype)+ # x^3 + x + 1 has one real root, -0.6823278...+ coeffs = torch.tensor([[1.0, 0.0, 1.0, 1.0]], device=device, dtype=dtype)+ roots, valid = _solve_cubic_real(coeffs)+ assert valid.tolist() == [[True, False, False]]+ assert torch.isfinite(roots).all()+ self.assert_close(roots, roots[:, :1].expand(-1, 3))+ self.assert_close(roots[:, 0], torch.tensor([-0.6823278038280193], device=device, dtype=dtype))++ @pytest.mark.parametrize(+ "coeffs", [[1.0, 0.0, 1.0, 1.0], [1.0, -6.0, 11.0, -6.0], [1.0, 0.0, 0.0, -8.0], [1.0, -3.0, 3.0, -1.0]]+ )+ def test_backward_is_finite(self, device, dtype, coeffs):+ # One real root, three, a vanishing depressed coefficient (x^3 = 8 takes a cube root of 0 in Cardano's formula)+ # and a triple root: the closed form's guards have unbounded derivatives at all of them (#4229).+ self._skip_half(dtype)+ c = torch.tensor([coeffs], device=device, dtype=dtype, requires_grad=True)+ roots, valid = _solve_cubic_real(c)+ (roots * valid).sum().backward()+ assert torch.isfinite(c.grad).all()++ def test_gradient_is_the_implicit_derivative(self, device, dtype):+ self._skip_half(dtype)+ # For a simple root, d root / d c_i = -x^(3 - i) / p'(x): x^3 - 8 has the root 2 and p'(2) = 12.+ c = torch.tensor([[1.0, 0.0, 0.0, -8.0]], device=device, dtype=dtype, requires_grad=True)+ roots, _ = _solve_cubic_real(c)+ roots[0, 0].backward()+ expected = -torch.tensor([[8.0, 4.0, 2.0, 1.0]], device=device, dtype=dtype) / 12.0+ self.assert_close(c.grad, expected)++ @pytest.mark.parametrize("coeffs", [[1.0, 0.0, 1.0, 1.0], [1.0, -6.0, 11.0, -6.0], [1.0, 0.0, 0.0, -8.0]])+ def test_gradcheck(self, device, coeffs):+ c = torch.tensor([coeffs], device=device, dtype=torch.float64)+ self.gradcheck(lambda c: _solve_cubic_real(c)[0], (c,))diff --git a/tests/geometry/test_homography.py b/tests/geometry/test_homography.pyindex 74a37cb93..1207e8da4 100644--- a/tests/geometry/test_homography.py+++ b/tests/geometry/test_homography.py@@ -22,7 +22,15 @@ import torchimport korniafrom kornia.core._compat import torch_version_le+from kornia.geometry.conversions import convert_points_from_homogeneous+from kornia.geometry.epipolar import normalize_pointsfrom kornia.geometry.homography import (+ _four_point_homography,+ _homography_design_rows,+ _oneway_transfer_error_shared_impl_,+ _transfer_basis,+ _transfer_errors,+ _transfer_from_basis,find_homography_dlt,find_homography_dlt_iterated,find_homography_lines_dlt,@@ -807,6 +815,10 @@ def _planar(device, dtype):return p1.to(device, dtype), p2.to(device, dtype), H.to(device, dtype)+def _hom(p: torch.Tensor) -> torch.Tensor:+ return torch.cat([p, torch.ones_like(p[..., :1])], -1)++def _inverse(H: torch.Tensor) -> torch.Tensor:"""H^-1 scaled so that its [2, 2] entry is 1, computed in float64 on the CPU."""H_inv = torch.linalg.inv(H.cpu().double())@@ -1160,3 +1172,105 @@ class TestConventionHomography(BaseTester):# #4890: excluding the zero-weight match from Hartley statistics must match dropping it entirely.tol = 1e-8 if dtype == torch.float64 else 1e-2assert _transfer_max(H_weighted, p1, kornia.geometry.transform_points(H_dropped, p1)) < tol+++class TestHomographySharedKernels(BaseTester):+ def test_design_rows_vanish_on_exact_matches(self, device, dtype):+ _skip_half(dtype, _HALF_DLT)+ src, dst, H = _planar(device, dtype)+ rows = _homography_design_rows(src, dst)+ assert rows.shape == (src.shape[0], 2 * src.shape[1], 9)+ residual = rows @ (H / H.norm()).reshape(-1, 9, 1)+ assert residual.abs().max() < 1e-3 * rows.abs().max()++ def test_four_point_homography_is_exact(self, device, dtype):+ _skip_half(dtype, _HALF_DLT)+ src, dst, H = _planar(torch.device("cpu"), torch.float64)+ src, dst = src[:, :4], dst[:, :4]+ n1, t1 = normalize_points(src)+ n2, t2 = normalize_points(dst)+ model = _four_point_homography(_hom(n1).to(device, dtype), n2.to(device, dtype))[0].cpu().double()+ model = torch.linalg.inv(t2[0]) @ model @ t1[0]+ tolerance = 1e-6 if dtype == torch.float64 else 1e-3+ self.assert_close(model / model[2, 2], H[0] / H[0, 2, 2], atol=tolerance, rtol=tolerance)++ @pytest.mark.parametrize("squared", [True, False])+ def test_shared_points_match_per_model(self, device, dtype, squared):+ pts1 = torch.rand(1, 20, 2, device=device, dtype=dtype)+ pts2 = torch.rand(1, 20, 2, device=device, dtype=dtype)+ H = create_random_homography(torch.zeros(5, 1, device=device, dtype=dtype), 3, std_val=0.1)+ out = oneway_transfer_error(pts1, pts2, H, squared=squared)+ work = torch.promote_types(dtype, torch.float32)+ expected = torch.cat(+ [+ oneway_transfer_error(pts1.to(work), pts2.to(work), H[i : i + 1].to(work), squared=squared)+ for i in range(5)+ ]+ )+ assert out.dtype == dtype+ self.assert_close(out, expected.to(dtype))++ def test_public_dispatch(self, device, dtype):+ if dtype in (torch.float16, torch.bfloat16):+ pytest.skip("compared at float32 and float64 accuracy")+ generator = torch.Generator().manual_seed(6)+ pts1 = torch.rand(1, 30, 2, generator=generator).to(device, dtype)+ pts2 = torch.rand(1, 30, 2, generator=generator).to(device, dtype)+ H = torch.eye(3) + 0.1 * (2 * torch.rand(3, 3, 3, generator=generator) - 1)+ H = H.to(device, dtype)+ out = oneway_transfer_error(pts1, pts2, H)+ assert torch.equal(out, _oneway_transfer_error_shared_impl_(pts1, pts2, H, True, 1e-8))+ per_model = torch.cat([oneway_transfer_error(pts1, pts2, H[i : i + 1]) for i in range(3)])+ self.assert_close(out, per_model)++ def test_shapes_and_homogeneous_points(self, device, dtype):+ H = create_random_homography(torch.zeros(4, 1, device=device, dtype=dtype), 3, std_val=0.1)+ pts1 = torch.rand(1, 7, 2, device=device, dtype=dtype)+ pts2 = torch.rand(1, 7, 2, device=device, dtype=dtype)+ # Homogeneous points are dehomogenized, whatever their w.+ out = _oneway_transfer_error_shared_impl_(2.0 * _hom(pts1), 3.0 * _hom(pts2), H, True, 1e-8)+ self.assert_close(out, _oneway_transfer_error_shared_impl_(pts1, pts2, H, True, 1e-8))+ self.assert_close(out, _oneway_transfer_error_shared_impl_(pts1, pts2, H.mT.contiguous().mT, True, 1e-8))+ empty = torch.zeros(1, 0, 2, device=device, dtype=dtype)+ assert _oneway_transfer_error_shared_impl_(empty, empty, H, True, 1e-8).shape == (4, 0)++ def test_pixel_scale_accuracy(self, device, dtype):+ if dtype != torch.float32:+ pytest.skip("the float32 pixel-scale case")+ generator = torch.Generator().manual_seed(3)+ f64 = torch.float64+ src = torch.rand(1, 2000, 2, generator=generator, dtype=f64) * torch.tensor([1920.0, 1080.0], dtype=f64)+ H = torch.tensor([[1.1, 0.05, 20.0], [0.02, 0.95, -10.0], [1e-4, 2e-4, 1.0]], dtype=f64)+ models = H[None] * (1 + 1e-3 * torch.randn(8, 3, 3, generator=generator, dtype=f64))+ dst = convert_points_from_homogeneous(_hom(src) @ H.T) + torch.randn(1, 2000, 2, generator=generator, dtype=f64)+ reference = torch.cat([oneway_transfer_error(src, dst, models[i : i + 1], eps=0.0) for i in range(8)])+ cast = lambda t: t.to(device, dtype) # noqa: E731+ shared = oneway_transfer_error(cast(src), cast(dst), cast(models), eps=0.0).double().cpu()+ per_model = (+ torch.cat([oneway_transfer_error(cast(src), cast(dst), cast(models[i : i + 1]), eps=0.0) for i in range(8)])+ .double()+ .cpu()+ )+ small = reference < 100+ assert (shared - reference)[small].abs().max() <= 2 * (per_model - reference)[small].abs().max() + 1e-6++ def test_ransac_transfer_basis_matches(self, device, dtype):+ if dtype in (torch.float16, torch.bfloat16):+ pytest.skip("RANSAC scores in float32 or float64")+ x1 = torch.cat(+ [torch.randn(50, 2, device=device, dtype=dtype), torch.ones(50, 1, device=device, dtype=dtype)], 1+ )+ x2 = torch.randn(50, 2, device=device, dtype=dtype)+ models = torch.randn(6, 3, 3, device=device, dtype=dtype)+ self.assert_close(+ _transfer_from_basis(models, _transfer_basis(x1, x2)),+ _transfer_errors(models, x1, x2, 0.0),+ rtol=1e-3,+ atol=1e-5,+ )++ def test_gradcheck(self, device):+ pts1 = torch.rand(1, 5, 2, device=device, dtype=torch.float64)+ pts2 = torch.rand(1, 5, 2, device=device, dtype=torch.float64)+ H = create_random_homography(torch.zeros(3, 1, device=device, dtype=torch.float64), 3, std_val=0.1)+ self.gradcheck(lambda a, b, h: _oneway_transfer_error_shared_impl_(a, b, h, True, 1e-8), (pts1, pts2, H))diff --git a/tests/geometry/test_ransac.py b/tests/geometry/test_ransac.pyindex a93ae670b..e5af1d757 100644--- a/tests/geometry/test_ransac.py+++ b/tests/geometry/test_ransac.py@@ -26,6 +26,10 @@ import korniafrom kornia.geometry import RANSAC, transform_pointsfrom kornia.geometry.conversions import axis_angle_to_rotation_matrix, convert_points_from_homogeneousfrom kornia.geometry.epipolar import find_fundamental, project_to_essential, sampson_epipolar_distance+from kornia.geometry.epipolar._metrics import _sampson_errors+from kornia.geometry.epipolar.fundamental import _rank2_projection, _refine_fundamental_lm+from kornia.geometry.homography import _refine_homography_lm, _transfer_errors, oneway_transfer_error+from kornia.geometry.ransac import _normalize_correspondencesfrom testing.base import BaseTesterfrom testing.casts import dict_to@@ -209,7 +213,7 @@ class TestRANSACFundamental(BaseTester):# The ground-truth F leaves up to 0.58px on these 10 points. At 0.5px the best eight-point fit has# only its own sample as inliers, which is no consensus, so RANSAC returns the zero failure matrix;# at 1px all ten are inliers, and over 100 seeds the refit's largest error is at most 1px.- ransac = RANSAC("fundamental", inl_th=1.0, max_iter=20, max_lo_iters=10).to(device=device, dtype=dtype)+ ransac = RANSAC("fundamental_8pt", inl_th=1.0, max_iter=20, max_lo_iters=10).to(device=device, dtype=dtype)fundamental_matrix, mask = ransac(pts_src, pts_dst)# A zero matrix is the failure result and has zero Sampson error for every point.assert fundamental_matrix.abs().amax() > 0@@ -220,7 +224,6 @@ class TestRANSACFundamental(BaseTester):assert gross_errors.sum().item() == 0@pytest.mark.slow- @pytest.mark.xfail(reason="might fail, because out F-RANSAC is not yet 7pt")@pytest.mark.parametrize("data", ["loftr_fund"], indirect=True)def test_real_clean_7pt(self, device, dtype, data):torch.random.manual_seed(0)@@ -250,7 +253,7 @@ class TestRANSACFundamental(BaseTester):kp1 = data_dev["loftr_indoor_tentatives0"]kp2 = data_dev["loftr_indoor_tentatives1"]- ransac = RANSAC("fundamental", inl_th=1.0, max_iter=20, max_lo_iters=10).to(device=device, dtype=dtype)+ ransac = RANSAC("fundamental_8pt", inl_th=1.0, max_iter=20, max_lo_iters=10).to(device=device, dtype=dtype)# compute transform from source to targetfundamental_matrix, _ = ransac(kp1, kp2)assert fundamental_matrix.abs().amax() > 0@@ -260,7 +263,6 @@ class TestRANSACFundamental(BaseTester):assert gross_errors.sum().item() < 2@pytest.mark.slow- @pytest.mark.xfail(reason="might fail, because this F-RANSAC is not 7pt")@pytest.mark.parametrize("data", ["loftr_fund"], indirect=True)def test_real_dirty_7pt(self, device, dtype, data):torch.random.manual_seed(0)@@ -337,7 +339,15 @@ class TestRANSACLocalOptimization(BaseTester):calls.append(1)return candidates- ransac = RANSAC("fundamental", inl_th=1.0, batch_size=4, max_iter=1, max_lo_iters=1, score_type="msac")+ ransac = RANSAC(+ "fundamental_8pt",+ inl_th=1.0,+ batch_size=4,+ max_iter=1,+ max_lo_iters=1,+ score_type="msac",+ local_optimization="dlt",+ )ransac.minimal_solver = lambda kp1, kp2, w: worse_fit.expand(kp1.shape[0], 3, 3).clone()ransac.polisher_solver = fake_polisher@@ -515,6 +525,7 @@ class TestRANSACSeed:seed=0,lo_sample_size=8,confidence=1.0,+ local_optimization="dlt",)ransac(kp1, kp1.clone())assert len(seeds) > 4 # four sampling batches and at least one local optimization@@ -748,7 +759,15 @@ class TestConventionRANSAC(BaseTester):# sample_is_valid_for_homography, which rejects some lattice samples, so a seeded batch of 64 is drawn.H = torch.tensor([_H_TRUE], device=device, dtype=dtype)for inl_th, expected in ((9.0, False), (11.0, True)):- ransac = RANSAC("homography", inl_th=inl_th, batch_size=64, max_iter=1, max_lo_iters=0, seed=0)+ ransac = RANSAC(+ "homography",+ inl_th=inl_th,+ batch_size=64,+ max_iter=1,+ max_lo_iters=0,+ seed=0,+ local_optimization="dlt",+ )_, mask = _fixed_model(ransac, H)(kp1, kp2_bad)assert bool(mask[9]) is expectedassert int(mask.sum()) == 15 + int(expected)@@ -774,7 +793,15 @@ class TestConventionRANSAC(BaseTester):# the distance itself against inl_th**2, the two verdicts would not both hold.assert 2.0 < distance < 4.0for inl_th, expected in ((2.0, False), (4.0, True)):- ransac = RANSAC("fundamental", inl_th=inl_th, batch_size=1, max_iter=1, max_lo_iters=0, seed=0)+ ransac = RANSAC(+ "fundamental",+ inl_th=inl_th,+ batch_size=1,+ max_iter=1,+ max_lo_iters=0,+ seed=0,+ local_optimization="dlt",+ )model, mask = _fixed_model(ransac, F)(kp1, kp2_bad)assert torch.equal(model, F[0])assert bool(mask[6]) is expected@@ -855,7 +882,11 @@ class TestConventionRANSAC(BaseTester):@pytest.mark.parametrize("model_type, n, validated_type, validated_n",- [("fundamental_7pt", 6, "fundamental", 7), ("essential", 4, "homography", 3)],+ [+ ("fundamental_7pt", 6, "fundamental_8pt", 7),+ ("fundamental", 6, "fundamental_8pt", 7),+ ("essential", 4, "homography", 3),+ ],)def test_convention_ransac_size_validation_4872(self, model_type, n, validated_type, validated_n, device, dtype):_cpu_only(device)@@ -877,7 +908,15 @@ class TestRANSACScoringAndStopping(BaseTester):target = points.clone()target[40:] += 100identity = torch.eye(3, device=device, dtype=dtype)[None]- ransac = RANSAC("homography", inl_th=threshold, batch_size=1, max_iter=1, max_lo_iters=0, score_type="msac")+ ransac = RANSAC(+ "homography",+ inl_th=threshold,+ batch_size=1,+ max_iter=1,+ max_lo_iters=0,+ score_type="msac",+ local_optimization="dlt",+ )ransac.remove_bad_samples = lambda a, b: (a, b)ransac.minimal_solver = lambda a, b, w: identitymodel, mask = ransac(points, target)@@ -892,7 +931,7 @@ class TestRANSACScoringAndStopping(BaseTester):matrix = torch.tensor([[0.0, 0.0, 0.0], [0.0, 0.0, -1.0], [0.0, 1.0, 0.0]], device=device, dtype=dtype)if model_type == "homography":matrix = torch.eye(3, device=device, dtype=dtype)- ransac = RANSAC(model_type, batch_size=1, max_iter=1)+ ransac = RANSAC(model_type, batch_size=1, max_iter=1, local_optimization="dlt")ransac.remove_bad_samples = lambda a, b: (a, b)ransac.minimal_solver = lambda a, b, w: matrix[None]ransac.polisher_solver = lambda a, b, w: matrix[None]@@ -926,7 +965,9 @@ class TestRANSACScoringAndStopping(BaseTester):# LO increases support to 70/100. The MSAC score is intentionally different.points = torch.rand(100, 2, device=device, dtype=dtype)matrix = torch.eye(3, device=device, dtype=dtype)[None]- ransac = RANSAC("fundamental", batch_size=16, max_iter=10, max_lo_iters=1, score_type="msac")+ ransac = RANSAC(+ "fundamental_8pt", batch_size=16, max_iter=10, max_lo_iters=1, score_type="msac", local_optimization="dlt"+ )sampled = []ransac.minimal_solver = lambda a, b, w: sampled.append(1) or matrixransac.polisher_solver = lambda a, b, w: matrix@@ -956,7 +997,9 @@ class TestRANSACScoringAndStopping(BaseTester):target = points.clone()target[:outliers] += 100matrix = torch.eye(3, device=device, dtype=dtype)[None]- ransac = RANSAC("homography", batch_size=8, max_iter=3, max_lo_iters=0, confidence=confidence)+ ransac = RANSAC(+ "homography", batch_size=8, max_iter=3, max_lo_iters=0, confidence=confidence, local_optimization="dlt"+ )calls = []ransac.remove_bad_samples = lambda a, b: (a, b)ransac.minimal_solver = lambda a, b, w: calls.append(1) or matrix@@ -965,7 +1008,7 @@ class TestRANSACScoringAndStopping(BaseTester):def test_failure_mask_shape(self, device, dtype):points = torch.zeros(10, 2, device=device, dtype=dtype)- ransac = RANSAC("fundamental", batch_size=2, max_iter=1)+ ransac = RANSAC("fundamental", batch_size=2, max_iter=1, local_optimization="dlt")ransac.minimal_solver = lambda a, b, w: torch.zeros(1, 3, 3, device=device, dtype=dtype)_, mask = ransac(points, points)assert mask.shape == (10,)@@ -978,7 +1021,9 @@ class TestRANSACScoringAndStopping(BaseTester):target = points + 100target[:4] = points[:4]identity = torch.eye(3, device=device, dtype=dtype)[None]- ransac = RANSAC("homography", batch_size=1, max_iter=2, max_lo_iters=0, score_type=score_type)+ ransac = RANSAC(+ "homography", batch_size=1, max_iter=2, max_lo_iters=0, score_type=score_type, local_optimization="dlt"+ )ransac.remove_bad_samples = lambda a, b: (a, b)ransac.minimal_solver = lambda a, b, w: identitymodel, mask = ransac(points, target)@@ -990,7 +1035,9 @@ class TestRANSACScoringAndStopping(BaseTester):# stopping bound must then follow the new incumbent, not the larger support it displaced.points = torch.rand(100, 2, device=device, dtype=dtype)matrix = torch.eye(3, device=device, dtype=dtype)[None]- ransac = RANSAC("fundamental", batch_size=1, max_iter=50, max_lo_iters=0, score_type="msac")+ ransac = RANSAC(+ "fundamental_8pt", batch_size=1, max_iter=50, max_lo_iters=0, score_type="msac", local_optimization="dlt"+ )sampled = []ransac.minimal_solver = lambda a, b, w: sampled.append(1) or matrixresults = {1: (1.0, 95), 2: (2.0, 60)}@@ -1010,7 +1057,15 @@ class TestRANSACScoringAndStopping(BaseTester):# batch still leaves the full refit to try.points = torch.rand(20, 2, device=device, dtype=dtype)identity = torch.eye(3, device=device, dtype=dtype)[None]- ransac = RANSAC("homography", batch_size=1, max_iter=1, max_lo_iters=5, lo_sample_size=lo_sample_size, seed=0)+ ransac = RANSAC(+ "homography",+ batch_size=1,+ max_iter=1,+ max_lo_iters=5,+ lo_sample_size=lo_sample_size,+ seed=0,+ local_optimization="dlt",+ )ransac.remove_bad_samples = lambda a, b: (a, b)ransac.minimal_solver = lambda a, b, w: identitycalls = []@@ -1029,7 +1084,15 @@ class TestRANSACScoringAndStopping(BaseTester):points = torch.rand(20, 2, device=device, dtype=dtype)minimal = torch.eye(3, device=device, dtype=dtype)[None]refit = 2 * minimal- ransac = RANSAC("homography", batch_size=1, max_iter=1, max_lo_iters=3, lo_sample_size=lo_sample_size, seed=0)+ ransac = RANSAC(+ "homography",+ batch_size=1,+ max_iter=1,+ max_lo_iters=3,+ lo_sample_size=lo_sample_size,+ seed=0,+ local_optimization="dlt",+ )ransac.remove_bad_samples = lambda a, b: (a, b)ransac.minimal_solver = lambda a, b, w: minimalpolished = []@@ -1087,7 +1150,13 @@ class TestRANSACSampling(BaseTester):points = torch.rand(20, 2, device=device, dtype=dtype)matrix = torch.eye(3, device=device, dtype=dtype)[None]ransac = RANSAC(- "homography", batch_size=8, max_iter=3, max_lo_iters=0, prosac_sampling=True, confidence=confidence+ "homography",+ batch_size=8,+ max_iter=3,+ max_lo_iters=0,+ prosac_sampling=True,+ confidence=confidence,+ local_optimization="dlt",)calls = []ransac.remove_bad_samples = lambda a, b: (a, b)@@ -1096,7 +1165,7 @@ class TestRANSACSampling(BaseTester):assert len(calls) == batchesdef test_prosac_stopping_uses_ranking(self, device):- ransac = RANSAC("fundamental", batch_size=16, max_iter=256, prosac_sampling=True)+ ransac = RANSAC("fundamental_8pt", batch_size=16, max_iter=256, prosac_sampling=True)# 150 inliers of 500: ranked first, one draw from the top-150 prefix certifies the model.# Ranked last, no prefix qualifies and the uniform bound (over 60,000 draws) caps at the budget.ranked = torch.arange(500, device=device) < 150@@ -1105,7 +1174,7 @@ class TestRANSACSampling(BaseTester):@pytest.mark.parametrize("support", [0, 8, 9, 50, 99])def test_prosac_stopping_rejects_small_prefix_support(self, device, support):- ransac = RANSAC("fundamental", batch_size=16, max_iter=256, prosac_sampling=True)+ ransac = RANSAC("fundamental_8pt", batch_size=16, max_iter=256, prosac_sampling=True)# Fewer than 20% of all correspondences cannot terminate, however perfect the prefix# (OpenCV USAC guard): the top ten all-inlier matches of a locally fitted model are no evidence.inliers = torch.arange(500, device=device) < support@@ -1135,7 +1204,13 @@ class TestRANSACSampling(BaseTester):points = torch.rand(20, 2, device=device, dtype=dtype)matrix = torch.eye(3, device=device, dtype=dtype)[None]ransac = RANSAC(- "homography", batch_size=16, max_iter=16, max_lo_iters=0, score_type="msac", prosac_sampling=True+ "homography",+ batch_size=16,+ max_iter=16,+ max_lo_iters=0,+ score_type="msac",+ prosac_sampling=True,+ local_optimization="dlt",)calls = []ransac.remove_bad_samples = lambda a, b: (a, b)@@ -1159,7 +1234,7 @@ class TestRANSACSampling(BaseTester):assert ransac._prosac_max_samples(torch.ones(4, device=device, dtype=torch.bool), 4) == 4096def test_prosac_stopping_respects_growth(self, device):- ransac = RANSAC("fundamental", batch_size=16, max_iter=256, prosac_sampling=True)+ ransac = RANSAC("fundamental_8pt", batch_size=16, max_iter=256, prosac_sampling=True)# 45 inliers among the top 100 of 200 pass the support guards, but the 3970 draws that# prefix needs exceed the ~106 draws PROSAC takes from it: later draws sampled larger# prefixes and must not be credited to the top 100. The uniform bound caps at the budget.@@ -1201,6 +1276,25 @@ class TestRANSACDefaults(BaseTester):assert ransac.max_lo_iters == 5assert not ransac.prosac_sampling+ @pytest.mark.parametrize(+ "model_type, sample_size, local_optimization",+ [+ ("homography", 4, "lm"),+ ("fundamental", 7, "lm"),+ ("fundamental_7pt", 7, "lm"),+ ("fundamental_8pt", 8, "lm"),+ ("essential", 5, "dlt"),+ ("homography_from_linesegments", 4, "dlt"),+ ],+ )+ def test_defaults_per_model(self, model_type, sample_size, local_optimization):+ # "fundamental" draws seven-point samples; Levenberg-Marquardt local optimization is the default wherever it+ # is implemented.+ ransac = RANSAC(model_type)+ assert ransac.minimal_sample_size == sample_size+ assert ransac.local_optimization == local_optimization+ assert ransac.refine_iters == 3+def test_legacy_configuration_is_still_available(self):ransac = RANSAC("fundamental", score_type="ransac", lo_sample_size=None)assert ransac.score_type == "ransac"@@ -1287,7 +1381,9 @@ class TestRANSACAutoBatch(BaseTester):def test_last_batch_is_truncated_to_the_budget(self, device, dtype):points = torch.rand(20, 2, device=device, dtype=dtype)matrix = torch.eye(3, device=device, dtype=dtype)[None]- ransac = RANSAC("homography", batch_size=16, max_samples=40, max_lo_iters=0, confidence=1.0)+ ransac = RANSAC(+ "homography", batch_size=16, max_samples=40, max_lo_iters=0, confidence=1.0, local_optimization="dlt"+ )sizes = []ransac.remove_bad_samples = lambda a, b: sizes.append(len(a)) or (a, b)ransac.minimal_solver = lambda a, b, w: matrix@@ -1301,7 +1397,13 @@ class TestRANSACAutoBatch(BaseTester):points = torch.arange(num_tc, device=device, dtype=dtype)[:, None].expand(num_tc, 2)matrix = torch.eye(3, device=device, dtype=dtype)[None]ransac = RANSAC(- "homography", batch_size=400, max_samples=1000, prosac_sampling=True, max_lo_iters=0, confidence=1.0+ "homography",+ batch_size=400,+ max_samples=1000,+ prosac_sampling=True,+ max_lo_iters=0,+ confidence=1.0,+ local_optimization="dlt",)batches = []ransac.remove_bad_samples = lambda a, b: (a, b)@@ -1325,8 +1427,9 @@ class TestRANSACAutoBatch(BaseTester):matrix = torch.tensor([[1.0, 0.1, 5.0], [0.0, 1.0, 3.0], [0.0, 0.0, 1.0]], device=device, dtype=dtype)kp2 = transform_points(matrix[None], kp1[None])[0]kp2[:60] = torch.rand(60, 2, device=device, dtype=dtype) * 500- auto = RANSAC("homography", inl_th=1.0, seed=0)- explicit = RANSAC("homography", inl_th=1.0, batch_size=auto.resolve_batch_size(200, kp1.device), seed=0)+ auto = RANSAC("homography", inl_th=1.0, seed=0, local_optimization="dlt")+ batch = auto.resolve_batch_size(200, kp1.device)+ explicit = RANSAC("homography", inl_th=1.0, batch_size=batch, seed=0, local_optimization="dlt")H_auto, mask_auto = auto(kp1, kp2)H_explicit, mask_explicit = explicit(kp1, kp2)assert torch.equal(mask_auto, mask_explicit)@@ -1347,7 +1450,15 @@ class TestRANSACBoundedLO(BaseTester):def test_subset_refits_and_final_full_refit(self, device, dtype):points = torch.rand(100, 2, device=device, dtype=dtype)matrix = torch.eye(3, device=device, dtype=dtype)[None]- ransac = RANSAC("fundamental", batch_size=1, max_iter=1, max_lo_iters=3, lo_sample_size=16, seed=0)+ ransac = RANSAC(+ "fundamental",+ batch_size=1,+ max_iter=1,+ max_lo_iters=3,+ lo_sample_size=16,+ seed=0,+ local_optimization="dlt",+ )ransac.minimal_solver = lambda a, b, w: matrixsizes = []ransac.polisher_solver = lambda a, b, w: sizes.append(a.shape[:2]) or matrix@@ -1362,7 +1473,14 @@ class TestRANSACBoundedLO(BaseTester):wrong = identity.clone()wrong[:, 0, 2] = 100ransac = RANSAC(- "homography", batch_size=1, max_iter=1, max_lo_iters=2, lo_sample_size=8, score_type="msac", seed=3+ "homography",+ batch_size=1,+ max_iter=1,+ max_lo_iters=2,+ lo_sample_size=8,+ score_type="msac",+ seed=3,+ local_optimization="dlt",)ransac.minimal_solver = lambda a, b, w: identityransac.remove_bad_samples = lambda a, b: (a, b)@@ -1374,7 +1492,15 @@ class TestRANSACBoundedLO(BaseTester):def test_seeded_subsets_reproducible(self, device, dtype):points = torch.rand(50, 2, device=device, dtype=dtype)identity = torch.eye(3, device=device, dtype=dtype)[None]- ransac = RANSAC("homography", batch_size=1, max_iter=1, max_lo_iters=2, lo_sample_size=8, seed=13)+ ransac = RANSAC(+ "homography",+ batch_size=1,+ max_iter=1,+ max_lo_iters=2,+ lo_sample_size=8,+ seed=13,+ local_optimization="dlt",+ )ransac.minimal_solver = lambda a, b, w: identityransac.remove_bad_samples = lambda a, b: (a, b)subsets = []@@ -1399,12 +1525,21 @@ class TestRANSACValidation(BaseTester):{"confidence": 1.5},{"confidence": 0.0},{"lo_sample_size": 3},+ {"local_optimization": "irls"},+ {"refine_iters": -1},+ {"refine_iters": True},+ {"refine_iters": 1.5},],)def test_invalid_configuration(self, kwargs):with pytest.raises(ValueError):RANSAC(**kwargs)+ @pytest.mark.parametrize("model_type", ["essential", "homography_from_linesegments"])+ def test_lm_local_optimization_needs_a_supported_model(self, model_type):+ with pytest.raises(ValueError):+ RANSAC(model_type, local_optimization="lm")+@pytest.mark.parametrize("model", ["fundamental_7pt", "essential"])def test_mismatched_correspondences(self, device, dtype, model):points = torch.zeros(9, 2, device=device, dtype=dtype)@@ -1512,3 +1647,291 @@ class TestRANSACEssentialInvalidPolisher(BaseTester):model, mask = estimator(points, points)assert torch.isfinite(model).all()assert mask.all()+++def _skew(v: torch.Tensor) -> torch.Tensor:+ return torch.tensor([[0.0, -v[2], v[1]], [v[2], 0.0, -v[0]], [-v[1], v[0], 0.0]], dtype=v.dtype)+++def _two_view_scene(n: int, outliers: int, noise: float, seed: int):+ """Pixel matches of a 640x480 two-view scene, the first ``outliers`` replaced by random points. float64 CPU.++ Returns the matches, their noise-free second-image positions, the ground-truth F and the inlier mask.+ """+ generator = torch.Generator().manual_seed(seed)+ f64 = torch.float64+ K = torch.tensor([[800.0, 0.0, 320.0], [0.0, 800.0, 240.0], [0.0, 0.0, 1.0]], dtype=f64)+ R = axis_angle_to_rotation_matrix(torch.tensor([[0.05, -0.1, 0.02]], dtype=f64))[0]+ t = torch.tensor([1.0, 0.1, 0.2], dtype=f64)+ X = torch.randn(n, 3, generator=generator, dtype=f64) * torch.tensor([2.0, 2.0, 1.0], dtype=f64)+ X = X + torch.tensor([0.0, 0.0, 8.0], dtype=f64)+ kp1 = convert_points_from_homogeneous(X @ K.T)+ clean = convert_points_from_homogeneous((X @ R.T + t) @ K.T)+ kp2 = clean + noise * torch.randn(n, 2, generator=generator, dtype=f64)+ kp2[:outliers] = torch.rand(outliers, 2, generator=generator, dtype=f64) * torch.tensor([640.0, 480.0], dtype=f64)+ F = torch.linalg.inv(K).T @ _skew(t) @ R @ torch.linalg.inv(K)+ inliers = torch.arange(n) >= outliers+ return kp1, kp2, clean, F / F.norm(), inliers+++def _planar_scene(n: int, outliers: int, noise: float, seed: int):+ """Matches ``kp2 = H(kp1)`` over 600x600 px, the first ``outliers`` replaced by random points. float64 CPU."""+ generator = torch.Generator().manual_seed(seed)+ f64 = torch.float64+ H = torch.tensor([[1.1, 0.05, 20.0], [0.02, 0.95, -10.0], [1e-4, 2e-4, 1.0]], dtype=f64)+ kp1 = torch.rand(n, 2, generator=generator, dtype=f64) * 600+ clean = transform_points(H[None], kp1[None])[0]+ kp2 = clean + noise * torch.randn(n, 2, generator=generator, dtype=f64)+ kp2[:outliers] = torch.rand(outliers, 2, generator=generator, dtype=f64) * 600+ return kp1, kp2, clean, H, torch.arange(n) >= outliers+++def _model_errors(model_type: str, model: torch.Tensor, kp1: torch.Tensor, kp2: torch.Tensor) -> torch.Tensor:+ """Unsquared pixel errors in float64: Sampson distances, or one-way transfer errors for homographies."""+ model, kp1, kp2 = model.cpu().double(), kp1.cpu().double(), kp2.cpu().double()+ if model_type == "homography":+ return oneway_transfer_error(kp1[None], kp2[None], model[None], squared=False, eps=0.0)[0]+ return sampson_epipolar_distance(kp1[None], kp2[None], model[None], squared=False, eps=0.0)[0]+++def _scene(model_type: str, n: int, outliers: int, noise: float, seed: int):+ return (_planar_scene if model_type == "homography" else _two_view_scene)(n, outliers, noise, seed)+++_LM_MODELS = ["homography", "fundamental", "fundamental_8pt"]+++class TestRANSACLevenbergMarquardt(BaseTester):+ """``local_optimization="lm"``, the default for homographies and fundamental matrices."""++ @pytest.mark.parametrize("model_type", _LM_MODELS)+ def test_recovers_exact_model_among_outliers(self, device, dtype, model_type):+ if dtype in (torch.float16, torch.bfloat16):+ pytest.skip("sub-pixel checks on 600 px coordinates are below half-precision resolution")+ kp1, kp2, _, _, inliers = _scene(model_type, 200, 60, 0.0, seed=0)+ ransac = RANSAC(model_type, inl_th=1.0, seed=0)+ model, mask = ransac(kp1.to(device, dtype), kp2.to(device, dtype))+ assert model.shape == (3, 3) and model.dtype == dtype and model.device == kp1.to(device).device+ assert mask.shape == (200,) and mask.dtype == torch.bool and mask.device == model.device+ assert torch.equal(mask.cpu(), inliers)+ tolerance = 1e-4 if dtype == torch.float64 else 5e-2+ assert _model_errors(model_type, model, kp1[inliers], kp2[inliers]).max() < tolerance++ @pytest.mark.parametrize("model_type", _LM_MODELS)+ def test_mask_holds_the_inliers_of_the_returned_model(self, device, dtype, model_type):+ kp1, kp2, _, _, _ = _scene(model_type, 300, 120, 0.7, seed=1)+ kp1, kp2 = kp1.to(device, dtype), kp2.to(device, dtype)+ model, mask = RANSAC(model_type, inl_th=1.5, seed=0)(kp1, kp2)+ errors = _model_errors(model_type, model, kp1, kp2)+ # Classify the returned model on the actual input coordinates, including rounding in half precision.+ assert mask.any()+ assert torch.equal(mask.cpu(), errors <= 1.5)++ def test_msac_does_not_discard_supported_candidates(self, device, dtype, monkeypatch):+ if dtype in (torch.float16, torch.bfloat16):+ pytest.skip("this tight-threshold regression uses float32/float64 coordinates")+ generator = torch.Generator().manual_seed(31)+ kp1 = (torch.rand(40, 2, generator=generator) * 100).to(device, dtype)+ kp2 = (torch.rand(40, 2, generator=generator) * 100).to(device, dtype)+ # Fix the sampled sets across backends: CPU and CUDA generators give different draws for the same seed.+ ransac = RANSAC("fundamental_8pt", seed=0, max_samples=256, confidence=1, inl_th=0.3)+ samples = ransac.sample(8, 40, 256, 0, device="cpu").to(device)+ monkeypatch.setattr(ransac, "sample", lambda *args, **kwargs: samples)+ # The eight highest MSAC scores belong to models supported by at most their eight-point sample.+ # A lower-scoring candidate has additional support and must remain eligible for local optimization.+ model, mask = ransac(kp1, kp2)+ assert mask.sum() > 8+ assert torch.isfinite(model).all()++ def test_failure_when_model_cast_loses_support(self, device, dtype):+ if dtype != torch.bfloat16:+ pytest.skip("the model loses consensus when rounded to bfloat16")+ kp1, kp2, _, _, _ = _scene("homography", 12, 0, 0.0, seed=1)+ model, mask = RANSAC("homography", seed=0, max_samples=256, inl_th=0.5)(+ kp1.to(device, dtype), kp2.to(device, dtype)+ )+ assert not mask.any()+ assert torch.equal(model, torch.zeros_like(model))++ @pytest.mark.parametrize("model_type", _LM_MODELS)+ def test_refinement_improves_on_the_minimal_model(self, device, dtype, model_type):+ if dtype in (torch.float16, torch.bfloat16):+ pytest.skip("sub-pixel accuracy on 600 px coordinates is below half-precision resolution")+ kp1, kp2, clean, _, inliers = _scene(model_type, 300, 90, 0.5, seed=2)+ args = kp1.to(device, dtype), kp2.to(device, dtype)+ minimal, _ = RANSAC(model_type, inl_th=1.5, seed=0, max_lo_iters=0, refine_iters=0)(*args)+ refined, _ = RANSAC(model_type, inl_th=1.5, seed=0)(*args)+ # The distance of the noise-free matches from each model: the best of the minimal models misses them by 0.2+ # to 0.4 px at 0.5 px of noise, the Levenberg-Marquardt refits on two hundred inliers by about 0.1 px.+ miss_minimal = _model_errors(model_type, minimal, kp1[inliers], clean[inliers]).mean()+ miss_refined = _model_errors(model_type, refined, kp1[inliers], clean[inliers]).mean()+ assert miss_refined < 0.75 * miss_minimal+ assert miss_refined < 0.15++ @pytest.mark.parametrize("model_type", _LM_MODELS)+ def test_no_consensus_returns_the_failure_result(self, device, dtype, model_type):+ generator = torch.Generator().manual_seed(0)+ kp1 = (torch.rand(40, 2, generator=generator) * 600).to(device, dtype)+ kp2 = (torch.rand(40, 2, generator=generator) * 600).to(device, dtype)+ # A sample's model fits its own points; at 1e-4 px no other random point is expected on an epipolar line.+ model, mask = RANSAC(model_type, inl_th=1e-4, seed=0, max_samples=512)(kp1, kp2)+ assert bool((model == 0).all()) and model.dtype == dtype+ assert mask.shape == (40,) and mask.dtype == torch.bool and not bool(mask.any())++ @pytest.mark.parametrize("model_type", _LM_MODELS)+ def test_nonfinite_correspondences_are_outliers(self, device, dtype, model_type):+ if dtype in (torch.float16, torch.bfloat16):+ pytest.skip("sub-pixel checks on 600 px coordinates are below half-precision resolution")+ kp1, kp2, _, _, _ = _scene(model_type, 150, 0, 0.0, seed=3)+ kp1[:3] = float("nan")+ kp2[3:6, 0] = float("inf")+ model, mask = RANSAC(model_type, inl_th=1.0, seed=0)(kp1.to(device, dtype), kp2.to(device, dtype))+ assert torch.isfinite(model).all()+ assert not bool(mask[:6].any()) and bool(mask[6:].all())++ @pytest.mark.parametrize("model_type", _LM_MODELS)+ def test_seeded_call_is_reproducible_and_private(self, device, dtype, model_type):+ kp1, kp2, _, _, _ = _scene(model_type, 120, 50, 0.5, seed=4)+ kp1, kp2 = kp1.to(device, dtype), kp2.to(device, dtype)+ state = torch.get_rng_state()+ model_a, mask_a = RANSAC(model_type, inl_th=2.0, seed=11, max_samples=1024)(kp1, kp2)+ assert torch.equal(torch.get_rng_state(), state)+ torch.manual_seed(123)+ model_b, mask_b = RANSAC(model_type, inl_th=2.0, seed=11, max_samples=1024)(kp1, kp2)+ assert torch.equal(model_a, model_b) and torch.equal(mask_a, mask_b)++ @pytest.mark.parametrize("score_type", ["msac", "ransac"])+ def test_score_types(self, device, dtype, score_type):+ if dtype in (torch.float16, torch.bfloat16):+ pytest.skip("sub-pixel checks on 600 px coordinates are below half-precision resolution")+ kp1, kp2, _, _, inliers = _planar_scene(200, 80, 0.0, seed=5)+ _, mask = RANSAC("homography", inl_th=1.0, score_type=score_type, seed=0)(+ kp1.to(device, dtype), kp2.to(device, dtype)+ )+ assert torch.equal(mask.cpu(), inliers)++ def test_half_precision_inputs(self, device, dtype):+ if dtype not in (torch.float16, torch.bfloat16):+ pytest.skip("half-precision inputs only")+ # A 10 px extent keeps bfloat16 rounding of the exact matches below inl_th; the pipeline computes in float32.+ kp1, kp2, _, _, inliers = _planar_scene(64, 16, 0.0, seed=6)+ kp1, kp2 = kp1 / 60, kp2 / 60+ kp2[:16] = torch.rand(16, 2, generator=torch.Generator().manual_seed(0), dtype=torch.float64) * 10 + 20+ model, mask = RANSAC("homography", inl_th=0.5, seed=0)(kp1.to(device, dtype), kp2.to(device, dtype))+ assert model.dtype == dtype and torch.isfinite(model).all()+ assert torch.equal(mask.cpu(), inliers)++ @pytest.mark.parametrize(+ "model_type, max_samples, expected",+ [("homography", 2000, [512, 1024, 464]), ("fundamental", 2000, [256, 512, 1024, 208])],+ )+ def test_auto_batches_grow_on_cpu_and_cover_the_budget(self, device, model_type, max_samples, expected):+ if device.type != "cpu":+ pytest.skip("the CPU batch schedule")+ # confidence=1 draws the whole budget: batches double from the first one, the last is cut to the budget.+ kp1, kp2, _, _, _ = _scene(model_type, 100, 30, 0.5, seed=7)+ ransac = RANSAC(model_type, max_samples=max_samples, confidence=1.0, seed=0)+ sizes = []+ sample = ransac.sample+ ransac.sample = lambda m, n, batch, *a, _s=sample, **k: sizes.append(batch) or _s(m, n, batch, *a, **k)+ ransac(kp1.float(), kp2.float())+ assert sizes == expected++ def test_explicit_batch_size_is_kept(self, device):+ kp1, kp2, _, _, _ = _planar_scene(100, 30, 0.5, seed=8)+ ransac = RANSAC("homography", batch_size=300, max_samples=1000, confidence=1.0, seed=0)+ sizes = []+ sample = ransac.sample+ ransac.sample = lambda m, n, batch, *a, _s=sample, **k: sizes.append(batch) or _s(m, n, batch, *a, **k)+ ransac(kp1.to(device, torch.float32), kp2.to(device, torch.float32))+ assert sizes == [300, 300, 300, 100]++ def test_prosac_offset_continues_the_schedule(self, device):+ # Batches of different sizes pass the number of sets drawn so far: each growth draw includes the newest+ # correspondence of its prefix, so its largest index follows the schedule from that offset.+ ransac = RANSAC("homography", max_samples=1000, prosac_sampling=True, seed=0)+ ends = ransac._prosac_schedule(4, 100, device)+ samples = ransac.sample(4, 100, 50, 3, device, offset=120)+ draws = torch.arange(121, 171, device=device)+ assert samples.amax(1).tolist() == (torch.searchsorted(ends, draws) + 3).tolist()+ # Without an offset, the batch index times the batch size is assumed, as before.+ assert torch.equal(ransac.sample(4, 100, 40, 3, device), ransac.sample(4, 100, 40, 3, device, offset=120))++ def test_prosac_finds_the_ranked_consensus(self, device, dtype):+ if dtype in (torch.float16, torch.bfloat16):+ pytest.skip("sub-pixel checks on 600 px coordinates are below half-precision resolution")+ # 60 of 300 matches follow the homography and are ranked first.+ kp1, kp2, _, _, inliers = _planar_scene(300, 240, 0.0, seed=9)+ kp1, kp2, inliers = kp1.flip(0), kp2.flip(0), inliers.flip(0)+ _, mask = RANSAC("homography", inl_th=1.0, prosac_sampling=True, seed=0)(+ kp1.to(device, dtype), kp2.to(device, dtype)+ )+ assert torch.equal(mask.cpu(), inliers)+++class TestRANSACLevenbergMarquardtKernels(BaseTester):+ """RANSAC's normalization and the Levenberg-Marquardt refiners it calls."""++ def _skip_half(self, dtype):+ if dtype in (torch.float16, torch.bfloat16):+ pytest.skip("the kernels run in float32 or float64")++ def test_normalize_correspondences(self, device, dtype):+ self._skip_half(dtype)+ kp1, kp2, _, _, _ = _two_view_scene(50, 0, 0.0, seed=14)+ kp1[3] = float("nan")+ kp2[7, 0] = float("inf")+ x1, x2, t1, t2, s1, s2 = _normalize_correspondences(kp1, kp2, True)+ finite = torch.ones(50, dtype=torch.bool)+ finite[[3, 7]] = False+ # Correspondences that are not finite in both images stay non-finite and do not enter the statistics.+ assert not torch.isfinite(x1[3]).all()+ assert not torch.isfinite(x2[7]).all()+ c1, c2 = kp1[finite].mean(0), kp2[finite].mean(0)+ radius = ((kp1[finite] - c1).norm(dim=1).mean() + (kp2[finite] - c2).norm(dim=1).mean()) / 2+ # One scale for both images: sqrt(2) over the mean of the two mean radii (normalize_points adds eps = 1e-8).+ expected_scale = float((radius + 1e-8) / math.sqrt(2.0))+ self.assert_close(torch.tensor([s1, s2]), torch.tensor([expected_scale, expected_scale]), rtol=1e-12, atol=0.0)+ self.assert_close(x1[finite, :2], (kp1[finite] - c1) / s1, rtol=1e-9, atol=1e-12)+ ones = torch.ones(48, 1, dtype=kp1.dtype)+ self.assert_close((t1 @ torch.cat([kp1[finite], ones], 1).T).T, x1[finite])+ self.assert_close((t2 @ torch.cat([kp2[finite], ones], 1).T).T, x2[finite])++ @pytest.mark.parametrize("model_type", ["homography", "fundamental"])+ @pytest.mark.parametrize("loss", ["cauchy", "truncated"])+ def test_refinement_reaches_a_local_minimum(self, device, dtype, model_type, loss):+ self._skip_half(dtype)+ # Noisy inliers only, refined from a perturbed ground truth: the refit's cost is below the start's and does+ # not drop along small steps in any direction of the model's manifold.+ kp1, kp2, _, truth, _ = _scene(model_type, 80, 0, 1.0, seed=13)+ x1, x2, t1, t2, s1, s2 = _normalize_correspondences(kp1, kp2, model_type != "homography")+ if model_type == "homography":+ start = t2 @ truth @ torch.linalg.inv(t1)+ refine, scale2, x2_arg = _refine_homography_lm, (2.0 / s2) ** 2, x2[:, :2]++ def errors(models):+ return _transfer_errors(models, x1, x2[:, :2], 0.0)++ else:+ start = torch.linalg.inv(t2).mT @ truth @ torch.linalg.inv(t1)+ refine, scale2, x2_arg = _refine_fundamental_lm, (2.0 / s1) ** 2, x2++ def errors(models):+ return _sampson_errors(models, x1, x2, 0.0)++ start = start / start.norm()+ start = start + 1e-2 * torch.randn(3, 3, generator=torch.Generator().manual_seed(0), dtype=torch.float64)+ if model_type != "homography":+ start = _rank2_projection(start[None])[0]++ def cost(models):+ r2 = errors(models)+ return (torch.log1p(r2 / scale2) if loss == "cauchy" else torch.fmin(r2, torch.tensor(scale2))).sum(1)++ refined = refine(start[None].to(device), x1.to(device), x2_arg.to(device), None, loss, scale2, 20).cpu()+ assert cost(refined) < cost(start[None])+ steps = 1e-4 * torch.randn(32, 3, 3, generator=torch.Generator().manual_seed(1), dtype=torch.float64)+ neighbours = refined + steps * refined.norm()+ if model_type != "homography":+ neighbours = _rank2_projection(neighbours)+ assert (cost(neighbours) >= cost(refined) * (1 - 1e-9)).all()