Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(feature): AdaLAM dm and device, LAF helpers keep padding and caller modules, validate inputs (#5726)

Dmytro Mishkinedf4207450d5
diff --git a/changelog.d/5726.fixed.md b/changelog.d/5726.fixed.md
new file mode 100644
index 000000000..ce54eb85d
--- /dev/null
+++ b/changelog.d/5726.fixed.md
@@ -0,0 +1,11 @@
+`match_adalam(dm=...)` now uses the distance matrix for the nearest-neighbour matches and their ratio scores; the argument was documented but never read, so any `dm` gave the same matches as no `dm`. `dm` holds plain (not squared) distances, like the `dm` of the other matchers, and AdaLAM squares it internally, so `dm=torch.cdist(desc1, desc2)` gives the matches of `dm=None`, which uses the squared L2 distances as before. A `dm` of the wrong shape raises.
+
+`match_adalam` with a `config` that does not set `"device"`, and `GeometryAwareDescriptorMatcher("adalam")`, now run on the device of the descriptors; they used to move everything to the CPU and return CPU tensors for CUDA or MPS input. The unique-pair step no longer needs `torch.unique(dim=0)`, which torch 2.5 lacks on MPS.
+
+`match_adalam(hw1=..., hw2=...)` now honours the image sizes when they are lists; only tuples were used and a list silently fell back to the keypoint spread.
+
+`get_laf_descriptors` and `LAFDescriptor` changed the caller's descriptor module: they called `.eval()` on it and cast it to the image's device and dtype in place, so a module shared with other code (a train-mode module, a float64 module) was silently switched to eval and to the image's dtype. The descriptor still runs in eval mode with its parameters cast to the image's device and dtype for the call (a TorchScript module runs as a cast copy), and the descriptors are unchanged, but once the call returns the module is as it was: its device, dtype, parameters and the train/eval mode of every submodule. Gradients still reach its parameters. Under `torch.compile` a descriptor whose dtype differs from the image's is now cast as in eager mode, also with `fullgraph=True`; such a compiled call used to raise a dtype error, or, on torch 2.14, break the graph.
+
+`make_upright` turned the all-zero padding LAF of an unfilled detector slot into a tiny nonzero frame, which `laf_is_filled` reported as a detection; it now returns the padding unchanged, and its gradient at a padding slot is finite. `laf_to_boundary_points` built its circle in float32 for float64 LAFs, so the points carried float32 rounding; it is now built in the LAF's dtype. `laf_from_three_points` now checks its input shape like `laf_to_three_points` instead of failing deep inside the stack or returning a wrong-shaped LAF.
+
+`HyNet` now raises a `ShapeError` for patches that are not `(B, 1, 32, 32)`, like `HardNet`, `SOSNet` and `TFeat`; a `(2, 1, 40, 40)` input used to return a descriptor of another width, `(2, 1152)`. The `ValueError` for a non-positive `scaling_coef` of `LocalFeature` (and `scale_laf` of `KeyNetHardNet` and `KeyNetAffNetHardNet`) now says `> 0`, matching the check that rejects `0`, and an `int` such as `scale_laf=2` is converted to `float`; it used to pass the constructor and fail in `forward` with a `TypeError`. The keypoint-range error of `LightGlue` and `OnnxLightGlue` used to be an empty `BaseError`; it now names the expected `[-1, 1]` range and the size orders: `image_size` is `(width, height)` for `LightGlue` and `OnnxLightGlue`, `hw1` / `hw2` is `(height, width)` for `LightGlueMatcher`. `gftt_response` now validates `sigmas` like `harris_response` and `hessian_response` (`TypeError` for a non-tensor, `ValueError` unless it has shape `(B,)`); a batch of one with three `sigmas` used to return a `(3, C, H, W)` response.
diff --git a/kornia/feature/adalam/adalam.py b/kornia/feature/adalam/adalam.py
index d2e896c4e..6aaac1de3 100644
--- a/kornia/feature/adalam/adalam.py
+++ b/kornia/feature/adalam/adalam.py
@@ -20,11 +20,11 @@
# Copyright (c) 2020, Luca Cavalli
import warnings
-from typing import Optional, Tuple, Union
+from typing import Optional, Sequence, Tuple, Union
import torch
-from kornia.core.check import KORNIA_CHECK_LAF, KORNIA_CHECK_SHAPE
+from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_LAF, KORNIA_CHECK_SHAPE
from kornia.feature.laf import get_laf_center, get_laf_orientation, get_laf_scale
from .core import AdalamConfig, _no_match, adalam_core
@@ -54,15 +54,21 @@ def match_adalam(
lafs1: torch.Tensor,
lafs2: torch.Tensor,
config: Optional[AdalamConfig] = None,
- hw1: Optional[Tuple[int, int]] = None,
- hw2: Optional[Tuple[int, int]] = None,
+ hw1: Optional[Sequence[int]] = None,
+ hw2: Optional[Sequence[int]] = None,
dm: Optional[torch.Tensor] = None,
) -> Tuple[torch.Tensor, torch.Tensor]:
"""Perform descriptor matching, followed by AdaLAM filtering.
See :cite:`AdaLAM2020` for more details.
- If the distance matrix dm is not provided, :py:func:`torch.cdist` is used.
+ The putative matches are the nearest neighbours in the distance matrix ``dm``, scored by the ratio of the two
+ smallest distances; with ``force_seed_mnn`` only mutual nearest neighbours can be seeds. ``dm`` holds plain
+ distances, like the ``dm`` of :func:`~kornia.feature.match_nn` and the other matchers: AdaLAM squares it
+ internally (its thresholds are tuned for squared distances), so ``dm=torch.cdist(desc1, desc2)`` gives the
+ matches of ``dm=None``, where the squared L2 distances between the descriptors are used.
+
+ The computation runs on the device of ``desc1`` unless ``config`` sets ``"device"``.
Args:
desc1: Batch of descriptors of a shape :math:`(B1, D)`.
@@ -70,8 +76,8 @@ def match_adalam(
lafs1: LAFs of a shape :math:`(1, B1, 2, 3)`.
lafs2: LAFs of a shape :math:`(1, B2, 2, 3)`.
config: dict with AdaLAM config
- dm: torch.Tensor containing the distances from each descriptor in desc1
- to each descriptor in desc2, shape of :math:`(B1, B2)`.
+ dm: torch.Tensor containing the non-negative distances (not squared) from each descriptor in desc1
+ to each descriptor in desc2, shape of :math:`(B1, B2)`. Smaller is better.
hw1: Height/width of image.
hw2: Height/width of image.
@@ -87,10 +93,8 @@ def match_adalam(
KORNIA_CHECK_LAF(lafs1)
KORNIA_CHECK_LAF(lafs2)
config_ = get_adalam_default_config()
- if config is None:
- config_["device"] = desc1.device
- else:
- config_ = get_adalam_default_config()
+ config_["device"] = desc1.device
+ if config is not None:
for key, val in config.items():
if key not in config_:
warnings.warn(
@@ -114,6 +118,7 @@ def match_adalam(
get_laf_scale(lafs1).reshape(-1),
get_laf_scale(lafs2).reshape(-1),
return_dist=True,
+ dm=dm,
)
return quality, idxs
@@ -147,8 +152,8 @@ class AdalamFilter:
putative_matches: torch.Tensor,
scores: torch.Tensor,
mnn: Optional[torch.Tensor] = None,
- im1shape: Optional[Tuple[int, int]] = None,
- im2shape: Optional[Tuple[int, int]] = None,
+ im1shape: Optional[Sequence[int]] = None,
+ im2shape: Optional[Sequence[int]] = None,
o1: Optional[torch.Tensor] = None,
o2: Optional[torch.Tensor] = None,
s1: Optional[torch.Tensor] = None,
@@ -175,11 +180,11 @@ class AdalamFilter:
'force_seed_mnn' in the DEFAULT_CONFIG. If None, it disables the mutual nearest neighbor filtering on
seed point selection. Expected a bool torch.Tensor with shape (num_keypoints_in_source_image,)
im1shape: Shape of the source image. If None, it is inferred from keypoints max and min, at the cost of
- wasted runtime. So please provide it. Expected a tuple with (width, height) or (height, width)
- of source image
+ wasted runtime. So please provide it. Expected a tuple or list with (width, height) or
+ (height, width) of source image
im2shape: Shape of the destination image. If None, it is inferred from keypoints max and min, at the cost
- of wasted runtime. So please provide it. Expected a tuple with (width, height) or (height, width)
- of destination image
+ of wasted runtime. So please provide it. Expected a tuple or list with (width, height) or
+ (height, width) of destination image
o1: keypoint orientations in degrees. They can be None if 'orientation_difference_threshold' in config
is set to None. See documentation on 'orientation_difference_threshold' in the DEFAULT_CONFIG.
Expected a float32 torch.Tensor with shape (num_keypoints_in_source/destination_image,)
@@ -219,13 +224,14 @@ class AdalamFilter:
k2: torch.Tensor,
d1: torch.Tensor,
d2: torch.Tensor,
- im1shape: Optional[Tuple[int, int]] = None,
- im2shape: Optional[Tuple[int, int]] = None,
+ im1shape: Optional[Sequence[int]] = None,
+ im2shape: Optional[Sequence[int]] = None,
o1: Optional[torch.Tensor] = None,
o2: Optional[torch.Tensor] = None,
s1: Optional[torch.Tensor] = None,
s2: Optional[torch.Tensor] = None,
return_dist: bool = False,
+ dm: Optional[torch.Tensor] = None,
) -> Union[Tuple[torch.Tensor, torch.Tensor], torch.Tensor]:
"""Match and filter with AdaLAM.
@@ -247,11 +253,11 @@ class AdalamFilter:
d2: descriptors in the destination image.
Expected an array with shape (num_keypoints_in_destination_image, descriptor_size).
im1shape: Shape of the source image. If None, it is inferred from keypoints max and min, at the cost of
- wasted runtime. So please provide it. Expected a tuple with (width, height) or (height, width)
- of source image
+ wasted runtime. So please provide it. Expected a tuple or list with (width, height) or
+ (height, width) of source image
im2shape: Shape of the destination image. If None, it is inferred from keypoints max and min, at the cost
- of wasted runtime. So please provide it. Expected a tuple with (width, height) or (height, width)
- of destination image
+ of wasted runtime. So please provide it. Expected a tuple or list with (width, height) or
+ (height, width) of destination image
o1: keypoint orientations in degrees. They can be None if 'orientation_difference_threshold' in config
is set to None. See documentation on 'orientation_difference_threshold' in the DEFAULT_CONFIG.
Expected an array with shape (num_keypoints_in_source/destination_image,)
@@ -261,6 +267,9 @@ class AdalamFilter:
Expected an array with shape (num_keypoints_in_source/destination_image,)
s2: Same as s1 for destination.
return_dist: if True, inverse confidence value is also outputted.
+ dm: non-negative distances (not squared) from each descriptor in d1 to each descriptor in d2, shape
+ (num_keypoints_in_source_image, num_keypoints_in_destination_image); smaller is better. They are
+ squared internally, like the L2 distances used when dm is None.
Returns:
Filtered putative matches.
@@ -293,13 +302,22 @@ class AdalamFilter:
else:
_s1, _s2 = s1, s2
+ if dm is not None:
+ KORNIA_CHECK(
+ tuple(dm.shape) == (len(_d1), len(_d2)),
+ f"dm must have shape {(len(_d1), len(_d2))}, got {tuple(dm.shape)}",
+ )
+
if (len(_d2) <= 1) or (len(_d1) <= 1):
idxs, dists = _no_match(_d1)
if return_dist:
return idxs, dists
return idxs
- distmat = dist_matrix(_d1, _d2, is_normalized=False)
+ if dm is None:
+ distmat = dist_matrix(_d1, _d2, is_normalized=False)
+ else:
+ distmat = torch.as_tensor(dm, device=self.config["device"], dtype=torch.float32).pow(2)
dd12, nn12 = torch.topk(distmat, k=2, dim=1, largest=False) # (n1, 2)
putative_matches = nn12[:, 0]
diff --git a/kornia/feature/adalam/core.py b/kornia/feature/adalam/core.py
index 69b07db5d..38dc97941 100644
--- a/kornia/feature/adalam/core.py
+++ b/kornia/feature/adalam/core.py
@@ -16,7 +16,7 @@
#
import math
-from typing import NotRequired, Optional, Tuple, TypedDict, Union
+from typing import NotRequired, Optional, Sequence, Tuple, TypedDict, Union
import torch
@@ -273,8 +273,8 @@ def adalam_core(
scores1: torch.Tensor,
config: AdalamConfig,
mnn: Optional[torch.Tensor] = None,
- im1shape: Optional[Tuple[int, int]] = None,
- im2shape: Optional[Tuple[int, int]] = None,
+ im1shape: Optional[Sequence[int]] = None,
+ im2shape: Optional[Sequence[int]] = None,
o1: Optional[torch.Tensor] = None,
o2: Optional[torch.Tensor] = None,
s1: Optional[torch.Tensor] = None,
@@ -301,11 +301,11 @@ def adalam_core(
'force_seed_mnn' in the DEFAULT_CONFIG. If None, it disables the mutual nearest neighbor filtering on seed
point selection. Expected a bool torch.Tensor with shape (num_keypoints_in_source_image,)
im1shape: Shape of the source image. If None, it is inferred from keypoints max and min, at the cost of wasted
- runtime. So please provide it. Expected a tuple with (width, height) or (height, width) of source
- image
+ runtime. So please provide it. Expected a tuple or list with (width, height) or (height, width)
+ of source image
im2shape: Shape of the destination image. If None, it is inferred from keypoints max and min, at the cost of
- wasted runtime. So please provide it. Expected a tuple with (width, height) or (height, width) of
- destination image
+ wasted runtime. So please provide it. Expected a tuple or list with (width, height) or
+ (height, width) of destination image
o1: keypoint orientations in degrees. They can be None if 'orientation_difference_threshold' in config is
set to None. See documentation on 'orientation_difference_threshold' in the DEFAULT_CONFIG.
Expected a float32 torch.Tensor with shape (num_keypoints_in_source/destination_image,)
@@ -331,14 +331,14 @@ def adalam_core(
SCALE_RATE_THR = config["scale_rate_threshold"]
REFIT = config["refit"]
- if isinstance(im1shape, tuple):
+ if im1shape is not None:
_im1shape = torch.tensor(im1shape, device=k1.device, dtype=k1.dtype)
else:
k1mins = k1.min(dim=0).values
k1maxs = k1.max(dim=0).values
_im1shape = k1maxs - k1mins
- if isinstance(im2shape, tuple):
+ if im2shape is not None:
_im2shape = torch.tensor(im2shape, device=k2.device, dtype=k2.dtype)
else:
k2mins = k2.min(dim=0).values
@@ -413,8 +413,13 @@ def adalam_core(
final_matches = torch.stack([absolute_im1idx, absolute_im2idx], dim=1)
if final_matches.shape[0] > 1:
+ # Unique rows, sorted lexicographically, through a 1-D key: torch.unique(dim=0) has no MPS kernel on torch 2.5.
# https://stackoverflow.com/a/72005790
- final_matches, idxs, counts = torch.unique(final_matches, dim=0, return_inverse=True, return_counts=True)
+ n2 = k2.shape[0]
+ keys, idxs, counts = torch.unique(
+ final_matches[:, 0] * n2 + final_matches[:, 1], return_inverse=True, return_counts=True
+ )
+ final_matches = torch.stack([torch.div(keys, n2, rounding_mode="floor"), keys % n2], dim=1)
_, ind_sorted = torch.sort(idxs)
cum_sum = counts.cumsum(0)
cum_sum = torch.cat((torch.tensor([0], dtype=cum_sum.dtype, device=cum_sum.device), cum_sum[:-1]))
diff --git a/kornia/feature/hynet.py b/kornia/feature/hynet.py
index 3d87a50e5..198136f13 100644
--- a/kornia/feature/hynet.py
+++ b/kornia/feature/hynet.py
@@ -20,6 +20,7 @@ from typing import Dict
import torch
from torch import nn
+from kornia.core.check import KORNIA_CHECK_SHAPE
from kornia.core.download import hf_url, load_state_dict_from_url
urls: Dict[str, str | list[str]] = {}
@@ -286,6 +287,7 @@ class HyNet(nn.Module):
Returns:
HyNet descriptors with shape ``(B, D)``.
"""
+ KORNIA_CHECK_SHAPE(x, ["B", "1", "32", "32"])
x = self.layer1(x)
x = self.layer2(x)
x = self.layer3(x)
diff --git a/kornia/feature/integrated.py b/kornia/feature/integrated.py
index 3afd9173a..c61a34139 100644
--- a/kornia/feature/integrated.py
+++ b/kornia/feature/integrated.py
@@ -15,6 +15,8 @@
# limitations under the License.
#
+import copy
+import itertools
import math
import warnings
from typing import ClassVar, Dict, List, Literal, Optional, Tuple, Union
@@ -24,7 +26,6 @@ from torch import nn
from kornia.color import rgb_to_grayscale
from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_LAF
-from kornia.core.utils import is_exporting
from kornia.geometry.subpix import ConvQuadInterp3d
from kornia.geometry.transform import ScalePyramid
@@ -79,6 +80,46 @@ def _lightglue_keypoint_scale_ori(lafs: torch.Tensor, feature_name: str) -> Tupl
return scales, oris
+def _run_descriptor(module: nn.Module, patches: torch.Tensor) -> torch.Tensor:
+ """Run ``module`` in eval mode on ``patches``, leaving its device, dtype and parameters as they are.
+
+ A module whose floating-point parameters and buffers already sit on the device and dtype of ``patches`` is called
+ directly. Otherwise they are cast for the call only, through ``torch.func.functional_call`` or, for a TorchScript
+ module, which that API refuses, in the slots of a copy of the module. The cast is differentiable, so gradients
+ reach the module's own parameters. Eager calls, ``torch.compile`` and ``torch.export`` take the same path. Every
+ submodule is switched to eval for the call and its ``training`` flag is restored afterwards.
+ """
+ modes = [m.training for m in module.modules()]
+ module.eval()
+ try:
+ tensors = list(itertools.chain(module.named_parameters(), module.named_buffers()))
+ needs_cast = any(
+ t.device != patches.device or (t.is_floating_point() and t.dtype != patches.dtype) for _, t in tensors
+ )
+ if not needs_cast:
+ return module(patches)
+ state = {
+ name: t.to(device=patches.device, dtype=patches.dtype) if t.is_floating_point() else t.to(patches.device)
+ for name, t in tensors
+ }
+ if not isinstance(module, torch.jit.ScriptModule):
+ return torch.func.functional_call(module, state, (patches,))
+ # functional_call refuses a TorchScript module, so the cast tensors go into the slots of a copy instead; they
+ # stay in the autograd graph, so gradients reach the module's own parameters on every device and dtype.
+ with torch.no_grad():
+ copied = copy.deepcopy(module)
+ for name, t in state.items():
+ *path, attr = name.split(".")
+ owner = copied
+ for part in path: # ScriptModules have no get_submodule
+ owner = getattr(owner, part)
+ setattr(owner, attr, t)
+ return copied(patches)
+ finally:
+ for m, mode in zip(module.modules(), modes):
+ m.training = mode
+
+
def get_laf_descriptors(
img: torch.Tensor,
lafs: torch.Tensor,
@@ -88,6 +129,11 @@ def get_laf_descriptors(
) -> torch.Tensor:
r"""Get local descriptors, corresponding to LAFs (keypoints).
+ The descriptor runs in eval mode, with its floating-point parameters and buffers cast to the device and dtype of
+ ``img`` for the call (a TorchScript module is called on a cast copy). The module keeps its device, dtype and
+ parameters, every submodule is switched to eval for the call and gets its train/eval mode back afterwards, and
+ gradients reach the module's parameters.
+
Args:
img: image features with shape :math:`(B,C,H,W)`.
lafs: local affine frames :math:`(B,N,2,3)`.
@@ -101,11 +147,6 @@ def get_laf_descriptors(
"""
KORNIA_CHECK_LAF(lafs)
- # Moving a module swaps its parameters, which graph capture forbids; the module is already placed under export.
- if not is_exporting():
- patch_descriptor = patch_descriptor.to(img)
- patch_descriptor.eval()
-
timg: torch.Tensor = img
if grayscale_descriptor and img.size(1) == 3:
timg = rgb_to_grayscale(img)
@@ -118,8 +159,9 @@ def get_laf_descriptors(
# matching width is the whole probe -- `probe.shape[-1]` would only agree for descriptors
# whose output is 2-D. The probe has a batch of one, so its numel is that width.
with torch.no_grad():
- probe = patch_descriptor(
- torch.zeros(1, timg.size(1), patch_size, patch_size, dtype=timg.dtype, device=timg.device)
+ probe = _run_descriptor(
+ patch_descriptor,
+ torch.zeros(1, timg.size(1), patch_size, patch_size, dtype=timg.dtype, device=timg.device),
)
return torch.empty(lafs.shape[0], 0, probe.numel(), dtype=probe.dtype, device=probe.device)
@@ -127,17 +169,19 @@ def get_laf_descriptors(
# Descriptor accepts standard torch.Tensor [B, CH, H, W], while patches are [B, N, CH, H, W] shape
# So we need to reshape a bit :)
B, N, CH, H, W = patches.size()
- return patch_descriptor(patches.view(B * N, CH, H, W)).view(B, N, -1)
+ return _run_descriptor(patch_descriptor, patches.view(B * N, CH, H, W)).view(B, N, -1)
class LAFDescriptor(nn.Module):
r"""nn.Module to get local descriptors, corresponding to LAFs (keypoints).
- Internally uses :func:`~kornia.feature.get_laf_descriptors`.
+ Internally uses :func:`~kornia.feature.get_laf_descriptors`: the descriptor runs in eval mode with its parameters
+ cast to the image's device and dtype for the call; the module keeps its device, dtype and parameters, and its
+ train/eval modes are restored after the call.
Args:
patch_descriptor_module: patch descriptor module, e.g. :class:`~kornia.feature.SIFTDescriptor`
- or :class:`~kornia.feature.HardNet`. Default: :class:`~kornia.feature.HardNet`.
+ or :class:`~kornia.feature.HardNet`. Default: :class:`~kornia.feature.HardNet` with pretrained weights.
patch_size: patch size in pixels, which descriptor expects.
grayscale_descriptor: ``True`` if patch_descriptor expects single-channel image.
@@ -187,7 +231,8 @@ class LocalFeature(nn.Module):
Args:
detector: the detection module.
descriptor: the descriptor module.
- scaling_coef: multiplier for change default detector scale (e.g. it is too small for KeyNet by default)
+ scaling_coef: multiplier for change default detector scale (e.g. it is too small for KeyNet by default).
+ An ``int`` is converted to ``float``. Must be positive.
"""
@@ -196,8 +241,9 @@ class LocalFeature(nn.Module):
self.detector = detector
self.descriptor = descriptor
if scaling_coef <= 0:
- raise ValueError(f"Scaling coef should be >= 0, got {scaling_coef}")
- self.scaling_coef = scaling_coef
+ raise ValueError(f"Scaling coef should be > 0, got {scaling_coef}")
+ # scale_laf accepts a float or a tensor, not an int
+ self.scaling_coef = float(scaling_coef)
def forward(
self, img: torch.Tensor, mask: Optional[torch.Tensor] = None
diff --git a/kornia/feature/laf.py b/kornia/feature/laf.py
index bc7fcadd0..bd172203b 100644
--- a/kornia/feature/laf.py
+++ b/kornia/feature/laf.py
@@ -230,6 +230,9 @@ def scale_laf(laf: torch.Tensor, scale_coef: Union[float, torch.Tensor]) -> torc
def make_upright(laf: torch.Tensor, eps: float = 1e-9) -> torch.Tensor:
"""Rectify the affine matrix, so that it becomes upright.
+ The all-zero LAF that pads an unfilled detector slot (see :func:`laf_is_filled`) is returned unchanged, so the
+ padding stays recognizable.
+
Args:
laf: :math:`(B, N, 2, 3)`
eps: for safe division.
@@ -243,6 +246,12 @@ def make_upright(laf: torch.Tensor, eps: float = 1e-9) -> torch.Tensor:
"""
KORNIA_CHECK_LAF(laf)
+ # Differentiate through an identity frame in place of the zero padding: sqrt at exactly zero has an infinite
+ # derivative, which torch.where below would turn into nan rather than mask.
+ filled = laf_is_filled(laf)[..., None, None]
+ eye = torch.eye(2, 3, device=laf.device, dtype=laf.dtype).expand_as(laf)
+ padding = laf
+ laf = torch.where(filled, laf, eye)
det = get_laf_scale(laf)
scale = det
# The function is equivalent to doing 2x2 SVD and resetting rotation
@@ -257,7 +266,9 @@ def make_upright(laf: torch.Tensor, eps: float = 1e-9) -> torch.Tensor:
dim=3,
)
laf_unit_scale = torch.cat([torch.cat([laf1_ell, laf2_ell], dim=2), laf[..., :, 2:3]], dim=3)
- return scale_laf(laf_unit_scale, scale)
+ upright = scale_laf(laf_unit_scale, scale)
+ # The padding LAF would otherwise come back as a tiny nonzero frame (the determinant and the division carry eps).
+ return torch.where(filled, upright, padding)
def ellipse_to_laf(ells: torch.Tensor) -> torch.Tensor:
@@ -334,16 +345,15 @@ def laf_to_boundary_points(LAF: torch.Tensor, n_pts: int = 50) -> torch.Tensor:
"""
KORNIA_CHECK_LAF(LAF)
B, N, _, _ = LAF.size()
+ # Build the circle on the CPU in at least float32 (the LAF's dtype when it is wider, so float64 LAFs do not carry
+ # float32 rounding), then cast it once.
+ build = torch.promote_types(LAF.dtype, torch.float32)
+ angles = torch.linspace(0, 2 * math.pi, n_pts - 1, dtype=build)
pts = torch.cat(
- [
- torch.sin(torch.linspace(0, 2 * math.pi, n_pts - 1)).unsqueeze(-1),
- torch.cos(torch.linspace(0, 2 * math.pi, n_pts - 1)).unsqueeze(-1),
- torch.ones(n_pts - 1, 1),
- ],
- dim=1,
+ [torch.sin(angles).unsqueeze(-1), torch.cos(angles).unsqueeze(-1), torch.ones(n_pts - 1, 1, dtype=build)], dim=1
)
# Add origin to draw also the orientation
- pts = torch.cat([torch.tensor([0.0, 0.0, 1.0]).view(1, 3), pts], dim=0)
+ pts = torch.cat([torch.tensor([0.0, 0.0, 1.0], dtype=build).view(1, 3), pts], dim=0)
# Move the 3-column basis before broadcasting it: expanding first and casting afterwards
# materialized -- and on an accelerator transferred -- one copy per LAF (~12 MiB at N = 20000)
# of a tensor with `n_pts` distinct rows.
@@ -923,6 +933,7 @@ def laf_from_three_points(threepts: torch.Tensor) -> torch.Tensor:
laf :math:`(B, N, 2, 3)`.
"""
+ KORNIA_CHECK_SHAPE(threepts, ["B", "N", "2", "3"])
return torch.stack(
[threepts[..., 0] - threepts[..., 2], threepts[..., 1] - threepts[..., 2], threepts[..., 2]], dim=-1
)
diff --git a/kornia/feature/lightglue.py b/kornia/feature/lightglue.py
index ef5cb0020..dd8a94e04 100644
--- a/kornia/feature/lightglue.py
+++ b/kornia/feature/lightglue.py
@@ -446,10 +446,18 @@ def filter_matches(scores: torch.Tensor, th: float) -> Tuple[torch.Tensor, torch
return m0, m1, mscores0, mscores1
+_KEYPOINT_RANGE_MSG = (
+ "Keypoints must lie inside the image: normalized by the image size they have to be in [-1, 1]. The keypoints are "
+ "(x, y) pixel coordinates. The image size is (width, height) for the ``image_size`` of LightGlue and "
+ "OnnxLightGlue, and (height, width) for the ``hw1`` / ``hw2`` of LightGlueMatcher; the wrong order, or keypoints "
+ "detected on a differently sized image, put them out of range."
+)
+
+
def _check_keypoints_normalized(kpts: torch.Tensor) -> None:
"""Check that keypoints lie in [-1, 1]; skipped under export, where reading the data is not possible."""
if not is_exporting():
- KORNIA_CHECK(torch.all(kpts >= -1).item() and torch.all(kpts <= 1).item(), "") # type: ignore
+ KORNIA_CHECK(torch.all(kpts >= -1).item() and torch.all(kpts <= 1).item(), _KEYPOINT_RANGE_MSG) # type: ignore
class LightGlue(nn.Module):
diff --git a/kornia/feature/lightglue_onnx/lightglue.py b/kornia/feature/lightglue_onnx/lightglue.py
index 91f1cf87e..76caa65e1 100644
--- a/kornia/feature/lightglue_onnx/lightglue.py
+++ b/kornia/feature/lightglue_onnx/lightglue.py
@@ -28,6 +28,13 @@ from kornia.core.external import onnxruntime as ort
from .utils import download_onnx_from_url, normalize_keypoints
+_KEYPOINT_RANGE_MSG = (
+ "Keypoints must lie inside the image: normalized by the image size they have to be in [-1, 1]. The keypoints are "
+ "(x, y) pixel coordinates. The image size is (width, height) for the ``image_size`` of LightGlue and "
+ "OnnxLightGlue, and (height, width) for the ``hw1`` / ``hw2`` of LightGlueMatcher; the wrong order, or keypoints "
+ "detected on a differently sized image, put them out of range."
+)
+
__all__ = ["OnnxLightGlue"]
@@ -159,8 +166,8 @@ class OnnxLightGlue:
kpts0 = normalize_keypoints(kpts0_, size=size0) # type: ignore
kpts1 = normalize_keypoints(kpts1_, size=size1) # type: ignore
- KORNIA_CHECK(torch.all(kpts0 >= -1).item() and torch.all(kpts0 <= 1).item(), "") # type: ignore
- KORNIA_CHECK(torch.all(kpts1 >= -1).item() and torch.all(kpts1 <= 1).item(), "") # type: ignore
+ KORNIA_CHECK(torch.all(kpts0 >= -1).item() and torch.all(kpts0 <= 1).item(), _KEYPOINT_RANGE_MSG) # type: ignore
+ KORNIA_CHECK(torch.all(kpts1 >= -1).item() and torch.all(kpts1 <= 1).item(), _KEYPOINT_RANGE_MSG) # type: ignore
# Inference.
lightglue_inputs = {"kpts0": kpts0, "kpts1": kpts1, "desc0": desc0, "desc1": desc1}
diff --git a/kornia/feature/matching.py b/kornia/feature/matching.py
index f2d9b2115..22e9295f4 100644
--- a/kornia/feature/matching.py
+++ b/kornia/feature/matching.py
@@ -25,7 +25,7 @@ from kornia.core.utils import _l2_normalize, is_exporting, is_mps_tensor_safe
from kornia.feature.laf import get_laf_center
from kornia.feature.steerers import DiscreteSteerer
-from .adalam import get_adalam_default_config, match_adalam
+from .adalam import match_adalam
def _cdist(d1: torch.Tensor, d2: torch.Tensor) -> torch.Tensor:
@@ -722,9 +722,7 @@ class GeometryAwareDescriptorMatcher(nn.Module):
params.update(self.params)
out = match_fginn(desc1, desc2, lafs1, lafs2, params["th"], params["spatial_th"], params["mutual"])
elif self.match_mode == "adalam":
- _params = get_adalam_default_config()
- _params.update(self.params) # type: ignore[typeddict-item]
- out = match_adalam(desc1, desc2, lafs1, lafs2, config=_params)
+ out = match_adalam(desc1, desc2, lafs1, lafs2, config=self.params) # type: ignore[arg-type]
else:
raise NotImplementedError
return out
diff --git a/kornia/feature/responses.py b/kornia/feature/responses.py
index 85e0b8d14..571af9416 100644
--- a/kornia/feature/responses.py
+++ b/kornia/feature/responses.py
@@ -179,6 +179,12 @@ def gftt_response(
"""
KORNIA_CHECK_SHAPE(input, ["B", "C", "H", "W"])
+ if sigmas is not None:
+ if not isinstance(sigmas, torch.Tensor):
+ raise TypeError(f"sigmas type is not a torch.Tensor. Got {type(sigmas)}")
+ if (not len(sigmas.shape) == 1) or (sigmas.size(0) != input.size(0)):
+ raise ValueError(f"Invalid sigmas shape, we expect B == input.size(0). Got: {sigmas.shape}")
+
gradients: torch.Tensor = spatial_gradient(input, grads_mode)
dx: torch.Tensor = gradients[:, :, 0]
dy: torch.Tensor = gradients[:, :, 1]
diff --git a/tests/feature/test_hynet.py b/tests/feature/test_hynet.py
index 6a7394fea..8e9ea9a9c 100644
--- a/tests/feature/test_hynet.py
+++ b/tests/feature/test_hynet.py
@@ -18,6 +18,7 @@
import pytest
import torch
+from kornia.core.check import ShapeError
from kornia.feature import FilterResponseNorm2d, HyNet
from testing.base import DYNAMO_UNAVAILABLE_REASON, BaseTester, dynamo_is_available
@@ -36,6 +37,12 @@ class TestHyNet(BaseTester):
out = hynet(inp)
assert out.shape == (1, 128)
+ @pytest.mark.parametrize("shape", [(2, 1, 40, 40), (2, 1, 32, 31), (2, 3, 32, 32), (1, 32, 32)])
+ def test_wrong_patch_shape_is_rejected_5724(self, device, shape):
+ # without the check a 40x40 patch silently produced a (2, 1152) descriptor
+ with pytest.raises(ShapeError):
+ HyNet().to(device)(torch.ones(*shape, device=device))
+
def test_shape_batch(self, device):
inp = torch.ones(4, 1, 32, 32, device=device)
hynet = HyNet().to(device)
diff --git a/tests/feature/test_integrated.py b/tests/feature/test_integrated.py
index 49e4ed111..410e60b62 100644
--- a/tests/feature/test_integrated.py
+++ b/tests/feature/test_integrated.py
@@ -15,7 +15,9 @@
# limitations under the License.
#
+import copy
import sys
+import warnings
import pytest
import torch
@@ -27,6 +29,7 @@ from kornia.core.exceptions import BaseError
from kornia.feature import (
DescriptorMatcher,
GFTTAffNetHardNet,
+ HardNet,
KeyNetHardNet,
LAFDescriptor,
LocalFeature,
@@ -43,7 +46,7 @@ from kornia.feature import (
from kornia.feature.integrated import LocalFeatureMatcher
from kornia.geometry import RANSAC, resize, transform_points
-from testing.base import BaseTester, supports_replicate_padding
+from testing.base import DYNAMO_UNAVAILABLE_REASON, BaseTester, dynamo_is_available, supports_replicate_padding
from testing.casts import dict_to
@@ -239,7 +242,195 @@ class TestLAFDescriptor(BaseTester):
self.gradcheck(lafdesc, (img, lafs), eps=1e-3, atol=1e-3, nondet_tol=1e-3)
+class _TrainModeProbe(nn.Module):
+ """Patch descriptor with dropout and a parameter, so mode and dtype changes are observable."""
+
+ def __init__(self):
+ super().__init__()
+ self.proj = nn.Linear(16 * 16, 5)
+ self.drop = nn.Dropout(0.5)
+
+ def forward(self, patches):
+ return self.drop(self.proj(patches.flatten(1)))
+
+
+class TestDescriptorModuleIsNotModified(BaseTester):
+ @staticmethod
+ def _inputs(device, dtype):
+ img = torch.rand(1, 1, 48, 64, device=device, dtype=dtype)
+ centers = torch.tensor([[20.0, 30.0], [30.0, 40.0]], device=device, dtype=dtype).view(1, 2, 2)
+ scales = torch.tensor([10.0, 8.0], device=device, dtype=dtype).view(1, 2, 1, 1)
+ ori = torch.tensor([0.0, 30.0], device=device, dtype=dtype).view(1, 2, 1)
+ return img, kornia.feature.laf_from_center_scale_ori(centers, scales, ori)
+
+ @staticmethod
+ def _state(module):
+ return (
+ [m.training for m in module.modules()],
+ [(p.dtype, p.device) for p in module.parameters()],
+ list(module.parameters()),
+ [p.data_ptr() for p in module.parameters()],
+ )
+
+ def _assert_state_equal(self, before, after):
+ assert before[0] == after[0]
+ assert before[1] == after[1]
+ assert all(a is b for a, b in zip(before[2], after[2]))
+ assert before[3] == after[3]
+
+ @staticmethod
+ def _reference(module, img, lafs, ps):
+ # what the descriptor gives when it is cast to the image and put in eval mode explicitly
+ ref = copy.deepcopy(module).to(img).eval()
+ patches = extract_patches_from_pyramid(img, lafs, ps)
+ B, N, C, H, W = patches.shape
+ return ref(patches.view(B * N, C, H, W)).view(B, N, -1)
+
+ @pytest.mark.parametrize("train", [True, False])
+ def test_module_is_unchanged_and_output_is_the_eval_cast_copy_5724(self, device, train):
+ if torch.device(device).type == "mps":
+ pytest.skip("MPS does not support float64")
+ img, lafs = self._inputs(device, torch.float64)
+ module = _TrainModeProbe().to(device).train(train) # float32 module, float64 image
+ before = self._state(module)
+ expected = self._reference(module, img, lafs, 16)
+ out = get_laf_descriptors(img, lafs, module, 16)
+ self._assert_state_equal(before, self._state(module))
+ assert out.dtype == torch.float64
+ self.assert_close(out, expected)
+
+ def test_lafdescriptor_keeps_every_submodule_mode_5724(self, device):
+ img, lafs = self._inputs(device, torch.float32)
+ module = _TrainModeProbe().to(device).train()
+ module.drop.eval() # mixed modes are restored one by one
+ before = self._state(module)
+ out = LAFDescriptor(module, 16)(img, lafs)
+ self._assert_state_equal(before, self._state(module))
+ self.assert_close(out, self._reference(module, img, lafs, 16))
+
+ def test_float64_module_with_a_float32_image_5724(self, device):
+ if torch.device(device).type == "mps":
+ pytest.skip("MPS does not support float64")
+ img, lafs = self._inputs(device, torch.float32)
+ module = _TrainModeProbe().to(device, torch.float64).train()
+ before = self._state(module)
+ out = get_laf_descriptors(img, lafs, module, 16)
+ self._assert_state_equal(before, self._state(module))
+ assert module.proj.weight.dtype == torch.float64
+ assert out.dtype == torch.float32
+ self.assert_close(out, self._reference(module, img, lafs, 16))
+
+ def test_gradients_reach_the_module_parameters_5724(self, device):
+ if torch.device(device).type == "mps":
+ pytest.skip("MPS does not support float64")
+ img, lafs = self._inputs(device, torch.float64)
+ module = _TrainModeProbe().to(device).eval() # float32 parameters, float64 image
+ get_laf_descriptors(img, lafs, module, 16).sum().backward()
+ for p in module.parameters():
+ assert p.grad is not None
+ assert p.grad.dtype == torch.float32
+ assert torch.isfinite(p.grad).all()
+ assert module.proj.weight.grad.abs().sum() > 0
+
+ @pytest.mark.parametrize("kind", ["script_hardnet", "trace_sift"])
+ @pytest.mark.parametrize("image_dtype", [torch.float32, torch.float64])
+ def test_torchscript_descriptors_5724(self, device, kind, image_dtype):
+ if torch.device(device).type == "mps" and image_dtype == torch.float64:
+ pytest.skip("MPS does not support float64")
+ img, lafs = self._inputs(device, image_dtype)
+ patch = torch.rand(2, 1, 32, 32, device=device)
+ if kind == "script_hardnet":
+ module = torch.jit.script(HardNet(False).to(device).train())
+ else:
+ module = torch.jit.trace(SIFTDescriptor(32).to(device), patch)
+ before = self._state(module)
+ if kind == "trace_sift" and image_dtype == torch.float64:
+ # the trace holds float32 constants, so a cast copy fails exactly as the module cast in place did
+ with pytest.raises(RuntimeError, match="Double but found Float"):
+ get_laf_descriptors(img, lafs, module, 32)
+ self._assert_state_equal(before, self._state(module))
+ return
+ out = get_laf_descriptors(img, lafs, module, 32)
+ self._assert_state_equal(before, self._state(module))
+ reference = copy.deepcopy(module).to(img).eval()
+ patches = extract_patches_from_pyramid(img, lafs, 32)
+ B, N, C, H, W = patches.shape
+ self.assert_close(out, reference(patches.view(B * N, C, H, W)).view(B, N, -1))
+ assert out.dtype == image_dtype
+
+ def test_empty_lafs_leave_the_module_alone_5724(self, device):
+ if torch.device(device).type == "mps":
+ pytest.skip("MPS does not support float64")
+ img, _ = self._inputs(device, torch.float32)
+ module = _TrainModeProbe().to(device, torch.float64).train()
+ before = self._state(module)
+ with pytest.warns(UserWarning, match="no keypoints"):
+ out = get_laf_descriptors(img, torch.zeros(1, 0, 2, 3, device=device), module, 16)
+ self._assert_state_equal(before, self._state(module))
+ assert out.shape == (1, 0, 5)
+ assert out.dtype == torch.float32
+
+ def test_torchscript_gradients_reach_the_module_5724(self, device):
+ # a float32 CPU module: on the CPU the image is float64 (a dtype cast), elsewhere the module is on another
+ # device than the image (a device cast)
+ image_dtype = torch.float64 if torch.device(device).type == "cpu" else torch.float32
+ img, lafs = self._inputs(device, image_dtype)
+ plain = HardNet(False)
+ scripted = torch.jit.script(copy.deepcopy(plain))
+ before = self._state(scripted)
+ get_laf_descriptors(img, lafs, plain, 32).sum().backward()
+ with warnings.catch_warnings(record=True) as caught:
+ warnings.simplefilter("always")
+ get_laf_descriptors(img, lafs, scripted, 32).sum().backward()
+ assert not [w for w in caught if "not a leaf Tensor" in str(w.message)]
+ self._assert_state_equal(before, self._state(scripted))
+ for p, q in zip(scripted.parameters(), plain.parameters()):
+ assert p.grad is not None
+ assert p.grad.dtype == torch.float32
+ assert p.grad.device == torch.device("cpu")
+ self.assert_close(p.grad, q.grad)
+
+ def test_dynamo_casts_a_module_of_another_dtype_5724(self, device, torch_optimizer):
+ if torch.device(device).type == "mps":
+ pytest.skip("MPS does not support float64")
+ img, lafs = self._inputs(device, torch.float64)
+ module = _TrainModeProbe().to(device).train() # float32 module, float64 image
+ before = self._state(module)
+ expected = self._reference(module, img, lafs, 16)
+ out = torch_optimizer(LAFDescriptor(module, 16))(img, lafs)
+ self._assert_state_equal(before, self._state(module))
+ self.assert_close(out, expected)
+
+ @pytest.mark.skipif(not dynamo_is_available(), reason=DYNAMO_UNAVAILABLE_REASON)
+ def test_export_casts_a_module_of_another_dtype_5724(self, device):
+ if torch.device(device).type == "mps":
+ pytest.skip("MPS does not support float64")
+ img, lafs = self._inputs(device, torch.float64)
+ module = _TrainModeProbe().to(device) # float32 module, float64 image
+ expected = self._reference(module, img, lafs, 16)
+ # strict export cannot capture module.eval() on torch 2.5 and 2.6
+ exported = torch.export.export(LAFDescriptor(module, 16), (img, lafs), strict=False)
+ self.assert_close(exported.module()(img, lafs), expected)
+
+
class TestLocalFeature(BaseTester):
+ def test_int_scaling_coef_5724(self, device, dtype):
+ img = torch.rand(1, 1, 48, 64, device=device, dtype=dtype)
+ det = ScaleSpaceDetector(10)
+ desc = LAFDescriptor(SIFTDescriptor(32), 32)
+ as_int = LocalFeature(det, desc, 2).to(device, dtype)
+ as_float = LocalFeature(det, desc, 2.0).to(device, dtype)
+ assert isinstance(as_int.scaling_coef, float)
+ lafs_int, _, descs_int = as_int(img)
+ lafs_float, _, descs_float = as_float(img)
+ self.assert_close(lafs_int, lafs_float)
+ self.assert_close(descs_int, descs_float)
+
+ @pytest.mark.parametrize("coef", [0, 0.0, -1, -0.5])
+ def test_non_positive_scaling_coef_message_5724(self, coef):
+ with pytest.raises(ValueError, match="should be > 0"):
+ LocalFeature(ScaleSpaceDetector(10), SIFTDescriptor(32), coef)
+
def test_smoke(self, device, dtype):
det = ScaleSpaceDetector(10)
desc = SIFTDescriptor(32)
diff --git a/tests/feature/test_laf.py b/tests/feature/test_laf.py
index 596c1742a..c8a2a3d1b 100644
--- a/tests/feature/test_laf.py
+++ b/tests/feature/test_laf.py
@@ -232,6 +232,22 @@ class TestMakeUpright(BaseTester):
img = torch.rand(batch_size, channels, height, width, device=device, dtype=torch.float64)
self.gradcheck(kornia.feature.make_upright, (img,))
+ def test_zero_padding_laf_stays_zero_5724(self, device, dtype):
+ laf = torch.zeros(2, 3, 2, 3, device=device, dtype=dtype)
+ laf[0, 0] = torch.tensor([[2.0, 1.0, 5.0], [0.5, 3.0, 7.0]])
+ laf[1, 2] = torch.tensor([[1.0, 0.0, 9.0], [0.0, 4.0, 2.0]])
+ out = kornia.feature.make_upright(laf)
+ expected_filled = torch.tensor([[True, False, False], [False, False, True]], device=device)
+ assert torch.equal(kornia.feature.laf_is_filled(out), expected_filled)
+ assert torch.equal(out[~expected_filled], torch.zeros(4, 2, 3, device=device, dtype=dtype))
+
+ def test_zero_padding_laf_keeps_gradients_finite_5724(self, device):
+ laf = torch.zeros(1, 2, 2, 3, device=device)
+ laf[0, 1] = torch.tensor([[2.0, 1.0, 5.0], [0.5, 3.0, 7.0]])
+ laf.requires_grad_(True)
+ kornia.feature.make_upright(laf).sum().backward()
+ assert torch.isfinite(laf.grad).all()
+
@pytest.mark.skip("Union")
def test_jit(self, device, dtype):
batch_size, channels, height, width = 1, 2, 2, 3
@@ -589,6 +605,23 @@ class TestLAF2pts(BaseTester):
laf = torch.rand(batch_size, channels, height, width, device=device, dtype=torch.float64)
self.gradcheck(kornia.feature.laf_to_boundary_points, (laf))
+ def test_circle_is_built_in_the_laf_dtype_5724(self, device):
+ if torch.device(device).type == "mps":
+ pytest.skip("MPS does not support float64")
+ n_pts = 7
+ laf = torch.tensor([[[[1.0, 0.0, 0.0], [0.0, 1.0, 0.0]]]], device=device, dtype=torch.float64)
+ pts = kornia.feature.laf_to_boundary_points(laf, n_pts)
+ angles = torch.linspace(0, 2 * math.pi, n_pts - 1, dtype=torch.float64, device=device)
+ expected = torch.cat(
+ [
+ torch.zeros(1, 2, device=device, dtype=torch.float64),
+ torch.stack([torch.sin(angles), torch.cos(angles)], 1),
+ ]
+ )
+ assert pts.dtype == torch.float64
+ # a float32 circle cast to float64 is off by ~1e-8 here
+ self.assert_close(pts[0, 0], expected, rtol=0, atol=1e-14)
+
def test_matches_explicit_affine_reference(self, device, dtype):
"""The boundary points are the LAF affine map applied to the origin + unit-circle basis.
@@ -1735,6 +1768,11 @@ class TestGetLAF3pts(BaseTester):
class TestGetLAFFrom3pts(BaseTester):
+ @pytest.mark.parametrize("shape", [(1, 3, 3, 3), (1, 3, 2, 2), (3, 2, 3), (1, 1, 3, 2, 3)])
+ def test_wrong_shape_is_rejected_5724(self, device, shape):
+ with pytest.raises(ShapeError):
+ kornia.feature.laf_from_three_points(torch.ones(*shape, device=device))
+
def test_shape(self, device):
inp = torch.ones(1, 3, 2, 3, device=device)
out = kornia.feature.laf_from_three_points(inp)
diff --git a/tests/feature/test_lightglue.py b/tests/feature/test_lightglue.py
index b66abde22..bc27be89d 100644
--- a/tests/feature/test_lightglue.py
+++ b/tests/feature/test_lightglue.py
@@ -25,6 +25,7 @@ from kornia.feature.lightglue import (
LearnableFourierPositionalEncoding,
LightGlue,
TokenConfidence,
+ _check_keypoints_normalized,
apply_cached_rotary_emb,
normalize_keypoints,
pad_to_length,
@@ -486,3 +487,19 @@ def test_autocast_of_another_device_type_leaves_descriptors_alone(model_device,
with torch.no_grad(), torch.autocast(autocast_device, dtype=autocast_dtype):
out = lg(data)
assert out["log_assignment"].dtype == torch.float32
+
+
+class TestKeypointRangeMessage:
+ def test_check_names_the_range_and_the_size_order_5724(self):
+ with pytest.raises(Exception, match=r"\[-1, 1\].*\(width, height\)"):
+ _check_keypoints_normalized(torch.tensor([[[0.0, 2.0]]]))
+
+ def test_check_accepts_normalized_keypoints_5724(self):
+ _check_keypoints_normalized(torch.tensor([[[-1.0, 1.0], [0.0, 0.5]]]))
+
+ def test_forward_with_a_too_small_image_size_5724(self, device):
+ lg = _make_lightglue(device, torch.float32)
+ data = _make_data(device, torch.float32)
+ data["image0"]["image_size"] = torch.tensor([[8.0, 8.0]], device=device) # keypoints reach 64
+ with pytest.raises(Exception, match="Keypoints must lie inside the image"):
+ lg(data)
diff --git a/tests/feature/test_lightglue_onnx.py b/tests/feature/test_lightglue_onnx.py
index 49a01dd37..b42a0d701 100644
--- a/tests/feature/test_lightglue_onnx.py
+++ b/tests/feature/test_lightglue_onnx.py
@@ -200,3 +200,14 @@ class TestOnnxLightGlue:
}
)
assert "Descriptors' dimensions do not match" in str(e)
+
+
+def test_onnx_lightglue_keypoint_range_message_5724():
+ # the range check runs before the session is used, so a model without a session reaches it
+ model = object.__new__(OnnxLightGlue)
+ model.device = torch.device("cpu")
+ kpts = torch.tensor([[[10.0, 10.0], [90.0, 20.0]]])
+ desc = torch.zeros(1, 2, 128)
+ side = {"keypoints": kpts, "descriptors": desc, "image_size": torch.tensor([[50, 50]])}
+ with pytest.raises(Exception, match=r"\[-1, 1\].*\(width, height\)"):
+ model({"image0": side, "image1": side})
diff --git a/tests/feature/test_matching.py b/tests/feature/test_matching.py
index 234972a54..94803b128 100644
--- a/tests/feature/test_matching.py
+++ b/tests/feature/test_matching.py
@@ -15,6 +15,8 @@
# limitations under the License.
#
+import math
+
import pytest
import torch
@@ -22,6 +24,7 @@ from kornia.core._compat import torch_version_le
from kornia.feature import matching
from kornia.feature.integrated import LightGlueMatcher
from kornia.feature.laf import laf_from_center_scale_ori
+from kornia.feature.lightglue import LightGlue
from kornia.feature.matching import (
DescriptorMatcher,
DescriptorMatcherWithSteerer,
@@ -581,6 +584,119 @@ class TestAdalam(BaseTester):
self.assert_close(idxs, expected_idxs, rtol=1e-4, atol=1e-4)
+def _adalam_scene(device, H=240, W=320, n_in=400, n_out=200, n_extra2=37, D=32, seed=0):
+ # n_in affine inliers (a 10 degree rotation, 1.2 scale and a shift) plus n_out outliers, in an H x W image.
+ # The second image has n_extra2 more outliers, so the two keypoint counts differ.
+ g = torch.Generator().manual_seed(seed)
+ xy1 = torch.rand(n_in + n_out, 2, generator=g) * torch.tensor([W - 1.0, H - 1.0])
+ a = math.radians(10.0)
+ R = 1.2 * torch.tensor([[math.cos(a), -math.sin(a)], [math.sin(a), math.cos(a)]])
+ xy2 = torch.cat(
+ [
+ (xy1[:n_in] - torch.tensor([160.0, 120.0])) @ R.T
+ + torch.tensor([165.0, 118.0])
+ + 0.7 * torch.randn(n_in, 2, generator=g),
+ torch.rand(n_out + n_extra2, 2, generator=g) * torch.tensor([W - 1.0, H - 1.0]),
+ ]
+ )
+ d1 = torch.nn.functional.normalize(torch.randn(n_in + n_out, D, generator=g), dim=1)
+ noisy = d1[:n_in] + 0.15 * torch.randn(n_in, D, generator=g)
+ d2 = torch.nn.functional.normalize(torch.cat([noisy, torch.randn(n_out + n_extra2, D, generator=g)]), dim=1)
+ s = torch.full((1, n_in + n_out, 1, 1), 8.0)
+ lafs1 = laf_from_center_scale_ori(xy1[None], s)
+ lafs2 = laf_from_center_scale_ori(xy2[None], 1.2 * torch.full((1, n_in + n_out + n_extra2, 1, 1), 8.0))
+ return d1.to(device), d2.to(device), lafs1.to(device), lafs2.to(device), (H, W)
+
+
+class TestLightGlueMatcherSize(BaseTester):
+ def test_swapped_hw_names_hw_5724(self, device):
+ # LightGlueMatcher takes hw as (height, width). Its constructor downloads weights, so the matcher is built
+ # around a random-weight LightGlue, enough to reach the range check; forward reads only these two attributes.
+ matcher = LightGlueMatcher.__new__(LightGlueMatcher)
+ torch.nn.Module.__init__(matcher)
+ matcher.feature_name = "disk"
+ matcher.matcher = LightGlue(
+ features=None, input_dim=64, descriptor_dim=64, n_layers=2, num_heads=4, flash=False
+ )
+ matcher = matcher.to(device).eval()
+ H, W = 40, 120
+ xy = torch.tensor([[[10.0, 20.0], [100.0, 30.0], [60.0, 5.0]]], device=device)
+ lafs = laf_from_center_scale_ori(xy, torch.full((1, 3, 1, 1), 4.0, device=device))
+ desc = torch.rand(3, 64, device=device)
+ with torch.no_grad():
+ matcher(desc, desc, lafs, lafs, hw1=(H, W), hw2=(H, W)) # (height, width) is accepted
+ with pytest.raises(Exception, match=r"\(height, width\) for the ``hw1``"):
+ matcher(desc, desc, lafs, lafs, hw1=(W, H), hw2=(W, H))
+
+
+class TestAdalamInputs(BaseTester):
+ def test_dm_distances_reproduce_the_default_matches_5724(self, device):
+ d1, d2, l1, l2, hw = _adalam_scene(device)
+ assert len(d1) != len(d2)
+ q0, i0 = match_adalam(d1, d2, l1, l2, hw1=hw, hw2=hw)
+ # dm holds plain distances like the dm of the other matchers; AdaLAM squares them internally
+ q1, i1 = match_adalam(d1, d2, l1, l2, hw1=hw, hw2=hw, dm=torch.cdist(d1, d2))
+ assert len(i0) > 100
+ assert torch.equal(i0.sort(0).values, i1.sort(0).values)
+ self.assert_close(q0.sort(0).values, q1.sort(0).values, low_tolerance=True)
+
+ def test_dm_drives_the_putative_matches_5724(self, device):
+ d1, d2, l1, l2, hw = _adalam_scene(device)
+ _, i0 = match_adalam(d1, d2, l1, l2, hw1=hw, hw2=hw)
+ dm = torch.cdist(d1, d2)
+ dm[:200] = dm[:200].flip(1)
+ _, i1 = match_adalam(d1, d2, l1, l2, hw1=hw, hw2=hw, dm=dm)
+ assert not torch.equal(i0, i1)
+ # for the first 200 rows the flipped distances prefer a mirrored candidate, which is not an inlier
+ assert len(i1) < len(i0)
+ flipped_rows = i1[:, 0] < 200
+ assert (i1[flipped_rows, 1] != i1[flipped_rows, 0]).all()
+
+ def test_dm_ratio_comes_from_dm_5724(self, device):
+ d1, d2, l1, l2, hw = _adalam_scene(device)
+ dm = torch.cdist(d1, d2)
+ _, i0 = match_adalam(d1, d2, l1, l2, hw1=hw, hw2=hw, dm=dm)
+ # a constant added to the squared distances keeps every nearest neighbour and pushes every ratio to 1, so
+ # fewer putative matches pass the ratio test of the seeds
+ _, i1 = match_adalam(d1, d2, l1, l2, hw1=hw, hw2=hw, dm=(dm**2 + 10.0).sqrt())
+ assert len(i1) < len(i0) - 100
+
+ def test_dm_wrong_shape_5724(self, device):
+ d1, d2, l1, l2, hw = _adalam_scene(device)
+ with pytest.raises(Exception, match="dm must have shape"):
+ match_adalam(d1, d2, l1, l2, hw1=hw, hw2=hw, dm=torch.zeros(len(d1), len(d2) - 1, device=device))
+ # also when a single descriptor would end the matching early
+ with pytest.raises(Exception, match="dm must have shape"):
+ match_adalam(d1[:1], d2, l1[:, :1], l2, hw1=hw, hw2=hw, dm=torch.zeros(5, 5, device=device))
+
+ def test_hw_list_equals_tuple_5724(self, device):
+ d1, d2, l1, l2, (H, W) = _adalam_scene(device)
+ # an image much larger than the keypoint spread changes the seed radius, so a list that is ignored differs
+ tuple_out = match_adalam(d1, d2, l1, l2, hw1=(4 * H, 4 * W), hw2=(4 * H, 4 * W))
+ list_out = match_adalam(d1, d2, l1, l2, hw1=[4 * H, 4 * W], hw2=[4 * H, 4 * W])
+ none_out = match_adalam(d1, d2, l1, l2)
+ assert len(tuple_out[1]) != len(none_out[1])
+ assert torch.equal(tuple_out[1], list_out[1])
+
+ @pytest.mark.parametrize("config", [{"ransac_iters": 128}, {}])
+ def test_device_follows_input_with_config_5724(self, device, config):
+ d1, d2, l1, l2, hw = _adalam_scene(device)
+ quality, idxs = match_adalam(d1, d2, l1, l2, config=config, hw1=hw, hw2=hw)
+ assert idxs.device == d1.device
+ assert quality.device == d1.device
+
+ def test_module_device_follows_input_5724(self, device):
+ d1, d2, l1, l2, _ = _adalam_scene(device)
+ quality, idxs = GeometryAwareDescriptorMatcher("adalam")(d1, d2, l1, l2)
+ assert idxs.device == d1.device
+ assert quality.device == d1.device
+
+ def test_explicit_device_is_kept_5724(self, device):
+ d1, d2, l1, l2, hw = _adalam_scene(device)
+ _, idxs = match_adalam(d1, d2, l1, l2, config={"device": torch.device("cpu")}, hw1=hw, hw2=hw)
+ assert idxs.device.type == "cpu"
+
+
class TestLightGlueDISK(BaseTester):
@pytest.mark.slow
@pytest.mark.skipif(torch_version_le(1, 9, 1), reason="Needs autocast")
diff --git a/tests/feature/test_responces_local_features.py b/tests/feature/test_responces_local_features.py
index eeec94b26..9a6ecffd4 100644
--- a/tests/feature/test_responces_local_features.py
+++ b/tests/feature/test_responces_local_features.py
@@ -15,6 +15,7 @@
# limitations under the License.
#
+import pytest
import torch
import kornia
@@ -155,6 +156,30 @@ class TestCornerHarris(BaseTester):
class TestCornerGFTT(BaseTester):
+ def test_sigmas_wrong_length_is_rejected_5724(self, device):
+ # B = 1 with three sigmas used to broadcast silently to a (3, C, H, W) response
+ inp = torch.rand(1, 1, 8, 8, device=device)
+ with pytest.raises(ValueError, match="Invalid sigmas shape"):
+ kornia.feature.gftt_response(inp, sigmas=torch.ones(3, device=device))
+
+ def test_sigmas_wrong_ndim_is_rejected_5724(self, device):
+ inp = torch.rand(2, 1, 8, 8, device=device)
+ with pytest.raises(ValueError, match="Invalid sigmas shape"):
+ kornia.feature.gftt_response(inp, sigmas=torch.ones(2, 1, device=device))
+
+ def test_sigmas_wrong_type_is_rejected_5724(self, device):
+ inp = torch.rand(2, 1, 8, 8, device=device)
+ with pytest.raises(TypeError, match=r"sigmas type is not a torch\.Tensor"):
+ kornia.feature.gftt_response(inp, sigmas=[1.0, 2.0]) # type: ignore[arg-type]
+
+ def test_sigmas_scale_the_response_5724(self, device):
+ inp = torch.rand(2, 1, 8, 8, device=device)
+ sigmas = torch.tensor([1.0, 2.0], device=device)
+ plain = kornia.feature.gftt_response(inp)
+ scaled = kornia.feature.gftt_response(inp, sigmas=sigmas)
+ assert scaled.shape == plain.shape
+ self.assert_close(scaled, plain * sigmas.pow(4).view(-1, 1, 1, 1))
+
def test_shape(self, device):
inp = torch.ones(1, 3, 4, 4, device=device)
shi_tomasi = kornia.feature.CornerGFTT().to(device)