π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
feat(feature): add specialized top-k SIFT scale-space pipeline (#4638)
Dmytro Mishkincecb47bc743e
diff --git a/.github/scripts/check_torch_env.py b/.github/scripts/check_torch_env.pyindex 6574a3081..65b1b3f5e 100644--- a/.github/scripts/check_torch_env.py+++ b/.github/scripts/check_torch_env.py@@ -108,30 +108,41 @@ def runtime_requirements(return kept-def scan_installed() -> tuple[dict[str, str], dict[str, list[str]]]:+def scan_installed(paths: Iterable[str] | None = None) -> tuple[dict[str, str], dict[str, list[str]]]:"""Return every installed distribution's version, and the names that resolve ambiguously.``distributions()`` walks ``sys.path`` in order and the first match wins, which is what``importlib.metadata.version`` and a plain ``import`` resolve to, so first-wins is the- honest answer across path entries. Two ``.dist-info`` directories for one name *inside a- single* path entry have no such order -- that is a half-written venv, exactly what an+ honest answer across path entries. Two ``.dist-info`` directories for one name *inside one*+ distribution location have no such order -- that is a half-written venv, exactly what aninterrupted ``uv pip install --reinstall-package torch`` leaves behind -- so those arereported rather than settled by whichever the filesystem happened to yield first.Returns:- The canonical-name-to-version map, and the names seen with disagreeing versions.+ The canonical-name-to-version map, and the names seen with disagreeing versions in+ one distribution location. ``paths`` is an optional metadata search path, used by+ self-contained tests; production scans ``sys.path``."""found: dict[str, str] = {}- seen: dict[str, set[str]] = {}- for dist in distributions():+ seen: dict[tuple[str, str], set[str]] = {}+ available = distributions() if paths is None else distributions(path=list(paths))+ for dist in available:name = dist.metadata["Name"]if not name:continuecanonical = canonicalize_name(name)found.setdefault(canonical, dist.version)- seen.setdefault(canonical, set()).add(dist.version)- return found, {name: sorted(versions) for name, versions in seen.items() if len(versions) > 1}+ # setuptools adds its vendored distributions to sys.path. Ordered locations+ # intentionally shadow one another; this is not a broken virtualenv. Only+ # conflicting metadata in one location is ambiguous.+ location = str(dist.locate_file(""))+ seen.setdefault((location, canonical), set()).add(dist.version)+ duplicate_versions: dict[str, set[str]] = {}+ for (_, name), versions in seen.items():+ if len(versions) > 1:+ duplicate_versions.setdefault(name, set()).update(versions)+ return found, {name: sorted(versions) for name, versions in duplicate_versions.items()}def installed_versions() -> dict[str, str]:diff --git a/benchmarks/README.md b/benchmarks/README.mdindex 8b787077a..1c7220990 100644--- a/benchmarks/README.md+++ b/benchmarks/README.md@@ -15,6 +15,10 @@ baselines. Goal: current, citable numbers with disclosed methodology β where k| [`feature/`](feature/) | Local-feature detector benchmarks incl. quality (matching) metrics; [`laf_ops.py`](feature/laf_ops.py) microbenchmarks the shared LAF operations and [`ellipse_to_laf.py`](feature/ellipse_to_laf.py) drills into one of them (both base-revision A/B β no cross-library baseline exists). [`local_features.py`](feature/local_features.py) measures Oxford graf speed and homography corner error for SIFT, SIFT-AffNet-HardNet and KeyNet-HardNet on CPU, CUDA or MPS (`--device cpu --timing-pairs 2` times the representative 1β2 pair and still scores all five); results in [`graf_benchmark.md`](feature/graf_benchmark.md). [`sift_runtime.py`](feature/sift_runtime.py) and [`plot_sift_runtime.py`](feature/plot_sift_runtime.py) chart scale-space SIFT runtime across releases and batch sizes; results in [`sift_runtime.md`](feature/sift_runtime.md). || [`common.py`](common.py) | Shared methodology utilities β use these in every new benchmark. |+[`feature/sift_scale_space.py`](feature/sift_scale_space.py) compares complete SIFT+extraction, matching and homography quality on CPU, CUDA or MPS;+[device results and usage](feature/sift_summary.md).+## Methodology contractEvery benchmark here must follow the same rules (utilities in [`common.py`](common.py)):@@ -119,6 +123,9 @@ version-directory rules; `load` is optional there because a base revision's harnit. The report states what was measured, on which commits, with which command, in the style ofthe sample-results sections below.+PR #4638 keeps its historical measurements in an [immutable archive](https://github.com/kornia/kornia/tree/efb04dbf9c85e4cf71625cc2467bd5243b0c803c/benchmarks),+with figures embedded in the PR description. Local reruns should write JSON outside the checkout.+## Sample results β geometry flagship opsDirectional numbers only β reproduce on your own hardware for anything you cite. Measureddiff --git a/benchmarks/common.py b/benchmarks/common.pyindex 2d3703c10..3ea748d88 100644--- a/benchmarks/common.py+++ b/benchmarks/common.py@@ -44,17 +44,23 @@ import torch.utils.benchmark as benchdef time_us(- fn: Callable[[], object], min_run_time: float = 1.0, sync: Optional[Callable[[], None]] = None+ fn: Callable[[], object],+ min_run_time: float = 1.0,+ sync: Optional[Callable[[], None]] = None,+ num_threads: int = 1,) -> tuple[float, float]:"""Median and interquartile-range wall clock of ``fn`` in microseconds.``blocked_autorange`` warms up, runs many repeats, and synchronizes CUDA. Devices it doesnot sync (MPS) pass their sync as ``sync`` so it lands inside the timed region. Returns``(nan, nan)`` if ``fn`` raises, so callers can render a skip cell instead of dying.+ ``num_threads`` controls the timed calls; Timer otherwise overrides the caller's thread count with one."""stmt = "fn(); sync()" if sync is not None else "fn()"try:- m = bench.Timer(stmt=stmt, globals={"fn": fn, "sync": sync}).blocked_autorange(min_run_time=min_run_time)+ m = bench.Timer(stmt=stmt, globals={"fn": fn, "sync": sync}, num_threads=num_threads).blocked_autorange(+ min_run_time=min_run_time+ )return m.median * 1e6, m.iqr * 1e6except Exception:return float("nan"), float("nan")diff --git a/benchmarks/common_test.py b/benchmarks/common_test.pyindex 5b36b8f4c..68e04ff92 100644--- a/benchmarks/common_test.py+++ b/benchmarks/common_test.py@@ -52,6 +52,15 @@ def test_time_us_accepts_sync_callable():assert calls # sync ran inside the timed region+def test_time_us_uses_requested_threads_and_restores_caller():+ threads = torch.get_num_threads()+ observed = set()+ median, _ = time_us(lambda: observed.add(torch.get_num_threads()), min_run_time=0.01, num_threads=2)+ assert median > 0+ assert observed == {2}+ assert torch.get_num_threads() == threads++def test_run_metadata_records_environment():meta = run_metadata(torch.device("cpu"))assert meta["torch"] == torch.__version__diff --git a/benchmarks/feature/sift_scale_space.py b/benchmarks/feature/sift_scale_space.pynew file mode 100644index 000000000..c848de04f--- /dev/null+++ b/benchmarks/feature/sift_scale_space.py@@ -0,0 +1,365 @@+# 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.+#+"""End-to-end SIFT descriptor-backend comparison on Oxford graf.++Run from the measured checkout root::++ python -m benchmarks.feature.sift_scale_space --seq /data/graf \\+ --expected-checkout "$PWD" --device cuda --json graf-sift-scale-space.json++Both public :class:`kornia.feature.SIFTFeatureScaleSpace` backends run their+whole forward pass: DoG detection, orientation, and RootSIFT description. The+patch implementation is constructed without ``descriptor_backend`` so this+harness can also measure a checkout from before that public argument existed.+Timing excludes image I/O, matching, and RANSAC. Matching uses SNN ratio 0.8;+quality is forward ground-truth transfer precision at three pixels and the+existing fixed-seed Graf homography RANSAC corner metric. MPS runs RANSAC on+CPU because MPS batched SVD is unsafe; it remains outside the timed region.+Optional ``--methods opencv --device cpu`` measures native uint8 CPU SIFT with+standard rejection filters plus NumPy RootSIFT; input conversion and conversion+of returned keypoints to Torch tensors are excluded. It shares the grayscale input and matching/RANSAC protocol.+"""++from __future__ import annotations++import argparse+import hashlib+import importlib.util+import json+import math+import sys+import tempfile+import time+from pathlib import Path++import numpy as np+import torch++import kornia+import kornia.feature as KF+from kornia.geometry import RANSAC, transform_points++if importlib.util.find_spec("PIL") is None:+ raise SystemExit("SKIP: this benchmark requires the optional Pillow package")+from PIL import Image++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))+from common import collect_load_metrics, run_metadata, save_json, time_us, versions_line+++def homography_quality(+ source: torch.Tensor, target: torch.Tensor, ground_truth: torch.Tensor, height: int, width: int+) -> dict:+ """Estimate a homography with the existing graf benchmark RANSAC protocol.++ RANSAC consensus is not ground-truth accuracy: a wrong model can have many+ inliers, so retain its corner error even when large. Failed estimates have+ a null error, never a misleading zero.+ """+ result = {"ransac_inliers": 0, "ransac_corner_error_px": None, "ransac_status": "insufficient_matches"}+ if source.shape[0] < 4:+ return result+ ransac = RANSAC("homography", inl_th=2.0, max_iter=10, batch_size=8196, confidence=0.9999, seed=3407)+ estimate, mask = ransac(source, target)+ inliers = int(mask.sum())+ result["ransac_inliers"] = inliers+ result["ransac_status"] = "failed_estimate"+ if inliers < 4 or not torch.isfinite(estimate).all():+ return result+ corners = source.new_tensor([[0, 0], [0, height - 1], [width - 1, height - 1], [width - 1, 0]])+ # Use explicit homogeneous division to reject a corner at infinity. This+ # matches the original graf L1 metric for finite homography projections.+ homogeneous = torch.cat([corners, torch.ones_like(corners[:, :1])], dim=-1)+ prediction = homogeneous @ estimate.T+ reference = homogeneous @ ground_truth.reshape(3, 3).to(source).T+ if (prediction[:, 2].abs() <= 1e-8).any() or (reference[:, 2].abs() <= 1e-8).any():+ result["ransac_status"] = "nonfinite_projection"+ return result+ distance = (prediction[:, :2] / prediction[:, 2:] - reference[:, :2] / reference[:, 2:]).abs().sum(-1)+ if not torch.isfinite(distance).all():+ result["ransac_status"] = "nonfinite_projection"+ return result+ result["ransac_corner_error_px"] = distance.mean().item()+ result["ransac_status"] = "estimated"+ return result+++def _image_path(seq: Path, index: int) -> Path:+ for extension in ("ppm", "png"):+ path = seq / f"img{index}.{extension}"+ if path.is_file():+ return path+ raise FileNotFoundError(f"No img{index}.ppm or img{index}.png in {seq}")+++def _load_image(path: Path, device: torch.device) -> torch.Tensor:+ pixels = np.array(Image.open(path).convert("L"), copy=True)+ return torch.from_numpy(pixels).to(device=device, dtype=torch.float32)[None, None].div_(255.0)+++def _build(method: str, num_features: int, device: torch.device) -> torch.nn.Module:+ # Deliberately leave this keyword off the patch constructor: the same file is+ # useful when run from a pre-feature base checkout where the new API is absent.+ if method == "patch":+ return KF.SIFTFeatureScaleSpace(num_features=num_features, rootsift=True, device=device).eval()+ return KF.SIFTFeatureScaleSpace(+ num_features=num_features, rootsift=True, device=device, descriptor_backend="pyramid"+ ).eval()+++def _profile_cpu_allocations(run) -> dict[str, int]:+ """Measure tensor allocation churn and peak live bytes in a separate forward.++ These are PyTorch CPU allocator events, not RSS or measured DRAM traffic.+ Native-library workspaces outside the allocator are not included.+ """+ with torch.profiler.profile(activities=[torch.profiler.ProfilerActivity.CPU], profile_memory=True) as profile:+ run()+ with tempfile.TemporaryDirectory(prefix="kornia-sift-profile-") as directory:+ path = Path(directory) / "trace.json"+ profile.export_chrome_trace(str(path))+ events = json.loads(path.read_text())["traceEvents"]+ allocations = sorted(+ (event for event in events if event.get("name") == "[memory]" and event["args"]["Device Type"] == 0),+ key=lambda event: event["ts"],+ )+ if not allocations:+ raise RuntimeError("CPU profiler did not record allocation events")+ live = peak = allocated = 0+ for event in allocations:+ size = event["args"]["Bytes"]+ live += size+ peak = max(peak, live)+ allocated += max(0, size)+ return {"cpu_peak_live_tensor_bytes": peak, "cpu_total_allocated_tensor_bytes": allocated}++[email protected]_mode()+def main() -> None:+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)+ parser.add_argument("--seq", type=Path, required=True)+ parser.add_argument("--expected-checkout", type=Path, required=True)+ parser.add_argument("--device", choices=("cpu", "mps", "cuda"), default="cpu")+ parser.add_argument("--threads", type=int, default=1, help="CPU threads, including inside timed calls")+ parser.add_argument("--nf", type=int, default=4096)+ parser.add_argument("--methods", nargs="+", choices=("patch", "pyramid", "opencv"), default=["patch", "pyramid"])+ parser.add_argument("--min-run-time", type=float, default=1.0)+ parser.add_argument("--quality-only", action="store_true")+ parser.add_argument("--profile-memory", action="store_true", help="Profile CPU tensor allocations outside timing")+ parser.add_argument("--json", type=Path, required=True)+ args = parser.parse_args()+ if args.threads < 1:+ parser.error("--threads must be positive")+ if args.profile_memory and (args.device != "cpu" or "opencv" in args.methods):+ parser.error("--profile-memory supports PyTorch CPU methods only")+ if "opencv" in args.methods:+ if args.device != "cpu":+ parser.error("OpenCV SIFT is a CPU baseline; run --methods opencv --device cpu")+ if importlib.util.find_spec("cv2") is None:+ raise SystemExit("SKIP: the OpenCV baseline requires optional opencv-python")+ import cv2++ cv2.setNumThreads(args.threads)++ imported_root = Path(kornia.__file__).resolve().parents[1]+ print(f"# interpreter: {sys.executable}\n# kornia: {kornia.__file__}", flush=True)+ if imported_root != args.expected_checkout.resolve():+ raise RuntimeError(f"Wrong Kornia checkout: {imported_root}")+ torch.manual_seed(0)+ torch.set_num_threads(args.threads)+ torch.backends.cuda.matmul.allow_tf32 = False+ torch.backends.cudnn.allow_tf32 = False+ device = torch.device(args.device)+ sync = {"cuda": torch.cuda.synchronize, "mps": torch.mps.synchronize}.get(device.type, lambda: None)+ ransac_device = torch.device("cpu") if device.type == "mps" else device++ paths = [_image_path(args.seq, index) for index in range(1, 7)]+ homographies = [args.seq / f"H1to{index}p" for index in range(2, 7)]+ images = [_load_image(path, device) for path in paths]+ meta = run_metadata(device)+ meta.update(+ load=collect_load_metrics(),+ sequence=args.seq.name,+ num_features=args.nf,+ seed=0,+ rootsift=True,+ descriptor_backends=args.methods,+ timing=(+ "entire SIFTFeatureScaleSpace forward (detection + orientation + description); "+ "or native uint8 OpenCV detectAndCompute + RootSIFT; I/O, matching and RANSAC excluded"+ ),+ min_run_time=args.min_run_time,+ timer_num_threads=args.threads,+ quality_only=args.quality_only,+ profile_memory=args.profile_memory,+ matching_ratio=0.8,+ precision_threshold_px=3.0,+ precision_metric="forward GT transfer Euclidean error",+ ransac_device=str(ransac_device),+ ransac={+ "model": "homography",+ "seed": 3407,+ "inlier_threshold_px": 2.0,+ "max_iter": 10,+ "batch_size": 8196,+ "confidence": 0.9999,+ },+ ransac_corner_metric="mean L1 corner transfer error against GT in pixels",+ image_conversion="Pillow RGB to L",+ compile=False,+ opencv_regime="uint8 CPU detectAndCompute + NumPy RootSIFT; input/keypoint-to-Torch conversion excluded",+ opencv_parameters={"nOctaveLayers": 3, "contrastThreshold": 0.04, "edgeThreshold": 10, "sigma": 1.6},+ cudnn_allow_tf32=torch.backends.cudnn.allow_tf32,+ cudnn_benchmark=torch.backends.cudnn.benchmark,+ input_sha256={path.name: hashlib.sha256(path.read_bytes()).hexdigest() for path in paths + homographies},+ implementation_sha256={+ str(path.relative_to(imported_root)): hashlib.sha256(path.read_bytes()).hexdigest()+ for path in (+ Path(__file__),+ Path(kornia.__file__).parent / "feature" / "integrated.py",+ Path(kornia.__file__).parent / "feature" / "scale_space_detector.py",+ Path(kornia.__file__).parent / "feature" / "sift" / "scale_space.py",+ Path(kornia.__file__).parent / "feature" / "siftdesc.py",+ Path(kornia.__file__).parent / "geometry" / "transform" / "pyramid.py",+ Path(kornia.__file__).parent / "geometry" / "subpix" / "spatial_soft_argmax.py",+ )+ if path.is_file()+ },+ )+ print(f"# {meta['git_commit']} | {meta['platform']} | {meta.get('cuda_device', device)}", flush=True)+ print(versions_line(meta), flush=True)++ rows: list[dict] = []+ for method in args.methods:+ torch.manual_seed(0)+ model = (+ cv2.SIFT_create(nfeatures=args.nf, nOctaveLayers=3, contrastThreshold=0.04, edgeThreshold=10, sigma=1.6)+ if method == "opencv"+ else _build(method, args.nf, device)+ )+ outputs: list[tuple[torch.Tensor, torch.Tensor]] = []+ print(f"# {method}: {model!r}", flush=True)+ for index, image in enumerate(images, 1):+ if method == "opencv":+ pixels = image[0, 0].mul(255).round().to(torch.uint8).numpy()++ def run(pixels=pixels, model=model):+ keypoints, desc = model.detectAndCompute(pixels, None)+ if desc is None:+ desc = np.empty((0, 128), dtype=np.float32)+ desc = np.sqrt(desc / (np.abs(desc).sum(axis=1, keepdims=True) + 1e-8))+ return keypoints, desc++ else:++ def run(image=image, model=model):+ return model(image)++ sync()+ start = time.perf_counter()+ extracted = run()+ sync()+ warm_seconds = time.perf_counter() - start+ if method == "opencv":+ keypoints, desc = extracted+ points = torch.tensor([kp.pt for kp in keypoints], dtype=torch.float32).reshape(-1, 2)+ descriptors = torch.from_numpy(desc)[None]+ filled = torch.ones(len(keypoints), dtype=torch.bool)+ else:+ lafs, _responses, descriptors = extracted+ filled = KF.laf_is_filled(lafs)[0]+ lafs = lafs[:, filled]+ descriptors = descriptors[:, filled]+ points = KF.get_laf_center(lafs)[0]+ if not torch.isfinite(descriptors).all():+ raise RuntimeError(f"Nonfinite descriptors for {method}, image {index}")+ median, iqr = float("nan"), float("nan")+ if not args.quality_only:+ median, iqr = time_us(+ run,+ min_run_time=max(args.min_run_time, 5.0 * warm_seconds),+ sync=sync if device.type == "mps" else None,+ num_threads=args.threads,+ )+ if not math.isfinite(median):+ raise RuntimeError(f"Timing failed for {method}, image {index}")+ outputs.append((points, descriptors[0]))+ row = {+ "op": "OpenCVSIFT" if method == "opencv" else "SIFTFeatureScaleSpace",+ "backend": method,+ "batch": 1,+ "image": index,+ "height": image.shape[-2],+ "width": image.shape[-1],+ "dtype": "uint8" if method == "opencv" else "float32",+ "features": int(filled.sum()),+ "median_us": median,+ "iqr_us": iqr,+ "throughput_per_s": 1e6 / median if math.isfinite(median) else float("nan"),+ }+ if args.profile_memory:+ row.update(_profile_cpu_allocations(run))+ rows.append(row)+ if not args.quality_only:+ print(+ f" img{index}: {median / 1000:.2f} ms +/- {iqr / 1000:.2f}; {int(filled.sum())} features",+ flush=True,+ )+ save_json(args.json, meta, rows)++ points1, descriptors1 = outputs[0]+ for index, (points2, descriptors2) in enumerate(outputs[1:], 2):+ _distance, matches = KF.match_snn(descriptors1, descriptors2, 0.8)+ ground_truth = torch.tensor(np.loadtxt(args.seq / f"H1to{index}p"), device=device, dtype=torch.float32)[+ None+ ]+ projected = transform_points(ground_truth, points1[None])[0]+ error = (projected[matches[:, 0]] - points2[matches[:, 1]]).norm(dim=-1)+ correct = int((error <= 3.0).sum())+ count = len(matches)+ geometry = homography_quality(+ points1[matches[:, 0]].to(ransac_device),+ points2[matches[:, 1]].to(ransac_device),+ ground_truth.to(ransac_device),+ *images[0].shape[-2:],+ )+ rows.append(+ {+ "op": "matching_quality",+ "backend": method,+ "batch": 1,+ "pair": f"1-{index}",+ "median_us": None,+ "iqr_us": None,+ "throughput_per_s": None,+ "matches": count,+ "correct_matches": correct,+ "precision": correct / count if count else 0.0,+ "median_transfer_error_px": error.median().item() if count else None,+ **geometry,+ }+ )+ print(+ f" 1-{index}: {correct}/{count} correct; RANSAC {geometry['ransac_inliers']} inliers, "+ f"corner L1 {geometry['ransac_corner_error_px']}",+ flush=True,+ )+ save_json(args.json, meta, rows)+++if __name__ == "__main__":+ main()diff --git a/benchmarks/feature/sift_summary.md b/benchmarks/feature/sift_summary.mdnew file mode 100644index 000000000..1384d17fe--- /dev/null+++ b/benchmarks/feature/sift_summary.md@@ -0,0 +1,110 @@+# SIFT pipeline benchmark++[`sift_scale_space.py`](sift_scale_space.py) compares the public patch and pyramid+`SIFTFeatureScaleSpace` backends on an Oxford-format six-image sequence, including+matching and homography quality. It supports CPU, CUDA and MPS, explicit thread counts,+optional OpenCV SIFT, quality-only runs and separate CPU tensor-allocation profiling.+The default library backend remains `patch`.++## Usage++Run from each measured checkout root with the same Pixi-selected interpreter:++```bash+python -m benchmarks.feature.sift_scale_space \+ --seq /path/to/graf --expected-checkout "$PWD" \+ --device cpu --threads 1 --methods patch pyramid --json /tmp/sift-cpu.json+# Use --device cuda or --device mps for accelerators.+# Use --methods opencv --device cpu for the optional native uint8 OpenCV baseline.+# --quality-only skips timing; --profile-memory profiles CPU allocations separately.+```++For revision comparisons, run the same script and `benchmarks/common.py` in both+checkouts and reverse revision order. The script verifies the imported checkout and+records versions, source/input hashes, feature counts, timing medians/IQRs and quality.+CPU profiling measures PyTorch tensor allocations, not RSS or DRAM traffic.+Keep generated JSON outside the repository.++## Recorded device results++These are optimization stages **within PR #4638**, not comparisons with main or a release.+Each row has its own measured baseline. Ratios are before / after; below 1Γ means slower.+Do not multiply ratios from separate measurement sessions into a cumulative speedup.++| Backend / optimization stage | Hardware / execution | Before β after (ms/image) | Speedup | Library revisions |+| --- | --- | ---: | ---: | --- |+| Pyramid / initial pass | Apple M1 CPU, 1 thread | 1201.12 β 794.80 | 1.51Γ | `3172b5f1` β `bc790974` |+| Pyramid / initial pass | Apple M1 MPS | 622.61 β 587.22 | 1.06Γ | `3172b5f1` β `bc790974` |+| Pyramid / memory pass | Apple M1 CPU, 1 thread | 821.86 β 674.91 | 1.22Γ | `bc790974` β `7547be2c` |+| Pyramid / memory pass | Apple M1 MPS | 677.95 β 628.79 | 1.08Γ | `bc790974` β `7547be2c` |+| Pyramid / initial + memory passes | Intel i7-14700K CPU, 1 thread | 1236.77 β 510.95 | 2.42Γ | `3172b5f1` β `7547be2c` |+| Pyramid / initial + memory passes | Intel i7-14700K CPU, 14 threads | 424.80 β 241.44 | 1.76Γ | `3172b5f1` β `7547be2c` |+| Pyramid / initial + memory passes | NVIDIA RTX 4090 CUDA | 120.77 β 102.49 | 1.18Γ | `3172b5f1` β `7547be2c` |+| Pyramid / CUDA pass | Intel i7-14700K CPU, 1 thread | 499.73 β 495.76 | 1.01Γ | `7547be2c` β `40bcf122` |+| Pyramid / CUDA pass | Intel i7-14700K CPU, 14 threads | 234.76 β 240.87 | 0.97Γ | `7547be2c` β `40bcf122` |+| Pyramid / CUDA pass | NVIDIA RTX 4090 CUDA | 105.50 β 78.99 | 1.34Γ | `7547be2c` β `40bcf122` |+| Default patch / shared interpolation | Intel i7-14700K CPU, 1 thread | 1450.40 β 1629.86 | 0.890Γ | `40bcf122` β `fa3d732c` |+| Default patch / shared interpolation | Intel i7-14700K CPU, 14 threads | 466.52 β 478.94 | 0.974Γ | `40bcf122` β `fa3d732c` |+| Default patch / shared interpolation | NVIDIA RTX 4090 CUDA | 59.50 β 57.03 | 1.043Γ | `40bcf122` β `fa3d732c` |++Graf images 1β6, 640Γ800 grayscale, batch one, FP32 RootSIFT, 4,096 returned features/image,+eager full forward including pyramid construction and allocations. Timings exclude I/O,+transfers, matching, RANSAC and profiling. Values average six warmed per-image medians;+Intel/CUDA uses two reversed-order runs, Apple one run per revision. IQR describes spread,+not confidence. Apple: M1, macOS 26.5.1, PyTorch 2.14.0. Intel/NVIDIA: i7-14700K / RTX 4090,+WSL2, PyTorch 2.14.0+cu130, TF32 disabled, CUDA host one thread. Both use Python 3.11.14.++### Review follow-up: descriptor octave selection++`SIFTDescriptorFromPyramid` binned gradients and pooled descriptor histograms at+**every** octave below the highest one any LAF selected, even when no LAF sampled+them. Building the maps only for occupied octaves leaves the descriptors bitwise+unchanged on CPU and costs nothing when every octave is occupied. 640Γ800 image,+64 frames, one forward, `torch.utils.benchmark` medians, same process per revision,+`99e92b78` β review fixes:++| Frame octaves | i7-14700K, 1 thread | i7-14700K, 14 threads | RTX 4090 |+| --- | ---: | ---: | ---: |+| all octave 0 (nothing skipped) | 538.5 β 528.5 ms (1.02Γ) | 114.1 β 115.5 ms (0.99Γ) | 7.58 β 7.57 ms (1.00Γ) |+| all octave 1 | 658.3 β 118.6 ms (5.5Γ) | 146.6 β 36.8 ms (4.0Γ) | 12.05 β 6.29 ms (1.9Γ) |+| all octave 2 | 693.0 β 33.4 ms (20.7Γ) | 155.4 β 12.7 ms (12.2Γ) | 14.77 β 6.51 ms (2.3Γ) |+| all octave 3 | 688.5 β 14.9 ms (46Γ) | 157.8 β 6.5 ms (24Γ) | 18.58 β 6.83 ms (2.7Γ) |+| mixed scales (every octave occupied) | 690.7 β 693.9 ms (1.00Γ) | 166.9 β 160.4 ms (1.04Γ) | 22.47 β 22.79 ms (0.99Γ) |++The octave-2 case also drops its largest CPU allocation from 382 to 18 MiB and CUDA+peak from 314 to 29 MiB. A full DoG detector spreads its detections over every+octave, so `SIFTFeature(descriptor_backend="pyramid")` end to end is unchanged+(RTX 4090 34.3 β 34.4 ms; 14 threads 332 β 320 ms, both within spread). The win+applies to externally supplied or scale-filtered frames.++The same session re-ran the table above's harness across the review fixes. Graf+quality is identical for both backends, and no timing moved outside its spread:+pyramid 69.4 β 70.8 ms CUDA, 487 β 486 ms at one thread, 245.7 β 248.9 ms at 14+threads; patch 55.15 β 55.16 ms CUDA. Making the pyramid's Gaussian kernels+float64 references rather than float32 has no measurable cost: interleaved in one+process, `_SIFTScalePyramid` measures 2576 Β΅s with float64 buffers and 2577 Β΅s with+float32 buffers on CUDA, 132.9 ms and 134.3 ms at one CPU thread.++CUDA pyramid batch two additionally measured **140.19 β 97.41 ms/batch (1.44Γ)** in one run+per revision. Apple memory changes reduced peak live CPU tensor allocations by **20% on+Graf and 73% on checkerboard**. CUDA pyramid peak extra tensor allocation remained ~238 MiB.+The last shared-interpolation pass retains CPU arithmetic; its measured CPU losses remain+in the table and establish no CPU speedup.++## Quality and limits++Default patch SIFT remains faster on CUDA (~57 versus ~79 ms in separate latest sessions).+Pyramid finds more correct Graf matches and recovers pair 1β5; **both fail pair 1β6**.+Matching uses SNN ratio 0.8, a 3 px correct-match threshold, and homography RANSAC with+2 px threshold and seed 3407; corner error is mean L1 discrepancy against ground truth.+All quality rows are unchanged by the CUDA/shared-interpolation passes. The first CPU+pass changed correct-match counts by at most one, with both better and worse corner errors.++Graf informed development and is not held out. Native FP16/BF16 forwards were checked,+but no half-precision speedup is established. Larger batches and end-to-end compiled+performance are unverified. MPS was not rerun for the CUDA follow-ups. These are archived+measurements, not new measurements of the merged PR head.++Figures live in the [PR description](https://github.com/kornia/kornia/pull/4638).+Historical raw measurements, per-image IQRs, controls, detailed reports and one-off scripts+remain available in the [archive](https://github.com/kornia/kornia/tree/efb04dbf9c85e4cf71625cc2467bd5243b0c803c/benchmarks).diff --git a/changelog.d/4638.added.md b/changelog.d/4638.added.mdnew file mode 100644index 000000000..6cfab756b--- /dev/null+++ b/changelog.d/4638.added.md@@ -0,0 +1,13 @@+`SIFTFeature` and `SIFTFeatureScaleSpace` now accept `descriptor_backend="pyramid"` for fast extraction at their sparse detections. `SIFTDescriptorFromPyramid` describes supplied LAFs and can share an extraction pyramid between orientation assignment and description.++The scale-space preset has a dedicated backend that reuses the detector Gaussian pyramid and retained octave/layer assignments, computing gradients once per used level. It preserves sparse detections and integrates rotated SIFT histograms directly from gradient fields.++The optimized scale-space path also specializes DoG detection: sparse refinement, exact octave coordinates, and top-K response ranking without contrast or edge rejection. The default patch backend remains available.++CPU Gaussian filtering avoids convolution work buffers; sparse neighbourhood gathers, two-bin angular voting, and device-specific descriptor chunks reduce extraction time without reducing integration support or the requested feature budget. Compiled and eager pyramid backends share checkpoint keys and support full-module serialization.++CPU inference builds Gaussian volumes directly in their final storage and reuses sampling coordinates; gradient atlases also avoid a full transpose copy. Spatial ties are rejected before bounded sparse gathers. Empty detections and descriptors retain zero gradients, and half-precision masks preserve their suppression semantics.++CUDA uses packed sparse refinement and separable descriptor histogram pooling to reduce kernel launches and extraction time while retaining bounded descriptor chunks. CPU and MPS keep their existing refinement paths.++Shared `conv_quad_interp3d` and `iterative_quad_interp3d` now group finite differences and Cramer determinants on CUDA float32/float64, also accelerating the default patch-based `SIFTFeatureScaleSpace` pipeline. CPU, MPS and reduced-precision inputs retain their scalar paths.diff --git a/docs/generate_examples.py b/docs/generate_examples.pyindex aa9c0cc71..829916ab8 100644--- a/docs/generate_examples.py+++ b/docs/generate_examples.py@@ -720,6 +720,8 @@ def main():"DISK","ALIKED","XFeat",+ "SIFTDescriptorFromPyramid",+ "SIFTFeatureScaleSpace",]# ITERATE OVER THE TRANSFORMSfor fn_name in responses:@@ -752,6 +754,34 @@ def main():out = torch.nn.functional.interpolate(out, img_outdoor.shape[-2:], mode="bilinear", align_corners=False)out = K.color.grayscale_to_rgb(out)img_in = img_outdoor+ elif fn_name == "SIFTFeatureScaleSpace":+ fn = K.feature.SIFTFeatureScaleSpace(num_features=2048, descriptor_backend="pyramid").eval()+ with torch.no_grad():+ lafs, scores, _ = fn(img_in)+ h, w = img_in.shape[-2:]+ valid = K.feature.laf_is_filled(lafs)[0]+ xy = K.feature.get_laf_center(lafs)[0, valid].round().long()+ heatmap = img_in.new_zeros(1, 1, h * w)+ index = xy[:, 1].clamp(0, h - 1) * w + xy[:, 0].clamp(0, w - 1)+ heatmap[0, 0].scatter_add_(0, index, scores[0, valid].abs())+ out = K.color.grayscale_to_rgb(F.max_pool2d(heatmap.view(1, 1, h, w), 5, stride=1, padding=2))+ img_in = K.color.grayscale_to_rgb(img_in)+ elif fn_name == "SIFTDescriptorFromPyramid":+ # A regular LAF grid turns the sparse descriptor into a compact score map:+ # show distance to the centre descriptor on the same RGB canvas as other examples.+ h, w = img_kornia.shape[-2:]+ ys = torch.arange(12, h - 12, 12, device=img_kornia.device, dtype=img_kornia.dtype)+ xs = torch.arange(12, w - 12, 12, device=img_kornia.device, dtype=img_kornia.dtype)+ yy, xx = torch.meshgrid(ys, xs, indexing="ij")+ xy = torch.stack([xx, yy], dim=-1).reshape(1, -1, 2)+ scale = torch.full((*xy.shape[:2], 1, 1), 6.0, device=xy.device, dtype=xy.dtype)+ lafs = K.feature.laf_from_center_scale_ori(xy, scale)+ desc = K.feature.SIFTDescriptorFromPyramid().eval()(K.color.rgb_to_grayscale(img_kornia), lafs)+ centre = desc[:, desc.shape[1] // 2 : desc.shape[1] // 2 + 1]+ out = (desc - centre).square().sum(-1).sqrt().reshape(1, 1, yy.shape[0], yy.shape[1])+ out = F.interpolate(out, (h, w), mode="bilinear", align_corners=False)+ out = K.color.grayscale_to_rgb(out)+ img_in = img_korniaelse:fn = getattr(mod, fn_name)out = fn(img_in)diff --git a/docs/source/feature.descriptors.rst b/docs/source/feature.descriptors.rstindex 8c8858cfd..2a484bad0 100644--- a/docs/source/feature.descriptors.rst+++ b/docs/source/feature.descriptors.rst@@ -4,6 +4,11 @@ Descriptors.. currentmodule:: kornia.feature.. autoclass:: DenseSIFTDescriptor+ :members: get_gradient_histograms++.. autoclass:: SIFTDescriptorFromPyramid+ :members: forward, orient_and_describe+.. autoclass:: SIFTDescriptor.. autoclass:: MKDDescriptor.. autoclass:: HardNetdiff --git a/docs/source/feature.local_features.rst b/docs/source/feature.local_features.rstindex 3d752652d..8326ac8b1 100644--- a/docs/source/feature.local_features.rst+++ b/docs/source/feature.local_features.rst@@ -38,6 +38,27 @@ Local features (detector and descriptor together).. autoclass:: SIFTFeature:members: forward+The scale-space SIFT preset supports ``descriptor_backend="pyramid"`` for+specialized sparse extraction from the detector's Gaussian pyramid::++ feature = kornia.feature.SIFTFeatureScaleSpace(+ num_features=4096, descriptor_backend="pyramid"+ )+ lafs, responses, descriptors = feature(grayscale_image)++This path uses a dedicated DoG detector, with strict sparse extrema, iterative+subpixel refinement, and top-K ranking by absolute response. It applies neither+contrast nor edge rejection. Precise doubling and integer octave decimation keep+pixel coordinates aligned. The converged integer Gaussian layer and refined+continuous scale are retained separately. Gradients are computed once per used+layer and shared between orientation and description. It returns one descriptor per detection and the same fixed feature+budget as the default patch backend. Its sampling and Gaussian support differ+from patch extraction, so descriptors are not numerically interchangeable.+No pyramid is retained between calls. For this backend, ``compile_modules``+accepts ``scale_pyr`` and ``subpix`` (or ``True`` for both); sparse orientation+and description run eagerly. The default ``patch`` backend retains the existing+generic detector and its compilation options.+.. autoclass:: SIFTFeatureScaleSpace:members: forwarddiff --git a/kornia/feature/__init__.py b/kornia/feature/__init__.pyindex 00f65c589..c7d426e85 100644--- a/kornia/feature/__init__.py+++ b/kornia/feature/__init__.py@@ -92,6 +92,7 @@ from .responses import (hessian_response,)from .scale_space_detector import MultiResolutionDetector, PassLAF, ScaleSpaceDetector+from .sift import SIFTDescriptorFromPyramidfrom .siftdesc import DenseSIFTDescriptor, SIFTDescriptorfrom .sold2 import SOLD2, SOLD2_detectorfrom .sosnet import SOSNet@@ -144,6 +145,7 @@ __all__ = ["PatchAffineShapeEstimator","PatchDominantGradientOrientation","SIFTDescriptor",+ "SIFTDescriptorFromPyramid","SIFTFeature","SIFTFeatureScaleSpace","SOLD2_detector",diff --git a/kornia/feature/integrated.py b/kornia/feature/integrated.pyindex 41621ed48..df04b6304 100644--- a/kornia/feature/integrated.py+++ b/kornia/feature/integrated.py@@ -16,7 +16,7 @@#import warnings-from typing import ClassVar, Dict, List, Optional, Tuple, Union+from typing import ClassVar, Dict, List, Literal, Optional, Tuple, Unionimport torchfrom torch import nn@@ -49,6 +49,8 @@ from .scale_space_detector import (ScaleSpaceDetector,get_default_detector_config,)+from .sift import SIFTDescriptorFromPyramid+from .sift.scale_space import _SIFTScalePyramid, _SIFTScaleSpaceDescriptor, _SIFTScaleSpaceDetectorfrom .siftdesc import SIFTDescriptor@@ -164,7 +166,7 @@ class LocalFeature(nn.Module):"""- def __init__(self, detector: nn.Module, descriptor: LAFDescriptor, scaling_coef: float = 1.0) -> None:+ def __init__(self, detector: nn.Module, descriptor: nn.Module, scaling_coef: float = 1.0) -> None:super().__init__()self.detector = detectorself.descriptor = descriptor@@ -212,9 +214,34 @@ class LocalFeature(nn.Module):return (lafs, responses, descs)-class SIFTFeature(LocalFeature):+class _SIFTFeature(LocalFeature):+ """Compose a sparse SIFT detector with a patch or pyramid extraction backend."""++ def __init__(self, detector: nn.Module, descriptor: nn.Module, upright: bool) -> None:+ super().__init__(detector, descriptor)+ self.upright = upright++ def forward(+ self, img: torch.Tensor, mask: Optional[torch.Tensor] = None+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:+ """Return sparse LAFs, detector responses, and one descriptor per LAF."""+ if not isinstance(self.descriptor, SIFTDescriptorFromPyramid):+ return super().forward(img, mask)+ lafs, responses = self.detector(img, mask)+ lafs = scale_laf(lafs, self.scaling_coef)+ gray_image = rgb_to_grayscale(img) if img.shape[1] == 3 else img+ lafs, descriptors = self.descriptor.orient_and_describe(gray_image, lafs, upright=self.upright)+ return lafs, responses, descriptors+++class SIFTFeature(_SIFTFeature):"""Convenience module, which implements DoG detector + (Root)SIFT descriptor.+ ``descriptor_backend="pyramid"`` uses :class:`SIFTDescriptorFromPyramid` for+ orientation and description at the detector's sparse LAFs. Detection and the+ feature budget are unchanged. The default ``"patch"`` backend retains the+ existing patch-wise pipeline.+Using `kornia.feature.MultiResolutionDetector` without blur pyramid Still not as good as OpenCV/VLFeat because ofhttps://github.com/kornia/kornia/pull/884,but we are working on it@@ -229,7 +256,10 @@ class SIFTFeature(LocalFeature):config: Optional[Detector_config] = None,compile_model: bool = False,score_threshold: float = 0.0,+ descriptor_backend: Literal["patch", "pyramid"] = "patch",) -> None:+ if descriptor_backend not in ("patch", "pyramid"):+ raise ValueError(f"Unknown SIFT descriptor backend: {descriptor_backend!r}")patch_size: int = 41if device is None:device = torch.device("cpu")@@ -239,21 +269,34 @@ class SIFTFeature(LocalFeature):BlobDoGSingle(1.0, 1.6),num_features,config,- ori_module=PassLAF() if upright else LAFOrienter(19),+ ori_module=PassLAF() if upright or descriptor_backend == "pyramid" else LAFOrienter(19),aff_module=PassLAF(),compile_model=compile_model,score_threshold=score_threshold,).to(device)- descriptor = LAFDescriptor(- SIFTDescriptor(patch_size=patch_size, rootsift=rootsift), patch_size=patch_size, grayscale_descriptor=True- ).to(device)- super().__init__(detector, descriptor)+ descriptor: nn.Module+ if descriptor_backend == "pyramid":+ descriptor = SIFTDescriptorFromPyramid(rootsift=rootsift).to(device)+ else:+ descriptor = LAFDescriptor(+ SIFTDescriptor(patch_size=patch_size, rootsift=rootsift),+ patch_size=patch_size,+ grayscale_descriptor=True,+ ).to(device)+ super().__init__(detector, descriptor, upright)class SIFTFeatureScaleSpace(LocalFeature):"""Convenience module, which implements DoG detector + (Root)SIFT descriptor.- Using `kornia.feature.ScaleSpaceDetector` with blur pyramid.+ The default patch backend uses `kornia.feature.ScaleSpaceDetector`. Select+ ``descriptor_backend="pyramid"`` for a specialized SIFT pipeline that reuses+ the detector's Gaussian images and each detection's octave and layer. Image+ gradients are computed once per used layer and sampled for sparse orientation+ and descriptor integration. A dedicated DoG detector refines only sparse+ extrema and ranks all valid candidates by response, without contrast or edge+ rejection. The feature budget is unchanged; detections may differ.+ The default ``"patch"`` backend retains patch-wise orientation and description.Still not as good as OpenCV/VLFeat because of https://github.com/kornia/kornia/pull/884, but we are working on it"""@@ -265,25 +308,64 @@ class SIFTFeatureScaleSpace(LocalFeature):rootsift: bool = True,device: Union[str, torch.device, None] = None,compile_modules: Union[bool, List[str]] = False,+ descriptor_backend: Literal["patch", "pyramid"] = "patch",) -> None:+ if descriptor_backend not in ("patch", "pyramid"):+ raise ValueError(f"Unknown SIFT descriptor backend: {descriptor_backend!r}")if device is None:device = torch.device("cpu")patch_size: int = 41- detector = ScaleSpaceDetector(- num_features,- resp_module=BlobDoG(),- subpix_module=ConvQuadInterp3d(strict_maxima_bonus=0.0),- scale_pyr_module=ScalePyramid(3, 1.6, 32, double_image=True),- ori_module=PassLAF() if upright else LAFOrienter(19),- scale_space_response=True,- minima_are_also_good=True,- mr_size=6.0,- compile_modules=compile_modules,- ).to(device)- descriptor = LAFDescriptor(- SIFTDescriptor(patch_size=patch_size, rootsift=rootsift), patch_size=patch_size, grayscale_descriptor=True- ).to(device)+ if descriptor_backend == "pyramid":+ detector = _SIFTScaleSpaceDetector(num_features, _SIFTScalePyramid()).to(device)+ if compile_modules:+ selected = {"scale_pyr", "subpix"} if compile_modules is True else set(compile_modules)+ unknown = selected - {"scale_pyr", "subpix"}+ if unknown:+ raise ValueError("The SIFT pyramid backend supports compile_modules=['scale_pyr', 'subpix'] only")+ if "scale_pyr" in selected:+ # In-place compilation preserves buffer paths and module+ # serialization, unlike wrapping or replacing forward.+ detector.scale_pyr.compile()+ if "subpix" in selected:+ detector._refine = torch.compile(detector._refine)+ else:+ detector = ScaleSpaceDetector(+ num_features,+ resp_module=BlobDoG(),+ subpix_module=ConvQuadInterp3d(strict_maxima_bonus=0.0),+ scale_pyr_module=ScalePyramid(3, 1.6, 32, double_image=True),+ ori_module=PassLAF() if upright or descriptor_backend == "pyramid" else LAFOrienter(19),+ scale_space_response=True,+ minima_are_also_good=True,+ mr_size=6.0,+ compile_modules=compile_modules,+ ).to(device)+ descriptor: nn.Module+ if descriptor_backend == "pyramid":+ descriptor = _SIFTScaleSpaceDescriptor(rootsift=rootsift).to(device)+ else:+ descriptor = LAFDescriptor(+ SIFTDescriptor(patch_size=patch_size, rootsift=rootsift),+ patch_size=patch_size,+ grayscale_descriptor=True,+ ).to(device)super().__init__(detector, descriptor)+ self.upright = upright+ self.descriptor_backend = descriptor_backend++ def forward(+ self, img: torch.Tensor, mask: Optional[torch.Tensor] = None+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:+ """Detect and describe sparse SIFT features, sharing scale space when selected."""+ if self.descriptor_backend == "patch":+ return super().forward(img, mask)+ gray = rgb_to_grayscale(img) if img.shape[1] == 3 else img+ responses, lafs, _, pyramid, octaves, levels = self.detector._detect_with_pyramid(+ gray, self.detector.num_features, mask+ )+ lafs = scale_laf(lafs, self.scaling_coef)+ lafs, descriptors = self.descriptor(pyramid, lafs, octaves, levels, upright=self.upright)+ return lafs, responses, descriptors.to(img.dtype)class GFTTAffNetHardNet(LocalFeature):diff --git a/kornia/feature/sift/__init__.py b/kornia/feature/sift/__init__.pynew file mode 100644index 000000000..695e9ed83--- /dev/null+++ b/kornia/feature/sift/__init__.py@@ -0,0 +1,22 @@+# 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.+#++"""SIFT extraction backends for sparse local features."""++from .pyramid import SIFTDescriptorFromPyramid++__all__ = ["SIFTDescriptorFromPyramid"]diff --git a/kornia/feature/sift/pyramid.py b/kornia/feature/sift/pyramid.pynew file mode 100644index 000000000..502d0b635--- /dev/null+++ b/kornia/feature/sift/pyramid.py@@ -0,0 +1,398 @@+# 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.+#++"""Pyramid-based SIFT extraction at sparse local affine frames."""++from __future__ import annotations++from typing import Tuple++import torch+import torch.nn.functional as F+from torch import nn++from kornia.constants import pi+from kornia.core.check import KORNIA_CHECK_LAF, KORNIA_CHECK_SHAPE+from kornia.core.utils import _l2_normalize+from kornia.feature.laf import (+ _grid_sample_patches,+ _promoted_grid_dtype,+ laf_is_valid,+ rotate_laf,+)+from kornia.feature.siftdesc import _dense_sift_histograms_from_gradients, _rootsift, get_sift_pooling_kernel+from kornia.filters import get_gaussian_kernel2d, spatial_gradient+from kornia.geometry.transform import pyrdown+++class SIFTDescriptorFromPyramid(nn.Module):+ """Extract sparse SIFT descriptors from a shared image-gradient pyramid.++ This module does not detect keypoints or return a dense descriptor map.+ ``forward(image, lafs)`` describes the supplied, already oriented LAFs.+ :meth:`orient_and_describe` additionally assigns their orientation while+ sharing one pyramid between orientation assignment and description. The+ pyramid belongs to this descriptor; it is not reused from the detector.++ The module combines the shared histogram maps of `VLFeat DSIFT+ <https://www.vlfeat.org/api/dsift.html>`_ with orientation-relative spatial and+ angular binning as in OpenCV's `SIFT implementation+ <https://github.com/opencv/opencv/blob/4.x/modules/features2d/src/sift.simd.hpp>`_:+ gradients are binned once at each pyramid octave, then local orientation and+ descriptor histograms are sampled from those maps. Unlike patch-wise SIFT,+ no image patch is resampled before either stage.++ For a general affine LAF the global angular bins are remapped through the+ LAF's ``A.T`` gradient pullback, including its direction-dependent magnitude.+ This makes affine frames useful without extracting patches, but is an+ approximation: a histogram bin represents every gradient in its angular+ interval by its centre direction, and spatial pooling is performed in the+ image pyramid before the affine footprint is sampled.++ Args:+ num_ang_bins: Number of descriptor angular bins.+ num_spatial_bins: Number of descriptor spatial bins per axis.+ spatial_bin_size: Side of the DenseSIFT spatial pooling window, in pixels.+ The default 8 approximately matches the 19-pixel octave support to the patch SIFT+ descriptor's 16-pixel pooling bins.+ rootsift: If ``True``, apply RootSIFT after clipping and normalization.+ clipval: Descriptor clipping threshold.+ orientation_bins: Number of bins for dominant-orientation assignment.++ Shape:+ - image: :math:`(B, 1, H, W)`+ - lafs: :math:`(B, N, 2, 3)` in image pixel coordinates+ - descriptors: :math:`(B, N, num_ang_bins * num_spatial_bins^2)`+ """++ def __init__(+ self,+ num_ang_bins: int = 8,+ num_spatial_bins: int = 4,+ spatial_bin_size: int = 8,+ rootsift: bool = True,+ clipval: float = 0.2,+ orientation_bins: int = 36,+ ) -> None:+ super().__init__()+ if num_ang_bins < 2 or orientation_bins < 2 or num_spatial_bins < 1 or spatial_bin_size < 1:+ raise ValueError(+ "SIFT bin counts and spatial_bin_size must be positive (angular bin counts need at least 2)"+ )+ self.num_ang_bins = num_ang_bins+ self.num_spatial_bins = num_spatial_bins+ self.spatial_bin_size = spatial_bin_size+ self.rootsift = rootsift+ self.clipval = clipval+ self.orientation_bins = orientation_bins+ self.eps = 1e-10+ pooling = get_sift_pooling_kernel(spatial_bin_size).reshape(1, 1, spatial_bin_size, spatial_bin_size)+ self.register_buffer("descriptor_pooling_kernel", pooling)+ # A 9x9 grid approximates integration over the roughly 19-pixel octave+ # support while keeping sparse orientation assignment inexpensive.+ weighting = get_gaussian_kernel2d((9, 9), (9.0 / 6.0, 9.0 / 6.0), True)+ self.register_buffer("orientation_weighting", weighting.reshape(1, 1, 9, 9), persistent=False)++ @staticmethod+ def _num_pyramid_levels(image: torch.Tensor) -> int:+ """Return the number of octaves ``_pyramid`` would construct for ``image``."""+ height, width = image.shape[-2:]+ levels = 1+ while min(height, width) >= 38:+ height, width = height // 2, width // 2+ levels += 1+ return levels++ def _pyramid(self, image: torch.Tensor, num_levels: int | None = None) -> list[torch.Tensor]:+ """Build at most ``num_levels`` octaves of the image pyramid."""+ levels = [image]+ while min(levels[-1].shape[-2:]) >= 38 and (num_levels is None or len(levels) < num_levels):+ levels.append(pyrdown(levels[-1]))+ return levels++ @staticmethod+ def _sample(maps: torch.Tensor, level_image: torch.Tensor, lafs: torch.Tensor, patch_size: int) -> torch.Tensor:+ b, n = lafs.shape[:2]+ if n == 0:+ return maps.new_zeros(b, 0, maps.shape[1], patch_size * patch_size)+ coordinates = (2.0 * torch.arange(patch_size, device=lafs.device, dtype=lafs.dtype) + 1.0) / patch_size - 1.0+ yy, xx = torch.meshgrid(coordinates, coordinates, indexing="ij")+ local = torch.stack([xx, yy], dim=-1).reshape(1, 1, patch_size, patch_size, 2)+ points = torch.einsum("bnij,xyj->bnxyi", lafs[..., :2, :2], local[0, 0]) + lafs[..., :2, 2].view(b, n, 1, 1, 2)+ h, w = level_image.shape[-2:]+ grid = 2.0 * (points + 0.5) / points.new_tensor([w, h]) - 1.0+ grid = grid.reshape(b, n * patch_size, patch_size, 2)+ grid_dtype = _promoted_grid_dtype(maps.dtype, grid.dtype)+ sample_maps = maps.to(grid_dtype) if maps.dtype != grid_dtype else maps+ grid = grid.to(grid_dtype) if grid.dtype != grid_dtype else grid+ sampled = _grid_sample_patches(sample_maps, grid, level_image.shape[-2], level_image.shape[-1]).to(maps.dtype)+ return sampled.reshape(b, maps.shape[1], n, patch_size * patch_size).permute(0, 2, 1, 3)++ @staticmethod+ def _remap_angles(histograms: torch.Tensor, affine: torch.Tensor, output_bins: int) -> torch.Tensor:+ """Move globally binned gradients into each LAF's local coordinates."""+ b, n, source_bins, samples = histograms.shape+ output_dtype = histograms.dtype+ working_dtype = _promoted_grid_dtype(histograms.dtype, affine.dtype)+ histograms = histograms.to(working_dtype)+ affine = affine.to(working_dtype)+ angles = torch.arange(source_bins, dtype=histograms.dtype, device=histograms.device)+ angles = 2.0 * pi * angles / float(source_bins)+ directions = torch.stack([torch.cos(angles), torch.sin(angles)], dim=-1)+ transformed = torch.einsum("bnji,kj->bnki", affine, directions)+ magnitude = torch.linalg.vector_norm(transformed, dim=-1)+ local_angle = torch.atan2(transformed[..., 1], transformed[..., 0])+ position = (local_angle % (2.0 * pi)) * float(output_bins) / (2.0 * pi)+ lower = torch.floor(position).long() % output_bins+ upper = (lower + 1) % output_bins+ upper_weight = position - torch.floor(position)+ values = histograms * magnitude.unsqueeze(-1)+ output = histograms.new_zeros(b, n, output_bins, samples)+ output.scatter_add_(+ 2, lower.unsqueeze(-1).expand(-1, -1, -1, samples), values * (1.0 - upper_weight).unsqueeze(-1)+ )+ output.scatter_add_(2, upper.unsqueeze(-1).expand(-1, -1, -1, samples), values * upper_weight.unsqueeze(-1))+ return output.to(output_dtype)++ @staticmethod+ def _level_occupancy(levels: torch.Tensor, num_levels: int) -> list[bool]:+ """Report which octaves at least one valid LAF selects.++ ``levels`` holds ``-1`` for invalid frames. A single host transfer+ answers both which octaves carry work and how high the pyramid reaches.+ """+ occupancy = torch.zeros(num_levels, dtype=torch.long, device=levels.device)+ occupancy.scatter_add_(0, levels.clamp_min(0).reshape(-1), (levels >= 0).long().reshape(-1))+ return [count > 0 for count in occupancy.tolist()]++ def _select_levels(self, lafs: torch.Tensor, num_levels: int) -> torch.Tensor:+ affine = lafs[..., :2, :2]+ det = (affine[..., 0, 0] * affine[..., 1, 1] - affine[..., 0, 1] * affine[..., 1, 0]).abs().sqrt()+ # At an octave the 19-pixel orientation window covers approximately one LAF diameter.+ return (det / 9.5).clamp_min(self.eps).log2().floor().clamp(0, num_levels - 1).long()++ @staticmethod+ def _laf_at_level(lafs: torch.Tensor, pyramid: list[torch.Tensor], level: int) -> torch.Tensor:+ """Map pixel-coordinate LAFs through ``pyrdown``'s align-corners-false grid."""+ if level == 0:+ return lafs+ # One clone is enough: every subsequent level transforms this private+ # tensor in place. The previous form cloned the complete selected LAF+ # set once per octave.+ output = lafs.clone()+ for index in range(level):+ source_h, source_w = pyramid[index].shape[-2:]+ target_h, target_w = pyramid[index + 1].shape[-2:]+ scale = output.new_tensor([float(target_w) / source_w, float(target_h) / source_h])+ output[..., :2, :2] *= scale.view(1, 1, 2, 1)+ output[..., :, 2] = (output[..., :, 2] + 0.5) * scale - 0.5+ return output++ def _orientation(+ self,+ pyramid: list[torch.Tensor],+ histograms: list[torch.Tensor | None],+ lafs: torch.Tensor,+ levels: torch.Tensor,+ ) -> torch.Tensor:+ b, n = lafs.shape[:2]+ result = lafs.new_zeros(b, n, self.orientation_bins)+ for level_index, (image, hist) in enumerate(zip(pyramid, histograms)):+ if hist is None:+ # No valid LAF selected this octave, so it carries no histogram map.+ continue+ weighting = self.orientation_weighting.to(dtype=hist.dtype, device=hist.device).reshape(1, 1, 1, -1)+ for batch_index in range(b):+ selected = (levels[batch_index] == level_index).nonzero().flatten()+ if selected.numel() == 0:+ continue+ current_lafs = lafs[batch_index : batch_index + 1, selected]+ level_lafs = self._laf_at_level(current_lafs, pyramid, level_index)+ # Histogram remapping is linear, so weight the sampled support before+ # the per-LAF angular pullback and avoid a 9x9 remapped temporary.+ sampled = (+ self._sample(+ hist[batch_index : batch_index + 1], image[batch_index : batch_index + 1], level_lafs, 9+ )+ * weighting+ ).sum(-1)+ mapped = self._remap_angles(+ sampled.unsqueeze(-1), level_lafs[..., :2, :2], self.orientation_bins+ ).squeeze(-1)+ result[batch_index, selected] = mapped[0].to(result.dtype)+ smoothed = F.conv1d(+ F.pad(result.reshape(b * n, 1, -1), (2, 2), mode="circular"),+ result.new_tensor([1, 4, 6, 4, 1]).view(1, 1, -1) / 16.0,+ )+ smoothed = smoothed.squeeze(1)+ index = smoothed.argmax(dim=1)+ left = smoothed.gather(1, ((index - 1) % self.orientation_bins).unsqueeze(-1)).squeeze(-1)+ center = smoothed.gather(1, index.unsqueeze(-1)).squeeze(-1)+ right = smoothed.gather(1, ((index + 1) % self.orientation_bins).unsqueeze(-1)).squeeze(-1)+ denominator = left + right - 2.0 * center+ safe_denominator = torch.where(denominator != 0, denominator, torch.ones_like(denominator))+ offset = torch.where(denominator != 0, 0.5 * (left - right) / safe_denominator, torch.zeros_like(denominator))+ return 2.0 * pi * (index.to(lafs.dtype).reshape(b, n) + offset.reshape(b, n)) / float(self.orientation_bins)++ def _descriptors(+ self,+ pyramid: list[torch.Tensor],+ histograms: list[torch.Tensor | None],+ lafs: torch.Tensor,+ levels: torch.Tensor,+ ) -> torch.Tensor:+ b, n = lafs.shape[:2]+ result = lafs.new_zeros(b, n, self.num_ang_bins, self.num_spatial_bins * self.num_spatial_bins)+ for level_index, (image, hist) in enumerate(zip(pyramid, histograms)):+ if hist is None:+ # Skip before pooling: an unused octave's (B, bins, H, W) map is+ # both the largest allocation here and the most expensive conv2d.+ continue+ kernel = self.descriptor_pooling_kernel.to(dtype=hist.dtype, device=hist.device)+ pooled = F.conv2d(+ hist.reshape(-1, 1, hist.shape[-2], hist.shape[-1]), kernel, padding=self.spatial_bin_size // 2+ ).reshape(+ hist.shape[0],+ hist.shape[1],+ hist.shape[-2] + (self.spatial_bin_size % 2 == 0),+ hist.shape[-1] + (self.spatial_bin_size % 2 == 0),+ )+ if self.spatial_bin_size % 2 == 0:+ # An even pooling kernel is centred between pixel centres. Average+ # its four neighbours so map index (y, x) stays registered to image+ # pixel (y, x), which is the LAF/grid-sampling convention.+ hist = 0.25 * (+ pooled[:, :, :-1, :-1] + pooled[:, :, 1:, :-1] + pooled[:, :, :-1, 1:] + pooled[:, :, 1:, 1:]+ )+ else:+ hist = pooled+ for batch_index in range(b):+ selected = (levels[batch_index] == level_index).nonzero().flatten()+ if selected.numel() == 0:+ continue+ current_lafs = lafs[batch_index : batch_index + 1, selected]+ level_lafs = self._laf_at_level(current_lafs, pyramid, level_index)+ sampled = self._sample(+ hist[batch_index : batch_index + 1],+ image[batch_index : batch_index + 1],+ level_lafs,+ self.num_spatial_bins,+ )+ mapped = self._remap_angles(sampled, level_lafs[..., :2, :2], self.num_ang_bins)+ result[batch_index, selected] = mapped[0].to(result.dtype)+ desc = result.flatten(2)+ desc = _l2_normalize(desc, dim=-1).clamp(0.0, self.clipval)+ desc = _l2_normalize(desc, dim=-1)+ if self.rootsift:+ return _rootsift(desc.reshape(-1, desc.shape[-1]), self.eps).reshape_as(desc)+ return desc++ def forward(self, image: torch.Tensor, lafs: torch.Tensor) -> torch.Tensor:+ """Describe supplied oriented frames without detecting or reorienting them.++ Args:+ image: Grayscale floating-point image of shape ``(B, 1, H, W)``.+ lafs: Already oriented pixel-coordinate frames of shape ``(B, N, 2, 3)``.++ Returns:+ Sparse descriptors of shape ``(B, N, num_ang_bins * num_spatial_bins**2)``,+ with the image dtype and device. Invalid frames receive zero descriptors.+ """+ return self.orient_and_describe(image, lafs, upright=True)[1]++ def orient_and_describe(+ self, image: torch.Tensor, lafs: torch.Tensor, upright: bool = False+ ) -> Tuple[torch.Tensor, torch.Tensor]:+ """Orient and describe sparse frames, building the extraction pyramid once.++ Args:+ image: Grayscale floating-point image of shape ``(B, 1, H, W)``.+ lafs: Pixel-coordinate frames of shape ``(B, N, 2, 3)``.+ upright: Preserve the supplied frame orientations rather than estimating them.++ Returns:+ Oriented frames in the input LAF dtype and descriptors in the image+ dtype, both on the image device. Invalid frames are preserved and+ receive zero descriptors. Empty frame sets are supported.+ """+ KORNIA_CHECK_SHAPE(image, ["B", "1", "H", "W"])+ KORNIA_CHECK_LAF(lafs)+ if image.shape[0] != lafs.shape[0]:+ raise ValueError(f"image and lafs must have the same batch size. Got {image.shape[0]} and {lafs.shape[0]}")+ image_dtype, laf_dtype = image.dtype, lafs.dtype+ lafs = lafs.to(device=image.device)+ if image.shape[0] == 0 or lafs.shape[1] == 0:+ # Keep empty outputs differentiably connected to both inputs, just+ # as the all-invalid path below does.+ zero = image[..., :0, :0].sum() + lafs[..., :0].sum()+ descriptors = (+ image.new_zeros(image.shape[0], lafs.shape[1], self.num_ang_bins * self.num_spatial_bins**2) + zero+ )+ return lafs, descriptors.to(image_dtype)+ # Promote before constructing coordinates: upcasting an already rounded+ # half-precision grid cannot recover subpixel geometry on large images.+ working_dtype = _promoted_grid_dtype(image.dtype, lafs.dtype)+ lafs = lafs.to(working_dtype)+ if image.dtype in (torch.float16, torch.bfloat16):+ image = image.float()+ valid = laf_is_valid(lafs)+ identity = torch.eye(2, 3, device=lafs.device, dtype=lafs.dtype).view(1, 1, 2, 3)+ # Padded detector slots and invalid training frames must never reach+ # grid_sample/atan2. Their public output remains the zero descriptor.+ safe_lafs = torch.where(valid.view(*valid.shape, 1, 1), lafs, identity)+ num_levels = self._num_pyramid_levels(image)+ levels = self._select_levels(safe_lafs, num_levels).masked_fill(~valid, -1)+ # Select before pyramid construction. The octave count depends only on+ # image shape, so octaves that no valid LAF selects need neither a+ # pyrdown result nor a histogram map.+ level_used = self._level_occupancy(levels, num_levels)+ max_level = max((index for index, used in enumerate(level_used) if used), default=-1)+ if max_level < 0:+ # Keep the zero result connected to the inputs: callers can backpropagate+ # through an all-invalid batch and receive finite zero gradients.+ zero = image[..., :0, :0].sum() + safe_lafs[..., :0].sum()+ descriptors = (+ image.new_zeros(image.shape[0], lafs.shape[1], self.num_ang_bins * self.num_spatial_bins**2) + zero+ )+ return lafs.to(laf_dtype), descriptors.to(image_dtype)+ pyramid = self._pyramid(image, max_level + 1)+ histograms: list[torch.Tensor | None] = []+ for level_index, level_image in enumerate(pyramid):+ # An intermediate octave still has to be resampled to reach the ones+ # above it, but binning its gradients is pure waste when no LAF+ # samples it: the map is (B, orientation_bins, H, W) at full octave+ # resolution and is pooled again per descriptor level.+ if not level_used[level_index]:+ histograms.append(None)+ continue+ gradients = spatial_gradient(level_image, "diff")+ histograms.append(+ _dense_sift_histograms_from_gradients(+ gradients[:, :, 0], gradients[:, :, 1], self.orientation_bins, self.eps+ )+ )+ if upright:+ oriented_lafs = safe_lafs+ else:+ angles = self._orientation(pyramid, histograms, safe_lafs, levels)+ # Kornia's LAF rotation is clockwise in image coordinates. Rotate the+ # frame against its dominant local gradient so it becomes horizontal.+ oriented_lafs = rotate_laf(safe_lafs, -torch.rad2deg(angles).unsqueeze(-1))+ descriptors = self._descriptors(pyramid, histograms, oriented_lafs, levels)+ oriented_lafs = torch.where(valid.view(*valid.shape, 1, 1), oriented_lafs, lafs)+ descriptors = descriptors.masked_fill(~valid.unsqueeze(-1), 0.0)+ return oriented_lafs.to(laf_dtype), descriptors.to(image_dtype)diff --git a/kornia/feature/sift/scale_space.py b/kornia/feature/sift/scale_space.pynew file mode 100644index 000000000..390d87743--- /dev/null+++ b/kornia/feature/sift/scale_space.py@@ -0,0 +1,748 @@+# 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.+#++"""Specialized sparse SIFT: one Gaussian pyramid for detection and description.++The pyramid, sparse DoG refinement, and descriptor share octave/layer conventions+and stay together here. The detection mechanics follow Lowe (2004) and OpenCV+SIFT. This variant deliberately omits contrast and edge rejection, selecting+valid extrema by top-K absolute response instead.++Descriptor support sizes and histogram weights follow OpenCV SIFT:+https://github.com/opencv/opencv/blob/4.x/modules/features2d/src/sift.simd.hpp+Fixed 19/41 sample grids with bilinear gradient sampling replace integer-pixel+integration; gradients are transformed into LAF coordinates before voting.+"""++from __future__ import annotations++import math+from typing import Any, Optional++import torch+import torch.nn.functional as F+from torch import nn++from kornia.constants import pi+from kornia.core.check import KORNIA_CHECK_SHAPE+from kornia.core.utils import _l2_normalize+from kornia.feature.laf import _grid_sample_patches, laf_from_center_scale_ori, laf_is_valid, rotate_laf+from kornia.feature.scale_space_detector import _check_mask, _resize_mask+from kornia.feature.siftdesc import _gradient_magnitude_orientation, _rootsift+from kornia.filters import get_gaussian_kernel1d+from kornia.geometry.subpix.spatial_soft_argmax import _solve_cramer_sym3x3+++class _SIFTScalePyramid(nn.Module):+ """Six Gaussian images per octave with exact factor-two coordinate spacing.++ The input camera sigma is 0.5 pixels. Doubling makes it 1.0; initial+ smoothing reaches sigma 1.6. Three intervals per octave require five+ incremental blurs, with Gaussian level three seeding the next octave.+ """++ def __init__(self) -> None:+ super().__init__()+ step = 2.0 ** (1.0 / 3.0)+ sigmas = [math.sqrt(1.6**2 - 1.0)]+ sigmas += [1.6 * step**i * math.sqrt(step**2 - 1.0) for i in range(5)]+ for index, sigma in enumerate(sigmas):+ size = int(8.0 * sigma + 1.0) | 1+ # Keep the reference kernel in float64. Rounding it at construction+ # would cap a float64 pyramid at float32 accuracy, unlike+ # ``ScalePyramid``, which builds its kernels in the input dtype.+ kernel = get_gaussian_kernel1d(size, sigma, dtype=torch.float64).reshape(-1)+ self.register_buffer(f"kernel_{index}", kernel)++ @staticmethod+ def _double(image: torch.Tensor) -> torch.Tensor:+ # Size 2H-1 maps even output pixels exactly onto original pixels. Pad+ # the final half-pixel with border replication, as precise 2x sampling.+ height, width = image.shape[-2:]+ doubled = F.interpolate(image, size=(2 * height - 1, 2 * width - 1), mode="bilinear", align_corners=True)+ return F.pad(doubled, (0, 1, 0, 1), mode="replicate")++ @staticmethod+ def _reflect_pad(image: torch.Tensor, radius: int, horizontal: bool) -> torch.Tensor:+ size = image.shape[-1 if horizontal else -2]+ if radius < size:+ padding = (radius, radius, 0, 0) if horizontal else (0, 0, radius, radius)+ return F.pad(image, padding, mode="reflect")+ # Reflection remains defined on tiny octaves even when PyTorch's pad+ # primitive rejects a radius >= the side length.+ index = torch.arange(-radius, size + radius, device=image.device)+ if size == 1:+ index = torch.zeros_like(index)+ else:+ period = 2 * (size - 1)+ index = index.remainder(period)+ index = torch.minimum(index, period - index)+ return image.index_select(-1 if horizontal else -2, index)++ def _blur(self, image: torch.Tensor, kernel: torch.Tensor) -> torch.Tensor:+ kernel = kernel.to(image)+ radius = kernel.numel() // 2+ # The detector promotes reduced precision inputs before pyramid construction.+ # Keep the convolution path for direct half-precision callers: its accumulation+ # order avoids a larger error across repeated pyramid levels.+ # Small arrays are faster in one convolution than in many slice additions.+ if (+ image.device.type == "cpu"+ and image.dtype not in (torch.float16, torch.bfloat16)+ and image.numel() >= 256 * 256+ ):+ return self._blur_cpu(image, kernel, radius)+ horizontal = F.conv2d(self._reflect_pad(image, radius, True), kernel.view(1, 1, 1, -1))+ return F.conv2d(self._reflect_pad(horizontal, radius, False), kernel.view(1, 1, -1, 1))++ def _blur_cpu(+ self, image: torch.Tensor, kernel: torch.Tensor, radius: int, out: torch.Tensor | None = None+ ) -> torch.Tensor:+ """Apply a separable kernel without CPU convolution's im2col buffer."""++ def blur_axis(value: torch.Tensor, horizontal: bool, destination: torch.Tensor | None = None) -> torch.Tensor:+ padded = self._reflect_pad(value, radius, horizontal)+ size = value.shape[-1 if horizontal else -2]+ height, width = value.shape[-2:]+ tiled = height * width >= 1024 * 1024 and not value.requires_grad and not torch.compiler.is_compiling()+ if destination is not None or tiled:+ # The final pass can write straight into its Gaussian-pyramid+ # slice. Out variants are used only when no gradient is needed.+ if destination is None:+ destination = value * kernel[radius]+ else:+ torch.mul(value, kernel[radius], out=destination)+ rows = 256 if tiled else height+ for row in range(0, height, rows):+ end = min(row + rows, height)+ target = destination[..., row:end, :]+ for offset in range(1, radius + 1):+ if horizontal:+ left = padded[..., row:end, radius - offset : radius + width - offset]+ right = padded[..., row:end, radius + offset : radius + width + offset]+ else:+ left = padded[..., radius + row - offset : radius + end - offset, :]+ right = padded[..., radius + row + offset : radius + end + offset, :]+ target.add_(left, alpha=kernel[radius - offset])+ target.add_(right, alpha=kernel[radius + offset])+ return destination+ if horizontal:+ result = padded[..., radius : radius + size] * kernel[radius]+ for offset in range(1, radius + 1):+ left = padded[..., radius - offset : radius + size - offset]+ right = padded[..., radius + offset : radius + size + offset]+ if torch.compiler.is_compiling():+ result = result + left * kernel[radius - offset] + right * kernel[radius + offset]+ else:+ result.add_(left, alpha=kernel[radius - offset])+ result.add_(right, alpha=kernel[radius + offset])+ else:+ result = padded[..., radius : radius + size, :] * kernel[radius]+ for offset in range(1, radius + 1):+ left = padded[..., radius - offset : radius + size - offset, :]+ right = padded[..., radius + offset : radius + size + offset, :]+ if torch.compiler.is_compiling():+ result = result + left * kernel[radius - offset] + right * kernel[radius + offset]+ else:+ result.add_(left, alpha=kernel[radius - offset])+ result.add_(right, alpha=kernel[radius + offset])+ return result++ return blur_axis(blur_axis(image, True), False, out)++ def forward(self, image: torch.Tensor) -> list[torch.Tensor]:+ """Build doubled-image Gaussian octaves for normalized grayscale images."""+ doubled = self._double(image)+ # Cast the float64 reference kernels once instead of on every blur.+ kernels = [getattr(self, f"kernel_{index}").to(doubled) for index in range(6)]+ first = self._blur(doubled, kernels[0])+ pyramid = []+ while True:+ if first.device.type == "cpu" and not first.requires_grad and not torch.compiler.is_compiling():+ # Build into the final volume instead of retaining six images+ # and then copying all six with stack. CPU's final blur pass can+ # also avoid its temporary image and the following copy.+ height, width = first.shape[-2:]+ gaussian = first.new_empty(*first.shape[:2], 6, height, width)+ gaussian[:, :, 0].copy_(first)+ for index in range(1, 6):+ previous = gaussian[:, :, index - 1]+ kernel = kernels[index]+ if first.dtype not in (torch.float16, torch.bfloat16) and first.numel() >= 256 * 256:+ self._blur_cpu(previous, kernel, kernel.numel() // 2, out=gaussian[:, :, index])+ else:+ gaussian[:, :, index].copy_(self._blur(previous, kernel))+ pyramid.append(gaussian)+ if min(height // 2, width // 2) < 12:+ break+ first = gaussian[:, :, 3, : 2 * (height // 2) : 2, : 2 * (width // 2) : 2]+ continue+ levels = [first]+ for index in range(1, 6):+ levels.append(self._blur(levels[-1], kernels[index]))+ pyramid.append(torch.stack(levels, dim=2))+ height, width = first.shape[-2:]+ if min(height // 2, width // 2) < 12:+ break+ # Decimate the already anti-aliased sigma=3.2 level. Bilinear+ # resizing here would shift pixel centres and add untracked blur.+ first = levels[3][..., : 2 * (height // 2) : 2, : 2 * (width // 2) : 2]+ return pyramid+++class _SIFTScaleSpaceDetector(nn.Module):+ """Classical sparse DoG SIFT detector for a six-level Gaussian pyramid.++ The supplied ``scale_pyr`` returns Gaussian octaves shaped ``(B, 1, 6, H, W)``.+ This intentionally does not share the generic response/subpixel detector path:+ extrema and iterative subpixel refinement follow the SIFT algorithm. All+ valid strict extrema are ranked by absolute refined DoG value. There is+ deliberately no contrast threshold or Hessian edge rejection.+ """++ def __init__(self, num_features: int, scale_pyr: nn.Module) -> None:+ super().__init__()+ if num_features < 0:+ raise ValueError("num_features must be nonnegative")+ self.num_features = num_features+ self.scale_pyr = scale_pyr++ def __getstate__(self) -> dict[str, Any]:+ state = super().__getstate__()+ # Like nn.Module.compile(), do not serialize a process-local compiled+ # callable. Unpickling restores the eager class method automatically.+ state.pop("_refine", None)+ return state++ @staticmethod+ def _values(dog: torch.Tensor, b: torch.Tensor, s: torch.Tensor, y: torch.Tensor, x: torch.Tensor) -> torch.Tensor:+ return dog[b, s, y, x]++ @staticmethod+ def _neighbourhood(+ dog: torch.Tensor, b: torch.Tensor, s: torch.Tensor, y: torch.Tensor, x: torch.Tensor+ ) -> torch.Tensor:+ # Share one gather between all finite differences / scale comparisons.+ # Index the flattened volume: gathering from an unfolded view would+ # allocate a dense (B, D-2, H-2, W-2, 3, 3, 3) tensor in backward.+ depth, height, width = dog.shape[1:]+ center = ((b * depth + s) * height + y) * width + x+ offsets = torch.tensor(+ [ds * height * width + dy * width + dx for ds in (-1, 0, 1) for dy in (-1, 0, 1) for dx in (-1, 0, 1)],+ device=dog.device,+ dtype=torch.long,+ )+ return dog.reshape(-1)[center[:, None] + offsets].reshape(-1, 3, 3, 3)++ def _refine_cuda(+ self, dog: torch.Tensor, b: torch.Tensor, s: torch.Tensor, y: torch.Tensor, x: torch.Tensor+ ) -> tuple[torch.Tensor, ...]:+ """Pack independent fits to reduce CUDA launches without changing Cramer arithmetic."""+ d, h, w = dog.shape[1:]+ coords = torch.stack((x, y, s), 1)+ alive = torch.ones_like(s, dtype=torch.bool)+ shifts = dog.new_zeros((s.numel(), 3))+ lower = coords.new_tensor((5, 5, 1))+ upper = coords.new_tensor((w - 5, h - 5, d - 1))+ address_upper = coords.new_tensor((w - 2, h - 2, d - 2))+ # Columns: x/y/s positive neighbour, negative neighbour, and four mixed-derivative terms.+ sample_indices = coords.new_tensor((14, 16, 22, 12, 10, 4, 17, 23, 25, 15, 21, 19, 11, 5, 7, 9, 3, 1))+ # Each row is a row-major 3x3 matrix. The first is H; the remaining+ # three replace successive columns of H with the right-hand side.+ matrix_indices = coords.new_tensor(+ (+ (0, 3, 4, 3, 1, 5, 4, 5, 2),+ (6, 3, 4, 7, 1, 5, 8, 5, 2),+ (0, 6, 4, 3, 7, 5, 4, 8, 2),+ (0, 3, 6, 3, 1, 7, 4, 5, 8),+ )+ ).flatten()+ offsets = coords.new_tensor(+ [ds * h * w + dy * w + dx for ds in (-1, 0, 1) for dy in (-1, 0, 1) for dx in (-1, 0, 1)]+ )+ for _ in range(5):+ alive = alive & ((coords >= lower) & (coords < upper)).all(1)+ coords = torch.minimum(coords.clamp_min(1), address_upper)+ # Fixed trip count: no alive.any()/move.any() synchronization. A+ # converged row stays at its integer center and reproduces its fit.+ x, y, s = coords.unbind(1)+ center = ((b * d + s) * h + y) * w + x+ values = dog.reshape(-1)[center[:, None] + offsets]+ # Dead rows may keep gathering, unlike the eager all-dead early exit.+ # Clear them before arithmetic so discarded NaNs cannot enter backward.+ values = torch.where(alive[:, None], values, torch.zeros_like(values))+ plus, minus, cross_a, cross_b, cross_c, cross_d = (+ values.index_select(1, sample_indices).reshape(-1, 6, 3).unbind(1)+ )+ gradient = (plus - minus) * 0.5+ diagonal = plus + minus - 2 * values[:, 13:14]+ mixed = (cross_a - cross_b - cross_c + cross_d) * 0.25+ system = torch.cat((diagonal, mixed, -gradient), 1)+ normalizer = system.abs().amax(1, keepdim=True).clamp_min(torch.finfo(dog.dtype).tiny)+ system = system / normalizer+ m00, m01, m02, m10, m11, m12, m20, m21, m22 = (+ system.index_select(1, matrix_indices).reshape(-1, 4, 9).unbind(2)+ )+ determinants = m00 * (m11 * m22 - m12 * m21) - m01 * (m10 * m22 - m12 * m20) + m02 * (m10 * m21 - m11 * m20)+ det = determinants[:, 0:1]+ solved = det.abs() > 1e-7+ shifts = determinants[:, 1:] / torch.where(solved, det, torch.ones_like(det))+ alive = alive & solved[:, 0] & torch.isfinite(shifts).all(1)+ move = alive & (shifts.abs() >= 0.5).any(1)+ coords = coords + torch.where(move[:, None], shifts.round().long(), torch.zeros_like(coords))+ converged = alive & (shifts.abs() < 0.5).all(1)+ converged = converged & ((coords >= lower) & (coords < upper)).all(1)+ shifts = torch.where(converged[:, None], shifts, torch.zeros_like(shifts))+ coords = torch.minimum(coords.clamp_min(1), address_upper)+ x, y, s = coords.unbind(1)+ sx, sy, ss = shifts.unbind(1)+ return b, s, y, x, sx, sy, ss, converged++ def _refine(+ self, dog: torch.Tensor, b: torch.Tensor, s: torch.Tensor, y: torch.Tensor, x: torch.Tensor+ ) -> tuple[torch.Tensor, ...]:+ """Iterative, sparse 3-D quadratic fit around strict DoG extrema."""+ if dog.device.type == "cuda" and dog.dtype in (torch.float32, torch.float64):+ return self._refine_cuda(dog, b, s, y, x)+ d, h, w = dog.shape[1:]+ alive = torch.ones_like(s, dtype=torch.bool)+ shift_x = torch.zeros_like(s, dtype=dog.dtype)+ shift_y = torch.zeros_like(s, dtype=dog.dtype)+ shift_s = torch.zeros_like(s, dtype=dog.dtype)+ for _ in range(5):+ inside = (s > 0) & (s < d - 1) & (y >= 5) & (y < h - 5) & (x >= 5) & (x < w - 5)+ alive &= inside+ # Keep rejected rows addressable while active rows are solved; this+ # prevents a recentered dead candidate from indexing outside DoG.+ s = s.clamp(1, d - 2)+ y = y.clamp(1, h - 2)+ x = x.clamp(1, w - 2)+ if not alive.any():+ break+ values = self._neighbourhood(dog, b, s, y, x)+ c = values[:, 1, 1, 1]+ xp, xm = values[:, 1, 1, 2], values[:, 1, 1, 0]+ yp, ym = values[:, 1, 2, 1], values[:, 1, 0, 1]+ sp, sm = values[:, 2, 1, 1], values[:, 0, 1, 1]+ gx, gy, gs = (xp - xm) * 0.5, (yp - ym) * 0.5, (sp - sm) * 0.5+ dxx, dyy, dss = xp + xm - 2 * c, yp + ym - 2 * c, sp + sm - 2 * c+ dxy = (values[:, 1, 2, 2] - values[:, 1, 2, 0] - values[:, 1, 0, 2] + values[:, 1, 0, 0]) * 0.25+ dxs = (values[:, 2, 1, 2] - values[:, 2, 1, 0] - values[:, 0, 1, 2] + values[:, 0, 1, 0]) * 0.25+ dys = (values[:, 2, 2, 1] - values[:, 2, 0, 1] - values[:, 0, 2, 1] + values[:, 0, 0, 1]) * 0.25+ normalizer = (+ torch.stack([dxx, dyy, dss, dxy, dxs, dys, gx, gy, gs])+ .abs()+ .amax(0)+ .clamp_min(torch.finfo(dog.dtype).tiny)+ )+ sx, sy, ss, solved = _solve_cramer_sym3x3(+ dxx / normalizer,+ dyy / normalizer,+ dss / normalizer,+ dxy / normalizer,+ dxs / normalizer,+ dys / normalizer,+ -gx / normalizer,+ -gy / normalizer,+ -gs / normalizer,+ )+ alive = alive & solved & torch.isfinite(sx) & torch.isfinite(sy) & torch.isfinite(ss)+ shift_x, shift_y, shift_s = sx, sy, ss+ move = alive & ((sx.abs() >= 0.5) | (sy.abs() >= 0.5) | (ss.abs() >= 0.5))+ x = x + torch.where(move, sx.round().long(), torch.zeros_like(x))+ y = y + torch.where(move, sy.round().long(), torch.zeros_like(y))+ s = s + torch.where(move, ss.round().long(), torch.zeros_like(s))+ if not move.any():+ break+ converged = alive & (shift_x.abs() < 0.5) & (shift_y.abs() < 0.5) & (shift_s.abs() < 0.5)+ inside = (s >= 1) & (s < d - 1) & (x >= 5) & (x < w - 5) & (y >= 5) & (y < h - 5)+ converged = converged & inside+ shift_x = torch.where(converged, shift_x, torch.zeros_like(shift_x))+ shift_y = torch.where(converged, shift_y, torch.zeros_like(shift_y))+ shift_s = torch.where(converged, shift_s, torch.zeros_like(shift_s))+ return b, s.clamp(1, d - 2), y.clamp(1, h - 2), x.clamp(1, w - 2), shift_x, shift_y, shift_s, converged++ def _octave(self, gaussian: torch.Tensor, octave: int, mask: Optional[torch.Tensor]) -> tuple[torch.Tensor, ...]:+ dog = (gaussian[:, 0, 1:] - gaussian[:, 0, :-1]).contiguous()+ _bsz, depth, height, width = dog.shape+ if depth < 3 or height < 11 or width < 11:+ empty = torch.empty(0, device=dog.device, dtype=torch.long)+ return empty, empty, empty, empty, dog.new_empty(0), dog.new_empty(0), dog.new_empty(0), dog.new_empty(0)+ # Spatial comparisons reject candidates before gathering+ # complete 3-D neighbourhoods. The sparse pass below still requires a+ # strict extremum against all 26 neighbours, including spatial diagonals.+ searchable = dog[:, 1:-1]+ center = searchable[:, :, 5:-5, 5:-5]+ left, right = searchable[:, :, 5:-5, 4:-6], searchable[:, :, 5:-5, 6:-4]+ above, below = searchable[:, :, 4:-6, 5:-5], searchable[:, :, 6:-4, 5:-5]+ spatial_max = (center > left) & (center > right) & (center > above) & (center > below)+ spatial_min = (center < left) & (center < right) & (center < above) & (center < below)+ # Equal diagonals (e.g. a checkerboard) can otherwise send millions of+ # doomed candidates into the 27-value sparse gather.+ for dy, dx in ((4, 4), (4, 6), (6, 4), (6, 6)):+ diagonal = searchable[:, :, dy : height - 10 + dy, dx : width - 10 + dx]+ spatial_max = spatial_max & (center > diagonal)+ spatial_min = spatial_min & (center < diagonal)+ candidate_mask = spatial_max | spatial_min+ keep_map = None+ if mask is not None:+ keep_map = _resize_mask(mask, gaussian[:, :, 0]).squeeze(1)+ if keep_map.shape[0] == 1:+ keep_map = keep_map.expand(gaussian.shape[0], -1, -1)+ candidate_mask = candidate_mask & (keep_map[:, None, 5:-5, 5:-5] > 0)+ candidates = candidate_mask.nonzero()+ if candidates.numel() == 0:+ empty = torch.empty(0, device=dog.device, dtype=torch.long)+ return empty, empty, empty, empty, dog.new_empty(0), dog.new_empty(0), dog.new_empty(0), dog.new_empty(0)+ b, s, y, x = candidates.unbind(1)+ s, y, x = s + 1, y + 5, x + 5+ # Bound temporary neighbour values and int64 gather indices even when+ # most spatial extrema subsequently fail the scale comparison.+ chunk_size = 16384 if dog.device.type == "cpu" else 65536+ keep = torch.empty_like(b, dtype=torch.bool)+ for start in range(0, b.numel(), chunk_size):+ part = slice(start, start + chunk_size)+ neighbours = self._neighbourhood(dog, b[part], s[part], y[part], x[part]).flatten(1)+ center = neighbours[:, 13:14]+ strict_max = (center > neighbours[:, :13]).all(dim=1) & (center > neighbours[:, 14:]).all(dim=1)+ strict_min = (center < neighbours[:, :13]).all(dim=1) & (center < neighbours[:, 14:]).all(dim=1)+ keep[part] = strict_max | strict_min+ b, s, y, x = b[keep], s[keep], y[keep], x[keep]+ if b.numel() == 0:+ empty = torch.empty(0, device=dog.device, dtype=torch.long)+ return empty, empty, empty, empty, dog.new_empty(0), dog.new_empty(0), dog.new_empty(0), dog.new_empty(0)+ if b.numel() <= chunk_size:+ b, s, y, x, sx, sy, ss, good = self._refine(dog, b, s, y, x)+ else:+ refined = [+ self._refine(dog, *part)+ for part in zip(b.split(chunk_size), s.split(chunk_size), y.split(chunk_size), x.split(chunk_size))+ ]+ b, s, y, x, sx, sy, ss, good = (torch.cat(values) for values in zip(*refined))+ c = self._values(dog, b, s, y, x)+ gx = (self._values(dog, b, s, y, x + 1) - self._values(dog, b, s, y, x - 1)) * 0.5+ gy = (self._values(dog, b, s, y + 1, x) - self._values(dog, b, s, y - 1, x)) * 0.5+ gs = (self._values(dog, b, s + 1, y, x) - self._values(dog, b, s - 1, y, x)) * 0.5+ contrast = c + 0.5 * (gx * sx + gy * sy + gs * ss)+ good = good & torch.isfinite(contrast)+ mask_weight = torch.ones_like(contrast)+ if keep_map is not None:+ x0, x1 = (x + sx).floor().long().clamp(0, width - 1), (x + sx).ceil().long().clamp(0, width - 1)+ y0, y1 = (y + sy).floor().long().clamp(0, height - 1), (y + sy).ceil().long().clamp(0, height - 1)+ mask_weight = torch.stack(+ [keep_map[b, y0, x0], keep_map[b, y0, x1], keep_map[b, y1, x0], keep_map[b, y1, x1]]+ ).amin(0)+ good &= mask_weight > 0+ pixel = 0.5 * float(2**octave)+ sigma = 1.6 * torch.exp2((s.to(dog.dtype) + ss) / 3.0) * pixel+ response = contrast.abs() * mask_weight+ b, s, y, x, response, sigma, sx, sy, sign = (+ item[good] for item in (b, s, y, x, response, sigma, sx, sy, contrast >= 0)+ )+ key = (((b * depth + s) * height + y) * width + x) * 2 + sign.long()+ order = key.argsort()+ keep = torch.ones_like(order, dtype=torch.bool)+ keep[1:] = key[order][1:] != key[order][:-1]+ order = order[keep]+ return b[order], s[order], y[order], x[order], response[order], sigma[order], sx[order], sy[order]++ def _detect_with_pyramid(+ self, img: torch.Tensor, num_feats: int, mask: Optional[torch.Tensor] = None+ ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, list[torch.Tensor], torch.Tensor, torch.Tensor]:+ KORNIA_CHECK_SHAPE(img, ["B", "1", "H", "W"])+ if mask is not None:+ _check_mask(mask, img)+ # Preserve the public mask-weight range before promoting the image+ # for the quadratic fit. Integer/bool masks remain binary masks.+ if mask.is_floating_point():+ mask = mask.clamp_max(1.0).to(img.dtype)+ bsz, dtype, device = img.shape[0], img.dtype, img.device+ zero = img[..., :0, :0].sum()+ if bsz == 0 or num_feats == 0:+ responses = img.new_zeros(bsz, num_feats) + zero+ lafs = img.new_zeros(bsz, num_feats, 2, 3) + zero+ filled = torch.zeros(bsz, num_feats, device=device, dtype=torch.bool)+ ids = torch.full((bsz, num_feats), -1, device=device, dtype=torch.long)+ return responses, lafs, filled, [img.unsqueeze(2)], ids, ids.clone()+ # The sparse fit uses second derivatives; keep them out of half-precision+ # underflow while preserving the public image/LAF/descriptor dtype.+ work = img.float() if dtype in (torch.float16, torch.bfloat16) else img+ pyramid = self.scale_pyr(work)+ entries = []+ for octave, gaussian in enumerate(pyramid):+ result = self._octave(gaussian, octave, mask)+ if result[0].numel() == 0:+ continue+ b, layer, y, x, response, sigma, sx, sy = result+ pixel = 0.5 * float(2**octave)+ xy = torch.stack([(x.to(gaussian.dtype) + sx) * pixel, (y.to(gaussian.dtype) + sy) * pixel], -1)+ entries.append((b, layer, xy, response, sigma, torch.full_like(layer, octave)))+ responses = torch.zeros(bsz, num_feats, device=device, dtype=dtype) + zero+ lafs = torch.zeros(bsz, num_feats, 2, 3, device=device, dtype=dtype) + zero+ filled = torch.zeros(bsz, num_feats, device=device, dtype=torch.bool)+ octaves = torch.full((bsz, num_feats), -1, device=device, dtype=torch.long)+ levels = torch.full_like(octaves, -1)+ if num_feats == 0 or not entries:+ return responses, lafs, filled, pyramid, octaves, levels+ b = torch.cat([entry[0] for entry in entries])+ layer = torch.cat([entry[1] for entry in entries])+ xy = torch.cat([entry[2] for entry in entries])+ response = torch.cat([entry[3] for entry in entries])+ sigma = torch.cat([entry[4] for entry in entries])+ octave = torch.cat([entry[5] for entry in entries])+ for batch in range(bsz):+ idx = (b == batch).nonzero().flatten()+ if idx.numel() == 0:+ continue+ take = idx[response[idx].topk(min(num_feats, idx.numel())).indices]+ count = take.numel()+ scale = (6.0 * sigma[take]).view(1, count, 1, 1)+ lafs[batch : batch + 1, :count] = laf_from_center_scale_ori(xy[take].view(1, count, 2), scale)[0]+ responses[batch, :count] = response[take]+ filled[batch, :count] = True+ octaves[batch, :count], levels[batch, :count] = octave[take], layer[take]+ return responses, lafs, filled, pyramid, octaves, levels++ def forward(self, img: torch.Tensor, mask: Optional[torch.Tensor] = None) -> tuple[torch.Tensor, torch.Tensor]:+ """Return zero-padded LAFs and absolute DoG responses."""+ responses, lafs, _, _, _, _ = self._detect_with_pyramid(img, self.num_features, mask)+ return lafs, responses+++class _SIFTScaleSpaceDescriptor(nn.Module):+ """Orient and describe LAFs from their detector-selected Gaussian levels.++ ``pyramid[octave]`` is ``(B, 1, L, H, W)`` and ``octave_indices`` and+ ``level_indices`` identify each LAF's converged integer Gaussian level. Coordinates in+ ``lafs`` are in original-image pixels; the supplied octave index sets the+ pixel distance to ``0.5 * 2**octave`` for the standard doubled SIFT pyramid.+ """++ def __init__(self, rootsift: bool = True, upright: bool = False, clipval: float = 0.2) -> None:+ super().__init__()+ self.rootsift, self.upright, self.clipval = rootsift, upright, clipval+ self.eps = 1e-10++ @staticmethod+ def _gradient_atlas(+ octave_images: torch.Tensor, used_levels: torch.Tensor, work_dtype: torch.dtype+ ) -> torch.Tensor:+ """Central differences directly in channel-major atlas storage.++ This is ``spatial_gradient(..., 'diff')`` with replicated borders, but+ avoids convolution workspaces and the subsequent full gradient transpose.+ """+ images = octave_images[:, 0].index_select(1, used_levels).to(work_dtype)+ padded = F.pad(images, (1, 1, 1, 1), mode="replicate")+ if padded.requires_grad:+ gx = (padded[..., 1:-1, 2:] - padded[..., 1:-1, :-2]) * 0.5+ gy = (padded[..., 2:, 1:-1] - padded[..., :-2, 1:-1]) * 0.5+ return torch.stack([gx, gy], 1).flatten(2, 3)+ atlas = images.new_empty(images.shape[0], 2, *images.shape[1:])+ torch.sub(padded[..., 1:-1, 2:], padded[..., 1:-1, :-2], out=atlas[:, 0])+ torch.sub(padded[..., 2:, 1:-1], padded[..., :-2, 1:-1], out=atlas[:, 1])+ return atlas.flatten(2, 3).mul_(0.5)++ @staticmethod+ def _grid(+ lafs: torch.Tensor, layer_indices: torch.Tensor, level_height: int, width: int, atlas_height: int, size: int+ ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:+ q = (2.0 * torch.arange(size, dtype=lafs.dtype, device=lafs.device) + 1.0) / size - 1.0+ yy, xx = torch.meshgrid(q, q, indexing="ij")+ local = torch.stack([xx, yy], -1)+ points = torch.einsum("bnij,xyj->bnxyi", lafs[..., :2, :2], local) + lafs[..., :2, 2].view(+ lafs.shape[0], lafs.shape[1], 1, 1, 2+ )+ if points.device.type == "cpu" and not points.requires_grad:+ # Reuse the coordinate allocation in CPU inference. MPS is faster+ # with the functional path than strided in-place component writes.+ # Each component is clamped within its own layer before shifting+ # into the atlas.+ points[..., 0].clamp_(0.0, float(width - 1)).add_(0.5).mul_(2.0).div_(width).sub_(1.0)+ points[..., 1].clamp_(0.0, float(level_height - 1))+ points[..., 1].add_(layer_indices[..., None, None].to(points.dtype) * level_height)+ points[..., 1].add_(0.5).mul_(2.0).div_(atlas_height).sub_(1.0)+ return points.reshape(lafs.shape[0], lafs.shape[1] * size, size, 2), xx, yy+ # Clamp in the selected layer before shifting it into the vertical atlas:+ # atlas-border padding would otherwise interpolate a neighbouring layer.+ x = points[..., 0].clamp(0.0, float(width - 1))+ y = points[..., 1].clamp(0.0, float(level_height - 1))+ y = y + layer_indices.view(lafs.shape[0], lafs.shape[1], 1, 1).to(y.dtype) * level_height+ grid = torch.stack([2.0 * (x + 0.5) / width - 1.0, 2.0 * (y + 0.5) / atlas_height - 1.0], -1)+ return grid.reshape(lafs.shape[0], lafs.shape[1] * size, size, 2), xx, yy++ def _sample_gradients(+ self, gradients: torch.Tensor, lafs: torch.Tensor, layer_indices: torch.Tensor, level_height: int, size: int+ ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:+ atlas_height, w = gradients.shape[-2:]+ work_dtype = torch.float32 if gradients.dtype in (torch.float16, torch.bfloat16) else gradients.dtype+ work_lafs = lafs.to(work_dtype)+ grid, xx, yy = self._grid(work_lafs, layer_indices, level_height, w, atlas_height, size)+ sampled = _grid_sample_patches(gradients.to(work_dtype), grid, atlas_height, w)+ sampled = sampled.reshape(lafs.shape[0], 2, lafs.shape[1], size * size).permute(0, 2, 1, 3)+ if gradients.device.type == "cpu":+ # The 2x2 bmm otherwise copies the strided channel planes for each+ # LAF. Componentwise multiplication reads the sampled planes directly.+ a = work_lafs[..., None]+ gx = torch.addcmul(a[:, :, 0, 0] * sampled[:, :, 0], a[:, :, 1, 0], sampled[:, :, 1])+ gy = torch.addcmul(a[:, :, 0, 1] * sampled[:, :, 0], a[:, :, 1, 1], sampled[:, :, 1])+ else:+ local_gradient = torch.einsum("bnji,bnjs->bnis", work_lafs[..., :2, :2], sampled)+ gx, gy = local_gradient[:, :, 0], local_gradient[:, :, 1]+ mag, angle = _gradient_magnitude_orientation(gx, gy, self.eps)+ return mag, angle, xx.reshape(-1), yy.reshape(-1)++ @staticmethod+ def _angular_histogram(mag: torch.Tensor, angle: torch.Tensor, bins: int) -> torch.Tensor:+ position = (angle % (2.0 * pi)) * bins / (2.0 * pi)+ lower = position.floor().long() % bins+ weight1 = position - position.floor()+ output = mag.new_zeros(*mag.shape[:-1], bins)+ output.scatter_add_(-1, lower, mag * (1.0 - weight1))+ output.scatter_add_(-1, (lower + 1) % bins, mag * weight1)+ return output++ def _orientation(+ self, gradients: torch.Tensor, lafs: torch.Tensor, layer_indices: torch.Tensor, level_height: int+ ) -> torch.Tensor:+ mag, angle, xx, yy = self._sample_gradients(gradients, lafs, layer_indices, level_height, 19)+ # sigma = LAF scale / (6 * octave pixel size); expressed in local LAF+ # coordinates it is scale-independent, while retaining the stated scale law.+ radius2 = xx.square() + yy.square()+ weight = torch.exp(-4.5 * radius2).to(mag.dtype)+ histogram = self._angular_histogram(mag * weight, angle, 36)+ histogram = F.conv1d(+ F.pad(histogram.reshape(-1, 1, 36), (2, 2), mode="circular"),+ mag.new_tensor([1, 4, 6, 4, 1]).view(1, 1, 5) / 16,+ ).squeeze(1)+ index = histogram.argmax(-1)+ left = histogram.gather(1, ((index - 1) % 36).unsqueeze(1)).squeeze(1)+ center = histogram.gather(1, index.unsqueeze(1)).squeeze(1)+ right = histogram.gather(1, ((index + 1) % 36).unsqueeze(1)).squeeze(1)+ denominator = left + right - 2 * center+ safe = torch.where(denominator != 0, denominator, torch.ones_like(denominator))+ offset = torch.where(denominator != 0, 0.5 * (left - right) / safe, torch.zeros_like(denominator))+ return (-2.0 * pi * (index.to(lafs.dtype) + offset) / 36.0).reshape(lafs.shape[:2])++ def _describe(+ self, gradients: torch.Tensor, lafs: torch.Tensor, layer_indices: torch.Tensor, level_height: int+ ) -> torch.Tensor:+ mag, angle, xx, yy = self._sample_gradients(gradients, lafs, layer_indices, level_height, 41)+ spatial_weights = None+ if mag.device.type in ("mps", "cuda"):+ bins = torch.arange(4, device=mag.device, dtype=mag.dtype)+ spatial_weights = (1.0 - (2.5 * xx[:41, None] + 1.5 - bins).abs()).clamp_min(0.0)+ desc = self._descriptor_histograms(mag, angle, xx, yy, spatial_weights)+ desc = _l2_normalize(desc, dim=-1).clamp(0.0, self.clipval)+ desc = _l2_normalize(desc, dim=-1)+ return _rootsift(desc.reshape(-1, 128), self.eps).reshape_as(desc) if self.rootsift else desc++ @staticmethod+ def _descriptor_histograms(+ mag: torch.Tensor,+ angle: torch.Tensor,+ xx: torch.Tensor,+ yy: torch.Tensor,+ spatial_weights: torch.Tensor | None = None,+ ) -> torch.Tensor:+ """Accumulate the two angular votes per sample into the 4 x 4 spatial cells."""+ b, n, _ = mag.shape+ weight = torch.exp(-0.78125 * (xx.square() + yy.square())).to(mag.dtype)+ angular = (angle % (2 * pi)) * 8 / (2 * pi)+ lower = angular.floor()+ fraction = angular - lower+ lower = lower.long().bitwise_and(7)+ weighted = mag * weight+ # Only two angular bins have nonzero weight. Avoid broadcasting every+ # sample against all eight bins and materializing their distances. The+ # scatter and both pooling paths below want each sample's eight bins+ # next to one another.+ angular_weights = mag.new_zeros(b, n, mag.shape[-1], 8)+ angular_weights.scatter_(-1, lower.unsqueeze(-1), (weighted * (1.0 - fraction)).unsqueeze(-1))+ angular_weights.scatter_add_(-1, (lower + 1).bitwise_and(7).unsqueeze(-1), (weighted * fraction).unsqueeze(-1))+ if spatial_weights is not None:+ # On CUDA and MPS the triangular spatial weights separate on the+ # square integration grid. Pool rows, then columns; the intermediate is only+ # (B,N,4,size,8), instead of multiplying each sample into 16 cells.+ size = spatial_weights.shape[0]+ rows = spatial_weights.T @ angular_weights.reshape(b, n, size, size * 8)+ return (spatial_weights.T @ rows.reshape(b, n, 4, size, 8)).reshape(b, n, 128)+ spatial_x = 2.5 * xx + 1.5+ spatial_y = 2.5 * yy + 1.5+ bins = torch.arange(4, device=mag.device, dtype=mag.dtype)+ cell_y, cell_x = torch.meshgrid(bins, bins, indexing="ij")+ spatial_weights = (1.0 - (spatial_x.unsqueeze(-1) - cell_x.reshape(-1)).abs()).clamp_min(0.0) * (+ 1.0 - (spatial_y.unsqueeze(-1) - cell_y.reshape(-1)).abs()+ ).clamp_min(0.0)+ # (B, N, 8, samples) @ (samples, 16) -> one 8-bin histogram per spatial cell.+ return torch.matmul(angular_weights.transpose(-1, -2), spatial_weights).transpose(-1, -2).reshape(b, n, 128)++ def forward(+ self,+ pyramid: list[torch.Tensor],+ lafs: torch.Tensor,+ octave_indices: torch.Tensor,+ level_indices: torch.Tensor,+ upright: bool | None = None,+ ) -> tuple[torch.Tensor, torch.Tensor]:+ """Return oriented LAFs and 128D descriptors from selected pyramid levels."""+ b, n = lafs.shape[:2]+ image = pyramid[0]+ output_dtype = image.dtype+ work_dtype = torch.float32 if output_dtype in (torch.float16, torch.bfloat16) else output_dtype+ valid = laf_is_valid(lafs)+ safe = torch.where(+ valid.view(b, n, 1, 1), lafs.to(work_dtype), torch.eye(2, 3, device=image.device, dtype=work_dtype)+ )+ zero = image[..., :0, :0].sum() + safe[..., :0].sum()+ oriented, descriptors = safe.clone(), torch.zeros(b, n, 128, device=image.device, dtype=work_dtype) + zero+ for octave, octave_images in enumerate(pyramid):+ pixel = 0.5 * float(2**octave)+ octave_selected = valid & (octave_indices == octave)+ if not octave_selected.any():+ continue+ used_levels = torch.unique(level_indices[octave_selected], sorted=True)+ level_height = octave_images.shape[-2]+ atlas = self._gradient_atlas(octave_images, used_levels, work_dtype)+ # Keep CPU voting temporaries in cache; accelerators benefit from+ # larger chunks that amortize kernel launches and synchronization.+ chunk_size = 128 if image.device.type == "cpu" else 1024+ for batch in range(b):+ indices = octave_selected[batch].nonzero().flatten()+ for start in range(0, indices.numel(), chunk_size):+ current_indices = indices[start : start + chunk_size]+ if current_indices.numel() == 0:+ continue+ layer_indices = torch.searchsorted(used_levels, level_indices[batch, current_indices]).view(1, -1)+ current = safe[batch : batch + 1, current_indices].clone()+ current[..., :2, :] /= pixel+ if not (self.upright if upright is None else upright):+ orientation_lafs = current.clone()+ orientation_lafs[..., :2, :2] *= 0.75+ alpha = self._orientation(+ atlas[batch : batch + 1], orientation_lafs, layer_indices, level_height+ )+ current = rotate_laf(current, torch.rad2deg(alpha).unsqueeze(-1))+ descriptor_lafs = current.clone()+ descriptor_lafs[..., :2, :2] *= 1.25+ oriented[batch, current_indices] = current[0] * pixel+ descriptors[batch, current_indices] = self._describe(+ atlas[batch : batch + 1], descriptor_lafs, layer_indices, level_height+ )[0]+ return torch.where(valid.view(b, n, 1, 1), oriented, lafs.to(oriented)).to(lafs.dtype), descriptors.masked_fill(+ ~valid.unsqueeze(-1), 0.0+ ).to(output_dtype)diff --git a/kornia/feature/siftdesc.py b/kornia/feature/siftdesc.pyindex d555b5b67..22a16b653 100644--- a/kornia/feature/siftdesc.py+++ b/kornia/feature/siftdesc.py@@ -71,6 +71,32 @@ def _gradient_magnitude_orientation(return mag.to(dtype), ori.to(dtype)+def _dense_sift_histograms_from_gradients(+ gx: torch.Tensor, gy: torch.Tensor, num_ang_bins: int, eps: float+) -> torch.Tensor:+ """Return unnormalised, per-pixel SIFT angular histogram maps.++ This is the gradient stage shared by :class:`DenseSIFTDescriptor` and sparse+ consumers which pool a scale pyramid themselves. In particular it deliberately+ does *not* materialise the ``num_ang_bins * num_spatial_bins**2`` dense+ descriptor tensor.+ """+ mag, ori = _gradient_magnitude_orientation(gx, gy, eps)+ o_big = float(num_ang_bins) * ori / (2.0 * pi)+ bo0 = torch.floor(o_big)+ w1 = o_big - bo0+ bo0 = bo0 % num_ang_bins+ bo1 = (bo0 + 1) % num_ang_bins+ w0 = (1.0 - w1) * mag+ w1 = w1 * mag+ return torch.cat([(bo0 == i).to(gx.dtype) * w0 + (bo1 == i).to(gx.dtype) * w1 for i in range(num_ang_bins)], 1)+++def _dense_sift_histograms(input: torch.Tensor, num_ang_bins: int, eps: float) -> torch.Tensor:+ grads = spatial_gradient(input, "diff")+ return _dense_sift_histograms_from_gradients(grads[:, :, 0], grads[:, :, 1], num_ang_bins, eps)++def get_sift_pooling_kernel(ksize: int = 25) -> torch.Tensor:r"""Return a weighted pooling kernel for SIFT descriptor.@@ -379,6 +405,16 @@ class DenseSIFTDescriptor(nn.Module):"""return self.bin_pooling_kernel.weight.detach().clone()+ def get_gradient_histograms(self, input: torch.Tensor) -> torch.Tensor:+ """Return unnormalised angular histogram maps before spatial pooling.++ The result has shape ``(B, num_ang_bins, H, W)``. It is useful when a+ caller shares an image pyramid between orientation assignment and sparse+ descriptor extraction.+ """+ KORNIA_CHECK_SHAPE(input, ["B", "1", "H", "W"])+ return _dense_sift_histograms(input, self.num_ang_bins, self.eps)+def forward(self, input: torch.Tensor) -> torch.Tensor:"""Compute dense SIFT descriptors over a full image grid.@@ -400,23 +436,13 @@ class DenseSIFTDescriptor(nn.Module):poolingconv_bias = self.PoolingConv.biasif poolingconv_bias is not None:poolingconv_bias = poolingconv_bias.to(input.dtype).to(input.device)- grads = spatial_gradient(input, "diff")- # unpack the edges- gx = grads[:, :, 0]- gy = grads[:, :, 1]- mag, ori = _gradient_magnitude_orientation(gx, gy, self.eps)- o_big = float(self.num_ang_bins) * ori / (2.0 * pi)-- bo0_big_ = torch.floor(o_big)- wo1_big_ = o_big - bo0_big_- bo0_big = bo0_big_ % self.num_ang_bins- bo1_big = (bo0_big + 1) % self.num_ang_bins- wo0_big = (1.0 - wo1_big_) * mag- wo1_big = wo1_big_ * mag+ histograms = self.get_gradient_histograms(input)+ # Keep the original per-bin convolution batch: folding angular bins into+ # the batch can select different kernels and alter established numerics.ang_bins = torch.cat([F.conv2d(- (bo0_big == i).to(input.dtype) * wo0_big + (bo1_big == i).to(input.dtype) * wo1_big,+ histograms[:, i : i + 1].contiguous(),bin_pooling_weight,bin_pooling_bias,self.bin_pooling_kernel.stride,diff --git a/kornia/geometry/subpix/spatial_soft_argmax.py b/kornia/geometry/subpix/spatial_soft_argmax.pyindex d65e8a259..8861110ce 100644--- a/kornia/geometry/subpix/spatial_soft_argmax.py+++ b/kornia/geometry/subpix/spatial_soft_argmax.py@@ -617,6 +617,62 @@ class SpatialSoftArgmax2d(nn.Module):return spatial_soft_argmax2d(input, self.temperature, self.normalized_coordinates)+def _solve_cramer_sym3x3_cuda(+ dxx: torch.Tensor,+ dyy: torch.Tensor,+ dss: torch.Tensor,+ dxy: torch.Tensor,+ dxs: torch.Tensor,+ dys: torch.Tensor,+ r0: torch.Tensor,+ r1: torch.Tensor,+ r2: torch.Tensor,+ eps: float = 1e-7,+) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:+ """Evaluate four Cramer determinants together, preserving scalar operation order.++ Used only for CUDA float32/float64. Packing trades extra temporary storage for+ fewer launches; the scalar implementation is faster on CPU and retains the+ float16 solve's promotion behavior.++ All inputs must be 1-D tensors of the same length: the packed layout indexes+ a single batch dimension and silently reshapes anything wider.+ """+ system = torch.stack((dxx, dyy, dss, dxy, dxs, dys, r0, r1, r2), 1)+ # Row-major H followed by H with successive columns replaced by the RHS.+ indices = torch.tensor(+ (+ (0, 3, 4, 3, 1, 5, 4, 5, 2),+ (6, 3, 4, 7, 1, 5, 8, 5, 2),+ (0, 6, 4, 3, 7, 5, 4, 8, 2),+ (0, 3, 6, 3, 1, 7, 4, 5, 8),+ ),+ device=dxx.device,+ dtype=torch.long,+ ).flatten()+ a, b, c, d, e, f, g, h, i = system.index_select(1, indices).reshape(-1, 4, 9).unbind(2)+ determinants = a * (e * i - f * h) - b * (d * i - f * g) + c * (d * h - e * g)+ det = determinants[:, 0:1]+ solved = det.abs() > eps+ shifts = determinants[:, 1:] / torch.where(solved, det, torch.ones_like(det))+ sx, sy, ss = shifts.unbind(1)+ return sx, sy, ss, solved[:, 0]+++def _quadratic_derivatives3d(patch: torch.Tensor) -> tuple[torch.Tensor, ...]:+ """Pack x/y/scale finite differences from an N x 27 neighbourhood on CUDA."""+ indices = torch.tensor(+ (14, 16, 22, 12, 10, 4, 17, 23, 25, 15, 21, 19, 11, 5, 7, 9, 3, 1),+ device=patch.device,+ dtype=torch.long,+ )+ plus, minus, cross_a, cross_b, cross_c, cross_d = patch.index_select(1, indices).reshape(-1, 6, 3).unbind(1)+ gradient = 0.5 * (plus - minus)+ diagonal = plus - 2.0 * patch[:, 13:14] + minus+ mixed = 0.25 * (cross_a - cross_b - cross_c + cross_d)+ return (*gradient.unbind(1), *diagonal.unbind(1), *mixed.unbind(1))++def _solve_cramer_sym3x3(dxx: torch.Tensor,dyy: torch.Tensor,@@ -652,6 +708,12 @@ def _solve_cramer_sym3x3(systems (``|det| > eps``). Outputs for unsolved entries are numericallymeaningless and should be discarded by the caller."""+ # The packed solve indexes one batch dimension, while the scalar code below+ # is rank-agnostic. Dispatch only where the two agree, so a wider caller+ # keeps its shape instead of being silently flattened on CUDA alone.+ if dxx.is_cuda and dxx.ndim == 1 and dxx.dtype in (torch.float32, torch.float64):+ return _solve_cramer_sym3x3_cuda(dxx, dyy, dss, dxy, dxs, dys, r0, r1, r2, eps)+# float16 cannot carry this solve. The determinant is a product of three# second derivatives, so for a [0, 1] response it lands around 1e-4 and# below β still above ``eps``, so ``solved`` admits it. The forward divides@@ -816,36 +878,39 @@ def conv_quad_interp3d(patch = inp_flat[center_flat.unsqueeze(1) + patch_offsets.unsqueeze(0)] # (NU, 27)# Named patch elements. Flat index: k = (dd+1)*9 + (dh+1)*3 + (dw+1), center k=13.- c000 = patch[:, 13]- p_xm = patch[:, 12]- p_xp = patch[:, 14]- p_ym = patch[:, 10]- p_yp = patch[:, 16]- p_sm = patch[:, 4]- p_sp = patch[:, 22]- p_xm_ym = patch[:, 9]- p_xp_ym = patch[:, 11]- p_xm_yp = patch[:, 15]- p_xp_yp = patch[:, 17]- p_xm_sm = patch[:, 3]- p_xp_sm = patch[:, 5]- p_xm_sp = patch[:, 21]- p_xp_sp = patch[:, 23]- p_ym_sm = patch[:, 1]- p_yp_sm = patch[:, 7]- p_ym_sp = patch[:, 19]- p_yp_sp = patch[:, 25]-- # ββ Step 4: compute gradients + Hessian + solve (all unique positions) βββ- gx = 0.5 * (p_xp - p_xm)- gy = 0.5 * (p_yp - p_ym)- gs = 0.5 * (p_sp - p_sm)- dxx = p_xp - 2.0 * c000 + p_xm- dyy = p_yp - 2.0 * c000 + p_ym- dss = p_sp - 2.0 * c000 + p_sm- dxy = 0.25 * (p_xp_yp - p_xm_yp - p_xp_ym + p_xm_ym)- dxs = 0.25 * (p_xp_sp - p_xm_sp - p_xp_sm + p_xm_sm)- dys = 0.25 * (p_yp_sp - p_ym_sp - p_yp_sm + p_ym_sm)+ if input.is_cuda and dtype in (torch.float32, torch.float64):+ gx, gy, gs, dxx, dyy, dss, dxy, dxs, dys = _quadratic_derivatives3d(patch)+ else:+ c000 = patch[:, 13]+ p_xm = patch[:, 12]+ p_xp = patch[:, 14]+ p_ym = patch[:, 10]+ p_yp = patch[:, 16]+ p_sm = patch[:, 4]+ p_sp = patch[:, 22]+ p_xm_ym = patch[:, 9]+ p_xp_ym = patch[:, 11]+ p_xm_yp = patch[:, 15]+ p_xp_yp = patch[:, 17]+ p_xm_sm = patch[:, 3]+ p_xp_sm = patch[:, 5]+ p_xm_sp = patch[:, 21]+ p_xp_sp = patch[:, 23]+ p_ym_sm = patch[:, 1]+ p_yp_sm = patch[:, 7]+ p_ym_sp = patch[:, 19]+ p_yp_sp = patch[:, 25]++ # ββ Step 4: compute gradients + Hessian + solve (all unique positions) βββ+ gx = 0.5 * (p_xp - p_xm)+ gy = 0.5 * (p_yp - p_ym)+ gs = 0.5 * (p_sp - p_sm)+ dxx = p_xp - 2.0 * c000 + p_xm+ dyy = p_yp - 2.0 * c000 + p_ym+ dss = p_sp - 2.0 * c000 + p_sm+ dxy = 0.25 * (p_xp_yp - p_xm_yp - p_xp_ym + p_xm_ym)+ dxs = 0.25 * (p_xp_sp - p_xm_sp - p_xp_sm + p_xm_sm)+ dys = 0.25 * (p_yp_sp - p_ym_sp - p_yp_sm + p_ym_sm)sx_u, sy_u, ss_u, sol_u = _solve_cramer_sym3x3(dxx, dyy, dss, dxy, dxs, dys, -gx, -gy, -gs)# Precompute gradientΒ·shift for the response correction (avoids storing gx/gy/gs tables).@@ -1154,36 +1219,39 @@ def iterative_quad_interp3d(patch = inp_flat[(bc_base + d_s * HW + h_s * W + w_s).unsqueeze(1) + patch_offsets.unsqueeze(0)]- c000 = patch[:, 13]- p_xm = patch[:, 12]- p_xp = patch[:, 14]- p_ym = patch[:, 10]- p_yp = patch[:, 16]- p_sm = patch[:, 4]- p_sp = patch[:, 22]- p_xm_ym = patch[:, 9]- p_xp_ym = patch[:, 11]- p_xm_yp = patch[:, 15]- p_xp_yp = patch[:, 17]- p_xm_sm = patch[:, 3]- p_xp_sm = patch[:, 5]- p_xm_sp = patch[:, 21]- p_xp_sp = patch[:, 23]- p_ym_sm = patch[:, 1]- p_yp_sm = patch[:, 7]- p_ym_sp = patch[:, 19]- p_yp_sp = patch[:, 25]-- gx = 0.5 * (p_xp - p_xm)- gy = 0.5 * (p_yp - p_ym)- gs = 0.5 * (p_sp - p_sm)-- dxx = p_xp - 2.0 * c000 + p_xm- dyy = p_yp - 2.0 * c000 + p_ym- dss = p_sp - 2.0 * c000 + p_sm- dxy = 0.25 * (p_xp_yp - p_xm_yp - p_xp_ym + p_xm_ym)- dxs = 0.25 * (p_xp_sp - p_xm_sp - p_xp_sm + p_xm_sm)- dys = 0.25 * (p_yp_sp - p_ym_sp - p_yp_sm + p_ym_sm)+ if input.is_cuda and dtype in (torch.float32, torch.float64):+ gx, gy, gs, dxx, dyy, dss, dxy, dxs, dys = _quadratic_derivatives3d(patch)+ else:+ c000 = patch[:, 13]+ p_xm = patch[:, 12]+ p_xp = patch[:, 14]+ p_ym = patch[:, 10]+ p_yp = patch[:, 16]+ p_sm = patch[:, 4]+ p_sp = patch[:, 22]+ p_xm_ym = patch[:, 9]+ p_xp_ym = patch[:, 11]+ p_xm_yp = patch[:, 15]+ p_xp_yp = patch[:, 17]+ p_xm_sm = patch[:, 3]+ p_xp_sm = patch[:, 5]+ p_xm_sp = patch[:, 21]+ p_xp_sp = patch[:, 23]+ p_ym_sm = patch[:, 1]+ p_yp_sm = patch[:, 7]+ p_ym_sp = patch[:, 19]+ p_yp_sp = patch[:, 25]++ gx = 0.5 * (p_xp - p_xm)+ gy = 0.5 * (p_yp - p_ym)+ gs = 0.5 * (p_sp - p_sm)++ dxx = p_xp - 2.0 * c000 + p_xm+ dyy = p_yp - 2.0 * c000 + p_ym+ dss = p_sp - 2.0 * c000 + p_sm+ dxy = 0.25 * (p_xp_yp - p_xm_yp - p_xp_ym + p_xm_ym)+ dxs = 0.25 * (p_xp_sp - p_xm_sp - p_xp_sm + p_xm_sm)+ dys = 0.25 * (p_yp_sp - p_ym_sp - p_yp_sm + p_ym_sm)sx, sy, ss, solved = _solve_cramer_sym3x3(dxx, dyy, dss, dxy, dxs, dys, -gx, -gy, -gs)valid = valid & solveddiff --git a/tests/feature/test_integrated.py b/tests/feature/test_integrated.pyindex d487f5c49..78e501df5 100644--- a/tests/feature/test_integrated.py+++ b/tests/feature/test_integrated.py@@ -282,6 +282,13 @@ class TestSIFTFeature(BaseTester):sift = SIFTFeature()assert sift is not None+ def test_pyramid_sift_opt_in(self, device, dtype):+ image = torch.rand(1, 1, 64, 64, device=device, dtype=dtype)+ lafs, responses, descriptors = SIFTFeature(2, descriptor_backend="pyramid").to(device, dtype)(image)+ assert lafs.shape == (1, 2, 2, 3)+ assert responses.shape == (1, 2)+ assert descriptors.shape == (1, 2, 128)+@pytest.mark.skip("jacobian not well computed")def test_gradcheck(self, device):B, C, H, W = 1, 1, 32, 32@@ -504,3 +511,56 @@ class TestLocalFeatureMatcher(BaseTester):out_jit = model_jit(inputs)for k, v in out.items():self.assert_close(v, out_jit[k])+++class TestSIFTPyramidBackend(BaseTester):+ @pytest.mark.parametrize("preset", [kornia.feature.SIFTFeature, kornia.feature.SIFTFeatureScaleSpace])+ @pytest.mark.parametrize("upright", [False, True])+ def test_sparse_output_and_real_descriptor(self, device, dtype, preset, upright):+ image = torch.rand(1, 1, 64, 64, device=device, dtype=dtype)+ feature = preset(num_features=3, upright=upright, descriptor_backend="pyramid").to(device, dtype).eval()+ if preset is kornia.feature.SIFTFeature:+ assert isinstance(feature.descriptor, kornia.feature.SIFTDescriptorFromPyramid)+ else:+ from kornia.feature.sift.scale_space import _SIFTScaleSpaceDescriptor++ assert isinstance(feature.descriptor, _SIFTScaleSpaceDescriptor)+ lafs, responses, descriptors = feature(image)+ assert lafs.shape == (1, 3, 2, 3)+ assert responses.shape == (1, 3)+ assert descriptors.shape == (1, 3, 128)+ assert torch.isfinite(descriptors).all()+ if preset is kornia.feature.SIFTFeature:+ self.assert_close(descriptors, feature.descriptor(image, lafs))++ @pytest.mark.parametrize("preset", [kornia.feature.SIFTFeature])+ def test_detector_responses_and_centers_are_unchanged(self, device, dtype, preset):+ image = torch.rand(1, 1, 64, 64, device=device, dtype=dtype)+ patch = preset(num_features=3, upright=True).to(device, dtype).eval()+ pyramid = preset(num_features=3, descriptor_backend="pyramid").to(device, dtype).eval()+ patch_lafs, patch_responses, _ = patch(image)+ pyramid_lafs, pyramid_responses, _ = pyramid(image)+ self.assert_close(get_laf_center(patch_lafs), get_laf_center(pyramid_lafs))+ self.assert_close(patch_responses, pyramid_responses)++ @pytest.mark.parametrize("preset", [kornia.feature.SIFTFeature, kornia.feature.SIFTFeatureScaleSpace])+ def test_invalid_backend(self, preset):+ with pytest.raises(ValueError, match="descriptor backend"):+ preset(descriptor_backend="unknown")++ def test_generic_local_feature_preserves_frames_and_forwards_mask(self, device, dtype):+ image = torch.rand(1, 1, 40, 40, device=device, dtype=dtype)+ lafs = torch.tensor([[[[6.0, 2.0, 20.0], [-2.0, 6.0, 20.0]]]], device=device, dtype=dtype)+ mask = torch.ones_like(image)++ class Detector(nn.Module):+ def forward(self, image, received_mask):+ assert received_mask is mask+ return lafs, image.new_ones(1, 1)++ descriptor = kornia.feature.SIFTDescriptorFromPyramid().to(device, dtype)+ feature = LocalFeature(Detector(), descriptor)+ returned, responses, descriptors = feature(image, mask)+ self.assert_close(returned, lafs)+ self.assert_close(responses, image.new_ones(1, 1))+ self.assert_close(descriptors, descriptor(image, lafs))diff --git a/tests/feature/test_sift_pyramid.py b/tests/feature/test_sift_pyramid.pynew file mode 100644index 000000000..a510915dc--- /dev/null+++ b/tests/feature/test_sift_pyramid.py@@ -0,0 +1,269 @@+# 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.+# limitations under the License.++from __future__ import annotations++import pytest+import torch++from kornia.feature import SIFTDescriptorFromPyramid, get_laf_orientation, laf_from_center_scale_ori++from testing.base import BaseTester, supports_reflect_padding+++class TestSIFTDescriptorFromPyramid(BaseTester):+ def test_shape_norm_and_empty(self, device, dtype):+ image = torch.rand(2, 1, 64, 80, device=device, dtype=dtype)+ xy = torch.tensor([[[24.0, 24.0], [48.0, 40.0]], [[20.0, 30.0], [52.0, 36.0]]], device=device, dtype=dtype)+ scale = torch.full((2, 2, 1, 1), 8.0, device=device, dtype=dtype)+ lafs = laf_from_center_scale_ori(xy, scale)+ feature = SIFTDescriptorFromPyramid().to(device, dtype)+ oriented, descriptors = feature.orient_and_describe(image, lafs)+ assert oriented.shape == lafs.shape+ assert descriptors.shape == (2, 2, 128)+ self.assert_close(descriptors.norm(dim=-1), torch.ones(2, 2, device=device, dtype=dtype))+ empty_lafs, empty_descriptors = feature.orient_and_describe(image, lafs[:, :0])+ assert empty_lafs.shape == (2, 0, 2, 3)+ assert empty_descriptors.shape == (2, 0, 128)++ def test_horizontal_gradient_keeps_orientation(self, device, dtype):+ image = torch.arange(64, device=device, dtype=dtype).reshape(1, 1, 1, 64).expand(1, 1, 64, 64)+ xy = torch.tensor([[[32.0, 32.0]]], device=device, dtype=dtype)+ lafs = laf_from_center_scale_ori(xy, torch.full((1, 1, 1, 1), 8.0, device=device, dtype=dtype))+ oriented, _ = SIFTDescriptorFromPyramid(rootsift=False).to(device, dtype).orient_and_describe(image, lafs)+ self.assert_close(+ get_laf_orientation(oriented), torch.zeros(1, 1, 1, device=device, dtype=dtype), rtol=0.0, atol=1e-2+ )++ def test_flat_input_has_finite_backward(self, device, dtype):+ image = torch.zeros(1, 1, 64, 64, device=device, dtype=dtype, requires_grad=True)+ xy = torch.tensor([[[32.0, 32.0]]], device=device, dtype=dtype)+ # This scale selects the second octave, exercising the in-place updates+ # on _laf_at_level's cloned LAF tensor during backward.+ lafs = laf_from_center_scale_ori(+ xy, torch.full((1, 1, 1, 1), 20.0, device=device, dtype=dtype, requires_grad=True)+ )+ _, descriptors = SIFTDescriptorFromPyramid().to(device, dtype).orient_and_describe(image, lafs)+ descriptors.sum().backward()+ assert torch.isfinite(image.grad).all()++ def test_odd_spatial_pooling(self, device, dtype):+ image = torch.rand(1, 1, 64, 64, device=device, dtype=dtype)+ xy = torch.tensor([[[32.0, 32.0]]], device=device, dtype=dtype)+ lafs = laf_from_center_scale_ori(xy, torch.full((1, 1, 1, 1), 8.0, device=device, dtype=dtype))+ _, descriptors = (+ SIFTDescriptorFromPyramid(spatial_bin_size=3).to(device, dtype).orient_and_describe(image, lafs)+ )+ assert descriptors.shape == (1, 1, 128)++ def test_invalid_laf_and_mixed_laf_dtype(self, device, dtype):+ image = torch.rand(1, 1, 64, 64, device=device, dtype=dtype)+ laf_dtype = torch.float32 if device.type == "mps" else torch.float64+ lafs = torch.zeros(1, 2, 2, 3, device=device, dtype=laf_dtype)+ lafs[0, 1] = torch.tensor([[8.0, 0.0, 32.0], [0.0, 8.0, 32.0]], device=device, dtype=laf_dtype)+ oriented, descriptors = SIFTDescriptorFromPyramid().to(device, dtype).orient_and_describe(image, lafs)+ assert oriented.dtype == lafs.dtype+ assert descriptors.dtype == dtype+ self.assert_close(descriptors[0, 0], torch.zeros(128, device=device, dtype=dtype))+ assert torch.isfinite(descriptors).all()++ def test_all_invalid_lafs_keep_zero_backward(self, device, dtype):+ image = torch.rand(1, 1, 64, 64, device=device, dtype=dtype, requires_grad=True)+ lafs = torch.zeros(1, 2, 2, 3, device=device, dtype=dtype, requires_grad=True)+ descriptors = SIFTDescriptorFromPyramid().to(device, dtype)(image, lafs)+ descriptors.sum().backward()+ self.assert_close(descriptors, torch.zeros_like(descriptors))+ self.assert_close(image.grad, torch.zeros_like(image.grad))+ self.assert_close(lafs.grad, torch.zeros_like(lafs.grad))++ def test_unused_upper_octaves_do_not_build_histograms(self, device, dtype, monkeypatch):+ import kornia.feature.sift.pyramid as implementation++ image = torch.rand(1, 1, 80, 80, device=device, dtype=dtype)+ lafs = torch.tensor([[[[6.0, 0, 40], [0, 6.0, 40]]]], device=device, dtype=dtype)+ calls = []+ pyrdown_calls = []+ original = implementation.spatial_gradient+ original_pyrdown = implementation.pyrdown++ def gradient(level, *args, **kwargs):+ calls.append(level.shape)+ return original(level, *args, **kwargs)++ def counted_pyrdown(level, *args, **kwargs):+ pyrdown_calls.append(level.shape)+ return original_pyrdown(level, *args, **kwargs)++ monkeypatch.setattr(implementation, "spatial_gradient", gradient)+ monkeypatch.setattr(implementation, "pyrdown", counted_pyrdown)+ actual = SIFTDescriptorFromPyramid().to(device, dtype)(image, lafs)+ assert calls == [image.shape]+ assert pyrdown_calls == []+ single_level = SIFTDescriptorFromPyramid().to(device, dtype)+ monkeypatch.setattr(single_level, "_pyramid", lambda image, num_levels=None: [image])+ self.assert_close(actual, single_level(image, lafs))++ def test_unused_lower_octaves_do_not_build_histograms(self, device, dtype, monkeypatch):+ import kornia.feature.sift.pyramid as implementation++ image = torch.rand(1, 1, 160, 160, device=device, dtype=dtype)+ # A large frame selects octave 2. Octaves 0 and 1 are still resampled to+ # reach it, but their histogram maps are the largest allocations here and+ # nothing ever samples them.+ lafs = torch.tensor([[[[40.0, 0.0, 80.0], [0.0, 40.0, 80.0]]]], device=device, dtype=dtype)+ feature = SIFTDescriptorFromPyramid().to(device, dtype)+ levels = feature._select_levels(lafs, feature._num_pyramid_levels(image))+ assert levels.flatten().tolist() == [2]++ shapes = []+ original = implementation.spatial_gradient++ def gradient(level, *args, **kwargs):+ shapes.append(tuple(level.shape[-2:]))+ return original(level, *args, **kwargs)++ monkeypatch.setattr(implementation, "spatial_gradient", gradient)+ oriented, descriptors = feature.orient_and_describe(image, lafs)+ assert shapes == [(40, 40)]++ # Skipping the unused octaves must not change a single output value.+ # Only CPU can be held to bitwise equality: the histogram scatter uses+ # atomics on an accelerator, so it is not run-to-run reproducible there.+ reference = SIFTDescriptorFromPyramid().to(device, dtype)+ monkeypatch.setattr(reference, "_level_occupancy", lambda levels, num_levels: [True] * num_levels)+ expected_lafs, expected_descriptors = reference.orient_and_describe(image, lafs)+ exact = {"rtol": 0.0, "atol": 0.0} if device.type == "cpu" else {}+ self.assert_close(oriented, expected_lafs, **exact)+ self.assert_close(descriptors, expected_descriptors, **exact)++ def test_all_invalid_lafs_skip_pyramid_construction(self, device, dtype, monkeypatch):+ image = torch.rand(1, 1, 80, 80, device=device, dtype=dtype)+ lafs = torch.zeros(1, 2, 2, 3, device=device, dtype=dtype)+ feature = SIFTDescriptorFromPyramid().to(device, dtype)++ def unexpected_pyramid(*args, **kwargs):+ raise AssertionError("all-invalid LAFs must not build an image pyramid")++ monkeypatch.setattr(feature, "_pyramid", unexpected_pyramid)+ descriptors = feature(image, lafs)+ self.assert_close(descriptors, torch.zeros_like(descriptors))++ def test_upright_preserves_laf_orientation(self, device, dtype):+ image = torch.rand(1, 1, 64, 64, device=device, dtype=dtype)+ xy = torch.tensor([[[32.0, 32.0]]], device=device, dtype=dtype)+ lafs = laf_from_center_scale_ori(+ xy,+ torch.full((1, 1, 1, 1), 8.0, device=device, dtype=dtype),+ torch.full((1, 1, 1), 25.0, device=device, dtype=dtype),+ )+ oriented, _ = SIFTDescriptorFromPyramid().to(device, dtype).orient_and_describe(image, lafs, upright=True)+ self.assert_close(get_laf_orientation(oriented), get_laf_orientation(lafs))++ def test_affine_gradient_is_canonicalized(self, device, dtype):+ # I(x,y)=x+y has a known gradient, so A^T(1,1) tests shear,+ # anisotropic magnitude, nonzero orientation, and the LAF rotation sign.+ axis = torch.arange(65, device=device, dtype=dtype)+ image = (axis[:, None] + axis[None, :])[None, None]+ lafs = torch.tensor([[[[8.0, 2.0, 32.0], [0.0, 6.0, 32.0]]]], device=device, dtype=dtype)+ oriented, descriptors = (+ SIFTDescriptorFromPyramid(rootsift=False).to(device, dtype).orient_and_describe(image, lafs)+ )+ gradient = oriented[..., :2, :2].transpose(-1, -2) @ torch.ones(2, 1, device=device, dtype=dtype)+ # Histogram discretization interpolates a 45-degree input between bins.+ assert gradient[..., 0, 0].min() > 0+ assert (gradient[..., 1, 0].abs() / gradient[..., 0, 0]).max() < 0.06+ assert descriptors.reshape(1, 1, 8, 16).sum(-1).argmax(-1).item() == 0++ def test_odd_pyramid_coordinates(self, device, dtype):+ if not supports_reflect_padding(device, dtype):+ pytest.skip("direct pyramid helper requires native reflect padding; the descriptor promotes half inputs")+ # Linear images remain linear away from borders. Sampling any octave at+ # the transformed frame centre must return the original pixel coordinate.+ h, w = 65, 67+ x = torch.arange(w, device=device, dtype=dtype)[None].expand(h, w)+ y = torch.arange(h, device=device, dtype=dtype)[:, None].expand(h, w)+ feature = SIFTDescriptorFromPyramid().to(device, dtype)+ lafs = torch.tensor([[[[20.0, 0.0, 27.0], [0.0, 20.0, 31.0]]]], device=device, dtype=dtype)+ pyramid = feature._pyramid(torch.stack([x, y])[None])+ level_lafs = feature._laf_at_level(lafs, pyramid, 1)+ sampled = feature._sample(pyramid[1], pyramid[1], level_lafs, 1)+ self.assert_close(sampled.flatten(), lafs[0, 0, :, 2])++ def test_nonfinite_frame_backward(self, device, dtype):+ image = torch.rand(1, 1, 40, 40, device=device, dtype=dtype, requires_grad=True)+ lafs = torch.tensor(+ [[[[8.0, 0.0, float("nan")], [0.0, 8.0, 20.0]], [[8.0, 0.0, 20.0], [0.0, 8.0, 20.0]]]],+ device=device,+ dtype=dtype,+ requires_grad=True,+ )+ _, desc = SIFTDescriptorFromPyramid().to(device, dtype).orient_and_describe(image, lafs)+ desc.sum().backward()+ self.assert_close(desc[0, 0], torch.zeros_like(desc[0, 0]))+ assert torch.isfinite(image.grad).all()+ assert torch.isfinite(lafs.grad).all()++ def test_gradcheck(self, device):+ image = torch.rand(1, 1, 8, 8, device=device, dtype=torch.float64)+ lafs = torch.tensor([[[[2.0, 0.0, 3.0], [0.0, 2.0, 3.0]]]], device=device, dtype=torch.float64)+ feature = SIFTDescriptorFromPyramid(spatial_bin_size=3).to(device, torch.float64)+ self.gradcheck(lambda image: feature(image, lafs), (image,))++ def test_empty_batch(self, device, dtype):+ image = torch.empty(0, 1, 40, 40, device=device, dtype=dtype)+ lafs = torch.empty(0, 3, 2, 3, device=device, dtype=dtype)+ oriented, desc = SIFTDescriptorFromPyramid().to(device, dtype).orient_and_describe(image, lafs)+ assert oriented.shape == (0, 3, 2, 3)+ assert desc.shape == (0, 3, 128)++ @pytest.mark.parametrize("batch_size,num_lafs", [(1, 0), (0, 3)])+ def test_empty_inputs_keep_zero_backward(self, device, dtype, batch_size, num_lafs):+ image = torch.empty(batch_size, 1, 40, 40, device=device, dtype=dtype, requires_grad=True)+ lafs = torch.empty(batch_size, num_lafs, 2, 3, device=device, dtype=dtype, requires_grad=True)+ descriptors = SIFTDescriptorFromPyramid().to(device, dtype)(image, lafs)+ descriptors.sum().backward()+ self.assert_close(image.grad, torch.zeros_like(image.grad))+ self.assert_close(lafs.grad, torch.zeros_like(lafs.grad))++ def test_descriptor_forward_does_not_reorient(self, device, dtype, monkeypatch):+ image = torch.rand(1, 1, 40, 40, device=device, dtype=dtype)+ lafs = torch.tensor([[[[6.0, 2.0, 20.0], [-2.0, 6.0, 20.0]]]], device=device, dtype=dtype)+ original = lafs.clone()+ descriptor = SIFTDescriptorFromPyramid().to(device, dtype)++ def unexpected_orientation(*args):+ raise AssertionError("Descriptor forward must respect the supplied orientation")++ monkeypatch.setattr(descriptor, "_orientation", unexpected_orientation)+ descriptors = descriptor(image, lafs)+ assert descriptors.shape == (1, 1, 128)+ self.assert_close(lafs, original)++ def test_orientation_and_description_share_one_pyramid(self, device, dtype, monkeypatch):+ image = torch.rand(1, 1, 40, 40, device=device, dtype=dtype)+ lafs = torch.tensor([[[[8.0, 0.0, 20.0], [0.0, 8.0, 20.0]]]], device=device, dtype=dtype)+ descriptor = SIFTDescriptorFromPyramid().to(device, dtype)+ original = descriptor._pyramid+ calls = []++ def counted_pyramid(image, num_levels=None):+ calls.append(image.shape)+ return original(image, num_levels)++ monkeypatch.setattr(descriptor, "_pyramid", counted_pyramid)+ descriptor.orient_and_describe(image, lafs)+ assert len(calls) == 1diff --git a/tests/feature/test_sift_scale_pyramid_optimized.py b/tests/feature/test_sift_scale_pyramid_optimized.pynew file mode 100644index 000000000..e3d70e1ca--- /dev/null+++ b/tests/feature/test_sift_scale_pyramid_optimized.py@@ -0,0 +1,146 @@+# 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.+# limitations under the License.++from __future__ import annotations++import pytest+import torch+import torch.nn.functional as F++from kornia.feature.sift.scale_space import _SIFTScalePyramid++from testing.base import (+ DYNAMO_UNAVAILABLE_REASON,+ BaseTester,+ dynamo_is_available,+ supports_reflect_padding,+ supports_replicate_padding,+)+++def _convolution_blur(pyramid: _SIFTScalePyramid, image: torch.Tensor, kernel: torch.Tensor) -> torch.Tensor:+ radius = kernel.numel() // 2+ horizontal = F.conv2d(pyramid._reflect_pad(image, radius, True), kernel.view(1, 1, 1, -1))+ return F.conv2d(pyramid._reflect_pad(horizontal, radius, False), kernel.view(1, 1, -1, 1))+++def _convolution_pyramid(pyramid: _SIFTScalePyramid, image: torch.Tensor) -> list[torch.Tensor]:+ first = _convolution_blur(pyramid, pyramid._double(image), pyramid.kernel_0.to(image))+ result = []+ while True:+ levels = [first]+ for index in range(1, 6):+ levels.append(_convolution_blur(pyramid, levels[-1], getattr(pyramid, f"kernel_{index}").to(image)))+ result.append(torch.stack(levels, dim=2))+ height, width = first.shape[-2:]+ if min(height // 2, width // 2) < 12:+ return result+ first = levels[3][..., : 2 * (height // 2) : 2, : 2 * (width // 2) : 2]+++class TestSIFTScalePyramidCPUOptimized(BaseTester):+ @staticmethod+ def _cpu(device: torch.device, dtype: torch.dtype) -> None:+ if device.type != "cpu":+ pytest.skip("the optimized implementation is CPU-only")+ if not supports_replicate_padding(device, dtype) or not supports_reflect_padding(device, dtype):+ pytest.skip("direct pyramid helper requires native border padding; the detector promotes half inputs")++ @pytest.mark.parametrize("shape", [(1, 1), (2, 3)])+ def test_blur_matches_convolution_with_asymmetric_kernel(self, device, dtype, shape):+ self._cpu(device, dtype)+ pyramid = _SIFTScalePyramid().to(device, dtype)+ image = torch.rand(1, 1, *shape, device=device, dtype=dtype)+ kernel = torch.rand_like(pyramid.kernel_4)++ actual = (+ pyramid._blur_cpu(image, kernel, kernel.numel() // 2)+ if dtype in (torch.float32, torch.float64)+ else pyramid._blur(image, kernel)+ )+ expected = _convolution_blur(pyramid, image, kernel)++ self.assert_close(actual, expected)++ def test_pyramid_matches_convolution(self, device, dtype):+ self._cpu(device, dtype)+ pyramid = _SIFTScalePyramid().to(device, dtype)+ # The doubled first octave exceeds the CPU slice threshold; subsequent+ # octaves exercise the convolution fallback for smaller arrays.+ image = torch.rand(1, 1, 129, 131, device=device, dtype=dtype)++ actual = pyramid(image)+ expected = _convolution_pyramid(pyramid, image)++ for actual_octave, expected_octave in zip(actual, expected):+ self.assert_close(actual_octave, expected_octave)++ def test_inference_preallocation_matches_training_and_keeps_levels_distinct(self, device, dtype):+ self._cpu(device, dtype)+ pyramid = _SIFTScalePyramid().to(device, dtype)+ image = torch.rand(2, 1, 129, 131, device=device, dtype=dtype)++ inference = pyramid(image)+ training = pyramid(image.detach().clone().requires_grad_())++ for inferred_octave, training_octave in zip(inference, training):+ self.assert_close(inferred_octave, training_octave)+ # Each Gaussian level occupies its own range of the preallocated+ # volume, preventing a later blur from overwriting an earlier one.+ assert len({inferred_octave[:, :, level].data_ptr() for level in range(6)}) == 6++ def test_blur_has_finite_gradient(self, device, dtype):+ self._cpu(device, dtype)+ pyramid = _SIFTScalePyramid().to(device, dtype)+ actual_input = torch.rand(1, 1, 17, 19, device=device, dtype=dtype, requires_grad=True)+ expected_input = actual_input.detach().clone().requires_grad_()+ kernel = pyramid.kernel_4++ actual = (+ pyramid._blur_cpu(actual_input, kernel, kernel.numel() // 2)+ if dtype in (torch.float32, torch.float64)+ else pyramid._blur(actual_input, kernel)+ )+ expected = _convolution_blur(pyramid, expected_input, kernel)+ actual.square().mean().backward()+ expected.square().mean().backward()++ assert actual_input.grad is not None and torch.isfinite(actual_input.grad).all()+ self.assert_close(actual_input.grad, expected_input.grad)++ def test_dynamo(self, device, dtype, torch_optimizer):+ self._cpu(device, dtype)+ pyramid = _SIFTScalePyramid().to(device, dtype)+ image = torch.rand(1, 1, 17, 19, device=device, dtype=dtype)+ expected = pyramid(image)++ for actual_octave, expected_octave in zip(torch_optimizer(pyramid)(image), expected):+ self.assert_close(actual_octave, expected_octave)++ @pytest.mark.skipif(not dynamo_is_available(), reason=DYNAMO_UNAVAILABLE_REASON)+ def test_dynamo_fullgraph(self, device, dtype):+ self._cpu(device, dtype)+ if dtype not in (torch.float32, torch.float64):+ pytest.skip("the CPU slice implementation uses full precision")+ pyramid = _SIFTScalePyramid().to(device, dtype)+ image = torch.rand(1, 1, 17, 19, device=device, dtype=dtype)+ kernel = pyramid.kernel_4+ radius = kernel.numel() // 2+ expected = pyramid._blur_cpu(image, kernel, radius)+ torch._dynamo.reset()+ actual = torch.compile(pyramid._blur_cpu, fullgraph=True)(image, kernel, radius)+ self.assert_close(actual, expected)diff --git a/tests/feature/test_sift_scale_space.py b/tests/feature/test_sift_scale_space.pynew file mode 100644index 000000000..52709a1c8--- /dev/null+++ b/tests/feature/test_sift_scale_space.py@@ -0,0 +1,650 @@+# 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.+#++from __future__ import annotations++import io++import pytest+import torch+from torch import nn++from kornia.feature import SIFTFeatureScaleSpace, get_laf_center, get_laf_orientation, laf_is_filled+from kornia.feature.sift.scale_space import _SIFTScaleSpaceDescriptor, _SIFTScaleSpaceDetector+from kornia.filters import spatial_gradient++from testing.base import (+ DYNAMO_UNAVAILABLE_REASON,+ BaseTester,+ dynamo_is_available,+ supports_reflect_padding,+ supports_replicate_padding,+)+++class TestSharedSIFTScaleSpace(BaseTester):+ def test_trilinear_histogram_bins(self, device, dtype):+ # Hand-computed votes in (row, column, angle) order. Cancel Gaussian+ # weighting to isolate spatial interpolation and the angle 7 -> 0 seam.+ work_dtype = torch.float32 if dtype in (torch.float16, torch.bfloat16) else dtype+ xx = torch.tensor([-0.6, -0.2, 0.2, 0.6, 0.0], device=device, dtype=work_dtype)+ yy = torch.tensor([0.6, -0.6, 0.2, -0.2, 0.2], device=device, dtype=work_dtype)+ mass = xx.new_tensor([1.0, 2.0, 3.0, 4.0, 2.0])+ mag = (mass * torch.exp(0.78125 * (xx.square() + yy.square()))).view(1, 1, -1)+ angle = xx.new_tensor([0.25, 1.5, 7.75, 4.0, 2.5]).view(1, 1, -1) * (torch.pi / 4)+ actual = _SIFTScaleSpaceDescriptor._descriptor_histograms(mag, angle, xx, yy).reshape(4, 4, 8)+ expected = torch.zeros_like(actual)+ expected[3, 0, 0], expected[3, 0, 1] = 0.75, 0.25+ expected[0, 1, 1:3] = 1.0+ expected[2, 2, 7], expected[2, 2, 0] = 0.75, 2.25+ expected[1, 3, 4] = 4.0+ expected[2, 1:3, 2:4] = 0.5+ self.assert_close(actual, expected, atol=2e-6, rtol=2e-6)++ def test_histogram_gradcheck(self, device):+ if device.type == "mps":+ pytest.skip("MPS does not support float64 gradcheck")+ xx = torch.tensor([-0.8, -0.15, 0.35, 0.9], device=device, dtype=torch.float64)+ yy = xx.flip(0)+ mag = xx.new_tensor([0.3, 0.6, 1.0, 0.4]).view(1, 1, -1)+ angle = xx.new_tensor([0.2, 1.3, 3.1, 5.6]).view(1, 1, -1)+ self.gradcheck(lambda m, a: _SIFTScaleSpaceDescriptor._descriptor_histograms(m, a, xx, yy), (mag, angle))++ def test_separable_histogram_matches_dense_values_and_gradients(self, device, dtype):+ # _sample_gradients promotes reduced precision before this private+ # histogram helper; keep half leaves to check their returned gradients.+ work_dtype = torch.float32 if dtype in (torch.float16, torch.bfloat16) else dtype+ coordinate = torch.tensor([-0.6, 0.0, 0.6], device=device, dtype=work_dtype)+ yy, xx = torch.meshgrid(coordinate, coordinate, indexing="ij")+ xx, yy = xx.reshape(-1), yy.reshape(-1)+ actual_mag = torch.linspace(0.1, 1.8, 18, device=device, dtype=dtype).reshape(2, 1, 9).requires_grad_()+ expected_mag = actual_mag.detach().clone().requires_grad_()+ # Include both directions across the 7 -> 0 seam without putting a+ # finite-difference probe exactly on an angular-bin boundary.+ actual_angle = (+ torch.tensor(+ [-0.13, 0.21, 1.07, 2.31, 3.53, 4.89, 5.97, 2 * torch.pi + 0.17, -2 * torch.pi + 1.43],+ device=device,+ dtype=dtype,+ )+ .repeat(2)+ .reshape(2, 1, 9)+ .requires_grad_()+ )+ expected_angle = actual_angle.detach().clone().requires_grad_()+ bins = torch.arange(4, device=device, dtype=work_dtype)+ separable = (1.0 - (2.5 * coordinate[:, None] + 1.5 - bins).abs()).clamp_min(0.0)++ actual = _SIFTScaleSpaceDescriptor._descriptor_histograms(+ actual_mag.to(work_dtype), actual_angle.to(work_dtype), xx, yy, separable+ )+ expected = _SIFTScaleSpaceDescriptor._descriptor_histograms(+ expected_mag.to(work_dtype), expected_angle.to(work_dtype), xx, yy+ )+ self.assert_close(actual, expected)+ weights = torch.linspace(0.1, 1.0, actual.numel(), device=device, dtype=work_dtype).reshape_as(actual)+ (actual * weights).sum().backward()+ (expected * weights).sum().backward()+ self.assert_close(actual_mag.grad, expected_mag.grad)+ self.assert_close(actual_angle.grad, expected_angle.grad)++ def test_separable_histogram_gradcheck_cpu_double(self, device):+ if device.type != "cpu":+ pytest.skip("covers the CPU float64 derivative of the separable path")+ coordinate = torch.tensor([-0.6, 0.0, 0.6], device=device, dtype=torch.float64)+ yy, xx = torch.meshgrid(coordinate, coordinate, indexing="ij")+ xx, yy = xx.reshape(-1), yy.reshape(-1)+ bins = torch.arange(4, device=device, dtype=torch.float64)+ separable = (1.0 - (2.5 * coordinate[:, None] + 1.5 - bins).abs()).clamp_min(0.0)+ mag = torch.linspace(0.1, 0.9, 9, device=device, dtype=torch.float64).reshape(1, 1, 9)+ angle = torch.tensor(+ [-0.13, 0.21, 1.07, 2.31, 3.53, 4.89, 5.97, 2 * torch.pi + 0.17, -2 * torch.pi + 1.43],+ device=device,+ dtype=torch.float64,+ ).reshape(1, 1, 9)+ self.gradcheck(+ lambda m, a: _SIFTScaleSpaceDescriptor._descriptor_histograms(m, a, xx, yy, separable), (mag, angle)+ )++ @pytest.mark.skipif(not dynamo_is_available(), reason=DYNAMO_UNAVAILABLE_REASON)+ @pytest.mark.parametrize("components", [["scale_pyr"], ["subpix"], ["scale_pyr", "subpix"]])+ def test_checkpoint_round_trip(self, components):+ eager = SIFTFeatureScaleSpace(8, descriptor_backend="pyramid")+ compiled = SIFTFeatureScaleSpace(8, descriptor_backend="pyramid", compile_modules=components)+ assert eager.state_dict().keys() == compiled.state_dict().keys()+ compiled.load_state_dict(eager.state_dict(), strict=True)+ eager.load_state_dict(compiled.state_dict(), strict=True)+ checkpoint = io.BytesIO()+ torch.save(compiled, checkpoint)+ checkpoint.seek(0)+ restored = torch.load(checkpoint, weights_only=False)+ image = torch.rand(1, 1, 17, 19)+ for expected, actual in zip(eager(image), restored(image)):+ self.assert_close(actual, expected)++ def test_single_pyramid_build_and_exact_images(self, device, dtype, monkeypatch):+ feature = SIFTFeatureScaleSpace(8, descriptor_backend="pyramid").to(device, dtype)+ image = torch.rand(1, 1, 65, 67, device=device, dtype=dtype)+ built = []+ original = feature.detector.scale_pyr.forward++ def build(image):+ result = original(image)+ built.append(result)+ return result++ original_descriptor = feature.descriptor.forward++ def describe(pyramid, *args, **kwargs):+ assert pyramid is built[-1]+ return original_descriptor(pyramid, *args, **kwargs)++ monkeypatch.setattr(feature.detector.scale_pyr, "forward", build)+ monkeypatch.setattr(feature.descriptor, "forward", describe)+ lafs, responses, desc = feature(image)+ assert len(built) == 1+ assert desc.shape == (1, 8, 128)+ assert torch.isfinite(desc).all()+ assert torch.isfinite(responses).all()+ assert torch.isfinite(lafs).all()++ def test_provenance_survives_topk_and_padding(self, device, dtype):+ detector = SIFTFeatureScaleSpace(40, upright=True, descriptor_backend="pyramid").to(device, dtype).detector+ image = torch.rand(2, 1, 65, 67, device=device, dtype=dtype)+ image[1] = 0+ responses, lafs, filled, pyramid, octaves, levels = detector._detect_with_pyramid(image, 40)+ assert torch.equal(filled, laf_is_filled(lafs))+ assert (octaves[~filled] == -1).all()+ assert (levels[~filled] == -1).all()+ assert not filled[1].any()+ expected_lafs, expected_responses = detector(image)+ self.assert_close(responses, expected_responses)+ self.assert_close(lafs, expected_lafs)+ for octave, images in enumerate(pyramid):+ selected = filled & (octaves == octave)+ # Selected layer is nearest to the continuous refined scale, not an+ # octave guessed from frame size (octaves have overlapping scales).+ sigma = lafs[..., 0, 0][selected] / (6 * 0.5 * 2**octave)+ expected = (3 * torch.log2(sigma / 1.6)).round().long().clamp(0, images.shape[2] - 1)+ assert torch.equal(levels[selected], expected)++ def test_selected_layer_and_rotation(self, device, dtype):+ axis = torch.arange(64, device=device, dtype=dtype)+ horizontal = axis[None, :].expand(64, 64)+ vertical = axis[:, None].expand(64, 64)+ pyramid = [torch.stack([horizontal, vertical])[None, None]]+ # Same location/scale, different Gaussian provenance must give different+ # orientations even though the returned canonical descriptors coincide.+ lafs = torch.tensor([[[[6.0, 0, 16], [0, 6.0, 16]]] * 2], device=device, dtype=dtype)+ octaves = torch.zeros(1, 2, device=device, dtype=torch.long)+ levels = torch.tensor([[0, 1]], device=device)+ oriented, desc = _SIFTScaleSpaceDescriptor()(pyramid, lafs, octaves, levels)+ self.assert_close(get_laf_center(oriented), get_laf_center(lafs))+ angles = get_laf_orientation(oriented).flatten()+ self.assert_close(angles.abs(), angles.new_tensor([0, 90]), atol=0.02, rtol=0)+ self.assert_close(desc[0, 0], desc[0, 1], atol=0.002, rtol=0.002)+ self.assert_close(desc.norm(dim=-1), torch.ones(1, 2, device=device, dtype=dtype))++ def test_mask_padding_and_empty(self, device, dtype):+ feature = SIFTFeatureScaleSpace(4, descriptor_backend="pyramid").to(device, dtype)+ image = torch.rand(2, 1, 40, 40, device=device, dtype=dtype)+ lafs, responses, desc = feature(image, torch.zeros_like(image))+ assert not lafs.any()+ assert not responses.any()+ assert not desc.any()+ feature.detector.num_features = 0+ lafs, responses, desc = feature(image)+ assert lafs.shape == (2, 0, 2, 3)+ assert desc.shape == (2, 0, 128)++ @pytest.mark.parametrize("case", ["flat", "masked", "num_features", "empty_batch"])+ def test_public_empty_outputs_are_graph_connected(self, device, dtype, case):+ if case == "empty_batch":+ image = torch.rand(0, 1, 40, 40, device=device, dtype=dtype, requires_grad=True)+ elif case == "flat":+ image = torch.zeros(1, 1, 40, 40, device=device, dtype=dtype, requires_grad=True)+ else:+ image = torch.rand(1, 1, 40, 40, device=device, dtype=dtype, requires_grad=True)+ feature = SIFTFeatureScaleSpace(4, descriptor_backend="pyramid").to(device, dtype)+ if case == "num_features":+ feature.detector.num_features = 0+ mask = torch.zeros_like(image) if case == "masked" else None++ lafs, responses, descriptors = feature(image, mask)++ assert not lafs.any() and not responses.any() and not descriptors.any()+ assert lafs.requires_grad and responses.requires_grad and descriptors.requires_grad+ (lafs.sum() + responses.sum() + descriptors.sum()).backward()+ assert image.grad is not None+ assert torch.isfinite(image.grad).all() and not image.grad.any()++ def test_float16_tiny_float32_mask_is_suppressed(self, device, dtype):+ if dtype != torch.float16:+ pytest.skip("exercises mask preservation across float16 detector promotion")+ image = torch.zeros(1, 1, 32, 32, device=device, dtype=dtype)+ dog = _quadratic_dog(device, dtype)+ detector = _SIFTScaleSpaceDetector(1, _FixedPyramid(dog)).to(device, dtype)+ mask = torch.full((1, 1, 32, 32), 1e-10, device=device, dtype=torch.float32)+ lafs, responses = detector(image, mask)+ assert not lafs.any() and not responses.any()++ def test_flat_gradient_backward(self, device, dtype):+ image = torch.zeros(1, 1, 1, 32, 32, device=device, dtype=dtype, requires_grad=True)+ lafs = torch.tensor([[[[3.0, 0, 8], [0, 3.0, 8]]]], device=device, dtype=dtype)+ ids = torch.zeros(1, 1, device=device, dtype=torch.long)+ _, desc = _SIFTScaleSpaceDescriptor()([image], lafs, ids, ids)+ desc.sum().backward()+ assert torch.isfinite(image.grad).all()++ def test_gradients_built_once_per_used_layer(self, device, dtype, monkeypatch):+ import kornia.feature.sift.scale_space as implementation++ pyramid = [torch.rand(2, 1, 3, 32, 32, device=device, dtype=dtype)]+ lafs = torch.tensor([[[[3.0, 0, 8], [0, 3.0, 8]]] * 3] * 2, device=device, dtype=dtype)+ # Exercise both ends of an atlas layer: border replication must stay in+ # that layer instead of interpolating a neighbouring Gaussian image.+ # Original-image centres 0.5/15.5 become octave-0 centres 1/31 because+ # its pixel distance is 0.5. Batch 1 uses the upper atlas layer at y=1.+ lafs[:, 0, :, 2] = 0.5+ lafs[:, 2, :, 2] = 15.5+ octaves = torch.zeros(2, 3, device=device, dtype=torch.long)+ levels = torch.tensor([[0, 0, 2], [2, 0, 2]], device=device)+ calls = []+ original = implementation._SIFTScaleSpaceDescriptor._gradient_atlas++ def gradient(image, levels, work_dtype):+ calls.append(image)+ return original(image, levels, work_dtype)++ monkeypatch.setattr(implementation._SIFTScaleSpaceDescriptor, "_gradient_atlas", staticmethod(gradient))+ module = _SIFTScaleSpaceDescriptor()+ _, desc = module(pyramid, lafs, octaves, levels)+ # Used layers are batched into one gradient call per octave, including+ # both images; the unused middle layer is never differentiated.+ assert len(calls) == 1+ assert calls[0].shape == (2, 1, 3, 32, 32)+ for batch in range(2):+ for feature in range(3):+ _, single = module(+ [pyramid[0][batch : batch + 1]],+ lafs[batch : batch + 1, feature : feature + 1],+ octaves[batch : batch + 1, feature : feature + 1],+ levels[batch : batch + 1, feature : feature + 1],+ )+ self.assert_close(desc[batch, feature], single[0, 0])++ @pytest.mark.parametrize("height,width", [(5, 7), (1, 7), (7, 1)])+ def test_gradient_atlas_matches_spatial_gradient_and_backward(self, device, dtype, height, width):+ levels = torch.tensor([0, 2], device=device)+ actual_images = torch.rand(2, 1, 3, height, width, device=device, dtype=dtype, requires_grad=True)+ expected_images = actual_images.detach().clone().requires_grad_()+ work_dtype = torch.float32 if dtype in (torch.float16, torch.bfloat16) else dtype+ actual = _SIFTScaleSpaceDescriptor._gradient_atlas(actual_images, levels, work_dtype)+ selected = expected_images[:, 0].index_select(1, levels).to(work_dtype)+ expected = spatial_gradient(selected.reshape(-1, 1, height, width), mode="diff")[:, 0]+ expected = expected.reshape(2, 2, 2, height, width).permute(0, 2, 1, 3, 4).reshape(2, 2, -1, width)+ self.assert_close(actual, expected)+ weights = torch.linspace(0.1, 1.0, actual.numel(), device=device, dtype=work_dtype).reshape_as(actual)+ (actual * weights).sum().backward()+ (expected * weights).sum().backward()+ assert actual_images.grad is not None and expected_images.grad is not None+ self.assert_close(actual_images.grad, expected_images.grad)++ def test_grid_inference_matches_autograd_path(self, device, dtype):+ lafs = torch.tensor(+ [+ [[[2.0, 0.3, 0.0], [-0.2, 1.5, 0.0]], [[1.0, 0.0, 6.0], [0.0, 2.0, 4.0]]],+ [[[2.0, 0.3, 8.0], [-0.2, 1.5, 5.0]], [[1.0, 0.0, 3.0], [0.0, 2.0, 8.0]]],+ ],+ device=device,+ dtype=dtype,+ )+ layers = torch.tensor([[0, 2], [2, 0]], device=device)+ inference, _, _ = _SIFTScaleSpaceDescriptor._grid(lafs, layers, 9, 11, 27, 19)+ autograd, _, _ = _SIFTScaleSpaceDescriptor._grid(lafs.detach().clone().requires_grad_(), layers, 9, 11, 27, 19)+ self.assert_close(inference, autograd)++ def test_upright_image_gradcheck(self, device):+ if device.type == "mps":+ pytest.skip("MPS does not support float64 gradcheck")+ image = torch.rand(1, 1, 1, 12, 12, device=device, dtype=torch.float64)+ lafs = torch.tensor([[[[1.0, 0, 3], [0, 1.0, 3]]]], device=device, dtype=torch.float64)+ ids = torch.zeros(1, 1, device=device, dtype=torch.long)+ module = _SIFTScaleSpaceDescriptor()+ # CUDA grid sampling accumulates repeated pixel contributions atomically.+ # Repeated float64 backward differs by ~6e-16 on both SIFT implementations.+ self.gradcheck(+ lambda image: module([image], lafs, ids, ids, upright=True)[1],+ (image,),+ nondet_tol=1e-12 if device.type == "cuda" else 0.0,+ )++ def test_specialized_detector_does_not_use_generic_detection(self, device, dtype, monkeypatch):+ from kornia.feature import ScaleSpaceDetector+ from kornia.feature.sift.scale_space import _SIFTScaleSpaceDetector++ def forbidden(*args, **kwargs):+ raise AssertionError("optimized SIFT must not call the generic detector")++ monkeypatch.setattr(ScaleSpaceDetector, "forward", forbidden)+ feature = SIFTFeatureScaleSpace(8, descriptor_backend="pyramid").to(device, dtype)+ assert isinstance(feature.detector, _SIFTScaleSpaceDetector)+ lafs, responses, descriptors = feature(torch.rand(1, 1, 33, 35, device=device, dtype=dtype))+ assert lafs.shape == (1, 8, 2, 3)+ assert responses.dtype == descriptors.dtype == lafs.dtype == dtype+++class TestSIFTScalePyramid(BaseTester):+ def test_precise_double_grid(self, device, dtype):+ from kornia.feature.sift.scale_space import _SIFTScalePyramid++ if not supports_replicate_padding(device, dtype):+ pytest.skip("direct pyramid helper requires native replicate padding; the detector promotes half inputs")+ image = torch.arange(35, device=device, dtype=dtype).reshape(1, 1, 5, 7)+ doubled = _SIFTScalePyramid._double(image)+ self.assert_close(doubled[..., ::2, ::2], image)+ self.assert_close(doubled[..., 0::2, 1:-1:2], 0.5 * (image[..., :-1] + image[..., 1:]))+ assert doubled.shape == (1, 1, 10, 14)++ def test_next_octave_is_exact_decimation(self, device, dtype):+ from kornia.feature.sift.scale_space import _SIFTScalePyramid++ if not supports_replicate_padding(device, dtype) or not supports_reflect_padding(device, dtype):+ pytest.skip("direct pyramid helper requires native border padding; the detector promotes half inputs")+ image = torch.rand(1, 1, 65, 67, device=device, dtype=dtype)+ pyramid = _SIFTScalePyramid().to(device, dtype)(image)+ for previous, current in zip(pyramid, pyramid[1:]):+ h, w = previous.shape[-2:]+ self.assert_close(current[:, :, 0], previous[:, :, 3, : 2 * (h // 2) : 2, : 2 * (w // 2) : 2])+ assert current.shape[2] == 6++ def test_reference_kernels_keep_double_precision(self, device):+ from kornia.feature.sift.scale_space import _SIFTScalePyramid++ if device.type == "mps":+ pytest.skip("MPS does not support float64")+ pyramid = _SIFTScalePyramid().to(device)+ for index in range(6):+ kernel = getattr(pyramid, f"kernel_{index}")+ assert kernel.dtype == torch.float64+ # Rounding the kernel at construction costs normalization at ~1e-8,+ # which would cap a float64 pyramid at float32 accuracy.+ assert (kernel.sum() - 1.0).abs() < 1e-15++ # A normalized kernel with reflection padding leaves a constant image+ # unchanged, so the residual measures kernel accuracy on its own. The+ # float32-rounded kernels this replaces leave ~2.4e-8 here.+ value = 0.37+ image = torch.full((1, 1, 96, 96), value, device=device, dtype=torch.float64)+ for octave in pyramid(image):+ assert (octave - value).abs().max() < 1e-14++ def test_pyramid_backend_rejects_unknown_compile_component(self):+ with pytest.raises(ValueError, match="compile_modules"):+ SIFTFeatureScaleSpace(descriptor_backend="pyramid", compile_modules=["resp"])+++class _FixedPyramid(nn.Module):+ def __init__(self, dog: torch.Tensor) -> None:+ super().__init__()+ self.dog = dog++ def forward(self, image: torch.Tensor) -> list[torch.Tensor]:+ gaussian = torch.cat([torch.zeros_like(self.dog[:, :1]), self.dog.cumsum(1)], 1).unsqueeze(1)+ return [gaussian.to(image)]+++def _quadratic_dog(+ device: torch.device,+ dtype: torch.dtype,+ amplitude: float = 1.0,+ curvature: tuple[float, float, float] = (1.0, 1.0, 1.0),+ center: tuple[float, float, float] = (2.2, 10.3, 11.2),+) -> torch.Tensor:+ # The detector constructs its pyramid in float32 for reduced-precision+ # inputs; preserve the analytic curvature in this substitute pyramid too.+ dtype = torch.float32 if dtype in (torch.float16, torch.bfloat16) else dtype+ s = torch.arange(5, device=device, dtype=dtype).view(1, 5, 1, 1)+ y = torch.arange(32, device=device, dtype=dtype).view(1, 1, 32, 1)+ x = torch.arange(32, device=device, dtype=dtype).view(1, 1, 1, 32)+ cs, cy, cx = curvature+ return amplitude * (+ 20.0 - cs * (s - center[0]).square() - cy * (y - center[1]).square() - cx * (x - center[2]).square()+ )+++class TestSIFTScaleSpaceDetector(BaseTester):+ @pytest.mark.parametrize("case", ["random", "quadratic", "singular", "outside"])+ def test_cuda_refinement_matches_reference(self, device, dtype, case):+ if device.type not in ("cpu", "cuda"):+ pytest.skip("CUDA implementation; CPU checks its arithmetic against the reference")+ if dtype not in (torch.float32, torch.float64):+ pytest.skip("the specialized detector promotes reduced precision before refinement")+ generator = torch.Generator().manual_seed(23)+ dog = torch.rand(1, 5, 32, 32, generator=generator, dtype=dtype)+ index = torch.arange(24)+ b, s, y, x = index * 0, index % 5, (index * 3) % 32, (index * 7) % 32+ if case == "quadratic":+ dog = _quadratic_dog(torch.device("cpu"), dtype)+ s, y, x = index * 0 + 2, index % 3 + 9, index % 4 + 10+ elif case == "singular":+ dog.zero_()+ elif case == "outside":+ # The eager implementation exits before reading these NaNs. Extra+ # fixed-trip CUDA iterations must not introduce NaNs in backward.+ dog.fill_(float("nan"))+ s = index * 0 - 1+ reference_image = dog.clone().requires_grad_()+ image = dog.to(device).requires_grad_()+ detector = _SIFTScaleSpaceDetector(24, nn.Identity())+ expected = detector._refine(reference_image, b, s, y, x)+ actual = detector._refine_cuda(image, *(value.to(device) for value in (b, s, y, x)))+ for value, reference in zip(actual, expected):+ self.assert_close(value, reference.to(device), rtol=0, atol=0)+ if case == "quadratic":+ assert actual[-1].all()+ weights = torch.linspace(0.1, 1.0, index.numel(), dtype=dtype)+ reference_loss = sum((value * weights).sum() for value in expected[4:7]) + reference_image[..., :0].sum()+ loss = sum((value * weights.to(device)).sum() for value in actual[4:7]) + image[..., :0].sum()+ reference_loss.backward()+ loss.backward()+ assert image.grad is not None and reference_image.grad is not None+ assert torch.isfinite(image.grad).all()+ self.assert_close(image.grad, reference_image.grad.to(device))++ def test_dynamo_refinement(self, device, dtype, torch_optimizer):+ dog = _quadratic_dog(device, dtype)+ detector = _SIFTScaleSpaceDetector(1, _FixedPyramid(dog))+ b = torch.tensor([0], device=device)+ s, y, x = b + 2, b + 10, b + 11+ expected = detector._refine(dog, b, s, y, x)+ actual = torch_optimizer(detector._refine)(dog, b, s, y, x)+ for value, reference in zip(actual, expected):+ self.assert_close(value, reference)++ @pytest.mark.parametrize("neighbour", [(0, 1, 1), (1, 1, 1), (-1, 0, 0)])+ @pytest.mark.parametrize("sign", [-1.0, 1.0])+ def test_rejects_equal_diagonal_and_adjacent_scale(self, device, dtype, neighbour, sign):+ dog = torch.zeros(1, 5, 32, 32, device=device, dtype=dtype)+ dog[0, 2, 16, 16] = sign+ ds, dy, dx = neighbour+ dog[0, 2 + ds, 16 + dy, 16 + dx] = sign+ detector = _SIFTScaleSpaceDetector(2, _FixedPyramid(dog))+ lafs, responses = detector(torch.zeros(1, 1, 32, 32, device=device, dtype=dtype))+ assert not lafs.any() and not responses.any()++ def test_checkerboard_equal_diagonals_reject_before_neighbourhood_gather(self, device, dtype, monkeypatch):+ y = torch.arange(32, device=device).view(1, 1, 32, 1)+ x = torch.arange(32, device=device).view(1, 1, 1, 32)+ dog = (1 - 2 * ((x + y) % 2)).to(torch.float32 if dtype in (torch.float16, torch.bfloat16) else dtype)+ dog = dog.expand(1, 5, -1, -1)+ gaussian = torch.cat([torch.zeros_like(dog[:, :1]), dog.cumsum(1)], 1).unsqueeze(1)+ detector = _SIFTScaleSpaceDetector(1, nn.Identity()).to(device, dtype)++ def forbidden(*args, **kwargs):+ raise AssertionError("checkerboard candidates must be rejected before sparse gathering")++ monkeypatch.setattr(detector, "_neighbourhood", forbidden)+ result = detector._octave(gaussian, 0, None)+ assert all(value.numel() == 0 for value in result)++ def test_scale_rejected_spikes_screen_neighbourhoods_in_bounded_chunks(self, device, dtype, monkeypatch):+ if device.type not in ("cpu", "mps") or dtype != torch.float32:+ pytest.skip("exercises the CPU/MPS sparse-screening chunk limits")+ size = 512+ coordinates = torch.arange(6, size - 5, 3, device=device)+ dog = torch.zeros(1, 5, size, size, device=device, dtype=dtype)+ # Every searchable scale sees the same isolated spatial maxima, so all+ # candidates reach sparse screening but fail strict scale comparison.+ dog[:, :, coordinates[:, None], coordinates] = 1.0+ gaussian = torch.cat([torch.zeros_like(dog[:, :1]), dog.cumsum(1)], 1).unsqueeze(1)+ detector = _SIFTScaleSpaceDetector(1, nn.Identity())+ original = detector._neighbourhood+ calls = []++ def record(*args):+ calls.append(args[1].numel())+ return original(*args)++ monkeypatch.setattr(detector, "_neighbourhood", record)+ with torch.inference_mode():+ result = detector._octave(gaussian, 0, None)+ limit = 16384 if device.type == "cpu" else 65536+ assert len(calls) > 1 and sum(calls) > limit and max(calls) <= limit+ assert all(value.numel() == 0 for value in result)++ def test_many_middle_scale_extrema_refine_in_chunks(self, device, dtype, monkeypatch):+ if device.type != "cpu" or dtype != torch.float32:+ pytest.skip("exercises the CPU refinement chunk limit")+ size = 512+ coordinates = torch.arange(6, size - 5, 3, device=device)+ dog = torch.zeros(1, 5, size, size, device=device, dtype=dtype)+ dog[:, 2, coordinates[:, None], coordinates] = 1.0+ gaussian = torch.cat([torch.zeros_like(dog[:, :1]), dog.cumsum(1)], 1).unsqueeze(1)+ detector = _SIFTScaleSpaceDetector(1, nn.Identity())+ original = detector._refine+ calls = []++ def record(*args):+ calls.append(args[1].numel())+ return original(*args)++ monkeypatch.setattr(detector, "_refine", record)+ with torch.inference_mode():+ *_, responses, _, _, _ = detector._octave(gaussian, 0, None)+ expected_count = coordinates.numel() ** 2+ assert len(calls) > 1 and sum(calls) == expected_count and max(calls) <= 16384+ assert responses.numel() == expected_count+ self.assert_close(responses, torch.ones_like(responses))++ def test_sparse_neighbourhood_values_and_backward(self, device, dtype):+ dog = torch.rand(2, 5, 13, 15, device=device, dtype=dtype, requires_grad=True)+ b = torch.tensor([0, 1, 0], device=device)+ s = torch.tensor([1, 3, 1], device=device)+ y = torch.tensor([5, 7, 5], device=device)+ x = torch.tensor([6, 9, 6], device=device)+ actual = _SIFTScaleSpaceDetector._neighbourhood(dog, b, s, y, x)+ expected = torch.stack([dog[0, 0:3, 4:7, 5:8], dog[1, 2:5, 6:9, 8:11], dog[0, 0:3, 4:7, 5:8]])+ self.assert_close(actual, expected)+ actual_grad = torch.autograd.grad(actual.sum(), dog)[0]+ expected_grad = torch.autograd.grad(expected.sum(), dog)[0]+ self.assert_close(actual_grad, expected_grad)++ def test_refines_analytic_extremum_and_keeps_tiny_amplitude(self, device, dtype):+ image = torch.zeros(1, 1, 32, 32, device=device, dtype=dtype)+ dog = _quadratic_dog(device, dtype)+ detector = _SIFTScaleSpaceDetector(4, _FixedPyramid(dog)).to(device, dtype)+ lafs, responses = detector(image)+ filled = laf_is_filled(lafs)+ assert filled[0, 0]+ expected = torch.tensor([11.2 * 0.5, 10.3 * 0.5], device=device, dtype=dtype)+ self.assert_close(get_laf_center(lafs)[0, 0], expected, rtol=2e-3, atol=2e-3)+ amplitude = 1e-4 if dtype == torch.float16 else 1e-8+ tiny_lafs, tiny_responses = _SIFTScaleSpaceDetector(4, _FixedPyramid(dog * amplitude)).to(device, dtype)(image)+ assert laf_is_filled(tiny_lafs)[0, 0]+ self.assert_close(get_laf_center(tiny_lafs)[0, 0], get_laf_center(lafs)[0, 0], rtol=2e-3, atol=2e-3)+ self.assert_close(tiny_responses[0, 0], responses[0, 0] * amplitude, rtol=5e-3, atol=1e-12)++ def test_keeps_edge_like_anisotropic_extremum(self, device, dtype):+ image = torch.zeros(1, 1, 32, 32, device=device, dtype=dtype)+ dog = _quadratic_dog(device, dtype, curvature=(1.0, 1e-3, 1.0))+ lafs, _ = _SIFTScaleSpaceDetector(4, _FixedPyramid(dog)).to(device, dtype)(image)+ assert laf_is_filled(lafs)[0, 0]++ def test_minimum_is_ranked_by_absolute_response_and_output_is_padded(self, device, dtype):+ image = torch.zeros(1, 1, 32, 32, device=device, dtype=dtype)+ maximum = _quadratic_dog(device, dtype)+ minimum = -_quadratic_dog(device, dtype) + 1.0+ # Put a stronger negative extremum in the second batch item; both signs+ # are valid and responses are absolute refined DoG values.+ dog = torch.cat([maximum, minimum * 2.0], 0)+ lafs, responses = _SIFTScaleSpaceDetector(3, _FixedPyramid(dog)).to(device, dtype)(image.expand(2, -1, -1, -1))+ assert laf_is_filled(lafs)[:, 0].all()+ assert (responses[:, 0] > 0).all()+ assert (~laf_is_filled(lafs)[:, 1:]).all()+ assert not responses[:, 1:].any()++ def test_mask_broadcast_zero_and_fractional_weight(self, device, dtype):+ image = torch.zeros(2, 1, 32, 32, device=device, dtype=dtype)+ dog = _quadratic_dog(device, dtype).expand(2, -1, -1, -1).clone()+ detector = _SIFTScaleSpaceDetector(2, _FixedPyramid(dog)).to(device, dtype)+ _, unmasked = detector(image)+ mask = torch.full((1, 1, 32, 32), 0.25, device=device, dtype=dtype)+ lafs, weighted = detector(image, mask)+ assert laf_is_filled(lafs)[:, 0].all()+ self.assert_close(weighted[:, 0], unmasked[:, 0] * 0.25, rtol=2e-3, atol=2e-3)+ zero_lafs, zero_responses = detector(image, torch.zeros_like(mask))+ assert not zero_lafs.any() and not zero_responses.any()++ def test_flat_and_singular_refinement_reject_without_oob_access(self, device, dtype):+ image = torch.zeros(1, 1, 32, 32, device=device, dtype=dtype)+ flat = torch.zeros(1, 5, 32, 32, device=device, dtype=dtype)+ lafs, responses = _SIFTScaleSpaceDetector(2, _FixedPyramid(flat)).to(device, dtype)(image)+ assert not lafs.any() and not responses.any()+ detector = _SIFTScaleSpaceDetector(1, _FixedPyramid(flat)).to(device, dtype)+ b = torch.zeros(1, device=device, dtype=torch.long)+ s = torch.full_like(b, 2)+ y = torch.full_like(b, 10)+ x = torch.full_like(b, 10)+ *_, converged = detector._refine(flat, b, s, y, x)+ assert not converged.any()++ def test_fractional_offsets_at_right_bottom_border(self, device, dtype):+ image = torch.zeros(1, 1, 32, 32, device=device, dtype=dtype)+ dog = _quadratic_dog(device, dtype, center=(2.2, 26.3, 26.2))+ lafs, _ = _SIFTScaleSpaceDetector(1, _FixedPyramid(dog))(image)+ assert laf_is_filled(lafs).all()+ expected = torch.tensor([26.2, 26.3], device=device, dtype=dtype) * 0.5+ self.assert_close(get_laf_center(lafs)[0, 0], expected, atol=0.01, rtol=0.001)++ def test_topk_sorts_by_refined_response(self, device, dtype):+ image = torch.zeros(1, 1, 32, 32, device=device, dtype=dtype)+ weaker = _quadratic_dog(device, dtype)+ stronger = _quadratic_dog(device, dtype, amplitude=2.0, center=(2.2, 10.3, 21.2))+ dog = torch.maximum(weaker, stronger)+ lafs, scores = _SIFTScaleSpaceDetector(2, _FixedPyramid(dog))(image)+ assert laf_is_filled(lafs).all()+ assert scores[0, 0] > scores[0, 1]+ expected = torch.tensor([[21.2, 10.3], [11.2, 10.3]], device=device, dtype=dtype) * 0.5+ self.assert_close(get_laf_center(lafs)[0], expected, atol=0.01, rtol=0.001)++ def test_refinement_backward_is_finite(self, device):+ dog = _quadratic_dog(device, torch.float32).requires_grad_()+ detector = _SIFTScaleSpaceDetector(1, _FixedPyramid(dog))+ lafs, responses = detector(torch.zeros(1, 1, 32, 32, device=device))+ (lafs.sum() + responses.sum()).backward()+ assert torch.isfinite(dog.grad).all()diff --git a/tests/geometry/subpix/test_spatial_softargmax.py b/tests/geometry/subpix/test_spatial_softargmax.pyindex 095e3844f..fcebaa6a6 100644--- a/tests/geometry/subpix/test_spatial_softargmax.py+++ b/tests/geometry/subpix/test_spatial_softargmax.py@@ -803,3 +803,96 @@ class TestAdaptiveQuadInterp3d(BaseTester):assert len(d_idx) > 0, "No NMS maxima found β check the synthetic input"diff = (coord_conv[0, 0, :, d_idx, h_idx, w_idx] - coord_iter[0, 0, :, d_idx, h_idx, w_idx]).abs().max()self.assert_close(diff, torch.zeros_like(diff), atol=1e-5, rtol=0)+++class TestPackedQuadraticFit(BaseTester):+ @pytest.mark.parametrize("count", [0, 17])+ def test_cramer_reference(self, device, dtype, count):+ from kornia.geometry.subpix import spatial_soft_argmax as subpix++ if dtype not in (torch.float32, torch.float64):+ pytest.skip("Packed quadratic fit is dispatched only for float32/float64")+ # Transposed input exercises the strided columns used by the patch gather.+ system = torch.randn(count, 9, device=device, dtype=dtype).T.detach().requires_grad_()+ if count:+ with torch.no_grad():+ system[:3] += 4+ system[:, :4] = 0+ system[0:2, :4] = 1+ system[2, :4] = system.new_tensor([0, 0.5e-7, 1e-7, 2e-7])+ system[6:, :4] = 0.1+ cpu = system.detach().cpu().requires_grad_()+ expected = subpix._solve_cramer_sym3x3(*cpu)+ actual = subpix._solve_cramer_sym3x3_cuda(*system)+ for got, want in zip(actual, expected):+ self.assert_close(got.cpu(), want, atol=0, rtol=0)+ weights = torch.linspace(0.1, 0.9, count, device=device, dtype=dtype)+ # Threshold cases pin forward/mask semantics. Near-singular derivatives+ # cancel large terms, so compare gradient accumulation on conditioned rows.+ weights[:4] = 0+ grad = torch.autograd.grad(sum((v * weights).sum() for v in actual[:3]), system)[0]+ grad_ref = torch.autograd.grad(sum((v * weights.cpu()).sum() for v in expected[:3]), cpu)[0]+ self.assert_close(grad.cpu(), grad_ref)++ def test_cramer_keeps_input_shape(self, device, dtype):+ from kornia.geometry.subpix import spatial_soft_argmax as subpix++ if dtype not in (torch.float32, torch.float64):+ pytest.skip("Packed quadratic fit is dispatched only for float32/float64")+ # The packed CUDA solve indexes a single batch dimension. A wider caller+ # must keep its shape and its values rather than be flattened on CUDA only.+ torch.manual_seed(0)+ system = torch.randn(9, 2, 5, device=device, dtype=dtype)+ system[:3] += 4.0+ actual = subpix._solve_cramer_sym3x3(*system)+ expected = subpix._solve_cramer_sym3x3(*system.reshape(9, -1))+ for got, want in zip(actual, expected):+ assert got.shape == (2, 5)+ self.assert_close(got.reshape(-1), want, atol=0, rtol=0)++ @pytest.mark.parametrize("count", [0, 19])+ def test_patch_derivatives(self, device, dtype, count):+ from kornia.geometry.subpix import spatial_soft_argmax as subpix++ if dtype not in (torch.float32, torch.float64):+ pytest.skip("Packed quadratic fit is dispatched only for float32/float64")+ patch = torch.randn(27, count, device=device, dtype=dtype).T.detach().requires_grad_()+ actual = subpix._quadratic_derivatives3d(patch)+ expected = (+ 0.5 * (patch[:, 14] - patch[:, 12]),+ 0.5 * (patch[:, 16] - patch[:, 10]),+ 0.5 * (patch[:, 22] - patch[:, 4]),+ patch[:, 14] - 2.0 * patch[:, 13] + patch[:, 12],+ patch[:, 16] - 2.0 * patch[:, 13] + patch[:, 10],+ patch[:, 22] - 2.0 * patch[:, 13] + patch[:, 4],+ 0.25 * (patch[:, 17] - patch[:, 15] - patch[:, 11] + patch[:, 9]),+ 0.25 * (patch[:, 23] - patch[:, 21] - patch[:, 5] + patch[:, 3]),+ 0.25 * (patch[:, 25] - patch[:, 19] - patch[:, 7] + patch[:, 1]),+ )+ for got, want in zip(actual, expected):+ self.assert_close(got, want, atol=0, rtol=0)+ loss = sum(v.square().sum() for v in actual)+ loss_ref = sum(v.square().sum() for v in expected)+ grad = torch.autograd.grad(loss, patch, retain_graph=True)[0]+ grad_ref = torch.autograd.grad(loss_ref, patch)[0]+ self.assert_close(grad, grad_ref)++ @pytest.mark.parametrize("op_name", ["conv_quad_interp3d", "iterative_quad_interp3d"])+ @pytest.mark.parametrize("n_iters", [1, 5])+ @pytest.mark.parametrize("allow_scale_steps", [False, True])+ def test_public_cuda_reference(self, device, dtype, op_name, n_iters, allow_scale_steps):+ if device.type != "cuda" or dtype not in (torch.float32, torch.float64):+ pytest.skip("Compare the packed CUDA path against the scalar CPU path")+ from kornia.geometry.subpix import spatial_soft_argmax as subpix++ op = getattr(subpix, op_name)+ sample = torch.rand(2, 2, 5, 9, 8, dtype=dtype).requires_grad_()+ cuda_sample = sample.detach().to(device).requires_grad_()+ kwargs = {"n_iters": n_iters, "allow_scale_steps": allow_scale_steps, "strict_maxima_bonus": 0.0}+ expected = op(sample, **kwargs)+ actual = op(cuda_sample, **kwargs)+ for got, want in zip(actual, expected):+ self.assert_close(got.cpu(), want, atol=0, rtol=0)+ grad = torch.autograd.grad(sum(t.square().mean() for t in actual), cuda_sample)[0]+ grad_ref = torch.autograd.grad(sum(t.square().mean() for t in expected), sample)[0]+ self.assert_close(grad.cpu(), grad_ref)diff --git a/tests/scripts/test_check_torch_env.py b/tests/scripts/test_check_torch_env.pyindex 9e81474f3..06b08cb48 100644--- a/tests/scripts/test_check_torch_env.py+++ b/tests/scripts/test_check_torch_env.py@@ -16,6 +16,7 @@#import sysfrom pathlib import Path+from subprocess import runimport pytest@@ -183,10 +184,53 @@ def test_installed_versions_reports_this_environment():assert "typing-extensions" in installed-def test_scan_installed_finds_no_duplicates_in_a_coherent_venv():- installed, duplicates = scan_installed()+def test_scan_installed_finds_no_duplicates_after_setuptools_adds_its_vendor_path():+ # setuptools adds vendored dependencies to sys.path. Some have a different version+ # from the environment's distribution, but normal import and metadata resolution use+ # the first path entry, so that is coherent rather than a half-written venv.+ script_dir = Path(__file__).parent.parent.parent / ".github" / "scripts"+ check = run( # noqa: S603 -- invokes the current test interpreter with a fixed probe.+ [+ sys.executable,+ "-c",+ f"import sys; sys.path.insert(0, {str(script_dir)!r}); import setuptools; "+ "from check_torch_env import scan_installed; assert scan_installed()[1] == {}",+ ],+ check=False,+ capture_output=True,+ text=True,+ )- assert installed["torch"]+ assert check.returncode == 0, check.stderr+++def _write_distribution(root: Path, name: str, version: str) -> None:+ dist_info = root / f"{name}-{version}.dist-info"+ dist_info.mkdir()+ (dist_info / "METADATA").write_text(f"Metadata-Version: 2.1\nName: {name}\nVersion: {version}\n", encoding="utf-8")+++def test_scan_installed_detects_conflicting_dist_infos_in_one_location(tmp_path):+ _write_distribution(tmp_path, "example", "1.0")+ _write_distribution(tmp_path, "example", "2.0")++ installed, duplicates = scan_installed([str(tmp_path)])++ assert installed["example"] in {"1.0", "2.0"}+ assert duplicates == {"example": ["1.0", "2.0"]}+++def test_scan_installed_keeps_first_path_entry_when_locations_disagree(tmp_path):+ first = tmp_path / "first"+ second = tmp_path / "second"+ first.mkdir()+ second.mkdir()+ _write_distribution(first, "example", "1.0")+ _write_distribution(second, "example", "2.0")++ installed, duplicates = scan_installed([str(first), str(second)])++ assert installed["example"] == "1.0"assert duplicates == {}diff --git a/tests/test_sift_scale_space_benchmark.py b/tests/test_sift_scale_space_benchmark.pynew file mode 100644index 000000000..9219f8d49--- /dev/null+++ b/tests/test_sift_scale_space_benchmark.py@@ -0,0 +1,75 @@+# 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.+#++"""Geometric-quality checks for the shared-pyramid SIFT benchmark."""++from __future__ import annotations++import pytest+import torch++pytest.importorskip("PIL")++from benchmarks.feature.sift_scale_space import homography_quality+from kornia.geometry import transform_points+++def test_ransac_recovers_homography_with_outliers():+ generator = torch.Generator().manual_seed(12)+ source = torch.rand(60, 2, generator=generator) * 100+ truth = torch.tensor([[1.1, 0.05, 3.0], [-0.03, 0.9, 8.0], [0.0002, -0.0001, 1.0]])+ target = transform_points(truth[None], source[None])[0]+ target[-10:] = torch.rand(10, 2, generator=generator) * 100+ result = homography_quality(source, target, truth, 100, 100)+ assert result["ransac_status"] == "estimated"+ assert result["ransac_inliers"] >= 50+ assert result["ransac_corner_error_px"] < 0.01+++def test_insufficient_matches_has_no_fake_zero_error():+ result = homography_quality(torch.zeros(3, 2), torch.zeros(3, 2), torch.eye(3), 100, 100)+ assert result["ransac_status"] == "insufficient_matches"+ assert result["ransac_inliers"] == 0+ assert result["ransac_corner_error_px"] is None+++def test_corner_metric_uses_non_square_pixel_extents_and_mean_l1(monkeypatch):+ import benchmarks.feature.sift_scale_space as benchmark++ # On a 21-wide, 11-high image, corner L1 errors are 0, 2, 4, 2.+ estimate = torch.diag(torch.tensor([1.1, 1.2, 1.0]))+ monkeypatch.setattr(+ benchmark, "RANSAC", lambda *args, **kwargs: lambda source, target: (estimate, torch.ones(4, dtype=torch.bool))+ )+ result = homography_quality(torch.zeros(4, 2), torch.zeros(4, 2), torch.eye(3), 11, 21)+ assert result["ransac_corner_error_px"] == pytest.approx(2.0, abs=1e-5)++[email protected]("inliers,status", [(0, "failed_estimate"), (4, "nonfinite_projection")])+def test_failed_geometry_retains_null_error(monkeypatch, inliers, status):+ import benchmarks.feature.sift_scale_space as benchmark++ # The denominator is x: the two left-hand corners project to infinity.+ estimate = torch.tensor([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [1.0, 0.0, 0.0]])+ monkeypatch.setattr(+ benchmark,+ "RANSAC",+ lambda *args, **kwargs: lambda source, target: (estimate, torch.arange(4) < inliers),+ )+ result = homography_quality(torch.zeros(4, 2), torch.zeros(4, 2), torch.eye(3), 11, 21)+ assert result["ransac_status"] == status+ assert result["ransac_corner_error_px"] is None