π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
RANSAC: batched CUDA solvers, PROSAC termination, auto batch, Gaussian IRLS polish (#4979)
Dmytro Mishkinb824673f66e9
diff --git a/benchmarks/README.md b/benchmarks/README.mdindex d89387128..ffc739eb4 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. |+| [`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. || [`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`). |diff --git a/benchmarks/geometry/heb.py b/benchmarks/geometry/heb.pynew file mode 100644index 000000000..1256612e2--- /dev/null+++ b/benchmarks/geometry/heb.py@@ -0,0 +1,337 @@+# 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.+#++"""Homography RANSAC time versus accuracy on a scene of the Homography Estimation Benchmark (HEB).++HEB (Barath et al., "Large-scale homography benchmark", CVPR 2023, https://github.com/danini/homography-benchmark)+ships SIFT correspondences with second-nearest-neighbour ratios and ground-truth inlier flags per image pair in+one HDF5 file per scene. Download one scene (``NYC_Library_homographies.h5``, 2.5 GB, from the dataset link in+that README) and run from the checkout being measured, with optional h5py:++ python benchmarks/geometry/heb.py run --h5 /data/heb/NYC_Library_homographies.h5 --device cuda \+ --batches auto --budgets 2048,8192,32768 --lo 0,5 --prosac off,on --pairs 200 --json /tmp/heb-cuda.json+ python benchmarks/geometry/heb.py plot --json this=/tmp/heb-cuda.json --json main=/tmp/heb-cuda-main.json \+ --out /tmp/heb-cuda.png++Protocol, as in the benchmark's own ``test_kornia.py``: correspondences with a ratio below ``--snn`` (0.8) are+kept and sorted best-first for PROSAC, the homography is estimated once per configuration, pair and seed on+preloaded device tensors, and its accuracy is the mean reprojection error of the ground-truth inliers, turned+into a mean average accuracy over ten thresholds spaced logarithmically from 1 to 20 px. Estimates with fewer+than four inliers, or non-finite ones, count as failures. Timing covers ``RANSAC.forward`` only, through+``common.time_us`` (median of many synchronized calls after warm-up), on every scored pair unless+``--timing-pairs`` limits it. The metric here is the benchmark's reprojection mAA; its homography-decomposition+pose error is not used, because on this data the ground-truth homography itself scores 16 degrees of+translation error.++The scene is hard: the median pair keeps 485 correspondences of which 3% are ground-truth inliers, so uniform+sampling never stops early and accuracy is bought with the draw budget. Configurations sweep the sampler,+the batch size (integers or ``auto``), the draw budget (``max_samples``) and local optimization; the+inlier threshold, confidence and scoring definition are fixed across configurations. Frontier curves are+empirical envelopes over one seed per pair unless ``--seeds`` lists more.+"""++from __future__ import annotations++import argparse+import itertools+import json+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 finish_run, setup_run, start_run, time_us # noqa: E402++from kornia.geometry import RANSAC # noqa: E402++MAA_THRESHOLDS_PX = np.logspace(np.log2(1.0), np.log2(20.0), 10, base=2.0)+FAILURE = 1e10+++def reprojection_error(points1: np.ndarray, points2: np.ndarray, homography: np.ndarray) -> float:+ """Mean distance, in pixels, between ``H @ points1`` and ``points2``; the benchmark's accuracy measure."""+ projected = np.column_stack((points1, np.ones(len(points1)))) @ homography.T+ with np.errstate(divide="ignore", invalid="ignore"):+ projected = projected[:, :2] / projected[:, 2:3]+ error = np.sqrt(np.sum((projected - points2) ** 2, axis=1))+ return float(np.mean(error)) if np.all(np.isfinite(error)) else FAILURE+++def mean_average_accuracy(errors: np.ndarray) -> float:+ """Mean over thresholds of the fraction of pairs whose error is at most the threshold."""+ return float(np.mean([(errors <= threshold).mean() for threshold in MAA_THRESHOLDS_PX]))+++def load_pairs(args: argparse.Namespace) -> dict[str, dict[str, np.ndarray]]:+ try:+ import h5py+ except ImportError as exc:+ raise SystemExit(f"Reading HEB needs h5py: {exc}") from exc+ with h5py.File(args.h5, "r") as handle:+ names = sorted(key[5:] for key in handle if key.startswith("corr_"))+ rng = np.random.default_rng(args.pair_seed)+ chosen = sorted(rng.choice(len(names), size=min(args.pairs, len(names)), replace=False))+ return {names[index]: {"matches": handle[f"corr_{names[index]}"][()]} for index in chosen}+++def parse_batches(spec: str) -> list[int | str]:+ return [item if item == "auto" else int(item) for item in spec.split(",")]+++def make_estimator(args: argparse.Namespace, config: dict[str, Any], seed: int) -> RANSAC:+ """Build the estimator; older revisions need a budget divisible by their fixed batch size."""+ common: dict[str, Any] = {+ "inl_th": args.threshold,+ "confidence": args.confidence,+ "max_lo_iters": config["max_lo_iters"],+ "score_type": args.score,+ "prosac_sampling": config["prosac"],+ "seed": seed,+ }+ try:+ return RANSAC("homography", batch_size=config["batch_size"], max_samples=config["budget"], **common)+ except TypeError:+ if config["batch_size"] == "auto":+ raise SystemExit("This revision has no auto batch size; pass integer --batches") from None+ if config["budget"] % config["batch_size"]:+ raise SystemExit("This revision has no max_samples; budget must be divisible by batch size") from None+ return RANSAC(+ "homography",+ batch_size=config["batch_size"],+ max_iter=config["budget"] // config["batch_size"],+ **common,+ )+++def run(args: argparse.Namespace) -> None:+ device, dtype, sync = setup_run(args, opencv=False)+ meta = start_run(+ "RANSAC on HEB",+ args,+ device,+ units="pairs/s",+ regimes=["Preloaded device tensors sorted best-first; full RANSAC.forward including sampling, scoring and LO"],+ )+ meta.update(+ h5=Path(args.h5).name,+ pairs=args.pairs,+ pair_seed=args.pair_seed,+ snn=args.snn,+ threshold_px=args.threshold,+ confidence=args.confidence,+ score=args.score,+ min_run_time=args.min_run_time,+ maa_thresholds_px=MAA_THRESHOLDS_PX.tolist(),+ accuracy="mean reprojection error of the ground-truth inliers, mAA over 1-20 px; failures count as misses",+ )+ data = load_pairs(args)+ inputs = {}+ for name, item in data.items():+ matches = item["matches"]+ keep = matches[:, 8] < args.snn+ order = np.argsort(matches[keep, 8], kind="stable")+ inputs[name] = tuple(+ torch.as_tensor(matches[keep][order, column : column + 2], device=device, dtype=dtype) for column in (0, 2)+ )+ configs = [+ {"prosac": prosac == "on", "batch_size": batch, "budget": budget, "max_lo_iters": lo}+ for prosac, batch, budget, lo in itertools.product(+ args.prosac.split(","),+ parse_batches(args.batches),+ map(int, args.budgets.split(",")),+ map(int, args.lo.split(",")),+ )+ if batch == "auto" or budget >= batch+ ]+ seeds = [int(seed) for seed in args.seeds.split(",")]+ rows: list[dict[str, Any]] = []+ for index, config in enumerate(configs):+ errors = []+ for seed in seeds:+ estimator = make_estimator(args, config, seed).to(device)+ for count, (name, (kp1, kp2)) in enumerate(inputs.items()):+ row: dict[str, Any] = {**config, "pair": name, "seed": seed, "correspondences": len(kp1)}+ if len(kp1) < 4:+ row.update(inliers=0, error_px=FAILURE, median_us=None, iqr_us=None)+ rows.append(row)+ errors.append(FAILURE)+ continue+ batches = []+ sample = estimator.sample+ estimator.sample = lambda m, n, batch, *a, _s=sample, _b=batches, **k: (+ _b.append(batch) or _s(m, n, batch, *a, **k)+ )+ try:+ with torch.inference_mode():+ model, mask = estimator(kp1, kp2)+ finally:+ estimator.sample = sample+ inliers = int(mask.sum())+ matches = data[name]["matches"]+ gt = matches[:, 9].astype(bool)+ error = FAILURE+ if inliers >= 4 and gt.sum() > 1:+ error = reprojection_error(+ matches[gt, :2], matches[gt, 2:4], model.detach().cpu().numpy().astype(np.float64)+ )+ errors.append(error)+ median = iqr = None+ if args.timing_pairs is None or count < args.timing_pairs:+ with torch.inference_mode():+ median, iqr = time_us(partial(estimator, kp1, kp2), args.min_run_time, sync=sync)+ row.update(+ inliers=inliers,+ # The last batch is sampled at nominal size, then truncated before fitting and scoring.+ sampled_sets=min(sum(batches), config["budget"]),+ batches=len(batches),+ error_px=error,+ median_us=median,+ iqr_us=iqr,+ )+ rows.append(row)+ timed = [+ row["median_us"]+ for row in rows+ if row["median_us"] is not None and all(row[k] == config[k] for k in config)+ ]+ maa = mean_average_accuracy(np.array(errors))+ mean_ms = np.mean(timed) / 1000 if timed else float("nan")+ print(+ f"[{index + 1}/{len(configs)}] prosac={config['prosac']!s:5} batch={config['batch_size']!s:5} "+ f"budget={config['budget']:6} lo={config['max_lo_iters']}: mAA={maa:.4f} mean {mean_ms:.2f} ms/pair",+ flush=True,+ )+ finish_run(args, "geometry-heb", meta, rows)+++def summarize(document: dict[str, Any]) -> list[dict[str, Any]]:+ """Per-configuration mAA and mean timed latency from a ``run`` output."""+ groups: dict[tuple, list[dict[str, Any]]] = defaultdict(list)+ for row in document["results"]:+ groups[(row["prosac"], str(row["batch_size"]), row["budget"], row["max_lo_iters"])].append(row)+ summaries = []+ for (prosac, batch, budget, lo), items in sorted(groups.items()):+ timed = [row["median_us"] for row in items if row.get("median_us") is not None]+ summaries.append(+ {+ "prosac": prosac,+ "batch_size": batch,+ "budget": budget,+ "max_lo_iters": lo,+ "maa": mean_average_accuracy(np.array([row["error_px"] for row in items])),+ "mean_ms": float(np.mean(timed)) / 1000 if timed else None,+ "mean_sampled_sets": float(np.mean([row.get("sampled_sets", 0) for row in items])),+ "pairs": len(items),+ }+ )+ return summaries+++def plot(args: argparse.Namespace) -> None:+ import matplotlib as mpl++ mpl.use("Agg")+ import matplotlib.pyplot as plt+ from matplotlib.lines import Line2D++ colors = {False: "#eb6834", True: "#2a78d6"}+ styles = ["-", "--", ":", "-."]+ fig, ax = plt.subplots(figsize=(7, 5))+ for (label, path), style in zip((spec.split("=", 1) for spec in args.json), itertools.cycle(styles)):+ summaries = [s for s in summarize(json.loads(Path(path).read_text())) if s["mean_ms"] is not None]+ for prosac in (False, True):+ points = [(s["mean_ms"], s["maa"], s["max_lo_iters"]) for s in summaries if s["prosac"] == prosac]+ if not points:+ continue+ for ms, maa, lo in points:+ ax.plot(+ ms,+ maa,+ marker="o" if lo == 0 else "s",+ ms=6,+ color=colors[prosac],+ mfc=colors[prosac] if style == "-" else "white",+ mew=1.5,+ ls="none",+ )+ best, frontier = -1.0, []+ for ms, maa, _ in sorted(points):+ if maa > best:+ frontier.append((ms, maa))+ best = maa+ ax.plot(+ *zip(*frontier), ls=style, color=colors[prosac], label=f"{'PROSAC' if prosac else 'uniform'}, {label}"+ )+ ax.set_xscale("log")+ ax.set_xlabel("mean RANSAC time per pair (ms)")+ ax.set_ylabel("mAA, reprojection error 1-20 px")+ ax.grid(True, color="#e6e5e1")+ handles, labels = ax.get_legend_handles_labels()+ handles += [+ Line2D([], [], marker="o", ls="none", color="gray", mfc="none"),+ Line2D([], [], marker="s", ls="none", color="gray", mfc="none"),+ ]+ labels += ["no local optimization", "local optimization"]+ ax.legend(handles, labels, fontsize=8, frameon=False)+ fig.tight_layout()+ fig.savefig(args.out, dpi=150)+ print(f"# wrote {args.out}")+++def main() -> None:+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)+ commands = parser.add_subparsers(dest="command", required=True)+ measure = commands.add_parser("run")+ measure.add_argument("--h5", type=Path, required=True, help="one HEB scene, e.g. NYC_Library_homographies.h5")+ measure.add_argument("--pairs", type=int, default=200, help="random pairs of the scene to use")+ measure.add_argument("--pair-seed", type=int, default=0)+ measure.add_argument("--device", default="cpu")+ measure.add_argument("--dtype", choices=("float32", "float64"), default="float32")+ measure.add_argument("--threads", type=int, default=1)+ measure.add_argument("--snn", type=float, default=0.8, help="keep correspondences with a ratio below this")+ measure.add_argument("--threshold", type=float, default=1.0, help="inlier threshold in pixels")+ measure.add_argument("--confidence", type=float, default=0.99)+ measure.add_argument("--score", choices=("ransac", "msac"), default="msac")+ measure.add_argument("--prosac", default="off,on")+ measure.add_argument("--batches", default="auto", help="comma-separated batch sizes, integers or auto")+ measure.add_argument("--budgets", default="2048,8192,32768", help="comma-separated draw budgets (max_samples)")+ measure.add_argument("--lo", default="0,5", help="comma-separated max_lo_iters values")+ measure.add_argument("--seeds", default="0")+ measure.add_argument("--min-run-time", type=float, default=0.05)+ measure.add_argument("--timing-pairs", type=int, help="time only the first N pairs; score all")+ measure.add_argument("--json", type=Path, required=True)+ measure.set_defaults(contribute=None, machine_slug=None)+ plotter = commands.add_parser("plot")+ plotter.add_argument("--json", action="append", required=True, help="label=path (repeatable)")+ plotter.add_argument("--out", type=Path, required=True)+ args = parser.parse_args()+ if args.command == "run":+ run(args)+ else:+ plot(args)+++if __name__ == "__main__":+ main()diff --git a/benchmarks/geometry/ransac.py b/benchmarks/geometry/ransac.pyindex 5f22605c5..67f2c1664 100644--- a/benchmarks/geometry/ransac.py+++ b/benchmarks/geometry/ransac.py@@ -217,6 +217,19 @@ def run(args: argparse.Namespace) -> None:# Both samplers see identical order; PROSAC assumes best matches come first.kp1 = torch.as_tensor(a[order], device=device, dtype=dtype)kp2 = torch.as_tensor(b[order], device=device, dtype=dtype)+ threshold = args.threshold+ if args.model == "essential":+ # Calibrated coordinates; the pixel threshold is divided by the mean focal length, and the+ # estimate is converted back to a fundamental matrix for the evaluator.+ calibration = [np.linalg.inv(data[f"{key}__{side}_K"]) for side in ("a", "b")]+ kp1, kp2 = (+ torch.as_tensor(+ np.column_stack((points, np.ones(len(points)))) @ inverse.T, device=device, dtype=dtype+ )[:, :2]+ for points, inverse in zip((a[order], b[order]), calibration)+ )+ focal = np.mean([data[f"{key}__{side}_K"][[0, 1], [0, 1]].mean() for side in ("a", "b")])+ threshold = args.threshold / focalfor batch, score, prosac, lo, seed in configs:row: dict[str, Any] = {"op": "RANSAC",@@ -244,7 +257,7 @@ def run(args: argparse.Namespace) -> None:else:estimator = RANSAC(model_type=args.model,- inl_th=args.threshold,+ inl_th=threshold,batch_size=batch,max_iter=args.sample_budget // batch,confidence=args.confidence,@@ -278,8 +291,11 @@ def run(args: argparse.Namespace) -> None:row.update(median_us=median, iqr_us=iqr, throughput_per_s=1e6 / median)original_mask = np.zeros(len(a), dtype=bool)original_mask[order] = mask.detach().cpu().numpy().reshape(-1)+ matrix = matrix.detach().cpu().to(torch.float64).numpy()+ if args.model == "essential":+ matrix = calibration[1].T @ matrix @ calibration[0]row.update(- matrix=matrix.detach().cpu().tolist(),+ matrix=matrix.tolist(),inlier_indices=np.flatnonzero(original_mask).tolist(),)except (RuntimeError, ValueError) as exc:@@ -830,7 +846,7 @@ def main() -> None:"--lo-sample-size", type=int, help="optional bounded LO subset; omitted for base compatibility")measure.add_argument("--seeds", default="0,1,2")- measure.add_argument("--model", choices=("fundamental", "fundamental_7pt"), default="fundamental")+ measure.add_argument("--model", choices=("fundamental", "fundamental_7pt", "essential"), default="fundamental")measure.add_argument("--threshold", type=float, default=1.0)measure.add_argument("--confidence", type=float, default=0.999)measure.add_argument("--min-run-time", type=float, default=0.2)diff --git a/changelog.d/4979.breaking.md b/changelog.d/4979.breaking.mdnew file mode 100644index 000000000..bea99abc4--- /dev/null+++ b/changelog.d/4979.breaking.md@@ -0,0 +1,15 @@+`RANSAC` gains `batch_size="auto"`, now the default, and `max_samples`. Before, every device drew batches of 2048+hypotheses and `max_iter` counted them. Now the budget is `max_samples` if given, otherwise `2048 * max_iter` as+before, and the batch is chosen per call: batches of up to 8192 homography or 2048 epipolar hypotheses on CUDA and+MPS, fewer once the `batch x N` residual matrix would exceed `2**27` entries, and on CPU 256 to 2048 hypotheses for+homographies or 128 to 512 for the epipolar models, fewer for more correspondences (`RANSAC.resolve_batch_size`).+Other devices retain 2048-sample batches.+Pass an integer `batch_size` to keep a fixed batch. `max_samples` must be an integer; a float raises `ValueError`.+Results for a given seed depend on the batch, so default results change on CUDA, MPS and on CPU inputs large+enough to lower the batch below 2048, and seeded local optimization with `lo_sample_size` draws from a stream offset+by the sample budget instead of `max_iter`, so those results change too. `find_homography_dlt_iterated` and+`find_homography_lines_dlt_iterated` re-weighted each correspondence with `exp(-e / (2 * soft_inl_th**2))` of the+unsquared error `e`, a kernel in which `soft_inl_th` had no pixel meaning (#4870). They now use the Gaussian+`exp(-e**2 / (2 * soft_inl_th**2))` of the error in pixels, for line segments the perpendicular distance of the+mapped endpoints from the image-2 line, so `soft_inl_th` is a standard deviation in pixels, and `RANSAC`'s homography+polishers set it to `inl_th`. Polished homographies change accordingly.diff --git a/changelog.d/4979.fixed.md b/changelog.d/4979.fixed.mdnew file mode 100644index 000000000..22f93afa2--- /dev/null+++ b/changelog.d/4979.fixed.md@@ -0,0 +1,15 @@+`RANSAC(prosac_sampling=True)` always ran the whole `batch_size * max_iter` budget. It now stops with PROSAC's+termination-length test (Chum and Matas, 2005): a ranked prefix certifies the incumbent when its support there is+non-random and the draws it needs for `confidence` fit inside the prefix's growth interval, with OpenCV USAC's guards+against short or weakly supported prefixes; the whole set is always a candidate, so PROSAC never runs longer than+uniform sampling would. `confidence=1` still runs the whole budget. `find_homography_dlt` with the default+`solver="lu"` computed the gauge null vector of a four-point sample with `torch.linalg.qr`, which has no batched CUDA+kernel and factored a batch of 2048 minimal samples one matrix at a time in about 250 ms. On CUDA it now uses the+batched SVD (about 1 ms), so `RANSAC("homography")` batches on GPU are up to 7x faster; CPU results are unchanged.+`find_essential` on CUDA computed the roots of NistΓ©r's degree-ten polynomial with `torch.linalg.eigvals`, which has+no batched CUDA kernel and factors the companion matrices one cusolver call at a time (about 3.6 ms each), so+`RANSAC("essential")` spent 6.4 s per batch of 2048 samples. The eigenvalues are now computed on the host with LAPACK+for CUDA inputs (about 15 ms for that batch, transfers included), which makes the solver about 150x faster on the GPU;+results are unchanged to roundoff. `RANSAC("homography_from_linesegments")` local+optimization re-weighted segments by the length-scaled residual of `line_segment_transfer_error_one_way`, which+down-weighted long segments (#4867); it now re-weights by the perpendicular distance in pixels that the score uses.diff --git a/docs/source/geometry.ransac.rst b/docs/source/geometry.ransac.rstindex 985749ccb..74002da60 100644--- a/docs/source/geometry.ransac.rst+++ b/docs/source/geometry.ransac.rst@@ -11,12 +11,28 @@ Robust model fitting with RANSAC (Random Sample Consensus), used to estimate homBatches, scores, and refinement--------------------------------``batch_size`` counts minimal sample sets. The total budget is-``batch_size * max_iter``; seven-point fundamental and five-point essential-solvers may produce several candidate matrices from each set. Smaller batches-permit earlier stopping, while larger batches amortize accelerator overhead.-``confidence=1`` disables early stopping and runs the whole budget.-Measure end-to-end latency and pose accuracy when choosing a batch size.+Hypotheses are generated and verified in batches. The sampling budget is+``max_samples`` minimal samples when given, otherwise ``batch_size * max_iter``+(``2048 * max_iter``, the historical default, with ``batch_size="auto"``); the+last batch is truncated to it. Seven-point fundamental and five-point essential+solvers may produce several candidate matrices from each set. Early stopping is+checked between batches, and ``confidence=1`` runs the whole budget.++The default ``batch_size="auto"`` picks the batch per call. On CUDA and MPS a+homography 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+compute-bound past 2048 hypotheses, so their batches stop there. Verification+holds a ``batch x N`` residual matrix, so past ``2**27`` entries (about 1 GiB+at peak in float32) the batch shrinks with ``N``, down to 2048. Other devices+retain the historical 2048-sample batch. A PROSAC batch+of either size spans most of the growth schedule, whereas certifying a model+after a small first batch drawn from a short prefix can stop on a poorly+conditioned fit. On CPU+the cost is linear in ``batch * N`` residuals and the eight-point solver costs+about ten DLTs, so the batch aims at a millisecond or so of work: 256 to 2048+hypotheses for homographies and 128 to 512 for the epipolar models, fewer for+more correspondences, which lets early stopping pay off. An integer+``batch_size`` fixes the batch on every device.``score_type="msac"`` minimizes the sum of squared residuals truncated at``inl_th ** 2``. The returned internal score is normalized to increase with@@ -25,9 +41,7 @@ Fundamental and essential models use Sampson residuals. Essential estimationexpects camera-normalized coordinates, so its threshold is not in pixels.Line-segment homographies use the squared mean distance from the transferredendpoints to the target segment's line; zero-length target segments are outliers.-Their local optimization still weights segments by the length-scaled residual of-:func:`~kornia.geometry.homography.line_segment_transfer_error_one_way`, which-down-weights long segments (`#4867 <https://github.com/kornia/kornia/issues/4867>`_).+Their local optimization re-weights segments by the same distance.A model is accepted only with more inliers than its minimal sample (fourcorrespondences for homographies, five for essential and seven or eight for@@ -49,12 +63,31 @@ For example, when smaller descriptor ratios indicate better matches:inliers[order] = sorted_inliersThe prefix grows within a batch, and each growth sample includes the newest-correspondence. This implements PROSAC sampling, not its original prefix-based-termination test: it runs the full budget and does not apply the uniform-sampling-confidence formula to biased draws. Uninformative or reversed rankings can hurt-accuracy. The ``weights`` argument is not used to rank correspondences.+correspondence. Stopping follows the paper's termination-length test: a ranked+prefix certifies the incumbent when its support there is non-random (a Chernoff+bound on accidental inliers with probability 0.05, at significance 0.05) and the+draws it needs for ``confidence`` fit inside the prefix's growth interval, so+that only draws from that prefix count. As in OpenCV's USAC, a prefix shorter+than ``min(N / 2, 100)`` or supporting fewer than 20% of all correspondences+cannot terminate; the whole set is always a candidate, so PROSAC never runs+longer than the uniform bound. Stopping is checked between batches.+Uninformative or reversed rankings can hurt accuracy. The ``weights`` argument+is not used to rank correspondences.++PROSAC pays off when the ranking tracks inlier-ness and the inlier ratio is low,+where uniform sampling cannot stop early: on SIFT correspondences with a ratio+test (HEB), it adds about 0.1 mAA at equal time for homographies. On learned+matchers with 85% or more inliers, uniform sampling already stops after one+batch, and the confidence-ranked prefixes can be spatially clustered, so the+model PROSAC certifies first may fit them well and the pose poorly. Prefer+uniform sampling there, or run PROSAC with ``confidence=1`` when the extra+draws are affordable.-By default, local optimization repeatedly refits all current inliers. A refit+By default, local optimization repeatedly refits all current inliers. For the+homography models the refit is the iteratively re-weighted least squares of+:func:`~kornia.geometry.homography.find_homography_dlt_iterated`, whose Gaussian+weights use ``inl_th`` as their standard deviation, so a correspondence at the+threshold keeps weight ``exp(-1/2)``. A refitreplaces the model when it raises the score, or when it ties it: a least-squaresfit on the same support is more precise than the minimal-sample model. A refitthat does not raise the score ends the refinement. This is iterative refitting,@@ -70,4 +103,4 @@ non-minimal solver's sample size (eight for fundamental/essential matrices).Evaluate the accuracy/runtime trade-off on your data before enabling it... autoclass:: RANSAC- :members: forward+ :members: forward, resolve_batch_sizediff --git a/docs/source/get-started/conventions.rst b/docs/source/get-started/conventions.rstindex e58c95b9f..a0fa77512 100644--- a/docs/source/get-started/conventions.rst+++ b/docs/source/get-started/conventions.rst@@ -525,8 +525,8 @@ normalised camera coordinates, and :func:`~kornia.geometry.homography.find_homog- ``sampsonDistance(pt1, pt2, F)``, the same argument order, independent of the scale of ``F``* - RANSAC threshold- ``inl_th`` is a point distance in the keypoints' units, calibrated units for ``model_type="essential"``;- for line segments, the mean distance of the transferred endpoints from the target segment's line, though- local optimization still weights segments by length (`#4867 <https://github.com/kornia/kornia/issues/4867>`_)+ for line segments, the mean distance of the transferred endpoints from the target segment's line, which+ local optimization re-weights by as well- ``ransacReprojThreshold`` of ``findHomography``, the same unit for points* - polynomial roots- ``solve_quadratic``, ``solve_cubic`` and ``solve_quartic`` take coefficients highest degree first anddiff --git a/kornia/geometry/epipolar/essential.py b/kornia/geometry/epipolar/essential.pyindex 6ec77fcac..c0e680c44 100644--- a/kornia/geometry/epipolar/essential.py+++ b/kornia/geometry/epipolar/essential.py@@ -390,7 +390,14 @@ def _null_to_Nister_solution_script(if no_roots.any():C = torch.where(no_roots.view(B, 1, 1), eye10, C)- roots_eig = torch.linalg.eigvals(C) # (B,10), complex+ 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), complexroots = torch.real(roots_eig)is_real = torch.abs(torch.imag(roots_eig)) < 1e-10diff --git a/kornia/geometry/homography.py b/kornia/geometry/homography.pyindex 5e971e225..df32e9ace 100644--- a/kornia/geometry/homography.py+++ b/kornia/geometry/homography.py@@ -203,6 +203,18 @@ def line_segment_transfer_error_one_way(return error+def _line_segment_squared_distance_one_way(ls1: torch.Tensor, ls2: torch.Tensor, H: torch.Tensor) -> torch.Tensor:+ """Squared perpendicular distance, in pixels, of the mapped image-1 endpoints from the image-2 line.++ :func:`line_segment_transfer_error_one_way` carries the image-2 segment length (#4867); dividing by it gives the+ pixel distance. A zero-length image-2 segment defines no line, so its distance is infinite.+ """+ residual = line_segment_transfer_error_one_way(ls1, ls2, H)+ length = (ls2[..., 1, :] - ls2[..., 0, :]).norm(dim=-1)+ distance = residual / torch.where(length > 0, length, torch.ones_like(length))+ return torch.where(length > 0, distance.square(), torch.full_like(distance, float("inf")))++def find_homography_dlt(points1: torch.Tensor, points2: torch.Tensor, weights: Optional[torch.Tensor] = None, solver: str = "lu") -> torch.Tensor:@@ -232,6 +244,17 @@ def find_homography_dlt(the computed homography matrix with shape :math:`(B, 3, 3)`."""+ device, dtype = _extract_device_dtype([points1, points2])+ A, transform1, transform2 = _homography_dlt_system(points1, points2, weights)+ return _homography_from_dlt_system(+ A, weights, transform1, safe_inverse_with_mask(transform2)[0], solver, device, dtype+ )+++def _homography_dlt_system(+ points1: torch.Tensor, points2: torch.Tensor, weights: Optional[torch.Tensor] = None+) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:+ """Build the weighted-normalized DLT design matrix and its two normalizing transforms."""if points1.shape != points2.shape:raise AssertionError(points1.shape)if points1.shape[1] < 4:@@ -239,9 +262,6 @@ def find_homography_dlt(KORNIA_CHECK_SHAPE(points1, ["B", "N", "2"])KORNIA_CHECK_SHAPE(points2, ["B", "N", "2"])- device, dtype = _extract_device_dtype([points1, points2])-- eps: float = 1e-8if weights is not None and weights.shape != points1.shape[:2]:raise AssertionError(weights.shape)points1_norm, transform1 = normalize_points(points1, weights=weights)@@ -255,20 +275,37 @@ def find_homography_dlt(ax = torch.cat([zeros, zeros, zeros, -x1, -y1, -ones, y2 * x1, y2 * y1, y2], dim=-1)ay = torch.cat([x1, y1, ones, zeros, zeros, zeros, -x2 * x1, -x2 * y1, -x2], dim=-1)A = torch.cat((ax, ay), dim=-1).reshape(ax.shape[0], -1, ax.shape[-1])+ return A, transform1, transform2+++def _homography_from_dlt_system(+ A: torch.Tensor,+ weights: Optional[torch.Tensor],+ transform1: torch.Tensor,+ transform2_inv: torch.Tensor,+ solver: str,+ device: torch.device,+ dtype: torch.dtype,+) -> torch.Tensor:+ """Solve the (weighted) DLT system of :func:`_homography_dlt_system` and denormalize the homography.+ The operand order matches the original single-call implementation.+ """+ eps: float = 1e-8+ num_points = A.shape[1] // 2if weights is None:# All points are equally importantw_full = Noneelse:# We should use provided weights- if not (len(weights.shape) == 2 and weights.shape == points1.shape[:2]):+ if not (len(weights.shape) == 2 and weights.shape == (A.shape[0], num_points)):raise AssertionError(weights.shape)w_full = weights.repeat_interleave(2, dim=1).unsqueeze(1)# Only the minimal four-point LU path works from the design matrix itself (see below).# Every other case forms the normal equations in the exact operand order the pre-gauge# implementation used, so weighted results stay bit-identical to it.- minimal_lu = solver == "lu" and points1.shape[1] == 4+ minimal_lu = solver == "lu" and num_points == 4if not minimal_lu:A = A.transpose(-2, -1) @ A if w_full is None else (A.transpose(-2, -1) * w_full) @ A@@ -277,7 +314,7 @@ def find_homography_dlt(_, _, V = _torch_svd_cast(A)except RuntimeError:warnings.warn("SVD did not converge", RuntimeWarning, stacklevel=1)- return torch.empty((points1_norm.size(0), 3, 3), device=device, dtype=dtype)+ return torch.empty((A.shape[0], 3, 3), device=device, dtype=dtype)H = V[..., -1].view(-1, 3, 3)elif solver == "lu":if not minimal_lu:@@ -298,8 +335,15 @@ def find_homography_dlt(finite = finite_entries.flatten(1).all(-1)Aw = torch.where(finite_entries, Aw, torch.zeros_like(Aw))gauge_dtype = torch.float64 if dtype == torch.float64 else torch.float32- Q, _ = torch.linalg.qr(Aw.detach().to(gauge_dtype).transpose(-2, -1), mode="complete")- null = Q[..., -1]+ design = Aw.detach().to(gauge_dtype)+ if device.type == "cuda":+ # torch.linalg.qr has no batched CUDA kernel: it factors the B matrices one cusolver call at a+ # time (~0.1 ms each), so a 2048-sample RANSAC batch spent ~250 ms here. The batched Jacobi+ # SVD is one kernel (~1 ms for 2048) and its null vector agrees with the QR one to roundoff.+ null = torch.linalg.svd(design)[2][..., -1, :]+ else:+ Q, _ = torch.linalg.qr(design.transpose(-2, -1), mode="complete")+ null = Q[..., -1]gauge = null.abs().argmax(dim=-1)retained = torch.arange(8, device=device).expand(A.shape[0], -1)retained = retained + (retained >= gauge[:, None]).to(retained.dtype)@@ -321,7 +365,7 @@ def find_homography_dlt(H = sol.reshape(-1, 3, 3)else:raise NotImplementedError- H = safe_inverse_with_mask(transform2)[0] @ (H @ transform1)+ H = transform2_inv @ (H @ transform1)return normalize_transformation(H, eps)@@ -332,27 +376,33 @@ def find_homography_dlt_iterated(Convention:- Direction and ``H[2, 2] = 1`` as :func:`find_homography_dlt`. Each solve after the first re-weights- with ``exp(-e / (2 * soft_inl_th**2))`` of the unsquared symmetric transfer error ``e``.- - Known defect: the exponent is linear, not quadratic, in ``e``, so ``soft_inl_th`` is not a pixel- standard deviation (`#4870 <https://github.com/kornia/kornia/issues/4870>`_).+ with the Gaussian kernel ``exp(-e**2 / (2 * soft_inl_th**2))`` of the symmetric transfer error ``e``+ (the root of the summed squared forward and backward transfer errors), so ``soft_inl_th`` is a+ standard deviation in pixels: a correspondence with ``e = soft_inl_th`` keeps weight ``exp(-1/2)``.Args:points1: A set of points in the first image with a tensor shape :math:`(B, N, 2)`.points2: A set of points in the second image with a tensor shape :math:`(B, N, 2)`.weights: Tensor containing the weights per point correspondence with a shape of :math:`(B, N)`.Used for the first iteration of the IRWLS.- soft_inl_th: scale in the re-weighting kernel given above.+ soft_inl_th: standard deviation, in pixels, of the Gaussian re-weighting kernel given above.n_iter: number of solves, including the initial one.Returns:the computed homography matrix with shape :math:`(B, 3, 3)`."""- H: torch.Tensor = find_homography_dlt(points1, points2, weights)+ device, dtype = _extract_device_dtype([points1, points2])+ # Weighted Hartley normalization changes with each set of IRLS weights.+ A, transform1, transform2 = _homography_dlt_system(points1, points2, weights)+ transform2_inv = safe_inverse_with_mask(transform2)[0]+ H: torch.Tensor = _homography_from_dlt_system(A, weights, transform1, transform2_inv, "lu", device, dtype)for _ in range(n_iter - 1):- errors: torch.Tensor = symmetric_transfer_error(points1, points2, H, False)- weights_new: torch.Tensor = torch.exp(-errors / (2.0 * (soft_inl_th**2)))- H = find_homography_dlt(points1, points2, weights_new)+ squared_errors: torch.Tensor = symmetric_transfer_error(points1, points2, H, True)+ weights_new: torch.Tensor = torch.exp(-squared_errors / (2.0 * (soft_inl_th**2)))+ A, transform1, transform2 = _homography_dlt_system(points1, points2, weights_new)+ transform2_inv = safe_inverse_with_mask(transform2)[0]+ H = _homography_from_dlt_system(A, weights_new, transform1, transform2_inv, "lu", device, dtype)return H@@ -492,19 +542,22 @@ def find_homography_lines_dlt_iterated(r"""Compute the homography matrix using the iteratively-reweighted least squares (IRWLS) from line segments.Convention:- - As :func:`find_homography_dlt_iterated`, with :func:`find_homography_lines_dlt` as the solver and the- unsquared error of :func:`line_segment_transfer_error_one_way` as ``e``.- - Known defects: those of the three functions apply+ - As :func:`find_homography_dlt_iterated`, with :func:`find_homography_lines_dlt` as the solver and, as+ ``e`` in the Gaussian kernel, the perpendicular distance in pixels of the mapped image-1 endpoints from+ the image-2 line: the residual of :func:`line_segment_transfer_error_one_way` divided by the image-2+ segment length it carries. A zero-length image-2 segment gets weight zero.+ - Known defects: the endpoint pairing of :func:`find_homography_lines_dlt` and the length-scaled+ residual of :func:`line_segment_transfer_error_one_way` still apply(`#4866 <https://github.com/kornia/kornia/issues/4866>`_,- `#4867 <https://github.com/kornia/kornia/issues/4867>`_,- `#4870 <https://github.com/kornia/kornia/issues/4870>`_).+ `#4867 <https://github.com/kornia/kornia/issues/4867>`_).Args:ls1: A set of line segments in the first image with a tensor shape :math:`(B, N, 2, 2)`.ls2: A set of line segments in the second image with a tensor shape :math:`(B, N, 2, 2)`.weights: Tensor containing the weights per segment with a shape of :math:`(B, N)`.Used for the first iteration of the IRWLS.- soft_inl_th: scale in the re-weighting kernel of :func:`find_homography_dlt_iterated`.+ soft_inl_th: standard deviation, in pixels, of the Gaussian re-weighting kernel of+ :func:`find_homography_dlt_iterated`.n_iter: number of solves, including the initial one.Returns:@@ -513,7 +566,7 @@ def find_homography_lines_dlt_iterated("""H: torch.Tensor = find_homography_lines_dlt(ls1, ls2, weights)for _ in range(n_iter - 1):- errors: torch.Tensor = line_segment_transfer_error_one_way(ls1, ls2, H, False)- weights_new: torch.Tensor = torch.exp(-errors / (2.0 * (soft_inl_th**2)))+ squared_distances: torch.Tensor = _line_segment_squared_distance_one_way(ls1, ls2, H)+ weights_new: torch.Tensor = torch.exp(-squared_distances / (2.0 * (soft_inl_th**2)))H = find_homography_lines_dlt(ls1, ls2, weights_new)return Hdiff --git a/kornia/geometry/ransac.py b/kornia/geometry/ransac.pyindex 1bbc4cbff..90b390271 100644--- a/kornia/geometry/ransac.py+++ b/kornia/geometry/ransac.py@@ -30,17 +30,20 @@ from torch import nnfrom kornia.core.check import KORNIA_CHECK_SHAPEfrom kornia.geometry.epipolar import find_essential, find_fundamental, project_to_essential, sampson_epipolar_distancefrom kornia.geometry.homography import (+ _line_segment_squared_distance_one_way,find_homography_dlt,find_homography_dlt_iterated,find_homography_lines_dlt,find_homography_lines_dlt_iterated,- line_segment_transfer_error_one_way,oneway_transfer_error,sample_is_valid_for_homography,)__all__ = ["RANSAC"]+# The batch size that the ``max_iter`` budget counts in when ``batch_size="auto"``.+_DEFAULT_BATCH = 2048+@lru_cache(maxsize=32)def _prosac_growth(sample_size: int, pop_size: int, budget: int) -> Tuple[int, ...]:@@ -56,14 +59,6 @@ def _prosac_growth(sample_size: int, pop_size: int, budget: int) -> Tuple[int, .return tuple(ends)-def _squared_line_distance(ls1: torch.Tensor, ls2: torch.Tensor, models: torch.Tensor) -> torch.Tensor:- """Convert the line helper's algebraic residual into squared coordinate distance."""- residual = line_segment_transfer_error_one_way(ls1, ls2, models)- length = (ls2[..., 1, :] - ls2[..., 0, :]).norm(dim=-1)- distance = residual / torch.where(length > 0, length, torch.ones_like(length))- return torch.where(length > 0, distance.square(), torch.full_like(distance, float("inf")))--class RANSAC(nn.Module):"""Module for robust geometry estimation with RANSAC. https://en.wikipedia.org/wiki/Random_sample_consensus.@@ -80,31 +75,34 @@ class RANSAC(nn.Module)::ref:`two-view-conventions` compares this with OpenCV.- ``score_type="msac"`` ranks candidates by ``sum(1 - min(e / inl_th**2, 1))`` over the squared errors``e``; acceptance and early stopping count inliers for either score.- - ``prosac_sampling=True`` expects correspondences sorted best-first and always runs the whole- ``batch_size * max_iter`` budget.+ - ``prosac_sampling=True`` expects correspondences sorted best-first and stops with PROSAC's+ termination-length test; ``confidence=1`` runs the whole ``batch_size * max_iter`` budget.- A seeded call uses a private generator and leaves torch's global RNG state unchanged; ``seed=None``draws from the global generator.- - Known defects: for ``"homography_from_linesegments"``, local optimization weights segments by the- length-scaled residual of :func:`~kornia.geometry.homography.line_segment_transfer_error_one_way`, which- down-weights long segments (`#4867 <https://github.com/kornia/kornia/issues/4867>`_), and the endpoint- pairing of :func:`~kornia.geometry.homography.find_homography_lines_dlt` applies+ - Known defects: for ``"homography_from_linesegments"``, the endpoint pairing of+ :func:`~kornia.geometry.homography.find_homography_lines_dlt` applies(`#4866 <https://github.com/kornia/kornia/issues/4866>`_).Args:model_type: "homography", "fundamental", "fundamental_7pt", "essential", or"homography_from_linesegments".inl_th: positive inlier threshold, in the units given above.- batch_size: number of generated samples at once.- max_iter: maximum batches to generate, giving a budget of ``batch_size * max_iter`` minimal samples.- The seven- and five-point solvers can return multiple models per sample.- confidence: uniform-sampling stopping confidence in ``(0, 1]``; 1 disables early stopping.+ batch_size: hypotheses generated and verified at once, or ``"auto"`` to pick the batch per call from+ the device and the number of correspondences (see :meth:`resolve_batch_size`).+ max_iter: with an integer ``batch_size``, the maximum number of batches, for a budget of+ ``batch_size * max_iter`` minimal samples; with ``"auto"``, the budget is ``2048 * max_iter``. The+ seven- and five-point solvers can return multiple models per sample.+ confidence: stopping confidence in ``(0, 1]``; 1 disables early stopping.max_lo_iters: maximum local refitting iterations; zero disables polishing.score_type: "ransac" for support count, or "msac" for truncated squared residuals.prosac_sampling: use PROSAC sampling on best-first ordered correspondences. The growth schedule- advances per sampled set within each batch; this mode uses the full sampling budget.+ advances per sampled set within each batch; stopping tests the incumbent's support within ranked+ prefixes (Chum and Matas, 2005, section 2.2) as well as within the whole set.seed: optional seed, reset on each call for reproducible estimation on the same device.lo_sample_size: optional inlier-subset size for a batch of ``max_lo_iters`` randomized localrefits followed by a full-inlier refit. None uses iterative full-inlier refitting.+ 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."""@@ -112,7 +110,7 @@ class RANSAC(nn.Module):self,model_type: str = "homography",inl_th: float = 2.0,- batch_size: int = 2048,+ batch_size: Union[int, str] = "auto",max_iter: int = 10,confidence: float = 0.99,max_lo_iters: int = 5,@@ -120,6 +118,7 @@ class RANSAC(nn.Module):prosac_sampling: bool = False,seed: Optional[int] = None,lo_sample_size: Optional[int] = None,+ max_samples: Optional[int] = None,) -> None:"""Initialize the RANSAC estimator.@@ -127,19 +126,24 @@ class RANSAC(nn.Module):model_type: type of model to estimate: "homography", "fundamental", "fundamental_7pt", "essential","homography_from_linesegments".inl_th: inlier threshold; the class docstring gives its unit per ``model_type``.- batch_size: number of generated samples at once.- max_iter: maximum batches to generate. At most ``batch_size * max_iter`` minimal samples are drawn.+ batch_size: number of generated samples at once, or ``"auto"``: batches of up to 8192 homography or+ 2048 epipolar hypotheses on CUDA and MPS, fewer for very many correspondences, and on CPU a batch+ sized for the model and the number of correspondences so that early stopping is checked every+ millisecond or so. Other devices retain the historical 2048-sample batch.+ max_iter: maximum batches to generate. At most ``batch_size * max_iter`` minimal samples are drawn+ (``2048 * max_iter`` with ``batch_size="auto"``) unless ``max_samples`` is given.confidence: desired confidence of the result, used for the early stopping. 1 runs the full budget.max_lo_iters: number of local optimization (polishing) iterations.score_type: scoring method to use: "ransac" or "msac".prosac_sampling: use PROSAC's progressive sampling schedule. Inputs must be sorted best-firstby match quality. The schedule advances for every sampled set, including within batches.- Uses the full sampling budget rather than the uniform sampler's confidence stopping rule.+ Stops when a ranked prefix, or the whole set, certifies the incumbent with ``confidence``.seed: optional random seed for reproducible results. If None, uses global random state.lo_sample_size: optional cap on the number of inliers used by each randomized local refit.Fits ``max_lo_iters`` independent subsets in one batch, followed by one full-inlier refit.None uses iterative full-inlier refitting. Subset refits must raise the score; a full-inlierrefit may also tie it, since it is more precise than the minimal-sample model.+ max_samples: optional budget of minimal samples, overriding ``batch_size * max_iter``."""super().__init__()@@ -155,14 +159,24 @@ class RANSAC(nn.Module):raise ValueError(f"Unsupported score type: {score_type}")if not math.isfinite(inl_th * inl_th) or inl_th <= 0 or inl_th * inl_th == 0:raise ValueError("inl_th and its square must be positive and finite")- if batch_size <= 0 or max_iter <= 0 or max_lo_iters < 0:- raise ValueError("batch_size and max_iter must be positive; max_lo_iters must be nonnegative")+ if isinstance(batch_size, str):+ if batch_size != "auto":+ raise ValueError('batch_size must be a positive integer or "auto"')+ elif isinstance(batch_size, bool) or not isinstance(batch_size, int) or batch_size <= 0:+ raise ValueError('batch_size must be a positive integer or "auto"')+ if max_iter <= 0 or max_lo_iters < 0:+ raise ValueError("max_iter must be positive; max_lo_iters must be nonnegative")+ if max_samples is not None and (+ isinstance(max_samples, bool) or not isinstance(max_samples, int) or max_samples <= 0+ ):+ raise ValueError("max_samples must be a positive integer")if not 0 < confidence <= 1:raise ValueError("confidence must lie in (0, 1]")self.score_type = score_typeself.inl_th = inl_thself.max_iter = max_iterself.batch_size = batch_size+ self.max_samples = max_samplesself.model_type = model_typeself.confidence = confidenceself.max_lo_iters = max_lo_iters@@ -180,16 +194,15 @@ class RANSAC(nn.Module):if model_type == "homography":self.error_fn = oneway_transfer_errorself.minimal_solver = find_homography_dlt- self.polisher_solver = find_homography_dlt_iterated+ # The polisher's Gaussian re-weighting uses the inlier threshold as its standard deviation.+ self.polisher_solver = partial(find_homography_dlt_iterated, soft_inl_th=inl_th)self.minimal_sample_size = 4self.polisher_sample_size = 4elif model_type == "homography_from_linesegments":- self.error_fn = _squared_line_distance+ self.error_fn = _line_segment_squared_distance_one_wayself.minimal_solver = find_homography_lines_dlt- # Known defect: this IRLS polisher weights segments by the length-scaled residual of- # line_segment_transfer_error_one_way, not by the distance used for scoring, so local- # optimization down-weights long segments (https://github.com/kornia/kornia/issues/4867).- self.polisher_solver = find_homography_lines_dlt_iterated+ # The polisher re-weights by the same perpendicular pixel distance the score uses.+ self.polisher_solver = partial(find_homography_lines_dlt_iterated, soft_inl_th=inl_th)self.minimal_sample_size = 4self.polisher_sample_size = 4elif model_type == "fundamental":@@ -287,6 +300,44 @@ class RANSAC(nn.Module):rand.scatter_(1, newest, torch.where(force_newest[:, None], 2.0, rand.gather(1, newest)))return rand.topk(k=sample_size, dim=1, sorted=False).indices+ @property+ def sample_budget(self) -> int:+ """Minimal samples drawn per call: ``max_samples`` if given, else ``batch_size * max_iter``.++ ``batch_size="auto"`` counts ``max_iter`` in batches of 2048, the historical batch, whatever batch the+ call resolves. Read at call time, like ``confidence``, so the attributes can be changed after construction.+ """+ if self.max_samples is not None:+ return self.max_samples+ if isinstance(self.batch_size, int):+ return self.batch_size * self.max_iter+ return _DEFAULT_BATCH * self.max_iter++ def resolve_batch_size(self, num_tc: int, device: torch.device) -> int:+ """Return the batch size of a call: the configured one, or the ``"auto"`` choice for the device.++ On CUDA and MPS a homography batch costs about the same from a few hundred up to 8192 hypotheses+ (the four-point solve is launch-bound), so the whole :attr:`sample_budget` is drawn in batches of+ up to 8192; the epipolar solvers are compute-bound past 2048 hypotheses, so their batches stop there+ and early stopping is checked in between. The verification holds a ``batch x N`` residual matrix and a+ few temporaries of that size, so past ``2**27`` entries (about 1 GiB at peak in float32) the batch+ shrinks with ``N``, down to the 2048 of the historical fixed batch. On CPU the cost is linear in+ ``batch * N`` residuals, and the eight-point solver is about ten times a DLT, so the batch aims at a+ millisecond or so of work, 256 to 2048 hypotheses for homographies and 128 to 512 for the epipolar+ models. Other devices retain the historical 2048-sample batch.+ """+ if isinstance(self.batch_size, int):+ return self.batch_size+ planar = self.model_type in ("homography", "homography_from_linesegments")+ if device.type == "cpu":+ work, lower, upper = (1 << 19, 256, 2048) if planar else (1 << 17, 128, 512)+ elif device.type in ("cuda", "mps"):+ work, lower, upper = 1 << 27, 2048, 8192 if planar else 2048+ else:+ return min(_DEFAULT_BATCH, self.sample_budget)+ batch = min(max(work // max(num_tc, 1), lower), upper)+ return min(batch, self.sample_budget)+def _is_supported(self, num_inliers: float) -> bool:"""Whether a model has support beyond the minimal sample it may have been fitted to.@@ -297,11 +348,53 @@ class RANSAC(nn.Module):def _prosac_schedule(self, sample_size: int, pop_size: int, device: torch.device) -> torch.Tensor:"""Return the cumulative PROSAC draw counts on ``device``, converting them once per configuration."""- key = (sample_size, pop_size, self.batch_size * self.max_iter, device)+ key = (sample_size, pop_size, self.sample_budget, device)if self._prosac_ends is None or self._prosac_ends[0] != key:self._prosac_ends = (key, torch.tensor(_prosac_growth(*key[:3]), device=device))return self._prosac_ends[1]+ def _prosac_max_samples(self, inliers: torch.Tensor, num_inliers: int) -> int:+ """PROSAC termination length test (Chum and Matas, CVPR 2005, section 2.2).++ A ranked prefix ``U_n`` certifies the incumbent when its support ``I_n`` there is non-random and+ ``k_n = log(1 - confidence) / log(1 - C(I_n, m) / C(n, m))`` draws fit inside the prefix's growth+ interval ``T'_n``, so that every counted draw was taken from ``U_n`` or a shorter prefix. The+ binomial tail of ``I_n - m`` accidental inliers with per-correspondence probability ``beta = 0.05`` is+ bounded by Chernoff's inequality at significance 0.05. As in OpenCV's USAC, prefixes shorter than+ ``min(N / 2, 100)`` correspondences or supporting fewer than 20% of all correspondences cannot+ terminate: a handful of top-ranked inliers to a model fitted to their neighbours is no evidence of a+ good model. The whole set is always a candidate, which is the uniform-sampling bound.+ """+ budget = self.sample_budget+ m, total = self.minimal_sample_size, inliers.numel()+ if self.confidence >= 1.0 or total <= m:+ return budget+ bound = min(budget, self.max_samples_by_conf(num_inliers, total, m, self.confidence))+ n_min = max(m + 1, min(total // 2, 100))+ # Independent of the keypoint dtype, including half precision. Double precision keeps a+ # near-integer bound from rounding down; MPS has no float64.+ dtype = torch.float32 if inliers.device.type == "mps" else torch.float64+ n = torch.arange(n_min, total + 1, device=inliers.device, dtype=dtype)+ support = inliers.cumsum(0)[n_min - 1 :].to(dtype)+ # Chernoff: P[Binomial(n - m, beta) >= I - m] <= exp(-(n - m) * D(q || beta)) for q > beta.+ beta = 0.05+ q = (support - m).clamp(min=0) / (n - m)+ divergence = torch.special.xlogy(q, q / beta) + torch.special.xlogy(1 - q, (1 - q) / (1 - beta))+ non_random = (q > beta) & ((n - m) * divergence > -math.log(0.05))+ enough = support >= 0.2 * total+ # Exact without-replacement probability of an all-inlier sample from the prefix, eq. 10.+ offsets = torch.arange(m, device=inliers.device, dtype=dtype)+ probability = ((support[:, None] - offsets).clamp(min=0) / (n[:, None] - offsets)).prod(1)+ required = torch.where(+ probability > 0,+ (math.log1p(-self.confidence) / torch.log1p(-probability)).ceil().clamp(min=1),+ torch.full_like(probability, float("inf")),+ )+ ends = self._prosac_schedule(m, total, inliers.device)[n_min - m :].to(dtype)+ eligible = non_random & enough & (required <= ends)+ candidate = torch.where(eligible, required, torch.full_like(required, float(budget))).min()+ return min(bound, int(candidate.item()))+@staticmethoddef max_samples_by_conf(n_inl: int, num_tc: int, sample_size: int, conf: float) -> int:"""Update max_iter to stop iterations earlier https://en.wikipedia.org/wiki/Random_sample_consensus.@@ -487,7 +580,8 @@ class RANSAC(nn.Module):generator = Noneif self.seed is not None:generator = torch.Generator(device=kp1.device)- generator.manual_seed(self.seed + self.max_iter + iteration)+ # The sampling generators use seed + batch index, at most sample_budget of them.+ generator.manual_seed(self.seed + self.sample_budget + iteration)indices = inliers.nonzero().flatten()# Independent refits share the current consensus and run in one# solver batch, rather than max_lo_iters tiny accelerator calls.@@ -599,17 +693,21 @@ class RANSAC(nn.Module):"""self.validate_inputs(kp1, kp2, weights)best_score_total = -float("inf")- max_samples = self.max_iter * self.batch_sizenum_tc: int = len(kp1)+ budget = self.sample_budget+ batch_size = self.resolve_batch_size(num_tc, kp1.device)+ max_samples = budgetbest_model_total = torch.zeros(3, 3, dtype=kp1.dtype, device=kp1.device)inliers_best_total: torch.Tensor = torch.zeros(num_tc, device=kp1.device, dtype=torch.bool)# Only a minimal-solver model needs projecting onto the essential manifold; LO refits already are.best_needs_projection = False- for i in range(self.max_iter):- if i * self.batch_size >= max_samples:+ for i in range(-(-budget // batch_size)):+ if i * batch_size >= max_samples:break- # Sample minimal samples in batch to estimate models- idxs = self.sample(self.minimal_sample_size, num_tc, self.batch_size, i, kp1.device)+ # Sample minimal samples in batch to estimate models. The last batch is truncated to the budget after+ # sampling, so that the PROSAC schedule and the seed follow the nominal batch size.+ current = min(batch_size, budget - i * batch_size)+ idxs = self.sample(self.minimal_sample_size, num_tc, batch_size, i, kp1.device)[:current]kp1_sampled = kp1[idxs]kp2_sampled = kp2[idxs]kp1_sampled, kp2_sampled = self.remove_bad_samples(kp1_sampled, kp2_sampled)@@ -640,9 +738,12 @@ class RANSAC(nn.Module):# sampled sets, not the number of roots returned by a minimal solver.# The bound follows the incumbent's own support, as in OpenCV's USAC: under# MSAC a better-scoring model can have less support than the one it replaced.- if not self.prosac_sampling:+ # PROSAC also tests ranked prefixes, which is where its speed comes from.+ if self.prosac_sampling:+ max_samples = self._prosac_max_samples(inliers, int(num_inliers))+ else:max_samples = min(- self.max_iter * self.batch_size,+ budget,self.max_samples_by_conf(int(num_inliers), num_tc, self.minimal_sample_size, self.confidence),)# The best model may come from the 5-point minimal solver (find_essential), which is notdiff --git a/tests/geometry/test_homography.py b/tests/geometry/test_homography.pyindex 2191fd3c0..61679c67d 100644--- a/tests/geometry/test_homography.py+++ b/tests/geometry/test_homography.py@@ -678,6 +678,25 @@ class TestHomographyNormalization(BaseTester):class TestFindHomographyDLTIter(BaseTester):+ def test_initial_solve_uses_weighted_normalization(self, device, dtype):+ points1 = torch.tensor(+ [[[0.0, 0.0], [1.0, 0.0], [0.0, 1.0], [2.0, 1.0], [1.0, 2.0], [2.0, 2.0], [100.0, -100.0]]],+ device=device,+ dtype=dtype,+ )+ points2 = torch.tensor(+ [[[2.0, 3.0], [3.1, 3.0], [2.0, 4.0], [4.0, 4.1], [3.0, 5.0], [4.1, 5.1], [-100.0, 100.0]]],+ device=device,+ dtype=dtype,+ )+ weights = torch.tensor([[1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0]], device=device, dtype=dtype)++ # A zero-weight outlier must not change Hartley normalization in the first IRLS solve.+ self.assert_close(+ find_homography_dlt_iterated(points1, points2, weights, n_iter=1),+ find_homography_dlt(points1, points2, weights),+ )+def test_smoke(self, device, dtype):points1 = torch.rand(1, 4, 2, device=device, dtype=dtype)points2 = torch.rand(1, 4, 2, device=device, dtype=dtype)@@ -958,17 +977,20 @@ class TestConventionHomography(BaseTester):pytest.skip(_F16_LU)p1, p2, _ = _planar(device, dtype)if model == "points":- name, iterated, args = "find_homography_dlt", find_homography_dlt_iterated, (p1, p2)+ # Count the point polisher's DLT solves across iterations.+ name, iterated, args = "_homography_from_dlt_system", find_homography_dlt_iterated, (p1, p2)+ plain = find_homography_dltelse:name = "find_homography_lines_dlt"iterated, args = find_homography_lines_dlt_iterated, (p1.reshape(1, 6, 2, 2), p2.reshape(1, 6, 2, 2))- plain = getattr(kornia.geometry.homography, name)+ plain = getattr(kornia.geometry.homography, name)+ solve = getattr(kornia.geometry.homography, name)weights = torch.ones(1, args[0].shape[1], device=device, dtype=dtype)calls = []def spy(*a, **k):calls.append(1)- return plain(*a, **k)+ return solve(*a, **k)monkeypatch.setattr(kornia.geometry.homography, name, spy)# n_iter counts the solves, the initial one included, so n_iter=1 is the plain solver.@@ -1022,7 +1044,7 @@ class TestConventionHomography(BaseTester):assert errors[1] > 1.9 * errors[0]@pytest.mark.parametrize("model", ["points", "lines"])- def test_wart_find_homography_dlt_iterated_weight_unsquared_4870(self, model, device, dtype, monkeypatch):+ def test_convention_find_homography_dlt_iterated_gaussian_weights_4870(self, model, device, dtype, monkeypatch):if model == "points" and dtype == torch.float16:pytest.skip(_F16_LU)if model == "lines":@@ -1042,28 +1064,44 @@ class TestConventionHomography(BaseTester):name, iterated, args, k = "find_homography_lines_dlt", find_homography_lines_dlt_iterated, (ls1, ls2), 2def error(H):- return line_segment_transfer_error_one_way(ls1, ls2, H, squared=False)+ # The kernel's e is the perpendicular distance in pixels: the residual of+ # line_segment_transfer_error_one_way divided by the image-2 segment length it carries (#4867).+ length = (ls2[..., 1, :] - ls2[..., 0, :]).norm(dim=-1)+ return line_segment_transfer_error_one_way(ls1, ls2, H, squared=False) / lengthplain = getattr(kornia.geometry.homography, name)weights = torch.ones(1, args[0].shape[1], device=device, dtype=dtype)- # soft_inl_th is set from the moved correspondence's first-solve error e_k, so that its weight under the- # linear kernel is exp(-1/2) whatever the error's scale.- sigma = float(error(plain(*args, weights))[0, k].sqrt())+ # soft_inl_th is set to the moved correspondence's first-solve error e_k, so that its Gaussian weight is+ # exp(-1/2) whatever the error's scale.+ sigma = float(error(plain(*args, weights))[0, k])calls = []- def spy(a, b, w=None, *rest):- H = plain(a, b, w, *rest)- calls.append((w, H))- return H+ if model == "points":+ # The point polisher's solver takes the weights as its second argument.+ name = "_homography_from_dlt_system"+ solve = kornia.geometry.homography._homography_from_dlt_system++ def spy(system, w, *rest):+ H = solve(system, w, *rest)+ calls.append((w, H))+ return H++ else:++ def spy(a, b, w=None, *rest):+ H = plain(a, b, w, *rest)+ calls.append((w, H))+ return Hmonkeypatch.setattr(kornia.geometry.homography, name, spy)iterated(*args, weights, soft_inl_th=sigma, n_iter=2)assert len(calls) == 2e = error(calls[0][1])- # #4870: the second solve weights each correspondence by exp(-e / (2 sigma^2)) with the unsquared error e,- # which for the moved correspondence is far from the Gaussian exp(-e^2 / (2 sigma^2)).- self.assert_close(calls[1][0], torch.exp(-e / (2.0 * sigma**2)))- assert (calls[1][0] - torch.exp(-(e**2) / (2.0 * sigma**2)))[0, k].abs() > 0.1+ # The second solve weights each correspondence by the Gaussian exp(-e^2 / (2 sigma^2)) of its error e, so+ # soft_inl_th is a standard deviation in the error's units (#4870 used exp(-e / (2 sigma^2))).+ self.assert_close(calls[1][0], torch.exp(-(e**2) / (2.0 * sigma**2)))+ self.assert_close(calls[1][0][0, k], torch.full((), 0.5, device=device, dtype=dtype).neg().exp())+ assert (calls[1][0] - torch.exp(-e / (2.0 * sigma**2)))[0, k].abs() > 0.1def test_wart_transfer_error_exact_match_is_sqrt_eps_4881(self, device, dtype):_skip_half(diff --git a/tests/geometry/test_ransac.py b/tests/geometry/test_ransac.pyindex 8406f60e8..354d4ea22 100644--- a/tests/geometry/test_ransac.py+++ b/tests/geometry/test_ransac.py@@ -345,6 +345,41 @@ class TestRANSACLocalOptimization(BaseTester):assert len(calls) > 0, "the local-optimization step never ran"self.assert_close(Fm, good_fit[0])+ def test_line_segment_polish_improves_the_fit(self, device, dtype):+ if dtype in (torch.float16, torch.bfloat16):+ pytest.skip("line_segment_transfer_error_one_way overflows half precision on 600 px coordinates")+ # Segments about 100 px long, half of them outliers. The polisher's Gaussian weights are on the perpendicular+ # distance in pixels, not on the length-scaled residual of line_segment_transfer_error_one_way (#4867), so+ # local optimization refines the minimal-sample model instead of fitting a handful of segments.+ torch.manual_seed(0)+ H = torch.tensor([[1.1, 0.05, 20.0], [0.02, 0.95, -10.0], [1e-4, 2e-4, 1.0]], device=device, dtype=dtype)+ centers = torch.rand(300, 2, device=device, dtype=dtype) * 600+ half = torch.randn(300, 2, device=device, dtype=dtype)+ half = 50 * half / half.norm(dim=-1, keepdim=True)+ ls1 = torch.stack([centers - half, centers + half], 1)+ ls2_clean = transform_points(H[None], ls1.reshape(1, -1, 2)).reshape(300, 2, 2)+ ls2 = ls2_clean + 0.3 * torch.randn_like(ls2_clean)+ ls2[150:] = torch.rand(150, 2, 2, device=device, dtype=dtype) * 600++ def endpoint_error(model):+ mapped = transform_points(model[None], ls1[:150].reshape(1, -1, 2)).reshape(150, 2, 2)+ return float((mapped - ls2_clean[:150]).norm(dim=-1).mean())++ errors = {}+ for max_lo_iters in (0, 5):+ ransac = RANSAC(+ "homography_from_linesegments",+ inl_th=2.0,+ batch_size=1024,+ max_iter=4,+ max_lo_iters=max_lo_iters,+ seed=0,+ confidence=1.0,+ )+ errors[max_lo_iters] = endpoint_error(ransac(ls1, ls2)[0])+ assert errors[5] < errors[0]+ assert errors[5] < 1.0+class TestRansacMethods:def test_max_samples_by_conf(self):@@ -456,6 +491,32 @@ class TestRANSACSeed:ransac = RANSAC("homography")assert ransac.seed is None+ def test_local_optimization_has_its_own_seed_stream(self, device, dtype, monkeypatch):+ # More batches than max_iter: the subset-refit generator must not reuse a sampling generator's seed.+ seeds = []++ class Spy(torch.Generator):+ def manual_seed(self, seed):+ seeds.append(seed)+ return super().manual_seed(seed)++ monkeypatch.setattr(kornia.geometry.ransac.torch, "Generator", Spy)+ torch.manual_seed(0)+ kp1 = torch.rand(200, 2, device=device, dtype=dtype) * 100+ ransac = RANSAC(+ "homography",+ inl_th=1.0,+ batch_size=16,+ max_iter=1,+ max_samples=64,+ seed=0,+ lo_sample_size=8,+ confidence=1.0,+ )+ ransac(kp1, kp1.clone())+ assert len(seeds) > 4 # four sampling batches and at least one local optimization+ assert len(seeds) == len(set(seeds))+class TestRANSACEssential(BaseTester):def test_smoke(self, device, dtype):@@ -1018,15 +1079,251 @@ class TestRANSACSampling(BaseTester):expected = 40000 / populationassert (counts - expected).abs().max() < 7 * math.sqrt(expected)- def test_prosac_does_not_use_uniform_confidence(self, device, dtype):+ @pytest.mark.parametrize("confidence,batches", [(0.99, 1), (1.0, 3)])+ def test_prosac_confidence(self, device, dtype, confidence, batches):+ points = torch.rand(20, 2, device=device, dtype=dtype)+ matrix = torch.eye(3, device=device, dtype=dtype)[None]+ ransac = RANSAC(+ "homography", batch_size=8, max_iter=3, max_lo_iters=0, prosac_sampling=True, confidence=confidence+ )+ calls = []+ ransac.remove_bad_samples = lambda a, b: (a, b)+ ransac.minimal_solver = lambda a, b, w: calls.append(1) or matrix+ ransac(points, points)+ assert len(calls) == batches++ def test_prosac_stopping_uses_ranking(self, device):+ ransac = RANSAC("fundamental", batch_size=16, max_iter=256, prosac_sampling=True)+ # 150 inliers of 500: ranked first, one draw from the top-150 prefix certifies the model.+ # Ranked last, no prefix qualifies and the uniform bound (over 60,000 draws) caps at the budget.+ ranked = torch.arange(500, device=device) < 150+ assert ransac._prosac_max_samples(ranked, 150) == 1+ assert ransac._prosac_max_samples(ranked.flip(0), 150) == 4096++ @pytest.mark.parametrize("support", [0, 8, 9, 50, 99])+ def test_prosac_stopping_rejects_small_prefix_support(self, device, support):+ ransac = RANSAC("fundamental", batch_size=16, max_iter=256, prosac_sampling=True)+ # Fewer than 20% of all correspondences cannot terminate, however perfect the prefix+ # (OpenCV USAC guard): the top ten all-inlier matches of a locally fitted model are no evidence.+ inliers = torch.arange(500, device=device) < support+ assert ransac._prosac_max_samples(inliers, support) == 4096++ def test_prosac_stopping_without_replacement(self, device):+ ransac = RANSAC("homography", batch_size=16, max_iter=256, prosac_sampling=True)+ # The best prefix is the whole set. C(10,4)/C(20,4) requires 104 draws+ # for 99% confidence; the with-replacement approximation gives only 72.+ inliers = torch.arange(20, device=device) >= 10+ assert ransac._prosac_max_samples(inliers, 10) == 104+ assert ransac.max_samples_by_conf(10, 20, 4, 0.99) == 104+ ransac.confidence = 1+ assert ransac._prosac_max_samples(inliers, 10) == 4096++ def test_prosac_stopping_never_exceeds_uniform_bound(self, device):+ ransac = RANSAC("homography", batch_size=16, max_iter=256, prosac_sampling=True)+ generator = torch.Generator().manual_seed(0)+ for _ in range(20):+ inliers = (torch.rand(300, generator=generator) < 0.4).to(device)+ support = int(inliers.sum())+ uniform = min(4096, ransac.max_samples_by_conf(support, 300, 4, 0.99))+ assert 1 <= ransac._prosac_max_samples(inliers, support) <= uniform++ @pytest.mark.parametrize("replace_incumbent", [False, True])+ def test_prosac_stopping_after_multiple_batches(self, device, dtype, replace_incumbent):points = torch.rand(20, 2, device=device, dtype=dtype)matrix = torch.eye(3, device=device, dtype=dtype)[None]- ransac = RANSAC("homography", batch_size=8, max_iter=3, max_lo_iters=0, prosac_sampling=True)+ ransac = RANSAC(+ "homography", batch_size=16, max_iter=16, max_lo_iters=0, score_type="msac", prosac_sampling=True+ )calls = []ransac.remove_bad_samples = lambda a, b: (a, b)ransac.minimal_solver = lambda a, b, w: calls.append(1) or matrix++ def verify(a, b, models, threshold):+ # The initial incumbent requires 104 draws (seven batches). A+ # better MSAC score with less support needs the entire budget.+ replace = replace_incumbent and len(calls) >= 2+ mask = torch.arange(20, device=device) >= (15 if replace else 10)+ return matrix[0], mask, 2.0 if replace else 1.0, float(mask.sum())++ ransac.verify = verify+ for _ in range(2):+ calls.clear()+ ransac(points, points)+ assert len(calls) == (16 if replace_incumbent else 7)++ def test_prosac_minimal_population(self, device):+ ransac = RANSAC("homography", batch_size=16, max_iter=256, prosac_sampling=True)+ assert ransac._prosac_max_samples(torch.ones(4, device=device, dtype=torch.bool), 4) == 4096++ def test_prosac_stopping_respects_growth(self, device):+ ransac = RANSAC("fundamental", batch_size=16, max_iter=256, prosac_sampling=True)+ # 45 inliers among the top 100 of 200 pass the support guards, but the 3970 draws that+ # prefix needs exceed the ~106 draws PROSAC takes from it: later draws sampled larger+ # prefixes and must not be credited to the top 100. The uniform bound caps at the budget.+ inliers = torch.zeros(200, device=device, dtype=torch.bool)+ inliers[:90:2] = True+ assert ransac._prosac_max_samples(inliers, 45) == 4096+ assert ransac._prosac_schedule(8, 200, inliers.device)[100 - 8].item() < 3970++ def test_prosac_stops_on_a_certified_prefix(self, device, dtype):+ if dtype in (torch.float16, torch.bfloat16):+ pytest.skip("a 1 px threshold on 500 px coordinates is below half-precision resolution")+ # 150 of 500 correspondences follow the homography and are ranked first: PROSAC stops after+ # its first batch, while uniform sampling needs far more than one batch of 16 at 30% inliers.+ torch.manual_seed(0)+ matrix = torch.tensor([[1.1, 0.05, 20.0], [0.02, 0.95, -10.0], [1e-4, -2e-4, 1.0]], device=device, dtype=dtype)+ points1 = torch.rand(500, 2, device=device, dtype=dtype) * 800+ points2 = transform_points(matrix[None], points1[None])[0]+ points2[150:] = torch.rand(350, 2, device=device, dtype=dtype) * 800+ calls = []+ for prosac in (True, False):+ ransac = RANSAC(+ "homography", inl_th=1.0, batch_size=16, max_iter=64, max_lo_iters=0, prosac_sampling=prosac, seed=0+ )+ sample = ransac.sample+ count = []+ ransac.sample = lambda *a, _s=sample, _c=count, **k: _c.append(1) or _s(*a, **k)+ _, mask = ransac(points1, points2)+ calls.append(len(count))+ assert mask[:150].all()+ assert calls[0] == 1+ assert calls[1] > 1+++class TestRANSACAutoBatch(BaseTester):+ def test_default_is_auto_with_the_historical_budget(self):+ ransac = RANSAC("homography")+ assert ransac.batch_size == "auto"+ assert ransac.sample_budget == 2048 * 10++ @pytest.mark.parametrize("bad", [0, -1, 2.5, True, "large"])+ def test_rejects_bad_batch_size(self, bad):+ with pytest.raises(ValueError):+ RANSAC("homography", batch_size=bad)++ @pytest.mark.parametrize("bad", [0, -5, True, 1000.0])+ def test_rejects_bad_max_samples(self, bad):+ with pytest.raises(ValueError):+ RANSAC("homography", max_samples=bad)++ def test_explicit_batch_keeps_its_budget(self):+ ransac = RANSAC("fundamental", batch_size=512, max_iter=4)+ assert ransac.sample_budget == 2048+ assert ransac.resolve_batch_size(5000, torch.device("cpu")) == 512+ assert ransac.resolve_batch_size(5000, torch.device("cuda")) == 512++ def test_max_samples_overrides_the_budget(self):+ assert RANSAC("homography", batch_size=256, max_iter=100, max_samples=1000).sample_budget == 1000+ assert RANSAC("homography", max_samples=1000).sample_budget == 1000++ def test_budget_follows_later_attribute_changes(self):+ # The budget is read at call time, like confidence, so configuring the module after construction works.+ ransac = RANSAC("homography", batch_size=256)+ ransac.max_iter = 100+ assert ransac.sample_budget == 25600+ ransac.max_samples = 1000+ assert ransac.sample_budget == 1000++ def test_accelerator_batch_shrinks_for_many_correspondences(self):+ # The residual matrix is batch x N: past 2**27 entries (1 GiB in float32 at peak) the batch shrinks, down to+ # the 2048 of the fixed historical batch, so the default cannot run out of memory where it did not before.+ cuda = torch.device("cuda")+ ransac = RANSAC("homography")+ assert ransac.resolve_batch_size(16384, cuda) == 8192+ assert ransac.resolve_batch_size(50000, cuda) == 2684+ assert ransac.resolve_batch_size(1_000_000, cuda) == 2048+ assert RANSAC("fundamental").resolve_batch_size(1_000_000, cuda) == 2048++ def test_accelerators_take_large_batches(self):+ ransac = RANSAC("homography", max_samples=5000)+ for device in (torch.device("cuda"), torch.device("mps")):+ assert ransac.resolve_batch_size(500, device) == 5000+ assert RANSAC("homography").resolve_batch_size(500, torch.device("cuda")) == 8192+ assert RANSAC("homography_from_linesegments").resolve_batch_size(500, torch.device("cuda")) == 8192+ # The epipolar solvers are compute-bound past 2048 hypotheses on the GPU.+ assert RANSAC("fundamental").resolve_batch_size(500, torch.device("cuda")) == 2048+ assert RANSAC("essential", max_samples=1000).resolve_batch_size(500, torch.device("mps")) == 1000++ @pytest.mark.parametrize("backend", ["xla", "privateuseone"])+ def test_other_devices_keep_historical_batch(self, backend):+ device = torch.device(backend)+ assert RANSAC("homography").resolve_batch_size(500, device) == 2048+ assert RANSAC("fundamental").resolve_batch_size(500, device) == 2048+ assert RANSAC("homography", max_samples=1000).resolve_batch_size(500, device) == 1000++ @pytest.mark.parametrize(+ "model_type,num_tc,expected",+ [+ ("homography", 100, 2048),+ ("homography", 500, 1048),+ ("homography", 4000, 256),+ ("fundamental", 100, 512),+ ("fundamental", 500, 262),+ ("fundamental", 4000, 128),+ ("essential", 4000, 128),+ ],+ )+ def test_cpu_batch_follows_model_and_point_count(self, model_type, num_tc, expected):+ assert RANSAC(model_type).resolve_batch_size(num_tc, torch.device("cpu")) == expected+ assert RANSAC(model_type, max_samples=200).resolve_batch_size(num_tc, torch.device("cpu")) == min(expected, 200)++ def test_last_batch_is_truncated_to_the_budget(self, device, dtype):+ points = torch.rand(20, 2, device=device, dtype=dtype)+ matrix = torch.eye(3, device=device, dtype=dtype)[None]+ ransac = RANSAC("homography", batch_size=16, max_samples=40, max_lo_iters=0, confidence=1.0)+ sizes = []+ ransac.remove_bad_samples = lambda a, b: sizes.append(len(a)) or (a, b)+ ransac.minimal_solver = lambda a, b, w: matrixransac(points, points)- assert len(calls) == 3+ assert sizes == [16, 16, 8]++ def test_truncated_last_batch_continues_the_prosac_schedule(self, device, dtype):+ # The PROSAC schedule counts draws, not batches: the truncated last batch of a 1000-draw budget takes draws+ # 801 to 1000, from the largest prefixes, rather than restarting at an earlier point of the schedule.+ num_tc = 100+ points = torch.arange(num_tc, device=device, dtype=dtype)[:, None].expand(num_tc, 2)+ matrix = torch.eye(3, device=device, dtype=dtype)[None]+ ransac = RANSAC(+ "homography", batch_size=400, max_samples=1000, prosac_sampling=True, max_lo_iters=0, confidence=1.0+ )+ batches = []+ ransac.remove_bad_samples = lambda a, b: (a, b)+ ransac.minimal_solver = lambda a, b, w: batches.append(a[..., 0].long()) or matrix.expand(len(a), 3, 3)+ ransac(points, points)+ assert [len(b) for b in batches] == [400, 400, 200]+ ends = ransac._prosac_schedule(4, num_tc, points.device)+ assert int(ends[-1]) >= 1000 # the schedule is still growing at the last draw+ # Every growth draw includes the newest correspondence of its prefix, so the largest index a batch draws is+ # the prefix its last draw belongs to.+ last_draws = torch.tensor([400, 800, 1000], device=points.device)+ expected = (torch.searchsorted(ends, last_draws) + 4).tolist()+ assert [int(b.max()) + 1 for b in batches] == expected++ def test_auto_batch_forward_matches_explicit_batch(self, device, dtype):+ if dtype in (torch.float16, torch.bfloat16):+ pytest.skip("a 1 px threshold on 500 px coordinates is below half-precision resolution")+ # The auto batch is a plain batch size: the same seed gives the same draws as that size given explicitly.+ torch.manual_seed(0)+ kp1 = torch.rand(200, 2, device=device, dtype=dtype) * 500+ matrix = torch.tensor([[1.0, 0.1, 5.0], [0.0, 1.0, 3.0], [0.0, 0.0, 1.0]], device=device, dtype=dtype)+ kp2 = transform_points(matrix[None], kp1[None])[0]+ kp2[:60] = torch.rand(60, 2, device=device, dtype=dtype) * 500+ auto = RANSAC("homography", inl_th=1.0, seed=0)+ explicit = RANSAC("homography", inl_th=1.0, batch_size=auto.resolve_batch_size(200, kp1.device), seed=0)+ H_auto, mask_auto = auto(kp1, kp2)+ H_explicit, mask_explicit = explicit(kp1, kp2)+ assert torch.equal(mask_auto, mask_explicit)+ self.assert_close(H_auto, H_explicit)+ assert mask_auto[60:].all()+++class TestRANSACPolisherScale(BaseTester):+ @pytest.mark.parametrize("model_type", ["homography", "homography_from_linesegments"])+ @pytest.mark.parametrize("inl_th", [0.5, 2.0])+ def test_polisher_gaussian_scale_is_inlier_threshold(self, model_type, inl_th):+ # The IRLS polisher's Gaussian re-weighting uses the inlier threshold as its standard deviation.+ ransac = RANSAC(model_type, inl_th=inl_th)+ assert ransac.polisher_solver.keywords == {"soft_inl_th": inl_th}class TestRANSACBoundedLO(BaseTester):diff --git a/tests/test_heb_benchmark.py b/tests/test_heb_benchmark.pynew file mode 100644index 000000000..366700f97--- /dev/null+++ b/tests/test_heb_benchmark.py@@ -0,0 +1,78 @@+# 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.+#++"""Budget accounting for the HEB RANSAC benchmark."""++from __future__ import annotations++from argparse import Namespace+from types import SimpleNamespace++import numpy as np+import pytest+import torch++from benchmarks.geometry import heb+++def test_legacy_estimator_requires_exact_budget(monkeypatch):+ def legacy_ransac(*args, **kwargs):+ if "max_samples" in kwargs:+ raise TypeError("unexpected keyword argument 'max_samples'")+ return SimpleNamespace(**kwargs)++ monkeypatch.setattr(heb, "RANSAC", legacy_ransac)+ args = Namespace(threshold=1.0, confidence=1.0, score="msac")+ config = {"batch_size": 600, "budget": 1000, "max_lo_iters": 0, "prosac": False}+ with pytest.raises(SystemExit, match="budget must be divisible by batch size"):+ heb.make_estimator(args, config, 0)++ config["budget"] = 1200+ assert heb.make_estimator(args, config, 0).max_iter == 2+++def test_reported_samples_exclude_truncated_tail(monkeypatch):+ matches = np.zeros((6, 10), dtype=np.float32)+ matches[:, :2] = [[0, 0], [1, 0], [0, 1], [1, 1], [2, 0], [0, 2]]+ matches[:, 2:4] = matches[:, :2]+ matches[:, 8] = 0.1+ monkeypatch.setattr(heb, "setup_run", lambda *args, **kwargs: (torch.device("cpu"), torch.float32, None))+ monkeypatch.setattr(heb, "start_run", lambda *args, **kwargs: {})+ monkeypatch.setattr(heb, "load_pairs", lambda args: {"pair": {"matches": matches}})+ rows = []+ monkeypatch.setattr(heb, "finish_run", lambda args, name, meta, result: rows.extend(result))+ args = Namespace(+ h5="unused.h5",+ pairs=1,+ pair_seed=0,+ snn=0.8,+ threshold=1.0,+ confidence=1.0,+ score="msac",+ min_run_time=0.01,+ batches="400",+ budgets="1000",+ lo="0",+ prosac="off",+ seeds="0",+ timing_pairs=0,+ )++ heb.run(args)++ assert rows[0]["batches"] == 3+ assert rows[0]["sampled_sets"] == 1000