🐍 Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
perf(geometry): reduce CPU RANSAC scoring and refinement overhead (#5095)
Dmytro Mishkina7d177cbf308
diff --git a/benchmarks/README.md b/benchmarks/README.mdindex ffc739eb4..6bc879f74 100644--- a/benchmarks/README.md+++ b/benchmarks/README.md@@ -35,7 +35,7 @@ Deeper, single-topic scripts:| Directory | Contents || --- | --- || [`augmentation/`](augmentation/) | Cross-library augmentation benchmarks — [`flagship.py`](augmentation/flagship.py) (class-API, parameter sampling included, vs torchvision v2/albumentations/OpenCV/PIL) plus pipeline/per-op scripts; see its [README](augmentation/README.md). |-| [`geometry/`](geometry/) | [`flagship.py`](geometry/flagship.py): core geometry ops vs OpenCV/torchvision v2. [`ransac.py`](geometry/ransac.py): batched RANSAC runtime and IMC pose accuracy on cached correspondences. [`heb.py`](geometry/heb.py): homography RANSAC time versus reprojection mAA on a HEB scene. |+| [`geometry/`](geometry/) | [`flagship.py`](geometry/flagship.py): core geometry ops vs OpenCV/torchvision v2. [`ransac.py`](geometry/ransac.py): batched RANSAC runtime and IMC pose accuracy on cached correspondences. [`ransac_cpu.py`](geometry/ransac_cpu.py): repeatable CPU base/branch comparison of H/F/E latency and geometric quality on HEB and PhotoTourism. [`heb.py`](geometry/heb.py): homography RANSAC time versus reprojection mAA on a HEB scene. || [`morphology/`](morphology/) | [`flagship.py`](morphology/flagship.py): representative morphology ops vs torchmorph, albumentations, scikit-image and OpenCV. [`engines.py`](morphology/engines.py): dilation engine comparison across explicit public engines. || [`filters/`](filters/) | [`flagship.py`](filters/flagship.py): core filters vs OpenCV/albumentations/torchvision v2/kornia-rs/PIL/scikit-image. [`gaussian_cpu.py`](filters/gaussian_cpu.py): Gaussian blur and scale-pyramid base/branch timing and numerical comparisons; [report](filters/gaussian_cpu.md). || [`color/`](color/) | pytest-benchmark microbenchmarks for color conversions (`*_test.py`). |@@ -47,6 +47,36 @@ Deeper, single-topic scripts:extraction, matching and homography quality on CPU, CUDA or MPS;[device results and usage](feature/sift_summary.md).+### CPU RANSAC base/branch comparison++Run the same harness from each checkout, using a PhotoTourism NPZ prepared by+[`ransac.py prepare`](geometry/ransac.py) and a HEB scene HDF5 file:++```bash+python benchmarks/geometry/ransac_cpu.py --npz /data/phototourism-7x10.npz \+ --heb /data/NYC_Library_homographies.h5 --pairs 10 --h-pairs 30 \+ --models H,F,E --budgets 256,4096 --seeds 0,1,2 --threads 4 --json /tmp/cpu.json+```++The default `--pairs 2` selects two pairs per scene/feature; `--pairs 10` uses up to+70 pairs per feature in a seven-scene, ten-pair export (fewer if a feature is missing+from some scenes). Timings are repeated public+`RANSAC.forward` calls at seed zero (median and IQR, `--min-run-time 0.1`); geometric+quality uses every requested seed. H measures ground-truth-inlier reprojection mAA+at 1–20 pixels; F/E measure recovered-pose mAA at 1–10 degrees, with scenes and seeds+weighted equally. Failures count as misses. JSON records every pair and an aggregate+summary. Use `--no-timing` for a quality-only run. PR #5095's measured base/branch comparison and+rejected batch experiments are in its [archived report](https://github.com/kornia/kornia/blob/7730b96647e7dc517c44ebb6ab4e81c92f239a86/benchmarks/geometry/ransac_cpu.md).++Sampling, scoring, batching, and local optimization use the class defaults;+`--confidence` defaults to 0.999. Pixel inlier thresholds default to H=8,+SIFT F/E=0.75, SIFT8k=0.5, and+ALIKED-LightGlue=1.5. Override with `--h-threshold` or repeatable+`--epi-threshold FEATURE=PX`. PhotoTourism correspondence order is preserved by+default (`--sort-matches` sorts scores/ratios); HEB uses the same seeded selection,+SNN<0.8 filter, and stable ratio ordering as `heb.py`. Optional `h5py` reads HEB;+OpenCV provides pose recovery for F/E. Neither PoseLib nor an IMC package is needed.+## Methodology contractEvery benchmark here must follow the same rules (utilities in [`common.py`](common.py)):diff --git a/benchmarks/geometry/ransac_cpu.py b/benchmarks/geometry/ransac_cpu.pynew file mode 100644index 000000000..223b96a5c--- /dev/null+++ b/benchmarks/geometry/ransac_cpu.py@@ -0,0 +1,379 @@+# LICENSE HEADER MANAGED BY add-license-header+#+# Copyright 2018 Kornia Team+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+#++"""Reproducible CPU RANSAC A/B timings and geometric quality on HEB and cached PhotoTourism pairs.++Run this same harness from each checkout. Only public RANSAC.forward is timed, on preloaded float32 CPU+inputs, with default sampling, scoring, batching and local optimization; only threshold, confidence+(default 0.999), budget and seed are overridden. Construction and pose recovery+are excluded. Each pair/budget is repeatedly timed at seed zero; quality is scored independently at all+requested seeds. Budgets count minimal samples, with confidence stopping allowed to finish earlier.++PhotoTourism NPZ files are prepared by ransac.py. Pair selection follows its pair_keys helper: the first+--pairs entries per scene/feature in sorted export order. Input correspondence order is preserved unless+--sort-matches is given. Essential estimation uses calibrated coordinates and divides the pixel threshold+by the mean focal length. Pose quality is max(rotation error, sign-invariant translation angular error),+with strict 1..10 degree mAA thresholds, averaged equally over scenes and seeds per feature.++HEB selects --h-pairs without replacement using default_rng(--pair-seed), then retains SNN ratios below+0.8 and sorts them best-first. Quality is mean reprojection error on all ground-truth inliers, with mAA+at ten logarithmic thresholds from 1 to 20 pixels (inclusive comparisons, as in heb.py). Failures count+as misses. The default pixel inlier thresholds are H=8, SIFT F/E=0.75, SIFT8k=0.5, ALIKED-LightGlue=1.5;+these are fixed diagnostic choices, not a claim of universal optimality. Override via --h-threshold and+--epi-threshold FEATURE=PX. Optional h5py reads HEB; OpenCV supplies pose recovery for F/E. No downloads.++ python benchmarks/geometry/ransac_cpu.py --npz /data/phototourism-7x10.npz \+ --heb /data/NYC_Library_homographies.h5 --pairs 10 --h-pairs 30 --json /tmp/cpu.json+"""++from __future__ import annotations++import argparse+import hashlib+import sys+from collections import defaultdict+from functools import partial+from pathlib import Path+from typing import Any++import numpy as np+import torch++ROOT = Path(__file__).resolve().parents[2]+sys.path.insert(0, str(ROOT))+sys.path.insert(1, str(ROOT / "benchmarks"))++from common import run_metadata, save_json, time_us, warm_up_cpu # noqa: E402+from geometry.heb import MAA_THRESHOLDS_PX, load_pairs, reprojection_error # noqa: E402+from geometry.ransac import PairCalibration, digest, measured_ransac_source, pair_keys # noqa: E402++import kornia # noqa: E402+from kornia.geometry import RANSAC # noqa: E402++MODEL_TYPES = {"H": "homography", "F": "fundamental", "E": "essential"}+EPI_THRESHOLDS = {"sift": 0.75, "sift8k": 0.5, "aliked_lightglue": 1.5}+++def load_epipolar(args: argparse.Namespace) -> list[dict[str, Any]]:+ """Load only the selected exported records, retaining their correspondence order by default."""+ items = []+ with np.load(args.npz, allow_pickle=False) as data:+ for key in pair_keys(data, args):+ scene, feature, _ = key.split("__")+ order = np.arange(len(data[key + "__mkp_a"]))+ field = key + "__score" if key + "__score" in data else key + "__ratio"+ if args.sort_matches and field in data:+ order = np.argsort(data[field].reshape(-1), kind="stable")+ items.append(+ {+ "pair": key,+ "scene": scene,+ "feature": feature,+ "a": data[key + "__mkp_a"][order].astype(np.float64),+ "b": data[key + "__mkp_b"][order].astype(np.float64),+ "calib": [{f: data[f"{key}__{side}_{f}"] for f in ("K", "R", "T")} for side in ("a", "b")],+ }+ )+ return items+++def load_homography(args: argparse.Namespace) -> list[dict[str, Any]]:+ """Use the same seeded HEB pair selection, SNN filter and stable ranking as heb.py."""+ selected = load_pairs(argparse.Namespace(h5=args.heb, pairs=args.h_pairs, pair_seed=args.pair_seed))+ items = []+ for name, item in selected.items():+ matches = item["matches"]+ retained = matches[matches[:, 8] < 0.8]+ ranked = retained[np.argsort(retained[:, 8], kind="stable")]+ gt = matches[matches[:, 9].astype(bool)]+ items.append(+ {+ "pair": name,+ "scene": args.heb.stem.removesuffix("_homographies"),+ "feature": "heb",+ "a": ranked[:, :2].astype(np.float64),+ "b": ranked[:, 2:4].astype(np.float64),+ "gt_a": gt[:, :2],+ "gt_b": gt[:, 2:4],+ }+ )+ return items+++def pose_error(F: np.ndarray, a: np.ndarray, b: np.ndarray, calib_a: dict[str, Any], calib_b: dict[str, Any]) -> float:+ """IMC angular pose error: max(rotation angle, unsigned translation angle), in degrees.++ This is the same OpenCV recovery and angular convention as imc2021-simple's metrics.pose_error;+ keeping this small metric here avoids importing its reconstruction and dataset dependencies.+ """+ import cv2++ if len(a) < 5 or len(b) < 5:+ return float("inf")+ rotation_gt = calib_b["R"] @ calib_a["R"].T+ translation_gt = calib_b["T"].reshape(-1) - rotation_gt @ calib_a["T"].reshape(-1)+ if np.linalg.norm(translation_gt) < 1e-9:+ return float("inf")+ Ka, Kb = calib_a["K"], calib_b["K"]+ normalized_a = (a - Ka[:2, 2]) / np.array([Ka[0, 0], Ka[1, 1]])+ normalized_b = (b - Kb[:2, 2]) / np.array([Kb[0, 0], Kb[1, 1]])+ try:+ _, rotation, translation, _ = cv2.recoverPose(Kb.T @ F @ Ka, normalized_a, normalized_b)+ except cv2.error:+ return float("inf")+ rotation_cos = np.clip((np.trace(rotation @ rotation_gt.T) - 1.0) / 2.0, -1.0, 1.0)+ translation = translation.reshape(-1)+ translation = translation / (np.linalg.norm(translation) + 1e-15)+ translation_gt = translation_gt / (np.linalg.norm(translation_gt) + 1e-15)+ translation_cos = np.clip(abs(translation @ translation_gt), 0.0, 1.0)+ return float(np.degrees(max(np.arccos(rotation_cos), np.arccos(translation_cos))))+++def summarize(rows: list[dict[str, Any]]) -> list[dict[str, Any]]:+ """Average geometric accuracy equally over scenes and seeds; report mean per-pair median latency."""+ groups: dict[tuple, list[dict[str, Any]]] = defaultdict(list)+ for row in rows:+ groups[row["problem"], row["feature"], row["budget"]].append(row)+ result = []+ for (problem, feature, budget), group in sorted(groups.items()):+ cells: dict[tuple, list[float]] = defaultdict(list)+ for row in group:+ error = row["err"] if row["err"] is not None else float("inf")+ success = error <= MAA_THRESHOLDS_PX if problem == "H" else error < np.arange(1, 11)+ cells[row["scene"], row["seed"]].append(float(np.mean(success)))+ timings = [row["median_us"] for row in group if row["median_us"] is not None]+ result.append(+ {+ "problem": problem,+ "feature": feature,+ "budget": budget,+ "maa": float(np.mean([np.mean(values) for values in cells.values()])),+ "mean_median_us": float(np.mean(timings)) if timings else None,+ "quality_evaluations": len(group),+ "timed_pairs": len(timings),+ }+ )+ return result+++def run(args: argparse.Namespace) -> None:+ """Measure public estimator calls and persist all per-pair geometric errors and timing spreads."""+ expected = ROOT / "kornia" / "__init__.py"+ if Path(kornia.__file__).resolve() != expected:+ raise RuntimeError(f"Imported {kornia.__file__}; expected {expected}")+ print(f"# kornia: {kornia.__file__}\n# interpreter: {sys.executable}", flush=True)+ models = args.models.split(",")+ torch.set_num_threads(args.threads)+ if any(model in models for model in ("F", "E")):+ import cv2++ cv2.setNumThreads(args.threads)+ torch.manual_seed(0)+ warm_up_cpu()+ epipolar = load_epipolar(args) if any(model in models for model in ("F", "E")) else []+ homography = load_homography(args) if "H" in models else []+ thresholds = EPI_THRESHOLDS | dict(args.epi_threshold)+ for item in epipolar:+ if item["feature"] not in thresholds:+ raise ValueError(f"Specify --epi-threshold {item['feature']}=PX for this feature")+ meta = run_metadata(torch.device("cpu"))+ meta.update(+ kornia_module="kornia/__init__.py",+ harness_sha256=digest(Path(__file__)),+ ransac_source_sha256=digest(measured_ransac_source()),+ source_sha256={+ name: digest(ROOT / name)+ for name in (+ "kornia/geometry/ransac.py",+ "kornia/geometry/homography.py",+ "kornia/geometry/epipolar/fundamental.py",+ "kornia/geometry/epipolar/essential.py",+ )+ },+ units="pairs/s",+ dtype="float32",+ models=models,+ budgets=args.budgets,+ seeds=args.seeds,+ pairs_per_scene_feature=args.pairs,+ h_pairs=args.h_pairs,+ pair_seed=args.pair_seed,+ sort_matches=args.sort_matches,+ h_snn=0.8,+ h_threshold_px=args.h_threshold,+ epipolar_thresholds_px=thresholds,+ confidence=args.confidence,+ min_run_time=args.min_run_time,+ timing_seed=0,+ timing_storage="Seed-zero timing is stored on the first requested quality seed; other rows are null",+ timing_enabled=not args.no_timing,+ timing_includes="Repeated public RANSAC.forward on preloaded float32 CPU inputs; seed zero; median and IQR",+ quality="All requested seeds; geometric errors; mAA averaged equally over scenes and seeds per feature",+ h_maa_thresholds_px=MAA_THRESHOLDS_PX.tolist(),+ pose_maa_thresholds_degrees=list(range(1, 11)),+ npz_sha256=digest(args.npz) if epipolar else None,+ heb_file=args.heb.name if homography else None,+ )+ # Identify the selected HEB content without hashing a multi-gigabyte scene or recording local paths.+ hasher = hashlib.sha256()+ for item in homography:+ hasher.update(item["pair"].encode())+ for field in ("a", "b", "gt_a", "gt_b"):+ hasher.update(np.ascontiguousarray(item[field]).tobytes())+ meta["heb_selected_sha256"] = hasher.hexdigest() if homography else None+ rows: list[dict[str, Any]] = []+ with torch.inference_mode():+ for problem in models:+ items = homography if problem == "H" else epipolar+ if not items:+ raise ValueError(f"No pairs selected for {problem}")+ for index, item in enumerate(items):+ calibration = None+ points = item["a"], item["b"]+ threshold = args.h_threshold if problem == "H" else thresholds[item["feature"]]+ if problem == "E":+ calibration = PairCalibration(*(entry["K"] for entry in item["calib"]))+ points = calibration.normalized(*points)+ kp1, kp2 = (torch.as_tensor(point, dtype=torch.float32) for point in points)+ for budget in args.budgets:+ estimator = RANSAC(+ MODEL_TYPES[problem],+ inl_th=threshold / calibration.focal if calibration is not None else threshold,+ max_samples=budget,+ confidence=args.confidence,+ seed=0,+ )+ minimum = {"H": 4, "F": 7, "E": 5}[problem]+ enough = len(kp1) >= minimum+ median = iqr = None+ if enough and not args.no_timing:+ median, iqr = time_us(partial(estimator, kp1, kp2), min_run_time=args.min_run_time)+ for seed_index, seed in enumerate(args.seeds):+ estimator.seed = seed+ error, support = float("inf"), 0+ if enough:+ matrix, mask = estimator(kp1, kp2)+ matrix = matrix.double().numpy()+ inliers = mask.numpy().reshape(-1).astype(bool)+ support = int(inliers.sum())+ usable = np.isfinite(matrix).all() and np.any(matrix != 0)+ if usable and problem == "H" and support >= 4 and len(item["gt_a"]) > 1:+ error = reprojection_error(item["gt_a"], item["gt_b"], matrix)+ elif usable and problem != "H":+ fundamental = calibration.fundamental(matrix) if calibration is not None else matrix+ error = pose_error(fundamental, item["a"][inliers], item["b"][inliers], *item["calib"])+ rows.append(+ {+ "op": "RANSAC",+ "backend": "kornia (eager)",+ "batch": 1,+ "problem": problem,+ "feature": item["feature"],+ "scene": item["scene"],+ "pair": item["pair"],+ "n": len(kp1),+ "budget": budget,+ "seed": seed,+ "threshold_px": threshold,+ "err": error,+ "error_units": "pixels" if problem == "H" else "degrees",+ "support": support,+ "timing_seed": 0,+ "median_us": median if seed_index == 0 else None,+ "iqr_us": iqr if seed_index == 0 else None,+ "throughput_per_s": 1e6 / median if seed_index == 0 and median else None,+ }+ )+ print(f"# {problem} {index + 1}/{len(items)} {item['pair']}", flush=True)+ # Preserve partial results if a long run is interrupted.+ save_json(args.json, meta, rows)+ summaries = summarize(rows)+ meta["summaries"] = summaries+ save_json(args.json, meta, rows)+ for summary in summaries:+ latency = summary["mean_median_us"]+ time_text = f"{latency / 1000:.3f} ms" if latency is not None else "untimed"+ print(+ f"{summary['problem']} {summary['feature']} budget={summary['budget']}: "+ f"mAA={summary['maa']:.4f}, {time_text}",+ flush=True,+ )+++def threshold_override(value: str) -> tuple[str, float]:+ """Parse FEATURE=PX and reject nonpositive or nonfinite thresholds."""+ try:+ feature, raw = value.split("=", 1)+ threshold = float(raw)+ if not feature or not np.isfinite(threshold) or threshold <= 0:+ raise ValueError+ return feature, threshold+ except ValueError as exc:+ raise argparse.ArgumentTypeError("expected FEATURE=PX with a positive finite threshold") from exc+++def main() -> None:+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)+ parser.add_argument("--npz", type=Path, help="PhotoTourism export from ransac.py prepare; required for F/E")+ parser.add_argument("--heb", type=Path, help="HEB scene HDF5; required for H")+ parser.add_argument("--models", default="H,F,E")+ parser.add_argument(+ "--pairs", type=int, default=2, help="PhotoTourism pairs per scene/feature; 10 uses the 7x10 export"+ )+ parser.add_argument("--h-pairs", type=int, default=30)+ parser.add_argument("--pair-seed", type=int, default=0, help="HEB selection seed")+ parser.add_argument("--scenes", default="", help="Optional comma-separated PhotoTourism scene filter")+ parser.add_argument("--features", default="", help="Optional comma-separated PhotoTourism feature filter")+ parser.add_argument("--sort-matches", action="store_true", help="Sort PhotoTourism score/ratio ascending")+ parser.add_argument("--budgets", default="256,4096")+ parser.add_argument("--seeds", default="0,1,2")+ parser.add_argument("--threads", type=int, default=4)+ parser.add_argument("--confidence", type=float, default=0.999)+ parser.add_argument("--h-threshold", type=float, default=8.0)+ parser.add_argument("--epi-threshold", type=threshold_override, action="append", default=[], metavar="FEATURE=PX")+ parser.add_argument(+ "--min-run-time", type=float, default=0.1, help="Minimum repeated timing duration per pair/budget"+ )+ parser.add_argument("--no-timing", action="store_true", help="Evaluate geometric quality only")+ parser.add_argument("--json", type=Path, required=True)+ args = parser.parse_args()+ if not args.models or any(model not in MODEL_TYPES for model in args.models.split(",")):+ parser.error("--models must be a comma-separated selection of H,F,E")+ if "H" in args.models and args.heb is None:+ parser.error("--heb is required when --models includes H")+ if any(model in args.models for model in ("F", "E")) and args.npz is None:+ parser.error("--npz is required when --models includes F or E")+ try:+ args.budgets = list(dict.fromkeys(int(value) for value in args.budgets.split(",")))+ args.seeds = list(dict.fromkeys(int(value) for value in args.seeds.split(",")))+ except ValueError:+ parser.error("--budgets and --seeds must be comma-separated integers")+ if min(args.budgets) < 1 or min(args.seeds) < 0:+ parser.error("budgets must be positive and seeds nonnegative")+ if min(args.pairs, args.h_pairs, args.threads) < 1:+ parser.error("pair counts and threads must be positive")+ if not np.isfinite(args.min_run_time) or args.min_run_time <= 0:+ parser.error("--min-run-time must be positive and finite")+ if not np.isfinite(args.h_threshold) or args.h_threshold <= 0:+ parser.error("--h-threshold must be positive and finite")+ if not 0 < args.confidence < 1:+ parser.error("--confidence must lie strictly between zero and one")+ run(args)+++if __name__ == "__main__":+ main()diff --git a/changelog.d/5095.fixed.md b/changelog.d/5095.fixed.mdnew file mode 100644index 000000000..9da0a227a--- /dev/null+++ b/changelog.d/5095.fixed.md@@ -0,0 +1 @@+Speed up `RANSAC` with `local_optimization="lm"`, the default for homographies, fundamental and essential matrices. Hypothesis verification allocates fewer temporaries and, on CPU, is tiled at about a million residuals. The Levenberg–Marquardt stages, which run on the host for every input device, evaluate only the cost of their last trial instead of building an unused Jacobian, and the final refinement drops correspondences outside its inlier mask before building its equations. Five-point essential estimation evaluates its Newton correction with bounded cumulative products instead of general powers. Returned models can differ slightly, since rounding differences can change which refinement steps are accepted.diff --git a/kornia/geometry/epipolar/essential.py b/kornia/geometry/epipolar/essential.pyindex adef49bc7..5ee771974 100644--- a/kornia/geometry/epipolar/essential.py+++ b/kornia/geometry/epipolar/essential.py@@ -27,7 +27,7 @@ from kornia.core.utils import _torch_svd_castfrom kornia.geometry.solvers.homogeneous import _null_space_householderfrom kornia.geometry.solvers.polynomial_solver import T_deg1, T_deg2-from .fundamental import _epipolar_design_rows, _hat_basis, _sampson_normal_equations, _solve_dtype+from .fundamental import _epipolar_design_rows, _hat_basis, _sampson_cost, _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@@ -299,6 +299,20 @@ _LINEAR_PRODUCTS = T_deg1.view(4, 4, 10)_CUBIC_PRODUCTS = T_deg2.view(10, 4, 20)+def _scaled_polynomial_powers(roots: torch.Tensor) -> torch.Tensor:+ """Return ``z**d / max(1, abs(z))**10`` for ``d = 0, ..., 10`` without large powers.++ For ``abs(z) > 1`` these are the powers of ``1/z`` in reverse order (the degree ten is even).+ Every multiplication therefore has magnitude at most one. Cumulative products avoid the two general+ tensor exponentiations in the Newton correction, which dominate its CPU cost.+ """+ large = roots.abs() > 1.0+ bounded = torch.where(large, torch.where(large, roots, 1.0).reciprocal(), roots)+ powers = bounded[..., None].expand(*bounded.shape, 10).cumprod(-1)+ powers = torch.cat((torch.ones_like(bounded[..., None]), powers), -1)+ return torch.where(large[..., None], powers.flip(-1), powers)++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).@@ -380,8 +394,7 @@ def _nister_candidates(basis: torch.Tensor, out_dtype: torch.dtype) -> Tuple[tor# 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)+ powers = _scaled_polynomial_powers(root0) # (B, 10, 11); root0 carries no gradientvalue = (powers * cs[:, None]).sum(-1)slope_terms = powers[..., :10] * (degrees[1:] * cs[:, 1:])[:, None]slope = slope_terms.sum(-1)@@ -880,6 +893,9 @@ def _refine_essential_lm("""K = E.shape[0]dtype, device = E.dtype, E.device+ cpu = K > 0 and device.type == "cpu" and not torch.is_grad_enabled()+ if cpu and K == 1 and mask is not None and mask.dtype == torch.bool:+ x1, x2, mask = x1[mask[0]], x2[mask[0]], NoneH = _hat_basis(dtype, device)eye3 = torch.eye(3, dtype=dtype, device=device)eye5 = torch.eye(5, dtype=dtype, device=device)@@ -909,11 +925,15 @@ def _refine_essential_lm(E = compose(U, V)system, cost = normal_equations(E, V)- for _ in range(iters):+ for iteration in range(iters):delta = -torch.linalg.solve_ex(system[..., :5] + damping * eye5, system[..., 5:])[0][..., 0]U_new = cayley(0.5 * delta[:, :3]) @ UV_new = cayley(0.5 * (V[..., :2] @ delta[:, 3:, None])[..., 0]) @ VE_new = compose(U_new, V_new)+ if cpu and iteration + 1 == iters:+ cost_new = _sampson_cost(E_new, algebraic, quadratic, mask, loss, scale2)+ accepted = cost_new < cost+ return torch.where(accepted[:, None, None], E_new, E)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)diff --git a/kornia/geometry/epipolar/fundamental.py b/kornia/geometry/epipolar/fundamental.pyindex ccd5b1989..5ee57e6be 100644--- a/kornia/geometry/epipolar/fundamental.py+++ b/kornia/geometry/epipolar/fundamental.py@@ -321,11 +321,35 @@ def _robust_loss(r2: torch.Tensor, loss: str, scale2: float) -> Tuple[torch.Tensdef _hat_basis(dtype: torch.dtype, device: torch.device) -> torch.Tensor:"""``E[a] = [e_a]_x``, the generators of rotations, as ``(3, 3, 3)``."""- E = torch.zeros(3, 3, 3, dtype=dtype, device=device)- E[0, 1, 2], E[0, 2, 1] = -1.0, 1.0- E[1, 0, 2], E[1, 2, 0] = 1.0, -1.0- E[2, 0, 1], E[2, 1, 0] = -1.0, 1.0- return E+ return torch.tensor(+ [+ [[0.0, 0.0, 0.0], [0.0, 0.0, -1.0], [0.0, 1.0, 0.0]],+ [[0.0, 0.0, 1.0], [0.0, 0.0, 0.0], [-1.0, 0.0, 0.0]],+ [[0.0, -1.0, 0.0], [1.0, 0.0, 0.0], [0.0, 0.0, 0.0]],+ ],+ dtype=dtype,+ device=device,+ )+++def _sampson_cost(+ F: torch.Tensor,+ algebraic: torch.Tensor,+ quadratic: torch.Tensor,+ mask: Optional[torch.Tensor],+ loss: str,+ scale2: float,+) -> torch.Tensor:+ """Robust Sampson costs without constructing trial Jacobians or normal equations."""+ quad1 = F[:, :2, :].mT @ F[:, :2, :]+ quad2 = F[:, :, :2] @ F[:, :, :2].mT+ numerator = F.flatten(1) @ algebraic+ denominator = torch.cat([quad1, quad2], 1).flatten(1) @ quadratic+ r2 = (numerator * denominator.rsqrt()).square()+ rho = torch.log1p(r2 / scale2) if loss == "cauchy" else torch.fmin(r2, torch.full_like(r2[:1, :1], scale2))+ if mask is not None:+ rho = rho * mask+ return rho.sum(1)def _sampson_normal_equations(@@ -377,10 +401,16 @@ def _refine_fundamental_lm(iteration takes the residuals and their Jacobian from two matrix products with per-correspondence monomials.``x1`` and ``x2`` are homogeneous ``(N, 3)`` points, normalized by the caller. ``loss`` is ``"truncated"`` or``"cauchy"`` with squared scale ``scale2``; ``mask`` (``(K, N)``) restricts each model to its correspondences. A- step is kept only if it lowers the cost. For RANSAC, under ``torch.no_grad``.+ step is kept only if it lowers the cost. For RANSAC, under ``torch.no_grad``. On CPU with gradients disabled, a+ singleton boolean mask compacts its correspondences, and the last trial evaluates only the cost: its Jacobian and+ updated optimizer state would not be used. Earlier iterations keep fused residual and Jacobian evaluation for small+ model batches."""K = F.shape[0]dtype, device = F.dtype, F.device+ cpu = K > 0 and device.type == "cpu" and not torch.is_grad_enabled()+ if cpu and K == 1 and mask is not None and mask.dtype == torch.bool:+ x1, x2, mask = x1[mask[0]], x2[mask[0]], NoneE = _hat_basis(dtype, device)eye3 = torch.eye(3, dtype=dtype, device=device)eye7 = torch.eye(7, dtype=dtype, device=device)@@ -408,7 +438,7 @@ def _refine_fundamental_lm(F = compose(UV, sigma)system, cost = normal_equations(F, UV)- for _ in range(iters):+ for iteration in range(iters):delta = -torch.linalg.solve_ex(system[..., :7] + damping * eye7, system[..., 7:])[0][..., 0]half = delta[:, :6].reshape(K * 2, 3) * 0.5skew = (half @ E.reshape(3, 9)).reshape(K, 2, 3, 3)@@ -416,6 +446,10 @@ def _refine_fundamental_lm(UV_new = (eye3 + factor * (skew + skew @ skew)) @ UV # Cayley transform of the half-angle skew matrixsigma_new = sigma + delta[:, 6]F_new = compose(UV_new, sigma_new)+ if cpu and iteration + 1 == iters:+ cost_new = _sampson_cost(F_new, algebraic, quadratic, mask, loss, scale2)+ accepted = cost_new < cost+ return torch.where(accepted[:, None, None], F_new, F)system_new, cost_new = normal_equations(F_new, UV_new)accept = (cost_new < cost)[:, None, None]UV = torch.where(accept[..., None], UV_new, UV)diff --git a/kornia/geometry/homography.py b/kornia/geometry/homography.pyindex 8d8b8ccc2..d626749e0 100644--- a/kornia/geometry/homography.py+++ b/kornia/geometry/homography.py@@ -348,6 +348,9 @@ def _refine_homography_lm("""K = H.shape[0]dtype, device = H.dtype, H.device+ cpu = K > 0 and device.type == "cpu" and not torch.is_grad_enabled()+ if cpu and K == 1 and mask is not None and mask.dtype == torch.bool:+ x1, x2, mask = x1[mask[0]], x2[mask[0]], Noneeye8 = torch.eye(8, dtype=dtype, device=device)eye9 = torch.eye(9, dtype=dtype, device=device)last = eye9[8]@@ -375,10 +378,18 @@ def _refine_homography_lm(return torch.cat([Jw @ J.mT, Jw @ r[..., None]], 2), rho.sum(1), tangentsystem, cost, tangent = normal_equations(h)- for _ in range(iters):+ for iteration in range(iters):delta = -torch.linalg.solve_ex(system[..., :8] + damping * eye8, system[..., 8:])[0]h_new = h + (tangent @ delta)[..., 0]h_new = h_new * h_new.square().sum(1, keepdim=True).rsqrt()+ if cpu and iteration + 1 == iters:+ projection = h_new.reshape(K, 3, 3) @ x1.T+ residual = projection[:, :2] / projection[:, 2:3] - x2.T+ r2 = residual.square().sum(1)+ rho = torch.log1p(r2 / scale2) if loss == "cauchy" else torch.fmin(r2, torch.full_like(r2[:1, :1], scale2))+ cost_new = (rho if mask is None else rho * mask).sum(1)+ accepted = cost_new < cost+ return torch.where(accepted[:, None], h_new, h).reshape(K, 3, 3)system_new, cost_new, tangent_new = normal_equations(h_new)accept = (cost_new < cost)[:, None, None]h, cost = torch.where(accept[:, :, 0], h_new, h), torch.where(accept[:, 0, 0], cost_new, cost)diff --git a/kornia/geometry/ransac.py b/kornia/geometry/ransac.pyindex 922e5cf83..e2041ac69 100644--- a/kornia/geometry/ransac.py+++ b/kornia/geometry/ransac.py@@ -426,9 +426,9 @@ class RANSAC(nn.Module):up to 1024, and at 256 on CUDA and MPS, up to 8192: a five-point sample needs few draws at high inlierratios, and its host eigenvalue solve costs the same on every device. All shrink, down to 64 samples, when abatch 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.+ of a seven-point sample and the ten candidate slots of a five-point one. On accelerators scoring holds two or+ three times that many entries at its peak, about 0.5 GiB in float32; on CPU it scores tiles of about a million+ residuals, independently of the batch. An integer ``batch_size`` is kept for every batch."""if isinstance(self.batch_size, int):return self.batch_size@@ -928,9 +928,40 @@ class RANSAC(nn.Module):"""MSAC scores ``sum(1 - min(e / threshold, 1))`` or RANSAC support counts ``(M,)`` of squared residuals."""if self.score_type == "msac":# fmin, unlike clamp, takes the threshold for NaN residuals: a NaN residual is an outlier.- return (1.0 - torch.fmin(errors, torch.full_like(errors[:1, :1], threshold)) / threshold).sum(1)+ # The clipped residuals own their storage: reuse it for the pointwise score operations.+ contributions = torch.fmin(errors, torch.full_like(errors[:1, :1], threshold))+ return contributions.div_(-threshold).add_(1.0).sum(1)return (errors <= threshold).sum(1).to(errors.dtype)+ def _lm_score_models(+ self, models: torch.Tensor, basis: torch.Tensor, threshold: float, max_residuals: int = 1 << 20+ ) -> Tuple[torch.Tensor, torch.Tensor, Optional[torch.Tensor]]:+ """Score minimal models without retaining the whole model-by-correspondence residual matrix.++ CPU hypothesis tiles bound temporary storage independently of the solver batch. Correspondences are never+ split, so each score uses the same reduction as full verification. Accelerators keep one tile to amortize+ launch overhead. Support counts accumulate in the working dtype while they are exactly representable,+ avoiding the default int64 conversion of every entry of the inlier matrix. Only PROSAC retains the boolean+ masks: its stopping rule must use the same inlier decisions as the score, including at rounding boundaries.+ """+ planar = self.model_type == "homography"+ n = basis.shape[1] // (3 if planar else 2)+ tile = max(1, max_residuals // max(n, 1)) if models.device.type == "cpu" else max(len(models), 1)+ scores, counts, masks = [], [], []+ count_dtype = models.dtype if n <= 1 << 24 else torch.int64+ residual_fn = _transfer_from_basis if planar else _sampson_from_quadratic_basis+ for start in range(0, len(models), tile):+ errors = residual_fn(models[start : start + tile], basis)+ inliers = errors <= threshold+ support = inliers.sum(1, dtype=count_dtype)+ counts.append(support)+ scores.append(self._lm_score(errors, threshold) if self.score_type == "msac" else support.to(models.dtype))+ if self.prosac_sampling:+ masks.append(inliers)+ if len(scores) == 1:+ return scores[0], counts[0], masks[0] if masks else None+ return torch.cat(scores), torch.cat(counts), torch.cat(masks) if masks else None+def _lm_refine(self,models: torch.Tensor,@@ -1002,13 +1033,11 @@ class RANSAC(nn.Module):models = self._lm_minimal_models(x1[indices], x2[indices])if len(models) == 0:continue- errors = _transfer_from_basis(models, basis) if planar else _sampson_from_quadratic_basis(models, basis)# Reject insufficient support before ranking: high MSAC scores from minimal samples alone must not# crowd supported models out of the candidate pool.- counts_all = (errors <= threshold).sum(1)- scores_all = self._lm_score(errors, threshold).masked_fill(counts_all <= m, -1.0)+ scores_all, counts_all, masks_all = self._lm_score_models(models, basis, threshold)+ scores_all = scores_all.masked_fill(counts_all <= m, -1.0)top_scores, top = scores_all.topk(min(_LM_CANDIDATES, len(models)))- top_inliers = errors[top] <= thresholdtop_counts = counts_all[top]# The run's best minimal models so far, refined after sampling.candidate_scores, order = torch.cat([top_scores, candidate_scores]).topk(@@ -1020,8 +1049,8 @@ class RANSAC(nn.Module):if scores[best] > best_score:# The bound follows the new incumbent's own support, as with local_optimization="dlt".best_score = scores[best]- if self.prosac_sampling:- max_samples = self._prosac_max_samples(top_inliers[best], int(counts[best]))+ if masks_all is not None:+ max_samples = self._prosac_max_samples(masks_all[top[best]], int(counts[best]))else:support = int(counts[best])max_samples = min(budget, self.max_samples_by_conf(support, num_tc, m, self.confidence))@@ -1042,7 +1071,7 @@ class RANSAC(nn.Module):model, inliers = candidates[best], inliers[best]if self.refine_iters > 0:# A Cauchy scale of a third of the threshold: the threshold as three standard deviations of the noise.- mask = inliers.to(torch.float64)[None]+ mask = inliers[None]refined = self._lm_refine(model[None], x1_host, x2_host, mask, "cauchy", threshold / 9, self.refine_iters)refined_inliers = self._lm_errors(refined, x1_host, x2_host)[0] <= thresholdif self._is_supported(int(refined_inliers.sum())):diff --git a/tests/geometry/epipolar/test_essential.py b/tests/geometry/epipolar/test_essential.pyindex 8216613bf..6060c9bf8 100644--- a/tests/geometry/epipolar/test_essential.py+++ b/tests/geometry/epipolar/test_essential.py@@ -42,6 +42,31 @@ def test_generate_two_view_random_scene_is_deterministic():assert torch.equal(actual_next, expected_next)+class TestScaledPolynomialPowers(BaseTester):+ def test_values(self, device, dtype):+ # The five-point Newton correction evaluates z**d / max(1, abs(z))**10.+ # Both signs, z=0, and the boundary |z|=1 must retain all eleven coefficients.+ values = [-2.0, -1.0, -0.5, 0.0, 0.5, 1.0, 2.0]+ roots = torch.tensor([values], device=device, dtype=dtype)+ # Integer powers of these binary fractions are exact; CUDA's general tensor pow can round them.+ expected = torch.tensor(+ [[[z**d / max(1.0, abs(z)) ** 10 for d in range(11)] for z in values]], device=device, dtype=dtype+ )+ actual = epi.essential._scaled_polynomial_powers(roots)+ self.assert_close(actual, expected, atol=0.0, rtol=0.0)++ def test_large_roots_remain_finite(self, device, dtype):+ # Direct z**10 would overflow. The highest two powers still have values 1 and 1/z,+ # including the sign of the derivative term at a negative root.+ large = torch.finfo(dtype).max ** 0.2 / 2+ roots = torch.tensor([[-large, large]], device=device, dtype=dtype)+ actual = epi.essential._scaled_polynomial_powers(roots)+ assert torch.isfinite(actual).all()+ assert bool((actual.abs() <= 1).all())+ self.assert_close(actual[..., -1], torch.ones_like(roots), atol=0.0, rtol=0.0)+ self.assert_close(actual[..., -2], roots.reciprocal(), atol=0.0, rtol=0.0)++class TestFindEssential(BaseTester):def test_smoke(self, device, dtype):points1 = torch.rand(1, 5, 2, device=device, dtype=dtype)diff --git a/tests/geometry/test_ransac.py b/tests/geometry/test_ransac.pyindex e2f6fa40e..1a47671c9 100644--- a/tests/geometry/test_ransac.py+++ b/tests/geometry/test_ransac.py@@ -1958,10 +1958,11 @@ class TestRANSACEssentialLevenbergMarquardt(BaseTester):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):+ @pytest.mark.parametrize("seed", [0, 1, 2])+ def test_planar_scene(self, device, dtype, seed):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.+ # A calibrated plane admits multiple essential matrices with the same epipolar fit. Check the recovered+ # consensus and essential manifold, not equality to one generating motion (which depends on sampled ties).generator = torch.Generator().manual_seed(12)f64 = torch.float64XY = (torch.rand(120, 2, generator=generator, dtype=f64) - 0.5) * 4@@ -1971,13 +1972,15 @@ class TestRANSACEssentialLevenbergMarquardt(BaseTester):Y = X @ R.T + tkp1, 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))+ E, mask = RANSAC("essential", inl_th=1e-4, seed=seed)(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+ tolerance = 1e-9 if dtype == torch.float64 else 1e-6+ self.assert_close(+ torch.linalg.svdvals(E), E.new_tensor([0.5**0.5, 0.5**0.5, 0.0]), atol=tolerance, rtol=tolerance+ )+ error = sampson_epipolar_distance(kp1[None, 30:], kp2[None, 30:], E[None], eps=0.0)+ assert error.max() < (1e-16 if dtype == torch.float64 else 1e-10)def test_batch_of_one_sample(self, device, dtype):self._skip_half(dtype)@@ -2056,3 +2059,48 @@ class TestRANSACLevenbergMarquardtKernels(BaseTester):if model_type != "homography":neighbours = _rank2_projection(neighbours)assert (cost(neighbours) >= cost(refined) * (1 - 1e-9)).all()+++class TestRANSACScoring(BaseTester):+ @pytest.mark.parametrize("model_type", ["homography", "fundamental", "essential"])+ @pytest.mark.parametrize("score_type", ["ransac", "msac"])+ @pytest.mark.parametrize("prosac", [False, True])+ def test_score_and_support_match_full_residuals(self, device, dtype, model_type, score_type, prosac):+ from kornia.geometry.epipolar._metrics import _sampson_from_quadratic_basis, _sampson_quadratic_basis+ from kornia.geometry.homography import _transfer_basis, _transfer_from_basis++ if dtype in (torch.float16, torch.bfloat16):+ pytest.skip("RANSAC scoring uses at least float32")+ generator = torch.Generator().manual_seed(10)+ x1 = torch.rand(137, 3, generator=generator).to(device, dtype)+ x2 = torch.rand(137, 3, generator=generator).to(device, dtype)+ x1[:, 2] = x2[:, 2] = 1+ x1[0] = float("nan")+ models = torch.rand(29, 3, 3, generator=generator).to(device, dtype)+ models[0] = float("nan")+ planar = model_type == "homography"+ basis = _transfer_basis(x1, x2[:, :2]) if planar else _sampson_quadratic_basis(x1, x2)+ residual_fn = _transfer_from_basis if planar else _sampson_from_quadratic_basis+ errors = residual_fn(models, basis)+ threshold = 0.1+ ransac = RANSAC(model_type, score_type=score_type, prosac_sampling=prosac)+ expected_support = (errors <= threshold).sum(1)+ expected_scores = ransac._lm_score(errors, threshold)+ # Force several tiles, including a tail of one model, without allocating huge fixtures.+ scores, support, masks = ransac._lm_score_models(models, basis, threshold, max_residuals=137 * 7)+ self.assert_close(scores, expected_scores)+ self.assert_close(support, expected_support.to(support.dtype), rtol=0, atol=0)+ assert scores[0] == 0 and support[0] == 0+ if prosac:+ assert masks is not None+ self.assert_close(support, masks.sum(1).to(support.dtype), rtol=0, atol=0)+ else:+ assert masks is None++ def test_msac_does_not_mutate_residuals(self, device, dtype):+ errors = torch.tensor([[0.0, 0.25, 1.0, 2.0, float("nan"), float("inf")]], device=device, dtype=dtype)+ original = errors.clone()+ score = RANSAC()._lm_score(errors, 1.0)+ self.assert_close(score, errors.new_tensor([1.75]))+ assert torch.equal(errors.isnan(), original.isnan())+ self.assert_close(errors.nan_to_num(), original.nan_to_num(), rtol=0, atol=0)diff --git a/tests/geometry/test_ransac_refinement.py b/tests/geometry/test_ransac_refinement.pynew file mode 100644index 000000000..5843b0d00--- /dev/null+++ b/tests/geometry/test_ransac_refinement.py@@ -0,0 +1,155 @@+# LICENSE HEADER MANAGED BY add-license-header+#+# Copyright 2018 Kornia Team+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+#++import pytest+import torch++from kornia.geometry.epipolar.essential import _refine_essential_lm+from kornia.geometry.epipolar.fundamental import _refine_fundamental_lm+from kornia.geometry.homography import _refine_homography_lm++from testing.base import BaseTester+++class TestRANSACRefinementCPU(BaseTester):+ def scene(self, device, dtype, model):+ if device.type != "cpu" or dtype in (torch.float16, torch.bfloat16):+ pytest.skip("CPU LM fast path uses float32 or float64")+ generator = torch.Generator(device=device).manual_seed(42)+ x1 = torch.randn(60, 3, generator=generator, device=device, dtype=dtype)+ x1[:, 2] = 1.0+ if model == "homography":+ matrix = torch.eye(3, device=device, dtype=dtype)+ x2 = x1[:, :2].clone()+ refine = _refine_homography_lm+ else:+ matrix = x1.new_tensor([[0.0, -0.3, -0.2], [0.3, 0.0, -1.0], [0.2, 1.0, 0.0]])+ depth = torch.rand(60, 1, generator=generator, device=device, dtype=dtype) + 2.0+ x2 = x1 * depth + x1.new_tensor([1.0, -0.2, 0.3])+ x2 = x2 / x2[:, 2:]+ refine = _refine_fundamental_lm if model == "fundamental" else _refine_essential_lm+ matrix = matrix + 0.01 * torch.randn(3, 3, generator=generator, device=device, dtype=dtype)+ x2[:, :2] += 0.001 * torch.randn(60, 2, generator=generator, device=device, dtype=dtype)+ return refine, matrix[None], x1, x2++ @pytest.mark.parametrize("model", ["homography", "fundamental", "essential"])+ @pytest.mark.parametrize("loss", ["truncated", "cauchy"])+ def test_mask_excludes_nonfinite_points(self, device, dtype, model, loss):+ refine, matrix, x1, x2 = self.scene(device, dtype, model)+ mask = torch.arange(len(x1), device=device) % 3 != 0+ with torch.no_grad():+ expected = refine(matrix, x1[mask], x2[mask], None, loss, 0.01, 3)+ x1[~mask] = float("nan")+ actual = refine(matrix, x1, x2, mask[None], loss, 0.01, 3)+ self.assert_close(actual, expected, atol=2e-6, rtol=2e-5)++ @pytest.mark.parametrize("model", ["homography", "fundamental", "essential"])+ @pytest.mark.parametrize("loss", ["truncated", "cauchy"])+ @pytest.mark.parametrize("iterations", [1, 3, 20])+ def test_matches_differentiable_refinement(self, device, dtype, model, loss, iterations):+ refine, matrix, x1, x2 = self.scene(device, dtype, model)+ # Sixteen starts, perturbed from the scene's model with per-entry deviations from 0.01 to 1. From the far ones+ # some last trials raise the cost and the reference rejects them, so a shortcut that accepted its last trial+ # unconditionally fails here for the fundamental and essential matrices. The homography steps rejected here+ # are too small to tell apart from rounding.+ generator = torch.Generator(device=device).manual_seed(0)+ scales = torch.logspace(-2, 0, 16, device=device, dtype=dtype)[:, None, None]+ models = matrix + scales * torch.randn(16, 3, 3, generator=generator, device=device, dtype=dtype)+ # The differentiable path retains the fully vectorized implementation as a reference.+ with torch.enable_grad():+ expected = refine(models, x1, x2, None, loss, 0.01, iterations)+ with torch.no_grad():+ actual = refine(models, x1, x2, None, loss, 0.01, iterations)+ tolerance = 5e-4 if dtype == torch.float32 else 2e-6+ self.assert_close(actual, expected, atol=tolerance, rtol=tolerance)++ @pytest.mark.parametrize("loss", ["truncated", "cauchy"])+ def test_sampson_trial_cost_matches_normal_equations(self, device, dtype, loss):+ from kornia.geometry.epipolar import fundamental++ _, matrix, x1, x2 = self.scene(device, dtype, "fundamental")+ algebraic = fundamental._epipolar_design_rows(x1, x2).T+ quadratic = torch.cat(+ [fundamental._epipolar_design_rows(x1, x1), fundamental._epipolar_design_rows(x2, x2)], 1+ ).T+ tangent = matrix[:, None].expand(-1, 7, -1, -1)+ for mask in (None, (torch.arange(len(x1), device=device) % 3 != 0)[None]):+ _, expected = fundamental._sampson_normal_equations(matrix, tangent, algebraic, quadratic, mask, loss, 0.01)+ actual = fundamental._sampson_cost(matrix, algebraic, quadratic, mask, loss, 0.01)+ self.assert_close(actual, expected)++ @pytest.mark.parametrize("model", ["homography", "fundamental", "essential"])+ def test_batched_weighted_mask(self, device, dtype, model):+ refine, matrix, x1, x2 = self.scene(device, dtype, model)+ models = matrix.repeat(3, 1, 1)+ models[1] += 0.1+ weights = x1.new_ones(3, len(x1))+ weights[0, :20], weights[1, 20:40], weights[2, 40:] = 0.0, 0.5, 0.0+ with torch.enable_grad():+ expected = refine(models, x1, x2, weights, "cauchy", 0.01, 5)+ with torch.no_grad():+ actual = refine(models, x1, x2, weights, "cauchy", 0.01, 5)+ tolerance = 5e-4 if dtype == torch.float32 else 2e-6+ self.assert_close(actual, expected, atol=tolerance, rtol=tolerance)++ @pytest.mark.parametrize("model", ["homography", "fundamental", "essential"])+ def test_empty_mask(self, device, dtype, model):+ refine, matrix, x1, x2 = self.scene(device, dtype, model)+ mask = torch.zeros(1, len(x1), device=device, dtype=torch.bool)+ with torch.enable_grad():+ expected = refine(matrix, x1, x2, mask, "cauchy", 0.01, 3)+ with torch.no_grad():+ actual = refine(matrix, x1, x2, mask, "cauchy", 0.01, 3)+ self.assert_close(actual, expected)++ @pytest.mark.parametrize("model", ["homography", "fundamental", "essential"])+ def test_differentiable_path(self, device, dtype, model):+ refine, matrix, x1, x2 = self.scene(device, dtype, model)+ matrix.requires_grad_()+ x1.requires_grad_()+ x2.requires_grad_()+ result = refine(matrix, x1, x2, None, "cauchy", 0.01, 3)+ gradients = torch.autograd.grad(result.square().sum(), (matrix, x1, x2))+ assert all(torch.isfinite(gradient).all() for gradient in gradients)++ @pytest.mark.parametrize("model", ["homography", "fundamental", "essential"])+ def test_keeps_input_tensors(self, device, dtype, model):+ refine, matrix, x1, x2 = self.scene(device, dtype, model)+ inputs = (matrix, x1, x2)+ copies = tuple(value.clone() for value in inputs)+ with torch.no_grad():+ refine(matrix, x1, x2, None, "cauchy", 0.01, 3)+ for value, copy in zip(inputs, copies):+ self.assert_close(value, copy, atol=0.0, rtol=0.0)++ @pytest.mark.parametrize("model", ["fundamental", "essential"])+ def test_partial_acceptance_keeps_zero_weight_model(self, device, dtype, model):+ refine, matrix, x1, x2 = self.scene(device, dtype, model)+ models = matrix.repeat(2, 1, 1)+ weights = x1.new_ones(2, len(x1))+ weights[0] = 0.0+ with torch.enable_grad():+ initial = refine(models, x1, x2, weights, "cauchy", 0.01, 0)+ expected = refine(models, x1, x2, weights, "cauchy", 0.01, 5)+ with torch.no_grad():+ actual = refine(models, x1, x2, weights, "cauchy", 0.01, 5)+ # The zero-weight row cannot lower its zero cost. The other row must take at least one accepted step,+ # exercising a mixture of accepted and rejected models without observing the refiner's internals.+ self.assert_close(actual[0], initial[0], atol=0.0, rtol=0.0)+ assert (actual[1] - initial[1]).norm() > 1e-3+ tolerance = 5e-4 if dtype == torch.float32 else 2e-6+ self.assert_close(actual, expected, atol=tolerance, rtol=tolerance)