Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

feat(geometry): RANSAC(compile=True), the whole LM estimation as one compiled graph (#5117)

Dmytro Mishkinb25d31194f1c
diff --git a/benchmarks/README.md b/benchmarks/README.md
index 6bc879f74..1cfda8ca1 100644
--- a/benchmarks/README.md
+++ b/benchmarks/README.md
@@ -49,6 +49,17 @@ extraction, matching and homography quality on CPU, CUDA or MPS;
### CPU RANSAC base/branch comparison
+For a self-contained latency and recovery comparison without downloaded data, run
+`geometry/ransac_compile_synthetic.py --compile --json /tmp/ransac.json` from
+each checkout. It measures H/F7/F8/E public forward calls on fixed noisy scenes,
+with separate repeated medians for each estimator seed. Use `--confidence 1
+--max-samples 2048` to compare equal sample budgets, and `--sample-batch` to
+inspect explicit batch sizes. Compilation and loading are warmed outside the
+timed region. The JSON records the sampling configuration, artifact mode,
+source digests, inlier recall and false positives alongside latency. PR #5117's
+[follow-up comparison](geometry/ransac_compile_results/followup.md) records the
+cache/RNG/refinement fixes and the speed/memory tradeoffs of splitting large CPU batches.
+
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:
diff --git a/benchmarks/geometry/ransac_compile_results/followup.md b/benchmarks/geometry/ransac_compile_results/followup.md
new file mode 100644
index 000000000..d8170ae1e
--- /dev/null
+++ b/benchmarks/geometry/ransac_compile_results/followup.md
@@ -0,0 +1,170 @@
+# PR #5117 follow-up: correctness and CPU speed
+
+Compared the original PR head `eedc9996b` with the revised implementation `82443d5af`.
+The revisions include the same benchmark harness; its hash is recorded in every result.
+
+On Apple M1 the large explicit homography batch is **2.19Γ— faster** with confidence stopping and
+unchanged true-inlier recall. Equal-budget default cases are within 4% of the previous throughput;
+these small differences are not evidence of a broad speedup. On M1 a fully exhausted large
+batch is about 5% slower after splitting; on an Intel i7-14700K it is **2Γ— faster**, so the split
+also raises scoring throughput there (see [Intel CPU and CUDA](#intel-cpu-and-cuda)). Default F7
+is about 6% slower over the extended 16-seed set (6–11% on the i7). The private random stream
+changes which samples lead to confidence stopping, so default timings include sampling/stopping
+variance; equal-budget timings help separate that effect from computation throughput. This is a
+targeted improvement, not a universal speedup. On CUDA the change is neutral except for
+homographies and essential matrices, about 6% and 3% slower when both revisions run in one process.
+
+## Changes measured
+
+- Use a private generator in a compiled sampler primitive, avoiding global RNG save/restore
+ and races between seeded calls and unrelated random draws. No execution lock serializes calls.
+- Split compiled CPU sampling batches whose candidate-by-correspondence matrix would exceed
+ `2**22` entries. For H with N=5000 and requested batch 8192, the maximum possible matrix
+ drops from 40,960,000 to 4,190,000 entries per batch. This is an allocation bound, not an RSS
+ measurement. Extra boundaries permit earlier confidence stopping; confidence=1 retains
+ the entire sample budget and exposes the throughput tradeoff.
+- Protect excluded rows before singular projective/Sampson divisions and mask the resulting
+ residuals/Jacobians. Remove an unnecessary homography target concatenation.
+- Distinguish thread count/default dtype/default device in artifact keys, disable autocast
+ consistently, fall back to tracing on artifact guard rejection, and publish artifacts atomically.
+
+## Method
+
+Apple M1, macOS 26.5.1 arm64, PyTorch 2.14.0, Python 3.11.14, CPU float32, four intra-op threads.
+Both revisions used the same interpreter and preloaded synthetic scenes, 50% true inliers,
+0.5-pixel noise, and a 1.5-pixel threshold (camera-normalized for E). N=2000 uses one fixed
+planar/two-view scene per model; N=5000 uses a separate fixed planar scene.
+
+Timed public `RANSAC.forward`, including staging, scoring, local optimization and final
+refinement. Constructor and first-call compilation are excluded. The shared benchmark
+helpers warm the CPU and use `torch.utils.benchmark.Timer.blocked_autorange`; raw rows contain
+per-seed medians and IQRs. Runs were serial, with test/compilation workers stopped during
+timing. Artifact mode was disabled for both revisions (`KORNIA_RANSAC_AOT=0`) to keep the
+comparison independent of the original cache compatibility bug. First calls warm compilation
+before any timing. Source location was verified and source digests recorded.
+
+The table reports the **median of the per-seed latency medians**, not a pooled-call median.
+Default, fixed-budget and large-batch cases use seeds 0,1,2 and a one-second minimum timing
+window per cell. The supplemental default-F7 case uses seeds 0–15 and 0.5 seconds per cell;
+it was added to investigate the initial three-seed F7 regression, and those original results
+are retained. Default confidence is 0.999 and budget 20480. Fixed-budget cases use confidence=1
+and the stated sample budget. Default batches use `auto`; large cases request batch 8192.
+
+| Case | Model | Original compiled ms | Revised compiled ms | Original/revised |
+| --- | --- | ---: | ---: | ---: |
+| Default, N=2000 | H | 7.91 | 7.54 | 1.05Γ— |
+| Default, N=2000 | F7 | 17.01 | 19.11 | 0.89Γ— |
+| Default, N=2000 | F8 | 14.92 | 15.09 | 0.99Γ— |
+| Default, N=2000 | E | 18.13 | 17.60 | 1.03Γ— |
+| 2048 samples, N=2000 | H | 11.50 | 11.08 | 1.04Γ— |
+| 2048 samples, N=2000 | F7 | 24.95 | 24.76 | 1.01Γ— |
+| 2048 samples, N=2000 | F8 | 15.90 | 15.41 | 1.03Γ— |
+| 2048 samples, N=2000 | E | 96.89 | 95.14 | 1.02Γ— |
+| Batch 8192, N=5000 | H | 37.73 | 17.26 | 2.19Γ— |
+| 8192 samples/batch, N=5000 | H | 39.27 | 41.25 | 0.95Γ— |
+| Default F7, 16 seeds | F7 | 18.54 | 19.61 | 0.95Γ— |
+
+Some large-batch and supplemental F7 timing rows have wide IQRs; consult the raw data before
+interpreting small changes. These results cover one CPU and controlled scenes, not real-world
+pose accuracy, other platforms, CUDA throughput, cold compilation, or concurrent throughput.
+
+## Intel CPU and CUDA
+
+Intel Core i7-14700K (WSL2) and NVIDIA RTX 4090, PyTorch 2.14.0+cu130, Python 3.11.14, float32,
+four intra-op threads. Same harness, cases and seeds as above, with `KORNIA_RANSAC_AOT=0`, timing
+only the compiled backend. Each case ran twice per revision in opposite orders (original then
+revised, then revised then original); both rounds are shown as `round 1 / round 2`.
+
+| Case | Model | Original compiled ms | Revised compiled ms | Original/revised |
+| --- | --- | ---: | ---: | ---: |
+| Default, N=2000 | H | 4.11 / 4.15 | 4.18 / 4.11 | 0.98Γ— / 1.01Γ— |
+| Default, N=2000 | F7 | 6.51 / 6.75 | 8.40 / 8.31 | 0.77Γ— / 0.81Γ— |
+| Default, N=2000 | F8 | 5.89 / 5.95 | 6.44 / 6.28 | 0.91Γ— / 0.95Γ— |
+| Default, N=2000 | E | 8.24 / 7.86 | 8.58 / 8.53 | 0.96Γ— / 0.92Γ— |
+| 2048 samples, N=2000 | H | 5.00 / 5.17 | 4.99 / 5.17 | 1.00Γ— / 1.00Γ— |
+| 2048 samples, N=2000 | F7 | 9.38 / 9.64 | 9.73 / 10.03 | 0.96Γ— / 0.96Γ— |
+| 2048 samples, N=2000 | F8 | 6.20 / 6.72 | 6.24 / 6.32 | 0.99Γ— / 1.06Γ— |
+| 2048 samples, N=2000 | E | 44.24 / 45.58 | 44.23 / 45.67 | 1.00Γ— / 1.00Γ— |
+| Batch 8192, N=5000 | H | 29.80 / 28.94 | 8.97 / 8.90 | 3.32Γ— / 3.25Γ— |
+| 8192 samples/batch, N=5000 | H | 29.78 / 29.61 | 14.78 / 15.42 | 2.02Γ— / 1.92Γ— |
+| Default F7, 16 seeds | F7 | 6.79 / 7.48 | 7.66 / 7.97 | 0.89Γ— / 0.94Γ— |
+
+The default F7 seeds range from 5.9 to 10.5 ms depending on the batch at which confidence stops,
+against a within-seed IQR of about 0.2 ms; the equal-budget F7 cost is 4%.
+
+CUDA, N=2000 (the CPU batch split does not apply on CUDA):
+
+| Case | Model | Inliers | Original compiled ms | Revised compiled ms | Original/revised |
+| --- | --- | ---: | ---: | ---: | ---: |
+| Default | H | 50% | 8.72 / 8.35 | 10.03 / 9.74 | 0.87Γ— / 0.86Γ— |
+| Default | H | 20% | 9.69 / 8.96 | 11.45 / 11.19 | 0.85Γ— / 0.80Γ— |
+| Default | F7 | 50% | 7.19 / 7.22 | 7.05 / 7.08 | 1.02Γ— / 1.02Γ— |
+| Default | F7 | 20% | 13.32 / 12.46 | 12.54 / 12.75 | 1.06Γ— / 0.98Γ— |
+| Default | F8 | 50% | 5.74 / 5.61 | 5.74 / 5.57 | 1.00Γ— / 1.01Γ— |
+| Default | F8 | 20% | 8.79 / 8.74 | 8.30 / 8.56 | 1.06Γ— / 1.02Γ— |
+| Default | E | 50% | 7.49 / 7.38 | 7.87 / 7.62 | 0.95Γ— / 0.97Γ— |
+| Default | E | 20% | 239.27 / 235.56 | 239.87 / 244.96 | 1.00Γ— / 0.96Γ— |
+| 2048 samples | H | 50% | 7.99 / 8.31 | 9.50 / 9.37 | 0.84Γ— / 0.89Γ— |
+| 2048 samples | F8 | 50% | 5.82 / 5.48 | 5.51 / 5.31 | 1.06Γ— / 1.03Γ— |
+| 2048 samples | E | 50% | 50.39 / 48.76 | 51.25 / 48.25 | 0.98Γ— / 1.01Γ— |
+
+Equal-budget F7 on CUDA varied up to 2Γ— for the same seed between rounds and is omitted. Every
+revised homography seed at 50% inliers is slower in both rounds (9.7–10.1 ms against 8.3–8.8 ms)
+with the same 992 inliers.
+
+Separate processes exaggerate these CUDA differences on this host, whose host-side work moves
+between performance and efficiency cores. Loading both revisions into one process and alternating
+them over six rounds (default settings, N=2000, 50% inliers, all four programs compiled), the
+revised implementation took 0.94Γ— (H), 0.96Γ— (F7), 1.03Γ— (F8) and 0.97Γ— (E) of the original's
+throughput. The homography difference comes from masking the full residual and Jacobian of
+excluded rows in the refinement: a revision with the original `homography.py` was 4–13% faster.
+
+On CUDA with 20% inliers, where 7- and 8-point sampling rarely draws an all-inlier sample within the
+budget, 64 seeds gave a mean inlier recall of 0.843 Β± 0.021 (original) and 0.841 Β± 0.020 (revised,
+with the SplitMix64 batch seeds that followed) for F7, against 0.850 Β± 0.022 for eager; F8 gave
+0.557 Β± 0.030, 0.534 Β± 0.027 and 0.509 Β± 0.027. Three-seed differences at this ratio are sampling luck.
+
+## Recovery
+
+Every recorded call returned a model. True-inlier recall was unchanged across revisions:
+H=0.992 at N=2000, H=0.990 at N=5000, and F7/F8/E=1.000. H had zero false positives. In the
+extended F7 set, false positives ranged from 6–7 originally and 6–8 after the change, out of
+1000 synthetic outliers. The per-seed support and false-positive counts are included in the
+raw results; equal recall does not mean identical models or masks. These few fixed scenes
+are a regression diagnostic and do not establish general geometric accuracy.
+
+## Reproduce
+
+Run from each checkout root with the same interpreter, using an identical copy of
+`benchmarks/geometry/ransac_compile_synthetic.py` in the baseline checkout:
+
+```bash
+KORNIA_RANSAC_AOT=0 python benchmarks/geometry/ransac_compile_synthetic.py \
+ --compile --sizes 2000 --ratios 0.5 --seeds 0,1,2 --threads 4 --min-run-time 1 \
+ --json /tmp/default.json
+```
+
+For the fixed-budget case add `--confidence 1 --max-samples 2048`. For the large-batch case
+replace `--sizes 2000` with `--ops H --sizes 5000 --sample-batch 8192`. For the large fixed-budget
+case also add `--confidence 1 --max-samples 8192`. For the supplemental F7 case use
+`--ops F7 --seeds 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15 --min-run-time 0.5` with N=2000.
+
+| Raw case | Original PR head | Revised implementation |
+| --- | --- | --- |
+| default | [base](https://github.com/kornia/kornia/blob/733729055be12f2281625be82f0b4df350e2fc50/benchmarks/geometry/ransac_compile_results/eedc9996b-default.json) | [revised](https://github.com/kornia/kornia/blob/733729055be12f2281625be82f0b4df350e2fc50/benchmarks/geometry/ransac_compile_results/82443d5af-default.json) |
+| fixed-budget | [base](https://github.com/kornia/kornia/blob/733729055be12f2281625be82f0b4df350e2fc50/benchmarks/geometry/ransac_compile_results/eedc9996b-fixed-budget.json) | [revised](https://github.com/kornia/kornia/blob/733729055be12f2281625be82f0b4df350e2fc50/benchmarks/geometry/ransac_compile_results/82443d5af-fixed-budget.json) |
+| large-batch | [base](https://github.com/kornia/kornia/blob/733729055be12f2281625be82f0b4df350e2fc50/benchmarks/geometry/ransac_compile_results/eedc9996b-large-batch.json) | [revised](https://github.com/kornia/kornia/blob/733729055be12f2281625be82f0b4df350e2fc50/benchmarks/geometry/ransac_compile_results/82443d5af-large-batch.json) |
+| large-fixed-budget | [base](https://github.com/kornia/kornia/blob/733729055be12f2281625be82f0b4df350e2fc50/benchmarks/geometry/ransac_compile_results/eedc9996b-large-fixed-budget.json) | [revised](https://github.com/kornia/kornia/blob/733729055be12f2281625be82f0b4df350e2fc50/benchmarks/geometry/ransac_compile_results/82443d5af-large-fixed-budget.json) |
+| f7-seeds | [base](https://github.com/kornia/kornia/blob/733729055be12f2281625be82f0b4df350e2fc50/benchmarks/geometry/ransac_compile_results/eedc9996b-f7-seeds.json) | [revised](https://github.com/kornia/kornia/blob/733729055be12f2281625be82f0b4df350e2fc50/benchmarks/geometry/ransac_compile_results/82443d5af-f7-seeds.json) |
+
+## Validation
+
+- CPU float32/float64 geometry suite: 1217 passed, 32 skipped, 10 non-strict XPASS.
+- Compiled RANSAC CPU suite: 38 passed, including concurrent RNG isolation, full seed domain,
+ ambient guards, inference/autocast, large batches and fresh-process artifact reuse.
+- Focused CPU half precision: float16 19 passed/17 skipped; bfloat16 20 passed/16 skipped.
+- PyTorch 2.5.1 refinement and essential backward regression checks: 93 passed.
+- Full pre-commit checks and type checking passed. Benchmark artifacts validated against
+ `benchmarks.results_schema.validate_artefact`.
+- Independent review found no remaining actionable findings in the changed areas.
+- CUDA compilation/runtime and GPU performance remain unverified locally.
diff --git a/benchmarks/geometry/ransac_compile_synthetic.py b/benchmarks/geometry/ransac_compile_synthetic.py
new file mode 100644
index 000000000..043c38ef6
--- /dev/null
+++ b/benchmarks/geometry/ransac_compile_synthetic.py
@@ -0,0 +1,191 @@
+# 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.
+#
+
+"""Synthetic RANSAC latency and inlier recovery, eager versus RANSAC(compile=True).
+
+Uses preloaded float inputs, fixed planar/two-view scenes, 0.5-pixel noise, and a 1.5-pixel
+threshold (camera-normalized for essential matrices). Public forward includes staging and
+refinement; construction and first-call compilation/loading are excluded. Every seed has
+its own repeated median/IQR and recall/false-positive count, so stopping variance is visible.
+Run the identical harness from each checkout; the source path is printed and hashes recorded.
+These controlled scenes diagnose latency and recovery, not real-world pose accuracy.
+
+ python benchmarks/geometry/ransac_compile_synthetic.py --compile --json /tmp/ransac.json
+ python benchmarks/geometry/ransac_compile_synthetic.py --compile --confidence 1 --max-samples 2048
+"""
+
+from __future__ import annotations
+
+import argparse
+import hashlib
+import itertools
+import os
+import sys
+from functools import partial
+from pathlib import Path
+
+import torch
+
+ROOT = Path(__file__).resolve().parents[2]
+sys.path.insert(0, str(ROOT))
+sys.path.insert(1, str(ROOT / "benchmarks"))
+
+from common import add_flagship_args, finish_run, run_batch_sweep, setup_run, start_run # noqa: E402
+
+import kornia # noqa: E402
+from kornia.geometry import RANSAC, transform_points # noqa: E402
+from kornia.geometry.conversions import axis_angle_to_rotation_matrix, convert_points_from_homogeneous # noqa: E402
+
+MODELS = {"H": "homography", "F7": "fundamental", "F8": "fundamental_8pt", "E": "essential"}
+
+
+def scene(model: str, n: int, ratio: float) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
+ """Fixed scenes matching the RANSAC test geometry; independent of the estimator seed."""
+ g = torch.Generator().manual_seed(n)
+ f64 = torch.float64
+ outliers = round(n * (1 - ratio))
+ if model == "H":
+ h = torch.tensor([[1.1, 0.05, 20.0], [0.02, 0.95, -10.0], [1e-4, 2e-4, 1.0]], dtype=f64)
+ p = torch.rand(n, 2, generator=g, dtype=f64) * 600
+ q = transform_points(h[None], p[None])[0]
+ extent = torch.tensor([600.0, 600.0], dtype=f64)
+ else:
+ camera = torch.tensor([[800.0, 0.0, 320.0], [0.0, 800.0, 240.0], [0.0, 0.0, 1.0]], dtype=f64)
+ rotation = axis_angle_to_rotation_matrix(torch.tensor([[0.05, -0.1, 0.02]], dtype=f64))[0]
+ translation = torch.tensor([1.0, 0.1, 0.2], dtype=f64)
+ xyz = torch.randn(n, 3, generator=g, dtype=f64) * torch.tensor([2.0, 2.0, 1.0], dtype=f64)
+ xyz += torch.tensor([0.0, 0.0, 8.0], dtype=f64)
+ p = convert_points_from_homogeneous(xyz @ camera.T)
+ q = convert_points_from_homogeneous((xyz @ rotation.T + translation) @ camera.T)
+ extent = torch.tensor([640.0, 480.0], dtype=f64)
+ q = q + 0.5 * torch.randn(n, 2, generator=g, dtype=f64)
+ q[:outliers] = torch.rand(outliers, 2, generator=g, dtype=f64) * extent
+ if model == "E":
+ center = torch.tensor([320.0, 240.0], dtype=f64)
+ p, q = (p - center) / 800, (q - center) / 800
+ return p, q, torch.arange(n) >= outliers
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ add_flagship_args(parser, ops=tuple(MODELS), batches="", size=0)
+ parser.add_argument("--sizes", default="500,2000,5000")
+ parser.add_argument("--ratios", default="0.2,0.5")
+ parser.add_argument("--seeds", default="0,1,2")
+ parser.add_argument("--confidence", type=float, default=0.999)
+ parser.add_argument("--max-samples", type=int, default=20480)
+ parser.add_argument("--sample-batch", default="auto", help="auto or a fixed number of minimal samples")
+ args = parser.parse_args()
+ sizes = [int(v) for v in args.sizes.split(",")]
+ ratios = [float(v) for v in args.ratios.split(",")]
+ seeds = [int(v) for v in args.seeds.split(",")]
+ if min(sizes) < 9 or any(not 0 < r <= 1 for r in ratios) or min(seeds) < 0:
+ parser.error("sizes must be >=9, ratios in (0,1], and seeds nonnegative")
+ if args.device not in ("cpu", "cuda") or args.dtype not in ("float32", "float64"):
+ parser.error("use CPU/CUDA float32/float64")
+ batch = args.sample_batch if args.sample_batch == "auto" else int(args.sample_batch)
+ device, dtype, sync = setup_run(args, opencv=False)
+ meta = start_run(
+ "Synthetic RANSAC",
+ args,
+ device,
+ units="pairs/s",
+ regimes=[
+ "Public RANSAC.forward; first call excluded; independent timing per RANSAC seed",
+ "Eager and compiled streams differ; confidence=1 compares a fixed sample budget",
+ ],
+ )
+ print(f"# interpreter: {sys.executable}", flush=True)
+ assert Path(kornia.__file__).resolve().is_relative_to(ROOT)
+ meta.update(
+ sizes=sizes,
+ inlier_ratios=ratios,
+ seeds=seeds,
+ compile=args.compile,
+ artifact_enabled=os.environ.get("KORNIA_RANSAC_AOT", "1") != "0",
+ confidence=args.confidence,
+ max_samples=args.max_samples,
+ sample_batch=batch,
+ noise_px=0.5,
+ inlier_threshold_px=1.5,
+ min_run_time=args.min_run_time,
+ source_sha256={
+ str(p.relative_to(ROOT)): hashlib.sha256(p.read_bytes()).hexdigest()
+ for p in [
+ Path(__file__).resolve(),
+ ROOT / "kornia/geometry/ransac.py",
+ ROOT / "kornia/geometry/_ransac_program.py",
+ ROOT / "kornia/geometry/homography.py",
+ ROOT / "kornia/geometry/epipolar/fundamental.py",
+ ROOT / "kornia/geometry/epipolar/essential.py",
+ ]
+ },
+ )
+ quality = {}
+ backends = ["kornia (eager)"] + (["kornia (compiled)"] if args.compile else [])
+
+ def build(config):
+ n, ratio, seed = config
+ ops = {}
+ for name, model_type in MODELS.items():
+ if args.ops and name not in args.ops:
+ continue
+ p, q, truth = scene(name, n, ratio)
+ p, q, truth = p.to(device, dtype), q.to(device, dtype), truth.to(device)
+ cells = {}
+ for backend in backends:
+ estimator = RANSAC(
+ model_type,
+ inl_th=1.5 / (800 if name == "E" else 1),
+ seed=seed,
+ confidence=args.confidence,
+ max_samples=args.max_samples,
+ batch_size=batch,
+ compile=backend.endswith("(compiled)"),
+ )
+ fn = partial(estimator, p, q)
+ model, mask = fn() # Warm first call before the timed sweep, including compilation.
+ quality[name, backend, config] = {
+ "recall": float((mask & truth).sum()) / int(truth.sum()),
+ "false_positives": int((mask & ~truth).sum()),
+ "support": int(mask.sum()),
+ "failed": bool((model == 0).all()),
+ }
+ cells[backend] = fn
+ ops[name] = cells
+ return ops, {}
+
+ configs = list(itertools.product(sizes, ratios, seeds))
+ results = run_batch_sweep(
+ configs,
+ build,
+ backends,
+ sync=sync,
+ units="pairs/s",
+ row_fields=lambda c: {"batch": 1, "n": c[0], "inlier_ratio": c[1], "seed": c[2]},
+ label_fn=lambda c: f"N={c[0]} inliers={c[1]:.0%} seed={c[2]}",
+ items_fn=lambda c: 1,
+ min_run_time=args.min_run_time,
+ )
+ for row in results:
+ config = row["n"], row["inlier_ratio"], row["seed"]
+ row.update(quality[row["op"], row["backend"], config])
+ finish_run(args, "geometry-ransac-compile-synthetic", meta, results)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/benchmarks/geometry/ransac_cpu.py b/benchmarks/geometry/ransac_cpu.py
index 223b96a5c..d192f5e0d 100644
--- a/benchmarks/geometry/ransac_cpu.py
+++ b/benchmarks/geometry/ransac_cpu.py
@@ -44,6 +44,7 @@ from __future__ import annotations
import argparse
import hashlib
+import os
import sys
from collections import defaultdict
from functools import partial
@@ -202,10 +203,13 @@ def run(args: argparse.Namespace) -> None:
"kornia/geometry/homography.py",
"kornia/geometry/epipolar/fundamental.py",
"kornia/geometry/epipolar/essential.py",
+ "kornia/geometry/_ransac_program.py",
)
},
units="pairs/s",
dtype="float32",
+ compile=args.compile,
+ artifact_enabled=os.environ.get("KORNIA_RANSAC_AOT", "1") != "0",
models=models,
budgets=args.budgets,
seeds=args.seeds,
@@ -256,11 +260,14 @@ def run(args: argparse.Namespace) -> None:
max_samples=budget,
confidence=args.confidence,
seed=0,
+ compile=args.compile,
)
minimum = {"H": 4, "F": 7, "E": 5}[problem]
enough = len(kp1) >= minimum
median = iqr = None
if enough and not args.no_timing:
+ if args.compile:
+ estimator(kp1, kp2) # the first call compiles, or loads the saved graph
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
@@ -349,6 +356,9 @@ def main() -> None:
"--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(
+ "--compile", action="store_true", help="Time RANSAC(compile=True); its first call compiles and is not timed"
+ )
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(",")):
diff --git a/changelog.d/5117.added.md b/changelog.d/5117.added.md
new file mode 100644
index 000000000..577bd941e
--- /dev/null
+++ b/changelog.d/5117.added.md
@@ -0,0 +1,11 @@
+`RANSAC(compile=True)` runs the whole `local_optimization="lm"` estimation (homography, fundamental and essential
+matrices) as one `torch.compile` graph on CPU and CUDA with torch 2.14 or later. The graph is traced once per configuration and does not
+depend on the number of correspondences, the threshold, the confidence or the sample budget; it is saved next to
+inductor's cache, so a later process loads it instead of compiling. Seeded compiled calls are reproducible but use
+their own random stream without changing the global CPU or CUDA generators. Ordinary and inference-mode calls
+share the compiled artifact. Eager results are unchanged.
+
+Compiled calls normalize autocast, distinguish thread/default-dtype/default-device settings in the artifact cache,
+and draw their samples from a counter-based hash of the seed, so concurrent seeded calls preserve the global RNG. Large explicit CPU batches
+split to bound scoring memory while retaining the sample budget. Zero-weight singular correspondences no longer
+prevent LM refinement; artifact writes are atomic.
diff --git a/docs/source/geometry.ransac.rst b/docs/source/geometry.ransac.rst
index 8bf71cbd8..a93a6a86f 100644
--- a/docs/source/geometry.ransac.rst
+++ b/docs/source/geometry.ransac.rst
@@ -173,6 +173,58 @@ non-minimal solver's sample size (eight for fundamental/essential matrices).
On PhotoTourism fundamental matrices the subset refits match or beat full-inlier
refitting at a lower cost on both CPU and CUDA.
+Compiled estimation
+-------------------
+
+``compile=True`` (torch 2.14 or later) runs the whole ``local_optimization="lm"``
+estimation as one ``torch.compile`` graph on CPU and CUDA. The sampling loop is a
+``torch.while_loop`` that carries the pool of the best minimal models, the
+early-stopping bound is computed inside the graph, and the batch sizes and the
+number of models that survive the degeneracy tests are dynamic. The graph does
+not depend on the number of correspondences, the threshold, the confidence or
+the sample budget: it is traced once per model type, score type, iteration
+counts, dtype and device. The first call compiles it, in 30 s for homographies
+to 60 s for essential matrices on an Apple M1, and saves the compiled function
+next to inductor's cache (``TORCHINDUCTOR_CACHE_DIR``); later processes load it
+in about a second. ``KORNIA_RANSAC_AOT=0`` disables that file, and each process
+then compiles again, in 17 to 35 s once inductor's kernels are cached.
+Ordinary calls and calls under ``torch.inference_mode()`` share the same artifact.
+Compiled arithmetic also runs with autocast disabled, using the input's working
+precision and float64 host refinement. The artifact cache distinguishes CPU
+thread counts, default dtypes and default devices; changing these settings may require another
+first-call compilation. On CPU, large explicit sampling batches are split so
+scoring holds at most ``2**22`` residuals per batch (or one hypothesis when
+``N`` alone exceeds that limit). This keeps the total sample budget and can
+check confidence stopping earlier than the requested batch size would.
+The sampling keys are a counter-based hash of the call's seed and each
+sample's index, computed inside the graph, and Floyd's algorithm turns them
+into subsets on every device, where compilation fuses its steps into one
+kernel. A sample's keys therefore depend neither on batch boundaries nor on the
+device, calls with different seeds do not share samples, and seeded calls
+never touch a global generator, including during concurrent calls. An unseeded
+call draws one seed from the input device's global generator and then hashes it
+as a seeded call does.
+On CUDA the loop counters and stopping bound stay on the host, with a transfer
+of the leading score and inlier count after each batch; compilation therefore
+does not remove every host-device synchronization.
+
+For the initial implementation at revision ``ad91a621``, on that CPU
+(4 threads, synthetic scenes of 500 to 5000 correspondences with
+20% or 50% inliers, averaged over seeds), compiled calls were 1.2 to 1.7 times
+faster for homographies, 1.6 to 2.4 times for fundamental matrices and 1.1 to
+1.6 times for essential matrices, whose five-point solver gained nothing: its
+time goes to LAPACK factorizations and the eigenvalues of the companion matrix.
+The compiled call runs the same algorithm with its own random stream, so a
+seeded call is reproducible but differs from the eager one. On synthetic
+scenes of 500 and 2000 correspondences with 20% to 50% inliers its mean inlier
+recall was within 0.015 of eager's for homographies and essential matrices and
+within 0.03 for fundamental matrices, where eager runs with other seeds differ
+from each other as much (60 seeds per case at 20% and 30% inliers). PROSAC
+sampling, ``degensac=True`` and ``local_optimization="dlt"`` are not supported.
+The current sampler draws a different seeded stream;
+use ``benchmarks/geometry/ransac_compile_synthetic.py`` to measure current
+latency and recovery, including ``--confidence 1`` for equal sample budgets.
+
Dominant planes
---------------
diff --git a/kornia/geometry/_ransac_program.py b/kornia/geometry/_ransac_program.py
new file mode 100644
index 000000000..3e184e8f4
--- /dev/null
+++ b/kornia/geometry/_ransac_program.py
@@ -0,0 +1,562 @@
+# 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.
+#
+
+"""The whole of ``RANSAC(local_optimization="lm")`` as one tensor program, compiled by ``RANSAC(compile=True)``.
+
+:meth:`~kornia.geometry.ransac.RANSAC._forward_lm` drives its sampling loop from the host: it reads each batch's best
+score to decide whether to stop, and returns early when no model is supported. Here the loop is a
+:func:`torch.while_loop` whose state is a fixed-size pool of the best minimal models, the stopping bound is computed
+in tensors, and every early return is a :func:`torch.where`. The sizes that depend on the data, the batch of each
+iteration and the number of models that survive the degeneracy tests, are unbacked, so a single graph serves every
+number of correspondences, threshold, confidence and sample budget. ``RANSAC(compile=True)`` compiles it once per
+configuration and keeps the compiled function on disk (:func:`load_program`).
+"""
+
+from __future__ import annotations
+
+import contextlib
+import functools
+import hashlib
+import inspect
+import os
+import platform
+import sys
+import tempfile
+import threading
+import warnings
+from typing import Callable, Dict, Iterator, Tuple
+
+import torch
+
+import kornia
+from kornia.geometry import homography as _homography
+from kornia.geometry import ransac as _ransac
+from kornia.geometry.conversions import convert_points_to_homogeneous
+from kornia.geometry.epipolar import _metrics as _epipolar_metrics
+from kornia.geometry.epipolar import essential as _essential
+from kornia.geometry.epipolar import fundamental as _fundamental
+from kornia.geometry.epipolar import normalize_transformation, project_to_essential
+from kornia.geometry.epipolar._metrics import _sampson_errors, _sampson_from_quadratic_basis, _sampson_quadratic_basis
+from kornia.geometry.epipolar.essential import _five_point_candidates, _refine_essential_lm
+from kornia.geometry.epipolar.fundamental import (
+ _eight_point_fundamental,
+ _epipolar_design_rows,
+ _refine_fundamental_lm,
+ _seven_point_candidates,
+)
+from kornia.geometry.homography import (
+ _four_point_homography,
+ _refine_homography_lm,
+ _transfer_basis,
+ _transfer_errors,
+ _transfer_from_basis,
+ sample_is_valid_for_homography,
+)
+from kornia.geometry.ransac import _LM_CANDIDATES, _normalize_correspondences_core
+from kornia.geometry.solvers import homogeneous as _homogeneous
+
+__all__ = ["MAX_BATCH", "build_lm_program", "load_program"]
+
+# The candidate pool: as many minimal models as RANSAC(local_optimization="lm") refines.
+_POOL = _LM_CANDIDATES
+# Upper bound of a batch; RANSAC(compile=True) rejects a larger integer batch_size.
+MAX_BATCH = 1 << 20
+
+_SAMPLE_SIZES = {"homography": 4, "fundamental": 7, "fundamental_7pt": 7, "fundamental_8pt": 8, "essential": 5}
+
+_LOW32 = 0xFFFFFFFF
+
+
+def _mul32(x: torch.Tensor, constant: int) -> torch.Tensor:
+ """``x * constant mod 2**32`` for 32-bit values held in int64: 16-bit halves keep every product below ``2**63``."""
+ return ((x & 0xFFFF) * constant + ((((x >> 16) * constant) & 0xFFFF) << 16)) & _LOW32
+
+
+def _mix32(x: torch.Tensor) -> torch.Tensor:
+ """Chris Wellons's lowbias32, a bijection of 32-bit integers (https://github.com/skeeto/hash-prospector)."""
+ x = x ^ (x >> 16)
+ x = _mul32(x, 0x7FEB352D)
+ x = x ^ (x >> 15)
+ x = _mul32(x, 0x846CA68B)
+ return x ^ (x >> 16)
+
+
+def _uniform_keys(
+ seed: torch.Tensor, drawn: torch.Tensor, batch: int, columns: int, device: torch.device
+) -> torch.Tensor:
+ """Uniform float64 ``(batch, columns)`` in ``[0, 1)`` for samples ``drawn`` to ``drawn + batch - 1`` of ``seed``.
+
+ A counter-based stream: each 32-bit word hashes the element's index with two key words derived from the int64
+ seed, so it depends on the seed and the sample's index alone. No generator is involved, so seeded calls cannot
+ race on or change any global generator; the keys do not depend on batch boundaries or the device; and the whole
+ computation fuses into the compiled sampler instead of calling out to a generator for every batch. Each value
+ takes 53 bits from two words.
+ """
+ low, high = seed & _LOW32, (seed >> 32) & _LOW32
+ key1 = _mix32(low ^ _mix32(high ^ 0x9E3779B9)).to(device)
+ key2 = _mix32(high ^ _mix32(low ^ 0x85EBCA6B)).to(device)
+ sample = drawn.to(device) + torch.arange(batch, device=device, dtype=torch.int64)
+ counter = (sample[:, None] * columns + torch.arange(columns, device=device, dtype=torch.int64)) * 2
+
+ def word(index: torch.Tensor) -> torch.Tensor:
+ return _mix32(_mix32((index & _LOW32) ^ key1) ^ ((key2 + (index >> 32)) & _LOW32))
+
+ bits = (word(counter) >> 11) * 4294967296 + word(counter + 1)
+ return bits.to(torch.float64) * 2.0**-53
+
+
+def _draw_samples(
+ m: int, num_tc: int, batch: int, device: torch.device, seed: torch.Tensor, drawn: torch.Tensor
+) -> torch.Tensor:
+ """``batch`` uniform ``m``-subsets of ``range(num_tc)`` from a private, reproducible random stream.
+
+ Floyd's algorithm over :func:`_uniform_keys` on every device. Eager RANSAC uses random-key top-k on accelerators,
+ where Floyd's ``m`` small steps are launch-bound; compiled, they fuse into one kernel over ``batch * m`` keys
+ instead of ``batch * N`` keys and a top-k (about 13% of a CUDA homography call at N=2000).
+ """
+ rand = _uniform_keys(seed, drawn, batch, m, device)
+ columns = []
+ for i in range(m):
+ last = num_tc - m + i
+ candidate = (rand[:, i] * (last + 1)).long()
+ if i > 0:
+ duplicate = (torch.stack(columns, 1) == candidate[:, None]).any(dim=1)
+ candidate = torch.where(duplicate, last, candidate)
+ columns.append(candidate)
+ return torch.stack(columns, 1)
+
+
+def _minimal_models(model_type: str, x1: torch.Tensor, x2: torch.Tensor) -> torch.Tensor:
+ """Minimal models ``(M, 3, 3)`` of samples ``(B, m, 3)``, as :meth:`RANSAC._lm_minimal_models`.
+
+ On CPU the degenerate samples and the absent roots are dropped (``M`` is unbacked); elsewhere they are NaN models,
+ which score no inliers. Every sample is solved before the drop: the shape checks of the batched triangular solves
+ would guard on an unbacked batch being empty.
+ """
+ compact = x1.device.type == "cpu"
+ if model_type == "homography":
+ oriented = sample_is_valid_for_homography(x1[..., :2], x2[..., :2])
+ models = _four_point_homography(x1, x2)
+ return models[oriented] if compact else models.masked_fill(~oriented[:, None, None], float("nan"))
+ design = _epipolar_design_rows(x1, x2)
+ if model_type == "essential":
+ candidates, valid = _five_point_candidates(design)
+ return candidates[valid] if compact else candidates.flatten(0, 1)
+ if model_type == "fundamental_8pt":
+ models = _eight_point_fundamental(design)
+ else:
+ candidates, valid = _seven_point_candidates(design)
+ models = candidates.masked_fill(~valid[..., None, None], float("nan")).flatten(0, 1)
+ return models[torch.isfinite(models).flatten(1).all(1)] if compact else models
+
+
+def _scores(
+ models: torch.Tensor, basis: torch.Tensor, threshold: torch.Tensor, planar: bool, msac: bool
+) -> Tuple[torch.Tensor, torch.Tensor]:
+ """MSAC scores (or support counts) in float64 and int64 support counts ``(M,)`` of minimal models.
+
+ Both sums accumulate in 64 bits: a float32 sum longer than 4096 elements makes inductor's CPU code guard on the
+ number of correspondences, which a single graph for every ``N`` cannot carry.
+ """
+ errors = _transfer_from_basis(models, basis) if planar else _sampson_from_quadratic_basis(models, basis)
+ counts = (errors <= threshold).sum(1)
+ if not msac:
+ return counts.to(torch.float64), counts
+ # fmin, unlike clamp, takes the threshold for NaN residuals: a NaN residual is an outlier.
+ return (1.0 - torch.fmin(errors, threshold) / threshold).sum(1, dtype=torch.float64), counts
+
+
+def _samples_needed(
+ support: torch.Tensor, num_tc: int, m: int, confidence: torch.Tensor, budget: torch.Tensor
+) -> torch.Tensor:
+ """:meth:`RANSAC.max_samples_by_conf` of ``support`` inliers in tensors, capped at ``budget`` (int64)."""
+ inliers = support.to(torch.float64)
+ probability = torch.ones_like(inliers)
+ for i in range(m):
+ probability = probability * (inliers - i) / (num_tc - i)
+ needed = torch.ceil(torch.log1p(-confidence) / torch.log1p(-probability))
+ bounded = (confidence < 1) & (inliers >= m) & (probability > 0) & (needed < budget.to(torch.float64))
+ needed = torch.where(bounded, needed, budget.to(torch.float64)).to(torch.int64)
+ return torch.where((confidence < 1) & (inliers >= num_tc), torch.ones_like(needed), needed)
+
+
+def _lm_errors(model_type: str, models: torch.Tensor, x1: torch.Tensor, x2: torch.Tensor) -> torch.Tensor:
+ """Squared residuals ``(K, N)`` of normalized models on normalized points, as :meth:`RANSAC._lm_errors`."""
+ if model_type == "homography":
+ return _transfer_from_basis(models, _transfer_basis(x1, x2[:, :2]))
+ return _sampson_from_quadratic_basis(models, _sampson_quadratic_basis(x1, x2))
+
+
+def _lm_refine(
+ model_type: str,
+ models: torch.Tensor,
+ x1: torch.Tensor,
+ x2: torch.Tensor,
+ mask: torch.Tensor | None,
+ loss: str,
+ scale2: torch.Tensor,
+ iters: int,
+) -> torch.Tensor:
+ if model_type == "homography":
+ return _refine_homography_lm(models, x1, x2[:, :2], mask, loss, scale2, iters)
+ if model_type == "essential":
+ return _refine_essential_lm(models, x1, x2, mask, loss, scale2, iters)
+ return _refine_fundamental_lm(models, x1, x2, mask, loss, scale2, iters)
+
+
+def build_lm_program(model_type: str, score_type: str, max_lo_iters: int, refine_iters: int) -> Callable[..., Tuple]:
+ """Return the tensor program of ``RANSAC(model_type, score_type=..., local_optimization="lm")``.
+
+ The program maps ``(kp1, kp2, inl_th, confidence, budget, first_batch, largest_batch, random_seed)`` --
+ the correspondences
+ ``(N, 2)``, the threshold and confidence as float64 tensors ``(1,)`` and the sample budget and first and largest
+ batch as 0-d int64 tensors, all on the host -- to the model ``(3, 3)`` and the inlier mask ``(N,)`` that
+ :meth:`~kornia.geometry.ransac.RANSAC._forward_lm` returns for them. Batches double from ``first_batch`` up to
+ ``largest_batch``; equal values keep a fixed batch.
+ """
+ m = _SAMPLE_SIZES[model_type]
+ planar = model_type == "homography"
+ essential = model_type == "essential"
+ msac = score_type == "msac"
+
+ def lm_program(
+ kp1: torch.Tensor,
+ kp2: torch.Tensor,
+ inl_th: torch.Tensor,
+ confidence: torch.Tensor,
+ budget: torch.Tensor,
+ first_batch: torch.Tensor,
+ largest_batch: torch.Tensor,
+ random_seed: torch.Tensor,
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
+ # One-element threshold and confidence: dynamo would trace 0-d float inputs as Python scalars, which it cannot
+ # keep symbolic here, and restart its analysis once with them as tensors.
+ inl_th, confidence = inl_th[0], confidence[0]
+ device, dtype = kp1.device, kp1.dtype
+ work = torch.float64 if dtype == torch.float64 else torch.float32
+ num_tc = kp1.shape[0]
+ torch._check(num_tc >= m)
+ host = torch.device("cpu")
+ # Moved first, then cast: a single .to(host, torch.float64) out of MPS returns zeros (pytorch/pytorch#197715).
+ kp1_host, kp2_host = kp1.detach().to(host).double(), kp2.detach().to(host).double()
+ finite = torch.isfinite(kp1_host).all(1) & torch.isfinite(kp2_host).all(1)
+ if essential:
+ x1_host, x2_host = (
+ convert_points_to_homogeneous(kp.masked_fill(~finite[:, None], float("nan")))
+ for kp in (kp1_host, kp2_host)
+ )
+ t1 = t2 = torch.eye(3, dtype=torch.float64, device=host)
+ threshold = inl_th.square()
+ else:
+ x1_host, x2_host, t1, t2, scales = _normalize_correspondences_core(kp1_host, kp2_host, not planar)
+ threshold = (inl_th / scales[1 if planar else 0]).square()
+ # Copies: the normalized points are views of one tensor, and inputs of the loop body must not alias.
+ x1, x2 = x1_host.to(device, work, copy=True), x2_host.to(device, work, copy=True)
+ basis = _transfer_basis(x1, x2[:, :2]) if planar else _sampson_quadratic_basis(x1, x2)
+ threshold_work = threshold.to(device, work)
+ pad_models = x1.new_full((_POOL, 3, 3), float("nan"))
+ pad_scores = torch.full((_POOL,), -2.0, dtype=torch.float64, device=device)
+ pad_counts = torch.zeros(_POOL, dtype=torch.int64, device=device)
+
+ def cond(drawn, batch, max_samples, best_score, pool, pool_scores): # type: ignore[no-untyped-def]
+ return drawn < max_samples
+
+ def body(drawn, batch, max_samples, best_score, pool, pool_scores): # type: ignore[no-untyped-def]
+ current = torch.minimum(batch, max_samples - drawn)
+ size = current.item()
+ torch._check(size >= 1)
+ torch._check(size <= MAX_BATCH)
+ indices = _draw_samples(m, num_tc, size, device, random_seed, drawn)
+ models = _minimal_models(model_type, x1[indices], x2[indices])
+ scores, counts = _scores(models, basis, threshold_work, planar, msac)
+ # Insufficient support ranks below every supported model, as in RANSAC._forward_lm; the padding, which
+ # keeps the top-k defined for a batch without models, below that.
+ scores = torch.cat([scores.masked_fill(counts <= m, -1.0), pad_scores])
+ top_scores, top = scores.topk(_POOL)
+ top_models = torch.cat([models, pad_models])[top]
+ top_counts = torch.cat([counts, pad_counts])[top]
+ pool_scores, order = torch.cat([top_scores, pool_scores]).topk(_POOL)
+ pool = torch.cat([top_models, pool])[order]
+ # The bound follows the new incumbent's own support, as with local_optimization="dlt".
+ # The loop counters and stopping bound stay on the host. Transfer both statistics together:
+ # otherwise CUDA scores promote the carried CPU scalars to CUDA and change the loop's metadata.
+ leading_score, leading_count = (
+ torch.stack([top_scores[0], top_counts[0].to(torch.float64)]).to(host).unbind()
+ )
+ improved = leading_score > best_score
+ needed = _samples_needed(leading_count, num_tc, m, confidence, budget)
+ max_samples = torch.where(improved, torch.minimum(budget, needed), max_samples)
+ best_score = torch.where(improved, leading_score, best_score)
+ batch = torch.minimum(2 * batch, largest_batch)
+ return drawn + current, batch, max_samples, best_score, pool, pool_scores
+
+ state = (
+ torch.zeros((), dtype=torch.int64, device=host),
+ first_batch.clone(),
+ budget.clone(),
+ torch.full((), -1.0, dtype=torch.float64, device=host),
+ pad_models.clone(),
+ pad_scores.clone(),
+ )
+ _, _, _, _, pool, pool_scores = torch.while_loop(cond, body, state)
+
+ # ---- refinement and selection on the host, in float64 ----
+ # RANSAC._forward_lm drops the non-finite correspondences here. Dropping them would leave an unbacked number
+ # of points, whose strides inductor cannot lower: they stay as finite stand-ins of weight 0 instead, which
+ # adds zeros to the same sums.
+ stand_in = torch.tensor([0.0, 0.0, 1.0], dtype=torch.float64, device=host)
+ x1_host = torch.where(finite[:, None], x1_host, stand_in)
+ x2_host = torch.where(finite[:, None], x2_host, stand_in)
+ weights = finite.to(torch.float64)[None]
+ valid = (pool_scores >= 0).to(host)
+ # An absent pool slot holds a finite stand-in, which the factorizations of the refinement accept, and is
+ # never selected.
+ candidates = torch.where(
+ valid[:, None, None], pool.to(host).double(), torch.eye(3, dtype=torch.float64, device=host)
+ )
+ if max_lo_iters > 0:
+ refits = _lm_refine(model_type, candidates, x1_host, x2_host, weights, "truncated", threshold, max_lo_iters)
+ # Refits first: a tie goes to the refit, which is fitted to more than a minimal sample.
+ candidates = torch.cat([refits, candidates])
+ valid = torch.cat([valid, valid])
+ errors = _lm_errors(model_type, candidates, x1_host, x2_host)
+ inliers = (errors <= threshold) & finite
+ support = inliers.sum(1)
+ if msac:
+ scores = ((1.0 - torch.fmin(errors, threshold) / threshold) * weights).sum(1)
+ else:
+ scores = support.to(torch.float64)
+ scores = scores.masked_fill(support <= m, -1.0).masked_fill(~valid, -2.0)
+ best = scores.argmax().reshape(1)
+ failed = scores.max() < 0
+ model, inliers = candidates.index_select(0, best)[0], inliers.index_select(0, best)[0]
+ if refine_iters > 0:
+ # A Cauchy scale of a third of the threshold: the threshold as three standard deviations of the noise.
+ mask = inliers.to(torch.float64)[None]
+ refined = _lm_refine(model_type, model[None], x1_host, x2_host, mask, "cauchy", threshold / 9, refine_iters)
+ refined_inliers = (_lm_errors(model_type, refined, x1_host, x2_host)[0] <= threshold) & finite
+ supported = refined_inliers.sum() > m
+ model = torch.where(supported, refined[0], model)
+ inliers = torch.where(supported, refined_inliers, inliers)
+ if essential:
+ # A minimal model is essential only up to rounding when neither refinement ran: project it.
+ model = project_to_essential(model)
+ model = (model / model.norm()).to(dtype)
+ # E and -E are the same model; a fixed sign makes equal inputs give equal outputs.
+ model = model * model.flatten().index_select(0, model.abs().argmax().reshape(1)).sign()
+ else:
+ model = (torch.linalg.inv(t2) @ model @ t1) if planar else (t2.mT @ model @ t1)
+ model = normalize_transformation(model).to(dtype)
+ failed = failed | ~torch.isfinite(model).all()
+ # The exact returned matrix, classified in pixel coordinates in float64, as RANSAC._forward_lm does.
+ model64 = torch.where(failed, torch.eye(3, dtype=torch.float64, device=host), model.to(torch.float64))
+ p1 = convert_points_to_homogeneous(kp1_host)
+ if planar:
+ pixel_errors = _transfer_errors(model64[None], p1, kp2_host)[0]
+ else:
+ pixel_errors = _sampson_errors(model64[None], p1, convert_points_to_homogeneous(kp2_host))[0]
+ mask = finite & (pixel_errors <= inl_th.square())
+ failed = failed | (mask.sum() <= m)
+ model = torch.where(failed, torch.zeros_like(model), model)
+ mask = mask & ~failed
+ return model.to(device), mask.to(device)
+
+ return lm_program
+
+
+# ---- compiled programs, in memory and on disk ----
+
+_PROGRAM_LOCK = threading.Lock()
+_PROGRAMS: Dict[Tuple, Callable[..., Tuple]] = {}
+
+
+def _source_digest() -> str:
+ """Digest of the modules whose code the compiled graph embeds, read once: an edit must not load a stale artifact."""
+ digest = hashlib.sha256()
+ for module in (
+ sys.modules[__name__],
+ _homography,
+ _fundamental,
+ _essential,
+ _epipolar_metrics,
+ _ransac,
+ _homogeneous,
+ ):
+ digest.update(inspect.getsource(module).encode())
+ return digest.hexdigest()
+
+
+def _dynamo_config() -> Iterator[None]:
+ """The dynamo settings the program needs: ``.item()`` of the batch size and the compacted model count.
+
+ Every configuration compiles the same code object, whose cache of graphs dynamo bounds by ``recompile_limit``. The
+ eigenvalues of the five-point solver are complex, which inductor leaves to ATen, with a warning that is expected.
+ """
+ with (
+ warnings.catch_warnings(),
+ torch._dynamo.config.patch(
+ capture_scalar_outputs=True,
+ capture_dynamic_output_shape_ops=True,
+ # Model/configuration integers are fixed per program. Generalizing the minimal sample size across
+ # model types makes CUDA solver metadata depend on symbolic matrix dimensions inside while_loop.
+ specialize_int=True,
+ recompile_limit=64,
+ ),
+ ):
+ warnings.filterwarnings(
+ "ignore", message="Torchinductor does not support code generation for complex operators"
+ )
+ yield
+
+
+def _artifact_path(key: Tuple) -> str:
+ from torch._inductor.cpu_vec_isa import pick_vec_isa
+ from torch._inductor.runtime.cache_dir_utils import cache_dir
+
+ digest = hashlib.sha256()
+ # The generated CPU kernels target this machine's vector instructions, which a shared cache directory may not.
+ device = torch.device(key[5])
+ accelerator = (
+ (torch.cuda.get_device_name(device), torch.cuda.get_device_capability(device))
+ if device.type == "cuda"
+ else None
+ )
+ machine = (platform.platform(), platform.machine(), str(pick_vec_isa()), accelerator)
+ for part in (torch.__version__, kornia.__version__, sys.version, machine, key, _source_digest()):
+ digest.update(repr(part).encode())
+ return os.path.join(cache_dir(), "kornia_ransac", f"{digest.hexdigest()[:32]}.bin")
+
+
+def load_program(key: Tuple, example_inputs: Tuple[torch.Tensor, ...]) -> Callable[..., Tuple]:
+ """Return the compiled program of ``key``.
+
+ The key contains the model configuration, tensor dispatch configuration, and the ambient thread/default-dtype
+ settings which Dynamo guards. Autocast is instead disabled while the program is traced and called, so an
+ estimator traced outside autocast is usable inside it too.
+
+ Compiled once per process. The compiled function is also saved next to inductor's own cache
+ (``TORCHINDUCTOR_CACHE_DIR``) and loaded from there by later processes, which then skip tracing. The number of
+ correspondences is dynamic, so the program serves every ``N``. ``KORNIA_RANSAC_AOT=0`` disables the artifact.
+ """
+ with _PROGRAM_LOCK:
+ program = _PROGRAMS.get(key)
+ if program is not None:
+ return program
+ compiled = torch.compile(build_lm_program(*key[:4]), fullgraph=True)
+ traced = _traced(compiled)
+ program = traced
+ if os.environ.get("KORNIA_RANSAC_AOT", "1") != "0":
+ try:
+ artifact = _load_or_save_artifact(key, compiled, _mark_dynamic(example_inputs))
+ program = _artifact_or_traced(artifact, traced)
+ except Exception as error: # noqa: BLE001 - the AOT API is experimental; the traced program is equivalent
+ warnings.warn(
+ f"RANSAC(compile=True) could not use its on-disk artifact: {type(error).__name__}: {error}",
+ stacklevel=3,
+ )
+ _PROGRAMS[key] = program
+ return program
+
+
+def _mark_dynamic(inputs: Tuple[torch.Tensor, ...]) -> Tuple[torch.Tensor, ...]:
+ """The inputs with the correspondence dimension marked dynamic, on new tensors: the caller's stay unmarked.
+
+ The traced program is called with marked inputs, as its guards expect; an artifact loaded by another process is
+ called with the plain ones, since its guards reject marked tensors.
+ """
+ kp1, kp2 = inputs[0].detach(), inputs[1].detach()
+ torch._dynamo.mark_dynamic(kp1, 0)
+ torch._dynamo.mark_dynamic(kp2, 0)
+ return (kp1, kp2, *inputs[2:])
+
+
+def _traced(compiled: Callable[..., Tuple]) -> Callable[..., Tuple]:
+ """``compiled`` called with the program's dynamo settings and dynamic correspondences."""
+
+ def run(*args: torch.Tensor) -> Tuple:
+ with _compiled_autocast_disabled(), _dynamo_config():
+ return compiled(*_mark_dynamic(args))
+
+ return run
+
+
+def _compiled_autocast_disabled() -> Iterator[None]:
+ """Give a compiled program one autocast-free dispatch key on both trace and invocation."""
+ # A CUDA program is still guarded by CPU autocast state (and vice versa), so disable both rather than only the
+ # input device's context. Disabled CUDA autocast is valid on CPU-only builds.
+ with torch.autocast(device_type="cpu", enabled=False), torch.autocast(device_type="cuda", enabled=False):
+ yield
+
+
+def _artifact_or_traced(artifact: Callable[..., Tuple], traced: Callable[..., Tuple]) -> Callable[..., Tuple]:
+ """Use an AOT artifact until an ambient guard rejects it, then retain the equivalent traced program."""
+ rejected = False
+
+ def run(*args: torch.Tensor) -> Tuple:
+ nonlocal rejected
+ if rejected:
+ return traced(*args)
+ try:
+ with _compiled_autocast_disabled():
+ return artifact(*args)
+ except (AssertionError, RuntimeError) as error:
+ if "GuardManager" not in str(error):
+ raise
+ # AOT artifacts encode guards that are not all exposed in their filename. The traced program has the
+ # same tensor semantics and can safely specialize for this process instead of making compile=True fail.
+ rejected = True
+ warnings.warn(
+ f"RANSAC(compile=True) artifact was incompatible at invocation; using the traced program: "
+ f"{type(error).__name__}: {error}",
+ stacklevel=3,
+ )
+ return traced(*args)
+
+ return run
+
+
+def _load_or_save_artifact(
+ key: Tuple, compiled: Callable[..., Tuple], example_inputs: Tuple[torch.Tensor, ...]
+) -> Callable[..., Tuple]:
+ path = _artifact_path(key)
+ if os.path.exists(path):
+ with open(path, "rb") as handle:
+ return torch.compiler.load_compiled_function(handle)
+ from torch._dynamo.exc import TensorifyScalarRestartAnalysis
+
+ with _compiled_autocast_disabled(), _dynamo_config():
+ try:
+ artifact = compiled.aot_compile((example_inputs, {})) # type: ignore[attr-defined]
+ except TensorifyScalarRestartAnalysis:
+ # torch.compile restarts its analysis once when a Python scalar cannot become a tensor; aot_compile
+ # (torch 2.14) raises instead, and succeeds when called again.
+ artifact = compiled.aot_compile((example_inputs, {})) # type: ignore[attr-defined]
+ directory = os.path.dirname(path)
+ os.makedirs(directory, exist_ok=True)
+ descriptor, temporary = tempfile.mkstemp(prefix=".tmp-", suffix=".bin", dir=directory)
+ os.close(descriptor)
+ try:
+ artifact.save_compiled_function(temporary)
+ # Readers either find no artifact or a complete one. Concurrent compilers may replace equivalent files.
+ os.replace(temporary, path)
+ finally:
+ if os.path.exists(temporary):
+ os.unlink(temporary)
+ return artifact
diff --git a/kornia/geometry/epipolar/essential.py b/kornia/geometry/epipolar/essential.py
index 5ee771974..99a511ae4 100644
--- a/kornia/geometry/epipolar/essential.py
+++ b/kornia/geometry/epipolar/essential.py
@@ -17,7 +17,7 @@
"""Module containing functionalities for the Essential matrix."""
-from typing import Any, Optional, Tuple
+from typing import Any, Optional, Tuple, Union
import torch
@@ -352,11 +352,18 @@ def _nister_candidates(basis: torch.Tensor, out_dtype: torch.dtype) -> Tuple[tor
# the identity instead, so that nothing below overflows or raises in the forward pass or gives a NaN gradient
# in the backward, and all ten of their slots are NaN.
A10, b10 = coeffs[..., :10], coeffs[..., 10:]
- lu, pivots, info = torch.linalg.lu_factor_ex(A10)
+ eye10 = torch.eye(10, device=device, dtype=dtype)
+ lu, pivots, info = torch.linalg.lu_factor_ex(A10.detach() if A10.requires_grad else A10)
singular = info > 0
- if bool(singular.any()):
- eye10 = torch.eye(10, device=device, dtype=dtype).expand(B, 10, 10)
+ if A10.requires_grad:
+ # The backward of a singular factorization is 0 * inf even in the rows whose result is replaced (x86 LAPACK):
+ # differentiate the factorization of the substituted matrix instead.
lu, pivots, _ = torch.linalg.lu_factor_ex(torch.where(singular[:, None, None], eye10, A10))
+ else:
+ # The factorization of the identity is the identity without row exchanges: substituting it costs no second
+ # factorization, and no host synchronization, which would split a compiled graph.
+ lu = torch.where(singular[:, None, None], eye10, lu)
+ pivots = torch.where(singular[:, None], torch.arange(1, 11, device=device, dtype=pivots.dtype), pivots)
eliminated = torch.linalg.lu_solve(lu, pivots, b10) # (B, 10, 10)
# ---- hidden-variable matrix (B, 3, 13) and its determinant, a polynomial of degree ten in z ----
@@ -878,7 +885,7 @@ def _refine_essential_lm(
x2: torch.Tensor,
mask: Optional[torch.Tensor],
loss: str,
- scale2: float,
+ scale2: Union[float, torch.Tensor],
iters: int,
) -> torch.Tensor:
"""Levenberg-Marquardt on the Sampson distance, batched over essential matrices ``(K, 3, 3)``.
diff --git a/kornia/geometry/epipolar/fundamental.py b/kornia/geometry/epipolar/fundamental.py
index 4e7354be2..9793c624d 100644
--- a/kornia/geometry/epipolar/fundamental.py
+++ b/kornia/geometry/epipolar/fundamental.py
@@ -18,7 +18,7 @@
"""Module containing the functionalities for computing the Fundamental Matrix."""
import math
-from typing import Literal, Optional, Tuple
+from typing import Literal, Optional, Tuple, Union
import torch
@@ -312,11 +312,14 @@ def _seven_point_candidates(A: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor
return F.to(A.dtype), valid & torch.isfinite(F).flatten(-2).all(-1)
-def _robust_loss(r2: torch.Tensor, loss: str, scale2: float) -> Tuple[torch.Tensor, torch.Tensor]:
- """IRLS weights and costs of a squared residual: Cauchy, or truncated at ``scale2``."""
+def _robust_loss(r2: torch.Tensor, loss: str, scale2: Union[float, torch.Tensor]) -> Tuple[torch.Tensor, torch.Tensor]:
+ """IRLS weights and costs of a squared residual: Cauchy, or truncated at ``scale2``.
+
+ ``scale2`` may be a 0-d tensor, which keeps a compiled caller free of a host synchronization.
+ """
if loss == "cauchy":
return 1.0 / (1.0 + r2 / scale2), torch.log1p(r2 / scale2)
- return (r2 < scale2).to(r2.dtype), torch.fmin(r2, torch.full_like(r2[:1, :1], scale2))
+ return (r2 < scale2).to(r2.dtype), torch.fmin(r2, torch.as_tensor(scale2, dtype=r2.dtype, device=r2.device))
def _hat_basis(dtype: torch.dtype, device: torch.device) -> torch.Tensor:
@@ -338,15 +341,23 @@ def _sampson_cost(
quadratic: torch.Tensor,
mask: Optional[torch.Tensor],
loss: str,
- scale2: float,
+ scale2: Union[float, torch.Tensor],
) -> 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
+ if mask is not None:
+ # A zero mask excludes the correspondence. Guarding its divisor keeps the residual of a finite row finite, so
+ # the zero weight below removes it exactly; an infinite residual times zero would be NaN, also in backward.
+ denominator = torch.where(mask != 0, denominator, torch.ones_like(denominator))
r2 = (numerator * denominator.rsqrt()).square()
- rho = torch.log1p(r2 / scale2) if loss == "cauchy" else torch.fmin(r2, torch.full_like(r2[:1, :1], scale2))
+ rho = (
+ torch.log1p(r2 / scale2)
+ if loss == "cauchy"
+ else torch.fmin(r2, torch.as_tensor(scale2, dtype=r2.dtype, device=r2.device))
+ )
if mask is not None:
rho = rho * mask
return rho.sum(1)
@@ -359,7 +370,7 @@ def _sampson_normal_equations(
quadratic: torch.Tensor,
mask: Optional[torch.Tensor],
loss: str,
- scale2: float,
+ scale2: Union[float, torch.Tensor],
) -> Tuple[torch.Tensor, torch.Tensor]:
"""Robust Gauss-Newton normal equations ``[J^T W J | J^T W r]`` ``(K, P, P + 1)`` and costs ``(K,)``.
@@ -374,7 +385,12 @@ def _sampson_normal_equations(
quad2 = F[:, None, :, :2] @ stacked[:, :, :, :2].mT
out_c = stacked.reshape(K, P + 1, 9) @ algebraic
out_g = torch.cat([quad1, quad2], 2).reshape(K, P + 1, 18) @ quadratic
- inv = out_g[:, 0].rsqrt()
+ denominator = out_g[:, 0]
+ if mask is not None:
+ # See _sampson_cost. Only the divisor is guarded: masking the residual and the whole (K, P, N) Jacobian as
+ # well adds nothing to a zero weight and costs the compiled program time.
+ denominator = torch.where(mask != 0, denominator, torch.ones_like(denominator))
+ inv = denominator.rsqrt()
r = out_c[:, 0] * inv
J = (out_c[:, 1:] - (r * inv)[:, None] * out_g[:, 1:]) * inv[:, None] # (K, P, N)
w, rho = _robust_loss(r * r, loss, scale2)
@@ -390,7 +406,7 @@ def _refine_fundamental_lm(
x2: torch.Tensor,
mask: Optional[torch.Tensor],
loss: str,
- scale2: float,
+ scale2: Union[float, torch.Tensor],
iters: int,
) -> torch.Tensor:
"""Levenberg-Marquardt on the Sampson distance, batched over fundamental matrices ``(K, 3, 3)``.
diff --git a/kornia/geometry/homography.py b/kornia/geometry/homography.py
index 7c8cdb984..a163b4c1d 100644
--- a/kornia/geometry/homography.py
+++ b/kornia/geometry/homography.py
@@ -17,7 +17,7 @@
import math
import warnings
-from typing import Optional, Tuple
+from typing import Optional, Tuple, Union
import torch
@@ -421,7 +421,7 @@ def _refine_homography_lm(
x2: torch.Tensor,
mask: Optional[torch.Tensor],
loss: str,
- scale2: float,
+ scale2: Union[float, torch.Tensor],
iters: int,
) -> torch.Tensor:
"""Levenberg-Marquardt on the one-way transfer error, batched over homographies ``(K, 3, 3)``.
@@ -439,7 +439,6 @@ def _refine_homography_lm(
eye8 = torch.eye(8, dtype=dtype, device=device)
eye9 = torch.eye(9, dtype=dtype, device=device)
last = eye9[8]
- target = torch.cat([x2[:, 0], x2[:, 1]])
h = H.flatten(1)
h = h * h.square().sum(1, keepdim=True).rsqrt()
damping = torch.full((K, 1, 1), 1e-3, dtype=dtype, device=device)
@@ -451,9 +450,15 @@ def _refine_homography_lm(
tangent = (eye9 - 2 * v[:, :, None] * v[:, None, :])[:, :, :8] # (K, 9, 8)
stacked = torch.cat([h[:, :, None], tangent], 2).mT.reshape(K, 27, 3) # rows of H, then of each direction
P = (stacked @ x1.T).reshape(K, 9, 3, -1) # (K, 9, 3, N): P = H x1, then its directional derivatives
- iz = 1.0 / P[:, 0, 2]
+ if mask is None:
+ iz = 1.0 / P[:, 0, 2]
+ else:
+ # A zero mask excludes the correspondence. Guarding its projective divisor keeps the residual and
+ # Jacobian of a finite row finite, so the zero weight below removes it exactly; masking the whole
+ # derivative stack as well costs the compiled CUDA program about 10% of a homography call.
+ iz = 1.0 / torch.where(mask != 0, P[:, 0, 2], torch.ones_like(P[:, 0, 2]))
uv = P[:, 0, :2] * iz[:, None] # (K, 2, N)
- r = uv.flatten(1) - target # (K, 2N): u residuals, then v residuals
+ r = (uv - x2.T).flatten(1) # (K, 2N): u residuals, then v residuals
J = ((P[:, 1:, :2] - uv[:, None] * P[:, 1:, 2:3]) * iz[:, None, None]).flatten(2) # (K, 8, 2N)
r2 = r[:, : x1.shape[0]].square() + r[:, x1.shape[0] :].square()
w, rho = _robust_loss(r2, loss, scale2)
@@ -469,9 +474,15 @@ def _refine_homography_lm(
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))
+ divisor = projection[:, 2]
+ if mask is not None:
+ divisor = torch.where(mask != 0, divisor, torch.ones_like(divisor))
+ r2 = (projection[:, :2] / divisor[:, None] - x2.T).square().sum(1)
+ rho = (
+ torch.log1p(r2 / scale2)
+ if loss == "cauchy"
+ else torch.fmin(r2, torch.as_tensor(scale2, dtype=r2.dtype, device=r2.device))
+ )
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)
diff --git a/kornia/geometry/ransac.py b/kornia/geometry/ransac.py
index 83a6e55f9..8b7b8d8a9 100644
--- a/kornia/geometry/ransac.py
+++ b/kornia/geometry/ransac.py
@@ -27,6 +27,7 @@ from typing import Callable, List, Optional, Tuple, Union
import torch
from torch import nn
+from kornia.core._compat import torch_version_lt
from kornia.core.check import KORNIA_CHECK_SHAPE
from kornia.geometry._degensac import (
_h_degenerate_sample,
@@ -74,6 +75,10 @@ _LM_CANDIDATES = 8
# Model types that DEGENSAC supports: seven-point fundamental matrices (Chum, Werner and Matas, CVPR 2005).
_DEGENSAC_MODELS = ("fundamental", "fundamental_7pt")
+# At most this many residuals are materialized by one compiled CPU scoring batch. Small/default inputs retain their
+# tuned batch sizes; large explicit batches are split without changing the minimal-sample budget.
+_COMPILED_CPU_SCORE_RESIDUALS = 1 << 22
+
@lru_cache(maxsize=32)
def _prosac_growth(sample_size: int, pop_size: int, budget: int) -> Tuple[int, ...]:
@@ -101,6 +106,24 @@ def _resolve_degensac(degensac: Optional[bool], model_type: str, local_optimizat
return False if degensac is None else degensac
+def _normalize_correspondences_core(
+ kp1: torch.Tensor, kp2: torch.Tensor, shared_scale: bool
+) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
+ """:func:`_normalize_correspondences` with the two scales as a ``(2,)`` tensor, without a host synchronization."""
+ finite = torch.isfinite(kp1).all(1) & torch.isfinite(kp2).all(1)
+ stacked = torch.stack([kp1, kp2])
+ placeholders = torch.where(finite[None, :, None], stacked, torch.zeros_like(stacked))
+ points, transforms = normalize_points(placeholders, weights=finite.to(kp1.dtype).expand(2, -1))
+ if shared_scale:
+ scale = transforms[:, 0, 0]
+ ratio = (2.0 / (1.0 / scale).sum()) / scale
+ points = points * ratio[:, None, None]
+ transforms = torch.cat([transforms[:, :2] * ratio[:, None, None], transforms[:, 2:]], 1)
+ points = torch.where(finite[None, :, None], points, torch.full_like(points, float("nan")))
+ points = convert_points_to_homogeneous(points)
+ return points[0], points[1], transforms[0], transforms[1], 1.0 / transforms[:, 0, 0]
+
+
def _normalize_correspondences(
kp1: torch.Tensor, kp2: torch.Tensor, shared_scale: bool
) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, float, float]:
@@ -116,19 +139,21 @@ def _normalize_correspondences(
Homogeneous normalized points ``(N, 3)`` of each image, the ``(3, 3)`` transforms that map pixels to them, and
the two scales in pixels per normalized unit.
"""
- finite = torch.isfinite(kp1).all(1) & torch.isfinite(kp2).all(1)
- stacked = torch.stack([kp1, kp2])
- placeholders = torch.where(finite[None, :, None], stacked, torch.zeros_like(stacked))
- points, transforms = normalize_points(placeholders, weights=finite.to(kp1.dtype).expand(2, -1))
- if shared_scale:
- scale = transforms[:, 0, 0]
- ratio = (2.0 / (1.0 / scale).sum()) / scale
- points = points * ratio[:, None, None]
- transforms = torch.cat([transforms[:, :2] * ratio[:, None, None], transforms[:, 2:]], 1)
- points = torch.where(finite[None, :, None], points, torch.full_like(points, float("nan")))
- points = convert_points_to_homogeneous(points)
- s1, s2 = (1.0 / transforms[:, 0, 0]).tolist()
- return points[0], points[1], transforms[0], transforms[1], s1, s2
+ x1, x2, t1, t2, scales = _normalize_correspondences_core(kp1, kp2, shared_scale)
+ s1, s2 = scales.tolist()
+ return x1, x2, t1, t2, s1, s2
+
+
+def _check_compile_config(local_optimization: str, prosac_sampling: bool, degensac: bool) -> None:
+ """Reject the configurations that ``RANSAC(compile=True)`` does not cover."""
+ if torch_version_lt(2, 14, 0):
+ raise ValueError("compile=True needs torch 2.14 or later")
+ if local_optimization != "lm":
+ raise ValueError('compile=True supports local_optimization="lm" only')
+ if prosac_sampling:
+ raise ValueError("compile=True does not support prosac_sampling")
+ if degensac:
+ raise ValueError("compile=True does not support degensac")
class RANSAC(nn.Module):
@@ -184,6 +209,13 @@ class RANSAC(nn.Module):
- A seeded call uses a private generator and leaves torch's global RNG state unchanged; ``seed=None``
draws the minimal samples from the global generator. DEGENSAC's recovery draws always come from a private
host generator, which an unseeded call seeds from the sample that triggers the recovery.
+ - ``compile=True`` runs the whole ``local_optimization="lm"`` estimation as one ``torch.compile`` graph
+ (torch 2.14 or later, CPU and CUDA). The graph is traced once per configuration and does not
+ depend on the number of correspondences, the threshold, the confidence or the budget; it is also saved next
+ to inductor's cache (``TORCHINDUCTOR_CACHE_DIR``), so a later process loads it instead of compiling. It
+ runs the same algorithm with its own random stream: a seeded call is reproducible and leaves every global
+ generator unchanged, while an unseeded call consumes one global random seed. Its result is not the eager
+ one. PROSAC sampling and DEGENSAC are not supported.
Args:
model_type: "homography", "fundamental", "fundamental_7pt", "fundamental_8pt", "essential", or
@@ -214,6 +246,7 @@ class RANSAC(nn.Module):
fundamental and essential matrices and ``"dlt"`` for line segments.
refine_iters: Levenberg-Marquardt iterations of the final refinement with ``local_optimization="lm"``;
zero disables it.
+ compile: run ``local_optimization="lm"`` as one compiled graph, as described above.
degensac: run DEGENSAC's dominant-plane recovery, as described above. Defaults to False; None also leaves
it off. True enables it for ``"fundamental"`` and ``"fundamental_7pt"`` with ``local_optimization="lm"``,
the only supported combinations; True with any other raises ``ValueError``.
@@ -236,6 +269,7 @@ class RANSAC(nn.Module):
local_optimization: Optional[str] = None,
refine_iters: int = 3,
degensac: Optional[bool] = False,
+ compile: bool = False,
) -> None:
"""Initialize the RANSAC estimator.
@@ -263,6 +297,7 @@ class RANSAC(nn.Module):
final robust refinement) or ``"dlt"`` (refits of each new best model); None picks ``"lm"`` where it
is supported, for homographies, fundamental and essential matrices.
refine_iters: Levenberg-Marquardt iterations of the final refinement on the inliers with ``"lm"``.
+ compile: run ``local_optimization="lm"`` as one compiled graph (torch 2.14 or later).
degensac: opt-in DEGENSAC dominant-plane recovery for seven-point fundamental matrices.
Defaults to False; None also leaves it off. True requires seven-point matrices with
local_optimization="lm".
@@ -318,6 +353,9 @@ class RANSAC(nn.Module):
self.lo_sample_size = lo_sample_size
self.local_optimization = local_optimization
self.refine_iters = refine_iters
+ if compile:
+ _check_compile_config(local_optimization, prosac_sampling, degensac)
+ self.compiled = compile
self.degensac = degensac
# The PROSAC growth schedule as a device tensor, reused across the batches of a call.
self._prosac_ends: Optional[Tuple[Tuple[int, int, int, torch.device], torch.Tensor]] = None
@@ -475,7 +513,10 @@ class RANSAC(nn.Module):
batch would score more than ``2**22`` (CPU) or ``2**25`` (accelerators) residuals, counting the three models
of a seven-point sample and the ten candidate slots of a five-point one. 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.
+ residuals, independently of the batch. An integer ``batch_size`` is kept for every batch, except that
+ compiled CPU RANSAC splits a batch whose candidate-by-correspondence score matrix would exceed the CPU
+ memory bound. This preserves the sample budget, though the extra batch boundaries can change when
+ confidence-based stopping is evaluated.
"""
if isinstance(self.batch_size, int):
return self.batch_size
@@ -867,6 +908,9 @@ class RANSAC(nn.Module):
self.validate_inputs(kp1, kp2, weights)
if self.local_optimization == "lm":
with torch.no_grad():
+ if self.compiled:
+ with torch.inference_mode(False), torch.no_grad():
+ return self._forward_compiled(kp1, kp2)
return self._forward_lm(kp1, kp2)
best_score_total = -float("inf")
num_tc: int = len(kp1)
@@ -935,6 +979,63 @@ class RANSAC(nn.Module):
inliers_best_total = torch.zeros_like(inliers_best_total)
return best_model_total, inliers_best_total
+ def _forward_compiled(self, kp1: torch.Tensor, kp2: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
+ """:meth:`_forward_lm` as the compiled program of :mod:`kornia.geometry._ransac_program`."""
+ from kornia.geometry._ransac_program import MAX_BATCH, load_program
+
+ if kp1.device.type not in ("cpu", "cuda"):
+ raise ValueError(f"compile=True runs on CPU and CUDA, not {kp1.device.type}")
+ # Artifacts guard tensor dispatch keys, gradients and strides. Normalize these without copying ordinary
+ # contiguous inputs; inference tensors need a clone under the disabled inference context in forward.
+ kp1, kp2 = (
+ kp.clone(memory_format=torch.contiguous_format) if kp.is_inference() else kp.detach().contiguous()
+ for kp in (kp1, kp2)
+ )
+ num_tc = len(kp1)
+ first, largest = self._lm_batch_range(num_tc, kp1.device)
+ if largest > MAX_BATCH:
+ raise ValueError(f"compile=True supports batches of at most {MAX_BATCH} samples")
+ if kp1.device.type == "cpu":
+ # The five-point solver can yield ten candidates and the seven-point solver three. Cap batches by the
+ # resulting score matrix, not just sampled sets, so an explicit large batch cannot allocate O(B * N)
+ # unbounded memory. The while-loop still draws exactly ``sample_budget`` sets.
+ slots = 10 if self.model_type == "essential" else 3 if self.minimal_sample_size == 7 else 1
+ cap = max(1, _COMPILED_CPU_SCORE_RESIDUALS // (slots * max(num_tc, 1)))
+ first, largest = min(first, cap), min(largest, cap)
+ host = torch.device("cpu")
+ scalars = [torch.tensor([value], dtype=torch.float64, device=host) for value in (self.inl_th, self.confidence)]
+ scalars += [
+ torch.tensor(value, dtype=torch.int64, device=host) for value in (self.sample_budget, first, largest)
+ ]
+ if self.seed is None:
+ # One ordinary global draw chooses this invocation's private stream; the program hashes it with each
+ # sample's index and never reads a generator, so it cannot race a seeded call's RNG isolation.
+ random_seed = torch.randint(0, torch.iinfo(torch.int64).max, (), dtype=torch.int64, device=kp1.device)
+ random_seed = random_seed.to(host)
+ else:
+ # Match Generator.manual_seed's domain while carrying it through the graph as a signed int64 tensor.
+ if isinstance(self.seed, bool) or not isinstance(self.seed, int):
+ raise TypeError("seed must be an integer")
+ if self.seed < -(1 << 63) or self.seed > (1 << 64) - 1:
+ raise ValueError("seed must be within [-2**63, 2**64 - 1]")
+ signed_seed = ((self.seed + (1 << 63)) % (1 << 64)) - (1 << 63)
+ random_seed = torch.tensor(signed_seed, dtype=torch.int64, device=host)
+ scalars.append(random_seed)
+ inputs = (kp1, kp2, *scalars)
+ key = (
+ self.model_type,
+ self.score_type,
+ self.max_lo_iters,
+ self.refine_iters,
+ kp1.dtype,
+ str(kp1.device),
+ torch.get_num_threads(),
+ torch.get_default_dtype(),
+ str(torch.get_default_device()),
+ )
+ program = load_program(key, inputs)
+ return program(*inputs)
+
def _lm_minimal_models(
self, x1: torch.Tensor, x2: torch.Tensor, track_origins: bool = False
) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
diff --git a/kornia/geometry/solvers/homogeneous.py b/kornia/geometry/solvers/homogeneous.py
index 23ff3c339..84f0ea147 100644
--- a/kornia/geometry/solvers/homogeneous.py
+++ b/kornia/geometry/solvers/homogeneous.py
@@ -185,7 +185,13 @@ def _null_space_lu(A: torch.Tensor) -> torch.Tensor:
"""
batch, m, n = A.shape
lu, pivots, _ = torch.linalg.lu_factor_ex(A.mT)
- lower = torch.linalg.solve_triangular(lu[:, :m, :m], lu[:, m:, :m], upper=False, left=False, unitriangular=True)
+ square = lu[:, :m, :m]
+ if torch.compiler.is_compiling() and A.device.type == "cuda":
+ # The CUDA meta kernel tests column-major contiguity of this strided LU view. With an unbacked
+ # batch inside while_loop that needs a data-dependent guard. Make that layout check always true,
+ # including empty batches; a row-major copy still needs a guard for the empty case.
+ square = square.mT.contiguous().mT
+ lower = torch.linalg.solve_triangular(square, lu[:, m:, :m], upper=False, left=False, unitriangular=True)
eye = torch.eye(n - m, dtype=A.dtype, device=A.device).expand(batch, -1, -1)
permutation, _, _ = torch.lu_unpack(lu, pivots, unpack_data=False)
return permutation @ torch.cat([-lower.mT, eye], 1)
diff --git a/tests/geometry/test_ransac.py b/tests/geometry/test_ransac.py
index 237c45eb5..c0f755c52 100644
--- a/tests/geometry/test_ransac.py
+++ b/tests/geometry/test_ransac.py
@@ -17,13 +17,17 @@
import math
+import os
+import subprocess
import sys
+from concurrent.futures import ThreadPoolExecutor
import pytest
import torch
import kornia
import kornia.geometry.ransac as ransac_module
+from kornia.core._compat import torch_version_lt
from kornia.geometry import RANSAC, transform_points
from kornia.geometry._degensac import _h_degenerate_sample
from kornia.geometry.conversions import axis_angle_to_rotation_matrix, convert_points_from_homogeneous
@@ -33,7 +37,7 @@ from kornia.geometry.epipolar.fundamental import _rank2_projection, _refine_fund
from kornia.geometry.homography import _refine_homography_lm, _transfer_errors, oneway_transfer_error
from kornia.geometry.ransac import _normalize_correspondences
-from testing.base import BaseTester
+from testing.base import BaseTester, dynamo_is_available
from testing.casts import dict_to
from testing.geometry.create import create_dominant_plane_scene
@@ -2109,6 +2113,457 @@ class TestRANSACScoring(BaseTester):
self.assert_close(errors.nan_to_num(), original.nan_to_num(), rtol=0, atol=0)
+_COMPILED_MODELS = ["homography", "fundamental", "fundamental_8pt", "essential"]
+_NO_COMPILED_PROGRAM = torch_version_lt(2, 14, 0) or not dynamo_is_available()
+_NO_COMPILED_PROGRAM_REASON = "RANSAC(compile=True) needs torch 2.14 or later"
+
+
+class TestRANSACCompiled(BaseTester):
+ """``compile=True``: the whole of ``local_optimization="lm"`` as one compiled graph.
+
+ Every test that compiles has ``compile`` in its name, which keeps it to the dynamo CI job.
+ """
+
+ def test_graph_mode_rejects_unsupported_configurations(self):
+ if torch_version_lt(2, 14, 0):
+ with pytest.raises(ValueError, match=r"2\.14"):
+ RANSAC("homography", compile=True)
+ return
+ with pytest.raises(ValueError, match="local_optimization"):
+ RANSAC("homography_from_linesegments", compile=True)
+ with pytest.raises(ValueError, match="local_optimization"):
+ RANSAC("homography", local_optimization="dlt", compile=True)
+ with pytest.raises(ValueError, match="prosac"):
+ RANSAC("homography", prosac_sampling=True, compile=True)
+ with pytest.raises(ValueError, match="degensac"):
+ RANSAC("fundamental", degensac=True, compile=True)
+ # Checked before anything is compiled.
+ with pytest.raises(ValueError, match="batches of at most"):
+ RANSAC("homography", batch_size=1 << 21, compile=True)(torch.rand(8, 2), torch.rand(8, 2))
+
+ @pytest.mark.skipif(_NO_COMPILED_PROGRAM, reason=_NO_COMPILED_PROGRAM_REASON)
+ @pytest.mark.parametrize("model_type", _COMPILED_MODELS)
+ def test_compile_recovers_the_eager_estimate(self, device, dtype, model_type):
+ if device.type not in ("cpu", "cuda"):
+ pytest.skip("the compiled program supports CPU and CUDA")
+ if dtype not in (torch.float32, torch.float64):
+ pytest.skip("the compiled program is checked in float32 and float64")
+ kp1, kp2, _, _, inliers = _scene(model_type, 300, 120, 0.5, seed=1)
+ kp1, kp2 = kp1.to(device, dtype), kp2.to(device, dtype)
+ th = _px(model_type, 1.5)
+ _, eager_mask = RANSAC(model_type, inl_th=th, seed=0)(kp1, kp2)
+ model, mask = RANSAC(model_type, inl_th=th, seed=0, compile=True)(kp1, kp2)
+ assert model.shape == (3, 3) and model.dtype == dtype and model.device == kp1.device
+ assert mask.shape == (300,) and mask.dtype == torch.bool and mask.device == kp1.device
+ # The mask holds the inliers of the returned model, as in eager mode.
+ assert torch.equal(mask.cpu(), _model_errors(model_type, model, kp1, kp2) <= th)
+ # The same algorithm with its own random stream: the same consensus up to borderline correspondences.
+ assert (mask & eager_mask).sum() >= 0.98 * eager_mask.sum()
+ assert (mask.cpu() & ~inliers).sum() <= 2
+ assert (mask.cpu() & inliers).sum() >= 0.9 * inliers.sum()
+
+ @pytest.mark.skipif(_NO_COMPILED_PROGRAM, reason=_NO_COMPILED_PROGRAM_REASON)
+ @pytest.mark.parametrize("artifact", ["0", "1"])
+ @pytest.mark.parametrize("model_type", _COMPILED_MODELS)
+ def test_compile_one_graph_for_every_input(self, monkeypatch, artifact, device, model_type):
+ if device.type not in ("cpu", "cuda"):
+ pytest.skip("the compiled program supports CPU and CUDA")
+ from torch._dynamo.utils import counters
+
+ from kornia.geometry import _ransac_program
+
+ # A fresh program per parametrization: with the on-disk artifact, a guard that an input violates raises.
+ monkeypatch.setenv("KORNIA_RANSAC_AOT", artifact)
+ monkeypatch.setattr(_ransac_program, "_PROGRAMS", {})
+ RANSAC(model_type, seed=0, compile=True)(
+ *(kp.to(device, torch.float32) for kp in _scene(model_type, 50, 10, 0.5, 0)[:2])
+ )
+ graphs = counters["stats"]["unique_graphs"]
+ # Sizes on both sides of inductor's 4096-element float32 reduction threshold, and every per-call number.
+ for n, inl_th, confidence, max_samples in ((9, 2.0, 0.99, 64), (1500, 1.0, 1.0, 300), (5000, 3.0, 0.9, 2000)):
+ kp1, kp2, _, _, _ = _scene(model_type, n, n // 4, 0.3, seed=n)
+ kp1, kp2 = kp1.to(device, torch.float32), kp2.to(device, torch.float32)
+ threshold = _px(model_type, inl_th)
+ ransac = RANSAC(model_type, inl_th=threshold, confidence=confidence, max_samples=max_samples, compile=True)
+ model, mask = ransac(kp1, kp2)
+ assert mask.shape == (n,)
+ assert torch.equal(mask.cpu(), _model_errors(model_type, model, kp1, kp2) <= threshold)
+ assert counters["stats"]["unique_graphs"] == graphs
+
+ @pytest.mark.skipif(_NO_COMPILED_PROGRAM, reason=_NO_COMPILED_PROGRAM_REASON)
+ def test_compile_seeded_calls_repeat_and_keep_the_global_generator(self, device):
+ if device.type not in ("cpu", "cuda"):
+ pytest.skip("the compiled program supports CPU and CUDA")
+ kp1, kp2, _, _, _ = _planar_scene(200, 80, 0.5, seed=3)
+ kp1, kp2 = kp1.to(device, torch.float32), kp2.to(device, torch.float32)
+ ransac = RANSAC("homography", seed=7, compile=True)
+ cuda_states = torch.cuda.get_rng_state_all() if torch.cuda.is_available() else []
+ state = torch.get_rng_state()
+ first = ransac(kp1.float(), kp2.float())
+ second = ransac(kp1.float(), kp2.float())
+ assert torch.equal(first[0], second[0]) and torch.equal(first[1], second[1])
+ assert torch.equal(torch.get_rng_state(), state)
+ for index, cuda_state in enumerate(cuda_states):
+ assert torch.equal(torch.cuda.get_rng_state(index), cuda_state)
+
+ @pytest.mark.skipif(_NO_COMPILED_PROGRAM, reason=_NO_COMPILED_PROGRAM_REASON)
+ def test_compile_seeded_calls_are_thread_safe(self):
+ """Concurrent seeded estimators use private streams and do not perturb another thread's generator."""
+ points = torch.rand(32, 2, generator=torch.Generator().manual_seed(0)) * 100
+
+ def run(seed):
+ return RANSAC(
+ "homography", batch_size=32, max_samples=32, max_lo_iters=0, refine_iters=0, compile=True, seed=seed
+ )(points, points)[0]
+
+ expected = run(7)
+ torch.manual_seed(123)
+ unrelated_expected = torch.rand(32)
+ torch.manual_seed(123)
+
+ with ThreadPoolExecutor(max_workers=4) as executor:
+ first = executor.submit(run, 7)
+ unrelated = executor.submit(torch.rand, 32)
+ second = executor.submit(run, 7)
+ first, unrelated, second = first.result(), unrelated.result(), second.result()
+ assert torch.equal(first, expected) and torch.equal(second, expected)
+ assert torch.equal(unrelated, unrelated_expected)
+
+ @pytest.mark.skipif(_NO_COMPILED_PROGRAM, reason=_NO_COMPILED_PROGRAM_REASON)
+ @pytest.mark.parametrize("seed", [0, (1 << 63) - 1, 1 << 63, (1 << 64) - 1])
+ def test_compile_preserves_full_generator_seed_domain(self, monkeypatch, seed):
+ from kornia.geometry import _ransac_program
+
+ captured = []
+
+ def load(key, inputs):
+ captured.append(inputs[-1])
+ return lambda *args: (torch.zeros(3, 3), torch.zeros(len(args[0]), dtype=torch.bool))
+
+ monkeypatch.setattr(_ransac_program, "load_program", load)
+ points = torch.rand(8, 2)
+ RANSAC("homography", compile=True, seed=seed)(points, points)
+ expected = ((seed + (1 << 63)) % (1 << 64)) - (1 << 63)
+ assert captured[0].item() == expected
+
+ @pytest.mark.skipif(_NO_COMPILED_PROGRAM, reason=_NO_COMPILED_PROGRAM_REASON)
+ @pytest.mark.parametrize("seed", [True, 1.2])
+ def test_compile_rejects_non_integer_seeds_before_compilation(self, monkeypatch, seed):
+ from kornia.geometry import _ransac_program
+
+ monkeypatch.setattr(
+ _ransac_program, "load_program", lambda *args: pytest.fail("invalid seeds must not compile")
+ )
+ points = torch.rand(8, 2)
+ with pytest.raises(TypeError, match="seed must be an integer"):
+ RANSAC("homography", compile=True, seed=seed)(points, points)
+
+ @pytest.mark.skipif(_NO_COMPILED_PROGRAM, reason=_NO_COMPILED_PROGRAM_REASON)
+ def test_compile_sampler_hash_matches_its_integer_reference(self, device):
+ """The int64 tensor form of lowbias32 equals the 32-bit integer hash: no signed product overflows."""
+ from kornia.geometry._ransac_program import _mix32
+
+ def lowbias32(x):
+ x ^= x >> 16
+ x = (x * 0x7FEB352D) & 0xFFFFFFFF
+ x ^= x >> 15
+ x = (x * 0x846CA68B) & 0xFFFFFFFF
+ return x ^ (x >> 16)
+
+ values = [0, 1, 0xFFFF, 0x10000, 0x7FFFFFFF, 0x80000000, 0xFFFFFFFF]
+ values += torch.randint(0, 1 << 32, (2000,), generator=torch.Generator().manual_seed(0)).tolist()
+ actual = _mix32(torch.tensor(values, dtype=torch.int64, device=device)).cpu().tolist()
+ assert actual == [lowbias32(v) for v in values]
+
+ @pytest.mark.skipif(_NO_COMPILED_PROGRAM, reason=_NO_COMPILED_PROGRAM_REASON)
+ def test_compile_sampler_keys_are_private_reproducible_and_batch_independent(self, device):
+ """A sample's keys are a hash of the seed and the sample's index alone.
+
+ No generator is involved, so seeded calls leave every global generator untouched; batch boundaries do not change
+ the stream; CPU and accelerators draw identical keys; and calls whose seeds differ by a batch offset or by
+ ``2**32`` do not share samples.
+ """
+ from kornia.geometry._ransac_program import _uniform_keys
+
+ if device.type not in ("cpu", "cuda"):
+ pytest.skip("the compiled program supports CPU and CUDA")
+
+ def keys(seed, drawn, batch=4, target=device):
+ return _uniform_keys(torch.tensor(seed), torch.tensor(drawn), batch, 8, target)
+
+ cuda_states = torch.cuda.get_rng_state_all() if torch.cuda.is_available() else []
+ state = torch.get_rng_state()
+ for seed in [0, (1 << 63) - 1, -(1 << 63), -1]:
+ first = keys(seed, 0)
+ assert first.dtype == torch.float64 and first.shape == (4, 8)
+ assert bool(((first >= 0) & (first < 1)).all())
+ assert torch.equal(first, keys(seed, 0))
+ assert torch.equal(first.cpu(), keys(seed, 0, target=torch.device("cpu")))
+ assert torch.equal(torch.get_rng_state(), state)
+ for index, cuda_state in enumerate(cuda_states):
+ assert torch.equal(torch.cuda.get_rng_state(index), cuda_state)
+ assert torch.equal(keys(7, 0, 256), torch.cat([keys(7, 0, 128), keys(7, 128, 128)]))
+ assert not torch.equal(keys(0, 128), keys(128, 0))
+ assert not torch.equal(keys(0, 0), keys(1 << 32, 0))
+ assert len({keys(seed, 0, 1)[0, 0].item() for seed in range(256)}) == 256
+
+ @pytest.mark.skipif(_NO_COMPILED_PROGRAM, reason=_NO_COMPILED_PROGRAM_REASON)
+ def test_compile_sampler_draws_uniform_subsets(self, device):
+ """Floyd's algorithm, which the program uses on every device: distinct indices, every 4-subset of 10 equally
+ likely (chi-square over the 210 subsets, 209 degrees of freedom, far below 4.5 standard deviations)."""
+ from kornia.geometry._ransac_program import _draw_samples
+
+ if device.type not in ("cpu", "cuda"):
+ pytest.skip("the compiled program supports CPU and CUDA")
+ draws = 105_000
+ samples = _draw_samples(4, 10, draws, device, torch.tensor(5), torch.tensor(0)).cpu()
+ assert samples.shape == (draws, 4) and samples.min() >= 0 and samples.max() < 10
+ ordered = samples.sort(1).values
+ assert (ordered[:, 1:] != ordered[:, :-1]).all()
+ _, counts = (ordered * torch.tensor([1000, 100, 10, 1])).sum(1).unique(return_counts=True)
+ assert len(counts) == math.comb(10, 4)
+ expected = draws / math.comb(10, 4)
+ assert ((counts - expected) ** 2 / expected).sum() < 209 + 4.5 * math.sqrt(2 * 209)
+
+ @pytest.mark.skipif(_NO_COMPILED_PROGRAM, reason=_NO_COMPILED_PROGRAM_REASON)
+ def test_compile_normalizes_autocast_and_keys_ambient_guards(self, monkeypatch):
+ """Artifact guards from ambient defaults do not collide, and caller autocast cannot alter a program."""
+ from kornia.geometry import _ransac_program
+
+ seen = []
+
+ def load(key, inputs):
+ seen.append(key)
+
+ def program(*args):
+ return torch.zeros(3, 3), torch.zeros(len(args[0]), dtype=torch.bool)
+
+ return program
+
+ monkeypatch.setattr(_ransac_program, "load_program", load)
+ points = torch.rand(16, 2)
+ estimator = RANSAC("homography", compile=True, seed=0)
+ original_dtype, original_threads = torch.get_default_dtype(), torch.get_num_threads()
+ changed_threads = 1 if original_threads != 1 else 2
+ try:
+ with torch.autocast("cpu", dtype=torch.bfloat16):
+ with _ransac_program._compiled_autocast_disabled():
+ assert not torch.is_autocast_enabled("cpu") and not torch.is_autocast_enabled("cuda")
+ estimator(points, points)
+ torch.set_default_dtype(torch.float64)
+ torch.set_num_threads(changed_threads)
+ estimator(points, points)
+ finally:
+ torch.set_default_dtype(original_dtype)
+ torch.set_num_threads(original_threads)
+ assert seen[0][-3:] == (original_threads, original_dtype, str(torch.get_default_device()))
+ assert seen[1][-3:] == (changed_threads, torch.float64, str(torch.get_default_device()))
+
+ @pytest.mark.skipif(_NO_COMPILED_PROGRAM, reason=_NO_COMPILED_PROGRAM_REASON)
+ def test_compile_explicit_cpu_controls_ignore_default_device(self, monkeypatch):
+ from kornia.geometry import _ransac_program
+
+ captured = []
+
+ def load(key, inputs):
+ captured.append((key, inputs))
+ return lambda *args: (torch.zeros(3, 3), torch.zeros(len(args[0]), dtype=torch.bool))
+
+ monkeypatch.setattr(_ransac_program, "load_program", load)
+ points = torch.rand(8, 2)
+ original = torch.get_default_device()
+ try:
+ torch.set_default_device("meta")
+ RANSAC("homography", compile=True, seed=0)(points, points)
+ finally:
+ torch.set_default_device(original)
+ assert captured[0][0][-1] == "meta"
+ assert all(control.device.type == "cpu" for control in captured[0][1][2:])
+
+ @pytest.mark.skipif(_NO_COMPILED_PROGRAM, reason=_NO_COMPILED_PROGRAM_REASON)
+ def test_compile_caps_cpu_scoring_batches_without_changing_budget(self, monkeypatch):
+ """Large explicit batches are split before their candidate-by-correspondence score matrix grows unbounded."""
+ from kornia.geometry import _ransac_program
+
+ captured = []
+
+ def load(key, inputs):
+ captured.append(inputs)
+ return lambda *args: (torch.zeros(3, 3), torch.zeros(len(args[0]), dtype=torch.bool))
+
+ monkeypatch.setattr(_ransac_program, "load_program", load)
+ num_tc, budget = 100_000, 1_000_000
+ RANSAC("homography", batch_size=budget, max_samples=budget, compile=True)(
+ torch.rand(num_tc, 2), torch.rand(num_tc, 2)
+ )
+ # Homographies have one candidate per sample, so the limit is exactly the residual cap divided by N.
+ expected = ransac_module._COMPILED_CPU_SCORE_RESIDUALS // num_tc
+ assert captured[0][4].item() == budget
+ assert captured[0][5].item() == captured[0][6].item() == expected
+
+ @pytest.mark.skipif(_NO_COMPILED_PROGRAM, reason=_NO_COMPILED_PROGRAM_REASON)
+ def test_compile_cpu_score_cap_runs_explicit_confidence_one_budget(self):
+ # This crosses 2**22 residuals at an explicit batch of 256, so CPU compilation splits it into scoring-safe
+ # batches. confidence=1 makes the requested sample budget observable independent of consensus quality.
+ count, budget = (1 << 15) + 1, 256
+ generator = torch.Generator().manual_seed(0)
+ kp1 = torch.rand(count, 2, generator=generator) * 100
+ kp2 = kp1 * 1.1 + 5
+ model, mask = RANSAC(
+ "homography",
+ batch_size=budget,
+ max_samples=budget,
+ confidence=1.0,
+ max_lo_iters=0,
+ refine_iters=0,
+ seed=0,
+ compile=True,
+ )(kp1, kp2)
+ assert torch.isfinite(model).all() and mask.shape == (count,)
+ assert mask.sum() == count
+
+ @pytest.mark.skipif(_NO_COMPILED_PROGRAM, reason=_NO_COMPILED_PROGRAM_REASON)
+ @pytest.mark.parametrize("error_type", [AssertionError, RuntimeError])
+ def test_compile_artifact_guard_rejection_recovers_with_traced_program(self, error_type):
+ from kornia.geometry._ransac_program import _artifact_or_traced
+
+ calls = {"artifact": 0, "traced": 0}
+
+ def artifact(*args):
+ calls["artifact"] += 1
+ raise error_type("GuardManager rejected ambient dispatch state")
+
+ def traced(*args):
+ calls["traced"] += 1
+ return torch.zeros(3, 3), torch.zeros(len(args[0]), dtype=torch.bool)
+
+ program = _artifact_or_traced(artifact, traced)
+ points = torch.rand(8, 2)
+ with pytest.warns(UserWarning, match="artifact was incompatible"):
+ first = program(points)
+ second = program(points)
+ assert calls == {"artifact": 1, "traced": 2}
+ assert torch.equal(first[0], second[0]) and torch.equal(first[1], second[1])
+
+ @pytest.mark.skipif(_NO_COMPILED_PROGRAM, reason=_NO_COMPILED_PROGRAM_REASON)
+ def test_compile_artifact_runtime_error_propagates(self):
+ from kornia.geometry._ransac_program import _artifact_or_traced
+
+ def artifact(*args):
+ raise RuntimeError("a compiled kernel failed")
+
+ def traced(*args):
+ pytest.fail("a runtime kernel failure must not be replayed through the traced program")
+
+ with pytest.raises(RuntimeError, match="kernel failed"):
+ _artifact_or_traced(artifact, traced)(torch.rand(8, 2))
+
+ @pytest.mark.skipif(_NO_COMPILED_PROGRAM, reason=_NO_COMPILED_PROGRAM_REASON)
+ @pytest.mark.parametrize("artifact", ["0", "1"])
+ def test_compile_reuses_program_across_inference_contexts(self, monkeypatch, artifact, device):
+ if device.type not in ("cpu", "cuda"):
+ pytest.skip("the compiled program supports CPU and CUDA")
+ from torch._dynamo.utils import counters
+
+ from kornia.geometry import _ransac_program
+
+ monkeypatch.setenv("KORNIA_RANSAC_AOT", artifact)
+ monkeypatch.setattr(_ransac_program, "_PROGRAMS", {})
+ kp1 = torch.rand(100, 2, generator=torch.Generator().manual_seed(0)) * 100
+ kp2 = kp1 * 1.1 + 5
+ kp1, kp2 = kp1.to(device), kp2.to(device)
+ estimator = RANSAC("homography", seed=0, compile=True)
+ expected = estimator(kp1, kp2)
+ # The compiled program disables both autocast dispatch keys internally, so it reuses the same graph here.
+ autocast_dtype = torch.float16 if device.type == "cuda" else torch.bfloat16
+ with torch.autocast(device.type, dtype=autocast_dtype):
+ actual = estimator(kp1, kp2)
+ self.assert_close(actual[0], expected[0], rtol=0, atol=0)
+ assert torch.equal(actual[1], expected[1])
+ graphs = counters["stats"]["unique_graphs"]
+ with torch.inference_mode():
+ inference_kp1, inference_kp2 = kp1.clone(), kp2.clone()
+ for points in ((kp1, kp2), (inference_kp1, inference_kp2)):
+ actual = estimator(*points)
+ self.assert_close(actual[0], expected[0], rtol=0, atol=0)
+ assert torch.equal(actual[1], expected[1])
+ # Inference tensors can also arrive from a caller that already left its inference context.
+ actual = estimator(inference_kp1, inference_kp2)
+ self.assert_close(actual[0], expected[0], rtol=0, atol=0)
+ # A differentiable/noncontiguous input must not invalidate an artifact traced from detached inputs.
+ actual = estimator(kp1.T.contiguous().T.requires_grad_(), kp2.T.contiguous().T.requires_grad_())
+ self.assert_close(actual[0], expected[0], rtol=0, atol=0)
+ assert counters["stats"]["unique_graphs"] == graphs
+ if artifact == "1":
+ # Exercise the disk load, as well as reuse of the in-memory program.
+ monkeypatch.setattr(_ransac_program, "_PROGRAMS", {})
+ with torch.inference_mode():
+ actual = estimator(inference_kp1, inference_kp2)
+ self.assert_close(actual[0], expected[0], rtol=0, atol=0)
+ assert counters["stats"]["unique_graphs"] == graphs
+
+ @pytest.mark.skipif(_NO_COMPILED_PROGRAM, reason=_NO_COMPILED_PROGRAM_REASON)
+ def test_compile_no_consensus_returns_the_failure_result(self, device):
+ if device.type not in ("cpu", "cuda"):
+ pytest.skip("the compiled program supports CPU and CUDA")
+ # Every sample maps a triangle onto a single point: sample_is_valid_for_homography rejects them all.
+ points1 = (10.0 * torch.rand(16, 2, generator=torch.Generator().manual_seed(123))).to(device)
+ points2 = torch.full((16, 2), 5.0)
+ for compile in (False, True):
+ model, mask = RANSAC("homography", inl_th=0.5, seed=0, compile=compile)(points1, points2.to(device))
+ assert torch.equal(model, torch.zeros(3, 3, device=device))
+ assert not mask.any()
+ # A minimal sample alone is never a consensus.
+ model, mask = RANSAC("homography", seed=0, compile=compile)(points1[:4], 2 * points1[:4])
+ assert torch.equal(model, torch.zeros(3, 3, device=device))
+ assert not mask.any()
+
+ @pytest.mark.skipif(_NO_COMPILED_PROGRAM, reason=_NO_COMPILED_PROGRAM_REASON)
+ def test_compile_non_finite_correspondences_are_never_inliers(self, device):
+ if device.type not in ("cpu", "cuda"):
+ pytest.skip("the compiled program supports CPU and CUDA")
+ kp1, kp2, _, _, inliers = _planar_scene(200, 40, 0.3, seed=4)
+ kp1, kp2 = kp1.to(device, torch.float32), kp2.to(device, torch.float32)
+ kp1[50], kp2[60, 1], kp2[70, 0] = float("nan"), float("inf"), float("-inf")
+ _, mask = RANSAC("homography", seed=0, compile=True)(kp1, kp2)
+ assert not mask[[50, 60, 70]].any()
+ expected = inliers.to(device).clone()
+ expected[[50, 60, 70]] = False
+ assert (mask & expected).sum() >= 0.95 * expected.sum() and (mask & ~expected).sum() == 0
+
+ @pytest.mark.skipif(_NO_COMPILED_PROGRAM, reason=_NO_COMPILED_PROGRAM_REASON)
+ def test_compile_artifact_serves_a_new_process(self, tmp_path):
+ script = (
+ "import torch\n"
+ "from torch._dynamo.utils import counters\n"
+ "from kornia.geometry import RANSAC\n"
+ "torch.set_num_threads(int(__import__('os').environ['RANSAC_TEST_THREADS']))\n"
+ "torch.set_default_dtype(getattr(torch, __import__('os').environ['RANSAC_TEST_DTYPE']))\n"
+ "g = torch.Generator().manual_seed(0)\n"
+ "kp1 = torch.rand(300, 2, generator=g, dtype=torch.float32) * 600\n"
+ "kp2 = kp1 * 1.1 + 5\n"
+ "model, mask = RANSAC('homography', seed=0, max_lo_iters=0, refine_iters=0, compile=True)(kp1, kp2)\n"
+ "print(int(mask.sum()), counters['stats']['unique_graphs'])\n"
+ )
+ env = {**os.environ, "TORCHINDUCTOR_CACHE_DIR": str(tmp_path), "KORNIA_RANSAC_AOT": "1"}
+ outputs = []
+ # The first process writes the float32/default one-thread artifact. A different ambient dtype and thread
+ # count must not load an artifact guarded for that process; the third process proves its own key is reusable.
+ for threads, dtype in ((1, "float32"), (2, "float64"), (2, "float64")):
+ result = subprocess.run( # noqa: S603 - fixed script and interpreter; no shell or external input.
+ [sys.executable, "-c", script],
+ env={**env, "RANSAC_TEST_THREADS": str(threads), "RANSAC_TEST_DTYPE": dtype},
+ capture_output=True,
+ text=True,
+ check=True,
+ timeout=600,
+ )
+ outputs.append(result.stdout.split())
+ assert list((tmp_path / "kornia_ransac").glob("*.bin"))
+ assert [output[0] for output in outputs] == ["300"] * 3
+ assert int(outputs[0][1]) >= 1 and int(outputs[1][1]) >= 1 and outputs[2][1] == "0"
+
+
class TestRANSACDegensacOptions(BaseTester):
@pytest.mark.parametrize(
"model_type", ["fundamental", "fundamental_7pt", "fundamental_8pt", "homography", "essential"]
diff --git a/tests/geometry/test_ransac_refinement.py b/tests/geometry/test_ransac_refinement.py
index 5843b0d00..22b139d96 100644
--- a/tests/geometry/test_ransac_refinement.py
+++ b/tests/geometry/test_ransac_refinement.py
@@ -106,6 +106,36 @@ class TestRANSACRefinementCPU(BaseTester):
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"])
+ @pytest.mark.parametrize("loss", ["truncated", "cauchy"])
+ def test_numeric_zero_mask_excludes_singular_correspondence(self, device, dtype, model, loss):
+ # A zero numeric mask is how the compiled RANSAC program drops its padding rows. It cannot use the CPU
+ # boolean-mask compaction, so the residual and Jacobian must be made finite before masking. The appended
+ # correspondence lies at a projective horizon for H and at both epipoles for F/E.
+ refine, matrix, x1, x2 = self.scene(device, dtype, model)
+ if model == "homography":
+ matrix = matrix.new_tensor([[[1.0, 0.0, 0.0], [0.0, 0.0, 1.0], [0.0, 1.0, 0.0]]])
+ singular_x1 = x1.new_tensor([[1.0, 0.0, 1.0]])
+ singular_x2 = x2.new_tensor([[0.0, 0.0]])
+ else:
+ matrix = matrix.new_tensor([[[0.0, -0.8, 0.0], [1.0, 0.0, 0.0], [0.0, 0.0, 0.0]]])
+ if model == "essential":
+ matrix = matrix / matrix.norm(dim=(-2, -1), keepdim=True)
+ singular_x1 = x1.new_tensor([[0.0, 0.0, 1.0]])
+ singular_x2 = x2.new_tensor([[0.0, 0.0, 1.0]])
+ weights = x1.new_ones(1, len(x1) + 1)
+ weights[0, -1] = 0.0
+ with torch.no_grad():
+ # 0.1 keeps the retained residuals away from the truncated-loss acceptance boundary, where
+ # adding an otherwise zero row can change float32 reduction order.
+ initial = refine(matrix, x1, x2, None, loss, 0.1, 0)
+ expected = refine(matrix, x1, x2, None, loss, 0.1, 5)
+ actual = refine(matrix, torch.cat([x1, singular_x1]), torch.cat([x2, singular_x2]), weights, loss, 0.1, 5)
+ assert torch.isfinite(actual).all()
+ assert (expected - initial).norm() > 1e-3
+ 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)