🐍 Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
RANSAC: Levenberg-Marquardt local optimization and a new five-point solver for essential matrices (#5078)
Dmytro Mishkina5eecf4e20b1
diff --git a/.github/workflows/pr_test_cpu.yml b/.github/workflows/pr_test_cpu.ymlindex a8c53afe9..b2c2224b0 100644--- a/.github/workflows/pr_test_cpu.yml+++ b/.github/workflows/pr_test_cpu.yml@@ -196,8 +196,8 @@ jobs:# 664 tests down across every subpackage -- `linalg.inv`, `linalg.solve`, `inv_ex`,# `lu_factor_ex` and `F.conv3d` all route through it -- where the same runner on torch# 2.9.1 had 200 failures. The blocker is the *virtual* GPU and not macOS 26: a physical M1- # on macOS 26.5 compiled those shaders in the #4202 comparison. The strict manifest now has- # 12 entries after #4185 fixed the two YUV420/YUV422 empty-input failures.+ # on macOS 26.5 compiled those shaders in the #4202 comparison. The strict manifest is empty+ # since #4185 fixed the two YUV420/YUV422 empty-input failures and #5078 the 12 eigvals ones.# The macOS 15 image is Metal 3 and takes the older kernel path, which is the path that# works on the runner fleet. Two consequences: no job here exercises the Metal 4 path that# users on current macOS run, and when GitHub retires macos-15 this leg stops schedulingdiff --git a/TESTING.md b/TESTING.mdindex cba867346..e94eec927 100644--- a/TESTING.md+++ b/TESTING.md@@ -323,8 +323,9 @@ does not inspect batch rank. That ceiling is why `RANSAC`'sbatched minimal solvers used to raise on MPS([#4201](https://github.com/kornia/kornia/issues/4201)). `_torch_svd_cast` and`_torch_linalg_svdvals` now route such inputs through the CPU, so the fundamental and-homography solvers no longer hit it; `find_essential` still raises, for an unrelated-reason -- `run_5point` calls `torch.linalg.eigvals`, which has no MPS kernel. The ceiling+homography solvers no longer hit it. `find_essential` raised for an unrelated reason --+`run_5point` called `torch.linalg.eigvals`, which has no MPS kernel -- until #5078 moved+those roots to the host. The ceilingis *not* why those solvers are absent from the baseline below -- see the next section:they are skipped, because they abort the process before they can raise.@@ -345,7 +346,7 @@ they are skipped, because they abort the process before they can raise.The `padding_mode="border"` issue in `F.grid_sample` (2D) is worked around in the implementation (`kornia/feature/laf.py`) by clamping the sampling grid to the outermost pixel *centers*, at `±(1 - 1/size)`, and using `padding_mode="zeros"`, which is exactly equivalent. Clamping to `[-1, 1]` is not: with `align_corners=False` that is the outer edge of the border pixel, where bilinear sampling blends it with the zero padding.-**CI coverage.** Pull-request CI runs one blocking MPS leg (`tests-mps` in `.github/workflows/pr_test_cpu.yml`): the newest Python and the newest pinned PyTorch, `float32`, on the GitHub-hosted **`macos-15`** Apple-silicon image. The image is pinned deliberately. `macos-latest` is `macos-26-arm64`, whose GPU is paravirtualized, and on macOS 26 torch 2.14 emits Metal 4 `mpp::tensor_ops::matmul2d` cooperative-tensor shaders that this virtual GPU cannot compile — one specialization failed 664 tests across every subpackage, since `linalg.inv`, `linalg.solve`, `inv_ex`, `lu_factor_ex` and `F.conv3d` all route through it. The defect is the *virtual* GPU, not macOS 26: a physical M1 on macOS 26.5 compiled those shaders in the #4202 comparison. macOS 15 is Metal 3 and takes the older kernel path, which is the path that happens to work on the runner fleet. Two consequences worth knowing: no job in this repository now exercises the Metal 4 path that users on current macOS actually run, and when GitHub retires the `macos-15` image this leg stops scheduling and `collector` goes red with no fallback. Re-test `macos-latest` once upstream guards those kernels by device capability; `macos-14` segfaults inside MPS kernels and must never be used. The comparison is recorded in [#4159](https://github.com/kornia/kornia/issues/4159#issuecomment-5532655834). The exact known-failure baseline from [#4159](https://github.com/kornia/kornia/issues/4159) lives in `testing/known_failure_xfails/mps_float32.txt`: #4202 reduced it from 200 entries to 14, and #4185 then fixed the YUV420/YUV422 empty-input cases, leaving the current 12-entry baseline. `--xfail-known-failures` applies those entries as strict xfails with their exact exception types. A new failure, a different exception, a skipped recorded test, or a fixed test therefore makes CI red.+**CI coverage.** Pull-request CI runs one blocking MPS leg (`tests-mps` in `.github/workflows/pr_test_cpu.yml`): the newest Python and the newest pinned PyTorch, `float32`, on the GitHub-hosted **`macos-15`** Apple-silicon image. The image is pinned deliberately. `macos-latest` is `macos-26-arm64`, whose GPU is paravirtualized, and on macOS 26 torch 2.14 emits Metal 4 `mpp::tensor_ops::matmul2d` cooperative-tensor shaders that this virtual GPU cannot compile — one specialization failed 664 tests across every subpackage, since `linalg.inv`, `linalg.solve`, `inv_ex`, `lu_factor_ex` and `F.conv3d` all route through it. The defect is the *virtual* GPU, not macOS 26: a physical M1 on macOS 26.5 compiled those shaders in the #4202 comparison. macOS 15 is Metal 3 and takes the older kernel path, which is the path that happens to work on the runner fleet. Two consequences worth knowing: no job in this repository now exercises the Metal 4 path that users on current macOS actually run, and when GitHub retires the `macos-15` image this leg stops scheduling and `collector` goes red with no fallback. Re-test `macos-latest` once upstream guards those kernels by device capability; `macos-14` segfaults inside MPS kernels and must never be used. The comparison is recorded in [#4159](https://github.com/kornia/kornia/issues/4159#issuecomment-5532655834). The exact known-failure baseline from [#4159](https://github.com/kornia/kornia/issues/4159) lives in `testing/known_failure_xfails/mps_float32.txt`: #4202 reduced it from 200 entries to 14, #4185 then fixed the YUV420/YUV422 empty-input cases, and #5078 fixed the last 12, the `torch.linalg.eigvals` calls of `find_essential`, which leaves the baseline empty. `--xfail-known-failures` applies the manifest's entries as strict xfails with their exact exception types. A new failure, a different exception, a skipped recorded test, or a fixed test therefore makes CI red.Run the identical contract locally with `pixi run test-mps`. `PYTORCH_ENABLE_MPS_FALLBACK=1` silently routes missing MPS kernels to the CPU and invalidates the baseline, so unset it first. The manifest is a full-suite contract and is not intended for `-k` or partial-directory runs; use `pixi run test-module ... --device=mps --dtype=float32` for focused diagnosis without the manifest. "Full suite" means the suite as an `mps`-only run collects it: tests marked `device_agnostic` are deselected there and covered by the CPU jobs, so they never appear in the manifest.diff --git a/benchmarks/geometry/ransac.py b/benchmarks/geometry/ransac.pyindex 8754a0371..0627e8364 100644--- a/benchmarks/geometry/ransac.py+++ b/benchmarks/geometry/ransac.py@@ -21,7 +21,11 @@ Run from the checkout being measured (copy this harness to older checkouts).Preparation/evaluation require optional h5py and the imc2021-simple package;measurement needs only the normal Kornia environment and NumPy. No downloads.``sweep`` runs kornia at its class defaults with and without PROSAC, and the optional-OpenCV (``cv2``) and PoseLib (``poselib``) reference estimators when installed.+OpenCV (``cv2``) and PoseLib (``poselib``) reference estimators when installed. With+``--model essential`` every method estimates E from the pair's intrinsics: kornia and OpenCV+(``findEssentialMat``) on normalized coordinates with the pixel threshold divided by the mean focal+length, PoseLib (``estimate_relative_pose``) on pixels with its cameras; each E is stored as the+fundamental matrix it implies, so ``evaluate`` scores both models alike.python benchmarks/geometry/ransac.py prepare --data-root ../imc2021-simple/data/phototourism \--scenes sacre_coeur,reichstag --cache sift=raw_matches.h5 \@@ -426,6 +430,42 @@ def base_methods(module: Any, methods: list[str]) -> list[str]:return [m for m in methods if prosac or not SWEEP_KORNIA[m].get("prosac_sampling")]+class PairCalibration:+ """Pixel and normalized camera coordinates of one pair, for the essential-matrix sweep.++ Pixel thresholds become calibrated ones through the mean focal length of the two cameras, as OpenCV's+ ``findEssentialMat`` does for one camera. Every method's essential matrix is stored as the fundamental matrix+ ``K2^-T E K1^-1``, so ``evaluate`` scores all models alike.+ """++ def __init__(self, K1: np.ndarray, K2: np.ndarray) -> None:+ self.K1, self.K2 = K1, K2+ self.inv1, self.inv2 = np.linalg.inv(K1), np.linalg.inv(K2)+ self.focal = float(np.mean([K[[0, 1], [0, 1]].mean() for K in (K1, K2)]))++ def normalized(self, points1: np.ndarray, points2: np.ndarray) -> tuple[np.ndarray, np.ndarray]:+ return tuple( # type: ignore[return-value]+ (np.column_stack((points, np.ones(len(points)))) @ inverse.T)[:, :2]+ for points, inverse in ((points1, self.inv1), (points2, self.inv2))+ )++ def fundamental(self, E: Any) -> np.ndarray:+ return self.inv2.T @ np.asarray(E, dtype=np.float64) @ self.inv1++ def cameras(self, poselib: Any) -> list[Any]:+ """PoseLib pinhole cameras; the image size, unused by the estimator, from the principal point."""+ return [+ poselib.Camera("PINHOLE", [K[0, 0], K[1, 1], K[0, 2], K[1, 2]], int(2 * K[0, 2]), int(2 * K[1, 2]))+ for K in (self.K1, self.K2)+ ]+++def essential_from_pose(R: np.ndarray, t: np.ndarray) -> np.ndarray:+ """``[t]_x R``."""+ tx = np.array([[0.0, -t[2], t[1]], [t[2], 0.0, -t[0]], [-t[1], t[0], 0.0]])+ return tx @ np.asarray(R)++def reference_calls(args: argparse.Namespace,backends: dict[str, Any],@@ -433,12 +473,19 @@ def reference_calls(points1: Any,points2: Any,ranked: bool,+ calibration: PairCalibration | None = None,) -> list[tuple[dict[str, Any], Any]]:- """One timed call per OpenCV/PoseLib method, iteration budget and threshold for a pair."""+ """One timed call per OpenCV/PoseLib method, iteration budget and threshold for a pair.++ With a ``calibration``, the essential-matrix estimators: OpenCV's ``findEssentialMat`` on normalized points with+ the threshold in calibrated units, and PoseLib's ``estimate_relative_pose`` on pixels with its cameras.+ """cv2, poselib = backends.get("cv2"), backends.get("poselib")opencv_methods = [m for m in args.opencv.split(",") if m] if cv2 is not None else []poselib_methods = [m for m in args.poselib.split(",") if m] if poselib is not None else []calls: list[tuple[dict[str, Any], Any]] = []+ normalized = calibration.normalized(points1, points2) if calibration is not None else None+ cameras = calibration.cameras(poselib) if calibration is not None and poselib is not None else Nonefor name, iters, threshold in itertools.product(opencv_methods, [int(x) for x in args.opencv_iters.split(",")], thresholds):@@ -451,7 +498,11 @@ def reference_calls(p2: Any = points2,) -> Any:cv2.setRNGSeed(args.seed)- return cv2.findFundamentalMat(p1, p2, flag, th, args.confidence, iters)+ if calibration is None:+ return cv2.findFundamentalMat(p1, p2, flag, th, args.confidence, iters)+ n1, n2 = normalized+ E, mask = cv2.findEssentialMat(n1, n2, np.eye(3), flag, args.confidence, th / calibration.focal, iters)+ return (E[:3] if E is not None else None), maskconfig = {"method": f"opencv {name}", "device": "cpu", "batch": None}config.update(sample_budget=iters, threshold_px=threshold)@@ -473,6 +524,9 @@ def reference_calls(# ``min_iterations`` (1000) and ``success_prob`` 0.9999 as in imc2021-simple.options = {"max_epipolar_error": th, "progressive_sampling": prosac, "max_iterations": iters}options.update(success_prob=POSELIB_SUCCESS_PROB, seed=args.seed)+ if cameras is not None:+ pose, info = poselib.estimate_relative_pose(p1, p2, cameras[0], cameras[1], options, {})+ return essential_from_pose(pose.R, pose.t), info["inliers"]matrix, info = poselib.estimate_fundamental(p1, p2, options, {})return matrix, info["inliers"] # a Python list; converted after the timer stops@@ -546,9 +600,14 @@ def sweep(args: argparse.Namespace) -> None:if not ranked: # PROSAC needs a best-first order; the export order is not oneprint(f"# NOTE: {key} has no match score or ratio: PROSAC configurations are skipped")order = np.argsort(data[field].reshape(-1), kind="stable") if ranked else np.arange(len(a))- kp1 = torch.as_tensor(a[order], device=device, dtype=torch.float32)- kp2 = torch.as_tensor(b[order], device=device, dtype=torch.float32)points1, points2 = a[order].astype(np.float64), b[order].astype(np.float64)+ calibration = None+ inputs = points1, points2+ if args.model == "essential":+ calibration = PairCalibration(data[f"{key}__a_K"], data[f"{key}__b_K"])+ inputs = calibration.normalized(points1, points2)+ kp1, kp2 = (torch.as_tensor(p, device=device, dtype=torch.float32) for p in inputs)+ units = calibration.focal if calibration is not None else 1.0calls: list[tuple[dict[str, Any], Any]] = []budgets = [int(x) for x in args.budgets.split(",")]for prefix, ransac_class, methods in estimators:@@ -558,8 +617,8 @@ def sweep(args: argparse.Namespace) -> None:# "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,+ model_type=args.model,+ inl_th=threshold / units,batch_size=batch,max_samples=budget,confidence=args.confidence,@@ -570,7 +629,7 @@ def sweep(args: argparse.Namespace) -> None:config = {"method": f"{prefix} {name}", "device": device.type, "batch": batch}config.update(sample_budget=budget, threshold_px=threshold)calls.append((config, partial(estimator, kp1, kp2)))- calls.extend(reference_calls(args, backends, thresholds, points1, points2, ranked))+ calls.extend(reference_calls(args, backends, thresholds, points1, points2, ranked, calibration))for config, call in calls:signature = (config["method"], config["sample_budget"], config["threshold_px"])if signature not in warmed: # first call per configuration: lazy initialization and@@ -592,7 +651,7 @@ def sweep(args: argparse.Namespace) -> None:"pair": key,"scene": scene,"feature": feature,- "model_type": "fundamental",+ "model_type": args.model,"seed": args.seed,"correspondences": len(a),"time_ms": elapsed_ms,@@ -601,8 +660,10 @@ def sweep(args: argparse.Namespace) -> None:if error is not None:row["error"] = errorif torch.is_tensor(matrix):- matrix, mask = matrix.cpu().numpy(), mask.cpu().numpy()+ matrix, mask = matrix.cpu().double().numpy(), mask.cpu().numpy()if matrix is not None and np.shape(matrix) == (3, 3) and np.abs(matrix).max() > 0:+ if calibration is not None:+ matrix = calibration.fundamental(matrix)original = np.zeros(len(a), dtype=bool)original[order] = np.asarray(mask).reshape(-1).astype(bool)packed = base64.b64encode(np.packbits(original).tobytes()).decode()@@ -928,6 +989,12 @@ def main() -> None:sw.add_argument("--device", default="cpu")sw.add_argument("--dtype", choices=("float32",), default="float32")sw.add_argument("--threads", type=int, default=4)+ sw.add_argument(+ "--model",+ choices=("fundamental", "essential"),+ default="fundamental",+ help="essential: calibrated inputs, thresholds in pixels divided by the mean focal length",+ )sw.add_argument("--kornia", default=",".join(SWEEP_KORNIA), help=f"subset of {','.join(SWEEP_KORNIA)}")sw.add_argument("--opencv", default=",".join(SWEEP_OPENCV), help=f"subset of {','.join(SWEEP_OPENCV)}")sw.add_argument("--poselib", default=",".join(SWEEP_POSELIB), help=f"subset of {','.join(SWEEP_POSELIB)}")diff --git a/changelog.d/5078.breaking.md b/changelog.d/5078.breaking.mdnew file mode 100644index 000000000..d0d6f3f5c--- /dev/null+++ b/changelog.d/5078.breaking.md@@ -0,0 +1 @@+`RANSAC("essential")` now defaults to `local_optimization="lm"`: the run's eight best five-point models are refined by Levenberg-Marquardt on the essential manifold, and the winner by a final Cauchy refinement on its inliers, in the caller's calibrated coordinates. Previously `"essential"` only supported `"dlt"`, which refits eight-point fundamental matrices on inlier subsets and projects them onto the manifold; `local_optimization="dlt"` still selects that loop, but its five-point samples now come from the new `find_essential` solver, so its estimates can differ from before at rounding level and in sign. Estimates for a given seed change; the returned E has unit Frobenius norm and a positive largest entry, and the returned mask holds the inliers of the returned matrix. The returned E no longer carries autograd; its gradient to the correspondences was NaN before. Automatic batches for essential matrices now start at 64 samples on CPU and double up to 1024, and start at 256 on CUDA and MPS and double up to 8192, instead of a fixed 128 to 512 samples per batch on CPU and 2048 on CUDA and MPS.diff --git a/changelog.d/5078.fixed.md b/changelog.d/5078.fixed.mdnew file mode 100644index 000000000..303dbfc30--- /dev/null+++ b/changelog.d/5078.fixed.md@@ -0,0 +1 @@+`find_essential` solves in float64 whatever the input dtype, so a float32 five-point sample no longer misses the true essential matrix (#4884); MPS, which has no float64, solves on the host and copies the candidates back. It now runs on MPS, where `torch.linalg.eigvals` raised `NotImplementedError` (#4528), and on float16 and bfloat16 inputs. On 42000 exact five-point samples with random motions it misses the true matrix by more than 1e-3 12 times, where it missed it 31 times. Its roots come from the host for every device, detached, with a Newton step that supplies their gradient, so `backward` no longer raises at a multiple root (#4903) nor returns NaN gradients for samples without parallax (#4952), and repeated calls on CUDA return identical results. A five-point sample whose constraints are rank deficient, such as one with a repeated correspondence, returns ten NaN candidates and a zero gradient. At 2048 samples it takes 29 ms instead of 40 ms on CPU and 21 ms instead of 28 ms on CUDA; at 256 samples it costs about the same on CPU and 1 ms more on CUDA.diff --git a/docs/source/geometry.ransac.rst b/docs/source/geometry.ransac.rstindex df8e68d12..47896ac13 100644--- a/docs/source/geometry.ransac.rst+++ b/docs/source/geometry.ransac.rst@@ -29,8 +29,12 @@ The default ``batch_size="auto"`` picks the batches per call. With the defaultfor homographies, and doubles the batch after each one up to 2048, 4096 forhomographies: inputs with many inliers stop after a small first batch, and theothers 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+is the whole budget up to 8192 samples. Essential matrices start smaller on+every device, with 64 samples up to 1024 on CPU and 256 up to 8192 on CUDA and+MPS: a five-point sample needs few draws at high inlier ratios, and its+eigenvalue solve runs on the host (on MPS, the whole solve). All shrink for many+correspondences, down to 64 samples, so that above that floor a batch scores at+most ``2**22`` (CPU) or ``2**25`` residuals. The rest ofthis 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 are@@ -100,9 +104,11 @@ draws are affordable.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+Homographies, fundamental and essential matrices default to+``local_optimization="lm"``. The sampling loop keeps the eight best-scoring+minimal models of the whole run, in coordinates normalized once per call (the+caller's calibrated ones for essential matrices, see below). After sampling,+all eight are refined together with``max_lo_iters`` Levenberg-Marquardt iterations that minimize the squaredSampson distance or one-way transfer error of every correspondence, truncatedat ``inl_th``. The best-scoring model among the refits and the minimal models@@ -116,8 +122,9 @@ Fundamental matrices keep rank two through the parametrization ofthe refinement follows PoseLib's ``refine_fundamental`` and``refine_homography``. Refining several models once sampling ends, rather thaneach 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+minimal model that improves on the best one so far. The homography and+fundamental-matrix solvers take their null spaces from a partial-pivoted LU+factorization, the five-point solver from Householder reflections, and scores come fromone matrix product per batch, which keeps the per-hypothesis cost low on everydevice. The refinements are a few dozen small operations per iteration and runon the CPU in float64 for every device, where launch latency would dominate.@@ -129,8 +136,23 @@ a third of the time on CPU and half on CUDA; ALIKED matches with LightGlue, onwhich both stop early, take about 0.5 ms longer on CPU. On the HEB homographiesit 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 the+Essential matrices are estimated in the caller's calibrated coordinates, without+the normalization, which would take them off the essential manifold, and are+returned with unit Frobenius norm and their largest entry positive. They are+refined as ``E = U diag(1, 1, 0) V^T`` with five parameters, as many as the+rotation and translation direction of PoseLib's ``refine_relpose``: rotations+of ``U`` about three axes and of ``V`` about its first two, which leaves out+the rotation of both about their third axes that does not change ``E``. The+five-point samples are solved with Nister's method in float64: a Householder+null space, the degree-ten polynomial from polynomial products, and its real+roots from the eigenvalues of its companion matrix on the host. MPS, which has+no float64, solves its samples on the host. On PhotoTourism pairs this raises+the pose mAA of essential matrices by 0.03 to 0.07 over the subset refits+below, in about half the time on CPU, and an eighth of it with 8000 SIFT+features per image.++``local_optimization="dlt"``, the only choice for 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/docs/source/get-started/precision.rst b/docs/source/get-started/precision.rstindex d95f638aa..e42a27dfc 100644--- a/docs/source/get-started/precision.rst+++ b/docs/source/get-started/precision.rst@@ -74,12 +74,12 @@ precision, so the table says nothing about those backends.* - ``kornia.geometry.epipolar``- ⚠️ Partial- ⚠️ Partial- - 53 / 51- - ``find_essential``, ``decompose_essential_matrix``, ``motion_from_essential*``, ``KRt_from_projection``- and the weighted eight-point ``find_fundamental`` raise ``NotImplementedError``: they call ``lu``, ``eigh``- or QR, which have no CPU half-precision kernels. The unweighted eight-point and the seven-point- ``find_fundamental`` factorize in float32 or float64 and return a half-precision ``F``, whose accuracy the- half-precision inputs limit.+ - 42 / 40+ - ``decompose_essential_matrix``, ``motion_from_essential*``, ``KRt_from_projection`` and the weighted+ eight-point ``find_fundamental`` raise ``NotImplementedError``: they call ``lu``, ``eigh`` or QR, which have+ no CPU half-precision kernels. ``find_essential`` solves in float64, and the unweighted eight-point and the+ seven-point ``find_fundamental`` factorize in float32 or float64; they return half-precision results, whose+ accuracy the half-precision inputs limit.* - ``kornia.geometry.homography``- ⚠️ Partial- ⚠️ Partial@@ -112,8 +112,8 @@ precision, so the table says nothing about those backends.* - ``kornia.geometry.ransac``- ⚠️ Partial- ⚠️ Partial- - 3 / 3- - The essential model raises through the epipolar solvers.+ - 2 / 2+ - Essential matrices with ``local_optimization="dlt"`` raise in its eight-point refits, which call ``eigh``.* - ``kornia.geometry`` (other)- ⚠️ Partial- ⚠️ Partialdiff --git a/kornia/geometry/epipolar/essential.py b/kornia/geometry/epipolar/essential.pyindex bfb9facef..adef49bc7 100644--- a/kornia/geometry/epipolar/essential.py+++ b/kornia/geometry/epipolar/essential.py@@ -24,8 +24,10 @@ import torchfrom kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SAME_SHAPE, KORNIA_CHECK_SHAPEfrom kornia.core.ops import eye_like, vec_likefrom kornia.core.utils import _torch_svd_cast-from kornia.geometry.solvers.polynomial_solver import T_deg1, T_deg2, coefficient_map, multiplication_indices, signs+from kornia.geometry.solvers.homogeneous import _null_space_householder+from kornia.geometry.solvers.polynomial_solver import T_deg1, T_deg2+from .fundamental import _epipolar_design_rows, _hat_basis, _sampson_normal_equations, _solve_dtypefrom .numeric import cross_product_matrix, matrix_cofactor_tensorfrom .projection import depth_from_point, projection_from_KRtfrom .triangulation import triangulate_points@@ -61,53 +63,47 @@ def run_5point(points1: torch.Tensor, points2: torch.Tensor, weights: Optional[tKORNIA_CHECK_SHAPE(points1, ["B", "N", "2"])KORNIA_CHECK_SAME_SHAPE(points1, points2)KORNIA_CHECK(points1.shape[1] >= 5, "Number of points should be >=5")-- batch_size, _, _ = points1.shape- x1, y1 = points1[..., 0:1], points1[..., 1:2]- x2, y2 = points2[..., 0:1], points2[..., 1:2]- ones = torch.ones_like(x1)- # build the equation system and find the null space.- # https://www.cc.gatech.edu/~afb/classes/CS4495-Fall2013/slides/CS4495-09-TwoViews-2.pdf- # [x * x', x * y', x, y * x', y * y', y, x', y', 1]- # BxNx9- X = torch.cat([x1 * x2, x1 * y2, x1, y1 * x2, y1 * y2, y1, x2, y2, ones], dim=-1)- # use Nister's 5PC to solve essential matrix+ # Rows vec(x2 x1^T), so that a null vector reshapes row-major to E.+ design = _epipolar_design_rows(points1, points2)# A sample without a real root keeps ten NaN slots, like the complex slots of any other sample.- return null_to_Nister_solution(X, batch_size)---def _multiply_deg_one_poly(a: torch.Tensor, b: torch.Tensor, T_deg1: torch.Tensor) -> torch.Tensor:- # a, b: (..., 4)- product_basis = a.unsqueeze(2) * b.unsqueeze(1) # (..., 4, 4)- product_vector = product_basis.flatten(start_dim=-2) # (..., 16)- return product_vector @ T_deg1 # (..., 10)-+ if design.shape[1] == 5:+ candidates, _ = _five_point_candidates(design)+ else:+ candidates = _least_squares_candidates(design)+ return candidates-def _multiply_deg_two_one_poly(a: torch.Tensor, b: torch.Tensor, T_deg2: torch.Tensor) -> torch.Tensor:- # a: (..., 10), b: (..., 4)- product_basis = a.unsqueeze(2) * b.unsqueeze(1) # (..., 10, 4)- product_vector = product_basis.flatten(start_dim=-2) # (..., 40)- return product_vector @ T_deg2 # (..., 20)+def _polynomial_product_table(m: int, n: int, dtype: torch.dtype, device: torch.device) -> torch.Tensor:+ """``T[i, j, i + j] = 1``: the coefficients of a product of polynomials with ``m`` and ``n`` coefficients."""+ i, j = torch.meshgrid(torch.arange(m, device=device), torch.arange(n, device=device), indexing="ij")+ table = torch.zeros(m, n, m + n - 1, dtype=dtype, device=device)+ table[i, j, i + j] = 1.0+ return table-def _determinant_to_polynomial_jit(- A: torch.Tensor,- multiplication_indices: torch.Tensor,- signs: torch.Tensor,- coefficient_map: torch.Tensor,-) -> torch.Tensor:- # A: (B, 3, 13) -> (B, 11)- B = A.shape[0]- A_flat = A.view(B, -1) # (B, 39)- gathered_values = A_flat[:, multiplication_indices] # (B, 486, 3)- products = torch.prod(gathered_values, dim=-1) # (B, 486)- signed_products = products * signs # (B, 486)+def _determinant_to_polynomial_jit(A: torch.Tensor) -> torch.Tensor:+ """Coefficients ``(B, 11)``, of ``z^0`` first, of the determinant of Nister's hidden-variable matrix ``(B, 3, 13)``.- cs = torch.zeros(B, 11, device=A.device, dtype=A.dtype)- batch_coefficient_map = coefficient_map.unsqueeze(0).expand(B, -1) # (B, 486)- cs.scatter_add_(1, batch_coefficient_map, signed_products)- return cs+ Each row of ``A`` holds three polynomials in ``z``, highest degree first: two cubics (columns 0-3 and 4-7) and a+ quartic (8-12). The determinant is the sum over the six permutations of the rows of signed products of one+ polynomial of each kind, expanded with polynomial product tables: a few matrix products, deterministic on every+ backend, where the explicit expansion into 486 triple products cost five times as much.+ """+ device, dtype = A.device, A.dtype+ levi_civita = torch.zeros(3, 3, 3, dtype=dtype, device=device)+ for (a, b, c), sign in (+ ((0, 1, 2), 1.0),+ ((1, 2, 0), 1.0),+ ((2, 0, 1), 1.0),+ ((0, 2, 1), -1.0),+ ((2, 1, 0), -1.0),+ ((1, 0, 2), -1.0),+ ):+ levi_civita[a, b, c] = sign+ cubic1, cubic2, quartic = A[..., 0:4].flip(-1), A[..., 4:8].flip(-1), A[..., 8:13].flip(-1)+ sextics = torch.einsum("xai,xbj,ijm->xabm", cubic1, cubic2, _polynomial_product_table(4, 4, dtype, device))+ signed = torch.einsum("xabm,abc->xcm", sextics, levi_civita)+ return torch.einsum("xcm,xck,mkn->xn", signed, quartic, _polynomial_product_table(7, 5, dtype, device))def _solve_2x2_tikhonov_safe(A: torch.Tensor, b: torch.Tensor, eps: float = 1e-12) -> Tuple[torch.Tensor, torch.Tensor]:@@ -184,11 +180,6 @@ def _solve_2x2_tikhonov_safe(A: torch.Tensor, b: torch.Tensor, eps: float = 1e-1return x, bad-# --- fun_select inline, to keep it JIT-simple ----def _fun_select(mat: torch.Tensor, i: int, j: int, ratio: int = 3) -> torch.Tensor:- return mat[:, ratio * j + i]--class _NullSpaceBasis(torch.autograd.Function):r"""The four right singular vectors of ``X`` with the smallest singular values, differentiably.@@ -239,277 +230,209 @@ class _NullSpaceBasis(torch.autograd.Function):return (X_ @ (M + M.transpose(-1, -2))).to(X.dtype)-def _null_to_Nister_solution_script(- X: torch.Tensor,- batch_size: int,- T_deg1: torch.Tensor,- T_deg2: torch.Tensor,- multiplication_indices: torch.Tensor,- signs: torch.Tensor,- coefficient_map: torch.Tensor,- idx_ij: torch.Tensor, # kept for signature compatibility (unused)- i_idx: torch.Tensor,- j_idx: torch.Tensor,- idx3: torch.Tensor,- top_idx: torch.Tensor,- bot_idx: torch.Tensor,-) -> torch.Tensor:- original_dtype = X.dtype+def _least_squares_basis(design: torch.Tensor) -> torch.Tensor:+ """Least-squares null space ``(B, 9, 4)`` of design rows ``(B, N, 9)`` with ``N > 5``.- if X.shape[-2] < 9:- null_ = _NullSpaceBasis.apply(X)[0] # (B, 9, 4)- nullSpace = null_.transpose(-1, -2) # (B, 4, 9)- else:- # every right singular vector has a gradient in torch.linalg.svd itself- _, _, V = _torch_svd_cast(X) # V: (B, 9, 9)- null_ = V[:, :, -4:].contiguous() # (B, 9, 4)- nullSpace = V.transpose(-1, -2)[:, -4:, :] # (B, 4, 9)-- B = batch_size- device = X.device- dtype = X.dtype-- coeffs = torch.zeros(B, 10, 20, device=device, dtype=dtype)-- # (B,9,4) -> (B,3,3,4) with column-major fix- null_ij = null_.view(B, 3, 3, 4).transpose(1, 2).contiguous() # (B, 3, 3, 4)-- # ---- determinant constraint ----- n00 = null_ij[:, 0, 0, :]- n01 = null_ij[:, 0, 1, :]- n02 = null_ij[:, 0, 2, :]- n10 = null_ij[:, 1, 0, :]- n11 = null_ij[:, 1, 1, :]- n12 = null_ij[:, 1, 2, :]- n20 = null_ij[:, 2, 0, :]- n21 = null_ij[:, 2, 1, :]- n22 = null_ij[:, 2, 2, :]-- # small reuse to reduce launches- p01_12 = _multiply_deg_one_poly(n01, n12, T_deg1)- p02_11 = _multiply_deg_one_poly(n02, n11, T_deg1)- p02_10 = _multiply_deg_one_poly(n02, n10, T_deg1)- p00_12 = _multiply_deg_one_poly(n00, n12, T_deg1)- p00_11 = _multiply_deg_one_poly(n00, n11, T_deg1)- p01_10 = _multiply_deg_one_poly(n01, n10, T_deg1)-- coeffs[:, 9] = (- _multiply_deg_two_one_poly(p01_12 - p02_11, n20, T_deg2)- + _multiply_deg_two_one_poly(p02_10 - p00_12, n21, T_deg2)- + _multiply_deg_two_one_poly(p00_11 - p01_10, n22, T_deg2)- )+ The four right singular vectors with the smallest singular values, in+ :func:`~kornia.geometry.epipolar.fundamental._solve_dtype`.+ """+ design = design.to(_solve_dtype(design.device))+ if design.shape[-2] < 9:+ return _NullSpaceBasis.apply(design)[0]+ # every right singular vector has a gradient in torch.linalg.svd itself+ _, _, V = _torch_svd_cast(design)+ return V[:, :, -4:]- # ---- EE^T constraints ----- a_data = null_ij[:, i_idx, :, :] # (B,9,3,4)- b_data = null_ij[:, j_idx, :, :] # (B,9,3,4)- prods = _multiply_deg_one_poly(a_data.reshape(-1, 4), b_data.reshape(-1, 4), T_deg1).view(B, 9, 3, 10)- D_blocks = prods.sum(dim=2).view(B, 3, 3, 10).contiguous()-- # trace removal- diag = D_blocks[:, idx3, idx3, :] # (B,3,10)- t = 0.5 * diag.sum(dim=1, keepdim=True) # (B,1,10)- D_blocks[:, idx3, idx3, :] = D_blocks[:, idx3, idx3, :] - t-- # first 9 rows of coeffs- D_for_i = D_blocks[:, i_idx, :, :] # (B,9,3,10)- Null_for_j = null_ij[:, :, j_idx, :].permute(0, 2, 1, 3).contiguous() # (B,9,3,4)- prods2 = _multiply_deg_two_one_poly(D_for_i.reshape(-1, 10), Null_for_j.reshape(-1, 4), T_deg2).view(B, 9, 3, 20)- coeffs[:, :9, :] = prods2.sum(dim=2) # (B,9,20)-- # ---- elimination: solve A10 * X = b_poly ----- A10 = coeffs[:, :, :10] # (B, 10, 10)- b_poly = coeffs[:, :, 10:] # (B, 10, 10)-- eye10 = torch.eye(10, device=device, dtype=dtype).unsqueeze(0).expand(B, 10, 10)-- # An exactly singular A10 means the sample has no solution. torch.linalg.solve raises on such an- # element rather than returning NaN, so the singular elements are found first with lu_factor_ex,- # which reports a zero pivot through ``info`` instead of raising, and are solved against the- # identity so that nothing below can raise or overflow on them in the forward pass. Their- # candidates are set to NaN at the end, so all ten of their slots are NaN. Every- # other element keeps A10: the replacement is made in ``coeffs`` and sliced like A10, because- # torch.linalg.solve can round a contiguous copy differently from the strided slice.- _, _, info = torch.linalg.lu_factor_ex(A10)- singular = info > 0 # (B,)- A_solve = A10- if singular.any():- A_solve = torch.where(singular.view(B, 1, 1), torch.cat((eye10, b_poly), dim=-1), coeffs)[:, :, :10]-- # Try direct solve first- eliminated = torch.linalg.solve(A_solve, b_poly) # (B,10,10)-- # Detect NaN/Inf from an ill-conditioned solve and fix with damping solve- bad = torch.isnan(eliminated).flatten(-2).any(-1) | torch.isinf(eliminated).flatten(-2).any(-1) # (B,)- if bad.any():- # Damped solve only for bad rows but WITHOUT compaction:- # build damped A = A10 + λI, where λ depends on scale- # (use per-batch scalar to avoid huge allocations)- diagA = torch.diagonal(A10, dim1=-2, dim2=-1).abs().mean(dim=-1) # (B,)- lam = (diagA * 1e-8 + 1e-8).to(dtype) # (B,)- # built from A_solve, not A10, so a singular element in the same batch cannot raise here- A_damped = A_solve + eye10 * lam.view(B, 1, 1)- eliminated_d = torch.linalg.solve(A_damped, b_poly)- eliminated = torch.where(bad.view(B, 1, 1), eliminated_d, eliminated)-- coeffs_ = torch.cat((A10, eliminated), dim=-1) # (B,10,20)-- # ---- build A (B,3,13) ----- A = torch.zeros(B, 3, 13, device=device, dtype=dtype)- A[:, :, 1:4] = coeffs_[:, top_idx, 10:13]- A[:, :, 0:3] = A[:, :, 0:3] - coeffs_[:, bot_idx, 10:13]-- A[:, :, 5:8] = coeffs_[:, top_idx, 13:16]- A[:, :, 4:7] = A[:, :, 4:7] - coeffs_[:, bot_idx, 13:16]-- A[:, :, 9:13] = coeffs_[:, top_idx, 16:20]- A[:, :, 8:12] = A[:, :, 8:12] - coeffs_[:, bot_idx, 16:20]-- # ---- determinant polynomial -> companion ----- cs = _determinant_to_polynomial_jit(A, multiplication_indices, signs, coefficient_map) # (B,11)-- C = torch.zeros(B, 10, 10, device=device, dtype=dtype)- C[:, 0:9, 1:10] = torch.eye(9, device=device, dtype=dtype)-- # Guard only an exactly zero leading coefficient. The roots do not depend on the polynomial's sign,- # and a floor such as clamp_min would turn a negative coefficient positive and change them. An- # element with a zero one is discarded below; the floor only keeps its companion matrix finite.- cs_de = torch.where(cs[:, -1] == 0, torch.full_like(cs[:, -1], 1e-8), cs[:, -1])- C[:, -1, :] = -cs[:, :-1] / cs_de.unsqueeze(-1)-- # A companion matrix that is not finite has no usable roots, and torch.linalg.eigvals aborts on it,- # which takes the whole batch down: a RuntimeError on some platforms, a crash inside MKL on others.- # It comes from an overflow: an elimination system that is ill-conditioned without being exactly- # singular has a solution large enough for the determinant polynomial to overflow, or a finite- # polynomial overflows when it is divided by its leading coefficient. Nor has a polynomial whose- # leading coefficient is exactly zero: its degree is below 10, the floor above scales its companion- # row by 1e8, and the eigenvalues are not its roots. Its eigenvector matrix can then be singular,- # which makes the eigvals backward raise. Those elements get the identity in place of C, and their- # candidates are set to NaN at the end, like a singular one.- no_roots = ~torch.isfinite(C).flatten(-2).all(-1) | (cs[:, -1] == 0) # (B,)- if no_roots.any():- C = torch.where(no_roots.view(B, 1, 1), eye10, C)-- if C.device.type == "cuda":- # torch.linalg.eigvals has no batched CUDA kernel: it hands the companion matrices to cusolver one- # at a time with a synchronization each, about 3.6 ms per 10x10 matrix, so a RANSAC batch of 2048- # five-point samples spent 6.4 s here. LAPACK on the host takes about 15 ms for the same batch,- # transfers included, and the transfers are differentiable.- roots_eig = torch.linalg.eigvals(C.cpu()).to(C.device) # (B,10), complex- else:- roots_eig = torch.linalg.eigvals(C) # (B,10), complex- roots = torch.real(roots_eig)- is_real = torch.abs(torch.imag(roots_eig)) < 1e-10+def _least_squares_candidates(design: torch.Tensor) -> torch.Tensor:+ """Nister's candidates ``(B, 10, 3, 3)`` of design rows ``(B, N, 9)`` with ``N > 5``, on the design's device.++ MPS inputs are solved on the host, as in :func:`_five_point_candidates`.+ """+ if design.device.type == "mps":+ return _least_squares_candidates(design.cpu()).to(design.device)+ return _nister_candidates(_least_squares_basis(design), design.dtype)[0]+++def _five_point_candidates(design: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:+ """Nister's five-point solver on the epipolar design rows ``(B, 5, 9)`` of minimal samples.- roots_unsqu = roots.unsqueeze(1) # (B,1,10)+ The four-dimensional null space comes from batched Householder reflections,+ :func:`~kornia.geometry.solvers.homogeneous._null_space_householder`, and everything up to the roots is computed+ in float64, so a float32 sample does not lose its true solution to rounding.+ A sample whose design rows are rank deficient, such as one with a repeated correspondence or points collinear in+ both images, has a null space of more than four dimensions and no unique solution: all ten of its slots are NaN.+ It is found by a partial-pivoted LU factorization of the detached rows. Rounding rarely leaves an exactly zero+ pivot, so rank deficiency is a pivot below ``1e3`` epsilons of the largest one: repeated correspondences measure+ at most about 1e-16 relative, regular samples above 1e-8 even with all five points in a patch 1e-4 wide.+ Collinear points rounded to float32 are no longer collinear, and are solved like any other sample. A rank-deficient+ sample is swapped for a constant full-rank design before the null space is taken, whose normalizations would+ otherwise divide by a vanishing norm, so that its gradient is zero.++ Note:+ MPS has no float64, so an MPS sample is solved on the host and its candidates are copied back; autograd+ follows both copies. Solved in float32 on the device instead, an exact sample could miss its true solution+ by more than 1e-3, and on an Apple M1 (torch 2.14) the host solve was also faster: 8 ms against 37 ms for 256+ samples, 45 ms against 75 ms for 2048, and about the same at 8192.++ Returns:+ Candidates ``(B, 10, 3, 3)`` of unit Frobenius norm in the design's dtype, NaN where the slot holds no+ real root, and the ``(B, 10)`` mask of the real ones.+ """+ if design.device.type == "mps":+ candidates, valid = _five_point_candidates(design.cpu())+ return candidates.to(design.device), valid.to(design.device)+ A = design.to(_solve_dtype(design.device))+ lu, _, info = torch.linalg.lu_factor_ex(A.detach().mT)+ pivots = lu.diagonal(dim1=-2, dim2=-1).abs()+ rank_deficient = (info > 0) | (pivots.amin(-1) <= 1e3 * torch.finfo(A.dtype).eps * pivots.amax(-1))+ A = torch.where(rank_deficient[:, None, None], torch.eye(5, 9, device=A.device, dtype=A.dtype), A)+ candidates, valid = _nister_candidates(_null_space_householder(A), design.dtype)+ valid = valid & ~rank_deficient[:, None]+ return torch.where(valid[..., None, None], candidates, torch.full_like(candidates, float("nan"))), valid+++# Monomial product tables of Nister's constraints: linear x linear -> quadratic (x^2, xy, xz, x, y^2, yz, y, z^2, z,+# 1), and quadratic x linear -> the twenty cubic monomials, in the order the elimination below expects.+_LINEAR_PRODUCTS = T_deg1.view(4, 4, 10)+_CUBIC_PRODUCTS = T_deg2.view(10, 4, 20)+++def _nister_candidates(basis: torch.Tensor, out_dtype: torch.dtype) -> Tuple[torch.Tensor, torch.Tensor]:+ """Essential matrices ``E = x X + y Y + z Z + W`` in the span of ``basis`` ``(B, 9, 4)`` (columns X, Y, Z, W).++ Nister's method: the cubic constraints ``det E = 0`` and ``2 E E^T E - tr(E E^T) E = 0`` as a ``(10, 20)``+ coefficient matrix, Gauss-Jordan elimination of its first ten monomials, a degree-ten polynomial in ``z`` from+ the determinant of the ``(3, 13)`` hidden-variable matrix, its real roots, and ``x``, ``y`` by+ back-substitution.++ The roots are the eigenvalues of the polynomial's companion matrix, from LAPACK on the host in float64 for every+ device: ``torch.linalg.eigvals`` has no batched CUDA kernel and none at all on MPS, and it is faster in+ float64 than in float32. They carry no gradient themselves: one Newton step on the differentiable polynomial+ polishes each root and supplies its derivative by the implicit function theorem, and is skipped at a multiple+ root, where the derivative does not exist.+ """+ B = basis.shape[0]+ device, dtype = basis.device, basis.dtype+ linear = _LINEAR_PRODUCTS.to(device, dtype)+ cubic = _CUBIC_PRODUCTS.to(device, dtype)+ N = basis.reshape(B, 3, 3, 4) # entries of E as linear forms in (x, y, z, 1)++ # ---- constraints ----+ # det E, expanded along the third row: its cofactors are the cross product of the first two.+ rows01 = torch.einsum("bja,bkc,acm->bjkm", N[:, 0], N[:, 1], linear)+ cofactors = torch.stack(+ [rows01[:, 1, 2] - rows01[:, 2, 1], rows01[:, 2, 0] - rows01[:, 0, 2], rows01[:, 0, 1] - rows01[:, 1, 0]], 1+ )+ determinant = torch.einsum("bjm,bjc,mcn->bn", cofactors, N[:, 2], cubic)+ # 2 E E^T E - tr(E E^T) E = 2 (E E^T - tr(E E^T) I / 2) E+ EEt = torch.einsum("bika,bjkc,acm->bijm", N, N, linear)+ half_trace = 0.5 * EEt.diagonal(dim1=1, dim2=2).sum(-1)+ EEt = EEt - torch.eye(3, device=device, dtype=dtype)[None, :, :, None] * half_trace[:, None, None, :]+ trace_constraints = torch.einsum("bikm,bkjc,mcn->bijn", EEt, N, cubic).reshape(B, 9, 20)+ coeffs = torch.cat([trace_constraints, determinant[:, None]], 1) # (B, 10, 20)++ # ---- elimination ----+ # An exactly singular elimination matrix means the sample has no solution. Its elements are factorized against+ # the identity instead, so that nothing below overflows or raises in the forward pass or gives a NaN gradient+ # in the backward, and all ten of their slots are NaN.+ A10, b10 = coeffs[..., :10], coeffs[..., 10:]+ lu, pivots, info = torch.linalg.lu_factor_ex(A10)+ singular = info > 0+ if bool(singular.any()):+ eye10 = torch.eye(10, device=device, dtype=dtype).expand(B, 10, 10)+ lu, pivots, _ = torch.linalg.lu_factor_ex(torch.where(singular[:, None, None], eye10, A10))+ eliminated = torch.linalg.lu_solve(lu, pivots, b10) # (B, 10, 10)++ # ---- hidden-variable matrix (B, 3, 13) and its determinant, a polynomial of degree ten in z ----+ top, bottom = eliminated[:, [4, 6, 8]], eliminated[:, [5, 7, 9]]+ A = torch.zeros(B, 3, 13, device=device, dtype=dtype)+ A[:, :, 1:4] = top[..., 0:3]+ A[:, :, 0:3] = A[:, :, 0:3] - bottom[..., 0:3]+ A[:, :, 5:8] = top[..., 3:6]+ A[:, :, 4:7] = A[:, :, 4:7] - bottom[..., 3:6]+ A[:, :, 9:13] = top[..., 6:10]+ A[:, :, 8:12] = A[:, :, 8:12] - bottom[..., 6:10]+ cs = _determinant_to_polynomial_jit(A) # (B, 11), z^0 first++ # ---- real roots ----+ # A polynomial that is not finite, or whose leading coefficient is exactly zero (its degree is below ten, #4831),+ # has no usable companion matrix: its sample gets the identity instead and NaN slots.+ lead = cs[:, -1]+ usable = ~singular & torch.isfinite(cs).all(1) & (lead != 0)+ detached = cs.detach().cpu().double()+ companion = torch.zeros(B, 10, 10, dtype=torch.float64)+ companion[:, :9, 1:] = torch.eye(9, dtype=torch.float64)+ companion[:, 9] = -detached[:, :10] / torch.where(detached[:, 10:] == 0, 1.0, detached[:, 10:])+ host_usable = usable.cpu() & torch.isfinite(companion).flatten(1).all(1)+ companion = torch.where(host_usable[:, None, None], companion, torch.eye(10, dtype=torch.float64))+ eigenvalues = torch.linalg.eigvals(companion)+ real = eigenvalues.imag.abs() <= 1e-10 * eigenvalues.abs().clamp(min=1.0)+ # A root beyond the fifth root of the dtype's largest number could overflow the z^4 terms of the back-substitution,+ # and a masked infinity still turns the backward into 0 * inf = NaN: its slot is dropped, and a zero stands in for+ # it. That only binds for a float32 solve, at |z| > 5.5e7, where the basis matrix W no longer shows in E.+ in_range = eigenvalues.real.abs() < torch.finfo(dtype).max ** 0.2+ valid = (real & in_range & host_usable[:, None]).to(device)+ root0 = torch.where(real & in_range, eigenvalues.real, 0.0).to(device, dtype)++ # ---- Newton step: the root's polish and its gradient ----+ # The polynomial and its slope are evaluated divided by s^10 with s = max(1, |z|): the same step, without the+ # overflow of z^10 for large roots in float32.+ degrees = torch.arange(11, device=device, dtype=dtype)+ scale = root0.abs().clamp(min=1.0)[..., None] # root0 carries no gradient+ powers = (root0[..., None] / scale) ** degrees * scale ** (degrees - 10) # (B, 10, 11)+ value = (powers * cs[:, None]).sum(-1)+ slope_terms = powers[..., :10] * (degrees[1:] * cs[:, 1:])[:, None]+ slope = slope_terms.sum(-1)+ # At a multiple root rounding leaves a tiny slope: dividing two rounding errors would move an accurate root.+ simple = valid & (slope.abs() > 8 * torch.finfo(dtype).eps * slope_terms.abs().sum(-1))+ simple = simple & torch.isfinite(value) & torch.isfinite(slope)+ step = value / torch.where(simple, slope, torch.ones_like(slope))+ z = root0 - torch.where(simple, step, torch.zeros_like(step))++ # ---- back-substitution for x and y ----+ zz = z[:, None] # (B, 1, 10)Bs = torch.stack((- A[:, :3, :1] * (roots_unsqu**3)- + A[:, :3, 1:2] * roots_unsqu.square()- + A[:, :3, 2:3] * roots_unsqu- + A[:, :3, 3:4],- A[:, :3, 4:5] * (roots_unsqu**3)- + A[:, :3, 5:6] * roots_unsqu.square()- + A[:, :3, 6:7] * roots_unsqu- + A[:, :3, 7:8],+ A[:, :3, :1] * zz**3 + A[:, :3, 1:2] * zz.square() + A[:, :3, 2:3] * zz + A[:, :3, 3:4],+ A[:, :3, 4:5] * zz**3 + A[:, :3, 5:6] * zz.square() + A[:, :3, 6:7] * zz + A[:, :3, 7:8],),dim=1,- ).transpose(1, -1) # (B,10,3,2)-- bs_vec = (- (- A[:, :3, 8:9] * (roots_unsqu**4)- + A[:, :3, 9:10] * (roots_unsqu**3)- + A[:, :3, 10:11] * roots_unsqu.square()- + A[:, :3, 11:12] * roots_unsqu- + A[:, :3, 12:13]- )- .transpose(1, 2)- .unsqueeze(-1)- ) # (B,10,3,1)-- A2 = Bs[:, :, 0:2, 0:2] # (B,10,2,2)- b2 = bs_vec[:, :, 0:2, :] # (B,10,2,1)-- xzs, bad2 = _solve_2x2_tikhonov_safe(A2, b2, 1e-12) # never throws-- # ---- build Es ----- xzs_sq = xzs.squeeze(-1) # (B,10,2)- x = -xzs_sq[:, :, 0]- y = -xzs_sq[:, :, 1]- z = roots-- N0 = nullSpace[:, 0, :].unsqueeze(1) # (B,1,9)- N1 = nullSpace[:, 1, :].unsqueeze(1)- N2 = nullSpace[:, 2, :].unsqueeze(1)- N3 = nullSpace[:, 3, :].unsqueeze(1)-- Es_vec = x.unsqueeze(-1) * N0 + y.unsqueeze(-1) * N1 + z.unsqueeze(-1) * N2 + N3 # (B,10,9)- inv_norm = torch.rsqrt(x * x + y * y + z * z + 1.0)- Es_vec = Es_vec * inv_norm.unsqueeze(-1)-- Es = Es_vec.view(B, 10, 3, 3).transpose(-1, -2)- # after Es is created (B,10,3,3)- if bad2.any():- Es[bad2] = torch.nan- # a singular elimination matrix has no candidates, and neither has a non-finite companion matrix- if singular.any():- Es[singular] = torch.nan- if no_roots.any():- Es[no_roots] = torch.nan- # mark complex roots as NaN (keeps shape, no compaction)- if is_real.logical_not().any():- Es[~is_real] = torch.nan-- return Es.to(dtype=original_dtype)---# Indices for null_ij reshaping-IDX_IJ = torch.tensor([[0, 3, 6], [1, 4, 7], [2, 5, 8]], dtype=torch.long)-I_IDX = torch.tensor([0, 0, 0, 1, 1, 1, 2, 2, 2], dtype=torch.long)-J_IDX = torch.tensor([0, 1, 2, 0, 1, 2, 0, 1, 2], dtype=torch.long)-IDX3 = torch.tensor([0, 1, 2], dtype=torch.long)--TOP_IDX = torch.tensor([4, 6, 8], dtype=torch.long)-BOT_IDX = torch.tensor([5, 7, 9], dtype=torch.long)+ ).transpose(1, -1) # (B, 10, 3, 2)+ bs = (+ (A[:, :3, 8:9] * zz**4 + A[:, :3, 9:10] * zz**3 + A[:, :3, 10:11] * zz.square() + A[:, :3, 11:12] * zz)+ + A[:, :3, 12:13]+ ).transpose(1, 2)[..., None] # (B, 10, 3, 1)+ # Each 2x2 system is divided by its largest entry, which leaves its solution unchanged: entries of size A z^3 would+ # otherwise overflow the squares of the regularized fallback in float32, and a masked infinity still gives a NaN+ # gradient. The scale is detached; the solution does not depend on it.+ system = torch.cat([Bs[:, :, :2, :2].flatten(2), bs[:, :, :2, 0]], -1)+ system_scale = system.detach().abs().amax(-1).clamp(min=torch.finfo(dtype).tiny)[..., None, None]+ xy, bad2 = _solve_2x2_tikhonov_safe(Bs[:, :, :2, :2] / system_scale, bs[:, :, :2] / system_scale, 1e-12)+ coefficients = torch.stack([-xy[..., 0, 0], -xy[..., 1, 0], z, torch.ones_like(z)], -1) # (B, 10, 4)+ Es = torch.einsum("bijk,brk->brij", N, coefficients)+ norm = Es.flatten(2).norm(dim=-1)[..., None, None]+ Es = Es / torch.where(norm > 0, norm, torch.ones_like(norm))+ valid = valid & ~bad2 & torch.isfinite(Es).flatten(2).all(-1)+ Es = torch.where(valid[..., None, None], Es, torch.full_like(Es, float("nan")))+ return Es.to(out_dtype), validdef fun_select(null_mat: torch.Tensor, i: int, j: int, ratio: int = 3) -> torch.Tensor:return null_mat[:, ratio * j + i]+# vec(x1 x2^T) -> vec(x2 x1^T): the column order of the historical design rows in terms of _epipolar_design_rows'.+_TRANSPOSED_ROWS = [0, 3, 6, 1, 4, 7, 2, 5, 8]++def null_to_Nister_solution(X: torch.Tensor, batch_size: int) -> torch.Tensor:- device = X.device- dtype_internal = X.dtype-- T1 = T_deg1.to(device=device, dtype=dtype_internal)- T2 = T_deg2.to(device=device, dtype=dtype_internal)- mult_idx = multiplication_indices.to(device=device)- sgns = signs.to(device=device, dtype=dtype_internal)- coeff_map = coefficient_map.to(device=device)- i_idx_dev = I_IDX.to(device=device)- j_idx_dev = J_IDX.to(device=device)- idx3_dev = IDX3.to(device=device)- top_idx_dev = TOP_IDX.to(device=device)- bot_idx_dev = BOT_IDX.to(device=device)- idx_ij_dev = IDX_IJ.to(device=device)-- return _null_to_Nister_solution_script(- X,- batch_size,- T1,- T2,- mult_idx,- sgns,- coeff_map,- idx_ij_dev,- i_idx_dev,- j_idx_dev,- idx3_dev,- top_idx_dev,- bot_idx_dev,- )+ """Candidates ``(B, 10, 3, 3)`` of design rows ``X`` ``(B, N, 9)`` in the column order ``vec(x1 x2^T)``."""+ design = X[..., _TRANSPOSED_ROWS]+ if design.shape[1] == 5:+ return _five_point_candidates(design)[0]+ return _least_squares_candidates(design)def essential_from_fundamental(F_mat: torch.Tensor, K1: torch.Tensor, K2: torch.Tensor) -> torch.Tensor:@@ -915,11 +838,12 @@ def find_essential(in them. :ref:`Two-view geometry <two-view-conventions>` maps this onto OpenCV.- All ten slots are always returned: each real root gives a candidate of unit Frobenius norm, and eachcomplex root a ``NaN`` slot, so a sample with no real solution returns ten ``NaN`` slots.- - Known defects: ``weights`` is ignored (`#4876 <https://github.com/kornia/kornia/issues/4876>`_); in- ``float32`` an exact five-point sample can miss the true solution, which six or more correspondences recover- (`#4884 <https://github.com/kornia/kornia/issues/4884>`_); backward can raise on a degenerate sample whose- polynomial has a multiple root at zero (`#4903 <https://github.com/kornia/kornia/issues/4903>`_);- on MPS the 5-point solve needs the CPU fallback (`#4528 <https://github.com/kornia/kornia/issues/4528>`_).+ - The solve runs in float64 whatever the input dtype, and the degree-ten polynomial's roots come from LAPACK+ on the host for every device. MPS has no float64, so MPS inputs are solved on the host and the candidates+ copied back, which on an Apple M1 was also faster than a float32 solve on the device. A sample whose five+ design rows are rank deficient, such as one with a repeated correspondence, has no unique solution: ten+ ``NaN`` slots and a zero gradient.+ - Known defects: ``weights`` is ignored (`#4876 <https://github.com/kornia/kornia/issues/4876>`_).Args:points1: A set of points in the first image with a tensor shape :math:`(B, N, 2), N>=5`.@@ -933,3 +857,67 @@ def find_essential("""return run_5point(points1, points2, weights).to(points1.dtype)+++def _refine_essential_lm(+ E: 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 essential matrices ``(K, 3, 3)``.++ ``E = U diag(1, 1, 0) V^T / sqrt(2)`` with ``U`` and ``V`` in SO(3): the factorization of+ :func:`~kornia.geometry.epipolar.fundamental._refine_fundamental_lm` with its singular-value ratio fixed to one.+ Five parameters, as many as the rotation and translation direction of PoseLib's ``refine_relpose``: Cayley+ rotations of ``U`` about the three axes and of ``V`` about ``V e_1`` and ``V e_2``. Rotating both about their third+ axes by the same angle leaves ``E`` unchanged, so that direction is left out and the normal equations stay regular.+ Residuals, losses, masks and step acceptance as for the fundamental matrix; ``x1`` and ``x2`` are homogeneous+ ``(N, 3)`` calibrated points. Returns matrices of unit Frobenius norm. For RANSAC, under ``torch.no_grad``.+ """+ K = E.shape[0]+ dtype, device = E.dtype, E.device+ H = _hat_basis(dtype, device)+ eye3 = torch.eye(3, dtype=dtype, device=device)+ eye5 = torch.eye(5, 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, _, Vh = torch.linalg.svd(E)+ V = Vh.mT+ # Proper rotations: the third singular vectors do not enter E, 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)+ damping = torch.full((K, 1, 1), 1e-3, dtype=dtype, device=device)++ def compose(U: torch.Tensor, V: torch.Tensor) -> torch.Tensor:+ return (U[..., :2] @ V[..., :2].mT) * 0.5**0.5++ def normal_equations(E: torch.Tensor, V: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:+ # Directions dE/dp: H_a E (rotations of U), -E [V e_k]_x (rotations of V about its first two axes).+ axes = (V[..., :2].mT.reshape(K * 2, 3) @ H.reshape(3, 9)).reshape(K, 2, 3, 3)+ tangent = torch.cat([H @ E[:, None], (E[:, None] @ axes).neg()], 1)+ return _sampson_normal_equations(E, tangent, algebraic, quadratic, mask, loss, scale2)++ def cayley(half: torch.Tensor) -> torch.Tensor:+ # The rotation by the vector 2 * half: Cayley transform of the half-angle skew matrix.+ skew = (half @ H.reshape(3, 9)).reshape(-1, 3, 3)+ factor = (2.0 / (1.0 + half.square().sum(1)))[:, None, None]+ return eye3 + factor * (skew + skew @ skew)++ E = compose(U, V)+ system, cost = normal_equations(E, V)+ for _ in range(iters):+ delta = -torch.linalg.solve_ex(system[..., :5] + damping * eye5, system[..., 5:])[0][..., 0]+ U_new = cayley(0.5 * delta[:, :3]) @ U+ V_new = cayley(0.5 * (V[..., :2] @ delta[:, 3:, None])[..., 0]) @ V+ E_new = compose(U_new, V_new)+ system_new, cost_new = normal_equations(E_new, V_new)+ accept = (cost_new < cost)[:, None, None]+ U, V = torch.where(accept, U_new, U), torch.where(accept, V_new, V)+ E, system = torch.where(accept, E_new, E), torch.where(accept, system_new, system)+ cost = torch.where(accept[:, 0, 0], cost_new, cost)+ damping = damping * torch.where(accept, 0.1, 10.0)+ return Ediff --git a/kornia/geometry/epipolar/fundamental.py b/kornia/geometry/epipolar/fundamental.pyindex f91c147e9..ccd5b1989 100644--- a/kornia/geometry/epipolar/fundamental.py+++ b/kornia/geometry/epipolar/fundamental.py@@ -328,6 +328,38 @@ def _hat_basis(dtype: torch.dtype, device: torch.device) -> torch.Tensor:return E+def _sampson_normal_equations(+ F: torch.Tensor,+ tangent: torch.Tensor,+ algebraic: torch.Tensor,+ quadratic: torch.Tensor,+ mask: Optional[torch.Tensor],+ loss: str,+ scale2: float,+) -> Tuple[torch.Tensor, torch.Tensor]:+ """Robust Gauss-Newton normal equations ``[J^T W J | J^T W r]`` ``(K, P, P + 1)`` and costs ``(K,)``.++ For the Sampson residuals of ``F`` ``(K, 3, 3)``, whose derivatives along ``P`` parameters are ``tangent``+ ``(K, P, 3, 3)``. ``algebraic`` ``(9, N)`` and ``quadratic`` ``(18, N)`` are the per-correspondence monomials of+ the epipolar constraint and of the squared gradient norm, from :func:`_epipolar_design_rows`.+ """+ K, P = tangent.shape[:2]+ stacked = torch.cat([F[:, None], tangent], 1) # (K, P + 1, 3, 3): F, then the P 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, P + 1, 9) @ algebraic+ out_g = torch.cat([quad1, quad2], 2).reshape(K, P + 1, 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, P, 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)++def _refine_fundamental_lm(F: torch.Tensor,x1: torch.Tensor,@@ -372,20 +404,7 @@ def _refine_fundamental_lm(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)+ return _sampson_normal_equations(F, tangent, algebraic, quadratic, mask, loss, scale2)F = compose(UV, sigma)system, cost = normal_equations(F, UV)diff --git a/kornia/geometry/ransac.py b/kornia/geometry/ransac.pyindex 92e48b50d..922e5cf83 100644--- a/kornia/geometry/ransac.py+++ b/kornia/geometry/ransac.py@@ -31,6 +31,7 @@ from kornia.core.check import KORNIA_CHECK_SHAPEfrom kornia.geometry.conversions import convert_points_to_homogeneousfrom kornia.geometry.epipolar import find_essential, find_fundamental, project_to_essential, sampson_epipolar_distancefrom kornia.geometry.epipolar._metrics import _sampson_from_quadratic_basis, _sampson_quadratic_basis+from kornia.geometry.epipolar.essential import _five_point_candidates, _refine_essential_lmfrom kornia.geometry.epipolar.fundamental import (_eight_point_fundamental,_epipolar_design_rows,@@ -59,7 +60,7 @@ __all__ = ["RANSAC"]_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_MODELS = ("homography", "fundamental", "fundamental_7pt", "fundamental_8pt", "essential")_LM_CANDIDATES = 8@@ -125,19 +126,22 @@ class RANSAC(nn.Module)::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="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+ - ``local_optimization="lm"``, the default for homographies, fundamental and essential 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 truncatedat ``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 inliersof 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.+ small operations per iteration, which launch latency makes slower on an accelerator. Homographies and+ fundamental matrices are estimated on Hartley-normalized correspondences; essential matrices in the+ caller's calibrated coordinates, which a normalization would take off the essential manifold, refined on+ that manifold and returned with unit Frobenius norm.+ - ``local_optimization="dlt"``, the only choice for ``"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``@@ -168,8 +172,8 @@ class RANSAC(nn.Module):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.+ local_optimization: ``"lm"`` or ``"dlt"``, as described above; None picks ``"lm"`` for homographies,+ fundamental and essential matrices and ``"dlt"`` for line segments.refine_iters: Levenberg-Marquardt iterations of the final refinement with ``local_optimization="lm"``;zero disables it.@@ -215,7 +219,7 @@ class RANSAC(nn.Module):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 afinal robust refinement) or ``"dlt"`` (refits of each new best model); None picks ``"lm"`` where it- is supported, for homographies and fundamental matrices.+ is supported, for homographies, fundamental and essential matrices.refine_iters: Levenberg-Marquardt iterations of the final refinement on the inliers with ``"lm"``."""@@ -418,10 +422,13 @@ class RANSAC(nn.Module):With ``local_optimization="lm"`` an ``"auto"`` batch instead starts at 256 samples on CPU (512 forhomographies) and doubles after every batch, up to 2048 (4096 for homographies), so that inputs withmany 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.+ On CUDA and MPS it is the whole budget up to 8192 samples. Essential matrices start at 64 samples on CPU,+ up to 1024, and at 256 on CUDA and MPS, up to 8192: a five-point sample needs few draws at high inlier+ ratios, and its host eigenvalue solve costs the same on every device. All shrink, down to 64 samples, when a+ batch would score more than ``2**22`` (CPU) or ``2**25`` (accelerators) residuals, counting the three models+ of a seven-point sample and the ten candidate slots of a five-point one; 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@@ -440,12 +447,18 @@ class RANSAC(nn.Module):budget = self.sample_budgetif 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+ # Candidate slots per sample: the cubic's three roots, the degree-ten polynomial's ten for "essential".+ models = {7: 3, 5: 10}.get(self.minimal_sample_size, 1)planar = self.model_type == "homography"+ # A five-point sample needs few draws at high inlier ratios, and the host eigenvalue solve costs about 7 us+ # per sample on every device: essential matrices start small everywhere (tuned on PhotoTourism).+ essential = self.model_type == "essential"if device.type == "cpu":- first, upper, work = (512, 4096, 1 << 22) if planar else (256, 2048, 1 << 22)+ first, upper, work = (+ (512, 4096, 1 << 22) if planar else (64, 1024, 1 << 22) if essential else (256, 2048, 1 << 22)+ )elif device.type in ("cuda", "mps"):- first, upper, work = 8192, 8192, 1 << 25+ first, upper, work = (256 if essential else 8192), 8192, 1 << 25else:first, upper, work = _DEFAULT_BATCH, _DEFAULT_BATCH, 1 << 25largest = max(min(upper, work // (models * max(num_tc, 1))), 64)@@ -876,7 +889,7 @@ class RANSAC(nn.Module):return best_model_total, inliers_best_totaldef _lm_minimal_models(self, x1: torch.Tensor, x2: torch.Tensor) -> torch.Tensor:- """Minimal models ``(M, 3, 3)`` of normalized homogeneous samples ``(B, m, 3)``.+ """Minimal models ``(M, 3, 3)`` of normalized (for essential matrices, calibrated) samples ``(B, m, 3)``.Samples that :func:`~kornia.geometry.homography.sample_is_valid_for_homography` rejects and absent roots ofthe seven-point cubic are dropped on CPU; on other devices, where dropping would need a synchronization, they@@ -894,6 +907,10 @@ class RANSAC(nn.Module):models = _four_point_homography(x1, x2)return models.masked_fill(~oriented[:, None, None], float("nan"))design = _epipolar_design_rows(x1, x2)+ if self.model_type == "essential":+ # Samples with a non-finite correspondence, rank-deficient samples and complex roots give NaN slots.+ candidates, valid = _five_point_candidates(design)+ return candidates[valid] if compact else candidates.flatten(0, 1)if self.minimal_sample_size == 7:candidates, valid = _seven_point_candidates(design)models = candidates.masked_fill(~valid[..., None, None], float("nan")).flatten(0, 1)@@ -902,7 +919,7 @@ class RANSAC(nn.Module):return models[torch.isfinite(models).flatten(1).all(1)] if compact else modelsdef _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."""+ """Squared residuals ``(M, N)`` of normalized models on normalized correspondences (calibrated: essential)."""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))@@ -924,9 +941,11 @@ class RANSAC(nn.Module):scale2: float,iters: int,) -> torch.Tensor:- """Refine normalized models with Levenberg-Marquardt; all inputs are float64 host tensors."""+ """Refine normalized (calibrated: essential) models with Levenberg-Marquardt, on float64 host tensors."""if self.model_type == "homography":return _refine_homography_lm(models, x1, x2[:, :2], mask, loss, scale2, iters)+ if self.model_type == "essential":+ return _refine_essential_lm(models, x1, x2, 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]:@@ -938,21 +957,34 @@ class RANSAC(nn.Module):needs: correspondences are normalized once per call rather than per sample, models stay in that normalizedframe at unit Frobenius norm instead of ``F[2, 2] = 1``, absent candidates are NaN on accelerators rather thandropped, and scoring uses the quadratic Sampson and folded transfer bases, which are fast and accurate in that- frame only.+ frame only. Essential matrices skip the normalization: calibrated coordinates are already of unit scale, and+ a translation or scaling of them would take the models off the essential manifold."""device, dtype = kp1.device, kp1.dtypework = torch.float64 if dtype == torch.float64 else torch.float32num_tc, m = len(kp1), self.minimal_sample_sizeplanar = self.model_type == "homography"+ essential = self.model_type == "essential"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)+ # Moved first, then cast: a single .to(host, torch.float64) out of MPS returns zeros on torch 2.14 and+ # raises on 2.5.1 (pytorch/pytorch#197715).+ kp1_host, kp2_host = kp1.detach().to(host).double(), kp2.detach().to(host).double()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+ if essential:+ # Non-finite correspondences stay NaN, as the normalization leaves them, and are never inliers.+ x1_host, x2_host = (+ convert_points_to_homogeneous(kp.masked_fill(~finite[:, None], float("nan")))+ for kp in (kp1_host, kp2_host)+ )+ t1 = t2 = torch.eye(3, dtype=torch.float64)+ threshold = self.inl_th**2+ else:+ 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)) ** 2x1, 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@@ -994,7 +1026,7 @@ class RANSAC(nn.Module):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]+ candidates = candidates.to(host).double()[candidate_scores.to(host) >= 0]if len(candidates) == 0:return failureif self.max_lo_iters > 0:@@ -1015,8 +1047,15 @@ class RANSAC(nn.Module):refined_inliers = self._lm_errors(refined, x1_host, x2_host)[0] <= thresholdif 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 essential:+ # A minimal model is essential only up to rounding when neither refinement ran: project it.+ model = project_to_essential(model)+ model = (model / model.norm()).to(dtype)+ # E and -E are the same model; a fixed sign makes equal inputs give equal outputs.+ model = model * model.flatten()[model.abs().argmax()].sign()+ else:+ 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 pixeldiff --git a/kornia/geometry/solvers/homogeneous.py b/kornia/geometry/solvers/homogeneous.pyindex 5a3ba3afb..23ff3c339 100644--- a/kornia/geometry/solvers/homogeneous.py+++ b/kornia/geometry/solvers/homogeneous.py@@ -189,3 +189,34 @@ def _null_space_lu(A: torch.Tensor) -> torch.Tensor: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)+++def _null_space_householder(A: torch.Tensor) -> torch.Tensor:+ r"""Orthonormal right null spaces of a batch of ``(B, m, n)`` matrices, ``m < n``, as ``(B, n, n - m)``.++ The last ``n - m`` columns of ``Q`` in the QR factorization ``A^T = Q R``, from ``m`` Householder reflections+ written as batched tensor operations: ``torch.linalg.qr`` has no batched CUDA kernel and loops over the batch.+ Both this and :func:`_null_space_lu` span the null space to rounding, but a solver that parametrizes its solution+ in the basis can depend on which basis it gets: on 22000 exact five-point samples, Nister's candidates missed the+ true essential matrix by more than 1e-3 nine times with this orthonormal basis, seven times with the SVD's, and 81+ times with the LU one. It costs about four times the LU null space. ``A`` must have full rank: at a vanishing+ reflector the normalization divides by zero.+ """+ batch, m, n = A.shape+ remaining = A.mT # (B, n, m): the columns still to be reduced, below the rows already done+ reflectors = []+ for _ in range(m):+ x = remaining[:, :, 0]+ head = x[:, :1]+ # The sign that avoids cancellation in the first entry of the reflector.+ sign = torch.where(head >= 0, torch.ones_like(head), -torch.ones_like(head))+ v = torch.cat([head + sign * x.norm(dim=1, keepdim=True), x[:, 1:]], 1)+ v = v / v.norm(dim=1, keepdim=True)+ reflectors.append(v)+ remaining = (remaining - 2 * v[:, :, None] * (v[:, None, :] @ remaining))[:, 1:, 1:]+ # Q e_j for j >= m, with Q = H_0 H_1 ... H_{m-1}: the reflectors in reverse order, H_k acting on rows k and below.+ Q = torch.eye(n, dtype=A.dtype, device=A.device)[:, m:].expand(batch, n, n - m)+ for k in reversed(range(m)):+ v, tail = reflectors[k], Q[:, k:]+ Q = torch.cat([Q[:, :k], tail - 2 * v[:, :, None] * (v[:, None, :] @ tail)], 1)+ return Qdiff --git a/testing/half_precision_xfails/cpu_bfloat16.txt b/testing/half_precision_xfails/cpu_bfloat16.txtindex 18f42e2c4..8462c622b 100644--- a/testing/half_precision_xfails/cpu_bfloat16.txt+++ b/testing/half_precision_xfails/cpu_bfloat16.txt@@ -123,18 +123,7 @@ call builtins.NotImplementedError tests/geometry/epipolar/test_essential.py::Tescall builtins.NotImplementedError tests/geometry/epipolar/test_essential.py::TestDecomposeEssentialMatrix::test_shape[cpu-bfloat16-batch_shape2]call builtins.NotImplementedError tests/geometry/epipolar/test_essential.py::TestDecomposeEssentialMatrix::test_shape[cpu-bfloat16-batch_shape3]call builtins.NotImplementedError tests/geometry/epipolar/test_essential.py::TestDecomposeEssentialMatrix::test_smoke[cpu-bfloat16]-call builtins.NotImplementedError tests/geometry/epipolar/test_essential.py::TestFindEssential::test_degenerate_case[cpu-bfloat16-10-5]-call builtins.NotImplementedError tests/geometry/epipolar/test_essential.py::TestFindEssential::test_degenerate_case[cpu-bfloat16-5-5]-call builtins.NotImplementedError tests/geometry/epipolar/test_essential.py::TestFindEssential::test_epipolar_constraint[cpu-bfloat16]-call builtins.NotImplementedError tests/geometry/epipolar/test_essential.py::TestFindEssential::test_shape[cpu-bfloat16-1-5]-call builtins.NotImplementedError tests/geometry/epipolar/test_essential.py::TestFindEssential::test_shape[cpu-bfloat16-16-5]-call builtins.NotImplementedError tests/geometry/epipolar/test_essential.py::TestFindEssential::test_shape[cpu-bfloat16-2-6]-call builtins.NotImplementedError tests/geometry/epipolar/test_essential.py::TestFindEssential::test_shape[cpu-bfloat16-3-7]-call builtins.NotImplementedError tests/geometry/epipolar/test_essential.py::TestFindEssential::test_shape_noweights[cpu-bfloat16-1-5]-call builtins.NotImplementedError tests/geometry/epipolar/test_essential.py::TestFindEssential::test_shape_noweights[cpu-bfloat16-2-6]-call builtins.NotImplementedError tests/geometry/epipolar/test_essential.py::TestFindEssential::test_shape_noweights[cpu-bfloat16-3-7]-call builtins.NotImplementedError tests/geometry/epipolar/test_essential.py::TestFindEssential::test_smoke[cpu-bfloat16]-call builtins.NotImplementedError tests/geometry/epipolar/test_essential.py::TestFindEssential::test_synthetic_sampson[cpu-bfloat16]+call builtins.AssertionError tests/geometry/epipolar/test_essential.py::TestFindEssential::test_synthetic_sampson[cpu-bfloat16]call builtins.NotImplementedError tests/geometry/epipolar/test_essential.py::TestMotionFromEssential::test_shape[cpu-bfloat16-batch_shape0]call builtins.NotImplementedError tests/geometry/epipolar/test_essential.py::TestMotionFromEssential::test_shape[cpu-bfloat16-batch_shape1]call builtins.NotImplementedError tests/geometry/epipolar/test_essential.py::TestMotionFromEssential::test_shape[cpu-bfloat16-batch_shape2]@@ -372,7 +361,6 @@ call builtins.AssertionError tests/geometry/test_quaternion.py::TestQuaternion::call builtins.AssertionError tests/geometry/test_quaternion.py::TestQuaternionAverage::test_single_quaternion_returns_itself[cpu-bfloat16]call 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.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 5719b42e7..822ba9a0a 100644--- a/testing/half_precision_xfails/cpu_float16.txt+++ b/testing/half_precision_xfails/cpu_float16.txt@@ -227,18 +227,7 @@ call builtins.NotImplementedError tests/geometry/epipolar/test_essential.py::Tescall builtins.NotImplementedError tests/geometry/epipolar/test_essential.py::TestDecomposeEssentialMatrix::test_shape[cpu-float16-batch_shape3]call builtins.NotImplementedError tests/geometry/epipolar/test_essential.py::TestDecomposeEssentialMatrix::test_smoke[cpu-float16]call builtins.AssertionError tests/geometry/epipolar/test_essential.py::TestEssentialFromFundamental::test_from_fundamental[cpu-float16]-call builtins.NotImplementedError tests/geometry/epipolar/test_essential.py::TestFindEssential::test_degenerate_case[cpu-float16-10-5]-call builtins.NotImplementedError tests/geometry/epipolar/test_essential.py::TestFindEssential::test_degenerate_case[cpu-float16-5-5]-call builtins.NotImplementedError tests/geometry/epipolar/test_essential.py::TestFindEssential::test_epipolar_constraint[cpu-float16]-call builtins.NotImplementedError tests/geometry/epipolar/test_essential.py::TestFindEssential::test_shape[cpu-float16-1-5]-call builtins.NotImplementedError tests/geometry/epipolar/test_essential.py::TestFindEssential::test_shape[cpu-float16-16-5]-call builtins.NotImplementedError tests/geometry/epipolar/test_essential.py::TestFindEssential::test_shape[cpu-float16-2-6]-call builtins.NotImplementedError tests/geometry/epipolar/test_essential.py::TestFindEssential::test_shape[cpu-float16-3-7]-call builtins.NotImplementedError tests/geometry/epipolar/test_essential.py::TestFindEssential::test_shape_noweights[cpu-float16-1-5]-call builtins.NotImplementedError tests/geometry/epipolar/test_essential.py::TestFindEssential::test_shape_noweights[cpu-float16-2-6]-call builtins.NotImplementedError tests/geometry/epipolar/test_essential.py::TestFindEssential::test_shape_noweights[cpu-float16-3-7]-call builtins.NotImplementedError tests/geometry/epipolar/test_essential.py::TestFindEssential::test_smoke[cpu-float16]-call builtins.NotImplementedError tests/geometry/epipolar/test_essential.py::TestFindEssential::test_synthetic_sampson[cpu-float16]+call builtins.AssertionError tests/geometry/epipolar/test_essential.py::TestFindEssential::test_synthetic_sampson[cpu-float16]call builtins.NotImplementedError tests/geometry/epipolar/test_essential.py::TestMotionFromEssential::test_shape[cpu-float16-batch_shape0]call builtins.NotImplementedError tests/geometry/epipolar/test_essential.py::TestMotionFromEssential::test_shape[cpu-float16-batch_shape1]call builtins.NotImplementedError tests/geometry/epipolar/test_essential.py::TestMotionFromEssential::test_shape[cpu-float16-batch_shape2]@@ -377,7 +366,6 @@ call builtins.AssertionError tests/geometry/test_quaternion.py::TestQuaternion::call builtins.AssertionError tests/geometry/test_quaternion.py::TestQuaternion::test_to_axis_angle[cpu-float16-None]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.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/testing/known_failure_xfails/mps_float32.txt b/testing/known_failure_xfails/mps_float32.txtindex d346e142d..fdfd5a821 100644--- a/testing/known_failure_xfails/mps_float32.txt+++ b/testing/known_failure_xfails/mps_float32.txt@@ -1,27 +1,15 @@# Exact strict baseline verified by# https://github.com/kornia/kornia/actions/runs/33920557535/job/101177935411 -- the post-#4185# full-suite replay completed with --xfail-known-failures: 8327 passed, 4126 skipped, 95 deselected,-# 43 xfailed, 9 xpassed in 425.15s. The 12 entries below are the strict MPS manifest.+# 43 xfailed, 9 xpassed in 425.15s. It recorded 12 entries; #5078 fixed them all, so the manifest is empty.# macos-15-arm64, Python 3.13.11, PyTorch 2.14.0, MPS float32, no CPU fallback,# one pytest process for the full suite (tests marked device_agnostic are deselected on an mps-only run).# Remove an entry when it becomes a strict XPASS; fix or explicitly add any new failure. Tracked in #4159.# torch 2.14.0 added MPS kernels for the eigen/QR/LU/SVD family and for both grid_sample backward# passes, which took the baseline from 200 entries to 14. #4185 then fixed the two YUV420/YUV422-# empty-input failures, leaving 12 entries. One cause remains:-# NotImplementedError aten::_linalg_eigvals has no MPS kernel (the 5-point essential solver).+# empty-input failures, leaving 12 entries, all from aten::_linalg_eigvals, which has no MPS kernel: the+# 5-point essential solver called it on the input's device. #5078 takes those roots on the host.# tests/geometry/test_ransac.py is skipped on MPS, not pinned: it aborts the process (#4204).# Keep the entries sorted by node ID: KnownFailureTracker prints its regeneration output sorted,# so an unsorted file turns the next re-record into a whole-file diff.# Format: <exact exception type>\t<pytest node ID>-NotImplementedError tests/geometry/epipolar/test_essential.py::TestFindEssential::test_degenerate_case[mps-float32-10-5]-NotImplementedError tests/geometry/epipolar/test_essential.py::TestFindEssential::test_degenerate_case[mps-float32-5-5]-NotImplementedError tests/geometry/epipolar/test_essential.py::TestFindEssential::test_epipolar_constraint[mps-float32]-NotImplementedError tests/geometry/epipolar/test_essential.py::TestFindEssential::test_shape[mps-float32-1-5]-NotImplementedError tests/geometry/epipolar/test_essential.py::TestFindEssential::test_shape[mps-float32-16-5]-NotImplementedError tests/geometry/epipolar/test_essential.py::TestFindEssential::test_shape[mps-float32-2-6]-NotImplementedError tests/geometry/epipolar/test_essential.py::TestFindEssential::test_shape[mps-float32-3-7]-NotImplementedError tests/geometry/epipolar/test_essential.py::TestFindEssential::test_shape_noweights[mps-float32-1-5]-NotImplementedError tests/geometry/epipolar/test_essential.py::TestFindEssential::test_shape_noweights[mps-float32-2-6]-NotImplementedError tests/geometry/epipolar/test_essential.py::TestFindEssential::test_shape_noweights[mps-float32-3-7]-NotImplementedError tests/geometry/epipolar/test_essential.py::TestFindEssential::test_smoke[mps-float32]-NotImplementedError tests/geometry/epipolar/test_essential.py::TestFindEssential::test_synthetic_sampson[mps-float32]diff --git a/testing/two_view.py b/testing/two_view.pyindex ff1c9a5cb..c6f1eac38 100644--- a/testing/two_view.py+++ b/testing/two_view.py@@ -67,3 +67,28 @@ def two_view_scene(device: torch.device, dtype: torch.dtype) -> Dict[str, torch.return x[..., :2] / x[..., 2:]return {"K1": K1, "K2": K2, "R": R, "t": t, "X": X, "P1": P1, "P2": P2, "x1": proj(P1, X), "x2": proj(P2, X)}+++def calibrated_two_view_scene(+ n: int, noise: float, seed: int, dtype: torch.dtype = torch.float64+) -> Dict[str, torch.Tensor]:+ """Seeded two-view scene in normalized camera coordinates, for essential-matrix tests.++ ``n`` points at depths around 4 in front of both cameras, a small rotation and a unit translation off every axis;+ ``x2`` carries Gaussian noise of standard deviation ``noise`` (calibrated units). ``E = [t]_x R`` is scaled to unit+ Frobenius norm, so that ``x2^T E x1 = 0`` for the noise-free projections.+ """+ generator = torch.Generator().manual_seed(seed)+ X = torch.randn(n, 3, generator=generator, dtype=dtype) * torch.tensor([1.0, 1.0, 0.5], dtype=dtype)+ X = X + torch.tensor([0.0, 0.0, 4.0], dtype=dtype)+ R = axis_angle_to_rotation_matrix(torch.tensor([[0.05, -0.1, 0.03]], dtype=dtype))[0]+ t = torch.nn.functional.normalize(torch.tensor([1.0, 0.2, 0.1], dtype=dtype), dim=0)+ Y = X @ R.T + t+ x1, x2 = X[:, :2] / X[:, 2:], Y[:, :2] / Y[:, 2:]+ x2 = x2 + noise * torch.randn(n, 2, generator=generator, dtype=dtype)+ zero = torch.zeros((), dtype=dtype)+ tx = torch.stack(+ [torch.stack([zero, -t[2], t[1]]), torch.stack([t[2], zero, -t[0]]), torch.stack([-t[1], t[0], zero])]+ )+ E = tx @ R+ return {"x1": x1, "x2": x2, "E": E / E.norm(), "R": R, "t": t}diff --git a/tests/geometry/epipolar/test_essential.py b/tests/geometry/epipolar/test_essential.pyindex f455f6dce..8216613bf 100644--- a/tests/geometry/epipolar/test_essential.py+++ b/tests/geometry/epipolar/test_essential.py@@ -20,10 +20,12 @@ import torchimport korniaimport kornia.geometry.epipolar as epi+from kornia.geometry.conversions import convert_points_to_homogeneous+from kornia.geometry.epipolar.essential import _refine_essential_lmfrom testing.base import BaseTesterfrom testing.geometry.create import generate_two_view_random_scene-from testing.two_view import two_view_scene+from testing.two_view import calibrated_two_view_scene, two_view_scenedef test_generate_two_view_random_scene_is_deterministic():@@ -66,6 +68,143 @@ class TestFindEssential(BaseTester):E_mat = epi.essential.find_essential(points1, points2, weights)assert E_mat.shape == (B, 10, 3, 3)+ @staticmethod+ def _true_e_error(candidates, E):+ """Smallest distance, up to sign, of the finite candidates ``(10, 3, 3)`` from ``E``; inf if there are none."""+ candidates = candidates.cpu().double()+ finite = candidates[torch.isfinite(candidates).flatten(1).all(1)]+ if len(finite) == 0:+ return float("inf")+ E = E.to(finite)+ return float(torch.minimum((finite - E).flatten(1).norm(dim=1), (finite + E).flatten(1).norm(dim=1)).min())++ @pytest.mark.parametrize("input_dtype", [torch.float32, torch.float64])+ def test_exact_five_point_sample_recovers_the_true_e_4884(self, device, input_dtype):+ if device.type == "mps" and input_dtype == torch.float64:+ pytest.skip("MPS does not support float64")+ # #4884: in float32 an exact five-point sample missed the true E; the solve now runs in float64, on the host+ # for MPS inputs.+ misses = 0+ for seed in range(20):+ scene = calibrated_two_view_scene(5, 0.0, seed)+ points1, points2 = scene["x1"][None].to(device, input_dtype), scene["x2"][None].to(device, input_dtype)+ misses += self._true_e_error(epi.find_essential(points1, points2)[0], scene["E"]) > 1e-4+ assert misses == 0++ @pytest.mark.parametrize("input_dtype", [torch.float32, torch.float64])+ def test_no_parallax_backward_is_finite_4903_4952(self, device, input_dtype):+ if device.type == "mps" and input_dtype == torch.float64:+ pytest.skip("MPS does not support float64")+ # With p1 == p2 the essential matrix is not determined. About one such sample in 300 has a multiple root at+ # z = 0, where the backward of torch.linalg.eigvals raised for the whole batch (#4903), and in float32 about+ # one in ten gave an all-NaN gradient (#4952). The roots now come from a detached solve, differentiated by a+ # Newton step that is skipped at a multiple root.+ generator = torch.Generator().manual_seed(0)+ points = torch.rand(1000, 5, 2, generator=generator, dtype=torch.float64).to(device, input_dtype)+ points.requires_grad_()+ epi.find_essential(points, points).nan_to_num().sum().backward()+ assert torch.isfinite(points.grad).all()++ def test_no_parallax_backward_is_finite_with_a_float32_solve(self, monkeypatch):+ # In a float32 solve, as MPS ran before its samples moved to the host, a spurious root near a vanishing+ # leading coefficient (|z| ~ 5e8) overflows z ** 10, and a backward through the masked powers gave+ # 0 * inf = NaN.+ monkeypatch.setattr(epi.essential, "_solve_dtype", lambda device: torch.float32)+ generator = torch.Generator().manual_seed(0)+ points = torch.rand(1000, 5, 2, generator=generator).requires_grad_()+ epi.find_essential(points, points).nan_to_num().sum().backward()+ assert torch.isfinite(points.grad).all()++ def test_true_e_is_recovered_on_random_motions(self, device):+ if device.type == "mps":+ pytest.skip("MPS does not support float64")+ # 2000 exact minimal samples of random scenes, rotations and translation directions. The previous solver+ # missed E by more than 1e-3 on two of them, this one on none (worst about 1e-4, depending on the BLAS); with+ # the LU null-space basis in place of the Householder one it missed seven.+ generator = torch.Generator().manual_seed(0)+ f64 = torch.float64+ X = torch.randn(2000, 5, 3, generator=generator, dtype=f64) * torch.tensor([1.0, 1.0, 0.5], dtype=f64)+ X = X + torch.tensor([0.0, 0.0, 4.0], dtype=f64)+ R = kornia.geometry.conversions.axis_angle_to_rotation_matrix(+ (torch.rand(2000, 3, generator=generator, dtype=f64) - 0.5) * 0.6+ )+ t = torch.nn.functional.normalize(torch.randn(2000, 3, generator=generator, dtype=f64), dim=-1)+ Y = X @ R.mT + t[:, None]+ x1, x2 = X[..., :2] / X[..., 2:], Y[..., :2] / Y[..., 2:]+ E = epi.essential_from_Rt(+ torch.eye(3, dtype=f64).expand(2000, 3, 3), torch.zeros(2000, 3, 1, dtype=f64), R, t[..., None]+ )+ E = E / E.flatten(1).norm(dim=1)[:, None, None]+ candidates = epi.find_essential(x1.to(device), x2.to(device)).cpu()+ distance = torch.minimum(+ (candidates - E[:, None]).flatten(2).norm(dim=-1), (candidates + E[:, None]).flatten(2).norm(dim=-1)+ )+ best = distance.nan_to_num(10.0).amin(1)+ assert best.max() < 1e-3+ assert torch.quantile(best, 0.99) < 1e-6++ def test_degenerate_sample_does_not_affect_the_batch(self, device, dtype):+ _skip_find_essential(device, dtype)+ scene = calibrated_two_view_scene(5, 0.0, 8)+ degenerate1, degenerate2 = scene["x1"].clone(), scene["x2"].clone()+ degenerate1[1], degenerate2[1] = degenerate1[0], degenerate2[0] # a repeated correspondence+ points1 = torch.stack([scene["x1"], degenerate1]).to(device, dtype)+ points2 = torch.stack([scene["x2"], degenerate2]).to(device, dtype)+ candidates = epi.find_essential(points1, points2)+ assert candidates.shape == (2, 10, 3, 3) and candidates.device == points1.device+ assert self._true_e_error(candidates[0], scene["E"]) < 1e-3+ alone = epi.find_essential(points1[:1], points2[:1])[0]+ assert torch.equal(torch.isfinite(candidates[0]), torch.isfinite(alone))+ self.assert_close(candidates[0].nan_to_num(7.0), alone.nan_to_num(7.0), atol=1e-6, rtol=0)++ @pytest.mark.parametrize("case", ["repeat-1-2", "repeat-2-4", "repeat-3-1", "repeat-0-3", "collinear"])+ def test_rank_deficient_sample_has_no_candidates(self, device, case):+ if device.type == "mps":+ pytest.skip("MPS does not support float64")+ # Five constraints of rank four leave a null space of five dimensions: E is not determined. Rounding usually+ # leaves a tiny pivot rather than an exact zero, which must not pass for a regular sample.+ if case == "collinear": # collinear in both images+ t = torch.tensor([-0.4, -0.1, 0.05, 0.2, 0.45], dtype=torch.float64)+ points1 = torch.stack([t, 0.3 * t + 0.1], -1)+ points2 = torch.stack([t + 0.05, -0.5 * t + 0.2], -1)+ else:+ _, i, j = case.split("-")+ scene = calibrated_two_view_scene(5, 0.0, 9)+ points1, points2 = scene["x1"].clone(), scene["x2"].clone()+ points1[int(j)], points2[int(j)] = points1[int(i)], points2[int(i)]+ points1 = points1[None].to(device).requires_grad_()+ candidates = epi.find_essential(points1, points2[None].to(device))+ assert torch.isnan(candidates).all()+ candidates.nan_to_num().sum().backward()+ assert (points1.grad == 0).all()++ @pytest.mark.parametrize("num_points", [5, 7])+ def test_mps_input_is_solved_on_the_host(self, device, num_points):+ if device.type != "mps":+ pytest.skip("compares an MPS input with the same input on the CPU")+ # MPS has no float64: its samples are solved on the host in float64 and the candidates copied back, so they+ # match a CPU solve of the same float32 input and still carry a gradient to the MPS input.+ scene = calibrated_two_view_scene(num_points, 0.0, 8)+ x1, x2 = scene["x1"][None].float(), scene["x2"][None].float()+ on_cpu = epi.find_essential(x1, x2)+ points1 = x1.to(device).requires_grad_()+ on_mps = epi.find_essential(points1, x2.to(device))+ assert on_mps.device == points1.device and on_mps.dtype == torch.float32+ assert torch.equal(torch.isfinite(on_mps).cpu(), torch.isfinite(on_cpu))+ self.assert_close(on_mps.cpu().nan_to_num(7.0), on_cpu.nan_to_num(7.0), atol=1e-6, rtol=0)+ assert self._true_e_error(on_mps[0].detach(), scene["E"]) < 1e-4+ on_mps.nan_to_num().sum().backward()+ assert points1.grad.device == points1.device+ assert torch.isfinite(points1.grad).all() and bool((points1.grad != 0).any())++ def test_repeated_calls_are_bitwise_equal(self, device, dtype):+ # No atomic accumulation: CUDA's scatter_add_ summed the determinant polynomial in a varying order.+ generator = torch.Generator().manual_seed(0)+ points1 = torch.randn(512, 5, 2, generator=generator, dtype=torch.float64).to(device, dtype)+ points2 = torch.randn(512, 5, 2, generator=generator, dtype=torch.float64).to(device, dtype)+ first, second = epi.find_essential(points1, points2), epi.find_essential(points1, points2)+ assert torch.equal(first.nan_to_num(7.0), second.nan_to_num(7.0))+def test_epipolar_constraint(self, device, dtype):calibrated_x1 = torch.tensor([[[0.0640, 0.7799], [-0.2011, 0.2836], [-0.1355, 0.2907], [0.0520, 1.0086], [-0.0361, 0.6533]]],@@ -740,7 +879,10 @@ class TestMotionFromEssentialChooseSolution(BaseTester):_NO_HALF_LU = "{} calls torch.det (LU), which has no float16/bfloat16 kernel"-_NO_HALF_FIND_ESSENTIAL = "find_essential calls torch.linalg.lu_factor_ex, which has no float16/bfloat16 kernel"+_NO_HALF_FIND_ESSENTIAL = (+ "find_essential solves in float64, but float16/bfloat16 correspondences are too coarse for these tolerances and "+ "the reference helpers call torch.linalg.inv, which has no half kernel"+)_HALF_PIXEL_F = ("a pixel-unit F spans eight decades (entries down to ~1e-8): float16 flushes the small entries to zero and ""bfloat16's 8-bit mantissa cannot resolve the epipolar residual, which kornia evaluates in the input dtype"@@ -770,8 +912,6 @@ def _skip_half(dtype: torch.dtype, reason: str) -> None:def _skip_find_essential(device: torch.device, dtype: torch.dtype) -> None:_skip_half(dtype, _NO_HALF_FIND_ESSENTIAL)- if device.type == "mps":- pytest.skip("find_essential calls torch.linalg.eigvals, which has no MPS kernel (#4528)")def _hom(p: torch.Tensor) -> torch.Tensor:@@ -817,19 +957,23 @@ class TestConventionEssential(BaseTester):real[num_points] = E[0, finite]assert real[num_points].shape[0] >= 1self.assert_close(real[num_points].norm(dim=(-2, -1)), torch.ones_like(real[num_points][:, 0, 0]))- # True-E recovery is checked on all twelve points because the minimal sample can miss it (#4884).# Minimal sample: every real candidate satisfies x2^T E x1 = 0 on the normalised coordinates of points1# (first image) and points2 (second image); the swapped product is the control.p1, p2 = n1[:, :5], n2[:, :5]for cand in real[5]:assert _epipolar_residual(cand[None], p1, p2).max() < 1e-3 * _epipolar_residual(cand[None], p2, p1).max()- # All twelve points: one candidate is the true E up to sign, on the same side.+ # The minimal sample and all twelve points: one candidate is the true E up to sign, on the same side. The+ # minimal sample used to miss it in float32 (#4884); the solve now runs in float64, on the host for MPS.E_gt = _gt_essential(two_view)E_gt = E_gt / E_gt.norm()- dist = torch.minimum((real[12] - E_gt).abs().amax(dim=(-2, -1)), (real[12] + E_gt).abs().amax(dim=(-2, -1)))- assert dist.min() < 1e-4- best = real[12][dist.argmin()][None]- assert _epipolar_residual(best, n1, n2).max() < 1e-3 * _epipolar_residual(best, n2, n1).max()+ for num_points in (5, 12):+ candidates = real[num_points]+ dist = torch.minimum(+ (candidates - E_gt).abs().amax(dim=(-2, -1)), (candidates + E_gt).abs().amax(dim=(-2, -1))+ )+ assert dist.min() < 1e-4+ best = candidates[dist.argmin()][None]+ assert _epipolar_residual(best, n1, n2).max() < 1e-3 * _epipolar_residual(best, n2, n1).max()def test_convention_essential_from_Rt_is_tx_R_of_relative_motion(self, device, dtype):two_view = two_view_scene(device, dtype)@@ -1046,7 +1190,6 @@ class TestConventionEssential(BaseTester):assert (X_b[1, :, 2] > 0).all()def test_convention_find_essential_no_real_root_nan_4883(self, device, dtype):- _skip_find_essential(device, dtype)# #4883: a five-point sample with no real root returns ten NaN slots, like the complex slots of any other# sample, so an isfinite filter drops it. Sample:# g = torch.Generator().manual_seed(0)@@ -1065,3 +1208,74 @@ class TestConventionEssential(BaseTester):(grad,) = torch.autograd.grad(E[1][real].sum(), p1)assert torch.isfinite(grad).all()assert (grad[0] == 0).all()+++class TestRefineEssentialLM(BaseTester):+ """``_refine_essential_lm``, RANSAC's Levenberg-Marquardt refinement of essential matrices (float64, host)."""++ @staticmethod+ def _start(E, scale, seed):+ noise = torch.randn(3, 3, generator=torch.Generator().manual_seed(seed), dtype=E.dtype)+ start = epi.project_to_essential(E + scale * noise)+ return (start / start.norm())[None]++ @staticmethod+ def _aligned(E, reference):+ return E * torch.sign((E * reference).sum())++ @pytest.mark.parametrize("loss", ["truncated", "cauchy"])+ def test_stays_on_the_manifold_and_lowers_the_cost(self, loss):+ scene = calibrated_two_view_scene(200, 1e-3, 0)+ x1, x2 = scene["x1"], scene["x2"]+ start = self._start(scene["E"], 0.02, 1)+ refined = _refine_essential_lm(+ start, convert_points_to_homogeneous(x1), convert_points_to_homogeneous(x2), None, loss, 3e-3**2, 10+ )+ singular_values = torch.linalg.svdvals(refined[0])+ self.assert_close(+ singular_values, torch.tensor([2**-0.5, 2**-0.5, 0.0], dtype=torch.float64), atol=1e-12, rtol=0+ )+ before = epi.sampson_epipolar_distance(x1[None], x2[None], start).sum()+ after = epi.sampson_epipolar_distance(x1[None], x2[None], refined).sum()+ assert after < 0.5 * before++ def test_reaches_the_noise_free_model(self):+ scene = calibrated_two_view_scene(100, 0.0, 2)+ h1, h2 = convert_points_to_homogeneous(scene["x1"]), convert_points_to_homogeneous(scene["x2"])+ refined = _refine_essential_lm(self._start(scene["E"], 0.01, 3), h1, h2, None, "cauchy", 1e-6, 20)[0]+ self.assert_close(self._aligned(refined, scene["E"]), scene["E"], atol=1e-9, rtol=0)++ def test_mask_restricts_each_model_to_its_correspondences(self):+ scene = calibrated_two_view_scene(60, 0.0, 4)+ x2 = scene["x2"].clone()+ x2[30:] = x2[30:] + 0.3 # gross outliers, excluded by the mask+ h1, h2 = convert_points_to_homogeneous(scene["x1"]), convert_points_to_homogeneous(x2)+ mask = torch.zeros(1, 60, dtype=torch.float64)+ mask[0, :30] = 1.0+ refined = _refine_essential_lm(self._start(scene["E"], 0.01, 5), h1, h2, mask, "cauchy", 1e-6, 20)[0]+ self.assert_close(self._aligned(refined, scene["E"]), scene["E"], atol=1e-9, rtol=0)++ def test_rejects_steps_that_raise_the_cost(self):+ # A start 0.3 off and 30 of 100 correspondences moved off their epipolar lines: an undamped Gauss-Newton step+ # raises the Cauchy cost at the third iteration here. The refiner keeps only steps that lower it, so its cost+ # after each iteration is never above the one before (the loop is deterministic, so k iterations are the+ # first k of k + 1).+ scene = calibrated_two_view_scene(100, 1e-3, 8)+ x1, x2 = scene["x1"], scene["x2"].clone()+ x2[70:] = x2[70:] + 0.2 * torch.randn(30, 2, generator=torch.Generator().manual_seed(8), dtype=x2.dtype)+ h1, h2 = convert_points_to_homogeneous(x1), convert_points_to_homogeneous(x2)+ start, scale2 = self._start(scene["E"], 0.3, 108), 3e-3**2+ costs = []+ for iters in range(11):+ refined = _refine_essential_lm(start, h1, h2, None, "cauchy", scale2, iters)+ costs.append(float(torch.log1p(epi.sampson_epipolar_distance(x1[None], x2[None], refined) / scale2).sum()))+ assert all(later <= earlier * (1 + 1e-9) for earlier, later in zip(costs, costs[1:]))+ assert costs[-1] < 0.5 * costs[0]++ def test_batched_models_are_refined_independently(self):+ scene = calibrated_two_view_scene(80, 0.0, 6)+ h1, h2 = convert_points_to_homogeneous(scene["x1"]), convert_points_to_homogeneous(scene["x2"])+ starts = torch.cat([self._start(scene["E"], 0.01, 7), self._start(scene["E"], 0.03, 8)])+ together = _refine_essential_lm(starts, h1, h2, None, "truncated", 1e-4, 15)+ alone = torch.cat([_refine_essential_lm(start[None], h1, h2, None, "truncated", 1e-4, 15) for start in starts])+ self.assert_close(together, alone, atol=1e-12, rtol=0)diff --git a/tests/geometry/epipolar/test_fundamental.py b/tests/geometry/epipolar/test_fundamental.pyindex e77b1459f..516d87d35 100644--- a/tests/geometry/epipolar/test_fundamental.py+++ b/tests/geometry/epipolar/test_fundamental.py@@ -23,12 +23,13 @@ import torchimport kornia.geometry.epipolar as epiimport kornia.geometry.epipolar.fundamental as fundamental_modulefrom kornia.core.utils import _torch_svd_cast-from kornia.geometry.conversions import axis_angle_to_rotation_matrix+from kornia.geometry.conversions import axis_angle_to_rotation_matrix, convert_points_to_homogeneousfrom kornia.geometry.epipolar.fundamental import (_eight_point_fundamental,_enforce_rank2,_epipolar_design_rows,_rank2_projection,+ _refine_fundamental_lm,_seven_point_candidates,)from kornia.geometry.solvers.homogeneous import _null_space_lu@@ -1082,3 +1083,49 @@ class TestSevenPoint(BaseTester):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],))+++class TestRefineFundamentalLM(BaseTester):+ @staticmethod+ def _problem(seed):+ generator = torch.Generator().manual_seed(seed)+ x1 = torch.rand(30, 2, generator=generator, dtype=torch.float64) * 2 - 1+ x2 = x1 + 0.1 * torch.rand(30, 2, generator=generator, dtype=torch.float64)+ F = torch.randn(2, 3, 3, generator=generator, dtype=torch.float64)+ mask = (torch.rand(2, 30, generator=generator, dtype=torch.float64) > 0.3).to(torch.float64)+ return F, convert_points_to_homogeneous(x1), convert_points_to_homogeneous(x2), mask++ def test_matches_recorded_outputs(self):+ # Recorded at c27b2dac, before the normal equations were shared with the essential refiner, on x86-64 with+ # MKL: sharing them changed no bit there. Other BLAS builds round differently and five LM iterations amplify+ # it (MKL restricted to SSE4.2 moves the result by up to 3.8e-11), so the pin allows 1e-9.+ F, h1, h2, _ = self._problem(0)+ truncated = _refine_fundamental_lm(F, h1, h2, None, "truncated", 0.01, 5)+ expected = [+ [+ [0.006098700800078563, -0.5116733906310833, -0.4728232264343061],+ [0.5402957876915827, 0.026014512989784022, -0.7119944428694382],+ [0.4517012115690219, 0.719917958973044, 0.03858329173804309],+ ],+ [+ [0.030697813957637547, 0.6162157569540634, 0.3919058257981223],+ [-0.09984663113859049, -0.6936885856570343, 0.38216094006781043],+ [0.016680785956596982, -0.28587426648587977, -0.5717588387569966],+ ],+ ]+ self.assert_close(truncated, torch.tensor(expected, dtype=torch.float64), atol=1e-9, rtol=0)+ F, h1, h2, mask = self._problem(1)+ cauchy = _refine_fundamental_lm(F, h1, h2, mask, "cauchy", 0.001, 5)+ expected = [+ [+ [0.004714855956989089, -0.09624554989117944, 0.5789110476966798],+ [0.09642747178202637, -0.004227697559524207, -0.8101614368196856],+ [-0.5879441787194538, 0.793171411548398, -0.0025179985239673804],+ ],+ [+ [-0.01217626570990575, 0.8162523711647025, 0.0863979715658775],+ [-0.792854504738295, -0.01999050672309971, 0.6096130586816405],+ [-0.041273601467539764, -0.660172201639381, -0.0304491757491199],+ ],+ ]+ self.assert_close(cauchy, torch.tensor(expected, dtype=torch.float64), atol=1e-9, rtol=0)diff --git a/tests/geometry/test_ransac.py b/tests/geometry/test_ransac.pyindex e5af1d757..e2f6fa40e 100644--- a/tests/geometry/test_ransac.py+++ b/tests/geometry/test_ransac.py@@ -574,7 +574,7 @@ class TestRANSACEssential(BaseTester):never beats the minimal-solver model, exactly as with the default sampler settings."""torch.random.manual_seed(0)- ransac = RANSAC("essential", batch_size=32, max_iter=1).to(device=device, dtype=dtype)+ ransac = RANSAC("essential", batch_size=32, max_iter=1, local_optimization="dlt").to(device=device, dtype=dtype)for _ in range(5):kp1 = torch.rand(20, 2, device=device, dtype=dtype)kp2 = torch.rand(20, 2, device=device, dtype=dtype)@@ -1283,7 +1283,7 @@ class TestRANSACDefaults(BaseTester):("fundamental", 7, "lm"),("fundamental_7pt", 7, "lm"),("fundamental_8pt", 8, "lm"),- ("essential", 5, "dlt"),+ ("essential", 5, "lm"),("homography_from_linesegments", 4, "dlt"),],)@@ -1535,10 +1535,9 @@ class TestRANSACValidation(BaseTester):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):+ def test_lm_local_optimization_needs_a_supported_model(self):with pytest.raises(ValueError):- RANSAC(model_type, local_optimization="lm")+ RANSAC("homography_from_linesegments", local_optimization="lm")@pytest.mark.parametrize("model", ["fundamental_7pt", "essential"])def test_mismatched_correspondences(self, device, dtype, model):@@ -1559,7 +1558,7 @@ class TestRANSACValidation(BaseTester):points2 = points1.clone()points2[:, 1] *= 2candidate = torch.tensor([[0.0, 0.0, 0.0], [0.0, 0.0, -1.0], [0.0, 2.0, 0.0]], device=device, dtype=dtype)[None]- ransac = RANSAC("essential", inl_th=0.01, batch_size=1, max_iter=1, max_lo_iters=0)+ ransac = RANSAC("essential", inl_th=0.01, batch_size=1, max_iter=1, max_lo_iters=0, local_optimization="dlt")ransac.minimal_solver = lambda a, b, w: candidatereturn ransac, points1, points2@@ -1641,7 +1640,15 @@ class TestRANSACEssentialInvalidPolisher(BaseTester):points = torch.rand(20, 2, device=device, dtype=dtype)valid = torch.tensor([[0.0, 0.0, 0.0], [0.0, 0.0, -1.0], [0.0, 1.0, 0.0]], device=device, dtype=dtype)[None]candidates = torch.cat([torch.full_like(valid, float("nan")), valid])- estimator = RANSAC("essential", batch_size=1, max_iter=1, max_lo_iters=2, lo_sample_size=lo_sample_size, seed=0)+ estimator = RANSAC(+ "essential",+ batch_size=1,+ max_iter=1,+ max_lo_iters=2,+ lo_sample_size=lo_sample_size,+ seed=0,+ local_optimization="dlt",+ )estimator.minimal_solver = lambda a, b, w: validestimator.polisher_solver = lambda a, b, w: candidatesmodel, mask = estimator(points, points)@@ -1694,38 +1701,65 @@ def _model_errors(model_type: str, model: torch.Tensor, kp1: torch.Tensor, kp2:return sampson_epipolar_distance(kp1[None], kp2[None], model[None], squared=False, eps=0.0)[0]+_FOCAL, _CENTER = 800.0, (320.0, 240.0)+++def _px(model_type: str, pixels: float) -> float:+ """A distance given in pixels, in the input units of ``model_type``: calibrated units for ``"essential"``."""+ return pixels / _FOCAL if model_type == "essential" else pixels+++def _to_input_units(model_type: str, kp: torch.Tensor) -> torch.Tensor:+ """Pixel coordinates of :func:`_two_view_scene`'s camera, as normalized camera coordinates for ``"essential"``."""+ if model_type != "essential":+ return kp+ return (kp - torch.tensor(_CENTER, dtype=kp.dtype, device=kp.device)) / _FOCAL++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)+ """``kp1, kp2, clean, model, inliers``; for ``"essential"`` the two-view scene in normalized camera coordinates."""+ if model_type == "homography":+ return _planar_scene(n, outliers, noise, seed)+ kp1, kp2, clean, F, inliers = _two_view_scene(n, outliers, noise, seed)+ if model_type != "essential":+ return kp1, kp2, clean, F, inliers+ K = torch.tensor([[_FOCAL, 0.0, _CENTER[0]], [0.0, _FOCAL, _CENTER[1]], [0.0, 0.0, 1.0]], dtype=F.dtype)+ E = K.T @ F @ K+ return (*(_to_input_units(model_type, kp) for kp in (kp1, kp2, clean)), E / E.norm(), inliers)-_LM_MODELS = ["homography", "fundamental", "fundamental_8pt"]+_LM_MODELS = ["homography", "fundamental", "fundamental_8pt", "essential"]class TestRANSACLevenbergMarquardt(BaseTester):- """``local_optimization="lm"``, the default for homographies and fundamental matrices."""+ """``local_optimization="lm"``, the default for homographies, fundamental and essential matrices.++ Essential-matrix cases use the two-view scene in normalized camera coordinates (focal length 800 px), with every+ pixel threshold and tolerance converted by :func:`_px`.+ """@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)+ ransac = RANSAC(model_type, inl_th=_px(model_type, 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 model.shape == (3, 3) and model.dtype == dtype and model.device == kp1.to(device, dtype).deviceassert mask.shape == (200,) and mask.dtype == torch.bool and mask.device == model.deviceassert torch.equal(mask.cpu(), inliers)- tolerance = 1e-4 if dtype == torch.float64 else 5e-2+ tolerance = _px(model_type, 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)+ model, mask = RANSAC(model_type, inl_th=_px(model_type, 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)+ assert torch.equal(mask.cpu(), errors <= _px(model_type, 1.5))def test_msac_does_not_discard_supported_candidates(self, device, dtype, monkeypatch):if dtype in (torch.float16, torch.bfloat16):@@ -1759,22 +1793,23 @@ class TestRANSACLevenbergMarquardt(BaseTester):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)+ th = _px(model_type, 1.5)+ minimal, _ = RANSAC(model_type, inl_th=th, seed=0, max_lo_iters=0, refine_iters=0)(*args)+ refined, _ = RANSAC(model_type, inl_th=th, 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+ assert miss_refined < _px(model_type, 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)+ kp1 = _to_input_units(model_type, torch.rand(40, 2, generator=generator) * 600).to(device, dtype)+ kp2 = _to_input_units(model_type, 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)+ model, mask = RANSAC(model_type, inl_th=_px(model_type, 1e-4), seed=0, max_samples=512)(kp1, kp2)assert bool((model == 0).all()) and model.dtype == dtypeassert mask.shape == (40,) and mask.dtype == torch.bool and not bool(mask.any())@@ -1785,7 +1820,8 @@ class TestRANSACLevenbergMarquardt(BaseTester):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))+ ransac = RANSAC(model_type, inl_th=_px(model_type, 1.0), seed=0)+ model, mask = ransac(kp1.to(device, dtype), kp2.to(device, dtype))assert torch.isfinite(model).all()assert not bool(mask[:6].any()) and bool(mask[6:].all())@@ -1794,10 +1830,11 @@ class TestRANSACLevenbergMarquardt(BaseTester):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)+ th = _px(model_type, 2.0)+ model_a, mask_a = RANSAC(model_type, inl_th=th, 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)+ model_b, mask_b = RANSAC(model_type, inl_th=th, 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"])@@ -1823,7 +1860,11 @@ class TestRANSACLevenbergMarquardt(BaseTester):@pytest.mark.parametrize("model_type, max_samples, expected",- [("homography", 2000, [512, 1024, 464]), ("fundamental", 2000, [256, 512, 1024, 208])],+ [+ ("homography", 2000, [512, 1024, 464]),+ ("fundamental", 2000, [256, 512, 1024, 208]),+ ("essential", 2000, [64, 128, 256, 512, 1024, 16]),+ ],)def test_auto_batches_grow_on_cpu_and_cover_the_budget(self, device, model_type, max_samples, expected):if device.type != "cpu":@@ -1837,6 +1878,14 @@ class TestRANSACLevenbergMarquardt(BaseTester):ransac(kp1.float(), kp2.float())assert sizes == expected+ def test_essential_auto_batches_per_device(self):+ # A five-point sample needs few draws at high inlier ratios: small first batches on every device, the CPU+ # one smallest (tuned on PhotoTourism, where a first batch of 256 doubled the time at equal accuracy).+ ransac = RANSAC("essential", max_samples=100000)+ assert ransac._lm_batch_range(100, torch.device("cpu")) == (64, 1024)+ assert ransac._lm_batch_range(100, torch.device("cuda")) == (256, 8192)+ assert ransac._lm_batch_range(100, torch.device("mps")) == (256, 8192)+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)@@ -1869,6 +1918,76 @@ class TestRANSACLevenbergMarquardt(BaseTester):assert torch.equal(mask.cpu(), inliers)+class TestRANSACEssentialLevenbergMarquardt(BaseTester):+ """What is specific to essential matrices with ``local_optimization="lm"``: no normalization, unit-norm output."""++ def _skip_half(self, dtype):+ if dtype in (torch.float16, torch.bfloat16):+ pytest.skip("calibrated thresholds of 1e-3 are below half-precision resolution")++ @pytest.mark.parametrize("seed", [0, 2, 3])+ def test_returns_a_unit_frobenius_essential_matrix(self, device, dtype, seed):+ self._skip_half(dtype)+ kp1, kp2, _, _, _ = _scene("essential", 200, 60, 0.5, seed=seed)+ E, _ = RANSAC("essential", inl_th=_px("essential", 1.5), seed=0)(kp1.to(device, dtype), kp2.to(device, dtype))+ singular_values = torch.linalg.svdvals(E.cpu().double())+ expected = torch.tensor([2**-0.5, 2**-0.5, 0.0], dtype=torch.float64)+ self.assert_close(singular_values, expected, atol=1e-6 if dtype == torch.float64 else 1e-3, rtol=0)+ # E and -E are the same model; the sign is fixed so that equal inputs give equal outputs on every backend.+ # Without the rule, the scene of seed 2 returns a negative largest entry on the CPU in either dtype.+ assert E.flatten()[E.abs().argmax()] > 0++ @pytest.mark.parametrize("n", [6, 7, 8])+ def test_small_inputs(self, device, dtype, n):+ self._skip_half(dtype)+ kp1, kp2, _, truth, _ = _scene("essential", n, 0, 0.0, seed=3)+ E, mask = RANSAC("essential", inl_th=_px("essential", 1.0), seed=0)(+ kp1.to(device, dtype), kp2.to(device, dtype)+ )+ assert E.shape == (3, 3) and mask.shape == (n,)+ # Noise-free: every correspondence is an inlier and E is the true one, up to sign.+ assert bool(mask.all())+ E = E.cpu().double()+ tolerance = 1e-9 if dtype == torch.float64 else 1e-4+ assert min(float((E - truth).norm()), float((E + truth).norm())) < tolerance++ def test_pixel_coordinates_by_mistake_stay_finite(self, device, dtype):+ self._skip_half(dtype)+ # Pixel coordinates are not a valid input for "essential", but must not produce NaN or raise.+ kp1, kp2, _, _, _ = _two_view_scene(100, 30, 0.0, seed=4)+ E, mask = RANSAC("essential", inl_th=1.0, seed=0)(kp1.to(device, dtype), kp2.to(device, dtype))+ assert torch.isfinite(E).all() and mask.shape == (100,)++ def test_planar_scene(self, device, dtype):+ self._skip_half(dtype)+ # Every scene point on one plane: the five-point solver still determines E (a homography does not), and the+ # pipeline recovers it among outliers.+ generator = torch.Generator().manual_seed(12)+ f64 = torch.float64+ XY = (torch.rand(120, 2, generator=generator, dtype=f64) - 0.5) * 4+ X = torch.cat([XY, (4.0 + 0.3 * XY[:, :1] - 0.2 * XY[:, 1:])], 1)+ 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)+ Y = X @ R.T + t+ kp1, kp2 = X[:, :2] / X[:, 2:], Y[:, :2] / Y[:, 2:]+ kp2[:30] = (torch.rand(30, 2, generator=generator, dtype=f64) - 0.5) * 1.2+ E_true = _skew(t) @ R+ E_true = E_true / E_true.norm()+ E, mask = RANSAC("essential", inl_th=1e-4, seed=0)(kp1.to(device, dtype), kp2.to(device, dtype))+ assert torch.equal(mask.cpu(), torch.arange(120) >= 30)+ E = E.cpu().double()+ tolerance = 1e-6 if dtype == torch.float64 else 1e-3+ assert torch.minimum((E - E_true).norm(), (E + E_true).norm()) < tolerance++ def test_batch_of_one_sample(self, device, dtype):+ self._skip_half(dtype)+ kp1, kp2, _, _, inliers = _scene("essential", 60, 10, 0.0, seed=5)+ ransac = RANSAC("essential", inl_th=_px("essential", 1.0), seed=0, batch_size=1, max_samples=64)+ _, mask = ransac(kp1.to(device, dtype), kp2.to(device, dtype))+ assert mask.shape == (60,)+ assert torch.equal(mask.cpu(), inliers)++class TestRANSACLevenbergMarquardtKernels(BaseTester):"""RANSAC's normalization and the Levenberg-Marquardt refiners it calls."""@@ -1901,6 +2020,8 @@ class TestRANSACLevenbergMarquardtKernels(BaseTester):@pytest.mark.parametrize("loss", ["cauchy", "truncated"])def test_refinement_reaches_a_local_minimum(self, device, dtype, model_type, loss):self._skip_half(dtype)+ if device.type == "mps":+ pytest.skip("the refinement kernels run in float64, which MPS does not support")# 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)diff --git a/tests/test_known_failures.py b/tests/test_known_failures.pyindex e556a051f..362491ed5 100644--- a/tests/test_known_failures.py+++ b/tests/test_known_failures.py@@ -193,8 +193,8 @@ class TestKnownFailureOutcomes:def test_recorded_mps_float32_baseline() -> None:failures, path = load_known_failures("mps", "float32")- # The exact count changes with every fix that removes a manifest line; the contract is the file, not a number.- assert len(failures) > 0+ # The exact count changes with every fix that removes a manifest line, down to none; the contract is the file,+ # not a number.assert path.name == "mps_float32.txt"assert all(issubclass(exception, BaseException) for exception in failures.values())assert ISSUE_URL == "https://github.com/kornia/kornia/issues/4159"