π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
feat: add AdaptiveQuadInterp3d and scale-space detector speedups (#3623)
Dmytro Mishkin398665c75632
diff --git a/benchmarks/feature/scale_space_detector.py b/benchmarks/feature/scale_space_detector.pynew file mode 100644index 000000000..ea5153067--- /dev/null+++ b/benchmarks/feature/scale_space_detector.py@@ -0,0 +1,659 @@+# 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.+#+"""Benchmark a fully-configurable feature pipeline on Oxford-Affine-style sequences.++An Oxford-Affine sequence directory contains::++ img1.png img2.png ... imgN.png+ H1to2p H1to3p ... H1toNp (3x3 homography ground truth, whitespace-separated)++The pipeline can be either a ``ScaleSpaceDetector``-based combination (freely composable+response function, subpix module, descriptor, orientation estimator and affine-shape+estimator) or one of the end-to-end learned detectors (ALIKED, DISK, DeDoDe).++Output columns per image pair (img1 vs imgK):++* ``error [px]`` -- mean corner reprojection error vs ground-truth homography (lower is better).+* ``inliers [#]`` -- RANSAC inlier count (higher is better).+* ``time [ms]`` -- detect + describe + match wall-clock time (lower is better).++Usage examples::++ # default (AdaptiveQuadInterp3d + DoG + SIFT)+ python benchmarks/feature/scale_space_detector.py --seq /data/graf++ # swap descriptor+ python benchmarks/feature/scale_space_detector.py --seq /data/graf --desc hardnet++ # Hessian + AffNet + OriNet+ python benchmarks/feature/scale_space_detector.py --seq /data/graf \\+ --resp hessian --aff affnet --ori orinet++ # end-to-end ALIKED (ignores --resp/--subpix/--desc/--ori/--aff)+ python benchmarks/feature/scale_space_detector.py --seq /data/graf --method aliked++ # one named sequence inside a root folder+ python benchmarks/feature/scale_space_detector.py --root /data/oxford-affine --seq graf++ # all sequences inside a root folder+ python benchmarks/feature/scale_space_detector.py --root /data/oxford-affine --device cuda+"""++from __future__ import annotations++import argparse+import time+from pathlib import Path+from typing import Callable, Dict, List, Tuple, Union++import cv2+import numpy as np+import torch+from torch import nn++import kornia.feature as KF+from kornia.feature.integrated import KeyNetAffNetHardNet, KeyNetHardNet+from kornia.feature.responses import BlobDoG, BlobDoGSingle, BlobHessian, CornerGFTT, CornerHarris+from kornia.geometry import RANSAC+from kornia.geometry.subpix import (+ AdaptiveQuadInterp3d,+ ConvQuadInterp3d,+ ConvSoftArgmax3d,+ IterativeQuadInterp3d,+)+from kornia.geometry.transform import ScalePyramid++# ---------------------------------------------------------------------------+# Metric+# ---------------------------------------------------------------------------+++def get_MAE_imgcorners(h: int, w: int, H_gt, H_est) -> float:+ """Mean corner reprojection error of H_est vs H_gt (pixels).++ Example::++ H_gt = np.loadtxt(Hgt)+ img1 = K.image_to_tensor(cv2.imread(f1, 0), False) / 255.+ img2 = K.image_to_tensor(cv2.imread(f2, 0), False) / 255.+ h, w = img1.size(2), img1.size(3)+ H_out = matchImages(img1, img2)+ MAE = get_MAE_imgcorners(h, w, H_gt, H_out.detach().cpu().numpy())+ """+ pts = np.float32([[0, 0], [0, h - 1], [w - 1, h - 1], [w - 1, 0]]).reshape(-1, 1, 2)+ dst = cv2.perspectiveTransform(pts, H_est).squeeze(1)+ dst_GT = cv2.perspectiveTransform(pts, H_gt).squeeze(1)+ return float(np.abs(dst - dst_GT).sum(axis=1).mean())+++# ---------------------------------------------------------------------------+# I/O helpers+# ---------------------------------------------------------------------------+++def load_gray(path: str, device: torch.device) -> torch.Tensor:+ img = cv2.imread(path, cv2.IMREAD_GRAYSCALE)+ if img is None:+ raise FileNotFoundError(f"Cannot read: {path}")+ return torch.from_numpy(img).float().div(255.0).unsqueeze(0).unsqueeze(0).to(device)+++def gray_to_rgb(t: torch.Tensor) -> torch.Tensor:+ return t.expand(-1, 3, -1, -1)+++def find_pairs(seq: Path):+ pairs = []+ for k in range(2, 10):+ img_p = seq / f"img{k}.png"+ h_p = seq / f"H1to{k}p"+ if img_p.exists() and h_p.exists():+ pairs.append((k, img_p, h_p))+ return pairs+++# ---------------------------------------------------------------------------+# Component registries+# ---------------------------------------------------------------------------++RESP_REGISTRY: dict[str, tuple] = {+ "dog": (BlobDoG, True, True),+ "dog_single": (lambda: BlobDoGSingle(1.0, 1.6), False, True),+ "hessian": (BlobHessian, False, True),+ "harris": (lambda: CornerHarris(k=0.04), False, False),+ "gftt": (CornerGFTT, False, False),+}++SUBPIX_REGISTRY: dict[str, Callable] = {+ "adaptive": lambda: AdaptiveQuadInterp3d(strict_maxima_bonus=0.0, allow_scale_steps=True),+ "conv": lambda: ConvQuadInterp3d(strict_maxima_bonus=0.0),+ "iterative": lambda: IterativeQuadInterp3d(strict_maxima_bonus=0.0),+ "soft": lambda: ConvSoftArgmax3d((3, 3, 3), (1, 1, 1), (1, 1, 1), normalized_coordinates=False, output_value=True),+}++DESC_REGISTRY: dict[str, tuple] = {+ "sift": (lambda: KF.SIFTDescriptor(32, rootsift=True), 32),+ "hardnet": (lambda: KF.HardNet(pretrained=True), 32),+ "hardnet8": (lambda: KF.HardNet8(pretrained=True), 32),+ "hynet": (lambda: KF.HyNet(pretrained=True), 32),+ "sosnet": (lambda: KF.SOSNet(pretrained=True), 32),+ "tfeat": (lambda: KF.TFeat(pretrained=True), 32),+ "mkd": (lambda: KF.MKDDescriptor(32), 32),+}++ORI_REGISTRY: dict[str, Callable] = {+ "none": KF.PassLAF,+ "lap": lambda: KF.LAFOrienter(32, angle_detector=KF.PatchDominantGradientOrientation(32)),+ "orinet": lambda: KF.LAFOrienter(32, angle_detector=KF.OriNet(pretrained=True)),+}++AFF_REGISTRY: dict[str, Callable] = {+ "none": KF.PassLAF,+ "patch": lambda: KF.LAFAffineShapeEstimator(32),+ "affnet": lambda: KF.LAFAffNetShapeEstimator(pretrained=True),+}+++# ---------------------------------------------------------------------------+# Extractor wrappers (unified: img -> (kp N x 2, desc N x D))+# ---------------------------------------------------------------------------+++class ScaleSpaceExtractor(nn.Module):+ def __init__(self, detector, desc_module, ori_module, aff_module, patch_size: int):+ super().__init__()+ self.detector, self.desc = detector, desc_module+ self.ori, self.aff = ori_module, aff_module+ self.patch_size = patch_size++ @torch.no_grad()+ def forward(self, img: torch.Tensor):+ t_det0 = time.perf_counter()+ lafs, _ = self.detector(img)+ if img.device.type == "cuda":+ torch.cuda.synchronize()+ det_ms = (time.perf_counter() - t_det0) * 1000+ lafs = self.aff(lafs, img)+ lafs = self.ori(lafs, img)+ patches = KF.extract_patches_from_pyramid(img, lafs, self.patch_size)+ B, N, C, H, W = patches.shape+ desc = self.desc(patches.view(B * N, C, H, W)).view(B, N, -1)+ return KF.get_laf_center(lafs)[0], desc[0], det_ms+++class ALIKEDExtractor(nn.Module):+ def __init__(self, model):+ super().__init__()+ self.model = model++ @torch.no_grad()+ def forward(self, img: torch.Tensor):+ f = self.model(gray_to_rgb(img))[0]+ return f.keypoints, f.descriptors, None+++class DISKExtractor(nn.Module):+ def __init__(self, model, n: int):+ super().__init__()+ self.model, self.n = model, n++ @torch.no_grad()+ def forward(self, img: torch.Tensor):+ f = self.model(gray_to_rgb(img), n=self.n, pad_if_not_divisible=True)[0]+ return f.keypoints, f.descriptors, None+++class DeDoDEExtractor(nn.Module):+ def __init__(self, model, n: int):+ super().__init__()+ self.model, self.n = model, n++ @torch.no_grad()+ def forward(self, img: torch.Tensor):+ kp, _, desc = self.model(gray_to_rgb(img), n=self.n)+ return kp[0], desc[0], None+++class DoGHardNet(nn.Module):+ def __init__(self, nf: int):+ super().__init__()+ from kornia_moons.feature import OpenCVDetectorWithAffNetKornia++ kornia_cv2dogaffnet = OpenCVDetectorWithAffNetKornia(+ cv2.SIFT_create(nf, edgeThreshold=-1, contrastThreshold=-1), make_upright=True+ )+ self.det = kornia_cv2dogaffnet+ self.desc = KF.HardNet(pretrained=True)+ self.ori = KF.LAFOrienter(32, angle_detector=KF.OriNet(pretrained=True))++ @torch.no_grad()+ def forward(self, img: torch.Tensor):+ lafs, _ = self.det(img)+ lafs = self.ori(lafs, img)+ patches = KF.extract_patches_from_pyramid(img, lafs, 32)+ B, N, C, H, W = patches.shape+ desc = self.desc(patches.view(B * N, C, H, W)).view(B, N, -1)+ return KF.get_laf_center(lafs)[0], desc[0], None+++class CV2SIFT(nn.Module):+ def __init__(self, nf: int):+ super().__init__()+ self.det = cv2.SIFT_create(nf, edgeThreshold=-1, contrastThreshold=-1)++ @torch.no_grad()+ def forward(self, img: torch.Tensor):+ kpts, desc = self.det.detectAndCompute((255 * img.cpu().numpy().squeeze()).astype(np.uint8), None)+ return torch.from_numpy(np.array([(x.pt[0], x.pt[1]) for x in kpts])), torch.from_numpy(desc), None+++class KeyNetExtractor(nn.Module):+ def __init__(self, n: int, ori: str, aff: str, device: torch.device, compile_model: bool = False):+ super().__init__()+ if aff != "none":+ self.feat = KeyNetAffNetHardNet(num_features=n, upright=(ori == "none")).to(device)+ else:+ self.feat = KeyNetHardNet(num_features=n, upright=(ori == "none")).to(device)+ if compile_model:+ det = self.feat.detector+ # model and nms run at 6 different image sizes β dynamic=True avoids recompilation+ det.model = torch.compile(det.model, dynamic=True)+ det.nms = torch.compile(det.nms, dynamic=True)+ # aff/ori/descriptor NOT compiled: extract_patches_from_pyramid (laf.py) contains+ # an .item() call inside a while-loop that creates graph breaks, causing extra+ # sub-graphs that need additional warmup and show as a spike on the first eval pair.++ @torch.no_grad()+ def forward(self, img: torch.Tensor):+ lafs, _, desc = self.feat(img)+ return KF.get_laf_center(lafs)[0], desc[0], None+++# ---------------------------------------------------------------------------+# Factory+# ---------------------------------------------------------------------------+++def build_extractor(+ method: str,+ resp: str,+ subpix: str,+ desc: str,+ ori: str,+ aff: str,+ device: torch.device,+ nf: int,+ compile_modules: Union[bool, List[str]] = False,+) -> nn.Module:+ if method == "scalespace":+ resp_factory, ssr, minima = RESP_REGISTRY[resp]+ subpix_mod = SUBPIX_REGISTRY[subpix]()+ detector = KF.ScaleSpaceDetector(+ num_features=nf,+ resp_module=resp_factory(),+ subpix_module=subpix_mod,+ scale_pyr_module=ScalePyramid(3, 1.6, 32, double_image=True),+ scale_space_response=ssr,+ minima_are_also_good=minima,+ compile_modules=["subpix", "resp", "scale_pyr"] if compile_modules else [],+ ).to(device)+ desc_factory, patch_size = DESC_REGISTRY[desc]+ return ScaleSpaceExtractor(+ detector,+ desc_factory().to(device),+ ORI_REGISTRY[ori]().to(device),+ AFF_REGISTRY[aff]().to(device),+ patch_size=patch_size,+ )+ if method == "aliked":+ return ALIKEDExtractor(KF.ALIKED.from_pretrained("aliked-n16rot", max_num_keypoints=nf).to(device))+ if method == "disk":+ return DISKExtractor(KF.DISK.from_pretrained("depth", device=device), n=nf)+ if method == "keynet":+ return KeyNetExtractor(n=nf, ori=ori, aff=aff, device=device, compile_model=bool(compile_modules))+ if method == "opencv_sift_affnet":+ return DoGHardNet(nf).to(device)+ if method == "opencv_sift":+ return CV2SIFT(nf).to(device)+ if method == "dedode":+ return DeDoDEExtractor(+ KF.DeDoDe.from_pretrained(detector_weights="L-upright", descriptor_weights="B-upright").to(device), n=nf+ )+ raise ValueError(f"Unknown method: {method!r}")+++def make_label(method: str, resp: str, subpix: str, desc: str, ori: str, aff: str) -> str:+ if method != "scalespace":+ return method+ parts = [f"resp={resp}", f"subpix={subpix}", f"desc={desc}"]+ if ori != "none":+ parts.append(f"ori={ori}")+ if aff != "none":+ parts.append(f"aff={aff}")+ return " ".join(parts)+++# ---------------------------------------------------------------------------+# Matching pipeline+# ---------------------------------------------------------------------------++[email protected]_grad()+def match_pair(img1, img2, extractor, ransac):+ t0 = time.perf_counter()+ kp1, desc1, det_ms1 = extractor(img1)+ kp2, desc2, det_ms2 = extractor(img2)+ _, idxs = KF.match_snn(desc1, desc2, 0.85)+ ms = (time.perf_counter() - t0) * 1000+ det_ms = (det_ms1 + det_ms2) if (det_ms1 is not None and det_ms2 is not None) else None+ if idxs.shape[0] < 4:+ return None, ms, det_ms, 0+ H_est, mask = ransac(kp1[idxs[:, 0]], kp2[idxs[:, 1]])+ n_inliers = int(mask.sum().item()) if mask is not None else 0+ return H_est.cpu().numpy(), ms, det_ms, n_inliers+++# ---------------------------------------------------------------------------+# Evaluation + printing+# ---------------------------------------------------------------------------+++def eval_sequence(seq: Path, extractor, ransac, device) -> dict:+ img1 = load_gray(str(seq / "img1.png"), device)+ h, w = img1.shape[2], img1.shape[3]+ pairs = find_pairs(seq)+ if not pairs:+ raise RuntimeError(f"No valid pairs in {seq}")+ rows = []+ for k, img_path, h_path in pairs:+ img2 = load_gray(str(img_path), device)+ H_gt = np.loadtxt(str(h_path))+ H, ms, det_ms, ni = match_pair(img1, img2, extractor, ransac)+ mae = get_MAE_imgcorners(h, w, H_gt, H) if H is not None else float("nan")+ rows.append({"k": k, "mae": mae, "ni": ni, "ms": ms, "det_ms": det_ms})+ return {"seq": seq.name, "h": h, "w": w, "rows": rows}+++def _col(rows, key):+ return [r[key] for r in rows]+++def print_sequence_table(stats: dict, label: str) -> None:+ rows = stats["rows"]+ has_det = rows[0]["det_ms"] is not None+ print(f"\n-- {stats['seq']} ({stats['h']}x{stats['w']}) --")+ print(f" method : {label}")+ if has_det:+ print(f"\n{'pair':<6} {'error [px]':>12} {'inliers [#]':>12} {'det [ms]':>10} {'time [ms]':>10}")+ print("-" * 56)+ for r in rows:+ print(f"1<>{r['k']:<3} {r['mae']:>12.1f} {r['ni']:>12} {r['det_ms']:>10.1f} {r['ms']:>10.1f}")+ print("-" * 56)+ print(+ f"{'mean':<6} {np.nanmean(_col(rows, 'mae')):>12.1f}"+ f" {np.mean(_col(rows, 'ni')):>12.1f}"+ f" {np.nanmean(_col(rows, 'det_ms')):>10.1f}"+ f" {np.mean(_col(rows, 'ms')):>10.1f}"+ )+ else:+ print(f"\n{'pair':<6} {'error [px]':>12} {'inliers [#]':>12} {'time [ms]':>10}")+ print("-" * 44)+ for r in rows:+ print(f"1<>{r['k']:<3} {r['mae']:>12.1f} {r['ni']:>12} {r['ms']:>10.1f}")+ print("-" * 44)+ print(+ f"{'mean':<6} {np.nanmean(_col(rows, 'mae')):>12.1f}"+ f" {np.mean(_col(rows, 'ni')):>12.1f}"+ f" {np.mean(_col(rows, 'ms')):>10.1f}"+ )+++def print_summary(all_stats, label: str) -> None:+ print("\n" + "=" * 44)+ print(f"OVERALL method={label}")+ print("=" * 44)++ def agg(key):+ return np.nanmean([np.nanmean([r[key] for r in s["rows"]]) for s in all_stats])++ print(f" error [px] : {agg('mae'):.1f}")+ print(f" inliers [#] : {agg('ni'):.1f}")+ has_det = all_stats[0]["rows"][0]["det_ms"] is not None+ if has_det:+ print(f" det [ms] : {agg('det_ms'):.1f}")+ print(f" time [ms] : {agg('ms'):.1f}")+++# ---------------------------------------------------------------------------+# Detection-only batch speed benchmark+# ---------------------------------------------------------------------------+++def _get_bench_module(extractor: nn.Module) -> Tuple[nn.Module, str]:+ """Return (module_to_time, label) for the speed benchmark.++ For pipeline extractors, isolates the detector so aff/ori/desc are excluded.+ For end-to-end models (ALIKED, DISK, DeDoDe) the full forward is timed.+ """+ if isinstance(extractor, ScaleSpaceExtractor):+ return extractor.detector, "detection only"+ if isinstance(extractor, KeyNetExtractor):+ return extractor.feat.detector, "detection only"+ return extractor, "full forward"+++def _time_fn(fn: Callable, n_iter: int, dev: torch.device) -> float:+ """Return mean wall-clock time in ms over n_iter calls."""+ if dev.type == "cuda":+ torch.cuda.synchronize()+ t0 = time.perf_counter()+ for _ in range(n_iter):+ fn()+ if dev.type == "cuda":+ torch.cuda.synchronize()+ return (time.perf_counter() - t0) / n_iter * 1000+++def run_speed_benchmark(+ extractor: nn.Module,+ img: torch.Tensor,+ batch_sizes: Tuple[int, ...] = (1, 4, 8),+ n_iter_gpu: int = 20,+ n_iter_cpu: int = 5,+ warmup: int = 3,+) -> None:+ """Print a batch-size x device timing table.++ Args:+ extractor: the extractor built by :func:`build_extractor`.+ img: single-image tensor ``(1, C, H, W)`` on any device (moved internally).+ batch_sizes: batch sizes to benchmark.+ n_iter_gpu: number of timed iterations on GPU.+ n_iter_cpu: number of timed iterations on CPU.+ warmup: warm-up iterations (not timed).+ """+ mod, what = _get_bench_module(extractor)++ try:+ orig_dev = next(mod.parameters()).device+ except StopIteration:+ orig_dev = img.device++ dev_map: Dict[str, torch.device] = {"cpu": torch.device("cpu")}+ if torch.cuda.is_available():+ dev_map["gpu"] = torch.device("cuda")++ col_w = 14+ print(f"\n-- Speed benchmark ({what}, ms / call) --")+ print(f"{'bs':<6}" + "".join(f"{k:>{col_w}}" for k in dev_map))+ print("-" * (6 + col_w * len(dev_map)))++ for bs in batch_sizes:+ row = f"{bs:<6}"+ for _, dev in dev_map.items():+ n_iter = n_iter_gpu if dev.type == "cuda" else n_iter_cpu+ mod.to(dev)+ img_b = img[0:1].expand(bs, -1, -1, -1).contiguous().to(dev)+ try:+ with torch.no_grad():+ for _ in range(warmup):+ mod(img_b)+ ms = _time_fn(lambda: mod(img_b), n_iter, dev) # noqa: B023+ row += f"{ms:>{col_w - 3}.1f} ms"+ except Exception:+ row += f"{'N/A':>{col_w}}"+ print(row)++ mod.to(orig_dev)+ print()+++# ---------------------------------------------------------------------------+# CLI+# ---------------------------------------------------------------------------+++def parse_args() -> argparse.Namespace:+ p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)+ g = p.add_argument_group("Sequences")+ g.add_argument("--seq", metavar="DIR", action="append", default=[])+ g.add_argument(+ "--root",+ metavar="DIR",+ default=None,+ help="Base folder. Alone: enumerates all subdirs with img1.png. With --seq name: resolves to root/name.",+ )++ g = p.add_argument_group("Method")+ g.add_argument(+ "--method",+ default="scalespace",+ choices=["scalespace", "aliked", "disk", "dedode", "keynet", "opencv_sift_affnet", "opencv_sift"],+ )+ g.add_argument(+ "--resp",+ default="dog",+ choices=list(RESP_REGISTRY),+ metavar="RESP",+ help=f"[scalespace only] choices: {list(RESP_REGISTRY)}",+ )+ g.add_argument(+ "--subpix",+ default="adaptive",+ choices=list(SUBPIX_REGISTRY),+ metavar="SUBPIX",+ help=f"[scalespace only] choices: {list(SUBPIX_REGISTRY)}",+ )+ g.add_argument(+ "--desc",+ default="sift",+ choices=list(DESC_REGISTRY),+ metavar="DESC",+ help=f"[scalespace only] choices: {list(DESC_REGISTRY)}",+ )+ g.add_argument(+ "--ori",+ default="none",+ choices=list(ORI_REGISTRY),+ metavar="ORI",+ help=f"[scalespace only] none=upright; choices: {list(ORI_REGISTRY)}",+ )+ g.add_argument(+ "--aff",+ default="none",+ choices=list(AFF_REGISTRY),+ metavar="AFF",+ help=f"[scalespace only] none=circular; choices: {list(AFF_REGISTRY)}",+ )++ g = p.add_argument_group("Shared")+ g.add_argument("--nf", metavar="N", type=int, default=4096)+ g.add_argument(+ "--compile",+ action="store_true",+ help="torch.compile the extractor (if supported by the method and PyTorch version)",+ )+ g.add_argument("--device", metavar="DEV", default=None)+ g.add_argument("--warmup", metavar="N", type=int, default=1)+ g.add_argument(+ "--speed-bench",+ action="store_true",+ help="Run detection-only speed benchmark (bs=1,4,8 on cpu+gpu) after the matching eval.",+ )+ return p.parse_args()+++def main() -> None:+ args = parse_args()+ device = torch.device(args.device or ("cuda" if torch.cuda.is_available() else "cpu"))+ root = Path(args.root) if args.root else None+ if args.seq:+ # Resolve each --seq name: use as-is if it exists, else try root/name+ seqs = []+ for s in args.seq:+ p = Path(s)+ if not p.exists() and root is not None:+ p = root / s+ seqs.append(p)+ elif root is not None:+ # --root only: enumerate all subdirectories that look like sequences+ seqs = sorted(d for d in root.iterdir() if d.is_dir() and (d / "img1.png").exists())+ else:+ seqs = []+ if not seqs:+ raise SystemExit("No sequences. Use --seq DIR or --root DIR or --root DIR --seq name.")++ label = make_label(args.method, args.resp, args.subpix, args.desc, args.ori, args.aff)+ print(f"device: {device} nf: {args.nf} sequences: {len(seqs)}")+ print(f" method : {label}")++ extractor = build_extractor(+ args.method,+ args.resp,+ args.subpix,+ args.desc,+ args.ori,+ args.aff,+ device,+ args.nf,+ compile_modules=args.compile,+ )+ ransac = RANSAC("homography", inl_th=2.0, max_iter=10, batch_size=8196, confidence=0.9999, seed=3407)++ first_img1 = load_gray(str(seqs[0] / "img1.png"), device)+ first_pairs = find_pairs(seqs[0])+ if first_pairs:+ first_img2 = load_gray(str(first_pairs[0][1]), device)+ for _ in range(args.warmup):+ match_pair(first_img1, first_img2, extractor, ransac)++ all_stats = []+ for seq in seqs:+ stats = eval_sequence(seq, extractor, ransac, device)+ all_stats.append(stats)+ print_sequence_table(stats, label)++ if len(all_stats) > 1:+ print_summary(all_stats, label)++ if args.speed_bench:+ bench_img = load_gray(str(seqs[0] / "img1.png"), torch.device("cpu"))+ run_speed_benchmark(extractor, bench_img)+++if __name__ == "__main__":+ main()diff --git a/docs/source/geometry.subpix.rst b/docs/source/geometry.subpix.rstindex be333206f..93cc9ffb2 100644--- a/docs/source/geometry.subpix.rst+++ b/docs/source/geometry.subpix.rst@@ -15,6 +15,37 @@ Convolutional.. autofunction:: conv_soft_argmax2d.. autofunction:: conv_soft_argmax3d.. autofunction:: conv_quad_interp3d+.. autofunction:: iterative_quad_interp3d++.. tip::++ :class:`AdaptiveQuadInterp3d` (the default subpix module in+ :class:`~kornia.feature.ScaleSpaceDetector`) automatically picks the faster+ backend based on the input device:++ * **CUDA** β :func:`conv_quad_interp3d` β batched gather+solve, 1.5β2Γ faster on GPU.+ * **CPU** β :func:`iterative_quad_interp3d` β processes only NMS maxima directly,+ no dilation overhead.++ Both backends produce numerically identical results (max difference < 2 Γ 10\ :sup:`-6`).++ .. code-block:: python++ import torch+ from kornia.geometry.subpix import AdaptiveQuadInterp3d+ from kornia.feature import ScaleSpaceDetector+ from kornia.feature.responses import BlobDoG+ from kornia.geometry.transform import ScalePyramid++ detector = ScaleSpaceDetector(+ num_features=2000,+ resp_module=BlobDoG(),+ # default β auto-selects conv on CUDA, patch on CPU:+ subpix_module=AdaptiveQuadInterp3d(strict_maxima_bonus=0.0),+ scale_pyr_module=ScalePyramid(3, 1.6, 32, double_image=True),+ scale_space_response=True,+ minima_are_also_good=True,+ )Spatial-------@@ -29,6 +60,7 @@ Non Maxima Suppression.. autofunction:: nms2d.. autofunction:: nms3d+.. autofunction:: nms3d_minmaxModule------@@ -36,6 +68,8 @@ Module.. autoclass:: SpatialSoftArgmax2d.. autoclass:: ConvSoftArgmax2d.. autoclass:: ConvSoftArgmax3d+.. autoclass:: AdaptiveQuadInterp3d.. autoclass:: ConvQuadInterp3d+.. autoclass:: IterativeQuadInterp3d.. autoclass:: NonMaximaSuppression2d.. autoclass:: NonMaximaSuppression3ddiff --git a/docs/source/geometry.transform.rst b/docs/source/geometry.transform.rstindex fd0dc7ac2..694a5547d 100644--- a/docs/source/geometry.transform.rst+++ b/docs/source/geometry.transform.rst@@ -41,7 +41,6 @@ Image 2d transforms.. autofunction:: pyrup.. autofunction:: build_pyramid.. autofunction:: build_laplacian_pyramid-.. autofunction:: upscale_doubleMatrix transformations----------------------diff --git a/kornia/feature/aliked/aliked.py b/kornia/feature/aliked/aliked.pyindex 310af37b9..f502a79f0 100644--- a/kornia/feature/aliked/aliked.py+++ b/kornia/feature/aliked/aliked.py@@ -975,6 +975,6 @@ class ALIKED(nn.Module):).to(device)url = _CHECKPOINT_URL.format(model_name)state_dict = torch.hub.load_state_dict_from_url(url, map_location=device)- model.load_state_dict(state_dict, strict=True)+ model.load_state_dict(state_dict, strict=False)model.eval()return modeldiff --git a/kornia/feature/dedode/decoder.py b/kornia/feature/dedode/decoder.pyindex 9cffa546d..4d982d815 100644--- a/kornia/feature/dedode/decoder.py+++ b/kornia/feature/dedode/decoder.py@@ -92,7 +92,6 @@ class ConvRefiner(nn.Module):for hb in range(hidden_blocks)])- self.hidden_blocks = self.hidden_blocksself.out_conv = nn.Conv2d(hidden_dim, out_dim, 1, 1, 0)self.amp = ampself.amp_dtype = amp_dtype@@ -127,6 +126,9 @@ class ConvRefiner(nn.Module):def forward(self, feats: torch.Tensor) -> torch.Tensor:_b, _c, _hs, _ws = feats.shape+ # AMP is intentionally scoped to "cuda" only: float16 autocast on CPU is not+ # supported by PyTorch and a no-op on MPS. Use amp_dtype=torch.float32 on+ # non-CUDA devices to disable AMP entirely.with torch.autocast("cuda", enabled=self.amp, dtype=self.amp_dtype):x0 = self.block1(feats)x = self.hidden_blocks(x0)diff --git a/kornia/feature/dedode/dedode.py b/kornia/feature/dedode/dedode.pyindex ae8fc3b6f..b05e8e3cc 100644--- a/kornia/feature/dedode/dedode.py+++ b/kornia/feature/dedode/dedode.py@@ -106,13 +106,12 @@ class DeDoDe(nn.Module):if apply_imagenet_normalization:images = self.normalizer(images)_B, _C, H, W = images.shape- h, w = images.shape[2:]if pad_if_not_divisible:- pd_h = 14 - h % 14 if h % 14 > 0 else 0- pd_w = 14 - w % 14 if w % 14 > 0 else 0+ pd_h = 14 - H % 14 if H % 14 > 0 else 0+ pd_w = 14 - W % 14 if W % 14 > 0 else 0images = F.pad(images, (0, pd_w, 0, pd_h), value=0.0)- keypoints, scores = self.detect(images, n=n, apply_imagenet_normalization=False, crop_h=h, crop_w=w)- descriptions = self.describe(images, keypoints, apply_imagenet_normalization=False, crop_h=h, crop_w=w)+ keypoints, scores = self.detect(images, n=n, apply_imagenet_normalization=False, crop_h=H, crop_w=W)+ descriptions = self.describe(images, keypoints, apply_imagenet_normalization=False, crop_h=H, crop_w=W)return dedode_denormalize_pixel_coordinates(keypoints, H, W), scores, descriptions@torch.inference_mode()@@ -127,6 +126,11 @@ class DeDoDe(nn.Module):) -> Tuple[torch.Tensor, torch.Tensor]:"""Detect keypoints in the input images.+ .. note::+ This method unconditionally sets the model to eval mode via ``self.train(False)``+ so that BatchNorm and Dropout behave deterministically. This is intentional: the+ detector is only used at inference time and its statistics must be frozen.+Args:images: A torch.Tensor of shape :math:`(B, 3, H, W)` containing the input images.n: The number of keypoints to detect.@@ -167,15 +171,23 @@ class DeDoDe(nn.Module):images: torch.Tensor,keypoints: Optional[torch.Tensor] = None,apply_imagenet_normalization: bool = True,+ pad_if_not_divisible: bool = True,crop_h: Optional[int] = None,crop_w: Optional[int] = None,) -> torch.Tensor:"""Describe keypoints in the input images. If keypoints are not provided, returns the dense descriptors.+ .. note::+ This method unconditionally sets the model to eval mode via ``self.train(False)``+ so that BatchNorm and Dropout behave deterministically. This is intentional: the+ descriptor is only used at inference time and its statistics must be frozen.+Args:images: A torch.Tensor of shape :math:`(B, 3, H, W)` containing the input images.keypoints: An optional torch.Tensor of shape :math:`(B, N, 2)` containing the detected keypoints.apply_imagenet_normalization: Whether to apply ImageNet normalization to the input images.+ pad_if_not_divisible: Zero-pad the image so H and W are divisible by 14. Required when+ using the ``G`` descriptor backed by DINOv2 (patch size 14). Ignored for ``B``.crop_h: The height of the crop to be used for description. If None, the full image is used.crop_w: The width of the crop to be used for description. If None, the full image is used.@@ -191,6 +203,10 @@ class DeDoDe(nn.Module):KORNIA_CHECK_SHAPE(keypoints, ["B", "N", "2"])if apply_imagenet_normalization:images = self.normalizer(images)+ if pad_if_not_divisible:+ pd_h = 14 - H % 14 if H % 14 > 0 else 0+ pd_w = 14 - W % 14 if W % 14 > 0 else 0+ images = F.pad(images, (0, pd_w, 0, pd_h), value=0.0)self.train(False)descriptions = self.descriptor.forward(images)if crop_h is not None and crop_w is not None:@@ -217,8 +233,8 @@ class DeDoDe(nn.Module):detector_weights: The weights to load for the detector.One of 'L-upright' (original paper, https://arxiv.org/abs/2308.08479),'L-C4', 'L-SO2' (from steerers, better for rotations, https://arxiv.org/abs/2312.02152),- 'L-C4-v2' (from dedode v2, better at rotations, less clustering, https://arxiv.org/abs/2404.08928)- Default is 'L-C4-v2', but perhaps it should be 'L-C4-v2'?+ 'L-C4-v2' (from dedode v2, better at rotations, less clustering, https://arxiv.org/abs/2404.08928).+ Default is 'L-C4-v2'.descriptor_weights: The weights to load for the descriptor.One of 'B-upright','G-upright' (original paper, https://arxiv.org/abs/2308.08479),'B-C4', 'B-SO2', 'G-C4', 'G-SO2' (from steerers, better for rotations, https://arxiv.org/abs/2312.02152).@@ -230,6 +246,9 @@ class DeDoDe(nn.Module):The pretrained model."""+ # The model architecture kind is encoded as the first character of the weight name,+ # e.g. "L-C4-v2" -> "L", "G-upright" -> "G". All current checkpoints follow this+ # convention intentionally so that new variants only need a new URL entry.model: DeDoDe = cls(detector_model=detector_weights[0], # type: ignore[arg-type]descriptor_model=descriptor_weights[0], # type: ignore[arg-type]diff --git a/kornia/feature/dedode/encoder.py b/kornia/feature/dedode/encoder.pyindex c9f2b8006..9aa0d3c5d 100644--- a/kornia/feature/dedode/encoder.py+++ b/kornia/feature/dedode/encoder.py@@ -39,6 +39,9 @@ class VGG19(nn.Module):self.amp_dtype = amp_dtypedef forward(self, x: torch.Tensor, **kwargs): # type: ignore[no-untyped-def]+ # AMP is intentionally scoped to "cuda" only: float16 autocast on CPU is not+ # supported by PyTorch and a no-op on MPS. Use amp_dtype=torch.float32 on+ # non-CUDA devices to disable AMP entirely.with torch.autocast("cuda", enabled=self.amp, dtype=self.amp_dtype):feats = []sizes = []diff --git a/kornia/feature/dedode/utils.py b/kornia/feature/dedode/utils.pyindex 5608e65f3..3708469a5 100644--- a/kornia/feature/dedode/utils.py+++ b/kornia/feature/dedode/utils.py@@ -39,8 +39,9 @@ def sample_keypoints(local_density = F.conv2d(local_density_x, weights[..., None], padding=(51 // 2, 0))[:, 0]scoremap = scoremap * (local_density + 1e-8) ** (-1 / 2)grid = get_grid(B, H, W, device=device).reshape(B, H * W, 2)- inds = torch.topk(scoremap.reshape(B, H * W), k=num_samples).indices # type: ignore- kps = torch.gather(grid, dim=1, index=inds[..., None].expand(B, num_samples, 2)) # type: ignore+ num_samples = min(num_samples, H * W) if num_samples is not None else H * W # type: ignore+ inds = torch.topk(scoremap.reshape(B, H * W), k=num_samples).indices+ kps = torch.gather(grid, dim=1, index=inds[..., None].expand(B, num_samples, 2))if return_scoremap:return kps, torch.gather(scoremap.reshape(B, H * W), dim=1, index=inds)return kpsdiff --git a/kornia/feature/disk/_unets/blocks.py b/kornia/feature/disk/_unets/blocks.pyindex a4a1530dd..42cb847ea 100644--- a/kornia/feature/disk/_unets/blocks.py+++ b/kornia/feature/disk/_unets/blocks.py@@ -17,8 +17,6 @@from __future__ import annotations-from typing import Any-import torchimport torch.nn.functional as Ffrom torch import nn@@ -53,7 +51,7 @@ class Conv(nn.Sequential):class ThinUnetDownBlock(nn.Sequential):- def __init__(self, in_: int, out_: int, size: int = 5, is_first: bool = False, setup: Any = None) -> None:+ def __init__(self, in_: int, out_: int, size: int = 5, is_first: bool = False) -> None:self.in_ = in_self.out_ = out_@@ -69,7 +67,7 @@ class ThinUnetDownBlock(nn.Sequential):class ThinUnetUpBlock(nn.Module):- def __init__(self, bottom_: int, horizontal_: int, out_: int, size: int = 5, setup: Any = None) -> None:+ def __init__(self, bottom_: int, horizontal_: int, out_: int, size: int = 5) -> None:super().__init__()self.bottom_ = bottom_diff --git a/kornia/feature/disk/detector.py b/kornia/feature/disk/detector.pyindex ab7340d50..206bb14d3 100644--- a/kornia/feature/disk/detector.py+++ b/kornia/feature/disk/detector.py@@ -17,37 +17,20 @@from __future__ import annotations-from typing import Optional-import torch-import torch.nn.functional as F--from .structs import Keypoints--def nms(signal: torch.Tensor, window_size: int = 5, cutoff: float = 0.0) -> torch.Tensor:- """Apply non-maximum suppression."""- if window_size % 2 != 1:- raise ValueError(f"window_size has to be odd, got {window_size}")+from kornia.geometry.subpix import nms2d- _, ixs = F.max_pool2d(signal, kernel_size=window_size, stride=1, padding=window_size // 2, return_indices=True)-- h, w = signal.shape[1:]- coords = torch.arange(h * w, device=signal.device).reshape(1, h, w)- nms = ixs == coords-- if cutoff is None:- return nms- else:- return nms & (signal > cutoff)+from .structs import Keypointsdef heatmap_to_keypoints(- heatmap: torch.Tensor, n: Optional[int] = None, window_size: int = 5, score_threshold: float = 0.0+ heatmap: torch.Tensor, n: int | None = None, window_size: int = 5, score_threshold: float = 0.0) -> list[Keypoints]:"""Inference-time nms-based detection protocol."""heatmap = heatmap.squeeze(1)- nmsed = nms(heatmap, window_size=window_size, cutoff=score_threshold)+ nms_mask = nms2d(heatmap.unsqueeze(1), (window_size, window_size), mask_only=True).squeeze(1)+ nmsed = nms_mask & (heatmap > score_threshold)keypoints = []for b in range(heatmap.shape[0]):diff --git a/kornia/feature/disk/disk.py b/kornia/feature/disk/disk.pyindex 74dc76334..06da385a8 100644--- a/kornia/feature/disk/disk.py+++ b/kornia/feature/disk/disk.py@@ -17,8 +17,6 @@from __future__ import annotations-from typing import Optional-import torchimport torch.nn.functional as Ffrom torch import nn@@ -88,7 +86,7 @@ class DISK(nn.Module):def forward(self,images: torch.Tensor,- n: Optional[int] = None,+ n: int | None = None,window_size: int = 5,score_threshold: float = 0.0,pad_if_not_divisible: bool = False,@@ -128,7 +126,7 @@ class DISK(nn.Module):return features@classmethod- def from_pretrained(cls, checkpoint: str = "depth", device: Optional[torch.device] = None) -> DISK:+ def from_pretrained(cls, checkpoint: str = "depth", device: torch.device | None = None) -> DISK:r"""Load a pretrained model.Depth model was trained using depth map supervision and is slightly more precise but biased to detect keypointsdiff --git a/kornia/feature/disk/structs.py b/kornia/feature/disk/structs.pyindex 662095f10..76b5f44b0 100644--- a/kornia/feature/disk/structs.py+++ b/kornia/feature/disk/structs.py@@ -98,4 +98,4 @@ class Keypoints:desc = descriptors[:, y, x].Tdesc = F.normalize(desc, dim=-1)- return DISKFeatures(self.xys.to(dtype), desc, self.detection_logp)+ return DISKFeatures(self.xys.to(dtype), desc, self.detection_logp.to(dtype))diff --git a/kornia/feature/integrated.py b/kornia/feature/integrated.pyindex fd0062d95..962448bcc 100644--- a/kornia/feature/integrated.py+++ b/kornia/feature/integrated.py@@ -189,6 +189,8 @@ class SIFTFeature(LocalFeature):rootsift: bool = True,device: Union[None, str, torch.device] = None,config: Optional[Detector_config] = None,+ compile_model: bool = False,+ score_threshold: float = 0.0,) -> None:patch_size: int = 41if device is None:@@ -201,6 +203,8 @@ class SIFTFeature(LocalFeature):config,ori_module=PassLAF() if upright 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@@ -222,6 +226,7 @@ class SIFTFeatureScaleSpace(LocalFeature):upright: bool = False,rootsift: bool = True,device: Union[None, str, torch.device] = None,+ compile_modules: Union[bool, List[str]] = False,) -> None:if device is None:device = torch.device("cpu")@@ -229,12 +234,13 @@ class SIFTFeatureScaleSpace(LocalFeature):detector = ScaleSpaceDetector(num_features,resp_module=BlobDoG(),- nms_module=ConvQuadInterp3d(10),+ 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@@ -250,43 +256,47 @@ class GFTTAffNetHardNet(LocalFeature):num_features: int = 8000,upright: bool = False,device: Union[None, str, torch.device] = None,- config: Optional[Detector_config] = None,+ compile_modules: Union[bool, List[str]] = False,) -> None:if device is None:device = torch.device("cpu")- if config is None:- config = get_default_detector_config()- detector = MultiResolutionDetector(- CornerGFTT(),+ detector = ScaleSpaceDetector(num_features,- config,+ resp_module=CornerGFTT(),+ scale_pyr_module=ScalePyramid(3, 1.6, 32, double_image=True),ori_module=PassLAF() if upright else LAFOrienter(19),aff_module=LAFAffNetShapeEstimator(True, preserve_orientation=False).eval(),+ scale_space_response=False,+ minima_are_also_good=False,+ mr_size=6.0,+ compile_modules=compile_modules,).to(device)descriptor = LAFDescriptor(None, patch_size=32, grayscale_descriptor=True).to(device)super().__init__(detector, descriptor)class HesAffNetHardNet(LocalFeature):- """Convenience module, which implements GFTT detector + AffNet-HardNet descriptor."""+ """Convenience module, which implements Hessian detector + AffNet-HardNet descriptor."""def __init__(self,num_features: int = 2048,upright: bool = False,device: Union[None, str, torch.device] = None,- config: Optional[Detector_config] = None,+ compile_modules: Union[bool, List[str]] = False,) -> None:if device is None:device = torch.device("cpu")- if config is None:- config = get_default_detector_config()- detector = MultiResolutionDetector(- BlobHessian(),+ detector = ScaleSpaceDetector(num_features,- config,+ resp_module=BlobHessian(),+ scale_pyr_module=ScalePyramid(3, 1.6, 32, double_image=True),ori_module=PassLAF() if upright else LAFOrienter(19),aff_module=LAFAffNetShapeEstimator(True, preserve_orientation=False).eval(),+ scale_space_response=False,+ minima_are_also_good=False,+ mr_size=6.0,+ compile_modules=compile_modules,).to(device)descriptor = LAFDescriptor(None, patch_size=32, grayscale_descriptor=True).to(device)super().__init__(detector, descriptor)@@ -301,11 +311,19 @@ class KeyNetHardNet(LocalFeature):upright: bool = False,device: Union[None, str, torch.device] = None,scale_laf: float = 1.0,+ compile_model: bool = False,+ score_threshold: float = 0.0,) -> None:if device is None:device = torch.device("cpu")ori_module = PassLAF() if upright else LAFOrienter(angle_detector=OriNet(True))- detector = KeyNetDetector(True, num_features=num_features, ori_module=ori_module).to(device)+ detector = KeyNetDetector(+ True,+ num_features=num_features,+ ori_module=ori_module,+ compile_model=compile_model,+ score_threshold=score_threshold,+ ).to(device)descriptor = LAFDescriptor(None, patch_size=32, grayscale_descriptor=True).to(device)super().__init__(detector, descriptor, scale_laf)@@ -322,6 +340,8 @@ class KeyNetAffNetHardNet(LocalFeature):upright: bool = False,device: Union[None, str, torch.device] = None,scale_laf: float = 1.0,+ compile_model: bool = False,+ score_threshold: float = 0.0,) -> None:if device is None:device = torch.device("cpu")@@ -331,6 +351,8 @@ class KeyNetAffNetHardNet(LocalFeature):num_features=num_features,ori_module=ori_module,aff_module=LAFAffNetShapeEstimator(True, preserve_orientation=False).eval(),+ compile_model=compile_model,+ score_threshold=score_threshold,).to(device)descriptor = LAFDescriptor(None, patch_size=32, grayscale_descriptor=True).to(device)super().__init__(detector, descriptor, scale_laf)diff --git a/kornia/feature/keynet.py b/kornia/feature/keynet.pyindex c70c285d3..5a4f5c7a5 100644--- a/kornia/feature/keynet.py+++ b/kornia/feature/keynet.py@@ -86,10 +86,10 @@ class _HandcraftedBlock(nn.Module):sobel_dx = self.spatial_gradient(dx)dxx, dxy = sobel_dx[:, :, 0, :, :], sobel_dx[:, :, 1, :, :]- sobel_dy = self.spatial_gradient(dy)- dyy = sobel_dy[:, :, 1, :, :]+ # Only dyy is used from sobel_dy; dyx is discarded.+ dyy = self.spatial_gradient(dy)[:, :, 1, :, :]- hc_feats = torch.cat([dx, dy, dx**2.0, dy**2.0, dx * dy, dxy, dxy**2.0, dxx, dyy, dxx * dyy], 1)+ hc_feats = torch.cat([dx, dy, dx.square(), dy.square(), dx * dy, dxy, dxy.square(), dxx, dyy, dxx * dyy], 1)return hc_feats@@ -153,8 +153,10 @@ class KeyNet(nn.Module):"""- def __init__(self, pretrained: bool = False, keynet_conf: KeyNet_conf = keynet_default_config) -> None:+ def __init__(self, pretrained: bool = False, keynet_conf: Optional[KeyNet_conf] = None) -> None:super().__init__()+ if keynet_conf is None:+ keynet_conf = keynet_default_confignum_filters = keynet_conf["num_filters"]self.num_levels = keynet_conf["num_levels"]@@ -176,12 +178,12 @@ class KeyNet(nn.Module):def forward(self, x: torch.Tensor) -> torch.Tensor:"""X - input image."""- shape_im = x.shape+ h, w = x.shape[2], x.shape[3]feats: List[torch.Tensor] = [self.feature_extractor(x)]for _ in range(1, self.num_levels):x = pyrdown(x, factor=1.2)feats_i = self.feature_extractor(x)- feats_i = F.interpolate(feats_i, size=(shape_im[2], shape_im[3]), mode="bilinear")+ feats_i = F.interpolate(feats_i, size=(h, w), mode="bilinear", align_corners=False)feats.append(feats_i)scores = self.last_conv(torch.cat(feats, 1))return scores@@ -211,9 +213,15 @@ class KeyNetDetector(MultiResolutionDetector):self,pretrained: bool = False,num_features: int = 2048,- keynet_conf: KeyNet_conf = keynet_default_config,+ keynet_conf: Optional[KeyNet_conf] = None,ori_module: Optional[nn.Module] = None,aff_module: Optional[nn.Module] = None,+ compile_model: bool = False,+ score_threshold: float = 0.0,) -> None:+ if keynet_conf is None:+ keynet_conf = keynet_default_configmodel = KeyNet(pretrained, keynet_conf)- super().__init__(model, num_features, keynet_conf["Detector_conf"], ori_module, aff_module)+ super().__init__(+ model, num_features, keynet_conf["Detector_conf"], ori_module, aff_module, compile_model, score_threshold+ )diff --git a/kornia/feature/laf.py b/kornia/feature/laf.pyindex a8290efb4..5dc700a99 100644--- a/kornia/feature/laf.py+++ b/kornia/feature/laf.py@@ -463,30 +463,28 @@ def extract_patches_from_pyramid(B, N, _, _ = laf.size()_, ch, h, w = img.size()scale = 2.0 * get_laf_scale(denormalize_laf(nlaf, img)) / float(PS)- max_level = min(img.size(2), img.size(3)) // PS- pyr_idx = scale.log2().clamp(min=0.0, max=max(0, max_level - 1)).long()+ # max_level is a compile-time constant for static image shapes.+ max_level = min(h, w) // PS+ pyr_idx = scale.log2().clamp(min=0.0, max=max(0, max_level - 1)).long() # (B, N, 1, 1)+ out = torch.zeros(B, N, ch, PS, PS, dtype=nlaf.dtype, device=nlaf.device)cur_img = img- cur_pyr_level = 0- out = torch.zeros(B, N, ch, PS, PS).to(nlaf.dtype).to(nlaf.device)- we_are_in_business = True- while we_are_in_business:- _, ch, h, w = cur_img.size()- # for loop temporarily, to be refactored+ # Always run at least level 0; max_level is a compile-time constant for static shapes.+ num_levels = max(1, max_level)+ for cur_pyr_level in range(num_levels):+ _, ch_l, h_l, w_l = cur_img.size()for i in range(B):- scale_mask = (pyr_idx[i] == cur_pyr_level).squeeze()- if (scale_mask.float().sum().item()) == 0:- continue- scale_mask = (scale_mask > 0).view(-1)- grid = generate_patch_grid_from_normalized_LAF(cur_img[i : i + 1], nlaf[i : i + 1, scale_mask, :, :], PS)+ # torch.where avoids nonzero/data-dependent shapes β fully compilable.+ level_mask = (pyr_idx[i] == cur_pyr_level).view(N, 1, 1, 1)+ grid = generate_patch_grid_from_normalized_LAF(cur_img[i : i + 1], nlaf[i : i + 1], PS)patches = F.grid_sample(- cur_img[i : i + 1].expand(grid.shape[0], ch, h, w), grid, padding_mode="border", align_corners=False+ cur_img[i : i + 1].expand(N, ch_l, h_l, w_l), grid, padding_mode="border", align_corners=False)- out[i].masked_scatter_(scale_mask.view(-1, 1, 1, 1), patches.to(nlaf.dtype))- we_are_in_business = min(cur_img.size(2), cur_img.size(3)) >= PS- if not we_are_in_business:- break- cur_img = pyrdown(cur_img)- cur_pyr_level += 1+ out[i] = torch.where(level_mask, patches.to(nlaf.dtype), out[i])+ if cur_pyr_level < num_levels - 1:+ cur_img = pyrdown(cur_img)+ # Stop early if the pyramided image is too small for further levels.+ if min(cur_img.size(2), cur_img.size(3)) < PS:+ breakreturn outdiff --git a/kornia/feature/scale_space_detector.py b/kornia/feature/scale_space_detector.pyindex c34068ffa..3f2489b12 100644--- a/kornia/feature/scale_space_detector.py+++ b/kornia/feature/scale_space_detector.py@@ -24,42 +24,46 @@ from torch import nnfrom typing_extensions import TypedDictfrom kornia.core.check import KORNIA_CHECK_SHAPE-from kornia.geometry.subpix import ConvSoftArgmax3d, NonMaximaSuppression2d+from kornia.geometry.subpix import (+ AdaptiveQuadInterp3d,+ ConvQuadInterp3d,+ IterativeQuadInterp3d,+ NonMaximaSuppression2d,+ nms3d_minmax,+)from kornia.geometry.transform import ScalePyramid, pyrdown, resize-from .laf import laf_from_center_scale_ori, laf_is_inside_image+from .laf import laf_from_center_scale_orifrom .orientation import PassLAFfrom .responses import BlobHessian+# Max |sin| among the 11 boundary points sampled by laf_to_boundary_points(n_pts=12):+# angles = linspace(0, 2Ο, 11) β k * 2Ο/11 for k=0..10+# max|sin| at k=3: sin(6Ο/11) β 0.9898; max|cos| at k=0: cos(0) = 1.0+# Used to inline the boundary check in _process_octave for isotropic LAFs (rotmat=eye(2)),+# avoiding CPUβGPU allocation + bmm every octave.+_MAX_ABS_SIN_12: float = math.sin(3 * 2 * math.pi / 11) # β 0.9898+def _scale_index_to_scale(max_coords: torch.Tensor, sigmas: torch.Tensor, num_levels: int) -> torch.Tensor:r"""Auxiliary function for ScaleSpaceDetector.- Converts scale level index from ConvSoftArgmax3d to the actual+ Converts scale level index from the subpix module to the actualscale, using the sigmas from the ScalePyramid output.Args:max_coords: torch.Tensor [BxNx3].- sigmas: torch.Tensor [BxNxD], D >= 1+ sigmas: torch.Tensor [BxD], D >= 1num_levels: number of levels in the scale index.Returns:torch.Tensor [BxNx3]."""- # depth (scale) in coord_max is represented as (float) index, not the scale yet.- # we will interpolate the scale using pytorch.grid_sample function- # Because grid_sample is for 4d input only, we will create fake 2nd dimension- # ToDo: replace with 3d input, when grid_sample will start to support it-- # Reshape for grid shape- B, N, _ = max_coords.shape- scale_coords = max_coords[:, :, 0].contiguous().view(-1, 1, 1, 1)- # Replace the scale_x_y- out = torch.cat(- [sigmas[0, 0] * torch.pow(2.0, scale_coords / float(num_levels)).view(B, N, 1), max_coords[:, :, 1:]], 2- )- return out+ B = max_coords.shape[0]+ base_sigma = sigmas[:, 0].view(B, 1, 1) # (B, 1, 1) β per-batch base sigma+ max_coords[:, :, 0:1] = base_sigma * torch.pow(2.0, max_coords[:, :, 0:1] / float(num_levels))+ return max_coordsdef _create_octave_mask(mask: torch.Tensor, octave_shape: List[int]) -> torch.Tensor:@@ -76,8 +80,8 @@ class ScaleSpaceDetector(nn.Module):like Harris, Hessian-Affine or SIFT (DoG).It has 5 modules inside: scale pyramid generator, response ("cornerness") function,- soft nms function, affine shape estimator and patch orientation estimator.- Each of those modules could be replaced with learned custom one, as long, as+ sub-pixel localization, affine shape estimator and patch orientation estimator.+ Each of those modules could be replaced with a learned custom one, as long asthey respect output shape.Args:@@ -86,16 +90,22 @@ class ScaleSpaceDetector(nn.Module):mr_size: multiplier for local feature scale compared to the detection scale.6.0 is matching OpenCV 12.0 convention for SIFT.scale_pyr_module: generates scale pyramid. See :class:`~kornia.geometry.ScalePyramid` for details.- Default: ScalePyramid(3, 1.6, 10).+ Default: ScalePyramid(3, 1.6, 15).resp_module: calculates ``'cornerness'`` of the pixel.- nms_module: outputs per-patch coordinates of the response maxima.- See :class:`~kornia.geometry.ConvSoftArgmax3d` for details.+ subpix_module: performs non-maximum suppression and refines keypoint location to sub-pixel /+ sub-scale accuracy. See :class:`~kornia.geometry.subpix.ConvQuadInterp3d` for details.ori_module: for local feature orientation estimation. Default:class:`~kornia.feature.PassLAF`,which does nothing. See :class:`~kornia.feature.LAFOrienter` for details.aff_module: for local feature affine shape estimation. Default: :class:`~kornia.feature.PassLAF`,which does nothing. See :class:`~kornia.feature.LAFAffineShapeEstimator` for details.- minima_are_also_good: if True, then both response function minima and maxima are detected- Useful for symmetric response functions like DoG or Hessian. Default is False+ minima_are_also_good: if True, then both response function minima and maxima are detected.+ Useful for symmetric response functions like DoG or Hessian. Default is False.+ compile_modules: selects which sub-modules to wrap with :func:`torch.compile`.+ Pass ``True`` to compile every sub-module, ``False`` (default) for none, or a list+ containing any subset of ``["scale_pyr", "resp", "subpix", "ori", "aff"]``.+ Compiling ``subpix`` gives ~5x GPU speedup for the default+ :class:`~kornia.geometry.subpix.ConvQuadInterp3d` backend by fusing its iteration loop.+ The first call incurs a one-time compilation cost; subsequent calls are fast."""@@ -105,32 +115,58 @@ class ScaleSpaceDetector(nn.Module):mr_size: float = 6.0,scale_pyr_module: Optional[nn.Module] = None,resp_module: Optional[nn.Module] = None,- nms_module: Optional[nn.Module] = None,+ subpix_module: Optional[nn.Module] = None,ori_module: Optional[nn.Module] = None,aff_module: Optional[nn.Module] = None,minima_are_also_good: bool = False,scale_space_response: bool = False,+ compile_modules: Union[bool, List[str]] = False,) -> None:super().__init__()self.mr_size = mr_sizeself.num_features = num_features++ _all_names = {"scale_pyr", "resp", "subpix", "ori", "aff"}+ if compile_modules is True:+ _compile_set = _all_names+ elif compile_modules is False:+ _compile_set = set()+ else:+ _compile_set = set(compile_modules)+ unknown = _compile_set - _all_names+ if unknown:+ raise ValueError(f"Unknown module names in compile_modules: {unknown}. Valid: {_all_names}")++ if _compile_set:+ # Allow torch.compile to keep data-dependent shape ops (torch.where / nonzero)+ # inside the compiled graph as unbacked symbols, avoiding graph breaks and the+ # 0/1-specialization recompilations that would otherwise fire whenever an octave+ # first encounters zero NMS maxima (blurry/extreme-viewpoint images).+ torch._dynamo.config.capture_dynamic_output_shape_ops = True++ def _maybe_compile(mod: nn.Module, name: str) -> nn.Module:+ return torch.compile(mod, dynamic=True) if name in _compile_set else mod+if scale_pyr_module is None:- scale_pyr_module = ScalePyramid(3, 1.6, 15)- self.scale_pyr = scale_pyr_module+ extra_levels = 3 if scale_space_response else 2+ scale_pyr_module = ScalePyramid(3, 1.6, 16, extra_levels=extra_levels)+ self.scale_pyr = _maybe_compile(scale_pyr_module, "scale_pyr")if resp_module is None:resp_module = BlobHessian()- self.resp = resp_module- if nms_module is None:- nms_module = ConvSoftArgmax3d(- (3, 3, 3), (1, 1, 1), (1, 1, 1), normalized_coordinates=False, output_value=True- )- self.nms = nms_module+ self.resp = _maybe_compile(resp_module, "resp")+ if subpix_module is None:+ subpix_module = AdaptiveQuadInterp3d(strict_maxima_bonus=0.0, allow_scale_steps=True)+ # Record before torch.compile wraps the module β isinstance won't match OptimizedModule.+ self._is_iterative_subpix: bool = isinstance(+ subpix_module, (ConvQuadInterp3d, AdaptiveQuadInterp3d, IterativeQuadInterp3d)+ )+ self.subpix = _maybe_compile(subpix_module, "subpix")if ori_module is None:ori_module = PassLAF()- self.ori = ori_module+ self.ori = _maybe_compile(ori_module, "ori")if aff_module is None:aff_module = PassLAF()- self.aff = aff_module+ self.aff = _maybe_compile(aff_module, "aff")self.minima_are_also_good = minima_are_also_good# scale_space_response should be True if the response function works on scale space# like Difference-of-Gaussians@@ -143,103 +179,184 @@ class ScaleSpaceDetector(nn.Module):f"mr_size={self.mr_size}, "f"scale_pyr={self.scale_pyr.__repr__()}, "f"resp={self.resp.__repr__()}, "- f"nms={self.nms.__repr__()}, "+ f"subpix={self.subpix.__repr__()}, "f"ori={self.ori.__repr__()}, "f"aff={self.aff.__repr__()})")+ def _process_octave(+ self,+ octave: torch.Tensor,+ sigmas_oct: torch.Tensor,+ num_feats: int,+ mask: Optional[torch.Tensor],+ rotmat: torch.Tensor,+ num_levels: int,+ is_iterative_subpix: bool,+ px_size: float,+ ) -> Tuple[torch.Tensor, torch.Tensor]:+ """Process one scale-space octave: response β NMS/subpix β top-K β LAF."""+ dev = octave.device+ dtype = octave.dtype+ B, CH, L, H, W = octave.size()++ # Run response function+ if self.scale_space_response:+ oct_resp = self.resp(octave, sigmas_oct.view(-1)) # (B, C, Ldog, H, W)+ else:+ oct_resp = self.resp(octave.permute(0, 2, 1, 3, 4).reshape(B * L, CH, H, W), sigmas_oct.view(-1)).view(+ B, L, CH, H, W+ )+ # Reorder to (B, CH, L, H, W) for scale-space NMS+ oct_resp = oct_resp.permute(0, 2, 1, 3, 4)+ scale_sigmas = sigmas_oct[:, : oct_resp.shape[2]]++ if mask is not None:+ oct_mask: torch.Tensor = _create_octave_mask(mask, oct_resp.shape)+ oct_resp = oct_mask * oct_resp++ # Always precompute NMS masks in one fused pass.+ # - For minima_are_also_good: both masks are needed anyway.+ # - Otherwise: max_nms_mask is passed to subpix (skips its internal NMS on GPU)+ # and drives the sparse top-K below.+ max_nms_mask: torch.Tensor+ min_nms_mask: torch.Tensor+ max_nms_mask, min_nms_mask = nms3d_minmax(oct_resp)++ if self.minima_are_also_good:+ if is_iterative_subpix:+ coord_max, response_max = self.subpix(oct_resp, precomputed_nms_mask=max_nms_mask)+ coord_min, response_min = self.subpix(-oct_resp, precomputed_nms_mask=min_nms_mask)+ else:+ coord_max, response_max = self.subpix(oct_resp)+ coord_min, response_min = self.subpix(-oct_resp)+ elif is_iterative_subpix:+ coord_max, response_max = self.subpix(oct_resp, precomputed_nms_mask=max_nms_mask)+ else:+ coord_max, response_max = self.subpix(oct_resp)++ # Zero responses at scale border levels so they never reach top-K.+ # (nms3d_minmax already sets the masks False at these positions.)+ response_max[:, :, 0] = 0.0+ response_max[:, :, -1] = 0.0++ if self.minima_are_also_good:+ response_min[:, :, 0] = 0.0+ response_min[:, :, -1] = 0.0+ take_min_mask = (response_min > response_max) & min_nms_mask+ response_max = torch.where(take_min_mask, response_min, response_max)+ coord_max = torch.where(take_min_mask.unsqueeze(2), coord_min, coord_max)+ # Candidate positions: original max-NMS plus swapped min-NMS positions.+ cand_mask = max_nms_mask | take_min_mask+ else:+ cand_mask = max_nms_mask++ # Sparse top-K: gather the small set of NMS candidates first, then run top-K+ # on that (~few-thousand) set instead of the full CHxLxHxW volume (~millions).+ # nms3d_minmax guarantees cand_mask is False at scale border levels already.+ mask_flat = cand_mask.view(B, -1) # (B, L*H*W)+ resp_flat = response_max.view(B, -1) # (B, L*H*W)+ coord_flat = coord_max.view(B, 3, -1).permute(0, 2, 1) # (B, L*H*W, 3)++ if B == 1:+ nms_idx = mask_flat[0].nonzero(as_tuple=True)[0] # (M,)+ resp_cands = resp_flat[0][nms_idx] # (M,)+ coord_cands = coord_flat[0][nms_idx] # (M, 3)+ k_eff = min(num_feats, nms_idx.shape[0])+ if k_eff > 0:+ resp_flat_best, local_idx = torch.topk(resp_cands, k=k_eff)+ max_coords_best = coord_cands[local_idx].unsqueeze(0) # (1, k_eff, 3)+ resp_flat_best = resp_flat_best.unsqueeze(0) # (1, k_eff)+ else:+ resp_flat_best = resp_flat.new_zeros(1, 0)+ max_coords_best = coord_flat.new_zeros(1, 0, 3)+ else:+ # Batched fallback: mask non-candidates to -inf so they lose top-K.+ fill = torch.finfo(dtype).min / 2+ resp_masked = resp_flat.masked_fill(~mask_flat, fill)+ k_eff = min(num_feats, resp_masked.size(1))+ resp_flat_best, idxs = torch.topk(resp_masked, k=k_eff, dim=1)+ max_coords_best = torch.gather(coord_flat, 1, idxs.unsqueeze(-1).expand(-1, -1, 3))++ B, N = resp_flat_best.size()++ max_coords_best = _scale_index_to_scale(max_coords_best, scale_sigmas, num_levels)++ current_lafs = torch.cat(+ [+ self.mr_size * max_coords_best[:, :, 0].view(B, N, 1, 1) * rotmat,+ max_coords_best[:, :, 1:3].view(B, N, 2, 1),+ ],+ 3,+ )++ # Inline equivalent of laf_is_inside_image(scale_laf(current_lafs, 0.5), octave[:, 0], 5)+ # for isotropic LAFs (rotmat = eye(2)). Avoids: scale_laf (torch.cat), and+ # laf_to_boundary_points (linspace/sin/cos allocations + CPUβGPU transfer + bmm).+ # For the axis-aligned isotropic case the 12-pt boundary check reduces to:+ # max x-extent = max|sin| * half_s; max y-extent = max|cos| * half_s = half_s+ half_s = current_lafs[:, :, 0, 0] * 0.5+ cx = current_lafs[:, :, 0, 2]+ cy = current_lafs[:, :, 1, 2]+ h, w = octave.shape[3], octave.shape[4]+ good_mask = (+ (cx - half_s * _MAX_ABS_SIN_12 >= 5)+ & (cx + half_s * _MAX_ABS_SIN_12 <= w - 5)+ & (cy - half_s >= 5)+ & (cy + half_s <= h - 5)+ )+ resp_flat_best = resp_flat_best * good_mask.to(dev, dtype)+ current_lafs.mul_(px_size)+ return resp_flat_best, current_lafs+def detect(self, img: torch.Tensor, num_feats: int, mask: Optional[torch.Tensor] = None) -> Tuple[torch.Tensor, torch.Tensor]:- dev: Union[str, torch.device, None] = img.device+ dev = img.devicedtype: torch.dtype = img.dtype- sigmas: List[torch.Tensor]sp, sigmas, _ = self.scale_pyr(img)- all_responses: List[torch.Tensor] = []- all_lafs: List[torch.Tensor] = []- px_size = 0.5 if self.scale_pyr.double_image else 1.0- for oct_idx, octave in enumerate(sp):- sigmas_oct = sigmas[oct_idx]- B, CH, L, H, W = octave.size()- # Run response function- if self.scale_space_response:- oct_resp = self.resp(octave, sigmas_oct.view(-1))- else:- oct_resp = self.resp(octave.permute(0, 2, 1, 3, 4).reshape(B * L, CH, H, W), sigmas_oct.view(-1)).view(- B, L, CH, H, W- )- # We want nms for scale responses, so reorder to (B, CH, L, H, W)- oct_resp = oct_resp.permute(0, 2, 1, 3, 4)- # 3rd extra level is required for DoG only- if isinstance(self.scale_pyr.extra_levels, torch.Tensor) and self.scale_pyr.extra_levels % 2 != 0:- oct_resp = oct_resp[:, :, :-1]-- if mask is not None:- oct_mask: torch.Tensor = _create_octave_mask(mask, oct_resp.shape)- oct_resp = oct_mask * oct_resp-- # Differentiable nms- coord_max: torch.Tensor- response_max: torch.Tensor- coord_max, response_max = self.nms(oct_resp)- if self.minima_are_also_good:- coord_min, response_min = self.nms(-oct_resp)- take_min_mask = (response_min > response_max).to(response_max.dtype)- response_max = response_min * take_min_mask + (1 - take_min_mask) * response_max- coord_max = coord_min * take_min_mask.unsqueeze(2) + (1 - take_min_mask.unsqueeze(2)) * coord_max-- # Now, lets crop out some small responses- responses_flatten = response_max.view(response_max.size(0), -1) # [B, N]- max_coords_flatten = coord_max.view(response_max.size(0), 3, -1).permute(0, 2, 1) # [B, N, 3]-- if responses_flatten.size(1) > num_feats:- resp_flat_best, idxs = torch.topk(responses_flatten, k=num_feats, dim=1)- max_coords_best = torch.gather(max_coords_flatten, 1, idxs.unsqueeze(-1).repeat(1, 1, 3))- else:- resp_flat_best = responses_flatten- max_coords_best = max_coords_flatten- B, N = resp_flat_best.size()-- # Converts scale level index from ConvSoftArgmax3d to the actual scale, using the sigmas- if isinstance(self.scale_pyr.n_levels, torch.Tensor):- num_levels = int(self.scale_pyr.n_levels.item())- elif isinstance(self.scale_pyr.n_levels, int):- num_levels = self.scale_pyr.n_levels- else:- raise TypeError(- "Expected the scale pyramid module to have `n_levels` as a torch.Tensor or int."- f"Gotcha {type(self.scale_pyr.n_levels)}"- )-- max_coords_best = _scale_index_to_scale(max_coords_best, sigmas_oct, num_levels)-- # Create local affine frames (LAFs)- rotmat = torch.eye(2, dtype=dtype, device=dev).view(1, 1, 2, 2)- current_lafs = torch.cat(- [- self.mr_size * max_coords_best[:, :, 0].view(B, N, 1, 1) * rotmat,- max_coords_best[:, :, 1:3].view(B, N, 2, 1),- ],- 3,+ # ββ Hoist loop invariants ββββββββββββββββββββββββββββββββββββββββββββ+ if isinstance(self.scale_pyr.n_levels, torch.Tensor):+ num_levels = int(self.scale_pyr.n_levels.item())+ elif isinstance(self.scale_pyr.n_levels, int):+ num_levels = self.scale_pyr.n_levels+ else:+ raise TypeError(+ "Expected the scale pyramid module to have `n_levels` as a torch.Tensor or int."+ f"Gotcha {type(self.scale_pyr.n_levels)}")-- # Zero response lafs, which touch the boundary- good_mask = laf_is_inside_image(current_lafs, octave[:, 0])- resp_flat_best = resp_flat_best * good_mask.to(dev, dtype)-- # Normalize LAFs- current_lafs *= px_size-- all_responses.append(resp_flat_best)- all_lafs.append(current_lafs)- px_size *= 2-- # Sort and keep best n- responses = torch.cat(all_responses, 1)- lafs = torch.cat(all_lafs, 1)+ rotmat = torch.eye(2, dtype=dtype, device=dev).view(1, 1, 2, 2)+ is_iterative_subpix = self._is_iterative_subpix+ px_size0 = 0.5 if self.scale_pyr.double_image else 1.0+ px_sizes = [px_size0 * (2.0**i) for i in range(len(sp))]++ # ββ Process octaves sequentially ββββββββββββββββββββββββββββββββββββ+ # All octaves are independent once the scale pyramid is built, but CUDA+ # stream parallelism does not help here: subpix allocates large scatter+ # tables per call, and concurrent CUDA allocations contend for the same+ # device memory allocator lock. Tested: sequential β parallel on GPU.+ n_oct = len(sp)+ results: List[Tuple[torch.Tensor, torch.Tensor]] = [+ self._process_octave(+ sp[i], sigmas[i], num_feats, mask, rotmat, num_levels, is_iterative_subpix, px_sizes[i]+ )+ for i in range(n_oct)+ ]++ # Sort and keep best n across all octaves.+ # Sparse per-octave top-K may yield fewer total candidates than num_feats+ # (e.g. small images with very few NMS maxima). topk then pads with zeros+ # to preserve the shape contract [B, num_feats, ...].+ responses = torch.cat([r[0] for r in results], 1)+ lafs = torch.cat([r[1] for r in results], 1)+ n_candidates = responses.size(1)+ if n_candidates < num_feats:+ pad = num_feats - n_candidates+ responses = F.pad(responses, (0, pad))+ lafs = F.pad(lafs, (0, 0, 0, 0, 0, pad))responses, idxs = torch.topk(responses, k=num_feats, dim=1)- lafs = torch.gather(lafs, 1, idxs.unsqueeze(-1).unsqueeze(-1).repeat(1, 1, 2, 3))+ lafs = torch.gather(lafs, 1, idxs.unsqueeze(-1).unsqueeze(-1).expand(-1, -1, 2, 3))return responses, lafsdef forward(self, img: torch.Tensor, mask: Optional[torch.Tensor] = None) -> Tuple[torch.Tensor, torch.Tensor]:@@ -310,9 +427,10 @@ class MultiResolutionDetector(nn.Module):config: Optional[Detector_config] = None,ori_module: Optional[nn.Module] = None,aff_module: Optional[nn.Module] = None,+ compile_model: bool = False,+ score_threshold: float = 0.0,) -> None:super().__init__()- self.model = modelif config is None:config = get_default_detector_config()# Load extraction configuration@@ -321,9 +439,17 @@ class MultiResolutionDetector(nn.Module):self.scale_factor_levels = config["scale_factor_levels"]self.mr_size = config["s_mult"]self.nms_size = config["nms_size"]- self.nms = NonMaximaSuppression2d((self.nms_size, self.nms_size))+ self.score_threshold = score_threshold+ nms = NonMaximaSuppression2d((self.nms_size, self.nms_size))self.num_features = num_features+ if compile_model:+ self.model = torch.compile(model, dynamic=True)+ self.nms = torch.compile(nms, dynamic=True)+ else:+ self.model = model+ self.nms = nms+if ori_module is None:self.ori: nn.Module = PassLAF()else:@@ -344,23 +470,26 @@ class MultiResolutionDetector(nn.Module):self, level_img: torch.Tensor, num_kp: int, factor: Tuple[float, float]) -> Tuple[torch.Tensor, torch.Tensor]:det_map = self.nms(self.remove_borders(self.model(level_img)))- device = level_img.device- dtype = level_img.dtype- yx = det_map.nonzero()[:, 2:].t()- scores = det_map[0, 0, yx[0], yx[1]] # keynet supports only non-batched images-- scores_sorted, indices = torch.sort(scores, descending=True)-- indices = indices[torch.where(scores_sorted > 0.0)]- yx = yx[:, indices[:num_kp]].t()- current_kp_num = len(yx)- xy_projected = yx.view(1, current_kp_num, 2).flip(2) * torch.tensor(factor, device=device, dtype=dtype)- scale_factor = 0.5 * (factor[0] + factor[1])- scale = scale_factor * self.mr_size * torch.ones(1, current_kp_num, 1, 1, device=device, dtype=dtype)- lafs = laf_from_center_scale_ori(- xy_projected, scale, torch.zeros(1, current_kp_num, 1, device=device, dtype=dtype)- )- return scores_sorted[:num_kp], lafs+ _, _, _h, w = det_map.shape+ det_flat = det_map.view(-1) # (H*W,) β B=1, C=1 guaranteed by MultiResolutionDetector++ # Mask out non-maxima (zeroed by NMS) and below-threshold scores, then topk.+ # Using masked_fill + topk instead of nonzero: avoids data-dependent output shapes,+ # supports score_threshold, and is compatible with torch.compile.+ fill = torch.finfo(det_flat.dtype).min / 2+ det_masked = det_flat.masked_fill(det_flat <= self.score_threshold, fill)+ k = min(num_kp, det_flat.numel())+ top_scores, top_flat_idx = torch.topk(det_masked, k=k)++ # Convert flat indices to (y, x) pixel coordinates.+ yx = torch.stack([top_flat_idx // w, top_flat_idx % w], dim=1) # (k, 2)++ fx = level_img.new_tensor([factor[0], factor[1]])+ xy_projected = yx.view(1, k, 2).flip(2).float() * fx+ scale_val = 0.5 * (factor[0] + factor[1]) * self.mr_size+ scale = level_img.new_full((1, k, 1, 1), scale_val)+ lafs = laf_from_center_scale_ori(xy_projected, scale, level_img.new_zeros(1, k, 1))+ return top_scores, lafsdef detect(self, img: torch.Tensor, mask: Optional[torch.Tensor] = None) -> Tuple[torch.Tensor, torch.Tensor]:# Compute points per level@@ -406,9 +535,7 @@ class MultiResolutionDetector(nn.Module):num_points_level = int(num_features_per_level[idx_level])if idx_level > 0 or (self.num_upscale_levels > 0):- nf2 = [num_features_per_level[a] for a in range(0, idx_level + 1 + self.num_upscale_levels)]- res_points = torch.tensor(nf2).sum().item()- num_points_level = int(res_points)+ num_points_level = sum(num_features_per_level[: idx_level + 1 + self.num_upscale_levels])cur_scores, cur_lafs = self.detect_features_on_single_level(cur_img, num_points_level, factor)all_responses.append(cur_scores.view(1, -1))diff --git a/kornia/geometry/ransac.py b/kornia/geometry/ransac.pyindex e5e1e2b20..437f20f78 100644--- a/kornia/geometry/ransac.py+++ b/kornia/geometry/ransac.py@@ -63,6 +63,7 @@ class RANSAC(nn.Module):max_lo_iters: int = 5,score_type: str = "ransac",prosac_sampling: bool = False,+ seed: Optional[int] = None,) -> None:"""Initialize the RANSAC estimator.@@ -76,6 +77,7 @@ class RANSAC(nn.Module):max_lo_iters: number of local optimization (polishing) iterations.score_type: scoring method to use: "ransac" or "msac".prosac_sampling: whether to use PROSAC sampling instead of random sampling.+ seed: optional random seed for reproducible results. If None, uses global random state."""super().__init__()@@ -96,6 +98,7 @@ class RANSAC(nn.Module):self.max_lo_iters = max_lo_itersself.model_type = model_typeself.prosac_sampling = prosac_sampling+ self.seed = seedself.error_fn: Callable[..., torch.Tensor]self.minimal_solver: Callable[..., torch.Tensor]@@ -154,7 +157,12 @@ class RANSAC(nn.Module):"""if device is None:device = torch.device("cpu")- rand = torch.rand(batch_size, pop_size, device=device)+ if self.seed is not None:+ generator = torch.Generator(device=device)+ generator.manual_seed(self.seed + iteration)+ rand = torch.rand(batch_size, pop_size, device=device, generator=generator)+ else:+ rand = torch.rand(batch_size, pop_size, device=device)_, out = rand.topk(k=sample_size, dim=1)return outdiff --git a/kornia/geometry/subpix/__init__.py b/kornia/geometry/subpix/__init__.pyindex cf9d4a16f..b6e74c946 100644--- a/kornia/geometry/subpix/__init__.py+++ b/kornia/geometry/subpix/__init__.py@@ -23,8 +23,9 @@ This subpackage provides subpixel localization and softmax utilities for geometrfrom __future__ import annotationsfrom .dsnt import render_gaussian2d, spatial_expectation2d, spatial_softmax2d-from .nms import NonMaximaSuppression2d, NonMaximaSuppression3d, nms2d, nms3d+from .nms import NonMaximaSuppression2d, NonMaximaSuppression3d, nms2d, nms3d, nms3d_minmaxfrom .spatial_soft_argmax import (+ AdaptiveQuadInterp3d,ConvQuadInterp3d,ConvSoftArgmax2d,ConvSoftArgmax3d,@@ -38,6 +39,7 @@ from .spatial_soft_argmax import ()__all__ = [+ "AdaptiveQuadInterp3d","ConvQuadInterp3d","ConvSoftArgmax2d","ConvSoftArgmax3d",@@ -51,6 +53,7 @@ __all__ = ["iterative_quad_interp3d","nms2d","nms3d",+ "nms3d_minmax","render_gaussian2d","spatial_expectation2d","spatial_soft_argmax2d",diff --git a/kornia/geometry/subpix/nms.py b/kornia/geometry/subpix/nms.pyindex f2cd723a6..0a35e43e5 100644--- a/kornia/geometry/subpix/nms.py+++ b/kornia/geometry/subpix/nms.py@@ -230,38 +230,38 @@ class NonMaximaSuppression3d(nn.Module):# find local maximum valuesB, CH, D, H, W = x.size()if self.kernel_size == (3, 3, 3):+ # 26-comparison explicit path: strict local maximum, works on CPU and CUDA.+ # Using integer slice literals (not slice objects) makes this torch.jit.script-friendly,+ # which fuses the ops and runs ~13x faster on CUDA than the eager path.mask = torch.zeros(B, CH, D, H, W, device=x.device, dtype=torch.bool)- center = slice(1, -1)- left = slice(0, -2)- right = slice(2, None)- center_tensor = x[..., center, center, center]+ ct = x[..., 1:-1, 1:-1, 1:-1]mask[..., 1:-1, 1:-1, 1:-1] = (- (center_tensor > x[..., center, center, left])- & (center_tensor > x[..., center, center, right])- & (center_tensor > x[..., center, left, center])- & (center_tensor > x[..., center, left, left])- & (center_tensor > x[..., center, left, right])- & (center_tensor > x[..., center, right, center])- & (center_tensor > x[..., center, right, left])- & (center_tensor > x[..., center, right, right])- & (center_tensor > x[..., left, center, center])- & (center_tensor > x[..., left, center, left])- & (center_tensor > x[..., left, center, right])- & (center_tensor > x[..., left, left, center])- & (center_tensor > x[..., left, left, left])- & (center_tensor > x[..., left, left, right])- & (center_tensor > x[..., left, right, center])- & (center_tensor > x[..., left, right, left])- & (center_tensor > x[..., left, right, right])- & (center_tensor > x[..., right, center, center])- & (center_tensor > x[..., right, center, left])- & (center_tensor > x[..., right, center, right])- & (center_tensor > x[..., right, left, center])- & (center_tensor > x[..., right, left, left])- & (center_tensor > x[..., right, left, right])- & (center_tensor > x[..., right, right, center])- & (center_tensor > x[..., right, right, left])- & (center_tensor > x[..., right, right, right])+ (ct > x[..., 0:-2, 0:-2, 0:-2])+ & (ct > x[..., 0:-2, 0:-2, 1:-1])+ & (ct > x[..., 0:-2, 0:-2, 2:])+ & (ct > x[..., 0:-2, 1:-1, 0:-2])+ & (ct > x[..., 0:-2, 1:-1, 1:-1])+ & (ct > x[..., 0:-2, 1:-1, 2:])+ & (ct > x[..., 0:-2, 2:, 0:-2])+ & (ct > x[..., 0:-2, 2:, 1:-1])+ & (ct > x[..., 0:-2, 2:, 2:])+ & (ct > x[..., 1:-1, 0:-2, 0:-2])+ & (ct > x[..., 1:-1, 0:-2, 1:-1])+ & (ct > x[..., 1:-1, 0:-2, 2:])+ & (ct > x[..., 1:-1, 1:-1, 0:-2])+ & (ct > x[..., 1:-1, 1:-1, 2:])+ & (ct > x[..., 1:-1, 2:, 0:-2])+ & (ct > x[..., 1:-1, 2:, 1:-1])+ & (ct > x[..., 1:-1, 2:, 2:])+ & (ct > x[..., 2:, 0:-2, 0:-2])+ & (ct > x[..., 2:, 0:-2, 1:-1])+ & (ct > x[..., 2:, 0:-2, 2:])+ & (ct > x[..., 2:, 1:-1, 0:-2])+ & (ct > x[..., 2:, 1:-1, 1:-1])+ & (ct > x[..., 2:, 1:-1, 2:])+ & (ct > x[..., 2:, 2:, 0:-2])+ & (ct > x[..., 2:, 2:, 1:-1])+ & (ct > x[..., 2:, 2:, 2:]))else:max_non_center = (@@ -298,3 +298,99 @@ def nms3d(input: torch.Tensor, kernel_size: tuple[int, int, int], mask_only: boo:class: `~kornia.feature.NonMaximaSuppression3d` for details."""return NonMaximaSuppression3d(kernel_size)(input, mask_only)+++def nms3d_minmax(input: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:+ r"""Compute both local-maxima and local-minima NMS masks for a 3-D scale-space tensor in one pass.++ Equivalent to calling ``nms3d(input, (3,3,3), mask_only=True)`` and+ ``nms3d(-input, (3,3,3), mask_only=True)`` separately, but only traverses+ the 26-neighbour comparisons once, halving the NMS cost.++ Uses integer slice literals (not Python loops or slice objects) so the 52+ comparison-and-reduction ops are visible to the compiler at trace time,+ allowing full fusion into a minimal number of kernels.++ Args:+ input: 5-D tensor of shape :math:`(B, C, D, H, W)`.++ Returns:+ A pair ``(max_mask, min_mask)`` of bool tensors with the same shape as+ *input*. ``max_mask[..., d, h, w]`` is ``True`` when the voxel is+ strictly greater than all 26 neighbours; ``min_mask`` is the same for+ strict local minima.++ Example:+ >>> x = torch.randn(1, 1, 5, 10, 10)+ >>> max_mask, min_mask = nms3d_minmax(x)+ >>> max_mask.shape+ torch.Size([1, 1, 5, 10, 10])++ """+ if input.dim() != 5:+ raise AssertionError(input.shape)+ B, CH, D, H, W = input.shape+ max_mask = torch.zeros(B, CH, D, H, W, device=input.device, dtype=torch.bool)+ min_mask = torch.zeros(B, CH, D, H, W, device=input.device, dtype=torch.bool)+ ct = input[..., 1:-1, 1:-1, 1:-1]+ # 26 explicit comparisons with integer slice literals β no Python loop so the+ # compiler sees all ops at trace time and can fuse them into a single kernel.+ is_max = (+ (ct > input[..., 0:-2, 0:-2, 0:-2])+ & (ct > input[..., 0:-2, 0:-2, 1:-1])+ & (ct > input[..., 0:-2, 0:-2, 2:])+ & (ct > input[..., 0:-2, 1:-1, 0:-2])+ & (ct > input[..., 0:-2, 1:-1, 1:-1])+ & (ct > input[..., 0:-2, 1:-1, 2:])+ & (ct > input[..., 0:-2, 2:, 0:-2])+ & (ct > input[..., 0:-2, 2:, 1:-1])+ & (ct > input[..., 0:-2, 2:, 2:])+ & (ct > input[..., 1:-1, 0:-2, 0:-2])+ & (ct > input[..., 1:-1, 0:-2, 1:-1])+ & (ct > input[..., 1:-1, 0:-2, 2:])+ & (ct > input[..., 1:-1, 1:-1, 0:-2])+ & (ct > input[..., 1:-1, 1:-1, 2:])+ & (ct > input[..., 1:-1, 2:, 0:-2])+ & (ct > input[..., 1:-1, 2:, 1:-1])+ & (ct > input[..., 1:-1, 2:, 2:])+ & (ct > input[..., 2:, 0:-2, 0:-2])+ & (ct > input[..., 2:, 0:-2, 1:-1])+ & (ct > input[..., 2:, 0:-2, 2:])+ & (ct > input[..., 2:, 1:-1, 0:-2])+ & (ct > input[..., 2:, 1:-1, 1:-1])+ & (ct > input[..., 2:, 1:-1, 2:])+ & (ct > input[..., 2:, 2:, 0:-2])+ & (ct > input[..., 2:, 2:, 1:-1])+ & (ct > input[..., 2:, 2:, 2:])+ )+ is_min = (+ (ct < input[..., 0:-2, 0:-2, 0:-2])+ & (ct < input[..., 0:-2, 0:-2, 1:-1])+ & (ct < input[..., 0:-2, 0:-2, 2:])+ & (ct < input[..., 0:-2, 1:-1, 0:-2])+ & (ct < input[..., 0:-2, 1:-1, 1:-1])+ & (ct < input[..., 0:-2, 1:-1, 2:])+ & (ct < input[..., 0:-2, 2:, 0:-2])+ & (ct < input[..., 0:-2, 2:, 1:-1])+ & (ct < input[..., 0:-2, 2:, 2:])+ & (ct < input[..., 1:-1, 0:-2, 0:-2])+ & (ct < input[..., 1:-1, 0:-2, 1:-1])+ & (ct < input[..., 1:-1, 0:-2, 2:])+ & (ct < input[..., 1:-1, 1:-1, 0:-2])+ & (ct < input[..., 1:-1, 1:-1, 2:])+ & (ct < input[..., 1:-1, 2:, 0:-2])+ & (ct < input[..., 1:-1, 2:, 1:-1])+ & (ct < input[..., 1:-1, 2:, 2:])+ & (ct < input[..., 2:, 0:-2, 0:-2])+ & (ct < input[..., 2:, 0:-2, 1:-1])+ & (ct < input[..., 2:, 0:-2, 2:])+ & (ct < input[..., 2:, 1:-1, 0:-2])+ & (ct < input[..., 2:, 1:-1, 1:-1])+ & (ct < input[..., 2:, 1:-1, 2:])+ & (ct < input[..., 2:, 2:, 0:-2])+ & (ct < input[..., 2:, 2:, 1:-1])+ & (ct < input[..., 2:, 2:, 2:])+ )+ max_mask[..., 1:-1, 1:-1, 1:-1] = is_max+ min_mask[..., 1:-1, 1:-1, 1:-1] = is_min+ return max_mask, min_maskdiff --git a/kornia/geometry/subpix/spatial_soft_argmax.py b/kornia/geometry/subpix/spatial_soft_argmax.pyindex 5b42278d2..16f406e84 100644--- a/kornia/geometry/subpix/spatial_soft_argmax.py+++ b/kornia/geometry/subpix/spatial_soft_argmax.py@@ -23,7 +23,6 @@ import torchimport torch.nn.functional as Ffrom torch import nn-from kornia.filters.sobel import spatial_gradient3dfrom kornia.geometry.conversions import normalize_pixel_coordinates, normalize_pixel_coordinates3dfrom kornia.geometry.grid import create_meshgrid, create_meshgrid3d@@ -344,7 +343,7 @@ def conv_soft_argmax2d(# applies exponential normalization trick# https://timvieira.github.io/blog/post/2014/02/11/exp-F.normalize-trick/# https://github.com/pytorch/pytorch/blob/bcb0bb7e0e03b386ad837015faba6b4b16e3bfb9/aten/src/ATen/native/SoftMax.cpp#L44- x_max = F.adaptive_max_pool2d(input, (1, 1))+ x_max = input.amax(dim=(-2, -1), keepdim=True) # faster than F.adaptive_max_pool2d(input, (1,1))# max is detached to prevent undesired backprop loops in the graphx_exp = ((input - x_max.detach()) / temperature).exp()@@ -465,7 +464,7 @@ def conv_soft_argmax3d(# applies exponential normalization trick# https://timvieira.github.io/blog/post/2014/02/11/exp-F.normalize-trick/# https://github.com/pytorch/pytorch/blob/bcb0bb7e0e03b386ad837015faba6b4b16e3bfb9/aten/src/ATen/native/SoftMax.cpp#L44- x_max = F.adaptive_max_pool3d(input, (1, 1, 1))+ x_max = input.amax(dim=(-3, -2, -1), keepdim=True) # faster than F.adaptive_max_pool3d(input, (1,1,1))# max is detached to prevent undesired backprop loops in the graphx_exp = ((input - x_max.detach()) / temperature).exp()@@ -618,21 +617,338 @@ def _solve_cramer_sym3x3(return sx, sy, ss, solved+def conv_quad_interp3d(+ input: torch.Tensor,+ n_iters: int = 5,+ strict_maxima_bonus: float = 10.0,+ max_subpixel_shift: float = 0.6,+ precomputed_nms_mask: Optional[torch.Tensor] = None,+ dilation_radius: int = 1,+ allow_scale_steps: bool = True,+) -> tuple[torch.Tensor, torch.Tensor]:+ r"""Subpixel localization of 3D scale-space extrema via quadratic interpolation.++ For each NMS maximum the function fits a 3-D quadratic to the local+ :math:`3 \times 3 \times 3` neighbourhood and solves for the sub-voxel+ shift that maximises the fit. When the shift along any axis exceeds+ ``max_subpixel_shift`` the integer centre is moved one step in that direction+ and the solve is repeated β up to ``n_iters`` times.++ Unlike a naive iterative approach, all Hessian solves are precomputed once at+ the start for every voxel that any keypoint could possibly visit (the+ **dilated NMS neighbourhood**, an L\ :math:`\infty` ball of radius+ ``dilation_radius`` around each maximum). The subsequent iteration loop contains+ **no data-dependent Python control flow** and no GPUβCPU synchronisation,+ making the function fully compatible with ``torch.compile`` / CUDA graphs.++ The ``dilation_radius`` controls the precompute footprint and should be set+ to the maximum number of integer-centre moves expected per keypoint. With the+ default ``max_subpixel_shift=0.6`` almost all keypoints converge within 1 move,+ so the default ``dilation_radius=1`` (i.e. :math:`3^3 = 27` positions per+ maximum) is sufficient. Use ``dilation_radius=2`` (:math:`5^3 = 125`) for+ extra safety. Setting it equal to ``n_iters`` recovers the original behaviour+ but is much slower on large images.++ Args:+ input: response pyramid with shape :math:`(B, C, D, H, W)`.+ n_iters: maximum number of localization iterations per keypoint.+ strict_maxima_bonus: value added to ``y_max`` at NMS-maximum positions+ so that strict maxima are preferred during top-K selection.+ max_subpixel_shift: threshold above which the integer centre is+ moved one step and another iteration is run.+ precomputed_nms_mask: optional bool tensor of shape+ :math:`(B, C, D, H, W)` β pass the result of+ :func:`~kornia.geometry.subpix.nms3d` to skip the internal NMS call.+ dilation_radius: L\ :math:`\infty` radius (in voxels) of the neighbourhood+ around each NMS maximum where the Hessian solve is precomputed.+ Keypoints that attempt to move farther than this are marked invalid.+ allow_scale_steps: if ``True`` (default), the iterative shift is also+ applied along the scale (depth) axis; set to ``False`` to keep the+ keypoint on its original scale level.++ Returns:+ Tuple ``(coords_max, y_max)``:++ * ``coords_max`` β shape :math:`(B, C, 3, D, H, W)`, refined+ ``[scale, x(width), y(height)]`` coordinates for each NMS maximum;+ non-maximum positions keep their grid coordinates.+ * ``y_max`` β shape :math:`(B, C, D, H, W)`, quadratically corrected+ response with optional strict-maxima bonus.++ Example:+ >>> input = torch.randn(2, 3, 5, 64, 64)+ >>> coords, vals = conv_quad_interp3d(input, n_iters=5)+ >>> coords.shape+ torch.Size([2, 3, 3, 5, 64, 64])+ >>> vals.shape+ torch.Size([2, 3, 5, 64, 64])++ """+ if not torch.is_tensor(input):+ raise TypeError(f"Input type is not a torch.Tensor. Got {type(input)}")+ if input.ndim != 5:+ raise ValueError(f"Invalid input shape, expected BxCxDxHxW. Got: {input.shape}")++ B, C, D, H, W = input.shape+ device = input.device+ dtype = input.dtype+ BC = B * C+ DHW = D * H * W+ HW = H * W++ coords_max = torch.empty(B, C, 3, D, H, W, device=device, dtype=dtype)+ coords_max[:, :, 0] = torch.arange(D, device=device, dtype=dtype).view(D, 1, 1)+ coords_max[:, :, 1] = torch.arange(W, device=device, dtype=dtype).view(1, 1, W)+ coords_max[:, :, 2] = torch.arange(H, device=device, dtype=dtype).view(1, H, 1)+ y_max = input.clone()++ if D < 3 or H < 3 or W < 3:+ return coords_max, y_max++ # ββ Step 1: NMS maxima ββββββββββββββββββββββββββββββββββββββββββββββββββββ+ nms_mask = precomputed_nms_mask if precomputed_nms_mask is not None else nms3d(input, (3, 3, 3), True)+ bc_idx, d_idx, h_idx, w_idx = torch.where(nms_mask.view(BC, D, H, W))+ N = bc_idx.shape[0]+ # Note: no early-return for N==0 β empty tensors flow through all ops as no-ops.++ # ββ Step 2: dilate NMS positions β Lβ ball of radius dilation_radius ββββββββ+ # Generates all voxels a keypoint could visit across n_iters shift steps.+ # With max_subpixel_shift=0.6, almost all keypoints converge in β€1 integer move,+ # so dilation_radius=1 (27 positions per max) is sufficient in practice.+ r = dilation_radius+ offs = torch.arange(-r, r + 1, device=device, dtype=torch.long) # (2r+1,)+ od, oh, ow = torch.meshgrid(offs, offs, offs, indexing="ij") # each: (2r+1)Β³+ od = od.reshape(-1) # (K,) K = (2r+1)Β³+ oh = oh.reshape(-1)+ ow = ow.reshape(-1)+ K = od.shape[0]++ # Broadcast expand: (N,1) + (1,K) β (N*K,)+ d_dil = (d_idx.unsqueeze(1) + od.unsqueeze(0)).reshape(-1)+ h_dil = (h_idx.unsqueeze(1) + oh.unsqueeze(0)).reshape(-1)+ w_dil = (w_idx.unsqueeze(1) + ow.unsqueeze(0)).reshape(-1)+ bc_dil = bc_idx.unsqueeze(1).expand(-1, K).reshape(-1)++ # Keep only interior positions (Hessian needs Β±1 neighbours in all dims).+ keep = (d_dil >= 1) & (d_dil <= D - 2) & (h_dil >= 1) & (h_dil <= H - 2) & (w_dil >= 1) & (w_dil <= W - 2)+ bc_u = bc_dil[keep]+ d_u = d_dil[keep]+ h_u = h_dil[keep]+ w_u = w_dil[keep]+ # Note: bc_u/d_u/h_u/w_u may contain duplicate positions (multiple NMS maxima sharing+ # a dilated neighbour). We intentionally skip torch.unique here because:+ # (a) torch.unique output size depends on VALUES not shapes β causes torch.compile+ # to recompile whenever the unique-element count changes across images, producing+ # multi-second spikes (e.g. 4-7 s) for images with different NMS density.+ # (b) The keep-filter boolean-index above already forces a graph break at this point,+ # so the code below runs in eager mode regardless β deduplication buys nothing.+ # (c) Duplicate positions receive the same solve result (same 3x3x3 patch, deterministic+ # quadratic system), so last-write-wins in the LUT is correct.++ # ββ Step 3: gather 3x3x3 neighbourhood for all kept dilated positions ββββ+ inp_flat = input.view(-1)+ patch_offsets = _PATCH_DD.to(device) * HW + _PATCH_DH.to(device) * W + _PATCH_DW.to(device) # (27,)+ center_flat = bc_u * DHW + d_u * HW + h_u * W + w_u+ 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)++ 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).+ gds_u = gx * sx_u + gy * sy_u + gs * ss_u++ # ββ Step 5: build a compact int32 lookup table βββββββββββββββββββββββββββ+ # Maps flat(bc, d, h, w) β index into the NK-sized solution arrays+ # (sx_u, sy_u, ss_u, gds_u, sol_u). -1 means "not precomputed here" β+ # the keypoint has moved out of the dilated neighbourhood and is invalid.+ # Duplicate positions use last-write-wins, which is correct since the same+ # position always yields the same quadratic solution.+ #+ # Memory: 1 x BC*D*H*W x int32 (4 bytes/elem)+ # vs 5 x BC*D*H*W x float32 + 1 x bool (21 bytes/elem previously)+ # β ~5x reduction. For a 640x800x6 octave: 12 MB vs 62 MB.+ NK = bc_u.shape[0]+ lut = torch.full((BC * DHW,), -1, dtype=torch.int32, device=device)+ lut[bc_u * DHW + d_u * HW + h_u * W + w_u] = torch.arange(NK, dtype=torch.int32, device=device)++ # ββ Step 6: iterative lookup β no .any().item() sync βββββββββββββββββββββ+ d_cur = d_idx.clone()+ h_cur = h_idx.clone()+ w_cur = w_idx.clone()+ valid = torch.ones(N, dtype=torch.bool, device=device)+ shift_x = torch.zeros(N, device=device, dtype=dtype)+ shift_y = torch.zeros(N, device=device, dtype=dtype)+ shift_s = torch.zeros(N, device=device, dtype=dtype)+ grad_dot_shift = torch.zeros(N, device=device, dtype=dtype)++ for _ in range(n_iters):+ di = d_cur.clamp(1, D - 2)+ hi = h_cur.clamp(1, H - 2)+ wi = w_cur.clamp(1, W - 2)++ flat_q = bc_idx * DHW + di * HW + hi * W + wi # (N,)+ lut_idx = lut[flat_q].long() # (N,) int64; -1 = not in precomputed range+ in_lut = lut_idx >= 0+ idx_safe = lut_idx.clamp(min=0) # safe index (clamp -1 β 0 before gather)++ sx = sx_u[idx_safe]+ sy = sy_u[idx_safe]+ ss = ss_u[idx_safe]+ gds = gds_u[idx_safe]+ sol = sol_u[idx_safe] & in_lut++ valid = valid & sol+ vf = valid.to(dtype)+ sx = sx * vf+ sy = sy * vf+ ss = ss * vf++ shift_x = torch.where(valid, sx, shift_x)+ shift_y = torch.where(valid, sy, shift_y)+ shift_s = torch.where(valid, ss, shift_s)+ grad_dot_shift = torch.where(valid, gds, grad_dot_shift)++ move_px = valid & (sx > max_subpixel_shift)+ move_nx = valid & (sx < -max_subpixel_shift)+ new_w = w_cur + move_px.long() - move_nx.long()+ valid = valid & (new_w >= 1) & (new_w <= W - 2)+ w_cur = new_w.clamp(0, W - 1)++ move_py = valid & (sy > max_subpixel_shift)+ move_ny = valid & (sy < -max_subpixel_shift)+ new_h = h_cur + move_py.long() - move_ny.long()+ valid = valid & (new_h >= 1) & (new_h <= H - 2)+ h_cur = new_h.clamp(0, H - 1)++ if allow_scale_steps:+ move_ps = valid & (ss > max_subpixel_shift)+ move_ns = valid & (ss < -max_subpixel_shift)+ new_d = d_cur + move_ps.long() - move_ns.long()+ valid = valid & (new_d >= 1) & (new_d <= D - 2)+ d_cur = new_d.clamp(0, D - 1)++ valid = valid & (shift_x.abs() <= 1.5) & (shift_y.abs() <= 1.5) & (shift_s.abs() <= 1.5)++ # ββ Write refined coordinates and corrected response ββββββββββββββββββββββ+ b_idx = bc_idx // C+ c_idx = bc_idx % C++ coords_max[b_idx, c_idx, 0, d_idx, h_idx, w_idx] = torch.where(valid, d_cur.to(dtype) + shift_s, d_idx.to(dtype))+ coords_max[b_idx, c_idx, 1, d_idx, h_idx, w_idx] = torch.where(valid, w_cur.to(dtype) + shift_x, w_idx.to(dtype))+ coords_max[b_idx, c_idx, 2, d_idx, h_idx, w_idx] = torch.where(valid, h_cur.to(dtype) + shift_y, h_idx.to(dtype))++ val_correction = 0.5 * torch.where(valid, grad_dot_shift, torch.zeros_like(grad_dot_shift))+ # Use the final recentered position for val_center (h_cur/w_cur may have moved during iteration)+ val_center = input.view(BC, D, H, W)[bc_idx, d_cur, h_cur, w_cur]+ y_max[b_idx, c_idx, d_idx, h_idx, w_idx] = val_center + val_correction+ if strict_maxima_bonus > 0:+ y_max[b_idx, c_idx, d_idx, h_idx, w_idx] += strict_maxima_bonus * valid.to(dtype)++ return coords_max, y_max+++class ConvQuadInterp3d(nn.Module):+ r"""Subpixel localization of 3D scale-space extrema via quadratic interpolation.++ Wraps :func:`~kornia.geometry.subpix.conv_quad_interp3d`. The Hessian system+ is solved once for each voxel in the dilated NMS neighbourhood (no dense+ precomputation over the whole volume), then the shift chain is followed by+ table lookup with no GPUβCPU synchronisation β making the module compatible+ with ``torch.compile`` and CUDA graphs.++ Args:+ n_iters: maximum localization iterations per keypoint.+ strict_maxima_bonus: score bonus at NMS-maximum positions.+ max_subpixel_shift: shift threshold that triggers integer centre move.+ """++ def __init__(+ self,+ n_iters: int = 5,+ strict_maxima_bonus: float = 10.0,+ max_subpixel_shift: float = 0.6,+ dilation_radius: int = 1,+ allow_scale_steps: bool = True,+ ) -> None:+ super().__init__()+ self.n_iters = n_iters+ self.strict_maxima_bonus = strict_maxima_bonus+ self.max_subpixel_shift = max_subpixel_shift+ self.dilation_radius = dilation_radius+ self.allow_scale_steps = allow_scale_steps++ def __repr__(self) -> str:+ return (+ f"{self.__class__.__name__}("+ f"n_iters={self.n_iters}, "+ f"strict_maxima_bonus={self.strict_maxima_bonus}, "+ f"max_subpixel_shift={self.max_subpixel_shift}, "+ f"dilation_radius={self.dilation_radius}, "+ f"allow_scale_steps={self.allow_scale_steps})"+ )++ def forward(+ self, x: torch.Tensor, precomputed_nms_mask: Optional[torch.Tensor] = None+ ) -> tuple[torch.Tensor, torch.Tensor]:+ return conv_quad_interp3d(+ x,+ self.n_iters,+ self.strict_maxima_bonus,+ self.max_subpixel_shift,+ precomputed_nms_mask,+ self.dilation_radius,+ self.allow_scale_steps,+ )++def iterative_quad_interp3d(input: torch.Tensor,n_iters: int = 5,strict_maxima_bonus: float = 10.0,max_subpixel_shift: float = 0.6,+ allow_scale_steps: bool = True,+ precomputed_nms_mask: Optional[torch.Tensor] = None,+ max_candidates: Optional[int] = None,) -> tuple[torch.Tensor, torch.Tensor]:r"""Iterative subpixel localization of 3D extrema via quadratic interpolation.- Unlike :func:`conv_quad_interp3d`, which performs a single-pass sliding-window- solve using spatial gradient convolutions, this function explicitly extracts the- :math:`3 \times 3 \times 3` patch at each NMS maximum and iterates up to- ``n_iters`` times. When the estimated subpixel shift along any spatial or scale- axis exceeds ``max_subpixel_shift`` the integer center is moved one step in that- direction and the solve is repeatedβmatching the localization loop from the- HessAff / SIFT family of detectors.+ Unlike :func:`conv_quad_interp3d`, which pre-computes the Hessian solve for all+ voxels reachable from NMS maxima and then follows shifts by table lookup, this+ function explicitly re-extracts the :math:`3 \times 3 \times 3` patch at each+ NMS maximum and iterates up to ``n_iters`` times. When the estimated subpixel+ shift along any spatial or scale axis exceeds ``max_subpixel_shift`` the integer+ center is moved one step in that direction and the solve is repeated β matching+ the localization loop from the HessAff / SIFT family of detectors.Args:input: response pyramid with shape :math:`(B, C, D, H, W)`.@@ -641,6 +957,20 @@ def iterative_quad_interp3d(that strict maxima are preferred when selecting the top-K keypoints.max_subpixel_shift: if the estimated shift along any axis is larger than thisthreshold the integer center is displaced and another iteration is run.+ allow_scale_steps: if ``True`` (default), the iterative shift is also+ applied along the scale (depth) axis; set to ``False`` to keep the+ keypoint on its original scale level.+ precomputed_nms_mask: optional bool tensor of shape+ :math:`(B, C, D, H, W)` β pass the result of+ :func:`~kornia.geometry.subpix.nms3d` to skip the internal NMS call.+ max_candidates: if given, only the top-``max_candidates`` NMS maxima (ranked by+ pre-refinement response) are processed. The rest keep their grid-coordinate+ values. This is a **CPU speed-up knob**: for large images the number of 3-D+ NMS maxima can be 10x-100x larger than the desired number of keypoints,+ making the per-candidate gather+solve loop the dominant CPU cost. Setting+ ``max_candidates = num_features * 5`` (say) dramatically reduces that work+ at the cost of occasionally missing a feature whose response rank would have+ improved after refinement.Returns:A tuple ``(coords_max, y_max)`` where@@ -669,9 +999,6 @@ def iterative_quad_interp3d(device = input.devicedtype = input.dtype- # Build coords_max with the same coordinate ordering as conv_quad_interp3d:- # dim-2: [scale(z), x(width), y(height)].- # Use empty + broadcast-fill: 23x faster than expand(...).clone() on large tensors.coords_max = torch.empty(B, C, 3, D, H, W, device=device, dtype=dtype)coords_max[:, :, 0] = torch.arange(D, device=device, dtype=dtype).view(D, 1, 1)coords_max[:, :, 1] = torch.arange(W, device=device, dtype=dtype).view(1, 1, W)@@ -681,80 +1008,81 @@ def iterative_quad_interp3d(if D < 3 or H < 3 or W < 3:return coords_max, y_max- # Flatten B and C into a single leading dimension for indexing convenience.inp = input.reshape(B * C, D, H, W)DHW = D * H * WHW = H * W- nms_mask = nms3d(input, (3, 3, 3), True) # (B, C, D, H, W) bool- nms_flat = nms_mask.view(B * C, D, H, W)+ nms_flat = (precomputed_nms_mask if precomputed_nms_mask is not None else nms3d(input, (3, 3, 3), True)).view(+ B * C, D, H, W+ )bc_idx, d_idx, h_idx, w_idx = torch.where(nms_flat)N = bc_idx.shape[0]- if N == 0:- return coords_max, y_max+ # Note: no early-return for N==0 β empty tensors flow through all ops as no-ops,+ # avoiding a Python branch that would cause torch.compile to specialise and recompile+ # when blurry octaves first yield zero NMS maxima.++ # ββ CPU speed-up: pre-filter to top-max_candidates by pre-refinement response ββ+ # For large images the NMS can yield tens of thousands of candidates while only a+ # few hundred features are ultimately needed. The per-candidate patch gather+ # (random memory access into a multi-MB volume) is cache-miss dominated on CPU;+ # reducing N here gives a proportional speedup of the iteration loop below.+ if max_candidates is not None and N > max_candidates:+ cand_vals = inp[bc_idx, d_idx, h_idx, w_idx] # (N,) pre-refinement responses+ _, keep = torch.topk(cand_vals, k=max_candidates)+ bc_idx = bc_idx[keep]+ d_idx = d_idx[keep]+ h_idx = h_idx[keep]+ w_idx = w_idx[keep]+ N = max_candidates++ patch_offsets = _PATCH_DD.to(device) * HW + _PATCH_DH.to(device) * W + _PATCH_DW.to(device)- # Pre-compute flat offsets for gathering a full 3x3x3 neighborhood in one shot.- # Uses module-level _PATCH_DD/_PATCH_DH/_PATCH_DW constants (avoids per-call allocation).- patch_offsets = _PATCH_DD.to(device) * HW + _PATCH_DH.to(device) * W + _PATCH_DW.to(device) # (27,)-- # Integer center positions β updated across iterations.d_cur = d_idx.clone()h_cur = h_idx.clone()w_cur = w_idx.clone()- # Track which keypoints remain valid (in bounds, system solvable).valid = torch.ones(N, dtype=torch.bool, device=device)- # Final subpixel offsets relative to the (possibly moved) integer center.shift_x = torch.zeros(N, device=device, dtype=dtype)shift_y = torch.zeros(N, device=device, dtype=dtype)shift_s = torch.zeros(N, device=device, dtype=dtype)grad_dot_shift = torch.zeros(N, device=device, dtype=dtype)- inp_flat = inp.reshape(-1) # flat view for gather indexing- bc_base = bc_idx * DHW # per-keypoint base offset (constant across iterations)+ inp_flat = inp.reshape(-1)+ bc_base = bc_idx * DHWfor _ in range(n_iters):- # Clamp so we can always safely access Β±1 neighbours.d_s = d_cur.clamp(1, D - 2)h_s = h_cur.clamp(1, H - 2)w_s = w_cur.clamp(1, W - 2)- # Gather full 3x3x3 patch in a single vectorized op: (N, 27)patch = inp_flat[(bc_base + d_s * HW + h_s * W + w_s).unsqueeze(1) + patch_offsets.unsqueeze(0)]- # Unpack patch neighbors by name. Flat index: k = (dd+1)*9 + (dh+1)*3 + (dw+1)- # where dd/dh/dw are the offsets in scale/height/width, each in {-1, 0, +1}.- # Naming convention: xm/xp = width-1/+1, ym/yp = height-1/+1, sm/sp = scale-1/+1.- c000 = patch[:, 13] # center (dd=0, dh=0, dw=0)- # axis neighbors- p_xm = patch[:, 12] # (dd= 0, dh= 0, dw=-1)- p_xp = patch[:, 14] # (dd= 0, dh= 0, dw=+1)- p_ym = patch[:, 10] # (dd= 0, dh=-1, dw= 0)- p_yp = patch[:, 16] # (dd= 0, dh=+1, dw= 0)- p_sm = patch[:, 4] # (dd=-1, dh= 0, dw= 0)- p_sp = patch[:, 22] # (dd=+1, dh= 0, dw= 0)- # diagonal neighbors used for mixed partials- p_xm_ym = patch[:, 9] # (dd= 0, dh=-1, dw=-1)- p_xp_ym = patch[:, 11] # (dd= 0, dh=-1, dw=+1)- p_xm_yp = patch[:, 15] # (dd= 0, dh=+1, dw=-1)- p_xp_yp = patch[:, 17] # (dd= 0, dh=+1, dw=+1)- p_xm_sm = patch[:, 3] # (dd=-1, dh= 0, dw=-1)- p_xp_sm = patch[:, 5] # (dd=-1, dh= 0, dw=+1)- p_xm_sp = patch[:, 21] # (dd=+1, dh= 0, dw=-1)- p_xp_sp = patch[:, 23] # (dd=+1, dh= 0, dw=+1)- p_ym_sm = patch[:, 1] # (dd=-1, dh=-1, dw= 0)- p_yp_sm = patch[:, 7] # (dd=-1, dh=+1, dw= 0)- p_ym_sp = patch[:, 19] # (dd=+1, dh=-1, dw= 0)- p_yp_sp = patch[:, 25] # (dd=+1, dh=+1, dw= 0)-- # First-order finite differences (0.5 * (next - prev)), matches C++ convention.- gx = 0.5 * (p_xp - p_xm) # x/width direction- gy = 0.5 * (p_yp - p_ym) # y/height direction- gs = 0.5 * (p_sp - p_sm) # scale direction-- # Second-order finite differences.+ 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_xmdyy = p_yp - 2.0 * c000 + p_ymdss = p_sp - 2.0 * c000 + p_sm@@ -763,22 +1091,18 @@ def iterative_quad_interp3d(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)- # Use non-inplace ops so that tensors saved by torch.where for autograd are not mutated.valid = valid & solved- # Zero out invalid solutions to avoid NaN propagation.valid_f = valid.to(dtype)sx = sx * valid_fsy = sy * valid_fss = ss * valid_f- # Save best estimates for valid keypoints.shift_x = torch.where(valid, sx, shift_x)shift_y = torch.where(valid, sy, shift_y)shift_s = torch.where(valid, ss, shift_s)grad_dot_shift = torch.where(valid, gx * sx + gy * sy + gs * ss, grad_dot_shift)- # Determine which axes need an integer step and move the center.move_pos_x = valid & (sx > max_subpixel_shift)move_neg_x = valid & (sx < -max_subpixel_shift)new_w = w_cur + move_pos_x.long() - move_neg_x.long()@@ -791,22 +1115,18 @@ def iterative_quad_interp3d(valid = valid & (new_h >= 1) & (new_h <= H - 2)h_cur = new_h.clamp(0, H - 1)- move_pos_s = valid & (ss > max_subpixel_shift)- move_neg_s = valid & (ss < -max_subpixel_shift)- new_d = d_cur + move_pos_s.long() - move_neg_s.long()- valid = valid & (new_d >= 1) & (new_d <= D - 2)- d_cur = new_d.clamp(0, D - 1)+ if allow_scale_steps:+ move_pos_s = valid & (ss > max_subpixel_shift)+ move_neg_s = valid & (ss < -max_subpixel_shift)+ new_d = d_cur + move_pos_s.long() - move_neg_s.long()+ valid = valid & (new_d >= 1) & (new_d <= D - 2)+ d_cur = new_d.clamp(0, D - 1)- # Invalidate keypoints whose final shift is still too large (C++ finalThreshold check).valid = valid & (shift_x.abs() <= 1.5) & (shift_y.abs() <= 1.5) & (shift_s.abs() <= 1.5)- # --- Write refined coordinates into the dense output map ----------------- # coords_max layout: dim-2 = [scale, x(width), y(height)] β same as conv_quad_interp3d.b_idx = bc_idx // Cc_idx = bc_idx % C- # For valid keypoints: integer center + subpixel offset.- # For invalid keypoints: fall back to original NMS position.final_s = torch.where(valid, d_cur.to(dtype) + shift_s, d_idx.to(dtype))final_x = torch.where(valid, w_cur.to(dtype) + shift_x, w_idx.to(dtype))final_y = torch.where(valid, h_cur.to(dtype) + shift_y, h_idx.to(dtype))@@ -815,9 +1135,9 @@ def iterative_quad_interp3d(coords_max[b_idx, c_idx, 1, d_idx, h_idx, w_idx] = final_xcoords_max[b_idx, c_idx, 2, d_idx, h_idx, w_idx] = final_y- # Quadratically corrected response value: val = center + 0.5 * grad^T * shift.val_correction = 0.5 * torch.where(valid, grad_dot_shift, torch.zeros_like(grad_dot_shift))- val_center = inp[bc_idx, d_idx, h_idx, w_idx]+ # Use the final recentered position for val_center (h_cur/w_cur may have moved during iteration)+ val_center = inp[bc_idx, d_cur, h_cur, w_cur]y_max[b_idx, c_idx, d_idx, h_idx, w_idx] = val_center + val_correctionif strict_maxima_bonus > 0:@@ -837,139 +1157,142 @@ class IterativeQuadInterp3d(nn.Module):n_iters: int = 5,strict_maxima_bonus: float = 10.0,max_subpixel_shift: float = 0.6,+ allow_scale_steps: bool = True,+ max_candidates: Optional[int] = None,) -> None:super().__init__()self.n_iters = n_itersself.strict_maxima_bonus = strict_maxima_bonusself.max_subpixel_shift = max_subpixel_shift+ self.allow_scale_steps = allow_scale_steps+ self.max_candidates = max_candidatesdef __repr__(self) -> str:return (f"{self.__class__.__name__}("f"n_iters={self.n_iters}, "f"strict_maxima_bonus={self.strict_maxima_bonus}, "- f"max_subpixel_shift={self.max_subpixel_shift})"+ f"max_subpixel_shift={self.max_subpixel_shift}, "+ f"allow_scale_steps={self.allow_scale_steps}, "+ f"max_candidates={self.max_candidates})")- def forward(self, x: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:- return iterative_quad_interp3d(x, self.n_iters, self.strict_maxima_bonus, self.max_subpixel_shift)---def conv_quad_interp3d(- input: torch.Tensor, strict_maxima_bonus: float = 10.0, eps: float = 1e-7-) -> tuple[torch.Tensor, torch.Tensor]:- r"""Compute the single iteration of quadratic interpolation of the extremum (max or min).+ def forward(+ self,+ x: torch.Tensor,+ precomputed_nms_mask: Optional[torch.Tensor] = None,+ ) -> tuple[torch.Tensor, torch.Tensor]:+ return iterative_quad_interp3d(+ x,+ self.n_iters,+ self.strict_maxima_bonus,+ self.max_subpixel_shift,+ self.allow_scale_steps,+ precomputed_nms_mask=precomputed_nms_mask,+ max_candidates=self.max_candidates,+ )- Args:- input: the given heatmap with shape :math:`(N, C, D_{in}, H_{in}, W_{in})`.- strict_maxima_bonus: pixels, which are strict maxima will score (1 + strict_maxima_bonus) * value.- This is needed for mimic behavior of strict NMS in classic local features- eps: parameter to control the hessian matrix ill-condition number.- Returns:- the location and value per each 3x3x3 window which contains strict extremum, similar to one done is SIFT.- :math:`(N, C, 3, D_{out}, H_{out}, W_{out})`, :math:`(N, C, D_{out}, H_{out}, W_{out})`,+class AdaptiveQuadInterp3d(nn.Module):+ r"""Subpixel localization of 3D scale-space extrema with automatic backend selection.- where+ Wraps :func:`~kornia.geometry.subpix.conv_quad_interp3d` and+ :func:`~kornia.geometry.subpix.iterative_quad_interp3d`, choosing the faster+ backend based on the input device and the requested ``mode``.- .. math::- D_{out} = \left\lfloor\frac{D_{in} + 2 \times \text{padding}[0] -- (\text{kernel\_size}[0] - 1) - 1}{\text{stride}[0]} + 1\right\rfloor+ Benchmarks show:- .. math::- H_{out} = \left\lfloor\frac{H_{in} + 2 \times \text{padding}[1] -- (\text{kernel\_size}[1] - 1) - 1}{\text{stride}[1]} + 1\right\rfloor+ * **GPU** β :func:`conv_quad_interp3d` is 1.5-2x faster due to better+ parallelism on the batched gather+solve.+ * **CPU** β :func:`iterative_quad_interp3d` is faster for large images because+ it processes only the NMS maxima directly without any dilation/dedup overhead.- .. math::- W_{out} = \left\lfloor\frac{W_{in} + 2 \times \text{padding}[2] -- (\text{kernel\_size}[2] - 1) - 1}{\text{stride}[2]} + 1\right\rfloor+ Args:+ mode: backend selection strategy.++ * ``"patch"`` β always use :func:`iterative_quad_interp3d`.+ * ``"conv"`` β always use :func:`conv_quad_interp3d`.+ * ``"auto"`` β use ``"conv"`` when the input is on a CUDA device,+ ``"patch"`` otherwise.++ n_iters: maximum localization iterations per keypoint.+ strict_maxima_bonus: score bonus added at NMS-maximum positions.+ max_subpixel_shift: integer-centre move threshold.+ dilation_radius: L\ :math:`\infty` precompute radius for ``"conv"`` mode+ (ignored in ``"patch"`` mode).+ max_candidates: if set, only the top-``max_candidates`` NMS maxima by+ pre-refinement response are processed in ``"patch"`` mode. Has no effect+ in ``"conv"`` mode. Useful on CPU when the number of 3-D NMS maxima greatly+ exceeds the desired number of keypoints (see :func:`iterative_quad_interp3d`).- Examples:- >>> input = torch.randn(20, 16, 3, 50, 32)- >>> nms_coords, nms_val = conv_quad_interp3d(input, 1.0)+ Example:+ >>> inp = torch.randn(1, 1, 3, 64, 64)+ >>> subpix = AdaptiveQuadInterp3d(mode="auto")+ >>> coords, vals = subpix(inp)+ >>> coords.shape+ torch.Size([1, 1, 3, 3, 64, 64])+ >>> vals.shape+ torch.Size([1, 1, 3, 64, 64])"""- if not torch.is_tensor(input):- raise TypeError(f"Input type is not a torch.Tensor. Got {type(input)}")-- if not len(input.shape) == 5:- raise ValueError(f"Invalid input shape, we expect BxCxDxHxW. Got: {input.shape}")-- B, CH, D, H, W = input.shape- grid_global: torch.Tensor = create_meshgrid3d(D, H, W, False, device=input.device).permute(0, 4, 1, 2, 3)- grid_global = grid_global.to(input.dtype)-- # to determine the location we are solving system of linear equations Ax = b, where b is 1st order gradient- # and A is Hessian matrix- b: torch.Tensor = spatial_gradient3d(input, order=1, mode="diff")- b = b.permute(0, 1, 3, 4, 5, 2).reshape(-1, 3, 1)- A: torch.Tensor = spatial_gradient3d(input, order=2, mode="diff")- A = A.permute(0, 1, 3, 4, 5, 2).reshape(-1, 6)- dxx = A[..., 0]- dyy = A[..., 1]- dss = A[..., 2]- dxy = 0.25 * A[..., 3] # normalization to match OpenCV implementation- dys = 0.25 * A[..., 4] # normalization to match OpenCV implementation- dxs = 0.25 * A[..., 5] # normalization to match OpenCV implementation-- nms_mask: torch.Tensor = nms3d(input, (3, 3, 3), True)- x_solved: torch.Tensor = torch.zeros_like(b)-- # Solve H * x = b for NMS points via Cramer's rule (avoids LU factorization + matrix construction).- nms_flat = nms_mask.view(-1)- b_nms = b[nms_flat, :, 0] # (N_nms, 3)- sx, sy, ss, solved_correctly = _solve_cramer_sym3x3(- dxx[nms_flat],- dyy[nms_flat],- dss[nms_flat],- dxy[nms_flat],- dxs[nms_flat],- dys[nms_flat],- b_nms[:, 0],- b_nms[:, 1],- b_nms[:, 2],- eps=eps,- )- x_solved_masked = torch.stack([sx, sy, ss], dim=-1).unsqueeze(-1) # (N_nms, 3, 1)-- # Kill those points, where we cannot solve- new_nms_mask = nms_mask.masked_scatter(nms_mask, solved_correctly)-- x_solved[torch.where(new_nms_mask.view(-1, 1, 1))[0]] = x_solved_masked[solved_correctly]-- dx: torch.Tensor = -x_solved-- # Ignore torch.ones, which are far from window center- mask1 = dx.abs().max(dim=1, keepdim=True)[0] > 0.7- dx.masked_fill_(mask1.expand_as(dx), 0)- dy: torch.Tensor = 0.5 * torch.bmm(b.permute(0, 2, 1), dx)- y_max = input + dy.view(B, CH, D, H, W)- if strict_maxima_bonus > 0:- y_max += strict_maxima_bonus * new_nms_mask.to(input.dtype)-- dx_res: torch.Tensor = dx.flip(1).reshape(B, CH, D, H, W, 3).permute(0, 1, 5, 2, 3, 4)- dx_res[:, :, (1, 2)] = dx_res[:, :, (2, 1)]-- coords_max: torch.Tensor = grid_global.repeat(B, 1, 1, 1, 1).unsqueeze(1)- coords_max = coords_max + dx_res-- return coords_max, y_max--class ConvQuadInterp3d(nn.Module):- r"""Calculate soft argmax 3d per window.-- See- :func: `~kornia.geometry.subpix.conv_quad_interp3d` for details.- """+ MODES = ("patch", "conv", "auto")- def __init__(self, strict_maxima_bonus: float = 10.0, eps: float = 1e-7) -> None:+ def __init__(+ self,+ mode: str = "auto",+ n_iters: int = 5,+ strict_maxima_bonus: float = 10.0,+ max_subpixel_shift: float = 0.6,+ dilation_radius: int = 1,+ allow_scale_steps: bool = True,+ max_candidates: Optional[int] = None,+ ) -> None:super().__init__()+ if mode not in self.MODES:+ raise ValueError(f"mode must be one of {self.MODES}, got '{mode}'")+ self.mode = mode+ self.n_iters = n_itersself.strict_maxima_bonus = strict_maxima_bonus- self.eps = eps+ self.max_subpixel_shift = max_subpixel_shift+ self.dilation_radius = dilation_radius+ self.allow_scale_steps = allow_scale_steps+ self.max_candidates = max_candidatesdef __repr__(self) -> str:- return f"{self.__class__.__name__}(strict_maxima_bonus={self.strict_maxima_bonus})"+ return (+ f"{self.__class__.__name__}("+ f"mode='{self.mode}', "+ f"n_iters={self.n_iters}, "+ f"strict_maxima_bonus={self.strict_maxima_bonus}, "+ f"max_subpixel_shift={self.max_subpixel_shift}, "+ f"dilation_radius={self.dilation_radius}, "+ f"allow_scale_steps={self.allow_scale_steps}, "+ f"max_candidates={self.max_candidates})"+ )- def forward(self, x: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:- return conv_quad_interp3d(x, self.strict_maxima_bonus, self.eps)+ def forward(+ self,+ x: torch.Tensor,+ precomputed_nms_mask: Optional[torch.Tensor] = None,+ ) -> tuple[torch.Tensor, torch.Tensor]:+ use_conv = self.mode == "conv" or (self.mode == "auto" and x.is_cuda)+ if use_conv:+ return conv_quad_interp3d(+ x,+ self.n_iters,+ self.strict_maxima_bonus,+ self.max_subpixel_shift,+ precomputed_nms_mask,+ self.dilation_radius,+ self.allow_scale_steps,+ )+ return iterative_quad_interp3d(+ x,+ self.n_iters,+ self.strict_maxima_bonus,+ self.max_subpixel_shift,+ self.allow_scale_steps,+ precomputed_nms_mask=precomputed_nms_mask,+ max_candidates=self.max_candidates,+ )diff --git a/kornia/geometry/transform/pyramid.py b/kornia/geometry/transform/pyramid.pyindex 47aff9fd7..5dd153c78 100644--- a/kornia/geometry/transform/pyramid.py+++ b/kornia/geometry/transform/pyramid.py@@ -23,19 +23,10 @@ import torchimport torch.nn.functional as Ffrom torch import nn-from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE+from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SHAPEfrom kornia.filters import filter2d, gaussian_blur2d-__all__ = [- "PyrDown",- "PyrUp",- "ScalePyramid",- "build_laplacian_pyramid",- "build_pyramid",- "pyrdown",- "pyrup",- "upscale_double",-]+__all__ = ["PyrDown", "PyrUp", "ScalePyramid", "build_laplacian_pyramid", "build_pyramid", "pyrdown", "pyrup"]def _get_pyramid_gaussian_kernel() -> torch.Tensor:@@ -149,17 +140,23 @@ class ScalePyramid(nn.Module):"""def __init__(- self, n_levels: int = 3, init_sigma: float = 1.6, min_size: int = 15, double_image: bool = False+ self,+ n_levels: int = 3,+ init_sigma: float = 1.6,+ min_size: int = 15,+ double_image: bool = False,+ extra_levels: int = 3,) -> None:super().__init__()# 3 extra levels are needed for DoG nms.self.n_levels = n_levels- self.extra_levels: int = 3+ self.extra_levels = extra_levelsself.init_sigma = init_sigmaself.min_size = min_sizeself.border = min_size // 2 - 1self.sigma_step = 2 ** (1.0 / float(self.n_levels))self.double_image = double_image+ self._precompute_gauss_kernels(n_levels, extra_levels, init_sigma, double_image)def __repr__(self) -> str:return (@@ -173,6 +170,48 @@ class ScalePyramid(nn.Module):f"double_image={self.double_image})")+ @staticmethod+ def _make_gaussian_kernel1d(sigma: float, ksize: int) -> torch.Tensor:+ """Normalized 1D Gaussian kernel as a float32 tensor."""+ x = torch.arange(ksize, dtype=torch.float64) - ksize // 2+ kernel = torch.exp(-0.5 * x**2 / sigma**2)+ return (kernel / kernel.sum()).float()++ def _precompute_gauss_kernels(+ self, n_levels: int, extra_levels: int, init_sigma: float, double_image: bool+ ) -> None:+ """Register precomputed 1D Gaussian kernels as buffers so they move with .to()."""+ # Initial blur: from camera sigma (0.5 / 1.0) up to init_sigma+ cur_sigma_init = 1.0 if double_image else 0.5+ if init_sigma > cur_sigma_init:+ sigma = max(math.sqrt(init_sigma**2 - cur_sigma_init**2), 0.01)+ ksize = self.get_kernel_size(sigma)+ self.register_buffer("_gk_init", self._make_gaussian_kernel1d(sigma, ksize))+ else:+ self.register_buffer("_gk_init", None)++ # Level-to-level kernels inside an octave.+ # cur_sigma_oct resets to init_sigma at the start of every octave, so+ # these delta_sigma values are the SAME for every octave β precompute once.+ cur_s = init_sigma+ for lvl in range(n_levels + extra_levels - 1):+ delta = cur_s * math.sqrt(self.sigma_step**2 - 1.0)+ ksize = self.get_kernel_size(delta)+ self.register_buffer(f"_gk_{lvl}", self._make_gaussian_kernel1d(delta, ksize))+ cur_s *= self.sigma_step++ def _blur_fast(self, x: torch.Tensor, kernel: torch.Tensor) -> torch.Tensor:+ """Separable Gaussian blur with a precomputed 1D kernel β no validation overhead."""+ ksize = kernel.shape[0]+ pad = ksize // 2+ _B, C, _H, _W = x.shape+ k = kernel.to(dtype=x.dtype)+ # Depthwise separable: same kernel applied independently to every channel.+ k_h = k.view(1, 1, 1, ksize).expand(C, 1, 1, ksize).contiguous()+ tmp = F.conv2d(F.pad(x, (pad, pad, 0, 0), mode="reflect"), k_h, groups=C)+ k_v = k.view(1, 1, ksize, 1).expand(C, 1, ksize, 1).contiguous()+ return F.conv2d(F.pad(tmp, (0, 0, pad, pad), mode="reflect"), k_v, groups=C)+def get_kernel_size(self, sigma: float) -> int:ksize = int(2.0 * 4.0 * sigma + 1.0)@@ -189,7 +228,7 @@ class ScalePyramid(nn.Module):cur_sigma = 0.5# Same as in OpenCV up to interpolation differenceif self.double_image:- x = upscale_double(input)+ x = F.interpolate(input, scale_factor=2.0, mode="bilinear", align_corners=True)pixel_distance = 0.5cur_sigma *= 2.0else:@@ -198,7 +237,12 @@ class ScalePyramid(nn.Module):if self.init_sigma > cur_sigma:sigma = max(math.sqrt(self.init_sigma**2 - cur_sigma**2), 0.01)ksize = self.get_kernel_size(sigma)- cur_level = gaussian_blur2d(x, (ksize, ksize), (sigma, sigma))+ min_dim = min(x.size(2), x.size(3))+ if self._gk_init is not None and ksize <= min_dim:+ cur_level = self._blur_fast(x, self._gk_init)+ else:+ ksize = min(ksize, min_dim if min_dim % 2 == 1 else min_dim - 1)+ cur_level = gaussian_blur2d(x, (ksize, ksize), (sigma, sigma))cur_sigma = self.init_sigmaelse:cur_level = x@@ -208,42 +252,50 @@ class ScalePyramid(nn.Module):bs, _, _, _ = x.size()cur_level, cur_sigma, pixel_distance = self.get_first_level(x)- sigmas = [cur_sigma * torch.ones(bs, self.n_levels + self.extra_levels).to(x.device).to(x.dtype)]- pixel_dists = [pixel_distance * torch.ones(bs, self.n_levels + self.extra_levels).to(x.device).to(x.dtype)]+ sigmas = [torch.full((bs, self.n_levels + self.extra_levels), cur_sigma, device=x.device, dtype=x.dtype)]+ pixel_dists = [+ torch.full((bs, self.n_levels + self.extra_levels), pixel_distance, device=x.device, dtype=x.dtype)+ ]pyr = [[cur_level]]- oct_idx = 0+while True:- cur_level = pyr[-1][0]+ # Build octave levels incrementally: each level is a Gaussian blur of+ # the previous one. This matches VLFeat's level-to-level construction+ # and avoids discrete truncation artefacts in DoG differences.+ cur_sigma_oct = self.init_sigma # sigma of pyr[-1][0] in current octave pixelsfor level_idx in range(1, self.n_levels + self.extra_levels):- sigma = cur_sigma * math.sqrt(self.sigma_step**2 - 1.0)- ksize = self.get_kernel_size(sigma)-- # Hack, because PyTorch does not allow to F.pad more than original size.- # But for the huge sigmas, one needs huge kernel and padding...-- ksize = min(ksize, cur_level.size(2), cur_level.size(3))- if ksize % 2 == 0:- ksize += 1-- cur_level = gaussian_blur2d(cur_level, (ksize, ksize), (sigma, sigma))- cur_sigma *= self.sigma_step- pyr[-1].append(cur_level)- sigmas[-1][:, level_idx] = cur_sigma+ kernel = getattr(self, f"_gk_{level_idx - 1}")+ min_dim = min(pyr[-1][-1].size(2), pyr[-1][-1].size(3))+ if kernel.shape[0] <= min_dim:+ new_level = self._blur_fast(pyr[-1][-1], kernel)+ else:+ # Tiny image: clamp kernel size and fall back to the validated path.+ delta_sigma = cur_sigma_oct * math.sqrt(self.sigma_step**2 - 1.0)+ ksize = min_dim if min_dim % 2 == 1 else min_dim - 1+ new_level = gaussian_blur2d(pyr[-1][-1], (ksize, ksize), (delta_sigma, delta_sigma))+ cur_sigma_oct *= self.sigma_step+ pyr[-1].append(new_level)+ sigmas[-1][:, level_idx] = cur_sigma_octpixel_dists[-1][:, level_idx] = pixel_distance- _pyr = pyr[-1][-self.extra_levels]- nextOctaveFirstLevel = _pyr[:, :, ::2, ::2]- pixel_distance *= 2.0- cur_sigma = self.init_sigma- if min(nextOctaveFirstLevel.size(2), nextOctaveFirstLevel.size(3)) <= self.min_size:+ # Seed next octave: bilinear 2x downscale of the (-extra_levels) level.+ # Bilinear resampling is more accurate than integer-stride decimation.+ _pyr = pyr[-1][-self.extra_levels]+ H, W = _pyr.shape[2], _pyr.shape[3]+ if min(H // 2, W // 2) <= self.min_size:break+ H_new, W_new = H // 2, W // 2+ nextOctaveFirstLevel = F.interpolate(_pyr, size=(H_new, W_new), mode="bilinear", align_corners=True)+ pixel_distance *= 2.0pyr.append([nextOctaveFirstLevel])- sigmas.append(cur_sigma * torch.ones(bs, self.n_levels + self.extra_levels).to(x.device))- pixel_dists.append(pixel_distance * torch.ones(bs, self.n_levels + self.extra_levels).to(x.device))- oct_idx += 1+ sigmas.append(+ torch.full((bs, self.n_levels + self.extra_levels), self.init_sigma, device=x.device, dtype=x.dtype)+ )+ pixel_dists.append(+ torch.full((bs, self.n_levels + self.extra_levels), pixel_distance, device=x.device, dtype=x.dtype)+ )output_pyr = [torch.stack(i, 2) for i in pyr]-return output_pyr, sigmas, pixel_dists@@ -432,28 +484,3 @@ def build_laplacian_pyramid(laplacian_pyramid.append(laplacian)laplacian_pyramid.append(gaussian_pyramid[-1])return laplacian_pyramid---def upscale_double(x: torch.Tensor) -> torch.Tensor:- r"""Upscale image by the factor of 2, even indices maps to original indices.-- Odd indices are linearly interpolated from the even torch.ones.-- Args:- x: input image.-- Shape:- - Input: :math:`(*, H, W)`- - Output :math:`(*, H, W)`-- """- KORNIA_CHECK_IS_TENSOR(x)- KORNIA_CHECK_SHAPE(x, ["*", "H", "W"])- double_shape = x.shape[:-2] + (x.shape[-2] * 2, x.shape[-1] * 2)- upscaled = torch.zeros(double_shape, device=x.device, dtype=x.dtype)- upscaled[..., ::2, ::2] = x- upscaled[..., ::2, 1::2][..., :-1] = (upscaled[..., ::2, ::2][..., :-1] + upscaled[..., ::2, 2::2]) / 2- upscaled[..., ::2, -1] = upscaled[..., ::2, -2]- upscaled[..., 1::2, :][..., :-1, :] = (upscaled[..., ::2, :][..., :-1, :] + upscaled[..., 2::2, :]) / 2- upscaled[..., -1, :] = upscaled[..., -2, :]- return upscaleddiff --git a/tests/feature/test_scale_space_detector.py b/tests/feature/test_scale_space_detector.pyindex 58a0727aa..19688ac7b 100644--- a/tests/feature/test_scale_space_detector.py+++ b/tests/feature/test_scale_space_detector.py@@ -19,6 +19,7 @@ import torchimport korniafrom kornia.feature.scale_space_detector import ScaleSpaceDetector+from kornia.geometry.subpix import ConvQuadInterp3dfrom testing.base import BaseTester@@ -46,8 +47,8 @@ class TestScaleSpaceDetector(BaseTester):n_feats = 1det = ScaleSpaceDetector(n_feats, resp_module=kornia.feature.BlobHessian(), mr_size=3.0).to(device, dtype)lafs, resps = det(inp)- expected_laf = torch.tensor([[[[9.5823, 0.0000, 16.0], [0.0, 9.5823, 16.0]]]], device=device, dtype=dtype)- expected_resp = torch.tensor([[0.0857]], device=device, dtype=dtype)+ expected_laf = torch.tensor([[[[8.4260, 0.0000, 16.0], [0.0, 8.4260, 16.0]]]], device=device, dtype=dtype)+ expected_resp = torch.tensor([[0.1159]], device=device, dtype=dtype)self.assert_close(lafs, expected_laf, rtol=0.001, atol=1e-03)self.assert_close(resps, expected_resp, rtol=0.001, atol=1e-03)@@ -61,12 +62,15 @@ class TestScaleSpaceDetector(BaseTester):n_feats = 1det = ScaleSpaceDetector(n_feats, resp_module=kornia.feature.BlobHessian(), mr_size=3.0).to(device, dtype)lafs, resps = det(inp, mask)- expected_laf = torch.tensor([[[[9.5823, 0.0000, 16.0], [0.0, 9.5823, 16.0]]]], device=device, dtype=dtype)- expected_resp = torch.tensor([[0.0857]], device=device, dtype=dtype)+ expected_laf = torch.tensor([[[[8.4260, 0.0000, 16.0], [0.0, 8.4260, 16.0]]]], device=device, dtype=dtype)+ expected_resp = torch.tensor([[0.1159]], device=device, dtype=dtype)self.assert_close(lafs, expected_laf, rtol=0.001, atol=1e-03)self.assert_close(resps, expected_resp, rtol=0.001, atol=1e-03)def test_gradcheck(self, device):batch_size, channels, height, width = 1, 1, 7, 7patches = torch.rand(batch_size, channels, height, width, device=device, dtype=torch.float64)- self.gradcheck(ScaleSpaceDetector(2).to(device), patches, nondet_tol=1e-4)+ # Use ConvQuadInterp3d for gradcheck β IterativeQuadInterp3d uses non-differentiable+ # indexed in-place assignments that are incompatible with torch.autograd.gradcheck.+ det = ScaleSpaceDetector(2, subpix_module=ConvQuadInterp3d(10)).to(device)+ self.gradcheck(det, patches, nondet_tol=1e-4)diff --git a/tests/geometry/subpix/test_iterative_quad_interp_pyhesaff.py b/tests/geometry/subpix/test_iterative_quad_interp_pyhesaff.pyindex 4cbbb712c..1d4aee9e3 100644--- a/tests/geometry/subpix/test_iterative_quad_interp_pyhesaff.py+++ b/tests/geometry/subpix/test_iterative_quad_interp_pyhesaff.py@@ -15,10 +15,10 @@# limitations under the License.#-"""Reference tests for iterative_quad_interp3d.+"""Reference tests for conv_quad_interp3d.These tests verify that the subpixel localisation implemented in-``iterative_quad_interp3d`` agrees with the single-step C++ HessAff+``conv_quad_interp3d`` agrees with the single-step C++ HessAff``localizeKeypoint`` formula (ported here in pure Python/NumPy).A synthetic 3-scale Gaussian response map is used as input so that the@@ -33,7 +33,7 @@ import pytestimport torchfrom kornia.geometry.subpix.nms import nms3d-from kornia.geometry.subpix.spatial_soft_argmax import iterative_quad_interp3d+from kornia.geometry.subpix.spatial_soft_argmax import conv_quad_interp3d# ---------------------------------------------------------------------------# Helpers@@ -106,7 +106,7 @@ class TestIterativeQuadInterp3dVsRefFormula:assert nms3d(resp_t, (3, 3, 3), True).sum().item() >= 1, "no NMS peak found"# Our function β one iteration keeps the initial integer position- coords, _ = iterative_quad_interp3d(resp_t, n_iters=1, strict_maxima_bonus=0)+ coords, _ = conv_quad_interp3d(resp_t, n_iters=1, strict_maxima_bonus=0)# Reference: apply the C++ formula to the numpy arraysresp_np = resp_t.cpu().float().numpy()[0, 0] # (3, H, W)@@ -135,7 +135,7 @@ class TestIterativeQuadInterp3dVsRefFormula:class TestIterativeQuadInterp3dAccuracy:- """Verify that iterative_quad_interp3d accurately recovers subpixel positions."""+ """Verify that conv_quad_interp3d accurately recovers subpixel positions."""def _run(self, cx: float, cy: float, cs: float, device: torch.device, dtype: torch.dtype) -> None:resp_t = _make_3d_gauss_response(19, 19, cx, cy, cs).to(device=device, dtype=dtype)@@ -143,7 +143,7 @@ class TestIterativeQuadInterp3dAccuracy:nms_mask = nms3d(resp_t, (3, 3, 3), True)assert nms_mask.sum().item() >= 1, "no NMS peak"- coords, _ = iterative_quad_interp3d(resp_t, strict_maxima_bonus=0)+ coords, _ = conv_quad_interp3d(resp_t, strict_maxima_bonus=0)d_peak = 1h_peak, w_peak = round(cy), round(cx)ours_x = coords[0, 0, 1, d_peak, h_peak, w_peak].item()@@ -165,7 +165,7 @@ class TestIterativeQuadInterp3dAccuracy:"""Blob at an integer position β recovered coords should be very close to integer."""cx, cy, cs = 9.0, 9.0, 1.0resp_t = _make_3d_gauss_response(19, 19, cx, cy, cs)- coords, _ = iterative_quad_interp3d(resp_t, strict_maxima_bonus=0)+ coords, _ = conv_quad_interp3d(resp_t, strict_maxima_bonus=0)d_peak = 1h_peak, w_peak = round(cy), round(cx)ours_x = coords[0, 0, 1, d_peak, h_peak, w_peak].item()@@ -186,7 +186,7 @@ class TestIterativeQuadInterp3dAccuracy:resp_np[d] += np.exp(-((xx - bx) ** 2 + (yy - by) ** 2) / (2 * 1.5**2) - (d - bs) ** 2 / (2 * 1.0**2))resp_t = torch.from_numpy(resp_np).unsqueeze(0).unsqueeze(0)- coords, _ = iterative_quad_interp3d(resp_t, strict_maxima_bonus=0)+ coords, _ = conv_quad_interp3d(resp_t, strict_maxima_bonus=0)d_peak = 1for bx, by, _ in blobs:h_int, w_int = round(by), round(bx)diff --git a/tests/geometry/subpix/test_nms.py b/tests/geometry/subpix/test_nms.pyindex 076fc0187..8dec998b9 100644--- a/tests/geometry/subpix/test_nms.py+++ b/tests/geometry/subpix/test_nms.py@@ -150,3 +150,33 @@ class TestNMS3d(BaseTester):batch_size, channels, depth, height, width = 1, 1, 4, 5, 4img = torch.rand(batch_size, channels, depth, height, width, device=device, dtype=torch.float64)self.gradcheck(kornia.geometry.subpix.nms3d, (img, (3, 3, 3)), nondet_tol=1e-4)+++class TestNMS3dMinMax(BaseTester):+ def test_shapes(self, device):+ inp = torch.randn(1, 1, 5, 10, 10, device=device)+ max_mask, min_mask = kornia.geometry.subpix.nms3d_minmax(inp)+ assert max_mask.shape == inp.shape+ assert min_mask.shape == inp.shape+ assert max_mask.dtype == torch.bool+ assert min_mask.dtype == torch.bool++ def test_consistent_with_nms3d(self, device):+ """nms3d_minmax must match nms3d(x) and nms3d(-x) exactly."""+ inp = torch.randn(2, 3, 7, 12, 12, device=device)+ max_mask, min_mask = kornia.geometry.subpix.nms3d_minmax(inp)+ max_ref = kornia.geometry.subpix.nms3d(inp, (3, 3, 3), mask_only=True)+ min_ref = kornia.geometry.subpix.nms3d(-inp, (3, 3, 3), mask_only=True)+ assert max_mask.equal(max_ref), "max mask mismatch"+ assert min_mask.equal(min_ref), "min mask mismatch"++ def test_no_overlap(self, device):+ """A voxel cannot be both a strict local maximum and minimum."""+ inp = torch.randn(1, 1, 5, 10, 10, device=device)+ max_mask, min_mask = kornia.geometry.subpix.nms3d_minmax(inp)+ assert not (max_mask & min_mask).any()++ def test_gradcheck(self, device):+ # nms3d_minmax is not differentiable (bool masks), so we just check it runs.+ inp = torch.randn(1, 1, 5, 7, 7, device=device)+ kornia.geometry.subpix.nms3d_minmax(inp)diff --git a/tests/geometry/subpix/test_spatial_softargmax.py b/tests/geometry/subpix/test_spatial_softargmax.pyindex ce0cd7ee9..b56275f64 100644--- a/tests/geometry/subpix/test_spatial_softargmax.py+++ b/tests/geometry/subpix/test_spatial_softargmax.py@@ -23,7 +23,7 @@ import korniafrom kornia.geometry.subpix.spatial_soft_argmax import (_get_center_kernel2d,_get_center_kernel3d,- iterative_quad_interp3d,+ conv_quad_interp3d,)from testing.base import BaseTester@@ -462,7 +462,7 @@ class TestConvSoftArgmax3d(BaseTester):self.assert_close(coords, expected_coord, atol=1e-4, rtol=1e-4)-class TestConvQuadInterp3d(BaseTester):+class TestConvQuadInterp3dModule(BaseTester):def test_smoke(self, device, dtype):sample = torch.randn(2, 3, 3, 4, 4, device=device, dtype=dtype)nms = kornia.geometry.ConvQuadInterp3d(1)@@ -622,24 +622,24 @@ class TestConvQuadInterp3d(BaseTester):self.assert_close(coords, expected_coord, atol=1e-4, rtol=1e-4)-class TestIterativeQuadInterp3d(BaseTester):+class TestConvQuadInterp3d(BaseTester):def test_smoke(self, device, dtype):sample = torch.randn(2, 3, 3, 4, 4, device=device, dtype=dtype)- op = kornia.geometry.IterativeQuadInterp3d(n_iters=3, strict_maxima_bonus=1)+ op = kornia.geometry.subpix.ConvQuadInterp3d(n_iters=3, strict_maxima_bonus=1)coord, val = op(sample)assert coord.shape == (2, 3, 3, 3, 4, 4)assert val.shape == (2, 3, 3, 4, 4)def test_exception(self, device, dtype):with pytest.raises(TypeError):- iterative_quad_interp3d("not_a_tensor")+ conv_quad_interp3d("not_a_tensor")with pytest.raises(ValueError):- iterative_quad_interp3d(torch.randn(3, 4, 4, device=device, dtype=dtype))+ conv_quad_interp3d(torch.randn(3, 4, 4, device=device, dtype=dtype))def test_cardinality(self, device, dtype):for B, C, D, H, W in [(1, 1, 3, 5, 5), (2, 4, 3, 8, 6)]:sample = torch.randn(B, C, D, H, W, device=device, dtype=dtype)- coord, val = iterative_quad_interp3d(sample)+ coord, val = conv_quad_interp3d(sample)assert coord.shape == (B, C, 3, D, H, W)assert val.shape == (B, C, D, H, W)@@ -647,7 +647,7 @@ class TestIterativeQuadInterp3d(BaseTester):sample = torch.rand(1, 1, 3, 5, 5, device=device, dtype=torch.float64)sample[0, 0, 1, 2, 2] += 20.0self.gradcheck(- kornia.geometry.IterativeQuadInterp3d(strict_maxima_bonus=0, n_iters=1),+ kornia.geometry.subpix.ConvQuadInterp3d(strict_maxima_bonus=0, n_iters=1),(sample,),atol=1e-3,rtol=1e-3,@@ -656,7 +656,7 @@ class TestIterativeQuadInterp3d(BaseTester):def test_dynamo(self, device, dtype, torch_optimizer):sample = torch.rand(1, 1, 3, 5, 5, device=device, dtype=dtype)sample[0, 0, 1, 2, 2] += 20.0- op = kornia.geometry.IterativeQuadInterp3d(strict_maxima_bonus=0, n_iters=1)+ op = kornia.geometry.subpix.ConvQuadInterp3d(strict_maxima_bonus=0, n_iters=1)op_opt = torch_optimizer(op)self.assert_close(op(sample)[0], op_opt(sample)[0])self.assert_close(op(sample)[1], op_opt(sample)[1])@@ -665,7 +665,7 @@ class TestIterativeQuadInterp3d(BaseTester):# A clear peak at scale=1, h=2, w=2 should return coords close to (1, 2, 2).sample = torch.zeros(1, 1, 3, 5, 5, device=device, dtype=dtype)sample[0, 0, 1, 2, 2] = 10.0- coord, _val = iterative_quad_interp3d(sample, strict_maxima_bonus=0)+ coord, _val = conv_quad_interp3d(sample, strict_maxima_bonus=0)# coords_max layout: dim2 = [scale, x(width), y(height)]assert coord[0, 0, 0, 1, 2, 2].item() == pytest.approx(1.0, abs=1e-3) # scaleassert coord[0, 0, 1, 1, 2, 2].item() == pytest.approx(2.0, abs=1e-3) # x@@ -681,7 +681,7 @@ class TestIterativeQuadInterp3d(BaseTester):for dw in range(-1, 2):dist2 = (dd - 0.2) ** 2 + (dh - 0.1) ** 2 + (dw + 0.15) ** 2sample[0, 0, 2 + dd, 3 + dh, 3 + dw] += float(torch.exp(torch.tensor(-dist2 * 4)))- coord, _ = iterative_quad_interp3d(sample, strict_maxima_bonus=0)+ coord, _ = conv_quad_interp3d(sample, strict_maxima_bonus=0)# The refined x (width) coord at the integer peak (d=2, h=3, w=3) should shift toward -0.15.x_coord = coord[0, 0, 1, 2, 3, 3].item()assert x_coord < 3.0 # shift in negative x direction@@ -689,7 +689,7 @@ class TestIterativeQuadInterp3d(BaseTester):def test_no_keypoints(self, device, dtype):# Flat input β no NMS maxima, output should equal input coords/values.sample = torch.ones(1, 1, 3, 4, 4, device=device, dtype=dtype)- coord, val = iterative_quad_interp3d(sample, strict_maxima_bonus=0)+ coord, val = conv_quad_interp3d(sample, strict_maxima_bonus=0)assert coord.shape == (1, 1, 3, 3, 4, 4)assert val.shape == (1, 1, 3, 4, 4)@@ -697,6 +697,97 @@ class TestIterativeQuadInterp3d(BaseTester):# With a clear symmetric peak a single iteration should converge.sample = torch.zeros(1, 1, 3, 5, 5, device=device, dtype=dtype)sample[0, 0, 1, 2, 2] = 5.0- coord1, _ = iterative_quad_interp3d(sample, n_iters=1, strict_maxima_bonus=0)- coord5, _ = iterative_quad_interp3d(sample, n_iters=5, strict_maxima_bonus=0)+ coord1, _ = conv_quad_interp3d(sample, n_iters=1, strict_maxima_bonus=0)+ coord5, _ = conv_quad_interp3d(sample, n_iters=5, strict_maxima_bonus=0)self.assert_close(coord1, coord5, atol=1e-5, rtol=1e-5)+++class TestAdaptiveQuadInterp3d(BaseTester):+ def test_smoke(self, device, dtype):+ for mode in ("patch", "conv", "auto"):+ x = torch.randn(1, 1, 3, 8, 8, device=device, dtype=dtype)+ coords, vals = kornia.geometry.subpix.AdaptiveQuadInterp3d(mode=mode)(x)+ assert coords.shape == (1, 1, 3, 3, 8, 8)+ assert vals.shape == (1, 1, 3, 8, 8)++ def test_invalid_mode(self, device, dtype):+ with pytest.raises(ValueError, match="mode must be one of"):+ kornia.geometry.subpix.AdaptiveQuadInterp3d(mode="bogus")++ def test_patch_conv_agree(self, device, dtype):+ """patch and conv backends must produce numerically identical results."""+ torch.manual_seed(7)+ x = torch.randn(1, 1, 5, 16, 16, device=device, dtype=dtype)+ coords_p, vals_p = kornia.geometry.subpix.AdaptiveQuadInterp3d(mode="patch", strict_maxima_bonus=0)(x)+ coords_c, vals_c = kornia.geometry.subpix.AdaptiveQuadInterp3d(mode="conv", strict_maxima_bonus=0)(x)+ from kornia.geometry.subpix import nms3d++ mask = nms3d(x, (3, 3, 3), True)+ b, c, d, h, w = torch.where(mask)+ self.assert_close(coords_p[b, c, :, d, h, w], coords_c[b, c, :, d, h, w], atol=1e-5, rtol=1e-5)+ self.assert_close(vals_p[b, c, d, h, w], vals_c[b, c, d, h, w], atol=1e-5, rtol=1e-5)++ def test_auto_dispatches(self, device, dtype):+ """auto mode must use conv on CUDA, patch on CPU (verified via result equality)."""+ x = torch.randn(1, 1, 3, 8, 8, device=device, dtype=dtype)+ auto = kornia.geometry.subpix.AdaptiveQuadInterp3d(mode="auto", strict_maxima_bonus=0)+ expected_mode = "conv" if x.is_cuda else "patch"+ ref = kornia.geometry.subpix.AdaptiveQuadInterp3d(mode=expected_mode, strict_maxima_bonus=0)+ self.assert_close(auto(x)[0], ref(x)[0], atol=1e-5, rtol=1e-5)+ self.assert_close(auto(x)[1], ref(x)[1], atol=1e-5, rtol=1e-5)++ def test_gradcheck(self, device):+ x = torch.zeros(1, 1, 3, 5, 5, device=device, dtype=torch.float64)+ x[0, 0, 1, 2, 2] = 5.0+ self.gradcheck(+ kornia.geometry.subpix.AdaptiveQuadInterp3d(mode="patch", strict_maxima_bonus=0),+ (x,),+ atol=1e-3,+ rtol=1e-3,+ )++ def test_dynamo(self, device, dtype, torch_optimizer):+ x = torch.rand(1, 1, 3, 5, 5, device=device, dtype=dtype)+ x[0, 0, 1, 2, 2] += 20.0+ op = kornia.geometry.subpix.AdaptiveQuadInterp3d(mode="patch", strict_maxima_bonus=0)+ op_opt = torch_optimizer(op)+ self.assert_close(op(x)[0], op_opt(x)[0])++ def test_conv_matches_iterative(self, device, dtype):+ """conv_quad_interp3d and iterative_quad_interp3d must give identical results at NMS maxima.++ Regression test for the c000_safe normalisation bug: dividing the Hessian by |centre|+ before the det-threshold check made conv accept poorly-conditioned positions that+ iterative correctly rejected, causing up to ~1 px coordinate divergence.+ """+ from kornia.geometry.subpix.nms import nms3d_minmax+ from kornia.geometry.subpix.spatial_soft_argmax import conv_quad_interp3d, iterative_quad_interp3d++ torch.manual_seed(7)+ B, C, D, H, W = 1, 1, 5, 32, 32+ # Synthetic DoG-like response: mix of positive and negative small-amplitude blobs+ x = torch.zeros(B, C, D, H, W, device=device, dtype=dtype)+ for d0, h0, w0, sign, amp in [(2, 8, 10, 1, 0.008), (2, 22, 16, -1, 0.005), (3, 14, 24, 1, 0.012)]:+ dd = torch.arange(D, device=device, dtype=dtype) - d0+ dh = torch.arange(H, device=device, dtype=dtype) - h0+ dw = torch.arange(W, device=device, dtype=dtype) - w0+ x[0, 0] += (+ sign+ * amp+ * (+ torch.exp(-0.5 * dd**2).view(D, 1, 1)+ * torch.exp(-0.5 * (dh / 2.5) ** 2).view(1, H, 1)+ * torch.exp(-0.5 * (dw / 2.5) ** 2).view(1, 1, W)+ )+ )++ max_mask, _ = nms3d_minmax(x)+ coord_conv, _ = conv_quad_interp3d(+ x, n_iters=5, strict_maxima_bonus=0.0, precomputed_nms_mask=max_mask, dilation_radius=3+ )+ coord_iter, _ = iterative_quad_interp3d(x, n_iters=5, strict_maxima_bonus=0.0)++ d_idx, h_idx, w_idx = torch.where(max_mask.view(D, H, W))+ 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)diff --git a/tests/geometry/test_ransac.py b/tests/geometry/test_ransac.pyindex d549a19bd..5451b2e22 100644--- a/tests/geometry/test_ransac.py+++ b/tests/geometry/test_ransac.py@@ -319,3 +319,52 @@ class TestRansacMethods:x2 = RANSAC.max_samples_by_conf(n_inl=500, num_tc=1000, sample_size=4, conf=conf)x3 = RANSAC.max_samples_by_conf(n_inl=800, num_tc=1000, sample_size=4, conf=conf)assert x1 > x2 > x3 # More inliers = fewer samples needed+++class TestRANSACSeed:+ def test_same_seed_reproducible(self, device, dtype):+ """Same seed should produce identical results across two calls."""+ torch.manual_seed(42)+ points1 = torch.rand(20, 2, device=device, dtype=dtype)+ points2 = torch.rand(20, 2, device=device, dtype=dtype)++ ransac = RANSAC("homography", inl_th=2.0, max_iter=5, seed=123).to(device=device, dtype=dtype)+ H1, inliers1 = ransac(points1, points2)+ H2, inliers2 = ransac(points1, points2)++ assert torch.allclose(H1, H2)+ assert torch.equal(inliers1, inliers2)++ def test_different_seeds_differ(self, device, dtype):+ """Different seeds should (very likely) produce different results."""+ torch.manual_seed(42)+ points1 = torch.rand(20, 2, device=device, dtype=dtype)+ points2 = torch.rand(20, 2, device=device, dtype=dtype)++ ransac_a = RANSAC("homography", inl_th=2.0, max_iter=5, seed=1).to(device=device, dtype=dtype)+ ransac_b = RANSAC("homography", inl_th=2.0, max_iter=5, seed=2).to(device=device, dtype=dtype)++ H_a, _ = ransac_a(points1, points2)+ H_b, _ = ransac_b(points1, points2)++ assert not torch.allclose(H_a, H_b)++ def test_no_seed_differs_from_seeded(self, device, dtype):+ """Without a seed, repeated calls should not be forced to be identical to a seeded call."""+ torch.manual_seed(0)+ points1 = torch.rand(20, 2, device=device, dtype=dtype)+ points2 = torch.rand(20, 2, device=device, dtype=dtype)++ ransac_seeded = RANSAC("homography", inl_th=2.0, max_iter=5, seed=42).to(device=device, dtype=dtype)+ H_s1, _ = ransac_seeded(points1, points2)+ H_s2, _ = ransac_seeded(points1, points2)+ # Seeded should be reproducible+ assert torch.allclose(H_s1, H_s2)++ def test_seed_stored_as_attribute(self, device, dtype):+ ransac = RANSAC("homography", seed=7)+ assert ransac.seed == 7++ def test_none_seed_stored(self, device, dtype):+ ransac = RANSAC("homography")+ assert ransac.seed is Nonediff --git a/tests/geometry/transform/test_pyramid.py b/tests/geometry/transform/test_pyramid.pyindex cdd41733e..8f0e17ef9 100644--- a/tests/geometry/transform/test_pyramid.py+++ b/tests/geometry/transform/test_pyramid.py@@ -183,105 +183,3 @@ class TestBuildLaplacianPyramid(BaseTester):batch_size, channels, height, width = 1, 2, 7, 9img = torch.rand(batch_size, channels, height, width, device=device, dtype=torch.float64)self.gradcheck(kornia.geometry.transform.build_laplacian_pyramid, (img, max_level), nondet_tol=1e-8)---class TestUpscaleDouble(BaseTester):- @pytest.mark.parametrize("shape", ((5, 5), (2, 5, 5), (1, 2, 5, 5)))- def test_smoke(self, shape, device, dtype):- x = self.prepare_data(shape, device, dtype)- assert kornia.geometry.transform.upscale_double(x) is not None-- def test_exception(self):- from kornia.core.exceptions import TypeCheckError-- with pytest.raises(TypeCheckError):- kornia.geometry.transform.upscale_double(None)-- @pytest.mark.parametrize("shape", ((5, 5), (2, 5, 5), (1, 2, 5, 5)))- def test_cardinality(self, shape, device, dtype):- x = self.prepare_data(shape, device, dtype)- actual = kornia.geometry.transform.upscale_double(x)-- h, w = shape[-2:]- expected = (*shape[:-2], h * 2, w * 2)-- assert tuple(actual.shape) == expected-- def test_dynamo(self, device, dtype, torch_optimizer):- img = self.prepare_data((1, 2, 5, 5), device, dtype)- op = kornia.geometry.transform.upscale_double- op_optimized = torch_optimizer(op)- self.assert_close(op(img), op_optimized(img))-- @pytest.mark.grad()- def test_gradcheck(self, device):- x = self.prepare_data((1, 2, 5, 5), device)- self.gradcheck(kornia.geometry.transform.upscale_double, (x,), rtol=5e-2)-- @pytest.mark.parametrize("shape", ((5, 5), (2, 5, 5), (1, 2, 5, 5)))- def test_upscale_double_and_back(self, shape, device, dtype):- x = self.prepare_data(shape, device, dtype)- upscaled = kornia.geometry.transform.upscale_double(x)-- expected = torch.tensor(- [- [- [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],- [0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5],- [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0],- [1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5],- [2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0],- [2.5, 2.5, 2.5, 2.5, 2.5, 2.5, 2.5, 2.5, 2.5, 2.5],- [3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0],- [3.5, 3.5, 3.5, 3.5, 3.5, 3.5, 3.5, 3.5, 3.5, 3.5],- [4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0],- [4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0],- ],- [- [0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.0],- [0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.0],- [0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.0],- [0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.0],- [0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.0],- [0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.0],- [0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.0],- [0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.0],- [0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.0],- [0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.0],- ],- ],- device=device,- dtype=dtype,- )-- if len(shape) == 2:- expected = expected[0]- elif len(shape) == 4:- expected = expected[None]-- self.assert_close(upscaled, expected)-- downscaled_back = upscaled[..., ::2, ::2]- self.assert_close(x, downscaled_back)-- @staticmethod- def prepare_data(shape, device, dtype=torch.float32):- xm = torch.tensor(- [[0, 0, 0, 0, 0], [1, 1, 1, 1, 1], [2, 2, 2, 2, 2], [3, 3, 3, 3, 3], [4, 4, 4, 4, 4]],- device=device,- dtype=dtype,- )- ym = torch.tensor(- [[0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4]],- device=device,- dtype=dtype,- )-- x = torch.zeros(shape, device=device, dtype=dtype)- if len(shape) == 2:- x = xm- else:- x[..., 0, :, :] = xm- x[..., 1, :, :] = ym-- return x